aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBenjamin, Max (mb388a) <mb388a@us.att.com>2019-04-08 14:14:34 -0400
committerBenjamin, Max (mb388a) <mb388a@us.att.com>2019-04-08 14:24:59 -0400
commitf47919f1fe367b612fa9c96d34c59f01a541e882 (patch)
tree5b6aa2fc36747d868897e68ccbec0c6db0aee81c
parent54452b80a1cf4d22ef750bc1377f8c1b05431d57 (diff)
Replaced all tabs with spaces in java and pom.xml
Added in maven plugins to enforce coding style rules Added in eclipse java formatting xml Change-Id: I3727bbf4ce8dc66abfd8ad21b6cfd0890c5d3ff0 Issue-ID: SO-1765 Signed-off-by: Benjamin, Max (mb388a) <mb388a@us.att.com>
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/adapters/vdu/VduPlugin.java202
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/audit/beans/AuditInventory.java96
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfig.java79
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfigIdentityMapper.java6
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java89
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneAuthHolder.java53
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java141
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/ServiceEndpointNotFoundException.java8
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/models/RackspaceAuthentication.java144
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfo.java19
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java32
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentStatus.java6
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoBlueprintAlreadyExists.java15
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyException.java100
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyManagerNotFound.java14
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeout.java64
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java46
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoDeploymentAlreadyExists.java15
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java1840
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/config/beans/PoConfig.java85
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/HeatCacheEntry.java16
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/NeutronCacheEntry.java55
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/VnfRollback.java405
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java399
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java408
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameter.java97
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java129
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java2265
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java403
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java417
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java53
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java412
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java956
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java26
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java48
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java91
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java9
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java9
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java12
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java7
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java15
-rw-r--r--adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java25
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java6
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java147
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java22
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java90
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java14
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java21
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java56
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java34
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java151
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java25
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java49
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java38
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java36
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java36
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java35
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java530
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java22
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java62
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java46
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java55
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java50
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java25
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java126
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java288
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java33
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java58
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java60
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java271
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java298
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java210
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java1
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java89
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java59
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java5
-rw-r--r--adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java135
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailPolicyRef.java36
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailPolicyRefSeq.java60
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnet.java193
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetHostRoute.java57
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetHostRoutes.java48
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetIp.java54
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetPool.java56
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetHostRouteMapper.java33
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetMapper.java197
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetPoolMapper.java30
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/ContrailNetwork.java135
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkError.java22
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkRequest.java318
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkResponse.java177
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkError.java22
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkRequest.java144
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkResponse.java55
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkExceptionResponse.java71
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkRequestCommon.java119
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkResponseCommon.java80
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkTechnology.java2
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/ProviderVlanNetwork.java66
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/QueryNetworkError.java3
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/QueryNetworkResponse.java200
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkError.java22
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkRequest.java36
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkResponse.java45
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkError.java22
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkRequest.java312
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkResponse.java74
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/RequestInformation.java223
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCErrorCommon.java15
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCEvent.java185
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCRequestCommon.java150
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCResponseCommon.java169
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceError.java21
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceRequest.java196
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceResponse.java58
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/ServiceInformation.java145
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantError.java82
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantRequest.java132
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantResponse.java108
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantError.java82
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantRequest.java51
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantResponse.java18
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/QueryTenantError.java48
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/QueryTenantResponse.java68
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantError.java58
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantRequest.java16
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantResponse.java18
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantExceptionResponse.java56
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantRequestCommon.java58
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantRollback.java89
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/CloudInfo.java79
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/PluginAction.java79
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduArtifact.java117
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduException.java57
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduInstance.java77
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduModelInfo.java57
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStateType.java11
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStatus.java78
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVfModuleRequest.java352
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVfModuleResponse.java142
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVolumeGroupRequest.java257
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVolumeGroupResponse.java126
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVfModuleRequest.java147
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVfModuleResponse.java81
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVolumeGroupRequest.java94
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVolumeGroupResponse.java29
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVfModuleResponse.java125
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVolumeGroupResponse.java130
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVfModuleRequest.java21
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVfModuleResponse.java29
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVolumeGroupRequest.java21
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVolumeGroupResponse.java29
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVfModuleRequest.java273
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVfModuleResponse.java102
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVolumeGroupRequest.java159
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVolumeGroupResponse.java70
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleExceptionResponse.java81
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java215
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfRequestCommon.java46
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfResponseCommon.java85
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VolumeGroupExceptionResponse.java24
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VolumeGroupRollback.java218
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HeatStatus.java2
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HostRoute.java68
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/MsoTenant.java70
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkInfo.java162
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkRollback.java246
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkStatus.java5
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/Pool.java94
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/RouteTarget.java65
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/StackInfo.java149
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/Subnet.java118
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/VnfRollback.java403
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/VnfStatus.java2
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoAdapterException.java27
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoCloudIdentityNotFound.java11
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoCloudSiteNotFound.java11
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoException.java82
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoExceptionCategory.java2
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoHeatNotFoundException.java9
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoIOException.java35
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoNetworkAlreadyExists.java14
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoNetworkNotFound.java14
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoOpenstackException.java85
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoStackAlreadyExists.java14
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoStackNotFound.java21
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoTenantAlreadyExists.java14
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoTenantNotFound.java17
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapAdapter.java50
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapElements.java20
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapEntry.java14
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/NetworkInfoMapper.java134
-rw-r--r--adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/StackInfoMapper.java130
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/BeansTest.java51
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/network/mappers/ContrailSubnetMappersTest.java393
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/nwrest/NetworkRequestTest.java25
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/vdu/BeansTest.java35
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoAdapterExceptionTest.java6
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoCloudIdentityNotFoundTest.java8
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoCloudSiteNotFoundTest.java8
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoIOExceptionTest.java4
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoNetworkAlreadyExistsTest.java8
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoNetworkNotFoundTest.java7
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoOpenstackExceptionTest.java12
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoStackAlreadyExistsTest.java6
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoStackNotFoundTest.java5
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoTenantAlreadyExistsTest.java7
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoTenantNotFoundTest.java6
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/JAXBMarshallingTest.java20
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/NetworkInfoMapperTest.java169
-rw-r--r--adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/StackInfoMapperTest.java108
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/db/migration/CloudConfig.java9
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/db/migration/R__CloudConfigMigration.java108
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDBApplication.java22
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDbRepositoryConfiguration.java15
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java32
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebMvcConfig.java2
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebSecurityConfigImpl.java29
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQuery.java112
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryException.java57
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionCategory.java4
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionCommon.java84
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryAllottedResourceCustomization.java215
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryResourceRecipe.java47
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceCsar.java31
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java116
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceNetworks.java169
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceVnfs.java193
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModule.java170
-rw-r--r--adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java396
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/AllTestsTestSuite.java6
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/CatalogDbAdapterBaseTest.java12
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/EmbeddedMariaDbConfig.java22
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java1535
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionTest.java15
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CloudConfigTest.java18
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/NetworkCollectionCatalogDbQueryTest.java192
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryResourceRecipeTest.java15
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceCsarTest.java1
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModuleTest.java5
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/TestAppender.java12
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientPortChanger.java5
-rw-r--r--adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java234
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAudit.java98
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAuditList.java28
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java24
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java120
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java94
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java99
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java85
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java170
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java401
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java70
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java43
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java144
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java16
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRef.java79
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRefSeq.java63
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnet.java330
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoute.java66
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoutes.java53
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetIp.java62
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetPool.java69
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapter.java357
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsync.java129
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java593
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java2444
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java1182
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotification.java161
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotificationResponse.java6
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotification.java63
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotificationResponse.java6
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoExceptionCategory.java12
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoRequest.java35
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify.java165
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify_Service.java33
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkRollback.java145
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkStatus.java14
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/ObjectFactory.java76
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotification.java188
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotificationResponse.java6
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotification.java49
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotificationResponse.java6
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotification.java135
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotificationResponse.java6
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkException.java84
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBean.java57
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/AaiClientPropertiesImpl.java67
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java122
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java62
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java31
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapter.java75
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapterImpl.java178
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/TenantAdapterRest.java437
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExists.java18
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantException.java72
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBean.java43
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/GenericValetResponse.java91
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java556
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/HeatRequest.java197
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmRequest.java73
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmResponse.java2
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateRequest.java227
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateResponse.java82
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteRequest.java120
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteResponse.java70
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackRequest.java100
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackResponse.java4
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetStatus.java101
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateRequest.java228
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateResponse.java78
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java185
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java472
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java289
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapter.java209
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsync.java129
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java457
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java2885
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java1385
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java1249
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VfRollback.java227
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java1143
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestUtils.java145
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java1169
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java1099
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java1090
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/CreateVnfNotification.java148
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/DeleteVnfNotification.java49
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoExceptionCategory.java12
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoRequest.java35
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/ObjectFactory.java41
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/QueryVnfNotification.java161
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/RollbackVnfNotification.java49
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/UpdateVnfNotification.java135
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify.java117
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java36
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfRollback.java64
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfStatus.java12
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfAlreadyExists.java17
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfException.java84
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfExceptionBean.java59
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfNotFound.java17
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java24
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java15
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java142
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java15
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java18
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java42
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java112
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java6
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java11
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java24
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java31
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduBlueprint.java81
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduInfo.java181
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduPlugin.java272
-rw-r--r--adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java11
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/BeansTest.java98
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java307
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java585
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java424
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java138
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/EmbeddedMariaDbConfig.java20
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/HealthCheckHandlerTest.java18
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/TestRestTemplateFactory.java26
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailPolicyRefSeqTest.java16
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailPolicyRefTest.java22
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailSubnetHostRouteTest.java27
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailSubnetHostRoutesTest.java28
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MSONetworkAdapterImplTest.java600
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImplTest.java415
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/NetworkAdapterRestTest.java593
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBeanTest.java52
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/exceptions/NetworkExceptionTest.java66
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/MsoTenantAdapterImplTest.java18
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/TenantAdapterRestTest.java360
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExistsTest.java35
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBeanTest.java45
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionTest.java65
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/valet/ValetClientTest.java155
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapperTest.java31
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/AllTestsTestSuite.java6
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BaseRestTestUtils.java205
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BpelRestClientTest.java42
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImplTest.java213
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java986
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImplTest.java481
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfMulticloudAdapterImplTest.java96
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImplTest.java70
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/QueryTest.java113
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VfRollbackTest.java116
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VnfAdapterRestTest.java951
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestTest.java72
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2Test.java75
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeGroupAdapterCommon.java11
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/bpmn/mock/StubOpenStack.java918
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java56
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/vdu/utils/VduBlueprintTest.java1
-rw-r--r--adapters/mso-openstack-adapters/src/test/java/org/onap/so/vdu/utils/VduInfoTest.java1
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java227
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomController.java26
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapter.java138
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapterImpl.java607
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/RequestStatusType.java20
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ResponseStatus.java6
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/WebSecurityConfigImpl.java31
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/CXFConfiguration.java71
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java48
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/RequestDBConfig.java53
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/WebMvcConfig.java2
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/exceptions/MsoRequestsDbException.java26
-rw-r--r--adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/exceptions/MsoRequestsDbExceptionBean.java24
-rw-r--r--adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestdb/rest/RequestProcessingDataRequestDbQueryTest.java93
-rw-r--r--adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/AllTestsTestSuite.java6
-rw-r--r--adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsSchedulerTest.java82
-rw-r--r--adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java113
-rw-r--r--adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/HealthCheckHandlerTest.java73
-rw-r--r--adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java829
-rw-r--r--adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/application/EmbeddedMariaDbConfig.java66
-rw-r--r--adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/application/TestAppender.java12
-rw-r--r--adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestDbClientPortChanger.java1
-rw-r--r--adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java98
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/CXFConfiguration.java41
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/ObjectFactory.java21
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/RequestHeader.java83
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java59
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterPortType.java18
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterRequest.java53
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterResponse.java8
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java81
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/WebSecurityConfigImpl.java29
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/CallbackHeader.java54
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/ObjectFactory.java24
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java63
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterPortType.java21
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java82
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/package-info.java3
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/exception/SDNCAdapterException.java8
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Constants.java26
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java139
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/RequestTunables.java263
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java75
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCResponse.java98
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java541
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java319
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/package-info.java3
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java251
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java157
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCAdapterUtils.java50
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java512
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java291
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java332
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java53
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/TypedRequestTunables.java291
-rw-r--r--adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtil.java26
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/AllTestsTestSuite.java6
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/BaseTest.java7
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/FileUtil.java6
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/ObjectFactoryTest.java62
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/SDNCAdapterRequestTest.java39
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/client/CallbackHeaderTest.java26
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequestTest.java43
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/MapRequestTunablesTest.java179
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImplTest.java94
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCResponseTest.java66
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCRestClientTest.java6
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/UtilsTest.java46
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallbackTest.java22
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/ObjectMappingTest.java835
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnectorTest.java18
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnectorTest.java1
-rw-r--r--adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtilTest.java12
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/CXFConfiguration.java56
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/RequestDBConfig.java53
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/WebSecurityConfigImpl.java31
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/constant/CommonConstant.java13
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/constant/DriverExceptionID.java30
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/exceptions/ApplicationException.java3
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/CustomerModel.java17
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/LocationConstraint.java4
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NSResourceInputParameter.java31
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsCreateReq.java10
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsOperationKey.java3
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsParameters.java5
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsScaleParameters.java42
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ResponseDescriptor.java1
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/RestfulResponse.java19
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ScaleNsByStepsData.java28
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ScaleNsData.java5
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/VFCScaleData.java14
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/VimLocation.java8
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/AaiUtil.java22
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/HealthCheckHandler.java15
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcAdapterRest.java21
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcManager.java728
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java159
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java70
-rw-r--r--adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/ValidateUtil.java97
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/exceptions/ApplicationExceptionTest.java54
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/CustomerModelTest.java2
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/LocationConstraintTest.java2
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NSResourceInputParameterTest.java2
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsCreateReqTest.java2
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsInstantiateReqTest.java2
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsOperationKeyTest.java2
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsParametersTest.java3
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsProgressStatusTest.java3
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/ResponseDescriptorTest.java2
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/RestfulResponseTest.java3
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/VimLocationTest.java2
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/EmbeddedMariaDbConfig.java66
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/HealthCheckHandlerTest.java41
-rw-r--r--adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/VfcManagerTest.java9
-rwxr-xr-xadapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmAdapterApplication.java8
-rw-r--r--adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java2
-rw-r--r--adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java4
-rw-r--r--adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/JobManager.java12
-rw-r--r--adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/VnfmOperation.java4
-rw-r--r--adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java4
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/ASDCControllerSingleton.java45
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/Application.java44
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/CatalogDBConfig.java54
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/JerseyConfiguration.java30
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/RequestDBConfig.java47
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java29
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java269
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java315
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCControllerStatus.java2
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCNotificationCallBack.java13
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCStatusCallBack.java60
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/DistributionStatusMessage.java95
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/FinalDistributionStatusMessage.java119
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/ResourceInstance.java63
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCControllerException.java22
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCDownloadException.java22
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCParametersException.java20
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerException.java20
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImpl.java317
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulator.java282
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonStatusData.java177
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java122
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java348
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java298
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java112
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java354
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/BigDecimalVersion.java42
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/IArtifactOrchestrator.java6
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfModuleData.java36
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfResourceInstaller.java4
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/PnfResourceStructure.java25
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceStructure.java25
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceType.java23
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java884
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleArtifact.java125
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleMetaData.java97
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleStructure.java109
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java27
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java238
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java4569
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImpl.java71
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/DistributionStatus.java5
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java316
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java1860
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/util/NotificationLogging.java249
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/util/ToLog.java1
-rw-r--r--asdc-controller/src/main/java/org/onap/so/asdc/util/YamlEditor.java92
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/ASDCPojoTest.java36
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/AllTestsTestSuite.java6
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/BaseTest.java36
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedCatalogDbConfig.java68
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedRequestDbConfig.java62
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/TestApplication.java20
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCConfigurationTest.java34
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java113
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerTest.java34
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCElementInfoTest.java179
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCStatusCallBackTest.java96
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/BigDecimalVersionTest.java27
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/DistributionStatusMessageTest.java33
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/YamlTest.java234
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCControllerExceptionTest.java43
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCDownloadExceptionTest.java43
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCParametersExceptionTest.java43
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerExceptionTest.java44
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImplTest.java32
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulatorTest.java286
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonStatusDataTest.java8
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaDataTest.java46
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/NotificationDataImplTest.java53
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImplTest.java34
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/ASDCRestInterfaceTest.java195
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/HealthCheckTest.java37
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/client/tests/ASDCConfigurationTest.java95
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/installer/ToscaResourceStructureTest.java165
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/installer/bpmn/BpmnInstallerTest.java28
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInputTest.java2
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java623
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImplTest.java55
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/WatchdogDistributionTest.java193
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/util/ASDCNotificationLoggingTest.java300
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/util/NotificationLoggingTest.java71
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingRunner.java32
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingVisitorImpl.java140
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/utils/TreePrinterListener.java112
-rw-r--r--asdc-controller/src/test/java/org/onap/so/asdc/utils/TreeUtils.java26
-rw-r--r--basepath_marker1
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/PayloadClient.java119
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigModifyAction.java53
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigScaleOutPayload.java83
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersConfigModify.java53
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersHealthCheck.java24
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersQuiesce.java53
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersResumeTraffic.java24
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersUpgrade.java66
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/HealthCheckAction.java53
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/QuiesceTrafficAction.java24
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersConfigModify.java24
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersConfigScaleOut.java82
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersHealthCheck.java52
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ResumeTrafficAction.java24
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/SnapshotAction.java53
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/StartStopAction.java24
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/UpgradeAction.java24
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/BuildingBlockExecution.java18
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DefaultToShortClassNameBeanNameGenerator.java10
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java2
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/InjectExecution.java10
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/InjectionHelper.java53
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/baseclient/BaseClient.java73
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/MalformedBuildingBlockInputException.java35
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/MissingBuildingBlockInputException.java35
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/RequiredExecutionVariableExeception.java24
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnIntegerParam.java35
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnParam.java55
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java58
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceInput.java86
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceRecipeRequest.java42
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java82
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/CryptoHandler.java66
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/ICryptoHandler.java8
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/OofInfraUtils.java7
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunner.java48
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidator.java30
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidatorRunner.java219
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunner.java41
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowCallbackResponse.java54
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContext.java133
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java194
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowResponse.java101
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/Metadata.java19
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/ShallowCopy.java33
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java143
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AllottedResource.java184
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/CloudRegion.java171
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Collection.java125
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Configuration.java403
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/CtagAssignment.java52
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Customer.java132
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Entitlement.java71
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Evc.java247
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ForwarderEvc.java136
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java909
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/HostRoute.java97
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/InstanceGroup.java184
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3InterfaceIpv4AddressList.java145
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3InterfaceIpv6AddressList.java176
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3Network.java487
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LInterface.java302
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LagInterface.java170
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LineOfBusiness.java57
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Metadatum.java73
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/NetworkPolicy.java114
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/OwningEntity.java69
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PServer.java83
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PhysicalLink.java157
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Platform.java57
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Pnf.java129
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Project.java56
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/RouteTableReference.java89
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/RouteTarget.java38
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/SegmentationAssignment.java49
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceInstance.java353
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceProxy.java107
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceSubscription.java79
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/SriovVf.java241
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Subnet.java267
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Tenant.java96
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VfModule.java221
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vlan.java244
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vnfc.java260
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VolumeGroup.java180
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBinding.java32
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBondingLink.java167
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/BuildingBlock.java98
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ConfigurationResourceKeys.java81
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ExecuteBuildingBlock.java188
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/GeneralBuildingBlock.java109
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java12
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/WorkflowResourceIds.java168
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/exceptions/InvalidBuildingBlockInputException.java9
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/License.java44
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/OrchestrationContext.java21
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java208
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestParameters.java193
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/Candidate.java105
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/CandidateType.java25
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionCandidates.java50
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionInfo.java121
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoAllottedResource.java266
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoCollection.java160
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoConfiguration.java118
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoGenericVnf.java264
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoInstanceGroup.java123
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoMetadata.java120
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoNetwork.java316
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceInstance.java116
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoVfModule.java240
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoVolumeGroup.java3
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/AssignFlows.java34
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java3452
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java864
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java769
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/CloudInfoFromAAI.java140
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java289
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java206
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/MultipleObjectsFoundException.java44
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/NoServiceInstanceFoundException.java44
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerAction.java298
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerCallback.java26
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerClient.java316
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerClientV2.java195
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerConfiguration.java82
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerOrchestrator.java41
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerOrchestratorException.java21
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerSupport.java341
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/AVPNDmaapBean.java18
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/AsyncRequestStatus.java182
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/InstanceReferences.java16
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/RequestStatus.java96
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java71
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/AbstractCDSPropertiesBean.java114
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java187
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java11
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnf.java67
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnf.java70
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnf.java155
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnf.java110
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnf.java69
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnf.java69
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DefaultDmaapPropertiesImpl.java19
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DmaapPropertiesClient.java157
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DmaapPropertiesMap.java15
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/GlobalDmaapPublisher.java44
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BBObjectNotFoundException.java23
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BadResponseException.java9
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java189
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/MapperException.java9
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/OrchestrationStatusValidationException.java6
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/AAIPropertiesImpl.java59
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/CDSPropertiesImpl.java8
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/PolicyRestPropertiesImpl.java66
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/UrnPropertiesReaderWrapper.java6
-rw-r--r--bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowProcessorException.java4
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllBaseTaskTestSuite.java8
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllGroovyTestSuites.java6
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllTestSuites.java6
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseTest.java168
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseUnitTest.java2
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java960
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java28
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/NonSpringSuite.java1
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/SerializableChecker.java66
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/TestApplication.java18
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/TestApplicationConfig.java114
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/appc/payload/PayloadClientTest.java100
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/BeansTest.java60
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DefaultToShortClassNameBeanNameGeneratorTest.java52
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DelegateExecutionImplTest.java3
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MSOCommonApplication.java73
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteGenericVnf.java20
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteVfModule.java45
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIGenericVnfSearch.java522
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/SPIPropertiesTest.java65
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/WorkflowContextHolderTest.java62
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/WorkflowTestTransformer.java13
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/baseclient/BaseClientTest.java52
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnParamTest.java49
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnRestClientTest.java23
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/ResourceInputTest.java94
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/ResourceRecipeRequestTest.java76
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilderTest.java610
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java55
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunnerTest.java84
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyDisabledValidator.java19
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorFour.java17
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorOne.java19
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorThree.java17
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorTwo.java18
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/ValidationConfig.java3
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorOne.java19
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorTwo.java18
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunnerTest.java82
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/FileUtil.java85
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseAAI.java2047
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseAPPC.java49
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseDatabase.java145
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseNetworkAdapter.java137
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseOof.java20
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponsePolicy.java141
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSDNCAdapter.java133
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSNIRO.java46
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseVNFAdapter.java244
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/BBDecompPojoTest.java32
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/BBPojoTest.java51
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java379
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/SerializationTest.java86
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/entities/exceptions/InvalidBuildingBlockInputExceptionTest.java79
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayerTest.java1296
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java5280
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java1480
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/CloudInfoFromAAITest.java207
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java407
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/MultipleObjectsFoundExceptionTest.java77
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/NoServiceInstanceFoundExceptionTest.java77
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/ResponseExceptionMapperImplTest.java100
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerActionTest.java858
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerClientV2Test.java160
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerSupportTest.java78
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/avpn/dmaap/beans/AVPNDmaapBeansTest.java37
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtilsTest.java15
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnfTest.java2
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnfTest.java2
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnfTest.java2
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnfTest.java2
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnfTest.java3
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnfTest.java1
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnfTest.java1
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnfTest.java1
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/dmaapproperties/DmaapPropertiesClientTest.java102
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/dmaapproperties/GlobalDmaapPublisherTest.java35
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/exception/ExceptionBuilderTest.java87
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/AAIPropertiesImplTest.java38
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/PolicyRestPropertiesImplTest.java44
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/ThreadedReadTest.java122
-rw-r--r--bpmn/MSOCommonBPMN/src/test/java/org/onap/so/test/categories/SpringAware.java2
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BadInjectedFieldException.java47
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java183
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/MissingInjectedFieldException.java20
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java506
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/RollbackData.java6
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/UrnPropertiesReader.java34
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java115
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java221
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/CompareModelsResult.java56
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ConfigResource.java23
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Configuration.java124
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Customer.java43
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java246
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/InventoryType.java21
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java177
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java149
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModelInfo.java155
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModuleResource.java151
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/NetworkResource.java120
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/OwningEntity.java40
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Project.java23
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java137
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Resource.java224
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java117
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceInstance.java54
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceModelInfo.java71
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java4
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/RollbackData.java26
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java1034
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceInstance.java210
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Subscriber.java58
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Vnf.java235
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java319
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/internal/VariableNameExtractor.java16
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/DecomposeJsonUtil.java97
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/JsonUtils.java1955
-rw-r--r--bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/xml/XmlTool.java359
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BadInjectedFiledExceptionTest.java61
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java440
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BeansTest.java67
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/MissingInjectedFiledExceptionTest.java47
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/ResponseBuilderTest.java173
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/RollbackDataTest.java13
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/UrnPropertiesReaderTest.java13
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/WorkflowExceptionTest.java60
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/AllottedResourceTest.java97
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CompareModelsResultTest.java127
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigResourceTest.java47
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigurationTest.java62
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CustomerTest.java44
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/DomainPojoTest.java38
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/HomingSolutionTest.java84
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/LicenseTest.java71
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModelInfoTest.java62
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModuleResourceTest.java64
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/NetworkResourceTest.java73
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/OwningEntityTest.java44
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ProjectTest.java40
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/RequestTest.java56
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceDecompositionTest.java68
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceTest.java102
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java208
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceInstanceTest.java101
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/SubscriberTest.java50
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java159
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/internal/VariableNameExtractorTest.java4
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/DecomposeJsonUtilTest.java295
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonDecomposingExceptionTest.java45
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtils2Test.java220
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtilsTest.java429
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/utils/CamundaDBSetup.java66
-rw-r--r--bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/xml/XmlToolTest.java118
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/CallbackHeader.java56
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/ObjectFactory.java24
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/RequestHeader.java87
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterCallbackRequest.java68
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterRequest.java35
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterResponse.java6
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCCallbackAdapterPortType.java19
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/package-info.java3
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/CreateVnfNotification.java232
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/DeleteVnfNotification.java117
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/MsoExceptionCategory.java12
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/MsoRequest.java37
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/ObjectFactory.java26
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/QueryVnfNotification.java243
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/RollbackVnfNotification.java86
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/UpdateVnfNotification.java151
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfAdapterNotify.java117
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfAdapterNotify_Service.java34
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfRollback.java96
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfStatus.java12
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerService.java719
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/ProcessEngineAwareService.java62
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java74
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/VnfAdapterNotifyServiceImpl.java313
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java6
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncResource.java206
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowMessageResource.java113
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowProcessor.java104
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowResource.java1060
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/LoggingAndURNMappingPlugin.java510
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/WorkflowExceptionPlugin.java208
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/CXFConfiguration.java71
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java77
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java31
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/RequestHeaderTest.java62
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/SDNCAdapterCallbackRequestTest.java52
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/SDNCAdapterRequestTest.java48
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/BaseIntegrationTest.java27
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/InfraEmbeddedMariaDbConfig.java24
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/IntegrationTestSuite.java4
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/BPMNUtil.java604
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CompleteMsoProcessIT.java282
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ConfirmVolumeGroupNameIT.java158
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ConfirmVolumeGroupTenantIT.java104
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CreateAAIVfModuleIT.java432
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CreateAAIVfModuleVolumeGroupIT.java178
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/DecomposeServiceIT.java76
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/DeleteAAIVfModuleIT.java453
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/FalloutHandlerIT.java343
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/GenerateVfModuleNameIT.java71
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ManualHandlingIT.java110
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteGenericVnf.java20
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteVfModule.java45
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIGenericVnfSearch.java522
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockLoggerDelegate.java16
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/OofHomingIT.java640
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/OofHomingTestIT.java625
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/PrepareUpdateAAIVfModuleIT.java334
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/RainyDayHandlerIT.java68
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ReceiveWorkflowMessageTest.java183
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SDNCAdapterCallbackRule.java81
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SDNCAdapterRestV2IT.java145
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SPIPropertiesTest.java65
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SniroHomingV1IT.java1008
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/UpdateAAIGenericVnfIT.java257
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/UpdateAAIVfModuleIT.java197
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/VnfAdapterRestV1IT.java600
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowAsyncResourceTest.java98
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowContextHolderTest.java63
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowTest.java4245
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowTestTransformer.java13
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/adapter/sdnc/ObjectFactoryTest.java1
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerServiceTest.java1
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncResourceExceptionHandlingTest.java61
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/FlakyTests.java2
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java47
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java1
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/AbstractTestBase.java56
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/CreateVcpeResCustServiceIT.java596
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DeleteVcpeResCustServiceIT.java394
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceBRGIT.java465
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceBRGRollbackIT.java589
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceTXCIT.java473
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceTXCRollbackIT.java591
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoDeleteAllottedResourceBRGIT.java238
-rw-r--r--bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoDeleteAllottedResourceTXCIT.java228
-rw-r--r--bpmn/so-bpmn-building-blocks/src/main/java/org/onap/so/bpmn/infrastructure/bpmn/activity/DeployActivitySpecs.java127
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/AllTestSuites.java6
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BaseTest.java184
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BaseUnitTest.java2
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java881
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java28
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/MockLoggerDelegate.java16
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/SerializableChecker.java66
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/TestApplication.java18
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java344
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAICheckVnfInMaintBBTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAISetVnfInMaintBBTest.java45
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAIUnsetVnfInMaintBBTest.java49
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/SDNOHealthCheckBBTest.java49
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/activity/DeployActivitySpecsTest.java55
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/process/WorkflowActionBBTest.java210
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateNetworkBBTest.java26
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateNetworkCollectionBBTest.java27
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateServiceInstanceBBTest.java23
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVfModuleBBTest.java73
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVnfBBTest.java23
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVolumeGroupBBTest.java39
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignNetworkBBTest.java41
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignServiceInstanceBBTest.java27
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVfModuleBBTest.java48
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVnfBBTest.java49
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVolumeGroupBBTest.java39
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/BuildingBlockValidatorRunnerTest.java8
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelServiceInstanceBBTest.java49
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelVfModuleBBTest.java45
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelVnfBBTest.java45
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ConfigurationScaleOutBBTest.java42
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateCustomerBBTest.java39
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateNetworkBBTest.java32
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateNetworkCollectionBBTest.java31
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateVfModuleBBTest.java169
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateVolumeGroupBBTest.java72
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateNetworkBBTest.java43
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateServiceInstanceBBTest.java22
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVfModuleBBTest.java50
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVnfBBTest.java65
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVolumeGroupBBTest.java37
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteInstanceGroupBBTest.java41
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteNetworkBBTest.java31
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteNetworkCollectionBBTest.java32
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteVfModuleBBTest.java74
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteVolumeGroupBBTest.java42
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DistributeTrafficActivityTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DistributeTrafficCheckActivityTest.java48
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ExecuteBuildingBlockTest.java179
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/FlowCompleteActivity.java46
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/GenericVnfHealthCheckBBTest.java45
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/HomingBBTest.java60
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/PauseForManualTaskActivityTest.java121
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/SDNCHandlerTest.java60
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignNetworkBBTest.java34
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignServiceInstanceBBTest.java26
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVfModuleBBTest.java69
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVnfBBTest.java91
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVolumeGroupBBTest.java39
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UpdateNetworkBBTest.java45
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckClosedLoopDisabledFlagActivityTest.java50
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckInMaintFlagActivityTest.java46
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckPserversLockedFlagActivity.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFHealthCheckActivityTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFLockActivityTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFQuiesceTrafficActivityTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFResumeTrafficActivityTest.java49
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSetClosedLoopDisabledFlagActivityTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSetInMaintFlagActivityTest.java46
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSnapShotActivityTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStartActivityTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStopActivityTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnlockActivityTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnsetClosedLoopDisabledFlagActivityTest.java48
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnsetInMaintFlagActivityTest.java46
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradeBackupActivityTest.java50
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradePostCheckActivityTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradePreCheckActivityTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradeSoftwareActivityTest.java47
-rw-r--r--bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VnfAdapterTest.java19
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResources.java112
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstance.java34
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIResource.java22
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIServiceInstance.java263
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAICreateResources.java166
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIDeleteServiceInstance.java36
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIServiceInstance.java155
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/common/name/generation/AAIObjectInstanceNameGenerator.java21
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForPnfCorrelationIdDelegate.java2
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegate.java49
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegate.java5
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateRelation.java4
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegate.java3
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClient.java8
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputs.java10
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareCdsCallDelegate.java26
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigAssignDelegate.java26
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigDeployDelegate.java41
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationId.java5
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClient.java19
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagementImpl.java4
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/properties/BPMNProperties.java16
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NSResourceInputParameter.java2
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NsOperationKey.java3
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NsParameters.java3
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/VimLocation.java2
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java1386
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java94
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncNetworkTopologyOperationTask.java27
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncServiceTopologyOperationTask.java21
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnOperationClient.java38
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnPreprocessTask.java9
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/GenericResourceApi.java10
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/HeaderUtil.java3
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilder.java400
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/NetworkRpcInputEntityBuilder.java35
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/ServiceRpcInputEntityBuilder.java28
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/NetworkInputParametersEntity.java5
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RequestInformationEntity.java4
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcNetworkTopologyOperationInputEntity.java4
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcNetworkTopologyOperationOutputEntity.java4
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcServiceTopologyOperationInputEntity.java7
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/ServiceInputParametersEntity.java5
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllBPMNTestSuites.java6
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllTasksTestsTestSuite.java8
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllTestsTestSuite.java17
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/BeansTest.java51
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java31
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResourcesTest.java301
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstanceTest.java87
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIServiceInstanceTest.java170
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/common/name/generation/AAIObjectInstanceNameGeneratorTest.java43
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java6
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForPnfCorrelationIdDelegateTest.java11
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegateTest.java51
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegateTest.java1
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateRelationTest.java1
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegateTest.java1
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java6
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java1
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementTestImpl.java4
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigAssignDelegateTest.java32
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigDeployDelegateTest.java47
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationIdTest.java13
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClientTest.java74
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/vfcmodel/VfcModelPojoTest.java19
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactoryTest.java130
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/HeaderUtilTest.java7
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilderTest.java222
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/NetworkRpcInputEntityBuilderTest.java67
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/ServiceRpcInputEntityBuilderTest.java67
-rw-r--r--bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/ClientEntityPojoTest.java68
-rw-r--r--bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/AllBPMNTestSuites.java27
-rw-r--r--bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/BaseBPMNTest.java25
-rw-r--r--bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java27
-rw-r--r--bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/GrpcNettyServer.java95
-rw-r--r--bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/TestApplication.java14
-rw-r--r--bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/CreateVcpeResCustServiceSimplifiedTest.java146
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/HomingV2.java2
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/OofHomingV2.java221
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java1030
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICommonTasks.java40
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java988
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasks.java295
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIFlagTasks.java148
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIQueryTasks.java399
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java1026
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivity.java196
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasks.java135
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasks.java46
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1.java222
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java69
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java119
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java86
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java236
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/Constants.java42
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/EtsiVnfDeleteTask.java68
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTask.java1
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTask.java109
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTask.java105
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmJobTask.java101
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeTask.java70
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTask.java5
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfiguration.java1
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProvider.java6
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImpl.java192
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProvider.java48
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmBasicHttpConfigProvider.java1
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameter.java1
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImpl.java4
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/VnfParameter.java1
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java263
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java67
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ActivateVfModule.java34
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetwork.java45
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtils.java124
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnf.java62
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CloudSiteCatalogUtils.java85
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnf.java8
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnf.java202
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java229
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java60
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java191
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java181
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/NetworkBBUtils.java89
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SourceSystem.java3
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java156
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnf.java47
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasks.java364
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java43
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java36
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/exceptions/SDNCErrorResponseException.java16
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java153
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java191
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java158
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java205
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java146
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java174
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java167
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java58
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/FlowCompletionTasks.java59
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java274
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/Resource.java141
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java2401
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailure.java217
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java744
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionExtractResourcesAAI.java41
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java52
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasks.java68
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/aai/mapper/AAIObjectMapper.java537
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClient.java29
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClientException.java14
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClientImpl.java237
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterRestProperties.java42
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java675
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClient.java20
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClientException.java14
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClientImpl.java183
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterRestProperties.java42
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClient.java20
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientImpl.java137
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterRestProperties.java50
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/AttributeNameValue.java7
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapper.java257
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperUtils.java33
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java1505
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClient.java93
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClientResponseValidator.java189
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingRequestObjectBuilder.java57
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofClient.java9
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofValidator.java35
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ModelInfo.java11
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofProperties.java9
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofRequest.java16
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofRequestParameters.java7
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/PlacementDemand.java8
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/PlacementInfo.java6
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/RequestInfo.java12
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/Resource.java11
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ResourceModelInfo.java1
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ServiceInfo.java7
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/SubscriberInfo.java7
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAICollectionResources.java48
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java96
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIInstanceGroupResources.java87
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAINetworkResources.java305
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java207
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVfModuleResources.java120
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java211
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVolumeGroupResources.java99
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVpnBindingResources.java110
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java48
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NetworkAdapterResources.java155
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCConfigurationResources.java145
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCNetworkResources.java104
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCServiceInstanceResources.java145
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVfModuleResources.java76
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVnfResources.java98
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNOHealthCheckResources.java24
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResources.java35
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResources.java33
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java116
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java76
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCProperties.java51
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java130
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcAction.java63
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcOperation.java38
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/endpoint/SDNCTopology.java37
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java59
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java344
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapper.java112
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapper.java85
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java265
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapper.java170
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java144
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java197
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Candidate.java54
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ConductorProperties.java51
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Demand.java85
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/LicenseInfo.java21
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ManagerProperties.java51
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ModelInfo.java76
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/PlacementInfo.java61
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/RequestInfo.java130
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Resource.java37
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ServiceInfo.java76
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroConductorRequest.java43
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroManagerRequest.java116
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SubscriberInfo.java53
-rw-r--r--bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/ticket/ExternalTicket.java165
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/AllIntegrationTestSuites.java3
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/BaseIntegrationTest.java94
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java28
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/FileUtil.java85
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/IntegrationTestSuite.java1
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/TestApplication.java18
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/UnitTestSuite.java1
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java128
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/aai/tasks/AAIFlagTasksTest.java321
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/data/TestDataSetup.java997
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java1192
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasksTest.java365
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java1285
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivityTest.java76
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasksTest.java112
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasksTest.java70
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1Test.java137
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasksTest.java84
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasksTest.java348
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasksTest.java174
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java412
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/EtsiVnfDeleteTaskTest.java124
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTaskTest.java2
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTaskTest.java251
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTaskTest.java239
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeJobTest.java122
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/StubbedBuildingBlockExecution.java96
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/TestConstants.java4
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfigurationTest.java1
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskTest.java169
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImplTest.java466
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProviderTest.java1
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImplTest.java2
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/VnfParameterTest.java1
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java120
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java86
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/audit/AuditTasksTest.java67
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ActivateVfModuleTest.java24
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtilsTest.java61
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkTest.java70
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnfTest.java191
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CloudSiteCatalogUtilsTest.java111
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnfTest.java2
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnfTest.java130
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOutTest.java284
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollectionTest.java152
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkTest.java90
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheckTest.java262
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/NetworkBBUtilsTest.java160
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java941
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBBTest.java140
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnfTest.java80
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasksTest.java146
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java87
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java63
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java169
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java191
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java122
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java201
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasksTest.java187
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java241
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java203
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidatorTest.java156
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/FlowCompletionTasksTest.java57
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidatorTest.java812
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidatorUnitTest.java45
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailureTest.java201
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java623
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksUpdateReqDbTest.java97
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java2786
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionUnitTest.java110
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasksTest.java121
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/aai/mapper/AAIObjectMapperTest.java1119
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java381
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java633
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java348
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientIT.java333
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterRestPropertiesTest.java36
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java604
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperPayloadTest.java1637
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperTest.java155
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientResponseValidatorTest.java134
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientTest.java146
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingRequestObjectBuilderTest.java142
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/oof/OofClientTestIT.java132
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAICollectionResourcesTest.java82
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java135
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIInstanceGroupResourcesTest.java147
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAINetworkResourcesTest.java671
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIServiceInstanceResourcesTest.java63
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVfModuleResourcesTest.java211
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java328
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVolumeGroupResourcesTest.java143
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVpnBindingResourcesTest.java142
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NamingServiceResourcesTest.java109
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NetworkAdapterResourcesTest.java327
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCConfigurationResourcesTest.java70
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCNetworkResourcesTest.java239
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCServiceInstanceResourcesTest.java192
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVfModuleResourcesTest.java155
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVnfResourcesTest.java244
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNOHealthCheckResourcesTest.java52
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResourcesTest.java189
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResourcesTest.java142
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/policy/CommonObjectMapperProviderTest.java4
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdn/common/SdnCommonTasksTest.java8
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientIT.java54
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java28
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapperTest.java742
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapperTest.java339
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapperTest.java89
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java547
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapperTest.java190
-rw-r--r--bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sniro/SniroClientTestIT.java98
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyBaseException.java31
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClient.java216
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClientConnector.java2
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClientTokenProvider.java83
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyConnectException.java19
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyRequest.java310
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponse.java16
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponseException.java66
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponseStatus.java12
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifySimpleTokenProvider.java21
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyTokenProvider.java4
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/Entity.java84
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/base/client/HttpMethod.java2
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientConnector.java346
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientException.java28
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientRedirectStrategy.java51
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientResponse.java51
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/BlueprintsResource.java37
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/Cloudify.java16
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/DeploymentsResource.java2
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/ExecutionsResource.java28
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/NodeInstancesResource.java7
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/TokensResource.java5
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/AzureConfig.java73
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Blueprint.java112
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Blueprints.java41
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CancelExecutionParams.java25
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CloudifyError.java68
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CreateDeploymentParams.java34
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Deployment.java370
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/DeploymentOutputs.java75
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Deployments.java47
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Execution.java167
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Executions.java47
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Metadata.java34
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/NodeInstance.java278
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/NodeInstances.java41
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/OpenstackConfig.java89
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Pagination.java55
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/ParameterDefinition.java60
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/StartExecutionParams.java81
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Token.java44
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/UpdateExecutionParams.java23
-rw-r--r--cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/UpdateNodeInstanceParams.java48
-rw-r--r--cloudify-client/src/test/java/org/onap/so/cloudify/BeanMultiTest.java49
-rw-r--r--cloudify-client/src/test/java/org/onap/so/cloudify/base/client/CloudifyClientTest.java128
-rw-r--r--cloudify-client/src/test/java/org/onap/so/cloudify/base/client/CloudifyClientTokenProviderTest.java38
-rw-r--r--cloudify-client/src/test/java/org/onap/so/cloudify/connector/http/HttpClientConnectorTest.java399
-rw-r--r--cloudify-client/src/test/java/org/onap/so/cloudify/connector/http/HttpClientRedirectStrategyTest.java47
-rw-r--r--cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/BlueprintsResourceTest.java195
-rw-r--r--cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/DeploymentsResourceTest.java193
-rw-r--r--cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/ExecutionsResourceTest.java248
-rw-r--r--cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/NodeInstancesResourceTest.java96
-rw-r--r--common/src/main/java/org/onap/so/client/DefaultProperties.java28
-rw-r--r--common/src/main/java/org/onap/so/client/HttpClient.java83
-rw-r--r--common/src/main/java/org/onap/so/client/PreconditionFailedException.java10
-rw-r--r--common/src/main/java/org/onap/so/client/ResponseExceptionMapper.java127
-rw-r--r--common/src/main/java/org/onap/so/client/ResponseExceptionMapperImpl.java13
-rw-r--r--common/src/main/java/org/onap/so/client/RestClient.java467
-rw-r--r--common/src/main/java/org/onap/so/client/RestClientSSL.java98
-rw-r--r--common/src/main/java/org/onap/so/client/RestProperties.java26
-rw-r--r--common/src/main/java/org/onap/so/client/RestPropertiesLoader.java104
-rw-r--r--common/src/main/java/org/onap/so/client/RestRequest.java101
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIClient.java82
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java46
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperPatchProvider.java8
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperProvider.java6
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIConfigurationClient.java107
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIDSLQueryClient.java53
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIErrorFormatter.java53
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java125
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIObjectType.java340
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIProperties.java17
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIQueryClient.java61
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIQueryObjectMapperProvider.java8
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java84
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIResourcesObjectMapperProvider.java6
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIRestClient.java54
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIRestClientI.java14
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIRestClientImpl.java19
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java213
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java308
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIUpdator.java8
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIUpdatorImpl.java44
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIValidator.java12
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java61
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIVersion.java26
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java28
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/AAIEntity.java4
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/AAIEntityObject.java4
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/AAIError.java4
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java29
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/Configuration.java70
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/CustomQuery.java100
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/QueryStep.java4
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/Relationships.java78
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/RequestError.java4
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/Results.java24
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/ServiceException.java7
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBody.java63
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBodySerializer.java42
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/Transaction.java119
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/Transactions.java33
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequest.java89
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequestSerializer.java42
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyResponse.java88
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionRequest.java31
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionResponse.java35
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/AAIResourceUri.java54
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java212
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUri.java75
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java174
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUri.java45
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java193
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/NodesUri.java41
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java45
-rw-r--r--common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestClient.java72
-rw-r--r--common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestProperties.java5
-rw-r--r--common/src/main/java/org/onap/so/client/cds/BasicAuthClientInterceptor.java9
-rw-r--r--common/src/main/java/org/onap/so/client/cds/CDSProcessingClient.java34
-rw-r--r--common/src/main/java/org/onap/so/client/cds/CDSProcessingHandler.java4
-rw-r--r--common/src/main/java/org/onap/so/client/cds/CDSProperties.java17
-rw-r--r--common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java31
-rw-r--r--common/src/main/java/org/onap/so/client/defaultproperties/PolicyRestPropertiesImpl.java87
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/Consumer.java2
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java75
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/DmaapConsumer.java189
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/DmaapProperties.java11
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/DmaapPropertiesLoader.java87
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/DmaapPublisher.java42
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/Publisher.java4
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/exceptions/DMaaPConsumerFailure.java18
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/exceptions/ExceededMaximumPollingTime.java20
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java41
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/rest/PropertiesBean.java230
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/rest/RestConsumer.java49
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/rest/RestPublisher.java41
-rw-r--r--common/src/main/java/org/onap/so/client/exceptions/SDNOException.java22
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/EmptyStringToNullSerializer.java40
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/Format.java30
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryClient.java43
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperPatchProvider.java16
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperProvider.java21
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectName.java5
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectPlurals.java3
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectType.java3
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectUriPartial.java2
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectUriTemplate.java2
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverter.java96
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryQueryClient.java198
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryResourcesClient.java575
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryRestClient.java67
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventorySubgraphType.java19
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryTransactionClient.java404
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/TransactionBuilder.java12
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNode.java91
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java75
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQuery.java38
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java223
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java6
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryRelationships.java186
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryResultWrapper.java172
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/Resource.java53
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/ResourceAndUrl.java63
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/__.java66
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/uri/Depth.java34
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryResourceUri.java54
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryUri.java81
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java4
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java464
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParser.java5
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java52
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/exceptions/BulkProcessFailed.java6
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryPatchDepthExceededException.java12
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryPayloadException.java28
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryUriComputationException.java16
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryUriNotFoundException.java8
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/exceptions/IncorrectNumberOfUriKeys.java10
-rw-r--r--common/src/main/java/org/onap/so/client/grm/GRMAction.java19
-rw-r--r--common/src/main/java/org/onap/so/client/grm/GRMClient.java99
-rw-r--r--common/src/main/java/org/onap/so/client/grm/GRMProperties.java11
-rw-r--r--common/src/main/java/org/onap/so/client/grm/GRMPropertiesLoader.java41
-rw-r--r--common/src/main/java/org/onap/so/client/grm/GRMRestClient.java31
-rw-r--r--common/src/main/java/org/onap/so/client/grm/GRMRestInvoker.java59
-rw-r--r--common/src/main/java/org/onap/so/client/grm/beans/OperationalInfo.java93
-rw-r--r--common/src/main/java/org/onap/so/client/grm/beans/Property.java63
-rw-r--r--common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPoint.java419
-rw-r--r--common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointList.java19
-rw-r--r--common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointLookup.java45
-rw-r--r--common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointLookupRequest.java50
-rw-r--r--common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointRequest.java50
-rw-r--r--common/src/main/java/org/onap/so/client/grm/beans/Status.java91
-rw-r--r--common/src/main/java/org/onap/so/client/grm/beans/Version.java73
-rw-r--r--common/src/main/java/org/onap/so/client/grm/beans/VersionLookup.java27
-rw-r--r--common/src/main/java/org/onap/so/client/grm/exceptions/GRMClientCallFailed.java10
-rw-r--r--common/src/main/java/org/onap/so/client/policy/CommonObjectMapperProvider.java26
-rw-r--r--common/src/main/java/org/onap/so/client/policy/DecisionAttributes.java122
-rw-r--r--common/src/main/java/org/onap/so/client/policy/JettisonStyleMapperProvider.java23
-rw-r--r--common/src/main/java/org/onap/so/client/policy/PolicyClient.java12
-rw-r--r--common/src/main/java/org/onap/so/client/policy/PolicyClientImpl.java167
-rw-r--r--common/src/main/java/org/onap/so/client/policy/PolicyRestClient.java28
-rw-r--r--common/src/main/java/org/onap/so/client/policy/PolicyRestProperties.java10
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/AllowedTreatments.java147
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/Bbid.java90
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/Config.java18
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/ConfigRequestParameters.java11
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/Content.java4
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/DecisionAttributes.java124
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/DictionaryData.java143
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/DictionaryItemsRequest.java50
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/DictionaryJson.java33
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/FabricConfigModel.java5
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/Id.java61
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/PolicyConfig.java15
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/PolicyDecision.java50
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/PolicyDecisionRequest.java50
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/PolicyServiceType.java41
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/Treatments.java90
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/Workstep.java90
-rw-r--r--common/src/main/java/org/onap/so/client/ruby/RubyClient.java105
-rw-r--r--common/src/main/java/org/onap/so/client/ruby/beans/Event.java59
-rw-r--r--common/src/main/java/org/onap/so/client/ruby/beans/MsoRequest.java344
-rw-r--r--common/src/main/java/org/onap/so/client/ruby/beans/Ruby.java59
-rw-r--r--common/src/main/java/org/onap/so/client/ruby/dmaap/RubyCreateTicketRequestPublisher.java51
-rw-r--r--common/src/main/java/org/onap/so/client/sdno/SDNOHealthCheckClient.java239
-rw-r--r--common/src/main/java/org/onap/so/client/sdno/SDNOValidator.java48
-rw-r--r--common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java165
-rw-r--r--common/src/main/java/org/onap/so/client/sdno/beans/AAIParamList.java92
-rw-r--r--common/src/main/java/org/onap/so/client/sdno/beans/Body.java11
-rw-r--r--common/src/main/java/org/onap/so/client/sdno/beans/Input.java23
-rw-r--r--common/src/main/java/org/onap/so/client/sdno/beans/RequestHdCustom.java306
-rw-r--r--common/src/main/java/org/onap/so/client/sdno/beans/RequestHealthDiagnostic.java22
-rw-r--r--common/src/main/java/org/onap/so/client/sdno/beans/ResultInfo.java161
-rw-r--r--common/src/main/java/org/onap/so/client/sdno/beans/SDNO.java39
-rw-r--r--common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java261
-rw-r--r--common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java49
-rw-r--r--common/src/main/java/org/onap/so/configuration/rest/HttpClientConnectionConfiguration.java4
-rw-r--r--common/src/main/java/org/onap/so/configuration/rest/HttpComponentsClientConfiguration.java1
-rw-r--r--common/src/main/java/org/onap/so/constants/Defaults.java49
-rw-r--r--common/src/main/java/org/onap/so/entity/MsoRequest.java66
-rw-r--r--common/src/main/java/org/onap/so/exceptions/MSOException.java32
-rw-r--r--common/src/main/java/org/onap/so/exceptions/MarshallerException.java2
-rw-r--r--common/src/main/java/org/onap/so/exceptions/ValidationException.java18
-rw-r--r--common/src/main/java/org/onap/so/jsonpath/JsonPathUtil.java107
-rw-r--r--common/src/main/java/org/onap/so/logger/ErrorCode.java2
-rw-r--r--common/src/main/java/org/onap/so/logger/LogConstants.java8
-rw-r--r--common/src/main/java/org/onap/so/logger/LoggerStartupListener.java65
-rw-r--r--common/src/main/java/org/onap/so/logger/MessageEnum.java209
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java36
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java73
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java51
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCTaskDecorator.java33
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java220
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java89
-rw-r--r--common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java91
-rw-r--r--common/src/main/java/org/onap/so/openpojo/rules/CustomSetterMustExistRule.java47
-rw-r--r--common/src/main/java/org/onap/so/openpojo/rules/EqualsAndHashCodeTester.java177
-rw-r--r--common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationMatcher.java63
-rw-r--r--common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationPropertyWithValueMatcher.java85
-rw-r--r--common/src/main/java/org/onap/so/openpojo/rules/HasEqualsAndHashCodeRule.java84
-rw-r--r--common/src/main/java/org/onap/so/openpojo/rules/HasToStringRule.java75
-rw-r--r--common/src/main/java/org/onap/so/openpojo/rules/ToStringTester.java42
-rw-r--r--common/src/main/java/org/onap/so/properties/MsoDatabaseException.java14
-rw-r--r--common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java16
-rw-r--r--common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java21
-rw-r--r--common/src/main/java/org/onap/so/security/MSOSpringFirewall.java14
-rw-r--r--common/src/main/java/org/onap/so/security/UserCredentials.java42
-rw-r--r--common/src/main/java/org/onap/so/security/UserDetailsServiceImpl.java34
-rw-r--r--common/src/main/java/org/onap/so/security/WebSecurityConfig.java64
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/CloudConfiguration.java68
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/ExceptionType.java80
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/GetOrchestrationListResponse.java25
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/GetOrchestrationResponse.java24
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/InstanceDirection.java3
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/InstanceReferences.java239
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/LineOfBusiness.java33
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/ModelInfo.java257
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java13
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/Networks.java125
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/OwningEntity.java55
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/Platform.java33
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/PolicyException.java18
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/Project.java31
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RelatedInstance.java93
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RelatedInstanceList.java27
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/Request.java147
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestDetails.java254
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestError.java54
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java177
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestList.java24
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java248
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestProcessingData.java91
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java63
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java76
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java55
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/Service.java102
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/ServiceException.java19
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java191
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesResponse.java32
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/SubscriberInfo.java32
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/VfModules.java128
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/Vnfs.java191
-rw-r--r--common/src/main/java/org/onap/so/spring/SpringContextHelper.java16
-rw-r--r--common/src/main/java/org/onap/so/test/categories/SlowTests.java2
-rw-r--r--common/src/main/java/org/onap/so/utils/CheckResults.java57
-rw-r--r--common/src/main/java/org/onap/so/utils/CryptoUtils.java60
-rw-r--r--common/src/main/java/org/onap/so/utils/TargetEntity.java9
-rw-r--r--common/src/main/java/org/onap/so/utils/UUIDChecker.java8
-rw-r--r--common/src/main/java/org/onap/so/utils/XmlMarshaller.java10
-rw-r--r--common/src/main/java/org/onap/so/web/exceptions/ExceptionResponse.java27
-rw-r--r--common/src/main/java/org/onap/so/web/exceptions/RuntimeExceptionMapper.java25
-rw-r--r--common/src/test/java/org/onap/so/BeansTest.java76
-rw-r--r--common/src/test/java/org/onap/so/NonSpringSuite.java1
-rw-r--r--common/src/test/java/org/onap/so/SpringSuite.java1
-rw-r--r--common/src/test/java/org/onap/so/adapter_utils/tests/CryptoTest.java63
-rw-r--r--common/src/test/java/org/onap/so/client/HttpClientTest.java85
-rw-r--r--common/src/test/java/org/onap/so/client/RestClientTest.java80
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIClientResponseExceptionMapperTest.java64
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIConfigurationClientTest.java225
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIErrorFormatterTest.java100
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java119
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIPServerTest.java36
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java170
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java326
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java140
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java59
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java150
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java219
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIURITest.java21
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIUpdatorTest.java52
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java135
-rw-r--r--common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java159
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/AAIResultWrapperTest.java131
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/RelationshipsTest.java46
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromParentUriTest.java26
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromUriTest.java64
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriTest.java156
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/uri/AAIUriFactoryTest.java74
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUriTest.java32
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/uri/IncorrectNumberOfUriKeysTest.java69
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java309
-rw-r--r--common/src/test/java/org/onap/so/client/aai/objects/CustomAAIObjectType.java26
-rw-r--r--common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java5
-rw-r--r--common/src/test/java/org/onap/so/client/cds/CDSProcessingClientTest.java65
-rw-r--r--common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java23
-rw-r--r--common/src/test/java/org/onap/so/client/defaultproperties/DefaultAAIPropertiesImpl.java104
-rw-r--r--common/src/test/java/org/onap/so/client/dmaap/DmaapClientTest.java16
-rw-r--r--common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java8
-rw-r--r--common/src/test/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverterTest.java138
-rw-r--r--common/src/test/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImplTest.java32
-rw-r--r--common/src/test/java/org/onap/so/client/grm/GRMBeansTest.java36
-rw-r--r--common/src/test/java/org/onap/so/client/grm/ServiceEndPointListTest.java128
-rw-r--r--common/src/test/java/org/onap/so/client/grm/ServiceEndPointRequestTest.java107
-rw-r--r--common/src/test/java/org/onap/so/client/grm/exception/GRMClientCallFailedTest.java1
-rw-r--r--common/src/test/java/org/onap/so/client/policy/PolicyClientImplTest.java195
-rw-r--r--common/src/test/java/org/onap/so/client/policy/entities/PolicyEntitiesTest.java36
-rw-r--r--common/src/test/java/org/onap/so/client/ruby/RubyCheckClientTest.java129
-rw-r--r--common/src/test/java/org/onap/so/client/ruby/beans/RubyBeansTest.java36
-rw-r--r--common/src/test/java/org/onap/so/client/sdno/SDNOHealthCheckClientTest.java120
-rw-r--r--common/src/test/java/org/onap/so/client/sdno/SDNOValidatorImplTest.java47
-rw-r--r--common/src/test/java/org/onap/so/client/sdno/SDNOValidatorTest.java128
-rw-r--r--common/src/test/java/org/onap/so/client/sdno/beans/SdnoBeansTest.java36
-rw-r--r--common/src/test/java/org/onap/so/configuration/rest/BasicHttpHeadersProviderTest.java2
-rw-r--r--common/src/test/java/org/onap/so/configuration/rest/HttpComponentsClientConfigurationTest.java1
-rw-r--r--common/src/test/java/org/onap/so/constants/DefaultsTest.java11
-rw-r--r--common/src/test/java/org/onap/so/entity/MsoRequestTest.java10
-rw-r--r--common/src/test/java/org/onap/so/exceptions/ValidationExceptionTest.java8
-rw-r--r--common/src/test/java/org/onap/so/jsonpath/JsonPathUtilTest.java54
-rw-r--r--common/src/test/java/org/onap/so/serviceinstancebeans/RequestStatusTest.java27
-rw-r--r--common/src/test/java/org/onap/so/serviceinstancebeans/ServiceInstanceBeansTest.java68
-rw-r--r--common/src/test/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequestTest.java28
-rw-r--r--common/src/test/java/org/onap/so/test/categories/SpringAware.java2
-rw-r--r--common/src/test/java/org/onap/so/utils/CheckResultsTest.java41
-rw-r--r--common/src/test/java/org/onap/so/utils/TestAppender.java13
-rw-r--r--common/src/test/java/org/onap/so/utils/UUIDCheckerTest.java19
-rw-r--r--common/src/test/java/org/onap/so/utils/XMLMarshallerTest.java16
-rw-r--r--common/src/test/java/org/onap/so/web/exceptions/RuntimeExceptionMapperTest.java52
-rw-r--r--cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java38
-rw-r--r--cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingOutInterceptor.java15
-rw-r--r--cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPMDCSetup.java25
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/BpmnRequest.java435
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaBooleanInput.java19
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaBpmnRequestInput.java16
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaInput.java79
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaIntegerInput.java23
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequest.java7
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequestSerializer.java9
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaRequest.java193
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java128
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java625
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/Track.java36
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java513
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaTaskClient.java110
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CommonConstants.java104
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ErrorNumbers.java9
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/LSInputImpl.java33
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java29
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java131
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java59
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java74
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java371
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java45
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java26
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java30
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java28
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Constants.java39
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Messages.java57
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/ModelType.java8
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/MsoException.java3
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Status.java11
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java28
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java70
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/BPMNFailureException.java4
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ClientConnectionException.java12
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ContactCamundaException.java8
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java11
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RequestDbFailureException.java4
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java4
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/VfModuleNotFoundException.java13
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/logging/ErrorLoggerInfo.java30
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/BeansTest.java60
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/BpmnRequestTest.java2
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequestSerializerTest.java6
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/AllTestsTestSuite.java5
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java122
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaTaskClientTest.java24
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java103
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java54
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java101
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java32
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java12
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapperTest.java107
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/common/ResponseBuilder.java53
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/filters/RequestUriFilter.java49
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java30
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java28
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java63
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java1768
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java248
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java187
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java23
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java352
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java68
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java344
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java1119
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java32
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java20
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java678
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RecipeLookupResult.java42
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestActionMap.java2
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java962
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java2878
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SubsystemHealthcheckResponse.java16
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java424
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TestApi.java23
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java35
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java70
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java55
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java47
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/CompareModelsRequest.java60
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcResp.java14
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EParameters.java47
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java163
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java131
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequest.java40
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceRequest.java45
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParam.java59
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java31
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/LocationConstraint.java4
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParameters.java5
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java1
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/VimLocation.java6
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/package-info.java11
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestDetails.java15
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestInfo.java42
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskList.java198
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskRequestReference.java41
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariableValue.java46
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariables.java17
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksGetResponse.java14
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksRequest.java14
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/ValidResponses.java18
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Value.java16
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Variables.java43
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java64
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java363
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationRequest.java87
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java457
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java72
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java188
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java541
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRunnable.java94
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/CreateEcompOperationEnvironmentBean.java255
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClient.java74
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapPropertiesImpl.java42
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisher.java55
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailed.java6
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailed.java18
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationException.java24
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java164
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilder.java26
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java173
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java363
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java288
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java540
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironment.java63
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java348
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java92
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Action.java5
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationRequestList.java14
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationResponse.java18
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Distribution.java48
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/DistributionStatus.java3
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/InstanceReferences.java56
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java35
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/OperationalEnvironment.java3
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RecoveryAction.java4
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstance.java71
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstanceList.java19
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Request.java111
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestDetails.java49
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestInfo.java73
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestList.java33
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestParameters.java87
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestReferences.java82
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestStatus.java70
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ResourceType.java2
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ServiceModelList.java54
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Status.java3
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationRequest.java118
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationResponse.java101
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantSyncResponse.java16
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/package-info.java8
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ApplyUpdatedConfigValidation.java37
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java102
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ConfigurationParametersValidation.java31
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java37
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InPlaceSoftwareUpdateValidation.java51
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java105
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/MembersValidation.java73
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java220
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java49
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java56
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java430
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestInfoValidation.java62
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidation.java183
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestScopeValidation.java32
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/SubscriberInfoValidation.java38
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java205
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationInformation.java329
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationRule.java6
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ActionType.java25
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ModelType.java8
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java46
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestInfo.java82
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestStatusType.java14
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelName.java131
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelNames.java36
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfInputs.java348
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfOutputs.java130
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequest.java73
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequests.java34
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfType.java56
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfTypes.java38
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/package-info.java11
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ActivitySequence.java8
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ArtifactInfo.java20
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/Validation.java8
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowInputParameter.java15
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecification.java12
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationList.java7
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecifications.java10
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java44
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java42
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java101
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java6
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java32
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java75
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java58
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java450
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java68
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java62
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java328
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java143
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java106
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java1438
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java259
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java387
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java28
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java2359
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java135
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java12
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java64
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java3
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java19
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java5
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java10
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java12
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java15
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java438
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java528
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java113
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java214
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java64
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java26
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java76
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java1
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java33
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java31
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java206
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java65
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java195
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java230
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java310
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java1163
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java154
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java284
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java221
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java82
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java34
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java36
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java269
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java163
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationBeansTest.java15
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java202
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java2
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java24
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryCustom.java1
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java57
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationStatusRepository.java11
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvDistributionStatusRepository.java21
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvServiceModelStatusRepository.java24
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/RequestProcessingDataRepository.java8
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ResourceOperationStatusRepository.java6
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/SiteStatusRepository.java4
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogComponentDistributionStatusRepository.java9
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogDistributionStatusRepository.java4
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogServiceModVerIdLookupRepository.java7
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/TestApplication.java12
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OperationStatusTest.java79
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OperationalEnvServiceModelStatusTest.java85
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/RequestDBConfig.java64
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/SiteStatusTest.java86
-rw-r--r--mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImplTest.java11
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java102
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java5
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java81
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationStatus.java172
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationStatusId.java103
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvDistributionStatus.java261
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvServiceModelStatus.java306
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvServiceModelStatusId.java109
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java228
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ResourceOperationStatus.java145
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ResourceOperationStatusId.java126
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/SiteStatus.java66
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/Status.java8
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogComponentDistributionStatus.java191
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogComponentDistributionStatusId.java89
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogDistributionStatus.java188
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogServiceModVerIdLookup.java205
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogServiceModVerIdLookupId.java89
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java612
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/data/controller/InstanceNameDuplicateCheckRequest.java6
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/exceptions/NoEntityFoundException.java3
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/RequestsDBHelper.java152
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/RequestsDbConstant.java5
-rw-r--r--mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/TimestampXMLAdapter.java11
-rw-r--r--mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/db/request/beans/BeansTest.java48
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpec.java279
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategories.java168
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategoriesId.java96
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParameters.java168
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParametersId.java98
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecCategories.java103
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecParameters.java217
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParameters.java168
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParametersId.java96
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AllottedResource.java264
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AllottedResourceCustomization.java390
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ArRecipe.java287
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AuthenticationType.java2
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/BuildingBlockDetail.java143
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudIdentity.java239
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudSite.java28
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudifyManager.java314
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionNetworkResourceCustomization.java320
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResource.java256
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceCustomization.java252
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceInstanceGroupCustomization.java260
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceInstanceGroupCustomizationId.java79
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResource.java265
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResourceCustomization.java274
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ControllerSelectionReference.java133
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ControllerSelectionReferenceId.java98
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcConfigurationCustomization.java311
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcCustomization.java418
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ExternalServiceToInternalService.java183
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatEnvironment.java237
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatFiles.java223
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplate.java317
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplateParam.java167
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplateParamId.java72
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HomingInstance.java14
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/InstanceGroup.java352
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/InstanceGroupType.java2
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Model.java364
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ModelRecipe.java327
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkCollectionResourceCustomization.java30
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkInstanceGroup.java8
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkRecipe.java285
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResource.java456
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResourceCustomization.java262
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationAction.java38
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java66
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatusStateTransitionDirective.java185
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatusValidationDirective.java20
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResource.java32
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceCustomization.java34
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Recipe.java12
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ResourceType.java34
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServerType.java2
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java38
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceProxyResourceCustomization.java293
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceRecipe.java311
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/SubType.java22
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/TempNetworkHeatTemplateLookup.java159
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/TempNetworkHeatTemplateLookupId.java78
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ToscaCsar.java239
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/UserParameters.java302
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VFCInstanceGroup.java8
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModule.java357
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModuleCustomization.java382
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfComponentsRecipe.java259
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfRecipe.java311
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResource.java447
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java18
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflow.java171
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflowId.java97
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcCustomization.java290
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcInstanceGroupCustomization.java211
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java401
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequence.java169
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequenceId.java98
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/NorthBoundRequest.java331
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/OrchestrationFlow.java200
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java252
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java597
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/AllottedResourceCustomizationRepository.java13
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/AllottedResourceRepository.java2
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ArRecipeRepository.java5
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/BuildingBlockDetailRepository.java2
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CloudSiteRepository.java3
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionNetworkResourceCustomizationRepository.java11
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceCustomizationRepository.java10
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceInstanceGroupCustomizationRepository.java8
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceRepository.java4
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ConfigurationResourceCustomizationRepository.java7
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ConfigurationResourceRepository.java4
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ControllerSelectionReferenceRepository.java14
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CvnfcConfigurationCustomizationRepository.java8
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepository.java8
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ExternalServiceToInternalServiceRepository.java11
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HeatEnvironmentRepository.java2
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HeatTemplateRepository.java4
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HomingInstanceRepository.java2
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/InstanceGroupRepository.java4
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ModelRecipeRepository.java6
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ModelRepository.java6
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkCollectionResourceCustomizationRepository.java10
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkInstanceGroupRepository.java4
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkRecipeRepository.java7
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkResourceCustomizationRepository.java11
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkResourceRepository.java24
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NorthBoundRequestRepository.java11
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/OrchestrationFlowRepository.java5
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/OrchestrationStatusStateTransitionDirectiveRepository.java9
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/PnfCustomizationRepository.java33
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/PnfResourceRepository.java25
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java4
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceProxyResourceCustomizationRepository.java11
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRecipeRepository.java8
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRepository.java147
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/TempNetworkHeatTemplateRepository.java4
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFCInstanceGroupRepository.java4
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFModuleCustomizationRepository.java9
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFModuleRepository.java59
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfComponentRecipeRepository.java14
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfCustomizationRepository.java10
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfRecipeRepository.java10
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfResourceRepository.java14
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfResourceWorkflowRepository.java6
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepository.java4
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfcInstanceGroupCustomizationRepository.java6
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java4
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/exceptions/NoEntityFoundException.java2
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/rest/beans/ServiceMacroHolder.java325
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioning.java162
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioningComparator.java32
-rw-r--r--mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/RecordNotFoundException.java40
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/BaseTest.java84
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/BuildingBlockDetailTest.java26
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/ControllerSelectionReferenceTest.java51
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/EmbeddedMariaDbConfig.java22
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/MavenVersioningTest.java299
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/NetworkTest.java17
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/OrchestrationStatusStateTransitionDirectiveTest.java26
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/ServiceTest.java24
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/TempNetworkHeatTemplateLookupTest.java33
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/TestApplication.java28
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/VFModuleTest.java35
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/BeansTest.java76
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CloudIdentityTest.java110
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CloudifyManagerTest.java38
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CvnfcConfigurationCustomizationTest.java79
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CvnfcCustomizationTest.java109
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/VnfcCustomizationTest.java93
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CloudSiteRepositoryTest.java17
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CloudifyManagerRepositoryTest.java2
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CollectionNetworkResourceCustomizationRepositoryTest.java13
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java279
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/PnfCustomizationRepositoryTest.java34
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/PnfResourceRepositoryTest.java30
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java31
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java31
-rw-r--r--mso-catalog-db/src/test/java/org/onap/so/db/catalog/test/RecordNotFoundExceptionTest.java4
-rw-r--r--pom.xml1663
-rw-r--r--project-configs/code-tools/onap-eclipse-format.xml313
-rw-r--r--project-configs/code-tools/pom-format.properties5
-rw-r--r--so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ActivityInstance.java3
-rw-r--r--so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessDefinition.java1
-rw-r--r--so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessInstance.java1
-rw-r--r--so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessInstanceVariable.java1
-rw-r--r--so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/SoActiveInfraRequests.java1
-rw-r--r--so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/camunda/CamundaRestUrlProvider.java16
-rw-r--r--so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/database/DatabaseUrlProvider.java1
-rw-r--r--so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/HttpServiceProviderConfiguration.java1
-rw-r--r--so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProvider.java1
-rw-r--r--so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProviderImpl.java3
-rw-r--r--so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProvider.java8
-rw-r--r--so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderImpl.java3
-rw-r--r--so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/CamundaConfigurationTest.java1
-rw-r--r--so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/CamundaRestUrlProviderTest.java2
-rw-r--r--so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/HttpServiceProviderConfigurationTest.java1
-rw-r--r--so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/PojoClassesTests.java4
-rw-r--r--so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/database/DatabaseUrlProviderTest.java1
-rw-r--r--so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/db/api/DatabaseServiceProviderTest.java3
-rw-r--r--so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderTest.java3
-rw-r--r--so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/utils/ObjectEqualsUtilsTest.java2
-rw-r--r--so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/JerseyConfiguration.java1
-rw-r--r--so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java3
-rw-r--r--so-monitoring/so-monitoring-service/src/test/java/org/onap/so/monitoring/rest/api/SoMonitoringControllerTest.java3
2280 files changed, 152967 insertions, 154886 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/adapters/vdu/VduPlugin.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/adapters/vdu/VduPlugin.java
index ff30c0ee70..bc2757b41c 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/adapters/vdu/VduPlugin.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/adapters/vdu/VduPlugin.java
@@ -21,27 +21,22 @@
package org.onap.so.adapters.vdu;
/**
- * This interface defines a common API for template-based cloud deployments.
- * The methods here should be adaptable for Openstack (Heat), Cloudify (TOSCA),
- * Aria (TOSCA), Multi-VIM (TBD), and others (e.g. Azure Resource Manager).
+ * This interface defines a common API for template-based cloud deployments. The methods here should be adaptable for
+ * Openstack (Heat), Cloudify (TOSCA), Aria (TOSCA), Multi-VIM (TBD), and others (e.g. Azure Resource Manager).
*
- * The deployed instances are referred to here as Virtual Deployment Units (VDUs).
- * The package of templates that define a give VDU is referred to as its blueprint.
+ * The deployed instances are referred to here as Virtual Deployment Units (VDUs). The package of templates that define
+ * a give VDU is referred to as its blueprint.
*
- * Template-based orchestrators all follow a similar template/blueprint model.
- * - One main template that is the top level definition
- * - Optional nested templates referenced/included by the main template
- * - Optional files attached to the template package, typically containing
- * configuration files, install scripts, orchestration scripts, etc.
- *
- * The main template also defines the required inputs for creating a new instance,
- * and output values exposed by successfully deployed instances. Inputs and outputs
- * may include simple or complex (JSON) data types.
- *
- * Each implementation of this interface is expected to understand the MSO CloudConfig
- * to obtain the credentials for its sub-orchestrator and the targeted cloud.
- * The sub-orchestrator may have different credentials from the cloud (e.g. an Aria
- * instance in front of an Openstack cloud) or they may be the same (e.g. Heat)
+ * Template-based orchestrators all follow a similar template/blueprint model. - One main template that is the top level
+ * definition - Optional nested templates referenced/included by the main template - Optional files attached to the
+ * template package, typically containing configuration files, install scripts, orchestration scripts, etc.
+ *
+ * The main template also defines the required inputs for creating a new instance, and output values exposed by
+ * successfully deployed instances. Inputs and outputs may include simple or complex (JSON) data types.
+ *
+ * Each implementation of this interface is expected to understand the MSO CloudConfig to obtain the credentials for its
+ * sub-orchestrator and the targeted cloud. The sub-orchestrator may have different credentials from the cloud (e.g. an
+ * Aria instance in front of an Openstack cloud) or they may be the same (e.g. Heat)
*/
import java.util.Map;
@@ -50,137 +45,110 @@ public interface VduPlugin {
/**
* The instantiateVdu interface deploys a new VDU instance from a vdu model package.
*
- * For some VIMs, this may be a single command (e.g. Heat -> create stack) or may
- * require a series of API calls (e.g. Cloudify -> upload blueprint, create deployment,
- * execute install workflow). These details are hidden within the plug-in implementation.
- * The instantiation should be fully completed before returning. On failures, this
+ * For some VIMs, this may be a single command (e.g. Heat -> create stack) or may require a series of API calls
+ * (e.g. Cloudify -> upload blueprint, create deployment, execute install workflow). These details are hidden within
+ * the plug-in implementation. The instantiation should be fully completed before returning. On failures, this
* method is expected to back out the attempt, leaving the cloud in its previous state.
*
- * It is expected that parameters have been validated and contain at minimum the
- * required parameters for the given template with no extra parameters.
+ * It is expected that parameters have been validated and contain at minimum the required parameters for the given
+ * template with no extra parameters.
*
- * The VDU name supplied by the caller will be globally unique, and identify the artifact
- * in A&AI. Inventory is managed by the higher levels invoking this function.
+ * The VDU name supplied by the caller will be globally unique, and identify the artifact in A&AI. Inventory is
+ * managed by the higher levels invoking this function.
*
* @param cloudInfo The target cloud + tenant identifiers for the VDU.
* @param instanceName A unique name for the VDU instance to update.
- * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects.
- * Will completely replace any inputs provided on the original instantiation.
- * @param vduModel Object containing the collection of templates and files that comprise
- * the blueprint for this VDU.
- * @param rollbackOnFailure Flag to preserve or roll back the update on Failure. Should normally
- * be True except in troubleshooting/debug cases. Might not be supported in all plug-ins.
+ * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects. Will completely replace
+ * any inputs provided on the original instantiation.
+ * @param vduModel Object containing the collection of templates and files that comprise the blueprint for this VDU.
+ * @param rollbackOnFailure Flag to preserve or roll back the update on Failure. Should normally be True except in
+ * troubleshooting/debug cases. Might not be supported in all plug-ins.
*
* @return A VduInstance object
- * @throws VduException Thrown if the sub-orchestrator API calls fail or if a timeout occurs.
- * Various subclasses of VduException may be thrown.
+ * @throws VduException Thrown if the sub-orchestrator API calls fail or if a timeout occurs. Various subclasses of
+ * VduException may be thrown.
*/
- public VduInstance instantiateVdu (
- CloudInfo cloudInfo,
- String instanceName,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException;
-
+ public VduInstance instantiateVdu(CloudInfo cloudInfo, String instanceName, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException;
+
/**
- * Query a deployed VDU instance. This call will return a VduInstance object, or null
- * if the deployment does not exist.
+ * Query a deployed VDU instance. This call will return a VduInstance object, or null if the deployment does not
+ * exist.
*
- * Some VIM orchestrators identify deployment instances by string UUIDs, and others
- * by integers. In the latter case, the ID will be passed in as a numeric string.
+ * Some VIM orchestrators identify deployment instances by string UUIDs, and others by integers. In the latter case,
+ * the ID will be passed in as a numeric string.
*
- * The returned VduInstance object contains the input and output parameter maps,
- * as well as other properties of the deployment (name, status, last action, etc.).
+ * The returned VduInstance object contains the input and output parameter maps, as well as other properties of the
+ * deployment (name, status, last action, etc.).
*
* @param cloudInfo The target cloud + tenant identifiers for the VDU.
* @param vduInstanceId The ID of the deployment to query
*
* @return A VduInstance object
- * @throws VduException Thrown if the sub-orchestrator API calls fail or if a timeout occurs.
- * Various subclasses of VduException may be thrown.
+ * @throws VduException Thrown if the sub-orchestrator API calls fail or if a timeout occurs. Various subclasses of
+ * VduException may be thrown.
*/
- public VduInstance queryVdu (
- CloudInfo cloudInfo,
- String vduInstanceId)
- throws VduException;
+ public VduInstance queryVdu(CloudInfo cloudInfo, String vduInstanceId) throws VduException;
+
-
/**
- * Delete a VDU instance by ID. If the VIM sub-orchestrator supports pre-installation
- * of blueprints/models, the blueprint itself may remain installed. This is recommended,
- * since other VDU instances may be using it.
- *
- * Some VIM orchestrators identify deployment instances by string UUIDs, and others
- * by integers. In the latter case, the ID will be passed in as a numeric string.
- *
- * For some VIMs, deletion may be a single command (e.g. Heat -> delete stack) or a
- * series of API calls (e.g. Cloudify -> execute uninstall workflow, delete deployment).
- * These details are hidden within the plug-in implementation. The deletion should be
- * fully completed before returning.
- *
- * The successful return is a VduInstance object which contains the state of the VDU
- * just prior to deletion, with a status of DELETED. If the deployment was not found,
- * the VduInstance object should be empty (with a status of NOTFOUND).
- * There is no rollback from a successful deletion.
- *
- * A deletion failure will result in an undefined deployment state - the components may
- * or may not have been all or partially uninstalled, so the resulting deployment must
- * be considered invalid.
+ * Delete a VDU instance by ID. If the VIM sub-orchestrator supports pre-installation of blueprints/models, the
+ * blueprint itself may remain installed. This is recommended, since other VDU instances may be using it.
+ *
+ * Some VIM orchestrators identify deployment instances by string UUIDs, and others by integers. In the latter case,
+ * the ID will be passed in as a numeric string.
+ *
+ * For some VIMs, deletion may be a single command (e.g. Heat -> delete stack) or a series of API calls (e.g.
+ * Cloudify -> execute uninstall workflow, delete deployment). These details are hidden within the plug-in
+ * implementation. The deletion should be fully completed before returning.
+ *
+ * The successful return is a VduInstance object which contains the state of the VDU just prior to deletion, with a
+ * status of DELETED. If the deployment was not found, the VduInstance object should be empty (with a status of
+ * NOTFOUND). There is no rollback from a successful deletion.
+ *
+ * A deletion failure will result in an undefined deployment state - the components may or may not have been all or
+ * partially uninstalled, so the resulting deployment must be considered invalid.
*
* @param cloudInfo The target cloud + tenant identifiers for the VDU.
* @param instanceId The unique id of the deployment to delete.
- * @param timeoutMinutes Timeout after which the delete action will be cancelled.
- * Consider sending the entire model here, if it may be of use to the plug-in?
+ * @param timeoutMinutes Timeout after which the delete action will be cancelled. Consider sending the entire model
+ * here, if it may be of use to the plug-in?
*
* @return A VduInstance object, representing its state just prior to deletion.
*
- * @throws VduException Thrown if the API calls fail or if a timeout occurs.
- * Various subclasses of VduException may be thrown.
+ * @throws VduException Thrown if the API calls fail or if a timeout occurs. Various subclasses of VduException may
+ * be thrown.
*/
- public VduInstance deleteVdu (
- CloudInfo cloudInfo,
- String instanceId,
- int timeoutMinutes)
- throws VduException;
+ public VduInstance deleteVdu(CloudInfo cloudInfo, String instanceId, int timeoutMinutes) throws VduException;
+
-
/**
- * The updateVdu interface attempts to update a VDU in-place, using either new inputs or
- * a new model definition (i.e. updated templates/blueprints). This depends on the
- * capabilities of the targeted sub-orchestrator, as not all implementations are expected
- * to support this ability. It is primary included initially only for Heat.
- *
- * It is expected that parameters have been validated and contain at minimum the required
- * parameters for the given template with no extra parameters. The VDU instance name cannot
- * be updated.
- *
- * The update should be fully completed before returning. The successful return is a
- * VduInstance object containing the updated VDU state.
- *
- * An update failure will result in an undefined deployment state - the components may
- * or may not have been all or partially modified, deleted, recreated, etc. So the resulting
- * VDU must be considered invalid.
+ * The updateVdu interface attempts to update a VDU in-place, using either new inputs or a new model definition
+ * (i.e. updated templates/blueprints). This depends on the capabilities of the targeted sub-orchestrator, as not
+ * all implementations are expected to support this ability. It is primary included initially only for Heat.
+ *
+ * It is expected that parameters have been validated and contain at minimum the required parameters for the given
+ * template with no extra parameters. The VDU instance name cannot be updated.
+ *
+ * The update should be fully completed before returning. The successful return is a VduInstance object containing
+ * the updated VDU state.
+ *
+ * An update failure will result in an undefined deployment state - the components may or may not have been all or
+ * partially modified, deleted, recreated, etc. So the resulting VDU must be considered invalid.
*
* @param cloudInfo The target cloud + tenant identifiers for the VDU.
* @param instanceId The unique ID for the VDU instance to update.
- * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects.
- * Will completely replace any inputs provided on the original instantiation.
- * @param vduModel Object containing the collection of templates and files that comprise
- * the blueprint for this VDU.
- * @param rollbackOnFailure Flag to preserve or roll back the update on Failure. Should normally
- * be True except in troubleshooting/debug cases. Might not be supported in all plug-ins.
+ * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects. Will completely replace
+ * any inputs provided on the original instantiation.
+ * @param vduModel Object containing the collection of templates and files that comprise the blueprint for this VDU.
+ * @param rollbackOnFailure Flag to preserve or roll back the update on Failure. Should normally be True except in
+ * troubleshooting/debug cases. Might not be supported in all plug-ins.
*
* @return A VduInfo object
- * @throws VduException Thrown if the sub-orchestrator API calls fail or if a timeout occurs.
- * Various subclasses of VduException may be thrown.
+ * @throws VduException Thrown if the sub-orchestrator API calls fail or if a timeout occurs. Various subclasses of
+ * VduException may be thrown.
*/
- public VduInstance updateVdu (
- CloudInfo cloudInfo,
- String instanceId,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException;
+ public VduInstance updateVdu(CloudInfo cloudInfo, String instanceId, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException;
-} \ No newline at end of file
+}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/audit/beans/AuditInventory.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/audit/beans/AuditInventory.java
index 025d40d7c4..7e612b3b41 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/audit/beans/AuditInventory.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/audit/beans/AuditInventory.java
@@ -22,53 +22,53 @@ package org.onap.so.audit.beans;
import java.io.Serializable;
-public class AuditInventory implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = 4937350343452380760L;
-
- private String cloudRegion;
-
- private String cloudOwner;
-
- private String tenantId;
-
- private String heatStackName;
-
- public String getCloudRegion() {
- return cloudRegion;
- }
-
- public void setCloudRegion(String cloudRegion) {
- this.cloudRegion = cloudRegion;
- }
-
- public String getCloudOwner() {
- return cloudOwner;
- }
-
- public void setCloudOwner(String cloudOwner) {
- this.cloudOwner = cloudOwner;
- }
-
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getHeatStackName() {
- return heatStackName;
- }
-
- public void setHeatStackName(String heatStackName) {
- this.heatStackName = heatStackName;
- }
-
-
+public class AuditInventory implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 4937350343452380760L;
+
+ private String cloudRegion;
+
+ private String cloudOwner;
+
+ private String tenantId;
+
+ private String heatStackName;
+
+ public String getCloudRegion() {
+ return cloudRegion;
+ }
+
+ public void setCloudRegion(String cloudRegion) {
+ this.cloudRegion = cloudRegion;
+ }
+
+ public String getCloudOwner() {
+ return cloudOwner;
+ }
+
+ public void setCloudOwner(String cloudOwner) {
+ this.cloudOwner = cloudOwner;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getHeatStackName() {
+ return heatStackName;
+ }
+
+ public void setHeatStackName(String heatStackName) {
+ this.heatStackName = heatStackName;
+ }
+
+
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfig.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfig.java
index b32ca1833f..fbf7741b4a 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfig.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfig.java
@@ -21,9 +21,7 @@
package org.onap.so.cloud;
import java.util.Optional;
-
import com.fasterxml.jackson.annotation.JsonRootName;
-
import org.onap.so.db.catalog.beans.CloudSite;
import org.onap.so.db.catalog.beans.CloudifyManager;
import org.onap.so.db.catalog.client.CatalogDbClient;
@@ -31,24 +29,21 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
- * JavaBean JSON class for a CloudConfig. This bean maps a JSON-format cloud
- * configuration file to Java. The CloudConfig contains information about
- * Openstack cloud configurations. It includes:
- * - CloudIdentity objects,representing DCP nodes (Openstack Identity Service)
- * - CloudSite objects, representing LCP nodes (Openstack Compute & other services)
+ * JavaBean JSON class for a CloudConfig. This bean maps a JSON-format cloud configuration file to Java. The CloudConfig
+ * contains information about Openstack cloud configurations. It includes: - CloudIdentity objects,representing DCP
+ * nodes (Openstack Identity Service) - CloudSite objects, representing LCP nodes (Openstack Compute & other services)
*
- * Note that this is only used to access Cloud Configurations loaded from a JSON
- * config file, so there are no explicit property setters.
+ * Note that this is only used to access Cloud Configurations loaded from a JSON config file, so there are no explicit
+ * property setters.
*
- * This class also contains methods to query cloud sites and/or identity
- * services by ID.
+ * This class also contains methods to query cloud sites and/or identity services by ID.
*
*/
@JsonRootName("cloud_config")
@Component
public class CloudConfig {
-
+
private static final String CLOUD_SITE_VERSION = "2.5";
private static final String DEFAULT_CLOUD_SITE_ID = "DEFAULT";
@@ -56,41 +51,40 @@ public class CloudConfig {
private CatalogDbClient catalogDbClient;
/**
- * Get a specific CloudSites, based on an ID. The ID is first checked
- * against the regions, and if no match is found there, then against
- * individual entries to try and find one with a CLLI that matches the ID
- * and an AIC version of 2.5.
+ * Get a specific CloudSites, based on an ID. The ID is first checked against the regions, and if no match is found
+ * there, then against individual entries to try and find one with a CLLI that matches the ID and an AIC version of
+ * 2.5.
*
* @param id the ID to match
* @return an Optional of CloudSite object.
*/
- public synchronized Optional<CloudSite> getCloudSite(String id) {
- if (id == null) {
- return Optional.empty();
- }
- CloudSite cloudSite = catalogDbClient.getCloudSite(id);
+ public synchronized Optional<CloudSite> getCloudSite(String id) {
+ if (id == null) {
+ return Optional.empty();
+ }
+ CloudSite cloudSite = catalogDbClient.getCloudSite(id);
+
+ if (cloudSite != null) {
+ return Optional.of(cloudSite);
+ } else {
+ return getCloudSiteWithClli(id);
+ }
+ }
- if (cloudSite != null) {
- return Optional.of(cloudSite);
- } else {
- return getCloudSiteWithClli(id);
- }
- }
-
/**
- * Get a specific CloudSites, based on a CLLI and (optional) version, which
- * will be matched against the aic_version field of the CloudSite.
+ * Get a specific CloudSites, based on a CLLI and (optional) version, which will be matched against the aic_version
+ * field of the CloudSite.
*
- * @param clli
- * the CLLI to match
+ * @param clli the CLLI to match
* @return a CloudSite, or null of no match found
*/
private Optional<CloudSite> getCloudSiteWithClli(String clli) {
- Optional <CloudSite> cloudSiteOptional = Optional.ofNullable(catalogDbClient.getCloudSiteByClliAndAicVersion(clli,CLOUD_SITE_VERSION));
+ Optional<CloudSite> cloudSiteOptional =
+ Optional.ofNullable(catalogDbClient.getCloudSiteByClliAndAicVersion(clli, CLOUD_SITE_VERSION));
if (cloudSiteOptional.isPresent()) {
- return cloudSiteOptional;
+ return cloudSiteOptional;
} else {
- return getDefaultCloudSite(clli);
+ return getDefaultCloudSite(clli);
}
}
@@ -107,12 +101,13 @@ public class CloudConfig {
}
}
- /**
- * Get a specific CloudifyManager, based on an ID.
- * @param id the ID to match
- * @return a CloudifyManager, or null of no match found
- */
- public CloudifyManager getCloudifyManager (String id) {
+ /**
+ * Get a specific CloudifyManager, based on an ID.
+ *
+ * @param id the ID to match
+ * @return a CloudifyManager, or null of no match found
+ */
+ public CloudifyManager getCloudifyManager(String id) {
return catalogDbClient.getCloudifyManager(id);
- }
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfigIdentityMapper.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfigIdentityMapper.java
index f554aa46cd..cbc0428b15 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfigIdentityMapper.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/CloudConfigIdentityMapper.java
@@ -20,11 +20,11 @@
package org.onap.so.cloud;
/**
- * This interface provides the method signature for mapping registration.
- * All mappings should be registered by the implementing class.
+ * This interface provides the method signature for mapping registration. All mappings should be registered by the
+ * implementing class.
*/
@FunctionalInterface
public interface CloudConfigIdentityMapper {
- public void registerAllMappings();
+ public void registerAllMappings();
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java
index 49c80b44b5..59c6becfbd 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java
@@ -21,13 +21,11 @@
package org.onap.so.cloud.authentication;
import java.util.Collections;
-
import org.onap.so.cloud.authentication.models.RackspaceAuthentication;
import org.onap.so.db.catalog.beans.AuthenticationType;
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.utils.CryptoUtils;
import org.springframework.stereotype.Component;
-
import com.woorea.openstack.keystone.model.Authentication;
import com.woorea.openstack.keystone.model.authentication.UsernamePassword;
import com.woorea.openstack.keystone.v3.model.Authentication.Identity;
@@ -44,44 +42,51 @@ import com.woorea.openstack.keystone.v3.model.Authentication.Scope.Project;
@Component
public final class AuthenticationMethodFactory {
- public final Authentication getAuthenticationFor(CloudIdentity cloudIdentity) {
- if (cloudIdentity == null) {
- throw new IllegalArgumentException("Cloud identity cannot be null");
- }
- if ((cloudIdentity.getIdentityAuthenticationType() == null)|| ("".equals(cloudIdentity.getIdentityAuthenticationType().toString()))) {
- throw new IllegalArgumentException("Cloud identity authentication type cannot be null or empty, provided value is " + cloudIdentity.getIdentityAuthenticationType() + ".");
- }
- AuthenticationType authenticationType = cloudIdentity.getIdentityAuthenticationType();
- if (AuthenticationType.RACKSPACE_APIKEY.equals(authenticationType)) {
- return new RackspaceAuthentication (cloudIdentity.getMsoId (), CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass ()));
- } else {
- return new UsernamePassword (cloudIdentity.getMsoId (), CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass ()));
- }
- }
-
-
- public final com.woorea.openstack.keystone.v3.model.Authentication getAuthenticationForV3(CloudIdentity cloudIdentity, String tenantId) {
- Identity identity = new Identity();
- Password password = new Password();
- User user = new User();
- Domain userDomain = new Domain();
- Scope scope = new Scope();
- Project project = new Project();
- Project.Domain projectDomain = new Project.Domain();
- userDomain.setName(cloudIdentity.getUserDomainName());
- projectDomain.setName(cloudIdentity.getProjectDomainName());
- user.setName(cloudIdentity.getMsoId());
- user.setPassword(CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass()));
- user.setDomain(userDomain);
- password.setUser(user);
- project.setDomain(projectDomain);
- project.setId(tenantId);
- scope.setProject(project);
- identity.setPassword(password);
- identity.setMethods(Collections.singletonList("password"));
- com.woorea.openstack.keystone.v3.model.Authentication v3Auth = new com.woorea.openstack.keystone.v3.model.Authentication();
- v3Auth.setIdentity(identity);
- v3Auth.setScope(scope);
- return v3Auth;
- }
+ public final Authentication getAuthenticationFor(CloudIdentity cloudIdentity) {
+ if (cloudIdentity == null) {
+ throw new IllegalArgumentException("Cloud identity cannot be null");
+ }
+ if ((cloudIdentity.getIdentityAuthenticationType() == null)
+ || ("".equals(cloudIdentity.getIdentityAuthenticationType().toString()))) {
+ throw new IllegalArgumentException(
+ "Cloud identity authentication type cannot be null or empty, provided value is "
+ + cloudIdentity.getIdentityAuthenticationType() + ".");
+ }
+ AuthenticationType authenticationType = cloudIdentity.getIdentityAuthenticationType();
+ if (AuthenticationType.RACKSPACE_APIKEY.equals(authenticationType)) {
+ return new RackspaceAuthentication(cloudIdentity.getMsoId(),
+ CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass()));
+ } else {
+ return new UsernamePassword(cloudIdentity.getMsoId(),
+ CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass()));
+ }
+ }
+
+
+ public final com.woorea.openstack.keystone.v3.model.Authentication getAuthenticationForV3(
+ CloudIdentity cloudIdentity, String tenantId) {
+ Identity identity = new Identity();
+ Password password = new Password();
+ User user = new User();
+ Domain userDomain = new Domain();
+ Scope scope = new Scope();
+ Project project = new Project();
+ Project.Domain projectDomain = new Project.Domain();
+ userDomain.setName(cloudIdentity.getUserDomainName());
+ projectDomain.setName(cloudIdentity.getProjectDomainName());
+ user.setName(cloudIdentity.getMsoId());
+ user.setPassword(CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass()));
+ user.setDomain(userDomain);
+ password.setUser(user);
+ project.setDomain(projectDomain);
+ project.setId(tenantId);
+ scope.setProject(project);
+ identity.setPassword(password);
+ identity.setMethods(Collections.singletonList("password"));
+ com.woorea.openstack.keystone.v3.model.Authentication v3Auth =
+ new com.woorea.openstack.keystone.v3.model.Authentication();
+ v3Auth.setIdentity(identity);
+ v3Auth.setScope(scope);
+ return v3Auth;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneAuthHolder.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneAuthHolder.java
index 49fd928f0f..4df8a91515 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneAuthHolder.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneAuthHolder.java
@@ -25,28 +25,33 @@ import java.util.Calendar;
public class KeystoneAuthHolder implements Serializable {
- private static final long serialVersionUID = -9073252905181739224L;
-
- private String id;
- private Calendar expiration;
- private String serviceUrl;
-
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public Calendar getexpiration() {
- return expiration;
- }
- public void setexpiration(Calendar expiration) {
- this.expiration = expiration;
- }
- public String getServiceUrl() {
- return serviceUrl;
- }
- public void setHeatUrl(String serviceUrl) {
- this.serviceUrl = serviceUrl;
- }
+ private static final long serialVersionUID = -9073252905181739224L;
+
+ private String id;
+ private Calendar expiration;
+ private String serviceUrl;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public Calendar getexpiration() {
+ return expiration;
+ }
+
+ public void setexpiration(Calendar expiration) {
+ this.expiration = expiration;
+ }
+
+ public String getServiceUrl() {
+ return serviceUrl;
+ }
+
+ public void setHeatUrl(String serviceUrl) {
+ this.serviceUrl = serviceUrl;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java
index 8fbccaaf69..f717144562 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java
@@ -25,7 +25,6 @@ import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
-
import org.onap.so.config.beans.PoConfig;
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.db.catalog.beans.CloudSite;
@@ -34,7 +33,6 @@ import org.onap.so.openstack.utils.MsoTenantUtils;
import org.onap.so.openstack.utils.MsoTenantUtilsFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.woorea.openstack.base.client.OpenStackConnectException;
import com.woorea.openstack.base.client.OpenStackRequest;
import com.woorea.openstack.base.client.OpenStackResponse;
@@ -43,7 +41,6 @@ import com.woorea.openstack.keystone.v3.Keystone;
import com.woorea.openstack.keystone.v3.model.Authentication;
import com.woorea.openstack.keystone.v3.model.Token;
import com.woorea.openstack.keystone.v3.model.Token.Service;
-
import net.jodah.failsafe.Failsafe;
import net.jodah.failsafe.RetryPolicy;
@@ -51,83 +48,83 @@ import net.jodah.failsafe.RetryPolicy;
@Component
public class KeystoneV3Authentication {
- @Autowired
+ @Autowired
private AuthenticationMethodFactory authenticationMethodFactory;
-
+
@Autowired
private MsoTenantUtilsFactory tenantUtilsFactory;
-
+
@Autowired
- private PoConfig poConfig;
-
- public KeystoneAuthHolder getToken(CloudSite cloudSite, String tenantId, String type) throws MsoException {
-
- String cloudId = cloudSite.getId();
+ private PoConfig poConfig;
+
+ public KeystoneAuthHolder getToken(CloudSite cloudSite, String tenantId, String type) throws MsoException {
+
+ String cloudId = cloudSite.getId();
String region = cloudSite.getRegionId();
- CloudIdentity cloudIdentity = cloudSite.getIdentityService();
- MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
+ CloudIdentity cloudIdentity = cloudSite.getIdentityService();
+ MsoTenantUtils tenantUtils =
+ tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
- Keystone keystoneTenantClient = new Keystone (keystoneUrl);
+ Keystone keystoneTenantClient = new Keystone(keystoneUrl);
Authentication v3Credentials = authenticationMethodFactory.getAuthenticationForV3(cloudIdentity, tenantId);
- OpenStackRequest<Token> v3Request = keystoneTenantClient.tokens ()
- .authenticate(v3Credentials);
-
- KeystoneAuthHolder holder = makeRequest(v3Request, type, region);
-
- return holder;
- }
-
- protected KeystoneAuthHolder makeRequest(OpenStackRequest<Token> v3Request, String type, String region) {
-
- OpenStackResponse response = Failsafe.with(createRetryPolicy()).get(() -> {
- return v3Request.request();
- });
- String id = response.header("X-Subject-Token");
- Token token = response.getEntity(Token.class);
- KeystoneAuthHolder result = new KeystoneAuthHolder();
- result.setId(id);
- result.setexpiration(token.getExpiresAt());
- result.setHeatUrl(findEndpointURL(token.getCatalog(), type, region, "public"));
- return result;
- }
-
- protected RetryPolicy createRetryPolicy() {
- RetryPolicy policy = new RetryPolicy();
- List<Predicate<Throwable>> result = new ArrayList<>();
- result.add(e -> {
- return e.getCause() instanceof OpenStackResponseException
- && Arrays.asList(poConfig.getRetryCodes().split(","))
- .contains(Integer.toString(((OpenStackResponseException)e).getStatus()));
- });
- result.add(e -> {
- return e.getCause() instanceof OpenStackConnectException;
- });
-
- Predicate<Throwable> pred = result.stream().reduce(Predicate::or).orElse(x -> false);
-
- policy.retryOn(error -> pred.test(error));
-
- policy.withDelay(poConfig.getRetryDelay(), TimeUnit.SECONDS)
- .withMaxRetries(poConfig.getRetryCount());
-
- return policy;
- }
-
- protected String findEndpointURL(List<Service> serviceCatalog, String type, String region, String facing) {
- for(Service service : serviceCatalog) {
- if(type.equals(service.getType())) {
- for(Service.Endpoint endpoint : service.getEndpoints()) {
- if(region == null || region.equals(endpoint.getRegion())) {
- if(facing.equals(endpoint.getInterface())) {
- return endpoint.getUrl();
- }
- }
- }
- }
- }
- throw new ServiceEndpointNotFoundException("endpoint url not found: type:" + type +" region: " + region + " facing: " + facing);
- }
+ OpenStackRequest<Token> v3Request = keystoneTenantClient.tokens().authenticate(v3Credentials);
+
+ KeystoneAuthHolder holder = makeRequest(v3Request, type, region);
+
+ return holder;
+ }
+
+ protected KeystoneAuthHolder makeRequest(OpenStackRequest<Token> v3Request, String type, String region) {
+
+ OpenStackResponse response = Failsafe.with(createRetryPolicy()).get(() -> {
+ return v3Request.request();
+ });
+ String id = response.header("X-Subject-Token");
+ Token token = response.getEntity(Token.class);
+ KeystoneAuthHolder result = new KeystoneAuthHolder();
+ result.setId(id);
+ result.setexpiration(token.getExpiresAt());
+ result.setHeatUrl(findEndpointURL(token.getCatalog(), type, region, "public"));
+ return result;
+ }
+
+ protected RetryPolicy createRetryPolicy() {
+ RetryPolicy policy = new RetryPolicy();
+ List<Predicate<Throwable>> result = new ArrayList<>();
+ result.add(e -> {
+ return e.getCause() instanceof OpenStackResponseException
+ && Arrays.asList(poConfig.getRetryCodes().split(","))
+ .contains(Integer.toString(((OpenStackResponseException) e).getStatus()));
+ });
+ result.add(e -> {
+ return e.getCause() instanceof OpenStackConnectException;
+ });
+
+ Predicate<Throwable> pred = result.stream().reduce(Predicate::or).orElse(x -> false);
+
+ policy.retryOn(error -> pred.test(error));
+
+ policy.withDelay(poConfig.getRetryDelay(), TimeUnit.SECONDS).withMaxRetries(poConfig.getRetryCount());
+
+ return policy;
+ }
+
+ protected String findEndpointURL(List<Service> serviceCatalog, String type, String region, String facing) {
+ for (Service service : serviceCatalog) {
+ if (type.equals(service.getType())) {
+ for (Service.Endpoint endpoint : service.getEndpoints()) {
+ if (region == null || region.equals(endpoint.getRegion())) {
+ if (facing.equals(endpoint.getInterface())) {
+ return endpoint.getUrl();
+ }
+ }
+ }
+ }
+ }
+ throw new ServiceEndpointNotFoundException(
+ "endpoint url not found: type:" + type + " region: " + region + " facing: " + facing);
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/ServiceEndpointNotFoundException.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/ServiceEndpointNotFoundException.java
index d95737d927..96a947804a 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/ServiceEndpointNotFoundException.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/ServiceEndpointNotFoundException.java
@@ -22,9 +22,9 @@ package org.onap.so.cloud.authentication;
public class ServiceEndpointNotFoundException extends RuntimeException {
- private static final long serialVersionUID = -5347215451284361397L;
+ private static final long serialVersionUID = -5347215451284361397L;
- public ServiceEndpointNotFoundException(String message) {
- super(message);
- }
+ public ServiceEndpointNotFoundException(String message) {
+ super(message);
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/models/RackspaceAuthentication.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/models/RackspaceAuthentication.java
index 009c9a4c6c..f8fa78ccfc 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/models/RackspaceAuthentication.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/models/RackspaceAuthentication.java
@@ -21,7 +21,6 @@
package org.onap.so.cloud.authentication.models;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -29,74 +28,77 @@ import com.woorea.openstack.keystone.model.Authentication;
@JsonRootName("auth")
public class RackspaceAuthentication extends Authentication {
-
- /**
- *
- */
- private static final long serialVersionUID = 5451283386875662918L;
-
- @JsonIgnore
- private String tenantId;
-
- @JsonIgnore
- private String tenantName;
-
- public static final class Token implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = -4448875265818207908L;
- private String username;
- private String apiKey;
-
- /**
- * @return the username
- */
- public String getUsername() {
- return username;
- }
- /**
- * @param username the username to set
- */
- public void setUsername(String username) {
- this.username = username;
- }
- /**
- * @return the apiKey
- */
- public String getApiKey() {
- return apiKey;
- }
- /**
- * @param apiKey the apiKey to set
- */
- public void setApiKey(String apiKey) {
- this.apiKey = apiKey;
- }
- }
-
- @JsonProperty("RAX-KSKEY:apiKeyCredentials")
- private Token token = new Token();
-
- public RackspaceAuthentication (String username, String apiKey) {
- this.token.username = username;
- this.token.apiKey = apiKey;
-
- }
-
- /**
- * @return the token
- */
- public Token getToken() {
- return token;
- }
-
- /**
- * @param token the token to set
- */
- public void setToken(Token token) {
- this.token = token;
- }
-
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 5451283386875662918L;
+
+ @JsonIgnore
+ private String tenantId;
+
+ @JsonIgnore
+ private String tenantName;
+
+ public static final class Token implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -4448875265818207908L;
+ private String username;
+ private String apiKey;
+
+ /**
+ * @return the username
+ */
+ public String getUsername() {
+ return username;
+ }
+
+ /**
+ * @param username the username to set
+ */
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ /**
+ * @return the apiKey
+ */
+ public String getApiKey() {
+ return apiKey;
+ }
+
+ /**
+ * @param apiKey the apiKey to set
+ */
+ public void setApiKey(String apiKey) {
+ this.apiKey = apiKey;
+ }
+ }
+
+ @JsonProperty("RAX-KSKEY:apiKeyCredentials")
+ private Token token = new Token();
+
+ public RackspaceAuthentication(String username, String apiKey) {
+ this.token.username = username;
+ this.token.apiKey = apiKey;
+
+ }
+
+ /**
+ * @return the token
+ */
+ public Token getToken() {
+ return token;
+ }
+
+ /**
+ * @param token the token to set
+ */
+ public void setToken(Token token) {
+ this.token = token;
+ }
+
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfo.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfo.java
index d2b3334c8c..42b77baeeb 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfo.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfo.java
@@ -40,12 +40,8 @@ public final class DeploymentInfo {
private final String actionStatus;
private final String errorMessage;
- DeploymentInfo(String id, DeploymentStatus deploymentStatus,
- Map<String, Object> deploymentOutputs,
- Map<String, Object> deploymentInputs,
- String lastAction,
- String actionStatus,
- String errorMessage) {
+ DeploymentInfo(String id, DeploymentStatus deploymentStatus, Map<String, Object> deploymentOutputs,
+ Map<String, Object> deploymentInputs, String lastAction, String actionStatus, String errorMessage) {
this.id = id;
this.status = deploymentStatus;
@@ -86,14 +82,9 @@ public final class DeploymentInfo {
@Override
public String toString() {
- return "DeploymentInfo {" +
- "id='" + id + '\'' +
- ", inputs='" + inputs + '\'' +
- ", outputs='" + outputs + '\'' +
- ", lastAction='" + lastAction + '\'' +
- ", status='" + status + '\'' +
- ", errorMessage='" + errorMessage + '\'' +
- '}';
+ return "DeploymentInfo {" + "id='" + id + '\'' + ", inputs='" + inputs + '\'' + ", outputs='" + outputs + '\''
+ + ", lastAction='" + lastAction + '\'' + ", status='" + status + '\'' + ", errorMessage='"
+ + errorMessage + '\'' + '}';
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java
index 3b945ae484..02ace5665d 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 Nokia.
- * =============================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 Nokia.
+ * ============================================================================= Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.so.cloudify.beans;
@@ -109,12 +104,7 @@ public final class DeploymentInfoBuilder {
}
public DeploymentInfo build() {
- return new DeploymentInfo(id,
- deploymentStatus,
- deploymentOutputs,
- deploymentInputs,
- lastAction,
- actionStatus,
- errorMessage);
+ return new DeploymentInfo(id, deploymentStatus, deploymentOutputs, deploymentInputs, lastAction, actionStatus,
+ errorMessage);
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentStatus.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentStatus.java
index 5aa47e9d6b..f7d6a9d214 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentStatus.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentStatus.java
@@ -22,10 +22,10 @@ package org.onap.so.cloudify.beans;
/*
- * Enum status values to capture the state of a deployment, based on last known workflow
- * (assume only INSTALL and UNINSTALL at this point).
+ * Enum status values to capture the state of a deployment, based on last known workflow (assume only INSTALL and
+ * UNINSTALL at this point).
*/
public enum DeploymentStatus {
- NOTFOUND, CREATED, INSTALLED, FAILED, INSTALLING, UNINSTALLING, UNKNOWN
+ NOTFOUND, CREATED, INSTALLED, FAILED, INSTALLING, UNINSTALLING, UNKNOWN
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoBlueprintAlreadyExists.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoBlueprintAlreadyExists.java
index d5d5684b0f..95912994bc 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoBlueprintAlreadyExists.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoBlueprintAlreadyExists.java
@@ -22,12 +22,13 @@ package org.onap.so.cloudify.exceptions;
public class MsoBlueprintAlreadyExists extends MsoCloudifyException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ // Constructor to create a new MsoCloudifyException instance
+ public MsoBlueprintAlreadyExists(String blueprintId, String cloud) {
+ // Set the detailed error as the Exception 'message'
+ super(409, "Conflict",
+ "Blueprint " + blueprintId + " already exists in Cloudify Manager supporting cloud site + " + cloud);
+ }
- // Constructor to create a new MsoCloudifyException instance
- public MsoBlueprintAlreadyExists (String blueprintId, String cloud) {
- // Set the detailed error as the Exception 'message'
- super(409, "Conflict", "Blueprint " + blueprintId + " already exists in Cloudify Manager supporting cloud site + " + cloud);
- }
-
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyException.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyException.java
index 992df5fd6a..441bd4dc07 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyException.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyException.java
@@ -26,61 +26,63 @@ import org.onap.so.openstack.exceptions.MsoExceptionCategory;
/**
* OpenStack exception.
*/
-public class MsoCloudifyException extends MsoException
-{
-
- /**
+public class MsoCloudifyException extends MsoException {
+
+ /**
* Serialization id.
*/
private static final long serialVersionUID = 3313636124141766495L;
-
+
private int statusCode;
- private String statusMessage;
- private String errorDetail;
- private boolean pendingWorkflow;
+ private String statusMessage;
+ private String errorDetail;
+ private boolean pendingWorkflow;
+
+ /**
+ * Constructor to create a new MsoOpenstackException instance
+ *
+ * @param code the error code
+ * @param message the error message
+ * @param detail error details
+ */
+ public MsoCloudifyException(int code, String message, String detail) {
+ // Set the detailed error as the Exception 'message'
+ super(detail);
+ super.category = MsoExceptionCategory.OPENSTACK;
+
+ this.statusCode = code;
+ this.statusMessage = message;
+ this.errorDetail = detail;
+ this.pendingWorkflow = false;
+ }
- /**
- * Constructor to create a new MsoOpenstackException instance
- * @param code the error code
- * @param message the error message
- * @param detail error details
- */
- public MsoCloudifyException (int code, String message, String detail) {
- // Set the detailed error as the Exception 'message'
- super(detail);
- super.category = MsoExceptionCategory.OPENSTACK;
-
- this.statusCode = code;
- this.statusMessage = message;
- this.errorDetail = detail;
- this.pendingWorkflow = false;
- }
-
- /**
- * Constructor to propagate the caught exception (mostly for stack trace)
+ /**
+ * Constructor to propagate the caught exception (mostly for stack trace)
+ *
* @param code the error code
* @param message the error message
* @param detail error details
- * @param e the cause
- */
- public MsoCloudifyException (int code, String message, String detail, Exception e) {
- // Set the detailed error as the Exception 'message'
- super(detail, e);
- super.category = MsoExceptionCategory.OPENSTACK;
-
- this.statusCode = code;
- this.statusMessage = message;
- this.errorDetail = detail;
- this.pendingWorkflow = false;
- }
-
- public void setPendingWorkflow (boolean pendingWorkflow) {
- this.pendingWorkflow = pendingWorkflow;
- }
-
- @Override
- public String toString () {
- String error = "" + statusCode + " " + statusMessage + ": " + errorDetail + (pendingWorkflow ? " [workflow pending]" : "");
- return error;
- }
+ * @param e the cause
+ */
+ public MsoCloudifyException(int code, String message, String detail, Exception e) {
+ // Set the detailed error as the Exception 'message'
+ super(detail, e);
+ super.category = MsoExceptionCategory.OPENSTACK;
+
+ this.statusCode = code;
+ this.statusMessage = message;
+ this.errorDetail = detail;
+ this.pendingWorkflow = false;
+ }
+
+ public void setPendingWorkflow(boolean pendingWorkflow) {
+ this.pendingWorkflow = pendingWorkflow;
+ }
+
+ @Override
+ public String toString() {
+ String error = "" + statusCode + " " + statusMessage + ": " + errorDetail
+ + (pendingWorkflow ? " [workflow pending]" : "");
+ return error;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyManagerNotFound.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyManagerNotFound.java
index 0c795478cd..bc6fd6204c 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyManagerNotFound.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyManagerNotFound.java
@@ -22,12 +22,12 @@ package org.onap.so.cloudify.exceptions;
public class MsoCloudifyManagerNotFound extends MsoCloudifyException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ // Constructor to create a new MsoCloudifyException instance
+ public MsoCloudifyManagerNotFound(String cloudSiteId) {
+ // Set the detailed error as the Exception 'message'
+ super(0, "Cloudify Manager Not Found", "No Cloudify Manager configured for cloud site " + cloudSiteId);
+ }
- // Constructor to create a new MsoCloudifyException instance
- public MsoCloudifyManagerNotFound (String cloudSiteId) {
- // Set the detailed error as the Exception 'message'
- super(0, "Cloudify Manager Not Found", "No Cloudify Manager configured for cloud site " + cloudSiteId);
- }
-
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeout.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeout.java
index 7dcd69d0a4..99b6ade326 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeout.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeout.java
@@ -25,40 +25,42 @@ import org.onap.so.openstack.exceptions.MsoException;
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
/**
- * MSO Exception when a Cloudify workflow execution times out waiting for completion.
- * Exception includes the last known state of the workflow execution.
+ * MSO Exception when a Cloudify workflow execution times out waiting for completion. Exception includes the last known
+ * state of the workflow execution.
*/
-public class MsoCloudifyTimeout extends MsoException
-{
-
- /**
+public class MsoCloudifyTimeout extends MsoException {
+
+ /**
* Serialization id.
*/
private static final long serialVersionUID = 3313636124141766495L;
-
- private Execution execution;
- /**
- * Constructor to create a new MsoOpenstackException instance
- * @param code the error code
- * @param message the error message
- * @param detail error details
- */
- public MsoCloudifyTimeout (Execution execution) {
- // Set the detailed error as the Exception 'message'
- super("Cloudify Workflow Timeout for workflow " + execution.getWorkflowId() + " on deployment " + execution.getDeploymentId());
- super.category = MsoExceptionCategory.OPENSTACK;
-
- this.execution = execution;
- }
-
- public Execution getExecution() {
- return this.execution;
- }
-
- @Override
- public String toString () {
- String error = "Workflow timeout: workflow=" + execution.getWorkflowId() + ",deployment=" + execution.getDeploymentId();
- return error;
- }
+ private Execution execution;
+
+ /**
+ * Constructor to create a new MsoOpenstackException instance
+ *
+ * @param code the error code
+ * @param message the error message
+ * @param detail error details
+ */
+ public MsoCloudifyTimeout(Execution execution) {
+ // Set the detailed error as the Exception 'message'
+ super("Cloudify Workflow Timeout for workflow " + execution.getWorkflowId() + " on deployment "
+ + execution.getDeploymentId());
+ super.category = MsoExceptionCategory.OPENSTACK;
+
+ this.execution = execution;
+ }
+
+ public Execution getExecution() {
+ return this.execution;
+ }
+
+ @Override
+ public String toString() {
+ String error = "Workflow timeout: workflow=" + execution.getWorkflowId() + ",deployment="
+ + execution.getDeploymentId();
+ return error;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java
index a84da50dc4..5c2348dffa 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java
@@ -22,33 +22,33 @@ package org.onap.so.cloudify.exceptions;
/**
* Reports an error with a Cloudify Workflow execution.
+ *
* @author JC1348
*
*/
public class MsoCloudifyWorkflowException extends MsoCloudifyException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ private String workflowStatus;
+ private boolean workflowStillRunning = false;
+
+ // Constructor to create a new MsoCloudifyException instance
+ public MsoCloudifyWorkflowException(String message, String deploymentId, String workflowId, String workflowStatus) {
+ super(0, "Workflow Exception",
+ "Workflow " + workflowId + " failed on deployment " + deploymentId + ": " + message);
+ this.workflowStatus = workflowStatus;
+ if (workflowStatus.equals("pending") || workflowStatus.equals("started") || workflowStatus.equals("cancelling")
+ || workflowStatus.equals("force_cancelling")) {
+ workflowStillRunning = true;
+ }
+ }
+
+ public String getWorkflowStatus() {
+ return workflowStatus;
+ }
- private String workflowStatus;
- private boolean workflowStillRunning = false;
-
- // Constructor to create a new MsoCloudifyException instance
- public MsoCloudifyWorkflowException (String message, String deploymentId, String workflowId, String workflowStatus)
- {
- super(0, "Workflow Exception", "Workflow " + workflowId + " failed on deployment " + deploymentId + ": " + message);
- this.workflowStatus = workflowStatus;
- if (workflowStatus.equals("pending") || workflowStatus.equals("started") ||
- workflowStatus.equals("cancelling") || workflowStatus.equals("force_cancelling"))
- {
- workflowStillRunning = true;
- }
- }
-
- public String getWorkflowStatus() {
- return workflowStatus;
- }
-
- public boolean isWorkflowStillRunning () {
- return workflowStillRunning;
- }
+ public boolean isWorkflowStillRunning() {
+ return workflowStillRunning;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoDeploymentAlreadyExists.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoDeploymentAlreadyExists.java
index 4f5685efb3..62112f4feb 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoDeploymentAlreadyExists.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoDeploymentAlreadyExists.java
@@ -22,12 +22,13 @@ package org.onap.so.cloudify.exceptions;
public class MsoDeploymentAlreadyExists extends MsoCloudifyException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ // Constructor to create a new MsoCloudifyException instance
+ public MsoDeploymentAlreadyExists(String deploymentId, String cloud) {
+ // Set the detailed error as the Exception 'message'
+ super(409, "Conflict",
+ "Deployment " + deploymentId + " already exists in Cloudify Manager suppporting cloud " + cloud);
+ }
- // Constructor to create a new MsoCloudifyException instance
- public MsoDeploymentAlreadyExists (String deploymentId, String cloud) {
- // Set the detailed error as the Exception 'message'
- super(409, "Conflict", "Deployment " + deploymentId + " already exists in Cloudify Manager suppporting cloud " + cloud);
- }
-
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java
index 6b16194471..0a0f2787da 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java
@@ -102,7 +102,7 @@ import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
-public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
+public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin {
private static final String CLOUDIFY = "Cloudify";
private static final String CREATE_DEPLOYMENT = "CreateDeployment";
@@ -132,24 +132,21 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
/**
- * Create a new Deployment from a specified blueprint, and install it in the specified
- * cloud location and tenant. The blueprint identifier and parameter map are passed in
- * as arguments, along with the cloud access credentials. The blueprint should have been
- * previously uploaded to Cloudify.
+ * Create a new Deployment from a specified blueprint, and install it in the specified cloud location and tenant.
+ * The blueprint identifier and parameter map are passed in as arguments, along with the cloud access credentials.
+ * The blueprint should have been previously uploaded to Cloudify.
*
- * It is expected that parameters have been validated and contain at minimum the required
- * parameters for the given template with no extra (undefined) parameters..
+ * It is expected that parameters have been validated and contain at minimum the required parameters for the given
+ * template with no extra (undefined) parameters..
*
- * The deployment ID supplied by the caller must be unique in the scope of the Cloudify
- * tenant (not the Openstack tenant). However, it should also be globally unique, as it
- * will be the identifier for the resource going forward in Inventory. This latter is
- * managed by the higher levels invoking this function.
+ * The deployment ID supplied by the caller must be unique in the scope of the Cloudify tenant (not the Openstack
+ * tenant). However, it should also be globally unique, as it will be the identifier for the resource going forward
+ * in Inventory. This latter is managed by the higher levels invoking this function.
*
- * This function executes the "install" workflow on the newly created workflow. Cloudify
- * will be polled for completion unless the client requests otherwise.
+ * This function executes the "install" workflow on the newly created workflow. Cloudify will be polled for
+ * completion unless the client requests otherwise.
*
- * An error will be thrown if the requested Deployment already exists in the specified
- * Cloudify instance.
+ * An error will be thrown if the requested Deployment already exists in the specified Cloudify instance.
*
* @param cloudSiteId The cloud (may be a region) in which to create the stack.
* @param tenantId The Openstack ID of the tenant in which to create the Stack
@@ -164,22 +161,16 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
* @throws MsoIOException Thrown on Cloudify connection errors.
*/
- public DeploymentInfo createAndInstallDeployment (String cloudSiteId,
- String tenantId,
- String deploymentId,
- String blueprintId,
- Map <String, ? extends Object> inputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- boolean backout) throws MsoException
- {
+ public DeploymentInfo createAndInstallDeployment(String cloudSiteId, String tenantId, String deploymentId,
+ String blueprintId, Map<String, ? extends Object> inputs, boolean pollForCompletion, int timeoutMinutes,
+ boolean backout) throws MsoException {
// Obtain the cloud site information where we will create the stack
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSite.isPresent()) {
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- Cloudify cloudify = getCloudifyClient (cloudSite.get());
+ Cloudify cloudify = getCloudifyClient(cloudSite.get());
logger.debug("Ready to Create Deployment ({}) with input params: {}", deploymentId, inputs);
@@ -187,159 +178,150 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
// - from provided "environment" file
// - passed in by caller
// - special input for cloud-specific Credentials
- Map<String,Object> expandedInputs = new HashMap<> (inputs);
+ Map<String, Object> expandedInputs = new HashMap<>(inputs);
String platform = cloudSite.get().getPlatform();
if (platform == null || platform.equals("") || platform.equalsIgnoreCase("OPENSTACK")) {
- // Create the Cloudify OpenstackConfig with the credentials
- OpenstackConfig openstackConfig = getOpenstackConfig (cloudSite.get(), tenantId);
- expandedInputs.put("openstack_config", openstackConfig);
+ // Create the Cloudify OpenstackConfig with the credentials
+ OpenstackConfig openstackConfig = getOpenstackConfig(cloudSite.get(), tenantId);
+ expandedInputs.put("openstack_config", openstackConfig);
} else if (platform.equalsIgnoreCase("AZURE")) {
- // Create Cloudify AzureConfig with the credentials
- AzureConfig azureConfig = getAzureConfig (cloudSite.get(), tenantId);
- expandedInputs.put("azure_config", azureConfig);
+ // Create Cloudify AzureConfig with the credentials
+ AzureConfig azureConfig = getAzureConfig(cloudSite.get(), tenantId);
+ expandedInputs.put("azure_config", azureConfig);
}
// Build up the parameters to create a new deployment
- CreateDeploymentParams deploymentParams = new CreateDeploymentParams();
- deploymentParams.setBlueprintId(blueprintId);
- deploymentParams.setInputs(expandedInputs);
-
- Deployment deployment = null;
- try {
- CreateDeployment createDeploymentRequest = cloudify.deployments().create(deploymentId, deploymentParams);
- logger.debug(createDeploymentRequest.toString());
-
- deployment = executeAndRecordCloudifyRequest (createDeploymentRequest);
- }
- catch (CloudifyResponseException e) {
+ CreateDeploymentParams deploymentParams = new CreateDeploymentParams();
+ deploymentParams.setBlueprintId(blueprintId);
+ deploymentParams.setInputs(expandedInputs);
+
+ Deployment deployment = null;
+ try {
+ CreateDeployment createDeploymentRequest = cloudify.deployments().create(deploymentId, deploymentParams);
+ logger.debug(createDeploymentRequest.toString());
+
+ deployment = executeAndRecordCloudifyRequest(createDeploymentRequest);
+ } catch (CloudifyResponseException e) {
// Since this came on the 'Create Deployment' command, nothing was changed
// in the cloud. Return the error as an exception.
- if (e.getStatus () == 409) {
+ if (e.getStatus() == 409) {
// Deployment already exists. Return a specific error for this case
- MsoException me = new MsoDeploymentAlreadyExists (deploymentId, cloudSiteId);
- me.addContext (CREATE_DEPLOYMENT);
+ MsoException me = new MsoDeploymentAlreadyExists(deploymentId, cloudSiteId);
+ me.addContext(CREATE_DEPLOYMENT);
throw me;
} else {
// Convert the CloudifyResponseException to an MsoException
logger.debug("ERROR STATUS = {},\n{}\n{}", e.getStatus(), e.getMessage(), e.getLocalizedMessage());
- MsoException me = cloudifyExceptionToMsoException (e, CREATE_DEPLOYMENT);
- me.setCategory (MsoExceptionCategory.OPENSTACK);
+ MsoException me = cloudifyExceptionToMsoException(e, CREATE_DEPLOYMENT);
+ me.setCategory(MsoExceptionCategory.OPENSTACK);
throw me;
}
} catch (CloudifyConnectException e) {
// Error connecting to Cloudify instance. Convert to an MsoException
- throw cloudifyExceptionToMsoException (e, CREATE_DEPLOYMENT);
+ throw cloudifyExceptionToMsoException(e, CREATE_DEPLOYMENT);
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, CREATE_DEPLOYMENT);
+ throw runtimeExceptionToMsoException(e, CREATE_DEPLOYMENT);
}
- /*
- * It can take some time for Cloudify to be ready to execute a workflow
- * on the deployment. Sleep 30 seconds based on observation of behavior
- * in a Cloudify VM instance (delay due to "create_deployment_environment").
- */
- sleep(30000);
-
- /*
- * Next execute the "install" workflow.
- * Note - this assumes there are no additional parameters required for the workflow.
- */
- int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
+ /*
+ * It can take some time for Cloudify to be ready to execute a workflow on the deployment. Sleep 30 seconds
+ * based on observation of behavior in a Cloudify VM instance (delay due to "create_deployment_environment").
+ */
+ sleep(30000);
+
+ /*
+ * Next execute the "install" workflow. Note - this assumes there are no additional parameters required for the
+ * workflow.
+ */
+ int createPollInterval =
+ Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
Execution installWorkflow = null;
try {
- installWorkflow = executeWorkflow (cloudify, deploymentId, "install", null, pollForCompletion, pollTimeout, createPollInterval);
-
- if (installWorkflow.getStatus().equals(TERMINATED)) {
- // Success!
- // Create and return a DeploymentInfo structure. Include the Runtime outputs
- return new DeploymentInfoBuilder()
- .withId(deployment.getId())
- .withDeploymentInputs(deployment.getInputs())
- .withDeploymentOutputs(getDeploymentOutputs(cloudify, deploymentId).get())
- .fromExecution(installWorkflow)
- .build();
- }
- else {
- // The workflow completed with errors. Must try to back it out.
- if (!backout)
- {
- logger.warn("{} Deployment installation failed, backout deletion suppressed {} {}",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
- "Exception in Deployment Installation, backout suppressed");
- }
- else {
- // Poll on delete if we rollback - use same values for now
- int deletePollInterval = createPollInterval;
- int deletePollTimeout = pollTimeout;
-
- try {
- // Run the uninstall to undo the install
- Execution uninstallWorkflow = executeWorkflow (cloudify, deploymentId, "uninstall", null, pollForCompletion, deletePollTimeout, deletePollInterval);
-
- if (uninstallWorkflow.getStatus().equals(TERMINATED))
- {
- // The uninstall completed. Delete the deployment itself
- DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId);
- executeAndRecordCloudifyRequest (deleteRequest);
- }
- else {
- // Didn't uninstall successfully. Log this error
- logger.error("{} Create Deployment: Cloudify error rolling back deployment install: {} {}",
- MessageEnum.RA_CREATE_STACK_ERR, installWorkflow.getError(),
- ErrorCode.BusinessProcesssError.getValue());
+ installWorkflow = executeWorkflow(cloudify, deploymentId, "install", null, pollForCompletion, pollTimeout,
+ createPollInterval);
+
+ if (installWorkflow.getStatus().equals(TERMINATED)) {
+ // Success!
+ // Create and return a DeploymentInfo structure. Include the Runtime outputs
+ return new DeploymentInfoBuilder().withId(deployment.getId())
+ .withDeploymentInputs(deployment.getInputs())
+ .withDeploymentOutputs(getDeploymentOutputs(cloudify, deploymentId).get())
+ .fromExecution(installWorkflow).build();
+ } else {
+ // The workflow completed with errors. Must try to back it out.
+ if (!backout) {
+ logger.warn("{} Deployment installation failed, backout deletion suppressed {} {}",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
+ "Exception in Deployment Installation, backout suppressed");
+ } else {
+ // Poll on delete if we rollback - use same values for now
+ int deletePollInterval = createPollInterval;
+ int deletePollTimeout = pollTimeout;
+
+ try {
+ // Run the uninstall to undo the install
+ Execution uninstallWorkflow = executeWorkflow(cloudify, deploymentId, "uninstall", null,
+ pollForCompletion, deletePollTimeout, deletePollInterval);
+
+ if (uninstallWorkflow.getStatus().equals(TERMINATED)) {
+ // The uninstall completed. Delete the deployment itself
+ DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId);
+ executeAndRecordCloudifyRequest(deleteRequest);
+ } else {
+ // Didn't uninstall successfully. Log this error
+ logger.error("{} Create Deployment: Cloudify error rolling back deployment install: {} {}",
+ MessageEnum.RA_CREATE_STACK_ERR, installWorkflow.getError(),
+ ErrorCode.BusinessProcesssError.getValue());
+ }
+ } catch (Exception e) {
+ // Catch-all for backout errors trying to uninstall/delete
+ // Log this error, and return the original exception
+ logger.error("{} Create Stack: Nested exception rolling back deployment install: {}",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e);
}
- }
- catch (Exception e) {
- // Catch-all for backout errors trying to uninstall/delete
- // Log this error, and return the original exception
- logger.error("{} Create Stack: Nested exception rolling back deployment install: {}",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e);
- }
- }
-
- MsoCloudifyException me = new MsoCloudifyException (0, "Workflow Execution Failed", installWorkflow.getError());
- me.addContext (CREATE_DEPLOYMENT);
+ }
+
+ MsoCloudifyException me =
+ new MsoCloudifyException(0, "Workflow Execution Failed", installWorkflow.getError());
+ me.addContext(CREATE_DEPLOYMENT);
throw me;
- }
- }
- catch (MsoException me) {
- // Install failed. Unless requested otherwise, back out the deployment
-
- if (!backout)
- {
- logger.warn("{} Deployment installation failed, backout deletion suppressed {}",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
- }
- else {
- // Poll on delete if we rollback - use same values for now
- int deletePollInterval = createPollInterval;
- int deletePollTimeout = pollTimeout;
-
- try {
- // Run the uninstall to undo the install.
- // Always try to run it, as it should be idempotent
- executeWorkflow (cloudify, deploymentId, "uninstall", null, pollForCompletion, deletePollTimeout, deletePollInterval);
-
- // Delete the deployment itself
- DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId);
- executeAndRecordCloudifyRequest (deleteRequest);
- }
- catch (Exception e) {
- // Catch-all for backout errors trying to uninstall/delete
- // Log this error, and return the original exception
- logger.error("{} Create Stack: Nested exception rolling back deployment install: {} ",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e);
- }
- }
+ }
+ } catch (MsoException me) {
+ // Install failed. Unless requested otherwise, back out the deployment
+
+ if (!backout) {
+ logger.warn("{} Deployment installation failed, backout deletion suppressed {}",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
+ } else {
+ // Poll on delete if we rollback - use same values for now
+ int deletePollInterval = createPollInterval;
+ int deletePollTimeout = pollTimeout;
+
+ try {
+ // Run the uninstall to undo the install.
+ // Always try to run it, as it should be idempotent
+ executeWorkflow(cloudify, deploymentId, "uninstall", null, pollForCompletion, deletePollTimeout,
+ deletePollInterval);
+
+ // Delete the deployment itself
+ DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId);
+ executeAndRecordCloudifyRequest(deleteRequest);
+ } catch (Exception e) {
+ // Catch-all for backout errors trying to uninstall/delete
+ // Log this error, and return the original exception
+ logger.error("{} Create Stack: Nested exception rolling back deployment install: {} ",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e);
+ }
+ }
// Propagate the original exception from Stack Query.
- me.addContext (CREATE_DEPLOYMENT);
+ me.addContext(CREATE_DEPLOYMENT);
throw me;
}
@@ -347,302 +329,275 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
/*
- * Get the runtime Outputs of a deployment.
- * Return the Map of tag/value outputs.
+ * Get the runtime Outputs of a deployment. Return the Map of tag/value outputs.
*/
- private Optional<Map<String, Object>> getDeploymentOutputs (Cloudify cloudify, String deploymentId)
- throws MsoException
- {
- // Build and send the Cloudify request
- DeploymentOutputs deploymentOutputs;
- try {
- GetDeploymentOutputs queryDeploymentOutputs = cloudify.deployments().outputsById(deploymentId);
- logger.debug(queryDeploymentOutputs.toString());
-
- deploymentOutputs = executeAndRecordCloudifyRequest(queryDeploymentOutputs);
- if (deploymentOutputs != null) {
- return Optional.ofNullable(deploymentOutputs.getOutputs());
- } else {
- return Optional.empty();
- }
- }
- catch (CloudifyConnectException ce) {
- // Couldn't connect to Cloudify
- logger.error("{} QueryDeploymentOutputs: Cloudify connection failure: {} ",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), ce);
- throw new MsoIOException (ce.getMessage(), ce);
- }
- catch (CloudifyResponseException re) {
- if (re.getStatus () == 404) {
- // No Outputs
- return Optional.empty();
+ private Optional<Map<String, Object>> getDeploymentOutputs(Cloudify cloudify, String deploymentId)
+ throws MsoException {
+ // Build and send the Cloudify request
+ DeploymentOutputs deploymentOutputs;
+ try {
+ GetDeploymentOutputs queryDeploymentOutputs = cloudify.deployments().outputsById(deploymentId);
+ logger.debug(queryDeploymentOutputs.toString());
+
+ deploymentOutputs = executeAndRecordCloudifyRequest(queryDeploymentOutputs);
+ if (deploymentOutputs != null) {
+ return Optional.ofNullable(deploymentOutputs.getOutputs());
+ } else {
+ return Optional.empty();
+ }
+ } catch (CloudifyConnectException ce) {
+ // Couldn't connect to Cloudify
+ logger.error("{} QueryDeploymentOutputs: Cloudify connection failure: {} ", MessageEnum.RA_CREATE_STACK_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), ce);
+ throw new MsoIOException(ce.getMessage(), ce);
+ } catch (CloudifyResponseException re) {
+ if (re.getStatus() == 404) {
+ // No Outputs
+ return Optional.empty();
}
- throw new MsoCloudifyException (re.getStatus(), re.getMessage(), re.getLocalizedMessage(), re);
- }
- catch (Exception e) {
- // Catch-all
- throw new MsoAdapterException (e.getMessage(), e);
- }
+ throw new MsoCloudifyException(re.getStatus(), re.getMessage(), re.getLocalizedMessage(), re);
+ } catch (Exception e) {
+ // Catch-all
+ throw new MsoAdapterException(e.getMessage(), e);
+ }
}
/*
- * Execute a workflow on a deployment. Handle polling for completion with timeout.
- * Return the final Execution object with status.
- * Throw an exception on Errors.
- * Question - how does the client know whether rollback needs to be done?
+ * Execute a workflow on a deployment. Handle polling for completion with timeout. Return the final Execution object
+ * with status. Throw an exception on Errors. Question - how does the client know whether rollback needs to be done?
*/
- private Execution executeWorkflow (Cloudify cloudify, String deploymentId, String workflowId, Map<String,Object> workflowParams, boolean pollForCompletion, int timeout, int pollInterval)
- throws MsoCloudifyException
- {
+ private Execution executeWorkflow(Cloudify cloudify, String deploymentId, String workflowId,
+ Map<String, Object> workflowParams, boolean pollForCompletion, int timeout, int pollInterval)
+ throws MsoCloudifyException {
logger.debug("Executing '{}' workflow on deployment '{}'", workflowId, deploymentId);
- StartExecutionParams executeParams = new StartExecutionParams();
- executeParams.setWorkflowId(workflowId);
- executeParams.setDeploymentId(deploymentId);
- executeParams.setParameters(workflowParams);
-
- Execution execution = null;
- String executionId = null;
- String command = "start";
- Exception savedException = null;
-
- try {
- StartExecution executionRequest = cloudify.executions().start(executeParams);
- logger.debug(executionRequest.toString());
- execution = executeAndRecordCloudifyRequest (executionRequest);
- executionId = execution.getId();
-
- if (!pollForCompletion) {
- // Client did not request polling, so just return the Execution object
- return execution;
- }
-
- // Enter polling loop
- boolean timedOut = false;
- int pollTimeout = timeout;
-
- String status = execution.getStatus();
-
- // Create a reusable cloudify query request
- GetExecution queryExecution = cloudify.executions().byId(executionId);
- command = "query";
-
- while (!timedOut && !(status.equals(TERMINATED) || status.equals("failed") || status.equals(CANCELLED)))
- {
- // workflow is still running; check for timeout
- if (pollTimeout <= 0) {
- logger.debug("workflow {} timed out on deployment {}", execution.getWorkflowId(),
- execution.getDeploymentId());
- timedOut = true;
- continue;
- }
-
- sleep(pollInterval * 1000L);
-
- pollTimeout -= pollInterval;
- logger.debug("pollTimeout remaining: " + pollTimeout);
-
- execution = queryExecution.execute();
- status = execution.getStatus();
- }
-
- // Broke the loop. Check again for a terminal state
- if (status.equals(TERMINATED)){
- // Success!
- logger.debug("Workflow '{}' completed successfully on deployment '{}'", workflowId, deploymentId);
- return execution;
- }
- else if (status.equals("failed")){
- // Workflow failed. Log it and return the execution object (don't throw exception here)
- logger.error("{} Cloudify workflow failure: {} {} Execute Workflow: Failed: {}",
- MessageEnum.RA_CREATE_STACK_ERR, execution.getError(),
- ErrorCode.BusinessProcesssError.getValue(), execution.getError());
- return execution;
- }
- else if (status.equals(CANCELLED)){
- // Workflow was cancelled, leaving the deployment in an indeterminate state. Log it and return the execution object (don't throw exception here)
- logger.error("{} Cloudify workflow cancelled. Deployment is in an indeterminate state {} {} {}",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
- "Execute Workflow cancelled: ", workflowId);
- return execution;
- }
- else {
- // Can only get here after a timeout
- logger.error("{} Cloudify workflow timeout {} Execute Workflow: Timed Out", MessageEnum.RA_CREATE_STACK_ERR,
- ErrorCode.BusinessProcesssError.getValue());
- }
- }
- catch (CloudifyConnectException ce) {
- logger.error("{} {} Execute Workflow ({} {}): Cloudify connection failure {} ", MessageEnum.RA_CREATE_STACK_ERR,
- ErrorCode.BusinessProcesssError.getValue(), command, ce);
- savedException = ce;
- }
- catch (CloudifyResponseException re) {
- logger.error("{} {} Execute Workflow ({}): Cloudify response error {} ", MessageEnum.RA_CREATE_STACK_ERR,
- ErrorCode.BusinessProcesssError.getValue(), command, re.getMessage(), re);
- savedException = re;
- }
- catch (RuntimeException e) {
- // Catch-all
- logger.error("{} {} Execute Workflow ({}): Internal error {}", MessageEnum.RA_CREATE_STACK_ERR,
- ErrorCode.BusinessProcesssError.getValue(), command, e.getMessage(), e);
- savedException = e;
- }
-
- // Get to this point ONLY on an error or timeout
- // The cloudify execution is still running (we've not received a terminal status),
- // so try to Cancel it.
- CancelExecutionParams cancelParams = new CancelExecutionParams();
- cancelParams.setAction("cancel");
- // TODO: Use force_cancel?
-
- Execution cancelExecution = null;
-
- try {
- CancelExecution cancelRequest = cloudify.executions().cancel(executionId, cancelParams);
- logger.debug(cancelRequest.toString());
- cancelExecution = cancelRequest.execute();
-
- // Enter polling loop
- boolean timedOut = false;
- int cancelTimeout = timeout; // TODO: For now, just use same timeout
-
- String status = cancelExecution.getStatus();
-
- // Poll for completion. Create a reusable cloudify query request
- GetExecution queryExecution = cloudify.executions().byId(executionId);
-
- while (!timedOut && !status.equals(CANCELLED))
- {
- // workflow is still running; check for timeout
- if (cancelTimeout <= 0) {
- logger.debug("Cancel timeout for workflow {} on deployment {}", workflowId, deploymentId);
- timedOut = true;
- continue;
- }
-
- sleep(pollInterval * 1000L);
-
- cancelTimeout -= pollInterval;
- logger.debug("pollTimeout remaining: {}", cancelTimeout);
-
- execution = queryExecution.execute();
- status = execution.getStatus();
- }
-
- // Broke the loop. Check again for a terminal state
- if (status.equals(CANCELLED)){
- // Finished cancelling. Return the original exception
- logger.debug("Cancel workflow {} completed on deployment {}", workflowId, deploymentId);
- throw new MsoCloudifyException (-1, "", "", savedException);
- }
- else {
- // Can only get here after a timeout
- logger.debug("Cancel workflow {} timeout out on deployment {}", workflowId, deploymentId);
- MsoCloudifyException exception = new MsoCloudifyException (-1, "", "", savedException);
- exception.setPendingWorkflow(true);
- throw exception;
- }
- }
- catch (Exception e) {
- // Catch-all. Log the message and throw the original exception
- logger.debug("Cancel workflow {} failed for deployment {} :", workflowId, deploymentId, e);
- MsoCloudifyException exception = new MsoCloudifyException (-1, "", "", savedException);
- exception.setPendingWorkflow(true);
- throw exception;
- }
+ StartExecutionParams executeParams = new StartExecutionParams();
+ executeParams.setWorkflowId(workflowId);
+ executeParams.setDeploymentId(deploymentId);
+ executeParams.setParameters(workflowParams);
+
+ Execution execution = null;
+ String executionId = null;
+ String command = "start";
+ Exception savedException = null;
+
+ try {
+ StartExecution executionRequest = cloudify.executions().start(executeParams);
+ logger.debug(executionRequest.toString());
+ execution = executeAndRecordCloudifyRequest(executionRequest);
+ executionId = execution.getId();
+
+ if (!pollForCompletion) {
+ // Client did not request polling, so just return the Execution object
+ return execution;
+ }
+
+ // Enter polling loop
+ boolean timedOut = false;
+ int pollTimeout = timeout;
+
+ String status = execution.getStatus();
+
+ // Create a reusable cloudify query request
+ GetExecution queryExecution = cloudify.executions().byId(executionId);
+ command = "query";
+
+ while (!timedOut && !(status.equals(TERMINATED) || status.equals("failed") || status.equals(CANCELLED))) {
+ // workflow is still running; check for timeout
+ if (pollTimeout <= 0) {
+ logger.debug("workflow {} timed out on deployment {}", execution.getWorkflowId(),
+ execution.getDeploymentId());
+ timedOut = true;
+ continue;
+ }
+
+ sleep(pollInterval * 1000L);
+
+ pollTimeout -= pollInterval;
+ logger.debug("pollTimeout remaining: " + pollTimeout);
+
+ execution = queryExecution.execute();
+ status = execution.getStatus();
+ }
+
+ // Broke the loop. Check again for a terminal state
+ if (status.equals(TERMINATED)) {
+ // Success!
+ logger.debug("Workflow '{}' completed successfully on deployment '{}'", workflowId, deploymentId);
+ return execution;
+ } else if (status.equals("failed")) {
+ // Workflow failed. Log it and return the execution object (don't throw exception here)
+ logger.error("{} Cloudify workflow failure: {} {} Execute Workflow: Failed: {}",
+ MessageEnum.RA_CREATE_STACK_ERR, execution.getError(),
+ ErrorCode.BusinessProcesssError.getValue(), execution.getError());
+ return execution;
+ } else if (status.equals(CANCELLED)) {
+ // Workflow was cancelled, leaving the deployment in an indeterminate state. Log it and return the
+ // execution object (don't throw exception here)
+ logger.error("{} Cloudify workflow cancelled. Deployment is in an indeterminate state {} {} {}",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
+ "Execute Workflow cancelled: ", workflowId);
+ return execution;
+ } else {
+ // Can only get here after a timeout
+ logger.error("{} Cloudify workflow timeout {} Execute Workflow: Timed Out",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
+ }
+ } catch (CloudifyConnectException ce) {
+ logger.error("{} {} Execute Workflow ({} {}): Cloudify connection failure {} ",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), command, ce);
+ savedException = ce;
+ } catch (CloudifyResponseException re) {
+ logger.error("{} {} Execute Workflow ({}): Cloudify response error {} ", MessageEnum.RA_CREATE_STACK_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), command, re.getMessage(), re);
+ savedException = re;
+ } catch (RuntimeException e) {
+ // Catch-all
+ logger.error("{} {} Execute Workflow ({}): Internal error {}", MessageEnum.RA_CREATE_STACK_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), command, e.getMessage(), e);
+ savedException = e;
+ }
+
+ // Get to this point ONLY on an error or timeout
+ // The cloudify execution is still running (we've not received a terminal status),
+ // so try to Cancel it.
+ CancelExecutionParams cancelParams = new CancelExecutionParams();
+ cancelParams.setAction("cancel");
+ // TODO: Use force_cancel?
+
+ Execution cancelExecution = null;
+
+ try {
+ CancelExecution cancelRequest = cloudify.executions().cancel(executionId, cancelParams);
+ logger.debug(cancelRequest.toString());
+ cancelExecution = cancelRequest.execute();
+
+ // Enter polling loop
+ boolean timedOut = false;
+ int cancelTimeout = timeout; // TODO: For now, just use same timeout
+
+ String status = cancelExecution.getStatus();
+
+ // Poll for completion. Create a reusable cloudify query request
+ GetExecution queryExecution = cloudify.executions().byId(executionId);
+
+ while (!timedOut && !status.equals(CANCELLED)) {
+ // workflow is still running; check for timeout
+ if (cancelTimeout <= 0) {
+ logger.debug("Cancel timeout for workflow {} on deployment {}", workflowId, deploymentId);
+ timedOut = true;
+ continue;
+ }
+
+ sleep(pollInterval * 1000L);
+
+ cancelTimeout -= pollInterval;
+ logger.debug("pollTimeout remaining: {}", cancelTimeout);
+
+ execution = queryExecution.execute();
+ status = execution.getStatus();
+ }
+
+ // Broke the loop. Check again for a terminal state
+ if (status.equals(CANCELLED)) {
+ // Finished cancelling. Return the original exception
+ logger.debug("Cancel workflow {} completed on deployment {}", workflowId, deploymentId);
+ throw new MsoCloudifyException(-1, "", "", savedException);
+ } else {
+ // Can only get here after a timeout
+ logger.debug("Cancel workflow {} timeout out on deployment {}", workflowId, deploymentId);
+ MsoCloudifyException exception = new MsoCloudifyException(-1, "", "", savedException);
+ exception.setPendingWorkflow(true);
+ throw exception;
+ }
+ } catch (Exception e) {
+ // Catch-all. Log the message and throw the original exception
+ logger.debug("Cancel workflow {} failed for deployment {} :", workflowId, deploymentId, e);
+ MsoCloudifyException exception = new MsoCloudifyException(-1, "", "", savedException);
+ exception.setPendingWorkflow(true);
+ throw exception;
+ }
}
/**
- * Query for a Cloudify Deployment (by Name). This call will always return a
- * DeploymentInfo object. If the deployment does not exist, an "empty" DeploymentInfo will be
- * returned - containing only the deployment ID and a special status of NOTFOUND.
+ * Query for a Cloudify Deployment (by Name). This call will always return a DeploymentInfo object. If the
+ * deployment does not exist, an "empty" DeploymentInfo will be returned - containing only the deployment ID and a
+ * special status of NOTFOUND.
*
* @param tenantId The Openstack ID of the tenant in which to query
* @param cloudSiteId The cloud identifier (may be a region) in which to query
* @return A StackInfo object
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
*/
- public DeploymentInfo queryDeployment (String cloudSiteId, String tenantId, String deploymentId)
- throws MsoException
- {
- logger.debug ("Query Cloudify Deployment: {} in tenant {}", deploymentId, tenantId);
+ public DeploymentInfo queryDeployment(String cloudSiteId, String tenantId, String deploymentId)
+ throws MsoException {
+ logger.debug("Query Cloudify Deployment: {} in tenant {}", deploymentId, tenantId);
// Obtain the cloud site information where we will create the stack
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSite.isPresent()) {
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- Cloudify cloudify = getCloudifyClient (cloudSite.get());
-
- // Build and send the Cloudify request
- Deployment deployment = new Deployment();
- try {
- GetDeployment queryDeployment = cloudify.deployments().byId(deploymentId);
- logger.debug(queryDeployment.toString());
- deployment = executeAndRecordCloudifyRequest(queryDeployment);
-
- // Next look for the latest execution
- ListExecutions listExecutions = cloudify.executions().listFiltered ("deployment_id=" + deploymentId, "-created_at");
- Executions executions = listExecutions.execute();
-
- // If no executions, does this give NOT_FOUND or empty set?
- if (executions.getItems().isEmpty()) {
- return new DeploymentInfoBuilder()
- .withId(deployment.getId())
- .withDeploymentInputs(deployment.getInputs())
- .build();
- }
- else {
- return new DeploymentInfoBuilder()
- .withId(deployment.getId())
- .withDeploymentInputs(deployment.getInputs())
- .withDeploymentOutputs(getDeploymentOutputs(cloudify, deploymentId).get())
- .fromExecution(executions.getItems().get(0))
- .build();
- }
- }
- catch (CloudifyConnectException ce) {
- // Couldn't connect to Cloudify
- logger.error("{} QueryDeployment: Cloudify connection failure: {} ", MessageEnum.RA_CREATE_STACK_ERR,
- ErrorCode.BusinessProcesssError.getValue(), ce);
- throw new MsoIOException (ce.getMessage(), ce);
- }
- catch (CloudifyResponseException re) {
- if (re.getStatus () == 404) {
- // Got a NOT FOUND error. React differently based on deployment vs. execution
- if (deployment != null) {
- // Got NOT_FOUND on the executions. Assume this is a valid "empty" set
- return new DeploymentInfoBuilder()
- .withId(deployment.getId())
- .withDeploymentInputs(deployment.getInputs())
- .withDeploymentOutputs(getDeploymentOutputs(cloudify, deploymentId).get())
- .build();
- } else {
- // Deployment not found. Default status of a DeploymentInfo object is NOTFOUND
- return new DeploymentInfoBuilder().withId(deploymentId).build();
- }
+ Cloudify cloudify = getCloudifyClient(cloudSite.get());
+
+ // Build and send the Cloudify request
+ Deployment deployment = new Deployment();
+ try {
+ GetDeployment queryDeployment = cloudify.deployments().byId(deploymentId);
+ logger.debug(queryDeployment.toString());
+ deployment = executeAndRecordCloudifyRequest(queryDeployment);
+
+ // Next look for the latest execution
+ ListExecutions listExecutions =
+ cloudify.executions().listFiltered("deployment_id=" + deploymentId, "-created_at");
+ Executions executions = listExecutions.execute();
+
+ // If no executions, does this give NOT_FOUND or empty set?
+ if (executions.getItems().isEmpty()) {
+ return new DeploymentInfoBuilder().withId(deployment.getId())
+ .withDeploymentInputs(deployment.getInputs()).build();
+ } else {
+ return new DeploymentInfoBuilder().withId(deployment.getId())
+ .withDeploymentInputs(deployment.getInputs())
+ .withDeploymentOutputs(getDeploymentOutputs(cloudify, deploymentId).get())
+ .fromExecution(executions.getItems().get(0)).build();
}
- throw new MsoCloudifyException (re.getStatus(), re.getMessage(), re.getLocalizedMessage(), re);
- }
- catch (Exception e) {
- // Catch-all
- throw new MsoAdapterException (e.getMessage(), e);
- }
+ } catch (CloudifyConnectException ce) {
+ // Couldn't connect to Cloudify
+ logger.error("{} QueryDeployment: Cloudify connection failure: {} ", MessageEnum.RA_CREATE_STACK_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), ce);
+ throw new MsoIOException(ce.getMessage(), ce);
+ } catch (CloudifyResponseException re) {
+ if (re.getStatus() == 404) {
+ // Got a NOT FOUND error. React differently based on deployment vs. execution
+ if (deployment != null) {
+ // Got NOT_FOUND on the executions. Assume this is a valid "empty" set
+ return new DeploymentInfoBuilder().withId(deployment.getId())
+ .withDeploymentInputs(deployment.getInputs())
+ .withDeploymentOutputs(getDeploymentOutputs(cloudify, deploymentId).get()).build();
+ } else {
+ // Deployment not found. Default status of a DeploymentInfo object is NOTFOUND
+ return new DeploymentInfoBuilder().withId(deploymentId).build();
+ }
+ }
+ throw new MsoCloudifyException(re.getStatus(), re.getMessage(), re.getLocalizedMessage(), re);
+ } catch (Exception e) {
+ // Catch-all
+ throw new MsoAdapterException(e.getMessage(), e);
+ }
}
/**
- * Delete a Cloudify deployment (by ID). If the deployment is not found, it will be
- * considered a successful deletion. The return value is a DeploymentInfo object which
- * contains the last deployment status.
+ * Delete a Cloudify deployment (by ID). If the deployment is not found, it will be considered a successful
+ * deletion. The return value is a DeploymentInfo object which contains the last deployment status.
*
- * There is no rollback from a successful deletion. A deletion failure will
- * also result in an undefined deployment state - the components may or may not have been
- * all or partially deleted, so the resulting deployment must be considered invalid.
+ * There is no rollback from a successful deletion. A deletion failure will also result in an undefined deployment
+ * state - the components may or may not have been all or partially deleted, so the resulting deployment must be
+ * considered invalid.
*
* @param tenantId The Openstack ID of the tenant in which to perform the delete
* @param cloudSiteId The cloud identifier (may be a region) from which to delete the stack.
@@ -650,274 +605,247 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
* @throws MsoCloudSiteNotFound
*/
- public DeploymentInfo uninstallAndDeleteDeployment (String cloudSiteId,
- String tenantId,
- String deploymentId,
- int timeoutMinutes) throws MsoException
- {
+ public DeploymentInfo uninstallAndDeleteDeployment(String cloudSiteId, String tenantId, String deploymentId,
+ int timeoutMinutes) throws MsoException {
// Obtain the cloud site information where we will create the stack
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSite.isPresent()) {
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- Cloudify cloudify = getCloudifyClient (cloudSite.get());
+ Cloudify cloudify = getCloudifyClient(cloudSite.get());
- logger.debug ("Ready to Uninstall/Delete Deployment ({})", deploymentId);
+ logger.debug("Ready to Uninstall/Delete Deployment ({})", deploymentId);
// Query first to save the trouble if deployment not found
- try {
- GetDeployment queryDeploymentRequest = cloudify.deployments().byId(deploymentId);
- logger.debug(queryDeploymentRequest.toString());
+ try {
+ GetDeployment queryDeploymentRequest = cloudify.deployments().byId(deploymentId);
+ logger.debug(queryDeploymentRequest.toString());
- // deployment = executeAndRecordCloudifyRequest (queryDeploymentRequest);
- }
- catch (CloudifyResponseException e) {
+ // deployment = executeAndRecordCloudifyRequest (queryDeploymentRequest);
+ } catch (CloudifyResponseException e) {
// Since this came on the 'Create Deployment' command, nothing was changed
// in the cloud. Return the error as an exception.
- if (e.getStatus () == 404) {
- // Deployment doesn't exist. Return a "NOTFOUND" DeploymentInfo object
- // TODO: Should return NULL?
+ if (e.getStatus() == 404) {
+ // Deployment doesn't exist. Return a "NOTFOUND" DeploymentInfo object
+ // TODO: Should return NULL?
logger.debug("Deployment requested for deletion does not exist: {}", deploymentId);
- return new DeploymentInfoBuilder()
- .withId(deploymentId)
- .withStatus(DeploymentStatus.NOTFOUND)
- .build();
- } else {
+ return new DeploymentInfoBuilder().withId(deploymentId).withStatus(DeploymentStatus.NOTFOUND).build();
+ } else {
// Convert the CloudifyResponseException to an MsoOpenstackException
logger.debug("ERROR STATUS = {}, \n {}\n {}\n {}", e.getStatus(), e.getMessage(),
- e.getLocalizedMessage(), e);
- MsoException me = cloudifyExceptionToMsoException (e, DELETE_DEPLOYMENT);
- me.setCategory (MsoExceptionCategory.INTERNAL);
+ e.getLocalizedMessage(), e);
+ MsoException me = cloudifyExceptionToMsoException(e, DELETE_DEPLOYMENT);
+ me.setCategory(MsoExceptionCategory.INTERNAL);
throw me;
}
} catch (CloudifyConnectException e) {
// Error connecting to Cloudify instance. Convert to an MsoException
- throw cloudifyExceptionToMsoException (e, DELETE_DEPLOYMENT);
+ throw cloudifyExceptionToMsoException(e, DELETE_DEPLOYMENT);
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, DELETE_DEPLOYMENT);
+ throw runtimeExceptionToMsoException(e, DELETE_DEPLOYMENT);
}
- /*
- * Query the outputs before deleting so they can be returned as well
- */
- //DeploymentOutputs outputs = getDeploymentOutputs (cloudify, deploymentId);
-
- /*
- * Next execute the "uninstall" workflow.
- * Note - this assumes there are no additional parameters required for the workflow.
- */
- // TODO: No deletePollInterval that I'm aware of. Use the create interval
- int deletePollInterval = Integer.parseInt(this.environment.getProperty (deletePollIntervalProp, deletePollIntervalDefault));
+ /*
+ * Query the outputs before deleting so they can be returned as well
+ */
+ // DeploymentOutputs outputs = getDeploymentOutputs (cloudify, deploymentId);
+
+ /*
+ * Next execute the "uninstall" workflow. Note - this assumes there are no additional parameters required for
+ * the workflow.
+ */
+ // TODO: No deletePollInterval that I'm aware of. Use the create interval
+ int deletePollInterval =
+ Integer.parseInt(this.environment.getProperty(deletePollIntervalProp, deletePollIntervalDefault));
int pollTimeout = (timeoutMinutes * 60) + deletePollInterval;
Execution uninstallWorkflow = null;
try {
- uninstallWorkflow = executeWorkflow (cloudify, deploymentId, "uninstall", null, true, pollTimeout, deletePollInterval);
-
- if (uninstallWorkflow.getStatus().equals(TERMINATED)) {
- // Successful uninstall.
- logger.debug("Uninstall successful for deployment {}", deploymentId);
- }
- else {
- // The uninstall workflow completed with an error. Must fail the request, but will
- // leave the deployment in an indeterminate state, as cloud resources may still exist.
- MsoCloudifyException me = new MsoCloudifyException (0, "Uninstall Workflow Failed", uninstallWorkflow.getError());
- me.addContext (DELETE_DEPLOYMENT);
+ uninstallWorkflow =
+ executeWorkflow(cloudify, deploymentId, "uninstall", null, true, pollTimeout, deletePollInterval);
+
+ if (uninstallWorkflow.getStatus().equals(TERMINATED)) {
+ // Successful uninstall.
+ logger.debug("Uninstall successful for deployment {}", deploymentId);
+ } else {
+ // The uninstall workflow completed with an error. Must fail the request, but will
+ // leave the deployment in an indeterminate state, as cloud resources may still exist.
+ MsoCloudifyException me =
+ new MsoCloudifyException(0, "Uninstall Workflow Failed", uninstallWorkflow.getError());
+ me.addContext(DELETE_DEPLOYMENT);
throw me;
- }
- }
- catch (MsoException me) {
- // Uninstall workflow has failed.
- // Must fail the deletion... may leave the deployment in an inconclusive state
- me.addContext (DELETE_DEPLOYMENT);
+ }
+ } catch (MsoException me) {
+ // Uninstall workflow has failed.
+ // Must fail the deletion... may leave the deployment in an inconclusive state
+ me.addContext(DELETE_DEPLOYMENT);
throw me;
}
-
+
// At this point, the deployment has been successfully uninstalled.
// Next step is to delete the deployment itself
- Deployment deployment;
+ Deployment deployment;
try {
- DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId);
+ DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId);
logger.debug(deleteRequest.toString());
- // The delete request returns the deleted deployment
- deployment = deleteRequest.execute();
+ // The delete request returns the deleted deployment
+ deployment = deleteRequest.execute();
- }
- catch (CloudifyConnectException ce) {
- // Failed to delete. Must fail the request, but will leave the (uninstalled)
- // deployment in Cloudify DB.
- MsoCloudifyException me = new MsoCloudifyException (0, "Deployment Delete Failed", ce.getMessage(), ce);
- me.addContext (DELETE_DEPLOYMENT);
+ } catch (CloudifyConnectException ce) {
+ // Failed to delete. Must fail the request, but will leave the (uninstalled)
+ // deployment in Cloudify DB.
+ MsoCloudifyException me = new MsoCloudifyException(0, "Deployment Delete Failed", ce.getMessage(), ce);
+ me.addContext(DELETE_DEPLOYMENT);
throw me;
- }
- catch (CloudifyResponseException re) {
- // Failed to delete. Must fail the request, but will leave the (uninstalled)
- // deployment in the Cloudify DB.
- MsoCloudifyException me = new MsoCloudifyException (re.getStatus(), re.getMessage(), re.getMessage(), re);
- me.addContext (DELETE_DEPLOYMENT);
+ } catch (CloudifyResponseException re) {
+ // Failed to delete. Must fail the request, but will leave the (uninstalled)
+ // deployment in the Cloudify DB.
+ MsoCloudifyException me = new MsoCloudifyException(re.getStatus(), re.getMessage(), re.getMessage(), re);
+ me.addContext(DELETE_DEPLOYMENT);
throw me;
- }
- catch (Exception e) {
- // Catch-all
- MsoAdapterException ae = new MsoAdapterException (e.getMessage(), e);
- ae.addContext (DELETE_DEPLOYMENT);
+ } catch (Exception e) {
+ // Catch-all
+ MsoAdapterException ae = new MsoAdapterException(e.getMessage(), e);
+ ae.addContext(DELETE_DEPLOYMENT);
throw ae;
}
- // Return the deleted deployment info (with runtime outputs) along with the completed uninstall workflow status
- return new DeploymentInfoBuilder()
- .withId(deployment.getId())
- .withDeploymentInputs(deployment.getInputs())
- .withDeploymentOutputs(getDeploymentOutputs(cloudify, deploymentId).get())
- .fromExecution(uninstallWorkflow)
- .build();
+ // Return the deleted deployment info (with runtime outputs) along with the completed uninstall workflow status
+ return new DeploymentInfoBuilder().withId(deployment.getId()).withDeploymentInputs(deployment.getInputs())
+ .withDeploymentOutputs(getDeploymentOutputs(cloudify, deploymentId).get())
+ .fromExecution(uninstallWorkflow).build();
}
/**
- * Check if a blueprint is available for use at a targeted cloud site.
- * This requires checking the Cloudify Manager which is servicing that
- * cloud site to see if the specified blueprint has been loaded.
+ * Check if a blueprint is available for use at a targeted cloud site. This requires checking the Cloudify Manager
+ * which is servicing that cloud site to see if the specified blueprint has been loaded.
*
* @param cloudSiteId The cloud site where the blueprint is needed
* @param blueprintId The ID for the blueprint in Cloudify
*/
- public boolean isBlueprintLoaded (String cloudSiteId, String blueprintId)
- throws MsoException
- {
+ public boolean isBlueprintLoaded(String cloudSiteId, String blueprintId) throws MsoException {
// Obtain the cloud site information where we will load the blueprint
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSite.isPresent()) {
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- Cloudify cloudify = getCloudifyClient (cloudSite.get());
-
- GetBlueprint getRequest = cloudify.blueprints().getMetadataById(blueprintId);
- try {
- Blueprint bp = getRequest.execute();
- logger.debug("Blueprint exists: {}", bp.getId());
- return true;
- }
- catch (CloudifyResponseException ce) {
- if (ce.getStatus() == 404) {
- return false;
- } else {
- throw ce;
- }
- } catch (Exception e) {
- throw e;
- }
+ Cloudify cloudify = getCloudifyClient(cloudSite.get());
+
+ GetBlueprint getRequest = cloudify.blueprints().getMetadataById(blueprintId);
+ try {
+ Blueprint bp = getRequest.execute();
+ logger.debug("Blueprint exists: {}", bp.getId());
+ return true;
+ } catch (CloudifyResponseException ce) {
+ if (ce.getStatus() == 404) {
+ return false;
+ } else {
+ throw ce;
+ }
+ } catch (Exception e) {
+ throw e;
+ }
}
/**
- * Upload a blueprint to the Cloudify Manager that is servicing a Cloud Site.
- * The blueprint currently must be structured as a single directory with all
- * of the required files. One of those files is designated the "main file"
- * for the blueprint. Files are provided as byte arrays, though expect only
- * text files will be distributed from ASDC and stored by MSO.
+ * Upload a blueprint to the Cloudify Manager that is servicing a Cloud Site. The blueprint currently must be
+ * structured as a single directory with all of the required files. One of those files is designated the "main file"
+ * for the blueprint. Files are provided as byte arrays, though expect only text files will be distributed from ASDC
+ * and stored by MSO.
*
- * Cloudify requires a single root directory in its blueprint zip files.
- * The requested blueprint ID will also be used as the directory.
- * All of the files will be added to this directory in the zip file.
+ * Cloudify requires a single root directory in its blueprint zip files. The requested blueprint ID will also be
+ * used as the directory. All of the files will be added to this directory in the zip file.
*/
- public void uploadBlueprint (String cloudSiteId,
- String blueprintId,
- String mainFileName,
- Map<String,byte[]> blueprintFiles,
- boolean failIfExists)
- throws MsoException
- {
+ public void uploadBlueprint(String cloudSiteId, String blueprintId, String mainFileName,
+ Map<String, byte[]> blueprintFiles, boolean failIfExists) throws MsoException {
// Obtain the cloud site information where we will load the blueprint
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSite.isPresent()) {
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- Cloudify cloudify = getCloudifyClient (cloudSite.get());
+ Cloudify cloudify = getCloudifyClient(cloudSite.get());
- boolean blueprintUploaded = uploadBlueprint (cloudify, blueprintId, mainFileName, blueprintFiles);
+ boolean blueprintUploaded = uploadBlueprint(cloudify, blueprintId, mainFileName, blueprintFiles);
if (!blueprintUploaded && failIfExists) {
- throw new MsoAdapterException ("Blueprint already exists");
+ throw new MsoAdapterException("Blueprint already exists");
}
}
/*
- * Common method to load a blueprint. May be called from
+ * Common method to load a blueprint. May be called from
*/
- protected boolean uploadBlueprint (Cloudify cloudify, String blueprintId, String mainFileName, Map<String,byte[]> blueprintFiles)
- throws MsoException
- {
- // Check if it already exists. If so, return false.
- GetBlueprint getRequest = cloudify.blueprints().getMetadataById(blueprintId);
- try {
- Blueprint bp = getRequest.execute();
- logger.debug("Blueprint {} already exists.", bp.getId());
- return false;
- }
- catch (CloudifyResponseException ce) {
- if (ce.getStatus() == 404) {
- // This is the expected result.
- logger.debug("Verified that Blueprint doesn't exist yet");
- } else {
- throw ce;
- }
- } catch (Exception e) {
- throw e;
- }
-
- // Create a blueprint ZIP file in memory
- ByteArrayOutputStream zipBuffer = new ByteArrayOutputStream();
- ZipOutputStream zipOut = new ZipOutputStream(zipBuffer);
-
- try {
- // Put the root directory
- String rootDir = blueprintId + ((blueprintId.endsWith("/") ? "" : "/"));
- zipOut.putNextEntry(new ZipEntry (rootDir));
- zipOut.closeEntry();
-
- for (String fileName : blueprintFiles.keySet()) {
- ZipEntry ze = new ZipEntry (rootDir + fileName);
- zipOut.putNextEntry (ze);
- zipOut.write (blueprintFiles.get(fileName));
- zipOut.closeEntry();
- }
- zipOut.close();
- }
- catch (IOException e) {
- // Since we're writing to a byte array, this should never happen
- }
+ protected boolean uploadBlueprint(Cloudify cloudify, String blueprintId, String mainFileName,
+ Map<String, byte[]> blueprintFiles) throws MsoException {
+ // Check if it already exists. If so, return false.
+ GetBlueprint getRequest = cloudify.blueprints().getMetadataById(blueprintId);
+ try {
+ Blueprint bp = getRequest.execute();
+ logger.debug("Blueprint {} already exists.", bp.getId());
+ return false;
+ } catch (CloudifyResponseException ce) {
+ if (ce.getStatus() == 404) {
+ // This is the expected result.
+ logger.debug("Verified that Blueprint doesn't exist yet");
+ } else {
+ throw ce;
+ }
+ } catch (Exception e) {
+ throw e;
+ }
+
+ // Create a blueprint ZIP file in memory
+ ByteArrayOutputStream zipBuffer = new ByteArrayOutputStream();
+ ZipOutputStream zipOut = new ZipOutputStream(zipBuffer);
+
+ try {
+ // Put the root directory
+ String rootDir = blueprintId + ((blueprintId.endsWith("/") ? "" : "/"));
+ zipOut.putNextEntry(new ZipEntry(rootDir));
+ zipOut.closeEntry();
+
+ for (String fileName : blueprintFiles.keySet()) {
+ ZipEntry ze = new ZipEntry(rootDir + fileName);
+ zipOut.putNextEntry(ze);
+ zipOut.write(blueprintFiles.get(fileName));
+ zipOut.closeEntry();
+ }
+ zipOut.close();
+ } catch (IOException e) {
+ // Since we're writing to a byte array, this should never happen
+ }
logger.debug("Blueprint zip file size: {}", zipBuffer.size());
// Ready to upload the blueprint zip
- try (InputStream blueprintStream = new ByteArrayInputStream (zipBuffer.toByteArray())) {
- UploadBlueprint uploadRequest = cloudify.blueprints().uploadFromStream(blueprintId, mainFileName, blueprintStream);
- Blueprint blueprint = uploadRequest.execute();
- logger.debug("Successfully uploaded blueprint {}", blueprint.getId());
- }
- catch (CloudifyResponseException | CloudifyConnectException e) {
- throw cloudifyExceptionToMsoException (e, "UPLOAD_BLUEPRINT");
- }
- catch (RuntimeException e) {
- // Catch-all
- throw runtimeExceptionToMsoException (e, "UPLOAD_BLUEPRINT");
- } catch (IOException e) {
- // for try-with-resources
- throw ioExceptionToMsoException(e, "UPLOAD_BLUEPRINT");
- }
-
- return true;
+ try (InputStream blueprintStream = new ByteArrayInputStream(zipBuffer.toByteArray())) {
+ UploadBlueprint uploadRequest =
+ cloudify.blueprints().uploadFromStream(blueprintId, mainFileName, blueprintStream);
+ Blueprint blueprint = uploadRequest.execute();
+ logger.debug("Successfully uploaded blueprint {}", blueprint.getId());
+ } catch (CloudifyResponseException | CloudifyConnectException e) {
+ throw cloudifyExceptionToMsoException(e, "UPLOAD_BLUEPRINT");
+ } catch (RuntimeException e) {
+ // Catch-all
+ throw runtimeExceptionToMsoException(e, "UPLOAD_BLUEPRINT");
+ } catch (IOException e) {
+ // for try-with-resources
+ throw ioExceptionToMsoException(e, "UPLOAD_BLUEPRINT");
+ }
+
+ return true;
}
@@ -926,35 +854,33 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
// PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
/**
- * Get a Cloudify client for the specified cloud site.
- * Everything that is required can be found in the Cloud Config.
+ * Get a Cloudify client for the specified cloud site. Everything that is required can be found in the Cloud Config.
*
* @param cloudSite
* @return a Cloudify object
*/
- public Cloudify getCloudifyClient (CloudSite cloudSite) throws MsoException
- {
+ public Cloudify getCloudifyClient(CloudSite cloudSite) throws MsoException {
CloudifyManager cloudifyConfig = cloudConfig.getCloudifyManager(cloudSite.getCloudifyId());
if (cloudifyConfig == null) {
- throw new MsoCloudifyManagerNotFound (cloudSite.getId());
+ throw new MsoCloudifyManagerNotFound(cloudSite.getId());
}
// Get a Cloudify client
- // Set a Token Provider to fetch tokens from Cloudify itself.
+ // Set a Token Provider to fetch tokens from Cloudify itself.
String cloudifyUrl = cloudifyConfig.getCloudifyUrl();
- Cloudify cloudify = new Cloudify (cloudifyUrl);
- cloudify.setTokenProvider(new CloudifyClientTokenProvider(cloudifyUrl, cloudifyConfig.getUsername(), CryptoUtils.decryptCloudConfigPassword(cloudifyConfig.getPassword())));
+ Cloudify cloudify = new Cloudify(cloudifyUrl);
+ cloudify.setTokenProvider(new CloudifyClientTokenProvider(cloudifyUrl, cloudifyConfig.getUsername(),
+ CryptoUtils.decryptCloudConfigPassword(cloudifyConfig.getPassword())));
- return cloudify;
+ return cloudify;
}
/*
- * Query for a Cloudify Deployment. This function is needed in several places, so
- * a common method is useful. This method takes an authenticated CloudifyClient
- * (which internally identifies the cloud & tenant to search), and returns
- * a Deployment object if found, Null if not found, or an MsoCloudifyException
- * if the Cloudify API call fails.
+ * Query for a Cloudify Deployment. This function is needed in several places, so a common method is useful. This
+ * method takes an authenticated CloudifyClient (which internally identifies the cloud & tenant to search), and
+ * returns a Deployment object if found, Null if not found, or an MsoCloudifyException if the Cloudify API call
+ * fails.
*
* @param cloudifyClient an authenticated Cloudify client
*
@@ -964,234 +890,223 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
*
* @throws MsoCloudifyException Thrown if the Cloudify API call returns an exception
*/
- protected Deployment queryDeployment (Cloudify cloudify, String deploymentId) throws MsoException {
+ protected Deployment queryDeployment(Cloudify cloudify, String deploymentId) throws MsoException {
if (deploymentId == null) {
return null;
}
try {
- GetDeployment request = cloudify.deployments().byId (deploymentId);
- return executeAndRecordCloudifyRequest (request);
+ GetDeployment request = cloudify.deployments().byId(deploymentId);
+ return executeAndRecordCloudifyRequest(request);
} catch (CloudifyResponseException e) {
- if (e.getStatus () == 404) {
- logger.debug ("queryDeployment - not found: {}", deploymentId);
+ if (e.getStatus() == 404) {
+ logger.debug("queryDeployment - not found: {}", deploymentId);
return null;
} else {
// Convert the CloudifyResponseException to an MsoCloudifyException
- throw cloudifyExceptionToMsoException (e, "QueryDeployment");
+ throw cloudifyExceptionToMsoException(e, "QueryDeployment");
}
} catch (CloudifyConnectException e) {
// Connection to Openstack failed
- throw cloudifyExceptionToMsoException (e, "QueryDeployment");
+ throw cloudifyExceptionToMsoException(e, "QueryDeployment");
}
}
- public void copyStringOutputsToInputs(Map<String, String> inputs,
- Map<String, Object> otherStackOutputs, boolean overWrite) {
- if (inputs == null || otherStackOutputs == null)
- return;
-
- for (Map.Entry<String, Object> entry : otherStackOutputs.entrySet()) {
- String key = entry.getKey();
- Object value = entry.getValue();
-
- if (value instanceof JsonNode) {
- // This is a bit of mess - but I think it's the least impacting
- // let's convert it BACK to a string - then it will get converted back later
- try {
- inputs.put(key, this.convertNode((JsonNode) value));
- } catch (Exception e) {
- logger.debug("WARNING: unable to convert JsonNode output value for {}", key);
- //effect here is this value will not have been copied to the inputs - and therefore will error out downstream
- }
- } else if (value instanceof java.util.LinkedHashMap) {
- logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
- try {
- inputs.put(key, JSON_MAPPER.writeValueAsString(value));
- } catch (Exception e) {
- logger.debug("WARNING: unable to convert LinkedHashMap output value for {}", key);
+ public void copyStringOutputsToInputs(Map<String, String> inputs, Map<String, Object> otherStackOutputs,
+ boolean overWrite) {
+ if (inputs == null || otherStackOutputs == null)
+ return;
+
+ for (Map.Entry<String, Object> entry : otherStackOutputs.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+
+ if (value instanceof JsonNode) {
+ // This is a bit of mess - but I think it's the least impacting
+ // let's convert it BACK to a string - then it will get converted back later
+ try {
+ inputs.put(key, this.convertNode((JsonNode) value));
+ } catch (Exception e) {
+ logger.debug("WARNING: unable to convert JsonNode output value for {}", key);
+ // effect here is this value will not have been copied to the inputs - and therefore will error out
+ // downstream
+ }
+ } else if (value instanceof java.util.LinkedHashMap) {
+ logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
+ try {
+ inputs.put(key, JSON_MAPPER.writeValueAsString(value));
+ } catch (Exception e) {
+ logger.debug("WARNING: unable to convert LinkedHashMap output value for {}", key);
+ }
+ } else {
+ // just try to cast it - could be an integer or some such
+ try {
+ inputs.put(key, (String) value);
+ } catch (Exception e) {
+ logger.debug("WARNING: unable to convert output value for {}", key);
+ // effect here is this value will not have been copied to the inputs - and therefore will error out
+ // downstream
+ }
+ }
}
- } else {
- // just try to cast it - could be an integer or some such
- try {
- inputs.put(key, (String) value);
- } catch (Exception e) {
- logger.debug("WARNING: unable to convert output value for {}", key);
- //effect here is this value will not have been copied to the inputs - and therefore will error out downstream
- }
- }
- }
- return;
- }
-
- /*
- * Normalize an input value to an Object, based on the target parameter type.
- * If the type is not recognized, it will just be returned unchanged (as a string).
- */
- public Object convertInputValue (Object inputValue, HeatTemplateParam templateParam)
- {
- String type = templateParam.getParamType();
- logger.debug("Parameter: {} is of type {}", templateParam.getParamName(), type);
-
- if (type.equalsIgnoreCase("number")) {
- try {
- return Integer.valueOf(inputValue.toString());
- }
- catch (Exception e) {
- logger.debug("Unable to convert {} to an integer!", inputValue);
- return null;
- }
- } else if (type.equalsIgnoreCase("json")) {
- try {
- if (inputValue instanceof String) {
- return JSON_MAPPER.readTree(inputValue.toString());
- }
- //will already marshal to json without intervention
- return inputValue;
- }
- catch (Exception e) {
- logger.debug("Unable to convert {} to a JsonNode!", inputValue);
- return null;
- }
- } else if (type.equalsIgnoreCase("boolean")) {
- return new Boolean(inputValue.toString());
- }
-
- // Nothing else matched. Return the original string
- return inputValue;
- }
-
-
- private String convertNode(final JsonNode node) {
- try {
- final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
- return JSON_MAPPER.writeValueAsString(obj);
- } catch (JsonParseException jpe) {
- logger.debug("Error converting json to string {}", jpe);
- } catch (Exception e) {
- logger.debug("Error converting json to string {}", e);
+ return;
}
- return "[Error converting json to string]";
- }
-
-
+
/*
- * Method to execute a Cloudify command and track its execution time.
- * For the metrics log, a category of "Cloudify" is used along with a
- * sub-category that identifies the specific call (using the real
- * cloudify-client classname of the CloudifyRequest<T> parameter).
+ * Normalize an input value to an Object, based on the target parameter type. If the type is not recognized, it will
+ * just be returned unchanged (as a string).
*/
+ public Object convertInputValue(Object inputValue, HeatTemplateParam templateParam) {
+ String type = templateParam.getParamType();
+ logger.debug("Parameter: {} is of type {}", templateParam.getParamName(), type);
+ if (type.equalsIgnoreCase("number")) {
+ try {
+ return Integer.valueOf(inputValue.toString());
+ } catch (Exception e) {
+ logger.debug("Unable to convert {} to an integer!", inputValue);
+ return null;
+ }
+ } else if (type.equalsIgnoreCase("json")) {
+ try {
+ if (inputValue instanceof String) {
+ return JSON_MAPPER.readTree(inputValue.toString());
+ }
+ // will already marshal to json without intervention
+ return inputValue;
+ } catch (Exception e) {
+ logger.debug("Unable to convert {} to a JsonNode!", inputValue);
+ return null;
+ }
+ } else if (type.equalsIgnoreCase("boolean")) {
+ return new Boolean(inputValue.toString());
+ }
+
+ // Nothing else matched. Return the original string
+ return inputValue;
+ }
+
+
+ private String convertNode(final JsonNode node) {
+ try {
+ final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
+ return JSON_MAPPER.writeValueAsString(obj);
+ } catch (JsonParseException jpe) {
+ logger.debug("Error converting json to string {}", jpe);
+ } catch (Exception e) {
+ logger.debug("Error converting json to string {}", e);
+ }
+ return "[Error converting json to string]";
+ }
- protected <T> T executeAndRecordCloudifyRequest (CloudifyRequest <T> request) {
- String requestType;
- if (request.getClass ().getEnclosingClass () != null) {
- requestType = request.getClass ().getEnclosingClass ().getSimpleName () + "."
- + request.getClass ().getSimpleName ();
+ /*
+ * Method to execute a Cloudify command and track its execution time. For the metrics log, a category of "Cloudify"
+ * is used along with a sub-category that identifies the specific call (using the real cloudify-client classname of
+ * the CloudifyRequest<T> parameter).
+ */
+
+
+ protected <T> T executeAndRecordCloudifyRequest(CloudifyRequest<T> request) {
+
+ String requestType;
+ if (request.getClass().getEnclosingClass() != null) {
+ requestType =
+ request.getClass().getEnclosingClass().getSimpleName() + "." + request.getClass().getSimpleName();
} else {
- requestType = request.getClass ().getSimpleName ();
+ requestType = request.getClass().getSimpleName();
}
int retryDelay = poConfig.getRetryDelay();
int retryCount = poConfig.getRetryCount();
- String retryCodes = poConfig.getRetryCodes();
+ String retryCodes = poConfig.getRetryCodes();
// Run the actual command. All exceptions will be propagated
- while (true)
- {
- try {
- return request.execute ();
- }
- catch (CloudifyResponseException e) {
- boolean retry = false;
- if (retryCodes != null ) {
- int code = e.getStatus();
- logger.debug("Config values RetryDelay: {} RetryCount:{} RetryCodes:{} ResponseCode:{}", retryDelay,
- retryCount, retryCodes, code);
- for (String rCode : retryCodes.split (",")) {
- try {
- if (retryCount > 0 && code == Integer.parseInt (rCode))
- {
- retryCount--;
- retry = true;
- logger.debug(
- "CloudifyResponseException ResponseCode:{} request:{} Retry indicated. Attempts remaining:{}",
- code, requestType, retryCount);
- break;
- }
- } catch (NumberFormatException e1) {
- logger.error("{} No retries. Exception in parsing retry code in config:{} {}",
- MessageEnum.RA_CONFIG_EXC, rCode, ErrorCode.SchemaError.getValue());
+ while (true) {
+ try {
+ return request.execute();
+ } catch (CloudifyResponseException e) {
+ boolean retry = false;
+ if (retryCodes != null) {
+ int code = e.getStatus();
+ logger.debug("Config values RetryDelay: {} RetryCount:{} RetryCodes:{} ResponseCode:{}", retryDelay,
+ retryCount, retryCodes, code);
+ for (String rCode : retryCodes.split(",")) {
+ try {
+ if (retryCount > 0 && code == Integer.parseInt(rCode)) {
+ retryCount--;
+ retry = true;
+ logger.debug(
+ "CloudifyResponseException ResponseCode:{} request:{} Retry indicated. Attempts remaining:{}",
+ code, requestType, retryCount);
+ break;
+ }
+ } catch (NumberFormatException e1) {
+ logger.error("{} No retries. Exception in parsing retry code in config:{} {}",
+ MessageEnum.RA_CONFIG_EXC, rCode, ErrorCode.SchemaError.getValue());
+ throw e;
+ }
+ }
+ }
+ if (retry) {
+ sleep(retryDelay * 1000L);
+ } else
+ throw e; // exceeded retryCount or code is not retryable
+ } catch (CloudifyConnectException e) {
+ // Connection to Cloudify failed
+ if (retryCount > 0) {
+ retryCount--;
+ logger.debug(" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount);
+ sleep(retryDelay * 1000L);
+ } else
throw e;
- }
- }
- }
- if (retry)
- {
- sleep(retryDelay * 1000L);
- }
- else
- throw e; // exceeded retryCount or code is not retryable
- }
- catch (CloudifyConnectException e) {
- // Connection to Cloudify failed
- if (retryCount > 0)
- {
- retryCount--;
- logger.debug(" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount);
- sleep(retryDelay * 1000L);
- }
- else
- throw e;
-
- }
+
+ }
}
}
+
/*
- * Convert an Exception on a Cloudify call to an MsoCloudifyException.
- * This method supports CloudifyResponseException and CloudifyConnectException.
+ * Convert an Exception on a Cloudify call to an MsoCloudifyException. This method supports
+ * CloudifyResponseException and CloudifyConnectException.
*/
- protected MsoException cloudifyExceptionToMsoException (CloudifyBaseException e, String context) {
+ protected MsoException cloudifyExceptionToMsoException(CloudifyBaseException e, String context) {
MsoException me = null;
if (e instanceof CloudifyResponseException) {
- CloudifyResponseException re = (CloudifyResponseException) e;
+ CloudifyResponseException re = (CloudifyResponseException) e;
try {
// Failed Cloudify calls return an error entity body.
- CloudifyError error = re.getResponse ().getErrorEntity (CloudifyError.class);
+ CloudifyError error = re.getResponse().getErrorEntity(CloudifyError.class);
logger.error("{} {} {} Exception - Cloudify Error on {}: {}", MessageEnum.RA_CONNECTION_EXCEPTION,
- CLOUDIFY, ErrorCode.DataError.getValue(), context, error.getErrorCode());
+ CLOUDIFY, ErrorCode.DataError.getValue(), context, error.getErrorCode());
String fullError = error.getErrorCode() + ": " + error.getMessage();
logger.debug(fullError);
- me = new MsoCloudifyException (re.getStatus(),
- re.getMessage(),
- fullError);
+ me = new MsoCloudifyException(re.getStatus(), re.getMessage(), fullError);
} catch (Exception e2) {
// Couldn't parse the body as a "CloudifyError". Report the original HTTP error.
logger.error("{} {} {} Exception - HTTP Error on {}: {}, {} ", MessageEnum.RA_CONNECTION_EXCEPTION,
- CLOUDIFY, ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2);
- me = new MsoCloudifyException (re.getStatus (), re.getMessage (), "");
+ CLOUDIFY, ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2);
+ me = new MsoCloudifyException(re.getStatus(), re.getMessage(), "");
}
// Add the context of the error
- me.addContext (context);
+ me.addContext(context);
// Generate an alarm for 5XX and higher errors.
- if (re.getStatus () >= 500) {
+ if (re.getStatus() >= 500) {
}
} else if (e instanceof CloudifyConnectException) {
- CloudifyConnectException ce = (CloudifyConnectException) e;
+ CloudifyConnectException ce = (CloudifyConnectException) e;
- me = new MsoIOException (ce.getMessage ());
- me.addContext (context);
+ me = new MsoIOException(ce.getMessage());
+ me.addContext(context);
// Generate an alarm for all connection errors.
logger.error("{} {} {} Cloudify connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY,
- ErrorCode.DataError.getValue(), context, e);
+ ErrorCode.DataError.getValue(), context, e);
}
return me;
@@ -1208,88 +1123,75 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
/**
* VduPlugin interface for instantiate function.
*
- * This one is a bit more complex, in that it will first upload the blueprint if needed,
- * then create the Cloudify deployment and execute the install workflow.
+ * This one is a bit more complex, in that it will first upload the blueprint if needed, then create the Cloudify
+ * deployment and execute the install workflow.
*
- * This implementation also merges any parameters defined in the ENV file with the other
- * other input parameters for any undefined parameters).
- * The basic MsoCloudifyUtils separates blueprint management from deploument actions,
- * but the VduPlugin does not declare blueprint management operations.
+ * This implementation also merges any parameters defined in the ENV file with the other other input parameters for
+ * any undefined parameters). The basic MsoCloudifyUtils separates blueprint management from deploument actions, but
+ * the VduPlugin does not declare blueprint management operations.
*/
@Override
- public VduInstance instantiateVdu (
- CloudInfo cloudInfo,
- String instanceName,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException
- {
- String cloudSiteId = cloudInfo.getCloudSiteId();
- String tenantId = cloudInfo.getTenantId();
-
- // Translate the VDU ModelInformation structure to that which is needed for
- // creating and uploading a blueprint. Use the model customization UUID as
- // the blueprint identifier.
-
- String blueprintId = vduModel.getModelCustomizationUUID();
-
- try {
-
- if (! isBlueprintLoaded (cloudSiteId, blueprintId)) {
- logger.debug("Blueprint {} is not loaded. Will upload it now.", blueprintId);
-
- // Prepare the blueprint inputs. Need the set of blueprint templates and files,
- // plus the main blueprint name.
- Map<String,byte[]> blueprintFiles = new HashMap<>();
- String mainTemplate = "";
-
- // Add all of the blueprint artifacts from the VDU model
- List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
- for (VduArtifact vduArtifact: vduArtifacts)
- {
- // Add all artifacts to the blueprint, with one exception.
- // ENVIRONMENT files will be processed later as additional parameters.
-
- ArtifactType artifactType = vduArtifact.getType();
- if (artifactType != ArtifactType.ENVIRONMENT) {
- blueprintFiles.put(vduArtifact.getName(), vduArtifact.getContent());
-
- if (artifactType == ArtifactType.MAIN_TEMPLATE) {
- mainTemplate = vduArtifact.getName();
- }
- }
- }
-
- // Upload the blueprint package
- uploadBlueprint(cloudSiteId, blueprintId, mainTemplate, blueprintFiles, false);
- }
- }
- catch (Exception e) {
- throw new VduException ("CloudifyUtils (instantiateVDU): blueprint Exception", e);
- }
-
-
- // Next, create and install a new deployment based on the blueprint.
- // For Cloudify, the deploymentId is specified by the client. Just use the instance name
- // as the ID.
-
- try {
- // Query the Cloudify Deployment object and populate a VduInstance
- DeploymentInfo deployment = createAndInstallDeployment (cloudSiteId,
- tenantId,
- instanceName,
- blueprintId,
- inputs,
- true, // (poll for completion)
- vduModel.getTimeoutMinutes(),
- rollbackOnFailure);
-
- return deploymentInfoToVduInstance(deployment);
- }
- catch (Exception e) {
- throw new VduException ("CloudifyUtils (instantiateVDU): Create-and-install-deployment Exception", e);
- }
+ public VduInstance instantiateVdu(CloudInfo cloudInfo, String instanceName, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException {
+ String cloudSiteId = cloudInfo.getCloudSiteId();
+ String tenantId = cloudInfo.getTenantId();
+
+ // Translate the VDU ModelInformation structure to that which is needed for
+ // creating and uploading a blueprint. Use the model customization UUID as
+ // the blueprint identifier.
+
+ String blueprintId = vduModel.getModelCustomizationUUID();
+
+ try {
+
+ if (!isBlueprintLoaded(cloudSiteId, blueprintId)) {
+ logger.debug("Blueprint {} is not loaded. Will upload it now.", blueprintId);
+
+ // Prepare the blueprint inputs. Need the set of blueprint templates and files,
+ // plus the main blueprint name.
+ Map<String, byte[]> blueprintFiles = new HashMap<>();
+ String mainTemplate = "";
+
+ // Add all of the blueprint artifacts from the VDU model
+ List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
+ for (VduArtifact vduArtifact : vduArtifacts) {
+ // Add all artifacts to the blueprint, with one exception.
+ // ENVIRONMENT files will be processed later as additional parameters.
+
+ ArtifactType artifactType = vduArtifact.getType();
+ if (artifactType != ArtifactType.ENVIRONMENT) {
+ blueprintFiles.put(vduArtifact.getName(), vduArtifact.getContent());
+
+ if (artifactType == ArtifactType.MAIN_TEMPLATE) {
+ mainTemplate = vduArtifact.getName();
+ }
+ }
+ }
+
+ // Upload the blueprint package
+ uploadBlueprint(cloudSiteId, blueprintId, mainTemplate, blueprintFiles, false);
+ }
+ } catch (Exception e) {
+ throw new VduException("CloudifyUtils (instantiateVDU): blueprint Exception", e);
+ }
+
+
+ // Next, create and install a new deployment based on the blueprint.
+ // For Cloudify, the deploymentId is specified by the client. Just use the instance name
+ // as the ID.
+
+ try {
+ // Query the Cloudify Deployment object and populate a VduInstance
+ DeploymentInfo deployment =
+ createAndInstallDeployment(cloudSiteId, tenantId, instanceName, blueprintId, inputs, true, // (poll
+ // for
+ // completion)
+ vduModel.getTimeoutMinutes(), rollbackOnFailure);
+
+ return deploymentInfoToVduInstance(deployment);
+ } catch (Exception e) {
+ throw new VduException("CloudifyUtils (instantiateVDU): Create-and-install-deployment Exception", e);
+ }
}
@@ -1297,21 +1199,18 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
* VduPlugin interface for query function.
*/
@Override
- public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
- throws VduException
- {
- String cloudSiteId = cloudInfo.getCloudSiteId();
- String tenantId = cloudInfo.getTenantId();
-
- try {
- // Query the Cloudify Deployment object and populate a VduInstance
- DeploymentInfo deployment = queryDeployment (cloudSiteId, tenantId, instanceId);
-
- return deploymentInfoToVduInstance(deployment);
- }
- catch (Exception e) {
- throw new VduException ("Query VDU Exception", e);
- }
+ public VduInstance queryVdu(CloudInfo cloudInfo, String instanceId) throws VduException {
+ String cloudSiteId = cloudInfo.getCloudSiteId();
+ String tenantId = cloudInfo.getTenantId();
+
+ try {
+ // Query the Cloudify Deployment object and populate a VduInstance
+ DeploymentInfo deployment = queryDeployment(cloudSiteId, tenantId, instanceId);
+
+ return deploymentInfoToVduInstance(deployment);
+ } catch (Exception e) {
+ throw new VduException("Query VDU Exception", e);
+ }
}
@@ -1319,139 +1218,124 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{
* VduPlugin interface for delete function.
*/
@Override
- public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
- throws VduException
- {
- String cloudSiteId = cloudInfo.getCloudSiteId();
- String tenantId = cloudInfo.getTenantId();
-
- try {
- // Uninstall and delete the Cloudify Deployment
- DeploymentInfo deployment = uninstallAndDeleteDeployment (cloudSiteId, tenantId, instanceId, timeoutMinutes);
-
- // Populate a VduInstance based on the deleted Cloudify Deployment object
- return deploymentInfoToVduInstance(deployment);
- }
- catch (Exception e) {
- throw new VduException ("Delete VDU Exception", e);
- }
+ public VduInstance deleteVdu(CloudInfo cloudInfo, String instanceId, int timeoutMinutes) throws VduException {
+ String cloudSiteId = cloudInfo.getCloudSiteId();
+ String tenantId = cloudInfo.getTenantId();
+
+ try {
+ // Uninstall and delete the Cloudify Deployment
+ DeploymentInfo deployment = uninstallAndDeleteDeployment(cloudSiteId, tenantId, instanceId, timeoutMinutes);
+
+ // Populate a VduInstance based on the deleted Cloudify Deployment object
+ return deploymentInfoToVduInstance(deployment);
+ } catch (Exception e) {
+ throw new VduException("Delete VDU Exception", e);
+ }
}
/**
* VduPlugin interface for update function.
*
- * Update is currently not supported in the MsoCloudifyUtils implementation.
- * Just return a VduException.
+ * Update is currently not supported in the MsoCloudifyUtils implementation. Just return a VduException.
*
*/
@Override
- public VduInstance updateVdu (
- CloudInfo cloudInfo,
- String instanceId,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException
- {
- throw new VduException ("CloudifyUtils: updateVDU interface not supported");
+ public VduInstance updateVdu(CloudInfo cloudInfo, String instanceId, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException {
+ throw new VduException("CloudifyUtils: updateVDU interface not supported");
}
/*
* Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
*/
- protected VduInstance deploymentInfoToVduInstance (DeploymentInfo deployment)
- {
- VduInstance vduInstance = new VduInstance();
+ protected VduInstance deploymentInfoToVduInstance(DeploymentInfo deployment) {
+ VduInstance vduInstance = new VduInstance();
- // only one ID in Cloudify, use for both VDU name and ID
- vduInstance.setVduInstanceId(deployment.getId());
- vduInstance.setVduInstanceName(deployment.getId());
+ // only one ID in Cloudify, use for both VDU name and ID
+ vduInstance.setVduInstanceId(deployment.getId());
+ vduInstance.setVduInstanceName(deployment.getId());
- // Copy inputs and outputs
- vduInstance.setInputs(deployment.getInputs());
- vduInstance.setOutputs(deployment.getOutputs());
+ // Copy inputs and outputs
+ vduInstance.setInputs(deployment.getInputs());
+ vduInstance.setOutputs(deployment.getOutputs());
- // Translate the status elements
- vduInstance.setStatus(deploymentStatusToVduStatus (deployment));
+ // Translate the status elements
+ vduInstance.setStatus(deploymentStatusToVduStatus(deployment));
- return vduInstance;
+ return vduInstance;
}
- protected VduStatus deploymentStatusToVduStatus (DeploymentInfo deployment)
- {
- VduStatus vduStatus = new VduStatus();
-
- // Determine the status based on last action & status
- // DeploymentInfo object should be enhanced to report a better status internally.
- DeploymentStatus status = deployment.getStatus();
-
- if (status == null) {
- vduStatus.setState(VduStateType.UNKNOWN);
- }
- else if (status == DeploymentStatus.NOTFOUND) {
- vduStatus.setState(VduStateType.NOTFOUND);
- }
- else if (status == DeploymentStatus.INSTALLED) {
- vduStatus.setState(VduStateType.INSTANTIATED);
- }
- else if (status == DeploymentStatus.CREATED) {
- // Deployment exists but is not installed. This shouldn't really happen,
- // since create + install or uninstall + delete are always done together.
- // But account for it anyway, assuming the operation is still in progress.
- String lastAction = deployment.getLastAction();
- if (lastAction == null)
- vduStatus.setState(VduStateType.INSTANTIATING);
- else
- vduStatus.setState(VduStateType.DELETING);
- }
- else if (status == DeploymentStatus.FAILED) {
- vduStatus.setState(VduStateType.FAILED);
- } else {
- vduStatus.setState(VduStateType.UNKNOWN);
- }
-
- vduStatus.setErrorMessage(deployment.getErrorMessage());
- vduStatus.setLastAction(new PluginAction(deployment.getLastAction(), deployment.getActionStatus(), deployment.getErrorMessage()));
-
- return vduStatus;
+ protected VduStatus deploymentStatusToVduStatus(DeploymentInfo deployment) {
+ VduStatus vduStatus = new VduStatus();
+
+ // Determine the status based on last action & status
+ // DeploymentInfo object should be enhanced to report a better status internally.
+ DeploymentStatus status = deployment.getStatus();
+
+ if (status == null) {
+ vduStatus.setState(VduStateType.UNKNOWN);
+ } else if (status == DeploymentStatus.NOTFOUND) {
+ vduStatus.setState(VduStateType.NOTFOUND);
+ } else if (status == DeploymentStatus.INSTALLED) {
+ vduStatus.setState(VduStateType.INSTANTIATED);
+ } else if (status == DeploymentStatus.CREATED) {
+ // Deployment exists but is not installed. This shouldn't really happen,
+ // since create + install or uninstall + delete are always done together.
+ // But account for it anyway, assuming the operation is still in progress.
+ String lastAction = deployment.getLastAction();
+ if (lastAction == null)
+ vduStatus.setState(VduStateType.INSTANTIATING);
+ else
+ vduStatus.setState(VduStateType.DELETING);
+ } else if (status == DeploymentStatus.FAILED) {
+ vduStatus.setState(VduStateType.FAILED);
+ } else {
+ vduStatus.setState(VduStateType.UNKNOWN);
+ }
+
+ vduStatus.setErrorMessage(deployment.getErrorMessage());
+ vduStatus.setLastAction(new PluginAction(deployment.getLastAction(), deployment.getActionStatus(),
+ deployment.getErrorMessage()));
+
+ return vduStatus;
}
/*
- * Return an OpenstackConfig object as expected by Cloudify Openstack Plug-in.
- * Base the values on the CloudSite definition.
+ * Return an OpenstackConfig object as expected by Cloudify Openstack Plug-in. Base the values on the CloudSite
+ * definition.
*/
- protected OpenstackConfig getOpenstackConfig (CloudSite cloudSite, String tenantId) {
+ protected OpenstackConfig getOpenstackConfig(CloudSite cloudSite, String tenantId) {
OpenstackConfig openstackConfig = new OpenstackConfig();
- openstackConfig.setRegion (cloudSite.getRegionId());
- openstackConfig.setAuthUrl (cloudSite.getIdentityService().getIdentityUrl());
- openstackConfig.setUsername (cloudSite.getIdentityService().getMsoId());
- openstackConfig.setPassword (CryptoUtils.decryptCloudConfigPassword(cloudSite.getIdentityService().getMsoPass()));
- openstackConfig.setTenantName (tenantId);
+ openstackConfig.setRegion(cloudSite.getRegionId());
+ openstackConfig.setAuthUrl(cloudSite.getIdentityService().getIdentityUrl());
+ openstackConfig.setUsername(cloudSite.getIdentityService().getMsoId());
+ openstackConfig
+ .setPassword(CryptoUtils.decryptCloudConfigPassword(cloudSite.getIdentityService().getMsoPass()));
+ openstackConfig.setTenantName(tenantId);
return openstackConfig;
}
/*
- * Return an Azure object as expected by Cloudify Azure Plug-in.
- * Base the values on the CloudSite definition.
+ * Return an Azure object as expected by Cloudify Azure Plug-in. Base the values on the CloudSite definition.
*/
- protected AzureConfig getAzureConfig (CloudSite cloudSite, String tenantId) {
+ protected AzureConfig getAzureConfig(CloudSite cloudSite, String tenantId) {
AzureConfig azureConfig = new AzureConfig();
// TODO: Use adminTenant for now, instead of adding another element
- azureConfig.setSubscriptionId (cloudSite.getIdentityService().getAdminTenant());
- azureConfig.setTenantId (tenantId);
- azureConfig.setClientId (cloudSite.getIdentityService().getMsoId());
- azureConfig.setClientSecret (cloudSite.getIdentityService().getMsoPass());
+ azureConfig.setSubscriptionId(cloudSite.getIdentityService().getAdminTenant());
+ azureConfig.setTenantId(tenantId);
+ azureConfig.setClientId(cloudSite.getIdentityService().getMsoId());
+ azureConfig.setClientSecret(cloudSite.getIdentityService().getMsoPass());
return azureConfig;
}
private void sleep(long time) {
- try {
- Thread.sleep(time);
- } catch (InterruptedException e) {
- logger.debug("Thread interrupted while sleeping!", e);
- Thread.currentThread().interrupt();
- }
+ try {
+ Thread.sleep(time);
+ } catch (InterruptedException e) {
+ logger.debug("Thread interrupted while sleeping!", e);
+ Thread.currentThread().interrupt();
+ }
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/config/beans/PoConfig.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/config/beans/PoConfig.java
index 9995a23668..0a63c0975f 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/config/beans/PoConfig.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/config/beans/PoConfig.java
@@ -24,44 +24,53 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
-@ConfigurationProperties(prefix="org.onap.so.adapters.po")
+@ConfigurationProperties(prefix = "org.onap.so.adapters.po")
public class PoConfig {
- private String retryCodes;
- private int retryDelay;
- private int retryCount;
- private int pollTimeout;
- private int pollInterval;
-
- public String getRetryCodes() {
- return retryCodes;
- }
- public void setRetryCodes(String retryCodes) {
- this.retryCodes = retryCodes;
- }
- public int getRetryDelay() {
- return retryDelay;
- }
- public void setRetryDelay(int retryDelay) {
- this.retryDelay = retryDelay;
- }
- public int getRetryCount() {
- return retryCount;
- }
- public void setRetryCount(int retryCount) {
- this.retryCount = retryCount;
- }
- public int getPollTimeout() {
- return pollTimeout;
- }
- public void setPollTimeout(int pollTimeout) {
- this.pollTimeout = pollTimeout;
- }
- public int getPollInterval() {
- return pollInterval;
- }
- public void setPollInterval(int pollInterval) {
- this.pollInterval = pollInterval;
- }
-
+ private String retryCodes;
+ private int retryDelay;
+ private int retryCount;
+ private int pollTimeout;
+ private int pollInterval;
+
+ public String getRetryCodes() {
+ return retryCodes;
+ }
+
+ public void setRetryCodes(String retryCodes) {
+ this.retryCodes = retryCodes;
+ }
+
+ public int getRetryDelay() {
+ return retryDelay;
+ }
+
+ public void setRetryDelay(int retryDelay) {
+ this.retryDelay = retryDelay;
+ }
+
+ public int getRetryCount() {
+ return retryCount;
+ }
+
+ public void setRetryCount(int retryCount) {
+ this.retryCount = retryCount;
+ }
+
+ public int getPollTimeout() {
+ return pollTimeout;
+ }
+
+ public void setPollTimeout(int pollTimeout) {
+ this.pollTimeout = pollTimeout;
+ }
+
+ public int getPollInterval() {
+ return pollInterval;
+ }
+
+ public void setPollInterval(int pollInterval) {
+ this.pollInterval = pollInterval;
+ }
+
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/HeatCacheEntry.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/HeatCacheEntry.java
index 5eaca976d0..43fb47b414 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/HeatCacheEntry.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/HeatCacheEntry.java
@@ -22,13 +22,11 @@ package org.onap.so.openstack.beans;
import java.io.Serializable;
import java.util.Calendar;
-
import com.woorea.openstack.heat.Heat;
/*
- * An entry in the Heat Client Cache. It saves the Heat client object
- * along with the token expiration. After this interval, this cache
- * item will no longer be used.
+ * An entry in the Heat Client Cache. It saves the Heat client object along with the token expiration. After this
+ * interval, this cache item will no longer be used.
*/
public class HeatCacheEntry implements Serializable {
@@ -38,19 +36,19 @@ public class HeatCacheEntry implements Serializable {
private String token;
private Calendar expires;
- public HeatCacheEntry (String heatUrl, String token, Calendar expires) {
+ public HeatCacheEntry(String heatUrl, String token, Calendar expires) {
this.heatUrl = heatUrl;
this.token = token;
this.expires = expires;
}
- public Heat getHeatClient () {
- Heat heatClient = new Heat (heatUrl);
- heatClient.token (token);
+ public Heat getHeatClient() {
+ Heat heatClient = new Heat(heatUrl);
+ heatClient.token(token);
return heatClient;
}
- public boolean isExpired () {
+ public boolean isExpired() {
if (expires == null) {
return true;
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/NeutronCacheEntry.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/NeutronCacheEntry.java
index d89fd1a73f..7c8b3601c0 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/NeutronCacheEntry.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/NeutronCacheEntry.java
@@ -24,44 +24,43 @@ import java.io.Serializable;
import java.util.Calendar;
/*
- * An entry in the Neutron Client Cache. It saves the Neutron client object
- * along with the token expiration. After this interval, this cache
- * item will no longer be used.
+ * An entry in the Neutron Client Cache. It saves the Neutron client object along with the token expiration. After this
+ * interval, this cache item will no longer be used.
*/
public class NeutronCacheEntry implements Serializable {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- private String neutronUrl;
- private String token;
- private Calendar expires;
+ private String neutronUrl;
+ private String token;
+ private Calendar expires;
- public NeutronCacheEntry (String neutronUrl, String token, Calendar expires) {
- this.neutronUrl = neutronUrl;
- this.token = token;
- this.expires = expires;
- }
-
- public String getNeutronUrl() {
- return neutronUrl;
- }
+ public NeutronCacheEntry(String neutronUrl, String token, Calendar expires) {
+ this.neutronUrl = neutronUrl;
+ this.token = token;
+ this.expires = expires;
+ }
- public void setNeutronUrl(String neutronUrl) {
- this.neutronUrl = neutronUrl;
- }
+ public String getNeutronUrl() {
+ return neutronUrl;
+ }
- public String getToken() {
- return token;
- }
+ public void setNeutronUrl(String neutronUrl) {
+ this.neutronUrl = neutronUrl;
+ }
- public void setToken(String token) {
- this.token = token;
- }
+ public String getToken() {
+ return token;
+ }
- public boolean isExpired() {
- if (expires == null) {
+ public void setToken(String token) {
+ this.token = token;
+ }
+
+ public boolean isExpired() {
+ if (expires == null) {
return true;
}
return System.currentTimeMillis() > expires.getTimeInMillis();
- }
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/VnfRollback.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/VnfRollback.java
index 8da4df28b1..258afc1e75 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/VnfRollback.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/beans/VnfRollback.java
@@ -22,206 +22,231 @@ package org.onap.so.openstack.beans;
import org.onap.so.entity.MsoRequest;
import org.springframework.stereotype.Component;
+
/**
- * Javabean representing the rollback criteria following a "Create VNF"
- * operation. This structure can be passed back to the "Rollback VNF"
- * operation to undo the effects of the create.
+ * Javabean representing the rollback criteria following a "Create VNF" operation. This structure can be passed back to
+ * the "Rollback VNF" operation to undo the effects of the create.
*
*
*/
@Component
public class VnfRollback {
- private String vnfId;
- private String tenantId;
- private String cloudSiteId;
- private String cloudOwner;
- private boolean tenantCreated = false;
- private boolean vnfCreated = false;
- private MsoRequest msoRequest;
- private String volumeGroupName;
- private String volumeGroupId;
- private String requestType;
- private String volumeGroupHeatStackId;
- private String baseGroupHeatStackId;
- private boolean isBase = false;
- private String vfModuleStackId;
- private String modelCustomizationUuid; //NOTE: this is the vfModule's modelCustomizationUuid
- private String mode = "HEAT";
-
- public VnfRollback() {}
-
- /**
- * For backwards compatibility... orchestration mode defaults to HEAT
- *
- * @param vnfId
- * @param tenantId
- * @param cloudSiteId
- * @param cloudOwner
- * @param tenantCreated
- * @param vnfCreated
- * @param msoRequest
- * @param volumeGroupName
- * @param volumeGroupId
- * @param requestType
- * @param modelCustomizationUuid
- */
- public VnfRollback(String vnfId, String tenantId, String cloudOwner, String cloudSiteId,
- boolean tenantCreated, boolean vnfCreated,
- MsoRequest msoRequest,
- String volumeGroupName, String volumeGroupId, String requestType, String modelCustomizationUuid) {
- super();
- this.vnfId = vnfId;
- this.tenantId = tenantId;
- this.cloudSiteId = cloudSiteId;
- this.cloudOwner = cloudOwner;
- this.tenantCreated = tenantCreated;
- this.vnfCreated = vnfCreated;
- this.msoRequest = msoRequest;
- this.volumeGroupName = volumeGroupName;
- this.volumeGroupId = volumeGroupId;
- this.requestType = requestType;
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
-
- /**
- * For backwards compatibility... orchestration mode defaults to HEAT
- *
- * @param vnfId
- * @param tenantId
- * @param cloudSiteId
- * @param cloudOwner
- * @param tenantCreated
- * @param vnfCreated
- * @param msoRequest
- * @param volumeGroupName
- * @param volumeGroupId
- * @param requestType
- * @param modelCustomizationUuid
- */
- public VnfRollback(String vnfId, String tenantId, String cloudOwner, String cloudSiteId,
- boolean tenantCreated, boolean vnfCreated,
- MsoRequest msoRequest, String volumeGroupName, String volumeGroupId,
- String requestType, String modelCustomizationUuid, String orchestrationMode) {
- super();
- this.vnfId = vnfId;
- this.tenantId = tenantId;
- this.cloudSiteId = cloudSiteId;
- this.cloudOwner = cloudOwner;
- this.tenantCreated = tenantCreated;
- this.vnfCreated = vnfCreated;
- this.msoRequest = msoRequest;
- this.volumeGroupName = volumeGroupName;
- this.volumeGroupId = volumeGroupId;
- this.requestType = requestType;
- this.modelCustomizationUuid = modelCustomizationUuid;
- this.mode = orchestrationMode;
- }
-
- public String getVnfId() {
- return vnfId;
- }
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getCloudSiteId() {
- return cloudSiteId;
- }
- public void setCloudSiteId(String cloudId) {
- this.cloudSiteId = cloudId;
- }
+ private String vnfId;
+ private String tenantId;
+ private String cloudSiteId;
+ private String cloudOwner;
+ private boolean tenantCreated = false;
+ private boolean vnfCreated = false;
+ private MsoRequest msoRequest;
+ private String volumeGroupName;
+ private String volumeGroupId;
+ private String requestType;
+ private String volumeGroupHeatStackId;
+ private String baseGroupHeatStackId;
+ private boolean isBase = false;
+ private String vfModuleStackId;
+ private String modelCustomizationUuid; // NOTE: this is the vfModule's modelCustomizationUuid
+ private String mode = "HEAT";
+
+ public VnfRollback() {}
+
+ /**
+ * For backwards compatibility... orchestration mode defaults to HEAT
+ *
+ * @param vnfId
+ * @param tenantId
+ * @param cloudSiteId
+ * @param cloudOwner
+ * @param tenantCreated
+ * @param vnfCreated
+ * @param msoRequest
+ * @param volumeGroupName
+ * @param volumeGroupId
+ * @param requestType
+ * @param modelCustomizationUuid
+ */
+ public VnfRollback(String vnfId, String tenantId, String cloudOwner, String cloudSiteId, boolean tenantCreated,
+ boolean vnfCreated, MsoRequest msoRequest, String volumeGroupName, String volumeGroupId, String requestType,
+ String modelCustomizationUuid) {
+ super();
+ this.vnfId = vnfId;
+ this.tenantId = tenantId;
+ this.cloudSiteId = cloudSiteId;
+ this.cloudOwner = cloudOwner;
+ this.tenantCreated = tenantCreated;
+ this.vnfCreated = vnfCreated;
+ this.msoRequest = msoRequest;
+ this.volumeGroupName = volumeGroupName;
+ this.volumeGroupId = volumeGroupId;
+ this.requestType = requestType;
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ /**
+ * For backwards compatibility... orchestration mode defaults to HEAT
+ *
+ * @param vnfId
+ * @param tenantId
+ * @param cloudSiteId
+ * @param cloudOwner
+ * @param tenantCreated
+ * @param vnfCreated
+ * @param msoRequest
+ * @param volumeGroupName
+ * @param volumeGroupId
+ * @param requestType
+ * @param modelCustomizationUuid
+ */
+ public VnfRollback(String vnfId, String tenantId, String cloudOwner, String cloudSiteId, boolean tenantCreated,
+ boolean vnfCreated, MsoRequest msoRequest, String volumeGroupName, String volumeGroupId, String requestType,
+ String modelCustomizationUuid, String orchestrationMode) {
+ super();
+ this.vnfId = vnfId;
+ this.tenantId = tenantId;
+ this.cloudSiteId = cloudSiteId;
+ this.cloudOwner = cloudOwner;
+ this.tenantCreated = tenantCreated;
+ this.vnfCreated = vnfCreated;
+ this.msoRequest = msoRequest;
+ this.volumeGroupName = volumeGroupName;
+ this.volumeGroupId = volumeGroupId;
+ this.requestType = requestType;
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ this.mode = orchestrationMode;
+ }
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudId) {
+ this.cloudSiteId = cloudId;
+ }
+
public String getCloudOwner() {
return cloudOwner;
}
- public void setCloudOwner(String cloudOwner) {
+
+ public void setCloudOwner(String cloudOwner) {
this.cloudOwner = cloudOwner;
}
- public boolean getTenantCreated() {
- return tenantCreated;
- }
- public void setTenantCreated(boolean tenantCreated) {
- this.tenantCreated = tenantCreated;
- }
- public boolean getVnfCreated() {
- return vnfCreated;
- }
- public void setVnfCreated(boolean vnfCreated) {
- this.vnfCreated = vnfCreated;
- }
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
- public void setMsoRequest (MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
- public String getVolumeGroupName() {
- return this.volumeGroupName;
- }
- public void setVolumeGroupName(String volumeGroupName) {
- this.volumeGroupName = volumeGroupName;
- }
- public String getVolumeGroupId() {
- return this.volumeGroupId;
- }
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
- public String getRequestType() {
- return this.requestType;
- }
- public void setRequestType(String requestType) {
- this.requestType = requestType;
- }
- public String getVolumeGroupHeatStackId() {
- return this.volumeGroupHeatStackId;
- }
- public void setVolumeGroupHeatStackId(String volumeGroupHeatStackId) {
- this.volumeGroupHeatStackId = volumeGroupHeatStackId;
- }
-
- public String getBaseGroupHeatStackId() {
- return this.baseGroupHeatStackId;
- }
- public void setBaseGroupHeatStackId(String baseGroupHeatStackId) {
- this.baseGroupHeatStackId = baseGroupHeatStackId;
- }
-
- public boolean isBase() {
- return this.isBase;
- }
- public void setIsBase(boolean isBase) {
- this.isBase = isBase;
- }
- public String getVfModuleStackId() {
- return this.vfModuleStackId;
- }
- public void setVfModuleStackId(String vfModuleStackId) {
- this.vfModuleStackId = vfModuleStackId;
- }
- public String getModelCustomizationUuid() {
- return this.modelCustomizationUuid;
- }
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
- public String getMode() {
- return this.mode;
- }
- public void setMode(String mode) {
- this.mode = mode;
- }
- @Override
+
+ public boolean getTenantCreated() {
+ return tenantCreated;
+ }
+
+ public void setTenantCreated(boolean tenantCreated) {
+ this.tenantCreated = tenantCreated;
+ }
+
+ public boolean getVnfCreated() {
+ return vnfCreated;
+ }
+
+ public void setVnfCreated(boolean vnfCreated) {
+ this.vnfCreated = vnfCreated;
+ }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
+
+ public String getVolumeGroupName() {
+ return this.volumeGroupName;
+ }
+
+ public void setVolumeGroupName(String volumeGroupName) {
+ this.volumeGroupName = volumeGroupName;
+ }
+
+ public String getVolumeGroupId() {
+ return this.volumeGroupId;
+ }
+
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ public String getRequestType() {
+ return this.requestType;
+ }
+
+ public void setRequestType(String requestType) {
+ this.requestType = requestType;
+ }
+
+ public String getVolumeGroupHeatStackId() {
+ return this.volumeGroupHeatStackId;
+ }
+
+ public void setVolumeGroupHeatStackId(String volumeGroupHeatStackId) {
+ this.volumeGroupHeatStackId = volumeGroupHeatStackId;
+ }
+
+ public String getBaseGroupHeatStackId() {
+ return this.baseGroupHeatStackId;
+ }
+
+ public void setBaseGroupHeatStackId(String baseGroupHeatStackId) {
+ this.baseGroupHeatStackId = baseGroupHeatStackId;
+ }
+
+ public boolean isBase() {
+ return this.isBase;
+ }
+
+ public void setIsBase(boolean isBase) {
+ this.isBase = isBase;
+ }
+
+ public String getVfModuleStackId() {
+ return this.vfModuleStackId;
+ }
+
+ public void setVfModuleStackId(String vfModuleStackId) {
+ this.vfModuleStackId = vfModuleStackId;
+ }
+
+ public String getModelCustomizationUuid() {
+ return this.modelCustomizationUuid;
+ }
+
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ public String getMode() {
+ return this.mode;
+ }
+
+ public void setMode(String mode) {
+ this.mode = mode;
+ }
+
+ @Override
public String toString() {
- return "VnfRollback: cloud=" + cloudSiteId + ", cloudOwner=" + cloudOwner + ", tenant=" + tenantId +
- ", vnf=" + vnfId + ", tenantCreated=" + tenantCreated +
- ", vnfCreated=" + vnfCreated + ", requestType = " + requestType
- + ", modelCustomizationUuid=" + this.modelCustomizationUuid
- + ", mode=" + mode;
- }
+ return "VnfRollback: cloud=" + cloudSiteId + ", cloudOwner=" + cloudOwner + ", tenant=" + tenantId + ", vnf="
+ + vnfId + ", tenantCreated=" + tenantCreated + ", vnfCreated=" + vnfCreated + ", requestType = "
+ + requestType + ", modelCustomizationUuid=" + this.modelCustomizationUuid + ", mode=" + mode;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java
index 5a7f67ea3c..c9a548d5f1 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java
@@ -54,103 +54,94 @@ import org.springframework.stereotype.Component;
@Component("CommonUtils")
public class MsoCommonUtils {
- private static Logger logger = LoggerFactory.getLogger(MsoCommonUtils.class);
+ private static Logger logger = LoggerFactory.getLogger(MsoCommonUtils.class);
- @Autowired
- private PoConfig poConfig;
+ @Autowired
+ private PoConfig poConfig;
/*
- * Method to execute an Openstack command and track its execution time.
- * For the metrics log, a category of "Openstack" is used along with a
- * sub-category that identifies the specific call (using the real
+ * Method to execute an Openstack command and track its execution time. For the metrics log, a category of
+ * "Openstack" is used along with a sub-category that identifies the specific call (using the real
* openstack-java-sdk classname of the OpenStackRequest<T> parameter).
*/
- protected <T> T executeAndRecordOpenstackRequest (OpenStackRequest <T> request) {
+ protected <T> T executeAndRecordOpenstackRequest(OpenStackRequest<T> request) {
- int limit;
+ int limit;
- long start = System.currentTimeMillis ();
- String requestType;
- if (request.getClass ().getEnclosingClass () != null) {
- requestType = request.getClass ().getEnclosingClass ().getSimpleName () + "."
- + request.getClass ().getSimpleName ();
+ long start = System.currentTimeMillis();
+ String requestType;
+ if (request.getClass().getEnclosingClass() != null) {
+ requestType =
+ request.getClass().getEnclosingClass().getSimpleName() + "." + request.getClass().getSimpleName();
} else {
- requestType = request.getClass ().getSimpleName ();
+ requestType = request.getClass().getSimpleName();
}
int retryDelay = poConfig.getRetryDelay();
int retryCount = poConfig.getRetryCount();
- String retryCodes = poConfig.getRetryCodes();
+ String retryCodes = poConfig.getRetryCodes();
// Run the actual command. All exceptions will be propagated
- while (true)
- {
- try {
- return request.execute ();
- }
- catch (OpenStackResponseException e) {
- boolean retry = false;
- if (retryCodes != null ) {
- int code = e.getStatus();
- logger.debug("Config values RetryDelay:{} RetryCount:{} RetryCodes:{} ResponseCode:{}", retryDelay,
- retryCount, retryCodes, code);
- for (String rCode : retryCodes.split (",")) {
- try {
- if (retryCount > 0 && code == Integer.parseInt (rCode))
- {
- retryCount--;
- retry = true;
- logger.debug(
- "OpenStackResponseException ResponseCode: {} request:{} Retry indicated. Attempts remaining:{}",
- code, requestType, retryCount);
- break;
- }
- } catch (NumberFormatException e1) {
- logger.error("{} No retries. Exception in parsing retry code in config:{} {} {}",
- MessageEnum.RA_CONFIG_EXC, rCode, ErrorCode.SchemaError.getValue(),
- "Exception in parsing retry code in config");
+ while (true) {
+ try {
+ return request.execute();
+ } catch (OpenStackResponseException e) {
+ boolean retry = false;
+ if (retryCodes != null) {
+ int code = e.getStatus();
+ logger.debug("Config values RetryDelay:{} RetryCount:{} RetryCodes:{} ResponseCode:{}", retryDelay,
+ retryCount, retryCodes, code);
+ for (String rCode : retryCodes.split(",")) {
+ try {
+ if (retryCount > 0 && code == Integer.parseInt(rCode)) {
+ retryCount--;
+ retry = true;
+ logger.debug(
+ "OpenStackResponseException ResponseCode: {} request:{} Retry indicated. Attempts remaining:{}",
+ code, requestType, retryCount);
+ break;
+ }
+ } catch (NumberFormatException e1) {
+ logger.error("{} No retries. Exception in parsing retry code in config:{} {} {}",
+ MessageEnum.RA_CONFIG_EXC, rCode, ErrorCode.SchemaError.getValue(),
+ "Exception in parsing retry code in config");
+ throw e;
+ }
+ }
+ }
+ if (retry) {
+ try {
+ Thread.sleep(retryDelay * 1000L);
+ } catch (InterruptedException e1) {
+ logger.debug("Thread interrupted while sleeping", e1);
+ Thread.currentThread().interrupt();
+ }
+ } else
+ throw e; // exceeded retryCount or code is not retryable
+ } catch (OpenStackConnectException e) {
+ // Connection to Openstack failed
+ if (retryCount > 0) {
+ retryCount--;
+ logger.debug(" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount);
+ try {
+ Thread.sleep(retryDelay * 1000L);
+ } catch (InterruptedException e1) {
+ logger.debug("Thread interrupted while sleeping", e1);
+ Thread.currentThread().interrupt();
+ }
+ } else
throw e;
- }
- }
- }
- if (retry)
- {
- try {
- Thread.sleep (retryDelay * 1000L);
- } catch (InterruptedException e1) {
- logger.debug ("Thread interrupted while sleeping", e1);
- Thread.currentThread().interrupt();
- }
- }
- else
- throw e; // exceeded retryCount or code is not retryable
- }
- catch (OpenStackConnectException e) {
- // Connection to Openstack failed
- if (retryCount > 0)
- {
- retryCount--;
- logger.debug (" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount);
- try {
- Thread.sleep (retryDelay * 1000L);
- } catch (InterruptedException e1) {
- logger.debug ("Thread interrupted while sleeping", e1);
- Thread.currentThread().interrupt();
- }
- }
- else
- throw e;
-
- }
+
+ }
}
}
/*
- * Convert an Openstack Exception on a Keystone call to an MsoException.
- * This method supports both OpenstackResponseException and OpenStackConnectException.
+ * Convert an Openstack Exception on a Keystone call to an MsoException. This method supports both
+ * OpenstackResponseException and OpenStackConnectException.
*/
- protected MsoException keystoneErrorToMsoException (OpenStackBaseException e, String context) {
+ protected MsoException keystoneErrorToMsoException(OpenStackBaseException e, String context) {
MsoException me = null;
if (e instanceof OpenStackResponseException) {
@@ -158,43 +149,43 @@ public class MsoCommonUtils {
try {
// Failed Keystone calls return an Error entity body.
- Error error = re.getResponse ().getErrorEntity (Error.class);
- logger.error("{} {} Openstack Keystone Error on {}: {}",
- MessageEnum.RA_CONNECTION_EXCEPTION, ErrorCode.DataError.getValue(), context, error);
- me = new MsoOpenstackException (error.getCode (), error.getTitle (), error.getMessage ());
+ Error error = re.getResponse().getErrorEntity(Error.class);
+ logger.error("{} {} Openstack Keystone Error on {}: {}", MessageEnum.RA_CONNECTION_EXCEPTION,
+ ErrorCode.DataError.getValue(), context, error);
+ me = new MsoOpenstackException(error.getCode(), error.getTitle(), error.getMessage());
} catch (Exception e2) {
// Can't parse the body as an "Error". Report the HTTP error
logger.error("{} {} HTTP Error on {}: {}, {}", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, re.getStatus(), re.getMessage(), e2);
- me = new MsoOpenstackException (re.getStatus (), re.getMessage (), "");
+ ErrorCode.DataError.getValue(), context, re.getStatus(), re.getMessage(), e2);
+ me = new MsoOpenstackException(re.getStatus(), re.getMessage(), "");
}
// Add the context of the error
- me.addContext (context);
+ me.addContext(context);
// Generate an alarm for 5XX and higher errors.
- if (re.getStatus () >= 500) {
+ if (re.getStatus() >= 500) {
}
} else if (e instanceof OpenStackConnectException) {
OpenStackConnectException ce = (OpenStackConnectException) e;
- me = new MsoIOException (ce.getMessage ());
- me.addContext (context);
+ me = new MsoIOException(ce.getMessage());
+ me.addContext(context);
// Generate an alarm for all connection errors.
logger.error("{} {} Openstack Keystone connection error on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG,
- ErrorCode.DataError.getValue(), context, e);
+ ErrorCode.DataError.getValue(), context, e);
}
return me;
}
/*
- * Convert an Openstack Exception on a Heat call to an MsoOpenstackException.
- * This method supports both OpenstackResponseException and OpenStackConnectException.
+ * Convert an Openstack Exception on a Heat call to an MsoOpenstackException. This method supports both
+ * OpenstackResponseException and OpenStackConnectException.
*/
- protected MsoException heatExceptionToMsoException (OpenStackBaseException e, String context) {
+ protected MsoException heatExceptionToMsoException(OpenStackBaseException e, String context) {
MsoException me = null;
if (e instanceof OpenStackResponseException) {
@@ -202,49 +193,49 @@ public class MsoCommonUtils {
try {
// Failed Heat calls return an Explanation entity body.
- Explanation explanation = re.getResponse ().getErrorEntity (Explanation.class);
+ Explanation explanation = re.getResponse().getErrorEntity(Explanation.class);
logger.error("{} {} Exception - Openstack Error on {} : {}", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, explanation.toString());
- String fullError = explanation.getExplanation() + ", error.type=" + explanation.getError().getType() + ", error.message=" + explanation.getError().getMessage();
+ ErrorCode.DataError.getValue(), context, explanation.toString());
+ String fullError = explanation.getExplanation() + ", error.type=" + explanation.getError().getType()
+ + ", error.message=" + explanation.getError().getMessage();
logger.debug(fullError);
- me = new MsoOpenstackException (explanation.getCode (),
- explanation.getTitle (),
- //explanation.getExplanation ());
- fullError);
+ me = new MsoOpenstackException(explanation.getCode(), explanation.getTitle(),
+ // explanation.getExplanation ());
+ fullError);
} catch (Exception e2) {
// Couldn't parse the body as an "Explanation". Report the original HTTP error.
logger.error("{} {} Exception - HTTP Error on {}: {}, ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2);
- me = new MsoOpenstackException (re.getStatus (), re.getMessage (), "");
+ ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2);
+ me = new MsoOpenstackException(re.getStatus(), re.getMessage(), "");
}
// Add the context of the error
- me.addContext (context);
+ me.addContext(context);
// Generate an alarm for 5XX and higher errors.
- if (re.getStatus () >= 500) {
+ if (re.getStatus() >= 500) {
}
} else if (e instanceof OpenStackConnectException) {
OpenStackConnectException ce = (OpenStackConnectException) e;
- me = new MsoIOException (ce.getMessage ());
- me.addContext (context);
+ me = new MsoIOException(ce.getMessage());
+ me.addContext(context);
// Generate an alarm for all connection errors.
logger.error("{} {} Openstack Heat connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, e);
+ ErrorCode.DataError.getValue(), context, e);
}
return me;
}
/*
- * Convert an Openstack Exception on a Neutron call to an MsoOpenstackException.
- * This method supports both OpenstackResponseException and OpenStackConnectException.
+ * Convert an Openstack Exception on a Neutron call to an MsoOpenstackException. This method supports both
+ * OpenstackResponseException and OpenStackConnectException.
*/
- protected MsoException neutronExceptionToMsoException (OpenStackBaseException e, String context) {
+ protected MsoException neutronExceptionToMsoException(OpenStackBaseException e, String context) {
MsoException me = null;
if (e instanceof OpenStackResponseException) {
@@ -252,171 +243,165 @@ public class MsoCommonUtils {
try {
// Failed Neutron calls return an NeutronError entity body
- NeutronError error = re.getResponse ().getErrorEntity (NeutronError.class);
+ NeutronError error = re.getResponse().getErrorEntity(NeutronError.class);
logger.error("{} {} Openstack Neutron Error on {} {}", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, error);
- me = new MsoOpenstackException (re.getStatus (), error.getType (), error.getMessage ());
+ ErrorCode.DataError.getValue(), context, error);
+ me = new MsoOpenstackException(re.getStatus(), error.getType(), error.getMessage());
} catch (Exception e2) {
// Couldn't parse body as a NeutronError. Report the HTTP error.
logger.error("{} {} Openstack HTTP Error on {}: {}, {}", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2);
- me = new MsoOpenstackException (re.getStatus (), re.getMessage (), null);
+ ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2);
+ me = new MsoOpenstackException(re.getStatus(), re.getMessage(), null);
}
// Add the context of the error
- me.addContext (context);
+ me.addContext(context);
// Generate an alarm for 5XX and higher errors.
- if (re.getStatus () >= 500) {
+ if (re.getStatus() >= 500) {
}
} else if (e instanceof OpenStackConnectException) {
OpenStackConnectException ce = (OpenStackConnectException) e;
- me = new MsoIOException (ce.getMessage ());
- me.addContext (context);
+ me = new MsoIOException(ce.getMessage());
+ me.addContext(context);
// Generate an alarm for all connection errors.
logger.error("{} {} Openstack Neutron Connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), context, e);
+ ErrorCode.DataError.getValue(), context, e);
}
return me;
}
/*
- * Convert a Java Runtime Exception to an MsoException.
- * All Runtime exceptions will be translated into an MsoAdapterException,
- * which captures internal errors.
- * Alarms will be generated on all such exceptions.
+ * Convert a Java Runtime Exception to an MsoException. All Runtime exceptions will be translated into an
+ * MsoAdapterException, which captures internal errors. Alarms will be generated on all such exceptions.
*/
- protected MsoException runtimeExceptionToMsoException (RuntimeException e, String context) {
- MsoAdapterException me = new MsoAdapterException (e.getMessage (), e);
- me.addContext (context);
- me.setCategory (MsoExceptionCategory.INTERNAL);
+ protected MsoException runtimeExceptionToMsoException(RuntimeException e, String context) {
+ MsoAdapterException me = new MsoAdapterException(e.getMessage(), e);
+ me.addContext(context);
+ me.setCategory(MsoExceptionCategory.INTERNAL);
// Always generate an alarm for internal exceptions
logger.error("{} {} An exception occured on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG,
- ErrorCode.DataError.getValue(), context, e);
+ ErrorCode.DataError.getValue(), context, e);
return me;
}
protected MsoException ioExceptionToMsoException(IOException e, String context) {
- MsoAdapterException me = new MsoAdapterException (e.getMessage (), e);
- me.addContext (context);
- me.setCategory (MsoExceptionCategory.INTERNAL);
+ MsoAdapterException me = new MsoAdapterException(e.getMessage(), e);
+ me.addContext(context);
+ me.setCategory(MsoExceptionCategory.INTERNAL);
// Always generate an alarm for internal exceptions
logger.error("{} {} An exception occured on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG,
- ErrorCode.DataError.getValue(), context, e);
+ ErrorCode.DataError.getValue(), context, e);
return me;
}
- public boolean isNullOrEmpty (String s) {
+ public boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
- protected CreateStackParam createStackParam(String stackName,
- String heatTemplate,
- Map <String, ?> stackInputs,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files,
- Map <String, Object> heatFiles) {
+ protected CreateStackParam createStackParam(String stackName, String heatTemplate, Map<String, ?> stackInputs,
+ int timeoutMinutes, String environment, Map<String, Object> files, Map<String, Object> heatFiles) {
// Create local variables checking to see if we have an environment, nested, get_files
// Could later add some checks to see if it's valid.
boolean haveEnvtVariable = true;
- if (environment == null || "".equalsIgnoreCase (environment.trim ())) {
+ if (environment == null || "".equalsIgnoreCase(environment.trim())) {
haveEnvtVariable = false;
- logger.debug ("createStackParam called with no environment variable");
+ logger.debug("createStackParam called with no environment variable");
} else {
logger.debug("createStackParam called with an environment variable: {}", environment);
}
boolean haveFiles = true;
- if (files == null || files.isEmpty ()) {
+ if (files == null || files.isEmpty()) {
haveFiles = false;
- logger.debug ("createStackParam called with no files / child template ids");
+ logger.debug("createStackParam called with no files / child template ids");
} else {
logger.debug("createStackParam called with {} files / child template ids", files.size());
}
boolean haveHeatFiles = true;
- if (heatFiles == null || heatFiles.isEmpty ()) {
+ if (heatFiles == null || heatFiles.isEmpty()) {
haveHeatFiles = false;
- logger.debug ("createStackParam called with no heatFiles");
+ logger.debug("createStackParam called with no heatFiles");
} else {
logger.debug("createStackParam called with {} heatFiles", heatFiles.size());
}
- //force entire stackInput object to generic Map<String, Object> for openstack compatibility
- ObjectMapper mapper = new ObjectMapper();
- Map<String, Object> normalized = new HashMap<>();
- try {
- normalized = mapper.readValue(mapper.writeValueAsString(stackInputs), new TypeReference<HashMap<String,Object>>() {});
- } catch (IOException e1) {
- logger.debug("could not map json", e1);
- }
-
- // Build up the stack to create
- // Disable auto-rollback, because error reason is lost. Always rollback in the code.
- CreateStackParam stack = new CreateStackParam ();
- stack.setStackName (stackName);
- stack.setTimeoutMinutes (timeoutMinutes);
- stack.setParameters (normalized);
- stack.setTemplate (heatTemplate);
- stack.setDisableRollback (true);
- // TJM New for PO Adapter - add envt variable
- if (haveEnvtVariable) {
- logger.debug("Found an environment variable - value: {}", environment);
- stack.setEnvironment (environment);
- }
- // Now handle nested templates or get_files - have to combine if we have both
- // as they're both treated as "files:" on the stack.
- if (haveFiles && haveHeatFiles) {
- // Let's do this here - not in the bean
- logger.debug ("Found files AND heatFiles - combine and add!");
- Map <String, Object> combinedFiles = new HashMap <> ();
- for (Entry<String, Object> entry : files.entrySet()) {
- combinedFiles.put(entry.getKey(), entry.getValue());
- }
- for (Entry<String, Object> entry : heatFiles.entrySet()) {
- combinedFiles.put(entry.getKey(), entry.getValue());
- }
- stack.setFiles (combinedFiles);
- } else {
- // Handle if we only have one or neither:
- if (haveFiles) {
- logger.debug ("Found files - adding to stack");
- stack.setFiles (files);
- }
- if (haveHeatFiles) {
- logger.debug ("Found heatFiles - adding to stack");
- // the setFiles was modified to handle adding the entries
- stack.setFiles (heatFiles);
- }
- }
-
- // 1802 - attempt to add better formatted printout of request to openstack
- try {
- Map<String, Object> inputs = new HashMap<>();
- for (Entry<String, ?> entry : stackInputs.entrySet()) {
- if (entry.getValue() != null) {
- inputs.put(entry.getKey(), entry.getValue());
- }
- }
- logger.debug("stack request: {}", stack.toString());
- } catch (Exception e) {
- // that's okay - this is a nice-to-have
- logger.debug("(had an issue printing nicely formatted request to debuglog) {}", e.getMessage());
- }
-
- return stack;
+ // force entire stackInput object to generic Map<String, Object> for openstack compatibility
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String, Object> normalized = new HashMap<>();
+ try {
+ normalized = mapper.readValue(mapper.writeValueAsString(stackInputs),
+ new TypeReference<HashMap<String, Object>>() {});
+ } catch (IOException e1) {
+ logger.debug("could not map json", e1);
+ }
+
+ // Build up the stack to create
+ // Disable auto-rollback, because error reason is lost. Always rollback in the code.
+ CreateStackParam stack = new CreateStackParam();
+ stack.setStackName(stackName);
+ stack.setTimeoutMinutes(timeoutMinutes);
+ stack.setParameters(normalized);
+ stack.setTemplate(heatTemplate);
+ stack.setDisableRollback(true);
+ // TJM New for PO Adapter - add envt variable
+ if (haveEnvtVariable) {
+ logger.debug("Found an environment variable - value: {}", environment);
+ stack.setEnvironment(environment);
+ }
+ // Now handle nested templates or get_files - have to combine if we have both
+ // as they're both treated as "files:" on the stack.
+ if (haveFiles && haveHeatFiles) {
+ // Let's do this here - not in the bean
+ logger.debug("Found files AND heatFiles - combine and add!");
+ Map<String, Object> combinedFiles = new HashMap<>();
+ for (Entry<String, Object> entry : files.entrySet()) {
+ combinedFiles.put(entry.getKey(), entry.getValue());
+ }
+ for (Entry<String, Object> entry : heatFiles.entrySet()) {
+ combinedFiles.put(entry.getKey(), entry.getValue());
+ }
+ stack.setFiles(combinedFiles);
+ } else {
+ // Handle if we only have one or neither:
+ if (haveFiles) {
+ logger.debug("Found files - adding to stack");
+ stack.setFiles(files);
+ }
+ if (haveHeatFiles) {
+ logger.debug("Found heatFiles - adding to stack");
+ // the setFiles was modified to handle adding the entries
+ stack.setFiles(heatFiles);
+ }
+ }
+
+ // 1802 - attempt to add better formatted printout of request to openstack
+ try {
+ Map<String, Object> inputs = new HashMap<>();
+ for (Entry<String, ?> entry : stackInputs.entrySet()) {
+ if (entry.getValue() != null) {
+ inputs.put(entry.getKey(), entry.getValue());
+ }
+ }
+ logger.debug("stack request: {}", stack.toString());
+ } catch (Exception e) {
+ // that's okay - this is a nice-to-have
+ logger.debug("(had an issue printing nicely formatted request to debuglog) {}", e.getMessage());
+ }
+
+ return stack;
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java
index 4b53006c21..a21db78cee 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java
@@ -34,210 +34,216 @@ import org.slf4j.LoggerFactory;
public class MsoHeatEnvironmentEntry {
private static final Logger logger = LoggerFactory.getLogger(MsoHeatEnvironmentEntry.class);
-
- private Set<MsoHeatEnvironmentParameter> parameters = null;
- private Set<MsoHeatEnvironmentResource> resources = null;
- private StringBuilder rawEntry = null;
- private boolean valid = true;
- private String errorString = null;
- private StringBuilder resourceRegistryEntryRaw = null;
-
- public MsoHeatEnvironmentEntry() {
- super();
- }
-
- public MsoHeatEnvironmentEntry(StringBuilder sb) {
- this();
- this.rawEntry = sb;
- this.processRawEntry();
- }
-
- private void processRawEntry() {
- try {
- if (this.rawEntry == null || "".equals(this.rawEntry.toString()))
- return;
- byte[] b = this.rawEntry.toString().getBytes();
- MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(b);
- this.parameters = yaml.getParameterListFromEnvt();
- //this.resources = yaml.getResourceListFromEnvt();
- StringBuilder sb = this.getResourceRegistryRawEntry();
- if (sb == null) {
- this.resourceRegistryEntryRaw = new StringBuilder("");
- } else {
- this.resourceRegistryEntryRaw = sb;
- }
- } catch (Exception e) {
- logger.debug("Exception:", e);
- this.valid = false;
- this.errorString = e.getMessage();
- //e.printStackTrace();
- }
- }
-
- public boolean isValid() {
- return this.valid;
- }
- public String getErrorString() {
- return this.errorString;
- }
-
- public Set<MsoHeatEnvironmentParameter> getParameters() {
- return this.parameters;
- }
- public Set<MsoHeatEnvironmentResource> getResources() {
- return this.resources;
- }
- public void setParameters(Set<MsoHeatEnvironmentParameter> paramSet) {
- if (paramSet == null) {
- this.parameters = null;
- } else {
- this.parameters = paramSet;
- }
- }
- public void setResources(Set<MsoHeatEnvironmentResource> resourceSet) {
- if (resourceSet == null) {
- this.resources = null;
- } else {
- this.resources = resourceSet;
- }
- }
-
- public void addParameter(MsoHeatEnvironmentParameter hep) {
- if (this.parameters == null) {
- this.parameters = new HashSet<>();
- }
- this.parameters.add(hep);
- }
- public void addResource(MsoHeatEnvironmentResource her) {
- if (this.resources == null) {
- this.resources = new HashSet<>();
- }
- this.resources.add(her);
- }
-
- public int getNumberOfParameters() {
- return this.parameters.size();
- }
- public int getNumberOfResources() {
- return this.resources.size();
- }
-
- public boolean hasResources() {
- if (this.resources != null && this.resources.size() > 0) {
- return true;
- }
- return false;
- }
- public boolean hasParameters() {
- if (this.parameters != null && this.parameters.size() > 0) {
- return true;
- }
- return false;
- }
-
- public boolean containsParameter(String paramName) {
- boolean contains = false;
- if (this.parameters == null || this.parameters.size() < 1) {
- return false;
- }
- if (this.parameters.contains(new MsoHeatEnvironmentParameter(paramName))) {
- contains = true;
- }
- return contains;
- }
-
- public boolean containsParameter(String paramName, String paramAlias) {
- if (this.containsParameter(paramName)) {
- return true;
- }
- if (this.containsParameter(paramAlias)) {
- return true;
- }
- return false;
- }
-
+
+ private Set<MsoHeatEnvironmentParameter> parameters = null;
+ private Set<MsoHeatEnvironmentResource> resources = null;
+ private StringBuilder rawEntry = null;
+ private boolean valid = true;
+ private String errorString = null;
+ private StringBuilder resourceRegistryEntryRaw = null;
+
+ public MsoHeatEnvironmentEntry() {
+ super();
+ }
+
+ public MsoHeatEnvironmentEntry(StringBuilder sb) {
+ this();
+ this.rawEntry = sb;
+ this.processRawEntry();
+ }
+
+ private void processRawEntry() {
+ try {
+ if (this.rawEntry == null || "".equals(this.rawEntry.toString()))
+ return;
+ byte[] b = this.rawEntry.toString().getBytes();
+ MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(b);
+ this.parameters = yaml.getParameterListFromEnvt();
+ // this.resources = yaml.getResourceListFromEnvt();
+ StringBuilder sb = this.getResourceRegistryRawEntry();
+ if (sb == null) {
+ this.resourceRegistryEntryRaw = new StringBuilder("");
+ } else {
+ this.resourceRegistryEntryRaw = sb;
+ }
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ this.valid = false;
+ this.errorString = e.getMessage();
+ // e.printStackTrace();
+ }
+ }
+
+ public boolean isValid() {
+ return this.valid;
+ }
+
+ public String getErrorString() {
+ return this.errorString;
+ }
+
+ public Set<MsoHeatEnvironmentParameter> getParameters() {
+ return this.parameters;
+ }
+
+ public Set<MsoHeatEnvironmentResource> getResources() {
+ return this.resources;
+ }
+
+ public void setParameters(Set<MsoHeatEnvironmentParameter> paramSet) {
+ if (paramSet == null) {
+ this.parameters = null;
+ } else {
+ this.parameters = paramSet;
+ }
+ }
+
+ public void setResources(Set<MsoHeatEnvironmentResource> resourceSet) {
+ if (resourceSet == null) {
+ this.resources = null;
+ } else {
+ this.resources = resourceSet;
+ }
+ }
+
+ public void addParameter(MsoHeatEnvironmentParameter hep) {
+ if (this.parameters == null) {
+ this.parameters = new HashSet<>();
+ }
+ this.parameters.add(hep);
+ }
+
+ public void addResource(MsoHeatEnvironmentResource her) {
+ if (this.resources == null) {
+ this.resources = new HashSet<>();
+ }
+ this.resources.add(her);
+ }
+
+ public int getNumberOfParameters() {
+ return this.parameters.size();
+ }
+
+ public int getNumberOfResources() {
+ return this.resources.size();
+ }
+
+ public boolean hasResources() {
+ if (this.resources != null && this.resources.size() > 0) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean hasParameters() {
+ if (this.parameters != null && this.parameters.size() > 0) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean containsParameter(String paramName) {
+ boolean contains = false;
+ if (this.parameters == null || this.parameters.size() < 1) {
+ return false;
+ }
+ if (this.parameters.contains(new MsoHeatEnvironmentParameter(paramName))) {
+ contains = true;
+ }
+ return contains;
+ }
+
+ public boolean containsParameter(String paramName, String paramAlias) {
+ if (this.containsParameter(paramName)) {
+ return true;
+ }
+ if (this.containsParameter(paramAlias)) {
+ return true;
+ }
+ return false;
+ }
+
@Override
public String toString() {
- return "MsoHeatEnvironmentEntry{" + "parameters=" + parameters +
- ", resourceRegistryEntryRaw='" + resourceRegistryEntryRaw + '\'' +
- '}';
+ return "MsoHeatEnvironmentEntry{" + "parameters=" + parameters + ", resourceRegistryEntryRaw='"
+ + resourceRegistryEntryRaw + '\'' + '}';
+ }
+
+ public StringBuilder toFullStringExcludeNonParams(Set<HeatTemplateParam> params) {
+ // Basically give back the envt - but exclude the params that aren't in the HeatTemplate
+
+ StringBuilder sb = new StringBuilder();
+ ArrayList<String> paramNameList = new ArrayList<String>(params.size());
+ for (HeatTemplateParam htp : params) {
+ paramNameList.add(htp.getParamName());
+ }
+
+ if (this.hasParameters()) {
+ sb.append("parameters:\n");
+ for (MsoHeatEnvironmentParameter hep : this.parameters) {
+ String paramName = hep.getName();
+ if (paramNameList.contains(paramName)) {
+ // This parameter *is* in the Heat Template - so include it:
+ sb.append(" " + hep.getName() + ": " + hep.getValue() + "\n");
+ // New - 1607 - if any of the params mapped badly - JUST RETURN THE ORIGINAL ENVT!
+ if (hep.getValue().startsWith("_BAD")) {
+ return this.rawEntry;
+ }
+ }
+ }
+ sb.append("\n");
+ }
+ // if (this.hasResources()) {
+ // sb.append("resource_registry:\n");
+ // for (MsoHeatEnvironmentResource her : this.resources) {
+ // sb.append(" \"" + her.getName() + "\": " + her.getValue() + "\n");
+ // }
+ // }
+ sb.append("\n");
+ sb.append(this.resourceRegistryEntryRaw);
+ return sb;
+ }
+
+ public StringBuilder toFullString() {
+ StringBuilder sb = new StringBuilder();
+
+ if (this.hasParameters()) {
+ sb.append("parameters:\n");
+ for (MsoHeatEnvironmentParameter hep : this.parameters) {
+ sb.append(" " + hep.getName() + ": " + hep.getValue() + "\n");
+ }
+ sb.append("\n");
+ }
+ // if (this.hasResources()) {
+ // sb.append("resource_registry:\n");
+ // for (MsoHeatEnvironmentResource her : this.resources) {
+ // sb.append(" \"" + her.getName() + "\": " + her.getValue() + "\n");
+ // }
+ // }
+ sb.append("\n");
+ sb.append(this.resourceRegistryEntryRaw);
+ return sb;
+ }
+
+ public StringBuilder getRawEntry() {
+ return this.rawEntry;
+ }
+
+ private StringBuilder getResourceRegistryRawEntry() {
+
+ if (this.rawEntry == null) {
+ return null;
+ }
+
+ StringBuilder sb = new StringBuilder();
+ int indexOf = this.rawEntry.indexOf("resource_registry:");
+ if (indexOf < 0) { // no resource_registry:
+ return null;
+ }
+ sb.append(this.rawEntry.substring(indexOf));
+ return sb;
}
- public StringBuilder toFullStringExcludeNonParams(Set<HeatTemplateParam> params) {
- // Basically give back the envt - but exclude the params that aren't in the HeatTemplate
-
- StringBuilder sb = new StringBuilder();
- ArrayList<String> paramNameList = new ArrayList<String>(params.size());
- for (HeatTemplateParam htp : params) {
- paramNameList.add(htp.getParamName());
- }
-
- if (this.hasParameters()) {
- sb.append("parameters:\n");
- for (MsoHeatEnvironmentParameter hep : this.parameters) {
- String paramName = hep.getName();
- if (paramNameList.contains(paramName)) {
- // This parameter *is* in the Heat Template - so include it:
- sb.append(" " + hep.getName() + ": " + hep.getValue() + "\n");
- // New - 1607 - if any of the params mapped badly - JUST RETURN THE ORIGINAL ENVT!
- if (hep.getValue().startsWith("_BAD")) {
- return this.rawEntry;
- }
- }
- }
- sb.append("\n");
- }
-// if (this.hasResources()) {
-// sb.append("resource_registry:\n");
-// for (MsoHeatEnvironmentResource her : this.resources) {
-// sb.append(" \"" + her.getName() + "\": " + her.getValue() + "\n");
-// }
-// }
- sb.append("\n");
- sb.append(this.resourceRegistryEntryRaw);
- return sb;
- }
-
- public StringBuilder toFullString() {
- StringBuilder sb = new StringBuilder();
-
- if (this.hasParameters()) {
- sb.append("parameters:\n");
- for (MsoHeatEnvironmentParameter hep : this.parameters) {
- sb.append(" " + hep.getName() + ": " + hep.getValue() + "\n");
- }
- sb.append("\n");
- }
-// if (this.hasResources()) {
-// sb.append("resource_registry:\n");
-// for (MsoHeatEnvironmentResource her : this.resources) {
-// sb.append(" \"" + her.getName() + "\": " + her.getValue() + "\n");
-// }
-// }
- sb.append("\n");
- sb.append(this.resourceRegistryEntryRaw);
- return sb;
- }
-
- public StringBuilder getRawEntry() {
- return this.rawEntry;
- }
-
- private StringBuilder getResourceRegistryRawEntry() {
-
- if (this.rawEntry == null) {
- return null;
- }
-
- StringBuilder sb = new StringBuilder();
- int indexOf = this.rawEntry.indexOf("resource_registry:");
- if (indexOf < 0) { // no resource_registry:
- return null;
- }
- sb.append(this.rawEntry.substring(indexOf));
- return sb;
- }
-
public void setHPAParameters(StringBuilder hpasb) {
try {
MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(hpasb.toString().getBytes());
@@ -252,7 +258,7 @@ public class MsoHeatEnvironmentEntry {
} catch (Exception e) {
logger.debug("Exception:", e);
this.errorString = e.getMessage();
- //e.printStackTrace();
+ // e.printStackTrace();
}
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameter.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameter.java
index 7e4c9d00c4..8b39b27546 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameter.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameter.java
@@ -24,54 +24,59 @@ import java.util.Objects;
public class MsoHeatEnvironmentParameter {
- private String name;
- private String value;
-
- public MsoHeatEnvironmentParameter(String name, String value) {
- super();
- this.name = name;
- this.value = value;
- }
- public MsoHeatEnvironmentParameter(String name) {
- // Allow to initialize with a null value
- this(name, null);
- }
- public MsoHeatEnvironmentParameter() {
- this(null, null);
- }
-
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
-
- public String getValue() {
- return this.value;
- }
- public void setValue(String value) {
- this.value = value;
- }
- public String toString() {
- return this.name + ": " + this.value;
- }
-
- public boolean equals(Object o) {
- if (!(o instanceof MsoHeatEnvironmentParameter)) {
- return false;
- }
- if (this == o) {
- return true;
- }
- MsoHeatEnvironmentParameter hep = (MsoHeatEnvironmentParameter) o;
- // If the name of the parameter is the same, then they're equal
+ private String name;
+ private String value;
+
+ public MsoHeatEnvironmentParameter(String name, String value) {
+ super();
+ this.name = name;
+ this.value = value;
+ }
+
+ public MsoHeatEnvironmentParameter(String name) {
+ // Allow to initialize with a null value
+ this(name, null);
+ }
+
+ public MsoHeatEnvironmentParameter() {
+ this(null, null);
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getValue() {
+ return this.value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public String toString() {
+ return this.name + ": " + this.value;
+ }
+
+ public boolean equals(Object o) {
+ if (!(o instanceof MsoHeatEnvironmentParameter)) {
+ return false;
+ }
+ if (this == o) {
+ return true;
+ }
+ MsoHeatEnvironmentParameter hep = (MsoHeatEnvironmentParameter) o;
+ // If the name of the parameter is the same, then they're equal
return hep.getName().equals(this.getName());
- }
-
- public int hashCode() {
+ }
+
+ public int hashCode() {
return Objects.hashCode(this.name);
- }
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java
index 56bab31880..04c62cc841 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java
@@ -29,71 +29,72 @@ import org.slf4j.LoggerFactory;
public class MsoHeatEnvironmentResource {
private static final Logger logger = LoggerFactory.getLogger(MsoHeatEnvironmentResource.class);
-
- private String name;
- private String value;
-
- public MsoHeatEnvironmentResource(String name, String value) {
- super();
- this.name = name;
- this.value = value;
- }
- public MsoHeatEnvironmentResource(String name) {
- // Allow to initialize with a null value
- this(name, null);
- }
- public MsoHeatEnvironmentResource() {
- this(null, null);
- }
-
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
-
- public String getValue() {
- return this.value;
- }
- public void setValue(String value) {
- this.value = value;
- }
-
- @Override
- public String toString() {
- return "\"" +
- this.name +
- "\": " +
- this.value;
- }
-
- @Override
- public boolean equals(Object o) {
- if (!(o instanceof MsoHeatEnvironmentResource)) {
- return false;
- }
- if (this == o) {
- return true;
- }
- MsoHeatEnvironmentResource her = (MsoHeatEnvironmentResource) o;
- // If the name of the parameter is the same, then they're equal
- if (her.getName().equals(this.getName())) {
- return true;
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- int result = 0;
- try {
- result = this.name.hashCode();
- } catch (Exception e) {
- logger.debug("Exception:", e);
+
+ private String name;
+ private String value;
+
+ public MsoHeatEnvironmentResource(String name, String value) {
+ super();
+ this.name = name;
+ this.value = value;
+ }
+
+ public MsoHeatEnvironmentResource(String name) {
+ // Allow to initialize with a null value
+ this(name, null);
+ }
+
+ public MsoHeatEnvironmentResource() {
+ this(null, null);
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getValue() {
+ return this.value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return "\"" + this.name + "\": " + this.value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof MsoHeatEnvironmentResource)) {
+ return false;
+ }
+ if (this == o) {
+ return true;
+ }
+ MsoHeatEnvironmentResource her = (MsoHeatEnvironmentResource) o;
+ // If the name of the parameter is the same, then they're equal
+ if (her.getName().equals(this.getName())) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = 0;
+ try {
+ result = this.name.hashCode();
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ }
+ return result;
}
- return result;
- }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java
index 300d06b5d1..b54301509f 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java
@@ -38,7 +38,6 @@ import com.woorea.openstack.keystone.Keystone;
import com.woorea.openstack.keystone.model.Access;
import com.woorea.openstack.keystone.model.Authentication;
import com.woorea.openstack.keystone.utils.KeystoneUtils;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -90,7 +89,7 @@ import org.springframework.stereotype.Component;
@Primary
@Component
-public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
+public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin {
private static final String TOKEN_AUTH = "TokenAuth";
@@ -131,136 +130,62 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
/**
- * keep this old method signature here to maintain backwards compatibility. keep others as well.
- * this method does not include environment, files, or heatFiles
+ * keep this old method signature here to maintain backwards compatibility. keep others as well. this method does
+ * not include environment, files, or heatFiles
*/
- public StackInfo createStack (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, ?> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes) throws MsoException {
+ public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes)
+ throws MsoException {
// Just call the new method with the environment & files variable set to null
- return this.createStack (cloudSiteId,
- cloudOwner,
- tenantId,
- stackName,
- null,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- null,
- null,
- null,
- true);
+ return this.createStack(cloudSiteId, cloudOwner, tenantId, stackName, null, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, null, null, null, true);
}
// This method has environment, but not files or heatFiles
- public StackInfo createStack (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, ?> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment) throws MsoException {
+ public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes,
+ String environment) throws MsoException {
// Just call the new method with the files/heatFiles variables set to null
- return this.createStack (cloudSiteId,
- cloudOwner,
- tenantId,
- stackName,
- null,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- environment,
- null,
- null,
- true);
+ return this.createStack(cloudSiteId, cloudOwner, tenantId, stackName, null, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, environment, null, null, true);
}
// This method has environment and files, but not heatFiles.
- public StackInfo createStack (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, ?> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files) throws MsoException {
- return this.createStack (cloudSiteId,
- cloudOwner,
- tenantId,
- stackName,
- null,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- environment,
- files,
- null,
- true);
+ public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes,
+ String environment, Map<String, Object> files) throws MsoException {
+ return this.createStack(cloudSiteId, cloudOwner, tenantId, stackName, null, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, environment, files, null, true);
}
// This method has environment, files, heatfiles
- public StackInfo createStack (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, ?> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files,
- Map <String, Object> heatFiles) throws MsoException {
- return this.createStack (cloudSiteId,
- cloudOwner,
- tenantId,
- stackName,
- null,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- environment,
- files,
- heatFiles,
- true);
+ public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes,
+ String environment, Map<String, Object> files, Map<String, Object> heatFiles) throws MsoException {
+ return this.createStack(cloudSiteId, cloudOwner, tenantId, stackName, null, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, environment, files, heatFiles, true);
}
/**
- * Create a new Stack in the specified cloud location and tenant. The Heat template
- * and parameter map are passed in as arguments, along with the cloud access credentials.
- * It is expected that parameters have been validated and contain at minimum the required
- * parameters for the given template with no extra (undefined) parameters..
+ * Create a new Stack in the specified cloud location and tenant. The Heat template and parameter map are passed in
+ * as arguments, along with the cloud access credentials. It is expected that parameters have been validated and
+ * contain at minimum the required parameters for the given template with no extra (undefined) parameters..
*
- * The Stack name supplied by the caller must be unique in the scope of this tenant.
- * However, it should also be globally unique, as it will be the identifier for the
- * resource going forward in Inventory. This latter is managed by the higher levels
- * invoking this function.
+ * The Stack name supplied by the caller must be unique in the scope of this tenant. However, it should also be
+ * globally unique, as it will be the identifier for the resource going forward in Inventory. This latter is managed
+ * by the higher levels invoking this function.
*
- * The caller may choose to let this function poll Openstack for completion of the
- * stack creation, or may handle polling itself via separate calls to query the status.
- * In either case, a StackInfo object will be returned containing the current status.
- * When polling is enabled, a status of CREATED is expected. When not polling, a
+ * The caller may choose to let this function poll Openstack for completion of the stack creation, or may handle
+ * polling itself via separate calls to query the status. In either case, a StackInfo object will be returned
+ * containing the current status. When polling is enabled, a status of CREATED is expected. When not polling, a
* status of BUILDING is expected.
*
- * An error will be thrown if the requested Stack already exists in the specified
- * Tenant and Cloud.
+ * An error will be thrown if the requested Stack already exists in the specified Tenant and Cloud.
*
- * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as
- * parameters for createStack. If environment is non-null, it will be added to the stack.
- * The nested templates and get_file entries both end up being added to the "files" on the
- * stack. We must combine them before we add them to the stack if they're both non-null.
+ * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as parameters for
+ * createStack. If environment is non-null, it will be added to the stack. The nested templates and get_file entries
+ * both end up being added to the "files" on the stack. We must combine them before we add them to the stack if
+ * they're both non-null.
*
* @param cloudSiteId The cloud (may be a region) in which to create the stack.
* @param cloudOwner the cloud owner of the cloud site in which to create the stack
@@ -280,19 +205,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
*/
@SuppressWarnings("unchecked")
- public StackInfo createStack (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String stackName,
- VduModelInfo vduModel,
- String heatTemplate,
- Map <String, ?> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files,
- Map <String, Object> heatFiles,
- boolean backout) throws MsoException {
+ public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ VduModelInfo vduModel, String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion,
+ int timeoutMinutes, String environment, Map<String, Object> files, Map<String, Object> heatFiles,
+ boolean backout) throws MsoException {
// Take out the multicloud inputs, if present.
for (String key : MsoMulticloudUtils.MULTICLOUD_INPUTS) {
@@ -304,259 +220,265 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
}
}
- CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
+ CreateStackParam stack =
+ createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
// Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
logger.debug("Found: {}", cloudSite);
// Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
// This could throw MsoTenantNotFound or MsoOpenstackException (both propagated)
- Heat heatClient = getHeatClient (cloudSite, tenantId);
+ Heat heatClient = getHeatClient(cloudSite, tenantId);
logger.debug("Found: {}", heatClient);
- logger.debug ("Ready to Create Stack ({}) with input params: {}", heatTemplate, stackInputs);
+ logger.debug("Ready to Create Stack ({}) with input params: {}", heatTemplate, stackInputs);
Stack heatStack = null;
try {
- OpenStackRequest <Stack> request = heatClient.getStacks ().create (stack);
+ OpenStackRequest<Stack> request = heatClient.getStacks().create(stack);
CloudIdentity cloudIdentity = cloudSite.getIdentityService();
- request.header ("X-Auth-User", cloudIdentity.getMsoId ());
- request.header ("X-Auth-Key", CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass ()));
- heatStack = executeAndRecordOpenstackRequest (request);
+ request.header("X-Auth-User", cloudIdentity.getMsoId());
+ request.header("X-Auth-Key", CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass()));
+ heatStack = executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 409) {
- MsoStackAlreadyExists me = new MsoStackAlreadyExists (stackName, tenantId, cloudSiteId);
- me.addContext (CREATE_STACK);
+ if (e.getStatus() == 409) {
+ MsoStackAlreadyExists me = new MsoStackAlreadyExists(stackName, tenantId, cloudSiteId);
+ me.addContext(CREATE_STACK);
throw me;
- } else {
+ } else {
logger.debug("ERROR STATUS = {},\n{}\n{}", e.getStatus(), e.getMessage(), e.getLocalizedMessage());
- throw heatExceptionToMsoException (e, CREATE_STACK);
+ throw heatExceptionToMsoException(e, CREATE_STACK);
}
} catch (OpenStackConnectException e) {
- throw heatExceptionToMsoException (e, CREATE_STACK);
+ throw heatExceptionToMsoException(e, CREATE_STACK);
} catch (RuntimeException e) {
- throw runtimeExceptionToMsoException (e, CREATE_STACK);
+ throw runtimeExceptionToMsoException(e, CREATE_STACK);
}
// Subsequent access by the canonical name "<stack name>/<stack-id>".
// Otherwise, simple query by name returns a 302 redirect.
// NOTE: This is specific to the v1 Orchestration API.
- String canonicalName = stackName + "/" + heatStack.getId ();
+ String canonicalName = stackName + "/" + heatStack.getId();
if (pollForCompletion) {
heatStack = pollStackForCompletion(cloudSiteId, tenantId, stackName, timeoutMinutes, backout, heatClient,
- heatStack, canonicalName);
+ heatStack, canonicalName);
} else {
// Get initial status, since it will have been null after the create.
- heatStack = queryHeatStack (heatClient, canonicalName);
- logger.debug (heatStack.getStackStatus ());
+ heatStack = queryHeatStack(heatClient, canonicalName);
+ logger.debug(heatStack.getStackStatus());
}
return new StackInfoMapper(heatStack).map();
}
- private Stack pollStackForCompletion(String cloudSiteId, String tenantId, String stackName, int timeoutMinutes,
- boolean backout, Heat heatClient, Stack heatStack, String canonicalName)
- throws MsoException, MsoOpenstackException {
- int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
- int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
- int deletePollInterval = createPollInterval;
- int deletePollTimeout = pollTimeout;
- boolean createTimedOut = false;
- StringBuilder stackErrorStatusReason = new StringBuilder("");
- logger.debug("createPollInterval={}, pollTimeout={}", createPollInterval, pollTimeout);
-
- while (true) {
- try {
- heatStack = queryHeatStack (heatClient, canonicalName);
- logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName);
+ private Stack pollStackForCompletion(String cloudSiteId, String tenantId, String stackName, int timeoutMinutes,
+ boolean backout, Heat heatClient, Stack heatStack, String canonicalName)
+ throws MsoException, MsoOpenstackException {
+ int createPollInterval =
+ Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
+ int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
+ int deletePollInterval = createPollInterval;
+ int deletePollTimeout = pollTimeout;
+ boolean createTimedOut = false;
+ StringBuilder stackErrorStatusReason = new StringBuilder("");
+ logger.debug("createPollInterval={}, pollTimeout={}", createPollInterval, pollTimeout);
+
+ while (true) {
try {
- logger.debug("Current stack {}", this.getOutputsAsStringBuilder(heatStack).toString());
- } catch (Exception e) {
- logger.debug("an error occurred trying to print out the current outputs of the stack", e);
- }
-
- if ("CREATE_IN_PROGRESS".equals (heatStack.getStackStatus ())) {
- if (pollTimeout <= 0) {
- logger.error("{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Create stack timeout",
- MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
- heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
- createTimedOut = true;
- break;
- }
- sleep(createPollInterval * 1000L);
- pollTimeout -= createPollInterval;
- logger.debug("pollTimeout remaining: {}", pollTimeout);
- } else {
- stackErrorStatusReason.append("Stack error (" + heatStack.getStackStatus() + "): " + heatStack.getStackStatusReason());
- break;
- }
- } catch (MsoException me) {
- // Cannot query the stack status. Something is wrong.
- // Try to roll back the stack
- if (!backout)
- {
- logger.warn("{} Exception in Create Stack, stack deletion suppressed {}",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
- }
- else
- {
- try {
- logger.debug(
- "Create Stack error - unable to query for stack status - attempting to delete stack: {}"
- + " - This will likely fail and/or we won't be able to query to see if delete worked",
- canonicalName);
- OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName);
- executeAndRecordOpenstackRequest (request);
- boolean deleted = false;
- while (!deleted) {
- try {
- heatStack = queryHeatStack(heatClient, canonicalName);
- if (heatStack != null) {
- logger.debug(heatStack.getStackStatus());
- if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
- if (deletePollTimeout <= 0) {
- logger.error(
- "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout",
+ heatStack = queryHeatStack(heatClient, canonicalName);
+ logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName);
+ try {
+ logger.debug("Current stack {}", this.getOutputsAsStringBuilder(heatStack).toString());
+ } catch (Exception e) {
+ logger.debug("an error occurred trying to print out the current outputs of the stack", e);
+ }
+
+ if ("CREATE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
+ if (pollTimeout <= 0) {
+ logger.error("{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Create stack timeout",
MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
- break;
- } else {
- sleep(deletePollInterval * 1000L);
- deletePollTimeout -= deletePollInterval;
- }
- } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){
- logger.debug("DELETE_COMPLETE for {}", canonicalName);
- deleted = true;
- continue;
- } else {
- //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
- break;
- }
- } else {
- // assume if we can't find it - it's deleted
- logger.debug("heatStack returned null - assume the stack {} has been deleted", canonicalName);
- deleted = true;
- continue;
- }
-
- } catch (Exception e3) {
- // Just log this one. We will report the original exception.
- logger.error("{} Create Stack: Nested exception rolling back stack: {} ",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e3);
- }
- }
- } catch (Exception e2) {
- // Just log this one. We will report the original exception.
- logger.error("{} Create Stack: Nested exception rolling back stack: {} ",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e2);
+ createTimedOut = true;
+ break;
+ }
+ sleep(createPollInterval * 1000L);
+ pollTimeout -= createPollInterval;
+ logger.debug("pollTimeout remaining: {}", pollTimeout);
+ } else {
+ stackErrorStatusReason.append(
+ "Stack error (" + heatStack.getStackStatus() + "): " + heatStack.getStackStatusReason());
+ break;
+ }
+ } catch (MsoException me) {
+ // Cannot query the stack status. Something is wrong.
+ // Try to roll back the stack
+ if (!backout) {
+ logger.warn("{} Exception in Create Stack, stack deletion suppressed {}",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
+ } else {
+ try {
+ logger.debug(
+ "Create Stack error - unable to query for stack status - attempting to delete stack: {}"
+ + " - This will likely fail and/or we won't be able to query to see if delete worked",
+ canonicalName);
+ OpenStackRequest<Void> request = heatClient.getStacks().deleteByName(canonicalName);
+ executeAndRecordOpenstackRequest(request);
+ boolean deleted = false;
+ while (!deleted) {
+ try {
+ heatStack = queryHeatStack(heatClient, canonicalName);
+ if (heatStack != null) {
+ logger.debug(heatStack.getStackStatus());
+ if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
+ if (deletePollTimeout <= 0) {
+ logger.error(
+ "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout",
+ MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId,
+ stackName, heatStack.getStackStatus(),
+ ErrorCode.AvailabilityError.getValue());
+ break;
+ } else {
+ sleep(deletePollInterval * 1000L);
+ deletePollTimeout -= deletePollInterval;
+ }
+ } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())) {
+ logger.debug("DELETE_COMPLETE for {}", canonicalName);
+ deleted = true;
+ continue;
+ } else {
+ // got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and
+ // evaluate
+ break;
+ }
+ } else {
+ // assume if we can't find it - it's deleted
+ logger.debug("heatStack returned null - assume the stack {} has been deleted",
+ canonicalName);
+ deleted = true;
+ continue;
+ }
+
+ } catch (Exception e3) {
+ // Just log this one. We will report the original exception.
+ logger.error("{} Create Stack: Nested exception rolling back stack: {} ",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
+ e3);
+ }
+ }
+ } catch (Exception e2) {
+ // Just log this one. We will report the original exception.
+ logger.error("{} Create Stack: Nested exception rolling back stack: {} ",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e2);
+ }
+ }
+
+ // Propagate the original exception from Stack Query.
+ me.addContext(CREATE_STACK);
+ throw me;
}
- }
-
- // Propagate the original exception from Stack Query.
- me.addContext (CREATE_STACK);
- throw me;
- }
- }
-
- if (!"CREATE_COMPLETE".equals (heatStack.getStackStatus ())) {
- logger.error("{} Create Stack error: Polling complete with non-success status: {}, {} {} ",
- MessageEnum.RA_CREATE_STACK_ERR, heatStack.getStackStatus(), heatStack.getStackStatusReason(),
- ErrorCode.BusinessProcesssError.getValue());
-
- // Rollback the stack creation, since it is in an indeterminate state.
- if (!backout)
- {
- logger.warn(
- "{} Create Stack errored, stack deletion suppressed {} Create Stack error, stack deletion suppressed",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
}
- else
- {
- try {
- logger.debug("Create Stack errored - attempting to DELETE stack: {}", canonicalName);
- logger.debug("deletePollInterval={}, deletePollTimeout={}", deletePollInterval, deletePollTimeout);
- OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName);
- executeAndRecordOpenstackRequest (request);
- boolean deleted = false;
- while (!deleted) {
- try {
- heatStack = queryHeatStack(heatClient, canonicalName);
- if (heatStack != null) {
- logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName);
- if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
- if (deletePollTimeout <= 0) {
- logger.error(
- "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout",
- MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
- heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
- break;
- } else {
- sleep(deletePollInterval * 1000L);
- deletePollTimeout -= deletePollInterval;
- logger.debug("deletePollTimeout remaining: {}", deletePollTimeout);
+
+ if (!"CREATE_COMPLETE".equals(heatStack.getStackStatus())) {
+ logger.error("{} Create Stack error: Polling complete with non-success status: {}, {} {} ",
+ MessageEnum.RA_CREATE_STACK_ERR, heatStack.getStackStatus(), heatStack.getStackStatusReason(),
+ ErrorCode.BusinessProcesssError.getValue());
+
+ // Rollback the stack creation, since it is in an indeterminate state.
+ if (!backout) {
+ logger.warn(
+ "{} Create Stack errored, stack deletion suppressed {} Create Stack error, stack deletion suppressed",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
+ } else {
+ try {
+ logger.debug("Create Stack errored - attempting to DELETE stack: {}", canonicalName);
+ logger.debug("deletePollInterval={}, deletePollTimeout={}", deletePollInterval, deletePollTimeout);
+ OpenStackRequest<Void> request = heatClient.getStacks().deleteByName(canonicalName);
+ executeAndRecordOpenstackRequest(request);
+ boolean deleted = false;
+ while (!deleted) {
+ try {
+ heatStack = queryHeatStack(heatClient, canonicalName);
+ if (heatStack != null) {
+ logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName);
+ if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
+ if (deletePollTimeout <= 0) {
+ logger.error(
+ "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout",
+ MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
+ heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
+ break;
+ } else {
+ sleep(deletePollInterval * 1000L);
+ deletePollTimeout -= deletePollInterval;
+ logger.debug("deletePollTimeout remaining: {}", deletePollTimeout);
+ }
+ } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())) {
+ logger.debug("DELETE_COMPLETE for {}", canonicalName);
+ deleted = true;
+ continue;
+ } else if ("DELETE_FAILED".equals(heatStack.getStackStatus())) {
+ // Warn about this (?) - but still throw the original exception
+ logger.warn(
+ "{} Create Stack errored, stack deletion FAILED {} Create Stack error, stack deletion FAILED",
+ MessageEnum.RA_CREATE_STACK_ERR,
+ ErrorCode.BusinessProcesssError.getValue());
+ logger.debug(
+ "Stack deletion FAILED on a rollback of a create - {}, status={}, reason={}",
+ canonicalName, heatStack.getStackStatus(),
+ heatStack.getStackStatusReason());
+ break;
+ } else {
+ // got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and
+ // evaluate
+ break;
+ }
+ } else {
+ // assume if we can't find it - it's deleted
+ logger.debug("heatStack returned null - assume the stack {} has been deleted",
+ canonicalName);
+ deleted = true;
+ continue;
+ }
+
+ } catch (MsoException me2) {
+ // We got an exception on the delete - don't throw this exception - throw the original -
+ // just log.
+ logger.debug("Exception thrown trying to delete {} on a create->rollback: {} ",
+ canonicalName, me2.getContextMessage(), me2);
+ logger.warn("{} Create Stack errored, then stack deletion FAILED - exception thrown {} {}",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
+ me2.getContextMessage());
+ }
+
+ } // end while !deleted
+ StringBuilder errorContextMessage;
+ if (createTimedOut) {
+ errorContextMessage = new StringBuilder("Stack Creation Timeout");
+ } else {
+ errorContextMessage = stackErrorStatusReason;
+ }
+ if (deleted) {
+ errorContextMessage.append(" - stack successfully deleted");
+ } else {
+ errorContextMessage.append(" - encountered an error trying to delete the stack");
}
- } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){
- logger.debug("DELETE_COMPLETE for {}", canonicalName);
- deleted = true;
- continue;
- } else if ("DELETE_FAILED".equals(heatStack.getStackStatus())) {
- // Warn about this (?) - but still throw the original exception
- logger.warn(
- "{} Create Stack errored, stack deletion FAILED {} Create Stack error, stack deletion FAILED",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue());
- logger.debug("Stack deletion FAILED on a rollback of a create - {}, status={}, reason={}",
- canonicalName, heatStack.getStackStatus(), heatStack.getStackStatusReason());
- break;
- } else {
- //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
- break;
- }
- } else {
- // assume if we can't find it - it's deleted
- logger.debug("heatStack returned null - assume the stack {} has been deleted", canonicalName);
- deleted = true;
- continue;
- }
-
- } catch (MsoException me2) {
- // We got an exception on the delete - don't throw this exception - throw the original - just log.
- logger.debug("Exception thrown trying to delete {} on a create->rollback: {} ", canonicalName,
- me2.getContextMessage(), me2);
- logger.warn("{} Create Stack errored, then stack deletion FAILED - exception thrown {} {}",
- MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(),
- me2.getContextMessage());
- }
-
- } // end while !deleted
- StringBuilder errorContextMessage;
- if (createTimedOut) {
- errorContextMessage = new StringBuilder("Stack Creation Timeout");
- } else {
- errorContextMessage = stackErrorStatusReason;
- }
- if (deleted) {
- errorContextMessage.append(" - stack successfully deleted");
- } else {
- errorContextMessage.append(" - encountered an error trying to delete the stack");
- }
- } catch (Exception e2) {
- // shouldn't happen - but handle
- logger.error("{} Create Stack: Nested exception rolling back stack: {} ", MessageEnum.RA_CREATE_STACK_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e2);
- }
- }
- MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
- me.addContext(CREATE_STACK);
- throw me;
- }
- return heatStack;
- }
+ } catch (Exception e2) {
+ // shouldn't happen - but handle
+ logger.error("{} Create Stack: Nested exception rolling back stack: {} ",
+ MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e2);
+ }
+ }
+ MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
+ me.addContext(CREATE_STACK);
+ throw me;
+ }
+ return heatStack;
+ }
/**
- * Query for a single stack (by Name) in a tenant. This call will always return a
- * StackInfo object. If the stack does not exist, an "empty" StackInfo will be
- * returned - containing only the stack name and a status of NOTFOUND.
+ * Query for a single stack (by Name) in a tenant. This call will always return a StackInfo object. If the stack
+ * does not exist, an "empty" StackInfo will be returned - containing only the stack name and a status of NOTFOUND.
*
* @param tenantId The Openstack ID of the tenant in which to query
* @param cloudSiteId The cloud identifier (may be a region) in which to query
@@ -565,61 +487,60 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
* @return A StackInfo object
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
*/
- public StackInfo queryStack (String cloudSiteId, String cloudOwner, String tenantId, String stackName) throws MsoException {
- logger.debug ("Query HEAT stack: {} in tenant {}", stackName, tenantId);
+ public StackInfo queryStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName)
+ throws MsoException {
+ logger.debug("Query HEAT stack: {} in tenant {}", stackName, tenantId);
// Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
logger.debug("Found: {}", cloudSite.toString());
// Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
Heat heatClient = null;
try {
- heatClient = getHeatClient (cloudSite, tenantId);
+ heatClient = getHeatClient(cloudSite, tenantId);
if (heatClient != null) {
logger.debug("Found: {}", heatClient.toString());
}
} catch (MsoTenantNotFound e) {
// Tenant doesn't exist, so stack doesn't either
- logger.debug ("Tenant with id " + tenantId + "not found.", e);
- return new StackInfo (stackName, HeatStatus.NOTFOUND);
+ logger.debug("Tenant with id " + tenantId + "not found.", e);
+ return new StackInfo(stackName, HeatStatus.NOTFOUND);
} catch (MsoException me) {
// Got an Openstack error. Propagate it
logger.error("{} {} Openstack Exception on Token request: ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.AvailabilityError.getValue(), me);
- me.addContext ("QueryStack");
+ ErrorCode.AvailabilityError.getValue(), me);
+ me.addContext("QueryStack");
throw me;
}
// Query the Stack.
// An MsoException will propagate transparently to the caller.
- Stack heatStack = queryHeatStack (heatClient, stackName);
+ Stack heatStack = queryHeatStack(heatClient, stackName);
if (heatStack == null) {
// Stack does not exist. Return a StackInfo with status NOTFOUND
- return new StackInfo (stackName, HeatStatus.NOTFOUND);
+ return new StackInfo(stackName, HeatStatus.NOTFOUND);
}
return new StackInfoMapper(heatStack).map();
}
/**
- * Delete a stack (by Name/ID) in a tenant. If the stack is not found, it will be
- * considered a successful deletion. The return value is a StackInfo object which
- * contains the current stack status.
+ * Delete a stack (by Name/ID) in a tenant. If the stack is not found, it will be considered a successful deletion.
+ * The return value is a StackInfo object which contains the current stack status.
*
- * The client may choose to let the adapter poll Openstack for completion of the
- * stack deletion, or may handle polling itself via separate query calls. In either
- * case, a StackInfo object will be returned. When polling is enabled, a final
- * status of NOTFOUND is expected. When not polling, a status of DELETING is expected.
+ * The client may choose to let the adapter poll Openstack for completion of the stack deletion, or may handle
+ * polling itself via separate query calls. In either case, a StackInfo object will be returned. When polling is
+ * enabled, a final status of NOTFOUND is expected. When not polling, a status of DELETING is expected.
*
- * There is no rollback from a successful stack deletion. A deletion failure will
- * also result in an undefined stack state - the components may or may not have been
- * all or partially deleted, so the resulting stack must be considered invalid.
+ * There is no rollback from a successful stack deletion. A deletion failure will also result in an undefined stack
+ * state - the components may or may not have been all or partially deleted, so the resulting stack must be
+ * considered invalid.
*
* @param tenantId The Openstack ID of the tenant in which to perform the delete
- * @param cloudOwner the cloud owner of the cloud site in which to delete the stack
+ * @param cloudOwner the cloud owner of the cloud site in which to delete the stack
* @param cloudSiteId The cloud identifier (may be a region) from which to delete the stack.
* @param stackName The name/id of the stack to delete. May be simple or canonical
* @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
@@ -627,40 +548,37 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
* @throws MsoCloudSiteNotFound
*/
- public StackInfo deleteStack (String tenantId,
- String cloudOwner,
- String cloudSiteId,
- String stackName,
- boolean pollForCompletion) throws MsoException {
+ public StackInfo deleteStack(String tenantId, String cloudOwner, String cloudSiteId, String stackName,
+ boolean pollForCompletion) throws MsoException {
// Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
logger.debug("Found: {}", cloudSite.toString());
// Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
Heat heatClient = null;
try {
- heatClient = getHeatClient (cloudSite, tenantId);
+ heatClient = getHeatClient(cloudSite, tenantId);
if (heatClient != null) {
logger.debug("Found: {}", heatClient.toString());
}
} catch (MsoTenantNotFound e) {
// Tenant doesn't exist, so stack doesn't either
- logger.debug ("Tenant with id " + tenantId + "not found.", e);
- return new StackInfo (stackName, HeatStatus.NOTFOUND);
+ logger.debug("Tenant with id " + tenantId + "not found.", e);
+ return new StackInfo(stackName, HeatStatus.NOTFOUND);
} catch (MsoException me) {
// Got an Openstack error. Propagate it
logger.error("{} {} Openstack Exception on Token request: ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.AvailabilityError.getValue(), me);
- me.addContext (DELETE_STACK);
+ ErrorCode.AvailabilityError.getValue(), me);
+ me.addContext(DELETE_STACK);
throw me;
}
// OK if stack not found, perform a query first
- Stack heatStack = queryHeatStack (heatClient, stackName);
- if (heatStack == null || "DELETE_COMPLETE".equals (heatStack.getStackStatus ())) {
+ Stack heatStack = queryHeatStack(heatClient, stackName);
+ if (heatStack == null || "DELETE_COMPLETE".equals(heatStack.getStackStatus())) {
// Not found. Return a StackInfo with status NOTFOUND
- return new StackInfo (stackName, HeatStatus.NOTFOUND);
+ return new StackInfo(stackName, HeatStatus.NOTFOUND);
}
// Delete the stack.
@@ -668,56 +586,56 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
// Use canonical name "<stack name>/<stack-id>" to delete.
// Otherwise, deletion by name returns a 302 redirect.
// NOTE: This is specific to the v1 Orchestration API.
- String canonicalName = heatStack.getStackName () + "/" + heatStack.getId ();
+ String canonicalName = heatStack.getStackName() + "/" + heatStack.getId();
try {
- OpenStackRequest <Void> request = null;
- if(null != heatClient) {
- request = heatClient.getStacks ().deleteByName (canonicalName);
- }
- else {
- logger.debug ("Heat Client is NULL" );
+ OpenStackRequest<Void> request = null;
+ if (null != heatClient) {
+ request = heatClient.getStacks().deleteByName(canonicalName);
+ } else {
+ logger.debug("Heat Client is NULL");
}
- executeAndRecordOpenstackRequest (request);
+ executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 404) {
+ if (e.getStatus() == 404) {
// Not found. We are OK with this. Return a StackInfo with status NOTFOUND
- return new StackInfo (stackName, HeatStatus.NOTFOUND);
+ return new StackInfo(stackName, HeatStatus.NOTFOUND);
} else {
// Convert the OpenStackResponseException to an MsoOpenstackException
- throw heatExceptionToMsoException (e, DELETE_STACK);
+ throw heatExceptionToMsoException(e, DELETE_STACK);
}
} catch (OpenStackConnectException e) {
// Error connecting to Openstack instance. Convert to an MsoException
- throw heatExceptionToMsoException (e, DELETE_STACK);
+ throw heatExceptionToMsoException(e, DELETE_STACK);
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, DELETE_STACK);
+ throw runtimeExceptionToMsoException(e, DELETE_STACK);
}
// Requery the stack for current status.
// It will probably still exist with "DELETE_IN_PROGRESS" status.
- heatStack = queryHeatStack (heatClient, canonicalName);
+ heatStack = queryHeatStack(heatClient, canonicalName);
if (pollForCompletion) {
// Set a timeout on polling
- int pollInterval = Integer.parseInt(this.environment.getProperty(deletePollIntervalProp, "" + deletePollIntervalDefault));
- int pollTimeout = Integer.parseInt(this.environment.getProperty(deletePollTimeoutProp, "" + deletePollIntervalDefault));
+ int pollInterval = Integer
+ .parseInt(this.environment.getProperty(deletePollIntervalProp, "" + deletePollIntervalDefault));
+ int pollTimeout = Integer
+ .parseInt(this.environment.getProperty(deletePollTimeoutProp, "" + deletePollIntervalDefault));
// When querying by canonical name, Openstack returns DELETE_COMPLETE status
// instead of "404" (which would result from query by stack name).
- while (heatStack != null && !"DELETE_COMPLETE".equals (heatStack.getStackStatus ())) {
- logger.debug ("Stack status: {}", heatStack.getStackStatus ());
+ while (heatStack != null && !"DELETE_COMPLETE".equals(heatStack.getStackStatus())) {
+ logger.debug("Stack status: {}", heatStack.getStackStatus());
- if ("DELETE_FAILED".equals (heatStack.getStackStatus ())) {
+ if ("DELETE_FAILED".equals(heatStack.getStackStatus())) {
// Throw a 'special case' of MsoOpenstackException to report the Heat status
- String error = "Stack delete error (" + heatStack.getStackStatus ()
- + "): "
- + heatStack.getStackStatusReason ();
- MsoOpenstackException me = new MsoOpenstackException (0, "", error);
- me.addContext (DELETE_STACK);
+ String error = "Stack delete error (" + heatStack.getStackStatus() + "): "
+ + heatStack.getStackStatusReason();
+ MsoOpenstackException me = new MsoOpenstackException(0, "", error);
+ me.addContext(DELETE_STACK);
// Alarm this condition, stack deletion failed
@@ -727,12 +645,12 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
if (pollTimeout <= 0) {
logger.error("{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Delete Stack Timeout",
- MessageEnum.RA_DELETE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
- heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
+ MessageEnum.RA_DELETE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
+ heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
// Throw a 'special case' of MsoOpenstackException to report the Heat status
- MsoOpenstackException me = new MsoOpenstackException (0, "", "Stack Deletion Timeout");
- me.addContext (DELETE_STACK);
+ MsoOpenstackException me = new MsoOpenstackException(0, "", "Stack Deletion Timeout");
+ me.addContext(DELETE_STACK);
// Alarm this condition, stack deletion failed
@@ -745,26 +663,26 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
pollTimeout -= pollInterval;
logger.debug("pollTimeout remaining: {}", pollTimeout);
- heatStack = queryHeatStack (heatClient, canonicalName);
+ heatStack = queryHeatStack(heatClient, canonicalName);
}
// The stack is gone when this point is reached
- return new StackInfo (stackName, HeatStatus.NOTFOUND);
+ return new StackInfo(stackName, HeatStatus.NOTFOUND);
}
// Return the current status (if not polling, the delete may still be in progress)
StackInfo stackInfo = new StackInfoMapper(heatStack).map();
- stackInfo.setName (stackName);
+ stackInfo.setName(stackName);
return stackInfo;
}
/**
- * Query for all stacks in a tenant site. This call will return a List of StackInfo
- * objects, one for each deployed stack.
+ * Query for all stacks in a tenant site. This call will return a List of StackInfo objects, one for each deployed
+ * stack.
*
- * Note that this is limited to a single site. To ensure that a tenant is truly
- * empty would require looping across all tenant endpoints.
+ * Note that this is limited to a single site. To ensure that a tenant is truly empty would require looping across
+ * all tenant endpoints.
*
* @param tenantId The Openstack ID of the tenant to query
* @param cloudSiteId The cloud identifier (may be a region) in which to query.
@@ -772,101 +690,96 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
* @throws MsoCloudSiteNotFound
*/
- public List <StackInfo> queryAllStacks (String tenantId, String cloudSiteId) throws MsoException {
+ public List<StackInfo> queryAllStacks(String tenantId, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
// Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
- Heat heatClient = getHeatClient (cloudSite, tenantId);
+ Heat heatClient = getHeatClient(cloudSite, tenantId);
try {
- OpenStackRequest <Stacks> request = heatClient.getStacks ().list ();
- Stacks stacks = executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Stacks> request = heatClient.getStacks().list();
+ Stacks stacks = executeAndRecordOpenstackRequest(request);
- List <StackInfo> stackList = new ArrayList <> ();
+ List<StackInfo> stackList = new ArrayList<>();
// Not sure if returns an empty list or null if no stacks exist
if (stacks != null) {
for (Stack stack : stacks) {
- stackList.add (new StackInfoMapper(stack).map());
+ stackList.add(new StackInfoMapper(stack).map());
}
}
return stackList;
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 404) {
+ if (e.getStatus() == 404) {
// Not sure if this can happen, but return an empty list
- logger.debug ("queryAllStacks - stack not found: ");
- return new ArrayList <> ();
+ logger.debug("queryAllStacks - stack not found: ");
+ return new ArrayList<>();
} else {
// Convert the OpenStackResponseException to an MsoOpenstackException
- throw heatExceptionToMsoException (e, QUERY_ALL_STACKS);
+ throw heatExceptionToMsoException(e, QUERY_ALL_STACKS);
}
} catch (OpenStackConnectException e) {
// Error connecting to Openstack instance. Convert to an MsoException
- throw heatExceptionToMsoException (e, QUERY_ALL_STACKS);
+ throw heatExceptionToMsoException(e, QUERY_ALL_STACKS);
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, QUERY_ALL_STACKS);
+ throw runtimeExceptionToMsoException(e, QUERY_ALL_STACKS);
}
}
/**
- * Validate parameters to be passed to Heat template. This method performs
- * three functions:
- * 1. Apply default values to parameters which have them defined
- * 2. Report any required parameters that are missing. This will generate an
- * exception in the caller, since stack create/update operations would fail.
- * 3. Report and remove any extraneous parameters. This will allow clients to
- * pass supersets of parameters and not get errors.
+ * Validate parameters to be passed to Heat template. This method performs three functions: 1. Apply default values
+ * to parameters which have them defined 2. Report any required parameters that are missing. This will generate an
+ * exception in the caller, since stack create/update operations would fail. 3. Report and remove any extraneous
+ * parameters. This will allow clients to pass supersets of parameters and not get errors.
*
- * These functions depend on the HeatTemplate definition from the MSO Catalog DB,
- * along with the input parameter Map. The output is an updated parameter map.
- * If the parameters are invalid for the template, an IllegalArgumentException
- * is thrown.
+ * These functions depend on the HeatTemplate definition from the MSO Catalog DB, along with the input parameter
+ * Map. The output is an updated parameter map. If the parameters are invalid for the template, an
+ * IllegalArgumentException is thrown.
*/
- public Map <String, Object> validateStackParams (Map <String, Object> inputParams,
- HeatTemplate heatTemplate) {
+ public Map<String, Object> validateStackParams(Map<String, Object> inputParams, HeatTemplate heatTemplate) {
// Check that required parameters have been supplied for this template type
StringBuilder missingParams = null;
- List <String> paramList = new ArrayList <> ();
+ List<String> paramList = new ArrayList<>();
// TODO: Enhance DB to support defaults for Heat Template parameters
- for (HeatTemplateParam parm : heatTemplate.getParameters ()) {
- if (parm.isRequired () && !inputParams.containsKey (parm.getParamName ())) {
+ for (HeatTemplateParam parm : heatTemplate.getParameters()) {
+ if (parm.isRequired() && !inputParams.containsKey(parm.getParamName())) {
if (missingParams == null) {
missingParams = new StringBuilder(parm.getParamName());
} else {
missingParams.append("," + parm.getParamName());
}
}
- paramList.add (parm.getParamName ());
+ paramList.add(parm.getParamName());
}
if (missingParams != null) {
// Problem - missing one or more required parameters
String error = "Missing Required inputs for HEAT Template: " + missingParams;
logger.error("{} for HEAT Template {} Missing Required inputs for HEAT Template: {}",
- MessageEnum.RA_MISSING_PARAM, ErrorCode.SchemaError.getValue(), missingParams);
- throw new IllegalArgumentException (error);
+ MessageEnum.RA_MISSING_PARAM, ErrorCode.SchemaError.getValue(), missingParams);
+ throw new IllegalArgumentException(error);
}
// Remove any extraneous parameters (don't throw an error)
- Map <String, Object> updatedParams = new HashMap <> ();
- List <String> extraParams = new ArrayList <> ();
+ Map<String, Object> updatedParams = new HashMap<>();
+ List<String> extraParams = new ArrayList<>();
for (Entry<String, Object> entry : inputParams.entrySet()) {
- if (!paramList.contains(entry.getKey())) {
- // This is not a valid parameter for this template
- extraParams.add(entry.getKey());
- } else {
- updatedParams.put(entry.getKey(), entry.getValue());
- }
+ if (!paramList.contains(entry.getKey())) {
+ // This is not a valid parameter for this template
+ extraParams.add(entry.getKey());
+ } else {
+ updatedParams.put(entry.getKey(), entry.getValue());
+ }
}
- if (!extraParams.isEmpty ()) {
+ if (!extraParams.isEmpty()) {
logger.warn("{} Heat Stack ({}) extra input params received: {} {}", MessageEnum.RA_GENERAL_WARNING,
- heatTemplate.getTemplateName(), extraParams, ErrorCode.DataError.getValue());
+ heatTemplate.getTemplateName(), extraParams, ErrorCode.DataError.getValue());
}
return updatedParams;
@@ -876,637 +789,626 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
// PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
/**
- * Get a Heat client for the Openstack Identity service.
- * This requires a 'member'-level userId + password, which will be retrieved from
- * properties based on the specified cloud Id. The tenant in which to operate
- * must also be provided.
+ * Get a Heat client for the Openstack Identity service. This requires a 'member'-level userId + password, which
+ * will be retrieved from properties based on the specified cloud Id. The tenant in which to operate must also be
+ * provided.
* <p>
- * On successful authentication, the Heat object will be cached for the
- * tenantID + cloudId so that it can be reused without reauthenticating with
- * Openstack every time.
+ * On successful authentication, the Heat object will be cached for the tenantID + cloudId so that it can be reused
+ * without reauthenticating with Openstack every time.
*
* @return an authenticated Heat object
*/
- public Heat getHeatClient (CloudSite cloudSite, String tenantId) throws MsoException {
+ public Heat getHeatClient(CloudSite cloudSite, String tenantId) throws MsoException {
String cloudId = cloudSite.getId();
// For DCP/LCP, the region should be the cloudId.
- String region = cloudSite.getRegionId ();
+ String region = cloudSite.getRegionId();
// Obtain an MSO token for the tenant
CloudIdentity cloudIdentity = cloudSite.getIdentityService();
logger.debug("Found: {}", cloudIdentity.toString());
- MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
+ MsoTenantUtils tenantUtils =
+ tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
logger.debug("keystoneUrl={}", keystoneUrl);
String heatUrl = null;
String tokenId = null;
Calendar expiration = null;
- try {
- if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
- Keystone keystoneTenantClient = new Keystone (keystoneUrl);
- Access access = null;
-
- Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
-
- OpenStackRequest <Access> request = keystoneTenantClient.tokens ()
- .authenticate (credentials).withTenantId (tenantId);
-
- access = executeAndRecordOpenstackRequest (request);
-
- try {
- // Isolate trying to printout the region IDs
- try {
- logger.debug("access={}", access.toString());
- for (Access.Service service : access.getServiceCatalog()) {
- List<Access.Service.Endpoint> endpoints = service.getEndpoints();
- for (Access.Service.Endpoint endpoint : endpoints) {
- logger.debug("AIC returned region={}", endpoint.getRegion());
- }
- }
- } catch (Exception e) {
- logger.debug("Encountered an error trying to printout Access object returned from AIC. {}",
- e.getMessage(), e);
- }
- heatUrl = KeystoneUtils.findEndpointURL (access.getServiceCatalog (), "orchestration", region, "public");
- logger.debug("heatUrl={}, region={}", heatUrl, region);
- } catch (RuntimeException e) {
- // This comes back for not found (probably an incorrect region ID)
- String error = "AIC did not match an orchestration service for: region=" + region + ",cloud=" + cloudIdentity.getIdentityUrl();
- throw new MsoAdapterException (error, e);
- }
- tokenId = access.getToken ().getId ();
- expiration = access.getToken ().getExpires ();
- } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
- try {
- KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "orchestration");
- tokenId = holder.getId();
- expiration = holder.getexpiration();
- heatUrl = holder.getServiceUrl();
- } catch (ServiceEndpointNotFoundException e) {
- // This comes back for not found (probably an incorrect region ID)
- String error = "cloud did not match an orchestration service for: region=" + region + ",cloud=" + cloudIdentity.getIdentityUrl();
- throw new MsoAdapterException (error, e);
- }
- }
- } catch (OpenStackResponseException e) {
- if (e.getStatus () == 401) {
+ try {
+ if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
+ Keystone keystoneTenantClient = new Keystone(keystoneUrl);
+ Access access = null;
+
+ Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
+
+ OpenStackRequest<Access> request =
+ keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId);
+
+ access = executeAndRecordOpenstackRequest(request);
+
+ try {
+ // Isolate trying to printout the region IDs
+ try {
+ logger.debug("access={}", access.toString());
+ for (Access.Service service : access.getServiceCatalog()) {
+ List<Access.Service.Endpoint> endpoints = service.getEndpoints();
+ for (Access.Service.Endpoint endpoint : endpoints) {
+ logger.debug("AIC returned region={}", endpoint.getRegion());
+ }
+ }
+ } catch (Exception e) {
+ logger.debug("Encountered an error trying to printout Access object returned from AIC. {}",
+ e.getMessage(), e);
+ }
+ heatUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "orchestration", region,
+ "public");
+ logger.debug("heatUrl={}, region={}", heatUrl, region);
+ } catch (RuntimeException e) {
+ // This comes back for not found (probably an incorrect region ID)
+ String error = "AIC did not match an orchestration service for: region=" + region + ",cloud="
+ + cloudIdentity.getIdentityUrl();
+ throw new MsoAdapterException(error, e);
+ }
+ tokenId = access.getToken().getId();
+ expiration = access.getToken().getExpires();
+ } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
+ try {
+ KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "orchestration");
+ tokenId = holder.getId();
+ expiration = holder.getexpiration();
+ heatUrl = holder.getServiceUrl();
+ } catch (ServiceEndpointNotFoundException e) {
+ // This comes back for not found (probably an incorrect region ID)
+ String error = "cloud did not match an orchestration service for: region=" + region + ",cloud="
+ + cloudIdentity.getIdentityUrl();
+ throw new MsoAdapterException(error, e);
+ }
+ }
+ } catch (OpenStackResponseException e) {
+ if (e.getStatus() == 401) {
// Authentication error.
- String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId ();
+ String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId();
- throw new MsoAdapterException (error);
+ throw new MsoAdapterException(error);
} else {
- throw keystoneErrorToMsoException (e, TOKEN_AUTH);
+ throw keystoneErrorToMsoException(e, TOKEN_AUTH);
}
} catch (OpenStackConnectException e) {
// Connection to Openstack failed
- MsoIOException me = new MsoIOException (e.getMessage (), e);
- me.addContext (TOKEN_AUTH);
+ MsoIOException me = new MsoIOException(e.getMessage(), e);
+ me.addContext(TOKEN_AUTH);
throw me;
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, TOKEN_AUTH);
+ throw runtimeExceptionToMsoException(e, TOKEN_AUTH);
}
- Heat heatClient = new Heat (heatUrl);
- heatClient.token (tokenId);
+ Heat heatClient = new Heat(heatUrl);
+ heatClient.token(tokenId);
return heatClient;
}
/*
- * Query for a Heat Stack. This function is needed in several places, so
- * a common method is useful. This method takes an authenticated Heat Client
- * (which internally identifies the cloud & tenant to search), and returns
- * a Stack object if found, Null if not found, or an MsoOpenstackException
- * if the Openstack API call fails.
+ * Query for a Heat Stack. This function is needed in several places, so a common method is useful. This method
+ * takes an authenticated Heat Client (which internally identifies the cloud & tenant to search), and returns a
+ * Stack object if found, Null if not found, or an MsoOpenstackException if the Openstack API call fails.
*
- * The stack name may be a simple name or a canonical name ("{name}/{id}").
- * When simple name is used, Openstack always returns a 302 redirect which
- * results in a 2nd request (to the canonical name). Note that query by
- * canonical name for a deleted stack returns a Stack object with status
- * "DELETE_COMPLETE" while query by simple name for a deleted stack returns
- * HTTP 404.
+ * The stack name may be a simple name or a canonical name ("{name}/{id}"). When simple name is used, Openstack
+ * always returns a 302 redirect which results in a 2nd request (to the canonical name). Note that query by
+ * canonical name for a deleted stack returns a Stack object with status "DELETE_COMPLETE" while query by simple
+ * name for a deleted stack returns HTTP 404.
*
* @param heatClient an authenticated Heat client
*
* @param stackName the stack name to query
*
- * @return a Stack object that describes the current stack or null if the
- * requested stack doesn't exist.
+ * @return a Stack object that describes the current stack or null if the requested stack doesn't exist.
*
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
*/
- protected Stack queryHeatStack (Heat heatClient, String stackName) throws MsoException {
+ protected Stack queryHeatStack(Heat heatClient, String stackName) throws MsoException {
if (stackName == null) {
return null;
}
try {
- OpenStackRequest <Stack> request = heatClient.getStacks ().byName (stackName);
- return executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Stack> request = heatClient.getStacks().byName(stackName);
+ return executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- logger.error("Error in Query Stack", e);
- if (e.getStatus () == 404) {
- logger.debug ("queryHeatStack - stack not found: {}", stackName);
+ logger.error("Error in Query Stack", e);
+ if (e.getStatus() == 404) {
+ logger.debug("queryHeatStack - stack not found: {}", stackName);
return null;
} else {
// Convert the OpenStackResponseException to an MsoOpenstackException
- throw heatExceptionToMsoException (e, "QueryStack");
+ throw heatExceptionToMsoException(e, "QueryStack");
}
} catch (OpenStackConnectException e) {
// Connection to Openstack failed
- throw heatExceptionToMsoException (e, "QueryAllStack");
+ throw heatExceptionToMsoException(e, "QueryAllStack");
}
}
- public Map<String, Object> queryStackForOutputs(String cloudSiteId, String cloudOwner,
- String tenantId, String stackName) throws MsoException {
- logger.debug("MsoHeatUtils.queryStackForOutputs)");
- StackInfo heatStack = this.queryStack(cloudSiteId, cloudOwner, tenantId, stackName);
- if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
- return null;
- }
- return heatStack.getOutputs();
- }
-
- public void copyStringOutputsToInputs(Map<String, Object> inputs,
- Map<String, Object> otherStackOutputs, boolean overWrite) {
- if (inputs == null || otherStackOutputs == null)
- return;
- for (String key : otherStackOutputs.keySet()) {
- if (!inputs.containsKey(key)) {
- Object obj = otherStackOutputs.get(key);
- if (obj instanceof String) {
- inputs.put(key, (String) otherStackOutputs.get(key));
- } else if (obj instanceof JsonNode ){
- // This is a bit of mess - but I think it's the least impacting
- // let's convert it BACK to a string - then it will get converted back later
- try {
- String str = this.convertNode((JsonNode) obj);
- inputs.put(key, str);
- } catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode {} ", key, e);
- //effect here is this value will not have been copied to the inputs - and therefore will error out downstream
- }
- } else if (obj instanceof java.util.LinkedHashMap) {
- logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
- try {
- String str = JSON_MAPPER.writeValueAsString(obj);
- inputs.put(key, str);
- } catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap {} ", key, e);
- }
- } else if (obj instanceof Integer) {
- try {
- String str = "" + obj;
- inputs.put(key, str);
- } catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer {} ", key, e);
- }
- } else {
- try {
- String str = obj.toString();
- inputs.put(key, str);
- } catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for Other {} ({}) ", key, e.getMessage(), e);
- //effect here is this value will not have been copied to the inputs - and therefore will error out downstream
- }
- }
- }
- }
- return;
- }
- public StringBuilder requestToStringBuilder(CreateStackParam stack) {
- StringBuilder sb = new StringBuilder();
- sb.append("Stack:\n");
- sb.append("\tStackName: " + stack.getStackName());
- sb.append("\tTemplateUrl: " + stack.getTemplateUrl());
- sb.append("\tTemplate: " + stack.getTemplate());
- sb.append("\tEnvironment: " + stack.getEnvironment());
- sb.append("\tTimeout: " + stack.getTimeoutMinutes());
- sb.append("\tParameters:\n");
- Map<String, Object> params = stack.getParameters();
- if (params == null || params.size() < 1) {
- sb.append("\nNONE");
- } else {
- for (String key : params.keySet()) {
- if (params.get(key) instanceof String) {
- sb.append("\n").append(key).append("=").append((String) params.get(key));
- } else if (params.get(key) instanceof JsonNode) {
- String jsonStringOut = this.convertNode((JsonNode)params.get(key));
- sb.append("\n").append(key).append("=").append(jsonStringOut);
- } else if (params.get(key) instanceof Integer) {
- String integerOut = "" + params.get(key);
- sb.append("\n").append(key).append("=").append(integerOut);
-
- } else {
- try {
- String str = params.get(key).toString();
- sb.append("\n").append(key).append("=").append(str);
- } catch (Exception e) {
- logger.debug("Exception :", e);
- }
- }
- }
- }
- return sb;
- }
-
- private String convertNode(final JsonNode node) {
- try {
- final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
- final String json = JSON_MAPPER.writeValueAsString(obj);
- return json;
- } catch (Exception e) {
- logger.debug("Error converting json to string {} ", e.getMessage(), e);
+ public Map<String, Object> queryStackForOutputs(String cloudSiteId, String cloudOwner, String tenantId,
+ String stackName) throws MsoException {
+ logger.debug("MsoHeatUtils.queryStackForOutputs)");
+ StackInfo heatStack = this.queryStack(cloudSiteId, cloudOwner, tenantId, stackName);
+ if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
+ return null;
+ }
+ return heatStack.getOutputs();
+ }
+
+ public void copyStringOutputsToInputs(Map<String, Object> inputs, Map<String, Object> otherStackOutputs,
+ boolean overWrite) {
+ if (inputs == null || otherStackOutputs == null)
+ return;
+ for (String key : otherStackOutputs.keySet()) {
+ if (!inputs.containsKey(key)) {
+ Object obj = otherStackOutputs.get(key);
+ if (obj instanceof String) {
+ inputs.put(key, (String) otherStackOutputs.get(key));
+ } else if (obj instanceof JsonNode) {
+ // This is a bit of mess - but I think it's the least impacting
+ // let's convert it BACK to a string - then it will get converted back later
+ try {
+ String str = this.convertNode((JsonNode) obj);
+ inputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode {} ", key, e);
+ // effect here is this value will not have been copied to the inputs - and therefore will error
+ // out downstream
+ }
+ } else if (obj instanceof java.util.LinkedHashMap) {
+ logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
+ try {
+ String str = JSON_MAPPER.writeValueAsString(obj);
+ inputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap {} ", key, e);
+ }
+ } else if (obj instanceof Integer) {
+ try {
+ String str = "" + obj;
+ inputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer {} ", key, e);
+ }
+ } else {
+ try {
+ String str = obj.toString();
+ inputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for Other {} ({}) ", key,
+ e.getMessage(), e);
+ // effect here is this value will not have been copied to the inputs - and therefore will error
+ // out downstream
+ }
+ }
+ }
+ }
+ return;
+ }
+
+ public StringBuilder requestToStringBuilder(CreateStackParam stack) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Stack:\n");
+ sb.append("\tStackName: " + stack.getStackName());
+ sb.append("\tTemplateUrl: " + stack.getTemplateUrl());
+ sb.append("\tTemplate: " + stack.getTemplate());
+ sb.append("\tEnvironment: " + stack.getEnvironment());
+ sb.append("\tTimeout: " + stack.getTimeoutMinutes());
+ sb.append("\tParameters:\n");
+ Map<String, Object> params = stack.getParameters();
+ if (params == null || params.size() < 1) {
+ sb.append("\nNONE");
+ } else {
+ for (String key : params.keySet()) {
+ if (params.get(key) instanceof String) {
+ sb.append("\n").append(key).append("=").append((String) params.get(key));
+ } else if (params.get(key) instanceof JsonNode) {
+ String jsonStringOut = this.convertNode((JsonNode) params.get(key));
+ sb.append("\n").append(key).append("=").append(jsonStringOut);
+ } else if (params.get(key) instanceof Integer) {
+ String integerOut = "" + params.get(key);
+ sb.append("\n").append(key).append("=").append(integerOut);
+
+ } else {
+ try {
+ String str = params.get(key).toString();
+ sb.append("\n").append(key).append("=").append(str);
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ }
+ }
+ }
+ }
+ return sb;
+ }
+
+ private String convertNode(final JsonNode node) {
+ try {
+ final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
+ final String json = JSON_MAPPER.writeValueAsString(obj);
+ return json;
+ } catch (Exception e) {
+ logger.debug("Error converting json to string {} ", e.getMessage(), e);
+ }
+ return "[Error converting json to string]";
+ }
+
+
+ protected StringBuilder getOutputsAsStringBuilder(Stack heatStack) {
+ // This should only be used as a utility to print out the stack outputs
+ // to the log
+ StringBuilder sb = new StringBuilder("");
+ if (heatStack == null) {
+ sb.append("(heatStack is null)");
+ return sb;
+ }
+ List<Output> outputList = heatStack.getOutputs();
+ if (outputList == null || outputList.isEmpty()) {
+ sb.append("(outputs is empty)");
+ return sb;
+ }
+ Map<String, Object> outputs = new HashMap<>();
+ for (Output outputItem : outputList) {
+ outputs.put(outputItem.getOutputKey(), outputItem.getOutputValue());
+ }
+ int counter = 0;
+ sb.append("OUTPUTS:\n");
+ for (String key : outputs.keySet()) {
+ sb.append("outputs[").append(counter++).append("]: ").append(key).append("=");
+ Object obj = outputs.get(key);
+ if (obj instanceof String) {
+ sb.append((String) obj).append(" (a string)");
+ } else if (obj instanceof JsonNode) {
+ sb.append(this.convertNode((JsonNode) obj)).append(" (a JsonNode)");
+ } else if (obj instanceof java.util.LinkedHashMap) {
+ try {
+ String str = JSON_MAPPER.writeValueAsString(obj);
+ sb.append(str).append(" (a java.util.LinkedHashMap)");
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ sb.append("(a LinkedHashMap value that would not convert nicely)");
+ }
+ } else if (obj instanceof Integer) {
+ String str = "";
+ try {
+ str = obj.toString() + " (an Integer)\n";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(an Integer unable to call .toString() on)";
+ }
+ sb.append(str);
+ } else if (obj instanceof ArrayList) {
+ String str = "";
+ try {
+ str = obj.toString() + " (an ArrayList)";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(an ArrayList unable to call .toString() on?)";
+ }
+ sb.append(str);
+ } else if (obj instanceof Boolean) {
+ String str = "";
+ try {
+ str = obj.toString() + " (a Boolean)";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(an Boolean unable to call .toString() on?)";
+ }
+ sb.append(str);
+ } else {
+ String str = "";
+ try {
+ str = obj.toString() + " (unknown Object type)";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(a value unable to call .toString() on?)";
+ }
+ sb.append(str);
+ }
+ sb.append("\n");
+ }
+ sb.append("[END]");
+ return sb;
+ }
+
+
+ public void copyBaseOutputsToInputs(Map<String, Object> inputs, Map<String, Object> otherStackOutputs,
+ List<String> paramNames, Map<String, String> aliases) {
+ if (inputs == null || otherStackOutputs == null)
+ return;
+ for (String key : otherStackOutputs.keySet()) {
+ if (paramNames != null) {
+ if (!paramNames.contains(key) && !aliases.containsKey(key)) {
+ logger.debug("\tParameter {} is NOT defined to be in the template - do not copy to inputs", key);
+ continue;
+ }
+ if (aliases.containsKey(key)) {
+ logger.debug("Found an alias! Will move {} to {}", key, aliases.get(key));
+ Object obj = otherStackOutputs.get(key);
+ key = aliases.get(key);
+ otherStackOutputs.put(key, obj);
+ }
+ }
+ if (!inputs.containsKey(key)) {
+ Object obj = otherStackOutputs.get(key);
+ logger.debug("\t**Adding {} to inputs (.toString()={}", key, obj.toString());
+ if (obj instanceof String) {
+ logger.debug("\t\t**A String");
+ inputs.put(key, obj);
+ } else if (obj instanceof Integer) {
+ logger.debug("\t\t**An Integer");
+ inputs.put(key, obj);
+ } else if (obj instanceof JsonNode) {
+ logger.debug("\t\t**A JsonNode");
+ inputs.put(key, obj);
+ } else if (obj instanceof Boolean) {
+ logger.debug("\t\t**A Boolean");
+ inputs.put(key, obj);
+ } else if (obj instanceof java.util.LinkedHashMap) {
+ logger.debug("\t\t**A java.util.LinkedHashMap **");
+ inputs.put(key, obj);
+ } else if (obj instanceof java.util.ArrayList) {
+ logger.debug("\t\t**An ArrayList");
+ inputs.put(key, obj);
+ } else {
+ logger.debug("\t\t**UNKNOWN OBJECT TYPE");
+ inputs.put(key, obj);
+ }
+ } else {
+ logger.debug("key={} is already in the inputs - will not overwrite", key);
+ }
+ }
+ return;
+ }
+
+ public List<String> convertCdlToArrayList(String cdl) {
+ String cdl2 = cdl.trim();
+ String cdl3;
+ if (cdl2.startsWith("[") && cdl2.endsWith("]")) {
+ cdl3 = cdl2.substring(1, cdl2.lastIndexOf("]"));
+ } else {
+ cdl3 = cdl2;
+ }
+ return new ArrayList<>(Arrays.asList(cdl3.split(",")));
}
- return "[Error converting json to string]";
- }
-
-
- protected StringBuilder getOutputsAsStringBuilder(Stack heatStack) {
- // This should only be used as a utility to print out the stack outputs
- // to the log
- StringBuilder sb = new StringBuilder("");
- if (heatStack == null) {
- sb.append("(heatStack is null)");
- return sb;
- }
- List<Output> outputList = heatStack.getOutputs();
- if (outputList == null || outputList.isEmpty()) {
- sb.append("(outputs is empty)");
- return sb;
- }
- Map<String, Object> outputs = new HashMap<>();
- for (Output outputItem : outputList) {
- outputs.put(outputItem.getOutputKey(), outputItem.getOutputValue());
- }
- int counter = 0;
- sb.append("OUTPUTS:\n");
- for (String key : outputs.keySet()) {
- sb.append("outputs[").append(counter++).append("]: ").append(key).append("=");
- Object obj = outputs.get(key);
- if (obj instanceof String) {
- sb.append((String) obj).append(" (a string)");
- } else if (obj instanceof JsonNode) {
- sb.append(this.convertNode((JsonNode) obj)).append(" (a JsonNode)");
- } else if (obj instanceof java.util.LinkedHashMap) {
- try {
- String str = JSON_MAPPER.writeValueAsString(obj);
- sb.append(str).append(" (a java.util.LinkedHashMap)");
- } catch (Exception e) {
- logger.debug("Exception :", e);
- sb.append("(a LinkedHashMap value that would not convert nicely)");
- }
- } else if (obj instanceof Integer) {
- String str = "";
- try {
- str = obj.toString() + " (an Integer)\n";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(an Integer unable to call .toString() on)";
- }
- sb.append(str);
- } else if (obj instanceof ArrayList) {
- String str = "";
- try {
- str = obj.toString() + " (an ArrayList)";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(an ArrayList unable to call .toString() on?)";
- }
- sb.append(str);
- } else if (obj instanceof Boolean) {
- String str = "";
- try {
- str = obj.toString() + " (a Boolean)";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(an Boolean unable to call .toString() on?)";
- }
- sb.append(str);
- }
- else {
- String str = "";
- try {
- str = obj.toString() + " (unknown Object type)";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(a value unable to call .toString() on?)";
- }
- sb.append(str);
- }
- sb.append("\n");
- }
- sb.append("[END]");
- return sb;
- }
-
-
- public void copyBaseOutputsToInputs(Map<String, Object> inputs,
- Map<String, Object> otherStackOutputs, List<String> paramNames, Map<String, String> aliases) {
- if (inputs == null || otherStackOutputs == null)
- return;
- for (String key : otherStackOutputs.keySet()) {
- if (paramNames != null) {
- if (!paramNames.contains(key) && !aliases.containsKey(key)) {
- logger.debug("\tParameter {} is NOT defined to be in the template - do not copy to inputs", key);
- continue;
- }
- if (aliases.containsKey(key)) {
- logger.debug("Found an alias! Will move {} to {}", key, aliases.get(key));
- Object obj = otherStackOutputs.get(key);
- key = aliases.get(key);
- otherStackOutputs.put(key, obj);
- }
- }
- if (!inputs.containsKey(key)) {
- Object obj = otherStackOutputs.get(key);
- logger.debug("\t**Adding {} to inputs (.toString()={}", key, obj.toString());
- if (obj instanceof String) {
- logger.debug("\t\t**A String");
- inputs.put(key, obj);
- } else if (obj instanceof Integer) {
- logger.debug("\t\t**An Integer");
- inputs.put(key, obj);
- } else if (obj instanceof JsonNode) {
- logger.debug("\t\t**A JsonNode");
- inputs.put(key, obj);
- } else if (obj instanceof Boolean) {
- logger.debug("\t\t**A Boolean");
- inputs.put(key, obj);
- } else if (obj instanceof java.util.LinkedHashMap) {
- logger.debug("\t\t**A java.util.LinkedHashMap **");
- inputs.put(key, obj);
- } else if (obj instanceof java.util.ArrayList) {
- logger.debug("\t\t**An ArrayList");
- inputs.put(key, obj);
- } else {
- logger.debug("\t\t**UNKNOWN OBJECT TYPE");
- inputs.put(key, obj);
- }
- } else {
- logger.debug("key={} is already in the inputs - will not overwrite", key);
- }
- }
- return;
- }
-
- public List<String> convertCdlToArrayList(String cdl) {
- String cdl2 = cdl.trim();
- String cdl3;
- if (cdl2.startsWith("[") && cdl2.endsWith("]")) {
- cdl3 = cdl2.substring(1, cdl2.lastIndexOf("]"));
- } else {
- cdl3 = cdl2;
- }
- return new ArrayList<>(Arrays.asList(cdl3.split(",")));
- }
/**
- * New with 1707 - this method will convert all the String *values* of the inputs
- * to their "actual" object type (based on the param type: in the db - which comes from the template):
- * (heat variable type) -> java Object type
- * string -> String
- * number -> Integer
- * json -> marshal object to json
- * comma_delimited_list -> ArrayList
- * boolean -> Boolean
- * if any of the conversions should fail, we will default to adding it to the inputs
- * as a string - see if Openstack can handle it.
- * Also, will remove any params that are extra.
- * Any aliases will be converted to their appropriate name (anyone use this feature?)
+ * New with 1707 - this method will convert all the String *values* of the inputs to their "actual" object type
+ * (based on the param type: in the db - which comes from the template): (heat variable type) -> java Object type
+ * string -> String number -> Integer json -> marshal object to json comma_delimited_list -> ArrayList boolean ->
+ * Boolean if any of the conversions should fail, we will default to adding it to the inputs as a string - see if
+ * Openstack can handle it. Also, will remove any params that are extra. Any aliases will be converted to their
+ * appropriate name (anyone use this feature?)
+ *
* @param inputs - the Map<String, String> of the inputs received on the request
* @param template the HeatTemplate object - this is so we can also verify if the param is valid for this template
* @return HashMap<String, Object> of the inputs, cleaned and converted
*/
- public Map<String, Object> convertInputMap(Map<String, Object> inputs, HeatTemplate template) {
- HashMap<String, Object> newInputs = new HashMap<>();
- HashMap<String, HeatTemplateParam> params = new HashMap<>();
- HashMap<String, HeatTemplateParam> paramAliases = new HashMap<>();
-
- if (inputs == null) {
- logger.debug("convertInputMap - inputs is null - nothing to do here");
- return new HashMap<>();
- }
-
- logger.debug("convertInputMap in MsoHeatUtils called, with {} inputs, and template {}", inputs.size(),
- template.getArtifactUuid());
- try {
- logger.debug(template.toString());
- Set<HeatTemplateParam> paramSet = template.getParameters();
- logger.debug("paramSet has {} entries", paramSet.size());
- } catch (Exception e) {
- logger.debug("Exception occurred in convertInputMap {} :", e.getMessage(), e);
- }
-
- for (HeatTemplateParam htp : template.getParameters()) {
- logger.debug("Adding {}", htp.getParamName());
- params.put(htp.getParamName(), htp);
- if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) {
- logger.debug("\tFound ALIAS {} -> {}", htp.getParamName(), htp.getParamAlias());
- paramAliases.put(htp.getParamAlias(), htp);
- }
- }
- logger.debug("Now iterate through the inputs...");
- for (String key : inputs.keySet()) {
- logger.debug("key={}", key);
- boolean alias = false;
- String realName = null;
- if (!params.containsKey(key)) {
- logger.debug("{} is not a parameter in the template! - check for an alias", key);
- // add check here for an alias
- if (!paramAliases.containsKey(key)) {
- logger.debug("The parameter {} is in the inputs, but it's not a parameter for this template - omit", key);
- continue;
- } else {
- alias = true;
- realName = paramAliases.get(key).getParamName();
- logger.debug("FOUND AN ALIAS! Will use {} in lieu of give key/alias {}", realName, key);
+ public Map<String, Object> convertInputMap(Map<String, Object> inputs, HeatTemplate template) {
+ HashMap<String, Object> newInputs = new HashMap<>();
+ HashMap<String, HeatTemplateParam> params = new HashMap<>();
+ HashMap<String, HeatTemplateParam> paramAliases = new HashMap<>();
+
+ if (inputs == null) {
+ logger.debug("convertInputMap - inputs is null - nothing to do here");
+ return new HashMap<>();
+ }
+
+ logger.debug("convertInputMap in MsoHeatUtils called, with {} inputs, and template {}", inputs.size(),
+ template.getArtifactUuid());
+ try {
+ logger.debug(template.toString());
+ Set<HeatTemplateParam> paramSet = template.getParameters();
+ logger.debug("paramSet has {} entries", paramSet.size());
+ } catch (Exception e) {
+ logger.debug("Exception occurred in convertInputMap {} :", e.getMessage(), e);
+ }
+
+ for (HeatTemplateParam htp : template.getParameters()) {
+ logger.debug("Adding {}", htp.getParamName());
+ params.put(htp.getParamName(), htp);
+ if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) {
+ logger.debug("\tFound ALIAS {} -> {}", htp.getParamName(), htp.getParamAlias());
+ paramAliases.put(htp.getParamAlias(), htp);
+ }
+ }
+ logger.debug("Now iterate through the inputs...");
+ for (String key : inputs.keySet()) {
+ logger.debug("key={}", key);
+ boolean alias = false;
+ String realName = null;
+ if (!params.containsKey(key)) {
+ logger.debug("{} is not a parameter in the template! - check for an alias", key);
+ // add check here for an alias
+ if (!paramAliases.containsKey(key)) {
+ logger.debug("The parameter {} is in the inputs, but it's not a parameter for this template - omit",
+ key);
+ continue;
+ } else {
+ alias = true;
+ realName = paramAliases.get(key).getParamName();
+ logger.debug("FOUND AN ALIAS! Will use {} in lieu of give key/alias {}", realName, key);
+ }
+ }
+ String type = params.get(key).getParamType();
+ if (type == null || "".equals(type)) {
+ logger.debug("**PARAM_TYPE is null/empty for {}, will default to string", key);
+ type = "string";
+ }
+ logger.debug("Parameter: {} is of type {}", key, type);
+ if ("string".equalsIgnoreCase(type)) {
+ // Easiest!
+ String str = inputs.get(key) != null ? inputs.get(key).toString() : null;
+ if (alias)
+ newInputs.put(realName, str);
+ else
+ newInputs.put(key, str);
+ } else if ("number".equalsIgnoreCase(type)) {
+ String integerString = inputs.get(key) != null ? inputs.get(key).toString() : null;
+ Integer anInteger = null;
+ try {
+ anInteger = Integer.parseInt(integerString);
+ } catch (Exception e) {
+ logger.debug("Unable to convert {} to an integer!!", integerString, e);
+ anInteger = null;
+ }
+ if (anInteger != null) {
+ if (alias)
+ newInputs.put(realName, anInteger);
+ else
+ newInputs.put(key, anInteger);
+ } else {
+ if (alias)
+ newInputs.put(realName, integerString);
+ else
+ newInputs.put(key, integerString);
+ }
+ } else if ("json".equalsIgnoreCase(type)) {
+ Object jsonObj = inputs.get(key);
+ Object json;
+ try {
+ if (jsonObj instanceof String) {
+ json = JSON_MAPPER.readTree(jsonObj.toString());
+ } else {
+ // will already marshal to json without intervention
+ json = jsonObj;
+ }
+ } catch (IOException e) {
+ logger.error("failed to map to json, directly converting to string instead", e);
+ json = jsonObj.toString();
+ }
+ if (alias)
+ newInputs.put(realName, json);
+ else
+ newInputs.put(key, json);
+ } else if ("comma_delimited_list".equalsIgnoreCase(type)) {
+ String commaSeparated = inputs.get(key) != null ? inputs.get(key).toString() : null;
+ try {
+ List<String> anArrayList = this.convertCdlToArrayList(commaSeparated);
+ if (alias)
+ newInputs.put(realName, anArrayList);
+ else
+ newInputs.put(key, anArrayList);
+ } catch (Exception e) {
+ logger.debug("Unable to convert {} to an ArrayList!!", commaSeparated, e);
+ if (alias)
+ newInputs.put(realName, commaSeparated);
+ else
+ newInputs.put(key, commaSeparated);
+ }
+ } else if ("boolean".equalsIgnoreCase(type)) {
+ String booleanString = inputs.get(key) != null ? inputs.get(key).toString() : null;
+ Boolean aBool = Boolean.valueOf(booleanString);
+ if (alias)
+ newInputs.put(realName, aBool);
+ else
+ newInputs.put(key, aBool);
+ } else {
+ // it's null or something undefined - just add it back as a String
+ String str = inputs.get(key).toString();
+ if (alias)
+ newInputs.put(realName, str);
+ else
+ newInputs.put(key, str);
+ }
+ }
+ return newInputs;
+ }
+
+ /*
+ * This helpful method added for Valet
+ */
+ public String getCloudSiteKeystoneUrl(String cloudSiteId) throws MsoCloudSiteNotFound {
+ String keystone_url = null;
+ try {
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudIdentity cloudIdentity = cloudSite.getIdentityService();
+ keystone_url = cloudIdentity.getIdentityUrl();
+ } catch (Exception e) {
+ throw new MsoCloudSiteNotFound(cloudSiteId);
+ }
+ if (keystone_url == null || keystone_url.isEmpty()) {
+ throw new MsoCloudSiteNotFound(cloudSiteId);
+ }
+ return keystone_url;
+ }
+
+ /*
+ * Create a string suitable for being dumped to a debug log that creates a pseudo-JSON request dumping what's being
+ * sent to Openstack API in the create or update request
+ */
+
+ private String printStackRequest(String tenantId, Map<String, Object> heatFiles,
+ Map<String, Object> nestedTemplates, String environment, Map<String, Object> inputs, String vfModuleName,
+ String template, int timeoutMinutes, boolean backout, String cloudSiteId) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("CREATE STACK REQUEST (formatted for readability)\n");
+ sb.append("tenant=" + tenantId + ", cloud=" + cloudSiteId);
+ sb.append("{\n");
+ sb.append(" \"stack_name\": \"" + vfModuleName + "\",\n");
+ sb.append(" \"disable_rollback\": " + backout + ",\n");
+ sb.append(" \"timeout_mins\": " + timeoutMinutes + ",\n");
+ sb.append(" \"template\": {\n");
+ sb.append(template);
+ sb.append(" },\n");
+ sb.append(" \"environment\": {\n");
+ if (environment == null)
+ sb.append("<none>");
+ else
+ sb.append(environment);
+ sb.append(" },\n");
+ sb.append(" \"files\": {\n");
+ int filesCounter = 0;
+ if (heatFiles != null) {
+ for (String key : heatFiles.keySet()) {
+ filesCounter++;
+ if (filesCounter > 1) {
+ sb.append(",\n");
+ }
+ sb.append(" \"" + key + "\": {\n");
+ sb.append(heatFiles.get(key).toString() + "\n }");
+ }
+ }
+ if (nestedTemplates != null) {
+ for (String key : nestedTemplates.keySet()) {
+ filesCounter++;
+ if (filesCounter > 1) {
+ sb.append(",\n");
+ }
+ sb.append(" \"" + key + "\": {\n");
+ sb.append(nestedTemplates.get(key).toString() + "\n }");
+ }
}
- }
- String type = params.get(key).getParamType();
- if (type == null || "".equals(type)) {
- logger.debug("**PARAM_TYPE is null/empty for {}, will default to string", key);
- type = "string";
- }
- logger.debug("Parameter: {} is of type {}", key, type);
- if ("string".equalsIgnoreCase(type)) {
- // Easiest!
- String str = inputs.get(key) != null ? inputs.get(key).toString() : null;
- if (alias)
- newInputs.put(realName, str);
- else
- newInputs.put(key, str);
- } else if ("number".equalsIgnoreCase(type)) {
- String integerString = inputs.get(key) != null ? inputs.get(key).toString() : null;
- Integer anInteger = null;
- try {
- anInteger = Integer.parseInt(integerString);
- } catch (Exception e) {
- logger.debug("Unable to convert {} to an integer!!", integerString, e);
- anInteger = null;
- }
- if (anInteger != null) {
- if (alias)
- newInputs.put(realName, anInteger);
- else
- newInputs.put(key, anInteger);
- }
- else {
- if (alias)
- newInputs.put(realName, integerString);
- else
- newInputs.put(key, integerString);
- }
- } else if ("json".equalsIgnoreCase(type)) {
- Object jsonObj = inputs.get(key);
- Object json;
- try {
- if (jsonObj instanceof String) {
- json = JSON_MAPPER.readTree(jsonObj.toString());
- } else {
- //will already marshal to json without intervention
- json = jsonObj;
- }
- } catch (IOException e) {
- logger.error("failed to map to json, directly converting to string instead", e);
- json = jsonObj.toString();
- }
- if (alias)
- newInputs.put(realName, json);
- else
- newInputs.put(key, json);
- } else if ("comma_delimited_list".equalsIgnoreCase(type)) {
- String commaSeparated = inputs.get(key) != null ? inputs.get(key).toString() : null;
- try {
- List<String> anArrayList = this.convertCdlToArrayList(commaSeparated);
- if (alias)
- newInputs.put(realName, anArrayList);
- else
- newInputs.put(key, anArrayList);
- } catch (Exception e) {
- logger.debug("Unable to convert {} to an ArrayList!!", commaSeparated, e);
- if (alias)
- newInputs.put(realName, commaSeparated);
- else
- newInputs.put(key, commaSeparated);
- }
- } else if ("boolean".equalsIgnoreCase(type)) {
- String booleanString = inputs.get(key) != null ? inputs.get(key).toString() : null;
- Boolean aBool = Boolean.valueOf(booleanString);
- if (alias)
- newInputs.put(realName, aBool);
- else
- newInputs.put(key, aBool);
- } else {
- // it's null or something undefined - just add it back as a String
- String str = inputs.get(key).toString();
- if (alias)
- newInputs.put(realName, str);
- else
- newInputs.put(key, str);
- }
- }
- return newInputs;
- }
-
- /*
- * This helpful method added for Valet
- */
- public String getCloudSiteKeystoneUrl(String cloudSiteId) throws MsoCloudSiteNotFound {
- String keystone_url = null;
- try {
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
- CloudIdentity cloudIdentity = cloudSite.getIdentityService();
- keystone_url = cloudIdentity.getIdentityUrl();
- } catch (Exception e) {
- throw new MsoCloudSiteNotFound(cloudSiteId);
- }
- if (keystone_url == null || keystone_url.isEmpty()) {
- throw new MsoCloudSiteNotFound(cloudSiteId);
- }
- return keystone_url;
- }
-
- /*
- * Create a string suitable for being dumped to a debug log that creates a
- * pseudo-JSON request dumping what's being sent to Openstack API in the create or update request
- */
-
- private String printStackRequest(String tenantId,
- Map<String, Object> heatFiles,
- Map<String, Object> nestedTemplates,
- String environment,
- Map<String, Object> inputs,
- String vfModuleName,
- String template,
- int timeoutMinutes,
- boolean backout,
- String cloudSiteId) {
- StringBuilder sb = new StringBuilder();
- sb.append("CREATE STACK REQUEST (formatted for readability)\n");
- sb.append("tenant=" + tenantId + ", cloud=" + cloudSiteId);
- sb.append("{\n");
- sb.append(" \"stack_name\": \"" + vfModuleName + "\",\n");
- sb.append(" \"disable_rollback\": " + backout + ",\n");
- sb.append(" \"timeout_mins\": " + timeoutMinutes + ",\n");
- sb.append(" \"template\": {\n");
- sb.append(template);
- sb.append(" },\n");
- sb.append(" \"environment\": {\n");
- if (environment == null)
- sb.append("<none>");
- else
- sb.append(environment);
- sb.append(" },\n");
- sb.append(" \"files\": {\n");
- int filesCounter = 0;
- if (heatFiles != null) {
- for (String key : heatFiles.keySet()) {
- filesCounter++;
- if (filesCounter > 1) {
- sb.append(",\n");
- }
- sb.append(" \"" + key + "\": {\n");
- sb.append(heatFiles.get(key).toString() + "\n }");
- }
- }
- if (nestedTemplates != null) {
- for (String key : nestedTemplates.keySet()) {
- filesCounter++;
- if (filesCounter > 1) {
- sb.append(",\n");
- }
- sb.append(" \"" + key + "\": {\n");
- sb.append(nestedTemplates.get(key).toString() + "\n }");
- }
- }
- sb.append("\n },\n");
- sb.append(" \"parameters\": {\n");
- int paramCounter = 0;
- for (String name : inputs.keySet()) {
- paramCounter++;
- if (paramCounter > 1) {
- sb.append(",\n");
- }
- Object o = inputs.get(name);
- if (o instanceof java.lang.String) {
- sb.append(" \"" + name + "\": \"" + inputs.get(name).toString() + "\"");
- } else if (o instanceof Integer) {
- sb.append(" \"" + name + "\": " + inputs.get(name).toString() );
- } else if (o instanceof ArrayList) {
- sb.append(" \"" + name + "\": " + inputs.get(name).toString() );
- } else if (o instanceof Boolean) {
- sb.append(" \"" + name + "\": " + inputs.get(name).toString() );
- } else {
- sb.append(" \"" + name + "\": " + "\"(there was an issue trying to dump this value...)\"" );
- }
- }
- sb.append("\n }\n}\n");
-
- return sb.toString();
- }
-
- /*******************************************************************************
+ sb.append("\n },\n");
+ sb.append(" \"parameters\": {\n");
+ int paramCounter = 0;
+ for (String name : inputs.keySet()) {
+ paramCounter++;
+ if (paramCounter > 1) {
+ sb.append(",\n");
+ }
+ Object o = inputs.get(name);
+ if (o instanceof java.lang.String) {
+ sb.append(" \"" + name + "\": \"" + inputs.get(name).toString() + "\"");
+ } else if (o instanceof Integer) {
+ sb.append(" \"" + name + "\": " + inputs.get(name).toString());
+ } else if (o instanceof ArrayList) {
+ sb.append(" \"" + name + "\": " + inputs.get(name).toString());
+ } else if (o instanceof Boolean) {
+ sb.append(" \"" + name + "\": " + inputs.get(name).toString());
+ } else {
+ sb.append(" \"" + name + "\": " + "\"(there was an issue trying to dump this value...)\"");
+ }
+ }
+ sb.append("\n }\n}\n");
+
+ return sb.toString();
+ }
+
+ /*******************************************************************************
*
* Methods (and associated utilities) to implement the VduPlugin interface
*
@@ -1515,64 +1417,47 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
/**
* VduPlugin interface for instantiate function.
*
- * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
- * and then invoke the existing function.
+ * Translate the VduPlugin parameters to the corresponding 'createStack' parameters, and then invoke the existing
+ * function.
*/
@Override
- public VduInstance instantiateVdu (
- CloudInfo cloudInfo,
- String instanceName,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException
- {
- String cloudSiteId = cloudInfo.getCloudSiteId();
- String cloudOwner = cloudInfo.getCloudOwner();
- String tenantId = cloudInfo.getTenantId();
-
- // Translate the VDU ModelInformation structure to that which is needed for
- // creating the Heat stack. Loop through the artifacts, looking specifically
- // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
- // be attached as a FILE.
- String heatTemplate = null;
- Map<String,Object> nestedTemplates = new HashMap<>();
- Map<String,Object> files = new HashMap<>();
- String heatEnvironment = null;
-
- for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
- if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
- heatTemplate = new String(vduArtifact.getContent());
- }
- else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
- nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
- }
- else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
- heatEnvironment = new String(vduArtifact.getContent());
- }
- }
-
- try {
- StackInfo stackInfo = createStack (cloudSiteId,
- cloudOwner,
- tenantId,
- instanceName,
- vduModel,
- heatTemplate,
- inputs,
- true, // poll for completion
- vduModel.getTimeoutMinutes(),
- heatEnvironment,
- nestedTemplates,
- files,
- rollbackOnFailure);
-
- // Populate a vduInstance from the StackInfo
- return stackInfoToVduInstance(stackInfo);
- }
- catch (Exception e) {
- throw new VduException ("MsoHeatUtils (instantiateVDU): createStack Exception", e);
- }
+ public VduInstance instantiateVdu(CloudInfo cloudInfo, String instanceName, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException {
+ String cloudSiteId = cloudInfo.getCloudSiteId();
+ String cloudOwner = cloudInfo.getCloudOwner();
+ String tenantId = cloudInfo.getTenantId();
+
+ // Translate the VDU ModelInformation structure to that which is needed for
+ // creating the Heat stack. Loop through the artifacts, looking specifically
+ // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
+ // be attached as a FILE.
+ String heatTemplate = null;
+ Map<String, Object> nestedTemplates = new HashMap<>();
+ Map<String, Object> files = new HashMap<>();
+ String heatEnvironment = null;
+
+ for (VduArtifact vduArtifact : vduModel.getArtifacts()) {
+ if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
+ heatTemplate = new String(vduArtifact.getContent());
+ } else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
+ nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
+ } else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
+ heatEnvironment = new String(vduArtifact.getContent());
+ }
+ }
+
+ try {
+ StackInfo stackInfo =
+ createStack(cloudSiteId, cloudOwner, tenantId, instanceName, vduModel, heatTemplate, inputs, true, // poll
+ // for
+ // completion
+ vduModel.getTimeoutMinutes(), heatEnvironment, nestedTemplates, files, rollbackOnFailure);
+
+ // Populate a vduInstance from the StackInfo
+ return stackInfoToVduInstance(stackInfo);
+ } catch (Exception e) {
+ throw new VduException("MsoHeatUtils (instantiateVDU): createStack Exception", e);
+ }
}
@@ -1580,22 +1465,19 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
* VduPlugin interface for query function.
*/
@Override
- public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
- throws VduException
- {
- String cloudSiteId = cloudInfo.getCloudSiteId();
- String cloudOwner = cloudInfo.getCloudOwner();
- String tenantId = cloudInfo.getTenantId();
-
- try {
- // Query the Cloudify Deployment object and populate a VduInstance
- StackInfo stackInfo = queryStack (cloudSiteId, cloudOwner, tenantId, instanceId);
-
- return stackInfoToVduInstance(stackInfo);
- }
- catch (Exception e) {
- throw new VduException ("MsoHeatUtile (queryVdu): queryStack Exception ", e);
- }
+ public VduInstance queryVdu(CloudInfo cloudInfo, String instanceId) throws VduException {
+ String cloudSiteId = cloudInfo.getCloudSiteId();
+ String cloudOwner = cloudInfo.getCloudOwner();
+ String tenantId = cloudInfo.getTenantId();
+
+ try {
+ // Query the Cloudify Deployment object and populate a VduInstance
+ StackInfo stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
+
+ return stackInfoToVduInstance(stackInfo);
+ } catch (Exception e) {
+ throw new VduException("MsoHeatUtile (queryVdu): queryStack Exception ", e);
+ }
}
@@ -1603,135 +1485,120 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
* VduPlugin interface for delete function.
*/
@Override
- public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
- throws VduException
- {
- String cloudSiteId = cloudInfo.getCloudSiteId();
- String cloudOwner = cloudInfo.getCloudOwner();
- String tenantId = cloudInfo.getTenantId();
-
- try {
- // Delete the Heat stack
- StackInfo stackInfo = deleteStack (tenantId, cloudOwner, cloudSiteId, instanceId, true);
-
- // Populate a VduInstance based on the deleted Cloudify Deployment object
- VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
-
- // Override return state to DELETED (HeatUtils sets to NOTFOUND)
- vduInstance.getStatus().setState(VduStateType.DELETED);
-
- return vduInstance;
- }
- catch (Exception e) {
- throw new VduException ("Delete VDU Exception", e);
- }
+ public VduInstance deleteVdu(CloudInfo cloudInfo, String instanceId, int timeoutMinutes) throws VduException {
+ String cloudSiteId = cloudInfo.getCloudSiteId();
+ String cloudOwner = cloudInfo.getCloudOwner();
+ String tenantId = cloudInfo.getTenantId();
+
+ try {
+ // Delete the Heat stack
+ StackInfo stackInfo = deleteStack(tenantId, cloudOwner, cloudSiteId, instanceId, true);
+
+ // Populate a VduInstance based on the deleted Cloudify Deployment object
+ VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
+
+ // Override return state to DELETED (HeatUtils sets to NOTFOUND)
+ vduInstance.getStatus().setState(VduStateType.DELETED);
+
+ return vduInstance;
+ } catch (Exception e) {
+ throw new VduException("Delete VDU Exception", e);
+ }
}
/**
* VduPlugin interface for update function.
*
- * Update is currently not supported in the MsoHeatUtils implementation of VduPlugin.
- * Just return a VduException.
+ * Update is currently not supported in the MsoHeatUtils implementation of VduPlugin. Just return a VduException.
*
*/
@Override
- public VduInstance updateVdu (
- CloudInfo cloudInfo,
- String instanceId,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException
- {
- throw new VduException ("MsoHeatUtils: updateVdu interface not supported");
+ public VduInstance updateVdu(CloudInfo cloudInfo, String instanceId, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException {
+ throw new VduException("MsoHeatUtils: updateVdu interface not supported");
}
/*
* Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
*/
- protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
- {
- VduInstance vduInstance = new VduInstance();
+ protected VduInstance stackInfoToVduInstance(StackInfo stackInfo) {
+ VduInstance vduInstance = new VduInstance();
+
+ // The full canonical name as the instance UUID
+ vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
+ vduInstance.setVduInstanceName(stackInfo.getName());
+
+ // Copy inputs and outputs
+ vduInstance.setInputs(stackInfo.getParameters());
+ vduInstance.setOutputs(stackInfo.getOutputs());
+
+ // Translate the status elements
+ vduInstance.setStatus(stackStatusToVduStatus(stackInfo));
- // The full canonical name as the instance UUID
- vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
- vduInstance.setVduInstanceName(stackInfo.getName());
+ return vduInstance;
+ }
- // Copy inputs and outputs
- vduInstance.setInputs(stackInfo.getParameters());
- vduInstance.setOutputs(stackInfo.getOutputs());
+ private VduStatus stackStatusToVduStatus(StackInfo stackInfo) {
+ VduStatus vduStatus = new VduStatus();
+
+ // Map the status fields to more generic VduStatus.
+ // There are lots of HeatStatus values, so this is a bit long...
+ HeatStatus heatStatus = stackInfo.getStatus();
+ String statusMessage = stackInfo.getStatusMessage();
+
+ if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
+ vduStatus.setState(VduStateType.INSTANTIATING);
+ vduStatus.setLastAction((new PluginAction("create", "in_progress", statusMessage)));
+ } else if (heatStatus == HeatStatus.NOTFOUND) {
+ vduStatus.setState(VduStateType.NOTFOUND);
+ } else if (heatStatus == HeatStatus.CREATED) {
+ vduStatus.setState(VduStateType.INSTANTIATED);
+ vduStatus.setLastAction((new PluginAction("create", "complete", statusMessage)));
+ } else if (heatStatus == HeatStatus.UPDATED) {
+ vduStatus.setState(VduStateType.INSTANTIATED);
+ vduStatus.setLastAction((new PluginAction("update", "complete", statusMessage)));
+ } else if (heatStatus == HeatStatus.UPDATING) {
+ vduStatus.setState(VduStateType.UPDATING);
+ vduStatus.setLastAction((new PluginAction("update", "in_progress", statusMessage)));
+ } else if (heatStatus == HeatStatus.DELETING) {
+ vduStatus.setState(VduStateType.DELETING);
+ vduStatus.setLastAction((new PluginAction("delete", "in_progress", statusMessage)));
+ } else if (heatStatus == HeatStatus.FAILED) {
+ vduStatus.setState(VduStateType.FAILED);
+ vduStatus.setErrorMessage(stackInfo.getStatusMessage());
+ } else {
+ vduStatus.setState(VduStateType.UNKNOWN);
+ }
- // Translate the status elements
- vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
+ return vduStatus;
+ }
- return vduInstance;
+ public Resources queryStackResources(String cloudSiteId, String tenantId, String stackName, int nestedDepth)
+ throws MsoException {
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Heat heatClient = getHeatClient(cloudSite, tenantId);
+ OpenStackRequest<Resources> request =
+ heatClient.getResources().listResources(stackName).queryParam("nested_depth", nestedDepth);
+ return executeAndRecordOpenstackRequest(request);
}
- private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
- {
- VduStatus vduStatus = new VduStatus();
-
- // Map the status fields to more generic VduStatus.
- // There are lots of HeatStatus values, so this is a bit long...
- HeatStatus heatStatus = stackInfo.getStatus();
- String statusMessage = stackInfo.getStatusMessage();
-
- if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
- vduStatus.setState(VduStateType.INSTANTIATING);
- vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
- }
- else if (heatStatus == HeatStatus.NOTFOUND) {
- vduStatus.setState(VduStateType.NOTFOUND);
- }
- else if (heatStatus == HeatStatus.CREATED) {
- vduStatus.setState(VduStateType.INSTANTIATED);
- vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
- }
- else if (heatStatus == HeatStatus.UPDATED) {
- vduStatus.setState(VduStateType.INSTANTIATED);
- vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
- }
- else if (heatStatus == HeatStatus.UPDATING) {
- vduStatus.setState(VduStateType.UPDATING);
- vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
- }
- else if (heatStatus == HeatStatus.DELETING) {
- vduStatus.setState(VduStateType.DELETING);
- vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
- }
- else if (heatStatus == HeatStatus.FAILED) {
- vduStatus.setState(VduStateType.FAILED);
- vduStatus.setErrorMessage(stackInfo.getStatusMessage());
- } else {
- vduStatus.setState(VduStateType.UNKNOWN);
- }
-
- return vduStatus;
+ public <R> R executeHeatClientRequest(String url, String cloudSiteId, String tenantId, Class<R> returnType)
+ throws MsoException {
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Heat heatClient = getHeatClient(cloudSite, tenantId);
+ OpenStackRequest<R> request = heatClient.get(url, returnType);
+ return executeAndRecordOpenstackRequest(request);
}
-
- public Resources queryStackResources(String cloudSiteId, String tenantId, String stackName, int nestedDepth) throws MsoException {
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId)
- .orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
- Heat heatClient = getHeatClient(cloudSite, tenantId);
- OpenStackRequest<Resources> request = heatClient.getResources().listResources(stackName).queryParam("nested_depth", nestedDepth);
- return executeAndRecordOpenstackRequest(request);
- }
-
- public <R> R executeHeatClientRequest(String url, String cloudSiteId, String tenantId, Class<R> returnType) throws MsoException {
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId)
- .orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
- Heat heatClient = getHeatClient(cloudSite, tenantId);
- OpenStackRequest<R> request = heatClient.get(url, returnType);
- return executeAndRecordOpenstackRequest(request);
- }
protected void sleep(long time) {
- try {
+ try {
Thread.sleep(time);
} catch (InterruptedException e) {
- logger.debug ("Thread interrupted while sleeping", e);
+ logger.debug("Thread interrupted while sleeping", e);
Thread.currentThread().interrupt();
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java
index c378be7d4b..1bf780f6d3 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java
@@ -67,95 +67,46 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
* Keep these methods around for backward compatibility
*/
- public StackInfo updateStack (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, Object> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes) throws MsoException {
+ public StackInfo updateStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, Object> stackInputs, boolean pollForCompletion, int timeoutMinutes)
+ throws MsoException {
// Keeping this method to allow compatibility with no environment or files variable sent. In this case,
// simply return the new method with the environment variable set to null.
- return this.updateStack (cloudSiteId,
- cloudOwner,
- tenantId,
- stackName,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- null,
- null,
- null);
+ return this.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, null, null, null);
}
- public StackInfo updateStack (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, Object> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment) throws MsoException {
+ public StackInfo updateStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, Object> stackInputs, boolean pollForCompletion, int timeoutMinutes,
+ String environment) throws MsoException {
// Keeping this method to allow compatibility with no environment variable sent. In this case,
// simply return the new method with the files variable set to null.
- return this.updateStack (cloudSiteId,
- cloudOwner,
- tenantId,
- stackName,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- environment,
- null,
- null);
+ return this.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, environment, null, null);
}
- public StackInfo updateStack (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, Object> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files) throws MsoException {
- return this.updateStack (cloudSiteId,
- cloudOwner,
- tenantId,
- stackName,
- heatTemplate,
- stackInputs,
- pollForCompletion,
- timeoutMinutes,
- environment,
- files,
- null);
+ public StackInfo updateStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, Object> stackInputs, boolean pollForCompletion, int timeoutMinutes,
+ String environment, Map<String, Object> files) throws MsoException {
+ return this.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate, stackInputs,
+ pollForCompletion, timeoutMinutes, environment, files, null);
}
/**
- * Update a Stack in the specified cloud location and tenant. The Heat template
- * and parameter map are passed in as arguments, along with the cloud access credentials.
- * It is expected that parameters have been validated and contain at minimum the required
- * parameters for the given template with no extra (undefined) parameters..
+ * Update a Stack in the specified cloud location and tenant. The Heat template and parameter map are passed in as
+ * arguments, along with the cloud access credentials. It is expected that parameters have been validated and
+ * contain at minimum the required parameters for the given template with no extra (undefined) parameters..
*
- * The Stack name supplied by the caller must be unique in the scope of this tenant.
- * However, it should also be globally unique, as it will be the identifier for the
- * resource going forward in Inventory. This latter is managed by the higher levels
- * invoking this function.
+ * The Stack name supplied by the caller must be unique in the scope of this tenant. However, it should also be
+ * globally unique, as it will be the identifier for the resource going forward in Inventory. This latter is managed
+ * by the higher levels invoking this function.
*
- * The caller may choose to let this function poll Openstack for completion of the
- * stack creation, or may handle polling itself via separate calls to query the status.
- * In either case, a StackInfo object will be returned containing the current status.
- * When polling is enabled, a status of CREATED is expected. When not polling, a
+ * The caller may choose to let this function poll Openstack for completion of the stack creation, or may handle
+ * polling itself via separate calls to query the status. In either case, a StackInfo object will be returned
+ * containing the current status. When polling is enabled, a status of CREATED is expected. When not polling, a
* status of BUILDING is expected.
*
- * An error will be thrown if the requested Stack already exists in the specified
- * Tenant and Cloud.
+ * An error will be thrown if the requested Stack already exists in the specified Tenant and Cloud.
*
* @param tenantId The Openstack ID of the tenant in which to create the Stack
* @param cloudSiteId The cloud identifier (may be a region) in which to create the tenant.
@@ -170,105 +121,98 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
* @throws MsoException Thrown if the Openstack API call returns an exception.
*/
- public StackInfo updateStack (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String stackName,
- String heatTemplate,
- Map <String, Object> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files,
- Map <String, Object> heatFiles) throws MsoException {
+ public StackInfo updateStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ String heatTemplate, Map<String, Object> stackInputs, boolean pollForCompletion, int timeoutMinutes,
+ String environment, Map<String, Object> files, Map<String, Object> heatFiles) throws MsoException {
boolean heatEnvtVariable = true;
- if (environment == null || "".equalsIgnoreCase (environment.trim ())) {
+ if (environment == null || "".equalsIgnoreCase(environment.trim())) {
heatEnvtVariable = false;
}
boolean haveFiles = true;
- if (files == null || files.isEmpty ()) {
+ if (files == null || files.isEmpty()) {
haveFiles = false;
}
boolean haveHeatFiles = true;
- if (heatFiles == null || heatFiles.isEmpty ()) {
+ if (heatFiles == null || heatFiles.isEmpty()) {
haveHeatFiles = false;
}
// Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
// Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
// This could throw MsoTenantNotFound or MsoOpenstackException (both propagated)
- Heat heatClient = getHeatClient (cloudSite, tenantId);
+ Heat heatClient = getHeatClient(cloudSite, tenantId);
// Perform a query first to get the current status
- Stack heatStack = queryHeatStack (heatClient, stackName);
- if (heatStack == null || "DELETE_COMPLETE".equals (heatStack.getStackStatus ())) {
+ Stack heatStack = queryHeatStack(heatClient, stackName);
+ if (heatStack == null || "DELETE_COMPLETE".equals(heatStack.getStackStatus())) {
// Not found. Return a StackInfo with status NOTFOUND
- throw new MsoStackNotFound (stackName, tenantId, cloudSiteId);
+ throw new MsoStackNotFound(stackName, tenantId, cloudSiteId);
}
// Use canonical name "<stack name>/<stack-id>" to update the stack.
// Otherwise, update by name returns a 302 redirect.
// NOTE: This is specific to the v1 Orchestration API.
- String canonicalName = heatStack.getStackName () + "/" + heatStack.getId ();
+ String canonicalName = heatStack.getStackName() + "/" + heatStack.getId();
- logger.debug ("Ready to Update Stack ({}) with input params: {}", canonicalName, stackInputs);
- //force entire stackInput object to generic Map<String, Object> for openstack compatibility
- ObjectMapper mapper = new ObjectMapper();
- Map<String, Object> normalized = new HashMap<>();
- try {
- normalized = mapper.readValue(mapper.writeValueAsString(stackInputs), new TypeReference<HashMap<String,Object>>() {});
- } catch (IOException e1) {
- logger.debug("could not map json", e1);
- }
+ logger.debug("Ready to Update Stack ({}) with input params: {}", canonicalName, stackInputs);
+ // force entire stackInput object to generic Map<String, Object> for openstack compatibility
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String, Object> normalized = new HashMap<>();
+ try {
+ normalized = mapper.readValue(mapper.writeValueAsString(stackInputs),
+ new TypeReference<HashMap<String, Object>>() {});
+ } catch (IOException e1) {
+ logger.debug("could not map json", e1);
+ }
// Build up the stack update parameters
// Disable auto-rollback, because error reason is lost. Always rollback in the code.
- UpdateStackParam stack = new UpdateStackParam ();
- stack.setTimeoutMinutes (timeoutMinutes);
- stack.setParameters (normalized);
- stack.setTemplate (heatTemplate);
- stack.setDisableRollback (true);
+ UpdateStackParam stack = new UpdateStackParam();
+ stack.setTimeoutMinutes(timeoutMinutes);
+ stack.setParameters(normalized);
+ stack.setTemplate(heatTemplate);
+ stack.setDisableRollback(true);
// TJM add envt to stack
if (heatEnvtVariable) {
- stack.setEnvironment (environment);
+ stack.setEnvironment(environment);
}
// Handle nested templates & get_files here. if we have both - must combine
// and then add to stack (both are part of "files:" being added to stack)
if (haveFiles && haveHeatFiles) {
// Let's do this here - not in the bean
- logger.debug ("Found files AND heatFiles - combine and add!");
- Map <String, Object> combinedFiles = new HashMap<>();
- for (String keyString : files.keySet ()) {
- combinedFiles.put (keyString, files.get (keyString));
+ logger.debug("Found files AND heatFiles - combine and add!");
+ Map<String, Object> combinedFiles = new HashMap<>();
+ for (String keyString : files.keySet()) {
+ combinedFiles.put(keyString, files.get(keyString));
}
- for (String keyString : heatFiles.keySet ()) {
- combinedFiles.put (keyString, heatFiles.get (keyString));
+ for (String keyString : heatFiles.keySet()) {
+ combinedFiles.put(keyString, heatFiles.get(keyString));
}
- stack.setFiles (combinedFiles);
+ stack.setFiles(combinedFiles);
} else {
// Handle case where we have one or neither
if (haveFiles) {
- stack.setFiles (files);
+ stack.setFiles(files);
}
if (haveHeatFiles) {
// setFiles method modified to handle adding a map.
- stack.setFiles (heatFiles);
+ stack.setFiles(heatFiles);
}
}
try {
// Execute the actual Openstack command to update the Heat stack
- OpenStackRequest <Void> request = heatClient.getStacks ().update (canonicalName, stack);
- executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Void> request = heatClient.getStacks().update(canonicalName, stack);
+ executeAndRecordOpenstackRequest(request);
} catch (OpenStackBaseException e) {
// Since this came on the 'Update Stack' command, nothing was changed
// in the cloud. Rethrow the error as an MSO exception.
- throw heatExceptionToMsoException (e, UPDATE_STACK);
+ throw heatExceptionToMsoException(e, UPDATE_STACK);
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, UPDATE_STACK);
+ throw runtimeExceptionToMsoException(e, UPDATE_STACK);
}
// If client has requested a final response, poll for stack completion
@@ -277,36 +221,37 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
// Set a time limit on overall polling.
// Use the resource (template) timeout for Openstack (expressed in minutes)
// and add one poll interval to give Openstack a chance to fail on its own.
- int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
+ int createPollInterval =
+ Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
boolean loopAgain = true;
while (loopAgain) {
try {
- updateStack = queryHeatStack (heatClient, canonicalName);
+ updateStack = queryHeatStack(heatClient, canonicalName);
logger.debug("{} ({}) ", updateStack.getStackStatus(), canonicalName);
try {
- logger
- .debug("Current stack {}" + this.getOutputsAsStringBuilderWithUpdate(heatStack).toString());
+ logger.debug(
+ "Current stack {}" + this.getOutputsAsStringBuilderWithUpdate(heatStack).toString());
} catch (Exception e) {
logger.debug("an error occurred trying to print out the current outputs of the stack", e);
}
- if ("UPDATE_IN_PROGRESS".equals (updateStack.getStackStatus ())) {
+ if ("UPDATE_IN_PROGRESS".equals(updateStack.getStackStatus())) {
// Stack update is still running.
// Sleep and try again unless timeout has been reached
if (pollTimeout <= 0) {
// Note that this should not occur, since there is a timeout specified
// in the Openstack call.
logger.error(
- "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Update stack timeout",
- MessageEnum.RA_UPDATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
- updateStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
+ "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Update stack timeout",
+ MessageEnum.RA_UPDATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
+ updateStack.getStackStatus(), ErrorCode.AvailabilityError.getValue());
loopAgain = false;
} else {
try {
- Thread.sleep (createPollInterval * 1000L);
+ Thread.sleep(createPollInterval * 1000L);
} catch (InterruptedException e) {
// If we are interrupted, we should stop ASAP.
loopAgain = false;
@@ -323,34 +268,33 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
// Cannot query the stack. Something is wrong.
// TODO: No way to roll back the stack at this point. What to do?
- e.addContext (UPDATE_STACK);
+ e.addContext(UPDATE_STACK);
throw e;
}
}
- if (!"UPDATE_COMPLETE".equals (updateStack.getStackStatus ())) {
+ if (!"UPDATE_COMPLETE".equals(updateStack.getStackStatus())) {
logger.error("{} Stack status: {} Stack status reason: {} {} Update Stack error",
- MessageEnum.RA_UPDATE_STACK_ERR, updateStack.getStackStatus(), updateStack.getStackStatusReason(),
- ErrorCode.DataError.getValue());
+ MessageEnum.RA_UPDATE_STACK_ERR, updateStack.getStackStatus(),
+ updateStack.getStackStatusReason(), ErrorCode.DataError.getValue());
// TODO: No way to roll back the stack at this point. What to do?
// Throw a 'special case' of MsoOpenstackException to report the Heat status
MsoOpenstackException me = null;
- if ("UPDATE_IN_PROGRESS".equals (updateStack.getStackStatus ())) {
- me = new MsoOpenstackException (0, "", "Stack Update Timeout");
+ if ("UPDATE_IN_PROGRESS".equals(updateStack.getStackStatus())) {
+ me = new MsoOpenstackException(0, "", "Stack Update Timeout");
} else {
- String error = "Stack error (" + updateStack.getStackStatus ()
- + "): "
- + updateStack.getStackStatusReason ();
- me = new MsoOpenstackException (0, "", error);
+ String error =
+ "Stack error (" + updateStack.getStackStatus() + "): " + updateStack.getStackStatusReason();
+ me = new MsoOpenstackException(0, "", error);
}
- me.addContext (UPDATE_STACK);
+ me.addContext(UPDATE_STACK);
throw me;
}
} else {
// Return the current status.
- updateStack = queryHeatStack (heatClient, canonicalName);
+ updateStack = queryHeatStack(heatClient, canonicalName);
if (updateStack != null) {
logger.debug("UpdateStack, status = {}", updateStack.getStackStatus());
} else {
@@ -360,93 +304,92 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
return new StackInfoMapper(updateStack).map();
}
- private StringBuilder getOutputsAsStringBuilderWithUpdate(Stack heatStack) {
- // This should only be used as a utility to print out the stack outputs
- // to the log
- StringBuilder sb = new StringBuilder("");
- if (heatStack == null) {
- sb.append("(heatStack is null)");
- return sb;
- }
- List<Output> outputList = heatStack.getOutputs();
- if (outputList == null || outputList.isEmpty()) {
- sb.append("(outputs is empty)");
- return sb;
- }
- Map<String, Object> outputs = new HashMap<>();
- for (Output outputItem : outputList) {
- outputs.put(outputItem.getOutputKey(), outputItem.getOutputValue());
- }
- int counter = 0;
- sb.append("OUTPUTS:\n");
- for (String key : outputs.keySet()) {
- sb.append("outputs[").append(counter++).append("]: ").append(key).append("=");
- Object obj = outputs.get(key);
- if (obj instanceof String) {
- sb.append((String) obj).append(" (a string)");
- } else if (obj instanceof JsonNode) {
- sb.append(this.convertNodeWithUpdate((JsonNode) obj)).append(" (a JsonNode)");
- } else if (obj instanceof java.util.LinkedHashMap) {
- try {
- String str = JSON_MAPPER.writeValueAsString(obj);
- sb.append(str).append(" (a java.util.LinkedHashMap)");
- } catch (Exception e) {
- logger.debug("Exception :", e);
- sb.append("(a LinkedHashMap value that would not convert nicely)");
- }
- } else if (obj instanceof Integer) {
- String str = "";
- try {
- str = obj.toString() + " (an Integer)\n";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(an Integer unable to call .toString() on)";
- }
- sb.append(str);
- } else if (obj instanceof ArrayList) {
- String str = "";
- try {
- str = obj.toString() + " (an ArrayList)";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(an ArrayList unable to call .toString() on?)";
- }
- sb.append(str);
- } else if (obj instanceof Boolean) {
- String str = "";
- try {
- str = obj.toString() + " (a Boolean)";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(an Boolean unable to call .toString() on?)";
- }
- sb.append(str);
- }
- else {
- String str = "";
- try {
- str = obj.toString() + " (unknown Object type)";
- } catch (Exception e) {
- logger.debug("Exception :", e);
- str = "(a value unable to call .toString() on?)";
- }
- sb.append(str);
- }
- sb.append("\n");
- }
- sb.append("[END]");
- return sb;
- }
+ private StringBuilder getOutputsAsStringBuilderWithUpdate(Stack heatStack) {
+ // This should only be used as a utility to print out the stack outputs
+ // to the log
+ StringBuilder sb = new StringBuilder("");
+ if (heatStack == null) {
+ sb.append("(heatStack is null)");
+ return sb;
+ }
+ List<Output> outputList = heatStack.getOutputs();
+ if (outputList == null || outputList.isEmpty()) {
+ sb.append("(outputs is empty)");
+ return sb;
+ }
+ Map<String, Object> outputs = new HashMap<>();
+ for (Output outputItem : outputList) {
+ outputs.put(outputItem.getOutputKey(), outputItem.getOutputValue());
+ }
+ int counter = 0;
+ sb.append("OUTPUTS:\n");
+ for (String key : outputs.keySet()) {
+ sb.append("outputs[").append(counter++).append("]: ").append(key).append("=");
+ Object obj = outputs.get(key);
+ if (obj instanceof String) {
+ sb.append((String) obj).append(" (a string)");
+ } else if (obj instanceof JsonNode) {
+ sb.append(this.convertNodeWithUpdate((JsonNode) obj)).append(" (a JsonNode)");
+ } else if (obj instanceof java.util.LinkedHashMap) {
+ try {
+ String str = JSON_MAPPER.writeValueAsString(obj);
+ sb.append(str).append(" (a java.util.LinkedHashMap)");
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ sb.append("(a LinkedHashMap value that would not convert nicely)");
+ }
+ } else if (obj instanceof Integer) {
+ String str = "";
+ try {
+ str = obj.toString() + " (an Integer)\n";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(an Integer unable to call .toString() on)";
+ }
+ sb.append(str);
+ } else if (obj instanceof ArrayList) {
+ String str = "";
+ try {
+ str = obj.toString() + " (an ArrayList)";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(an ArrayList unable to call .toString() on?)";
+ }
+ sb.append(str);
+ } else if (obj instanceof Boolean) {
+ String str = "";
+ try {
+ str = obj.toString() + " (a Boolean)";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(an Boolean unable to call .toString() on?)";
+ }
+ sb.append(str);
+ } else {
+ String str = "";
+ try {
+ str = obj.toString() + " (unknown Object type)";
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ str = "(a value unable to call .toString() on?)";
+ }
+ sb.append(str);
+ }
+ sb.append("\n");
+ }
+ sb.append("[END]");
+ return sb;
+ }
- private String convertNodeWithUpdate(final JsonNode node) {
- try {
- final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
- final String json = JSON_MAPPER.writeValueAsString(obj);
- return json;
- } catch (Exception e) {
- logger.debug("Error converting json to string {} ", e.getMessage(), e);
+ private String convertNodeWithUpdate(final JsonNode node) {
+ try {
+ final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
+ final String json = JSON_MAPPER.writeValueAsString(obj);
+ return json;
+ } catch (Exception e) {
+ logger.debug("Error converting json to string {} ", e.getMessage(), e);
+ }
+ return "[Error converting json to string]";
}
- return "[Error converting json to string]";
- }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java
index c96cca9f61..cfc8c23c5f 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java
@@ -62,25 +62,24 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
@Autowired
private AuthenticationMethodFactory authenticationMethodFactory;
-
- @Autowired
- private MsoHeatUtils msoHeatUtils;
-
- @Autowired
- private MsoNeutronUtils msoNeutronUtils;
-
- @Autowired
- private MsoTenantUtilsFactory tenantUtilsFactory;
+
+ @Autowired
+ private MsoHeatUtils msoHeatUtils;
+
+ @Autowired
+ private MsoNeutronUtils msoNeutronUtils;
+
+ @Autowired
+ private MsoTenantUtilsFactory tenantUtilsFactory;
+
/**
- * Create a tenant with the specified name in the given cloud. If the tenant already exists,
- * an Exception will be thrown. The MSO User will also be added to the "member" list of
- * the new tenant to perform subsequent Nova/Heat commands in the tenant. If the MSO User
- * association fails, the entire transaction will be rolled back.
+ * Create a tenant with the specified name in the given cloud. If the tenant already exists, an Exception will be
+ * thrown. The MSO User will also be added to the "member" list of the new tenant to perform subsequent Nova/Heat
+ * commands in the tenant. If the MSO User association fails, the entire transaction will be rolled back.
* <p>
- * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin
- * requests go to the centralized identity service in DCP. However, if some artifact
- * must exist in each local LCP instance as well, then it will be needed to access the
- * correct region.
+ * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin requests go to the centralized
+ * identity service in DCP. However, if some artifact must exist in each local LCP instance as well, then it will be
+ * needed to access the correct region.
* <p>
*
* @param tenantName The tenant name to create
@@ -89,44 +88,42 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
* @throws MsoTenantAlreadyExists Thrown if the requested tenant already exists
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
*/
- public String createTenant (String tenantName,
- String cloudSiteId,
- Map <String, String> metadata,
- boolean backout) throws MsoException {
+ public String createTenant(String tenantName, String cloudSiteId, Map<String, String> metadata, boolean backout)
+ throws MsoException {
// Obtain the cloud site information where we will create the tenant
Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSiteOpt.isPresent()) {
logger.error("{} MSOCloudSite {} not found {} ", MessageEnum.RA_CREATE_TENANT_ERR, cloudSiteId,
- ErrorCode.DataError.getValue());
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ ErrorCode.DataError.getValue());
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSiteOpt.get());
Tenant tenant = null;
try {
// Check if the tenant already exists
- tenant = findTenantByName (keystoneAdminClient, tenantName);
+ tenant = findTenantByName(keystoneAdminClient, tenantName);
if (tenant != null) {
// Tenant already exists. Throw an exception
logger.error("{} Tenant name {} already exists on Cloud site id {}, {}",
- MessageEnum.RA_TENANT_ALREADY_EXIST, tenantName, cloudSiteId, ErrorCode.DataError.getValue());
- throw new MsoTenantAlreadyExists (tenantName, cloudSiteId);
+ MessageEnum.RA_TENANT_ALREADY_EXIST, tenantName, cloudSiteId, ErrorCode.DataError.getValue());
+ throw new MsoTenantAlreadyExists(tenantName, cloudSiteId);
}
// Does not exist, create a new one
- tenant = new Tenant ();
- tenant.setName (tenantName);
- tenant.setDescription ("SDN Tenant (via MSO)");
- tenant.setEnabled (true);
+ tenant = new Tenant();
+ tenant.setName(tenantName);
+ tenant.setDescription("SDN Tenant (via MSO)");
+ tenant.setEnabled(true);
- OpenStackRequest <Tenant> request = keystoneAdminClient.tenants ().create (tenant);
- tenant = executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Tenant> request = keystoneAdminClient.tenants().create(tenant);
+ tenant = executeAndRecordOpenstackRequest(request);
} catch (OpenStackBaseException e) {
// Convert Keystone OpenStackResponseException to MsoOpenstackException
- throw keystoneErrorToMsoException (e, "CreateTenant");
+ throw keystoneErrorToMsoException(e, "CreateTenant");
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, "CreateTenant");
+ throw runtimeExceptionToMsoException(e, "CreateTenant");
}
// Add MSO User to the tenant as a member and
@@ -134,67 +131,61 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
try {
CloudIdentity cloudIdentity = cloudSiteOpt.get().getIdentityService();
- User msoUser = findUserByNameOrId (keystoneAdminClient, cloudIdentity.getMsoId ());
- Role memberRole = findRoleByNameOrId (keystoneAdminClient, cloudIdentity.getMemberRole ());
-
- if(msoUser != null && memberRole != null) {
- OpenStackRequest <Void> request = keystoneAdminClient.tenants ().addUser (tenant.getId (),
- msoUser.getId (),
- memberRole.getId ());
- executeAndRecordOpenstackRequest (request);
+ User msoUser = findUserByNameOrId(keystoneAdminClient, cloudIdentity.getMsoId());
+ Role memberRole = findRoleByNameOrId(keystoneAdminClient, cloudIdentity.getMemberRole());
+
+ if (msoUser != null && memberRole != null) {
+ OpenStackRequest<Void> request =
+ keystoneAdminClient.tenants().addUser(tenant.getId(), msoUser.getId(), memberRole.getId());
+ executeAndRecordOpenstackRequest(request);
}
- if (cloudIdentity.getTenantMetadata () && metadata != null && !metadata.isEmpty ()) {
- Metadata tenantMetadata = new Metadata ();
- tenantMetadata.setMetadata (metadata);
+ if (cloudIdentity.getTenantMetadata() && metadata != null && !metadata.isEmpty()) {
+ Metadata tenantMetadata = new Metadata();
+ tenantMetadata.setMetadata(metadata);
- OpenStackRequest <Metadata> metaRequest = keystoneAdminClient.tenants ()
- .createOrUpdateMetadata (tenant.getId (),
- tenantMetadata);
- executeAndRecordOpenstackRequest (metaRequest);
+ OpenStackRequest<Metadata> metaRequest =
+ keystoneAdminClient.tenants().createOrUpdateMetadata(tenant.getId(), tenantMetadata);
+ executeAndRecordOpenstackRequest(metaRequest);
}
} catch (Exception e) {
// Failed to attach MSO User to the new tenant. Can't operate without access,
// so roll back the tenant.
- if (!backout)
- {
- logger.warn("{} Create Tenant errored, Tenant deletion suppressed {} ", MessageEnum.RA_CREATE_TENANT_ERR,
- ErrorCode.DataError.getValue());
- }
- else
- {
- try {
- OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ());
- executeAndRecordOpenstackRequest (request);
- } catch (Exception e2) {
- // Just log this one. We will report the original exception.
- logger.error("{} Nested exception rolling back tenant {} ", MessageEnum.RA_CREATE_TENANT_ERR,
- ErrorCode.DataError.getValue(), e2);
+ if (!backout) {
+ logger.warn("{} Create Tenant errored, Tenant deletion suppressed {} ",
+ MessageEnum.RA_CREATE_TENANT_ERR, ErrorCode.DataError.getValue());
+ } else {
+ try {
+ OpenStackRequest<Void> request = keystoneAdminClient.tenants().delete(tenant.getId());
+ executeAndRecordOpenstackRequest(request);
+ } catch (Exception e2) {
+ // Just log this one. We will report the original exception.
+ logger.error("{} Nested exception rolling back tenant {} ", MessageEnum.RA_CREATE_TENANT_ERR,
+ ErrorCode.DataError.getValue(), e2);
+ }
}
- }
-
+
// Propagate the original exception on user/role/tenant mapping
if (e instanceof OpenStackBaseException) {
// Convert Keystone Exception to MsoOpenstackException
- throw keystoneErrorToMsoException ((OpenStackBaseException) e, "CreateTenantUser");
+ throw keystoneErrorToMsoException((OpenStackBaseException) e, "CreateTenantUser");
} else {
- MsoAdapterException me = new MsoAdapterException (e.getMessage (), e);
- me.addContext ("CreateTenantUser");
+ MsoAdapterException me = new MsoAdapterException(e.getMessage(), e);
+ me.addContext("CreateTenantUser");
throw me;
}
}
- return tenant.getId ();
+ return tenant.getId();
}
/**
- * Query for a tenant by ID in the given cloud. If the tenant exists,
- * return an MsoTenant object. If not, return null.
+ * Query for a tenant by ID in the given cloud. If the tenant exists, return an MsoTenant object. If not, return
+ * null.
* <p>
- * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin
- * requests go to the centralized identity service in DCP. However, if some artifact
- * must exist in each local LCP instance as well, then it will be needed to access the
- * correct region.
+ * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin requests go to the centralized
+ * identity service in DCP. However, if some artifact must exist in each local LCP instance as well, then it will be
+ * needed to access the correct region.
* <p>
*
* @param tenantId The Openstack ID of the tenant to query
@@ -202,47 +193,46 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
* @return the tenant properties of the queried tenant, or null if not found
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
*/
- public MsoTenant queryTenant (String tenantId, String cloudSiteId) throws MsoException {
+ public MsoTenant queryTenant(String tenantId, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will query the tenant
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
- Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
+ Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSite);
// Check if the tenant exists and return its Tenant Id
try {
- Tenant tenant = findTenantById (keystoneAdminClient, tenantId);
+ Tenant tenant = findTenantById(keystoneAdminClient, tenantId);
if (tenant == null) {
return null;
}
- Map <String, String> metadata = new HashMap <String, String> ();
- if (cloudSite.getIdentityService().getTenantMetadata ()) {
- OpenStackRequest <Metadata> request = keystoneAdminClient.tenants ().showMetadata (tenant.getId ());
- Metadata tenantMetadata = executeAndRecordOpenstackRequest (request);
+ Map<String, String> metadata = new HashMap<String, String>();
+ if (cloudSite.getIdentityService().getTenantMetadata()) {
+ OpenStackRequest<Metadata> request = keystoneAdminClient.tenants().showMetadata(tenant.getId());
+ Metadata tenantMetadata = executeAndRecordOpenstackRequest(request);
if (tenantMetadata != null) {
- metadata = tenantMetadata.getMetadata ();
+ metadata = tenantMetadata.getMetadata();
}
}
- return new MsoTenant (tenant.getId (), tenant.getName (), metadata);
+ return new MsoTenant(tenant.getId(), tenant.getName(), metadata);
} catch (OpenStackBaseException e) {
// Convert Keystone OpenStackResponseException to MsoOpenstackException
- throw keystoneErrorToMsoException (e, "QueryTenant");
+ throw keystoneErrorToMsoException(e, "QueryTenant");
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, "QueryTenant");
+ throw runtimeExceptionToMsoException(e, "QueryTenant");
}
}
/**
- * Query for a tenant with the specified name in the given cloud. If the tenant exists,
- * return an MsoTenant object. If not, return null. This query is useful if the client
- * knows it has the tenant name, skipping an initial lookup by ID that would always fail.
+ * Query for a tenant with the specified name in the given cloud. If the tenant exists, return an MsoTenant object.
+ * If not, return null. This query is useful if the client knows it has the tenant name, skipping an initial lookup
+ * by ID that would always fail.
* <p>
- * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin
- * requests go to the centralized identity service in DCP. However, if some artifact
- * must exist in each local LCP instance as well, then it will be needed to access the
- * correct region.
+ * For the AIC Cloud (DCP/LCP): it is not clear that cloudId is needed, as all admin requests go to the centralized
+ * identity service in DCP. However, if some artifact must exist in each local LCP instance as well, then it will be
+ * needed to access the correct region.
* <p>
*
* @param tenantName The name of the tenant to query
@@ -250,44 +240,43 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
* @return the tenant properties of the queried tenant, or null if not found
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
*/
- public MsoTenant queryTenantByName (String tenantName, String cloudSiteId) throws MsoException {
+ public MsoTenant queryTenantByName(String tenantName, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will query the tenant
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
- Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSite);
try {
- Tenant tenant = findTenantByName (keystoneAdminClient, tenantName);
+ Tenant tenant = findTenantByName(keystoneAdminClient, tenantName);
if (tenant == null) {
return null;
}
- Map <String, String> metadata = new HashMap <String, String> ();
- if (cloudSite.getIdentityService().getTenantMetadata ()) {
- OpenStackRequest <Metadata> request = keystoneAdminClient.tenants ().showMetadata (tenant.getId ());
- Metadata tenantMetadata = executeAndRecordOpenstackRequest (request);
+ Map<String, String> metadata = new HashMap<String, String>();
+ if (cloudSite.getIdentityService().getTenantMetadata()) {
+ OpenStackRequest<Metadata> request = keystoneAdminClient.tenants().showMetadata(tenant.getId());
+ Metadata tenantMetadata = executeAndRecordOpenstackRequest(request);
if (tenantMetadata != null) {
- metadata = tenantMetadata.getMetadata ();
+ metadata = tenantMetadata.getMetadata();
}
}
- return new MsoTenant (tenant.getId (), tenant.getName (), metadata);
+ return new MsoTenant(tenant.getId(), tenant.getName(), metadata);
} catch (OpenStackBaseException e) {
// Convert Keystone OpenStackResponseException to MsoOpenstackException
- throw keystoneErrorToMsoException (e, "QueryTenantName");
+ throw keystoneErrorToMsoException(e, "QueryTenantName");
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, "QueryTenantName");
+ throw runtimeExceptionToMsoException(e, "QueryTenantName");
}
}
/**
- * Delete the specified Tenant (by ID) in the given cloud. This method returns true or
- * false, depending on whether the tenant existed and was successfully deleted, or if
- * the tenant already did not exist. Both cases are treated as success (no Exceptions).
+ * Delete the specified Tenant (by ID) in the given cloud. This method returns true or false, depending on whether
+ * the tenant existed and was successfully deleted, or if the tenant already did not exist. Both cases are treated
+ * as success (no Exceptions).
* <p>
- * Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity
- * service in DCP. So deleting a tenant from one cloudSiteId will remove it from all
- * sites managed by that identity service.
+ * Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity service in DCP. So deleting a
+ * tenant from one cloudSiteId will remove it from all sites managed by that identity service.
* <p>
*
* @param tenantId The Openstack ID of the tenant to delete
@@ -295,43 +284,42 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
* @return true if the tenant was deleted, false if the tenant did not exist.
* @throws MsoOpenstackException If the Openstack API call returns an exception.
*/
- public boolean deleteTenant (String tenantId, String cloudSiteId) throws MsoException {
+ public boolean deleteTenant(String tenantId, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will query the tenant
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
- Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSite);
try {
// Check that the tenant exists. Also, need the ID to delete
- Tenant tenant = findTenantById (keystoneAdminClient, tenantId);
+ Tenant tenant = findTenantById(keystoneAdminClient, tenantId);
if (tenant == null) {
logger.error("{} Tenant id {} not found on cloud site id {}, {}", MessageEnum.RA_TENANT_NOT_FOUND,
- tenantId, cloudSiteId, ErrorCode.DataError.getValue());
+ tenantId, cloudSiteId, ErrorCode.DataError.getValue());
return false;
}
- OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ());
- executeAndRecordOpenstackRequest (request);
- logger.debug ("Deleted Tenant {} ({})", tenant.getId(), tenant.getName());
+ OpenStackRequest<Void> request = keystoneAdminClient.tenants().delete(tenant.getId());
+ executeAndRecordOpenstackRequest(request);
+ logger.debug("Deleted Tenant {} ({})", tenant.getId(), tenant.getName());
} catch (OpenStackBaseException e) {
// Convert Keystone OpenStackResponseException to MsoOpenstackException
- throw keystoneErrorToMsoException (e, "Delete Tenant");
+ throw keystoneErrorToMsoException(e, "Delete Tenant");
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, "DeleteTenant");
+ throw runtimeExceptionToMsoException(e, "DeleteTenant");
}
return true;
}
/**
- * Delete the specified Tenant (by Name) in the given cloud. This method returns true or
- * false, depending on whether the tenant existed and was successfully deleted, or if
- * the tenant already did not exist. Both cases are treated as success (no Exceptions).
+ * Delete the specified Tenant (by Name) in the given cloud. This method returns true or false, depending on whether
+ * the tenant existed and was successfully deleted, or if the tenant already did not exist. Both cases are treated
+ * as success (no Exceptions).
* <p>
- * Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity
- * service in DCP. So deleting a tenant from one cloudSiteId will remove it from all
- * sites managed by that identity service.
+ * Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity service in DCP. So deleting a
+ * tenant from one cloudSiteId will remove it from all sites managed by that identity service.
* <p>
*
* @param tenantName The name of the tenant to delete
@@ -339,37 +327,37 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
* @return true if the tenant was deleted, false if the tenant did not exist.
* @throws MsoOpenstackException If the Openstack API call returns an exception.
*/
- public boolean deleteTenantByName (String tenantName, String cloudSiteId) throws MsoException {
+ public boolean deleteTenantByName(String tenantName, String cloudSiteId) throws MsoException {
// Obtain the cloud site information where we will query the tenant
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSite.isPresent()) {
- throw new MsoCloudSiteNotFound (cloudSiteId);
+ throw new MsoCloudSiteNotFound(cloudSiteId);
}
- Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite.get());
+ Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSite.get());
try {
// Need the Tenant ID to delete (can't directly delete by name)
- Tenant tenant = findTenantByName (keystoneAdminClient, tenantName);
+ Tenant tenant = findTenantByName(keystoneAdminClient, tenantName);
if (tenant == null) {
// OK if tenant already doesn't exist.
logger.error("{} Tenant {} not found on Cloud site id {}, {}", MessageEnum.RA_TENANT_NOT_FOUND,
- tenantName, cloudSiteId, ErrorCode.DataError.getValue());
+ tenantName, cloudSiteId, ErrorCode.DataError.getValue());
return false;
}
// Execute the Delete. It has no return value.
- OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ());
- executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Void> request = keystoneAdminClient.tenants().delete(tenant.getId());
+ executeAndRecordOpenstackRequest(request);
logger.debug("Deleted Tenant {} ({})", tenant.getId(), tenant.getName());
} catch (OpenStackBaseException e) {
// Note: It doesn't seem to matter if tenant doesn't exist, no exception is thrown.
// Convert Keystone OpenStackResponseException to MsoOpenstackException
- throw keystoneErrorToMsoException (e, "DeleteTenant");
+ throw keystoneErrorToMsoException(e, "DeleteTenant");
} catch (RuntimeException e) {
// Catch-all
- throw runtimeExceptionToMsoException (e, "DeleteTenant");
+ throw runtimeExceptionToMsoException(e, "DeleteTenant");
}
return true;
@@ -379,26 +367,24 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
// PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
/*
- * Get a Keystone Admin client for the Openstack Identity service.
- * This requires an 'admin'-level userId + password along with an 'admin' tenant
- * in the target cloud. These values will be retrieved from properties based
- * on the specified cloud ID.
- * <p>
- * On successful authentication, the Keystone object will be cached for the cloudId
- * so that it can be reused without going back to Openstack every time.
+ * Get a Keystone Admin client for the Openstack Identity service. This requires an 'admin'-level userId + password
+ * along with an 'admin' tenant in the target cloud. These values will be retrieved from properties based on the
+ * specified cloud ID. <p> On successful authentication, the Keystone object will be cached for the cloudId so that
+ * it can be reused without going back to Openstack every time.
*
* @param cloudId
*
* @return an authenticated Keystone object
*/
- public Keystone getKeystoneAdminClient (CloudSite cloudSite) throws MsoException {
+ public Keystone getKeystoneAdminClient(CloudSite cloudSite) throws MsoException {
CloudIdentity cloudIdentity = cloudSite.getIdentityService();
- String cloudId = cloudIdentity.getId ();
- String adminTenantName = cloudIdentity.getAdminTenant ();
- String region = cloudSite.getRegionId ();
+ String cloudId = cloudIdentity.getId();
+ String adminTenantName = cloudIdentity.getAdminTenant();
+ String region = cloudSite.getRegionId();
- MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
+ MsoTenantUtils tenantUtils =
+ tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
final String keystoneUrl = tenantUtils.getKeystoneUrl(region, cloudIdentity);
Keystone keystone = new Keystone(keystoneUrl);
@@ -406,51 +392,50 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
Access access = null;
String token = null;
try {
- Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
- OpenStackRequest <Access> request = keystone.tokens ()
- .authenticate (credentials)
- .withTenantName (adminTenantName);
- access = executeAndRecordOpenstackRequest (request);
- token = access.getToken ().getId ();
+ Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
+ OpenStackRequest<Access> request =
+ keystone.tokens().authenticate(credentials).withTenantName(adminTenantName);
+ access = executeAndRecordOpenstackRequest(request);
+ token = access.getToken().getId();
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 401) {
+ if (e.getStatus() == 401) {
// Authentication error. Can't access admin tenant - something is mis-configured
- String error = "MSO Authentication Failed for " + cloudIdentity.getId ();
+ String error = "MSO Authentication Failed for " + cloudIdentity.getId();
- throw new MsoAdapterException (error);
+ throw new MsoAdapterException(error);
} else {
- throw keystoneErrorToMsoException (e, "TokenAuth");
+ throw keystoneErrorToMsoException(e, "TokenAuth");
}
} catch (OpenStackConnectException e) {
// Connection to Openstack failed
- throw keystoneErrorToMsoException (e, "TokenAuth");
+ throw keystoneErrorToMsoException(e, "TokenAuth");
}
// Get the Identity service URL. Throws runtime exception if not found per region.
String adminUrl = null;
try {
- // TODO: FOR TESTING!!!!
- adminUrl = KeystoneUtils.findEndpointURL (access.getServiceCatalog (), "identity", region, "public");
- adminUrl = adminUrl.replaceFirst("5000", "35357");
+ // TODO: FOR TESTING!!!!
+ adminUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "identity", region, "public");
+ adminUrl = adminUrl.replaceFirst("5000", "35357");
} catch (RuntimeException e) {
- String error = "Identity service not found: region=" + region + ",cloud=" + cloudIdentity.getId ();
+ String error = "Identity service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
logger.error("{} Region: {} Cloud identity {} {} Exception in findEndpointURL ",
- MessageEnum.IDENTITY_SERVICE_NOT_FOUND, region, cloudIdentity.getId(),
- ErrorCode.DataError.getValue(), e);
- throw new MsoAdapterException (error, e);
+ MessageEnum.IDENTITY_SERVICE_NOT_FOUND, region, cloudIdentity.getId(),
+ ErrorCode.DataError.getValue(), e);
+ throw new MsoAdapterException(error, e);
}
// A new Keystone object is required for the new URL. Use the auth token from above.
// Note: this doesn't go back to Openstack, it's just a local object.
- keystone = new Keystone (adminUrl);
- keystone.token (token);
+ keystone = new Keystone(adminUrl);
+ keystone.token(token);
return keystone;
}
/*
- * Find a tenant (or query its existance) by its Name or Id. Check first against the
- * ID. If that fails, then try by name.
+ * Find a tenant (or query its existance) by its Name or Id. Check first against the ID. If that fails, then try by
+ * name.
*
* @param adminClient an authenticated Keystone object
*
@@ -458,14 +443,14 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
*
* @return a Tenant object or null if not found
*/
- public Tenant findTenantByNameOrId (Keystone adminClient, String tenantNameOrId) {
+ public Tenant findTenantByNameOrId(Keystone adminClient, String tenantNameOrId) {
if (tenantNameOrId == null) {
return null;
}
- Tenant tenant = findTenantById (adminClient, tenantNameOrId);
+ Tenant tenant = findTenantById(adminClient, tenantNameOrId);
if (tenant == null) {
- tenant = findTenantByName (adminClient, tenantNameOrId);
+ tenant = findTenantByName(adminClient, tenantNameOrId);
}
return tenant;
@@ -480,28 +465,28 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
*
* @return a Tenant object or null if not found
*/
- private Tenant findTenantById (Keystone adminClient, String tenantId) {
+ private Tenant findTenantById(Keystone adminClient, String tenantId) {
if (tenantId == null) {
return null;
}
try {
- OpenStackRequest <Tenant> request = adminClient.tenants ().show (tenantId);
- return executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Tenant> request = adminClient.tenants().show(tenantId);
+ return executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 404) {
+ if (e.getStatus() == 404) {
return null;
} else {
logger.error("{} {} Openstack Error, GET Tenant by Id ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), tenantId, e);
+ ErrorCode.DataError.getValue(), tenantId, e);
throw e;
}
}
}
/*
- * Find a tenant (or query its existance) by its Name. This method avoids an
- * initial lookup by ID when it's known that we have the tenant Name.
+ * Find a tenant (or query its existance) by its Name. This method avoids an initial lookup by ID when it's known
+ * that we have the tenant Name.
*
* @param adminClient an authenticated Keystone object
*
@@ -509,28 +494,27 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
*
* @return a Tenant object or null if not found
*/
- public Tenant findTenantByName (Keystone adminClient, String tenantName) {
+ public Tenant findTenantByName(Keystone adminClient, String tenantName) {
if (tenantName == null) {
return null;
}
try {
- OpenStackRequest <Tenant> request = adminClient.tenants ().show ("").queryParam ("name", tenantName);
- return executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Tenant> request = adminClient.tenants().show("").queryParam("name", tenantName);
+ return executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 404) {
+ if (e.getStatus() == 404) {
return null;
} else {
logger.error("{} {} Openstack Error, GET Tenant By Name ({}) ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), tenantName, e);
+ ErrorCode.DataError.getValue(), tenantName, e);
throw e;
}
}
}
/*
- * Look up an Openstack User by Name or Openstack ID. Check the ID first, and if that
- * fails, try the Name.
+ * Look up an Openstack User by Name or Openstack ID. Check the ID first, and if that fails, try the Name.
*
* @param adminClient an authenticated Keystone object
*
@@ -538,29 +522,28 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
*
* @return a User object or null if not found
*/
- private User findUserByNameOrId (Keystone adminClient, String userNameOrId) {
+ private User findUserByNameOrId(Keystone adminClient, String userNameOrId) {
if (userNameOrId == null) {
return null;
}
try {
- OpenStackRequest <User> request = adminClient.users ().show (userNameOrId);
- return executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<User> request = adminClient.users().show(userNameOrId);
+ return executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 404) {
+ if (e.getStatus() == 404) {
// Not found by ID. Search for name
- return findUserByName (adminClient, userNameOrId);
+ return findUserByName(adminClient, userNameOrId);
} else {
logger.error("{} {} Openstack Error, GET User ({}) ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), userNameOrId, e);
+ ErrorCode.DataError.getValue(), userNameOrId, e);
throw e;
}
}
}
/*
- * Look up an Openstack User by Name. This avoids initial Openstack query by ID
- * if we know we have the User Name.
+ * Look up an Openstack User by Name. This avoids initial Openstack query by ID if we know we have the User Name.
*
* @param adminClient an authenticated Keystone object
*
@@ -568,31 +551,29 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
*
* @return a User object or null if not found
*/
- public User findUserByName (Keystone adminClient, String userName) {
+ public User findUserByName(Keystone adminClient, String userName) {
if (userName == null) {
return null;
}
try {
- OpenStackRequest <User> request = adminClient.users ().show ("").queryParam ("name", userName);
- return executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<User> request = adminClient.users().show("").queryParam("name", userName);
+ return executeAndRecordOpenstackRequest(request);
} catch (OpenStackResponseException e) {
- if (e.getStatus () == 404) {
+ if (e.getStatus() == 404) {
return null;
} else {
logger.error("{} {} Openstack Error, GET User By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), userName, e);
+ ErrorCode.DataError.getValue(), userName, e);
throw e;
}
}
}
/*
- * Look up an Openstack Role by Name or Id. There is no direct query for Roles, so
- * need to retrieve a full list from Openstack and look for a match. By default,
- * Openstack should have a "_member_" role for normal VM-level privileges and an
- * "admin" role for expanded privileges (e.g. administer tenants, users, and roles).
- * <p>
+ * Look up an Openstack Role by Name or Id. There is no direct query for Roles, so need to retrieve a full list from
+ * Openstack and look for a match. By default, Openstack should have a "_member_" role for normal VM-level
+ * privileges and an "admin" role for expanded privileges (e.g. administer tenants, users, and roles). <p>
*
* @param adminClient an authenticated Keystone object
*
@@ -600,17 +581,17 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
*
* @return a Role object
*/
- private Role findRoleByNameOrId (Keystone adminClient, String roleNameOrId) {
+ private Role findRoleByNameOrId(Keystone adminClient, String roleNameOrId) {
if (roleNameOrId == null) {
return null;
}
// Search by name or ID. Must search in list
- OpenStackRequest <Roles> request = adminClient.roles ().list ();
- Roles roles = executeAndRecordOpenstackRequest (request);
+ OpenStackRequest<Roles> request = adminClient.roles().list();
+ Roles roles = executeAndRecordOpenstackRequest(request);
for (Role role : roles) {
- if (roleNameOrId.equals (role.getName ()) || roleNameOrId.equals (role.getId ())) {
+ if (roleNameOrId.equals(role.getName()) || roleNameOrId.equals(role.getId())) {
return role;
}
}
@@ -618,8 +599,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
return null;
}
- @Override
- public String getKeystoneUrl(String regionId, CloudIdentity cloudIdentity) throws MsoException {
- return cloudIdentity.getIdentityUrl();
- }
+ @Override
+ public String getKeystoneUrl(String regionId, CloudIdentity cloudIdentity) throws MsoException {
+ return cloudIdentity.getIdentityUrl();
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java
index 067763cc1a..63bc235363 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java
@@ -21,7 +21,6 @@
package org.onap.so.openstack.utils;
import java.util.Map;
-
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.openstack.beans.MsoTenant;
import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
@@ -31,31 +30,31 @@ import org.springframework.stereotype.Component;
@Component
public class MsoKeystoneV3Utils extends MsoTenantUtils {
- @Override
- public String createTenant(String tenantName, String cloudSiteId, Map<String, String> metadata, boolean backout)
- throws MsoException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public MsoTenant queryTenant(String tenantId, String cloudSiteId) throws MsoException, MsoCloudSiteNotFound {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public MsoTenant queryTenantByName(String tenantName, String cloudSiteId)
- throws MsoException, MsoCloudSiteNotFound {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean deleteTenant(String tenantId, String cloudSiteId) throws MsoException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getKeystoneUrl(String regionId, CloudIdentity cloudIdentity) throws MsoException {
- return cloudIdentity.getIdentityUrl();
- }
+ @Override
+ public String createTenant(String tenantName, String cloudSiteId, Map<String, String> metadata, boolean backout)
+ throws MsoException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public MsoTenant queryTenant(String tenantId, String cloudSiteId) throws MsoException, MsoCloudSiteNotFound {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public MsoTenant queryTenantByName(String tenantName, String cloudSiteId)
+ throws MsoException, MsoCloudSiteNotFound {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean deleteTenant(String tenantId, String cloudSiteId) throws MsoException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public String getKeystoneUrl(String regionId, CloudIdentity cloudIdentity) throws MsoException {
+ return cloudIdentity.getIdentityUrl();
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java
index eb003cdda6..2788387bc1 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java
@@ -64,7 +64,7 @@ import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
-public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
+public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
public static final String OOF_DIRECTIVES = "oof_directives";
public static final String SDNC_DIRECTIVES = "sdnc_directives";
@@ -94,29 +94,25 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
*******************************************************************************/
/**
- * Create a new Stack in the specified cloud location and tenant. The Heat template
- * and parameter map are passed in as arguments, along with the cloud access credentials.
- * It is expected that parameters have been validated and contain at minimum the required
- * parameters for the given template with no extra (undefined) parameters..
+ * Create a new Stack in the specified cloud location and tenant. The Heat template and parameter map are passed in
+ * as arguments, along with the cloud access credentials. It is expected that parameters have been validated and
+ * contain at minimum the required parameters for the given template with no extra (undefined) parameters..
*
- * The Stack name supplied by the caller must be unique in the scope of this tenant.
- * However, it should also be globally unique, as it will be the identifier for the
- * resource going forward in Inventory. This latter is managed by the higher levels
- * invoking this function.
+ * The Stack name supplied by the caller must be unique in the scope of this tenant. However, it should also be
+ * globally unique, as it will be the identifier for the resource going forward in Inventory. This latter is managed
+ * by the higher levels invoking this function.
*
- * The caller may choose to let this function poll Openstack for completion of the
- * stack creation, or may handle polling itself via separate calls to query the status.
- * In either case, a StackInfo object will be returned containing the current status.
- * When polling is enabled, a status of CREATED is expected. When not polling, a
+ * The caller may choose to let this function poll Openstack for completion of the stack creation, or may handle
+ * polling itself via separate calls to query the status. In either case, a StackInfo object will be returned
+ * containing the current status. When polling is enabled, a status of CREATED is expected. When not polling, a
* status of BUILDING is expected.
*
- * An error will be thrown if the requested Stack already exists in the specified
- * Tenant and Cloud.
+ * An error will be thrown if the requested Stack already exists in the specified Tenant and Cloud.
*
- * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as
- * parameters for createStack. If environment is non-null, it will be added to the stack.
- * The nested templates and get_file entries both end up being added to the "files" on the
- * stack. We must combine them before we add them to the stack if they're both non-null.
+ * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as parameters for
+ * createStack. If environment is non-null, it will be added to the stack. The nested templates and get_file entries
+ * both end up being added to the "files" on the stack. We must combine them before we add them to the stack if
+ * they're both non-null.
*
* @param cloudSiteId The cloud (may be a region) in which to create the stack
* @param cloudOwner the cloud owner of the cloud site in which to create the stack
@@ -136,19 +132,10 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
@SuppressWarnings("unchecked")
@Override
- public StackInfo createStack (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String stackName,
- VduModelInfo vduModel,
- String heatTemplate,
- Map <String, ?> stackInputs,
- boolean pollForCompletion,
- int timeoutMinutes,
- String environment,
- Map <String, Object> files,
- Map <String, Object> heatFiles,
- boolean backout) throws MsoException {
+ public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName,
+ VduModelInfo vduModel, String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion,
+ int timeoutMinutes, String environment, Map<String, Object> files, Map<String, Object> heatFiles,
+ boolean backout) throws MsoException {
logger.trace("Started MsoMulticloudUtils.createStack");
@@ -160,7 +147,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
String vfModuleId = "";
String templateType = "";
- for (String key: MULTICLOUD_INPUTS) {
+ for (String key : MULTICLOUD_INPUTS) {
if (!stackInputs.isEmpty() && stackInputs.containsKey(key)) {
if (key == OOF_DIRECTIVES) {
oofDirectives = (String) stackInputs.get(key);
@@ -181,17 +168,18 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
}
- if (!stackInputs.isEmpty() && stackInputs.containsKey(VF_MODULE_ID)){
+ if (!stackInputs.isEmpty() && stackInputs.containsKey(VF_MODULE_ID)) {
vfModuleId = (String) stackInputs.get(VF_MODULE_ID);
}
- if (!stackInputs.isEmpty() && stackInputs.containsKey(VNF_ID)){
+ if (!stackInputs.isEmpty() && stackInputs.containsKey(VNF_ID)) {
genericVnfId = (String) stackInputs.get(VNF_ID);
}
// create the multicloud payload
- CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
+ CreateStackParam stack =
+ createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
- MulticloudRequest multicloudRequest= new MulticloudRequest();
+ MulticloudRequest multicloudRequest = new MulticloudRequest();
multicloudRequest.setGenericVnfId(genericVnfId);
multicloudRequest.setVfModuleId(vfModuleId);
@@ -230,11 +218,13 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
if (logger.isDebugEnabled()) {
logger.debug("Multicloud Create Response Body: {}", multicloudResponseBody);
}
- StackInfo stackStatus = getStackStatus(cloudSiteId, cloudOwner, tenantId, canonicalName, pollForCompletion, timeoutMinutes, backout);
+ StackInfo stackStatus = getStackStatus(cloudSiteId, cloudOwner, tenantId, canonicalName, pollForCompletion,
+ timeoutMinutes, backout);
if (HeatStatus.CREATED.equals(stackStatus.getStatus())) {
String workloadId = multicloudResponseBody == null ? null : multicloudResponseBody.getWorkloadId();
- multicloudAaiUpdate(cloudSiteId, cloudOwner, tenantId, genericVnfId, vfModuleId, workloadId, pollForCompletion, timeoutMinutes);
+ multicloudAaiUpdate(cloudSiteId, cloudOwner, tenantId, genericVnfId, vfModuleId, workloadId,
+ pollForCompletion, timeoutMinutes);
}
return stackStatus;
@@ -249,8 +239,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
@Override
- public Map<String, Object> queryStackForOutputs(String cloudSiteId, String cloudOwner,
- String tenantId, String stackName) throws MsoException {
+ public Map<String, Object> queryStackForOutputs(String cloudSiteId, String cloudOwner, String tenantId,
+ String stackName) throws MsoException {
logger.debug("MsoHeatUtils.queryStackForOutputs)");
StackInfo heatStack = this.queryStack(cloudSiteId, cloudOwner, tenantId, stackName);
if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
@@ -260,9 +250,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
/**
- * Query for a single stack (by ID) in a tenant. This call will always return a
- * StackInfo object. If the stack does not exist, an "empty" StackInfo will be
- * returned - containing only the stack name and a status of NOTFOUND.
+ * Query for a single stack (by ID) in a tenant. This call will always return a StackInfo object. If the stack does
+ * not exist, an "empty" StackInfo will be returned - containing only the stack name and a status of NOTFOUND.
*
* @param tenantId The Openstack ID of the tenant in which to query
* @param cloudSiteId The cloud identifier (may be a region) in which to query
@@ -272,9 +261,10 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
* @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
*/
@Override
- public StackInfo queryStack (String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
+ public StackInfo queryStack(String cloudSiteId, String cloudOwner, String tenantId, String instanceId)
+ throws MsoException {
if (logger.isDebugEnabled()) {
- logger.debug (String.format("Query multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
+ logger.debug(String.format("Query multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
}
String stackName = null;
String stackId = null;
@@ -296,7 +286,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
if (multicloudClient != null) {
Response response = multicloudClient.get();
if (logger.isDebugEnabled()) {
- logger.debug (String.format("Multicloud GET Response: %s", response.toString()));
+ logger.debug(String.format("Multicloud GET Response: %s", response.toString()));
}
MulticloudQueryResponse multicloudQueryBody = null;
@@ -304,7 +294,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
returnInfo.setStatus(HeatStatus.NOTFOUND);
returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
} else if (response.getStatus() == Response.Status.OK.getStatusCode() && response.hasEntity()) {
- multicloudQueryBody = getQueryBody((java.io.InputStream)response.getEntity());
+ multicloudQueryBody = getQueryBody((java.io.InputStream) response.getEntity());
if (multicloudQueryBody != null) {
returnInfo.setCanonicalName(stackName + "/" + multicloudQueryBody.getWorkloadId());
returnInfo.setStatus(getHeatStatus(multicloudQueryBody.getWorkloadStatus()));
@@ -325,9 +315,10 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
return returnInfo;
}
- public StackInfo deleteStack (String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
+ public StackInfo deleteStack(String cloudSiteId, String cloudOwner, String tenantId, String instanceId)
+ throws MsoException {
if (logger.isDebugEnabled()) {
- logger.debug (String.format("Delete multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
+ logger.debug(String.format("Delete multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
}
String stackName = null;
String stackId = null;
@@ -372,23 +363,33 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
// PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
private HeatStatus getHeatStatus(String workloadStatus) {
- if (workloadStatus.length() == 0) return HeatStatus.INIT;
- if ("CREATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.BUILDING;
- if ("CREATE_COMPLETE".equals(workloadStatus)) return HeatStatus.CREATED;
- if ("CREATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
- if ("DELETE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.DELETING;
- if ("DELETE_COMPLETE".equals(workloadStatus)) return HeatStatus.NOTFOUND;
- if ("DELETE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
- if ("UPDATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.UPDATING;
- if ("UPDATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
- if ("UPDATE_COMPLETE".equals(workloadStatus)) return HeatStatus.UPDATED;
+ if (workloadStatus.length() == 0)
+ return HeatStatus.INIT;
+ if ("CREATE_IN_PROGRESS".equals(workloadStatus))
+ return HeatStatus.BUILDING;
+ if ("CREATE_COMPLETE".equals(workloadStatus))
+ return HeatStatus.CREATED;
+ if ("CREATE_FAILED".equals(workloadStatus))
+ return HeatStatus.FAILED;
+ if ("DELETE_IN_PROGRESS".equals(workloadStatus))
+ return HeatStatus.DELETING;
+ if ("DELETE_COMPLETE".equals(workloadStatus))
+ return HeatStatus.NOTFOUND;
+ if ("DELETE_FAILED".equals(workloadStatus))
+ return HeatStatus.FAILED;
+ if ("UPDATE_IN_PROGRESS".equals(workloadStatus))
+ return HeatStatus.UPDATING;
+ if ("UPDATE_FAILED".equals(workloadStatus))
+ return HeatStatus.FAILED;
+ if ("UPDATE_COMPLETE".equals(workloadStatus))
+ return HeatStatus.UPDATED;
return HeatStatus.UNKNOWN;
}
- private void multicloudAaiUpdate(String cloudSiteId, String cloudOwner, String tenantId, String genericVnfId, String vfModuleId, String workloadId,
- boolean pollForCompletion, int timeoutMinutes) {
+ private void multicloudAaiUpdate(String cloudSiteId, String cloudOwner, String tenantId, String genericVnfId,
+ String vfModuleId, String workloadId, boolean pollForCompletion, int timeoutMinutes) {
- MulticloudRequest multicloudRequest= new MulticloudRequest();
+ MulticloudRequest multicloudRequest = new MulticloudRequest();
multicloudRequest.setGenericVnfId(genericVnfId);
multicloudRequest.setVfModuleId(vfModuleId);
@@ -405,7 +406,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
Response response = multicloudClient.post(multicloudRequest);
if (response.getStatus() != Response.Status.ACCEPTED.getStatusCode()) {
if (logger.isDebugEnabled())
- logger.debug("Multicloud AAI update request failed: " + response.getStatus() + response.getStatusInfo());
+ logger.debug(
+ "Multicloud AAI update request failed: " + response.getStatus() + response.getStatusInfo());
return;
}
@@ -413,7 +415,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
return;
}
- int updatePollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
+ int updatePollInterval =
+ Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
int pollTimeout = (timeoutMinutes * 60) + updatePollInterval;
boolean updateTimedOut = false;
logger.debug("updatePollInterval=" + updatePollInterval + ", pollTimeout=" + pollTimeout);
@@ -423,14 +426,15 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
try {
stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, workloadId);
if (logger.isDebugEnabled())
- logger.debug (stackInfo.getStatus() + " (" + workloadId + ")");
+ logger.debug(stackInfo.getStatus() + " (" + workloadId + ")");
if (HeatStatus.UPDATING.equals(stackInfo.getStatus())) {
if (pollTimeout <= 0) {
// Note that this should not occur, since there is a timeout specified
// in the Openstack (multicloud?) call.
if (logger.isDebugEnabled())
- logger.debug("Multicloud AAI update timeout failure: {} {} {} {}", cloudOwner, cloudSiteId, tenantId, workloadId);
+ logger.debug("Multicloud AAI update timeout failure: {} {} {} {}", cloudOwner, cloudSiteId,
+ tenantId, workloadId);
updateTimedOut = true;
break;
}
@@ -445,27 +449,33 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
} catch (MsoException me) {
if (logger.isDebugEnabled())
- logger.debug("Multicloud AAI update exception: {} {} {} {}", cloudOwner, cloudSiteId, tenantId, workloadId, me);
+ logger.debug("Multicloud AAI update exception: {} {} {} {}", cloudOwner, cloudSiteId, tenantId,
+ workloadId, me);
return;
}
}
if (updateTimedOut) {
if (logger.isDebugEnabled())
- logger.debug("Multicloud AAI update request failed: {} {}", response.getStatus(), response.getStatusInfo().toString());
+ logger.debug("Multicloud AAI update request failed: {} {}", response.getStatus(),
+ response.getStatusInfo().toString());
} else if (!HeatStatus.UPDATED.equals(stackInfo.getStatus())) {
if (logger.isDebugEnabled())
- logger.debug("Multicloud AAI update request failed: {} {}", response.getStatus(), response.getStatusInfo().toString());
+ logger.debug("Multicloud AAI update request failed: {} {}", response.getStatus(),
+ response.getStatusInfo().toString());
} else {
if (logger.isDebugEnabled())
- logger.debug("Multicloud AAI update successful: {} {}", response.getStatus(), response.getStatusInfo().toString());
+ logger.debug("Multicloud AAI update successful: {} {}", response.getStatus(),
+ response.getStatusInfo().toString());
}
}
- private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
+ private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId)
+ throws MsoException {
return getStackStatus(cloudSiteId, cloudOwner, tenantId, instanceId, false, 0, false);
}
- private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId, boolean pollForCompletion, int timeoutMinutes, boolean backout) throws MsoException {
+ private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId,
+ boolean pollForCompletion, int timeoutMinutes, boolean backout) throws MsoException {
StackInfo stackInfo = new StackInfo();
// If client has requested a final response, poll for stack completion
@@ -474,7 +484,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
// Use the resource (template) timeout for Openstack (expressed in minutes)
// and add one poll interval to give Openstack a chance to fail on its own.s
- int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
+ int createPollInterval =
+ Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
// New 1610 - poll on delete if we rollback - use same values for now
int deletePollInterval = createPollInterval;
@@ -486,7 +497,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
while (true) {
try {
stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
- logger.debug (stackInfo.getStatus() + " (" + instanceId + ")");
+ logger.debug(stackInfo.getStatus() + " (" + instanceId + ")");
if (HeatStatus.BUILDING.equals(stackInfo.getStatus())) {
// Stack creation is still running.
@@ -494,7 +505,10 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
if (pollTimeout <= 0) {
// Note that this should not occur, since there is a timeout specified
// in the Openstack (multicloud?) call.
- logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId, instanceId, stackInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(), "Create stack timeout"));
+ logger.error(String.format("%s %s %s %s %s %s %s %s %d %s",
+ MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId,
+ instanceId, stackInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(),
+ "Create stack timeout"));
createTimedOut = true;
break;
}
@@ -504,20 +518,28 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
pollTimeout -= createPollInterval;
logger.debug("pollTimeout remaining: " + pollTimeout);
} else {
- //save off the status & reason msg before we attempt delete
- stackErrorStatusReason.append("Stack error (" + stackInfo.getStatus() + "): " + stackInfo.getStatusMessage());
+ // save off the status & reason msg before we attempt delete
+ stackErrorStatusReason
+ .append("Stack error (" + stackInfo.getStatus() + "): " + stackInfo.getStatusMessage());
break;
}
} catch (MsoException me) {
// Cannot query the stack status. Something is wrong.
// Try to roll back the stack
if (!backout) {
- logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack error, stack deletion suppressed", "", "", ErrorCode.BusinessProcesssError.getValue(), "Exception in Create Stack, stack deletion suppressed"));
+ logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack error, stack deletion suppressed", "", "",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Exception in Create Stack, stack deletion suppressed"));
} else {
try {
- logger.debug("Create Stack error - unable to query for stack status - attempting to delete stack: " + instanceId + " - This will likely fail and/or we won't be able to query to see if delete worked");
+ logger.debug(
+ "Create Stack error - unable to query for stack status - attempting to delete stack: "
+ + instanceId
+ + " - This will likely fail and/or we won't be able to query to see if delete worked");
StackInfo deleteInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
- // this may be a waste of time - if we just got an exception trying to query the stack - we'll just
+ // this may be a waste of time - if we just got an exception trying to query the stack -
+ // we'll just
// get another one, n'est-ce pas?
boolean deleted = false;
while (!deleted) {
@@ -526,52 +548,66 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
if (deletePollTimeout <= 0) {
- logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId, instanceId,
- queryInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(),
+ logger.error(String.format("%s %s %s %s %s %s %s %s %d %s",
+ MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner,
+ cloudSiteId, tenantId, instanceId, queryInfo.getStatus(), "", "",
+ ErrorCode.AvailabilityError.getValue(),
"Rollback: DELETE stack timeout"));
break;
} else {
sleep(deletePollInterval * 1000L);
deletePollTimeout -= deletePollInterval;
}
- } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
+ } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())) {
logger.debug("DELETE_COMPLETE for " + instanceId);
deleted = true;
continue;
} else {
- //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
+ // got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and
+ // evaluate
break;
}
} catch (Exception e3) {
// Just log this one. We will report the original exception.
- logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e3, "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack: Nested exception rolling back stack on error on query"));
+ logger.error(String.format("%s %s %s %s %d %s",
+ MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack: Nested exception rolling back stack: " + e3, "", "",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create Stack: Nested exception rolling back stack on error on query"));
}
}
} catch (Exception e2) {
// Just log this one. We will report the original exception.
- logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e2, "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack: Nested exception rolling back stack"));
+ logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack: Nested exception rolling back stack: " + e2, "", "",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create Stack: Nested exception rolling back stack"));
}
}
// Propagate the original exception from Stack Query.
- me.addContext (CREATE_STACK);
+ me.addContext(CREATE_STACK);
throw me;
}
}
if (!HeatStatus.CREATED.equals(stackInfo.getStatus())) {
- logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack error: Polling complete with non-success status: "
- + stackInfo.getStatus () + ", " + stackInfo.getStatusMessage(), "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error"));
+ logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack error: Polling complete with non-success status: " + stackInfo.getStatus() + ", "
+ + stackInfo.getStatusMessage(),
+ "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error"));
// Rollback the stack creation, since it is in an indeterminate state.
if (!backout) {
- logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, stack deletion suppressed", "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error, stack deletion suppressed"));
- }
- else
- {
+ logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack errored, stack deletion suppressed", "", "",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create Stack error, stack deletion suppressed"));
+ } else {
try {
logger.debug("Create Stack errored - attempting to DELETE stack: " + instanceId);
- logger.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout=" + deletePollTimeout);
+ logger.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout="
+ + deletePollTimeout);
StackInfo deleteInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
boolean deleted = false;
while (!deleted) {
@@ -580,35 +616,48 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
if (deletePollTimeout <= 0) {
- logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId, instanceId,
- queryInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(),
+ logger.error(String.format("%s %s %s %s %s %s %s %s %d %s",
+ MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId,
+ tenantId, instanceId, queryInfo.getStatus(), "", "",
+ ErrorCode.AvailabilityError.getValue(),
"Rollback: DELETE stack timeout"));
break;
} else {
sleep(deletePollInterval * 1000L);
deletePollTimeout -= deletePollInterval;
}
- } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
+ } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())) {
logger.debug("DELETE_COMPLETE for " + instanceId);
deleted = true;
continue;
} else {
- //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
- logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, stack deletion FAILED", "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error, stack deletion FAILED"));
- logger.debug("Stack deletion FAILED on a rollback of a create - " + instanceId + ", status=" + queryInfo.getStatus() + ", reason=" + queryInfo.getStatusMessage());
+ // got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and
+ // evaluate
+ logger.warn(String.format("%s %s %s %s %d %s",
+ MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack errored, stack deletion FAILED", "", "",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create Stack error, stack deletion FAILED"));
+ logger.debug("Stack deletion FAILED on a rollback of a create - " + instanceId
+ + ", status=" + queryInfo.getStatus() + ", reason="
+ + queryInfo.getStatusMessage());
break;
}
} catch (MsoException me2) {
// Just log this one. We will report the original exception.
- logger.debug("Exception thrown trying to delete " + instanceId + " on a create->rollback: " + me2.getContextMessage(), me2);
- logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, then stack deletion FAILED - exception thrown", "", "", ErrorCode.BusinessProcesssError.getValue(), me2.getContextMessage()));
+ logger.debug("Exception thrown trying to delete " + instanceId
+ + " on a create->rollback: " + me2.getContextMessage(), me2);
+ logger.warn(String.format("%s %s %s %s %d %s",
+ MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack errored, then stack deletion FAILED - exception thrown", "", "",
+ ErrorCode.BusinessProcesssError.getValue(), me2.getContextMessage()));
}
}
StringBuilder errorContextMessage;
if (createTimedOut) {
errorContextMessage = new StringBuilder("Stack Creation Timeout");
} else {
- errorContextMessage = stackErrorStatusReason;
+ errorContextMessage = stackErrorStatusReason;
}
if (deleted) {
errorContextMessage.append(" - stack successfully deleted");
@@ -617,7 +666,10 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
}
} catch (MsoException e2) {
// shouldn't happen - but handle
- logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e2, "", "", ErrorCode.BusinessProcesssError.getValue(), "Exception in Create Stack: rolling back stack"));
+ logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack: Nested exception rolling back stack: " + e2, "", "",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Exception in Create Stack: rolling back stack"));
}
}
MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
@@ -714,18 +766,19 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
private RestClient getMulticloudClient(String endpoint, String tenantId) {
HttpClient client = null;
try {
- client = httpClientFactory.newJsonClient(
- new URL(endpoint),
- TargetEntity.MULTICLOUD);
+ client = httpClientFactory.newJsonClient(new URL(endpoint), TargetEntity.MULTICLOUD);
if (tenantId != null && !tenantId.isEmpty()) {
client.addAdditionalHeader("Project", tenantId);
}
} catch (MalformedURLException e) {
- logger.debug(String.format("Encountered malformed URL error getting multicloud rest client %s", e.getMessage()));
+ logger.debug(
+ String.format("Encountered malformed URL error getting multicloud rest client %s", e.getMessage()));
} catch (IllegalArgumentException e) {
- logger.debug(String.format("Encountered illegal argument getting multicloud rest client %s",e.getMessage()));
+ logger.debug(
+ String.format("Encountered illegal argument getting multicloud rest client %s", e.getMessage()));
} catch (UriBuilderException e) {
- logger.debug(String.format("Encountered URI builder error getting multicloud rest client %s", e.getMessage()));
+ logger.debug(
+ String.format("Encountered URI builder error getting multicloud rest client %s", e.getMessage()));
}
return client;
}
@@ -734,10 +787,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
try {
return JSON_MAPPER.readTree(directives);
} catch (Exception e) {
- logger.error(String.format("%s %s %s %s %d %s",
- MessageEnum.RA_CREATE_STACK_ERR.toString(),
- "Create Stack: " + e, "", "",
- ErrorCode.BusinessProcesssError.getValue(),
+ logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(),
+ "Create Stack: " + e, "", "", ErrorCode.BusinessProcesssError.getValue(),
"Exception in Create Stack: Invalid JSON format of directives" + directives));
MsoException me = new MsoAdapterException("Invalid JSON format of directives parameter: " + directives);
me.addContext(CREATE_STACK);
@@ -748,62 +799,45 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
/**
* VduPlugin interface for instantiate function.
*
- * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
- * and then invoke the existing function.
+ * Translate the VduPlugin parameters to the corresponding 'createStack' parameters, and then invoke the existing
+ * function.
*/
@Override
- public VduInstance instantiateVdu (
- CloudInfo cloudInfo,
- String instanceName,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException
- {
+ public VduInstance instantiateVdu(CloudInfo cloudInfo, String instanceName, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException {
String cloudSiteId = cloudInfo.getCloudSiteId();
String cloudOwner = cloudInfo.getCloudOwner();
String tenantId = cloudInfo.getTenantId();
// Translate the VDU ModelInformation structure to that which is needed for
- // creating the Heat stack. Loop through the artifacts, looking specifically
- // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
+ // creating the Heat stack. Loop through the artifacts, looking specifically
+ // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
// be attached as a FILE.
String heatTemplate = null;
- Map<String,Object> nestedTemplates = new HashMap<>();
- Map<String,Object> files = new HashMap<>();
+ Map<String, Object> nestedTemplates = new HashMap<>();
+ Map<String, Object> files = new HashMap<>();
String heatEnvironment = null;
- for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
+ for (VduArtifact vduArtifact : vduModel.getArtifacts()) {
if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
heatTemplate = new String(vduArtifact.getContent());
- }
- else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
+ } else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
- }
- else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
+ } else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
heatEnvironment = new String(vduArtifact.getContent());
}
}
try {
- StackInfo stackInfo = createStack (cloudSiteId,
- cloudOwner,
- tenantId,
- instanceName,
- vduModel,
- heatTemplate,
- inputs,
- true, // poll for completion
- vduModel.getTimeoutMinutes(),
- heatEnvironment,
- nestedTemplates,
- files,
- rollbackOnFailure);
+ StackInfo stackInfo =
+ createStack(cloudSiteId, cloudOwner, tenantId, instanceName, vduModel, heatTemplate, inputs, true, // poll
+ // for
+ // completion
+ vduModel.getTimeoutMinutes(), heatEnvironment, nestedTemplates, files, rollbackOnFailure);
// Populate a vduInstance from the StackInfo
return stackInfoToVduInstance(stackInfo);
- }
- catch (Exception e) {
- throw new VduException ("MsoMulticloudUtils (instantiateVDU): createStack Exception", e);
+ } catch (Exception e) {
+ throw new VduException("MsoMulticloudUtils (instantiateVDU): createStack Exception", e);
}
}
@@ -812,21 +846,18 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
* VduPlugin interface for query function.
*/
@Override
- public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
- throws VduException
- {
+ public VduInstance queryVdu(CloudInfo cloudInfo, String instanceId) throws VduException {
String cloudSiteId = cloudInfo.getCloudSiteId();
String cloudOwner = cloudInfo.getCloudOwner();
String tenantId = cloudInfo.getTenantId();
try {
- // Query the Cloudify Deployment object and populate a VduInstance
- StackInfo stackInfo = queryStack (cloudSiteId, cloudOwner, tenantId, instanceId);
+ // Query the Cloudify Deployment object and populate a VduInstance
+ StackInfo stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
return stackInfoToVduInstance(stackInfo);
- }
- catch (Exception e) {
- throw new VduException ("MsoMulticloudUtils (queryVdu): queryStack Exception ", e);
+ } catch (Exception e) {
+ throw new VduException("MsoMulticloudUtils (queryVdu): queryStack Exception ", e);
}
}
@@ -835,16 +866,14 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
* VduPlugin interface for delete function.
*/
@Override
- public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
- throws VduException
- {
+ public VduInstance deleteVdu(CloudInfo cloudInfo, String instanceId, int timeoutMinutes) throws VduException {
String cloudSiteId = cloudInfo.getCloudSiteId();
String cloudOwner = cloudInfo.getCloudOwner();
String tenantId = cloudInfo.getTenantId();
try {
// Delete the Multicloud stack
- StackInfo stackInfo = deleteStack (cloudSiteId, cloudOwner, tenantId, instanceId);
+ StackInfo stackInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
// Populate a VduInstance based on the deleted Cloudify Deployment object
VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
@@ -853,9 +882,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
vduInstance.getStatus().setState(VduStateType.DELETED);
return vduInstance;
- }
- catch (Exception e) {
- throw new VduException ("Delete VDU Exception", e);
+ } catch (Exception e) {
+ throw new VduException("Delete VDU Exception", e);
}
}
@@ -863,28 +891,21 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
/**
* VduPlugin interface for update function.
*
- * Update is currently not supported in the MsoMulticloudUtils implementation of VduPlugin.
- * Just return a VduException.
+ * Update is currently not supported in the MsoMulticloudUtils implementation of VduPlugin. Just return a
+ * VduException.
*
*/
@Override
- public VduInstance updateVdu (
- CloudInfo cloudInfo,
- String instanceId,
- Map<String,Object> inputs,
- VduModelInfo vduModel,
- boolean rollbackOnFailure)
- throws VduException
- {
- throw new VduException ("MsoMulticloudUtils: updateVdu interface not supported");
+ public VduInstance updateVdu(CloudInfo cloudInfo, String instanceId, Map<String, Object> inputs,
+ VduModelInfo vduModel, boolean rollbackOnFailure) throws VduException {
+ throw new VduException("MsoMulticloudUtils: updateVdu interface not supported");
}
/*
* Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
*/
- protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
- {
+ protected VduInstance stackInfoToVduInstance(StackInfo stackInfo) {
VduInstance vduInstance = new VduInstance();
if (logger.isDebugEnabled()) {
@@ -899,13 +920,12 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
vduInstance.setOutputs(stackInfo.getOutputs());
// Translate the status elements
- vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
+ vduInstance.setStatus(stackStatusToVduStatus(stackInfo));
return vduInstance;
}
- private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
- {
+ private VduStatus stackStatusToVduStatus(StackInfo stackInfo) {
VduStatus vduStatus = new VduStatus();
// Map the status fields to more generic VduStatus.
@@ -919,30 +939,24 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
logger.debug(String.format("Stack Status Message: %s", statusMessage));
}
- if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
+ if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
vduStatus.setState(VduStateType.INSTANTIATING);
- vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
- }
- else if (heatStatus == HeatStatus.NOTFOUND) {
+ vduStatus.setLastAction((new PluginAction("create", "in_progress", statusMessage)));
+ } else if (heatStatus == HeatStatus.NOTFOUND) {
vduStatus.setState(VduStateType.NOTFOUND);
- }
- else if (heatStatus == HeatStatus.CREATED) {
+ } else if (heatStatus == HeatStatus.CREATED) {
vduStatus.setState(VduStateType.INSTANTIATED);
- vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
- }
- else if (heatStatus == HeatStatus.UPDATED) {
+ vduStatus.setLastAction((new PluginAction("create", "complete", statusMessage)));
+ } else if (heatStatus == HeatStatus.UPDATED) {
vduStatus.setState(VduStateType.INSTANTIATED);
- vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
- }
- else if (heatStatus == HeatStatus.UPDATING) {
+ vduStatus.setLastAction((new PluginAction("update", "complete", statusMessage)));
+ } else if (heatStatus == HeatStatus.UPDATING) {
vduStatus.setState(VduStateType.UPDATING);
- vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
- }
- else if (heatStatus == HeatStatus.DELETING) {
+ vduStatus.setLastAction((new PluginAction("update", "in_progress", statusMessage)));
+ } else if (heatStatus == HeatStatus.DELETING) {
vduStatus.setState(VduStateType.DELETING);
- vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
- }
- else if (heatStatus == HeatStatus.FAILED) {
+ vduStatus.setLastAction((new PluginAction("delete", "in_progress", statusMessage)));
+ } else if (heatStatus == HeatStatus.FAILED) {
vduStatus.setState(VduStateType.FAILED);
vduStatus.setErrorMessage(stackInfo.getStatusMessage());
} else {
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java
index 850f16ff4d..78db27f65e 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java
@@ -27,7 +27,6 @@ import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Optional;
-
import org.onap.so.cloud.CloudConfig;
import org.onap.so.cloud.authentication.AuthenticationMethodFactory;
import org.onap.so.cloud.authentication.KeystoneAuthHolder;
@@ -51,7 +50,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.woorea.openstack.base.client.OpenStackBaseException;
import com.woorea.openstack.base.client.OpenStackConnectException;
import com.woorea.openstack.base.client.OpenStackRequest;
@@ -67,519 +65,495 @@ import com.woorea.openstack.quantum.model.Port;
import com.woorea.openstack.quantum.model.Segment;
@Component
-public class MsoNeutronUtils extends MsoCommonUtils
-{
+public class MsoNeutronUtils extends MsoCommonUtils {
- // Fetch cloud configuration each time (may be cached in CloudConfig class)
- @Autowired
- private CloudConfig cloudConfig;
+ // Fetch cloud configuration each time (may be cached in CloudConfig class)
+ @Autowired
+ private CloudConfig cloudConfig;
- @Autowired
+ @Autowired
private AuthenticationMethodFactory authenticationMethodFactory;
-
- @Autowired
- private MsoTenantUtilsFactory tenantUtilsFactory;
- @Autowired
- private KeystoneV3Authentication keystoneV3Authentication;
+ @Autowired
+ private MsoTenantUtilsFactory tenantUtilsFactory;
+
+ @Autowired
+ private KeystoneV3Authentication keystoneV3Authentication;
private static Logger logger = LoggerFactory.getLogger(MsoNeutronUtils.class);
public enum NetworkType {
- BASIC, PROVIDER, MULTI_PROVIDER
- };
-
- /**
- * Create a network with the specified parameters in the given cloud/tenant.
- *
- * If a network already exists with the same name, an exception will be thrown. Note that
- * this is an MSO-imposed restriction. Openstack does not require uniqueness on network names.
- * <p>
- * @param cloudSiteId The cloud identifier (may be a region) in which to create the network.
- * @param tenantId The tenant in which to create the network
- * @param type The type of network to create (Basic, Provider, Multi-Provider)
- * @param networkName The network name to create
- * @param provider The provider network name (for Provider or Multi-Provider networks)
- * @param vlans A list of VLAN segments for the network (for Provider or Multi-Provider networks)
- * @return a NetworkInfo object which describes the newly created network
- * @throws MsoNetworkAlreadyExists Thrown if a network with the same name already exists
- * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
- * @throws MsoCloudSiteNotFound Thrown if the cloudSite is invalid or unknown
- */
- public NetworkInfo createNetwork (String cloudSiteId, String tenantId, NetworkType type, String networkName, String provider, List<Integer> vlans)
- throws MsoException
- {
- // Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
-
- Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
- // Check if a network already exists with this name
- // Openstack will allow duplicate name, so require explicit check
- Network network = findNetworkByName (neutronClient, networkName);
-
- if (network != null) {
- // Network already exists. Throw an exception
- logger.error("{} Network {} on Cloud site {} for tenant {} already exists {}",
- MessageEnum.RA_NETWORK_ALREADY_EXIST, networkName, cloudSiteId, tenantId,
- ErrorCode.DataError.getValue());
- throw new MsoNetworkAlreadyExists (networkName, tenantId, cloudSiteId);
- }
-
- // Does not exist, create a new one
- network = new Network();
- network.setName(networkName);
- network.setAdminStateUp(true);
-
- if (type == NetworkType.PROVIDER) {
- if (provider != null && vlans != null && vlans.size() > 0) {
- network.setProviderPhysicalNetwork (provider);
- network.setProviderNetworkType("vlan");
- network.setProviderSegmentationId (vlans.get(0));
- }
- } else if (type == NetworkType.MULTI_PROVIDER) {
- if (provider != null && vlans != null && vlans.size() > 0) {
- List<Segment> segments = new ArrayList<>(vlans.size());
- for (int vlan : vlans) {
- Segment segment = new Segment();
- segment.setProviderPhysicalNetwork (provider);
- segment.setProviderNetworkType("vlan");
- segment.setProviderSegmentationId (vlan);
-
- segments.add(segment);
- }
- network.setSegments(segments);
- }
- }
-
- try {
- OpenStackRequest<Network> request = neutronClient.networks().create(network);
- Network newNetwork = executeAndRecordOpenstackRequest(request);
- return new NetworkInfoMapper(newNetwork).map();
- }
- catch (OpenStackBaseException e) {
- // Convert Neutron exception to an MsoOpenstackException
- MsoException me = neutronExceptionToMsoException (e, "CreateNetwork");
- throw me;
- }
- catch (RuntimeException e) {
- // Catch-all
- MsoException me = runtimeExceptionToMsoException(e, "CreateNetwork");
- throw me;
- }
- }
-
-
- /**
- * Query for a network with the specified name or ID in the given cloud. If the network exists,
- * return an NetworkInfo object. If not, return null.
- * <p>
- * Whenever possible, the network ID should be used as it is much more efficient. Query by
- * name requires retrieval of all networks for the tenant and search for matching name.
- * <p>
- * @param networkNameOrId The network to query
- * @param tenantId The Openstack tenant to look in for the network
- * @param cloudSiteId The cloud identifier (may be a region) in which to query the network.
- * @return a NetworkInfo object describing the queried network, or null if not found
- * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
- * @throws MsoCloudSiteNotFound
- */
- public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException
- {
- logger.debug("In queryNetwork");
-
- // Obtain the cloud site information
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
-
- Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
- // Check if the network exists and return its info
- try {
- Network network = findNetworkByNameOrId (neutronClient, networkNameOrId);
- if (network == null) {
- logger.debug("Query Network: {} not found in tenant {}", networkNameOrId, tenantId);
- return null;
- }
- return new NetworkInfoMapper(network).map();
- }
- catch (OpenStackBaseException e) {
- // Convert Neutron exception to an MsoOpenstackException
- MsoException me = neutronExceptionToMsoException (e, "QueryNetwork");
- throw me;
- }
- catch (RuntimeException e) {
- // Catch-all
- MsoException me = runtimeExceptionToMsoException(e, "QueryNetwork");
- throw me;
- }
- }
-
- public Optional<Port> getNeutronPort(String neutronPortId, String tenantId, String cloudSiteId)
- {
- try {
- logger.debug("Finding Neutron port:" + neutronPortId);
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
- Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
- Port port = findPortById (neutronClient, neutronPortId);
- if (port == null) {
- return Optional.empty();
- }
- return Optional.of(port);
- }
- catch (RuntimeException | MsoException e) {
- logger.error("Error retrieving neutron port", e);
- return Optional.empty();
- }
- }
-
- /**
- * Delete the specified Network (by ID) in the given cloud.
- * If the network does not exist, success is returned.
- * <p>
- * @param networkId Openstack ID of the network to delete
- * @param tenantId The Openstack tenant.
- * @param cloudSiteId The cloud identifier (may be a region) from which to delete the network.
- * @return true if the network was deleted, false if the network did not exist
- * @throws MsoOpenstackException If the Openstack API call returns an exception, this local
- * exception will be thrown.
- * @throws MsoCloudSiteNotFound
- */
- public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException
- {
- // Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
- Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
- try {
- // Check that the network exists.
- Network network = findNetworkById (neutronClient, networkId);
- if (network == null) {
- logger.info("{} Network not found! Network id: {} Cloud site: {} Tenant: {} ",
- MessageEnum.RA_DELETE_NETWORK_EXC, networkId, cloudSiteId, tenantId);
- return false;
- }
-
- OpenStackRequest<Void> request = neutronClient.networks().delete(network.getId());
- executeAndRecordOpenstackRequest(request);
-
- logger.debug("Deleted Network {} ({})", network.getId(), network.getName());
+ BASIC, PROVIDER, MULTI_PROVIDER
+ };
+
+ /**
+ * Create a network with the specified parameters in the given cloud/tenant.
+ *
+ * If a network already exists with the same name, an exception will be thrown. Note that this is an MSO-imposed
+ * restriction. Openstack does not require uniqueness on network names.
+ * <p>
+ *
+ * @param cloudSiteId The cloud identifier (may be a region) in which to create the network.
+ * @param tenantId The tenant in which to create the network
+ * @param type The type of network to create (Basic, Provider, Multi-Provider)
+ * @param networkName The network name to create
+ * @param provider The provider network name (for Provider or Multi-Provider networks)
+ * @param vlans A list of VLAN segments for the network (for Provider or Multi-Provider networks)
+ * @return a NetworkInfo object which describes the newly created network
+ * @throws MsoNetworkAlreadyExists Thrown if a network with the same name already exists
+ * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
+ * @throws MsoCloudSiteNotFound Thrown if the cloudSite is invalid or unknown
+ */
+ public NetworkInfo createNetwork(String cloudSiteId, String tenantId, NetworkType type, String networkName,
+ String provider, List<Integer> vlans) throws MsoException {
+ // Obtain the cloud site information where we will create the stack
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+
+ Quantum neutronClient = getNeutronClient(cloudSite, tenantId);
+
+ // Check if a network already exists with this name
+ // Openstack will allow duplicate name, so require explicit check
+ Network network = findNetworkByName(neutronClient, networkName);
+
+ if (network != null) {
+ // Network already exists. Throw an exception
+ logger.error("{} Network {} on Cloud site {} for tenant {} already exists {}",
+ MessageEnum.RA_NETWORK_ALREADY_EXIST, networkName, cloudSiteId, tenantId,
+ ErrorCode.DataError.getValue());
+ throw new MsoNetworkAlreadyExists(networkName, tenantId, cloudSiteId);
+ }
+
+ // Does not exist, create a new one
+ network = new Network();
+ network.setName(networkName);
+ network.setAdminStateUp(true);
+
+ if (type == NetworkType.PROVIDER) {
+ if (provider != null && vlans != null && vlans.size() > 0) {
+ network.setProviderPhysicalNetwork(provider);
+ network.setProviderNetworkType("vlan");
+ network.setProviderSegmentationId(vlans.get(0));
+ }
+ } else if (type == NetworkType.MULTI_PROVIDER) {
+ if (provider != null && vlans != null && vlans.size() > 0) {
+ List<Segment> segments = new ArrayList<>(vlans.size());
+ for (int vlan : vlans) {
+ Segment segment = new Segment();
+ segment.setProviderPhysicalNetwork(provider);
+ segment.setProviderNetworkType("vlan");
+ segment.setProviderSegmentationId(vlan);
+
+ segments.add(segment);
+ }
+ network.setSegments(segments);
+ }
+ }
+
+ try {
+ OpenStackRequest<Network> request = neutronClient.networks().create(network);
+ Network newNetwork = executeAndRecordOpenstackRequest(request);
+ return new NetworkInfoMapper(newNetwork).map();
+ } catch (OpenStackBaseException e) {
+ // Convert Neutron exception to an MsoOpenstackException
+ MsoException me = neutronExceptionToMsoException(e, "CreateNetwork");
+ throw me;
+ } catch (RuntimeException e) {
+ // Catch-all
+ MsoException me = runtimeExceptionToMsoException(e, "CreateNetwork");
+ throw me;
+ }
+ }
+
+
+ /**
+ * Query for a network with the specified name or ID in the given cloud. If the network exists, return an
+ * NetworkInfo object. If not, return null.
+ * <p>
+ * Whenever possible, the network ID should be used as it is much more efficient. Query by name requires retrieval
+ * of all networks for the tenant and search for matching name.
+ * <p>
+ *
+ * @param networkNameOrId The network to query
+ * @param tenantId The Openstack tenant to look in for the network
+ * @param cloudSiteId The cloud identifier (may be a region) in which to query the network.
+ * @return a NetworkInfo object describing the queried network, or null if not found
+ * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
+ * @throws MsoCloudSiteNotFound
+ */
+ public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException {
+ logger.debug("In queryNetwork");
+
+ // Obtain the cloud site information
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+
+ Quantum neutronClient = getNeutronClient(cloudSite, tenantId);
+
+ // Check if the network exists and return its info
+ try {
+ Network network = findNetworkByNameOrId(neutronClient, networkNameOrId);
+ if (network == null) {
+ logger.debug("Query Network: {} not found in tenant {}", networkNameOrId, tenantId);
+ return null;
+ }
+ return new NetworkInfoMapper(network).map();
+ } catch (OpenStackBaseException e) {
+ // Convert Neutron exception to an MsoOpenstackException
+ MsoException me = neutronExceptionToMsoException(e, "QueryNetwork");
+ throw me;
+ } catch (RuntimeException e) {
+ // Catch-all
+ MsoException me = runtimeExceptionToMsoException(e, "QueryNetwork");
+ throw me;
+ }
}
- catch (OpenStackBaseException e) {
- // Convert Neutron exception to an MsoOpenstackException
- MsoException me = neutronExceptionToMsoException (e, "Delete Network");
- throw me;
- }
- catch (RuntimeException e) {
- // Catch-all
- MsoException me = runtimeExceptionToMsoException(e, "DeleteNetwork");
- throw me;
- }
-
- return true;
- }
-
-
- /**
- * Update a network with the specified parameters in the given cloud/tenant.
- *
- * Specifically, this call is intended to update the VLAN segments on a
- * multi-provider network. The provider segments will be replaced with the
- * supplied list of VLANs.
- * <p>
- * Note that updating the 'segments' array is not normally supported by Neutron.
- * This method relies on a Platform Orchestration extension (using SDN controller
- * to manage the virtual networking).
- *
- * @param cloudSiteId The cloud site ID (may be a region) in which to update the network.
- * @param tenantId Openstack ID of the tenant in which to update the network
- * @param networkId The unique Openstack ID of the network to be updated
- * @param type The network type (Basic, Provider, Multi-Provider)
- * @param provider The provider network name. This should not change.
- * @param vlans The list of VLAN segments to replace
- * @return a NetworkInfo object which describes the updated network
- * @throws MsoNetworkNotFound Thrown if the requested network does not exist
- * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
- * @throws MsoCloudSiteNotFound
- */
- public NetworkInfo updateNetwork (String cloudSiteId, String tenantId, String networkId, NetworkType type, String provider, List<Integer> vlans)
- throws MsoException
- {
- // Obtain the cloud site information where we will create the stack
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
- Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
- // Check that the network exists
- Network network = findNetworkById (neutronClient, networkId);
-
- if (network == null) {
- // Network not found. Throw an exception
- logger.error("{} Network {} on Cloud site {} for Tenant {} not found {}", MessageEnum.RA_NETWORK_NOT_FOUND,
- networkId, cloudSiteId, tenantId, ErrorCode.DataError.getValue());
- throw new MsoNetworkNotFound (networkId, tenantId, cloudSiteId);
- }
-
- // Overwrite the properties to be updated
- if (type == NetworkType.PROVIDER) {
- if (provider != null && vlans != null && vlans.size() > 0) {
- network.setProviderPhysicalNetwork (provider);
- network.setProviderNetworkType("vlan");
- network.setProviderSegmentationId (vlans.get(0));
- }
- } else if (type == NetworkType.MULTI_PROVIDER) {
- if (provider != null && vlans != null && vlans.size() > 0) {
- List<Segment> segments = new ArrayList<>(vlans.size());
- for (int vlan : vlans) {
- Segment segment = new Segment();
- segment.setProviderPhysicalNetwork (provider);
- segment.setProviderNetworkType("vlan");
- segment.setProviderSegmentationId (vlan);
-
- segments.add(segment);
- }
- network.setSegments(segments);
- }
- }
-
- try {
- OpenStackRequest<Network> request = neutronClient.networks().update(network);
- Network newNetwork = executeAndRecordOpenstackRequest(request);
- return new NetworkInfoMapper(newNetwork).map();
- }
- catch (OpenStackBaseException e) {
- // Convert Neutron exception to an MsoOpenstackException
- MsoException me = neutronExceptionToMsoException (e, "UpdateNetwork");
- throw me;
- }
- catch (RuntimeException e) {
- // Catch-all
- MsoException me = runtimeExceptionToMsoException(e, "UpdateNetwork");
- throw me;
- }
- }
-
-
- // -------------------------------------------------------------------
- // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
-
- /**
- * Get a Neutron (Quantum) client for the Openstack Network service.
- * This requires a 'member'-level userId + password, which will be retrieved from
- * properties based on the specified cloud Id. The tenant in which to operate
- * must also be provided.
- * <p>
- * On successful authentication, the Quantum object will be cached for the
- * tenantID + cloudId so that it can be reused without reauthenticating with
- * Openstack every time.
- *
- * @param cloudSite - a cloud site definition
- * @param tenantId - Openstack tenant ID
- * @return an authenticated Quantum object
- */
- private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException
- {
- String cloudId = cloudSite.getId();
- String region = cloudSite.getRegionId();
-
-
- // Obtain an MSO token for the tenant from the identity service
- CloudIdentity cloudIdentity = cloudSite.getIdentityService();
- MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
+
+ public Optional<Port> getNeutronPort(String neutronPortId, String tenantId, String cloudSiteId) {
+ try {
+ logger.debug("Finding Neutron port:" + neutronPortId);
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Quantum neutronClient = getNeutronClient(cloudSite, tenantId);
+ Port port = findPortById(neutronClient, neutronPortId);
+ if (port == null) {
+ return Optional.empty();
+ }
+ return Optional.of(port);
+ } catch (RuntimeException | MsoException e) {
+ logger.error("Error retrieving neutron port", e);
+ return Optional.empty();
+ }
+ }
+
+ /**
+ * Delete the specified Network (by ID) in the given cloud. If the network does not exist, success is returned.
+ * <p>
+ *
+ * @param networkId Openstack ID of the network to delete
+ * @param tenantId The Openstack tenant.
+ * @param cloudSiteId The cloud identifier (may be a region) from which to delete the network.
+ * @return true if the network was deleted, false if the network did not exist
+ * @throws MsoOpenstackException If the Openstack API call returns an exception, this local exception will be
+ * thrown.
+ * @throws MsoCloudSiteNotFound
+ */
+ public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException {
+ // Obtain the cloud site information where we will create the stack
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Quantum neutronClient = getNeutronClient(cloudSite, tenantId);
+
+ try {
+ // Check that the network exists.
+ Network network = findNetworkById(neutronClient, networkId);
+ if (network == null) {
+ logger.info("{} Network not found! Network id: {} Cloud site: {} Tenant: {} ",
+ MessageEnum.RA_DELETE_NETWORK_EXC, networkId, cloudSiteId, tenantId);
+ return false;
+ }
+
+ OpenStackRequest<Void> request = neutronClient.networks().delete(network.getId());
+ executeAndRecordOpenstackRequest(request);
+
+ logger.debug("Deleted Network {} ({})", network.getId(), network.getName());
+ } catch (OpenStackBaseException e) {
+ // Convert Neutron exception to an MsoOpenstackException
+ MsoException me = neutronExceptionToMsoException(e, "Delete Network");
+ throw me;
+ } catch (RuntimeException e) {
+ // Catch-all
+ MsoException me = runtimeExceptionToMsoException(e, "DeleteNetwork");
+ throw me;
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Update a network with the specified parameters in the given cloud/tenant.
+ *
+ * Specifically, this call is intended to update the VLAN segments on a multi-provider network. The provider
+ * segments will be replaced with the supplied list of VLANs.
+ * <p>
+ * Note that updating the 'segments' array is not normally supported by Neutron. This method relies on a Platform
+ * Orchestration extension (using SDN controller to manage the virtual networking).
+ *
+ * @param cloudSiteId The cloud site ID (may be a region) in which to update the network.
+ * @param tenantId Openstack ID of the tenant in which to update the network
+ * @param networkId The unique Openstack ID of the network to be updated
+ * @param type The network type (Basic, Provider, Multi-Provider)
+ * @param provider The provider network name. This should not change.
+ * @param vlans The list of VLAN segments to replace
+ * @return a NetworkInfo object which describes the updated network
+ * @throws MsoNetworkNotFound Thrown if the requested network does not exist
+ * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
+ * @throws MsoCloudSiteNotFound
+ */
+ public NetworkInfo updateNetwork(String cloudSiteId, String tenantId, String networkId, NetworkType type,
+ String provider, List<Integer> vlans) throws MsoException {
+ // Obtain the cloud site information where we will create the stack
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+ Quantum neutronClient = getNeutronClient(cloudSite, tenantId);
+
+ // Check that the network exists
+ Network network = findNetworkById(neutronClient, networkId);
+
+ if (network == null) {
+ // Network not found. Throw an exception
+ logger.error("{} Network {} on Cloud site {} for Tenant {} not found {}", MessageEnum.RA_NETWORK_NOT_FOUND,
+ networkId, cloudSiteId, tenantId, ErrorCode.DataError.getValue());
+ throw new MsoNetworkNotFound(networkId, tenantId, cloudSiteId);
+ }
+
+ // Overwrite the properties to be updated
+ if (type == NetworkType.PROVIDER) {
+ if (provider != null && vlans != null && vlans.size() > 0) {
+ network.setProviderPhysicalNetwork(provider);
+ network.setProviderNetworkType("vlan");
+ network.setProviderSegmentationId(vlans.get(0));
+ }
+ } else if (type == NetworkType.MULTI_PROVIDER) {
+ if (provider != null && vlans != null && vlans.size() > 0) {
+ List<Segment> segments = new ArrayList<>(vlans.size());
+ for (int vlan : vlans) {
+ Segment segment = new Segment();
+ segment.setProviderPhysicalNetwork(provider);
+ segment.setProviderNetworkType("vlan");
+ segment.setProviderSegmentationId(vlan);
+
+ segments.add(segment);
+ }
+ network.setSegments(segments);
+ }
+ }
+
+ try {
+ OpenStackRequest<Network> request = neutronClient.networks().update(network);
+ Network newNetwork = executeAndRecordOpenstackRequest(request);
+ return new NetworkInfoMapper(newNetwork).map();
+ } catch (OpenStackBaseException e) {
+ // Convert Neutron exception to an MsoOpenstackException
+ MsoException me = neutronExceptionToMsoException(e, "UpdateNetwork");
+ throw me;
+ } catch (RuntimeException e) {
+ // Catch-all
+ MsoException me = runtimeExceptionToMsoException(e, "UpdateNetwork");
+ throw me;
+ }
+ }
+
+
+ // -------------------------------------------------------------------
+ // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
+
+ /**
+ * Get a Neutron (Quantum) client for the Openstack Network service. This requires a 'member'-level userId +
+ * password, which will be retrieved from properties based on the specified cloud Id. The tenant in which to operate
+ * must also be provided.
+ * <p>
+ * On successful authentication, the Quantum object will be cached for the tenantID + cloudId so that it can be
+ * reused without reauthenticating with Openstack every time.
+ *
+ * @param cloudSite - a cloud site definition
+ * @param tenantId - Openstack tenant ID
+ * @return an authenticated Quantum object
+ */
+ private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException {
+ String cloudId = cloudSite.getId();
+ String region = cloudSite.getRegionId();
+
+
+ // Obtain an MSO token for the tenant from the identity service
+ CloudIdentity cloudIdentity = cloudSite.getIdentityService();
+ MsoTenantUtils tenantUtils =
+ tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
final String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
- String neutronUrl = null;
- String tokenId = null;
- Calendar expiration = null;
- try {
- if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
- Keystone keystoneTenantClient = new Keystone(keystoneUrl);
- Access access = null;
-
- Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
- OpenStackRequest<Access> request = keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId);
- access = executeAndRecordOpenstackRequest(request);
-
-
- try {
- neutronUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "network", region, "public");
- if (! neutronUrl.endsWith("/")) {
- neutronUrl += "/v2.0/";
- }
- } catch (RuntimeException e) {
- // This comes back for not found (probably an incorrect region ID)
- String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
- throw new MsoAdapterException (error, e);
- }
- tokenId = access.getToken().getId();
- expiration = access.getToken().getExpires();
- } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
- try {
- KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "network");
- tokenId = holder.getId();
- expiration = holder.getexpiration();
- neutronUrl = holder.getServiceUrl();
- if (! neutronUrl.endsWith("/")) {
- neutronUrl += "/v2.0/";
- }
- } catch (ServiceEndpointNotFoundException e) {
- // This comes back for not found (probably an incorrect region ID)
- String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
- throw new MsoAdapterException (error, e);
- }
- }
- }
- catch (OpenStackResponseException e) {
- if (e.getStatus() == 401) {
- // Authentication error.
- String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId();
-
- throw new MsoAdapterException(error);
- }
- else {
- MsoException me = keystoneErrorToMsoException(e, "TokenAuth");
- throw me;
- }
- }
- catch (OpenStackConnectException e) {
- // Connection to Openstack failed
- MsoIOException me = new MsoIOException (e.getMessage(), e);
- me.addContext("TokenAuth");
- throw me;
- }
- catch (RuntimeException e) {
- // Catch-all
- MsoException me = runtimeExceptionToMsoException(e, "TokenAuth");
- throw me;
- }
-
- Quantum neutronClient = new Quantum(neutronUrl);
- neutronClient.token(tokenId);
- return neutronClient;
- }
-
- /*
- * Find a tenant (or query its existence) by its Name or Id. Check first against the
- * ID. If that fails, then try by name.
- *
- * @param adminClient an authenticated Keystone object
- * @param tenantName the tenant name or ID to query
- * @return a Tenant object or null if not found
- */
- public Network findNetworkByNameOrId (Quantum neutronClient, String networkNameOrId)
- {
- if (networkNameOrId == null) {
+ String neutronUrl = null;
+ String tokenId = null;
+ Calendar expiration = null;
+ try {
+ if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) {
+ Keystone keystoneTenantClient = new Keystone(keystoneUrl);
+ Access access = null;
+
+ Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
+ OpenStackRequest<Access> request =
+ keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId);
+ access = executeAndRecordOpenstackRequest(request);
+
+
+ try {
+ neutronUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "network", region, "public");
+ if (!neutronUrl.endsWith("/")) {
+ neutronUrl += "/v2.0/";
+ }
+ } catch (RuntimeException e) {
+ // This comes back for not found (probably an incorrect region ID)
+ String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
+ throw new MsoAdapterException(error, e);
+ }
+ tokenId = access.getToken().getId();
+ expiration = access.getToken().getExpires();
+ } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
+ try {
+ KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "network");
+ tokenId = holder.getId();
+ expiration = holder.getexpiration();
+ neutronUrl = holder.getServiceUrl();
+ if (!neutronUrl.endsWith("/")) {
+ neutronUrl += "/v2.0/";
+ }
+ } catch (ServiceEndpointNotFoundException e) {
+ // This comes back for not found (probably an incorrect region ID)
+ String error = "Network service not found: region=" + region + ",cloud=" + cloudIdentity.getId();
+ throw new MsoAdapterException(error, e);
+ }
+ }
+ } catch (OpenStackResponseException e) {
+ if (e.getStatus() == 401) {
+ // Authentication error.
+ String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId();
+
+ throw new MsoAdapterException(error);
+ } else {
+ MsoException me = keystoneErrorToMsoException(e, "TokenAuth");
+ throw me;
+ }
+ } catch (OpenStackConnectException e) {
+ // Connection to Openstack failed
+ MsoIOException me = new MsoIOException(e.getMessage(), e);
+ me.addContext("TokenAuth");
+ throw me;
+ } catch (RuntimeException e) {
+ // Catch-all
+ MsoException me = runtimeExceptionToMsoException(e, "TokenAuth");
+ throw me;
+ }
+
+ Quantum neutronClient = new Quantum(neutronUrl);
+ neutronClient.token(tokenId);
+ return neutronClient;
+ }
+
+ /*
+ * Find a tenant (or query its existence) by its Name or Id. Check first against the ID. If that fails, then try by
+ * name.
+ *
+ * @param adminClient an authenticated Keystone object
+ *
+ * @param tenantName the tenant name or ID to query
+ *
+ * @return a Tenant object or null if not found
+ */
+ public Network findNetworkByNameOrId(Quantum neutronClient, String networkNameOrId) {
+ if (networkNameOrId == null) {
return null;
}
- Network network = findNetworkById(neutronClient, networkNameOrId);
+ Network network = findNetworkById(neutronClient, networkNameOrId);
- if (network == null) {
+ if (network == null) {
network = findNetworkByName(neutronClient, networkNameOrId);
}
- return network;
- }
-
- /*
- * Find a network (or query its existence) by its Id.
- *
- * @param neutronClient an authenticated Quantum object
- * @param networkId the network ID to query
- * @return a Network object or null if not found
- */
- private Network findNetworkById (Quantum neutronClient, String networkId)
- {
- if (networkId == null) {
+ return network;
+ }
+
+ /*
+ * Find a network (or query its existence) by its Id.
+ *
+ * @param neutronClient an authenticated Quantum object
+ *
+ * @param networkId the network ID to query
+ *
+ * @return a Network object or null if not found
+ */
+ private Network findNetworkById(Quantum neutronClient, String networkId) {
+ if (networkId == null) {
return null;
}
- try {
- OpenStackRequest<Network> request = neutronClient.networks().show(networkId);
- Network network = executeAndRecordOpenstackRequest(request);
- return network;
- }
- catch (OpenStackResponseException e) {
- if (e.getStatus() == 404) {
- return null;
- } else {
- logger.error("{} {} Openstack Error, GET Network By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), networkId, e);
- throw e;
- }
- }
- }
-
-
- private Port findPortById (Quantum neutronClient, String neutronPortId)
- {
- if (neutronPortId == null) {
+ try {
+ OpenStackRequest<Network> request = neutronClient.networks().show(networkId);
+ Network network = executeAndRecordOpenstackRequest(request);
+ return network;
+ } catch (OpenStackResponseException e) {
+ if (e.getStatus() == 404) {
+ return null;
+ } else {
+ logger.error("{} {} Openstack Error, GET Network By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
+ ErrorCode.DataError.getValue(), networkId, e);
+ throw e;
+ }
+ }
+ }
+
+
+ private Port findPortById(Quantum neutronClient, String neutronPortId) {
+ if (neutronPortId == null) {
return null;
}
- try {
- OpenStackRequest<Port> request = neutronClient.ports().show(neutronPortId);
- Port port = executeAndRecordOpenstackRequest(request);
- return port;
- }
- catch (OpenStackResponseException e) {
- if (e.getStatus() == 404) {
- logger.warn("Neutron port not found: " + neutronPortId,"Neutron port not found: " + neutronPortId);
- return null;
- } else {
- logger.error("{} {} Openstack Error, GET Neutron Port By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), neutronPortId, e);
- throw e;
- }
- }
- }
-
- /*
- * Find a network (or query its existence) by its Name. This method avoids an
- * initial lookup by ID when it's known that we have the network Name.
- *
- * Neutron does not support 'name=*' query parameter for Network query (show).
- * The only way to query by name is to retrieve all networks and look for the
- * match. While inefficient, this capability will be provided as it is needed
- * by MSO, but should be avoided in favor of ID whenever possible.
- *
- * TODO:
- * Network names are not required to be unique, though MSO will attempt to enforce
- * uniqueness. This call probably needs to return an error (instead of returning
- * the first match).
- *
- * @param neutronClient an authenticated Quantum object
- * @param networkName the network name to query
- * @return a Network object or null if not found
- */
- public Network findNetworkByName (Quantum neutronClient, String networkName)
- {
- if (networkName == null) {
+ try {
+ OpenStackRequest<Port> request = neutronClient.ports().show(neutronPortId);
+ Port port = executeAndRecordOpenstackRequest(request);
+ return port;
+ } catch (OpenStackResponseException e) {
+ if (e.getStatus() == 404) {
+ logger.warn("Neutron port not found: " + neutronPortId, "Neutron port not found: " + neutronPortId);
+ return null;
+ } else {
+ logger.error("{} {} Openstack Error, GET Neutron Port By ID ({}): ",
+ MessageEnum.RA_CONNECTION_EXCEPTION, ErrorCode.DataError.getValue(), neutronPortId, e);
+ throw e;
+ }
+ }
+ }
+
+ /*
+ * Find a network (or query its existence) by its Name. This method avoids an initial lookup by ID when it's known
+ * that we have the network Name.
+ *
+ * Neutron does not support 'name=*' query parameter for Network query (show). The only way to query by name is to
+ * retrieve all networks and look for the match. While inefficient, this capability will be provided as it is needed
+ * by MSO, but should be avoided in favor of ID whenever possible.
+ *
+ * TODO: Network names are not required to be unique, though MSO will attempt to enforce uniqueness. This call
+ * probably needs to return an error (instead of returning the first match).
+ *
+ * @param neutronClient an authenticated Quantum object
+ *
+ * @param networkName the network name to query
+ *
+ * @return a Network object or null if not found
+ */
+ public Network findNetworkByName(Quantum neutronClient, String networkName) {
+ if (networkName == null) {
return null;
}
- try {
- OpenStackRequest<Networks> request = neutronClient.networks().list();
- Networks networks = executeAndRecordOpenstackRequest(request);
- for (Network network : networks.getList()) {
- if (network.getName().equals(networkName)) {
- logger.debug("Found match on network name: {}", networkName);
- return network;
- }
- }
- logger.debug("findNetworkByName - no match found for {}", networkName);
- return null;
- }
- catch (OpenStackResponseException e) {
- if (e.getStatus() == 404) {
- return null;
- } else {
- logger.error("{} {} Openstack Error, GET Network By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
- ErrorCode.DataError.getValue(), networkName, e);
- throw e;
- }
- }
- }
+ try {
+ OpenStackRequest<Networks> request = neutronClient.networks().list();
+ Networks networks = executeAndRecordOpenstackRequest(request);
+ for (Network network : networks.getList()) {
+ if (network.getName().equals(networkName)) {
+ logger.debug("Found match on network name: {}", networkName);
+ return network;
+ }
+ }
+ logger.debug("findNetworkByName - no match found for {}", networkName);
+ return null;
+ } catch (OpenStackResponseException e) {
+ if (e.getStatus() == 404) {
+ return null;
+ } else {
+ logger.error("{} {} Openstack Error, GET Network By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION,
+ ErrorCode.DataError.getValue(), networkName, e);
+ throw e;
+ }
+ }
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java
index 7cf41dbac9..e10c108165 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java
@@ -38,19 +38,17 @@ public abstract class MsoTenantUtils extends MsoCommonUtils {
@Autowired
protected CloudConfig cloudConfig;
- public abstract String createTenant (String tenantName, String cloudSiteId, Map <String, String> metadata, boolean backout)
- throws MsoException;
-
- public abstract MsoTenant queryTenant (String tenantId, String cloudSiteId)
- throws MsoException, MsoCloudSiteNotFound;
-
- public abstract MsoTenant queryTenantByName (String tenantName, String cloudSiteId)
- throws MsoException, MsoCloudSiteNotFound;
-
- public abstract boolean deleteTenant (String tenantId, String cloudSiteId)
- throws MsoException;
-
- public abstract String getKeystoneUrl (String regionId, CloudIdentity cloudIdentity)
- throws MsoException;
+ public abstract String createTenant(String tenantName, String cloudSiteId, Map<String, String> metadata,
+ boolean backout) throws MsoException;
+
+ public abstract MsoTenant queryTenant(String tenantId, String cloudSiteId)
+ throws MsoException, MsoCloudSiteNotFound;
+
+ public abstract MsoTenant queryTenantByName(String tenantName, String cloudSiteId)
+ throws MsoException, MsoCloudSiteNotFound;
+
+ public abstract boolean deleteTenant(String tenantId, String cloudSiteId) throws MsoException;
+
+ public abstract String getKeystoneUrl(String regionId, CloudIdentity cloudIdentity) throws MsoException;
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java
index c5b93d9fbe..514cb2eb7b 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java
@@ -36,28 +36,28 @@ public class MsoTenantUtilsFactory {
protected static Logger logger = LoggerFactory.getLogger(MsoTenantUtilsFactory.class);
@Autowired
- protected CloudConfig cloudConfig;
- @Autowired
- protected MsoKeystoneUtils keystoneUtils;
- @Autowired
- protected MsoKeystoneV3Utils keystoneV3Utils;
-
- // based on Cloud IdentityServerType returns ORM or KEYSTONE Utils
- public MsoTenantUtils getTenantUtils(String cloudSiteId) throws MsoCloudSiteNotFound {
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
-
- return getTenantUtilsByServerType(cloudSite.getIdentityService().getIdentityServerType());
- }
-
- public MsoTenantUtils getTenantUtilsByServerType(ServerType serverType) {
-
- MsoTenantUtils tenantU = null;
- if (ServerType.KEYSTONE.equals(serverType)) {
- tenantU = keystoneUtils;
- } else if (ServerType.KEYSTONE_V3.equals(serverType)) {
- tenantU = keystoneV3Utils;
- }
- return tenantU;
- }
+ protected CloudConfig cloudConfig;
+ @Autowired
+ protected MsoKeystoneUtils keystoneUtils;
+ @Autowired
+ protected MsoKeystoneV3Utils keystoneV3Utils;
+
+ // based on Cloud IdentityServerType returns ORM or KEYSTONE Utils
+ public MsoTenantUtils getTenantUtils(String cloudSiteId) throws MsoCloudSiteNotFound {
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
+
+ return getTenantUtilsByServerType(cloudSite.getIdentityService().getIdentityServerType());
+ }
+
+ public MsoTenantUtils getTenantUtilsByServerType(ServerType serverType) {
+
+ MsoTenantUtils tenantU = null;
+ if (ServerType.KEYSTONE.equals(serverType)) {
+ tenantU = keystoneUtils;
+ } else if (ServerType.KEYSTONE_V3.equals(serverType)) {
+ tenantU = keystoneV3Utils;
+ }
+ return tenantU;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java
index 5f26449f0f..0541a8f51b 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java
@@ -40,39 +40,40 @@ import org.yaml.snakeyaml.Yaml;
public class MsoYamlEditorWithEnvt {
private static final Logger logger = LoggerFactory.getLogger(MsoYamlEditorWithEnvt.class);
-
- private Map <String, Object> yml;
- private Yaml yaml = new Yaml ();
+
+ private Map<String, Object> yml;
+ private Yaml yaml = new Yaml();
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
- public MsoYamlEditorWithEnvt() {
- super();
- }
- public MsoYamlEditorWithEnvt(byte[] b) {
- init(b);
- }
+ public MsoYamlEditorWithEnvt() {
+ super();
+ }
+
+ public MsoYamlEditorWithEnvt(byte[] b) {
+ init(b);
+ }
@SuppressWarnings("unchecked")
- private synchronized void init (byte[] body) {
- InputStream input = new ByteArrayInputStream (body);
- yml = (Map <String, Object>) yaml.load (input);
- }
+ private synchronized void init(byte[] body) {
+ InputStream input = new ByteArrayInputStream(body);
+ yml = (Map<String, Object>) yaml.load(input);
+ }
@SuppressWarnings("unchecked")
- public synchronized Set <MsoHeatEnvironmentParameter> getParameterListFromEnvt() {
- // In an environment entry, the parameters section can only contain the name:value -
- // not other attributes.
- Set <MsoHeatEnvironmentParameter> paramSet = new HashSet<>();
- Map<String, Object> resourceMap = null;
- try {
- resourceMap = (Map<String,Object>) yml.get("parameters");
- } catch (Exception e) {
- logger.debug("Exception:", e);
- return paramSet;
- }
- if (resourceMap == null) {
- return paramSet;
- }
+ public synchronized Set<MsoHeatEnvironmentParameter> getParameterListFromEnvt() {
+ // In an environment entry, the parameters section can only contain the name:value -
+ // not other attributes.
+ Set<MsoHeatEnvironmentParameter> paramSet = new HashSet<>();
+ Map<String, Object> resourceMap = null;
+ try {
+ resourceMap = (Map<String, Object>) yml.get("parameters");
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ return paramSet;
+ }
+ if (resourceMap == null) {
+ return paramSet;
+ }
for (Entry<String, Object> stringObjectEntry : resourceMap.entrySet()) {
MsoHeatEnvironmentParameter hep = new MsoHeatEnvironmentParameter();
@@ -84,7 +85,7 @@ public class MsoYamlEditorWithEnvt {
// but this adds an extra '\n' at the end - which won't hurt - but we don't need it
value = value.substring(0, value.length() - 1);
} else if (obj instanceof LinkedHashMap) {
- //Handle that it's json
+ // Handle that it's json
try {
value = JSON_MAPPER.writeValueAsString(obj);
} catch (Exception e) {
@@ -92,20 +93,21 @@ public class MsoYamlEditorWithEnvt {
value = "_BAD_JSON_MAPPING";
}
} else {
- //this handles integers/longs/floats/etc.
+ // this handles integers/longs/floats/etc.
value = String.valueOf(obj);
}
hep.setName((String) pair.getKey());
hep.setValue(value);
paramSet.add(hep);
}
- return paramSet;
+ return paramSet;
}
- public synchronized Set <MsoHeatEnvironmentResource> getResourceListFromEnvt() {
- try {
- Set<MsoHeatEnvironmentResource> resourceList = new HashSet<>();
- @SuppressWarnings("unchecked")
- Map<String, Object> resourceMap = (Map<String,Object>) yml.get("resource_registry");
+
+ public synchronized Set<MsoHeatEnvironmentResource> getResourceListFromEnvt() {
+ try {
+ Set<MsoHeatEnvironmentResource> resourceList = new HashSet<>();
+ @SuppressWarnings("unchecked")
+ Map<String, Object> resourceMap = (Map<String, Object>) yml.get("resource_registry");
for (Entry<String, Object> stringObjectEntry : resourceMap.entrySet()) {
MsoHeatEnvironmentResource her = new MsoHeatEnvironmentResource();
@@ -114,16 +116,17 @@ public class MsoYamlEditorWithEnvt {
her.setValue((String) pair.getValue());
resourceList.add(her);
}
- return resourceList;
- } catch (Exception e) {
- logger.debug("Exception:", e);
- }
- return null;
+ return resourceList;
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ }
+ return null;
}
- public synchronized Set <HeatTemplateParam> getParameterList () {
- Set <HeatTemplateParam> paramSet = new HashSet <> ();
+
+ public synchronized Set<HeatTemplateParam> getParameterList() {
+ Set<HeatTemplateParam> paramSet = new HashSet<>();
@SuppressWarnings("unchecked")
- Map <String, Object> resourceMap = (Map <String, Object>) yml.get ("parameters");
+ Map<String, Object> resourceMap = (Map<String, Object>) yml.get("parameters");
for (Entry<String, Object> stringObjectEntry : resourceMap.entrySet()) {
HeatTemplateParam param = new HeatTemplateParam();
@@ -138,7 +141,7 @@ public class MsoYamlEditorWithEnvt {
// This exception only - the value is an integer. For what we're doing
// here - we don't care - so set value to something - and it will
// get marked as not being required - which is correct.
- //System.out.println("cce exception!");
+ // System.out.println("cce exception!");
value = "300";
// okay
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java
index 543ad07d52..a4cdba22a1 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java
@@ -22,7 +22,6 @@ package org.onap.so.openstack.utils;
import java.io.Serializable;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -30,10 +29,7 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "id",
- "links"
-})
+@JsonPropertyOrder({"id", "links"})
public class MulticloudCreateHeatResponse implements Serializable {
private final static long serialVersionUID = -5215028275577848311L;
@@ -43,8 +39,7 @@ public class MulticloudCreateHeatResponse implements Serializable {
private List<MulticloudCreateLinkResponse> links;
@JsonCreator
- public MulticloudCreateHeatResponse(
- @JsonProperty("id") String id,
+ public MulticloudCreateHeatResponse(@JsonProperty("id") String id,
@JsonProperty("links") List<MulticloudCreateLinkResponse> links) {
this.id = id;
this.links = links;
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java
index b609ac96c4..e8a5b1480e 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java
@@ -29,10 +29,7 @@ import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "href",
- "rel"
-})
+@JsonPropertyOrder({"href", "rel"})
public class MulticloudCreateLinkResponse implements Serializable {
private final static long serialVersionUID = -5215028275577848311L;
@@ -42,9 +39,7 @@ public class MulticloudCreateLinkResponse implements Serializable {
private String rel;
@JsonCreator
- public MulticloudCreateLinkResponse(
- @JsonProperty("href") String href,
- @JsonProperty("rel") String rel) {
+ public MulticloudCreateLinkResponse(@JsonProperty("href") String href, @JsonProperty("rel") String rel) {
this.href = href;
this.rel = rel;
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java
index fafd4a074d..bb15e58c88 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java
@@ -28,11 +28,7 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "template_type",
- "workload_id",
- "template_response"
-})
+@JsonPropertyOrder({"template_type", "workload_id", "template_response"})
public class MulticloudCreateResponse implements Serializable {
private final static long serialVersionUID = -5215028275577848311L;
@@ -44,8 +40,7 @@ public class MulticloudCreateResponse implements Serializable {
private MulticloudCreateStackResponse templateResponse;
@JsonCreator
- public MulticloudCreateResponse(
- @JsonProperty("template_type") String templateType,
+ public MulticloudCreateResponse(@JsonProperty("template_type") String templateType,
@JsonProperty("workload_id") String workloadId,
@JsonProperty("template_response") MulticloudCreateStackResponse templateResponse) {
this.templateType = templateType;
@@ -85,6 +80,7 @@ public class MulticloudCreateResponse implements Serializable {
@Override
public String toString() {
- return new ToStringBuilder(this).append("templateType", templateType).append("workloadId", workloadId).append("templateResponse", templateResponse).toString();
+ return new ToStringBuilder(this).append("templateType", templateType).append("workloadId", workloadId)
+ .append("templateResponse", templateResponse).toString();
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java
index f1d44a8814..67cb73539d 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java
@@ -28,9 +28,7 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "stack"
-})
+@JsonPropertyOrder({"stack"})
public class MulticloudCreateStackResponse implements Serializable {
private final static long serialVersionUID = -5215028275577848311L;
@@ -38,8 +36,7 @@ public class MulticloudCreateStackResponse implements Serializable {
private MulticloudCreateHeatResponse stack;
@JsonCreator
- public MulticloudCreateStackResponse(
- @JsonProperty("stack") MulticloudCreateHeatResponse stack) {
+ public MulticloudCreateStackResponse(@JsonProperty("stack") MulticloudCreateHeatResponse stack) {
this.stack = stack;
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java
index b22e9dc03e..ca8f041aae 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java
@@ -28,11 +28,7 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "template_type",
- "workload_id",
- "workload_status"
-})
+@JsonPropertyOrder({"template_type", "workload_id", "workload_status"})
public class MulticloudQueryResponse implements Serializable {
private final static long serialVersionUID = -5215028275577848311L;
@@ -44,10 +40,8 @@ public class MulticloudQueryResponse implements Serializable {
private String workloadStatus;
@JsonCreator
- public MulticloudQueryResponse(
- @JsonProperty("template_type") String templateType,
- @JsonProperty("workload_id") String workloadId,
- @JsonProperty("workload_status") String workloadStatus) {
+ public MulticloudQueryResponse(@JsonProperty("template_type") String templateType,
+ @JsonProperty("workload_id") String workloadId, @JsonProperty("workload_status") String workloadStatus) {
this.templateType = templateType;
this.workloadId = workloadId;
this.workloadStatus = workloadStatus;
@@ -85,6 +79,7 @@ public class MulticloudQueryResponse implements Serializable {
@Override
public String toString() {
- return new ToStringBuilder(this).append("templateType", templateType).append("workloadId", workloadId).append("workloadStatus", workloadStatus).toString();
+ return new ToStringBuilder(this).append("templateType", templateType).append("workloadId", workloadId)
+ .append("workloadStatus", workloadStatus).toString();
}
}
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java
index 3689d34204..b733552a2b 100644
--- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java
+++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java
@@ -26,22 +26,12 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.JsonNode;
import com.woorea.openstack.heat.model.CreateStackParam;
-
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "generic-vnf-id",
- "vf-module-id",
- "vf-module-model-invariant-id",
- "vf-module-model-version-id",
- "vf-module-model-customization-id",
- "oof_directives",
- "sdnc_directives",
- "user_directives",
- "template_type",
- "template_data"
-})
+@JsonPropertyOrder({"generic-vnf-id", "vf-module-id", "vf-module-model-invariant-id", "vf-module-model-version-id",
+ "vf-module-model-customization-id", "oof_directives", "sdnc_directives", "user_directives", "template_type",
+ "template_data"})
public class MulticloudRequest implements Serializable {
private final static long serialVersionUID = -5215028275577848311L;
@@ -169,15 +159,12 @@ public class MulticloudRequest implements Serializable {
@Override
public String toString() {
- return new ToStringBuilder(this).append("genericVnfId", genericVnfId)
- .append("vfModuleId", vfModuleId)
+ return new ToStringBuilder(this).append("genericVnfId", genericVnfId).append("vfModuleId", vfModuleId)
.append("vfModuleModelInvariantId", vfModuleModelInvariantId)
.append("vfModuleModelVersionId", vfModuleModelVersionId)
.append("vfModuleModelCustomizationId", vfModuleModelCustomizationId)
- .append("oofDirectives", oofDirectives)
- .append("sdncDirectives", sdncDirectives)
- .append("userDirectives", userDirectives)
- .append("templateType", templateType)
+ .append("oofDirectives", oofDirectives).append("sdncDirectives", sdncDirectives)
+ .append("userDirectives", userDirectives).append("templateType", templateType)
.append("templateData", templateData).toString();
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java
index a74dbf614b..a9365a3946 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/AllTestsTestSuite.java
@@ -19,14 +19,14 @@
*/
package org.onap.so;
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses("**/*Test.class")
public class AllTestsTestSuite {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java
index 82b18d86ed..ecdd052b73 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/BaseTest.java
@@ -26,13 +26,10 @@ package org.onap.so;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
-
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
-
import javax.ws.rs.core.MediaType;
-
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.junit.After;
@@ -48,7 +45,6 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
-
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
@@ -58,77 +54,74 @@ import com.github.tomakehurst.wiremock.client.WireMock;
@AutoConfigureWireMock(port = 0)
public abstract class BaseTest extends TestDataSetup {
- @Value("${wiremock.server.port}")
- protected int wireMockPort;
- @Autowired
- protected WireMockServer wireMockServer;
-
- @After
- public void after() {
- wireMockServer.resetAll();
- }
-
- protected static String getBody(String body, int port, String urlPath) throws IOException {
- return body.replaceAll("port", "http://localhost:" + port + urlPath);
- }
-
- @Before
- public void init() throws IOException {
- CloudIdentity identity = getCloudIdentity();
- CloudSite cloudSite = getCloudSite(identity);
- mockCloud(identity, cloudSite);
- }
-
- private void mockCloud(CloudIdentity identity, CloudSite cloudSite) throws IOException {
- wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/MTN13")).willReturn(aResponse()
- .withBody(getBody(mapper.writeValueAsString(cloudSite),wireMockPort, ""))
- .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/DEFAULT")).willReturn(aResponse()
- .withBody(getBody(mapper.writeValueAsString(cloudSite),wireMockPort, ""))
- .withHeader(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/cloudIdentity/mtn13")).willReturn(aResponse()
- .withBody(getBody(mapper.writeValueAsString(identity),wireMockPort, ""))
- .withHeader(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- }
-
- protected CloudIdentity getCloudIdentity() {
- CloudIdentity identity = new CloudIdentity();
- identity.setId("mtn13");
- identity.setMsoId("m93945");
- identity.setMsoPass("93937EA01B94A10A49279D4572B48369");
- identity.setAdminTenant("admin");
- identity.setMemberRole("admin");
- identity.setTenantMetadata(false);
- identity.setIdentityUrl("http://localhost:"+wireMockPort+"/v2.0");
- identity.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
- identity.setIdentityServerType(ServerType.KEYSTONE);
- return identity;
- }
-
- protected CloudSite getCloudSite(CloudIdentity identity) {
- CloudSite cloudSite = new CloudSite();
- cloudSite.setId("MTN13");
- cloudSite.setCloudVersion("3.0");
- cloudSite.setClli("MDT13");
- cloudSite.setRegionId("mtn13");
- cloudSite.setIdentityService(identity);
- return cloudSite;
- }
-
- private static String readFile(String fileName) throws IOException {
- try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
- StringBuilder sb = new StringBuilder();
- String line = br.readLine();
-
- while (line != null) {
- sb.append(line);
- sb.append("\n");
- line = br.readLine();
- }
- return sb.toString();
- }
- }
+ @Value("${wiremock.server.port}")
+ protected int wireMockPort;
+ @Autowired
+ protected WireMockServer wireMockServer;
+
+ @After
+ public void after() {
+ wireMockServer.resetAll();
+ }
+
+ protected static String getBody(String body, int port, String urlPath) throws IOException {
+ return body.replaceAll("port", "http://localhost:" + port + urlPath);
+ }
+
+ @Before
+ public void init() throws IOException {
+ CloudIdentity identity = getCloudIdentity();
+ CloudSite cloudSite = getCloudSite(identity);
+ mockCloud(identity, cloudSite);
+ }
+
+ private void mockCloud(CloudIdentity identity, CloudSite cloudSite) throws IOException {
+ wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/MTN13")).willReturn(aResponse()
+ .withBody(getBody(mapper.writeValueAsString(cloudSite), wireMockPort, ""))
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/DEFAULT")).willReturn(aResponse()
+ .withBody(getBody(mapper.writeValueAsString(cloudSite), wireMockPort, ""))
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/cloudIdentity/mtn13")).willReturn(aResponse()
+ .withBody(getBody(mapper.writeValueAsString(identity), wireMockPort, ""))
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
+ }
+
+ protected CloudIdentity getCloudIdentity() {
+ CloudIdentity identity = new CloudIdentity();
+ identity.setId("mtn13");
+ identity.setMsoId("m93945");
+ identity.setMsoPass("93937EA01B94A10A49279D4572B48369");
+ identity.setAdminTenant("admin");
+ identity.setMemberRole("admin");
+ identity.setTenantMetadata(false);
+ identity.setIdentityUrl("http://localhost:" + wireMockPort + "/v2.0");
+ identity.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
+ identity.setIdentityServerType(ServerType.KEYSTONE);
+ return identity;
+ }
+
+ protected CloudSite getCloudSite(CloudIdentity identity) {
+ CloudSite cloudSite = new CloudSite();
+ cloudSite.setId("MTN13");
+ cloudSite.setCloudVersion("3.0");
+ cloudSite.setClli("MDT13");
+ cloudSite.setRegionId("mtn13");
+ cloudSite.setIdentityService(identity);
+ return cloudSite;
+ }
+
+ private static String readFile(String fileName) throws IOException {
+ try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+
+ while (line != null) {
+ sb.append(line);
+ sb.append("\n");
+ line = br.readLine();
+ }
+ return sb.toString();
+ }
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
index c1705508ce..75794efe79 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
@@ -28,11 +28,10 @@ import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
-
import javax.sql.DataSource;
@Configuration
-@Profile({"test","local"})
+@Profile({"test", "local"})
public class EmbeddedMariaDbConfig {
@Bean
@@ -42,21 +41,16 @@ public class EmbeddedMariaDbConfig {
@Bean
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java
index ae3fb8271a..120c3e3493 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/StubOpenStack.java
@@ -29,49 +29,43 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
-
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
-
import org.apache.http.HttpStatus;
-
import com.github.tomakehurst.wiremock.WireMockServer;
public class StubOpenStack {
public static void mockOpenStackResponseAccess(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
}
public static void mockOpenStackResponseUnauthorized(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(
- post(urlPathEqualTo("/v2.0/tokens"))
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
.willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_UNAUTHORIZED)));
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_UNAUTHORIZED)));
}
public static void mockOpenStackDelete(WireMockServer wireMockServer, String id) {
- wireMockServer.stubFor(delete(urlMatching("/mockPublicUrl/stacks/" + id)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(delete(urlMatching("/mockPublicUrl/stacks/" + id))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
}
public static void mockOpenStackGet(WireMockServer wireMockServer, String id) {
- wireMockServer.stubFor(
- get(urlPathEqualTo("/mockPublicUrl/stacks/" + id))
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + id))
.willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Stack_Created.json")
- .withStatus(HttpStatus.SC_OK)));
+ .withBodyFile("OpenstackResponse_Stack_Created.json").withStatus(HttpStatus.SC_OK)));
}
public static void mockOpenStackPostStack_200(WireMockServer wireMockServer, String filename) {
wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/stacks")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
+ .withHeader("Content-Type", "application/json").withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
}
public static void mockOpenStackPostTenantWithBodyFile_200(WireMockServer wireMockServer) throws IOException {
@@ -79,7 +73,8 @@ public class StubOpenStack {
.willReturn(aResponse().withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK)));
}
- public static void mockOpenStackGetTenantByName(WireMockServer wireMockServer, String tenantName) throws IOException {
+ public static void mockOpenStackGetTenantByName(WireMockServer wireMockServer, String tenantName)
+ throws IOException {
wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/tenants/[?]name=" + tenantName))
.willReturn(aResponse().withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK)));
}
@@ -90,55 +85,53 @@ public class StubOpenStack {
}
public static void mockOpenStackDeleteTenantById_200(WireMockServer wireMockServer, String tenantId) {
- wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/tenants/" + tenantId)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/tenants/" + tenantId))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
}
public static void mockOpenStackGetUserById(WireMockServer wireMockServer, String user) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/users/" + user)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/users/" + user))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK)));
}
public static void mockOpenStackGetUserByName(WireMockServer wireMockServer, String userName) {
- wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/users/[?]name=" + userName)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/users/[?]name=" + userName))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK)));
}
public static void mockOpenStackGetUserByName_500(WireMockServer wireMockServer, String userName) {
- wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/users/[?]name=" + userName)).willReturn(aResponse()
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+ wireMockServer.stubFor(get(urlMatching("/mockPublicUrl/users/[?]name=" + userName))
+ .willReturn(aResponse().withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
}
public static void mockOpenStackGetRoles_200(WireMockServer wireMockServer, String roleFor) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/" + roleFor + "/roles")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Roles.json").withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/" + roleFor + "/roles"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_Roles.json").withStatus(HttpStatus.SC_OK)));
}
public static void mockOpenstackPostNetwork(WireMockServer wireMockServer, String responseFile) {
- wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/v2.0/networks")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/v2.0/networks"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile(responseFile)
+ .withStatus(HttpStatus.SC_OK)));
}
public static void mockOpenstackPutNetwork(WireMockServer wireMockServer, String responseFile, String networkId) {
- wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+networkId)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetNeutronNetwork(WireMockServer wireMockServer, String filename,String networkId) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+ networkId))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile(responseFile)
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetNeutronNetwork(WireMockServer wireMockServer, String filename,
+ String networkId) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId)).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
}
public static void mockOpenStackGetNeutronNetwork_500(WireMockServer wireMockServer, String networkId) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+ networkId))
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId))
.willReturn(aResponse().withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
}
@@ -162,6 +155,7 @@ public class StubOpenStack {
}
public static String getBodyFromFile(String fileName, int port, String urlPath) throws IOException {
- return readFile("src/test/resources/__files/" + fileName).replaceAll("port", "http://localhost:" + port + urlPath);
+ return readFile("src/test/resources/__files/" + fileName).replaceAll("port",
+ "http://localhost:" + port + urlPath);
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java
index 479731c870..f73c3a8e6c 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestApplication.java
@@ -28,12 +28,12 @@ import org.springframework.context.annotation.Profile;
@SpringBootApplication
@Profile("test")
-@ComponentScan(basePackages = {"org.onap.so", "com.att"}, excludeFilters = {
- @Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
+@ComponentScan(basePackages = {"org.onap.so", "com.att"},
+ excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
public class TestApplication {
- public static void main(String... args) {
- SpringApplication.run(TestApplication.class, args);
- System.getProperties().setProperty("mso.db", "MARIADB");
- System.getProperties().setProperty("server.name", "Springboot");
- }
+ public static void main(String... args) {
+ SpringApplication.run(TestApplication.class, args);
+ System.getProperties().setProperty("mso.db", "MARIADB");
+ System.getProperties().setProperty("server.name", "Springboot");
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java
index 21c4c225ba..61cc24b31a 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/TestDataSetup.java
@@ -23,18 +23,17 @@ package org.onap.so;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
-
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestDataSetup {
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- public static final String RESOURCE_PATH = "src/test/resources/__files/";
- public ObjectMapper mapper;
-
- @Before
- public void testDataSetupBefore() {
- mapper = new ObjectMapper();
- }
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ public static final String RESOURCE_PATH = "src/test/resources/__files/";
+ public ObjectMapper mapper;
+
+ @Before
+ public void testDataSetupBefore() {
+ mapper = new ObjectMapper();
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java
index ea25fe580d..fb3b3e0dc5 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudConfigTest.java
@@ -21,9 +21,7 @@
package org.onap.so.cloud;
import static org.junit.Assert.*;
-
import java.util.Optional;
-
import org.junit.Test;
import org.onap.so.BaseTest;
import org.onap.so.db.catalog.beans.AuthenticationType;
@@ -38,35 +36,35 @@ import org.springframework.beans.factory.annotation.Autowired;
*
*
*/
-public class CloudConfigTest extends BaseTest{
+public class CloudConfigTest extends BaseTest {
+
+ @Autowired
+ private CloudConfig con;
- @Autowired
- private CloudConfig con;
+ /**
+ * This method implements a test for the getCloudSite method.
+ */
+ @Test
+ public final void testGetCloudSite() {
+ CloudSite site1 = con.getCloudSite("MTN13").get();
- /**
- * This method implements a test for the getCloudSite method.
- */
- @Test
- public final void testGetCloudSite () {
- CloudSite site1 = con.getCloudSite("MTN13").get();
+ assertEquals("mtn13", site1.getRegionId());
+ assertEquals("mtn13", site1.getIdentityServiceId());
+ assertEquals("MDT13", site1.getClli());
+ assertEquals("3.0", site1.getCloudVersion());
+ }
- assertEquals ("mtn13", site1.getRegionId());
- assertEquals ("mtn13", site1.getIdentityServiceId());
- assertEquals ("MDT13", site1.getClli());
- assertEquals ("3.0", site1.getCloudVersion());
- }
+ /**
+ * This method implements a test for the getCloudSite method.
+ */
+ @Test
+ public final void testGetDefaultCloudSite() {
+ Optional<CloudSite> site = con.getCloudSite("NotThere");
+ assertTrue(site.isPresent());
+ CloudSite site1 = site.get();
+ assertEquals("NotThere", site1.getRegionId());
+ assertEquals("MDT13", site1.getClli());
+ assertEquals("NotThere", site1.getId());
+ }
- /**
- * This method implements a test for the getCloudSite method.
- */
- @Test
- public final void testGetDefaultCloudSite () {
- Optional<CloudSite> site = con.getCloudSite("NotThere");
- assertTrue(site.isPresent());
- CloudSite site1 = site.get();
- assertEquals ("NotThere", site1.getRegionId());
- assertEquals("MDT13", site1.getClli());
- assertEquals("NotThere", site1.getId());
- }
-
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java
index 096d5dad8b..6c58cda2d1 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/CloudPojoTest.java
@@ -25,7 +25,6 @@ import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.db.catalog.beans.CloudSite;
import org.onap.so.db.catalog.beans.CloudifyManager;
import org.onap.so.openpojo.rules.ToStringTester;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.impl.PojoClassFactory;
import com.openpojo.validation.Validator;
@@ -37,23 +36,18 @@ import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
public class CloudPojoTest {
- @Test
- public void pojoStructure() {
- test(PojoClassFactory.getPojoClass(CloudIdentity.class));
- test(PojoClassFactory.getPojoClass(CloudifyManager.class));
- test(PojoClassFactory.getPojoClass(CloudSite.class));
- test(PojoClassFactory.getPojoClass(CloudConfig.class));
- }
-
- private void test(PojoClass pojoClass) {
- Validator validator = ValidatorBuilder.create()
- .with(new EqualsAndHashCodeMatchRule())
- .with(new NoPrimitivesRule())
- .with(new NoPublicFieldsRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .with(new ToStringTester())
- .build();
- validator.validate(pojoClass);
- }
+ @Test
+ public void pojoStructure() {
+ test(PojoClassFactory.getPojoClass(CloudIdentity.class));
+ test(PojoClassFactory.getPojoClass(CloudifyManager.class));
+ test(PojoClassFactory.getPojoClass(CloudSite.class));
+ test(PojoClassFactory.getPojoClass(CloudConfig.class));
+ }
+
+ private void test(PojoClass pojoClass) {
+ Validator validator = ValidatorBuilder.create().with(new EqualsAndHashCodeMatchRule())
+ .with(new NoPrimitivesRule()).with(new NoPublicFieldsRule()).with(new SetterTester())
+ .with(new GetterTester()).with(new ToStringTester()).build();
+ validator.validate(pojoClass);
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java
index a5abe75af2..41aac0084c 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/AuthenticationMethodTest.java
@@ -23,17 +23,14 @@ package org.onap.so.cloud.authentication;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import org.junit.Test;
import org.onap.so.cloud.authentication.models.RackspaceAuthentication;
import org.onap.so.db.catalog.beans.AuthenticationType;
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.utils.CryptoUtils;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -41,81 +38,83 @@ import com.woorea.openstack.keystone.model.Authentication;
import com.woorea.openstack.keystone.model.authentication.UsernamePassword;
/**
- * A few JUnit tests to evaluate the new factory that manages authentication
- * types and their associated wrapper classes. Here it is assumed that core types
- * only are tested.
+ * A few JUnit tests to evaluate the new factory that manages authentication types and their associated wrapper classes.
+ * Here it is assumed that core types only are tested.
*
*/
public class AuthenticationMethodTest {
- private AuthenticationMethodFactory authenticationMethodFactory = new AuthenticationMethodFactory();
- /**
- *
- */
- public AuthenticationMethodTest() {
- // TODO Auto-generated constructor stub
- }
-
- @Test
- public void testCustomRackspaceAuth() {
- CloudIdentity ci = new CloudIdentity();
- ci.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY);
- ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
- ci.setMsoId("test");
-
- Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
- assertTrue(RackspaceAuthentication.class.equals(auth.getClass()));
-
- }
-
- @Test
- public void testCoreUsernamePasswordAuth() {
- CloudIdentity ci = new CloudIdentity();
- ci.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
- ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
- ci.setMsoId("someuser");
-
- Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
- assertTrue(UsernamePassword.class.equals(auth.getClass()));
-
- }
-
- @Test
- public void testCustomRackspaceAuthFromCloudIdentity() {
- CloudIdentity ci = new CloudIdentity();
- ci.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY);
- ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
- ci.setMsoId("test");
-
- Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
- assertTrue(RackspaceAuthentication.class.equals(auth.getClass()));
- }
-
- @Test
- public void testCoreUsernamePasswordAuthFromCloudIdentity() {
- CloudIdentity ci = new CloudIdentity();
- ci.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
- ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
- ci.setMsoId("someuser");
-
- Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
- assertTrue(UsernamePassword.class.equals(auth.getClass()));
-
- }
-
- @Test
- public void getAuthenticationForV3Test() throws JsonParseException, JsonMappingException, IOException {
-
- CloudIdentity identity = new CloudIdentity();
- identity.setMsoId("my-username");
- identity.setMsoPass(CryptoUtils.encryptCloudConfigPassword("my-password"));
- identity.setProjectDomainName("test-domain");
- identity.setUserDomainName("user-domain");
- ObjectMapper mapper = new ObjectMapper();
- com.woorea.openstack.keystone.v3.model.Authentication expected =
- mapper.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/__files/KeystoneV3Payload.json"))), com.woorea.openstack.keystone.v3.model.Authentication.class);
- com.woorea.openstack.keystone.v3.model.Authentication actual = authenticationMethodFactory.getAuthenticationForV3(identity, "project-x");
-
- assertThat(actual, sameBeanAs(expected));
- }
+ private AuthenticationMethodFactory authenticationMethodFactory = new AuthenticationMethodFactory();
+
+ /**
+ *
+ */
+ public AuthenticationMethodTest() {
+ // TODO Auto-generated constructor stub
+ }
+
+ @Test
+ public void testCustomRackspaceAuth() {
+ CloudIdentity ci = new CloudIdentity();
+ ci.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY);
+ ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
+ ci.setMsoId("test");
+
+ Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
+ assertTrue(RackspaceAuthentication.class.equals(auth.getClass()));
+
+ }
+
+ @Test
+ public void testCoreUsernamePasswordAuth() {
+ CloudIdentity ci = new CloudIdentity();
+ ci.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
+ ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
+ ci.setMsoId("someuser");
+
+ Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
+ assertTrue(UsernamePassword.class.equals(auth.getClass()));
+
+ }
+
+ @Test
+ public void testCustomRackspaceAuthFromCloudIdentity() {
+ CloudIdentity ci = new CloudIdentity();
+ ci.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY);
+ ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
+ ci.setMsoId("test");
+
+ Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
+ assertTrue(RackspaceAuthentication.class.equals(auth.getClass()));
+ }
+
+ @Test
+ public void testCoreUsernamePasswordAuthFromCloudIdentity() {
+ CloudIdentity ci = new CloudIdentity();
+ ci.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
+ ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");
+ ci.setMsoId("someuser");
+
+ Authentication auth = authenticationMethodFactory.getAuthenticationFor(ci);
+ assertTrue(UsernamePassword.class.equals(auth.getClass()));
+
+ }
+
+ @Test
+ public void getAuthenticationForV3Test() throws JsonParseException, JsonMappingException, IOException {
+
+ CloudIdentity identity = new CloudIdentity();
+ identity.setMsoId("my-username");
+ identity.setMsoPass(CryptoUtils.encryptCloudConfigPassword("my-password"));
+ identity.setProjectDomainName("test-domain");
+ identity.setUserDomainName("user-domain");
+ ObjectMapper mapper = new ObjectMapper();
+ com.woorea.openstack.keystone.v3.model.Authentication expected = mapper.readValue(
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/KeystoneV3Payload.json"))),
+ com.woorea.openstack.keystone.v3.model.Authentication.class);
+ com.woorea.openstack.keystone.v3.model.Authentication actual =
+ authenticationMethodFactory.getAuthenticationForV3(identity, "project-x");
+
+ assertThat(actual, sameBeanAs(expected));
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java
index 8469ad506c..5bd77d8e10 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloud/authentication/KeystoneAuthHolderTest.java
@@ -19,22 +19,17 @@
*/
/*
- * ============LICENSE_START==========================================
- * ONAP - SO
- * ===================================================================
- * Copyright (c) 2019 IBM.
- * ===================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START========================================== ONAP - SO
+ * =================================================================== Copyright (c) 2019 IBM.
+ * =================================================================== Licensed under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the
+ * License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
*
* ============LICENSE_END=============================================
* ====================================================================
@@ -42,9 +37,7 @@
package org.onap.so.cloud.authentication;
import static org.junit.Assert.assertEquals;
-
import java.util.Calendar;
-
import org.junit.Before;
import org.junit.Test;
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java
index ce13d98dd1..9fbb45a2c3 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/beans/DeploymentInfoBuilderTest.java
@@ -1,26 +1,20 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 Nokia.
- * =============================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 Nokia.
+ * ============================================================================= Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.so.cloudify.beans;
import static org.assertj.core.api.Assertions.assertThat;
-
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import org.onap.so.cloudify.v3.model.Execution;
@@ -33,15 +27,10 @@ public class DeploymentInfoBuilderTest {
@Test
public void shouldConstructDeploymentInfo_withBasicValues() {
- DeploymentInfo deploymentInfo = new DeploymentInfoBuilder()
- .withId("id")
- .withStatus(DeploymentStatus.CREATED)
- .withDeploymentOutputs(ImmutableMap.of())
- .withDeploymentInputs(ImmutableMap.of())
- .withActionStatus("started")
- .withLastAction(INSTALL_WORKFLOW_ID)
- .withErrorMessage(ERROR_MESSAGE)
- .build();
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.CREATED)
+ .withDeploymentOutputs(ImmutableMap.of()).withDeploymentInputs(ImmutableMap.of())
+ .withActionStatus("started").withLastAction(INSTALL_WORKFLOW_ID).withErrorMessage(ERROR_MESSAGE)
+ .build();
assertThat(deploymentInfo.getId()).isEqualTo("id");
assertThat(deploymentInfo.getStatus()).isEqualTo(DeploymentStatus.CREATED);
@@ -54,9 +43,7 @@ public class DeploymentInfoBuilderTest {
@Test
public void shouldConstructDeploymentInfo_withCreateDeploymentStatus_fromNullExecution() {
- DeploymentInfo deploymentInfo = new DeploymentInfoBuilder()
- .fromExecution(null)
- .build();
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().fromExecution(null).build();
assertThat(deploymentInfo.getStatus()).isEqualTo(DeploymentStatus.CREATED);
}
@@ -156,19 +143,17 @@ public class DeploymentInfoBuilderTest {
}
private void verifyDeploymentInfoConstruction(String workflowIdLastAction, String actionStatus,
- DeploymentStatus expectedDeploymentStatus) {
+ DeploymentStatus expectedDeploymentStatus) {
Execution execution = new Execution();
execution.setWorkflowId(workflowIdLastAction);
execution.setStatus(actionStatus);
execution.setError(ERROR_MESSAGE);
- DeploymentInfo deploymentInfo = new DeploymentInfoBuilder()
- .fromExecution(execution)
- .build();
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().fromExecution(execution).build();
assertThat(deploymentInfo.getLastAction()).isEqualTo(workflowIdLastAction);
assertThat(deploymentInfo.getActionStatus()).isEqualTo(actionStatus);
assertThat(deploymentInfo.getErrorMessage()).isEqualTo(ERROR_MESSAGE);
assertThat(deploymentInfo.getStatus()).isEqualTo(expectedDeploymentStatus);
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java
index 4bf087b7a4..d45f685795 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyExceptionTest.java
@@ -1,39 +1,33 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.cloudify.exceptions;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class MsoCloudifyExceptionTest {
-
- @Test
+
+ @Test
public void test() {
Exception e = null;
- boolean pendingWorkflow=true;
- MsoCloudifyException mce=new MsoCloudifyException(200, "message", "detail");
- MsoCloudifyException mcl=new MsoCloudifyException(200, "message", "detail", e);
+ boolean pendingWorkflow = true;
+ MsoCloudifyException mce = new MsoCloudifyException(200, "message", "detail");
+ MsoCloudifyException mcl = new MsoCloudifyException(200, "message", "detail", e);
mce.setPendingWorkflow(pendingWorkflow);
- assert(mcl.toString()!=null);
+ assert (mcl.toString() != null);
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java
index a1859e491a..08b2356fdc 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTest.java
@@ -1,35 +1,29 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.cloudify.exceptions;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class MsoCloudifyTest {
-
- @Test
+
+ @Test
public void test() {
- MsoBlueprintAlreadyExists mbae=new MsoBlueprintAlreadyExists("blueprintId", "cloud");
- MsoCloudifyManagerNotFound mcm=new MsoCloudifyManagerNotFound("cloudSiteId");
- MsoDeploymentAlreadyExists mdae=new MsoDeploymentAlreadyExists("deploymentId", "cloud");
+ MsoBlueprintAlreadyExists mbae = new MsoBlueprintAlreadyExists("blueprintId", "cloud");
+ MsoCloudifyManagerNotFound mcm = new MsoCloudifyManagerNotFound("cloudSiteId");
+ MsoDeploymentAlreadyExists mdae = new MsoDeploymentAlreadyExists("deploymentId", "cloud");
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java
index 21c625feb3..48c5c877a5 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyTimeoutTest.java
@@ -1,38 +1,32 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.cloudify.exceptions;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
-
import org.junit.Test;
import org.onap.so.cloudify.v3.model.Execution;
public class MsoCloudifyTimeoutTest {
-
- @Test
+
+ @Test
public void test() {
- Execution execution=mock(Execution.class);
- MsoCloudifyTimeout mct=new MsoCloudifyTimeout(execution);
+ Execution execution = mock(Execution.class);
+ MsoCloudifyTimeout mct = new MsoCloudifyTimeout(execution);
mct.getExecution();
- assert(mct.toString()!=null);
+ assert (mct.toString() != null);
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java
index 68df574611..b8b2c97a65 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowExceptionTest.java
@@ -1,36 +1,31 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.cloudify.exceptions;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class MsoCloudifyWorkflowExceptionTest {
-
- @Test
+
+ @Test
public void test() {
- MsoCloudifyWorkflowException mcw=new MsoCloudifyWorkflowException("message", "id", "workflowId", "workflowStatus");
+ MsoCloudifyWorkflowException mcw =
+ new MsoCloudifyWorkflowException("message", "id", "workflowId", "workflowStatus");
mcw.getWorkflowStatus();
assertFalse(mcw.isWorkflowStillRunning());
-
+
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java
index 833b4ab760..d14115971c 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/cloudify/utils/MsoCloudifyUtilsTest.java
@@ -33,7 +33,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
@@ -42,7 +41,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
@@ -67,7 +65,6 @@ import org.onap.so.db.catalog.beans.HeatTemplateParam;
import org.onap.so.openstack.exceptions.MsoAdapterException;
import org.onap.so.openstack.exceptions.MsoException;
import org.skyscreamer.jsonassert.JSONAssert;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -76,273 +73,264 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class MsoCloudifyUtilsTest {
- private static final String CLOUD_SITE_ID = "cloudSiteIdTest";
- private static final String BLUEPRINT_ID = "bluePrintIdTest";
- private static final String FILE_NAME = "fileName";
-
- @Test
- public void instantiateVduTest() throws MsoException {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("id");
- expected.setVduInstanceName("id");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.INSTANTIATED);
- status.setLastAction(new PluginAction(null, null, null));
- expected.setStatus(status);
-
- MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class);
- CloudSite site = new CloudSite();
- Optional<CloudSite> opSite = Optional.ofNullable(site);
- CloudConfig config = Mockito.mock(CloudConfig.class);
- cloudify.cloudConfig = config;
- Cloudify cloudifyClient = new Cloudify("cloudSite");
- CloudInfo cloudInfo = new CloudInfo();
- cloudInfo.setCloudSiteId("cloudSiteId");
- cloudInfo.setTenantId("tenantId");
- VduModelInfo vduModel = new VduModelInfo();
- vduModel.setModelCustomizationUUID("blueprintId");
- vduModel.setTimeoutMinutes(1);
- VduArtifact artifact = new VduArtifact();
- artifact.setName("name");
- artifact.setType(ArtifactType.MAIN_TEMPLATE);
- byte[] content = new byte[1];
- artifact.setContent(content);
- List<VduArtifact> artifacts = new ArrayList<>();
- artifacts.add(artifact);
- vduModel.setArtifacts(artifacts);
- DeploymentInfo deployment = new DeploymentInfoBuilder()
- .withId("id")
- .withStatus(DeploymentStatus.INSTALLED)
- .build();
- Map<String, byte[]> blueprintFiles = new HashMap<>();
- blueprintFiles.put(artifact.getName(), artifact.getContent());
- String instanceName = "instanceName";
- Map<String, Object> inputs = new HashMap<>();
- boolean rollbackOnFailure = true;
-
- when(config.getCloudSite(cloudInfo.getCloudSiteId())).thenReturn(opSite);
- doReturn(false).when(cloudify).isBlueprintLoaded(cloudInfo.getCloudSiteId(),
- vduModel.getModelCustomizationUUID());
- doReturn(cloudifyClient).when(cloudify).getCloudifyClient(site);
- doReturn(true).when(cloudify).uploadBlueprint(cloudifyClient, vduModel.getModelCustomizationUUID(),
- artifact.getName(), blueprintFiles);
- doReturn(deployment).when(cloudify).createAndInstallDeployment(cloudInfo.getCloudSiteId(),
- cloudInfo.getTenantId(), instanceName, vduModel.getModelCustomizationUUID(), inputs, true,
- vduModel.getTimeoutMinutes(), rollbackOnFailure);
-
- VduInstance actual = cloudify.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void queryVduTest() throws MsoException {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("id");
- expected.setVduInstanceName("id");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.INSTANTIATED);
- status.setLastAction(new PluginAction(null, null, null));
- expected.setStatus(status);
-
- CloudInfo cloudInfo = new CloudInfo();
- cloudInfo.setCloudSiteId("cloudSiteId");
- cloudInfo.setTenantId("tenantId");
- DeploymentInfo deployment = new DeploymentInfoBuilder()
- .withId("id")
- .withStatus(DeploymentStatus.INSTALLED)
- .build();
- String instanceId = "instanceId";
-
- MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class);
-
- doReturn(deployment).when(cloudify).queryDeployment(cloudInfo.getCloudSiteId(), cloudInfo.getTenantId(),
- instanceId);
-
- VduInstance actual = cloudify.queryVdu(cloudInfo, instanceId);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void deleteVduTest() throws MsoException {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("id");
- expected.setVduInstanceName("id");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.DELETING);
- status.setLastAction(new PluginAction("deleting", null, null));
- expected.setStatus(status);
-
- CloudInfo cloudInfo = new CloudInfo();
- cloudInfo.setCloudSiteId("cloudSiteId");
- cloudInfo.setTenantId("tenantId");
- String instanceId = "instanceId";
- int timeoutMinutes = 1;
- DeploymentInfo deploymentInfo = new DeploymentInfoBuilder()
- .withId("id")
- .withStatus(DeploymentStatus.CREATED)
- .withLastAction("deleting").build();
- MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class);
- doReturn(deploymentInfo).when(cloudify).uninstallAndDeleteDeployment(cloudInfo.getCloudSiteId(),
- cloudInfo.getTenantId(), instanceId, timeoutMinutes);
-
- VduInstance actual = cloudify.deleteVdu(cloudInfo, instanceId, timeoutMinutes);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void deploymentInfoToVduInstanceTest() {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("id");
- expected.setVduInstanceName("id");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.DELETING);
- status.setLastAction(new PluginAction("deleting", null, null));
- expected.setStatus(status);
-
- DeploymentInfo deploymentInfo = new DeploymentInfoBuilder()
- .withId("id")
- .withStatus(DeploymentStatus.CREATED)
- .withLastAction("deleting").build();
-
- MsoCloudifyUtils cloudify = new MsoCloudifyUtils();
-
- VduInstance actual = cloudify.deploymentInfoToVduInstance(deploymentInfo);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void deploymentStatusToVduStatusTest() {
- VduStatus expected = new VduStatus();
- expected.setState(VduStateType.DELETING);
- expected.setLastAction(new PluginAction("deleting", null, null));
-
- DeploymentInfo deploymentInfo = new DeploymentInfoBuilder()
- .withId("id")
- .withStatus(DeploymentStatus.CREATED)
- .withLastAction("deleting").build();
-
- MsoCloudifyUtils cloudify = new MsoCloudifyUtils();
-
- VduStatus actual = cloudify.deploymentStatusToVduStatus(deploymentInfo);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void getAzureConfigTest() {
- AzureConfig expected = new AzureConfig();
- expected.setSubscriptionId("subscriptionId");
- expected.setTenantId("tenantId");
- expected.setClientId("msoId");
- expected.setClientSecret("msoPass");
-
- MsoCloudifyUtils cloudify = new MsoCloudifyUtils();
- CloudSite cloudSite = Mockito.mock(CloudSite.class);
- CloudIdentity cloudIdentity = Mockito.mock(CloudIdentity.class);
- when(cloudSite.getIdentityService()).thenReturn(cloudIdentity);
- when(cloudIdentity.getAdminTenant()).thenReturn("subscriptionId");
- when(cloudIdentity.getMsoId()).thenReturn("msoId");
- when(cloudIdentity.getMsoPass()).thenReturn("msoPass");
- String tenantId = "tenantId";
- AzureConfig actual = cloudify.getAzureConfig(cloudSite, tenantId);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void uploadBlueprintSuccessful() throws MsoException {
- // given
- MsoCloudifyUtils testedObjectSpy = spy(MsoCloudifyUtils.class);
- testedObjectSpy.cloudConfig = mock(CloudConfig.class);
- Map<String, byte[]> blueprints = new HashMap<>();
-
- mockCloudConfig(testedObjectSpy);
- doReturn(true).when(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID),
- eq(FILE_NAME), eq(blueprints));
- // when
- testedObjectSpy.uploadBlueprint(CLOUD_SITE_ID, BLUEPRINT_ID, FILE_NAME, blueprints, true);
- // then
- verify(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME),
- eq(blueprints));
- }
-
- @Test
- public void uploadBlueprint_exceptionThrown_blueprintExists() throws MsoException {
- // given
- MsoCloudifyUtils testedObjectSpy = spy(MsoCloudifyUtils.class);
- testedObjectSpy.cloudConfig = mock(CloudConfig.class);
- Map<String, byte[]> blueprints = new HashMap<>();
-
- mockCloudConfig(testedObjectSpy);
- doReturn(false).when(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID),
- eq(FILE_NAME), eq(blueprints));
- // when
- try {
- testedObjectSpy.uploadBlueprint(CLOUD_SITE_ID, BLUEPRINT_ID, FILE_NAME, blueprints, true);
- // then
- fail("MsoAdapterException should be thrown");
- } catch (MsoAdapterException e) {
- Assert.assertEquals(e.getMessage(), "Blueprint already exists");
- }
- verify(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME),
- eq(blueprints));
- }
-
- @Test
- public void convertInputValueTest() throws JsonParseException, JsonMappingException, IOException {
- MsoCloudifyUtils utils = new MsoCloudifyUtils();
- ObjectMapper mapper = new ObjectMapper();
- HeatTemplateParam paramNum = new HeatTemplateParam();
- paramNum.setParamType("number");
- paramNum.setParamName("my-number");
-
- HeatTemplateParam paramString = new HeatTemplateParam();
- paramString.setParamType("string");
- paramString.setParamName("my-string");
-
- HeatTemplateParam paramJson = new HeatTemplateParam();
- paramJson.setParamType("json");
- paramJson.setParamName("my-json");
-
- HeatTemplateParam paramJsonEscaped = new HeatTemplateParam();
- paramJsonEscaped.setParamType("json");
- paramJsonEscaped.setParamName("my-json-escaped");
-
- Map<String, Object> jsonMap = mapper.readValue(getJson("free-form.json"), new TypeReference<Map<String, Object>>(){});
-
- assertEquals(3, utils.convertInputValue("3", paramNum));
- assertEquals("hello", utils.convertInputValue("hello", paramString));
- assertTrue("expect no change in type", utils.convertInputValue(jsonMap, paramJson) instanceof Map);
- assertTrue("expect string to become jsonNode", utils.convertInputValue(getJson("free-form.json"), paramJsonEscaped) instanceof JsonNode);
-
- JSONAssert.assertEquals(getJson("free-form.json"), mapper.writeValueAsString(utils.convertInputValue(getJson("free-form.json"), paramJsonEscaped)), false);
-
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/MsoHeatUtils/" + filename)));
- }
-
- private void mockCloudConfig(MsoCloudifyUtils testedObjectSpy) {
- CloudifyManager cloudifyManager = createCloudifyManager();
- when(testedObjectSpy.cloudConfig.getCloudSite(CLOUD_SITE_ID)).thenReturn(Optional.of(createCloudSite()));
- when(testedObjectSpy.cloudConfig.getCloudifyManager(CLOUD_SITE_ID)).thenReturn(cloudifyManager);
- }
-
- private CloudifyManager createCloudifyManager() {
- CloudifyManager cloudifyManager = new CloudifyManager();
- cloudifyManager.setCloudifyUrl("cloudUrlTest");
- cloudifyManager.setPassword("546573746F736973546573746F736973");
- return cloudifyManager;
- }
-
- private CloudSite createCloudSite() {
- CloudSite cloudSite = new CloudSite();
- cloudSite.setCloudifyId(CLOUD_SITE_ID);
- return cloudSite;
- }
+ private static final String CLOUD_SITE_ID = "cloudSiteIdTest";
+ private static final String BLUEPRINT_ID = "bluePrintIdTest";
+ private static final String FILE_NAME = "fileName";
+
+ @Test
+ public void instantiateVduTest() throws MsoException {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("id");
+ expected.setVduInstanceName("id");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.INSTANTIATED);
+ status.setLastAction(new PluginAction(null, null, null));
+ expected.setStatus(status);
+
+ MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class);
+ CloudSite site = new CloudSite();
+ Optional<CloudSite> opSite = Optional.ofNullable(site);
+ CloudConfig config = Mockito.mock(CloudConfig.class);
+ cloudify.cloudConfig = config;
+ Cloudify cloudifyClient = new Cloudify("cloudSite");
+ CloudInfo cloudInfo = new CloudInfo();
+ cloudInfo.setCloudSiteId("cloudSiteId");
+ cloudInfo.setTenantId("tenantId");
+ VduModelInfo vduModel = new VduModelInfo();
+ vduModel.setModelCustomizationUUID("blueprintId");
+ vduModel.setTimeoutMinutes(1);
+ VduArtifact artifact = new VduArtifact();
+ artifact.setName("name");
+ artifact.setType(ArtifactType.MAIN_TEMPLATE);
+ byte[] content = new byte[1];
+ artifact.setContent(content);
+ List<VduArtifact> artifacts = new ArrayList<>();
+ artifacts.add(artifact);
+ vduModel.setArtifacts(artifacts);
+ DeploymentInfo deployment =
+ new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.INSTALLED).build();
+ Map<String, byte[]> blueprintFiles = new HashMap<>();
+ blueprintFiles.put(artifact.getName(), artifact.getContent());
+ String instanceName = "instanceName";
+ Map<String, Object> inputs = new HashMap<>();
+ boolean rollbackOnFailure = true;
+
+ when(config.getCloudSite(cloudInfo.getCloudSiteId())).thenReturn(opSite);
+ doReturn(false).when(cloudify).isBlueprintLoaded(cloudInfo.getCloudSiteId(),
+ vduModel.getModelCustomizationUUID());
+ doReturn(cloudifyClient).when(cloudify).getCloudifyClient(site);
+ doReturn(true).when(cloudify).uploadBlueprint(cloudifyClient, vduModel.getModelCustomizationUUID(),
+ artifact.getName(), blueprintFiles);
+ doReturn(deployment).when(cloudify).createAndInstallDeployment(cloudInfo.getCloudSiteId(),
+ cloudInfo.getTenantId(), instanceName, vduModel.getModelCustomizationUUID(), inputs, true,
+ vduModel.getTimeoutMinutes(), rollbackOnFailure);
+
+ VduInstance actual = cloudify.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void queryVduTest() throws MsoException {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("id");
+ expected.setVduInstanceName("id");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.INSTANTIATED);
+ status.setLastAction(new PluginAction(null, null, null));
+ expected.setStatus(status);
+
+ CloudInfo cloudInfo = new CloudInfo();
+ cloudInfo.setCloudSiteId("cloudSiteId");
+ cloudInfo.setTenantId("tenantId");
+ DeploymentInfo deployment =
+ new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.INSTALLED).build();
+ String instanceId = "instanceId";
+
+ MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class);
+
+ doReturn(deployment).when(cloudify).queryDeployment(cloudInfo.getCloudSiteId(), cloudInfo.getTenantId(),
+ instanceId);
+
+ VduInstance actual = cloudify.queryVdu(cloudInfo, instanceId);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void deleteVduTest() throws MsoException {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("id");
+ expected.setVduInstanceName("id");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.DELETING);
+ status.setLastAction(new PluginAction("deleting", null, null));
+ expected.setStatus(status);
+
+ CloudInfo cloudInfo = new CloudInfo();
+ cloudInfo.setCloudSiteId("cloudSiteId");
+ cloudInfo.setTenantId("tenantId");
+ String instanceId = "instanceId";
+ int timeoutMinutes = 1;
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.CREATED)
+ .withLastAction("deleting").build();
+ MsoCloudifyUtils cloudify = Mockito.spy(MsoCloudifyUtils.class);
+ doReturn(deploymentInfo).when(cloudify).uninstallAndDeleteDeployment(cloudInfo.getCloudSiteId(),
+ cloudInfo.getTenantId(), instanceId, timeoutMinutes);
+
+ VduInstance actual = cloudify.deleteVdu(cloudInfo, instanceId, timeoutMinutes);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void deploymentInfoToVduInstanceTest() {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("id");
+ expected.setVduInstanceName("id");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.DELETING);
+ status.setLastAction(new PluginAction("deleting", null, null));
+ expected.setStatus(status);
+
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.CREATED)
+ .withLastAction("deleting").build();
+
+ MsoCloudifyUtils cloudify = new MsoCloudifyUtils();
+
+ VduInstance actual = cloudify.deploymentInfoToVduInstance(deploymentInfo);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void deploymentStatusToVduStatusTest() {
+ VduStatus expected = new VduStatus();
+ expected.setState(VduStateType.DELETING);
+ expected.setLastAction(new PluginAction("deleting", null, null));
+
+ DeploymentInfo deploymentInfo = new DeploymentInfoBuilder().withId("id").withStatus(DeploymentStatus.CREATED)
+ .withLastAction("deleting").build();
+
+ MsoCloudifyUtils cloudify = new MsoCloudifyUtils();
+
+ VduStatus actual = cloudify.deploymentStatusToVduStatus(deploymentInfo);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void getAzureConfigTest() {
+ AzureConfig expected = new AzureConfig();
+ expected.setSubscriptionId("subscriptionId");
+ expected.setTenantId("tenantId");
+ expected.setClientId("msoId");
+ expected.setClientSecret("msoPass");
+
+ MsoCloudifyUtils cloudify = new MsoCloudifyUtils();
+ CloudSite cloudSite = Mockito.mock(CloudSite.class);
+ CloudIdentity cloudIdentity = Mockito.mock(CloudIdentity.class);
+ when(cloudSite.getIdentityService()).thenReturn(cloudIdentity);
+ when(cloudIdentity.getAdminTenant()).thenReturn("subscriptionId");
+ when(cloudIdentity.getMsoId()).thenReturn("msoId");
+ when(cloudIdentity.getMsoPass()).thenReturn("msoPass");
+ String tenantId = "tenantId";
+ AzureConfig actual = cloudify.getAzureConfig(cloudSite, tenantId);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void uploadBlueprintSuccessful() throws MsoException {
+ // given
+ MsoCloudifyUtils testedObjectSpy = spy(MsoCloudifyUtils.class);
+ testedObjectSpy.cloudConfig = mock(CloudConfig.class);
+ Map<String, byte[]> blueprints = new HashMap<>();
+
+ mockCloudConfig(testedObjectSpy);
+ doReturn(true).when(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME),
+ eq(blueprints));
+ // when
+ testedObjectSpy.uploadBlueprint(CLOUD_SITE_ID, BLUEPRINT_ID, FILE_NAME, blueprints, true);
+ // then
+ verify(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME), eq(blueprints));
+ }
+
+ @Test
+ public void uploadBlueprint_exceptionThrown_blueprintExists() throws MsoException {
+ // given
+ MsoCloudifyUtils testedObjectSpy = spy(MsoCloudifyUtils.class);
+ testedObjectSpy.cloudConfig = mock(CloudConfig.class);
+ Map<String, byte[]> blueprints = new HashMap<>();
+
+ mockCloudConfig(testedObjectSpy);
+ doReturn(false).when(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME),
+ eq(blueprints));
+ // when
+ try {
+ testedObjectSpy.uploadBlueprint(CLOUD_SITE_ID, BLUEPRINT_ID, FILE_NAME, blueprints, true);
+ // then
+ fail("MsoAdapterException should be thrown");
+ } catch (MsoAdapterException e) {
+ Assert.assertEquals(e.getMessage(), "Blueprint already exists");
+ }
+ verify(testedObjectSpy).uploadBlueprint(any(Cloudify.class), eq(BLUEPRINT_ID), eq(FILE_NAME), eq(blueprints));
+ }
+
+ @Test
+ public void convertInputValueTest() throws JsonParseException, JsonMappingException, IOException {
+ MsoCloudifyUtils utils = new MsoCloudifyUtils();
+ ObjectMapper mapper = new ObjectMapper();
+ HeatTemplateParam paramNum = new HeatTemplateParam();
+ paramNum.setParamType("number");
+ paramNum.setParamName("my-number");
+
+ HeatTemplateParam paramString = new HeatTemplateParam();
+ paramString.setParamType("string");
+ paramString.setParamName("my-string");
+
+ HeatTemplateParam paramJson = new HeatTemplateParam();
+ paramJson.setParamType("json");
+ paramJson.setParamName("my-json");
+
+ HeatTemplateParam paramJsonEscaped = new HeatTemplateParam();
+ paramJsonEscaped.setParamType("json");
+ paramJsonEscaped.setParamName("my-json-escaped");
+
+ Map<String, Object> jsonMap =
+ mapper.readValue(getJson("free-form.json"), new TypeReference<Map<String, Object>>() {});
+
+ assertEquals(3, utils.convertInputValue("3", paramNum));
+ assertEquals("hello", utils.convertInputValue("hello", paramString));
+ assertTrue("expect no change in type", utils.convertInputValue(jsonMap, paramJson) instanceof Map);
+ assertTrue("expect string to become jsonNode",
+ utils.convertInputValue(getJson("free-form.json"), paramJsonEscaped) instanceof JsonNode);
+
+ JSONAssert.assertEquals(getJson("free-form.json"),
+ mapper.writeValueAsString(utils.convertInputValue(getJson("free-form.json"), paramJsonEscaped)), false);
+
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/MsoHeatUtils/" + filename)));
+ }
+
+ private void mockCloudConfig(MsoCloudifyUtils testedObjectSpy) {
+ CloudifyManager cloudifyManager = createCloudifyManager();
+ when(testedObjectSpy.cloudConfig.getCloudSite(CLOUD_SITE_ID)).thenReturn(Optional.of(createCloudSite()));
+ when(testedObjectSpy.cloudConfig.getCloudifyManager(CLOUD_SITE_ID)).thenReturn(cloudifyManager);
+ }
+
+ private CloudifyManager createCloudifyManager() {
+ CloudifyManager cloudifyManager = new CloudifyManager();
+ cloudifyManager.setCloudifyUrl("cloudUrlTest");
+ cloudifyManager.setPassword("546573746F736973546573746F736973");
+ return cloudifyManager;
+ }
+
+ private CloudSite createCloudSite() {
+ CloudSite cloudSite = new CloudSite();
+ cloudSite.setCloudifyId(CLOUD_SITE_ID);
+ return cloudSite;
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java
index 1884b3243a..870b4d98f2 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/config/PoConfigTest.java
@@ -28,15 +28,15 @@ import org.springframework.beans.factory.annotation.Autowired;
public class PoConfigTest extends BaseTest {
-
- @Autowired
- private PoConfig poConfig;
-
-
- @Test
- public void tenantConfigValues() {
- assertEquals("504", poConfig.getRetryCodes());
- assertEquals(5, poConfig.getRetryDelay());
-
- }
+
+ @Autowired
+ private PoConfig poConfig;
+
+
+ @Test
+ public void tenantConfigValues() {
+ assertEquals("504", poConfig.getRetryCodes());
+ assertEquals(5, poConfig.getRetryDelay());
+
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java
index b675f4814d..f8d07250f5 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/HeatCacheEntryTest.java
@@ -23,43 +23,41 @@ package org.onap.so.openstack.beans;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
import java.util.Calendar;
import java.util.GregorianCalendar;
-
import org.junit.Test;
import org.onap.so.BaseTest;
public class HeatCacheEntryTest {
-
- private static final String HEAT_URL = "testHeatUrl";
- private static final String TOKEN = "testToken";
- @Test
- public void getHeatClientTest() {
- Calendar expires = new GregorianCalendar(2013,0,31);
- HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
- assertNotNull(heatCacheEntry.getHeatClient());
- }
-
- @Test
- public void isExpiredTrueTest() {
- Calendar expires = new GregorianCalendar(2013,0,31);
- HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
- assertTrue(heatCacheEntry.isExpired());
- }
-
- @Test
- public void isExpiredFalseTest() {
- Calendar expires = new GregorianCalendar(2100,0,31);
- HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
- assertFalse(heatCacheEntry.isExpired());
- }
-
- @Test
- public void isExpiredNullTest() {
- Calendar expires = null;
- HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
- assertTrue(heatCacheEntry.isExpired());
- }
+ private static final String HEAT_URL = "testHeatUrl";
+ private static final String TOKEN = "testToken";
+
+ @Test
+ public void getHeatClientTest() {
+ Calendar expires = new GregorianCalendar(2013, 0, 31);
+ HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
+ assertNotNull(heatCacheEntry.getHeatClient());
+ }
+
+ @Test
+ public void isExpiredTrueTest() {
+ Calendar expires = new GregorianCalendar(2013, 0, 31);
+ HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
+ assertTrue(heatCacheEntry.isExpired());
+ }
+
+ @Test
+ public void isExpiredFalseTest() {
+ Calendar expires = new GregorianCalendar(2100, 0, 31);
+ HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
+ assertFalse(heatCacheEntry.isExpired());
+ }
+
+ @Test
+ public void isExpiredNullTest() {
+ Calendar expires = null;
+ HeatCacheEntry heatCacheEntry = new HeatCacheEntry(HEAT_URL, TOKEN, expires);
+ assertTrue(heatCacheEntry.isExpired());
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java
index 379501f206..ece5b21f19 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/MsoTenantTest.java
@@ -1,42 +1,36 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.openstack.beans;
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Test;
public class MsoTenantTest {
- MsoTenant ms = new MsoTenant();
-
+ MsoTenant ms = new MsoTenant();
+
@Test
public void test() {
- Map<String, String> map = new HashMap<>();
- map.put("id","name");
- ms.setTenantId("tenantId");
- ms.setTenantName("tenantName");
- ms.setMetadata(map);
- assert(ms.getMetadata().equals(map));
- assert(ms.getTenantId().equals("tenantId"));
- assert(ms.getTenantName().equals("tenantName"));
+ Map<String, String> map = new HashMap<>();
+ map.put("id", "name");
+ ms.setTenantId("tenantId");
+ ms.setTenantName("tenantName");
+ ms.setMetadata(map);
+ assert (ms.getMetadata().equals(map));
+ assert (ms.getTenantId().equals("tenantId"));
+ assert (ms.getTenantName().equals("tenantName"));
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java
index 5a5e2bb75e..142007089a 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NetworkRollbackTest.java
@@ -1,22 +1,17 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.openstack.beans;
@@ -34,12 +29,12 @@ public class NetworkRollbackTest {
@InjectMocks
NetworkRollback nr = new NetworkRollback();
-
+
@Test
public void test() {
List<Integer> vlans = new ArrayList();
- vlans.add(1);
- vlans.add(2);
+ vlans.add(1);
+ vlans.add(2);
nr.setCloudId("cloudId");
nr.setModelCustomizationUuid("modelCustomizationUuid");
nr.setNetworkId("networkId");
@@ -52,18 +47,18 @@ public class NetworkRollbackTest {
nr.setNetworkCreated(false);
nr.setVlans(vlans);
nr.setMsoRequest(ms);
- assert(nr.getCloudId().equals("cloudId"));
- assert(nr.getModelCustomizationUuid().equals("modelCustomizationUuid"));
- assert(nr.getNetworkId().equals("networkId"));
- assert(nr.getNetworkName().equals("networkName"));
- assert(nr.getNetworkStackId().equals("networkStackId"));
- assert(nr.getNeutronNetworkId().equals("neutronNetworkId"));
- assert(nr.getPhysicalNetwork().equals("physicalNetwork"));
- assert(nr.getNetworkType().equals("networkType"));
- assert(nr.getTenantId().equals("tenantId"));
- assert(nr.getMsoRequest().equals(ms));
+ assert (nr.getCloudId().equals("cloudId"));
+ assert (nr.getModelCustomizationUuid().equals("modelCustomizationUuid"));
+ assert (nr.getNetworkId().equals("networkId"));
+ assert (nr.getNetworkName().equals("networkName"));
+ assert (nr.getNetworkStackId().equals("networkStackId"));
+ assert (nr.getNeutronNetworkId().equals("neutronNetworkId"));
+ assert (nr.getPhysicalNetwork().equals("physicalNetwork"));
+ assert (nr.getNetworkType().equals("networkType"));
+ assert (nr.getTenantId().equals("tenantId"));
+ assert (nr.getMsoRequest().equals(ms));
assertFalse(nr.getNetworkCreated());
- assert(nr.getVlans().equals(vlans));
- assert(nr.toString()!=null);
+ assert (nr.getVlans().equals(vlans));
+ assert (nr.toString() != null);
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java
index 8626e7d177..2c67431f02 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/NeutronCacheEntryTest.java
@@ -22,36 +22,34 @@ package org.onap.so.openstack.beans;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
import java.util.Calendar;
import java.util.GregorianCalendar;
-
import org.junit.Test;
import org.onap.so.BaseTest;
public class NeutronCacheEntryTest {
-
- private static final String NEUTRON_URL = "testNeutronUrl";
- private static final String TOKEN = "testToken";
-
- @Test
- public void isExpiredTrueTest() {
- Calendar expires = new GregorianCalendar(2013,0,31);
- NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires);
- assertTrue(neutronCacheEntry.isExpired());
- }
-
- @Test
- public void isExpiredFalseTest() {
- Calendar expires = new GregorianCalendar(2100,0,31);
- NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires);
- assertFalse(neutronCacheEntry.isExpired());
- }
-
- @Test
- public void isExpiredNullTest() {
- Calendar expires = null;
- NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires);
- assertTrue(neutronCacheEntry.isExpired());
- }
+
+ private static final String NEUTRON_URL = "testNeutronUrl";
+ private static final String TOKEN = "testToken";
+
+ @Test
+ public void isExpiredTrueTest() {
+ Calendar expires = new GregorianCalendar(2013, 0, 31);
+ NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires);
+ assertTrue(neutronCacheEntry.isExpired());
+ }
+
+ @Test
+ public void isExpiredFalseTest() {
+ Calendar expires = new GregorianCalendar(2100, 0, 31);
+ NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires);
+ assertFalse(neutronCacheEntry.isExpired());
+ }
+
+ @Test
+ public void isExpiredNullTest() {
+ Calendar expires = null;
+ NeutronCacheEntry neutronCacheEntry = new NeutronCacheEntry(NEUTRON_URL, TOKEN, expires);
+ assertTrue(neutronCacheEntry.isExpired());
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java
index ac194ccee2..9c2ed66318 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/OpenstackBeansPojoTest.java
@@ -30,18 +30,15 @@ import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
public class OpenstackBeansPojoTest {
- @Test
- public void pojoStructure() {
- test(PojoClassFactory.getPojoClass(VnfRollback.class));
- test(PojoClassFactory.getPojoClass(NeutronCacheEntry.class));
- test(PojoClassFactory.getPojoClass(HeatCacheEntry.class));
- }
-
- private void test(PojoClass pojoClass) {
- Validator validator = ValidatorBuilder.create()
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
- validator.validate(pojoClass);
- }
+ @Test
+ public void pojoStructure() {
+ test(PojoClassFactory.getPojoClass(VnfRollback.class));
+ test(PojoClassFactory.getPojoClass(NeutronCacheEntry.class));
+ test(PojoClassFactory.getPojoClass(HeatCacheEntry.class));
+ }
+
+ private void test(PojoClass pojoClass) {
+ Validator validator = ValidatorBuilder.create().with(new SetterTester()).with(new GetterTester()).build();
+ validator.validate(pojoClass);
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java
index 444a9a8e94..f3614c1b09 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/beans/VnfRollbackTest.java
@@ -21,73 +21,73 @@
package org.onap.so.openstack.beans;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.BaseTest;
import org.onap.so.entity.MsoRequest;
import org.springframework.beans.factory.annotation.Autowired;
public class VnfRollbackTest extends BaseTest {
- @Autowired
- private VnfRollback vnfRollback;
-
- private String vnfId = "testVnfId";
- private String tenantId = "testTenantId";
- private String cloudOwner = "testCloudOwner";
- private String cloudSiteId = "testCloudSiteId";
- private boolean tenantCreated = true;
- private boolean vnfCreated = true;
- private MsoRequest msoRequest = new MsoRequest();
- private String volumeGroupName = "testVolumeGroupName";
- private String volumeGroupId = "testVolumeGroupId";
- private String requestType = "testRequestType";
- private String modelCustomizationUuid = "testModelCustimizationUuid";
- private String orchestrationMode = "testOrchestrationMode";
- private static final String VNF_ROLLBACK_STRING = "VnfRollback: cloud=testCloudSiteId, cloudOwner=testCloudOwner, tenant=testTenantId, vnf=testVnfId, "
- + "tenantCreated=true, vnfCreated=true, requestType = testRequestType, modelCustomizationUuid=testModelCustimizationUuid, mode=testOrchestrationMode";
-
- @Test
- public void VnfRollbackInstantiationTest() {
- vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated,
- msoRequest, volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid);
-
- assertEquals(vnfId, vnfRollback.getVnfId());
- assertEquals(tenantId, vnfRollback.getTenantId());
- assertEquals(cloudOwner, vnfRollback.getCloudOwner());
- assertEquals(cloudSiteId, vnfRollback.getCloudSiteId());
- assertEquals(tenantCreated, vnfRollback.getTenantCreated());
- assertEquals(vnfCreated, vnfRollback.getVnfCreated());
- assertEquals(msoRequest, vnfRollback.getMsoRequest());
- assertEquals(volumeGroupName, vnfRollback.getVolumeGroupName());
- assertEquals(volumeGroupId, vnfRollback.getVolumeGroupId());
- assertEquals(requestType, vnfRollback.getRequestType());
- assertEquals(modelCustomizationUuid, vnfRollback.getModelCustomizationUuid());
- }
-
- @Test
- public void VnfRollbackInstantiationOrchestrationModeTest() {
- vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated,
- msoRequest, volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid, orchestrationMode);
-
- assertEquals(vnfId, vnfRollback.getVnfId());
- assertEquals(tenantId, vnfRollback.getTenantId());
- assertEquals(cloudOwner, vnfRollback.getCloudOwner());
- assertEquals(cloudSiteId, vnfRollback.getCloudSiteId());
- assertEquals(tenantCreated, vnfRollback.getTenantCreated());
- assertEquals(vnfCreated, vnfRollback.getVnfCreated());
- assertEquals(msoRequest, vnfRollback.getMsoRequest());
- assertEquals(volumeGroupName, vnfRollback.getVolumeGroupName());
- assertEquals(volumeGroupId, vnfRollback.getVolumeGroupId());
- assertEquals(requestType, vnfRollback.getRequestType());
- assertEquals(modelCustomizationUuid, vnfRollback.getModelCustomizationUuid());
- assertEquals(orchestrationMode, vnfRollback.getMode());
- }
-
- @Test
- public void toStringTest() {
- vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated,
- msoRequest, volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid, orchestrationMode);
-
- assertEquals(VNF_ROLLBACK_STRING, vnfRollback.toString());
- }
+ @Autowired
+ private VnfRollback vnfRollback;
+
+ private String vnfId = "testVnfId";
+ private String tenantId = "testTenantId";
+ private String cloudOwner = "testCloudOwner";
+ private String cloudSiteId = "testCloudSiteId";
+ private boolean tenantCreated = true;
+ private boolean vnfCreated = true;
+ private MsoRequest msoRequest = new MsoRequest();
+ private String volumeGroupName = "testVolumeGroupName";
+ private String volumeGroupId = "testVolumeGroupId";
+ private String requestType = "testRequestType";
+ private String modelCustomizationUuid = "testModelCustimizationUuid";
+ private String orchestrationMode = "testOrchestrationMode";
+ private static final String VNF_ROLLBACK_STRING =
+ "VnfRollback: cloud=testCloudSiteId, cloudOwner=testCloudOwner, tenant=testTenantId, vnf=testVnfId, "
+ + "tenantCreated=true, vnfCreated=true, requestType = testRequestType, modelCustomizationUuid=testModelCustimizationUuid, mode=testOrchestrationMode";
+
+ @Test
+ public void VnfRollbackInstantiationTest() {
+ vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated, msoRequest,
+ volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid);
+
+ assertEquals(vnfId, vnfRollback.getVnfId());
+ assertEquals(tenantId, vnfRollback.getTenantId());
+ assertEquals(cloudOwner, vnfRollback.getCloudOwner());
+ assertEquals(cloudSiteId, vnfRollback.getCloudSiteId());
+ assertEquals(tenantCreated, vnfRollback.getTenantCreated());
+ assertEquals(vnfCreated, vnfRollback.getVnfCreated());
+ assertEquals(msoRequest, vnfRollback.getMsoRequest());
+ assertEquals(volumeGroupName, vnfRollback.getVolumeGroupName());
+ assertEquals(volumeGroupId, vnfRollback.getVolumeGroupId());
+ assertEquals(requestType, vnfRollback.getRequestType());
+ assertEquals(modelCustomizationUuid, vnfRollback.getModelCustomizationUuid());
+ }
+
+ @Test
+ public void VnfRollbackInstantiationOrchestrationModeTest() {
+ vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated, msoRequest,
+ volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid, orchestrationMode);
+
+ assertEquals(vnfId, vnfRollback.getVnfId());
+ assertEquals(tenantId, vnfRollback.getTenantId());
+ assertEquals(cloudOwner, vnfRollback.getCloudOwner());
+ assertEquals(cloudSiteId, vnfRollback.getCloudSiteId());
+ assertEquals(tenantCreated, vnfRollback.getTenantCreated());
+ assertEquals(vnfCreated, vnfRollback.getVnfCreated());
+ assertEquals(msoRequest, vnfRollback.getMsoRequest());
+ assertEquals(volumeGroupName, vnfRollback.getVolumeGroupName());
+ assertEquals(volumeGroupId, vnfRollback.getVolumeGroupId());
+ assertEquals(requestType, vnfRollback.getRequestType());
+ assertEquals(modelCustomizationUuid, vnfRollback.getModelCustomizationUuid());
+ assertEquals(orchestrationMode, vnfRollback.getMode());
+ }
+
+ @Test
+ public void toStringTest() {
+ vnfRollback = new VnfRollback(vnfId, tenantId, cloudOwner, cloudSiteId, tenantCreated, vnfCreated, msoRequest,
+ volumeGroupName, volumeGroupId, requestType, modelCustomizationUuid, orchestrationMode);
+
+ assertEquals(VNF_ROLLBACK_STRING, vnfRollback.toString());
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java
index dbce712cb0..5cf7c86522 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java
@@ -27,10 +27,8 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
-
import java.io.File;
import java.io.IOException;
-
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -42,7 +40,6 @@ import org.onap.so.openstack.exceptions.MsoIOException;
import org.onap.so.openstack.exceptions.MsoOpenstackException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -59,149 +56,150 @@ import com.woorea.openstack.quantum.model.NeutronError;
* This class implements test methods of the MsoCommonUtils
*/
public class MsoCommonUtilsTest extends BaseTest {
- @Autowired
- @Qualifier("CommonUtils")
- private MsoCommonUtils commonUtils;
-
- @Mock
- private OpenStackRequest openstackRequest;
-
- @Test
+ @Autowired
+ @Qualifier("CommonUtils")
+ private MsoCommonUtils commonUtils;
+
+ @Mock
+ private OpenStackRequest openstackRequest;
+
+ @Test
public final void testExecuteAndRecordOpenstackRequest() {
- Mockito.when(openstackRequest.endpoint()).thenReturn("localhost");
- Mockito.when(openstackRequest.path()).thenReturn("/test");
- //TODO:Must try a real connection
- assertNull(commonUtils.executeAndRecordOpenstackRequest (openstackRequest));
- }
-
- @Test
- public void testexecuteAndRecordOpenstackRequestResponseException() {
- expectedException.expect(OpenStackResponseException.class);
-
- doThrow(OpenStackResponseException.class).when(openstackRequest).execute();
-
- commonUtils.executeAndRecordOpenstackRequest(openstackRequest);
- }
-
- @Test
- public void testexecuteAndRecordOpenstackRequestConnectException() {
- expectedException.expect(OpenStackConnectException.class);
-
- doThrow(OpenStackConnectException.class).when(openstackRequest).execute();
-
- commonUtils.executeAndRecordOpenstackRequest(openstackRequest);
- }
-
- @Test
+ Mockito.when(openstackRequest.endpoint()).thenReturn("localhost");
+ Mockito.when(openstackRequest.path()).thenReturn("/test");
+ // TODO:Must try a real connection
+ assertNull(commonUtils.executeAndRecordOpenstackRequest(openstackRequest));
+ }
+
+ @Test
+ public void testexecuteAndRecordOpenstackRequestResponseException() {
+ expectedException.expect(OpenStackResponseException.class);
+
+ doThrow(OpenStackResponseException.class).when(openstackRequest).execute();
+
+ commonUtils.executeAndRecordOpenstackRequest(openstackRequest);
+ }
+
+ @Test
+ public void testexecuteAndRecordOpenstackRequestConnectException() {
+ expectedException.expect(OpenStackConnectException.class);
+
+ doThrow(OpenStackConnectException.class).when(openstackRequest).execute();
+
+ commonUtils.executeAndRecordOpenstackRequest(openstackRequest);
+ }
+
+ @Test
public final void testKeystoneErrorToMsoException() throws JsonParseException, JsonMappingException, IOException {
- OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
-
- OpenStackBaseException openStackResponseException = new OpenStackResponseException("response",1);
-
- MsoException me = commonUtils.keystoneErrorToMsoException(openStackConnectException,"ContextError");
-
- assertTrue(me instanceof MsoIOException);
- assertTrue("connect".equals(me.getMessage()));
-
-
- MsoException me2 = commonUtils.keystoneErrorToMsoException(openStackResponseException,"ContextError");
- assertTrue(me2 instanceof MsoOpenstackException);
- assertTrue("ContextError".equals(me2.getContext()));
- assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
-
-
- OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
- Error error = mapper.readValue(new File(RESOURCE_PATH + "Error.json"), Error.class);
-
- doReturn(error).when(openStackResponse).getErrorEntity(eq(Error.class));
-
- openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
-
- MsoException me3 = commonUtils.keystoneErrorToMsoException(openStackResponseException,"ContextError");
-
- assertTrue(me3 instanceof MsoOpenstackException);
- assertEquals("1 title: message", me3.toString());
- }
-
- @Test
- public final void testHeatExceptionToMsoException() throws JsonParseException, JsonMappingException, IOException {
- OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
-
- OpenStackBaseException openStackResponseException = new OpenStackResponseException("response",1);
-
- MsoException me = commonUtils.heatExceptionToMsoException(openStackConnectException,"ContextError");
-
- assertTrue(me instanceof MsoIOException);
- assertTrue("connect".equals(me.getMessage()));
-
-
- MsoException me2 = commonUtils.heatExceptionToMsoException(openStackResponseException,"ContextError");
- assertTrue(me2 instanceof MsoOpenstackException);
- assertTrue("ContextError".equals(me2.getContext()));
- assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
-
-
- OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
- Explanation explanation = mapper.readValue(new File(RESOURCE_PATH + "Explanation.json"), Explanation.class);
-
- doReturn(explanation).when(openStackResponse).getErrorEntity(eq(Explanation.class));
-
- openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
-
- MsoException me3 = commonUtils.heatExceptionToMsoException(openStackResponseException,"ContextError");
-
- assertTrue(me3 instanceof MsoOpenstackException);
- assertEquals("1 title: explanation, error.type=null, error.message=null", me3.toString());
- }
-
- @Test
- public final void testNeutronExceptionToMsoException() throws JsonParseException, JsonMappingException, IOException {
- OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
-
- OpenStackBaseException openStackResponseException = new OpenStackResponseException("response",1);
-
- MsoException me = commonUtils.neutronExceptionToMsoException(openStackConnectException,"ContextError");
-
- assertTrue(me instanceof MsoIOException);
- assertTrue("connect".equals(me.getMessage()));
-
- MsoException me2 = commonUtils.neutronExceptionToMsoException(openStackResponseException,"ContextError");
- assertTrue(me2 instanceof MsoOpenstackException);
- assertTrue("ContextError".equals(me2.getContext()));
- assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
-
-
- OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
- NeutronError explanation = mapper.readValue(new File(RESOURCE_PATH + "NeutronError.json"), NeutronError.class);
-
- doReturn(explanation).when(openStackResponse).getErrorEntity(eq(NeutronError.class));
-
- openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
-
- MsoException me3 = commonUtils.neutronExceptionToMsoException(openStackResponseException,"ContextError");
-
- assertTrue(me3 instanceof MsoOpenstackException);
- assertEquals("501 type: message", me3.toString());
- }
-
- @Test
- public final void testRuntimeExceptionToMsoException() {
- RuntimeException re = new RuntimeException("runtime");
- MsoException me = commonUtils.runtimeExceptionToMsoException(re, "ContextError");
-
- assertTrue(me instanceof MsoAdapterException);
- assertTrue("ContextError".equals(me.getContext()));
+ OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
+
+ OpenStackBaseException openStackResponseException = new OpenStackResponseException("response", 1);
+
+ MsoException me = commonUtils.keystoneErrorToMsoException(openStackConnectException, "ContextError");
+
+ assertTrue(me instanceof MsoIOException);
+ assertTrue("connect".equals(me.getMessage()));
+
+
+ MsoException me2 = commonUtils.keystoneErrorToMsoException(openStackResponseException, "ContextError");
+ assertTrue(me2 instanceof MsoOpenstackException);
+ assertTrue("ContextError".equals(me2.getContext()));
+ assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
+
+
+ OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
+ Error error = mapper.readValue(new File(RESOURCE_PATH + "Error.json"), Error.class);
+
+ doReturn(error).when(openStackResponse).getErrorEntity(eq(Error.class));
+
+ openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
+
+ MsoException me3 = commonUtils.keystoneErrorToMsoException(openStackResponseException, "ContextError");
+
+ assertTrue(me3 instanceof MsoOpenstackException);
+ assertEquals("1 title: message", me3.toString());
+ }
+
+ @Test
+ public final void testHeatExceptionToMsoException() throws JsonParseException, JsonMappingException, IOException {
+ OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
+
+ OpenStackBaseException openStackResponseException = new OpenStackResponseException("response", 1);
+
+ MsoException me = commonUtils.heatExceptionToMsoException(openStackConnectException, "ContextError");
+
+ assertTrue(me instanceof MsoIOException);
+ assertTrue("connect".equals(me.getMessage()));
+
+
+ MsoException me2 = commonUtils.heatExceptionToMsoException(openStackResponseException, "ContextError");
+ assertTrue(me2 instanceof MsoOpenstackException);
+ assertTrue("ContextError".equals(me2.getContext()));
+ assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
+
+
+ OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
+ Explanation explanation = mapper.readValue(new File(RESOURCE_PATH + "Explanation.json"), Explanation.class);
+
+ doReturn(explanation).when(openStackResponse).getErrorEntity(eq(Explanation.class));
+
+ openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
+
+ MsoException me3 = commonUtils.heatExceptionToMsoException(openStackResponseException, "ContextError");
+
+ assertTrue(me3 instanceof MsoOpenstackException);
+ assertEquals("1 title: explanation, error.type=null, error.message=null", me3.toString());
+ }
+
+ @Test
+ public final void testNeutronExceptionToMsoException()
+ throws JsonParseException, JsonMappingException, IOException {
+ OpenStackBaseException openStackConnectException = new OpenStackConnectException("connect");
+
+ OpenStackBaseException openStackResponseException = new OpenStackResponseException("response", 1);
+
+ MsoException me = commonUtils.neutronExceptionToMsoException(openStackConnectException, "ContextError");
+
+ assertTrue(me instanceof MsoIOException);
+ assertTrue("connect".equals(me.getMessage()));
+
+ MsoException me2 = commonUtils.neutronExceptionToMsoException(openStackResponseException, "ContextError");
+ assertTrue(me2 instanceof MsoOpenstackException);
+ assertTrue("ContextError".equals(me2.getContext()));
+ assertTrue(MsoExceptionCategory.OPENSTACK.equals(me2.getCategory()));
+
+
+ OpenStackResponse openStackResponse = Mockito.mock(OpenStackResponse.class);
+ NeutronError explanation = mapper.readValue(new File(RESOURCE_PATH + "NeutronError.json"), NeutronError.class);
+
+ doReturn(explanation).when(openStackResponse).getErrorEntity(eq(NeutronError.class));
+
+ openStackResponseException = new OpenStackResponseException("response", 501, openStackResponse);
+
+ MsoException me3 = commonUtils.neutronExceptionToMsoException(openStackResponseException, "ContextError");
+
+ assertTrue(me3 instanceof MsoOpenstackException);
+ assertEquals("501 type: message", me3.toString());
+ }
+
+ @Test
+ public final void testRuntimeExceptionToMsoException() {
+ RuntimeException re = new RuntimeException("runtime");
+ MsoException me = commonUtils.runtimeExceptionToMsoException(re, "ContextError");
+
+ assertTrue(me instanceof MsoAdapterException);
+ assertTrue("ContextError".equals(me.getContext()));
assertTrue(MsoExceptionCategory.INTERNAL.equals(me.getCategory()));
- }
-
- @Test
- public void testIoExceptionToMsoException() {
- IOException exception = new IOException("IOExceptionTestMessage");
-
- MsoException msoException = commonUtils.ioExceptionToMsoException(exception, "ContextError");
-
- assertTrue(msoException instanceof MsoAdapterException);
- assertEquals("ContextError", msoException.getContext());
- assertTrue(MsoExceptionCategory.INTERNAL.equals(msoException.getCategory()));
- }
+ }
+
+ @Test
+ public void testIoExceptionToMsoException() {
+ IOException exception = new IOException("IOExceptionTestMessage");
+
+ MsoException msoException = commonUtils.ioExceptionToMsoException(exception, "ContextError");
+
+ assertTrue(msoException instanceof MsoAdapterException);
+ assertEquals("ContextError", msoException.getContext());
+ assertTrue(MsoExceptionCategory.INTERNAL.equals(msoException.getCategory()));
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java
index 700d03dad3..1b98f14e8c 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntryTest.java
@@ -25,16 +25,13 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
-
import org.junit.Test;
import org.onap.so.TestDataSetup;
import org.onap.so.db.catalog.beans.HeatTemplateParam;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -43,8 +40,8 @@ public class MsoHeatEnvironmentEntryTest extends TestDataSetup {
private static final String PARAMETER_NAME = "keyTest";
private static final String VALUE_NAME = "valueTest";
private static final String NOT_EXISTING_PARAM = "notExistingParam";
- private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY = "parameters: {"
- + PARAMETER_NAME + ": " + VALUE_NAME + "}";
+ private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY =
+ "parameters: {" + PARAMETER_NAME + ": " + VALUE_NAME + "}";
private static final String RAW_ENTRY_WITH_RESOURCE_REGISTRY = "resource_registry: resourceTest";
private static final String RAW_ENTRY_INVALID = "invalidRawEntry";
@@ -57,13 +54,15 @@ public class MsoHeatEnvironmentEntryTest extends TestDataSetup {
}
@Test
- public void toFullString_ResourceRegistryNotPresentInRawEntry() throws JsonParseException, JsonMappingException, IOException {
+ public void toFullString_ResourceRegistryNotPresentInRawEntry()
+ throws JsonParseException, JsonMappingException, IOException {
StringBuilder sb = new StringBuilder(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY);
-
+
MsoHeatEnvironmentEntry testedObject = new MsoHeatEnvironmentEntry(sb);
-
- HeatTemplateParam heatTemplateParam = mapper.readValue(new File(RESOURCE_PATH + "HeatTemplateParam.json"), HeatTemplateParam.class);
-
+
+ HeatTemplateParam heatTemplateParam =
+ mapper.readValue(new File(RESOURCE_PATH + "HeatTemplateParam.json"), HeatTemplateParam.class);
+
assertThat(testedObject.getRawEntry()).isEqualTo(sb);
assertThat(testedObject.isValid()).isTrue();
assertThat(testedObject.containsParameter(PARAMETER_NAME)).isTrue();
@@ -71,18 +70,22 @@ public class MsoHeatEnvironmentEntryTest extends TestDataSetup {
assertTrue(testedObject.containsParameter(PARAMETER_NAME, "dummyAlias"));
assertTrue(testedObject.containsParameter("dummyName", PARAMETER_NAME));
assertFalse(testedObject.containsParameter("dummyName", "dummyAlias"));
- assertEquals("parameters:\n " + PARAMETER_NAME + ": " + VALUE_NAME + "\n\n\n", testedObject.toFullString().toString());
- assertEquals("parameters:\n " + PARAMETER_NAME + ": " + VALUE_NAME + "\n\n\n", testedObject.toFullStringExcludeNonParams(new HashSet<HeatTemplateParam>(Arrays.asList(heatTemplateParam))).toString());
+ assertEquals("parameters:\n " + PARAMETER_NAME + ": " + VALUE_NAME + "\n\n\n",
+ testedObject.toFullString().toString());
+ assertEquals("parameters:\n " + PARAMETER_NAME + ": " + VALUE_NAME + "\n\n\n",
+ testedObject
+ .toFullStringExcludeNonParams(new HashSet<HeatTemplateParam>(Arrays.asList(heatTemplateParam)))
+ .toString());
assertEquals(1, testedObject.getNumberOfParameters());
assertFalse(testedObject.hasResources());
-
+
MsoHeatEnvironmentResource heatResource = new MsoHeatEnvironmentResource("resourceName", "resourceValue");
MsoHeatEnvironmentParameter heatParameter = new MsoHeatEnvironmentParameter("parameterName", "parameterValue");
testedObject.addResource(heatResource);
testedObject.addParameter(heatParameter);
assertEquals(1, testedObject.getNumberOfResources());
assertEquals(2, testedObject.getNumberOfParameters());
-
+
testedObject.setResources(null);
testedObject.setParameters(null);
assertNull(testedObject.getParameters());
@@ -91,7 +94,7 @@ public class MsoHeatEnvironmentEntryTest extends TestDataSetup {
@Test
public void toFullString_ExceptionOccurred() {
- StringBuilder sb = new StringBuilder(RAW_ENTRY_INVALID);
+ StringBuilder sb = new StringBuilder(RAW_ENTRY_INVALID);
MsoHeatEnvironmentEntry testedObject = new MsoHeatEnvironmentEntry(sb);
assertThat(testedObject.getRawEntry()).isEqualTo(sb);
assertThat(testedObject.isValid()).isFalse();
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java
index 182a6d0e02..954f237ffe 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentParameterTest.java
@@ -1,46 +1,40 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.openstack.utils;
import static org.mockito.Mockito.mock;
-
import org.junit.Test;
public class MsoHeatEnvironmentParameterTest {
- @Test
- public void test() {
- MsoHeatEnvironmentParameter hep=mock(MsoHeatEnvironmentParameter.class);
- Object op=hep.getName();
- MsoHeatEnvironmentParameter meo=new MsoHeatEnvironmentParameter();
- MsoHeatEnvironmentParameter mea=new MsoHeatEnvironmentParameter("name");
- MsoHeatEnvironmentParameter mep=new MsoHeatEnvironmentParameter("name"," value");
- mea.setName("name");
- mep.setValue("value");
- assert(mea.getName().equals("name"));
- assert(mep.getValue().equals("value"));
- assert(meo.toString()!=null);
- //assertTrue(op.equals(hep));
- meo.equals(op);
- meo.hashCode();
- }
+ @Test
+ public void test() {
+ MsoHeatEnvironmentParameter hep = mock(MsoHeatEnvironmentParameter.class);
+ Object op = hep.getName();
+ MsoHeatEnvironmentParameter meo = new MsoHeatEnvironmentParameter();
+ MsoHeatEnvironmentParameter mea = new MsoHeatEnvironmentParameter("name");
+ MsoHeatEnvironmentParameter mep = new MsoHeatEnvironmentParameter("name", " value");
+ mea.setName("name");
+ mep.setValue("value");
+ assert (mea.getName().equals("name"));
+ assert (mep.getValue().equals("value"));
+ assert (meo.toString() != null);
+ // assertTrue(op.equals(hep));
+ meo.equals(op);
+ meo.hashCode();
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java
index 934c149055..2c67dfd009 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResourceTest.java
@@ -1,49 +1,43 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.openstack.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
import org.junit.Test;
public class MsoHeatEnvironmentResourceTest {
- @Test
- public void test() {
- Object op = true;
+ @Test
+ public void test() {
+ Object op = true;
+
+ MsoHeatEnvironmentResource mre = new MsoHeatEnvironmentResource("name");
+ MsoHeatEnvironmentResource mae = new MsoHeatEnvironmentResource("name", "maeValue");
+ MsoHeatEnvironmentResource msoHER = new MsoHeatEnvironmentResource();
- MsoHeatEnvironmentResource mre = new MsoHeatEnvironmentResource("name");
- MsoHeatEnvironmentResource mae = new MsoHeatEnvironmentResource("name", "maeValue");
- MsoHeatEnvironmentResource msoHER = new MsoHeatEnvironmentResource();
-
- msoHER.setName("msoHERName");
- msoHER.setValue("msoHERValue");
+ msoHER.setName("msoHERName");
+ msoHER.setValue("msoHERValue");
- assertEquals("name", mre.getName());
- assertEquals("maeValue", mae.getValue());
- assertEquals("\"msoHERName\": msoHERValue", msoHER.toString());
- assertEquals("\"name\": maeValue", mae.toString());
- assertFalse(mae.equals(op));
- assertTrue(mae.equals(mre));
- assertEquals("name".hashCode(), mae.hashCode());
- }
+ assertEquals("name", mre.getName());
+ assertEquals("maeValue", mae.getValue());
+ assertEquals("\"msoHERName\": msoHERValue", msoHER.toString());
+ assertEquals("\"name\": maeValue", mae.toString());
+ assertFalse(mae.equals(op));
+ assertTrue(mae.equals(mre));
+ assertEquals("name".hashCode(), mae.hashCode());
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java
index 925365f00e..3f5402cc99 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java
@@ -28,13 +28,11 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertNotNull;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.apache.http.HttpStatus;
import org.junit.Assert;
import org.junit.Test;
@@ -56,142 +54,142 @@ import org.onap.so.openstack.exceptions.MsoException;
import org.onap.so.openstack.exceptions.MsoIOException;
import org.onap.so.openstack.exceptions.MsoOpenstackException;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.woorea.openstack.heat.Heat;
import com.woorea.openstack.heat.model.CreateStackParam;
-public class MsoHeatUtilsTest extends BaseTest{
-
- @Autowired
- private MsoHeatUtils heatUtils;
-
- @Test
- public void instantiateVduTest() throws MsoException, IOException {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b");
- expected.setVduInstanceName("name");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.INSTANTIATED);
- status.setLastAction((new PluginAction("create", "complete", null)));
- expected.setStatus(status);
-
- CloudInfo cloudInfo = new CloudInfo();
- cloudInfo.setCloudSiteId("MTN13");
- cloudInfo.setTenantId("tenantId");
- VduModelInfo vduModel = new VduModelInfo();
- vduModel.setModelCustomizationUUID("blueprintId");
- vduModel.setTimeoutMinutes(1);
- VduArtifact artifact = new VduArtifact();
- artifact.setName("name");
- artifact.setType(ArtifactType.MAIN_TEMPLATE);
- byte[] content = new byte[1];
- artifact.setContent(content);
- List<VduArtifact> artifacts = new ArrayList<>();
- artifacts.add(artifact);
- vduModel.setArtifacts(artifacts);
- Map<String, byte[]> blueprintFiles = new HashMap<>();
- blueprintFiles.put(artifact.getName(), artifact.getContent());
- String instanceName = "instanceName";
- Map<String, Object> inputs = new HashMap<>();
- boolean rollbackOnFailure = true;
-
- StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json");
-
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceName/stackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_StackId.json")
- .withStatus(HttpStatus.SC_OK)));
-
- VduInstance actual = heatUtils.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
-
- @Test
- public void queryVduTest() throws Exception {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b");
- expected.setVduInstanceName("name");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.INSTANTIATED);
- status.setLastAction((new PluginAction("create", "complete",null)));
- expected.setStatus(status);
-
- CloudInfo cloudInfo = new CloudInfo();
- cloudInfo.setCloudSiteId("mtn13");
- cloudInfo.setTenantId("tenantId");
- String instanceId = "instanceId";
-
- StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json");
-
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_StackId.json")
- .withStatus(HttpStatus.SC_OK)));
-
- VduInstance actual = heatUtils.queryVdu(cloudInfo, instanceId);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void deleteVduTest() throws Exception {
- VduInstance expected = new VduInstance();
- expected.setVduInstanceId("instanceId");
- expected.setVduInstanceName("instanceId");
- VduStatus status = new VduStatus();
- status.setState(VduStateType.DELETED);
- expected.setStatus(status);
-
- CloudInfo cloudInfo = new CloudInfo();
- cloudInfo.setCloudSiteId("mtn13");
- cloudInfo.setTenantId("tenantId");
- String instanceId = "instanceId";
-
- int timeoutInMinutes = 1;
-
- StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId")).willReturn(aResponse().withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK)));
- StubOpenStack.mockOpenStackDelete(wireMockServer, "name/da886914-efb2-4917-b335-c8381528d90b");
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/name/da886914-efb2-4917-b335-c8381528d90b")).willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_DeleteComplete.json").withStatus(HttpStatus.SC_OK)));
-
- VduInstance actual = heatUtils.deleteVdu(cloudInfo, instanceId, timeoutInMinutes);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public final void requestToStringBuilderTest() {
- CreateStackParam param = new CreateStackParam();
- param.setDisableRollback(false);
- param.setEnvironment("environment");
- param.setFiles(new HashMap<String, Object>());
- param.setParameters(new HashMap<>());
- param.setStackName("stackName");
- param.setTemplate("template");
- param.setTemplateUrl("http://templateUrl");
- param.setTimeoutMinutes(1);
-
- StringBuilder stringBuilder = heatUtils.requestToStringBuilder(param);
-
- Assert.assertTrue(stringBuilder.toString().contains("StackName:"));
- }
-
- @Test
- public final void copyBaseOutputsToInputsTest() {
- Map<String, Object> inputs = new HashMap<>();
- inputs.put("str1", "str");
- Map<String, Object> otherStackOutputs = new HashMap<>();
- otherStackOutputs.put("str", "str");
- List<String> paramNames = new ArrayList<>();
- Map<String, String> aliases = new HashMap<>();
- aliases.put("str", "str");
- heatUtils.copyBaseOutputsToInputs(inputs, otherStackOutputs, null, aliases);
- Assert.assertEquals("str",otherStackOutputs.get("str"));
- }
+public class MsoHeatUtilsTest extends BaseTest {
+
+ @Autowired
+ private MsoHeatUtils heatUtils;
+
+ @Test
+ public void instantiateVduTest() throws MsoException, IOException {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b");
+ expected.setVduInstanceName("name");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.INSTANTIATED);
+ status.setLastAction((new PluginAction("create", "complete", null)));
+ expected.setStatus(status);
+
+ CloudInfo cloudInfo = new CloudInfo();
+ cloudInfo.setCloudSiteId("MTN13");
+ cloudInfo.setTenantId("tenantId");
+ VduModelInfo vduModel = new VduModelInfo();
+ vduModel.setModelCustomizationUUID("blueprintId");
+ vduModel.setTimeoutMinutes(1);
+ VduArtifact artifact = new VduArtifact();
+ artifact.setName("name");
+ artifact.setType(ArtifactType.MAIN_TEMPLATE);
+ byte[] content = new byte[1];
+ artifact.setContent(content);
+ List<VduArtifact> artifacts = new ArrayList<>();
+ artifacts.add(artifact);
+ vduModel.setArtifacts(artifacts);
+ Map<String, byte[]> blueprintFiles = new HashMap<>();
+ blueprintFiles.put(artifact.getName(), artifact.getContent());
+ String instanceName = "instanceName";
+ Map<String, Object> inputs = new HashMap<>();
+ boolean rollbackOnFailure = true;
+
+ StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json");
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceName/stackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK)));
+
+ VduInstance actual = heatUtils.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+
+ @Test
+ public void queryVduTest() throws Exception {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b");
+ expected.setVduInstanceName("name");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.INSTANTIATED);
+ status.setLastAction((new PluginAction("create", "complete", null)));
+ expected.setStatus(status);
+
+ CloudInfo cloudInfo = new CloudInfo();
+ cloudInfo.setCloudSiteId("mtn13");
+ cloudInfo.setTenantId("tenantId");
+ String instanceId = "instanceId";
+
+ StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json");
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK)));
+
+ VduInstance actual = heatUtils.queryVdu(cloudInfo, instanceId);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void deleteVduTest() throws Exception {
+ VduInstance expected = new VduInstance();
+ expected.setVduInstanceId("instanceId");
+ expected.setVduInstanceName("instanceId");
+ VduStatus status = new VduStatus();
+ status.setState(VduStateType.DELETED);
+ expected.setStatus(status);
+
+ CloudInfo cloudInfo = new CloudInfo();
+ cloudInfo.setCloudSiteId("mtn13");
+ cloudInfo.setTenantId("tenantId");
+ String instanceId = "instanceId";
+
+ int timeoutInMinutes = 1;
+
+ StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId"))
+ .willReturn(aResponse().withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK)));
+ StubOpenStack.mockOpenStackDelete(wireMockServer, "name/da886914-efb2-4917-b335-c8381528d90b");
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/name/da886914-efb2-4917-b335-c8381528d90b"))
+ .willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_DeleteComplete.json")
+ .withStatus(HttpStatus.SC_OK)));
+
+ VduInstance actual = heatUtils.deleteVdu(cloudInfo, instanceId, timeoutInMinutes);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public final void requestToStringBuilderTest() {
+ CreateStackParam param = new CreateStackParam();
+ param.setDisableRollback(false);
+ param.setEnvironment("environment");
+ param.setFiles(new HashMap<String, Object>());
+ param.setParameters(new HashMap<>());
+ param.setStackName("stackName");
+ param.setTemplate("template");
+ param.setTemplateUrl("http://templateUrl");
+ param.setTimeoutMinutes(1);
+
+ StringBuilder stringBuilder = heatUtils.requestToStringBuilder(param);
+
+ Assert.assertTrue(stringBuilder.toString().contains("StackName:"));
+ }
+
+ @Test
+ public final void copyBaseOutputsToInputsTest() {
+ Map<String, Object> inputs = new HashMap<>();
+ inputs.put("str1", "str");
+ Map<String, Object> otherStackOutputs = new HashMap<>();
+ otherStackOutputs.put("str", "str");
+ List<String> paramNames = new ArrayList<>();
+ Map<String, String> aliases = new HashMap<>();
+ aliases.put("str", "str");
+ heatUtils.copyBaseOutputsToInputs(inputs, otherStackOutputs, null, aliases);
+ Assert.assertEquals("str", otherStackOutputs.get("str"));
+ }
@Test
public final void getHeatClientSuccessTest() throws MsoException, IOException {
@@ -231,8 +229,7 @@ public class MsoHeatUtilsTest extends BaseTest{
StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json");
StubOpenStack.mockOpenStackGet(wireMockServer, "TEST-stack/stackId");
StackInfo stackInfo = heatUtils.createStack(cloudSite.getId(), "CloudOwner", "tenantId", "TEST-stack", null,
- "TEST-heat", new HashMap<>(), false, 1, "TEST-env",
- new HashMap<>(), new HashMap<>(), false);
+ "TEST-heat", new HashMap<>(), false, 1, "TEST-env", new HashMap<>(), new HashMap<>(), false);
assertNotNull(stackInfo);
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java
index 9edc805cf3..7a48dc092a 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsUnitTest.java
@@ -23,7 +23,6 @@ package org.onap.so.openstack.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
@@ -33,12 +32,10 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import org.junit.Test;
import org.onap.so.db.catalog.beans.HeatTemplate;
import org.onap.so.db.catalog.beans.HeatTemplateParam;
import org.skyscreamer.jsonassert.JSONAssert;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -47,150 +44,153 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class MsoHeatUtilsUnitTest {
-
- private ObjectMapper mapper = new ObjectMapper();
- @Test
- public void convertInputMapTest() throws JsonParseException, JsonMappingException, IOException {
- MsoHeatUtils utils = new MsoHeatUtils();
-
- Map<String, Object> input = new HashMap<>();
- HeatTemplate template = new HeatTemplate();
- template.setArtifactUuid("my-uuid");
- Set<HeatTemplateParam> parameters = template.getParameters();
- HeatTemplateParam paramNum = new HeatTemplateParam();
- paramNum.setParamType("number");
- paramNum.setParamName("my-number");
- input.put("my-number", "3");
-
- HeatTemplateParam paramString = new HeatTemplateParam();
- paramString.setParamType("string");
- paramString.setParamName("my-string");
- input.put("my-string", "hello");
-
- HeatTemplateParam paramJson = new HeatTemplateParam();
- paramJson.setParamType("json");
- paramJson.setParamName("my-json");
-
- HeatTemplateParam paramJsonEscaped = new HeatTemplateParam();
- paramJsonEscaped.setParamType("json");
- paramJsonEscaped.setParamName("my-json-escaped");
-
- Map<String, Object> jsonMap = mapper.readValue(getJson("free-form.json"), new TypeReference<Map<String, Object>>(){});
- input.put("my-json", jsonMap);
-
- input.put("my-json-escaped", getJson("free-form.json"));
-
- parameters.add(paramNum);
- parameters.add(paramString);
- parameters.add(paramJson);
- parameters.add(paramJsonEscaped);
-
- Map<String, Object> output = utils.convertInputMap(input, template);
-
- assertEquals(3, output.get("my-number"));
- assertEquals("hello", output.get("my-string"));
- assertTrue("expect no change in type", output.get("my-json") instanceof Map);
- assertTrue("expect string to become jsonNode", output.get("my-json-escaped") instanceof JsonNode);
-
- JSONAssert.assertEquals(getJson("free-form.json"), mapper.writeValueAsString(output.get("my-json-escaped")), false);
- }
-
- @Test
- public final void convertInputMapValuesTest() {
- MsoHeatUtils utils = new MsoHeatUtils();
- Map<String, Object> inputs = new HashMap<>();
- Set<HeatTemplateParam> params = new HashSet<>();
- HeatTemplate ht = new HeatTemplate();
- HeatTemplateParam htp = new HeatTemplateParam();
- htp.setParamName("vnf_name");
- htp.setParamType("string");
- params.add(htp);
- inputs.put("vnf_name", "a_vnf_name");
- htp = new HeatTemplateParam();
- htp.setParamName("image_size");
- htp.setParamType("number");
- params.add(htp);
- inputs.put("image_size", "1024");
- htp = new HeatTemplateParam();
- htp.setParamName("external");
- htp.setParamType("boolean");
- params.add(htp);
- inputs.put("external", "false");
- htp = new HeatTemplateParam();
- htp.setParamName("oam_ips");
- htp.setParamType("comma_delimited_list");
- params.add(htp);
- inputs.put("oam_ips", "a,b");
- htp = new HeatTemplateParam();
- htp.setParamName("oam_prefixes");
- htp.setParamType("json");
- params.add(htp);
- String jsonEscInput = "[{\"prefix\": \"aValue\"}, {\"prefix\": \"aValue2\"}]";
- inputs.put("oam_prefixes", jsonEscInput);
- ht.setParameters(params);
-
- Map<String, Object> output = utils.convertInputMap(inputs, ht);
-
- assertEquals("a_vnf_name", output.get("vnf_name"));
- assertEquals(1024, output.get("image_size"));
- assertEquals(false, output.get("external"));
- List<String> cdl = new ArrayList<>();
- cdl.add(0, "a");
- cdl.add(1, "b");
- assertEquals(cdl, output.get("oam_ips"));
- ObjectMapper JSON_MAPPER = new ObjectMapper();
- JsonNode jn = null;
- try {
- jn = JSON_MAPPER.readTree(jsonEscInput);
- } catch (Exception e) {
- }
- assertEquals(jn, output.get("oam_prefixes"));
- }
-
- @Test
- public final void convertInputMapNullsTest() {
- MsoHeatUtils utils = new MsoHeatUtils();
- Map<String, Object> inputs = new HashMap<>();
- Set<HeatTemplateParam> params = new HashSet<>();
- HeatTemplate ht = new HeatTemplate();
- HeatTemplateParam htp = new HeatTemplateParam();
- htp.setParamName("vnf_name");
- htp.setParamType("string");
- params.add(htp);
- inputs.put("vnf_name", null);
- htp = new HeatTemplateParam();
- htp.setParamName("image_size");
- htp.setParamType("number");
- params.add(htp);
- inputs.put("image_size", null);
- htp = new HeatTemplateParam();
- htp.setParamName("external");
- htp.setParamType("boolean");
- params.add(htp);
- inputs.put("external", null);
- htp = new HeatTemplateParam();
- htp.setParamName("oam_ips");
- htp.setParamType("comma_delimited_list");
- params.add(htp);
- inputs.put("oam_ips", null);
- htp = new HeatTemplateParam();
- htp.setParamName("oam_prefixes");
- htp.setParamType("json");
- params.add(htp);
- inputs.put("oam_prefixes", null);
- ht.setParameters(params);
-
- Map<String, Object> output = utils.convertInputMap(inputs, ht);
-
- assertNull(output.get("vnf_name"));
- assertNull(output.get("image_size"));
- assertEquals(false, output.get("external"));
- assertNull(output.get("oam_ips"));
- assertNull(output.get("oam_prefixes"));
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/MsoHeatUtils/" + filename)));
- }
-
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ public void convertInputMapTest() throws JsonParseException, JsonMappingException, IOException {
+ MsoHeatUtils utils = new MsoHeatUtils();
+
+ Map<String, Object> input = new HashMap<>();
+ HeatTemplate template = new HeatTemplate();
+ template.setArtifactUuid("my-uuid");
+ Set<HeatTemplateParam> parameters = template.getParameters();
+ HeatTemplateParam paramNum = new HeatTemplateParam();
+ paramNum.setParamType("number");
+ paramNum.setParamName("my-number");
+ input.put("my-number", "3");
+
+ HeatTemplateParam paramString = new HeatTemplateParam();
+ paramString.setParamType("string");
+ paramString.setParamName("my-string");
+ input.put("my-string", "hello");
+
+ HeatTemplateParam paramJson = new HeatTemplateParam();
+ paramJson.setParamType("json");
+ paramJson.setParamName("my-json");
+
+ HeatTemplateParam paramJsonEscaped = new HeatTemplateParam();
+ paramJsonEscaped.setParamType("json");
+ paramJsonEscaped.setParamName("my-json-escaped");
+
+ Map<String, Object> jsonMap =
+ mapper.readValue(getJson("free-form.json"), new TypeReference<Map<String, Object>>() {});
+ input.put("my-json", jsonMap);
+
+ input.put("my-json-escaped", getJson("free-form.json"));
+
+ parameters.add(paramNum);
+ parameters.add(paramString);
+ parameters.add(paramJson);
+ parameters.add(paramJsonEscaped);
+
+ Map<String, Object> output = utils.convertInputMap(input, template);
+
+ assertEquals(3, output.get("my-number"));
+ assertEquals("hello", output.get("my-string"));
+ assertTrue("expect no change in type", output.get("my-json") instanceof Map);
+ assertTrue("expect string to become jsonNode", output.get("my-json-escaped") instanceof JsonNode);
+
+ JSONAssert.assertEquals(getJson("free-form.json"), mapper.writeValueAsString(output.get("my-json-escaped")),
+ false);
+ }
+
+ @Test
+ public final void convertInputMapValuesTest() {
+ MsoHeatUtils utils = new MsoHeatUtils();
+ Map<String, Object> inputs = new HashMap<>();
+ Set<HeatTemplateParam> params = new HashSet<>();
+ HeatTemplate ht = new HeatTemplate();
+ HeatTemplateParam htp = new HeatTemplateParam();
+ htp.setParamName("vnf_name");
+ htp.setParamType("string");
+ params.add(htp);
+ inputs.put("vnf_name", "a_vnf_name");
+ htp = new HeatTemplateParam();
+ htp.setParamName("image_size");
+ htp.setParamType("number");
+ params.add(htp);
+ inputs.put("image_size", "1024");
+ htp = new HeatTemplateParam();
+ htp.setParamName("external");
+ htp.setParamType("boolean");
+ params.add(htp);
+ inputs.put("external", "false");
+ htp = new HeatTemplateParam();
+ htp.setParamName("oam_ips");
+ htp.setParamType("comma_delimited_list");
+ params.add(htp);
+ inputs.put("oam_ips", "a,b");
+ htp = new HeatTemplateParam();
+ htp.setParamName("oam_prefixes");
+ htp.setParamType("json");
+ params.add(htp);
+ String jsonEscInput = "[{\"prefix\": \"aValue\"}, {\"prefix\": \"aValue2\"}]";
+ inputs.put("oam_prefixes", jsonEscInput);
+ ht.setParameters(params);
+
+ Map<String, Object> output = utils.convertInputMap(inputs, ht);
+
+ assertEquals("a_vnf_name", output.get("vnf_name"));
+ assertEquals(1024, output.get("image_size"));
+ assertEquals(false, output.get("external"));
+ List<String> cdl = new ArrayList<>();
+ cdl.add(0, "a");
+ cdl.add(1, "b");
+ assertEquals(cdl, output.get("oam_ips"));
+ ObjectMapper JSON_MAPPER = new ObjectMapper();
+ JsonNode jn = null;
+ try {
+ jn = JSON_MAPPER.readTree(jsonEscInput);
+ } catch (Exception e) {
+ }
+ assertEquals(jn, output.get("oam_prefixes"));
+ }
+
+ @Test
+ public final void convertInputMapNullsTest() {
+ MsoHeatUtils utils = new MsoHeatUtils();
+ Map<String, Object> inputs = new HashMap<>();
+ Set<HeatTemplateParam> params = new HashSet<>();
+ HeatTemplate ht = new HeatTemplate();
+ HeatTemplateParam htp = new HeatTemplateParam();
+ htp.setParamName("vnf_name");
+ htp.setParamType("string");
+ params.add(htp);
+ inputs.put("vnf_name", null);
+ htp = new HeatTemplateParam();
+ htp.setParamName("image_size");
+ htp.setParamType("number");
+ params.add(htp);
+ inputs.put("image_size", null);
+ htp = new HeatTemplateParam();
+ htp.setParamName("external");
+ htp.setParamType("boolean");
+ params.add(htp);
+ inputs.put("external", null);
+ htp = new HeatTemplateParam();
+ htp.setParamName("oam_ips");
+ htp.setParamType("comma_delimited_list");
+ params.add(htp);
+ inputs.put("oam_ips", null);
+ htp = new HeatTemplateParam();
+ htp.setParamName("oam_prefixes");
+ htp.setParamType("json");
+ params.add(htp);
+ inputs.put("oam_prefixes", null);
+ ht.setParameters(params);
+
+ Map<String, Object> output = utils.convertInputMap(inputs, ht);
+
+ assertNull(output.get("vnf_name"));
+ assertNull(output.get("image_size"));
+ assertEquals(false, output.get("external"));
+ assertNull(output.get("oam_ips"));
+ assertNull(output.get("oam_prefixes"));
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get("src/test/resources/__files/MsoHeatUtils/" + filename)));
+ }
+
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java
index 5691d9cd69..8951f8a304 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java
@@ -26,13 +26,11 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
-
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -48,7 +46,6 @@ import org.onap.so.openstack.beans.HeatStatus;
import org.onap.so.openstack.beans.StackInfo;
import org.onap.so.openstack.exceptions.MsoException;
import org.springframework.core.env.Environment;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.woorea.openstack.base.client.OpenStackRequest;
@@ -57,109 +54,110 @@ import com.woorea.openstack.heat.model.Stack;
@RunWith(MockitoJUnitRunner.class)
public class MsoHeatUtilsWithUpdateTest extends TestDataSetup {
- @Mock
- private CloudConfig cloudConfig;
-
- @Mock
- private Environment environment;
-
- @Spy
- @InjectMocks
- private MsoHeatUtilsWithUpdate heatUtils;
-
+ @Mock
+ private CloudConfig cloudConfig;
+
+ @Mock
+ private Environment environment;
+
+ @Spy
+ @InjectMocks
+ private MsoHeatUtilsWithUpdate heatUtils;
+
private String cloudOwner;
- private String cloudSiteId;
- private String tenantId;
- private String stackName;
- private String heatTemplate;
- private Map<String, Object> stackInputs;
- private boolean pollForCompletion;
- private int timeoutMinutes;
-
- @Before
- public void before() {
- MockitoAnnotations.initMocks(this);
-
+ private String cloudSiteId;
+ private String tenantId;
+ private String stackName;
+ private String heatTemplate;
+ private Map<String, Object> stackInputs;
+ private boolean pollForCompletion;
+ private int timeoutMinutes;
+
+ @Before
+ public void before() {
+ MockitoAnnotations.initMocks(this);
+
cloudOwner = "cloudOwner";
- cloudSiteId = "cloudSiteId";
- tenantId = "tenantId";
- stackName = "stackName";
- heatTemplate = "heatTemplate";
- stackInputs = new HashMap<>();
- pollForCompletion = true;
- timeoutMinutes = 0;
- }
-
- @Test
- public void updateStackTest() throws MsoException, JsonParseException, JsonMappingException, IOException {
- CloudSite cloudSite = new CloudSite();
- Heat heatClient = new Heat("endpoint");
- Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class);
- Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class);
-
- StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null);
- expectedStackInfo.setCanonicalName("stackName/id");
-
- doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class));
- doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class));
- doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class));
- doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class));
- doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class));
-
- StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName,
- heatTemplate, stackInputs, pollForCompletion, timeoutMinutes);
-
- assertThat(actualStackInfo, sameBeanAs(expectedStackInfo));
- }
-
- @Test
- public void updateStackWithEnvironmentTest() throws JsonParseException, JsonMappingException, IOException, MsoException {
- String environmentString = "environmentString";
-
- CloudSite cloudSite = new CloudSite();
- Heat heatClient = new Heat("endpoint");
- Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class);
- Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class);
-
- StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null);
- expectedStackInfo.setCanonicalName("stackName/id");
-
- doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class));
- doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class));
-
- doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class));
- doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class));
- doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class));
-
- StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName,
- heatTemplate, stackInputs, pollForCompletion, timeoutMinutes, environmentString);
-
- assertThat(actualStackInfo, sameBeanAs(expectedStackInfo));
- }
-
- @Test
- public void updateStackWithFilesTest() throws MsoException, JsonParseException, JsonMappingException, IOException {
- String environmentString = "environmentString";
- Map<String, Object> files = new HashMap<>();
- files.put("file1", new Object());
-
- CloudSite cloudSite = new CloudSite();
- Heat heatClient = new Heat("endpoint");
- Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class);
- Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class);
-
- StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null);
- expectedStackInfo.setCanonicalName("stackName/id");
-
- doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class));
- doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class));
- doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class));
- doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class));
- doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class));
-
- StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName,
- heatTemplate, stackInputs, pollForCompletion, timeoutMinutes , environmentString, files);
-
- assertThat(actualStackInfo, sameBeanAs(expectedStackInfo));
- }
+ cloudSiteId = "cloudSiteId";
+ tenantId = "tenantId";
+ stackName = "stackName";
+ heatTemplate = "heatTemplate";
+ stackInputs = new HashMap<>();
+ pollForCompletion = true;
+ timeoutMinutes = 0;
+ }
+
+ @Test
+ public void updateStackTest() throws MsoException, JsonParseException, JsonMappingException, IOException {
+ CloudSite cloudSite = new CloudSite();
+ Heat heatClient = new Heat("endpoint");
+ Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class);
+ Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class);
+
+ StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null);
+ expectedStackInfo.setCanonicalName("stackName/id");
+
+ doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class));
+ doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class));
+ doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class));
+ doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class));
+ doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class));
+
+ StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate,
+ stackInputs, pollForCompletion, timeoutMinutes);
+
+ assertThat(actualStackInfo, sameBeanAs(expectedStackInfo));
+ }
+
+ @Test
+ public void updateStackWithEnvironmentTest()
+ throws JsonParseException, JsonMappingException, IOException, MsoException {
+ String environmentString = "environmentString";
+
+ CloudSite cloudSite = new CloudSite();
+ Heat heatClient = new Heat("endpoint");
+ Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class);
+ Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class);
+
+ StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null);
+ expectedStackInfo.setCanonicalName("stackName/id");
+
+ doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class));
+ doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class));
+
+ doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class));
+ doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class));
+ doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class));
+
+ StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate,
+ stackInputs, pollForCompletion, timeoutMinutes, environmentString);
+
+ assertThat(actualStackInfo, sameBeanAs(expectedStackInfo));
+ }
+
+ @Test
+ public void updateStackWithFilesTest() throws MsoException, JsonParseException, JsonMappingException, IOException {
+ String environmentString = "environmentString";
+ Map<String, Object> files = new HashMap<>();
+ files.put("file1", new Object());
+
+ CloudSite cloudSite = new CloudSite();
+ Heat heatClient = new Heat("endpoint");
+ Stack heatStack = mapper.readValue(new File(RESOURCE_PATH + "HeatStack.json"), Stack.class);
+ Stack updateStack = mapper.readValue(new File(RESOURCE_PATH + "UpdateStack.json"), Stack.class);
+
+ StackInfo expectedStackInfo = new StackInfo("stackName", HeatStatus.UPDATED, "stackStatusReason", null);
+ expectedStackInfo.setCanonicalName("stackName/id");
+
+ doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class));
+ doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class));
+ doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class));
+ doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class));
+ doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class));
+
+ StackInfo actualStackInfo = heatUtils.updateStack(cloudSiteId, cloudOwner, tenantId, stackName, heatTemplate,
+ stackInputs, pollForCompletion, timeoutMinutes, environmentString, files);
+
+ assertThat(actualStackInfo, sameBeanAs(expectedStackInfo));
+ }
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java
index 3526a68ef6..6ecabfd45a 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoKeystoneUtilsTest.java
@@ -28,7 +28,6 @@ import org.onap.so.BaseTest;
import org.onap.so.openstack.beans.MsoTenant;
import org.onap.so.openstack.exceptions.MsoException;
import org.springframework.beans.factory.annotation.Autowired;
-
import java.io.IOException;
import java.util.HashMap;
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java
index e066c4eec6..0d8f451a6d 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java
@@ -30,11 +30,9 @@ import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
import static org.onap.so.openstack.utils.MsoMulticloudUtils.MULTICLOUD_QUERY_BODY_NULL;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Optional;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Ignore;
@@ -67,43 +65,40 @@ public class MsoMulticloudUtilsTest extends BaseTest {
private CloudConfig cloudConfigMock;
private static final String CREATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": "
- + "\"TEST-workload\", \"template_response\": {\"stack\": {\"id\": \"TEST-stack\", \"links\": []}}}";
- private static final String UPDATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": "
- + "\"TEST-workload\"}";
+ + "\"TEST-workload\", \"template_response\": {\"stack\": {\"id\": \"TEST-stack\", \"links\": []}}}";
+ private static final String UPDATE_STACK_RESPONSE =
+ "{\"template_type\": \"TEST-template\", \"workload_id\": " + "\"TEST-workload\"}";
private static final String GET_CREATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": "
+ "\"TEST-workload\", \"workload_status\": \"CREATE_COMPLETE\"}";
private static final String GET_UPDATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": "
+ "\"TEST-workload\", \"workload_status\": \"UPDATE_COMPLETE\"}";
private static final String MULTICLOUD_CREATE_PATH = "/api/multicloud/v1/CloudOwner/MTN14/infra_workload";
- private static final String MULTICLOUD_UPDATE_PATH = "/api/multicloud/v1/CloudOwner/MTN14/infra_workload/TEST-workload";
- private static final String MULTICLOUD_GET_PATH = "/api/multicloud/v1/CloudOwner/MTN14/infra_workload/TEST-workload";
+ private static final String MULTICLOUD_UPDATE_PATH =
+ "/api/multicloud/v1/CloudOwner/MTN14/infra_workload/TEST-workload";
+ private static final String MULTICLOUD_GET_PATH =
+ "/api/multicloud/v1/CloudOwner/MTN14/infra_workload/TEST-workload";
@Test
public void createStackSuccess() throws MsoException, IOException {
- wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).inScenario("CREATE")
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(CREATE_STACK_RESPONSE)
- .withStatus(HttpStatus.SC_CREATED))
- .willSetStateTo("CREATING"));
- wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH))
- .inScenario("CREATE").whenScenarioStateIs("CREATING")
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(GET_CREATE_STACK_RESPONSE)
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_UPDATE_PATH)).inScenario("CREATE")
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(UPDATE_STACK_RESPONSE)
- .withStatus(HttpStatus.SC_ACCEPTED))
+ wireMockServer
+ .stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).inScenario("CREATE")
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(CREATE_STACK_RESPONSE).withStatus(HttpStatus.SC_CREATED))
+ .willSetStateTo("CREATING"));
+ wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH)).inScenario("CREATE")
+ .whenScenarioStateIs("CREATING").willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(GET_CREATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_UPDATE_PATH))
+ .inScenario("CREATE").willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_ACCEPTED))
.willSetStateTo("UPDATING"));
- wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH))
- .inScenario("CREATE").whenScenarioStateIs("UPDATING")
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(GET_UPDATE_STACK_RESPONSE)
- .withStatus(HttpStatus.SC_OK)));
- StackInfo result = multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(),
- "TEST-heat", new HashMap<>(), true, 200, "TEST-env",
- new HashMap<>(), new HashMap<>(), false);
+ wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH)).inScenario("CREATE")
+ .whenScenarioStateIs("UPDATING").willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(GET_UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK)));
+ StackInfo result =
+ multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(),
+ "TEST-heat", new HashMap<>(), true, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false);
wireMockServer.resetScenarios();
assertNotNull(result);
assertEquals("TEST-stack", result.getName());
@@ -125,9 +120,8 @@ public class MsoMulticloudUtilsTest extends BaseTest {
@Test
public void queryStackWithNullMulticloudQueryBody() throws MsoException {
wireMockServer.stubFor(get(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/instanceId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(CREATE_STACK_RESPONSE)
- .withStatus(HttpStatus.SC_OK)));
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(CREATE_STACK_RESPONSE)
+ .withStatus(HttpStatus.SC_OK)));
StackInfo result = multicloudUtils.queryStack("MTN13", "CloudOwner", "TEST-tenant", "instanceId");
assertTrue(HeatStatus.FAILED == result.getStatus());
@@ -136,8 +130,7 @@ public class MsoMulticloudUtilsTest extends BaseTest {
@Test(expected = VduException.class)
public void updateVdu() throws MsoException {
- multicloudUtils.updateVdu(new CloudInfo(), "instanceId", new HashMap<>(), new VduModelInfo(),
- false);
+ multicloudUtils.updateVdu(new CloudInfo(), "instanceId", new HashMap<>(), new VduModelInfo(), false);
}
@Test
@@ -148,17 +141,16 @@ public class MsoMulticloudUtilsTest extends BaseTest {
assertTrue(VduStateType.DELETED == vduInstance.getStatus().getState());
}
- @Ignore @Test
+ @Ignore
+ @Test
public void createStackMulticloudClientIsNull() {
try {
multicloudUtilsMock.cloudConfig = cloudConfigMock;
CloudSite cloudSite = new CloudSite();
cloudSite.setIdentityService(new CloudIdentity());
- when(cloudConfigMock.getCloudSite("MTN13")).
- thenReturn(Optional.of(cloudSite));
+ when(cloudConfigMock.getCloudSite("MTN13")).thenReturn(Optional.of(cloudSite));
multicloudUtilsMock.createStack("MNT14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(),
- "TEST-heat", new HashMap<>(), false, 200, "TEST-env",
- new HashMap<>(), new HashMap<>(), false);
+ "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false);
} catch (MsoException e) {
assertEquals("0 : Multicloud client could not be initialized", e.toString());
return;
@@ -169,12 +161,10 @@ public class MsoMulticloudUtilsTest extends BaseTest {
@Test
public void createStackBadRequest() {
try {
- wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_BAD_REQUEST)));
+ wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_BAD_REQUEST)));
multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(),
- "TEST-heat", new HashMap<>(), false, 200, "TEST-env",
- new HashMap<>(), new HashMap<>(), false);
+ "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false);
} catch (MsoException e) {
assertEquals("0 : Bad Request", e.toString());
return;
@@ -184,12 +174,11 @@ public class MsoMulticloudUtilsTest extends BaseTest {
@Test
public void createStackEmptyResponseEntity() throws MsoException {
- wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_CREATED)));
- StackInfo result = multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(),
- "TEST-heat", new HashMap<>(), false, 200, "TEST-env",
- new HashMap<>(), new HashMap<>(), false);
+ wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_CREATED)));
+ StackInfo result =
+ multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(),
+ "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false);
assertNotNull(result);
assertEquals("TEST-stack/", result.getName());
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java
index 8c337865df..56cdb128aa 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoNeutronUtilsTest.java
@@ -28,61 +28,63 @@ import org.onap.so.BaseTest;
import org.onap.so.openstack.beans.NetworkInfo;
import org.onap.so.openstack.exceptions.MsoException;
import org.springframework.beans.factory.annotation.Autowired;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-public class MsoNeutronUtilsTest extends BaseTest{
-
+public class MsoNeutronUtilsTest extends BaseTest {
+
@Autowired
private MsoNeutronUtils msoNeutronUtils;
private List<Integer> vlans;
-
+
@Before
public void before() throws IOException {
vlans = new ArrayList<>();
vlans.add(3014);
StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort);
}
-
+
@Test
public void createNetworkTest_OpenStackBaseException() throws Exception {
expectedException.expect(MsoException.class);
- msoNeutronUtils.createNetwork("MTN13", "tenantId",
- MsoNeutronUtils.NetworkType.PROVIDER,"networkName", "PROVIDER", vlans);
+ msoNeutronUtils.createNetwork("MTN13", "tenantId", MsoNeutronUtils.NetworkType.PROVIDER, "networkName",
+ "PROVIDER", vlans);
}
@Test
public void createNetworkTest_NetworkTypeAsMultiProvider() throws Exception {
StubOpenStack.mockOpenstackPostNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json");
NetworkInfo networkInfo = msoNeutronUtils.createNetwork("MTN13", "tenantId",
- MsoNeutronUtils.NetworkType.MULTI_PROVIDER,"networkName","PROVIDER", vlans);
+ MsoNeutronUtils.NetworkType.MULTI_PROVIDER, "networkName", "PROVIDER", vlans);
- Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9",networkInfo.getId());
+ Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9", networkInfo.getId());
}
@Test
public void createNetworkTest() throws Exception {
StubOpenStack.mockOpenstackPostNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json");
NetworkInfo networkInfo = msoNeutronUtils.createNetwork("MTN13", "tenantId",
- MsoNeutronUtils.NetworkType.PROVIDER,"networkName","PROVIDER", vlans);
+ MsoNeutronUtils.NetworkType.PROVIDER, "networkName", "PROVIDER", vlans);
- Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9",networkInfo.getId());
+ Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9", networkInfo.getId());
}
@Test
public void queryNetworkTest() throws Exception {
- StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
- NetworkInfo networkInfo = msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId","MTN13");
+ StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
+ NetworkInfo networkInfo =
+ msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId", "MTN13");
- Assert.assertEquals("net1",networkInfo.getName());
+ Assert.assertEquals("net1", networkInfo.getName());
}
@Test
public void queryNetworkTest_404() throws Exception {
- NetworkInfo networkInfo = msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId","MTN13");
+ NetworkInfo networkInfo =
+ msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId", "MTN13");
Assert.assertNull(networkInfo);
}
@@ -90,36 +92,41 @@ public class MsoNeutronUtilsTest extends BaseTest{
public void queryNetworkTest_500() throws Exception {
expectedException.expect(MsoException.class);
StubOpenStack.mockOpenStackGetNeutronNetwork_500(wireMockServer, "43173f6a-d699-414b-888f-ab243dda6dfe");
- msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId","MTN13");
+ msoNeutronUtils.queryNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId", "MTN13");
}
@Test
public void deleteNetworkkTest() throws Exception {
- StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
+ StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
StubOpenStack.mockOpenStackDeleteNeutronNetwork(wireMockServer, "43173f6a-d699-414b-888f-ab243dda6dfe");
- Boolean result = msoNeutronUtils.deleteNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId","MTN13");
+ Boolean result = msoNeutronUtils.deleteNetwork("43173f6a-d699-414b-888f-ab243dda6dfe", "tenantId", "MTN13");
Assert.assertTrue(result);
}
@Test
public void updateNetworkTest() throws Exception {
- StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
- StubOpenStack.mockOpenstackPutNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
+ StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
+ StubOpenStack.mockOpenstackPutNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
NetworkInfo networkInfo = msoNeutronUtils.updateNetwork("MTN13", "tenantId",
- "43173f6a-d699-414b-888f-ab243dda6dfe",MsoNeutronUtils.NetworkType.PROVIDER,"PROVIDER", vlans);
+ "43173f6a-d699-414b-888f-ab243dda6dfe", MsoNeutronUtils.NetworkType.PROVIDER, "PROVIDER", vlans);
- Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9",networkInfo.getId());
+ Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9", networkInfo.getId());
}
@Test
public void updateNetworkTest_NetworkTypeAsMultiProvider() throws Exception {
- StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
- StubOpenStack.mockOpenstackPutNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
+ StubOpenStack.mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
+ StubOpenStack.mockOpenstackPutNetwork(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
NetworkInfo networkInfo = msoNeutronUtils.updateNetwork("MTN13", "tenantId",
- "43173f6a-d699-414b-888f-ab243dda6dfe",MsoNeutronUtils.NetworkType.MULTI_PROVIDER,"PROVIDER", vlans);
+ "43173f6a-d699-414b-888f-ab243dda6dfe", MsoNeutronUtils.NetworkType.MULTI_PROVIDER, "PROVIDER", vlans);
- Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9",networkInfo.getId());
+ Assert.assertEquals("2a4017ef-31ff-496a-9294-e96ecc3bc9c9", networkInfo.getId());
}
}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java
index f2717ab7ce..c9f3a8a8a8 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoTenantUtilsFactoryTest.java
@@ -27,7 +27,6 @@ import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
-
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -59,7 +58,7 @@ public class MsoTenantUtilsFactoryTest {
// WHEN
MsoCloudSiteNotFound msoCloudSiteNotFound = catchThrowableOfType(
- () -> msoTenantUtilsFactory.getTenantUtils(cloudSiteId), MsoCloudSiteNotFound.class);
+ () -> msoTenantUtilsFactory.getTenantUtils(cloudSiteId), MsoCloudSiteNotFound.class);
// THEN
assertThat(msoCloudSiteNotFound.getMessage()).contains(cloudSiteId);
@@ -90,7 +89,7 @@ public class MsoTenantUtilsFactoryTest {
}
private <T extends MsoTenantUtils> void shouldReturnAppropriateUtilsInstanceForGivenServerType(
- ServerType serverType, T expectedInstance) throws MsoCloudSiteNotFound {
+ ServerType serverType, T expectedInstance) throws MsoCloudSiteNotFound {
// GIVEN
String cloudSiteId = "CloudSiteId";
CloudSite cloudSite = mock(CloudSite.class, RETURNS_DEEP_STUBS);
diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java
index 70b5f2699d..90e874fc84 100644
--- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java
+++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvtTest.java
@@ -1,95 +1,90 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.openstack.utils;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertNull;
-
import java.io.File;
import java.io.IOException;
import java.util.Set;
-
import org.junit.Test;
import org.onap.so.TestDataSetup;
import org.onap.so.db.catalog.beans.HeatTemplateParam;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
public class MsoYamlEditorWithEnvtTest extends TestDataSetup {
- private MsoYamlEditorWithEnvt yaml;
+ private MsoYamlEditorWithEnvt yaml;
private static final String PARAMETER_NAME = "keyTest";
private static final String PARAMETER_VALUE = "{type : paramType}";
private static final String RESOURCE_NAME = "resourceKey";
private static final String RESOURCE_VALUE = "resourceValue";
- private static final String RAW_ENTRY_WITH_RESOURCE_REGISTRY = "resource_registry: {" + RESOURCE_NAME + " : " + RESOURCE_VALUE + "}";
- private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY = "parameters: {"
- + PARAMETER_NAME + ": " + PARAMETER_VALUE + "}";
-
- @Test
- public void getParameterListTest() throws JsonParseException, JsonMappingException, IOException {
- yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY.getBytes());
-
- MsoHeatEnvironmentParameter expectedHeatParam = mapper.readValue(new File(RESOURCE_PATH + "HeatEnvironmentParameter.json"), MsoHeatEnvironmentParameter.class);
-
- Set<MsoHeatEnvironmentParameter> heatEnvironmentSet = yaml.getParameterListFromEnvt();
-
- for(MsoHeatEnvironmentParameter heatEnvironment : heatEnvironmentSet) {
- assertThat(heatEnvironment, sameBeanAs(expectedHeatParam));
- }
- }
-
- @Test
- public void getResourceListFromEnvtTest() {
- yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_RESOURCE_REGISTRY.getBytes());
-
- MsoHeatEnvironmentResource expectedHeatResource = new MsoHeatEnvironmentResource(RESOURCE_NAME, RESOURCE_VALUE);
-
- Set<MsoHeatEnvironmentResource> heatResourceSet = yaml.getResourceListFromEnvt();
-
- for(MsoHeatEnvironmentResource heatResource : heatResourceSet) {
- assertThat(heatResource, sameBeanAs(expectedHeatResource));
- }
- }
-
- @Test
- public void getResourceListFromEnvtExceptionTest() {
- yaml = new MsoYamlEditorWithEnvt();
-
- Set<MsoHeatEnvironmentResource> heatResourceSet = yaml.getResourceListFromEnvt();
-
- assertNull(heatResourceSet);
- }
-
- @Test
- public void getParameterListFromEnvtTest() throws JsonParseException, JsonMappingException, IOException {
- yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY.getBytes());
-
- HeatTemplateParam expectedHeatParam = mapper.readValue(new File(RESOURCE_PATH + "HeatTemplateParamExpected.json"), HeatTemplateParam.class);
-
- Set<HeatTemplateParam> heatParamSet = yaml.getParameterList();
-
- for(HeatTemplateParam heatParam : heatParamSet) {
- assertThat(heatParam, sameBeanAs(expectedHeatParam));
- }
- }
+ private static final String RAW_ENTRY_WITH_RESOURCE_REGISTRY =
+ "resource_registry: {" + RESOURCE_NAME + " : " + RESOURCE_VALUE + "}";
+ private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY =
+ "parameters: {" + PARAMETER_NAME + ": " + PARAMETER_VALUE + "}";
+
+ @Test
+ public void getParameterListTest() throws JsonParseException, JsonMappingException, IOException {
+ yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY.getBytes());
+
+ MsoHeatEnvironmentParameter expectedHeatParam = mapper.readValue(
+ new File(RESOURCE_PATH + "HeatEnvironmentParameter.json"), MsoHeatEnvironmentParameter.class);
+
+ Set<MsoHeatEnvironmentParameter> heatEnvironmentSet = yaml.getParameterListFromEnvt();
+
+ for (MsoHeatEnvironmentParameter heatEnvironment : heatEnvironmentSet) {
+ assertThat(heatEnvironment, sameBeanAs(expectedHeatParam));
+ }
+ }
+
+ @Test
+ public void getResourceListFromEnvtTest() {
+ yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_RESOURCE_REGISTRY.getBytes());
+
+ MsoHeatEnvironmentResource expectedHeatResource = new MsoHeatEnvironmentResource(RESOURCE_NAME, RESOURCE_VALUE);
+
+ Set<MsoHeatEnvironmentResource> heatResourceSet = yaml.getResourceListFromEnvt();
+
+ for (MsoHeatEnvironmentResource heatResource : heatResourceSet) {
+ assertThat(heatResource, sameBeanAs(expectedHeatResource));
+ }
+ }
+
+ @Test
+ public void getResourceListFromEnvtExceptionTest() {
+ yaml = new MsoYamlEditorWithEnvt();
+
+ Set<MsoHeatEnvironmentResource> heatResourceSet = yaml.getResourceListFromEnvt();
+
+ assertNull(heatResourceSet);
+ }
+
+ @Test
+ public void getParameterListFromEnvtTest() throws JsonParseException, JsonMappingException, IOException {
+ yaml = new MsoYamlEditorWithEnvt(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY.getBytes());
+
+ HeatTemplateParam expectedHeatParam =
+ mapper.readValue(new File(RESOURCE_PATH + "HeatTemplateParamExpected.json"), HeatTemplateParam.class);
+
+ Set<HeatTemplateParam> heatParamSet = yaml.getParameterList();
+
+ for (HeatTemplateParam heatParam : heatParamSet) {
+ assertThat(heatParam, sameBeanAs(expectedHeatParam));
+ }
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailPolicyRef.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailPolicyRef.java
index f207c6185e..d03246b366 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailPolicyRef.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailPolicyRef.java
@@ -24,22 +24,22 @@ package org.onap.so.adapters.network.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ContrailPolicyRef {
-
- @JsonProperty("network_policy_refs_data_sequence")
- private ContrailPolicyRefSeq seq;
-
-
- public ContrailPolicyRefSeq getSeq() {
- return seq;
- }
-
- public void setSeq(ContrailPolicyRefSeq seq) {
- this.seq = seq;
- }
-
- public ContrailPolicyRef withRefSeq(ContrailPolicyRefSeq seq) {
- this.seq = seq;
- return this;
- }
-
+
+ @JsonProperty("network_policy_refs_data_sequence")
+ private ContrailPolicyRefSeq seq;
+
+
+ public ContrailPolicyRefSeq getSeq() {
+ return seq;
+ }
+
+ public void setSeq(ContrailPolicyRefSeq seq) {
+ this.seq = seq;
+ }
+
+ public ContrailPolicyRef withRefSeq(ContrailPolicyRefSeq seq) {
+ this.seq = seq;
+ return this;
+ }
+
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailPolicyRefSeq.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailPolicyRefSeq.java
index a3a5a710ed..c0ec000874 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailPolicyRefSeq.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailPolicyRefSeq.java
@@ -24,42 +24,40 @@ package org.onap.so.adapters.network.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ContrailPolicyRefSeq {
-
- @JsonProperty("network_policy_refs_data_sequence_major")
- private String major;
-
- @JsonProperty("network_policy_refs_data_sequence_minor")
- private String minor;
- public ContrailPolicyRefSeq() {
- }
-
- public ContrailPolicyRefSeq(String major, String minor) {
- super();
- this.major = major;
- this.minor = minor;
- }
+ @JsonProperty("network_policy_refs_data_sequence_major")
+ private String major;
- public String getMajor() {
- return major;
- }
+ @JsonProperty("network_policy_refs_data_sequence_minor")
+ private String minor;
- public void setMajor(String major) {
- this.major = major;
- }
+ public ContrailPolicyRefSeq() {}
- public String getMinor() {
- return minor;
- }
+ public ContrailPolicyRefSeq(String major, String minor) {
+ super();
+ this.major = major;
+ this.minor = minor;
+ }
- public void setMinor(String minor) {
- this.minor = minor;
- }
+ public String getMajor() {
+ return major;
+ }
- @Override
- public String toString() {
- return "ContrailPolicyRefSeq [major=" + major + ", minor=" + minor
- + "]";
- }
+ public void setMajor(String major) {
+ this.major = major;
+ }
+
+ public String getMinor() {
+ return minor;
+ }
+
+ public void setMinor(String minor) {
+ this.minor = minor;
+ }
+
+ @Override
+ public String toString() {
+ return "ContrailPolicyRefSeq [major=" + major + ", minor=" + minor + "]";
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnet.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnet.java
index fc674a0416..487fe804c5 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnet.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnet.java
@@ -22,107 +22,104 @@ package org.onap.so.adapters.network.beans;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class ContrailSubnet {
- @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet")
- private ContrailSubnetIp subnet = new ContrailSubnetIp();
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_default_gateway")
- private String defaultGateway;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_name")
- private String subnetName;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_enable_dhcp")
- private Boolean enableDhcp;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_addr_from_start")
- private Boolean addrFromStart = true;
- /** future - leave this commented
- private String subnet_uuid;
- private String dns_server_address;
- private List<String> dns_nameservers;
- private String dhcp_option_list;
- **/
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools")
- private List<ContrailSubnetPool> allocationPools = new ArrayList<>();
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes")
- private ContrailSubnetHostRoutes hostRoutes = new ContrailSubnetHostRoutes();
-
- public ContrailSubnet() {
- super();
- }
-
- public String getDefaultGateway() {
- return defaultGateway;
- }
-
- public void setDefaultGateway(String defaultGateway) {
- this.defaultGateway = defaultGateway;
- }
-
- public ContrailSubnetIp getSubnet() {
- return subnet;
- }
-
- public void setSubnet(ContrailSubnetIp subnet) {
- this.subnet = subnet;
- }
-
- public Boolean isEnableDhcp() {
- return enableDhcp;
- }
-
- public void setEnableDhcp(Boolean enableDhcp) {
- this.enableDhcp = enableDhcp;
- }
-
- public String getSubnetName() {
- return subnetName;
- }
-
- public void setSubnetName(String subnetName) {
- this.subnetName = subnetName;
- }
-
- public List<ContrailSubnetPool> getAllocationPools() {
- return allocationPools;
- }
-
- public void setAllocationPools(List<ContrailSubnetPool> allocationPools) {
- this.allocationPools = allocationPools;
- }
-
- public Boolean isAddrFromStart() {
- return addrFromStart;
- }
-
- public void setAddrFromStart(Boolean addrFromStart) {
- this.addrFromStart = addrFromStart;
- }
-
- public ContrailSubnetHostRoutes getHostRoutes() {
- return hostRoutes;
- }
-
- public void setHostRoutes(ContrailSubnetHostRoutes hostRoutes) {
- this.hostRoutes = hostRoutes;
- }
-
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder ();
- for (ContrailSubnetPool pool : allocationPools)
- {
- buf.append(pool.toString());
- }
- return "ContrailSubnet [subnet=" + subnet.toString() + " default_gateway=" + defaultGateway
- + " enable_dhcp=" + enableDhcp + " addr_from_start=" + addrFromStart + " subnet_name=" + subnetName + " allocation_pools=" + buf + " ]";
- }
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet")
+ private ContrailSubnetIp subnet = new ContrailSubnetIp();
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_default_gateway")
+ private String defaultGateway;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_name")
+ private String subnetName;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_enable_dhcp")
+ private Boolean enableDhcp;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_addr_from_start")
+ private Boolean addrFromStart = true;
+ /**
+ * future - leave this commented private String subnet_uuid; private String dns_server_address; private List<String>
+ * dns_nameservers; private String dhcp_option_list;
+ **/
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools")
+ private List<ContrailSubnetPool> allocationPools = new ArrayList<>();
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes")
+ private ContrailSubnetHostRoutes hostRoutes = new ContrailSubnetHostRoutes();
+
+ public ContrailSubnet() {
+ super();
+ }
+
+ public String getDefaultGateway() {
+ return defaultGateway;
+ }
+
+ public void setDefaultGateway(String defaultGateway) {
+ this.defaultGateway = defaultGateway;
+ }
+
+ public ContrailSubnetIp getSubnet() {
+ return subnet;
+ }
+
+ public void setSubnet(ContrailSubnetIp subnet) {
+ this.subnet = subnet;
+ }
+
+ public Boolean isEnableDhcp() {
+ return enableDhcp;
+ }
+
+ public void setEnableDhcp(Boolean enableDhcp) {
+ this.enableDhcp = enableDhcp;
+ }
+
+ public String getSubnetName() {
+ return subnetName;
+ }
+
+ public void setSubnetName(String subnetName) {
+ this.subnetName = subnetName;
+ }
+
+ public List<ContrailSubnetPool> getAllocationPools() {
+ return allocationPools;
+ }
+
+ public void setAllocationPools(List<ContrailSubnetPool> allocationPools) {
+ this.allocationPools = allocationPools;
+ }
+
+ public Boolean isAddrFromStart() {
+ return addrFromStart;
+ }
+
+ public void setAddrFromStart(Boolean addrFromStart) {
+ this.addrFromStart = addrFromStart;
+ }
+
+ public ContrailSubnetHostRoutes getHostRoutes() {
+ return hostRoutes;
+ }
+
+ public void setHostRoutes(ContrailSubnetHostRoutes hostRoutes) {
+ this.hostRoutes = hostRoutes;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder buf = new StringBuilder();
+ for (ContrailSubnetPool pool : allocationPools) {
+ buf.append(pool.toString());
+ }
+ return "ContrailSubnet [subnet=" + subnet.toString() + " default_gateway=" + defaultGateway + " enable_dhcp="
+ + enableDhcp + " addr_from_start=" + addrFromStart + " subnet_name=" + subnetName + " allocation_pools="
+ + buf + " ]";
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetHostRoute.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetHostRoute.java
index 7d53715e3c..4d0fe40e49 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetHostRoute.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetHostRoute.java
@@ -22,33 +22,34 @@ package org.onap.so.adapters.network.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
+
public class ContrailSubnetHostRoute {
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route_prefix")
- private String prefix;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route_next_hop")
- private String nextHop;
-
- public String getPrefix() {
- return prefix;
- }
-
- public void setPrefix(String prefix) {
- this.prefix = prefix;
- }
-
- public String getNextHop() {
- return nextHop;
- }
-
- public void setNextHop(String nextHop) {
- this.nextHop = nextHop;
- }
-
- @Override
- public String toString() {
- return "ContrailSubnetHostRoute [prefix=" + prefix + ", nextHop=" + nextHop + "]";
- }
-
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route_prefix")
+ private String prefix;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route_next_hop")
+ private String nextHop;
+
+ public String getPrefix() {
+ return prefix;
+ }
+
+ public void setPrefix(String prefix) {
+ this.prefix = prefix;
+ }
+
+ public String getNextHop() {
+ return nextHop;
+ }
+
+ public void setNextHop(String nextHop) {
+ this.nextHop = nextHop;
+ }
+
+ @Override
+ public String toString() {
+ return "ContrailSubnetHostRoute [prefix=" + prefix + ", nextHop=" + nextHop + "]";
+ }
+
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetHostRoutes.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetHostRoutes.java
index cd7192b6e2..e7bb8275d3 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetHostRoutes.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetHostRoutes.java
@@ -23,31 +23,29 @@ package org.onap.so.adapters.network.beans;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
+
public class ContrailSubnetHostRoutes {
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route")
- private List<ContrailSubnetHostRoute> hostRoutes = new ArrayList<>();
-
- public List<ContrailSubnetHostRoute> getHostRoutes() {
- return hostRoutes;
- }
-
- public void setHostRoutes(List<ContrailSubnetHostRoute> hostRoutes) {
- this.hostRoutes = hostRoutes;
- }
-
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder ();
- if (hostRoutes != null)
- {
- for (ContrailSubnetHostRoute hr : hostRoutes)
- {
- buf.append(hr.toString());
- }
- }
- return "ContrailSubnetHostRoutes [" + buf.toString() + "]";
- }
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route")
+ private List<ContrailSubnetHostRoute> hostRoutes = new ArrayList<>();
+
+ public List<ContrailSubnetHostRoute> getHostRoutes() {
+ return hostRoutes;
+ }
+
+ public void setHostRoutes(List<ContrailSubnetHostRoute> hostRoutes) {
+ this.hostRoutes = hostRoutes;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder buf = new StringBuilder();
+ if (hostRoutes != null) {
+ for (ContrailSubnetHostRoute hr : hostRoutes) {
+ buf.append(hr.toString());
+ }
+ }
+ return "ContrailSubnetHostRoutes [" + buf.toString() + "]";
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetIp.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetIp.java
index 3986592dde..064b8733cb 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetIp.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetIp.java
@@ -24,32 +24,32 @@ package org.onap.so.adapters.network.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ContrailSubnetIp {
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix")
- private String ipPrefix;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix_len")
- private String ipPrefixLen;
-
- public String getIpPrefix() {
- return ipPrefix;
- }
-
- public void setIpPrefix(String ipPrefix) {
- this.ipPrefix = ipPrefix;
- }
-
- public String getIpPrefixLen() {
- return ipPrefixLen;
- }
-
- public void setIpPrefixLen(String ipPrefixLen) {
- this.ipPrefixLen = ipPrefixLen;
- }
-
- @Override
- public String toString() {
- return "ContrailSubnetIp [ip_prefix=" + ipPrefix + ", ip_prefix_len=" + ipPrefixLen + "]";
- }
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix")
+ private String ipPrefix;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix_len")
+ private String ipPrefixLen;
+
+ public String getIpPrefix() {
+ return ipPrefix;
+ }
+
+ public void setIpPrefix(String ipPrefix) {
+ this.ipPrefix = ipPrefix;
+ }
+
+ public String getIpPrefixLen() {
+ return ipPrefixLen;
+ }
+
+ public void setIpPrefixLen(String ipPrefixLen) {
+ this.ipPrefixLen = ipPrefixLen;
+ }
+
+ @Override
+ public String toString() {
+ return "ContrailSubnetIp [ip_prefix=" + ipPrefix + ", ip_prefix_len=" + ipPrefixLen + "]";
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetPool.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetPool.java
index 11a06c69d5..434416c7ed 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetPool.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/beans/ContrailSubnetPool.java
@@ -24,32 +24,32 @@ package org.onap.so.adapters.network.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ContrailSubnetPool {
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools_start")
- private String start;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools_end")
- private String end;
-
- public String getStart() {
- return start;
- }
-
- public void setStart(String start) {
- this.start = start;
- }
-
- public String getEnd() {
- return end;
- }
-
- public void setEnd(String end) {
- this.end = end;
- }
-
- @Override
- public String toString() {
- return "ContrailSubnetPool [start=" + start + ", end=" + end + "]";
- }
-
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools_start")
+ private String start;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools_end")
+ private String end;
+
+ public String getStart() {
+ return start;
+ }
+
+ public void setStart(String start) {
+ this.start = start;
+ }
+
+ public String getEnd() {
+ return end;
+ }
+
+ public void setEnd(String end) {
+ this.end = end;
+ }
+
+ @Override
+ public String toString() {
+ return "ContrailSubnetPool [start=" + start + ", end=" + end + "]";
+ }
+
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetHostRouteMapper.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetHostRouteMapper.java
index 03800de5b8..f711c25172 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetHostRouteMapper.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetHostRouteMapper.java
@@ -25,20 +25,21 @@ import org.onap.so.openstack.beans.HostRoute;
public class ContrailSubnetHostRouteMapper {
- private final HostRoute hostRoute;
- public ContrailSubnetHostRouteMapper(HostRoute hostRoute) {
- this.hostRoute = hostRoute;
- }
-
- public ContrailSubnetHostRoute map() {
-
- final ContrailSubnetHostRoute contrailSubnetHostRoute = new ContrailSubnetHostRoute();
-
- if (hostRoute != null) {
- contrailSubnetHostRoute.setNextHop(hostRoute.getNextHop());
- contrailSubnetHostRoute.setPrefix(hostRoute.getPrefix());
- }
- return contrailSubnetHostRoute;
- }
-
+ private final HostRoute hostRoute;
+
+ public ContrailSubnetHostRouteMapper(HostRoute hostRoute) {
+ this.hostRoute = hostRoute;
+ }
+
+ public ContrailSubnetHostRoute map() {
+
+ final ContrailSubnetHostRoute contrailSubnetHostRoute = new ContrailSubnetHostRoute();
+
+ if (hostRoute != null) {
+ contrailSubnetHostRoute.setNextHop(hostRoute.getNextHop());
+ contrailSubnetHostRoute.setPrefix(hostRoute.getPrefix());
+ }
+ return contrailSubnetHostRoute;
+ }
+
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetMapper.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetMapper.java
index d3ccb35a60..be0ad5c078 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetMapper.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetMapper.java
@@ -23,7 +23,6 @@ package org.onap.so.adapters.network.mappers;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-
import org.onap.so.adapters.network.beans.ContrailSubnet;
import org.onap.so.adapters.network.beans.ContrailSubnetHostRoute;
import org.onap.so.adapters.network.beans.ContrailSubnetHostRoutes;
@@ -35,101 +34,103 @@ import org.onap.so.openstack.beans.Subnet;
public class ContrailSubnetMapper {
- private final Subnet inputSubnet;
- public ContrailSubnetMapper(Subnet inputSubnet) {
- this.inputSubnet = inputSubnet;
- }
-
- public ContrailSubnet map() {
-
- final ContrailSubnet result = new ContrailSubnet();
- if (inputSubnet != null) {
- final String subnetname = this.getSubnetName(inputSubnet);
- result.setSubnetName(subnetname);
- result.setEnableDhcp(inputSubnet.getEnableDHCP());
- result.setDefaultGateway(inputSubnet.getGatewayIp());
-
- Optional<ContrailSubnetIp> csIp = createSubnet(inputSubnet);
- if (csIp.isPresent()) {
- result.setSubnet(csIp.get());
- }
- Optional<List<ContrailSubnetPool>> pools = this.createContrailSubnetPool(inputSubnet);
- if (pools.isPresent()) {
- result.setAllocationPools(pools.get());
- }
- Optional<ContrailSubnetHostRoutes> routes = this.createContrailSubnetHostRoutes(inputSubnet);
- if (routes.isPresent()) {
- result.setHostRoutes(routes.get());
- }
- }
-
- return result;
- }
-
- protected String getSubnetName(Subnet subnet) {
- final String result;
- if (!isNullOrEmpty(subnet.getSubnetName())) {
- result = subnet.getSubnetName();
- } else {
- result = subnet.getSubnetId();
- }
-
- return result;
- }
-
- protected Optional<List<ContrailSubnetPool>> createContrailSubnetPool(final Subnet subnet) {
- Optional<List<ContrailSubnetPool>> result = Optional.empty();
- if (subnet.getAllocationPools() != null) {
- List<ContrailSubnetPool> pools = new ArrayList<>();
- for (Pool pool : subnet.getAllocationPools()) {
- if ( !isNullOrEmpty(pool.getStart()) && !isNullOrEmpty(pool.getEnd()) ) {
-
- pools.add(new ContrailSubnetPoolMapper(pool).map());
- }
- }
- if (!pools.isEmpty()) {
- result = Optional.of(pools);
- }
- }
-
- return result;
- }
-
- protected Optional<ContrailSubnetHostRoutes> createContrailSubnetHostRoutes(final Subnet subnet) {
- Optional<ContrailSubnetHostRoutes> result = Optional.empty();
- if (subnet.getHostRoutes() != null) {
- ContrailSubnetHostRoutes hostRoutesObj = new ContrailSubnetHostRoutes();
- List<ContrailSubnetHostRoute> hrList = new ArrayList<>();
- for (HostRoute hr : subnet.getHostRoutes()) {
- if ( !isNullOrEmpty(hr.getPrefix()) || !isNullOrEmpty(hr.getNextHop()) ) {
- hrList.add(new ContrailSubnetHostRouteMapper(hr).map());
- }
- }
- if (!hrList.isEmpty()) {
- hostRoutesObj.setHostRoutes(hrList);
- result = Optional.of(hostRoutesObj);
- }
- }
-
- return result;
-
- }
- protected Optional<ContrailSubnetIp> createSubnet(final Subnet subnet) {
- Optional<ContrailSubnetIp> result = Optional.empty();
- if (!isNullOrEmpty(subnet.getCidr()) ) {
- int idx = subnet.getCidr().indexOf("/");
- final ContrailSubnetIp csIp = new ContrailSubnetIp();
- if (idx != -1) {
- csIp.setIpPrefix(subnet.getCidr().substring(0, idx));
- csIp.setIpPrefixLen(subnet.getCidr().substring(idx+1));
- result = Optional.of(csIp);
- }
- }
-
- return result;
- }
-
- protected boolean isNullOrEmpty (String s) {
- return s == null || s.isEmpty();
- }
+ private final Subnet inputSubnet;
+
+ public ContrailSubnetMapper(Subnet inputSubnet) {
+ this.inputSubnet = inputSubnet;
+ }
+
+ public ContrailSubnet map() {
+
+ final ContrailSubnet result = new ContrailSubnet();
+ if (inputSubnet != null) {
+ final String subnetname = this.getSubnetName(inputSubnet);
+ result.setSubnetName(subnetname);
+ result.setEnableDhcp(inputSubnet.getEnableDHCP());
+ result.setDefaultGateway(inputSubnet.getGatewayIp());
+
+ Optional<ContrailSubnetIp> csIp = createSubnet(inputSubnet);
+ if (csIp.isPresent()) {
+ result.setSubnet(csIp.get());
+ }
+ Optional<List<ContrailSubnetPool>> pools = this.createContrailSubnetPool(inputSubnet);
+ if (pools.isPresent()) {
+ result.setAllocationPools(pools.get());
+ }
+ Optional<ContrailSubnetHostRoutes> routes = this.createContrailSubnetHostRoutes(inputSubnet);
+ if (routes.isPresent()) {
+ result.setHostRoutes(routes.get());
+ }
+ }
+
+ return result;
+ }
+
+ protected String getSubnetName(Subnet subnet) {
+ final String result;
+ if (!isNullOrEmpty(subnet.getSubnetName())) {
+ result = subnet.getSubnetName();
+ } else {
+ result = subnet.getSubnetId();
+ }
+
+ return result;
+ }
+
+ protected Optional<List<ContrailSubnetPool>> createContrailSubnetPool(final Subnet subnet) {
+ Optional<List<ContrailSubnetPool>> result = Optional.empty();
+ if (subnet.getAllocationPools() != null) {
+ List<ContrailSubnetPool> pools = new ArrayList<>();
+ for (Pool pool : subnet.getAllocationPools()) {
+ if (!isNullOrEmpty(pool.getStart()) && !isNullOrEmpty(pool.getEnd())) {
+
+ pools.add(new ContrailSubnetPoolMapper(pool).map());
+ }
+ }
+ if (!pools.isEmpty()) {
+ result = Optional.of(pools);
+ }
+ }
+
+ return result;
+ }
+
+ protected Optional<ContrailSubnetHostRoutes> createContrailSubnetHostRoutes(final Subnet subnet) {
+ Optional<ContrailSubnetHostRoutes> result = Optional.empty();
+ if (subnet.getHostRoutes() != null) {
+ ContrailSubnetHostRoutes hostRoutesObj = new ContrailSubnetHostRoutes();
+ List<ContrailSubnetHostRoute> hrList = new ArrayList<>();
+ for (HostRoute hr : subnet.getHostRoutes()) {
+ if (!isNullOrEmpty(hr.getPrefix()) || !isNullOrEmpty(hr.getNextHop())) {
+ hrList.add(new ContrailSubnetHostRouteMapper(hr).map());
+ }
+ }
+ if (!hrList.isEmpty()) {
+ hostRoutesObj.setHostRoutes(hrList);
+ result = Optional.of(hostRoutesObj);
+ }
+ }
+
+ return result;
+
+ }
+
+ protected Optional<ContrailSubnetIp> createSubnet(final Subnet subnet) {
+ Optional<ContrailSubnetIp> result = Optional.empty();
+ if (!isNullOrEmpty(subnet.getCidr())) {
+ int idx = subnet.getCidr().indexOf("/");
+ final ContrailSubnetIp csIp = new ContrailSubnetIp();
+ if (idx != -1) {
+ csIp.setIpPrefix(subnet.getCidr().substring(0, idx));
+ csIp.setIpPrefixLen(subnet.getCidr().substring(idx + 1));
+ result = Optional.of(csIp);
+ }
+ }
+
+ return result;
+ }
+
+ protected boolean isNullOrEmpty(String s) {
+ return s == null || s.isEmpty();
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetPoolMapper.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetPoolMapper.java
index a492cd30c0..39b02cd6d5 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetPoolMapper.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/network/mappers/ContrailSubnetPoolMapper.java
@@ -25,19 +25,19 @@ import org.onap.so.openstack.beans.Pool;
public class ContrailSubnetPoolMapper {
- private final Pool pool;
-
- public ContrailSubnetPoolMapper(Pool pool) {
- this.pool = pool;
- }
-
- public ContrailSubnetPool map() {
-
- ContrailSubnetPool result = new ContrailSubnetPool();
- if (pool != null) {
- result.setStart(pool.getStart());
- result.setEnd(pool.getEnd());
- }
- return result;
- }
+ private final Pool pool;
+
+ public ContrailSubnetPoolMapper(Pool pool) {
+ this.pool = pool;
+ }
+
+ public ContrailSubnetPool map() {
+
+ ContrailSubnetPool result = new ContrailSubnetPool();
+ if (pool != null) {
+ result.setStart(pool.getStart());
+ result.setEnd(pool.getEnd());
+ }
+ return result;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/ContrailNetwork.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/ContrailNetwork.java
index 9a7431130d..c80712a07e 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/ContrailNetwork.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/ContrailNetwork.java
@@ -23,76 +23,75 @@ package org.onap.so.adapters.nwrest;
import java.io.Serializable;
import java.util.List;
-
import org.onap.so.openstack.beans.RouteTarget;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("contrailNetwork")
-public class ContrailNetwork implements Serializable{
-
-
- /**
- *
- */
- private static final long serialVersionUID = 6879356795950005963L;
- private String shared = "false";
- private String external = "false";
- private List<RouteTarget> routeTargets;
- private List<String> policyFqdns;
- private List<String> routeTableFqdns;
-
- public ContrailNetwork() {
- super();
- }
-
- public ContrailNetwork(String shared, String external, List<RouteTarget> routeTargets, List<String> policyFqdns, List<String> routeTableFqdns) {
- super();
- this.shared = shared;
- this.external = external;
- this.routeTargets = routeTargets;
- this.policyFqdns = policyFqdns;
- this.routeTableFqdns = routeTableFqdns;
- }
-
- public String getShared() {
- return shared;
- }
-
- public void setShared(String shared) {
- this.shared = shared;
- }
-
- public String getExternal() {
- return external;
- }
-
- public void setExternal(String external) {
- this.external = external;
- }
-
- public List<RouteTarget> getRouteTargets() {
- return routeTargets;
- }
-
- public void setRouteTargets(List<RouteTarget> routeTargets) {
- this.routeTargets = routeTargets;
- }
-
- public List<String> getPolicyFqdns() {
- return policyFqdns;
- }
-
- public void setPolicyFqdns(List<String> policyFqdns) {
- this.policyFqdns = policyFqdns;
- }
-
- public List<String> getRouteTableFqdns() {
- return routeTableFqdns;
- }
-
- public void setRouteTableFqdns(List<String> routeTableFqdns) {
- this.routeTableFqdns = routeTableFqdns;
- }
-
+public class ContrailNetwork implements Serializable {
+
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 6879356795950005963L;
+ private String shared = "false";
+ private String external = "false";
+ private List<RouteTarget> routeTargets;
+ private List<String> policyFqdns;
+ private List<String> routeTableFqdns;
+
+ public ContrailNetwork() {
+ super();
+ }
+
+ public ContrailNetwork(String shared, String external, List<RouteTarget> routeTargets, List<String> policyFqdns,
+ List<String> routeTableFqdns) {
+ super();
+ this.shared = shared;
+ this.external = external;
+ this.routeTargets = routeTargets;
+ this.policyFqdns = policyFqdns;
+ this.routeTableFqdns = routeTableFqdns;
+ }
+
+ public String getShared() {
+ return shared;
+ }
+
+ public void setShared(String shared) {
+ this.shared = shared;
+ }
+
+ public String getExternal() {
+ return external;
+ }
+
+ public void setExternal(String external) {
+ this.external = external;
+ }
+
+ public List<RouteTarget> getRouteTargets() {
+ return routeTargets;
+ }
+
+ public void setRouteTargets(List<RouteTarget> routeTargets) {
+ this.routeTargets = routeTargets;
+ }
+
+ public List<String> getPolicyFqdns() {
+ return policyFqdns;
+ }
+
+ public void setPolicyFqdns(List<String> policyFqdns) {
+ this.policyFqdns = policyFqdns;
+ }
+
+ public List<String> getRouteTableFqdns() {
+ return routeTableFqdns;
+ }
+
+ public void setRouteTableFqdns(List<String> routeTableFqdns) {
+ this.routeTableFqdns = routeTableFqdns;
+ }
+
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkError.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkError.java
index fec9b474dd..4833625a6b 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkError.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkError.java
@@ -22,24 +22,22 @@ package org.onap.so.adapters.nwrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
@XmlRootElement(name = "createNetworkError")
public class CreateNetworkError extends NetworkExceptionResponse implements Serializable {
- private static final long serialVersionUID = -4283402447149144456L;
+ private static final long serialVersionUID = -4283402447149144456L;
- public CreateNetworkError() {
- super("");
- }
+ public CreateNetworkError() {
+ super("");
+ }
- public CreateNetworkError(String message) {
- super(message);
- }
+ public CreateNetworkError(String message) {
+ super(message);
+ }
- public CreateNetworkError(String message, MsoExceptionCategory category, boolean rolledBack, String messageid) {
- super(message, category, rolledBack, messageid);
- }
+ public CreateNetworkError(String message, MsoExceptionCategory category, boolean rolledBack, String messageid) {
+ super(message, category, rolledBack, messageid);
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkRequest.java
index 153ee78cb0..4f3ed4c96e 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkRequest.java
@@ -25,175 +25,173 @@ package org.onap.so.adapters.nwrest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.entity.MsoRequest;
import org.onap.so.openstack.beans.Subnet;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
-/* README
- Map<String, String> elements when marshalled to XML produce a list of <entry><key>${MsoUtils.xmlEscape(key)}</key><value>${MsoUtils.xmlEscape(value)}</value></entry> elements.
- When marshalling to JSON they create a list of "${key}" : "${value}" pairs with no extra wrappers.
-*/
+/*
+ * README Map<String, String> elements when marshalled to XML produce a list of
+ * <entry><key>${MsoUtils.xmlEscape(key)}</key><value>${MsoUtils.xmlEscape(value)}</value></entry> elements. When
+ * marshalling to JSON they create a list of "${key}" : "${value}" pairs with no extra wrappers.
+ */
@JsonRootName("createNetworkRequest")
@XmlRootElement(name = "createNetworkRequest")
public class CreateNetworkRequest extends NetworkRequestCommon {
- /**
- *
- */
- private static final long serialVersionUID = -8984362978831333521L;
- private String cloudSiteId;
- private String tenantId;
- private String networkId;
- private String networkName;
- private String networkType;
- private String networkTypeVersion;
- private String modelCustomizationUuid;
- private String networkTechnology = "NEUTRON";
- private List<Subnet> subnets;
- private ProviderVlanNetwork providerVlanNetwork;
- private ContrailNetwork contrailNetwork;
- private Boolean failIfExists = false;
- private Boolean backout = true;
- private Map<String,String> networkParams = new HashMap<>();
- private MsoRequest msoRequest = new MsoRequest();
- private boolean contrailRequest;
-
- public CreateNetworkRequest() {
- super();
- }
-
- public String getCloudSiteId() {
- return cloudSiteId;
- }
-
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
-
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getNetworkId() {
- return networkId;
- }
-
- public void setNetworkId(String networkId) {
- this.networkId = networkId;
- }
-
- public String getNetworkName() {
- return networkName;
- }
-
- public void setNetworkName(String networkName) {
- this.networkName = networkName;
- }
-
- public String getNetworkType() {
- return networkType;
- }
-
- public void setNetworkType(String networkType) {
- this.networkType = networkType;
- }
-
- public String getModelCustomizationUuid() {
- return this.modelCustomizationUuid;
- }
-
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
-
- public String getNetworkTypeVersion() {
- return networkTypeVersion;
- }
-
- public void setNetworkTypeVersion(String networkTypeVersion) {
- this.networkTypeVersion = networkTypeVersion;
- }
-
- public String getNetworkTechnology() {
- return networkTechnology;
- }
-
- public void setNetworkTechnology(String networkTechnology) {
- this.networkTechnology = networkTechnology;
- }
-
- public List<Subnet> getSubnets() {
- return subnets;
- }
-
- public void setSubnets(List<Subnet> subnets) {
- this.subnets = subnets;
- }
-
- public ProviderVlanNetwork getProviderVlanNetwork() {
- return providerVlanNetwork;
- }
-
- public void setProviderVlanNetwork(ProviderVlanNetwork providerVlanNetwork) {
- this.providerVlanNetwork = providerVlanNetwork;
- }
-
- public ContrailNetwork getContrailNetwork() {
- return contrailNetwork;
- }
-
- public void setContrailNetwork(ContrailNetwork contrailNetwork) {
- this.contrailNetwork = contrailNetwork;
- }
-
- public Boolean getFailIfExists() {
- return failIfExists;
- }
-
- public void setFailIfExists(Boolean failIfExists) {
- this.failIfExists = failIfExists;
- }
-
- public Boolean getBackout() {
- return backout;
- }
-
- public void setBackout(Boolean backout) {
- this.backout = backout;
- }
-
- public Map<String, String> getNetworkParams() {
- return networkParams;
- }
-
- public void setNetworkParams(Map<String, String> networkParams) {
- this.networkParams = networkParams;
- }
-
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
-
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
-
- public boolean isContrailRequest() {
- return this.contrailRequest;
- }
-
- public void setContrailRequest(boolean contrailRequest) {
- this.contrailRequest = contrailRequest;
- }
-
+ /**
+ *
+ */
+ private static final long serialVersionUID = -8984362978831333521L;
+ private String cloudSiteId;
+ private String tenantId;
+ private String networkId;
+ private String networkName;
+ private String networkType;
+ private String networkTypeVersion;
+ private String modelCustomizationUuid;
+ private String networkTechnology = "NEUTRON";
+ private List<Subnet> subnets;
+ private ProviderVlanNetwork providerVlanNetwork;
+ private ContrailNetwork contrailNetwork;
+ private Boolean failIfExists = false;
+ private Boolean backout = true;
+ private Map<String, String> networkParams = new HashMap<>();
+ private MsoRequest msoRequest = new MsoRequest();
+ private boolean contrailRequest;
+
+ public CreateNetworkRequest() {
+ super();
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getNetworkId() {
+ return networkId;
+ }
+
+ public void setNetworkId(String networkId) {
+ this.networkId = networkId;
+ }
+
+ public String getNetworkName() {
+ return networkName;
+ }
+
+ public void setNetworkName(String networkName) {
+ this.networkName = networkName;
+ }
+
+ public String getNetworkType() {
+ return networkType;
+ }
+
+ public void setNetworkType(String networkType) {
+ this.networkType = networkType;
+ }
+
+ public String getModelCustomizationUuid() {
+ return this.modelCustomizationUuid;
+ }
+
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ public String getNetworkTypeVersion() {
+ return networkTypeVersion;
+ }
+
+ public void setNetworkTypeVersion(String networkTypeVersion) {
+ this.networkTypeVersion = networkTypeVersion;
+ }
+
+ public String getNetworkTechnology() {
+ return networkTechnology;
+ }
+
+ public void setNetworkTechnology(String networkTechnology) {
+ this.networkTechnology = networkTechnology;
+ }
+
+ public List<Subnet> getSubnets() {
+ return subnets;
+ }
+
+ public void setSubnets(List<Subnet> subnets) {
+ this.subnets = subnets;
+ }
+
+ public ProviderVlanNetwork getProviderVlanNetwork() {
+ return providerVlanNetwork;
+ }
+
+ public void setProviderVlanNetwork(ProviderVlanNetwork providerVlanNetwork) {
+ this.providerVlanNetwork = providerVlanNetwork;
+ }
+
+ public ContrailNetwork getContrailNetwork() {
+ return contrailNetwork;
+ }
+
+ public void setContrailNetwork(ContrailNetwork contrailNetwork) {
+ this.contrailNetwork = contrailNetwork;
+ }
+
+ public Boolean getFailIfExists() {
+ return failIfExists;
+ }
+
+ public void setFailIfExists(Boolean failIfExists) {
+ this.failIfExists = failIfExists;
+ }
+
+ public Boolean getBackout() {
+ return backout;
+ }
+
+ public void setBackout(Boolean backout) {
+ this.backout = backout;
+ }
+
+ public Map<String, String> getNetworkParams() {
+ return networkParams;
+ }
+
+ public void setNetworkParams(Map<String, String> networkParams) {
+ this.networkParams = networkParams;
+ }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
+
+ public boolean isContrailRequest() {
+ return this.contrailRequest;
+ }
+
+ public void setContrailRequest(boolean contrailRequest) {
+ this.contrailRequest = contrailRequest;
+ }
+
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkResponse.java
index 763732213d..7968348d8d 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/CreateNetworkResponse.java
@@ -23,105 +23,96 @@ package org.onap.so.adapters.nwrest;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.beans.NetworkRollback;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("createNetworkResponse")
@XmlRootElement(name = "createNetworkResponse")
public class CreateNetworkResponse extends NetworkResponseCommon {
- /**
- *
- */
- private static final long serialVersionUID = -7730406297031948309L;
-
- private String networkId;
- private String neutronNetworkId;
- private String networkStackId;
- private String networkFqdn;
- private Boolean networkCreated;
- private Map<String, String> subnetMap;
- private NetworkRollback rollback = new NetworkRollback();
-
- public CreateNetworkResponse() {
- super();
- }
-
- public CreateNetworkResponse(String networkId,
- String neutronNetworkId,
- String networkStackId,
- String networkFqdn,
- Boolean networkCreated,
- Map<String, String> subnetIdMap,
- NetworkRollback rollback,
- String messageId) {
- super(messageId);
- this.networkId = networkId;
- this.neutronNetworkId = neutronNetworkId;
- this.networkStackId = networkStackId;
- this.networkFqdn = networkFqdn;
- this.networkCreated = networkCreated;
- this.subnetMap = subnetIdMap;
- this.rollback = rollback;
- }
-
- public String getNetworkId() {
- return networkId;
- }
-
- public void setNetworkId(String networkId) {
- this.networkId = networkId;
- }
-
- public String getNeutronNetworkId() {
- return neutronNetworkId;
- }
-
- public void setNeutronNetworkId(String neutronNetworkId) {
- this.neutronNetworkId = neutronNetworkId;
- }
-
- public String getNetworkStackId() {
- return networkStackId;
- }
-
- public void setNetworkStackId(String networkStackId) {
- this.networkStackId = networkStackId;
- }
-
- public String getNetworkFqdn() {
- return networkFqdn;
- }
-
- public void setNetworkFqdn(String networkFqdn) {
- this.networkFqdn = networkFqdn;
- }
-
- public Boolean getNetworkCreated() {
- return networkCreated;
- }
-
- public void setNetworkCreated(Boolean networkCreated) {
- this.networkCreated = networkCreated;
- }
-
- public Map<String, String> getSubnetMap() {
- return subnetMap;
- }
-
- public void setSubnetMap(Map<String, String> subnetMap) {
- this.subnetMap = subnetMap;
- }
-
- public NetworkRollback getRollback() {
- return rollback;
- }
-
- public void setRollback(NetworkRollback rollback) {
- this.rollback = rollback;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -7730406297031948309L;
+
+ private String networkId;
+ private String neutronNetworkId;
+ private String networkStackId;
+ private String networkFqdn;
+ private Boolean networkCreated;
+ private Map<String, String> subnetMap;
+ private NetworkRollback rollback = new NetworkRollback();
+
+ public CreateNetworkResponse() {
+ super();
+ }
+
+ public CreateNetworkResponse(String networkId, String neutronNetworkId, String networkStackId, String networkFqdn,
+ Boolean networkCreated, Map<String, String> subnetIdMap, NetworkRollback rollback, String messageId) {
+ super(messageId);
+ this.networkId = networkId;
+ this.neutronNetworkId = neutronNetworkId;
+ this.networkStackId = networkStackId;
+ this.networkFqdn = networkFqdn;
+ this.networkCreated = networkCreated;
+ this.subnetMap = subnetIdMap;
+ this.rollback = rollback;
+ }
+
+ public String getNetworkId() {
+ return networkId;
+ }
+
+ public void setNetworkId(String networkId) {
+ this.networkId = networkId;
+ }
+
+ public String getNeutronNetworkId() {
+ return neutronNetworkId;
+ }
+
+ public void setNeutronNetworkId(String neutronNetworkId) {
+ this.neutronNetworkId = neutronNetworkId;
+ }
+
+ public String getNetworkStackId() {
+ return networkStackId;
+ }
+
+ public void setNetworkStackId(String networkStackId) {
+ this.networkStackId = networkStackId;
+ }
+
+ public String getNetworkFqdn() {
+ return networkFqdn;
+ }
+
+ public void setNetworkFqdn(String networkFqdn) {
+ this.networkFqdn = networkFqdn;
+ }
+
+ public Boolean getNetworkCreated() {
+ return networkCreated;
+ }
+
+ public void setNetworkCreated(Boolean networkCreated) {
+ this.networkCreated = networkCreated;
+ }
+
+ public Map<String, String> getSubnetMap() {
+ return subnetMap;
+ }
+
+ public void setSubnetMap(Map<String, String> subnetMap) {
+ this.subnetMap = subnetMap;
+ }
+
+ public NetworkRollback getRollback() {
+ return rollback;
+ }
+
+ public void setRollback(NetworkRollback rollback) {
+ this.rollback = rollback;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkError.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkError.java
index f874be56a3..a08c584fe6 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkError.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkError.java
@@ -22,24 +22,22 @@ package org.onap.so.adapters.nwrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
@XmlRootElement(name = "deleteNetworkError")
public class DeleteNetworkError extends NetworkExceptionResponse implements Serializable {
- private static final long serialVersionUID = 2735474165790444180L;
+ private static final long serialVersionUID = 2735474165790444180L;
- public DeleteNetworkError() {
- super("");
- }
+ public DeleteNetworkError() {
+ super("");
+ }
- public DeleteNetworkError(String message) {
- super(message);
- }
+ public DeleteNetworkError(String message) {
+ super(message);
+ }
- public DeleteNetworkError(String message, MsoExceptionCategory category, boolean unused, String messageid) {
- super(message, category, unused, messageid);
- }
+ public DeleteNetworkError(String message, MsoExceptionCategory category, boolean unused, String messageid) {
+ super(message, category, unused, messageid);
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkRequest.java
index 7c3669d7d7..eec960c5a5 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkRequest.java
@@ -25,9 +25,7 @@ package org.onap.so.adapters.nwrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.entity.MsoRequest;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -35,75 +33,75 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@XmlRootElement(name = "deleteNetworkRequest")
public class DeleteNetworkRequest extends NetworkRequestCommon {
- /**
- *
- */
- private static final long serialVersionUID = -2445072708572065058L;
- private String cloudSiteId;
- private String tenantId;
- private String networkId;
- private String networkStackId;
- private String networkType;
- private String modelCustomizationUuid;
- private MsoRequest msoRequest = new MsoRequest();
-
- public DeleteNetworkRequest() {
- //empty default constructor
- }
-
- public String getCloudSiteId() {
- return cloudSiteId;
- }
-
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
-
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getNetworkId() {
- return networkId;
- }
-
- public void setNetworkId(String networkId) {
- this.networkId = networkId;
- }
-
- public String getNetworkStackId() {
- return networkStackId;
- }
-
- public void setNetworkStackId(String networkStackId) {
- this.networkStackId = networkStackId;
- }
-
- public String getNetworkType() {
- return networkType;
- }
-
- public void setNetworkType(String networkType) {
- this.networkType = networkType;
- }
-
- public String getModelCustomizationUuid() {
- return this.modelCustomizationUuid;
- }
-
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
-
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
-
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -2445072708572065058L;
+ private String cloudSiteId;
+ private String tenantId;
+ private String networkId;
+ private String networkStackId;
+ private String networkType;
+ private String modelCustomizationUuid;
+ private MsoRequest msoRequest = new MsoRequest();
+
+ public DeleteNetworkRequest() {
+ // empty default constructor
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getNetworkId() {
+ return networkId;
+ }
+
+ public void setNetworkId(String networkId) {
+ this.networkId = networkId;
+ }
+
+ public String getNetworkStackId() {
+ return networkStackId;
+ }
+
+ public void setNetworkStackId(String networkStackId) {
+ this.networkStackId = networkStackId;
+ }
+
+ public String getNetworkType() {
+ return networkType;
+ }
+
+ public void setNetworkType(String networkType) {
+ this.networkType = networkType;
+ }
+
+ public String getModelCustomizationUuid() {
+ return this.modelCustomizationUuid;
+ }
+
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkResponse.java
index 1de7f8be76..720fb87940 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/DeleteNetworkResponse.java
@@ -23,43 +23,42 @@ package org.onap.so.adapters.nwrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("deleteNetworkResponse")
@XmlRootElement(name = "deleteNetworkResponse")
public class DeleteNetworkResponse extends NetworkResponseCommon {
- /**
- *
- */
- private static final long serialVersionUID = 68336086339501537L;
- private String networkId;
- private Boolean networkDeleted;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 68336086339501537L;
+ private String networkId;
+ private Boolean networkDeleted;
+
+ public DeleteNetworkResponse() {
+ super();
+ }
- public DeleteNetworkResponse() {
- super();
- }
+ public DeleteNetworkResponse(String networkId, Boolean networkDeleted, String messageId) {
+ super(messageId);
+ this.networkId = networkId;
+ this.networkDeleted = networkDeleted;
+ }
- public DeleteNetworkResponse(String networkId, Boolean networkDeleted, String messageId) {
- super(messageId);
- this.networkId = networkId;
- this.networkDeleted = networkDeleted;
- }
-
- public String getNetworkId() {
- return networkId;
- }
+ public String getNetworkId() {
+ return networkId;
+ }
- public void setNetworkId(String networkId) {
- this.networkId = networkId;
- }
+ public void setNetworkId(String networkId) {
+ this.networkId = networkId;
+ }
- public Boolean getNetworkDeleted() {
- return networkDeleted;
- }
+ public Boolean getNetworkDeleted() {
+ return networkDeleted;
+ }
- public void setNetworkDeleted(Boolean networkDeleted) {
- this.networkDeleted = networkDeleted;
- }
+ public void setNetworkDeleted(Boolean networkDeleted) {
+ this.networkDeleted = networkDeleted;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkExceptionResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkExceptionResponse.java
index 4b9f283e20..9d86c0ee87 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkExceptionResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkExceptionResponse.java
@@ -26,48 +26,49 @@ import org.onap.so.openstack.exceptions.MsoExceptionCategory;
public class NetworkExceptionResponse extends NetworkResponseCommon {
/**
- *
- */
- private static final long serialVersionUID = -7160401922983004097L;
- private String message;
- private MsoExceptionCategory category;
- private Boolean rolledBack;
+ *
+ */
+ private static final long serialVersionUID = -7160401922983004097L;
+ private String message;
+ private MsoExceptionCategory category;
+ private Boolean rolledBack;
- public NetworkExceptionResponse () {}
+ public NetworkExceptionResponse() {}
- public NetworkExceptionResponse (String message) {
- super();
- this.message = message;
- }
+ public NetworkExceptionResponse(String message) {
+ super();
+ this.message = message;
+ }
- public NetworkExceptionResponse (String message, MsoExceptionCategory category, boolean rolledBack, String messageid) {
- super(messageid);
- this.message = message;
- this.category = category;
- this.rolledBack = rolledBack;
- }
+ public NetworkExceptionResponse(String message, MsoExceptionCategory category, boolean rolledBack,
+ String messageid) {
+ super(messageid);
+ this.message = message;
+ this.category = category;
+ this.rolledBack = rolledBack;
+ }
- public String getMessage() {
- return message;
- }
+ public String getMessage() {
+ return message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public MsoExceptionCategory getCategory () {
- return category;
- }
+ public MsoExceptionCategory getCategory() {
+ return category;
+ }
- public void setCategory (MsoExceptionCategory category) {
- this.category = category;
- }
+ public void setCategory(MsoExceptionCategory category) {
+ this.category = category;
+ }
- public Boolean getRolledBack() {
- return rolledBack;
- }
+ public Boolean getRolledBack() {
+ return rolledBack;
+ }
- public void setRolledBack(Boolean rolledBack) {
- this.rolledBack = rolledBack;
- }
+ public void setRolledBack(Boolean rolledBack) {
+ this.rolledBack = rolledBack;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkRequestCommon.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkRequestCommon.java
index 5e4e015556..3629b3fda7 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkRequestCommon.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkRequestCommon.java
@@ -26,10 +26,8 @@ package org.onap.so.adapters.nwrest;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
-
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -41,70 +39,71 @@ import org.slf4j.LoggerFactory;
* Everything that is common between all Network Requests.
*/
public abstract class NetworkRequestCommon implements Serializable {
- private static final long serialVersionUID = -6732431343649282079L;
- private static final Logger logger = LoggerFactory.getLogger(NetworkRequestCommon.class);
- private Boolean skipAAI = false;
- private String messageId;
- private String notificationUrl;
- @JsonProperty
- private boolean synchronous = true;
- public Boolean getSkipAAI() {
- return skipAAI;
- }
+ private static final long serialVersionUID = -6732431343649282079L;
+ private static final Logger logger = LoggerFactory.getLogger(NetworkRequestCommon.class);
+ private Boolean skipAAI = false;
+ private String messageId;
+ private String notificationUrl;
+ @JsonProperty
+ private boolean synchronous = true;
+
+ public Boolean getSkipAAI() {
+ return skipAAI;
+ }
+
+ public void setSkipAAI(Boolean skipAAI) {
+ this.skipAAI = skipAAI;
+ }
- public void setSkipAAI(Boolean skipAAI) {
- this.skipAAI = skipAAI;
- }
+ public String getMessageId() {
+ return messageId;
+ }
- public String getMessageId() {
- return messageId;
- }
+ public void setMessageId(String messageId) {
+ this.messageId = messageId;
+ }
- public void setMessageId(String messageId) {
- this.messageId = messageId;
- }
+ public String getNotificationUrl() {
+ return notificationUrl;
+ }
- public String getNotificationUrl() {
- return notificationUrl;
- }
+ public void setNotificationUrl(String notificationUrl) {
+ this.notificationUrl = notificationUrl;
+ this.synchronous = notificationUrl == null || (notificationUrl.isEmpty());
+ }
- public void setNotificationUrl(String notificationUrl) {
- this.notificationUrl = notificationUrl;
- this.synchronous = notificationUrl == null || (notificationUrl.isEmpty());
- }
+ public boolean isSynchronous() {
+ return this.synchronous;
+ }
- public boolean isSynchronous() {
- return this.synchronous;
- }
-
- @JsonIgnore
- protected void setSynchronous(boolean synchronous) {
- this.synchronous = synchronous;
- }
+ @JsonIgnore
+ protected void setSynchronous(boolean synchronous) {
+ this.synchronous = synchronous;
+ }
- public String toJsonString() {
- String jsonString = null;
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- jsonString = mapper.writeValueAsString(this);
- } catch (Exception e) {
- logger.debug("Exception:", e);
- }
- return jsonString;
- }
+ public String toJsonString() {
+ String jsonString = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ jsonString = mapper.writeValueAsString(this);
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ }
+ return jsonString;
+ }
- public String toXmlString() {
- try {
- ByteArrayOutputStream bs = new ByteArrayOutputStream();
- JAXBContext context = JAXBContext.newInstance(this.getClass());
- Marshaller marshaller = context.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //pretty print XML
- marshaller.marshal(this, bs);
- return bs.toString();
- } catch (Exception e) {
- logger.debug("Exception:", e);
- return "";
- }
- }
+ public String toXmlString() {
+ try {
+ ByteArrayOutputStream bs = new ByteArrayOutputStream();
+ JAXBContext context = JAXBContext.newInstance(this.getClass());
+ Marshaller marshaller = context.createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // pretty print XML
+ marshaller.marshal(this, bs);
+ return bs.toString();
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ return "";
+ }
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkResponseCommon.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkResponseCommon.java
index d1907a237e..54eccb34e4 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkResponseCommon.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkResponseCommon.java
@@ -26,10 +26,8 @@ package org.onap.so.adapters.nwrest;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
-
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.slf4j.Logger;
@@ -40,49 +38,49 @@ import org.slf4j.LoggerFactory;
*/
public abstract class NetworkResponseCommon implements Serializable {
- private static final long serialVersionUID = 1233520856935129726L;
- private String messageId;
- private static final Logger logger = LoggerFactory.getLogger(NetworkResponseCommon.class);
+ private static final long serialVersionUID = 1233520856935129726L;
+ private String messageId;
+ private static final Logger logger = LoggerFactory.getLogger(NetworkResponseCommon.class);
- public NetworkResponseCommon() {
- messageId = null;
- }
+ public NetworkResponseCommon() {
+ messageId = null;
+ }
- public NetworkResponseCommon(String messageId) {
- this.messageId = messageId;
- }
+ public NetworkResponseCommon(String messageId) {
+ this.messageId = messageId;
+ }
- public String getMessageId() {
- return messageId;
- }
+ public String getMessageId() {
+ return messageId;
+ }
- public void setMessageId(String messageId) {
- this.messageId = messageId;
- }
+ public void setMessageId(String messageId) {
+ this.messageId = messageId;
+ }
- public String toJsonString() {
- String jsonString = null;
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- jsonString = mapper.writeValueAsString(this);
- } catch (Exception e) {
- logger.debug("Exception:", e);
- }
- return jsonString;
- }
+ public String toJsonString() {
+ String jsonString = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ jsonString = mapper.writeValueAsString(this);
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ }
+ return jsonString;
+ }
- public String toXmlString() {
- try {
- ByteArrayOutputStream bs = new ByteArrayOutputStream();
- JAXBContext context = JAXBContext.newInstance(this.getClass());
- Marshaller marshaller = context.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //pretty print XML
- marshaller.marshal(this, bs);
- return bs.toString();
- } catch (Exception e) {
- logger.debug("Exception:", e);
- return "";
- }
- }
+ public String toXmlString() {
+ try {
+ ByteArrayOutputStream bs = new ByteArrayOutputStream();
+ JAXBContext context = JAXBContext.newInstance(this.getClass());
+ Marshaller marshaller = context.createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // pretty print XML
+ marshaller.marshal(this, bs);
+ return bs.toString();
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ return "";
+ }
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkTechnology.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkTechnology.java
index cade9b44c8..963dc18d06 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkTechnology.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/NetworkTechnology.java
@@ -22,5 +22,5 @@ package org.onap.so.adapters.nwrest;
public enum NetworkTechnology {
- NEUTRON, VMWARE, CONTRAIL
+ NEUTRON, VMWARE, CONTRAIL
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/ProviderVlanNetwork.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/ProviderVlanNetwork.java
index fbd21b8197..f6ac9f2f87 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/ProviderVlanNetwork.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/ProviderVlanNetwork.java
@@ -25,37 +25,37 @@ package org.onap.so.adapters.nwrest;
import java.io.Serializable;
import java.util.List;
-public class ProviderVlanNetwork implements Serializable{
- /**
- *
- */
- private static final long serialVersionUID = 6744949861614446315L;
- private String physicalNetworkName;
- private List<Integer> vlans;
-
- public ProviderVlanNetwork() {
- super();
- }
-
- public ProviderVlanNetwork(String physicalNetworkName, List<Integer> vlans) {
- super();
- this.physicalNetworkName = physicalNetworkName;
- this.vlans = vlans;
- }
-
- public String getPhysicalNetworkName() {
- return physicalNetworkName;
- }
-
- public void setPhysicalNetworkName(String physicalNetworkName) {
- this.physicalNetworkName = physicalNetworkName;
- }
-
- public List<Integer> getVlans() {
- return vlans;
- }
-
- public void setVlans(List<Integer> vlans) {
- this.vlans = vlans;
- }
+public class ProviderVlanNetwork implements Serializable {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 6744949861614446315L;
+ private String physicalNetworkName;
+ private List<Integer> vlans;
+
+ public ProviderVlanNetwork() {
+ super();
+ }
+
+ public ProviderVlanNetwork(String physicalNetworkName, List<Integer> vlans) {
+ super();
+ this.physicalNetworkName = physicalNetworkName;
+ this.vlans = vlans;
+ }
+
+ public String getPhysicalNetworkName() {
+ return physicalNetworkName;
+ }
+
+ public void setPhysicalNetworkName(String physicalNetworkName) {
+ this.physicalNetworkName = physicalNetworkName;
+ }
+
+ public List<Integer> getVlans() {
+ return vlans;
+ }
+
+ public void setVlans(List<Integer> vlans) {
+ this.vlans = vlans;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/QueryNetworkError.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/QueryNetworkError.java
index 6e8ace9cf0..22f883008b 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/QueryNetworkError.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/QueryNetworkError.java
@@ -22,10 +22,9 @@ package org.onap.so.adapters.nwrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "queryNetworkError")
public class QueryNetworkError extends NetworkExceptionResponse implements Serializable {
- private static final long serialVersionUID = -6125469596399867146L;
+ private static final long serialVersionUID = -6125469596399867146L;
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/QueryNetworkResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/QueryNetworkResponse.java
index 98b0c8ebec..7fd0f34828 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/QueryNetworkResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/QueryNetworkResponse.java
@@ -25,111 +25,109 @@ package org.onap.so.adapters.nwrest;
import java.util.List;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.beans.NetworkStatus;
import org.onap.so.openstack.beans.RouteTarget;
@XmlRootElement(name = "queryNetworkResponse")
public class QueryNetworkResponse extends NetworkResponseCommon {
- /**
- *
- */
- private static final long serialVersionUID = -5251191073081795026L;
- private String networkId;
- private String neutronNetworkId;
- private String networkStackId;
- private Boolean networkExists;
- private NetworkStatus networkStatus;
- private List<Integer> vlans;
- private List<RouteTarget> routeTargets;
- private Map<String, String> subnetIdMap;
- private Map<String, String> networkOutputs;
-
- public QueryNetworkResponse() {
- super();
- }
-
- public QueryNetworkResponse(String networkId, String neutronNetworkId, String networkStackId,
- NetworkStatus networkStatus, Map<String, String> networkOutputs) {
- super();
- this.networkId = networkId;
- this.neutronNetworkId = neutronNetworkId;
- this.networkStackId = networkStackId;
- this.networkStatus = networkStatus;
- this.networkOutputs = networkOutputs;
- }
-
- public String getNetworkId() {
- return networkId;
- }
-
- public void setNetworkId(String networkId) {
- this.networkId = networkId;
- }
-
- public String getNeutronNetworkId() {
- return neutronNetworkId;
- }
-
- public void setNeutronNetworkId(String neutronNetworkId) {
- this.neutronNetworkId = neutronNetworkId;
- }
-
- public String getNetworkStackId() {
- return networkStackId;
- }
-
- public void setNetworkStackId(String networkStackId) {
- this.networkStackId = networkStackId;
- }
-
- public NetworkStatus getNetworkStatus() {
- return networkStatus;
- }
-
- public void setNetworkStatus(NetworkStatus networkStatus) {
- this.networkStatus = networkStatus;
- }
-
- public Boolean getNetworkExists() {
- return networkExists;
- }
-
- public void setNetworkExists(Boolean networkExists) {
- this.networkExists = networkExists;
- }
-
- public List<Integer> getVlans() {
- return vlans;
- }
-
- public void setVlans(List<Integer> vlans) {
- this.vlans = vlans;
- }
-
- public List<RouteTarget> getRouteTargets() {
- return routeTargets;
- }
-
- public void setRouteTargets(List<RouteTarget> routeTargets) {
- this.routeTargets = routeTargets;
- }
-
- public Map<String, String> getSubnetIdMap() {
- return subnetIdMap;
- }
-
- public void setSubnetIdMap(Map<String, String> subnetIdMap) {
- this.subnetIdMap = subnetIdMap;
- }
-
- public Map<String, String> getNetworkOutputs() {
- return networkOutputs;
- }
-
- public void setNetworkOutputs(Map<String, String> networkOutputs) {
- this.networkOutputs = networkOutputs;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -5251191073081795026L;
+ private String networkId;
+ private String neutronNetworkId;
+ private String networkStackId;
+ private Boolean networkExists;
+ private NetworkStatus networkStatus;
+ private List<Integer> vlans;
+ private List<RouteTarget> routeTargets;
+ private Map<String, String> subnetIdMap;
+ private Map<String, String> networkOutputs;
+
+ public QueryNetworkResponse() {
+ super();
+ }
+
+ public QueryNetworkResponse(String networkId, String neutronNetworkId, String networkStackId,
+ NetworkStatus networkStatus, Map<String, String> networkOutputs) {
+ super();
+ this.networkId = networkId;
+ this.neutronNetworkId = neutronNetworkId;
+ this.networkStackId = networkStackId;
+ this.networkStatus = networkStatus;
+ this.networkOutputs = networkOutputs;
+ }
+
+ public String getNetworkId() {
+ return networkId;
+ }
+
+ public void setNetworkId(String networkId) {
+ this.networkId = networkId;
+ }
+
+ public String getNeutronNetworkId() {
+ return neutronNetworkId;
+ }
+
+ public void setNeutronNetworkId(String neutronNetworkId) {
+ this.neutronNetworkId = neutronNetworkId;
+ }
+
+ public String getNetworkStackId() {
+ return networkStackId;
+ }
+
+ public void setNetworkStackId(String networkStackId) {
+ this.networkStackId = networkStackId;
+ }
+
+ public NetworkStatus getNetworkStatus() {
+ return networkStatus;
+ }
+
+ public void setNetworkStatus(NetworkStatus networkStatus) {
+ this.networkStatus = networkStatus;
+ }
+
+ public Boolean getNetworkExists() {
+ return networkExists;
+ }
+
+ public void setNetworkExists(Boolean networkExists) {
+ this.networkExists = networkExists;
+ }
+
+ public List<Integer> getVlans() {
+ return vlans;
+ }
+
+ public void setVlans(List<Integer> vlans) {
+ this.vlans = vlans;
+ }
+
+ public List<RouteTarget> getRouteTargets() {
+ return routeTargets;
+ }
+
+ public void setRouteTargets(List<RouteTarget> routeTargets) {
+ this.routeTargets = routeTargets;
+ }
+
+ public Map<String, String> getSubnetIdMap() {
+ return subnetIdMap;
+ }
+
+ public void setSubnetIdMap(Map<String, String> subnetIdMap) {
+ this.subnetIdMap = subnetIdMap;
+ }
+
+ public Map<String, String> getNetworkOutputs() {
+ return networkOutputs;
+ }
+
+ public void setNetworkOutputs(Map<String, String> networkOutputs) {
+ this.networkOutputs = networkOutputs;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkError.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkError.java
index cb148dfcef..1cdc48fc69 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkError.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkError.java
@@ -22,24 +22,22 @@ package org.onap.so.adapters.nwrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
@XmlRootElement(name = "rollbackNetworkError")
public class RollbackNetworkError extends NetworkExceptionResponse implements Serializable {
- private static final long serialVersionUID = -3954464103037391980L;
+ private static final long serialVersionUID = -3954464103037391980L;
- public RollbackNetworkError() {
- super("");
- }
+ public RollbackNetworkError() {
+ super("");
+ }
- public RollbackNetworkError(String message) {
- super(message);
- }
+ public RollbackNetworkError(String message) {
+ super(message);
+ }
- public RollbackNetworkError(String message, MsoExceptionCategory category, boolean unused, String messageid) {
- super(message, category, unused, messageid);
- }
+ public RollbackNetworkError(String message, MsoExceptionCategory category, boolean unused, String messageid) {
+ super(message, category, unused, messageid);
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkRequest.java
index 494d3123d1..a53d578da2 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkRequest.java
@@ -23,29 +23,27 @@ package org.onap.so.adapters.nwrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.beans.NetworkRollback;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("rollbackNetworkRequest")
@XmlRootElement(name = "rollbackNetworkRequest")
public class RollbackNetworkRequest extends NetworkRequestCommon {
- /**
- *
- */
- private static final long serialVersionUID = -8705660877263749940L;
- private NetworkRollback networkRollback;
-
- public RollbackNetworkRequest() {
- super();
- }
-
- public NetworkRollback getNetworkRollback() {
- return networkRollback;
- }
-
- public void setNetworkRollback(NetworkRollback networkRollback) {
- this.networkRollback = networkRollback;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -8705660877263749940L;
+ private NetworkRollback networkRollback;
+
+ public RollbackNetworkRequest() {
+ super();
+ }
+
+ public NetworkRollback getNetworkRollback() {
+ return networkRollback;
+ }
+
+ public void setNetworkRollback(NetworkRollback networkRollback) {
+ this.networkRollback = networkRollback;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkResponse.java
index 9be8bb3a69..b9632cc7d9 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/RollbackNetworkResponse.java
@@ -23,7 +23,6 @@ package org.onap.so.adapters.nwrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -31,26 +30,26 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@XmlRootElement(name = "rollbackNetworkResponse")
public class RollbackNetworkResponse extends NetworkResponseCommon {
- /**
- *
- */
- private static final long serialVersionUID = 3115905123337163846L;
- private Boolean networkRolledBack;
-
- public RollbackNetworkResponse() {
- super();
- }
-
- public RollbackNetworkResponse(Boolean networkRolledBack, String messageId) {
- super(messageId);
- this.networkRolledBack = networkRolledBack;
- }
-
- public Boolean getNetworkRolledBack() {
- return networkRolledBack;
- }
-
- public void setNetworkRolledBack(Boolean networkRolledBack) {
- this.networkRolledBack = networkRolledBack;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = 3115905123337163846L;
+ private Boolean networkRolledBack;
+
+ public RollbackNetworkResponse() {
+ super();
+ }
+
+ public RollbackNetworkResponse(Boolean networkRolledBack, String messageId) {
+ super(messageId);
+ this.networkRolledBack = networkRolledBack;
+ }
+
+ public Boolean getNetworkRolledBack() {
+ return networkRolledBack;
+ }
+
+ public void setNetworkRolledBack(Boolean networkRolledBack) {
+ this.networkRolledBack = networkRolledBack;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkError.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkError.java
index 642ac4cc64..59122f3d8d 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkError.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkError.java
@@ -22,24 +22,22 @@ package org.onap.so.adapters.nwrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
@XmlRootElement(name = "updateNetworkError")
public class UpdateNetworkError extends NetworkExceptionResponse implements Serializable {
- private static final long serialVersionUID = 46820809807914392L;
+ private static final long serialVersionUID = 46820809807914392L;
- public UpdateNetworkError() {
- super("");
- }
+ public UpdateNetworkError() {
+ super("");
+ }
- public UpdateNetworkError(String message) {
- super(message);
- }
+ public UpdateNetworkError(String message) {
+ super(message);
+ }
- public UpdateNetworkError(String message, MsoExceptionCategory category, boolean unused, String messageid) {
- super(message, category, unused, messageid);
- }
+ public UpdateNetworkError(String message, MsoExceptionCategory category, boolean unused, String messageid) {
+ super(message, category, unused, messageid);
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkRequest.java
index 595662251f..9d01697e32 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkRequest.java
@@ -27,12 +27,9 @@ package org.onap.so.adapters.nwrest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.entity.MsoRequest;
import org.onap.so.openstack.beans.Subnet;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -40,157 +37,160 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("updateNetworkRequest")
@XmlRootElement(name = "updateNetworkRequest")
public class UpdateNetworkRequest extends NetworkRequestCommon {
- /**
- *
- */
- private static final long serialVersionUID = -1219693235726357143L;
- private String cloudSiteId;
- private String tenantId;
- private String networkId;
- private String networkStackId;
- private String networkName;
- private String networkType;
- private String networkTypeVersion;
- private String modelCustomizationUuid;
- private String networkTechnology = "NEUTRON";
- private List<Subnet> subnets;
- private ProviderVlanNetwork providerVlanNetwork;
- private ContrailNetwork contrailNetwork;
- private Boolean backout = true;
- private Map<String,String> networkParams = new HashMap<>();
- private MsoRequest msoRequest = new MsoRequest();
-
- @JsonProperty
- private boolean contrailRequest;
- public UpdateNetworkRequest() {
- super();
- }
-
- public String getCloudSiteId() {
- return cloudSiteId;
- }
-
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
-
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getNetworkId() {
- return networkId;
- }
-
- public void setNetworkId(String networkId) {
- this.networkId = networkId;
- }
-
- public String getNetworkStackId() {
- return networkStackId;
- }
-
- public void setNetworkStackId(String networkStackId) {
- this.networkStackId = networkStackId;
- }
-
- public String getNetworkName() {
- return networkName;
- }
-
- public void setNetworkName(String networkName) {
- this.networkName = networkName;
- }
-
- public String getNetworkType() {
- return networkType;
- }
-
- public void setNetworkType(String networkType) {
- this.networkType = networkType;
- }
-
- public String getModelCustomizationUuid() {
- return this.modelCustomizationUuid;
- }
-
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
-
- public String getNetworkTypeVersion() {
- return networkTypeVersion;
- }
-
- public void setNetworkTypeVersion(String networkTypeVersion) {
- this.networkTypeVersion = networkTypeVersion;
- }
-
- public String getNetworkTechnology() {
- return networkTechnology;
- }
-
- public void setNetworkTechnology(String networkTechnology) {
- this.networkTechnology = networkTechnology;
- }
-
- public List<Subnet> getSubnets() {
- return subnets;
- }
-
- public void setSubnets(List<Subnet> subnets) {
- this.subnets = subnets;
- }
-
- public ProviderVlanNetwork getProviderVlanNetwork() {
- return providerVlanNetwork;
- }
-
- public void setProviderVlanNetwork(ProviderVlanNetwork providerVlanNetwork) {
- this.providerVlanNetwork = providerVlanNetwork;
- }
-
- public ContrailNetwork getContrailNetwork() {
- return contrailNetwork;
- }
-
- public void setContrailNetwork(ContrailNetwork contrailNetwork) {
- this.contrailNetwork = contrailNetwork;
- }
-
- public Boolean getBackout() {
- return backout;
- }
-
- public void setBackout(Boolean backout) {
- this.backout = backout;
- }
-
- public Map<String, String> getNetworkParams() {
- return networkParams;
- }
-
- public void setNetworkParams(Map<String, String> networkParams) {
- this.networkParams = networkParams;
- }
-
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
-
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
- @JsonIgnore
- protected void setContrailRequest(boolean contrailRequest) {
- this.contrailRequest = contrailRequest;
- }
- public boolean isContrailRequest() {
- return contrailRequest;
- }
-
+ /**
+ *
+ */
+ private static final long serialVersionUID = -1219693235726357143L;
+ private String cloudSiteId;
+ private String tenantId;
+ private String networkId;
+ private String networkStackId;
+ private String networkName;
+ private String networkType;
+ private String networkTypeVersion;
+ private String modelCustomizationUuid;
+ private String networkTechnology = "NEUTRON";
+ private List<Subnet> subnets;
+ private ProviderVlanNetwork providerVlanNetwork;
+ private ContrailNetwork contrailNetwork;
+ private Boolean backout = true;
+ private Map<String, String> networkParams = new HashMap<>();
+ private MsoRequest msoRequest = new MsoRequest();
+
+ @JsonProperty
+ private boolean contrailRequest;
+
+ public UpdateNetworkRequest() {
+ super();
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getNetworkId() {
+ return networkId;
+ }
+
+ public void setNetworkId(String networkId) {
+ this.networkId = networkId;
+ }
+
+ public String getNetworkStackId() {
+ return networkStackId;
+ }
+
+ public void setNetworkStackId(String networkStackId) {
+ this.networkStackId = networkStackId;
+ }
+
+ public String getNetworkName() {
+ return networkName;
+ }
+
+ public void setNetworkName(String networkName) {
+ this.networkName = networkName;
+ }
+
+ public String getNetworkType() {
+ return networkType;
+ }
+
+ public void setNetworkType(String networkType) {
+ this.networkType = networkType;
+ }
+
+ public String getModelCustomizationUuid() {
+ return this.modelCustomizationUuid;
+ }
+
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ public String getNetworkTypeVersion() {
+ return networkTypeVersion;
+ }
+
+ public void setNetworkTypeVersion(String networkTypeVersion) {
+ this.networkTypeVersion = networkTypeVersion;
+ }
+
+ public String getNetworkTechnology() {
+ return networkTechnology;
+ }
+
+ public void setNetworkTechnology(String networkTechnology) {
+ this.networkTechnology = networkTechnology;
+ }
+
+ public List<Subnet> getSubnets() {
+ return subnets;
+ }
+
+ public void setSubnets(List<Subnet> subnets) {
+ this.subnets = subnets;
+ }
+
+ public ProviderVlanNetwork getProviderVlanNetwork() {
+ return providerVlanNetwork;
+ }
+
+ public void setProviderVlanNetwork(ProviderVlanNetwork providerVlanNetwork) {
+ this.providerVlanNetwork = providerVlanNetwork;
+ }
+
+ public ContrailNetwork getContrailNetwork() {
+ return contrailNetwork;
+ }
+
+ public void setContrailNetwork(ContrailNetwork contrailNetwork) {
+ this.contrailNetwork = contrailNetwork;
+ }
+
+ public Boolean getBackout() {
+ return backout;
+ }
+
+ public void setBackout(Boolean backout) {
+ this.backout = backout;
+ }
+
+ public Map<String, String> getNetworkParams() {
+ return networkParams;
+ }
+
+ public void setNetworkParams(Map<String, String> networkParams) {
+ this.networkParams = networkParams;
+ }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
+
+ @JsonIgnore
+ protected void setContrailRequest(boolean contrailRequest) {
+ this.contrailRequest = contrailRequest;
+ }
+
+ public boolean isContrailRequest() {
+ return contrailRequest;
+ }
+
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkResponse.java
index 7ce66ba58e..3dee803786 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/nwrest/UpdateNetworkResponse.java
@@ -23,56 +23,54 @@ package org.onap.so.adapters.nwrest;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("updateNetworkResponse")
@XmlRootElement(name = "updateNetworkResponse")
public class UpdateNetworkResponse extends NetworkResponseCommon {
-
- /**
- *
- */
- private static final long serialVersionUID = -7528214382414366136L;
- private String networkId;
- private String neutronNetworkId;
- private Map<String, String> subnetMap;
- public UpdateNetworkResponse() {
- /* Empty Constructor */
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -7528214382414366136L;
+ private String networkId;
+ private String neutronNetworkId;
+ private Map<String, String> subnetMap;
+
+ public UpdateNetworkResponse() {
+ /* Empty Constructor */
+ }
- public UpdateNetworkResponse(String networkId, String neutronNetworkId,
- Map<String, String> subnetMap, String messageId) {
- super(messageId);
- this.networkId = networkId;
- this.neutronNetworkId = neutronNetworkId;
- this.subnetMap = subnetMap;
- }
+ public UpdateNetworkResponse(String networkId, String neutronNetworkId, Map<String, String> subnetMap,
+ String messageId) {
+ super(messageId);
+ this.networkId = networkId;
+ this.neutronNetworkId = neutronNetworkId;
+ this.subnetMap = subnetMap;
+ }
- public String getNetworkId() {
- return networkId;
- }
+ public String getNetworkId() {
+ return networkId;
+ }
- public void setNetworkId(String networkId) {
- this.networkId = networkId;
- }
+ public void setNetworkId(String networkId) {
+ this.networkId = networkId;
+ }
- public String getNeutronNetworkId() {
- return neutronNetworkId;
- }
+ public String getNeutronNetworkId() {
+ return neutronNetworkId;
+ }
- public void setNeutronNetworkId(String neutronNetworkId) {
- this.neutronNetworkId = neutronNetworkId;
- }
+ public void setNeutronNetworkId(String neutronNetworkId) {
+ this.neutronNetworkId = neutronNetworkId;
+ }
- public Map<String, String> getSubnetMap() {
- return subnetMap;
- }
+ public Map<String, String> getSubnetMap() {
+ return subnetMap;
+ }
- public void setSubnetMap(Map<String, String> subnetMap) {
- this.subnetMap = subnetMap;
- }
+ public void setSubnetMap(Map<String, String> subnetMap) {
+ this.subnetMap = subnetMap;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/RequestInformation.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/RequestInformation.java
index ae7ff27bed..7c4018b591 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/RequestInformation.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/RequestInformation.java
@@ -21,123 +21,120 @@
package org.onap.so.adapters.sdncrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlElement;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Request Information specified by the SDNC "agnostic" API.
*/
public class RequestInformation implements Serializable {
- private static final long serialVersionUID = 1L;
-
- // Identifies the transaction MSO has with the calling system.
- private String requestId;
-
- // Identifies the calling system, e.g. CCD.
- private String source;
-
- // The calling system's endpoint for receiving notifications from MSO.
- private String notificationUrl;
-
- // NOTE: these are defined in the SDNC AID, but not used by MSO:
- // request-action
- // request-sub-action
-
- // Identifies the request action
- private String requestAction;
-
- // Identifies the request sub action
- private String requestSubAction;
-
- @JsonProperty("orderNumber")
- @XmlElement(name = "orderNumber")
- private String orderNumber;
-
- @JsonProperty("orderVersion")
- @XmlElement(name = "orderVersion")
- private String orderVersion;
-
- public RequestInformation(String requestId, String source, String notificationUrl) {
- this.requestId = requestId;
- this.source = source;
- this.notificationUrl = notificationUrl;
- }
-
- public RequestInformation() {
- }
-
- @JsonProperty("requestId")
- @XmlElement(name = "requestId")
- public String getRequestId() {
- return requestId;
- }
-
- @JsonProperty("requestId")
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
- @JsonProperty("source")
- @XmlElement(name = "source")
- public String getSource() {
- return source;
- }
-
- @JsonProperty("source")
- public void setSource(String source) {
- this.source = source;
- }
-
- @JsonProperty("notificationUrl")
- @XmlElement(name = "notificationUrl")
- public String getNotificationUrl() {
- return notificationUrl;
- }
-
- @JsonProperty("notificationUrl")
- public void setNotificationUrl(String notificationUrl) {
- this.notificationUrl = notificationUrl;
- }
-
- @JsonProperty("requestAction")
- @XmlElement(name = "requestAction")
- public String getRequestAction() {
- return requestAction;
- }
-
- @JsonProperty("requestAction")
- public void setRequestAction(String requestAction) {
- this.requestAction = requestAction;
- }
-
- @JsonProperty("requestSubAction")
- @XmlElement(name = "requestSubAction")
- public String getRequestSubAction() {
- return requestSubAction;
- }
-
- @JsonProperty("requestSubAction")
- public void setRequestSubAction(String requestSubAction) {
- this.requestSubAction = requestSubAction;
- }
-
- public String getOrderNumber() {
- return orderNumber;
- }
-
- public void setOrderNumber(String orderNumber) {
- this.orderNumber = orderNumber;
- }
-
- public String getOrderVersion() {
- return orderVersion;
- }
-
- public void setOrderVersion(String orderVersion) {
- this.orderVersion = orderVersion;
- }
-
-
-} \ No newline at end of file
+ private static final long serialVersionUID = 1L;
+
+ // Identifies the transaction MSO has with the calling system.
+ private String requestId;
+
+ // Identifies the calling system, e.g. CCD.
+ private String source;
+
+ // The calling system's endpoint for receiving notifications from MSO.
+ private String notificationUrl;
+
+ // NOTE: these are defined in the SDNC AID, but not used by MSO:
+ // request-action
+ // request-sub-action
+
+ // Identifies the request action
+ private String requestAction;
+
+ // Identifies the request sub action
+ private String requestSubAction;
+
+ @JsonProperty("orderNumber")
+ @XmlElement(name = "orderNumber")
+ private String orderNumber;
+
+ @JsonProperty("orderVersion")
+ @XmlElement(name = "orderVersion")
+ private String orderVersion;
+
+ public RequestInformation(String requestId, String source, String notificationUrl) {
+ this.requestId = requestId;
+ this.source = source;
+ this.notificationUrl = notificationUrl;
+ }
+
+ public RequestInformation() {}
+
+ @JsonProperty("requestId")
+ @XmlElement(name = "requestId")
+ public String getRequestId() {
+ return requestId;
+ }
+
+ @JsonProperty("requestId")
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ @JsonProperty("source")
+ @XmlElement(name = "source")
+ public String getSource() {
+ return source;
+ }
+
+ @JsonProperty("source")
+ public void setSource(String source) {
+ this.source = source;
+ }
+
+ @JsonProperty("notificationUrl")
+ @XmlElement(name = "notificationUrl")
+ public String getNotificationUrl() {
+ return notificationUrl;
+ }
+
+ @JsonProperty("notificationUrl")
+ public void setNotificationUrl(String notificationUrl) {
+ this.notificationUrl = notificationUrl;
+ }
+
+ @JsonProperty("requestAction")
+ @XmlElement(name = "requestAction")
+ public String getRequestAction() {
+ return requestAction;
+ }
+
+ @JsonProperty("requestAction")
+ public void setRequestAction(String requestAction) {
+ this.requestAction = requestAction;
+ }
+
+ @JsonProperty("requestSubAction")
+ @XmlElement(name = "requestSubAction")
+ public String getRequestSubAction() {
+ return requestSubAction;
+ }
+
+ @JsonProperty("requestSubAction")
+ public void setRequestSubAction(String requestSubAction) {
+ this.requestSubAction = requestSubAction;
+ }
+
+ public String getOrderNumber() {
+ return orderNumber;
+ }
+
+ public void setOrderNumber(String orderNumber) {
+ this.orderNumber = orderNumber;
+ }
+
+ public String getOrderVersion() {
+ return orderVersion;
+ }
+
+ public void setOrderVersion(String orderVersion) {
+ this.orderVersion = orderVersion;
+ }
+
+
+}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCErrorCommon.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCErrorCommon.java
index b6cd6a1eed..e80976c99e 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCErrorCommon.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCErrorCommon.java
@@ -26,13 +26,12 @@ import java.io.Serializable;
* Base class for all SDNC adapter error responses.
*/
public abstract class SDNCErrorCommon extends SDNCResponseCommon implements Serializable {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- public SDNCErrorCommon(String sdncRequestId, String responseCode,
- String responseMessage, String ackFinalIndicator) {
- super(sdncRequestId, responseCode, responseMessage, ackFinalIndicator);
- }
+ public SDNCErrorCommon(String sdncRequestId, String responseCode, String responseMessage,
+ String ackFinalIndicator) {
+ super(sdncRequestId, responseCode, responseMessage, ackFinalIndicator);
+ }
- public SDNCErrorCommon() {
- }
-} \ No newline at end of file
+ public SDNCErrorCommon() {}
+}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCEvent.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCEvent.java
index f577fa9b59..b79102857b 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCEvent.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCEvent.java
@@ -26,10 +26,8 @@ import java.io.IOException;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -40,104 +38,103 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// NOTE: the JAXB (XML) annotations are required with JBoss AS7 and RESTEasy,
-// even though we are using JSON exclusively. The @NoJackson annotation
-// is also required in this environment.
+// even though we are using JSON exclusively. The @NoJackson annotation
+// is also required in this environment.
/**
- Map<String, String> elements when marshalled to XML produce a list of <entry><key>${MsoUtils.xmlEscape(key)}</key><value>${MsoUtils.xmlEscape(value)}</value></entry> elements.
- When marshalling to JSON they create a list of "${key}" : "${value}" pairs with no extra wrappers.
+ * Map<String, String> elements when marshalled to XML produce a list of
+ * <entry><key>${MsoUtils.xmlEscape(key)}</key><value>${MsoUtils.xmlEscape(value)}</value></entry> elements. When
+ * marshalling to JSON they create a list of "${key}" : "${value}" pairs with no extra wrappers.
* </pre>
*/
@JsonRootName("SDNCEvent")
@JsonInclude(Include.NON_NULL)
@XmlRootElement(name = "SDNCEvent")
public class SDNCEvent implements Serializable {
- private static final long serialVersionUID = 1L;
-
- private static final Logger logger = LoggerFactory.getLogger(SDNCEvent.class);
-
- // Event type
- private String eventType;
-
- // Event correlator type
- private String eventCorrelatorType;
-
- // Event correlator value.
- private String eventCorrelator;
-
- // Map of response parameters (possibly none).
- private Map<String, String> params = null;
-
- public SDNCEvent(String eventType, String eventCorrelatorType, String eventCorrelator) {
- this.eventType = eventType;
- this.eventCorrelatorType = eventCorrelatorType;
- this.eventCorrelator = eventCorrelator;
- }
-
- public SDNCEvent() {
- }
-
- @JsonProperty("eventType")
- @XmlElement(name = "eventType")
- public String getEventType() {
- return eventType;
- }
-
- @JsonProperty("eventType")
- public void setEventType(String eventType) {
- this.eventType = eventType;
- }
-
- @JsonProperty("eventCorrelatorType")
- @XmlElement(name = "eventCorrelatorType")
- public String getEventCorrelatorType() {
- return eventCorrelatorType;
- }
-
- @JsonProperty("eventCorrelatorType")
- public void setEventCorrelatorType(String eventCorrelatorType) {
- this.eventCorrelatorType = eventCorrelatorType;
- }
-
- @JsonProperty("eventCorrelator")
- @XmlElement(name = "eventCorrelator")
- public String getEventCorrelator() {
- return eventCorrelator;
- }
-
- @JsonProperty("eventCorrelator")
- public void setEventCorrelator(String eventCorrelator) {
- this.eventCorrelator = eventCorrelator;
- }
-
- @JsonProperty("params")
- @XmlElement(name = "params")
- public Map<String, String> getParams() {
- return params;
- }
-
- @JsonProperty("params")
- public void setParams(Map<String, String> params) {
- this.params = params;
- }
-
- public void addParam(String name, String value) {
- if (params == null) {
- params = new LinkedHashMap<>();
- }
- params.put(name, value);
- }
-
- public String toJson() {
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.setSerializationInclusion(Include.NON_NULL);
- return mapper.writeValueAsString(this);
- } catch (IOException e) {
- logger.debug("Exception:", e);
- throw new UnsupportedOperationException("Cannot convert "
- + getClass().getSimpleName() + " to JSON", e);
- }
- }
+ private static final long serialVersionUID = 1L;
+
+ private static final Logger logger = LoggerFactory.getLogger(SDNCEvent.class);
+
+ // Event type
+ private String eventType;
+
+ // Event correlator type
+ private String eventCorrelatorType;
+
+ // Event correlator value.
+ private String eventCorrelator;
+
+ // Map of response parameters (possibly none).
+ private Map<String, String> params = null;
+
+ public SDNCEvent(String eventType, String eventCorrelatorType, String eventCorrelator) {
+ this.eventType = eventType;
+ this.eventCorrelatorType = eventCorrelatorType;
+ this.eventCorrelator = eventCorrelator;
+ }
+
+ public SDNCEvent() {}
+
+ @JsonProperty("eventType")
+ @XmlElement(name = "eventType")
+ public String getEventType() {
+ return eventType;
+ }
+
+ @JsonProperty("eventType")
+ public void setEventType(String eventType) {
+ this.eventType = eventType;
+ }
+
+ @JsonProperty("eventCorrelatorType")
+ @XmlElement(name = "eventCorrelatorType")
+ public String getEventCorrelatorType() {
+ return eventCorrelatorType;
+ }
+
+ @JsonProperty("eventCorrelatorType")
+ public void setEventCorrelatorType(String eventCorrelatorType) {
+ this.eventCorrelatorType = eventCorrelatorType;
+ }
+
+ @JsonProperty("eventCorrelator")
+ @XmlElement(name = "eventCorrelator")
+ public String getEventCorrelator() {
+ return eventCorrelator;
+ }
+
+ @JsonProperty("eventCorrelator")
+ public void setEventCorrelator(String eventCorrelator) {
+ this.eventCorrelator = eventCorrelator;
+ }
+
+ @JsonProperty("params")
+ @XmlElement(name = "params")
+ public Map<String, String> getParams() {
+ return params;
+ }
+
+ @JsonProperty("params")
+ public void setParams(Map<String, String> params) {
+ this.params = params;
+ }
+
+ public void addParam(String name, String value) {
+ if (params == null) {
+ params = new LinkedHashMap<>();
+ }
+ params.put(name, value);
+ }
+
+ public String toJson() {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.setSerializationInclusion(Include.NON_NULL);
+ return mapper.writeValueAsString(this);
+ } catch (IOException e) {
+ logger.debug("Exception:", e);
+ throw new UnsupportedOperationException("Cannot convert " + getClass().getSimpleName() + " to JSON", e);
+ }
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCRequestCommon.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCRequestCommon.java
index 4080705551..60e1ce088c 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCRequestCommon.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCRequestCommon.java
@@ -24,15 +24,12 @@ package org.onap.so.adapters.sdncrest;
import java.io.IOException;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlElement;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -40,79 +37,76 @@ import org.slf4j.LoggerFactory;
* Base class for all SDNC adapter requests.
*/
public abstract class SDNCRequestCommon implements Serializable {
- private static final long serialVersionUID = 1L;
-
- private static final Logger logger = LoggerFactory.getLogger(SDNCRequestCommon.class);
-
- // Endpoint on which BPMN can receive notifications from the SDNC adapter.
- private String bpNotificationUrl;
-
- // BPMN flow timeout value in ISO 8601 format, e.g. PT5M.
- // Not currently used by the SDNC adapter.
- private String bpTimeout;
-
- // Identifies the MSO transaction with SDNC.
- // Maps to sdnc-request-header/requestId in the SDNC request.
- private String sdncRequestId;
-
- public SDNCRequestCommon(String sdncRequestId, String bpNotificationUrl,
- String bpTimeout) {
- this.sdncRequestId = sdncRequestId;
- this.bpNotificationUrl = bpNotificationUrl;
- this.bpTimeout = bpTimeout;
- }
-
- public SDNCRequestCommon() {
- }
-
- @JsonProperty("bpNotificationUrl")
- @XmlElement(name = "bpNotificationUrl")
- public String getBPNotificationUrl() {
- return bpNotificationUrl;
- }
-
- @JsonProperty("bpNotificationUrl")
- public void setBPNotificationUrl(String bpNotificationUrl) {
- this.bpNotificationUrl = bpNotificationUrl;
- }
-
- @JsonProperty("bpTimeout")
- @XmlElement(name = "bpTimeout")
- public String getBPTimeout() {
- return bpTimeout;
- }
-
- @JsonProperty("bpTimeout")
- public void setBPTimeout(String bpTimeout) {
- this.bpTimeout = bpTimeout;
- }
-
- @JsonProperty("sdncRequestId")
- @XmlElement(name = "sdncRequestId")
- public String getSdncRequestId() {
- return sdncRequestId;
- }
-
- @JsonProperty("sdncRequestId")
- public void setSdncRequestId(String sdncRequestId) {
- this.sdncRequestId = sdncRequestId;
- }
-
- @JsonIgnore
- public boolean isSynchronous() {
- return bpNotificationUrl == null || bpNotificationUrl.isEmpty();
- }
-
- public String toJson() {
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.setSerializationInclusion(Include.NON_NULL);
- return mapper.writeValueAsString(this);
- } catch (IOException e) {
- logger.debug("Exception:", e);
- throw new UnsupportedOperationException("Cannot convert "
- + getClass().getSimpleName() + " to JSON", e);
- }
- }
+ private static final long serialVersionUID = 1L;
+
+ private static final Logger logger = LoggerFactory.getLogger(SDNCRequestCommon.class);
+
+ // Endpoint on which BPMN can receive notifications from the SDNC adapter.
+ private String bpNotificationUrl;
+
+ // BPMN flow timeout value in ISO 8601 format, e.g. PT5M.
+ // Not currently used by the SDNC adapter.
+ private String bpTimeout;
+
+ // Identifies the MSO transaction with SDNC.
+ // Maps to sdnc-request-header/requestId in the SDNC request.
+ private String sdncRequestId;
+
+ public SDNCRequestCommon(String sdncRequestId, String bpNotificationUrl, String bpTimeout) {
+ this.sdncRequestId = sdncRequestId;
+ this.bpNotificationUrl = bpNotificationUrl;
+ this.bpTimeout = bpTimeout;
+ }
+
+ public SDNCRequestCommon() {}
+
+ @JsonProperty("bpNotificationUrl")
+ @XmlElement(name = "bpNotificationUrl")
+ public String getBPNotificationUrl() {
+ return bpNotificationUrl;
+ }
+
+ @JsonProperty("bpNotificationUrl")
+ public void setBPNotificationUrl(String bpNotificationUrl) {
+ this.bpNotificationUrl = bpNotificationUrl;
+ }
+
+ @JsonProperty("bpTimeout")
+ @XmlElement(name = "bpTimeout")
+ public String getBPTimeout() {
+ return bpTimeout;
+ }
+
+ @JsonProperty("bpTimeout")
+ public void setBPTimeout(String bpTimeout) {
+ this.bpTimeout = bpTimeout;
+ }
+
+ @JsonProperty("sdncRequestId")
+ @XmlElement(name = "sdncRequestId")
+ public String getSdncRequestId() {
+ return sdncRequestId;
+ }
+
+ @JsonProperty("sdncRequestId")
+ public void setSdncRequestId(String sdncRequestId) {
+ this.sdncRequestId = sdncRequestId;
+ }
+
+ @JsonIgnore
+ public boolean isSynchronous() {
+ return bpNotificationUrl == null || bpNotificationUrl.isEmpty();
+ }
+
+ public String toJson() {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.setSerializationInclusion(Include.NON_NULL);
+ return mapper.writeValueAsString(this);
+ } catch (IOException e) {
+ logger.debug("Exception:", e);
+ throw new UnsupportedOperationException("Cannot convert " + getClass().getSimpleName() + " to JSON", e);
+ }
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCResponseCommon.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCResponseCommon.java
index a7d14cce69..5851493fea 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCResponseCommon.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCResponseCommon.java
@@ -24,14 +24,11 @@ package org.onap.so.adapters.sdncrest;
import java.io.IOException;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlElement;
-
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,88 +36,86 @@ import org.slf4j.LoggerFactory;
* Base class for all SDNC adapter responses, including errors.
*/
public abstract class SDNCResponseCommon implements Serializable {
- private static final long serialVersionUID = 1L;
-
- private static final Logger logger = LoggerFactory.getLogger(SDNCResponseCommon.class);
-
- // Identifies the MSO transaction with SDNC.
- private String sdncRequestId;
-
- // Response code, either from SDNC, or generated by the SDNC adapter.
- // 2XX responses are considered success responses.
- private String responseCode;
-
- // Response message, either from SDNC, or generated by the SDNC adapter.
- private String responseMessage;
-
- // Indicates if the response is final (Y or N).
- private String ackFinalIndicator;
-
- public SDNCResponseCommon(String sdncRequestId, String responseCode,
- String responseMessage, String ackFinalIndicator) {
- this.sdncRequestId = sdncRequestId;
- this.responseCode = responseCode;
- this.responseMessage = responseMessage;
- this.ackFinalIndicator = ackFinalIndicator;
- }
-
- public SDNCResponseCommon() {
- }
-
- @JsonProperty("sdncRequestId")
- @XmlElement(name = "sdncRequestId")
- public String getSdncRequestId() {
- return sdncRequestId;
- }
-
- @JsonProperty("sdncRequestId")
- public void setSdncRequestId(String sdncRequestId) {
- this.sdncRequestId = sdncRequestId;
- }
-
- @JsonProperty("responseCode")
- @XmlElement(name = "responseCode")
- public String getResponseCode() {
- return responseCode;
- }
-
- @JsonProperty("responseCode")
- public void setResponseCode(String responseCode) {
- this.responseCode = responseCode;
- }
-
- @JsonProperty("responseMessage")
- @XmlElement(name = "responseMessage")
- public String getResponseMessage() {
- return responseMessage;
- }
-
- @JsonProperty("responseMessage")
- public void setResponseMessage(String responseMessage) {
- this.responseMessage = responseMessage;
- }
-
- @JsonProperty("ackFinalIndicator")
- @XmlElement(name = "ackFinalIndicator")
- public String getAckFinalIndicator() {
- return ackFinalIndicator;
- }
-
- @JsonProperty("ackFinalIndicator")
- public void setAckFinalIndicator(String ackFinalIndicator) {
- this.ackFinalIndicator = ackFinalIndicator;
- }
-
- public String toJson() {
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.setSerializationInclusion(Include.NON_NULL);
- return mapper.writeValueAsString(this);
- } catch (IOException e) {
- logger.debug("Exception:", e);
- throw new UnsupportedOperationException("Cannot convert "
- + getClass().getSimpleName() + " to JSON", e);
- }
- }
+ private static final long serialVersionUID = 1L;
+
+ private static final Logger logger = LoggerFactory.getLogger(SDNCResponseCommon.class);
+
+ // Identifies the MSO transaction with SDNC.
+ private String sdncRequestId;
+
+ // Response code, either from SDNC, or generated by the SDNC adapter.
+ // 2XX responses are considered success responses.
+ private String responseCode;
+
+ // Response message, either from SDNC, or generated by the SDNC adapter.
+ private String responseMessage;
+
+ // Indicates if the response is final (Y or N).
+ private String ackFinalIndicator;
+
+ public SDNCResponseCommon(String sdncRequestId, String responseCode, String responseMessage,
+ String ackFinalIndicator) {
+ this.sdncRequestId = sdncRequestId;
+ this.responseCode = responseCode;
+ this.responseMessage = responseMessage;
+ this.ackFinalIndicator = ackFinalIndicator;
+ }
+
+ public SDNCResponseCommon() {}
+
+ @JsonProperty("sdncRequestId")
+ @XmlElement(name = "sdncRequestId")
+ public String getSdncRequestId() {
+ return sdncRequestId;
+ }
+
+ @JsonProperty("sdncRequestId")
+ public void setSdncRequestId(String sdncRequestId) {
+ this.sdncRequestId = sdncRequestId;
+ }
+
+ @JsonProperty("responseCode")
+ @XmlElement(name = "responseCode")
+ public String getResponseCode() {
+ return responseCode;
+ }
+
+ @JsonProperty("responseCode")
+ public void setResponseCode(String responseCode) {
+ this.responseCode = responseCode;
+ }
+
+ @JsonProperty("responseMessage")
+ @XmlElement(name = "responseMessage")
+ public String getResponseMessage() {
+ return responseMessage;
+ }
+
+ @JsonProperty("responseMessage")
+ public void setResponseMessage(String responseMessage) {
+ this.responseMessage = responseMessage;
+ }
+
+ @JsonProperty("ackFinalIndicator")
+ @XmlElement(name = "ackFinalIndicator")
+ public String getAckFinalIndicator() {
+ return ackFinalIndicator;
+ }
+
+ @JsonProperty("ackFinalIndicator")
+ public void setAckFinalIndicator(String ackFinalIndicator) {
+ this.ackFinalIndicator = ackFinalIndicator;
+ }
+
+ public String toJson() {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.setSerializationInclusion(Include.NON_NULL);
+ return mapper.writeValueAsString(this);
+ } catch (IOException e) {
+ logger.debug("Exception:", e);
+ throw new UnsupportedOperationException("Cannot convert " + getClass().getSimpleName() + " to JSON", e);
+ }
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceError.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceError.java
index fdb735891c..9d61db046f 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceError.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceError.java
@@ -21,16 +21,14 @@
package org.onap.so.adapters.sdncrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonRootName;
// NOTE: the JAXB (XML) annotations are required with JBoss AS7 and RESTEasy,
-// even though we are using JSON exclusively. The @NoJackson annotation
-// is also required in this environment.
+// even though we are using JSON exclusively. The @NoJackson annotation
+// is also required in this environment.
/**
* SDNC adapter error response for "agnostic" API services.
@@ -39,13 +37,12 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_NULL)
@XmlRootElement(name = "SDNCServiceError")
public class SDNCServiceError extends SDNCErrorCommon implements Serializable {
- private static final long serialVersionUID = 1;
+ private static final long serialVersionUID = 1;
- public SDNCServiceError(String sdncRequestId, String responseCode,
- String responseMessage, String ackFinalIndicator) {
- super(sdncRequestId, responseCode, responseMessage, ackFinalIndicator);
- }
+ public SDNCServiceError(String sdncRequestId, String responseCode, String responseMessage,
+ String ackFinalIndicator) {
+ super(sdncRequestId, responseCode, responseMessage, ackFinalIndicator);
+ }
- public SDNCServiceError() {
- }
-} \ No newline at end of file
+ public SDNCServiceError() {}
+}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceRequest.java
index 950362e986..c9f42d1550 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceRequest.java
@@ -21,127 +21,121 @@
package org.onap.so.adapters.sdncrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
// NOTE: the JAXB (XML) annotations are required with JBoss AS7 and RESTEasy,
-// even though we are using JSON exclusively. The @NoJackson annotation
-// is also required in this environment.
+// even though we are using JSON exclusively. The @NoJackson annotation
+// is also required in this environment.
/**
- * SDNC adapter request for "agnostic" API services.
- * The target action is determined by a service type and an operation.
+ * SDNC adapter request for "agnostic" API services. The target action is determined by a service type and an operation.
*/
@JsonRootName("SDNCServiceRequest")
@JsonInclude(Include.NON_NULL)
@XmlRootElement(name = "SDNCServiceRequest")
public class SDNCServiceRequest extends SDNCRequestCommon implements Serializable {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- // Request Information specified by SDNC "agnostic" API
- private RequestInformation requestInformation;
+ // Request Information specified by SDNC "agnostic" API
+ private RequestInformation requestInformation;
- // Service Information specified by: SDNC "agnostic" API
- private ServiceInformation serviceInformation;
+ // Service Information specified by: SDNC "agnostic" API
+ private ServiceInformation serviceInformation;
- // The SDNC service type specified by SDNC "agnostic" API
- private String sdncService;
+ // The SDNC service type specified by SDNC "agnostic" API
+ private String sdncService;
- // The SDNC operation specified by SDNC "agnostic" API
- private String sdncOperation;
+ // The SDNC operation specified by SDNC "agnostic" API
+ private String sdncOperation;
- // The SDNC service data type specified by SDNC "agnostic" API
- private String sdncServiceDataType;
+ // The SDNC service data type specified by SDNC "agnostic" API
+ private String sdncServiceDataType;
- // The SDNC service data specified by SDNC "agnostic" API
+ // The SDNC service data specified by SDNC "agnostic" API
private String sdncServiceData;
- public SDNCServiceRequest() {
- }
-
- public SDNCServiceRequest(String bpNotificationUrl, String bpTimeout,
- String sdncRequestId, String sdncService, String sdncOperation,
- RequestInformation requestInformation,
- ServiceInformation serviceInformation, String sdncServiceDataType,
- String sndcServiceData) {
- super(bpNotificationUrl, bpTimeout, sdncRequestId);
- this.requestInformation = requestInformation;
- this.serviceInformation = serviceInformation;
- this.sdncService = sdncService;
- this.sdncOperation = sdncOperation;
- this.sdncServiceDataType = sdncServiceDataType;
- this.sdncServiceData = sndcServiceData;
- }
-
- @JsonProperty("requestInformation")
- @XmlElement(name = "requestInformation")
- public RequestInformation getRequestInformation() {
- return requestInformation;
- }
-
- @JsonProperty("requestInformation")
- public void setRequestInformation(RequestInformation requestInformation) {
- this.requestInformation = requestInformation;
- }
-
- @JsonProperty("serviceInformation")
- @XmlElement(name = "serviceInformation")
- public ServiceInformation getServiceInformation() {
- return serviceInformation;
- }
-
- @JsonProperty("serviceInformation")
- public void setServiceInformation(ServiceInformation serviceInformation) {
- this.serviceInformation = serviceInformation;
- }
-
- @JsonProperty("sdncService")
- @XmlElement(name = "sdncService")
- public String getSdncService() {
- return sdncService;
- }
-
- @JsonProperty("sdncService")
- public void setSdncService(String sdncService) {
- this.sdncService = sdncService;
- }
-
- @JsonProperty("sdncOperation")
- @XmlElement(name = "sdncOperation")
- public String getSdncOperation() {
- return sdncOperation;
- }
-
- @JsonProperty("sdncOperation")
- public void setSdncOperation(String sdncOperation) {
- this.sdncOperation = sdncOperation;
- }
-
- @JsonProperty("sdncServiceDataType")
- @XmlElement(name = "sdncServiceDataType")
- public String getSdncServiceDataType() {
- return sdncServiceDataType;
- }
-
- @JsonProperty("sdncServiceDataType")
- public void setSdncServiceDataType(String sdncServiceDataType) {
- this.sdncServiceDataType = sdncServiceDataType;
- }
-
- @JsonProperty("sdncServiceData")
- @XmlElement(name = "sdncServiceData")
- public String getSdncServiceData() {
- return sdncServiceData;
- }
-
- @JsonProperty("sdncServiceData")
- public void setSdncServiceData(String sndcServiceData) {
- this.sdncServiceData = sndcServiceData;
- }
-} \ No newline at end of file
+ public SDNCServiceRequest() {}
+
+ public SDNCServiceRequest(String bpNotificationUrl, String bpTimeout, String sdncRequestId, String sdncService,
+ String sdncOperation, RequestInformation requestInformation, ServiceInformation serviceInformation,
+ String sdncServiceDataType, String sndcServiceData) {
+ super(bpNotificationUrl, bpTimeout, sdncRequestId);
+ this.requestInformation = requestInformation;
+ this.serviceInformation = serviceInformation;
+ this.sdncService = sdncService;
+ this.sdncOperation = sdncOperation;
+ this.sdncServiceDataType = sdncServiceDataType;
+ this.sdncServiceData = sndcServiceData;
+ }
+
+ @JsonProperty("requestInformation")
+ @XmlElement(name = "requestInformation")
+ public RequestInformation getRequestInformation() {
+ return requestInformation;
+ }
+
+ @JsonProperty("requestInformation")
+ public void setRequestInformation(RequestInformation requestInformation) {
+ this.requestInformation = requestInformation;
+ }
+
+ @JsonProperty("serviceInformation")
+ @XmlElement(name = "serviceInformation")
+ public ServiceInformation getServiceInformation() {
+ return serviceInformation;
+ }
+
+ @JsonProperty("serviceInformation")
+ public void setServiceInformation(ServiceInformation serviceInformation) {
+ this.serviceInformation = serviceInformation;
+ }
+
+ @JsonProperty("sdncService")
+ @XmlElement(name = "sdncService")
+ public String getSdncService() {
+ return sdncService;
+ }
+
+ @JsonProperty("sdncService")
+ public void setSdncService(String sdncService) {
+ this.sdncService = sdncService;
+ }
+
+ @JsonProperty("sdncOperation")
+ @XmlElement(name = "sdncOperation")
+ public String getSdncOperation() {
+ return sdncOperation;
+ }
+
+ @JsonProperty("sdncOperation")
+ public void setSdncOperation(String sdncOperation) {
+ this.sdncOperation = sdncOperation;
+ }
+
+ @JsonProperty("sdncServiceDataType")
+ @XmlElement(name = "sdncServiceDataType")
+ public String getSdncServiceDataType() {
+ return sdncServiceDataType;
+ }
+
+ @JsonProperty("sdncServiceDataType")
+ public void setSdncServiceDataType(String sdncServiceDataType) {
+ this.sdncServiceDataType = sdncServiceDataType;
+ }
+
+ @JsonProperty("sdncServiceData")
+ @XmlElement(name = "sdncServiceData")
+ public String getSdncServiceData() {
+ return sdncServiceData;
+ }
+
+ @JsonProperty("sdncServiceData")
+ public void setSdncServiceData(String sndcServiceData) {
+ this.sdncServiceData = sndcServiceData;
+ }
+}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceResponse.java
index 18c9d49939..842bcfcc02 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceResponse.java
@@ -23,56 +23,54 @@ package org.onap.so.adapters.sdncrest;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
// NOTE: the JAXB (XML) annotations are required with JBoss AS7 and RESTEasy,
-// even though we are using JSON exclusively. The @NoJackson annotation
-// is also required in this environment.
+// even though we are using JSON exclusively. The @NoJackson annotation
+// is also required in this environment.
/**
- Map<String, String> elements when marshalled to XML produce a list of <entry><key>${MsoUtils.xmlEscape(key)}</key><value>${MsoUtils.xmlEscape(value)}</value></entry> elements.
- When marshalling to JSON they create a list of "${key}" : "${value}" pairs with no extra wrappers.
+ * Map<String, String> elements when marshalled to XML produce a list of
+ * <entry><key>${MsoUtils.xmlEscape(key)}</key><value>${MsoUtils.xmlEscape(value)}</value></entry> elements. When
+ * marshalling to JSON they create a list of "${key}" : "${value}" pairs with no extra wrappers.
* </pre>
*/
@JsonRootName("SDNCServiceResponse")
@JsonInclude(Include.NON_NULL)
@XmlRootElement(name = "SDNCServiceResponse")
public class SDNCServiceResponse extends SDNCResponseCommon implements Serializable {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- // Map of response parameters (possibly none).
- private Map<String, String> params = null;
+ // Map of response parameters (possibly none).
+ private Map<String, String> params = null;
- public SDNCServiceResponse(String sdncRequestId, String responseCode,
- String responseMessage, String ackFinalIndicator) {
- super(sdncRequestId, responseCode, responseMessage, ackFinalIndicator);
- }
+ public SDNCServiceResponse(String sdncRequestId, String responseCode, String responseMessage,
+ String ackFinalIndicator) {
+ super(sdncRequestId, responseCode, responseMessage, ackFinalIndicator);
+ }
- public SDNCServiceResponse() {
- }
+ public SDNCServiceResponse() {}
- @JsonProperty("params")
- @XmlElement(name = "params")
- public Map<String, String> getParams() {
- return params;
- }
+ @JsonProperty("params")
+ @XmlElement(name = "params")
+ public Map<String, String> getParams() {
+ return params;
+ }
- @JsonProperty("params")
- public void setParams(Map<String, String> params) {
- this.params = params;
- }
+ @JsonProperty("params")
+ public void setParams(Map<String, String> params) {
+ this.params = params;
+ }
- public void addParam(String name, String value) {
- if (params == null) {
- params = new LinkedHashMap<>();
- }
- params.put(name, value);
- }
+ public void addParam(String name, String value) {
+ if (params == null) {
+ params = new LinkedHashMap<>();
+ }
+ params.put(name, value);
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/ServiceInformation.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/ServiceInformation.java
index b4fe26ac00..da055cbcb3 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/ServiceInformation.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/ServiceInformation.java
@@ -21,84 +21,81 @@
package org.onap.so.adapters.sdncrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlElement;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Service Information specified by the SDNC "agnostic" API.
*/
public class ServiceInformation implements Serializable {
- private static final long serialVersionUID = 1L;
-
- // The subscription's service type for the target service instance.
- private String serviceType;
-
- // Identifies the target service instance for this particular SDNC request.
- // NOTE: this could be a child of the parent model instance, i.e. this
- // service instance ID may be different from the service instance ID
- // associated with the transaction MSO has with the system that invoked it.
- private String serviceInstanceId;
-
- // The subscriber name.
- private String subscriberName;
-
- // The subscriber global ID (customer ID).
- private String subscriberGlobalId;
-
- public ServiceInformation(String serviceType, String serviceInstanceId,
- String subscriberName, String subscriberGlobalId) {
- this.serviceType = serviceType;
- this.serviceInstanceId = serviceInstanceId;
- this.subscriberName = subscriberName;
- this.subscriberGlobalId = subscriberGlobalId;
- }
-
- public ServiceInformation() {
- }
-
- @JsonProperty("serviceType")
- @XmlElement(name = "serviceType")
- public String getServiceType() {
- return serviceType;
- }
-
- @JsonProperty("serviceType")
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
-
- @JsonProperty("serviceInstanceId")
- @XmlElement(name = "serviceInstanceId")
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- @JsonProperty("serviceInstanceId")
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
-
- @JsonProperty("subscriberName")
- @XmlElement(name = "subscriberName")
- public String getSubscriberName() {
- return subscriberName;
- }
-
- @JsonProperty("subscriberName")
- public void setSubscriberName(String subscriberName) {
- this.subscriberName = subscriberName;
- }
-
- @JsonProperty("subscriberGlobalId")
- @XmlElement(name = "subscriberGlobalId")
- public String getSubscriberGlobalId() {
- return subscriberGlobalId;
- }
-
- @JsonProperty("subscriberGlobalId")
- public void setSubscriberGlobalId(String subscriberGlobalId) {
- this.subscriberGlobalId = subscriberGlobalId;
- }
-} \ No newline at end of file
+ private static final long serialVersionUID = 1L;
+
+ // The subscription's service type for the target service instance.
+ private String serviceType;
+
+ // Identifies the target service instance for this particular SDNC request.
+ // NOTE: this could be a child of the parent model instance, i.e. this
+ // service instance ID may be different from the service instance ID
+ // associated with the transaction MSO has with the system that invoked it.
+ private String serviceInstanceId;
+
+ // The subscriber name.
+ private String subscriberName;
+
+ // The subscriber global ID (customer ID).
+ private String subscriberGlobalId;
+
+ public ServiceInformation(String serviceType, String serviceInstanceId, String subscriberName,
+ String subscriberGlobalId) {
+ this.serviceType = serviceType;
+ this.serviceInstanceId = serviceInstanceId;
+ this.subscriberName = subscriberName;
+ this.subscriberGlobalId = subscriberGlobalId;
+ }
+
+ public ServiceInformation() {}
+
+ @JsonProperty("serviceType")
+ @XmlElement(name = "serviceType")
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ @JsonProperty("serviceType")
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ @JsonProperty("serviceInstanceId")
+ @XmlElement(name = "serviceInstanceId")
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ @JsonProperty("serviceInstanceId")
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ @JsonProperty("subscriberName")
+ @XmlElement(name = "subscriberName")
+ public String getSubscriberName() {
+ return subscriberName;
+ }
+
+ @JsonProperty("subscriberName")
+ public void setSubscriberName(String subscriberName) {
+ this.subscriberName = subscriberName;
+ }
+
+ @JsonProperty("subscriberGlobalId")
+ @XmlElement(name = "subscriberGlobalId")
+ public String getSubscriberGlobalId() {
+ return subscriberGlobalId;
+ }
+
+ @JsonProperty("subscriberGlobalId")
+ public void setSubscriberGlobalId(String subscriberGlobalId) {
+ this.subscriberGlobalId = subscriberGlobalId;
+ }
+}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantError.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantError.java
index 34da8c6292..06f0f87622 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantError.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantError.java
@@ -23,51 +23,49 @@ package org.onap.so.adapters.tenantrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
@XmlRootElement(name = "createTenantError")
public class CreateTenantError implements Serializable {
- private static final long serialVersionUID = 7305288262646805568L;
- private String message;
- private MsoExceptionCategory category;
- private Boolean rolledBack;
-
- public CreateTenantError () {}
-
- public CreateTenantError (String message) {
- this.message = message;
- }
-
- public CreateTenantError (String message, MsoExceptionCategory category, boolean rolledBack) {
- this.message = message;
- this.category = category;
- this.rolledBack = rolledBack;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public MsoExceptionCategory getCategory () {
- return category;
- }
-
- public void setCategory (MsoExceptionCategory category) {
- this.category = category;
- }
-
- public Boolean getRolledBack() {
- return rolledBack;
- }
-
- public void setRolledBack(Boolean rolledBack) {
- this.rolledBack = rolledBack;
- }
+ private static final long serialVersionUID = 7305288262646805568L;
+ private String message;
+ private MsoExceptionCategory category;
+ private Boolean rolledBack;
+
+ public CreateTenantError() {}
+
+ public CreateTenantError(String message) {
+ this.message = message;
+ }
+
+ public CreateTenantError(String message, MsoExceptionCategory category, boolean rolledBack) {
+ this.message = message;
+ this.category = category;
+ this.rolledBack = rolledBack;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public MsoExceptionCategory getCategory() {
+ return category;
+ }
+
+ public void setCategory(MsoExceptionCategory category) {
+ this.category = category;
+ }
+
+ public Boolean getRolledBack() {
+ return rolledBack;
+ }
+
+ public void setRolledBack(Boolean rolledBack) {
+ this.rolledBack = rolledBack;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantRequest.java
index 1f4b872ab9..8aba765908 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantRequest.java
@@ -26,77 +26,73 @@ package org.onap.so.adapters.tenantrest;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.entity.MsoRequest;
@XmlRootElement(name = "createTenantRequest")
public class CreateTenantRequest extends TenantRequestCommon {
- private String cloudSiteId;
- private String tenantName;
- private Boolean failIfExists;
- private Boolean backout;
- private Map<String,String> metadata = new HashMap<>();
- private MsoRequest msoRequest = new MsoRequest();
-
- public CreateTenantRequest() {
- //empty constructor
- }
-
- public String getCloudSiteId() {
- return cloudSiteId;
- }
-
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
-
- public String getTenantName() {
- return tenantName;
- }
-
- public void setTenantName(String tenantName) {
- this.tenantName = tenantName;
- }
-
- public Boolean getFailIfExists() {
- return failIfExists;
- }
-
- public void setFailIfExists(Boolean failIfExists) {
- this.failIfExists = failIfExists;
- }
-
- public Boolean getBackout() {
- return backout;
- }
-
- public void setBackout(Boolean backout) {
- this.backout = backout;
- }
-
- public Map<String, String> getMetadata() {
- return metadata;
- }
-
- public void setMetadata(Map<String, String> metadata) {
- this.metadata = metadata;
- }
-
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
-
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
-
- @Override
- public String toString() {
- return "CreateTenantRequest [cloudSiteId=" + cloudSiteId
- + ", tenantName=" + tenantName + ", failIfExists="
- + failIfExists + ", backout=" + backout + ", metadata="
- + metadata + "]";
- }
+ private String cloudSiteId;
+ private String tenantName;
+ private Boolean failIfExists;
+ private Boolean backout;
+ private Map<String, String> metadata = new HashMap<>();
+ private MsoRequest msoRequest = new MsoRequest();
+
+ public CreateTenantRequest() {
+ // empty constructor
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
+
+ public String getTenantName() {
+ return tenantName;
+ }
+
+ public void setTenantName(String tenantName) {
+ this.tenantName = tenantName;
+ }
+
+ public Boolean getFailIfExists() {
+ return failIfExists;
+ }
+
+ public void setFailIfExists(Boolean failIfExists) {
+ this.failIfExists = failIfExists;
+ }
+
+ public Boolean getBackout() {
+ return backout;
+ }
+
+ public void setBackout(Boolean backout) {
+ this.backout = backout;
+ }
+
+ public Map<String, String> getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(Map<String, String> metadata) {
+ this.metadata = metadata;
+ }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
+
+ @Override
+ public String toString() {
+ return "CreateTenantRequest [cloudSiteId=" + cloudSiteId + ", tenantName=" + tenantName + ", failIfExists="
+ + failIfExists + ", backout=" + backout + ", metadata=" + metadata + "]";
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantResponse.java
index ec304cec41..853f0acb67 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/CreateTenantResponse.java
@@ -23,63 +23,61 @@ package org.onap.so.adapters.tenantrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "createTenantResponse")
public class CreateTenantResponse implements Serializable {
- private static final long serialVersionUID = -456155026754759682L;
- private String cloudSiteId;
- private String tenantId;
- private Boolean tenantCreated;
- private TenantRollback tenantRollback = new TenantRollback();
-
- public CreateTenantResponse() {}
-
- public CreateTenantResponse(String cloudSiteId, String tenantId,
- Boolean tenantCreated, TenantRollback tenantRollback) {
- this.cloudSiteId = cloudSiteId;
- this.tenantId = tenantId;
- this.tenantCreated = tenantCreated;
- this.tenantRollback = tenantRollback;
- }
-
- public String getCloudSiteId() {
- return cloudSiteId;
- }
-
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
-
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public Boolean getTenantCreated() {
- return tenantCreated;
- }
-
- public void setTenantCreated(Boolean tenantCreated) {
- this.tenantCreated = tenantCreated;
- }
-
- public TenantRollback getTenantRollback() {
- return tenantRollback;
- }
-
- public void setTenantRollback(TenantRollback tenantRollback) {
- this.tenantRollback = tenantRollback;
- }
-
- @Override
- public String toString() {
- return "CreateTenantResponse [cloudSiteId=" + cloudSiteId
- + ", tenantId=" + tenantId + ", tenantCreated=" + tenantCreated
- + ", tenantRollback=" + tenantRollback.toString() + "]";
- }
+ private static final long serialVersionUID = -456155026754759682L;
+ private String cloudSiteId;
+ private String tenantId;
+ private Boolean tenantCreated;
+ private TenantRollback tenantRollback = new TenantRollback();
+
+ public CreateTenantResponse() {}
+
+ public CreateTenantResponse(String cloudSiteId, String tenantId, Boolean tenantCreated,
+ TenantRollback tenantRollback) {
+ this.cloudSiteId = cloudSiteId;
+ this.tenantId = tenantId;
+ this.tenantCreated = tenantCreated;
+ this.tenantRollback = tenantRollback;
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public Boolean getTenantCreated() {
+ return tenantCreated;
+ }
+
+ public void setTenantCreated(Boolean tenantCreated) {
+ this.tenantCreated = tenantCreated;
+ }
+
+ public TenantRollback getTenantRollback() {
+ return tenantRollback;
+ }
+
+ public void setTenantRollback(TenantRollback tenantRollback) {
+ this.tenantRollback = tenantRollback;
+ }
+
+ @Override
+ public String toString() {
+ return "CreateTenantResponse [cloudSiteId=" + cloudSiteId + ", tenantId=" + tenantId + ", tenantCreated="
+ + tenantCreated + ", tenantRollback=" + tenantRollback.toString() + "]";
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantError.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantError.java
index d2c22e8506..b16fdd3c81 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantError.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantError.java
@@ -23,51 +23,49 @@ package org.onap.so.adapters.tenantrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
@XmlRootElement(name = "deleteTenantError")
public class DeleteTenantError implements Serializable {
- private static final long serialVersionUID = -5778340182805870809L;
- private String message;
- private MsoExceptionCategory category;
- private Boolean rolledBack;
-
- public DeleteTenantError () {}
-
- public DeleteTenantError (String message) {
- this.message = message;
- }
-
- public DeleteTenantError (String message, MsoExceptionCategory category, boolean rolledBack) {
- this.message = message;
- this.category = category;
- this.rolledBack = rolledBack;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public MsoExceptionCategory getCategory () {
- return category;
- }
-
- public void setCategory (MsoExceptionCategory category) {
- this.category = category;
- }
-
- public Boolean getRolledBack() {
- return rolledBack;
- }
-
- public void setRolledBack(Boolean rolledBack) {
- this.rolledBack = rolledBack;
- }
+ private static final long serialVersionUID = -5778340182805870809L;
+ private String message;
+ private MsoExceptionCategory category;
+ private Boolean rolledBack;
+
+ public DeleteTenantError() {}
+
+ public DeleteTenantError(String message) {
+ this.message = message;
+ }
+
+ public DeleteTenantError(String message, MsoExceptionCategory category, boolean rolledBack) {
+ this.message = message;
+ this.category = category;
+ this.rolledBack = rolledBack;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public MsoExceptionCategory getCategory() {
+ return category;
+ }
+
+ public void setCategory(MsoExceptionCategory category) {
+ this.category = category;
+ }
+
+ public Boolean getRolledBack() {
+ return rolledBack;
+ }
+
+ public void setRolledBack(Boolean rolledBack) {
+ this.rolledBack = rolledBack;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantRequest.java
index b2d521b050..281e172378 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantRequest.java
@@ -25,42 +25,41 @@ package org.onap.so.adapters.tenantrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.entity.MsoRequest;
@XmlRootElement(name = "deleteTenantRequest")
public class DeleteTenantRequest extends TenantRequestCommon {
- private String cloudSiteId;
- private String tenantId;
+ private String cloudSiteId;
+ private String tenantId;
+
+ private MsoRequest msoRequest = new MsoRequest();
- private MsoRequest msoRequest = new MsoRequest();
+ public DeleteTenantRequest() {
+ // empty constructor
+ }
- public DeleteTenantRequest() {
- //empty constructor
- }
-
- public String getCloudSiteId() {
- return cloudSiteId;
- }
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
- public String getTenantId() {
- return tenantId;
- }
+ public String getTenantId() {
+ return tenantId;
+ }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantResponse.java
index e7961d4607..23174145fa 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/DeleteTenantResponse.java
@@ -27,15 +27,15 @@ import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "deleteTenantResponse")
public class DeleteTenantResponse {
- private Boolean tenantDeleted;
+ private Boolean tenantDeleted;
- public DeleteTenantResponse() {}
-
- public Boolean getTenantDeleted() {
- return tenantDeleted;
- }
+ public DeleteTenantResponse() {}
- public void setTenantDeleted(Boolean tenantDeleted) {
- this.tenantDeleted = tenantDeleted;
- }
+ public Boolean getTenantDeleted() {
+ return tenantDeleted;
+ }
+
+ public void setTenantDeleted(Boolean tenantDeleted) {
+ this.tenantDeleted = tenantDeleted;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/QueryTenantError.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/QueryTenantError.java
index 10f4b70a07..ef0bfb99a5 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/QueryTenantError.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/QueryTenantError.java
@@ -23,41 +23,39 @@ package org.onap.so.adapters.tenantrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
@XmlRootElement(name = "queryTenantError")
public class QueryTenantError implements Serializable {
- private static final long serialVersionUID = 7358240830662453507L;
- private String message;
- private MsoExceptionCategory category;
+ private static final long serialVersionUID = 7358240830662453507L;
+ private String message;
+ private MsoExceptionCategory category;
- public QueryTenantError () {}
+ public QueryTenantError() {}
- public QueryTenantError (String message) {
- this.message = message;
- }
+ public QueryTenantError(String message) {
+ this.message = message;
+ }
- public QueryTenantError (String message, MsoExceptionCategory category) {
- this.message = message;
- this.category = category;
- }
+ public QueryTenantError(String message, MsoExceptionCategory category) {
+ this.message = message;
+ this.category = category;
+ }
- public String getMessage() {
- return message;
- }
+ public String getMessage() {
+ return message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public MsoExceptionCategory getCategory () {
- return category;
- }
+ public MsoExceptionCategory getCategory() {
+ return category;
+ }
- public void setCategory (MsoExceptionCategory category) {
- this.category = category;
- }
+ public void setCategory(MsoExceptionCategory category) {
+ this.category = category;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/QueryTenantResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/QueryTenantResponse.java
index 8d478cd393..f0e1d88bd3 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/QueryTenantResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/QueryTenantResponse.java
@@ -23,41 +23,43 @@ package org.onap.so.adapters.tenantrest;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "queryTenantResponse")
public class QueryTenantResponse extends TenantRequestCommon {
- private String tenantId;
- private String tenantName;
- private Map<String,String> metadata;
-
- public QueryTenantResponse() {}
-
- public QueryTenantResponse (String id, String name, Map<String,String> metadata) {
- this.tenantId = id;
- this.tenantName = name;
- this.metadata = metadata;
- }
-
- public String getTenantId() {
- return tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getTenantName() {
- return tenantName;
- }
- public void setTenantName(String tenantName) {
- this.tenantName = tenantName;
- }
-
- public Map<String, String> getMetadata() {
- return metadata;
- }
- public void setMetadata(Map<String, String> metadata) {
- this.metadata = metadata;
- }
+ private String tenantId;
+ private String tenantName;
+ private Map<String, String> metadata;
+
+ public QueryTenantResponse() {}
+
+ public QueryTenantResponse(String id, String name, Map<String, String> metadata) {
+ this.tenantId = id;
+ this.tenantName = name;
+ this.metadata = metadata;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getTenantName() {
+ return tenantName;
+ }
+
+ public void setTenantName(String tenantName) {
+ this.tenantName = tenantName;
+ }
+
+ public Map<String, String> getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(Map<String, String> metadata) {
+ this.metadata = metadata;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantError.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantError.java
index 725b40549d..58d322f5d4 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantError.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantError.java
@@ -23,47 +23,45 @@ package org.onap.so.adapters.tenantrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
@XmlRootElement(name = "rollbackTenantError")
public class RollbackTenantError implements Serializable {
- private static final long serialVersionUID = -5313713674529615223L;
- private String message;
- private MsoExceptionCategory category;
- private Boolean rolledBack;
+ private static final long serialVersionUID = -5313713674529615223L;
+ private String message;
+ private MsoExceptionCategory category;
+ private Boolean rolledBack;
- public RollbackTenantError () {}
+ public RollbackTenantError() {}
- public RollbackTenantError (String message, MsoExceptionCategory category, boolean rolledBack) {
- this.message = message;
- this.category = category;
- this.rolledBack = rolledBack;
- }
+ public RollbackTenantError(String message, MsoExceptionCategory category, boolean rolledBack) {
+ this.message = message;
+ this.category = category;
+ this.rolledBack = rolledBack;
+ }
- public String getMessage() {
- return message;
- }
+ public String getMessage() {
+ return message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public MsoExceptionCategory getCategory () {
- return category;
- }
+ public MsoExceptionCategory getCategory() {
+ return category;
+ }
- public void setCategory (MsoExceptionCategory category) {
- this.category = category;
- }
+ public void setCategory(MsoExceptionCategory category) {
+ this.category = category;
+ }
- public Boolean getRolledBack() {
- return rolledBack;
- }
+ public Boolean getRolledBack() {
+ return rolledBack;
+ }
- public void setRolledBack(Boolean rolledBack) {
- this.rolledBack = rolledBack;
- }
+ public void setRolledBack(Boolean rolledBack) {
+ this.rolledBack = rolledBack;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantRequest.java
index d99150fc47..20f079184c 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantRequest.java
@@ -27,15 +27,15 @@ import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "rollbackTenantRequest")
public class RollbackTenantRequest extends TenantRequestCommon {
- private TenantRollback tenantRollback;
+ private TenantRollback tenantRollback;
- public RollbackTenantRequest() {}
+ public RollbackTenantRequest() {}
- public TenantRollback getTenantRollback() {
- return tenantRollback;
- }
+ public TenantRollback getTenantRollback() {
+ return tenantRollback;
+ }
- public void setTenantRollback(TenantRollback tenantRollback) {
- this.tenantRollback = tenantRollback;
- }
+ public void setTenantRollback(TenantRollback tenantRollback) {
+ this.tenantRollback = tenantRollback;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantResponse.java
index 25b77b3490..a64f8893c7 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/RollbackTenantResponse.java
@@ -27,15 +27,15 @@ import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "rollbackTenantResponse")
public class RollbackTenantResponse {
- private Boolean tenantRolledback;
+ private Boolean tenantRolledback;
- public RollbackTenantResponse() {}
-
- public Boolean getTenantRolledback() {
- return tenantRolledback;
- }
+ public RollbackTenantResponse() {}
- public void setTenantRolledback(Boolean tenantRolledback) {
- this.tenantRolledback = tenantRolledback;
- }
+ public Boolean getTenantRolledback() {
+ return tenantRolledback;
+ }
+
+ public void setTenantRolledback(Boolean tenantRolledback) {
+ this.tenantRolledback = tenantRolledback;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantExceptionResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantExceptionResponse.java
index f4dd7f9499..18b8c817d4 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantExceptionResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantExceptionResponse.java
@@ -23,9 +23,7 @@ package org.onap.so.adapters.tenantrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
@XmlRootElement(name = "createTenantResponse")
@@ -34,39 +32,39 @@ public class TenantExceptionResponse implements Serializable {
private static final long serialVersionUID = -9062290006520066109L;
private String message;
- private MsoExceptionCategory category;
- private Boolean rolledBack;
+ private MsoExceptionCategory category;
+ private Boolean rolledBack;
+
+ public TenantExceptionResponse() {}
- public TenantExceptionResponse () {}
+ public TenantExceptionResponse(String message, MsoExceptionCategory category, boolean rolledBack) {
+ this.message = message;
+ this.category = category;
+ this.rolledBack = rolledBack;
+ }
- public TenantExceptionResponse (String message, MsoExceptionCategory category, boolean rolledBack) {
- this.message = message;
- this.category = category;
- this.rolledBack = rolledBack;
- }
+ public String getMessage() {
+ return message;
+ }
- public String getMessage() {
- return message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public MsoExceptionCategory getCategory() {
+ return category;
+ }
- public MsoExceptionCategory getCategory () {
- return category;
- }
+ public void setCategory(MsoExceptionCategory category) {
+ this.category = category;
+ }
- public void setCategory (MsoExceptionCategory category) {
- this.category = category;
- }
+ public Boolean getRolledBack() {
+ return rolledBack;
+ }
- public Boolean getRolledBack() {
- return rolledBack;
- }
+ public void setRolledBack(Boolean rolledBack) {
+ this.rolledBack = rolledBack;
+ }
- public void setRolledBack(Boolean rolledBack) {
- this.rolledBack = rolledBack;
- }
-
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantRequestCommon.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantRequestCommon.java
index 7d629cb554..f35149d1db 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantRequestCommon.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantRequestCommon.java
@@ -25,44 +25,42 @@ package org.onap.so.adapters.tenantrest;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
-
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class TenantRequestCommon implements Serializable {
- private static final long serialVersionUID = 1486834308868170854L;
- private static Logger logger = LoggerFactory.getLogger(TenantRequestCommon.class);
- public String toJsonString() {
- try {
- String jsonString;
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- jsonString = mapper.writeValueAsString(this);
- return jsonString;
- } catch (Exception e) {
- logger.debug("Exception :", e);
- return "";
- }
- }
+ private static final long serialVersionUID = 1486834308868170854L;
+ private static Logger logger = LoggerFactory.getLogger(TenantRequestCommon.class);
+
+ public String toJsonString() {
+ try {
+ String jsonString;
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ jsonString = mapper.writeValueAsString(this);
+ return jsonString;
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ return "";
+ }
+ }
- public String toXmlString() {
- try {
- ByteArrayOutputStream bs = new ByteArrayOutputStream();
- JAXBContext context = JAXBContext.newInstance(this.getClass());
- Marshaller marshaller = context.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //pretty print XML
- marshaller.marshal(this, bs);
- return bs.toString();
- } catch (Exception e) {
- logger.debug("Exception :", e);
- return "";
- }
- }
+ public String toXmlString() {
+ try {
+ ByteArrayOutputStream bs = new ByteArrayOutputStream();
+ JAXBContext context = JAXBContext.newInstance(this.getClass());
+ Marshaller marshaller = context.createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // pretty print XML
+ marshaller.marshal(this, bs);
+ return bs.toString();
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ return "";
+ }
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantRollback.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantRollback.java
index 195628167e..009ee60991 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantRollback.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/tenantrest/TenantRollback.java
@@ -23,58 +23,59 @@ package org.onap.so.adapters.tenantrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.entity.MsoRequest;
/**
- * Javabean representing the rollback criteria following a "Create Tenant"
- * operation. This structure can be passed back to the "Rollback Tenant"
- * operation to undo the effects of the create.
+ * Javabean representing the rollback criteria following a "Create Tenant" operation. This structure can be passed back
+ * to the "Rollback Tenant" operation to undo the effects of the create.
*
*
*/
@XmlRootElement(name = "rollbackTenantRequest")
public class TenantRollback extends TenantRequestCommon {
- private static final long serialVersionUID = -4540810517355635993L;
- private String tenantId;
- private String cloudId;
- private boolean tenantCreated = false;
- private MsoRequest msoRequest;
-
- public TenantRollback() {}
-
- public String getTenantId() {
- return tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getCloudId() {
- return cloudId;
- }
- public void setCloudId(String cloudId) {
- this.cloudId = cloudId;
- }
-
- public boolean getTenantCreated() {
- return tenantCreated;
- }
- public void setTenantCreated(boolean tenantCreated) {
- this.tenantCreated = tenantCreated;
- }
-
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
- public void setMsoRequest (MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
-
- @Override
+ private static final long serialVersionUID = -4540810517355635993L;
+ private String tenantId;
+ private String cloudId;
+ private boolean tenantCreated = false;
+ private MsoRequest msoRequest;
+
+ public TenantRollback() {}
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getCloudId() {
+ return cloudId;
+ }
+
+ public void setCloudId(String cloudId) {
+ this.cloudId = cloudId;
+ }
+
+ public boolean getTenantCreated() {
+ return tenantCreated;
+ }
+
+ public void setTenantCreated(boolean tenantCreated) {
+ this.tenantCreated = tenantCreated;
+ }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
+
+ @Override
public String toString() {
- return "VnfRollback: cloud=" + cloudId + ", tenant=" + tenantId +
- ", tenantCreated=" + tenantCreated;
- }
+ return "VnfRollback: cloud=" + cloudId + ", tenant=" + tenantId + ", tenantCreated=" + tenantCreated;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/CloudInfo.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/CloudInfo.java
index f7db785deb..f03c9d381b 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/CloudInfo.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/CloudInfo.java
@@ -21,57 +21,60 @@
package org.onap.so.adapters.vdu;
/**
- * Cloud information structure for deploying/managing a VDU. Includes the cloud site
- * as well as tenant information within the site. Currently this is defined as a
- * cloud site ID. which would map to a CloudConfig entry.
- * Perhaps the CloudConfig entry itself should be provided, instead of requiring each
- * plug-in to query it.
+ * Cloud information structure for deploying/managing a VDU. Includes the cloud site as well as tenant information
+ * within the site. Currently this is defined as a cloud site ID. which would map to a CloudConfig entry. Perhaps the
+ * CloudConfig entry itself should be provided, instead of requiring each plug-in to query it.
*
- * The meaning of 'tenant' may differ by cloud provider, but every cloud supports some
- * sort of tenant partitioning.
+ * The meaning of 'tenant' may differ by cloud provider, but every cloud supports some sort of tenant partitioning.
*
*/
public class CloudInfo {
- private String cloudSiteId;
- private String cloudOwner;
- private String tenantId;
- private String tenantName;//bpmn query and pass
+ private String cloudSiteId;
+ private String cloudOwner;
+ private String tenantId;
+ private String tenantName;// bpmn query and pass
- public CloudInfo() {
- }
+ public CloudInfo() {}
- public CloudInfo (String cloudSiteId, String cloudOwner, String tenantId, String tenantName) {
- this.cloudSiteId = cloudSiteId;
- this.cloudOwner = cloudOwner;
- this.tenantId = tenantId;
- this.tenantName = tenantName;
- }
+ public CloudInfo(String cloudSiteId, String cloudOwner, String tenantId, String tenantName) {
+ this.cloudSiteId = cloudSiteId;
+ this.cloudOwner = cloudOwner;
+ this.tenantId = tenantId;
+ this.tenantName = tenantName;
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
- public String getCloudSiteId() {
- return cloudSiteId;
- }
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
public String getCloudOwner() {
return cloudOwner;
}
+
public void setCloudOwner(String cloudOwner) {
this.cloudOwner = cloudOwner;
}
- public String getTenantId() {
- return tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getTenantName() {
- return tenantName;
- }
- public void setTenantName(String tenantName) {
- this.tenantName = tenantName;
- }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getTenantName() {
+ return tenantName;
+ }
+
+ public void setTenantName(String tenantName) {
+ this.tenantName = tenantName;
+ }
-} \ No newline at end of file
+}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/PluginAction.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/PluginAction.java
index 1f097ddd68..634b2ad60d 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/PluginAction.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/PluginAction.java
@@ -21,43 +21,46 @@
package org.onap.so.adapters.vdu;
/**
- * Java beam representing a detailed action performed within a plugin during VDU
- * orchestration. This allows the plugin to convey more detailed information about
- * recent activities it has performed. It is primarily intended for logging and
- * troubleshooting, so plugins are free to populate this as desired.
+ * Java beam representing a detailed action performed within a plugin during VDU orchestration. This allows the plugin
+ * to convey more detailed information about recent activities it has performed. It is primarily intended for logging
+ * and troubleshooting, so plugins are free to populate this as desired.
*/
public class PluginAction {
-
- private String action;
- private String status;
- private String rawMessage;
-
- public PluginAction () {
- }
-
- public PluginAction (String action, String status, String rawMessage) {
- this.action = action;
- this.status = status;
- this.rawMessage = rawMessage;
- }
-
- public String getAction() {
- return action;
- }
- public void setAction(String action) {
- this.action = action;
- }
- public String getStatus() {
- return status;
- }
- public void setStatus(String status) {
- this.status = status;
- }
- public String getRawMessage() {
- return rawMessage;
- }
- public void setRawMessage(String rawMessage) {
- this.rawMessage = rawMessage;
- }
-
-} \ No newline at end of file
+
+ private String action;
+ private String status;
+ private String rawMessage;
+
+ public PluginAction() {}
+
+ public PluginAction(String action, String status, String rawMessage) {
+ this.action = action;
+ this.status = status;
+ this.rawMessage = rawMessage;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getRawMessage() {
+ return rawMessage;
+ }
+
+ public void setRawMessage(String rawMessage) {
+ this.rawMessage = rawMessage;
+ }
+
+}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduArtifact.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduArtifact.java
index 8701aa4a7d..2f99fed875 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduArtifact.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduArtifact.java
@@ -26,60 +26,65 @@ import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
public class VduArtifact {
-
- // Enumerate the types of artifacts permitted. This may need to be a variable string
- // value if arbitrary (cloud-specific) artifacts may be attached to VDUs in ASDC.
- public enum ArtifactType {
- MAIN_TEMPLATE, NESTED_TEMPLATE, CONFIG_FILE, SCRIPT_FILE, TEXT_FILE, ENVIRONMENT
- }
-
- private String name;
- private byte[] content;
- private ArtifactType type;
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VduArtifact)) {
- return false;
- }
- VduArtifact castOther = (VduArtifact) other;
- return new EqualsBuilder().append(name, castOther.name).append(content, castOther.content)
- .append(type, castOther.type).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(name).append(content).append(type).toHashCode();
- }
-
- // Default constructor
- public VduArtifact() {}
-
- // Fully specified constructor
- public VduArtifact (String name, byte[] content, ArtifactType type) {
- this.name = name;
- this.content = content;
- this.type = type;
- }
-
- public String getName() {
- return name;
- }
- public void setName (String name) {
- this.name = name;
- }
- public byte[] getContent() {
- return content;
- }
- public void setContent(byte[] content) {
- this.content = content;
- }
- public ArtifactType getType() {
- return type;
- }
- public void setType(ArtifactType type) {
- this.type = type;
- }
-
-
+
+ // Enumerate the types of artifacts permitted. This may need to be a variable string
+ // value if arbitrary (cloud-specific) artifacts may be attached to VDUs in ASDC.
+ public enum ArtifactType {
+ MAIN_TEMPLATE, NESTED_TEMPLATE, CONFIG_FILE, SCRIPT_FILE, TEXT_FILE, ENVIRONMENT
+ }
+
+ private String name;
+ private byte[] content;
+ private ArtifactType type;
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VduArtifact)) {
+ return false;
+ }
+ VduArtifact castOther = (VduArtifact) other;
+ return new EqualsBuilder().append(name, castOther.name).append(content, castOther.content)
+ .append(type, castOther.type).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(name).append(content).append(type).toHashCode();
+ }
+
+ // Default constructor
+ public VduArtifact() {}
+
+ // Fully specified constructor
+ public VduArtifact(String name, byte[] content, ArtifactType type) {
+ this.name = name;
+ this.content = content;
+ this.type = type;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public byte[] getContent() {
+ return content;
+ }
+
+ public void setContent(byte[] content) {
+ this.content = content;
+ }
+
+ public ArtifactType getType() {
+ return type;
+ }
+
+ public void setType(ArtifactType type) {
+ this.type = type;
+ }
+
+
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduException.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduException.java
index c611b87e5c..acb2e6172a 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduException.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduException.java
@@ -26,35 +26,36 @@ import org.onap.so.openstack.exceptions.MsoExceptionCategory;
/**
* OpenStack exception.
*/
-public class VduException extends MsoException
-{
-
- /**
+public class VduException extends MsoException {
+
+ /**
* Serialization id.
*/
private static final long serialVersionUID = 3313636124141766495L;
-
- /**
- * Constructor to create a new VduException instance
- * @param detail error details
- */
- public VduException (String detail) {
- // Set the detailed error as the Exception 'message'
- super(detail);
- // TODO: Need a more generic category than OPENSTACK
- super.category = MsoExceptionCategory.OPENSTACK;
- }
-
- /**
- * Constructor to create a new VduException instance
- * @param detail error details
- * @param e the cause
- */
- public VduException (String detail, Exception e) {
- // Set the detailed error as the Exception 'message'
- super(detail, e);
- // TODO: Need a more generic category than OPENSTACK
- super.category = MsoExceptionCategory.OPENSTACK;
- }
-} \ No newline at end of file
+ /**
+ * Constructor to create a new VduException instance
+ *
+ * @param detail error details
+ */
+ public VduException(String detail) {
+ // Set the detailed error as the Exception 'message'
+ super(detail);
+ // TODO: Need a more generic category than OPENSTACK
+ super.category = MsoExceptionCategory.OPENSTACK;
+ }
+
+ /**
+ * Constructor to create a new VduException instance
+ *
+ * @param detail error details
+ * @param e the cause
+ */
+ public VduException(String detail, Exception e) {
+ // Set the detailed error as the Exception 'message'
+ super(detail, e);
+ // TODO: Need a more generic category than OPENSTACK
+ super.category = MsoExceptionCategory.OPENSTACK;
+ }
+
+}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduInstance.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduInstance.java
index 8f5f0f9745..0c625e5534 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduInstance.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduInstance.java
@@ -26,55 +26,54 @@ import java.util.HashMap;
/*
* This Java bean class relays VDU status information in a cloud-agnostic format.
*
- * This bean is returned by all implementors of the VduPlugin interface operations
- * (instantiate, query, delete).
+ * This bean is returned by all implementors of the VduPlugin interface operations (instantiate, query, delete).
*/
public class VduInstance {
- // Set defaults for everything
- protected String vduInstanceId;
- protected String vduInstanceName;
- protected VduStatus status;
- protected Map<String, Object> outputs = new HashMap<>();
- protected Map<String, Object> inputs = new HashMap<>();
+ // Set defaults for everything
+ protected String vduInstanceId;
+ protected String vduInstanceName;
+ protected VduStatus status;
+ protected Map<String, Object> outputs = new HashMap<>();
+ protected Map<String, Object> inputs = new HashMap<>();
- public String getVduInstanceId() {
- return vduInstanceId;
- }
+ public String getVduInstanceId() {
+ return vduInstanceId;
+ }
- public void setVduInstanceId(String vduInstanceId) {
- this.vduInstanceId = vduInstanceId;
- }
+ public void setVduInstanceId(String vduInstanceId) {
+ this.vduInstanceId = vduInstanceId;
+ }
- public String getVduInstanceName() {
- return vduInstanceName;
- }
+ public String getVduInstanceName() {
+ return vduInstanceName;
+ }
- public void setVduInstanceName(String vduInstanceName) {
- this.vduInstanceName = vduInstanceName;
- }
+ public void setVduInstanceName(String vduInstanceName) {
+ this.vduInstanceName = vduInstanceName;
+ }
- public VduStatus getStatus() {
- return status;
- }
+ public VduStatus getStatus() {
+ return status;
+ }
- public void setStatus(VduStatus status) {
- this.status = status;
- }
+ public void setStatus(VduStatus status) {
+ this.status = status;
+ }
- public Map<String, Object> getOutputs() {
- return outputs;
- }
+ public Map<String, Object> getOutputs() {
+ return outputs;
+ }
- public void setOutputs(Map<String, Object> outputs) {
- this.outputs = outputs;
- }
+ public void setOutputs(Map<String, Object> outputs) {
+ this.outputs = outputs;
+ }
- public Map<String, Object> getInputs() {
- return inputs;
- }
+ public Map<String, Object> getInputs() {
+ return inputs;
+ }
- public void setInputs(Map<String, Object> inputs) {
- this.inputs = inputs;
- }
-} \ No newline at end of file
+ public void setInputs(Map<String, Object> inputs) {
+ this.inputs = inputs;
+ }
+}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduModelInfo.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduModelInfo.java
index a3ce1b5a6c..d22b735ff6 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduModelInfo.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduModelInfo.java
@@ -24,41 +24,50 @@ import java.util.ArrayList;
import java.util.List;
public class VduModelInfo {
- private String modelCustomizationUUID;
- private String modelUUID;
- private String modelInvariantUUID;
- private int timeoutMinutes;
- private List<VduArtifact> artifacts = new ArrayList<>();
+ private String modelCustomizationUUID;
+ private String modelUUID;
+ private String modelInvariantUUID;
+ private int timeoutMinutes;
+ private List<VduArtifact> artifacts = new ArrayList<>();
+
+ public String getModelCustomizationUUID() {
+ return modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
- public String getModelCustomizationUUID() {
- return modelCustomizationUUID;
- }
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
public String getModelUUID() {
return modelUUID;
}
+
public void setModelUUID(String modelUUID) {
this.modelUUID = modelUUID;
}
+
public String getModelInvariantUUID() {
return modelInvariantUUID;
}
+
public void setModelInvariantUUID(String modelInvariantUUID) {
this.modelInvariantUUID = modelInvariantUUID;
}
- public int getTimeoutMinutes() {
- return timeoutMinutes;
- }
- public void setTimeoutMinutes(int timeoutMinutes) {
- this.timeoutMinutes = timeoutMinutes;
- }
- public List<VduArtifact> getArtifacts() {
- return artifacts;
- }
- public void setArtifacts(List<VduArtifact> artifacts) {
- this.artifacts = artifacts;
- }
-} \ No newline at end of file
+ public int getTimeoutMinutes() {
+ return timeoutMinutes;
+ }
+
+ public void setTimeoutMinutes(int timeoutMinutes) {
+ this.timeoutMinutes = timeoutMinutes;
+ }
+
+ public List<VduArtifact> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(List<VduArtifact> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStateType.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStateType.java
index 0b95b392f6..8870f5c7b5 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStateType.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStateType.java
@@ -25,12 +25,7 @@ package org.onap.so.adapters.vdu;
* Enum status values to capture the state of a generic (cloud-agnostic) VDU.
*/
public enum VduStateType {
- NOTFOUND,
- INSTANTIATING,
- INSTANTIATED,
- DELETING,
- DELETED, // Note - only returned in success response to deleteVdu call.
- UPDATING,
- FAILED,
- UNKNOWN
+ NOTFOUND, INSTANTIATING, INSTANTIATED, DELETING, DELETED, // Note - only returned in success response to deleteVdu
+ // call.
+ UPDATING, FAILED, UNKNOWN
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStatus.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStatus.java
index 7797c997a5..331b7e7584 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStatus.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStatus.java
@@ -21,38 +21,46 @@
package org.onap.so.adapters.vdu;
public class VduStatus {
-
- private VduStateType state;
- private String errorMessage;
- private PluginAction lastAction;
-
- public VduStatus(){}
- public VduStatus( VduStateType state) {
- this.state = state;
- }
- public VduStateType getState() {
- return state;
- }
- public void setState(VduStateType state) {
- this.state = state;
- }
- public String getErrorMessage() {
- return errorMessage;
- }
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
- public PluginAction getLastAction() {
- return lastAction;
- }
- public void setLastAction(PluginAction lastAction) {
- this.lastAction = lastAction;
- }
- public void setLastAction (String action, String status, String rawCloudMessage) {
- lastAction = new PluginAction();
- lastAction.setAction (action);
- lastAction.setStatus (status);
- lastAction.setRawMessage(rawCloudMessage);
- }
-
-} \ No newline at end of file
+
+ private VduStateType state;
+ private String errorMessage;
+ private PluginAction lastAction;
+
+ public VduStatus() {}
+
+ public VduStatus(VduStateType state) {
+ this.state = state;
+ }
+
+ public VduStateType getState() {
+ return state;
+ }
+
+ public void setState(VduStateType state) {
+ this.state = state;
+ }
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public PluginAction getLastAction() {
+ return lastAction;
+ }
+
+ public void setLastAction(PluginAction lastAction) {
+ this.lastAction = lastAction;
+ }
+
+ public void setLastAction(String action, String status, String rawCloudMessage) {
+ lastAction = new PluginAction();
+ lastAction.setAction(action);
+ lastAction.setStatus(status);
+ lastAction.setRawMessage(rawCloudMessage);
+ }
+
+}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVfModuleRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVfModuleRequest.java
index 80e0a95b27..fb8fb2ed84 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVfModuleRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVfModuleRequest.java
@@ -22,209 +22,207 @@ package org.onap.so.adapters.vnfrest;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
-
import org.onap.so.entity.MsoRequest;
import org.onap.so.openstack.mappers.MapAdapter;
-
import com.fasterxml.jackson.annotation.JsonRootName;
-/* README
- Map<String, String> elements when marshalled to XML produce a list of <entry><key>${MsoUtils.xmlEscape(key)}</key><value>${MsoUtils.xmlEscape(value)}</value></entry> elements.
- When marshalling to JSON they create a list of "${key}" : "${value}" pairs with no extra wrappers.
-*/
+/*
+ * README Map<String, String> elements when marshalled to XML produce a list of
+ * <entry><key>${MsoUtils.xmlEscape(key)}</key><value>${MsoUtils.xmlEscape(value)}</value></entry> elements. When
+ * marshalling to JSON they create a list of "${key}" : "${value}" pairs with no extra wrappers.
+ */
@JsonRootName("createVfModuleRequest")
@XmlRootElement(name = "createVfModuleRequest")
@XmlAccessorType(XmlAccessType.FIELD)
public class CreateVfModuleRequest extends VfRequestCommon {
- private String cloudSiteId;
- private String cloudOwner;
- private String tenantId;
-
- private String vnfId;
- private String vnfType;
- private String vnfVersion;
-
- private String vfModuleId;
- private String vfModuleName;
- private String vfModuleType;
-
- private String volumeGroupId;
- private String volumeGroupStackId;
- private String baseVfModuleId;
- private String baseVfModuleStackId;
- private String modelCustomizationUuid;
-
- private String requestType;
- private Boolean failIfExists = false;
- private Boolean backout = true;
- private Boolean enableBridge;
- @XmlJavaTypeAdapter(MapAdapter.class)
- private Map<String, Object> vfModuleParams = new HashMap<>();
- private MsoRequest msoRequest = new MsoRequest();
-
- public String getCloudSiteId() {
- return cloudSiteId;
- }
-
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
-
- public String getCloudOwner() {
- return cloudOwner;
- }
-
- public void setCloudOwner(String cloudOwner) {
- this.cloudOwner = cloudOwner;
- }
-
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getVnfId() {
- return vnfId;
- }
-
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
-
- public String getVfModuleName() {
- return vfModuleName;
- }
-
- public void setVfModuleName(String vfModuleName) {
- this.vfModuleName = vfModuleName;
- }
-
- public String getVnfType() {
- return vnfType;
- }
-
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
-
- public String getVnfVersion() {
- return vnfVersion;
- }
-
- public void setVnfVersion(String vnfVersion) {
- this.vnfVersion = vnfVersion;
- }
-
- public String getVfModuleId() {
- return vfModuleId;
- }
-
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
-
- public String getVfModuleType() {
- return vfModuleType;
- }
-
- public void setVfModuleType(String vfModuleType) {
- this.vfModuleType = vfModuleType;
- }
-
- public String getVolumeGroupId() {
- return volumeGroupId;
- }
-
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
-
- public String getVolumeGroupStackId() {
- return volumeGroupStackId;
- }
-
- public void setVolumeGroupStackId(String volumeGroupStackId) {
- this.volumeGroupStackId = volumeGroupStackId;
- }
-
- public String getBaseVfModuleId() {
- return baseVfModuleId;
- }
-
- public void setBaseVfModuleId(String baseVfModuleId) {
- this.baseVfModuleId = baseVfModuleId;
- }
-
- public String getBaseVfModuleStackId() {
- return baseVfModuleStackId;
- }
+ private String cloudSiteId;
+ private String cloudOwner;
+ private String tenantId;
+
+ private String vnfId;
+ private String vnfType;
+ private String vnfVersion;
+
+ private String vfModuleId;
+ private String vfModuleName;
+ private String vfModuleType;
+
+ private String volumeGroupId;
+ private String volumeGroupStackId;
+ private String baseVfModuleId;
+ private String baseVfModuleStackId;
+ private String modelCustomizationUuid;
+
+ private String requestType;
+ private Boolean failIfExists = false;
+ private Boolean backout = true;
+ private Boolean enableBridge;
+ @XmlJavaTypeAdapter(MapAdapter.class)
+ private Map<String, Object> vfModuleParams = new HashMap<>();
+ private MsoRequest msoRequest = new MsoRequest();
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
+
+ public String getCloudOwner() {
+ return cloudOwner;
+ }
+
+ public void setCloudOwner(String cloudOwner) {
+ this.cloudOwner = cloudOwner;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getVfModuleName() {
+ return vfModuleName;
+ }
+
+ public void setVfModuleName(String vfModuleName) {
+ this.vfModuleName = vfModuleName;
+ }
+
+ public String getVnfType() {
+ return vnfType;
+ }
+
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ public String getVnfVersion() {
+ return vnfVersion;
+ }
+
+ public void setVnfVersion(String vnfVersion) {
+ this.vnfVersion = vnfVersion;
+ }
+
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ public String getVfModuleType() {
+ return vfModuleType;
+ }
+
+ public void setVfModuleType(String vfModuleType) {
+ this.vfModuleType = vfModuleType;
+ }
+
+ public String getVolumeGroupId() {
+ return volumeGroupId;
+ }
+
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ public String getVolumeGroupStackId() {
+ return volumeGroupStackId;
+ }
+
+ public void setVolumeGroupStackId(String volumeGroupStackId) {
+ this.volumeGroupStackId = volumeGroupStackId;
+ }
+
+ public String getBaseVfModuleId() {
+ return baseVfModuleId;
+ }
+
+ public void setBaseVfModuleId(String baseVfModuleId) {
+ this.baseVfModuleId = baseVfModuleId;
+ }
+
+ public String getBaseVfModuleStackId() {
+ return baseVfModuleStackId;
+ }
- public void setBaseVfModuleStackId(String baseVfModuleStackId) {
- this.baseVfModuleStackId = baseVfModuleStackId;
- }
+ public void setBaseVfModuleStackId(String baseVfModuleStackId) {
+ this.baseVfModuleStackId = baseVfModuleStackId;
+ }
- public String getModelCustomizationUuid() {
- return this.modelCustomizationUuid;
- }
+ public String getModelCustomizationUuid() {
+ return this.modelCustomizationUuid;
+ }
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
- public String getRequestType() {
- return requestType;
- }
+ public String getRequestType() {
+ return requestType;
+ }
- public void setRequestType(String requestType) {
- this.requestType = requestType;
- }
+ public void setRequestType(String requestType) {
+ this.requestType = requestType;
+ }
- public Boolean getFailIfExists() {
- return failIfExists;
- }
+ public Boolean getFailIfExists() {
+ return failIfExists;
+ }
- public void setFailIfExists(Boolean failIfExists) {
- this.failIfExists = failIfExists;
- }
+ public void setFailIfExists(Boolean failIfExists) {
+ this.failIfExists = failIfExists;
+ }
- public Boolean getBackout() {
- return backout;
- }
+ public Boolean getBackout() {
+ return backout;
+ }
- public void setBackout(Boolean backout) {
- this.backout = backout;
- }
+ public void setBackout(Boolean backout) {
+ this.backout = backout;
+ }
- public Map<String, Object> getVfModuleParams() {
- return vfModuleParams;
- }
+ public Map<String, Object> getVfModuleParams() {
+ return vfModuleParams;
+ }
- public void setVfModuleParams(Map<String, Object> vfModuleParams) {
- this.vfModuleParams = vfModuleParams;
- }
+ public void setVfModuleParams(Map<String, Object> vfModuleParams) {
+ this.vfModuleParams = vfModuleParams;
+ }
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
- public Boolean getEnableBridge() {
- return this.enableBridge;
- }
+ public Boolean getEnableBridge() {
+ return this.enableBridge;
+ }
- public void setEnableBridge(Boolean enableBridge) {
- this.enableBridge = enableBridge;
- }
+ public void setEnableBridge(Boolean enableBridge) {
+ this.enableBridge = enableBridge;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVfModuleResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVfModuleResponse.java
index b9d1f4c376..abcb6bdf1a 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVfModuleResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVfModuleResponse.java
@@ -23,83 +23,79 @@ package org.onap.so.adapters.vnfrest;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("createVfModuleResponse")
@XmlRootElement(name = "createVfModuleResponse")
public class CreateVfModuleResponse extends VfResponseCommon {
- private String vnfId;
- private String vfModuleId;
- private String vfModuleStackId;
- private Boolean vfModuleCreated;
- private Map<String,String> vfModuleOutputs = new HashMap<>();
- private VfModuleRollback rollback = new VfModuleRollback();
-
- public CreateVfModuleResponse() {
- super();
- }
-
- public CreateVfModuleResponse(String vnfId, String vfModuleId,
- String vfModuleStackId, Boolean vfModuleCreated,
- Map<String, String> vfModuleOutputs, VfModuleRollback rollback,
- String messageId) {
- super(messageId);
- this.vnfId = vnfId;
- this.vfModuleId = vfModuleId;
- this.vfModuleStackId = vfModuleStackId;
- this.vfModuleCreated = vfModuleCreated;
- this.vfModuleOutputs = vfModuleOutputs;
- this.rollback = rollback;
- }
-
- public String getVnfId() {
- return vnfId;
- }
-
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
-
- public String getVfModuleId() {
- return vfModuleId;
- }
-
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
-
- public String getVfModuleStackId() {
- return vfModuleStackId;
- }
-
- public void setVfModuleStackId(String vfModuleStackId) {
- this.vfModuleStackId = vfModuleStackId;
- }
-
- public Boolean getVfModuleCreated() {
- return vfModuleCreated;
- }
-
- public void setVfModuleCreated(Boolean vfModuleCreated) {
- this.vfModuleCreated = vfModuleCreated;
- }
-
- public Map<String, String> getVfModuleOutputs() {
- return vfModuleOutputs;
- }
-
- public void setVfModuleOutputs(Map<String, String> vfModuleOutputs) {
- this.vfModuleOutputs = vfModuleOutputs;
- }
-
- public VfModuleRollback getRollback() {
- return rollback;
- }
-
- public void setRollback(VfModuleRollback rollback) {
- this.rollback = rollback;
- }
+ private String vnfId;
+ private String vfModuleId;
+ private String vfModuleStackId;
+ private Boolean vfModuleCreated;
+ private Map<String, String> vfModuleOutputs = new HashMap<>();
+ private VfModuleRollback rollback = new VfModuleRollback();
+
+ public CreateVfModuleResponse() {
+ super();
+ }
+
+ public CreateVfModuleResponse(String vnfId, String vfModuleId, String vfModuleStackId, Boolean vfModuleCreated,
+ Map<String, String> vfModuleOutputs, VfModuleRollback rollback, String messageId) {
+ super(messageId);
+ this.vnfId = vnfId;
+ this.vfModuleId = vfModuleId;
+ this.vfModuleStackId = vfModuleStackId;
+ this.vfModuleCreated = vfModuleCreated;
+ this.vfModuleOutputs = vfModuleOutputs;
+ this.rollback = rollback;
+ }
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ public String getVfModuleStackId() {
+ return vfModuleStackId;
+ }
+
+ public void setVfModuleStackId(String vfModuleStackId) {
+ this.vfModuleStackId = vfModuleStackId;
+ }
+
+ public Boolean getVfModuleCreated() {
+ return vfModuleCreated;
+ }
+
+ public void setVfModuleCreated(Boolean vfModuleCreated) {
+ this.vfModuleCreated = vfModuleCreated;
+ }
+
+ public Map<String, String> getVfModuleOutputs() {
+ return vfModuleOutputs;
+ }
+
+ public void setVfModuleOutputs(Map<String, String> vfModuleOutputs) {
+ this.vfModuleOutputs = vfModuleOutputs;
+ }
+
+ public VfModuleRollback getRollback() {
+ return rollback;
+ }
+
+ public void setRollback(VfModuleRollback rollback) {
+ this.rollback = rollback;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVolumeGroupRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVolumeGroupRequest.java
index a1443f569a..2cb8c0a0ca 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVolumeGroupRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVolumeGroupRequest.java
@@ -23,150 +23,147 @@ package org.onap.so.adapters.vnfrest;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
-
import org.onap.so.entity.MsoRequest;
import org.onap.so.openstack.mappers.MapAdapter;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("createVolumeGroupRequest")
@XmlRootElement(name = "createVolumeGroupRequest")
@XmlAccessorType(XmlAccessType.FIELD)
public class CreateVolumeGroupRequest extends VfRequestCommon {
- private String cloudSiteId;
- private String cloudOwner;
- private String tenantId;
- private String volumeGroupName;
- private String volumeGroupId;
- private String vnfType;
- private String vnfVersion;
- private String vfModuleType;
- private String modelCustomizationUuid;
- @XmlJavaTypeAdapter(MapAdapter.class)
- private Map<String,Object> volumeGroupParams = new HashMap<>();
- private Boolean failIfExists;
- private Boolean enableBridge;
- private Boolean suppressBackout;
- private MsoRequest msoRequest = new MsoRequest();
-
- public CreateVolumeGroupRequest() {
- super();
- }
-
- public String getCloudSiteId() {
- return cloudSiteId;
- }
-
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
-
- public String getCloudOwner() {
- return cloudOwner;
- }
-
- public void setCloudOwner(String cloudOwner) {
- this.cloudOwner = cloudOwner;
- }
-
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getVnfType() {
- return vnfType;
- }
-
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
-
- public String getVnfVersion() {
- return vnfVersion;
- }
-
- public void setVnfVersion(String vnfVersion) {
- this.vnfVersion = vnfVersion;
- }
-
- public String getVfModuleType() {
- return vfModuleType;
- }
-
- public void setVfModuleType(String vfModuleType) {
- this.vfModuleType = vfModuleType;
- }
-
- public Map<String, Object> getVolumeGroupParams() {
- return volumeGroupParams;
- }
-
- public void setVolumeGroupParams(Map<String, Object> volumeGroupParams) {
- this.volumeGroupParams = volumeGroupParams;
- }
-
- public String getVolumeGroupName() {
- return volumeGroupName;
- }
-
- public void setVolumeGroupName(String volumeGroupName) {
- this.volumeGroupName = volumeGroupName;
- }
-
- public String getVolumeGroupId() {
- return volumeGroupId;
- }
-
- public String getModelCustomizationUuid() {
- return this.modelCustomizationUuid;
- }
-
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
-
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
-
- public Boolean getFailIfExists() {
- return failIfExists;
- }
-
- public void setFailIfExists(Boolean failIfExists) {
- this.failIfExists = failIfExists;
- }
-
- public Boolean getSuppressBackout() {
- return suppressBackout;
- }
-
- public void setSuppressBackout(Boolean suppressBackout) {
- this.suppressBackout = suppressBackout;
- }
+ private String cloudSiteId;
+ private String cloudOwner;
+ private String tenantId;
+ private String volumeGroupName;
+ private String volumeGroupId;
+ private String vnfType;
+ private String vnfVersion;
+ private String vfModuleType;
+ private String modelCustomizationUuid;
+ @XmlJavaTypeAdapter(MapAdapter.class)
+ private Map<String, Object> volumeGroupParams = new HashMap<>();
+ private Boolean failIfExists;
+ private Boolean enableBridge;
+ private Boolean suppressBackout;
+ private MsoRequest msoRequest = new MsoRequest();
+
+ public CreateVolumeGroupRequest() {
+ super();
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
+
+ public String getCloudOwner() {
+ return cloudOwner;
+ }
+
+ public void setCloudOwner(String cloudOwner) {
+ this.cloudOwner = cloudOwner;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getVnfType() {
+ return vnfType;
+ }
+
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ public String getVnfVersion() {
+ return vnfVersion;
+ }
+
+ public void setVnfVersion(String vnfVersion) {
+ this.vnfVersion = vnfVersion;
+ }
+
+ public String getVfModuleType() {
+ return vfModuleType;
+ }
+
+ public void setVfModuleType(String vfModuleType) {
+ this.vfModuleType = vfModuleType;
+ }
+
+ public Map<String, Object> getVolumeGroupParams() {
+ return volumeGroupParams;
+ }
+
+ public void setVolumeGroupParams(Map<String, Object> volumeGroupParams) {
+ this.volumeGroupParams = volumeGroupParams;
+ }
+
+ public String getVolumeGroupName() {
+ return volumeGroupName;
+ }
+
+ public void setVolumeGroupName(String volumeGroupName) {
+ this.volumeGroupName = volumeGroupName;
+ }
+
+ public String getVolumeGroupId() {
+ return volumeGroupId;
+ }
+
+ public String getModelCustomizationUuid() {
+ return this.modelCustomizationUuid;
+ }
+
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ public Boolean getFailIfExists() {
+ return failIfExists;
+ }
+
+ public void setFailIfExists(Boolean failIfExists) {
+ this.failIfExists = failIfExists;
+ }
+
+ public Boolean getSuppressBackout() {
+ return suppressBackout;
+ }
+
+ public void setSuppressBackout(Boolean suppressBackout) {
+ this.suppressBackout = suppressBackout;
+ }
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
- public Boolean getEnableBridge() {
- return enableBridge;
- }
+ public Boolean getEnableBridge() {
+ return enableBridge;
+ }
- public void setEnableBridge(Boolean enableBridge) {
- this.enableBridge = enableBridge;
- }
+ public void setEnableBridge(Boolean enableBridge) {
+ this.enableBridge = enableBridge;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVolumeGroupResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVolumeGroupResponse.java
index d98318d3e6..780aec38c0 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVolumeGroupResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/CreateVolumeGroupResponse.java
@@ -23,78 +23,70 @@ package org.onap.so.adapters.vnfrest;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("createVolumeGroupResponse")
@XmlRootElement(name = "createVolumeGroupResponse")
public class CreateVolumeGroupResponse extends VfResponseCommon {
- private String volumeGroupId;
- private String volumeGroupStackId;
- private Boolean volumeGroupCreated;
- private Map<String,String> volumeGroupOutputs = new HashMap<>();
- private VolumeGroupRollback volumeGroupRollback = new VolumeGroupRollback();
-
- public CreateVolumeGroupResponse() {
- super();
- }
-
- public CreateVolumeGroupResponse(
- String volumeGroupId,
- String volumeGroupStackId,
- Boolean volumeGroupCreated,
- Map<String, String> volumeGroupOutputs,
- VolumeGroupRollback volumeGroupRollback,
- String messageId)
- {
- super(messageId);
- this.volumeGroupId = volumeGroupId;
- this.volumeGroupStackId = volumeGroupStackId;
- this.volumeGroupCreated = volumeGroupCreated;
- this.volumeGroupOutputs = volumeGroupOutputs;
- this.volumeGroupRollback = volumeGroupRollback;
- }
-
- public String getVolumeGroupId() {
- return volumeGroupId;
- }
-
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
-
- public String getVolumeGroupStackId() {
- return volumeGroupStackId;
- }
-
- public void setVolumeGroupStackId(String volumeGroupStackId) {
- this.volumeGroupStackId = volumeGroupStackId;
- }
-
- public Boolean getVolumeGroupCreated() {
- return volumeGroupCreated;
- }
-
- public void setVolumeGroupCreated(Boolean volumeGroupCreated) {
- this.volumeGroupCreated = volumeGroupCreated;
- }
-
- public Map<String, String> getVolumeGroupOutputs() {
- return volumeGroupOutputs;
- }
-
- public void setVolumeGroupOutputs(Map<String, String> volumeGroupOutputs) {
- this.volumeGroupOutputs = volumeGroupOutputs;
- }
-
- public VolumeGroupRollback getVolumeGroupRollback() {
- return volumeGroupRollback;
- }
-
- public void setVolumeGroupRollback(VolumeGroupRollback volumeGroupRollback) {
- this.volumeGroupRollback = volumeGroupRollback;
- }
+ private String volumeGroupId;
+ private String volumeGroupStackId;
+ private Boolean volumeGroupCreated;
+ private Map<String, String> volumeGroupOutputs = new HashMap<>();
+ private VolumeGroupRollback volumeGroupRollback = new VolumeGroupRollback();
+
+ public CreateVolumeGroupResponse() {
+ super();
+ }
+
+ public CreateVolumeGroupResponse(String volumeGroupId, String volumeGroupStackId, Boolean volumeGroupCreated,
+ Map<String, String> volumeGroupOutputs, VolumeGroupRollback volumeGroupRollback, String messageId) {
+ super(messageId);
+ this.volumeGroupId = volumeGroupId;
+ this.volumeGroupStackId = volumeGroupStackId;
+ this.volumeGroupCreated = volumeGroupCreated;
+ this.volumeGroupOutputs = volumeGroupOutputs;
+ this.volumeGroupRollback = volumeGroupRollback;
+ }
+
+ public String getVolumeGroupId() {
+ return volumeGroupId;
+ }
+
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ public String getVolumeGroupStackId() {
+ return volumeGroupStackId;
+ }
+
+ public void setVolumeGroupStackId(String volumeGroupStackId) {
+ this.volumeGroupStackId = volumeGroupStackId;
+ }
+
+ public Boolean getVolumeGroupCreated() {
+ return volumeGroupCreated;
+ }
+
+ public void setVolumeGroupCreated(Boolean volumeGroupCreated) {
+ this.volumeGroupCreated = volumeGroupCreated;
+ }
+
+ public Map<String, String> getVolumeGroupOutputs() {
+ return volumeGroupOutputs;
+ }
+
+ public void setVolumeGroupOutputs(Map<String, String> volumeGroupOutputs) {
+ this.volumeGroupOutputs = volumeGroupOutputs;
+ }
+
+ public VolumeGroupRollback getVolumeGroupRollback() {
+ return volumeGroupRollback;
+ }
+
+ public void setVolumeGroupRollback(VolumeGroupRollback volumeGroupRollback) {
+ this.volumeGroupRollback = volumeGroupRollback;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVfModuleRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVfModuleRequest.java
index d9825ddca2..6a979d754b 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVfModuleRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVfModuleRequest.java
@@ -22,86 +22,83 @@ package org.onap.so.adapters.vnfrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.entity.MsoRequest;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("deleteVfModuleRequest")
@XmlRootElement(name = "deleteVfModuleRequest")
public class DeleteVfModuleRequest extends VfRequestCommon implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -8504083539107392561L;
- private String cloudSiteId;
- private String cloudOwner;
- private String tenantId;
- private String vnfId;
- private String vfModuleId;
- private String vfModuleStackId;
-
- private MsoRequest msoRequest = new MsoRequest();
-
- public DeleteVfModuleRequest() {
- super();
- }
-
- public String getCloudSiteId() {
- return cloudSiteId;
- }
-
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
-
- public String getCloudOwner() {
- return cloudOwner;
- }
-
- public void setCloudOwner(String cloudOwner) {
- this.cloudOwner = cloudOwner;
- }
-
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getVnfId() {
- return vnfId;
- }
-
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
-
- public String getVfModuleId() {
- return vfModuleId;
- }
-
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
-
- public String getVfModuleStackId() {
- return vfModuleStackId;
- }
-
- public void setVfModuleStackId(String vfModuleStackId) {
- this.vfModuleStackId = vfModuleStackId;
- }
-
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
-
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -8504083539107392561L;
+ private String cloudSiteId;
+ private String cloudOwner;
+ private String tenantId;
+ private String vnfId;
+ private String vfModuleId;
+ private String vfModuleStackId;
+
+ private MsoRequest msoRequest = new MsoRequest();
+
+ public DeleteVfModuleRequest() {
+ super();
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
+
+ public String getCloudOwner() {
+ return cloudOwner;
+ }
+
+ public void setCloudOwner(String cloudOwner) {
+ this.cloudOwner = cloudOwner;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ public String getVfModuleStackId() {
+ return vfModuleStackId;
+ }
+
+ public void setVfModuleStackId(String vfModuleStackId) {
+ this.vfModuleStackId = vfModuleStackId;
+ }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVfModuleResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVfModuleResponse.java
index ca713d36a0..eac56e1ce9 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVfModuleResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVfModuleResponse.java
@@ -23,58 +23,59 @@ package org.onap.so.adapters.vnfrest;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("deleteVfModuleResponse")
@XmlRootElement(name = "deleteVfModuleResponse")
public class DeleteVfModuleResponse extends VfResponseCommon {
- private String vnfId;
- private String vfModuleId;
- private Boolean vfModuleDeleted;
- private Map<String,String> vfModuleOutputs = new HashMap<>();
- public DeleteVfModuleResponse() {
- super();
- }
+ private String vnfId;
+ private String vfModuleId;
+ private Boolean vfModuleDeleted;
+ private Map<String, String> vfModuleOutputs = new HashMap<>();
+
+ public DeleteVfModuleResponse() {
+ super();
+ }
+
+ public DeleteVfModuleResponse(String vnfId, String vfModuleId, Boolean vfModuleDeleted, String messageId,
+ Map<String, String> outputs) {
+ super(messageId);
+ this.vnfId = vnfId;
+ this.vfModuleId = vfModuleId;
+ this.vfModuleDeleted = vfModuleDeleted;
+ this.vfModuleOutputs = outputs;
+ }
- public DeleteVfModuleResponse(String vnfId, String vfModuleId, Boolean vfModuleDeleted, String messageId, Map<String,String> outputs) {
- super(messageId);
- this.vnfId = vnfId;
- this.vfModuleId = vfModuleId;
- this.vfModuleDeleted = vfModuleDeleted;
- this.vfModuleOutputs = outputs;
- }
+ public String getVnfId() {
+ return vnfId;
+ }
- public String getVnfId() {
- return vnfId;
- }
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
- public String getVfModuleId() {
- return vfModuleId;
- }
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
+ public Boolean getVfModuleDeleted() {
+ return vfModuleDeleted;
+ }
- public Boolean getVfModuleDeleted() {
- return vfModuleDeleted;
- }
+ public void setVfModuleDeleted(Boolean vfModuleDeleted) {
+ this.vfModuleDeleted = vfModuleDeleted;
+ }
- public void setVfModuleDeleted(Boolean vfModuleDeleted) {
- this.vfModuleDeleted = vfModuleDeleted;
- }
- public Map<String, String> getVfModuleOutputs() {
- return vfModuleOutputs;
- }
+ public Map<String, String> getVfModuleOutputs() {
+ return vfModuleOutputs;
+ }
- public void setVfModuleOutputs(Map<String, String> vfModuleOutputs) {
- this.vfModuleOutputs = vfModuleOutputs;
- }
+ public void setVfModuleOutputs(Map<String, String> vfModuleOutputs) {
+ this.vfModuleOutputs = vfModuleOutputs;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVolumeGroupRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVolumeGroupRequest.java
index aba53a4dd3..88c283da16 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVolumeGroupRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVolumeGroupRequest.java
@@ -22,33 +22,31 @@ package org.onap.so.adapters.vnfrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.entity.MsoRequest;
-
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.ToStringBuilder;
@JsonRootName("deleteVolumeGroupRequest")
@XmlRootElement(name = "deleteVolumeGroupRequest")
public class DeleteVolumeGroupRequest extends VfRequestCommon {
- private String cloudSiteId;
- private String cloudOwner;
- private String tenantId;
- private String volumeGroupId;
- private String volumeGroupStackId;
- private MsoRequest msoRequest = new MsoRequest();
-
- public DeleteVolumeGroupRequest() {
- super();
- }
+ private String cloudSiteId;
+ private String cloudOwner;
+ private String tenantId;
+ private String volumeGroupId;
+ private String volumeGroupStackId;
+ private MsoRequest msoRequest = new MsoRequest();
+
+ public DeleteVolumeGroupRequest() {
+ super();
+ }
- public String getCloudSiteId() {
- return cloudSiteId;
- }
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
public String getCloudOwner() {
return cloudOwner;
@@ -58,42 +56,42 @@ public class DeleteVolumeGroupRequest extends VfRequestCommon {
this.cloudOwner = cloudOwner;
}
- public String getTenantId() {
- return tenantId;
- }
+ public String getTenantId() {
+ return tenantId;
+ }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
- public String getVolumeGroupId() {
- return volumeGroupId;
- }
+ public String getVolumeGroupId() {
+ return volumeGroupId;
+ }
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
- public String getVolumeGroupStackId() {
- return volumeGroupStackId;
- }
+ public String getVolumeGroupStackId() {
+ return volumeGroupStackId;
+ }
- public void setVolumeGroupStackId(String volumeGroupStackId) {
- this.volumeGroupStackId = volumeGroupStackId;
- }
+ public void setVolumeGroupStackId(String volumeGroupStackId) {
+ this.volumeGroupStackId = volumeGroupStackId;
+ }
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
- @Override
- public String toString() {
- return new ToStringBuilder(this).appendSuper(super.toString()).append("cloudSiteId", cloudSiteId)
- .append("tenantId", tenantId).append("volumeGroupId", volumeGroupId)
- .append("volumeGroupStackId", volumeGroupStackId).append("msoRequest", msoRequest).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).appendSuper(super.toString()).append("cloudSiteId", cloudSiteId)
+ .append("tenantId", tenantId).append("volumeGroupId", volumeGroupId)
+ .append("volumeGroupStackId", volumeGroupStackId).append("msoRequest", msoRequest).toString();
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVolumeGroupResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVolumeGroupResponse.java
index 4a7442108a..d75090a827 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVolumeGroupResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/DeleteVolumeGroupResponse.java
@@ -22,28 +22,27 @@ package org.onap.so.adapters.vnfrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("deleteVolumeGroupResponse")
@XmlRootElement(name = "deleteVolumeGroupResponse")
public class DeleteVolumeGroupResponse extends VfResponseCommon {
- private Boolean volumeGroupDeleted;
+ private Boolean volumeGroupDeleted;
- public DeleteVolumeGroupResponse() {
- super();
- }
+ public DeleteVolumeGroupResponse() {
+ super();
+ }
- public DeleteVolumeGroupResponse(Boolean volumeGroupDeleted, String messageId) {
- super(messageId);
- this.volumeGroupDeleted = volumeGroupDeleted;
- }
+ public DeleteVolumeGroupResponse(Boolean volumeGroupDeleted, String messageId) {
+ super(messageId);
+ this.volumeGroupDeleted = volumeGroupDeleted;
+ }
- public Boolean getVolumeGroupDeleted() {
- return volumeGroupDeleted;
- }
+ public Boolean getVolumeGroupDeleted() {
+ return volumeGroupDeleted;
+ }
- public void setVolumeGroupDeleted(Boolean volumeGroupDeleted) {
- this.volumeGroupDeleted = volumeGroupDeleted;
- }
+ public void setVolumeGroupDeleted(Boolean volumeGroupDeleted) {
+ this.volumeGroupDeleted = volumeGroupDeleted;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVfModuleResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVfModuleResponse.java
index 3b480d8ea9..e48d99672a 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVfModuleResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVfModuleResponse.java
@@ -23,7 +23,6 @@
package org.onap.so.adapters.vnfrest;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
import org.onap.so.openstack.beans.VnfStatus;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -32,66 +31,66 @@ import org.slf4j.LoggerFactory;
@JsonRootName("queryVfModuleResponse")
@XmlRootElement(name = "queryVfModuleResponse")
-public class QueryVfModuleResponse extends VfResponseCommon{
- private static final Logger logger = LoggerFactory.getLogger(QueryVfModuleResponse.class);
- private String vnfId;
- private String vfModuleId;
- private String vfModuleStackId;
- private VnfStatus vnfStatus;
- private Map<String, String> vfModuleOutputs;
-
- public QueryVfModuleResponse() {
- super();
- }
-
- public QueryVfModuleResponse(String vnfId, String vfModuleId, String vfModuleStackId, VnfStatus vnfStatus,
- Map<String, String> vfModuleOutputs) {
- super();
- this.vnfId = vnfId;
- this.vfModuleId = vfModuleId;
- this.vfModuleStackId = vfModuleStackId;
- this.vnfStatus = vnfStatus;
- this.vfModuleOutputs = vfModuleOutputs;
- }
-
- public String getVnfId() {
- return vnfId;
- }
-
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
-
- public String getVfModuleId() {
- return vfModuleId;
- }
-
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
-
- public String getVfModuleStackId() {
- return vfModuleStackId;
- }
-
- public void setVfModuleStackId(String vfModuleStackId) {
- this.vfModuleStackId = vfModuleStackId;
- }
-
- public VnfStatus getVnfStatus() {
- return vnfStatus;
- }
-
- public void setVnfStatus(VnfStatus vnfStatus) {
- this.vnfStatus = vnfStatus;
- }
-
- public Map<String, String> getVfModuleOutputs() {
- return vfModuleOutputs;
- }
-
- public void setVfModuleOutputs(Map<String, String> vfModuleOutputs) {
- this.vfModuleOutputs = vfModuleOutputs;
- }
-
+public class QueryVfModuleResponse extends VfResponseCommon {
+ private static final Logger logger = LoggerFactory.getLogger(QueryVfModuleResponse.class);
+ private String vnfId;
+ private String vfModuleId;
+ private String vfModuleStackId;
+ private VnfStatus vnfStatus;
+ private Map<String, String> vfModuleOutputs;
+
+ public QueryVfModuleResponse() {
+ super();
+ }
+
+ public QueryVfModuleResponse(String vnfId, String vfModuleId, String vfModuleStackId, VnfStatus vnfStatus,
+ Map<String, String> vfModuleOutputs) {
+ super();
+ this.vnfId = vnfId;
+ this.vfModuleId = vfModuleId;
+ this.vfModuleStackId = vfModuleStackId;
+ this.vnfStatus = vnfStatus;
+ this.vfModuleOutputs = vfModuleOutputs;
+ }
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ public String getVfModuleStackId() {
+ return vfModuleStackId;
+ }
+
+ public void setVfModuleStackId(String vfModuleStackId) {
+ this.vfModuleStackId = vfModuleStackId;
+ }
+
+ public VnfStatus getVnfStatus() {
+ return vnfStatus;
+ }
+
+ public void setVnfStatus(VnfStatus vnfStatus) {
+ this.vnfStatus = vnfStatus;
+ }
+
+ public Map<String, String> getVfModuleOutputs() {
+ return vfModuleOutputs;
+ }
+
+ public void setVfModuleOutputs(Map<String, String> vfModuleOutputs) {
+ this.vfModuleOutputs = vfModuleOutputs;
+ }
+
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVolumeGroupResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVolumeGroupResponse.java
index f15c62493a..a95df93a27 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVolumeGroupResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVolumeGroupResponse.java
@@ -24,83 +24,73 @@ package org.onap.so.adapters.vnfrest;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.beans.VnfStatus;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@XmlRootElement(name = "queryVolumeGroupResponse")
public class QueryVolumeGroupResponse {
- private static final Logger logger = LoggerFactory.getLogger(QueryVolumeGroupResponse.class);
- private String volumeGroupId;
- private String volumeGroupStackId;
- private VnfStatus volumeGroupStatus;
- private Map<String,String> volumeGroupOutputs;
-
- public QueryVolumeGroupResponse() {
- }
-
- public QueryVolumeGroupResponse(
- String volumeGroupId,
- String volumeGroupStackId,
- VnfStatus volumeGroupStatus,
- Map<String, String> volumeGroupOutputs)
- {
- super();
- this.volumeGroupId = volumeGroupId;
- this.volumeGroupStackId = volumeGroupStackId;
- this.volumeGroupStatus = volumeGroupStatus;
- this.volumeGroupOutputs = volumeGroupOutputs;
- }
-
- public String getVolumeGroupId() {
- return volumeGroupId;
- }
-
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
-
- public String getVolumeGroupStackId() {
- return volumeGroupStackId;
- }
-
- public void setVolumeGroupStackId(String volumeGroupStackId) {
- this.volumeGroupStackId = volumeGroupStackId;
- }
-
- public VnfStatus getVolumeGroupStatus() {
- return volumeGroupStatus;
- }
-
- public void setVolumeGroupStatus(VnfStatus volumeGroupStatus) {
- this.volumeGroupStatus = volumeGroupStatus;
- }
-
- public Map<String, String> getVolumeGroupOutputs() {
- return volumeGroupOutputs;
- }
-
- public void setVolumeGroupOutputs(Map<String, String> volumeGroupOutputs) {
- this.volumeGroupOutputs = volumeGroupOutputs;
- }
-
- public String toJsonString() {
- String jsonString = null;
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- jsonString = mapper.writeValueAsString(this);
- }
- catch (Exception e) {
- logger.debug("Exception :", e);
- }
- return jsonString;
- }
+ private static final Logger logger = LoggerFactory.getLogger(QueryVolumeGroupResponse.class);
+ private String volumeGroupId;
+ private String volumeGroupStackId;
+ private VnfStatus volumeGroupStatus;
+ private Map<String, String> volumeGroupOutputs;
+
+ public QueryVolumeGroupResponse() {}
+
+ public QueryVolumeGroupResponse(String volumeGroupId, String volumeGroupStackId, VnfStatus volumeGroupStatus,
+ Map<String, String> volumeGroupOutputs) {
+ super();
+ this.volumeGroupId = volumeGroupId;
+ this.volumeGroupStackId = volumeGroupStackId;
+ this.volumeGroupStatus = volumeGroupStatus;
+ this.volumeGroupOutputs = volumeGroupOutputs;
+ }
+
+ public String getVolumeGroupId() {
+ return volumeGroupId;
+ }
+
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ public String getVolumeGroupStackId() {
+ return volumeGroupStackId;
+ }
+
+ public void setVolumeGroupStackId(String volumeGroupStackId) {
+ this.volumeGroupStackId = volumeGroupStackId;
+ }
+
+ public VnfStatus getVolumeGroupStatus() {
+ return volumeGroupStatus;
+ }
+
+ public void setVolumeGroupStatus(VnfStatus volumeGroupStatus) {
+ this.volumeGroupStatus = volumeGroupStatus;
+ }
+
+ public Map<String, String> getVolumeGroupOutputs() {
+ return volumeGroupOutputs;
+ }
+
+ public void setVolumeGroupOutputs(Map<String, String> volumeGroupOutputs) {
+ this.volumeGroupOutputs = volumeGroupOutputs;
+ }
+
+ public String toJsonString() {
+ String jsonString = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ jsonString = mapper.writeValueAsString(this);
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ }
+ return jsonString;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVfModuleRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVfModuleRequest.java
index 4ad7a7a417..351782f1fa 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVfModuleRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVfModuleRequest.java
@@ -22,24 +22,23 @@ package org.onap.so.adapters.vnfrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("rollbackVfModuleRequest")
@XmlRootElement(name = "rollbackVfModuleRequest")
public class RollbackVfModuleRequest extends VfRequestCommon {
- private VfModuleRollback vfModuleRollback;
+ private VfModuleRollback vfModuleRollback;
- public RollbackVfModuleRequest() {
- super();
- }
+ public RollbackVfModuleRequest() {
+ super();
+ }
- public VfModuleRollback getVfModuleRollback() {
- return vfModuleRollback;
- }
+ public VfModuleRollback getVfModuleRollback() {
+ return vfModuleRollback;
+ }
- public void setVfModuleRollback(VfModuleRollback vfModuleRollback) {
- this.vfModuleRollback = vfModuleRollback;
- }
+ public void setVfModuleRollback(VfModuleRollback vfModuleRollback) {
+ this.vfModuleRollback = vfModuleRollback;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVfModuleResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVfModuleResponse.java
index 43db90c566..dc9f42de1d 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVfModuleResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVfModuleResponse.java
@@ -22,28 +22,27 @@ package org.onap.so.adapters.vnfrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("rollbackVfModuleResponse")
@XmlRootElement(name = "rollbackVfModuleResponse")
public class RollbackVfModuleResponse extends VfResponseCommon {
- private Boolean vfModuleRolledback;
+ private Boolean vfModuleRolledback;
- public RollbackVfModuleResponse() {
- super();
- }
+ public RollbackVfModuleResponse() {
+ super();
+ }
- public RollbackVfModuleResponse(Boolean vfModuleRolledback, String messageId) {
- super(messageId);
- this.vfModuleRolledback = vfModuleRolledback;
- }
+ public RollbackVfModuleResponse(Boolean vfModuleRolledback, String messageId) {
+ super(messageId);
+ this.vfModuleRolledback = vfModuleRolledback;
+ }
- public Boolean getVfModuleRolledback() {
- return vfModuleRolledback;
- }
+ public Boolean getVfModuleRolledback() {
+ return vfModuleRolledback;
+ }
- public void setVfModuleRolledback(Boolean vfModuleRolledback) {
- this.vfModuleRolledback = vfModuleRolledback;
- }
+ public void setVfModuleRolledback(Boolean vfModuleRolledback) {
+ this.vfModuleRolledback = vfModuleRolledback;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVolumeGroupRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVolumeGroupRequest.java
index 14c2c2a3d9..534d9595da 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVolumeGroupRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVolumeGroupRequest.java
@@ -22,23 +22,22 @@ package org.onap.so.adapters.vnfrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("rollbackVolumeGroupRequest")
@XmlRootElement(name = "rollbackVolumeGroupRequest")
public class RollbackVolumeGroupRequest extends VfRequestCommon {
- private VolumeGroupRollback volumeGroupRollback;
+ private VolumeGroupRollback volumeGroupRollback;
- public RollbackVolumeGroupRequest() {
- super();
- }
+ public RollbackVolumeGroupRequest() {
+ super();
+ }
- public VolumeGroupRollback getVolumeGroupRollback() {
- return volumeGroupRollback;
- }
+ public VolumeGroupRollback getVolumeGroupRollback() {
+ return volumeGroupRollback;
+ }
- public void setVolumeGroupRollback(VolumeGroupRollback volumeGroupRollback) {
- this.volumeGroupRollback = volumeGroupRollback;
- }
+ public void setVolumeGroupRollback(VolumeGroupRollback volumeGroupRollback) {
+ this.volumeGroupRollback = volumeGroupRollback;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVolumeGroupResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVolumeGroupResponse.java
index 46ac26825c..6038d9702a 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVolumeGroupResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/RollbackVolumeGroupResponse.java
@@ -22,28 +22,27 @@ package org.onap.so.adapters.vnfrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("rollbackVolumeGroupResponse")
@XmlRootElement(name = "rollbackVolumeGroupResponse")
public class RollbackVolumeGroupResponse extends VfResponseCommon {
- private Boolean volumeGroupRolledBack;
+ private Boolean volumeGroupRolledBack;
- public RollbackVolumeGroupResponse() {
- super();
- }
+ public RollbackVolumeGroupResponse() {
+ super();
+ }
- public RollbackVolumeGroupResponse(Boolean volumeGroupRolledBack, String messageId) {
- super(messageId);
- this.volumeGroupRolledBack = volumeGroupRolledBack;
- }
+ public RollbackVolumeGroupResponse(Boolean volumeGroupRolledBack, String messageId) {
+ super(messageId);
+ this.volumeGroupRolledBack = volumeGroupRolledBack;
+ }
- public Boolean getVolumeGroupRolledBack() {
- return volumeGroupRolledBack;
- }
+ public Boolean getVolumeGroupRolledBack() {
+ return volumeGroupRolledBack;
+ }
- public void setVolumeGroupRolledBack(Boolean volumeGroupRolledBack) {
- this.volumeGroupRolledBack = volumeGroupRolledBack;
- }
+ public void setVolumeGroupRolledBack(Boolean volumeGroupRolledBack) {
+ this.volumeGroupRolledBack = volumeGroupRolledBack;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVfModuleRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVfModuleRequest.java
index a02dc1f94e..bb21502bc4 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVfModuleRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVfModuleRequest.java
@@ -23,15 +23,12 @@ package org.onap.so.adapters.vnfrest;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
-
import org.onap.so.entity.MsoRequest;
import org.onap.so.openstack.mappers.MapAdapter;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("updateVfModuleRequest")
@@ -39,42 +36,42 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@XmlAccessorType(XmlAccessType.FIELD)
public class UpdateVfModuleRequest extends VfRequestCommon {
- private String cloudSiteId;
- private String cloudOwner;
- private String tenantId;
+ private String cloudSiteId;
+ private String cloudOwner;
+ private String tenantId;
- private String vnfId;
- private String vnfType;
- private String vnfVersion;
+ private String vnfId;
+ private String vnfType;
+ private String vnfVersion;
- private String vfModuleName;
- private String vfModuleType;
- private String vfModuleId;
- private String vfModuleStackId;
+ private String vfModuleName;
+ private String vfModuleType;
+ private String vfModuleId;
+ private String vfModuleStackId;
- private String volumeGroupId;
- private String volumeGroupStackId;
+ private String volumeGroupId;
+ private String volumeGroupStackId;
- private String baseVfModuleId;
- private String baseVfModuleStackId;
+ private String baseVfModuleId;
+ private String baseVfModuleStackId;
- private String modelCustomizationUuid;
+ private String modelCustomizationUuid;
- private String requestType;
- private Boolean failIfExists;
- private Boolean backout;
+ private String requestType;
+ private Boolean failIfExists;
+ private Boolean backout;
- @XmlJavaTypeAdapter(MapAdapter.class)
- private Map<String,Object> vfModuleParams = new HashMap<>();
- private MsoRequest msoRequest = new MsoRequest();
+ @XmlJavaTypeAdapter(MapAdapter.class)
+ private Map<String, Object> vfModuleParams = new HashMap<>();
+ private MsoRequest msoRequest = new MsoRequest();
- public String getCloudSiteId() {
- return cloudSiteId;
- }
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
public String getCloudOwner() {
return cloudOwner;
@@ -84,147 +81,147 @@ public class UpdateVfModuleRequest extends VfRequestCommon {
this.cloudOwner = cloudOwner;
}
- public String getTenantId() {
- return tenantId;
- }
+ public String getTenantId() {
+ return tenantId;
+ }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
- public String getVnfId() {
- return vnfId;
- }
+ public String getVnfId() {
+ return vnfId;
+ }
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
- public String getVfModuleName() {
- return vfModuleName;
- }
+ public String getVfModuleName() {
+ return vfModuleName;
+ }
- public void setVfModuleName(String vfModuleName) {
- this.vfModuleName = vfModuleName;
- }
+ public void setVfModuleName(String vfModuleName) {
+ this.vfModuleName = vfModuleName;
+ }
- public String getVnfType() {
- return vnfType;
- }
+ public String getVnfType() {
+ return vnfType;
+ }
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
- public String getVnfVersion() {
- return vnfVersion;
- }
+ public String getVnfVersion() {
+ return vnfVersion;
+ }
- public void setVnfVersion(String vnfVersion) {
- this.vnfVersion = vnfVersion;
- }
+ public void setVnfVersion(String vnfVersion) {
+ this.vnfVersion = vnfVersion;
+ }
- public String getVfModuleId() {
- return vfModuleId;
- }
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
- public String getVfModuleType() {
- return vfModuleType;
- }
+ public String getVfModuleType() {
+ return vfModuleType;
+ }
- public void setVfModuleType(String vfModuleType) {
- this.vfModuleType = vfModuleType;
- }
+ public void setVfModuleType(String vfModuleType) {
+ this.vfModuleType = vfModuleType;
+ }
- public String getVfModuleStackId() {
- return vfModuleStackId;
- }
+ public String getVfModuleStackId() {
+ return vfModuleStackId;
+ }
- public void setVfModuleStackId(String vfModuleStackId) {
- this.vfModuleStackId = vfModuleStackId;
- }
+ public void setVfModuleStackId(String vfModuleStackId) {
+ this.vfModuleStackId = vfModuleStackId;
+ }
- public String getVolumeGroupId() {
- return volumeGroupId;
- }
+ public String getVolumeGroupId() {
+ return volumeGroupId;
+ }
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
- public String getVolumeGroupStackId() {
- return volumeGroupStackId;
- }
+ public String getVolumeGroupStackId() {
+ return volumeGroupStackId;
+ }
- public void setVolumeGroupStackId(String volumeGroupStackId) {
- this.volumeGroupStackId = volumeGroupStackId;
- }
+ public void setVolumeGroupStackId(String volumeGroupStackId) {
+ this.volumeGroupStackId = volumeGroupStackId;
+ }
- public String getBaseVfModuleId() {
- return baseVfModuleId;
- }
+ public String getBaseVfModuleId() {
+ return baseVfModuleId;
+ }
- public String getModelCustomizationUuid() {
- return this.modelCustomizationUuid;
- }
+ public String getModelCustomizationUuid() {
+ return this.modelCustomizationUuid;
+ }
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
- public void setBaseVfModuleId(String baseVfModuleId) {
- this.baseVfModuleId = baseVfModuleId;
- }
+ public void setBaseVfModuleId(String baseVfModuleId) {
+ this.baseVfModuleId = baseVfModuleId;
+ }
- public String getBaseVfModuleStackId() {
- return baseVfModuleStackId;
- }
+ public String getBaseVfModuleStackId() {
+ return baseVfModuleStackId;
+ }
- public void setBaseVfModuleStackId(String baseVfModuleStackId) {
- this.baseVfModuleStackId = baseVfModuleStackId;
- }
+ public void setBaseVfModuleStackId(String baseVfModuleStackId) {
+ this.baseVfModuleStackId = baseVfModuleStackId;
+ }
- public String getRequestType() {
- return requestType;
- }
+ public String getRequestType() {
+ return requestType;
+ }
- public void setRequestType(String requestType) {
- this.requestType = requestType;
- }
+ public void setRequestType(String requestType) {
+ this.requestType = requestType;
+ }
- public Boolean getFailIfExists() {
- return failIfExists;
- }
+ public Boolean getFailIfExists() {
+ return failIfExists;
+ }
- public void setFailIfExists(Boolean failIfExists) {
- this.failIfExists = failIfExists;
- }
+ public void setFailIfExists(Boolean failIfExists) {
+ this.failIfExists = failIfExists;
+ }
- public Boolean getBackout() {
- return backout;
- }
+ public Boolean getBackout() {
+ return backout;
+ }
- public void setBackout(Boolean backout) {
- this.backout = backout;
- }
+ public void setBackout(Boolean backout) {
+ this.backout = backout;
+ }
- public Map<String, Object> getVfModuleParams() {
- return vfModuleParams;
- }
+ public Map<String, Object> getVfModuleParams() {
+ return vfModuleParams;
+ }
- public void setVfModuleParams(Map<String, Object> vfModuleParams) {
- this.vfModuleParams = vfModuleParams;
- }
+ public void setVfModuleParams(Map<String, Object> vfModuleParams) {
+ this.vfModuleParams = vfModuleParams;
+ }
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVfModuleResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVfModuleResponse.java
index 4504bf3461..ff5735af58 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVfModuleResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVfModuleResponse.java
@@ -23,63 +23,59 @@ package org.onap.so.adapters.vnfrest;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("updateVfModuleResponse")
@XmlRootElement(name = "updateVfModuleResponse")
public class UpdateVfModuleResponse extends VfResponseCommon {
- private String vnfId;
- private String vfModuleId;
- private String vfModuleStackId;
- private Map<String,String> vfModuleOutputs = new HashMap<>();
-
- public UpdateVfModuleResponse() {
- super();
- }
-
- public UpdateVfModuleResponse(String vnfId, String vfModuleId,
- String vfModuleStackId,
- Map<String, String> vfModuleOutputs,
- String messageId) {
- super(messageId);
- this.vnfId = vnfId;
- this.vfModuleId = vfModuleId;
- this.vfModuleStackId = vfModuleStackId;
- this.vfModuleOutputs = vfModuleOutputs;
- }
-
- public String getVnfId() {
- return vnfId;
- }
-
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
-
- public String getVfModuleId() {
- return vfModuleId;
- }
-
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
-
- public String getVfModuleStackId() {
- return vfModuleStackId;
- }
-
- public void setVfModuleStackId(String vfModuleStackId) {
- this.vfModuleStackId = vfModuleStackId;
- }
-
- public Map<String, String> getVfModuleOutputs() {
- return vfModuleOutputs;
- }
-
- public void setVfModuleOutputs(Map<String, String> vfModuleOutputs) {
- this.vfModuleOutputs = vfModuleOutputs;
- }
+ private String vnfId;
+ private String vfModuleId;
+ private String vfModuleStackId;
+ private Map<String, String> vfModuleOutputs = new HashMap<>();
+
+ public UpdateVfModuleResponse() {
+ super();
+ }
+
+ public UpdateVfModuleResponse(String vnfId, String vfModuleId, String vfModuleStackId,
+ Map<String, String> vfModuleOutputs, String messageId) {
+ super(messageId);
+ this.vnfId = vnfId;
+ this.vfModuleId = vfModuleId;
+ this.vfModuleStackId = vfModuleStackId;
+ this.vfModuleOutputs = vfModuleOutputs;
+ }
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ public String getVfModuleStackId() {
+ return vfModuleStackId;
+ }
+
+ public void setVfModuleStackId(String vfModuleStackId) {
+ this.vfModuleStackId = vfModuleStackId;
+ }
+
+ public Map<String, String> getVfModuleOutputs() {
+ return vfModuleOutputs;
+ }
+
+ public void setVfModuleOutputs(Map<String, String> vfModuleOutputs) {
+ this.vfModuleOutputs = vfModuleOutputs;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVolumeGroupRequest.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVolumeGroupRequest.java
index e7c8171d6c..30d6bc9154 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVolumeGroupRequest.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVolumeGroupRequest.java
@@ -23,45 +23,42 @@ package org.onap.so.adapters.vnfrest;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
-
import org.onap.so.entity.MsoRequest;
import org.onap.so.openstack.mappers.MapAdapter;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("updateVolumeGroupRequest")
@XmlRootElement(name = "updateVolumeGroupRequest")
@XmlAccessorType(XmlAccessType.FIELD)
public class UpdateVolumeGroupRequest extends VfRequestCommon {
- private String cloudSiteId;
- private String cloudOwner;
- private String tenantId;
- private String volumeGroupId;
- private String volumeGroupStackId;
- private String vnfType;
- private String vnfVersion;
- private String vfModuleType;
- private String modelCustomizationUuid;
- @XmlJavaTypeAdapter(MapAdapter.class)
- private Map<String,Object> volumeGroupParams = new HashMap<>();
- private MsoRequest msoRequest = new MsoRequest();
-
- public UpdateVolumeGroupRequest() {
- super();
- }
-
- public String getCloudSiteId() {
- return cloudSiteId;
- }
-
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
+ private String cloudSiteId;
+ private String cloudOwner;
+ private String tenantId;
+ private String volumeGroupId;
+ private String volumeGroupStackId;
+ private String vnfType;
+ private String vnfVersion;
+ private String vfModuleType;
+ private String modelCustomizationUuid;
+ @XmlJavaTypeAdapter(MapAdapter.class)
+ private Map<String, Object> volumeGroupParams = new HashMap<>();
+ private MsoRequest msoRequest = new MsoRequest();
+
+ public UpdateVolumeGroupRequest() {
+ super();
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
public String getCloudOwner() {
return cloudOwner;
@@ -71,75 +68,75 @@ public class UpdateVolumeGroupRequest extends VfRequestCommon {
this.cloudOwner = cloudOwner;
}
- public String getTenantId() {
- return tenantId;
- }
+ public String getTenantId() {
+ return tenantId;
+ }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
- public String getVolumeGroupId() {
- return volumeGroupId;
- }
+ public String getVolumeGroupId() {
+ return volumeGroupId;
+ }
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
- public String getVolumeGroupStackId() {
- return volumeGroupStackId;
- }
+ public String getVolumeGroupStackId() {
+ return volumeGroupStackId;
+ }
- public void setVolumeGroupStackId(String volumeGroupStackId) {
- this.volumeGroupStackId = volumeGroupStackId;
- }
+ public void setVolumeGroupStackId(String volumeGroupStackId) {
+ this.volumeGroupStackId = volumeGroupStackId;
+ }
- public String getVnfType() {
- return vnfType;
- }
+ public String getVnfType() {
+ return vnfType;
+ }
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
- public String getVnfVersion() {
- return vnfVersion;
- }
+ public String getVnfVersion() {
+ return vnfVersion;
+ }
- public void setVnfVersion(String vnfVersion) {
- this.vnfVersion = vnfVersion;
- }
+ public void setVnfVersion(String vnfVersion) {
+ this.vnfVersion = vnfVersion;
+ }
- public String getVfModuleType() {
- return vfModuleType;
- }
+ public String getVfModuleType() {
+ return vfModuleType;
+ }
- public void setVfModuleType(String vfModuleType) {
- this.vfModuleType = vfModuleType;
- }
+ public void setVfModuleType(String vfModuleType) {
+ this.vfModuleType = vfModuleType;
+ }
- public String getModelCustomizationUuid() {
- return this.modelCustomizationUuid;
- }
+ public String getModelCustomizationUuid() {
+ return this.modelCustomizationUuid;
+ }
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
- public Map<String, Object> getVolumeGroupParams() {
- return volumeGroupParams;
- }
+ public Map<String, Object> getVolumeGroupParams() {
+ return volumeGroupParams;
+ }
- public void setVolumeGroupParams(Map<String, Object> volumeGroupParams) {
- this.volumeGroupParams = volumeGroupParams;
- }
+ public void setVolumeGroupParams(Map<String, Object> volumeGroupParams) {
+ this.volumeGroupParams = volumeGroupParams;
+ }
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVolumeGroupResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVolumeGroupResponse.java
index 8c003b1835..f3bd29ef99 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVolumeGroupResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/UpdateVolumeGroupResponse.java
@@ -23,57 +23,51 @@ package org.onap.so.adapters.vnfrest;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("updateVolumeGroupResponse")
@XmlRootElement(name = "updateVolumeGroupResponse")
public class UpdateVolumeGroupResponse extends VfResponseCommon {
- private String volumeGroupId;
- private String volumeGroupStackId;
- private Map<String,String> volumeGroupOutputs;
+ private String volumeGroupId;
+ private String volumeGroupStackId;
+ private Map<String, String> volumeGroupOutputs;
- public UpdateVolumeGroupResponse() {
- super();
- this.volumeGroupOutputs = new HashMap<>();
- }
+ public UpdateVolumeGroupResponse() {
+ super();
+ this.volumeGroupOutputs = new HashMap<>();
+ }
- public UpdateVolumeGroupResponse(
- String volumeGroupId,
- String volumeGroupStackId,
- Map<String, String> volumeGroupOutputs,
- String messageId)
- {
- super(messageId);
- this.volumeGroupId = volumeGroupId;
- this.volumeGroupStackId = volumeGroupStackId;
- this.volumeGroupOutputs = volumeGroupOutputs;
- }
+ public UpdateVolumeGroupResponse(String volumeGroupId, String volumeGroupStackId,
+ Map<String, String> volumeGroupOutputs, String messageId) {
+ super(messageId);
+ this.volumeGroupId = volumeGroupId;
+ this.volumeGroupStackId = volumeGroupStackId;
+ this.volumeGroupOutputs = volumeGroupOutputs;
+ }
- public String getVolumeGroupId() {
- return volumeGroupId;
- }
+ public String getVolumeGroupId() {
+ return volumeGroupId;
+ }
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
- public String getVolumeGroupStackId() {
- return volumeGroupStackId;
- }
+ public String getVolumeGroupStackId() {
+ return volumeGroupStackId;
+ }
- public void setVolumeGroupStackId(String volumeGroupStackId) {
- this.volumeGroupStackId = volumeGroupStackId;
- }
+ public void setVolumeGroupStackId(String volumeGroupStackId) {
+ this.volumeGroupStackId = volumeGroupStackId;
+ }
- public Map<String, String> getVolumeGroupOutputs() {
- return volumeGroupOutputs;
- }
+ public Map<String, String> getVolumeGroupOutputs() {
+ return volumeGroupOutputs;
+ }
- public void setVolumeGroupOutputs(Map<String, String> volumeGroupOutputs) {
- this.volumeGroupOutputs = volumeGroupOutputs;
- }
+ public void setVolumeGroupOutputs(Map<String, String> volumeGroupOutputs) {
+ this.volumeGroupOutputs = volumeGroupOutputs;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleExceptionResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleExceptionResponse.java
index 4f53531585..c1e77dcd4c 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleExceptionResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleExceptionResponse.java
@@ -22,9 +22,7 @@ package org.onap.so.adapters.vnfrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
@XmlRootElement(name = "vfModuleException")
@@ -33,43 +31,44 @@ public class VfModuleExceptionResponse extends VfResponseCommon implements Seria
private static final long serialVersionUID = -9062290006520066109L;
private String message;
- private MsoExceptionCategory category;
- private Boolean rolledBack;
-
- public VfModuleExceptionResponse () {}
-
- public VfModuleExceptionResponse (String message) {
- this.message = message;
- }
-
- public VfModuleExceptionResponse (String message, MsoExceptionCategory category, boolean rolledBack, String messageid) {
- super(messageid);
- this.message = message;
- this.category = category;
- this.rolledBack = rolledBack;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public MsoExceptionCategory getCategory () {
- return category;
- }
-
- public void setCategory (MsoExceptionCategory category) {
- this.category = category;
- }
-
- public Boolean getRolledBack() {
- return rolledBack;
- }
-
- public void setRolledBack(Boolean rolledBack) {
- this.rolledBack = rolledBack;
- }
+ private MsoExceptionCategory category;
+ private Boolean rolledBack;
+
+ public VfModuleExceptionResponse() {}
+
+ public VfModuleExceptionResponse(String message) {
+ this.message = message;
+ }
+
+ public VfModuleExceptionResponse(String message, MsoExceptionCategory category, boolean rolledBack,
+ String messageid) {
+ super(messageid);
+ this.message = message;
+ this.category = category;
+ this.rolledBack = rolledBack;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public MsoExceptionCategory getCategory() {
+ return category;
+ }
+
+ public void setCategory(MsoExceptionCategory category) {
+ this.category = category;
+ }
+
+ public Boolean getRolledBack() {
+ return rolledBack;
+ }
+
+ public void setRolledBack(Boolean rolledBack) {
+ this.rolledBack = rolledBack;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java
index a6a988690c..5f93765688 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java
@@ -22,119 +22,130 @@ package org.onap.so.adapters.vnfrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.entity.MsoRequest;
import org.onap.so.openstack.beans.VnfRollback;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("VfModuleRollback")
@XmlRootElement(name = "VfModuleRollback")
public class VfModuleRollback {
- private String vnfId;
- private String vfModuleId;
- private String vfModuleStackId;
- private boolean vfModuleCreated = false;
- private String tenantId;
- private String cloudOwner;
- private String cloudSiteId;
- private MsoRequest msoRequest;
- private String messageId;
- private String mode = "HEAT"; // default
-
- public VfModuleRollback() {
- }
-
- public VfModuleRollback(VnfRollback vrb, String vfModuleId, String vfModuleStackId, String messageId)
- {
- this.vnfId = vrb.getVnfId();
- this.vfModuleId = vfModuleId;
- this.vfModuleStackId = vfModuleStackId;
- this.vfModuleCreated = vrb.getVnfCreated();
- this.tenantId = vrb.getTenantId();
- this.cloudOwner = vrb.getCloudOwner();
- this.cloudSiteId = vrb.getCloudSiteId();
- this.msoRequest = vrb.getMsoRequest();
- this.messageId = messageId;
- this.mode = vrb.getMode();
- }
-
- public VfModuleRollback(String vnfId, String vfModuleId,
- String vfModuleStackId, boolean vfModuleCreated, String tenantId,
- String cloudOwner,
- String cloudSiteId,
- MsoRequest msoRequest,
- String messageId) {
- super();
- this.vnfId = vnfId;
- this.vfModuleId = vfModuleId;
- this.vfModuleStackId = vfModuleStackId;
- this.vfModuleCreated = vfModuleCreated;
- this.tenantId = tenantId;
- this.cloudOwner = cloudOwner;
- this.cloudSiteId = cloudSiteId;
- this.msoRequest = msoRequest;
- this.messageId = messageId;
- }
-
- public String getVnfId() {
- return vnfId;
- }
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
- public String getVfModuleId() {
- return vfModuleId;
- }
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
- public String getVfModuleStackId() {
- return vfModuleStackId;
- }
- public void setVfModuleStackId(String vfModuleStackId) {
- this.vfModuleStackId = vfModuleStackId;
- }
- public boolean isVfModuleCreated() {
- return vfModuleCreated;
- }
- public void setVfModuleCreated(boolean vfModuleCreated) {
- this.vfModuleCreated = vfModuleCreated;
- }
- public String getTenantId() {
- return tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getCloudSiteId() {
- return cloudSiteId;
- }
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
+ private String vnfId;
+ private String vfModuleId;
+ private String vfModuleStackId;
+ private boolean vfModuleCreated = false;
+ private String tenantId;
+ private String cloudOwner;
+ private String cloudSiteId;
+ private MsoRequest msoRequest;
+ private String messageId;
+ private String mode = "HEAT"; // default
+
+ public VfModuleRollback() {}
+
+ public VfModuleRollback(VnfRollback vrb, String vfModuleId, String vfModuleStackId, String messageId) {
+ this.vnfId = vrb.getVnfId();
+ this.vfModuleId = vfModuleId;
+ this.vfModuleStackId = vfModuleStackId;
+ this.vfModuleCreated = vrb.getVnfCreated();
+ this.tenantId = vrb.getTenantId();
+ this.cloudOwner = vrb.getCloudOwner();
+ this.cloudSiteId = vrb.getCloudSiteId();
+ this.msoRequest = vrb.getMsoRequest();
+ this.messageId = messageId;
+ this.mode = vrb.getMode();
+ }
+
+ public VfModuleRollback(String vnfId, String vfModuleId, String vfModuleStackId, boolean vfModuleCreated,
+ String tenantId, String cloudOwner, String cloudSiteId, MsoRequest msoRequest, String messageId) {
+ super();
+ this.vnfId = vnfId;
+ this.vfModuleId = vfModuleId;
+ this.vfModuleStackId = vfModuleStackId;
+ this.vfModuleCreated = vfModuleCreated;
+ this.tenantId = tenantId;
+ this.cloudOwner = cloudOwner;
+ this.cloudSiteId = cloudSiteId;
+ this.msoRequest = msoRequest;
+ this.messageId = messageId;
+ }
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ public String getVfModuleStackId() {
+ return vfModuleStackId;
+ }
+
+ public void setVfModuleStackId(String vfModuleStackId) {
+ this.vfModuleStackId = vfModuleStackId;
+ }
+
+ public boolean isVfModuleCreated() {
+ return vfModuleCreated;
+ }
+
+ public void setVfModuleCreated(boolean vfModuleCreated) {
+ this.vfModuleCreated = vfModuleCreated;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
+
public String getCloudOwner() {
return cloudOwner;
}
+
public void setCloudOwner(String cloudOwner) {
this.cloudOwner = cloudOwner;
}
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
- public String getMessageId() {
- return messageId;
- }
- public void setMessageId(String messageId) {
- this.messageId = messageId;
- }
- public String getMode() {
- return mode;
- }
- public void setMode(String mode) {
- this.mode = mode;
- }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
+
+ public String getMessageId() {
+ return messageId;
+ }
+
+ public void setMessageId(String messageId) {
+ this.messageId = messageId;
+ }
+
+ public String getMode() {
+ return mode;
+ }
+
+ public void setMode(String mode) {
+ this.mode = mode;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfRequestCommon.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfRequestCommon.java
index f934bc63d8..53c7f003bd 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfRequestCommon.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfRequestCommon.java
@@ -28,34 +28,34 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
* Everything that is common between all VfModule and VolumeGroup Requests.
*/
public abstract class VfRequestCommon extends VfResponseCommon {
- private Boolean skipAAI;
- private String notificationUrl;
+ private Boolean skipAAI;
+ private String notificationUrl;
- public Boolean getSkipAAI() {
- return skipAAI;
- }
+ public Boolean getSkipAAI() {
+ return skipAAI;
+ }
- public void setSkipAAI(Boolean skipAAI) {
- this.skipAAI = skipAAI;
- }
+ public void setSkipAAI(Boolean skipAAI) {
+ this.skipAAI = skipAAI;
+ }
- public String getNotificationUrl() {
- return notificationUrl;
- }
+ public String getNotificationUrl() {
+ return notificationUrl;
+ }
- public void setNotificationUrl(String notificationUrl) {
- this.notificationUrl = notificationUrl;
- }
+ public void setNotificationUrl(String notificationUrl) {
+ this.notificationUrl = notificationUrl;
+ }
- public boolean isSynchronous() {
- return notificationUrl == null || notificationUrl.isEmpty();
- }
+ public boolean isSynchronous() {
+ return notificationUrl == null || notificationUrl.isEmpty();
+ }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("skipAAI", skipAAI).append("notificationUrl", notificationUrl)
- .toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("skipAAI", skipAAI).append("notificationUrl", notificationUrl)
+ .toString();
+ }
- // getMessageId, setMessageId, toJsonString, toJsonString are all defined in VfResponseCommon.
+ // getMessageId, setMessageId, toJsonString, toJsonString are all defined in VfResponseCommon.
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfResponseCommon.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfResponseCommon.java
index 73414a370a..23bbbb3f43 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfResponseCommon.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfResponseCommon.java
@@ -24,64 +24,61 @@ package org.onap.so.adapters.vnfrest;
import java.io.ByteArrayOutputStream;
-
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Everything that is common between all VfModule and VolumeGroup Responses,
- * except for QueryVfModuleResponse and QueryVolumeGroupResponse.
+ * Everything that is common between all VfModule and VolumeGroup Responses, except for QueryVfModuleResponse and
+ * QueryVolumeGroupResponse.
*/
public abstract class VfResponseCommon {
- private static final Logger logger = LoggerFactory.getLogger(VfResponseCommon.class);
- private String messageId;
+ private static final Logger logger = LoggerFactory.getLogger(VfResponseCommon.class);
+ private String messageId;
- public VfResponseCommon() {
- messageId = null;
- }
+ public VfResponseCommon() {
+ messageId = null;
+ }
- public VfResponseCommon(String messageId) {
- this.messageId = messageId;
- }
+ public VfResponseCommon(String messageId) {
+ this.messageId = messageId;
+ }
- public String getMessageId() {
- return messageId;
- }
+ public String getMessageId() {
+ return messageId;
+ }
- public void setMessageId(String messageId) {
- this.messageId = messageId;
- }
+ public void setMessageId(String messageId) {
+ this.messageId = messageId;
+ }
- public String toJsonString() {
- try {
- String jsonString;
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- jsonString = mapper.writeValueAsString(this);
- return jsonString;
- } catch (Exception e) {
- logger.debug("Exception :",e);
- return "";
- }
- }
+ public String toJsonString() {
+ try {
+ String jsonString;
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ jsonString = mapper.writeValueAsString(this);
+ return jsonString;
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ return "";
+ }
+ }
- public String toXmlString() {
- try {
- ByteArrayOutputStream bs = new ByteArrayOutputStream();
- JAXBContext context = JAXBContext.newInstance(this.getClass());
- Marshaller marshaller = context.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //pretty print XML
- marshaller.marshal(this, bs);
- return bs.toString();
- } catch (Exception e) {
- logger.debug("Exception :",e);
- return "";
- }
- }
+ public String toXmlString() {
+ try {
+ ByteArrayOutputStream bs = new ByteArrayOutputStream();
+ JAXBContext context = JAXBContext.newInstance(this.getClass());
+ Marshaller marshaller = context.createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // pretty print XML
+ marshaller.marshal(this, bs);
+ return bs.toString();
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ return "";
+ }
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VolumeGroupExceptionResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VolumeGroupExceptionResponse.java
index 2e5801b4ae..6e7d8c1a03 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VolumeGroupExceptionResponse.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VolumeGroupExceptionResponse.java
@@ -22,24 +22,24 @@ package org.onap.so.adapters.vnfrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
@XmlRootElement(name = "volumeGroupException")
public class VolumeGroupExceptionResponse extends VfModuleExceptionResponse {
- // Exactly the same as a VfModuleExceptionResponse
+ // Exactly the same as a VfModuleExceptionResponse
- private static final long serialVersionUID = 1168681288205898800L;
+ private static final long serialVersionUID = 1168681288205898800L;
- public VolumeGroupExceptionResponse() {
- super();
- }
+ public VolumeGroupExceptionResponse() {
+ super();
+ }
- public VolumeGroupExceptionResponse(String message) {
- super(message);
- }
+ public VolumeGroupExceptionResponse(String message) {
+ super(message);
+ }
- public VolumeGroupExceptionResponse(String message, MsoExceptionCategory category, boolean rolledBack, String messageid) {
- super(message, category, rolledBack, messageid);
- }
+ public VolumeGroupExceptionResponse(String message, MsoExceptionCategory category, boolean rolledBack,
+ String messageid) {
+ super(message, category, rolledBack, messageid);
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VolumeGroupRollback.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VolumeGroupRollback.java
index ea7ce582ad..4f57e7584f 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VolumeGroupRollback.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VolumeGroupRollback.java
@@ -22,117 +22,121 @@ package org.onap.so.adapters.vnfrest;
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.entity.MsoRequest;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("VolumeGroupRollback")
@XmlRootElement(name = "VolumeGroupRollback")
public class VolumeGroupRollback {
-// “volumeGroupRollback”: {
-// “volumeGroupId”: “<A&AI_ VOLUME_GROUP_ID>”,
-// “volumeGroupStackId”: “<VOLUME_GROUP _STACK_ID>”,
-// “tenantId”: “<TENANT_ID>”,
-// "cloudOwnerId"" "<CLOUD_OWNER>",
-// “cloudSiteId”: “<CLOUD_CLLI>”,
-// “volumeGroupCreated”: TRUE|FALSE,
-// “msoRequest”: {
-// “requestId”: “<REQUEST_ID>”,
-// “serviceInstanceId”: “<SERVICE_INSTANCE_ID>”
-// }
-//},
-
- private String volumeGroupId;
- private String volumeGroupStackId;
- private String tenantId;
- private String cloudOwnerId;
- private String cloudSiteId;
- private boolean volumeGroupCreated = false;
- private MsoRequest msoRequest;
- private String messageId;
-
- public VolumeGroupRollback() {
- }
-
- public VolumeGroupRollback(VolumeGroupRollback vrb, String volumeGroupStackId, String messageId)
- {
- this.volumeGroupId = vrb.getVolumeGroupId();
- this.volumeGroupStackId = volumeGroupStackId;
- this.tenantId = vrb.getTenantId();
- this.cloudOwnerId = vrb.getCloudOwnerId();
- this.cloudSiteId = vrb.getCloudSiteId();
- this.volumeGroupCreated = vrb.isVolumeGroupCreated();
- this.msoRequest = vrb.getMsoRequest();
- this.messageId = messageId;
- }
-
- public VolumeGroupRollback(
- String volumeGroupId,
- String volumeGroupStackId,
- boolean volumeGroupCreated,
- String tenantId,
- String cloudOwnerId,
- String cloudSiteId,
- MsoRequest msoRequest,
- String messageId)
- {
- super();
- this.volumeGroupId = volumeGroupId;
- this.volumeGroupStackId = volumeGroupStackId;
- this.volumeGroupCreated = volumeGroupCreated;
- this.tenantId = tenantId;
- this.cloudOwnerId = cloudOwnerId;
- this.cloudSiteId = cloudSiteId;
- this.msoRequest = msoRequest;
- this.messageId = messageId;
- }
-
- public String getVolumeGroupId() {
- return volumeGroupId;
- }
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
- public String getVolumeGroupStackId() {
- return volumeGroupStackId;
- }
- public void setVolumeGroupStackId(String volumeGroupStackId) {
- this.volumeGroupStackId = volumeGroupStackId;
- }
- public String getTenantId() {
- return tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getCloudSiteId() {
- return cloudSiteId;
- }
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
- public String getCloudOwnerId() {
- return cloudOwnerId;
- }
- public void setCloudOwnerId(String cloudOwnerId) {
- this.cloudOwnerId = cloudOwnerId;
- }public boolean isVolumeGroupCreated() {
- return volumeGroupCreated;
- }
- public void setVolumeGroupCreated(boolean volumeGroupCreated) {
- this.volumeGroupCreated = volumeGroupCreated;
- }
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
- public void setMsoRequest(MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
- public String getMessageId() {
- return messageId;
- }
- public void setMessageId(String messageId) {
- this.messageId = messageId;
- }
+ // “volumeGroupRollback”: {
+ // “volumeGroupId”: “<A&AI_ VOLUME_GROUP_ID>”,
+ // “volumeGroupStackId”: “<VOLUME_GROUP _STACK_ID>”,
+ // “tenantId”: “<TENANT_ID>”,
+ // "cloudOwnerId"" "<CLOUD_OWNER>",
+ // “cloudSiteId”: “<CLOUD_CLLI>”,
+ // “volumeGroupCreated”: TRUE|FALSE,
+ // “msoRequest”: {
+ // “requestId”: “<REQUEST_ID>”,
+ // “serviceInstanceId”: “<SERVICE_INSTANCE_ID>”
+ // }
+ // },
+
+ private String volumeGroupId;
+ private String volumeGroupStackId;
+ private String tenantId;
+ private String cloudOwnerId;
+ private String cloudSiteId;
+ private boolean volumeGroupCreated = false;
+ private MsoRequest msoRequest;
+ private String messageId;
+
+ public VolumeGroupRollback() {}
+
+ public VolumeGroupRollback(VolumeGroupRollback vrb, String volumeGroupStackId, String messageId) {
+ this.volumeGroupId = vrb.getVolumeGroupId();
+ this.volumeGroupStackId = volumeGroupStackId;
+ this.tenantId = vrb.getTenantId();
+ this.cloudOwnerId = vrb.getCloudOwnerId();
+ this.cloudSiteId = vrb.getCloudSiteId();
+ this.volumeGroupCreated = vrb.isVolumeGroupCreated();
+ this.msoRequest = vrb.getMsoRequest();
+ this.messageId = messageId;
+ }
+
+ public VolumeGroupRollback(String volumeGroupId, String volumeGroupStackId, boolean volumeGroupCreated,
+ String tenantId, String cloudOwnerId, String cloudSiteId, MsoRequest msoRequest, String messageId) {
+ super();
+ this.volumeGroupId = volumeGroupId;
+ this.volumeGroupStackId = volumeGroupStackId;
+ this.volumeGroupCreated = volumeGroupCreated;
+ this.tenantId = tenantId;
+ this.cloudOwnerId = cloudOwnerId;
+ this.cloudSiteId = cloudSiteId;
+ this.msoRequest = msoRequest;
+ this.messageId = messageId;
+ }
+
+ public String getVolumeGroupId() {
+ return volumeGroupId;
+ }
+
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ public String getVolumeGroupStackId() {
+ return volumeGroupStackId;
+ }
+
+ public void setVolumeGroupStackId(String volumeGroupStackId) {
+ this.volumeGroupStackId = volumeGroupStackId;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
+
+ public String getCloudOwnerId() {
+ return cloudOwnerId;
+ }
+
+ public void setCloudOwnerId(String cloudOwnerId) {
+ this.cloudOwnerId = cloudOwnerId;
+ }
+
+ public boolean isVolumeGroupCreated() {
+ return volumeGroupCreated;
+ }
+
+ public void setVolumeGroupCreated(boolean volumeGroupCreated) {
+ this.volumeGroupCreated = volumeGroupCreated;
+ }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
+
+ public String getMessageId() {
+ return messageId;
+ }
+
+ public void setMessageId(String messageId) {
+ this.messageId = messageId;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HeatStatus.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HeatStatus.java
index dd68d37736..2d047a188a 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HeatStatus.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HeatStatus.java
@@ -25,6 +25,6 @@ package org.onap.so.openstack.beans;
* Enum status values to mirror the Openstack Heat stack status values
*/
public enum HeatStatus {
- INIT, CREATED, NOTFOUND, FAILED, BUILDING, DELETING, UNKNOWN, UPDATING, UPDATED
+ INIT, CREATED, NOTFOUND, FAILED, BUILDING, DELETING, UNKNOWN, UPDATING, UPDATED
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HostRoute.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HostRoute.java
index 228bb2c03d..431870ba9e 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HostRoute.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HostRoute.java
@@ -27,43 +27,43 @@ import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "prefix",
- "nextHop"
-})
+@XmlType(name = "", propOrder = {"prefix", "nextHop"})
public class HostRoute {
- private String prefix;
- private String nextHop;
+ private String prefix;
+ private String nextHop;
- /**
- * @return the prefix
- */
- public String getPrefix() {
- return prefix;
- }
- /**
- * @param prefix the prefix to set
- */
- public void setPrefix(String prefix) {
- this.prefix = prefix;
- }
- /**
- * @return the nextHop
- */
- public String getNextHop() {
- return nextHop;
- }
- /**
- * @param nextHop the nextHop to set
- */
- public void setNextHop(String nextHop) {
- this.nextHop = nextHop;
- }
+ /**
+ * @return the prefix
+ */
+ public String getPrefix() {
+ return prefix;
+ }
- @Override
- public String toString() {
- return "Host_route [prefix=" + prefix + ", nextHop=" + nextHop + "]";
- }
+ /**
+ * @param prefix the prefix to set
+ */
+ public void setPrefix(String prefix) {
+ this.prefix = prefix;
+ }
+
+ /**
+ * @return the nextHop
+ */
+ public String getNextHop() {
+ return nextHop;
+ }
+
+ /**
+ * @param nextHop the nextHop to set
+ */
+ public void setNextHop(String nextHop) {
+ this.nextHop = nextHop;
+ }
+
+ @Override
+ public String toString() {
+ return "Host_route [prefix=" + prefix + ", nextHop=" + nextHop + "]";
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/MsoTenant.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/MsoTenant.java
index b06ea0e59f..df6d46cd31 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/MsoTenant.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/MsoTenant.java
@@ -25,42 +25,44 @@ package org.onap.so.openstack.beans;
import java.util.Map;
/**
- * This bean class represents the Openstack tenant properties that are
- * needed by MSO.
+ * This bean class represents the Openstack tenant properties that are needed by MSO.
*
*
*/
public class MsoTenant {
- private String tenantId;
- private String tenantName;
- private Map<String,String> metadata;
-
- public MsoTenant() {}
-
- public MsoTenant (String id, String name, Map<String,String> metadata) {
- this.tenantId = id;
- this.tenantName = name;
- this.metadata = metadata;
- }
-
- public String getTenantId() {
- return tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getTenantName() {
- return tenantName;
- }
- public void setTenantName(String tenantName) {
- this.tenantName = tenantName;
- }
-
- public Map<String, String> getMetadata() {
- return metadata;
- }
- public void setMetadata(Map<String, String> metadata) {
- this.metadata = metadata;
- }
+ private String tenantId;
+ private String tenantName;
+ private Map<String, String> metadata;
+
+ public MsoTenant() {}
+
+ public MsoTenant(String id, String name, Map<String, String> metadata) {
+ this.tenantId = id;
+ this.tenantName = name;
+ this.metadata = metadata;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getTenantName() {
+ return tenantName;
+ }
+
+ public void setTenantName(String tenantName) {
+ this.tenantName = tenantName;
+ }
+
+ public Map<String, String> getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(Map<String, String> metadata) {
+ this.metadata = metadata;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkInfo.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkInfo.java
index 6110fa5073..722e2157e7 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkInfo.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkInfo.java
@@ -32,89 +32,83 @@ import java.util.List;
*/
public class NetworkInfo {
- // Set defaults for everything
- private String name = "";
- private String id = "";
- private NetworkStatus status = NetworkStatus.UNKNOWN;
- private String provider = "";
- private List<Integer> vlans = new ArrayList<>();
- private List<String> subnets = new ArrayList<>();
- private String shared = "";
-
- public NetworkInfo () {
- }
-
- public NetworkInfo (String name, NetworkStatus status) {
- this.name = name;
- this.id = name; // Don't have an ID, so just use name
- this.status = status;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName (String name) {
- this.name = name;
- }
-
- public String getId() {
- return id;
- }
-
- public void setId (String id) {
- this.id = id;
- }
-
- public NetworkStatus getStatus() {
- return status;
- }
-
- public void setStatus (NetworkStatus status) {
- this.status = status;
- }
-
- public String getProvider() {
- return provider;
- }
-
- public void setProvider (String provider) {
- this.provider = provider;
- }
-
- public List<Integer> getVlans () {
- return vlans;
- }
-
- public void setVlans (List<Integer> vlans) {
- this.vlans = vlans;
- }
-
- public List<String> getSubnets () {
- return subnets;
- }
-
- public void setSubnets (List<String> subnets) {
- this.subnets = subnets;
- }
-
- public String getShared() {
- return shared;
- }
-
- public void setShared(String shared) {
- this.shared = shared;
- }
-
- @Override
- public String toString() {
- return "NetworkInfo{" + "name='" + name + '\'' +
- ", id='" + id + '\'' +
- ", status=" + status +
- ", provider='" + provider + '\'' +
- ", vlans=" + vlans +
- ", subnets=" + subnets +
- '}';
- }
+ // Set defaults for everything
+ private String name = "";
+ private String id = "";
+ private NetworkStatus status = NetworkStatus.UNKNOWN;
+ private String provider = "";
+ private List<Integer> vlans = new ArrayList<>();
+ private List<String> subnets = new ArrayList<>();
+ private String shared = "";
+
+ public NetworkInfo() {}
+
+ public NetworkInfo(String name, NetworkStatus status) {
+ this.name = name;
+ this.id = name; // Don't have an ID, so just use name
+ this.status = status;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public NetworkStatus getStatus() {
+ return status;
+ }
+
+ public void setStatus(NetworkStatus status) {
+ this.status = status;
+ }
+
+ public String getProvider() {
+ return provider;
+ }
+
+ public void setProvider(String provider) {
+ this.provider = provider;
+ }
+
+ public List<Integer> getVlans() {
+ return vlans;
+ }
+
+ public void setVlans(List<Integer> vlans) {
+ this.vlans = vlans;
+ }
+
+ public List<String> getSubnets() {
+ return subnets;
+ }
+
+ public void setSubnets(List<String> subnets) {
+ this.subnets = subnets;
+ }
+
+ public String getShared() {
+ return shared;
+ }
+
+ public void setShared(String shared) {
+ this.shared = shared;
+ }
+
+ @Override
+ public String toString() {
+ return "NetworkInfo{" + "name='" + name + '\'' + ", id='" + id + '\'' + ", status=" + status + ", provider='"
+ + provider + '\'' + ", vlans=" + vlans + ", subnets=" + subnets + '}';
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkRollback.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkRollback.java
index e95c564f27..924ed8857e 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkRollback.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkRollback.java
@@ -23,135 +23,141 @@ package org.onap.so.openstack.beans;
import java.io.Serializable;
import java.util.List;
-
import org.onap.so.entity.MsoRequest;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
- * Javabean representing the rollback criteria following a "Create Network"
- * or "Update Network" operation. This structure can be passed back to the
- * "Rollback Network" operation to undo the effects of the create/update.
+ * Javabean representing the rollback criteria following a "Create Network" or "Update Network" operation. This
+ * structure can be passed back to the "Rollback Network" operation to undo the effects of the create/update.
*
- * Once a network is created, the only possible update through MSO is to
- * the set of VLANs supported by the network. The vlans attribute of the
- * rollback object contains the previous VLANs before update.
+ * Once a network is created, the only possible update through MSO is to the set of VLANs supported by the network. The
+ * vlans attribute of the rollback object contains the previous VLANs before update.
*
*
*/
@JsonInclude(Include.NON_EMPTY)
-public class NetworkRollback implements Serializable{
- /**
- *
- */
- private static final long serialVersionUID = 11949663223019185L;
- private String networkId;
- private String neutronNetworkId;
- private String networkStackId;
- private String tenantId;
- private String cloudId;
- private String networkType;
- private String modelCustomizationUuid;
- private boolean networkCreated = false;
- // Previous values for updates
- private String networkName = null;
- private String physicalNetwork = null;
- private List<Integer> vlans = null;
- private MsoRequest msoRequest;
-
- public String getNetworkId() {
- return networkId;
- }
- public void setNetworkId(String networkId) {
- this.networkId = networkId;
- }
-
- public String getNeutronNetworkId() {
- return neutronNetworkId;
- }
- public void setNeutronNetworkId(String neutronNetworkId) {
- this.neutronNetworkId = neutronNetworkId;
- }
-
- public String getNetworkStackId() {
- return networkStackId;
- }
- public void setNetworkStackId(String networkStackId) {
- this.networkStackId = networkStackId;
- }
- public String getTenantId() {
- return tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
- public String getCloudId() {
- return cloudId;
- }
- public void setCloudId(String cloudId) {
- this.cloudId = cloudId;
- }
-
- public String getNetworkType() {
- return networkType;
- }
- public void setNetworkType(String networkType) {
- this.networkType = networkType;
- }
-
- public String getModelCustomizationUuid() {
- return this.modelCustomizationUuid;
- }
-
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
-
- public boolean getNetworkCreated() {
- return networkCreated;
- }
- public void setNetworkCreated(boolean networkCreated) {
- this.networkCreated = networkCreated;
- }
-
- public String getNetworkName() {
- return networkName;
- }
- public void setNetworkName(String networkName) {
- this.networkName = networkName;
- }
-
- public String getPhysicalNetwork() {
- return physicalNetwork;
- }
- public void setPhysicalNetwork(String physicalNetwork) {
- this.physicalNetwork = physicalNetwork;
- }
-
- public List<Integer> getVlans () {
- return vlans;
- }
- public void setVlans (List<Integer> vlans) {
- this.vlans = vlans;
- }
-
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
- public void setMsoRequest (MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
-
- @Override
- public String toString() {
- return "NetworkRollback [networkId=" + networkId
- + ", neutronNetworkId=" + neutronNetworkId + ", networkStackId="
- + networkStackId + ", tenantId=" + tenantId + ", cloudId="
- + cloudId + ", networkType=" + networkType
- + ", networkCreated=" + networkCreated + ", networkName=" + networkName
- + ", physicalNetwork=" + physicalNetwork + "]";
- }
+public class NetworkRollback implements Serializable {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 11949663223019185L;
+ private String networkId;
+ private String neutronNetworkId;
+ private String networkStackId;
+ private String tenantId;
+ private String cloudId;
+ private String networkType;
+ private String modelCustomizationUuid;
+ private boolean networkCreated = false;
+ // Previous values for updates
+ private String networkName = null;
+ private String physicalNetwork = null;
+ private List<Integer> vlans = null;
+ private MsoRequest msoRequest;
+
+ public String getNetworkId() {
+ return networkId;
+ }
+
+ public void setNetworkId(String networkId) {
+ this.networkId = networkId;
+ }
+
+ public String getNeutronNetworkId() {
+ return neutronNetworkId;
+ }
+
+ public void setNeutronNetworkId(String neutronNetworkId) {
+ this.neutronNetworkId = neutronNetworkId;
+ }
+
+ public String getNetworkStackId() {
+ return networkStackId;
+ }
+
+ public void setNetworkStackId(String networkStackId) {
+ this.networkStackId = networkStackId;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getCloudId() {
+ return cloudId;
+ }
+
+ public void setCloudId(String cloudId) {
+ this.cloudId = cloudId;
+ }
+
+ public String getNetworkType() {
+ return networkType;
+ }
+
+ public void setNetworkType(String networkType) {
+ this.networkType = networkType;
+ }
+
+ public String getModelCustomizationUuid() {
+ return this.modelCustomizationUuid;
+ }
+
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ public boolean getNetworkCreated() {
+ return networkCreated;
+ }
+
+ public void setNetworkCreated(boolean networkCreated) {
+ this.networkCreated = networkCreated;
+ }
+
+ public String getNetworkName() {
+ return networkName;
+ }
+
+ public void setNetworkName(String networkName) {
+ this.networkName = networkName;
+ }
+
+ public String getPhysicalNetwork() {
+ return physicalNetwork;
+ }
+
+ public void setPhysicalNetwork(String physicalNetwork) {
+ this.physicalNetwork = physicalNetwork;
+ }
+
+ public List<Integer> getVlans() {
+ return vlans;
+ }
+
+ public void setVlans(List<Integer> vlans) {
+ this.vlans = vlans;
+ }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
+
+ @Override
+ public String toString() {
+ return "NetworkRollback [networkId=" + networkId + ", neutronNetworkId=" + neutronNetworkId
+ + ", networkStackId=" + networkStackId + ", tenantId=" + tenantId + ", cloudId=" + cloudId
+ + ", networkType=" + networkType + ", networkCreated=" + networkCreated + ", networkName=" + networkName
+ + ", physicalNetwork=" + physicalNetwork + "]";
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkStatus.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkStatus.java
index b7b1366562..74b6e6bb9c 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkStatus.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/NetworkStatus.java
@@ -22,10 +22,9 @@ package org.onap.so.openstack.beans;
/**
- * Enum status values to mirror the Openstack Neutron
- * network status values
+ * Enum status values to mirror the Openstack Neutron network status values
*/
public enum NetworkStatus {
- NOTFOUND, ACTIVE, DOWN, BUILD, ERROR, UNKNOWN
+ NOTFOUND, ACTIVE, DOWN, BUILD, ERROR, UNKNOWN
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/Pool.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/Pool.java
index ca3a9c5a8d..565ade770a 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/Pool.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/Pool.java
@@ -26,52 +26,56 @@ import org.apache.commons.lang3.builder.EqualsBuilder;
public class Pool implements Serializable {
- private String start;
- private String end;
- private static final long serialVersionUID = 768026109321305392L;
+ private String start;
+ private String end;
+ private static final long serialVersionUID = 768026109321305392L;
- /**
- * @return the start
- */
- public String getStart() {
- return start;
- }
- /**
- * @param start the start to set
- */
- public void setStart(String start) {
- this.start = start;
- }
- /**
- * @return the end
- */
- public String getEnd() {
- return end;
- }
- /**
- * @param end the end to set
- */
- public void setEnd(String end) {
- this.end = end;
- }
+ /**
+ * @return the start
+ */
+ public String getStart() {
+ return start;
+ }
+
+ /**
+ * @param start the start to set
+ */
+ public void setStart(String start) {
+ this.start = start;
+ }
+
+ /**
+ * @return the end
+ */
+ public String getEnd() {
+ return end;
+ }
+
+ /**
+ * @param end the end to set
+ */
+ public void setEnd(String end) {
+ this.end = end;
+ }
+
+ @Override
+ public String toString() {
+ return "Allocation_pool [start=" + start + ", end=" + end + "]";
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Pool)) {
+ return false;
+ }
+ Pool castOther = (Pool) other;
+ return new EqualsBuilder().append(start, castOther.start).append(end, castOther.end).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(start).append(end).toHashCode();
+ }
- @Override
- public String toString() {
- return "Allocation_pool [start=" + start + ", end=" + end + "]";
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Pool)) {
- return false;
- }
- Pool castOther = (Pool) other;
- return new EqualsBuilder().append(start, castOther.start).append(end, castOther.end).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(start).append(end).toHashCode();
- }
-
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/RouteTarget.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/RouteTarget.java
index fcea8796c2..ab816ddfe5 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/RouteTarget.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/RouteTarget.java
@@ -21,42 +21,41 @@
package org.onap.so.openstack.beans;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "routeTarget",
- "routeTargetRole"
-})
-public class RouteTarget implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = 5425083030715789604L;
- private String routeTarget;
- private String routeTargetRole;
-
- public String getRouteTarget() {
- return routeTarget;
- }
- public void setRouteTarget(String routeTarget) {
- this.routeTarget = routeTarget;
- }
- public String getRouteTargetRole() {
- return routeTargetRole;
- }
- public void setRouteTargetRole(String routeTargetRole) {
- this.routeTargetRole = routeTargetRole;
- }
-
-
- @Override
- public String toString() {
- return "RouteTarget [routeTarget=" + routeTarget + ", routeTargetRole=" + routeTargetRole + "]";
- }
-
+@XmlType(name = "", propOrder = {"routeTarget", "routeTargetRole"})
+public class RouteTarget implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 5425083030715789604L;
+ private String routeTarget;
+ private String routeTargetRole;
+
+ public String getRouteTarget() {
+ return routeTarget;
+ }
+
+ public void setRouteTarget(String routeTarget) {
+ this.routeTarget = routeTarget;
+ }
+
+ public String getRouteTargetRole() {
+ return routeTargetRole;
+ }
+
+ public void setRouteTargetRole(String routeTargetRole) {
+ this.routeTargetRole = routeTargetRole;
+ }
+
+
+ @Override
+ public String toString() {
+ return "RouteTarget [routeTarget=" + routeTarget + ", routeTargetRole=" + routeTargetRole + "]";
+ }
+
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/StackInfo.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/StackInfo.java
index 028ec9ec8d..76d3667632 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/StackInfo.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/StackInfo.java
@@ -31,79 +31,80 @@ import java.util.Map;
*/
public class StackInfo {
- // Set defaults for everything
- private String name = "";
- private String canonicalName = "";
- private HeatStatus status = HeatStatus.UNKNOWN;
- private String statusMessage = "";
- private Map<String,Object> outputs = new HashMap<>();
- private Map<String,Object> parameters = new HashMap<>();
-
- public StackInfo () {
- }
-
- public StackInfo (String name, HeatStatus status, String statusMessage, Map<String,Object> outputs) {
- this.name = name;
- this.canonicalName = name; // Don't have an ID, so just use name
-
- this.status = status;
- if (statusMessage != null) this.statusMessage = statusMessage;
- if (outputs != null) this.outputs = outputs;
- }
-
- public StackInfo (String name, HeatStatus status) {
- this.name = name;
- this.canonicalName = name; // Don't have an ID, so just use name
- this.status = status;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName (String name) {
- this.name = name;
- }
-
- public String getCanonicalName() {
- return canonicalName;
- }
-
- public void setCanonicalName (String name) {
- this.canonicalName = name;
- }
-
- public HeatStatus getStatus() {
- return status;
- }
-
- public void setStatus (HeatStatus status) {
- this.status = status;
- }
-
- public String getStatusMessage() {
- return statusMessage;
- }
-
- public void setStatusMessage (String statusMessage) {
- this.statusMessage = statusMessage;
- }
-
- public Map<String,Object> getOutputs () {
- return outputs;
- }
-
- public void setOutputs (Map<String,Object> outputs) {
- this.outputs = outputs;
- }
-
- public Map<String,Object> getParameters () {
- return parameters;
- }
-
- public void setParameters (Map<String,Object> parameters) {
- this.parameters = parameters;
- }
-
+ // Set defaults for everything
+ private String name = "";
+ private String canonicalName = "";
+ private HeatStatus status = HeatStatus.UNKNOWN;
+ private String statusMessage = "";
+ private Map<String, Object> outputs = new HashMap<>();
+ private Map<String, Object> parameters = new HashMap<>();
+
+ public StackInfo() {}
+
+ public StackInfo(String name, HeatStatus status, String statusMessage, Map<String, Object> outputs) {
+ this.name = name;
+ this.canonicalName = name; // Don't have an ID, so just use name
+
+ this.status = status;
+ if (statusMessage != null)
+ this.statusMessage = statusMessage;
+ if (outputs != null)
+ this.outputs = outputs;
+ }
+
+ public StackInfo(String name, HeatStatus status) {
+ this.name = name;
+ this.canonicalName = name; // Don't have an ID, so just use name
+ this.status = status;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getCanonicalName() {
+ return canonicalName;
+ }
+
+ public void setCanonicalName(String name) {
+ this.canonicalName = name;
+ }
+
+ public HeatStatus getStatus() {
+ return status;
+ }
+
+ public void setStatus(HeatStatus status) {
+ this.status = status;
+ }
+
+ public String getStatusMessage() {
+ return statusMessage;
+ }
+
+ public void setStatusMessage(String statusMessage) {
+ this.statusMessage = statusMessage;
+ }
+
+ public Map<String, Object> getOutputs() {
+ return outputs;
+ }
+
+ public void setOutputs(Map<String, Object> outputs) {
+ this.outputs = outputs;
+ }
+
+ public Map<String, Object> getParameters() {
+ return parameters;
+ }
+
+ public void setParameters(Map<String, Object> parameters) {
+ this.parameters = parameters;
+ }
+
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/Subnet.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/Subnet.java
index 4fcf46975d..8f55f7b262 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/Subnet.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/Subnet.java
@@ -24,64 +24,62 @@ package org.onap.so.openstack.beans;
import java.io.Serializable;
import java.util.List;
-
import javax.xml.bind.annotation.XmlTransient;
public class Subnet implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -530027355187604839L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -530027355187604839L;
- private String subnetName;
-
- private String neutronId;
+ private String subnetName;
- private String subnetId; // value from aai
+ private String neutronId;
- private String cidr; //Only field required
+ private String subnetId; // value from aai
+
+ private String cidr; // Only field required
private String gatewayIp;
- private String ipVersion="4";
+ private String ipVersion = "4";
+
+ private Boolean enableDHCP = false;
- private Boolean enableDHCP=false;
-
- private Boolean addrFromStart=true;
+ private Boolean addrFromStart = true;
private List<HostRoute> hostRoutes;
private List<Pool> allocationPools;
private List<String> dnsNameServers;
-
+
private Integer subnetSequence;
public Integer getSubnetSequence() {
- return subnetSequence;
- }
+ return subnetSequence;
+ }
+
+ public void setSubnetSequence(Integer subnetSequence) {
+ this.subnetSequence = subnetSequence;
+ }
- public void setSubnetSequence(Integer subnetSequence) {
- this.subnetSequence = subnetSequence;
- }
+ public Subnet() {}
- public Subnet () {
+ public String getSubnetName() {
+ return subnetName;
}
- public String getSubnetName() {
- return subnetName;
- }
+ public void setSubnetName(String subnetName) {
+ this.subnetName = subnetName;
+ }
- public void setSubnetName(String subnetName) {
- this.subnetName = subnetName;
- }
-
- public List<Pool> getAllocationPools() {
- return allocationPools;
- }
+ public List<Pool> getAllocationPools() {
+ return allocationPools;
+ }
- /**
+ /**
* @return the cidr
*/
public String getCidr() {
@@ -100,15 +98,15 @@ public class Subnet implements Serializable {
return enableDHCP;
}
- public Boolean getAddrFromStart() {
- return addrFromStart;
- }
+ public Boolean getAddrFromStart() {
+ return addrFromStart;
+ }
- public void setAddrFromStart(Boolean addrFromStart) {
- this.addrFromStart = addrFromStart;
- }
+ public void setAddrFromStart(Boolean addrFromStart) {
+ this.addrFromStart = addrFromStart;
+ }
- /**
+ /**
* @return the gw
*/
public String getGatewayIp() {
@@ -145,79 +143,71 @@ public class Subnet implements Serializable {
}
public void setAllocationPools(List<Pool> allocationPools) {
- this.allocationPools = allocationPools;
- }
+ this.allocationPools = allocationPools;
+ }
/**
- * @param cidr
- * the cidr to set
+ * @param cidr the cidr to set
*/
public void setCidr(String cidr) {
this.cidr = cidr;
}
/**
- * @param dnsNames
- * the dnsNames to set
+ * @param dnsNames the dnsNames to set
*/
public void setDnsNameServers(List<String> dnsNameServers) {
this.dnsNameServers = dnsNameServers;
}
/**
- * @param enableDHCP
- * the enableDHCP to set
+ * @param enableDHCP the enableDHCP to set
*/
public void setEnableDHCP(Boolean enableDHCP) {
this.enableDHCP = enableDHCP;
}
/**
- * @param gw
- * the gw to set
+ * @param gw the gw to set
*/
public void setGatewayIp(String gatewayIp) {
this.gatewayIp = gatewayIp;
}
/**
- * @param hostRoutes
- * the hostRoutes to set
+ * @param hostRoutes the hostRoutes to set
*/
public void setHostRoutes(List<HostRoute> hostRoutes) {
this.hostRoutes = hostRoutes;
}
/**
- * @param neutronId
- * the id to set
+ * @param neutronId the id to set
*/
public void setNeutronId(String neutronId) {
this.neutronId = neutronId;
}
/**
- * @param ipversion
- * the ipversion to set
+ * @param ipversion the ipversion to set
*/
public void setIpVersion(String ipVersion) {
this.ipVersion = ipVersion;
}
/**
- * @param name
- * the name to set
+ * @param name the name to set
*/
public void setSubnetId(String subnetId) {
this.subnetId = subnetId;
}
- @Override
- public String toString() {
- return "Subnet [subnetName=" + subnetName + ", neutronId=" + neutronId + ", subnetId=" + subnetId + ", cidr="
- + cidr + ", gatewayIp=" + gatewayIp + ", ipVersion=" + ipVersion + ", enableDHCP=" + enableDHCP
- + ", addrFromStart=" + addrFromStart + ", hostRoutes=" + hostRoutes + ", allocationPools="
- + allocationPools + ", dnsNameServers=" + dnsNameServers + "]";
- }
+ @Override
+ public String toString() {
+ return "Subnet [subnetName=" + subnetName + ", neutronId=" + neutronId + ", subnetId=" + subnetId + ", cidr="
+ + cidr + ", gatewayIp=" + gatewayIp + ", ipVersion=" + ipVersion + ", enableDHCP=" + enableDHCP
+ + ", addrFromStart=" + addrFromStart + ", hostRoutes=" + hostRoutes + ", allocationPools="
+ + allocationPools + ", dnsNameServers=" + dnsNameServers + "]";
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/VnfRollback.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/VnfRollback.java
index 1c7164a0a0..c95c0b77fb 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/VnfRollback.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/VnfRollback.java
@@ -21,204 +21,229 @@
package org.onap.so.openstack.beans;
import org.onap.so.entity.MsoRequest;
+
/**
- * Javabean representing the rollback criteria following a "Create VNF"
- * operation. This structure can be passed back to the "Rollback VNF"
- * operation to undo the effects of the create.
+ * Javabean representing the rollback criteria following a "Create VNF" operation. This structure can be passed back to
+ * the "Rollback VNF" operation to undo the effects of the create.
*
*
*/
public class VnfRollback {
- private String vnfId;
- private String tenantId;
- private String cloudOwner;
- private String cloudSiteId;
- private boolean tenantCreated = false;
- private boolean vnfCreated = false;
- private MsoRequest msoRequest;
- private String volumeGroupName;
- private String volumeGroupId;
- private String requestType;
- private String volumeGroupHeatStackId;
- private String baseGroupHeatStackId;
- private boolean isBase = false;
- private String vfModuleStackId;
- private String modelCustomizationUuid; //NOTE: this is the vfModule's modelCustomizationUuid
- private String mode = "HEAT";
-
- public VnfRollback() {}
-
- /**
- * For backwards compatibility... orchestration mode defaults to HEAT
- *
- * @param vnfId
- * @param tenantId
- * @param cloudOwner
- * @param cloudSiteId
- * @param tenantCreated
- * @param vnfCreated
- * @param msoRequest
- * @param volumeGroupName
- * @param volumeGroupId
- * @param requestType
- * @param modelCustomizationUuid
- */
- public VnfRollback(String vnfId, String tenantId, String cloudOwner, String cloudSiteId,
- boolean tenantCreated, boolean vnfCreated,
- MsoRequest msoRequest,
- String volumeGroupName, String volumeGroupId, String requestType, String modelCustomizationUuid) {
- super();
- this.vnfId = vnfId;
- this.tenantId = tenantId;
- this.cloudOwner = cloudOwner;
- this.cloudSiteId = cloudSiteId;
- this.tenantCreated = tenantCreated;
- this.vnfCreated = vnfCreated;
- this.msoRequest = msoRequest;
- this.volumeGroupName = volumeGroupName;
- this.volumeGroupId = volumeGroupId;
- this.requestType = requestType;
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
-
- /**
- *
- * @param vnfId
- * @param tenantId
- * @param cloudOwner
- * @param cloudSiteId
- * @param tenantCreated
- * @param vnfCreated
- * @param msoRequest
- * @param volumeGroupName
- * @param volumeGroupId
- * @param requestType
- * @param modelCustomizationUuid
- */
- public VnfRollback(String vnfId, String tenantId, String cloudOwner, String cloudSiteId,
- boolean tenantCreated, boolean vnfCreated,
- MsoRequest msoRequest, String volumeGroupName, String volumeGroupId,
- String requestType, String modelCustomizationUuid, String orchestrationMode) {
- super();
- this.vnfId = vnfId;
- this.tenantId = tenantId;
- this.cloudOwner = cloudOwner;
- this.cloudSiteId = cloudSiteId;
- this.tenantCreated = tenantCreated;
- this.vnfCreated = vnfCreated;
- this.msoRequest = msoRequest;
- this.volumeGroupName = volumeGroupName;
- this.volumeGroupId = volumeGroupId;
- this.requestType = requestType;
- this.modelCustomizationUuid = modelCustomizationUuid;
- this.mode = orchestrationMode;
- }
-
- public String getVnfId() {
- return vnfId;
- }
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getCloudSiteId() {
- return cloudSiteId;
- }
- public void setCloudSiteId(String cloudId) {
- this.cloudSiteId = cloudId;
- }
+ private String vnfId;
+ private String tenantId;
+ private String cloudOwner;
+ private String cloudSiteId;
+ private boolean tenantCreated = false;
+ private boolean vnfCreated = false;
+ private MsoRequest msoRequest;
+ private String volumeGroupName;
+ private String volumeGroupId;
+ private String requestType;
+ private String volumeGroupHeatStackId;
+ private String baseGroupHeatStackId;
+ private boolean isBase = false;
+ private String vfModuleStackId;
+ private String modelCustomizationUuid; // NOTE: this is the vfModule's modelCustomizationUuid
+ private String mode = "HEAT";
+
+ public VnfRollback() {}
+
+ /**
+ * For backwards compatibility... orchestration mode defaults to HEAT
+ *
+ * @param vnfId
+ * @param tenantId
+ * @param cloudOwner
+ * @param cloudSiteId
+ * @param tenantCreated
+ * @param vnfCreated
+ * @param msoRequest
+ * @param volumeGroupName
+ * @param volumeGroupId
+ * @param requestType
+ * @param modelCustomizationUuid
+ */
+ public VnfRollback(String vnfId, String tenantId, String cloudOwner, String cloudSiteId, boolean tenantCreated,
+ boolean vnfCreated, MsoRequest msoRequest, String volumeGroupName, String volumeGroupId, String requestType,
+ String modelCustomizationUuid) {
+ super();
+ this.vnfId = vnfId;
+ this.tenantId = tenantId;
+ this.cloudOwner = cloudOwner;
+ this.cloudSiteId = cloudSiteId;
+ this.tenantCreated = tenantCreated;
+ this.vnfCreated = vnfCreated;
+ this.msoRequest = msoRequest;
+ this.volumeGroupName = volumeGroupName;
+ this.volumeGroupId = volumeGroupId;
+ this.requestType = requestType;
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ /**
+ *
+ * @param vnfId
+ * @param tenantId
+ * @param cloudOwner
+ * @param cloudSiteId
+ * @param tenantCreated
+ * @param vnfCreated
+ * @param msoRequest
+ * @param volumeGroupName
+ * @param volumeGroupId
+ * @param requestType
+ * @param modelCustomizationUuid
+ */
+ public VnfRollback(String vnfId, String tenantId, String cloudOwner, String cloudSiteId, boolean tenantCreated,
+ boolean vnfCreated, MsoRequest msoRequest, String volumeGroupName, String volumeGroupId, String requestType,
+ String modelCustomizationUuid, String orchestrationMode) {
+ super();
+ this.vnfId = vnfId;
+ this.tenantId = tenantId;
+ this.cloudOwner = cloudOwner;
+ this.cloudSiteId = cloudSiteId;
+ this.tenantCreated = tenantCreated;
+ this.vnfCreated = vnfCreated;
+ this.msoRequest = msoRequest;
+ this.volumeGroupName = volumeGroupName;
+ this.volumeGroupId = volumeGroupId;
+ this.requestType = requestType;
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ this.mode = orchestrationMode;
+ }
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudId) {
+ this.cloudSiteId = cloudId;
+ }
+
public String getCloudOwner() {
return cloudOwner;
}
+
public void setCloudOwner(String cloudOwner) {
this.cloudOwner = cloudOwner;
}
- public boolean getTenantCreated() {
- return tenantCreated;
- }
- public void setTenantCreated(boolean tenantCreated) {
- this.tenantCreated = tenantCreated;
- }
- public boolean getVnfCreated() {
- return vnfCreated;
- }
- public void setVnfCreated(boolean vnfCreated) {
- this.vnfCreated = vnfCreated;
- }
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
- public void setMsoRequest (MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
- public String getVolumeGroupName() {
- return this.volumeGroupName;
- }
- public void setVolumeGroupName(String volumeGroupName) {
- this.volumeGroupName = volumeGroupName;
- }
- public String getVolumeGroupId() {
- return this.volumeGroupId;
- }
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
- public String getRequestType() {
- return this.requestType;
- }
- public void setRequestType(String requestType) {
- this.requestType = requestType;
- }
- public String getVolumeGroupHeatStackId() {
- return this.volumeGroupHeatStackId;
- }
- public void setVolumeGroupHeatStackId(String volumeGroupHeatStackId) {
- this.volumeGroupHeatStackId = volumeGroupHeatStackId;
- }
-
- public String getBaseGroupHeatStackId() {
- return this.baseGroupHeatStackId;
- }
- public void setBaseGroupHeatStackId(String baseGroupHeatStackId) {
- this.baseGroupHeatStackId = baseGroupHeatStackId;
- }
-
- public boolean isBase() {
- return this.isBase;
- }
- public void setIsBase(boolean isBase) {
- this.isBase = isBase;
- }
- public String getVfModuleStackId() {
- return this.vfModuleStackId;
- }
- public void setVfModuleStackId(String vfModuleStackId) {
- this.vfModuleStackId = vfModuleStackId;
- }
- public String getModelCustomizationUuid() {
- return this.modelCustomizationUuid;
- }
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
- public String getMode() {
- return this.mode;
- }
- public void setMode(String mode) {
- this.mode = mode;
- }
- @Override
+
+ public boolean getTenantCreated() {
+ return tenantCreated;
+ }
+
+ public void setTenantCreated(boolean tenantCreated) {
+ this.tenantCreated = tenantCreated;
+ }
+
+ public boolean getVnfCreated() {
+ return vnfCreated;
+ }
+
+ public void setVnfCreated(boolean vnfCreated) {
+ this.vnfCreated = vnfCreated;
+ }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
+
+ public String getVolumeGroupName() {
+ return this.volumeGroupName;
+ }
+
+ public void setVolumeGroupName(String volumeGroupName) {
+ this.volumeGroupName = volumeGroupName;
+ }
+
+ public String getVolumeGroupId() {
+ return this.volumeGroupId;
+ }
+
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ public String getRequestType() {
+ return this.requestType;
+ }
+
+ public void setRequestType(String requestType) {
+ this.requestType = requestType;
+ }
+
+ public String getVolumeGroupHeatStackId() {
+ return this.volumeGroupHeatStackId;
+ }
+
+ public void setVolumeGroupHeatStackId(String volumeGroupHeatStackId) {
+ this.volumeGroupHeatStackId = volumeGroupHeatStackId;
+ }
+
+ public String getBaseGroupHeatStackId() {
+ return this.baseGroupHeatStackId;
+ }
+
+ public void setBaseGroupHeatStackId(String baseGroupHeatStackId) {
+ this.baseGroupHeatStackId = baseGroupHeatStackId;
+ }
+
+ public boolean isBase() {
+ return this.isBase;
+ }
+
+ public void setIsBase(boolean isBase) {
+ this.isBase = isBase;
+ }
+
+ public String getVfModuleStackId() {
+ return this.vfModuleStackId;
+ }
+
+ public void setVfModuleStackId(String vfModuleStackId) {
+ this.vfModuleStackId = vfModuleStackId;
+ }
+
+ public String getModelCustomizationUuid() {
+ return this.modelCustomizationUuid;
+ }
+
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ public String getMode() {
+ return this.mode;
+ }
+
+ public void setMode(String mode) {
+ this.mode = mode;
+ }
+
+ @Override
public String toString() {
- return "VnfRollback: owner=" + cloudOwner + ", cloud=" + cloudSiteId + ", tenant=" + tenantId +
- ", vnf=" + vnfId + ", tenantCreated=" + tenantCreated +
- ", vnfCreated=" + vnfCreated + ", requestType = " + requestType
- + ", modelCustomizationUuid=" + this.modelCustomizationUuid
- + ", mode=" + mode;
- }
-} \ No newline at end of file
+ return "VnfRollback: owner=" + cloudOwner + ", cloud=" + cloudSiteId + ", tenant=" + tenantId + ", vnf=" + vnfId
+ + ", tenantCreated=" + tenantCreated + ", vnfCreated=" + vnfCreated + ", requestType = " + requestType
+ + ", modelCustomizationUuid=" + this.modelCustomizationUuid + ", mode=" + mode;
+ }
+}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/VnfStatus.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/VnfStatus.java
index 9f1ae8813d..e657dfe3bc 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/VnfStatus.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/VnfStatus.java
@@ -25,6 +25,6 @@ package org.onap.so.openstack.beans;
* Enum status values to mirror the Openstack Heat stack status values
*/
public enum VnfStatus {
- ACTIVE, FAILED, NOTFOUND, UNKNOWN
+ ACTIVE, FAILED, NOTFOUND, UNKNOWN
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoAdapterException.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoAdapterException.java
index 31c4727934..ab93d4cca2 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoAdapterException.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoAdapterException.java
@@ -27,19 +27,18 @@ package org.onap.so.openstack.exceptions;
*
*
*/
-public class MsoAdapterException extends MsoException
-{
- private static final long serialVersionUID = 1L;
-
- // Constructor to create a new MsoException instance
- public MsoAdapterException (String message) {
- super(message);
- super.category = MsoExceptionCategory.INTERNAL;
- }
+public class MsoAdapterException extends MsoException {
+ private static final long serialVersionUID = 1L;
- // Constructor to wrap a nested exception
- public MsoAdapterException (String message, Throwable t) {
- super(message, t);
- super.category = MsoExceptionCategory.INTERNAL;
- }
+ // Constructor to create a new MsoException instance
+ public MsoAdapterException(String message) {
+ super(message);
+ super.category = MsoExceptionCategory.INTERNAL;
+ }
+
+ // Constructor to wrap a nested exception
+ public MsoAdapterException(String message, Throwable t) {
+ super(message, t);
+ super.category = MsoExceptionCategory.INTERNAL;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoCloudIdentityNotFound.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoCloudIdentityNotFound.java
index 31f3f6f7dd..5892d00573 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoCloudIdentityNotFound.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoCloudIdentityNotFound.java
@@ -34,23 +34,24 @@ public class MsoCloudIdentityNotFound extends MsoException {
/**
* Default constructor (needed for BPEL/JAXB)
*/
- public MsoCloudIdentityNotFound () {
+ public MsoCloudIdentityNotFound() {
super("Cloud Identity not found");
- super.category=MsoExceptionCategory.USERDATA;
+ super.category = MsoExceptionCategory.USERDATA;
}
/**
* Constructor to create a new MsoOpenstackException instance
+ *
* @param cloudSite the cloud site
*/
- public MsoCloudIdentityNotFound (String cloudIdentity) {
+ public MsoCloudIdentityNotFound(String cloudIdentity) {
// Set the detailed error as the Exception 'message'
super("Cloud Identity [" + cloudIdentity + "] not found");
- super.category=MsoExceptionCategory.USERDATA;
+ super.category = MsoExceptionCategory.USERDATA;
}
@Override
- public String toString () {
+ public String toString() {
return getMessage();
}
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoCloudSiteNotFound.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoCloudSiteNotFound.java
index ceb08d8ccb..1d30aa2b94 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoCloudSiteNotFound.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoCloudSiteNotFound.java
@@ -34,23 +34,24 @@ public class MsoCloudSiteNotFound extends MsoException {
/**
* Default constructor (needed for BPEL/JAXB)
*/
- public MsoCloudSiteNotFound () {
+ public MsoCloudSiteNotFound() {
super("Cloud site not found");
- super.category=MsoExceptionCategory.USERDATA;
+ super.category = MsoExceptionCategory.USERDATA;
}
/**
* Constructor to create a new MsoOpenstackException instance
+ *
* @param cloudSite the cloud site
*/
- public MsoCloudSiteNotFound (String cloudSite) {
+ public MsoCloudSiteNotFound(String cloudSite) {
// Set the detailed error as the Exception 'message'
super("Cloud Site [" + cloudSite + "] not found");
- super.category=MsoExceptionCategory.USERDATA;
+ super.category = MsoExceptionCategory.USERDATA;
}
@Override
- public String toString () {
+ public String toString() {
return getMessage();
}
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoException.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoException.java
index 625914e820..901575d995 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoException.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoException.java
@@ -22,45 +22,47 @@ package org.onap.so.openstack.exceptions;
-public abstract class MsoException extends Exception
-{
- private static final long serialVersionUID = 1L;
+public abstract class MsoException extends Exception {
+ private static final long serialVersionUID = 1L;
- protected MsoExceptionCategory category = MsoExceptionCategory.INTERNAL;
- protected String context = null;
-
- protected MsoException (String message) {
- super(message);
- }
-
- protected MsoException (String message, Throwable t) {
- super(message,t);
- }
-
- public MsoExceptionCategory getCategory() {
- return category;
- }
- public void setCategory (MsoExceptionCategory category) {
- this.category = category;
- }
-
- public String getContext () {
- return context;
- }
- public void setContext (String context) {
- this.context = context;
- }
- public void addContext (String ctx) {
- if (this.context != null)
- this.context = ctx + ":" + this.context;
- else
- this.context = ctx;
- }
-
- public String getContextMessage () {
- if (this.context == null)
- return getMessage();
- else
- return "[" + context + "] " + getMessage();
- }
+ protected MsoExceptionCategory category = MsoExceptionCategory.INTERNAL;
+ protected String context = null;
+
+ protected MsoException(String message) {
+ super(message);
+ }
+
+ protected MsoException(String message, Throwable t) {
+ super(message, t);
+ }
+
+ public MsoExceptionCategory getCategory() {
+ return category;
+ }
+
+ public void setCategory(MsoExceptionCategory category) {
+ this.category = category;
+ }
+
+ public String getContext() {
+ return context;
+ }
+
+ public void setContext(String context) {
+ this.context = context;
+ }
+
+ public void addContext(String ctx) {
+ if (this.context != null)
+ this.context = ctx + ":" + this.context;
+ else
+ this.context = ctx;
+ }
+
+ public String getContextMessage() {
+ if (this.context == null)
+ return getMessage();
+ else
+ return "[" + context + "] " + getMessage();
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoExceptionCategory.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoExceptionCategory.java
index ed57488301..735f49d486 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoExceptionCategory.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoExceptionCategory.java
@@ -23,5 +23,5 @@ package org.onap.so.openstack.exceptions;
public enum MsoExceptionCategory {
- OPENSTACK, IO, INTERNAL, USERDATA
+ OPENSTACK, IO, INTERNAL, USERDATA
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoHeatNotFoundException.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoHeatNotFoundException.java
index dda7384d9e..026a06094f 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoHeatNotFoundException.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoHeatNotFoundException.java
@@ -25,11 +25,11 @@ package org.onap.so.openstack.exceptions;
*/
public class MsoHeatNotFoundException extends MsoException {
/**
- * Serialization id.
- */
- private static final long serialVersionUID = 6547134336163166841L;
+ * Serialization id.
+ */
+ private static final long serialVersionUID = 6547134336163166841L;
- /**
+ /**
* Default constructor (needed for BPEL/JAXB)
*/
public MsoHeatNotFoundException() {
@@ -39,6 +39,7 @@ public class MsoHeatNotFoundException extends MsoException {
/**
* Constructor to create a new MsoHeatNotFoundException instance
+ *
* @param heat the heat parameter
*/
public MsoHeatNotFoundException(String heat) {
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoIOException.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoIOException.java
index 35f2445d41..33377f447b 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoIOException.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoIOException.java
@@ -24,30 +24,31 @@ package org.onap.so.openstack.exceptions;
/**
* I/O exception
*/
-public class MsoIOException extends MsoException
-{
+public class MsoIOException extends MsoException {
- /**
+ /**
* Serialization id.
*/
private static final long serialVersionUID = 6752445132721635760L;
/**
* Basic constructor with message
+ *
+ * @param message the error message
+ */
+ public MsoIOException(String message) {
+ super(message);
+ super.category = MsoExceptionCategory.IO;
+ }
+
+ /**
+ * Constructor to wrap a nested exception
+ *
* @param message the error message
+ * @param t the cause
*/
- public MsoIOException (String message) {
- super(message);
- super.category = MsoExceptionCategory.IO;
- }
-
- /**
- * Constructor to wrap a nested exception
- * @param message the error message
- * @param t the cause
- */
- public MsoIOException (String message, Throwable t) {
- super (message, t);
- super.category = MsoExceptionCategory.IO;
- }
+ public MsoIOException(String message, Throwable t) {
+ super(message, t);
+ super.category = MsoExceptionCategory.IO;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoNetworkAlreadyExists.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoNetworkAlreadyExists.java
index dd7817d310..ddbafa7307 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoNetworkAlreadyExists.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoNetworkAlreadyExists.java
@@ -24,12 +24,12 @@ package org.onap.so.openstack.exceptions;
public class MsoNetworkAlreadyExists extends MsoOpenstackException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ // Constructor to create a new MsoOpenstackException instance
+ public MsoNetworkAlreadyExists(String stack, String tenant, String cloud) {
+ // Set the detailed error as the Exception 'message'
+ super(409, "Conflict", "Stack " + stack + " already exists in Tenant " + tenant + " in Cloud " + cloud);
+ }
- // Constructor to create a new MsoOpenstackException instance
- public MsoNetworkAlreadyExists (String stack, String tenant, String cloud) {
- // Set the detailed error as the Exception 'message'
- super(409, "Conflict", "Stack " + stack + " already exists in Tenant " + tenant + " in Cloud " + cloud);
- }
-
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoNetworkNotFound.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoNetworkNotFound.java
index 7306142cd0..ca8294196f 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoNetworkNotFound.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoNetworkNotFound.java
@@ -24,12 +24,12 @@ package org.onap.so.openstack.exceptions;
public class MsoNetworkNotFound extends MsoOpenstackException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ // Constructor to create a new MsoOpenstackException instance
+ public MsoNetworkNotFound(String networkId, String tenant, String cloud) {
+ // Set the detailed error as the Exception 'message'
+ super(404, "Not Found", "Network " + networkId + " does not exist in Cloud/Tenant " + cloud + "/" + tenant);
+ }
- // Constructor to create a new MsoOpenstackException instance
- public MsoNetworkNotFound (String networkId, String tenant, String cloud) {
- // Set the detailed error as the Exception 'message'
- super(404, "Not Found", "Network " + networkId + " does not exist in Cloud/Tenant " + cloud + "/" + tenant);
- }
-
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoOpenstackException.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoOpenstackException.java
index 1410650dd2..f5b6c7b4f9 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoOpenstackException.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoOpenstackException.java
@@ -24,57 +24,54 @@ package org.onap.so.openstack.exceptions;
/**
* OpenStack exception.
*/
-public class MsoOpenstackException extends MsoException
-{
-
- /**
+public class MsoOpenstackException extends MsoException {
+
+ /**
* Serialization id.
*/
private static final long serialVersionUID = 3313636124141766495L;
-
+
private int statusCode;
- private String statusMessage;
- private String errorDetail;
+ private String statusMessage;
+ private String errorDetail;
+
+ /**
+ * Constructor to create a new MsoOpenstackException instance
+ *
+ * @param code the error code
+ * @param message the error message
+ * @param detail error details
+ */
+ public MsoOpenstackException(int code, String message, String detail) {
+ // Set the detailed error as the Exception 'message'
+ super(detail);
+ super.category = MsoExceptionCategory.OPENSTACK;
+
+ this.statusCode = code;
+ this.statusMessage = message;
+ this.errorDetail = detail;
+ }
- /**
- * Constructor to create a new MsoOpenstackException instance
- * @param code the error code
- * @param message the error message
- * @param detail error details
- */
- public MsoOpenstackException (int code, String message, String detail) {
- // Set the detailed error as the Exception 'message'
- super(detail);
- super.category = MsoExceptionCategory.OPENSTACK;
-
- this.statusCode = code;
- this.statusMessage = message;
- this.errorDetail = detail;
- }
-
- /**
- * Constructor to propagate the caught exception (mostly for stack trace)
+ /**
+ * Constructor to propagate the caught exception (mostly for stack trace)
+ *
* @param code the error code
* @param message the error message
* @param detail error details
- * @param e the cause
- */
- public MsoOpenstackException (int code, String message, String detail, Exception e) {
- // Set the detailed error as the Exception 'message'
- super(detail, e);
- super.category = MsoExceptionCategory.OPENSTACK;
-
- this.statusCode = code;
- this.statusMessage = message;
- this.errorDetail = detail;
- }
+ * @param e the cause
+ */
+ public MsoOpenstackException(int code, String message, String detail, Exception e) {
+ // Set the detailed error as the Exception 'message'
+ super(detail, e);
+ super.category = MsoExceptionCategory.OPENSTACK;
+
+ this.statusCode = code;
+ this.statusMessage = message;
+ this.errorDetail = detail;
+ }
- @Override
- public String toString() {
- return statusCode +
- " " +
- statusMessage +
- ": " +
- errorDetail;
- }
+ @Override
+ public String toString() {
+ return statusCode + " " + statusMessage + ": " + errorDetail;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoStackAlreadyExists.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoStackAlreadyExists.java
index fc98ee95ed..fec9363fd4 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoStackAlreadyExists.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoStackAlreadyExists.java
@@ -24,12 +24,12 @@ package org.onap.so.openstack.exceptions;
public class MsoStackAlreadyExists extends MsoOpenstackException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ // Constructor to create a new MsoOpenstackException instance
+ public MsoStackAlreadyExists(String stack, String tenant, String cloud) {
+ // Set the detailed error as the Exception 'message'
+ super(409, "Conflict", "Stack " + stack + " already exists in Tenant " + tenant + " in Cloud " + cloud);
+ }
- // Constructor to create a new MsoOpenstackException instance
- public MsoStackAlreadyExists (String stack, String tenant, String cloud) {
- // Set the detailed error as the Exception 'message'
- super(409, "Conflict", "Stack " + stack + " already exists in Tenant " + tenant + " in Cloud " + cloud);
- }
-
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoStackNotFound.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoStackNotFound.java
index 1cd6b9650a..9925b62d12 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoStackNotFound.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoStackNotFound.java
@@ -26,19 +26,20 @@ package org.onap.so.openstack.exceptions;
*/
public class MsoStackNotFound extends MsoOpenstackException {
- /**
+ /**
* Serialization id.
*/
private static final long serialVersionUID = 7354069716354359246L;
/**
- * Constructor to create a new MsoOpenstackException instance.
- * @param stack the stack name
- * @param tenant the tenant name
- * @param cloud the cloud name
- */
- public MsoStackNotFound (String stack, String tenant, String cloud) {
- // Set the detailed error as the Exception 'message'
- super(404, "Not Found", "Stack " + stack + " does not exist in Cloud/Tenant " + cloud + "/" + tenant);
- }
+ * Constructor to create a new MsoOpenstackException instance.
+ *
+ * @param stack the stack name
+ * @param tenant the tenant name
+ * @param cloud the cloud name
+ */
+ public MsoStackNotFound(String stack, String tenant, String cloud) {
+ // Set the detailed error as the Exception 'message'
+ super(404, "Not Found", "Stack " + stack + " does not exist in Cloud/Tenant " + cloud + "/" + tenant);
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoTenantAlreadyExists.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoTenantAlreadyExists.java
index 5da32847b1..58585470a6 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoTenantAlreadyExists.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoTenantAlreadyExists.java
@@ -24,12 +24,12 @@ package org.onap.so.openstack.exceptions;
public class MsoTenantAlreadyExists extends MsoOpenstackException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ // Constructor to create a new MsoOpenstackException instance
+ public MsoTenantAlreadyExists(String tenant, String cloud) {
+ // Set the detailed error as the Exception 'message'
+ super(409, "Conflict", "Tenant " + tenant + " already exists in Cloud " + cloud);
+ }
- // Constructor to create a new MsoOpenstackException instance
- public MsoTenantAlreadyExists (String tenant, String cloud) {
- // Set the detailed error as the Exception 'message'
- super(409, "Conflict", "Tenant " + tenant + " already exists in Cloud " + cloud);
- }
-
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoTenantNotFound.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoTenantNotFound.java
index 9b135b61b2..6f4ce1d213 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoTenantNotFound.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/exceptions/MsoTenantNotFound.java
@@ -32,12 +32,13 @@ public class MsoTenantNotFound extends MsoOpenstackException {
private static final long serialVersionUID = 5640069939645577063L;
/**
- * Constructor to create the exception
- * @param tenant the tenant id
- * @param cloud the cloud id
- */
- public MsoTenantNotFound (String tenant, String cloud) {
- // Set the detailed error as the Exception 'message'
- super(404, "Not Found", "Tenant " + tenant + " does not exist in Cloud " + cloud);
- }
+ * Constructor to create the exception
+ *
+ * @param tenant the tenant id
+ * @param cloud the cloud id
+ */
+ public MsoTenantNotFound(String tenant, String cloud) {
+ // Set the detailed error as the Exception 'message'
+ super(404, "Not Found", "Tenant " + tenant + " does not exist in Cloud " + cloud);
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapAdapter.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapAdapter.java
index e816646e1c..ef5d4316d7 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapAdapter.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapAdapter.java
@@ -22,41 +22,43 @@ package org.onap.so.openstack.mappers;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.adapters.XmlAdapter;
-
import org.w3c.dom.Element;
public class MapAdapter extends XmlAdapter<MapEntry, Map<String, Object>> {
- @Override
- public MapEntry marshal(Map<String, Object> v) throws Exception {
+ @Override
+ public MapEntry marshal(Map<String, Object> v) throws Exception {
- if (v == null || v.isEmpty()) {return null;}
+ if (v == null || v.isEmpty()) {
+ return null;
+ }
- MapEntry map = new MapEntry();
+ MapEntry map = new MapEntry();
- for (String key : v.keySet()) {
- map.addEntry(key, v.get(key));
- }
+ for (String key : v.keySet()) {
+ map.addEntry(key, v.get(key));
+ }
- return map;
- }
+ return map;
+ }
- @Override
- public Map<String, Object> unmarshal(MapEntry v) throws Exception {
- if (v == null) {return null;}
+ @Override
+ public Map<String, Object> unmarshal(MapEntry v) throws Exception {
+ if (v == null) {
+ return null;
+ }
- Map<String, Object> map = new HashMap<>(v.entry.size());
+ Map<String, Object> map = new HashMap<>(v.entry.size());
- for(MapElements entry: v.entry) {
- if (entry.value instanceof Element) {
- map.put(entry.key, ((Element)entry.value).getTextContent());
- } else {
- map.put(entry.key, entry.value);
- }
- }
+ for (MapElements entry : v.entry) {
+ if (entry.value instanceof Element) {
+ map.put(entry.key, ((Element) entry.value).getTextContent());
+ } else {
+ map.put(entry.key, entry.value);
+ }
+ }
- return map;
- }
+ return map;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapElements.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapElements.java
index 709393bb84..d20d2b7758 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapElements.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapElements.java
@@ -22,16 +22,16 @@ package org.onap.so.openstack.mappers;
import javax.xml.bind.annotation.XmlElement;
-public class MapElements
-{
- @XmlElement public String key;
- @XmlElement public Object value;
+public class MapElements {
+ @XmlElement
+ public String key;
+ @XmlElement
+ public Object value;
- public MapElements() {} //Required by JAXB
+ public MapElements() {} // Required by JAXB
- public MapElements(String key, Object value)
- {
- this.key = key;
- this.value = value;
- }
+ public MapElements(String key, Object value) {
+ this.key = key;
+ this.value = value;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapEntry.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapEntry.java
index e6dc0e0538..489e11e111 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapEntry.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapEntry.java
@@ -24,13 +24,13 @@ import java.util.ArrayList;
import java.util.List;
public class MapEntry {
-
- public List<MapElements> entry = new ArrayList<>();
-
- public MapEntry() {} //Required by JAXB
- public void addEntry(String key, Object value) {
- entry.add(new MapElements(key, value));
- }
+ public List<MapElements> entry = new ArrayList<>();
+
+ public MapEntry() {} // Required by JAXB
+
+ public void addEntry(String key, Object value) {
+ entry.add(new MapElements(key, value));
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/NetworkInfoMapper.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/NetworkInfoMapper.java
index aa0f17810e..279620ac31 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/NetworkInfoMapper.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/NetworkInfoMapper.java
@@ -25,83 +25,79 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.javatuples.Pair;
import org.onap.so.openstack.beans.NetworkInfo;
import org.onap.so.openstack.beans.NetworkStatus;
-
import com.woorea.openstack.quantum.model.Network;
import com.woorea.openstack.quantum.model.Segment;
public class NetworkInfoMapper {
- private final Network network;
- private final Map<String,NetworkStatus> networkStatusMap = new HashMap<>();
+ private final Network network;
+ private final Map<String, NetworkStatus> networkStatusMap = new HashMap<>();
+
+ public NetworkInfoMapper(Network network) {
+ this.network = network;
+ configureNetworkStatusMap();
+ }
+
+ /**
+ * Capture the data from a Neutron Network object.
+ *
+ * For MSO, there are assumptions regarding all networks. - Everything will be a provider network - All provider
+ * networks are VLANs - Multiple VLANs are supported, and indicated by multi-provider segments. Each will have the
+ * same physical network & network type "vlan".
+ *
+ * @param network
+ */
+ public NetworkInfo map() {
+ final NetworkInfo info = new NetworkInfo();
+ if (network == null) {
+ info.setStatus(NetworkStatus.NOTFOUND);
+ } else {
+ info.setName(network.getName());
+ info.setId(network.getId());
+ info.setStatus(this.mapStatus(network.getStatus()));
+ Pair<Optional<String>, List<Integer>> result = locateVlanInformation(network);
+ Optional<String> value0 = result.getValue0();
+ if (value0.isPresent()) {
+ info.setProvider(value0.get());
+ }
+ info.setVlans(result.getValue1());
+ info.setSubnets(network.getSubnets());
+ }
+ return info;
+ }
+
+ protected NetworkStatus mapStatus(String status) {
+ return networkStatusMap.getOrDefault(status, NetworkStatus.UNKNOWN);
+ }
+
+ protected Pair<Optional<String>, List<Integer>> locateVlanInformation(Network network) {
+ final List<Integer> vlans = new ArrayList<>();
+ Optional<String> provider = Optional.empty();
+ if (network.getProviderPhysicalNetwork() != null) {
+ provider = Optional.ofNullable(network.getProviderPhysicalNetwork());
+ if ("vlan".equals(network.getProviderNetworkType())) {
+ vlans.add(network.getProviderSegmentationId());
+ }
+ } else if (network.getSegments() != null && !network.getSegments().isEmpty()) {
+ Segment s = network.getSegments().get(0);
+ provider = Optional.ofNullable(s.getProviderPhysicalNetwork());
+ if ("vlan".equals(s.getProviderNetworkType())) {
+ for (Segment s1 : network.getSegments()) {
+ vlans.add(s1.getProviderSegmentationId());
+ }
+ }
+ }
- public NetworkInfoMapper(Network network) {
- this.network = network;
- configureNetworkStatusMap();
- }
-
- /**
- * Capture the data from a Neutron Network object.
- *
- * For MSO, there are assumptions regarding all networks.
- * - Everything will be a provider network
- * - All provider networks are VLANs
- * - Multiple VLANs are supported, and indicated by multi-provider segments.
- * Each will have the same physical network & network type "vlan".
- *
- * @param network
- */
- public NetworkInfo map() {
- final NetworkInfo info = new NetworkInfo();
- if (network == null) {
- info.setStatus(NetworkStatus.NOTFOUND);
- } else {
- info.setName(network.getName());
- info.setId(network.getId());
- info.setStatus(this.mapStatus(network.getStatus()));
- Pair<Optional<String>, List<Integer>> result = locateVlanInformation(network);
- Optional<String> value0 = result.getValue0();
- if (value0.isPresent()) {
- info.setProvider(value0.get());
- }
- info.setVlans(result.getValue1());
- info.setSubnets(network.getSubnets());
- }
- return info;
- }
+ return Pair.with(provider, vlans);
+ }
- protected NetworkStatus mapStatus(String status) {
- return networkStatusMap.getOrDefault(status, NetworkStatus.UNKNOWN);
- }
-
- protected Pair<Optional<String>, List<Integer>> locateVlanInformation(Network network) {
- final List<Integer> vlans = new ArrayList<>();
- Optional<String> provider = Optional.empty();
- if (network.getProviderPhysicalNetwork() != null) {
- provider = Optional.ofNullable(network.getProviderPhysicalNetwork());
- if ("vlan".equals(network.getProviderNetworkType())) {
- vlans.add(network.getProviderSegmentationId());
- }
- } else if (network.getSegments() != null && !network.getSegments().isEmpty()) {
- Segment s = network.getSegments().get(0);
- provider = Optional.ofNullable(s.getProviderPhysicalNetwork());
- if ("vlan".equals(s.getProviderNetworkType())) {
- for (Segment s1 : network.getSegments()) {
- vlans.add(s1.getProviderSegmentationId());
- }
- }
- }
-
- return Pair.with(provider, vlans);
- }
-
- private void configureNetworkStatusMap() {
- networkStatusMap.put("ACTIVE", NetworkStatus.ACTIVE);
- networkStatusMap.put("DOWN", NetworkStatus.DOWN);
- networkStatusMap.put("BUILD", NetworkStatus.BUILD);
- networkStatusMap.put("ERROR", NetworkStatus.ERROR);
- }
+ private void configureNetworkStatusMap() {
+ networkStatusMap.put("ACTIVE", NetworkStatus.ACTIVE);
+ networkStatusMap.put("DOWN", NetworkStatus.DOWN);
+ networkStatusMap.put("BUILD", NetworkStatus.BUILD);
+ networkStatusMap.put("ERROR", NetworkStatus.ERROR);
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/StackInfoMapper.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/StackInfoMapper.java
index 85fd6cc279..8efa48ce79 100644
--- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/StackInfoMapper.java
+++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/StackInfoMapper.java
@@ -24,76 +24,76 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.onap.so.openstack.beans.HeatStatus;
import org.onap.so.openstack.beans.StackInfo;
-
import com.woorea.openstack.heat.model.Stack;
import com.woorea.openstack.heat.model.Stack.Output;
public class StackInfoMapper {
- private final Stack stack;
- private final Map<String,HeatStatus> heatStatusMap = new HashMap<>();
- public StackInfoMapper(Stack stack) {
- this.stack = stack;
- configureHeatStatusMap();
- }
-
- public StackInfo map() {
- final StackInfo info = new StackInfo();
- if (stack == null) {
- info.setStatus(HeatStatus.NOTFOUND);
- } else {
- info.setName(stack.getStackName());
- info.setCanonicalName(stack.getStackName() + "/" + stack.getId());
- info.setStatus(this.mapStatus(stack.getStackStatus()));
-
- info.setStatusMessage(stack.getStackStatusReason());
-
- Optional<Map<String, Object>> result = this.mapOutputToMap(stack.getOutputs());
- if (result.isPresent()) {
- info.setOutputs(result.get());
- }
-
- info.setParameters(stack.getParameters());
- }
-
- return info;
- }
-
- protected HeatStatus mapStatus(String status) {
- final HeatStatus result;
- if (status == null) {
- result = HeatStatus.INIT;
- } else {
- result = heatStatusMap.getOrDefault(status, HeatStatus.UNKNOWN);
- }
-
- return result;
- }
-
- protected Optional<Map<String, Object>> mapOutputToMap(List<Output> outputs) {
- Optional<Map<String, Object>> result = Optional.empty();
- if (outputs != null) {
- final HashMap<String, Object> map = new HashMap<>();
- for (Output output : outputs) {
- map.put(output.getOutputKey(), output.getOutputValue());
- }
- result = Optional.of(map);
- }
-
- return result;
- }
- private void configureHeatStatusMap() {
- heatStatusMap.put("CREATE_IN_PROGRESS", HeatStatus.BUILDING);
- heatStatusMap.put("CREATE_COMPLETE", HeatStatus.CREATED);
- heatStatusMap.put("CREATE_FAILED", HeatStatus.FAILED);
- heatStatusMap.put("DELETE_IN_PROGRESS", HeatStatus.DELETING);
- heatStatusMap.put("DELETE_COMPLETE", HeatStatus.NOTFOUND);
- heatStatusMap.put("DELETE_FAILED", HeatStatus.FAILED);
- heatStatusMap.put("UPDATE_IN_PROGRESS", HeatStatus.UPDATING);
- heatStatusMap.put("UPDATE_FAILED", HeatStatus.FAILED);
- heatStatusMap.put("UPDATE_COMPLETE", HeatStatus.UPDATED);
- }
+ private final Stack stack;
+ private final Map<String, HeatStatus> heatStatusMap = new HashMap<>();
+
+ public StackInfoMapper(Stack stack) {
+ this.stack = stack;
+ configureHeatStatusMap();
+ }
+
+ public StackInfo map() {
+ final StackInfo info = new StackInfo();
+ if (stack == null) {
+ info.setStatus(HeatStatus.NOTFOUND);
+ } else {
+ info.setName(stack.getStackName());
+ info.setCanonicalName(stack.getStackName() + "/" + stack.getId());
+ info.setStatus(this.mapStatus(stack.getStackStatus()));
+
+ info.setStatusMessage(stack.getStackStatusReason());
+
+ Optional<Map<String, Object>> result = this.mapOutputToMap(stack.getOutputs());
+ if (result.isPresent()) {
+ info.setOutputs(result.get());
+ }
+
+ info.setParameters(stack.getParameters());
+ }
+
+ return info;
+ }
+
+ protected HeatStatus mapStatus(String status) {
+ final HeatStatus result;
+ if (status == null) {
+ result = HeatStatus.INIT;
+ } else {
+ result = heatStatusMap.getOrDefault(status, HeatStatus.UNKNOWN);
+ }
+
+ return result;
+ }
+
+ protected Optional<Map<String, Object>> mapOutputToMap(List<Output> outputs) {
+ Optional<Map<String, Object>> result = Optional.empty();
+ if (outputs != null) {
+ final HashMap<String, Object> map = new HashMap<>();
+ for (Output output : outputs) {
+ map.put(output.getOutputKey(), output.getOutputValue());
+ }
+ result = Optional.of(map);
+ }
+
+ return result;
+ }
+
+ private void configureHeatStatusMap() {
+ heatStatusMap.put("CREATE_IN_PROGRESS", HeatStatus.BUILDING);
+ heatStatusMap.put("CREATE_COMPLETE", HeatStatus.CREATED);
+ heatStatusMap.put("CREATE_FAILED", HeatStatus.FAILED);
+ heatStatusMap.put("DELETE_IN_PROGRESS", HeatStatus.DELETING);
+ heatStatusMap.put("DELETE_COMPLETE", HeatStatus.NOTFOUND);
+ heatStatusMap.put("DELETE_FAILED", HeatStatus.FAILED);
+ heatStatusMap.put("UPDATE_IN_PROGRESS", HeatStatus.UPDATING);
+ heatStatusMap.put("UPDATE_FAILED", HeatStatus.FAILED);
+ heatStatusMap.put("UPDATE_COMPLETE", HeatStatus.UPDATED);
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/BeansTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/BeansTest.java
index e3474009c9..3ef91d3dbe 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/BeansTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/BeansTest.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters;
import org.junit.Test;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterNonConcrete;
@@ -35,31 +34,27 @@ import com.openpojo.validation.test.impl.SetterTester;
public class BeansTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.adapters.nwrest");
+ test("org.onap.so.adapters.sdncrest");
+ test("org.onap.so.adapters.tenantrest");
+ test("org.onap.so.adapters.vnfrest");
+ test("org.onap.so.adapters.network.beans");
+ test("org.onap.so.openstack.beans");
+ }
+
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule())
+ .with(new SetterTester()).with(new GetterTester()).build();
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, new FilterNonConcrete());
+ }
- @Test
- public void pojoStructure() {
- test("org.onap.so.adapters.nwrest");
- test("org.onap.so.adapters.sdncrest");
- test("org.onap.so.adapters.tenantrest");
- test("org.onap.so.adapters.vnfrest");
- test("org.onap.so.adapters.network.beans");
- test("org.onap.so.openstack.beans");
- }
-
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterMustExistRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, new FilterNonConcrete());
- }
-
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
-} \ No newline at end of file
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
+}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/network/mappers/ContrailSubnetMappersTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/network/mappers/ContrailSubnetMappersTest.java
index 240074bca7..61beceb922 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/network/mappers/ContrailSubnetMappersTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/network/mappers/ContrailSubnetMappersTest.java
@@ -21,11 +21,9 @@
package org.onap.so.adapters.network.mappers;
import static org.junit.Assert.assertEquals;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-
import org.junit.Test;
import org.onap.so.adapters.network.beans.ContrailSubnet;
import org.onap.so.adapters.network.beans.ContrailSubnetHostRoute;
@@ -38,199 +36,200 @@ import org.onap.so.openstack.beans.Subnet;
public class ContrailSubnetMappersTest {
-
-
- @Test
- public void contrailSubnetHostRouteMapperTest() {
- HostRoute hostRoute = new HostRoute();
- hostRoute.setNextHop("hop");
- hostRoute.setPrefix("prefix");
- ContrailSubnetHostRouteMapper mapper = new ContrailSubnetHostRouteMapper(hostRoute);
- ContrailSubnetHostRoute cshr = mapper.map();
- assertEquals("hop", cshr.getNextHop());
- assertEquals("prefix", cshr.getPrefix());
- }
-
- @Test
- public void contrailSubnetPoolMapperTest() {
- Pool pool = new Pool();
- pool.setStart("start");
- pool.setEnd("end");
- ContrailSubnetPoolMapper mapper = new ContrailSubnetPoolMapper(pool);
- ContrailSubnetPool csPool = mapper.map();
- assertEquals("start", csPool.getStart());
- assertEquals("end", csPool.getEnd());
- }
-
- @Test
- public void checkIsNullOrEmpty() {
- ContrailSubnetMapper mapper = new ContrailSubnetMapper(null);
- assertEquals(true, mapper.isNullOrEmpty(""));
- assertEquals(true, mapper.isNullOrEmpty(null));
- assertEquals(false, mapper.isNullOrEmpty("hello"));
- }
-
- @Test
- public void createSubnetTestValidCidr() {
- Subnet subnet = new Subnet();
- subnet.setCidr("test/value");
- ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
- ContrailSubnet result = mapper.map();
-
- assertEquals("test",result.getSubnet().getIpPrefix());
- assertEquals("value", result.getSubnet().getIpPrefixLen());
- }
-
- @Test
- public void createSubnetTestInvalidCidr() {
- Subnet subnet = new Subnet();
- subnet.setCidr("test");
- ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
- ContrailSubnet result = mapper.map();
- assertEquals(null, result.getSubnet().getIpPrefix());
- assertEquals(null, result.getSubnet().getIpPrefixLen());
-
- }
-
- @Test
- public void createSubnetTestNullCidr() {
- Subnet subnet = new Subnet();
- ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
- ContrailSubnet result = mapper.map();
- assertEquals(null, result.getSubnet().getIpPrefix());
- assertEquals(null, result.getSubnet().getIpPrefixLen());
- }
-
- @Test
- public void createContrailSubnetPoolTest() {
- List<Pool> pools = new ArrayList<>();
- Pool pool1 = new Pool();
- pool1.setStart("start1");
- pool1.setEnd("end1");
- Pool pool2 = new Pool();
- pool2.setStart("start2");
- pool2.setEnd("end2");
- pools.add(pool1);
- pools.add(pool2);
-
- Subnet subnet = new Subnet();
- subnet.setAllocationPools(pools);
- ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
- ContrailSubnet result = mapper.map();
- List<ContrailSubnetPool> cspools = result.getAllocationPools();
- assertEquals(2, cspools.size());
- assertEquals("start2", cspools.get(1).getStart());
- assertEquals("end2", cspools.get(1).getEnd());
- }
-
- @Test
- public void createContrailSubnetPoolInvalidTest() {
- List<Pool> pools = new ArrayList<>();
- Pool pool1 = new Pool();
- pool1.setStart("start1");
- pool1.setEnd("end1");
- Pool pool2 = new Pool();
- pool2.setStart("start2");
- pools.add(pool1);
- pools.add(pool2);
-
- Subnet subnet = new Subnet();
- subnet.setAllocationPools(pools);
- ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
- ContrailSubnet result = mapper.map();
- List<ContrailSubnetPool> cspools = result.getAllocationPools();
- assertEquals(1, cspools.size());
- assertEquals("start1", cspools.get(0).getStart());
- assertEquals("end1", cspools.get(0).getEnd());
- }
-
- @Test
- public void createContrailSubnetPoolEmptyTest() {
-
- Subnet subnet = new Subnet();
- ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
- ContrailSubnet result = mapper.map();
- List<ContrailSubnetPool> cspools = result.getAllocationPools();
- assertEquals(true, cspools.isEmpty());
-
- }
-
- @Test
- public void createContrailSubnetHostRoutesTest() {
- List<HostRoute> hostRoutes = new ArrayList<>();
- HostRoute hostRoute1 = new HostRoute();
- hostRoute1.setNextHop("next-hop1");
- hostRoute1.setPrefix("prefix1");
- HostRoute hostRoute2 = new HostRoute();
- hostRoute2.setNextHop("next-hop2");
- hostRoute2.setPrefix("prefix2");
- hostRoutes.add(hostRoute1);
- hostRoutes.add(hostRoute2);
-
- Subnet subnet = new Subnet();
- subnet.setHostRoutes(hostRoutes);
- ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
- ContrailSubnet result = mapper.map();
- ContrailSubnetHostRoutes routes = result.getHostRoutes();
- assertEquals(2, routes.getHostRoutes().size());
- assertEquals("next-hop2", routes.getHostRoutes().get(1).getNextHop());
- assertEquals("prefix2", routes.getHostRoutes().get(1).getPrefix());
- }
-
- @Test
- public void createContrailSubnetHostRoutesMissingFieldTest() {
- List<HostRoute> hostRoutes = new ArrayList<>();
- HostRoute hostRoute1 = new HostRoute();
- hostRoute1.setNextHop("next-hop1");
- HostRoute hostRoute2 = new HostRoute();
- hostRoute2.setNextHop("next-hop2");
- hostRoute2.setPrefix("prefix2");
- hostRoutes.add(hostRoute1);
- hostRoutes.add(hostRoute2);
-
- Subnet subnet = new Subnet();
- subnet.setHostRoutes(hostRoutes);
- ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
- ContrailSubnet result = mapper.map();
- ContrailSubnetHostRoutes routes = result.getHostRoutes();
- assertEquals(2, routes.getHostRoutes().size());
- assertEquals("next-hop1", routes.getHostRoutes().get(0).getNextHop());
- assertEquals("prefix2", routes.getHostRoutes().get(1).getPrefix());
- }
-
- @Test
- public void createContrailSubnetHostRoutesEmptyTest() {
- List<HostRoute> hostRoutes = new ArrayList<>();
- Subnet subnet = new Subnet();
- subnet.setHostRoutes(hostRoutes);
- ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
- ContrailSubnet result = mapper.map();
- ContrailSubnetHostRoutes routes = result.getHostRoutes();
- assertEquals(true, routes.getHostRoutes().isEmpty());
- }
-
- @Test
- public void getSubnetNameTest() {
- Subnet subnet = new Subnet();
- subnet.setSubnetName("name");
- ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
- assertEquals("if subnetName is populated map", "name", mapper.getSubnetName(subnet));
- subnet = new Subnet();
- subnet.setSubnetId("id");
- mapper = new ContrailSubnetMapper(subnet);
- assertEquals("choose id when name is null", "id", mapper.getSubnetName(subnet));
- subnet = new Subnet();
- mapper = new ContrailSubnetMapper(subnet);
- assertEquals("expect null", null, mapper.getSubnetName(subnet));
- }
- @Test
- public void mapRemainingFields() {
- Subnet subnet = new Subnet();
- subnet.setEnableDHCP(true);
- subnet.setGatewayIp("gateway-ip");
- ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
- ContrailSubnet result = mapper.map();
- assertEquals(true, result.isEnableDhcp());
- assertEquals("gateway-ip", result.getDefaultGateway());
- }
+
+
+ @Test
+ public void contrailSubnetHostRouteMapperTest() {
+ HostRoute hostRoute = new HostRoute();
+ hostRoute.setNextHop("hop");
+ hostRoute.setPrefix("prefix");
+ ContrailSubnetHostRouteMapper mapper = new ContrailSubnetHostRouteMapper(hostRoute);
+ ContrailSubnetHostRoute cshr = mapper.map();
+ assertEquals("hop", cshr.getNextHop());
+ assertEquals("prefix", cshr.getPrefix());
+ }
+
+ @Test
+ public void contrailSubnetPoolMapperTest() {
+ Pool pool = new Pool();
+ pool.setStart("start");
+ pool.setEnd("end");
+ ContrailSubnetPoolMapper mapper = new ContrailSubnetPoolMapper(pool);
+ ContrailSubnetPool csPool = mapper.map();
+ assertEquals("start", csPool.getStart());
+ assertEquals("end", csPool.getEnd());
+ }
+
+ @Test
+ public void checkIsNullOrEmpty() {
+ ContrailSubnetMapper mapper = new ContrailSubnetMapper(null);
+ assertEquals(true, mapper.isNullOrEmpty(""));
+ assertEquals(true, mapper.isNullOrEmpty(null));
+ assertEquals(false, mapper.isNullOrEmpty("hello"));
+ }
+
+ @Test
+ public void createSubnetTestValidCidr() {
+ Subnet subnet = new Subnet();
+ subnet.setCidr("test/value");
+ ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
+ ContrailSubnet result = mapper.map();
+
+ assertEquals("test", result.getSubnet().getIpPrefix());
+ assertEquals("value", result.getSubnet().getIpPrefixLen());
+ }
+
+ @Test
+ public void createSubnetTestInvalidCidr() {
+ Subnet subnet = new Subnet();
+ subnet.setCidr("test");
+ ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
+ ContrailSubnet result = mapper.map();
+ assertEquals(null, result.getSubnet().getIpPrefix());
+ assertEquals(null, result.getSubnet().getIpPrefixLen());
+
+ }
+
+ @Test
+ public void createSubnetTestNullCidr() {
+ Subnet subnet = new Subnet();
+ ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
+ ContrailSubnet result = mapper.map();
+ assertEquals(null, result.getSubnet().getIpPrefix());
+ assertEquals(null, result.getSubnet().getIpPrefixLen());
+ }
+
+ @Test
+ public void createContrailSubnetPoolTest() {
+ List<Pool> pools = new ArrayList<>();
+ Pool pool1 = new Pool();
+ pool1.setStart("start1");
+ pool1.setEnd("end1");
+ Pool pool2 = new Pool();
+ pool2.setStart("start2");
+ pool2.setEnd("end2");
+ pools.add(pool1);
+ pools.add(pool2);
+
+ Subnet subnet = new Subnet();
+ subnet.setAllocationPools(pools);
+ ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
+ ContrailSubnet result = mapper.map();
+ List<ContrailSubnetPool> cspools = result.getAllocationPools();
+ assertEquals(2, cspools.size());
+ assertEquals("start2", cspools.get(1).getStart());
+ assertEquals("end2", cspools.get(1).getEnd());
+ }
+
+ @Test
+ public void createContrailSubnetPoolInvalidTest() {
+ List<Pool> pools = new ArrayList<>();
+ Pool pool1 = new Pool();
+ pool1.setStart("start1");
+ pool1.setEnd("end1");
+ Pool pool2 = new Pool();
+ pool2.setStart("start2");
+ pools.add(pool1);
+ pools.add(pool2);
+
+ Subnet subnet = new Subnet();
+ subnet.setAllocationPools(pools);
+ ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
+ ContrailSubnet result = mapper.map();
+ List<ContrailSubnetPool> cspools = result.getAllocationPools();
+ assertEquals(1, cspools.size());
+ assertEquals("start1", cspools.get(0).getStart());
+ assertEquals("end1", cspools.get(0).getEnd());
+ }
+
+ @Test
+ public void createContrailSubnetPoolEmptyTest() {
+
+ Subnet subnet = new Subnet();
+ ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
+ ContrailSubnet result = mapper.map();
+ List<ContrailSubnetPool> cspools = result.getAllocationPools();
+ assertEquals(true, cspools.isEmpty());
+
+ }
+
+ @Test
+ public void createContrailSubnetHostRoutesTest() {
+ List<HostRoute> hostRoutes = new ArrayList<>();
+ HostRoute hostRoute1 = new HostRoute();
+ hostRoute1.setNextHop("next-hop1");
+ hostRoute1.setPrefix("prefix1");
+ HostRoute hostRoute2 = new HostRoute();
+ hostRoute2.setNextHop("next-hop2");
+ hostRoute2.setPrefix("prefix2");
+ hostRoutes.add(hostRoute1);
+ hostRoutes.add(hostRoute2);
+
+ Subnet subnet = new Subnet();
+ subnet.setHostRoutes(hostRoutes);
+ ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
+ ContrailSubnet result = mapper.map();
+ ContrailSubnetHostRoutes routes = result.getHostRoutes();
+ assertEquals(2, routes.getHostRoutes().size());
+ assertEquals("next-hop2", routes.getHostRoutes().get(1).getNextHop());
+ assertEquals("prefix2", routes.getHostRoutes().get(1).getPrefix());
+ }
+
+ @Test
+ public void createContrailSubnetHostRoutesMissingFieldTest() {
+ List<HostRoute> hostRoutes = new ArrayList<>();
+ HostRoute hostRoute1 = new HostRoute();
+ hostRoute1.setNextHop("next-hop1");
+ HostRoute hostRoute2 = new HostRoute();
+ hostRoute2.setNextHop("next-hop2");
+ hostRoute2.setPrefix("prefix2");
+ hostRoutes.add(hostRoute1);
+ hostRoutes.add(hostRoute2);
+
+ Subnet subnet = new Subnet();
+ subnet.setHostRoutes(hostRoutes);
+ ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
+ ContrailSubnet result = mapper.map();
+ ContrailSubnetHostRoutes routes = result.getHostRoutes();
+ assertEquals(2, routes.getHostRoutes().size());
+ assertEquals("next-hop1", routes.getHostRoutes().get(0).getNextHop());
+ assertEquals("prefix2", routes.getHostRoutes().get(1).getPrefix());
+ }
+
+ @Test
+ public void createContrailSubnetHostRoutesEmptyTest() {
+ List<HostRoute> hostRoutes = new ArrayList<>();
+ Subnet subnet = new Subnet();
+ subnet.setHostRoutes(hostRoutes);
+ ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
+ ContrailSubnet result = mapper.map();
+ ContrailSubnetHostRoutes routes = result.getHostRoutes();
+ assertEquals(true, routes.getHostRoutes().isEmpty());
+ }
+
+ @Test
+ public void getSubnetNameTest() {
+ Subnet subnet = new Subnet();
+ subnet.setSubnetName("name");
+ ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
+ assertEquals("if subnetName is populated map", "name", mapper.getSubnetName(subnet));
+ subnet = new Subnet();
+ subnet.setSubnetId("id");
+ mapper = new ContrailSubnetMapper(subnet);
+ assertEquals("choose id when name is null", "id", mapper.getSubnetName(subnet));
+ subnet = new Subnet();
+ mapper = new ContrailSubnetMapper(subnet);
+ assertEquals("expect null", null, mapper.getSubnetName(subnet));
+ }
+
+ @Test
+ public void mapRemainingFields() {
+ Subnet subnet = new Subnet();
+ subnet.setEnableDHCP(true);
+ subnet.setGatewayIp("gateway-ip");
+ ContrailSubnetMapper mapper = new ContrailSubnetMapper(subnet);
+ ContrailSubnet result = mapper.map();
+ assertEquals(true, result.isEnableDhcp());
+ assertEquals("gateway-ip", result.getDefaultGateway());
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/nwrest/NetworkRequestTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/nwrest/NetworkRequestTest.java
index 5e04fc49ee..f0f1565cf3 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/nwrest/NetworkRequestTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/nwrest/NetworkRequestTest.java
@@ -21,21 +21,20 @@
package org.onap.so.adapters.nwrest;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
public class NetworkRequestTest {
-
- @Test
- public void isSynchronousTrue() {
- CreateNetworkRequest networkResponse = new CreateNetworkRequest();
- assertEquals(true, networkResponse.isSynchronous());
- //flip synchronous to false in the background
- networkResponse.setNotificationUrl("testtest");
- assertEquals(false, networkResponse.isSynchronous());
- networkResponse.setNotificationUrl("");
- assertEquals(true, networkResponse.isSynchronous());
- }
-
+
+ @Test
+ public void isSynchronousTrue() {
+ CreateNetworkRequest networkResponse = new CreateNetworkRequest();
+ assertEquals(true, networkResponse.isSynchronous());
+ // flip synchronous to false in the background
+ networkResponse.setNotificationUrl("testtest");
+ assertEquals(false, networkResponse.isSynchronous());
+ networkResponse.setNotificationUrl("");
+ assertEquals(true, networkResponse.isSynchronous());
+ }
+
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/vdu/BeansTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/vdu/BeansTest.java
index e681d43256..d7704a46d6 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/vdu/BeansTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/adapters/vdu/BeansTest.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters.vdu;
import org.junit.Test;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterPackageInfo;
@@ -33,24 +32,22 @@ import com.openpojo.validation.test.impl.SetterTester;
public class BeansTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.adapters.vdu");
+ }
- @Test
- public void pojoStructure() {
- test("org.onap.so.adapters.vdu");
- }
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterTester())
+ .with(new GetterTester()).build();
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses);
+ }
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses);
- }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoAdapterExceptionTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoAdapterExceptionTest.java
index 28a4a8302f..4c864a72b7 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoAdapterExceptionTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoAdapterExceptionTest.java
@@ -28,14 +28,14 @@ public class MsoAdapterExceptionTest {
@Test
public void testConstructor() {
MsoAdapterException msoAdapterException = new MsoAdapterException("test");
- Assert.assertEquals("test",msoAdapterException.getMessage());
+ Assert.assertEquals("test", msoAdapterException.getMessage());
Assert.assertEquals(MsoExceptionCategory.INTERNAL, msoAdapterException.category);
}
@Test
public void testOverloadedConstructor() {
- MsoAdapterException msoAdapterException = new MsoAdapterException("test" , new Throwable());
- Assert.assertEquals("test",msoAdapterException.getMessage());
+ MsoAdapterException msoAdapterException = new MsoAdapterException("test", new Throwable());
+ Assert.assertEquals("test", msoAdapterException.getMessage());
Assert.assertEquals(MsoExceptionCategory.INTERNAL, msoAdapterException.category);
Assert.assertNotNull(msoAdapterException.getCause());
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoCloudIdentityNotFoundTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoCloudIdentityNotFoundTest.java
index e7befed71a..050c784c51 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoCloudIdentityNotFoundTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoCloudIdentityNotFoundTest.java
@@ -27,16 +27,16 @@ public class MsoCloudIdentityNotFoundTest {
@Test
public void testConstructor() {
MsoCloudIdentityNotFound msoCloudIdentityNotFound = new MsoCloudIdentityNotFound();
- Assert.assertEquals("Cloud Identity not found",msoCloudIdentityNotFound.getMessage());
- Assert.assertEquals("Cloud Identity not found",msoCloudIdentityNotFound.toString());
+ Assert.assertEquals("Cloud Identity not found", msoCloudIdentityNotFound.getMessage());
+ Assert.assertEquals("Cloud Identity not found", msoCloudIdentityNotFound.toString());
Assert.assertEquals(MsoExceptionCategory.USERDATA, msoCloudIdentityNotFound.category);
}
@Test
public void testOverloadedConstructor() {
MsoCloudIdentityNotFound msoCloudIdentityNotFound = new MsoCloudIdentityNotFound("test");
- Assert.assertEquals("Cloud Identity [test] not found",msoCloudIdentityNotFound.getMessage());
- Assert.assertEquals("Cloud Identity [test] not found",msoCloudIdentityNotFound.toString());
+ Assert.assertEquals("Cloud Identity [test] not found", msoCloudIdentityNotFound.getMessage());
+ Assert.assertEquals("Cloud Identity [test] not found", msoCloudIdentityNotFound.toString());
Assert.assertEquals(MsoExceptionCategory.USERDATA, msoCloudIdentityNotFound.category);
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoCloudSiteNotFoundTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoCloudSiteNotFoundTest.java
index c75a66e100..d6c57bb267 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoCloudSiteNotFoundTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoCloudSiteNotFoundTest.java
@@ -27,16 +27,16 @@ public class MsoCloudSiteNotFoundTest {
@Test
public void testConstructor() {
MsoCloudSiteNotFound msoCloudSiteNotFound = new MsoCloudSiteNotFound();
- Assert.assertEquals("Cloud site not found",msoCloudSiteNotFound.getMessage());
- Assert.assertEquals("Cloud site not found",msoCloudSiteNotFound.toString());
+ Assert.assertEquals("Cloud site not found", msoCloudSiteNotFound.getMessage());
+ Assert.assertEquals("Cloud site not found", msoCloudSiteNotFound.toString());
Assert.assertEquals(MsoExceptionCategory.USERDATA, msoCloudSiteNotFound.category);
}
@Test
public void testOverloadedConstructor() {
MsoCloudSiteNotFound msoCloudSiteNotFound = new MsoCloudSiteNotFound("test");
- Assert.assertEquals("Cloud Site [test] not found",msoCloudSiteNotFound.getMessage());
- Assert.assertEquals("Cloud Site [test] not found",msoCloudSiteNotFound.toString());
+ Assert.assertEquals("Cloud Site [test] not found", msoCloudSiteNotFound.getMessage());
+ Assert.assertEquals("Cloud Site [test] not found", msoCloudSiteNotFound.toString());
Assert.assertEquals(MsoExceptionCategory.USERDATA, msoCloudSiteNotFound.category);
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoIOExceptionTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoIOExceptionTest.java
index e257e52cd4..58425ed7d1 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoIOExceptionTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoIOExceptionTest.java
@@ -27,14 +27,14 @@ public class MsoIOExceptionTest {
@Test
public void testConstructor() {
MsoIOException msoIOException = new MsoIOException("test");
- Assert.assertEquals("test",msoIOException.getMessage());
+ Assert.assertEquals("test", msoIOException.getMessage());
Assert.assertEquals(MsoExceptionCategory.IO, msoIOException.category);
}
@Test
public void testOverloadedConstructor() {
MsoIOException msoIOException = new MsoIOException("test", new Throwable());
- Assert.assertEquals("test",msoIOException.getMessage());
+ Assert.assertEquals("test", msoIOException.getMessage());
Assert.assertEquals(MsoExceptionCategory.IO, msoIOException.category);
Assert.assertNotNull(msoIOException.getCause());
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoNetworkAlreadyExistsTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoNetworkAlreadyExistsTest.java
index 96ff89c094..f19fd57947 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoNetworkAlreadyExistsTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoNetworkAlreadyExistsTest.java
@@ -27,9 +27,11 @@ public class MsoNetworkAlreadyExistsTest {
@Test
public void testConstructor() {
- MsoNetworkAlreadyExists msoNetworkAlreadyExists = new MsoNetworkAlreadyExists("test","test","test");
- Assert.assertEquals("Stack test already exists in Tenant test in Cloud test",msoNetworkAlreadyExists.getMessage());
- Assert.assertEquals("409 Conflict: Stack test already exists in Tenant test in Cloud test",msoNetworkAlreadyExists.toString());
+ MsoNetworkAlreadyExists msoNetworkAlreadyExists = new MsoNetworkAlreadyExists("test", "test", "test");
+ Assert.assertEquals("Stack test already exists in Tenant test in Cloud test",
+ msoNetworkAlreadyExists.getMessage());
+ Assert.assertEquals("409 Conflict: Stack test already exists in Tenant test in Cloud test",
+ msoNetworkAlreadyExists.toString());
}
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoNetworkNotFoundTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoNetworkNotFoundTest.java
index 5991e55915..e35214f191 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoNetworkNotFoundTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoNetworkNotFoundTest.java
@@ -27,9 +27,10 @@ public class MsoNetworkNotFoundTest {
@Test
public void testConstructor() {
- MsoNetworkNotFound msoNetworkNotFound =new MsoNetworkNotFound("test","test","test");
- Assert.assertEquals("Network test does not exist in Cloud/Tenant test/test",msoNetworkNotFound.getMessage());
- Assert.assertEquals("404 Not Found: Network test does not exist in Cloud/Tenant test/test",msoNetworkNotFound.toString());
+ MsoNetworkNotFound msoNetworkNotFound = new MsoNetworkNotFound("test", "test", "test");
+ Assert.assertEquals("Network test does not exist in Cloud/Tenant test/test", msoNetworkNotFound.getMessage());
+ Assert.assertEquals("404 Not Found: Network test does not exist in Cloud/Tenant test/test",
+ msoNetworkNotFound.toString());
}
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoOpenstackExceptionTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoOpenstackExceptionTest.java
index 7bdb2283e8..f9022c3f57 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoOpenstackExceptionTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoOpenstackExceptionTest.java
@@ -27,17 +27,17 @@ public class MsoOpenstackExceptionTest {
@Test
public void testConstructor() {
- MsoOpenstackException msoOpenstackException= new MsoOpenstackException(404,"test","test");
- Assert.assertEquals("test",msoOpenstackException.getMessage());
- Assert.assertEquals("404 test: test",msoOpenstackException.toString());
+ MsoOpenstackException msoOpenstackException = new MsoOpenstackException(404, "test", "test");
+ Assert.assertEquals("test", msoOpenstackException.getMessage());
+ Assert.assertEquals("404 test: test", msoOpenstackException.toString());
Assert.assertEquals(MsoExceptionCategory.OPENSTACK, msoOpenstackException.category);
}
@Test
public void testOverloadedConstructor() {
- MsoOpenstackException msoOpenstackExceptionEx= new MsoOpenstackException(404,"test","test",new Exception());
- Assert.assertEquals("test",msoOpenstackExceptionEx.getMessage());
- Assert.assertEquals("404 test: test",msoOpenstackExceptionEx.toString());
+ MsoOpenstackException msoOpenstackExceptionEx = new MsoOpenstackException(404, "test", "test", new Exception());
+ Assert.assertEquals("test", msoOpenstackExceptionEx.getMessage());
+ Assert.assertEquals("404 test: test", msoOpenstackExceptionEx.toString());
Assert.assertEquals(MsoExceptionCategory.OPENSTACK, msoOpenstackExceptionEx.category);
Assert.assertNotNull(msoOpenstackExceptionEx.getCause());
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoStackAlreadyExistsTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoStackAlreadyExistsTest.java
index 4b44f0db93..6a9f05d853 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoStackAlreadyExistsTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoStackAlreadyExistsTest.java
@@ -28,7 +28,9 @@ public class MsoStackAlreadyExistsTest {
@Test
public void testConstructor() {
MsoStackAlreadyExists msoStackAlreadyExists = new MsoStackAlreadyExists("test", "test", "test");
- Assert.assertEquals("Stack test already exists in Tenant test in Cloud test",msoStackAlreadyExists.getMessage());
- Assert.assertEquals("409 Conflict: Stack test already exists in Tenant test in Cloud test",msoStackAlreadyExists.toString());
+ Assert.assertEquals("Stack test already exists in Tenant test in Cloud test",
+ msoStackAlreadyExists.getMessage());
+ Assert.assertEquals("409 Conflict: Stack test already exists in Tenant test in Cloud test",
+ msoStackAlreadyExists.toString());
}
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoStackNotFoundTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoStackNotFoundTest.java
index 8ce5a33cc4..1dd07b72e5 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoStackNotFoundTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoStackNotFoundTest.java
@@ -28,7 +28,8 @@ public class MsoStackNotFoundTest {
@Test
public void testConstructor() {
MsoStackNotFound msoStackNotFound = new MsoStackNotFound("test", "test", "test");
- Assert.assertEquals("Stack test does not exist in Cloud/Tenant test/test",msoStackNotFound.getMessage());
- Assert.assertEquals("404 Not Found: Stack test does not exist in Cloud/Tenant test/test",msoStackNotFound.toString());
+ Assert.assertEquals("Stack test does not exist in Cloud/Tenant test/test", msoStackNotFound.getMessage());
+ Assert.assertEquals("404 Not Found: Stack test does not exist in Cloud/Tenant test/test",
+ msoStackNotFound.toString());
}
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoTenantAlreadyExistsTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoTenantAlreadyExistsTest.java
index 5999a587a5..5bfdbd38e4 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoTenantAlreadyExistsTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoTenantAlreadyExistsTest.java
@@ -27,8 +27,9 @@ public class MsoTenantAlreadyExistsTest {
@Test
public void testConstructor() {
- MsoTenantAlreadyExists msoTenantAlreadyExists = new MsoTenantAlreadyExists("test","test");
- Assert.assertEquals("Tenant test already exists in Cloud test",msoTenantAlreadyExists.getMessage());
- Assert.assertEquals("409 Conflict: Tenant test already exists in Cloud test",msoTenantAlreadyExists.toString());
+ MsoTenantAlreadyExists msoTenantAlreadyExists = new MsoTenantAlreadyExists("test", "test");
+ Assert.assertEquals("Tenant test already exists in Cloud test", msoTenantAlreadyExists.getMessage());
+ Assert.assertEquals("409 Conflict: Tenant test already exists in Cloud test",
+ msoTenantAlreadyExists.toString());
}
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoTenantNotFoundTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoTenantNotFoundTest.java
index 23df616573..f45cddc676 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoTenantNotFoundTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/exceptions/MsoTenantNotFoundTest.java
@@ -27,9 +27,9 @@ public class MsoTenantNotFoundTest {
@Test
public void testConstructor() {
- MsoTenantNotFound msoTenantNotFound = new MsoTenantNotFound("test","test");
- Assert.assertEquals("Tenant test does not exist in Cloud test",msoTenantNotFound.getMessage());
- Assert.assertEquals("404 Not Found: Tenant test does not exist in Cloud test",msoTenantNotFound.toString());
+ MsoTenantNotFound msoTenantNotFound = new MsoTenantNotFound("test", "test");
+ Assert.assertEquals("Tenant test does not exist in Cloud test", msoTenantNotFound.getMessage());
+ Assert.assertEquals("404 Not Found: Tenant test does not exist in Cloud test", msoTenantNotFound.toString());
}
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/JAXBMarshallingTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/JAXBMarshallingTest.java
index 038e88317d..8d27e54892 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/JAXBMarshallingTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/JAXBMarshallingTest.java
@@ -21,14 +21,11 @@
package org.onap.so.openstack.mappers;
import static org.junit.Assert.assertEquals;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
-
import org.junit.Test;
import org.onap.so.adapters.vnfrest.CreateVfModuleRequest;
@@ -36,16 +33,17 @@ import org.onap.so.adapters.vnfrest.CreateVfModuleRequest;
public class JAXBMarshallingTest {
- @Test
- public void xmlMarshalTest() throws IOException, JAXBException {
- JAXBContext context = JAXBContext.newInstance(CreateVfModuleRequest.class);
+ @Test
+ public void xmlMarshalTest() throws IOException, JAXBException {
+ JAXBContext context = JAXBContext.newInstance(CreateVfModuleRequest.class);
- CreateVfModuleRequest request = (CreateVfModuleRequest) context.createUnmarshaller().unmarshal(Files.newBufferedReader(Paths.get("src/test/resources/createVfModuleRequest-with-params.xml")));
+ CreateVfModuleRequest request = (CreateVfModuleRequest) context.createUnmarshaller().unmarshal(
+ Files.newBufferedReader(Paths.get("src/test/resources/createVfModuleRequest-with-params.xml")));
- assertEquals("ubuntu-16-04-cloud-amd64", request.getVfModuleParams().get("vcpe_image_name"));
- assertEquals("10.2.0.0/24", request.getVfModuleParams().get("cpe_public_net_cidr"));
- assertEquals("", request.getVfModuleParams().get("workload_context"));
+ assertEquals("ubuntu-16-04-cloud-amd64", request.getVfModuleParams().get("vcpe_image_name"));
+ assertEquals("10.2.0.0/24", request.getVfModuleParams().get("cpe_public_net_cidr"));
+ assertEquals("", request.getVfModuleParams().get("workload_context"));
- }
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/NetworkInfoMapperTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/NetworkInfoMapperTest.java
index 90e15f8ba5..0af0efccd2 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/NetworkInfoMapperTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/NetworkInfoMapperTest.java
@@ -21,104 +21,101 @@
package org.onap.so.openstack.mappers;
import static org.junit.Assert.assertEquals;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
-
import org.javatuples.Pair;
import org.junit.Test;
import org.onap.so.openstack.beans.NetworkInfo;
import org.onap.so.openstack.beans.NetworkStatus;
-
import com.woorea.openstack.quantum.model.Network;
import com.woorea.openstack.quantum.model.Segment;
public class NetworkInfoMapperTest {
- @Test
- public void checkNetworkStatusMap() {
- NetworkInfoMapper mapper = new NetworkInfoMapper(new Network());
- assertEquals(NetworkStatus.ACTIVE, mapper.mapStatus("ACTIVE"));
- assertEquals(NetworkStatus.BUILD, mapper.mapStatus("BUILD"));
- assertEquals(NetworkStatus.ERROR, mapper.mapStatus("ERROR"));
- assertEquals(NetworkStatus.DOWN, mapper.mapStatus("DOWN"));
- assertEquals(NetworkStatus.UNKNOWN, mapper.mapStatus("NOT IN MAP"));
- assertEquals(NetworkStatus.UNKNOWN, mapper.mapStatus(null));
- }
-
- @Test
- public void checkLocateVlanInformationNoSegments() {
- Network network = new Network();
- network.setProviderPhysicalNetwork("test-physical-network");
- network.setProviderNetworkType("vlan");
- network.setProviderSegmentationId(2);
- NetworkInfoMapper mapper = new NetworkInfoMapper(network);
- NetworkInfo result = mapper.map();
- assertEquals("test-physical-network", result.getProvider());
- assertEquals(1, result.getVlans().size());
- assertEquals(2, result.getVlans().get(0).intValue());
- }
-
- @Test
- public void checkLocateVlanInformationSegments() {
- Network network = new Network();
- addSegments(network);
+ @Test
+ public void checkNetworkStatusMap() {
+ NetworkInfoMapper mapper = new NetworkInfoMapper(new Network());
+ assertEquals(NetworkStatus.ACTIVE, mapper.mapStatus("ACTIVE"));
+ assertEquals(NetworkStatus.BUILD, mapper.mapStatus("BUILD"));
+ assertEquals(NetworkStatus.ERROR, mapper.mapStatus("ERROR"));
+ assertEquals(NetworkStatus.DOWN, mapper.mapStatus("DOWN"));
+ assertEquals(NetworkStatus.UNKNOWN, mapper.mapStatus("NOT IN MAP"));
+ assertEquals(NetworkStatus.UNKNOWN, mapper.mapStatus(null));
+ }
+
+ @Test
+ public void checkLocateVlanInformationNoSegments() {
+ Network network = new Network();
+ network.setProviderPhysicalNetwork("test-physical-network");
+ network.setProviderNetworkType("vlan");
+ network.setProviderSegmentationId(2);
+ NetworkInfoMapper mapper = new NetworkInfoMapper(network);
+ NetworkInfo result = mapper.map();
+ assertEquals("test-physical-network", result.getProvider());
+ assertEquals(1, result.getVlans().size());
+ assertEquals(2, result.getVlans().get(0).intValue());
+ }
+
+ @Test
+ public void checkLocateVlanInformationSegments() {
+ Network network = new Network();
+ addSegments(network);
+
+ NetworkInfoMapper mapper = new NetworkInfoMapper(network);
+ NetworkInfo result = mapper.map();
+ assertEquals("type1", result.getProvider());
+ assertEquals(2, result.getVlans().size());
+ assertEquals(Arrays.asList(1, 2).toString(), result.getVlans().toString());
+ }
+
+ @Test
+ public void checkLocateVlanInformationSegmentsAndPhysical() {
+ Network network = new Network();
+ addSegments(network);
+ network.setProviderPhysicalNetwork("test-physical-network");
+ network.setProviderNetworkType("vlan");
+ network.setProviderSegmentationId(2);
+ NetworkInfoMapper mapper = new NetworkInfoMapper(network);
+ NetworkInfo result = mapper.map();
+ assertEquals("test-physical-network", result.getProvider());
+ assertEquals(1, result.getVlans().size());
+ assertEquals(2, result.getVlans().get(0).intValue());
+ }
+
+ @Test
+ public void nullNetwork() {
+ NetworkInfoMapper mapper = new NetworkInfoMapper(null);
+ assertEquals(NetworkStatus.NOTFOUND, mapper.map().getStatus());
+ }
+
+ @Test
+ public void mapFields() {
+ Network network = new Network();
+ network.setId("id");
+ network.setName("name");
+ network.setSubnets(Arrays.asList("string1", "string2"));
+ NetworkInfoMapper mapper = new NetworkInfoMapper(network);
+ NetworkInfo mapped = mapper.map();
+ assertEquals("name", mapped.getName());
+ assertEquals("id", mapped.getId());
+ assertEquals(network.getSubnets(), mapped.getSubnets());
+ }
- NetworkInfoMapper mapper = new NetworkInfoMapper(network);
- NetworkInfo result = mapper.map();
- assertEquals("type1", result.getProvider());
- assertEquals(2, result.getVlans().size());
- assertEquals(Arrays.asList(1, 2).toString(), result.getVlans().toString());
- }
-
- @Test
- public void checkLocateVlanInformationSegmentsAndPhysical() {
- Network network = new Network();
- addSegments(network);
- network.setProviderPhysicalNetwork("test-physical-network");
- network.setProviderNetworkType("vlan");
- network.setProviderSegmentationId(2);
- NetworkInfoMapper mapper = new NetworkInfoMapper(network);
- NetworkInfo result = mapper.map();
- assertEquals("test-physical-network", result.getProvider());
- assertEquals(1, result.getVlans().size());
- assertEquals(2, result.getVlans().get(0).intValue());
- }
-
- @Test
- public void nullNetwork() {
- NetworkInfoMapper mapper = new NetworkInfoMapper(null);
- assertEquals(NetworkStatus.NOTFOUND, mapper.map().getStatus());
- }
-
- @Test
- public void mapFields() {
- Network network = new Network();
- network.setId("id");
- network.setName("name");
- network.setSubnets(Arrays.asList("string1", "string2"));
- NetworkInfoMapper mapper = new NetworkInfoMapper(network);
- NetworkInfo mapped = mapper.map();
- assertEquals("name", mapped.getName());
- assertEquals("id", mapped.getId());
- assertEquals(network.getSubnets(), mapped.getSubnets());
- }
-
- private Network addSegments(Network network) {
- List<Segment> segments = new ArrayList<>();
- Segment segment1 = new Segment();
- segment1.setProviderPhysicalNetwork("type1");
- segment1.setProviderNetworkType("vlan");
- segment1.setProviderSegmentationId(1);
- segments.add(segment1);
- Segment segment2 = new Segment();
- segment2.setProviderPhysicalNetwork("type2");
- segment2.setProviderNetworkType("vlan");
- segment2.setProviderSegmentationId(2);
- segments.add(segment2);
- network.setSegments(segments);
- return network;
- }
+ private Network addSegments(Network network) {
+ List<Segment> segments = new ArrayList<>();
+ Segment segment1 = new Segment();
+ segment1.setProviderPhysicalNetwork("type1");
+ segment1.setProviderNetworkType("vlan");
+ segment1.setProviderSegmentationId(1);
+ segments.add(segment1);
+ Segment segment2 = new Segment();
+ segment2.setProviderPhysicalNetwork("type2");
+ segment2.setProviderNetworkType("vlan");
+ segment2.setProviderSegmentationId(2);
+ segments.add(segment2);
+ network.setSegments(segments);
+ return network;
+ }
}
diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/StackInfoMapperTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/StackInfoMapperTest.java
index f01745f8c1..4ca0186a82 100644
--- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/StackInfoMapperTest.java
+++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/StackInfoMapperTest.java
@@ -21,17 +21,14 @@
package org.onap.so.openstack.mappers;
import static org.junit.Assert.assertEquals;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Test;
import org.onap.so.openstack.beans.HeatStatus;
import org.onap.so.openstack.beans.StackInfo;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -39,56 +36,57 @@ import com.woorea.openstack.heat.model.Stack;
public class StackInfoMapperTest {
- private static final String PATH = "src/test/resources/";
- @Test
- public void nullStack() {
- StackInfoMapper mapper = new StackInfoMapper(null);
- assertEquals(HeatStatus.NOTFOUND, mapper.map().getStatus());
- }
-
- @Test
- public void checkHeatStatusMap() {
- StackInfoMapper mapper = new StackInfoMapper(null);
- assertEquals(HeatStatus.BUILDING, mapper.mapStatus("CREATE_IN_PROGRESS"));
- assertEquals(HeatStatus.CREATED, mapper.mapStatus("CREATE_COMPLETE"));
- assertEquals(HeatStatus.FAILED, mapper.mapStatus("CREATE_FAILED"));
- assertEquals(HeatStatus.DELETING, mapper.mapStatus("DELETE_IN_PROGRESS"));
- assertEquals(HeatStatus.NOTFOUND, mapper.mapStatus("DELETE_COMPLETE"));
- assertEquals(HeatStatus.FAILED, mapper.mapStatus("DELETE_FAILED"));
- assertEquals(HeatStatus.UPDATING, mapper.mapStatus("UPDATE_IN_PROGRESS"));
- assertEquals(HeatStatus.FAILED, mapper.mapStatus("UPDATE_FAILED"));
- assertEquals(HeatStatus.UPDATED, mapper.mapStatus("UPDATE_COMPLETE"));
- assertEquals(HeatStatus.INIT, mapper.mapStatus(null));
- assertEquals(HeatStatus.UNKNOWN, mapper.mapStatus("status-not-there"));
- }
-
- @Test
- public void checkOutputToMap() throws JsonParseException, JsonMappingException, IOException {
- ObjectMapper jacksonMapper = new ObjectMapper();
- Stack sample = jacksonMapper.readValue(this.getJson("stack-example.json"), Stack.class);
- StackInfoMapper mapper = new StackInfoMapper(sample);
- StackInfo result = mapper.map();
- Map<String, Object> map = result.getOutputs();
- assertEquals(true, map.containsKey("key2"));
- assertEquals("value1", map.get("key1"));
- }
-
- @Test
- public void mapRemainingFields() {
- Stack stack = new Stack();
- stack.setStackName("name");
- stack.setId("id");
- stack.setStackStatusReason("message");
- stack.setParameters(new HashMap<String, Object>());
- StackInfoMapper mapper = new StackInfoMapper(stack);
- StackInfo info = mapper.map();
- assertEquals("name", info.getName());
- assertEquals("name/id", info.getCanonicalName());
- assertEquals("message", info.getStatusMessage());
- assertEquals(stack.getParameters(), info.getParameters());
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get(PATH + filename)));
- }
+ private static final String PATH = "src/test/resources/";
+
+ @Test
+ public void nullStack() {
+ StackInfoMapper mapper = new StackInfoMapper(null);
+ assertEquals(HeatStatus.NOTFOUND, mapper.map().getStatus());
+ }
+
+ @Test
+ public void checkHeatStatusMap() {
+ StackInfoMapper mapper = new StackInfoMapper(null);
+ assertEquals(HeatStatus.BUILDING, mapper.mapStatus("CREATE_IN_PROGRESS"));
+ assertEquals(HeatStatus.CREATED, mapper.mapStatus("CREATE_COMPLETE"));
+ assertEquals(HeatStatus.FAILED, mapper.mapStatus("CREATE_FAILED"));
+ assertEquals(HeatStatus.DELETING, mapper.mapStatus("DELETE_IN_PROGRESS"));
+ assertEquals(HeatStatus.NOTFOUND, mapper.mapStatus("DELETE_COMPLETE"));
+ assertEquals(HeatStatus.FAILED, mapper.mapStatus("DELETE_FAILED"));
+ assertEquals(HeatStatus.UPDATING, mapper.mapStatus("UPDATE_IN_PROGRESS"));
+ assertEquals(HeatStatus.FAILED, mapper.mapStatus("UPDATE_FAILED"));
+ assertEquals(HeatStatus.UPDATED, mapper.mapStatus("UPDATE_COMPLETE"));
+ assertEquals(HeatStatus.INIT, mapper.mapStatus(null));
+ assertEquals(HeatStatus.UNKNOWN, mapper.mapStatus("status-not-there"));
+ }
+
+ @Test
+ public void checkOutputToMap() throws JsonParseException, JsonMappingException, IOException {
+ ObjectMapper jacksonMapper = new ObjectMapper();
+ Stack sample = jacksonMapper.readValue(this.getJson("stack-example.json"), Stack.class);
+ StackInfoMapper mapper = new StackInfoMapper(sample);
+ StackInfo result = mapper.map();
+ Map<String, Object> map = result.getOutputs();
+ assertEquals(true, map.containsKey("key2"));
+ assertEquals("value1", map.get("key1"));
+ }
+
+ @Test
+ public void mapRemainingFields() {
+ Stack stack = new Stack();
+ stack.setStackName("name");
+ stack.setId("id");
+ stack.setStackStatusReason("message");
+ stack.setParameters(new HashMap<String, Object>());
+ StackInfoMapper mapper = new StackInfoMapper(stack);
+ StackInfo info = mapper.map();
+ assertEquals("name", info.getName());
+ assertEquals("name/id", info.getCanonicalName());
+ assertEquals("message", info.getStatusMessage());
+ assertEquals(stack.getParameters(), info.getParameters());
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(PATH + filename)));
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/db/migration/CloudConfig.java b/adapters/mso-catalog-db-adapter/src/main/java/db/migration/CloudConfig.java
index 82139f21af..6a0bec5f08 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/db/migration/CloudConfig.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/db/migration/CloudConfig.java
@@ -25,13 +25,12 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.db.catalog.beans.CloudSite;
import org.onap.so.db.catalog.beans.CloudifyManager;
-
import java.util.HashMap;
import java.util.Map;
/**
- * @deprecated
- * This class is introduced as deprecated as its only purpose is for migration of cloud config data. It shouldnt be used elsewhere.
+ * @deprecated This class is introduced as deprecated as its only purpose is for migration of cloud config data. It
+ * shouldnt be used elsewhere.
*/
@Deprecated
@@ -71,12 +70,12 @@ public class CloudConfig {
this.cloudifyManagers = cloudifyManagers;
}
- public void populateId(){
+ public void populateId() {
for (Map.Entry<String, CloudIdentity> entry : identityServices.entrySet()) {
entry.getValue().setId(entry.getKey());
}
- for (Map.Entry <String, CloudSite> entry : cloudSites.entrySet()) {
+ for (Map.Entry<String, CloudSite> entry : cloudSites.entrySet()) {
entry.getValue().setId(entry.getKey());
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/db/migration/R__CloudConfigMigration.java b/adapters/mso-catalog-db-adapter/src/main/java/db/migration/R__CloudConfigMigration.java
index c20acaf967..053c6da1cb 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/db/migration/R__CloudConfigMigration.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/db/migration/R__CloudConfigMigration.java
@@ -35,7 +35,6 @@ import org.onap.so.db.catalog.beans.CloudSite;
import org.onap.so.db.catalog.beans.CloudifyManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -48,56 +47,57 @@ import java.sql.Statement;
import java.util.Collection;
/**
- * Performs migration using JDBC Connection from the cloud config provided in the environment (application-{profile}.yaml) and persist data (when not already present) to the catalod database.
+ * Performs migration using JDBC Connection from the cloud config provided in the environment
+ * (application-{profile}.yaml) and persist data (when not already present) to the catalod database.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
-public class R__CloudConfigMigration implements JdbcMigration , MigrationInfoProvider, MigrationChecksumProvider {
+public class R__CloudConfigMigration implements JdbcMigration, MigrationInfoProvider, MigrationChecksumProvider {
public static final String FLYWAY = "FLYWAY";
private static final Logger logger = LoggerFactory.getLogger(R__CloudConfigMigration.class);
@JsonProperty("cloud_config")
private CloudConfig cloudConfig;
-
+
@Override
- public boolean isUndo(){
- return false;
+ public boolean isUndo() {
+ return false;
}
@Override
public void migrate(Connection connection) throws Exception {
logger.debug("Starting migration for CloudConfig");
-
+
CloudConfig cloudConfig = null;
-
+
String tableQuery = "SELECT * FROM identity_services";
int totalRetries = 20;
boolean tableExists = false;
int count = 1;
- while(!tableExists && count != totalRetries) {
- try(Statement stmt = connection.createStatement();) {
- stmt.executeQuery(tableQuery);
- tableExists = true;
+ while (!tableExists && count != totalRetries) {
+ try (Statement stmt = connection.createStatement();) {
+ stmt.executeQuery(tableQuery);
+ tableExists = true;
} catch (SQLException e) {
- count++;
- // Wait 5 mintues
- Thread.sleep(300000);
+ count++;
+ // Wait 5 mintues
+ Thread.sleep(300000);
}
}
-
+
// Try the override file
String configLocation = System.getProperty("spring.config.additional-location");
if (configLocation != null) {
try (InputStream stream = new FileInputStream(Paths.get(configLocation).normalize().toString())) {
cloudConfig = loadCloudConfig(stream);
- }catch(Exception e){
+ } catch (Exception e) {
logger.warn("Error Loading override.yaml", e);
- }
+ }
}
-
+
if (cloudConfig == null) {
logger.debug("No CloudConfig defined in {}", configLocation);
- // Try the application.yaml file
+ // Try the application.yaml file
try (InputStream stream = R__CloudConfigMigration.class.getResourceAsStream(getApplicationYamlName())) {
cloudConfig = loadCloudConfig(stream);
}
@@ -106,8 +106,8 @@ public class R__CloudConfigMigration implements JdbcMigration , MigrationInfoPro
logger.debug("No CloudConfig defined in {}", getApplicationYamlName());
}
}
-
- if(cloudConfig != null){
+
+ if (cloudConfig != null) {
migrateCloudIdentity(cloudConfig.getIdentityServices().values(), connection);
migrateCloudSite(cloudConfig.getCloudSites().values(), connection);
migrateCloudifyManagers(cloudConfig.getCloudifyManagers().values(), connection);
@@ -122,32 +122,35 @@ public class R__CloudConfigMigration implements JdbcMigration , MigrationInfoPro
this.cloudConfig = cloudConfig;
}
- private CloudConfig loadCloudConfig(InputStream stream) throws IOException {
- ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
- R__CloudConfigMigration cloudConfigMigration =
- mapper.readValue(stream, R__CloudConfigMigration.class);
+ private CloudConfig loadCloudConfig(InputStream stream) throws IOException {
+ ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
+ R__CloudConfigMigration cloudConfigMigration = mapper.readValue(stream, R__CloudConfigMigration.class);
CloudConfig cloudConfig = cloudConfigMigration.getCloudConfig();
- if(cloudConfig != null){
- cloudConfig.populateId();
+ if (cloudConfig != null) {
+ cloudConfig.populateId();
}
return cloudConfig;
}
private String getApplicationYamlName() {
- String profile = System.getProperty("spring.profiles.active") == null ? "" : "-" + System.getProperty("spring.profiles.active");
+ String profile = System.getProperty("spring.profiles.active") == null ? ""
+ : "-" + System.getProperty("spring.profiles.active");
return "/application" + profile + ".yaml";
}
- private void migrateCloudIdentity(Collection<CloudIdentity> entities, Connection connection) throws SQLException {
+ private void migrateCloudIdentity(Collection<CloudIdentity> entities, Connection connection) throws SQLException {
logger.debug("Starting migration for CloudConfig-->IdentityService");
- String insert = "INSERT INTO `identity_services` (`ID`, `IDENTITY_URL`, `MSO_ID`, `MSO_PASS`, `ADMIN_TENANT`, `MEMBER_ROLE`, `TENANT_METADATA`, `IDENTITY_SERVER_TYPE`, `IDENTITY_AUTHENTICATION_TYPE`, `LAST_UPDATED_BY`) " +
- "VALUES (?,?,?,?,?,?,?,?,?,?);";
+ String insert =
+ "INSERT INTO `identity_services` (`ID`, `IDENTITY_URL`, `MSO_ID`, `MSO_PASS`, `ADMIN_TENANT`, `MEMBER_ROLE`, `TENANT_METADATA`, `IDENTITY_SERVER_TYPE`, `IDENTITY_AUTHENTICATION_TYPE`, `LAST_UPDATED_BY`) "
+ + "VALUES (?,?,?,?,?,?,?,?,?,?);";
- try (Statement stmt = connection.createStatement();PreparedStatement ps = connection.prepareStatement(insert)) {
+ try (Statement stmt = connection.createStatement();
+ PreparedStatement ps = connection.prepareStatement(insert)) {
for (CloudIdentity cloudIdentity : entities) {
- try (ResultSet rows = stmt.executeQuery("Select count(1) from identity_services where id='" + cloudIdentity.getId() + "'")) {
+ try (ResultSet rows = stmt.executeQuery(
+ "Select count(1) from identity_services where id='" + cloudIdentity.getId() + "'")) {
int count = 0;
while (rows.next()) {
count = rows.getInt(1);
@@ -160,8 +163,14 @@ public class R__CloudConfigMigration implements JdbcMigration , MigrationInfoPro
ps.setString(5, cloudIdentity.getAdminTenant());
ps.setString(6, cloudIdentity.getMemberRole());
ps.setBoolean(7, cloudIdentity.getTenantMetadata());
- ps.setString(8, cloudIdentity.getIdentityServerType() != null ? cloudIdentity.getIdentityServerType().name() : null);
- ps.setString(9, cloudIdentity.getIdentityAuthenticationType() != null ? cloudIdentity.getIdentityAuthenticationType().name() : null);
+ ps.setString(8,
+ cloudIdentity.getIdentityServerType() != null
+ ? cloudIdentity.getIdentityServerType().name()
+ : null);
+ ps.setString(9,
+ cloudIdentity.getIdentityAuthenticationType() != null
+ ? cloudIdentity.getIdentityAuthenticationType().name()
+ : null);
ps.setString(10, FLYWAY);
ps.executeUpdate();
}
@@ -170,14 +179,17 @@ public class R__CloudConfigMigration implements JdbcMigration , MigrationInfoPro
}
}
- private void migrateCloudSite(Collection<CloudSite> entities, Connection connection) throws SQLException {
+ private void migrateCloudSite(Collection<CloudSite> entities, Connection connection) throws SQLException {
logger.debug("Starting migration for CloudConfig-->CloudSite");
- String insert = "INSERT INTO `cloud_sites` (`ID`, `REGION_ID`, `IDENTITY_SERVICE_ID`, `CLOUD_VERSION`, `CLLI`, `CLOUDIFY_ID`, `PLATFORM`, `ORCHESTRATOR`, `LAST_UPDATED_BY`) " +
- "VALUES (?,?,?,?,?,?,?,?,?);";
+ String insert =
+ "INSERT INTO `cloud_sites` (`ID`, `REGION_ID`, `IDENTITY_SERVICE_ID`, `CLOUD_VERSION`, `CLLI`, `CLOUDIFY_ID`, `PLATFORM`, `ORCHESTRATOR`, `LAST_UPDATED_BY`) "
+ + "VALUES (?,?,?,?,?,?,?,?,?);";
- try (Statement stmt = connection.createStatement();PreparedStatement ps = connection.prepareStatement(insert)) {
+ try (Statement stmt = connection.createStatement();
+ PreparedStatement ps = connection.prepareStatement(insert)) {
for (CloudSite cloudSite : entities) {
- try (ResultSet rows = stmt.executeQuery("Select count(1) from cloud_sites where id='" + cloudSite.getId() + "'")) {
+ try (ResultSet rows =
+ stmt.executeQuery("Select count(1) from cloud_sites where id='" + cloudSite.getId() + "'")) {
int count = 0;
while (rows.next()) {
count = rows.getInt(1);
@@ -199,13 +211,17 @@ public class R__CloudConfigMigration implements JdbcMigration , MigrationInfoPro
}
}
- private void migrateCloudifyManagers(Collection<CloudifyManager> entities, Connection connection) throws SQLException {
- String insert = "INSERT INTO `cloudify_managers` (`ID`, `CLOUDIFY_URL`, `USERNAME`, `PASSWORD`, `VERSION`, `LAST_UPDATED_BY`)" +
- " VALUES (?,?,?,?,?,?);";
+ private void migrateCloudifyManagers(Collection<CloudifyManager> entities, Connection connection)
+ throws SQLException {
+ String insert =
+ "INSERT INTO `cloudify_managers` (`ID`, `CLOUDIFY_URL`, `USERNAME`, `PASSWORD`, `VERSION`, `LAST_UPDATED_BY`)"
+ + " VALUES (?,?,?,?,?,?);";
- try (Statement stmt = connection.createStatement();PreparedStatement ps = connection.prepareStatement(insert)) {
+ try (Statement stmt = connection.createStatement();
+ PreparedStatement ps = connection.prepareStatement(insert)) {
for (CloudifyManager cloudifyManager : entities) {
- try (ResultSet rows = stmt.executeQuery("Select count(1) from cloudify_managers where id='" + cloudifyManager.getId() + "'")) {
+ try (ResultSet rows = stmt.executeQuery(
+ "Select count(1) from cloudify_managers where id='" + cloudifyManager.getId() + "'")) {
int count = 0;
while (rows.next()) {
count = rows.getInt(1);
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDBApplication.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDBApplication.java
index 374e597116..a0a0756d3d 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDBApplication.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDBApplication.java
@@ -25,23 +25,25 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
-@SpringBootApplication(scanBasePackages = {"org.onap.so.adapters.catalogdb", "org.onap.so.db.catalog.client","org.onap.so.logging.jaxrs.filter","org.onap.so.logging.spring.interceptor","org.onap.so.client","org.onap.so.configuration"})
+@SpringBootApplication(scanBasePackages = {"org.onap.so.adapters.catalogdb", "org.onap.so.db.catalog.client",
+ "org.onap.so.logging.jaxrs.filter", "org.onap.so.logging.spring.interceptor", "org.onap.so.client",
+ "org.onap.so.configuration"})
@EnableJpaRepositories("org.onap.so.db.catalog.data.repository")
@EntityScan("org.onap.so.db.catalog.beans")
public class CatalogDBApplication {
-
- private static final String LOGS_DIR = "logs_dir";
- private static void setLogsDir() {
- if (System.getProperty(LOGS_DIR) == null) {
- System.getProperties().setProperty(LOGS_DIR, "./logs/catdb/");
- }
- }
-
+ private static final String LOGS_DIR = "logs_dir";
+
+ private static void setLogsDir() {
+ if (System.getProperty(LOGS_DIR) == null) {
+ System.getProperties().setProperty(LOGS_DIR, "./logs/catdb/");
+ }
+ }
+
public static void main(String[] args) {
SpringApplication.run(CatalogDBApplication.class, args);
System.getProperties().setProperty("mso.db", "MARIADB");
- System.getProperties().setProperty("server.name", "Springboot");
+ System.getProperties().setProperty("server.name", "Springboot");
setLogsDir();
}
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDbRepositoryConfiguration.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDbRepositoryConfiguration.java
index 3906762e60..fdec7cf5d6 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDbRepositoryConfiguration.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDbRepositoryConfiguration.java
@@ -21,9 +21,7 @@
package org.onap.so.adapters.catalogdb;
import java.util.stream.Collectors;
-
import javax.persistence.EntityManager;
-
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
@@ -32,12 +30,13 @@ import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapt
@Configuration
public class CatalogDbRepositoryConfiguration extends RepositoryRestConfigurerAdapter {
- @Autowired
- private EntityManager entityManager;
+ @Autowired
+ private EntityManager entityManager;
- @Override
- public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
- config.exposeIdsFor(entityManager.getMetamodel().getEntities().stream().map(e -> e.getJavaType()).collect(Collectors.toList()).toArray(new Class[0]));
- }
+ @Override
+ public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
+ config.exposeIdsFor(entityManager.getMetamodel().getEntities().stream().map(e -> e.getJavaType())
+ .collect(Collectors.toList()).toArray(new Class[0]));
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java
index ff162c862e..db73d4afec 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java
@@ -22,12 +22,10 @@ package org.onap.so.adapters.catalogdb;
import javax.annotation.PostConstruct;
import javax.ws.rs.ApplicationPath;
-
import org.glassfish.jersey.server.ResourceConfig;
import org.onap.so.adapters.catalogdb.rest.CatalogDbAdapterRest;
import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging;
import org.springframework.context.annotation.Configuration;
-
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
@@ -36,20 +34,20 @@ import io.swagger.jaxrs.listing.SwaggerSerializers;
@ApplicationPath("/ecomp/mso/catalog")
public class JerseyConfiguration extends ResourceConfig {
- @PostConstruct
- public void setUp() {
- register(CatalogDbAdapterRest.class);
- register(ApiListingResource.class);
- register(SwaggerSerializers.class);
- register(JaxRsFilterLogging.class);
- BeanConfig beanConfig = new BeanConfig();
- beanConfig.setVersion("1.0.2");
- beanConfig.setSchemes(new String[]{"http"});
- beanConfig.setHost("localhost:8080");
- beanConfig.setBasePath("/ecomp/mso/catalog");
- beanConfig.setResourcePackage("org.onap.so.adapters.catalogdb");
- beanConfig.setPrettyPrint(true);
- beanConfig.setScan(true);
- }
+ @PostConstruct
+ public void setUp() {
+ register(CatalogDbAdapterRest.class);
+ register(ApiListingResource.class);
+ register(SwaggerSerializers.class);
+ register(JaxRsFilterLogging.class);
+ BeanConfig beanConfig = new BeanConfig();
+ beanConfig.setVersion("1.0.2");
+ beanConfig.setSchemes(new String[] {"http"});
+ beanConfig.setHost("localhost:8080");
+ beanConfig.setBasePath("/ecomp/mso/catalog");
+ beanConfig.setResourcePackage("org.onap.so.adapters.catalogdb");
+ beanConfig.setPrettyPrint(true);
+ beanConfig.setScan(true);
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebMvcConfig.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebMvcConfig.java
index efe6010f23..4dabb58f7d 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebMvcConfig.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebMvcConfig.java
@@ -36,7 +36,7 @@ public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public MappedInterceptor mappedLoggingInterceptor() {
- return new MappedInterceptor(new String[]{"/**"}, loggingInterceptor);
+ return new MappedInterceptor(new String[] {"/**"}, loggingInterceptor);
}
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebSecurityConfigImpl.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebSecurityConfigImpl.java
index 2eb4858803..1d58975e6b 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebSecurityConfigImpl.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebSecurityConfigImpl.java
@@ -33,21 +33,18 @@ import org.springframework.util.StringUtils;
@EnableWebSecurity
public class WebSecurityConfigImpl extends WebSecurityConfig {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf().disable()
- .authorizeRequests()
- .antMatchers("/manage/health","/manage/info").permitAll()
- .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),","))
- .and()
- .httpBasic();
- }
-
- @Override
- public void configure(WebSecurity web) throws Exception {
- super.configure(web);
- StrictHttpFirewall firewall = new MSOSpringFirewall();
- web.httpFirewall(firewall);
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll()
+ .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and()
+ .httpBasic();
+ }
+
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ super.configure(web);
+ StrictHttpFirewall firewall = new MSOSpringFirewall();
+ web.httpFirewall(firewall);
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQuery.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQuery.java
index cc1b3ddb17..edec48dc95 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQuery.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQuery.java
@@ -29,68 +29,70 @@ import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class CatalogQuery {
- protected static Logger logger = LoggerFactory.getLogger(CatalogQuery.class);
- private static final boolean IS_EMBED = true;
+ protected static Logger logger = LoggerFactory.getLogger(CatalogQuery.class);
+ private static final boolean IS_EMBED = true;
- public abstract String JSON2(boolean isArray, boolean isEmbed);
+ public abstract String JSON2(boolean isArray, boolean isEmbed);
- protected void put(Map<String, String> valueMap, String key, String value) {
- valueMap.put(key, value == null? "null": '"'+ value+ '"');
- }
+ protected void put(Map<String, String> valueMap, String key, String value) {
+ valueMap.put(key, value == null ? "null" : '"' + value + '"');
+ }
- protected void put(Map<String, String> valueMap, String key, Integer value) {
- valueMap.put(key, value == null? "null": value.toString());
- }
+ protected void put(Map<String, String> valueMap, String key, Integer value) {
+ valueMap.put(key, value == null ? "null" : value.toString());
+ }
- protected void put(Map<String, String> valueMap, String key, Boolean value) {
- valueMap.put(key, value == null? "null": value? "true": "false");
- }
+ protected void put(Map<String, String> valueMap, String key, Boolean value) {
+ valueMap.put(key, value == null ? "null" : value ? "true" : "false");
+ }
- protected String setTemplate(String template, Map<String, String> valueMap) {
- StringBuffer result = new StringBuffer();
+ protected String setTemplate(String template, Map<String, String> valueMap) {
+ StringBuffer result = new StringBuffer();
- String pattern = "<.*>";
- Pattern r = Pattern.compile(pattern);
- Matcher m = r.matcher(template);
+ String pattern = "<.*>";
+ Pattern r = Pattern.compile(pattern);
+ Matcher m = r.matcher(template);
- logger.debug("CatalogQuery template: {}", template);
- while (m.find()) {
- String key = template.substring(m.start() + 1, m.end() - 1);
- logger.debug("CatalogQuery key: {} contains key? {}", key , valueMap.containsKey(key));
- m.appendReplacement(result, Matcher.quoteReplacement(valueMap.getOrDefault(key, "\"TBD\"")));
- }
- m.appendTail(result);
- logger.debug("CatalogQuery return: {}", result.toString());
- return result.toString();
- }
+ logger.debug("CatalogQuery template: {}", template);
+ while (m.find()) {
+ String key = template.substring(m.start() + 1, m.end() - 1);
+ logger.debug("CatalogQuery key: {} contains key? {}", key, valueMap.containsKey(key));
+ m.appendReplacement(result, Matcher.quoteReplacement(valueMap.getOrDefault(key, "\"TBD\"")));
+ }
+ m.appendTail(result);
+ logger.debug("CatalogQuery return: {}", result.toString());
+ return result.toString();
+ }
- /**
- * The simple, clean, generic way to handle the interface
- */
- protected String smartToJSON() {
- String jsonString = null;
- try {
- ObjectMapper mapper = new ObjectMapper();
- jsonString = mapper.writeValueAsString(this);
- }
- catch (Exception e) {
- logger.error("Error converting to JSON" , e);
- jsonString = "invalid"; //throws instead?
- }
- return jsonString;
- }
+ /**
+ * The simple, clean, generic way to handle the interface
+ */
+ protected String smartToJSON() {
+ String jsonString = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ jsonString = mapper.writeValueAsString(this);
+ } catch (Exception e) {
+ logger.error("Error converting to JSON", e);
+ jsonString = "invalid"; // throws instead?
+ }
+ return jsonString;
+ }
- public String toJsonString(String version, boolean isArray) {
- switch(version) {
- case "v1": return smartToJSON();
- case "v2": return JSON2(isArray, !IS_EMBED);
- default:
- return "invalid version: "+ version;
- }
- }
- @Override
- public String toString(){
- return smartToJSON();
-
- }
+ public String toJsonString(String version, boolean isArray) {
+ switch (version) {
+ case "v1":
+ return smartToJSON();
+ case "v2":
+ return JSON2(isArray, !IS_EMBED);
+ default:
+ return "invalid version: " + version;
+ }
+ }
+
+ @Override
+ public String toString() {
+ return smartToJSON();
+
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryException.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryException.java
index 890347344c..f47c9006c6 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryException.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryException.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters.catalogdb.catalogrest;
import java.io.Serializable;
-
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "catalogQueryException")
@@ -29,30 +28,46 @@ public class CatalogQueryException extends CatalogQueryExceptionCommon implement
private static final long serialVersionUID = -9062290006520066109L;
private String message;
- private CatalogQueryExceptionCategory category;
- private Boolean rolledBack;
+ private CatalogQueryExceptionCategory category;
+ private Boolean rolledBack;
+
+ public CatalogQueryException() {}
+
+ public CatalogQueryException(String message) {
+ this.message = message;
+ }
+
+ public CatalogQueryException(String message, CatalogQueryExceptionCategory category, boolean rolledBack,
+ String messageid) {
+ super(messageid);
+ this.message = message;
+ this.category = category;
+ this.rolledBack = rolledBack;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public CatalogQueryException () {}
+ public CatalogQueryExceptionCategory getCategory() {
+ return category;
+ }
- public CatalogQueryException (String message) {
- this.message = message;
- }
+ public void setCategory(CatalogQueryExceptionCategory category) {
+ this.category = category;
+ }
- public CatalogQueryException (String message, CatalogQueryExceptionCategory category, boolean rolledBack, String messageid) {
- super(messageid);
- this.message = message;
- this.category = category;
- this.rolledBack = rolledBack;
- }
+ public Boolean getRolledBack() {
+ return rolledBack;
+ }
- public String getMessage() { return message; }
- public void setMessage(String message) { this.message = message; }
+ public void setRolledBack(Boolean rolledBack) {
+ this.rolledBack = rolledBack;
+ }
- public CatalogQueryExceptionCategory getCategory () { return category; }
- public void setCategory (CatalogQueryExceptionCategory category) { this.category = category; }
- public Boolean getRolledBack() { return rolledBack; }
- public void setRolledBack(Boolean rolledBack) { this.rolledBack = rolledBack; }
-
-
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionCategory.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionCategory.java
index 687cc7d3e0..d22c865555 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionCategory.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionCategory.java
@@ -20,4 +20,6 @@
package org.onap.so.adapters.catalogdb.catalogrest;
-public enum CatalogQueryExceptionCategory { OPENSTACK, IO, INTERNAL, USERDATA }
+public enum CatalogQueryExceptionCategory {
+ OPENSTACK, IO, INTERNAL, USERDATA
+}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionCommon.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionCommon.java
index 283fef1d3b..324ac073a8 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionCommon.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionCommon.java
@@ -24,54 +24,62 @@
package org.onap.so.adapters.catalogdb.catalogrest;
import java.io.ByteArrayOutputStream;
-
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public abstract class CatalogQueryExceptionCommon {
- private String messageId;
- protected static Logger logger = LoggerFactory.getLogger(CatalogQueryExceptionCommon.class);
+ private String messageId;
+ protected static Logger logger = LoggerFactory.getLogger(CatalogQueryExceptionCommon.class);
+
+ public CatalogQueryExceptionCommon() {
+ messageId = null;
+ }
+
+ public CatalogQueryExceptionCommon(String messageId) {
+ this.messageId = messageId;
+ }
+
+ public String getMessageId() {
+ return messageId;
+ }
- public CatalogQueryExceptionCommon() { messageId = null; }
- public CatalogQueryExceptionCommon(String messageId) { this.messageId = messageId; }
+ public void setMessageId(String messageId) {
+ this.messageId = messageId;
+ }
- public String getMessageId() { return messageId; }
- public void setMessageId(String messageId) { this.messageId = messageId; }
+ public String toJsonString() {
+ try {
+ String jsonString;
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ jsonString = mapper.writeValueAsString(this);
+ return jsonString;
+ } catch (Exception e) {
+ logger.error("Exception:", e);
+ return "";
+ }
+ }
- public String toJsonString() {
- try {
- String jsonString;
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- jsonString = mapper.writeValueAsString(this);
- return jsonString;
- } catch (Exception e) {
- logger.error ("Exception:", e);
- return "";
- }
- }
+ public String toXmlString() {
+ try {
+ ByteArrayOutputStream bs = new ByteArrayOutputStream();
+ JAXBContext context = JAXBContext.newInstance(this.getClass());
+ Marshaller marshaller = context.createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // pretty print XML
+ marshaller.marshal(this, bs);
+ return bs.toString();
+ } catch (Exception e) {
+ logger.error("Exception:", e);
+ return "";
+ }
+ }
- public String toXmlString() {
- try {
- ByteArrayOutputStream bs = new ByteArrayOutputStream();
- JAXBContext context = JAXBContext.newInstance(this.getClass());
- Marshaller marshaller = context.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //pretty print XML
- marshaller.marshal(this, bs);
- return bs.toString();
- } catch (Exception e) {
- logger.error ("Exception:", e);
- return "";
- }
- }
-
- @Override
- public String toString(){
- return toJsonString();
- }
+ @Override
+ public String toString() {
+ return toJsonString();
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryAllottedResourceCustomization.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryAllottedResourceCustomization.java
index 859666f446..e550394931 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryAllottedResourceCustomization.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryAllottedResourceCustomization.java
@@ -32,116 +32,113 @@ import org.slf4j.LoggerFactory;
@XmlRootElement(name = "serviceAllottedResources")
public class QueryAllottedResourceCustomization extends CatalogQuery {
protected static Logger logger = LoggerFactory.getLogger(QueryAllottedResourceCustomization.class);
- private List<AllottedResourceCustomization> allottedResourceCustomization;
- private static final String TEMPLATE =
- "\t{\n"+
- "\t\t\"modelInfo\" : {\n"+
- "\t\t\t\"modelName\" : <MODEL_NAME>,\n"+
- "\t\t\t\"modelUuid\" : <MODEL_UUID>,\n"+
- "\t\t\t\"modelInvariantUuid\" : <MODEL_INVARIANT_ID>,\n"+
- "\t\t\t\"modelVersion\" : <MODEL_VERSION>,\n"+
- "\t\t\t\"modelCustomizationUuid\" : <MODEL_CUSTOMIZATION_UUID>,\n"+
- "\t\t\t\"modelInstanceName\" : <MODEL_INSTANCE_NAME>\n"+
- "\t\t},\n"+
- "\t\t\"toscaNodeType\" : <TOSCA_NODE_TYPE>,\n"+
- "\t\t\"allottedResourceType\" : <ALLOTTED_RESOURCE_TYPE>,\n"+
- "\t\t\"allottedResourceRole\" : <ALLOTTED_RESOURCE_ROLE>,\n"+
- "\t\t\"providingServiceModelName\" : <PROVIDING_SERVICE_MODEL_NAME>,\n"+
- "\t\t\"providingServiceModelInvariantUuid\" : <PROVIDING_SERVICE_MODEL_INVARIANT_UUID>,\n"+
- "\t\t\"providingServiceModelUuid\" : <PROVIDING_SERVICE_MODEL_UUID>,\n"+
- "\t\t\"nfFunction\" : <NF_FUNCTION>,\n"+
- "\t\t\"nfType\" : <NF_TYPE>,\n"+
- "\t\t\"nfRole\" : <NF_ROLE>,\n"+
- "\t\t\"nfNamingCode\" : <NF_NAMING_CODE>,\n"+
- "\t\t\"resourceInput\" : <RESOURCE_INPUT>\n"+
- "\t}";
-
- public QueryAllottedResourceCustomization() {
- super();
- allottedResourceCustomization = new ArrayList<>();
- }
-
- public QueryAllottedResourceCustomization(List<AllottedResourceCustomization> vlist) {
- allottedResourceCustomization = vlist;
- }
-
- public List<AllottedResourceCustomization> getServiceAllottedResources(){
- return this.allottedResourceCustomization;
- }
-
- public void setServiceAllottedResources(List<AllottedResourceCustomization> v) {
- this.allottedResourceCustomization = v;
- }
-
- @Override
- public String toString () {
- StringBuilder sb = new StringBuilder();
-
- boolean first = true;
- int i = 1;
- for (AllottedResourceCustomization o : allottedResourceCustomization) {
- sb.append(i).append("\t");
- if (!first)
- sb.append("\n");
-
- first = false;
- sb.append(o);
- }
- return sb.toString();
+ private List<AllottedResourceCustomization> allottedResourceCustomization;
+ private static final String TEMPLATE =
+ "\t{\n" + "\t\t\"modelInfo\" : {\n" + "\t\t\t\"modelName\" : <MODEL_NAME>,\n"
+ + "\t\t\t\"modelUuid\" : <MODEL_UUID>,\n"
+ + "\t\t\t\"modelInvariantUuid\" : <MODEL_INVARIANT_ID>,\n"
+ + "\t\t\t\"modelVersion\" : <MODEL_VERSION>,\n"
+ + "\t\t\t\"modelCustomizationUuid\" : <MODEL_CUSTOMIZATION_UUID>,\n"
+ + "\t\t\t\"modelInstanceName\" : <MODEL_INSTANCE_NAME>\n" + "\t\t},\n"
+ + "\t\t\"toscaNodeType\" : <TOSCA_NODE_TYPE>,\n"
+ + "\t\t\"allottedResourceType\" : <ALLOTTED_RESOURCE_TYPE>,\n"
+ + "\t\t\"allottedResourceRole\" : <ALLOTTED_RESOURCE_ROLE>,\n"
+ + "\t\t\"providingServiceModelName\" : <PROVIDING_SERVICE_MODEL_NAME>,\n"
+ + "\t\t\"providingServiceModelInvariantUuid\" : <PROVIDING_SERVICE_MODEL_INVARIANT_UUID>,\n"
+ + "\t\t\"providingServiceModelUuid\" : <PROVIDING_SERVICE_MODEL_UUID>,\n"
+ + "\t\t\"nfFunction\" : <NF_FUNCTION>,\n"
+ + "\t\t\"nfType\" : <NF_TYPE>,\n"
+ + "\t\t\"nfRole\" : <NF_ROLE>,\n"
+ + "\t\t\"nfNamingCode\" : <NF_NAMING_CODE>,\n"
+ + "\t\t\"resourceInput\" : <RESOURCE_INPUT>\n" + "\t}";
+
+ public QueryAllottedResourceCustomization() {
+ super();
+ allottedResourceCustomization = new ArrayList<>();
+ }
+
+ public QueryAllottedResourceCustomization(List<AllottedResourceCustomization> vlist) {
+ allottedResourceCustomization = vlist;
+ }
+
+ public List<AllottedResourceCustomization> getServiceAllottedResources() {
+ return this.allottedResourceCustomization;
+ }
+
+ public void setServiceAllottedResources(List<AllottedResourceCustomization> v) {
+ this.allottedResourceCustomization = v;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+
+ boolean first = true;
+ int i = 1;
+ for (AllottedResourceCustomization o : allottedResourceCustomization) {
+ sb.append(i).append("\t");
+ if (!first)
+ sb.append("\n");
+
+ first = false;
+ sb.append(o);
+ }
+ return sb.toString();
}
- @Override
- public String JSON2(boolean isArray, boolean isEmbed) {
- StringBuilder sb = new StringBuilder();
- if (!isEmbed && isArray)
- sb.append("{ ");
- if (isArray)
- sb.append("\"serviceAllottedResources\": [");
- Map<String, String> valueMap = new HashMap<>();
- String sep = "";
- boolean first = true;
-
- if (this.allottedResourceCustomization != null) {
- for (AllottedResourceCustomization o : allottedResourceCustomization) {
- if (first)
- sb.append("\n");
-
- first = false;
-
- boolean arNull = o.getAllottedResource() == null ? true : false;
-
- put(valueMap, "MODEL_NAME", arNull ? null : o.getAllottedResource().getModelName());
- put(valueMap, "MODEL_UUID", arNull ? null : o.getAllottedResource().getModelUUID());
- put(valueMap, "MODEL_INVARIANT_ID", arNull ? null : o.getAllottedResource().getModelInvariantUUID());
- put(valueMap, "MODEL_VERSION", arNull ? null : o.getAllottedResource().getModelVersion());
- put(valueMap, "MODEL_CUSTOMIZATION_UUID", o.getModelCustomizationUUID());
- put(valueMap, "MODEL_INSTANCE_NAME", o.getModelInstanceName());
- put(valueMap, "TOSCA_NODE_TYPE", arNull ? null : o.getAllottedResource().getToscaNodeType());
- put(valueMap, "ALLOTTED_RESOURCE_TYPE", arNull ? null : o.getAllottedResource().getSubcategory());
- put(valueMap, "ALLOTTED_RESOURCE_ROLE", o.getTargetNetworkRole() != null ? o.getTargetNetworkRole() : o.getNfRole());
- put(valueMap, "NF_TYPE", o.getNfType());
- put(valueMap, "NF_ROLE", o.getNfRole());
- put(valueMap, "NF_FUNCTION", o.getNfFunction());
- put(valueMap, "NF_NAMING_CODE", o.getNfNamingCode());
- put(valueMap, "PROVIDING_SERVICE_MODEL_INVARIANT_UUID", o.getProvidingServiceModelInvariantUUID());
- put(valueMap, "PROVIDING_SERVICE_MODEL_UUID", o.getProvidingServiceModelUUID());
- put(valueMap, "PROVIDING_SERVICE_MODEL_NAME", o.getProvidingServiceModelName());
- put(valueMap, "RESOURCE_INPUT", o.getResourceInput());
-
- sb.append(sep).append(this.setTemplate(TEMPLATE, valueMap));
- sep = ",\n";
- }
- }
- if (!first)
- sb.append("\n");
-
- if (isArray)
- sb.append("]");
-
- if (!isEmbed && isArray)
- sb.append("}");
-
- return sb.toString();
- }
+ @Override
+ public String JSON2(boolean isArray, boolean isEmbed) {
+ StringBuilder sb = new StringBuilder();
+ if (!isEmbed && isArray)
+ sb.append("{ ");
+ if (isArray)
+ sb.append("\"serviceAllottedResources\": [");
+ Map<String, String> valueMap = new HashMap<>();
+ String sep = "";
+ boolean first = true;
+
+ if (this.allottedResourceCustomization != null) {
+ for (AllottedResourceCustomization o : allottedResourceCustomization) {
+ if (first)
+ sb.append("\n");
+
+ first = false;
+
+ boolean arNull = o.getAllottedResource() == null ? true : false;
+
+ put(valueMap, "MODEL_NAME", arNull ? null : o.getAllottedResource().getModelName());
+ put(valueMap, "MODEL_UUID", arNull ? null : o.getAllottedResource().getModelUUID());
+ put(valueMap, "MODEL_INVARIANT_ID", arNull ? null : o.getAllottedResource().getModelInvariantUUID());
+ put(valueMap, "MODEL_VERSION", arNull ? null : o.getAllottedResource().getModelVersion());
+ put(valueMap, "MODEL_CUSTOMIZATION_UUID", o.getModelCustomizationUUID());
+ put(valueMap, "MODEL_INSTANCE_NAME", o.getModelInstanceName());
+ put(valueMap, "TOSCA_NODE_TYPE", arNull ? null : o.getAllottedResource().getToscaNodeType());
+ put(valueMap, "ALLOTTED_RESOURCE_TYPE", arNull ? null : o.getAllottedResource().getSubcategory());
+ put(valueMap, "ALLOTTED_RESOURCE_ROLE",
+ o.getTargetNetworkRole() != null ? o.getTargetNetworkRole() : o.getNfRole());
+ put(valueMap, "NF_TYPE", o.getNfType());
+ put(valueMap, "NF_ROLE", o.getNfRole());
+ put(valueMap, "NF_FUNCTION", o.getNfFunction());
+ put(valueMap, "NF_NAMING_CODE", o.getNfNamingCode());
+ put(valueMap, "PROVIDING_SERVICE_MODEL_INVARIANT_UUID", o.getProvidingServiceModelInvariantUUID());
+ put(valueMap, "PROVIDING_SERVICE_MODEL_UUID", o.getProvidingServiceModelUUID());
+ put(valueMap, "PROVIDING_SERVICE_MODEL_NAME", o.getProvidingServiceModelName());
+ put(valueMap, "RESOURCE_INPUT", o.getResourceInput());
+
+ sb.append(sep).append(this.setTemplate(TEMPLATE, valueMap));
+ sep = ",\n";
+ }
+ }
+ if (!first)
+ sb.append("\n");
+
+ if (isArray)
+ sb.append("]");
+
+ if (!isEmbed && isArray)
+ sb.append("}");
+
+ return sb.toString();
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryResourceRecipe.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryResourceRecipe.java
index 58a2e852f0..ee52abe047 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryResourceRecipe.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryResourceRecipe.java
@@ -21,7 +21,6 @@ package org.onap.so.adapters.catalogdb.catalogrest;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.commons.lang3.StringUtils;
import org.onap.so.db.catalog.beans.Recipe;
import org.slf4j.Logger;
@@ -31,21 +30,20 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
- * serivce csar query support
- * <br>
+ * serivce csar query support <br>
* <p>
* </p>
*
* @author
- * @version ONAP Beijing Release 2018-02-28
+ * @version ONAP Beijing Release 2018-02-28
*/
-public class QueryResourceRecipe extends CatalogQuery{
+public class QueryResourceRecipe extends CatalogQuery {
protected static Logger logger = LoggerFactory.getLogger(QueryResourceRecipe.class);
-
+
private Recipe resourceRecipe;
-
- public QueryResourceRecipe(Recipe resourceRecipe){
- this.resourceRecipe =resourceRecipe;
+
+ public QueryResourceRecipe(Recipe resourceRecipe) {
+ this.resourceRecipe = resourceRecipe;
}
@Override
@@ -56,25 +54,28 @@ public class QueryResourceRecipe extends CatalogQuery{
@Override
public String JSON2(boolean isArray, boolean isEmbed) {
- Map<String, String> valueMap = new HashMap<>();
- valueMap.put("id", null == resourceRecipe || null == resourceRecipe.getId()
- ? StringUtils.EMPTY :String.valueOf(resourceRecipe.getId()));
- valueMap.put("action", null == resourceRecipe || null == resourceRecipe.getAction()
- ? StringUtils.EMPTY :resourceRecipe.getAction());
- valueMap.put("orchestrationUri", null == resourceRecipe || null == resourceRecipe.getOrchestrationUri()
- ? StringUtils.EMPTY : resourceRecipe.getOrchestrationUri());
- valueMap.put("recipeTimeout", null == resourceRecipe || null == resourceRecipe.getRecipeTimeout()
- ? StringUtils.EMPTY : String.valueOf(resourceRecipe.getRecipeTimeout()));
- valueMap.put("paramXSD", null == resourceRecipe || null == resourceRecipe.getParamXsd()
- ? StringUtils.EMPTY : resourceRecipe.getParamXsd());
- valueMap.put("description", null == resourceRecipe || null == resourceRecipe.getDescription()
- ? StringUtils.EMPTY : resourceRecipe.getDescription());
+ Map<String, String> valueMap = new HashMap<>();
+ valueMap.put("id", null == resourceRecipe || null == resourceRecipe.getId() ? StringUtils.EMPTY
+ : String.valueOf(resourceRecipe.getId()));
+ valueMap.put("action", null == resourceRecipe || null == resourceRecipe.getAction() ? StringUtils.EMPTY
+ : resourceRecipe.getAction());
+ valueMap.put("orchestrationUri",
+ null == resourceRecipe || null == resourceRecipe.getOrchestrationUri() ? StringUtils.EMPTY
+ : resourceRecipe.getOrchestrationUri());
+ valueMap.put("recipeTimeout",
+ null == resourceRecipe || null == resourceRecipe.getRecipeTimeout() ? StringUtils.EMPTY
+ : String.valueOf(resourceRecipe.getRecipeTimeout()));
+ valueMap.put("paramXSD", null == resourceRecipe || null == resourceRecipe.getParamXsd() ? StringUtils.EMPTY
+ : resourceRecipe.getParamXsd());
+ valueMap.put("description",
+ null == resourceRecipe || null == resourceRecipe.getDescription() ? StringUtils.EMPTY
+ : resourceRecipe.getDescription());
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
String jsonStr = "";
try {
jsonStr = mapper.writeValueAsString(valueMap);
- } catch(JsonProcessingException e) {
+ } catch (JsonProcessingException e) {
logger.error("Error creating JSON", e);
}
return jsonStr;
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceCsar.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceCsar.java
index c7ae137759..1afd395136 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceCsar.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceCsar.java
@@ -21,36 +21,29 @@ package org.onap.so.adapters.catalogdb.catalogrest;
import java.util.HashMap;
import java.util.Map;
-
import org.onap.so.db.catalog.beans.ToscaCsar;
/**
- * serivce csar query support
- * <br>
+ * serivce csar query support <br>
* <p>
* </p>
*
* @author
- * @version ONAP Beijing Release 2018-02-28
+ * @version ONAP Beijing Release 2018-02-28
*/
-public class QueryServiceCsar extends CatalogQuery{
-
- private static final String TEMPLATE =
- "\t{\n"+
- "\t\t\"artifactUUID\" : <ARTIFACT_UUID>,\n"+
- "\t\t\"name\" : <NAME>,\n"+
- "\t\t\"version\" : <VERSION>,\n"+
- "\t\t\"artifactChecksum\" : <ARTIFACT_CHECK_SUM>,\n"+
- "\t\t\"url\" : <URL>,\n"+
- "\t\t\"description\" : <DESCRIPTION>\n"+
- "\t}";
-
+public class QueryServiceCsar extends CatalogQuery {
+
+ private static final String TEMPLATE = "\t{\n" + "\t\t\"artifactUUID\" : <ARTIFACT_UUID>,\n"
+ + "\t\t\"name\" : <NAME>,\n" + "\t\t\"version\" : <VERSION>,\n"
+ + "\t\t\"artifactChecksum\" : <ARTIFACT_CHECK_SUM>,\n" + "\t\t\"url\" : <URL>,\n"
+ + "\t\t\"description\" : <DESCRIPTION>\n" + "\t}";
+
private ToscaCsar toscaCsar;
-
- public QueryServiceCsar(ToscaCsar toscaCsar){
+
+ public QueryServiceCsar(ToscaCsar toscaCsar) {
this.toscaCsar = toscaCsar;
}
-
+
@Override
public String toString() {
return toscaCsar.toString();
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java
index edbf9749c6..0eb7d0418e 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java
@@ -19,14 +19,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.adapters.catalogdb.catalogrest;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.db.catalog.beans.Service;
import org.onap.so.db.catalog.rest.beans.ServiceMacroHolder;
@@ -34,68 +32,70 @@ import org.onap.so.db.catalog.rest.beans.ServiceMacroHolder;
public class QueryServiceMacroHolder extends CatalogQuery {
private ServiceMacroHolder serviceMacroHolder;
private static final String LINE_BEGINNING = "(?m)^";
- private static final String TEMPLATE =
- "{ \"serviceResources\" : {\n"+
- "\t\"modelInfo\" : {\n"+
- "\t\t\"modelName\" : <SERVICE_MODEL_NAME>,\n"+
- "\t\t\"modelUuid\" : <SERVICE_MODEL_UUID>,\n"+
- "\t\t\"modelInvariantUuid\" : <SERVICE_MODEL_INVARIANT_ID>,\n"+
- "\t\t\"modelVersion\" : <SERVICE_MODEL_VERSION>\n"+
- "\t},\n"+
- "\t\"serviceType\" : <SERVICE_TYPE>,\n"+
- "\t\"serviceRole\" : <SERVICE_ROLE>,\n"+
- "\t\"environmentContext\" : <ENVIRONMENT_CONTEXT>,\n"+
- "\t\"resourceOrder\" : <RESOURCE_ORDER>,\n"+
- "\t\"workloadContext\" : <WORKLOAD_CONTEXT>,\n"+
- "<_SERVICEVNFS_>,\n"+
- "<_SERVICENETWORKS_>,\n"+
- "<_SERVICEALLOTTEDRESOURCES_>\n"+
- "\t}}";
-
- public QueryServiceMacroHolder() {
- super();
- serviceMacroHolder = new ServiceMacroHolder();
- }
- public QueryServiceMacroHolder(ServiceMacroHolder vlist) { serviceMacroHolder = vlist; }
-
- public ServiceMacroHolder getServiceResources(){ return this.serviceMacroHolder; }
- public void setServiceResources(ServiceMacroHolder v) { this.serviceMacroHolder = v; }
-
- @Override
- public String toString () { return serviceMacroHolder.toString(); }
-
- @Override
- public String JSON2(boolean isArray, boolean x) {
- Service service = serviceMacroHolder.getService();
- if (service == null) {
+ private static final String TEMPLATE = "{ \"serviceResources\" : {\n" + "\t\"modelInfo\" : {\n"
+ + "\t\t\"modelName\" : <SERVICE_MODEL_NAME>,\n"
+ + "\t\t\"modelUuid\" : <SERVICE_MODEL_UUID>,\n"
+ + "\t\t\"modelInvariantUuid\" : <SERVICE_MODEL_INVARIANT_ID>,\n"
+ + "\t\t\"modelVersion\" : <SERVICE_MODEL_VERSION>\n" + "\t},\n"
+ + "\t\"serviceType\" : <SERVICE_TYPE>,\n" + "\t\"serviceRole\" : <SERVICE_ROLE>,\n"
+ + "\t\"environmentContext\" : <ENVIRONMENT_CONTEXT>,\n" + "\t\"resourceOrder\" : <RESOURCE_ORDER>,\n"
+ + "\t\"workloadContext\" : <WORKLOAD_CONTEXT>,\n" + "<_SERVICEVNFS_>,\n" + "<_SERVICENETWORKS_>,\n"
+ + "<_SERVICEALLOTTEDRESOURCES_>\n" + "\t}}";
+
+ public QueryServiceMacroHolder() {
+ super();
+ serviceMacroHolder = new ServiceMacroHolder();
+ }
+
+ public QueryServiceMacroHolder(ServiceMacroHolder vlist) {
+ serviceMacroHolder = vlist;
+ }
+
+ public ServiceMacroHolder getServiceResources() {
+ return this.serviceMacroHolder;
+ }
+
+ public void setServiceResources(ServiceMacroHolder v) {
+ this.serviceMacroHolder = v;
+ }
+
+ @Override
+ public String toString() {
+ return serviceMacroHolder.toString();
+ }
+
+ @Override
+ public String JSON2(boolean isArray, boolean x) {
+ Service service = serviceMacroHolder.getService();
+ if (service == null) {
return "\"serviceResources\": null";
- }
+ }
- StringBuilder buf = new StringBuilder();
- Map<String, String> valueMap = new HashMap<>();
+ StringBuilder buf = new StringBuilder();
+ Map<String, String> valueMap = new HashMap<>();
- put(valueMap, "SERVICE_MODEL_NAME", service.getModelName());
- put(valueMap, "SERVICE_MODEL_UUID", service.getModelUUID());
- put(valueMap, "SERVICE_MODEL_INVARIANT_ID", service.getModelInvariantUUID());
- put(valueMap, "SERVICE_MODEL_VERSION", service.getModelVersion());
- put(valueMap, "SERVICE_TYPE", service.getServiceType());
- put(valueMap, "SERVICE_ROLE", service.getServiceRole());
- put(valueMap, "ENVIRONMENT_CONTEXT", service.getEnvironmentContext());
- put(valueMap, "WORKLOAD_CONTEXT", service.getWorkloadContext());
- put(valueMap, "RESOURCE_ORDER", service.getResourceOrder());
+ put(valueMap, "SERVICE_MODEL_NAME", service.getModelName());
+ put(valueMap, "SERVICE_MODEL_UUID", service.getModelUUID());
+ put(valueMap, "SERVICE_MODEL_INVARIANT_ID", service.getModelInvariantUUID());
+ put(valueMap, "SERVICE_MODEL_VERSION", service.getModelVersion());
+ put(valueMap, "SERVICE_TYPE", service.getServiceType());
+ put(valueMap, "SERVICE_ROLE", service.getServiceRole());
+ put(valueMap, "ENVIRONMENT_CONTEXT", service.getEnvironmentContext());
+ put(valueMap, "WORKLOAD_CONTEXT", service.getWorkloadContext());
+ put(valueMap, "RESOURCE_ORDER", service.getResourceOrder());
- String subitem;
- subitem = new QueryServiceVnfs(service.getVnfCustomizations()).JSON2(true, true);
- valueMap.put("_SERVICEVNFS_", subitem.replaceAll(LINE_BEGINNING, "\t"));
+ String subitem;
+ subitem = new QueryServiceVnfs(service.getVnfCustomizations()).JSON2(true, true);
+ valueMap.put("_SERVICEVNFS_", subitem.replaceAll(LINE_BEGINNING, "\t"));
- subitem = new QueryServiceNetworks(service.getNetworkCustomizations()).JSON2(true, true);
- valueMap.put("_SERVICENETWORKS_", subitem.replaceAll(LINE_BEGINNING, "\t"));
+ subitem = new QueryServiceNetworks(service.getNetworkCustomizations()).JSON2(true, true);
+ valueMap.put("_SERVICENETWORKS_", subitem.replaceAll(LINE_BEGINNING, "\t"));
- subitem = new QueryAllottedResourceCustomization(service.getAllottedCustomizations()).JSON2(true, true);
- valueMap.put("_SERVICEALLOTTEDRESOURCES_", subitem.replaceAll(LINE_BEGINNING, "\t"));
+ subitem = new QueryAllottedResourceCustomization(service.getAllottedCustomizations()).JSON2(true, true);
+ valueMap.put("_SERVICEALLOTTEDRESOURCES_", subitem.replaceAll(LINE_BEGINNING, "\t"));
buf.append(this.setTemplate(TEMPLATE, valueMap));
- return buf.toString();
- }
+ return buf.toString();
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceNetworks.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceNetworks.java
index f7457fda4a..96ea797631 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceNetworks.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceNetworks.java
@@ -26,9 +26,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.db.catalog.beans.NetworkResourceCustomization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -36,98 +34,99 @@ import org.slf4j.LoggerFactory;
@XmlRootElement(name = "serviceNetworks")
public class QueryServiceNetworks extends CatalogQuery {
protected static Logger logger = LoggerFactory.getLogger(QueryServiceNetworks.class);
- private List<NetworkResourceCustomization> serviceNetworks;
- private static final String TEMPLATE =
- "\t{\n"+
- "\t\t\"modelInfo\" : {\n"+
- "\t\t\t\"modelName\" : <MODEL_NAME>,\n"+
- "\t\t\t\"modelUuid\" : <MODEL_UUID>,\n"+
- "\t\t\t\"modelInvariantUuid\" : <MODEL_INVARIANT_ID>,\n"+
- "\t\t\t\"modelVersion\" : <MODEL_VERSION>,\n"+
- "\t\t\t\"modelCustomizationUuid\" : <MODEL_CUSTOMIZATION_UUID>,\n"+
- "\t\t\t\"modelInstanceName\" : <MODEL_INSTANCE_NAME>\n"+
- "\t},\n"+
- "\t\t\"toscaNodeType\" : <TOSCA_NODE_TYPE>,\n"+
- "\t\t\"networkType\" : <NETWORK_TYPE>,\n"+
- "\t\t\"networkTechnology\" : <NETWORK_TECHNOLOGY>,\n"+
- "\t\t\"resourceInput\" : <RESOURCE_INPUT>,\n"+
- "\t\t\"networkRole\" : <NETWORK_ROLE>,\n"+
- "\t\t\"networkScope\" : <NETWORK_SCOPE>\n"+
- "\t}";
+ private List<NetworkResourceCustomization> serviceNetworks;
+ private static final String TEMPLATE =
+ "\t{\n" + "\t\t\"modelInfo\" : {\n" + "\t\t\t\"modelName\" : <MODEL_NAME>,\n"
+ + "\t\t\t\"modelUuid\" : <MODEL_UUID>,\n"
+ + "\t\t\t\"modelInvariantUuid\" : <MODEL_INVARIANT_ID>,\n"
+ + "\t\t\t\"modelVersion\" : <MODEL_VERSION>,\n"
+ + "\t\t\t\"modelCustomizationUuid\" : <MODEL_CUSTOMIZATION_UUID>,\n"
+ + "\t\t\t\"modelInstanceName\" : <MODEL_INSTANCE_NAME>\n" + "\t},\n"
+ + "\t\t\"toscaNodeType\" : <TOSCA_NODE_TYPE>,\n"
+ + "\t\t\"networkType\" : <NETWORK_TYPE>,\n"
+ + "\t\t\"networkTechnology\" : <NETWORK_TECHNOLOGY>,\n"
+ + "\t\t\"resourceInput\" : <RESOURCE_INPUT>,\n"
+ + "\t\t\"networkRole\" : <NETWORK_ROLE>,\n"
+ + "\t\t\"networkScope\" : <NETWORK_SCOPE>\n" + "\t}";
- public QueryServiceNetworks() {
- super();
- serviceNetworks = new ArrayList<>();
- }
-
- public QueryServiceNetworks(List<NetworkResourceCustomization> vlist) {
- logger.debug ("QueryServiceNetworks:");
- serviceNetworks = new ArrayList<>();
- for (NetworkResourceCustomization o : vlist) {
- if(logger.isDebugEnabled())
- logger.debug (o.toString());
- serviceNetworks.add(o);
- }
- }
+ public QueryServiceNetworks() {
+ super();
+ serviceNetworks = new ArrayList<>();
+ }
- public List<NetworkResourceCustomization> getServiceNetworks(){ return this.serviceNetworks; }
- public void setServiceNetworks(List<NetworkResourceCustomization> v) { this.serviceNetworks = v; }
+ public QueryServiceNetworks(List<NetworkResourceCustomization> vlist) {
+ logger.debug("QueryServiceNetworks:");
+ serviceNetworks = new ArrayList<>();
+ for (NetworkResourceCustomization o : vlist) {
+ if (logger.isDebugEnabled())
+ logger.debug(o.toString());
+ serviceNetworks.add(o);
+ }
+ }
- @Override
- public String toString () {
- StringBuilder sb = new StringBuilder();
+ public List<NetworkResourceCustomization> getServiceNetworks() {
+ return this.serviceNetworks;
+ }
- boolean first = true;
- int i = 1;
- for (NetworkResourceCustomization o : serviceNetworks) {
- sb.append(i).append("\t");
- if (!first)
- sb.append("\n");
- first = false;
- sb.append(o);
- }
- return sb.toString();
+ public void setServiceNetworks(List<NetworkResourceCustomization> v) {
+ this.serviceNetworks = v;
}
- @Override
- public String JSON2(boolean isArray, boolean isEmbed) {
- StringBuilder sb = new StringBuilder();
- if (!isEmbed && isArray)
- sb.append("{ ");
- if (isArray)
- sb.append("\"serviceNetworks\": [");
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
- Map<String, String> valueMap = new HashMap<>();
- String sep = "";
- boolean first = true;
+ boolean first = true;
+ int i = 1;
+ for (NetworkResourceCustomization o : serviceNetworks) {
+ sb.append(i).append("\t");
+ if (!first)
+ sb.append("\n");
+ first = false;
+ sb.append(o);
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public String JSON2(boolean isArray, boolean isEmbed) {
+ StringBuilder sb = new StringBuilder();
+ if (!isEmbed && isArray)
+ sb.append("{ ");
+ if (isArray)
+ sb.append("\"serviceNetworks\": [");
- for (NetworkResourceCustomization o : serviceNetworks) {
- if (first)
- sb.append("\n");
- first = false;
- boolean nrNull = o.getNetworkResource() == null ? true : false;
- put(valueMap, "MODEL_NAME", nrNull ? null : o.getNetworkResource().getModelName());
- put(valueMap, "MODEL_UUID", nrNull ? null : o.getNetworkResource().getModelUUID());
- put(valueMap, "MODEL_INVARIANT_ID", nrNull ? null : o.getNetworkResource().getModelInvariantUUID());
- put(valueMap, "MODEL_VERSION", nrNull ? null : o.getNetworkResource().getModelVersion());
- put(valueMap, "MODEL_CUSTOMIZATION_UUID", o.getModelCustomizationUUID());
- put(valueMap, "MODEL_INSTANCE_NAME", o.getModelInstanceName());
- put(valueMap, "TOSCA_NODE_TYPE", nrNull ? null : o.getNetworkResource().getToscaNodeType());
- put(valueMap, "NETWORK_TYPE", o.getNetworkType());
- put(valueMap, "NETWORK_ROLE", o.getNetworkRole());
- put(valueMap, "NETWORK_SCOPE", o.getNetworkScope());
- put(valueMap, "NETWORK_TECHNOLOGY", o.getNetworkTechnology());
- put(valueMap, "RESOURCE_INPUT", o.getResourceInput());
+ Map<String, String> valueMap = new HashMap<>();
+ String sep = "";
+ boolean first = true;
+
+ for (NetworkResourceCustomization o : serviceNetworks) {
+ if (first)
+ sb.append("\n");
+ first = false;
+ boolean nrNull = o.getNetworkResource() == null ? true : false;
+ put(valueMap, "MODEL_NAME", nrNull ? null : o.getNetworkResource().getModelName());
+ put(valueMap, "MODEL_UUID", nrNull ? null : o.getNetworkResource().getModelUUID());
+ put(valueMap, "MODEL_INVARIANT_ID", nrNull ? null : o.getNetworkResource().getModelInvariantUUID());
+ put(valueMap, "MODEL_VERSION", nrNull ? null : o.getNetworkResource().getModelVersion());
+ put(valueMap, "MODEL_CUSTOMIZATION_UUID", o.getModelCustomizationUUID());
+ put(valueMap, "MODEL_INSTANCE_NAME", o.getModelInstanceName());
+ put(valueMap, "TOSCA_NODE_TYPE", nrNull ? null : o.getNetworkResource().getToscaNodeType());
+ put(valueMap, "NETWORK_TYPE", o.getNetworkType());
+ put(valueMap, "NETWORK_ROLE", o.getNetworkRole());
+ put(valueMap, "NETWORK_SCOPE", o.getNetworkScope());
+ put(valueMap, "NETWORK_TECHNOLOGY", o.getNetworkTechnology());
+ put(valueMap, "RESOURCE_INPUT", o.getResourceInput());
sb.append(sep).append(this.setTemplate(TEMPLATE, valueMap));
sep = ",\n";
- }
- if (!first)
- sb.append("\n");
- if (isArray)
- sb.append("]");
- if (!isEmbed && isArray)
- sb.append("}");
- return sb.toString();
- }
+ }
+ if (!first)
+ sb.append("\n");
+ if (isArray)
+ sb.append("]");
+ if (!isEmbed && isArray)
+ sb.append("}");
+ return sb.toString();
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceVnfs.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceVnfs.java
index 4170047e0b..b1bdeda445 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceVnfs.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceVnfs.java
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.adapters.catalogdb.catalogrest;
/* should be called QueryVnfResource.java */
@@ -25,9 +25,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.db.catalog.beans.VnfResourceCustomization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -35,105 +33,102 @@ import org.slf4j.LoggerFactory;
@XmlRootElement(name = "serviceVnfs")
public class QueryServiceVnfs extends CatalogQuery {
protected static Logger logger = LoggerFactory.getLogger(QueryServiceVnfs.class);
-
- private List<VnfResourceCustomization> serviceVnfs;
- private static final String TEMPLATE =
- "\n"+
- "\t{ \"modelInfo\" : {\n"+
- "\t\t\"modelName\" : <MODEL_NAME>,\n"+
- "\t\t\"modelUuid\" : <MODEL_UUID>,\n"+
- "\t\t\"modelInvariantUuid\" : <MODEL_INVARIANT_ID>,\n"+
- "\t\t\"modelVersion\" : <MODEL_VERSION>,\n"+
- "\t\t\"modelCustomizationUuid\" : <MODEL_CUSTOMIZATION_UUID>,\n"+
- "\t\t\"modelInstanceName\" : <MODEL_INSTANCE_NAME>\n"+
- "\t\t},\n"+
- "\t\"toscaNodeType\" : <TOSCA_NODE_TYPE>,\n"+
- "\t\"nfFunction\" : <NF_FUNCTION>,\n"+
- "\t\"nfType\" : <NF_TYPE>,\n"+
- "\t\"nfRole\" : <NF_ROLE>,\n"+
- "\t\"nfNamingCode\" : <NF_NAMING_CODE>,\n"+
- "\t\"multiStageDesign\" : <MULTI_STEP_DESIGN>,\n"+
- "\t\"resourceInput\" : <RESOURCE_INPUT>,\n"+
- "<_VFMODULES_>\n" +
- "\t}";
-
- public QueryServiceVnfs() {
- super();
- serviceVnfs = new ArrayList<>();
- }
-
- public QueryServiceVnfs(List<VnfResourceCustomization> vlist) {
- serviceVnfs = new ArrayList<>();
- for (VnfResourceCustomization o : vlist) {
- if(logger.isDebugEnabled())
- logger.debug (o.toString());
- serviceVnfs.add(o);
- }
- }
-
- public List<VnfResourceCustomization> getServiceVnfs(){ return this.serviceVnfs; }
- public void setServiceVnfs(List<VnfResourceCustomization> v) { this.serviceVnfs = v; }
-
- @Override
- public String toString () {
- StringBuilder sb = new StringBuilder();
-
- boolean first = true;
- int i = 1;
- for (VnfResourceCustomization o : serviceVnfs) {
- sb.append(i).append("\t");
- if (!first)
- sb.append("\n");
- first = false;
- sb.append(o);
- }
- return sb.toString();
+
+ private List<VnfResourceCustomization> serviceVnfs;
+ private static final String TEMPLATE = "\n" + "\t{ \"modelInfo\" : {\n"
+ + "\t\t\"modelName\" : <MODEL_NAME>,\n" + "\t\t\"modelUuid\" : <MODEL_UUID>,\n"
+ + "\t\t\"modelInvariantUuid\" : <MODEL_INVARIANT_ID>,\n"
+ + "\t\t\"modelVersion\" : <MODEL_VERSION>,\n"
+ + "\t\t\"modelCustomizationUuid\" : <MODEL_CUSTOMIZATION_UUID>,\n"
+ + "\t\t\"modelInstanceName\" : <MODEL_INSTANCE_NAME>\n" + "\t\t},\n"
+ + "\t\"toscaNodeType\" : <TOSCA_NODE_TYPE>,\n"
+ + "\t\"nfFunction\" : <NF_FUNCTION>,\n" + "\t\"nfType\" : <NF_TYPE>,\n"
+ + "\t\"nfRole\" : <NF_ROLE>,\n" + "\t\"nfNamingCode\" : <NF_NAMING_CODE>,\n"
+ + "\t\"multiStageDesign\" : <MULTI_STEP_DESIGN>,\n"
+ + "\t\"resourceInput\" : <RESOURCE_INPUT>,\n" + "<_VFMODULES_>\n" + "\t}";
+
+ public QueryServiceVnfs() {
+ super();
+ serviceVnfs = new ArrayList<>();
}
- @Override
- public String JSON2(boolean isArray, boolean isEmbed) {
- StringBuilder sb = new StringBuilder();
- if (!isEmbed && isArray)
- sb.append("{ ");
- if (isArray)
- sb.append("\"serviceVnfs\": [");
- Map<String, String> valueMap = new HashMap<>();
- String sep = "";
- boolean first = true;
-
- for (VnfResourceCustomization o : serviceVnfs) {
- if (first)
- sb.append("\n");
- first = false;
-
- boolean vrNull = o.getVnfResources() == null ? true : false;
-
- put(valueMap, "MODEL_NAME", vrNull ? null : o.getVnfResources().getModelName());
- put(valueMap, "MODEL_UUID", vrNull ? null : o.getVnfResources().getModelUUID());
- put(valueMap, "MODEL_INVARIANT_ID", vrNull ? null : o.getVnfResources().getModelInvariantId());
- put(valueMap, "MODEL_VERSION", vrNull ? null : o.getVnfResources().getModelVersion());
- put(valueMap, "MODEL_CUSTOMIZATION_UUID", o.getModelCustomizationUUID());
- put(valueMap, "MODEL_INSTANCE_NAME", o.getModelInstanceName());
- put(valueMap, "TOSCA_NODE_TYPE", vrNull ? null : o.getVnfResources().getToscaNodeType());
- put(valueMap, "NF_FUNCTION", o.getNfFunction());
- put(valueMap, "NF_TYPE", o.getNfType());
- put(valueMap, "NF_ROLE", o.getNfRole());
- put(valueMap, "NF_NAMING_CODE", o.getNfNamingCode());
- put(valueMap, "MULTI_STEP_DESIGN", o.getMultiStageDesign());
- put(valueMap, "RESOURCE_INPUT", o.getResourceInput());
-
- String subitem = new QueryVfModule(vrNull ? null : o.getVfModuleCustomizations()).JSON2(true, true);
- valueMap.put("_VFMODULES_", subitem.replaceAll("(?m)^", "\t\t"));
+ public QueryServiceVnfs(List<VnfResourceCustomization> vlist) {
+ serviceVnfs = new ArrayList<>();
+ for (VnfResourceCustomization o : vlist) {
+ if (logger.isDebugEnabled())
+ logger.debug(o.toString());
+ serviceVnfs.add(o);
+ }
+ }
+
+ public List<VnfResourceCustomization> getServiceVnfs() {
+ return this.serviceVnfs;
+ }
+
+ public void setServiceVnfs(List<VnfResourceCustomization> v) {
+ this.serviceVnfs = v;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+
+ boolean first = true;
+ int i = 1;
+ for (VnfResourceCustomization o : serviceVnfs) {
+ sb.append(i).append("\t");
+ if (!first)
+ sb.append("\n");
+ first = false;
+ sb.append(o);
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public String JSON2(boolean isArray, boolean isEmbed) {
+ StringBuilder sb = new StringBuilder();
+ if (!isEmbed && isArray)
+ sb.append("{ ");
+ if (isArray)
+ sb.append("\"serviceVnfs\": [");
+ Map<String, String> valueMap = new HashMap<>();
+ String sep = "";
+ boolean first = true;
+
+ for (VnfResourceCustomization o : serviceVnfs) {
+ if (first)
+ sb.append("\n");
+ first = false;
+
+ boolean vrNull = o.getVnfResources() == null ? true : false;
+
+ put(valueMap, "MODEL_NAME", vrNull ? null : o.getVnfResources().getModelName());
+ put(valueMap, "MODEL_UUID", vrNull ? null : o.getVnfResources().getModelUUID());
+ put(valueMap, "MODEL_INVARIANT_ID", vrNull ? null : o.getVnfResources().getModelInvariantId());
+ put(valueMap, "MODEL_VERSION", vrNull ? null : o.getVnfResources().getModelVersion());
+ put(valueMap, "MODEL_CUSTOMIZATION_UUID", o.getModelCustomizationUUID());
+ put(valueMap, "MODEL_INSTANCE_NAME", o.getModelInstanceName());
+ put(valueMap, "TOSCA_NODE_TYPE", vrNull ? null : o.getVnfResources().getToscaNodeType());
+ put(valueMap, "NF_FUNCTION", o.getNfFunction());
+ put(valueMap, "NF_TYPE", o.getNfType());
+ put(valueMap, "NF_ROLE", o.getNfRole());
+ put(valueMap, "NF_NAMING_CODE", o.getNfNamingCode());
+ put(valueMap, "MULTI_STEP_DESIGN", o.getMultiStageDesign());
+ put(valueMap, "RESOURCE_INPUT", o.getResourceInput());
+
+ String subitem = new QueryVfModule(vrNull ? null : o.getVfModuleCustomizations()).JSON2(true, true);
+ valueMap.put("_VFMODULES_", subitem.replaceAll("(?m)^", "\t\t"));
sb.append(sep).append(this.setTemplate(TEMPLATE, valueMap));
sep = ",\n";
- }
- if (!first)
- sb.append("\n");
- if (isArray)
- sb.append("]");
- if (!isEmbed && isArray)
- sb.append("}");
- return sb.toString();
- }
+ }
+ if (!first)
+ sb.append("\n");
+ if (isArray)
+ sb.append("]");
+ if (!isEmbed && isArray)
+ sb.append("}");
+ return sb.toString();
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModule.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModule.java
index 3680c59dca..1dec9cecae 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModule.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModule.java
@@ -17,114 +17,112 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.adapters.catalogdb.catalogrest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import org.onap.so.db.catalog.beans.HeatEnvironment;
import org.onap.so.db.catalog.beans.VfModuleCustomization;
@XmlRootElement(name = "vfModules")
public class QueryVfModule extends CatalogQuery {
- private List<VfModuleCustomization> vfModules;
- private static final String TEMPLATE =
- "\t{\n"+
- "\t\t\"modelInfo\" : { \n"+
- "\t\t\t\"modelName\" : <MODEL_NAME>,\n"+
- "\t\t\t\"modelUuid\" : <MODEL_UUID>,\n"+
- "\t\t\t\"modelInvariantUuid\" : <MODEL_INVARIANT_ID>,\n"+
- "\t\t\t\"modelVersion\" : <MODEL_VERSION>,\n"+
- "\t\t\t\"modelCustomizationUuid\" : <MODEL_CUSTOMIZATION_UUID>\n"+
- "\t\t},"+
- "\t\t\"isBase\" : <IS_BASE>,\n"+
- "\t\t\"vfModuleLabel\" : <VF_MODULE_LABEL>,\n"+
- "\t\t\"initialCount\" : <INITIAL_COUNT>,\n"+
- "\t\t\"hasVolumeGroup\" : <HAS_VOLUME_GROUP>\n"+
- "\t}";
+ private List<VfModuleCustomization> vfModules;
+ private static final String TEMPLATE = "\t{\n" + "\t\t\"modelInfo\" : { \n"
+ + "\t\t\t\"modelName\" : <MODEL_NAME>,\n"
+ + "\t\t\t\"modelUuid\" : <MODEL_UUID>,\n"
+ + "\t\t\t\"modelInvariantUuid\" : <MODEL_INVARIANT_ID>,\n"
+ + "\t\t\t\"modelVersion\" : <MODEL_VERSION>,\n"
+ + "\t\t\t\"modelCustomizationUuid\" : <MODEL_CUSTOMIZATION_UUID>\n" + "\t\t},"
+ + "\t\t\"isBase\" : <IS_BASE>,\n" + "\t\t\"vfModuleLabel\" : <VF_MODULE_LABEL>,\n"
+ + "\t\t\"initialCount\" : <INITIAL_COUNT>,\n"
+ + "\t\t\"hasVolumeGroup\" : <HAS_VOLUME_GROUP>\n" + "\t}";
+
+ public QueryVfModule() {
+ super();
+ vfModules = new ArrayList<>();
+ }
- public QueryVfModule() {
- super();
- vfModules = new ArrayList<>();
- }
-
- public QueryVfModule(List<VfModuleCustomization> vlist) {
- vfModules = new ArrayList<>();
- if (vlist != null) {
- for (VfModuleCustomization o : vlist) {
- if(logger.isDebugEnabled())
- logger.debug (o.toString());
- vfModules.add(o);
- }
- }
- }
+ public QueryVfModule(List<VfModuleCustomization> vlist) {
+ vfModules = new ArrayList<>();
+ if (vlist != null) {
+ for (VfModuleCustomization o : vlist) {
+ if (logger.isDebugEnabled())
+ logger.debug(o.toString());
+ vfModules.add(o);
+ }
+ }
+ }
- public List<VfModuleCustomization> getVfModule(){ return this.vfModules; }
- public void setVfModule(List<VfModuleCustomization> v) { this.vfModules = v; }
+ public List<VfModuleCustomization> getVfModule() {
+ return this.vfModules;
+ }
- @Override
- public String toString () {
- StringBuilder sb = new StringBuilder();
+ public void setVfModule(List<VfModuleCustomization> v) {
+ this.vfModules = v;
+ }
- boolean first = true;
- int i = 1;
- for (VfModuleCustomization o : vfModules) {
- sb.append(i).append("\t");
- if (!first)
- sb.append("\n");
- first = false;
- sb.append(o);
- }
- return sb.toString();
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+
+ boolean first = true;
+ int i = 1;
+ for (VfModuleCustomization o : vfModules) {
+ sb.append(i).append("\t");
+ if (!first)
+ sb.append("\n");
+ first = false;
+ sb.append(o);
+ }
+ return sb.toString();
}
- @Override
- public String JSON2(boolean isArray, boolean isEmbed) {
- StringBuilder sb = new StringBuilder();
- if (!isEmbed && isArray)
- sb.append("{ ");
- if (isArray)
- sb.append("\"vfModules\": [");
- Map<String, String> valueMap = new HashMap<>();
- String sep = "";
- boolean first = true;
+ @Override
+ public String JSON2(boolean isArray, boolean isEmbed) {
+ StringBuilder sb = new StringBuilder();
+ if (!isEmbed && isArray)
+ sb.append("{ ");
+ if (isArray)
+ sb.append("\"vfModules\": [");
+ Map<String, String> valueMap = new HashMap<>();
+ String sep = "";
+ boolean first = true;
- for (VfModuleCustomization o : vfModules) {
- if (first)
- sb.append("\n");
- first = false;
+ for (VfModuleCustomization o : vfModules) {
+ if (first)
+ sb.append("\n");
+ first = false;
- boolean vfNull = o.getVfModule() == null ? true : false;
- boolean hasVolumeGroup = false;
- HeatEnvironment envt = o.getVolumeHeatEnv();
- if (envt != null) {
- hasVolumeGroup = true;
- }
+ boolean vfNull = o.getVfModule() == null ? true : false;
+ boolean hasVolumeGroup = false;
+ HeatEnvironment envt = o.getVolumeHeatEnv();
+ if (envt != null) {
+ hasVolumeGroup = true;
+ }
- put(valueMap, "MODEL_NAME", vfNull ? null : o.getVfModule().getModelName());
- put(valueMap, "MODEL_UUID", vfNull ? null : o.getVfModule().getModelUUID());
- put(valueMap, "MODEL_INVARIANT_ID", vfNull ? null : o.getVfModule().getModelInvariantUUID());
- put(valueMap, "MODEL_VERSION", vfNull ? null : o.getVfModule().getModelVersion());
- put(valueMap, "MODEL_CUSTOMIZATION_UUID", o.getModelCustomizationUUID());
- put(valueMap, "IS_BASE", vfNull ? false : o.getVfModule().getIsBase() ? true : false);
- put(valueMap, "VF_MODULE_LABEL", o.getLabel());
- put(valueMap, "INITIAL_COUNT", o.getInitialCount());
- put(valueMap, "HAS_VOLUME_GROUP", new Boolean(hasVolumeGroup));
+ put(valueMap, "MODEL_NAME", vfNull ? null : o.getVfModule().getModelName());
+ put(valueMap, "MODEL_UUID", vfNull ? null : o.getVfModule().getModelUUID());
+ put(valueMap, "MODEL_INVARIANT_ID", vfNull ? null : o.getVfModule().getModelInvariantUUID());
+ put(valueMap, "MODEL_VERSION", vfNull ? null : o.getVfModule().getModelVersion());
+ put(valueMap, "MODEL_CUSTOMIZATION_UUID", o.getModelCustomizationUUID());
+ put(valueMap, "IS_BASE", vfNull ? false : o.getVfModule().getIsBase() ? true : false);
+ put(valueMap, "VF_MODULE_LABEL", o.getLabel());
+ put(valueMap, "INITIAL_COUNT", o.getInitialCount());
+ put(valueMap, "HAS_VOLUME_GROUP", new Boolean(hasVolumeGroup));
sb.append(sep).append(this.setTemplate(TEMPLATE, valueMap));
sep = ",\n";
- }
- if (!first)
- sb.append("\n");
- if (isArray)
- sb.append("]");
- if (!isEmbed && isArray)
- sb.append("}");
- return sb.toString();
- }
+ }
+ if (!first)
+ sb.append("\n");
+ if (isArray)
+ sb.append("]");
+ if (!isEmbed && isArray)
+ sb.append("}");
+ return sb.toString();
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java
index 5009dce020..6cc53e6ec9 100644
--- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java
+++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java
@@ -26,7 +26,6 @@ package org.onap.so.adapters.catalogdb.rest;
import java.util.ArrayList;
import java.util.List;
-
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@@ -36,7 +35,6 @@ import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.onap.so.adapters.catalogdb.catalogrest.CatalogQuery;
import org.onap.so.adapters.catalogdb.catalogrest.CatalogQueryException;
@@ -125,176 +123,159 @@ public class CatalogDbAdapterRest {
private static final String NO_MATCHING_PARAMETERS = "no matching parameters";
public Response respond(String version, int respStatus, boolean isArray, CatalogQuery qryResp) {
- return Response
- .status(respStatus)
- .entity(qryResp.toJsonString(version, isArray))
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .build();
+ return Response.status(respStatus).entity(qryResp.toJsonString(version, isArray))
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).build();
}
@GET
@Path("vnfResources/{vnfModelCustomizationUuid}")
- @Transactional( readOnly = true)
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- public Response serviceVnfs (
- @PathParam("version") String version,
- @PathParam("vnfModelCustomizationUuid") String vnfUuid
- ) {
- return serviceVnfsImpl (version, !IS_ARRAY, vnfUuid, null, null, null, null);
+ @Transactional(readOnly = true)
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ public Response serviceVnfs(@PathParam("version") String version,
+ @PathParam("vnfModelCustomizationUuid") String vnfUuid) {
+ return serviceVnfsImpl(version, !IS_ARRAY, vnfUuid, null, null, null, null);
}
@GET
@Path("serviceVnfs")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Transactional( readOnly = true)
- public Response serviceVnfs(
- @PathParam("version") String version,
- @QueryParam("vnfModelCustomizationUuid") String vnfUuid,
- @QueryParam("serviceModelUuid") String smUuid,
- @QueryParam("serviceModelInvariantUuid") String smiUuid,
- @QueryParam("serviceModelVersion") String smVer,
- @QueryParam("serviceModelName") String smName
- ) {
- return serviceVnfsImpl (version, IS_ARRAY, vnfUuid, smUuid, smiUuid, smVer, smName);
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Transactional(readOnly = true)
+ public Response serviceVnfs(@PathParam("version") String version,
+ @QueryParam("vnfModelCustomizationUuid") String vnfUuid, @QueryParam("serviceModelUuid") String smUuid,
+ @QueryParam("serviceModelInvariantUuid") String smiUuid, @QueryParam("serviceModelVersion") String smVer,
+ @QueryParam("serviceModelName") String smName) {
+ return serviceVnfsImpl(version, IS_ARRAY, vnfUuid, smUuid, smiUuid, smVer, smName);
}
- public Response serviceVnfsImpl(String version, boolean isArray, String vnfUuid, String serviceModelUUID, String smiUuid, String smVer, String smName) {
+ public Response serviceVnfsImpl(String version, boolean isArray, String vnfUuid, String serviceModelUUID,
+ String smiUuid, String smVer, String smName) {
QueryServiceVnfs qryResp = null;
- int respStatus = HttpStatus.SC_OK;
+ int respStatus = HttpStatus.SC_OK;
List<VnfResourceCustomization> ret = new ArrayList<>();
Service service = null;
try {
- if (vnfUuid != null && !"".equals(vnfUuid))
- ret = vnfCustomizationRepo.findByModelCustomizationUUID(vnfUuid);
- else if (serviceModelUUID != null && !"".equals(serviceModelUUID))
+ if (vnfUuid != null && !"".equals(vnfUuid))
+ ret = vnfCustomizationRepo.findByModelCustomizationUUID(vnfUuid);
+ else if (serviceModelUUID != null && !"".equals(serviceModelUUID))
service = serviceRepo.findFirstOneByModelUUIDOrderByModelVersionDesc(serviceModelUUID);
- else if (smiUuid != null && !"".equals(smiUuid))
- if (smVer != null && !"".equals(smVer))
- service = serviceRepo.findFirstByModelVersionAndModelInvariantUUID(smVer,smiUuid);
- else
+ else if (smiUuid != null && !"".equals(smiUuid))
+ if (smVer != null && !"".equals(smVer))
+ service = serviceRepo.findFirstByModelVersionAndModelInvariantUUID(smVer, smiUuid);
+ else
service = serviceRepo.findFirstByModelInvariantUUIDOrderByModelVersionDesc(smiUuid);
else if (smName != null && !"".equals(smName)) {
- if (smVer != null && !"".equals(smVer))
+ if (smVer != null && !"".equals(smVer))
service = serviceRepo.findByModelNameAndModelVersion(smName, smVer);
- else
- service = serviceRepo.findFirstByModelNameOrderByModelVersionDesc(smName);
- }
- else {
- throw(new Exception(NO_MATCHING_PARAMETERS));
+ else
+ service = serviceRepo.findFirstByModelNameOrderByModelVersionDesc(smName);
+ } else {
+ throw (new Exception(NO_MATCHING_PARAMETERS));
}
if (service == null && ret.isEmpty()) {
respStatus = HttpStatus.SC_NOT_FOUND;
qryResp = new QueryServiceVnfs();
- }else if( service == null && !ret.isEmpty()){
- qryResp = new QueryServiceVnfs(ret);
+ } else if (service == null && !ret.isEmpty()) {
+ qryResp = new QueryServiceVnfs(ret);
} else if (service != null) {
- qryResp = new QueryServiceVnfs(service.getVnfCustomizations());
+ qryResp = new QueryServiceVnfs(service.getVnfCustomizations());
}
- logger.debug ("serviceVnfs qryResp= {}", qryResp);
+ logger.debug("serviceVnfs qryResp= {}", qryResp);
return respond(version, respStatus, isArray, qryResp);
} catch (Exception e) {
logger.error("Exception - queryServiceVnfs", e);
- CatalogQueryException excResp = new CatalogQueryException(e.getMessage(), CatalogQueryExceptionCategory.INTERNAL, Boolean.FALSE, null);
- return Response
- .status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity(new GenericEntity<CatalogQueryException>(excResp) {})
- .build();
+ CatalogQueryException excResp = new CatalogQueryException(e.getMessage(),
+ CatalogQueryExceptionCategory.INTERNAL, Boolean.FALSE, null);
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
+ .entity(new GenericEntity<CatalogQueryException>(excResp) {}).build();
}
}
@GET
@Path("networkResources/{networkModelCustomizationUuid}")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Transactional( readOnly = true)
- public Response serviceNetworks (
- @PathParam("version") String version,
- @PathParam("networkModelCustomizationUuid") String nUuid
- ) {
- return serviceNetworksImpl (version, !IS_ARRAY, nUuid, null, null, null, null);
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Transactional(readOnly = true)
+ public Response serviceNetworks(@PathParam("version") String version,
+ @PathParam("networkModelCustomizationUuid") String nUuid) {
+ return serviceNetworksImpl(version, !IS_ARRAY, nUuid, null, null, null, null);
}
@GET
@Path("serviceNetworks")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Transactional( readOnly = true)
- public Response serviceNetworks (
- @PathParam("version") String version,
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Transactional(readOnly = true)
+ public Response serviceNetworks(@PathParam("version") String version,
@QueryParam("networkModelCustomizationUuid") String networkModelCustomizationUuid,
- @QueryParam("networkType") String networkType,
- @QueryParam("networkModelName") String networkModelName,
+ @QueryParam("networkType") String networkType, @QueryParam("networkModelName") String networkModelName,
@QueryParam("serviceModelUuid") String serviceModelUuid,
@QueryParam("serviceModelInvariantUuid") String serviceModelInvariantUuid,
@QueryParam("serviceModelVersion") String serviceModelVersion,
- @QueryParam("networkModelVersion") String networkModelVersion
- ) {
+ @QueryParam("networkModelVersion") String networkModelVersion) {
if (networkModelName != null && !"".equals(networkModelName)) {
networkType = networkModelName;
}
- return serviceNetworksImpl (version, IS_ARRAY, networkModelCustomizationUuid, networkType, serviceModelUuid, serviceModelInvariantUuid, serviceModelVersion);
+ return serviceNetworksImpl(version, IS_ARRAY, networkModelCustomizationUuid, networkType, serviceModelUuid,
+ serviceModelInvariantUuid, serviceModelVersion);
}
- public Response serviceNetworksImpl (String version, boolean isArray, String networkModelCustomizationUuid, String networkType, String serviceModelUuid, String serviceModelInvariantUuid, String serviceModelVersion) {
+ public Response serviceNetworksImpl(String version, boolean isArray, String networkModelCustomizationUuid,
+ String networkType, String serviceModelUuid, String serviceModelInvariantUuid, String serviceModelVersion) {
QueryServiceNetworks qryResp;
int respStatus = HttpStatus.SC_OK;
String uuid = "";
List<NetworkResourceCustomization> ret = new ArrayList<>();
Service service = null;
- try{
+ try {
if (networkModelCustomizationUuid != null && !"".equals(networkModelCustomizationUuid)) {
- uuid = networkModelCustomizationUuid;
+ uuid = networkModelCustomizationUuid;
ret = networkCustomizationRepo.findByModelCustomizationUUID(networkModelCustomizationUuid);
- }else if (networkType != null && !"".equals(networkType)) {
- uuid = networkType;
- NetworkResource networkResources = networkResourceRepo.findFirstByModelNameOrderByModelVersionDesc(networkType);
- if(networkResources != null)
- ret=networkResources.getNetworkResourceCustomization();
- }
- else if (serviceModelInvariantUuid != null && !"".equals(serviceModelInvariantUuid)) {
+ } else if (networkType != null && !"".equals(networkType)) {
+ uuid = networkType;
+ NetworkResource networkResources =
+ networkResourceRepo.findFirstByModelNameOrderByModelVersionDesc(networkType);
+ if (networkResources != null)
+ ret = networkResources.getNetworkResourceCustomization();
+ } else if (serviceModelInvariantUuid != null && !"".equals(serviceModelInvariantUuid)) {
uuid = serviceModelInvariantUuid;
- if (serviceModelVersion != null && !"".equals(serviceModelVersion)) {
+ if (serviceModelVersion != null && !"".equals(serviceModelVersion)) {
service = serviceRepo.findFirstByModelVersionAndModelInvariantUUID(serviceModelVersion, uuid);
- }
- else {
+ } else {
service = serviceRepo.findFirstByModelInvariantUUIDOrderByModelVersionDesc(uuid);
}
- }else if (serviceModelUuid != null && !"".equals(serviceModelUuid)) {
- uuid = serviceModelUuid;
+ } else if (serviceModelUuid != null && !"".equals(serviceModelUuid)) {
+ uuid = serviceModelUuid;
service = serviceRepo.findOneByModelUUID(serviceModelUuid);
- }
- else {
- throw(new Exception(NO_MATCHING_PARAMETERS));
+ } else {
+ throw (new Exception(NO_MATCHING_PARAMETERS));
}
- if(service != null)
+ if (service != null)
ret = service.getNetworkCustomizations();
if (ret == null || ret.isEmpty()) {
- logger.debug ("serviceNetworks not found");
+ logger.debug("serviceNetworks not found");
respStatus = HttpStatus.SC_NOT_FOUND;
qryResp = new QueryServiceNetworks();
- } else {
+ } else {
qryResp = new QueryServiceNetworks(ret);
- logger.debug ("serviceNetworks found qryResp= {}", qryResp);
+ logger.debug("serviceNetworks found qryResp= {}", qryResp);
}
return respond(version, respStatus, isArray, qryResp);
} catch (Exception e) {
- logger.error ("Exception - queryServiceNetworks", e);
- CatalogQueryException excResp = new CatalogQueryException(e.getMessage(), CatalogQueryExceptionCategory.INTERNAL, Boolean.FALSE, null);
- return Response
- .status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity(new GenericEntity<CatalogQueryException>(excResp) {})
- .build();
+ logger.error("Exception - queryServiceNetworks", e);
+ CatalogQueryException excResp = new CatalogQueryException(e.getMessage(),
+ CatalogQueryExceptionCategory.INTERNAL, Boolean.FALSE, null);
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
+ .entity(new GenericEntity<CatalogQueryException>(excResp) {}).build();
}
}
@GET
@Path("serviceResources")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Transactional(readOnly = true)
- public Response serviceResources(
- @PathParam("version") String version,
+ public Response serviceResources(@PathParam("version") String version,
@QueryParam("serviceModelUuid") String modelUUID,
@QueryParam("serviceModelInvariantUuid") String modelInvariantUUID,
@QueryParam("serviceModelVersion") String modelVersion) {
@@ -303,11 +284,11 @@ public class CatalogDbAdapterRest {
String uuid = "";
ServiceMacroHolder ret = new ServiceMacroHolder();
- try{
+ try {
if (modelUUID != null && !"".equals(modelUUID)) {
uuid = modelUUID;
- logger.debug ("Query serviceMacroHolder getAllResourcesByServiceModelUuid serviceModelUuid: {}" , uuid);
- Service serv =serviceRepo.findOneByModelUUID(uuid);
+ logger.debug("Query serviceMacroHolder getAllResourcesByServiceModelUuid serviceModelUuid: {}", uuid);
+ Service serv = serviceRepo.findOneByModelUUID(uuid);
if (serv != null) {
ret.setNetworkResourceCustomizations(new ArrayList(serv.getNetworkCustomizations()));
@@ -315,163 +296,149 @@ public class CatalogDbAdapterRest {
ret.setAllottedResourceCustomizations(new ArrayList(serv.getAllottedCustomizations()));
}
ret.setService(serv);
- }
- else if (modelInvariantUUID != null && !"".equals(modelInvariantUUID)) {
+ } else if (modelInvariantUUID != null && !"".equals(modelInvariantUUID)) {
uuid = modelInvariantUUID;
if (modelVersion != null && !"".equals(modelVersion)) {
- logger.debug ("Query serviceMacroHolder getAllResourcesByServiceModelInvariantUuid serviceModelInvariantUuid: {} serviceModelVersion: {}",uuid, modelVersion);
+ logger.debug(
+ "Query serviceMacroHolder getAllResourcesByServiceModelInvariantUuid serviceModelInvariantUuid: {} serviceModelVersion: {}",
+ uuid, modelVersion);
Service serv = serviceRepo.findFirstByModelVersionAndModelInvariantUUID(modelVersion, uuid);
ret.setService(serv);
- }
- else {
- logger.debug ("Query serviceMacroHolder getAllResourcesByServiceModelInvariantUuid serviceModelUuid: {}" , uuid);
+ } else {
+ logger.debug(
+ "Query serviceMacroHolder getAllResourcesByServiceModelInvariantUuid serviceModelUuid: {}",
+ uuid);
Service serv = serviceRepo.findFirstByModelInvariantUUIDOrderByModelVersionDesc(uuid);
ret.setService(serv);
}
- }
- else {
- throw(new Exception(NO_MATCHING_PARAMETERS));
+ } else {
+ throw (new Exception(NO_MATCHING_PARAMETERS));
}
if (ret.getService() == null) {
- logger.debug ("serviceMacroHolder not found");
+ logger.debug("serviceMacroHolder not found");
respStatus = HttpStatus.SC_NOT_FOUND;
qryResp = new QueryServiceMacroHolder();
} else {
qryResp = new QueryServiceMacroHolder(ret);
- logger.debug ("serviceMacroHolder qryResp= {}", qryResp);
+ logger.debug("serviceMacroHolder qryResp= {}", qryResp);
}
return respond(version, respStatus, IS_ARRAY, qryResp);
} catch (Exception e) {
- logger.error ("Exception - queryServiceMacroHolder", e);
- CatalogQueryException excResp = new CatalogQueryException(e.getMessage(), CatalogQueryExceptionCategory.INTERNAL, Boolean.FALSE, null);
- return Response
- .status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity(new GenericEntity<CatalogQueryException>(excResp){} )
- .build();
+ logger.error("Exception - queryServiceMacroHolder", e);
+ CatalogQueryException excResp = new CatalogQueryException(e.getMessage(),
+ CatalogQueryExceptionCategory.INTERNAL, Boolean.FALSE, null);
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
+ .entity(new GenericEntity<CatalogQueryException>(excResp) {}).build();
}
}
@GET
@Path("allottedResources/{arModelCustomizationUuid}")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Transactional( readOnly = true)
- public Response serviceAllottedResources (
- @PathParam("version") String version,
- @PathParam("arModelCustomizationUuid") String aUuid
- ) {
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Transactional(readOnly = true)
+ public Response serviceAllottedResources(@PathParam("version") String version,
+ @PathParam("arModelCustomizationUuid") String aUuid) {
return serviceAllottedResourcesImpl(version, !IS_ARRAY, aUuid, null, null, null);
}
@GET
@Path("serviceAllottedResources")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Transactional( readOnly = true)
- public Response serviceAllottedResources(
- @PathParam("version") String version,
- @QueryParam("serviceModelUuid") String smUuid,
- @QueryParam("serviceModelInvariantUuid") String smiUuid,
- @QueryParam("serviceModelVersion") String smVer,
- @QueryParam("arModelCustomizationUuid") String aUuid
- ) {
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Transactional(readOnly = true)
+ public Response serviceAllottedResources(@PathParam("version") String version,
+ @QueryParam("serviceModelUuid") String smUuid, @QueryParam("serviceModelInvariantUuid") String smiUuid,
+ @QueryParam("serviceModelVersion") String smVer, @QueryParam("arModelCustomizationUuid") String aUuid) {
return serviceAllottedResourcesImpl(version, IS_ARRAY, aUuid, smUuid, smiUuid, smVer);
}
- public Response serviceAllottedResourcesImpl(String version, boolean isArray, String aUuid, String smUuid, String serviceModelInvariantUuid, String smVer) {
+ public Response serviceAllottedResourcesImpl(String version, boolean isArray, String aUuid, String smUuid,
+ String serviceModelInvariantUuid, String smVer) {
QueryAllottedResourceCustomization qryResp;
int respStatus = HttpStatus.SC_OK;
String uuid = "";
List<AllottedResourceCustomization> ret = new ArrayList<>();
Service service = null;
- try{
+ try {
if (smUuid != null && !"".equals(smUuid)) {
- uuid = smUuid;
- service = serviceRepo.findFirstOneByModelUUIDOrderByModelVersionDesc(uuid);
- }
- else if (serviceModelInvariantUuid != null && !"".equals(serviceModelInvariantUuid)) {
+ uuid = smUuid;
+ service = serviceRepo.findFirstOneByModelUUIDOrderByModelVersionDesc(uuid);
+ } else if (serviceModelInvariantUuid != null && !"".equals(serviceModelInvariantUuid)) {
uuid = serviceModelInvariantUuid;
- if (smVer != null && !"".equals(smVer)) {
+ if (smVer != null && !"".equals(smVer)) {
service = serviceRepo.findFirstByModelVersionAndModelInvariantUUID(smVer, uuid);
- }
- else {
+ } else {
service = serviceRepo.findFirstByModelInvariantUUIDOrderByModelVersionDesc(uuid);
}
- }
- else if (aUuid != null && !"".equals(aUuid)) {
- uuid = aUuid;
+ } else if (aUuid != null && !"".equals(aUuid)) {
+ uuid = aUuid;
ret = allottedCustomizationRepo.findByModelCustomizationUUID(uuid);
- }
- else {
- throw(new Exception(NO_MATCHING_PARAMETERS));
+ } else {
+ throw (new Exception(NO_MATCHING_PARAMETERS));
}
- if(service != null)
- ret=service.getAllottedCustomizations();
+ if (service != null)
+ ret = service.getAllottedCustomizations();
if (ret == null || ret.isEmpty()) {
- logger.debug ("AllottedResourceCustomization not found");
+ logger.debug("AllottedResourceCustomization not found");
respStatus = HttpStatus.SC_NOT_FOUND;
qryResp = new QueryAllottedResourceCustomization();
- } else {
+ } else {
qryResp = new QueryAllottedResourceCustomization(ret);
- logger.debug ("AllottedResourceCustomization qryResp= {}", qryResp);
- }
+ logger.debug("AllottedResourceCustomization qryResp= {}", qryResp);
+ }
return respond(version, respStatus, isArray, qryResp);
} catch (Exception e) {
- logger.error ("Exception - queryAllottedResourceCustomization", e);
- CatalogQueryException excResp = new CatalogQueryException(e.getMessage(), CatalogQueryExceptionCategory.INTERNAL, Boolean.FALSE, null);
- return Response
- .status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity(new GenericEntity<CatalogQueryException>(excResp) {})
- .build();
+ logger.error("Exception - queryAllottedResourceCustomization", e);
+ CatalogQueryException excResp = new CatalogQueryException(e.getMessage(),
+ CatalogQueryExceptionCategory.INTERNAL, Boolean.FALSE, null);
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
+ .entity(new GenericEntity<CatalogQueryException>(excResp) {}).build();
}
}
@GET
@Path("vfModules")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Transactional( readOnly = true)
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Transactional(readOnly = true)
public Response vfModules(@QueryParam("vfModuleModelName") String vfModuleModelName) {
QueryVfModule qryResp;
int respStatus = HttpStatus.SC_OK;
- List<VfModuleCustomization> ret = null;
- try{
- if(vfModuleModelName != null && !"".equals(vfModuleModelName)){
+ List<VfModuleCustomization> ret = null;
+ try {
+ if (vfModuleModelName != null && !"".equals(vfModuleModelName)) {
VfModule vfModule = vfModuleRepo.findFirstByModelNameOrderByModelVersionDesc(vfModuleModelName);
- if(vfModule != null)
- ret = vfModule.getVfModuleCustomization();
- }else{
- throw(new Exception(NO_MATCHING_PARAMETERS));
+ if (vfModule != null)
+ ret = vfModule.getVfModuleCustomization();
+ } else {
+ throw (new Exception(NO_MATCHING_PARAMETERS));
}
- if(ret == null || ret.isEmpty()){
- logger.debug ("vfModules not found");
+ if (ret == null || ret.isEmpty()) {
+ logger.debug("vfModules not found");
respStatus = HttpStatus.SC_NOT_FOUND;
qryResp = new QueryVfModule();
- }else{
- qryResp = new QueryVfModule(ret);
- if(logger.isDebugEnabled())
- logger.debug ("vfModules tojsonstring is: {}", qryResp.JSON2(false, false));
- }
- return Response
- .status(respStatus)
- .entity(qryResp.JSON2(false, false))
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .build();
- }catch(Exception e){
- logger.error ("Exception during query VfModules by vfModuleModuleName: ", e);
- CatalogQueryException excResp = new CatalogQueryException(e.getMessage(), CatalogQueryExceptionCategory.INTERNAL, Boolean.FALSE, null);
- return Response
- .status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity(new GenericEntity<CatalogQueryException>(excResp) {})
- .build();
+ } else {
+ qryResp = new QueryVfModule(ret);
+ if (logger.isDebugEnabled())
+ logger.debug("vfModules tojsonstring is: {}", qryResp.JSON2(false, false));
+ }
+ return Response.status(respStatus).entity(qryResp.JSON2(false, false))
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).build();
+ } catch (Exception e) {
+ logger.error("Exception during query VfModules by vfModuleModuleName: ", e);
+ CatalogQueryException excResp = new CatalogQueryException(e.getMessage(),
+ CatalogQueryExceptionCategory.INTERNAL, Boolean.FALSE, null);
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
+ .entity(new GenericEntity<CatalogQueryException>(excResp) {}).build();
}
}
+
/**
- * Get the tosca csar info from catalog
- * <br>
+ * Get the tosca csar info from catalog <br>
*
* @param smUuid service model uuid
* @return the tosca csar information of the serivce.
@@ -479,13 +446,13 @@ public class CatalogDbAdapterRest {
*/
@GET
@Path("serviceToscaCsar")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response serviceToscaCsar(@QueryParam("serviceModelUuid") String smUuid) {
int respStatus = HttpStatus.SC_OK;
String entity = "";
try {
if (smUuid != null && !"".equals(smUuid)) {
- logger.debug("Query Csar by service model uuid: {}",smUuid);
+ logger.debug("Query Csar by service model uuid: {}", smUuid);
Service service = serviceRepo.findFirstOneByModelUUIDOrderByModelVersionDesc(smUuid);
@@ -504,26 +471,19 @@ public class CatalogDbAdapterRest {
} else {
throw (new Exception("Incoming parameter is null or blank"));
}
- return Response
- .status(respStatus)
- .entity(entity)
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .build();
+ return Response.status(respStatus).entity(entity)
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).build();
} catch (Exception e) {
logger.error("Exception during query csar by service model uuid: ", e);
CatalogQueryException excResp = new CatalogQueryException(e.getMessage(),
CatalogQueryExceptionCategory.INTERNAL, Boolean.FALSE, null);
- return Response
- .status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity(new GenericEntity<CatalogQueryException>(excResp) {
- })
- .build();
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
+ .entity(new GenericEntity<CatalogQueryException>(excResp) {}).build();
}
}
/**
- * Get the resource recipe info from catalog
- * <br>
+ * Get the resource recipe info from catalog <br>
*
* @param rmUuid resource model uuid
* @return the recipe information of the resource.
@@ -531,19 +491,21 @@ public class CatalogDbAdapterRest {
*/
@GET
@Path("resourceRecipe")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- public Response resourceRecipe(@QueryParam("resourceModelUuid") String rmUuid, @QueryParam("action") String action) {
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ public Response resourceRecipe(@QueryParam("resourceModelUuid") String rmUuid,
+ @QueryParam("action") String action) {
int respStatus = HttpStatus.SC_OK;
String entity = "";
try {
if (rmUuid != null && !"".equals(rmUuid)) {
logger.debug("Query recipe by resource model uuid: {}", rmUuid);
- //check vnf and network and ar, the resource could be any resource.
+ // check vnf and network and ar, the resource could be any resource.
Recipe recipe = null;
VnfResource vnf = vnfResourceRepo.findResourceByModelUUID(rmUuid);
if (vnf != null) {
- recipe = vnfRecipeRepo.findFirstVnfRecipeByNfRoleAndActionAndVersionStr(vnf.getModelName(), action, vnf.getModelVersion());
+ recipe = vnfRecipeRepo.findFirstVnfRecipeByNfRoleAndActionAndVersionStr(vnf.getModelName(), action,
+ vnf.getModelVersion());
// for network service fetch the default recipe
if (recipe == null && vnf.getSubCategory().equalsIgnoreCase(NETWORK_SERVICE)) {
@@ -555,8 +517,9 @@ public class CatalogDbAdapterRest {
if (null == recipe) {
NetworkResource nResource = networkResourceRepo.findResourceByModelUUID(rmUuid);
- if(nResource != null) {
- recipe = networkRecipeRepo.findFirstByModelNameAndActionAndVersionStr(nResource.getModelName(), action, nResource.getModelVersion());
+ if (nResource != null) {
+ recipe = networkRecipeRepo.findFirstByModelNameAndActionAndVersionStr(nResource.getModelName(),
+ action, nResource.getModelVersion());
// for network fetch the default recipe
if (recipe == null) {
@@ -568,7 +531,8 @@ public class CatalogDbAdapterRest {
if (null == recipe) {
AllottedResource arResource = arResourceRepo.findResourceByModelUUID(rmUuid);
if (arResource != null) {
- recipe = arRecipeRepo.findByModelNameAndActionAndVersion(arResource.getModelName(), action, arResource.getModelVersion());
+ recipe = arRecipeRepo.findByModelNameAndActionAndVersion(arResource.getModelName(), action,
+ arResource.getModelVersion());
}
}
if (recipe != null) {
@@ -580,20 +544,14 @@ public class CatalogDbAdapterRest {
} else {
throw new Exception("Incoming parameter is null or blank");
}
- return Response
- .status(respStatus)
- .entity(entity)
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .build();
+ return Response.status(respStatus).entity(entity)
+ .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).build();
} catch (Exception e) {
logger.error("Exception during query recipe by resource model uuid: ", e);
CatalogQueryException excResp = new CatalogQueryException(e.getMessage(),
CatalogQueryExceptionCategory.INTERNAL, Boolean.FALSE, null);
- return Response
- .status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity(new GenericEntity<CatalogQueryException>(excResp) {
- })
- .build();
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
+ .entity(new GenericEntity<CatalogQueryException>(excResp) {}).build();
}
}
}
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/AllTestsTestSuite.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/AllTestsTestSuite.java
index 3c05f8164b..4ffa38dd96 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/AllTestsTestSuite.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/AllTestsTestSuite.java
@@ -19,14 +19,14 @@
*/
package org.onap.so.adapters.catalogdb;
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses("**/*Test.class")
public class AllTestsTestSuite {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/CatalogDbAdapterBaseTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/CatalogDbAdapterBaseTest.java
index b2a20681d9..3fb156d68a 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/CatalogDbAdapterBaseTest.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/CatalogDbAdapterBaseTest.java
@@ -12,10 +12,10 @@ import org.springframework.test.context.junit4.SpringRunner;
@ActiveProfiles("test")
public class CatalogDbAdapterBaseTest {
- @LocalServerPort
- protected int port;
-
-
- @Test
- public void testNothing(){}
+ @LocalServerPort
+ protected int port;
+
+
+ @Test
+ public void testNothing() {}
}
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/EmbeddedMariaDbConfig.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/EmbeddedMariaDbConfig.java
index 5d9eedb20f..eaf1bb3e4b 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/EmbeddedMariaDbConfig.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/EmbeddedMariaDbConfig.java
@@ -19,6 +19,7 @@
*/
package org.onap.so.adapters.catalogdb;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
@@ -30,7 +31,7 @@ import org.springframework.context.annotation.Profile;
import javax.sql.DataSource;
@Configuration
-@Profile({"test","local"})
+@Profile({"test", "local"})
public class EmbeddedMariaDbConfig {
@Bean
@@ -40,21 +41,16 @@ public class EmbeddedMariaDbConfig {
@Bean
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
}
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java
index bd8c5bc3e3..145ba50583 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java
@@ -29,13 +29,10 @@ import static org.onap.so.logger.MdcConstants.RESPONSECODE;
import static org.onap.so.logger.MdcConstants.RESPONSEDESC;
import static org.onap.so.logger.MdcConstants.SERVICE_NAME;
import static org.onap.so.logger.MdcConstants.STATUSCODE;
-
import java.io.IOException;
import java.util.Map;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.json.JSONException;
import org.junit.Test;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
@@ -48,799 +45,801 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
-
import ch.qos.logback.classic.spi.ILoggingEvent;
public class CatalogDBRestTest extends CatalogDbAdapterBaseTest {
- private static final String ECOMP_MSO_CATALOG_V2_VF_MODULES = "ecomp/mso/catalog/v2/vfModules";
+ private static final String ECOMP_MSO_CATALOG_V2_VF_MODULES = "ecomp/mso/catalog/v2/vfModules";
+
+ private static final String ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES =
+ "ecomp/mso/catalog/v2/serviceAllottedResources";
+
+ private static final String ECOMP_MSO_CATALOG_V2_RESOURCE_RECEIPE = "ecomp/mso/catalog/v2/resourceRecipe";
+
+ private static final String ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS = "ecomp/mso/catalog/v2/serviceNetworks";
+
+ private static final String ECOMP_MSO_CATALOG_V2_SERVICE_VNFS = "ecomp/mso/catalog/v2/serviceVnfs";
+
+ private static final String ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES = "ecomp/mso/catalog/v2/serviceResources";
+
+ TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
+
+ HttpHeaders headers = new HttpHeaders();
- private static final String ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES = "ecomp/mso/catalog/v2/serviceAllottedResources";
+ private final String expectedServiceResourceResponse =
+ "{\r\n\"serviceResources\": {\r\n\"modelInfo\": {\r\n\"modelName\": \"MSOTADevInfra_vSAMP10a_Service\",\r\n\"modelUuid\": \"5df8b6de-2083-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"9647dfc4-2083-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"1.0\"\r\n},\r\n\"serviceType\": \"NA\",\r\n\"serviceRole\": \"NA\",\r\n\"environmentContext\": \"Luna\",\r\n\"workloadContext\": \"Oxygen\",\r\n\"serviceVnfs\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10a\",\r\n\"modelUuid\": \"ff2ae348-214a-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"2fff5b20-214b-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"68dc9a92-214c-11e7-93ae-92361f002671\",\r\n\"modelInstanceName\": \"vSAMP10a 1\"\r\n},\r\n\"toscaNodeType\": \"VF\",\r\n\"nfFunction\": \"vSAMP\",\r\n\"nfType\": \"vSAMP\",\r\n\"nfRole\": \"vSAMP\",\r\n\"nfNamingCode\": \"vSAMP\",\r\n\"multiStageDesign\": null,\r\n\"vfModules\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::base::module-0\",\r\n\"modelUuid\": \"20c4431c-246d-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"cb82ffd8-252a-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": true,\r\n\"vfModuleLabel\": \"base\",\r\n\"initialCount\": 1,\r\n\"hasVolumeGroup\": false\r\n},\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::PCM::module-1\",\r\n\"modelUuid\": \"066de97e-253e-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"64efd51a-2544-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"b4ea86b4-253f-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": false,\r\n\"vfModuleLabel\": \"PCM\",\r\n\"initialCount\": 0,\r\n\"hasVolumeGroup\": false\r\n}\r\n]\r\n}\r\n],\r\n\"serviceNetworks\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"CONTRAIL30_GNDIRECT\",\r\n\"modelUuid\": \"10b36f65-f4e6-4be6-ae49-9596dc1c47fc\",\r\n\"modelInvariantUuid\": \"ce4ff476-9641-4e60-b4d5-b4abbec1271d\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"3bdbb104-476c-483e-9f8b-c095b3d308ac\",\r\n\"modelInstanceName\": \"CONTRAIL30_GNDIRECT 9\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"networkType\": \"\",\r\n\"networkTechnology\": \"\",\r\n\"networkRole\": \"\",\r\n\"networkScope\": \"\"\r\n}\r\n],\r\n\"serviceAllottedResources\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"Tunnel_Xconn\",\r\n\"modelUuid\": \"f6b7d4c6-e8a4-46e2-81bc-31cad5072842\",\r\n\"modelInvariantUuid\": \"b7a1b78e-6b6b-4b36-9698-8c9530da14af\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"367a8ba9-057a-4506-b106-fbae818597c6\",\r\n\"modelInstanceName\": \"Sec_Tunnel_Xconn 11\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"allottedResourceType\": \"\",\r\n\"allottedResourceRole\": null,\r\n\"providingServiceModelName\": null,\r\n\"providingServiceModelInvariantUuid\": null,\r\n\"providingServiceModelUuid\": null,\r\n\"nfFunction\": null,\r\n\"nfType\": null,\r\n\"nfRole\": null,\r\n\"nfNamingCode\": null\r\n}\r\n]\r\n}\r\n}";
- private static final String ECOMP_MSO_CATALOG_V2_RESOURCE_RECEIPE = "ecomp/mso/catalog/v2/resourceRecipe";
+ private final String expectedServiceResourceResponsev2 =
+ "{\r\n\"serviceResources\": {\r\n\"modelInfo\": {\r\n\"modelName\": \"MSOTADevInfra_vSAMP10a_Service\",\r\n\"modelUuid\": \"5df8b6de-2083-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"9647dfc4-2083-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2.0\"\r\n},\r\n\"serviceType\": \"NA\",\r\n\"serviceRole\": \"NA\",\r\n\"environmentContext\": \"Luna\",\r\n\"workloadContext\": \"Oxygen\",\r\n\"serviceVnfs\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10a\",\r\n\"modelUuid\": \"ff2ae348-214a-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"2fff5b20-214b-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2.0\",\r\n\"modelCustomizationUuid\": \"68dc9a92-214c-11e7-93ae-92361f002672\",\r\n\"modelInstanceName\": \"vSAMP10a 2\"\r\n},\r\n\"toscaNodeType\": \"VF\",\r\n\"nfFunction\": \"vSAMP\",\r\n\"nfType\": \"vSAMP\",\r\n\"nfRole\": \"vSAMP\",\r\n\"nfNamingCode\": \"vSAMP\",\r\n\"multiStageDesign\": null,\r\n\"vfModules\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::base::module-0\",\r\n\"modelUuid\": \"20c4431c-246d-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"cb82ffd8-252a-11e7-93ae-92361f002672\"\r\n},\r\n\"isBase\": true,\r\n\"vfModuleLabel\": \"base\",\r\n\"initialCount\": 1,\r\n\"hasVolumeGroup\": false\r\n},\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::PCM::module-1\",\r\n\"modelUuid\": \"066de97e-253e-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"64efd51a-2544-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"b4ea86b4-253f-11e7-93ae-92361f002672\"\r\n},\r\n\"isBase\": false,\r\n\"vfModuleLabel\": \"PCM\",\r\n\"initialCount\": 0,\r\n\"hasVolumeGroup\": false\r\n}\r\n]\r\n}\r\n],\r\n\"serviceNetworks\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"CONTRAIL30_GNDIRECT\",\r\n\"modelUuid\": \"10b36f65-f4e6-4be6-ae49-9596dc1c47fc\",\r\n\"modelInvariantUuid\": \"ce4ff476-9641-4e60-b4d5-b4abbec1271d\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"3bdbb104-476c-483e-9f8b-c095b3d308ac\",\r\n\"modelInstanceName\": \"CONTRAIL30_GNDIRECT 9\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"networkType\": \"\",\r\n\"networkTechnology\": \"\",\r\n\"networkRole\": \"\",\r\n\"networkScope\": \"\"\r\n}\r\n],\r\n\"serviceAllottedResources\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"Tunnel_Xconn\",\r\n\"modelUuid\": \"f6b7d4c6-e8a4-46e2-81bc-31cad5072842\",\r\n\"modelInvariantUuid\": \"b7a1b78e-6b6b-4b36-9698-8c9530da14af\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"367a8ba9-057a-4506-b106-fbae818597c6\",\r\n\"modelInstanceName\": \"Sec_Tunnel_Xconn 11\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"allottedResourceType\": \"\",\r\n\"allottedResourceRole\": null,\r\n\"providingServiceModelName\": null,\r\n\"providingServiceModelInvariantUuid\": null,\r\n\"providingServiceModelUuid\": null,\r\n\"nfFunction\": null,\r\n\"nfType\": null,\r\n\"nfRole\": null,\r\n\"nfNamingCode\": null\r\n}\r\n]\r\n}\r\n}";
- private static final String ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS = "ecomp/mso/catalog/v2/serviceNetworks";
- private static final String ECOMP_MSO_CATALOG_V2_SERVICE_VNFS = "ecomp/mso/catalog/v2/serviceVnfs";
+ private final String expectedServiceVnfResponse =
+ "{\r\n\"serviceVnfs\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10a\",\r\n\"modelUuid\": \"ff2ae348-214a-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"2fff5b20-214b-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"68dc9a92-214c-11e7-93ae-92361f002671\",\r\n\"modelInstanceName\": \"vSAMP10a 1\"\r\n},\r\n\"toscaNodeType\": \"VF\",\r\n\"nfFunction\": \"vSAMP\",\r\n\"nfType\": \"vSAMP\",\r\n\"nfRole\": \"vSAMP\",\r\n\"nfNamingCode\": \"vSAMP\",\r\n\"multiStageDesign\": null,\r\n\"vfModules\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::base::module-0\",\r\n\"modelUuid\": \"20c4431c-246d-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"cb82ffd8-252a-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": true,\r\n\"vfModuleLabel\": \"base\",\r\n\"initialCount\": 1,\r\n\"hasVolumeGroup\": false\r\n},\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::PCM::module-1\",\r\n\"modelUuid\": \"066de97e-253e-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"64efd51a-2544-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"b4ea86b4-253f-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": false,\r\n\"vfModuleLabel\": \"PCM\",\r\n\"initialCount\": 0,\r\n\"hasVolumeGroup\": false\r\n}\r\n]\r\n}\r\n]\r\n}";
- private static final String ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES = "ecomp/mso/catalog/v2/serviceResources";
+ private final String expectedServiceVnfResponseV3 =
+ "{\r\n\"serviceVnfs\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10a\",\r\n\"modelUuid\": \"ff2ae348-214a-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"2fff5b20-214b-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2.0\",\r\n\"modelCustomizationUuid\": \"68dc9a92-214c-11e7-93ae-92361f002672\",\r\n\"modelInstanceName\": \"vSAMP10a 2\"\r\n},\r\n\"toscaNodeType\": \"VF\",\r\n\"nfFunction\": \"vSAMP\",\r\n\"nfType\": \"vSAMP\",\r\n\"nfRole\": \"vSAMP\",\r\n\"nfNamingCode\": \"vSAMP\",\r\n\"multiStageDesign\": null,\r\n\"vfModules\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::base::module-0\",\r\n\"modelUuid\": \"20c4431c-246d-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"cb82ffd8-252a-11e7-93ae-92361f002672\"\r\n},\r\n\"isBase\": true,\r\n\"vfModuleLabel\": \"base\",\r\n\"initialCount\": 1,\r\n\"hasVolumeGroup\": false\r\n},\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::PCM::module-1\",\r\n\"modelUuid\": \"066de97e-253e-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"64efd51a-2544-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"b4ea86b4-253f-11e7-93ae-92361f002672\"\r\n},\r\n\"isBase\": false,\r\n\"vfModuleLabel\": \"PCM\",\r\n\"initialCount\": 0,\r\n\"hasVolumeGroup\": false\r\n}\r\n]\r\n}\r\n]\r\n}";
- TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
+ private final String expectedServiceNetworkResourceResponse =
+ "{\r\n\"serviceNetworks\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"CONTRAIL30_GNDIRECT\",\r\n\"modelUuid\": \"10b36f65-f4e6-4be6-ae49-9596dc1c47fc\",\r\n\"modelInvariantUuid\": \"ce4ff476-9641-4e60-b4d5-b4abbec1271d\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"3bdbb104-476c-483e-9f8b-c095b3d308ac\",\r\n\"modelInstanceName\": \"CONTRAIL30_GNDIRECT 9\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"networkType\": \"\",\r\n\"networkTechnology\": \"\",\r\n\"networkRole\": \"\",\r\n\"networkScope\": \"\"\r\n}\r\n]\r\n}";
- HttpHeaders headers = new HttpHeaders();
-
- private final String expectedServiceResourceResponse = "{\r\n\"serviceResources\": {\r\n\"modelInfo\": {\r\n\"modelName\": \"MSOTADevInfra_vSAMP10a_Service\",\r\n\"modelUuid\": \"5df8b6de-2083-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"9647dfc4-2083-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"1.0\"\r\n},\r\n\"serviceType\": \"NA\",\r\n\"serviceRole\": \"NA\",\r\n\"environmentContext\": \"Luna\",\r\n\"workloadContext\": \"Oxygen\",\r\n\"serviceVnfs\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10a\",\r\n\"modelUuid\": \"ff2ae348-214a-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"2fff5b20-214b-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"68dc9a92-214c-11e7-93ae-92361f002671\",\r\n\"modelInstanceName\": \"vSAMP10a 1\"\r\n},\r\n\"toscaNodeType\": \"VF\",\r\n\"nfFunction\": \"vSAMP\",\r\n\"nfType\": \"vSAMP\",\r\n\"nfRole\": \"vSAMP\",\r\n\"nfNamingCode\": \"vSAMP\",\r\n\"multiStageDesign\": null,\r\n\"vfModules\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::base::module-0\",\r\n\"modelUuid\": \"20c4431c-246d-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"cb82ffd8-252a-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": true,\r\n\"vfModuleLabel\": \"base\",\r\n\"initialCount\": 1,\r\n\"hasVolumeGroup\": false\r\n},\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::PCM::module-1\",\r\n\"modelUuid\": \"066de97e-253e-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"64efd51a-2544-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"b4ea86b4-253f-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": false,\r\n\"vfModuleLabel\": \"PCM\",\r\n\"initialCount\": 0,\r\n\"hasVolumeGroup\": false\r\n}\r\n]\r\n}\r\n],\r\n\"serviceNetworks\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"CONTRAIL30_GNDIRECT\",\r\n\"modelUuid\": \"10b36f65-f4e6-4be6-ae49-9596dc1c47fc\",\r\n\"modelInvariantUuid\": \"ce4ff476-9641-4e60-b4d5-b4abbec1271d\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"3bdbb104-476c-483e-9f8b-c095b3d308ac\",\r\n\"modelInstanceName\": \"CONTRAIL30_GNDIRECT 9\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"networkType\": \"\",\r\n\"networkTechnology\": \"\",\r\n\"networkRole\": \"\",\r\n\"networkScope\": \"\"\r\n}\r\n],\r\n\"serviceAllottedResources\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"Tunnel_Xconn\",\r\n\"modelUuid\": \"f6b7d4c6-e8a4-46e2-81bc-31cad5072842\",\r\n\"modelInvariantUuid\": \"b7a1b78e-6b6b-4b36-9698-8c9530da14af\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"367a8ba9-057a-4506-b106-fbae818597c6\",\r\n\"modelInstanceName\": \"Sec_Tunnel_Xconn 11\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"allottedResourceType\": \"\",\r\n\"allottedResourceRole\": null,\r\n\"providingServiceModelName\": null,\r\n\"providingServiceModelInvariantUuid\": null,\r\n\"providingServiceModelUuid\": null,\r\n\"nfFunction\": null,\r\n\"nfType\": null,\r\n\"nfRole\": null,\r\n\"nfNamingCode\": null\r\n}\r\n]\r\n}\r\n}";
+ private final String badQueryParamResponse =
+ "{\"messageId\":null,\"message\":\"no matching parameters\",\"category\":\"INTERNAL\",\"rolledBack\":false}\"";
- private final String expectedServiceResourceResponsev2 = "{\r\n\"serviceResources\": {\r\n\"modelInfo\": {\r\n\"modelName\": \"MSOTADevInfra_vSAMP10a_Service\",\r\n\"modelUuid\": \"5df8b6de-2083-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"9647dfc4-2083-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2.0\"\r\n},\r\n\"serviceType\": \"NA\",\r\n\"serviceRole\": \"NA\",\r\n\"environmentContext\": \"Luna\",\r\n\"workloadContext\": \"Oxygen\",\r\n\"serviceVnfs\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10a\",\r\n\"modelUuid\": \"ff2ae348-214a-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"2fff5b20-214b-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2.0\",\r\n\"modelCustomizationUuid\": \"68dc9a92-214c-11e7-93ae-92361f002672\",\r\n\"modelInstanceName\": \"vSAMP10a 2\"\r\n},\r\n\"toscaNodeType\": \"VF\",\r\n\"nfFunction\": \"vSAMP\",\r\n\"nfType\": \"vSAMP\",\r\n\"nfRole\": \"vSAMP\",\r\n\"nfNamingCode\": \"vSAMP\",\r\n\"multiStageDesign\": null,\r\n\"vfModules\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::base::module-0\",\r\n\"modelUuid\": \"20c4431c-246d-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"cb82ffd8-252a-11e7-93ae-92361f002672\"\r\n},\r\n\"isBase\": true,\r\n\"vfModuleLabel\": \"base\",\r\n\"initialCount\": 1,\r\n\"hasVolumeGroup\": false\r\n},\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::PCM::module-1\",\r\n\"modelUuid\": \"066de97e-253e-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"64efd51a-2544-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"b4ea86b4-253f-11e7-93ae-92361f002672\"\r\n},\r\n\"isBase\": false,\r\n\"vfModuleLabel\": \"PCM\",\r\n\"initialCount\": 0,\r\n\"hasVolumeGroup\": false\r\n}\r\n]\r\n}\r\n],\r\n\"serviceNetworks\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"CONTRAIL30_GNDIRECT\",\r\n\"modelUuid\": \"10b36f65-f4e6-4be6-ae49-9596dc1c47fc\",\r\n\"modelInvariantUuid\": \"ce4ff476-9641-4e60-b4d5-b4abbec1271d\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"3bdbb104-476c-483e-9f8b-c095b3d308ac\",\r\n\"modelInstanceName\": \"CONTRAIL30_GNDIRECT 9\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"networkType\": \"\",\r\n\"networkTechnology\": \"\",\r\n\"networkRole\": \"\",\r\n\"networkScope\": \"\"\r\n}\r\n],\r\n\"serviceAllottedResources\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"Tunnel_Xconn\",\r\n\"modelUuid\": \"f6b7d4c6-e8a4-46e2-81bc-31cad5072842\",\r\n\"modelInvariantUuid\": \"b7a1b78e-6b6b-4b36-9698-8c9530da14af\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"367a8ba9-057a-4506-b106-fbae818597c6\",\r\n\"modelInstanceName\": \"Sec_Tunnel_Xconn 11\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"allottedResourceType\": \"\",\r\n\"allottedResourceRole\": null,\r\n\"providingServiceModelName\": null,\r\n\"providingServiceModelInvariantUuid\": null,\r\n\"providingServiceModelUuid\": null,\r\n\"nfFunction\": null,\r\n\"nfType\": null,\r\n\"nfRole\": null,\r\n\"nfNamingCode\": null\r\n}\r\n]\r\n}\r\n}";
+ private final String expectedAllottedResponse =
+ "{\r\n\"serviceAllottedResources\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"Tunnel_Xconn\",\r\n\"modelUuid\": \"f6b7d4c6-e8a4-46e2-81bc-31cad5072842\",\r\n\"modelInvariantUuid\": \"b7a1b78e-6b6b-4b36-9698-8c9530da14af\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"367a8ba9-057a-4506-b106-fbae818597c6\",\r\n\"modelInstanceName\": \"Sec_Tunnel_Xconn 11\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"allottedResourceType\": \"\",\r\n\"allottedResourceRole\": null,\r\n\"providingServiceModelName\": null,\r\n\"providingServiceModelInvariantUuid\": null,\r\n\"providingServiceModelUuid\": null,\r\n\"nfFunction\": null,\r\n\"nfType\": null,\r\n\"nfRole\": null,\r\n\"nfNamingCode\": null\r\n}\r\n]\r\n}";
-
- private final String expectedServiceVnfResponse = "{\r\n\"serviceVnfs\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10a\",\r\n\"modelUuid\": \"ff2ae348-214a-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"2fff5b20-214b-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"68dc9a92-214c-11e7-93ae-92361f002671\",\r\n\"modelInstanceName\": \"vSAMP10a 1\"\r\n},\r\n\"toscaNodeType\": \"VF\",\r\n\"nfFunction\": \"vSAMP\",\r\n\"nfType\": \"vSAMP\",\r\n\"nfRole\": \"vSAMP\",\r\n\"nfNamingCode\": \"vSAMP\",\r\n\"multiStageDesign\": null,\r\n\"vfModules\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::base::module-0\",\r\n\"modelUuid\": \"20c4431c-246d-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"cb82ffd8-252a-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": true,\r\n\"vfModuleLabel\": \"base\",\r\n\"initialCount\": 1,\r\n\"hasVolumeGroup\": false\r\n},\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::PCM::module-1\",\r\n\"modelUuid\": \"066de97e-253e-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"64efd51a-2544-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"b4ea86b4-253f-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": false,\r\n\"vfModuleLabel\": \"PCM\",\r\n\"initialCount\": 0,\r\n\"hasVolumeGroup\": false\r\n}\r\n]\r\n}\r\n]\r\n}";
+ private final String serviceUUID = "5df8b6de-2083-11e7-93ae-92361f002671";
- private final String expectedServiceVnfResponseV3 = "{\r\n\"serviceVnfs\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10a\",\r\n\"modelUuid\": \"ff2ae348-214a-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"2fff5b20-214b-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2.0\",\r\n\"modelCustomizationUuid\": \"68dc9a92-214c-11e7-93ae-92361f002672\",\r\n\"modelInstanceName\": \"vSAMP10a 2\"\r\n},\r\n\"toscaNodeType\": \"VF\",\r\n\"nfFunction\": \"vSAMP\",\r\n\"nfType\": \"vSAMP\",\r\n\"nfRole\": \"vSAMP\",\r\n\"nfNamingCode\": \"vSAMP\",\r\n\"multiStageDesign\": null,\r\n\"vfModules\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::base::module-0\",\r\n\"modelUuid\": \"20c4431c-246d-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"cb82ffd8-252a-11e7-93ae-92361f002672\"\r\n},\r\n\"isBase\": true,\r\n\"vfModuleLabel\": \"base\",\r\n\"initialCount\": 1,\r\n\"hasVolumeGroup\": false\r\n},\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::PCM::module-1\",\r\n\"modelUuid\": \"066de97e-253e-11e7-93ae-92361f002672\",\r\n\"modelInvariantUuid\": \"64efd51a-2544-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"b4ea86b4-253f-11e7-93ae-92361f002672\"\r\n},\r\n\"isBase\": false,\r\n\"vfModuleLabel\": \"PCM\",\r\n\"initialCount\": 0,\r\n\"hasVolumeGroup\": false\r\n}\r\n]\r\n}\r\n]\r\n}";
-
- private final String expectedServiceNetworkResourceResponse = "{\r\n\"serviceNetworks\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"CONTRAIL30_GNDIRECT\",\r\n\"modelUuid\": \"10b36f65-f4e6-4be6-ae49-9596dc1c47fc\",\r\n\"modelInvariantUuid\": \"ce4ff476-9641-4e60-b4d5-b4abbec1271d\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"3bdbb104-476c-483e-9f8b-c095b3d308ac\",\r\n\"modelInstanceName\": \"CONTRAIL30_GNDIRECT 9\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"networkType\": \"\",\r\n\"networkTechnology\": \"\",\r\n\"networkRole\": \"\",\r\n\"networkScope\": \"\"\r\n}\r\n]\r\n}";
-
- private final String badQueryParamResponse = "{\"messageId\":null,\"message\":\"no matching parameters\",\"category\":\"INTERNAL\",\"rolledBack\":false}\"";
-
- private final String expectedAllottedResponse = "{\r\n\"serviceAllottedResources\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"Tunnel_Xconn\",\r\n\"modelUuid\": \"f6b7d4c6-e8a4-46e2-81bc-31cad5072842\",\r\n\"modelInvariantUuid\": \"b7a1b78e-6b6b-4b36-9698-8c9530da14af\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"367a8ba9-057a-4506-b106-fbae818597c6\",\r\n\"modelInstanceName\": \"Sec_Tunnel_Xconn 11\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"allottedResourceType\": \"\",\r\n\"allottedResourceRole\": null,\r\n\"providingServiceModelName\": null,\r\n\"providingServiceModelInvariantUuid\": null,\r\n\"providingServiceModelUuid\": null,\r\n\"nfFunction\": null,\r\n\"nfType\": null,\r\n\"nfRole\": null,\r\n\"nfNamingCode\": null\r\n}\r\n]\r\n}";
-
- private final String serviceUUID = "5df8b6de-2083-11e7-93ae-92361f002671";
+ private final String arResourceUUID = "25e2d69b-3b22-47b8-b4c9-7b14fd4a80df";
- private final String arResourceUUID = "25e2d69b-3b22-47b8-b4c9-7b14fd4a80df";
-
- private final String serviceInvariantUUID = "9647dfc4-2083-11e7-93ae-92361f002671";
-
- /* Health Check Resources Endpoint */
-
- @Test
- public void testHealthcheck() throws JSONException {
+ private final String serviceInvariantUUID = "9647dfc4-2083-11e7-93ae-92361f002671";
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ /* Health Check Resources Endpoint */
- ResponseEntity<String> response = restTemplate.exchange(
- createURLWithPort("/manage/health"),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- for(ILoggingEvent logEvent : TestAppender.events)
- if(logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor") &&
- logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")
- ){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+ @Test
+ public void testHealthcheck() throws JSONException {
+
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(createURLWithPort("/manage/health"), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ for (ILoggingEvent logEvent : TestAppender.events)
+ if (logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor")
+ && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.INSTANCE_UUID));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID));
- assertEquals("",mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME));
- assertEquals("/manage/health",mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME));
- assertEquals("INPROGRESS",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
- }else if(logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor") &&
- logEvent.getMarker()!= null && logEvent.getMarker().getName().equals("EXIT")){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+ assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME));
+ assertEquals("/manage/health", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME));
+ assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ } else if (logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor")
+ && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID));
- assertEquals("200",mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE));
- assertEquals("",mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME));
- assertEquals("/manage/health",mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME));
- assertEquals("COMPLETED",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ assertEquals("200", mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE));
+ assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME));
+ assertEquals("/manage/health", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME));
+ assertEquals("COMPLETED", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
}
- }
-
- /* Service Resources Endpoint */
-
- @Test
- public void testGetServiceModelUUID() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES))
- .queryParam("serviceModelUuid", serviceUUID);
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceResourceResponse, response.getBody().toString(), JSONCompareMode.LENIENT);
- }
-
- @Test
- public void testGetServiceInvariantUUIDAndVersion() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES))
- .queryParam("serviceModelInvariantUuid", "9647dfc4-2083-11e7-93ae-92361f002671").queryParam("serviceModelVersion", "1.0");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceResourceResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceInvariantUUID() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES))
- .queryParam("serviceModelInvariantUuid", "9647dfc4-2083-11e7-93ae-92361f002671");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceResourceResponsev2, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceInvariantUUIDEmtpyModelVer() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES))
- .queryParam("serviceModelInvariantUuid", "9647dfc4-2083-11e7-93ae-92361f002671").queryParam("serviceModelVersion", "");;
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceResourceResponsev2, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceModelUUID404() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- String expectedResponse = "\"serviceResources\": null";
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES))
- .queryParam("serviceModelUuid", "5df8b6de-2083-11e7-93");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.NOT_FOUND.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceBadQueryParams() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES))
- .queryParam("BadQueryParam", "5df8b6de-2083-11e7-93");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(badQueryParamResponse, response.getBody().toString(), false);
- }
-
- /* VNF Resources Endpoint */
-
- @Test
- public void testGetVNFResourcesByCustomizationUUID() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- String expectedResponse = "{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10a\",\r\n\"modelUuid\": \"ff2ae348-214a-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"2fff5b20-214b-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"68dc9a92-214c-11e7-93ae-92361f002671\",\r\n\"modelInstanceName\": \"vSAMP10a 1\"\r\n},\r\n\"toscaNodeType\": \"VF\",\r\n\"nfFunction\": \"vSAMP\",\r\n\"nfType\": \"vSAMP\",\r\n\"nfRole\": \"vSAMP\",\r\n\"nfNamingCode\": \"vSAMP\",\r\n\"multiStageDesign\": null,\r\n\"vfModules\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::base::module-0\",\r\n\"modelUuid\": \"20c4431c-246d-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"cb82ffd8-252a-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": true,\r\n\"vfModuleLabel\": \"base\",\r\n\"initialCount\": 1,\r\n\"hasVolumeGroup\": false\r\n},\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::PCM::module-1\",\r\n\"modelUuid\": \"066de97e-253e-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"64efd51a-2544-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"b4ea86b4-253f-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": false,\r\n\"vfModuleLabel\": \"PCM\",\r\n\"initialCount\": 0,\r\n\"hasVolumeGroup\": false\r\n}\r\n]\r\n}";
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("ecomp/mso/catalog/v2/vnfResources/68dc9a92-214c-11e7-93ae-92361f002671"))
- ;
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedResponse, response.getBody().toString(), false);
- }
-
-
-
- @Test
- public void testGetVNFResources404() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("ecomp/mso/catalog/v2/vnfResources/68dc-11e7-93ae-92361f002671"))
- ;
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.NOT_FOUND.getStatusCode(),response.getStatusCode().value());
-
- }
-
- @Test
- public void testGetServiceVNFResourcesByCustomizationUUID() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
- .queryParam("vnfModelCustomizationUuid", "68dc9a92-214c-11e7-93ae-92361f002671");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceVnfResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceVNFResourcesByServiceModelUUID() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
- .queryParam("serviceModelUuid", serviceUUID);
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceVnfResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceVNFResourcesByServiceModelInvariantUUIDAndVersion() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
- .queryParam("serviceModelInvariantUuid", "9647dfc4-2083-11e7-93ae-92361f002671")
- .queryParam("serviceModelVersion", "1.0");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceVnfResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceVNFResourcesByServiceModelInvariantUUIDEmptyVersion() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
- .queryParam("serviceModelInvariantUuid", "9647dfc4-2083-11e7-93ae-92361f002671")
- .queryParam("serviceModelVersion", "");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceVnfResponseV3, response.getBody().toString(), false);
- }
-
-
- @Test
- public void testGetServiceVNFResourcesByServiceModelInvariantUUID() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
- .queryParam("serviceModelInvariantUuid", "9647dfc4-2083-11e7-93ae-92361f002671");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceVnfResponseV3, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceVNFResourcesByServiceModelName() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
- .queryParam("serviceModelName", "MSOTADevInfra_vSAMP10a_Service");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceVnfResponseV3, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceVNFResourcesByServiceModelNameEmptyVersion() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
- .queryParam("serviceModelName", "MSOTADevInfra_vSAMP10a_Service").queryParam("serviceModelVersion", "");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceVnfResponseV3, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceVNFResourcesByServiceModelNameAndVersion() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
- .queryParam("serviceModelName", "MSOTADevInfra_vSAMP10a_Service").queryParam("serviceModelVersion", "1.0");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceVnfResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testSerfviceVNFResources404() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
- .queryParam("serviceModelName", "BADNAME").queryParam("serviceModelVersion", "1.0");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.NOT_FOUND.getStatusCode(),response.getStatusCode().value());
-
- }
-
-
- @Test
- public void testSerfviceVNFBadParams() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
- .queryParam("BadParamName", "BADNAME");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(badQueryParamResponse, response.getBody().toString(), false);
-
-
- }
-
-
-
+ }
+
+ /* Service Resources Endpoint */
+
+ @Test
+ public void testGetServiceModelUUID() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES))
+ .queryParam("serviceModelUuid", serviceUUID);
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceResourceResponse, response.getBody().toString(),
+ JSONCompareMode.LENIENT);
+ }
+
+ @Test
+ public void testGetServiceInvariantUUIDAndVersion() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES))
+ .queryParam("serviceModelInvariantUuid", "9647dfc4-2083-11e7-93ae-92361f002671")
+ .queryParam("serviceModelVersion", "1.0");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceResourceResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceInvariantUUID() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES))
+ .queryParam("serviceModelInvariantUuid", "9647dfc4-2083-11e7-93ae-92361f002671");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceResourceResponsev2, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceInvariantUUIDEmtpyModelVer() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES))
+ .queryParam("serviceModelInvariantUuid", "9647dfc4-2083-11e7-93ae-92361f002671")
+ .queryParam("serviceModelVersion", "");;
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceResourceResponsev2, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceModelUUID404() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ String expectedResponse = "\"serviceResources\": null";
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES))
+ .queryParam("serviceModelUuid", "5df8b6de-2083-11e7-93");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceBadQueryParams() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_RESOURCES))
+ .queryParam("BadQueryParam", "5df8b6de-2083-11e7-93");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(badQueryParamResponse, response.getBody().toString(), false);
+ }
+
+ /* VNF Resources Endpoint */
+
+ @Test
+ public void testGetVNFResourcesByCustomizationUUID() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ String expectedResponse =
+ "{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10a\",\r\n\"modelUuid\": \"ff2ae348-214a-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"2fff5b20-214b-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"68dc9a92-214c-11e7-93ae-92361f002671\",\r\n\"modelInstanceName\": \"vSAMP10a 1\"\r\n},\r\n\"toscaNodeType\": \"VF\",\r\n\"nfFunction\": \"vSAMP\",\r\n\"nfType\": \"vSAMP\",\r\n\"nfRole\": \"vSAMP\",\r\n\"nfNamingCode\": \"vSAMP\",\r\n\"multiStageDesign\": null,\r\n\"vfModules\": [\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::base::module-0\",\r\n\"modelUuid\": \"20c4431c-246d-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"cb82ffd8-252a-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": true,\r\n\"vfModuleLabel\": \"base\",\r\n\"initialCount\": 1,\r\n\"hasVolumeGroup\": false\r\n},\r\n{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::PCM::module-1\",\r\n\"modelUuid\": \"066de97e-253e-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"64efd51a-2544-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"b4ea86b4-253f-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": false,\r\n\"vfModuleLabel\": \"PCM\",\r\n\"initialCount\": 0,\r\n\"hasVolumeGroup\": false\r\n}\r\n]\r\n}";
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(
+ createURLWithPort("ecomp/mso/catalog/v2/vnfResources/68dc9a92-214c-11e7-93ae-92361f002671"));
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedResponse, response.getBody().toString(), false);
+ }
+
+
+
+ @Test
+ public void testGetVNFResources404() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort("ecomp/mso/catalog/v2/vnfResources/68dc-11e7-93ae-92361f002671"));
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
+
+ }
+
+ @Test
+ public void testGetServiceVNFResourcesByCustomizationUUID() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
+ .queryParam("vnfModelCustomizationUuid", "68dc9a92-214c-11e7-93ae-92361f002671");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceVnfResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceVNFResourcesByServiceModelUUID() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
+ .queryParam("serviceModelUuid", serviceUUID);
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceVnfResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceVNFResourcesByServiceModelInvariantUUIDAndVersion() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
+ .queryParam("serviceModelInvariantUuid", "9647dfc4-2083-11e7-93ae-92361f002671")
+ .queryParam("serviceModelVersion", "1.0");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceVnfResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceVNFResourcesByServiceModelInvariantUUIDEmptyVersion() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
+ .queryParam("serviceModelInvariantUuid", "9647dfc4-2083-11e7-93ae-92361f002671")
+ .queryParam("serviceModelVersion", "");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceVnfResponseV3, response.getBody().toString(), false);
+ }
+
+
+ @Test
+ public void testGetServiceVNFResourcesByServiceModelInvariantUUID() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
+ .queryParam("serviceModelInvariantUuid", "9647dfc4-2083-11e7-93ae-92361f002671");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceVnfResponseV3, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceVNFResourcesByServiceModelName() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
+ .queryParam("serviceModelName", "MSOTADevInfra_vSAMP10a_Service");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceVnfResponseV3, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceVNFResourcesByServiceModelNameEmptyVersion() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
+ .queryParam("serviceModelName", "MSOTADevInfra_vSAMP10a_Service").queryParam("serviceModelVersion", "");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceVnfResponseV3, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceVNFResourcesByServiceModelNameAndVersion() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
+ .queryParam("serviceModelName", "MSOTADevInfra_vSAMP10a_Service")
+ .queryParam("serviceModelVersion", "1.0");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceVnfResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testSerfviceVNFResources404() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
+ .queryParam("serviceModelName", "BADNAME").queryParam("serviceModelVersion", "1.0");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
+
+ }
+
+
+ @Test
+ public void testSerfviceVNFBadParams() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_VNFS))
+ .queryParam("BadParamName", "BADNAME");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(badQueryParamResponse, response.getBody().toString(), false);
+
+
+ }
+
+
+
/* Network Resources Endpoint */
-
- @Test
- public void testGetNetworkResourcesByCustomizationUUID() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- String expectedResponse = "{\r\n\"modelInfo\": {\r\n\"modelName\": \"CONTRAIL30_GNDIRECT\",\r\n\"modelUuid\": \"10b36f65-f4e6-4be6-ae49-9596dc1c47fc\",\r\n\"modelInvariantUuid\": \"ce4ff476-9641-4e60-b4d5-b4abbec1271d\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"3bdbb104-476c-483e-9f8b-c095b3d308ac\",\r\n\"modelInstanceName\": \"CONTRAIL30_GNDIRECT 9\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"networkType\": \"\",\r\n\"networkTechnology\": \"\",\r\n\"networkRole\": \"\",\r\n\"networkScope\": \"\"\r\n}";
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("ecomp/mso/catalog/v2/networkResources/3bdbb104-476c-483e-9f8b-c095b3d308ac"))
- ;
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedResponse, response.getBody().toString(), false);
- }
-
-
-
- @Test
- public void testGetNetworkResources404() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("ecomp/mso/catalog/v2/networkResources/3bdbb104-4asdf"))
- ;
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.NOT_FOUND.getStatusCode(),response.getStatusCode().value());
-
- }
-
- /* Service Network Resources Endpoints */
-
- @Test
- public void testGetServiceNetworkResourcesByUnknownQueryParam() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
- .queryParam("serviceModelName", "PROVIDER NETWORK").queryParam("serviceModelVersion", "2.0");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(badQueryParamResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceNetworkResourcesByServiceModelUUID() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
- .queryParam("serviceModelUuid", serviceUUID);
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceNetworkResourceResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceNetworkResourcesByServiceModelUUIDNotExist() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
- .queryParam("serviceModelUuid", "doesNotExist");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.NOT_FOUND.getStatusCode(),response.getStatusCode().value());
-
- }
-
- @Test
- public void testGetServiceNetworkResourcesByNetworkCustomizationUUIDNotExist() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
- .queryParam("networkModelCustomizationUuid", "06b8966e-097c-4d63-afda-e0d");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.NOT_FOUND.getStatusCode(),response.getStatusCode().value());
-
- }
-
- @Test
- public void testGetServiceNetworkResourcesByServiceModelInvariantUUID() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
- .queryParam("serviceModelInvariantUuid", serviceInvariantUUID);
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceNetworkResourceResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceNetworkResourcesByServiceModelInvariantUUIDAndVersion() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
- .queryParam("serviceModelInvariantUuid", serviceInvariantUUID)
- .queryParam("serviceModelVersion", "2.0");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceNetworkResourceResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceNetworkResourcesByServiceModelInvariantAndEmptyVersion() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
- .queryParam("serviceModelInvariantUuid", serviceInvariantUUID)
- .queryParam("serviceModelVersion", "");
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceNetworkResourceResponse, response.getBody().toString(), false);
- }
-
-
- @Test
- public void testGetServiceNetworkResourcesByNetworkCustomizationUUID() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
- .queryParam("networkModelCustomizationUuid", "3bdbb104-476c-483e-9f8b-c095b3d308ac");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceNetworkResourceResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceNetworkResourcesByNetworkModelName() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
- .queryParam("networkModelName", "CONTRAIL30_GNDIRECT");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedServiceNetworkResourceResponse, response.getBody().toString(), false);
- }
-
- /* Allotted endpoints */
-
- @Test
- public void testGetAllottedResourcesByCustomizationUUID() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- String expectedResponse = "{\r\n\"modelInfo\": {\r\n\"modelName\": \"Tunnel_Xconn\",\r\n\"modelUuid\": \"f6b7d4c6-e8a4-46e2-81bc-31cad5072842\",\r\n\"modelInvariantUuid\": \"b7a1b78e-6b6b-4b36-9698-8c9530da14af\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"367a8ba9-057a-4506-b106-fbae818597c6\",\r\n\"modelInstanceName\": \"Sec_Tunnel_Xconn 11\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"allottedResourceType\": \"\",\r\n\"allottedResourceRole\": null,\r\n\"providingServiceModelName\": null,\r\n\"providingServiceModelInvariantUuid\": null,\r\n\"providingServiceModelUuid\": null,\r\n\"nfFunction\": null,\r\n\"nfType\": null,\r\n\"nfRole\": null,\r\n\"nfNamingCode\": null\r\n}";
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("ecomp/mso/catalog/v2/allottedResources/367a8ba9-057a-4506-b106-fbae818597c6"));
-
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedResponse, response.getBody().toString(), false);
- }
-
-
- @Test
- public void testGetAllottedResourcesByServiceModelUuuid() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES))
- .queryParam("serviceModelUuid",serviceUUID);
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedAllottedResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testResourceReceipe() throws JSONException {
- String expectedResourceRecipe = "{\"orchestrationUri\":\"/mso/async/services/CreateSDNCNetworkResource\",\"action\":\"createInstance\",\"description\":\"sotnvpnattachmentvF\",\"id\":\"1\",\"recipeTimeout\":\"180\",\"paramXSD\":\"\"}";
-
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_RESOURCE_RECEIPE))
- .queryParam("resourceModelUuid", arResourceUUID)
- .queryParam("action", "createInstance");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedResourceRecipe, response.getBody().toString(), false);
- }
-
- @Test
- public void testResourceReceipeNotMatched() throws JSONException {
-
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_RESOURCE_RECEIPE))
- .queryParam("resourceModelUuid", arResourceUUID)
- .queryParam("action", "invalid_action");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.NOT_FOUND.getStatusCode(),response.getStatusCode().value());
- }
-
- @Test
- public void testGetServiceAllottedResourcesByServiceModelInvariantUuid() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES))
- .queryParam("serviceModelInvariantUuid", serviceInvariantUUID);
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedAllottedResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceAllottedResourcesByServiceModelInvariantUuidModelVersion() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES))
- .queryParam("serviceModelInvariantUuid", serviceInvariantUUID)
- .queryParam("serviceModelVersion", "1.0");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedAllottedResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetServiceAllottedResourcesByServiceModelInvariantUuidModelVersionEmpty() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES))
- .queryParam("serviceModelInvariantUuid", serviceInvariantUUID)
- .queryParam("serviceModelVersion", "1.0");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedAllottedResponse, response.getBody().toString(), false);
- }
-
- @Test
- public void testGetAllottedResourcesByAllottedCustomizationId() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES))
- .queryParam("arModelCustomizationUuid", "367a8ba9-057a-4506-b106-fbae818597c6");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedAllottedResponse, response.getBody().toString(), false);
- }
-
-
- @Test
- public void testGetAllottedResourcesResourcesNonExistResource() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES))
- .queryParam("arModelCustomizationUuid", "NOTEXIST");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.NOT_FOUND.getStatusCode(),response.getStatusCode().value());
-
- }
-
- /* VF Modules Endpoint */
-
- @Test
- public void testGetVFModulesNonExistResource() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_VF_MODULES))
- .queryParam("vfModuleModelName", "NEUTRON_BASIC");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.NOT_FOUND.getStatusCode(),response.getStatusCode().value());
-
- }
-
- @Test
- public void testGetVFModulesByVfModuleModelName() throws JSONException {
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- String expectedResponse = "{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::base::module-0\",\r\n\"modelUuid\": \"20c4431c-246d-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"cb82ffd8-252a-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": true,\r\n\"vfModuleLabel\": \"base\",\r\n\"initialCount\": 1,\r\n\"hasVolumeGroup\": false\r\n}";
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_VF_MODULES))
- .queryParam("vfModuleModelName", "vSAMP10aDEV::base::module-0");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(expectedResponse, response.getBody().toString(), false);
-
- }
-
- @Test
- public void testGetVFModulesBadQueryParam() throws JSONException, IOException {
- TestAppender.events.clear();
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- headers.set("Accept", MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_VF_MODULES))
- .queryParam("ADASD", "NEUTRON_BASIC");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),response.getStatusCode().value());
- JSONAssert.assertEquals(badQueryParamResponse, response.getBody().toString(), false);
-
-
- for(ILoggingEvent logEvent : TestAppender.events)
- if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") &&
- logEvent.getMarker().getName().equals("ENTRY")
- ){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
- assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP));
- assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
- assertNotNull(mdc.get(INVOCATION_ID));
- assertEquals("UNKNOWN",mdc.get(PARTNERNAME));
- assertEquals("v2/vfModules",mdc.get(SERVICE_NAME));
- assertEquals("INPROGRESS",mdc.get(STATUSCODE));
- }else if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") &&
- logEvent.getMarker().getName().equals("EXIT")){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+
+ @Test
+ public void testGetNetworkResourcesByCustomizationUUID() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ String expectedResponse =
+ "{\r\n\"modelInfo\": {\r\n\"modelName\": \"CONTRAIL30_GNDIRECT\",\r\n\"modelUuid\": \"10b36f65-f4e6-4be6-ae49-9596dc1c47fc\",\r\n\"modelInvariantUuid\": \"ce4ff476-9641-4e60-b4d5-b4abbec1271d\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"3bdbb104-476c-483e-9f8b-c095b3d308ac\",\r\n\"modelInstanceName\": \"CONTRAIL30_GNDIRECT 9\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"networkType\": \"\",\r\n\"networkTechnology\": \"\",\r\n\"networkRole\": \"\",\r\n\"networkScope\": \"\"\r\n}";
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(
+ createURLWithPort("ecomp/mso/catalog/v2/networkResources/3bdbb104-476c-483e-9f8b-c095b3d308ac"));
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedResponse, response.getBody().toString(), false);
+ }
+
+
+
+ @Test
+ public void testGetNetworkResources404() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort("ecomp/mso/catalog/v2/networkResources/3bdbb104-4asdf"));
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
+
+ }
+
+ /* Service Network Resources Endpoints */
+
+ @Test
+ public void testGetServiceNetworkResourcesByUnknownQueryParam() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
+ .queryParam("serviceModelName", "PROVIDER NETWORK").queryParam("serviceModelVersion", "2.0");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(badQueryParamResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceNetworkResourcesByServiceModelUUID() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
+ .queryParam("serviceModelUuid", serviceUUID);
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceNetworkResourceResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceNetworkResourcesByServiceModelUUIDNotExist() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
+ .queryParam("serviceModelUuid", "doesNotExist");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
+
+ }
+
+ @Test
+ public void testGetServiceNetworkResourcesByNetworkCustomizationUUIDNotExist() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
+ .queryParam("networkModelCustomizationUuid", "06b8966e-097c-4d63-afda-e0d");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
+
+ }
+
+ @Test
+ public void testGetServiceNetworkResourcesByServiceModelInvariantUUID() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
+ .queryParam("serviceModelInvariantUuid", serviceInvariantUUID);
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceNetworkResourceResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceNetworkResourcesByServiceModelInvariantUUIDAndVersion() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
+ .queryParam("serviceModelInvariantUuid", serviceInvariantUUID).queryParam("serviceModelVersion", "2.0");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceNetworkResourceResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceNetworkResourcesByServiceModelInvariantAndEmptyVersion() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
+ .queryParam("serviceModelInvariantUuid", serviceInvariantUUID).queryParam("serviceModelVersion", "");
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceNetworkResourceResponse, response.getBody().toString(), false);
+ }
+
+
+ @Test
+ public void testGetServiceNetworkResourcesByNetworkCustomizationUUID() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
+ .queryParam("networkModelCustomizationUuid", "3bdbb104-476c-483e-9f8b-c095b3d308ac");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceNetworkResourceResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceNetworkResourcesByNetworkModelName() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_NETWORKS))
+ .queryParam("networkModelName", "CONTRAIL30_GNDIRECT");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedServiceNetworkResourceResponse, response.getBody().toString(), false);
+ }
+
+ /* Allotted endpoints */
+
+ @Test
+ public void testGetAllottedResourcesByCustomizationUUID() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ String expectedResponse =
+ "{\r\n\"modelInfo\": {\r\n\"modelName\": \"Tunnel_Xconn\",\r\n\"modelUuid\": \"f6b7d4c6-e8a4-46e2-81bc-31cad5072842\",\r\n\"modelInvariantUuid\": \"b7a1b78e-6b6b-4b36-9698-8c9530da14af\",\r\n\"modelVersion\": \"1.0\",\r\n\"modelCustomizationUuid\": \"367a8ba9-057a-4506-b106-fbae818597c6\",\r\n\"modelInstanceName\": \"Sec_Tunnel_Xconn 11\"\r\n},\r\n\"toscaNodeType\": \"\",\r\n\"allottedResourceType\": \"\",\r\n\"allottedResourceRole\": null,\r\n\"providingServiceModelName\": null,\r\n\"providingServiceModelInvariantUuid\": null,\r\n\"providingServiceModelUuid\": null,\r\n\"nfFunction\": null,\r\n\"nfType\": null,\r\n\"nfRole\": null,\r\n\"nfNamingCode\": null\r\n}";
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(
+ createURLWithPort("ecomp/mso/catalog/v2/allottedResources/367a8ba9-057a-4506-b106-fbae818597c6"));
+
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedResponse, response.getBody().toString(), false);
+ }
+
+
+ @Test
+ public void testGetAllottedResourcesByServiceModelUuuid() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES))
+ .queryParam("serviceModelUuid", serviceUUID);
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedAllottedResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testResourceReceipe() throws JSONException {
+ String expectedResourceRecipe =
+ "{\"orchestrationUri\":\"/mso/async/services/CreateSDNCNetworkResource\",\"action\":\"createInstance\",\"description\":\"sotnvpnattachmentvF\",\"id\":\"1\",\"recipeTimeout\":\"180\",\"paramXSD\":\"\"}";
+
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_RESOURCE_RECEIPE))
+ .queryParam("resourceModelUuid", arResourceUUID).queryParam("action", "createInstance");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedResourceRecipe, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testResourceReceipeNotMatched() throws JSONException {
+
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_RESOURCE_RECEIPE))
+ .queryParam("resourceModelUuid", arResourceUUID).queryParam("action", "invalid_action");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
+ }
+
+ @Test
+ public void testGetServiceAllottedResourcesByServiceModelInvariantUuid() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES))
+ .queryParam("serviceModelInvariantUuid", serviceInvariantUUID);
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedAllottedResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceAllottedResourcesByServiceModelInvariantUuidModelVersion() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES))
+ .queryParam("serviceModelInvariantUuid", serviceInvariantUUID).queryParam("serviceModelVersion", "1.0");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedAllottedResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetServiceAllottedResourcesByServiceModelInvariantUuidModelVersionEmpty() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES))
+ .queryParam("serviceModelInvariantUuid", serviceInvariantUUID).queryParam("serviceModelVersion", "1.0");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedAllottedResponse, response.getBody().toString(), false);
+ }
+
+ @Test
+ public void testGetAllottedResourcesByAllottedCustomizationId() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES))
+ .queryParam("arModelCustomizationUuid", "367a8ba9-057a-4506-b106-fbae818597c6");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedAllottedResponse, response.getBody().toString(), false);
+ }
+
+
+ @Test
+ public void testGetAllottedResourcesResourcesNonExistResource() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_SERVICE_ALLOTTED_RESOURCES))
+ .queryParam("arModelCustomizationUuid", "NOTEXIST");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
+
+ }
+
+ /* VF Modules Endpoint */
+
+ @Test
+ public void testGetVFModulesNonExistResource() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_VF_MODULES))
+ .queryParam("vfModuleModelName", "NEUTRON_BASIC");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
+
+ }
+
+ @Test
+ public void testGetVFModulesByVfModuleModelName() throws JSONException {
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ String expectedResponse =
+ "{\r\n\"modelInfo\": {\r\n\"modelName\": \"vSAMP10aDEV::base::module-0\",\r\n\"modelUuid\": \"20c4431c-246d-11e7-93ae-92361f002671\",\r\n\"modelInvariantUuid\": \"78ca26d0-246d-11e7-93ae-92361f002671\",\r\n\"modelVersion\": \"2\",\r\n\"modelCustomizationUuid\": \"cb82ffd8-252a-11e7-93ae-92361f002671\"\r\n},\r\n\"isBase\": true,\r\n\"vfModuleLabel\": \"base\",\r\n\"initialCount\": 1,\r\n\"hasVolumeGroup\": false\r\n}";
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_VF_MODULES))
+ .queryParam("vfModuleModelName", "vSAMP10aDEV::base::module-0");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(expectedResponse, response.getBody().toString(), false);
+
+ }
+
+ @Test
+ public void testGetVFModulesBadQueryParam() throws JSONException, IOException {
+ TestAppender.events.clear();
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort(ECOMP_MSO_CATALOG_V2_VF_MODULES)).queryParam("ADASD", "NEUTRON_BASIC");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ JSONAssert.assertEquals(badQueryParamResponse, response.getBody().toString(), false);
+
+
+ for (ILoggingEvent logEvent : TestAppender.events)
+ if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging")
+ && logEvent.getMarker().getName().equals("ENTRY")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
+ assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP));
+ assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
+ assertNotNull(mdc.get(INVOCATION_ID));
+ assertEquals("UNKNOWN", mdc.get(PARTNERNAME));
+ assertEquals("v2/vfModules", mdc.get(SERVICE_NAME));
+ assertEquals("INPROGRESS", mdc.get(STATUSCODE));
+ } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging")
+ && logEvent.getMarker().getName().equals("EXIT")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP));
assertNotNull(mdc.get(ENDTIME));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
assertNotNull(mdc.get(INVOCATION_ID));
- assertEquals("500",mdc.get(RESPONSECODE));
- assertEquals("UNKNOWN",mdc.get(PARTNERNAME));
- assertEquals("v2/vfModules",mdc.get(SERVICE_NAME));
- assertEquals("ERROR",mdc.get(STATUSCODE));
+ assertEquals("500", mdc.get(RESPONSECODE));
+ assertEquals("UNKNOWN", mdc.get(PARTNERNAME));
+ assertEquals("v2/vfModules", mdc.get(SERVICE_NAME));
+ assertEquals("ERROR", mdc.get(STATUSCODE));
assertNotNull(mdc.get(RESPONSEDESC));
- }
- }
-
- private String createURLWithPort(String uri) {
- return "http://localhost:" + port + uri;
- }
+ }
+ }
+
+ private String createURLWithPort(String uri) {
+ return "http://localhost:" + port + uri;
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionTest.java
index 3e30dcc3b2..15e986505e 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionTest.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogQueryExceptionTest.java
@@ -26,12 +26,13 @@ import static org.junit.Assert.assertEquals;
public class CatalogQueryExceptionTest {
@Test
- public void catalogQueryExceptionConstructor(){
+ public void catalogQueryExceptionConstructor() {
CatalogQueryException messageCatalogQueryException = new CatalogQueryException("TestMessage");
assertNotNull(messageCatalogQueryException.getMessage());
- assertEquals("TestMessage",messageCatalogQueryException.getMessage());
+ assertEquals("TestMessage", messageCatalogQueryException.getMessage());
- CatalogQueryException paramsCatalogQueryException = new CatalogQueryException("TestMessage",CatalogQueryExceptionCategory.INTERNAL,true,"messageID");
+ CatalogQueryException paramsCatalogQueryException =
+ new CatalogQueryException("TestMessage", CatalogQueryExceptionCategory.INTERNAL, true, "messageID");
assertParams(paramsCatalogQueryException);
CatalogQueryException defaultCatalogQueryException = new CatalogQueryException();
@@ -44,12 +45,12 @@ public class CatalogQueryExceptionTest {
private void assertParams(CatalogQueryException paramsCatalogQueryException) {
assertNotNull(paramsCatalogQueryException.getMessage());
- assertEquals("TestMessage",paramsCatalogQueryException.getMessage());
+ assertEquals("TestMessage", paramsCatalogQueryException.getMessage());
assertNotNull(paramsCatalogQueryException.getCategory());
- assertEquals(CatalogQueryExceptionCategory.INTERNAL,paramsCatalogQueryException.getCategory());
+ assertEquals(CatalogQueryExceptionCategory.INTERNAL, paramsCatalogQueryException.getCategory());
assertNotNull(paramsCatalogQueryException.getRolledBack());
- assertEquals(true,paramsCatalogQueryException.getRolledBack());
+ assertEquals(true, paramsCatalogQueryException.getRolledBack());
assertNotNull(paramsCatalogQueryException.getMessageId());
- assertEquals("messageID",paramsCatalogQueryException.getMessageId());
+ assertEquals("messageID", paramsCatalogQueryException.getMessageId());
}
}
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CloudConfigTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CloudConfigTest.java
index f2f06d7f3d..bf5a742661 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CloudConfigTest.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CloudConfigTest.java
@@ -58,7 +58,7 @@ public class CloudConfigTest extends CatalogDbAdapterBaseTest {
@Transactional
public void createCloudSiteRest_TEST() {
headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type",MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
CloudSite cloudSite = new CloudSite();
cloudSite.setId("MTN7");
@@ -78,17 +78,19 @@ public class CloudConfigTest extends CatalogDbAdapterBaseTest {
cloudIdentity.setIdentityAuthenticationType(AuthenticationType.RACKSPACE_APIKEY);
cloudSite.setIdentityService(cloudIdentity);
String uri = "/cloudSite";
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:"+ port + uri);
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:" + port + uri);
HttpEntity<CloudSite> request = new HttpEntity<CloudSite>(cloudSite, headers);
- ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(),
- HttpMethod.POST, request, String.class);
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, request, String.class);
assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatusCode().value());
- builder = UriComponentsBuilder.fromHttpUrl("http://localhost:"+ port + uri +"/" + cloudSite.getId());
+ builder = UriComponentsBuilder.fromHttpUrl("http://localhost:" + port + uri + "/" + cloudSite.getId());
HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- ResponseEntity<CloudSite> actualCloudSite = restTemplate.exchange(builder.toUriString(),HttpMethod.GET, entity, CloudSite.class);
- builder = UriComponentsBuilder.fromHttpUrl("http://localhost:"+ port + uri);
- ResponseEntity<String> cloudSiteString = restTemplate.exchange(builder.toUriString(),HttpMethod.GET, entity, String.class);
+ ResponseEntity<CloudSite> actualCloudSite =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, CloudSite.class);
+ builder = UriComponentsBuilder.fromHttpUrl("http://localhost:" + port + uri);
+ ResponseEntity<String> cloudSiteString =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
System.out.println(cloudSiteString.getBody());
assertEquals(Response.Status.OK.getStatusCode(), actualCloudSite.getStatusCode().value());
assertThat(actualCloudSite.getBody(), sameBeanAs(cloudSite).ignoring("created").ignoring("updated")
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/NetworkCollectionCatalogDbQueryTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/NetworkCollectionCatalogDbQueryTest.java
index e6a281a375..440270e047 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/NetworkCollectionCatalogDbQueryTest.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/NetworkCollectionCatalogDbQueryTest.java
@@ -26,11 +26,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
import java.util.List;
-
import javax.transaction.Transactional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -53,102 +50,103 @@ import org.springframework.test.context.junit4.SpringRunner;
public class NetworkCollectionCatalogDbQueryTest extends CatalogDbAdapterBaseTest {
- private static final Logger logger = LoggerFactory.getLogger(NetworkCollectionCatalogDbQueryTest.class);
- private static final String NETWORKCOLLECTION = "NetworkCollection";
-
- private final String serviceUUID = "5df8b6de-2083-11e7-93ae-92361f002671";
+ private static final Logger logger = LoggerFactory.getLogger(NetworkCollectionCatalogDbQueryTest.class);
+ private static final String NETWORKCOLLECTION = "NetworkCollection";
+
+ private final String serviceUUID = "5df8b6de-2083-11e7-93ae-92361f002671";
+
+ @LocalServerPort
+ private int port;
+ boolean isInitialized;
+
+ @Autowired
+ CatalogDbClientPortChanger client;
+
+ @Before
+ public void initialize() {
+ client.wiremockPort = String.valueOf(port);
+ }
+
+ @Test
+ @Transactional
+ public void networkCollectionTest() {
+ logger.debug("TEST IS STARTING UP...");
+ String modelUUID = "4694a55f-58b3-4f17-92a5-796d6f5ffd0d";
+ boolean found = false;
+ logger.debug(Integer.toString(port));
+ InstanceGroup instanceGroup = null;
+ List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupList = null;
+ org.onap.so.db.catalog.beans.Service service = client.getServiceByID(modelUUID);
+ if (service == null) {
+ logger.debug("null");
+ } else {
+ List<CollectionResourceCustomization> customizations = service.getCollectionResourceCustomizations();
+ if (customizations.isEmpty()) {
+ logger.debug("No Network Collection found. CollectionResourceCustomizations is empty");
+ }
+ for (CollectionResourceCustomization crc : customizations) {
+ if (client.getNetworkCollectionResourceCustomizationByID(
+ crc.getModelCustomizationUUID()) instanceof NetworkCollectionResourceCustomization) {
+ if (crc.getCollectionResource() != null) {
+ if (crc.getCollectionResource().getToscaNodeType() != null) {
+ String toscaNodeType = crc.getCollectionResource().getToscaNodeType();
+ if (toscaNodeType.contains(NETWORKCOLLECTION)) {
+ logger.debug("Found a network collection");
+ instanceGroup = crc.getCollectionResource().getInstanceGroup();
+ collectionInstanceGroupList = instanceGroup.getCollectionInstanceGroupCustomizations();
+ CollectionNetworkResourceCustomization collectionNetworkCust =
+ instanceGroup.getCollectionNetworkResourceCustomizations().get(0);
+ logger.debug("Found Collection Network Resource Customization: "
+ + collectionNetworkCust.getModelCustomizationUUID());
+ } else {
+ logger.debug(
+ "No Network Collection found. toscaNodeType does not contain NetworkCollection");
+ }
+ } else {
+ logger.debug("No Network Collection found. toscaNodeType is null");
+ }
+ } else {
+ logger.debug("No Network Collection found. collectionResource is null");
+ }
+ found = true;
+ } else {
+ logger.debug("Not a Network Collection Resource Customization Instance");
+ }
+ }
+ }
+ assertEquals("Number of CollectionResourceInstanceGroupCustomization in list", 2,
+ collectionInstanceGroupList.size());
+ assertNotNull(instanceGroup);
+ assertTrue(found);
+ }
- @LocalServerPort
- private int port;
- boolean isInitialized;
+ @Test
+ public void buildingBlockDetailTest() {
+ logger.debug("TEST IS STARTING UP...");
+ logger.debug(Integer.toString(port));
+ String buildingBlockFlowName = "CreateNetworkCollectionBB";
+ BuildingBlockDetail buildingBlockDetail = client.getBuildingBlockDetail(buildingBlockFlowName);
+ logger.debug("" + buildingBlockDetail.getResourceType());
+ assertNotNull(buildingBlockDetail);
+ }
- @Autowired
- CatalogDbClientPortChanger client;
+ @Test
+ public void fetchServiceTopology_Test() {
+ org.onap.so.db.catalog.beans.Service service = client.getServiceByID(serviceUUID);
- @Before
- public void initialize(){
- client.wiremockPort= String.valueOf(port);
- }
-
- @Test
- @Transactional
- public void networkCollectionTest() {
- logger.debug("TEST IS STARTING UP...");
- String modelUUID = "4694a55f-58b3-4f17-92a5-796d6f5ffd0d";
- boolean found = false;
- logger.debug(Integer.toString(port));
- InstanceGroup instanceGroup = null;
- List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupList = null;
- org.onap.so.db.catalog.beans.Service service = client.getServiceByID(modelUUID);
- if (service == null) {
- logger.debug("null");
- } else {
- List<CollectionResourceCustomization> customizations = service.getCollectionResourceCustomizations();
- if (customizations.isEmpty()) {
- logger.debug("No Network Collection found. CollectionResourceCustomizations is empty");
- }
- for (CollectionResourceCustomization crc : customizations) {
- if(client.getNetworkCollectionResourceCustomizationByID(crc.getModelCustomizationUUID())
- instanceof NetworkCollectionResourceCustomization) {
- if (crc.getCollectionResource() != null) {
- if (crc.getCollectionResource()
- .getToscaNodeType() != null) {
- String toscaNodeType = crc.getCollectionResource()
- .getToscaNodeType();
- if (toscaNodeType.contains(NETWORKCOLLECTION)) {
- logger.debug("Found a network collection");
- instanceGroup = crc.getCollectionResource().getInstanceGroup();
- collectionInstanceGroupList =
- instanceGroup.getCollectionInstanceGroupCustomizations();
- CollectionNetworkResourceCustomization collectionNetworkCust = instanceGroup.getCollectionNetworkResourceCustomizations().get(0);
- logger.debug("Found Collection Network Resource Customization: " + collectionNetworkCust.getModelCustomizationUUID());
- } else {
- logger.debug(
- "No Network Collection found. toscaNodeType does not contain NetworkCollection");
- }
- } else {
- logger.debug("No Network Collection found. toscaNodeType is null");
- }
- } else {
- logger.debug("No Network Collection found. collectionResource is null");
- }
- found = true;
- } else {
- logger.debug("Not a Network Collection Resource Customization Instance");
- }
- }
- }
- assertEquals("Number of CollectionResourceInstanceGroupCustomization in list", 2, collectionInstanceGroupList.size());
- assertNotNull(instanceGroup);
- assertTrue(found);
- }
-
- @Test
- public void buildingBlockDetailTest() {
- logger.debug("TEST IS STARTING UP...");
- logger.debug(Integer.toString(port));
- String buildingBlockFlowName = "CreateNetworkCollectionBB";
- BuildingBlockDetail buildingBlockDetail = client.getBuildingBlockDetail(buildingBlockFlowName);
- logger.debug("" + buildingBlockDetail.getResourceType());
- assertNotNull(buildingBlockDetail);
- }
-
- @Test
- public void fetchServiceTopology_Test() {
- org.onap.so.db.catalog.beans.Service service = client.getServiceByID(serviceUUID);
+ if (service == null) {
+ fail("Service is null");
+ }
+ assertEquals(serviceUUID, service.getModelUUID());
+ assertEquals("MSOTADevInfra_vSAMP10a_Service", service.getModelName());
+ }
- if (service == null) {
- fail("Service is null");
- }
- assertEquals(serviceUUID, service.getModelUUID());
- assertEquals("MSOTADevInfra_vSAMP10a_Service",service.getModelName());
- }
-
- @Test
- public void CollectionNetworkResourceCustomizationTest() {
- String modelCustId = "1a61be4b-3378-4c9a-91c8-c919519b2d01";
- CollectionNetworkResourceCustomization collectionNetworkCust = client.getCollectionNetworkResourceCustomizationByID(modelCustId);
- assertNotNull(collectionNetworkCust);
- logger.debug(collectionNetworkCust.getModelCustomizationUUID());
- }
+ @Test
+ public void CollectionNetworkResourceCustomizationTest() {
+ String modelCustId = "1a61be4b-3378-4c9a-91c8-c919519b2d01";
+ CollectionNetworkResourceCustomization collectionNetworkCust =
+ client.getCollectionNetworkResourceCustomizationByID(modelCustId);
+ assertNotNull(collectionNetworkCust);
+ logger.debug(collectionNetworkCust.getModelCustomizationUUID());
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryResourceRecipeTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryResourceRecipeTest.java
index e403867c42..8fae1c2900 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryResourceRecipeTest.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryResourceRecipeTest.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.catalogdb.catalogrest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
-
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -62,7 +61,7 @@ public class QueryResourceRecipeTest {
}
private Recipe createRecipe() {
- ServiceRecipe recipe = new ServiceRecipe();
+ ServiceRecipe recipe = new ServiceRecipe();
recipe.setId(RECIPE_ID);
recipe.setAction(RECIPE_ACTION);
recipe.setOrchestrationUri(RECIPE_URI);
@@ -76,8 +75,9 @@ public class QueryResourceRecipeTest {
public void convertToJson() {
Recipe recipe = createRecipe();
QueryResourceRecipe queryResourceRecipe = new QueryResourceRecipe(recipe);
- assertEquals("{\"orchestrationUri\":\"uriTest\",\"action\":\"actionTest\",\"description\":\"descrTest\",\"id\":\"123\",\"recipeTimeout\":\"100\",\"paramXSD\":\"paramsXsdTest\"}",
- queryResourceRecipe.JSON2(false,false));
+ assertEquals(
+ "{\"orchestrationUri\":\"uriTest\",\"action\":\"actionTest\",\"description\":\"descrTest\",\"id\":\"123\",\"recipeTimeout\":\"100\",\"paramXSD\":\"paramsXsdTest\"}",
+ queryResourceRecipe.JSON2(false, false));
}
@Test
@@ -86,10 +86,11 @@ public class QueryResourceRecipeTest {
QueryResourceRecipe networkQueryRR = new QueryResourceRecipe(new NetworkRecipe());
QueryResourceRecipe arQueryRR = new QueryResourceRecipe(new ArRecipe());
- String expected = "{\"orchestrationUri\":\"\",\"action\":\"\",\"description\":\"\",\"id\":\"\",\"recipeTimeout\":\"\",\"paramXSD\":\"\"}";
+ String expected =
+ "{\"orchestrationUri\":\"\",\"action\":\"\",\"description\":\"\",\"id\":\"\",\"recipeTimeout\":\"\",\"paramXSD\":\"\"}";
assertEquals(expected, vnfQueryRR.JSON2(false, false));
- assertEquals(expected, networkQueryRR.JSON2(false,false));
- assertEquals(expected, arQueryRR.JSON2(false,false));
+ assertEquals(expected, networkQueryRR.JSON2(false, false));
+ assertEquals(expected, arQueryRR.JSON2(false, false));
}
}
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceCsarTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceCsarTest.java
index 32cc2946db..44e5998404 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceCsarTest.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceCsarTest.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters.catalogdb.catalogrest;
import static org.assertj.core.api.Assertions.assertThat;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.so.db.catalog.beans.ToscaCsar;
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModuleTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModuleTest.java
index 98e90c828c..cf0a06e8b0 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModuleTest.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModuleTest.java
@@ -21,10 +21,8 @@
package org.onap.so.adapters.catalogdb.catalogrest;
import static org.assertj.core.api.Assertions.assertThat;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
import org.onap.so.db.catalog.beans.HeatEnvironment;
import org.onap.so.db.catalog.beans.VfModule;
@@ -52,8 +50,7 @@ public class QueryVfModuleTest {
.contains(VF_MODEL_UUID);
assertThat(JsonPathUtil.getInstance().locateResult(jsonResult, "$.vfModules[0].modelInfo.modelInvariantUuid"))
.contains(VF_MODULE_INVARIANT_UUID);
- assertThat(JsonPathUtil.getInstance().locateResult(jsonResult, "$.vfModules[0].isBase"))
- .contains("true");
+ assertThat(JsonPathUtil.getInstance().locateResult(jsonResult, "$.vfModules[0].isBase")).contains("true");
assertThat(JsonPathUtil.getInstance().locateResult(jsonResult, "$.vfModules[0].vfModuleLabel"))
.contains(VF_MODEL_CUSTOMIZATION_LABEL);
assertThat(JsonPathUtil.getInstance().locateResult(jsonResult, "$.vfModules[0].initialCount"))
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/TestAppender.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/TestAppender.java
index c5772d9883..0fcb73beab 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/TestAppender.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/TestAppender.java
@@ -27,11 +27,11 @@ import ch.qos.logback.core.AppenderBase;
-public class TestAppender extends AppenderBase<ILoggingEvent> {
+public class TestAppender extends AppenderBase<ILoggingEvent> {
static List<ILoggingEvent> events = new ArrayList<>();
-
- @Override
- protected void append(ILoggingEvent loggingEvent) {
- events.add(loggingEvent);
- }
+
+ @Override
+ protected void append(ILoggingEvent loggingEvent) {
+ events.add(loggingEvent);
+ }
}
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientPortChanger.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientPortChanger.java
index e38bd02069..14498b6617 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientPortChanger.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientPortChanger.java
@@ -21,7 +21,6 @@
package org.onap.so.db.catalog.client;
import org.springframework.stereotype.Component;
-
import java.net.URI;
@Component()
@@ -29,7 +28,7 @@ public class CatalogDbClientPortChanger extends CatalogDbClient {
public String wiremockPort;
- CatalogDbClientPortChanger(){
+ CatalogDbClientPortChanger() {
}
@@ -44,6 +43,6 @@ public class CatalogDbClientPortChanger extends CatalogDbClient {
String prefix = "http://localhost:" + wiremockPort;
String query = uri.getQuery();
- return URI.create(prefix + path + (query == null || query.isEmpty()?"":"?"+query));
+ return URI.create(prefix + path + (query == null || query.isEmpty() ? "" : "?" + query));
}
}
diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java
index 763b3441fb..e1152bad4a 100644
--- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java
+++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java
@@ -24,7 +24,6 @@ package org.onap.so.db.catalog.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
import java.util.List;
import java.util.UUID;
import org.junit.Assert;
@@ -82,17 +81,17 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testGetRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep() {
- RainyDayHandlerStatus rainyDayHandlerStatus = client
- .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(
- "AssignServiceInstanceBB", "*", "*", "*", "*");
+ RainyDayHandlerStatus rainyDayHandlerStatus =
+ client.getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(
+ "AssignServiceInstanceBB", "*", "*", "*", "*");
Assert.assertEquals("Rollback", rainyDayHandlerStatus.getPolicy());
}
@Test
public void testGetRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStepRecordNotFound() {
- RainyDayHandlerStatus rainyDayHandlerStatus = client
- .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(
- UUID.randomUUID().toString(), "*", "*", "*", "*");
+ RainyDayHandlerStatus rainyDayHandlerStatus =
+ client.getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(
+ UUID.randomUUID().toString(), "*", "*", "*", "*");
Assert.assertNull(rainyDayHandlerStatus);
}
@@ -184,8 +183,8 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testGetVnfResourceCustomizationByModelCustomizationUUID() {
- VnfResourceCustomization vnfResourceCustomization = client
- .getVnfResourceCustomizationByModelCustomizationUUID("68dc9a92-214c-11e7-93ae-92361f002671");
+ VnfResourceCustomization vnfResourceCustomization =
+ client.getVnfResourceCustomizationByModelCustomizationUUID("68dc9a92-214c-11e7-93ae-92361f002671");
Assert.assertNotNull(vnfResourceCustomization);
Assert.assertEquals("vSAMP", vnfResourceCustomization.getNfRole());
Assert.assertNotNull(vnfResourceCustomization.getModelCustomizationUUID());
@@ -197,8 +196,8 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testGetVnfResourceCustomizationByModelCustomizationUUINotFound() {
- VnfResourceCustomization vnfResourceCustomization = client
- .getVnfResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString());
+ VnfResourceCustomization vnfResourceCustomization =
+ client.getVnfResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString());
Assert.assertNull(vnfResourceCustomization);
}
@@ -208,13 +207,13 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
Assert.assertNotNull(instanceGroup);
Assert.assertEquals("network_collection_resource_1806..NetworkCollection..0", instanceGroup.getModelName());
Assert.assertEquals("org.openecomp.resource.cr.NetworkCollectionResource1806",
- instanceGroup.getToscaNodeType().toString());
+ instanceGroup.getToscaNodeType().toString());
}
@Test
public void testGetVfModuleCustomizationByModelCuztomizationUUID() {
- VfModuleCustomization vfModuleCustomization = client
- .getVfModuleCustomizationByModelCuztomizationUUID("cb82ffd8-252a-11e7-93ae-92361f002671");
+ VfModuleCustomization vfModuleCustomization =
+ client.getVfModuleCustomizationByModelCuztomizationUUID("cb82ffd8-252a-11e7-93ae-92361f002671");
Assert.assertNotNull(vfModuleCustomization);
Assert.assertNotNull(vfModuleCustomization.getModelCustomizationUUID());
Assert.assertEquals("base", vfModuleCustomization.getLabel());
@@ -222,15 +221,15 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testGetVfModuleCustomizationByModelCuztomizationUUIDNotFound() {
- VfModuleCustomization vfModuleCustomization = client
- .getVfModuleCustomizationByModelCuztomizationUUID(UUID.randomUUID().toString());
+ VfModuleCustomization vfModuleCustomization =
+ client.getVfModuleCustomizationByModelCuztomizationUUID(UUID.randomUUID().toString());
Assert.assertNull(vfModuleCustomization);
}
@Test
public void testGetNetworkResourceCustomizationByModelCustomizationUUID() {
- NetworkResourceCustomization networkResourceCustomization = client
- .getNetworkResourceCustomizationByModelCustomizationUUID("3bdbb104-476c-483e-9f8b-c095b3d308ac");
+ NetworkResourceCustomization networkResourceCustomization =
+ client.getNetworkResourceCustomizationByModelCustomizationUUID("3bdbb104-476c-483e-9f8b-c095b3d308ac");
Assert.assertNotNull(networkResourceCustomization);
Assert.assertNotNull(networkResourceCustomization.getModelCustomizationUUID());
Assert.assertEquals("CONTRAIL30_GNDIRECT 9", networkResourceCustomization.getModelInstanceName());
@@ -239,16 +238,16 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testGetNetworkResourceCustomizationByModelCustomizationUUIDNotFound() {
- NetworkResourceCustomization networkResourceCustomization = client
- .getNetworkResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString());
+ NetworkResourceCustomization networkResourceCustomization =
+ client.getNetworkResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString());
Assert.assertNull(networkResourceCustomization);
}
@Test
public void testGgetVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID() {
- VfModuleCustomization vfModuleCustomization = client
- .getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
- "cb82ffd8-252a-11e7-93ae-92361f002672", "20c4431c-246d-11e7-93ae-92361f002672");
+ VfModuleCustomization vfModuleCustomization =
+ client.getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
+ "cb82ffd8-252a-11e7-93ae-92361f002672", "20c4431c-246d-11e7-93ae-92361f002672");
Assert.assertNotNull(vfModuleCustomization);
Assert.assertNotNull(vfModuleCustomization.getModelCustomizationUUID());
Assert.assertNotNull(vfModuleCustomization.getVfModule());
@@ -257,35 +256,35 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testGgetVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUIDNotFound() {
- VfModuleCustomization vfModuleCustomization = client
- .getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
- "cb82ffd8-252a-11e7-93ae-92361f002672", UUID.randomUUID().toString());
+ VfModuleCustomization vfModuleCustomization =
+ client.getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
+ "cb82ffd8-252a-11e7-93ae-92361f002672", UUID.randomUUID().toString());
Assert.assertNull(vfModuleCustomization);
}
@Test
public void testGetFirstByServiceModelUUIDAndAction() {
- ServiceRecipe serviceRecipe = client
- .getFirstByServiceModelUUIDAndAction("4694a55f-58b3-4f17-92a5-796d6f5ffd0d", "createInstance");
+ ServiceRecipe serviceRecipe =
+ client.getFirstByServiceModelUUIDAndAction("4694a55f-58b3-4f17-92a5-796d6f5ffd0d", "createInstance");
Assert.assertNotNull(serviceRecipe);
Assert.assertNotNull(serviceRecipe.getServiceModelUUID());
Assert.assertNotNull(serviceRecipe.getAction());
Assert.assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance",
- serviceRecipe.getOrchestrationUri());
+ serviceRecipe.getOrchestrationUri());
Assert.assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription());
}
@Test
public void testGetFirstByServiceModelUUIDAndActionNotFound() {
- ServiceRecipe serviceRecipe = client
- .getFirstByServiceModelUUIDAndAction("5df8b6de-2083-11e7-93ae-92361f002671", UUID.randomUUID().toString());
+ ServiceRecipe serviceRecipe = client.getFirstByServiceModelUUIDAndAction("5df8b6de-2083-11e7-93ae-92361f002671",
+ UUID.randomUUID().toString());
Assert.assertNull(serviceRecipe);
}
@Test
public void testGetFirstVnfResourceByModelInvariantUUIDAndModelVersion() {
VnfResource vnfResource = client
- .getFirstVnfResourceByModelInvariantUUIDAndModelVersion("2fff5b20-214b-11e7-93ae-92361f002671", "2.0");
+ .getFirstVnfResourceByModelInvariantUUIDAndModelVersion("2fff5b20-214b-11e7-93ae-92361f002671", "2.0");
Assert.assertNotNull(vnfResource);
Assert.assertNotNull(vnfResource.getModelInvariantId());
Assert.assertNotNull(vnfResource.getModelVersion());
@@ -296,9 +295,8 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testGetFirstVnfResourceByModelInvariantUUIDAndModelVersionNotFound() {
- VnfResource vnfResource = client
- .getFirstVnfResourceByModelInvariantUUIDAndModelVersion("2fff5b20-214b-11e7-93ae-92361f002671",
- UUID.randomUUID().toString());
+ VnfResource vnfResource = client.getFirstVnfResourceByModelInvariantUUIDAndModelVersion(
+ "2fff5b20-214b-11e7-93ae-92361f002671", UUID.randomUUID().toString());
Assert.assertNull(vnfResource);
}
@@ -306,15 +304,15 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
public void testGetFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources() {
VnfResource vnfr = new VnfResource();
vnfr.setModelUUID("ff2ae348-214a-11e7-93ae-92361f002671");
- VnfResourceCustomization firstVnfResourceCustomizationByModelInstanceNameAndVnfResources = client
- .getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources("vSAMP10a 1", vnfr);
+ VnfResourceCustomization firstVnfResourceCustomizationByModelInstanceNameAndVnfResources =
+ client.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources("vSAMP10a 1", vnfr);
Assert.assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources);
Assert.assertEquals("vSAMP", firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getNfRole());
Assert.assertEquals("vSAMP10a 1",
- firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getModelInstanceName());
+ firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getModelInstanceName());
Assert.assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVnfResources());
- Assert
- .assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVfModuleCustomizations());
+ Assert.assertNotNull(
+ firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVfModuleCustomizations());
}
@Test
@@ -335,9 +333,9 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testGetFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction() {
- VnfComponentsRecipe vnfComponentsRecipe = client
- .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
- "20c4431c-246d-11e7-93ae-92361f002671", "volumeGroup", "createInstance");
+ VnfComponentsRecipe vnfComponentsRecipe =
+ client.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+ "20c4431c-246d-11e7-93ae-92361f002671", "volumeGroup", "createInstance");
Assert.assertNotNull(vnfComponentsRecipe);
Assert.assertNotNull(vnfComponentsRecipe.getAction());
Assert.assertNotNull(vnfComponentsRecipe.getVfModuleModelUUID());
@@ -350,28 +348,28 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testGetFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndActionNotFound() {
- VnfComponentsRecipe vnfComponentsRecipe = client
- .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(UUID.randomUUID().toString(),
- "volumeGroup", "createInstance");
+ VnfComponentsRecipe vnfComponentsRecipe =
+ client.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+ UUID.randomUUID().toString(), "volumeGroup", "createInstance");
Assert.assertNull(vnfComponentsRecipe);
}
@Test
public void testGetFirstVnfComponentsRecipeByVnfComponentTypeAndAction() {
- VnfComponentsRecipe vnfComponentsRecipe = client
- .getFirstVnfComponentsRecipeByVnfComponentTypeAndAction("volumeGroup", "createInstance");
+ VnfComponentsRecipe vnfComponentsRecipe =
+ client.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction("volumeGroup", "createInstance");
Assert.assertNotNull(vnfComponentsRecipe);
Assert.assertNotNull(vnfComponentsRecipe.getAction());
Assert.assertNotNull(vnfComponentsRecipe.getVnfComponentType());
Assert.assertEquals("VID_DEFAULT recipe t", vnfComponentsRecipe.getDescription());
- Assert
- .assertEquals("/mso/async/services/CreateVfModuleVolumeInfraV1", vnfComponentsRecipe.getOrchestrationUri());
+ Assert.assertEquals("/mso/async/services/CreateVfModuleVolumeInfraV1",
+ vnfComponentsRecipe.getOrchestrationUri());
}
@Test
public void testGetServiceByModelVersionAndModelInvariantUUID() {
- Service service = client
- .getServiceByModelVersionAndModelInvariantUUID("2.0", "9647dfc4-2083-11e7-93ae-92361f002671");
+ Service service =
+ client.getServiceByModelVersionAndModelInvariantUUID("2.0", "9647dfc4-2083-11e7-93ae-92361f002671");
Assert.assertNotNull(service);
Assert.assertNotNull(service.getModelVersion());
Assert.assertNotNull(service.getModelInvariantUUID());
@@ -387,8 +385,8 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testGetVfModuleByModelInvariantUUIDAndModelVersion() {
- VfModule vfModule = client
- .getVfModuleByModelInvariantUUIDAndModelVersion("78ca26d0-246d-11e7-93ae-92361f002671", "2");
+ VfModule vfModule =
+ client.getVfModuleByModelInvariantUUIDAndModelVersion("78ca26d0-246d-11e7-93ae-92361f002671", "2");
Assert.assertNotNull(vfModule);
Assert.assertNotNull(vfModule.getModelVersion());
Assert.assertNotNull(vfModule.getModelInvariantUUID());
@@ -404,8 +402,8 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testGetServiceByModelInvariantUUIDOrderByModelVersionDesc() {
- List<Service> serviceList = client
- .getServiceByModelInvariantUUIDOrderByModelVersionDesc("9647dfc4-2083-11e7-93ae-92361f002671");
+ List<Service> serviceList =
+ client.getServiceByModelInvariantUUIDOrderByModelVersionDesc("9647dfc4-2083-11e7-93ae-92361f002671");
Assert.assertFalse(serviceList.isEmpty());
Assert.assertEquals(2, serviceList.size());
Service service = serviceList.get(0);
@@ -414,15 +412,15 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testGetServiceByModelInvariantUUIDOrderByModelVersionDescNotFound() {
- List<Service> serviceList = client
- .getServiceByModelInvariantUUIDOrderByModelVersionDesc(UUID.randomUUID().toString());
+ List<Service> serviceList =
+ client.getServiceByModelInvariantUUIDOrderByModelVersionDesc(UUID.randomUUID().toString());
Assert.assertTrue(serviceList.isEmpty());
}
@Test
public void testGetVfModuleByModelInvariantUUIDOrderByModelVersionDesc() {
- List<VfModule> moduleList = client
- .getVfModuleByModelInvariantUUIDOrderByModelVersionDesc("78ca26d0-246d-11e7-93ae-92361f002671");
+ List<VfModule> moduleList =
+ client.getVfModuleByModelInvariantUUIDOrderByModelVersionDesc("78ca26d0-246d-11e7-93ae-92361f002671");
Assert.assertFalse(moduleList.isEmpty());
Assert.assertEquals(2, moduleList.size());
VfModule module = moduleList.get(0);
@@ -432,7 +430,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testPostCloudSite() {
CatalogDbClientPortChanger localClient = new CatalogDbClientPortChanger(
- "http://localhost:" + client.wiremockPort, msoAdaptersAuth, client.wiremockPort);
+ "http://localhost:" + client.wiremockPort, msoAdaptersAuth, client.wiremockPort);
CloudSite cloudSite = new CloudSite();
cloudSite.setId("MTN6");
cloudSite.setClli("TESTCLLI");
@@ -471,60 +469,22 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testPostHomingInstance() {
CatalogDbClientPortChanger localClient = new CatalogDbClientPortChanger(
- "http://localhost:" + client.wiremockPort, msoAdaptersAuth, client.wiremockPort);
+ "http://localhost:" + client.wiremockPort, msoAdaptersAuth, client.wiremockPort);
HomingInstance homingInstance = new HomingInstance();
homingInstance.setServiceInstanceId("5df8d6be-2083-11e7-93ae-92361f232671");
homingInstance.setCloudOwner("CloudOwner-1");
homingInstance.setCloudRegionId("CloudRegionOne");
- homingInstance.setOofDirectives("{\n" +
- "\"directives\": [\n" +
- "{\n" +
- "\"directives\": [\n" +
- "{\n" +
- "\"attributes\": [\n" +
- "{\n" +
- "\"attribute_value\": \"onap.hpa.flavor31\",\n" +
- "\"attribute_name\": \"firewall_flavor_name\"\n" +
- "}\n" +
- "],\n" +
- "\"type\": \"flavor_directives\"\n" +
- "}\n" +
- "],\n" +
- "\"type\": \"vnfc\",\n" +
- "\"id\": \"vfw\"\n" +
- "},\n" +
- "{\n" +
- "\"directives\": [\n" +
- "{\n" +
- "\"attributes\": [\n" +
- "{\n" +
- "\"attribute_value\": \"onap.hpa.flavor32\",\n" +
- "\"attribute_name\": \"packetgen_flavor_name\"\n" +
- "}\n" +
- "],\n" +
- "\"type\": \"flavor_directives\"\n" +
- "}\n" +
- "],\n" +
- "\"type\": \"vnfc\",\n" +
- "\"id\": \"vgenerator\"\n" +
- "},\n" +
- "{\n" +
- "\"directives\": [\n" +
- "{\n" +
- "\"attributes\": [\n" +
- "{\n" +
- "\"attribute_value\": \"onap.hpa.flavor31\",\n" +
- "\"attribute_name\": \"sink_flavor_name\"\n" +
- "}\n" +
- "],\n" +
- "\"type\": \"flavor_directives\"\n" +
- "}\n" +
- "],\n" +
- "\"type\": \"vnfc\",\n" +
- "\"id\": \"vsink\"\n" +
- "}\n" +
- "]\n" +
- "}");
+ homingInstance.setOofDirectives("{\n" + "\"directives\": [\n" + "{\n" + "\"directives\": [\n" + "{\n"
+ + "\"attributes\": [\n" + "{\n" + "\"attribute_value\": \"onap.hpa.flavor31\",\n"
+ + "\"attribute_name\": \"firewall_flavor_name\"\n" + "}\n" + "],\n"
+ + "\"type\": \"flavor_directives\"\n" + "}\n" + "],\n" + "\"type\": \"vnfc\",\n" + "\"id\": \"vfw\"\n"
+ + "},\n" + "{\n" + "\"directives\": [\n" + "{\n" + "\"attributes\": [\n" + "{\n"
+ + "\"attribute_value\": \"onap.hpa.flavor32\",\n" + "\"attribute_name\": \"packetgen_flavor_name\"\n"
+ + "}\n" + "],\n" + "\"type\": \"flavor_directives\"\n" + "}\n" + "],\n" + "\"type\": \"vnfc\",\n"
+ + "\"id\": \"vgenerator\"\n" + "},\n" + "{\n" + "\"directives\": [\n" + "{\n" + "\"attributes\": [\n"
+ + "{\n" + "\"attribute_value\": \"onap.hpa.flavor31\",\n" + "\"attribute_name\": \"sink_flavor_name\"\n"
+ + "}\n" + "],\n" + "\"type\": \"flavor_directives\"\n" + "}\n" + "],\n" + "\"type\": \"vnfc\",\n"
+ + "\"id\": \"vsink\"\n" + "}\n" + "]\n" + "}");
localClient.postHomingInstance(homingInstance);
HomingInstance getHomingInstance = this.client.getHomingInstance("5df8d6be-2083-11e7-93ae-92361f232671");
Assert.assertNotNull(getHomingInstance);
@@ -574,7 +534,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
northBoundRequest.setIsAlacarte(true);
northBoundRequest.setCloudOwner("my-custom-cloud-owner");
client.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner("createService", "service", true,
- "my-custom-cloud-owner");
+ "my-custom-cloud-owner");
Assert.assertNotNull(northBoundRequest);
Assert.assertEquals("createService", northBoundRequest.getAction());
Assert.assertEquals("service", northBoundRequest.getRequestScope());
@@ -584,27 +544,27 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testFindServiceRecipeByActionAndServiceModelUUID() {
- ServiceRecipe serviceRecipe = client
- .findServiceRecipeByActionAndServiceModelUUID("createInstance", "4694a55f-58b3-4f17-92a5-796d6f5ffd0d");
+ ServiceRecipe serviceRecipe = client.findServiceRecipeByActionAndServiceModelUUID("createInstance",
+ "4694a55f-58b3-4f17-92a5-796d6f5ffd0d");
Assert.assertNotNull(serviceRecipe);
Assert.assertNotNull(serviceRecipe.getServiceModelUUID());
Assert.assertNotNull(serviceRecipe.getAction());
Assert.assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance",
- serviceRecipe.getOrchestrationUri());
+ serviceRecipe.getOrchestrationUri());
Assert.assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription());
}
@Test
public void testFindServiceRecipeByActionAndServiceModelUUIDNotFound() {
- ServiceRecipe serviceRecipe = client
- .findServiceRecipeByActionAndServiceModelUUID("not_found", "5df8b6de-2083-11e7-93ae-test");
+ ServiceRecipe serviceRecipe =
+ client.findServiceRecipeByActionAndServiceModelUUID("not_found", "5df8b6de-2083-11e7-93ae-test");
Assert.assertNull(serviceRecipe);
}
@Test
public void testFindExternalToInternalServiceByServiceName() {
- ExternalServiceToInternalService externalServiceToInternalService = client
- .findExternalToInternalServiceByServiceName("MySpecialServiceName");
+ ExternalServiceToInternalService externalServiceToInternalService =
+ client.findExternalToInternalServiceByServiceName("MySpecialServiceName");
Assert.assertNotNull(externalServiceToInternalService);
Assert.assertNotNull(externalServiceToInternalService.getServiceName());
Assert.assertNotNull(externalServiceToInternalService.getServiceModelUUID());
@@ -613,8 +573,8 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void testFindExternalToInternalServiceByServiceNameNotFound() {
- ExternalServiceToInternalService externalServiceToInternalService = client
- .findExternalToInternalServiceByServiceName("Not_Found");
+ ExternalServiceToInternalService externalServiceToInternalService =
+ client.findExternalToInternalServiceByServiceName("Not_Found");
Assert.assertNull(externalServiceToInternalService);
}
@@ -624,7 +584,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
Assert.assertNotNull(pnfResource);
assertEquals("PNFResource modelUUID", "ff2ae348-214a-11e7-93ae-92361f002680", pnfResource.getModelUUID());
assertEquals("PNFResource modelInvariantUUID", "2fff5b20-214b-11e7-93ae-92361f002680",
- pnfResource.getModelInvariantUUID());
+ pnfResource.getModelInvariantUUID());
assertEquals("PNFResource modelVersion", "1.0", pnfResource.getModelVersion());
assertEquals("PNFResource orchestration mode", "", pnfResource.getOrchestrationMode());
}
@@ -637,8 +597,8 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
@Test
public void getPnfResourceCustomizationByModelCustomizationUUID_validUuid_expectedOutput() {
- PnfResourceCustomization pnfResourceCustomization = client
- .getPnfResourceCustomizationByModelCustomizationUUID("68dc9a92-214c-11e7-93ae-92361f002680");
+ PnfResourceCustomization pnfResourceCustomization =
+ client.getPnfResourceCustomizationByModelCustomizationUUID("68dc9a92-214c-11e7-93ae-92361f002680");
assertEquals("modelInstanceName", "PNF routing", pnfResourceCustomization.getModelInstanceName());
assertEquals("blueprintName", "test_configuration_restconf", pnfResourceCustomization.getBlueprintName());
assertEquals("blueprintVersion", "1.0.0", pnfResourceCustomization.getBlueprintVersion());
@@ -647,25 +607,25 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
assertNotNull(pnfResource);
assertEquals("PNFResource modelUUID", "ff2ae348-214a-11e7-93ae-92361f002680", pnfResource.getModelUUID());
assertEquals("PNFResource modelInvariantUUID", "2fff5b20-214b-11e7-93ae-92361f002680",
- pnfResource.getModelInvariantUUID());
+ pnfResource.getModelInvariantUUID());
assertEquals("PNFResource modelVersion", "1.0", pnfResource.getModelVersion());
assertEquals("PNFResource orchestration mode", "", pnfResource.getOrchestrationMode());
}
@Test
public void getPnfResourceCustomizationByModelCustomizationUUID_invalidUuid_nullOutput() {
- PnfResourceCustomization pnfResourceCustomization = client
- .getPnfResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString());
+ PnfResourceCustomization pnfResourceCustomization =
+ client.getPnfResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString());
Assert.assertNull(pnfResourceCustomization);
}
@Test
public void getPnfResourceCustomizationFromJoinTable_validServiceUuid_expectedOutput() {
- List<PnfResourceCustomization> pnfResourceCustomizationList = client
- .getPnfResourceCustomizationByModelUuid("5df8b6de-2083-11e7-93ae-92361f002676");
+ List<PnfResourceCustomization> pnfResourceCustomizationList =
+ client.getPnfResourceCustomizationByModelUuid("5df8b6de-2083-11e7-93ae-92361f002676");
assertEquals(1, pnfResourceCustomizationList.size());
- PnfResourceCustomization pnfResourceCustomization= pnfResourceCustomizationList.get(0);
+ PnfResourceCustomization pnfResourceCustomization = pnfResourceCustomizationList.get(0);
assertEquals("modelInstanceName", "PNF routing", pnfResourceCustomization.getModelInstanceName());
assertEquals("blueprintName", "test_configuration_restconf", pnfResourceCustomization.getBlueprintName());
assertEquals("blueprintVersion", "1.0.0", pnfResourceCustomization.getBlueprintVersion());
@@ -674,29 +634,27 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
assertEquals("PNFResource modelUUID", "ff2ae348-214a-11e7-93ae-92361f002680", pnfResource.getModelUUID());
assertEquals("PNFResource modelInvariantUUID", "2fff5b20-214b-11e7-93ae-92361f002680",
- pnfResource.getModelInvariantUUID());
+ pnfResource.getModelInvariantUUID());
assertEquals("PNFResource modelVersion", "1.0", pnfResource.getModelVersion());
assertEquals("PNFResource orchestration mode", "", pnfResource.getOrchestrationMode());
}
@Test
public void getPnfResourceCustomizationFromJoinTable_invalidServiceUuid_nullOutput() {
- List<PnfResourceCustomization> pnfResourceCustomizationList = client
- .getPnfResourceCustomizationByModelUuid(UUID.randomUUID().toString());
+ List<PnfResourceCustomization> pnfResourceCustomizationList =
+ client.getPnfResourceCustomizationByModelUuid(UUID.randomUUID().toString());
assertEquals(0, pnfResourceCustomizationList.size());
}
-
+
@Test
public void getWorkflowByArtifactUUID_validUuid_expectedOutput() {
- Workflow workflow = client
- .findWorkflowByArtifactUUID("5b0c4322-643d-4c9f-b184-4516049e99b1");
+ Workflow workflow = client.findWorkflowByArtifactUUID("5b0c4322-643d-4c9f-b184-4516049e99b1");
assertEquals("artifactName", "testingWorkflow", workflow.getArtifactName());
}
@Test
public void getWorkflowByArtifactUUID_invalidUuid_nullOutput() {
- Workflow workflow = client
- .findWorkflowByArtifactUUID(UUID.randomUUID().toString());
+ Workflow workflow = client.findWorkflowByArtifactUUID(UUID.randomUUID().toString());
Assert.assertNull(workflow);
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAudit.java
index a2c117b3d9..149de0b698 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAudit.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAudit.java
@@ -2,55 +2,55 @@ package org.onap.so.adapters.audit;
import java.io.Serializable;
import java.net.URI;
-
import org.onap.so.client.aai.AAIObjectType;
import org.apache.commons.lang3.builder.ToStringBuilder;
-public class AAIObjectAudit implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = -4560928512855386021L;
- private boolean doesObjectExist = false;
- private Object aaiObject;
- private URI resourceURI;
- private String aaiObjectType;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("doesObjectExist", doesObjectExist).append("aaiObject", aaiObject)
- .append("resourceURI", resourceURI).append("aaiObjectType", aaiObjectType).toString();
- }
-
- public String getAaiObjectType() {
- return aaiObjectType;
- }
-
- public void setAaiObjectType(String aaiObjectType) {
- this.aaiObjectType = aaiObjectType;
- }
-
- public boolean isDoesObjectExist() {
- return doesObjectExist;
- }
-
- public void setDoesObjectExist(boolean doesObjectExist) {
- this.doesObjectExist = doesObjectExist;
- }
-
- public Object getAaiObject() {
- return aaiObject;
- }
-
- public void setAaiObject(Object aaiObject) {
- this.aaiObject = aaiObject;
- }
-
- public URI getResourceURI() {
- return resourceURI;
- }
- public void setResourceURI(URI resourceURI) {
- this.resourceURI = resourceURI;
- }
-} \ No newline at end of file
+public class AAIObjectAudit implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -4560928512855386021L;
+ private boolean doesObjectExist = false;
+ private Object aaiObject;
+ private URI resourceURI;
+ private String aaiObjectType;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("doesObjectExist", doesObjectExist).append("aaiObject", aaiObject)
+ .append("resourceURI", resourceURI).append("aaiObjectType", aaiObjectType).toString();
+ }
+
+ public String getAaiObjectType() {
+ return aaiObjectType;
+ }
+
+ public void setAaiObjectType(String aaiObjectType) {
+ this.aaiObjectType = aaiObjectType;
+ }
+
+ public boolean isDoesObjectExist() {
+ return doesObjectExist;
+ }
+
+ public void setDoesObjectExist(boolean doesObjectExist) {
+ this.doesObjectExist = doesObjectExist;
+ }
+
+ public Object getAaiObject() {
+ return aaiObject;
+ }
+
+ public void setAaiObject(Object aaiObject) {
+ this.aaiObject = aaiObject;
+ }
+
+ public URI getResourceURI() {
+ return resourceURI;
+ }
+
+ public void setResourceURI(URI resourceURI) {
+ this.resourceURI = resourceURI;
+ }
+}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAuditList.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAuditList.java
index a1a8d5b5ed..f3a2cfea9b 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAuditList.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAuditList.java
@@ -5,21 +5,21 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.builder.ToStringBuilder;
-public class AAIObjectAuditList implements Serializable{
+public class AAIObjectAuditList implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 6712662349909726930L;
- private List<AAIObjectAudit> auditList = new ArrayList<>();
+ /**
+ *
+ */
+ private static final long serialVersionUID = 6712662349909726930L;
+ private List<AAIObjectAudit> auditList = new ArrayList<>();
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("auditList", auditList).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("auditList", auditList).toString();
+ }
- public List<AAIObjectAudit> getAuditList() {
- return auditList;
- }
+ public List<AAIObjectAudit> getAuditList() {
+ return auditList;
+ }
-} \ No newline at end of file
+}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java
index 292cebf292..ad28f0daeb 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java
@@ -23,17 +23,17 @@ package org.onap.so.adapters.audit;
import org.onap.so.client.aai.AAIResourcesClient;
public class AbstractAudit {
-
- private AAIResourcesClient aaiClient;
- protected AAIResourcesClient getAaiClient(){
- if(aaiClient == null)
- return new AAIResourcesClient();
- else
- return aaiClient;
- }
-
- protected void setAaiClient(AAIResourcesClient aaiResource){
- aaiClient = aaiResource;
- }
+ private AAIResourcesClient aaiClient;
+
+ protected AAIResourcesClient getAaiClient() {
+ if (aaiClient == null)
+ return new AAIResourcesClient();
+ else
+ return aaiClient;
+ }
+
+ protected void setAaiClient(AAIResourcesClient aaiResource) {
+ aaiClient = aaiResource;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java
index 710a6ddc13..52f5478f2f 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java
@@ -1,7 +1,6 @@
package org.onap.so.adapters.audit;
import java.util.Optional;
-
import org.camunda.bpm.client.task.ExternalTask;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.Logger;
@@ -13,63 +12,64 @@ import org.springframework.stereotype.Component;
@Component
public abstract class AbstractAuditService {
-
- private static final Logger logger = LoggerFactory.getLogger(AbstractAuditService.class);
-
-
-
- protected static final String UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI = "Unable to find all VServers and L-Interaces in A&AI";
-
- @Autowired
- public Environment env;
-
- /**
- * @param auditHeatStackFailed
- * @param auditList
- * @return
- */
- protected boolean didCreateAuditFail(Optional<AAIObjectAuditList> auditList) {
- if (auditList.get().getAuditList() != null && !auditList.get().getAuditList().isEmpty()) {
- if (logger.isInfoEnabled()) {
- logger.info("Audit Results: {}", auditList.get().toString());
- }
- return auditList.get().getAuditList().stream().filter(auditObject -> !auditObject.isDoesObjectExist())
- .findFirst().map(v -> true).orElse(false);
- } else {
- return false;
- }
- }
-
- /**
- * @param auditHeatStackFailed
- * @param auditList
- * @return
- */
- protected boolean didDeleteAuditFail(Optional<AAIObjectAuditList> auditList) {
- if (auditList.get().getAuditList() != null && !auditList.get().getAuditList().isEmpty()) {
- if (logger.isInfoEnabled()) {
- logger.info("Audit Results: {}", auditList.get().toString());
- }
- return auditList.get().getAuditList().stream().filter(AAIObjectAudit::isDoesObjectExist)
- .findFirst().map(v -> true).orElse(false);
- } else {
- return false;
- }
- }
-
- protected String[] getRetrySequence() {
- return env.getProperty("mso.workflow.topics.retrySequence",String[].class);
- }
-
- protected void setupMDC(ExternalTask externalTask) {
- String msoRequestId = externalTask.getVariable("mso-request-id");
- if(msoRequestId != null && !msoRequestId.isEmpty())
- MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId);
- }
-
- protected long calculateRetryDelay(int currentRetries){
- int retrySequence = getRetrySequence().length - currentRetries;
- long retryMultiplier = Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier","6000"));
- return Integer.parseInt(getRetrySequence()[retrySequence]) * retryMultiplier;
- }
+
+ private static final Logger logger = LoggerFactory.getLogger(AbstractAuditService.class);
+
+
+
+ protected static final String UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI =
+ "Unable to find all VServers and L-Interaces in A&AI";
+
+ @Autowired
+ public Environment env;
+
+ /**
+ * @param auditHeatStackFailed
+ * @param auditList
+ * @return
+ */
+ protected boolean didCreateAuditFail(Optional<AAIObjectAuditList> auditList) {
+ if (auditList.get().getAuditList() != null && !auditList.get().getAuditList().isEmpty()) {
+ if (logger.isInfoEnabled()) {
+ logger.info("Audit Results: {}", auditList.get().toString());
+ }
+ return auditList.get().getAuditList().stream().filter(auditObject -> !auditObject.isDoesObjectExist())
+ .findFirst().map(v -> true).orElse(false);
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * @param auditHeatStackFailed
+ * @param auditList
+ * @return
+ */
+ protected boolean didDeleteAuditFail(Optional<AAIObjectAuditList> auditList) {
+ if (auditList.get().getAuditList() != null && !auditList.get().getAuditList().isEmpty()) {
+ if (logger.isInfoEnabled()) {
+ logger.info("Audit Results: {}", auditList.get().toString());
+ }
+ return auditList.get().getAuditList().stream().filter(AAIObjectAudit::isDoesObjectExist).findFirst()
+ .map(v -> true).orElse(false);
+ } else {
+ return false;
+ }
+ }
+
+ protected String[] getRetrySequence() {
+ return env.getProperty("mso.workflow.topics.retrySequence", String[].class);
+ }
+
+ protected void setupMDC(ExternalTask externalTask) {
+ String msoRequestId = externalTask.getVariable("mso-request-id");
+ if (msoRequestId != null && !msoRequestId.isEmpty())
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId);
+ }
+
+ protected long calculateRetryDelay(int currentRetries) {
+ int retrySequence = getRetrySequence().length - currentRetries;
+ long retryMultiplier = Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier", "6000"));
+ return Integer.parseInt(getRetrySequence()[retrySequence]) * retryMultiplier;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java
index 5dfba25141..d46229ae8e 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java
@@ -25,7 +25,6 @@ package org.onap.so.adapters.audit;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-
import org.camunda.bpm.client.task.ExternalTask;
import org.camunda.bpm.client.task.ExternalTaskService;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
@@ -40,54 +39,59 @@ import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
-public class AuditCreateStackService extends AbstractAuditService{
+public class AuditCreateStackService extends AbstractAuditService {
+
+ private static final Logger logger = LoggerFactory.getLogger(AuditCreateStackService.class);
+
+ @Autowired
+ public HeatStackAudit heatStackAudit;
- private static final Logger logger = LoggerFactory.getLogger(AuditCreateStackService.class);
-
- @Autowired
- public HeatStackAudit heatStackAudit;
-
- @Autowired
- public Environment env;
+ @Autowired
+ public Environment env;
- protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService){
- AuditInventory auditInventory = externalTask.getVariable("auditInventory");
+ protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) {
+ AuditInventory auditInventory = externalTask.getVariable("auditInventory");
Map<String, Object> variables = new HashMap<>();
- setupMDC(externalTask);
- boolean success = false;
- try {
- logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory,externalTask.getRetries());
- Optional<AAIObjectAuditList> auditListOpt= heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(), auditInventory.getCloudOwner(),
- auditInventory.getTenantId(), auditInventory.getHeatStackName());
- if (auditListOpt.isPresent()) {
- GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider();
- variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get()));
- success = !didCreateAuditFail(auditListOpt);
- }
- } catch (Exception e) {
- logger.error("Error during audit of stack", e);
- }
- variables.put("auditIsSuccessful", success);
- if (success) {
- externalTaskService.complete(externalTask,variables);
- logger.debug("The External Task Id: {} Successful", externalTask.getId());
- } else {
- if(externalTask.getRetries() == null){
- logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", externalTask.getId(),getRetrySequence().length);
- externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000);
- }else if(externalTask.getRetries() != null &&
- externalTask.getRetries()-1 == 0){
- logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId());
- externalTaskService.complete(externalTask, variables);
- }else{
- logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", externalTask.getId(),externalTask.getRetries()-1, calculateRetryDelay(externalTask.getRetries()));
- externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, externalTask.getRetries()-1, calculateRetryDelay(externalTask.getRetries()));
- }
- logger.debug("The External Task Id: {} Failed", externalTask.getId());
- }
- }
+ setupMDC(externalTask);
+ boolean success = false;
+ try {
+ logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory,
+ externalTask.getRetries());
+ Optional<AAIObjectAuditList> auditListOpt = heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(),
+ auditInventory.getCloudOwner(), auditInventory.getTenantId(), auditInventory.getHeatStackName());
+ if (auditListOpt.isPresent()) {
+ GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider();
+ variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get()));
+ success = !didCreateAuditFail(auditListOpt);
+ }
+ } catch (Exception e) {
+ logger.error("Error during audit of stack", e);
+ }
+ variables.put("auditIsSuccessful", success);
+ if (success) {
+ externalTaskService.complete(externalTask, variables);
+ logger.debug("The External Task Id: {} Successful", externalTask.getId());
+ } else {
+ if (externalTask.getRetries() == null) {
+ logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}",
+ externalTask.getId(), getRetrySequence().length);
+ externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI,
+ UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000);
+ } else if (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) {
+ logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId());
+ externalTaskService.complete(externalTask, variables);
+ } else {
+ logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ",
+ externalTask.getId(), externalTask.getRetries() - 1,
+ calculateRetryDelay(externalTask.getRetries()));
+ externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI,
+ UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, externalTask.getRetries() - 1,
+ calculateRetryDelay(externalTask.getRetries()));
+ }
+ logger.debug("The External Task Id: {} Failed", externalTask.getId());
+ }
+ }
-
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java
index 2c2b2f810d..aca6e9e268 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java
@@ -23,7 +23,6 @@ package org.onap.so.adapters.audit;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-
import org.camunda.bpm.client.task.ExternalTask;
import org.camunda.bpm.client.task.ExternalTaskService;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
@@ -37,51 +36,57 @@ import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
-public class AuditDeleteStackService extends AbstractAuditService{
-
- private static final Logger logger = LoggerFactory.getLogger(AuditDeleteStackService.class);
-
- @Autowired
- public HeatStackAudit heatStackAudit;
-
- @Autowired
- public Environment env;
+public class AuditDeleteStackService extends AbstractAuditService {
+
+ private static final Logger logger = LoggerFactory.getLogger(AuditDeleteStackService.class);
+
+ @Autowired
+ public HeatStackAudit heatStackAudit;
+
+ @Autowired
+ public Environment env;
- protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService){
- AuditInventory auditInventory = externalTask.getVariable("auditInventory");
- Map<String, Object> variables = new HashMap<>();
- setupMDC(externalTask);
- boolean success = false;
- try {
- logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory,externalTask.getRetries());
- Optional<AAIObjectAuditList> auditListOpt=heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(), auditInventory.getCloudOwner(),
- auditInventory.getTenantId(), auditInventory.getHeatStackName());
- if (auditListOpt.isPresent()) {
- GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider();
- variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get()));
- success = didDeleteAuditFail(auditListOpt);
- }
- } catch (Exception e) {
- logger.error("Error during audit of stack", e);
- }
- variables.put("auditIsSuccessful", success);
- if (success) {
- externalTaskService.complete(externalTask, variables);
- logger.debug("The External Task Id: {} Successful", externalTask.getId());
- } else {
- if(externalTask.getRetries() == null){
- logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", externalTask.getId(),getRetrySequence().length);
- externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000);
- }else if(externalTask.getRetries() != null &&
- externalTask.getRetries()-1 == 0){
- logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId());
- externalTaskService.complete(externalTask);
- }else{
- logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", externalTask.getId(),externalTask.getRetries()-1, calculateRetryDelay(externalTask.getRetries()));
- externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, externalTask.getRetries()-1, calculateRetryDelay(externalTask.getRetries()));
- }
- logger.debug("The External Task Id: {} Failed", externalTask.getId());
- }
- }
+ protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) {
+ AuditInventory auditInventory = externalTask.getVariable("auditInventory");
+ Map<String, Object> variables = new HashMap<>();
+ setupMDC(externalTask);
+ boolean success = false;
+ try {
+ logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory,
+ externalTask.getRetries());
+ Optional<AAIObjectAuditList> auditListOpt = heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(),
+ auditInventory.getCloudOwner(), auditInventory.getTenantId(), auditInventory.getHeatStackName());
+ if (auditListOpt.isPresent()) {
+ GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider();
+ variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get()));
+ success = didDeleteAuditFail(auditListOpt);
+ }
+ } catch (Exception e) {
+ logger.error("Error during audit of stack", e);
+ }
+ variables.put("auditIsSuccessful", success);
+ if (success) {
+ externalTaskService.complete(externalTask, variables);
+ logger.debug("The External Task Id: {} Successful", externalTask.getId());
+ } else {
+ if (externalTask.getRetries() == null) {
+ logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}",
+ externalTask.getId(), getRetrySequence().length);
+ externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI,
+ UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000);
+ } else if (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) {
+ logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId());
+ externalTaskService.complete(externalTask);
+ } else {
+ logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ",
+ externalTask.getId(), externalTask.getRetries() - 1,
+ calculateRetryDelay(externalTask.getRetries()));
+ externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI,
+ UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, externalTask.getRetries() - 1,
+ calculateRetryDelay(externalTask.getRetries()));
+ }
+ logger.debug("The External Task Id: {} Failed", externalTask.getId());
+ }
+ }
-} \ No newline at end of file
+}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java
index ed29a1c47d..3508810e04 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java
@@ -21,9 +21,7 @@
package org.onap.so.adapters.audit;
import java.security.GeneralSecurityException;
-
import javax.annotation.PostConstruct;
-
import org.camunda.bpm.client.ExternalTaskClient;
import org.camunda.bpm.client.backoff.ExponentialBackoffStrategy;
import org.camunda.bpm.client.interceptor.ClientRequestInterceptor;
@@ -40,49 +38,48 @@ import org.springframework.stereotype.Component;
@Profile("!test")
public class AuditStackService {
- private static final Logger logger = LoggerFactory.getLogger(AuditStackService.class);
+ private static final Logger logger = LoggerFactory.getLogger(AuditStackService.class);
+
+ @Autowired
+ public Environment env;
+
+ @Autowired
+ private AuditCreateStackService auditCreateStack;
+
+ @Autowired
+ private AuditDeleteStackService auditDeleteStack;
- @Autowired
- public Environment env;
+ @PostConstruct
+ public void auditAddAAIInventory() {
+ String auth = "";
+ try {
+ auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey"));
+ } catch (IllegalStateException | GeneralSecurityException e) {
+ logger.error("Error Decrypting Password", e);
+ }
+ ClientRequestInterceptor interceptor =
+ new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth);
+ ExternalTaskClient client = ExternalTaskClient.create()
+ .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor)
+ .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build();
+ client.subscribe("InventoryAddAudit").lockDuration(60000).handler(auditCreateStack::executeExternalTask).open();
+ }
- @Autowired
- private AuditCreateStackService auditCreateStack;
-
- @Autowired
- private AuditDeleteStackService auditDeleteStack;
+ @PostConstruct
+ public void auditDeleteAAIInventory() {
+ String auth = "";
+ try {
+ auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey"));
+ } catch (IllegalStateException | GeneralSecurityException e) {
+ logger.error("Error Decrypting Password", e);
+ }
+ ClientRequestInterceptor interceptor =
+ new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth);
+ ExternalTaskClient client = ExternalTaskClient.create()
+ .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor)
+ .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build();
+ client.subscribe("InventoryDeleteAudit").lockDuration(60000).handler(auditDeleteStack::executeExternalTask)
+ .open();
+ }
- @PostConstruct
- public void auditAddAAIInventory() {
- String auth = "";
- try {
- auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey"));
- } catch (IllegalStateException | GeneralSecurityException e) {
- logger.error("Error Decrypting Password", e);
- }
- ClientRequestInterceptor interceptor = new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"),
- auth);
- ExternalTaskClient client = ExternalTaskClient.create()
- .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor)
- .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build();
- client.subscribe("InventoryAddAudit").lockDuration(60000)
- .handler(auditCreateStack::executeExternalTask).open();
- }
-
- @PostConstruct
- public void auditDeleteAAIInventory() {
- String auth = "";
- try {
- auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey"));
- } catch (IllegalStateException | GeneralSecurityException e) {
- logger.error("Error Decrypting Password", e);
- }
- ClientRequestInterceptor interceptor = new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"),
- auth);
- ExternalTaskClient client = ExternalTaskClient.create()
- .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor)
- .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0,0,0)).build();
- client.subscribe("InventoryDeleteAudit").lockDuration(60000)
- .handler(auditDeleteStack::executeExternalTask).open();
- }
-
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java
index 519e1c92b1..8559fe5c36 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.audit;
import java.util.Optional;
import java.util.Set;
-
import org.onap.aai.domain.yang.LInterface;
import org.onap.aai.domain.yang.Vserver;
import org.onap.so.client.aai.AAIObjectType;
@@ -33,97 +32,100 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
@Component
public class AuditVServer extends AbstractAudit {
- private static final Logger logger = LoggerFactory.getLogger(AuditVServer.class);
+ private static final Logger logger = LoggerFactory.getLogger(AuditVServer.class);
+
+ public Optional<AAIObjectAuditList> auditVservers(Set<Vserver> vServersToAudit, String tenantId, String cloudOwner,
+ String cloudRegion) {
+ if (vServersToAudit == null || vServersToAudit.isEmpty()) {
+ return Optional.empty();
+ }
+ GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider();
+ vServersToAudit.stream().forEach(vserver -> {
+ try {
+ logger.debug("Vserver to Audit: {}", objectMapper.getMapper().writeValueAsString(vserver));
+ } catch (JsonProcessingException e) {
+
+ }
+ });
+ AAIObjectAuditList auditList = new AAIObjectAuditList();
+ vServersToAudit.stream().forEach(vServer -> auditList.getAuditList()
+ .addAll(doesVServerExistInAAI(vServer, tenantId, cloudOwner, cloudRegion).getAuditList()));
+ return Optional.of(auditList);
+ }
+
+ private AAIObjectAuditList doesVServerExistInAAI(Vserver vServer, String tenantId, String cloudOwner,
+ String cloudRegion) {
+ AAIObjectAuditList auditList = new AAIObjectAuditList();
+ AAIObjectAudit vServerAudit = new AAIObjectAudit();
+ AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion,
+ tenantId, vServer.getVserverId());
+ Vserver vServerShallow = new Vserver();
+ BeanUtils.copyProperties(vServer, vServerShallow, "LInterfaces");
+ boolean vServerExists = getAaiClient().exists(vserverURI);
+ logger.info("v-server {} exists: {}", vServer.getVserverId(), vServerExists);
+ vServerAudit.setAaiObject(vServerShallow);
+ vServerAudit.setDoesObjectExist(vServerExists);
+ vServerAudit.setResourceURI(vserverURI.build());
+ vServerAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName());
+ auditList.getAuditList().add(vServerAudit);
+ if (vServer.getLInterfaces() != null) {
+ vServer.getLInterfaces().getLInterface().stream().forEach(lInterface -> auditList.getAuditList().addAll(
+ doesLinterfaceExistinAAI(lInterface, vServer.getVserverId(), tenantId, cloudOwner, cloudRegion)
+ .getAuditList()));
+ }
+ return auditList;
+ }
- public Optional<AAIObjectAuditList> auditVservers(Set<Vserver> vServersToAudit, String tenantId, String cloudOwner, String cloudRegion) {
- if (vServersToAudit == null || vServersToAudit.isEmpty()){
- return Optional.empty();
- }
- GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider();
- vServersToAudit.stream().forEach(vserver -> {
- try {
- logger.debug("Vserver to Audit: {}",objectMapper.getMapper().writeValueAsString(vserver));
- } catch (JsonProcessingException e) {
-
- }
- });
- AAIObjectAuditList auditList = new AAIObjectAuditList();
- vServersToAudit.stream()
- .forEach(vServer -> auditList.getAuditList().addAll(doesVServerExistInAAI(vServer, tenantId, cloudOwner, cloudRegion).getAuditList()));
- return Optional.of(auditList);
- }
+ private AAIObjectAuditList doesLinterfaceExistinAAI(LInterface lInterface, String vServerId, String tenantId,
+ String cloudOwner, String cloudRegion) {
+ AAIObjectAuditList auditList = new AAIObjectAuditList();
+ AAIObjectAudit lInterfaceAudit = new AAIObjectAudit();
+ AAIResourceUri linterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner,
+ cloudRegion, tenantId, vServerId, lInterface.getInterfaceName());
+ Optional<LInterface> queriedLInterface = getAaiClient().get(LInterface.class, linterfaceURI);
+ if (queriedLInterface.isPresent()) {
+ lInterfaceAudit.setDoesObjectExist(true);
+ lInterface.setInterfaceName(lInterface.getInterfaceName());
+ }
+ LInterface lInterfaceShallow = new LInterface();
+ BeanUtils.copyProperties(lInterface, lInterfaceShallow, "LInterfaces");
+ lInterfaceAudit.setAaiObject(lInterface);
+ lInterfaceAudit.setResourceURI(linterfaceURI.build());
+ lInterfaceAudit.setAaiObjectType(AAIObjectType.L_INTERFACE.typeName());
+ auditList.getAuditList().add(lInterfaceAudit);
+ logger.info("l-interface id:{} name: {} exists: {} ", lInterface.getInterfaceId(),
+ lInterface.getInterfaceName(), lInterfaceAudit.isDoesObjectExist());
- private AAIObjectAuditList doesVServerExistInAAI(Vserver vServer, String tenantId, String cloudOwner, String cloudRegion) {
- AAIObjectAuditList auditList = new AAIObjectAuditList();
- AAIObjectAudit vServerAudit = new AAIObjectAudit();
- AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion,
- tenantId, vServer.getVserverId());
- Vserver vServerShallow = new Vserver();
- BeanUtils.copyProperties(vServer,vServerShallow,"LInterfaces");
- boolean vServerExists = getAaiClient().exists(vserverURI);
- logger.info("v-server {} exists: {}", vServer.getVserverId(), vServerExists);
- vServerAudit.setAaiObject(vServerShallow);
- vServerAudit.setDoesObjectExist(vServerExists);
- vServerAudit.setResourceURI(vserverURI.build());
- vServerAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName());
- auditList.getAuditList().add(vServerAudit);
- if (vServer.getLInterfaces() != null) {
- vServer.getLInterfaces().getLInterface().stream().forEach(lInterface -> auditList.getAuditList().addAll(doesLinterfaceExistinAAI(lInterface,
- vServer.getVserverId(), tenantId, cloudOwner, cloudRegion).getAuditList()));
- }
- return auditList;
- }
+ if (lInterface.getLInterfaces() != null) {
+ lInterface.getLInterfaces().getLInterface().stream()
+ .forEach(subInterface -> auditList.getAuditList().add(doesSubInterfaceExistinAAI(subInterface,
+ lInterface.getInterfaceName(), vServerId, tenantId, cloudOwner, cloudRegion)));
+ }
+ logger.debug("l-interface {} does not contain any sub-iterfaces, skipping audit of sub-interfaces",
+ lInterface.getInterfaceId());
- private AAIObjectAuditList doesLinterfaceExistinAAI(LInterface lInterface, String vServerId, String tenantId,
- String cloudOwner, String cloudRegion) {
- AAIObjectAuditList auditList = new AAIObjectAuditList();
- AAIObjectAudit lInterfaceAudit = new AAIObjectAudit();
- AAIResourceUri linterfaceURI = AAIUriFactory
- .createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, cloudRegion, tenantId, vServerId, lInterface.getInterfaceName());
- Optional<LInterface> queriedLInterface = getAaiClient().get(LInterface.class, linterfaceURI);
- if (queriedLInterface.isPresent()) {
- lInterfaceAudit.setDoesObjectExist(true);
- lInterface.setInterfaceName(lInterface.getInterfaceName());
- }
- LInterface lInterfaceShallow = new LInterface();
- BeanUtils.copyProperties(lInterface,lInterfaceShallow,"LInterfaces");
- lInterfaceAudit.setAaiObject(lInterface);
- lInterfaceAudit.setResourceURI(linterfaceURI.build());
- lInterfaceAudit.setAaiObjectType(AAIObjectType.L_INTERFACE.typeName());
- auditList.getAuditList().add(lInterfaceAudit);
- logger.info("l-interface id:{} name: {} exists: {} ", lInterface.getInterfaceId(), lInterface.getInterfaceName(),
- lInterfaceAudit.isDoesObjectExist());
+ return auditList;
+ }
- if (lInterface.getLInterfaces() != null) {
- lInterface.getLInterfaces().getLInterface().stream()
- .forEach(subInterface -> auditList.getAuditList().add(doesSubInterfaceExistinAAI(subInterface,
- lInterface.getInterfaceName(), vServerId, tenantId, cloudOwner, cloudRegion)));
- }
- logger.debug("l-interface {} does not contain any sub-iterfaces, skipping audit of sub-interfaces", lInterface.getInterfaceId());
+ private AAIObjectAudit doesSubInterfaceExistinAAI(LInterface subInterface, String linterfaceName, String vServerId,
+ String tenantId, String cloudOwner, String cloudRegion) {
+ logger.info("checking if sub-l-interface {} , linterfaceName: {} vserverId: {} exists",
+ subInterface.getInterfaceName(), linterfaceName, vServerId);
+ AAIObjectAudit subInterfaceAudit = new AAIObjectAudit();
- return auditList;
- }
- private AAIObjectAudit doesSubInterfaceExistinAAI(LInterface subInterface, String linterfaceName, String vServerId,
- String tenantId, String cloudOwner, String cloudRegion) {
- logger.info("checking if sub-l-interface {} , linterfaceName: {} vserverId: {} exists",
- subInterface.getInterfaceName(), linterfaceName, vServerId);
- AAIObjectAudit subInterfaceAudit = new AAIObjectAudit();
-
-
- AAIResourceUri subInterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner,
- cloudRegion, tenantId, vServerId, linterfaceName, subInterface.getInterfaceName());
- subInterfaceAudit.setResourceURI(subInterfaceURI.build());
- boolean doesExist = getAaiClient().exists(subInterfaceURI);
- logger.info("sub-l-interface-id:{} exists: {}", subInterface.getInterfaceId(), doesExist);
- subInterfaceAudit.setAaiObject(subInterface);
- subInterfaceAudit.setDoesObjectExist(doesExist);
- subInterfaceAudit.setAaiObjectType(AAIObjectType.SUB_L_INTERFACE.typeName());
- return subInterfaceAudit;
- }
+ AAIResourceUri subInterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner,
+ cloudRegion, tenantId, vServerId, linterfaceName, subInterface.getInterfaceName());
+ subInterfaceAudit.setResourceURI(subInterfaceURI.build());
+ boolean doesExist = getAaiClient().exists(subInterfaceURI);
+ logger.info("sub-l-interface-id:{} exists: {}", subInterface.getInterfaceId(), doesExist);
+ subInterfaceAudit.setAaiObject(subInterface);
+ subInterfaceAudit.setDoesObjectExist(doesExist);
+ subInterfaceAudit.setAaiObjectType(AAIObjectType.SUB_L_INTERFACE.typeName());
+ return subInterfaceAudit;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java
index b522300b6a..5c0d2d3019 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java
@@ -30,7 +30,6 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-
import org.onap.aai.domain.yang.LInterface;
import org.onap.aai.domain.yang.LInterfaces;
import org.onap.aai.domain.yang.Vlan;
@@ -42,7 +41,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.woorea.openstack.heat.model.Link;
import com.woorea.openstack.heat.model.Resource;
import com.woorea.openstack.heat.model.Resources;
@@ -52,213 +50,222 @@ import com.woorea.openstack.quantum.model.Port;
@Component
public class HeatStackAudit {
- private static final String RESOURCES = "/resources";
+ private static final String RESOURCES = "/resources";
+
+ protected static final Logger logger = LoggerFactory.getLogger(HeatStackAudit.class);
+
+ @Autowired
+ protected MsoHeatUtils heat;
+
+ @Autowired
+ protected MsoNeutronUtils neutron;
+
+ @Autowired
+ protected AuditVServer auditVservers;
+
+ public Optional<AAIObjectAuditList> auditHeatStack(String cloudRegion, String cloudOwner, String tenantId,
+ String heatStackName) {
+ try {
+ logger.debug("Fetching Top Level Stack Information");
+ Resources resources = heat.queryStackResources(cloudRegion, tenantId, heatStackName, 3);
+ List<Resource> novaResources = resources.getList().stream()
+ .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList());
+ List<Resource> resourceGroups = resources.getList().stream()
+ .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType()) && p.getName().contains("subinterfaces"))
+ .collect(Collectors.toList());
+ List<Optional<Port>> neutronPortDetails = retrieveNeutronPortDetails(resources, cloudRegion, tenantId);
+ if (novaResources.isEmpty())
+ return Optional.of(new AAIObjectAuditList());
+ else {
+ Set<Vserver> vserversToAudit = createVserverSet(resources, novaResources, neutronPortDetails);
+ Set<Vserver> vserversWithSubInterfaces =
+ processSubInterfaces(cloudRegion, tenantId, resourceGroups, vserversToAudit);
+ return auditVservers.auditVservers(vserversWithSubInterfaces, tenantId, cloudOwner, cloudRegion);
+ }
+ } catch (Exception e) {
+ logger.error("Error during auditing stack resources", e);
+ return Optional.empty();
+ }
+ }
+
+ protected Set<Vserver> processSubInterfaces(String cloudRegion, String tenantId, List<Resource> resourceGroups,
+ Set<Vserver> vServersToAudit) throws Exception {
+ for (Resource resourceGroup : resourceGroups) {
+ processResourceGroups(cloudRegion, tenantId, vServersToAudit, resourceGroup);
+ }
+ return vServersToAudit;
+ }
+
+ protected void processResourceGroups(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface,
+ Resource resourceGroup) throws Exception {
+ Optional<Link> stackLink =
+ resourceGroup.getLinks().stream().filter(link -> "nested".equals(link.getRel())).findAny();
+ if (stackLink.isPresent()) {
+ try {
+ Optional<String> path = extractResourcePathFromHref(stackLink.get().getHref());
+ if (path.isPresent()) {
+ logger.debug("Fetching nested Resource Stack Information");
+ Resources nestedResourceGroupResources =
+ heat.executeHeatClientRequest(path.get(), cloudRegion, tenantId, Resources.class);
+ processNestedResourceGroup(cloudRegion, tenantId, vServersWithLInterface,
+ nestedResourceGroupResources);
+ } else
+ throw new Exception("Error finding Path from Self Link");
+ } catch (Exception e) {
+ logger.error("Error Parsing Link to obtain Path", e);
+ throw new Exception("Error finding Path from Self Link");
+ }
+ }
+ }
+
+ protected void processNestedResourceGroup(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface,
+ Resources nestedResourceGroupResources) throws Exception {
+ for (Resource resourceGroupNested : nestedResourceGroupResources) {
+ Optional<Link> subInterfaceStackLink =
+ resourceGroupNested.getLinks().stream().filter(link -> "nested".equals(link.getRel())).findAny();
+ if (subInterfaceStackLink.isPresent()) {
+ addSubInterface(cloudRegion, tenantId, vServersWithLInterface, subInterfaceStackLink.get());
+ }
+ }
+ }
+
+ protected void addSubInterface(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface,
+ Link subInterfaceStackLink) throws Exception {
+ Optional<String> resourcePath = extractResourcePathFromHref(subInterfaceStackLink.getHref());
+ Optional<String> stackPath = extractStackPathFromHref(subInterfaceStackLink.getHref());
+ if (resourcePath.isPresent() && stackPath.isPresent()) {
+ logger.debug("Fetching nested Sub-Interface Stack Information");
+ Stack subinterfaceStack =
+ heat.executeHeatClientRequest(stackPath.get(), cloudRegion, tenantId, Stack.class);
+ Resources subinterfaceResources =
+ heat.executeHeatClientRequest(resourcePath.get(), cloudRegion, tenantId, Resources.class);
+ if (subinterfaceStack != null) {
+ addSubInterfaceToVserver(vServersWithLInterface, subinterfaceStack, subinterfaceResources);
+ }
+ } else
+ throw new Exception("Error finding Path from Self Link");
- protected static final Logger logger = LoggerFactory.getLogger(HeatStackAudit.class);
+ }
- @Autowired
- protected MsoHeatUtils heat;
-
- @Autowired
- protected MsoNeutronUtils neutron;
+ protected void addSubInterfaceToVserver(Set<Vserver> vServersWithLInterface, Stack subinterfaceStack,
+ Resources subinterfaceResources) throws Exception {
+ String parentNeutronPortId = (String) subinterfaceStack.getParameters().get("port_interface");
+ logger.debug("Parent neutron Port: {} on SubInterface: {}", parentNeutronPortId, subinterfaceStack.getId());
+ for (Vserver auditVserver : vServersWithLInterface)
+ for (LInterface lInterface : auditVserver.getLInterfaces().getLInterface())
- @Autowired
- protected AuditVServer auditVservers;
+ if (parentNeutronPortId.equals(lInterface.getInterfaceId())) {
+ logger.debug("Found Parent Port on VServer: {} on Port: {}", auditVserver.getVserverId(),
+ lInterface.getInterfaceId());
+ Resource contrailVm = subinterfaceResources.getList().stream()
+ .filter(resource -> "OS::ContrailV2::VirtualMachineInterface".equals(resource.getType()))
+ .findAny().orElse(null);
+ if (contrailVm == null) {
+ throw new Exception("Cannnot find Contrail Virtual Machine Interface on Stack: "
+ + subinterfaceStack.getId());
+ }
+ LInterface subInterface = new LInterface();
+ subInterface.setInterfaceId(contrailVm.getPhysicalResourceId());
+ subInterface.setIsPortMirrored(false);
+ subInterface.setInMaint(false);
+ subInterface.setIsIpUnnumbered(false);
+ String macAddr = (String) subinterfaceStack.getParameters().get("mac_address");
+ subInterface.setMacaddr(macAddr);
- public Optional<AAIObjectAuditList> auditHeatStack(String cloudRegion, String cloudOwner, String tenantId, String heatStackName) {
- try {
- logger.debug("Fetching Top Level Stack Information");
- Resources resources = heat.queryStackResources(cloudRegion, tenantId, heatStackName, 3);
- List<Resource> novaResources = resources.getList().stream()
- .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList());
- List<Resource> resourceGroups = resources.getList().stream()
- .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType()) && p.getName().contains("subinterfaces"))
- .collect(Collectors.toList());
- List<Optional<Port>> neutronPortDetails = retrieveNeutronPortDetails(resources, cloudRegion, tenantId);
- if (novaResources.isEmpty())
- return Optional.of(new AAIObjectAuditList());
- else {
- Set<Vserver> vserversToAudit = createVserverSet(resources, novaResources, neutronPortDetails);
- Set<Vserver> vserversWithSubInterfaces = processSubInterfaces(cloudRegion, tenantId, resourceGroups,
- vserversToAudit);
- return auditVservers.auditVservers(vserversWithSubInterfaces,
- tenantId, cloudOwner, cloudRegion);
- }
- } catch (Exception e) {
- logger.error("Error during auditing stack resources", e);
- return Optional.empty();
- }
- }
+ String namePrefix = (String) subinterfaceStack.getParameters().get("subinterface_name_prefix");
+ Integer vlanIndex = Integer.parseInt((String) subinterfaceStack.getParameters().get("counter"));
+ String vlanTagList = (String) subinterfaceStack.getParameters().get("vlan_tag");
+ List<String> subInterfaceVlanTagList = Arrays.asList(vlanTagList.split(","));
+ subInterface.setInterfaceName(namePrefix + "_" + subInterfaceVlanTagList.get(vlanIndex));
+ subInterface.setVlans(new Vlans());
+ Vlan vlan = new Vlan();
+ vlan.setInMaint(false);
+ vlan.setIsIpUnnumbered(false);
+ vlan.setVlanIdInner(Long.parseLong(subInterfaceVlanTagList.get(vlanIndex)));
+ vlan.setVlanInterface(namePrefix + "_" + subInterfaceVlanTagList.get(vlanIndex));
+ subInterface.getVlans().getVlan().add(vlan);
+ if (lInterface.getLInterfaces() == null)
+ lInterface.setLInterfaces(new LInterfaces());
- protected Set<Vserver> processSubInterfaces(String cloudRegion, String tenantId, List<Resource> resourceGroups,
- Set<Vserver> vServersToAudit) throws Exception {
- for (Resource resourceGroup : resourceGroups) {
- processResourceGroups(cloudRegion, tenantId, vServersToAudit, resourceGroup);
- }
- return vServersToAudit;
- }
+ lInterface.getLInterfaces().getLInterface().add(subInterface);
+ } else
+ logger.debug("Did Not Find Parent Port on VServer: {} Parent Port: SubInterface: {}",
+ auditVserver.getVserverId(), lInterface.getInterfaceId(), subinterfaceStack.getId());
+ }
- protected void processResourceGroups(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface,
- Resource resourceGroup) throws Exception {
- Optional<Link> stackLink = resourceGroup.getLinks().stream().filter(link -> "nested".equals(link.getRel()))
- .findAny();
- if (stackLink.isPresent()) {
- try {
- Optional<String> path = extractResourcePathFromHref(stackLink.get().getHref());
- if (path.isPresent()) {
- logger.debug("Fetching nested Resource Stack Information");
- Resources nestedResourceGroupResources = heat.executeHeatClientRequest(path.get(), cloudRegion,
- tenantId, Resources.class);
- processNestedResourceGroup(cloudRegion, tenantId, vServersWithLInterface,
- nestedResourceGroupResources);
- } else
- throw new Exception("Error finding Path from Self Link");
- } catch (Exception e) {
- logger.error("Error Parsing Link to obtain Path", e);
- throw new Exception("Error finding Path from Self Link");
- }
- }
- }
+ protected Set<Vserver> createVserverSet(Resources resources, List<Resource> novaResources,
+ List<Optional<Port>> neutronPortDetails) {
+ Set<Vserver> vserversToAudit = new HashSet<>();
+ for (Resource novaResource : novaResources) {
+ Vserver auditVserver = new Vserver();
+ auditVserver.setLInterfaces(new LInterfaces());
+ auditVserver.setVserverId(novaResource.getPhysicalResourceId());
+ Stream<Port> filteredNeutronPorts = filterNeutronPorts(novaResource, neutronPortDetails);
+ filteredNeutronPorts.forEach(port -> {
+ LInterface lInterface = new LInterface();
+ lInterface.setInterfaceId(port.getId());
+ lInterface.setInterfaceName(port.getName());
+ auditVserver.getLInterfaces().getLInterface().add(lInterface);
+ });
+ vserversToAudit.add(auditVserver);
+ }
+ return vserversToAudit;
+ }
- protected void processNestedResourceGroup(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface,
- Resources nestedResourceGroupResources) throws Exception {
- for (Resource resourceGroupNested : nestedResourceGroupResources) {
- Optional<Link> subInterfaceStackLink = resourceGroupNested.getLinks().stream()
- .filter(link -> "nested".equals(link.getRel())).findAny();
- if (subInterfaceStackLink.isPresent()) {
- addSubInterface(cloudRegion, tenantId, vServersWithLInterface,subInterfaceStackLink.get());
- }
- }
- }
+ /**
+ * @param novaResource Single openstack resource that is of type Nova
+ * @param neutronPorts List of Neutron ports created within the stack
+ * @return Filtered list of neutron ports taht relate to the nova server in openstack
+ */
+ protected Stream<Port> filterNeutronPorts(Resource novaResource, List<Optional<Port>> neutronPorts) {
+ List<Port> filteredNeutronPorts =
+ neutronPorts.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
+ return filteredNeutronPorts.stream()
+ .filter(port -> port.getDeviceId().equalsIgnoreCase(novaResource.getPhysicalResourceId()));
+ }
- protected void addSubInterface(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface, Link subInterfaceStackLink) throws Exception {
- Optional<String> resourcePath = extractResourcePathFromHref(subInterfaceStackLink.getHref());
- Optional<String> stackPath = extractStackPathFromHref(subInterfaceStackLink.getHref());
- if (resourcePath.isPresent() && stackPath.isPresent()) {
- logger.debug("Fetching nested Sub-Interface Stack Information");
- Stack subinterfaceStack = heat.executeHeatClientRequest(stackPath.get(), cloudRegion, tenantId, Stack.class);
- Resources subinterfaceResources = heat.executeHeatClientRequest(resourcePath.get(), cloudRegion, tenantId, Resources.class);
- if (subinterfaceStack != null) {
- addSubInterfaceToVserver(vServersWithLInterface, subinterfaceStack, subinterfaceResources);
- }
- } else
- throw new Exception("Error finding Path from Self Link");
-
- }
+ /**
+ * @param resources Resource stream created by the stack in openstack
+ * @param cloudSiteId Unique site id to identify which openstack we talk to
+ * @param tenantId The tenant within the cloud we are talking to where resouces exist
+ * @return List of optional neutron ports found within the cloud site and tenant
+ */
+ protected List<Optional<Port>> retrieveNeutronPortDetails(Resources resources, String cloudSiteId,
+ String tenantId) {
+ return resources.getList().parallelStream().filter(resource -> "OS::Neutron::Port".equals(resource.getType()))
+ .map(resource -> neutron.getNeutronPort(resource.getPhysicalResourceId(), tenantId, cloudSiteId))
+ .collect(Collectors.toList());
- protected void addSubInterfaceToVserver(Set<Vserver> vServersWithLInterface, Stack subinterfaceStack, Resources subinterfaceResources) throws Exception {
- String parentNeutronPortId = (String) subinterfaceStack.getParameters().get("port_interface");
- logger.debug("Parent neutron Port: {} on SubInterface: {}", parentNeutronPortId, subinterfaceStack.getId());
- for (Vserver auditVserver : vServersWithLInterface)
- for (LInterface lInterface : auditVserver.getLInterfaces().getLInterface())
-
- if (parentNeutronPortId.equals(lInterface.getInterfaceId())) {
- logger.debug("Found Parent Port on VServer: {} on Port: {}", auditVserver.getVserverId(), lInterface.getInterfaceId());
- Resource contrailVm = subinterfaceResources.getList().stream().filter(resource -> "OS::ContrailV2::VirtualMachineInterface".equals(resource.getType())).findAny()
- .orElse(null);
- if(contrailVm == null){
- throw new Exception("Cannnot find Contrail Virtual Machine Interface on Stack: "+ subinterfaceStack.getId());
- }
- LInterface subInterface = new LInterface();
- subInterface.setInterfaceId(contrailVm.getPhysicalResourceId());
- subInterface.setIsPortMirrored(false);
- subInterface.setInMaint(false);
- subInterface.setIsIpUnnumbered(false);
- String macAddr = (String) subinterfaceStack.getParameters().get("mac_address");
- subInterface.setMacaddr(macAddr);
-
- String namePrefix = (String) subinterfaceStack.getParameters().get("subinterface_name_prefix");
- Integer vlanIndex = Integer.parseInt((String) subinterfaceStack.getParameters().get("counter"));
- String vlanTagList = (String) subinterfaceStack.getParameters().get("vlan_tag");
- List<String> subInterfaceVlanTagList = Arrays.asList(vlanTagList.split(","));
- subInterface.setInterfaceName(namePrefix+"_"+subInterfaceVlanTagList.get(vlanIndex));
- subInterface.setVlans(new Vlans());
- Vlan vlan = new Vlan();
- vlan.setInMaint(false);
- vlan.setIsIpUnnumbered(false);
- vlan.setVlanIdInner(Long.parseLong(subInterfaceVlanTagList.get(vlanIndex)));
- vlan.setVlanInterface(namePrefix+"_"+subInterfaceVlanTagList.get(vlanIndex));
- subInterface.getVlans().getVlan().add(vlan);
- if(lInterface.getLInterfaces() == null)
- lInterface.setLInterfaces(new LInterfaces());
-
- lInterface.getLInterfaces().getLInterface().add(subInterface);
- }else
- logger.debug("Did Not Find Parent Port on VServer: {} Parent Port: SubInterface: {}",auditVserver.getVserverId(),
- lInterface.getInterfaceId(),subinterfaceStack.getId());
- }
+ }
- protected Set<Vserver> createVserverSet(Resources resources, List<Resource> novaResources, List<Optional<Port>> neutronPortDetails) {
- Set<Vserver> vserversToAudit = new HashSet<>();
- for (Resource novaResource : novaResources) {
- Vserver auditVserver = new Vserver();
- auditVserver.setLInterfaces(new LInterfaces());
- auditVserver.setVserverId(novaResource.getPhysicalResourceId());
- Stream<Port> filteredNeutronPorts = filterNeutronPorts(novaResource, neutronPortDetails);
- filteredNeutronPorts.forEach(port -> {
- LInterface lInterface = new LInterface();
- lInterface.setInterfaceId(port.getId());
- lInterface.setInterfaceName(port.getName());
- auditVserver.getLInterfaces().getLInterface().add(lInterface);
- });
- vserversToAudit.add(auditVserver);
- }
- return vserversToAudit;
- }
+ protected Optional<String> extractResourcePathFromHref(String href) {
+ try {
+ Optional<String> stackPath = extractStackPathFromHref(href);
+ if (stackPath.isPresent()) {
+ return Optional.of(stackPath.get() + RESOURCES);
+ } else
+ return Optional.empty();
+ } catch (Exception e) {
+ logger.error("Error parsing URI", e);
+ }
+ return Optional.empty();
+ }
- /**
- * @param novaResource Single openstack resource that is of type Nova
- * @param neutronPorts List of Neutron ports created within the stack
- * @return Filtered list of neutron ports taht relate to the nova server in openstack
- */
- protected Stream<Port> filterNeutronPorts(Resource novaResource, List<Optional<Port>> neutronPorts) {
- List<Port> filteredNeutronPorts = neutronPorts.stream().filter(Optional::isPresent).map(Optional::get)
- .collect(Collectors.toList());
- return filteredNeutronPorts.stream()
- .filter(port -> port.getDeviceId().equalsIgnoreCase(novaResource.getPhysicalResourceId()));
- }
-
- /**
- * @param resources Resource stream created by the stack in openstack
- * @param cloudSiteId Unique site id to identify which openstack we talk to
- * @param tenantId The tenant within the cloud we are talking to where resouces exist
- * @return List of optional neutron ports found within the cloud site and tenant
- */
- protected List<Optional<Port>> retrieveNeutronPortDetails(Resources resources,String cloudSiteId,String tenantId){
- return resources.getList().parallelStream()
- .filter(resource -> "OS::Neutron::Port".equals(resource.getType()))
- .map(resource -> neutron.getNeutronPort(resource.getPhysicalResourceId(),tenantId,cloudSiteId)).collect(Collectors.toList());
+ protected Optional<String> extractStackPathFromHref(String href) {
+ try {
+ URI uri = new URI(href);
+ Pattern p = Pattern.compile("/stacks.*");
+ Matcher m = p.matcher(uri.getPath());
+ if (m.find()) {
+ return Optional.of(m.group());
+ } else
+ return Optional.empty();
+ } catch (Exception e) {
+ logger.error("Error parsing URI", e);
+ }
+ return Optional.empty();
+ }
- }
- protected Optional<String> extractResourcePathFromHref(String href) {
- try {
- Optional<String> stackPath = extractStackPathFromHref(href);
- if (stackPath.isPresent()){
- return Optional.of(stackPath.get()+RESOURCES);
- }else
- return Optional.empty();
- } catch (Exception e) {
- logger.error("Error parsing URI", e);
- }
- return Optional.empty();
- }
-
- protected Optional<String> extractStackPathFromHref(String href) {
- try {
- URI uri = new URI(href);
- Pattern p = Pattern.compile("/stacks.*");
- Matcher m = p.matcher(uri.getPath());
- if (m.find()){
- return Optional.of(m.group());
- }else
- return Optional.empty();
- } catch (Exception e) {
- logger.error("Error parsing URI", e);
- }
- return Optional.empty();
- }
-
-
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java
index efced9d9f9..4453071e06 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.inventory.create;
import java.util.Optional;
import java.util.stream.Stream;
-
import org.onap.aai.domain.yang.LInterface;
import org.onap.so.adapters.audit.AAIObjectAudit;
import org.onap.so.adapters.audit.AAIObjectAuditList;
@@ -32,37 +31,44 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.springframework.stereotype.Component;
@Component
-public class CreateAAIInventory{
-
- private AAIResourcesClient aaiClient;
+public class CreateAAIInventory {
+
+ private AAIResourcesClient aaiClient;
+
+ public void createInventory(AAIObjectAuditList auditList) throws InventoryException {
+ if (didAuditFailVserverLInterfaces(auditList)) {
+ throw new InventoryException("Audit failed for VServer or LInterface cannot write Sub-Interfaces");
+ }
+ auditList.getAuditList().parallelStream()
+ .filter(auditObject -> !auditObject.isDoesObjectExist()
+ && AAIObjectType.SUB_L_INTERFACE.typeName().equals(auditObject.getAaiObjectType()))
+ .forEach(auditObject -> getAaiClient().createIfNotExists(AAIUriFactory.createResourceFromExistingURI(
+ AAIObjectType.fromTypeName(auditObject.getAaiObjectType()), auditObject.getResourceURI()),
+ Optional.of(auditObject.getAaiObject())));
+ }
+
+
+ /**
+ * @param auditHeatStackFailed
+ * @param auditList
+ * @return
+ */
+ protected boolean didAuditFailVserverLInterfaces(AAIObjectAuditList auditList) {
+ Stream<AAIObjectAudit> issue = auditList.getAuditList().stream()
+ .filter(auditObject -> auditObject.getAaiObjectType().equals(AAIObjectType.VSERVER.typeName())
+ || auditObject.getAaiObjectType().equals(AAIObjectType.L_INTERFACE.typeName()));
+
+ return issue.filter(auditObject -> !auditObject.isDoesObjectExist()).findFirst().map(v -> true).orElse(false);
+ }
- public void createInventory(AAIObjectAuditList auditList) throws InventoryException {
- if(didAuditFailVserverLInterfaces(auditList)){
- throw new InventoryException("Audit failed for VServer or LInterface cannot write Sub-Interfaces");
- }
- auditList.getAuditList().parallelStream().filter(auditObject -> !auditObject.isDoesObjectExist() && AAIObjectType.SUB_L_INTERFACE.typeName().equals(auditObject.getAaiObjectType())).
- forEach(auditObject -> getAaiClient().createIfNotExists(AAIUriFactory.createResourceFromExistingURI(AAIObjectType.fromTypeName(auditObject.getAaiObjectType()), auditObject.getResourceURI()), Optional.of(auditObject.getAaiObject())));
- }
-
-
- /**
- * @param auditHeatStackFailed
- * @param auditList
- * @return
- */
- protected boolean didAuditFailVserverLInterfaces(AAIObjectAuditList auditList) {
- Stream<AAIObjectAudit> issue = auditList.getAuditList().stream().filter(auditObject -> auditObject.getAaiObjectType().equals(AAIObjectType.VSERVER.typeName()) || auditObject.getAaiObjectType().equals(AAIObjectType.L_INTERFACE.typeName()));
-
- return issue.filter(auditObject -> !auditObject.isDoesObjectExist()).findFirst().map(v -> true).orElse(false);
- }
+ protected AAIResourcesClient getAaiClient() {
+ if (aaiClient == null)
+ return new AAIResourcesClient();
+ else
+ return aaiClient;
+ }
- protected AAIResourcesClient getAaiClient(){
- if(aaiClient == null)
- return new AAIResourcesClient();
- else
- return aaiClient;
- }
- protected void setAaiClient(AAIResourcesClient aaiResource){
- aaiClient = aaiResource;
- }
+ protected void setAaiClient(AAIResourcesClient aaiResource) {
+ aaiClient = aaiResource;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java
index 58d8a4cd55..8bd813026f 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java
@@ -21,9 +21,7 @@
package org.onap.so.adapters.inventory.create;
import java.security.GeneralSecurityException;
-
import javax.annotation.PostConstruct;
-
import org.camunda.bpm.client.ExternalTaskClient;
import org.camunda.bpm.client.backoff.ExponentialBackoffStrategy;
import org.camunda.bpm.client.interceptor.ClientRequestInterceptor;
@@ -40,29 +38,28 @@ import org.springframework.stereotype.Component;
@Profile("!test")
public class CreateInventoryService {
- private static final Logger logger = LoggerFactory.getLogger(CreateInventoryService.class);
+ private static final Logger logger = LoggerFactory.getLogger(CreateInventoryService.class);
- @Autowired
- public Environment env;
+ @Autowired
+ public Environment env;
- @Autowired
- private CreateInventoryTask createInventory;
+ @Autowired
+ private CreateInventoryTask createInventory;
- @PostConstruct
- public void auditAAIInventory() {
- String auth = "";
- try {
- auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey"));
- } catch (IllegalStateException | GeneralSecurityException e) {
- logger.error("Error Decrypting Password", e);
- }
- ClientRequestInterceptor interceptor = new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"),
- auth);
- ExternalTaskClient client = ExternalTaskClient.create()
- .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor)
- .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build();
- client.subscribe("InventoryCreate").lockDuration(60000)
- .handler(createInventory::executeExternalTask).open();
- }
+ @PostConstruct
+ public void auditAAIInventory() {
+ String auth = "";
+ try {
+ auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey"));
+ } catch (IllegalStateException | GeneralSecurityException e) {
+ logger.error("Error Decrypting Password", e);
+ }
+ ClientRequestInterceptor interceptor =
+ new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth);
+ ExternalTaskClient client = ExternalTaskClient.create()
+ .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor)
+ .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build();
+ client.subscribe("InventoryCreate").lockDuration(60000).handler(createInventory::executeExternalTask).open();
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java
index 4a14b1460e..add3aac74d 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters.inventory.create;
import java.io.IOException;
-
import org.camunda.bpm.client.task.ExternalTask;
import org.camunda.bpm.client.task.ExternalTaskService;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
@@ -38,77 +37,78 @@ import org.springframework.stereotype.Component;
@Component
public class CreateInventoryTask {
- private static final String UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI = "Unable to write all inventory to A&AI";
+ private static final String UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI = "Unable to write all inventory to A&AI";
+
+ private static final Logger logger = LoggerFactory.getLogger(CreateInventoryTask.class);
+
+ @Autowired
+ CreateAAIInventory createInventory;
+
+ @Autowired
+ public Environment env;
+
+ protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) {
+ boolean success = true;
+ String auditInventoryString = externalTask.getVariable("auditInventoryResult");
+ GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider();
+ AAIObjectAuditList auditInventory = null;
+ try {
+ auditInventory = objectMapper.getMapper().readValue(auditInventoryString, AAIObjectAuditList.class);
+ } catch (IOException e1) {
+ success = false;
+ }
+ setupMDC(externalTask);
+
+ if (auditInventory != null) {
+ try {
+ logger.info("Executing External Task Create Inventory, Retry Number: {} \n {}", auditInventory,
+ externalTask.getRetries());
+ createInventory.createInventory(auditInventory);
+ } catch (Exception e) {
+ logger.error("Error during inventory of stack", e);
+ success = false;
+ }
+ if (success) {
+ externalTaskService.complete(externalTask);
+ logger.debug("The External Task Id: {} Successful", externalTask.getId());
+ } else {
+ if (externalTask.getRetries() == null) {
+ logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}",
+ externalTask.getId(), getRetrySequence().length);
+ externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI,
+ UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, getRetrySequence().length, 10000);
+ } else if (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) {
+ logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId());
+ externalTaskService.handleBpmnError(externalTask, "AAIInventoryFailure");
+ } else {
+ logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ",
+ externalTask.getId(), externalTask.getRetries() - 1,
+ calculateRetryDelay(externalTask.getRetries()));
+ externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI,
+ UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, externalTask.getRetries() - 1,
+ calculateRetryDelay(externalTask.getRetries()));
+ }
+ logger.debug("The External Task Id: {} Failed", externalTask.getId());
+ }
+ } else {
+ logger.debug("The External Task Id: {} Failed, No Audit Results Written", externalTask.getId());
+ externalTaskService.handleBpmnError(externalTask, "AAIInventoryFailure");
+ }
+ }
+
+ private void setupMDC(ExternalTask externalTask) {
+ String msoRequestId = (String) externalTask.getVariable("mso-request-id");
+ if (msoRequestId != null && !msoRequestId.isEmpty())
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId);
+ }
- private static final Logger logger = LoggerFactory.getLogger(CreateInventoryTask.class);
-
- @Autowired
- CreateAAIInventory createInventory;
-
- @Autowired
- public Environment env;
+ protected long calculateRetryDelay(int currentRetries) {
+ int retrySequence = getRetrySequence().length - currentRetries;
+ long retryMultiplier = Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier", "6000"));
+ return Integer.parseInt(getRetrySequence()[retrySequence]) * retryMultiplier;
+ }
- protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) {
- boolean success = true;
- String auditInventoryString = externalTask.getVariable("auditInventoryResult");
- GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider();
- AAIObjectAuditList auditInventory = null;
- try {
- auditInventory = objectMapper.getMapper().readValue(auditInventoryString, AAIObjectAuditList.class);
- } catch (IOException e1) {
- success = false;
- }
- setupMDC(externalTask);
-
- if (auditInventory != null) {
- try {
- logger.info("Executing External Task Create Inventory, Retry Number: {} \n {}", auditInventory,
- externalTask.getRetries());
- createInventory.createInventory(auditInventory);
- } catch (Exception e) {
- logger.error("Error during inventory of stack", e);
- success = false;
- }
- if (success) {
- externalTaskService.complete(externalTask);
- logger.debug("The External Task Id: {} Successful", externalTask.getId());
- } else {
- if (externalTask.getRetries() == null) {
- logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}",
- externalTask.getId(), getRetrySequence().length);
- externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI,
- UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, getRetrySequence().length, 10000);
- } else if (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) {
- logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId());
- externalTaskService.handleBpmnError(externalTask, "AAIInventoryFailure");
- } else {
- logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ",
- externalTask.getId(), externalTask.getRetries() - 1,
- calculateRetryDelay(externalTask.getRetries()));
- externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI,
- UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, externalTask.getRetries() - 1,
- calculateRetryDelay(externalTask.getRetries()));
- }
- logger.debug("The External Task Id: {} Failed", externalTask.getId());
- }
- } else {
- logger.debug("The External Task Id: {} Failed, No Audit Results Written", externalTask.getId());
- externalTaskService.handleBpmnError(externalTask, "AAIInventoryFailure");
- }
- }
-
- private void setupMDC(ExternalTask externalTask) {
- String msoRequestId = (String)externalTask.getVariable("mso-request-id");
- if(msoRequestId != null && !msoRequestId.isEmpty())
- MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId);
- }
- protected long calculateRetryDelay(int currentRetries){
- int retrySequence = getRetrySequence().length - currentRetries;
- long retryMultiplier = Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier","6000"));
- return Integer.parseInt(getRetrySequence()[retrySequence]) * retryMultiplier;
- }
-
- public String[] getRetrySequence() {
- return env.getProperty("mso.workflow.topics.retrySequence",String[].class);
- }
+ public String[] getRetrySequence() {
+ return env.getProperty("mso.workflow.topics.retrySequence", String[].class);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java
index 22c6902ed2..24fa9af7f9 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java
@@ -2,13 +2,13 @@ package org.onap.so.adapters.inventory.create;
public class InventoryException extends Exception {
- /**
- *
- */
- private static final long serialVersionUID = 912652713891488731L;
-
- public InventoryException(String errorMessage) {
- super(errorMessage);
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = 912652713891488731L;
+
+ public InventoryException(String errorMessage) {
+ super(errorMessage);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRef.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRef.java
index 7febf7e9a0..9d7eafbf82 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRef.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRef.java
@@ -34,48 +34,39 @@ import org.slf4j.LoggerFactory;
public class ContrailPolicyRef {
private static final Logger logger = LoggerFactory.getLogger(ContrailPolicyRef.class);
-
- @JsonProperty("network_policy_refs_data_sequence")
- private ContrailPolicyRefSeq seq;
-
- public JsonNode toJsonNode()
- {
- JsonNode node = null;
- try
- {
- ObjectMapper mapper = new ObjectMapper();
- node = mapper.convertValue(this, JsonNode.class);
- }
- catch (Exception e)
- {
- logger.error("{} {} Error creating JsonString for Contrail Policy Ref: ", MessageEnum.RA_MARSHING_ERROR,
- ErrorCode.SchemaError.getValue(), e);
- }
-
- return node;
- }
-
- public String toJsonString()
- {
- String jsonString = null;
- try
- {
- ObjectMapper mapper = new ObjectMapper();
- jsonString = mapper.writeValueAsString(this);
- }
- catch (Exception e)
- {
- logger.error("{} {} Error creating JsonString for Contrail Policy Ref: ", MessageEnum.RA_MARSHING_ERROR,
- ErrorCode.SchemaError.getValue(), e);
- }
-
- return jsonString;
- }
-
- public void populate(String major, String minor)
- {
- seq = new ContrailPolicyRefSeq(major, minor);
- return;
- }
-
+
+ @JsonProperty("network_policy_refs_data_sequence")
+ private ContrailPolicyRefSeq seq;
+
+ public JsonNode toJsonNode() {
+ JsonNode node = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ node = mapper.convertValue(this, JsonNode.class);
+ } catch (Exception e) {
+ logger.error("{} {} Error creating JsonString for Contrail Policy Ref: ", MessageEnum.RA_MARSHING_ERROR,
+ ErrorCode.SchemaError.getValue(), e);
+ }
+
+ return node;
+ }
+
+ public String toJsonString() {
+ String jsonString = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ jsonString = mapper.writeValueAsString(this);
+ } catch (Exception e) {
+ logger.error("{} {} Error creating JsonString for Contrail Policy Ref: ", MessageEnum.RA_MARSHING_ERROR,
+ ErrorCode.SchemaError.getValue(), e);
+ }
+
+ return jsonString;
+ }
+
+ public void populate(String major, String minor) {
+ seq = new ContrailPolicyRefSeq(major, minor);
+ return;
+ }
+
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRefSeq.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRefSeq.java
index 17d4a743dc..d5ea301dd3 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRefSeq.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRefSeq.java
@@ -24,43 +24,42 @@ package org.onap.so.adapters.network;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ContrailPolicyRefSeq {
-
- @JsonProperty("network_policy_refs_data_sequence_major")
- private String major;
-
- @JsonProperty("network_policy_refs_data_sequence_minor")
- private String minor;
- public ContrailPolicyRefSeq() {
- /* To be done */
- }
-
- public ContrailPolicyRefSeq(String major, String minor) {
- super();
- this.major = major;
- this.minor = minor;
- }
+ @JsonProperty("network_policy_refs_data_sequence_major")
+ private String major;
- public String getMajor() {
- return major;
- }
+ @JsonProperty("network_policy_refs_data_sequence_minor")
+ private String minor;
- public void setMajor(String major) {
- this.major = major;
- }
+ public ContrailPolicyRefSeq() {
+ /* To be done */
+ }
- public String getMinor() {
- return minor;
- }
+ public ContrailPolicyRefSeq(String major, String minor) {
+ super();
+ this.major = major;
+ this.minor = minor;
+ }
- public void setMinor(String minor) {
- this.minor = minor;
- }
+ public String getMajor() {
+ return major;
+ }
- @Override
- public String toString() {
- return "ContrailPolicyRefSeq [major=" + major + ", minor=" + minor
- + "]";
- }
+ public void setMajor(String major) {
+ this.major = major;
+ }
+
+ public String getMinor() {
+ return minor;
+ }
+
+ public void setMinor(String minor) {
+ this.minor = minor;
+ }
+
+ @Override
+ public String toString() {
+ return "ContrailPolicyRefSeq [major=" + major + ", minor=" + minor + "]";
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnet.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnet.java
index 2662cef16e..0c55bd6945 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnet.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnet.java
@@ -27,7 +27,6 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
-
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.onap.so.openstack.beans.HostRoute;
@@ -41,178 +40,161 @@ import org.springframework.beans.factory.annotation.Autowired;
public class ContrailSubnet {
private static final Logger logger = LoggerFactory.getLogger(ContrailSubnet.class);
- @Autowired
- private MsoCommonUtils msoCommonUtils;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet")
- private ContrailSubnetIp subnet = new ContrailSubnetIp();
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_default_gateway")
- private String defaultGateway;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_name")
- private String subnetName;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_enable_dhcp")
- private Boolean enableDhcp;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_addr_from_start")
- private Boolean addrFromStart = true;
- /** future - leave this commented
- private String subnet_uuid;
- private String dns_server_address;
- private List<String> dns_nameservers;
- private String dhcp_option_list;
- **/
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools")
- private List<ContrailSubnetPool> allocationPools = new ArrayList <> ();
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes")
- private final ContrailSubnetHostRoutes host_routes = new ContrailSubnetHostRoutes();
-
- public ContrailSubnet() {
- super();
- }
-
- public String getDefaultGateway() {
- return defaultGateway;
- }
-
- public void setDefaultGateway(String defaultGateway) {
- this.defaultGateway = defaultGateway;
- }
-
- public ContrailSubnetIp getSubnet() {
- return subnet;
- }
-
- public void setSubnet(ContrailSubnetIp subnet) {
- this.subnet = subnet;
- }
-
- public Boolean isEnableDhcp() {
- return enableDhcp;
- }
-
- public void setEnableDhcp(Boolean enableDhcp) {
- this.enableDhcp = enableDhcp;
- }
-
- public String getSubnetName() {
- return subnetName;
- }
-
- public void setSubnetName(String subnetName) {
- this.subnetName = subnetName;
- }
-
- public List<ContrailSubnetPool> getAllocationPools() {
- return allocationPools;
- }
-
- public void setPools(List<ContrailSubnetPool> allocationPools) {
- this.allocationPools = allocationPools;
- }
-
- public Boolean isAddrFromStart() {
- return addrFromStart;
- }
-
- public void setAddrFromStart(Boolean addrFromStart) {
- this.addrFromStart = addrFromStart;
- }
-
- public JsonNode toJsonNode()
- {
- JsonNode node = null;
- try
- {
- ObjectMapper mapper = new ObjectMapper();
- node = mapper.convertValue(this, JsonNode.class);
- }
- catch (Exception e)
- {
- logger.error("{} {} Error creating JsonNode for Contrail Subnet: {} ", MessageEnum.RA_MARSHING_ERROR,
- ErrorCode.SchemaError.getValue(), subnetName, e);
- }
-
- return node;
- }
-
- public String toJsonString()
- {
- String jsonString = null;
- try
- {
- ObjectMapper mapper = new ObjectMapper();
- jsonString = mapper.writeValueAsString(this);
- }
- catch (Exception e)
- {
- logger.error("{} {} Error creating JsonString for Contrail Subnet: {} ", MessageEnum.RA_MARSHING_ERROR,
- ErrorCode.SchemaError.getValue(), subnetName, e);
- }
-
- return jsonString;
- }
- //poulate contrail subnet with input(from bopel) subnet
- public void populateWith(Subnet inputSubnet)
- {
- if (inputSubnet != null)
- {
- if (!msoCommonUtils.isNullOrEmpty(inputSubnet.getSubnetName()))
- subnetName = inputSubnet.getSubnetName();
- else
- subnetName = inputSubnet.getSubnetId();
- enableDhcp = inputSubnet.getEnableDHCP();
- defaultGateway = inputSubnet.getGatewayIp();
- if (!msoCommonUtils.isNullOrEmpty(inputSubnet.getCidr()) )
- {
- int idx = inputSubnet.getCidr().indexOf("/");
- if (idx != -1)
- {
- subnet.setIpPrefix(inputSubnet.getCidr().substring(0, idx));
- subnet.setIpPrefixLen(inputSubnet.getCidr().substring(idx+1));
- }
- }
- if (inputSubnet.getAllocationPools() != null)
- {
- for (Pool pool : inputSubnet.getAllocationPools())
- {
- if ( !msoCommonUtils.isNullOrEmpty(pool.getStart()) && !msoCommonUtils.isNullOrEmpty(pool.getEnd()) )
- {
- ContrailSubnetPool csp = new ContrailSubnetPool();
- csp.populateWith(pool);
- allocationPools.add (csp);
- }
- }
- }
- if (inputSubnet.getHostRoutes() != null)
- {
- List<ContrailSubnetHostRoute> hrList = host_routes.getHost_routes();
- for (HostRoute hr : inputSubnet.getHostRoutes())
- {
- if ( !msoCommonUtils.isNullOrEmpty(hr.getPrefix()) || !msoCommonUtils.isNullOrEmpty(hr.getNextHop()) )
- {
- ContrailSubnetHostRoute cshr = new ContrailSubnetHostRoute();
- cshr.populateWith(hr);
- hrList.add (cshr);
- }
- }
- }
- }
- }
-
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder ();
- for (ContrailSubnetPool pool : allocationPools)
- {
- buf.append(pool.toString());
- }
- return "ContrailSubnet [subnet=" + subnet.toString() + " default_gateway=" + defaultGateway
- + " enable_dhcp=" + enableDhcp + " addr_from_start=" + addrFromStart + " subnet_name=" + subnetName + " allocation_pools=" + buf + " ]";
- }
+ @Autowired
+ private MsoCommonUtils msoCommonUtils;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet")
+ private ContrailSubnetIp subnet = new ContrailSubnetIp();
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_default_gateway")
+ private String defaultGateway;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_name")
+ private String subnetName;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_enable_dhcp")
+ private Boolean enableDhcp;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_addr_from_start")
+ private Boolean addrFromStart = true;
+ /**
+ * future - leave this commented private String subnet_uuid; private String dns_server_address; private List<String>
+ * dns_nameservers; private String dhcp_option_list;
+ **/
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools")
+ private List<ContrailSubnetPool> allocationPools = new ArrayList<>();
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes")
+ private final ContrailSubnetHostRoutes host_routes = new ContrailSubnetHostRoutes();
+
+ public ContrailSubnet() {
+ super();
+ }
+
+ public String getDefaultGateway() {
+ return defaultGateway;
+ }
+
+ public void setDefaultGateway(String defaultGateway) {
+ this.defaultGateway = defaultGateway;
+ }
+
+ public ContrailSubnetIp getSubnet() {
+ return subnet;
+ }
+
+ public void setSubnet(ContrailSubnetIp subnet) {
+ this.subnet = subnet;
+ }
+
+ public Boolean isEnableDhcp() {
+ return enableDhcp;
+ }
+
+ public void setEnableDhcp(Boolean enableDhcp) {
+ this.enableDhcp = enableDhcp;
+ }
+
+ public String getSubnetName() {
+ return subnetName;
+ }
+
+ public void setSubnetName(String subnetName) {
+ this.subnetName = subnetName;
+ }
+
+ public List<ContrailSubnetPool> getAllocationPools() {
+ return allocationPools;
+ }
+
+ public void setPools(List<ContrailSubnetPool> allocationPools) {
+ this.allocationPools = allocationPools;
+ }
+
+ public Boolean isAddrFromStart() {
+ return addrFromStart;
+ }
+
+ public void setAddrFromStart(Boolean addrFromStart) {
+ this.addrFromStart = addrFromStart;
+ }
+
+ public JsonNode toJsonNode() {
+ JsonNode node = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ node = mapper.convertValue(this, JsonNode.class);
+ } catch (Exception e) {
+ logger.error("{} {} Error creating JsonNode for Contrail Subnet: {} ", MessageEnum.RA_MARSHING_ERROR,
+ ErrorCode.SchemaError.getValue(), subnetName, e);
+ }
+
+ return node;
+ }
+
+ public String toJsonString() {
+ String jsonString = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ jsonString = mapper.writeValueAsString(this);
+ } catch (Exception e) {
+ logger.error("{} {} Error creating JsonString for Contrail Subnet: {} ", MessageEnum.RA_MARSHING_ERROR,
+ ErrorCode.SchemaError.getValue(), subnetName, e);
+ }
+
+ return jsonString;
+ }
+
+ // poulate contrail subnet with input(from bopel) subnet
+ public void populateWith(Subnet inputSubnet) {
+ if (inputSubnet != null) {
+ if (!msoCommonUtils.isNullOrEmpty(inputSubnet.getSubnetName()))
+ subnetName = inputSubnet.getSubnetName();
+ else
+ subnetName = inputSubnet.getSubnetId();
+ enableDhcp = inputSubnet.getEnableDHCP();
+ defaultGateway = inputSubnet.getGatewayIp();
+ if (!msoCommonUtils.isNullOrEmpty(inputSubnet.getCidr())) {
+ int idx = inputSubnet.getCidr().indexOf("/");
+ if (idx != -1) {
+ subnet.setIpPrefix(inputSubnet.getCidr().substring(0, idx));
+ subnet.setIpPrefixLen(inputSubnet.getCidr().substring(idx + 1));
+ }
+ }
+ if (inputSubnet.getAllocationPools() != null) {
+ for (Pool pool : inputSubnet.getAllocationPools()) {
+ if (!msoCommonUtils.isNullOrEmpty(pool.getStart())
+ && !msoCommonUtils.isNullOrEmpty(pool.getEnd())) {
+ ContrailSubnetPool csp = new ContrailSubnetPool();
+ csp.populateWith(pool);
+ allocationPools.add(csp);
+ }
+ }
+ }
+ if (inputSubnet.getHostRoutes() != null) {
+ List<ContrailSubnetHostRoute> hrList = host_routes.getHost_routes();
+ for (HostRoute hr : inputSubnet.getHostRoutes()) {
+ if (!msoCommonUtils.isNullOrEmpty(hr.getPrefix())
+ || !msoCommonUtils.isNullOrEmpty(hr.getNextHop())) {
+ ContrailSubnetHostRoute cshr = new ContrailSubnetHostRoute();
+ cshr.populateWith(hr);
+ hrList.add(cshr);
+ }
+ }
+ }
+ }
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder buf = new StringBuilder();
+ for (ContrailSubnetPool pool : allocationPools) {
+ buf.append(pool.toString());
+ }
+ return "ContrailSubnet [subnet=" + subnet.toString() + " default_gateway=" + defaultGateway + " enable_dhcp="
+ + enableDhcp + " addr_from_start=" + addrFromStart + " subnet_name=" + subnetName + " allocation_pools="
+ + buf + " ]";
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoute.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoute.java
index d938306c48..32f85ddf60 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoute.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoute.java
@@ -23,45 +23,43 @@ package org.onap.so.adapters.network;
import org.onap.so.openstack.beans.HostRoute;
import com.fasterxml.jackson.annotation.JsonProperty;
+
public class ContrailSubnetHostRoute {
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route_prefix")
- private String prefix;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route_next_hop")
- private String nextHop;
- public ContrailSubnetHostRoute() {
- }
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route_prefix")
+ private String prefix;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route_next_hop")
+ private String nextHop;
+
+ public ContrailSubnetHostRoute() {}
+
+ public String getPrefix() {
+ return prefix;
+ }
+
+ public void setPrefix(String prefix) {
+ this.prefix = prefix;
+ }
- public String getPrefix() {
- return prefix;
- }
+ public String getNextHop() {
+ return nextHop;
+ }
- public void setPrefix(String prefix) {
- this.prefix = prefix;
- }
+ public void setNextHop(String nextHop) {
+ this.nextHop = nextHop;
+ }
- public String getNextHop() {
- return nextHop;
- }
+ public void populateWith(HostRoute hostRoute) {
+ if (hostRoute != null) {
+ prefix = hostRoute.getPrefix();
+ nextHop = hostRoute.getNextHop();
+ }
+ }
- public void setNextHop(String nextHop) {
- this.nextHop = nextHop;
- }
-
- public void populateWith(HostRoute hostRoute)
- {
- if (hostRoute != null)
- {
- prefix = hostRoute.getPrefix();
- nextHop = hostRoute.getNextHop();
- }
- }
+ @Override
+ public String toString() {
+ return "ContrailSubnetHostRoute [prefix=" + prefix + ", nextHop=" + nextHop + "]";
+ }
- @Override
- public String toString() {
- return "ContrailSubnetHostRoute [prefix=" + prefix + ", nextHop=" + nextHop + "]";
- }
-
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoutes.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoutes.java
index 12744a4273..76881bd58b 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoutes.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoutes.java
@@ -24,34 +24,31 @@ package org.onap.so.adapters.network;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
+
public class ContrailSubnetHostRoutes {
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route")
- private List<ContrailSubnetHostRoute> host_routes = new ArrayList <ContrailSubnetHostRoute> ();
-
- public ContrailSubnetHostRoutes() {
- }
-
- public List<ContrailSubnetHostRoute> getHost_routes() {
- return host_routes;
- }
-
- public void setHost_routes(List<ContrailSubnetHostRoute> host_routes) {
- this.host_routes = host_routes;
- }
-
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder ();
- if (host_routes != null)
- {
- for (ContrailSubnetHostRoute hr : host_routes)
- {
- buf.append(hr.toString());
- }
- }
- return "ContrailSubnetHostRoutes [" + buf.toString() + "]";
- }
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route")
+ private List<ContrailSubnetHostRoute> host_routes = new ArrayList<ContrailSubnetHostRoute>();
+
+ public ContrailSubnetHostRoutes() {}
+
+ public List<ContrailSubnetHostRoute> getHost_routes() {
+ return host_routes;
+ }
+
+ public void setHost_routes(List<ContrailSubnetHostRoute> host_routes) {
+ this.host_routes = host_routes;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder buf = new StringBuilder();
+ if (host_routes != null) {
+ for (ContrailSubnetHostRoute hr : host_routes) {
+ buf.append(hr.toString());
+ }
+ }
+ return "ContrailSubnetHostRoutes [" + buf.toString() + "]";
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetIp.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetIp.java
index 91d089eb33..a00a1eb5ea 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetIp.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetIp.java
@@ -24,36 +24,36 @@ package org.onap.so.adapters.network;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ContrailSubnetIp {
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix")
- private String ipPrefix;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix_len")
- private String ipPrefixLen;
-
- public ContrailSubnetIp() {
- /* Empty constructor */
- }
-
- public String getIpPrefix() {
- return ipPrefix;
- }
-
- public void setIpPrefix(String ipPrefix) {
- this.ipPrefix = ipPrefix;
- }
-
- public String getIpPrefixLen() {
- return ipPrefixLen;
- }
-
- public void setIpPrefixLen(String ipPrefixLen) {
- this.ipPrefixLen = ipPrefixLen;
- }
-
- @Override
- public String toString() {
- return "ContrailSubnetIp [ip_prefix=" + ipPrefix + ", ip_prefix_len=" + ipPrefixLen + "]";
- }
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix")
+ private String ipPrefix;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix_len")
+ private String ipPrefixLen;
+
+ public ContrailSubnetIp() {
+ /* Empty constructor */
+ }
+
+ public String getIpPrefix() {
+ return ipPrefix;
+ }
+
+ public void setIpPrefix(String ipPrefix) {
+ this.ipPrefix = ipPrefix;
+ }
+
+ public String getIpPrefixLen() {
+ return ipPrefixLen;
+ }
+
+ public void setIpPrefixLen(String ipPrefixLen) {
+ this.ipPrefixLen = ipPrefixLen;
+ }
+
+ @Override
+ public String toString() {
+ return "ContrailSubnetIp [ip_prefix=" + ipPrefix + ", ip_prefix_len=" + ipPrefixLen + "]";
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetPool.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetPool.java
index 710d0cc8fd..edba780318 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetPool.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetPool.java
@@ -23,46 +23,45 @@ package org.onap.so.adapters.network;
import org.onap.so.openstack.beans.Pool;
import com.fasterxml.jackson.annotation.JsonProperty;
+
public class ContrailSubnetPool {
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools_start")
- private String start;
-
- @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools_end")
- private String end;
- public ContrailSubnetPool() {
- /* Empty constructor */
- }
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools_start")
+ private String start;
+
+ @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools_end")
+ private String end;
+
+ public ContrailSubnetPool() {
+ /* Empty constructor */
+ }
+
+ public String getStart() {
+ return start;
+ }
+
+ public void setStart(String start) {
+ this.start = start;
+ }
- public String getStart() {
- return start;
- }
+ public String getEnd() {
+ return end;
+ }
- public void setStart(String start) {
- this.start = start;
- }
+ public void setEnd(String end) {
+ this.end = end;
+ }
- public String getEnd() {
- return end;
- }
+ public void populateWith(Pool pool) {
+ if (pool != null) {
+ start = pool.getStart();
+ end = pool.getEnd();
+ }
+ }
- public void setEnd(String end) {
- this.end = end;
- }
-
- public void populateWith(Pool pool)
- {
- if (pool != null)
- {
- start = pool.getStart();
- end = pool.getEnd();
- }
- }
+ @Override
+ public String toString() {
+ return "ContrailSubnetPool [start=" + start + ", end=" + end + "]";
+ }
- @Override
- public String toString() {
- return "ContrailSubnetPool [start=" + start + ", end=" + end + "]";
- }
-
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapter.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapter.java
index 6e2fcb02c9..302a6d302b 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapter.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapter.java
@@ -23,14 +23,12 @@ package org.onap.so.adapters.network;
import java.util.List;
import java.util.Map;
-
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebParam.Mode;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.ws.Holder;
-
import org.onap.so.adapters.network.exceptions.NetworkException;
import org.onap.so.entity.MsoRequest;
import org.onap.so.openstack.beans.NetworkRollback;
@@ -38,193 +36,170 @@ import org.onap.so.openstack.beans.NetworkStatus;
import org.onap.so.openstack.beans.RouteTarget;
import org.onap.so.openstack.beans.Subnet;
-@WebService (name="NetworkAdapter", targetNamespace="http://org.onap.so/network")
-public interface MsoNetworkAdapter
-{
- // TODO: Rename all of these to include Vlan in the service name? At least for the
- // create and update calls, since they are specific to VLAN-based provider networks.
-
- /**
- * This is the "Create Network" Web Service Endpoint definition.
- */
- @WebMethod
- public void createNetwork (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkType") @XmlElement(required=true) String networkType,
- @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid,
- @WebParam(name="networkName") @XmlElement(required=true) String networkName,
- @WebParam(name="physicalNetworkName") String physicalNetworkName,
- @WebParam(name="vlans") List<Integer> vlans,
- @WebParam(name="shared") String shared,
- @WebParam(name="external") String external,
- @WebParam(name="failIfExists") Boolean failIfExists,
- @WebParam(name="backout") Boolean backout,
- @WebParam(name="subnets") List<Subnet> subnets,
- @WebParam(name="networkParams") Map<String, String> networkParams,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="networkId", mode=Mode.OUT) Holder<String> networkId,
- @WebParam(name="neutronNetworkId", mode=Mode.OUT) Holder<String> neutronNetworkId,
- @WebParam(name="subnetIdMap", mode=Mode.OUT) Holder<Map<String, String>> subnetIdMap,
- @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback )
- throws NetworkException;
-
- @WebMethod
- public void createNetworkContrail (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkType") @XmlElement(required=true) String networkType,
- @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid,
- @WebParam(name="networkName") @XmlElement(required=true) String networkName,
- @WebParam(name="routeTargets") List<RouteTarget> routeTargets,
- @WebParam(name="shared") String shared,
- @WebParam(name="external") String external,
- @WebParam(name="failIfExists") Boolean failIfExists,
- @WebParam(name="backout") Boolean backout,
- @WebParam(name="subnets") List<Subnet> subnets,
- @WebParam(name="networkParams") Map<String, String> networkParams,
- @WebParam(name="policyFqdns") List<String> policyFqdns,
- @WebParam(name="routeTableFqdns") List<String> routeTableFqdns,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="networkId", mode=Mode.OUT) Holder<String> networkId,
- @WebParam(name="neutronNetworkId", mode=Mode.OUT) Holder<String> neutronNetworkId,
- @WebParam(name="networkFqdn", mode=Mode.OUT) Holder<String> networkFqdn,
- @WebParam(name="subnetIdMap", mode=Mode.OUT) Holder<Map<String, String>> subnetIdMap,
- @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback )
- throws NetworkException;
-
- /**
- * This is the "Update VLANs" Web Service Endpoint definition.
- * This webservice replaces the set of VLANs on a network.
- */
- @WebMethod
- public void updateNetwork (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkType") @XmlElement(required=true) String networkType,
- @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid,
- @WebParam(name="networkId") @XmlElement(required=true) String networkId,
- @WebParam(name="networkName") @XmlElement(required=true) String networkName,
- @WebParam(name="physicalNetworkName") @XmlElement(required=true) String physicalNetworkName,
- @WebParam(name="vlans") @XmlElement(required=true) List<Integer> vlans,
- @WebParam(name="shared") String shared,
- @WebParam(name="external") String external,
- @WebParam(name="subnets") List<Subnet> subnets,
- @WebParam(name="networkParams") Map<String,String> networkParams,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="subnetIdMap", mode=Mode.OUT) Holder<Map<String, String>> subnetIdMap,
- @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback )
- throws NetworkException;
-
- @WebMethod
- public void updateNetworkContrail (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkType") @XmlElement(required=true) String networkType,
- @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid,
- @WebParam(name="networkId") @XmlElement(required=true) String networkId,
- @WebParam(name="networkName") @XmlElement(required=true) String networkName,
- @WebParam(name="routeTargets") List<RouteTarget> routeTargets,
- @WebParam(name="shared") String shared,
- @WebParam(name="external") String external,
- @WebParam(name="subnets") List<Subnet> subnets,
- @WebParam(name="networkParams") Map<String,String> networkParams,
- @WebParam(name="policyFqdns") List<String> policyFqdns,
- @WebParam(name="routeTableFqdns") List<String> routeTableFqdns,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="subnetIdMap", mode=Mode.OUT) Holder<Map<String, String>> subnetIdMap,
- @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback )
- throws NetworkException;
-
- /**
- * TODO:
- * This is the "Add VLAN" Web Service Endpoint definition.
- * This webservice adds a VLAN to a network.
- * This service assumes that PO supports querying the current vlans in real time.
- * Otherwise, the caller must have the complete list and should use updateVlans instead.
- @WebMethod
- public void addVlan (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkType") @XmlElement(required=true) String networkType,
- @WebParam(name="networkId") @XmlElement(required=true) String networkId,
- @WebParam(name="physicalNetworkName") @XmlElement(required=true) String physicalNetworkName,
- @WebParam(name="vlan") @XmlElement(required=true) Integer vlan,
- @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback )
- throws NetworkException;
- */
-
- /**
- * TODO:
- * This is the "Remove VLAN" Web Service Endpoint definition.
- * This webservice removes a VLAN from a network.
- * This service assumes that PO supports querying the current vlans in real time.
- * Otherwise, the caller must have the complete list and should use updateVlans instead.
- *
- * This service returns an indicator (noMoreVLans) if the VLAN that was removed was
- * the last one on the network.
- *
- * It is not clear that Rollback will work for delete. The network can be
- * recreated from the NetworkRollback object, but the network ID (and stack ID
- * for Heat-based orchestration) will be different. The caller will need to know
- * to update these identifiers in the inventory DB (A&AI).
- @WebMethod
- public void removeVlan (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkType") @XmlElement(required=true) String networkType,
- @WebParam(name="networkId") @XmlElement(required=true) String networkId,
- @WebParam(name="physicalNetworkName") @XmlElement(required=true) String physicalNetworkName,
- @WebParam(name="vlan") @XmlElement(required=true) Integer vlan,
- @WebParam(name="noMoreVlans", mode=Mode.OUT) Holder<Boolean> noMoreVlans,
- @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback )
- throws NetworkException;
- */
-
- /**
- * This is the "Query Network" Web Service Endpoint definition.
- * TODO: Should this just return the NetworkInfo complete structure?
- */
- @WebMethod
- public void queryNetwork (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkNameOrId") @XmlElement(required=true) String networkNameOrId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="networkExists", mode=Mode.OUT) Holder<Boolean> networkExists,
- @WebParam(name="networkId", mode=Mode.OUT) Holder<String> networkId,
- @WebParam(name="neutronNetworkId", mode=Mode.OUT) Holder<String> neutronNetworkId,
- @WebParam(name="status", mode=Mode.OUT) Holder<NetworkStatus> status,
- @WebParam(name="vlans", mode=Mode.OUT) Holder<List<Integer>> vlans,
- @WebParam(name="subnetIdMap", mode=Mode.OUT) Holder<Map<String, String>> subnetIdMap)
- throws NetworkException;
-
- @WebMethod
- public void queryNetworkContrail (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkNameOrId") @XmlElement(required=true) String networkNameOrId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="networkExists", mode=Mode.OUT) Holder<Boolean> networkExists,
- @WebParam(name="networkId", mode=Mode.OUT) Holder<String> networkId,
- @WebParam(name="neutronNetworkId", mode=Mode.OUT) Holder<String> neutronNetworkId,
- @WebParam(name="status", mode=Mode.OUT) Holder<NetworkStatus> status,
- @WebParam(name="routeTargets", mode=Mode.OUT) Holder<List<RouteTarget>> routeTargets,
- @WebParam(name="subnetIdMap", mode=Mode.OUT) Holder<Map<String, String>> subnetIdMap)
- throws NetworkException;
-
- /**
- * This is the "Delete Network" Web Service endpoint definition.
- */
- @WebMethod
- public void deleteNetwork (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkType") @XmlElement(required=true) String networkType,
- @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid,
- @WebParam(name="networkId") @XmlElement(required=true) String networkId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="networkDeleted", mode=Mode.OUT) Holder<Boolean> networkDeleted)
- throws NetworkException;
-
- /**
- * This is the "Rollback Network" Web Service endpoint definition.
- */
- @WebMethod
- public void rollbackNetwork (@WebParam(name="rollback") @XmlElement(required=true) NetworkRollback rollback)
- throws NetworkException;
-
- @WebMethod
- public void healthCheck ();
+@WebService(name = "NetworkAdapter", targetNamespace = "http://org.onap.so/network")
+public interface MsoNetworkAdapter {
+ // TODO: Rename all of these to include Vlan in the service name? At least for the
+ // create and update calls, since they are specific to VLAN-based provider networks.
+
+ /**
+ * This is the "Create Network" Web Service Endpoint definition.
+ */
+ @WebMethod
+ public void createNetwork(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "networkType") @XmlElement(required = true) String networkType,
+ @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid,
+ @WebParam(name = "networkName") @XmlElement(required = true) String networkName,
+ @WebParam(name = "physicalNetworkName") String physicalNetworkName,
+ @WebParam(name = "vlans") List<Integer> vlans, @WebParam(name = "shared") String shared,
+ @WebParam(name = "external") String external, @WebParam(name = "failIfExists") Boolean failIfExists,
+ @WebParam(name = "backout") Boolean backout, @WebParam(name = "subnets") List<Subnet> subnets,
+ @WebParam(name = "networkParams") Map<String, String> networkParams,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "networkId", mode = Mode.OUT) Holder<String> networkId,
+ @WebParam(name = "neutronNetworkId", mode = Mode.OUT) Holder<String> neutronNetworkId,
+ @WebParam(name = "subnetIdMap", mode = Mode.OUT) Holder<Map<String, String>> subnetIdMap,
+ @WebParam(name = "rollback", mode = Mode.OUT) Holder<NetworkRollback> rollback) throws NetworkException;
+
+ @WebMethod
+ public void createNetworkContrail(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "networkType") @XmlElement(required = true) String networkType,
+ @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid,
+ @WebParam(name = "networkName") @XmlElement(required = true) String networkName,
+ @WebParam(name = "routeTargets") List<RouteTarget> routeTargets, @WebParam(name = "shared") String shared,
+ @WebParam(name = "external") String external, @WebParam(name = "failIfExists") Boolean failIfExists,
+ @WebParam(name = "backout") Boolean backout, @WebParam(name = "subnets") List<Subnet> subnets,
+ @WebParam(name = "networkParams") Map<String, String> networkParams,
+ @WebParam(name = "policyFqdns") List<String> policyFqdns,
+ @WebParam(name = "routeTableFqdns") List<String> routeTableFqdns,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "networkId", mode = Mode.OUT) Holder<String> networkId,
+ @WebParam(name = "neutronNetworkId", mode = Mode.OUT) Holder<String> neutronNetworkId,
+ @WebParam(name = "networkFqdn", mode = Mode.OUT) Holder<String> networkFqdn,
+ @WebParam(name = "subnetIdMap", mode = Mode.OUT) Holder<Map<String, String>> subnetIdMap,
+ @WebParam(name = "rollback", mode = Mode.OUT) Holder<NetworkRollback> rollback) throws NetworkException;
+
+ /**
+ * This is the "Update VLANs" Web Service Endpoint definition. This webservice replaces the set of VLANs on a
+ * network.
+ */
+ @WebMethod
+ public void updateNetwork(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "networkType") @XmlElement(required = true) String networkType,
+ @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid,
+ @WebParam(name = "networkId") @XmlElement(required = true) String networkId,
+ @WebParam(name = "networkName") @XmlElement(required = true) String networkName,
+ @WebParam(name = "physicalNetworkName") @XmlElement(required = true) String physicalNetworkName,
+ @WebParam(name = "vlans") @XmlElement(required = true) List<Integer> vlans,
+ @WebParam(name = "shared") String shared, @WebParam(name = "external") String external,
+ @WebParam(name = "subnets") List<Subnet> subnets,
+ @WebParam(name = "networkParams") Map<String, String> networkParams,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "subnetIdMap", mode = Mode.OUT) Holder<Map<String, String>> subnetIdMap,
+ @WebParam(name = "rollback", mode = Mode.OUT) Holder<NetworkRollback> rollback) throws NetworkException;
+
+ @WebMethod
+ public void updateNetworkContrail(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "networkType") @XmlElement(required = true) String networkType,
+ @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid,
+ @WebParam(name = "networkId") @XmlElement(required = true) String networkId,
+ @WebParam(name = "networkName") @XmlElement(required = true) String networkName,
+ @WebParam(name = "routeTargets") List<RouteTarget> routeTargets, @WebParam(name = "shared") String shared,
+ @WebParam(name = "external") String external, @WebParam(name = "subnets") List<Subnet> subnets,
+ @WebParam(name = "networkParams") Map<String, String> networkParams,
+ @WebParam(name = "policyFqdns") List<String> policyFqdns,
+ @WebParam(name = "routeTableFqdns") List<String> routeTableFqdns,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "subnetIdMap", mode = Mode.OUT) Holder<Map<String, String>> subnetIdMap,
+ @WebParam(name = "rollback", mode = Mode.OUT) Holder<NetworkRollback> rollback) throws NetworkException;
+
+ /**
+ * TODO: This is the "Add VLAN" Web Service Endpoint definition. This webservice adds a VLAN to a network. This
+ * service assumes that PO supports querying the current vlans in real time. Otherwise, the caller must have the
+ * complete list and should use updateVlans instead.
+ *
+ * @WebMethod public void addVlan (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
+ * @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
+ * @WebParam(name="networkType") @XmlElement(required=true) String networkType,
+ * @WebParam(name="networkId") @XmlElement(required=true) String networkId,
+ * @WebParam(name="physicalNetworkName") @XmlElement(required=true) String physicalNetworkName,
+ * @WebParam(name="vlan") @XmlElement(required=true) Integer vlan,
+ * @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback ) throws NetworkException;
+ */
+
+ /**
+ * TODO: This is the "Remove VLAN" Web Service Endpoint definition. This webservice removes a VLAN from a network.
+ * This service assumes that PO supports querying the current vlans in real time. Otherwise, the caller must have
+ * the complete list and should use updateVlans instead.
+ *
+ * This service returns an indicator (noMoreVLans) if the VLAN that was removed was the last one on the network.
+ *
+ * It is not clear that Rollback will work for delete. The network can be recreated from the NetworkRollback object,
+ * but the network ID (and stack ID for Heat-based orchestration) will be different. The caller will need to know to
+ * update these identifiers in the inventory DB (A&AI).
+ *
+ * @WebMethod public void removeVlan (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
+ * @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
+ * @WebParam(name="networkType") @XmlElement(required=true) String networkType,
+ * @WebParam(name="networkId") @XmlElement(required=true) String networkId,
+ * @WebParam(name="physicalNetworkName") @XmlElement(required=true) String physicalNetworkName,
+ * @WebParam(name="vlan") @XmlElement(required=true) Integer vlan,
+ * @WebParam(name="noMoreVlans", mode=Mode.OUT) Holder<Boolean> noMoreVlans,
+ * @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback ) throws NetworkException;
+ */
+
+ /**
+ * This is the "Query Network" Web Service Endpoint definition. TODO: Should this just return the NetworkInfo
+ * complete structure?
+ */
+ @WebMethod
+ public void queryNetwork(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "networkNameOrId") @XmlElement(required = true) String networkNameOrId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "networkExists", mode = Mode.OUT) Holder<Boolean> networkExists,
+ @WebParam(name = "networkId", mode = Mode.OUT) Holder<String> networkId,
+ @WebParam(name = "neutronNetworkId", mode = Mode.OUT) Holder<String> neutronNetworkId,
+ @WebParam(name = "status", mode = Mode.OUT) Holder<NetworkStatus> status,
+ @WebParam(name = "vlans", mode = Mode.OUT) Holder<List<Integer>> vlans,
+ @WebParam(name = "subnetIdMap", mode = Mode.OUT) Holder<Map<String, String>> subnetIdMap)
+ throws NetworkException;
+
+ @WebMethod
+ public void queryNetworkContrail(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "networkNameOrId") @XmlElement(required = true) String networkNameOrId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "networkExists", mode = Mode.OUT) Holder<Boolean> networkExists,
+ @WebParam(name = "networkId", mode = Mode.OUT) Holder<String> networkId,
+ @WebParam(name = "neutronNetworkId", mode = Mode.OUT) Holder<String> neutronNetworkId,
+ @WebParam(name = "status", mode = Mode.OUT) Holder<NetworkStatus> status,
+ @WebParam(name = "routeTargets", mode = Mode.OUT) Holder<List<RouteTarget>> routeTargets,
+ @WebParam(name = "subnetIdMap", mode = Mode.OUT) Holder<Map<String, String>> subnetIdMap)
+ throws NetworkException;
+
+ /**
+ * This is the "Delete Network" Web Service endpoint definition.
+ */
+ @WebMethod
+ public void deleteNetwork(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "networkType") @XmlElement(required = true) String networkType,
+ @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid,
+ @WebParam(name = "networkId") @XmlElement(required = true) String networkId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "networkDeleted", mode = Mode.OUT) Holder<Boolean> networkDeleted) throws NetworkException;
+
+ /**
+ * This is the "Rollback Network" Web Service endpoint definition.
+ */
+ @WebMethod
+ public void rollbackNetwork(@WebParam(name = "rollback") @XmlElement(required = true) NetworkRollback rollback)
+ throws NetworkException;
+
+ @WebMethod
+ public void healthCheck();
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsync.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsync.java
index a85da58536..5b7340e24f 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsync.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsync.java
@@ -23,87 +23,82 @@ package org.onap.so.adapters.network;
import java.util.List;
import java.util.Map;
-
import javax.jws.Oneway;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlElement;
-
import org.onap.so.entity.MsoRequest;
import org.onap.so.openstack.beans.NetworkRollback;
import org.onap.so.openstack.beans.Subnet;
+
/**
- * This webservice defines the Asynchronous versions of NETWORK adapter calls.
- * The notification messages for final responses are documented elsewhere
- * (by the client service WSDL).
+ * This webservice defines the Asynchronous versions of NETWORK adapter calls. The notification messages for final
+ * responses are documented elsewhere (by the client service WSDL).
*
*/
-@WebService (name="NetworkAdapterAsync", targetNamespace="http://org.onap.so/networkA")
-public interface MsoNetworkAdapterAsync
-{
- /**
- * This is the "Create NETWORK" Web Service Endpoint definition.
- */
- @WebMethod
- @Oneway
- public void createNetworkA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkType") @XmlElement(required=true) String networkType,
- @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid,
- @WebParam(name="networkName") @XmlElement(required=true) String networkName,
- @WebParam(name="physicalNetworkName") String physicalNetworkName,
- @WebParam(name="vlans") List<Integer> vlans,
- @WebParam(name="failIfExists") Boolean failIfExists,
- @WebParam(name="backout") Boolean backout,
- @WebParam(name="subnets") List<Subnet> subnets,
- @WebParam(name="networkParams") Map<String, String> networkParams,
- @WebParam(name="messageId") @XmlElement(required=true) String messageId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl );
+@WebService(name = "NetworkAdapterAsync", targetNamespace = "http://org.onap.so/networkA")
+public interface MsoNetworkAdapterAsync {
+ /**
+ * This is the "Create NETWORK" Web Service Endpoint definition.
+ */
+ @WebMethod
+ @Oneway
+ public void createNetworkA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "networkType") @XmlElement(required = true) String networkType,
+ @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid,
+ @WebParam(name = "networkName") @XmlElement(required = true) String networkName,
+ @WebParam(name = "physicalNetworkName") String physicalNetworkName,
+ @WebParam(name = "vlans") List<Integer> vlans, @WebParam(name = "failIfExists") Boolean failIfExists,
+ @WebParam(name = "backout") Boolean backout, @WebParam(name = "subnets") List<Subnet> subnets,
+ @WebParam(name = "networkParams") Map<String, String> networkParams,
+ @WebParam(name = "messageId") @XmlElement(required = true) String messageId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl);
- @WebMethod
- @Oneway
- public void updateNetworkA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkType") @XmlElement(required=true) String networkType,
- @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid,
- @WebParam(name="networkId") @XmlElement(required=true) String networkId,
- @WebParam(name="networkName") @XmlElement(required=true) String networkName,
- @WebParam(name="physicalNetworkName") @XmlElement(required=true) String physicalNetworkName,
- @WebParam(name="vlans") @XmlElement(required=true) List<Integer> vlans,
- @WebParam(name="subnets") List<Subnet> subnets,
- @WebParam(name="networkParams") Map<String, String> networkParams,
- @WebParam(name="messageId") @XmlElement(required=true) String messageId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl );
+ @WebMethod
+ @Oneway
+ public void updateNetworkA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "networkType") @XmlElement(required = true) String networkType,
+ @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid,
+ @WebParam(name = "networkId") @XmlElement(required = true) String networkId,
+ @WebParam(name = "networkName") @XmlElement(required = true) String networkName,
+ @WebParam(name = "physicalNetworkName") @XmlElement(required = true) String physicalNetworkName,
+ @WebParam(name = "vlans") @XmlElement(required = true) List<Integer> vlans,
+ @WebParam(name = "subnets") List<Subnet> subnets,
+ @WebParam(name = "networkParams") Map<String, String> networkParams,
+ @WebParam(name = "messageId") @XmlElement(required = true) String messageId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl);
- @WebMethod
- @Oneway
- public void queryNetworkA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkNameOrId") @XmlElement(required=true) String networkNameOrId,
- @WebParam(name="messageId") @XmlElement(required=true) String messageId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl );
+ @WebMethod
+ @Oneway
+ public void queryNetworkA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "networkNameOrId") @XmlElement(required = true) String networkNameOrId,
+ @WebParam(name = "messageId") @XmlElement(required = true) String messageId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl);
- @WebMethod
- @Oneway
- public void deleteNetworkA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="networkType") @XmlElement(required=true) String networkType,
- @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid,
- @WebParam(name="networkId") @XmlElement(required=true) String networkId,
- @WebParam(name="messageId") @XmlElement(required=true) String messageId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl );
+ @WebMethod
+ @Oneway
+ public void deleteNetworkA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "networkType") @XmlElement(required = true) String networkType,
+ @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid,
+ @WebParam(name = "networkId") @XmlElement(required = true) String networkId,
+ @WebParam(name = "messageId") @XmlElement(required = true) String messageId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl);
- @WebMethod
- @Oneway
- public void rollbackNetworkA (@WebParam(name="rollback") @XmlElement(required=true) NetworkRollback rollback,
- @WebParam(name="messageId") @XmlElement(required=true) String messageId,
- @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl );
+ @WebMethod
+ @Oneway
+ public void rollbackNetworkA(@WebParam(name = "rollback") @XmlElement(required = true) NetworkRollback rollback,
+ @WebParam(name = "messageId") @XmlElement(required = true) String messageId,
+ @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl);
- @WebMethod
- public void healthCheckA ();
+ @WebMethod
+ public void healthCheckA();
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java
index 53fa2f6dc2..d13b1724df 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java
@@ -59,15 +59,17 @@ import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
-@WebService(serviceName = "NetworkAdapterAsync", endpointInterface = "org.onap.so.adapters.network.MsoNetworkAdapterAsync", targetNamespace = "http://org.onap.so/networkA")
+@WebService(serviceName = "NetworkAdapterAsync",
+ endpointInterface = "org.onap.so.adapters.network.MsoNetworkAdapterAsync",
+ targetNamespace = "http://org.onap.so/networkA")
public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync {
private static final Logger logger = LoggerFactory.getLogger(MsoNetworkAdapterAsyncImpl.class);
private static final String BPEL_AUTH_PROP = "org.onap.so.adapters.network.bpelauth";
private static final String ENCRYPTION_KEY_PROP = "org.onap.so.adapters.network.encryptionKey";
- private static final String NETWORK_EXCEPTION_MSG="Got a NetworkException on createNetwork: ";
- private static final String CREATE_NETWORK_ERROR_LOGMSG ="{} {} Error sending createNetwork notification {} ";
+ private static final String NETWORK_EXCEPTION_MSG = "Got a NetworkException on createNetwork: ";
+ private static final String CREATE_NETWORK_ERROR_LOGMSG = "{} {} Error sending createNetwork notification {} ";
private static final String FAULT_INFO_ERROR_LOGMSG = "{} {} Exception - fault info ";
@Autowired
@@ -75,116 +77,86 @@ public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync {
@Autowired
private MsoNetworkAdapter networkAdapter;
+
/**
* Health Check web method. Does nothing but return to show the adapter is deployed.
*/
@Override
- public void healthCheckA () {
- logger.debug ("Health check call in Network Adapter");
+ public void healthCheckA() {
+ logger.debug("Health check call in Network Adapter");
}
/**
- * This is the "Create Network" web service implementation.
- * It will create a new Network of the requested type in the specified cloud
- * and tenant. The tenant must exist at the time this service is called.
+ * This is the "Create Network" web service implementation. It will create a new Network of the requested type in
+ * the specified cloud and tenant. The tenant must exist at the time this service is called.
*
- * If a network with the same name already exists, this can be considered a
- * success or failure, depending on the value of the 'failIfExists' parameter.
+ * If a network with the same name already exists, this can be considered a success or failure, depending on the
+ * value of the 'failIfExists' parameter.
*
- * There will be a pre-defined set of network types defined in the MSO Catalog.
- * All such networks will have a similar configuration, based on the allowable
- * Openstack networking definitions. This includes basic networks, provider
- * networks (with a single VLAN), and multi-provider networks (one or more VLANs)
+ * There will be a pre-defined set of network types defined in the MSO Catalog. All such networks will have a
+ * similar configuration, based on the allowable Openstack networking definitions. This includes basic networks,
+ * provider networks (with a single VLAN), and multi-provider networks (one or more VLANs)
*
- * Initially, all provider networks must be "vlan" type, and multiple segments in
- * a multi-provider network must be multiple VLANs on the same physical network.
+ * Initially, all provider networks must be "vlan" type, and multiple segments in a multi-provider network must be
+ * multiple VLANs on the same physical network.
*
- * This service supports two modes of Network creation/update:
- * - via Heat Templates
- * - via Neutron API
- * The network orchestration mode for each network type is declared in its
- * catalog definition. All Heat-based templates must support some subset of
- * the same input parameters: network_name, physical_network, vlan(s).
+ * This service supports two modes of Network creation/update: - via Heat Templates - via Neutron API The network
+ * orchestration mode for each network type is declared in its catalog definition. All Heat-based templates must
+ * support some subset of the same input parameters: network_name, physical_network, vlan(s).
*
- * The method returns the network ID and a NetworkRollback object. This latter
- * object can be passed as-is to the rollbackNetwork operation to undo everything
- * that was created. This is useful if a network is successfully created but
- * the orchestration fails on a subsequent operation.
+ * The method returns the network ID and a NetworkRollback object. This latter object can be passed as-is to the
+ * rollbackNetwork operation to undo everything that was created. This is useful if a network is successfully
+ * created but the orchestration fails on a subsequent operation.
*/
@Override
- public void createNetworkA (String cloudSiteId,
- String tenantId,
- String networkType,
- String modelCustomizationUuid,
- String networkName,
- String physicalNetworkName,
- List <Integer> vlans,
- Boolean failIfExists,
- Boolean backout,
- List <Subnet> subnets,
- Map<String,String> networkParams,
- String messageId,
- MsoRequest msoRequest,
- String notificationUrl) {
+ public void createNetworkA(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid,
+ String networkName, String physicalNetworkName, List<Integer> vlans, Boolean failIfExists, Boolean backout,
+ List<Subnet> subnets, Map<String, String> networkParams, String messageId, MsoRequest msoRequest,
+ String notificationUrl) {
logger.debug("Async Create Network: {} of type {} in {}/{}", networkName, networkType, cloudSiteId, tenantId);
// Use the synchronous method to perform the actual Create
-
+
// Synchronous Web Service Outputs
- Holder <String> networkId = new Holder <> ();
- Holder <String> neutronNetworkId = new Holder <> ();
- Holder <NetworkRollback> networkRollback = new Holder <> ();
- Holder <Map <String, String>> subnetIdMap = new Holder <> ();
-
- HashMap<String, String> params = (HashMap<String,String>) networkParams;
+ Holder<String> networkId = new Holder<>();
+ Holder<String> neutronNetworkId = new Holder<>();
+ Holder<NetworkRollback> networkRollback = new Holder<>();
+ Holder<Map<String, String>> subnetIdMap = new Holder<>();
+
+ HashMap<String, String> params = (HashMap<String, String>) networkParams;
if (params == null)
- params = new HashMap<String,String>();
+ params = new HashMap<String, String>();
String shared = null;
String external = null;
if (params.containsKey("shared"))
- shared = params.get("shared");
+ shared = params.get("shared");
if (params.containsKey("external"))
- external = params.get("external");
+ external = params.get("external");
try {
- networkAdapter.createNetwork (cloudSiteId,
- tenantId,
- networkType,
- modelCustomizationUuid,
- networkName,
- physicalNetworkName,
- vlans,
- shared,
- external,
- failIfExists,
- backout,
- subnets,
- params,
- msoRequest,
- networkId,
- neutronNetworkId,
- subnetIdMap,
- networkRollback);
+ networkAdapter.createNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkName,
+ physicalNetworkName, vlans, shared, external, failIfExists, backout, subnets, params, msoRequest,
+ networkId, neutronNetworkId, subnetIdMap, networkRollback);
} catch (NetworkException e) {
- logger.debug (NETWORK_EXCEPTION_MSG, e);
+ logger.debug(NETWORK_EXCEPTION_MSG, e);
MsoExceptionCategory exCat = null;
String eMsg = null;
try {
- eMsg = e.getFaultInfo ().getMessage ();
- exCat = MsoExceptionCategory.fromValue (e.getFaultInfo ().getCategory ().name ());
+ eMsg = e.getFaultInfo().getMessage();
+ exCat = MsoExceptionCategory.fromValue(e.getFaultInfo().getCategory().name());
} catch (Exception e1) {
- logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC,
- ErrorCode.DataError.getValue(), e1);
+ logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC, ErrorCode.DataError.getValue(),
+ e1);
}
// Build and send Asynchronous error response
try {
- NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.createNetworkNotification (messageId, false, exCat, eMsg, null, null, null, null);
+ NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.createNetworkNotification(messageId, false, exCat, eMsg, null, null, null, null);
} catch (Exception e1) {
logger.error(CREATE_NETWORK_ERROR_LOGMSG, MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC,
- ErrorCode.DataError.getValue(), e1.getMessage(), e1);
+ ErrorCode.DataError.getValue(), e1.getMessage(), e1);
}
return;
@@ -192,118 +164,83 @@ public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync {
logger.debug("Async Create Network:Name {} physicalNetworkName:{}", networkName, physicalNetworkName);
// Build and send Asynchronous response
try {
- NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.createNetworkNotification (messageId,
- true,
- null,
- null,
- networkId.value,
- neutronNetworkId.value,
- copyCreateSubnetIdMap (subnetIdMap),
- copyNrb (networkRollback));
+ NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.createNetworkNotification(messageId, true, null, null, networkId.value, neutronNetworkId.value,
+ copyCreateSubnetIdMap(subnetIdMap), copyNrb(networkRollback));
} catch (Exception e) {
logger.error(CREATE_NETWORK_ERROR_LOGMSG, MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC,
- ErrorCode.DataError.getValue(), e.getMessage(), e);
+ ErrorCode.DataError.getValue(), e.getMessage(), e);
}
return;
}
/**
- * This is the "Update Network" web service implementation.
- * It will update an existing Network of the requested type in the specified cloud
- * and tenant. The typical use will be to replace the VLANs with the supplied
- * list (to add or remove a VLAN), but other properties may be updated as well.
+ * This is the "Update Network" web service implementation. It will update an existing Network of the requested type
+ * in the specified cloud and tenant. The typical use will be to replace the VLANs with the supplied list (to add or
+ * remove a VLAN), but other properties may be updated as well.
*
- * There will be a pre-defined set of network types defined in the MSO Catalog.
- * All such networks will have a similar configuration, based on the allowable
- * Openstack networking definitions. This includes basic networks, provider
- * networks (with a single VLAN), and multi-provider networks (one or more VLANs).
+ * There will be a pre-defined set of network types defined in the MSO Catalog. All such networks will have a
+ * similar configuration, based on the allowable Openstack networking definitions. This includes basic networks,
+ * provider networks (with a single VLAN), and multi-provider networks (one or more VLANs).
*
- * Initially, all provider networks must currently be "vlan" type, and multi-provider
- * networks must be multiple VLANs on the same physical network.
+ * Initially, all provider networks must currently be "vlan" type, and multi-provider networks must be multiple
+ * VLANs on the same physical network.
*
- * This service supports two modes of Network update:
- * - via Heat Templates
- * - via Neutron API
- * The network orchestration mode for each network type is declared in its
- * catalog definition. All Heat-based templates must support some subset of
- * the same input parameters: network_name, physical_network, vlan, segments.
+ * This service supports two modes of Network update: - via Heat Templates - via Neutron API The network
+ * orchestration mode for each network type is declared in its catalog definition. All Heat-based templates must
+ * support some subset of the same input parameters: network_name, physical_network, vlan, segments.
*
- * The method returns a NetworkRollback object. This object can be passed
- * as-is to the rollbackNetwork operation to undo everything that was updated.
- * This is useful if a network is successfully updated but orchestration
- * fails on a subsequent operation.
+ * The method returns a NetworkRollback object. This object can be passed as-is to the rollbackNetwork operation to
+ * undo everything that was updated. This is useful if a network is successfully updated but orchestration fails on
+ * a subsequent operation.
*/
@Override
- public void updateNetworkA (String cloudSiteId,
- String tenantId,
- String networkType,
- String modelCustomizationUuid,
- String networkId,
- String networkName,
- String physicalNetworkName,
- List <Integer> vlans,
- List <Subnet> subnets,
- Map <String,String> networkParams,
- String messageId,
- MsoRequest msoRequest,
- String notificationUrl) {
+ public void updateNetworkA(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid,
+ String networkId, String networkName, String physicalNetworkName, List<Integer> vlans, List<Subnet> subnets,
+ Map<String, String> networkParams, String messageId, MsoRequest msoRequest, String notificationUrl) {
logger.debug("Async Update Network: {} of type {} in {}/{}", networkId, networkType, cloudSiteId, tenantId);
// Use the synchronous method to perform the actual Create
-
+
// Synchronous Web Service Outputs
- Holder <NetworkRollback> networkRollback = new Holder <> ();
- Holder <Map <String, String>> subnetIdMap = new Holder <> ();
-
- HashMap<String, String> params = (HashMap<String,String>) networkParams;
+ Holder<NetworkRollback> networkRollback = new Holder<>();
+ Holder<Map<String, String>> subnetIdMap = new Holder<>();
+
+ HashMap<String, String> params = (HashMap<String, String>) networkParams;
if (params == null)
- params = new HashMap<String,String>();
+ params = new HashMap<String, String>();
String shared = null;
String external = null;
if (params.containsKey("shared"))
- shared = params.get("shared");
+ shared = params.get("shared");
if (params.containsKey("external"))
- external = params.get("external");
+ external = params.get("external");
try {
- networkAdapter.updateNetwork (cloudSiteId,
- tenantId,
- networkType,
- modelCustomizationUuid,
- networkId,
- networkName,
- physicalNetworkName,
- vlans,
- shared,
- external,
- subnets,
- params,
- msoRequest,
- subnetIdMap,
- networkRollback);
+ networkAdapter.updateNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkId,
+ networkName, physicalNetworkName, vlans, shared, external, subnets, params, msoRequest, subnetIdMap,
+ networkRollback);
} catch (NetworkException e) {
- logger.debug ("Got a NetworkException on updateNetwork: ", e);
+ logger.debug("Got a NetworkException on updateNetwork: ", e);
MsoExceptionCategory exCat = null;
String eMsg = null;
try {
- eMsg = e.getFaultInfo ().getMessage ();
- exCat = MsoExceptionCategory.fromValue (e.getFaultInfo ().getCategory ().name ());
+ eMsg = e.getFaultInfo().getMessage();
+ exCat = MsoExceptionCategory.fromValue(e.getFaultInfo().getCategory().name());
} catch (Exception e1) {
- logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC,
- ErrorCode.DataError.getValue(), e1);
+ logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC, ErrorCode.DataError.getValue(),
+ e1);
}
// Build and send Asynchronous error response
try {
- NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.updateNetworkNotification (messageId, false, exCat, eMsg, null, copyNrb (networkRollback));
+ NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.updateNetworkNotification(messageId, false, exCat, eMsg, null, copyNrb(networkRollback));
} catch (Exception e1) {
logger.error("{} {} Error sending updateNetwork notification {} ",
- MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, ErrorCode.DataError.getValue(), e1.getMessage(),
- e1);
+ MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, ErrorCode.DataError.getValue(), e1.getMessage(), e1);
}
return;
@@ -311,161 +248,127 @@ public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync {
logger.debug("Async Update Network:Name {} NetworkId:{}", networkName, networkId);
// Build and send Asynchronous response
try {
- NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.updateNetworkNotification (messageId,
- true,
- null,
- null,
- copyUpdateSubnetIdMap (subnetIdMap),
- copyNrb (networkRollback));
+ NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.updateNetworkNotification(messageId, true, null, null, copyUpdateSubnetIdMap(subnetIdMap),
+ copyNrb(networkRollback));
} catch (Exception e) {
logger.error("{} {} Error sending updateNotification request {} ", MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC,
- ErrorCode.DataError.getValue(), e.getMessage(), e);
+ ErrorCode.DataError.getValue(), e.getMessage(), e);
}
return;
}
/**
- * This is the queryNetwork method. It returns the existence and status of
- * the specified network, along with its Neutron UUID and list of VLANs.
- * This method attempts to find the network using both Heat and Neutron.
- * Heat stacks are first searched based on the provided network name/id.
- * If none is found, the Neutron is directly queried.
+ * This is the queryNetwork method. It returns the existence and status of the specified network, along with its
+ * Neutron UUID and list of VLANs. This method attempts to find the network using both Heat and Neutron. Heat stacks
+ * are first searched based on the provided network name/id. If none is found, the Neutron is directly queried.
*/
@Override
- public void queryNetworkA (String cloudSiteId,
- String tenantId,
- String networkNameOrId,
- String messageId,
- MsoRequest msoRequest,
- String notificationUrl) {
+ public void queryNetworkA(String cloudSiteId, String tenantId, String networkNameOrId, String messageId,
+ MsoRequest msoRequest, String notificationUrl) {
logger.debug("Async Query Network {} in {}/{}", networkNameOrId, cloudSiteId, tenantId);
String errorCreateNetworkMessage = "{} {} Error sending createNetwork notification {} ";
// Use the synchronous method to perform the actual Create
-
+
// Synchronous Web Service Outputs
- Holder <Boolean> networkExists = new Holder <> ();
- Holder <String> networkId = new Holder <> ();
- Holder <String> neutronNetworkId = new Holder <> ();
- Holder <NetworkStatus> status = new Holder <> ();
- Holder <List <Integer>> vlans = new Holder <> ();
- Holder <Map <String, String>> subnetIdMap = new Holder <> ();
+ Holder<Boolean> networkExists = new Holder<>();
+ Holder<String> networkId = new Holder<>();
+ Holder<String> neutronNetworkId = new Holder<>();
+ Holder<NetworkStatus> status = new Holder<>();
+ Holder<List<Integer>> vlans = new Holder<>();
+ Holder<Map<String, String>> subnetIdMap = new Holder<>();
try {
- networkAdapter.queryNetwork (cloudSiteId,
- tenantId,
- networkNameOrId,
- msoRequest,
- networkExists,
- networkId,
- neutronNetworkId,
- status,
- vlans,
- subnetIdMap);
+ networkAdapter.queryNetwork(cloudSiteId, tenantId, networkNameOrId, msoRequest, networkExists, networkId,
+ neutronNetworkId, status, vlans, subnetIdMap);
} catch (NetworkException e) {
- logger.debug (NETWORK_EXCEPTION_MSG, e);
+ logger.debug(NETWORK_EXCEPTION_MSG, e);
MsoExceptionCategory exCat = null;
String eMsg = null;
try {
- eMsg = e.getFaultInfo ().getMessage ();
- exCat = MsoExceptionCategory.fromValue (e.getFaultInfo ().getCategory ().name ());
+ eMsg = e.getFaultInfo().getMessage();
+ exCat = MsoExceptionCategory.fromValue(e.getFaultInfo().getCategory().name());
} catch (Exception e1) {
- logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC,
- ErrorCode.DataError.getValue(), e1);
+ logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC, ErrorCode.DataError.getValue(),
+ e1);
}
// Build and send Asynchronous error response
try {
- NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.queryNetworkNotification (messageId, false, exCat, eMsg, null, null, null, null, null, null);
+ NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.queryNetworkNotification(messageId, false, exCat, eMsg, null, null, null, null, null, null);
} catch (Exception e1) {
logger.error(errorCreateNetworkMessage, MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC,
- ErrorCode.DataError.getValue(), e1.getMessage(), e1);
+ ErrorCode.DataError.getValue(), e1.getMessage(), e1);
}
return;
}
logger.debug("Async Query Network:NameOrId {} tenantId:{}", networkNameOrId, tenantId);
// Build and send Asynchronous response
try {
- NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- org.onap.so.adapters.network.async.client.NetworkStatus networkS = org.onap.so.adapters.network.async.client.NetworkStatus.fromValue (status.value.name ());
- notifyPort.queryNetworkNotification (messageId,
- true,
- null,
- null,
- networkExists.value,
- networkId.value,
- neutronNetworkId.value,
- networkS,
- vlans.value,
- copyQuerySubnetIdMap (subnetIdMap));
+ NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ org.onap.so.adapters.network.async.client.NetworkStatus networkS =
+ org.onap.so.adapters.network.async.client.NetworkStatus.fromValue(status.value.name());
+ notifyPort.queryNetworkNotification(messageId, true, null, null, networkExists.value, networkId.value,
+ neutronNetworkId.value, networkS, vlans.value, copyQuerySubnetIdMap(subnetIdMap));
} catch (Exception e) {
logger.error(errorCreateNetworkMessage, MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC,
- ErrorCode.DataError.getValue(), e.getMessage(), e);
+ ErrorCode.DataError.getValue(), e.getMessage(), e);
}
return;
}
/**
- * This is the "Delete Network" web service implementation.
- * It will delete a Network in the specified cloud and tenant.
+ * This is the "Delete Network" web service implementation. It will delete a Network in the specified cloud and
+ * tenant.
*
* If the network is not found, it is treated as a success.
*
- * This service supports two modes of Network creation/update/delete:
- * - via Heat Templates
- * - via Neutron API
- * The network orchestration mode for each network type is declared in its
- * catalog definition.
+ * This service supports two modes of Network creation/update/delete: - via Heat Templates - via Neutron API The
+ * network orchestration mode for each network type is declared in its catalog definition.
*
- * For Heat-based orchestration, the networkId should be the stack ID.
- * For Neutron-based orchestration, the networkId should be the Neutron network UUID.
+ * For Heat-based orchestration, the networkId should be the stack ID. For Neutron-based orchestration, the
+ * networkId should be the Neutron network UUID.
*
- * The method returns nothing on success. Rollback is not possible for delete
- * commands, so any failure on delete will require manual fallout in the client.
+ * The method returns nothing on success. Rollback is not possible for delete commands, so any failure on delete
+ * will require manual fallout in the client.
*/
@Override
- public void deleteNetworkA (String cloudSiteId,
- String tenantId,
- String networkType,
- String modelCustomizationUuid,
- String networkId,
- String messageId,
- MsoRequest msoRequest,
- String notificationUrl) {
+ public void deleteNetworkA(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid,
+ String networkId, String messageId, MsoRequest msoRequest, String notificationUrl) {
String serviceName = "DeleteNetworkA";
logger.debug("Async Delete Network {} in {}/{}", networkId, cloudSiteId, tenantId);
// Use the synchronous method to perform the actual Create
-
+
// Synchronous Web Service Outputs
- Holder <Boolean> networkDeleted = new Holder <> ();
+ Holder<Boolean> networkDeleted = new Holder<>();
try {
- networkAdapter.deleteNetwork (cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkId, msoRequest, networkDeleted);
+ networkAdapter.deleteNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkId,
+ msoRequest, networkDeleted);
} catch (NetworkException e) {
- logger.debug (NETWORK_EXCEPTION_MSG, e);
+ logger.debug(NETWORK_EXCEPTION_MSG, e);
MsoExceptionCategory exCat = null;
String eMsg = null;
try {
- eMsg = e.getFaultInfo ().getMessage ();
- exCat = MsoExceptionCategory.fromValue (e.getFaultInfo ().getCategory ().name ());
+ eMsg = e.getFaultInfo().getMessage();
+ exCat = MsoExceptionCategory.fromValue(e.getFaultInfo().getCategory().name());
} catch (Exception e1) {
- logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC,
- ErrorCode.DataError.getValue(), e1);
+ logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC, ErrorCode.DataError.getValue(),
+ e1);
}
// Build and send Asynchronous error response
try {
- NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.deleteNetworkNotification (messageId, false, exCat, eMsg, null);
+ NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.deleteNetworkNotification(messageId, false, exCat, eMsg, null);
} catch (Exception e1) {
logger.error("{} {} Error sending createNetwork notification {} ",
- MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, ErrorCode.DataError.getValue(), e1.getMessage(),
- e1);
+ MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, ErrorCode.DataError.getValue(), e1.getMessage(), e1);
}
return;
@@ -473,59 +376,57 @@ public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync {
logger.debug("Async Delete NetworkId: {} tenantId:{}", networkId, tenantId);
// Build and send Asynchronous response
try {
- NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.deleteNetworkNotification (messageId, true, null, null, networkDeleted.value);
+ NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.deleteNetworkNotification(messageId, true, null, null, networkDeleted.value);
} catch (Exception e) {
logger.error("{} {} Error sending deleteNetwork notification {} ", MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC,
- ErrorCode.DataError.getValue(), e.getMessage(), e);
+ ErrorCode.DataError.getValue(), e.getMessage(), e);
}
return;
}
/**
- * This web service endpoint will rollback a previous Create VNF operation.
- * A rollback object is returned to the client in a successful creation
- * response. The client can pass that object as-is back to the rollbackNetwork
+ * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the
+ * client in a successful creation response. The client can pass that object as-is back to the rollbackNetwork
* operation to undo the creation.
*
- * The rollback includes removing the VNF and deleting the tenant if the
- * tenant did not exist prior to the VNF creation.
+ * The rollback includes removing the VNF and deleting the tenant if the tenant did not exist prior to the VNF
+ * creation.
*/
@Override
- public void rollbackNetworkA (NetworkRollback rollback, String messageId, String notificationUrl) {
+ public void rollbackNetworkA(NetworkRollback rollback, String messageId, String notificationUrl) {
// rollback may be null (e.g. if network already existed when Create was called)
if (rollback == null) {
- logger.warn("{} {} Rollback is null", MessageEnum.RA_ROLLBACK_NULL,
- ErrorCode.SchemaError.getValue());
+ logger.warn("{} {} Rollback is null", MessageEnum.RA_ROLLBACK_NULL, ErrorCode.SchemaError.getValue());
return;
}
logger.info("{} {}", MessageEnum.RA_ASYNC_ROLLBACK, rollback.getNetworkStackId());
// Use the synchronous method to perform the actual Create
-
+
try {
- networkAdapter.rollbackNetwork (rollback);
+ networkAdapter.rollbackNetwork(rollback);
} catch (NetworkException e) {
- logger.debug ("Got a NetworkException on rollbackNetwork: ", e);
+ logger.debug("Got a NetworkException on rollbackNetwork: ", e);
// Build and send Asynchronous error response
MsoExceptionCategory exCat = null;
String eMsg = null;
try {
- eMsg = e.getFaultInfo ().getMessage ();
- exCat = MsoExceptionCategory.fromValue (e.getFaultInfo ().getCategory ().name ());
+ eMsg = e.getFaultInfo().getMessage();
+ exCat = MsoExceptionCategory.fromValue(e.getFaultInfo().getCategory().name());
} catch (Exception e1) {
logger.error("{} {} Exception in get fault info ", MessageEnum.RA_FAULT_INFO_EXC,
- ErrorCode.DataError.getValue(), e1);
+ ErrorCode.DataError.getValue(), e1);
}
// Build and send Asynchronous error response
try {
- NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.rollbackNetworkNotification (rollback.getMsoRequest ().getRequestId (), false, exCat, eMsg);
+ NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.rollbackNetworkNotification(rollback.getMsoRequest().getRequestId(), false, exCat, eMsg);
} catch (Exception e1) {
logger.error(CREATE_NETWORK_ERROR_LOGMSG, MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC,
- ErrorCode.DataError.getValue(), e1.getMessage(), e1);
+ ErrorCode.DataError.getValue(), e1.getMessage(), e1);
}
return;
@@ -533,169 +434,167 @@ public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync {
logger.debug("Async Rollback NetworkId: {} tenantId:{}", rollback.getNetworkStackId(), rollback.getTenantId());
// Build and send Asynchronous response
try {
- NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.rollbackNetworkNotification (rollback.getMsoRequest ().getRequestId (), true, null, null);
+ NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.rollbackNetworkNotification(rollback.getMsoRequest().getRequestId(), true, null, null);
} catch (Exception e) {
- logger
- .error("{} {} Error sending rollbackNetwork notification {} ", MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC,
- ErrorCode.DataError.getValue(), e.getMessage(), e);
+ logger.error("{} {} Error sending rollbackNetwork notification {} ",
+ MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, ErrorCode.DataError.getValue(), e.getMessage(), e);
}
return;
}
- private org.onap.so.adapters.network.async.client.NetworkRollback copyNrb (Holder <NetworkRollback> hNrb) {
- org.onap.so.adapters.network.async.client.NetworkRollback cnrb = new org.onap.so.adapters.network.async.client.NetworkRollback ();
+ private org.onap.so.adapters.network.async.client.NetworkRollback copyNrb(Holder<NetworkRollback> hNrb) {
+ org.onap.so.adapters.network.async.client.NetworkRollback cnrb =
+ new org.onap.so.adapters.network.async.client.NetworkRollback();
if (hNrb != null && hNrb.value != null) {
- org.onap.so.adapters.network.async.client.MsoRequest cmr = new org.onap.so.adapters.network.async.client.MsoRequest ();
-
- cnrb.setCloudId (hNrb.value.getCloudId ());
- cmr.setRequestId (hNrb.value.getMsoRequest ().getRequestId ());
- cmr.setServiceInstanceId (hNrb.value.getMsoRequest ().getServiceInstanceId ());
- cnrb.setMsoRequest (cmr);
- cnrb.setNetworkId (hNrb.value.getNetworkId ());
- cnrb.setNetworkStackId (hNrb.value.getNetworkStackId ());
- cnrb.setNeutronNetworkId (hNrb.value.getNeutronNetworkId ());
- cnrb.setTenantId (hNrb.value.getTenantId ());
- cnrb.setNetworkType (hNrb.value.getNetworkType ());
- cnrb.setNetworkCreated (hNrb.value.getNetworkCreated ());
- cnrb.setNetworkName (hNrb.value.getNetworkName ());
- cnrb.setPhysicalNetwork (hNrb.value.getPhysicalNetwork ());
- List <Integer> vlansc = cnrb.getVlans ();
- List <Integer> vlansh = hNrb.value.getVlans ();
+ org.onap.so.adapters.network.async.client.MsoRequest cmr =
+ new org.onap.so.adapters.network.async.client.MsoRequest();
+
+ cnrb.setCloudId(hNrb.value.getCloudId());
+ cmr.setRequestId(hNrb.value.getMsoRequest().getRequestId());
+ cmr.setServiceInstanceId(hNrb.value.getMsoRequest().getServiceInstanceId());
+ cnrb.setMsoRequest(cmr);
+ cnrb.setNetworkId(hNrb.value.getNetworkId());
+ cnrb.setNetworkStackId(hNrb.value.getNetworkStackId());
+ cnrb.setNeutronNetworkId(hNrb.value.getNeutronNetworkId());
+ cnrb.setTenantId(hNrb.value.getTenantId());
+ cnrb.setNetworkType(hNrb.value.getNetworkType());
+ cnrb.setNetworkCreated(hNrb.value.getNetworkCreated());
+ cnrb.setNetworkName(hNrb.value.getNetworkName());
+ cnrb.setPhysicalNetwork(hNrb.value.getPhysicalNetwork());
+ List<Integer> vlansc = cnrb.getVlans();
+ List<Integer> vlansh = hNrb.value.getVlans();
if (vlansh != null) {
- vlansc.addAll (vlansh);
+ vlansc.addAll(vlansh);
}
}
return cnrb;
}
- private NetworkAdapterNotify getNotifyEP (String notificationUrl) {
+ private NetworkAdapterNotify getNotifyEP(String notificationUrl) {
URL warWsdlLoc = null;
try {
- warWsdlLoc = Thread.currentThread ().getContextClassLoader ().getResource ("NetworkAdapterNotify.wsdl");
+ warWsdlLoc = Thread.currentThread().getContextClassLoader().getResource("NetworkAdapterNotify.wsdl");
} catch (Exception e) {
logger.error("{} {} Exception - WSDL not found ", MessageEnum.RA_WSDL_NOT_FOUND,
- ErrorCode.DataError.getValue(), e);
+ ErrorCode.DataError.getValue(), e);
}
if (warWsdlLoc == null) {
- logger
- .error("{} {} WSDL not found", MessageEnum.RA_WSDL_NOT_FOUND, ErrorCode.DataError.getValue());
+ logger.error("{} {} WSDL not found", MessageEnum.RA_WSDL_NOT_FOUND, ErrorCode.DataError.getValue());
} else {
try {
logger.debug("NetworkAdpaterNotify.wsdl location: {}", warWsdlLoc.toURI().toString());
} catch (Exception e) {
logger.error("{} {} Exception - WSDL URL convention ", MessageEnum.RA_WSDL_URL_CONVENTION_EXC,
- ErrorCode.SchemaError.getValue(), e);
+ ErrorCode.SchemaError.getValue(), e);
}
}
- NetworkAdapterNotify_Service notifySvc = new NetworkAdapterNotify_Service (warWsdlLoc,
- new QName ("http://org.onap.so/networkNotify",
- "networkAdapterNotify"));
+ NetworkAdapterNotify_Service notifySvc = new NetworkAdapterNotify_Service(warWsdlLoc,
+ new QName("http://org.onap.so/networkNotify", "networkAdapterNotify"));
- NetworkAdapterNotify notifyPort = notifySvc.getMsoNetworkAdapterAsyncImplPort ();
+ NetworkAdapterNotify notifyPort = notifySvc.getMsoNetworkAdapterAsyncImplPort();
BindingProvider bp = (BindingProvider) notifyPort;
URL epUrl = null;
try {
- epUrl = new URL (notificationUrl);
+ epUrl = new URL(notificationUrl);
} catch (MalformedURLException e1) {
logger.error("{} {} Exception - init notification ", MessageEnum.RA_INIT_NOTIF_EXC,
- ErrorCode.DataError.getValue(), e1);
+ ErrorCode.DataError.getValue(), e1);
}
- if(null != epUrl) {
+ if (null != epUrl) {
logger.debug("Notification Endpoint URL: {}", epUrl.toExternalForm());
- bp.getRequestContext ().put (BindingProvider.ENDPOINT_ADDRESS_PROPERTY, epUrl.toExternalForm ());
- }
- else {
+ bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, epUrl.toExternalForm());
+ } else {
logger.debug("Notification Endpoint URL is NULL: ");
}
// authentication
try {
- Map <String, Object> reqCtx = bp.getRequestContext ();
- Map <String, List <String>> headers = new HashMap <> ();
+ Map<String, Object> reqCtx = bp.getRequestContext();
+ Map<String, List<String>> headers = new HashMap<>();
- String userCredentials = this.getEncryptedProperty (BPEL_AUTH_PROP, "", ENCRYPTION_KEY_PROP);
+ String userCredentials = this.getEncryptedProperty(BPEL_AUTH_PROP, "", ENCRYPTION_KEY_PROP);
- String basicAuth = "Basic " + DatatypeConverter.printBase64Binary (userCredentials.getBytes ());
- reqCtx.put (MessageContext.HTTP_REQUEST_HEADERS, headers);
- headers.put ("Authorization", Collections.singletonList (basicAuth));
+ String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
+ reqCtx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
+ headers.put("Authorization", Collections.singletonList(basicAuth));
} catch (Exception e) {
logger.error("{} {} Unable to set authorization in callback request {} ",
- MessageEnum.RA_SET_CALLBACK_AUTH_EXC, ErrorCode.DataError.getValue(), e.getMessage(), e);
+ MessageEnum.RA_SET_CALLBACK_AUTH_EXC, ErrorCode.DataError.getValue(), e.getMessage(), e);
}
return notifyPort;
}
-
+
public String getEncryptedProperty(String key, String defaultValue, String encryptionKey) {
- try {
- return CryptoUtils.decrypt(this.environment.getProperty(key), this.environment.getProperty(encryptionKey));
- } catch (GeneralSecurityException e) {
- logger.debug("Exception while decrypting property: {} ", this.environment.getProperty(key), e);
- }
- return defaultValue;
+ try {
+ return CryptoUtils.decrypt(this.environment.getProperty(key), this.environment.getProperty(encryptionKey));
+ } catch (GeneralSecurityException e) {
+ logger.debug("Exception while decrypting property: {} ", this.environment.getProperty(key), e);
+ }
+ return defaultValue;
- }
+ }
- private CreateNetworkNotification.SubnetIdMap copyCreateSubnetIdMap (Holder <Map <String, String>> hMap) {
+ private CreateNetworkNotification.SubnetIdMap copyCreateSubnetIdMap(Holder<Map<String, String>> hMap) {
- CreateNetworkNotification.SubnetIdMap subnetIdMap = new CreateNetworkNotification.SubnetIdMap ();
+ CreateNetworkNotification.SubnetIdMap subnetIdMap = new CreateNetworkNotification.SubnetIdMap();
if (hMap != null && hMap.value != null) {
- Map <String, String> sMap = hMap.value;
- CreateNetworkNotification.SubnetIdMap.Entry entry = new CreateNetworkNotification.SubnetIdMap.Entry ();
-
- for (Map.Entry<String,String> mapEntry : sMap.entrySet ()) {
- String key = mapEntry.getKey();
- String value = mapEntry.getValue();
- entry.setKey (key);
- entry.setValue (value);
- subnetIdMap.getEntry ().add (entry);
+ Map<String, String> sMap = hMap.value;
+ CreateNetworkNotification.SubnetIdMap.Entry entry = new CreateNetworkNotification.SubnetIdMap.Entry();
+
+ for (Map.Entry<String, String> mapEntry : sMap.entrySet()) {
+ String key = mapEntry.getKey();
+ String value = mapEntry.getValue();
+ entry.setKey(key);
+ entry.setValue(value);
+ subnetIdMap.getEntry().add(entry);
}
}
return subnetIdMap;
}
- private UpdateNetworkNotification.SubnetIdMap copyUpdateSubnetIdMap (Holder <Map <String, String>> hMap) {
+ private UpdateNetworkNotification.SubnetIdMap copyUpdateSubnetIdMap(Holder<Map<String, String>> hMap) {
- UpdateNetworkNotification.SubnetIdMap subnetIdMap = new UpdateNetworkNotification.SubnetIdMap ();
+ UpdateNetworkNotification.SubnetIdMap subnetIdMap = new UpdateNetworkNotification.SubnetIdMap();
if (hMap != null && hMap.value != null) {
- Map <String, String> sMap = hMap.value;
- UpdateNetworkNotification.SubnetIdMap.Entry entry = new UpdateNetworkNotification.SubnetIdMap.Entry ();
-
- for (Map.Entry<String,String> mapEntry : sMap.entrySet ()) {
- String key = mapEntry.getKey();
- String value = mapEntry.getValue();
- entry.setKey (key);
- entry.setValue (value);
- subnetIdMap.getEntry ().add (entry);
+ Map<String, String> sMap = hMap.value;
+ UpdateNetworkNotification.SubnetIdMap.Entry entry = new UpdateNetworkNotification.SubnetIdMap.Entry();
+
+ for (Map.Entry<String, String> mapEntry : sMap.entrySet()) {
+ String key = mapEntry.getKey();
+ String value = mapEntry.getValue();
+ entry.setKey(key);
+ entry.setValue(value);
+ subnetIdMap.getEntry().add(entry);
}
}
return subnetIdMap;
}
- private QueryNetworkNotification.SubnetIdMap copyQuerySubnetIdMap (Holder <Map <String, String>> hMap) {
+ private QueryNetworkNotification.SubnetIdMap copyQuerySubnetIdMap(Holder<Map<String, String>> hMap) {
- QueryNetworkNotification.SubnetIdMap subnetIdMap = new QueryNetworkNotification.SubnetIdMap ();
+ QueryNetworkNotification.SubnetIdMap subnetIdMap = new QueryNetworkNotification.SubnetIdMap();
if (hMap != null && hMap.value != null) {
- Map <String, String> sMap = hMap.value;
- QueryNetworkNotification.SubnetIdMap.Entry entry = new QueryNetworkNotification.SubnetIdMap.Entry ();
-
- for (Map.Entry<String,String> mapEntry : sMap.entrySet ()) {
- String key = mapEntry.getKey();
- String value = mapEntry.getValue();
- entry.setKey (key);
- entry.setValue (value);
- subnetIdMap.getEntry ().add (entry);
+ Map<String, String> sMap = hMap.value;
+ QueryNetworkNotification.SubnetIdMap.Entry entry = new QueryNetworkNotification.SubnetIdMap.Entry();
+
+ for (Map.Entry<String, String> mapEntry : sMap.entrySet()) {
+ String key = mapEntry.getKey();
+ String value = mapEntry.getValue();
+ entry.setKey(key);
+ entry.setValue(value);
+ subnetIdMap.getEntry().add(entry);
}
}
return subnetIdMap;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java
index 73e7143ae3..a79a6191cf 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java
@@ -76,11 +76,12 @@ import org.springframework.transaction.annotation.Transactional;
@Component
@Transactional
-@WebService(serviceName = "NetworkAdapter", endpointInterface = "org.onap.so.adapters.network.MsoNetworkAdapter", targetNamespace = "http://org.onap.so/network")
+@WebService(serviceName = "NetworkAdapter", endpointInterface = "org.onap.so.adapters.network.MsoNetworkAdapter",
+ targetNamespace = "http://org.onap.so/network")
public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
- private static final String AIC3_NW_PROPERTY= "org.onap.so.adapters.network.aic3nw";
- private static final String AIC3_NW="OS::ContrailV2::VirtualNetwork";
+ private static final String AIC3_NW_PROPERTY = "org.onap.so.adapters.network.aic3nw";
+ private static final String AIC3_NW = "OS::ContrailV2::VirtualNetwork";
private static final String VLANS = "vlans";
private static final String PHYSICAL_NETWORK = "physical_network";
private static final String UPDATE_NETWORK_CONTEXT = "UpdateNetwork";
@@ -106,176 +107,93 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
private MsoCommonUtils commonUtils;
@Autowired
- private NetworkResourceCustomizationRepository networkCustomRepo;
+ private NetworkResourceCustomizationRepository networkCustomRepo;
@Autowired
private CollectionNetworkResourceCustomizationRepository collectionNetworkCustomRepo;
@Autowired
- private NetworkResourceRepository networkResourceRepo;
+ private NetworkResourceRepository networkResourceRepo;
+
/**
* Health Check web method. Does nothing but return to show the adapter is deployed.
*/
@Override
- public void healthCheck () {
- logger.debug ("Health check call in Network Adapter");
+ public void healthCheck() {
+ logger.debug("Health check call in Network Adapter");
}
/**
* Do not use this constructor or the msoPropertiesFactory will be NULL.
*
- * @see MsoNetworkAdapterImpl#MsoNetworkAdapterImpl(MsoPropertiesFactory)
+ * @see MsoNetworkAdapterImpl#MsoNetworkAdapterImpl(MsoPropertiesFactory)
*/
- public MsoNetworkAdapterImpl() {
- }
+ public MsoNetworkAdapterImpl() {}
@Override
- public void createNetwork (String cloudSiteId,
- String tenantId,
- String networkType,
- String modelCustomizationUuid,
- String networkName,
- String physicalNetworkName,
- List <Integer> vlans,
- String shared,
- String external,
- Boolean failIfExists,
- Boolean backout,
- List <Subnet> subnets,
- Map<String, String> networkParams,
- MsoRequest msoRequest,
- Holder <String> networkId,
- Holder <String> neutronNetworkId,
- Holder <Map <String, String>> subnetIdMap,
- Holder <NetworkRollback> rollback) throws NetworkException {
- Holder <String> networkFqdn = new Holder <> ();
- createNetwork (cloudSiteId,
- tenantId,
- networkType,
- modelCustomizationUuid,
- networkName,
- physicalNetworkName,
- vlans,
- null,
- shared,
- external,
- failIfExists,
- backout,
- subnets,
- null,
- null,
- msoRequest,
- networkId,
- neutronNetworkId,
- networkFqdn,
- subnetIdMap,
- rollback);
+ public void createNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid,
+ String networkName, String physicalNetworkName, List<Integer> vlans, String shared, String external,
+ Boolean failIfExists, Boolean backout, List<Subnet> subnets, Map<String, String> networkParams,
+ MsoRequest msoRequest, Holder<String> networkId, Holder<String> neutronNetworkId,
+ Holder<Map<String, String>> subnetIdMap, Holder<NetworkRollback> rollback) throws NetworkException {
+ Holder<String> networkFqdn = new Holder<>();
+ createNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkName, physicalNetworkName,
+ vlans, null, shared, external, failIfExists, backout, subnets, null, null, msoRequest, networkId,
+ neutronNetworkId, networkFqdn, subnetIdMap, rollback);
}
@Override
- public void createNetworkContrail (String cloudSiteId,
- String tenantId,
- String networkType,
- String modelCustomizationUuid,
- String networkName,
- List <RouteTarget> routeTargets,
- String shared,
- String external,
- Boolean failIfExists,
- Boolean backout,
- List <Subnet> subnets,
- Map<String, String> networkParams,
- List <String> policyFqdns,
- List<String> routeTableFqdns,
- MsoRequest msoRequest,
- Holder <String> networkId,
- Holder <String> neutronNetworkId,
- Holder <String> networkFqdn,
- Holder <Map <String, String>> subnetIdMap,
- Holder <NetworkRollback> rollback) throws NetworkException {
- createNetwork (cloudSiteId,
- tenantId,
- networkType,
- modelCustomizationUuid,
- networkName,
- null,
- null,
- routeTargets,
- shared,
- external,
- failIfExists,
- backout,
- subnets,
- policyFqdns,
- routeTableFqdns,
- msoRequest,
- networkId,
- neutronNetworkId,
- networkFqdn,
- subnetIdMap,
- rollback);
+ public void createNetworkContrail(String cloudSiteId, String tenantId, String networkType,
+ String modelCustomizationUuid, String networkName, List<RouteTarget> routeTargets, String shared,
+ String external, Boolean failIfExists, Boolean backout, List<Subnet> subnets,
+ Map<String, String> networkParams, List<String> policyFqdns, List<String> routeTableFqdns,
+ MsoRequest msoRequest, Holder<String> networkId, Holder<String> neutronNetworkId,
+ Holder<String> networkFqdn, Holder<Map<String, String>> subnetIdMap, Holder<NetworkRollback> rollback)
+ throws NetworkException {
+ createNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkName, null, null, routeTargets,
+ shared, external, failIfExists, backout, subnets, policyFqdns, routeTableFqdns, msoRequest, networkId,
+ neutronNetworkId, networkFqdn, subnetIdMap, rollback);
}
/**
- * This is the "Create Network" web service implementation.
- * It will create a new Network of the requested type in the specified cloud
- * and tenant. The tenant must exist at the time this service is called.
+ * This is the "Create Network" web service implementation. It will create a new Network of the requested type in
+ * the specified cloud and tenant. The tenant must exist at the time this service is called.
*
- * If a network with the same name already exists, this can be considered a
- * success or failure, depending on the value of the 'failIfExists' parameter.
+ * If a network with the same name already exists, this can be considered a success or failure, depending on the
+ * value of the 'failIfExists' parameter.
*
- * There will be a pre-defined set of network types defined in the MSO Catalog.
- * All such networks will have a similar configuration, based on the allowable
- * Openstack networking definitions. This includes basic networks, provider
- * networks (with a single VLAN), and multi-provider networks (one or more VLANs)
+ * There will be a pre-defined set of network types defined in the MSO Catalog. All such networks will have a
+ * similar configuration, based on the allowable Openstack networking definitions. This includes basic networks,
+ * provider networks (with a single VLAN), and multi-provider networks (one or more VLANs)
*
- * Initially, all provider networks must be "vlan" type, and multiple segments in
- * a multi-provider network must be multiple VLANs on the same physical network.
+ * Initially, all provider networks must be "vlan" type, and multiple segments in a multi-provider network must be
+ * multiple VLANs on the same physical network.
*
- * This service supports two modes of Network creation/update:
- * - via Heat Templates
- * - via Neutron API
- * The network orchestration mode for each network type is declared in its
- * catalog definition. All Heat-based templates must support some subset of
- * the same input parameters: network_name, physical_network, vlan(s).
+ * This service supports two modes of Network creation/update: - via Heat Templates - via Neutron API The network
+ * orchestration mode for each network type is declared in its catalog definition. All Heat-based templates must
+ * support some subset of the same input parameters: network_name, physical_network, vlan(s).
*
- * The method returns the network ID and a NetworkRollback object. This latter
- * object can be passed as-is to the rollbackNetwork operation to undo everything
- * that was created. This is useful if a network is successfully created but
- * the orchestration fails on a subsequent operation.
+ * The method returns the network ID and a NetworkRollback object. This latter object can be passed as-is to the
+ * rollbackNetwork operation to undo everything that was created. This is useful if a network is successfully
+ * created but the orchestration fails on a subsequent operation.
*/
- private void createNetwork (String cloudSiteId,
- String tenantId,
- String networkType,
- String modelCustomizationUuid,
- String networkName,
- String physicalNetworkName,
- List <Integer> vlans,
- List <RouteTarget> routeTargets,
- String shared,
- String external,
- Boolean failIfExists,
- Boolean backout,
- List <Subnet> subnets,
- List <String> policyFqdns,
- List <String> routeTableFqdns,
- MsoRequest msoRequest,
- Holder <String> networkId,
- Holder <String> neutronNetworkId,
- Holder <String> networkFqdn,
- Holder <Map <String, String>> subnetIdMap,
- Holder <NetworkRollback> rollback) throws NetworkException {
+ private void createNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid,
+ String networkName, String physicalNetworkName, List<Integer> vlans, List<RouteTarget> routeTargets,
+ String shared, String external, Boolean failIfExists, Boolean backout, List<Subnet> subnets,
+ List<String> policyFqdns, List<String> routeTableFqdns, MsoRequest msoRequest, Holder<String> networkId,
+ Holder<String> neutronNetworkId, Holder<String> networkFqdn, Holder<Map<String, String>> subnetIdMap,
+ Holder<NetworkRollback> rollback) throws NetworkException {
logger.debug("*** CREATE Network: {} of type {} in {}/{}", networkName, networkType, cloudSiteId, tenantId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
// Build a default rollback object (no actions performed)
- NetworkRollback networkRollback = new NetworkRollback ();
- networkRollback.setCloudId (cloudSiteId);
- networkRollback.setTenantId (tenantId);
- networkRollback.setMsoRequest (msoRequest);
+ NetworkRollback networkRollback = new NetworkRollback();
+ networkRollback.setCloudId(cloudSiteId);
+ networkRollback.setTenantId(tenantId);
+ networkRollback.setMsoRequest(msoRequest);
networkRollback.setModelCustomizationUuid(modelCustomizationUuid);
// tenant query is not required here.
@@ -283,10 +201,9 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
// So this is just catching that error in a bit more obvious way up front.
Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
- if (!cloudSiteOpt.isPresent())
- {
- String error = String
- .format("Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration",
+ if (!cloudSiteOpt.isPresent()) {
+ String error = String.format(
+ "Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration",
networkName, cloudSiteId, tenantId);
logger.error("{} {} {}", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error);
// Set the detailed error as the Exception 'message'
@@ -294,443 +211,332 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
}
- NetworkResource networkResource = networkCheck (startTime,
- networkType,
- modelCustomizationUuid,
- networkName,
- physicalNetworkName,
- vlans,
- routeTargets,
- cloudSiteId,
- cloudSiteOpt.get());
- String mode = networkResource.getOrchestrationMode ();
- NetworkType neutronNetworkType = NetworkType.valueOf (networkResource.getNeutronNetworkType ());
+ NetworkResource networkResource = networkCheck(startTime, networkType, modelCustomizationUuid, networkName,
+ physicalNetworkName, vlans, routeTargets, cloudSiteId, cloudSiteOpt.get());
+ String mode = networkResource.getOrchestrationMode();
+ NetworkType neutronNetworkType = NetworkType.valueOf(networkResource.getNeutronNetworkType());
- if (NEUTRON_MODE.equals (mode)) {
+ if (NEUTRON_MODE.equals(mode)) {
- // Use an MsoNeutronUtils for all neutron commands
+ // Use an MsoNeutronUtils for all neutron commands
- // See if the Network already exists (by name)
- NetworkInfo netInfo = null;
- long queryNetworkStarttime = System.currentTimeMillis ();
- try {
- netInfo = neutron.queryNetwork (networkName, tenantId, cloudSiteId);
- } catch (MsoException me) {
- logger.error(
+ // See if the Network already exists (by name)
+ NetworkInfo netInfo = null;
+ long queryNetworkStarttime = System.currentTimeMillis();
+ try {
+ netInfo = neutron.queryNetwork(networkName, tenantId, cloudSiteId);
+ } catch (MsoException me) {
+ logger.error(
"{} {} Exception while querying network {} for CloudSite {} from Tenant {} from OpenStack ",
- MessageEnum.RA_QUERY_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(),
- networkName, cloudSiteId, tenantId, me);
- me.addContext (CREATE_NETWORK_CONTEXT);
- throw new NetworkException (me);
- }
+ MessageEnum.RA_QUERY_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(), networkName,
+ cloudSiteId, tenantId, me);
+ me.addContext(CREATE_NETWORK_CONTEXT);
+ throw new NetworkException(me);
+ }
- if (netInfo != null) {
- // Exists. If that's OK, return success with the network ID.
- // Otherwise, return an exception.
- if (failIfExists != null && failIfExists) {
- String error = String
- .format("Create Nework: Network %s already exists in %s/%s with ID %s", networkName,
- cloudSiteId, tenantId, netInfo.getId());
- logger.error("{} {} {}", MessageEnum.RA_NETWORK_ALREADY_EXIST,
- ErrorCode.DataError.getValue(), error);
- throw new NetworkException(error, MsoExceptionCategory.USERDATA);
- } else {
- // Populate the outputs from the existing network.
- networkId.value = netInfo.getId ();
- neutronNetworkId.value = netInfo.getId ();
- rollback.value = networkRollback; // Default rollback - no updates performed
- logger.warn("{} {} Found Existing network, status={} for Neutron mode ",
- MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(),
- netInfo.getStatus());
- }
- return;
+ if (netInfo != null) {
+ // Exists. If that's OK, return success with the network ID.
+ // Otherwise, return an exception.
+ if (failIfExists != null && failIfExists) {
+ String error = String.format("Create Nework: Network %s already exists in %s/%s with ID %s",
+ networkName, cloudSiteId, tenantId, netInfo.getId());
+ logger.error("{} {} {}", MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(),
+ error);
+ throw new NetworkException(error, MsoExceptionCategory.USERDATA);
+ } else {
+ // Populate the outputs from the existing network.
+ networkId.value = netInfo.getId();
+ neutronNetworkId.value = netInfo.getId();
+ rollback.value = networkRollback; // Default rollback - no updates performed
+ logger.warn("{} {} Found Existing network, status={} for Neutron mode ",
+ MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(), netInfo.getStatus());
}
+ return;
+ }
- long createNetworkStarttime = System.currentTimeMillis ();
- try {
- netInfo = neutron.createNetwork (cloudSiteId,
- tenantId,
- neutronNetworkType,
- networkName,
- physicalNetworkName,
- vlans);
- } catch (MsoException me) {
- me.addContext(CREATE_NETWORK_CONTEXT);
- logger.error("{} {} Create Network: type {} in {}/{}: ", MessageEnum.RA_CREATE_NETWORK_EXC,
+ long createNetworkStarttime = System.currentTimeMillis();
+ try {
+ netInfo = neutron.createNetwork(cloudSiteId, tenantId, neutronNetworkType, networkName,
+ physicalNetworkName, vlans);
+ } catch (MsoException me) {
+ me.addContext(CREATE_NETWORK_CONTEXT);
+ logger.error("{} {} Create Network: type {} in {}/{}: ", MessageEnum.RA_CREATE_NETWORK_EXC,
ErrorCode.DataError.getValue(), neutronNetworkType, cloudSiteId, tenantId, me);
- throw new NetworkException (me);
- }
+ throw new NetworkException(me);
+ }
- // Note: ignoring MsoNetworkAlreadyExists because we already checked.
+ // Note: ignoring MsoNetworkAlreadyExists because we already checked.
- // If reach this point, network creation is successful.
- // Since directly created via Neutron, networkId tracked by MSO is the same
- // as the neutron network ID.
- networkId.value = netInfo.getId ();
- neutronNetworkId.value = netInfo.getId ();
+ // If reach this point, network creation is successful.
+ // Since directly created via Neutron, networkId tracked by MSO is the same
+ // as the neutron network ID.
+ networkId.value = netInfo.getId();
+ neutronNetworkId.value = netInfo.getId();
- networkRollback.setNetworkCreated (true);
- networkRollback.setNetworkId (netInfo.getId ());
- networkRollback.setNeutronNetworkId (netInfo.getId ());
- networkRollback.setNetworkType (networkType);
+ networkRollback.setNetworkCreated(true);
+ networkRollback.setNetworkId(netInfo.getId());
+ networkRollback.setNeutronNetworkId(netInfo.getId());
+ networkRollback.setNetworkType(networkType);
- logger.debug("Network {} created, id = {}", networkName, netInfo.getId());
- } else if ("HEAT".equals (mode)) {
+ logger.debug("Network {} created, id = {}", networkName, netInfo.getId());
+ } else if ("HEAT".equals(mode)) {
- HeatTemplate heatTemplate = networkResource.getHeatTemplate();
- if (heatTemplate == null) {
- String error = String
- .format("Network error - undefined Heat Template. Network Type = %s", networkType);
- logger.error("{} {} {}", MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(),
- error);
- throw new NetworkException (error, MsoExceptionCategory.INTERNAL);
- }
+ HeatTemplate heatTemplate = networkResource.getHeatTemplate();
+ if (heatTemplate == null) {
+ String error = String.format("Network error - undefined Heat Template. Network Type = %s", networkType);
+ logger.error("{} {} {}", MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(), error);
+ throw new NetworkException(error, MsoExceptionCategory.INTERNAL);
+ }
- logger.debug("Got HEAT Template from DB: {}", heatTemplate.toString());
+ logger.debug("Got HEAT Template from DB: {}", heatTemplate.toString());
- // "Fix" the template if it has CR/LF (getting this from Oracle)
- String template = heatTemplate.getHeatTemplate ();
- template = template.replaceAll ("\r\n", "\n");
+ // "Fix" the template if it has CR/LF (getting this from Oracle)
+ String template = heatTemplate.getHeatTemplate();
+ template = template.replaceAll("\r\n", "\n");
- boolean aic3template=false;
- String aic3nw = AIC3_NW;
+ boolean aic3template = false;
+ String aic3nw = AIC3_NW;
- aic3nw = environment.getProperty(AIC3_NW_PROPERTY, AIC3_NW);
+ aic3nw = environment.getProperty(AIC3_NW_PROPERTY, AIC3_NW);
- if (template.contains(aic3nw))
- aic3template = true;
+ if (template.contains(aic3nw))
+ aic3template = true;
- // First, look up to see if the Network already exists (by name).
- // For HEAT orchestration of networks, the stack name will always match the network name
- StackInfo heatStack = null;
- long queryNetworkStarttime = System.currentTimeMillis ();
- try {
- heatStack = heat.queryStack (cloudSiteId, "CloudOwner", tenantId, networkName);
- } catch (MsoException me) {
- me.addContext (CREATE_NETWORK_CONTEXT);
- logger.error("{} {} Create Network (heat): query network {} in {}/{}: ",
- MessageEnum.RA_QUERY_NETWORK_EXC, ErrorCode.DataError.getValue(), networkName,
- cloudSiteId, tenantId, me);
- throw new NetworkException (me);
- }
+ // First, look up to see if the Network already exists (by name).
+ // For HEAT orchestration of networks, the stack name will always match the network name
+ StackInfo heatStack = null;
+ long queryNetworkStarttime = System.currentTimeMillis();
+ try {
+ heatStack = heat.queryStack(cloudSiteId, "CloudOwner", tenantId, networkName);
+ } catch (MsoException me) {
+ me.addContext(CREATE_NETWORK_CONTEXT);
+ logger.error("{} {} Create Network (heat): query network {} in {}/{}: ",
+ MessageEnum.RA_QUERY_NETWORK_EXC, ErrorCode.DataError.getValue(), networkName, cloudSiteId,
+ tenantId, me);
+ throw new NetworkException(me);
+ }
- if (heatStack != null && (heatStack.getStatus () != HeatStatus.NOTFOUND)) {
- // Stack exists. Return success or error depending on input directive
- if (failIfExists != null && failIfExists) {
- String error = String
- .format("CreateNetwork: Stack %s already exists in %s/%s as %s", networkName, cloudSiteId,
- tenantId, heatStack.getCanonicalName());
- logger.error("{} {} {}", MessageEnum.RA_NETWORK_ALREADY_EXIST,
- ErrorCode.DataError.getValue(), error);
- throw new NetworkException(error, MsoExceptionCategory.USERDATA);
- } else {
- // Populate the outputs from the existing stack.
- networkId.value = heatStack.getCanonicalName ();
- neutronNetworkId.value = (String) heatStack.getOutputs ().get (NETWORK_ID);
- rollback.value = networkRollback; // Default rollback - no updates performed
- if (aic3template)
- {
- networkFqdn.value = (String) heatStack.getOutputs().get(NETWORK_FQDN);
- }
- Map <String, Object> outputs = heatStack.getOutputs ();
- Map <String, String> sMap = new HashMap <> ();
- if (outputs != null) {
- for (Map.Entry<String, Object> entry : outputs.entrySet()) {
- String key=entry.getKey();
- if (key != null && key.startsWith ("subnet")) {
- if (aic3template) //one subnet_id output
- {
- Map <String, String> map = getSubnetUUId(key, outputs, subnets);
- sMap.putAll(map);
- }
- else //multiples subnet_%aaid% outputs
- {
- String subnetUUId = (String) outputs.get(key);
- sMap.put (key.substring("subnet_id_".length()), subnetUUId);
- }
- }
- }
+ if (heatStack != null && (heatStack.getStatus() != HeatStatus.NOTFOUND)) {
+ // Stack exists. Return success or error depending on input directive
+ if (failIfExists != null && failIfExists) {
+ String error = String.format("CreateNetwork: Stack %s already exists in %s/%s as %s", networkName,
+ cloudSiteId, tenantId, heatStack.getCanonicalName());
+ logger.error("{} {} {}", MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(),
+ error);
+ throw new NetworkException(error, MsoExceptionCategory.USERDATA);
+ } else {
+ // Populate the outputs from the existing stack.
+ networkId.value = heatStack.getCanonicalName();
+ neutronNetworkId.value = (String) heatStack.getOutputs().get(NETWORK_ID);
+ rollback.value = networkRollback; // Default rollback - no updates performed
+ if (aic3template) {
+ networkFqdn.value = (String) heatStack.getOutputs().get(NETWORK_FQDN);
+ }
+ Map<String, Object> outputs = heatStack.getOutputs();
+ Map<String, String> sMap = new HashMap<>();
+ if (outputs != null) {
+ for (Map.Entry<String, Object> entry : outputs.entrySet()) {
+ String key = entry.getKey();
+ if (key != null && key.startsWith("subnet")) {
+ if (aic3template) // one subnet_id output
+ {
+ Map<String, String> map = getSubnetUUId(key, outputs, subnets);
+ sMap.putAll(map);
+ } else // multiples subnet_%aaid% outputs
+ {
+ String subnetUUId = (String) outputs.get(key);
+ sMap.put(key.substring("subnet_id_".length()), subnetUUId);
+ }
+ }
}
- subnetIdMap.value = sMap;
- logger.warn("{} {} Found Existing network stack, status={} networkName={} for {}/{}",
- MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(),
- heatStack.getStatus(), networkName, cloudSiteId, tenantId);
}
- return;
- }
-
- // Ready to deploy the new Network
- // Build the common set of HEAT template parameters
- Map <String, Object> stackParams = populateNetworkParams (neutronNetworkType,
- networkName,
- physicalNetworkName,
- vlans,
- routeTargets,
- shared,
- external,
- aic3template);
-
- // Validate (and update) the input parameters against the DB definition
- // Shouldn't happen unless DB config is wrong, since all networks use same inputs
- // and inputs were already validated.
- try {
- stackParams = heat.validateStackParams (stackParams, heatTemplate);
- } catch (IllegalArgumentException e) {
- String error = "Create Network: Configuration Error: " + e.getMessage ();
- logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC,
- ErrorCode.DataError.getValue(), error,e);
- // Input parameters were not valid
- throw new NetworkException (error, MsoExceptionCategory.INTERNAL);
+ subnetIdMap.value = sMap;
+ logger.warn("{} {} Found Existing network stack, status={} networkName={} for {}/{}",
+ MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(), heatStack.getStatus(),
+ networkName, cloudSiteId, tenantId);
}
+ return;
+ }
- if (subnets != null) {
- try {
- if (aic3template)
- {
- template = mergeSubnetsAIC3 (template, subnets, stackParams);
- }
- else
- {
- template = mergeSubnets (template, subnets);
- }
- } catch (MsoException me) {
- me.addContext (CREATE_NETWORK_CONTEXT);
- logger
- .error("{} {} Exception Create Network, merging subnets for network (heat) type {} in {}/{} ",
- MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(),
- neutronNetworkType.toString(), cloudSiteId, tenantId, me);
- throw new NetworkException (me);
- }
- }
+ // Ready to deploy the new Network
+ // Build the common set of HEAT template parameters
+ Map<String, Object> stackParams = populateNetworkParams(neutronNetworkType, networkName,
+ physicalNetworkName, vlans, routeTargets, shared, external, aic3template);
+
+ // Validate (and update) the input parameters against the DB definition
+ // Shouldn't happen unless DB config is wrong, since all networks use same inputs
+ // and inputs were already validated.
+ try {
+ stackParams = heat.validateStackParams(stackParams, heatTemplate);
+ } catch (IllegalArgumentException e) {
+ String error = "Create Network: Configuration Error: " + e.getMessage();
+ logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error, e);
+ // Input parameters were not valid
+ throw new NetworkException(error, MsoExceptionCategory.INTERNAL);
+ }
- if (policyFqdns != null && !policyFqdns.isEmpty() && aic3template) {
- try {
- mergePolicyRefs (policyFqdns, stackParams);
- } catch (MsoException me) {
- me.addContext (CREATE_NETWORK_CONTEXT);
- logger.error("{} {} Exception Create Network, merging policyRefs type {} in {}/{} ",
+ if (subnets != null) {
+ try {
+ if (aic3template) {
+ template = mergeSubnetsAIC3(template, subnets, stackParams);
+ } else {
+ template = mergeSubnets(template, subnets);
+ }
+ } catch (MsoException me) {
+ me.addContext(CREATE_NETWORK_CONTEXT);
+ logger.error("{} {} Exception Create Network, merging subnets for network (heat) type {} in {}/{} ",
MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(),
neutronNetworkType.toString(), cloudSiteId, tenantId, me);
- throw new NetworkException (me);
- }
+ throw new NetworkException(me);
}
+ }
- if (routeTableFqdns != null && !routeTableFqdns.isEmpty() && aic3template) {
- try {
- mergeRouteTableRefs (routeTableFqdns, stackParams);
- } catch (MsoException me) {
- me.addContext (CREATE_NETWORK_CONTEXT);
- logger.error("{} {} Exception Create Network, merging routeTableRefs type {} in {}/{} ",
+ if (policyFqdns != null && !policyFqdns.isEmpty() && aic3template) {
+ try {
+ mergePolicyRefs(policyFqdns, stackParams);
+ } catch (MsoException me) {
+ me.addContext(CREATE_NETWORK_CONTEXT);
+ logger.error("{} {} Exception Create Network, merging policyRefs type {} in {}/{} ",
MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(),
neutronNetworkType.toString(), cloudSiteId, tenantId, me);
- throw new NetworkException (me);
- }
+ throw new NetworkException(me);
}
+ }
- // Deploy the network stack
- // Ignore MsoStackAlreadyExists exception because we already checked.
+ if (routeTableFqdns != null && !routeTableFqdns.isEmpty() && aic3template) {
try {
- if (backout == null)
- backout = true;
- heatStack = heat.createStack (cloudSiteId,
- "CloudOwner",
- tenantId,
- networkName,
- null,
- template,
- stackParams,
- true,
- heatTemplate.getTimeoutMinutes (),
- null,
- null,
- null,
- backout.booleanValue());
+ mergeRouteTableRefs(routeTableFqdns, stackParams);
} catch (MsoException me) {
- me.addContext (CREATE_NETWORK_CONTEXT);
- logger
- .error("{} {} Exception creating network type {} in {}/{} ", MessageEnum.RA_CREATE_NETWORK_EXC,
- ErrorCode.DataError.getValue(), networkName, cloudSiteId, tenantId, me);
- throw new NetworkException (me);
+ me.addContext(CREATE_NETWORK_CONTEXT);
+ logger.error("{} {} Exception Create Network, merging routeTableRefs type {} in {}/{} ",
+ MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(),
+ neutronNetworkType.toString(), cloudSiteId, tenantId, me);
+ throw new NetworkException(me);
}
+ }
- // Reach this point if createStack is successful.
+ // Deploy the network stack
+ // Ignore MsoStackAlreadyExists exception because we already checked.
+ try {
+ if (backout == null)
+ backout = true;
+ heatStack = heat.createStack(cloudSiteId, "CloudOwner", tenantId, networkName, null, template,
+ stackParams, true, heatTemplate.getTimeoutMinutes(), null, null, null, backout.booleanValue());
+ } catch (MsoException me) {
+ me.addContext(CREATE_NETWORK_CONTEXT);
+ logger.error("{} {} Exception creating network type {} in {}/{} ", MessageEnum.RA_CREATE_NETWORK_EXC,
+ ErrorCode.DataError.getValue(), networkName, cloudSiteId, tenantId, me);
+ throw new NetworkException(me);
+ }
- // For Heat-based orchestration, the MSO-tracked network ID is the heat stack,
- // and the neutronNetworkId is the network UUID returned in stack outputs.
- networkId.value = heatStack.getCanonicalName ();
- neutronNetworkId.value = (String) heatStack.getOutputs ().get (NETWORK_ID);
- if (aic3template)
- {
- networkFqdn.value = (String) heatStack.getOutputs().get(NETWORK_FQDN);
- }
- Map <String, Object> outputs = heatStack.getOutputs ();
- Map <String, String> sMap = new HashMap <> ();
- if (outputs != null) {
- for (Map.Entry<String, Object> entry : outputs.entrySet()) {
- String key = entry.getKey();
- if (key != null && key.startsWith ("subnet")) {
- if (aic3template) //one subnet output expected
- {
- Map <String, String> map = getSubnetUUId(key, outputs, subnets);
- sMap.putAll(map);
- }
- else //multiples subnet_%aaid% outputs allowed
- {
- String subnetUUId = (String) outputs.get(key);
- sMap.put (key.substring("subnet_id_".length()), subnetUUId);
- }
+ // Reach this point if createStack is successful.
+
+ // For Heat-based orchestration, the MSO-tracked network ID is the heat stack,
+ // and the neutronNetworkId is the network UUID returned in stack outputs.
+ networkId.value = heatStack.getCanonicalName();
+ neutronNetworkId.value = (String) heatStack.getOutputs().get(NETWORK_ID);
+ if (aic3template) {
+ networkFqdn.value = (String) heatStack.getOutputs().get(NETWORK_FQDN);
+ }
+ Map<String, Object> outputs = heatStack.getOutputs();
+ Map<String, String> sMap = new HashMap<>();
+ if (outputs != null) {
+ for (Map.Entry<String, Object> entry : outputs.entrySet()) {
+ String key = entry.getKey();
+ if (key != null && key.startsWith("subnet")) {
+ if (aic3template) // one subnet output expected
+ {
+ Map<String, String> map = getSubnetUUId(key, outputs, subnets);
+ sMap.putAll(map);
+ } else // multiples subnet_%aaid% outputs allowed
+ {
+ String subnetUUId = (String) outputs.get(key);
+ sMap.put(key.substring("subnet_id_".length()), subnetUUId);
}
}
}
- subnetIdMap.value = sMap;
+ }
+ subnetIdMap.value = sMap;
- rollback.value = networkRollback;
- // Populate remaining rollback info and response parameters.
- networkRollback.setNetworkStackId (heatStack.getCanonicalName ());
- networkRollback.setNeutronNetworkId ((String) heatStack.getOutputs ().get (NETWORK_ID));
- networkRollback.setNetworkCreated (true);
- networkRollback.setNetworkType (networkType);
+ rollback.value = networkRollback;
+ // Populate remaining rollback info and response parameters.
+ networkRollback.setNetworkStackId(heatStack.getCanonicalName());
+ networkRollback.setNeutronNetworkId((String) heatStack.getOutputs().get(NETWORK_ID));
+ networkRollback.setNetworkCreated(true);
+ networkRollback.setNetworkType(networkType);
- logger.debug("Network {} successfully created via HEAT", networkName);
- }
+ logger.debug("Network {} successfully created via HEAT", networkName);
+ }
return;
}
@Override
- public void updateNetwork (String cloudSiteId,
- String tenantId,
- String networkType,
- String modelCustomizationUuid,
- String networkId,
- String networkName,
- String physicalNetworkName,
- List <Integer> vlans,
- String shared,
- String external,
- List <Subnet> subnets,
- Map<String,String> networkParams,
- MsoRequest msoRequest,
- Holder <Map <String, String>> subnetIdMap,
- Holder <NetworkRollback> rollback) throws NetworkException {
- updateNetwork (cloudSiteId,
- tenantId,
- networkType,
- modelCustomizationUuid,
- networkId,
- networkName,
- physicalNetworkName,
- vlans,
- null,
- shared,
- external,
- subnets,
- null,
- null,
- msoRequest,
- subnetIdMap,
- rollback);
+ public void updateNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid,
+ String networkId, String networkName, String physicalNetworkName, List<Integer> vlans, String shared,
+ String external, List<Subnet> subnets, Map<String, String> networkParams, MsoRequest msoRequest,
+ Holder<Map<String, String>> subnetIdMap, Holder<NetworkRollback> rollback) throws NetworkException {
+ updateNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkId, networkName,
+ physicalNetworkName, vlans, null, shared, external, subnets, null, null, msoRequest, subnetIdMap,
+ rollback);
}
@Override
- public void updateNetworkContrail (String cloudSiteId,
- String tenantId,
- String networkType,
- String modelCustomizationUuid,
- String networkId,
- String networkName,
- List <RouteTarget> routeTargets,
- String shared,
- String external,
- List <Subnet> subnets,
- Map<String, String> networkParams,
- List <String> policyFqdns,
- List<String> routeTableFqdns,
- MsoRequest msoRequest,
- Holder <Map <String, String>> subnetIdMap,
- Holder <NetworkRollback> rollback) throws NetworkException {
- updateNetwork (cloudSiteId,
- tenantId,
- networkType,
- modelCustomizationUuid,
- networkId,
- networkName,
- null,
- null,
- routeTargets,
- shared,
- external,
- subnets,
- policyFqdns,
- routeTableFqdns,
- msoRequest,
- subnetIdMap,
- rollback);
+ public void updateNetworkContrail(String cloudSiteId, String tenantId, String networkType,
+ String modelCustomizationUuid, String networkId, String networkName, List<RouteTarget> routeTargets,
+ String shared, String external, List<Subnet> subnets, Map<String, String> networkParams,
+ List<String> policyFqdns, List<String> routeTableFqdns, MsoRequest msoRequest,
+ Holder<Map<String, String>> subnetIdMap, Holder<NetworkRollback> rollback) throws NetworkException {
+ updateNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkId, networkName, null, null,
+ routeTargets, shared, external, subnets, policyFqdns, routeTableFqdns, msoRequest, subnetIdMap,
+ rollback);
}
/**
- * This is the "Update Network" web service implementation.
- * It will update an existing Network of the requested type in the specified cloud
- * and tenant. The typical use will be to replace the VLANs with the supplied
- * list (to add or remove a VLAN), but other properties may be updated as well.
+ * This is the "Update Network" web service implementation. It will update an existing Network of the requested type
+ * in the specified cloud and tenant. The typical use will be to replace the VLANs with the supplied list (to add or
+ * remove a VLAN), but other properties may be updated as well.
*
- * There will be a pre-defined set of network types defined in the MSO Catalog.
- * All such networks will have a similar configuration, based on the allowable
- * Openstack networking definitions. This includes basic networks, provider
- * networks (with a single VLAN), and multi-provider networks (one or more VLANs).
+ * There will be a pre-defined set of network types defined in the MSO Catalog. All such networks will have a
+ * similar configuration, based on the allowable Openstack networking definitions. This includes basic networks,
+ * provider networks (with a single VLAN), and multi-provider networks (one or more VLANs).
*
- * Initially, all provider networks must currently be "vlan" type, and multi-provider
- * networks must be multiple VLANs on the same physical network.
+ * Initially, all provider networks must currently be "vlan" type, and multi-provider networks must be multiple
+ * VLANs on the same physical network.
*
- * This service supports two modes of Network update:
- * - via Heat Templates
- * - via Neutron API
- * The network orchestration mode for each network type is declared in its
- * catalog definition. All Heat-based templates must support some subset of
- * the same input parameters: network_name, physical_network, vlan, segments.
+ * This service supports two modes of Network update: - via Heat Templates - via Neutron API The network
+ * orchestration mode for each network type is declared in its catalog definition. All Heat-based templates must
+ * support some subset of the same input parameters: network_name, physical_network, vlan, segments.
*
- * The method returns a NetworkRollback object. This object can be passed
- * as-is to the rollbackNetwork operation to undo everything that was updated.
- * This is useful if a network is successfully updated but orchestration
- * fails on a subsequent operation.
+ * The method returns a NetworkRollback object. This object can be passed as-is to the rollbackNetwork operation to
+ * undo everything that was updated. This is useful if a network is successfully updated but orchestration fails on
+ * a subsequent operation.
*/
- private void updateNetwork (String cloudSiteId,
- String tenantId,
- String networkType,
- String modelCustomizationUuid,
- String networkId,
- String networkName,
- String physicalNetworkName,
- List <Integer> vlans,
- List <RouteTarget> routeTargets,
- String shared,
- String external,
- List <Subnet> subnets,
- List <String> policyFqdns,
- List<String> routeTableFqdns,
- MsoRequest msoRequest,
- Holder <Map <String, String>> subnetIdMap,
- Holder <NetworkRollback> rollback) throws NetworkException {
+ private void updateNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid,
+ String networkId, String networkName, String physicalNetworkName, List<Integer> vlans,
+ List<RouteTarget> routeTargets, String shared, String external, List<Subnet> subnets,
+ List<String> policyFqdns, List<String> routeTableFqdns, MsoRequest msoRequest,
+ Holder<Map<String, String>> subnetIdMap, Holder<NetworkRollback> rollback) throws NetworkException {
logger.debug("***UPDATE Network adapter with Network: {} of type {} in {}/{}", networkName, networkType,
- cloudSiteId, tenantId);
+ cloudSiteId, tenantId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
// Build a default rollback object (no actions performed)
- NetworkRollback networkRollback = new NetworkRollback ();
- networkRollback.setCloudId (cloudSiteId);
- networkRollback.setTenantId (tenantId);
- networkRollback.setMsoRequest (msoRequest);
+ NetworkRollback networkRollback = new NetworkRollback();
+ networkRollback.setCloudId(cloudSiteId);
+ networkRollback.setTenantId(tenantId);
+ networkRollback.setMsoRequest(msoRequest);
- Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSiteOpt.isPresent()) {
String error = String.format(
- "UpdateNetwork: Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration",
- networkName, cloudSiteId, tenantId);
+ "UpdateNetwork: Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration",
+ networkName, cloudSiteId, tenantId);
logger.error("{} {} {}", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error);
// Set the detailed error as the Exception 'message'
throw new NetworkException(error, MsoExceptionCategory.USERDATA);
@@ -738,441 +544,364 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
+ NetworkResource networkResource = networkCheck(startTime, networkType, modelCustomizationUuid, networkName,
+ physicalNetworkName, vlans, routeTargets, cloudSiteId, cloudSiteOpt.get());
+ String mode = networkResource.getOrchestrationMode();
+ NetworkType neutronNetworkType = NetworkType.valueOf(networkResource.getNeutronNetworkType());
- NetworkResource networkResource = networkCheck(
- startTime,
- networkType,
- modelCustomizationUuid,
- networkName,
- physicalNetworkName,
- vlans,
- routeTargets,
- cloudSiteId,
- cloudSiteOpt.get());
- String mode = networkResource.getOrchestrationMode();
- NetworkType neutronNetworkType = NetworkType.valueOf(networkResource.getNeutronNetworkType());
-
- // Use an MsoNeutronUtils for all Neutron commands
+ // Use an MsoNeutronUtils for all Neutron commands
- if (NEUTRON_MODE.equals(mode)) {
+ if (NEUTRON_MODE.equals(mode)) {
- // Verify that the Network exists
- // For Neutron-based orchestration, the networkId is the Neutron Network UUID.
- NetworkInfo netInfo = null;
- long queryNetworkStarttime = System.currentTimeMillis();
- try {
- netInfo = neutron.queryNetwork(networkId, tenantId, cloudSiteId);
- } catch (MsoException me) {
- me.addContext(UPDATE_NETWORK_CONTEXT);
- logger.error("{} {} Exception - queryNetwork query {} in {}/{} ", MessageEnum.RA_QUERY_NETWORK_EXC,
+ // Verify that the Network exists
+ // For Neutron-based orchestration, the networkId is the Neutron Network UUID.
+ NetworkInfo netInfo = null;
+ long queryNetworkStarttime = System.currentTimeMillis();
+ try {
+ netInfo = neutron.queryNetwork(networkId, tenantId, cloudSiteId);
+ } catch (MsoException me) {
+ me.addContext(UPDATE_NETWORK_CONTEXT);
+ logger.error("{} {} Exception - queryNetwork query {} in {}/{} ", MessageEnum.RA_QUERY_NETWORK_EXC,
ErrorCode.BusinessProcesssError.getValue(), networkId, cloudSiteId, tenantId, me);
- throw new NetworkException(me);
- }
+ throw new NetworkException(me);
+ }
- if (netInfo == null) {
- String error = String
- .format("Update Nework: Network %s does not exist in %s/%s", networkId, cloudSiteId, tenantId);
- logger.error("{} {} {}", MessageEnum.RA_NETWORK_NOT_FOUND,
- ErrorCode.BusinessProcesssError.getValue(), error);
- // Does not exist. Throw an exception (can't update a non-existent network)
- throw new NetworkException(error, MsoExceptionCategory.USERDATA);
- }
- long updateNetworkStarttime = System.currentTimeMillis();
- try {
- netInfo = neutron.updateNetwork(cloudSiteId,
- tenantId,
- networkId,
- neutronNetworkType,
- physicalNetworkName,
- vlans);
- } catch (MsoException me) {
- me.addContext(UPDATE_NETWORK_CONTEXT);
- logger.error("{} {} Exception - updateNetwork {} in {}/{} ", MessageEnum.RA_UPDATE_NETWORK_ERR,
+ if (netInfo == null) {
+ String error = String.format("Update Nework: Network %s does not exist in %s/%s", networkId,
+ cloudSiteId, tenantId);
+ logger.error("{} {} {}", MessageEnum.RA_NETWORK_NOT_FOUND, ErrorCode.BusinessProcesssError.getValue(),
+ error);
+ // Does not exist. Throw an exception (can't update a non-existent network)
+ throw new NetworkException(error, MsoExceptionCategory.USERDATA);
+ }
+ long updateNetworkStarttime = System.currentTimeMillis();
+ try {
+ netInfo = neutron.updateNetwork(cloudSiteId, tenantId, networkId, neutronNetworkType,
+ physicalNetworkName, vlans);
+ } catch (MsoException me) {
+ me.addContext(UPDATE_NETWORK_CONTEXT);
+ logger.error("{} {} Exception - updateNetwork {} in {}/{} ", MessageEnum.RA_UPDATE_NETWORK_ERR,
ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me);
- throw new NetworkException(me);
- }
-
- // Add the network ID and previously queried vlans to the rollback object
- networkRollback.setNetworkId(netInfo.getId());
- networkRollback.setNeutronNetworkId(netInfo.getId());
- networkRollback.setNetworkType(networkType);
- // Save previous parameters
- networkRollback.setNetworkName(netInfo.getName());
- networkRollback.setPhysicalNetwork(netInfo.getProvider());
- networkRollback.setVlans(netInfo.getVlans());
-
- logger.debug("Network {} updated, id = {}", networkId, netInfo.getId());
- } else if ("HEAT".equals(mode)) {
+ throw new NetworkException(me);
+ }
- // First, look up to see that the Network already exists.
- // For Heat-based orchestration, the networkId is the network Stack ID.
- StackInfo heatStack = null;
- long queryStackStarttime = System.currentTimeMillis();
- try {
- heatStack = heat.queryStack(cloudSiteId, "CloudOwner", tenantId, networkName);
- } catch (MsoException me) {
- me.addContext(UPDATE_NETWORK_CONTEXT);
- logger.error("{} {} Exception - QueryStack query {} in {}/{} ", MessageEnum.RA_QUERY_NETWORK_EXC,
+ // Add the network ID and previously queried vlans to the rollback object
+ networkRollback.setNetworkId(netInfo.getId());
+ networkRollback.setNeutronNetworkId(netInfo.getId());
+ networkRollback.setNetworkType(networkType);
+ // Save previous parameters
+ networkRollback.setNetworkName(netInfo.getName());
+ networkRollback.setPhysicalNetwork(netInfo.getProvider());
+ networkRollback.setVlans(netInfo.getVlans());
+
+ logger.debug("Network {} updated, id = {}", networkId, netInfo.getId());
+ } else if ("HEAT".equals(mode)) {
+
+ // First, look up to see that the Network already exists.
+ // For Heat-based orchestration, the networkId is the network Stack ID.
+ StackInfo heatStack = null;
+ long queryStackStarttime = System.currentTimeMillis();
+ try {
+ heatStack = heat.queryStack(cloudSiteId, "CloudOwner", tenantId, networkName);
+ } catch (MsoException me) {
+ me.addContext(UPDATE_NETWORK_CONTEXT);
+ logger.error("{} {} Exception - QueryStack query {} in {}/{} ", MessageEnum.RA_QUERY_NETWORK_EXC,
ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me);
- throw new NetworkException(me);
- }
+ throw new NetworkException(me);
+ }
- if (heatStack == null || (heatStack.getStatus() == HeatStatus.NOTFOUND)) {
- String error = String
- .format("UpdateNetwork: Stack %s does not exist in %s/%s", networkName, cloudSiteId, tenantId);
- logger.error("{} {} {}", MessageEnum.RA_NETWORK_NOT_FOUND, ErrorCode.DataError.getValue(),
- error);
- // Network stack does not exist. Return an error
- throw new NetworkException(error, MsoExceptionCategory.USERDATA);
- }
+ if (heatStack == null || (heatStack.getStatus() == HeatStatus.NOTFOUND)) {
+ String error = String.format("UpdateNetwork: Stack %s does not exist in %s/%s", networkName,
+ cloudSiteId, tenantId);
+ logger.error("{} {} {}", MessageEnum.RA_NETWORK_NOT_FOUND, ErrorCode.DataError.getValue(), error);
+ // Network stack does not exist. Return an error
+ throw new NetworkException(error, MsoExceptionCategory.USERDATA);
+ }
- // Get the previous parameters for rollback
- Map<String, Object> heatParams = heatStack.getParameters();
+ // Get the previous parameters for rollback
+ Map<String, Object> heatParams = heatStack.getParameters();
- String previousNetworkName = (String) heatParams.get("network_name");
- String previousPhysicalNetwork = (String) heatParams.get(PHYSICAL_NETWORK);
+ String previousNetworkName = (String) heatParams.get("network_name");
+ String previousPhysicalNetwork = (String) heatParams.get(PHYSICAL_NETWORK);
- List<Integer> previousVlans = new ArrayList<>();
- String vlansParam = (String) heatParams.get(VLANS);
- if (vlansParam != null) {
- for (String vlan : vlansParam.split(",")) {
- try {
- previousVlans.add(Integer.parseInt(vlan));
- } catch (NumberFormatException e) {
- logger.warn("{} {} Exception - VLAN parse for params {} ", MessageEnum.RA_VLAN_PARSE,
+ List<Integer> previousVlans = new ArrayList<>();
+ String vlansParam = (String) heatParams.get(VLANS);
+ if (vlansParam != null) {
+ for (String vlan : vlansParam.split(",")) {
+ try {
+ previousVlans.add(Integer.parseInt(vlan));
+ } catch (NumberFormatException e) {
+ logger.warn("{} {} Exception - VLAN parse for params {} ", MessageEnum.RA_VLAN_PARSE,
ErrorCode.DataError.getValue(), vlansParam, e);
- }
}
}
- logger.debug("Update Stack: Previous VLANS: {}", previousVlans);
+ }
+ logger.debug("Update Stack: Previous VLANS: {}", previousVlans);
- // Ready to deploy the updated Network via Heat
+ // Ready to deploy the updated Network via Heat
- HeatTemplate heatTemplate = networkResource.getHeatTemplate();
- if (heatTemplate == null) {
- String error = "Network error - undefined Heat Template. Network Type=" + networkType;
- logger.error("{} {} {}", MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(),
- error);
- throw new NetworkException(error, MsoExceptionCategory.INTERNAL);
- }
+ HeatTemplate heatTemplate = networkResource.getHeatTemplate();
+ if (heatTemplate == null) {
+ String error = "Network error - undefined Heat Template. Network Type=" + networkType;
+ logger.error("{} {} {}", MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(), error);
+ throw new NetworkException(error, MsoExceptionCategory.INTERNAL);
+ }
- logger.debug("Got HEAT Template from DB: {}", heatTemplate.toString());
+ logger.debug("Got HEAT Template from DB: {}", heatTemplate.toString());
- // "Fix" the template if it has CR/LF (getting this from Oracle)
- String template = heatTemplate.getHeatTemplate();
- template = template.replaceAll("\r\n", "\n");
+ // "Fix" the template if it has CR/LF (getting this from Oracle)
+ String template = heatTemplate.getHeatTemplate();
+ template = template.replaceAll("\r\n", "\n");
- boolean aic3template = false;
- String aic3nw = AIC3_NW;
+ boolean aic3template = false;
+ String aic3nw = AIC3_NW;
- aic3nw = environment.getProperty(AIC3_NW_PROPERTY, AIC3_NW);
+ aic3nw = environment.getProperty(AIC3_NW_PROPERTY, AIC3_NW);
- if (template.contains(aic3nw))
- aic3template = true;
+ if (template.contains(aic3nw))
+ aic3template = true;
- // Build the common set of HEAT template parameters
- Map<String, Object> stackParams = populateNetworkParams(neutronNetworkType,
- networkName,
- physicalNetworkName,
- vlans,
- routeTargets,
- shared,
- external,
- aic3template);
+ // Build the common set of HEAT template parameters
+ Map<String, Object> stackParams = populateNetworkParams(neutronNetworkType, networkName,
+ physicalNetworkName, vlans, routeTargets, shared, external, aic3template);
- // Validate (and update) the input parameters against the DB definition
- // Shouldn't happen unless DB config is wrong, since all networks use same inputs
- try {
- stackParams = heat.validateStackParams(stackParams, heatTemplate);
- } catch (IllegalArgumentException e) {
- String error = "UpdateNetwork: Configuration Error: Network Type=" + networkType;
- logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error);
- throw new NetworkException(error, MsoExceptionCategory.INTERNAL, e);
- }
+ // Validate (and update) the input parameters against the DB definition
+ // Shouldn't happen unless DB config is wrong, since all networks use same inputs
+ try {
+ stackParams = heat.validateStackParams(stackParams, heatTemplate);
+ } catch (IllegalArgumentException e) {
+ String error = "UpdateNetwork: Configuration Error: Network Type=" + networkType;
+ logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error);
+ throw new NetworkException(error, MsoExceptionCategory.INTERNAL, e);
+ }
- if (subnets != null) {
- try {
- if (aic3template) {
- template = mergeSubnetsAIC3(template, subnets, stackParams);
- } else {
- template = mergeSubnets(template, subnets);
- }
- } catch (MsoException me) {
- me.addContext(UPDATE_NETWORK_CONTEXT);
- logger.error("{} {} Exception - UpdateNetwork mergeSubnets for network type {} in {}/{} ",
- MessageEnum.RA_UPDATE_NETWORK_ERR, ErrorCode.DataError.getValue(),
- neutronNetworkType.toString(), cloudSiteId, tenantId, me);
- throw new NetworkException(me);
+ if (subnets != null) {
+ try {
+ if (aic3template) {
+ template = mergeSubnetsAIC3(template, subnets, stackParams);
+ } else {
+ template = mergeSubnets(template, subnets);
}
- }
-
- if (policyFqdns != null && aic3template) {
- try {
- mergePolicyRefs(policyFqdns, stackParams);
- } catch (MsoException me) {
- me.addContext(UPDATE_NETWORK_CONTEXT);
- logger.error("{} {} Exception - UpdateNetwork mergePolicyRefs type {} in {}/{} ",
+ } catch (MsoException me) {
+ me.addContext(UPDATE_NETWORK_CONTEXT);
+ logger.error("{} {} Exception - UpdateNetwork mergeSubnets for network type {} in {}/{} ",
MessageEnum.RA_UPDATE_NETWORK_ERR, ErrorCode.DataError.getValue(),
neutronNetworkType.toString(), cloudSiteId, tenantId, me);
- throw new NetworkException(me);
- }
+ throw new NetworkException(me);
}
+ }
- if (routeTableFqdns != null && !routeTableFqdns.isEmpty() && aic3template) {
- try {
- mergeRouteTableRefs(routeTableFqdns, stackParams);
- } catch (MsoException me) {
- me.addContext(UPDATE_NETWORK_CONTEXT);
- logger.error("{} {} Exception - UpdateNetwork mergeRouteTableRefs type {} in {}/{} ",
+ if (policyFqdns != null && aic3template) {
+ try {
+ mergePolicyRefs(policyFqdns, stackParams);
+ } catch (MsoException me) {
+ me.addContext(UPDATE_NETWORK_CONTEXT);
+ logger.error("{} {} Exception - UpdateNetwork mergePolicyRefs type {} in {}/{} ",
MessageEnum.RA_UPDATE_NETWORK_ERR, ErrorCode.DataError.getValue(),
neutronNetworkType.toString(), cloudSiteId, tenantId, me);
- throw new NetworkException(me);
- }
+ throw new NetworkException(me);
}
+ }
- // Update the network stack
- // Ignore MsoStackNotFound exception because we already checked.
- long updateStackStarttime = System.currentTimeMillis();
+ if (routeTableFqdns != null && !routeTableFqdns.isEmpty() && aic3template) {
try {
- heatStack = heatWithUpdate.updateStack(cloudSiteId,
- "CloudOwner",
- tenantId,
- networkId,
- template,
- stackParams,
- true,
- heatTemplate.getTimeoutMinutes());
+ mergeRouteTableRefs(routeTableFqdns, stackParams);
} catch (MsoException me) {
me.addContext(UPDATE_NETWORK_CONTEXT);
- logger.error("{} {} Exception - update network {} in {}/{} ", MessageEnum.RA_UPDATE_NETWORK_ERR,
- ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me);
+ logger.error("{} {} Exception - UpdateNetwork mergeRouteTableRefs type {} in {}/{} ",
+ MessageEnum.RA_UPDATE_NETWORK_ERR, ErrorCode.DataError.getValue(),
+ neutronNetworkType.toString(), cloudSiteId, tenantId, me);
throw new NetworkException(me);
}
+ }
- Map<String, Object> outputs = heatStack.getOutputs();
- Map<String, String> sMap = new HashMap<>();
- if (outputs != null) {
- for (Map.Entry<String, Object> entry : outputs.entrySet()) {
- String key=entry.getKey();
- if (key != null && key.startsWith("subnet")) {
- if (aic3template) //one subnet output expected
- {
- Map<String, String> map = getSubnetUUId(key, outputs, subnets);
- sMap.putAll(map);
- } else //multiples subnet_%aaid% outputs allowed
- {
- String subnetUUId = (String) outputs.get(key);
- sMap.put(key.substring("subnet_id_".length()), subnetUUId);
- }
+ // Update the network stack
+ // Ignore MsoStackNotFound exception because we already checked.
+ long updateStackStarttime = System.currentTimeMillis();
+ try {
+ heatStack = heatWithUpdate.updateStack(cloudSiteId, "CloudOwner", tenantId, networkId, template,
+ stackParams, true, heatTemplate.getTimeoutMinutes());
+ } catch (MsoException me) {
+ me.addContext(UPDATE_NETWORK_CONTEXT);
+ logger.error("{} {} Exception - update network {} in {}/{} ", MessageEnum.RA_UPDATE_NETWORK_ERR,
+ ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me);
+ throw new NetworkException(me);
+ }
+
+ Map<String, Object> outputs = heatStack.getOutputs();
+ Map<String, String> sMap = new HashMap<>();
+ if (outputs != null) {
+ for (Map.Entry<String, Object> entry : outputs.entrySet()) {
+ String key = entry.getKey();
+ if (key != null && key.startsWith("subnet")) {
+ if (aic3template) // one subnet output expected
+ {
+ Map<String, String> map = getSubnetUUId(key, outputs, subnets);
+ sMap.putAll(map);
+ } else // multiples subnet_%aaid% outputs allowed
+ {
+ String subnetUUId = (String) outputs.get(key);
+ sMap.put(key.substring("subnet_id_".length()), subnetUUId);
}
}
}
- subnetIdMap.value = sMap;
+ }
+ subnetIdMap.value = sMap;
- // Reach this point if createStack is successful.
- // Populate remaining rollback info and response parameters.
- networkRollback.setNetworkStackId(heatStack.getCanonicalName());
- if(null != outputs) {
- networkRollback.setNeutronNetworkId((String) outputs.get(NETWORK_ID));
- }
- else {
- logger.debug("outputs is NULL");
- }
- networkRollback.setNetworkType(networkType);
- // Save previous parameters
- networkRollback.setNetworkName(previousNetworkName);
- networkRollback.setPhysicalNetwork(previousPhysicalNetwork);
- networkRollback.setVlans(previousVlans);
+ // Reach this point if createStack is successful.
+ // Populate remaining rollback info and response parameters.
+ networkRollback.setNetworkStackId(heatStack.getCanonicalName());
+ if (null != outputs) {
+ networkRollback.setNeutronNetworkId((String) outputs.get(NETWORK_ID));
+ } else {
+ logger.debug("outputs is NULL");
+ }
+ networkRollback.setNetworkType(networkType);
+ // Save previous parameters
+ networkRollback.setNetworkName(previousNetworkName);
+ networkRollback.setPhysicalNetwork(previousPhysicalNetwork);
+ networkRollback.setVlans(previousVlans);
- rollback.value = networkRollback;
+ rollback.value = networkRollback;
- logger.debug("Network {} successfully updated via HEAT", networkId);
- }
+ logger.debug("Network {} successfully updated via HEAT", networkId);
+ }
return;
}
- private NetworkResource networkCheck (long startTime,
- String networkType,
- String modelCustomizationUuid,
- String networkName,
- String physicalNetworkName,
- List <Integer> vlans,
- List <RouteTarget> routeTargets,
- String cloudSiteId,
- CloudSite cloudSite) throws NetworkException {
+ private NetworkResource networkCheck(long startTime, String networkType, String modelCustomizationUuid,
+ String networkName, String physicalNetworkName, List<Integer> vlans, List<RouteTarget> routeTargets,
+ String cloudSiteId, CloudSite cloudSite) throws NetworkException {
// Retrieve the Network Resource definition
NetworkResource networkResource = null;
NetworkResourceCustomization networkCust = null;
CollectionNetworkResourceCustomization collectionNetworkCust = null;
- if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) {
- if (!commonUtils.isNullOrEmpty(networkType)) {
- networkResource = networkResourceRepo.findFirstByModelNameOrderByModelVersionDesc(networkType);
- }
- } else {
- networkCust = networkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid);
- if (networkCust == null) {
- collectionNetworkCust = collectionNetworkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid);
- }
- }
- if(networkCust != null){
- logger.debug("Got Network Customization definition from Catalog: {}", networkCust.toString());
-
- networkResource = networkCust.getNetworkResource();
- } else if (collectionNetworkCust != null) {
- logger.debug("Retrieved Collection Network Resource Customization from Catalog: {}",
- collectionNetworkCust.toString());
- networkResource = collectionNetworkCust.getNetworkResource();
- }
- if (networkResource == null) {
- String error = String.format(
- "Create/UpdateNetwork: Unable to get network resource with NetworkType: %s or ModelCustomizationUUID:%s",
- networkType, modelCustomizationUuid);
- logger.error("{} {} {} ", MessageEnum.RA_UNKOWN_PARAM, ErrorCode.DataError.getValue(), error);
-
- throw new NetworkException(error, MsoExceptionCategory.USERDATA);
- }
+ if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) {
+ if (!commonUtils.isNullOrEmpty(networkType)) {
+ networkResource = networkResourceRepo.findFirstByModelNameOrderByModelVersionDesc(networkType);
+ }
+ } else {
+ networkCust = networkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid);
+ if (networkCust == null) {
+ collectionNetworkCust =
+ collectionNetworkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid);
+ }
+ }
+ if (networkCust != null) {
+ logger.debug("Got Network Customization definition from Catalog: {}", networkCust.toString());
+
+ networkResource = networkCust.getNetworkResource();
+ } else if (collectionNetworkCust != null) {
+ logger.debug("Retrieved Collection Network Resource Customization from Catalog: {}",
+ collectionNetworkCust.toString());
+ networkResource = collectionNetworkCust.getNetworkResource();
+ }
+ if (networkResource == null) {
+ String error = String.format(
+ "Create/UpdateNetwork: Unable to get network resource with NetworkType: %s or ModelCustomizationUUID:%s",
+ networkType, modelCustomizationUuid);
+ logger.error("{} {} {} ", MessageEnum.RA_UNKOWN_PARAM, ErrorCode.DataError.getValue(), error);
+
+ throw new NetworkException(error, MsoExceptionCategory.USERDATA);
+ }
logger.debug("Got Network definition from Catalog: {}", networkResource.toString());
- String mode = networkResource.getOrchestrationMode();
- NetworkType neutronNetworkType = NetworkType
- .valueOf(networkResource.getNeutronNetworkType());
-
- // All Networks are orchestrated via HEAT or Neutron
- if (!("HEAT".equals(mode) || NEUTRON_MODE.equals(mode))) {
- String error = "CreateNetwork: Configuration Error: Network Type = " + networkType;
- logger.error("{} {} {}", MessageEnum.RA_NETWORK_ORCHE_MODE_NOT_SUPPORT,
- ErrorCode.DataError.getValue(), error);
- throw new NetworkException(error, MsoExceptionCategory.INTERNAL);
- }
-
- MavenLikeVersioning aicV = new MavenLikeVersioning();
- aicV.setVersion(cloudSite.getCloudVersion());
- if ((aicV.isMoreRecentThan(networkResource.getAicVersionMin()) || aicV
- .isTheSameVersion(networkResource.getAicVersionMin())) // aic
- // >=
- // min
- && (aicV.isTheSameVersion(networkResource
- .getAicVersionMax()) || !(aicV
- .isMoreRecentThan(networkResource
- .getAicVersionMax())))) // aic <= max
- {
- logger.debug("Network Type:{} VersionMin:{} VersionMax:{} supported on Cloud:{} with AIC_Version:{}",
- networkType, networkResource.getAicVersionMin(), networkResource.getAicVersionMax(), cloudSiteId,
- cloudSite.getCloudVersion());
- } else {
- String error = String
- .format("Network Type:%s Version_Min:%s Version_Max:%s not supported on Cloud:%s with AIC_Version:%s",
- networkType, networkType, networkResource.getAicVersionMin(),
- networkResource.getAicVersionMax(), cloudSiteId, cloudSite.getCloudVersion());
- logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error);
- throw new NetworkException(error, MsoExceptionCategory.USERDATA);
- }
-
- // Validate the Network parameters.
- String missing = validateNetworkParams(neutronNetworkType,
- networkName, physicalNetworkName, vlans, routeTargets);
- if (!missing.isEmpty()) {
- String error = "Create Network: Missing parameters: " + missing;
- logger.error("{} {} {}", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error);
-
- throw new NetworkException(error, MsoExceptionCategory.USERDATA);
- }
+ String mode = networkResource.getOrchestrationMode();
+ NetworkType neutronNetworkType = NetworkType.valueOf(networkResource.getNeutronNetworkType());
+
+ // All Networks are orchestrated via HEAT or Neutron
+ if (!("HEAT".equals(mode) || NEUTRON_MODE.equals(mode))) {
+ String error = "CreateNetwork: Configuration Error: Network Type = " + networkType;
+ logger.error("{} {} {}", MessageEnum.RA_NETWORK_ORCHE_MODE_NOT_SUPPORT, ErrorCode.DataError.getValue(),
+ error);
+ throw new NetworkException(error, MsoExceptionCategory.INTERNAL);
+ }
+
+ MavenLikeVersioning aicV = new MavenLikeVersioning();
+ aicV.setVersion(cloudSite.getCloudVersion());
+ if ((aicV.isMoreRecentThan(networkResource.getAicVersionMin())
+ || aicV.isTheSameVersion(networkResource.getAicVersionMin())) // aic
+ // >=
+ // min
+ && (aicV.isTheSameVersion(networkResource.getAicVersionMax())
+ || !(aicV.isMoreRecentThan(networkResource.getAicVersionMax())))) // aic <= max
+ {
+ logger.debug("Network Type:{} VersionMin:{} VersionMax:{} supported on Cloud:{} with AIC_Version:{}",
+ networkType, networkResource.getAicVersionMin(), networkResource.getAicVersionMax(), cloudSiteId,
+ cloudSite.getCloudVersion());
+ } else {
+ String error = String.format(
+ "Network Type:%s Version_Min:%s Version_Max:%s not supported on Cloud:%s with AIC_Version:%s",
+ networkType, networkType, networkResource.getAicVersionMin(), networkResource.getAicVersionMax(),
+ cloudSiteId, cloudSite.getCloudVersion());
+ logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error);
+ throw new NetworkException(error, MsoExceptionCategory.USERDATA);
+ }
+
+ // Validate the Network parameters.
+ String missing =
+ validateNetworkParams(neutronNetworkType, networkName, physicalNetworkName, vlans, routeTargets);
+ if (!missing.isEmpty()) {
+ String error = "Create Network: Missing parameters: " + missing;
+ logger.error("{} {} {}", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error);
+
+ throw new NetworkException(error, MsoExceptionCategory.USERDATA);
+ }
return networkResource;
}
@Override
- public void queryNetwork (String cloudSiteId,
- String tenantId,
- String networkNameOrId,
- MsoRequest msoRequest,
- Holder <Boolean> networkExists,
- Holder <String> networkId,
- Holder <String> neutronNetworkId,
- Holder <NetworkStatus> status,
- Holder <List <Integer>> vlans,
- Holder <Map <String, String>> subnetIdMap) throws NetworkException {
- queryNetwork (cloudSiteId,
- tenantId,
- networkNameOrId,
- msoRequest,
- networkExists,
- networkId,
- neutronNetworkId,
- status,
- vlans,
- null,
- subnetIdMap);
+ public void queryNetwork(String cloudSiteId, String tenantId, String networkNameOrId, MsoRequest msoRequest,
+ Holder<Boolean> networkExists, Holder<String> networkId, Holder<String> neutronNetworkId,
+ Holder<NetworkStatus> status, Holder<List<Integer>> vlans, Holder<Map<String, String>> subnetIdMap)
+ throws NetworkException {
+ queryNetwork(cloudSiteId, tenantId, networkNameOrId, msoRequest, networkExists, networkId, neutronNetworkId,
+ status, vlans, null, subnetIdMap);
}
@Override
- public void queryNetworkContrail (String cloudSiteId,
- String tenantId,
- String networkNameOrId,
- MsoRequest msoRequest,
- Holder <Boolean> networkExists,
- Holder <String> networkId,
- Holder <String> neutronNetworkId,
- Holder <NetworkStatus> status,
- Holder <List <RouteTarget>> routeTargets,
- Holder <Map <String, String>> subnetIdMap) throws NetworkException {
- queryNetwork (cloudSiteId,
- tenantId,
- networkNameOrId,
- msoRequest,
- networkExists,
- networkId,
- neutronNetworkId,
- status,
- null,
- routeTargets,
- subnetIdMap);
+ public void queryNetworkContrail(String cloudSiteId, String tenantId, String networkNameOrId, MsoRequest msoRequest,
+ Holder<Boolean> networkExists, Holder<String> networkId, Holder<String> neutronNetworkId,
+ Holder<NetworkStatus> status, Holder<List<RouteTarget>> routeTargets,
+ Holder<Map<String, String>> subnetIdMap) throws NetworkException {
+ queryNetwork(cloudSiteId, tenantId, networkNameOrId, msoRequest, networkExists, networkId, neutronNetworkId,
+ status, null, routeTargets, subnetIdMap);
}
/**
- * This is the queryNetwork method. It returns the existence and status of
- * the specified network, along with its Neutron UUID and list of VLANs.
- * This method attempts to find the network using both Heat and Neutron.
- * Heat stacks are first searched based on the provided network name/id.
- * If none is found, the Neutron is directly queried.
+ * This is the queryNetwork method. It returns the existence and status of the specified network, along with its
+ * Neutron UUID and list of VLANs. This method attempts to find the network using both Heat and Neutron. Heat stacks
+ * are first searched based on the provided network name/id. If none is found, the Neutron is directly queried.
*/
- private void queryNetwork (String cloudSiteId,
- String tenantId,
- String networkNameOrId,
- MsoRequest msoRequest,
- Holder <Boolean> networkExists,
- Holder <String> networkId,
- Holder <String> neutronNetworkId,
- Holder <NetworkStatus> status,
- Holder <List <Integer>> vlans,
- Holder <List <RouteTarget>> routeTargets,
- Holder <Map <String, String>> subnetIdMap) throws NetworkException {
+ private void queryNetwork(String cloudSiteId, String tenantId, String networkNameOrId, MsoRequest msoRequest,
+ Holder<Boolean> networkExists, Holder<String> networkId, Holder<String> neutronNetworkId,
+ Holder<NetworkStatus> status, Holder<List<Integer>> vlans, Holder<List<RouteTarget>> routeTargets,
+ Holder<Map<String, String>> subnetIdMap) throws NetworkException {
logger.debug("*** QUERY Network with Network: {} in {}/{}", networkNameOrId, cloudSiteId, tenantId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
- if (commonUtils.isNullOrEmpty (cloudSiteId)
- || commonUtils.isNullOrEmpty(tenantId)
- || commonUtils.isNullOrEmpty(networkNameOrId)) {
+ if (commonUtils.isNullOrEmpty(cloudSiteId) || commonUtils.isNullOrEmpty(tenantId)
+ || commonUtils.isNullOrEmpty(networkNameOrId)) {
String error = "Missing mandatory parameter cloudSiteId, tenantId or networkId";
logger.error("{} {} {}", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error);
- throw new NetworkException (error, MsoExceptionCategory.USERDATA);
+ throw new NetworkException(error, MsoExceptionCategory.USERDATA);
}
Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
- if (!cloudSiteOpt.isPresent())
- {
- String error = String
- .format("Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration",
+ if (!cloudSiteOpt.isPresent()) {
+ String error = String.format(
+ "Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration",
networkNameOrId, cloudSiteId, tenantId);
logger.error("{} {} {}", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error);
- // Set the detailed error as the Exception 'message'
- throw new NetworkException (error, MsoExceptionCategory.USERDATA);
+ // Set the detailed error as the Exception 'message'
+ throw new NetworkException(error, MsoExceptionCategory.USERDATA);
}
// Use MsoNeutronUtils for all NEUTRON commands
@@ -1181,38 +910,37 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
String neutronId;
// Try Heat first, since networks may be named the same as the Heat stack
StackInfo heatStack = null;
- long queryStackStarttime = System.currentTimeMillis ();
+ long queryStackStarttime = System.currentTimeMillis();
try {
- heatStack = heat.queryStack (cloudSiteId, "CloudOwner", tenantId, networkNameOrId);
+ heatStack = heat.queryStack(cloudSiteId, "CloudOwner", tenantId, networkNameOrId);
} catch (MsoException me) {
- me.addContext ("QueryNetwork");
+ me.addContext("QueryNetwork");
logger.error("{} {} Exception - Query Network (heat): {} in {}/{} ", MessageEnum.RA_QUERY_NETWORK_EXC,
- ErrorCode.DataError.getValue(), networkNameOrId, cloudSiteId, tenantId, me);
- throw new NetworkException (me);
+ ErrorCode.DataError.getValue(), networkNameOrId, cloudSiteId, tenantId, me);
+ throw new NetworkException(me);
}
// Populate the outputs based on the returned Stack information
- if (heatStack != null && heatStack.getStatus () != HeatStatus.NOTFOUND) {
+ if (heatStack != null && heatStack.getStatus() != HeatStatus.NOTFOUND) {
// Found it. Get the neutronNetworkId for further query
- Map <String, Object> outputs = heatStack.getOutputs ();
- neutronId = (String) outputs.get (NETWORK_ID);
+ Map<String, Object> outputs = heatStack.getOutputs();
+ neutronId = (String) outputs.get(NETWORK_ID);
mode = "HEAT";
- Map <String, String> sMap = new HashMap <> ();
+ Map<String, String> sMap = new HashMap<>();
if (outputs != null) {
- for (String key : outputs.keySet ()) {
- if (key != null && key.startsWith ("subnet_id_")) //multiples subnet_%aaid% outputs
- {
- String subnetUUId = (String) outputs.get(key);
- sMap.put (key.substring("subnet_id_".length()), subnetUUId);
- }
- else if (key != null && key.startsWith ("subnet")) //one subnet output expected
- {
- Map <String, String> map = getSubnetUUId(key, outputs, null);
- sMap.putAll(map);
- }
-
- }
+ for (String key : outputs.keySet()) {
+ if (key != null && key.startsWith("subnet_id_")) // multiples subnet_%aaid% outputs
+ {
+ String subnetUUId = (String) outputs.get(key);
+ sMap.put(key.substring("subnet_id_".length()), subnetUUId);
+ } else if (key != null && key.startsWith("subnet")) // one subnet output expected
+ {
+ Map<String, String> map = getSubnetUUId(key, outputs, null);
+ sMap.putAll(map);
+ }
+
+ }
}
subnetIdMap.value = sMap;
} else {
@@ -1224,143 +952,133 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
// Query directly against the Neutron Network for the details
// no RouteTargets available for ContrailV2 in neutron net-show
// networkId is heatStackId
- long queryNetworkStarttime = System.currentTimeMillis ();
+ long queryNetworkStarttime = System.currentTimeMillis();
try {
- NetworkInfo netInfo = neutron.queryNetwork (neutronId, tenantId, cloudSiteId);
+ NetworkInfo netInfo = neutron.queryNetwork(neutronId, tenantId, cloudSiteId);
if (netInfo != null) {
// Found. Populate the output elements
networkExists.value = Boolean.TRUE;
- if ("HEAT".equals (mode)) {
- networkId.value = heatStack.getCanonicalName ();
+ if ("HEAT".equals(mode)) {
+ networkId.value = heatStack.getCanonicalName();
} else {
- networkId.value = netInfo.getId ();
+ networkId.value = netInfo.getId();
}
- neutronNetworkId.value = netInfo.getId ();
- status.value = netInfo.getStatus ();
+ neutronNetworkId.value = netInfo.getId();
+ status.value = netInfo.getStatus();
if (vlans != null)
- vlans.value = netInfo.getVlans ();
+ vlans.value = netInfo.getVlans();
logger.debug("Network {} found({}), ID = {}{}", networkNameOrId, mode, networkId.value,
- ("HEAT".equals(mode) ? ",NeutronId = " + neutronNetworkId.value : ""));
+ ("HEAT".equals(mode) ? ",NeutronId = " + neutronNetworkId.value : ""));
} else {
// Not found. Populate the status fields, leave the rest null
networkExists.value = Boolean.FALSE;
status.value = NetworkStatus.NOTFOUND;
neutronNetworkId.value = null;
if (vlans != null)
- vlans.value = new ArrayList<>();
+ vlans.value = new ArrayList<>();
logger.debug("Network {} not found", networkNameOrId);
}
} catch (MsoException me) {
- me.addContext ("QueryNetwork");
+ me.addContext("QueryNetwork");
logger.error("{} {} Exception - Query Network (neutron): {} in {}/{} ", MessageEnum.RA_QUERY_NETWORK_EXC,
- ErrorCode.DataError.getValue(), networkNameOrId, cloudSiteId, tenantId, me);
- throw new NetworkException (me);
+ ErrorCode.DataError.getValue(), networkNameOrId, cloudSiteId, tenantId, me);
+ throw new NetworkException(me);
}
return;
}
/**
- * This is the "Delete Network" web service implementation.
- * It will delete a Network in the specified cloud and tenant.
+ * This is the "Delete Network" web service implementation. It will delete a Network in the specified cloud and
+ * tenant.
*
* If the network is not found, it is treated as a success.
*
- * This service supports two modes of Network creation/update/delete:
- * - via Heat Templates
- * - via Neutron API
- * The network orchestration mode for each network type is declared in its
- * catalog definition.
+ * This service supports two modes of Network creation/update/delete: - via Heat Templates - via Neutron API The
+ * network orchestration mode for each network type is declared in its catalog definition.
*
- * For Heat-based orchestration, the networkId should be the stack ID.
- * For Neutron-based orchestration, the networkId should be the Neutron network UUID.
+ * For Heat-based orchestration, the networkId should be the stack ID. For Neutron-based orchestration, the
+ * networkId should be the Neutron network UUID.
*
- * The method returns nothing on success. Rollback is not possible for delete
- * commands, so any failure on delete will require manual fallout in the client.
+ * The method returns nothing on success. Rollback is not possible for delete commands, so any failure on delete
+ * will require manual fallout in the client.
*/
@Override
- public void deleteNetwork (String cloudSiteId,
- String tenantId,
- String networkType,
- String modelCustomizationUuid,
- String networkId,
- MsoRequest msoRequest,
- Holder <Boolean> networkDeleted) throws NetworkException {
+ public void deleteNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid,
+ String networkId, MsoRequest msoRequest, Holder<Boolean> networkDeleted) throws NetworkException {
logger.debug("*** DELETE Network adapter with Network: {} in {}/{}", networkId, cloudSiteId, tenantId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
- if (commonUtils.isNullOrEmpty (cloudSiteId)
- || commonUtils.isNullOrEmpty(tenantId)
- || commonUtils.isNullOrEmpty(networkId)) {
- String error = "Missing mandatory parameter cloudSiteId, tenantId or networkId";
- logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error);
- throw new NetworkException (error, MsoExceptionCategory.USERDATA);
- }
+ if (commonUtils.isNullOrEmpty(cloudSiteId) || commonUtils.isNullOrEmpty(tenantId)
+ || commonUtils.isNullOrEmpty(networkId)) {
+ String error = "Missing mandatory parameter cloudSiteId, tenantId or networkId";
+ logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error);
+ throw new NetworkException(error, MsoExceptionCategory.USERDATA);
+ }
+
+ // Retrieve the Network Resource definition
+ NetworkResource networkResource = null;
- // Retrieve the Network Resource definition
- NetworkResource networkResource = null;
-
- if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) {
- if (!commonUtils.isNullOrEmpty(networkType)) {
- networkResource = networkResourceRepo.findFirstByModelNameOrderByModelVersionDesc(networkType);
- }
- } else {
- NetworkResourceCustomization nrc = networkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid);
- if (nrc != null) {
- networkResource = nrc.getNetworkResource();
- }
- }
- String mode = "";
- if (networkResource != null) {
- logger.debug("Got Network definition from Catalog: {}", networkResource.toString());
-
- mode = networkResource.getOrchestrationMode ();
+ if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) {
+ if (!commonUtils.isNullOrEmpty(networkType)) {
+ networkResource = networkResourceRepo.findFirstByModelNameOrderByModelVersionDesc(networkType);
}
+ } else {
+ NetworkResourceCustomization nrc =
+ networkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid);
+ if (nrc != null) {
+ networkResource = nrc.getNetworkResource();
+ }
+ }
+ String mode = "";
+ if (networkResource != null) {
+ logger.debug("Got Network definition from Catalog: {}", networkResource.toString());
- if (NEUTRON_MODE.equals (mode)) {
+ mode = networkResource.getOrchestrationMode();
+ }
- // Use MsoNeutronUtils for all NEUTRON commands
- long deleteNetworkStarttime = System.currentTimeMillis ();
- try {
- // The deleteNetwork function in MsoNeutronUtils returns success if the network
- // was not found. So don't bother to query first.
- boolean deleted = neutron.deleteNetwork (networkId, tenantId, cloudSiteId);
- networkDeleted.value = deleted;
- } catch (MsoException me) {
- me.addContext ("DeleteNetwork");
- logger.error("{} {} Delete Network (neutron): {} in {}/{} ", MessageEnum.RA_DELETE_NETWORK_EXC,
+ if (NEUTRON_MODE.equals(mode)) {
+
+ // Use MsoNeutronUtils for all NEUTRON commands
+ long deleteNetworkStarttime = System.currentTimeMillis();
+ try {
+ // The deleteNetwork function in MsoNeutronUtils returns success if the network
+ // was not found. So don't bother to query first.
+ boolean deleted = neutron.deleteNetwork(networkId, tenantId, cloudSiteId);
+ networkDeleted.value = deleted;
+ } catch (MsoException me) {
+ me.addContext("DeleteNetwork");
+ logger.error("{} {} Delete Network (neutron): {} in {}/{} ", MessageEnum.RA_DELETE_NETWORK_EXC,
ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me);
- throw new NetworkException (me);
- }
- } else { // DEFAULT to ("HEAT".equals (mode))
- long deleteStackStarttime = System.currentTimeMillis ();
+ throw new NetworkException(me);
+ }
+ } else { // DEFAULT to ("HEAT".equals (mode))
+ long deleteStackStarttime = System.currentTimeMillis();
- try {
- // The deleteStack function in MsoHeatUtils returns NOTFOUND if the stack was not found or if the stack was deleted.
- // So query first to report back if stack WAS deleted or just NOTOFUND
- StackInfo heatStack = null;
- heatStack = heat.queryStack(cloudSiteId, "CloudOwner", tenantId, networkId);
- if (heatStack != null && heatStack.getStatus() != HeatStatus.NOTFOUND)
- {
- heat.deleteStack (tenantId, "CloudOwner", cloudSiteId, networkId, true);
- networkDeleted.value = true;
- }
- else
- {
- networkDeleted.value = false;
- }
- } catch (MsoException me) {
- me.addContext ("DeleteNetwork");
- logger.error("{} {} Delete Network (heat): {} in {}/{} ", MessageEnum.RA_DELETE_NETWORK_EXC,
- ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me);
- throw new NetworkException (me);
+ try {
+ // The deleteStack function in MsoHeatUtils returns NOTFOUND if the stack was not found or if the stack
+ // was deleted.
+ // So query first to report back if stack WAS deleted or just NOTOFUND
+ StackInfo heatStack = null;
+ heatStack = heat.queryStack(cloudSiteId, "CloudOwner", tenantId, networkId);
+ if (heatStack != null && heatStack.getStatus() != HeatStatus.NOTFOUND) {
+ heat.deleteStack(tenantId, "CloudOwner", cloudSiteId, networkId, true);
+ networkDeleted.value = true;
+ } else {
+ networkDeleted.value = false;
}
+ } catch (MsoException me) {
+ me.addContext("DeleteNetwork");
+ logger.error("{} {} Delete Network (heat): {} in {}/{} ", MessageEnum.RA_DELETE_NETWORK_EXC,
+ ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me);
+ throw new NetworkException(me);
}
+ }
// On success, nothing is returned.
@@ -1368,126 +1086,117 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
}
/**
- * This web service endpoint will rollback a previous Create VNF operation.
- * A rollback object is returned to the client in a successful creation
- * response. The client can pass that object as-is back to the rollbackVnf
- * operation to undo the creation.
+ * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the
+ * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation
+ * to undo the creation.
*
- * The rollback includes removing the VNF and deleting the tenant if the
- * tenant did not exist prior to the VNF creation.
+ * The rollback includes removing the VNF and deleting the tenant if the tenant did not exist prior to the VNF
+ * creation.
*/
@Override
- public void rollbackNetwork (NetworkRollback rollback) throws NetworkException {
+ public void rollbackNetwork(NetworkRollback rollback) throws NetworkException {
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
if (rollback == null) {
- logger
- .error("{} {} rollback is null", MessageEnum.RA_ROLLBACK_NULL, ErrorCode.DataError.getValue());
+ logger.error("{} {} rollback is null", MessageEnum.RA_ROLLBACK_NULL, ErrorCode.DataError.getValue());
return;
}
// Get the elements of the VnfRollback object for easier access
- String cloudSiteId = rollback.getCloudId ();
- String tenantId = rollback.getTenantId ();
- String networkId = rollback.getNetworkStackId ();
- String networkType = rollback.getNetworkType ();
+ String cloudSiteId = rollback.getCloudId();
+ String tenantId = rollback.getTenantId();
+ String networkId = rollback.getNetworkStackId();
+ String networkType = rollback.getNetworkType();
String modelCustomizationUuid = rollback.getModelCustomizationUuid();
logger.debug("*** ROLLBACK Network {} in {}/{}", networkId, cloudSiteId, tenantId);
- // Retrieve the Network Resource definition
- NetworkResource networkResource = null;
- if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) {
- networkResource = networkCustomRepo.findOneByNetworkType(networkType).getNetworkResource();
- } else {
- networkResource = networkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid).getNetworkResource();
- }
- String mode = "";
- if (networkResource != null) {
+ // Retrieve the Network Resource definition
+ NetworkResource networkResource = null;
+ if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) {
+ networkResource = networkCustomRepo.findOneByNetworkType(networkType).getNetworkResource();
+ } else {
+ networkResource =
+ networkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid).getNetworkResource();
+ }
+ String mode = "";
+ if (networkResource != null) {
- logger.debug("Got Network definition from Catalog: {}", networkResource.toString());
+ logger.debug("Got Network definition from Catalog: {}", networkResource.toString());
- mode = networkResource.getOrchestrationMode ();
- }
+ mode = networkResource.getOrchestrationMode();
+ }
- if (rollback.getNetworkCreated ()) {
- // Rolling back a newly created network, so delete it.
- if (NEUTRON_MODE.equals (mode)) {
- // Use MsoNeutronUtils for all NEUTRON commands
- long deleteNetworkStarttime = System.currentTimeMillis ();
- try {
- // The deleteNetwork function in MsoNeutronUtils returns success if the network
- // was not found. So don't bother to query first.
- neutron.deleteNetwork (networkId, tenantId, cloudSiteId);
- } catch (MsoException me) {
- me.addContext ("RollbackNetwork");
- logger.error("{} {} Exception - Rollback Network (neutron): {} in {}/{} ",
- MessageEnum.RA_DELETE_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(),
- networkId, cloudSiteId, tenantId, me);
- throw new NetworkException (me);
- }
- } else { // DEFAULT to if ("HEAT".equals (mode))
- long deleteStackStarttime = System.currentTimeMillis ();
- try {
- // The deleteStack function in MsoHeatUtils returns success if the stack
- // was not found. So don't bother to query first.
- heat.deleteStack (tenantId, "CloudOwner", cloudSiteId, networkId, true);
- } catch (MsoException me) {
- me.addContext ("RollbackNetwork");
- logger.error("{} {} Exception - Rollback Network (heat): {} in {}/{} ",
- MessageEnum.RA_DELETE_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(),
- networkId, cloudSiteId, tenantId, me);
- throw new NetworkException (me);
- }
+ if (rollback.getNetworkCreated()) {
+ // Rolling back a newly created network, so delete it.
+ if (NEUTRON_MODE.equals(mode)) {
+ // Use MsoNeutronUtils for all NEUTRON commands
+ long deleteNetworkStarttime = System.currentTimeMillis();
+ try {
+ // The deleteNetwork function in MsoNeutronUtils returns success if the network
+ // was not found. So don't bother to query first.
+ neutron.deleteNetwork(networkId, tenantId, cloudSiteId);
+ } catch (MsoException me) {
+ me.addContext("RollbackNetwork");
+ logger.error("{} {} Exception - Rollback Network (neutron): {} in {}/{} ",
+ MessageEnum.RA_DELETE_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(), networkId,
+ cloudSiteId, tenantId, me);
+ throw new NetworkException(me);
+ }
+ } else { // DEFAULT to if ("HEAT".equals (mode))
+ long deleteStackStarttime = System.currentTimeMillis();
+ try {
+ // The deleteStack function in MsoHeatUtils returns success if the stack
+ // was not found. So don't bother to query first.
+ heat.deleteStack(tenantId, "CloudOwner", cloudSiteId, networkId, true);
+ } catch (MsoException me) {
+ me.addContext("RollbackNetwork");
+ logger.error("{} {} Exception - Rollback Network (heat): {} in {}/{} ",
+ MessageEnum.RA_DELETE_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(), networkId,
+ cloudSiteId, tenantId, me);
+ throw new NetworkException(me);
}
}
+ }
return;
}
- private String validateNetworkParams (NetworkType neutronNetworkType,
- String networkName,
- String physicalNetwork,
- List <Integer> vlans,
- List <RouteTarget> routeTargets) {
+ private String validateNetworkParams(NetworkType neutronNetworkType, String networkName, String physicalNetwork,
+ List<Integer> vlans, List<RouteTarget> routeTargets) {
String sep = "";
- StringBuilder missing = new StringBuilder ();
+ StringBuilder missing = new StringBuilder();
if (commonUtils.isNullOrEmpty(networkName)) {
- missing.append ("networkName");
+ missing.append("networkName");
sep = ",";
}
if (neutronNetworkType == NetworkType.PROVIDER || neutronNetworkType == NetworkType.MULTI_PROVIDER) {
if (commonUtils.isNullOrEmpty(physicalNetwork)) {
- missing.append (sep).append ("physicalNetworkName");
+ missing.append(sep).append("physicalNetworkName");
sep = ",";
}
- if (vlans == null || vlans.isEmpty ()) {
- missing.append (sep).append (VLANS);
+ if (vlans == null || vlans.isEmpty()) {
+ missing.append(sep).append(VLANS);
}
}
- return missing.toString ();
+ return missing.toString();
}
- private Map <String, Object> populateNetworkParams (NetworkType neutronNetworkType,
- String networkName,
- String physicalNetwork,
- List <Integer> vlans,
- List <RouteTarget> routeTargets,
- String shared,
- String external,
- boolean aic3template) {
+ private Map<String, Object> populateNetworkParams(NetworkType neutronNetworkType, String networkName,
+ String physicalNetwork, List<Integer> vlans, List<RouteTarget> routeTargets, String shared, String external,
+ boolean aic3template) {
// Build the common set of HEAT template parameters
- Map <String, Object> stackParams = new HashMap <> ();
- stackParams.put ("network_name", networkName);
+ Map<String, Object> stackParams = new HashMap<>();
+ stackParams.put("network_name", networkName);
if (neutronNetworkType == NetworkType.PROVIDER) {
// For Provider type
- stackParams.put (PHYSICAL_NETWORK, physicalNetwork);
- stackParams.put ("vlan", vlans.get (0).toString ());
+ stackParams.put(PHYSICAL_NETWORK, physicalNetwork);
+ stackParams.put("vlan", vlans.get(0).toString());
} else if (neutronNetworkType == NetworkType.MULTI_PROVIDER) {
// For Multi-provider, PO supports a custom resource extension of ProviderNet.
// It supports all ProviderNet properties except segmentation_id, and adds a
@@ -1495,16 +1204,16 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
// Note that this does not match the Neutron definition of Multi-Provider network,
// which contains a list of 'segments', each having physical_network, network_type,
// and segmentation_id.
- StringBuilder buf = new StringBuilder ();
+ StringBuilder buf = new StringBuilder();
String sep = "";
for (Integer vlan : vlans) {
- buf.append (sep).append (vlan.toString ());
+ buf.append(sep).append(vlan.toString());
sep = ",";
}
- String csl = buf.toString ();
+ String csl = buf.toString();
- stackParams.put (PHYSICAL_NETWORK, physicalNetwork);
- stackParams.put (VLANS, csl);
+ stackParams.put(PHYSICAL_NETWORK, physicalNetwork);
+ stackParams.put(VLANS, csl);
}
if (routeTargets != null) {
@@ -1513,402 +1222,319 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
String rtExport = "";
String sep = "";
for (RouteTarget rt : routeTargets) {
- boolean rtIsNull = false;
- if (rt != null)
- {
- String routeTarget = rt.getRouteTarget();
- String routeTargetRole = rt.getRouteTargetRole();
- logger.debug("Checking for an actually null route target: {}", rt);
- if (routeTarget == null || routeTarget.equals("") || routeTarget.equalsIgnoreCase("null"))
- rtIsNull = true;
- if (routeTargetRole == null || routeTargetRole.equals("") || routeTargetRole.equalsIgnoreCase("null"))
- rtIsNull = true;
- } else {
- rtIsNull = true;
- }
- if (!rtIsNull) {
- logger.debug("Input RT:{}", rt);
- String role = rt.getRouteTargetRole();
- String rtValue = rt.getRouteTarget();
-
- if ("IMPORT".equalsIgnoreCase(role))
- {
- sep = rtImport.isEmpty() ? "" : ",";
- rtImport = aic3template ? rtImport + sep + "target:" + rtValue : rtImport + sep + rtValue ;
- }
- else if ("EXPORT".equalsIgnoreCase(role))
- {
- sep = rtExport.isEmpty() ? "" : ",";
- rtExport = aic3template ? rtExport + sep + "target:" + rtValue : rtExport + sep + rtValue ;
- }
- else // covers BOTH, empty etc
- {
- sep = rtGlobal.isEmpty() ? "" : ",";
- rtGlobal = aic3template ? rtGlobal + sep + "target:" + rtValue : rtGlobal + sep + rtValue ;
- }
-
- }
+ boolean rtIsNull = false;
+ if (rt != null) {
+ String routeTarget = rt.getRouteTarget();
+ String routeTargetRole = rt.getRouteTargetRole();
+ logger.debug("Checking for an actually null route target: {}", rt);
+ if (routeTarget == null || routeTarget.equals("") || routeTarget.equalsIgnoreCase("null"))
+ rtIsNull = true;
+ if (routeTargetRole == null || routeTargetRole.equals("")
+ || routeTargetRole.equalsIgnoreCase("null"))
+ rtIsNull = true;
+ } else {
+ rtIsNull = true;
+ }
+ if (!rtIsNull) {
+ logger.debug("Input RT:{}", rt);
+ String role = rt.getRouteTargetRole();
+ String rtValue = rt.getRouteTarget();
+
+ if ("IMPORT".equalsIgnoreCase(role)) {
+ sep = rtImport.isEmpty() ? "" : ",";
+ rtImport = aic3template ? rtImport + sep + "target:" + rtValue : rtImport + sep + rtValue;
+ } else if ("EXPORT".equalsIgnoreCase(role)) {
+ sep = rtExport.isEmpty() ? "" : ",";
+ rtExport = aic3template ? rtExport + sep + "target:" + rtValue : rtExport + sep + rtValue;
+ } else // covers BOTH, empty etc
+ {
+ sep = rtGlobal.isEmpty() ? "" : ",";
+ rtGlobal = aic3template ? rtGlobal + sep + "target:" + rtValue : rtGlobal + sep + rtValue;
+ }
+
+ }
}
- if (!rtImport.isEmpty())
- {
- stackParams.put ("route_targets_import", rtImport);
+ if (!rtImport.isEmpty()) {
+ stackParams.put("route_targets_import", rtImport);
}
- if (!rtExport.isEmpty())
- {
- stackParams.put ("route_targets_export", rtExport);
+ if (!rtExport.isEmpty()) {
+ stackParams.put("route_targets_export", rtExport);
}
- if (!rtGlobal.isEmpty())
- {
- stackParams.put ("route_targets", rtGlobal);
+ if (!rtGlobal.isEmpty()) {
+ stackParams.put("route_targets", rtGlobal);
}
}
if (commonUtils.isNullOrEmpty(shared)) {
- stackParams.put ("shared", "False");
+ stackParams.put("shared", "False");
} else {
- stackParams.put ("shared", shared);
+ stackParams.put("shared", shared);
}
if (commonUtils.isNullOrEmpty(external)) {
- stackParams.put ("external", "False");
+ stackParams.put("external", "False");
} else {
- stackParams.put ("external", external);
+ stackParams.put("external", external);
}
return stackParams;
}
- /** policyRef_list structure in stackParams
- [
- {
- "network_policy_refs_data_sequence": {
- "network_policy_refs_data_sequence_major": "1",
- "network_policy_refs_data_sequence_minor": "0"
- }
- },
- {
- "network_policy_refs_data_sequence": {
- "network_policy_refs_data_sequence_major": "2",
- "network_policy_refs_data_sequence_minor": "0"
- }
- }
- ]
- **/
- private void mergePolicyRefs(List <String> pFqdns, Map <String, Object> stackParams) throws MsoException {
- //Resource Property
- List<ContrailPolicyRef> prlist = new ArrayList <> ();
- int index = 1;
- for (String pf : pFqdns) {
- if (!commonUtils.isNullOrEmpty(pf))
- {
- ContrailPolicyRef pr = new ContrailPolicyRef();
- ContrailPolicyRefSeq refSeq = new ContrailPolicyRefSeq(String.valueOf(index), "0");
- pr.setSeq(refSeq);
- index++;
- logger.debug("Contrail PolicyRefs Data:{}", pr);
- prlist.add(pr);
- }
- }
-
- JsonNode node = null;
- try
- {
- ObjectMapper mapper = new ObjectMapper();
- node = mapper.convertValue(prlist, JsonNode.class);
- String jsonString = mapper.writeValueAsString(prlist);
- logger.debug("Json PolicyRefs Data:{}", jsonString);
- }
- catch (Exception e)
- {
- String error = "Error creating JsonNode for policyRefs Data";
- logger.error("{} {} {} ", MessageEnum.RA_MARSHING_ERROR, ErrorCode.BusinessProcesssError.getValue(),
- error, e);
- throw new MsoAdapterException (error);
- }
- //update parameters
- if (pFqdns != null && node != null)
- {
- StringBuilder buf = new StringBuilder ();
- String sep = "";
- for (String pf : pFqdns) {
- if (!commonUtils.isNullOrEmpty(pf))
- {
- buf.append (sep).append (pf);
- sep = ",";
- }
- }
- String csl = buf.toString ();
- stackParams.put ("policy_refs", csl);
- stackParams.put ("policy_refsdata", node);
- }
+ /**
+ * policyRef_list structure in stackParams [ { "network_policy_refs_data_sequence": {
+ * "network_policy_refs_data_sequence_major": "1", "network_policy_refs_data_sequence_minor": "0" } }, {
+ * "network_policy_refs_data_sequence": { "network_policy_refs_data_sequence_major": "2",
+ * "network_policy_refs_data_sequence_minor": "0" } } ]
+ **/
+ private void mergePolicyRefs(List<String> pFqdns, Map<String, Object> stackParams) throws MsoException {
+ // Resource Property
+ List<ContrailPolicyRef> prlist = new ArrayList<>();
+ int index = 1;
+ for (String pf : pFqdns) {
+ if (!commonUtils.isNullOrEmpty(pf)) {
+ ContrailPolicyRef pr = new ContrailPolicyRef();
+ ContrailPolicyRefSeq refSeq = new ContrailPolicyRefSeq(String.valueOf(index), "0");
+ pr.setSeq(refSeq);
+ index++;
+ logger.debug("Contrail PolicyRefs Data:{}", pr);
+ prlist.add(pr);
+ }
+ }
+
+ JsonNode node = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ node = mapper.convertValue(prlist, JsonNode.class);
+ String jsonString = mapper.writeValueAsString(prlist);
+ logger.debug("Json PolicyRefs Data:{}", jsonString);
+ } catch (Exception e) {
+ String error = "Error creating JsonNode for policyRefs Data";
+ logger.error("{} {} {} ", MessageEnum.RA_MARSHING_ERROR, ErrorCode.BusinessProcesssError.getValue(), error,
+ e);
+ throw new MsoAdapterException(error);
+ }
+ // update parameters
+ if (pFqdns != null && node != null) {
+ StringBuilder buf = new StringBuilder();
+ String sep = "";
+ for (String pf : pFqdns) {
+ if (!commonUtils.isNullOrEmpty(pf)) {
+ buf.append(sep).append(pf);
+ sep = ",";
+ }
+ }
+ String csl = buf.toString();
+ stackParams.put("policy_refs", csl);
+ stackParams.put("policy_refsdata", node);
+ }
logger.debug("StackParams updated with policy refs");
- return;
+ return;
}
- private void mergeRouteTableRefs(List <String> rtFqdns, Map <String, Object> stackParams) throws MsoException {
-
- //update parameters
- if (rtFqdns != null)
- {
- StringBuilder buf = new StringBuilder ();
- String sep = "";
- for (String rtf : rtFqdns) {
- if (!commonUtils.isNullOrEmpty(rtf))
- {
- buf.append (sep).append (rtf);
- sep = ",";
- }
- }
- String csl = buf.toString ();
- stackParams.put ("route_table_refs", csl);
- }
+ private void mergeRouteTableRefs(List<String> rtFqdns, Map<String, Object> stackParams) throws MsoException {
+
+ // update parameters
+ if (rtFqdns != null) {
+ StringBuilder buf = new StringBuilder();
+ String sep = "";
+ for (String rtf : rtFqdns) {
+ if (!commonUtils.isNullOrEmpty(rtf)) {
+ buf.append(sep).append(rtf);
+ sep = ",";
+ }
+ }
+ String csl = buf.toString();
+ stackParams.put("route_table_refs", csl);
+ }
logger.debug("StackParams updated with route_table refs");
- return;
+ return;
}
- /*** Subnet Output structure from Juniper
- {
- "ipam_subnets": [
- {
- "subnet": {
- "ip_prefix": "10.100.1.0",
- "ip_prefix_len": 28
- },
- "addr_from_start": null,
- "enable_dhcp": false,
- "default_gateway": "10.100.1.1",
- "dns_nameservers": [],
- "dhcp_option_list": null,
- "subnet_uuid": "10391fbf-6b9c-4160-825d-2d018b7649cf",
- "allocation_pools": [
- {
- "start": "10.100.1.3",
- "end": "10.100.1.5"
- },
- {
- "start": "10.100.1.6",
- "end": "10.100.1.9"
- }
- ],
- "host_routes": null,
- "dns_server_address": "10.100.1.13",
- "subnet_name": "subnet_MsoNW1_692c9032-e1a2-4d64-828c-7b9a4fcc05b0"
- },
- {
- "subnet": {
- "ip_prefix": "10.100.2.16",
- "ip_prefix_len": 28
- },
- "addr_from_start": null,
- "enable_dhcp": true,
- "default_gateway": "10.100.2.17",
- "dns_nameservers": [],
- "dhcp_option_list": null,
- "subnet_uuid": "c7aac5ea-66fe-443a-85f9-9c38a608c0f6",
- "allocation_pools": [
- {
- "start": "10.100.2.18",
- "end": "10.100.2.20"
- }
- ],
- "host_routes": null,
- "dns_server_address": "10.100.2.29",
- "subnet_name": "subnet_MsoNW1_692c9032-e1a2-4d64-828c-7b9a4fcc05b1"
+ /***
+ * Subnet Output structure from Juniper { "ipam_subnets": [ { "subnet": { "ip_prefix": "10.100.1.0",
+ * "ip_prefix_len": 28 }, "addr_from_start": null, "enable_dhcp": false, "default_gateway": "10.100.1.1",
+ * "dns_nameservers": [], "dhcp_option_list": null, "subnet_uuid": "10391fbf-6b9c-4160-825d-2d018b7649cf",
+ * "allocation_pools": [ { "start": "10.100.1.3", "end": "10.100.1.5" }, { "start": "10.100.1.6", "end":
+ * "10.100.1.9" } ], "host_routes": null, "dns_server_address": "10.100.1.13", "subnet_name":
+ * "subnet_MsoNW1_692c9032-e1a2-4d64-828c-7b9a4fcc05b0" }, { "subnet": { "ip_prefix": "10.100.2.16",
+ * "ip_prefix_len": 28 }, "addr_from_start": null, "enable_dhcp": true, "default_gateway": "10.100.2.17",
+ * "dns_nameservers": [], "dhcp_option_list": null, "subnet_uuid": "c7aac5ea-66fe-443a-85f9-9c38a608c0f6",
+ * "allocation_pools": [ { "start": "10.100.2.18", "end": "10.100.2.20" } ], "host_routes": null,
+ * "dns_server_address": "10.100.2.29", "subnet_name": "subnet_MsoNW1_692c9032-e1a2-4d64-828c-7b9a4fcc05b1" } ],
+ * "host_routes": null }
+ ***/
+ private String mergeSubnetsAIC3(String heatTemplate, List<Subnet> subnets, Map<String, Object> stackParams)
+ throws MsoException {
+
+ // Resource Property
+ List<ContrailSubnet> cslist = new ArrayList<>();
+ for (Subnet subnet : subnets) {
+ logger.debug("Input Subnet:{}", subnet.toString());
+ ContrailSubnet cs = new ContrailSubnetMapper(subnet).map();
+ logger.debug("Contrail Subnet:{}", cs.toString());
+ cslist.add(cs);
}
- ],
- "host_routes": null
- }
- ***/
- private String mergeSubnetsAIC3 (String heatTemplate, List <Subnet> subnets, Map <String, Object> stackParams) throws MsoException {
-
- //Resource Property
- List<ContrailSubnet> cslist = new ArrayList <> ();
- for (Subnet subnet : subnets) {
- logger.debug("Input Subnet:{}", subnet.toString());
- ContrailSubnet cs = new ContrailSubnetMapper(subnet).map();
- logger.debug("Contrail Subnet:{}", cs.toString());
- cslist.add(cs);
- }
-
- JsonNode node = null;
- try
- {
- ObjectMapper mapper = new ObjectMapper();
- node = mapper.convertValue(cslist, JsonNode.class);
- String jsonString = mapper.writeValueAsString(cslist);
- logger.debug("Json Subnet List:{}", jsonString);
- }
- catch (Exception e)
- {
- String error = "Error creating JsonNode from input subnets";
- logger.error("{} {} {} ", MessageEnum.RA_MARSHING_ERROR, ErrorCode.DataError.getValue(), error, e);
- throw new MsoAdapterException (error);
- }
- //update parameters
- if (node != null)
- {
- stackParams.put ("subnet_list", node);
- }
- //Outputs - All subnets are in one ipam_subnets structure
- String outputTempl = " subnet:\n" + " description: Openstack subnet identifier\n"
- + " value: { get_attr: [network, network_ipam_refs, 0, attr]}\n";
-
- // append outputs in heatTemplate
- int outputsIdx = heatTemplate.indexOf ("outputs:");
- heatTemplate = insertStr (heatTemplate, outputTempl, outputsIdx + 8);
+
+ JsonNode node = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ node = mapper.convertValue(cslist, JsonNode.class);
+ String jsonString = mapper.writeValueAsString(cslist);
+ logger.debug("Json Subnet List:{}", jsonString);
+ } catch (Exception e) {
+ String error = "Error creating JsonNode from input subnets";
+ logger.error("{} {} {} ", MessageEnum.RA_MARSHING_ERROR, ErrorCode.DataError.getValue(), error, e);
+ throw new MsoAdapterException(error);
+ }
+ // update parameters
+ if (node != null) {
+ stackParams.put("subnet_list", node);
+ }
+ // Outputs - All subnets are in one ipam_subnets structure
+ String outputTempl = " subnet:\n" + " description: Openstack subnet identifier\n"
+ + " value: { get_attr: [network, network_ipam_refs, 0, attr]}\n";
+
+ // append outputs in heatTemplate
+ int outputsIdx = heatTemplate.indexOf("outputs:");
+ heatTemplate = insertStr(heatTemplate, outputTempl, outputsIdx + 8);
logger.debug("Template updated with all AIC3.0 subnets:{}", heatTemplate);
- return heatTemplate;
+ return heatTemplate;
}
- private String mergeSubnets (String heatTemplate, List <Subnet> subnets) throws MsoException {
-
- String resourceTempl = " subnet_%subnetId%:\n" + " type: OS::Neutron::Subnet\n"
- + " properties:\n"
- + " name: %name%\n"
- + " network_id: { get_resource: network }\n"
- + " cidr: %cidr%\n";
-
- /* make these optional
- + " ip_version: %ipversion%\n"
- + " enable_dhcp: %enabledhcp%\n"
- + " gateway_ip: %gatewayip%\n"
- + " allocation_pools:\n"
- + " - start: %poolstart%\n"
- + " end: %poolend%\n";
-
- */
-
- String outputTempl = " subnet_id_%subnetId%:\n" + " description: Openstack subnet identifier\n"
- + " value: {get_resource: subnet_%subnetId%}\n";
-
- String curR;
- String curO;
- StringBuilder resourcesBuf = new StringBuilder ();
- StringBuilder outputsBuf = new StringBuilder ();
- for (Subnet subnet : subnets) {
-
- // build template for each subnet
- curR = resourceTempl;
- if (subnet.getSubnetId () != null) {
- curR = curR.replace ("%subnetId%", subnet.getSubnetId ());
- } else {
- String error = "Missing Required AAI SubnetId for subnet in HEAT Template";
- logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error);
- throw new MsoAdapterException (error);
- }
-
- if (subnet.getSubnetName () != null) {
- curR = curR.replace ("%name%", subnet.getSubnetName ());
- } else {
- curR = curR.replace ("%name%", subnet.getSubnetId ());
- }
-
- if (subnet.getCidr () != null) {
- curR = curR.replace ("%cidr%", subnet.getCidr ());
- } else {
- String error = "Missing Required cidr for subnet in HEAT Template";
- logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error);
- throw new MsoAdapterException (error);
- }
-
- if (subnet.getIpVersion () != null) {
- curR = curR + " ip_version: " + subnet.getIpVersion () + "\n";
- }
- if (subnet.getEnableDHCP () != null) {
- curR = curR + " enable_dhcp: " + Boolean.toString (subnet.getEnableDHCP ()) + "\n";
- }
- if (subnet.getGatewayIp () != null && !subnet.getGatewayIp ().isEmpty() ) {
- curR = curR + " gateway_ip: " + subnet.getGatewayIp () + "\n";
- }
-
- if (subnet.getAllocationPools() != null) {
- curR = curR + " allocation_pools:\n";
- for (Pool pool : subnet.getAllocationPools())
- {
- if (!commonUtils.isNullOrEmpty(pool.getStart()) && !commonUtils.isNullOrEmpty(pool.getEnd()))
- {
- curR = curR + " - start: " + pool.getStart () + "\n";
- curR = curR + " end: " + pool.getEnd () + "\n";
- }
- }
- }
-
- resourcesBuf.append (curR);
-
- curO = outputTempl;
- curO = curO.replace ("%subnetId%", subnet.getSubnetId ());
-
- outputsBuf.append (curO);
-
- }
- // append resources and outputs in heatTemplate
+ private String mergeSubnets(String heatTemplate, List<Subnet> subnets) throws MsoException {
+
+ String resourceTempl = " subnet_%subnetId%:\n" + " type: OS::Neutron::Subnet\n" + " properties:\n"
+ + " name: %name%\n" + " network_id: { get_resource: network }\n" + " cidr: %cidr%\n";
+
+ /*
+ * make these optional + " ip_version: %ipversion%\n" + " enable_dhcp: %enabledhcp%\n" +
+ * " gateway_ip: %gatewayip%\n" + " allocation_pools:\n" + " - start: %poolstart%\n" +
+ * " end: %poolend%\n";
+ *
+ */
+
+ String outputTempl = " subnet_id_%subnetId%:\n" + " description: Openstack subnet identifier\n"
+ + " value: {get_resource: subnet_%subnetId%}\n";
+
+ String curR;
+ String curO;
+ StringBuilder resourcesBuf = new StringBuilder();
+ StringBuilder outputsBuf = new StringBuilder();
+ for (Subnet subnet : subnets) {
+
+ // build template for each subnet
+ curR = resourceTempl;
+ if (subnet.getSubnetId() != null) {
+ curR = curR.replace("%subnetId%", subnet.getSubnetId());
+ } else {
+ String error = "Missing Required AAI SubnetId for subnet in HEAT Template";
+ logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error);
+ throw new MsoAdapterException(error);
+ }
+
+ if (subnet.getSubnetName() != null) {
+ curR = curR.replace("%name%", subnet.getSubnetName());
+ } else {
+ curR = curR.replace("%name%", subnet.getSubnetId());
+ }
+
+ if (subnet.getCidr() != null) {
+ curR = curR.replace("%cidr%", subnet.getCidr());
+ } else {
+ String error = "Missing Required cidr for subnet in HEAT Template";
+ logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error);
+ throw new MsoAdapterException(error);
+ }
+
+ if (subnet.getIpVersion() != null) {
+ curR = curR + " ip_version: " + subnet.getIpVersion() + "\n";
+ }
+ if (subnet.getEnableDHCP() != null) {
+ curR = curR + " enable_dhcp: " + Boolean.toString(subnet.getEnableDHCP()) + "\n";
+ }
+ if (subnet.getGatewayIp() != null && !subnet.getGatewayIp().isEmpty()) {
+ curR = curR + " gateway_ip: " + subnet.getGatewayIp() + "\n";
+ }
+
+ if (subnet.getAllocationPools() != null) {
+ curR = curR + " allocation_pools:\n";
+ for (Pool pool : subnet.getAllocationPools()) {
+ if (!commonUtils.isNullOrEmpty(pool.getStart()) && !commonUtils.isNullOrEmpty(pool.getEnd())) {
+ curR = curR + " - start: " + pool.getStart() + "\n";
+ curR = curR + " end: " + pool.getEnd() + "\n";
+ }
+ }
+ }
+
+ resourcesBuf.append(curR);
+
+ curO = outputTempl;
+ curO = curO.replace("%subnetId%", subnet.getSubnetId());
+
+ outputsBuf.append(curO);
+
+ }
+ // append resources and outputs in heatTemplate
logger.debug("Tempate initial:{}", heatTemplate);
- int outputsIdx = heatTemplate.indexOf ("outputs:");
- heatTemplate = insertStr (heatTemplate, outputsBuf.toString (), outputsIdx + 8);
- int resourcesIdx = heatTemplate.indexOf ("resources:");
- heatTemplate = insertStr (heatTemplate, resourcesBuf.toString (), resourcesIdx + 10);
+ int outputsIdx = heatTemplate.indexOf("outputs:");
+ heatTemplate = insertStr(heatTemplate, outputsBuf.toString(), outputsIdx + 8);
+ int resourcesIdx = heatTemplate.indexOf("resources:");
+ heatTemplate = insertStr(heatTemplate, resourcesBuf.toString(), resourcesIdx + 10);
logger.debug("Template updated with all subnets:{}", heatTemplate);
- return heatTemplate;
+ return heatTemplate;
}
- private Map <String, String> getSubnetUUId(String key, Map <String, Object> outputs, List <Subnet> subnets) {
-
- Map <String, String> sMap = new HashMap <> ();
-
- try{
- Object obj = outputs.get(key);
- ObjectMapper mapper = new ObjectMapper();
- String jStr = mapper.writeValueAsString(obj);
- logger.debug("Subnet_Ipam Output JSON String:{} {}", obj.getClass(), jStr);
-
- JsonNode rootNode = mapper.readTree(jStr);
- for (JsonNode sNode : rootNode.path("ipam_subnets"))
- {
- logger.debug("Output Subnet Node {}", sNode.toString());
- String name = sNode.path("subnet_name").textValue();
- String uuid = sNode.path("subnet_uuid").textValue();
- String aaiId = name; // default
- // try to find aaiId for name in input subnetList
- if (subnets != null)
- {
- for (Subnet subnet : subnets)
- {
- if ( subnet != null && !commonUtils.isNullOrEmpty(subnet.getSubnetName()))
- {
- if (subnet.getSubnetName().equals(name))
- {
- aaiId = subnet.getSubnetId();
- break;
- }
- }
- }
- }
- sMap.put(aaiId, uuid); //bpmn needs aaid to uuid map
- }
- }
- catch (Exception e)
- {
- logger.error("{} {} Exception getting subnet-uuids ", MessageEnum.RA_MARSHING_ERROR,
- ErrorCode.DataError.getValue(), e);
- }
+ private Map<String, String> getSubnetUUId(String key, Map<String, Object> outputs, List<Subnet> subnets) {
+
+ Map<String, String> sMap = new HashMap<>();
+
+ try {
+ Object obj = outputs.get(key);
+ ObjectMapper mapper = new ObjectMapper();
+ String jStr = mapper.writeValueAsString(obj);
+ logger.debug("Subnet_Ipam Output JSON String:{} {}", obj.getClass(), jStr);
+
+ JsonNode rootNode = mapper.readTree(jStr);
+ for (JsonNode sNode : rootNode.path("ipam_subnets")) {
+ logger.debug("Output Subnet Node {}", sNode.toString());
+ String name = sNode.path("subnet_name").textValue();
+ String uuid = sNode.path("subnet_uuid").textValue();
+ String aaiId = name; // default
+ // try to find aaiId for name in input subnetList
+ if (subnets != null) {
+ for (Subnet subnet : subnets) {
+ if (subnet != null && !commonUtils.isNullOrEmpty(subnet.getSubnetName())) {
+ if (subnet.getSubnetName().equals(name)) {
+ aaiId = subnet.getSubnetId();
+ break;
+ }
+ }
+ }
+ }
+ sMap.put(aaiId, uuid); // bpmn needs aaid to uuid map
+ }
+ } catch (Exception e) {
+ logger.error("{} {} Exception getting subnet-uuids ", MessageEnum.RA_MARSHING_ERROR,
+ ErrorCode.DataError.getValue(), e);
+ }
logger.debug("Return sMap {}", sMap.toString());
- return sMap;
+ return sMap;
}
- private static String insertStr (String template, String snippet, int index) {
+ private static String insertStr(String template, String snippet, int index) {
String updatedTemplate;
logger.debug("Index:{} Snippet:{}", index, snippet);
- String templateBeg = template.substring (0, index);
- String templateEnd = template.substring (index);
+ String templateBeg = template.substring(0, index);
+ String templateEnd = template.substring(index);
updatedTemplate = templateBeg + "\n" + snippet + templateEnd;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java
index 4a6d591977..b44704d1cf 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java
@@ -85,652 +85,552 @@ import org.springframework.transaction.annotation.Transactional;
public class NetworkAdapterRest {
private static final Logger logger = LoggerFactory.getLogger(NetworkAdapterRest.class);
- private static final String TESTING_KEYWORD = "___TESTING___";
- private String EXCEPTION = "Exception:";
-
- @Autowired
- private MsoNetworkAdapterImpl adapter;
-
- @Autowired
- private Provider<BpelRestClient> bpelRestClientProvider;
-
-
- @POST
- @Path("")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "CreateNetwork",
- response = Response.class,
- notes = "Creates a new network, CreateNetworkRquest JSON is required")
- @ApiResponses({
- @ApiResponse(code = 200, message = "network has been successfully created"),
- @ApiResponse(code = 202, message = "create network request has been accepted (async only)"),
- @ApiResponse(code = 500, message = "create network failed, examine entity object for details") })
- public Response createNetwork(
- @ApiParam(value = "details of network being created", required = true)
- CreateNetworkRequest req) {
- logger.debug("createNetwork enter: {}", req.toJsonString());
- CreateNetworkTask task = new CreateNetworkTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} Exception while create network ", MessageEnum.RA_CREATE_NETWORK_EXC,
- ErrorCode.BusinessProcesssError.getValue(), e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("createNetwork exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class CreateNetworkTask implements Runnable {
- private final CreateNetworkRequest req;
- private CreateNetworkResponse response = null;
- private CreateNetworkError eresp = null;
- private boolean sendxml;
-
- public CreateNetworkTask(CreateNetworkRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<CreateNetworkResponse>(response) {}
- : new GenericEntity<CreateNetworkError>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- logger.debug("CreateNetworkTask start");
- try {
- // Synchronous Web Service Outputs
- Holder<String> networkId = new Holder<>();
- Holder<String> neutronNetworkId = new Holder<>();
- Holder<String> networkFqdn = new Holder<>();
- Holder<Map<String, String>> subnetIdMap = new Holder<>();
- Holder<NetworkRollback> rollback = new Holder<>();
-
- HashMap<String, String> params = (HashMap<String, String>) req.getNetworkParams();
- if (params == null) {
- params = new HashMap<String,String>();
- }
- String shared = null;
- String external = null;
-
- String cloudsite = req.getCloudSiteId();
- if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) {
- String tenant = req.getTenantId();
- if (tenant != null && tenant.equals(TESTING_KEYWORD)) {
- throw new NetworkException("testing.");
- }
- networkId.value = "479D3D8B-6360-47BC-AB75-21CC91981484";
- neutronNetworkId.value = "55e55884-28fa-11e6-8971-0017f20fe1b8";
- networkFqdn.value = "086f70b6-28fb-11e6-8260-0017f20fe1b8";
- subnetIdMap.value = testMap();
- rollback.value = new NetworkRollback();
- } else if (req.isContrailRequest()) {
- ContrailNetwork ctn = req.getContrailNetwork();
- if (ctn == null) {
- ctn = new ContrailNetwork();
- req.setContrailNetwork(ctn);
- }
- if (params.containsKey("shared")) {
- shared = params.get("shared");
- } else {
- if (ctn.getShared() != null) {
- shared = ctn.getShared();
- }
- }
- if (params.containsKey("external")) {
- external = params.get("external");
- } else {
- if (ctn.getExternal() != null) {
- external = ctn.getExternal();
- }
- }
- adapter.createNetworkContrail(
- req.getCloudSiteId(),
- req.getTenantId(),
- req.getNetworkType(),
- req.getModelCustomizationUuid(),
- req.getNetworkName(),
- req.getContrailNetwork().getRouteTargets(),
- shared,
- external,
- req.getFailIfExists(),
- req.getBackout(),
- req.getSubnets(),
- params,
- req.getContrailNetwork().getPolicyFqdns(),
- req.getContrailNetwork().getRouteTableFqdns(),
- req.getMsoRequest(),
- networkId,
- neutronNetworkId,
- networkFqdn,
- subnetIdMap,
- rollback);
- } else {
- ProviderVlanNetwork pvn = req.getProviderVlanNetwork();
- if (pvn == null) {
- pvn = new ProviderVlanNetwork();
- req.setProviderVlanNetwork(pvn);
- }
- if (params.containsKey("shared"))
- shared = params.get("shared");
- if (params.containsKey("external"))
- external = params.get("external");
- adapter.createNetwork(
- req.getCloudSiteId(),
- req.getTenantId(),
- req.getNetworkType(),
- req.getModelCustomizationUuid(),
- req.getNetworkName(),
- req.getProviderVlanNetwork().getPhysicalNetworkName(),
- req.getProviderVlanNetwork().getVlans(),
- shared,
- external,
- req.getFailIfExists(),
- req.getBackout(),
- req.getSubnets(),
- params,
- req.getMsoRequest(),
- networkId,
- neutronNetworkId,
- subnetIdMap,
- rollback);
- }
- response = new CreateNetworkResponse(
- req.getNetworkId(),
- neutronNetworkId.value,
- rollback.value.getNetworkStackId(),
- networkFqdn.value,
- rollback.value.getNetworkCreated(),
- subnetIdMap.value,
- rollback.value,
- req.getMessageId());
- } catch (NetworkException e) {
- logger.debug(EXCEPTION, e);
- eresp = new CreateNetworkError(
- e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("CreateNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse());
- }
- }
-
- @DELETE
- @Path("{aaiNetworkId}")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "DeleteNetwork",
- response = Response.class,
- notes = "Deletes an existing network, aaiNetworkId and DeleteNetworkRequest JSON are required")
- @ApiResponses({
- @ApiResponse(code = 200, message = "network has been successfully deleted"),
- @ApiResponse(code = 202, message = "request to delete network has been accepted (async only)"),
- @ApiResponse(code = 500, message = "delete network failed, examine entity object for details") })
- public Response deleteNetwork(
- @ApiParam(value = "aaiNetworkId to be deleted ", required = true)
- @PathParam("aaiNetworkId") String aaiNetworkId,
- @ApiParam(value = "details of network being deleted", required = true)
- DeleteNetworkRequest req)
- {
- logger.debug("deleteNetwork enter: {}", req.toJsonString());
- if (aaiNetworkId == null || !aaiNetworkId.equals(req.getNetworkId())) {
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity("A&AI NetworkId in URL ("+aaiNetworkId+") does not match content ("+req.getNetworkId()+")")
- .build();
- }
- DeleteNetworkTask task = new DeleteNetworkTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} Exception while delete network ", MessageEnum.RA_DELETE_NETWORK_EXC,
- ErrorCode.BusinessProcesssError.getValue(), e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("deleteNetwork exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class DeleteNetworkTask implements Runnable {
- private final DeleteNetworkRequest req;
- private DeleteNetworkResponse response = null;
- private DeleteNetworkError eresp = null;
- private boolean sendxml;
-
- public DeleteNetworkTask(DeleteNetworkRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<DeleteNetworkResponse>(response) {}
- : new GenericEntity<DeleteNetworkError>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- logger.debug("DeleteNetworkTask start");
- try {
- Holder<Boolean> networkDeleted = new Holder<>();
- if (req.getCloudSiteId().equals(TESTING_KEYWORD)) {
- networkDeleted.value = true;
- } else {
- adapter.deleteNetwork(
- req.getCloudSiteId(),
- req.getTenantId(),
- req.getNetworkType(),
- req.getModelCustomizationUuid(),
- req.getNetworkStackId(),
- req.getMsoRequest(),
- networkDeleted);
- }
- response = new DeleteNetworkResponse(req.getNetworkId(), networkDeleted.value, req.getMessageId());
- } catch (NetworkException e) {
- logger.debug(EXCEPTION, e);
- eresp = new DeleteNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("DeleteNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse());
- }
- }
-
- @GET
- @Path("{aaiNetworkId}")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "QueryNetwork",
- response = Response.class,
- notes = "Queries an existing network")
- @ApiResponses({
- @ApiResponse(code = 200, message = "Query network successful"),
- @ApiResponse(code = 500, message = "Query network failed, examine entity object for details") })
- public Response queryNetwork(
- @ApiParam(value = "cloudSiteId", required = false)
- @QueryParam("cloudSiteId") String cloudSiteId,
- @ApiParam(value = "tenantId", required = false)
- @QueryParam("tenantId") String tenantId,
- @ApiParam(value = "networkStackId", required = false)
- @QueryParam("networkStackId") String networkStackId,
- @ApiParam(value = "skipAAI", required = false)
- @QueryParam("skipAAI") String skipAAI,
- @ApiParam(value = "msoRequest.requestId", required = false)
- @QueryParam("msoRequest.requestId") String requestId,
- @ApiParam(value = "msoRequest.serviceInstanceId", required = false)
- @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId,
- @ApiParam(value = "aaiNetworkId", required = false)
- @PathParam("aaiNetworkId") String aaiNetworkId)
- {
- //This request responds synchronously only
- logger.debug("Query network enter:{}" + aaiNetworkId);
- MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId);
-
- try {
- int respStatus = HttpStatus.SC_OK;
- QueryNetworkResponse resp = new QueryNetworkResponse(networkStackId, null, networkStackId, null, null);
- Holder<Boolean> networkExists = new Holder<>();
+ private static final String TESTING_KEYWORD = "___TESTING___";
+ private String EXCEPTION = "Exception:";
+
+ @Autowired
+ private MsoNetworkAdapterImpl adapter;
+
+ @Autowired
+ private Provider<BpelRestClient> bpelRestClientProvider;
+
+
+ @POST
+ @Path("")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "CreateNetwork", response = Response.class,
+ notes = "Creates a new network, CreateNetworkRquest JSON is required")
+ @ApiResponses({@ApiResponse(code = 200, message = "network has been successfully created"),
+ @ApiResponse(code = 202, message = "create network request has been accepted (async only)"),
+ @ApiResponse(code = 500, message = "create network failed, examine entity object for details")})
+ public Response createNetwork(
+ @ApiParam(value = "details of network being created", required = true) CreateNetworkRequest req) {
+ logger.debug("createNetwork enter: {}", req.toJsonString());
+ CreateNetworkTask task = new CreateNetworkTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} Exception while create network ", MessageEnum.RA_CREATE_NETWORK_EXC,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("createNetwork exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class CreateNetworkTask implements Runnable {
+ private final CreateNetworkRequest req;
+ private CreateNetworkResponse response = null;
+ private CreateNetworkError eresp = null;
+ private boolean sendxml;
+
+ public CreateNetworkTask(CreateNetworkRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<CreateNetworkResponse>(response) {}
+ : new GenericEntity<CreateNetworkError>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("CreateNetworkTask start");
+ try {
+ // Synchronous Web Service Outputs
+ Holder<String> networkId = new Holder<>();
+ Holder<String> neutronNetworkId = new Holder<>();
+ Holder<String> networkFqdn = new Holder<>();
+ Holder<Map<String, String>> subnetIdMap = new Holder<>();
+ Holder<NetworkRollback> rollback = new Holder<>();
+
+ HashMap<String, String> params = (HashMap<String, String>) req.getNetworkParams();
+ if (params == null) {
+ params = new HashMap<String, String>();
+ }
+ String shared = null;
+ String external = null;
+
+ String cloudsite = req.getCloudSiteId();
+ if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) {
+ String tenant = req.getTenantId();
+ if (tenant != null && tenant.equals(TESTING_KEYWORD)) {
+ throw new NetworkException("testing.");
+ }
+ networkId.value = "479D3D8B-6360-47BC-AB75-21CC91981484";
+ neutronNetworkId.value = "55e55884-28fa-11e6-8971-0017f20fe1b8";
+ networkFqdn.value = "086f70b6-28fb-11e6-8260-0017f20fe1b8";
+ subnetIdMap.value = testMap();
+ rollback.value = new NetworkRollback();
+ } else if (req.isContrailRequest()) {
+ ContrailNetwork ctn = req.getContrailNetwork();
+ if (ctn == null) {
+ ctn = new ContrailNetwork();
+ req.setContrailNetwork(ctn);
+ }
+ if (params.containsKey("shared")) {
+ shared = params.get("shared");
+ } else {
+ if (ctn.getShared() != null) {
+ shared = ctn.getShared();
+ }
+ }
+ if (params.containsKey("external")) {
+ external = params.get("external");
+ } else {
+ if (ctn.getExternal() != null) {
+ external = ctn.getExternal();
+ }
+ }
+ adapter.createNetworkContrail(req.getCloudSiteId(), req.getTenantId(), req.getNetworkType(),
+ req.getModelCustomizationUuid(), req.getNetworkName(),
+ req.getContrailNetwork().getRouteTargets(), shared, external, req.getFailIfExists(),
+ req.getBackout(), req.getSubnets(), params, req.getContrailNetwork().getPolicyFqdns(),
+ req.getContrailNetwork().getRouteTableFqdns(), req.getMsoRequest(), networkId,
+ neutronNetworkId, networkFqdn, subnetIdMap, rollback);
+ } else {
+ ProviderVlanNetwork pvn = req.getProviderVlanNetwork();
+ if (pvn == null) {
+ pvn = new ProviderVlanNetwork();
+ req.setProviderVlanNetwork(pvn);
+ }
+ if (params.containsKey("shared"))
+ shared = params.get("shared");
+ if (params.containsKey("external"))
+ external = params.get("external");
+ adapter.createNetwork(req.getCloudSiteId(), req.getTenantId(), req.getNetworkType(),
+ req.getModelCustomizationUuid(), req.getNetworkName(),
+ req.getProviderVlanNetwork().getPhysicalNetworkName(),
+ req.getProviderVlanNetwork().getVlans(), shared, external, req.getFailIfExists(),
+ req.getBackout(), req.getSubnets(), params, req.getMsoRequest(), networkId,
+ neutronNetworkId, subnetIdMap, rollback);
+ }
+ response = new CreateNetworkResponse(req.getNetworkId(), neutronNetworkId.value,
+ rollback.value.getNetworkStackId(), networkFqdn.value, rollback.value.getNetworkCreated(),
+ subnetIdMap.value, rollback.value, req.getMessageId());
+ } catch (NetworkException e) {
+ logger.debug(EXCEPTION, e);
+ eresp = new CreateNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("CreateNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse());
+ }
+ }
+
+ @DELETE
+ @Path("{aaiNetworkId}")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "DeleteNetwork", response = Response.class,
+ notes = "Deletes an existing network, aaiNetworkId and DeleteNetworkRequest JSON are required")
+ @ApiResponses({@ApiResponse(code = 200, message = "network has been successfully deleted"),
+ @ApiResponse(code = 202, message = "request to delete network has been accepted (async only)"),
+ @ApiResponse(code = 500, message = "delete network failed, examine entity object for details")})
+ public Response deleteNetwork(
+ @ApiParam(value = "aaiNetworkId to be deleted ",
+ required = true) @PathParam("aaiNetworkId") String aaiNetworkId,
+ @ApiParam(value = "details of network being deleted", required = true) DeleteNetworkRequest req) {
+ logger.debug("deleteNetwork enter: {}", req.toJsonString());
+ if (aaiNetworkId == null || !aaiNetworkId.equals(req.getNetworkId())) {
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity(
+ "A&AI NetworkId in URL (" + aaiNetworkId + ") does not match content (" + req.getNetworkId() + ")")
+ .build();
+ }
+ DeleteNetworkTask task = new DeleteNetworkTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} Exception while delete network ", MessageEnum.RA_DELETE_NETWORK_EXC,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("deleteNetwork exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class DeleteNetworkTask implements Runnable {
+ private final DeleteNetworkRequest req;
+ private DeleteNetworkResponse response = null;
+ private DeleteNetworkError eresp = null;
+ private boolean sendxml;
+
+ public DeleteNetworkTask(DeleteNetworkRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<DeleteNetworkResponse>(response) {}
+ : new GenericEntity<DeleteNetworkError>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("DeleteNetworkTask start");
+ try {
+ Holder<Boolean> networkDeleted = new Holder<>();
+ if (req.getCloudSiteId().equals(TESTING_KEYWORD)) {
+ networkDeleted.value = true;
+ } else {
+ adapter.deleteNetwork(req.getCloudSiteId(), req.getTenantId(), req.getNetworkType(),
+ req.getModelCustomizationUuid(), req.getNetworkStackId(), req.getMsoRequest(),
+ networkDeleted);
+ }
+ response = new DeleteNetworkResponse(req.getNetworkId(), networkDeleted.value, req.getMessageId());
+ } catch (NetworkException e) {
+ logger.debug(EXCEPTION, e);
+ eresp = new DeleteNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("DeleteNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse());
+ }
+ }
+
+ @GET
+ @Path("{aaiNetworkId}")
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "QueryNetwork", response = Response.class, notes = "Queries an existing network")
+ @ApiResponses({@ApiResponse(code = 200, message = "Query network successful"),
+ @ApiResponse(code = 500, message = "Query network failed, examine entity object for details")})
+ public Response queryNetwork(
+ @ApiParam(value = "cloudSiteId", required = false) @QueryParam("cloudSiteId") String cloudSiteId,
+ @ApiParam(value = "tenantId", required = false) @QueryParam("tenantId") String tenantId,
+ @ApiParam(value = "networkStackId", required = false) @QueryParam("networkStackId") String networkStackId,
+ @ApiParam(value = "skipAAI", required = false) @QueryParam("skipAAI") String skipAAI,
+ @ApiParam(value = "msoRequest.requestId",
+ required = false) @QueryParam("msoRequest.requestId") String requestId,
+ @ApiParam(value = "msoRequest.serviceInstanceId",
+ required = false) @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId,
+ @ApiParam(value = "aaiNetworkId", required = false) @PathParam("aaiNetworkId") String aaiNetworkId) {
+ // This request responds synchronously only
+ logger.debug("Query network enter:{}" + aaiNetworkId);
+ MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId);
+
+ try {
+ int respStatus = HttpStatus.SC_OK;
+ QueryNetworkResponse resp = new QueryNetworkResponse(networkStackId, null, networkStackId, null, null);
+ Holder<Boolean> networkExists = new Holder<>();
Holder<String> networkId = new Holder<>();
Holder<String> neutronNetworkId = new Holder<>();
Holder<NetworkStatus> status = new Holder<>();
Holder<List<RouteTarget>> routeTargets = new Holder<>();
Holder<Map<String, String>> subnetIdMap = new Holder<>();
- adapter.queryNetworkContrail(cloudSiteId, tenantId, aaiNetworkId, msoRequest,
- networkExists, networkId, neutronNetworkId, status, routeTargets, subnetIdMap);
-
- if (!networkExists.value) {
- logger.debug("network not found");
- respStatus = HttpStatus.SC_NOT_FOUND;
- } else {
- logger.debug("network found {}, status={}", networkId.value, status.value);
- resp.setNetworkExists(networkExists.value);
- resp.setNetworkId(networkId.value);
- resp.setNeutronNetworkId(neutronNetworkId.value);
- resp.setNetworkStatus(status.value);
- resp.setRouteTargets(routeTargets.value);
- resp.setSubnetIdMap(subnetIdMap.value);
- }
- logger.debug("Query network exit");
- return Response
- .status(respStatus)
- .entity(new GenericEntity<QueryNetworkResponse>(resp) {})
- .build();
- } catch (NetworkException e) {
- logger.error("{} {} Exception when query VNF ", MessageEnum.RA_QUERY_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
- QueryNetworkError err = new QueryNetworkError();
- err.setMessage(e.getMessage());
- err.setCategory(MsoExceptionCategory.INTERNAL);
- return Response
- .status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity(new GenericEntity<QueryNetworkError>(err) {})
- .build();
- }
- }
-
- @DELETE
- @Path("{aaiNetworkId}/rollback")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "RollbackNetwork",
- response = Response.class,
- notes = "Rollback an existing network")
- @ApiResponses({
- @ApiResponse(code = 200, message = "Rollback network successful"),
- @ApiResponse(code = 202, message = "Rollback network request has been accepted (async only)"),
- @ApiResponse(code = 500, message = "Rollback network failed, examine entity object for details") })
- public Response rollbackNetwork(
- @ApiParam(value = "RollbackNetworkRequest in JSON format", required = true)
- RollbackNetworkRequest req)
- {
- logger.debug("rollbackNetwork enter: {}", req.toJsonString());
- RollbackNetworkTask task = new RollbackNetworkTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} Exception in rollbackNetwork ", MessageEnum.RA_ROLLBACK_NULL,
- ErrorCode.BusinessProcesssError.getValue(), e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("rollbackNetwork exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class RollbackNetworkTask implements Runnable {
- private final RollbackNetworkRequest req;
- private RollbackNetworkResponse response = null;
- private RollbackNetworkError eresp = null;
- private boolean sendxml;
-
- public RollbackNetworkTask(RollbackNetworkRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<RollbackNetworkResponse>(response) {}
- : new GenericEntity<RollbackNetworkError>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- logger.debug("RollbackNetworkTask start");
- try {
- NetworkRollback nwr = req.getNetworkRollback();
- adapter.rollbackNetwork(nwr);
- response = new RollbackNetworkResponse(true, req.getMessageId());
- } catch (NetworkException e) {
- logger.debug(EXCEPTION, e);
- eresp = new RollbackNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("RollbackNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse());
- }
- }
-
- @PUT
- @Path("{aaiNetworkId}")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "UpdateNetwork",
- response = Response.class,
- notes = "Update an existing network")
- @ApiResponses({
- @ApiResponse(code = 200, message = "Update network successful"),
- @ApiResponse(code = 202, message = "Update network request has been accepted (async only)"),
- @ApiResponse(code = 500, message = "Update network failed, examine entity object for details") })
- public Response updateNetwork(
- @ApiParam(value = "aaiNetworkId", required = true)
- @PathParam("aaiNetworkId") String aaiNetworkId,
- @ApiParam(value = "UpdateNetworkRequest in JSON format", required = true)
- UpdateNetworkRequest req)
- {
- logger.debug("updateNetwork enter: {}", req.toJsonString());
- if (aaiNetworkId == null || !aaiNetworkId.equals(req.getNetworkId())) {
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity("A&AI NetworkId in URL ("+aaiNetworkId+") does not match content ("+req.getNetworkId()+")")
- .build();
- }
- UpdateNetworkTask task = new UpdateNetworkTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} Exception in updateNetwork ", MessageEnum.RA_UPDATE_NETWORK_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("updateNetwork exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class UpdateNetworkTask implements Runnable {
- private final UpdateNetworkRequest req;
- private UpdateNetworkResponse response = null;
- private UpdateNetworkError eresp = null;
- private boolean sendxml;
-
- public UpdateNetworkTask(UpdateNetworkRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<UpdateNetworkResponse>(response) {}
- : new GenericEntity<UpdateNetworkError>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- logger.debug("UpdateNetworkTask start");
- try {
- Holder<Map<String, String>> subnetIdMap = new Holder<>();
- Holder<NetworkRollback> rollback = new Holder<> ();
- HashMap<String, String> params = (HashMap<String, String>) req.getNetworkParams();
- if (params == null) {
- params = new HashMap<String,String>();
- }
- String shared = null;
- String external = null;
-
- if (req.getCloudSiteId().equals(TESTING_KEYWORD)) {
- subnetIdMap.value = testMap();
- NetworkRollback rb = new NetworkRollback ();
- rb.setCloudId(req.getCloudSiteId());
- rb.setTenantId(req.getTenantId());
- rb.setMsoRequest(req.getMsoRequest());
- rollback.value = rb;
- } else if (req.isContrailRequest()) {
- ContrailNetwork ctn = req.getContrailNetwork();
- if (ctn == null) {
- ctn = new ContrailNetwork();
- req.setContrailNetwork(ctn);
- }
- if (params.containsKey("shared")) {
- shared = params.get("shared");
- } else {
- if (ctn.getShared() != null) {
- shared = ctn.getShared();
- }
- }
- if (params.containsKey("external")) {
- external = params.get("external");
- } else {
- if (ctn.getExternal() != null) {
- external = ctn.getExternal();
- }
- }
- adapter.updateNetworkContrail(
- req.getCloudSiteId(),
- req.getTenantId(),
- req.getNetworkType(),
- req.getModelCustomizationUuid(),
- req.getNetworkStackId(),
- req.getNetworkName(),
- req.getContrailNetwork().getRouteTargets(),
- shared,
- external,
- req.getSubnets(),
- params,
- req.getContrailNetwork().getPolicyFqdns(),
- req.getContrailNetwork().getRouteTableFqdns(),
- req.getMsoRequest(),
- subnetIdMap,
- rollback);
- } else {
- ProviderVlanNetwork pvn = req.getProviderVlanNetwork();
- if (pvn == null) {
- pvn = new ProviderVlanNetwork();
- req.setProviderVlanNetwork(pvn);
- }
- if (params.containsKey("shared")) {
- shared = params.get("shared");
- }
- if (params.containsKey("external")) {
- external = params.get("external");
- }
- adapter.updateNetwork(
- req.getCloudSiteId(),
- req.getTenantId(),
- req.getNetworkType(),
- req.getModelCustomizationUuid(),
- req.getNetworkStackId(),
- req.getNetworkName(),
- req.getProviderVlanNetwork().getPhysicalNetworkName(),
- req.getProviderVlanNetwork().getVlans(),
- shared,
- external,
- req.getSubnets(),
- params,
- req.getMsoRequest(),
- subnetIdMap,
- rollback);
- }
- response = new UpdateNetworkResponse(
- req.getNetworkId(),
- null, // NeutronNetworkId is not available from an update
- subnetIdMap.value,
- req.getMessageId());
- } catch (NetworkException e) {
- logger.debug(EXCEPTION, e);
- eresp = new UpdateNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("UpdateNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse());
- }
- }
-
- public static Map<String, String> testMap() {
- Map<String, String> m = new HashMap<>();
- m.put("mickey", "7");
- m.put("clyde", "10");
- m.put("wayne", "99");
- return m;
+ adapter.queryNetworkContrail(cloudSiteId, tenantId, aaiNetworkId, msoRequest, networkExists, networkId,
+ neutronNetworkId, status, routeTargets, subnetIdMap);
+
+ if (!networkExists.value) {
+ logger.debug("network not found");
+ respStatus = HttpStatus.SC_NOT_FOUND;
+ } else {
+ logger.debug("network found {}, status={}", networkId.value, status.value);
+ resp.setNetworkExists(networkExists.value);
+ resp.setNetworkId(networkId.value);
+ resp.setNeutronNetworkId(neutronNetworkId.value);
+ resp.setNetworkStatus(status.value);
+ resp.setRouteTargets(routeTargets.value);
+ resp.setSubnetIdMap(subnetIdMap.value);
+ }
+ logger.debug("Query network exit");
+ return Response.status(respStatus).entity(new GenericEntity<QueryNetworkResponse>(resp) {}).build();
+ } catch (NetworkException e) {
+ logger.error("{} {} Exception when query VNF ", MessageEnum.RA_QUERY_VNF_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ QueryNetworkError err = new QueryNetworkError();
+ err.setMessage(e.getMessage());
+ err.setCategory(MsoExceptionCategory.INTERNAL);
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
+ .entity(new GenericEntity<QueryNetworkError>(err) {}).build();
+ }
+ }
+
+ @DELETE
+ @Path("{aaiNetworkId}/rollback")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "RollbackNetwork", response = Response.class, notes = "Rollback an existing network")
+ @ApiResponses({@ApiResponse(code = 200, message = "Rollback network successful"),
+ @ApiResponse(code = 202, message = "Rollback network request has been accepted (async only)"),
+ @ApiResponse(code = 500, message = "Rollback network failed, examine entity object for details")})
+ public Response rollbackNetwork(
+ @ApiParam(value = "RollbackNetworkRequest in JSON format", required = true) RollbackNetworkRequest req) {
+ logger.debug("rollbackNetwork enter: {}", req.toJsonString());
+ RollbackNetworkTask task = new RollbackNetworkTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} Exception in rollbackNetwork ", MessageEnum.RA_ROLLBACK_NULL,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("rollbackNetwork exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class RollbackNetworkTask implements Runnable {
+ private final RollbackNetworkRequest req;
+ private RollbackNetworkResponse response = null;
+ private RollbackNetworkError eresp = null;
+ private boolean sendxml;
+
+ public RollbackNetworkTask(RollbackNetworkRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<RollbackNetworkResponse>(response) {}
+ : new GenericEntity<RollbackNetworkError>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("RollbackNetworkTask start");
+ try {
+ NetworkRollback nwr = req.getNetworkRollback();
+ adapter.rollbackNetwork(nwr);
+ response = new RollbackNetworkResponse(true, req.getMessageId());
+ } catch (NetworkException e) {
+ logger.debug(EXCEPTION, e);
+ eresp = new RollbackNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("RollbackNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse());
+ }
+ }
+
+ @PUT
+ @Path("{aaiNetworkId}")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "UpdateNetwork", response = Response.class, notes = "Update an existing network")
+ @ApiResponses({@ApiResponse(code = 200, message = "Update network successful"),
+ @ApiResponse(code = 202, message = "Update network request has been accepted (async only)"),
+ @ApiResponse(code = 500, message = "Update network failed, examine entity object for details")})
+ public Response updateNetwork(
+ @ApiParam(value = "aaiNetworkId", required = true) @PathParam("aaiNetworkId") String aaiNetworkId,
+ @ApiParam(value = "UpdateNetworkRequest in JSON format", required = true) UpdateNetworkRequest req) {
+ logger.debug("updateNetwork enter: {}", req.toJsonString());
+ if (aaiNetworkId == null || !aaiNetworkId.equals(req.getNetworkId())) {
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity(
+ "A&AI NetworkId in URL (" + aaiNetworkId + ") does not match content (" + req.getNetworkId() + ")")
+ .build();
+ }
+ UpdateNetworkTask task = new UpdateNetworkTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} Exception in updateNetwork ", MessageEnum.RA_UPDATE_NETWORK_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("updateNetwork exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class UpdateNetworkTask implements Runnable {
+ private final UpdateNetworkRequest req;
+ private UpdateNetworkResponse response = null;
+ private UpdateNetworkError eresp = null;
+ private boolean sendxml;
+
+ public UpdateNetworkTask(UpdateNetworkRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<UpdateNetworkResponse>(response) {}
+ : new GenericEntity<UpdateNetworkError>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("UpdateNetworkTask start");
+ try {
+ Holder<Map<String, String>> subnetIdMap = new Holder<>();
+ Holder<NetworkRollback> rollback = new Holder<>();
+ HashMap<String, String> params = (HashMap<String, String>) req.getNetworkParams();
+ if (params == null) {
+ params = new HashMap<String, String>();
+ }
+ String shared = null;
+ String external = null;
+
+ if (req.getCloudSiteId().equals(TESTING_KEYWORD)) {
+ subnetIdMap.value = testMap();
+ NetworkRollback rb = new NetworkRollback();
+ rb.setCloudId(req.getCloudSiteId());
+ rb.setTenantId(req.getTenantId());
+ rb.setMsoRequest(req.getMsoRequest());
+ rollback.value = rb;
+ } else if (req.isContrailRequest()) {
+ ContrailNetwork ctn = req.getContrailNetwork();
+ if (ctn == null) {
+ ctn = new ContrailNetwork();
+ req.setContrailNetwork(ctn);
+ }
+ if (params.containsKey("shared")) {
+ shared = params.get("shared");
+ } else {
+ if (ctn.getShared() != null) {
+ shared = ctn.getShared();
+ }
+ }
+ if (params.containsKey("external")) {
+ external = params.get("external");
+ } else {
+ if (ctn.getExternal() != null) {
+ external = ctn.getExternal();
+ }
+ }
+ adapter.updateNetworkContrail(req.getCloudSiteId(), req.getTenantId(), req.getNetworkType(),
+ req.getModelCustomizationUuid(), req.getNetworkStackId(), req.getNetworkName(),
+ req.getContrailNetwork().getRouteTargets(), shared, external, req.getSubnets(), params,
+ req.getContrailNetwork().getPolicyFqdns(), req.getContrailNetwork().getRouteTableFqdns(),
+ req.getMsoRequest(), subnetIdMap, rollback);
+ } else {
+ ProviderVlanNetwork pvn = req.getProviderVlanNetwork();
+ if (pvn == null) {
+ pvn = new ProviderVlanNetwork();
+ req.setProviderVlanNetwork(pvn);
+ }
+ if (params.containsKey("shared")) {
+ shared = params.get("shared");
+ }
+ if (params.containsKey("external")) {
+ external = params.get("external");
+ }
+ adapter.updateNetwork(req.getCloudSiteId(), req.getTenantId(), req.getNetworkType(),
+ req.getModelCustomizationUuid(), req.getNetworkStackId(), req.getNetworkName(),
+ req.getProviderVlanNetwork().getPhysicalNetworkName(),
+ req.getProviderVlanNetwork().getVlans(), shared, external, req.getSubnets(), params,
+ req.getMsoRequest(), subnetIdMap, rollback);
+ }
+ response = new UpdateNetworkResponse(req.getNetworkId(), null, // NeutronNetworkId is not available from
+ // an update
+ subnetIdMap.value, req.getMessageId());
+ } catch (NetworkException e) {
+ logger.debug(EXCEPTION, e);
+ eresp = new UpdateNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("UpdateNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse());
+ }
+ }
+
+ public static Map<String, String> testMap() {
+ Map<String, String> m = new HashMap<>();
+ m.put("mickey", "7");
+ m.put("clyde", "10");
+ m.put("wayne", "99");
+ return m;
}
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotification.java
index fcce165d27..f30ccf2214 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotification.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotification.java
@@ -24,7 +24,6 @@ package org.onap.so.adapters.network.async.client;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -32,9 +31,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for createNetworkNotification complex type.
+ * <p>
+ * Java class for createNetworkNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="createNetworkNotification">
@@ -79,16 +80,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "createNetworkNotification", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage",
- "networkId",
- "neutronNetworkId",
- "subnetIdMap",
- "rollback"
-})
+@XmlType(name = "createNetworkNotification", propOrder = {"messageId", "completed", "exception", "errorMessage",
+ "networkId", "neutronNetworkId", "subnetIdMap", "rollback"})
public class CreateNetworkNotification {
@XmlElement(required = true)
@@ -104,10 +97,8 @@ public class CreateNetworkNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -116,10 +107,8 @@ public class CreateNetworkNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -144,10 +133,8 @@ public class CreateNetworkNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -156,10 +143,8 @@ public class CreateNetworkNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -168,10 +153,8 @@ public class CreateNetworkNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -180,10 +163,8 @@ public class CreateNetworkNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
@@ -192,10 +173,8 @@ public class CreateNetworkNotification {
/**
* Gets the value of the networkId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getNetworkId() {
return networkId;
@@ -204,10 +183,8 @@ public class CreateNetworkNotification {
/**
* Sets the value of the networkId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setNetworkId(String value) {
this.networkId = value;
@@ -216,10 +193,8 @@ public class CreateNetworkNotification {
/**
* Gets the value of the neutronNetworkId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getNeutronNetworkId() {
return neutronNetworkId;
@@ -228,10 +203,8 @@ public class CreateNetworkNotification {
/**
* Sets the value of the neutronNetworkId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setNeutronNetworkId(String value) {
this.neutronNetworkId = value;
@@ -240,10 +213,8 @@ public class CreateNetworkNotification {
/**
* Gets the value of the subnetIdMap property.
*
- * @return
- * possible object is
- * {@link CreateNetworkNotification.SubnetIdMap }
- *
+ * @return possible object is {@link CreateNetworkNotification.SubnetIdMap }
+ *
*/
public CreateNetworkNotification.SubnetIdMap getSubnetIdMap() {
return subnetIdMap;
@@ -252,10 +223,8 @@ public class CreateNetworkNotification {
/**
* Sets the value of the subnetIdMap property.
*
- * @param value
- * allowed object is
- * {@link CreateNetworkNotification.SubnetIdMap }
- *
+ * @param value allowed object is {@link CreateNetworkNotification.SubnetIdMap }
+ *
*/
public void setSubnetIdMap(CreateNetworkNotification.SubnetIdMap value) {
this.subnetIdMap = value;
@@ -264,10 +233,8 @@ public class CreateNetworkNotification {
/**
* Gets the value of the rollback property.
*
- * @return
- * possible object is
- * {@link NetworkRollback }
- *
+ * @return possible object is {@link NetworkRollback }
+ *
*/
public NetworkRollback getRollback() {
return rollback;
@@ -276,10 +243,8 @@ public class CreateNetworkNotification {
/**
* Sets the value of the rollback property.
*
- * @param value
- * allowed object is
- * {@link NetworkRollback }
- *
+ * @param value allowed object is {@link NetworkRollback }
+ *
*/
public void setRollback(NetworkRollback value) {
this.rollback = value;
@@ -287,9 +252,11 @@ public class CreateNetworkNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -317,9 +284,7 @@ public class CreateNetworkNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "entry"
- })
+ @XmlType(name = "", propOrder = {"entry"})
public static class SubnetIdMap {
protected List<CreateNetworkNotification.SubnetIdMap.Entry> entry;
@@ -328,21 +293,20 @@ public class CreateNetworkNotification {
* Gets the value of the entry property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the entry property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you
+ * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE>
+ * method for the entry property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getEntry().add(newItem);
+ * getEntry().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link CreateNetworkNotification.SubnetIdMap.Entry }
+ * Objects of the following type(s) are allowed in the list {@link CreateNetworkNotification.SubnetIdMap.Entry }
*
*
*/
@@ -355,9 +319,11 @@ public class CreateNetworkNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -375,10 +341,7 @@ public class CreateNetworkNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "key",
- "value"
- })
+ @XmlType(name = "", propOrder = {"key", "value"})
public static class Entry {
protected String key;
@@ -387,10 +350,8 @@ public class CreateNetworkNotification {
/**
* Gets the value of the key property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getKey() {
return key;
@@ -399,10 +360,8 @@ public class CreateNetworkNotification {
/**
* Sets the value of the key property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setKey(String value) {
this.key = value;
@@ -411,10 +370,8 @@ public class CreateNetworkNotification {
/**
* Gets the value of the value property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getValue() {
return value;
@@ -423,10 +380,8 @@ public class CreateNetworkNotification {
/**
* Sets the value of the value property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setValue(String value) {
this.value = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotificationResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotificationResponse.java
index a0e40c0e6a..4ade875193 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotificationResponse.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotificationResponse.java
@@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for createNetworkNotificationResponse complex type.
+ * <p>
+ * Java class for createNetworkNotificationResponse complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="createNetworkNotificationResponse">
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotification.java
index d4f992a9b4..ff94be9156 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotification.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotification.java
@@ -27,9 +27,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for deleteNetworkNotification complex type.
+ * <p>
+ * Java class for deleteNetworkNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="deleteNetworkNotification">
@@ -50,13 +52,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "deleteNetworkNotification", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage",
- "networkDeleted"
-})
+@XmlType(name = "deleteNetworkNotification",
+ propOrder = {"messageId", "completed", "exception", "errorMessage", "networkDeleted"})
public class DeleteNetworkNotification {
@XmlElement(required = true)
@@ -69,10 +66,8 @@ public class DeleteNetworkNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -81,10 +76,8 @@ public class DeleteNetworkNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -109,10 +102,8 @@ public class DeleteNetworkNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -121,10 +112,8 @@ public class DeleteNetworkNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -133,10 +122,8 @@ public class DeleteNetworkNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -145,10 +132,8 @@ public class DeleteNetworkNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
@@ -157,10 +142,8 @@ public class DeleteNetworkNotification {
/**
* Gets the value of the networkDeleted property.
*
- * @return
- * possible object is
- * {@link Boolean }
- *
+ * @return possible object is {@link Boolean }
+ *
*/
public Boolean isNetworkDeleted() {
return networkDeleted;
@@ -169,10 +152,8 @@ public class DeleteNetworkNotification {
/**
* Sets the value of the networkDeleted property.
*
- * @param value
- * allowed object is
- * {@link Boolean }
- *
+ * @param value allowed object is {@link Boolean }
+ *
*/
public void setNetworkDeleted(Boolean value) {
this.networkDeleted = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotificationResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotificationResponse.java
index 76eb8115d5..7f7d0ae569 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotificationResponse.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotificationResponse.java
@@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for deleteNetworkNotificationResponse complex type.
+ * <p>
+ * Java class for deleteNetworkNotificationResponse complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="deleteNetworkNotificationResponse">
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoExceptionCategory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoExceptionCategory.java
index 8c18a59e68..ad3c541730 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoExceptionCategory.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoExceptionCategory.java
@@ -25,10 +25,13 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for msoExceptionCategory.
+ * <p>
+ * Java class for msoExceptionCategory.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
* <p>
+ * The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ *
* <pre>
* &lt;simpleType name="msoExceptionCategory">
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
@@ -45,10 +48,7 @@ import javax.xml.bind.annotation.XmlType;
@XmlEnum
public enum MsoExceptionCategory {
- OPENSTACK,
- IO,
- INTERNAL,
- USERDATA;
+ OPENSTACK, IO, INTERNAL, USERDATA;
public String value() {
return name();
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoRequest.java
index aa6f34f2e0..90ae448660 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoRequest.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoRequest.java
@@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for msoRequest complex type.
+ * <p>
+ * Java class for msoRequest complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="msoRequest">
@@ -46,10 +48,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "msoRequest", propOrder = {
- "requestId",
- "serviceInstanceId"
-})
+@XmlType(name = "msoRequest", propOrder = {"requestId", "serviceInstanceId"})
public class MsoRequest {
protected String requestId;
@@ -58,10 +57,8 @@ public class MsoRequest {
/**
* Gets the value of the requestId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getRequestId() {
return requestId;
@@ -70,10 +67,8 @@ public class MsoRequest {
/**
* Sets the value of the requestId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setRequestId(String value) {
this.requestId = value;
@@ -82,10 +77,8 @@ public class MsoRequest {
/**
* Gets the value of the serviceInstanceId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getServiceInstanceId() {
return serviceInstanceId;
@@ -94,10 +87,8 @@ public class MsoRequest {
/**
* Sets the value of the serviceInstanceId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setServiceInstanceId(String value) {
this.serviceInstanceId = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify.java
index 0433aab0cc..8fb62cc32e 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters.network.async.client;
import java.util.List;
-
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
@@ -32,15 +31,11 @@ import javax.xml.ws.ResponseWrapper;
/**
- * This class was generated by the JAX-WS RI.
- * JAX-WS RI 2.2.9-b14002
- * Generated source version: 2.2
+ * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.9-b14002 Generated source version: 2.2
*
*/
@WebService(name = "networkAdapterNotify", targetNamespace = "http://org.onap.so/networkNotify")
-@XmlSeeAlso({
- ObjectFactory.class
-})
+@XmlSeeAlso({ObjectFactory.class})
public interface NetworkAdapterNotify {
@@ -52,18 +47,17 @@ public interface NetworkAdapterNotify {
* @param completed
*/
@WebMethod
- @RequestWrapper(localName = "rollbackNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.RollbackNetworkNotification")
- @ResponseWrapper(localName = "rollbackNetworkNotificationResponse", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.RollbackNetworkNotificationResponse")
- @Action(input = "http://org.onap.so/notify/adapterNotify/rollbackNetworkNotificationRequest", output = "http://org.onap.so/notify/adapterNotify/rollbackNetworkNotificationResponse")
- public void rollbackNetworkNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage);
+ @RequestWrapper(localName = "rollbackNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify",
+ className = "org.onap.so.adapters.network.async.client.RollbackNetworkNotification")
+ @ResponseWrapper(localName = "rollbackNetworkNotificationResponse",
+ targetNamespace = "http://org.onap.so/networkNotify",
+ className = "org.onap.so.adapters.network.async.client.RollbackNetworkNotificationResponse")
+ @Action(input = "http://org.onap.so/notify/adapterNotify/rollbackNetworkNotificationRequest",
+ output = "http://org.onap.so/notify/adapterNotify/rollbackNetworkNotificationResponse")
+ public void rollbackNetworkNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage);
/**
*
@@ -79,30 +73,23 @@ public interface NetworkAdapterNotify {
* @param subnetIdMap
*/
@WebMethod
- @RequestWrapper(localName = "queryNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.QueryNetworkNotification")
- @ResponseWrapper(localName = "queryNetworkNotificationResponse", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.QueryNetworkNotificationResponse")
- @Action(input = "http://org.onap.so/notify/adapterNotify/queryNetworkNotificationRequest", output = "http://org.onap.so/notify/adapterNotify/queryNetworkNotificationResponse")
- public void queryNetworkNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "networkExists", targetNamespace = "")
- Boolean networkExists,
- @WebParam(name = "networkId", targetNamespace = "")
- String networkId,
- @WebParam(name = "neutronNetworkId", targetNamespace = "")
- String neutronNetworkId,
- @WebParam(name = "status", targetNamespace = "")
- NetworkStatus status,
- @WebParam(name = "vlans", targetNamespace = "")
- List<Integer> vlans,
- @WebParam(name = "subnetIdMap", targetNamespace = "")
- org.onap.so.adapters.network.async.client.QueryNetworkNotification.SubnetIdMap subnetIdMap);
+ @RequestWrapper(localName = "queryNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify",
+ className = "org.onap.so.adapters.network.async.client.QueryNetworkNotification")
+ @ResponseWrapper(localName = "queryNetworkNotificationResponse",
+ targetNamespace = "http://org.onap.so/networkNotify",
+ className = "org.onap.so.adapters.network.async.client.QueryNetworkNotificationResponse")
+ @Action(input = "http://org.onap.so/notify/adapterNotify/queryNetworkNotificationRequest",
+ output = "http://org.onap.so/notify/adapterNotify/queryNetworkNotificationResponse")
+ public void queryNetworkNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "networkExists", targetNamespace = "") Boolean networkExists,
+ @WebParam(name = "networkId", targetNamespace = "") String networkId,
+ @WebParam(name = "neutronNetworkId", targetNamespace = "") String neutronNetworkId,
+ @WebParam(name = "status", targetNamespace = "") NetworkStatus status,
+ @WebParam(name = "vlans", targetNamespace = "") List<Integer> vlans, @WebParam(name = "subnetIdMap",
+ targetNamespace = "") org.onap.so.adapters.network.async.client.QueryNetworkNotification.SubnetIdMap subnetIdMap);
/**
*
@@ -116,26 +103,22 @@ public interface NetworkAdapterNotify {
* @param subnetIdMap
*/
@WebMethod
- @RequestWrapper(localName = "createNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.CreateNetworkNotification")
- @ResponseWrapper(localName = "createNetworkNotificationResponse", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.CreateNetworkNotificationResponse")
- @Action(input = "http://org.onap.so/notify/adapterNotify/createNetworkNotificationRequest", output = "http://org.onap.so/notify/adapterNotify/createNetworkNotificationResponse")
- public void createNetworkNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "networkId", targetNamespace = "")
- String networkId,
- @WebParam(name = "neutronNetworkId", targetNamespace = "")
- String neutronNetworkId,
- @WebParam(name = "subnetIdMap", targetNamespace = "")
- org.onap.so.adapters.network.async.client.CreateNetworkNotification.SubnetIdMap subnetIdMap,
- @WebParam(name = "rollback", targetNamespace = "")
- NetworkRollback rollback);
+ @RequestWrapper(localName = "createNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify",
+ className = "org.onap.so.adapters.network.async.client.CreateNetworkNotification")
+ @ResponseWrapper(localName = "createNetworkNotificationResponse",
+ targetNamespace = "http://org.onap.so/networkNotify",
+ className = "org.onap.so.adapters.network.async.client.CreateNetworkNotificationResponse")
+ @Action(input = "http://org.onap.so/notify/adapterNotify/createNetworkNotificationRequest",
+ output = "http://org.onap.so/notify/adapterNotify/createNetworkNotificationResponse")
+ public void createNetworkNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "networkId", targetNamespace = "") String networkId,
+ @WebParam(name = "neutronNetworkId", targetNamespace = "") String neutronNetworkId,
+ @WebParam(name = "subnetIdMap",
+ targetNamespace = "") org.onap.so.adapters.network.async.client.CreateNetworkNotification.SubnetIdMap subnetIdMap,
+ @WebParam(name = "rollback", targetNamespace = "") NetworkRollback rollback);
/**
*
@@ -146,20 +129,18 @@ public interface NetworkAdapterNotify {
* @param completed
*/
@WebMethod
- @RequestWrapper(localName = "deleteNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.DeleteNetworkNotification")
- @ResponseWrapper(localName = "deleteNetworkNotificationResponse", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.DeleteNetworkNotificationResponse")
- @Action(input = "http://org.onap.so/notify/adapterNotify/deleteNetworkNotificationRequest", output = "http://org.onap.so/notify/adapterNotify/deleteNetworkNotificationResponse")
- public void deleteNetworkNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "networkDeleted", targetNamespace = "")
- Boolean networkDeleted);
+ @RequestWrapper(localName = "deleteNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify",
+ className = "org.onap.so.adapters.network.async.client.DeleteNetworkNotification")
+ @ResponseWrapper(localName = "deleteNetworkNotificationResponse",
+ targetNamespace = "http://org.onap.so/networkNotify",
+ className = "org.onap.so.adapters.network.async.client.DeleteNetworkNotificationResponse")
+ @Action(input = "http://org.onap.so/notify/adapterNotify/deleteNetworkNotificationRequest",
+ output = "http://org.onap.so/notify/adapterNotify/deleteNetworkNotificationResponse")
+ public void deleteNetworkNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "networkDeleted", targetNamespace = "") Boolean networkDeleted);
/**
*
@@ -171,21 +152,19 @@ public interface NetworkAdapterNotify {
* @param subnetIdMap
*/
@WebMethod
- @RequestWrapper(localName = "updateNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.UpdateNetworkNotification")
- @ResponseWrapper(localName = "updateNetworkNotificationResponse", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.UpdateNetworkNotificationResponse")
- @Action(input = "http://org.onap.so/notify/adapterNotify/updateNetworkNotificationRequest", output = "http://org.onap.so/notify/adapterNotify/updateNetworkNotificationResponse")
- public void updateNetworkNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "subnetIdMap", targetNamespace = "")
- org.onap.so.adapters.network.async.client.UpdateNetworkNotification.SubnetIdMap subnetIdMap,
- @WebParam(name = "rollback", targetNamespace = "")
- NetworkRollback rollback);
+ @RequestWrapper(localName = "updateNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify",
+ className = "org.onap.so.adapters.network.async.client.UpdateNetworkNotification")
+ @ResponseWrapper(localName = "updateNetworkNotificationResponse",
+ targetNamespace = "http://org.onap.so/networkNotify",
+ className = "org.onap.so.adapters.network.async.client.UpdateNetworkNotificationResponse")
+ @Action(input = "http://org.onap.so/notify/adapterNotify/updateNetworkNotificationRequest",
+ output = "http://org.onap.so/notify/adapterNotify/updateNetworkNotificationResponse")
+ public void updateNetworkNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "subnetIdMap",
+ targetNamespace = "") org.onap.so.adapters.network.async.client.UpdateNetworkNotification.SubnetIdMap subnetIdMap,
+ @WebParam(name = "rollback", targetNamespace = "") NetworkRollback rollback);
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify_Service.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify_Service.java
index f408f227c6..c275073c46 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify_Service.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify_Service.java
@@ -23,7 +23,6 @@
package org.onap.so.adapters.network.async.client;
import java.net.URL;
-
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
@@ -33,26 +32,26 @@ import javax.xml.ws.WebServiceFeature;
/**
- * This class was generated by the JAX-WS RI.
- * JAX-WS RI 2.2.9-b14002
- * Generated source version: 2.2
+ * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.9-b14002 Generated source version: 2.2
*
*/
-@WebServiceClient(name = "networkAdapterNotify", targetNamespace = "http://org.onap.so/networkNotify", wsdlLocation = "/NetworkAdapterNotify.wsdl")
-public class NetworkAdapterNotify_Service
- extends Service
-{
+@WebServiceClient(name = "networkAdapterNotify", targetNamespace = "http://org.onap.so/networkNotify",
+ wsdlLocation = "/NetworkAdapterNotify.wsdl")
+public class NetworkAdapterNotify_Service extends Service {
private static final URL NETWORKADAPTERNOTIFY_WSDL_LOCATION;
private static final WebServiceException NETWORKADAPTERNOTIFY_EXCEPTION;
- private static final String URL="http://org.onap.so/networkNotify";
+ private static final String URL = "http://org.onap.so/networkNotify";
private static final QName NETWORKADAPTERNOTIFY_QNAME = new QName(URL, "networkAdapterNotify");
static {
- NETWORKADAPTERNOTIFY_WSDL_LOCATION = org.onap.so.adapters.network.async.client.NetworkAdapterNotify_Service.class.getResource("/NetworkAdapterNotify.wsdl");
+ NETWORKADAPTERNOTIFY_WSDL_LOCATION =
+ org.onap.so.adapters.network.async.client.NetworkAdapterNotify_Service.class
+ .getResource("/NetworkAdapterNotify.wsdl");
WebServiceException e = null;
if (NETWORKADAPTERNOTIFY_WSDL_LOCATION == null) {
- e = new WebServiceException("Cannot find '/NetworkAdapterNotify.wsdl' wsdl. Place the resource correctly in the classpath.");
+ e = new WebServiceException(
+ "Cannot find '/NetworkAdapterNotify.wsdl' wsdl. Place the resource correctly in the classpath.");
}
NETWORKADAPTERNOTIFY_EXCEPTION = e;
}
@@ -83,8 +82,7 @@ public class NetworkAdapterNotify_Service
/**
*
- * @return
- * returns NetworkAdapterNotify
+ * @return returns NetworkAdapterNotify
*/
@WebEndpoint(name = "MsoNetworkAdapterAsyncImplPort")
public NetworkAdapterNotify getMsoNetworkAdapterAsyncImplPort() {
@@ -93,10 +91,9 @@ public class NetworkAdapterNotify_Service
/**
*
- * @param features
- * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
- * @return
- * returns NetworkAdapterNotify
+ * @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features
+ * not in the <code>features</code> parameter will have their default values.
+ * @return returns NetworkAdapterNotify
*/
@WebEndpoint(name = "MsoNetworkAdapterAsyncImplPort")
public NetworkAdapterNotify getMsoNetworkAdapterAsyncImplPort(WebServiceFeature... features) {
@@ -104,7 +101,7 @@ public class NetworkAdapterNotify_Service
}
private static URL __getWsdlLocation() {
- if (NETWORKADAPTERNOTIFY_EXCEPTION!= null) {
+ if (NETWORKADAPTERNOTIFY_EXCEPTION != null) {
throw NETWORKADAPTERNOTIFY_EXCEPTION;
}
return NETWORKADAPTERNOTIFY_WSDL_LOCATION;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkRollback.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkRollback.java
index e7ace110ac..c51a21d5f0 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkRollback.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkRollback.java
@@ -24,7 +24,6 @@ package org.onap.so.adapters.network.async.client;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -32,9 +31,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for networkRollback complex type.
+ * <p>
+ * Java class for networkRollback complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="networkRollback">
@@ -62,20 +63,9 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "networkRollback", propOrder = {
- "cloudId",
- "msoRequest",
- "networkCreated",
- "networkId",
- "networkStackId",
- "networkName",
- "networkType",
- "networkUpdated",
- "neutronNetworkId",
- "physicalNetwork",
- "tenantId",
- "vlans"
-})
+@XmlType(name = "networkRollback",
+ propOrder = {"cloudId", "msoRequest", "networkCreated", "networkId", "networkStackId", "networkName",
+ "networkType", "networkUpdated", "neutronNetworkId", "physicalNetwork", "tenantId", "vlans"})
public class NetworkRollback {
protected String cloudId;
@@ -95,10 +85,8 @@ public class NetworkRollback {
/**
* Gets the value of the cloudId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getCloudId() {
return cloudId;
@@ -107,10 +95,8 @@ public class NetworkRollback {
/**
* Sets the value of the cloudId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setCloudId(String value) {
this.cloudId = value;
@@ -119,10 +105,8 @@ public class NetworkRollback {
/**
* Gets the value of the msoRequest property.
*
- * @return
- * possible object is
- * {@link MsoRequest }
- *
+ * @return possible object is {@link MsoRequest }
+ *
*/
public MsoRequest getMsoRequest() {
return msoRequest;
@@ -131,10 +115,8 @@ public class NetworkRollback {
/**
* Sets the value of the msoRequest property.
*
- * @param value
- * allowed object is
- * {@link MsoRequest }
- *
+ * @param value allowed object is {@link MsoRequest }
+ *
*/
public void setMsoRequest(MsoRequest value) {
this.msoRequest = value;
@@ -159,10 +141,8 @@ public class NetworkRollback {
/**
* Gets the value of the networkId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getNetworkId() {
return networkId;
@@ -171,10 +151,8 @@ public class NetworkRollback {
/**
* Sets the value of the networkId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setNetworkId(String value) {
this.networkId = value;
@@ -183,10 +161,8 @@ public class NetworkRollback {
/**
* Gets the value of the networkStackId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getNetworkStackId() {
return networkStackId;
@@ -195,10 +171,8 @@ public class NetworkRollback {
/**
* Sets the value of the networkStackId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setNetworkStackId(String value) {
this.networkStackId = value;
@@ -207,10 +181,8 @@ public class NetworkRollback {
/**
* Gets the value of the networkName property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getNetworkName() {
return networkName;
@@ -219,10 +191,8 @@ public class NetworkRollback {
/**
* Sets the value of the networkName property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setNetworkName(String value) {
this.networkName = value;
@@ -231,10 +201,8 @@ public class NetworkRollback {
/**
* Gets the value of the networkType property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getNetworkType() {
return networkType;
@@ -243,10 +211,8 @@ public class NetworkRollback {
/**
* Sets the value of the networkType property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setNetworkType(String value) {
this.networkType = value;
@@ -271,10 +237,8 @@ public class NetworkRollback {
/**
* Gets the value of the neutronNetworkId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getNeutronNetworkId() {
return neutronNetworkId;
@@ -283,10 +247,8 @@ public class NetworkRollback {
/**
* Sets the value of the neutronNetworkId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setNeutronNetworkId(String value) {
this.neutronNetworkId = value;
@@ -295,10 +257,8 @@ public class NetworkRollback {
/**
* Gets the value of the physicalNetwork property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getPhysicalNetwork() {
return physicalNetwork;
@@ -307,10 +267,8 @@ public class NetworkRollback {
/**
* Sets the value of the physicalNetwork property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setPhysicalNetwork(String value) {
this.physicalNetwork = value;
@@ -319,10 +277,8 @@ public class NetworkRollback {
/**
* Gets the value of the tenantId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getTenantId() {
return tenantId;
@@ -331,10 +287,8 @@ public class NetworkRollback {
/**
* Sets the value of the tenantId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setTenantId(String value) {
this.tenantId = value;
@@ -344,21 +298,20 @@ public class NetworkRollback {
* Gets the value of the vlans property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the vlans property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to
+ * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for
+ * the vlans property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getVlans().add(newItem);
+ * getVlans().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link Integer }
+ * Objects of the following type(s) are allowed in the list {@link Integer }
*
*
*/
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkStatus.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkStatus.java
index 982f214bd8..36641477c0 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkStatus.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkStatus.java
@@ -25,10 +25,13 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for networkStatus.
+ * <p>
+ * Java class for networkStatus.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
* <p>
+ * The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ *
* <pre>
* &lt;simpleType name="networkStatus">
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
@@ -47,12 +50,7 @@ import javax.xml.bind.annotation.XmlType;
@XmlEnum
public enum NetworkStatus {
- NOTFOUND,
- ACTIVE,
- DOWN,
- BUILD,
- ERROR,
- UNKNOWN;
+ NOTFOUND, ACTIVE, DOWN, BUILD, ERROR, UNKNOWN;
public String value() {
return name();
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/ObjectFactory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/ObjectFactory.java
index f2238fce78..81ccd8aa04 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/ObjectFactory.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/ObjectFactory.java
@@ -27,40 +27,41 @@ import javax.xml.namespace.QName;
/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the org.onap.so.adapters.network.async.client package.
- * <p>An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
- * provided in this class.
+ * This object contains factory methods for each Java content interface and Java element interface generated in the
+ * org.onap.so.adapters.network.async.client package.
+ * <p>
+ * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content.
+ * The Java representation of XML content can consist of schema derived interfaces and classes representing the binding
+ * of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in
+ * this class.
*
*/
@XmlRegistry
public class ObjectFactory {
-
- private static final String Url= "http://org.onap.so/networkNotify";
+
+ private static final String Url = "http://org.onap.so/networkNotify";
private static final QName _RollbackNetworkNotification_QNAME = new QName(Url, "rollbackNetworkNotification");
private static final QName _UpdateNetworkNotification_QNAME = new QName(Url, "updateNetworkNotification");
- private static final QName _QueryNetworkNotificationResponse_QNAME = new QName(Url, "queryNetworkNotificationResponse");
- private static final QName _UpdateNetworkNotificationResponse_QNAME = new QName(Url, "updateNetworkNotificationResponse");
- private static final QName _CreateNetworkNotificationResponse_QNAME = new QName(Url, "createNetworkNotificationResponse");
+ private static final QName _QueryNetworkNotificationResponse_QNAME =
+ new QName(Url, "queryNetworkNotificationResponse");
+ private static final QName _UpdateNetworkNotificationResponse_QNAME =
+ new QName(Url, "updateNetworkNotificationResponse");
+ private static final QName _CreateNetworkNotificationResponse_QNAME =
+ new QName(Url, "createNetworkNotificationResponse");
private static final QName _DeleteNetworkNotification_QNAME = new QName(Url, "deleteNetworkNotification");
- private static final QName _DeleteNetworkNotificationResponse_QNAME = new QName(Url, "deleteNetworkNotificationResponse");
+ private static final QName _DeleteNetworkNotificationResponse_QNAME =
+ new QName(Url, "deleteNetworkNotificationResponse");
private static final QName _CreateNetworkNotification_QNAME = new QName(Url, "createNetworkNotification");
private static final QName _QueryNetworkNotification_QNAME = new QName(Url, "queryNetworkNotification");
- private static final QName _RollbackNetworkNotificationResponse_QNAME = new QName(Url, "rollbackNetworkNotificationResponse");
+ private static final QName _RollbackNetworkNotificationResponse_QNAME =
+ new QName(Url, "rollbackNetworkNotificationResponse");
/**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.so.adapters.network.async.client
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
+ * org.onap.so.adapters.network.async.client
*
*/
- public ObjectFactory() {
- }
+ public ObjectFactory() {}
/**
* Create an instance of {@link QueryNetworkNotification }
@@ -211,7 +212,8 @@ public class ObjectFactory {
*
*/
@XmlElementDecl(namespace = Url, name = "rollbackNetworkNotification")
- public JAXBElement<RollbackNetworkNotification> createRollbackNetworkNotification(RollbackNetworkNotification value) {
+ public JAXBElement<RollbackNetworkNotification> createRollbackNetworkNotification(
+ RollbackNetworkNotification value) {
return new JAXBElement<>(_RollbackNetworkNotification_QNAME, RollbackNetworkNotification.class, null, value);
}
@@ -229,8 +231,10 @@ public class ObjectFactory {
*
*/
@XmlElementDecl(namespace = Url, name = "queryNetworkNotificationResponse")
- public JAXBElement<QueryNetworkNotificationResponse> createQueryNetworkNotificationResponse(QueryNetworkNotificationResponse value) {
- return new JAXBElement<>(_QueryNetworkNotificationResponse_QNAME, QueryNetworkNotificationResponse.class, null, value);
+ public JAXBElement<QueryNetworkNotificationResponse> createQueryNetworkNotificationResponse(
+ QueryNetworkNotificationResponse value) {
+ return new JAXBElement<>(_QueryNetworkNotificationResponse_QNAME, QueryNetworkNotificationResponse.class, null,
+ value);
}
/**
@@ -238,8 +242,10 @@ public class ObjectFactory {
*
*/
@XmlElementDecl(namespace = Url, name = "updateNetworkNotificationResponse")
- public JAXBElement<UpdateNetworkNotificationResponse> createUpdateNetworkNotificationResponse(UpdateNetworkNotificationResponse value) {
- return new JAXBElement<>(_UpdateNetworkNotificationResponse_QNAME, UpdateNetworkNotificationResponse.class, null, value);
+ public JAXBElement<UpdateNetworkNotificationResponse> createUpdateNetworkNotificationResponse(
+ UpdateNetworkNotificationResponse value) {
+ return new JAXBElement<>(_UpdateNetworkNotificationResponse_QNAME, UpdateNetworkNotificationResponse.class,
+ null, value);
}
/**
@@ -247,8 +253,10 @@ public class ObjectFactory {
*
*/
@XmlElementDecl(namespace = Url, name = "createNetworkNotificationResponse")
- public JAXBElement<CreateNetworkNotificationResponse> createCreateNetworkNotificationResponse(CreateNetworkNotificationResponse value) {
- return new JAXBElement<>(_CreateNetworkNotificationResponse_QNAME, CreateNetworkNotificationResponse.class, null, value);
+ public JAXBElement<CreateNetworkNotificationResponse> createCreateNetworkNotificationResponse(
+ CreateNetworkNotificationResponse value) {
+ return new JAXBElement<>(_CreateNetworkNotificationResponse_QNAME, CreateNetworkNotificationResponse.class,
+ null, value);
}
/**
@@ -265,8 +273,10 @@ public class ObjectFactory {
*
*/
@XmlElementDecl(namespace = Url, name = "deleteNetworkNotificationResponse")
- public JAXBElement<DeleteNetworkNotificationResponse> createDeleteNetworkNotificationResponse(DeleteNetworkNotificationResponse value) {
- return new JAXBElement<>(_DeleteNetworkNotificationResponse_QNAME, DeleteNetworkNotificationResponse.class, null, value);
+ public JAXBElement<DeleteNetworkNotificationResponse> createDeleteNetworkNotificationResponse(
+ DeleteNetworkNotificationResponse value) {
+ return new JAXBElement<>(_DeleteNetworkNotificationResponse_QNAME, DeleteNetworkNotificationResponse.class,
+ null, value);
}
/**
@@ -292,8 +302,10 @@ public class ObjectFactory {
*
*/
@XmlElementDecl(namespace = Url, name = "rollbackNetworkNotificationResponse")
- public JAXBElement<RollbackNetworkNotificationResponse> createRollbackNetworkNotificationResponse(RollbackNetworkNotificationResponse value) {
- return new JAXBElement<>(_RollbackNetworkNotificationResponse_QNAME, RollbackNetworkNotificationResponse.class, null, value);
+ public JAXBElement<RollbackNetworkNotificationResponse> createRollbackNetworkNotificationResponse(
+ RollbackNetworkNotificationResponse value) {
+ return new JAXBElement<>(_RollbackNetworkNotificationResponse_QNAME, RollbackNetworkNotificationResponse.class,
+ null, value);
}
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotification.java
index 87aa2183f1..d9adbf2ad2 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotification.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotification.java
@@ -24,7 +24,6 @@ package org.onap.so.adapters.network.async.client;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -32,9 +31,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for queryNetworkNotification complex type.
+ * <p>
+ * Java class for queryNetworkNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="queryNetworkNotification">
@@ -81,18 +82,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "queryNetworkNotification", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage",
- "networkExists",
- "networkId",
- "neutronNetworkId",
- "status",
- "vlans",
- "subnetIdMap"
-})
+@XmlType(name = "queryNetworkNotification", propOrder = {"messageId", "completed", "exception", "errorMessage",
+ "networkExists", "networkId", "neutronNetworkId", "status", "vlans", "subnetIdMap"})
public class QueryNetworkNotification {
@XmlElement(required = true)
@@ -111,10 +102,8 @@ public class QueryNetworkNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -123,10 +112,8 @@ public class QueryNetworkNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -151,10 +138,8 @@ public class QueryNetworkNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -163,10 +148,8 @@ public class QueryNetworkNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -175,10 +158,8 @@ public class QueryNetworkNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -187,10 +168,8 @@ public class QueryNetworkNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
@@ -199,10 +178,8 @@ public class QueryNetworkNotification {
/**
* Gets the value of the networkExists property.
*
- * @return
- * possible object is
- * {@link Boolean }
- *
+ * @return possible object is {@link Boolean }
+ *
*/
public Boolean isNetworkExists() {
return networkExists;
@@ -211,10 +188,8 @@ public class QueryNetworkNotification {
/**
* Sets the value of the networkExists property.
*
- * @param value
- * allowed object is
- * {@link Boolean }
- *
+ * @param value allowed object is {@link Boolean }
+ *
*/
public void setNetworkExists(Boolean value) {
this.networkExists = value;
@@ -223,10 +198,8 @@ public class QueryNetworkNotification {
/**
* Gets the value of the networkId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getNetworkId() {
return networkId;
@@ -235,10 +208,8 @@ public class QueryNetworkNotification {
/**
* Sets the value of the networkId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setNetworkId(String value) {
this.networkId = value;
@@ -247,10 +218,8 @@ public class QueryNetworkNotification {
/**
* Gets the value of the neutronNetworkId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getNeutronNetworkId() {
return neutronNetworkId;
@@ -259,10 +228,8 @@ public class QueryNetworkNotification {
/**
* Sets the value of the neutronNetworkId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setNeutronNetworkId(String value) {
this.neutronNetworkId = value;
@@ -271,10 +238,8 @@ public class QueryNetworkNotification {
/**
* Gets the value of the status property.
*
- * @return
- * possible object is
- * {@link NetworkStatus }
- *
+ * @return possible object is {@link NetworkStatus }
+ *
*/
public NetworkStatus getStatus() {
return status;
@@ -283,10 +248,8 @@ public class QueryNetworkNotification {
/**
* Sets the value of the status property.
*
- * @param value
- * allowed object is
- * {@link NetworkStatus }
- *
+ * @param value allowed object is {@link NetworkStatus }
+ *
*/
public void setStatus(NetworkStatus value) {
this.status = value;
@@ -296,21 +259,20 @@ public class QueryNetworkNotification {
* Gets the value of the vlans property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the vlans property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to
+ * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for
+ * the vlans property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getVlans().add(newItem);
+ * getVlans().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link Integer }
+ * Objects of the following type(s) are allowed in the list {@link Integer }
*
*
*/
@@ -324,10 +286,8 @@ public class QueryNetworkNotification {
/**
* Gets the value of the subnetIdMap property.
*
- * @return
- * possible object is
- * {@link QueryNetworkNotification.SubnetIdMap }
- *
+ * @return possible object is {@link QueryNetworkNotification.SubnetIdMap }
+ *
*/
public QueryNetworkNotification.SubnetIdMap getSubnetIdMap() {
return subnetIdMap;
@@ -336,10 +296,8 @@ public class QueryNetworkNotification {
/**
* Sets the value of the subnetIdMap property.
*
- * @param value
- * allowed object is
- * {@link QueryNetworkNotification.SubnetIdMap }
- *
+ * @param value allowed object is {@link QueryNetworkNotification.SubnetIdMap }
+ *
*/
public void setSubnetIdMap(QueryNetworkNotification.SubnetIdMap value) {
this.subnetIdMap = value;
@@ -347,9 +305,11 @@ public class QueryNetworkNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -377,9 +337,7 @@ public class QueryNetworkNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "entry"
- })
+ @XmlType(name = "", propOrder = {"entry"})
public static class SubnetIdMap {
protected List<QueryNetworkNotification.SubnetIdMap.Entry> entry;
@@ -388,21 +346,20 @@ public class QueryNetworkNotification {
* Gets the value of the entry property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the entry property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you
+ * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE>
+ * method for the entry property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getEntry().add(newItem);
+ * getEntry().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link QueryNetworkNotification.SubnetIdMap.Entry }
+ * Objects of the following type(s) are allowed in the list {@link QueryNetworkNotification.SubnetIdMap.Entry }
*
*
*/
@@ -415,9 +372,11 @@ public class QueryNetworkNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -435,10 +394,7 @@ public class QueryNetworkNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "key",
- "value"
- })
+ @XmlType(name = "", propOrder = {"key", "value"})
public static class Entry {
protected String key;
@@ -447,10 +403,8 @@ public class QueryNetworkNotification {
/**
* Gets the value of the key property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getKey() {
return key;
@@ -459,10 +413,8 @@ public class QueryNetworkNotification {
/**
* Sets the value of the key property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setKey(String value) {
this.key = value;
@@ -471,10 +423,8 @@ public class QueryNetworkNotification {
/**
* Gets the value of the value property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getValue() {
return value;
@@ -483,10 +433,8 @@ public class QueryNetworkNotification {
/**
* Sets the value of the value property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setValue(String value) {
this.value = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotificationResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotificationResponse.java
index 0320df27fc..2e18e05860 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotificationResponse.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotificationResponse.java
@@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for queryNetworkNotificationResponse complex type.
+ * <p>
+ * Java class for queryNetworkNotificationResponse complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="queryNetworkNotificationResponse">
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotification.java
index 08f37fc85d..7b5d0f0f2a 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotification.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotification.java
@@ -27,9 +27,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for rollbackNetworkNotification complex type.
+ * <p>
+ * Java class for rollbackNetworkNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="rollbackNetworkNotification">
@@ -49,12 +51,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "rollbackNetworkNotification", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage"
-})
+@XmlType(name = "rollbackNetworkNotification", propOrder = {"messageId", "completed", "exception", "errorMessage"})
public class RollbackNetworkNotification {
@XmlElement(required = true)
@@ -66,10 +63,8 @@ public class RollbackNetworkNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -78,10 +73,8 @@ public class RollbackNetworkNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -106,10 +99,8 @@ public class RollbackNetworkNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -118,10 +109,8 @@ public class RollbackNetworkNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -130,10 +119,8 @@ public class RollbackNetworkNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -142,10 +129,8 @@ public class RollbackNetworkNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotificationResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotificationResponse.java
index 44db3a1583..7ddc8d75de 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotificationResponse.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotificationResponse.java
@@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for rollbackNetworkNotificationResponse complex type.
+ * <p>
+ * Java class for rollbackNetworkNotificationResponse complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="rollbackNetworkNotificationResponse">
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotification.java
index daff548b45..1a464d3250 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotification.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotification.java
@@ -24,7 +24,6 @@ package org.onap.so.adapters.network.async.client;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -32,9 +31,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for updateNetworkNotification complex type.
+ * <p>
+ * Java class for updateNetworkNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="updateNetworkNotification">
@@ -77,14 +78,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "updateNetworkNotification", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage",
- "subnetIdMap",
- "rollback"
-})
+@XmlType(name = "updateNetworkNotification",
+ propOrder = {"messageId", "completed", "exception", "errorMessage", "subnetIdMap", "rollback"})
public class UpdateNetworkNotification {
@XmlElement(required = true)
@@ -98,10 +93,8 @@ public class UpdateNetworkNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -110,10 +103,8 @@ public class UpdateNetworkNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -138,10 +129,8 @@ public class UpdateNetworkNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -150,10 +139,8 @@ public class UpdateNetworkNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -162,10 +149,8 @@ public class UpdateNetworkNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -174,10 +159,8 @@ public class UpdateNetworkNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
@@ -186,10 +169,8 @@ public class UpdateNetworkNotification {
/**
* Gets the value of the subnetIdMap property.
*
- * @return
- * possible object is
- * {@link UpdateNetworkNotification.SubnetIdMap }
- *
+ * @return possible object is {@link UpdateNetworkNotification.SubnetIdMap }
+ *
*/
public UpdateNetworkNotification.SubnetIdMap getSubnetIdMap() {
return subnetIdMap;
@@ -198,10 +179,8 @@ public class UpdateNetworkNotification {
/**
* Sets the value of the subnetIdMap property.
*
- * @param value
- * allowed object is
- * {@link UpdateNetworkNotification.SubnetIdMap }
- *
+ * @param value allowed object is {@link UpdateNetworkNotification.SubnetIdMap }
+ *
*/
public void setSubnetIdMap(UpdateNetworkNotification.SubnetIdMap value) {
this.subnetIdMap = value;
@@ -210,10 +189,8 @@ public class UpdateNetworkNotification {
/**
* Gets the value of the rollback property.
*
- * @return
- * possible object is
- * {@link NetworkRollback }
- *
+ * @return possible object is {@link NetworkRollback }
+ *
*/
public NetworkRollback getRollback() {
return rollback;
@@ -222,10 +199,8 @@ public class UpdateNetworkNotification {
/**
* Sets the value of the rollback property.
*
- * @param value
- * allowed object is
- * {@link NetworkRollback }
- *
+ * @param value allowed object is {@link NetworkRollback }
+ *
*/
public void setRollback(NetworkRollback value) {
this.rollback = value;
@@ -233,9 +208,11 @@ public class UpdateNetworkNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -263,9 +240,7 @@ public class UpdateNetworkNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "entry"
- })
+ @XmlType(name = "", propOrder = {"entry"})
public static class SubnetIdMap {
protected List<UpdateNetworkNotification.SubnetIdMap.Entry> entry;
@@ -274,21 +249,20 @@ public class UpdateNetworkNotification {
* Gets the value of the entry property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the entry property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you
+ * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE>
+ * method for the entry property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getEntry().add(newItem);
+ * getEntry().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link UpdateNetworkNotification.SubnetIdMap.Entry }
+ * Objects of the following type(s) are allowed in the list {@link UpdateNetworkNotification.SubnetIdMap.Entry }
*
*
*/
@@ -301,9 +275,11 @@ public class UpdateNetworkNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -321,10 +297,7 @@ public class UpdateNetworkNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "key",
- "value"
- })
+ @XmlType(name = "", propOrder = {"key", "value"})
public static class Entry {
protected String key;
@@ -333,10 +306,8 @@ public class UpdateNetworkNotification {
/**
* Gets the value of the key property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getKey() {
return key;
@@ -345,10 +316,8 @@ public class UpdateNetworkNotification {
/**
* Sets the value of the key property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setKey(String value) {
this.key = value;
@@ -357,10 +326,8 @@ public class UpdateNetworkNotification {
/**
* Gets the value of the value property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getValue() {
return value;
@@ -369,10 +336,8 @@ public class UpdateNetworkNotification {
/**
* Sets the value of the value property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setValue(String value) {
this.value = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotificationResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotificationResponse.java
index e0016d9b8e..0ffcb5e9e6 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotificationResponse.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotificationResponse.java
@@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for updateNetworkNotificationResponse complex type.
+ * <p>
+ * Java class for updateNetworkNotificationResponse complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="updateNetworkNotificationResponse">
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkException.java
index cb4cd8b927..175535fef3 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkException.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkException.java
@@ -23,58 +23,58 @@ package org.onap.so.adapters.network.exceptions;
import javax.xml.ws.WebFault;
-
import org.onap.so.openstack.exceptions.MsoException;
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
/**
- * This class simply extends Exception (without addition additional functionality)
- * to provide an identifier for Network related exceptions on create, delete, query.
+ * This class simply extends Exception (without addition additional functionality) to provide an identifier for Network
+ * related exceptions on create, delete, query.
*
*
*/
-@WebFault (name="NetworkException", faultBean="org.onap.so.adapters.network.exceptions.NetworkExceptionBean", targetNamespace="http://org.onap.so/network")
+@WebFault(name = "NetworkException", faultBean = "org.onap.so.adapters.network.exceptions.NetworkExceptionBean",
+ targetNamespace = "http://org.onap.so/network")
public class NetworkException extends Exception {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ private NetworkExceptionBean faultInfo;
+
+ public NetworkException(String msg) {
+ super(msg);
+ faultInfo = new NetworkExceptionBean(msg);
+ }
+
+ public NetworkException(Throwable e) {
+ super(e);
+ faultInfo = new NetworkExceptionBean(e.getMessage());
+ }
+
+ public NetworkException(String msg, Throwable e) {
+ super(msg, e);
+ faultInfo = new NetworkExceptionBean(msg);
+ }
+
+ public NetworkException(String msg, MsoExceptionCategory category) {
+ super(msg);
+ faultInfo = new NetworkExceptionBean(msg, category);
+ }
+
+ public NetworkException(String msg, MsoExceptionCategory category, Throwable e) {
+ super(msg, e);
+ faultInfo = new NetworkExceptionBean(msg, category);
+ }
- private NetworkExceptionBean faultInfo;
-
- public NetworkException (String msg) {
- super(msg);
- faultInfo = new NetworkExceptionBean (msg);
- }
-
- public NetworkException (Throwable e) {
- super(e);
- faultInfo = new NetworkExceptionBean (e.getMessage());
- }
-
- public NetworkException (String msg, Throwable e) {
- super (msg, e);
- faultInfo = new NetworkExceptionBean (msg);
- }
+ public NetworkException(MsoException e) {
+ super(e);
+ faultInfo = new NetworkExceptionBean(e.getContextMessage(), e.getCategory());
+ }
- public NetworkException (String msg, MsoExceptionCategory category) {
- super(msg);
- faultInfo = new NetworkExceptionBean (msg, category);
- }
-
- public NetworkException (String msg, MsoExceptionCategory category, Throwable e) {
- super (msg, e);
- faultInfo = new NetworkExceptionBean (msg, category);
- }
-
- public NetworkException (MsoException e) {
- super (e);
- faultInfo = new NetworkExceptionBean (e.getContextMessage(), e.getCategory());
- }
-
- public NetworkExceptionBean getFaultInfo() {
- return faultInfo;
- }
+ public NetworkExceptionBean getFaultInfo() {
+ return faultInfo;
+ }
- public void setFaultInfo(NetworkExceptionBean faultInfo) {
- this.faultInfo = faultInfo;
- }
+ public void setFaultInfo(NetworkExceptionBean faultInfo) {
+ this.faultInfo = faultInfo;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBean.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBean.java
index 5256891ffa..6a3d567ebd 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBean.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBean.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.network.exceptions;
import java.io.Serializable;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
/**
@@ -33,41 +32,41 @@ public class NetworkExceptionBean implements Serializable {
private static final long serialVersionUID = 1655343530371342871L;
private String message;
- private MsoExceptionCategory category;
- private Boolean rolledBack;
+ private MsoExceptionCategory category;
+ private Boolean rolledBack;
- public NetworkExceptionBean () {}
+ public NetworkExceptionBean() {}
- public NetworkExceptionBean (String message) {
- this.message = message;
- }
+ public NetworkExceptionBean(String message) {
+ this.message = message;
+ }
- public NetworkExceptionBean (String message, MsoExceptionCategory category) {
- this.message = message;
- this.category = category;
- }
+ public NetworkExceptionBean(String message, MsoExceptionCategory category) {
+ this.message = message;
+ this.category = category;
+ }
- public String getMessage() {
- return message;
- }
+ public String getMessage() {
+ return message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public MsoExceptionCategory getCategory () {
- return category;
- }
+ public MsoExceptionCategory getCategory() {
+ return category;
+ }
- public void setCategory (MsoExceptionCategory category) {
- this.category = category;
- }
+ public void setCategory(MsoExceptionCategory category) {
+ this.category = category;
+ }
- public Boolean isRolledBack() {
- return rolledBack;
- }
+ public Boolean isRolledBack() {
+ return rolledBack;
+ }
- public void setRolledBack(Boolean rolledBack) {
- this.rolledBack = rolledBack;
- }
+ public void setRolledBack(Boolean rolledBack) {
+ this.rolledBack = rolledBack;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/AaiClientPropertiesImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/AaiClientPropertiesImpl.java
index c529413891..68b8598267 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/AaiClientPropertiesImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/AaiClientPropertiesImpl.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.openstack;
import java.net.MalformedURLException;
import java.net.URL;
-
import org.onap.so.client.aai.AAIProperties;
import org.onap.so.client.aai.AAIVersion;
import org.onap.so.spring.SpringContextHelper;
@@ -30,40 +29,40 @@ import org.springframework.context.ApplicationContext;
public class AaiClientPropertiesImpl implements AAIProperties {
- private String aaiEndpoint;
- private String auth;
- private String key;
- private static final String SYSTEM_NAME = "MSO";
-
- public AaiClientPropertiesImpl() {
- ApplicationContext context = SpringContextHelper.getAppContext();
- aaiEndpoint = context.getEnvironment().getProperty("aai.endpoint");
- this.auth = context.getEnvironment().getProperty("aai.auth");
- this.key = context.getEnvironment().getProperty("mso.msoKey");
- }
+ private String aaiEndpoint;
+ private String auth;
+ private String key;
+ private static final String SYSTEM_NAME = "MSO";
+
+ public AaiClientPropertiesImpl() {
+ ApplicationContext context = SpringContextHelper.getAppContext();
+ aaiEndpoint = context.getEnvironment().getProperty("aai.endpoint");
+ this.auth = context.getEnvironment().getProperty("aai.auth");
+ this.key = context.getEnvironment().getProperty("mso.msoKey");
+ }
+
+ @Override
+ public URL getEndpoint() throws MalformedURLException {
+ return new URL(aaiEndpoint);
+ }
+
+ @Override
+ public String getSystemName() {
+ return SYSTEM_NAME;
+ }
- @Override
- public URL getEndpoint() throws MalformedURLException {
- return new URL(aaiEndpoint);
- }
+ @Override
+ public AAIVersion getDefaultVersion() {
+ return AAIVersion.LATEST;
+ }
- @Override
- public String getSystemName() {
- return SYSTEM_NAME;
- }
-
- @Override
- public AAIVersion getDefaultVersion() {
- return AAIVersion.LATEST;
- }
-
- @Override
- public String getAuth() {
- return this.auth;
- }
+ @Override
+ public String getAuth() {
+ return this.auth;
+ }
- @Override
- public String getKey() {
- return this.key;
- }
+ @Override
+ public String getKey() {
+ return this.key;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java
index 72c74ccaf9..4396fc035d 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java
@@ -23,9 +23,7 @@
package org.onap.so.adapters.openstack;
import java.util.Arrays;
-
import javax.xml.ws.Endpoint;
-
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.endpoint.Server;
@@ -47,62 +45,59 @@ import org.onap.so.adapters.vnf.VnfAdapterRestV2;
import org.onap.so.adapters.vnf.VolumeAdapterRest;
import org.onap.so.adapters.vnf.VolumeAdapterRestV2;
import org.onap.so.client.policy.JettisonStyleMapperProvider;
-
import org.onap.so.logging.cxf.interceptor.SOAPLoggingInInterceptor;
import org.onap.so.logging.cxf.interceptor.SOAPLoggingOutInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
@Configuration
public class CXFConfiguration {
- @Autowired
- private NetworkAdapterRest networkAdapterRest;
- @Autowired
- private TenantAdapterRest tenantAdapterRest;
- @Autowired
- private VnfAdapterRest vnfAdapterRest;
- @Autowired
- private VnfAdapterRestV2 vnfAdapterRestV2;
- @Autowired
- private VolumeAdapterRest volumeAdapterRest;
- @Autowired
- private VolumeAdapterRestV2 volumeAdapterRestV2;
- @Autowired
- private MsoNetworkAdapterImpl networkAdapterImpl;
- @Autowired
- private MsoNetworkAdapterAsyncImpl networkAdapterAsyncImpl;
- @Autowired
- private MsoTenantAdapterImpl tenantAdapterImpl;
- @Autowired
- private MsoVnfAdapterImpl vnfAdapterImpl;
- @Autowired
- private MsoVnfAdapterAsyncImpl vnfAdapterAsyncImpl;
- @Autowired
- private MsoVnfCloudifyAdapterImpl vnfCloudifyAdapterImpl;
- @Autowired
- private JettisonStyleMapperProvider jettisonStyleObjectMapper;
+ @Autowired
+ private NetworkAdapterRest networkAdapterRest;
+ @Autowired
+ private TenantAdapterRest tenantAdapterRest;
+ @Autowired
+ private VnfAdapterRest vnfAdapterRest;
+ @Autowired
+ private VnfAdapterRestV2 vnfAdapterRestV2;
+ @Autowired
+ private VolumeAdapterRest volumeAdapterRest;
+ @Autowired
+ private VolumeAdapterRestV2 volumeAdapterRestV2;
+ @Autowired
+ private MsoNetworkAdapterImpl networkAdapterImpl;
+ @Autowired
+ private MsoNetworkAdapterAsyncImpl networkAdapterAsyncImpl;
+ @Autowired
+ private MsoTenantAdapterImpl tenantAdapterImpl;
+ @Autowired
+ private MsoVnfAdapterImpl vnfAdapterImpl;
+ @Autowired
+ private MsoVnfAdapterAsyncImpl vnfAdapterAsyncImpl;
+ @Autowired
+ private MsoVnfCloudifyAdapterImpl vnfCloudifyAdapterImpl;
+ @Autowired
+ private JettisonStyleMapperProvider jettisonStyleObjectMapper;
- @Bean(name=Bus.DEFAULT_BUS_ID)
- public SpringBus springBus() {
+ @Bean(name = Bus.DEFAULT_BUS_ID)
+ public SpringBus springBus() {
return new SpringBus();
- }
-
- @Bean
- public ServletRegistrationBean SoapDispatcherServlet() {
- ServletRegistrationBean servletRegistrationBean =
- new ServletRegistrationBean(new CXFServlet(), "/services/*");
+ }
+
+ @Bean
+ public ServletRegistrationBean SoapDispatcherServlet() {
+ ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new CXFServlet(), "/services/*");
servletRegistrationBean.setName("services");
- return servletRegistrationBean;
- }
+ return servletRegistrationBean;
+ }
- /*
- * network adapter endpoint
- */
+ /*
+ * network adapter endpoint
+ */
@Bean
public Endpoint networkAdapterEndpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(), networkAdapterImpl);
@@ -112,8 +107,8 @@ public class CXFConfiguration {
endpoint.getOutInterceptors().add(new SOAPLoggingOutInterceptor());
endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor());
return endpoint;
- }
-
+ }
+
@Bean
public Endpoint networkAdapterAsyncEndpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(), networkAdapterAsyncImpl);
@@ -123,8 +118,8 @@ public class CXFConfiguration {
endpoint.getOutInterceptors().add(new SOAPLoggingOutInterceptor());
endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor());
return endpoint;
- }
-
+ }
+
/*
* tenant adapter endpoint
*/
@@ -138,11 +133,9 @@ public class CXFConfiguration {
endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor());
return endpoint;
}
-
+
/*
- * vnfAdapterEndpoint
- * VnfAsyncAdapterEndpoint
- * VnfCloudAdapterEndpoint
+ * vnfAdapterEndpoint VnfAsyncAdapterEndpoint VnfCloudAdapterEndpoint
*/
@Bean
public Endpoint vnfAdapterEndpoint() {
@@ -154,7 +147,7 @@ public class CXFConfiguration {
endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor());
return endpoint;
}
-
+
@Bean
public Endpoint VnfAsyncAdapterEndpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(), vnfAdapterAsyncImpl);
@@ -165,7 +158,7 @@ public class CXFConfiguration {
endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor());
return endpoint;
}
-
+
@Bean
public Endpoint VnfCloudAdapterEndpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(), vnfCloudifyAdapterImpl);
@@ -176,34 +169,31 @@ public class CXFConfiguration {
endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor());
return endpoint;
}
-
+
@Bean
public Server rsServer() {
JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
endpoint.setBus(springBus());
- endpoint.setServiceBeans(Arrays.<Object>asList(networkAdapterRest,
- tenantAdapterRest,
- vnfAdapterRest,
- vnfAdapterRestV2,
- volumeAdapterRest,
- volumeAdapterRestV2));
+ endpoint.setServiceBeans(Arrays.<Object>asList(networkAdapterRest, tenantAdapterRest, vnfAdapterRest,
+ vnfAdapterRestV2, volumeAdapterRest, volumeAdapterRestV2));
endpoint.setAddress("/rest");
endpoint.setFeatures(Arrays.asList(createSwaggerFeature(), new LoggingFeature()));
endpoint.setProvider(new JacksonJsonProvider(jettisonStyleObjectMapper.getMapper()));
return endpoint.create();
- }
-
-
+ }
+
+
@Bean
public Swagger2Feature createSwaggerFeature() {
- Swagger2Feature swagger2Feature= new Swagger2Feature();
+ Swagger2Feature swagger2Feature = new Swagger2Feature();
swagger2Feature.setPrettyPrint(true);
swagger2Feature.setTitle("SO Orchestration Application");
swagger2Feature.setContact("The ONAP SO team");
swagger2Feature.setDescription("This project is the SO Orchestration Engine");
swagger2Feature.setVersion("1.0.0");
- swagger2Feature.setResourcePackage("org.onap.so.adapters.network,org.onap.so.adapters.tenant,org.onap.so.adapters.vnf");
+ swagger2Feature.setResourcePackage(
+ "org.onap.so.adapters.network,org.onap.so.adapters.tenant,org.onap.so.adapters.vnf");
swagger2Feature.setScan(true);
return swagger2Feature;
- }
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java
index 9408f0d681..97a2500c59 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters.openstack;
import java.util.concurrent.Executor;
-
import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@@ -34,46 +33,45 @@ import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
-@SpringBootApplication(scanBasePackages = { "org.onap.so" })
+@SpringBootApplication(scanBasePackages = {"org.onap.so"})
@EnableAsync
@EnableScheduling
-@EnableJpaRepositories({ "org.onap.so.db.catalog.data.repository",
- "org.onap.so.db.request.data.repository"})
-@EntityScan({ "org.onap.so.db.catalog.beans", "org.onap.so.db.request.beans"})
+@EnableJpaRepositories({"org.onap.so.db.catalog.data.repository", "org.onap.so.db.request.data.repository"})
+@EntityScan({"org.onap.so.db.catalog.beans", "org.onap.so.db.request.beans"})
public class MsoOpenstackAdaptersApplication {
- @Value("${mso.async.core-pool-size}")
- private int corePoolSize;
+ @Value("${mso.async.core-pool-size}")
+ private int corePoolSize;
- @Value("${mso.async.max-pool-size}")
- private int maxPoolSize;
+ @Value("${mso.async.max-pool-size}")
+ private int maxPoolSize;
- @Value("${mso.async.queue-capacity}")
- private int queueCapacity;
+ @Value("${mso.async.queue-capacity}")
+ private int queueCapacity;
- private static final String LOGS_DIR = "logs_dir";
+ private static final String LOGS_DIR = "logs_dir";
- private static void setLogsDir() {
- if (System.getProperty(LOGS_DIR) == null) {
- System.getProperties().setProperty(LOGS_DIR, "./logs/openstack/");
- }
- }
+ private static void setLogsDir() {
+ if (System.getProperty(LOGS_DIR) == null) {
+ System.getProperties().setProperty(LOGS_DIR, "./logs/openstack/");
+ }
+ }
- public static void main(String[] args) {
- SpringApplication.run(MsoOpenstackAdaptersApplication.class, args);
- setLogsDir();
- }
+ public static void main(String[] args) {
+ SpringApplication.run(MsoOpenstackAdaptersApplication.class, args);
+ setLogsDir();
+ }
- @Bean
- public Executor asyncExecutor() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setTaskDecorator(new MDCTaskDecorator());
- executor.setCorePoolSize(corePoolSize);
- executor.setMaxPoolSize(maxPoolSize);
- executor.setQueueCapacity(queueCapacity);
- executor.setThreadNamePrefix("OpenstackAdapters-");
- executor.initialize();
- return executor;
- }
+ @Bean
+ public Executor asyncExecutor() {
+ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+ executor.setTaskDecorator(new MDCTaskDecorator());
+ executor.setCorePoolSize(corePoolSize);
+ executor.setMaxPoolSize(maxPoolSize);
+ executor.setQueueCapacity(queueCapacity);
+ executor.setThreadNamePrefix("OpenstackAdapters-");
+ executor.initialize();
+ return executor;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java
index aca16d9996..97e43d9828 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java
@@ -19,7 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.adapters.openstack;
import org.onap.so.security.MSOSpringFirewall;
@@ -33,21 +33,18 @@ import org.springframework.util.StringUtils;
@EnableWebSecurity
public class WebSecurityConfigImpl extends WebSecurityConfig {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf().disable()
- .authorizeRequests()
- .antMatchers("/manage/health","/manage/info").permitAll()
- .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),","))
- .and()
- .httpBasic();
- }
-
- @Override
- public void configure(WebSecurity web) throws Exception {
- super.configure(web);
- StrictHttpFirewall firewall = new MSOSpringFirewall();
- web.httpFirewall(firewall);
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll()
+ .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and()
+ .httpBasic();
+ }
+
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ super.configure(web);
+ StrictHttpFirewall firewall = new MSOSpringFirewall();
+ web.httpFirewall(firewall);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapter.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapter.java
index d82d478a93..68f7558add 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapter.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapter.java
@@ -24,55 +24,48 @@ package org.onap.so.adapters.tenant;
import java.util.Map;
-
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebParam.Mode;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.ws.Holder;
-
import org.onap.so.adapters.tenant.exceptions.TenantException;
import org.onap.so.adapters.tenantrest.TenantRollback;
import org.onap.so.entity.MsoRequest;
-@WebService (name="TenantAdapter", targetNamespace="http://org.onap.so/tenant")
-public interface MsoTenantAdapter
-{
- /**
- * This is the "Create Tenant" Web Service Endpoint definition.
- */
- @WebMethod
- public void createTenant (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantName") @XmlElement(required=true) String tenantName,
- @WebParam(name="metadata") Map<String,String> metadata,
- @WebParam(name="failIfExists") Boolean failIfExists,
- @WebParam(name="backout") Boolean backout,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="tenantId", mode=Mode.OUT) Holder<String> tenantId,
- @WebParam(name="rollback", mode=Mode.OUT) Holder<TenantRollback> rollback )
- throws TenantException;
-
- @WebMethod
- public void queryTenant (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantNameOrId") @XmlElement(required=true) String tenantNameOrId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="tenantId", mode=Mode.OUT) Holder<String> tenantId,
- @WebParam(name="tenantName", mode=Mode.OUT) Holder<String> tenantName,
- @WebParam(name="metadata", mode=Mode.OUT) Holder<Map<String,String>> metadata )
- throws TenantException;
-
- @WebMethod
- public void deleteTenant (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="tenantDeleted", mode=Mode.OUT) Holder<Boolean> tenantDeleted)
- throws TenantException;
-
- @WebMethod
- public void rollbackTenant (@WebParam(name="rollback") @XmlElement(required=true) TenantRollback rollback)
- throws TenantException;
-
- @WebMethod
- public void healthCheck ();
+@WebService(name = "TenantAdapter", targetNamespace = "http://org.onap.so/tenant")
+public interface MsoTenantAdapter {
+ /**
+ * This is the "Create Tenant" Web Service Endpoint definition.
+ */
+ @WebMethod
+ public void createTenant(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantName") @XmlElement(required = true) String tenantName,
+ @WebParam(name = "metadata") Map<String, String> metadata,
+ @WebParam(name = "failIfExists") Boolean failIfExists, @WebParam(name = "backout") Boolean backout,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "tenantId", mode = Mode.OUT) Holder<String> tenantId,
+ @WebParam(name = "rollback", mode = Mode.OUT) Holder<TenantRollback> rollback) throws TenantException;
+
+ @WebMethod
+ public void queryTenant(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantNameOrId") @XmlElement(required = true) String tenantNameOrId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "tenantId", mode = Mode.OUT) Holder<String> tenantId,
+ @WebParam(name = "tenantName", mode = Mode.OUT) Holder<String> tenantName,
+ @WebParam(name = "metadata", mode = Mode.OUT) Holder<Map<String, String>> metadata) throws TenantException;
+
+ @WebMethod
+ public void deleteTenant(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "tenantDeleted", mode = Mode.OUT) Holder<Boolean> tenantDeleted) throws TenantException;
+
+ @WebMethod
+ public void rollbackTenant(@WebParam(name = "rollback") @XmlElement(required = true) TenantRollback rollback)
+ throws TenantException;
+
+ @WebMethod
+ public void healthCheck();
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapterImpl.java
index ceae1caca6..04b90b444f 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapterImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapterImpl.java
@@ -45,96 +45,93 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-@WebService(serviceName = "TenantAdapter", endpointInterface = "org.onap.so.adapters.tenant.MsoTenantAdapter", targetNamespace = "http://org.onap.so/tenant")
+@WebService(serviceName = "TenantAdapter", endpointInterface = "org.onap.so.adapters.tenant.MsoTenantAdapter",
+ targetNamespace = "http://org.onap.so/tenant")
@Component
public class MsoTenantAdapterImpl implements MsoTenantAdapter {
- public static final String CREATE_TENANT = "createTenant";
+ public static final String CREATE_TENANT = "createTenant";
public static final String OPENSTACK = "OpenStack";
public static final String QUERY_TENANT = "QueryTenant";
public static final String DELETE_TENANT = "DeleteTenant";
public static final String ROLLBACK_TENANT = "RollbackTenant";
- private static final String OPENSTACK_COMMUNICATE_EXCEPTION_MSG = "{} {} Exception while communicate with Open Stack ";
+ private static final String OPENSTACK_COMMUNICATE_EXCEPTION_MSG =
+ "{} {} Exception while communicate with Open Stack ";
@Resource
private WebServiceContext wsContext;
@Autowired
- private MsoTenantUtilsFactory tFactory;
+ private MsoTenantUtilsFactory tFactory;
private static Logger logger = LoggerFactory.getLogger(MsoTenantAdapterImpl.class);
+
/**
* Health Check web method. Does nothing but return to show the adapter is deployed.
*/
@Override
- public void healthCheck () {
- logger.debug ("Health check call in Tenant Adapter");
+ public void healthCheck() {
+ logger.debug("Health check call in Tenant Adapter");
}
/**
- * This is the "Create Tenant" web service implementation. It will create
- * a new Tenant in the specified cloud. If the tenant already exists, this
- * can be considered a success or failure, depending on the value of the
+ * This is the "Create Tenant" web service implementation. It will create a new Tenant in the specified cloud. If
+ * the tenant already exists, this can be considered a success or failure, depending on the value of the
* 'failIfExists' parameter.
*
- * The method returns the tenantId (the Openstack ID), and a TenantRollback
- * object. This last object can be passed as-is to the rollbackTenant method
- * to undo what (if anything) was created. This is useful if a Tenant is
+ * The method returns the tenantId (the Openstack ID), and a TenantRollback object. This last object can be passed
+ * as-is to the rollbackTenant method to undo what (if anything) was created. This is useful if a Tenant is
* successfully created but the orchestrator fails on a subsequent operation.
*/
@Override
- public void createTenant (String cloudSiteId,
- String tenantName,
- Map <String, String> metadata,
- Boolean failIfExists,
- Boolean backout,
- MsoRequest msoRequest,
- Holder <String> tenantId,
- Holder <TenantRollback> rollback) throws TenantException {
+ public void createTenant(String cloudSiteId, String tenantName, Map<String, String> metadata, Boolean failIfExists,
+ Boolean backout, MsoRequest msoRequest, Holder<String> tenantId, Holder<TenantRollback> rollback)
+ throws TenantException {
logger.debug("Call to MSO createTenant adapter. Creating Tenant: {} in {}", tenantName, cloudSiteId);
// Start building up rollback object
- TenantRollback tenantRollback = new TenantRollback ();
- tenantRollback.setCloudId (cloudSiteId);
- tenantRollback.setMsoRequest (msoRequest);
-
+ TenantRollback tenantRollback = new TenantRollback();
+ tenantRollback.setCloudId(cloudSiteId);
+ tenantRollback.setMsoRequest(msoRequest);
+
MsoTenantUtils tUtils;
- try {
- tUtils = tFactory.getTenantUtils (cloudSiteId);
- } catch (MsoCloudSiteNotFound me) {
- logger.error("{} {} no implementation found for {}: ", MessageEnum.RA_CREATE_TENANT_ERR,
- ErrorCode.DataError.getValue(), cloudSiteId, me);
- throw new TenantException (me);
- }
+ try {
+ tUtils = tFactory.getTenantUtils(cloudSiteId);
+ } catch (MsoCloudSiteNotFound me) {
+ logger.error("{} {} no implementation found for {}: ", MessageEnum.RA_CREATE_TENANT_ERR,
+ ErrorCode.DataError.getValue(), cloudSiteId, me);
+ throw new TenantException(me);
+ }
MsoTenant newTenant = null;
String newTenantId;
try {
- newTenant = tUtils.queryTenantByName (tenantName, cloudSiteId);
+ newTenant = tUtils.queryTenantByName(tenantName, cloudSiteId);
} catch (MsoException me) {
logger.error(OPENSTACK_COMMUNICATE_EXCEPTION_MSG, MessageEnum.RA_CREATE_TENANT_ERR,
- ErrorCode.DataError.getValue(), me);
- throw new TenantException (me);
+ ErrorCode.DataError.getValue(), me);
+ throw new TenantException(me);
}
if (newTenant == null) {
if (backout == null)
backout = true;
try {
- newTenantId = tUtils.createTenant (tenantName, cloudSiteId, metadata, backout.booleanValue ());
+ newTenantId = tUtils.createTenant(tenantName, cloudSiteId, metadata, backout.booleanValue());
} catch (MsoException me) {
- logger.error (OPENSTACK_COMMUNICATE_EXCEPTION_MSG, MessageEnum.RA_CREATE_TENANT_ERR, ErrorCode.DataError.getValue(), me);
- throw new TenantException (me);
+ logger.error(OPENSTACK_COMMUNICATE_EXCEPTION_MSG, MessageEnum.RA_CREATE_TENANT_ERR,
+ ErrorCode.DataError.getValue(), me);
+ throw new TenantException(me);
}
- tenantRollback.setTenantId (newTenantId);
- tenantRollback.setTenantCreated (true);
- logger.debug ("Tenant {} successfully created with ID {}", tenantName, newTenantId);
+ tenantRollback.setTenantId(newTenantId);
+ tenantRollback.setTenantCreated(true);
+ logger.debug("Tenant {} successfully created with ID {}", tenantName, newTenantId);
} else {
if (failIfExists != null && failIfExists) {
logger.error("{} {} CreateTenant: Tenant {} already exists in {} ", MessageEnum.RA_TENANT_ALREADY_EXIST,
- ErrorCode.DataError.getValue(), tenantName, cloudSiteId);
- throw new TenantAlreadyExists (tenantName, cloudSiteId, newTenant.getTenantId ());
+ ErrorCode.DataError.getValue(), tenantName, cloudSiteId);
+ throw new TenantAlreadyExists(tenantName, cloudSiteId, newTenant.getTenantId());
}
- newTenantId = newTenant.getTenantId ();
- tenantRollback.setTenantCreated (false);
+ newTenantId = newTenant.getTenantId();
+ tenantRollback.setTenantCreated(false);
logger.debug("Tenant {} already exists with ID {}", tenantName, newTenantId);
}
@@ -145,69 +142,63 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter {
}
@Override
- public void queryTenant (String cloudSiteId,
- String tenantNameOrId,
- MsoRequest msoRequest,
- Holder <String> tenantId,
- Holder <String> tenantName,
- Holder <Map <String, String>> metadata) throws TenantException {
+ public void queryTenant(String cloudSiteId, String tenantNameOrId, MsoRequest msoRequest, Holder<String> tenantId,
+ Holder<String> tenantName, Holder<Map<String, String>> metadata) throws TenantException {
- logger.debug ("Querying Tenant {} in {}", tenantNameOrId, cloudSiteId);
+ logger.debug("Querying Tenant {} in {}", tenantNameOrId, cloudSiteId);
MsoTenantUtils tUtils;
- try {
- tUtils = tFactory.getTenantUtils (cloudSiteId);
- } catch (MsoCloudSiteNotFound me) {
- logger.error("{} {} no implementation found for {}: ", MessageEnum.RA_CREATE_TENANT_ERR,
- ErrorCode.DataError.getValue(), cloudSiteId, me);
- throw new TenantException (me);
- }
-
+ try {
+ tUtils = tFactory.getTenantUtils(cloudSiteId);
+ } catch (MsoCloudSiteNotFound me) {
+ logger.error("{} {} no implementation found for {}: ", MessageEnum.RA_CREATE_TENANT_ERR,
+ ErrorCode.DataError.getValue(), cloudSiteId, me);
+ throw new TenantException(me);
+ }
+
MsoTenant qTenant = null;
try {
- qTenant = tUtils.queryTenant (tenantNameOrId, cloudSiteId);
+ qTenant = tUtils.queryTenant(tenantNameOrId, cloudSiteId);
if (qTenant == null) {
// Not found by ID, Try by name.
- qTenant = tUtils.queryTenantByName (tenantNameOrId, cloudSiteId);
+ qTenant = tUtils.queryTenantByName(tenantNameOrId, cloudSiteId);
}
if (qTenant == null) {
- logger.debug ("QueryTenant: Tenant {} not found", tenantNameOrId);
+ logger.debug("QueryTenant: Tenant {} not found", tenantNameOrId);
tenantId.value = null;
tenantName.value = null;
metadata.value = null;
} else {
logger.debug("QueryTenant: Tenant {} found with ID {}", tenantNameOrId, qTenant.getTenantId());
- tenantId.value = qTenant.getTenantId ();
- tenantName.value = qTenant.getTenantName ();
- metadata.value = qTenant.getMetadata ();
+ tenantId.value = qTenant.getTenantId();
+ tenantName.value = qTenant.getTenantName();
+ metadata.value = qTenant.getMetadata();
}
} catch (MsoException me) {
logger.error("Exception in queryTenant for {}: ", MessageEnum.RA_GENERAL_EXCEPTION,
- ErrorCode.DataError.getValue(), tenantNameOrId, me);
- throw new TenantException (me);
+ ErrorCode.DataError.getValue(), tenantNameOrId, me);
+ throw new TenantException(me);
}
return;
}
@Override
- public void deleteTenant (String cloudSiteId,
- String tenantId,
- MsoRequest msoRequest,
- Holder <Boolean> tenantDeleted) throws TenantException {
+ public void deleteTenant(String cloudSiteId, String tenantId, MsoRequest msoRequest, Holder<Boolean> tenantDeleted)
+ throws TenantException {
- logger.debug ("Deleting Tenant {} in {}", tenantId, cloudSiteId);
+ logger.debug("Deleting Tenant {} in {}", tenantId, cloudSiteId);
// Delete the Tenant.
try {
-
- MsoTenantUtils tUtils = tFactory.getTenantUtils (cloudSiteId);
- boolean deleted = tUtils.deleteTenant (tenantId, cloudSiteId);
+
+ MsoTenantUtils tUtils = tFactory.getTenantUtils(cloudSiteId);
+ boolean deleted = tUtils.deleteTenant(tenantId, cloudSiteId);
tenantDeleted.value = deleted;
} catch (MsoException me) {
logger.error("{} {} Exception - DeleteTenant {}: ", MessageEnum.RA_DELETE_TEMAMT_ERR,
- ErrorCode.DataError.getValue(), tenantId, me);
- throw new TenantException (me);
+ ErrorCode.DataError.getValue(), tenantId, me);
+ throw new TenantException(me);
}
// On success, nothing is returned.
@@ -215,40 +206,39 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter {
}
/**
- * This web service endpoint will rollback a previous Create VNF operation.
- * A rollback object is returned to the client in a successful creation
- * response. The client can pass that object as-is back to the rollbackVnf
- * operation to undo the creation.
+ * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the
+ * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation
+ * to undo the creation.
*
- * The rollback includes removing the VNF and deleting the tenant if the
- * tenant did not exist prior to the VNF creation.
+ * The rollback includes removing the VNF and deleting the tenant if the tenant did not exist prior to the VNF
+ * creation.
*/
@Override
- public void rollbackTenant (TenantRollback rollback) throws TenantException {
+ public void rollbackTenant(TenantRollback rollback) throws TenantException {
// rollback may be null (e.g. if stack already existed when Create was called)
if (rollback == null) {
logger.warn("{} {} rollbackTenant, rollback is null", MessageEnum.RA_ROLLBACK_NULL,
- ErrorCode.DataError.getValue());
+ ErrorCode.DataError.getValue());
return;
}
// Get the elements of the VnfRollback object for easier access
- String cloudSiteId = rollback.getCloudId ();
- String tenantId = rollback.getTenantId ();
+ String cloudSiteId = rollback.getCloudId();
+ String tenantId = rollback.getTenantId();
logger.debug("Rolling Back Tenant {} in {}", rollback.getTenantId(), cloudSiteId);
- if (rollback.getTenantCreated ()) {
+ if (rollback.getTenantCreated()) {
try {
-
- MsoTenantUtils tUtils = tFactory.getTenantUtils (cloudSiteId);
- tUtils.deleteTenant (tenantId, cloudSiteId);
+
+ MsoTenantUtils tUtils = tFactory.getTenantUtils(cloudSiteId);
+ tUtils.deleteTenant(tenantId, cloudSiteId);
} catch (MsoException me) {
- me.addContext (ROLLBACK_TENANT);
+ me.addContext(ROLLBACK_TENANT);
// Failed to delete the tenant.
logger.error("{} {} Exception - rollbackTenant {}: ", MessageEnum.RA_ROLLBACK_TENANT_ERR,
- ErrorCode.DataError.getValue(), tenantId, me);
- throw new TenantException (me);
+ ErrorCode.DataError.getValue(), tenantId, me);
+ throw new TenantException(me);
}
}
return;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/TenantAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/TenantAdapterRest.java
index 11051df34e..6a38cc60e6 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/TenantAdapterRest.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/TenantAdapterRest.java
@@ -65,8 +65,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
- * This class services calls to the REST interface for Tenants (http://host:port/vnfs/rest/v1/tenants)
- * Both XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default.
+ * This class services calls to the REST interface for Tenants (http://host:port/vnfs/rest/v1/tenants) Both XML and JSON
+ * can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default.
*/
@Path("/v1/tenants")
@Api(value = "/v1/tenants", description = "root of tenant adapters restful web service")
@@ -74,265 +74,176 @@ import org.springframework.stereotype.Component;
public class TenantAdapterRest {
private static Logger logger = LoggerFactory.getLogger(TenantAdapterRest.class);
- private static final String EXCEPTION= "Exception :";
- //RAA? No logging in wrappers
- @Autowired
- private MsoTenantAdapterImpl tenantImpl;
-
-
-
- /*
- URL:
- EP: http://host:8080/tenants/rest
- Resource: v1/tenants
- REQ - metadata?
- {
- "cloudSiteId": "DAN",
- "tenantName": "RAA_1",
- "failIfExists": true,
- "msoRequest": {
- "requestId": "ra1",
- "serviceInstanceId": "sa1"
- }}
- RESP-
- {
- "cloudSiteId": "DAN",
- "tenantId": "128e10b9996d43a7874f19bbc4eb6749",
- "tenantCreated": true,
- "tenantRollback": {
- "tenantId": "128e10b9996d43a7874f19bbc4eb6749",
- "cloudId": "DAN", // RAA? cloudId instead of cloudSiteId
- "tenantCreated": true,
- "msoRequest": {
- "requestId": "ra1",
- "serviceInstanceId": "sa1"
- }
- }
- }
- */
- @POST
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "CreateTenant",
- response = Response.class,
- notes = "Creates a new tenant, CreateTenantRequest data is required")
- @ApiResponses({
- @ApiResponse(code = 200, message = "tenant has been successfully created"),
- @ApiResponse(code = 500, message = "create tenant failed") })
- public Response createTenant(
- @ApiParam(value = "details of tenant being created", required = true)
- CreateTenantRequest req) {
- logger.debug("createTenant enter: {}", req.toJsonString());
-
- String newTenantId = null;
- TenantRollback tenantRollback = new TenantRollback ();
-
- try {
- Holder<String> htenant = new Holder<>();
- Holder<TenantRollback> hrollback = new Holder<>();
- MsoTenantAdapter impl = tenantImpl;
- impl.createTenant(
- req.getCloudSiteId(),
- req.getTenantName(),
- req.getMetadata(),
- req.getFailIfExists(),
- req.getBackout(),
- req.getMsoRequest(),
- htenant,
- hrollback);
- newTenantId = htenant.value;
- tenantRollback = hrollback.value;
-
- }
- catch (TenantAlreadyExists tae) {
- logger.debug(EXCEPTION, tae);
- CreateTenantError exc = new CreateTenantError(tae.getMessage(), tae.getFaultInfo().getCategory(), Boolean.TRUE);
- return Response.status(HttpServletResponse.SC_NOT_IMPLEMENTED).entity(exc).build();
- }
- catch (TenantException te) {
- logger.debug(EXCEPTION, te);
- CreateTenantError exc = new CreateTenantError(te.getFaultInfo().getMessage(), te.getFaultInfo().getCategory(), Boolean.TRUE);
- return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
- }
- catch (Exception e) {
- logger.debug(EXCEPTION, e);
- CreateTenantError exc = new CreateTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE);
- return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
- }
-
- CreateTenantResponse resp = new CreateTenantResponse (req.getCloudSiteId(), newTenantId, tenantRollback.getTenantCreated(), tenantRollback);
- return Response.status(HttpServletResponse.SC_OK).entity(resp).build();
- }
-
- /*
- URL:
- http://host:8080/tenants/rest
- Resource: v1/tenant/tennatId
- REQ:
- {"cloudSiteId": "DAN",
- "tenantId": "ca84cd3d3df44272845da554656b3ace",
- "msoRequest": {
- "requestId": "ra1",
- "serviceInstanceId": "sa1"
- }
- }
- RESP:
- {"tenantDeleted": true}
- */
- @DELETE
- @Path("{tenantId}")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "DeleteTenant",
- response = Response.class,
- notes = "Delete an existing tenant")
- @ApiResponses({
- @ApiResponse(code = 200, message = "tenant has been successfully deleted"),
- @ApiResponse(code = 500, message = "delete tenant failed") })
- public Response deleteTenant(
- @ApiParam(value = "tenantId of tenant being deleted", required = true)
- @PathParam("tenantId") String tenantId,
- @ApiParam(value = "DeleteTenantRequest object containing additional information of tenant being deleted", required = false)
- DeleteTenantRequest req)
- {
- boolean tenantDeleted = false;
-
- try {
- Holder<Boolean> deleted = new Holder<>();
- MsoTenantAdapter impl = tenantImpl;
- impl.deleteTenant(
- req.getCloudSiteId(),
- req.getTenantId(),
- req.getMsoRequest(),
- deleted);
- tenantDeleted = deleted.value;
- }
- catch (TenantException te) {
- logger.debug(EXCEPTION, te);
- DeleteTenantError exc = new DeleteTenantError(te.getFaultInfo().getMessage(), te.getFaultInfo().getCategory(), Boolean.TRUE);
- return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
- }
- catch (Exception e) {
- logger.debug(EXCEPTION, e);
- DeleteTenantError exc = new DeleteTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE);
- return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
- }
- DeleteTenantResponse resp = new DeleteTenantResponse();
- resp.setTenantDeleted(tenantDeleted);
- return Response.status(HttpServletResponse.SC_OK).entity(resp).build();
- }
-
- /*
- URL
- EP://http://host:8080/tenants/rest
- Resource: /v1/tenants
- Params:?tenantNameOrId=RAA_1&cloudSiteId=DAN
- RESP
- {
- "tenantId": "214b428a1f554c02935e66330f6a5409",
- "tenantName": "RAA_1",
- "metadata": {}
- }
- */
- @GET
- @Path("{tenantId}")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "QueryTenant",
- response = Response.class,
- notes = "Query an existing tenant")
- @ApiResponses({
- @ApiResponse(code = 200, message = "tenant has been successfully queried"),
- @ApiResponse(code = 500, message = "query tenant failed") })
- public Response queryTenant(
- @ApiParam(value = "tenantId", required = true)
- @PathParam("tenantId") String tenantId,
-// @QueryParam("tenantNameOrId") String tenantNameOrId, //RAA? diff from doc
- @ApiParam(value = "cloudSiteId", required = true)
- @QueryParam("cloudSiteId") String cloudSiteId,
- @ApiParam(value = "msoRequest.requestId", required = true)
- @QueryParam("msoRequest.requestId") String requestId,
- @ApiParam(value = "msoRequest.serviceInstanceId", required = true)
- @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId)
- {
- MsoTenant tenant = null;
- try {
- Holder<String> htenant = new Holder<>();
- Holder<String> tenantName = new Holder<>();
- Holder<Map<String,String>> metadata = new Holder<>();
- MsoTenantAdapter impl = tenantImpl;
- impl.queryTenant(
- cloudSiteId,
- tenantId,
- null,
- htenant,
- tenantName,
- metadata
- );
- tenant = new MsoTenant(htenant.value, tenantName.value, metadata.value);
-
- }
- catch (TenantException te) {
- logger.debug(EXCEPTION, te);
- QueryTenantError exc = new QueryTenantError(te.getFaultInfo().getMessage(), te.getFaultInfo().getCategory());
- return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
- }
- catch (Exception e) {
- logger.debug(EXCEPTION, e);
- QueryTenantError exc = new QueryTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL);
- return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
- }
- QueryTenantResponse resp = new QueryTenantResponse(tenant.getTenantId(), tenant.getTenantName(), tenant.getMetadata());
- return Response.status(HttpServletResponse.SC_OK).entity(resp).build();
- }
-
- /*
- URL
- EP: //http://host:8080/tenants/rest
- Resource: /v1/tenants/rollback
- REQ
- {"cloudSiteId": "DAN",
- "tenantId": "f58abb05041d4ff384d4d22d1ccd2a6c",
- "msoRequest": {
- "requestId": "ra1",
- "serviceInstanceId": "sa1"
- }
- }
- RESP:
- {"tenantDeleted": true}
- */
- @DELETE
- @Path("")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "RollbackTenant",
- response = Response.class,
- notes = "Rollback an existing tenant")
- @ApiResponses({
- @ApiResponse(code = 200, message = "tenant has been successfully rolledback"),
- @ApiResponse(code = 500, message = "rollback tenant failed") })
- public Response rollbackTenant(
- @ApiParam(value = "rollback, command action", required = true)
- @QueryParam("rollback") String action,
- @ApiParam(value = "RollbackTenantRequest", required = true)
- RollbackTenantRequest req)
- {
- try {
- MsoTenantAdapter impl = tenantImpl;
- impl.rollbackTenant(req.getTenantRollback());
- }
- catch (TenantException te) {
- logger.debug(EXCEPTION, te);
- RollbackTenantError exc = new RollbackTenantError(te.getFaultInfo().getMessage(), te.getFaultInfo().getCategory(), Boolean.TRUE);
- return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
- }
- catch (Exception e) {
- logger.debug(EXCEPTION, e);
- RollbackTenantError exc = new RollbackTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE);
- return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
- }
-
- RollbackTenantResponse resp = new RollbackTenantResponse ();
- resp.setTenantRolledback(req != null);
- return Response.status(HttpServletResponse.SC_OK).entity(resp).build();
- }
+ private static final String EXCEPTION = "Exception :";
+ // RAA? No logging in wrappers
+ @Autowired
+ private MsoTenantAdapterImpl tenantImpl;
+
+
+
+ /*
+ * URL: EP: http://host:8080/tenants/rest Resource: v1/tenants REQ - metadata? { "cloudSiteId": "DAN", "tenantName":
+ * "RAA_1", "failIfExists": true, "msoRequest": { "requestId": "ra1", "serviceInstanceId": "sa1" }} RESP- {
+ * "cloudSiteId": "DAN", "tenantId": "128e10b9996d43a7874f19bbc4eb6749", "tenantCreated": true, "tenantRollback": {
+ * "tenantId": "128e10b9996d43a7874f19bbc4eb6749", "cloudId": "DAN", // RAA? cloudId instead of cloudSiteId
+ * "tenantCreated": true, "msoRequest": { "requestId": "ra1", "serviceInstanceId": "sa1" } } }
+ */
+ @POST
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "CreateTenant", response = Response.class,
+ notes = "Creates a new tenant, CreateTenantRequest data is required")
+ @ApiResponses({@ApiResponse(code = 200, message = "tenant has been successfully created"),
+ @ApiResponse(code = 500, message = "create tenant failed")})
+ public Response createTenant(
+ @ApiParam(value = "details of tenant being created", required = true) CreateTenantRequest req) {
+ logger.debug("createTenant enter: {}", req.toJsonString());
+
+ String newTenantId = null;
+ TenantRollback tenantRollback = new TenantRollback();
+
+ try {
+ Holder<String> htenant = new Holder<>();
+ Holder<TenantRollback> hrollback = new Holder<>();
+ MsoTenantAdapter impl = tenantImpl;
+ impl.createTenant(req.getCloudSiteId(), req.getTenantName(), req.getMetadata(), req.getFailIfExists(),
+ req.getBackout(), req.getMsoRequest(), htenant, hrollback);
+ newTenantId = htenant.value;
+ tenantRollback = hrollback.value;
+
+ } catch (TenantAlreadyExists tae) {
+ logger.debug(EXCEPTION, tae);
+ CreateTenantError exc =
+ new CreateTenantError(tae.getMessage(), tae.getFaultInfo().getCategory(), Boolean.TRUE);
+ return Response.status(HttpServletResponse.SC_NOT_IMPLEMENTED).entity(exc).build();
+ } catch (TenantException te) {
+ logger.debug(EXCEPTION, te);
+ CreateTenantError exc = new CreateTenantError(te.getFaultInfo().getMessage(),
+ te.getFaultInfo().getCategory(), Boolean.TRUE);
+ return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
+ } catch (Exception e) {
+ logger.debug(EXCEPTION, e);
+ CreateTenantError exc = new CreateTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE);
+ return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
+ }
+
+ CreateTenantResponse resp = new CreateTenantResponse(req.getCloudSiteId(), newTenantId,
+ tenantRollback.getTenantCreated(), tenantRollback);
+ return Response.status(HttpServletResponse.SC_OK).entity(resp).build();
+ }
+
+ /*
+ * URL: http://host:8080/tenants/rest Resource: v1/tenant/tennatId REQ: {"cloudSiteId": "DAN", "tenantId":
+ * "ca84cd3d3df44272845da554656b3ace", "msoRequest": { "requestId": "ra1", "serviceInstanceId": "sa1" } } RESP:
+ * {"tenantDeleted": true}
+ */
+ @DELETE
+ @Path("{tenantId}")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "DeleteTenant", response = Response.class, notes = "Delete an existing tenant")
+ @ApiResponses({@ApiResponse(code = 200, message = "tenant has been successfully deleted"),
+ @ApiResponse(code = 500, message = "delete tenant failed")})
+ public Response deleteTenant(
+ @ApiParam(value = "tenantId of tenant being deleted",
+ required = true) @PathParam("tenantId") String tenantId,
+ @ApiParam(value = "DeleteTenantRequest object containing additional information of tenant being deleted",
+ required = false) DeleteTenantRequest req) {
+ boolean tenantDeleted = false;
+
+ try {
+ Holder<Boolean> deleted = new Holder<>();
+ MsoTenantAdapter impl = tenantImpl;
+ impl.deleteTenant(req.getCloudSiteId(), req.getTenantId(), req.getMsoRequest(), deleted);
+ tenantDeleted = deleted.value;
+ } catch (TenantException te) {
+ logger.debug(EXCEPTION, te);
+ DeleteTenantError exc = new DeleteTenantError(te.getFaultInfo().getMessage(),
+ te.getFaultInfo().getCategory(), Boolean.TRUE);
+ return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
+ } catch (Exception e) {
+ logger.debug(EXCEPTION, e);
+ DeleteTenantError exc = new DeleteTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE);
+ return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
+ }
+ DeleteTenantResponse resp = new DeleteTenantResponse();
+ resp.setTenantDeleted(tenantDeleted);
+ return Response.status(HttpServletResponse.SC_OK).entity(resp).build();
+ }
+
+ /*
+ * URL EP://http://host:8080/tenants/rest Resource: /v1/tenants Params:?tenantNameOrId=RAA_1&cloudSiteId=DAN RESP {
+ * "tenantId": "214b428a1f554c02935e66330f6a5409", "tenantName": "RAA_1", "metadata": {} }
+ */
+ @GET
+ @Path("{tenantId}")
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "QueryTenant", response = Response.class, notes = "Query an existing tenant")
+ @ApiResponses({@ApiResponse(code = 200, message = "tenant has been successfully queried"),
+ @ApiResponse(code = 500, message = "query tenant failed")})
+ public Response queryTenant(@ApiParam(value = "tenantId", required = true) @PathParam("tenantId") String tenantId,
+ // @QueryParam("tenantNameOrId") String tenantNameOrId, //RAA? diff from doc
+ @ApiParam(value = "cloudSiteId", required = true) @QueryParam("cloudSiteId") String cloudSiteId,
+ @ApiParam(value = "msoRequest.requestId",
+ required = true) @QueryParam("msoRequest.requestId") String requestId,
+ @ApiParam(value = "msoRequest.serviceInstanceId",
+ required = true) @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId) {
+ MsoTenant tenant = null;
+ try {
+ Holder<String> htenant = new Holder<>();
+ Holder<String> tenantName = new Holder<>();
+ Holder<Map<String, String>> metadata = new Holder<>();
+ MsoTenantAdapter impl = tenantImpl;
+ impl.queryTenant(cloudSiteId, tenantId, null, htenant, tenantName, metadata);
+ tenant = new MsoTenant(htenant.value, tenantName.value, metadata.value);
+
+ } catch (TenantException te) {
+ logger.debug(EXCEPTION, te);
+ QueryTenantError exc =
+ new QueryTenantError(te.getFaultInfo().getMessage(), te.getFaultInfo().getCategory());
+ return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
+ } catch (Exception e) {
+ logger.debug(EXCEPTION, e);
+ QueryTenantError exc = new QueryTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL);
+ return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
+ }
+ QueryTenantResponse resp =
+ new QueryTenantResponse(tenant.getTenantId(), tenant.getTenantName(), tenant.getMetadata());
+ return Response.status(HttpServletResponse.SC_OK).entity(resp).build();
+ }
+
+ /*
+ * URL EP: //http://host:8080/tenants/rest Resource: /v1/tenants/rollback REQ {"cloudSiteId": "DAN", "tenantId":
+ * "f58abb05041d4ff384d4d22d1ccd2a6c", "msoRequest": { "requestId": "ra1", "serviceInstanceId": "sa1" } } RESP:
+ * {"tenantDeleted": true}
+ */
+ @DELETE
+ @Path("")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "RollbackTenant", response = Response.class, notes = "Rollback an existing tenant")
+ @ApiResponses({@ApiResponse(code = 200, message = "tenant has been successfully rolledback"),
+ @ApiResponse(code = 500, message = "rollback tenant failed")})
+ public Response rollbackTenant(
+ @ApiParam(value = "rollback, command action", required = true) @QueryParam("rollback") String action,
+ @ApiParam(value = "RollbackTenantRequest", required = true) RollbackTenantRequest req) {
+ try {
+ MsoTenantAdapter impl = tenantImpl;
+ impl.rollbackTenant(req.getTenantRollback());
+ } catch (TenantException te) {
+ logger.debug(EXCEPTION, te);
+ RollbackTenantError exc = new RollbackTenantError(te.getFaultInfo().getMessage(),
+ te.getFaultInfo().getCategory(), Boolean.TRUE);
+ return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
+ } catch (Exception e) {
+ logger.debug(EXCEPTION, e);
+ RollbackTenantError exc =
+ new RollbackTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE);
+ return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build();
+ }
+
+ RollbackTenantResponse resp = new RollbackTenantResponse();
+ resp.setTenantRolledback(req != null);
+ return Response.status(HttpServletResponse.SC_OK).entity(resp).build();
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExists.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExists.java
index 5b8e7c7294..8955eb50c6 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExists.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExists.java
@@ -23,23 +23,23 @@ package org.onap.so.adapters.tenant.exceptions;
import javax.xml.ws.WebFault;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
/**
- * This class reports an exception when trying to create a VNF when another
- * VNF of the same name already exists in the target cloud/tenant. Note that
- * the createVnf method suppresses this exception by default.
+ * This class reports an exception when trying to create a VNF when another VNF of the same name already exists in the
+ * target cloud/tenant. Note that the createVnf method suppresses this exception by default.
*
*
*/
-@WebFault (name="TenantAlreadyExists", faultBean="org.onap.so.adapters.tenant.exceptions.TenantExceptionBean", targetNamespace="http://org.onap.so/tenant")
+@WebFault(name = "TenantAlreadyExists", faultBean = "org.onap.so.adapters.tenant.exceptions.TenantExceptionBean",
+ targetNamespace = "http://org.onap.so/tenant")
public class TenantAlreadyExists extends TenantException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- public TenantAlreadyExists (String name, String cloudId, String tenantId) {
- super("Tenant " + name + " already exists in " + cloudId + " with ID " + tenantId, MsoExceptionCategory.USERDATA);
- }
+ public TenantAlreadyExists(String name, String cloudId, String tenantId) {
+ super("Tenant " + name + " already exists in " + cloudId + " with ID " + tenantId,
+ MsoExceptionCategory.USERDATA);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantException.java
index b8074ef7fc..998da98c8d 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantException.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantException.java
@@ -23,53 +23,53 @@ package org.onap.so.adapters.tenant.exceptions;
import javax.xml.ws.WebFault;
-
import org.onap.so.openstack.exceptions.MsoException;
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
/**
- * This class simply extends Exception (without addition additional functionality)
- * to provide an identifier for Tenant related exceptions on create, delete, query.
+ * This class simply extends Exception (without addition additional functionality) to provide an identifier for Tenant
+ * related exceptions on create, delete, query.
*
*
*/
-@WebFault (name="TenantException", faultBean="org.onap.so.adapters.tenant.exceptions.TenantExceptionBean", targetNamespace="http://org.onap.so/tenant")
+@WebFault(name = "TenantException", faultBean = "org.onap.so.adapters.tenant.exceptions.TenantExceptionBean",
+ targetNamespace = "http://org.onap.so/tenant")
public class TenantException extends Exception {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ private TenantExceptionBean faultInfo;
+
+ public TenantException(String msg) {
+ super(msg);
+ faultInfo = new TenantExceptionBean(msg);
+ }
+
+ public TenantException(String msg, Throwable e) {
+ super(msg, e);
+ faultInfo = new TenantExceptionBean(msg);
+ }
+
+ public TenantException(String msg, MsoExceptionCategory category) {
+ super(msg);
+ faultInfo = new TenantExceptionBean(msg, category);
+ }
- private TenantExceptionBean faultInfo;
-
- public TenantException (String msg) {
- super(msg);
- faultInfo = new TenantExceptionBean (msg);
- }
-
- public TenantException (String msg, Throwable e) {
- super (msg, e);
- faultInfo = new TenantExceptionBean (msg);
- }
+ public TenantException(String msg, MsoExceptionCategory category, Throwable e) {
+ super(msg, e);
+ faultInfo = new TenantExceptionBean(msg, category);
+ }
- public TenantException (String msg, MsoExceptionCategory category) {
- super(msg);
- faultInfo = new TenantExceptionBean (msg, category);
- }
-
- public TenantException (String msg, MsoExceptionCategory category, Throwable e) {
- super (msg, e);
- faultInfo = new TenantExceptionBean (msg, category);
- }
-
- public TenantException (MsoException e) {
- super (e);
- faultInfo = new TenantExceptionBean (e.getContextMessage(), e.getCategory());
- }
+ public TenantException(MsoException e) {
+ super(e);
+ faultInfo = new TenantExceptionBean(e.getContextMessage(), e.getCategory());
+ }
- public TenantExceptionBean getFaultInfo() {
- return faultInfo;
- }
+ public TenantExceptionBean getFaultInfo() {
+ return faultInfo;
+ }
- public void setFaultInfo(TenantExceptionBean faultInfo) {
- this.faultInfo = faultInfo;
- }
+ public void setFaultInfo(TenantExceptionBean faultInfo) {
+ this.faultInfo = faultInfo;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBean.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBean.java
index 1dada60e93..2d9260615a 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBean.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBean.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.tenant.exceptions;
import java.io.Serializable;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
/**
@@ -33,32 +32,32 @@ public class TenantExceptionBean implements Serializable {
private static final long serialVersionUID = -9062290006520066109L;
private String message;
- private MsoExceptionCategory category;
+ private MsoExceptionCategory category;
- public TenantExceptionBean () {}
+ public TenantExceptionBean() {}
- public TenantExceptionBean (String message) {
- this.message = message;
- }
+ public TenantExceptionBean(String message) {
+ this.message = message;
+ }
- public TenantExceptionBean (String message, MsoExceptionCategory category) {
- this.message = message;
- this.category = category;
- }
+ public TenantExceptionBean(String message, MsoExceptionCategory category) {
+ this.message = message;
+ this.category = category;
+ }
- public String getMessage() {
- return message;
- }
+ public String getMessage() {
+ return message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public MsoExceptionCategory getCategory () {
- return category;
- }
+ public MsoExceptionCategory getCategory() {
+ return category;
+ }
- public void setCategory (MsoExceptionCategory category) {
- this.category = category;
- }
+ public void setCategory(MsoExceptionCategory category) {
+ this.category = category;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/GenericValetResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/GenericValetResponse.java
index 30062a0144..6946fb1f90 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/GenericValetResponse.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/GenericValetResponse.java
@@ -23,50 +23,57 @@ package org.onap.so.adapters.valet;
import org.apache.commons.lang3.builder.ToStringBuilder;
/*
- * The purpose of this class is to encapsulate the possible responses from Valet in to one generic class
- * that the vnf adapter can more easily utilize. This will ensure we get an object back. Any status
- * code other than 200 will be treated as a failure. We may still get a 200 back - but the
- * ValetStatus.status is "failed" - which will also be treated as a failure. The T class is
- * expected to be one of the Valet*Response pojos.
+ * The purpose of this class is to encapsulate the possible responses from Valet in to one generic class that the vnf
+ * adapter can more easily utilize. This will ensure we get an object back. Any status code other than 200 will be
+ * treated as a failure. We may still get a 200 back - but the ValetStatus.status is "failed" - which will also be
+ * treated as a failure. The T class is expected to be one of the Valet*Response pojos.
*/
public class GenericValetResponse<T> {
- private int statusCode;
- private String errorMessage;
- private T returnObject;
-
+ private int statusCode;
+ private String errorMessage;
+ private T returnObject;
+
+
+ public GenericValetResponse(int statusCode, String errorMessage, T obj) {
+ super();
+ this.statusCode = statusCode;
+ this.errorMessage = errorMessage;
+ this.returnObject = obj;
+ }
+
+ public GenericValetResponse() {
+ this(-1, "not set", null);
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("statusCode", statusCode).append("errorMessage", errorMessage)
+ .append("returnObject", returnObject).toString();
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public String getErrorMessage() {
+ return this.errorMessage;
+ }
+
+ public void setStatusCode(int statusCode) {
+ this.statusCode = statusCode;
+ }
+
+ public int getStatusCode() {
+ return this.statusCode;
+ }
+
+ public void setReturnObject(T obj) {
+ this.returnObject = obj;
+ }
+
+ public T getReturnObject() {
+ return this.returnObject;
+ }
- public GenericValetResponse(int statusCode, String errorMessage, T obj) {
- super();
- this.statusCode = statusCode;
- this.errorMessage = errorMessage;
- this.returnObject = obj;
- }
- public GenericValetResponse() {
- this(-1, "not set", null);
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("statusCode", statusCode).append("errorMessage", errorMessage)
- .append("returnObject", returnObject).toString();
- }
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
- public String getErrorMessage() {
- return this.errorMessage;
- }
- public void setStatusCode(int statusCode) {
- this.statusCode = statusCode;
- }
- public int getStatusCode() {
- return this.statusCode;
- }
- public void setReturnObject(T obj) {
- this.returnObject = obj;
- }
- public T getReturnObject() {
- return this.returnObject;
- }
-
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java
index b8e504084b..34177ff5a3 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java
@@ -58,278 +58,292 @@ public class ValetClient {
private static Logger logger = LoggerFactory.getLogger(ValetClient.class);
- @Autowired
- private Environment environment;
-
- private static final String VALET_BASE_URL = "org.onap.so.adapters.valet.base_url";
- private static final String VALET_BASE_PATH = "org.onap.so.adapters.valet.base_path";
- private static final String VALET_AUTH = "org.onap.so.adapters.valet.basic_auth";
- private static final String REQ_ID_HEADER_NAME = "X-RequestID";
- protected static final String NO_STATUS_RETURNED = "no status returned from Valet";
-
- private static final String DEFAULT_BASE_URL = "http://localhost:8080/";
- private static final String DEFAULT_BASE_PATH = "api/valet/placement/v1";
- private static final String DEFAULT_AUTH_STRING = "";
- private static final String REQUEST_ID="requestId";
- private static final String HEADERS=", headers=";
- private static final String BODY=", body=";
- @Autowired
- private ObjectMapper mapper;
-
- protected String baseUrl;
- protected String basePath;
- protected String authString;
-
- /*
- * Setup the properties needed from properties file. Each will fall to a default
- */
- @PostConstruct
- private void setupParams() {
- try {
+ @Autowired
+ private Environment environment;
+
+ private static final String VALET_BASE_URL = "org.onap.so.adapters.valet.base_url";
+ private static final String VALET_BASE_PATH = "org.onap.so.adapters.valet.base_path";
+ private static final String VALET_AUTH = "org.onap.so.adapters.valet.basic_auth";
+ private static final String REQ_ID_HEADER_NAME = "X-RequestID";
+ protected static final String NO_STATUS_RETURNED = "no status returned from Valet";
+
+ private static final String DEFAULT_BASE_URL = "http://localhost:8080/";
+ private static final String DEFAULT_BASE_PATH = "api/valet/placement/v1";
+ private static final String DEFAULT_AUTH_STRING = "";
+ private static final String REQUEST_ID = "requestId";
+ private static final String HEADERS = ", headers=";
+ private static final String BODY = ", body=";
+ @Autowired
+ private ObjectMapper mapper;
+
+ protected String baseUrl;
+ protected String basePath;
+ protected String authString;
+
+ /*
+ * Setup the properties needed from properties file. Each will fall to a default
+ */
+ @PostConstruct
+ private void setupParams() {
+ try {
this.baseUrl = this.environment.getProperty(ValetClient.VALET_BASE_URL, ValetClient.DEFAULT_BASE_URL);
this.basePath = this.environment.getProperty(ValetClient.VALET_BASE_PATH, ValetClient.DEFAULT_BASE_PATH);
- this.authString = this.environment.getProperty(ValetClient.VALET_AUTH, ValetClient.DEFAULT_AUTH_STRING);
- } catch (Exception e) {
- logger.debug("Error retrieving valet properties. {}", e.getMessage());
+ this.authString = this.environment.getProperty(ValetClient.VALET_AUTH, ValetClient.DEFAULT_AUTH_STRING);
+ } catch (Exception e) {
+ logger.debug("Error retrieving valet properties. {}", e.getMessage());
+ }
+ }
+
+ /*
+ * This method will be invoked to send a Create request to Valet.
+ */
+ public GenericValetResponse<ValetCreateResponse> callValetCreateRequest(String requestId, String regionId,
+ String ownerId, String tenantId, String serviceInstanceId, String vnfId, String vnfName, String vfModuleId,
+ String vfModuleName, String keystoneUrl, HeatRequest heatRequest) throws Exception {
+ ResponseEntity<ValetCreateResponse> response = null;
+ GenericValetResponse<ValetCreateResponse> gvr = null;
+
+ try {
+ UriBuilder builder = UriBuilder.fromPath(baseUrl).path(basePath).queryParam(REQUEST_ID, requestId);
+ URI uri = builder.build();
+
+ ValetCreateRequest vcr = this.createValetCreateRequest(regionId, ownerId, tenantId, serviceInstanceId,
+ vnfId, vnfName, vfModuleId, vfModuleName, keystoneUrl, heatRequest);
+ String body = mapper.writeValueAsString(vcr);
+ HttpHeaders headers = generateHeaders(requestId);
+ HttpEntity<String> entity = new HttpEntity<>(body, headers);
+
+ response = getRestTemplate().exchange(uri, HttpMethod.POST, entity, ValetCreateResponse.class);
+ gvr = this.getGVRFromResponse(response);
+ } catch (Exception e) {
+ logger.error("An exception occurred in callValetCreateRequest", e);
+ throw e;
+ }
+ return gvr;
+ }
+
+ private RestTemplate getRestTemplate() {
+ RestTemplate restTemplate = new RestTemplate();
+ restTemplate
+ .setRequestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory()));
+ return restTemplate;
+ }
+
+ /*
+ * This method will be invoked to send an Update request to Valet.
+ */
+ public GenericValetResponse<ValetUpdateResponse> callValetUpdateRequest(String requestId, String regionId,
+ String ownerId, String tenantId, String serviceInstanceId, String vnfId, String vnfName, String vfModuleId,
+ String vfModuleName, String keystoneUrl, HeatRequest heatRequest) throws Exception {
+ ResponseEntity<ValetUpdateResponse> response = null;
+ GenericValetResponse<ValetUpdateResponse> gvr = null;
+
+ try {
+ UriBuilder builder = UriBuilder.fromPath(baseUrl).path(basePath).queryParam(REQUEST_ID, requestId);
+ URI uri = builder.build();
+
+ ValetUpdateRequest vur = this.createValetUpdateRequest(regionId, ownerId, tenantId, serviceInstanceId,
+ vnfId, vnfName, vfModuleId, vfModuleName, keystoneUrl, heatRequest);
+ String body = mapper.writeValueAsString(vur);
+ HttpHeaders headers = generateHeaders(requestId);
+ HttpEntity<String> entity = new HttpEntity<>(body, headers);
+
+
+ response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetUpdateResponse.class);
+ gvr = this.getGVRFromResponse(response);
+ } catch (Exception e) {
+ logger.error("An exception occurred in callValetUpdateRequest", e);
+ throw e;
+ }
+ return gvr;
+ }
+
+ /*
+ * This method will be invoked to send a Delete request to Valet.
+ */
+ public GenericValetResponse<ValetDeleteResponse> callValetDeleteRequest(String requestId, String regionId,
+ String ownerId, String tenantId, String vfModuleId, String vfModuleName) throws Exception {
+ ResponseEntity<ValetDeleteResponse> response = null;
+ GenericValetResponse<ValetDeleteResponse> gvr = null;
+
+ try {
+ UriBuilder builder = UriBuilder.fromPath(baseUrl).path(basePath).queryParam(REQUEST_ID, requestId);
+ URI uri = builder.build();
+
+ ValetDeleteRequest vdr =
+ this.createValetDeleteRequest(regionId, ownerId, tenantId, vfModuleId, vfModuleName);
+
+ String body = mapper.writeValueAsString(vdr);
+ HttpHeaders headers = generateHeaders(requestId);
+ HttpEntity<String> entity = new HttpEntity<>(body, headers);
+
+
+ response = getRestTemplate().exchange(uri, HttpMethod.DELETE, entity, ValetDeleteResponse.class);
+ gvr = this.getGVRFromResponse(response);
+ } catch (Exception e) {
+ logger.error("An exception occurred in callValetDeleteRequest", e);
+ throw e;
+ }
+ return gvr;
+ }
+
+ /*
+ * This method is called to invoke a Confirm request to Valet.
+ */
+ public GenericValetResponse<ValetConfirmResponse> callValetConfirmRequest(String requestId, String stackId)
+ throws Exception {
+ ResponseEntity<ValetConfirmResponse> response = null;
+ GenericValetResponse<ValetConfirmResponse> gvr = null;
+
+ try {
+ UriBuilder builder = UriBuilder.fromPath(this.baseUrl).path(this.basePath).path("{requestId}/confirm/");
+ URI uri = builder.build(requestId);
+
+ ValetConfirmRequest vcr = this.createValetConfirmRequest(stackId);
+
+ String body = mapper.writeValueAsString(vcr);
+ HttpHeaders headers = generateHeaders(requestId);
+ HttpEntity<String> entity = new HttpEntity<>(body, headers);
+ logger.debug("valet confirm req: {} {} {} {} {}", uri, HEADERS, headers, BODY, body);
+
+ response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetConfirmResponse.class);
+ gvr = this.getGVRFromResponse(response);
+ } catch (Exception e) {
+ logger.error("An exception occurred in callValetConfirmRequest", e);
+ throw e;
+ }
+ return gvr;
+ }
+
+ /*
+ * This method is called to invoke a Rollback request to Valet.
+ */
+ public GenericValetResponse<ValetRollbackResponse> callValetRollbackRequest(String requestId, String stackId,
+ Boolean suppressRollback, String errorMessage) throws Exception {
+ ResponseEntity<ValetRollbackResponse> response = null;
+ GenericValetResponse<ValetRollbackResponse> gvr = null;
+
+ try {
+ UriBuilder builder = UriBuilder.fromPath(this.baseUrl).path(this.basePath).path("{requestId}/rollback/");
+ URI uri = builder.build(requestId);
+
+ ValetRollbackRequest vrr = this.createValetRollbackRequest(stackId, suppressRollback, errorMessage);
+
+ String body = mapper.writeValueAsString(vrr);
+ HttpHeaders headers = generateHeaders(requestId);
+ HttpEntity<String> entity = new HttpEntity<>(body, headers);
+
+
+ response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetRollbackResponse.class);
+ gvr = this.getGVRFromResponse(response);
+ } catch (Exception e) {
+ logger.error("An exception occurred in callValetRollbackRequest", e);
+ throw e;
+ }
+ return gvr;
+ }
+
+ /*
+ * This method is to construct the ValetCreateRequest pojo
+ */
+ private ValetCreateRequest createValetCreateRequest(String regionId, String ownerId, String tenantId,
+ String serviceInstanceId, String vnfId, String vnfName, String vfModuleId, String vfModuleName,
+ String keystoneUrl, HeatRequest heatRequest) {
+ ValetCreateRequest vcr = new ValetCreateRequest();
+ vcr.setHeatRequest(heatRequest);
+ vcr.setKeystoneUrl(keystoneUrl);
+ vcr.setRegionId(regionId);
+ vcr.setOwnerId(ownerId);
+ vcr.setServiceInstanceId(serviceInstanceId);
+ vcr.setTenantId(tenantId);
+ vcr.setVfModuleId(vfModuleId);
+ vcr.setVfModuleName(vfModuleName);
+ vcr.setVnfId(vnfId);
+ vcr.setVnfName(vnfName);
+
+ return vcr;
+ }
+
+ /*
+ * This method is to construct the ValetUpdateRequest pojo
+ */
+ private ValetUpdateRequest createValetUpdateRequest(String regionId, String ownerId, String tenantId,
+ String serviceInstanceId, String vnfId, String vnfName, String vfModuleId, String vfModuleName,
+ String keystoneUrl, HeatRequest heatRequest) {
+ ValetUpdateRequest vur = new ValetUpdateRequest();
+ vur.setHeatRequest(heatRequest);
+ vur.setKeystoneUrl(keystoneUrl);
+ vur.setRegionId(regionId == null ? "" : regionId);
+ vur.setOwnerId(ownerId == null ? "" : ownerId);
+ vur.setServiceInstanceId(serviceInstanceId == null ? "" : serviceInstanceId);
+ vur.setTenantId(tenantId == null ? "" : tenantId);
+ vur.setVfModuleId(vfModuleId == null ? "" : vfModuleId);
+ vur.setVfModuleName(vfModuleName == null ? "" : vfModuleName);
+ vur.setVnfId(vnfId == null ? "" : vnfId);
+ vur.setVnfName(vnfName == null ? "" : vnfName);
+
+ return vur;
+ }
+
+ /*
+ * This method is to construct the ValetDeleteRequest pojo
+ */
+ private ValetDeleteRequest createValetDeleteRequest(String regionId, String ownerId, String tenantId,
+ String vfModuleId, String vfModuleName) {
+ ValetDeleteRequest vdr = new ValetDeleteRequest();
+ vdr.setRegionId(regionId == null ? "" : regionId);
+ vdr.setOwnerId(ownerId == null ? "" : ownerId);
+ vdr.setTenantId(tenantId == null ? "" : tenantId);
+ vdr.setVfModuleId(vfModuleId == null ? "" : vfModuleId);
+ vdr.setVfModuleName(vfModuleName == null ? "" : vfModuleName);
+
+ return vdr;
+ }
+
+ /*
+ * This method is to construct the ValetDeleteRequest pojo
+ */
+ private ValetConfirmRequest createValetConfirmRequest(String stackId) {
+ ValetConfirmRequest vcr = new ValetConfirmRequest();
+ vcr.setStackId(stackId);
+
+ return vcr;
+ }
+
+ /*
+ * This method is to construct the ValetRollbackRequest pojo
+ */
+ private ValetRollbackRequest createValetRollbackRequest(String stackId, Boolean suppressRollback,
+ String errorMessage) {
+ ValetRollbackRequest vrr = new ValetRollbackRequest();
+ vrr.setStackId(stackId);
+ vrr.setSuppressRollback(suppressRollback);
+ vrr.setErrorMessage(errorMessage);
+
+ return vrr;
+ }
+
+ private HttpHeaders generateHeaders(String requestId) {
+ HttpHeaders headers = new HttpHeaders();
+ headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
+ if (!(this.authString == null || this.authString.isEmpty())) {
+ headers.add("Authorization", "Basic " + this.authString);
+ }
+ headers.add(ValetClient.REQ_ID_HEADER_NAME, requestId);
+
+ return headers;
+ }
+
+ private <T> GenericValetResponse<T> getGVRFromResponse(ResponseEntity<T> response) {
+ GenericValetResponse<T> gvr = null;
+ if (response != null) {
+ T responseObj = response.getBody();
+ gvr = new GenericValetResponse<>(response.getStatusCodeValue(), ValetClient.NO_STATUS_RETURNED,
+ responseObj);
+
+ } else {
+ gvr = new GenericValetResponse<>(-1, ValetClient.NO_STATUS_RETURNED, null);
+ }
+ return gvr;
}
- }
-
- /*
- * This method will be invoked to send a Create request to Valet.
- */
- public GenericValetResponse<ValetCreateResponse> callValetCreateRequest(String requestId, String regionId, String ownerId, String tenantId, String serviceInstanceId,
- String vnfId, String vnfName, String vfModuleId, String vfModuleName, String keystoneUrl, HeatRequest heatRequest) throws Exception {
- ResponseEntity<ValetCreateResponse> response = null;
- GenericValetResponse<ValetCreateResponse> gvr = null;
-
- try {
- UriBuilder builder = UriBuilder.fromPath(baseUrl).path(basePath).queryParam(REQUEST_ID, requestId);
- URI uri = builder.build();
-
- ValetCreateRequest vcr = this.createValetCreateRequest(regionId, ownerId, tenantId, serviceInstanceId, vnfId, vnfName, vfModuleId, vfModuleName, keystoneUrl, heatRequest);
- String body = mapper.writeValueAsString(vcr);
- HttpHeaders headers = generateHeaders(requestId);
- HttpEntity<String> entity = new HttpEntity<>(body, headers);
-
- response = getRestTemplate().exchange(uri, HttpMethod.POST, entity, ValetCreateResponse.class);
- gvr = this.getGVRFromResponse(response);
- } catch (Exception e) {
- logger.error("An exception occurred in callValetCreateRequest", e);
- throw e;
- }
- return gvr;
- }
-
- private RestTemplate getRestTemplate(){
- RestTemplate restTemplate = new RestTemplate();
- restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory()));
- return restTemplate;
- }
-
- /*
- * This method will be invoked to send an Update request to Valet.
- */
- public GenericValetResponse<ValetUpdateResponse> callValetUpdateRequest(String requestId, String regionId, String ownerId, String tenantId, String serviceInstanceId,
- String vnfId, String vnfName, String vfModuleId, String vfModuleName, String keystoneUrl, HeatRequest heatRequest) throws Exception {
- ResponseEntity<ValetUpdateResponse> response = null;
- GenericValetResponse<ValetUpdateResponse> gvr = null;
-
- try {
- UriBuilder builder = UriBuilder.fromPath(baseUrl).path(basePath).queryParam(REQUEST_ID, requestId);
- URI uri = builder.build();
-
- ValetUpdateRequest vur = this.createValetUpdateRequest(regionId, ownerId, tenantId, serviceInstanceId, vnfId, vnfName, vfModuleId, vfModuleName, keystoneUrl, heatRequest);
- String body = mapper.writeValueAsString(vur);
- HttpHeaders headers = generateHeaders(requestId);
- HttpEntity<String> entity = new HttpEntity<>(body, headers);
-
-
- response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetUpdateResponse.class);
- gvr = this.getGVRFromResponse(response);
- } catch (Exception e) {
- logger.error("An exception occurred in callValetUpdateRequest", e);
- throw e;
- }
- return gvr;
- }
-
- /*
- * This method will be invoked to send a Delete request to Valet.
- */
- public GenericValetResponse<ValetDeleteResponse> callValetDeleteRequest(String requestId, String regionId, String ownerId, String tenantId, String vfModuleId, String vfModuleName) throws Exception {
- ResponseEntity<ValetDeleteResponse> response = null;
- GenericValetResponse<ValetDeleteResponse> gvr = null;
-
- try {
- UriBuilder builder = UriBuilder.fromPath(baseUrl).path(basePath).queryParam(REQUEST_ID, requestId);
- URI uri = builder.build();
-
- ValetDeleteRequest vdr = this.createValetDeleteRequest(regionId, ownerId, tenantId, vfModuleId, vfModuleName);
-
- String body = mapper.writeValueAsString(vdr);
- HttpHeaders headers = generateHeaders(requestId);
- HttpEntity<String> entity = new HttpEntity<>(body, headers);
-
-
- response = getRestTemplate().exchange(uri, HttpMethod.DELETE, entity, ValetDeleteResponse.class);
- gvr = this.getGVRFromResponse(response);
- } catch (Exception e) {
- logger.error("An exception occurred in callValetDeleteRequest", e);
- throw e;
- }
- return gvr;
- }
-
- /*
- * This method is called to invoke a Confirm request to Valet.
- */
- public GenericValetResponse<ValetConfirmResponse> callValetConfirmRequest(String requestId, String stackId) throws Exception {
- ResponseEntity<ValetConfirmResponse> response = null;
- GenericValetResponse<ValetConfirmResponse> gvr = null;
-
- try {
- UriBuilder builder = UriBuilder.fromPath(this.baseUrl).path(this.basePath).path("{requestId}/confirm/");
- URI uri = builder.build(requestId);
-
- ValetConfirmRequest vcr = this.createValetConfirmRequest(stackId);
-
- String body = mapper.writeValueAsString(vcr);
- HttpHeaders headers = generateHeaders(requestId);
- HttpEntity<String> entity = new HttpEntity<>(body, headers);
- logger.debug("valet confirm req: {} {} {} {} {}", uri, HEADERS, headers, BODY, body);
-
- response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetConfirmResponse.class);
- gvr = this.getGVRFromResponse(response);
- } catch (Exception e) {
- logger.error("An exception occurred in callValetConfirmRequest", e);
- throw e;
- }
- return gvr;
- }
-
- /*
- * This method is called to invoke a Rollback request to Valet.
- */
- public GenericValetResponse<ValetRollbackResponse> callValetRollbackRequest(String requestId, String stackId, Boolean suppressRollback, String errorMessage) throws Exception {
- ResponseEntity<ValetRollbackResponse> response = null;
- GenericValetResponse<ValetRollbackResponse> gvr = null;
-
- try {
- UriBuilder builder = UriBuilder.fromPath(this.baseUrl).path(this.basePath).path("{requestId}/rollback/");
- URI uri = builder.build(requestId);
-
- ValetRollbackRequest vrr = this.createValetRollbackRequest(stackId, suppressRollback, errorMessage);
-
- String body = mapper.writeValueAsString(vrr);
- HttpHeaders headers = generateHeaders(requestId);
- HttpEntity<String> entity = new HttpEntity<>(body, headers);
-
-
- response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetRollbackResponse.class);
- gvr = this.getGVRFromResponse(response);
- } catch (Exception e) {
- logger.error("An exception occurred in callValetRollbackRequest", e);
- throw e;
- }
- return gvr;
- }
-
- /*
- * This method is to construct the ValetCreateRequest pojo
- */
- private ValetCreateRequest createValetCreateRequest(String regionId, String ownerId, String tenantId, String serviceInstanceId,
- String vnfId, String vnfName, String vfModuleId, String vfModuleName, String keystoneUrl, HeatRequest heatRequest) {
- ValetCreateRequest vcr = new ValetCreateRequest();
- vcr.setHeatRequest(heatRequest);
- vcr.setKeystoneUrl(keystoneUrl);
- vcr.setRegionId(regionId);
- vcr.setOwnerId(ownerId);
- vcr.setServiceInstanceId(serviceInstanceId);
- vcr.setTenantId(tenantId);
- vcr.setVfModuleId(vfModuleId);
- vcr.setVfModuleName(vfModuleName);
- vcr.setVnfId(vnfId);
- vcr.setVnfName(vnfName);
-
- return vcr;
- }
-
- /*
- * This method is to construct the ValetUpdateRequest pojo
- */
- private ValetUpdateRequest createValetUpdateRequest(String regionId, String ownerId, String tenantId, String serviceInstanceId,
- String vnfId, String vnfName, String vfModuleId, String vfModuleName, String keystoneUrl, HeatRequest heatRequest) {
- ValetUpdateRequest vur = new ValetUpdateRequest();
- vur.setHeatRequest(heatRequest);
- vur.setKeystoneUrl(keystoneUrl);
- vur.setRegionId(regionId == null ? "" : regionId);
- vur.setOwnerId(ownerId == null ? "" : ownerId);
- vur.setServiceInstanceId(serviceInstanceId == null ? "" : serviceInstanceId);
- vur.setTenantId(tenantId == null ? "" : tenantId);
- vur.setVfModuleId(vfModuleId == null ? "" : vfModuleId);
- vur.setVfModuleName(vfModuleName == null ? "" : vfModuleName);
- vur.setVnfId(vnfId == null ? "" : vnfId);
- vur.setVnfName(vnfName == null ? "" : vnfName);
-
- return vur;
- }
-
- /*
- * This method is to construct the ValetDeleteRequest pojo
- */
- private ValetDeleteRequest createValetDeleteRequest(String regionId, String ownerId, String tenantId, String vfModuleId, String vfModuleName) {
- ValetDeleteRequest vdr = new ValetDeleteRequest();
- vdr.setRegionId(regionId == null ? "" : regionId);
- vdr.setOwnerId(ownerId == null ? "" : ownerId);
- vdr.setTenantId(tenantId == null ? "" : tenantId);
- vdr.setVfModuleId(vfModuleId == null ? "" : vfModuleId);
- vdr.setVfModuleName(vfModuleName == null ? "" : vfModuleName);
-
- return vdr;
- }
-
- /*
- * This method is to construct the ValetDeleteRequest pojo
- */
- private ValetConfirmRequest createValetConfirmRequest(String stackId) {
- ValetConfirmRequest vcr = new ValetConfirmRequest();
- vcr.setStackId(stackId);
-
- return vcr;
- }
-
- /*
- * This method is to construct the ValetRollbackRequest pojo
- */
- private ValetRollbackRequest createValetRollbackRequest(String stackId, Boolean suppressRollback, String errorMessage) {
- ValetRollbackRequest vrr = new ValetRollbackRequest();
- vrr.setStackId(stackId);
- vrr.setSuppressRollback(suppressRollback);
- vrr.setErrorMessage(errorMessage);
-
- return vrr;
- }
-
- private HttpHeaders generateHeaders(String requestId) {
- HttpHeaders headers = new HttpHeaders();
- headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
- if (!(this.authString == null || this.authString.isEmpty())) {
- headers.add("Authorization", "Basic " + this.authString);
- }
- headers.add(ValetClient.REQ_ID_HEADER_NAME, requestId);
-
- return headers;
- }
-
- private <T> GenericValetResponse<T> getGVRFromResponse(ResponseEntity<T> response) {
- GenericValetResponse<T> gvr = null;
- if (response != null) {
- T responseObj = response.getBody();
- gvr = new GenericValetResponse<>(response.getStatusCodeValue(), ValetClient.NO_STATUS_RETURNED, responseObj);
-
- } else {
- gvr = new GenericValetResponse<>(-1, ValetClient.NO_STATUS_RETURNED, null);
- }
- return gvr;
- }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/HeatRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/HeatRequest.java
index 5a28f65db4..c12c89dbff 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/HeatRequest.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/HeatRequest.java
@@ -19,108 +19,119 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.adapters.valet.beans;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/*
- * This class represents the heat request as sent to OpenStack as defined in the
- * Valet Placement Operations API
+ * This class represents the heat request as sent to OpenStack as defined in the Valet Placement Operations API
*/
public class HeatRequest implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
- @JsonProperty("stack_name")
- private String stackName;
- @JsonProperty("disable_rollback")
- private Boolean disableRollback;
- @JsonProperty("timeout_mins")
- private Integer timeoutMins;
- @JsonProperty("template")
- private String template;
- @JsonProperty("environment")
- private String environment;
- @JsonProperty("files")
- private Map<String, Object> files = new HashMap<>();
- @JsonProperty("parameters")
- private Map<String, Object> parameters = new HashMap<>();
-
- public HeatRequest(String stackName, boolean disableRollback, int timeoutMins, String template, String environment, Map<String, Object> files, Map<String, Object> parameters) {
- super();
- this.stackName = stackName;
- this.disableRollback = disableRollback;
- this.timeoutMins = timeoutMins;
- this.template = template;
- this.environment = environment;
- this.files = files;
- this.parameters = parameters;
- }
-
- public String getStackName() {
- return this.stackName;
- }
- public void setStackName(String stackName) {
- this.stackName = stackName;
- }
- public Boolean getDisableRollback() {
- return this.disableRollback;
- }
- public void setDisableRollback(Boolean disableRollback) {
- this.disableRollback = disableRollback;
- }
- public Integer getTimeoutMins() {
- return this.timeoutMins;
- }
- public void setTimeoutMins(Integer timeoutMins) {
- this.timeoutMins = timeoutMins;
- }
- public String getTemplate() {
- return this.template;
- }
- public void setTemplate(String template) {
- this.template = template;
- }
- public String getEnvironment() {
- return this.environment;
- }
- public void setEnvironment(String environment) {
- this.environment = environment;
- }
- public Map<String, Object> getFiles() {
- return this.files;
- }
- public void setFiles(Map<String, Object> files) {
- this.files = files;
- }
- public Map<String, Object> getParameters() {
- return this.parameters;
- }
- public void setParameters(Map<String, Object> parameters) {
- this.parameters = parameters;
- }
- @Override
- public int hashCode() {
- return Objects.hash(stackName, disableRollback, timeoutMins, template, environment, files, parameters);
- }
- @Override
- public boolean equals(Object o) {
- if (o == this)
- return true;
- if (!(o instanceof HeatRequest)) {
- return false;
- }
- HeatRequest hr = (HeatRequest) o;
- return Objects.equals(stackName, hr.stackName)
- && Objects.equals(disableRollback, hr.disableRollback)
- && Objects.equals(timeoutMins, hr.timeoutMins)
- && Objects.equals(template, hr.template)
- && Objects.equals(environment, hr.environment)
- && Objects.equals(files, hr.files)
- && Objects.equals(parameters, hr.parameters);
- }
+ private static final long serialVersionUID = 768026109321305392L;
+ @JsonProperty("stack_name")
+ private String stackName;
+ @JsonProperty("disable_rollback")
+ private Boolean disableRollback;
+ @JsonProperty("timeout_mins")
+ private Integer timeoutMins;
+ @JsonProperty("template")
+ private String template;
+ @JsonProperty("environment")
+ private String environment;
+ @JsonProperty("files")
+ private Map<String, Object> files = new HashMap<>();
+ @JsonProperty("parameters")
+ private Map<String, Object> parameters = new HashMap<>();
+
+ public HeatRequest(String stackName, boolean disableRollback, int timeoutMins, String template, String environment,
+ Map<String, Object> files, Map<String, Object> parameters) {
+ super();
+ this.stackName = stackName;
+ this.disableRollback = disableRollback;
+ this.timeoutMins = timeoutMins;
+ this.template = template;
+ this.environment = environment;
+ this.files = files;
+ this.parameters = parameters;
+ }
+
+ public String getStackName() {
+ return this.stackName;
+ }
+
+ public void setStackName(String stackName) {
+ this.stackName = stackName;
+ }
+
+ public Boolean getDisableRollback() {
+ return this.disableRollback;
+ }
+
+ public void setDisableRollback(Boolean disableRollback) {
+ this.disableRollback = disableRollback;
+ }
+
+ public Integer getTimeoutMins() {
+ return this.timeoutMins;
+ }
+
+ public void setTimeoutMins(Integer timeoutMins) {
+ this.timeoutMins = timeoutMins;
+ }
+
+ public String getTemplate() {
+ return this.template;
+ }
+
+ public void setTemplate(String template) {
+ this.template = template;
+ }
+
+ public String getEnvironment() {
+ return this.environment;
+ }
+
+ public void setEnvironment(String environment) {
+ this.environment = environment;
+ }
+
+ public Map<String, Object> getFiles() {
+ return this.files;
+ }
+
+ public void setFiles(Map<String, Object> files) {
+ this.files = files;
+ }
+
+ public Map<String, Object> getParameters() {
+ return this.parameters;
+ }
+
+ public void setParameters(Map<String, Object> parameters) {
+ this.parameters = parameters;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(stackName, disableRollback, timeoutMins, template, environment, files, parameters);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof HeatRequest)) {
+ return false;
+ }
+ HeatRequest hr = (HeatRequest) o;
+ return Objects.equals(stackName, hr.stackName) && Objects.equals(disableRollback, hr.disableRollback)
+ && Objects.equals(timeoutMins, hr.timeoutMins) && Objects.equals(template, hr.template)
+ && Objects.equals(environment, hr.environment) && Objects.equals(files, hr.files)
+ && Objects.equals(parameters, hr.parameters);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmRequest.java
index 36083e8be6..0d6c47b2db 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmRequest.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmRequest.java
@@ -22,44 +22,47 @@ package org.onap.so.adapters.valet.beans;
import java.io.Serializable;
import java.util.Objects;
-
import com.fasterxml.jackson.annotation.JsonProperty;
+
/*
* This class represents the body of a Confirm operation on a Valet Placement API call
*/
public class ValetConfirmRequest implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
-
- @JsonProperty("stack_id")
- private String stackId;
-
- public ValetConfirmRequest() {
- super();
- }
- public ValetConfirmRequest(String stackId) {
- super();
- this.stackId = stackId;
- }
-
- public String getStackId() {
- return this.stackId;
- }
- public void setStackId(String stackId) {
- this.stackId = stackId;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(stackId);
- }
- @Override
- public boolean equals(Object o) {
- if (o == this)
- return true;
- if (!(o instanceof ValetConfirmRequest)) {
- return false;
- }
- ValetConfirmRequest vcr = (ValetConfirmRequest) o;
- return Objects.equals(stackId, vcr.stackId);
- }
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @JsonProperty("stack_id")
+ private String stackId;
+
+ public ValetConfirmRequest() {
+ super();
+ }
+
+ public ValetConfirmRequest(String stackId) {
+ super();
+ this.stackId = stackId;
+ }
+
+ public String getStackId() {
+ return this.stackId;
+ }
+
+ public void setStackId(String stackId) {
+ this.stackId = stackId;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(stackId);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof ValetConfirmRequest)) {
+ return false;
+ }
+ ValetConfirmRequest vcr = (ValetConfirmRequest) o;
+ return Objects.equals(stackId, vcr.stackId);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmResponse.java
index c009da9608..f69b9b7eb8 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmResponse.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmResponse.java
@@ -25,6 +25,6 @@ import java.io.Serializable;
/* This class has no body - placeholder if needed - for the response to a Confirm operation */
public class ValetConfirmResponse implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
+ private static final long serialVersionUID = 768026109321305392L;
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateRequest.java
index cb92ecddad..5aac0a167a 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateRequest.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateRequest.java
@@ -22,122 +22,137 @@ package org.onap.so.adapters.valet.beans;
import java.io.Serializable;
import java.util.Objects;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/*
* This class represents the body of a Create request operation on a Valet Placement API call
*/
public class ValetCreateRequest implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
-
- @JsonProperty("region_id")
- private String regionId;
- @JsonProperty("owner_id")
- private String ownerId;
- @JsonProperty("tenant_id")
- private String tenantId;
- @JsonProperty("service_instance_id")
- private String serviceInstanceId;
- @JsonProperty("vnf_id")
- private String vnfId;
- @JsonProperty("vnf_name")
- private String vnfName;
- @JsonProperty("vf_module_id")
- private String vfModuleId;
- @JsonProperty("vf_module_name")
- private String vfModuleName;
- @JsonProperty("keystone_url")
- private String keystoneUrl;
- @JsonProperty("heat_request")
- private HeatRequest heatRequest;
-
- public ValetCreateRequest() {
- super();
- }
-
- public String getRegionId() {
- return this.regionId;
- }
- public void setRegionId(String regionId) {
- this.regionId = regionId;
- }
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @JsonProperty("region_id")
+ private String regionId;
+ @JsonProperty("owner_id")
+ private String ownerId;
+ @JsonProperty("tenant_id")
+ private String tenantId;
+ @JsonProperty("service_instance_id")
+ private String serviceInstanceId;
+ @JsonProperty("vnf_id")
+ private String vnfId;
+ @JsonProperty("vnf_name")
+ private String vnfName;
+ @JsonProperty("vf_module_id")
+ private String vfModuleId;
+ @JsonProperty("vf_module_name")
+ private String vfModuleName;
+ @JsonProperty("keystone_url")
+ private String keystoneUrl;
+ @JsonProperty("heat_request")
+ private HeatRequest heatRequest;
+
+ public ValetCreateRequest() {
+ super();
+ }
+
+ public String getRegionId() {
+ return this.regionId;
+ }
+
+ public void setRegionId(String regionId) {
+ this.regionId = regionId;
+ }
+
public String getOwnerId() {
return this.ownerId;
}
+
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
- public String getTenantId() {
- return this.tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getServiceInstanceId() {
- return this.serviceInstanceId;
- }
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
- public String getVnfId() {
- return this.vnfId;
- }
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
- public String getVnfName() {
- return this.vnfName;
- }
- public void setVnfName(String vnfName) {
- this.vnfName = vnfName;
- }
- public String getVfModuleId() {
- return this.vfModuleId;
- }
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
- public String getVfModuleName() {
- return this.vfModuleName;
- }
- public void setVfModuleName(String vfModuleName) {
- this.vfModuleName = vfModuleName;
- }
- public String getKeystoneUrl() {
- return this.keystoneUrl;
- }
- public void setKeystoneUrl(String keystoneUrl) {
- this.keystoneUrl = keystoneUrl;
- }
- public HeatRequest getHeatRequest() {
- return this.heatRequest;
- }
- public void setHeatRequest(HeatRequest heatRequest) {
- this.heatRequest = heatRequest;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(regionId, ownerId, tenantId, serviceInstanceId, vnfId, vnfName, vfModuleId, vfModuleName, keystoneUrl, heatRequest);
- }
- @Override
- public boolean equals(Object o) {
- if (o == this)
- return true;
- if (!(o instanceof ValetCreateRequest)) {
- return false;
- }
- ValetCreateRequest vcr = (ValetCreateRequest) o;
- return Objects.equals(regionId, vcr.regionId)
- && Objects.equals(ownerId, vcr.ownerId)
- && Objects.equals(tenantId, vcr.tenantId)
- && Objects.equals(serviceInstanceId, vcr.serviceInstanceId)
- && Objects.equals(vnfId, vcr.vnfId)
- && Objects.equals(vnfName, vcr.vnfName)
- && Objects.equals(vfModuleId, vcr.vfModuleId)
- && Objects.equals(vfModuleName, vcr.vfModuleName)
- && Objects.equals(keystoneUrl, vcr.keystoneUrl)
- && Objects.equals(heatRequest, vcr.heatRequest);
- }
+
+ public String getTenantId() {
+ return this.tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getServiceInstanceId() {
+ return this.serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getVnfId() {
+ return this.vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getVnfName() {
+ return this.vnfName;
+ }
+
+ public void setVnfName(String vnfName) {
+ this.vnfName = vnfName;
+ }
+
+ public String getVfModuleId() {
+ return this.vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ public String getVfModuleName() {
+ return this.vfModuleName;
+ }
+
+ public void setVfModuleName(String vfModuleName) {
+ this.vfModuleName = vfModuleName;
+ }
+
+ public String getKeystoneUrl() {
+ return this.keystoneUrl;
+ }
+
+ public void setKeystoneUrl(String keystoneUrl) {
+ this.keystoneUrl = keystoneUrl;
+ }
+
+ public HeatRequest getHeatRequest() {
+ return this.heatRequest;
+ }
+
+ public void setHeatRequest(HeatRequest heatRequest) {
+ this.heatRequest = heatRequest;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(regionId, ownerId, tenantId, serviceInstanceId, vnfId, vnfName, vfModuleId, vfModuleName,
+ keystoneUrl, heatRequest);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof ValetCreateRequest)) {
+ return false;
+ }
+ ValetCreateRequest vcr = (ValetCreateRequest) o;
+ return Objects.equals(regionId, vcr.regionId) && Objects.equals(ownerId, vcr.ownerId)
+ && Objects.equals(tenantId, vcr.tenantId) && Objects.equals(serviceInstanceId, vcr.serviceInstanceId)
+ && Objects.equals(vnfId, vcr.vnfId) && Objects.equals(vnfName, vcr.vnfName)
+ && Objects.equals(vfModuleId, vcr.vfModuleId) && Objects.equals(vfModuleName, vcr.vfModuleName)
+ && Objects.equals(keystoneUrl, vcr.keystoneUrl) && Objects.equals(heatRequest, vcr.heatRequest);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateResponse.java
index e0c750e79f..e09788714a 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateResponse.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateResponse.java
@@ -24,47 +24,51 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
import java.util.Objects;
import java.io.Serializable;
+
/*
* This class represents the body of a Create response on a Valet Placement API call
*/
public class ValetCreateResponse implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
-
- @JsonProperty("status")
- private ValetStatus status;
- @JsonProperty("parameters")
- private Map<String, Object> parameters;
-
- public ValetCreateResponse() {
- super();
- }
-
- public ValetStatus getStatus() {
- return this.status;
- }
- public void setStatus(ValetStatus status) {
- this.status = status;
- }
- public Map<String, Object> getParameters() {
- return this.parameters;
- }
- public void setParameters(Map<String, Object> parameters) {
- this.parameters = parameters;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(status, parameters);
- }
- @Override
- public boolean equals(Object o) {
- if (o == this)
- return true;
- if (!(o instanceof ValetCreateResponse)) {
- return false;
- }
- ValetCreateResponse vcr = (ValetCreateResponse) o;
- return Objects.equals(status, vcr.status)
- && Objects.equals(parameters, vcr.parameters);
- }
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @JsonProperty("status")
+ private ValetStatus status;
+ @JsonProperty("parameters")
+ private Map<String, Object> parameters;
+
+ public ValetCreateResponse() {
+ super();
+ }
+
+ public ValetStatus getStatus() {
+ return this.status;
+ }
+
+ public void setStatus(ValetStatus status) {
+ this.status = status;
+ }
+
+ public Map<String, Object> getParameters() {
+ return this.parameters;
+ }
+
+ public void setParameters(Map<String, Object> parameters) {
+ this.parameters = parameters;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(status, parameters);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof ValetCreateResponse)) {
+ return false;
+ }
+ ValetCreateResponse vcr = (ValetCreateResponse) o;
+ return Objects.equals(status, vcr.status) && Objects.equals(parameters, vcr.parameters);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteRequest.java
index 75d7df1a83..fb6ceb45d8 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteRequest.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteRequest.java
@@ -22,72 +22,80 @@ package org.onap.so.adapters.valet.beans;
import java.io.Serializable;
import java.util.Objects;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/*
* This class represents the body of a Delete request on a Valet Placement API call
*/
public class ValetDeleteRequest implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
-
- @JsonProperty("region_id")
- private String regionId;
- @JsonProperty("owner_id")
- private String ownerId;
- @JsonProperty("tenant_id")
- private String tenantId;
- @JsonProperty("vf_module_id")
- private String vfModuleId;
- @JsonProperty("vf_module_name")
- private String vfModuleName;
-
- public String getRegionId() {
- return this.regionId;
- }
- public void setRegionId(String regionId) {
- this.regionId = regionId;
- }
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @JsonProperty("region_id")
+ private String regionId;
+ @JsonProperty("owner_id")
+ private String ownerId;
+ @JsonProperty("tenant_id")
+ private String tenantId;
+ @JsonProperty("vf_module_id")
+ private String vfModuleId;
+ @JsonProperty("vf_module_name")
+ private String vfModuleName;
+
+ public String getRegionId() {
+ return this.regionId;
+ }
+
+ public void setRegionId(String regionId) {
+ this.regionId = regionId;
+ }
+
public String getOwnerId() {
return this.ownerId;
}
+
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
- public String getTenantId() {
- return this.tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getVfModuleId() {
- return this.vfModuleId;
- }
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
- public String getVfModuleName() {
- return this.vfModuleName;
- }
- public void setVfModuleName(String vfModuleName) {
- this.vfModuleName = vfModuleName;
- }
- @Override
- public int hashCode() {
- return Objects.hash(regionId, ownerId, tenantId, vfModuleId, vfModuleName);
- }
- @Override
- public boolean equals(Object o) {
- if (o == this)
- return true;
- if (!(o instanceof ValetDeleteRequest)) {
- return false;
- }
- ValetDeleteRequest vdr = (ValetDeleteRequest) o;
- return Objects.equals(regionId, vdr.regionId)
- && Objects.equals(ownerId, vdr.ownerId)
- && Objects.equals(tenantId, vdr.tenantId)
- && Objects.equals(vfModuleId, vdr.vfModuleId)
- && Objects.equals(vfModuleName, vdr.vfModuleName);
- }
+
+ public String getTenantId() {
+ return this.tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getVfModuleId() {
+ return this.vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ public String getVfModuleName() {
+ return this.vfModuleName;
+ }
+
+ public void setVfModuleName(String vfModuleName) {
+ this.vfModuleName = vfModuleName;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(regionId, ownerId, tenantId, vfModuleId, vfModuleName);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof ValetDeleteRequest)) {
+ return false;
+ }
+ ValetDeleteRequest vdr = (ValetDeleteRequest) o;
+ return Objects.equals(regionId, vdr.regionId) && Objects.equals(ownerId, vdr.ownerId)
+ && Objects.equals(tenantId, vdr.tenantId) && Objects.equals(vfModuleId, vdr.vfModuleId)
+ && Objects.equals(vfModuleName, vdr.vfModuleName);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteResponse.java
index fa58752d61..81cfbc7acb 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteResponse.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteResponse.java
@@ -22,45 +22,47 @@ package org.onap.so.adapters.valet.beans;
import java.io.Serializable;
import java.util.Objects;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/*
* This class represents the body of a Delete response on a Valet Placement API call
*/
public class ValetDeleteResponse implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
- @JsonProperty("status")
- private ValetStatus status;
-
- public ValetDeleteResponse() {
- super();
- }
- public ValetDeleteResponse(ValetStatus status) {
- super();
- this.status = status;
- }
-
- public ValetStatus getStatus() {
- return this.status;
- }
- public void setStatus(ValetStatus status) {
- this.status = status;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(status);
- }
- @Override
- public boolean equals(Object o) {
- if (o == this)
- return true;
- if (!(o instanceof ValetDeleteResponse)) {
- return false;
- }
- ValetDeleteResponse vdr = (ValetDeleteResponse) o;
- return Objects.equals(status, vdr.status);
- }
+ private static final long serialVersionUID = 768026109321305392L;
+ @JsonProperty("status")
+ private ValetStatus status;
+
+ public ValetDeleteResponse() {
+ super();
+ }
+
+ public ValetDeleteResponse(ValetStatus status) {
+ super();
+ this.status = status;
+ }
+
+ public ValetStatus getStatus() {
+ return this.status;
+ }
+
+ public void setStatus(ValetStatus status) {
+ this.status = status;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(status);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof ValetDeleteResponse)) {
+ return false;
+ }
+ ValetDeleteResponse vdr = (ValetDeleteResponse) o;
+ return Objects.equals(status, vdr.status);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackRequest.java
index ae0af67f80..7ca11af443 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackRequest.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackRequest.java
@@ -22,60 +22,64 @@ package org.onap.so.adapters.valet.beans;
import java.io.Serializable;
import java.util.Objects;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/*
* This class represents the body of a Rollback request on a Valet Placement API call
*/
public class ValetRollbackRequest implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @JsonProperty("stack_id")
+ private String stackId;
+ @JsonProperty("suppress_rollback")
+ private Boolean suppressRollback = false;
+ @JsonProperty("error_message")
+ private String errorMessage;
+
+ public ValetRollbackRequest() {
+ super();
+ }
+
+ public String getStackId() {
+ return this.stackId;
+ }
+
+ public void setStackId(String stackId) {
+ this.stackId = stackId;
+ }
+
+ public Boolean getSuppressRollback() {
+ return this.suppressRollback;
+ }
+
+ public void setSuppressRollback(Boolean suppressRollback) {
+ this.suppressRollback = suppressRollback;
+ }
+
+ public String getErrorMessage() {
+ return this.errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(stackId, suppressRollback, errorMessage);
+ }
- @JsonProperty("stack_id")
- private String stackId;
- @JsonProperty("suppress_rollback")
- private Boolean suppressRollback = false;
- @JsonProperty("error_message")
- private String errorMessage;
-
- public ValetRollbackRequest() {
- super();
- }
-
- public String getStackId() {
- return this.stackId;
- }
- public void setStackId(String stackId) {
- this.stackId = stackId;
- }
- public Boolean getSuppressRollback() {
- return this.suppressRollback;
- }
- public void setSuppressRollback(Boolean suppressRollback) {
- this.suppressRollback = suppressRollback;
- }
- public String getErrorMessage() {
- return this.errorMessage;
- }
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(stackId, suppressRollback, errorMessage);
- }
- @Override
- public boolean equals(Object o) {
- if (o == this)
- return true;
- if (!(o instanceof ValetRollbackRequest)) {
- return false;
- }
- ValetRollbackRequest vrr = (ValetRollbackRequest) o;
- return Objects.equals(stackId, vrr.stackId)
- && Objects.equals(suppressRollback, vrr.suppressRollback)
- && Objects.equals(errorMessage, vrr.errorMessage);
- }
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof ValetRollbackRequest)) {
+ return false;
+ }
+ ValetRollbackRequest vrr = (ValetRollbackRequest) o;
+ return Objects.equals(stackId, vrr.stackId) && Objects.equals(suppressRollback, vrr.suppressRollback)
+ && Objects.equals(errorMessage, vrr.errorMessage);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackResponse.java
index 429aa95af0..d9d29c0935 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackResponse.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackResponse.java
@@ -21,9 +21,9 @@
package org.onap.so.adapters.valet.beans;
import java.io.Serializable;
-/* This class has no body - placeholder - body of a Rollback response on a Valet Placement Operation */
+/* This class has no body - placeholder - body of a Rollback response on a Valet Placement Operation */
public class ValetRollbackResponse implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
+ private static final long serialVersionUID = 768026109321305392L;
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetStatus.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetStatus.java
index cc48e95c81..3b8528cd72 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetStatus.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetStatus.java
@@ -22,62 +22,65 @@ package org.onap.so.adapters.valet.beans;
import java.io.Serializable;
import java.util.Objects;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
-/*
+/*
* This class represents the status object as defined in the Valet Placement Operations API - part of Response objects
*/
public class ValetStatus implements Serializable {
- private static final long serialVersionUID = 1L;
- @JsonProperty("status")
- private String status;
- @JsonProperty("message")
- private String message;
+ private static final long serialVersionUID = 1L;
+ @JsonProperty("status")
+ private String status;
+ @JsonProperty("message")
+ private String message;
+
+
+ public ValetStatus() {
+ super();
+ }
+
+ public ValetStatus(String statusCode, String statusMessage) {
+ super();
+ this.status = statusCode;
+ this.message = statusMessage;
+ }
+
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("status", status).append("message", message).toString();
+ }
+
+ public String getStatus() {
+ return this.status;
+ }
+
+ public void setStatus(String statusCode) {
+ this.status = statusCode;
+ }
+
+ public String getMessage() {
+ return this.message;
+ }
+ public void setMessage(String statusMessage) {
+ this.message = statusMessage;
+ }
- public ValetStatus() {
- super();
- }
-
- public ValetStatus(String statusCode, String statusMessage) {
- super();
- this.status = statusCode;
- this.message = statusMessage;
- }
-
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("status", status).append("message", message).toString();
- }
-
- public String getStatus() {
- return this.status;
- }
- public void setStatus(String statusCode) {
- this.status = statusCode;
- }
- public String getMessage() {
- return this.message;
- }
- public void setMessage(String statusMessage) {
- this.message = statusMessage;
- }
+ @Override
+ public int hashCode() {
+ return Objects.hash(status, message);
+ }
- @Override
- public int hashCode() {
- return Objects.hash(status, message);
- }
- @Override
- public boolean equals(Object o) {
- if (o == this)
- return true;
- if (!(o instanceof ValetStatus)) {
- return false;
- }
- ValetStatus vs = (ValetStatus) o;
- return Objects.equals(status, vs.status) && Objects.equals(message, vs.message);
- }
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof ValetStatus)) {
+ return false;
+ }
+ ValetStatus vs = (ValetStatus) o;
+ return Objects.equals(status, vs.status) && Objects.equals(message, vs.message);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateRequest.java
index 2d39dd1a71..ff27d88a1f 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateRequest.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateRequest.java
@@ -22,122 +22,138 @@ package org.onap.so.adapters.valet.beans;
import java.io.Serializable;
import java.util.Objects;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/*
* This class represents the body of an Update request on a Valet Placement API call
*/
public class ValetUpdateRequest implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
-
- @JsonProperty("region_id")
- private String regionId;
- @JsonProperty("owner)_id")
- private String ownerId;
- @JsonProperty("tenant_id")
- private String tenantId;
- @JsonProperty("service_instance_id")
- private String serviceInstanceId;
- @JsonProperty("vnf_id")
- private String vnfId;
- @JsonProperty("vnf_name")
- private String vnfName;
- @JsonProperty("vf_module_id")
- private String vfModuleId;
- @JsonProperty("vf_module_name")
- private String vfModuleName;
- @JsonProperty("keystone_url")
- private String keystoneUrl;
- @JsonProperty("heat_request")
- private HeatRequest heatRequest;
-
- public ValetUpdateRequest() {
- super();
- }
-
- public String getRegionId() {
- return this.regionId;
- }
- public void setRegionId(String regionId) {
- this.regionId = regionId;
- }
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @JsonProperty("region_id")
+ private String regionId;
+ @JsonProperty("owner)_id")
+ private String ownerId;
+ @JsonProperty("tenant_id")
+ private String tenantId;
+ @JsonProperty("service_instance_id")
+ private String serviceInstanceId;
+ @JsonProperty("vnf_id")
+ private String vnfId;
+ @JsonProperty("vnf_name")
+ private String vnfName;
+ @JsonProperty("vf_module_id")
+ private String vfModuleId;
+ @JsonProperty("vf_module_name")
+ private String vfModuleName;
+ @JsonProperty("keystone_url")
+ private String keystoneUrl;
+ @JsonProperty("heat_request")
+ private HeatRequest heatRequest;
+
+ public ValetUpdateRequest() {
+ super();
+ }
+
+ public String getRegionId() {
+ return this.regionId;
+ }
+
+ public void setRegionId(String regionId) {
+ this.regionId = regionId;
+ }
+
public String getOwnerId() {
return this.ownerId;
}
+
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
- public String getTenantId() {
- return this.tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getServiceInstanceId() {
- return this.serviceInstanceId;
- }
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
- public String getVnfId() {
- return this.vnfId;
- }
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
- public String getVnfName() {
- return this.vnfName;
- }
- public void setVnfName(String vnfName) {
- this.vnfName = vnfName;
- }
- public String getVfModuleId() {
- return this.vfModuleId;
- }
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
- public String getVfModuleName() {
- return this.vfModuleName;
- }
- public void setVfModuleName(String vfModuleName) {
- this.vfModuleName = vfModuleName;
- }
- public String getKeystoneUrl() {
- return this.keystoneUrl;
- }
- public void setKeystoneUrl(String keystoneUrl) {
- this.keystoneUrl = keystoneUrl;
- }
- public HeatRequest getHeatRequest() {
- return this.heatRequest;
- }
- public void setHeatRequest(HeatRequest heatRequest) {
- this.heatRequest = heatRequest;
- }
- @Override
- public int hashCode() {
- return Objects.hash(regionId, ownerId, tenantId, serviceInstanceId, vnfId, vnfName, vfModuleId, vfModuleName, keystoneUrl, heatRequest);
-
- }
- @Override
- public boolean equals(Object o) {
- if (o == this)
- return true;
- if (!(o instanceof ValetUpdateRequest)) {
- return false;
- }
- ValetUpdateRequest vur = (ValetUpdateRequest) o;
- return Objects.equals(regionId, vur.regionId)
- && Objects.equals(ownerId, vur.ownerId)
- && Objects.equals(tenantId, vur.tenantId)
- && Objects.equals(serviceInstanceId, vur.serviceInstanceId)
- && Objects.equals(vnfId, vur.vnfId)
- && Objects.equals(vnfName, vur.vnfName)
- && Objects.equals(vfModuleId, vur.vfModuleId)
- && Objects.equals(vfModuleName, vur.vfModuleName)
- && Objects.equals(keystoneUrl, vur.keystoneUrl)
- && Objects.equals(heatRequest, vur.heatRequest);
- }
+
+ public String getTenantId() {
+ return this.tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getServiceInstanceId() {
+ return this.serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getVnfId() {
+ return this.vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getVnfName() {
+ return this.vnfName;
+ }
+
+ public void setVnfName(String vnfName) {
+ this.vnfName = vnfName;
+ }
+
+ public String getVfModuleId() {
+ return this.vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ public String getVfModuleName() {
+ return this.vfModuleName;
+ }
+
+ public void setVfModuleName(String vfModuleName) {
+ this.vfModuleName = vfModuleName;
+ }
+
+ public String getKeystoneUrl() {
+ return this.keystoneUrl;
+ }
+
+ public void setKeystoneUrl(String keystoneUrl) {
+ this.keystoneUrl = keystoneUrl;
+ }
+
+ public HeatRequest getHeatRequest() {
+ return this.heatRequest;
+ }
+
+ public void setHeatRequest(HeatRequest heatRequest) {
+ this.heatRequest = heatRequest;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(regionId, ownerId, tenantId, serviceInstanceId, vnfId, vnfName, vfModuleId, vfModuleName,
+ keystoneUrl, heatRequest);
+
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof ValetUpdateRequest)) {
+ return false;
+ }
+ ValetUpdateRequest vur = (ValetUpdateRequest) o;
+ return Objects.equals(regionId, vur.regionId) && Objects.equals(ownerId, vur.ownerId)
+ && Objects.equals(tenantId, vur.tenantId) && Objects.equals(serviceInstanceId, vur.serviceInstanceId)
+ && Objects.equals(vnfId, vur.vnfId) && Objects.equals(vnfName, vur.vnfName)
+ && Objects.equals(vfModuleId, vur.vfModuleId) && Objects.equals(vfModuleName, vur.vfModuleName)
+ && Objects.equals(keystoneUrl, vur.keystoneUrl) && Objects.equals(heatRequest, vur.heatRequest);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateResponse.java
index b6cb27caa3..10b6d2a09e 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateResponse.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateResponse.java
@@ -23,49 +23,51 @@ package org.onap.so.adapters.valet.beans;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Objects;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/*
* This class represents the body of an Update response on a Valet Placement API call
*/
public class ValetUpdateResponse implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
- @JsonProperty("status")
- private ValetStatus status;
- @JsonProperty("parameters")
- private HashMap<String, Object> parameters;
-
- public ValetUpdateResponse() {
- super();
- }
-
- public ValetStatus getStatus() {
- return this.status;
- }
- public void setStatus(ValetStatus status) {
- this.status = status;
- }
- public HashMap<String, Object> getParameters() {
- return this.parameters;
- }
- public void setParameters(HashMap<String, Object> parameters) {
- this.parameters = parameters;
- }
+ private static final long serialVersionUID = 768026109321305392L;
+ @JsonProperty("status")
+ private ValetStatus status;
+ @JsonProperty("parameters")
+ private HashMap<String, Object> parameters;
+
+ public ValetUpdateResponse() {
+ super();
+ }
+
+ public ValetStatus getStatus() {
+ return this.status;
+ }
+
+ public void setStatus(ValetStatus status) {
+ this.status = status;
+ }
+
+ public HashMap<String, Object> getParameters() {
+ return this.parameters;
+ }
+
+ public void setParameters(HashMap<String, Object> parameters) {
+ this.parameters = parameters;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(status, parameters);
+ }
- @Override
- public int hashCode() {
- return Objects.hash(status, parameters);
- }
- @Override
- public boolean equals(Object o) {
- if (o == this)
- return true;
- if (!(o instanceof ValetUpdateResponse)) {
- return false;
- }
- ValetUpdateResponse vur = (ValetUpdateResponse) o;
- return Objects.equals(status, vur.status)
- && Objects.equals(parameters, vur.parameters);
- }
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof ValetUpdateResponse)) {
+ return false;
+ }
+ ValetUpdateResponse vur = (ValetUpdateResponse) o;
+ return Objects.equals(status, vur.status) && Objects.equals(parameters, vur.parameters);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java
index b418368170..f8a6e96bc6 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters.vdu.mapper;
import java.util.List;
-
import org.onap.so.adapters.vdu.VduModelInfo;
import org.onap.so.adapters.vdu.VduArtifact;
import org.onap.so.adapters.vdu.VduArtifact.ArtifactType;
@@ -34,98 +33,96 @@ import org.springframework.stereotype.Component;
@Component
public class VfModuleCustomizationToVduMapper {
- public VduModelInfo mapVfModuleCustomizationToVdu(VfModuleCustomization vfModuleCustom)
- {
- VduModelInfo vduModel = new VduModelInfo();
- vduModel.setModelCustomizationUUID(vfModuleCustom.getModelCustomizationUUID());
- vduModel.setModelUUID(vfModuleCustom.getVfModule().getModelUUID());
- vduModel.setModelInvariantUUID(vfModuleCustom.getVfModule().getModelInvariantUUID());
-
- // Map the cloud templates, attached files, and environment file
- mapCloudTemplates(vfModuleCustom.getVfModule().getModuleHeatTemplate(), vduModel);
- mapCloudFiles(vfModuleCustom,vduModel);
- mapEnvironment(vfModuleCustom.getHeatEnvironment(), vduModel);
-
- return vduModel;
- }
-
- public VduModelInfo mapVfModuleCustVolumeToVdu(VfModuleCustomization vfModuleCustom)
- {
- VduModelInfo vduModel = new VduModelInfo();
- vduModel.setModelCustomizationUUID(vfModuleCustom.getModelCustomizationUUID());
- vduModel.setModelUUID(vfModuleCustom.getVfModule().getModelUUID());
- vduModel.setModelInvariantUUID(vfModuleCustom.getVfModule().getModelInvariantUUID());
-
- // Map the cloud templates, attached files, and environment file
- mapCloudTemplates(vfModuleCustom.getVfModule().getVolumeHeatTemplate(), vduModel);
- mapCloudFiles(vfModuleCustom,vduModel);
- mapEnvironment(vfModuleCustom.getVolumeHeatEnv(), vduModel);
-
- return vduModel;
- }
-
- private void mapCloudTemplates(HeatTemplate heatTemplate, VduModelInfo vduModel) {
- // TODO: These catalog objects will be refactored to be non-Heat-specific
-
- List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
-
- // Main template. Also set the VDU timeout based on the main template.
- vduArtifacts.add(mapHeatTemplateToVduArtifact(heatTemplate, ArtifactType.MAIN_TEMPLATE));
- vduModel.setTimeoutMinutes(heatTemplate.getTimeoutMinutes());
-
- // Nested templates
- List<HeatTemplate> childTemplates = heatTemplate.getChildTemplates();
- if (childTemplates != null) {
- for(HeatTemplate childTemplate : childTemplates){
- vduArtifacts.add(mapHeatTemplateToVduArtifact(childTemplate, ArtifactType.NESTED_TEMPLATE));
- }
- }
- }
-
- private VduArtifact mapHeatTemplateToVduArtifact(HeatTemplate heatTemplate, ArtifactType artifactType) {
- VduArtifact vduArtifact = new VduArtifact();
- vduArtifact.setName(heatTemplate.getTemplateName());
- vduArtifact.setContent(heatTemplate.getHeatTemplate().getBytes());
- vduArtifact.setType(artifactType);
- return vduArtifact;
- }
-
- private void mapCloudFiles(VfModuleCustomization vfModuleCustom, VduModelInfo vduModel) {
- // TODO: These catalog objects will be refactored to be non-Heat-specific
-
- List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
-
- // Attached Files
- List<HeatFiles> heatFiles = vfModuleCustom.getVfModule().getHeatFiles();
- if (heatFiles != null) {
- for(HeatFiles file : heatFiles){
- vduArtifacts.add(mapCloudFileToVduArtifact(file, ArtifactType.TEXT_FILE));
- }
- }
- }
-
- private VduArtifact mapCloudFileToVduArtifact(HeatFiles heatFile, ArtifactType artifactType) {
- VduArtifact vduArtifact = new VduArtifact();
- vduArtifact.setName(heatFile.getFileName());
- vduArtifact.setContent(heatFile.getFileBody().getBytes());
- vduArtifact.setType(artifactType);
- return vduArtifact;
- }
-
- private void mapEnvironment(HeatEnvironment heatEnvironment, VduModelInfo vduModel) {
- // TODO: These catalog objects will be refactored to be non-Heat-specific
- if (heatEnvironment != null) {
- List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
- vduArtifacts.add(mapEnvironmentFileToVduArtifact(heatEnvironment));
- }
- }
-
- private VduArtifact mapEnvironmentFileToVduArtifact(HeatEnvironment heatEnv) {
- VduArtifact vduArtifact = new VduArtifact();
- vduArtifact.setName(heatEnv.getName());
- vduArtifact.setContent(heatEnv.getEnvironment().getBytes());
- vduArtifact.setType(ArtifactType.ENVIRONMENT);
- return vduArtifact;
- }
+ public VduModelInfo mapVfModuleCustomizationToVdu(VfModuleCustomization vfModuleCustom) {
+ VduModelInfo vduModel = new VduModelInfo();
+ vduModel.setModelCustomizationUUID(vfModuleCustom.getModelCustomizationUUID());
+ vduModel.setModelUUID(vfModuleCustom.getVfModule().getModelUUID());
+ vduModel.setModelInvariantUUID(vfModuleCustom.getVfModule().getModelInvariantUUID());
+
+ // Map the cloud templates, attached files, and environment file
+ mapCloudTemplates(vfModuleCustom.getVfModule().getModuleHeatTemplate(), vduModel);
+ mapCloudFiles(vfModuleCustom, vduModel);
+ mapEnvironment(vfModuleCustom.getHeatEnvironment(), vduModel);
+
+ return vduModel;
+ }
+
+ public VduModelInfo mapVfModuleCustVolumeToVdu(VfModuleCustomization vfModuleCustom) {
+ VduModelInfo vduModel = new VduModelInfo();
+ vduModel.setModelCustomizationUUID(vfModuleCustom.getModelCustomizationUUID());
+ vduModel.setModelUUID(vfModuleCustom.getVfModule().getModelUUID());
+ vduModel.setModelInvariantUUID(vfModuleCustom.getVfModule().getModelInvariantUUID());
+
+ // Map the cloud templates, attached files, and environment file
+ mapCloudTemplates(vfModuleCustom.getVfModule().getVolumeHeatTemplate(), vduModel);
+ mapCloudFiles(vfModuleCustom, vduModel);
+ mapEnvironment(vfModuleCustom.getVolumeHeatEnv(), vduModel);
+
+ return vduModel;
+ }
+
+ private void mapCloudTemplates(HeatTemplate heatTemplate, VduModelInfo vduModel) {
+ // TODO: These catalog objects will be refactored to be non-Heat-specific
+
+ List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
+
+ // Main template. Also set the VDU timeout based on the main template.
+ vduArtifacts.add(mapHeatTemplateToVduArtifact(heatTemplate, ArtifactType.MAIN_TEMPLATE));
+ vduModel.setTimeoutMinutes(heatTemplate.getTimeoutMinutes());
+
+ // Nested templates
+ List<HeatTemplate> childTemplates = heatTemplate.getChildTemplates();
+ if (childTemplates != null) {
+ for (HeatTemplate childTemplate : childTemplates) {
+ vduArtifacts.add(mapHeatTemplateToVduArtifact(childTemplate, ArtifactType.NESTED_TEMPLATE));
+ }
+ }
+ }
+
+ private VduArtifact mapHeatTemplateToVduArtifact(HeatTemplate heatTemplate, ArtifactType artifactType) {
+ VduArtifact vduArtifact = new VduArtifact();
+ vduArtifact.setName(heatTemplate.getTemplateName());
+ vduArtifact.setContent(heatTemplate.getHeatTemplate().getBytes());
+ vduArtifact.setType(artifactType);
+ return vduArtifact;
+ }
+
+ private void mapCloudFiles(VfModuleCustomization vfModuleCustom, VduModelInfo vduModel) {
+ // TODO: These catalog objects will be refactored to be non-Heat-specific
+
+ List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
+
+ // Attached Files
+ List<HeatFiles> heatFiles = vfModuleCustom.getVfModule().getHeatFiles();
+ if (heatFiles != null) {
+ for (HeatFiles file : heatFiles) {
+ vduArtifacts.add(mapCloudFileToVduArtifact(file, ArtifactType.TEXT_FILE));
+ }
+ }
+ }
+
+ private VduArtifact mapCloudFileToVduArtifact(HeatFiles heatFile, ArtifactType artifactType) {
+ VduArtifact vduArtifact = new VduArtifact();
+ vduArtifact.setName(heatFile.getFileName());
+ vduArtifact.setContent(heatFile.getFileBody().getBytes());
+ vduArtifact.setType(artifactType);
+ return vduArtifact;
+ }
+
+ private void mapEnvironment(HeatEnvironment heatEnvironment, VduModelInfo vduModel) {
+ // TODO: These catalog objects will be refactored to be non-Heat-specific
+ if (heatEnvironment != null) {
+ List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
+ vduArtifacts.add(mapEnvironmentFileToVduArtifact(heatEnvironment));
+ }
+ }
+
+ private VduArtifact mapEnvironmentFileToVduArtifact(HeatEnvironment heatEnv) {
+ VduArtifact vduArtifact = new VduArtifact();
+ vduArtifact.setName(heatEnv.getName());
+ vduArtifact.setContent(heatEnv.getEnvironment().getBytes());
+ vduArtifact.setType(ArtifactType.ENVIRONMENT);
+ return vduArtifact;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java
index 1601de064d..906c285c28 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java
@@ -48,254 +48,250 @@ import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
- * This is the class that is used to POST replies from the MSO adapters to the BPEL engine.
- * It can be configured via property file, or modified using the member methods.
- * The properties to use are:
- * org.onap.so.adapters.vnf.bpelauth encrypted authorization string to send to BEPL engine
- * org.onap.so.adapters.vnf.sockettimeout socket timeout value
- * org.onap.so.adapters.vnf.connecttimeout connect timeout value
- * org.onap.so.adapters.vnf.retrycount number of times to retry failed connections
- * org.onap.so.adapters.vnf.retryinterval interval (in seconds) between retries
- * org.onap.so.adapters.vnf.retrylist list of response codes that will trigger a retry (the special code
- * 900 means "connection was not established")
+ * This is the class that is used to POST replies from the MSO adapters to the BPEL engine. It can be configured via
+ * property file, or modified using the member methods. The properties to use are: org.onap.so.adapters.vnf.bpelauth
+ * encrypted authorization string to send to BEPL engine org.onap.so.adapters.vnf.sockettimeout socket timeout value
+ * org.onap.so.adapters.vnf.connecttimeout connect timeout value org.onap.so.adapters.vnf.retrycount number of times to
+ * retry failed connections org.onap.so.adapters.vnf.retryinterval interval (in seconds) between retries
+ * org.onap.so.adapters.vnf.retrylist list of response codes that will trigger a retry (the special code 900 means
+ * "connection was not established")
*/
@Component
@Scope("prototype")
public class BpelRestClient {
- public static final String MSO_PROP_VNF_ADAPTER = "MSO_PROP_VNF_ADAPTER";
- private static final String PROPERTY_DOMAIN = "org.onap.so.adapters.vnf";
- private static final String BPEL_AUTH_PROPERTY = PROPERTY_DOMAIN+".bpelauth";
- private static final String SOCKET_TIMEOUT_PROPERTY = PROPERTY_DOMAIN+".sockettimeout";
- private static final String CONN_TIMEOUT_PROPERTY = PROPERTY_DOMAIN+".connecttimeout";
- private static final String RETRY_COUNT_PROPERTY = PROPERTY_DOMAIN+".retrycount";
- private static final String RETRY_INTERVAL_PROPERTY = PROPERTY_DOMAIN+".retryinterval";
- private static final String RETRY_LIST_PROPERTY = PROPERTY_DOMAIN+".retrylist";
- private static final String ENCRYPTION_KEY_PROP = "org.onap.so.adapters.network.encryptionKey";
+ public static final String MSO_PROP_VNF_ADAPTER = "MSO_PROP_VNF_ADAPTER";
+ private static final String PROPERTY_DOMAIN = "org.onap.so.adapters.vnf";
+ private static final String BPEL_AUTH_PROPERTY = PROPERTY_DOMAIN + ".bpelauth";
+ private static final String SOCKET_TIMEOUT_PROPERTY = PROPERTY_DOMAIN + ".sockettimeout";
+ private static final String CONN_TIMEOUT_PROPERTY = PROPERTY_DOMAIN + ".connecttimeout";
+ private static final String RETRY_COUNT_PROPERTY = PROPERTY_DOMAIN + ".retrycount";
+ private static final String RETRY_INTERVAL_PROPERTY = PROPERTY_DOMAIN + ".retryinterval";
+ private static final String RETRY_LIST_PROPERTY = PROPERTY_DOMAIN + ".retrylist";
+ private static final String ENCRYPTION_KEY_PROP = "org.onap.so.adapters.network.encryptionKey";
private static final Logger logger = LoggerFactory.getLogger(BpelRestClient.class);
- /** Default socket timeout (in seconds) */
- public static final int DEFAULT_SOCKET_TIMEOUT = 5;
- /** Default connect timeout (in seconds) */
- public static final int DEFAULT_CONNECT_TIMEOUT = 5;
- /** By default, retry up to five times */
- public static final int DEFAULT_RETRY_COUNT = 5;
- /** Default interval to wait between retries (in seconds), negative means use backoff algorithm */
- public static final int DEFAULT_RETRY_INTERVAL = -15;
- /** Default list of response codes to trigger a retry */
- public static final String DEFAULT_RETRY_LIST = "408,429,500,502,503,504,900"; // 900 is "connection failed"
- /** Default credentials */
- public static final String DEFAULT_CREDENTIALS = "";
-
- @Autowired
- private Environment env;
- // Properties of the BPEL client -- all are configurable
- private int socketTimeout;
- private int connectTimeout;
- private int retryCount;
- private int retryInterval;
- private Set<Integer> retryList;
- private String credentials;
-
- // last response from BPEL engine
- private int lastResponseCode;
- private String lastResponse;
-
- /**
- * Create a client to send results to the BPEL engine, using configuration from the
- * MSO_PROP_VNF_ADAPTER properties.
- */
- public BpelRestClient() {
- socketTimeout = DEFAULT_SOCKET_TIMEOUT;
- connectTimeout = DEFAULT_CONNECT_TIMEOUT;
- retryCount = DEFAULT_RETRY_COUNT;
- retryInterval = DEFAULT_RETRY_INTERVAL;
- setRetryList(DEFAULT_RETRY_LIST);
- credentials = DEFAULT_CREDENTIALS;
- lastResponseCode = 0;
- lastResponse = "";
-
- }
-
- @PostConstruct
- protected void init() {
-
- socketTimeout = env.getProperty(SOCKET_TIMEOUT_PROPERTY, Integer.class, DEFAULT_SOCKET_TIMEOUT);
- connectTimeout = env.getProperty(CONN_TIMEOUT_PROPERTY, Integer.class, DEFAULT_CONNECT_TIMEOUT);
- retryCount = env.getProperty(RETRY_COUNT_PROPERTY, Integer.class, DEFAULT_RETRY_COUNT);
- retryInterval = env.getProperty(RETRY_INTERVAL_PROPERTY, Integer.class, DEFAULT_RETRY_INTERVAL);
- setRetryList(env.getProperty(RETRY_LIST_PROPERTY, DEFAULT_RETRY_LIST));
- credentials = getEncryptedProperty(BPEL_AUTH_PROPERTY, DEFAULT_CREDENTIALS, ENCRYPTION_KEY_PROP);
- }
-
- public int getSocketTimeout() {
- return socketTimeout;
- }
-
- public void setSocketTimeout(int socketTimeout) {
- this.socketTimeout = socketTimeout;
- }
-
- public int getConnectTimeout() {
- return connectTimeout;
- }
-
- public void setConnectTimeout(int connectTimeout) {
- this.connectTimeout = connectTimeout;
- }
-
- public int getRetryCount() {
- return retryCount;
- }
-
- public void setRetryCount(int retryCount) {
- int newRetryCount = retryCount;
- if (newRetryCount < 0)
- newRetryCount = DEFAULT_RETRY_COUNT;
- this.retryCount = newRetryCount;
- }
-
- public int getRetryInterval() {
- return retryInterval;
- }
-
- public void setRetryInterval(int retryInterval) {
- this.retryInterval = retryInterval;
- }
-
- public String getCredentials() {
- return credentials;
- }
-
- public void setCredentials(String credentials) {
- this.credentials = credentials;
- }
-
- public String getRetryList() {
- if (retryList.isEmpty())
- return "";
- String t = retryList.toString();
- return t.substring(1, t.length()-1);
- }
-
- public void setRetryList(String retryList) {
- Set<Integer> s = new TreeSet<>();
- for (String t : retryList.split("[, ]")) {
- try {
- s.add(Integer.parseInt(t));
- } catch (NumberFormatException x) {
- // ignore
- }
- }
- this.retryList = s;
- }
-
- public int getLastResponseCode() {
- return lastResponseCode;
- }
-
- public String getLastResponse() {
- return lastResponse;
- }
-
- /**
- * Post a response to the URL of the BPEL engine. As long as the response code is one of those in
- * the retryList, the post will be retried up to "retrycount" times with an interval (in seconds)
- * of "retryInterval". If retryInterval is negative, then each successive retry interval will be
- * double the previous one.
- * @param toBpelStr the content (XML or JSON) to post
- * @param bpelUrl the URL to post to
- * @param isxml true if the content is XML, otherwise assumed to be JSON
- * @return true if the post succeeded, false if all retries failed
- */
- public boolean bpelPost(final String toBpelStr, final String bpelUrl, final boolean isxml) {
- debug("Sending response to BPEL: " + toBpelStr);
- int totalretries = 0;
- int retryint = retryInterval;
- while (true) {
- sendOne(toBpelStr, bpelUrl, isxml);
- // Note: really should handle response code 415 by switching between content types if needed
- if (!retryList.contains(lastResponseCode)) {
- debug("Got response code: " + lastResponseCode + ": returning.");
- return true;
- }
- if (totalretries >= retryCount) {
- debug("Retried " + totalretries + " times, giving up.");
- logger.error("{} {} Could not deliver response to BPEL after {} tries: {}", MessageEnum.RA_SEND_VNF_NOTIF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), totalretries, toBpelStr);
- return false;
- }
- totalretries++;
- int sleepinterval = retryint;
- if (retryint < 0) {
- // if retry interval is negative double the retry on each pass
- sleepinterval = -retryint;
- retryint *= 2;
- }
- debug("Sleeping for " + sleepinterval + " seconds.");
- try {
- Thread.sleep(sleepinterval * 1000L);
- } catch (InterruptedException e) {
- logger.debug("Exception while Thread sleep", e);
- Thread.currentThread().interrupt();
- }
- }
- }
- private void debug(String m) {
- logger.debug(m);
- }
- private void sendOne(final String toBpelStr, final String bpelUrl, final boolean isxml) {
- logger.debug("Sending to BPEL server: {}", bpelUrl);
- logger.debug("Content is: {}", toBpelStr);
-
- //POST
- HttpPost post = new HttpPost(bpelUrl);
- if (credentials != null && !credentials.isEmpty())
- post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes()));
-
- logger.debug("HTTPPost Headers: {}", post.getAllHeaders());
-
- //ContentType
+ /** Default socket timeout (in seconds) */
+ public static final int DEFAULT_SOCKET_TIMEOUT = 5;
+ /** Default connect timeout (in seconds) */
+ public static final int DEFAULT_CONNECT_TIMEOUT = 5;
+ /** By default, retry up to five times */
+ public static final int DEFAULT_RETRY_COUNT = 5;
+ /** Default interval to wait between retries (in seconds), negative means use backoff algorithm */
+ public static final int DEFAULT_RETRY_INTERVAL = -15;
+ /** Default list of response codes to trigger a retry */
+ public static final String DEFAULT_RETRY_LIST = "408,429,500,502,503,504,900"; // 900 is "connection failed"
+ /** Default credentials */
+ public static final String DEFAULT_CREDENTIALS = "";
+
+ @Autowired
+ private Environment env;
+ // Properties of the BPEL client -- all are configurable
+ private int socketTimeout;
+ private int connectTimeout;
+ private int retryCount;
+ private int retryInterval;
+ private Set<Integer> retryList;
+ private String credentials;
+
+ // last response from BPEL engine
+ private int lastResponseCode;
+ private String lastResponse;
+
+ /**
+ * Create a client to send results to the BPEL engine, using configuration from the MSO_PROP_VNF_ADAPTER properties.
+ */
+ public BpelRestClient() {
+ socketTimeout = DEFAULT_SOCKET_TIMEOUT;
+ connectTimeout = DEFAULT_CONNECT_TIMEOUT;
+ retryCount = DEFAULT_RETRY_COUNT;
+ retryInterval = DEFAULT_RETRY_INTERVAL;
+ setRetryList(DEFAULT_RETRY_LIST);
+ credentials = DEFAULT_CREDENTIALS;
+ lastResponseCode = 0;
+ lastResponse = "";
+
+ }
+
+ @PostConstruct
+ protected void init() {
+
+ socketTimeout = env.getProperty(SOCKET_TIMEOUT_PROPERTY, Integer.class, DEFAULT_SOCKET_TIMEOUT);
+ connectTimeout = env.getProperty(CONN_TIMEOUT_PROPERTY, Integer.class, DEFAULT_CONNECT_TIMEOUT);
+ retryCount = env.getProperty(RETRY_COUNT_PROPERTY, Integer.class, DEFAULT_RETRY_COUNT);
+ retryInterval = env.getProperty(RETRY_INTERVAL_PROPERTY, Integer.class, DEFAULT_RETRY_INTERVAL);
+ setRetryList(env.getProperty(RETRY_LIST_PROPERTY, DEFAULT_RETRY_LIST));
+ credentials = getEncryptedProperty(BPEL_AUTH_PROPERTY, DEFAULT_CREDENTIALS, ENCRYPTION_KEY_PROP);
+ }
+
+ public int getSocketTimeout() {
+ return socketTimeout;
+ }
+
+ public void setSocketTimeout(int socketTimeout) {
+ this.socketTimeout = socketTimeout;
+ }
+
+ public int getConnectTimeout() {
+ return connectTimeout;
+ }
+
+ public void setConnectTimeout(int connectTimeout) {
+ this.connectTimeout = connectTimeout;
+ }
+
+ public int getRetryCount() {
+ return retryCount;
+ }
+
+ public void setRetryCount(int retryCount) {
+ int newRetryCount = retryCount;
+ if (newRetryCount < 0)
+ newRetryCount = DEFAULT_RETRY_COUNT;
+ this.retryCount = newRetryCount;
+ }
+
+ public int getRetryInterval() {
+ return retryInterval;
+ }
+
+ public void setRetryInterval(int retryInterval) {
+ this.retryInterval = retryInterval;
+ }
+
+ public String getCredentials() {
+ return credentials;
+ }
+
+ public void setCredentials(String credentials) {
+ this.credentials = credentials;
+ }
+
+ public String getRetryList() {
+ if (retryList.isEmpty())
+ return "";
+ String t = retryList.toString();
+ return t.substring(1, t.length() - 1);
+ }
+
+ public void setRetryList(String retryList) {
+ Set<Integer> s = new TreeSet<>();
+ for (String t : retryList.split("[, ]")) {
+ try {
+ s.add(Integer.parseInt(t));
+ } catch (NumberFormatException x) {
+ // ignore
+ }
+ }
+ this.retryList = s;
+ }
+
+ public int getLastResponseCode() {
+ return lastResponseCode;
+ }
+
+ public String getLastResponse() {
+ return lastResponse;
+ }
+
+ /**
+ * Post a response to the URL of the BPEL engine. As long as the response code is one of those in the retryList, the
+ * post will be retried up to "retrycount" times with an interval (in seconds) of "retryInterval". If retryInterval
+ * is negative, then each successive retry interval will be double the previous one.
+ *
+ * @param toBpelStr the content (XML or JSON) to post
+ * @param bpelUrl the URL to post to
+ * @param isxml true if the content is XML, otherwise assumed to be JSON
+ * @return true if the post succeeded, false if all retries failed
+ */
+ public boolean bpelPost(final String toBpelStr, final String bpelUrl, final boolean isxml) {
+ debug("Sending response to BPEL: " + toBpelStr);
+ int totalretries = 0;
+ int retryint = retryInterval;
+ while (true) {
+ sendOne(toBpelStr, bpelUrl, isxml);
+ // Note: really should handle response code 415 by switching between content types if needed
+ if (!retryList.contains(lastResponseCode)) {
+ debug("Got response code: " + lastResponseCode + ": returning.");
+ return true;
+ }
+ if (totalretries >= retryCount) {
+ debug("Retried " + totalretries + " times, giving up.");
+ logger.error("{} {} Could not deliver response to BPEL after {} tries: {}",
+ MessageEnum.RA_SEND_VNF_NOTIF_ERR, ErrorCode.BusinessProcesssError.getValue(), totalretries,
+ toBpelStr);
+ return false;
+ }
+ totalretries++;
+ int sleepinterval = retryint;
+ if (retryint < 0) {
+ // if retry interval is negative double the retry on each pass
+ sleepinterval = -retryint;
+ retryint *= 2;
+ }
+ debug("Sleeping for " + sleepinterval + " seconds.");
+ try {
+ Thread.sleep(sleepinterval * 1000L);
+ } catch (InterruptedException e) {
+ logger.debug("Exception while Thread sleep", e);
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ private void debug(String m) {
+ logger.debug(m);
+ }
+
+ private void sendOne(final String toBpelStr, final String bpelUrl, final boolean isxml) {
+ logger.debug("Sending to BPEL server: {}", bpelUrl);
+ logger.debug("Content is: {}", toBpelStr);
+
+ // POST
+ HttpPost post = new HttpPost(bpelUrl);
+ if (credentials != null && !credentials.isEmpty())
+ post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes()));
+
+ logger.debug("HTTPPost Headers: {}", post.getAllHeaders());
+
+ // ContentType
ContentType ctype = isxml ? ContentType.APPLICATION_XML : ContentType.APPLICATION_JSON;
post.setEntity(new StringEntity(toBpelStr, ctype));
- //Timeouts
- RequestConfig requestConfig = RequestConfig
- .custom()
- .setSocketTimeout(socketTimeout * 1000)
- .setConnectTimeout(connectTimeout * 1000)
- .build();
- post.setConfig(requestConfig);
-
+ // Timeouts
+ RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout * 1000)
+ .setConnectTimeout(connectTimeout * 1000).build();
+ post.setConfig(requestConfig);
+
try (CloseableHttpClient client = HttpClients.createDefault()) {
- CloseableHttpResponse response = client.execute(post);
- if (response != null) {
- lastResponseCode = response.getStatusLine().getStatusCode();
- HttpEntity entity = response.getEntity();
- lastResponse = (entity != null) ? EntityUtils.toString(entity) : "";
- } else {
- lastResponseCode = 900;
- lastResponse = "";
- }
- } catch (Exception e) {
+ CloseableHttpResponse response = client.execute(post);
+ if (response != null) {
+ lastResponseCode = response.getStatusLine().getStatusCode();
+ HttpEntity entity = response.getEntity();
+ lastResponse = (entity != null) ? EntityUtils.toString(entity) : "";
+ } else {
+ lastResponseCode = 900;
+ lastResponse = "";
+ }
+ } catch (Exception e) {
logger.error("{} {} Exception - Error sending Bpel notification: {} ", MessageEnum.RA_SEND_VNF_NOTIF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), toBpelStr, e);
- lastResponseCode = 900;
- lastResponse = "";
- }
-
- logger.debug("Response code from BPEL server: {}", lastResponseCode);
- logger.debug("Response body is: {}", lastResponse);
- }
-
- private String getEncryptedProperty(String key, String defaultValue, String encryptionKey) {
- if (env.getProperty(key) != null) {
- try {
- return CryptoUtils.decrypt(env.getProperty(key), env.getProperty(encryptionKey));
- } catch (GeneralSecurityException e) {
- logger.debug("Exception while decrypting property: {} ", env.getProperty(key), e);
- }
- }
- return defaultValue;
- }
+ ErrorCode.BusinessProcesssError.getValue(), toBpelStr, e);
+ lastResponseCode = 900;
+ lastResponse = "";
+ }
+
+ logger.debug("Response code from BPEL server: {}", lastResponseCode);
+ logger.debug("Response body is: {}", lastResponse);
+ }
+
+ private String getEncryptedProperty(String key, String defaultValue, String encryptionKey) {
+ if (env.getProperty(key) != null) {
+ try {
+ return CryptoUtils.decrypt(env.getProperty(key), env.getProperty(encryptionKey));
+ } catch (GeneralSecurityException e) {
+ logger.debug("Exception while decrypting property: {} ", env.getProperty(key), e);
+ }
+ }
+ return defaultValue;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java
index bbfcef02e2..7786b872ef 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java
@@ -31,162 +31,159 @@ import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
-
import org.onap.so.adapters.vdu.VduArtifact;
import org.onap.so.adapters.vdu.VduArtifact.ArtifactType;
import org.onap.so.adapters.vdu.VduModelInfo;
import org.onap.so.adapters.vnf.exceptions.VnfException;
-
import com.google.common.io.Files;
/**
- * The purpose of this class is to create a CSAR byte array from Vdu inputs for the purpose
- * of forwarding to a TOSCA orchestrator.
+ * The purpose of this class is to create a CSAR byte array from Vdu inputs for the purpose of forwarding to a TOSCA
+ * orchestrator.
*
* @author DeWayne
*
*/
public class CSAR {
- private static final String MANIFEST_FILENAME = "MANIFEST.MF";
- private VduModelInfo vduModel;
-
- public CSAR(VduModelInfo model){
- this.vduModel = model;
- }
-
- /**
- * Creates a byte array representation of a CSAR corresponding to the VduBlueprint arg in the
- * constructor.
- *
- * @return
- * @throws VnfException
- */
- public byte[] create() {
- File dir = Files.createTempDir();
-
- /**
- * Create subdir
- */
- File metadir = new File(dir.getAbsolutePath() + "/TOSCA-Metadata");
- if (!metadir.mkdir()) {
- throw new RuntimeException("CSAR TOSCA-Metadata directory create failed");
- }
-
- /**
- * Organize model info for consumption
- */
- VduArtifact mainTemplate = null;
- List<VduArtifact> extraFiles = new ArrayList<>();
- for(VduArtifact artifact: vduModel.getArtifacts()) {
- if(artifact.getType() == ArtifactType.MAIN_TEMPLATE ) {
- mainTemplate = artifact;
- } else{
- extraFiles.add(artifact);
- }
- }
-
- if (mainTemplate == null) { // make a dummy to avoid null pointers
- mainTemplate = new VduArtifact("", new byte[0], null);
- }
-
- /**
- * Write template files
- */
- try (OutputStream ofs = new FileOutputStream(new File(dir, mainTemplate.getName()));
- PrintStream mfstream = new PrintStream(new File(metadir.getAbsolutePath() + '/' + MANIFEST_FILENAME));
- ) {
- ofs.write(mainTemplate.getContent());
-
- /**
- * Write other files
- */
- if (!extraFiles.isEmpty()) {
- for (VduArtifact artifact: extraFiles){
- try (OutputStream out = new FileOutputStream(new File(dir, artifact.getName()));) {
- out.write(artifact.getContent());
- }
- }
- }
-
-
- /**
- * Create manifest
- */
- mfstream.println("TOSCA-Meta-File-Version: 1.0");
- mfstream.println("CSAR-Version: 1.1");
- mfstream.println("Created-by: ONAP");
- mfstream.println("Entry-Definitions: " + mainTemplate.getName());
-
- /**
- * ZIP it up
- */
- ByteArrayOutputStream zipbytes = new ByteArrayOutputStream();
- ZipOutputStream zos = new ZipOutputStream(zipbytes);
- compressTree(zos, "", dir, dir);
- zos.close();
- return zipbytes.toByteArray();
-
- } catch (Exception e) {
- throw new RuntimeException("Failed to create CSAR: " + e.getMessage());
- } finally {
- /**
- * Clean up tmpdir
- */
- deleteDirectory(dir);
- }
- }
-
- /**
- * Private methods
- */
-
- /**
- * Compresses (ZIPs) a directory tree
- *
- * @param dir
- * @throws IOException
- */
- private void compressTree(ZipOutputStream zos, String path, File basedir, File dir) throws IOException {
- if (!dir.isDirectory())
- return;
-
- for (File f : dir.listFiles()) {
- if (f.isDirectory()) {
- String newpath = path + f.getName() + '/';
- ZipEntry entry = new ZipEntry(newpath);
- zos.putNextEntry(entry);
- zos.closeEntry();
- compressTree(zos, newpath, basedir, f);
- } else {
- ZipEntry ze = new ZipEntry(
- f.getAbsolutePath().substring(basedir.getAbsolutePath().length() + 1).replaceAll("\\\\", "/"));
- zos.putNextEntry(ze);
- // read the file and write to ZipOutputStream
- try (FileInputStream fis = new FileInputStream(f);) {
- byte[] buffer = new byte[1024];
- int len;
- while ((len = fis.read(buffer)) > 0) {
- zos.write(buffer, 0, len);
- }
- }
- zos.closeEntry();
- }
- }
- }
-
- private boolean deleteDirectory(File directory) {
- if (directory.exists()) {
- File[] files = directory.listFiles();
- if (null != files) {
- for (int i = 0; i < files.length; i++) {
- if (files[i].isDirectory()) {
- deleteDirectory(files[i]);
- } else {
- files[i].delete();
- }
- }
- }
- }
- return (directory.delete());
- }
+ private static final String MANIFEST_FILENAME = "MANIFEST.MF";
+ private VduModelInfo vduModel;
+
+ public CSAR(VduModelInfo model) {
+ this.vduModel = model;
+ }
+
+ /**
+ * Creates a byte array representation of a CSAR corresponding to the VduBlueprint arg in the constructor.
+ *
+ * @return
+ * @throws VnfException
+ */
+ public byte[] create() {
+ File dir = Files.createTempDir();
+
+ /**
+ * Create subdir
+ */
+ File metadir = new File(dir.getAbsolutePath() + "/TOSCA-Metadata");
+ if (!metadir.mkdir()) {
+ throw new RuntimeException("CSAR TOSCA-Metadata directory create failed");
+ }
+
+ /**
+ * Organize model info for consumption
+ */
+ VduArtifact mainTemplate = null;
+ List<VduArtifact> extraFiles = new ArrayList<>();
+ for (VduArtifact artifact : vduModel.getArtifacts()) {
+ if (artifact.getType() == ArtifactType.MAIN_TEMPLATE) {
+ mainTemplate = artifact;
+ } else {
+ extraFiles.add(artifact);
+ }
+ }
+
+ if (mainTemplate == null) { // make a dummy to avoid null pointers
+ mainTemplate = new VduArtifact("", new byte[0], null);
+ }
+
+ /**
+ * Write template files
+ */
+ try (OutputStream ofs = new FileOutputStream(new File(dir, mainTemplate.getName()));
+ PrintStream mfstream =
+ new PrintStream(new File(metadir.getAbsolutePath() + '/' + MANIFEST_FILENAME));) {
+ ofs.write(mainTemplate.getContent());
+
+ /**
+ * Write other files
+ */
+ if (!extraFiles.isEmpty()) {
+ for (VduArtifact artifact : extraFiles) {
+ try (OutputStream out = new FileOutputStream(new File(dir, artifact.getName()));) {
+ out.write(artifact.getContent());
+ }
+ }
+ }
+
+
+ /**
+ * Create manifest
+ */
+ mfstream.println("TOSCA-Meta-File-Version: 1.0");
+ mfstream.println("CSAR-Version: 1.1");
+ mfstream.println("Created-by: ONAP");
+ mfstream.println("Entry-Definitions: " + mainTemplate.getName());
+
+ /**
+ * ZIP it up
+ */
+ ByteArrayOutputStream zipbytes = new ByteArrayOutputStream();
+ ZipOutputStream zos = new ZipOutputStream(zipbytes);
+ compressTree(zos, "", dir, dir);
+ zos.close();
+ return zipbytes.toByteArray();
+
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to create CSAR: " + e.getMessage());
+ } finally {
+ /**
+ * Clean up tmpdir
+ */
+ deleteDirectory(dir);
+ }
+ }
+
+ /**
+ * Private methods
+ */
+
+ /**
+ * Compresses (ZIPs) a directory tree
+ *
+ * @param dir
+ * @throws IOException
+ */
+ private void compressTree(ZipOutputStream zos, String path, File basedir, File dir) throws IOException {
+ if (!dir.isDirectory())
+ return;
+
+ for (File f : dir.listFiles()) {
+ if (f.isDirectory()) {
+ String newpath = path + f.getName() + '/';
+ ZipEntry entry = new ZipEntry(newpath);
+ zos.putNextEntry(entry);
+ zos.closeEntry();
+ compressTree(zos, newpath, basedir, f);
+ } else {
+ ZipEntry ze = new ZipEntry(
+ f.getAbsolutePath().substring(basedir.getAbsolutePath().length() + 1).replaceAll("\\\\", "/"));
+ zos.putNextEntry(ze);
+ // read the file and write to ZipOutputStream
+ try (FileInputStream fis = new FileInputStream(f);) {
+ byte[] buffer = new byte[1024];
+ int len;
+ while ((len = fis.read(buffer)) > 0) {
+ zos.write(buffer, 0, len);
+ }
+ }
+ zos.closeEntry();
+ }
+ }
+ }
+
+ private boolean deleteDirectory(File directory) {
+ if (directory.exists()) {
+ File[] files = directory.listFiles();
+ if (null != files) {
+ for (int i = 0; i < files.length; i++) {
+ if (files[i].isDirectory()) {
+ deleteDirectory(files[i]);
+ } else {
+ files[i].delete();
+ }
+ }
+ }
+ }
+ return (directory.delete());
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapter.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapter.java
index 349aa78d44..f6ea2261d7 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapter.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapter.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.vnf;
import java.util.Map;
-
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebParam.Mode;
@@ -30,7 +29,6 @@ import javax.jws.WebService;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.ws.Holder;
-
import org.onap.so.adapters.vnf.exceptions.VnfAlreadyExists;
import org.onap.so.adapters.vnf.exceptions.VnfException;
import org.onap.so.entity.MsoRequest;
@@ -38,121 +36,112 @@ import org.onap.so.openstack.beans.VnfRollback;
import org.onap.so.openstack.beans.VnfStatus;
import org.onap.so.openstack.mappers.MapAdapter;
-@WebService (name="VnfAdapter", targetNamespace="http://org.onap.so/vnf")
-public interface MsoVnfAdapter
-{
- /**
- * This is the "Create VNF" Web Service Endpoint definition.
- */
- @WebMethod
- public void createVnf (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="vnfType") @XmlElement(required=true) String vnfType,
- @WebParam(name="vnfVersion") @XmlElement(required=false) String vnfVersion,
- @WebParam(name="vnfName") @XmlElement(required=true) String vnfName,
- @WebParam(name="requestType") @XmlElement(required=false) String requestType,
- @WebParam(name="volumeGroupHeatStackId") @XmlElement(required=false) String volumeGroupHeatStackId,
- @WebParam(name="inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String,Object> inputs,
- @WebParam(name="failIfExists") Boolean failIfExists,
- @WebParam(name="backout") Boolean backout,
- @WebParam(name="enableBridge") Boolean enableBridge,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="vnfId", mode=Mode.OUT) Holder<String> vnfId,
- @WebParam(name="outputs", mode=Mode.OUT) Holder<Map<String,String>> outputs,
- @WebParam(name="rollback", mode=Mode.OUT) Holder<VnfRollback> rollback )
- throws VnfException, VnfAlreadyExists;
+@WebService(name = "VnfAdapter", targetNamespace = "http://org.onap.so/vnf")
+public interface MsoVnfAdapter {
+ /**
+ * This is the "Create VNF" Web Service Endpoint definition.
+ */
+ @WebMethod
+ public void createVnf(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "vnfType") @XmlElement(required = true) String vnfType,
+ @WebParam(name = "vnfVersion") @XmlElement(required = false) String vnfVersion,
+ @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName,
+ @WebParam(name = "requestType") @XmlElement(required = false) String requestType,
+ @WebParam(name = "volumeGroupHeatStackId") @XmlElement(required = false) String volumeGroupHeatStackId,
+ @WebParam(name = "inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> inputs,
+ @WebParam(name = "failIfExists") Boolean failIfExists, @WebParam(name = "backout") Boolean backout,
+ @WebParam(name = "enableBridge") Boolean enableBridge, @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "vnfId", mode = Mode.OUT) Holder<String> vnfId,
+ @WebParam(name = "outputs", mode = Mode.OUT) Holder<Map<String, String>> outputs,
+ @WebParam(name = "rollback", mode = Mode.OUT) Holder<VnfRollback> rollback)
+ throws VnfException, VnfAlreadyExists;
- @WebMethod
- public void updateVnf (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="vnfType") @XmlElement(required=true) String vnfType,
- @WebParam(name="vnfVersion") @XmlElement(required=false) String vnfVersion,
- @WebParam(name="vnfName") @XmlElement(required=true) String vnfName,
- @WebParam(name="requestType") @XmlElement(required=false) String requestType,
- @WebParam(name="volumeGroupHeatStackId") @XmlElement(required=false) String volumeGroupHeatStackId,
- @WebParam(name="inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String,Object> inputs,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="outputs", mode=Mode.OUT) Holder<Map<String,String>> outputs,
- @WebParam(name="rollback", mode=Mode.OUT) Holder<VnfRollback> rollback )
- throws VnfException;
+ @WebMethod
+ public void updateVnf(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "vnfType") @XmlElement(required = true) String vnfType,
+ @WebParam(name = "vnfVersion") @XmlElement(required = false) String vnfVersion,
+ @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName,
+ @WebParam(name = "requestType") @XmlElement(required = false) String requestType,
+ @WebParam(name = "volumeGroupHeatStackId") @XmlElement(required = false) String volumeGroupHeatStackId,
+ @WebParam(name = "inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> inputs,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "outputs", mode = Mode.OUT) Holder<Map<String, String>> outputs,
+ @WebParam(name = "rollback", mode = Mode.OUT) Holder<VnfRollback> rollback) throws VnfException;
- @WebMethod
- public void queryVnf (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="vnfName") @XmlElement(required=true) String vnfName,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="vnfExists", mode=Mode.OUT) Holder<Boolean> vnfExists,
- @WebParam(name="vnfId", mode=Mode.OUT) Holder<String> vnfId,
- @WebParam(name="status", mode=Mode.OUT) Holder<VnfStatus> status,
- @WebParam(name="outputs", mode=Mode.OUT) Holder<Map<String,String>> outputs )
- throws VnfException;
+ @WebMethod
+ public void queryVnf(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "vnfExists", mode = Mode.OUT) Holder<Boolean> vnfExists,
+ @WebParam(name = "vnfId", mode = Mode.OUT) Holder<String> vnfId,
+ @WebParam(name = "status", mode = Mode.OUT) Holder<VnfStatus> status,
+ @WebParam(name = "outputs", mode = Mode.OUT) Holder<Map<String, String>> outputs) throws VnfException;
- @WebMethod
- public void deleteVnf (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="vnfName") @XmlElement(required=true) String vnfName,
- @WebParam(name="request") MsoRequest msoRequest)
- throws VnfException;
+ @WebMethod
+ public void deleteVnf(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName,
+ @WebParam(name = "request") MsoRequest msoRequest) throws VnfException;
- @WebMethod
- public void rollbackVnf (@WebParam(name="rollback") @XmlElement(required=true) VnfRollback rollback)
- throws VnfException;
+ @WebMethod
+ public void rollbackVnf(@WebParam(name = "rollback") @XmlElement(required = true) VnfRollback rollback)
+ throws VnfException;
- @WebMethod
- public void createVfModule (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="vnfType") @XmlElement(required=true) String vnfType,
- @WebParam(name="vnfVersion") @XmlElement(required=false) String vnfVersion,
- @WebParam(name="genericVnfId") @XmlElement(required=true) String genericVnfId,
- @WebParam(name="vnfName") @XmlElement(required=true) String vnfName,
- @WebParam(name="vfModuleId") @XmlElement(required=true) String vfModuleId,
- @WebParam(name="requestType") @XmlElement(required=false) String requestType,
- @WebParam(name="volumeGroupHeatStackId") @XmlElement(required=false) String volumeGroupHeatStackId,
- @WebParam(name="baseVfHeatStackId") @XmlElement(required=false) String baseVfHeatStackId,
- @WebParam(name = "modelCustomizationUuid") @XmlElement(required = false) String modelCustomizationUuid,
- @WebParam(name="inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String,Object> inputs,
- @WebParam(name="failIfExists") Boolean failIfExists,
- @WebParam(name="backout") Boolean backout,
- @WebParam(name="enableBridge") Boolean enableBridge,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="vnfId", mode=Mode.OUT) Holder<String> vnfId,
- @WebParam(name="outputs", mode=Mode.OUT) Holder<Map<String,String>> outputs,
- @WebParam(name="rollback", mode=Mode.OUT) Holder<VnfRollback> rollback )
- throws VnfException, VnfAlreadyExists;
+ @WebMethod
+ public void createVfModule(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "vnfType") @XmlElement(required = true) String vnfType,
+ @WebParam(name = "vnfVersion") @XmlElement(required = false) String vnfVersion,
+ @WebParam(name = "genericVnfId") @XmlElement(required = true) String genericVnfId,
+ @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName,
+ @WebParam(name = "vfModuleId") @XmlElement(required = true) String vfModuleId,
+ @WebParam(name = "requestType") @XmlElement(required = false) String requestType,
+ @WebParam(name = "volumeGroupHeatStackId") @XmlElement(required = false) String volumeGroupHeatStackId,
+ @WebParam(name = "baseVfHeatStackId") @XmlElement(required = false) String baseVfHeatStackId,
+ @WebParam(name = "modelCustomizationUuid") @XmlElement(required = false) String modelCustomizationUuid,
+ @WebParam(name = "inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> inputs,
+ @WebParam(name = "failIfExists") Boolean failIfExists, @WebParam(name = "backout") Boolean backout,
+ @WebParam(name = "enableBridge") Boolean enableBridge, @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "vnfId", mode = Mode.OUT) Holder<String> vnfId,
+ @WebParam(name = "outputs", mode = Mode.OUT) Holder<Map<String, String>> outputs,
+ @WebParam(name = "rollback", mode = Mode.OUT) Holder<VnfRollback> rollback)
+ throws VnfException, VnfAlreadyExists;
- @WebMethod
- public void deleteVfModule (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="vfName") @XmlElement(required=true) String vfName,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name = "vfModuleOutputs", mode = Mode.OUT) Holder<Map<String, String>> vfModuleOutputs)
- throws VnfException;
+ @WebMethod
+ public void deleteVfModule(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "vfName") @XmlElement(required = true) String vfName,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "vfModuleOutputs", mode = Mode.OUT) Holder<Map<String, String>> vfModuleOutputs)
+ throws VnfException;
- @WebMethod
- public void updateVfModule (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="vnfType") @XmlElement(required=true) String vnfType,
- @WebParam(name="vnfVersion") @XmlElement(required=false) String vnfVersion,
- @WebParam(name="vnfName") @XmlElement(required=true) String vnfName,
- @WebParam(name="requestType") @XmlElement(required=false) String requestType,
- @WebParam(name="volumeGroupHeatStackId") @XmlElement(required=false) String volumeGroupHeatStackId,
- @WebParam(name="baseVfHeatStackId") @XmlElement(required=false) String baseVfHeatStackId,
- @WebParam(name="vfModuleStackId") @XmlElement(required=false) String vfModuleStackId,
- @WebParam(name = "modelCustomizationUuid") @XmlElement(required = false) String modelCustomizationUuid,
- @WebParam(name="inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String,Object> inputs,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="outputs", mode=Mode.OUT) Holder<Map<String,String>> outputs,
- @WebParam(name="rollback", mode=Mode.OUT) Holder<VnfRollback> rollback )
- throws VnfException;
+ @WebMethod
+ public void updateVfModule(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "vnfType") @XmlElement(required = true) String vnfType,
+ @WebParam(name = "vnfVersion") @XmlElement(required = false) String vnfVersion,
+ @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName,
+ @WebParam(name = "requestType") @XmlElement(required = false) String requestType,
+ @WebParam(name = "volumeGroupHeatStackId") @XmlElement(required = false) String volumeGroupHeatStackId,
+ @WebParam(name = "baseVfHeatStackId") @XmlElement(required = false) String baseVfHeatStackId,
+ @WebParam(name = "vfModuleStackId") @XmlElement(required = false) String vfModuleStackId,
+ @WebParam(name = "modelCustomizationUuid") @XmlElement(required = false) String modelCustomizationUuid,
+ @WebParam(name = "inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> inputs,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "outputs", mode = Mode.OUT) Holder<Map<String, String>> outputs,
+ @WebParam(name = "rollback", mode = Mode.OUT) Holder<VnfRollback> rollback) throws VnfException;
- @WebMethod
- public void healthCheck ();
+ @WebMethod
+ public void healthCheck();
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsync.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsync.java
index 5642e01a72..13ca78a1f5 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsync.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsync.java
@@ -22,90 +22,85 @@ package org.onap.so.adapters.vnf;
import java.util.Map;
-
import javax.jws.Oneway;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
-
import org.onap.so.entity.MsoRequest;
import org.onap.so.openstack.beans.VnfRollback;
import org.onap.so.openstack.mappers.MapAdapter;
/**
- * This webservice defines the Asynchronous versions of VNF adapter calls.
- * The notification messages for final responses are documented elsewhere
- * (by the client service WSDL).
+ * This webservice defines the Asynchronous versions of VNF adapter calls. The notification messages for final responses
+ * are documented elsewhere (by the client service WSDL).
*
*/
-@WebService (name="VnfAdapterAsync", targetNamespace="http://org.onap.so/vnfA")
-public interface MsoVnfAdapterAsync
-{
- /**
- * This is the "Create VNF" Web Service Endpoint definition.
- */
- @WebMethod
- @Oneway
- public void createVnfA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="vnfType") @XmlElement(required=true) String vnfType,
- @WebParam(name="vnfVersion") @XmlElement(required=false) String vnfVersion,
- @WebParam(name="vnfName") @XmlElement(required=true) String vnfName,
- @WebParam(name="requestType") @XmlElement(required=false) String requestType,
- @WebParam(name="volumeGroupHeatStackId") @XmlElement(required=false) String volumeGroupHeatStackId,
- @WebParam(name="inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String,Object> inputs,
- @WebParam(name="failIfExists") Boolean failIfExists,
- @WebParam(name="backout") Boolean backout,
- @WebParam(name="enableBridge") Boolean enableBridge,
- @WebParam(name="messageId") @XmlElement(required=true) String messageId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl );
+@WebService(name = "VnfAdapterAsync", targetNamespace = "http://org.onap.so/vnfA")
+public interface MsoVnfAdapterAsync {
+ /**
+ * This is the "Create VNF" Web Service Endpoint definition.
+ */
+ @WebMethod
+ @Oneway
+ public void createVnfA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "vnfType") @XmlElement(required = true) String vnfType,
+ @WebParam(name = "vnfVersion") @XmlElement(required = false) String vnfVersion,
+ @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName,
+ @WebParam(name = "requestType") @XmlElement(required = false) String requestType,
+ @WebParam(name = "volumeGroupHeatStackId") @XmlElement(required = false) String volumeGroupHeatStackId,
+ @WebParam(name = "inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> inputs,
+ @WebParam(name = "failIfExists") Boolean failIfExists, @WebParam(name = "backout") Boolean backout,
+ @WebParam(name = "enableBridge") Boolean enableBridge,
+ @WebParam(name = "messageId") @XmlElement(required = true) String messageId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl);
- @WebMethod
- @Oneway
- public void updateVnfA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="vnfType") @XmlElement(required=true) String vnfType,
- @WebParam(name="vnfVersion") @XmlElement(required=false) String vnfVersion,
- @WebParam(name="vnfName") @XmlElement(required=true) String vnfName,
- @WebParam(name="requestType") @XmlElement(required=false) String requestType,
- @WebParam(name="volumeGroupHeatStackId") @XmlElement(required=false) String volumeGroupHeatStackId,
- @WebParam(name="inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String,Object> inputs,
- @WebParam(name="messageId") @XmlElement(required=true) String messageId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl );
+ @WebMethod
+ @Oneway
+ public void updateVnfA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "vnfType") @XmlElement(required = true) String vnfType,
+ @WebParam(name = "vnfVersion") @XmlElement(required = false) String vnfVersion,
+ @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName,
+ @WebParam(name = "requestType") @XmlElement(required = false) String requestType,
+ @WebParam(name = "volumeGroupHeatStackId") @XmlElement(required = false) String volumeGroupHeatStackId,
+ @WebParam(name = "inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> inputs,
+ @WebParam(name = "messageId") @XmlElement(required = true) String messageId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl);
- @WebMethod
- @Oneway
- public void queryVnfA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="vnfName") @XmlElement(required=true) String vnfName,
- @WebParam(name="messageId") @XmlElement(required=true) String messageId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl );
+ @WebMethod
+ @Oneway
+ public void queryVnfA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName,
+ @WebParam(name = "messageId") @XmlElement(required = true) String messageId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl);
- @WebMethod
- @Oneway
- public void deleteVnfA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId,
- @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner,
- @WebParam(name="tenantId") @XmlElement(required=true) String tenantId,
- @WebParam(name="vnfName") @XmlElement(required=true) String vnfName,
- @WebParam(name="messageId") @XmlElement(required=true) String messageId,
- @WebParam(name="request") MsoRequest msoRequest,
- @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl );
+ @WebMethod
+ @Oneway
+ public void deleteVnfA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId,
+ @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner,
+ @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId,
+ @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName,
+ @WebParam(name = "messageId") @XmlElement(required = true) String messageId,
+ @WebParam(name = "request") MsoRequest msoRequest,
+ @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl);
- @WebMethod
- @Oneway
- public void rollbackVnfA (@WebParam(name="rollback") @XmlElement(required=true) VnfRollback rollback,
- @WebParam(name="messageId") @XmlElement(required=true) String messageId,
- @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl );
+ @WebMethod
+ @Oneway
+ public void rollbackVnfA(@WebParam(name = "rollback") @XmlElement(required = true) VnfRollback rollback,
+ @WebParam(name = "messageId") @XmlElement(required = true) String messageId,
+ @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl);
- @WebMethod
- public void healthCheckA ();
+ @WebMethod
+ public void healthCheckA();
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java
index 5e42fa5603..fe11fa07b4 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java
@@ -55,7 +55,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
-@WebService(serviceName = "VnfAdapterAsync", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapterAsync", targetNamespace = "http://org.onap.so/vnfA")
+@WebService(serviceName = "VnfAdapterAsync", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapterAsync",
+ targetNamespace = "http://org.onap.so/vnfA")
@Component
public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
@@ -74,38 +75,32 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
* Health Check web method. Does nothing but return to show the adapter is deployed.
*/
@Override
- public void healthCheckA () {
- logger.debug ("Health check call in VNF Adapter");
+ public void healthCheckA() {
+ logger.debug("Health check call in VNF Adapter");
}
/**
- * This is the asynchronous "Create VNF" web service implementation.
- * It will create a new VNF of the requested type in the specified cloud
- * and tenant. The tenant must exist before this service is called.
+ * This is the asynchronous "Create VNF" web service implementation. It will create a new VNF of the requested type
+ * in the specified cloud and tenant. The tenant must exist before this service is called.
*
- * If a VNF with the same name already exists, this can be considered a
- * success or failure, depending on the value of the 'failIfExists' parameter.
+ * If a VNF with the same name already exists, this can be considered a success or failure, depending on the value
+ * of the 'failIfExists' parameter.
*
- * All VNF types will be defined in the MSO catalog. The caller must request
- * one of these pre-defined types or an error will be returned. Within the
- * catalog, each VNF type references (among other things) a Heat template
- * which is used to deploy the required VNF artifacts (VMs, networks, etc.)
- * to the cloud.
+ * All VNF types will be defined in the MSO catalog. The caller must request one of these pre-defined types or an
+ * error will be returned. Within the catalog, each VNF type references (among other things) a Heat template which
+ * is used to deploy the required VNF artifacts (VMs, networks, etc.) to the cloud.
*
- * Depending on the Heat template, a variable set of input parameters will
- * be defined, some of which are required. The caller is responsible to
- * pass the necessary input data for the VNF or an error will be thrown.
+ * Depending on the Heat template, a variable set of input parameters will be defined, some of which are required.
+ * The caller is responsible to pass the necessary input data for the VNF or an error will be thrown.
*
- * The method sends an asynchronous response to the notification URL when
- * processing completes. The createAsyncResponse contains the vnfId (the
- * canonical name of the stack), a Map of VNF output attributes, and a
- * VnfRollback object. This last object can be passed as-is to the
- * rollbackVnf operation to undo everything that was created for the VNF.
- * This is useful if a VNF is successfully created but the orchestrator
- * fails on a subsequent operation.
+ * The method sends an asynchronous response to the notification URL when processing completes. The
+ * createAsyncResponse contains the vnfId (the canonical name of the stack), a Map of VNF output attributes, and a
+ * VnfRollback object. This last object can be passed as-is to the rollbackVnf operation to undo everything that was
+ * created for the VNF. This is useful if a VNF is successfully created but the orchestrator fails on a subsequent
+ * operation.
*
- * Note: this method is implemented by calling the synchronous web method
- * and translating the response to an asynchronous notification.
+ * Note: this method is implemented by calling the synchronous web method and translating the response to an
+ * asynchronous notification.
*
* @param cloudSiteId CLLI code of the cloud site in which to create the VNF
* @param cloudOwner cloud owner of the cloud site in which to create the VNF
@@ -113,74 +108,48 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
* @param vnfType VNF type key, should match a VNF definition in catalog DB
* @param vnfName Name to be assigned to the new VNF
* @param inputs Map of key=value inputs for VNF stack creation
- * @param failIfExists Flag whether already existing VNF should be considered
- * a success or failure
+ * @param failIfExists Flag whether already existing VNF should be considered a success or failure
* @param msoRequest Request tracking information for logs
* @param notificationURL the target URL for asynchronous response
*/
@Override
- public void createVnfA (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfType,
- String vnfVersion,
- String vnfName,
- String requestType,
- String volumeGroupHeatStackId,
- Map <String, Object> inputs,
- Boolean failIfExists,
- Boolean backout,
- Boolean enableBridge,
- String messageId,
- MsoRequest msoRequest,
- String notificationUrl) {
+ public void createVnfA(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion,
+ String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs,
+ Boolean failIfExists, Boolean backout, Boolean enableBridge, String messageId, MsoRequest msoRequest,
+ String notificationUrl) {
logger.info("{} createVnfA", MessageEnum.RA_ASYNC_CREATE_VNF);
// Use the synchronous method to perform the actual Create
MsoVnfAdapter vnfAdapter = vnfImpl;
// Synchronous Web Service Outputs
- Holder <String> vnfId = new Holder <> ();
- Holder <Map <String, String>> outputs = new Holder <> ();
- Holder <VnfRollback> vnfRollback = new Holder <> ();
+ Holder<String> vnfId = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
+ Holder<VnfRollback> vnfRollback = new Holder<>();
try {
- vnfAdapter.createVnf (cloudSiteId,
- cloudOwner,
- tenantId,
- vnfType,
- vnfVersion,
- vnfName,
- requestType,
- volumeGroupHeatStackId,
- inputs,
- failIfExists,
- backout,
- enableBridge,
- msoRequest,
- vnfId,
- outputs,
- vnfRollback);
+ vnfAdapter.createVnf(cloudSiteId, cloudOwner, tenantId, vnfType, vnfVersion, vnfName, requestType,
+ volumeGroupHeatStackId, inputs, failIfExists, backout, enableBridge, msoRequest, vnfId, outputs,
+ vnfRollback);
} catch (VnfException e) {
logger.error("{} {} VnfException in createVnfA ", MessageEnum.RA_CREATE_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
+ ErrorCode.BusinessProcesssError.getValue(), e);
org.onap.so.adapters.vnf.async.client.MsoExceptionCategory exCat = null;
String eMsg = null;
try {
- eMsg = e.getFaultInfo ().getMessage ();
- exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory.fromValue (e.getFaultInfo ()
- .getCategory ()
- .name ());
+ eMsg = e.getFaultInfo().getMessage();
+ exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory
+ .fromValue(e.getFaultInfo().getCategory().name());
} catch (Exception e1) {
logger.error("{} {} Exception - Fault info ", MessageEnum.RA_FAULT_INFO_EXC,
- ErrorCode.BusinessProcesssError.getValue(), e1);
+ ErrorCode.BusinessProcesssError.getValue(), e1);
}
// Build and send Asynchronous error response
try {
- VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.createVnfNotification (messageId, false, exCat, eMsg, null, null, null);
+ VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.createVnfNotification(messageId, false, exCat, eMsg, null, null, null);
} catch (Exception e1) {
logger.error("{} {} Exception sending createVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e1);
+ ErrorCode.BusinessProcesssError.getValue(), e1);
}
logger.info("{}", MessageEnum.RA_ASYNC_CREATE_VNF_COMPLETE);
return;
@@ -188,35 +157,21 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
logger.debug("Async Create VNF: {} VnfId:{}", vnfName, vnfId.value);
// Build and send Asynchronous response
try {
- VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.createVnfNotification (messageId,
- true,
- null,
- null,
- vnfId.value,
- copyCreateOutputs (outputs),
- copyVrb (vnfRollback));
+ VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.createVnfNotification(messageId, true, null, null, vnfId.value, copyCreateOutputs(outputs),
+ copyVrb(vnfRollback));
} catch (Exception e) {
logger.error("{} {} Exception sending createVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
+ ErrorCode.BusinessProcesssError.getValue(), e);
}
logger.info("{} createVnfA", MessageEnum.RA_ASYNC_CREATE_VNF_COMPLETE);
return;
}
@Override
- public void updateVnfA (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfType,
- String vnfVersion,
- String vnfName,
- String requestType,
- String volumeGroupHeatStackId,
- Map <String, Object> inputs,
- String messageId,
- MsoRequest msoRequest,
- String notificationUrl) {
+ public void updateVnfA(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion,
+ String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs,
+ String messageId, MsoRequest msoRequest, String notificationUrl) {
logger.info("{} UpdateVnfA", MessageEnum.RA_ASYNC_UPDATE_VNF);
@@ -224,33 +179,33 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
MsoVnfAdapter vnfAdapter = vnfImpl;
// Synchronous Web Service Outputs
- Holder <String> vnfId = new Holder <> ();
- Holder <Map <String, String>> outputs = new Holder <> ();
- Holder <VnfRollback> vnfRollback = new Holder <> ();
+ Holder<String> vnfId = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
+ Holder<VnfRollback> vnfRollback = new Holder<>();
try {
- vnfAdapter.updateVnf (cloudSiteId, cloudOwner, tenantId, vnfType,vnfVersion, vnfName, requestType, volumeGroupHeatStackId, inputs, msoRequest, outputs, vnfRollback);
+ vnfAdapter.updateVnf(cloudSiteId, cloudOwner, tenantId, vnfType, vnfVersion, vnfName, requestType,
+ volumeGroupHeatStackId, inputs, msoRequest, outputs, vnfRollback);
} catch (VnfException e) {
logger.error("{} {} Exception sending updateVnf notification ", MessageEnum.RA_UPDATE_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
+ ErrorCode.BusinessProcesssError.getValue(), e);
org.onap.so.adapters.vnf.async.client.MsoExceptionCategory exCat = null;
String eMsg = null;
try {
- eMsg = e.getFaultInfo ().getMessage ();
- exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory.fromValue (e.getFaultInfo ()
- .getCategory ()
- .name ());
+ eMsg = e.getFaultInfo().getMessage();
+ exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory
+ .fromValue(e.getFaultInfo().getCategory().name());
} catch (Exception e1) {
logger.error("{} {} Exception - fault info ", MessageEnum.RA_FAULT_INFO_EXC,
- ErrorCode.BusinessProcesssError.getValue(), e1);
+ ErrorCode.BusinessProcesssError.getValue(), e1);
}
// Build and send Asynchronous error response
try {
- VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.updateVnfNotification (messageId, false, exCat, eMsg, null, null);
+ VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.updateVnfNotification(messageId, false, exCat, eMsg, null, null);
} catch (Exception e1) {
logger.error("{} {} Exception sending updateVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e1);
+ ErrorCode.BusinessProcesssError.getValue(), e1);
}
logger.info("{} UpdateVnfA", MessageEnum.RA_ASYNC_UPDATE_VNF_COMPLETE);
return;
@@ -258,27 +213,23 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
logger.debug("Async Update VNF: {} VnfId:{}", vnfName, vnfId.value);
// Build and send Asynchronous response
try {
- VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.updateVnfNotification (messageId,
- true,
- null,
- null,
- copyUpdateOutputs (outputs),
- copyVrb (vnfRollback));
+ VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.updateVnfNotification(messageId, true, null, null, copyUpdateOutputs(outputs),
+ copyVrb(vnfRollback));
} catch (Exception e) {
logger.error("{} {} Exception sending updateVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
+ ErrorCode.BusinessProcesssError.getValue(), e);
}
logger.info("{} UpdateVnfA", MessageEnum.RA_ASYNC_UPDATE_VNF_COMPLETE);
return;
}
/**
- * This is the "Query VNF" web service implementation.
- * It will look up a VNF by name or ID in the specified cloud and tenant.
+ * This is the "Query VNF" web service implementation. It will look up a VNF by name or ID in the specified cloud
+ * and tenant.
*
- * The method returns an indicator that the VNF exists, its Openstack internal
- * ID, its status, and the set of outputs (from when the stack was created).
+ * The method returns an indicator that the VNF exists, its Openstack internal ID, its status, and the set of
+ * outputs (from when the stack was created).
*
* @param cloudSiteId CLLI code of the cloud site in which to query
* @param cloudOwner cloud owner of cloud site in which to query
@@ -288,13 +239,8 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
* @param notificationURL the target URL for asynchronous response
*/
@Override
- public void queryVnfA (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfName,
- String messageId,
- MsoRequest msoRequest,
- String notificationUrl) {
+ public void queryVnfA(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, String messageId,
+ MsoRequest msoRequest, String notificationUrl) {
String serviceName = "QueryVnfA";
logger.info("{}", MessageEnum.RA_ASYNC_QUERY_VNF);
@@ -303,59 +249,54 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
MsoVnfAdapter vnfAdapter = vnfImpl;
// Synchronous Web Service Outputs
- Holder <Boolean> vnfExists = new Holder <> ();
- Holder <String> vnfId = new Holder <> ();
- Holder <VnfStatus> status = new Holder <> ();
- Holder <Map <String, String>> outputs = new Holder <> ();
+ Holder<Boolean> vnfExists = new Holder<>();
+ Holder<String> vnfId = new Holder<>();
+ Holder<VnfStatus> status = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
try {
- vnfAdapter.queryVnf (cloudSiteId, cloudOwner, tenantId, vnfName, msoRequest, vnfExists, vnfId, status, outputs);
+ vnfAdapter.queryVnf(cloudSiteId, cloudOwner, tenantId, vnfName, msoRequest, vnfExists, vnfId, status,
+ outputs);
} catch (VnfException e) {
logger.error("{} {} Exception sending queryVnfA notification ", MessageEnum.RA_QUERY_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
+ ErrorCode.BusinessProcesssError.getValue(), e);
org.onap.so.adapters.vnf.async.client.MsoExceptionCategory exCat = null;
String eMsg = null;
try {
- eMsg = e.getFaultInfo ().getMessage ();
- exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory.fromValue (e.getFaultInfo ()
- .getCategory ()
- .name ());
+ eMsg = e.getFaultInfo().getMessage();
+ exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory
+ .fromValue(e.getFaultInfo().getCategory().name());
} catch (Exception e1) {
logger.error("{} {} Exception - fault info ", MessageEnum.RA_FAULT_INFO_EXC,
- ErrorCode.BusinessProcesssError.getValue(), e1);
+ ErrorCode.BusinessProcesssError.getValue(), e1);
}
// Build and send Asynchronous error response
try {
- VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.queryVnfNotification (messageId, false, exCat, eMsg, null, null, null, null);
+ VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.queryVnfNotification(messageId, false, exCat, eMsg, null, null, null, null);
} catch (Exception e1) {
logger.error("{} {} Exception sending queryVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e1);
+ ErrorCode.BusinessProcesssError.getValue(), e1);
}
logger.info("{} queryVnfA", MessageEnum.RA_ASYNC_QUERY_VNF_COMPLETE);
return;
}
if (!vnfExists.value) {
- logger.debug ("Async Query, VNF not found");
+ logger.debug("Async Query, VNF not found");
} else {
logger.debug("Async Query, VNF={}, status={}", vnfId.value, status.value);
}
// Build and send Asynchronous response
try {
- VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- org.onap.so.adapters.vnf.async.client.VnfStatus vnfS = org.onap.so.adapters.vnf.async.client.VnfStatus.fromValue (status.value.name ());
- notifyPort.queryVnfNotification (messageId,
- true,
- null,
- null,
- vnfExists.value,
- vnfId.value,
- vnfS,
- copyQueryOutputs (outputs));
+ VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ org.onap.so.adapters.vnf.async.client.VnfStatus vnfS =
+ org.onap.so.adapters.vnf.async.client.VnfStatus.fromValue(status.value.name());
+ notifyPort.queryVnfNotification(messageId, true, null, null, vnfExists.value, vnfId.value, vnfS,
+ copyQueryOutputs(outputs));
} catch (Exception e) {
logger.error("{} {} Exception sending queryVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
+ ErrorCode.BusinessProcesssError.getValue(), e);
}
logger.info("{} queryVnfA", MessageEnum.RA_ASYNC_QUERY_VNF_COMPLETE);
@@ -363,8 +304,8 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
}
/**
- * This is the Asynchronous "Delete VNF" web service implementation.
- * It will delete a VNF by name or ID in the specified cloud and tenant.
+ * This is the Asynchronous "Delete VNF" web service implementation. It will delete a VNF by name or ID in the
+ * specified cloud and tenant.
*
* The method has no outputs.
*
@@ -376,13 +317,8 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
* @param notificationURL the target URL for asynchronous response
*/
@Override
- public void deleteVnfA (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfName,
- String messageId,
- MsoRequest msoRequest,
- String notificationUrl) {
+ public void deleteVnfA(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, String messageId,
+ MsoRequest msoRequest, String notificationUrl) {
String serviceName = "DeleteVnfA";
logger.info("{}", MessageEnum.RA_ASYNC_DELETE_VNF);
@@ -391,28 +327,27 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
MsoVnfAdapter vnfAdapter = vnfImpl;
try {
- vnfAdapter.deleteVnf (cloudSiteId, cloudOwner, tenantId, vnfName, msoRequest);
+ vnfAdapter.deleteVnf(cloudSiteId, cloudOwner, tenantId, vnfName, msoRequest);
} catch (VnfException e) {
logger.error("{} {} Exception sending deleteVnfA notification ", MessageEnum.RA_DELETE_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
+ ErrorCode.BusinessProcesssError.getValue(), e);
org.onap.so.adapters.vnf.async.client.MsoExceptionCategory exCat = null;
String eMsg = null;
try {
- eMsg = e.getFaultInfo ().getMessage ();
- exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory.fromValue (e.getFaultInfo ()
- .getCategory ()
- .name ());
+ eMsg = e.getFaultInfo().getMessage();
+ exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory
+ .fromValue(e.getFaultInfo().getCategory().name());
} catch (Exception e1) {
logger.error("{} {} Exception - fault info ", MessageEnum.RA_FAULT_INFO_EXC,
- ErrorCode.BusinessProcesssError.getValue(), e1);
+ ErrorCode.BusinessProcesssError.getValue(), e1);
}
// Build and send Asynchronous error response
try {
- VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.deleteVnfNotification (messageId, false, exCat, eMsg);
+ VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.deleteVnfNotification(messageId, false, exCat, eMsg);
} catch (Exception e1) {
logger.error("{} {} Exception sending deleteVnfA notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e1);
+ ErrorCode.BusinessProcesssError.getValue(), e1);
}
logger.info("{} deleteVnfA", MessageEnum.RA_ASYNC_DELETE_VNF_COMPLETE);
return;
@@ -421,12 +356,12 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
logger.debug("Async Delete VNF: {}", vnfName);
// Build and send Asynchronous response
try {
- VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.deleteVnfNotification (messageId, true, null, null);
+ VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.deleteVnfNotification(messageId, true, null, null);
} catch (Exception e) {
logger.error("{} {} Exception sending deleteVnfA notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
+ ErrorCode.BusinessProcesssError.getValue(), e);
}
logger.info("{} deleteVnfA", MessageEnum.RA_ASYNC_DELETE_VNF_COMPLETE);
@@ -434,13 +369,12 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
}
/**
- * This web service endpoint will rollback a previous Create VNF operation.
- * A rollback object is returned to the client in a successful creation
- * response. The client can pass that object as-is back to the rollbackVnf
- * operation to undo the creation.
+ * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the
+ * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation
+ * to undo the creation.
*/
@Override
- public void rollbackVnfA (VnfRollback rollback, String messageId, String notificationUrl) {
+ public void rollbackVnfA(VnfRollback rollback, String messageId, String notificationUrl) {
// rollback may be null (e.g. if stack already existed when Create was called)
if (rollback == null) {
logger.info("{} rollbackVnfA: Empty Rollback: No action to perform", MessageEnum.RA_ROLLBACK_NULL);
@@ -453,200 +387,199 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync {
MsoVnfAdapter vnfAdapter = vnfImpl;
try {
- vnfAdapter.rollbackVnf (rollback);
+ vnfAdapter.rollbackVnf(rollback);
} catch (VnfException e) {
logger.error("{} {} Exception sending rollbackVnfA notification ", MessageEnum.RA_ROLLBACK_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
+ ErrorCode.BusinessProcesssError.getValue(), e);
org.onap.so.adapters.vnf.async.client.MsoExceptionCategory exCat = null;
String eMsg = null;
try {
- eMsg = e.getFaultInfo ().getMessage ();
- exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory.fromValue (e.getFaultInfo ()
- .getCategory ()
- .name ());
+ eMsg = e.getFaultInfo().getMessage();
+ exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory
+ .fromValue(e.getFaultInfo().getCategory().name());
} catch (Exception e1) {
logger.error("{} {} Exception - fault info ", MessageEnum.RA_FAULT_INFO_EXC,
- ErrorCode.BusinessProcesssError.getValue(), e1);
+ ErrorCode.BusinessProcesssError.getValue(), e1);
}
// Build and send Asynchronous error response
try {
- VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.rollbackVnfNotification (messageId, false, exCat, eMsg);
+ VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.rollbackVnfNotification(messageId, false, exCat, eMsg);
} catch (Exception e1) {
logger.error("{} {} Exception sending rollbackVnfA notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e1);
+ ErrorCode.BusinessProcesssError.getValue(), e1);
}
logger.info("{} rollbackVnfA", MessageEnum.RA_ASYNC_ROLLBACK_VNF_COMPLETE);
return;
}
- logger.debug ("Async Rollback VNF:" + rollback.getVnfId ());
+ logger.debug("Async Rollback VNF:" + rollback.getVnfId());
// Build and send Asynchronous response
try {
- VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl);
- notifyPort.rollbackVnfNotification (messageId, true, null, null);
+ VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl);
+ notifyPort.rollbackVnfNotification(messageId, true, null, null);
} catch (Exception e) {
logger.error("{} {} Exception sending rollbackVnfA notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
+ ErrorCode.BusinessProcesssError.getValue(), e);
}
logger.info("{} rollbackVnfA", MessageEnum.RA_ASYNC_ROLLBACK_VNF_COMPLETE);
return;
}
- private org.onap.so.adapters.vnf.async.client.VnfRollback copyVrb (Holder <VnfRollback> hVrb) {
- org.onap.so.adapters.vnf.async.client.VnfRollback cvrb = new org.onap.so.adapters.vnf.async.client.VnfRollback ();
+ private org.onap.so.adapters.vnf.async.client.VnfRollback copyVrb(Holder<VnfRollback> hVrb) {
+ org.onap.so.adapters.vnf.async.client.VnfRollback cvrb =
+ new org.onap.so.adapters.vnf.async.client.VnfRollback();
if (hVrb != null && hVrb.value != null) {
- org.onap.so.adapters.vnf.async.client.MsoRequest cmr = new org.onap.so.adapters.vnf.async.client.MsoRequest ();
+ org.onap.so.adapters.vnf.async.client.MsoRequest cmr =
+ new org.onap.so.adapters.vnf.async.client.MsoRequest();
- cvrb.setCloudSiteId (hVrb.value.getCloudSiteId ());
+ cvrb.setCloudSiteId(hVrb.value.getCloudSiteId());
if (hVrb.value.getMsoRequest() != null) {
- cmr.setRequestId (hVrb.value.getMsoRequest ().getRequestId ());
- cmr.setServiceInstanceId (hVrb.value.getMsoRequest ().getServiceInstanceId ());
+ cmr.setRequestId(hVrb.value.getMsoRequest().getRequestId());
+ cmr.setServiceInstanceId(hVrb.value.getMsoRequest().getServiceInstanceId());
} else {
- cmr.setRequestId (null);
- cmr.setServiceInstanceId (null);
+ cmr.setRequestId(null);
+ cmr.setServiceInstanceId(null);
}
- cvrb.setMsoRequest (cmr);
- cvrb.setVnfId (hVrb.value.getVnfId ());
- cvrb.setTenantId (hVrb.value.getTenantId ());
- cvrb.setTenantCreated (hVrb.value.getTenantCreated ());
- cvrb.setVnfCreated (hVrb.value.getVnfCreated ());
+ cvrb.setMsoRequest(cmr);
+ cvrb.setVnfId(hVrb.value.getVnfId());
+ cvrb.setTenantId(hVrb.value.getTenantId());
+ cvrb.setTenantCreated(hVrb.value.getTenantCreated());
+ cvrb.setVnfCreated(hVrb.value.getVnfCreated());
}
return cvrb;
}
- private CreateVnfNotification.Outputs copyCreateOutputs (Holder <Map <String, String>> hMap) {
+ private CreateVnfNotification.Outputs copyCreateOutputs(Holder<Map<String, String>> hMap) {
- CreateVnfNotification.Outputs outputs = new CreateVnfNotification.Outputs ();
+ CreateVnfNotification.Outputs outputs = new CreateVnfNotification.Outputs();
if (hMap != null && hMap.value != null) {
- Map <String, String> sMap = new HashMap <> ();
+ Map<String, String> sMap = new HashMap<>();
sMap = hMap.value;
- CreateVnfNotification.Outputs.Entry entry = new CreateVnfNotification.Outputs.Entry ();
+ CreateVnfNotification.Outputs.Entry entry = new CreateVnfNotification.Outputs.Entry();
- for (String key : sMap.keySet ()) {
- entry.setKey (key);
- entry.setValue (sMap.get (key));
- outputs.getEntry ().add (entry);
+ for (String key : sMap.keySet()) {
+ entry.setKey(key);
+ entry.setValue(sMap.get(key));
+ outputs.getEntry().add(entry);
}
}
return outputs;
}
- private UpdateVnfNotification.Outputs copyUpdateOutputs (Holder <Map <String, String>> hMap) {
+ private UpdateVnfNotification.Outputs copyUpdateOutputs(Holder<Map<String, String>> hMap) {
- UpdateVnfNotification.Outputs outputs = new UpdateVnfNotification.Outputs ();
+ UpdateVnfNotification.Outputs outputs = new UpdateVnfNotification.Outputs();
if (hMap != null && hMap.value != null) {
- Map <String, String> sMap = new HashMap <> ();
+ Map<String, String> sMap = new HashMap<>();
sMap = hMap.value;
- UpdateVnfNotification.Outputs.Entry entry = new UpdateVnfNotification.Outputs.Entry ();
-
- for (Map.Entry<String,String> mapEntry : sMap.entrySet ()) {
- String key = mapEntry.getKey();
- String value = mapEntry.getValue();
- entry.setKey (key);
- entry.setValue (value);
- outputs.getEntry ().add (entry);
+ UpdateVnfNotification.Outputs.Entry entry = new UpdateVnfNotification.Outputs.Entry();
+
+ for (Map.Entry<String, String> mapEntry : sMap.entrySet()) {
+ String key = mapEntry.getKey();
+ String value = mapEntry.getValue();
+ entry.setKey(key);
+ entry.setValue(value);
+ outputs.getEntry().add(entry);
}
}
return outputs;
}
- private QueryVnfNotification.Outputs copyQueryOutputs (Holder <Map <String, String>> hMap) {
+ private QueryVnfNotification.Outputs copyQueryOutputs(Holder<Map<String, String>> hMap) {
- QueryVnfNotification.Outputs outputs = new QueryVnfNotification.Outputs ();
+ QueryVnfNotification.Outputs outputs = new QueryVnfNotification.Outputs();
if (hMap != null && hMap.value != null) {
- Map <String, String> sMap = new HashMap <> ();
+ Map<String, String> sMap = new HashMap<>();
sMap = hMap.value;
- QueryVnfNotification.Outputs.Entry entry = new QueryVnfNotification.Outputs.Entry ();
+ QueryVnfNotification.Outputs.Entry entry = new QueryVnfNotification.Outputs.Entry();
- for (Map.Entry<String,String> mapEntry : sMap.entrySet ()) {
- String key = mapEntry.getKey();
- String value = mapEntry.getValue();
- entry.setKey (key);
- entry.setValue (value);
- outputs.getEntry ().add (entry);
+ for (Map.Entry<String, String> mapEntry : sMap.entrySet()) {
+ String key = mapEntry.getKey();
+ String value = mapEntry.getValue();
+ entry.setKey(key);
+ entry.setValue(value);
+ outputs.getEntry().add(entry);
}
}
return outputs;
}
- private VnfAdapterNotify getNotifyEP (String notificationUrl) {
+ private VnfAdapterNotify getNotifyEP(String notificationUrl) {
URL warWsdlLoc = null;
try {
- warWsdlLoc = Thread.currentThread ().getContextClassLoader ().getResource ("VnfAdapterNotify.wsdl");
+ warWsdlLoc = Thread.currentThread().getContextClassLoader().getResource("VnfAdapterNotify.wsdl");
} catch (Exception e) {
logger.error("{} {} Exception - WSDL not found ", MessageEnum.RA_WSDL_NOT_FOUND,
- ErrorCode.BusinessProcesssError.getValue(), e);
+ ErrorCode.BusinessProcesssError.getValue(), e);
}
if (warWsdlLoc == null) {
logger.error("{} {} WSDL not found", MessageEnum.RA_WSDL_NOT_FOUND,
- ErrorCode.BusinessProcesssError.getValue());
+ ErrorCode.BusinessProcesssError.getValue());
} else {
try {
logger.debug("VnfAdpaterNotify.wsdl location:{}", warWsdlLoc.toURI().toString());
} catch (Exception e) {
logger.error("{} {} Exception - WSDL URL convention ", MessageEnum.RA_WSDL_URL_CONVENTION_EXC,
- ErrorCode.BusinessProcesssError.getValue(), e);
+ ErrorCode.BusinessProcesssError.getValue(), e);
}
}
- VnfAdapterNotify_Service notifySvc = new VnfAdapterNotify_Service (warWsdlLoc,
- new QName ("http://org.onap.so/vnfNotify",
- "vnfAdapterNotify"));
+ VnfAdapterNotify_Service notifySvc =
+ new VnfAdapterNotify_Service(warWsdlLoc, new QName("http://org.onap.so/vnfNotify", "vnfAdapterNotify"));
- VnfAdapterNotify notifyPort = notifySvc.getMsoVnfAdapterAsyncImplPort ();
+ VnfAdapterNotify notifyPort = notifySvc.getMsoVnfAdapterAsyncImplPort();
BindingProvider bp = (BindingProvider) notifyPort;
URL epUrl = null;
try {
- epUrl = new URL (notificationUrl);
+ epUrl = new URL(notificationUrl);
} catch (MalformedURLException e1) {
logger.error("{} {} MalformedURLException ", MessageEnum.RA_INIT_NOTIF_EXC,
- ErrorCode.BusinessProcesssError.getValue(), e1);
+ ErrorCode.BusinessProcesssError.getValue(), e1);
}
- if(null != epUrl) {
+ if (null != epUrl) {
logger.debug("Notification Endpoint URL: {}", epUrl.toExternalForm());
- bp.getRequestContext ().put (BindingProvider.ENDPOINT_ADDRESS_PROPERTY, epUrl.toExternalForm ());
- }
- else {
- logger.debug ("epUrl is NULL:");
+ bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, epUrl.toExternalForm());
+ } else {
+ logger.debug("epUrl is NULL:");
}
// authentication
try {
- Map <String, Object> reqCtx = bp.getRequestContext ();
- Map <String, List <String>> headers = new HashMap <> ();
+ Map<String, Object> reqCtx = bp.getRequestContext();
+ Map<String, List<String>> headers = new HashMap<>();
String userCredentials = this.getEncryptedProperty(BPEL_AUTH_PROP, "", ENCRYPTION_KEY_PROP);
- String basicAuth = "Basic " + DatatypeConverter.printBase64Binary (userCredentials.getBytes ());
- reqCtx.put (MessageContext.HTTP_REQUEST_HEADERS, headers);
- headers.put ("Authorization", Collections.singletonList (basicAuth));
+ String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
+ reqCtx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
+ headers.put("Authorization", Collections.singletonList(basicAuth));
} catch (Exception e) {
logger.error("{} {} Exception - Unable to set authorization in callback request ",
- MessageEnum.RA_SET_CALLBACK_AUTH_EXC, ErrorCode.BusinessProcesssError.getValue(), e);
+ MessageEnum.RA_SET_CALLBACK_AUTH_EXC, ErrorCode.BusinessProcesssError.getValue(), e);
}
return notifyPort;
}
public String getEncryptedProperty(String key, String defaultValue, String encryptionKey) {
- try {
- return CryptoUtils.decrypt(this.environment.getProperty(key), this.environment.getProperty(encryptionKey));
- } catch (GeneralSecurityException e) {
- logger.debug("Exception while decrypting property: {} ", this.environment.getProperty(key), e);
- }
- return defaultValue;
-
- }
+ try {
+ return CryptoUtils.decrypt(this.environment.getProperty(key), this.environment.getProperty(encryptionKey));
+ } catch (GeneralSecurityException e) {
+ logger.debug("Exception while decrypting property: {} ", this.environment.getProperty(key), e);
+ }
+ return defaultValue;
+
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java
index 6e9656a213..5c7e70673b 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java
@@ -33,10 +33,8 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
-
import javax.jws.WebService;
import javax.xml.ws.Holder;
-
import org.apache.commons.collections.CollectionUtils;
import org.onap.so.adapters.valet.GenericValetResponse;
import org.onap.so.adapters.valet.ValetClient;
@@ -70,7 +68,6 @@ import org.onap.so.heatbridge.HeatBridgeApi;
import org.onap.so.heatbridge.HeatBridgeImpl;
import org.onap.so.heatbridge.openstack.api.OpenstackClient;
import org.onap.so.logger.MessageEnum;
-
import org.onap.so.openstack.beans.HeatStatus;
import org.onap.so.openstack.beans.StackInfo;
import org.onap.so.openstack.beans.VnfRollback;
@@ -92,21 +89,21 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-@WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter", targetNamespace = "http://org.onap.so/vnf")
+@WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter",
+ targetNamespace = "http://org.onap.so/vnf")
@Component
@Transactional
public class MsoVnfAdapterImpl implements MsoVnfAdapter {
- @Autowired
- private CloudConfig cloudConfig;
+ @Autowired
+ private CloudConfig cloudConfig;
- @Autowired
- private Environment environment;
+ @Autowired
+ private Environment environment;
private static final Logger logger = LoggerFactory.getLogger(MsoVnfAdapterImpl.class);
@@ -116,8 +113,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
private static final String ADD_GET_FILES_ON_VOLUME_REQ = "org.onap.so.adapters.vnf.addGetFilesOnVolumeReq";
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
private static final String VALET_ENABLED = "org.onap.so.adapters.vnf.valet_enabled";
- private static final String FAIL_REQUESTS_ON_VALET_FAILURE = "org.onap.so.adapters.vnf.fail_requests_on_valet_failure";
- private static final String SUCCESS_MSG = "Successfully received response from Open Stack";
+ private static final String FAIL_REQUESTS_ON_VALET_FAILURE =
+ "org.onap.so.adapters.vnf.fail_requests_on_valet_failure";
+ private static final String SUCCESS_MSG = "Successfully received response from Open Stack";
@Autowired
private VFModuleCustomizationRepository vfModuleCustomRepo;
@@ -135,44 +133,39 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
/**
* DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL.
+ *
* @see MsoVnfAdapterImpl#MsoVnfAdapterImpl(MsoPropertiesFactory, CloudConfigFactory)
*/
public MsoVnfAdapterImpl() {
- // Do nothing
- //DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL.
- }
+ // Do nothing
+ // DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL.
+ }
- /**
+ /**
* Health Check web method. Does nothing but return to show the adapter is deployed.
*/
@Override
- public void healthCheck () {
- logger.debug ("Health check call in VNF Adapter");
+ public void healthCheck() {
+ logger.debug("Health check call in VNF Adapter");
}
/**
- * This is the "Create VNF" web service implementation.
- * It will create a new VNF of the requested type in the specified cloud
- * and tenant. The tenant must exist before this service is called.
+ * This is the "Create VNF" web service implementation. It will create a new VNF of the requested type in the
+ * specified cloud and tenant. The tenant must exist before this service is called.
*
- * If a VNF with the same name already exists, this can be considered a
- * success or failure, depending on the value of the 'failIfExists' parameter.
+ * If a VNF with the same name already exists, this can be considered a success or failure, depending on the value
+ * of the 'failIfExists' parameter.
*
- * All VNF types will be defined in the MSO catalog. The caller must request
- * one of these pre-defined types or an error will be returned. Within the
- * catalog, each VNF type references (among other things) a Heat template
- * which is used to deploy the required VNF artifacts (VMs, networks, etc.)
- * to the cloud.
+ * All VNF types will be defined in the MSO catalog. The caller must request one of these pre-defined types or an
+ * error will be returned. Within the catalog, each VNF type references (among other things) a Heat template which
+ * is used to deploy the required VNF artifacts (VMs, networks, etc.) to the cloud.
*
- * Depending on the Heat template, a variable set of input parameters will
- * be defined, some of which are required. The caller is responsible to
- * pass the necessary input data for the VNF or an error will be thrown.
+ * Depending on the Heat template, a variable set of input parameters will be defined, some of which are required.
+ * The caller is responsible to pass the necessary input data for the VNF or an error will be thrown.
*
- * The method returns the vnfId (the canonical name), a Map of VNF output
- * attributes, and a VnfRollback object. This last object can be passed
- * as-is to the rollbackVnf operation to undo everything that was created
- * for the VNF. This is useful if a VNF is successfully created but the
- * orchestrator fails on a subsequent operation.
+ * The method returns the vnfId (the canonical name), a Map of VNF output attributes, and a VnfRollback object. This
+ * last object can be passed as-is to the rollbackVnf operation to undo everything that was created for the VNF.
+ * This is useful if a VNF is successfully created but the orchestrator fails on a subsequent operation.
*
* @param cloudSiteId CLLI code of the cloud site in which to create the VNF
* @param cloudOwner cloud owner of the cloud region in which to create the VNF
@@ -181,124 +174,70 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
* @param vnfVersion VNF version key, should match a VNF definition in catalog DB
* @param vnfName Name to be assigned to the new VNF
* @param inputs Map of key=value inputs for VNF stack creation
- * @param failIfExists Flag whether already existing VNF should be considered
- * a success or failure
+ * @param failIfExists Flag whether already existing VNF should be considered a success or failure
* @param msoRequest Request tracking information for logs
* @param vnfId Holder for output VNF Openstack ID
* @param outputs Holder for Map of VNF outputs from heat (assigned IPs, etc)
* @param rollback Holder for returning VnfRollback object
*/
@Override
- public void createVnf (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfType,
- String vnfVersion,
- String vnfName,
- String requestType,
- String volumeGroupHeatStackId,
- Map <String, Object> inputs,
- Boolean failIfExists,
- Boolean backout,
- Boolean enableBridge,
- MsoRequest msoRequest,
- Holder <String> vnfId,
- Holder <Map <String, String>> outputs,
- Holder <VnfRollback> rollback) throws VnfException {
+ public void createVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion,
+ String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs,
+ Boolean failIfExists, Boolean backout, Boolean enableBridge, MsoRequest msoRequest, Holder<String> vnfId,
+ Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) throws VnfException {
// parameters used for multicloud adapter
String genericVnfId = "";
String vfModuleId = "";
- // Create a hook here to catch shortcut createVf requests:
- if (requestType != null && requestType.startsWith("VFMOD")) {
- logger.debug("Calling createVfModule from createVnf -- requestType=" + requestType);
- String newRequestType = requestType.substring(5);
- String vfVolGroupHeatStackId = "";
- String vfBaseHeatStackId = "";
- try {
- if (volumeGroupHeatStackId != null) {
- vfVolGroupHeatStackId = volumeGroupHeatStackId.substring(0, volumeGroupHeatStackId.lastIndexOf('|'));
- vfBaseHeatStackId = volumeGroupHeatStackId.substring(volumeGroupHeatStackId.lastIndexOf('|')+1);
- }
- } catch (Exception e) {
- // might be ok - both are just blank
- logger.debug("ERROR trying to parse the volumeGroupHeatStackId {}", volumeGroupHeatStackId,e);
- }
- this.createVfModule(cloudSiteId,
- cloudOwner,
- tenantId,
- vnfType,
- vnfVersion,
- genericVnfId,
- vnfName,
- vfModuleId,
- newRequestType,
- vfVolGroupHeatStackId,
- vfBaseHeatStackId,
- null,
- inputs,
- failIfExists,
- backout,
- enableBridge,
- msoRequest,
- vnfId,
- outputs,
- rollback);
- return;
- }
- // createVf will know if the requestType starts with "X" that it's the "old" way
- StringBuilder newRequestTypeSb = new StringBuilder("X");
- String vfVolGroupHeatStackId = "";
- String vfBaseHeatStackId = "";
- if (requestType != null) {
- newRequestTypeSb.append(requestType);
- }
- this.createVfModule(cloudSiteId,
- cloudOwner,
- tenantId,
- vnfType,
- vnfVersion,
- genericVnfId,
- vnfName,
- vfModuleId,
- newRequestTypeSb.toString(),
- vfVolGroupHeatStackId,
- vfBaseHeatStackId,
- null,
- inputs,
- failIfExists,
- backout,
- enableBridge,
- msoRequest,
- vnfId,
- outputs,
- rollback);
- return;
- // End createVf shortcut
+ // Create a hook here to catch shortcut createVf requests:
+ if (requestType != null && requestType.startsWith("VFMOD")) {
+ logger.debug("Calling createVfModule from createVnf -- requestType=" + requestType);
+ String newRequestType = requestType.substring(5);
+ String vfVolGroupHeatStackId = "";
+ String vfBaseHeatStackId = "";
+ try {
+ if (volumeGroupHeatStackId != null) {
+ vfVolGroupHeatStackId =
+ volumeGroupHeatStackId.substring(0, volumeGroupHeatStackId.lastIndexOf('|'));
+ vfBaseHeatStackId = volumeGroupHeatStackId.substring(volumeGroupHeatStackId.lastIndexOf('|') + 1);
+ }
+ } catch (Exception e) {
+ // might be ok - both are just blank
+ logger.debug("ERROR trying to parse the volumeGroupHeatStackId {}", volumeGroupHeatStackId, e);
+ }
+ this.createVfModule(cloudSiteId, cloudOwner, tenantId, vnfType, vnfVersion, genericVnfId, vnfName,
+ vfModuleId, newRequestType, vfVolGroupHeatStackId, vfBaseHeatStackId, null, inputs, failIfExists,
+ backout, enableBridge, msoRequest, vnfId, outputs, rollback);
+ return;
}
+ // createVf will know if the requestType starts with "X" that it's the "old" way
+ StringBuilder newRequestTypeSb = new StringBuilder("X");
+ String vfVolGroupHeatStackId = "";
+ String vfBaseHeatStackId = "";
+ if (requestType != null) {
+ newRequestTypeSb.append(requestType);
+ }
+ this.createVfModule(cloudSiteId, cloudOwner, tenantId, vnfType, vnfVersion, genericVnfId, vnfName, vfModuleId,
+ newRequestTypeSb.toString(), vfVolGroupHeatStackId, vfBaseHeatStackId, null, inputs, failIfExists,
+ backout, enableBridge, msoRequest, vnfId, outputs, rollback);
+ return;
+ // End createVf shortcut
+ }
@Override
- public void updateVnf(String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfType,
- String vnfVersion,
- String vnfName,
- String requestType,
- String volumeGroupHeatStackId,
- Map <String, Object> inputs,
- MsoRequest msoRequest,
- Holder <Map <String, String>> outputs,
- Holder <VnfRollback> rollback) throws VnfException {
- // As of 1707 - this method should no longer be called
- logger.debug("UpdateVnf called?? This should not be called any longer - update vfModule");
+ public void updateVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion,
+ String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs,
+ MsoRequest msoRequest, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback)
+ throws VnfException {
+ // As of 1707 - this method should no longer be called
+ logger.debug("UpdateVnf called?? This should not be called any longer - update vfModule");
}
/**
- * This is the "Query VNF" web service implementation.
- * It will look up a VNF by name or ID in the specified cloud and tenant.
+ * This is the "Query VNF" web service implementation. It will look up a VNF by name or ID in the specified cloud
+ * and tenant.
*
- * The method returns an indicator that the VNF exists, its Openstack internal
- * ID, its status, and the set of outputs (from when the stack was created).
+ * The method returns an indicator that the VNF exists, its Openstack internal ID, its status, and the set of
+ * outputs (from when the stack was created).
*
* @param cloudSiteId CLLI code of the cloud site in which to query
* @param tenantId Openstack tenant identifier
@@ -309,61 +248,55 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
* @param outputs Holder for Map of VNF outputs from heat (assigned IPs, etc)
*/
@Override
- public void queryVnf (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfName,
- MsoRequest msoRequest,
- Holder <Boolean> vnfExists,
- Holder <String> vnfId,
- Holder <VnfStatus> status,
- Holder <Map <String, String>> outputs) throws VnfException {
+ public void queryVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest,
+ Holder<Boolean> vnfExists, Holder<String> vnfId, Holder<VnfStatus> status,
+ Holder<Map<String, String>> outputs) throws VnfException {
logger.debug("Querying VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
StackInfo heatStack = null;
- long subStartTime = System.currentTimeMillis ();
+ long subStartTime = System.currentTimeMillis();
try {
- heatStack = heat.queryStack (cloudSiteId, cloudOwner, tenantId, vnfName);
+ heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vnfName);
} catch (MsoException me) {
- me.addContext ("QueryVNF");
+ me.addContext("QueryVNF");
// Failed to query the Stack due to an openstack exception.
// Convert to a generic VnfException
- String error = "Query VNF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
+ String error =
+ "Query VNF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudSiteId,
- tenantId, "OpenStack", "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryStack",
- me);
+ tenantId, "OpenStack", "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryStack", me);
logger.debug(error);
- throw new VnfException (me);
+ throw new VnfException(me);
}
// Populate the outputs based on the returned Stack information
//
- if (heatStack == null || heatStack.getStatus () == HeatStatus.NOTFOUND) {
+ if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
// Not Found
vnfExists.value = Boolean.FALSE;
status.value = VnfStatus.NOTFOUND;
vnfId.value = null;
outputs.value = new HashMap<>(); // Return as an empty map
- logger.debug ("VNF {} not found", vnfName);
+ logger.debug("VNF {} not found", vnfName);
} else {
vnfExists.value = Boolean.TRUE;
- status.value = stackStatusToVnfStatus (heatStack.getStatus ());
- vnfId.value = heatStack.getCanonicalName ();
- outputs.value = copyStringOutputs (heatStack.getOutputs ());
+ status.value = stackStatusToVnfStatus(heatStack.getStatus());
+ vnfId.value = heatStack.getCanonicalName();
+ outputs.value = copyStringOutputs(heatStack.getOutputs());
- logger.debug ("VNF {} found, ID = {}", vnfName, vnfId.value);
+ logger.debug("VNF {} found, ID = {}", vnfName, vnfId.value);
}
return;
}
/**
- * This is the "Delete VNF" web service implementation.
- * It will delete a VNF by name or ID in the specified cloud and tenant.
+ * This is the "Delete VNF" web service implementation. It will delete a VNF by name or ID in the specified cloud
+ * and tenant.
*
* The method has no outputs.
*
@@ -374,33 +307,31 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
* @param msoRequest Request tracking information for logs
*/
@Override
- public void deleteVnf (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfName,
- MsoRequest msoRequest) throws VnfException {
+ public void deleteVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest)
+ throws VnfException {
logger.debug("Deleting VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
// Use the MsoHeatUtils to delete the stack. Set the polling flag to true.
// The possible outcomes of deleteStack are a StackInfo object with status
// of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException
// could be thrown.
- long subStartTime = System.currentTimeMillis ();
+ long subStartTime = System.currentTimeMillis();
try {
- heat.deleteStack (tenantId, cloudOwner, cloudSiteId, vnfName, true);
+ heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true);
} catch (MsoException me) {
- me.addContext ("DeleteVNF");
+ me.addContext("DeleteVNF");
// Failed to query the Stack due to an openstack exception.
// Convert to a generic VnfException
- String error = "Delete VNF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", "DeleteVNF", ErrorCode.DataError.getValue(), "Exception - DeleteVNF",
- me);
+ String error =
+ "Delete VNF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner,
+ cloudSiteId, tenantId, "OpenStack", "DeleteVNF", ErrorCode.DataError.getValue(),
+ "Exception - DeleteVNF", me);
logger.debug(error);
- throw new VnfException (me);
+ throw new VnfException(me);
}
// On success, nothing is returned.
@@ -408,25 +339,24 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
}
/**
- * This web service endpoint will rollback a previous Create VNF operation.
- * A rollback object is returned to the client in a successful creation
- * response. The client can pass that object as-is back to the rollbackVnf
- * operation to undo the creation.
+ * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the
+ * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation
+ * to undo the creation.
*/
@Override
- public void rollbackVnf (VnfRollback rollback) throws VnfException {
- long startTime = System.currentTimeMillis ();
- // rollback may be null (e.g. if stack already existed when Create was called)
+ public void rollbackVnf(VnfRollback rollback) throws VnfException {
+ long startTime = System.currentTimeMillis();
+ // rollback may be null (e.g. if stack already existed when Create was called)
if (rollback == null) {
logger.info(MessageEnum.RA_ROLLBACK_NULL.toString(), "OpenStack", "rollbackVnf");
return;
}
// Get the elements of the VnfRollback object for easier access
- String cloudSiteId = rollback.getCloudSiteId ();
- String cloudOwner = rollback.getCloudOwner ();
- String tenantId = rollback.getTenantId ();
- String vnfId = rollback.getVnfId ();
+ String cloudSiteId = rollback.getCloudSiteId();
+ String cloudOwner = rollback.getCloudOwner();
+ String tenantId = rollback.getTenantId();
+ String vnfId = rollback.getVnfId();
logger.debug("Rolling Back VNF {} in {}", vnfId, cloudOwner + "/" + cloudSiteId + "/" + tenantId);
@@ -435,22 +365,23 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
// of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException
// could be thrown.
try {
- heat.deleteStack (tenantId, cloudOwner, cloudSiteId, vnfId, true);
+ heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfId, true);
} catch (MsoException me) {
// Failed to rollback the Stack due to an openstack exception.
// Convert to a generic VnfException
- me.addContext ("RollbackVNF");
- String error = "Rollback VNF: " + vnfId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfId, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", "DeleteStack", ErrorCode.DataError.getValue(),
- "Exception - DeleteStack", me);
+ me.addContext("RollbackVNF");
+ String error =
+ "Rollback VNF: " + vnfId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfId, cloudOwner,
+ cloudSiteId, tenantId, "OpenStack", "DeleteStack", ErrorCode.DataError.getValue(),
+ "Exception - DeleteStack", me);
logger.debug(error);
- throw new VnfException (me);
+ throw new VnfException(me);
}
return;
}
- private VnfStatus stackStatusToVnfStatus (HeatStatus stackStatus) {
+ private VnfStatus stackStatusToVnfStatus(HeatStatus stackStatus) {
switch (stackStatus) {
case CREATED:
return VnfStatus.ACTIVE;
@@ -463,75 +394,73 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
}
}
- private Map <String, String> copyStringOutputs(Map <String, Object> stackOutputs) {
- Map <String, String> stringOutputs = new HashMap <> ();
- for (Map.Entry<String,Object> entry : stackOutputs.entrySet ()) {
+ private Map<String, String> copyStringOutputs(Map<String, Object> stackOutputs) {
+ Map<String, String> stringOutputs = new HashMap<>();
+ for (Map.Entry<String, Object> entry : stackOutputs.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
try {
- stringOutputs.put(key, value.toString());
+ stringOutputs.put(key, value.toString());
} catch (Exception e) {
- StringBuilder msg = new StringBuilder("Unable to add " + key + " to outputs");
- if (value instanceof Integer) { // nothing to add to the message
- } else if (value instanceof JsonNode) {
- msg.append(" - exception converting JsonNode");
- } else if (value instanceof java.util.LinkedHashMap) {
- msg.append(" exception converting LinkedHashMap");
- } else {
- msg.append(" - unable to call .toString() " + e.getMessage());
- }
- logger.debug(msg.toString(), e);
+ StringBuilder msg = new StringBuilder("Unable to add " + key + " to outputs");
+ if (value instanceof Integer) { // nothing to add to the message
+ } else if (value instanceof JsonNode) {
+ msg.append(" - exception converting JsonNode");
+ } else if (value instanceof java.util.LinkedHashMap) {
+ msg.append(" exception converting LinkedHashMap");
+ } else {
+ msg.append(" - unable to call .toString() " + e.getMessage());
+ }
+ logger.debug(msg.toString(), e);
}
}
return stringOutputs;
}
- private Map <String, Object> copyStringInputs (Map <String, Object> stringInputs) {
- return new HashMap <> (stringInputs);
+ private Map<String, Object> copyStringInputs(Map<String, Object> stringInputs) {
+ return new HashMap<>(stringInputs);
}
protected boolean callHeatbridge(String heatStackId) {
- String executionDir = "/usr/local/lib/python2.7/dist-packages/heatbridge";
- String openstackIdentityUrl = "", username = "", password = "", tenant = "", region = "", owner = "";
+ String executionDir = "/usr/local/lib/python2.7/dist-packages/heatbridge";
+ String openstackIdentityUrl = "", username = "", password = "", tenant = "", region = "", owner = "";
long waitTimeMs = 10000L;
- try {
- String[] cmdarray =
- {"/usr/bin/python", "HeatBridgeMain.py", openstackIdentityUrl, username, password, tenant, region, owner,
- heatStackId};
- String[] envp = null;
- File dir = new File(executionDir);
- logger.debug("Calling HeatBridgeMain.py in {} with arguments {}", dir, Arrays.toString(cmdarray));
- Runtime r = Runtime.getRuntime();
- Process p = r.exec(cmdarray, envp, dir);
- boolean wait = p.waitFor(waitTimeMs, TimeUnit.MILLISECONDS);
-
- logger.debug(" HeatBridgeMain.py returned {} with code {}", wait, p.exitValue());
- return wait && p.exitValue() == 0;
- } catch (IOException e) {
- logger.debug(" HeatBridgeMain.py failed with IO Exception! " + e);
- return false;
- } catch (RuntimeException e) {
- logger.debug(" HeatBridgeMain.py failed during runtime!" + e);
- return false;
- }
- catch (Exception e) {
- logger.debug(" HeatBridgeMain.py failed for unknown reasons! " + e);
- return false;
- }
+ try {
+ String[] cmdarray = {"/usr/bin/python", "HeatBridgeMain.py", openstackIdentityUrl, username, password,
+ tenant, region, owner, heatStackId};
+ String[] envp = null;
+ File dir = new File(executionDir);
+ logger.debug("Calling HeatBridgeMain.py in {} with arguments {}", dir, Arrays.toString(cmdarray));
+ Runtime r = Runtime.getRuntime();
+ Process p = r.exec(cmdarray, envp, dir);
+ boolean wait = p.waitFor(waitTimeMs, TimeUnit.MILLISECONDS);
+
+ logger.debug(" HeatBridgeMain.py returned {} with code {}", wait, p.exitValue());
+ return wait && p.exitValue() == 0;
+ } catch (IOException e) {
+ logger.debug(" HeatBridgeMain.py failed with IO Exception! " + e);
+ return false;
+ } catch (RuntimeException e) {
+ logger.debug(" HeatBridgeMain.py failed during runtime!" + e);
+ return false;
+ } catch (Exception e) {
+ logger.debug(" HeatBridgeMain.py failed for unknown reasons! " + e);
+ return false;
+ }
}
- private void heatbridge(StackInfo heatStack, String cloudOwner, String cloudSiteId, String tenantId, String genericVnfName,
- String vfModuleId) {
+ private void heatbridge(StackInfo heatStack, String cloudOwner, String cloudSiteId, String tenantId,
+ String genericVnfName, String vfModuleId) {
try {
- CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
- () -> new MsoCloudSiteNotFound(cloudSiteId));
+ CloudSite cloudSite =
+ cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
CloudIdentity cloudIdentity = cloudSite.getIdentityService();
String heatStackId = heatStack.getCanonicalName().split("/")[1];
List<String> oobMgtNetNames = new ArrayList<>();
- HeatBridgeApi heatBridgeClient = new HeatBridgeImpl(new AAIResourcesClient(), cloudIdentity,
- cloudOwner, cloudSiteId, tenantId);
+ HeatBridgeApi heatBridgeClient =
+ new HeatBridgeImpl(new AAIResourcesClient(), cloudIdentity, cloudOwner, cloudSiteId, tenantId);
OpenstackClient openstackClient = heatBridgeClient.authenticate();
List<Resource> stackResources = heatBridgeClient.queryNestedHeatStackResources(heatStackId);
@@ -543,14 +472,14 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
List<Flavor> osFlavors = heatBridgeClient.extractOpenstackFlavorsFromServers(osServers);
logger.debug("Successfully queried heat stack{} for resources.", heatStackId);
- //os images
+ // os images
if (osImages != null && !osImages.isEmpty()) {
heatBridgeClient.buildAddImagesToAaiAction(osImages);
logger.debug("Successfully built AAI actions to add images.");
} else {
logger.debug("No images to update to AAI.");
}
- //flavors
+ // flavors
if (osFlavors != null && !osFlavors.isEmpty()) {
heatBridgeClient.buildAddFlavorsToAaiAction(osFlavors);
logger.debug("Successfully built AAI actions to add flavors.");
@@ -558,22 +487,22 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
logger.debug("No flavors to update to AAI.");
}
- //compute resources
+ // compute resources
heatBridgeClient.buildAddVserversToAaiAction(genericVnfName, vfModuleId, osServers);
logger.debug("Successfully queried compute resources and built AAI vserver actions.");
- //neutron resources
+ // neutron resources
List<String> oobMgtNetIds = new ArrayList<>();
- //if no network-id list is provided, however network-name list is
+ // if no network-id list is provided, however network-name list is
if (!CollectionUtils.isEmpty(oobMgtNetNames)) {
oobMgtNetIds = heatBridgeClient.extractNetworkIds(oobMgtNetNames);
}
heatBridgeClient.buildAddVserverLInterfacesToAaiAction(stackResources, oobMgtNetIds);
logger.debug(
- "Successfully queried neutron resources and built AAI actions to add l-interfaces to vservers.");
+ "Successfully queried neutron resources and built AAI actions to add l-interfaces to vservers.");
- //Update AAI
+ // Update AAI
heatBridgeClient.submitToAai();
} catch (Exception ex) {
logger.debug("Heatbrige failed for stackId: " + heatStack.getCanonicalName(), ex);
@@ -585,9 +514,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
return JSON_MAPPER.writeValueAsString(obj);
} catch (JsonParseException jpe) {
- logger.debug("Error converting json to string: {}", jpe.getMessage(),jpe);
+ logger.debug("Error converting json to string: {}", jpe.getMessage(), jpe);
} catch (Exception e) {
- logger.debug("Error converting json to string: {}", e.getMessage(),e);
+ logger.debug("Error converting json to string: {}", e.getMessage(), e);
}
return "[Error converting json to string]";
}
@@ -602,15 +531,15 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
Object obj = objectMap.get(key);
if (obj instanceof String) {
stringMap.put(key, (String) objectMap.get(key));
- } else if (obj instanceof JsonNode ){
+ } else if (obj instanceof JsonNode) {
// This is a bit of mess - but I think it's the least impacting
// let's convert it BACK to a string - then it will get converted back later
try {
String str = this.convertNode((JsonNode) obj);
stringMap.put(key, str);
} catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode "+ key,e);
- //okay in this instance - only string values (fqdn) are expected to be needed
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode " + key, e);
+ // okay in this instance - only string values (fqdn) are expected to be needed
}
} else if (obj instanceof java.util.LinkedHashMap) {
logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
@@ -618,21 +547,23 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
String str = JSON_MAPPER.writeValueAsString(obj);
stringMap.put(key, str);
} catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap "+ key,e);
- }
- } else if (obj instanceof Integer) {
- try {
- String str = "" + obj;
- stringMap.put(key, str);
- } catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer "+ key,e);
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap " + key, e);
+ }
+ } else if (obj instanceof Integer) {
+ try {
+ String str = "" + obj;
+ stringMap.put(key, str);
+ } catch (Exception e) {
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer " + key, e);
}
} else {
try {
- String str = obj.toString();
+ String str = obj.toString();
stringMap.put(key, str);
} catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value "+ key + " (" + e.getMessage() + ")",e);
+ logger.debug(
+ "DANGER WILL ROBINSON: unable to convert value " + key + " (" + e.getMessage() + ")",
+ e);
}
}
}
@@ -642,34 +573,21 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
}
@Override
- public void createVfModule(String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfType,
- String vnfVersion,
- String genericVnfName,
- String vnfName,
- String vfModuleId,
- String requestType,
- String volumeGroupHeatStackId,
- String baseVfHeatStackId,
- String modelCustomizationUuid,
- Map <String, Object> inputs,
- Boolean failIfExists,
- Boolean backout,
- Boolean enableBridge,
- MsoRequest msoRequest,
- Holder <String> vnfId,
- Holder <Map <String, String>> outputs,
- Holder <VnfRollback> rollback) throws VnfException {
- String vfModuleName = vnfName;
- String vfModuleType = vnfType;
- String vfVersion = vnfVersion;
+ public void createVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfType,
+ String vnfVersion, String genericVnfName, String vnfName, String vfModuleId, String requestType,
+ String volumeGroupHeatStackId, String baseVfHeatStackId, String modelCustomizationUuid,
+ Map<String, Object> inputs, Boolean failIfExists, Boolean backout, Boolean enableBridge,
+ MsoRequest msoRequest, Holder<String> vnfId, Holder<Map<String, String>> outputs,
+ Holder<VnfRollback> rollback) throws VnfException {
+ String vfModuleName = vnfName;
+ String vfModuleType = vnfType;
+ String vfVersion = vnfVersion;
String mcu = modelCustomizationUuid;
boolean useMCUuid = false;
if (mcu != null && !mcu.isEmpty()) {
if ("null".equalsIgnoreCase(mcu)) {
- logger.debug("modelCustomizationUuid: passed in as the string 'null' - will ignore: " + modelCustomizationUuid);
+ logger.debug("modelCustomizationUuid: passed in as the string 'null' - will ignore: "
+ + modelCustomizationUuid);
useMCUuid = false;
mcu = "";
} else {
@@ -678,37 +596,39 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
}
}
- String requestTypeString = "";
+ String requestTypeString = "";
if (requestType != null && !"".equals(requestType)) {
- requestTypeString = requestType;
+ requestTypeString = requestType;
}
String nestedStackId = null;
- if (volumeGroupHeatStackId != null && !"".equals(volumeGroupHeatStackId) && !"null".equalsIgnoreCase(volumeGroupHeatStackId)) {
- nestedStackId = volumeGroupHeatStackId;
+ if (volumeGroupHeatStackId != null && !"".equals(volumeGroupHeatStackId)
+ && !"null".equalsIgnoreCase(volumeGroupHeatStackId)) {
+ nestedStackId = volumeGroupHeatStackId;
}
String nestedBaseStackId = null;
if (baseVfHeatStackId != null && !"".equals(baseVfHeatStackId) && !"null".equalsIgnoreCase(baseVfHeatStackId)) {
- nestedBaseStackId = baseVfHeatStackId;
+ nestedBaseStackId = baseVfHeatStackId;
}
- //This method will also handle doing things the "old" way - i.e., just orchestrate a VNF
+ // This method will also handle doing things the "old" way - i.e., just orchestrate a VNF
boolean oldWay = false;
if (requestTypeString.startsWith("X")) {
- oldWay = true;
+ oldWay = true;
logger.debug("orchestrating a VNF - *NOT* a module!");
- requestTypeString = requestTypeString.substring(1);
+ requestTypeString = requestTypeString.substring(1);
}
// 1607 - let's parse out the request type we're being sent
boolean isBaseRequest = false;
boolean isVolumeRequest = false;
if (requestTypeString.startsWith("VOLUME")) {
- isVolumeRequest = true;
+ isVolumeRequest = true;
}
- logger.debug("requestTypeString = " + requestTypeString + ", nestedStackId = " + nestedStackId + ", nestedBaseStackId = " + nestedBaseStackId);
+ logger.debug("requestTypeString = " + requestTypeString + ", nestedStackId = " + nestedStackId
+ + ", nestedBaseStackId = " + nestedBaseStackId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
// Build a default rollback object (no actions performed)
VnfRollback vfRollback = new VnfRollback();
@@ -723,145 +643,158 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
vfRollback.setModelCustomizationUuid(mcu);
// Put data into A&AI through Heatstack
- if(enableBridge != null && enableBridge) {
- callHeatbridge(baseVfHeatStackId);
+ if (enableBridge != null && enableBridge) {
+ callHeatbridge(baseVfHeatStackId);
}
StackInfo heatStack = null;
- long subStartTime1 = System.currentTimeMillis ();
+ long subStartTime1 = System.currentTimeMillis();
try {
- heatStack = heat.queryStack (cloudSiteId, cloudOwner, tenantId, vfModuleName);
+ heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vfModuleName);
} catch (MsoException me) {
- String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(), "Exception - queryStack",
- me);
+ String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/"
+ + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(),
+ "Exception - queryStack", me);
logger.debug(error);
// Failed to query the Stack due to an openstack exception.
// Convert to a generic VnfException
- me.addContext ("CreateVFModule");
- throw new VnfException (me);
+ me.addContext("CreateVFModule");
+ throw new VnfException(me);
}
// New with 1607 - more precise handling/messaging if the stack already exists
if (heatStack != null && heatStack.getStatus() != HeatStatus.NOTFOUND) {
- // INIT, CREATED, NOTFOUND, FAILED, BUILDING, DELETING, UNKNOWN, UPDATING, UPDATED
- HeatStatus status = heatStack.getStatus();
- if (status == HeatStatus.INIT || status == HeatStatus.BUILDING || status == HeatStatus.DELETING || status == HeatStatus.UPDATING) {
- // fail - it's in progress - return meaningful error
- String error = "Create VF: Stack " + vfModuleName + " already exists and has status " + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; please wait for it to complete, or fix manually.";
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(),
- "Stack " + vfModuleName + " already exists");
- logger.debug(error);
- throw new VnfAlreadyExists (vfModuleName, cloudOwner, cloudSiteId, tenantId, heatStack.getCanonicalName ());
- }
- if (status == HeatStatus.FAILED) {
- // fail - it exists and is in a FAILED state
- String error = "Create VF: Stack " + vfModuleName + " already exists and is in FAILED state in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention.";
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(),
- "Stack " + vfModuleName + " already exists and is " + "in FAILED state");
- logger.debug(error);
- throw new VnfAlreadyExists (vfModuleName, cloudOwner, cloudSiteId, tenantId, heatStack.getCanonicalName ());
- }
- if (status == HeatStatus.UNKNOWN || status == HeatStatus.UPDATED) {
- // fail - it exists and is in a FAILED state
- String error =
- "Create VF: Stack " + vfModuleName + " already exists and has status " + status.toString() + " in "
- + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention.";
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(),
- "Stack " + vfModuleName + " already exists and is " + "in UPDATED or UNKNOWN state");
- logger.debug(error);
- throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, heatStack.getCanonicalName());
- }
- if (status == HeatStatus.CREATED) {
- // fail - it exists
- if (failIfExists != null && failIfExists) {
- String error =
- "Create VF: Stack " + vfModuleName + " already exists in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId;
+ // INIT, CREATED, NOTFOUND, FAILED, BUILDING, DELETING, UNKNOWN, UPDATING, UPDATED
+ HeatStatus status = heatStack.getStatus();
+ if (status == HeatStatus.INIT || status == HeatStatus.BUILDING || status == HeatStatus.DELETING
+ || status == HeatStatus.UPDATING) {
+ // fail - it's in progress - return meaningful error
+ String error = "Create VF: Stack " + vfModuleName + " already exists and has status "
+ + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + "; please wait for it to complete, or fix manually.";
logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(),
- "Stack " + vfModuleName + " already exists");
+ cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(),
+ "Stack " + vfModuleName + " already exists");
logger.debug(error);
- throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, heatStack.getCanonicalName());
- } else {
- logger.debug ("Found Existing stack, status={}", heatStack.getStatus ());
- // Populate the outputs from the existing stack.
- vnfId.value = heatStack.getCanonicalName ();
- outputs.value = copyStringOutputs (heatStack.getOutputs ());
- rollback.value = vfRollback; // Default rollback - no updates performed
- }
- }
+ throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId,
+ heatStack.getCanonicalName());
+ }
+ if (status == HeatStatus.FAILED) {
+ // fail - it exists and is in a FAILED state
+ String error = "Create VF: Stack " + vfModuleName + " already exists and is in FAILED state in "
+ + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention.";
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(),
+ "Stack " + vfModuleName + " already exists and is " + "in FAILED state");
+ logger.debug(error);
+ throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId,
+ heatStack.getCanonicalName());
+ }
+ if (status == HeatStatus.UNKNOWN || status == HeatStatus.UPDATED) {
+ // fail - it exists and is in a FAILED state
+ String error = "Create VF: Stack " + vfModuleName + " already exists and has status "
+ + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + "; requires manual intervention.";
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(),
+ "Stack " + vfModuleName + " already exists and is " + "in UPDATED or UNKNOWN state");
+ logger.debug(error);
+ throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId,
+ heatStack.getCanonicalName());
+ }
+ if (status == HeatStatus.CREATED) {
+ // fail - it exists
+ if (failIfExists != null && failIfExists) {
+ String error = "Create VF: Stack " + vfModuleName + " already exists in " + cloudOwner + "/"
+ + cloudSiteId + "/" + tenantId;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(),
+ vfModuleName, cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack",
+ ErrorCode.DataError.getValue(), "Stack " + vfModuleName + " already exists");
+ logger.debug(error);
+ throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId,
+ heatStack.getCanonicalName());
+ } else {
+ logger.debug("Found Existing stack, status={}", heatStack.getStatus());
+ // Populate the outputs from the existing stack.
+ vnfId.value = heatStack.getCanonicalName();
+ outputs.value = copyStringOutputs(heatStack.getOutputs());
+ rollback.value = vfRollback; // Default rollback - no updates performed
+ }
+ }
return;
}
// handle a nestedStackId if sent- this one would be for the volume - so applies to both Vf and Vnf
StackInfo nestedHeatStack = null;
- long subStartTime2 = System.currentTimeMillis ();
+ long subStartTime2 = System.currentTimeMillis();
Map<String, Object> nestedVolumeOutputs = null;
if (nestedStackId != null) {
- try {
- logger.debug("Querying for nestedStackId = {}", nestedStackId);
- nestedHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedStackId);
- } catch (MsoException me) {
- // Failed to query the Stack due to an openstack exception.
- // Convert to a generic VnfException
- me.addContext ("CreateVFModule");
- String error = "Create VFModule: Attached heatStack ID Query " + nestedStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", "queryStack", ErrorCode.BusinessProcesssError.getValue(),
- "MsoException trying to query nested stack", me);
- logger.debug("ERROR trying to query nested stack= {}", error);
- throw new VnfException (me);
- }
- if (nestedHeatStack == null || nestedHeatStack.getStatus() == HeatStatus.NOTFOUND) {
- String error = "Create VFModule: Attached heatStack ID DOES NOT EXIST " + nestedStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR" ;
- logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, error, "OpenStack", "queryStack",
- ErrorCode.BusinessProcesssError.getValue(),
- "Create VFModule: Attached heatStack ID " + "DOES NOT EXIST");
- logger.debug(error);
- throw new VnfException (error, MsoExceptionCategory.USERDATA);
- } else {
- logger.debug("Found nested volume heat stack - copying values to inputs *later*");
- nestedVolumeOutputs = nestedHeatStack.getOutputs();
- }
+ try {
+ logger.debug("Querying for nestedStackId = {}", nestedStackId);
+ nestedHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedStackId);
+ } catch (MsoException me) {
+ // Failed to query the Stack due to an openstack exception.
+ // Convert to a generic VnfException
+ me.addContext("CreateVFModule");
+ String error = "Create VFModule: Attached heatStack ID Query " + nestedStackId + " in " + cloudOwner
+ + "/" + cloudSiteId + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack",
+ ErrorCode.BusinessProcesssError.getValue(), "MsoException trying to query nested stack", me);
+ logger.debug("ERROR trying to query nested stack= {}", error);
+ throw new VnfException(me);
+ }
+ if (nestedHeatStack == null || nestedHeatStack.getStatus() == HeatStatus.NOTFOUND) {
+ String error = "Create VFModule: Attached heatStack ID DOES NOT EXIST " + nestedStackId + " in "
+ + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR";
+ logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, error, "OpenStack", "queryStack",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create VFModule: Attached heatStack ID " + "DOES NOT EXIST");
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ } else {
+ logger.debug("Found nested volume heat stack - copying values to inputs *later*");
+ nestedVolumeOutputs = nestedHeatStack.getOutputs();
+ }
}
// handle a nestedBaseStackId if sent- this is the stack ID of the base. Should be null for VNF requests
StackInfo nestedBaseHeatStack = null;
- long subStartTime3 = System.currentTimeMillis ();
+ long subStartTime3 = System.currentTimeMillis();
Map<String, Object> baseStackOutputs = null;
if (nestedBaseStackId != null) {
- try {
- logger.debug("Querying for nestedBaseStackId = {}", nestedBaseStackId);
- nestedBaseHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId);
- } catch (MsoException me) {
- // Failed to query the Stack due to an openstack exception.
- // Convert to a generic VnfException
- me.addContext ("CreateVFModule");
- String error = "Create VFModule: Attached baseHeatStack ID Query " + nestedBaseStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ;
- logger
- .error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", "QueryStack", ErrorCode.BusinessProcesssError.getValue(),
- "MsoException trying to query nested base stack", me);
- logger.debug("ERROR trying to query nested base stack= {}", error);
- throw new VnfException (me);
- }
- if (nestedBaseHeatStack == null || nestedBaseHeatStack.getStatus() == HeatStatus.NOTFOUND) {
- String error = "Create VFModule: Attached base heatStack ID DOES NOT EXIST " + nestedBaseStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR" ;
- logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, error, "OpenStack", "QueryStack",
- ErrorCode.BusinessProcesssError.getValue(),
- "Create VFModule: Attached base heatStack ID DOES NOT EXIST");
- logger.debug("Exception occurred", error);
- throw new VnfException (error, MsoExceptionCategory.USERDATA);
- } else {
- logger.debug("Found nested base heat stack - these values will be copied to inputs *later*");
- baseStackOutputs = nestedBaseHeatStack.getOutputs();
- }
+ try {
+ logger.debug("Querying for nestedBaseStackId = {}", nestedBaseStackId);
+ nestedBaseHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId);
+ } catch (MsoException me) {
+ // Failed to query the Stack due to an openstack exception.
+ // Convert to a generic VnfException
+ me.addContext("CreateVFModule");
+ String error = "Create VFModule: Attached baseHeatStack ID Query " + nestedBaseStackId + " in "
+ + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, "OpenStack", "QueryStack",
+ ErrorCode.BusinessProcesssError.getValue(), "MsoException trying to query nested base stack",
+ me);
+ logger.debug("ERROR trying to query nested base stack= {}", error);
+ throw new VnfException(me);
+ }
+ if (nestedBaseHeatStack == null || nestedBaseHeatStack.getStatus() == HeatStatus.NOTFOUND) {
+ String error = "Create VFModule: Attached base heatStack ID DOES NOT EXIST " + nestedBaseStackId
+ + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR";
+ logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, error, "OpenStack", "QueryStack",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create VFModule: Attached base heatStack ID DOES NOT EXIST");
+ logger.debug("Exception occurred", error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ } else {
+ logger.debug("Found nested base heat stack - these values will be copied to inputs *later*");
+ baseStackOutputs = nestedBaseHeatStack.getOutputs();
+ }
}
// Ready to deploy the new VNF
@@ -870,30 +803,31 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
try {
// Retrieve the VF
- VfModule vf = null;
- VnfResource vnfResource = null;
- VfModuleCustomization vfmc = null;
- logger.debug("version: {}", vfVersion);
+ VfModule vf = null;
+ VnfResource vnfResource = null;
+ VfModuleCustomization vfmc = null;
+ logger.debug("version: {}", vfVersion);
if (useMCUuid) {
- // 1707 - db refactoring
- vfmc = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(mcu);
- if(vfmc != null)
- vf=vfmc.getVfModule();
- else
- vf=null;
+ // 1707 - db refactoring
+ vfmc = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(mcu);
+ if (vfmc != null)
+ vf = vfmc.getVfModule();
+ else
+ vf = null;
// 1702 - this will be the new way going forward. We find the vf by mcu - otherwise, code is the same.
if (vf == null) {
- logger.debug("Unable to find vfModuleCust with modelCustomizationUuid={}", mcu);
- String error = "Create vfModule error: Unable to find vfModuleCust with modelCustomizationUuid=" + mcu;
+ logger.debug("Unable to find vfModuleCust with modelCustomizationUuid={}", mcu);
+ String error =
+ "Create vfModule error: Unable to find vfModuleCust with modelCustomizationUuid=" + mcu;
logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(),
- "VF Module ModelCustomizationUuid", modelCustomizationUuid, "OpenStack",
- ErrorCode.DataError.getValue(),
- "Create VF Module: Unable to find vfModule with " + "modelCustomizationUuid=" + mcu);
+ "VF Module ModelCustomizationUuid", modelCustomizationUuid, "OpenStack",
+ ErrorCode.DataError.getValue(),
+ "Create VF Module: Unable to find vfModule with " + "modelCustomizationUuid=" + mcu);
logger.debug(error);
throw new VnfException(error, MsoExceptionCategory.USERDATA);
} else {
- logger.trace("Found vfModuleCust entry {}", vfmc.toString());
+ logger.trace("Found vfModuleCust entry {}", vfmc.toString());
}
if (vf.getIsBase()) {
isBaseRequest = true;
@@ -901,166 +835,170 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
} else {
logger.debug("This is *not* a BASE VF request!");
if (!isVolumeRequest && nestedBaseStackId == null) {
- logger.debug("DANGER WILL ROBINSON! This is unexpected - no nestedBaseStackId with this non-base request");
+ logger.debug(
+ "DANGER WILL ROBINSON! This is unexpected - no nestedBaseStackId with this non-base request");
}
}
- }
-
- else { // This is to support gamma only - get info from vnf_resource table
- if (vfVersion != null && !vfVersion.isEmpty()) {
- vnfResource = vnfResourceRepo.findByModelNameAndModelVersion(vnfType, vnfVersion);
- } else {
- vnfResource = vnfResourceRepo.findByModelName(vnfType);
- }
- if (vnfResource == null) {
- String error = "Create VNF: Unknown VNF Type: " + vnfType;
- logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VNF Type", vnfType,
- "OpenStack", ErrorCode.DataError.getValue(), "Create VNF: Unknown VNF Type");
- logger.debug(error);
- throw new VnfException(error, MsoExceptionCategory.USERDATA);
- }
+ }
+
+ else { // This is to support gamma only - get info from vnf_resource table
+ if (vfVersion != null && !vfVersion.isEmpty()) {
+ vnfResource = vnfResourceRepo.findByModelNameAndModelVersion(vnfType, vnfVersion);
+ } else {
+ vnfResource = vnfResourceRepo.findByModelName(vnfType);
+ }
+ if (vnfResource == null) {
+ String error = "Create VNF: Unknown VNF Type: " + vnfType;
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VNF Type", vnfType,
+ "OpenStack", ErrorCode.DataError.getValue(), "Create VNF: Unknown VNF Type");
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ }
logger.debug("Got VNF module definition from Catalog: {}", vnfResource.toString());
}
- // By here - we have either a vf or vnfResource
+ // By here - we have either a vf or vnfResource
- //1607 - Add version check
+ // 1607 - Add version check
// First - see if it's in the VnfResource record
// if we have a vf Module - then we have to query to get the VnfResource record.
if (!oldWay && vf.getVnfResources() != null) {
- vnfResource = vf.getVnfResources();
- if (vnfResource == null) {
- logger.debug("Unable to find vnfResource will not error for now...");
- }
+ vnfResource = vf.getVnfResources();
+ if (vnfResource == null) {
+ logger.debug("Unable to find vnfResource will not error for now...");
+ }
}
String minVersionVnf = null;
String maxVersionVnf = null;
if (vnfResource != null) {
- try {
- minVersionVnf = vnfResource.getAicVersionMin();
- maxVersionVnf = vnfResource.getAicVersionMax();
- } catch (Exception e) {
- logger.debug("Unable to pull min/max version for this VNF Resource entry",e);
- minVersionVnf = null;
- maxVersionVnf = null;
- }
- if (minVersionVnf != null && "".equals(minVersionVnf)) {
- minVersionVnf = null;
- }
- if (maxVersionVnf != null && "".equals(maxVersionVnf)) {
- maxVersionVnf = null;
- }
- }
- if (minVersionVnf != null && maxVersionVnf != null) {
- MavenLikeVersioning aicV = new MavenLikeVersioning();
-
- // double check
- if (this.cloudConfig != null) {
+ try {
+ minVersionVnf = vnfResource.getAicVersionMin();
+ maxVersionVnf = vnfResource.getAicVersionMax();
+ } catch (Exception e) {
+ logger.debug("Unable to pull min/max version for this VNF Resource entry", e);
+ minVersionVnf = null;
+ maxVersionVnf = null;
+ }
+ if (minVersionVnf != null && "".equals(minVersionVnf)) {
+ minVersionVnf = null;
+ }
+ if (maxVersionVnf != null && "".equals(maxVersionVnf)) {
+ maxVersionVnf = null;
+ }
+ }
+ if (minVersionVnf != null && maxVersionVnf != null) {
+ MavenLikeVersioning aicV = new MavenLikeVersioning();
+
+ // double check
+ if (this.cloudConfig != null) {
Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId);
if (cloudSiteOpt.isPresent()) {
aicV.setVersion(cloudSiteOpt.get().getCloudVersion());
- // Add code to handle unexpected values in here
- boolean moreThanMin = true;
- boolean equalToMin = true;
- boolean moreThanMax = true;
- boolean equalToMax = true;
- boolean doNotTest = false;
- try {
- moreThanMin = aicV.isMoreRecentThan(minVersionVnf);
- equalToMin = aicV.isTheSameVersion(minVersionVnf);
- moreThanMax = aicV.isMoreRecentThan(maxVersionVnf);
- equalToMax = aicV.isTheSameVersion(maxVersionVnf);
- } catch (Exception e) {
- logger.debug("An exception occurred while trying to test AIC Version {} - will default to not check",
- e.getMessage(), e);
- doNotTest = true;
- }
- if (!doNotTest) {
- if ((moreThanMin || equalToMin) // aic >= min
- && (equalToMax || !(moreThanMax))) { //aic <= max
- logger.debug(
- "VNF Resource " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUUID()
- + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: "
- + cloudSiteId + " with AIC_Version:" + cloudSiteOpt.get().getCloudVersion());
- } else {
- // ERROR
- String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUUID() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteId + " with AIC_Version:" + cloudSiteOpt.get().getCloudVersion();
- logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack",
- ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion");
- logger.debug(error);
- throw new VnfException(error, MsoExceptionCategory.USERDATA);
- }
- } else {
- logger.debug("bypassing testing AIC version...");
- }
- } // let this error out downstream to avoid introducing uncertainty at this stage
- } else {
- logger.debug("cloudConfig is NULL - cannot check cloud site version");
- }
- } else {
- logger.debug("AIC Version not set in VNF_Resource - this is expected thru 1607 - do not error here - not checked"
- + ".");
- }
- // End Version check 1607
-
-
-
-
- // By the time we get here - heatTemplateId and heatEnvtId should be populated (or null)
- HeatTemplate heatTemplate = null;
+ // Add code to handle unexpected values in here
+ boolean moreThanMin = true;
+ boolean equalToMin = true;
+ boolean moreThanMax = true;
+ boolean equalToMax = true;
+ boolean doNotTest = false;
+ try {
+ moreThanMin = aicV.isMoreRecentThan(minVersionVnf);
+ equalToMin = aicV.isTheSameVersion(minVersionVnf);
+ moreThanMax = aicV.isMoreRecentThan(maxVersionVnf);
+ equalToMax = aicV.isTheSameVersion(maxVersionVnf);
+ } catch (Exception e) {
+ logger.debug(
+ "An exception occurred while trying to test AIC Version {} - will default to not check",
+ e.getMessage(), e);
+ doNotTest = true;
+ }
+ if (!doNotTest) {
+ if ((moreThanMin || equalToMin) // aic >= min
+ && (equalToMax || !(moreThanMax))) { // aic <= max
+ logger.debug("VNF Resource " + vnfResource.getModelName() + ", ModelUuid="
+ + vnfResource.getModelUUID() + " VersionMin=" + minVersionVnf + " VersionMax:"
+ + maxVersionVnf + " supported on Cloud: " + cloudSiteId + " with AIC_Version:"
+ + cloudSiteOpt.get().getCloudVersion());
+ } else {
+ // ERROR
+ String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid="
+ + vnfResource.getModelUUID() + " VersionMin=" + minVersionVnf + " VersionMax:"
+ + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteId
+ + " with AIC_Version:" + cloudSiteOpt.get().getCloudVersion();
+ logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion");
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ }
+ } else {
+ logger.debug("bypassing testing AIC version...");
+ }
+ } // let this error out downstream to avoid introducing uncertainty at this stage
+ } else {
+ logger.debug("cloudConfig is NULL - cannot check cloud site version");
+ }
+ } else {
+ logger.debug(
+ "AIC Version not set in VNF_Resource - this is expected thru 1607 - do not error here - not checked"
+ + ".");
+ }
+ // End Version check 1607
+
+
+
+ // By the time we get here - heatTemplateId and heatEnvtId should be populated (or null)
+ HeatTemplate heatTemplate = null;
HeatEnvironment heatEnvironment = null;
if (oldWay) {
- //This will handle old Gamma BrocadeVCE VNF
- heatTemplate = vnfResource.getHeatTemplates();
- }
- else {
- if (vf != null) {
- if (isVolumeRequest) {
- heatTemplate = vf.getVolumeHeatTemplate();
- heatEnvironment = vfmc.getVolumeHeatEnv();
- } else {
- heatTemplate = vf.getModuleHeatTemplate();
- heatEnvironment = vfmc.getHeatEnvironment();
- }
- }
- }
-
- if (heatTemplate == null) {
- String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + ", reqType=" + requestTypeString;
- logger
- .error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", vfModuleType,
- "OpenStack", ErrorCode.DataError.getValue(), error);
- logger.debug(error);
- throw new VnfException(error, MsoExceptionCategory.INTERNAL);
- } else {
- logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate());
- }
-
- if (oldWay) {
- //This will handle old Gamma BrocadeVCE VNF
- logger.debug("No environment parameter found for this Type " + vfModuleType);
- } else {
- if (heatEnvironment == null) {
- String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType;
- logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID",
- "OpenStack", ErrorCode.DataError.getValue(), error);
- logger.debug(error);
- throw new VnfException (error, MsoExceptionCategory.INTERNAL);
- } else {
- logger.debug("Got Heat Environment from DB: {}", heatEnvironment.getEnvironment());
- }
- }
+ // This will handle old Gamma BrocadeVCE VNF
+ heatTemplate = vnfResource.getHeatTemplates();
+ } else {
+ if (vf != null) {
+ if (isVolumeRequest) {
+ heatTemplate = vf.getVolumeHeatTemplate();
+ heatEnvironment = vfmc.getVolumeHeatEnv();
+ } else {
+ heatTemplate = vf.getModuleHeatTemplate();
+ heatEnvironment = vfmc.getHeatEnvironment();
+ }
+ }
+ }
+
+ if (heatTemplate == null) {
+ String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType
+ + ", reqType=" + requestTypeString;
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID",
+ vfModuleType, "OpenStack", ErrorCode.DataError.getValue(), error);
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.INTERNAL);
+ } else {
+ logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate());
+ }
+
+ if (oldWay) {
+ // This will handle old Gamma BrocadeVCE VNF
+ logger.debug("No environment parameter found for this Type " + vfModuleType);
+ } else {
+ if (heatEnvironment == null) {
+ String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType;
+ logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID",
+ "OpenStack", ErrorCode.DataError.getValue(), error);
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.INTERNAL);
+ } else {
+ logger.debug("Got Heat Environment from DB: {}", heatEnvironment.getEnvironment());
+ }
+ }
logger.debug("In MsoVnfAdapterImpl, about to call db.getNestedTemplates avec templateId="
- + heatTemplate.getArtifactUuid ());
+ + heatTemplate.getArtifactUuid());
List<HeatTemplate> nestedTemplates = heatTemplate.getChildTemplates();
- Map <String, Object> nestedTemplatesChecked = new HashMap <> ();
+ Map<String, Object> nestedTemplatesChecked = new HashMap<>();
if (nestedTemplates != null && !nestedTemplates.isEmpty()) {
// for debugging print them out
logger.debug("Contents of nestedTemplates - to be added to files: on stack:");
for (HeatTemplate entry : nestedTemplates) {
- nestedTemplatesChecked.put (entry.getTemplateName(), entry.getTemplateBody());
+ nestedTemplatesChecked.put(entry.getTemplateName(), entry.getTemplateBody());
logger.debug(entry.getTemplateName() + " -> " + entry.getTemplateBody());
}
} else {
@@ -1072,51 +1010,53 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
// *if* there are any
List<HeatFiles> heatFiles = null;
- Map<String, Object> heatFilesObjects = new HashMap<>();
+ Map<String, Object> heatFilesObjects = new HashMap<>();
// Add ability to turn on adding get_files with volume requests (by property).
boolean addGetFilesOnVolumeReq = false;
try {
- String propertyString = this.environment.getProperty(MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ);
- if ("true".equalsIgnoreCase(propertyString) || "y".equalsIgnoreCase(propertyString)) {
- addGetFilesOnVolumeReq = true;
- logger.debug("AddGetFilesOnVolumeReq - setting to true! {}", propertyString);
- }
+ String propertyString = this.environment.getProperty(MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ);
+ if ("true".equalsIgnoreCase(propertyString) || "y".equalsIgnoreCase(propertyString)) {
+ addGetFilesOnVolumeReq = true;
+ logger.debug("AddGetFilesOnVolumeReq - setting to true! {}", propertyString);
+ }
} catch (Exception e) {
logger.debug("An error occured trying to get property " + MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ
- + " - default to false", e);
- }
-
- if (!isVolumeRequest || addGetFilesOnVolumeReq) {
- if (oldWay) {
- logger.debug("In MsoVnfAdapterImpl createVfModule, this should not happen - old way is gamma only - no heat "
- + "files!");
- } else {
- // 1607 - now use VF_MODULE_TO_HEAT_FILES table
- logger.debug("In MsoVnfAdapterImpl createVfModule, about to call db.getHeatFilesForVfModule avec vfModuleId="
- + vf.getModelUUID());
- heatFiles = vf.getHeatFiles();
- }
- if (heatFiles != null && !heatFiles.isEmpty()) {
- // add these to stack - to be done in createStack
- // here, we will map them to Map<String, Object> from
- // Map<String, HeatFiles>
- // this will match the nested templates format
- logger.debug("Contents of heatFiles - to be added to files: on stack");
-
- for (HeatFiles heatfile : heatFiles) {
- logger.debug(heatfile.getFileName() + " -> " + heatfile.getFileBody());
- heatFilesObjects.put(heatfile.getFileName(), heatfile.getFileBody());
+ + " - default to false", e);
+ }
+
+ if (!isVolumeRequest || addGetFilesOnVolumeReq) {
+ if (oldWay) {
+ logger.debug(
+ "In MsoVnfAdapterImpl createVfModule, this should not happen - old way is gamma only - no heat "
+ + "files!");
+ } else {
+ // 1607 - now use VF_MODULE_TO_HEAT_FILES table
+ logger.debug(
+ "In MsoVnfAdapterImpl createVfModule, about to call db.getHeatFilesForVfModule avec vfModuleId="
+ + vf.getModelUUID());
+ heatFiles = vf.getHeatFiles();
+ }
+ if (heatFiles != null && !heatFiles.isEmpty()) {
+ // add these to stack - to be done in createStack
+ // here, we will map them to Map<String, Object> from
+ // Map<String, HeatFiles>
+ // this will match the nested templates format
+ logger.debug("Contents of heatFiles - to be added to files: on stack");
+
+ for (HeatFiles heatfile : heatFiles) {
+ logger.debug(heatfile.getFileName() + " -> " + heatfile.getFileBody());
+ heatFilesObjects.put(heatfile.getFileName(), heatfile.getFileBody());
+ }
+ } else {
+ logger.debug("No heat files found -nothing to do here");
+ heatFilesObjects = null;
+ }
}
- } else {
- logger.debug("No heat files found -nothing to do here");
- heatFilesObjects = null;
- }
- }
// Check that required parameters have been supplied
String missingParams = null;
- List <String> paramList = new ArrayList <> ();
+ List<String> paramList = new ArrayList<>();
// New for 1510 - consult the PARAM_ALIAS field to see if we've been
// supplied an alias. Only check if we don't find it initially.
@@ -1125,11 +1065,11 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
// shouldn't
boolean checkRequiredParameters = true;
try {
- String propertyString = this.environment.getProperty (MsoVnfAdapterImpl.CHECK_REQD_PARAMS);
- if ("false".equalsIgnoreCase (propertyString) || "n".equalsIgnoreCase (propertyString)) {
+ String propertyString = this.environment.getProperty(MsoVnfAdapterImpl.CHECK_REQD_PARAMS);
+ if ("false".equalsIgnoreCase(propertyString) || "n".equalsIgnoreCase(propertyString)) {
checkRequiredParameters = false;
logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking..."
- + MsoVnfAdapterImpl.CHECK_REQD_PARAMS);
+ + MsoVnfAdapterImpl.CHECK_REQD_PARAMS);
}
} catch (Exception e) {
// No problem - default is true
@@ -1140,21 +1080,22 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
// Part 2: only submit to openstack the parameters in the envt that are in the heat template
// Note this also removes any comments
MsoHeatEnvironmentEntry mhee = null;
- if (heatEnvironment != null && heatEnvironment.getEnvironment() != null && heatEnvironment.getEnvironment().contains ("parameters:")) {
+ if (heatEnvironment != null && heatEnvironment.getEnvironment() != null
+ && heatEnvironment.getEnvironment().contains("parameters:")) {
- logger.debug("Enhanced environment checking enabled - 1604");
+ logger.debug("Enhanced environment checking enabled - 1604");
StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment());
mhee = new MsoHeatEnvironmentEntry(sb);
StringBuilder sb2 = new StringBuilder("\nHeat Template Parameters:\n");
for (HeatTemplateParam parm : heatTemplate.getParameters()) {
- sb2.append("\t" + parm.getParamName() + ", required=" + parm.isRequired());
+ sb2.append("\t" + parm.getParamName() + ", required=" + parm.isRequired());
}
if (!mhee.isValid()) {
- sb2.append("Environment says it's not valid! " + mhee.getErrorString());
+ sb2.append("Environment says it's not valid! " + mhee.getErrorString());
} else {
- sb2.append("\nEnvironment:");
- sb2.append(mhee.toFullString());
+ sb2.append("\nEnvironment:");
+ sb2.append(mhee.toFullString());
}
logger.debug(sb2.toString());
} else {
@@ -1169,18 +1110,18 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
StringBuilder sb = new StringBuilder("\nTemplate Parameters:\n");
int cntr = 0;
try {
- for (HeatTemplateParam htp : heatTemplate.getParameters()) {
- sb.append("param[" + cntr++ + "]=" + htp.getParamName());
- parameterNames.add(htp.getParamName());
- if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) {
- aliasToParam.put(htp.getParamAlias(), htp.getParamName());
- sb.append(" ** (alias=" + htp.getParamAlias() + ")");
- }
- sb.append("\n");
- }
+ for (HeatTemplateParam htp : heatTemplate.getParameters()) {
+ sb.append("param[" + cntr++ + "]=" + htp.getParamName());
+ parameterNames.add(htp.getParamName());
+ if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) {
+ aliasToParam.put(htp.getParamAlias(), htp.getParamName());
+ sb.append(" ** (alias=" + htp.getParamAlias() + ")");
+ }
+ sb.append("\n");
+ }
logger.debug(sb.toString());
} catch (Exception e) {
- logger.debug("??An exception occurred trying to go through Parameter Names {}", e.getMessage(),e);
+ logger.debug("??An exception occurred trying to go through Parameter Names {}", e.getMessage(), e);
}
// Step 1 - convert what we got as inputs (Map<String, String>) to a
// Map<String, Object> - where the object matches the param type identified in the template
@@ -1193,176 +1134,164 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
logger.debug("Now add in the volume stack outputs if applicable");
heat.copyBaseOutputsToInputs(goldenInputs, nestedVolumeOutputs, parameterNames, aliasToParam);
- for (HeatTemplateParam parm : heatTemplate.getParameters ()) {
- logger.debug(
- "Parameter:'" + parm.getParamName() + "', isRequired=" + parm.isRequired() + ", alias=" + parm
- .getParamAlias());
+ for (HeatTemplateParam parm : heatTemplate.getParameters()) {
+ logger.debug("Parameter:'" + parm.getParamName() + "', isRequired=" + parm.isRequired() + ", alias="
+ + parm.getParamAlias());
- if (parm.isRequired () && (goldenInputs == null || !goldenInputs.containsKey (parm.getParamName ()))) {
- // The check for an alias was moved to the method in MsoHeatUtils - when we converted the Map<String, String> to Map<String, Object>
- logger.debug("**Parameter " + parm.getParamName() + " is required and not in the inputs...check "
- + "environment");
+ if (parm.isRequired() && (goldenInputs == null || !goldenInputs.containsKey(parm.getParamName()))) {
+ // The check for an alias was moved to the method in MsoHeatUtils - when we converted the
+ // Map<String, String> to Map<String, Object>
+ logger.debug("**Parameter " + parm.getParamName() + " is required and not in the inputs...check "
+ + "environment");
if (mhee != null && mhee.containsParameter(parm.getParamName())) {
logger.debug("Required parameter {} appears to be in environment - do not count as missing",
- parm.getParamName());
+ parm.getParamName());
} else {
logger.debug("adding to missing parameters list: {}", parm.getParamName());
if (missingParams == null) {
- missingParams = parm.getParamName ();
+ missingParams = parm.getParamName();
} else {
- missingParams += "," + parm.getParamName ();
+ missingParams += "," + parm.getParamName();
}
}
}
- paramList.add (parm.getParamName ());
+ paramList.add(parm.getParamName());
}
if (missingParams != null) {
- if (checkRequiredParameters) {
- // Problem - missing one or more required parameters
- String error = "Create VFModule: Missing Required inputs: " + missingParams;
- logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "OpenStack",
- ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs");
- logger.debug(error);
- throw new VnfException (error, MsoExceptionCategory.USERDATA);
- } else {
- logger.debug ("found missing parameters - but checkRequiredParameters is false - will not block");
- }
+ if (checkRequiredParameters) {
+ // Problem - missing one or more required parameters
+ String error = "Create VFModule: Missing Required inputs: " + missingParams;
+ logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "OpenStack",
+ ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs");
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ } else {
+ logger.debug("found missing parameters - but checkRequiredParameters is false - will not block");
+ }
} else {
- logger.debug ("No missing parameters found - ok to proceed");
+ logger.debug("No missing parameters found - ok to proceed");
}
// We can now remove the recreating of the ENV with only legit params - that check is done for us,
// and it causes problems with json that has arrays
String newEnvironmentString = null;
if (mhee != null) {
- newEnvironmentString = mhee.getRawEntry().toString();
+ newEnvironmentString = mhee.getRawEntry().toString();
}
// "Fix" the template if it has CR/LF (getting this from Oracle)
- String template = heatTemplate.getHeatTemplate ();
- template = template.replaceAll ("\r\n", "\n");
+ String template = heatTemplate.getHeatTemplate();
+ template = template.replaceAll("\r\n", "\n");
// Valet - 1806
boolean isValetEnabled = this.checkBooleanProperty(MsoVnfAdapterImpl.VALET_ENABLED, false);
- boolean failRequestOnValetFailure = this.checkBooleanProperty(MsoVnfAdapterImpl.FAIL_REQUESTS_ON_VALET_FAILURE, false);
+ boolean failRequestOnValetFailure =
+ this.checkBooleanProperty(MsoVnfAdapterImpl.FAIL_REQUESTS_ON_VALET_FAILURE, false);
logger.debug("isValetEnabled={}, failRequestsOnValetFailure={}", isValetEnabled, failRequestOnValetFailure);
if (oldWay || isVolumeRequest) {
- isValetEnabled = false;
+ isValetEnabled = false;
logger.debug("do not send to valet for volume requests or brocade");
}
boolean sendResponseToValet = false;
if (isValetEnabled) {
- Holder<Map<String, Object>> valetModifiedParamsHolder = new Holder<>();
- sendResponseToValet = this.valetCreateRequest(cloudSiteId, cloudOwner, tenantId, heatFilesObjects,
- nestedTemplatesChecked, vfModuleName, backout, heatTemplate, newEnvironmentString, goldenInputs,
- msoRequest, inputs, failRequestOnValetFailure, valetModifiedParamsHolder);
- if (sendResponseToValet) {
- goldenInputs = valetModifiedParamsHolder.value;
- }
+ Holder<Map<String, Object>> valetModifiedParamsHolder = new Holder<>();
+ sendResponseToValet = this.valetCreateRequest(cloudSiteId, cloudOwner, tenantId, heatFilesObjects,
+ nestedTemplatesChecked, vfModuleName, backout, heatTemplate, newEnvironmentString, goldenInputs,
+ msoRequest, inputs, failRequestOnValetFailure, valetModifiedParamsHolder);
+ if (sendResponseToValet) {
+ goldenInputs = valetModifiedParamsHolder.value;
+ }
}
// Have the tenant. Now deploy the stack itself
// Ignore MsoTenantNotFound and MsoStackAlreadyExists exceptions
// because we already checked for those.
- long createStackStarttime = System.currentTimeMillis ();
+ long createStackStarttime = System.currentTimeMillis();
try {
// heatStack = heat.createStack(cloudSiteId, tenantId, vnfName, template, inputs, true,
// heatTemplate.getTimeoutMinutes());
- if (backout == null) {
- backout = true;
- }
- if (heat != null) {
- logger.debug("heat is not null!!");
-
- heatStack = heat.createStack (cloudSiteId,
- cloudOwner,
- tenantId,
- vfModuleName,
- null,
- template,
- goldenInputs,
- true,
- heatTemplate.getTimeoutMinutes(),
- newEnvironmentString,
- nestedTemplatesChecked,
- heatFilesObjects,
- backout.booleanValue());
- }
- else {
- logger.debug("heat is null!");
- throw new MsoHeatNotFoundException();
- }
+ if (backout == null) {
+ backout = true;
+ }
+ if (heat != null) {
+ logger.debug("heat is not null!!");
+
+ heatStack = heat.createStack(cloudSiteId, cloudOwner, tenantId, vfModuleName, null, template,
+ goldenInputs, true, heatTemplate.getTimeoutMinutes(), newEnvironmentString,
+ nestedTemplatesChecked, heatFilesObjects, backout.booleanValue());
+ } else {
+ logger.debug("heat is null!");
+ throw new MsoHeatNotFoundException();
+ }
} catch (MsoException me) {
- me.addContext ("CreateVFModule");
- String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger
- .error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", ErrorCode.DataError.getValue(), "MsoException - createStack",
- me);
+ me.addContext("CreateVFModule");
+ String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/"
+ + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType,
+ cloudOwner, cloudSiteId, tenantId, "OpenStack", ErrorCode.DataError.getValue(),
+ "MsoException - createStack", me);
logger.debug(error);
if (isValetEnabled && sendResponseToValet) {
- logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet");
- try {
- GenericValetResponse<ValetRollbackResponse> gvr = this.vci.callValetRollbackRequest(msoRequest.getRequestId(), null, backout, me.getMessage());
- // Nothing to really do here whether it succeeded or not other than log it.
- logger.debug("Return code from Rollback response is {}", gvr.getStatusCode());
- } catch (Exception e) {
- logger.error("Exception encountered while sending Rollback to Valet ", e);
- }
+ logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet");
+ try {
+ GenericValetResponse<ValetRollbackResponse> gvr = this.vci
+ .callValetRollbackRequest(msoRequest.getRequestId(), null, backout, me.getMessage());
+ // Nothing to really do here whether it succeeded or not other than log it.
+ logger.debug("Return code from Rollback response is {}", gvr.getStatusCode());
+ } catch (Exception e) {
+ logger.error("Exception encountered while sending Rollback to Valet ", e);
+ }
}
- throw new VnfException (me);
+ throw new VnfException(me);
} catch (NullPointerException npe) {
- String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + npe;
- logger
- .error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", ErrorCode.DataError.getValue(),
+ String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/"
+ + tenantId + ": " + npe;
+ logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType,
+ cloudOwner, cloudSiteId, tenantId, "OpenStack", ErrorCode.DataError.getValue(),
"NullPointerException - createStack", npe);
logger.debug(error);
logger.debug("NULL POINTER EXCEPTION at heat.createStack");
- //npe.addContext ("CreateVNF");
- throw new VnfException ("NullPointerException during heat.createStack");
+ // npe.addContext ("CreateVNF");
+ throw new VnfException("NullPointerException during heat.createStack");
} catch (Exception e) {
- logger.debug("unhandled exception at heat.createStack",e);
- throw new VnfException("Exception during heat.createStack! " + e.getMessage());
+ logger.debug("unhandled exception at heat.createStack", e);
+ throw new VnfException("Exception during heat.createStack! " + e.getMessage());
}
// Reach this point if createStack is successful.
// Populate remaining rollback info and response parameters.
- vfRollback.setVnfId (heatStack.getCanonicalName ());
- vfRollback.setVnfCreated (true);
+ vfRollback.setVnfId(heatStack.getCanonicalName());
+ vfRollback.setVnfCreated(true);
- vnfId.value = heatStack.getCanonicalName ();
- outputs.value = copyStringOutputs (heatStack.getOutputs ());
+ vnfId.value = heatStack.getCanonicalName();
+ outputs.value = copyStringOutputs(heatStack.getOutputs());
rollback.value = vfRollback;
if (isValetEnabled && sendResponseToValet) {
- logger.debug("valet is enabled, the orchestration succeeded - now send confirm to valet with stack id");
- try {
- GenericValetResponse<ValetConfirmResponse> gvr = this.vci.callValetConfirmRequest(msoRequest.getRequestId(), heatStack.getCanonicalName());
+ logger.debug("valet is enabled, the orchestration succeeded - now send confirm to valet with stack id");
+ try {
+ GenericValetResponse<ValetConfirmResponse> gvr =
+ this.vci.callValetConfirmRequest(msoRequest.getRequestId(), heatStack.getCanonicalName());
// Nothing to really do here whether it succeeded or not other than log it.
logger.debug("Return code from Confirm response is {}", gvr.getStatusCode());
} catch (Exception e) {
logger.error("Exception encountered while sending Confirm to Valet ", e);
}
}
- logger.debug ("VF Module {} successfully created", vfModuleName);
- //call heatbridge
+ logger.debug("VF Module {} successfully created", vfModuleName);
+ // call heatbridge
heatbridge(heatStack, cloudOwner, cloudSiteId, tenantId, genericVnfName, vfModuleId);
return;
} catch (Exception e) {
- logger.debug("unhandled exception in create VF",e);
- throw new VnfException("Exception during create VF " + e.getMessage());
+ logger.debug("unhandled exception in create VF", e);
+ throw new VnfException("Exception during create VF " + e.getMessage());
}
}
@Override
- public void deleteVfModule (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfName,
- MsoRequest msoRequest,
- Holder <Map <String, String>> outputs) throws VnfException {
+ public void deleteVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfName,
+ MsoRequest msoRequest, Holder<Map<String, String>> outputs) throws VnfException {
logger.debug("Deleting VF {} in ", vnfName, cloudOwner + "/" + cloudSiteId + "/" + tenantId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
// 1702 capture the output parameters on a delete
// so we'll need to query first
@@ -1372,62 +1301,69 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
} catch (MsoException me) {
// Failed to query the Stack due to an openstack exception.
// Convert to a generic VnfException
- me.addContext ("DeleteVFModule");
- String error = "Delete VFModule: Query to get outputs: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), "Exception - QueryStack",
- me);
+ me.addContext("DeleteVFModule");
+ String error = "Delete VFModule: Query to get outputs: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId
+ + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner,
+ cloudSiteId, tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(),
+ "Exception - QueryStack", me);
logger.debug(error);
- throw new VnfException (me);
+ throw new VnfException(me);
}
- // call method which handles the conversion from Map<String,Object> to Map<String,String> for our expected Object types
+ // call method which handles the conversion from Map<String,Object> to Map<String,String> for our expected
+ // Object types
outputs.value = this.convertMapStringObjectToStringString(stackOutputs);
boolean isValetEnabled = this.checkBooleanProperty(MsoVnfAdapterImpl.VALET_ENABLED, false);
- boolean failRequestOnValetFailure = this.checkBooleanProperty(MsoVnfAdapterImpl.FAIL_REQUESTS_ON_VALET_FAILURE, false);
+ boolean failRequestOnValetFailure =
+ this.checkBooleanProperty(MsoVnfAdapterImpl.FAIL_REQUESTS_ON_VALET_FAILURE, false);
logger.debug("isValetEnabled={}, failRequestsOnValetFailure={}", isValetEnabled, failRequestOnValetFailure);
boolean valetDeleteRequestSucceeded = false;
if (isValetEnabled) {
- valetDeleteRequestSucceeded = this.valetDeleteRequest(cloudSiteId, cloudOwner, tenantId, vnfName, msoRequest, failRequestOnValetFailure);
+ valetDeleteRequestSucceeded = this.valetDeleteRequest(cloudSiteId, cloudOwner, tenantId, vnfName,
+ msoRequest, failRequestOnValetFailure);
}
// Use the MsoHeatUtils to delete the stack. Set the polling flag to true.
// The possible outcomes of deleteStack are a StackInfo object with status
// of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException
// could be thrown.
- long subStartTime = System.currentTimeMillis ();
+ long subStartTime = System.currentTimeMillis();
try {
- heat.deleteStack (tenantId, cloudOwner, cloudSiteId, vnfName, true);
+ heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true);
} catch (MsoException me) {
- me.addContext ("DeleteVNF");
+ me.addContext("DeleteVNF");
// Failed to query the Stack due to an openstack exception.
// Convert to a generic VnfException
- String error = "Delete VF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", "DeleteStack", ErrorCode.DataError.getValue(),
- "Exception - deleteStack", me);
+ String error =
+ "Delete VF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner,
+ cloudSiteId, tenantId, "OpenStack", "DeleteStack", ErrorCode.DataError.getValue(),
+ "Exception - deleteStack", me);
logger.debug(error);
if (isValetEnabled && valetDeleteRequestSucceeded) {
- logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet");
- try {
- GenericValetResponse<ValetRollbackResponse> gvr = this.vci.callValetRollbackRequest(msoRequest.getRequestId(), vnfName, false, me.getMessage());
- // Nothing to really do here whether it succeeded or not other than log it.
- logger.debug("Return code from Rollback response is {}", gvr.getStatusCode());
- } catch (Exception e) {
- logger.error("Exception encountered while sending Rollback to Valet ", e);
- }
+ logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet");
+ try {
+ GenericValetResponse<ValetRollbackResponse> gvr = this.vci
+ .callValetRollbackRequest(msoRequest.getRequestId(), vnfName, false, me.getMessage());
+ // Nothing to really do here whether it succeeded or not other than log it.
+ logger.debug("Return code from Rollback response is {}", gvr.getStatusCode());
+ } catch (Exception e) {
+ logger.error("Exception encountered while sending Rollback to Valet ", e);
+ }
}
- throw new VnfException (me);
+ throw new VnfException(me);
}
if (isValetEnabled && valetDeleteRequestSucceeded) {
- // only if the original request succeeded do we send a confirm
- logger.debug("valet is enabled, the delete succeeded - now send confirm to valet");
- try {
- GenericValetResponse<ValetConfirmResponse> gvr = this.vci.callValetConfirmRequest(msoRequest.getRequestId(), vnfName);
+ // only if the original request succeeded do we send a confirm
+ logger.debug("valet is enabled, the delete succeeded - now send confirm to valet");
+ try {
+ GenericValetResponse<ValetConfirmResponse> gvr =
+ this.vci.callValetConfirmRequest(msoRequest.getRequestId(), vnfName);
// Nothing to really do here whether it succeeded or not other than log it.
- logger.debug("Return code from Confirm response is {}", gvr.getStatusCode());
+ logger.debug("Return code from Confirm response is {}", gvr.getStatusCode());
} catch (Exception e) {
- logger.error("Exception encountered while sending Confirm to Valet ", e);
+ logger.error("Exception encountered while sending Confirm to Valet ", e);
}
}
@@ -1436,47 +1372,37 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
}
@Override
- public void updateVfModule (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfType,
- String vnfVersion,
- String vnfName,
- String requestType,
- String volumeGroupHeatStackId,
- String baseVfHeatStackId,
- String vfModuleStackId,
- String modelCustomizationUuid,
- Map <String, Object> inputs,
- MsoRequest msoRequest,
- Holder <Map <String, String>> outputs,
- Holder <VnfRollback> rollback) throws VnfException {
- String vfModuleName = vnfName;
- String vfModuleType = vnfType;
- String methodName = "updateVfModule";
- String serviceName = VNF_ADAPTER_SERVICE_NAME + methodName;
-
- StringBuilder sbInit = new StringBuilder();
- sbInit.append("updateVfModule: \n");
- sbInit.append("cloudOwner=" + cloudOwner + "\n");
+ public void updateVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfType,
+ String vnfVersion, String vnfName, String requestType, String volumeGroupHeatStackId,
+ String baseVfHeatStackId, String vfModuleStackId, String modelCustomizationUuid, Map<String, Object> inputs,
+ MsoRequest msoRequest, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback)
+ throws VnfException {
+ String vfModuleName = vnfName;
+ String vfModuleType = vnfType;
+ String methodName = "updateVfModule";
+ String serviceName = VNF_ADAPTER_SERVICE_NAME + methodName;
+
+ StringBuilder sbInit = new StringBuilder();
+ sbInit.append("updateVfModule: \n");
+ sbInit.append("cloudOwner=" + cloudOwner + "\n");
sbInit.append("cloudSiteId=" + cloudSiteId + "\n");
- sbInit.append("tenantId=" + tenantId + "\n");
- sbInit.append("vnfType=" + vnfType + "\n");
- sbInit.append("vnfVersion=" + vnfVersion + "\n");
- sbInit.append("vnfName=" + vnfName + "\n");
- sbInit.append("requestType=" + requestType + "\n");
- sbInit.append("volumeGroupHeatStackId=" + volumeGroupHeatStackId + "\n");
- sbInit.append("baseVfHeatStackId=" + baseVfHeatStackId + "\n");
- sbInit.append("vfModuleStackId=" + vfModuleStackId + "\n");
- sbInit.append("modelCustomizationUuid=" + modelCustomizationUuid + "\n");
- logger.debug(sbInit.toString());
+ sbInit.append("tenantId=" + tenantId + "\n");
+ sbInit.append("vnfType=" + vnfType + "\n");
+ sbInit.append("vnfVersion=" + vnfVersion + "\n");
+ sbInit.append("vnfName=" + vnfName + "\n");
+ sbInit.append("requestType=" + requestType + "\n");
+ sbInit.append("volumeGroupHeatStackId=" + volumeGroupHeatStackId + "\n");
+ sbInit.append("baseVfHeatStackId=" + baseVfHeatStackId + "\n");
+ sbInit.append("vfModuleStackId=" + vfModuleStackId + "\n");
+ sbInit.append("modelCustomizationUuid=" + modelCustomizationUuid + "\n");
+ logger.debug(sbInit.toString());
String mcu = modelCustomizationUuid;
boolean useMCUuid = false;
if (mcu != null && !mcu.isEmpty()) {
if ("null".equalsIgnoreCase(mcu)) {
logger.debug("modelCustomizationUuid: passed in as the string 'null' - will ignore: {}",
- modelCustomizationUuid);
+ modelCustomizationUuid);
useMCUuid = false;
mcu = "";
} else {
@@ -1485,47 +1411,50 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
}
}
- String requestTypeString = "";
+ String requestTypeString = "";
if (requestType != null && !"".equals(requestType)) {
- requestTypeString = requestType;
+ requestTypeString = requestType;
}
String nestedStackId = null;
- if (volumeGroupHeatStackId != null && !"".equals(volumeGroupHeatStackId) && !"null".equalsIgnoreCase(volumeGroupHeatStackId)) {
- nestedStackId = volumeGroupHeatStackId;
+ if (volumeGroupHeatStackId != null && !"".equals(volumeGroupHeatStackId)
+ && !"null".equalsIgnoreCase(volumeGroupHeatStackId)) {
+ nestedStackId = volumeGroupHeatStackId;
}
String nestedBaseStackId = null;
if (baseVfHeatStackId != null && !"".equals(baseVfHeatStackId) && !"null".equalsIgnoreCase(baseVfHeatStackId)) {
- nestedBaseStackId = baseVfHeatStackId;
+ nestedBaseStackId = baseVfHeatStackId;
}
if (inputs == null) {
- // Create an empty set of inputs
- inputs = new HashMap<>();
+ // Create an empty set of inputs
+ inputs = new HashMap<>();
logger.debug("inputs == null - setting to empty");
}
boolean isBaseRequest = false;
boolean isVolumeRequest = false;
if (requestTypeString.startsWith("VOLUME")) {
- isVolumeRequest = true;
+ isVolumeRequest = true;
}
if ((vfModuleName == null || "".equals(vfModuleName.trim())) && vfModuleStackId != null) {
- vfModuleName = this.getVfModuleNameFromModuleStackId(vfModuleStackId);
+ vfModuleName = this.getVfModuleNameFromModuleStackId(vfModuleStackId);
}
- logger.debug ("Updating VFModule: " + vfModuleName + " of type " + vfModuleType + "in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId);
- logger.debug("requestTypeString = " + requestTypeString + ", nestedVolumeStackId = " + nestedStackId + ", nestedBaseStackId = " + nestedBaseStackId);
+ logger.debug("Updating VFModule: " + vfModuleName + " of type " + vfModuleType + "in " + cloudOwner + "/"
+ + cloudSiteId + "/" + tenantId);
+ logger.debug("requestTypeString = " + requestTypeString + ", nestedVolumeStackId = " + nestedStackId
+ + ", nestedBaseStackId = " + nestedBaseStackId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
// Build a default rollback object (no actions performed)
- VnfRollback vfRollback = new VnfRollback ();
- vfRollback.setCloudSiteId (cloudSiteId);
- vfRollback.setCloudOwner (cloudOwner);
- vfRollback.setTenantId (tenantId);
- vfRollback.setMsoRequest (msoRequest);
+ VnfRollback vfRollback = new VnfRollback();
+ vfRollback.setCloudSiteId(cloudSiteId);
+ vfRollback.setCloudOwner(cloudOwner);
+ vfRollback.setTenantId(tenantId);
+ vfRollback.setMsoRequest(msoRequest);
vfRollback.setRequestType(requestTypeString);
vfRollback.setVolumeGroupHeatStackId(volumeGroupHeatStackId);
vfRollback.setBaseGroupHeatStackId(baseVfHeatStackId);
@@ -1534,575 +1463,569 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
vfRollback.setModelCustomizationUuid(mcu);
StackInfo heatStack = null;
- long queryStackStarttime = System.currentTimeMillis ();
+ long queryStackStarttime = System.currentTimeMillis();
logger.debug("UpdateVfModule - querying for {}", vfModuleName);
try {
- heatStack = heat.queryStack (cloudSiteId, cloudOwner, tenantId, vfModuleName);
+ heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vfModuleName);
} catch (MsoException me) {
// Failed to query the Stack due to an openstack exception.
// Convert to a generic VnfException
- me.addContext ("UpdateVFModule");
- String error = "Update VFModule: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), "Exception - QueryStack",
- me);
+ me.addContext("UpdateVFModule");
+ String error = "Update VFModule: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/"
+ + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(),
+ "Exception - QueryStack", me);
logger.debug(error);
- throw new VnfException (me);
+ throw new VnfException(me);
}
- //TODO - do we need to check for the other status possibilities?
- if (heatStack == null || heatStack.getStatus () == HeatStatus.NOTFOUND) {
+ // TODO - do we need to check for the other status possibilities?
+ if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
// Not Found
- String error = "Update VF: Stack " + vfModuleName + " does not exist in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_NOT_EXIST.toString(), vfModuleName, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), error);
- throw new VnfNotFound (cloudSiteId, cloudOwner, tenantId, vfModuleName);
+ String error = "Update VF: Stack " + vfModuleName + " does not exist in " + cloudOwner + "/" + cloudSiteId
+ + "/" + tenantId;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_NOT_EXIST.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(),
+ error);
+ throw new VnfNotFound(cloudSiteId, cloudOwner, tenantId, vfModuleName);
} else {
logger.debug("Found Existing stack, status={}", heatStack.getStatus());
// Populate the outputs from the existing stack.
- outputs.value = copyStringOutputs (heatStack.getOutputs ());
+ outputs.value = copyStringOutputs(heatStack.getOutputs());
rollback.value = vfRollback; // Default rollback - no updates performed
}
// 1604 Cinder Volume support - handle a nestedStackId if sent (volumeGroupHeatStackId):
StackInfo nestedHeatStack = null;
- long queryStackStarttime2 = System.currentTimeMillis ();
+ long queryStackStarttime2 = System.currentTimeMillis();
Map<String, Object> nestedVolumeOutputs = null;
if (nestedStackId != null) {
- try {
- logger.debug("Querying for nestedStackId = {}", nestedStackId);
- nestedHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedStackId);
- } catch (MsoException me) {
- // Failed to query the Stack due to an openstack exception.
- // Convert to a generic VnfException
- me.addContext ("UpdateVFModule");
- String error = "Update VF: Attached heatStack ID Query " + nestedStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), "Exception - " + error,
- me);
- logger.debug("ERROR trying to query nested stack= {}", error);
- throw new VnfException (me);
- }
- if (nestedHeatStack == null || nestedHeatStack.getStatus() == HeatStatus.NOTFOUND) {
- String error = "Update VFModule: Attached volume heatStack ID DOES NOT EXIST " + nestedStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR" ;
- logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId,
- tenantId, error, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), error);
- logger.debug(error);
- throw new VnfException (error, MsoExceptionCategory.USERDATA);
- } else {
- logger.debug("Found nested heat stack - copying values to inputs *later*");
- nestedVolumeOutputs = nestedHeatStack.getOutputs();
- heat.copyStringOutputsToInputs(inputs, nestedHeatStack.getOutputs(), false);
- }
+ try {
+ logger.debug("Querying for nestedStackId = {}", nestedStackId);
+ nestedHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedStackId);
+ } catch (MsoException me) {
+ // Failed to query the Stack due to an openstack exception.
+ // Convert to a generic VnfException
+ me.addContext("UpdateVFModule");
+ String error = "Update VF: Attached heatStack ID Query " + nestedStackId + " in " + cloudOwner + "/"
+ + cloudSiteId + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner,
+ cloudSiteId, tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(),
+ "Exception - " + error, me);
+ logger.debug("ERROR trying to query nested stack= {}", error);
+ throw new VnfException(me);
+ }
+ if (nestedHeatStack == null || nestedHeatStack.getStatus() == HeatStatus.NOTFOUND) {
+ String error = "Update VFModule: Attached volume heatStack ID DOES NOT EXIST " + nestedStackId + " in "
+ + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR";
+ logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName,
+ cloudOwner, cloudSiteId, tenantId, error, "OpenStack", "QueryStack",
+ ErrorCode.DataError.getValue(), error);
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ } else {
+ logger.debug("Found nested heat stack - copying values to inputs *later*");
+ nestedVolumeOutputs = nestedHeatStack.getOutputs();
+ heat.copyStringOutputsToInputs(inputs, nestedHeatStack.getOutputs(), false);
+ }
}
// handle a nestedBaseStackId if sent - this is the stack ID of the base.
StackInfo nestedBaseHeatStack = null;
Map<String, Object> baseStackOutputs = null;
if (nestedBaseStackId != null) {
- long queryStackStarttime3 = System.currentTimeMillis ();
- try {
- logger.debug("Querying for nestedBaseStackId = {}", nestedBaseStackId);
- nestedBaseHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId);
- } catch (MsoException me) {
- // Failed to query the Stack due to an openstack exception.
- // Convert to a generic VnfException
- me.addContext ("UpdateVfModule");
- String error = "Update VFModule: Attached baseHeatStack ID Query " + nestedBaseStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ;
- logger
- .error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(),
- "Exception - " + error, me);
- logger.debug("ERROR trying to query nested base stack= {}", error);
- throw new VnfException (me);
- }
- if (nestedBaseHeatStack == null || nestedBaseHeatStack.getStatus() == HeatStatus.NOTFOUND) {
- String error = "Update VFModule: Attached base heatStack ID DOES NOT EXIST " + nestedBaseStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR" ;
- logger.error ("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, error, "OpenStack",
- "QueryStack", ErrorCode.DataError.getValue(), error);
- logger.debug(error);
- throw new VnfException (error, MsoExceptionCategory.USERDATA);
- } else {
- logger.debug("Found nested base heat stack - copying values to inputs *later*");
- baseStackOutputs = nestedBaseHeatStack.getOutputs();
- heat.copyStringOutputsToInputs(inputs, nestedBaseHeatStack.getOutputs(), false);
- }
+ long queryStackStarttime3 = System.currentTimeMillis();
+ try {
+ logger.debug("Querying for nestedBaseStackId = {}", nestedBaseStackId);
+ nestedBaseHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId);
+ } catch (MsoException me) {
+ // Failed to query the Stack due to an openstack exception.
+ // Convert to a generic VnfException
+ me.addContext("UpdateVfModule");
+ String error = "Update VFModule: Attached baseHeatStack ID Query " + nestedBaseStackId + " in "
+ + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(),
+ "Exception - " + error, me);
+ logger.debug("ERROR trying to query nested base stack= {}", error);
+ throw new VnfException(me);
+ }
+ if (nestedBaseHeatStack == null || nestedBaseHeatStack.getStatus() == HeatStatus.NOTFOUND) {
+ String error = "Update VFModule: Attached base heatStack ID DOES NOT EXIST " + nestedBaseStackId
+ + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR";
+ logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, error, "OpenStack", "QueryStack",
+ ErrorCode.DataError.getValue(), error);
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ } else {
+ logger.debug("Found nested base heat stack - copying values to inputs *later*");
+ baseStackOutputs = nestedBaseHeatStack.getOutputs();
+ heat.copyStringOutputsToInputs(inputs, nestedBaseHeatStack.getOutputs(), false);
+ }
}
// Ready to deploy the new VNF
- // Retrieve the VF definition
- VnfResource vnfResource = null;
- VfModule vf = null;
- VfModuleCustomization vfmc = null;
- if (useMCUuid){
- vfmc = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(modelCustomizationUuid);
- vf = vfmc != null ? vfmc.getVfModule() : null;
- if (vf == null) {
- logger.debug("Unable to find a vfModule matching modelCustomizationUuid={}", mcu);
- }
- } else {
- logger.debug("1707 and later - MUST PROVIDE Model Customization UUID!");
- }
- if (vf == null) {
- String error = "Update VfModule: unable to find vfModule with modelCustomizationUuid=" + mcu;
- logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module Type",
- vfModuleType, "OpenStack", ErrorCode.DataError.getValue(), error);
- throw new VnfException(error, MsoExceptionCategory.USERDATA);
- }
- logger.debug("Got VF module definition from Catalog: {}", vf.toString());
- if (vf.getIsBase()) {
- isBaseRequest = true;
- logger.debug("This a BASE update request");
- } else {
- logger.debug("This is *not* a BASE VF update request");
- if (!isVolumeRequest && nestedBaseStackId == null) {
- logger.debug("DANGER WILL ROBINSON! This is unexpected - no nestedBaseStackId with this non-base request");
- }
+ // Retrieve the VF definition
+ VnfResource vnfResource = null;
+ VfModule vf = null;
+ VfModuleCustomization vfmc = null;
+ if (useMCUuid) {
+ vfmc = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(modelCustomizationUuid);
+ vf = vfmc != null ? vfmc.getVfModule() : null;
+ if (vf == null) {
+ logger.debug("Unable to find a vfModule matching modelCustomizationUuid={}", mcu);
+ }
+ } else {
+ logger.debug("1707 and later - MUST PROVIDE Model Customization UUID!");
+ }
+ if (vf == null) {
+ String error = "Update VfModule: unable to find vfModule with modelCustomizationUuid=" + mcu;
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module Type",
+ vfModuleType, "OpenStack", ErrorCode.DataError.getValue(), error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ }
+ logger.debug("Got VF module definition from Catalog: {}", vf.toString());
+ if (vf.getIsBase()) {
+ isBaseRequest = true;
+ logger.debug("This a BASE update request");
+ } else {
+ logger.debug("This is *not* a BASE VF update request");
+ if (!isVolumeRequest && nestedBaseStackId == null) {
+ logger.debug(
+ "DANGER WILL ROBINSON! This is unexpected - no nestedBaseStackId with this non-base request");
}
+ }
- //1607 - Add version check
- // First - see if it's in the VnfResource record
- // if we have a vf Module - then we have to query to get the VnfResource record.
- if (vf.getModelUUID() != null) {
- String vnfResourceModelUuid = vf.getModelUUID();
+ // 1607 - Add version check
+ // First - see if it's in the VnfResource record
+ // if we have a vf Module - then we have to query to get the VnfResource record.
+ if (vf.getModelUUID() != null) {
+ String vnfResourceModelUuid = vf.getModelUUID();
- vnfResource = vf.getVnfResources();
- if (vnfResource == null) {
- logger.debug("Unable to find vnfResource at ? will not error for now...", vnfResourceModelUuid);
- }
+ vnfResource = vf.getVnfResources();
+ if (vnfResource == null) {
+ logger.debug("Unable to find vnfResource at ? will not error for now...", vnfResourceModelUuid);
}
+ }
- String minVersionVnf = null;
- String maxVersionVnf = null;
- if (vnfResource != null) {
- try {
- minVersionVnf = vnfResource.getAicVersionMin();
- maxVersionVnf = vnfResource.getAicVersionMax();
- } catch (Exception e) {
- logger.debug("Unable to pull min/max version for this VNF Resource entry",e);
- minVersionVnf = null;
- maxVersionVnf = null;
- }
- if (minVersionVnf != null && "".equals(minVersionVnf)) {
- minVersionVnf = null;
- }
- if (maxVersionVnf != null && "".equals(maxVersionVnf)) {
- maxVersionVnf = null;
- }
- }
- if (minVersionVnf != null && maxVersionVnf != null) {
- MavenLikeVersioning aicV = new MavenLikeVersioning();
-
- // double check
- if (this.cloudConfig != null) {
- Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId);
- if (cloudSiteOpt.isPresent()) {
- aicV.setVersion(cloudSiteOpt.get().getCloudVersion());
- boolean moreThanMin = true;
- boolean equalToMin = true;
- boolean moreThanMax = true;
- boolean equalToMax = true;
- boolean doNotTest = false;
- try {
- moreThanMin = aicV.isMoreRecentThan(minVersionVnf);
- equalToMin = aicV.isTheSameVersion(minVersionVnf);
- moreThanMax = aicV.isMoreRecentThan(maxVersionVnf);
- equalToMax = aicV.isTheSameVersion(maxVersionVnf);
- } catch (Exception e) {
- logger.debug("An exception occured while trying to test AIC Version {} - will default to not check",
- e.getMessage(), e);
- doNotTest = true;
- }
- if (!doNotTest) {
- if ((moreThanMin || equalToMin) // aic >= min
- && ((equalToMax) || !(moreThanMax))) { // aic <= max
- logger.debug(
- "VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:"
- + maxVersionVnf + " supported on Cloud: " + cloudSiteId + " with AIC_Version:" + aicV);
+ String minVersionVnf = null;
+ String maxVersionVnf = null;
+ if (vnfResource != null) {
+ try {
+ minVersionVnf = vnfResource.getAicVersionMin();
+ maxVersionVnf = vnfResource.getAicVersionMax();
+ } catch (Exception e) {
+ logger.debug("Unable to pull min/max version for this VNF Resource entry", e);
+ minVersionVnf = null;
+ maxVersionVnf = null;
+ }
+ if (minVersionVnf != null && "".equals(minVersionVnf)) {
+ minVersionVnf = null;
+ }
+ if (maxVersionVnf != null && "".equals(maxVersionVnf)) {
+ maxVersionVnf = null;
+ }
+ }
+ if (minVersionVnf != null && maxVersionVnf != null) {
+ MavenLikeVersioning aicV = new MavenLikeVersioning();
+
+ // double check
+ if (this.cloudConfig != null) {
+ Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId);
+ if (cloudSiteOpt.isPresent()) {
+ aicV.setVersion(cloudSiteOpt.get().getCloudVersion());
+ boolean moreThanMin = true;
+ boolean equalToMin = true;
+ boolean moreThanMax = true;
+ boolean equalToMax = true;
+ boolean doNotTest = false;
+ try {
+ moreThanMin = aicV.isMoreRecentThan(minVersionVnf);
+ equalToMin = aicV.isTheSameVersion(minVersionVnf);
+ moreThanMax = aicV.isMoreRecentThan(maxVersionVnf);
+ equalToMax = aicV.isTheSameVersion(maxVersionVnf);
+ } catch (Exception e) {
+ logger.debug(
+ "An exception occured while trying to test AIC Version {} - will default to not check",
+ e.getMessage(), e);
+ doNotTest = true;
+ }
+ if (!doNotTest) {
+ if ((moreThanMin || equalToMin) // aic >= min
+ && ((equalToMax) || !(moreThanMax))) { // aic <= max
+ logger.debug("VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf
+ + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSiteId
+ + " with AIC_Version:" + aicV);
+ } else {
+ // ERROR
+ String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin="
+ + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: "
+ + cloudSiteId + " with AIC_Version:" + aicV;
+ logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion");
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ }
+ } else {
+ logger.debug("bypassing testing AIC version...");
+ }
+ } // let this error out downstream to avoid introducing uncertainty at this stage
} else {
- // ERROR
- String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin="
- + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: "
- + cloudSiteId + " with AIC_Version:" + aicV;
- logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack",
- ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion");
- logger.debug(error);
- throw new VnfException(error, MsoExceptionCategory.USERDATA);
- }
- } else {
- logger.debug("bypassing testing AIC version...");
- }
- } // let this error out downstream to avoid introducing uncertainty at this stage
- } else {
- logger.debug("cloudConfig is NULL - cannot check cloud site version");
- }
-
- } else {
- logger.debug("AIC Version not set in VNF_Resource - do not error for now - not checked.");
+ logger.debug("cloudConfig is NULL - cannot check cloud site version");
}
- // End Version check 1607
- HeatTemplate heatTemplate = null;
- HeatEnvironment heatEnvironment = null;
- if (isVolumeRequest) {
- heatTemplate = vf.getVolumeHeatTemplate();
- heatEnvironment = vfmc.getVolumeHeatEnv();
- } else {
- heatTemplate = vf.getModuleHeatTemplate();
- heatEnvironment = vfmc.getHeatEnvironment();
- }
-
- if (heatTemplate == null) {
- String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + ", reqType=" + requestTypeString;
- logger
- .error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", vfModuleType,
- "OpenStack", ErrorCode.DataError.getValue(), error);
- throw new VnfException(error, MsoExceptionCategory.INTERNAL);
- } else {
- logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate());
- }
-
- if (heatEnvironment == null) {
- String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType;
- logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID",
+ } else {
+ logger.debug("AIC Version not set in VNF_Resource - do not error for now - not checked.");
+ }
+ // End Version check 1607
+
+ HeatTemplate heatTemplate = null;
+ HeatEnvironment heatEnvironment = null;
+ if (isVolumeRequest) {
+ heatTemplate = vf.getVolumeHeatTemplate();
+ heatEnvironment = vfmc.getVolumeHeatEnv();
+ } else {
+ heatTemplate = vf.getModuleHeatTemplate();
+ heatEnvironment = vfmc.getHeatEnvironment();
+ }
+
+ if (heatTemplate == null) {
+ String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType
+ + ", reqType=" + requestTypeString;
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID",
+ vfModuleType, "OpenStack", ErrorCode.DataError.getValue(), error);
+ throw new VnfException(error, MsoExceptionCategory.INTERNAL);
+ } else {
+ logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate());
+ }
+
+ if (heatEnvironment == null) {
+ String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType;
+ logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID",
"OpenStack", ErrorCode.DataError.getValue(), error);
- throw new VnfException (error, MsoExceptionCategory.INTERNAL);
- } else {
- logger.debug ("Got Heat Environment from DB: {}", heatEnvironment.getEnvironment());
- }
+ throw new VnfException(error, MsoExceptionCategory.INTERNAL);
+ } else {
+ logger.debug("Got Heat Environment from DB: {}", heatEnvironment.getEnvironment());
+ }
logger.debug("In MsoVnfAdapterImpl, about to call db.getNestedTemplates avec templateId={}",
- heatTemplate.getArtifactUuid());
+ heatTemplate.getArtifactUuid());
- List<HeatTemplate> nestedTemplates = heatTemplate.getChildTemplates();
- Map <String, Object> nestedTemplatesChecked = new HashMap <> ();
- if (nestedTemplates != null && !nestedTemplates.isEmpty()) {
- // for debugging print them out
- logger.debug("Contents of nestedTemplates - to be added to files: on stack:");
- for (HeatTemplate entry : nestedTemplates) {
+ List<HeatTemplate> nestedTemplates = heatTemplate.getChildTemplates();
+ Map<String, Object> nestedTemplatesChecked = new HashMap<>();
+ if (nestedTemplates != null && !nestedTemplates.isEmpty()) {
+ // for debugging print them out
+ logger.debug("Contents of nestedTemplates - to be added to files: on stack:");
+ for (HeatTemplate entry : nestedTemplates) {
- nestedTemplatesChecked.put (entry.getTemplateName(), entry.getTemplateBody());
- logger.debug(entry.getTemplateName() + " -> " + entry.getTemplateBody());
- }
- } else {
- logger.debug("No nested templates found - nothing to do here");
- nestedTemplatesChecked = null;
+ nestedTemplatesChecked.put(entry.getTemplateName(), entry.getTemplateBody());
+ logger.debug(entry.getTemplateName() + " -> " + entry.getTemplateBody());
}
+ } else {
+ logger.debug("No nested templates found - nothing to do here");
+ nestedTemplatesChecked = null;
+ }
- // Also add the files: for any get_files associated with this VfModule
- // *if* there are any
- logger.debug("In MsoVnfAdapterImpl.updateVfModule, about to call db.getHeatFiles avec vfModuleId={}",
- vf.getModelUUID());
+ // Also add the files: for any get_files associated with this VfModule
+ // *if* there are any
+ logger.debug("In MsoVnfAdapterImpl.updateVfModule, about to call db.getHeatFiles avec vfModuleId={}",
+ vf.getModelUUID());
- List<HeatFiles> heatFiles = null;
- Map <String, Object> heatFilesObjects = new HashMap <> ();
+ List<HeatFiles> heatFiles = null;
+ Map<String, Object> heatFilesObjects = new HashMap<>();
- // Add ability to turn on adding get_files with volume requests (by property).
- boolean addGetFilesOnVolumeReq = false;
- try {
- String propertyString = this.environment.getProperty(MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ);
- if ("true".equalsIgnoreCase(propertyString) || "y".equalsIgnoreCase(propertyString)) {
- addGetFilesOnVolumeReq = true;
- logger.debug("AddGetFilesOnVolumeReq - setting to true! {}", propertyString);
- }
- } catch (Exception e) {
- logger.debug("An error occured trying to get property {} - default to false",
- MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ, e);
+ // Add ability to turn on adding get_files with volume requests (by property).
+ boolean addGetFilesOnVolumeReq = false;
+ try {
+ String propertyString = this.environment.getProperty(MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ);
+ if ("true".equalsIgnoreCase(propertyString) || "y".equalsIgnoreCase(propertyString)) {
+ addGetFilesOnVolumeReq = true;
+ logger.debug("AddGetFilesOnVolumeReq - setting to true! {}", propertyString);
}
- if (!isVolumeRequest || addGetFilesOnVolumeReq) {
+ } catch (Exception e) {
+ logger.debug("An error occured trying to get property {} - default to false",
+ MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ, e);
+ }
+ if (!isVolumeRequest || addGetFilesOnVolumeReq) {
logger.debug("In MsoVnfAdapterImpl updateVfModule, about to call db.getHeatFilesForVfModule avec "
- + "vfModuleId={}", vf.getModelUUID());
-
- heatFiles = vf.getHeatFiles();
- if (heatFiles != null && !heatFiles.isEmpty()) {
- // add these to stack - to be done in createStack
- // here, we will map them to Map<String, Object> from Map<String, HeatFiles>
- // this will match the nested templates format
- logger.debug("Contents of heatFiles - to be added to files: on stack:");
- for (HeatFiles heatfile : heatFiles) {
- logger.debug(heatfile.getFileName() + " -> " + heatfile.getFileBody());
- heatFilesObjects.put(heatfile.getFileName(), heatfile.getFileBody());
- }
- } else {
- logger.debug("No heat files found -nothing to do here");
- heatFilesObjects = null;
+ + "vfModuleId={}", vf.getModelUUID());
+
+ heatFiles = vf.getHeatFiles();
+ if (heatFiles != null && !heatFiles.isEmpty()) {
+ // add these to stack - to be done in createStack
+ // here, we will map them to Map<String, Object> from Map<String, HeatFiles>
+ // this will match the nested templates format
+ logger.debug("Contents of heatFiles - to be added to files: on stack:");
+ for (HeatFiles heatfile : heatFiles) {
+ logger.debug(heatfile.getFileName() + " -> " + heatfile.getFileBody());
+ heatFilesObjects.put(heatfile.getFileName(), heatfile.getFileBody());
}
+ } else {
+ logger.debug("No heat files found -nothing to do here");
+ heatFilesObjects = null;
}
+ }
- // Check that required parameters have been supplied
- String missingParams = null;
- List <String> paramList = new ArrayList <> ();
+ // Check that required parameters have been supplied
+ String missingParams = null;
+ List<String> paramList = new ArrayList<>();
- // New for 1510 - consult the PARAM_ALIAS field to see if we've been
- // supplied an alias. Only check if we don't find it initially.
- // Also new in 1510 - don't flag missing parameters if there's an environment - because they might be there.
- // And also new - add parameter to turn off checking all together if we find we're blocking orders we
- // shouldn't
- boolean checkRequiredParameters = true;
- try {
- String propertyString = this.environment.getProperty (MsoVnfAdapterImpl.CHECK_REQD_PARAMS);
- if ("false".equalsIgnoreCase (propertyString) || "n".equalsIgnoreCase (propertyString)) {
- checkRequiredParameters = false;
- logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking...",
+ // New for 1510 - consult the PARAM_ALIAS field to see if we've been
+ // supplied an alias. Only check if we don't find it initially.
+ // Also new in 1510 - don't flag missing parameters if there's an environment - because they might be there.
+ // And also new - add parameter to turn off checking all together if we find we're blocking orders we
+ // shouldn't
+ boolean checkRequiredParameters = true;
+ try {
+ String propertyString = this.environment.getProperty(MsoVnfAdapterImpl.CHECK_REQD_PARAMS);
+ if ("false".equalsIgnoreCase(propertyString) || "n".equalsIgnoreCase(propertyString)) {
+ checkRequiredParameters = false;
+ logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking...",
MsoVnfAdapterImpl.CHECK_REQD_PARAMS);
- }
- } catch (Exception e) {
- // No problem - default is true
- logger.debug ("An exception occured trying to get property {}", MsoVnfAdapterImpl.CHECK_REQD_PARAMS,
- e);
}
- // 1604 - Add enhanced environment & parameter checking
- // Part 1: parse envt entries to see if reqd parameter is there (before used a simple grep
- // Part 2: only submit to openstack the parameters in the envt that are in the heat template
- // Note this also removes any comments
- MsoHeatEnvironmentEntry mhee = null;
- if (heatEnvironment != null && heatEnvironment.getEnvironment().toLowerCase ().contains ("parameters:")) {
- logger.debug("Enhanced environment checking enabled - 1604");
- StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment());
- mhee = new MsoHeatEnvironmentEntry(sb);
- StringBuilder sb2 = new StringBuilder("\nHeat Template Parameters:\n");
- for (HeatTemplateParam parm : heatTemplate.getParameters()) {
- sb2.append("\t" + parm.getParamName() + ", required=" + parm.isRequired());
- }
- if (!mhee.isValid()) {
- sb2.append("Environment says it's not valid! " + mhee.getErrorString());
- } else {
- sb2.append("\nEnvironment:");
- sb2.append(mhee.toFullString());
- }
- logger.debug(sb2.toString());
+ } catch (Exception e) {
+ // No problem - default is true
+ logger.debug("An exception occured trying to get property {}", MsoVnfAdapterImpl.CHECK_REQD_PARAMS, e);
+ }
+ // 1604 - Add enhanced environment & parameter checking
+ // Part 1: parse envt entries to see if reqd parameter is there (before used a simple grep
+ // Part 2: only submit to openstack the parameters in the envt that are in the heat template
+ // Note this also removes any comments
+ MsoHeatEnvironmentEntry mhee = null;
+ if (heatEnvironment != null && heatEnvironment.getEnvironment().toLowerCase().contains("parameters:")) {
+ logger.debug("Enhanced environment checking enabled - 1604");
+ StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment());
+ mhee = new MsoHeatEnvironmentEntry(sb);
+ StringBuilder sb2 = new StringBuilder("\nHeat Template Parameters:\n");
+ for (HeatTemplateParam parm : heatTemplate.getParameters()) {
+ sb2.append("\t" + parm.getParamName() + ", required=" + parm.isRequired());
+ }
+ if (!mhee.isValid()) {
+ sb2.append("Environment says it's not valid! " + mhee.getErrorString());
} else {
- logger.debug("NO ENVIRONMENT for this entry");
- }
- // New for 1607 - support params of json type
- HashMap<String, JsonNode> jsonParams = new HashMap<>();
- boolean hasJson = false;
-
- for (HeatTemplateParam parm : heatTemplate.getParameters ()) {
- logger.debug ("Parameter:'" + parm.getParamName ()
- + "', isRequired="
- + parm.isRequired ()
- + ", alias="
- + parm.getParamAlias ());
- // handle json
- String parameterType = parm.getParamType();
- if (parameterType == null || "".equals(parameterType.trim())) {
- parameterType = "String";
- }
- JsonNode jsonNode = null;
- if ("json".equalsIgnoreCase(parameterType) && inputs != null) {
- if (inputs.containsKey(parm.getParamName()) ) {
- hasJson = true;
- String jsonString = null;
- try {
- jsonString = JSON_MAPPER.writeValueAsString(inputs.get(parm.getParamName()));
- jsonNode = JSON_MAPPER.readTree(jsonString);
- } catch (JsonParseException jpe) {
- //TODO - what to do here?
- //for now - send the error to debug
- logger.debug("Json Error Converting {} - {}", parm.getParamName(), jpe.getMessage(), jpe);
- hasJson = false;
- jsonNode = null;
- } catch (Exception e) {
+ sb2.append("\nEnvironment:");
+ sb2.append(mhee.toFullString());
+ }
+ logger.debug(sb2.toString());
+ } else {
+ logger.debug("NO ENVIRONMENT for this entry");
+ }
+ // New for 1607 - support params of json type
+ HashMap<String, JsonNode> jsonParams = new HashMap<>();
+ boolean hasJson = false;
+
+ for (HeatTemplateParam parm : heatTemplate.getParameters()) {
+ logger.debug("Parameter:'" + parm.getParamName() + "', isRequired=" + parm.isRequired() + ", alias="
+ + parm.getParamAlias());
+ // handle json
+ String parameterType = parm.getParamType();
+ if (parameterType == null || "".equals(parameterType.trim())) {
+ parameterType = "String";
+ }
+ JsonNode jsonNode = null;
+ if ("json".equalsIgnoreCase(parameterType) && inputs != null) {
+ if (inputs.containsKey(parm.getParamName())) {
+ hasJson = true;
+ String jsonString = null;
+ try {
+ jsonString = JSON_MAPPER.writeValueAsString(inputs.get(parm.getParamName()));
+ jsonNode = JSON_MAPPER.readTree(jsonString);
+ } catch (JsonParseException jpe) {
+ // TODO - what to do here?
+ // for now - send the error to debug
+ logger.debug("Json Error Converting {} - {}", parm.getParamName(), jpe.getMessage(), jpe);
+ hasJson = false;
+ jsonNode = null;
+ } catch (Exception e) {
// or here?
logger.debug("Json Error Converting {} {}", parm.getParamName(), e.getMessage(), e);
hasJson = false;
jsonNode = null;
}
- if (jsonNode != null) {
- jsonParams.put(parm.getParamName(), jsonNode);
- }
- } else if (inputs.containsKey(parm.getParamAlias())) {
- hasJson = true;
- String jsonString = null;
- try {
- jsonString = (String)inputs.get(parm.getParamAlias());
- jsonNode = JSON_MAPPER.readTree(jsonString);
- } catch (JsonParseException jpe) {
- //TODO - what to do here?
- //for now - send the error to debug, but just leave it as a String
- String errorMessage = jpe.getMessage();
- logger.debug("Json Error Converting " + parm.getParamName() + " - " + errorMessage,jpe);
- hasJson = false;
- jsonNode = null;
- } catch (Exception e) {
- // or here?
- logger.debug("Json Error Converting " + parm.getParamName() + " " + e.getMessage(), e);
- hasJson = false;
- jsonNode = null;
- }
- if (jsonNode != null) {
- // Notice here - we add it to the jsonParams hashMap with the actual name -
- // then manipulate the inputs so when we check for aliases below - it will not
- // get flagged.
- jsonParams.put(parm.getParamName(), jsonNode);
- inputs.remove(parm.getParamAlias());
- inputs.put(parm.getParamName(), jsonString);
- }
- } //TODO add a check for the parameter in the env file
- }
-
- if (parm.isRequired () && (inputs == null || !inputs.containsKey (parm.getParamName ()))) {
- if (inputs.containsKey (parm.getParamAlias ())) {
- // They've submitted using an alias name. Remove that from inputs, and add back using real name.
- String realParamName = parm.getParamName ();
- String alias = parm.getParamAlias ();
- Object value = inputs.get (alias);
- logger.debug ("*Found an Alias: paramName=" + realParamName
- + ",alias="
- + alias
- + ",value="
- + value);
- inputs.remove (alias);
- inputs.put (realParamName, value);
- logger.debug ("{} entry removed from inputs, added back using {}", alias, realParamName);
+ if (jsonNode != null) {
+ jsonParams.put(parm.getParamName(), jsonNode);
+ }
+ } else if (inputs.containsKey(parm.getParamAlias())) {
+ hasJson = true;
+ String jsonString = null;
+ try {
+ jsonString = (String) inputs.get(parm.getParamAlias());
+ jsonNode = JSON_MAPPER.readTree(jsonString);
+ } catch (JsonParseException jpe) {
+ // TODO - what to do here?
+ // for now - send the error to debug, but just leave it as a String
+ String errorMessage = jpe.getMessage();
+ logger.debug("Json Error Converting " + parm.getParamName() + " - " + errorMessage, jpe);
+ hasJson = false;
+ jsonNode = null;
+ } catch (Exception e) {
+ // or here?
+ logger.debug("Json Error Converting " + parm.getParamName() + " " + e.getMessage(), e);
+ hasJson = false;
+ jsonNode = null;
+ }
+ if (jsonNode != null) {
+ // Notice here - we add it to the jsonParams hashMap with the actual name -
+ // then manipulate the inputs so when we check for aliases below - it will not
+ // get flagged.
+ jsonParams.put(parm.getParamName(), jsonNode);
+ inputs.remove(parm.getParamAlias());
+ inputs.put(parm.getParamName(), jsonString);
}
- // enhanced - check if it's in the Environment (note: that method
- else if (mhee != null && mhee.containsParameter(parm.getParamName())) {
+ } // TODO add a check for the parameter in the env file
+ }
- logger.debug("Required parameter {} appears to be in environment - do not count as missing",
+ if (parm.isRequired() && (inputs == null || !inputs.containsKey(parm.getParamName()))) {
+ if (inputs.containsKey(parm.getParamAlias())) {
+ // They've submitted using an alias name. Remove that from inputs, and add back using real name.
+ String realParamName = parm.getParamName();
+ String alias = parm.getParamAlias();
+ Object value = inputs.get(alias);
+ logger.debug("*Found an Alias: paramName=" + realParamName + ",alias=" + alias + ",value=" + value);
+ inputs.remove(alias);
+ inputs.put(realParamName, value);
+ logger.debug("{} entry removed from inputs, added back using {}", alias, realParamName);
+ }
+ // enhanced - check if it's in the Environment (note: that method
+ else if (mhee != null && mhee.containsParameter(parm.getParamName())) {
+
+ logger.debug("Required parameter {} appears to be in environment - do not count as missing",
parm.getParamName());
- }
- else {
- logger.debug("adding to missing parameters list: {}", parm.getParamName());
- if (missingParams == null) {
- missingParams = parm.getParamName ();
- } else {
- missingParams += "," + parm.getParamName ();
- }
+ } else {
+ logger.debug("adding to missing parameters list: {}", parm.getParamName());
+ if (missingParams == null) {
+ missingParams = parm.getParamName();
+ } else {
+ missingParams += "," + parm.getParamName();
}
}
- paramList.add (parm.getParamName ());
}
+ paramList.add(parm.getParamName());
+ }
- if (missingParams != null) {
- // Problem - missing one or more required parameters
- if (checkRequiredParameters) {
+ if (missingParams != null) {
+ // Problem - missing one or more required parameters
+ if (checkRequiredParameters) {
String error = "Update VNF: Missing Required inputs: " + missingParams;
- logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "OpenStack",
- ErrorCode.DataError.getValue(), error);
- throw new VnfException (error, MsoExceptionCategory.USERDATA);
- } else {
- logger.debug("found missing parameters - but checkRequiredParameters is false - will not block");
- }
+ logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "OpenStack",
+ ErrorCode.DataError.getValue(), error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
} else {
- logger.debug("No missing parameters found - ok to proceed");
+ logger.debug("found missing parameters - but checkRequiredParameters is false - will not block");
}
+ } else {
+ logger.debug("No missing parameters found - ok to proceed");
+ }
- // Just submit the envt entry as received from the database
- String newEnvironmentString = null;
- if (mhee != null) {
- newEnvironmentString = mhee.getRawEntry().toString();
- }
- // Remove any extraneous parameters (don't throw an error)
- if (inputs != null) {
- List <String> extraParams = new ArrayList <> ();
- extraParams.addAll (inputs.keySet ());
- // This is not a valid parameter for this template
- extraParams.removeAll (paramList);
- if (!extraParams.isEmpty ()) {
- logger.warn("{} {} {} {} {} {}", MessageEnum.RA_VNF_EXTRA_PARAM.toString(), vnfType,
+ // Just submit the envt entry as received from the database
+ String newEnvironmentString = null;
+ if (mhee != null) {
+ newEnvironmentString = mhee.getRawEntry().toString();
+ }
+ // Remove any extraneous parameters (don't throw an error)
+ if (inputs != null) {
+ List<String> extraParams = new ArrayList<>();
+ extraParams.addAll(inputs.keySet());
+ // This is not a valid parameter for this template
+ extraParams.removeAll(paramList);
+ if (!extraParams.isEmpty()) {
+ logger.warn("{} {} {} {} {} {}", MessageEnum.RA_VNF_EXTRA_PARAM.toString(), vnfType,
extraParams.toString(), "OpenStack", ErrorCode.DataError.getValue(), "Extra params");
- inputs.keySet ().removeAll (extraParams);
- }
+ inputs.keySet().removeAll(extraParams);
}
- Map<String, Object> goldenInputs = copyStringInputs(inputs);
- // 1607 - when we get here - we have clean inputs. Create inputsTwo in case we have json
- Map<String, Object> inputsTwo = null;
- if (hasJson && jsonParams.size() > 0) {
- inputsTwo = new HashMap<>();
- for (Map.Entry<String, Object> entry : inputs.entrySet()) {
- String keyParamName = entry.getKey();
- Object value = entry.getValue();
- if (jsonParams.containsKey(keyParamName)) {
- inputsTwo.put(keyParamName, jsonParams.get(keyParamName));
- } else {
- inputsTwo.put(keyParamName, value);
- }
- }
- goldenInputs = inputsTwo;
+ }
+ Map<String, Object> goldenInputs = copyStringInputs(inputs);
+ // 1607 - when we get here - we have clean inputs. Create inputsTwo in case we have json
+ Map<String, Object> inputsTwo = null;
+ if (hasJson && jsonParams.size() > 0) {
+ inputsTwo = new HashMap<>();
+ for (Map.Entry<String, Object> entry : inputs.entrySet()) {
+ String keyParamName = entry.getKey();
+ Object value = entry.getValue();
+ if (jsonParams.containsKey(keyParamName)) {
+ inputsTwo.put(keyParamName, jsonParams.get(keyParamName));
+ } else {
+ inputsTwo.put(keyParamName, value);
+ }
}
+ goldenInputs = inputsTwo;
+ }
- // "Fix" the template if it has CR/LF (getting this from Oracle)
- String template = heatTemplate.getHeatTemplate ();
- template = template.replaceAll ("\r\n", "\n");
+ // "Fix" the template if it has CR/LF (getting this from Oracle)
+ String template = heatTemplate.getHeatTemplate();
+ template = template.replaceAll("\r\n", "\n");
- boolean isValetEnabled = this.checkBooleanProperty(MsoVnfAdapterImpl.VALET_ENABLED, false);
- boolean failRequestOnValetFailure = this.checkBooleanProperty(MsoVnfAdapterImpl.FAIL_REQUESTS_ON_VALET_FAILURE, false);
- logger.debug("isValetEnabled={}, failRequestsOnValetFailure={}", isValetEnabled, failRequestOnValetFailure);
- if (isVolumeRequest) {
- isValetEnabled = false;
- logger.debug("never send a volume request to valet");
+ boolean isValetEnabled = this.checkBooleanProperty(MsoVnfAdapterImpl.VALET_ENABLED, false);
+ boolean failRequestOnValetFailure =
+ this.checkBooleanProperty(MsoVnfAdapterImpl.FAIL_REQUESTS_ON_VALET_FAILURE, false);
+ logger.debug("isValetEnabled={}, failRequestsOnValetFailure={}", isValetEnabled, failRequestOnValetFailure);
+ if (isVolumeRequest) {
+ isValetEnabled = false;
+ logger.debug("never send a volume request to valet");
+ }
+ boolean sendResponseToValet = false;
+ if (isValetEnabled) {
+ Holder<Map<String, Object>> valetModifiedParamsHolder = new Holder<>();
+ String parsedVfModuleName = this.getVfModuleNameFromModuleStackId(vfModuleStackId);
+ // Make sure it is set to something.
+ if (parsedVfModuleName == null || parsedVfModuleName.isEmpty()) {
+ parsedVfModuleName = "unknown";
}
- boolean sendResponseToValet = false;
- if (isValetEnabled) {
- Holder<Map<String, Object>> valetModifiedParamsHolder = new Holder<>();
- String parsedVfModuleName = this.getVfModuleNameFromModuleStackId(vfModuleStackId);
- // Make sure it is set to something.
- if (parsedVfModuleName == null || parsedVfModuleName.isEmpty()) {
- parsedVfModuleName = "unknown";
- }
- sendResponseToValet = this.valetUpdateRequest(cloudSiteId, cloudOwner, tenantId, heatFilesObjects,
- nestedTemplatesChecked, parsedVfModuleName, false, heatTemplate, newEnvironmentString, (HashMap<String, Object>) goldenInputs,
- msoRequest, inputs, failRequestOnValetFailure, valetModifiedParamsHolder);
- if (sendResponseToValet) {
- goldenInputs = valetModifiedParamsHolder.value;
- }
+ sendResponseToValet = this.valetUpdateRequest(cloudSiteId, cloudOwner, tenantId, heatFilesObjects,
+ nestedTemplatesChecked, parsedVfModuleName, false, heatTemplate, newEnvironmentString,
+ (HashMap<String, Object>) goldenInputs, msoRequest, inputs, failRequestOnValetFailure,
+ valetModifiedParamsHolder);
+ if (sendResponseToValet) {
+ goldenInputs = valetModifiedParamsHolder.value;
}
+ }
- // Have the tenant. Now deploy the stack itself
- // Ignore MsoTenantNotFound and MsoStackAlreadyExists exceptions
- // because we already checked for those.
- long updateStackStarttime = System.currentTimeMillis ();
- try {
- heatStack = heatU.updateStack(
- cloudSiteId,
- cloudOwner,
- tenantId,
- vfModuleName,
- template,
- goldenInputs,
- true,
- heatTemplate.getTimeoutMinutes(),
- newEnvironmentString,
- //heatEnvironmentString,
- nestedTemplatesChecked,
- heatFilesObjects
- );
- } catch (MsoException me) {
- me.addContext ("UpdateVFModule");
- String error = "Update VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger
- .error("{} {} {} {} {} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId,
- tenantId, "OpenStack", ErrorCode.DataError.getValue(), "Exception - " + error, me);
- if (isValetEnabled && sendResponseToValet) {
- logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet");
- try {
- GenericValetResponse<ValetRollbackResponse> gvr = this.vci.callValetRollbackRequest(msoRequest.getRequestId(), null, false, me.getMessage());
- // Nothing to really do here whether it succeeded or not other than log it.
- logger.debug("Return code from Rollback response is {}", gvr.getStatusCode());
- } catch (Exception e) {
- logger.error("Exception encountered while sending Rollback to Valet ", e);
- }
+ // Have the tenant. Now deploy the stack itself
+ // Ignore MsoTenantNotFound and MsoStackAlreadyExists exceptions
+ // because we already checked for those.
+ long updateStackStarttime = System.currentTimeMillis();
+ try {
+ heatStack = heatU.updateStack(cloudSiteId, cloudOwner, tenantId, vfModuleName, template, goldenInputs, true,
+ heatTemplate.getTimeoutMinutes(), newEnvironmentString,
+ // heatEnvironmentString,
+ nestedTemplatesChecked, heatFilesObjects);
+ } catch (MsoException me) {
+ me.addContext("UpdateVFModule");
+ String error = "Update VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), vfModuleType, cloudOwner,
+ cloudSiteId, tenantId, "OpenStack", ErrorCode.DataError.getValue(), "Exception - " + error, me);
+ if (isValetEnabled && sendResponseToValet) {
+ logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet");
+ try {
+ GenericValetResponse<ValetRollbackResponse> gvr =
+ this.vci.callValetRollbackRequest(msoRequest.getRequestId(), null, false, me.getMessage());
+ // Nothing to really do here whether it succeeded or not other than log it.
+ logger.debug("Return code from Rollback response is {}", gvr.getStatusCode());
+ } catch (Exception e) {
+ logger.error("Exception encountered while sending Rollback to Valet ", e);
}
- throw new VnfException (me);
}
+ throw new VnfException(me);
+ }
// Reach this point if updateStack is successful.
// Populate remaining rollback info and response parameters.
- vfRollback.setVnfId (heatStack.getCanonicalName ());
- vfRollback.setVnfCreated (true);
+ vfRollback.setVnfId(heatStack.getCanonicalName());
+ vfRollback.setVnfCreated(true);
if (isValetEnabled && sendResponseToValet) {
- logger.debug("valet is enabled, the update succeeded - now send confirm to valet with stack id");
- try {
- GenericValetResponse<ValetConfirmResponse> gvr = this.vci.callValetConfirmRequest(msoRequest.getRequestId(), heatStack.getCanonicalName());
+ logger.debug("valet is enabled, the update succeeded - now send confirm to valet with stack id");
+ try {
+ GenericValetResponse<ValetConfirmResponse> gvr =
+ this.vci.callValetConfirmRequest(msoRequest.getRequestId(), heatStack.getCanonicalName());
// Nothing to really do here whether it succeeded or not other than log it.
logger.debug("Return code from Confirm response is {}", gvr.getStatusCode());
} catch (Exception e) {
@@ -2110,72 +2033,74 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
}
}
- outputs.value = copyStringOutputs (heatStack.getOutputs ());
+ outputs.value = copyStringOutputs(heatStack.getOutputs());
rollback.value = vfRollback;
return;
}
private String getVfModuleNameFromModuleStackId(String vfModuleStackId) {
- // expected format of vfModuleStackId is "MSOTEST51-vSAMP3_base_module-0/1fc1f86c-7b35-447f-99a6-c23ec176ae24"
- // before the "/" is the vfModuleName and after the "/" is the heat stack id in Openstack
- if (vfModuleStackId == null)
- return null;
- int index = vfModuleStackId.lastIndexOf('/');
- if (index <= 0)
- return null;
- String vfModuleName = null;
- try {
- vfModuleName = vfModuleStackId.substring(0, index);
- } catch (Exception e) {
- logger.debug("Exception", e);
- vfModuleName = null;
- }
- return vfModuleName;
+ // expected format of vfModuleStackId is "MSOTEST51-vSAMP3_base_module-0/1fc1f86c-7b35-447f-99a6-c23ec176ae24"
+ // before the "/" is the vfModuleName and after the "/" is the heat stack id in Openstack
+ if (vfModuleStackId == null)
+ return null;
+ int index = vfModuleStackId.lastIndexOf('/');
+ if (index <= 0)
+ return null;
+ String vfModuleName = null;
+ try {
+ vfModuleName = vfModuleStackId.substring(0, index);
+ } catch (Exception e) {
+ logger.debug("Exception", e);
+ vfModuleName = null;
+ }
+ return vfModuleName;
}
/*
* Helper method to check a boolean property value - on error return provided default
*/
private boolean checkBooleanProperty(String propertyName, boolean defaultValue) {
- boolean property = defaultValue;
- try {
- String propertyString = this.environment.getProperty(propertyName);
- if ("true".equalsIgnoreCase(propertyString) || "y".equalsIgnoreCase(propertyString)) {
- property = true;
- } else if ("false".equalsIgnoreCase(propertyString) || "n".equalsIgnoreCase(propertyString)) {
- property = false;
- }
- } catch (Exception e) {
- logger.debug("An exception occured trying to get property {} - defaulting to ", propertyName, defaultValue, e);
- property = defaultValue;
- }
- return property;
+ boolean property = defaultValue;
+ try {
+ String propertyString = this.environment.getProperty(propertyName);
+ if ("true".equalsIgnoreCase(propertyString) || "y".equalsIgnoreCase(propertyString)) {
+ property = true;
+ } else if ("false".equalsIgnoreCase(propertyString) || "n".equalsIgnoreCase(propertyString)) {
+ property = false;
+ }
+ } catch (Exception e) {
+ logger.debug("An exception occured trying to get property {} - defaulting to ", propertyName, defaultValue,
+ e);
+ property = defaultValue;
+ }
+ return property;
}
/*
* Helper method to combine getFiles and nestedTemplates in to a single Map
*/
- private Map<String, Object> combineGetFilesAndNestedTemplates(Map<String, Object> getFiles, Map<String, Object> nestedTemplates) {
- boolean haveGetFiles = true;
- boolean haveNestedTemplates = true;
- Map<String, Object> files = new HashMap<String, Object>();
- if (getFiles == null || getFiles.isEmpty()) {
- haveGetFiles = false;
- }
- if (nestedTemplates == null || nestedTemplates.isEmpty()) {
- haveNestedTemplates = false;
- }
+ private Map<String, Object> combineGetFilesAndNestedTemplates(Map<String, Object> getFiles,
+ Map<String, Object> nestedTemplates) {
+ boolean haveGetFiles = true;
+ boolean haveNestedTemplates = true;
+ Map<String, Object> files = new HashMap<String, Object>();
+ if (getFiles == null || getFiles.isEmpty()) {
+ haveGetFiles = false;
+ }
+ if (nestedTemplates == null || nestedTemplates.isEmpty()) {
+ haveNestedTemplates = false;
+ }
if (haveGetFiles && haveNestedTemplates) {
- for (String keyString : getFiles.keySet ()) {
- files.put (keyString, getFiles.get (keyString));
+ for (String keyString : getFiles.keySet()) {
+ files.put(keyString, getFiles.get(keyString));
}
- for (String keyString : nestedTemplates.keySet ()) {
- files.put (keyString, nestedTemplates.get (keyString));
+ for (String keyString : nestedTemplates.keySet()) {
+ files.put(keyString, nestedTemplates.get(keyString));
}
} else {
// Handle if we only have one or neither:
if (haveGetFiles) {
- files = getFiles;
+ files = getFiles;
}
if (haveNestedTemplates) {
files = nestedTemplates;
@@ -2187,171 +2112,173 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
/*
* Valet Create request
*/
- private boolean valetCreateRequest(String cloudSiteId, String cloudOwner, String tenantId, Map<String, Object> heatFilesObjects, Map<String, Object> nestedTemplatesChecked,
- String vfModuleName, boolean backout, HeatTemplate heatTemplate, String newEnvironmentString, Map<String, Object> goldenInputs,
- MsoRequest msoRequest, Map<String, Object> inputs, boolean failRequestOnValetFailure, Holder<Map<String, Object>> valetModifiedParamsHolder) throws VnfException {
- boolean valetSucceeded = false;
- String valetErrorMessage = "more detail not available";
- try {
- String keystoneUrl = heat.getCloudSiteKeystoneUrl(cloudSiteId);
- Map<String, Object> files = this.combineGetFilesAndNestedTemplates(heatFilesObjects,
- nestedTemplatesChecked);
- HeatRequest heatRequest = new HeatRequest(vfModuleName, backout, heatTemplate.getTimeoutMinutes(),
- heatTemplate.getTemplateBody(), newEnvironmentString, files, goldenInputs);
- GenericValetResponse<ValetCreateResponse> createReq = this.vci.callValetCreateRequest(msoRequest.getRequestId(),
- cloudSiteId, cloudOwner, tenantId, msoRequest.getServiceInstanceId(), (String)inputs.get("vnf_id"),
- (String)inputs.get("vnf_name"), (String)inputs.get("vf_module_id"), (String)inputs.get("vf_module_name"), keystoneUrl,
- heatRequest);
- ValetCreateResponse vcr = createReq.getReturnObject();
- if (vcr != null && createReq.getStatusCode() == 200) {
- ValetStatus status = vcr.getStatus();
- if (status != null) {
- String statusCode = status.getStatus(); // "ok" or "failed"
- if ("ok".equalsIgnoreCase(statusCode)) {
- Map<String, Object> newInputs = vcr.getParameters();
- if (newInputs != null) {
- Map<String, Object> oldGold = goldenInputs;
- logger.debug("parameters before being modified by valet:{}", oldGold.toString());
- goldenInputs = new HashMap<String, Object>();
- for (String key : newInputs.keySet()) {
- goldenInputs.put(key, newInputs.get(key));
- }
- valetModifiedParamsHolder.value = goldenInputs;
- logger.debug("parameters after being modified by valet:{}", goldenInputs.toString());
- valetSucceeded = true;
- }
- } else {
- valetErrorMessage = status.getMessage();
- }
- }
- } else {
- logger.debug("Got a bad response back from valet");
- valetErrorMessage = "Bad response back from Valet";
- valetSucceeded = false;
- }
- } catch (Exception e) {
- logger.error("An exception occurred trying to call valet ...", e);
- valetSucceeded = false;
- valetErrorMessage = e.getMessage();
- }
- if (failRequestOnValetFailure && !valetSucceeded) {
- // The valet request failed - and property says to fail the request
- //TODO Create a new exception class for valet?
- throw new VnfException("A failure occurred with Valet: " + valetErrorMessage);
- }
- return valetSucceeded;
+ private boolean valetCreateRequest(String cloudSiteId, String cloudOwner, String tenantId,
+ Map<String, Object> heatFilesObjects, Map<String, Object> nestedTemplatesChecked, String vfModuleName,
+ boolean backout, HeatTemplate heatTemplate, String newEnvironmentString, Map<String, Object> goldenInputs,
+ MsoRequest msoRequest, Map<String, Object> inputs, boolean failRequestOnValetFailure,
+ Holder<Map<String, Object>> valetModifiedParamsHolder) throws VnfException {
+ boolean valetSucceeded = false;
+ String valetErrorMessage = "more detail not available";
+ try {
+ String keystoneUrl = heat.getCloudSiteKeystoneUrl(cloudSiteId);
+ Map<String, Object> files =
+ this.combineGetFilesAndNestedTemplates(heatFilesObjects, nestedTemplatesChecked);
+ HeatRequest heatRequest = new HeatRequest(vfModuleName, backout, heatTemplate.getTimeoutMinutes(),
+ heatTemplate.getTemplateBody(), newEnvironmentString, files, goldenInputs);
+ GenericValetResponse<ValetCreateResponse> createReq = this.vci.callValetCreateRequest(
+ msoRequest.getRequestId(), cloudSiteId, cloudOwner, tenantId, msoRequest.getServiceInstanceId(),
+ (String) inputs.get("vnf_id"), (String) inputs.get("vnf_name"), (String) inputs.get("vf_module_id"),
+ (String) inputs.get("vf_module_name"), keystoneUrl, heatRequest);
+ ValetCreateResponse vcr = createReq.getReturnObject();
+ if (vcr != null && createReq.getStatusCode() == 200) {
+ ValetStatus status = vcr.getStatus();
+ if (status != null) {
+ String statusCode = status.getStatus(); // "ok" or "failed"
+ if ("ok".equalsIgnoreCase(statusCode)) {
+ Map<String, Object> newInputs = vcr.getParameters();
+ if (newInputs != null) {
+ Map<String, Object> oldGold = goldenInputs;
+ logger.debug("parameters before being modified by valet:{}", oldGold.toString());
+ goldenInputs = new HashMap<String, Object>();
+ for (String key : newInputs.keySet()) {
+ goldenInputs.put(key, newInputs.get(key));
+ }
+ valetModifiedParamsHolder.value = goldenInputs;
+ logger.debug("parameters after being modified by valet:{}", goldenInputs.toString());
+ valetSucceeded = true;
+ }
+ } else {
+ valetErrorMessage = status.getMessage();
+ }
+ }
+ } else {
+ logger.debug("Got a bad response back from valet");
+ valetErrorMessage = "Bad response back from Valet";
+ valetSucceeded = false;
+ }
+ } catch (Exception e) {
+ logger.error("An exception occurred trying to call valet ...", e);
+ valetSucceeded = false;
+ valetErrorMessage = e.getMessage();
+ }
+ if (failRequestOnValetFailure && !valetSucceeded) {
+ // The valet request failed - and property says to fail the request
+ // TODO Create a new exception class for valet?
+ throw new VnfException("A failure occurred with Valet: " + valetErrorMessage);
+ }
+ return valetSucceeded;
}
/*
* Valet update request
*/
- private boolean valetUpdateRequest(String cloudSiteId, String cloudOwnerId, String tenantId,
- Map<String, Object> heatFilesObjects, Map<String, Object> nestedTemplatesChecked, String vfModuleName,
- boolean backout, HeatTemplate heatTemplate, String newEnvironmentString,
- Map<String, Object> goldenInputs, MsoRequest msoRequest, Map<String, Object> inputs,
- boolean failRequestOnValetFailure, Holder<Map<String, Object>> valetModifiedParamsHolder) throws VnfException {
-
- boolean valetSucceeded = false;
- String valetErrorMessage = "more detail not available";
- try {
- String keystoneUrl = heat.getCloudSiteKeystoneUrl(cloudSiteId);
- Map<String, Object> files = this.combineGetFilesAndNestedTemplates(heatFilesObjects,
- nestedTemplatesChecked);
- HeatRequest heatRequest = new HeatRequest(vfModuleName, false, heatTemplate.getTimeoutMinutes(),
- heatTemplate.getTemplateBody(), newEnvironmentString, files, goldenInputs);
- // vnf name is not sent to MSO on update requests - so we will set it to the vf module name for now
- GenericValetResponse<ValetUpdateResponse> updateReq = this.vci.callValetUpdateRequest(msoRequest.getRequestId(),
- cloudSiteId, cloudOwnerId, tenantId, msoRequest.getServiceInstanceId(), (String)inputs.get("vnf_id"),
- vfModuleName, (String)inputs.get("vf_module_id"), vfModuleName, keystoneUrl,
- heatRequest);
- ValetUpdateResponse vur = updateReq.getReturnObject();
- if (vur != null && updateReq.getStatusCode() == 200) {
- ValetStatus status = vur.getStatus();
- if (status != null) {
- String statusCode = status.getStatus(); // "ok" or "failed"
- if ("ok".equalsIgnoreCase(statusCode)) {
- Map<String, Object> newInputs = vur.getParameters();
- if (newInputs != null) {
- Map<String, Object> oldGold = goldenInputs;
- logger.debug("parameters before being modified by valet:{}", oldGold.toString());
- goldenInputs = new HashMap<String, Object>();
- for (String key : newInputs.keySet()) {
- goldenInputs.put(key, newInputs.get(key));
- }
- valetModifiedParamsHolder.value = goldenInputs;
- logger.debug("parameters after being modified by valet:{}", goldenInputs.toString());
- valetSucceeded = true;
- }
- } else {
- valetErrorMessage = status.getMessage();
- }
- }
- } else {
- logger.debug("Got a bad response back from valet");
- valetErrorMessage = "Got a bad response back from valet";
- valetSucceeded = false;
- }
- } catch (Exception e) {
- logger.error("An exception occurred trying to call valet - will continue processing for now...", e);
- valetErrorMessage = e.getMessage();
- valetSucceeded = false;
+ private boolean valetUpdateRequest(String cloudSiteId, String cloudOwnerId, String tenantId,
+ Map<String, Object> heatFilesObjects, Map<String, Object> nestedTemplatesChecked, String vfModuleName,
+ boolean backout, HeatTemplate heatTemplate, String newEnvironmentString, Map<String, Object> goldenInputs,
+ MsoRequest msoRequest, Map<String, Object> inputs, boolean failRequestOnValetFailure,
+ Holder<Map<String, Object>> valetModifiedParamsHolder) throws VnfException {
+
+ boolean valetSucceeded = false;
+ String valetErrorMessage = "more detail not available";
+ try {
+ String keystoneUrl = heat.getCloudSiteKeystoneUrl(cloudSiteId);
+ Map<String, Object> files =
+ this.combineGetFilesAndNestedTemplates(heatFilesObjects, nestedTemplatesChecked);
+ HeatRequest heatRequest = new HeatRequest(vfModuleName, false, heatTemplate.getTimeoutMinutes(),
+ heatTemplate.getTemplateBody(), newEnvironmentString, files, goldenInputs);
+ // vnf name is not sent to MSO on update requests - so we will set it to the vf module name for now
+ GenericValetResponse<ValetUpdateResponse> updateReq =
+ this.vci.callValetUpdateRequest(msoRequest.getRequestId(), cloudSiteId, cloudOwnerId, tenantId,
+ msoRequest.getServiceInstanceId(), (String) inputs.get("vnf_id"), vfModuleName,
+ (String) inputs.get("vf_module_id"), vfModuleName, keystoneUrl, heatRequest);
+ ValetUpdateResponse vur = updateReq.getReturnObject();
+ if (vur != null && updateReq.getStatusCode() == 200) {
+ ValetStatus status = vur.getStatus();
+ if (status != null) {
+ String statusCode = status.getStatus(); // "ok" or "failed"
+ if ("ok".equalsIgnoreCase(statusCode)) {
+ Map<String, Object> newInputs = vur.getParameters();
+ if (newInputs != null) {
+ Map<String, Object> oldGold = goldenInputs;
+ logger.debug("parameters before being modified by valet:{}", oldGold.toString());
+ goldenInputs = new HashMap<String, Object>();
+ for (String key : newInputs.keySet()) {
+ goldenInputs.put(key, newInputs.get(key));
+ }
+ valetModifiedParamsHolder.value = goldenInputs;
+ logger.debug("parameters after being modified by valet:{}", goldenInputs.toString());
+ valetSucceeded = true;
+ }
+ } else {
+ valetErrorMessage = status.getMessage();
+ }
+ }
+ } else {
+ logger.debug("Got a bad response back from valet");
+ valetErrorMessage = "Got a bad response back from valet";
+ valetSucceeded = false;
+ }
+ } catch (Exception e) {
+ logger.error("An exception occurred trying to call valet - will continue processing for now...", e);
+ valetErrorMessage = e.getMessage();
+ valetSucceeded = false;
+ }
+ if (failRequestOnValetFailure && !valetSucceeded) {
+ // The valet request failed - and property says to fail the request
+ // TODO Create a new exception class for valet?
+ throw new VnfException("A failure occurred with Valet: " + valetErrorMessage);
+ }
+ return valetSucceeded;
}
- if (failRequestOnValetFailure && !valetSucceeded) {
- // The valet request failed - and property says to fail the request
- // TODO Create a new exception class for valet?
- throw new VnfException("A failure occurred with Valet: " + valetErrorMessage);
- }
- return valetSucceeded;
- }
-
- /*
- * Valet delete request
- */
- private boolean valetDeleteRequest(String cloudSiteId, String cloudOwnerId, String tenantId, String vnfName,
- MsoRequest msoRequest, boolean failRequestOnValetFailure) {
- boolean valetDeleteRequestSucceeded = false;
- String valetErrorMessage = "more detail not available";
- try {
- String vfModuleId = vnfName;
- String vfModuleName = vnfName;
- try {
- vfModuleName = vnfName.substring(0, vnfName.indexOf('/'));
- vfModuleId = vnfName.substring(vnfName.indexOf('/') + 1);
- } catch (Exception e) {
- // do nothing - send what we got for vnfName for both to valet
- logger.error("An exception occurred trying to call MsoVnfAdapterImpl.valetDeleteRequest() method", e);
- }
- GenericValetResponse<ValetDeleteResponse> deleteReq = this.vci.callValetDeleteRequest(msoRequest.getRequestId(),
- cloudSiteId, cloudOwnerId, tenantId, vfModuleId, vfModuleName);
- ValetDeleteResponse vdr = deleteReq.getReturnObject();
- if (vdr != null && deleteReq.getStatusCode() == 200) {
- ValetStatus status = vdr.getStatus();
- if (status != null) {
- String statusCode = status.getStatus(); // "ok" or "failed"
- if ("ok".equalsIgnoreCase(statusCode)) {
- logger.debug("delete request to valet returned success");
- valetDeleteRequestSucceeded = true;
+
+ /*
+ * Valet delete request
+ */
+ private boolean valetDeleteRequest(String cloudSiteId, String cloudOwnerId, String tenantId, String vnfName,
+ MsoRequest msoRequest, boolean failRequestOnValetFailure) {
+ boolean valetDeleteRequestSucceeded = false;
+ String valetErrorMessage = "more detail not available";
+ try {
+ String vfModuleId = vnfName;
+ String vfModuleName = vnfName;
+ try {
+ vfModuleName = vnfName.substring(0, vnfName.indexOf('/'));
+ vfModuleId = vnfName.substring(vnfName.indexOf('/') + 1);
+ } catch (Exception e) {
+ // do nothing - send what we got for vnfName for both to valet
+ logger.error("An exception occurred trying to call MsoVnfAdapterImpl.valetDeleteRequest() method", e);
+ }
+ GenericValetResponse<ValetDeleteResponse> deleteReq = this.vci.callValetDeleteRequest(
+ msoRequest.getRequestId(), cloudSiteId, cloudOwnerId, tenantId, vfModuleId, vfModuleName);
+ ValetDeleteResponse vdr = deleteReq.getReturnObject();
+ if (vdr != null && deleteReq.getStatusCode() == 200) {
+ ValetStatus status = vdr.getStatus();
+ if (status != null) {
+ String statusCode = status.getStatus(); // "ok" or "failed"
+ if ("ok".equalsIgnoreCase(statusCode)) {
+ logger.debug("delete request to valet returned success");
+ valetDeleteRequestSucceeded = true;
+ } else {
+ logger.debug("delete request to valet returned failure");
+ valetDeleteRequestSucceeded = false;
+ valetErrorMessage = status.getMessage();
+ }
+ }
} else {
- logger.debug("delete request to valet returned failure");
+ logger.debug("Got a bad response back from valet - delete request failed");
valetDeleteRequestSucceeded = false;
- valetErrorMessage = status.getMessage();
- }
- }
- } else {
- logger.debug("Got a bad response back from valet - delete request failed");
- valetDeleteRequestSucceeded = false;
- valetErrorMessage = "Got a bad response back from valet - delete request failed";
- }
- } catch (Exception e) {
- logger.error("An exception occurred trying to call valet - valetDeleteRequest failed", e);
- valetDeleteRequestSucceeded = false;
- valetErrorMessage = e.getMessage();
+ valetErrorMessage = "Got a bad response back from valet - delete request failed";
+ }
+ } catch (Exception e) {
+ logger.error("An exception occurred trying to call valet - valetDeleteRequest failed", e);
+ valetDeleteRequestSucceeded = false;
+ valetErrorMessage = e.getMessage();
+ }
+ if (valetDeleteRequestSucceeded == false && failRequestOnValetFailure == true) {
+ logger.error("ValetDeleteRequestFailed - del req still will be sent to openstack",
+ new VnfException("ValetDeleteRequestFailedError"));
+ }
+ return valetDeleteRequestSucceeded;
}
- if (valetDeleteRequestSucceeded == false && failRequestOnValetFailure == true) {
- logger.error("ValetDeleteRequestFailed - del req still will be sent to openstack", new VnfException
- ("ValetDeleteRequestFailedError"));
- }
- return valetDeleteRequestSucceeded;
- }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java
index dc695615cb..2ea7ff417c 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java
@@ -30,10 +30,8 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
-
import javax.jws.WebService;
import javax.xml.ws.Holder;
-
import org.onap.so.adapters.vnf.exceptions.VnfAlreadyExists;
import org.onap.so.adapters.vnf.exceptions.VnfException;
import org.onap.so.cloud.CloudConfig;
@@ -54,7 +52,6 @@ import org.onap.so.db.catalog.utils.MavenLikeVersioning;
import org.onap.so.entity.MsoRequest;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.onap.so.openstack.beans.MsoTenant;
import org.onap.so.openstack.beans.VnfRollback;
import org.onap.so.openstack.beans.VnfStatus;
@@ -69,7 +66,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -77,7 +73,8 @@ import org.springframework.transaction.annotation.Transactional;
@Component
@Transactional
-@WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter", targetNamespace = "http://org.onap.so/vnf")
+@WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter",
+ targetNamespace = "http://org.onap.so/vnf")
public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
private static Logger logger = LoggerFactory.getLogger(MsoVnfCloudifyAdapterImpl.class);
@@ -87,8 +84,8 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
private static final String LOG_REPLY_NAME = "MSO-VnfAdapter:MSO-BPMN.";
private static final String CHECK_REQD_PARAMS = "org.onap.so.adapters.vnf.checkRequiredParameters";
private static final String ADD_GET_FILES_ON_VOLUME_REQ = "org.onap.so.adapters.vnf.addGetFilesOnVolumeReq";
- private static final String CLOUDIFY_RESPONSE_SUCCESS="Successfully received response from Cloudify";
- private static final String CLOUDIFY="Cloudify";
+ private static final String CLOUDIFY_RESPONSE_SUCCESS = "Successfully received response from Cloudify";
+ private static final String CLOUDIFY = "Cloudify";
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
@@ -106,16 +103,18 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
@Autowired
protected MsoCloudifyUtils cloudifyUtils;
+
/**
* Health Check web method. Does nothing but return to show the adapter is deployed.
*/
@Override
- public void healthCheck () {
+ public void healthCheck() {
logger.debug("Health check call in VNF Cloudify Adapter");
}
/**
* DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL.
+ *
* @see MsoVnfCloudifyAdapterImpl#MsoVnfAdapterImpl(MsoPropertiesFactory, CloudConfigFactory)
*/
public MsoVnfCloudifyAdapterImpl() {
@@ -123,57 +122,31 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
}
/**
- * This is the "Create VNF" web service implementation.
- * This function is now unsupported and will return an error.
+ * This is the "Create VNF" web service implementation. This function is now unsupported and will return an error.
*
*/
@Override
- public void createVnf (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfType,
- String vnfVersion,
- String vnfName,
- String requestType,
- String volumeGroupHeatStackId,
- Map <String, Object> inputs,
- Boolean failIfExists,
- Boolean backout,
- Boolean enableBridge,
- MsoRequest msoRequest,
- Holder <String> vnfId,
- Holder <Map <String, String>> outputs,
- Holder <VnfRollback> rollback)
- throws VnfException
- {
- // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules.
+ public void createVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion,
+ String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs,
+ Boolean failIfExists, Boolean backout, Boolean enableBridge, MsoRequest msoRequest, Holder<String> vnfId,
+ Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) throws VnfException {
+ // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules.
logger.debug("CreateVNF command attempted but not supported");
throw new VnfException("CreateVNF: Unsupported command", MsoExceptionCategory.USERDATA);
}
/**
- * This is the "Update VNF" web service implementation.
- * This function is now unsupported and will return an error.
+ * This is the "Update VNF" web service implementation. This function is now unsupported and will return an error.
*
*/
@Override
- public void updateVnf (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfType,
- String vnfVersion,
- String vnfName,
- String requestType,
- String volumeGroupHeatStackId,
- Map <String, Object> inputs,
- MsoRequest msoRequest,
- Holder <Map <String, String>> outputs,
- Holder <VnfRollback> rollback)
- throws VnfException
- {
- // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules.
- logger.debug("UpdateVNF command attempted but not supported");
- throw new VnfException ("UpdateVNF: Unsupported command", MsoExceptionCategory.USERDATA);
+ public void updateVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion,
+ String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs,
+ MsoRequest msoRequest, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback)
+ throws VnfException {
+ // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules.
+ logger.debug("UpdateVNF command attempted but not supported");
+ throw new VnfException("UpdateVNF: Unsupported command", MsoExceptionCategory.USERDATA);
}
/**
@@ -181,13 +154,13 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
*
* This really should be QueryVfModule, but nobody ever changed it.
*
- * For Cloudify, this will look up a deployment by its deployment ID, which is really the same
- * as deployment name, since it assigned by the client when a deployment is created.
- * Also, the input cloudSiteId is used only to identify which Cloudify instance to query,
- * and the tenantId is ignored (since that really only applies for Openstack/Heat).
+ * For Cloudify, this will look up a deployment by its deployment ID, which is really the same as deployment name,
+ * since it assigned by the client when a deployment is created. Also, the input cloudSiteId is used only to
+ * identify which Cloudify instance to query, and the tenantId is ignored (since that really only applies for
+ * Openstack/Heat).
*
- * The method returns an indicator that the VNF exists, along with its status and outputs.
- * The input "vnfName" will also be reflected back as its ID.
+ * The method returns an indicator that the VNF exists, along with its status and outputs. The input "vnfName" will
+ * also be reflected back as its ID.
*
* @param cloudSiteId CLLI code of the cloud site in which to query
* @param cloudOwner cloud owner of the cloud site in which to query
@@ -199,44 +172,35 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
* @param outputs Holder for Map of VNF outputs from Cloudify deployment (assigned IPs, etc)
*/
@Override
- public void queryVnf (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfName,
- MsoRequest msoRequest,
- Holder <Boolean> vnfExists,
- Holder <String> vnfId,
- Holder <VnfStatus> status,
- Holder <Map <String, String>> outputs)
- throws VnfException
- {
- logger.debug ("Querying VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId);
+ public void queryVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest,
+ Holder<Boolean> vnfExists, Holder<String> vnfId, Holder<VnfStatus> status,
+ Holder<Map<String, String>> outputs) throws VnfException {
+ logger.debug("Querying VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
- long subStartTime = System.currentTimeMillis ();
-
- DeploymentInfo deployment = null;
-
- try {
- deployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, vnfName);
- }
- catch (MsoCloudifyManagerNotFound e) {
- // This site does not have a Cloudify Manager.
- // This isn't an error, just means we won't find the VNF here.
- deployment = null;
- }
- catch (MsoException me) {
- // Failed to query the Deployment due to a cloudify exception.
- // Convert to a generic VnfException
- me.addContext("QueryVNF");
- String error = "Query VNF (Cloudify): " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger
- .error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, tenantId,
- CLOUDIFY, "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryDeployment", me);
- logger.debug(error);
- throw new VnfException(me);
- }
+ long startTime = System.currentTimeMillis();
+ long subStartTime = System.currentTimeMillis();
+
+ DeploymentInfo deployment = null;
+
+ try {
+ deployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, vnfName);
+ } catch (MsoCloudifyManagerNotFound e) {
+ // This site does not have a Cloudify Manager.
+ // This isn't an error, just means we won't find the VNF here.
+ deployment = null;
+ } catch (MsoException me) {
+ // Failed to query the Deployment due to a cloudify exception.
+ // Convert to a generic VnfException
+ me.addContext("QueryVNF");
+ String error = "Query VNF (Cloudify): " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner,
+ cloudSiteId, tenantId, CLOUDIFY, "QueryVNF", ErrorCode.DataError.getValue(),
+ "Exception - queryDeployment", me);
+ logger.debug(error);
+ throw new VnfException(me);
+ }
if (deployment != null && deployment.getStatus() != DeploymentStatus.NOTFOUND) {
vnfExists.value = Boolean.TRUE;
@@ -258,37 +222,31 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
/**
- * This is the "Delete VNF" web service implementation.
- * This function is now unsupported and will return an error.
+ * This is the "Delete VNF" web service implementation. This function is now unsupported and will return an error.
*
*/
@Override
- public void deleteVnf (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfName,
- MsoRequest msoRequest) throws VnfException {
+ public void deleteVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest)
+ throws VnfException {
- // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules.
+ // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules.
logger.debug("DeleteVNF command attempted but not supported");
- throw new VnfException ("DeleteVNF: Unsupported command", MsoExceptionCategory.USERDATA);
+ throw new VnfException("DeleteVNF: Unsupported command", MsoExceptionCategory.USERDATA);
}
/**
- * This web service endpoint will rollback a previous Create VNF operation.
- * A rollback object is returned to the client in a successful creation
- * response. The client can pass that object as-is back to the rollbackVnf
- * operation to undo the creation.
+ * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the
+ * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation
+ * to undo the creation.
*
- * TODO: This should be rollbackVfModule and/or rollbackVolumeGroup,
- * but APIs were apparently never updated.
+ * TODO: This should be rollbackVfModule and/or rollbackVolumeGroup, but APIs were apparently never updated.
*/
@Override
- public void rollbackVnf (VnfRollback rollback) throws VnfException {
- long startTime = System.currentTimeMillis ();
- // rollback may be null (e.g. if stack already existed when Create was called)
+ public void rollbackVnf(VnfRollback rollback) throws VnfException {
+ long startTime = System.currentTimeMillis();
+ // rollback may be null (e.g. if stack already existed when Create was called)
if (rollback == null) {
- logger.info ("{} {} {}", MessageEnum.RA_ROLLBACK_NULL.toString(), "OpenStack", "rollbackVnf");
+ logger.info("{} {} {}", MessageEnum.RA_ROLLBACK_NULL.toString(), "OpenStack", "rollbackVnf");
return;
}
@@ -298,104 +256,102 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
}
// Get the elements of the VnfRollback object for easier access
- String cloudSiteId = rollback.getCloudSiteId ();
+ String cloudSiteId = rollback.getCloudSiteId();
String cloudOwner = rollback.getCloudOwner();
- String tenantId = rollback.getTenantId ();
- String vfModuleId = rollback.getVfModuleStackId ();
+ String tenantId = rollback.getTenantId();
+ String vfModuleId = rollback.getVfModuleStackId();
logger.debug("Rolling Back VF Module {} in {}", vfModuleId, cloudOwner + "/" + cloudSiteId + "/" + tenantId);
- DeploymentInfo deployment = null;
+ DeploymentInfo deployment = null;
// Use the MsoCloudifyUtils to delete the deployment. Set the polling flag to true.
// The possible outcomes of deleteStack are a StackInfo object with status
// of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException
// could be thrown.
- long subStartTime = System.currentTimeMillis ();
+ long subStartTime = System.currentTimeMillis();
try {
- // KLUDGE - Cloudify requires Tenant Name for Openstack. We have the ID.
- // Go directly to Keystone until APIs could be updated to supply the name.
- MsoTenant msoTenant = keystoneUtils.queryTenant(tenantId, cloudSiteId);
- String tenantName = (msoTenant != null? msoTenant.getTenantName() : tenantId);
+ // KLUDGE - Cloudify requires Tenant Name for Openstack. We have the ID.
+ // Go directly to Keystone until APIs could be updated to supply the name.
+ MsoTenant msoTenant = keystoneUtils.queryTenant(tenantId, cloudSiteId);
+ String tenantName = (msoTenant != null ? msoTenant.getTenantName() : tenantId);
- // TODO: Get a reasonable timeout. Use a global property, or store the creation timeout in rollback object and use that.
+ // TODO: Get a reasonable timeout. Use a global property, or store the creation timeout in rollback object
+ // and use that.
deployment = cloudifyUtils.uninstallAndDeleteDeployment(cloudSiteId, tenantName, vfModuleId, 5);
logger.debug("Rolled back deployment: {}", deployment.getId());
} catch (MsoException me) {
// Failed to rollback the VNF due to a cloudify exception.
// Convert to a generic VnfException
- me.addContext ("RollbackVNF");
- String error = "Rollback VF Module: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, cloudSiteId,
- tenantId, CLOUDIFY, "DeleteDeployment", ErrorCode.DataError.getValue(),
- "Exception - DeleteDeployment", me);
+ me.addContext("RollbackVNF");
+ String error = "Rollback VF Module: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/"
+ + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner,
+ cloudSiteId, tenantId, CLOUDIFY, "DeleteDeployment", ErrorCode.DataError.getValue(),
+ "Exception - DeleteDeployment", me);
logger.debug(error);
- throw new VnfException (me);
+ throw new VnfException(me);
}
return;
}
- private VnfStatus deploymentStatusToVnfStatus (DeploymentInfo deployment) {
- // Determine the status based on last action & status
- // DeploymentInfo object should be enhanced to report a better status internally.
- DeploymentStatus status = deployment.getStatus();
- String lastAction = deployment.getLastAction();
-
- if (status == null || lastAction == null) {
- return VnfStatus.UNKNOWN;
- }
- else if (status == DeploymentStatus.NOTFOUND) {
- return VnfStatus.NOTFOUND;
- }
- else if (status == DeploymentStatus.INSTALLED) {
- return VnfStatus.ACTIVE;
- }
- else if (status == DeploymentStatus.CREATED) {
- // Should have an INACTIVE status for this case. Shouldn't really happen, but
- // Install was never run, or Uninstall was done but deployment didn't get deleted.
- return VnfStatus.UNKNOWN;
- }
- else if (status == DeploymentStatus.FAILED) {
- return VnfStatus.FAILED;
- }
-
- return VnfStatus.UNKNOWN;
+ private VnfStatus deploymentStatusToVnfStatus(DeploymentInfo deployment) {
+ // Determine the status based on last action & status
+ // DeploymentInfo object should be enhanced to report a better status internally.
+ DeploymentStatus status = deployment.getStatus();
+ String lastAction = deployment.getLastAction();
+
+ if (status == null || lastAction == null) {
+ return VnfStatus.UNKNOWN;
+ } else if (status == DeploymentStatus.NOTFOUND) {
+ return VnfStatus.NOTFOUND;
+ } else if (status == DeploymentStatus.INSTALLED) {
+ return VnfStatus.ACTIVE;
+ } else if (status == DeploymentStatus.CREATED) {
+ // Should have an INACTIVE status for this case. Shouldn't really happen, but
+ // Install was never run, or Uninstall was done but deployment didn't get deleted.
+ return VnfStatus.UNKNOWN;
+ } else if (status == DeploymentStatus.FAILED) {
+ return VnfStatus.FAILED;
+ }
+
+ return VnfStatus.UNKNOWN;
}
- private Map <String, String> copyStringOutputs (Map <String, Object> stackOutputs) {
- Map <String, String> stringOutputs = new HashMap <String, String> ();
- for (String key : stackOutputs.keySet ()) {
- if (stackOutputs.get (key) instanceof String) {
- stringOutputs.put (key, (String) stackOutputs.get (key));
- } else if (stackOutputs.get(key) instanceof Integer) {
- try {
- String str = "" + stackOutputs.get(key);
- stringOutputs.put(key, str);
- } catch (Exception e) {
- logger.debug("Unable to add " + key + " to outputs");
- }
+ private Map<String, String> copyStringOutputs(Map<String, Object> stackOutputs) {
+ Map<String, String> stringOutputs = new HashMap<String, String>();
+ for (String key : stackOutputs.keySet()) {
+ if (stackOutputs.get(key) instanceof String) {
+ stringOutputs.put(key, (String) stackOutputs.get(key));
+ } else if (stackOutputs.get(key) instanceof Integer) {
+ try {
+ String str = "" + stackOutputs.get(key);
+ stringOutputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("Unable to add " + key + " to outputs");
+ }
} else if (stackOutputs.get(key) instanceof JsonNode) {
- try {
- String str = this.convertNode((JsonNode) stackOutputs.get(key));
- stringOutputs.put(key, str);
- } catch (Exception e) {
- logger.debug("Unable to add " + key + " to outputs - exception converting JsonNode");
- }
+ try {
+ String str = this.convertNode((JsonNode) stackOutputs.get(key));
+ stringOutputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("Unable to add " + key + " to outputs - exception converting JsonNode");
+ }
} else if (stackOutputs.get(key) instanceof java.util.LinkedHashMap) {
- try {
- String str = JSON_MAPPER.writeValueAsString(stackOutputs.get(key));
- stringOutputs.put(key, str);
- } catch (Exception e) {
- logger.debug("Unable to add " + key + " to outputs - exception converting LinkedHashMap");
- }
+ try {
+ String str = JSON_MAPPER.writeValueAsString(stackOutputs.get(key));
+ stringOutputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("Unable to add " + key + " to outputs - exception converting LinkedHashMap");
+ }
} else {
- try {
- String str = stackOutputs.get(key).toString();
- stringOutputs.put(key, str);
- } catch (Exception e) {
- logger.debug("Unable to add " + key + " to outputs - unable to call .toString() " + e.getMessage());
- }
+ try {
+ String str = stackOutputs.get(key).toString();
+ stringOutputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("Unable to add " + key + " to outputs - unable to call .toString() " + e.getMessage());
+ }
}
}
return stringOutputs;
@@ -403,43 +359,41 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
private void sendMapToDebug(Map<String, Object> inputs, String optionalName) {
- int i = 0;
- StringBuilder sb = new StringBuilder(optionalName == null ? "\ninputs" : "\n" + optionalName);
- if (inputs == null) {
- sb.append("\tNULL");
- }
- else if (inputs.size() < 1) {
- sb.append("\tEMPTY");
- } else {
- for (String str : inputs.keySet()) {
- String outputString;
- try {
- outputString = inputs.get(str).toString();
- } catch (Exception e) {
- outputString = "Unable to call toString() on the value for " + str;
- }
- sb.append("\t\nitem " + i++ + ": '" + str + "'='" + outputString + "'");
- }
- }
- logger.debug(sb.toString());
- return;
+ int i = 0;
+ StringBuilder sb = new StringBuilder(optionalName == null ? "\ninputs" : "\n" + optionalName);
+ if (inputs == null) {
+ sb.append("\tNULL");
+ } else if (inputs.size() < 1) {
+ sb.append("\tEMPTY");
+ } else {
+ for (String str : inputs.keySet()) {
+ String outputString;
+ try {
+ outputString = inputs.get(str).toString();
+ } catch (Exception e) {
+ outputString = "Unable to call toString() on the value for " + str;
+ }
+ sb.append("\t\nitem " + i++ + ": '" + str + "'='" + outputString + "'");
+ }
+ }
+ logger.debug(sb.toString());
+ return;
}
private void sendMapToDebug(Map<String, Object> inputs) {
- int i = 0;
- StringBuilder sb = new StringBuilder("inputs:");
- if (inputs == null) {
- sb.append("\tNULL");
- }
- else if (inputs.size() < 1) {
- sb.append("\tEMPTY");
- } else {
- for (String str : inputs.keySet()) {
- sb.append("\titem " + i++ + ": " + str + "=" + inputs.get(str));
- }
- }
- logger.debug(sb.toString());
- return;
+ int i = 0;
+ StringBuilder sb = new StringBuilder("inputs:");
+ if (inputs == null) {
+ sb.append("\tNULL");
+ } else if (inputs.size() < 1) {
+ sb.append("\tEMPTY");
+ } else {
+ for (String str : inputs.keySet()) {
+ sb.append("\titem " + i++ + ": " + str + "=" + inputs.get(str));
+ }
+ }
+ logger.debug(sb.toString());
+ return;
}
private String convertNode(final JsonNode node) {
@@ -465,15 +419,15 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
Object obj = objectMap.get(key);
if (obj instanceof String) {
stringMap.put(key, (String) objectMap.get(key));
- } else if (obj instanceof JsonNode ){
+ } else if (obj instanceof JsonNode) {
// This is a bit of mess - but I think it's the least impacting
// let's convert it BACK to a string - then it will get converted back later
try {
String str = this.convertNode((JsonNode) obj);
stringMap.put(key, str);
} catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode "+ key);
- //okay in this instance - only string values (fqdn) are expected to be needed
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode " + key);
+ // okay in this instance - only string values (fqdn) are expected to be needed
}
} else if (obj instanceof java.util.LinkedHashMap) {
logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
@@ -481,21 +435,22 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
String str = JSON_MAPPER.writeValueAsString(obj);
stringMap.put(key, str);
} catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap "+ key);
- }
- } else if (obj instanceof Integer) {
- try {
- String str = "" + obj;
- stringMap.put(key, str);
- } catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer "+ key);
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap " + key);
+ }
+ } else if (obj instanceof Integer) {
+ try {
+ String str = "" + obj;
+ stringMap.put(key, str);
+ } catch (Exception e) {
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer " + key);
}
} else {
try {
- String str = obj.toString();
+ String str = obj.toString();
stringMap.put(key, str);
} catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value "+ key + " (" + e.getMessage() + ")");
+ logger.debug(
+ "DANGER WILL ROBINSON: unable to convert value " + key + " (" + e.getMessage() + ")");
}
}
}
@@ -505,46 +460,38 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
}
/**
- * This is the "Create VF Module" web service implementation.
- * It will instantiate a new VF Module of the requested type in the specified cloud
- * and tenant. The tenant must exist before this service is called.
+ * This is the "Create VF Module" web service implementation. It will instantiate a new VF Module of the requested
+ * type in the specified cloud and tenant. The tenant must exist before this service is called.
*
- * If a VF Module with the same name already exists, this can be considered a
- * success or failure, depending on the value of the 'failIfExists' parameter.
+ * If a VF Module with the same name already exists, this can be considered a success or failure, depending on the
+ * value of the 'failIfExists' parameter.
*
- * All VF Modules are defined in the MSO catalog. The caller must request
- * one of the pre-defined module types or an error will be returned. Within the
- * catalog, each VF Module references (among other things) a cloud template
- * which is used to deploy the required artifacts (VMs, networks, etc.)
- * to the cloud. In this adapter implementation, that artifact is expected
- * to be a Cloudify blueprint.
+ * All VF Modules are defined in the MSO catalog. The caller must request one of the pre-defined module types or an
+ * error will be returned. Within the catalog, each VF Module references (among other things) a cloud template which
+ * is used to deploy the required artifacts (VMs, networks, etc.) to the cloud. In this adapter implementation, that
+ * artifact is expected to be a Cloudify blueprint.
*
- * Depending on the blueprint, a variable set of input parameters will
- * be defined, some of which are required. The caller is responsible to
- * pass the necessary input data for the module or an error will be thrown.
+ * Depending on the blueprint, a variable set of input parameters will be defined, some of which are required. The
+ * caller is responsible to pass the necessary input data for the module or an error will be thrown.
*
- * The method returns the vfModuleId, a Map of output attributes, and a VnfRollback
- * object. This last object can be passed as-is to the rollbackVnf operation to
- * undo everything that was created for the Module. This is useful if a VF module
- * is successfully created but the orchestration fails on a subsequent step.
+ * The method returns the vfModuleId, a Map of output attributes, and a VnfRollback object. This last object can be
+ * passed as-is to the rollbackVnf operation to undo everything that was created for the Module. This is useful if a
+ * VF module is successfully created but the orchestration fails on a subsequent step.
*
* @param cloudSiteId CLLI code of the cloud site in which to create the VNF
* @param cloudOwner cloud owner of the cloud site in which to create the VNF
* @param tenantId Openstack tenant identifier
- * @param vfModuleType VF Module type key, should match a VNF definition in catalog DB.
- * Deprecated - should use modelCustomizationUuid
- * @param vnfVersion VNF version key, should match a VNF definition in catalog DB
- * Deprecated - VF Module versions also captured by modelCustomizationUuid
+ * @param vfModuleType VF Module type key, should match a VNF definition in catalog DB. Deprecated - should use
+ * modelCustomizationUuid
+ * @param vnfVersion VNF version key, should match a VNF definition in catalog DB Deprecated - VF Module versions
+ * also captured by modelCustomizationUuid
* @param genericVnfId Generic VNF ID
* @param vfModuleName Name to be assigned to the new VF Module
* @param vfModuleId Id of the new VF Module
* @param requestType Indicates if this is a Volume Group or Module request
- * @param volumeGroupId Identifier (i.e. deployment ID) for a Volume Group
- * to attach to a VF Module
- * @param baseVfModuleId Identifier (i.e. deployment ID) of the Base Module if
- * this is an Add-on module
- * @param modelCustomizationUuid Unique ID for the VF Module's model. Replaces
- * the use of vfModuleType.
+ * @param volumeGroupId Identifier (i.e. deployment ID) for a Volume Group to attach to a VF Module
+ * @param baseVfModuleId Identifier (i.e. deployment ID) of the Base Module if this is an Add-on module
+ * @param modelCustomizationUuid Unique ID for the VF Module's model. Replaces the use of vfModuleType.
* @param inputs Map of key=value inputs for VNF stack creation
* @param failIfExists Flag whether already existing VNF should be considered
* @param backout Flag whether to suppress automatic backout (for testing)
@@ -554,68 +501,51 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
* @param rollback Holder for returning VnfRollback object
*/
@Override
- public void createVfModule(String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vfModuleType,
- String vnfVersion,
- String genericVnfId,
- String vfModuleName,
- String vfModuleId,
- String requestType,
- String volumeGroupId,
- String baseVfModuleId,
- String modelCustomizationUuid,
- Map <String, Object> inputs,
- Boolean failIfExists,
- Boolean backout,
- Boolean enableBridge,
- MsoRequest msoRequest,
- Holder <String> vnfId,
- Holder <Map <String, String>> outputs,
- Holder <VnfRollback> rollback)
- throws VnfException
- {
+ public void createVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vfModuleType,
+ String vnfVersion, String genericVnfId, String vfModuleName, String vfModuleId, String requestType,
+ String volumeGroupId, String baseVfModuleId, String modelCustomizationUuid, Map<String, Object> inputs,
+ Boolean failIfExists, Boolean backout, Boolean enableBridge, MsoRequest msoRequest, Holder<String> vnfId,
+ Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) throws VnfException {
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
- // Require a model customization ID. Every VF Module definition must have one.
+ // Require a model customization ID. Every VF Module definition must have one.
if (modelCustomizationUuid == null || modelCustomizationUuid.isEmpty()) {
logger.debug("Missing required input: modelCustomizationUuid");
String error = "Create vfModule error: Missing required input: modelCustomizationUuid";
logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(),
- "VF Module ModelCustomizationUuid", CLOUDIFY, ErrorCode.DataError.getValue(),
- "Create VF Module: Missing required input: modelCustomizationUuid");
+ "VF Module ModelCustomizationUuid", CLOUDIFY, ErrorCode.DataError.getValue(),
+ "Create VF Module: Missing required input: modelCustomizationUuid");
logger.debug(error);
throw new VnfException(error, MsoExceptionCategory.USERDATA);
}
// Clean up some inputs to make comparisons easier
if (requestType == null)
- requestType = "";
+ requestType = "";
if ("".equals(volumeGroupId) || "null".equals(volumeGroupId))
- volumeGroupId = null;
+ volumeGroupId = null;
if ("".equals(baseVfModuleId) || "null".equals(baseVfModuleId))
- baseVfModuleId = null;
+ baseVfModuleId = null;
if (inputs == null) {
- // Create an empty set of inputs
- inputs = new HashMap<>();
- logger.debug("inputs == null - setting to empty");
+ // Create an empty set of inputs
+ inputs = new HashMap<>();
+ logger.debug("inputs == null - setting to empty");
} else {
- this.sendMapToDebug(inputs);
+ this.sendMapToDebug(inputs);
}
// Check if this is for a "Volume" module
boolean isVolumeRequest = false;
if (requestType.startsWith("VOLUME")) {
- isVolumeRequest = true;
+ isVolumeRequest = true;
}
- logger.debug("requestType = " + requestType + ", volumeGroupStackId = " + volumeGroupId + ", baseStackId = " +
- baseVfModuleId);
+ logger.debug("requestType = " + requestType + ", volumeGroupStackId = " + volumeGroupId + ", baseStackId = "
+ + baseVfModuleId);
// Build a default rollback object (no actions performed)
VnfRollback vfRollback = new VnfRollback();
@@ -624,158 +554,161 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
vfRollback.setTenantId(tenantId);
vfRollback.setMsoRequest(msoRequest);
vfRollback.setRequestType(requestType);
- vfRollback.setIsBase(false); // Until we know better
+ vfRollback.setIsBase(false); // Until we know better
vfRollback.setVolumeGroupHeatStackId(volumeGroupId);
vfRollback.setBaseGroupHeatStackId(baseVfModuleId);
vfRollback.setModelCustomizationUuid(modelCustomizationUuid);
vfRollback.setMode("CFY");
- rollback.value = vfRollback; // Default rollback - no updates performed
+ rollback.value = vfRollback; // Default rollback - no updates performed
// Get the VNF/VF Module definition from the Catalog DB first.
- // There are three relevant records: VfModule, VfModuleCustomization, VnfResource
+ // There are three relevant records: VfModule, VfModuleCustomization, VnfResource
VfModule vf = null;
- VnfResource vnfResource = null;
- VfModuleCustomization vfmc = null;
+ VnfResource vnfResource = null;
+ VfModuleCustomization vfmc = null;
try {
vfmc = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(modelCustomizationUuid);
if (vfmc == null) {
String error = "Create vfModule error: Unable to find vfModuleCust with modelCustomizationUuid="
- + modelCustomizationUuid;
+ + modelCustomizationUuid;
logger.debug(error);
- logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module "
- + "ModelCustomizationUuid",
- modelCustomizationUuid, "CatalogDb", ErrorCode.DataError.getValue(), error);
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(),
+ "VF Module " + "ModelCustomizationUuid", modelCustomizationUuid, "CatalogDb",
+ ErrorCode.DataError.getValue(), error);
throw new VnfException(error, MsoExceptionCategory.USERDATA);
} else {
logger.debug("Found vfModuleCust entry " + vfmc.toString());
}
// Get the vfModule and vnfResource records
- vf = vfmc.getVfModule();
- vnfResource = vfmc.getVfModule().getVnfResources();
- }
- catch (Exception e) {
+ vf = vfmc.getVfModule();
+ vnfResource = vfmc.getVfModule().getVnfResources();
+ } catch (Exception e) {
- logger.debug("unhandled exception in create VF - [Query]" + e.getMessage());
- throw new VnfException("Exception during create VF " + e.getMessage());
+ logger.debug("unhandled exception in create VF - [Query]" + e.getMessage());
+ throw new VnfException("Exception during create VF " + e.getMessage());
}
- // Perform a version check against cloudSite
+ // Perform a version check against cloudSite
// Obtain the cloud site information where we will create the VF Module
- Optional<CloudSite> cloudSiteOp = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSiteOp = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSiteOp.isPresent()) {
- throw new VnfException (new MsoCloudSiteNotFound (cloudSiteId));
+ throw new VnfException(new MsoCloudSiteNotFound(cloudSiteId));
}
CloudSite cloudSite = cloudSiteOp.get();
- MavenLikeVersioning aicV = new MavenLikeVersioning();
- aicV.setVersion(cloudSite.getCloudVersion());
-
- String vnfMin = vnfResource.getAicVersionMin();
- String vnfMax = vnfResource.getAicVersionMax();
-
- if ( (vnfMin != null && !(aicV.isMoreRecentThan(vnfMin) || aicV.isTheSameVersion(vnfMin))) ||
- (vnfMax != null && aicV.isMoreRecentThan(vnfMax)))
- {
- // ERROR
- String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUUID()
- + " VersionMin=" + vnfMin + " VersionMax:" + vnfMax + " NOT supported on Cloud: " + cloudSiteId
- + " with AIC_Version:" + cloudSite.getCloudVersion();
- logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack",
- ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion");
- logger.debug(error);
- throw new VnfException(error, MsoExceptionCategory.USERDATA);
- }
- // End Version check
+ MavenLikeVersioning aicV = new MavenLikeVersioning();
+ aicV.setVersion(cloudSite.getCloudVersion());
+
+ String vnfMin = vnfResource.getAicVersionMin();
+ String vnfMax = vnfResource.getAicVersionMax();
+
+ if ((vnfMin != null && !(aicV.isMoreRecentThan(vnfMin) || aicV.isTheSameVersion(vnfMin)))
+ || (vnfMax != null && aicV.isMoreRecentThan(vnfMax))) {
+ // ERROR
+ String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid="
+ + vnfResource.getModelUUID() + " VersionMin=" + vnfMin + " VersionMax:" + vnfMax
+ + " NOT supported on Cloud: " + cloudSiteId + " with AIC_Version:" + cloudSite.getCloudVersion();
+ logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion");
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ }
+ // End Version check
DeploymentInfo cloudifyDeployment = null;
// First, look up to see if the VF already exists.
- long subStartTime1 = System.currentTimeMillis ();
+ long subStartTime1 = System.currentTimeMillis();
try {
- cloudifyDeployment = cloudifyUtils.queryDeployment (cloudSiteId, tenantId, vfModuleName);
- }
- catch (MsoException me) {
+ cloudifyDeployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, vfModuleName);
+ } catch (MsoException me) {
// Failed to query the Deployment due to a cloudify exception.
- String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ;
+ String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/"
+ + tenantId + ": " + me;
logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudSiteId,
- tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(),
- "Exception - queryDeployment", me);
+ tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(),
+ "Exception - queryDeployment", me);
logger.debug(error);
// Convert to a generic VnfException
- me.addContext ("CreateVFModule");
- throw new VnfException (me);
+ me.addContext("CreateVFModule");
+ throw new VnfException(me);
}
// More precise handling/messaging if the Module already exists
- if (cloudifyDeployment != null && !(cloudifyDeployment.getStatus () == DeploymentStatus.NOTFOUND)) {
- // CREATED, INSTALLED, INSTALLING, FAILED, UNINSTALLING, UNKNOWN
- DeploymentStatus status = cloudifyDeployment.getStatus();
- logger.debug ("Found Existing Deployment, status=" + status);
-
- if (status == DeploymentStatus.INSTALLED) {
- // fail - it exists
- if (failIfExists != null && failIfExists) {
- String error = "Create VF: Deployment " + vfModuleName + " already exists in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(),
- "Deployment " + vfModuleName + " already exists");
- logger.debug(error);
- throw new VnfAlreadyExists (vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId());
- } else {
- // Found existing deployment and client has not requested "failIfExists".
- // Populate the outputs from the existing deployment.
+ if (cloudifyDeployment != null && !(cloudifyDeployment.getStatus() == DeploymentStatus.NOTFOUND)) {
+ // CREATED, INSTALLED, INSTALLING, FAILED, UNINSTALLING, UNKNOWN
+ DeploymentStatus status = cloudifyDeployment.getStatus();
+ logger.debug("Found Existing Deployment, status=" + status);
+
+ if (status == DeploymentStatus.INSTALLED) {
+ // fail - it exists
+ if (failIfExists != null && failIfExists) {
+ String error = "Create VF: Deployment " + vfModuleName + " already exists in " + cloudOwner + "/"
+ + cloudSiteId + "/" + tenantId;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(),
+ vfModuleName, cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment",
+ ErrorCode.DataError.getValue(), "Deployment " + vfModuleName + " already exists");
+ logger.debug(error);
+ throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId,
+ cloudifyDeployment.getId());
+ } else {
+ // Found existing deployment and client has not requested "failIfExists".
+ // Populate the outputs from the existing deployment.
- vnfId.value = cloudifyDeployment.getId();
- outputs.value = copyStringOutputs (cloudifyDeployment.getOutputs ());
+ vnfId.value = cloudifyDeployment.getId();
+ outputs.value = copyStringOutputs(cloudifyDeployment.getOutputs());
return;
- }
- }
- // Check through various detailed error cases
- if (status == DeploymentStatus.INSTALLING || status == DeploymentStatus.UNINSTALLING) {
- // fail - it's in progress - return meaningful error
- String error = "Create VF: Deployment " + vfModuleName + " already exists and has status " + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; please wait for it to complete, or fix manually.";
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(),
- "Deployment " + vfModuleName + " already exists");
- logger.debug(error);
- throw new VnfAlreadyExists (vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId());
- }
- else if (status == DeploymentStatus.FAILED) {
- // fail - it exists and is in a FAILED state
- String error = "Create VF: Deployment " + vfModuleName + " already exists and is in FAILED state in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention.";
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(),
- "Deployment " + vfModuleName + " already " + "exists and is in FAILED state");
- logger.debug(error);
- throw new VnfAlreadyExists (vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId());
- }
- else if (status == DeploymentStatus.UNKNOWN || status == DeploymentStatus.CREATED) {
- // fail - it exists and is in a UNKNOWN state
- String error = "Create VF: Deployment " + vfModuleName + " already exists and has status " + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention.";
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(),
- "Deployment " + vfModuleName + " already " + "exists and is in " + status.toString() + " state");
- logger.debug(error);
- throw new VnfAlreadyExists (vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId());
- }
- else {
- // Unexpected, since all known status values have been tested for
- String error =
- "Create VF: Deployment " + vfModuleName + " already exists with unexpected status " + status
- .toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention.";
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(),
- "Deployment " + vfModuleName + " already " + "exists and is in an unknown state");
- logger.debug(error);
- throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId());
- }
+ }
+ }
+ // Check through various detailed error cases
+ if (status == DeploymentStatus.INSTALLING || status == DeploymentStatus.UNINSTALLING) {
+ // fail - it's in progress - return meaningful error
+ String error = "Create VF: Deployment " + vfModuleName + " already exists and has status "
+ + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + "; please wait for it to complete, or fix manually.";
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(),
+ "Deployment " + vfModuleName + " already exists");
+ logger.debug(error);
+ throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId());
+ } else if (status == DeploymentStatus.FAILED) {
+ // fail - it exists and is in a FAILED state
+ String error = "Create VF: Deployment " + vfModuleName + " already exists and is in FAILED state in "
+ + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention.";
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(),
+ "Deployment " + vfModuleName + " already " + "exists and is in FAILED state");
+ logger.debug(error);
+ throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId());
+ } else if (status == DeploymentStatus.UNKNOWN || status == DeploymentStatus.CREATED) {
+ // fail - it exists and is in a UNKNOWN state
+ String error = "Create VF: Deployment " + vfModuleName + " already exists and has status "
+ + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + "; requires manual intervention.";
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(),
+ "Deployment " + vfModuleName + " already " + "exists and is in " + status.toString()
+ + " state");
+ logger.debug(error);
+ throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId());
+ } else {
+ // Unexpected, since all known status values have been tested for
+ String error = "Create VF: Deployment " + vfModuleName + " already exists with unexpected status "
+ + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + "; requires manual intervention.";
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
+ cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(),
+ "Deployment " + vfModuleName + " already " + "exists and is in an unknown state");
+ logger.debug(error);
+ throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId());
+ }
}
@@ -785,43 +718,42 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
// If a Volume Group was provided, query its outputs for inclusion in Module input parameters
if (volumeGroupId != null) {
- long subStartTime2 = System.currentTimeMillis ();
+ long subStartTime2 = System.currentTimeMillis();
DeploymentInfo volumeDeployment = null;
try {
- volumeDeployment = cloudifyUtils.queryDeployment (cloudSiteId, tenantId, volumeGroupId);
- }
- catch (MsoException me) {
+ volumeDeployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, volumeGroupId);
+ } catch (MsoException me) {
// Failed to query the Volume GroupDeployment due to a cloudify exception.
- String error = "Create VF Module: Query Volume Group " + volumeGroupId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ;
+ String error = "Create VF Module: Query Volume Group " + volumeGroupId + " in " + cloudOwner + "/"
+ + cloudSiteId + "/" + tenantId + ": " + me;
logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId,
- cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment(volume)",
- ErrorCode.DataError.getValue(), "Exception - queryDeployment(volume)", me);
+ cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment(volume)",
+ ErrorCode.DataError.getValue(), "Exception - queryDeployment(volume)", me);
logger.debug(error);
// Convert to a generic VnfException
- me.addContext ("CreateVFModule(QueryVolume)");
- throw new VnfException (me);
+ me.addContext("CreateVFModule(QueryVolume)");
+ throw new VnfException(me);
}
- if (volumeDeployment == null || volumeDeployment.getStatus() == DeploymentStatus.NOTFOUND) {
- String error =
- "Create VFModule: Attached Volume Group DOES NOT EXIST " + volumeGroupId + " in " + cloudSiteId + "/"
- + tenantId + " USER ERROR";
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId,
- cloudSiteId, tenantId, error, CLOUDIFY, "queryDeployment(volume)",
- ErrorCode.BusinessProcesssError.getValue(),
- "Create VFModule: Attached Volume Group DOES NOT EXIST");
- logger.debug(error);
- throw new VnfException(error, MsoExceptionCategory.USERDATA);
- } else {
- logger.debug("Found nested volume group");
- volumeGroupOutputs = volumeDeployment.getOutputs();
- this.sendMapToDebug(volumeGroupOutputs, "volumeGroupOutputs");
- }
+ if (volumeDeployment == null || volumeDeployment.getStatus() == DeploymentStatus.NOTFOUND) {
+ String error = "Create VFModule: Attached Volume Group DOES NOT EXIST " + volumeGroupId + " in "
+ + cloudSiteId + "/" + tenantId + " USER ERROR";
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId,
+ cloudSiteId, tenantId, error, CLOUDIFY, "queryDeployment(volume)",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create VFModule: Attached Volume Group DOES NOT EXIST");
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ } else {
+ logger.debug("Found nested volume group");
+ volumeGroupOutputs = volumeDeployment.getOutputs();
+ this.sendMapToDebug(volumeGroupOutputs, "volumeGroupOutputs");
+ }
}
// If this is an Add-On Module, query the Base Module outputs
// Note: This will be performed whether or not the current request is for an
- // Add-On Volume Group or Add-On VF Module
+ // Add-On Volume Group or Add-On VF Module
if (vf.getIsBase()) {
logger.debug("This is a BASE Module request");
@@ -832,37 +764,34 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
// Add-On Modules should always have a Base, but just treat as a warning if not provided.
// Add-on Volume requests may or may not specify a base.
if (!isVolumeRequest && baseVfModuleId == null) {
- logger.debug ("WARNING: Add-on Module request - no Base Module ID provided");
+ logger.debug("WARNING: Add-on Module request - no Base Module ID provided");
}
if (baseVfModuleId != null) {
- long subStartTime2 = System.currentTimeMillis ();
- DeploymentInfo baseDeployment = null;
- try {
- baseDeployment = cloudifyUtils.queryDeployment (cloudSiteId, tenantId, baseVfModuleId);
- }
- catch (MsoException me) {
- // Failed to query the Volume GroupDeployment due to a cloudify exception.
- String error =
- "Create VF Module: Query Base " + baseVfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": "
- + me;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId,
- cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment(Base)",
- ErrorCode.DataError.getValue(), "Exception - queryDeployment(Base)", me);
- logger.debug(error);
- // Convert to a generic VnfException
- me.addContext("CreateVFModule(QueryBase)");
- throw new VnfException (me);
- }
+ long subStartTime2 = System.currentTimeMillis();
+ DeploymentInfo baseDeployment = null;
+ try {
+ baseDeployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, baseVfModuleId);
+ } catch (MsoException me) {
+ // Failed to query the Volume GroupDeployment due to a cloudify exception.
+ String error = "Create VF Module: Query Base " + baseVfModuleId + " in " + cloudOwner + "/"
+ + cloudSiteId + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId,
+ cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment(Base)",
+ ErrorCode.DataError.getValue(), "Exception - queryDeployment(Base)", me);
+ logger.debug(error);
+ // Convert to a generic VnfException
+ me.addContext("CreateVFModule(QueryBase)");
+ throw new VnfException(me);
+ }
if (baseDeployment == null || baseDeployment.getStatus() == DeploymentStatus.NOTFOUND) {
- String error =
- "Create VFModule: Base Module DOES NOT EXIST " + baseVfModuleId + " in " + cloudSiteId + "/"
- + tenantId + " USER ERROR";
+ String error = "Create VFModule: Base Module DOES NOT EXIST " + baseVfModuleId + " in "
+ + cloudSiteId + "/" + tenantId + " USER ERROR";
logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId,
- cloudSiteId, tenantId, error, CLOUDIFY, "queryDeployment(Base)",
- ErrorCode.BusinessProcesssError.getValue(),
- "Create VFModule: Base " + "Module DOES NOT EXIST");
+ cloudSiteId, tenantId, error, CLOUDIFY, "queryDeployment(Base)",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create VFModule: Base " + "Module DOES NOT EXIST");
logger.debug(error);
throw new VnfException(error, MsoExceptionCategory.USERDATA);
} else {
@@ -876,36 +805,36 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
// Ready to deploy the new VNF
- // NOTE: For this section, heatTemplate is used for both HEAT templates and Cloudify blueprints.
+ // NOTE: For this section, heatTemplate is used for both HEAT templates and Cloudify blueprints.
// In final implementation (post-POC), the template object would either be generic or there would
// be a separate DB Table/Object for Blueprints.
- // NOTE: The template is fixed for the VF Module. The environment is part of the customization.
+ // NOTE: The template is fixed for the VF Module. The environment is part of the customization.
HeatTemplate heatTemplate = null;
HeatEnvironment heatEnvironment = null;
if (isVolumeRequest) {
- heatTemplate = vf.getVolumeHeatTemplate();
- heatEnvironment = vfmc.getVolumeHeatEnv();
- } else {
- heatTemplate = vf.getModuleHeatTemplate();
- heatEnvironment = vfmc.getHeatEnvironment();
- }
-
- if (heatTemplate == null) {
- String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + ", reqType="
- + requestType;
- logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", vfModuleType,
- "OpenStack", ErrorCode.DataError.getValue(), error);
- throw new VnfException(error, MsoExceptionCategory.INTERNAL);
- } else {
- logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate());
- }
+ heatTemplate = vf.getVolumeHeatTemplate();
+ heatEnvironment = vfmc.getVolumeHeatEnv();
+ } else {
+ heatTemplate = vf.getModuleHeatTemplate();
+ heatEnvironment = vfmc.getHeatEnvironment();
+ }
+
+ if (heatTemplate == null) {
+ String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType
+ + ", reqType=" + requestType;
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID",
+ vfModuleType, "OpenStack", ErrorCode.DataError.getValue(), error);
+ throw new VnfException(error, MsoExceptionCategory.INTERNAL);
+ } else {
+ logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate());
+ }
if (heatEnvironment == null) {
String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType;
logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID",
- "OpenStack", ErrorCode.DataError.getValue(), error);
+ "OpenStack", ErrorCode.DataError.getValue(), error);
// Alarm on this error, configuration must be fixed
throw new VnfException(error, MsoExceptionCategory.INTERNAL);
} else {
@@ -915,260 +844,252 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
try {
// All variables converted to their native object types
- HashMap<String, Object> goldenInputs = new HashMap<String,Object>();
+ HashMap<String, Object> goldenInputs = new HashMap<String, Object>();
List<String> extraInputs = new ArrayList<String>();
- // NOTE: SKIP THIS FOR CLOUDIFY for now. Just use what was passed in.
- // This whole section needs to be rewritten.
- Boolean skipInputChecks = false;
-
- if (skipInputChecks) {
- goldenInputs = new HashMap<String,Object>();
- for (String key : inputs.keySet()) {
- goldenInputs.put(key, inputs.get(key));
- }
- }
- else {
- // Build maps for the parameters (including aliases) to simplify checks
- HashMap<String, HeatTemplateParam> params = new HashMap<String, HeatTemplateParam>();
-
- Set<HeatTemplateParam> paramSet = heatTemplate.getParameters();
- logger.debug("paramSet has {} entries", paramSet.size());
-
- for (HeatTemplateParam htp : paramSet) {
- params.put(htp.getParamName(), htp);
-
- // Include aliases.
- String alias = htp.getParamAlias();
- if (alias != null && !alias.equals("") && !params.containsKey(alias)) {
- params.put(alias, htp);
- }
- }
-
- // First, convert all inputs to their "template" type
- for (String key : inputs.keySet()) {
- if (params.containsKey(key)) {
- Object value = cloudifyUtils.convertInputValue(inputs.get(key), params.get(key));
- if (value != null) {
- goldenInputs.put(key, value);
- }
- else {
- logger.debug("Failed to convert input " + key + "='" + inputs.get(key) + "' to " + params.get(key)
- .getParamType());
- }
- } else {
- extraInputs.add(key);
- }
- }
-
- if (!extraInputs.isEmpty()) {
- logger.debug("Ignoring extra inputs: " + extraInputs);
- }
-
- // Next add in Volume Group Outputs if there are any. Copy directly without conversions.
- if (volumeGroupOutputs != null && !volumeGroupOutputs.isEmpty()) {
- for (String key : volumeGroupOutputs.keySet()) {
- if (params.containsKey(key) && !goldenInputs.containsKey(key)) {
- goldenInputs.put(key, volumeGroupOutputs.get(key));
- }
- }
- }
-
- // Next add in Base Module Outputs if there are any. Copy directly without conversions.
- if (baseModuleOutputs != null && !baseModuleOutputs.isEmpty()) {
- for (String key : baseModuleOutputs.keySet()) {
- if (params.containsKey(key) && !goldenInputs.containsKey(key)) {
- goldenInputs.put(key, baseModuleOutputs.get(key));
- }
- }
- }
-
- // Last, add in values from the "environment" file.
- // These are added to the inputs, since Cloudify doesn't pass an environment file like Heat.
-
- // TODO: This may take a different form for Cloudify, but for now process it
- // with Heat environment file syntax
+ // NOTE: SKIP THIS FOR CLOUDIFY for now. Just use what was passed in.
+ // This whole section needs to be rewritten.
+ Boolean skipInputChecks = false;
+
+ if (skipInputChecks) {
+ goldenInputs = new HashMap<String, Object>();
+ for (String key : inputs.keySet()) {
+ goldenInputs.put(key, inputs.get(key));
+ }
+ } else {
+ // Build maps for the parameters (including aliases) to simplify checks
+ HashMap<String, HeatTemplateParam> params = new HashMap<String, HeatTemplateParam>();
+
+ Set<HeatTemplateParam> paramSet = heatTemplate.getParameters();
+ logger.debug("paramSet has {} entries", paramSet.size());
+
+ for (HeatTemplateParam htp : paramSet) {
+ params.put(htp.getParamName(), htp);
+
+ // Include aliases.
+ String alias = htp.getParamAlias();
+ if (alias != null && !alias.equals("") && !params.containsKey(alias)) {
+ params.put(alias, htp);
+ }
+ }
+
+ // First, convert all inputs to their "template" type
+ for (String key : inputs.keySet()) {
+ if (params.containsKey(key)) {
+ Object value = cloudifyUtils.convertInputValue(inputs.get(key), params.get(key));
+ if (value != null) {
+ goldenInputs.put(key, value);
+ } else {
+ logger.debug("Failed to convert input " + key + "='" + inputs.get(key) + "' to "
+ + params.get(key).getParamType());
+ }
+ } else {
+ extraInputs.add(key);
+ }
+ }
+
+ if (!extraInputs.isEmpty()) {
+ logger.debug("Ignoring extra inputs: " + extraInputs);
+ }
+
+ // Next add in Volume Group Outputs if there are any. Copy directly without conversions.
+ if (volumeGroupOutputs != null && !volumeGroupOutputs.isEmpty()) {
+ for (String key : volumeGroupOutputs.keySet()) {
+ if (params.containsKey(key) && !goldenInputs.containsKey(key)) {
+ goldenInputs.put(key, volumeGroupOutputs.get(key));
+ }
+ }
+ }
+
+ // Next add in Base Module Outputs if there are any. Copy directly without conversions.
+ if (baseModuleOutputs != null && !baseModuleOutputs.isEmpty()) {
+ for (String key : baseModuleOutputs.keySet()) {
+ if (params.containsKey(key) && !goldenInputs.containsKey(key)) {
+ goldenInputs.put(key, baseModuleOutputs.get(key));
+ }
+ }
+ }
+
+ // Last, add in values from the "environment" file.
+ // These are added to the inputs, since Cloudify doesn't pass an environment file like Heat.
+
+ // TODO: This may take a different form for Cloudify, but for now process it
+ // with Heat environment file syntax
StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment());
- MsoHeatEnvironmentEntry mhee = new MsoHeatEnvironmentEntry (sb);
-
- if (mhee.getParameters() != null) {
- for (MsoHeatEnvironmentParameter envParam : mhee.getParameters()) {
- // If this is a template input, copy to golden inputs
- String envKey = envParam.getName();
- if (params.containsKey(envKey) && !goldenInputs.containsKey(envKey)) {
- Object value = cloudifyUtils.convertInputValue(envParam.getValue(), params.get(envKey));
- if (value != null) {
- goldenInputs.put(envKey, value);
- }
- else {
- logger.debug("Failed to convert environment parameter " + envKey + "='" + envParam.getValue() + "' to " +
- params.get(envKey).getParamType());
- }
- }
- }
- }
-
- this.sendMapToDebug(goldenInputs, "Final inputs sent to Cloudify");
-
-
- // Check that required parameters have been supplied from any of the sources
- String missingParams = null;
- boolean checkRequiredParameters = true;
- try {
- String propertyString = this.environment.getProperty(MsoVnfCloudifyAdapterImpl.CHECK_REQD_PARAMS);
- if ("false".equalsIgnoreCase (propertyString) || "n".equalsIgnoreCase (propertyString)) {
- checkRequiredParameters = false;
- logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking... {}",
- MsoVnfCloudifyAdapterImpl.CHECK_REQD_PARAMS);
- }
- } catch (Exception e) {
- // No problem - default is true
- logger.debug("An exception occured trying to get property {}",
- MsoVnfCloudifyAdapterImpl.CHECK_REQD_PARAMS, e);
- }
-
-
- for (HeatTemplateParam parm : heatTemplate.getParameters ()) {
- if (parm.isRequired () && (!goldenInputs.containsKey (parm.getParamName ()))) {
- logger.debug("adding to missing parameters list: {}", parm.getParamName());
- if (missingParams == null) {
- missingParams = parm.getParamName();
- } else {
- missingParams += "," + parm.getParamName();
- }
- }
- }
-
- if (missingParams != null) {
- if (checkRequiredParameters) {
- // Problem - missing one or more required parameters
- String error = "Create VFModule: Missing Required inputs: " + missingParams;
- logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, CLOUDIFY,
- ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs");
- logger.debug(error);
- throw new VnfException(error, MsoExceptionCategory.USERDATA);
- } else {
- logger.debug(
- "found missing parameters [" + missingParams + "] - but checkRequiredParameters is false -"
- + " will not block");
- }
- } else {
- logger.debug("No missing parameters found - ok to proceed");
- }
-
- } // NOTE: END PARAMETER CHECKING
-
- // Ready to deploy the VF Module.
- // *First step - make sure the blueprint is loaded into Cloudify.
- String blueprintName = heatTemplate.getTemplateName();
- String blueprint = heatTemplate.getTemplateBody();
- String blueprintId = blueprintName;
-
- // Use the main blueprint name as the blueprint ID (strip yaml extensions).
+ MsoHeatEnvironmentEntry mhee = new MsoHeatEnvironmentEntry(sb);
+
+ if (mhee.getParameters() != null) {
+ for (MsoHeatEnvironmentParameter envParam : mhee.getParameters()) {
+ // If this is a template input, copy to golden inputs
+ String envKey = envParam.getName();
+ if (params.containsKey(envKey) && !goldenInputs.containsKey(envKey)) {
+ Object value = cloudifyUtils.convertInputValue(envParam.getValue(), params.get(envKey));
+ if (value != null) {
+ goldenInputs.put(envKey, value);
+ } else {
+ logger.debug("Failed to convert environment parameter " + envKey + "='"
+ + envParam.getValue() + "' to " + params.get(envKey).getParamType());
+ }
+ }
+ }
+ }
+
+ this.sendMapToDebug(goldenInputs, "Final inputs sent to Cloudify");
+
+
+ // Check that required parameters have been supplied from any of the sources
+ String missingParams = null;
+ boolean checkRequiredParameters = true;
+ try {
+ String propertyString = this.environment.getProperty(MsoVnfCloudifyAdapterImpl.CHECK_REQD_PARAMS);
+ if ("false".equalsIgnoreCase(propertyString) || "n".equalsIgnoreCase(propertyString)) {
+ checkRequiredParameters = false;
+ logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking... {}",
+ MsoVnfCloudifyAdapterImpl.CHECK_REQD_PARAMS);
+ }
+ } catch (Exception e) {
+ // No problem - default is true
+ logger.debug("An exception occured trying to get property {}",
+ MsoVnfCloudifyAdapterImpl.CHECK_REQD_PARAMS, e);
+ }
+
+
+ for (HeatTemplateParam parm : heatTemplate.getParameters()) {
+ if (parm.isRequired() && (!goldenInputs.containsKey(parm.getParamName()))) {
+ logger.debug("adding to missing parameters list: {}", parm.getParamName());
+ if (missingParams == null) {
+ missingParams = parm.getParamName();
+ } else {
+ missingParams += "," + parm.getParamName();
+ }
+ }
+ }
+
+ if (missingParams != null) {
+ if (checkRequiredParameters) {
+ // Problem - missing one or more required parameters
+ String error = "Create VFModule: Missing Required inputs: " + missingParams;
+ logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, CLOUDIFY,
+ ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs");
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ } else {
+ logger.debug("found missing parameters [" + missingParams
+ + "] - but checkRequiredParameters is false -" + " will not block");
+ }
+ } else {
+ logger.debug("No missing parameters found - ok to proceed");
+ }
+
+ } // NOTE: END PARAMETER CHECKING
+
+ // Ready to deploy the VF Module.
+ // *First step - make sure the blueprint is loaded into Cloudify.
+ String blueprintName = heatTemplate.getTemplateName();
+ String blueprint = heatTemplate.getTemplateBody();
+ String blueprintId = blueprintName;
+
+ // Use the main blueprint name as the blueprint ID (strip yaml extensions).
if (blueprintId.endsWith(".yaml"))
- blueprintId = blueprintId.substring(0,blueprintId.lastIndexOf(".yaml"));
-
- try {
- if (! cloudifyUtils.isBlueprintLoaded (cloudSiteId, blueprintId)) {
- logger.debug("Blueprint " + blueprintId + " is not loaded. Will upload it now.");
-
- Map<String,byte[]> blueprintFiles = new HashMap<String,byte[]>();
-
- blueprintFiles.put(blueprintName, blueprint.getBytes());
-
- // TODO: Implement nested blueprint logic based on Cloudify structures.
- // For now, just use the Heat structures.
- // The query returns a map of String->Object, where the map keys provide one layer of
- // indirection from the Heat template names. For this case, assume the map key matches
- // the nested blueprint name.
- List<HeatTemplate> nestedBlueprints = heatTemplate.getChildTemplates();
- if (nestedBlueprints != null) {
- for (HeatTemplate nestedBlueprint: nestedBlueprints) {
- blueprintFiles.put(nestedBlueprint.getTemplateName(), nestedBlueprint.getTemplateBody().getBytes());
- }
- }
-
- // TODO: Implement file artifact logic based on Cloudify structures.
- // For now, just use the Heat structures.
- List<HeatFiles> heatFiles = vf.getHeatFiles();
- if (heatFiles != null) {
- for (HeatFiles heatFile: heatFiles) {
- blueprintFiles.put(heatFile.getFileName(), heatFile.getFileBody().getBytes());
- }
- }
-
- // Upload the blueprint package
- cloudifyUtils.uploadBlueprint(cloudSiteId, blueprintId, blueprintName, blueprintFiles, false);
-
- }
- }
-
- catch (MsoException me) {
- me.addContext("CreateVFModule");
- String error = "Create VF Module: Upload blueprint failed. Blueprint=" + blueprintName + ": " + me;
- logger.error("{} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudSiteId,
- tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), "MsoException - uploadBlueprint", me);
- logger.debug(error);
- throw new VnfException(me);
- }
+ blueprintId = blueprintId.substring(0, blueprintId.lastIndexOf(".yaml"));
+
+ try {
+ if (!cloudifyUtils.isBlueprintLoaded(cloudSiteId, blueprintId)) {
+ logger.debug("Blueprint " + blueprintId + " is not loaded. Will upload it now.");
+
+ Map<String, byte[]> blueprintFiles = new HashMap<String, byte[]>();
+
+ blueprintFiles.put(blueprintName, blueprint.getBytes());
+
+ // TODO: Implement nested blueprint logic based on Cloudify structures.
+ // For now, just use the Heat structures.
+ // The query returns a map of String->Object, where the map keys provide one layer of
+ // indirection from the Heat template names. For this case, assume the map key matches
+ // the nested blueprint name.
+ List<HeatTemplate> nestedBlueprints = heatTemplate.getChildTemplates();
+ if (nestedBlueprints != null) {
+ for (HeatTemplate nestedBlueprint : nestedBlueprints) {
+ blueprintFiles.put(nestedBlueprint.getTemplateName(),
+ nestedBlueprint.getTemplateBody().getBytes());
+ }
+ }
+
+ // TODO: Implement file artifact logic based on Cloudify structures.
+ // For now, just use the Heat structures.
+ List<HeatFiles> heatFiles = vf.getHeatFiles();
+ if (heatFiles != null) {
+ for (HeatFiles heatFile : heatFiles) {
+ blueprintFiles.put(heatFile.getFileName(), heatFile.getFileBody().getBytes());
+ }
+ }
+
+ // Upload the blueprint package
+ cloudifyUtils.uploadBlueprint(cloudSiteId, blueprintId, blueprintName, blueprintFiles, false);
+
+ }
+ }
+
+ catch (MsoException me) {
+ me.addContext("CreateVFModule");
+ String error = "Create VF Module: Upload blueprint failed. Blueprint=" + blueprintName + ": " + me;
+ logger.error("{} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType,
+ cloudSiteId, tenantId, CLOUDIFY, ErrorCode.DataError.getValue(),
+ "MsoException - uploadBlueprint", me);
+ logger.debug(error);
+ throw new VnfException(me);
+ }
// Ignore MsoTenantNotFound and MsoStackAlreadyExists exceptions
// because we already checked for those.
- long createDeploymentStarttime = System.currentTimeMillis ();
+ long createDeploymentStarttime = System.currentTimeMillis();
try {
- // KLUDGE - Cloudify requires Tenant Name for Openstack. We have the ID.
- // Go directly to Keystone until APIs could be updated to supply the name.
- MsoTenant msoTenant = keystoneUtils.queryTenant(tenantId, cloudSiteId);
- String tenantName = (msoTenant != null? msoTenant.getTenantName() : tenantId);
-
- if (backout == null) {
- backout = true;
- }
-
- cloudifyDeployment = cloudifyUtils.createAndInstallDeployment (cloudSiteId,
- tenantName,
- vfModuleName,
- blueprintId,
- goldenInputs,
- true,
- heatTemplate.getTimeoutMinutes (),
- backout.booleanValue());
+ // KLUDGE - Cloudify requires Tenant Name for Openstack. We have the ID.
+ // Go directly to Keystone until APIs could be updated to supply the name.
+ MsoTenant msoTenant = keystoneUtils.queryTenant(tenantId, cloudSiteId);
+ String tenantName = (msoTenant != null ? msoTenant.getTenantName() : tenantId);
+
+ if (backout == null) {
+ backout = true;
+ }
+
+ cloudifyDeployment = cloudifyUtils.createAndInstallDeployment(cloudSiteId, tenantName, vfModuleName,
+ blueprintId, goldenInputs, true, heatTemplate.getTimeoutMinutes(), backout.booleanValue());
} catch (MsoException me) {
- me.addContext ("CreateVFModule");
- String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger
- .error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId,
- tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), "MsoException - createDeployment",
- me);
+ me.addContext("CreateVFModule");
+ String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/"
+ + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType,
+ cloudOwner, cloudSiteId, tenantId, CLOUDIFY, ErrorCode.DataError.getValue(),
+ "MsoException - createDeployment", me);
logger.debug(error);
- throw new VnfException (me);
+ throw new VnfException(me);
} catch (NullPointerException npe) {
- String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + npe;
- logger
- .error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId,
- tenantId, CLOUDIFY, ErrorCode.DataError.getValue(),
+ String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/"
+ + tenantId + ": " + npe;
+ logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType,
+ cloudOwner, cloudSiteId, tenantId, CLOUDIFY, ErrorCode.DataError.getValue(),
"NullPointerException - createDeployment", npe);
logger.debug(error);
logger.debug("NULL POINTER EXCEPTION at cloudify.createAndInstallDeployment");
- //npe.addContext ("CreateVNF");
- throw new VnfException ("NullPointerException during cloudify.createAndInstallDeployment");
+ // npe.addContext ("CreateVNF");
+ throw new VnfException("NullPointerException during cloudify.createAndInstallDeployment");
} catch (Exception e) {
logger.debug("unhandled exception at cloudify.createAndInstallDeployment");
- throw new VnfException("Exception during cloudify.createAndInstallDeployment! " + e.getMessage());
+ throw new VnfException("Exception during cloudify.createAndInstallDeployment! " + e.getMessage());
}
} catch (Exception e) {
- logger.debug("unhandled exception in create VF");
- throw new VnfException("Exception during create VF " + e.getMessage());
+ logger.debug("unhandled exception in create VF");
+ throw new VnfException("Exception during create VF " + e.getMessage());
}
// Reach this point if create is successful.
// Populate remaining rollback info and response parameters.
- vfRollback.setVnfCreated (true);
- vfRollback.setVnfId (cloudifyDeployment.getId());
+ vfRollback.setVnfCreated(true);
+ vfRollback.setVnfId(cloudifyDeployment.getId());
vnfId.value = cloudifyDeployment.getId();
- outputs.value = copyStringOutputs (cloudifyDeployment.getOutputs ());
+ outputs.value = copyStringOutputs(cloudifyDeployment.getOutputs());
rollback.value = vfRollback;
@@ -1176,48 +1097,47 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
return;
}
- public void deleteVfModule (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfName,
- MsoRequest msoRequest,
- Holder <Map <String, String>> outputs) throws VnfException {
- logger.debug ("Deleting VF " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId);
+ public void deleteVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfName,
+ MsoRequest msoRequest, Holder<Map<String, String>> outputs) throws VnfException {
+ logger.debug("Deleting VF " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
// 1702 capture the output parameters on a delete
// so we'll need to query first
DeploymentInfo deployment = null;
try {
- deployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, vnfName);
+ deployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, vnfName);
} catch (MsoException me) {
- // Failed to query the deployment. Convert to a generic VnfException
- me.addContext ("DeleteVFModule");
- String error = "Delete VFModule: Query to get outputs: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId,
- tenantId, CLOUDIFY, "QueryDeployment", ErrorCode.DataError.getValue(),
- "Exception - QueryDeployment", me);
+ // Failed to query the deployment. Convert to a generic VnfException
+ me.addContext("DeleteVFModule");
+ String error = "Delete VFModule: Query to get outputs: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId
+ + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner,
+ cloudSiteId, tenantId, CLOUDIFY, "QueryDeployment", ErrorCode.DataError.getValue(),
+ "Exception - QueryDeployment", me);
logger.debug(error);
- throw new VnfException (me);
+ throw new VnfException(me);
}
- // call method which handles the conversion from Map<String,Object> to Map<String,String> for our expected Object types
+ // call method which handles the conversion from Map<String,Object> to Map<String,String> for our expected
+ // Object types
outputs.value = convertMapStringObjectToStringString(deployment.getOutputs());
// Use the MsoHeatUtils to delete the stack. Set the polling flag to true.
// The possible outcomes of deleteStack are a StackInfo object with status
// of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException
// could be thrown.
- long subStartTime = System.currentTimeMillis ();
+ long subStartTime = System.currentTimeMillis();
try {
cloudifyUtils.uninstallAndDeleteDeployment(cloudSiteId, tenantId, vnfName, 5);
} catch (MsoException me) {
me.addContext("DeleteVfModule");
// Convert to a generic VnfException
- String error = "Delete VF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId,
- tenantId, "DeleteDeployment", "DeleteDeployment", ErrorCode.DataError.getValue(),
- "Exception - DeleteDeployment: " + me.getMessage());
+ String error =
+ "Delete VF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner,
+ cloudSiteId, tenantId, "DeleteDeployment", "DeleteDeployment", ErrorCode.DataError.getValue(),
+ "Exception - DeleteDeployment: " + me.getMessage());
logger.debug(error);
throw new VnfException(me);
}
@@ -1226,27 +1146,16 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter {
return;
}
- // TODO: Should Update be supported for Cloudify? What would this look like?
+ // TODO: Should Update be supported for Cloudify? What would this look like?
@Override
- public void updateVfModule (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfType,
- String vnfVersion,
- String vnfName,
- String requestType,
- String volumeGroupHeatStackId,
- String baseVfHeatStackId,
- String vfModuleStackId,
- String modelCustomizationUuid,
- Map <String, Object> inputs,
- MsoRequest msoRequest,
- Holder <Map <String, String>> outputs,
- Holder <VnfRollback> rollback) throws VnfException
- {
- // This operation is not currently supported for Cloudify-orchestrated VF Modules.
- logger.debug("Update VF Module command attempted but not supported");
- throw new VnfException ("UpdateVfModule: Unsupported command", MsoExceptionCategory.USERDATA);
- }
+ public void updateVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfType,
+ String vnfVersion, String vnfName, String requestType, String volumeGroupHeatStackId,
+ String baseVfHeatStackId, String vfModuleStackId, String modelCustomizationUuid, Map<String, Object> inputs,
+ MsoRequest msoRequest, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback)
+ throws VnfException {
+ // This operation is not currently supported for Cloudify-orchestrated VF Modules.
+ logger.debug("Update VF Module command attempted but not supported");
+ throw new VnfException("UpdateVfModule: Unsupported command", MsoExceptionCategory.USERDATA);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java
index 82b194a973..7b48d0b07f 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java
@@ -21,21 +21,15 @@
*/
/**
- * This VNF Adapter implementation is based on the VDU Plugin model. It assumes that each
- * VF Module definition in the MSO catalog is expressed via a set of template and/or file
- * artifacts that are appropriate for some specific sub-orchestrator that provides an
- * implementation of the VduPlugin interface. This adapter handles all of the common
- * VF Module logic, including:
- * - catalog lookups for artifact retrieval
- * - parameter filtering and validation
- * - base and volume module queries
- * - rollback logic
- * - logging and error handling
+ * This VNF Adapter implementation is based on the VDU Plugin model. It assumes that each VF Module definition in the
+ * MSO catalog is expressed via a set of template and/or file artifacts that are appropriate for some specific
+ * sub-orchestrator that provides an implementation of the VduPlugin interface. This adapter handles all of the common
+ * VF Module logic, including: - catalog lookups for artifact retrieval - parameter filtering and validation - base and
+ * volume module queries - rollback logic - logging and error handling
*
- * Then based on the orchestration mode of the VNF, it will invoke different VDU plug-ins
- * to perform the low level instantiations, deletions, and queries. At this time, the
- * set of available plug-ins is hard-coded, though in the future a dynamic selection
- * is expected (e.g. via a service-provider interface).
+ * Then based on the orchestration mode of the VNF, it will invoke different VDU plug-ins to perform the low level
+ * instantiations, deletions, and queries. At this time, the set of available plug-ins is hard-coded, though in the
+ * future a dynamic selection is expected (e.g. via a service-provider interface).
*/
package org.onap.so.adapters.vnf;
@@ -46,10 +40,8 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
-
import javax.jws.WebService;
import javax.xml.ws.Holder;
-
import org.onap.so.adapters.vdu.CloudInfo;
import org.onap.so.adapters.vdu.VduException;
import org.onap.so.adapters.vdu.VduInstance;
@@ -74,7 +66,6 @@ import org.onap.so.db.catalog.utils.MavenLikeVersioning;
import org.onap.so.entity.MsoRequest;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.onap.so.openstack.beans.VnfRollback;
import org.onap.so.openstack.beans.VnfStatus;
import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
@@ -90,12 +81,12 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-@WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter", targetNamespace = "http://org.onap.so/vnf")
+@WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter",
+ targetNamespace = "http://org.onap.so/vnf")
@Component
@Transactional
public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
@@ -127,19 +118,20 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
@Autowired
protected MsoMulticloudUtils multicloudUtils;
- @Autowired
- protected VfModuleCustomizationToVduMapper vduMapper;
+ @Autowired
+ protected VfModuleCustomizationToVduMapper vduMapper;
- /**
+ /**
* Health Check web method. Does nothing but return to show the adapter is deployed.
*/
@Override
- public void healthCheck () {
+ public void healthCheck() {
logger.debug("Health check call in VNF Plugin Adapter");
}
/**
* DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL.
+ *
* @see MsoVnfPluginAdapterImpl#MsoVnfAdapterImpl(MsoPropertiesFactory, CloudConfigFactory)
*/
public MsoVnfPluginAdapterImpl() {
@@ -147,57 +139,31 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
}
/**
- * This is the "Create VNF" web service implementation.
- * This function is now unsupported and will return an error.
+ * This is the "Create VNF" web service implementation. This function is now unsupported and will return an error.
*
*/
@Override
- public void createVnf (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfType,
- String vnfVersion,
- String vnfName,
- String requestType,
- String volumeGroupHeatStackId,
- Map <String, Object> inputs,
- Boolean failIfExists,
- Boolean backout,
- Boolean enableBridge,
- MsoRequest msoRequest,
- Holder <String> vnfId,
- Holder <Map <String, String>> outputs,
- Holder <VnfRollback> rollback)
- throws VnfException
- {
- // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules.
+ public void createVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion,
+ String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs,
+ Boolean failIfExists, Boolean backout, Boolean enableBridge, MsoRequest msoRequest, Holder<String> vnfId,
+ Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) throws VnfException {
+ // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules.
logger.debug("CreateVNF command attempted but not supported");
throw new VnfException("CreateVNF: Unsupported command", MsoExceptionCategory.USERDATA);
}
/**
- * This is the "Update VNF" web service implementation.
- * This function is now unsupported and will return an error.
+ * This is the "Update VNF" web service implementation. This function is now unsupported and will return an error.
*
*/
@Override
- public void updateVnf (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfType,
- String vnfVersion,
- String vnfName,
- String requestType,
- String volumeGroupHeatStackId,
- Map <String, Object> inputs,
- MsoRequest msoRequest,
- Holder <Map <String, String>> outputs,
- Holder <VnfRollback> rollback)
- throws VnfException
- {
- // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules.
- logger.debug("UpdateVNF command attempted but not supported");
- throw new VnfException ("UpdateVNF: Unsupported command", MsoExceptionCategory.USERDATA);
+ public void updateVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion,
+ String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs,
+ MsoRequest msoRequest, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback)
+ throws VnfException {
+ // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules.
+ logger.debug("UpdateVNF command attempted but not supported");
+ throw new VnfException("UpdateVNF: Unsupported command", MsoExceptionCategory.USERDATA);
}
/**
@@ -205,8 +171,8 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
*
* This really should be QueryVfModule, but nobody ever changed it.
*
- * The method returns an indicator that the VNF exists, along with its status and outputs.
- * The input "vnfName" will also be reflected back as its ID.
+ * The method returns an indicator that the VNF exists, along with its status and outputs. The input "vnfName" will
+ * also be reflected back as its ID.
*
* @param cloudSiteId CLLI code of the cloud site in which to query
* @param tenantId Openstack tenant identifier
@@ -217,92 +183,78 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
* @param outputs Holder for Map of outputs from the deployed VF Module (assigned IPs, etc)
*/
@Override
- public void queryVnf (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfNameOrId,
- MsoRequest msoRequest,
- Holder <Boolean> vnfExists,
- Holder <String> vnfId,
- Holder <VnfStatus> status,
- Holder <Map <String, String>> outputs)
- throws VnfException
- {
+ public void queryVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfNameOrId,
+ MsoRequest msoRequest, Holder<Boolean> vnfExists, Holder<String> vnfId, Holder<VnfStatus> status,
+ Holder<Map<String, String>> outputs) throws VnfException {
logger.debug("Querying VNF " + vnfNameOrId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
- long subStartTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
+ long subStartTime = System.currentTimeMillis();
- VduInstance vduInstance = null;
- CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null);
+ VduInstance vduInstance = null;
+ CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null);
VduPlugin vduPlugin = getVduPlugin(cloudSiteId, cloudOwner);
- try {
- vduInstance = vduPlugin.queryVdu (cloudInfo, vnfNameOrId);
- }
- catch (VduException e) {
- // Failed to query the VDU due to a plugin exception.
- // Convert to a generic VnfException
- e.addContext("QueryVNF");
- String error = "Query VNF (VDU): " + vnfNameOrId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + e;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfNameOrId, cloudOwner, cloudSiteId,
- tenantId, "VDU", "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryVDU", e);
- logger.debug(error);
- throw new VnfException(e);
- }
-
- if (vduInstance != null && vduInstance.getStatus().getState() != VduStateType.NOTFOUND) {
- vnfExists.value = Boolean.TRUE;
- status.value = vduStatusToVnfStatus(vduInstance);
- vnfId.value = vduInstance.getVduInstanceId();
- outputs.value = copyStringOutputs(vduInstance.getOutputs());
-
- logger.debug("VNF {} found, ID = {}", vnfNameOrId, vnfId.value);
+ try {
+ vduInstance = vduPlugin.queryVdu(cloudInfo, vnfNameOrId);
+ } catch (VduException e) {
+ // Failed to query the VDU due to a plugin exception.
+ // Convert to a generic VnfException
+ e.addContext("QueryVNF");
+ String error = "Query VNF (VDU): " + vnfNameOrId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + ": " + e;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfNameOrId, cloudOwner,
+ cloudSiteId, tenantId, "VDU", "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryVDU",
+ e);
+ logger.debug(error);
+ throw new VnfException(e);
+ }
+
+ if (vduInstance != null && vduInstance.getStatus().getState() != VduStateType.NOTFOUND) {
+ vnfExists.value = Boolean.TRUE;
+ status.value = vduStatusToVnfStatus(vduInstance);
+ vnfId.value = vduInstance.getVduInstanceId();
+ outputs.value = copyStringOutputs(vduInstance.getOutputs());
+
+ logger.debug("VNF {} found, ID = {}", vnfNameOrId, vnfId.value);
+ } else {
+ vnfExists.value = Boolean.FALSE;
+ status.value = VnfStatus.NOTFOUND;
+ vnfId.value = null;
+ outputs.value = new HashMap<String, String>(); // Return as an empty map
+
+ logger.debug("VNF {} not found", vnfNameOrId);
}
- else {
- vnfExists.value = Boolean.FALSE;
- status.value = VnfStatus.NOTFOUND;
- vnfId.value = null;
- outputs.value = new HashMap<String, String>(); // Return as an empty map
-
- logger.debug("VNF {} not found", vnfNameOrId);
- }
return;
}
/**
- * This is the "Delete VNF" web service implementation.
- * This function is now unsupported and will return an error.
+ * This is the "Delete VNF" web service implementation. This function is now unsupported and will return an error.
*
*/
@Override
- public void deleteVnf (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfName,
- MsoRequest msoRequest) throws VnfException {
-
- // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules.
- logger.debug("DeleteVNF command attempted but not supported");
- throw new VnfException ("DeleteVNF: Unsupported command", MsoExceptionCategory.USERDATA);
+ public void deleteVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest)
+ throws VnfException {
+
+ // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules.
+ logger.debug("DeleteVNF command attempted but not supported");
+ throw new VnfException("DeleteVNF: Unsupported command", MsoExceptionCategory.USERDATA);
}
/**
- * This web service endpoint will rollback a previous Create VNF operation.
- * A rollback object is returned to the client in a successful creation
- * response. The client can pass that object as-is back to the rollbackVnf
- * operation to undo the creation.
+ * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the
+ * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation
+ * to undo the creation.
*
- * TODO: This should be rollbackVfModule and/or rollbackVolumeGroup,
- * but APIs were apparently never updated.
+ * TODO: This should be rollbackVfModule and/or rollbackVolumeGroup, but APIs were apparently never updated.
*/
@Override
- public void rollbackVnf (VnfRollback rollback) throws VnfException {
- long startTime = System.currentTimeMillis ();
- // rollback may be null (e.g. if stack already existed when Create was called)
+ public void rollbackVnf(VnfRollback rollback) throws VnfException {
+ long startTime = System.currentTimeMillis();
+ // rollback may be null (e.g. if stack already existed when Create was called)
if (rollback == null) {
logger.info("{} {} {}", MessageEnum.RA_ROLLBACK_NULL.toString(), "OpenStack", "rollbackVnf");
return;
@@ -314,131 +266,127 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
}
// Get the elements of the VnfRollback object for easier access
- String cloudSiteId = rollback.getCloudSiteId ();
+ String cloudSiteId = rollback.getCloudSiteId();
String cloudOwner = rollback.getCloudOwner();
- String tenantId = rollback.getTenantId ();
- CloudInfo cloudInfo = new CloudInfo (cloudSiteId, cloudOwner, tenantId, null);
+ String tenantId = rollback.getTenantId();
+ CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null);
- String vfModuleId = rollback.getVfModuleStackId ();
+ String vfModuleId = rollback.getVfModuleStackId();
logger.debug("Rolling Back VF Module " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId);
- VduInstance vduInstance = null;
+ VduInstance vduInstance = null;
// Use the VduPlugin to delete the VF Module.
VduPlugin vduPlugin = getVduPlugin(cloudSiteId, cloudOwner);
- long subStartTime = System.currentTimeMillis ();
+ long subStartTime = System.currentTimeMillis();
try {
- // TODO: Get a reasonable timeout. Use a global property, or store the creation timeout in rollback object and use that.
+ // TODO: Get a reasonable timeout. Use a global property, or store the creation timeout in rollback object
+ // and use that.
vduInstance = vduPlugin.deleteVdu(cloudInfo, vfModuleId, 5);
logger.debug("Rolled back VDU instantiation: {}", vduInstance.getVduInstanceId());
- }
- catch (VduException ve) {
+ } catch (VduException ve) {
// Failed to rollback the VF Module due to a plugin exception.
// Convert to a generic VnfException
- ve.addContext ("RollbackVFModule");
- String error = "Rollback VF Module: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + ve;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, cloudSiteId,
- tenantId, "VDU", "DeleteVdu", ErrorCode.DataError.getValue(), "Exception - DeleteVdu", ve);
+ ve.addContext("RollbackVFModule");
+ String error = "Rollback VF Module: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/"
+ + tenantId + ": " + ve;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner,
+ cloudSiteId, tenantId, "VDU", "DeleteVdu", ErrorCode.DataError.getValue(), "Exception - DeleteVdu",
+ ve);
logger.debug(error);
- throw new VnfException (ve);
+ throw new VnfException(ve);
}
return;
}
- private VnfStatus vduStatusToVnfStatus (VduInstance vdu) {
- // Determine the status based on last action & status
- // DeploymentInfo object should be enhanced to report a better status internally.
- VduStatus vduStatus = vdu.getStatus();
- VduStateType status = vduStatus.getState();
-
- if (status == null) {
- return VnfStatus.UNKNOWN;
- }
- else if (status == VduStateType.NOTFOUND) {
- return VnfStatus.NOTFOUND;
- }
- else if (status == VduStateType.INSTANTIATED) {
- return VnfStatus.ACTIVE;
- }
- else if (status == VduStateType.FAILED) {
- return VnfStatus.FAILED;
- }
-
- return VnfStatus.UNKNOWN;
+ private VnfStatus vduStatusToVnfStatus(VduInstance vdu) {
+ // Determine the status based on last action & status
+ // DeploymentInfo object should be enhanced to report a better status internally.
+ VduStatus vduStatus = vdu.getStatus();
+ VduStateType status = vduStatus.getState();
+
+ if (status == null) {
+ return VnfStatus.UNKNOWN;
+ } else if (status == VduStateType.NOTFOUND) {
+ return VnfStatus.NOTFOUND;
+ } else if (status == VduStateType.INSTANTIATED) {
+ return VnfStatus.ACTIVE;
+ } else if (status == VduStateType.FAILED) {
+ return VnfStatus.FAILED;
+ }
+
+ return VnfStatus.UNKNOWN;
+ }
+
+ /*
+ * Normalize an input value to an Object, based on the target parameter type. If the type is not recognized, it will
+ * just be returned unchanged (as a string).
+ */
+ private Object convertInputValue(Object inputValue, HeatTemplateParam templateParam) {
+ String type = templateParam.getParamType();
+ logger.debug("Parameter: {} is of type ", templateParam.getParamName(), type);
+
+ if (type.equalsIgnoreCase("number")) {
+ try {
+ return Integer.valueOf(inputValue.toString());
+ } catch (Exception e) {
+ logger.debug("Unable to convert " + inputValue + " to an integer!", e);
+ return null;
+ }
+ } else if (type.equalsIgnoreCase("json")) {
+ try {
+ JsonNode jsonNode = JSON_MAPPER.readTree(JSON_MAPPER.writeValueAsString(inputValue));
+ return jsonNode;
+ } catch (Exception e) {
+ logger.debug("Unable to convert " + inputValue + " to a JsonNode!", e);
+ return null;
+ }
+ } else if (type.equalsIgnoreCase("boolean")) {
+ return new Boolean(inputValue.toString());
+ }
+
+ // Nothing else matched. Return the original string
+ return inputValue;
}
- /*
- * Normalize an input value to an Object, based on the target parameter type.
- * If the type is not recognized, it will just be returned unchanged (as a string).
- */
- private Object convertInputValue (Object inputValue, HeatTemplateParam templateParam)
- {
- String type = templateParam.getParamType();
- logger.debug("Parameter: {} is of type ", templateParam.getParamName(), type);
-
- if (type.equalsIgnoreCase("number")) {
- try {
- return Integer.valueOf(inputValue.toString());
- }
- catch (Exception e) {
- logger.debug("Unable to convert " + inputValue + " to an integer!" , e);
- return null;
- }
- } else if (type.equalsIgnoreCase("json")) {
- try {
- JsonNode jsonNode = JSON_MAPPER.readTree(JSON_MAPPER.writeValueAsString(inputValue));
- return jsonNode;
- }
- catch (Exception e) {
- logger.debug("Unable to convert " + inputValue + " to a JsonNode!", e);
- return null;
- }
- } else if (type.equalsIgnoreCase("boolean")) {
- return new Boolean(inputValue.toString());
- }
-
- // Nothing else matched. Return the original string
- return inputValue;
- }
-
- private Map <String, String> copyStringOutputs (Map <String, Object> stackOutputs) {
- Map <String, String> stringOutputs = new HashMap <String, String> ();
- for (String key : stackOutputs.keySet ()) {
- if (stackOutputs.get (key) instanceof String) {
- stringOutputs.put (key, (String) stackOutputs.get (key));
- } else if (stackOutputs.get(key) instanceof Integer) {
- try {
- String str = "" + stackOutputs.get(key);
- stringOutputs.put(key, str);
- } catch (Exception e) {
- logger.debug("Unable to add {} to outputs", key, e);
- }
+ private Map<String, String> copyStringOutputs(Map<String, Object> stackOutputs) {
+ Map<String, String> stringOutputs = new HashMap<String, String>();
+ for (String key : stackOutputs.keySet()) {
+ if (stackOutputs.get(key) instanceof String) {
+ stringOutputs.put(key, (String) stackOutputs.get(key));
+ } else if (stackOutputs.get(key) instanceof Integer) {
+ try {
+ String str = "" + stackOutputs.get(key);
+ stringOutputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("Unable to add {} to outputs", key, e);
+ }
} else if (stackOutputs.get(key) instanceof JsonNode) {
- try {
- String str = this.convertNode((JsonNode) stackOutputs.get(key));
- stringOutputs.put(key, str);
- } catch (Exception e) {
- logger.debug("Unable to add {} to outputs - exception converting JsonNode", key, e);
- }
+ try {
+ String str = this.convertNode((JsonNode) stackOutputs.get(key));
+ stringOutputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("Unable to add {} to outputs - exception converting JsonNode", key, e);
+ }
} else if (stackOutputs.get(key) instanceof java.util.LinkedHashMap) {
- try {
- String str = JSON_MAPPER.writeValueAsString(stackOutputs.get(key));
- stringOutputs.put(key, str);
- } catch (Exception e) {
- logger.debug("Unable to add {} to outputs - exception converting LinkedHashMap", key, e);
- }
+ try {
+ String str = JSON_MAPPER.writeValueAsString(stackOutputs.get(key));
+ stringOutputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("Unable to add {} to outputs - exception converting LinkedHashMap", key, e);
+ }
} else {
- try {
- String str = stackOutputs.get(key).toString();
- stringOutputs.put(key, str);
- } catch (Exception e) {
- logger
- .debug("Unable to add " + key + " to outputs - unable to call .toString() " + e.getMessage(), e);
- }
+ try {
+ String str = stackOutputs.get(key).toString();
+ stringOutputs.put(key, str);
+ } catch (Exception e) {
+ logger.debug("Unable to add " + key + " to outputs - unable to call .toString() " + e.getMessage(),
+ e);
+ }
}
}
return stringOutputs;
@@ -446,43 +394,41 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
private void sendMapToDebug(Map<String, Object> inputs, String optionalName) {
- int i = 0;
- StringBuilder sb = new StringBuilder(optionalName == null ? "\ninputs" : "\n" + optionalName);
- if (inputs == null) {
- sb.append("\tNULL");
- }
- else if (inputs.size() < 1) {
- sb.append("\tEMPTY");
- } else {
- for (String str : inputs.keySet()) {
- String outputString;
- try {
- outputString = inputs.get(str).toString();
- } catch (Exception e) {
- outputString = "Unable to call toString() on the value for " + str;
- }
- sb.append("\t\nitem " + i++ + ": '" + str + "'='" + outputString + "'");
- }
- }
- logger.debug(sb.toString());
- return;
+ int i = 0;
+ StringBuilder sb = new StringBuilder(optionalName == null ? "\ninputs" : "\n" + optionalName);
+ if (inputs == null) {
+ sb.append("\tNULL");
+ } else if (inputs.size() < 1) {
+ sb.append("\tEMPTY");
+ } else {
+ for (String str : inputs.keySet()) {
+ String outputString;
+ try {
+ outputString = inputs.get(str).toString();
+ } catch (Exception e) {
+ outputString = "Unable to call toString() on the value for " + str;
+ }
+ sb.append("\t\nitem " + i++ + ": '" + str + "'='" + outputString + "'");
+ }
+ }
+ logger.debug(sb.toString());
+ return;
}
private void sendMapToDebug(Map<String, Object> inputs) {
- int i = 0;
- StringBuilder sb = new StringBuilder("inputs:");
- if (inputs == null) {
- sb.append("\tNULL");
- }
- else if (inputs.size() < 1) {
- sb.append("\tEMPTY");
- } else {
- for (String str : inputs.keySet()) {
- sb.append("\titem " + i++ + ": " + str + "=" + inputs.get(str));
- }
- }
- logger.debug(sb.toString());
- return;
+ int i = 0;
+ StringBuilder sb = new StringBuilder("inputs:");
+ if (inputs == null) {
+ sb.append("\tNULL");
+ } else if (inputs.size() < 1) {
+ sb.append("\tEMPTY");
+ } else {
+ for (String str : inputs.keySet()) {
+ sb.append("\titem " + i++ + ": " + str + "=" + inputs.get(str));
+ }
+ }
+ logger.debug(sb.toString());
+ return;
}
private String convertNode(final JsonNode node) {
@@ -508,15 +454,15 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
Object obj = objectMap.get(key);
if (obj instanceof String) {
stringMap.put(key, (String) objectMap.get(key));
- } else if (obj instanceof JsonNode ){
+ } else if (obj instanceof JsonNode) {
// This is a bit of mess - but I think it's the least impacting
// let's convert it BACK to a string - then it will get converted back later
try {
String str = this.convertNode((JsonNode) obj);
stringMap.put(key, str);
} catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode "+ key, e);
- //okay in this instance - only string values (fqdn) are expected to be needed
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode " + key, e);
+ // okay in this instance - only string values (fqdn) are expected to be needed
}
} else if (obj instanceof java.util.LinkedHashMap) {
logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
@@ -524,21 +470,23 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
String str = JSON_MAPPER.writeValueAsString(obj);
stringMap.put(key, str);
} catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap "+ key, e);
- }
- } else if (obj instanceof Integer) {
- try {
- String str = "" + obj;
- stringMap.put(key, str);
- } catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer "+ key, e);
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap " + key, e);
+ }
+ } else if (obj instanceof Integer) {
+ try {
+ String str = "" + obj;
+ stringMap.put(key, str);
+ } catch (Exception e) {
+ logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer " + key, e);
}
} else {
try {
- String str = obj.toString();
+ String str = obj.toString();
stringMap.put(key, str);
} catch (Exception e) {
- logger.debug("DANGER WILL ROBINSON: unable to convert value "+ key + " (" + e.getMessage() + ")", e);
+ logger.debug(
+ "DANGER WILL ROBINSON: unable to convert value " + key + " (" + e.getMessage() + ")",
+ e);
}
}
}
@@ -548,44 +496,37 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
}
/**
- * This is the "Create VF Module" web service implementation.
- * It will instantiate a new VF Module of the requested type in the specified cloud
- * and tenant. The tenant must exist before this service is called.
+ * This is the "Create VF Module" web service implementation. It will instantiate a new VF Module of the requested
+ * type in the specified cloud and tenant. The tenant must exist before this service is called.
*
- * If a VF Module with the same name already exists, this can be considered a
- * success or failure, depending on the value of the 'failIfExists' parameter.
+ * If a VF Module with the same name already exists, this can be considered a success or failure, depending on the
+ * value of the 'failIfExists' parameter.
*
- * All VF Modules are defined in the MSO catalog. The caller must request one of
- * the pre-defined module types or an error will be returned. Within the catalog,
- * each VF Module references (among other things) a collection of artifacts that
- * are used to deploy the required cloud resources (VMs, networks, etc.).
+ * All VF Modules are defined in the MSO catalog. The caller must request one of the pre-defined module types or an
+ * error will be returned. Within the catalog, each VF Module references (among other things) a collection of
+ * artifacts that are used to deploy the required cloud resources (VMs, networks, etc.).
*
- * Depending on the module templates, a variable set of input parameters will
- * be defined, some of which are required. The caller is responsible to
- * pass the necessary input data for the module or an error will be thrown.
+ * Depending on the module templates, a variable set of input parameters will be defined, some of which are
+ * required. The caller is responsible to pass the necessary input data for the module or an error will be thrown.
*
- * The method returns the vfModuleId, a Map of output attributes, and a VnfRollback
- * object. This last object can be passed as-is to the rollbackVnf operation to
- * undo everything that was created for the Module. This is useful if a VF module
- * is successfully created but the orchestration fails on a subsequent step.
+ * The method returns the vfModuleId, a Map of output attributes, and a VnfRollback object. This last object can be
+ * passed as-is to the rollbackVnf operation to undo everything that was created for the Module. This is useful if a
+ * VF module is successfully created but the orchestration fails on a subsequent step.
*
* @param cloudSiteId CLLI code of the cloud site in which to create the VNF
* @param cloudOwner cloud owner of the cloud site in which to create the VNF
* @param tenantId Openstack tenant identifier
- * @param vfModuleType VF Module type key, should match a VNF definition in catalog DB.
- * Deprecated - should use modelCustomizationUuid
- * @param vnfVersion VNF version key, should match a VNF definition in catalog DB
- * Deprecated - VF Module versions also captured by modelCustomizationUuid
+ * @param vfModuleType VF Module type key, should match a VNF definition in catalog DB. Deprecated - should use
+ * modelCustomizationUuid
+ * @param vnfVersion VNF version key, should match a VNF definition in catalog DB Deprecated - VF Module versions
+ * also captured by modelCustomizationUuid
* @param vnfId - VNF ID
* @param vfModuleName Name to be assigned to the new VF Module
* @param vfModuleId Id fo the new VF Module
* @param requestType Indicates if this is a Volume Group or Module request
- * @param volumeGroupId Identifier (i.e. deployment ID) for a Volume Group
- * to attach to a VF Module
- * @param baseVfModuleId Identifier (i.e. deployment ID) of the Base Module if
- * this is an Add-on module
- * @param modelCustomizationUuid Unique ID for the VF Module's model. Replaces
- * the use of vfModuleType.
+ * @param volumeGroupId Identifier (i.e. deployment ID) for a Volume Group to attach to a VF Module
+ * @param baseVfModuleId Identifier (i.e. deployment ID) of the Base Module if this is an Add-on module
+ * @param modelCustomizationUuid Unique ID for the VF Module's model. Replaces the use of vfModuleType.
* @param inputs Map of key=value inputs for VNF stack creation
* @param failIfExists Flag whether already existing VNF should be considered
* @param backout Flag whether to suppress automatic backout (for testing)
@@ -595,68 +536,51 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
* @param rollback Holder for returning VnfRollback object
*/
@Override
- public void createVfModule(String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vfModuleType,
- String vnfVersion,
- String genericVnfId,
- String vfModuleName,
- String vfModuleId,
- String requestType,
- String volumeGroupId,
- String baseVfModuleId,
- String modelCustomizationUuid,
- Map <String, Object> inputs,
- Boolean failIfExists,
- Boolean backout,
- Boolean enableBridge,
- MsoRequest msoRequest,
- Holder <String> vnfId,
- Holder <Map <String, String>> outputs,
- Holder <VnfRollback> rollback)
- throws VnfException
- {
+ public void createVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vfModuleType,
+ String vnfVersion, String genericVnfId, String vfModuleName, String vfModuleId, String requestType,
+ String volumeGroupId, String baseVfModuleId, String modelCustomizationUuid, Map<String, Object> inputs,
+ Boolean failIfExists, Boolean backout, Boolean enableBridge, MsoRequest msoRequest, Holder<String> vnfId,
+ Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) throws VnfException {
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
- // Require a model customization ID. Every VF Module definition must have one.
- if (modelCustomizationUuid == null || modelCustomizationUuid.isEmpty()) {
+ // Require a model customization ID. Every VF Module definition must have one.
+ if (modelCustomizationUuid == null || modelCustomizationUuid.isEmpty()) {
logger.debug("Missing required input: modelCustomizationUuid");
String error = "Create vfModule error: Missing required input: modelCustomizationUuid";
logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(),
- "VF Module ModelCustomizationUuid", "VDU", ErrorCode.DataError,
- "Create VF Module: " + "Missing required input: modelCustomizationUuid");
+ "VF Module ModelCustomizationUuid", "VDU", ErrorCode.DataError,
+ "Create VF Module: " + "Missing required input: modelCustomizationUuid");
logger.debug(error);
throw new VnfException(error, MsoExceptionCategory.USERDATA);
}
// Clean up some inputs to make comparisons easier
if (requestType == null)
- requestType = "";
+ requestType = "";
if ("".equals(volumeGroupId) || "null".equals(volumeGroupId))
- volumeGroupId = null;
+ volumeGroupId = null;
if ("".equals(baseVfModuleId) || "null".equals(baseVfModuleId))
- baseVfModuleId = null;
+ baseVfModuleId = null;
if (inputs == null) {
- // Create an empty set of inputs
- inputs = new HashMap<>();
- logger.debug("inputs == null - setting to empty");
+ // Create an empty set of inputs
+ inputs = new HashMap<>();
+ logger.debug("inputs == null - setting to empty");
} else {
- this.sendMapToDebug(inputs);
+ this.sendMapToDebug(inputs);
}
// Check if this is for a "Volume" module
boolean isVolumeRequest = false;
if (requestType.startsWith("VOLUME")) {
- isVolumeRequest = true;
+ isVolumeRequest = true;
}
- logger.debug("requestType = " + requestType + ", volumeGroupStackId = " + volumeGroupId + ", baseStackId = " +
- baseVfModuleId);
+ logger.debug("requestType = " + requestType + ", volumeGroupStackId = " + volumeGroupId + ", baseStackId = "
+ + baseVfModuleId);
// Build a default rollback object (no actions performed)
VnfRollback vfRollback = new VnfRollback();
@@ -665,69 +589,70 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
vfRollback.setTenantId(tenantId);
vfRollback.setMsoRequest(msoRequest);
vfRollback.setRequestType(requestType);
- vfRollback.setIsBase(false); // Until we know better
+ vfRollback.setIsBase(false); // Until we know better
vfRollback.setVolumeGroupHeatStackId(volumeGroupId);
vfRollback.setBaseGroupHeatStackId(baseVfModuleId);
vfRollback.setModelCustomizationUuid(modelCustomizationUuid);
vfRollback.setMode("CFY");
- rollback.value = vfRollback; // Default rollback - no updates performed
+ rollback.value = vfRollback; // Default rollback - no updates performed
// Get the VNF/VF Module definition from the Catalog DB first.
- // There are three relevant records: VfModule, VfModuleCustomization, VnfResource
+ // There are three relevant records: VfModule, VfModuleCustomization, VnfResource
VfModule vfModule = null;
- VnfResource vnfResource = null;
- VfModuleCustomization vfModuleCust = null;
+ VnfResource vnfResource = null;
+ VfModuleCustomization vfModuleCust = null;
try {
- vfModuleCust = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(modelCustomizationUuid);
+ vfModuleCust =
+ vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(modelCustomizationUuid);
if (vfModuleCust == null) {
String error = "Create vfModule error: Unable to find vfModuleCust with modelCustomizationUuid="
- + modelCustomizationUuid;
+ + modelCustomizationUuid;
logger.debug(error);
logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(),
- "VF Module ModelCustomizationUuid", modelCustomizationUuid, "CatalogDb",
- ErrorCode.DataError, error);
+ "VF Module ModelCustomizationUuid", modelCustomizationUuid, "CatalogDb", ErrorCode.DataError,
+ error);
throw new VnfException(error, MsoExceptionCategory.USERDATA);
} else {
logger.debug("Found vfModuleCust entry {}", vfModuleCust.toString());
}
// Get the vfModule and vnfResource records
- vfModule = vfModuleCust.getVfModule();
- vnfResource = vfModuleCust.getVfModule().getVnfResources();
- }
- catch (Exception e) {
+ vfModule = vfModuleCust.getVfModule();
+ vnfResource = vfModuleCust.getVfModule().getVnfResources();
+ } catch (Exception e) {
- logger.debug("unhandled exception in create VF - [Query]" + e.getMessage());
- throw new VnfException("Exception during create VF " + e.getMessage());
+ logger.debug("unhandled exception in create VF - [Query]" + e.getMessage());
+ throw new VnfException("Exception during create VF " + e.getMessage());
}
// Perform a version check against cloudSite
// Obtain the cloud site information where we will create the VF Module
- Optional<CloudSite> cloudSiteOp = cloudConfig.getCloudSite (cloudSiteId);
+ Optional<CloudSite> cloudSiteOp = cloudConfig.getCloudSite(cloudSiteId);
if (!cloudSiteOp.isPresent()) {
// If cloudSiteId is not present in the catalog DB, then default to multicloud
- logger.debug("{} is not present in cloud_site catalog DB, defaulting to Multicloud plugin adapter", cloudSiteId);
+ logger.debug("{} is not present in cloud_site catalog DB, defaulting to Multicloud plugin adapter",
+ cloudSiteId);
} else {
CloudSite cloudSite = cloudSiteOp.get();
- MavenLikeVersioning aicV = new MavenLikeVersioning();
- aicV.setVersion(cloudSite.getCloudVersion());
+ MavenLikeVersioning aicV = new MavenLikeVersioning();
+ aicV.setVersion(cloudSite.getCloudVersion());
- String vnfMin = vnfResource.getAicVersionMin();
- String vnfMax = vnfResource.getAicVersionMax();
+ String vnfMin = vnfResource.getAicVersionMin();
+ String vnfMax = vnfResource.getAicVersionMax();
- if ((vnfMin != null && !(aicV.isMoreRecentThan(vnfMin) || aicV.isTheSameVersion(vnfMin))) || (vnfMax != null
- && aicV.isMoreRecentThan(vnfMax))) {
+ if ((vnfMin != null && !(aicV.isMoreRecentThan(vnfMin) || aicV.isTheSameVersion(vnfMin)))
+ || (vnfMax != null && aicV.isMoreRecentThan(vnfMax))) {
// ERROR
String error =
- "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUUID()
- + " VersionMin=" + vnfMin + " VersionMax:" + vnfMax + " NOT supported on Cloud: " + cloudSiteId
- + " with AIC_Version:" + cloudSite.getCloudVersion();
+ "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUUID()
+ + " VersionMin=" + vnfMin + " VersionMax:" + vnfMax + " NOT supported on Cloud: "
+ + cloudSiteId + " with AIC_Version:" + cloudSite.getCloudVersion();
logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack",
- ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion");
+ ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion");
logger.debug(error);
throw new VnfException(error, MsoExceptionCategory.USERDATA);
}
@@ -736,42 +661,43 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
VduInstance vduInstance = null;
- CloudInfo cloudInfo = new CloudInfo (cloudSiteId, cloudOwner, tenantId, null);
+ CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null);
// Use the VduPlugin.
VduPlugin vduPlugin = getVduPlugin(cloudSiteId, cloudOwner);
- long subStartTime1 = System.currentTimeMillis ();
+ long subStartTime1 = System.currentTimeMillis();
try {
- vduInstance = vduPlugin.queryVdu (cloudInfo, vfModuleName);
- }
- catch (VduException me) {
+ vduInstance = vduPlugin.queryVdu(cloudInfo, vfModuleName);
+ } catch (VduException me) {
// Failed to query the VDU due to a plugin exception.
- String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ;
+ String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/"
+ + tenantId + ": " + me;
logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(),
- "Exception - queryVdu", me);
+ cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(),
+ "Exception - queryVdu", me);
logger.debug(error);
// Convert to a generic VnfException
- me.addContext ("CreateVFModule");
- throw new VnfException (me);
+ me.addContext("CreateVFModule");
+ throw new VnfException(me);
}
// More precise handling/messaging if the Module already exists
if (vduInstance != null && !(vduInstance.getStatus().getState() == VduStateType.NOTFOUND)) {
- VduStateType status = vduInstance.getStatus().getState();
+ VduStateType status = vduInstance.getStatus().getState();
logger.debug("Found Existing VDU, status=" + status);
if (status == VduStateType.INSTANTIATED) {
if (failIfExists != null && failIfExists) {
// fail - it exists
- String error =
- "Create VF: Deployment " + vfModuleName + " already exists in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(),
- "VF Module " + vfModuleName + " already exists");
+ String error = "Create VF: Deployment " + vfModuleName + " already exists in " + cloudOwner + "/"
+ + cloudSiteId + "/" + tenantId;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(),
+ vfModuleName, cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu",
+ ErrorCode.DataError.getValue(), "VF Module " + vfModuleName + " already exists");
logger.debug(error);
- throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, vduInstance.getVduInstanceId());
+ throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId,
+ vduInstance.getVduInstanceId());
} else {
// Found existing deployment and client has not requested "failIfExists".
// Populate the outputs from the existing deployment.
@@ -783,46 +709,49 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
}
// Check through various detailed error cases
else if (status == VduStateType.INSTANTIATING || status == VduStateType.DELETING
- || status == VduStateType.UPDATING) {
+ || status == VduStateType.UPDATING) {
// fail - it's in progress - return meaningful error
- String error =
- "Create VF: Deployment " + vfModuleName + " already exists and has status " + status.toString()
- + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; please wait for it to complete, or fix manually.";
+ String error = "Create VF: Deployment " + vfModuleName + " already exists and has status "
+ + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + "; please wait for it to complete, or fix manually.";
logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(),
- "VF Module " + vfModuleName + " already exists");
+ cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(),
+ "VF Module " + vfModuleName + " already exists");
logger.debug(error);
- throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, vduInstance.getVduInstanceId());
+ throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId,
+ vduInstance.getVduInstanceId());
} else if (status == VduStateType.FAILED) {
// fail - it exists and is in a FAILED state
- String error =
- "Create VF: Deployment " + vfModuleName + " already exists and is in FAILED state in " + cloudOwner + "/" + cloudSiteId
- + "/" + tenantId + "; requires manual intervention.";
+ String error = "Create VF: Deployment " + vfModuleName + " already exists and is in FAILED state in "
+ + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention.";
logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(),
- "VF Module " + vfModuleName + " already exists and is in FAILED state");
+ cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(),
+ "VF Module " + vfModuleName + " already exists and is in FAILED state");
logger.debug(error);
- throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, vduInstance.getVduInstanceId());
+ throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId,
+ vduInstance.getVduInstanceId());
} else if (status == VduStateType.UNKNOWN) {
// fail - it exists and is in a UNKNOWN state
- String error =
- "Create VF: Deployment " + vfModuleName + " already exists and has status " + status.toString()
- + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention.";
+ String error = "Create VF: Deployment " + vfModuleName + " already exists and has status "
+ + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + "; requires manual intervention.";
logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(),
- "VF Module " + vfModuleName + " already exists and is in " + status.toString() + " state");
+ cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(),
+ "VF Module " + vfModuleName + " already exists and is in " + status.toString() + " state");
logger.debug(error);
- throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, vduInstance.getVduInstanceId());
+ throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId,
+ vduInstance.getVduInstanceId());
} else {
// Unexpected, since all known status values have been tested for
- String error =
- "Create VF: Deployment " + vfModuleName + " already exists with unexpected status " + status
- .toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention.";
+ String error = "Create VF: Deployment " + vfModuleName + " already exists with unexpected status "
+ + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + "; requires manual intervention.";
logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName,
- cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(),
- "VF Module " + vfModuleName + " already exists and is in an unknown state");
+ cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(),
+ "VF Module " + vfModuleName + " already exists and is in an unknown state");
logger.debug(error);
- throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, vduInstance.getVduInstanceId());
+ throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId,
+ vduInstance.getVduInstanceId());
}
}
@@ -833,41 +762,42 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
// If a Volume Group was provided, query its outputs for inclusion in Module input parameters
if (volumeGroupId != null) {
- long subStartTime2 = System.currentTimeMillis ();
+ long subStartTime2 = System.currentTimeMillis();
VduInstance volumeVdu = null;
try {
- volumeVdu = vduPlugin.queryVdu (cloudInfo, volumeGroupId);
- }
- catch (VduException me) {
+ volumeVdu = vduPlugin.queryVdu(cloudInfo, volumeGroupId);
+ } catch (VduException me) {
// Failed to query the Volume Group VDU due to a plugin exception.
- String error = "Create VF Module: Query Volume Group " + volumeGroupId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ;
+ String error = "Create VF Module: Query Volume Group " + volumeGroupId + " in " + cloudOwner + "/"
+ + cloudSiteId + "/" + tenantId + ": " + me;
logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId,
- cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu(volume)", ErrorCode.DataError.getValue(),
- "Exception - queryVdu(volume)", me);
+ cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu(volume)", ErrorCode.DataError.getValue(),
+ "Exception - queryVdu(volume)", me);
logger.debug(error);
// Convert to a generic VnfException
- me.addContext ("CreateVFModule(QueryVolume)");
- throw new VnfException (me);
+ me.addContext("CreateVFModule(QueryVolume)");
+ throw new VnfException(me);
}
- if (volumeVdu == null || volumeVdu.getStatus().getState() == VduStateType.NOTFOUND) {
- String error = "Create VFModule: Attached Volume Group DOES NOT EXIST " + volumeGroupId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR" ;
- logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId,
- cloudOwner, cloudSiteId, tenantId, error, "VDU", "queryVdu(volume)",
- ErrorCode.BusinessProcesssError.getValue(),
- "Create VFModule: Attached Volume Group " + "DOES NOT EXIST");
- logger.debug(error);
- throw new VnfException (error, MsoExceptionCategory.USERDATA);
- } else {
- logger.debug("Found nested volume group");
- volumeGroupOutputs = volumeVdu.getOutputs();
- this.sendMapToDebug(volumeGroupOutputs, "volumeGroupOutputs");
- }
+ if (volumeVdu == null || volumeVdu.getStatus().getState() == VduStateType.NOTFOUND) {
+ String error = "Create VFModule: Attached Volume Group DOES NOT EXIST " + volumeGroupId + " in "
+ + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR";
+ logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId,
+ cloudOwner, cloudSiteId, tenantId, error, "VDU", "queryVdu(volume)",
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Create VFModule: Attached Volume Group " + "DOES NOT EXIST");
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ } else {
+ logger.debug("Found nested volume group");
+ volumeGroupOutputs = volumeVdu.getOutputs();
+ this.sendMapToDebug(volumeGroupOutputs, "volumeGroupOutputs");
+ }
}
// If this is an Add-On Module, query the Base Module outputs
// Note: This will be performed whether or not the current request is for an
- // Add-On Volume Group or Add-On VF Module
+ // Add-On Volume Group or Add-On VF Module
if (vfModule.getIsBase()) {
logger.debug("This is a BASE Module request");
@@ -882,31 +812,29 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
}
if (baseVfModuleId != null) {
- long subStartTime2 = System.currentTimeMillis ();
- VduInstance baseVdu = null;
- try {
- baseVdu = vduPlugin.queryVdu (cloudInfo, baseVfModuleId);
- }
- catch (MsoException me) {
- // Failed to query the Base VF Module due to a Vdu Plugin exception.
- String error = "Create VF Module: Query Base " + baseVfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId,
- cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu(Base)", ErrorCode.DataError.getValue(),
- "Exception - queryVdu(Base)", me);
- logger.debug(error);
- // Convert to a generic VnfException
- me.addContext ("CreateVFModule(QueryBase)");
- throw new VnfException (me);
- }
+ long subStartTime2 = System.currentTimeMillis();
+ VduInstance baseVdu = null;
+ try {
+ baseVdu = vduPlugin.queryVdu(cloudInfo, baseVfModuleId);
+ } catch (MsoException me) {
+ // Failed to query the Base VF Module due to a Vdu Plugin exception.
+ String error = "Create VF Module: Query Base " + baseVfModuleId + " in " + cloudOwner + "/"
+ + cloudSiteId + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId,
+ cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu(Base)", ErrorCode.DataError.getValue(),
+ "Exception - queryVdu(Base)", me);
+ logger.debug(error);
+ // Convert to a generic VnfException
+ me.addContext("CreateVFModule(QueryBase)");
+ throw new VnfException(me);
+ }
if (baseVdu == null || baseVdu.getStatus().getState() == VduStateType.NOTFOUND) {
- String error =
- "Create VFModule: Base Module DOES NOT EXIST " + baseVfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/"
- + tenantId + " USER ERROR";
- logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId,
- cloudOwner, cloudSiteId, tenantId, error, "VDU", "queryVdu(Base)",
- ErrorCode.BusinessProcesssError.getValue(),
- "Create VFModule: Base Module DOES NOT EXIST");
+ String error = "Create VFModule: Base Module DOES NOT EXIST " + baseVfModuleId + " in " + cloudOwner
+ + "/" + cloudSiteId + "/" + tenantId + " USER ERROR";
+ logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(),
+ baseVfModuleId, cloudOwner, cloudSiteId, tenantId, error, "VDU", "queryVdu(Base)",
+ ErrorCode.BusinessProcesssError.getValue(), "Create VFModule: Base Module DOES NOT EXIST");
logger.debug(error);
throw new VnfException(error, MsoExceptionCategory.USERDATA);
} else {
@@ -918,27 +846,27 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
}
- // NOTE: For this section, heatTemplate is used for all template artifacts.
+ // NOTE: For this section, heatTemplate is used for all template artifacts.
// In final implementation (post-POC), the template object would either be generic or there would
// be a separate DB Table/Object for different sub-orchestrators.
- // NOTE: The template is fixed for the VF Module. The environment is part of the customization.
+ // NOTE: The template is fixed for the VF Module. The environment is part of the customization.
HeatTemplate heatTemplate = null;
HeatEnvironment heatEnvironment = null;
if (isVolumeRequest) {
- heatTemplate = vfModule.getVolumeHeatTemplate();
- heatEnvironment = vfModuleCust.getVolumeHeatEnv();
- } else {
- heatTemplate = vfModule.getModuleHeatTemplate();
- heatEnvironment = vfModuleCust.getHeatEnvironment();
- }
-
- if (heatTemplate == null) {
- String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + ", reqType="
- + requestType;
- logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", vfModuleType,
- "VNF", ErrorCode.DataError.getValue(), error);
+ heatTemplate = vfModule.getVolumeHeatTemplate();
+ heatEnvironment = vfModuleCust.getVolumeHeatEnv();
+ } else {
+ heatTemplate = vfModule.getModuleHeatTemplate();
+ heatEnvironment = vfModuleCust.getHeatEnvironment();
+ }
+
+ if (heatTemplate == null) {
+ String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType
+ + ", reqType=" + requestType;
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID",
+ vfModuleType, "VNF", ErrorCode.DataError.getValue(), error);
logger.debug(error);
throw new VnfException(error, MsoExceptionCategory.INTERNAL);
} else {
@@ -948,7 +876,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
if (heatEnvironment == null) {
String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType;
logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID",
- "OpenStack", ErrorCode.DataError.getValue(), error);
+ "OpenStack", ErrorCode.DataError.getValue(), error);
throw new VnfException(error, MsoExceptionCategory.INTERNAL);
} else {
logger.debug("Got Heat Environment from DB: " + heatEnvironment.getEnvironment());
@@ -956,152 +884,150 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
// Create the combined set of parameters from the incoming request, base-module outputs,
- // volume-module outputs. Also, convert all variables to their native object types.
+ // volume-module outputs. Also, convert all variables to their native object types.
- HashMap<String, Object> goldenInputs = new HashMap<String,Object>();
+ HashMap<String, Object> goldenInputs = new HashMap<String, Object>();
List<String> extraInputs = new ArrayList<String>();
- Boolean skipInputChecks = false;
-
- if (skipInputChecks) {
- goldenInputs = new HashMap<String,Object>();
- for (String key : inputs.keySet()) {
- goldenInputs.put(key, inputs.get(key));
- }
- }
- else {
- // Build maps for the parameters (including aliases) to simplify checks
- HashMap<String, HeatTemplateParam> params = new HashMap<String, HeatTemplateParam>();
-
- Set<HeatTemplateParam> paramSet = heatTemplate.getParameters();
- logger.debug("paramSet has " + paramSet.size() + " entries");
-
- for (HeatTemplateParam htp : paramSet) {
- params.put(htp.getParamName(), htp);
-
- // Include aliases.
- String alias = htp.getParamAlias();
- if (alias != null && !alias.equals("") && !params.containsKey(alias)) {
- params.put(alias, htp);
- }
- }
-
- // First, convert all inputs to their "template" type
- for (String key : inputs.keySet()) {
- if (params.containsKey(key)) {
- Object value = convertInputValue(inputs.get(key), params.get(key));
- if (value != null) {
- goldenInputs.put(key, value);
- }
- else {
- logger.debug("Failed to convert input " + key + "='" + inputs.get(key) + "' to " + params.get(key)
- .getParamType());
- }
- } else {
- extraInputs.add(key);
- }
- }
-
- if (!extraInputs.isEmpty()) {
- // Add multicloud inputs
- for (String key : MsoMulticloudUtils.MULTICLOUD_INPUTS) {
- if (extraInputs.contains(key)) {
- goldenInputs.put(key, inputs.get(key));
- extraInputs.remove(key);
- if (extraInputs.isEmpty()) {
- break;
- }
- }
- }
- logger.debug("Ignoring extra inputs: " + extraInputs);
- }
-
- // Next add in Volume Group Outputs if there are any. Copy directly without conversions.
- if (volumeGroupOutputs != null && !volumeGroupOutputs.isEmpty()) {
- for (String key : volumeGroupOutputs.keySet()) {
- if (params.containsKey(key) && !goldenInputs.containsKey(key)) {
- goldenInputs.put(key, volumeGroupOutputs.get(key));
- }
- }
- }
-
- // Next add in Base Module Outputs if there are any. Copy directly without conversions.
- if (baseModuleOutputs != null && !baseModuleOutputs.isEmpty()) {
- for (String key : baseModuleOutputs.keySet()) {
- if (params.containsKey(key) && !goldenInputs.containsKey(key)) {
- goldenInputs.put(key, baseModuleOutputs.get(key));
- }
- }
- }
-
- // TODO: The model should support a mechanism to pre-assign default parameter values
- // per "customization" (i.e. usage) of a given module. In HEAT, this is specified by
- // an Environment file. There is not a general mechanism in the model to handle this.
- // For the general case, any such parameter/values can be added dynamically to the
- // inputs (only if not already specified).
+ Boolean skipInputChecks = false;
+
+ if (skipInputChecks) {
+ goldenInputs = new HashMap<String, Object>();
+ for (String key : inputs.keySet()) {
+ goldenInputs.put(key, inputs.get(key));
+ }
+ } else {
+ // Build maps for the parameters (including aliases) to simplify checks
+ HashMap<String, HeatTemplateParam> params = new HashMap<String, HeatTemplateParam>();
+
+ Set<HeatTemplateParam> paramSet = heatTemplate.getParameters();
+ logger.debug("paramSet has " + paramSet.size() + " entries");
+
+ for (HeatTemplateParam htp : paramSet) {
+ params.put(htp.getParamName(), htp);
+
+ // Include aliases.
+ String alias = htp.getParamAlias();
+ if (alias != null && !alias.equals("") && !params.containsKey(alias)) {
+ params.put(alias, htp);
+ }
+ }
+
+ // First, convert all inputs to their "template" type
+ for (String key : inputs.keySet()) {
+ if (params.containsKey(key)) {
+ Object value = convertInputValue(inputs.get(key), params.get(key));
+ if (value != null) {
+ goldenInputs.put(key, value);
+ } else {
+ logger.debug("Failed to convert input " + key + "='" + inputs.get(key) + "' to "
+ + params.get(key).getParamType());
+ }
+ } else {
+ extraInputs.add(key);
+ }
+ }
+
+ if (!extraInputs.isEmpty()) {
+ // Add multicloud inputs
+ for (String key : MsoMulticloudUtils.MULTICLOUD_INPUTS) {
+ if (extraInputs.contains(key)) {
+ goldenInputs.put(key, inputs.get(key));
+ extraInputs.remove(key);
+ if (extraInputs.isEmpty()) {
+ break;
+ }
+ }
+ }
+ logger.debug("Ignoring extra inputs: " + extraInputs);
+ }
+
+ // Next add in Volume Group Outputs if there are any. Copy directly without conversions.
+ if (volumeGroupOutputs != null && !volumeGroupOutputs.isEmpty()) {
+ for (String key : volumeGroupOutputs.keySet()) {
+ if (params.containsKey(key) && !goldenInputs.containsKey(key)) {
+ goldenInputs.put(key, volumeGroupOutputs.get(key));
+ }
+ }
+ }
+
+ // Next add in Base Module Outputs if there are any. Copy directly without conversions.
+ if (baseModuleOutputs != null && !baseModuleOutputs.isEmpty()) {
+ for (String key : baseModuleOutputs.keySet()) {
+ if (params.containsKey(key) && !goldenInputs.containsKey(key)) {
+ goldenInputs.put(key, baseModuleOutputs.get(key));
+ }
+ }
+ }
+
+ // TODO: The model should support a mechanism to pre-assign default parameter values
+ // per "customization" (i.e. usage) of a given module. In HEAT, this is specified by
+ // an Environment file. There is not a general mechanism in the model to handle this.
+ // For the general case, any such parameter/values can be added dynamically to the
+ // inputs (only if not already specified).
// Check that required parameters have been supplied from any of the sources
String missingParams = null;
boolean checkRequiredParameters = true;
try {
String propertyString = this.environment.getProperty(MsoVnfPluginAdapterImpl.CHECK_REQD_PARAMS);
- if ("false".equalsIgnoreCase (propertyString) || "n".equalsIgnoreCase (propertyString)) {
+ if ("false".equalsIgnoreCase(propertyString) || "n".equalsIgnoreCase(propertyString)) {
checkRequiredParameters = false;
logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking..."
- + MsoVnfPluginAdapterImpl.CHECK_REQD_PARAMS);
+ + MsoVnfPluginAdapterImpl.CHECK_REQD_PARAMS);
}
} catch (Exception e) {
// No problem - default is true
- logger.debug ("An exception occured trying to get property " + MsoVnfPluginAdapterImpl.CHECK_REQD_PARAMS,
- e);
+ logger.debug("An exception occured trying to get property " + MsoVnfPluginAdapterImpl.CHECK_REQD_PARAMS,
+ e);
}
// Do the actual parameter checking.
// Include looking at the ENV file as a valid definition of a parameter value.
- // TODO: This handling of ENV applies only to Heat. A general mechanism to
+ // TODO: This handling of ENV applies only to Heat. A general mechanism to
// support pre-set parameter/values does not yet exist in the model.
//
- StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment());
- MsoHeatEnvironmentEntry mhee = new MsoHeatEnvironmentEntry (sb);
- for (HeatTemplateParam parm : heatTemplate.getParameters ()) {
- if (parm.isRequired () && (!goldenInputs.containsKey (parm.getParamName ()))) {
+ StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment());
+ MsoHeatEnvironmentEntry mhee = new MsoHeatEnvironmentEntry(sb);
+ for (HeatTemplateParam parm : heatTemplate.getParameters()) {
+ if (parm.isRequired() && (!goldenInputs.containsKey(parm.getParamName()))) {
if (mhee != null && mhee.containsParameter(parm.getParamName())) {
- logger.debug ("Required parameter " + parm.getParamName ()
- + " appears to be in environment - do not count as missing");
+ logger.debug("Required parameter " + parm.getParamName()
+ + " appears to be in environment - do not count as missing");
} else {
- logger.debug("adding to missing parameters list: " + parm.getParamName ());
- if (missingParams == null) {
- missingParams = parm.getParamName ();
- } else {
- missingParams += "," + parm.getParamName ();
- }
+ logger.debug("adding to missing parameters list: " + parm.getParamName());
+ if (missingParams == null) {
+ missingParams = parm.getParamName();
+ } else {
+ missingParams += "," + parm.getParamName();
+ }
}
}
}
- if (missingParams != null) {
- if (checkRequiredParameters) {
- // Problem - missing one or more required parameters
- String error = "Create VFModule: Missing Required inputs: " + missingParams;
- logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "VDU",
- ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs");
- logger.debug(error);
- throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ if (missingParams != null) {
+ if (checkRequiredParameters) {
+ // Problem - missing one or more required parameters
+ String error = "Create VFModule: Missing Required inputs: " + missingParams;
+ logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "VDU",
+ ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs");
+ logger.debug(error);
+ throw new VnfException(error, MsoExceptionCategory.USERDATA);
+ } else {
+ logger.debug("found missing parameters [" + missingParams
+ + "] - but checkRequiredParameters is false - " + "will not block");
+ }
} else {
- logger.debug(
- "found missing parameters [" + missingParams + "] - but checkRequiredParameters is false - "
- + "will not block");
+ logger.debug("No missing parameters found - ok to proceed");
}
- } else {
- logger.debug("No missing parameters found - ok to proceed");
- }
- } // NOTE: END PARAMETER CHECKING
+ } // NOTE: END PARAMETER CHECKING
- // Here we go... ready to deploy the VF Module.
- long instantiateVduStartTime = System.currentTimeMillis ();
- if (backout == null) backout = true;
+ // Here we go... ready to deploy the VF Module.
+ long instantiateVduStartTime = System.currentTimeMillis();
+ if (backout == null)
+ backout = true;
try {
// Construct the VDU Model structure to pass to the targeted VduPlugin
@@ -1118,22 +1044,25 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
} catch (VduException me) {
// Failed to instantiate the VDU.
me.addContext("CreateVFModule");
- String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId,
- tenantId, "VDU", ErrorCode.DataError.getValue(), "MsoException - instantiateVdu", me);
+ String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner,
+ cloudSiteId, tenantId, "VDU", ErrorCode.DataError.getValue(), "MsoException - instantiateVdu", me);
logger.debug(error);
// Convert to a generic VnfException
throw new VnfException(me);
} catch (NullPointerException npe) {
- String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + npe;
- logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId,
- tenantId, "VDU", ErrorCode.DataError.getValue(), "NullPointerException - instantiateVdu",
- npe);
+ String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + ": " + npe;
+ logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner,
+ cloudSiteId, tenantId, "VDU", ErrorCode.DataError.getValue(),
+ "NullPointerException - instantiateVdu", npe);
logger.debug(error);
logger.debug("NULL POINTER EXCEPTION at vduPlugin.instantiateVdu", npe);
throw new VnfException("NullPointerException during instantiateVdu");
} catch (Exception e) {
- String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + e;
+ String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId
+ + ": " + e;
logger.debug("Unhandled exception at vduPlugin.instantiateVdu", e);
logger.debug(error);
throw new VnfException("Exception during instantiateVdu: " + e.getMessage());
@@ -1142,10 +1071,10 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
// Reach this point if create is successful.
// Populate remaining rollback info and response parameters.
- vfRollback.setVnfCreated (true);
- vfRollback.setVnfId (vduInstance.getVduInstanceId());
+ vfRollback.setVnfCreated(true);
+ vfRollback.setVnfId(vduInstance.getVduInstanceId());
vnfId.value = vduInstance.getVduInstanceId();
- outputs.value = copyStringOutputs (vduInstance.getOutputs ());
+ outputs.value = copyStringOutputs(vduInstance.getOutputs());
rollback.value = vfRollback;
@@ -1154,40 +1083,37 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
}
- public void deleteVfModule (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vfModuleId,
- MsoRequest msoRequest,
- Holder <Map <String, String>> outputs) throws VnfException
- {
+ public void deleteVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vfModuleId,
+ MsoRequest msoRequest, Holder<Map<String, String>> outputs) throws VnfException {
logger.debug("Deleting VF Module " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId);
// Will capture execution time for metrics
- long startTime = System.currentTimeMillis ();
+ long startTime = System.currentTimeMillis();
// Capture the output parameters on a delete, so need to query first
- VduInstance vduInstance = null;
- CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null);
+ VduInstance vduInstance = null;
+ CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null);
// Use the VduPlugin.
VduPlugin vduPlugin = getVduPlugin(cloudSiteId, cloudOwner);
- try {
- vduInstance = vduPlugin.queryVdu (cloudInfo, vfModuleId);
- }
- catch (VduException e) {
- // Failed to query the VDU due to a plugin exception.
- // Convert to a generic VnfException
- e.addContext("QueryVFModule");
- String error = "Query VfModule (VDU): " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + e;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleId, cloudOwner, cloudSiteId,
- tenantId, "VDU", "QueryVFModule", ErrorCode.DataError.getValue(), "Exception - queryVDU", e);
- logger.debug(error);
- throw new VnfException(e);
- }
-
- // call method which handles the conversion from Map<String,Object> to Map<String,String> for our expected Object types
+ try {
+ vduInstance = vduPlugin.queryVdu(cloudInfo, vfModuleId);
+ } catch (VduException e) {
+ // Failed to query the VDU due to a plugin exception.
+ // Convert to a generic VnfException
+ e.addContext("QueryVFModule");
+ String error = "Query VfModule (VDU): " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/"
+ + tenantId + ": " + e;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleId, cloudOwner,
+ cloudSiteId, tenantId, "VDU", "QueryVFModule", ErrorCode.DataError.getValue(),
+ "Exception - queryVDU", e);
+ logger.debug(error);
+ throw new VnfException(e);
+ }
+
+ // call method which handles the conversion from Map<String,Object> to Map<String,String> for our expected
+ // Object types
outputs.value = convertMapStringObjectToStringString(vduInstance.getOutputs());
// Use the VduPlugin to delete the VDU.
@@ -1196,19 +1122,20 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
// - a vnfInstance object with status of NOTFOUND (VDU did not exist, treat as success)
// - a vnfInstance object with status of FAILED (error)
// Also, VduException could be thrown.
- long subStartTime = System.currentTimeMillis ();
+ long subStartTime = System.currentTimeMillis();
try {
- // TODO: Get an appropriate timeout value - require access to the model
+ // TODO: Get an appropriate timeout value - require access to the model
vduPlugin.deleteVdu(cloudInfo, vfModuleId, 5);
} catch (VduException me) {
- me.addContext ("DeleteVfModule");
+ me.addContext("DeleteVfModule");
// Convert to a generic VnfException
- String error = "Delete VF: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, cloudSiteId,
- tenantId, "VDU", "DeleteVdu", ErrorCode.DataError.getValue(),
- "Exception - DeleteVdu: " + me.getMessage());
+ String error =
+ "Delete VF: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me;
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner,
+ cloudSiteId, tenantId, "VDU", "DeleteVdu", ErrorCode.DataError.getValue(),
+ "Exception - DeleteVdu: " + me.getMessage());
logger.debug(error);
- throw new VnfException (me);
+ throw new VnfException(me);
}
// On success, nothing is returned.
@@ -1217,53 +1144,39 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter {
// Update VF Module not yet implemented for generic VDU plug-in model.
@Override
- public void updateVfModule (String cloudSiteId,
- String cloudOwner,
- String tenantId,
- String vnfType,
- String vnfVersion,
- String vnfName,
- String requestType,
- String volumeGroupHeatStackId,
- String baseVfHeatStackId,
- String vfModuleStackId,
- String modelCustomizationUuid,
- Map <String, Object> inputs,
- MsoRequest msoRequest,
- Holder <Map <String, String>> outputs,
- Holder <VnfRollback> rollback) throws VnfException
- {
- // This operation is not currently supported for VduPlugin-orchestrated VF Modules.
- logger.debug("Update VF Module command attempted but not supported");
- throw new VnfException ("UpdateVfModule: Unsupported command", MsoExceptionCategory.USERDATA);
- }
+ public void updateVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfType,
+ String vnfVersion, String vnfName, String requestType, String volumeGroupHeatStackId,
+ String baseVfHeatStackId, String vfModuleStackId, String modelCustomizationUuid, Map<String, Object> inputs,
+ MsoRequest msoRequest, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback)
+ throws VnfException {
+ // This operation is not currently supported for VduPlugin-orchestrated VF Modules.
+ logger.debug("Update VF Module command attempted but not supported");
+ throw new VnfException("UpdateVfModule: Unsupported command", MsoExceptionCategory.USERDATA);
+ }
/*
- * Dynamic selection of a VduPlugin version. For initial tests, base on the "orchestrator"
- * defined for the target cloud. Should really be looking at the VNF Model (ochestration_mode)
- * but we don't currently have access to that in Query and Delete cases.
+ * Dynamic selection of a VduPlugin version. For initial tests, base on the "orchestrator" defined for the target
+ * cloud. Should really be looking at the VNF Model (ochestration_mode) but we don't currently have access to that
+ * in Query and Delete cases.
*/
- private VduPlugin getVduPlugin (String cloudSiteId, String cloudOwner) {
- Optional<CloudSite> cloudSiteOp = cloudConfig.getCloudSite(cloudSiteId);
- if (cloudSiteOp.isPresent()) {
- CloudSite cloudSite = cloudSiteOp.get();
- String orchestrator = cloudSite.getOrchestrator();
-
- if (orchestrator.equalsIgnoreCase("CLOUDIFY")) {
- return cloudifyUtils;
- }
- else if (orchestrator.equalsIgnoreCase("HEAT")) {
- return heatUtils;
- }
- else if (orchestrator.equalsIgnoreCase("MULTICLOUD")) {
+ private VduPlugin getVduPlugin(String cloudSiteId, String cloudOwner) {
+ Optional<CloudSite> cloudSiteOp = cloudConfig.getCloudSite(cloudSiteId);
+ if (cloudSiteOp.isPresent()) {
+ CloudSite cloudSite = cloudSiteOp.get();
+ String orchestrator = cloudSite.getOrchestrator();
+
+ if (orchestrator.equalsIgnoreCase("CLOUDIFY")) {
+ return cloudifyUtils;
+ } else if (orchestrator.equalsIgnoreCase("HEAT")) {
+ return heatUtils;
+ } else if (orchestrator.equalsIgnoreCase("MULTICLOUD")) {
return multicloudUtils;
- }
- else {
+ } else {
// Default if cloudSite record exists - return HEAT plugin - will fail later
- return heatUtils;
+ return heatUtils;
}
- }
+ }
// Default if no cloudSite record exists - return multicloud plugin
- return multicloudUtils;
+ return multicloudUtils;
}
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VfRollback.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VfRollback.java
index 3736669094..7ba8ca8905 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VfRollback.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VfRollback.java
@@ -25,108 +25,129 @@ package org.onap.so.adapters.vnf;
import org.onap.so.entity.MsoRequest;
public class VfRollback {
- private String vnfId;
- private String tenantId;
- private String cloudSiteId;
- private boolean tenantCreated = false;
- private boolean vnfCreated = false;
- private MsoRequest msoRequest;
- private String volumeGroupName;
- private String volumeGroupId;
- private String requestType;
- private String volumeGroupHeatStackId;
- private String baseGroupHeatStackId;
- private boolean isBase = false;
- private String vfModuleStackId;
-
-
- public String getVnfId() {
- return vnfId;
- }
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
- public String getTenantId() {
- return tenantId;
- }
-
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getCloudSiteId() {
- return cloudSiteId;
- }
- public void setCloudSiteId(String cloudId) {
- this.cloudSiteId = cloudId;
- }
- public boolean getTenantCreated() {
- return tenantCreated;
- }
- public void setTenantCreated(boolean tenantCreated) {
- this.tenantCreated = tenantCreated;
- }
- public boolean getVnfCreated() {
- return vnfCreated;
- }
- public void setVnfCreated(boolean vnfCreated) {
- this.vnfCreated = vnfCreated;
- }
- public MsoRequest getMsoRequest() {
- return msoRequest;
- }
- public void setMsoRequest (MsoRequest msoRequest) {
- this.msoRequest = msoRequest;
- }
- public String getVolumeGroupName() {
- return this.volumeGroupName;
- }
- public void setVolumeGroupName(String volumeGroupName) {
- this.volumeGroupName = volumeGroupName;
- }
- public String getVolumeGroupId() {
- return this.volumeGroupId;
- }
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
- public String getRequestType() {
- return this.requestType;
- }
- public void setRequestType(String requestType) {
- this.requestType = requestType;
- }
- public String getVolumeGroupHeatStackId() {
- return this.volumeGroupHeatStackId;
- }
- public void setVolumeGroupHeatStackId(String volumeGroupHeatStackId) {
- this.volumeGroupHeatStackId = volumeGroupHeatStackId;
- }
-
- public String getBaseGroupHeatStackId() {
- return this.baseGroupHeatStackId;
- }
- public void setBaseGroupHeatStackId(String baseGroupHeatStackId) {
- this.baseGroupHeatStackId = baseGroupHeatStackId;
- }
-
- public boolean isBase() {
- return this.isBase;
- }
- public void setIsBase(boolean isBase) {
- this.isBase = isBase;
- }
- public String getVfModuleStackId() {
- return this.vfModuleStackId;
- }
- public void setVfModuleStackId(String vfModuleStackId) {
- this.vfModuleStackId = vfModuleStackId;
- }
-
- @Override
+ private String vnfId;
+ private String tenantId;
+ private String cloudSiteId;
+ private boolean tenantCreated = false;
+ private boolean vnfCreated = false;
+ private MsoRequest msoRequest;
+ private String volumeGroupName;
+ private String volumeGroupId;
+ private String requestType;
+ private String volumeGroupHeatStackId;
+ private String baseGroupHeatStackId;
+ private boolean isBase = false;
+ private String vfModuleStackId;
+
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudId) {
+ this.cloudSiteId = cloudId;
+ }
+
+ public boolean getTenantCreated() {
+ return tenantCreated;
+ }
+
+ public void setTenantCreated(boolean tenantCreated) {
+ this.tenantCreated = tenantCreated;
+ }
+
+ public boolean getVnfCreated() {
+ return vnfCreated;
+ }
+
+ public void setVnfCreated(boolean vnfCreated) {
+ this.vnfCreated = vnfCreated;
+ }
+
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
+
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
+
+ public String getVolumeGroupName() {
+ return this.volumeGroupName;
+ }
+
+ public void setVolumeGroupName(String volumeGroupName) {
+ this.volumeGroupName = volumeGroupName;
+ }
+
+ public String getVolumeGroupId() {
+ return this.volumeGroupId;
+ }
+
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ public String getRequestType() {
+ return this.requestType;
+ }
+
+ public void setRequestType(String requestType) {
+ this.requestType = requestType;
+ }
+
+ public String getVolumeGroupHeatStackId() {
+ return this.volumeGroupHeatStackId;
+ }
+
+ public void setVolumeGroupHeatStackId(String volumeGroupHeatStackId) {
+ this.volumeGroupHeatStackId = volumeGroupHeatStackId;
+ }
+
+ public String getBaseGroupHeatStackId() {
+ return this.baseGroupHeatStackId;
+ }
+
+ public void setBaseGroupHeatStackId(String baseGroupHeatStackId) {
+ this.baseGroupHeatStackId = baseGroupHeatStackId;
+ }
+
+ public boolean isBase() {
+ return this.isBase;
+ }
+
+ public void setIsBase(boolean isBase) {
+ this.isBase = isBase;
+ }
+
+ public String getVfModuleStackId() {
+ return this.vfModuleStackId;
+ }
+
+ public void setVfModuleStackId(String vfModuleStackId) {
+ this.vfModuleStackId = vfModuleStackId;
+ }
+
+ @Override
public String toString() {
- return "VfRollback: cloud=" + cloudSiteId + ", tenant=" + tenantId +
- ", vnf=" + vnfId + ", tenantCreated=" + tenantCreated +
- ", vnfCreated=" + vnfCreated + ", requestType = " + requestType +
- ", volumeGroupHeatStackId = " + this.volumeGroupHeatStackId;
- }
+ return "VfRollback: cloud=" + cloudSiteId + ", tenant=" + tenantId + ", vnf=" + vnfId + ", tenantCreated="
+ + tenantCreated + ", vnfCreated=" + vnfCreated + ", requestType = " + requestType
+ + ", volumeGroupHeatStackId = " + this.volumeGroupHeatStackId;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java
index d1a48a7c9b..487b14b942 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java
@@ -26,7 +26,6 @@ package org.onap.so.adapters.vnf;
import java.util.Map;
-
import javax.inject.Provider;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@@ -41,7 +40,6 @@ import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.ws.Holder;
-
import org.apache.http.HttpStatus;
import org.onap.so.adapters.vnf.exceptions.VnfException;
import org.onap.so.adapters.vnfrest.CreateVfModuleRequest;
@@ -66,7 +64,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@@ -74,636 +71,524 @@ import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
- * This class services calls to the REST interface for VF Modules (http://host:port/vnfs/rest/v1/vnfs)
- * Both XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default.
- * For testing, call with cloudSiteId = ___TESTING___
- * To test exceptions, also set tenantId = ___TESTING___
+ * This class services calls to the REST interface for VF Modules (http://host:port/vnfs/rest/v1/vnfs) Both XML and JSON
+ * can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. For testing, call
+ * with cloudSiteId = ___TESTING___ To test exceptions, also set tenantId = ___TESTING___
*/
@Path("/v1/vnfs")
@Api(value = "/v1/vnfs", description = "root of vnf adapters restful web service")
@Transactional
@Component
public class VnfAdapterRest {
- private static Logger logger = LoggerFactory.getLogger(VnfAdapterRest.class);
- private static final String TESTING_KEYWORD = "___TESTING___";
- private static final String RESP=", resp=";
-
- @Autowired
- private MsoVnfAdapterImpl vnfAdapter;
- //TODO Logging, SkipAAI, CREATED flags, Integrate with BPEL, Auth,
-
- @Autowired
- private Provider<BpelRestClient> bpelRestClientProvider;
-
-
- /*
- * URL:http://localhost:8080/vnfs/rest/v1/vnfs/<aaivnfid>/vf-modules/<aaimodid>
- * REQUEST:
- * {"deleteVfModuleRequest":
- {"cloudSiteId": "DAN",
- "tenantId": "214b428a1f554c02935e66330f6a5409",
- "vnfId": "somevnfid",
- "vfModuleId": "somemodid",
- "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73",
- "messageId": "ra.1",
- "notificationUrl": "http://localhost:8089/vnfmock",
- "skipAAI": true,
- "msoRequest": {
- "requestId": "ra1",
- "serviceInstanceId": "sa1"
- }}
- }
- */
- @DELETE
- @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "DeleteVfModule",
- response = Response.class,
- notes = "Delete an existing vnfModule, DeleteVfModuleRequest JSON is required")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfModule has been successfully deleted"),
- @ApiResponse(code = 202, message = "delete vnfModule request has been accepted (async only)"),
- @ApiResponse(code = 500, message = "delete vnfModule failed, examine entity object for details") })
- public Response deleteVfModule (
- @ApiParam(value = "aaiVnfId", required = true)
- @PathParam("aaiVnfId") String aaiVnfId,
- @ApiParam(value = "aaiVfModuleId", required = true)
- @PathParam("aaiVfModuleId") String aaiVfModuleId,
- @ApiParam(value = "DeleteVfModuleRequest", required = true)
- final DeleteVfModuleRequest req)
- {
- logger.debug("Delete VfModule enter: " + req.toJsonString());
- if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) {
- logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL");
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity("vnfid in URL does not match content")
- .build();
- }
- if (aaiVfModuleId == null || !aaiVfModuleId.equals(req.getVfModuleId())) {
- logger.debug("Req rejected - aaiVfModuleId not provided or doesn't match URL");
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity("vfModuleId in URL does not match content")
- .build();
- }
- DeleteVfModuleTask task = new DeleteVfModuleTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling delete, send generic failure as sync resp to caller
- logger.error("", MessageEnum.RA_DELETE_VNF_ERR.toString(), "deleteVfModule",
- ErrorCode.BusinessProcesssError.getValue(), "Exception in deleteVfModule", e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("deleteVNFVolumes exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class DeleteVfModuleTask implements Runnable {
- private final DeleteVfModuleRequest req;
- private DeleteVfModuleResponse response = null;
- private VfModuleExceptionResponse eresp = null;
- private boolean sendxml;
-
- public DeleteVfModuleTask(DeleteVfModuleRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<DeleteVfModuleResponse>(response) {}
- : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
-
- @Override
- public void run() {
- try {
- String cloudsite = req.getCloudSiteId();
- Holder<Map<String, String>> outputs = new Holder <> ();
- if (cloudsite != null && !cloudsite.equals(TESTING_KEYWORD)) {
- //vnfAdapter.deleteVnf (req.getCloudSiteId(), req.getTenantId(), req.getVfModuleStackId(), req.getMsoRequest());
- vnfAdapter.deleteVfModule (req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), req.getVfModuleStackId(), req.getMsoRequest(), outputs);
- }
- response = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), Boolean.TRUE, req.getMessageId(), outputs.value);
- } catch (VnfException e) {
- logger.error("{} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(),
- ErrorCode.BusinessProcesssError.getValue(), "VnfException - Delete VNF Module", e);
- eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("Delete vfModule exit: code=" + getStatusCode() + RESP + getResponse());
- }
- }
-
- /*
- * URL:http://localhost:8080/vnfs/rest/v1/vnfs/<aaiVnfId>/vf-modules/<aaiVfModuleId>?cloudSiteId=DAN&tenantId=vfModule?&skipAAI=TRUE&msoRequest.requestId=ra1&msoRequest.serviceInstanceId=si1&vfModuleName=T2N2S1
- * RESP:
- * {"queryVfModuleResponse": {
- "vfModuleId": "AvfmodId",
- "vfModuleOutputs": {"entry": {
- "key": "server_private_ip_1",
- "value": "10.100.1.25"
- }},
- "vfModuleStackId": "RaaVnf1/abfa8a6d-feb1-40af-aea3-109403b1cf6b",
- "vnfId": "AvnfID",
- "vnfStatus": "ACTIVE"
- }}
- */
- @GET
- @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "QueryVfModule",
- response = Response.class,
- notes = "Query an existing vnfModule")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfModule has been successfully queried"),
- @ApiResponse(code = 500, message = "query vnfModule failed, examine entity object for details") })
- public Response queryVfModule(
- @ApiParam(value = "aaiVnfId", required = true)
- @PathParam("aaiVnfId") String aaiVnfId,
- @ApiParam(value = "aaiVfModuleId", required = true)
- @PathParam("aaiVfModuleId") String aaiVfModuleId,
- @ApiParam(value = "cloudSiteId", required = true)
- @QueryParam("cloudSiteId") String cloudSiteId,
- @ApiParam(value = "cloudOwner", required = true)
- @QueryParam("cloudOwner") String cloudOwner,
- @ApiParam(value = "tenantId", required = true)
- @QueryParam("tenantId") String tenantId,
- @ApiParam(value = "vfModuleName", required = true)
- @QueryParam("vfModuleName") String vfModuleName, //RAA? Id in doc
- @ApiParam(value = "skipAAI", required = true)
- @QueryParam("skipAAI") Boolean skipAAI,
- @ApiParam(value = "msoRequest.requestId", required = true)
- @QueryParam("msoRequest.requestId") String requestId,
- @ApiParam(value = "msoRequest.serviceInstanceId", required = true)
- @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId)
- {
- //This request responds synchronously only
- logger.debug("Query vfModule enter:" + vfModuleName);
- MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId);
-
- try {
- int respStatus = HttpStatus.SC_OK;
- QueryVfModuleResponse qryResp = new QueryVfModuleResponse(aaiVnfId, aaiVfModuleId, null, null, null);
- Holder<Boolean> vnfExists = new Holder<>();
- Holder<String> vfModuleId = new Holder<>();
- Holder<VnfStatus> status = new Holder<>();
- Holder<Map<String, String>> outputs = new Holder <> ();
- vnfAdapter.queryVnf (cloudSiteId, cloudOwner, tenantId, vfModuleName, msoRequest, vnfExists, vfModuleId, status, outputs);
- if (!vnfExists.value) {
- logger.debug("vfModule not found");
- respStatus = HttpStatus.SC_NOT_FOUND;
- } else {
- logger.debug("vfModule found" + vfModuleId.value + ", status=" + status.value);
- qryResp.setVfModuleId(vfModuleId.value);
- qryResp.setVnfStatus(status.value);
- qryResp.setVfModuleOutputs(outputs.value);
- }
- logger.debug("Query vfModule exit");
- return Response
- .status(respStatus)
- .entity(new GenericEntity<QueryVfModuleResponse>(qryResp) {})
- .build();
- } catch (VnfException e) {
- logger.error("{} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule",
- ErrorCode.BusinessProcesssError.getValue(), "VnfException - queryVfModule", e);
- VfModuleExceptionResponse excResp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null);
- return Response
- .status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity(new GenericEntity<VfModuleExceptionResponse>(excResp) {})
- .build();
- }
- }
-
- /*URL: http://localhost:8080/vnfs/rest/v1/vnfs/<aaivnfid>/vf-modules
- *REQUEST:
- * {"createVfModuleRequest":
- {"cloudSiteId": "DAN",
- "tenantId": "214b428a1f554c02935e66330f6a5409",
- "vnfId": "somevnfid",
- "vfModuleId": "somemodid",
- "vfModuleName": "RaaVnf1",
- "vnfType": "ApacheVnf",
- "vfModuleParams": {"entry": [
- {"key": "network_id",
- "value": "59ed7b41-2983-413f-ba93-e7d437433916"},
- {"key": "subnet_id",
- "value": "086c9298-5c57-49b7-bb2b-6fd5730c5d92"},
- {"key": "server_name_0",
- "value": "RaaVnf1"}
- ]},
- "failIfExists": true,
- "messageId": "ra.1",
- "notificationUrl": "http://localhost:8089/vnfmock",
- "skipAAI": true,
- "msoRequest": {
- "requestId": "ra1",
- "serviceInstanceId": "sa1"
- }}
- }
- */
- @POST
- @Path("{aaiVnfId}/vf-modules")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "CreateVfModule",
- response = Response.class,
- notes = "Create a vnfModule")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfModule has been successfully created"),
- @ApiResponse(code = 202, message = "create vnfModule request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "create vnfModule failed, examine entity object for details") })
- public Response createVfModule(
- @ApiParam(value = "aaiVnfId", required = true)
- @PathParam("aaiVnfId") String aaiVnfId,
- @ApiParam(value = "CreateVfModuleRequest", required = true)
- final CreateVfModuleRequest req)
- {
- logger.debug("Create VfModule enter inside VnfAdapterRest: " + req.toJsonString());
- if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) {
- logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL");
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity("vnfid in URL does not match content")
- .build();
- }
- CreateVfModuleTask task = new CreateVfModuleTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR, "createVfModule",
- ErrorCode.BusinessProcesssError, "Exception - createVfModule", e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("createVfModule exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class CreateVfModuleTask implements Runnable {
- private final CreateVfModuleRequest req;
- private CreateVfModuleResponse response = null;
- private VfModuleExceptionResponse eresp = null;
- private boolean sendxml;
-
- public CreateVfModuleTask(CreateVfModuleRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<CreateVfModuleResponse>(response) {}
- : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
-
- @Override
- public void run() {
- logger.debug ("CreateVfModuleTask start");
- try {
- // Synchronous Web Service Outputs
- Holder <String> vfModuleStackId = new Holder <> ();
- Holder <Map <String, String>> outputs = new Holder <> ();
- Holder <VnfRollback> vnfRollback = new Holder <> ();
- String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
- logger.debug("completeVnfVfModuleType=" + completeVnfVfModuleType);
- String cloudsite = req.getCloudSiteId();
- String cloudOwner = req.getCloudOwner();
- if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) {
- String tenant = req.getTenantId();
- if (tenant != null && tenant.equals(TESTING_KEYWORD)) {
- throw new VnfException("testing.");
- }
- vnfRollback.value = new VnfRollback(req.getVnfId(), tenant, cloudOwner, cloudsite,
- true, false, new MsoRequest("reqid", "svcid"),
- req.getVolumeGroupId(), req.getVolumeGroupId(), req.getRequestType(), req.getModelCustomizationUuid());
- vfModuleStackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484";
- outputs.value = VolumeAdapterRest.testMap();
- } else {
-// vnfAdapter.createVnf (createReq.getCloudSiteId(),
-// createReq.getTenantId(),
-// createReq.getVnfType(),
-// createReq.getVnfVersion(),
-// createReq.getVfModuleName(),
-// createReq.getRequestType(),
-// createReq.getVolumeGroupStackId(),
-// createReq.getVfModuleParams(),
-// createReq.getFailIfExists(),
-// createReq.getBackout(),
-// createReq.getMsoRequest(),
-// vfModuleStackId,
-// outputs,
-// vnfRollback);
- vnfAdapter.createVfModule(req.getCloudSiteId(),
- req.getCloudOwner(),
- req.getTenantId(),
- //req.getVnfType(),
- completeVnfVfModuleType,
- req.getVnfVersion(),
- req.getVnfId(),
- req.getVfModuleName(),
- req.getVfModuleId(),
- req.getRequestType(),
- req.getVolumeGroupStackId(),
- req.getBaseVfModuleStackId(),
- req.getModelCustomizationUuid(),
- req.getVfModuleParams(),
- req.getFailIfExists(),
- req.getBackout(),
- req.getEnableBridge(),
- req.getMsoRequest(),
- vfModuleStackId,
- outputs,
- vnfRollback);
- }
- VfModuleRollback modRollback = new VfModuleRollback(vnfRollback.value, req.getVfModuleId(), vfModuleStackId.value, req.getMessageId());
- response = new CreateVfModuleResponse(req.getVnfId(), req.getVfModuleId(),
- vfModuleStackId.value, Boolean.TRUE, outputs.value, modRollback, req.getMessageId());
- } catch (VnfException e) {
- logger.debug("Exception :",e);
- eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("CreateVfModuleTask exit: code=" + getStatusCode() + RESP + getResponse());
- }
- }
-
- @PUT
- @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "UpdateVfModule",
- response = Response.class,
- notes = "Update an existing vnfModule")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfModule has been successfully updated"),
- @ApiResponse(code = 202, message = "update vnfModule request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "update vnfModule failed, examine entity object for details") })
- public Response updateVfModule(
- @ApiParam(value = "aaiVnfId", required = true)
- @PathParam("aaiVnfId") String aaiVnfId,
- @ApiParam(value = "aaiVfModuleId", required = true)
- @PathParam("aaiVfModuleId") String aaiVfModuleId,
- @ApiParam(value = "UpdateVfModuleRequest", required = true)
- final UpdateVfModuleRequest req)
- {
- logger.debug("Update VfModule enter: " + req.toJsonString());
- UpdateVfModulesTask task = new UpdateVfModulesTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), "updateVfModule",
- ErrorCode.BusinessProcesssError.getValue(), "Exception - updateVfModule", e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("updateVfModules exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class UpdateVfModulesTask implements Runnable {
- private final UpdateVfModuleRequest req;
- private UpdateVfModuleResponse response = null;
- private VfModuleExceptionResponse eresp = null;
- private boolean sendxml;
-
- public UpdateVfModulesTask(UpdateVfModuleRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<UpdateVfModuleResponse>(response) {}
- : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- try {
- //MsoVnfAdapter vnfAdapter = new MsoVnfAdapterImpl (msoPropertiesFactory, cloudConfigFactory);
-
- // Synchronous Web Service Outputs
- Holder <String> vfModuleStackId = new Holder <> ();
- Holder <Map <String, String>> outputs = new Holder <> ();
- Holder <VnfRollback> vnfRollback = new Holder <> ();
- String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
- logger.debug("in updateVf - completeVnfVfModuleType=" + completeVnfVfModuleType);
-
- vnfAdapter.updateVfModule (req.getCloudSiteId(),
- req.getCloudOwner(),
- req.getTenantId(),
- //req.getVnfType(),
- completeVnfVfModuleType,
- req.getVnfVersion(),
- req.getVfModuleName(),
- req.getRequestType(),
- req.getVolumeGroupStackId(),
- req.getBaseVfModuleStackId(),
- req.getVfModuleStackId(),
- req.getModelCustomizationUuid(),
- req.getVfModuleParams(),
- req.getMsoRequest(),
- outputs,
- vnfRollback);
-
- response = new UpdateVfModuleResponse(req.getVnfId(), req.getVfModuleId(),
- vfModuleStackId.value, outputs.value, req.getMessageId());
- } catch (VnfException e) {
- logger.debug("Exception :",e);
- eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost (getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("Update VfModule exit: code=" + getStatusCode() + RESP + getResponse());
- }
- }
- /*
- * URL:http://localhost:8080/vnfs/rest/v1/vnfs/<aaivnfid>/vf-modules/<aaimodid>/rollback
- * REQUEST:
- * {"deleteVfModuleRequest":
- {"cloudSiteId": "DAN",
- "tenantId": "214b428a1f554c02935e66330f6a5409",
- "vnfId": "somevnfid",
- "vfModuleId": "somemodid",
- "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73",
- "messageId": "ra.1",
- "notificationUrl": "http://localhost:8089/vnfmock",
- "skipAAI": true,
- "msoRequest": {
- "requestId": "ra1",
- "serviceInstanceId": "sa1"
- }}
- }
- */
- @DELETE
- @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}/rollback")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "RollbackVfModule",
- response = Response.class,
- notes = "Rollback an existing vnfModule")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfModule has been successfully rolled back"),
- @ApiResponse(code = 202, message = "rollback vnfModule request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "rollback vnfModule failed, examine entity object for details") })
- public Response rollbackVfModule (
- @ApiParam(value = "aaiVnfId", required = true)
- @PathParam("aaiVnfId") String aaiVnfId,
- @ApiParam(value = "aaiVfModuleId", required = true)
- @PathParam("aaiVfModuleId") String aaiVfModuleId,
- @ApiParam(value = "RollbackVfModuleRequest", required = true)
- //@QueryParam("rollback") String rollback,
- final RollbackVfModuleRequest req)
- {
- logger.debug("Rollback VfModule enter: " + req.toJsonString());
- RollbackVfModulesTask task = new RollbackVfModulesTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), "rollbackVfModule",
- ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("rollbackVfModule exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class RollbackVfModulesTask implements Runnable {
- private final RollbackVfModuleRequest req;
- private RollbackVfModuleResponse response = null;
- private VfModuleExceptionResponse eresp = null;
- private boolean sendxml;
-
- public RollbackVfModulesTask(RollbackVfModuleRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<RollbackVfModuleResponse>(response) {}
- : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- try {
- VfModuleRollback vmr = req.getVfModuleRollback();
- VnfRollback vrb = new VnfRollback(
- vmr.getVfModuleStackId(), vmr.getTenantId(), vmr.getCloudOwner(), vmr.getCloudSiteId(), true, true,
- vmr.getMsoRequest(), null, null, null, null);
- vnfAdapter.rollbackVnf (vrb);
- response = new RollbackVfModuleResponse(Boolean.TRUE, req.getMessageId());
- } catch (VnfException e) {
- logger.error("{} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR, ErrorCode.BusinessProcesssError,
- "Exception" + " - " + "rollbackVfModule", e);
- eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, false, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost (getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("RollbackVfModulesTask exit: code=" + getStatusCode() + RESP + getResponse());
- }
- }
+ private static Logger logger = LoggerFactory.getLogger(VnfAdapterRest.class);
+ private static final String TESTING_KEYWORD = "___TESTING___";
+ private static final String RESP = ", resp=";
+
+ @Autowired
+ private MsoVnfAdapterImpl vnfAdapter;
+ // TODO Logging, SkipAAI, CREATED flags, Integrate with BPEL, Auth,
+
+ @Autowired
+ private Provider<BpelRestClient> bpelRestClientProvider;
+
+
+ /*
+ * URL:http://localhost:8080/vnfs/rest/v1/vnfs/<aaivnfid>/vf-modules/<aaimodid> REQUEST: {"deleteVfModuleRequest":
+ * {"cloudSiteId": "DAN", "tenantId": "214b428a1f554c02935e66330f6a5409", "vnfId": "somevnfid", "vfModuleId":
+ * "somemodid", "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73", "messageId": "ra.1", "notificationUrl":
+ * "http://localhost:8089/vnfmock", "skipAAI": true, "msoRequest": { "requestId": "ra1", "serviceInstanceId": "sa1"
+ * }} }
+ */
+ @DELETE
+ @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "DeleteVfModule", response = Response.class,
+ notes = "Delete an existing vnfModule, DeleteVfModuleRequest JSON is required")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully deleted"),
+ @ApiResponse(code = 202, message = "delete vnfModule request has been accepted (async only)"),
+ @ApiResponse(code = 500, message = "delete vnfModule failed, examine entity object for details")})
+ public Response deleteVfModule(
+ @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId,
+ @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId,
+ @ApiParam(value = "DeleteVfModuleRequest", required = true) final DeleteVfModuleRequest req) {
+ logger.debug("Delete VfModule enter: " + req.toJsonString());
+ if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) {
+ logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL");
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN)
+ .entity("vnfid in URL does not match content").build();
+ }
+ if (aaiVfModuleId == null || !aaiVfModuleId.equals(req.getVfModuleId())) {
+ logger.debug("Req rejected - aaiVfModuleId not provided or doesn't match URL");
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN)
+ .entity("vfModuleId in URL does not match content").build();
+ }
+ DeleteVfModuleTask task = new DeleteVfModuleTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling delete, send generic failure as sync resp to caller
+ logger.error("", MessageEnum.RA_DELETE_VNF_ERR.toString(), "deleteVfModule",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception in deleteVfModule", e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("deleteVNFVolumes exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class DeleteVfModuleTask implements Runnable {
+ private final DeleteVfModuleRequest req;
+ private DeleteVfModuleResponse response = null;
+ private VfModuleExceptionResponse eresp = null;
+ private boolean sendxml;
+
+ public DeleteVfModuleTask(DeleteVfModuleRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<DeleteVfModuleResponse>(response) {}
+ : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ try {
+ String cloudsite = req.getCloudSiteId();
+ Holder<Map<String, String>> outputs = new Holder<>();
+ if (cloudsite != null && !cloudsite.equals(TESTING_KEYWORD)) {
+ // vnfAdapter.deleteVnf (req.getCloudSiteId(), req.getTenantId(), req.getVfModuleStackId(),
+ // req.getMsoRequest());
+ vnfAdapter.deleteVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(),
+ req.getVfModuleStackId(), req.getMsoRequest(), outputs);
+ }
+ response = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), Boolean.TRUE,
+ req.getMessageId(), outputs.value);
+ } catch (VnfException e) {
+ logger.error("{} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(),
+ ErrorCode.BusinessProcesssError.getValue(), "VnfException - Delete VNF Module", e);
+ eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("Delete vfModule exit: code=" + getStatusCode() + RESP + getResponse());
+ }
+ }
+
+ /*
+ * URL:http://localhost:8080/vnfs/rest/v1/vnfs/<aaiVnfId>/vf-modules/<aaiVfModuleId>?cloudSiteId=DAN&tenantId=
+ * vfModule?&skipAAI=TRUE&msoRequest.requestId=ra1&msoRequest.serviceInstanceId=si1&vfModuleName=T2N2S1 RESP:
+ * {"queryVfModuleResponse": { "vfModuleId": "AvfmodId", "vfModuleOutputs": {"entry": { "key":
+ * "server_private_ip_1", "value": "10.100.1.25" }}, "vfModuleStackId":
+ * "RaaVnf1/abfa8a6d-feb1-40af-aea3-109403b1cf6b", "vnfId": "AvnfID", "vnfStatus": "ACTIVE" }}
+ */
+ @GET
+ @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}")
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "QueryVfModule", response = Response.class, notes = "Query an existing vnfModule")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully queried"),
+ @ApiResponse(code = 500, message = "query vnfModule failed, examine entity object for details")})
+ public Response queryVfModule(@ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId,
+ @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId,
+ @ApiParam(value = "cloudSiteId", required = true) @QueryParam("cloudSiteId") String cloudSiteId,
+ @ApiParam(value = "cloudOwner", required = true) @QueryParam("cloudOwner") String cloudOwner,
+ @ApiParam(value = "tenantId", required = true) @QueryParam("tenantId") String tenantId,
+ @ApiParam(value = "vfModuleName", required = true) @QueryParam("vfModuleName") String vfModuleName, // RAA?
+ // Id in
+ // doc
+ @ApiParam(value = "skipAAI", required = true) @QueryParam("skipAAI") Boolean skipAAI,
+ @ApiParam(value = "msoRequest.requestId",
+ required = true) @QueryParam("msoRequest.requestId") String requestId,
+ @ApiParam(value = "msoRequest.serviceInstanceId",
+ required = true) @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId) {
+ // This request responds synchronously only
+ logger.debug("Query vfModule enter:" + vfModuleName);
+ MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId);
+
+ try {
+ int respStatus = HttpStatus.SC_OK;
+ QueryVfModuleResponse qryResp = new QueryVfModuleResponse(aaiVnfId, aaiVfModuleId, null, null, null);
+ Holder<Boolean> vnfExists = new Holder<>();
+ Holder<String> vfModuleId = new Holder<>();
+ Holder<VnfStatus> status = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
+ vnfAdapter.queryVnf(cloudSiteId, cloudOwner, tenantId, vfModuleName, msoRequest, vnfExists, vfModuleId,
+ status, outputs);
+ if (!vnfExists.value) {
+ logger.debug("vfModule not found");
+ respStatus = HttpStatus.SC_NOT_FOUND;
+ } else {
+ logger.debug("vfModule found" + vfModuleId.value + ", status=" + status.value);
+ qryResp.setVfModuleId(vfModuleId.value);
+ qryResp.setVnfStatus(status.value);
+ qryResp.setVfModuleOutputs(outputs.value);
+ }
+ logger.debug("Query vfModule exit");
+ return Response.status(respStatus).entity(new GenericEntity<QueryVfModuleResponse>(qryResp) {}).build();
+ } catch (VnfException e) {
+ logger.error("{} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule",
+ ErrorCode.BusinessProcesssError.getValue(), "VnfException - queryVfModule", e);
+ VfModuleExceptionResponse excResp =
+ new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null);
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
+ .entity(new GenericEntity<VfModuleExceptionResponse>(excResp) {}).build();
+ }
+ }
+
+ /*
+ * URL: http://localhost:8080/vnfs/rest/v1/vnfs/<aaivnfid>/vf-modules REQUEST: {"createVfModuleRequest":
+ * {"cloudSiteId": "DAN", "tenantId": "214b428a1f554c02935e66330f6a5409", "vnfId": "somevnfid", "vfModuleId":
+ * "somemodid", "vfModuleName": "RaaVnf1", "vnfType": "ApacheVnf", "vfModuleParams": {"entry": [ {"key":
+ * "network_id", "value": "59ed7b41-2983-413f-ba93-e7d437433916"}, {"key": "subnet_id", "value":
+ * "086c9298-5c57-49b7-bb2b-6fd5730c5d92"}, {"key": "server_name_0", "value": "RaaVnf1"} ]}, "failIfExists": true,
+ * "messageId": "ra.1", "notificationUrl": "http://localhost:8089/vnfmock", "skipAAI": true, "msoRequest": {
+ * "requestId": "ra1", "serviceInstanceId": "sa1" }} }
+ */
+ @POST
+ @Path("{aaiVnfId}/vf-modules")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "CreateVfModule", response = Response.class, notes = "Create a vnfModule")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully created"),
+ @ApiResponse(code = 202, message = "create vnfModule request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "create vnfModule failed, examine entity object for details")})
+ public Response createVfModule(
+ @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId,
+ @ApiParam(value = "CreateVfModuleRequest", required = true) final CreateVfModuleRequest req) {
+ logger.debug("Create VfModule enter inside VnfAdapterRest: " + req.toJsonString());
+ if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) {
+ logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL");
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN)
+ .entity("vnfid in URL does not match content").build();
+ }
+ CreateVfModuleTask task = new CreateVfModuleTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR, "createVfModule",
+ ErrorCode.BusinessProcesssError, "Exception - createVfModule", e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("createVfModule exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class CreateVfModuleTask implements Runnable {
+ private final CreateVfModuleRequest req;
+ private CreateVfModuleResponse response = null;
+ private VfModuleExceptionResponse eresp = null;
+ private boolean sendxml;
+
+ public CreateVfModuleTask(CreateVfModuleRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<CreateVfModuleResponse>(response) {}
+ : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("CreateVfModuleTask start");
+ try {
+ // Synchronous Web Service Outputs
+ Holder<String> vfModuleStackId = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
+ Holder<VnfRollback> vnfRollback = new Holder<>();
+ String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
+ logger.debug("completeVnfVfModuleType=" + completeVnfVfModuleType);
+ String cloudsite = req.getCloudSiteId();
+ String cloudOwner = req.getCloudOwner();
+ if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) {
+ String tenant = req.getTenantId();
+ if (tenant != null && tenant.equals(TESTING_KEYWORD)) {
+ throw new VnfException("testing.");
+ }
+ vnfRollback.value = new VnfRollback(req.getVnfId(), tenant, cloudOwner, cloudsite, true, false,
+ new MsoRequest("reqid", "svcid"), req.getVolumeGroupId(), req.getVolumeGroupId(),
+ req.getRequestType(), req.getModelCustomizationUuid());
+ vfModuleStackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484";
+ outputs.value = VolumeAdapterRest.testMap();
+ } else {
+ // vnfAdapter.createVnf (createReq.getCloudSiteId(),
+ // createReq.getTenantId(),
+ // createReq.getVnfType(),
+ // createReq.getVnfVersion(),
+ // createReq.getVfModuleName(),
+ // createReq.getRequestType(),
+ // createReq.getVolumeGroupStackId(),
+ // createReq.getVfModuleParams(),
+ // createReq.getFailIfExists(),
+ // createReq.getBackout(),
+ // createReq.getMsoRequest(),
+ // vfModuleStackId,
+ // outputs,
+ // vnfRollback);
+ vnfAdapter.createVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(),
+ // req.getVnfType(),
+ completeVnfVfModuleType, req.getVnfVersion(), req.getVnfId(), req.getVfModuleName(),
+ req.getVfModuleId(), req.getRequestType(), req.getVolumeGroupStackId(),
+ req.getBaseVfModuleStackId(), req.getModelCustomizationUuid(), req.getVfModuleParams(),
+ req.getFailIfExists(), req.getBackout(), req.getEnableBridge(), req.getMsoRequest(),
+ vfModuleStackId, outputs, vnfRollback);
+ }
+ VfModuleRollback modRollback = new VfModuleRollback(vnfRollback.value, req.getVfModuleId(),
+ vfModuleStackId.value, req.getMessageId());
+ response = new CreateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), vfModuleStackId.value,
+ Boolean.TRUE, outputs.value, modRollback, req.getMessageId());
+ } catch (VnfException e) {
+ logger.debug("Exception :", e);
+ eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("CreateVfModuleTask exit: code=" + getStatusCode() + RESP + getResponse());
+ }
+ }
+
+ @PUT
+ @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "UpdateVfModule", response = Response.class, notes = "Update an existing vnfModule")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully updated"),
+ @ApiResponse(code = 202, message = "update vnfModule request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "update vnfModule failed, examine entity object for details")})
+ public Response updateVfModule(
+ @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId,
+ @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId,
+ @ApiParam(value = "UpdateVfModuleRequest", required = true) final UpdateVfModuleRequest req) {
+ logger.debug("Update VfModule enter: " + req.toJsonString());
+ UpdateVfModulesTask task = new UpdateVfModulesTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), "updateVfModule",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception - updateVfModule", e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("updateVfModules exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class UpdateVfModulesTask implements Runnable {
+ private final UpdateVfModuleRequest req;
+ private UpdateVfModuleResponse response = null;
+ private VfModuleExceptionResponse eresp = null;
+ private boolean sendxml;
+
+ public UpdateVfModulesTask(UpdateVfModuleRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<UpdateVfModuleResponse>(response) {}
+ : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ try {
+ // MsoVnfAdapter vnfAdapter = new MsoVnfAdapterImpl (msoPropertiesFactory, cloudConfigFactory);
+
+ // Synchronous Web Service Outputs
+ Holder<String> vfModuleStackId = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
+ Holder<VnfRollback> vnfRollback = new Holder<>();
+ String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
+ logger.debug("in updateVf - completeVnfVfModuleType=" + completeVnfVfModuleType);
+
+ vnfAdapter.updateVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(),
+ // req.getVnfType(),
+ completeVnfVfModuleType, req.getVnfVersion(), req.getVfModuleName(), req.getRequestType(),
+ req.getVolumeGroupStackId(), req.getBaseVfModuleStackId(), req.getVfModuleStackId(),
+ req.getModelCustomizationUuid(), req.getVfModuleParams(), req.getMsoRequest(), outputs,
+ vnfRollback);
+
+ response = new UpdateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), vfModuleStackId.value,
+ outputs.value, req.getMessageId());
+ } catch (VnfException e) {
+ logger.debug("Exception :", e);
+ eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("Update VfModule exit: code=" + getStatusCode() + RESP + getResponse());
+ }
+ }
+
+ /*
+ * URL:http://localhost:8080/vnfs/rest/v1/vnfs/<aaivnfid>/vf-modules/<aaimodid>/rollback REQUEST:
+ * {"deleteVfModuleRequest": {"cloudSiteId": "DAN", "tenantId": "214b428a1f554c02935e66330f6a5409", "vnfId":
+ * "somevnfid", "vfModuleId": "somemodid", "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73", "messageId":
+ * "ra.1", "notificationUrl": "http://localhost:8089/vnfmock", "skipAAI": true, "msoRequest": { "requestId": "ra1",
+ * "serviceInstanceId": "sa1" }} }
+ */
+ @DELETE
+ @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}/rollback")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "RollbackVfModule", response = Response.class, notes = "Rollback an existing vnfModule")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully rolled back"),
+ @ApiResponse(code = 202,
+ message = "rollback vnfModule request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "rollback vnfModule failed, examine entity object for details")})
+ public Response rollbackVfModule(
+ @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId,
+ @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId,
+ @ApiParam(value = "RollbackVfModuleRequest", required = true)
+ // @QueryParam("rollback") String rollback,
+ final RollbackVfModuleRequest req) {
+ logger.debug("Rollback VfModule enter: " + req.toJsonString());
+ RollbackVfModulesTask task = new RollbackVfModulesTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), "rollbackVfModule",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("rollbackVfModule exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class RollbackVfModulesTask implements Runnable {
+ private final RollbackVfModuleRequest req;
+ private RollbackVfModuleResponse response = null;
+ private VfModuleExceptionResponse eresp = null;
+ private boolean sendxml;
+
+ public RollbackVfModulesTask(RollbackVfModuleRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<RollbackVfModuleResponse>(response) {}
+ : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ try {
+ VfModuleRollback vmr = req.getVfModuleRollback();
+ VnfRollback vrb = new VnfRollback(vmr.getVfModuleStackId(), vmr.getTenantId(), vmr.getCloudOwner(),
+ vmr.getCloudSiteId(), true, true, vmr.getMsoRequest(), null, null, null, null);
+ vnfAdapter.rollbackVnf(vrb);
+ response = new RollbackVfModuleResponse(Boolean.TRUE, req.getMessageId());
+ } catch (VnfException e) {
+ logger.error("{} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR, ErrorCode.BusinessProcesssError,
+ "Exception" + " - " + "rollbackVfModule", e);
+ eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, false,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("RollbackVfModulesTask exit: code=" + getStatusCode() + RESP + getResponse());
+ }
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestUtils.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestUtils.java
index 8c96acc361..b53ac0f899 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestUtils.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestUtils.java
@@ -23,7 +23,6 @@
package org.onap.so.adapters.vnf;
import java.util.Optional;
-
import org.onap.so.cloud.CloudConfig;
import org.onap.so.db.catalog.beans.CloudSite;
import org.slf4j.Logger;
@@ -32,80 +31,74 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
-public class VnfAdapterRestUtils
-{
- private static Logger logger = LoggerFactory.getLogger(VnfAdapterRestUtils.class);
-
- private static final String HEAT_MODE = "HEAT";
- private static final String CLOUDIFY_MODE = "CLOUDIFY";
- private static final String MULTICLOUD_MODE = "MULTICLOUD";
-
- @Autowired
- private CloudConfig cloudConfig;
-
- @Autowired
- private MsoVnfCloudifyAdapterImpl cloudifyImpl;
-
- @Autowired
- private MsoVnfAdapterImpl vnfImpl;
-
- @Autowired
- private MsoVnfPluginAdapterImpl vnfPluginImpl;
-
- /*
- * Choose which implementation of VNF Adapter to use, based on the orchestration mode.
- * Currently, the two supported orchestrators are HEAT and CLOUDIFY.
- */
- public MsoVnfAdapter getVnfAdapterImpl (String mode, String cloudSiteId)
- {
- // First, determine the orchestration mode to use.
- // If was explicitly provided as a parameter, use that. Else if specified for the
- // cloudsite, use that. Otherwise, the default is the (original) HEAT-based impl.
-
- logger.debug("Entered GetVnfAdapterImpl: mode=" + mode + ", cloudSite=" + cloudSiteId);
-
- if (mode == null) {
- // Didn't get an explicit mode type requested.
- // Use the CloudSite to determine which Impl to use, based on whether the target cloutSite
- // has a CloudifyManager assigned to it
- Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
- if (cloudSite.isPresent()) {
- logger.debug("Got CloudSite: " + cloudSite.toString());
- if (cloudConfig.getCloudifyManager(cloudSite.get().getCloudifyId()) != null) {
- mode = CLOUDIFY_MODE;
- } else if (MULTICLOUD_MODE.equalsIgnoreCase(cloudSite.get().getOrchestrator())) {
- mode = MULTICLOUD_MODE;
- }
- else {
- mode = HEAT_MODE;
- }
- }
- }
-
- logger.debug ("GetVnfAdapterImpl: mode=" + mode);
-
- MsoVnfAdapter vnfAdapter = null;
-
- // TODO: Make this more dynamic (e.g. Service Loader)
- if (CLOUDIFY_MODE.equalsIgnoreCase(mode)) {
- logger.debug("GetVnfAdapterImpl: Return Cloudify Adapter");
- vnfAdapter = cloudifyImpl;
- }
- else if (HEAT_MODE.equalsIgnoreCase(mode)) {
- logger.debug("GetVnfAdapterImpl: Return Heat Adapter");
- vnfAdapter = vnfImpl;
- }
- else if (MULTICLOUD_MODE.equalsIgnoreCase(mode)) {
- logger.debug("GetVnfAdapterImpl: Return Plugin (multicloud) Adapter");
- vnfAdapter = vnfPluginImpl;
- }
- else {
- // Don't expect this, but default is the HEAT adapter
- logger.debug("GetVnfAdapterImpl: Return Default (Heat) Adapter");
- vnfAdapter = vnfImpl;
- }
-
- return vnfAdapter;
- }
+public class VnfAdapterRestUtils {
+ private static Logger logger = LoggerFactory.getLogger(VnfAdapterRestUtils.class);
+
+ private static final String HEAT_MODE = "HEAT";
+ private static final String CLOUDIFY_MODE = "CLOUDIFY";
+ private static final String MULTICLOUD_MODE = "MULTICLOUD";
+
+ @Autowired
+ private CloudConfig cloudConfig;
+
+ @Autowired
+ private MsoVnfCloudifyAdapterImpl cloudifyImpl;
+
+ @Autowired
+ private MsoVnfAdapterImpl vnfImpl;
+
+ @Autowired
+ private MsoVnfPluginAdapterImpl vnfPluginImpl;
+
+ /*
+ * Choose which implementation of VNF Adapter to use, based on the orchestration mode. Currently, the two supported
+ * orchestrators are HEAT and CLOUDIFY.
+ */
+ public MsoVnfAdapter getVnfAdapterImpl(String mode, String cloudSiteId) {
+ // First, determine the orchestration mode to use.
+ // If was explicitly provided as a parameter, use that. Else if specified for the
+ // cloudsite, use that. Otherwise, the default is the (original) HEAT-based impl.
+
+ logger.debug("Entered GetVnfAdapterImpl: mode=" + mode + ", cloudSite=" + cloudSiteId);
+
+ if (mode == null) {
+ // Didn't get an explicit mode type requested.
+ // Use the CloudSite to determine which Impl to use, based on whether the target cloutSite
+ // has a CloudifyManager assigned to it
+ Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId);
+ if (cloudSite.isPresent()) {
+ logger.debug("Got CloudSite: " + cloudSite.toString());
+ if (cloudConfig.getCloudifyManager(cloudSite.get().getCloudifyId()) != null) {
+ mode = CLOUDIFY_MODE;
+ } else if (MULTICLOUD_MODE.equalsIgnoreCase(cloudSite.get().getOrchestrator())) {
+ mode = MULTICLOUD_MODE;
+ } else {
+ mode = HEAT_MODE;
+ }
+ }
+ }
+
+ logger.debug("GetVnfAdapterImpl: mode=" + mode);
+
+ MsoVnfAdapter vnfAdapter = null;
+
+ // TODO: Make this more dynamic (e.g. Service Loader)
+ if (CLOUDIFY_MODE.equalsIgnoreCase(mode)) {
+ logger.debug("GetVnfAdapterImpl: Return Cloudify Adapter");
+ vnfAdapter = cloudifyImpl;
+ } else if (HEAT_MODE.equalsIgnoreCase(mode)) {
+ logger.debug("GetVnfAdapterImpl: Return Heat Adapter");
+ vnfAdapter = vnfImpl;
+ } else if (MULTICLOUD_MODE.equalsIgnoreCase(mode)) {
+ logger.debug("GetVnfAdapterImpl: Return Plugin (multicloud) Adapter");
+ vnfAdapter = vnfPluginImpl;
+ } else {
+ // Don't expect this, but default is the HEAT adapter
+ logger.debug("GetVnfAdapterImpl: Return Default (Heat) Adapter");
+ vnfAdapter = vnfImpl;
+ }
+
+ return vnfAdapter;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java
index 41d350d765..440b0dae0a 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java
@@ -25,7 +25,6 @@ package org.onap.so.adapters.vnf;
import java.util.Map;
-
import javax.inject.Provider;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@@ -40,7 +39,6 @@ import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.ws.Holder;
-
import org.apache.http.HttpStatus;
import org.onap.so.adapters.vnf.exceptions.VnfException;
import org.onap.so.adapters.vnfrest.CreateVfModuleRequest;
@@ -64,7 +62,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@@ -72,651 +69,535 @@ import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
- * This class services calls to the REST interface for VF Modules (http://host:port/vnfs/rest/v2/vnfs)
- * Both XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default.
- * For testing, call with cloudSiteId = ___TESTING___
- * To test exceptions, also set tenantId = ___TESTING___
+ * This class services calls to the REST interface for VF Modules (http://host:port/vnfs/rest/v2/vnfs) Both XML and JSON
+ * can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. For testing, call
+ * with cloudSiteId = ___TESTING___ To test exceptions, also set tenantId = ___TESTING___
*
- * V2 incorporates run-time selection of sub-orchestrator implementation (Heat or Cloudify)
- * based on the target cloud.
+ * V2 incorporates run-time selection of sub-orchestrator implementation (Heat or Cloudify) based on the target cloud.
*/
@Path("/v2/vnfs")
@Api(value = "/v2/vnfs", description = "root of vnf adapters restful web service v2")
@Component
public class VnfAdapterRestV2 {
- private static Logger logger = LoggerFactory.getLogger(VnfAdapterRestV2.class);
- private static final String TESTING_KEYWORD = "___TESTING___";
- private static final String RESP=", resp=";
-
- @Autowired
- private VnfAdapterRestUtils vnfAdapterRestUtils;
-
- @Autowired
- private Provider<BpelRestClient> bpelRestClientProvider;
-
- /*
- * URL:http://localhost:8080/vnfs/rest/v2/vnfs/<aaivnfid>/vf-modules/<aaimodid>
- * REQUEST:
- * {"deleteVfModuleRequest":
- {"cloudSiteId": "DAN",
- "tenantId": "214b428a1f554c02935e66330f6a5409",
- "vnfId": "somevnfid",
- "vfModuleId": "somemodid",
- "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73",
- "messageId": "ra.1",
- "notificationUrl": "http://localhost:8089/vnfmock",
- "skipAAI": true,
- "msoRequest": {
- "requestId": "ra1",
- "serviceInstanceId": "sa1"
- }}
- }
- */
- @DELETE
- @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "DeleteVfModule",
- response = Response.class,
- notes = "Delete an existing vnfModule, DeleteVfModuleRequest JSON is required")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfModule has been successfully deleted"),
- @ApiResponse(code = 202, message = "delete vnfModule request has been accepted (async only)"),
- @ApiResponse(code = 500, message = "delete vnfModule failed, examine entity object for details") })
- public Response deleteVfModule (
- @ApiParam(value = "aaiVnfId", required = true)
- @PathParam("aaiVnfId") String aaiVnfId,
- @ApiParam(value = "aaiVfModuleId", required = true)
- @PathParam("aaiVfModuleId") String aaiVfModuleId,
- @ApiParam(value = "mode", required = true)
- @QueryParam("mode") String mode,
- @ApiParam(value = "DeleteVfModuleRequest", required = true)
- final DeleteVfModuleRequest req)
- {
- logger.debug("Delete VfModule enter: " + req.toJsonString());
- if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) {
- logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL");
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity("vnfid in URL does not match content")
- .build();
- }
- if (aaiVfModuleId == null || !aaiVfModuleId.equals(req.getVfModuleId())) {
- logger.debug("Req rejected - aaiVfModuleId not provided or doesn't match URL");
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity("vfModuleId in URL does not match content")
- .build();
- }
-
- DeleteVfModuleTask task = new DeleteVfModuleTask(req, mode);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling delete, send generic failure as sync resp to caller
- logger.error("{} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), "deleteVfModule",
- ErrorCode.BusinessProcesssError.getValue(), "Exception in deleteVfModule", e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("deleteVNFVolumes exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class DeleteVfModuleTask implements Runnable {
- private final DeleteVfModuleRequest req;
- private DeleteVfModuleResponse response = null;
- private VfModuleExceptionResponse eresp = null;
- private boolean sendxml;
- private String mode;
-
- public DeleteVfModuleTask(DeleteVfModuleRequest req, String mode) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- this.mode = mode;
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<DeleteVfModuleResponse>(response) {}
- : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
-
- @Override
- public void run() {
- try {
- String cloudsite = req.getCloudSiteId();
- Holder<Map<String, String>> outputs = new Holder <Map <String, String>> ();
- if (cloudsite != null && !cloudsite.equals(TESTING_KEYWORD)) {
- //vnfAdapter.deleteVnf (req.getCloudSiteId(), req.getTenantId(), req.getVfModuleStackId(), req.getMsoRequest());
- // Support different Adapter Implementations
- MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsite);
- adapter.deleteVfModule (req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), req.getVfModuleStackId(), req.getMsoRequest(), outputs);
- }
- response = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), Boolean.TRUE, req.getMessageId(), outputs.value);
- } catch (VnfException e) {
- logger.error("{} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(),
- ErrorCode.BusinessProcesssError.getValue(), "VnfException - " + "Delete VNF Module", e);
- eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("Delete vfModule exit: code=" + getStatusCode() + RESP + getResponse());
- }
- }
-
- /*
- * URL:http://localhost:8080/vnfs/rest/v2/vnfs/<aaiVnfId>/vf-modules/<aaiVfModuleId>?cloudSiteId=DAN&tenantId=vfModule?&skipAAI=TRUE&msoRequest.requestId=ra1&msoRequest.serviceInstanceId=si1&vfModuleName=T2N2S1
- * RESP:
- * {"queryVfModuleResponse": {
- "vfModuleId": "AvfmodId",
- "vfModuleOutputs": {"entry": {
- "key": "server_private_ip_1",
- "value": "10.100.1.25"
- }},
- "vfModuleStackId": "RaaVnf1/abfa8a6d-feb1-40af-aea3-109403b1cf6b",
- "vnfId": "AvnfID",
- "vnfStatus": "ACTIVE"
- }}
- */
- @GET
- @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "QueryVfModule",
- response = Response.class,
- notes = "Query an existing vnfModule")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfModule has been successfully queried"),
- @ApiResponse(code = 500, message = "query vnfModule failed, examine entity object for details") })
- public Response queryVfModule(
- @ApiParam(value = "aaiVnfId", required = true)
- @PathParam("aaiVnfId") String aaiVnfId,
- @ApiParam(value = "aaiVfModuleId", required = true)
- @PathParam("aaiVfModuleId") String aaiVfModuleId,
- @ApiParam(value = "cloudSiteId", required = true)
- @QueryParam("cloudSiteId") String cloudSiteId,
- @ApiParam(value = "cloudOwner", required = true)
- @QueryParam("cloudOwner") String cloudOwner,
- @ApiParam(value = "tenantId", required = true)
- @QueryParam("tenantId") String tenantId,
- @ApiParam(value = "vfModuleName", required = true)
- @QueryParam("vfModuleName") String vfModuleName, //RAA? Id in doc
- @ApiParam(value = "skipAAI", required = true)
- @QueryParam("skipAAI") Boolean skipAAI,
- @ApiParam(value = "msoRequest.requestId", required = true)
- @QueryParam("msoRequest.requestId") String requestId,
- @ApiParam(value = "msoRequest.serviceInstanceId", required = true)
- @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId,
- @ApiParam(value = "mode", required = true)
- @QueryParam("mode") String mode)
- {
- //This request responds synchronously only
- logger.debug("Query vfModule enter:" + vfModuleName);
- MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId);
-
- try {
- int respStatus = HttpStatus.SC_OK;
- QueryVfModuleResponse qryResp = new QueryVfModuleResponse(aaiVnfId, aaiVfModuleId, null, null, null);
- Holder<Boolean> vnfExists = new Holder<Boolean>();
- Holder<String> vfModuleId = new Holder<String>();
- Holder<VnfStatus> status = new Holder<VnfStatus>();
- Holder<Map<String, String>> outputs = new Holder <Map <String, String>> ();
-
- // Support different Adapter Implementations
- MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudSiteId);
- adapter.queryVnf (cloudSiteId, cloudOwner, tenantId, vfModuleName, msoRequest, vnfExists, vfModuleId, status, outputs);
-
- if (!vnfExists.value) {
- logger.debug("vfModule not found");
- respStatus = HttpStatus.SC_NOT_FOUND;
- } else {
- logger.debug("vfModule found" + vfModuleId.value + ", status=" + status.value);
- qryResp.setVfModuleId(vfModuleId.value);
- qryResp.setVnfStatus(status.value);
- qryResp.setVfModuleOutputs(outputs.value);
- }
- logger.debug ("Query vfModule exit");
- return Response
- .status(respStatus)
- .entity(new GenericEntity<QueryVfModuleResponse>(qryResp) {})
- .build();
- } catch (VnfException e) {
- logger.error("{} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule",
- ErrorCode.BusinessProcesssError.getValue(), "VnfException - queryVfModule", e);
- VfModuleExceptionResponse excResp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null);
- return Response
- .status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity(new GenericEntity<VfModuleExceptionResponse>(excResp) {})
- .build();
- }
- }
-
- /*URL: http://localhost:8080/vnfs/rest/v2/vnfs/<aaivnfid>/vf-modules
- *REQUEST:
- * {"createVfModuleRequest":
- {"cloudSiteId": "DAN",
- "tenantId": "214b428a1f554c02935e66330f6a5409",
- "vnfId": "somevnfid",
- "vfModuleId": "somemodid",
- "vfModuleName": "RaaVnf1",
- "vnfType": "ApacheVnf",
- "vfModuleParams": {"entry": [
- {"key": "network_id",
- "value": "59ed7b41-2983-413f-ba93-e7d437433916"},
- {"key": "subnet_id",
- "value": "086c9298-5c57-49b7-bb2b-6fd5730c5d92"},
- {"key": "server_name_0",
- "value": "RaaVnf1"}
- ]},
- "failIfExists": true,
- "messageId": "ra.1",
- "notificationUrl": "http://localhost:8089/vnfmock",
- "skipAAI": true,
- "msoRequest": {
- "requestId": "ra1",
- "serviceInstanceId": "sa1"
- }}
- }
- */
- @POST
- @Path("{aaiVnfId}/vf-modules")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "CreateVfModule",
- response = Response.class,
- notes = "Create a vnfModule")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfModule has been successfully created"),
- @ApiResponse(code = 202, message = "create vnfModule request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "create vnfModule failed, examine entity object for details") })
- public Response createVfModule(
- @ApiParam(value = "aaiVnfId", required = true)
- @PathParam("aaiVnfId") String aaiVnfId,
- @ApiParam(value = "mode", required = true)
- @QueryParam("mode") String mode,
- @ApiParam(value = "CreateVfModuleRequest", required = true)
- final CreateVfModuleRequest req)
- {
- logger.debug("Create VfModule enter inside VnfAdapterRest: " + req.toJsonString());
- if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) {
- logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL");
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity("vnfid in URL does not match content")
- .build();
- }
-
- CreateVfModuleTask task = new CreateVfModuleTask(req, mode);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), "createVfModule",
- ErrorCode.BusinessProcesssError.getValue(), "Exception - createVfModule", e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("createVfModule exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class CreateVfModuleTask implements Runnable {
- private final CreateVfModuleRequest req;
- private CreateVfModuleResponse response = null;
- private VfModuleExceptionResponse eresp = null;
- private boolean sendxml;
- private String mode;
-
- public CreateVfModuleTask(CreateVfModuleRequest req, String mode) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- this.mode = mode;
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<CreateVfModuleResponse>(response) {}
- : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
-
- @Override
- public void run() {
- logger.debug("CreateVfModuleTask start");
- try {
- // Synchronous Web Service Outputs
- Holder <String> vfModuleStackId = new Holder <String> ();
- Holder <Map <String, String>> outputs = new Holder <Map <String, String>> ();
- Holder <VnfRollback> vnfRollback = new Holder <VnfRollback> ();
- String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
- logger.debug("completeVnfVfModuleType=" + completeVnfVfModuleType);
-
- String cloudsiteId = req.getCloudSiteId();
- String cloudOwner = req.getCloudOwner();
- if (cloudsiteId != null && cloudsiteId.equals(TESTING_KEYWORD)) {
- String tenant = req.getTenantId();
- if (tenant != null && tenant.equals(TESTING_KEYWORD)) {
- throw new VnfException("testing.");
- }
- vnfRollback.value = new VnfRollback(req.getVnfId(), tenant, cloudOwner, cloudsiteId,
- true, false, new MsoRequest("reqid", "svcid"),
- req.getVolumeGroupId(), req.getVolumeGroupId(), req.getRequestType(), req.getModelCustomizationUuid());
- vfModuleStackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484";
- outputs.value = VolumeAdapterRest.testMap();
- } else {
- // Support different Adapter Implementations
- MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId);
- adapter.createVfModule(req.getCloudSiteId(),
- req.getCloudOwner(),
- req.getTenantId(),
- completeVnfVfModuleType,
- req.getVnfVersion(),
- req.getVnfId(),
- req.getVfModuleName(),
- req.getVfModuleId(),
- req.getRequestType(),
- req.getVolumeGroupStackId(),
- req.getBaseVfModuleStackId(),
- req.getModelCustomizationUuid(),
- req.getVfModuleParams(),
- req.getFailIfExists(),
- req.getBackout(),
- req.getEnableBridge(),
- req.getMsoRequest(),
- vfModuleStackId,
- outputs,
- vnfRollback);
- }
- VfModuleRollback modRollback = new VfModuleRollback(vnfRollback.value, req.getVfModuleId(), vfModuleStackId.value, req.getMessageId());
- response = new CreateVfModuleResponse(req.getVnfId(), req.getVfModuleId(),
- vfModuleStackId.value, Boolean.TRUE, outputs.value, modRollback, req.getMessageId());
- } catch (VnfException e) {
- eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("CreateVfModuleTask exit: code=" + getStatusCode() + RESP + getResponse());
- }
- }
-
- @PUT
- @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "UpdateVfModule",
- response = Response.class,
- notes = "Update an existing vnfModule")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfModule has been successfully updated"),
- @ApiResponse(code = 202, message = "update vnfModule request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "update vnfModule failed, examine entity object for details") })
- public Response updateVfModule(
- @ApiParam(value = "aaiVnfId", required = true)
- @PathParam("aaiVnfId") String aaiVnfId,
- @ApiParam(value = "aaiVfModuleId", required = true)
- @PathParam("aaiVfModuleId") String aaiVfModuleId,
- @ApiParam(value = "mode", required = true)
- @QueryParam("mode") String mode,
- @ApiParam(value = "UpdateVfModuleRequest", required = true)
- final UpdateVfModuleRequest req)
- {
- logger.debug("Update VfModule enter: " + req.toJsonString());
- UpdateVfModulesTask task = new UpdateVfModulesTask(req, mode);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), "updateVfModule",
- ErrorCode.BusinessProcesssError.getValue(), "Exception - updateVfModule", e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("updateVfModules exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class UpdateVfModulesTask implements Runnable {
- private final UpdateVfModuleRequest req;
- private UpdateVfModuleResponse response = null;
- private VfModuleExceptionResponse eresp = null;
- private boolean sendxml;
- private String mode;
-
- public UpdateVfModulesTask(UpdateVfModuleRequest req, String mode) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- this.mode = mode;
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<UpdateVfModuleResponse>(response) {}
- : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- try {
- //MsoVnfAdapter vnfAdapter = new MsoVnfAdapterImpl (msoPropertiesFactory, cloudConfigFactory);
-
- // Synchronous Web Service Outputs
- Holder <String> vfModuleStackId = new Holder <String> ();
- Holder <Map <String, String>> outputs = new Holder <Map <String, String>> ();
- Holder <VnfRollback> vnfRollback = new Holder <VnfRollback> ();
- String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
- logger.debug("in updateVf - completeVnfVfModuleType=" + completeVnfVfModuleType);
-
- String cloudsiteId = req.getCloudSiteId();
-
- // Support different Adapter Implementations
- MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId);
- adapter.updateVfModule (req.getCloudSiteId(),
- req.getCloudOwner(),
- req.getTenantId(),
- completeVnfVfModuleType,
- req.getVnfVersion(),
- req.getVfModuleName(),
- req.getRequestType(),
- req.getVolumeGroupStackId(),
- req.getBaseVfModuleId(),
- req.getVfModuleStackId(),
- req.getModelCustomizationUuid(),
- req.getVfModuleParams(),
- req.getMsoRequest(),
- outputs,
- vnfRollback);
-
- response = new UpdateVfModuleResponse(req.getVnfId(), req.getVfModuleId(),
- vfModuleStackId.value, outputs.value, req.getMessageId());
- } catch (VnfException e) {
- eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost (getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("Update VfModule exit: code=" + getStatusCode() + RESP + getResponse());
- }
- }
- /*
- * URL:http://localhost:8080/vnfs/rest/v2/vnfs/<aaivnfid>/vf-modules/<aaimodid>/rollback
- * REQUEST:
- * {"deleteVfModuleRequest":
- {"cloudSiteId": "DAN",
- "tenantId": "214b428a1f554c02935e66330f6a5409",
- "vnfId": "somevnfid",
- "vfModuleId": "somemodid",
- "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73",
- "messageId": "ra.1",
- "notificationUrl": "http://localhost:8089/vnfmock",
- "skipAAI": true,
- "msoRequest": {
- "requestId": "ra1",
- "serviceInstanceId": "sa1"
- }}
- }
- */
- @DELETE
- @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}/rollback")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "RollbackVfModule",
- response = Response.class,
- notes = "Rollback an existing vnfModule")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfModule has been successfully rolled back"),
- @ApiResponse(code = 202, message = "rollback vnfModule request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "rollback vnfModule failed, examine entity object for details") })
- public Response rollbackVfModule (
- @ApiParam(value = "aaiVnfId", required = true)
- @PathParam("aaiVnfId") String aaiVnfId,
- @ApiParam(value = "aaiVfModuleId", required = true)
- @PathParam("aaiVfModuleId") String aaiVfModuleId,
- @ApiParam(value = "RollbackVfModuleRequest", required = true)
- //@QueryParam("rollback") String rollback,
- final RollbackVfModuleRequest req)
- {
- logger.debug("Rollback VfModule enter: " + req.toJsonString());
- RollbackVfModulesTask task = new RollbackVfModulesTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), "rollbackVfModule",
- ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("rollbackVfModule exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class RollbackVfModulesTask implements Runnable {
- private final RollbackVfModuleRequest req;
- private RollbackVfModuleResponse response = null;
- private VfModuleExceptionResponse eresp = null;
- private boolean sendxml;
-
- public RollbackVfModulesTask(RollbackVfModuleRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<RollbackVfModuleResponse>(response) {}
- : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- try {
- VfModuleRollback vmr = req.getVfModuleRollback();
- VnfRollback vrb = new VnfRollback(
- vmr.getVfModuleStackId(), vmr.getTenantId(), vmr.getCloudOwner(), vmr.getCloudSiteId(), true, vmr.isVfModuleCreated(),
- vmr.getMsoRequest(), null, null, null, null);
-
- // Support multiple adapter implementations
- MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl (vmr.getMode(), vmr.getCloudSiteId());
- adapter.rollbackVnf (vrb);
-
- response = new RollbackVfModuleResponse(Boolean.TRUE, req.getMessageId());
- } catch (VnfException e) {
- logger.error("{} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(),
- ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e);
- eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, false, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost (getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("RollbackVfModulesTask exit: code=" + getStatusCode() + RESP + getResponse());
- }
- }
+ private static Logger logger = LoggerFactory.getLogger(VnfAdapterRestV2.class);
+ private static final String TESTING_KEYWORD = "___TESTING___";
+ private static final String RESP = ", resp=";
+
+ @Autowired
+ private VnfAdapterRestUtils vnfAdapterRestUtils;
+
+ @Autowired
+ private Provider<BpelRestClient> bpelRestClientProvider;
+
+ /*
+ * URL:http://localhost:8080/vnfs/rest/v2/vnfs/<aaivnfid>/vf-modules/<aaimodid> REQUEST: {"deleteVfModuleRequest":
+ * {"cloudSiteId": "DAN", "tenantId": "214b428a1f554c02935e66330f6a5409", "vnfId": "somevnfid", "vfModuleId":
+ * "somemodid", "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73", "messageId": "ra.1", "notificationUrl":
+ * "http://localhost:8089/vnfmock", "skipAAI": true, "msoRequest": { "requestId": "ra1", "serviceInstanceId": "sa1"
+ * }} }
+ */
+ @DELETE
+ @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "DeleteVfModule", response = Response.class,
+ notes = "Delete an existing vnfModule, DeleteVfModuleRequest JSON is required")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully deleted"),
+ @ApiResponse(code = 202, message = "delete vnfModule request has been accepted (async only)"),
+ @ApiResponse(code = 500, message = "delete vnfModule failed, examine entity object for details")})
+ public Response deleteVfModule(
+ @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId,
+ @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId,
+ @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode,
+ @ApiParam(value = "DeleteVfModuleRequest", required = true) final DeleteVfModuleRequest req) {
+ logger.debug("Delete VfModule enter: " + req.toJsonString());
+ if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) {
+ logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL");
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN)
+ .entity("vnfid in URL does not match content").build();
+ }
+ if (aaiVfModuleId == null || !aaiVfModuleId.equals(req.getVfModuleId())) {
+ logger.debug("Req rejected - aaiVfModuleId not provided or doesn't match URL");
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN)
+ .entity("vfModuleId in URL does not match content").build();
+ }
+
+ DeleteVfModuleTask task = new DeleteVfModuleTask(req, mode);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling delete, send generic failure as sync resp to caller
+ logger.error("{} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), "deleteVfModule",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception in deleteVfModule", e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("deleteVNFVolumes exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class DeleteVfModuleTask implements Runnable {
+ private final DeleteVfModuleRequest req;
+ private DeleteVfModuleResponse response = null;
+ private VfModuleExceptionResponse eresp = null;
+ private boolean sendxml;
+ private String mode;
+
+ public DeleteVfModuleTask(DeleteVfModuleRequest req, String mode) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ this.mode = mode;
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<DeleteVfModuleResponse>(response) {}
+ : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ try {
+ String cloudsite = req.getCloudSiteId();
+ Holder<Map<String, String>> outputs = new Holder<Map<String, String>>();
+ if (cloudsite != null && !cloudsite.equals(TESTING_KEYWORD)) {
+ // vnfAdapter.deleteVnf (req.getCloudSiteId(), req.getTenantId(), req.getVfModuleStackId(),
+ // req.getMsoRequest());
+ // Support different Adapter Implementations
+ MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsite);
+ adapter.deleteVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(),
+ req.getVfModuleStackId(), req.getMsoRequest(), outputs);
+ }
+ response = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), Boolean.TRUE,
+ req.getMessageId(), outputs.value);
+ } catch (VnfException e) {
+ logger.error("{} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(),
+ ErrorCode.BusinessProcesssError.getValue(), "VnfException - " + "Delete VNF Module", e);
+ eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("Delete vfModule exit: code=" + getStatusCode() + RESP + getResponse());
+ }
+ }
+
+ /*
+ * URL:http://localhost:8080/vnfs/rest/v2/vnfs/<aaiVnfId>/vf-modules/<aaiVfModuleId>?cloudSiteId=DAN&tenantId=
+ * vfModule?&skipAAI=TRUE&msoRequest.requestId=ra1&msoRequest.serviceInstanceId=si1&vfModuleName=T2N2S1 RESP:
+ * {"queryVfModuleResponse": { "vfModuleId": "AvfmodId", "vfModuleOutputs": {"entry": { "key":
+ * "server_private_ip_1", "value": "10.100.1.25" }}, "vfModuleStackId":
+ * "RaaVnf1/abfa8a6d-feb1-40af-aea3-109403b1cf6b", "vnfId": "AvnfID", "vnfStatus": "ACTIVE" }}
+ */
+ @GET
+ @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}")
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "QueryVfModule", response = Response.class, notes = "Query an existing vnfModule")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully queried"),
+ @ApiResponse(code = 500, message = "query vnfModule failed, examine entity object for details")})
+ public Response queryVfModule(@ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId,
+ @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId,
+ @ApiParam(value = "cloudSiteId", required = true) @QueryParam("cloudSiteId") String cloudSiteId,
+ @ApiParam(value = "cloudOwner", required = true) @QueryParam("cloudOwner") String cloudOwner,
+ @ApiParam(value = "tenantId", required = true) @QueryParam("tenantId") String tenantId,
+ @ApiParam(value = "vfModuleName", required = true) @QueryParam("vfModuleName") String vfModuleName, // RAA?
+ // Id in
+ // doc
+ @ApiParam(value = "skipAAI", required = true) @QueryParam("skipAAI") Boolean skipAAI,
+ @ApiParam(value = "msoRequest.requestId",
+ required = true) @QueryParam("msoRequest.requestId") String requestId,
+ @ApiParam(value = "msoRequest.serviceInstanceId",
+ required = true) @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId,
+ @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode) {
+ // This request responds synchronously only
+ logger.debug("Query vfModule enter:" + vfModuleName);
+ MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId);
+
+ try {
+ int respStatus = HttpStatus.SC_OK;
+ QueryVfModuleResponse qryResp = new QueryVfModuleResponse(aaiVnfId, aaiVfModuleId, null, null, null);
+ Holder<Boolean> vnfExists = new Holder<Boolean>();
+ Holder<String> vfModuleId = new Holder<String>();
+ Holder<VnfStatus> status = new Holder<VnfStatus>();
+ Holder<Map<String, String>> outputs = new Holder<Map<String, String>>();
+
+ // Support different Adapter Implementations
+ MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudSiteId);
+ adapter.queryVnf(cloudSiteId, cloudOwner, tenantId, vfModuleName, msoRequest, vnfExists, vfModuleId, status,
+ outputs);
+
+ if (!vnfExists.value) {
+ logger.debug("vfModule not found");
+ respStatus = HttpStatus.SC_NOT_FOUND;
+ } else {
+ logger.debug("vfModule found" + vfModuleId.value + ", status=" + status.value);
+ qryResp.setVfModuleId(vfModuleId.value);
+ qryResp.setVnfStatus(status.value);
+ qryResp.setVfModuleOutputs(outputs.value);
+ }
+ logger.debug("Query vfModule exit");
+ return Response.status(respStatus).entity(new GenericEntity<QueryVfModuleResponse>(qryResp) {}).build();
+ } catch (VnfException e) {
+ logger.error("{} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule",
+ ErrorCode.BusinessProcesssError.getValue(), "VnfException - queryVfModule", e);
+ VfModuleExceptionResponse excResp =
+ new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null);
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
+ .entity(new GenericEntity<VfModuleExceptionResponse>(excResp) {}).build();
+ }
+ }
+
+ /*
+ * URL: http://localhost:8080/vnfs/rest/v2/vnfs/<aaivnfid>/vf-modules REQUEST: {"createVfModuleRequest":
+ * {"cloudSiteId": "DAN", "tenantId": "214b428a1f554c02935e66330f6a5409", "vnfId": "somevnfid", "vfModuleId":
+ * "somemodid", "vfModuleName": "RaaVnf1", "vnfType": "ApacheVnf", "vfModuleParams": {"entry": [ {"key":
+ * "network_id", "value": "59ed7b41-2983-413f-ba93-e7d437433916"}, {"key": "subnet_id", "value":
+ * "086c9298-5c57-49b7-bb2b-6fd5730c5d92"}, {"key": "server_name_0", "value": "RaaVnf1"} ]}, "failIfExists": true,
+ * "messageId": "ra.1", "notificationUrl": "http://localhost:8089/vnfmock", "skipAAI": true, "msoRequest": {
+ * "requestId": "ra1", "serviceInstanceId": "sa1" }} }
+ */
+ @POST
+ @Path("{aaiVnfId}/vf-modules")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "CreateVfModule", response = Response.class, notes = "Create a vnfModule")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully created"),
+ @ApiResponse(code = 202, message = "create vnfModule request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "create vnfModule failed, examine entity object for details")})
+ public Response createVfModule(
+ @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId,
+ @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode,
+ @ApiParam(value = "CreateVfModuleRequest", required = true) final CreateVfModuleRequest req) {
+ logger.debug("Create VfModule enter inside VnfAdapterRest: " + req.toJsonString());
+ if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) {
+ logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL");
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN)
+ .entity("vnfid in URL does not match content").build();
+ }
+
+ CreateVfModuleTask task = new CreateVfModuleTask(req, mode);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), "createVfModule",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception - createVfModule", e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("createVfModule exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class CreateVfModuleTask implements Runnable {
+ private final CreateVfModuleRequest req;
+ private CreateVfModuleResponse response = null;
+ private VfModuleExceptionResponse eresp = null;
+ private boolean sendxml;
+ private String mode;
+
+ public CreateVfModuleTask(CreateVfModuleRequest req, String mode) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ this.mode = mode;
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<CreateVfModuleResponse>(response) {}
+ : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("CreateVfModuleTask start");
+ try {
+ // Synchronous Web Service Outputs
+ Holder<String> vfModuleStackId = new Holder<String>();
+ Holder<Map<String, String>> outputs = new Holder<Map<String, String>>();
+ Holder<VnfRollback> vnfRollback = new Holder<VnfRollback>();
+ String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
+ logger.debug("completeVnfVfModuleType=" + completeVnfVfModuleType);
+
+ String cloudsiteId = req.getCloudSiteId();
+ String cloudOwner = req.getCloudOwner();
+ if (cloudsiteId != null && cloudsiteId.equals(TESTING_KEYWORD)) {
+ String tenant = req.getTenantId();
+ if (tenant != null && tenant.equals(TESTING_KEYWORD)) {
+ throw new VnfException("testing.");
+ }
+ vnfRollback.value = new VnfRollback(req.getVnfId(), tenant, cloudOwner, cloudsiteId, true, false,
+ new MsoRequest("reqid", "svcid"), req.getVolumeGroupId(), req.getVolumeGroupId(),
+ req.getRequestType(), req.getModelCustomizationUuid());
+ vfModuleStackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484";
+ outputs.value = VolumeAdapterRest.testMap();
+ } else {
+ // Support different Adapter Implementations
+ MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId);
+ adapter.createVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(),
+ completeVnfVfModuleType, req.getVnfVersion(), req.getVnfId(), req.getVfModuleName(),
+ req.getVfModuleId(), req.getRequestType(), req.getVolumeGroupStackId(),
+ req.getBaseVfModuleStackId(), req.getModelCustomizationUuid(), req.getVfModuleParams(),
+ req.getFailIfExists(), req.getBackout(), req.getEnableBridge(), req.getMsoRequest(),
+ vfModuleStackId, outputs, vnfRollback);
+ }
+ VfModuleRollback modRollback = new VfModuleRollback(vnfRollback.value, req.getVfModuleId(),
+ vfModuleStackId.value, req.getMessageId());
+ response = new CreateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), vfModuleStackId.value,
+ Boolean.TRUE, outputs.value, modRollback, req.getMessageId());
+ } catch (VnfException e) {
+ eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("CreateVfModuleTask exit: code=" + getStatusCode() + RESP + getResponse());
+ }
+ }
+
+ @PUT
+ @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "UpdateVfModule", response = Response.class, notes = "Update an existing vnfModule")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully updated"),
+ @ApiResponse(code = 202, message = "update vnfModule request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "update vnfModule failed, examine entity object for details")})
+ public Response updateVfModule(
+ @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId,
+ @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId,
+ @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode,
+ @ApiParam(value = "UpdateVfModuleRequest", required = true) final UpdateVfModuleRequest req) {
+ logger.debug("Update VfModule enter: " + req.toJsonString());
+ UpdateVfModulesTask task = new UpdateVfModulesTask(req, mode);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), "updateVfModule",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception - updateVfModule", e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("updateVfModules exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class UpdateVfModulesTask implements Runnable {
+ private final UpdateVfModuleRequest req;
+ private UpdateVfModuleResponse response = null;
+ private VfModuleExceptionResponse eresp = null;
+ private boolean sendxml;
+ private String mode;
+
+ public UpdateVfModulesTask(UpdateVfModuleRequest req, String mode) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ this.mode = mode;
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<UpdateVfModuleResponse>(response) {}
+ : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ try {
+ // MsoVnfAdapter vnfAdapter = new MsoVnfAdapterImpl (msoPropertiesFactory, cloudConfigFactory);
+
+ // Synchronous Web Service Outputs
+ Holder<String> vfModuleStackId = new Holder<String>();
+ Holder<Map<String, String>> outputs = new Holder<Map<String, String>>();
+ Holder<VnfRollback> vnfRollback = new Holder<VnfRollback>();
+ String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
+ logger.debug("in updateVf - completeVnfVfModuleType=" + completeVnfVfModuleType);
+
+ String cloudsiteId = req.getCloudSiteId();
+
+ // Support different Adapter Implementations
+ MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId);
+ adapter.updateVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(),
+ completeVnfVfModuleType, req.getVnfVersion(), req.getVfModuleName(), req.getRequestType(),
+ req.getVolumeGroupStackId(), req.getBaseVfModuleId(), req.getVfModuleStackId(),
+ req.getModelCustomizationUuid(), req.getVfModuleParams(), req.getMsoRequest(), outputs,
+ vnfRollback);
+
+ response = new UpdateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), vfModuleStackId.value,
+ outputs.value, req.getMessageId());
+ } catch (VnfException e) {
+ eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("Update VfModule exit: code=" + getStatusCode() + RESP + getResponse());
+ }
+ }
+
+ /*
+ * URL:http://localhost:8080/vnfs/rest/v2/vnfs/<aaivnfid>/vf-modules/<aaimodid>/rollback REQUEST:
+ * {"deleteVfModuleRequest": {"cloudSiteId": "DAN", "tenantId": "214b428a1f554c02935e66330f6a5409", "vnfId":
+ * "somevnfid", "vfModuleId": "somemodid", "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73", "messageId":
+ * "ra.1", "notificationUrl": "http://localhost:8089/vnfmock", "skipAAI": true, "msoRequest": { "requestId": "ra1",
+ * "serviceInstanceId": "sa1" }} }
+ */
+ @DELETE
+ @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}/rollback")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "RollbackVfModule", response = Response.class, notes = "Rollback an existing vnfModule")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully rolled back"),
+ @ApiResponse(code = 202,
+ message = "rollback vnfModule request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "rollback vnfModule failed, examine entity object for details")})
+ public Response rollbackVfModule(
+ @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId,
+ @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId,
+ @ApiParam(value = "RollbackVfModuleRequest", required = true)
+ // @QueryParam("rollback") String rollback,
+ final RollbackVfModuleRequest req) {
+ logger.debug("Rollback VfModule enter: " + req.toJsonString());
+ RollbackVfModulesTask task = new RollbackVfModulesTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), "rollbackVfModule",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("rollbackVfModule exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class RollbackVfModulesTask implements Runnable {
+ private final RollbackVfModuleRequest req;
+ private RollbackVfModuleResponse response = null;
+ private VfModuleExceptionResponse eresp = null;
+ private boolean sendxml;
+
+ public RollbackVfModulesTask(RollbackVfModuleRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<RollbackVfModuleResponse>(response) {}
+ : new GenericEntity<VfModuleExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ try {
+ VfModuleRollback vmr = req.getVfModuleRollback();
+ VnfRollback vrb = new VnfRollback(vmr.getVfModuleStackId(), vmr.getTenantId(), vmr.getCloudOwner(),
+ vmr.getCloudSiteId(), true, vmr.isVfModuleCreated(), vmr.getMsoRequest(), null, null, null,
+ null);
+
+ // Support multiple adapter implementations
+ MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(vmr.getMode(), vmr.getCloudSiteId());
+ adapter.rollbackVnf(vrb);
+
+ response = new RollbackVfModuleResponse(Boolean.TRUE, req.getMessageId());
+ } catch (VnfException e) {
+ logger.error("{} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(),
+ ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e);
+ eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, false,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("RollbackVfModulesTask exit: code=" + getStatusCode() + RESP + getResponse());
+ }
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java
index e7d7b56624..c02a872a85 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java
@@ -71,10 +71,9 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
- * This class services calls to the REST interface for VNF Volumes (http://host:port/vnfs/rest/v1/volume-groups)
- * Both XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default.
- * For testing, call with cloudSiteId = ___TESTING___
- * To test exceptions, also set tenantId = ___TESTING___
+ * This class services calls to the REST interface for VNF Volumes (http://host:port/vnfs/rest/v1/volume-groups) Both
+ * XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. For
+ * testing, call with cloudSiteId = ___TESTING___ To test exceptions, also set tenantId = ___TESTING___
*/
@Path("/v1/volume-groups")
@Api(value = "/v1/volume-groups", description = "root of volume-groups adapters restful web service")
@@ -82,580 +81,524 @@ import org.springframework.stereotype.Component;
public class VolumeAdapterRest {
private static final Logger logger = LoggerFactory.getLogger(VolumeAdapterRest.class);
- private static final String TESTING_KEYWORD = "___TESTING___";
- private static final String EXCEPTION="Exception :";
- private static final String RESP=", resp=";
- private static final String VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT="VolumeGroupId in URL does not match content";
- @Autowired
- private MsoVnfAdapterImpl vnfAdapter;
-
- @Autowired
- private Provider<BpelRestClient> bpelRestClientProvider;
-
- @POST
- @Path("")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "CreateVNFVolumes",
- response = Response.class,
- notes = "Create a new vnfVolume")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfVolume has been successfully created"),
- @ApiResponse(code = 202, message = "create vnfVolume request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "create vnfVolume failed, examine entity object for details") })
- public Response createVNFVolumes(
- @ApiParam(value = "CreateVolumeGroupRequest", required = true)
- final CreateVolumeGroupRequest req
- ) {
- logger.debug("createVNFVolumes enter: {}", req.toJsonString());
- CreateVNFVolumesTask task = new CreateVNFVolumesTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} Exception - createVNFVolumes: ", MessageEnum.RA_CREATE_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("createVNFVolumes exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class CreateVNFVolumesTask implements Runnable {
- private final CreateVolumeGroupRequest req;
- private CreateVolumeGroupResponse response = null;
- private VolumeGroupExceptionResponse eresp = null;
- private boolean sendxml;
-
- public CreateVNFVolumesTask(CreateVolumeGroupRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<CreateVolumeGroupResponse>(response) {}
- : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- logger.debug("CreateVFModule VolumesTask start");
- try {
- // Synchronous Web Service Outputs
- Holder<String> stackId = new Holder<>();
- Holder<Map<String, String>> outputs = new Holder<>();
- Holder<VnfRollback> vnfRollback = new Holder<>();
- String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
- logger.debug("in createVfModuleVolumes - completeVnfVfModuleType={}", completeVnfVfModuleType);
-
- String cloudsite = req.getCloudSiteId();
- if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) {
- String tenant = req.getTenantId();
- if (tenant != null && tenant.equals(TESTING_KEYWORD)) {
- throw new VnfException("testing.");
- }
- stackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484";
- outputs.value = testMap();
- } else {
-// vnfAdapter.createVnf(
-// req.getCloudSiteId(),
-// req.getTenantId(),
-// req.getVnfType(),
-// req.getVnfVersion(),
-// req.getVolumeGroupName(),
-// "VOLUME", // request type is VOLUME
-// null, // not sure about this
-// req.getVolumeGroupParams(),
-// req.getFailIfExists(),
-// req.getSuppressBackout(),
-// req.getMsoRequest(),
-// stackId,
-// outputs,
-// vnfRollback);
- vnfAdapter.createVfModule(
- req.getCloudSiteId(), //cloudSiteId,
- req.getCloudOwner(), //cloudOwner,
- req.getTenantId(), //tenantId,
- //req.getVnfType(), //vnfType,
- completeVnfVfModuleType,
- req.getVnfVersion(), //vnfVersion,
- "", // genericVnfId
- req.getVolumeGroupName(), //vnfName,
- "", // vfModuleid
- "VOLUME", //requestType,
- null, //volumeGroupHeatStackId,
- null, //baseVfHeatStackId,
- req.getModelCustomizationUuid(),
- req.getVolumeGroupParams(), //inputs,
- req.getFailIfExists(), //failIfExists,
- req.getSuppressBackout(), //backout,
- req.getEnableBridge(),
- req.getMsoRequest(), // msoRequest,
- stackId,
- outputs,
- vnfRollback);
- }
- VolumeGroupRollback rb = new VolumeGroupRollback(
- req.getVolumeGroupId(),
- stackId.value,
- true, // TODO boolean volumeGroupCreated, when would it be false?
- req.getTenantId(),
- req.getCloudOwner(),
- req.getCloudSiteId(),
- req.getMsoRequest(),
- req.getMessageId());
- response = new CreateVolumeGroupResponse(
- req.getVolumeGroupId(),
- stackId.value,
- true, // TODO boolean volumeGroupCreated, when would it be false?
- outputs.value,
- rb,
- req.getMessageId());
- } catch (VnfException e) {
- logger.debug(EXCEPTION, e);
- eresp = new VolumeGroupExceptionResponse(
- e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("CreateVFModule VolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse());
- }
- }
-
- @DELETE
- @Path("{aaiVolumeGroupId}")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "DeleteVNFVolumes",
- response = Response.class,
- notes = "Delete an existing vnfVolume")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfVolume has been successfully deleted"),
- @ApiResponse(code = 202, message = "delete vnfVolume request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "delete vnfVolume failed, examine entity object for details") })
- public Response deleteVNFVolumes(
- @ApiParam(value = "aaiVolumeGroupId", required = true)
- @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
- @ApiParam(value = "DeleteVolumeGroupRequest", required = true)
- final DeleteVolumeGroupRequest req
- )
- {
- logger.debug("deleteVNFVolumes enter: {}", req.toJsonString());
- if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) {
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity(VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT)
- .build();
- }
- DeleteVNFVolumesTask task = new DeleteVNFVolumesTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} Exception - deleteVNFVolumes: ", MessageEnum.RA_DELETE_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("deleteVNFVolumes exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class DeleteVNFVolumesTask implements Runnable {
- private final DeleteVolumeGroupRequest req;
- private DeleteVolumeGroupResponse response = null;
- private VolumeGroupExceptionResponse eresp = null;
- private boolean sendxml;
-
- public DeleteVNFVolumesTask(DeleteVolumeGroupRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<DeleteVolumeGroupResponse>(response) {}
- : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- logger.debug("DeleteVNFVolumesTask start");
- try {
- if (!req.getCloudSiteId().equals(TESTING_KEYWORD)) {
- vnfAdapter.deleteVnf(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), req.getVolumeGroupStackId(), req.getMsoRequest());
- }
- response = new DeleteVolumeGroupResponse(true, req.getMessageId());
- } catch (VnfException e) {
- logger.debug(EXCEPTION, e);
- eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("DeleteVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse());
- }
- }
-
- @DELETE
- @Path("{aaiVolumeGroupId}/rollback")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "RollbackVNFVolumes",
- response = Response.class,
- notes = "Delete an existing vnfVolume")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfVolume has been successfully rolled back"),
- @ApiResponse(code = 202, message = "rollback vnfVolume request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "rollback vnfVolume failed, examine entity object for details") })
- public Response rollbackVNFVolumes(
- @ApiParam(value = "aaiVolumeGroupId", required = true)
- @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
- @ApiParam(value = "RollbackVolumeGroupRequest", required = true)
- final RollbackVolumeGroupRequest req
- )
- {
- logger.debug("rollbackVNFVolumes enter: {}", req.toJsonString());
- if (aaiVolumeGroupId == null || req.getVolumeGroupRollback() == null || !aaiVolumeGroupId.equals(req.getVolumeGroupRollback().getVolumeGroupId())) {
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity(VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT)
- .build();
- }
- RollbackVNFVolumesTask task = new RollbackVNFVolumesTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} Exception - rollbackVNFVolumes: ", MessageEnum.RA_ROLLBACK_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("rollbackVNFVolumes exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class RollbackVNFVolumesTask implements Runnable {
- private final RollbackVolumeGroupRequest req;
- private RollbackVolumeGroupResponse response = null;
- private VolumeGroupExceptionResponse eresp = null;
- private boolean sendxml;
-
- public RollbackVNFVolumesTask(RollbackVolumeGroupRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<RollbackVolumeGroupResponse>(response) {}
- : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- logger.debug("DeleteVNFVolumesTask start");
- try {
- VolumeGroupRollback vgr = req.getVolumeGroupRollback();
- VnfRollback vrb = new VnfRollback(
- vgr.getVolumeGroupStackId(), vgr.getTenantId(), vgr.getCloudOwnerId(), vgr.getCloudSiteId(), true, true,
- vgr.getMsoRequest(), null, null, null, null);
- vnfAdapter.rollbackVnf(vrb);
- response = new RollbackVolumeGroupResponse(true, req.getMessageId());
- } catch (VnfException e) {
- logger.debug(EXCEPTION, e);
- eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("DeleteVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse());
- }
-
- }
-
- @PUT
- @Path("{aaiVolumeGroupId}")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "UpdateVNFVolumes",
- response = Response.class,
- notes = "Update an existing vnfVolume")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfVolume has been successfully updated"),
- @ApiResponse(code = 202, message = "update vnfVolume request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "update vnfVolume failed, examine entity object for details") })
- public Response updateVNFVolumes(
- @ApiParam(value = "aaiVolumeGroupId", required = true)
- @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
- @ApiParam(value = "UpdateVolumeGroupRequest", required = true)
- final UpdateVolumeGroupRequest req
- )
- {
- logger.debug("updateVNFVolumes enter: {}", req.toJsonString());
- if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) {
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity(VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT)
- .build();
- }
- UpdateVNFVolumesTask task = new UpdateVNFVolumesTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} Exception - updateVNFVolumes: ", MessageEnum.RA_UPDATE_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("updateVNFVolumes exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class UpdateVNFVolumesTask implements Runnable {
- private final UpdateVolumeGroupRequest req;
- private UpdateVolumeGroupResponse response = null;
- private VolumeGroupExceptionResponse eresp = null;
- private boolean sendxml;
-
- public UpdateVNFVolumesTask(UpdateVolumeGroupRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<UpdateVolumeGroupResponse>(response) {}
- : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- logger.debug("UpdateVNFVolumesTask start");
- try {
- Holder<Map<String, String>> outputs = new Holder<> ();
- Holder<VnfRollback> vnfRollback = new Holder<> ();
- String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
- logger.debug("in updateVfModuleVolume - completeVnfVfModuleType={}", completeVnfVfModuleType);
-
- if (req.getCloudSiteId().equals(TESTING_KEYWORD)) {
- outputs.value = testMap();
- } else {
- //vnfAdapter.updateVnf(
- // req.getCloudSiteId(),
- // req.getTenantId(),
- // req.getVnfType(),
- // req.getVnfVersion(),
- // req.getVfModuleType(),
- // "VOLUME", // request type is VOLUME
- // req.getVolumeGroupStackId(),
- // req.getVolumeGroupParams(),
- // req.getMsoRequest(),
- // outputs,
- // vnfRollback);
- vnfAdapter.updateVfModule (req.getCloudSiteId(),
- req.getCloudOwner(),
- req.getTenantId(),
- //req.getVnfType(),
- completeVnfVfModuleType,
- req.getVnfVersion(),
- req.getVolumeGroupStackId(),
- "VOLUME",
- null,
- null,
- req.getVolumeGroupStackId(),
- req.getModelCustomizationUuid(),
- req.getVolumeGroupParams(),
- req.getMsoRequest(),
- outputs,
- vnfRollback);
- }
- response = new UpdateVolumeGroupResponse(
- req.getVolumeGroupId(), req.getVolumeGroupStackId(),
- outputs.value, req.getMessageId());
- } catch (VnfException e) {
- logger.debug(EXCEPTION, e);
- eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("UpdateVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse());
- }
- }
-
- @GET
- @Path("{aaiVolumeGroupId}")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "QueryVNFVolumes",
- response = Response.class,
- notes = "Query an existing vnfVolume")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfVolume has been successfully queried"),
- @ApiResponse(code = 500, message = "query vnfVolume failed, examine entity object for details") })
- public Response queryVNFVolumes(
- @ApiParam(value = "aaiVolumeGroupId", required = true)
- @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
- @ApiParam(value = "cloudSiteId", required = true)
- @QueryParam("cloudSiteId") String cloudSiteId,
- @ApiParam(value = "cloudOwner", required = true)
- @QueryParam("cloudOwner") String cloudOwner,
- @ApiParam(value = "tenantId", required = true)
- @QueryParam("tenantId") String tenantId,
- @ApiParam(value = "volumeGroupStackId", required = true)
- @QueryParam("volumeGroupStackId") String volumeGroupStackId,
- @ApiParam(value = "skipAAI", required = true)
- @QueryParam("skipAAI") Boolean skipAAI,
- @ApiParam(value = "msoRequest.requestId", required = true)
- @QueryParam("msoRequest.requestId") String requestId,
- @ApiParam(value = "msoRequest.serviceInstanceId", required = true)
- @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId
- )
- {
- //This request responds synchronously only
- logger.debug("queryVNFVolumes enter: {} {}", aaiVolumeGroupId, volumeGroupStackId);
- MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId);
-
- try {
- int respStatus = HttpStatus.SC_OK;
- QueryVolumeGroupResponse qryResp = new QueryVolumeGroupResponse(aaiVolumeGroupId, volumeGroupStackId, null, null);
- Holder<Boolean> vnfExists = new Holder<>();
- Holder<String> vfModuleId = new Holder<>();
- Holder<VnfStatus> status = new Holder<>();
- Holder<Map<String, String>> outputs = new Holder<>();
- if (cloudSiteId != null && cloudSiteId.equals(TESTING_KEYWORD)) {
- if (tenantId != null && tenantId.equals(TESTING_KEYWORD)) {
- throw new VnfException("testing.");
- }
- vnfExists.value = true;
- vfModuleId.value = TESTING_KEYWORD;
- status.value = VnfStatus.ACTIVE;
- outputs.value = testMap();
- } else {
- vnfAdapter.queryVnf(cloudSiteId, cloudOwner, tenantId, volumeGroupStackId, msoRequest, vnfExists, vfModuleId, status, outputs);
- }
- if (!vnfExists.value) {
- logger.debug("VNFVolumes not found");
- qryResp.setVolumeGroupStatus(status.value);
- respStatus = HttpStatus.SC_NOT_FOUND;
- } else {
- logger.debug("VNFVolumes found {}, status={}", vfModuleId.value, status.value);
- qryResp.setVolumeGroupStatus(status.value);
- qryResp.setVolumeGroupOutputs(outputs.value);
- }
- logger.debug("Query queryVNFVolumes exit");
- return Response
- .status(respStatus)
- .entity(new GenericEntity<QueryVolumeGroupResponse>(qryResp) {})
- .build();
- } catch (VnfException e) {
- logger.error("{} {} AaiVolumeGroupId: {} VnfException - queryVNFVolumes", MessageEnum.RA_QUERY_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), aaiVolumeGroupId, e);
- VolumeGroupExceptionResponse excResp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null);
- logger.debug("Query queryVNFVolumes exit");
- return Response
- .status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity(new GenericEntity<VolumeGroupExceptionResponse>(excResp) {})
- .build();
- }
- }
+ private static final String TESTING_KEYWORD = "___TESTING___";
+ private static final String EXCEPTION = "Exception :";
+ private static final String RESP = ", resp=";
+ private static final String VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT =
+ "VolumeGroupId in URL does not match content";
+ @Autowired
+ private MsoVnfAdapterImpl vnfAdapter;
+
+ @Autowired
+ private Provider<BpelRestClient> bpelRestClientProvider;
+
+ @POST
+ @Path("")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "CreateVNFVolumes", response = Response.class, notes = "Create a new vnfVolume")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully created"),
+ @ApiResponse(code = 202, message = "create vnfVolume request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "create vnfVolume failed, examine entity object for details")})
+ public Response createVNFVolumes(
+ @ApiParam(value = "CreateVolumeGroupRequest", required = true) final CreateVolumeGroupRequest req) {
+ logger.debug("createVNFVolumes enter: {}", req.toJsonString());
+ CreateVNFVolumesTask task = new CreateVNFVolumesTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} Exception - createVNFVolumes: ", MessageEnum.RA_CREATE_VNF_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("createVNFVolumes exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class CreateVNFVolumesTask implements Runnable {
+ private final CreateVolumeGroupRequest req;
+ private CreateVolumeGroupResponse response = null;
+ private VolumeGroupExceptionResponse eresp = null;
+ private boolean sendxml;
+
+ public CreateVNFVolumesTask(CreateVolumeGroupRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<CreateVolumeGroupResponse>(response) {}
+ : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("CreateVFModule VolumesTask start");
+ try {
+ // Synchronous Web Service Outputs
+ Holder<String> stackId = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
+ Holder<VnfRollback> vnfRollback = new Holder<>();
+ String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
+ logger.debug("in createVfModuleVolumes - completeVnfVfModuleType={}", completeVnfVfModuleType);
+
+ String cloudsite = req.getCloudSiteId();
+ if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) {
+ String tenant = req.getTenantId();
+ if (tenant != null && tenant.equals(TESTING_KEYWORD)) {
+ throw new VnfException("testing.");
+ }
+ stackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484";
+ outputs.value = testMap();
+ } else {
+ // vnfAdapter.createVnf(
+ // req.getCloudSiteId(),
+ // req.getTenantId(),
+ // req.getVnfType(),
+ // req.getVnfVersion(),
+ // req.getVolumeGroupName(),
+ // "VOLUME", // request type is VOLUME
+ // null, // not sure about this
+ // req.getVolumeGroupParams(),
+ // req.getFailIfExists(),
+ // req.getSuppressBackout(),
+ // req.getMsoRequest(),
+ // stackId,
+ // outputs,
+ // vnfRollback);
+ vnfAdapter.createVfModule(req.getCloudSiteId(), // cloudSiteId,
+ req.getCloudOwner(), // cloudOwner,
+ req.getTenantId(), // tenantId,
+ // req.getVnfType(), //vnfType,
+ completeVnfVfModuleType, req.getVnfVersion(), // vnfVersion,
+ "", // genericVnfId
+ req.getVolumeGroupName(), // vnfName,
+ "", // vfModuleid
+ "VOLUME", // requestType,
+ null, // volumeGroupHeatStackId,
+ null, // baseVfHeatStackId,
+ req.getModelCustomizationUuid(), req.getVolumeGroupParams(), // inputs,
+ req.getFailIfExists(), // failIfExists,
+ req.getSuppressBackout(), // backout,
+ req.getEnableBridge(), req.getMsoRequest(), // msoRequest,
+ stackId, outputs, vnfRollback);
+ }
+ VolumeGroupRollback rb = new VolumeGroupRollback(req.getVolumeGroupId(), stackId.value, true, // TODO
+ // boolean
+ // volumeGroupCreated,
+ // when
+ // would
+ // it be
+ // false?
+ req.getTenantId(), req.getCloudOwner(), req.getCloudSiteId(), req.getMsoRequest(),
+ req.getMessageId());
+ response = new CreateVolumeGroupResponse(req.getVolumeGroupId(), stackId.value, true, // TODO boolean
+ // volumeGroupCreated,
+ // when would it
+ // be false?
+ outputs.value, rb, req.getMessageId());
+ } catch (VnfException e) {
+ logger.debug(EXCEPTION, e);
+ eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("CreateVFModule VolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse());
+ }
+ }
+
+ @DELETE
+ @Path("{aaiVolumeGroupId}")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "DeleteVNFVolumes", response = Response.class, notes = "Delete an existing vnfVolume")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully deleted"),
+ @ApiResponse(code = 202, message = "delete vnfVolume request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "delete vnfVolume failed, examine entity object for details")})
+ public Response deleteVNFVolumes(
+ @ApiParam(value = "aaiVolumeGroupId",
+ required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
+ @ApiParam(value = "DeleteVolumeGroupRequest", required = true) final DeleteVolumeGroupRequest req) {
+ logger.debug("deleteVNFVolumes enter: {}", req.toJsonString());
+ if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) {
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN)
+ .entity(VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT).build();
+ }
+ DeleteVNFVolumesTask task = new DeleteVNFVolumesTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} Exception - deleteVNFVolumes: ", MessageEnum.RA_DELETE_VNF_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("deleteVNFVolumes exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class DeleteVNFVolumesTask implements Runnable {
+ private final DeleteVolumeGroupRequest req;
+ private DeleteVolumeGroupResponse response = null;
+ private VolumeGroupExceptionResponse eresp = null;
+ private boolean sendxml;
+
+ public DeleteVNFVolumesTask(DeleteVolumeGroupRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<DeleteVolumeGroupResponse>(response) {}
+ : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("DeleteVNFVolumesTask start");
+ try {
+ if (!req.getCloudSiteId().equals(TESTING_KEYWORD)) {
+ vnfAdapter.deleteVnf(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(),
+ req.getVolumeGroupStackId(), req.getMsoRequest());
+ }
+ response = new DeleteVolumeGroupResponse(true, req.getMessageId());
+ } catch (VnfException e) {
+ logger.debug(EXCEPTION, e);
+ eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("DeleteVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse());
+ }
+ }
+
+ @DELETE
+ @Path("{aaiVolumeGroupId}/rollback")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "RollbackVNFVolumes", response = Response.class, notes = "Delete an existing vnfVolume")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully rolled back"),
+ @ApiResponse(code = 202,
+ message = "rollback vnfVolume request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "rollback vnfVolume failed, examine entity object for details")})
+ public Response rollbackVNFVolumes(
+ @ApiParam(value = "aaiVolumeGroupId",
+ required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
+ @ApiParam(value = "RollbackVolumeGroupRequest", required = true) final RollbackVolumeGroupRequest req) {
+ logger.debug("rollbackVNFVolumes enter: {}", req.toJsonString());
+ if (aaiVolumeGroupId == null || req.getVolumeGroupRollback() == null
+ || !aaiVolumeGroupId.equals(req.getVolumeGroupRollback().getVolumeGroupId())) {
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN)
+ .entity(VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT).build();
+ }
+ RollbackVNFVolumesTask task = new RollbackVNFVolumesTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} Exception - rollbackVNFVolumes: ", MessageEnum.RA_ROLLBACK_VNF_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("rollbackVNFVolumes exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class RollbackVNFVolumesTask implements Runnable {
+ private final RollbackVolumeGroupRequest req;
+ private RollbackVolumeGroupResponse response = null;
+ private VolumeGroupExceptionResponse eresp = null;
+ private boolean sendxml;
+
+ public RollbackVNFVolumesTask(RollbackVolumeGroupRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<RollbackVolumeGroupResponse>(response) {}
+ : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("DeleteVNFVolumesTask start");
+ try {
+ VolumeGroupRollback vgr = req.getVolumeGroupRollback();
+ VnfRollback vrb = new VnfRollback(vgr.getVolumeGroupStackId(), vgr.getTenantId(), vgr.getCloudOwnerId(),
+ vgr.getCloudSiteId(), true, true, vgr.getMsoRequest(), null, null, null, null);
+ vnfAdapter.rollbackVnf(vrb);
+ response = new RollbackVolumeGroupResponse(true, req.getMessageId());
+ } catch (VnfException e) {
+ logger.debug(EXCEPTION, e);
+ eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("DeleteVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse());
+ }
+
+ }
+
+ @PUT
+ @Path("{aaiVolumeGroupId}")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "UpdateVNFVolumes", response = Response.class, notes = "Update an existing vnfVolume")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully updated"),
+ @ApiResponse(code = 202, message = "update vnfVolume request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "update vnfVolume failed, examine entity object for details")})
+ public Response updateVNFVolumes(
+ @ApiParam(value = "aaiVolumeGroupId",
+ required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
+ @ApiParam(value = "UpdateVolumeGroupRequest", required = true) final UpdateVolumeGroupRequest req) {
+ logger.debug("updateVNFVolumes enter: {}", req.toJsonString());
+ if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) {
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN)
+ .entity(VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT).build();
+ }
+ UpdateVNFVolumesTask task = new UpdateVNFVolumesTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} Exception - updateVNFVolumes: ", MessageEnum.RA_UPDATE_VNF_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("updateVNFVolumes exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class UpdateVNFVolumesTask implements Runnable {
+ private final UpdateVolumeGroupRequest req;
+ private UpdateVolumeGroupResponse response = null;
+ private VolumeGroupExceptionResponse eresp = null;
+ private boolean sendxml;
+
+ public UpdateVNFVolumesTask(UpdateVolumeGroupRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<UpdateVolumeGroupResponse>(response) {}
+ : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("UpdateVNFVolumesTask start");
+ try {
+ Holder<Map<String, String>> outputs = new Holder<>();
+ Holder<VnfRollback> vnfRollback = new Holder<>();
+ String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
+ logger.debug("in updateVfModuleVolume - completeVnfVfModuleType={}", completeVnfVfModuleType);
+
+ if (req.getCloudSiteId().equals(TESTING_KEYWORD)) {
+ outputs.value = testMap();
+ } else {
+ // vnfAdapter.updateVnf(
+ // req.getCloudSiteId(),
+ // req.getTenantId(),
+ // req.getVnfType(),
+ // req.getVnfVersion(),
+ // req.getVfModuleType(),
+ // "VOLUME", // request type is VOLUME
+ // req.getVolumeGroupStackId(),
+ // req.getVolumeGroupParams(),
+ // req.getMsoRequest(),
+ // outputs,
+ // vnfRollback);
+ vnfAdapter.updateVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(),
+ // req.getVnfType(),
+ completeVnfVfModuleType, req.getVnfVersion(), req.getVolumeGroupStackId(), "VOLUME", null,
+ null, req.getVolumeGroupStackId(), req.getModelCustomizationUuid(),
+ req.getVolumeGroupParams(), req.getMsoRequest(), outputs, vnfRollback);
+ }
+ response = new UpdateVolumeGroupResponse(req.getVolumeGroupId(), req.getVolumeGroupStackId(),
+ outputs.value, req.getMessageId());
+ } catch (VnfException e) {
+ logger.debug(EXCEPTION, e);
+ eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("UpdateVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse());
+ }
+ }
+
+ @GET
+ @Path("{aaiVolumeGroupId}")
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "QueryVNFVolumes", response = Response.class, notes = "Query an existing vnfVolume")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully queried"),
+ @ApiResponse(code = 500, message = "query vnfVolume failed, examine entity object for details")})
+ public Response queryVNFVolumes(
+ @ApiParam(value = "aaiVolumeGroupId",
+ required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
+ @ApiParam(value = "cloudSiteId", required = true) @QueryParam("cloudSiteId") String cloudSiteId,
+ @ApiParam(value = "cloudOwner", required = true) @QueryParam("cloudOwner") String cloudOwner,
+ @ApiParam(value = "tenantId", required = true) @QueryParam("tenantId") String tenantId,
+ @ApiParam(value = "volumeGroupStackId",
+ required = true) @QueryParam("volumeGroupStackId") String volumeGroupStackId,
+ @ApiParam(value = "skipAAI", required = true) @QueryParam("skipAAI") Boolean skipAAI,
+ @ApiParam(value = "msoRequest.requestId",
+ required = true) @QueryParam("msoRequest.requestId") String requestId,
+ @ApiParam(value = "msoRequest.serviceInstanceId",
+ required = true) @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId) {
+ // This request responds synchronously only
+ logger.debug("queryVNFVolumes enter: {} {}", aaiVolumeGroupId, volumeGroupStackId);
+ MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId);
+
+ try {
+ int respStatus = HttpStatus.SC_OK;
+ QueryVolumeGroupResponse qryResp =
+ new QueryVolumeGroupResponse(aaiVolumeGroupId, volumeGroupStackId, null, null);
+ Holder<Boolean> vnfExists = new Holder<>();
+ Holder<String> vfModuleId = new Holder<>();
+ Holder<VnfStatus> status = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
+ if (cloudSiteId != null && cloudSiteId.equals(TESTING_KEYWORD)) {
+ if (tenantId != null && tenantId.equals(TESTING_KEYWORD)) {
+ throw new VnfException("testing.");
+ }
+ vnfExists.value = true;
+ vfModuleId.value = TESTING_KEYWORD;
+ status.value = VnfStatus.ACTIVE;
+ outputs.value = testMap();
+ } else {
+ vnfAdapter.queryVnf(cloudSiteId, cloudOwner, tenantId, volumeGroupStackId, msoRequest, vnfExists,
+ vfModuleId, status, outputs);
+ }
+ if (!vnfExists.value) {
+ logger.debug("VNFVolumes not found");
+ qryResp.setVolumeGroupStatus(status.value);
+ respStatus = HttpStatus.SC_NOT_FOUND;
+ } else {
+ logger.debug("VNFVolumes found {}, status={}", vfModuleId.value, status.value);
+ qryResp.setVolumeGroupStatus(status.value);
+ qryResp.setVolumeGroupOutputs(outputs.value);
+ }
+ logger.debug("Query queryVNFVolumes exit");
+ return Response.status(respStatus).entity(new GenericEntity<QueryVolumeGroupResponse>(qryResp) {}).build();
+ } catch (VnfException e) {
+ logger.error("{} {} AaiVolumeGroupId: {} VnfException - queryVNFVolumes", MessageEnum.RA_QUERY_VNF_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), aaiVolumeGroupId, e);
+ VolumeGroupExceptionResponse excResp = new VolumeGroupExceptionResponse(e.getMessage(),
+ MsoExceptionCategory.INTERNAL, Boolean.FALSE, null);
+ logger.debug("Query queryVNFVolumes exit");
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
+ .entity(new GenericEntity<VolumeGroupExceptionResponse>(excResp) {}).build();
+ }
+ }
+
public static Map<String, String> testMap() {
- Map<String, String> m = new HashMap<>();
- m.put("mickey", "7");
- m.put("clyde", "10");
- m.put("wayne", "99");
- return m;
+ Map<String, String> m = new HashMap<>();
+ m.put("mickey", "7");
+ m.put("clyde", "10");
+ m.put("wayne", "99");
+ return m;
}
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java
index cbbfdf359a..0ceba20051 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java
@@ -70,13 +70,11 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
- * This class services calls to the REST interface for VNF Volumes (http://host:port/vnfs/rest/v1/volume-groups)
- * Both XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default.
- * For testing, call with cloudSiteId = ___TESTING___
- * To test exceptions, also set tenantId = ___TESTING___
+ * This class services calls to the REST interface for VNF Volumes (http://host:port/vnfs/rest/v1/volume-groups) Both
+ * XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. For
+ * testing, call with cloudSiteId = ___TESTING___ To test exceptions, also set tenantId = ___TESTING___
*
- * V2 incorporates run-time selection of sub-orchestrator implementation (Heat or Cloudify)
- * based on the target cloud.
+ * V2 incorporates run-time selection of sub-orchestrator implementation (Heat or Cloudify) based on the target cloud.
*/
@Path("/v2/volume-groups")
@Api(value = "/v2/volume-groups", description = "root of volume-groups adapters restful web service v2")
@@ -84,581 +82,511 @@ import org.springframework.stereotype.Component;
public class VolumeAdapterRestV2 {
private static final Logger logger = LoggerFactory.getLogger(VolumeAdapterRestV2.class);
- private static final String TESTING_KEYWORD = "___TESTING___";
- private static final String RESP=", resp=";
- private static final String EXCEPTION="Exception :";
- private static final String VOLUME_GROUPID_MISSING="VolumeGroupId in URL does not match content";
-
- @Autowired
- private VnfAdapterRestUtils vnfAdapterRestUtils;
-
- @Autowired
- private Provider<BpelRestClient> bpelRestClientProvider;
-
- @POST
- @Path("")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "CreateVNFVolumes",
- response = Response.class,
- notes = "Create a new vnfVolume")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfVolume has been successfully created"),
- @ApiResponse(code = 202, message = "create vnfVolume request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "create vnfVolume failed, examine entity object for details") })
- public Response createVNFVolumes(
- @ApiParam(value = "mode", required = true)
- @QueryParam("mode") String mode,
- @ApiParam(value = "CreateVolumeGroupRequest", required = true)
- final CreateVolumeGroupRequest req)
- {
- logger.debug("createVNFVolumes enter: {}", req.toJsonString());
- CreateVNFVolumesTask task = new CreateVNFVolumesTask(req, mode);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} Exception - createVNFVolumes: ", MessageEnum.RA_CREATE_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("createVNFVolumes exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class CreateVNFVolumesTask implements Runnable {
- private final CreateVolumeGroupRequest req;
- private CreateVolumeGroupResponse response = null;
- private VolumeGroupExceptionResponse eresp = null;
- private boolean sendxml;
- private String mode;
-
- public CreateVNFVolumesTask(CreateVolumeGroupRequest req, String mode) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- this.mode = mode;
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<CreateVolumeGroupResponse>(response) {}
- : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- logger.debug("CreateVFModule VolumesTask start");
- try {
- // Synchronous Web Service Outputs
- Holder<String> stackId = new Holder<>();
- Holder<Map<String, String>> outputs = new Holder<>();
- Holder<VnfRollback> vnfRollback = new Holder<>();
- String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
- logger.debug("in createVfModuleVolumes - completeVnfVfModuleType={}", completeVnfVfModuleType);
-
- String cloudsiteId = req.getCloudSiteId();
- if (cloudsiteId != null && cloudsiteId.equals(TESTING_KEYWORD)) {
- String tenant = req.getTenantId();
- if (tenant != null && tenant.equals(TESTING_KEYWORD)) {
- throw new VnfException("testing.");
- }
- stackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484";
- outputs.value = testMap();
- } else {
- // Support different Adapter Implementations
- MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId);
- vnfAdapter.createVfModule(
- req.getCloudSiteId(), //cloudSiteId,
- req.getCloudOwner(), //cloudOwner,
- req.getTenantId(), //tenantId,
- completeVnfVfModuleType, //vnfType,
- req.getVnfVersion(), //vnfVersion,
- "", // genericVnfId
- req.getVolumeGroupName(), //vnfName,
- "", // vfModuleId
- "VOLUME", //requestType,
- null, //volumeGroupHeatStackId,
- null, //baseVfHeatStackId,
- req.getModelCustomizationUuid(),
- req.getVolumeGroupParams(), //inputs,
- req.getFailIfExists(), //failIfExists,
- req.getSuppressBackout(), //backout,
- req.getEnableBridge(),
- req.getMsoRequest(), // msoRequest,
- stackId,
- outputs,
- vnfRollback);
- }
-
- VolumeGroupRollback rb = new VolumeGroupRollback(
- req.getVolumeGroupId(),
- stackId.value,
- vnfRollback.value.getVnfCreated(),
- req.getTenantId(),
- req.getCloudOwner(),
- req.getCloudSiteId(),
- req.getMsoRequest(),
- req.getMessageId());
-
- response = new CreateVolumeGroupResponse(
- req.getVolumeGroupId(),
- stackId.value,
- vnfRollback.value.getVnfCreated(),
- outputs.value,
- rb,
- req.getMessageId());
- } catch (VnfException e) {
- logger.debug(EXCEPTION, e);
- eresp = new VolumeGroupExceptionResponse(
- e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("CreateVFModule VolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse());
- }
- }
-
- @DELETE
- @Path("{aaiVolumeGroupId}")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "DeleteVNFVolumes",
- response = Response.class,
- notes = "Delete an existing vnfVolume")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfVolume has been successfully deleted"),
- @ApiResponse(code = 202, message = "delete vnfVolume request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "delete vnfVolume failed, examine entity object for details") })
- public Response deleteVNFVolumes(
- @ApiParam(value = "aaiVolumeGroupId", required = true)
- @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
- @ApiParam(value = "mode", required = true)
- @QueryParam("mode") String mode,
- @ApiParam(value = "DeleteVolumeGroupRequest", required = true)
- final DeleteVolumeGroupRequest req
- )
- {
- logger.debug("deleteVNFVolumes enter: {}", req.toJsonString());
- if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) {
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity(VOLUME_GROUPID_MISSING)
- .build();
- }
- DeleteVNFVolumesTask task = new DeleteVNFVolumesTask(req, mode);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} Exception - deleteVNFVolumes: ", MessageEnum.RA_DELETE_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("deleteVNFVolumes exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class DeleteVNFVolumesTask implements Runnable {
- private final DeleteVolumeGroupRequest req;
- private DeleteVolumeGroupResponse response = null;
- private VolumeGroupExceptionResponse eresp = null;
- private boolean sendxml;
- private String mode;
-
- public DeleteVNFVolumesTask(DeleteVolumeGroupRequest req, String mode) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- this.mode = mode;
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<DeleteVolumeGroupResponse>(response) {}
- : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- logger.debug("DeleteVNFVolumesTask start");
- String cloudSiteId = req.getCloudSiteId();
- try {
- if (! cloudSiteId.equals(TESTING_KEYWORD)) {
- // Support different Adapter Implementations
- MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudSiteId);
- vnfAdapter.deleteVnf(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), req.getVolumeGroupStackId(), req.getMsoRequest());
- }
- response = new DeleteVolumeGroupResponse(true, req.getMessageId());
- } catch (VnfException e) {
- logger.debug(EXCEPTION, e);
- eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("DeleteVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse());
- }
- }
-
- @DELETE
- @Path("{aaiVolumeGroupId}/rollback")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "RollbackVNFVolumes",
- response = Response.class,
- notes = "Delete an existing vnfVolume")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfVolume has been successfully rolled back"),
- @ApiResponse(code = 202, message = "rollback vnfVolume request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "rollback vnfVolume failed, examine entity object for details") })
- public Response rollbackVNFVolumes(
- @ApiParam(value = "aaiVolumeGroupId", required = true)
- @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
- @ApiParam(value = "RollbackVolumeGroupRequest", required = true)
- final RollbackVolumeGroupRequest req
- )
- {
- logger.debug("rollbackVNFVolumes enter: {}", req.toJsonString());
- if (aaiVolumeGroupId == null || req.getVolumeGroupRollback() == null || !aaiVolumeGroupId.equals(req.getVolumeGroupRollback().getVolumeGroupId())) {
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity(VOLUME_GROUPID_MISSING)
- .build();
- }
- RollbackVNFVolumesTask task = new RollbackVNFVolumesTask(req);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} Exception - rollbackVNFVolumes: ", MessageEnum.RA_ROLLBACK_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("rollbackVNFVolumes exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class RollbackVNFVolumesTask implements Runnable {
- private final RollbackVolumeGroupRequest req;
- private RollbackVolumeGroupResponse response = null;
- private VolumeGroupExceptionResponse eresp = null;
- private boolean sendxml;
-
- public RollbackVNFVolumesTask(RollbackVolumeGroupRequest req) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<RollbackVolumeGroupResponse>(response) {}
- : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- logger.debug("RollbackVNFVolumesTask start");
- try {
- VolumeGroupRollback vgr = req.getVolumeGroupRollback();
- VnfRollback vrb = new VnfRollback(
- vgr.getVolumeGroupStackId(), vgr.getTenantId(), vgr.getCloudOwnerId(), vgr.getCloudSiteId(), true, true,
- vgr.getMsoRequest(), null, null, null, null);
-
- // Support different Adapter Implementations
- MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(vrb.getMode(), vrb.getCloudSiteId());
- vnfAdapter.rollbackVnf(vrb);
- response = new RollbackVolumeGroupResponse(true, req.getMessageId());
- } catch (VnfException e) {
- logger.debug(EXCEPTION, e);
- eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("RollbackVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse());
- }
-
- }
-
- @PUT
- @Path("{aaiVolumeGroupId}")
- @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "UpdateVNFVolumes",
- response = Response.class,
- notes = "Update an existing vnfVolume")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfVolume has been successfully updated"),
- @ApiResponse(code = 202, message = "update vnfVolume request has been successfully accepted (async only)"),
- @ApiResponse(code = 500, message = "update vnfVolume failed, examine entity object for details") })
- public Response updateVNFVolumes(
- @ApiParam(value = "aaiVolumeGroupId", required = true)
- @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
- @ApiParam(value = "mode", required = true)
- @QueryParam("mode") String mode,
- @ApiParam(value = "UpdateVolumeGroupRequest", required = true)
- final UpdateVolumeGroupRequest req
- )
- {
- logger.debug("updateVNFVolumes enter: {}", req.toJsonString());
- if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) {
- return Response
- .status(HttpStatus.SC_BAD_REQUEST)
- .type(MediaType.TEXT_PLAIN)
- .entity(VOLUME_GROUPID_MISSING)
- .build();
- }
- UpdateVNFVolumesTask task = new UpdateVNFVolumesTask(req, mode);
- if (req.isSynchronous()) {
- // This is a synchronous request
- task.run();
- return Response
- .status(task.getStatusCode())
- .entity(task.getGenericEntityResponse())
- .build();
- } else {
- // This is an asynchronous request
- try {
- Thread t1 = new Thread(task);
- t1.start();
- } catch (Exception e) {
- // problem handling create, send generic failure as sync resp to caller
- logger.error("{} {} Exception - updateVNFVolumes: ", MessageEnum.RA_UPDATE_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), e);
- return Response.serverError().build();
- }
- // send sync response (ACK) to caller
- logger.debug("updateVNFVolumes exit");
- return Response.status(HttpStatus.SC_ACCEPTED).build();
- }
- }
-
- public class UpdateVNFVolumesTask implements Runnable {
- private final UpdateVolumeGroupRequest req;
- private UpdateVolumeGroupResponse response = null;
- private VolumeGroupExceptionResponse eresp = null;
- private boolean sendxml;
- private String mode;
-
- public UpdateVNFVolumesTask(UpdateVolumeGroupRequest req, String mode) {
- this.req = req;
- this.sendxml = true; // can be set with a field or header later
- this.mode = mode;
- }
- public int getStatusCode() {
- return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
- }
- public Object getGenericEntityResponse() {
- return (response != null)
- ? new GenericEntity<UpdateVolumeGroupResponse>(response) {}
- : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
- }
- private String getResponse() {
- if (response != null) {
- return sendxml ? response.toXmlString() : response.toJsonString();
- } else {
- return sendxml ? eresp.toXmlString() : eresp.toJsonString();
- }
- }
- @Override
- public void run() {
- logger.debug("UpdateVNFVolumesTask start");
- try {
- Holder<Map<String, String>> outputs = new Holder<> ();
- Holder<VnfRollback> vnfRollback = new Holder<> ();
- String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
- logger.debug("in updateVfModuleVolume - completeVnfVfModuleType={}", completeVnfVfModuleType);
-
- if (req.getCloudSiteId().equals(TESTING_KEYWORD)) {
- outputs.value = testMap();
- } else {
- // Support different Adapter Implementations
- MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, req.getCloudSiteId());
- vnfAdapter.updateVfModule (req.getCloudSiteId(),
- req.getCloudOwner(),
- req.getTenantId(),
- //req.getVnfType(),
- completeVnfVfModuleType,
- req.getVnfVersion(),
- req.getVolumeGroupStackId(),
- "VOLUME",
- null,
- null,
- req.getVolumeGroupStackId(),
- req.getModelCustomizationUuid(),
- req.getVolumeGroupParams(),
- req.getMsoRequest(),
- outputs,
- vnfRollback);
- }
- response = new UpdateVolumeGroupResponse(
- req.getVolumeGroupId(), req.getVolumeGroupStackId(),
- outputs.value, req.getMessageId());
- } catch (VnfException e) {
- logger.debug(EXCEPTION, e);
- eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId());
- }
- if (!req.isSynchronous()) {
- // This is asynch, so POST response back to caller
- BpelRestClient bpelClient = bpelRestClientProvider.get();
- bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
- }
- logger.debug("UpdateVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse());
- }
- }
-
- @GET
- @Path("{aaiVolumeGroupId}")
- @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @ApiOperation(value = "QueryVNFVolumes",
- response = Response.class,
- notes = "Query an existing vnfVolume")
- @ApiResponses({
- @ApiResponse(code = 200, message = "vnfVolume has been successfully queried"),
- @ApiResponse(code = 500, message = "query vnfVolume failed, examine entity object for details") })
- public Response queryVNFVolumes(
- @ApiParam(value = "aaiVolumeGroupId", required = true)
- @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
- @ApiParam(value = "cloudSiteId", required = true)
- @QueryParam("cloudSiteId") String cloudSiteId,
- @ApiParam(value = "cloudOwner", required = true)
- @QueryParam("cloudOwner") String cloudOwner,
- @ApiParam(value = "tenantId", required = true)
- @QueryParam("tenantId") String tenantId,
- @ApiParam(value = "volumeGroupStackId", required = true)
- @QueryParam("volumeGroupStackId") String volumeGroupStackId,
- @ApiParam(value = "skipAAI", required = true)
- @QueryParam("skipAAI") Boolean skipAAI,
- @ApiParam(value = "msoRequest.requestId", required = true)
- @QueryParam("msoRequest.requestId") String requestId,
- @ApiParam(value = "msoRequest.serviceInstanceId", required = true)
- @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId,
- @ApiParam(value = "mode", required = true)
- @QueryParam("mode") String mode
- )
- {
- //This request responds synchronously only
- logger.debug("queryVNFVolumes enter: {} {}", aaiVolumeGroupId, volumeGroupStackId);
- MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId);
-
- try {
- int respStatus = HttpStatus.SC_OK;
- QueryVolumeGroupResponse qryResp = new QueryVolumeGroupResponse(aaiVolumeGroupId, volumeGroupStackId, null, null);
- Holder<Boolean> vnfExists = new Holder<>();
- Holder<String> vfModuleId = new Holder<>();
- Holder<VnfStatus> status = new Holder<>();
- Holder<Map<String, String>> outputs = new Holder<>();
- if (cloudSiteId != null && cloudSiteId.equals(TESTING_KEYWORD)) {
- if (tenantId != null && tenantId.equals(TESTING_KEYWORD)) {
- throw new VnfException("testing.");
- }
- vnfExists.value = true;
- vfModuleId.value = TESTING_KEYWORD;
- status.value = VnfStatus.ACTIVE;
- outputs.value = testMap();
- } else {
- // Support different Adapter Implementations
- MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudSiteId);
- vnfAdapter.queryVnf(cloudSiteId, cloudOwner, tenantId, volumeGroupStackId, msoRequest, vnfExists, vfModuleId, status, outputs);
- }
- if (!vnfExists.value) {
- logger.debug("VNFVolumes not found");
- qryResp.setVolumeGroupStatus(status.value);
- respStatus = HttpStatus.SC_NOT_FOUND;
- } else {
- logger.debug("VNFVolumes found {}, status={}", vfModuleId.value, status.value);
- qryResp.setVolumeGroupStatus(status.value);
- qryResp.setVolumeGroupOutputs(outputs.value);
- }
- logger.debug("Query queryVNFVolumes exit");
- return Response
- .status(respStatus)
- .entity(new GenericEntity<QueryVolumeGroupResponse>(qryResp) {})
- .build();
- } catch (VnfException e) {
- logger.error("{} {} AaiVolumeGroupId: {} VnfException - queryVNFVolumes: ", MessageEnum.RA_QUERY_VNF_ERR,
- ErrorCode.BusinessProcesssError.getValue(), aaiVolumeGroupId, e);
- VolumeGroupExceptionResponse excResp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null);
- logger.debug("Query queryVNFVolumes exit");
- return Response
- .status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity(new GenericEntity<VolumeGroupExceptionResponse>(excResp) {})
- .build();
- }
- }
+ private static final String TESTING_KEYWORD = "___TESTING___";
+ private static final String RESP = ", resp=";
+ private static final String EXCEPTION = "Exception :";
+ private static final String VOLUME_GROUPID_MISSING = "VolumeGroupId in URL does not match content";
+
+ @Autowired
+ private VnfAdapterRestUtils vnfAdapterRestUtils;
+
+ @Autowired
+ private Provider<BpelRestClient> bpelRestClientProvider;
+
+ @POST
+ @Path("")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "CreateVNFVolumes", response = Response.class, notes = "Create a new vnfVolume")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully created"),
+ @ApiResponse(code = 202, message = "create vnfVolume request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "create vnfVolume failed, examine entity object for details")})
+ public Response createVNFVolumes(@ApiParam(value = "mode", required = true) @QueryParam("mode") String mode,
+ @ApiParam(value = "CreateVolumeGroupRequest", required = true) final CreateVolumeGroupRequest req) {
+ logger.debug("createVNFVolumes enter: {}", req.toJsonString());
+ CreateVNFVolumesTask task = new CreateVNFVolumesTask(req, mode);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} Exception - createVNFVolumes: ", MessageEnum.RA_CREATE_VNF_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("createVNFVolumes exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class CreateVNFVolumesTask implements Runnable {
+ private final CreateVolumeGroupRequest req;
+ private CreateVolumeGroupResponse response = null;
+ private VolumeGroupExceptionResponse eresp = null;
+ private boolean sendxml;
+ private String mode;
+
+ public CreateVNFVolumesTask(CreateVolumeGroupRequest req, String mode) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ this.mode = mode;
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<CreateVolumeGroupResponse>(response) {}
+ : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("CreateVFModule VolumesTask start");
+ try {
+ // Synchronous Web Service Outputs
+ Holder<String> stackId = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
+ Holder<VnfRollback> vnfRollback = new Holder<>();
+ String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
+ logger.debug("in createVfModuleVolumes - completeVnfVfModuleType={}", completeVnfVfModuleType);
+
+ String cloudsiteId = req.getCloudSiteId();
+ if (cloudsiteId != null && cloudsiteId.equals(TESTING_KEYWORD)) {
+ String tenant = req.getTenantId();
+ if (tenant != null && tenant.equals(TESTING_KEYWORD)) {
+ throw new VnfException("testing.");
+ }
+ stackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484";
+ outputs.value = testMap();
+ } else {
+ // Support different Adapter Implementations
+ MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId);
+ vnfAdapter.createVfModule(req.getCloudSiteId(), // cloudSiteId,
+ req.getCloudOwner(), // cloudOwner,
+ req.getTenantId(), // tenantId,
+ completeVnfVfModuleType, // vnfType,
+ req.getVnfVersion(), // vnfVersion,
+ "", // genericVnfId
+ req.getVolumeGroupName(), // vnfName,
+ "", // vfModuleId
+ "VOLUME", // requestType,
+ null, // volumeGroupHeatStackId,
+ null, // baseVfHeatStackId,
+ req.getModelCustomizationUuid(), req.getVolumeGroupParams(), // inputs,
+ req.getFailIfExists(), // failIfExists,
+ req.getSuppressBackout(), // backout,
+ req.getEnableBridge(), req.getMsoRequest(), // msoRequest,
+ stackId, outputs, vnfRollback);
+ }
+
+ VolumeGroupRollback rb = new VolumeGroupRollback(req.getVolumeGroupId(), stackId.value,
+ vnfRollback.value.getVnfCreated(), req.getTenantId(), req.getCloudOwner(), req.getCloudSiteId(),
+ req.getMsoRequest(), req.getMessageId());
+
+ response = new CreateVolumeGroupResponse(req.getVolumeGroupId(), stackId.value,
+ vnfRollback.value.getVnfCreated(), outputs.value, rb, req.getMessageId());
+ } catch (VnfException e) {
+ logger.debug(EXCEPTION, e);
+ eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("CreateVFModule VolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse());
+ }
+ }
+
+ @DELETE
+ @Path("{aaiVolumeGroupId}")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "DeleteVNFVolumes", response = Response.class, notes = "Delete an existing vnfVolume")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully deleted"),
+ @ApiResponse(code = 202, message = "delete vnfVolume request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "delete vnfVolume failed, examine entity object for details")})
+ public Response deleteVNFVolumes(
+ @ApiParam(value = "aaiVolumeGroupId",
+ required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
+ @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode,
+ @ApiParam(value = "DeleteVolumeGroupRequest", required = true) final DeleteVolumeGroupRequest req) {
+ logger.debug("deleteVNFVolumes enter: {}", req.toJsonString());
+ if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) {
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity(VOLUME_GROUPID_MISSING)
+ .build();
+ }
+ DeleteVNFVolumesTask task = new DeleteVNFVolumesTask(req, mode);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} Exception - deleteVNFVolumes: ", MessageEnum.RA_DELETE_VNF_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("deleteVNFVolumes exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class DeleteVNFVolumesTask implements Runnable {
+ private final DeleteVolumeGroupRequest req;
+ private DeleteVolumeGroupResponse response = null;
+ private VolumeGroupExceptionResponse eresp = null;
+ private boolean sendxml;
+ private String mode;
+
+ public DeleteVNFVolumesTask(DeleteVolumeGroupRequest req, String mode) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ this.mode = mode;
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<DeleteVolumeGroupResponse>(response) {}
+ : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("DeleteVNFVolumesTask start");
+ String cloudSiteId = req.getCloudSiteId();
+ try {
+ if (!cloudSiteId.equals(TESTING_KEYWORD)) {
+ // Support different Adapter Implementations
+ MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudSiteId);
+ vnfAdapter.deleteVnf(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(),
+ req.getVolumeGroupStackId(), req.getMsoRequest());
+ }
+ response = new DeleteVolumeGroupResponse(true, req.getMessageId());
+ } catch (VnfException e) {
+ logger.debug(EXCEPTION, e);
+ eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("DeleteVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse());
+ }
+ }
+
+ @DELETE
+ @Path("{aaiVolumeGroupId}/rollback")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "RollbackVNFVolumes", response = Response.class, notes = "Delete an existing vnfVolume")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully rolled back"),
+ @ApiResponse(code = 202,
+ message = "rollback vnfVolume request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "rollback vnfVolume failed, examine entity object for details")})
+ public Response rollbackVNFVolumes(
+ @ApiParam(value = "aaiVolumeGroupId",
+ required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
+ @ApiParam(value = "RollbackVolumeGroupRequest", required = true) final RollbackVolumeGroupRequest req) {
+ logger.debug("rollbackVNFVolumes enter: {}", req.toJsonString());
+ if (aaiVolumeGroupId == null || req.getVolumeGroupRollback() == null
+ || !aaiVolumeGroupId.equals(req.getVolumeGroupRollback().getVolumeGroupId())) {
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity(VOLUME_GROUPID_MISSING)
+ .build();
+ }
+ RollbackVNFVolumesTask task = new RollbackVNFVolumesTask(req);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} Exception - rollbackVNFVolumes: ", MessageEnum.RA_ROLLBACK_VNF_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("rollbackVNFVolumes exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class RollbackVNFVolumesTask implements Runnable {
+ private final RollbackVolumeGroupRequest req;
+ private RollbackVolumeGroupResponse response = null;
+ private VolumeGroupExceptionResponse eresp = null;
+ private boolean sendxml;
+
+ public RollbackVNFVolumesTask(RollbackVolumeGroupRequest req) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<RollbackVolumeGroupResponse>(response) {}
+ : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("RollbackVNFVolumesTask start");
+ try {
+ VolumeGroupRollback vgr = req.getVolumeGroupRollback();
+ VnfRollback vrb = new VnfRollback(vgr.getVolumeGroupStackId(), vgr.getTenantId(), vgr.getCloudOwnerId(),
+ vgr.getCloudSiteId(), true, true, vgr.getMsoRequest(), null, null, null, null);
+
+ // Support different Adapter Implementations
+ MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(vrb.getMode(), vrb.getCloudSiteId());
+ vnfAdapter.rollbackVnf(vrb);
+ response = new RollbackVolumeGroupResponse(true, req.getMessageId());
+ } catch (VnfException e) {
+ logger.debug(EXCEPTION, e);
+ eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("RollbackVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse());
+ }
+
+ }
+
+ @PUT
+ @Path("{aaiVolumeGroupId}")
+ @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "UpdateVNFVolumes", response = Response.class, notes = "Update an existing vnfVolume")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully updated"),
+ @ApiResponse(code = 202, message = "update vnfVolume request has been successfully accepted (async only)"),
+ @ApiResponse(code = 500, message = "update vnfVolume failed, examine entity object for details")})
+ public Response updateVNFVolumes(
+ @ApiParam(value = "aaiVolumeGroupId",
+ required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
+ @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode,
+ @ApiParam(value = "UpdateVolumeGroupRequest", required = true) final UpdateVolumeGroupRequest req) {
+ logger.debug("updateVNFVolumes enter: {}", req.toJsonString());
+ if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) {
+ return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity(VOLUME_GROUPID_MISSING)
+ .build();
+ }
+ UpdateVNFVolumesTask task = new UpdateVNFVolumesTask(req, mode);
+ if (req.isSynchronous()) {
+ // This is a synchronous request
+ task.run();
+ return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build();
+ } else {
+ // This is an asynchronous request
+ try {
+ Thread t1 = new Thread(task);
+ t1.start();
+ } catch (Exception e) {
+ // problem handling create, send generic failure as sync resp to caller
+ logger.error("{} {} Exception - updateVNFVolumes: ", MessageEnum.RA_UPDATE_VNF_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ return Response.serverError().build();
+ }
+ // send sync response (ACK) to caller
+ logger.debug("updateVNFVolumes exit");
+ return Response.status(HttpStatus.SC_ACCEPTED).build();
+ }
+ }
+
+ public class UpdateVNFVolumesTask implements Runnable {
+ private final UpdateVolumeGroupRequest req;
+ private UpdateVolumeGroupResponse response = null;
+ private VolumeGroupExceptionResponse eresp = null;
+ private boolean sendxml;
+ private String mode;
+
+ public UpdateVNFVolumesTask(UpdateVolumeGroupRequest req, String mode) {
+ this.req = req;
+ this.sendxml = true; // can be set with a field or header later
+ this.mode = mode;
+ }
+
+ public int getStatusCode() {
+ return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST;
+ }
+
+ public Object getGenericEntityResponse() {
+ return (response != null) ? new GenericEntity<UpdateVolumeGroupResponse>(response) {}
+ : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {};
+ }
+
+ private String getResponse() {
+ if (response != null) {
+ return sendxml ? response.toXmlString() : response.toJsonString();
+ } else {
+ return sendxml ? eresp.toXmlString() : eresp.toJsonString();
+ }
+ }
+
+ @Override
+ public void run() {
+ logger.debug("UpdateVNFVolumesTask start");
+ try {
+ Holder<Map<String, String>> outputs = new Holder<>();
+ Holder<VnfRollback> vnfRollback = new Holder<>();
+ String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType();
+ logger.debug("in updateVfModuleVolume - completeVnfVfModuleType={}", completeVnfVfModuleType);
+
+ if (req.getCloudSiteId().equals(TESTING_KEYWORD)) {
+ outputs.value = testMap();
+ } else {
+ // Support different Adapter Implementations
+ MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, req.getCloudSiteId());
+ vnfAdapter.updateVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(),
+ // req.getVnfType(),
+ completeVnfVfModuleType, req.getVnfVersion(), req.getVolumeGroupStackId(), "VOLUME", null,
+ null, req.getVolumeGroupStackId(), req.getModelCustomizationUuid(),
+ req.getVolumeGroupParams(), req.getMsoRequest(), outputs, vnfRollback);
+ }
+ response = new UpdateVolumeGroupResponse(req.getVolumeGroupId(), req.getVolumeGroupStackId(),
+ outputs.value, req.getMessageId());
+ } catch (VnfException e) {
+ logger.debug(EXCEPTION, e);
+ eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true,
+ req.getMessageId());
+ }
+ if (!req.isSynchronous()) {
+ // This is asynch, so POST response back to caller
+ BpelRestClient bpelClient = bpelRestClientProvider.get();
+ bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml);
+ }
+ logger.debug("UpdateVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse());
+ }
+ }
+
+ @GET
+ @Path("{aaiVolumeGroupId}")
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @ApiOperation(value = "QueryVNFVolumes", response = Response.class, notes = "Query an existing vnfVolume")
+ @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully queried"),
+ @ApiResponse(code = 500, message = "query vnfVolume failed, examine entity object for details")})
+ public Response queryVNFVolumes(
+ @ApiParam(value = "aaiVolumeGroupId",
+ required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId,
+ @ApiParam(value = "cloudSiteId", required = true) @QueryParam("cloudSiteId") String cloudSiteId,
+ @ApiParam(value = "cloudOwner", required = true) @QueryParam("cloudOwner") String cloudOwner,
+ @ApiParam(value = "tenantId", required = true) @QueryParam("tenantId") String tenantId,
+ @ApiParam(value = "volumeGroupStackId",
+ required = true) @QueryParam("volumeGroupStackId") String volumeGroupStackId,
+ @ApiParam(value = "skipAAI", required = true) @QueryParam("skipAAI") Boolean skipAAI,
+ @ApiParam(value = "msoRequest.requestId",
+ required = true) @QueryParam("msoRequest.requestId") String requestId,
+ @ApiParam(value = "msoRequest.serviceInstanceId",
+ required = true) @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId,
+ @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode) {
+ // This request responds synchronously only
+ logger.debug("queryVNFVolumes enter: {} {}", aaiVolumeGroupId, volumeGroupStackId);
+ MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId);
+
+ try {
+ int respStatus = HttpStatus.SC_OK;
+ QueryVolumeGroupResponse qryResp =
+ new QueryVolumeGroupResponse(aaiVolumeGroupId, volumeGroupStackId, null, null);
+ Holder<Boolean> vnfExists = new Holder<>();
+ Holder<String> vfModuleId = new Holder<>();
+ Holder<VnfStatus> status = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
+ if (cloudSiteId != null && cloudSiteId.equals(TESTING_KEYWORD)) {
+ if (tenantId != null && tenantId.equals(TESTING_KEYWORD)) {
+ throw new VnfException("testing.");
+ }
+ vnfExists.value = true;
+ vfModuleId.value = TESTING_KEYWORD;
+ status.value = VnfStatus.ACTIVE;
+ outputs.value = testMap();
+ } else {
+ // Support different Adapter Implementations
+ MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudSiteId);
+ vnfAdapter.queryVnf(cloudSiteId, cloudOwner, tenantId, volumeGroupStackId, msoRequest, vnfExists,
+ vfModuleId, status, outputs);
+ }
+ if (!vnfExists.value) {
+ logger.debug("VNFVolumes not found");
+ qryResp.setVolumeGroupStatus(status.value);
+ respStatus = HttpStatus.SC_NOT_FOUND;
+ } else {
+ logger.debug("VNFVolumes found {}, status={}", vfModuleId.value, status.value);
+ qryResp.setVolumeGroupStatus(status.value);
+ qryResp.setVolumeGroupOutputs(outputs.value);
+ }
+ logger.debug("Query queryVNFVolumes exit");
+ return Response.status(respStatus).entity(new GenericEntity<QueryVolumeGroupResponse>(qryResp) {}).build();
+ } catch (VnfException e) {
+ logger.error("{} {} AaiVolumeGroupId: {} VnfException - queryVNFVolumes: ", MessageEnum.RA_QUERY_VNF_ERR,
+ ErrorCode.BusinessProcesssError.getValue(), aaiVolumeGroupId, e);
+ VolumeGroupExceptionResponse excResp = new VolumeGroupExceptionResponse(e.getMessage(),
+ MsoExceptionCategory.INTERNAL, Boolean.FALSE, null);
+ logger.debug("Query queryVNFVolumes exit");
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
+ .entity(new GenericEntity<VolumeGroupExceptionResponse>(excResp) {}).build();
+ }
+ }
+
public static Map<String, String> testMap() {
- Map<String, String> m = new HashMap<>();
- m.put("mickey", "7");
- m.put("clyde", "10");
- m.put("wayne", "99");
- return m;
+ Map<String, String> m = new HashMap<>();
+ m.put("mickey", "7");
+ m.put("clyde", "10");
+ m.put("wayne", "99");
+ return m;
}
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/CreateVnfNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/CreateVnfNotification.java
index ba301b10fe..e3c59fd93d 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/CreateVnfNotification.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/CreateVnfNotification.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.vnf.async.client;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -30,9 +29,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for createVnfNotification complex type.
+ * <p>
+ * Java class for createVnfNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="createVnfNotification">
@@ -76,15 +77,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "createVnfNotification", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage",
- "vnfId",
- "outputs",
- "rollback"
-})
+@XmlType(name = "createVnfNotification",
+ propOrder = {"messageId", "completed", "exception", "errorMessage", "vnfId", "outputs", "rollback"})
public class CreateVnfNotification {
@XmlElement(required = true)
@@ -99,10 +93,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -111,10 +103,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -139,10 +129,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -151,10 +139,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -163,10 +149,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -175,10 +159,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
@@ -187,10 +169,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the vnfId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfId() {
return vnfId;
@@ -199,10 +179,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the vnfId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfId(String value) {
this.vnfId = value;
@@ -211,10 +189,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the outputs property.
*
- * @return
- * possible object is
- * {@link CreateVnfNotification.Outputs }
- *
+ * @return possible object is {@link CreateVnfNotification.Outputs }
+ *
*/
public CreateVnfNotification.Outputs getOutputs() {
return outputs;
@@ -223,10 +199,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the outputs property.
*
- * @param value
- * allowed object is
- * {@link CreateVnfNotification.Outputs }
- *
+ * @param value allowed object is {@link CreateVnfNotification.Outputs }
+ *
*/
public void setOutputs(CreateVnfNotification.Outputs value) {
this.outputs = value;
@@ -235,10 +209,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the rollback property.
*
- * @return
- * possible object is
- * {@link VnfRollback }
- *
+ * @return possible object is {@link VnfRollback }
+ *
*/
public VnfRollback getRollback() {
return rollback;
@@ -247,10 +219,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the rollback property.
*
- * @param value
- * allowed object is
- * {@link VnfRollback }
- *
+ * @param value allowed object is {@link VnfRollback }
+ *
*/
public void setRollback(VnfRollback value) {
this.rollback = value;
@@ -258,9 +228,11 @@ public class CreateVnfNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -288,9 +260,7 @@ public class CreateVnfNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "entry"
- })
+ @XmlType(name = "", propOrder = {"entry"})
public static class Outputs {
protected List<CreateVnfNotification.Outputs.Entry> entry;
@@ -299,21 +269,20 @@ public class CreateVnfNotification {
* Gets the value of the entry property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the entry property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you
+ * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE>
+ * method for the entry property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getEntry().add(newItem);
+ * getEntry().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link CreateVnfNotification.Outputs.Entry }
+ * Objects of the following type(s) are allowed in the list {@link CreateVnfNotification.Outputs.Entry }
*
*
*/
@@ -326,9 +295,11 @@ public class CreateVnfNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -346,10 +317,7 @@ public class CreateVnfNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "key",
- "value"
- })
+ @XmlType(name = "", propOrder = {"key", "value"})
public static class Entry {
protected String key;
@@ -358,10 +326,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the key property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getKey() {
return key;
@@ -370,10 +336,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the key property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setKey(String value) {
this.key = value;
@@ -382,10 +346,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the value property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getValue() {
return value;
@@ -394,10 +356,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the value property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setValue(String value) {
this.value = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/DeleteVnfNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/DeleteVnfNotification.java
index d8c533b041..434cf7f772 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/DeleteVnfNotification.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/DeleteVnfNotification.java
@@ -27,9 +27,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for deleteVnfNotification complex type.
+ * <p>
+ * Java class for deleteVnfNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="deleteVnfNotification">
@@ -49,12 +51,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "deleteVnfNotification", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage"
-})
+@XmlType(name = "deleteVnfNotification", propOrder = {"messageId", "completed", "exception", "errorMessage"})
public class DeleteVnfNotification {
@XmlElement(required = true)
@@ -66,10 +63,8 @@ public class DeleteVnfNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -78,10 +73,8 @@ public class DeleteVnfNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -106,10 +99,8 @@ public class DeleteVnfNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -118,10 +109,8 @@ public class DeleteVnfNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -130,10 +119,8 @@ public class DeleteVnfNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -142,10 +129,8 @@ public class DeleteVnfNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoExceptionCategory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoExceptionCategory.java
index 73642a7f44..de389d354b 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoExceptionCategory.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoExceptionCategory.java
@@ -25,10 +25,13 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for msoExceptionCategory.
+ * <p>
+ * Java class for msoExceptionCategory.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
* <p>
+ * The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ *
* <pre>
* &lt;simpleType name="msoExceptionCategory">
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
@@ -45,10 +48,7 @@ import javax.xml.bind.annotation.XmlType;
@XmlEnum
public enum MsoExceptionCategory {
- OPENSTACK,
- IO,
- INTERNAL,
- USERDATA;
+ OPENSTACK, IO, INTERNAL, USERDATA;
public String value() {
return name();
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoRequest.java
index a4253b0cef..b1159f1de7 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoRequest.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoRequest.java
@@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for msoRequest complex type.
+ * <p>
+ * Java class for msoRequest complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="msoRequest">
@@ -46,10 +48,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "msoRequest", propOrder = {
- "requestId",
- "serviceInstanceId"
-})
+@XmlType(name = "msoRequest", propOrder = {"requestId", "serviceInstanceId"})
public class MsoRequest {
protected String requestId;
@@ -58,10 +57,8 @@ public class MsoRequest {
/**
* Gets the value of the requestId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getRequestId() {
return requestId;
@@ -70,10 +67,8 @@ public class MsoRequest {
/**
* Sets the value of the requestId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setRequestId(String value) {
this.requestId = value;
@@ -82,10 +77,8 @@ public class MsoRequest {
/**
* Gets the value of the serviceInstanceId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getServiceInstanceId() {
return serviceInstanceId;
@@ -94,10 +87,8 @@ public class MsoRequest {
/**
* Sets the value of the serviceInstanceId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setServiceInstanceId(String value) {
this.serviceInstanceId = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/ObjectFactory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/ObjectFactory.java
index 1e1a80e74c..ced49e2313 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/ObjectFactory.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/ObjectFactory.java
@@ -29,23 +29,19 @@ import javax.xml.namespace.QName;
/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the org.onap.so.adapters.vnf.async.client package.
- * <p>An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
- * provided in this class.
+ * This object contains factory methods for each Java content interface and Java element interface generated in the
+ * org.onap.so.adapters.vnf.async.client package.
+ * <p>
+ * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content.
+ * The Java representation of XML content can consist of schema derived interfaces and classes representing the binding
+ * of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in
+ * this class.
*
*/
@XmlRegistry
public class ObjectFactory {
- private static final String URL= "http://org.onap.so/vnfNotify";
+ private static final String URL = "http://org.onap.so/vnfNotify";
private final static QName _QueryVnfNotification_QNAME = new QName(URL, "queryVnfNotification");
private final static QName _RollbackVnfNotification_QNAME = new QName(URL, "rollbackVnfNotification");
private final static QName _CreateVnfNotification_QNAME = new QName(URL, "createVnfNotification");
@@ -53,11 +49,11 @@ public class ObjectFactory {
private final static QName _UpdateVnfNotification_QNAME = new QName(URL, "updateVnfNotification");
/**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.so.adapters.vnf.async.client
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
+ * org.onap.so.adapters.vnf.async.client
*
*/
- public ObjectFactory() {
- }
+ public ObjectFactory() {}
/**
* Create an instance of {@link UpdateVnfNotification }
@@ -169,7 +165,8 @@ public class ObjectFactory {
*/
@XmlElementDecl(namespace = URL, name = "queryVnfNotification")
public JAXBElement<QueryVnfNotification> createQueryVnfNotification(QueryVnfNotification value) {
- return new JAXBElement<QueryVnfNotification>(_QueryVnfNotification_QNAME, QueryVnfNotification.class, null, value);
+ return new JAXBElement<QueryVnfNotification>(_QueryVnfNotification_QNAME, QueryVnfNotification.class, null,
+ value);
}
/**
@@ -178,7 +175,8 @@ public class ObjectFactory {
*/
@XmlElementDecl(namespace = URL, name = "rollbackVnfNotification")
public JAXBElement<RollbackVnfNotification> createRollbackVnfNotification(RollbackVnfNotification value) {
- return new JAXBElement<RollbackVnfNotification>(_RollbackVnfNotification_QNAME, RollbackVnfNotification.class, null, value);
+ return new JAXBElement<RollbackVnfNotification>(_RollbackVnfNotification_QNAME, RollbackVnfNotification.class,
+ null, value);
}
/**
@@ -187,7 +185,8 @@ public class ObjectFactory {
*/
@XmlElementDecl(namespace = URL, name = "createVnfNotification")
public JAXBElement<CreateVnfNotification> createCreateVnfNotification(CreateVnfNotification value) {
- return new JAXBElement<CreateVnfNotification>(_CreateVnfNotification_QNAME, CreateVnfNotification.class, null, value);
+ return new JAXBElement<CreateVnfNotification>(_CreateVnfNotification_QNAME, CreateVnfNotification.class, null,
+ value);
}
/**
@@ -196,7 +195,8 @@ public class ObjectFactory {
*/
@XmlElementDecl(namespace = URL, name = "deleteVnfNotification")
public JAXBElement<DeleteVnfNotification> createDeleteVnfNotification(DeleteVnfNotification value) {
- return new JAXBElement<DeleteVnfNotification>(_DeleteVnfNotification_QNAME, DeleteVnfNotification.class, null, value);
+ return new JAXBElement<DeleteVnfNotification>(_DeleteVnfNotification_QNAME, DeleteVnfNotification.class, null,
+ value);
}
/**
@@ -205,7 +205,8 @@ public class ObjectFactory {
*/
@XmlElementDecl(namespace = URL, name = "updateVnfNotification")
public JAXBElement<UpdateVnfNotification> createUpdateVnfNotification(UpdateVnfNotification value) {
- return new JAXBElement<UpdateVnfNotification>(_UpdateVnfNotification_QNAME, UpdateVnfNotification.class, null, value);
+ return new JAXBElement<UpdateVnfNotification>(_UpdateVnfNotification_QNAME, UpdateVnfNotification.class, null,
+ value);
}
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/QueryVnfNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/QueryVnfNotification.java
index 0fd701d4f6..8968851fe1 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/QueryVnfNotification.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/QueryVnfNotification.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.vnf.async.client;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -30,9 +29,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for queryVnfNotification complex type.
+ * <p>
+ * Java class for queryVnfNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="queryVnfNotification">
@@ -77,16 +78,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "queryVnfNotification", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage",
- "vnfExists",
- "vnfId",
- "status",
- "outputs"
-})
+@XmlType(name = "queryVnfNotification",
+ propOrder = {"messageId", "completed", "exception", "errorMessage", "vnfExists", "vnfId", "status", "outputs"})
public class QueryVnfNotification {
@XmlElement(required = true)
@@ -102,10 +95,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -114,10 +105,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -142,10 +131,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -154,10 +141,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -166,10 +151,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -178,10 +161,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
@@ -190,10 +171,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the vnfExists property.
*
- * @return
- * possible object is
- * {@link Boolean }
- *
+ * @return possible object is {@link Boolean }
+ *
*/
public Boolean isVnfExists() {
return vnfExists;
@@ -202,10 +181,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the vnfExists property.
*
- * @param value
- * allowed object is
- * {@link Boolean }
- *
+ * @param value allowed object is {@link Boolean }
+ *
*/
public void setVnfExists(Boolean value) {
this.vnfExists = value;
@@ -214,10 +191,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the vnfId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfId() {
return vnfId;
@@ -226,10 +201,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the vnfId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfId(String value) {
this.vnfId = value;
@@ -238,10 +211,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the status property.
*
- * @return
- * possible object is
- * {@link VnfStatus }
- *
+ * @return possible object is {@link VnfStatus }
+ *
*/
public VnfStatus getStatus() {
return status;
@@ -250,10 +221,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the status property.
*
- * @param value
- * allowed object is
- * {@link VnfStatus }
- *
+ * @param value allowed object is {@link VnfStatus }
+ *
*/
public void setStatus(VnfStatus value) {
this.status = value;
@@ -262,10 +231,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the outputs property.
*
- * @return
- * possible object is
- * {@link QueryVnfNotification.Outputs }
- *
+ * @return possible object is {@link QueryVnfNotification.Outputs }
+ *
*/
public QueryVnfNotification.Outputs getOutputs() {
return outputs;
@@ -274,10 +241,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the outputs property.
*
- * @param value
- * allowed object is
- * {@link QueryVnfNotification.Outputs }
- *
+ * @param value allowed object is {@link QueryVnfNotification.Outputs }
+ *
*/
public void setOutputs(QueryVnfNotification.Outputs value) {
this.outputs = value;
@@ -285,9 +250,11 @@ public class QueryVnfNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -315,9 +282,7 @@ public class QueryVnfNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "entry"
- })
+ @XmlType(name = "", propOrder = {"entry"})
public static class Outputs {
protected List<QueryVnfNotification.Outputs.Entry> entry;
@@ -326,21 +291,20 @@ public class QueryVnfNotification {
* Gets the value of the entry property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the entry property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you
+ * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE>
+ * method for the entry property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getEntry().add(newItem);
+ * getEntry().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link QueryVnfNotification.Outputs.Entry }
+ * Objects of the following type(s) are allowed in the list {@link QueryVnfNotification.Outputs.Entry }
*
*
*/
@@ -353,9 +317,11 @@ public class QueryVnfNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -373,10 +339,7 @@ public class QueryVnfNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "key",
- "value"
- })
+ @XmlType(name = "", propOrder = {"key", "value"})
public static class Entry {
protected String key;
@@ -385,10 +348,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the key property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getKey() {
return key;
@@ -397,10 +358,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the key property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setKey(String value) {
this.key = value;
@@ -409,10 +368,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the value property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getValue() {
return value;
@@ -421,10 +378,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the value property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setValue(String value) {
this.value = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/RollbackVnfNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/RollbackVnfNotification.java
index 05947f5e62..e5f8878e84 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/RollbackVnfNotification.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/RollbackVnfNotification.java
@@ -27,9 +27,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for rollbackVnfNotification complex type.
+ * <p>
+ * Java class for rollbackVnfNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="rollbackVnfNotification">
@@ -49,12 +51,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "rollbackVnfNotification", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage"
-})
+@XmlType(name = "rollbackVnfNotification", propOrder = {"messageId", "completed", "exception", "errorMessage"})
public class RollbackVnfNotification {
@XmlElement(required = true)
@@ -66,10 +63,8 @@ public class RollbackVnfNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -78,10 +73,8 @@ public class RollbackVnfNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -106,10 +99,8 @@ public class RollbackVnfNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -118,10 +109,8 @@ public class RollbackVnfNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -130,10 +119,8 @@ public class RollbackVnfNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -142,10 +129,8 @@ public class RollbackVnfNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/UpdateVnfNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/UpdateVnfNotification.java
index 13fa8cb0ef..b738d6dc64 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/UpdateVnfNotification.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/UpdateVnfNotification.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.vnf.async.client;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -30,9 +29,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for updateVnfNotification complex type.
+ * <p>
+ * Java class for updateVnfNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="updateVnfNotification">
@@ -75,14 +76,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "updateVnfNotification", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage",
- "outputs",
- "rollback"
-})
+@XmlType(name = "updateVnfNotification",
+ propOrder = {"messageId", "completed", "exception", "errorMessage", "outputs", "rollback"})
public class UpdateVnfNotification {
@XmlElement(required = true)
@@ -96,10 +91,8 @@ public class UpdateVnfNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -108,10 +101,8 @@ public class UpdateVnfNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -136,10 +127,8 @@ public class UpdateVnfNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -148,10 +137,8 @@ public class UpdateVnfNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -160,10 +147,8 @@ public class UpdateVnfNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -172,10 +157,8 @@ public class UpdateVnfNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
@@ -184,10 +167,8 @@ public class UpdateVnfNotification {
/**
* Gets the value of the outputs property.
*
- * @return
- * possible object is
- * {@link UpdateVnfNotification.Outputs }
- *
+ * @return possible object is {@link UpdateVnfNotification.Outputs }
+ *
*/
public UpdateVnfNotification.Outputs getOutputs() {
return outputs;
@@ -196,10 +177,8 @@ public class UpdateVnfNotification {
/**
* Sets the value of the outputs property.
*
- * @param value
- * allowed object is
- * {@link UpdateVnfNotification.Outputs }
- *
+ * @param value allowed object is {@link UpdateVnfNotification.Outputs }
+ *
*/
public void setOutputs(UpdateVnfNotification.Outputs value) {
this.outputs = value;
@@ -208,10 +187,8 @@ public class UpdateVnfNotification {
/**
* Gets the value of the rollback property.
*
- * @return
- * possible object is
- * {@link VnfRollback }
- *
+ * @return possible object is {@link VnfRollback }
+ *
*/
public VnfRollback getRollback() {
return rollback;
@@ -220,10 +197,8 @@ public class UpdateVnfNotification {
/**
* Sets the value of the rollback property.
*
- * @param value
- * allowed object is
- * {@link VnfRollback }
- *
+ * @param value allowed object is {@link VnfRollback }
+ *
*/
public void setRollback(VnfRollback value) {
this.rollback = value;
@@ -231,9 +206,11 @@ public class UpdateVnfNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -261,9 +238,7 @@ public class UpdateVnfNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "entry"
- })
+ @XmlType(name = "", propOrder = {"entry"})
public static class Outputs {
protected List<UpdateVnfNotification.Outputs.Entry> entry;
@@ -272,21 +247,20 @@ public class UpdateVnfNotification {
* Gets the value of the entry property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the entry property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you
+ * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE>
+ * method for the entry property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getEntry().add(newItem);
+ * getEntry().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link UpdateVnfNotification.Outputs.Entry }
+ * Objects of the following type(s) are allowed in the list {@link UpdateVnfNotification.Outputs.Entry }
*
*
*/
@@ -299,9 +273,11 @@ public class UpdateVnfNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -319,10 +295,7 @@ public class UpdateVnfNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "key",
- "value"
- })
+ @XmlType(name = "", propOrder = {"key", "value"})
public static class Entry {
protected String key;
@@ -331,10 +304,8 @@ public class UpdateVnfNotification {
/**
* Gets the value of the key property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getKey() {
return key;
@@ -343,10 +314,8 @@ public class UpdateVnfNotification {
/**
* Sets the value of the key property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setKey(String value) {
this.key = value;
@@ -355,10 +324,8 @@ public class UpdateVnfNotification {
/**
* Gets the value of the value property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getValue() {
return value;
@@ -367,10 +334,8 @@ public class UpdateVnfNotification {
/**
* Sets the value of the value property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setValue(String value) {
this.value = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify.java
index 24370b4d79..d4bdaa3d34 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify.java
@@ -30,15 +30,11 @@ import javax.xml.ws.RequestWrapper;
/**
- * This class was generated by the JAX-WS RI.
- * JAX-WS RI 2.2.9-b14002
- * Generated source version: 2.2
+ * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.9-b14002 Generated source version: 2.2
*
*/
@WebService(name = "vnfAdapterNotify", targetNamespace = "http://org.onap.so/vnfNotify")
-@XmlSeeAlso({
- ObjectFactory.class
-})
+@XmlSeeAlso({ObjectFactory.class})
public interface VnfAdapterNotify {
@@ -51,17 +47,13 @@ public interface VnfAdapterNotify {
*/
@WebMethod
@Oneway
- @RequestWrapper(localName = "rollbackVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.RollbackVnfNotification")
+ @RequestWrapper(localName = "rollbackVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.RollbackVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/rollbackVnfNotificationRequest")
- public void rollbackVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage);
+ public void rollbackVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage);
/**
*
@@ -76,25 +68,17 @@ public interface VnfAdapterNotify {
*/
@WebMethod
@Oneway
- @RequestWrapper(localName = "queryVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.QueryVnfNotification")
+ @RequestWrapper(localName = "queryVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.QueryVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/queryVnfNotificationRequest")
- public void queryVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "vnfExists", targetNamespace = "")
- Boolean vnfExists,
- @WebParam(name = "vnfId", targetNamespace = "")
- String vnfId,
- @WebParam(name = "status", targetNamespace = "")
- VnfStatus status,
- @WebParam(name = "outputs", targetNamespace = "")
- org.onap.so.adapters.vnf.async.client.QueryVnfNotification.Outputs outputs);
+ public void queryVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "vnfExists", targetNamespace = "") Boolean vnfExists,
+ @WebParam(name = "vnfId", targetNamespace = "") String vnfId,
+ @WebParam(name = "status", targetNamespace = "") VnfStatus status, @WebParam(name = "outputs",
+ targetNamespace = "") org.onap.so.adapters.vnf.async.client.QueryVnfNotification.Outputs outputs);
/**
*
@@ -108,23 +92,17 @@ public interface VnfAdapterNotify {
*/
@WebMethod
@Oneway
- @RequestWrapper(localName = "createVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.CreateVnfNotification")
+ @RequestWrapper(localName = "createVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.CreateVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/createVnfNotificationRequest")
- public void createVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "vnfId", targetNamespace = "")
- String vnfId,
- @WebParam(name = "outputs", targetNamespace = "")
- org.onap.so.adapters.vnf.async.client.CreateVnfNotification.Outputs outputs,
- @WebParam(name = "rollback", targetNamespace = "")
- VnfRollback rollback);
+ public void createVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "vnfId", targetNamespace = "") String vnfId,
+ @WebParam(name = "outputs",
+ targetNamespace = "") org.onap.so.adapters.vnf.async.client.CreateVnfNotification.Outputs outputs,
+ @WebParam(name = "rollback", targetNamespace = "") VnfRollback rollback);
/**
*
@@ -137,21 +115,16 @@ public interface VnfAdapterNotify {
*/
@WebMethod
@Oneway
- @RequestWrapper(localName = "updateVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.UpdateVnfNotification")
+ @RequestWrapper(localName = "updateVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.UpdateVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest")
- public void updateVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "outputs", targetNamespace = "")
- org.onap.so.adapters.vnf.async.client.UpdateVnfNotification.Outputs outputs,
- @WebParam(name = "rollback", targetNamespace = "")
- VnfRollback rollback);
+ public void updateVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "outputs",
+ targetNamespace = "") org.onap.so.adapters.vnf.async.client.UpdateVnfNotification.Outputs outputs,
+ @WebParam(name = "rollback", targetNamespace = "") VnfRollback rollback);
/**
*
@@ -162,16 +135,12 @@ public interface VnfAdapterNotify {
*/
@WebMethod
@Oneway
- @RequestWrapper(localName = "deleteVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.DeleteVnfNotification")
+ @RequestWrapper(localName = "deleteVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.DeleteVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/deleteVnfNotificationRequest")
- public void deleteVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage);
+ public void deleteVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage);
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java
index 4b140b1b30..e1a42706a9 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters.vnf.async.client;
import java.net.URL;
-
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
@@ -31,25 +30,24 @@ import javax.xml.ws.WebServiceFeature;
/**
- * This class was generated by the JAX-WS RI.
- * JAX-WS RI 2.2.9-b14002
- * Generated source version: 2.2
+ * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.9-b14002 Generated source version: 2.2
*
*/
-@WebServiceClient(name = "vnfAdapterNotify", targetNamespace = "http://org.onap.so/vnfNotify", wsdlLocation = "/VnfAdapterNotify.wsdl")
-public class VnfAdapterNotify_Service
- extends Service
-{
+@WebServiceClient(name = "vnfAdapterNotify", targetNamespace = "http://org.onap.so/vnfNotify",
+ wsdlLocation = "/VnfAdapterNotify.wsdl")
+public class VnfAdapterNotify_Service extends Service {
private final static URL VNFADAPTERNOTIFY_WSDL_LOCATION;
private final static WebServiceException VNFADAPTERNOTIFY_EXCEPTION;
private final static QName VNFADAPTERNOTIFY_QNAME = new QName("http://org.onap.so/vnfNotify", "vnfAdapterNotify");
static {
- VNFADAPTERNOTIFY_WSDL_LOCATION = org.onap.so.adapters.vnf.async.client.VnfAdapterNotify_Service.class.getResource("/VnfAdapterNotify.wsdl");
+ VNFADAPTERNOTIFY_WSDL_LOCATION = org.onap.so.adapters.vnf.async.client.VnfAdapterNotify_Service.class
+ .getResource("/VnfAdapterNotify.wsdl");
WebServiceException e = null;
if (VNFADAPTERNOTIFY_WSDL_LOCATION == null) {
- e = new WebServiceException("Cannot find '/VnfAdapterNotify.wsdl' wsdl. Place the resource correctly in the classpath.");
+ e = new WebServiceException(
+ "Cannot find '/VnfAdapterNotify.wsdl' wsdl. Place the resource correctly in the classpath.");
}
VNFADAPTERNOTIFY_EXCEPTION = e;
}
@@ -80,28 +78,28 @@ public class VnfAdapterNotify_Service
/**
*
- * @return
- * returns VnfAdapterNotify
+ * @return returns VnfAdapterNotify
*/
@WebEndpoint(name = "MsoVnfAdapterAsyncImplPort")
public VnfAdapterNotify getMsoVnfAdapterAsyncImplPort() {
- return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"), VnfAdapterNotify.class);
+ return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"),
+ VnfAdapterNotify.class);
}
/**
*
- * @param features
- * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
- * @return
- * returns VnfAdapterNotify
+ * @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features
+ * not in the <code>features</code> parameter will have their default values.
+ * @return returns VnfAdapterNotify
*/
@WebEndpoint(name = "MsoVnfAdapterAsyncImplPort")
public VnfAdapterNotify getMsoVnfAdapterAsyncImplPort(WebServiceFeature... features) {
- return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"), VnfAdapterNotify.class, features);
+ return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"),
+ VnfAdapterNotify.class, features);
}
private static URL __getWsdlLocation() {
- if (VNFADAPTERNOTIFY_EXCEPTION!= null) {
+ if (VNFADAPTERNOTIFY_EXCEPTION != null) {
throw VNFADAPTERNOTIFY_EXCEPTION;
}
return VNFADAPTERNOTIFY_WSDL_LOCATION;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfRollback.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfRollback.java
index 9ad20738d0..7d8b4d1b41 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfRollback.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfRollback.java
@@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for vnfRollback complex type.
+ * <p>
+ * Java class for vnfRollback complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="vnfRollback">
@@ -50,14 +52,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "vnfRollback", propOrder = {
- "cloudSiteId",
- "msoRequest",
- "tenantCreated",
- "tenantId",
- "vnfCreated",
- "vnfId"
-})
+@XmlType(name = "vnfRollback",
+ propOrder = {"cloudSiteId", "msoRequest", "tenantCreated", "tenantId", "vnfCreated", "vnfId"})
public class VnfRollback {
protected String cloudSiteId;
@@ -70,10 +66,8 @@ public class VnfRollback {
/**
* Gets the value of the cloudSiteId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getCloudSiteId() {
return cloudSiteId;
@@ -82,10 +76,8 @@ public class VnfRollback {
/**
* Sets the value of the cloudSiteId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setCloudSiteId(String value) {
this.cloudSiteId = value;
@@ -94,10 +86,8 @@ public class VnfRollback {
/**
* Gets the value of the msoRequest property.
*
- * @return
- * possible object is
- * {@link MsoRequest }
- *
+ * @return possible object is {@link MsoRequest }
+ *
*/
public MsoRequest getMsoRequest() {
return msoRequest;
@@ -106,10 +96,8 @@ public class VnfRollback {
/**
* Sets the value of the msoRequest property.
*
- * @param value
- * allowed object is
- * {@link MsoRequest }
- *
+ * @param value allowed object is {@link MsoRequest }
+ *
*/
public void setMsoRequest(MsoRequest value) {
this.msoRequest = value;
@@ -134,10 +122,8 @@ public class VnfRollback {
/**
* Gets the value of the tenantId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getTenantId() {
return tenantId;
@@ -146,10 +132,8 @@ public class VnfRollback {
/**
* Sets the value of the tenantId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setTenantId(String value) {
this.tenantId = value;
@@ -174,10 +158,8 @@ public class VnfRollback {
/**
* Gets the value of the vnfId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfId() {
return vnfId;
@@ -186,10 +168,8 @@ public class VnfRollback {
/**
* Sets the value of the vnfId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfId(String value) {
this.vnfId = value;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfStatus.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfStatus.java
index 1998ae0ce9..767777767c 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfStatus.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfStatus.java
@@ -25,10 +25,13 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for vnfStatus.
+ * <p>
+ * Java class for vnfStatus.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
* <p>
+ * The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ *
* <pre>
* &lt;simpleType name="vnfStatus">
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
@@ -45,10 +48,7 @@ import javax.xml.bind.annotation.XmlType;
@XmlEnum
public enum VnfStatus {
- ACTIVE,
- FAILED,
- NOTFOUND,
- UNKNOWN;
+ ACTIVE, FAILED, NOTFOUND, UNKNOWN;
public String value() {
return name();
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfAlreadyExists.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfAlreadyExists.java
index 38283aa17b..31ad3f4fc3 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfAlreadyExists.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfAlreadyExists.java
@@ -25,18 +25,19 @@ package org.onap.so.adapters.vnf.exceptions;
import javax.xml.ws.WebFault;
/**
- * This class reports an exception when trying to create a VNF when another
- * VNF of the same name already exists in the target cloud/tenant. Note that
- * the createVnf method suppresses this exception by default.
+ * This class reports an exception when trying to create a VNF when another VNF of the same name already exists in the
+ * target cloud/tenant. Note that the createVnf method suppresses this exception by default.
*
*
*/
-@WebFault (name="VnfAlreadyExists", faultBean="org.onap.so.adapters.vnf.exceptions.VnfExceptionBean", targetNamespace="http://org.onap.so/vnf")
+@WebFault(name = "VnfAlreadyExists", faultBean = "org.onap.so.adapters.vnf.exceptions.VnfExceptionBean",
+ targetNamespace = "http://org.onap.so/vnf")
public class VnfAlreadyExists extends VnfException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- public VnfAlreadyExists (String name, String cloudId, String cloudOwner, String tenantId, String vnfId) {
- super("Resource " + name + " already exists in owner/cloud/tenant " + cloudOwner + "/" + cloudId + "/" + tenantId + " with ID " + vnfId);
- }
+ public VnfAlreadyExists(String name, String cloudId, String cloudOwner, String tenantId, String vnfId) {
+ super("Resource " + name + " already exists in owner/cloud/tenant " + cloudOwner + "/" + cloudId + "/"
+ + tenantId + " with ID " + vnfId);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfException.java
index 39f48e64dd..c5dd92eda9 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfException.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfException.java
@@ -23,58 +23,58 @@ package org.onap.so.adapters.vnf.exceptions;
import javax.xml.ws.WebFault;
-
import org.onap.so.openstack.exceptions.MsoException;
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
/**
- * This class simply extends Exception (without addition additional functionality)
- * to provide an identifier for VNF related exceptions on create, delete, query.
+ * This class simply extends Exception (without addition additional functionality) to provide an identifier for VNF
+ * related exceptions on create, delete, query.
*
*
*/
-@WebFault (name="VnfException", faultBean="org.onap.so.adapters.vnf.exceptions.VnfExceptionBean", targetNamespace="http://org.onap.so/vnf")
+@WebFault(name = "VnfException", faultBean = "org.onap.so.adapters.vnf.exceptions.VnfExceptionBean",
+ targetNamespace = "http://org.onap.so/vnf")
public class VnfException extends Exception {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
+
+ private VnfExceptionBean faultInfo;
+
+ public VnfException(String msg) {
+ super(msg);
+ faultInfo = new VnfExceptionBean(msg);
+ }
+
+ public VnfException(Throwable e) {
+ super(e);
+ faultInfo = new VnfExceptionBean(e.getMessage());
+ }
+
+ public VnfException(String msg, Throwable e) {
+ super(msg, e);
+ faultInfo = new VnfExceptionBean(msg);
+ }
+
+ public VnfException(String msg, MsoExceptionCategory category) {
+ super(msg);
+ faultInfo = new VnfExceptionBean(msg, category);
+ }
+
+ public VnfException(String msg, MsoExceptionCategory category, Throwable e) {
+ super(msg, e);
+ faultInfo = new VnfExceptionBean(msg, category);
+ }
- private VnfExceptionBean faultInfo;
-
- public VnfException (String msg) {
- super(msg);
- faultInfo = new VnfExceptionBean (msg);
- }
-
- public VnfException (Throwable e) {
- super(e);
- faultInfo = new VnfExceptionBean (e.getMessage());
- }
-
- public VnfException (String msg, Throwable e) {
- super (msg, e);
- faultInfo = new VnfExceptionBean (msg);
- }
+ public VnfException(MsoException e) {
+ super(e);
+ faultInfo = new VnfExceptionBean(e.getContextMessage(), e.getCategory());
+ }
- public VnfException (String msg, MsoExceptionCategory category) {
- super(msg);
- faultInfo = new VnfExceptionBean (msg, category);
- }
-
- public VnfException (String msg, MsoExceptionCategory category, Throwable e) {
- super (msg, e);
- faultInfo = new VnfExceptionBean (msg, category);
- }
-
- public VnfException (MsoException e) {
- super (e);
- faultInfo = new VnfExceptionBean (e.getContextMessage(), e.getCategory());
- }
-
- public VnfExceptionBean getFaultInfo() {
- return faultInfo;
- }
+ public VnfExceptionBean getFaultInfo() {
+ return faultInfo;
+ }
- public void setFaultInfo(VnfExceptionBean faultInfo) {
- this.faultInfo = faultInfo;
- }
+ public void setFaultInfo(VnfExceptionBean faultInfo) {
+ this.faultInfo = faultInfo;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfExceptionBean.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfExceptionBean.java
index 011afa72ee..30e9fa590c 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfExceptionBean.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfExceptionBean.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.vnf.exceptions;
import java.io.Serializable;
-
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
/**
@@ -33,42 +32,42 @@ public class VnfExceptionBean implements Serializable {
private static final long serialVersionUID = -5699310749783790095L;
private String message;
- private MsoExceptionCategory category;
- private Boolean rolledBack;
+ private MsoExceptionCategory category;
+ private Boolean rolledBack;
- public VnfExceptionBean () {}
+ public VnfExceptionBean() {}
- public VnfExceptionBean (String message) {
- // Create a default category to prevent null pointer exceptions
- this(message, MsoExceptionCategory.INTERNAL);
- }
+ public VnfExceptionBean(String message) {
+ // Create a default category to prevent null pointer exceptions
+ this(message, MsoExceptionCategory.INTERNAL);
+ }
- public VnfExceptionBean (String message, MsoExceptionCategory category) {
- this.message = message;
- this.category = category;
- }
+ public VnfExceptionBean(String message, MsoExceptionCategory category) {
+ this.message = message;
+ this.category = category;
+ }
- public String getMessage() {
- return message;
- }
+ public String getMessage() {
+ return message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public MsoExceptionCategory getCategory () {
- return category;
- }
+ public MsoExceptionCategory getCategory() {
+ return category;
+ }
- public void setCategory (MsoExceptionCategory category) {
- this.category = category;
- }
+ public void setCategory(MsoExceptionCategory category) {
+ this.category = category;
+ }
- public Boolean isRolledBack() {
- return rolledBack;
- }
+ public Boolean isRolledBack() {
+ return rolledBack;
+ }
- public void setRolledBack(Boolean rolledBack) {
- this.rolledBack = rolledBack;
- }
+ public void setRolledBack(Boolean rolledBack) {
+ this.rolledBack = rolledBack;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfNotFound.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfNotFound.java
index 18d622453b..4220d389c5 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfNotFound.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfNotFound.java
@@ -24,18 +24,19 @@ package org.onap.so.adapters.vnf.exceptions;
import javax.xml.ws.WebFault;
/**
- * This class reports an exception when trying to update a Network that does
- * not exist in the target cloud/tenant. Note that deleteNetwork suppresses
- * this exception (deletion of non-existent network is considered a success).
+ * This class reports an exception when trying to update a Network that does not exist in the target cloud/tenant. Note
+ * that deleteNetwork suppresses this exception (deletion of non-existent network is considered a success).
*
*
*/
-@WebFault (name="VnfNotFound", faultBean="org.onap.so.adapters.vnf.exceptions.VnfExceptionBean", targetNamespace="http://org.onap.so/vnf")
+@WebFault(name = "VnfNotFound", faultBean = "org.onap.so.adapters.vnf.exceptions.VnfExceptionBean",
+ targetNamespace = "http://org.onap.so/vnf")
public class VnfNotFound extends VnfException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- public VnfNotFound (String cloudId, String cloudOwner, String tenantId, String vnfName) {
- super("Resource " + vnfName + " not found in owner/cloud/tenant " + cloudOwner + "/" + cloudId + "/" + tenantId);
- }
+ public VnfNotFound(String cloudId, String cloudOwner, String tenantId, String vnfName) {
+ super("Resource " + vnfName + " not found in owner/cloud/tenant " + cloudOwner + "/" + cloudId + "/"
+ + tenantId);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java
index 6b06761474..c6fd73d9cb 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java
@@ -1,17 +1,14 @@
/*
* Copyright (C) 2018 Bell Canada. All rights reserved.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
*/
package org.onap.so.heatbridge;
@@ -23,8 +20,8 @@ import org.openstack4j.model.compute.Server;
import org.openstack4j.model.heat.Resource;
/**
- * Defines the contract to extract Heat Stack Resources from Openstack and inventory it to AAI.
- * This API is used only to "create" objects in AAI.
+ * Defines the contract to extract Heat Stack Resources from Openstack and inventory it to AAI. This API is used only to
+ * "create" objects in AAI.
*/
public interface HeatBridgeApi {
@@ -54,8 +51,9 @@ public interface HeatBridgeApi {
List<String> extractStackResourceIdsByResourceType(List<Resource> stackResources, String resourceType);
/**
- * Get network IDs for a given list of network names.
- * It is assumed that there is a one to one mapping between the name and ID.
+ * Get network IDs for a given list of network names. It is assumed that there is a one to one mapping between the
+ * name and ID.
+ *
* @param networkNameList List of network names
* @return List of matching network IDs
*/
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java
index f993d71e4c..9bf2ec73f4 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java
@@ -1,17 +1,14 @@
/*
* Copyright (C) 2018 Bell Canada. All rights reserved.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
*/
package org.onap.so.heatbridge;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java
index 90ceeb7d1c..a5e6a4558f 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java
@@ -1,17 +1,14 @@
/*
* Copyright (C) 2018 Bell Canada. All rights reserved.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
*/
package org.onap.so.heatbridge;
@@ -23,10 +20,8 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
-
import javax.annotation.Nonnull;
import javax.ws.rs.WebApplicationException;
-
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.validator.routines.InetAddressValidator;
import org.onap.aai.domain.yang.Flavor;
@@ -65,7 +60,6 @@ import org.openstack4j.model.network.IP;
import org.openstack4j.model.network.Network;
import org.openstack4j.model.network.NetworkType;
import org.openstack4j.model.network.Port;
-
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
@@ -76,7 +70,8 @@ import com.google.common.collect.ImmutableMap;
public class HeatBridgeImpl implements HeatBridgeApi {
private static final Logger logger = LoggerFactory.getLogger(HeatBridgeImpl.class);
- private static final String ERR_MSG_NULL_OS_CLIENT = "Initialization error: Null openstack client. Authenticate with Keystone first.";
+ private static final String ERR_MSG_NULL_OS_CLIENT =
+ "Initialization error: Null openstack client. Authenticate with Keystone first.";
private static final String OOB_MGT_NETWORK_IDENTIFIER = "Management";
private OpenstackClient osClient;
private AAIResourcesClient resourcesClient;
@@ -89,7 +84,7 @@ public class HeatBridgeImpl implements HeatBridgeApi {
public HeatBridgeImpl(AAIResourcesClient resourcesClient, final CloudIdentity cloudIdentity,
- @Nonnull final String cloudOwner, @Nonnull final String cloudRegionId, @Nonnull final String tenantId) {
+ @Nonnull final String cloudOwner, @Nonnull final String cloudRegionId, @Nonnull final String tenantId) {
Objects.requireNonNull(cloudOwner, "Null cloud-owner value!");
Objects.requireNonNull(cloudRegionId, "Null cloud-region identifier!");
Objects.requireNonNull(tenantId, "Null tenant identifier!");
@@ -105,10 +100,11 @@ public class HeatBridgeImpl implements HeatBridgeApi {
@Override
public OpenstackClient authenticate() throws HeatBridgeException {
- this.osClient = new MsoCloudClientFactoryImpl(new OpenstackClientFactoryImpl())
- .getOpenstackClient(cloudIdentity.getIdentityUrl(), cloudIdentity.getMsoId(), cloudIdentity.getMsoPass(), cloudRegionId, tenantId);
- logger.debug("Successfully authenticated with keystone for tenant: " + tenantId + " and cloud "
- + "region: " + cloudRegionId);
+ this.osClient = new MsoCloudClientFactoryImpl(new OpenstackClientFactoryImpl()).getOpenstackClient(
+ cloudIdentity.getIdentityUrl(), cloudIdentity.getMsoId(), cloudIdentity.getMsoPass(), cloudRegionId,
+ tenantId);
+ logger.debug("Successfully authenticated with keystone for tenant: " + tenantId + " and cloud " + "region: "
+ + cloudRegionId);
return osClient;
}
@@ -116,29 +112,27 @@ public class HeatBridgeImpl implements HeatBridgeApi {
public List<Resource> queryNestedHeatStackResources(final String heatStackId) {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
Preconditions.checkState(!Strings.isNullOrEmpty(heatStackId), "Invalid heatStackId!");
- List<Resource> stackBasedResources = osClient
- .getStackBasedResources(heatStackId, HeatBridgeConstants.OS_DEFAULT_HEAT_NESTING);
+ List<Resource> stackBasedResources =
+ osClient.getStackBasedResources(heatStackId, HeatBridgeConstants.OS_DEFAULT_HEAT_NESTING);
logger.debug(stackBasedResources.size() + " heat stack resources are extracted for stack: " + heatStackId);
return stackBasedResources;
}
@Override
public List<String> extractStackResourceIdsByResourceType(final List<Resource> stackResources,
- final String resourceType) {
- return stackResources.stream()
- .filter(stackResource -> stackResource.getType().equals(resourceType))
- .map(Resource::getPhysicalResourceId)
- .collect(Collectors.toList());
+ final String resourceType) {
+ return stackResources.stream().filter(stackResource -> stackResource.getType().equals(resourceType))
+ .map(Resource::getPhysicalResourceId).collect(Collectors.toList());
}
@Override
public List<String> extractNetworkIds(final List<String> networkNameList) {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
return networkNameList.stream()
- .map(netName -> osClient.listNetworksByFilter(ImmutableMap.of(HeatBridgeConstants.OS_NAME_KEY, netName)))
- .filter(nets -> nets != null && nets.size() == 1) //extract network-id only if network-name is unique
- .map(nets -> nets.get(0).getId())
- .collect(Collectors.toList());
+ .map(netName -> osClient
+ .listNetworksByFilter(ImmutableMap.of(HeatBridgeConstants.OS_NAME_KEY, netName)))
+ .filter(nets -> nets != null && nets.size() == 1) // extract network-id only if network-name is unique
+ .map(nets -> nets.get(0).getId()).collect(Collectors.toList());
}
@Override
@@ -146,8 +140,8 @@ public class HeatBridgeImpl implements HeatBridgeApi {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
// Filter Openstack Compute resources
- List<String> serverIds = extractStackResourceIdsByResourceType(stackResources,
- HeatBridgeConstants.OS_SERVER_RESOURCE_TYPE);
+ List<String> serverIds =
+ extractStackResourceIdsByResourceType(stackResources, HeatBridgeConstants.OS_SERVER_RESOURCE_TYPE);
return serverIds.stream().map(serverId -> osClient.getServerById(serverId)).collect(Collectors.toList());
}
@@ -155,23 +149,24 @@ public class HeatBridgeImpl implements HeatBridgeApi {
public List<org.openstack4j.model.compute.Image> extractOpenstackImagesFromServers(final List<Server> servers) {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
return servers.stream().map(Server::getImage)
- .filter(distinctByProperty(org.openstack4j.model.compute.Image::getId)).collect(Collectors.toList());
+ .filter(distinctByProperty(org.openstack4j.model.compute.Image::getId)).collect(Collectors.toList());
}
@Override
public List<org.openstack4j.model.compute.Flavor> extractOpenstackFlavorsFromServers(final List<Server> servers) {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
return servers.stream().map(Server::getFlavor)
- .filter(distinctByProperty(org.openstack4j.model.compute.Flavor::getId)).collect(Collectors.toList());
+ .filter(distinctByProperty(org.openstack4j.model.compute.Flavor::getId)).collect(Collectors.toList());
}
@Override
public void buildAddImagesToAaiAction(final List<org.openstack4j.model.compute.Image> images)
- throws HeatBridgeException {
+ throws HeatBridgeException {
for (org.openstack4j.model.compute.Image image : images) {
Image aaiImage = aaiHelper.buildImage(image);
try {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.IMAGE, cloudOwner, cloudRegionId, aaiImage.getImageId());
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.IMAGE, cloudOwner, cloudRegionId,
+ aaiImage.getImageId());
if (!resourcesClient.exists(uri)) {
transaction.create(uri, aaiImage);
logger.debug("Queuing AAI command to add image: " + aaiImage.getImageId());
@@ -179,19 +174,20 @@ public class HeatBridgeImpl implements HeatBridgeApi {
logger.debug("Nothing to add since image: " + aaiImage.getImageId() + "already exists in AAI.");
}
} catch (WebApplicationException e) {
- throw new HeatBridgeException("Failed to update image to AAI: " + aaiImage.getImageId() + ". Error"
- + " cause: " + e, e);
+ throw new HeatBridgeException(
+ "Failed to update image to AAI: " + aaiImage.getImageId() + ". Error" + " cause: " + e, e);
}
}
}
@Override
public void buildAddFlavorsToAaiAction(final List<org.openstack4j.model.compute.Flavor> flavors)
- throws HeatBridgeException {
+ throws HeatBridgeException {
for (org.openstack4j.model.compute.Flavor flavor : flavors) {
Flavor aaiFlavor = aaiHelper.buildFlavor(flavor);
try {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.FLAVOR, cloudOwner, cloudRegionId, aaiFlavor.getFlavorId());
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.FLAVOR, cloudOwner, cloudRegionId,
+ aaiFlavor.getFlavorId());
if (!resourcesClient.exists(uri)) {
transaction.create(uri, aaiFlavor);
logger.debug("Queuing AAI command to add flavor: " + aaiFlavor.getFlavorId());
@@ -199,31 +195,32 @@ public class HeatBridgeImpl implements HeatBridgeApi {
logger.debug("Nothing to add since flavor: " + aaiFlavor.getFlavorId() + "already exists in AAI.");
}
} catch (WebApplicationException e) {
- throw new HeatBridgeException("Failed to update flavor to AAI: " + aaiFlavor.getFlavorId() + ". Error"
- + " cause: " + e, e);
+ throw new HeatBridgeException(
+ "Failed to update flavor to AAI: " + aaiFlavor.getFlavorId() + ". Error" + " cause: " + e, e);
}
}
}
@Override
public void buildAddVserversToAaiAction(final String genericVnfId, final String vfModuleId,
- final List<Server> servers) {
+ final List<Server> servers) {
servers.forEach(server -> {
Vserver vserver = aaiHelper.buildVserver(server.getId(), server);
// Build vserver relationships to: image, flavor, pserver, vf-module
- vserver.setRelationshipList(aaiHelper.getVserverRelationshipList(cloudOwner, cloudRegionId, genericVnfId,
- vfModuleId, server));
- transaction.create(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegionId, tenantId, vserver.getVserverId()), vserver);
+ vserver.setRelationshipList(
+ aaiHelper.getVserverRelationshipList(cloudOwner, cloudRegionId, genericVnfId, vfModuleId, server));
+ transaction.create(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegionId,
+ tenantId, vserver.getVserverId()), vserver);
});
}
@Override
public void buildAddVserverLInterfacesToAaiAction(final List<Resource> stackResources,
- final List<String> oobMgtNetIds) {
+ final List<String> oobMgtNetIds) {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
- List<String> portIds = extractStackResourceIdsByResourceType(stackResources,
- HeatBridgeConstants.OS_PORT_RESOURCE_TYPE);
+ List<String> portIds =
+ extractStackResourceIdsByResourceType(stackResources, HeatBridgeConstants.OS_PORT_RESOURCE_TYPE);
for (String portId : portIds) {
Port port = osClient.getPortById(portId);
LInterface lIf = new LInterface();
@@ -240,8 +237,8 @@ public class HeatBridgeImpl implements HeatBridgeApi {
updateLInterfaceVlan(port, lIf);
// Update l-interface to the vserver
- transaction.create(AAIUriFactory.createResourceUri(
- AAIObjectType.L_INTERFACE, cloudOwner, cloudRegionId, tenantId, port.getDeviceId(), lIf.getInterfaceName()), lIf);
+ transaction.create(AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, cloudRegionId,
+ tenantId, port.getDeviceId(), lIf.getInterfaceName()), lIf);
}
}
@@ -278,56 +275,57 @@ public class HeatBridgeImpl implements HeatBridgeApi {
}
/**
- * Needs to be corrected according to the specification that is in draft
- * If pserver/p-interface does not have a SRIOV-PF object matching the PCI-ID of the Openstack port object, then
- * create it in AAI.
- * Openstack SRIOV Port object has pci-id (to match sriov-pf on pserver/p-interface), physical-network ID (that
- * matches the p-interface name).
+ * Needs to be corrected according to the specification that is in draft If pserver/p-interface does not have a
+ * SRIOV-PF object matching the PCI-ID of the Openstack port object, then create it in AAI. Openstack SRIOV Port
+ * object has pci-id (to match sriov-pf on pserver/p-interface), physical-network ID (that matches the p-interface
+ * name).
*
* @param port Openstack port object
* @param lIf AAI l-interface object
*/
private void updateSriovPfToPserver(final Port port, final LInterface lIf) {
if (port.getProfile() == null || Strings
- .isNullOrEmpty(port.getProfile().get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString())) {
+ .isNullOrEmpty(port.getProfile().get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString())) {
logger.debug("The SRIOV port:" + port.getName() + " is missing physical-network-id, cannot update "
- + "sriov-pf object for host pserver: " + port.getHostId());
+ + "sriov-pf object for host pserver: " + port.getHostId());
return;
}
- Optional<String> matchingPifName = HeatBridgeUtils
- .getMatchingPserverPifName(port.getProfile().get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString());
+ Optional<String> matchingPifName = HeatBridgeUtils.getMatchingPserverPifName(
+ port.getProfile().get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString());
if (matchingPifName.isPresent()) {
// Update l-interface description
String pserverHostName = port.getHostId();
- lIf.setInterfaceDescription(
- "Attached to SR-IOV port: " + pserverHostName + "::" + matchingPifName.get());
+ lIf.setInterfaceDescription("Attached to SR-IOV port: " + pserverHostName + "::" + matchingPifName.get());
try {
- Optional<PInterface> matchingPIf = resourcesClient.get(PInterface.class,
- AAIUriFactory.createResourceUri(AAIObjectType.P_INTERFACE, pserverHostName, matchingPifName.get()).depth(Depth.ONE));
+ Optional<PInterface> matchingPIf = resourcesClient.get(PInterface.class,
+ AAIUriFactory
+ .createResourceUri(AAIObjectType.P_INTERFACE, pserverHostName, matchingPifName.get())
+ .depth(Depth.ONE));
if (matchingPIf.isPresent()) {
- SriovPfs pIfSriovPfs = matchingPIf.get().getSriovPfs();
+ SriovPfs pIfSriovPfs = matchingPIf.get().getSriovPfs();
if (pIfSriovPfs == null) {
pIfSriovPfs = new SriovPfs();
}
// Extract PCI-ID from OS port object
String pfPciId = port.getProfile().get(HeatBridgeConstants.OS_PCI_SLOT_KEY).toString();
-
+
List<SriovPf> existingSriovPfs = pIfSriovPfs.getSriovPf();
if (CollectionUtils.isEmpty(existingSriovPfs) || existingSriovPfs.stream()
- .noneMatch(existingSriovPf -> existingSriovPf.getPfPciId().equals(pfPciId))) {
+ .noneMatch(existingSriovPf -> existingSriovPf.getPfPciId().equals(pfPciId))) {
// Add sriov-pf object with PCI-ID to AAI
SriovPf sriovPf = new SriovPf();
sriovPf.setPfPciId(pfPciId);
- logger.debug("Queuing AAI command to update sriov-pf object to pserver: " + pserverHostName + "/" +
- matchingPifName.get());
- transaction.create(AAIUriFactory.createResourceUri(
- AAIObjectType.SRIOV_PF, pserverHostName, matchingPifName.get(), sriovPf.getPfPciId()), sriovPf);
+ logger.debug("Queuing AAI command to update sriov-pf object to pserver: " + pserverHostName
+ + "/" + matchingPifName.get());
+ transaction.create(AAIUriFactory.createResourceUri(AAIObjectType.SRIOV_PF, pserverHostName,
+ matchingPifName.get(), sriovPf.getPfPciId()), sriovPf);
}
}
} catch (WebApplicationException e) {
// Silently log that we failed to update the Pserver p-interface with PCI-ID
- logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.GENERAL_EXCEPTION, pserverHostName, matchingPifName.get(), cloudOwner,
- tenantId, "OpenStack", "Heatbridge", ErrorCode.DataError.getValue(), "Exception - Failed to add sriov-pf object to pserver", e);
+ logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.GENERAL_EXCEPTION, pserverHostName,
+ matchingPifName.get(), cloudOwner, tenantId, "OpenStack", "Heatbridge",
+ ErrorCode.DataError.getValue(), "Exception - Failed to add sriov-pf object to pserver", e);
}
}
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java
index 1f302341ad..dd64d53732 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java
@@ -1,17 +1,14 @@
/*
* Copyright (C) 2018 Bell Canada. All rights reserved.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
*/
package org.onap.so.heatbridge.constants;
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java
index 100b50e502..edf5e2d339 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java
@@ -1,17 +1,14 @@
/*
* Copyright (C) 2018 Bell Canada. All rights reserved.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
*/
package org.onap.so.heatbridge.factory;
@@ -37,5 +34,6 @@ public interface MsoCloudClientFactory {
*/
- OpenstackClient getOpenstackClient(String url, String msoId, String msoPass, String cloudRegionId, String tenantId) throws HeatBridgeException;
+ OpenstackClient getOpenstackClient(String url, String msoId, String msoPass, String cloudRegionId, String tenantId)
+ throws HeatBridgeException;
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java
index b70b32a4d6..bd74bf6aa0 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java
@@ -1,17 +1,14 @@
/*
* Copyright (C) 2018 Bell Canada. All rights reserved.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
*/
package org.onap.so.heatbridge.factory;
@@ -29,10 +26,9 @@ import org.onap.so.heatbridge.openstack.factory.OpenstackClientFactory;
import org.onap.so.utils.CryptoUtils;
/**
- * This class implements {@link MsoCloudClientFactory}
- * It loads the cloud configuration from SO and uses it to authenticate with keystone.
- * As a result of authentication with keystone, it returns the Openstack client with the auth token so that
- * subsequent API calls to Openstack can be made.
+ * This class implements {@link MsoCloudClientFactory} It loads the cloud configuration from SO and uses it to
+ * authenticate with keystone. As a result of authentication with keystone, it returns the Openstack client with the
+ * auth token so that subsequent API calls to Openstack can be made.
*/
public class MsoCloudClientFactoryImpl implements MsoCloudClientFactory {
@@ -42,23 +38,23 @@ public class MsoCloudClientFactoryImpl implements MsoCloudClientFactory {
Objects.requireNonNull(openstackClientFactory, "Null OpenstackClientFactory object");
this.openstackClientFactory = openstackClientFactory;
}
+
@Override
- public OpenstackClient getOpenstackClient(@Nonnull String url, @Nonnull String msoId, @Nonnull String msoPass, @Nonnull String cloudRegionId, @Nonnull String tenantId) throws
- HeatBridgeException {
+ public OpenstackClient getOpenstackClient(@Nonnull String url, @Nonnull String msoId, @Nonnull String msoPass,
+ @Nonnull String cloudRegionId, @Nonnull String tenantId) throws HeatBridgeException {
Objects.requireNonNull(url, "Null openstack url!");
Objects.requireNonNull(msoId, "Null openstack user id!");
Objects.requireNonNull(msoPass, "Null openstack password!");
Objects.requireNonNull(cloudRegionId, "Null cloud-region ID!");
Objects.requireNonNull(tenantId, "Null tenant ID!");
try {
- final OpenstackAccess osAccess = new OpenstackAccessBuilder()
- .setBaseUrl(url) // keystone URL
- .setUser(msoId) // keystone username
- .setPassword(CryptoUtils.decryptCloudConfigPassword(msoPass)) // keystone decrypted password
- .setRegion(cloudRegionId) // openstack region
- .setDomainName(HeatBridgeConstants.OS_DEFAULT_DOMAIN_NAME) // hardcode to "default"
- .setTenantId(tenantId) // tenantId
- .build();
+ final OpenstackAccess osAccess = new OpenstackAccessBuilder().setBaseUrl(url) // keystone URL
+ .setUser(msoId) // keystone username
+ .setPassword(CryptoUtils.decryptCloudConfigPassword(msoPass)) // keystone decrypted password
+ .setRegion(cloudRegionId) // openstack region
+ .setDomainName(HeatBridgeConstants.OS_DEFAULT_DOMAIN_NAME) // hardcode to "default"
+ .setTenantId(tenantId) // tenantId
+ .build();
// Identify the Keystone version
String version = new URL(url).getPath().replace("/", "");
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java
index a0f1f0798f..515f2dc0e5 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java
@@ -1,17 +1,14 @@
/*
* Copyright (C) 2018 Bell Canada.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
*/
package org.onap.so.heatbridge.helpers;
@@ -49,58 +46,49 @@ public class AaiHelper {
* @param vfModuleId AAI vf-module identifier
* @param server Openstack Server object
*/
- public RelationshipList getVserverRelationshipList(final String cloudOwner, final String cloudRegionId, final String
- genericVnfId, final String vfModuleId, final Server server) {
+ public RelationshipList getVserverRelationshipList(final String cloudOwner, final String cloudRegionId,
+ final String genericVnfId, final String vfModuleId, final Server server) {
RelationshipList relationshipList = new RelationshipList();
List<Relationship> relationships = relationshipList.getRelationship();
// vserver to pserver relationship
- Relationship pserverRelationship = buildRelationship(HeatBridgeConstants.AAI_PSERVER,
- ImmutableMap.<String, String>builder()
- .put(HeatBridgeConstants.AAI_PSERVER_HOSTNAME, server.getHypervisorHostname())
- .build());
+ Relationship pserverRelationship =
+ buildRelationship(HeatBridgeConstants.AAI_PSERVER, ImmutableMap.<String, String>builder()
+ .put(HeatBridgeConstants.AAI_PSERVER_HOSTNAME, server.getHypervisorHostname()).build());
relationships.add(pserverRelationship);
// vserver to vf-module relationship
Relationship vfModuleRelationship = buildRelationship(HeatBridgeConstants.AAI_VF_MODULE,
- ImmutableMap.<String, String>builder()
- .put(HeatBridgeConstants.AAI_GENERIC_VNF_ID, genericVnfId)
- .put(HeatBridgeConstants.AAI_VF_MODULE_ID, vfModuleId)
- .build());
+ ImmutableMap.<String, String>builder().put(HeatBridgeConstants.AAI_GENERIC_VNF_ID, genericVnfId)
+ .put(HeatBridgeConstants.AAI_VF_MODULE_ID, vfModuleId).build());
relationships.add(vfModuleRelationship);
// vserver to image relationship
Relationship imageRel = buildRelationship(HeatBridgeConstants.AAI_IMAGE,
- ImmutableMap.<String, String>builder()
- .put(HeatBridgeConstants.AAI_CLOUD_OWNER, cloudOwner)
- .put(HeatBridgeConstants.AAI_CLOUD_REGION_ID, cloudRegionId)
- .put(HeatBridgeConstants.AAI_IMAGE_ID, server.getImage().getId())
- .build());
+ ImmutableMap.<String, String>builder().put(HeatBridgeConstants.AAI_CLOUD_OWNER, cloudOwner)
+ .put(HeatBridgeConstants.AAI_CLOUD_REGION_ID, cloudRegionId)
+ .put(HeatBridgeConstants.AAI_IMAGE_ID, server.getImage().getId()).build());
relationships.add(imageRel);
// vserver to flavor relationship
Relationship flavorRel = buildRelationship(HeatBridgeConstants.AAI_FLAVOR,
- ImmutableMap.<String, String>builder()
- .put(HeatBridgeConstants.AAI_CLOUD_OWNER, cloudOwner)
- .put(HeatBridgeConstants.AAI_CLOUD_REGION_ID, cloudRegionId)
- .put(HeatBridgeConstants.AAI_FLAVOR_ID, server.getFlavor().getId())
- .build());
+ ImmutableMap.<String, String>builder().put(HeatBridgeConstants.AAI_CLOUD_OWNER, cloudOwner)
+ .put(HeatBridgeConstants.AAI_CLOUD_REGION_ID, cloudRegionId)
+ .put(HeatBridgeConstants.AAI_FLAVOR_ID, server.getFlavor().getId()).build());
relationships.add(flavorRel);
return relationshipList;
}
public RelationshipList getLInterfaceRelationshipList(final String pserverName, final String pIfName,
- final String pfPciId) {
+ final String pfPciId) {
RelationshipList relationshipList = new RelationshipList();
List<Relationship> relationships = relationshipList.getRelationship();
// sriov-vf to sriov-pf relationship
Relationship sriovPfRelationship = buildRelationship(HeatBridgeConstants.AAI_SRIOV_PF,
- ImmutableMap.<String, String>builder()
- .put(HeatBridgeConstants.AAI_PSERVER_HOSTNAME, pserverName)
- .put(HeatBridgeConstants.AAI_P_INTERFACE_NAME, pIfName)
- .put(HeatBridgeConstants.AAI_SRIOV_PF_PCI_ID, pfPciId)
- .build());
+ ImmutableMap.<String, String>builder().put(HeatBridgeConstants.AAI_PSERVER_HOSTNAME, pserverName)
+ .put(HeatBridgeConstants.AAI_P_INTERFACE_NAME, pIfName)
+ .put(HeatBridgeConstants.AAI_SRIOV_PF_PCI_ID, pfPciId).build());
relationships.add(sriovPfRelationship);
return relationshipList;
@@ -122,7 +110,7 @@ public class AaiHelper {
vserver.setVserverName2(server.getName());
vserver.setProvStatus(server.getStatus().value());
server.getLinks().stream().filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY))
- .findFirst().ifPresent(link -> vserver.setVserverSelflink(link.getHref()));
+ .findFirst().ifPresent(link -> vserver.setVserverSelflink(link.getHref()));
return vserver;
}
@@ -139,7 +127,7 @@ public class AaiHelper {
aaiImage.setImageOsDistro(HeatBridgeConstants.OS_UNKNOWN_KEY);
aaiImage.setImageOsVersion(HeatBridgeConstants.OS_UNKNOWN_KEY);
image.getLinks().stream().filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY))
- .findFirst().ifPresent(link -> aaiImage.setImageSelflink(link.getHref()));
+ .findFirst().ifPresent(link -> aaiImage.setImageSelflink(link.getHref()));
return aaiImage;
}
@@ -154,7 +142,7 @@ public class AaiHelper {
aaiFlavor.setFlavorId(flavor.getId());
aaiFlavor.setFlavorName(flavor.getName());
flavor.getLinks().stream().filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY))
- .findFirst().ifPresent(link -> aaiFlavor.setFlavorSelflink(link.getHref()));
+ .findFirst().ifPresent(link -> aaiFlavor.setFlavorSelflink(link.getHref()));
return aaiFlavor;
}
@@ -167,7 +155,7 @@ public class AaiHelper {
public List<String> getFlavorsUriFromVserver(final List<Vserver> vservers) {
List<String> flavorUris = new ArrayList<>();
vservers.forEach(vserver -> flavorUris.addAll(
- filterRelatedLinksByRelatedToProperty(vserver.getRelationshipList(), HeatBridgeConstants.AAI_FLAVOR)));
+ filterRelatedLinksByRelatedToProperty(vserver.getRelationshipList(), HeatBridgeConstants.AAI_FLAVOR)));
return flavorUris;
}
@@ -180,7 +168,7 @@ public class AaiHelper {
public List<String> getImagesUriFromVserver(final List<Vserver> vservers) {
List<String> imageUris = new ArrayList<>();
vservers.forEach(vserver -> imageUris.addAll(
- filterRelatedLinksByRelatedToProperty(vserver.getRelationshipList(), HeatBridgeConstants.AAI_IMAGE)));
+ filterRelatedLinksByRelatedToProperty(vserver.getRelationshipList(), HeatBridgeConstants.AAI_IMAGE)));
return imageUris;
}
@@ -192,20 +180,18 @@ public class AaiHelper {
*/
public Map<String, List<String>> getPserverToPciIdMap(final List<Vserver> vservers) {
Map<String, List<String>> pserverToPciIdMap = new HashMap<>();
- for(Vserver vserver : vservers) {
- if(vserver.getLInterfaces() != null) {
- List<String> pciIds = vserver.getLInterfaces().getLInterface()
- .stream()
- .filter(lInterface -> lInterface.getSriovVfs() != null
- && CollectionUtils.isNotEmpty(lInterface.getSriovVfs().getSriovVf()))
- .flatMap(lInterface -> lInterface.getSriovVfs().getSriovVf().stream())
- .map(SriovVf::getPciId)
- .collect(Collectors.toList());
+ for (Vserver vserver : vservers) {
+ if (vserver.getLInterfaces() != null) {
+ List<String> pciIds = vserver.getLInterfaces().getLInterface().stream()
+ .filter(lInterface -> lInterface.getSriovVfs() != null
+ && CollectionUtils.isNotEmpty(lInterface.getSriovVfs().getSriovVf()))
+ .flatMap(lInterface -> lInterface.getSriovVfs().getSriovVf().stream()).map(SriovVf::getPciId)
+ .collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(pciIds)) {
List<String> matchingPservers = extractRelationshipDataValue(vserver.getRelationshipList(),
- HeatBridgeConstants.AAI_PSERVER, HeatBridgeConstants.AAI_PSERVER_HOSTNAME);
+ HeatBridgeConstants.AAI_PSERVER, HeatBridgeConstants.AAI_PSERVER_HOSTNAME);
Preconditions.checkState(matchingPservers != null && matchingPservers.size() == 1,
- "Invalid pserver relationships for vserver: " + vserver.getVserverName());
+ "Invalid pserver relationships for vserver: " + vserver.getVserverName());
pserverToPciIdMap.put(matchingPservers.get(0), pciIds);
}
}
@@ -214,8 +200,8 @@ public class AaiHelper {
}
/**
- * Extract from relationship-list object all the relationship-value that match the related-to and
- * relationship-key fields.
+ * Extract from relationship-list object all the relationship-value that match the related-to and relationship-key
+ * fields.
*
* @param relationshipListObj AAI relationship-list object
* @param relatedToProperty related-to value
@@ -223,15 +209,14 @@ public class AaiHelper {
* @return relationship-value matching the key requested for the relationship object of type related-to property
*/
private List<String> extractRelationshipDataValue(final RelationshipList relationshipListObj,
- final String relatedToProperty, final String relationshipKey) {
+ final String relatedToProperty, final String relationshipKey) {
if (relationshipListObj != null && relationshipListObj.getRelationship() != null) {
return relationshipListObj.getRelationship().stream()
- .filter(relationship -> relationship.getRelatedTo().equals(relatedToProperty))
- .map(Relationship::getRelationshipData)
- .flatMap(Collection::stream)
- .filter(data -> data.getRelationshipKey() != null && relationshipKey.equals(data.getRelationshipKey()))
- .map(RelationshipData::getRelationshipValue)
- .collect(Collectors.toList());
+ .filter(relationship -> relationship.getRelatedTo().equals(relatedToProperty))
+ .map(Relationship::getRelationshipData).flatMap(Collection::stream)
+ .filter(data -> data.getRelationshipKey() != null
+ && relationshipKey.equals(data.getRelationshipKey()))
+ .map(RelationshipData::getRelationshipValue).collect(Collectors.toList());
}
return new ArrayList<>();
}
@@ -244,12 +229,11 @@ public class AaiHelper {
* @return a list of related-links filtered by the specified related-to property
*/
private List<String> filterRelatedLinksByRelatedToProperty(final RelationshipList relationshipListObj,
- final String relatedToProperty) {
+ final String relatedToProperty) {
if (relationshipListObj != null && relationshipListObj.getRelationship() != null) {
return relationshipListObj.getRelationship().stream()
- .filter(relationship -> relationship.getRelatedTo().equals(relatedToProperty))
- .map(Relationship::getRelatedLink)
- .collect(Collectors.toList());
+ .filter(relationship -> relationship.getRelatedTo().equals(relatedToProperty))
+ .map(Relationship::getRelatedLink).collect(Collectors.toList());
}
return new ArrayList<>();
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java
index 143e33581d..1fa41ee2a0 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java
@@ -27,6 +27,7 @@ public interface OpenstackClient {
/**
* Get a server object by server ID
+ *
* @param serverId Unique server-name (simple name) or server-id (UUID)
* @return Server object
*/
@@ -34,6 +35,7 @@ public interface OpenstackClient {
/**
* Get a port object by port ID
+ *
* @param portId Unique UUID of the port.
* @return Port object.
*/
@@ -41,12 +43,14 @@ public interface OpenstackClient {
/**
* Returns a list of all ports we have the right to see
+ *
* @return List of all Openstack ports
*/
List<Port> getAllPorts();
/**
* Returns a list of all the resources for the stack
+ *
* @param stackId Stack name or unique UUID
* @param nestingDepth The recursion level for which resources will be listed.
* @return List of Openstack Stack resources
@@ -55,6 +59,7 @@ public interface OpenstackClient {
/**
* Get a network instance by network ID
+ *
* @param networkId Unique UUID of the network.
* @return Network object.
*/
@@ -62,6 +67,7 @@ public interface OpenstackClient {
/**
* List networks by filtering parameters
+ *
* @param filterParams key-value pairs for filtering params
* @return List of filtered Network objects
*/
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java
index ebd4753323..2843eb226e 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java
@@ -38,15 +38,13 @@ abstract class OpenstackClientImpl implements OpenstackClient {
}
@Override
- public List<Port> getAllPorts() { return (List<Port>)getClient().networking().port().list(); }
+ public List<Port> getAllPorts() {
+ return (List<Port>) getClient().networking().port().list();
+ }
@Override
public List<Resource> getStackBasedResources(String stackId, int nestingDepth) {
- return getClient().heat()
- .resources()
- .list(stackId, nestingDepth)
- .stream()
- .filter(Objects::nonNull)
+ return getClient().heat().resources().list(stackId, nestingDepth).stream().filter(Objects::nonNull)
.collect(Collectors.toList());
}
@@ -62,6 +60,7 @@ abstract class OpenstackClientImpl implements OpenstackClient {
/**
* Retrieves the specific client to utilize.
+ *
* @return The specific client to utilize
*/
protected abstract OSClient getClient();
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java
index 141dd4fe50..25b3f1dbeb 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java
@@ -40,15 +40,14 @@ public class OpenstackClientFactoryImpl implements OpenstackClientFactory {
OSClientV3 client;
try {
- client = OSFactory.builderV3()
- .endpoint(osAccess.getUrl())
- .credentials(osAccess.getUser(), osAccess.getPassword(), osAccess.getDomainNameIdentifier())
- .scopeToProject(Identifier.byId(osAccess.getTenantId()))
- .authenticate()
- .useRegion(osAccess.getRegion());
+ client = OSFactory.builderV3().endpoint(osAccess.getUrl())
+ .credentials(osAccess.getUser(), osAccess.getPassword(), osAccess.getDomainNameIdentifier())
+ .scopeToProject(Identifier.byId(osAccess.getTenantId())).authenticate()
+ .useRegion(osAccess.getRegion());
return new OpenstackV3ClientImpl(client);
} catch (AuthenticationException exception) {
- throw new OpenstackClientException("Failed to authenticate with Keystone-v3: " + osAccess.getUrl(), exception);
+ throw new OpenstackClientException("Failed to authenticate with Keystone-v3: " + osAccess.getUrl(),
+ exception);
}
}
@@ -62,16 +61,13 @@ public class OpenstackClientFactoryImpl implements OpenstackClientFactory {
OSClientV2 client;
try {
- client = OSFactory.builderV2()
- .endpoint(osAccess.getUrl())
- .credentials(osAccess.getUser(), osAccess.getPassword())
- .tenantId(osAccess.getTenantId())
- .authenticate()
- .useRegion(osAccess.getRegion());
+ client = OSFactory.builderV2().endpoint(osAccess.getUrl())
+ .credentials(osAccess.getUser(), osAccess.getPassword()).tenantId(osAccess.getTenantId())
+ .authenticate().useRegion(osAccess.getRegion());
return new OpenstackV2ClientImpl(client);
} catch (AuthenticationException exception) {
throw new OpenstackClientException("Failed to authenticate with Keystone-v2.0: " + osAccess.getUrl(),
- exception);
+ exception);
}
}
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java
index 7daa8c2c71..d3faf1d7bf 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java
@@ -1,17 +1,14 @@
/*
* Copyright (C) 2018 Bell Canada. All rights reserved.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
*/
package org.onap.so.heatbridge.utils;
@@ -36,25 +33,25 @@ public class HeatBridgeUtils {
private static final String COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX = "sriov-d-";
public static Optional<String> getMatchingPserverPifName(@Nonnull final String physicalNetworkName) {
- Preconditions.checkState(!Strings.isNullOrEmpty(physicalNetworkName), "Physical network name is null or "
- + "empty!");
+ Preconditions.checkState(!Strings.isNullOrEmpty(physicalNetworkName),
+ "Physical network name is null or " + "empty!");
if (physicalNetworkName.contains(OS_SIDE_DEDICATED_SRIOV_PREFIX)) {
- return Optional
- .of(physicalNetworkName.replace(OS_SIDE_DEDICATED_SRIOV_PREFIX, COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX));
+ return Optional.of(
+ physicalNetworkName.replace(OS_SIDE_DEDICATED_SRIOV_PREFIX, COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX));
} else if (physicalNetworkName.contains(OS_SIDE_SHARED_SRIOV_PREFIX)) {
return Optional
- .of(physicalNetworkName.replace(OS_SIDE_SHARED_SRIOV_PREFIX, COMPUTE_SIDE_SHARED_SRIOV_PREFIX));
+ .of(physicalNetworkName.replace(OS_SIDE_SHARED_SRIOV_PREFIX, COMPUTE_SIDE_SHARED_SRIOV_PREFIX));
}
return Optional.empty();
}
public static Optional<String> getMatchingPhysicalNetworkName(final String pserverPinterfaceName) {
if (pserverPinterfaceName.contains(COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX)) {
- return Optional
- .of(pserverPinterfaceName.replace(COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX, OS_SIDE_DEDICATED_SRIOV_PREFIX));
+ return Optional.of(
+ pserverPinterfaceName.replace(COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX, OS_SIDE_DEDICATED_SRIOV_PREFIX));
} else if (pserverPinterfaceName.contains(COMPUTE_SIDE_SHARED_SRIOV_PREFIX)) {
return Optional
- .of(pserverPinterfaceName.replace(COMPUTE_SIDE_SHARED_SRIOV_PREFIX, OS_SIDE_SHARED_SRIOV_PREFIX));
+ .of(pserverPinterfaceName.replace(COMPUTE_SIDE_SHARED_SRIOV_PREFIX, OS_SIDE_SHARED_SRIOV_PREFIX));
}
return Optional.empty();
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduBlueprint.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduBlueprint.java
index cef0371789..df714803e8 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduBlueprint.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduBlueprint.java
@@ -23,67 +23,62 @@ package org.onap.so.vdu.utils;
import java.util.Map;
/*
- * This Java bean class describes the template model of a VDU as distributed
- * by SDC to SO. It is composed of one or more templates, one of which must be
- * the main template,
+ * This Java bean class describes the template model of a VDU as distributed by SDC to SO. It is composed of one or more
+ * templates, one of which must be the main template,
*
- * The structure of this class corresponds to the format in which the templates
- * and associated artifacts are represented in the SO Catalog.
+ * The structure of this class corresponds to the format in which the templates and associated artifacts are represented
+ * in the SO Catalog.
*
- * The map keys will be the "path" that is used to reference these artifacts within
- * the other templates. This may be relevant to how different VDU plugins package
- * the files for delivery to the sub-orchestrator.
+ * The map keys will be the "path" that is used to reference these artifacts within the other templates. This may be
+ * relevant to how different VDU plugins package the files for delivery to the sub-orchestrator.
*
- * In the future, it is possible that pre-packaged blueprints (e.g. complete TOSCA CSARs)
- * could be stored in the catalog (and added to this structure).
+ * In the future, it is possible that pre-packaged blueprints (e.g. complete TOSCA CSARs) could be stored in the catalog
+ * (and added to this structure).
*
* This bean is passed as an input to instantiateVdu and updateVdu.
*/
public class VduBlueprint {
- String vduModelId;
- String mainTemplateName;
- Map<String,byte[]> templateFiles;
- Map<String,byte[]> attachedFiles;
+ String vduModelId;
+ String mainTemplateName;
+ Map<String, byte[]> templateFiles;
+ Map<String, byte[]> attachedFiles;
- public String getVduModelId() {
- return vduModelId;
- }
+ public String getVduModelId() {
+ return vduModelId;
+ }
- public void setVduModelId(String vduModelId) {
- this.vduModelId = vduModelId;
- }
+ public void setVduModelId(String vduModelId) {
+ this.vduModelId = vduModelId;
+ }
- public String getMainTemplateName() {
- return mainTemplateName;
- }
+ public String getMainTemplateName() {
+ return mainTemplateName;
+ }
- public void setMainTemplateName(String mainTemplateName) {
- this.mainTemplateName = mainTemplateName;
- }
+ public void setMainTemplateName(String mainTemplateName) {
+ this.mainTemplateName = mainTemplateName;
+ }
- public Map<String, byte[]> getTemplateFiles() {
- return templateFiles;
- }
+ public Map<String, byte[]> getTemplateFiles() {
+ return templateFiles;
+ }
- public void setTemplateFiles(Map<String, byte[]> templateFiles) {
- this.templateFiles = templateFiles;
- }
+ public void setTemplateFiles(Map<String, byte[]> templateFiles) {
+ this.templateFiles = templateFiles;
+ }
- public Map<String, byte[]> getAttachedFiles() {
- return attachedFiles;
- }
+ public Map<String, byte[]> getAttachedFiles() {
+ return attachedFiles;
+ }
- public void setAttachedFiles(Map<String, byte[]> attachedFiles) {
- this.attachedFiles = attachedFiles;
- }
+ public void setAttachedFiles(Map<String, byte[]> attachedFiles) {
+ this.attachedFiles = attachedFiles;
+ }
- @Override
+ @Override
public String toString() {
- return "VduInfo {" +
- "id='" + vduModelId + '\'' +
- "mainTemplateName='" + mainTemplateName + '\'' +
- '}';
+ return "VduInfo {" + "id='" + vduModelId + '\'' + "mainTemplateName='" + mainTemplateName + '\'' + '}';
}
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduInfo.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduInfo.java
index 227d513a0b..22e3e1f5e9 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduInfo.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduInfo.java
@@ -26,104 +26,97 @@ import java.util.HashMap;
/*
* This Java bean class relays VDU status information in a cloud-agnostic format.
*
- * This bean is returned by all implementors of the MsoVduUtils interface operations
- * (instantiate, query, delete).
+ * This bean is returned by all implementors of the MsoVduUtils interface operations (instantiate, query, delete).
*/
public class VduInfo {
- // Set defaults for everything
- private String vduInstanceId = "";
- private String vduInstanceName = "";
- private VduStatus status = VduStatus.NOTFOUND;
- private Map<String,Object> outputs = new HashMap<>();
- private Map<String,Object> inputs = new HashMap<>();
- private String lastAction;
- private String actionStatus;
- private String errorMessage;
-
- public VduInfo () {
- }
-
- // Add more constructors as appropriate
- //
-
- public VduInfo (String id, Map<String,Object> outputs) {
- this.vduInstanceId = id;
- if (outputs != null) this.outputs = outputs;
- }
-
- public VduInfo (String id) {
- this.vduInstanceId = id;
- }
-
- public VduInfo (String id, VduStatus status) {
- this.vduInstanceId = id;
- this.status = status;
- }
-
- public String getVnfInstanceId() {
- return vduInstanceId;
- }
-
- public void setVnfInstanceId (String id) {
- this.vduInstanceId = id;
- }
-
- public String getVnfInstanceName() {
- return vduInstanceName;
- }
-
- public void setVnfInstanceName (String name) {
- this.vduInstanceName = name;
- }
-
- public VduStatus getStatus() {
- return status;
- }
-
- public void setStatus (VduStatus status) {
- this.status = status;
- }
-
- public Map<String,Object> getOutputs () {
- return outputs;
- }
-
- public void setOutputs (Map<String,Object> outputs) {
- this.outputs = outputs;
- }
-
- public Map<String,Object> getInputs () {
- return inputs;
- }
-
- public void setInputs (Map<String,Object> inputs) {
- this.inputs = inputs;
- }
-
- public String getLastAction() {
- return lastAction;
- }
-
- public String getActionStatus() {
- return actionStatus;
- }
-
- public String getErrorMessage() {
- return errorMessage;
- }
-
- @Override
+ // Set defaults for everything
+ private String vduInstanceId = "";
+ private String vduInstanceName = "";
+ private VduStatus status = VduStatus.NOTFOUND;
+ private Map<String, Object> outputs = new HashMap<>();
+ private Map<String, Object> inputs = new HashMap<>();
+ private String lastAction;
+ private String actionStatus;
+ private String errorMessage;
+
+ public VduInfo() {}
+
+ // Add more constructors as appropriate
+ //
+
+ public VduInfo(String id, Map<String, Object> outputs) {
+ this.vduInstanceId = id;
+ if (outputs != null)
+ this.outputs = outputs;
+ }
+
+ public VduInfo(String id) {
+ this.vduInstanceId = id;
+ }
+
+ public VduInfo(String id, VduStatus status) {
+ this.vduInstanceId = id;
+ this.status = status;
+ }
+
+ public String getVnfInstanceId() {
+ return vduInstanceId;
+ }
+
+ public void setVnfInstanceId(String id) {
+ this.vduInstanceId = id;
+ }
+
+ public String getVnfInstanceName() {
+ return vduInstanceName;
+ }
+
+ public void setVnfInstanceName(String name) {
+ this.vduInstanceName = name;
+ }
+
+ public VduStatus getStatus() {
+ return status;
+ }
+
+ public void setStatus(VduStatus status) {
+ this.status = status;
+ }
+
+ public Map<String, Object> getOutputs() {
+ return outputs;
+ }
+
+ public void setOutputs(Map<String, Object> outputs) {
+ this.outputs = outputs;
+ }
+
+ public Map<String, Object> getInputs() {
+ return inputs;
+ }
+
+ public void setInputs(Map<String, Object> inputs) {
+ this.inputs = inputs;
+ }
+
+ public String getLastAction() {
+ return lastAction;
+ }
+
+ public String getActionStatus() {
+ return actionStatus;
+ }
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ @Override
public String toString() {
- return "VduInfo {" +
- "id='" + vduInstanceId + '\'' +
- "name='" + vduInstanceName + '\'' +
- ", inputs='" + inputs + '\'' +
- ", outputs='" + outputs + '\'' +
- ", lastAction='" + lastAction + '\'' +
- ", status='" + status + '\'' +
- ", errorMessage='" + errorMessage + '\'' +
- '}';
+ return "VduInfo {" + "id='" + vduInstanceId + '\'' + "name='" + vduInstanceName + '\'' + ", inputs='" + inputs
+ + '\'' + ", outputs='" + outputs + '\'' + ", lastAction='" + lastAction + '\'' + ", status='" + status
+ + '\'' + ", errorMessage='" + errorMessage + '\'' + '}';
}
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduPlugin.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduPlugin.java
index 871260a86d..1350694c0e 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduPlugin.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduPlugin.java
@@ -20,126 +20,103 @@
package org.onap.so.vdu.utils;
/**
- * This interface defines a common API for template-based cloud deployments.
- * The methods here should be adaptable for Openstack (Heat), Cloudify (TOSCA),
- * Aria (TOSCA), Multi-VIM (TBD), and others (e.g. Azure Resource Manager).
+ * This interface defines a common API for template-based cloud deployments. The methods here should be adaptable for
+ * Openstack (Heat), Cloudify (TOSCA), Aria (TOSCA), Multi-VIM (TBD), and others (e.g. Azure Resource Manager).
*
- * The deployed instances are referred to here as Virtual Deployment Units (VDUs).
- * The package of templates that define a give VDU is referred to as its blueprint.
+ * The deployed instances are referred to here as Virtual Deployment Units (VDUs). The package of templates that define
+ * a give VDU is referred to as its blueprint.
*
- * Template-based orchestrators all follow a similar template/blueprint model.
- * - One main template that is the top level definition
- * - Optional nested templates referenced/included by the main template
- * - Optional files attached to the template package, typically containing
- * configuration files, install scripts, orchestration scripts, etc.
- *
- * The main template also defines the required inputs for creating a new instance,
- * and output values exposed by successfully deployed instances. Inputs and outputs
- * may include simple or complex (JSON) data types.
- *
- * Each implementation of this interface is expected to understand the MSO CloudConfig
- * to obtain the credentials for its sub-orchestrator and the targeted cloud.
- * The sub-orchestrator may have different credentials from the cloud (e.g. an Aria
- * instance in front of an Openstack cloud) or they may be the same (e.g. Heat)
+ * Template-based orchestrators all follow a similar template/blueprint model. - One main template that is the top level
+ * definition - Optional nested templates referenced/included by the main template - Optional files attached to the
+ * template package, typically containing configuration files, install scripts, orchestration scripts, etc.
+ *
+ * The main template also defines the required inputs for creating a new instance, and output values exposed by
+ * successfully deployed instances. Inputs and outputs may include simple or complex (JSON) data types.
+ *
+ * Each implementation of this interface is expected to understand the MSO CloudConfig to obtain the credentials for its
+ * sub-orchestrator and the targeted cloud. The sub-orchestrator may have different credentials from the cloud (e.g. an
+ * Aria instance in front of an Openstack cloud) or they may be the same (e.g. Heat)
*/
import java.util.Map;
-
import org.onap.so.openstack.exceptions.MsoException;
public interface VduPlugin {
/**
- * The instantiateVdu interface deploys a new VDU instance from a blueprint package.
- * The templates and files in the blueprint may be pre-installed where supported
- * (e.g. in Cloudify or Aria), or may be passed in directly (e.g. for Heat). These
- * files are expressed as byte arrays, though only text files are expected from ASDC.
- *
- * For some VIMs, this may be a single command (e.g. Heat -> create stack) or may
- * require a series of API calls (e.g. Cloudify -> upload blueprint, create deployment,
- * execute install workflow). These details are hidden within the implementation.
- * The instantiation should be fully completed before returning. On failures, this
- * method is expected to back out the attempt, leaving the cloud in its previous state.
- *
- * It is expected that parameters have been validated and contain at minimum the
- * required parameters for the given template with no extra parameters.
+ * The instantiateVdu interface deploys a new VDU instance from a blueprint package. The templates and files in the
+ * blueprint may be pre-installed where supported (e.g. in Cloudify or Aria), or may be passed in directly (e.g. for
+ * Heat). These files are expressed as byte arrays, though only text files are expected from ASDC.
+ *
+ * For some VIMs, this may be a single command (e.g. Heat -> create stack) or may require a series of API calls
+ * (e.g. Cloudify -> upload blueprint, create deployment, execute install workflow). These details are hidden within
+ * the implementation. The instantiation should be fully completed before returning. On failures, this method is
+ * expected to back out the attempt, leaving the cloud in its previous state.
+ *
+ * It is expected that parameters have been validated and contain at minimum the required parameters for the given
+ * template with no extra parameters.
*
- * The VDU name supplied by the caller will be globally unique, and identify the artifact
- * in A&AI. Inventory is managed by the higher levels invoking this function.
+ * The VDU name supplied by the caller will be globally unique, and identify the artifact in A&AI. Inventory is
+ * managed by the higher levels invoking this function.
*
- * @param cloudSiteId The target cloud for the VDU. Maps to a CloudConfig entry.
- * @param tenantId The cloud tenant in which to deploy the VDU. The meaning may differ by
- * cloud provider, but every cloud supports some sort of tenant partitioning.
+ * @param cloudSiteId The target cloud for the VDU. Maps to a CloudConfig entry.
+ * @param tenantId The cloud tenant in which to deploy the VDU. The meaning may differ by cloud provider, but every
+ * cloud supports some sort of tenant partitioning.
* @param vduInstanceName A unique name for the VDU instance to create
- * @param vduBlueprint Object containing the collection of templates and files that comprise
- * the blueprint for this VDU.
- * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects.
- * @param environmentFile A file containing default parameter name/value pairs. This is
- * primarily for Heat, though ASDC may create a similar file for other orchestrators.
+ * @param vduBlueprint Object containing the collection of templates and files that comprise the blueprint for this
+ * VDU.
+ * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects.
+ * @param environmentFile A file containing default parameter name/value pairs. This is primarily for Heat, though
+ * ASDC may create a similar file for other orchestrators.
* @param timeoutMinutes Timeout after which the instantiation attempt will be cancelled
- * @param suppressBackout Flag to preserve the deployment on install Failure. Should normally
- * be False except in troubleshooting/debug cases
+ * @param suppressBackout Flag to preserve the deployment on install Failure. Should normally be False except in
+ * troubleshooting/debug cases
*
* @return A VduInfo object
- * @throws MsoException Thrown if the sub-orchestrator API calls fail or if a timeout occurs.
- * Various subclasses of MsoException may be thrown.
+ * @throws MsoException Thrown if the sub-orchestrator API calls fail or if a timeout occurs. Various subclasses of
+ * MsoException may be thrown.
*/
- public VduInfo instantiateVdu (
- String cloudSiteId,
- String tenantId,
- String vduInstanceName,
- VduBlueprint vduBlueprint,
- Map <String, ?> inputs,
- String environmentFile,
- int timeoutMinutes,
- boolean suppressBackout)
- throws MsoException;
+ public VduInfo instantiateVdu(String cloudSiteId, String tenantId, String vduInstanceName,
+ VduBlueprint vduBlueprint, Map<String, ?> inputs, String environmentFile, int timeoutMinutes,
+ boolean suppressBackout) throws MsoException;
+
-
/**
- * Query a deployed VDU instance. This call will return a VduInfo object, or null
- * if the deployment does not exist.
+ * Query a deployed VDU instance. This call will return a VduInfo object, or null if the deployment does not exist.
*
- * Some VIM orchestrators identify deployment instances by string UUIDs, and others
- * by integers. In the latter case, the ID will be passed in as a numeric string.
+ * Some VIM orchestrators identify deployment instances by string UUIDs, and others by integers. In the latter case,
+ * the ID will be passed in as a numeric string.
*
- * The returned VduInfo object contains the input and output parameter maps,
- * as well as other properties of the deployment (name, status, last action, etc.).
+ * The returned VduInfo object contains the input and output parameter maps, as well as other properties of the
+ * deployment (name, status, last action, etc.).
*
* @param cloudSiteId The target cloud to query for the VDU.
* @param tenantId The cloud tenant in which to query
* @param vduInstanceId The ID of the deployment to query
*
* @return A VduInfo object
- * @throws MsoException Thrown if the VIM/sub-orchestrator API calls fail.
- * Various subclasses of MsoException may be thrown.
+ * @throws MsoException Thrown if the VIM/sub-orchestrator API calls fail. Various subclasses of MsoException may be
+ * thrown.
*/
- public VduInfo queryVdu (
- String cloudSiteId,
- String tenantId,
- String vduInstanceId)
- throws MsoException;
+ public VduInfo queryVdu(String cloudSiteId, String tenantId, String vduInstanceId) throws MsoException;
+
-
/**
- * Delete a VDU instance by ID. If the VIM sub-orchestrator supports pre-installation
- * of blueprints, the blueprint itself may remain installed. This is recommended, since
- * other VDU instances may be using it.
- *
- * Some VIM orchestrators identify deployment instances by string UUIDs, and others
- * by integers. In the latter case, the ID will be passed in as a numeric string.
- *
- * For some VIMs, deletion may be a single command (e.g. Heat -> delete stack) or a
- * series of API calls (e.g. Cloudify -> execute uninstall workflow, delete deployment).
- * These details are hidden within the implementation. The deletion should be fully
- * completed before returning.
- *
- * The successful return is a VduInfo object which contains the state of the object just prior
- * to deletion, with a status of DELETED. If the deployment was not found, the VduInfo object
- * should be empty (with a status of NOTFOUND). There is no rollback from a successful deletion.
- *
- * A deletion failure will result in an undefined deployment state - the components may
- * or may not have been all or partially uninstalled, so the resulting deployment must
- * be considered invalid.
+ * Delete a VDU instance by ID. If the VIM sub-orchestrator supports pre-installation of blueprints, the blueprint
+ * itself may remain installed. This is recommended, since other VDU instances may be using it.
+ *
+ * Some VIM orchestrators identify deployment instances by string UUIDs, and others by integers. In the latter case,
+ * the ID will be passed in as a numeric string.
+ *
+ * For some VIMs, deletion may be a single command (e.g. Heat -> delete stack) or a series of API calls (e.g.
+ * Cloudify -> execute uninstall workflow, delete deployment). These details are hidden within the implementation.
+ * The deletion should be fully completed before returning.
+ *
+ * The successful return is a VduInfo object which contains the state of the object just prior to deletion, with a
+ * status of DELETED. If the deployment was not found, the VduInfo object should be empty (with a status of
+ * NOTFOUND). There is no rollback from a successful deletion.
+ *
+ * A deletion failure will result in an undefined deployment state - the components may or may not have been all or
+ * partially uninstalled, so the resulting deployment must be considered invalid.
*
* @param cloudSiteId The target cloud from which to delete the VDU.
* @param tenantId The cloud tenant in which to delete the VDU.
@@ -149,100 +126,81 @@ public interface VduPlugin {
*
* @return A VduInfo object, representing the state of the instance just prior to deletion.
*
- * @throws MsoException Thrown if the API calls fail or if a timeout occurs.
- * Various subclasses of MsoException may be thrown.
+ * @throws MsoException Thrown if the API calls fail or if a timeout occurs. Various subclasses of MsoException may
+ * be thrown.
*/
- public VduInfo deleteVdu (
- String cloudSiteId,
- String tenantId,
- String vduInstanceId,
- int timeoutMinutes,
- boolean keepBlueprintLoaded)
- throws MsoException;
+ public VduInfo deleteVdu(String cloudSiteId, String tenantId, String vduInstanceId, int timeoutMinutes,
+ boolean keepBlueprintLoaded) throws MsoException;
+
-
/**
- * The updateVdu interface attempts to update a VDU in-place, using either new inputs or
- * a new model definition (i.e. updated templates/blueprints). This depends on the
- * capabilities of the targeted sub-orchestrator, as not all implementations are expected
- * to support this ability. It is primary included initially only for Heat.
- *
- * It is expected that parameters have been validated and contain at minimum the required
- * parameters for the given template with no extra parameters. The VDU instance name cannot
- * be updated.
- *
- * The update should be fully completed before returning. The successful return is a
- * VduInfo object containing the updated VDU state.
- *
- * An update failure will result in an undefined deployment state - the components may
- * or may not have been all or partially modified, deleted, recreated, etc. So the resulting
- * VDU must be considered invalid.
- *
- * @param cloudSiteId The target cloud for the VDU. Maps to a CloudConfig entry.
- * @param tenantId The cloud tenant in which to deploy the VDU. The meaning may differ by
- * cloud provider, but every cloud supports some sort of tenant partitioning.
+ * The updateVdu interface attempts to update a VDU in-place, using either new inputs or a new model definition
+ * (i.e. updated templates/blueprints). This depends on the capabilities of the targeted sub-orchestrator, as not
+ * all implementations are expected to support this ability. It is primary included initially only for Heat.
+ *
+ * It is expected that parameters have been validated and contain at minimum the required parameters for the given
+ * template with no extra parameters. The VDU instance name cannot be updated.
+ *
+ * The update should be fully completed before returning. The successful return is a VduInfo object containing the
+ * updated VDU state.
+ *
+ * An update failure will result in an undefined deployment state - the components may or may not have been all or
+ * partially modified, deleted, recreated, etc. So the resulting VDU must be considered invalid.
+ *
+ * @param cloudSiteId The target cloud for the VDU. Maps to a CloudConfig entry.
+ * @param tenantId The cloud tenant in which to deploy the VDU. The meaning may differ by cloud provider, but every
+ * cloud supports some sort of tenant partitioning.
* @param vduInstanceId The unique ID for the VDU instance to update.
- * @param vduBlueprint Object containing the collection of templates and files that comprise
- * the blueprint for this VDU.
- * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects.
- * @param environmentFile A file containing default parameter name/value pairs. This is
- * primarily for Heat, though ASDC may create a similar file for other orchestrators.
+ * @param vduBlueprint Object containing the collection of templates and files that comprise the blueprint for this
+ * VDU.
+ * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects.
+ * @param environmentFile A file containing default parameter name/value pairs. This is primarily for Heat, though
+ * ASDC may create a similar file for other orchestrators.
* @param timeoutMinutes Timeout after which the instantiation attempt will be cancelled
*
* @return A VduInfo object
- * @throws MsoException Thrown if the sub-orchestrator API calls fail or if a timeout occurs.
- * Various subclasses of MsoException may be thrown.
+ * @throws MsoException Thrown if the sub-orchestrator API calls fail or if a timeout occurs. Various subclasses of
+ * MsoException may be thrown.
*/
- public VduInfo updateVdu (
- String cloudSiteId,
- String tenantId,
- String vduInstanceId,
- VduBlueprint vduBlueprint,
- Map <String, ?> inputs,
- String environmentFile,
- int timeoutMinutes)
- throws MsoException;
+ public VduInfo updateVdu(String cloudSiteId, String tenantId, String vduInstanceId, VduBlueprint vduBlueprint,
+ Map<String, ?> inputs, String environmentFile, int timeoutMinutes) throws MsoException;
+
-
/**
- * Check if a blueprint package has been installed in the sub-orchestrator and available
- * for use at a targeted cloud site. If the specific sub-orchestrator does not support
- * pre-installation, then those implementations should always return False.
+ * Check if a blueprint package has been installed in the sub-orchestrator and available for use at a targeted cloud
+ * site. If the specific sub-orchestrator does not support pre-installation, then those implementations should
+ * always return False.
*
* @param cloudSiteId The cloud site where the blueprint is needed
* @param vduModelId Unique ID of the VDU model to query
*
* @throws MsoException Thrown if the API call fails.
*/
- public boolean isBlueprintLoaded (String cloudSiteId, String vduModelId)
- throws MsoException;
+ public boolean isBlueprintLoaded(String cloudSiteId, String vduModelId) throws MsoException;
+
-
/**
- * Install a blueprint package to the target sub-orchestrator for a cloud site.
- * The blueprints currently must be structured as a single directory with all of the
- * required files. One of those files is designated the "main file" for the blueprint.
- * Files are provided as byte arrays, though expect only text files will be distributed
- * from ASDC and stored by MSO.
+ * Install a blueprint package to the target sub-orchestrator for a cloud site. The blueprints currently must be
+ * structured as a single directory with all of the required files. One of those files is designated the "main file"
+ * for the blueprint. Files are provided as byte arrays, though expect only text files will be distributed from ASDC
+ * and stored by MSO.
*
* @param cloudSiteId The cloud site where the blueprint is needed
- * @param vduBlueprint Object containing the collection of templates and files that comprise
- * the blueprint for this VDU.
+ * @param vduBlueprint Object containing the collection of templates and files that comprise the blueprint for this
+ * VDU.
* @param failIfExists Flag to return an error if blueprint already exists
*
* @throws MsoException Thrown if the API call fails.
*/
- public void uploadBlueprint (String cloudSiteId,
- VduBlueprint vduBlueprint,
- boolean failIfExists)
- throws MsoException;
+ public void uploadBlueprint(String cloudSiteId, VduBlueprint vduBlueprint, boolean failIfExists)
+ throws MsoException;
/**
- * Indicator that this VIM sub-orchestrator implementation supports independent upload
- * of blueprint packages. Each implementation should return a constant value.
+ * Indicator that this VIM sub-orchestrator implementation supports independent upload of blueprint packages. Each
+ * implementation should return a constant value.
*
* @returns True if the sub-orchestrator supports blueprint pre-installation (upload).
*/
- public boolean blueprintUploadSupported ();
+ public boolean blueprintUploadSupported();
}
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java
index 1412b02da0..0c4b9e01b9 100644
--- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java
+++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java
@@ -25,13 +25,8 @@ package org.onap.so.vdu.utils;
* Enum status values to capture the state of a generic (cloud-agnostic) VDU.
*/
public enum VduStatus {
- NOTFOUND,
- INSTANTIATING,
- INSTANTIATED,
- DELETING,
- DELETED, // Note - only returned in success response to deleteVdu call.
- UPDATING,
- FAILED,
- UNKNOWN
+ NOTFOUND, INSTANTIATING, INSTANTIATED, DELETING, DELETED, // Note - only returned in success response to deleteVdu
+ // call.
+ UPDATING, FAILED, UNKNOWN
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/BeansTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/BeansTest.java
index 7aa86da237..ea9512bfa7 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/BeansTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/BeansTest.java
@@ -36,55 +36,53 @@ import org.springframework.stereotype.Component;
public class BeansTest {
- private final PojoClassFilter filterTestClasses = new FilterTestClasses();
-
- private final PojoClassFilter enumFilter = new FilterEnum();
-
- private final PojoClassFilter noNestedClasses = new FilterTestNestedClasses();
-
-
-
- @Test
- public void pojoStructure() {
- test("org.onap.so.adapters.network.async.client");
- test("org.onap.so.adapters.vnf.async.client");
- test("org.onap.so.adapters.network");
- test("org.onap.so.adapters.vnf");
- test("org.onap.so.adapters.valet");
- test("org.onap.so.adapters.valet.beans");
- test("org.onap.so.vdu.utils");
- }
-
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new NoStaticExceptFinalRule())
- .with(new SerializableMustHaveSerialVersionUIDRule())
- .with(new NoPublicFieldsExceptStaticFinalRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .with(new ToStringTester())
-
- .build();
-
-
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses,enumFilter,new FilterNonConcrete(), noNestedClasses, new FilterBeans());
- }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
-
- private static class FilterTestNestedClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.isNestedClass();
- }
- }
-
- private static class FilterBeans implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return pojoClass.getAnnotations().stream().filter(o -> o instanceof Component).count() <= 0;
- }
- }
+ private final PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ private final PojoClassFilter enumFilter = new FilterEnum();
+
+ private final PojoClassFilter noNestedClasses = new FilterTestNestedClasses();
+
+
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.adapters.network.async.client");
+ test("org.onap.so.adapters.vnf.async.client");
+ test("org.onap.so.adapters.network");
+ test("org.onap.so.adapters.vnf");
+ test("org.onap.so.adapters.valet");
+ test("org.onap.so.adapters.valet.beans");
+ test("org.onap.so.vdu.utils");
+ }
+
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new NoStaticExceptFinalRule())
+ .with(new SerializableMustHaveSerialVersionUIDRule()).with(new NoPublicFieldsExceptStaticFinalRule())
+ .with(new SetterTester()).with(new GetterTester()).with(new ToStringTester())
+
+ .build();
+
+
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, enumFilter, new FilterNonConcrete(),
+ noNestedClasses, new FilterBeans());
+ }
+
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
+
+ private static class FilterTestNestedClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.isNestedClass();
+ }
+ }
+
+ private static class FilterBeans implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return pojoClass.getAnnotations().stream().filter(o -> o instanceof Component).count() <= 0;
+ }
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java
index 1eaac18fb6..80b2a21419 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java
@@ -23,12 +23,10 @@ package org.onap.so.adapters.audit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.doReturn;
-
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
-
import org.camunda.bpm.client.task.ExternalTask;
import org.camunda.bpm.client.task.ExternalTaskService;
import org.junit.Before;
@@ -40,160 +38,165 @@ import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.onap.so.audit.beans.AuditInventory;
import org.springframework.core.env.Environment;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class AuditStackServiceDataTest extends AuditCreateStackService {
- @InjectMocks
- private AuditCreateStackService auditStackService = new AuditCreateStackService();
-
- @Mock
- private HeatStackAudit heatStackAuditMock;
-
- @Mock
- private Environment mockEnv;
-
- @Mock
- private ExternalTask mockExternalTask;
-
- @Mock
- private ExternalTaskService mockExternalTaskService;
-
- private ObjectMapper objectMapper = new ObjectMapper();
-
- private AuditInventory auditInventory = new AuditInventory();
-
- Optional<AAIObjectAuditList> auditListOptSuccess;
-
- Optional<AAIObjectAuditList> auditListOptFailure;
-
- @Before
- public void setup() throws JsonParseException, JsonMappingException, IOException {
- auditInventory.setCloudOwner("cloudOwner");
- auditInventory.setCloudRegion("cloudRegion");
- auditInventory.setTenantId("tenantId");
- auditInventory.setHeatStackName("stackName");
- MockitoAnnotations.initMocks(this);
-
- AAIObjectAuditList auditListSuccess = objectMapper.readValue(new File("src/test/resources/ExpectedVServerFound.json"), AAIObjectAuditList.class);
- auditListOptSuccess = Optional.of(auditListSuccess);
-
- AAIObjectAuditList auditListFailure = objectMapper.readValue(new File("src/test/resources/Vserver2_Found_VServer1_Not_Found.json"), AAIObjectAuditList.class);
- auditListOptFailure = Optional.of(auditListFailure);
- String[] retrySequence = new String[8];
- retrySequence[0] = "1";
- retrySequence[1] = "1";
- retrySequence[2] = "2";
- retrySequence[3] = "3";
- retrySequence[4] = "5";
- retrySequence[5] = "8";
- retrySequence[6] = "13";
- retrySequence[7] = "20";
- doReturn(auditInventory).when(mockExternalTask).getVariable("auditInventory");
- doReturn("6000").when(mockEnv).getProperty("mso.workflow.topics.retryMultiplier","6000");
- doReturn(retrySequence).when(mockEnv).getProperty("mso.workflow.topics.retrySequence",String[].class);
- doReturn("aasdfasdf").when(mockExternalTask).getId();
- }
-
- @Test
- public void execute_external_task_audit_success_Test() {
- doReturn(auditListOptSuccess).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId", "stackName");
- auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService);
- ArgumentCaptor<Map> captor = ArgumentCaptor.forClass(Map.class);
- ArgumentCaptor<ExternalTask> taskCaptor = ArgumentCaptor.forClass(ExternalTask.class);
- Mockito.verify(mockExternalTaskService).complete(taskCaptor.capture(),captor.capture());
- Map actualMap = captor.getValue();
- assertEquals(true,actualMap.get("auditIsSuccessful"));
- assertNotNull(actualMap.get("auditInventoryResult"));
- }
-
- @Test
- public void execute_external_task_audit_first_failure_Test() {
- doReturn(auditListOptFailure).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId", "stackName");
- doReturn(null).when(mockExternalTask).getRetries();
- auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService);
- Mockito.verify(mockExternalTaskService).handleFailure(mockExternalTask,
- "Unable to find all VServers and L-Interaces in A&AI",
- "Unable to find all VServers and L-Interaces in A&AI", 8, 10000L);
- }
-
- @Test
- public void execute_external_task_audit_intermediate_failure_Test() {
- doReturn(auditListOptFailure).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId", "stackName");
- doReturn(6).when(mockExternalTask).getRetries();
- auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService);
- Mockito.verify(mockExternalTaskService).handleFailure(mockExternalTask,
- "Unable to find all VServers and L-Interaces in A&AI",
- "Unable to find all VServers and L-Interaces in A&AI", 5, 12000L);
-
- }
-
- @Test
- public void execute_external_task_audit_final_failure_Test() {
- doReturn(auditListOptFailure).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId", "stackName");
- doReturn(1).when(mockExternalTask).getRetries();
- auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService);
- ArgumentCaptor<Map> captor = ArgumentCaptor.forClass(Map.class);
- ArgumentCaptor<ExternalTask> taskCaptor = ArgumentCaptor.forClass(ExternalTask.class);
- Mockito.verify(mockExternalTaskService).complete(taskCaptor.capture(),captor.capture());
- Map actualMap = captor.getValue();
- assertEquals(false,actualMap.get("auditIsSuccessful"));
- assertNotNull(actualMap.get("auditInventoryResult"));
- }
-
- @Test
- public void retry_sequence_calculation_Test() {
- long firstRetry = auditStackService.calculateRetryDelay(8);
- assertEquals(6000L, firstRetry);
- long secondRetry = auditStackService.calculateRetryDelay(7);
- assertEquals(6000L, secondRetry);
- long thirdRetry = auditStackService.calculateRetryDelay(6);
- assertEquals(12000L, thirdRetry);
- long fourthRetry = auditStackService.calculateRetryDelay(5);
- assertEquals(18000L, fourthRetry);
- long fifthRetry = auditStackService.calculateRetryDelay(4);
- assertEquals(30000L, fifthRetry);
- long sixRetry = auditStackService.calculateRetryDelay(3);
- assertEquals(48000L, sixRetry);
- long seventhRetry = auditStackService.calculateRetryDelay(2);
- assertEquals(78000L, seventhRetry);
- long eigthRetry = auditStackService.calculateRetryDelay(1);
- assertEquals(120000L, eigthRetry);
- }
-
- @Test
- public void retry_sequence_Test() {
- long firstRetry = auditStackService.calculateRetryDelay(8);
- assertEquals(6000L, firstRetry);
- long secondRetry = auditStackService.calculateRetryDelay(7);
- assertEquals(6000L, secondRetry);
- long thirdRetry = auditStackService.calculateRetryDelay(6);
- assertEquals(12000L, thirdRetry);
- long fourthRetry = auditStackService.calculateRetryDelay(5);
- assertEquals(18000L, fourthRetry);
- long fifthRetry = auditStackService.calculateRetryDelay(4);
- assertEquals(30000L, fifthRetry);
- long sixRetry = auditStackService.calculateRetryDelay(3);
- assertEquals(48000L, sixRetry);
- long seventhRetry = auditStackService.calculateRetryDelay(2);
- assertEquals(78000L, seventhRetry);
- long eigthRetry = auditStackService.calculateRetryDelay(1);
- assertEquals(120000L, eigthRetry);
- }
-
-
- @Test
- public void determineAuditResult_Test() throws Exception{
- boolean actual = auditStackService.didCreateAuditFail(auditListOptSuccess);
- assertEquals(false, actual);
- }
-
- @Test
- public void determineAuditResult_Failure_Test() throws Exception{
- boolean actual = auditStackService.didCreateAuditFail(auditListOptFailure);
- assertEquals(true, actual);
- }
+ @InjectMocks
+ private AuditCreateStackService auditStackService = new AuditCreateStackService();
+
+ @Mock
+ private HeatStackAudit heatStackAuditMock;
+
+ @Mock
+ private Environment mockEnv;
+
+ @Mock
+ private ExternalTask mockExternalTask;
+
+ @Mock
+ private ExternalTaskService mockExternalTaskService;
+
+ private ObjectMapper objectMapper = new ObjectMapper();
+
+ private AuditInventory auditInventory = new AuditInventory();
+
+ Optional<AAIObjectAuditList> auditListOptSuccess;
+
+ Optional<AAIObjectAuditList> auditListOptFailure;
+
+ @Before
+ public void setup() throws JsonParseException, JsonMappingException, IOException {
+ auditInventory.setCloudOwner("cloudOwner");
+ auditInventory.setCloudRegion("cloudRegion");
+ auditInventory.setTenantId("tenantId");
+ auditInventory.setHeatStackName("stackName");
+ MockitoAnnotations.initMocks(this);
+
+ AAIObjectAuditList auditListSuccess = objectMapper
+ .readValue(new File("src/test/resources/ExpectedVServerFound.json"), AAIObjectAuditList.class);
+ auditListOptSuccess = Optional.of(auditListSuccess);
+
+ AAIObjectAuditList auditListFailure = objectMapper.readValue(
+ new File("src/test/resources/Vserver2_Found_VServer1_Not_Found.json"), AAIObjectAuditList.class);
+ auditListOptFailure = Optional.of(auditListFailure);
+ String[] retrySequence = new String[8];
+ retrySequence[0] = "1";
+ retrySequence[1] = "1";
+ retrySequence[2] = "2";
+ retrySequence[3] = "3";
+ retrySequence[4] = "5";
+ retrySequence[5] = "8";
+ retrySequence[6] = "13";
+ retrySequence[7] = "20";
+ doReturn(auditInventory).when(mockExternalTask).getVariable("auditInventory");
+ doReturn("6000").when(mockEnv).getProperty("mso.workflow.topics.retryMultiplier", "6000");
+ doReturn(retrySequence).when(mockEnv).getProperty("mso.workflow.topics.retrySequence", String[].class);
+ doReturn("aasdfasdf").when(mockExternalTask).getId();
+ }
+
+ @Test
+ public void execute_external_task_audit_success_Test() {
+ doReturn(auditListOptSuccess).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId",
+ "stackName");
+ auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService);
+ ArgumentCaptor<Map> captor = ArgumentCaptor.forClass(Map.class);
+ ArgumentCaptor<ExternalTask> taskCaptor = ArgumentCaptor.forClass(ExternalTask.class);
+ Mockito.verify(mockExternalTaskService).complete(taskCaptor.capture(), captor.capture());
+ Map actualMap = captor.getValue();
+ assertEquals(true, actualMap.get("auditIsSuccessful"));
+ assertNotNull(actualMap.get("auditInventoryResult"));
+ }
+
+ @Test
+ public void execute_external_task_audit_first_failure_Test() {
+ doReturn(auditListOptFailure).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId",
+ "stackName");
+ doReturn(null).when(mockExternalTask).getRetries();
+ auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService);
+ Mockito.verify(mockExternalTaskService).handleFailure(mockExternalTask,
+ "Unable to find all VServers and L-Interaces in A&AI",
+ "Unable to find all VServers and L-Interaces in A&AI", 8, 10000L);
+ }
+
+ @Test
+ public void execute_external_task_audit_intermediate_failure_Test() {
+ doReturn(auditListOptFailure).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId",
+ "stackName");
+ doReturn(6).when(mockExternalTask).getRetries();
+ auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService);
+ Mockito.verify(mockExternalTaskService).handleFailure(mockExternalTask,
+ "Unable to find all VServers and L-Interaces in A&AI",
+ "Unable to find all VServers and L-Interaces in A&AI", 5, 12000L);
+
+ }
+
+ @Test
+ public void execute_external_task_audit_final_failure_Test() {
+ doReturn(auditListOptFailure).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId",
+ "stackName");
+ doReturn(1).when(mockExternalTask).getRetries();
+ auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService);
+ ArgumentCaptor<Map> captor = ArgumentCaptor.forClass(Map.class);
+ ArgumentCaptor<ExternalTask> taskCaptor = ArgumentCaptor.forClass(ExternalTask.class);
+ Mockito.verify(mockExternalTaskService).complete(taskCaptor.capture(), captor.capture());
+ Map actualMap = captor.getValue();
+ assertEquals(false, actualMap.get("auditIsSuccessful"));
+ assertNotNull(actualMap.get("auditInventoryResult"));
+ }
+
+ @Test
+ public void retry_sequence_calculation_Test() {
+ long firstRetry = auditStackService.calculateRetryDelay(8);
+ assertEquals(6000L, firstRetry);
+ long secondRetry = auditStackService.calculateRetryDelay(7);
+ assertEquals(6000L, secondRetry);
+ long thirdRetry = auditStackService.calculateRetryDelay(6);
+ assertEquals(12000L, thirdRetry);
+ long fourthRetry = auditStackService.calculateRetryDelay(5);
+ assertEquals(18000L, fourthRetry);
+ long fifthRetry = auditStackService.calculateRetryDelay(4);
+ assertEquals(30000L, fifthRetry);
+ long sixRetry = auditStackService.calculateRetryDelay(3);
+ assertEquals(48000L, sixRetry);
+ long seventhRetry = auditStackService.calculateRetryDelay(2);
+ assertEquals(78000L, seventhRetry);
+ long eigthRetry = auditStackService.calculateRetryDelay(1);
+ assertEquals(120000L, eigthRetry);
+ }
+
+ @Test
+ public void retry_sequence_Test() {
+ long firstRetry = auditStackService.calculateRetryDelay(8);
+ assertEquals(6000L, firstRetry);
+ long secondRetry = auditStackService.calculateRetryDelay(7);
+ assertEquals(6000L, secondRetry);
+ long thirdRetry = auditStackService.calculateRetryDelay(6);
+ assertEquals(12000L, thirdRetry);
+ long fourthRetry = auditStackService.calculateRetryDelay(5);
+ assertEquals(18000L, fourthRetry);
+ long fifthRetry = auditStackService.calculateRetryDelay(4);
+ assertEquals(30000L, fifthRetry);
+ long sixRetry = auditStackService.calculateRetryDelay(3);
+ assertEquals(48000L, sixRetry);
+ long seventhRetry = auditStackService.calculateRetryDelay(2);
+ assertEquals(78000L, seventhRetry);
+ long eigthRetry = auditStackService.calculateRetryDelay(1);
+ assertEquals(120000L, eigthRetry);
+ }
+
+
+ @Test
+ public void determineAuditResult_Test() throws Exception {
+ boolean actual = auditStackService.didCreateAuditFail(auditListOptSuccess);
+ assertEquals(false, actual);
+ }
+
+ @Test
+ public void determineAuditResult_Failure_Test() throws Exception {
+ boolean actual = auditStackService.didCreateAuditFail(auditListOptFailure);
+ assertEquals(true, actual);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java
index f0fce4db45..d43dbd99f9 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java
@@ -24,7 +24,6 @@ import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
@@ -34,7 +33,6 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -51,7 +49,6 @@ import org.onap.so.client.aai.entities.AAIResultWrapper;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.skyscreamer.jsonassert.JSONAssert;
-
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -62,283 +59,311 @@ import com.woorea.openstack.heat.model.Resources;
@RunWith(MockitoJUnitRunner.Silent.class)
public class AuditVServerTest extends AuditVServer {
- private ObjectMapper objectMapper = new ObjectMapper();
-
- @InjectMocks
- private AuditVServer auditNova = new AuditVServer();
-
- @Mock
- private AAIResourcesClient aaiResourcesMock;
-
- private String cloudOwner = "cloudOwner";
- private String cloudRegion = "cloudRegion";
- private String tenantId = "tenantId";
-
- private AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER,cloudOwner, cloudRegion,
- tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db");
-
- private AAIResourceUri vserverURI2 = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion,
- tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz");
-
- private AAIResourceUri ssc_1_trusted_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
- cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db","ssc_1_trusted_port_0");
-
- private AAIResourceUri ssc_1_service1_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
- cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db","ssc_1_service1_port_0");
-
- private AAIResourceUri ssc_1_mgmt_port_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
- cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db","ssc_1_mgmt_port_1");
-
- private AAIResourceUri ssc_1_mgmt_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
- cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db","ssc_1_mgmt_port_0");
-
- private AAIResourceUri ssc_1_service2_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
- cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db","ssc_1_service2_port_0");
-
- private AAIResourceUri ssc_1_int_ha_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
- cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db","ssc_1_int_ha_port_0");
-
- private AAIResourceUri test_port_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
- cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz","test_port_1");
-
- private AAIResourceUri test_port_2_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
- cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz","test_port_2");
-
- private AAIResourceUri service2_sub_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE,
- cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db","ssc_1_service2_port_0","service2_sub_interface_1");
-
- private AAIResourceUri service1_sub_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE,
- cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db","ssc_1_service1_port_0","service1_sub_interface_1");
-
- private AAIResourceUri service1_sub_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE,
- cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db","ssc_1_service1_port_0","service1_sub_interface_2");
-
-
-
-
- private Set<Vserver> vserversToAudit = new HashSet<>();
-
- LInterface test_port_1 = new LInterface();
- LInterface test_port_2 = new LInterface();
- LInterface ssc_1_int_ha_port_0 = new LInterface();
- LInterface service2_sub_interface_1 = new LInterface();
- LInterface ssc_1_service2_port_0 = new LInterface();
- LInterface ssc_1_mgmt_port_0 = new LInterface();
- LInterface ssc_1_mgmt_port_1 = new LInterface();
- LInterface service1_sub_interface_2 = new LInterface();
- LInterface service1_sub_interface_1 = new LInterface();
- LInterface ssc_1_service1_port_0 = new LInterface();
- LInterface ssc_1_trusted_port_0 = new LInterface();
-
-
-
- @Before
- public void setup() {
- objectMapper.setSerializationInclusion(Include.NON_NULL);
- auditNova.setAaiClient(aaiResourcesMock);
-
- Vserver vServer1= new Vserver();
- vServer1.setVserverId("3a4c2ca5-27b3-4ecc-98c5-06804867c4db");
- LInterfaces vServer1Linterfaces = new LInterfaces();
- vServer1.setLInterfaces(vServer1Linterfaces);
-
- ssc_1_trusted_port_0.setInterfaceId("dec8bdc7-5718-41dc-bfbb-561ff6eeb81c");
- ssc_1_trusted_port_0.setInterfaceName("ssc_1_trusted_port_0");
- vServer1.getLInterfaces().getLInterface().add(ssc_1_trusted_port_0);
-
-
- ssc_1_service1_port_0.setInterfaceId("1c56a24b-5f03-435a-850d-31cd4252de56");
- ssc_1_service1_port_0.setInterfaceName("ssc_1_service1_port_0");
- vServer1.getLInterfaces().getLInterface().add(ssc_1_service1_port_0);
- ssc_1_service1_port_0.setLInterfaces(new LInterfaces());
-
-
- service1_sub_interface_1.setInterfaceId("0d9cd813-2ae1-46c0-9ebb-48081f6cffbb");
- service1_sub_interface_1.setInterfaceName("service1_sub_interface_1");
- ssc_1_service1_port_0.getLInterfaces().getLInterface().add(service1_sub_interface_1);
-
-
- service1_sub_interface_2.setInterfaceId("b7019dd0-2ee9-4447-bdef-ac25676b205a");
- service1_sub_interface_2.setInterfaceName("service1_sub_interface_2");
- ssc_1_service1_port_0.getLInterfaces().getLInterface().add(service1_sub_interface_2);
-
-
- ssc_1_mgmt_port_1.setInterfaceId("12afcd28-929f-4d80-8a5a-0833bfd5e20b");
- ssc_1_mgmt_port_1.setInterfaceName("ssc_1_mgmt_port_1");
- vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_1);
-
- ssc_1_mgmt_port_0.setInterfaceId("80baec42-ffae-425f-ad8c-3f7b2c24bfff");
- ssc_1_mgmt_port_0.setInterfaceName("ssc_1_mgmt_port_0");
- vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_0);
-
-
- ssc_1_service2_port_0.setLInterfaces(new LInterfaces());
- ssc_1_service2_port_0.setInterfaceId("13eddf95-4cf3-45f2-823a-2d890a6549b4");
- ssc_1_service2_port_0.setInterfaceName("ssc_1_service2_port_0");
- vServer1.getLInterfaces().getLInterface().add(ssc_1_service2_port_0);
-
-
- service2_sub_interface_1.setInterfaceId("f711be16-2654-4a09-b89d-0511fda20e81");
- service2_sub_interface_1.setInterfaceName("service2_sub_interface_1");
- ssc_1_service2_port_0.getLInterfaces().getLInterface().add(service2_sub_interface_1);
-
-
- ssc_1_int_ha_port_0.setInterfaceId("9cab2903-70f7-44fd-b681-491d6ae2adb8");
- ssc_1_int_ha_port_0.setInterfaceName("ssc_1_int_ha_port_0");
- vServer1.getLInterfaces().getLInterface().add(ssc_1_int_ha_port_0);
-
- Vserver vServer2= new Vserver();
- vServer2.setVserverId("3a4c2ca5-27b3-4ecc-98c5-06804867c4dz");
- LInterfaces vServer2Linterfaces = new LInterfaces();
- vServer2.setLInterfaces(vServer2Linterfaces);
-
- test_port_1.setInterfaceId("9cab2903-70f7-44fd-b681-491d6ae2adz1");
- test_port_1.setInterfaceName("test_port_1");
-
-
- test_port_2.setInterfaceId("9cab2903-70f7-44fd-b681-491d6ae2adz2");
- test_port_2.setInterfaceName("test_port_2");
-
- vServer2.getLInterfaces().getLInterface().add(test_port_1);
- vServer2.getLInterfaces().getLInterface().add(test_port_2);
-
- vserversToAudit.add(vServer1);
- vserversToAudit.add(vServer2);
- }
-
- @Test
- public void audit_Vserver_Empty_HashSet() throws JsonParseException, JsonMappingException, IOException {
- Optional<AAIObjectAuditList> actual = auditNova.auditVservers(new HashSet<Vserver>(), tenantId, cloudOwner, cloudRegion);
- assertEquals(Optional.empty(), actual);
- }
-
- @Test
- public void audit_Vserver_Found_Test() throws JsonParseException, JsonMappingException, IOException {
- doReturn(true).when(aaiResourcesMock).exists(vserverURI);
- doReturn(true).when(aaiResourcesMock).exists(vserverURI2);
- doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_trusted_port_0_uri);
- doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_service1_port_0_uri);
- doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class,ssc_1_mgmt_port_1_uri);
- doReturn(Optional.of(ssc_1_mgmt_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_mgmt_port_0_uri);
- doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_service2_port_0_uri);
- doReturn(Optional.of(service2_sub_interface_1)).when(aaiResourcesMock).get(LInterface.class,service1_sub_1_uri);
- doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_int_ha_port_0_uri);
- doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class,test_port_1_uri);
- doReturn(Optional.of(test_port_2)).when(aaiResourcesMock).get(LInterface.class,test_port_2_uri);
-
- doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri);
- doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri);
- doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri);
-
- Optional<AAIObjectAuditList> actual = auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion);
- String actualString = objectMapper.writeValueAsString(actual.get());
- String expected = getJson("ExpectedVServerFound.json");
- JSONAssert.assertEquals(expected,actualString, false);
- }
-
- @Test
- public void audit_Vserver_Found_Test_Network_Not_Found()
- throws JsonParseException, JsonMappingException, IOException {
- doReturn(true).when(aaiResourcesMock).exists(vserverURI);
- doReturn(true).when(aaiResourcesMock).exists(vserverURI2);
- doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_trusted_port_0_uri);
- doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_service1_port_0_uri);
- doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class,ssc_1_mgmt_port_1_uri);
- doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class,ssc_1_mgmt_port_0_uri);
- doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_service2_port_0_uri);
- doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_int_ha_port_0_uri);
- doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class,test_port_1_uri);
- doReturn(Optional.of(test_port_2)).when(aaiResourcesMock).get(LInterface.class,test_port_2_uri);
-
- doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri);
- doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri);
- doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri);
-
- Optional<AAIObjectAuditList> actual = auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion);
- String actualString = objectMapper.writeValueAsString(actual.get());
- String expected = getJson("VServer_Found_network_Not_Found.json");
- JSONAssert.assertEquals(expected,actualString, false);
- }
-
- @Test
- public void audit_Vserver_Found_Test_Network_Not_Found_Second_Server()
- throws JsonParseException, JsonMappingException, IOException {
- doReturn(true).when(aaiResourcesMock).exists(vserverURI);
- doReturn(true).when(aaiResourcesMock).exists(vserverURI2);
- doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_trusted_port_0_uri);
- doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_service1_port_0_uri);
- doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class,ssc_1_mgmt_port_1_uri);
- doReturn(Optional.of(ssc_1_mgmt_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_mgmt_port_0_uri);
- doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_service2_port_0_uri);
- doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_int_ha_port_0_uri);
- doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class,test_port_1_uri);
- doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class,test_port_2_uri);
- doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri);
- doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri);
- doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri);
- Optional<AAIObjectAuditList> actual = auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion);
- String actualString = objectMapper.writeValueAsString(actual.get());
- String expected = getJson("VServer_Found_Network_Sec_Server_Not_Found.json");
- JSONAssert.assertEquals(expected,actualString, false);
- }
-
- @Test
- public void audit_Vserver_Not_Found_Test() throws JsonParseException, JsonMappingException, IOException {
- doReturn(false).when(aaiResourcesMock).exists(vserverURI);
- doReturn(false).when(aaiResourcesMock).exists(vserverURI2);
- Optional<AAIObjectAuditList> actual = auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion);
- String actualString = objectMapper.writeValueAsString(actual.get());
- String expected = getJson("Vservers_Not_Found.json");
- JSONAssert.assertEquals(expected,actualString, false);
- }
-
- @Test
- public void audit_Vserver_first_Not_Found_Test() throws JsonParseException, JsonMappingException, IOException {
- doReturn(false).when(aaiResourcesMock).exists(vserverURI);
- doReturn(true).when(aaiResourcesMock).exists(vserverURI2);
- doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class,test_port_1_uri);
- doReturn(Optional.of(test_port_2)).when(aaiResourcesMock).get(LInterface.class,test_port_2_uri);
- Optional<AAIObjectAuditList> actual = auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion);
- String actualString = objectMapper.writeValueAsString(actual.get());
- String expected = getJson("Vserver2_Found_VServer1_Not_Found.json");
- JSONAssert.assertEquals(expected,actualString, false);
- }
-
-
- @Test
- public void doesSubInterfaceExistinAAI_Test(){
- AAIResourceUri subInterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner,
- cloudRegion, tenantId, "vserverId", "l-interface", "sub-interface");
-
- assertEquals("/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/cloudRegion/tenants/tenant/tenantId/vservers/vserver/vserverId/l-interfaces/l-interface/l-interface/l-interfaces/l-interface/sub-interface",subInterfaceURI.build().toString());
- }
-
- @Test
- public void audit_Vserver_Second_Not_Found_Test() throws JsonParseException, JsonMappingException, IOException {
- doReturn(true).when(aaiResourcesMock).exists(vserverURI);
- doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_trusted_port_0_uri);
- doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_service1_port_0_uri);
- doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class,ssc_1_mgmt_port_1_uri);
- doReturn(Optional.of(ssc_1_mgmt_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_mgmt_port_0_uri);
- doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_service2_port_0_uri);
- doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class,ssc_1_int_ha_port_0_uri);
- doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class,test_port_1_uri);
- doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class,test_port_2_uri);
- doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri);
- doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri);
- doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri);
-
- doReturn(false).when(aaiResourcesMock).exists(vserverURI2);
- Optional<AAIObjectAuditList> actual = auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion);
- String actualString = objectMapper.writeValueAsString(actual.get());
- String expected = getJson("VServer_Found_Sec_Server_Not_Found2.json");
-
- JSONAssert.assertEquals(expected,actualString, false);
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get("src/test/resources/" + filename)));
- }
+ private ObjectMapper objectMapper = new ObjectMapper();
+
+ @InjectMocks
+ private AuditVServer auditNova = new AuditVServer();
+
+ @Mock
+ private AAIResourcesClient aaiResourcesMock;
+
+ private String cloudOwner = "cloudOwner";
+ private String cloudRegion = "cloudRegion";
+ private String tenantId = "tenantId";
+
+ private AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion,
+ tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db");
+
+ private AAIResourceUri vserverURI2 = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion,
+ tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz");
+
+ private AAIResourceUri ssc_1_trusted_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
+ cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_trusted_port_0");
+
+ private AAIResourceUri ssc_1_service1_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
+ cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service1_port_0");
+
+ private AAIResourceUri ssc_1_mgmt_port_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
+ cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_mgmt_port_1");
+
+ private AAIResourceUri ssc_1_mgmt_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
+ cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_mgmt_port_0");
+
+ private AAIResourceUri ssc_1_service2_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
+ cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service2_port_0");
+
+ private AAIResourceUri ssc_1_int_ha_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE,
+ cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_int_ha_port_0");
+
+ private AAIResourceUri test_port_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner,
+ cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz", "test_port_1");
+
+ private AAIResourceUri test_port_2_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner,
+ cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz", "test_port_2");
+
+ private AAIResourceUri service2_sub_1_uri =
+ AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, cloudRegion, tenantId,
+ "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service2_port_0", "service2_sub_interface_1");
+
+ private AAIResourceUri service1_sub_0_uri =
+ AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, cloudRegion, tenantId,
+ "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service1_port_0", "service1_sub_interface_1");
+
+ private AAIResourceUri service1_sub_1_uri =
+ AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, cloudRegion, tenantId,
+ "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service1_port_0", "service1_sub_interface_2");
+
+
+
+ private Set<Vserver> vserversToAudit = new HashSet<>();
+
+ LInterface test_port_1 = new LInterface();
+ LInterface test_port_2 = new LInterface();
+ LInterface ssc_1_int_ha_port_0 = new LInterface();
+ LInterface service2_sub_interface_1 = new LInterface();
+ LInterface ssc_1_service2_port_0 = new LInterface();
+ LInterface ssc_1_mgmt_port_0 = new LInterface();
+ LInterface ssc_1_mgmt_port_1 = new LInterface();
+ LInterface service1_sub_interface_2 = new LInterface();
+ LInterface service1_sub_interface_1 = new LInterface();
+ LInterface ssc_1_service1_port_0 = new LInterface();
+ LInterface ssc_1_trusted_port_0 = new LInterface();
+
+
+
+ @Before
+ public void setup() {
+ objectMapper.setSerializationInclusion(Include.NON_NULL);
+ auditNova.setAaiClient(aaiResourcesMock);
+
+ Vserver vServer1 = new Vserver();
+ vServer1.setVserverId("3a4c2ca5-27b3-4ecc-98c5-06804867c4db");
+ LInterfaces vServer1Linterfaces = new LInterfaces();
+ vServer1.setLInterfaces(vServer1Linterfaces);
+
+ ssc_1_trusted_port_0.setInterfaceId("dec8bdc7-5718-41dc-bfbb-561ff6eeb81c");
+ ssc_1_trusted_port_0.setInterfaceName("ssc_1_trusted_port_0");
+ vServer1.getLInterfaces().getLInterface().add(ssc_1_trusted_port_0);
+
+
+ ssc_1_service1_port_0.setInterfaceId("1c56a24b-5f03-435a-850d-31cd4252de56");
+ ssc_1_service1_port_0.setInterfaceName("ssc_1_service1_port_0");
+ vServer1.getLInterfaces().getLInterface().add(ssc_1_service1_port_0);
+ ssc_1_service1_port_0.setLInterfaces(new LInterfaces());
+
+
+ service1_sub_interface_1.setInterfaceId("0d9cd813-2ae1-46c0-9ebb-48081f6cffbb");
+ service1_sub_interface_1.setInterfaceName("service1_sub_interface_1");
+ ssc_1_service1_port_0.getLInterfaces().getLInterface().add(service1_sub_interface_1);
+
+
+ service1_sub_interface_2.setInterfaceId("b7019dd0-2ee9-4447-bdef-ac25676b205a");
+ service1_sub_interface_2.setInterfaceName("service1_sub_interface_2");
+ ssc_1_service1_port_0.getLInterfaces().getLInterface().add(service1_sub_interface_2);
+
+
+ ssc_1_mgmt_port_1.setInterfaceId("12afcd28-929f-4d80-8a5a-0833bfd5e20b");
+ ssc_1_mgmt_port_1.setInterfaceName("ssc_1_mgmt_port_1");
+ vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_1);
+
+ ssc_1_mgmt_port_0.setInterfaceId("80baec42-ffae-425f-ad8c-3f7b2c24bfff");
+ ssc_1_mgmt_port_0.setInterfaceName("ssc_1_mgmt_port_0");
+ vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_0);
+
+
+ ssc_1_service2_port_0.setLInterfaces(new LInterfaces());
+ ssc_1_service2_port_0.setInterfaceId("13eddf95-4cf3-45f2-823a-2d890a6549b4");
+ ssc_1_service2_port_0.setInterfaceName("ssc_1_service2_port_0");
+ vServer1.getLInterfaces().getLInterface().add(ssc_1_service2_port_0);
+
+
+ service2_sub_interface_1.setInterfaceId("f711be16-2654-4a09-b89d-0511fda20e81");
+ service2_sub_interface_1.setInterfaceName("service2_sub_interface_1");
+ ssc_1_service2_port_0.getLInterfaces().getLInterface().add(service2_sub_interface_1);
+
+
+ ssc_1_int_ha_port_0.setInterfaceId("9cab2903-70f7-44fd-b681-491d6ae2adb8");
+ ssc_1_int_ha_port_0.setInterfaceName("ssc_1_int_ha_port_0");
+ vServer1.getLInterfaces().getLInterface().add(ssc_1_int_ha_port_0);
+
+ Vserver vServer2 = new Vserver();
+ vServer2.setVserverId("3a4c2ca5-27b3-4ecc-98c5-06804867c4dz");
+ LInterfaces vServer2Linterfaces = new LInterfaces();
+ vServer2.setLInterfaces(vServer2Linterfaces);
+
+ test_port_1.setInterfaceId("9cab2903-70f7-44fd-b681-491d6ae2adz1");
+ test_port_1.setInterfaceName("test_port_1");
+
+
+ test_port_2.setInterfaceId("9cab2903-70f7-44fd-b681-491d6ae2adz2");
+ test_port_2.setInterfaceName("test_port_2");
+
+ vServer2.getLInterfaces().getLInterface().add(test_port_1);
+ vServer2.getLInterfaces().getLInterface().add(test_port_2);
+
+ vserversToAudit.add(vServer1);
+ vserversToAudit.add(vServer2);
+ }
+
+ @Test
+ public void audit_Vserver_Empty_HashSet() throws JsonParseException, JsonMappingException, IOException {
+ Optional<AAIObjectAuditList> actual =
+ auditNova.auditVservers(new HashSet<Vserver>(), tenantId, cloudOwner, cloudRegion);
+ assertEquals(Optional.empty(), actual);
+ }
+
+ @Test
+ public void audit_Vserver_Found_Test() throws JsonParseException, JsonMappingException, IOException {
+ doReturn(true).when(aaiResourcesMock).exists(vserverURI);
+ doReturn(true).when(aaiResourcesMock).exists(vserverURI2);
+ doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_trusted_port_0_uri);
+ doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_service1_port_0_uri);
+ doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_1_uri);
+ doReturn(Optional.of(ssc_1_mgmt_port_0)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_0_uri);
+ doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_service2_port_0_uri);
+ doReturn(Optional.of(service2_sub_interface_1)).when(aaiResourcesMock).get(LInterface.class,
+ service1_sub_1_uri);
+ doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_int_ha_port_0_uri);
+ doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri);
+ doReturn(Optional.of(test_port_2)).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri);
+
+ doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri);
+ doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri);
+ doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri);
+
+ Optional<AAIObjectAuditList> actual =
+ auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion);
+ String actualString = objectMapper.writeValueAsString(actual.get());
+ String expected = getJson("ExpectedVServerFound.json");
+ JSONAssert.assertEquals(expected, actualString, false);
+ }
+
+ @Test
+ public void audit_Vserver_Found_Test_Network_Not_Found()
+ throws JsonParseException, JsonMappingException, IOException {
+ doReturn(true).when(aaiResourcesMock).exists(vserverURI);
+ doReturn(true).when(aaiResourcesMock).exists(vserverURI2);
+ doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_trusted_port_0_uri);
+ doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_service1_port_0_uri);
+ doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_1_uri);
+ doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_0_uri);
+ doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_service2_port_0_uri);
+ doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_int_ha_port_0_uri);
+ doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri);
+ doReturn(Optional.of(test_port_2)).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri);
+
+ doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri);
+ doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri);
+ doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri);
+
+ Optional<AAIObjectAuditList> actual =
+ auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion);
+ String actualString = objectMapper.writeValueAsString(actual.get());
+ String expected = getJson("VServer_Found_network_Not_Found.json");
+ JSONAssert.assertEquals(expected, actualString, false);
+ }
+
+ @Test
+ public void audit_Vserver_Found_Test_Network_Not_Found_Second_Server()
+ throws JsonParseException, JsonMappingException, IOException {
+ doReturn(true).when(aaiResourcesMock).exists(vserverURI);
+ doReturn(true).when(aaiResourcesMock).exists(vserverURI2);
+ doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_trusted_port_0_uri);
+ doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_service1_port_0_uri);
+ doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_1_uri);
+ doReturn(Optional.of(ssc_1_mgmt_port_0)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_0_uri);
+ doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_service2_port_0_uri);
+ doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_int_ha_port_0_uri);
+ doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri);
+ doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri);
+ doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri);
+ doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri);
+ doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri);
+ Optional<AAIObjectAuditList> actual =
+ auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion);
+ String actualString = objectMapper.writeValueAsString(actual.get());
+ String expected = getJson("VServer_Found_Network_Sec_Server_Not_Found.json");
+ JSONAssert.assertEquals(expected, actualString, false);
+ }
+
+ @Test
+ public void audit_Vserver_Not_Found_Test() throws JsonParseException, JsonMappingException, IOException {
+ doReturn(false).when(aaiResourcesMock).exists(vserverURI);
+ doReturn(false).when(aaiResourcesMock).exists(vserverURI2);
+ Optional<AAIObjectAuditList> actual =
+ auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion);
+ String actualString = objectMapper.writeValueAsString(actual.get());
+ String expected = getJson("Vservers_Not_Found.json");
+ JSONAssert.assertEquals(expected, actualString, false);
+ }
+
+ @Test
+ public void audit_Vserver_first_Not_Found_Test() throws JsonParseException, JsonMappingException, IOException {
+ doReturn(false).when(aaiResourcesMock).exists(vserverURI);
+ doReturn(true).when(aaiResourcesMock).exists(vserverURI2);
+ doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri);
+ doReturn(Optional.of(test_port_2)).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri);
+ Optional<AAIObjectAuditList> actual =
+ auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion);
+ String actualString = objectMapper.writeValueAsString(actual.get());
+ String expected = getJson("Vserver2_Found_VServer1_Not_Found.json");
+ JSONAssert.assertEquals(expected, actualString, false);
+ }
+
+
+ @Test
+ public void doesSubInterfaceExistinAAI_Test() {
+ AAIResourceUri subInterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner,
+ cloudRegion, tenantId, "vserverId", "l-interface", "sub-interface");
+
+ assertEquals(
+ "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/cloudRegion/tenants/tenant/tenantId/vservers/vserver/vserverId/l-interfaces/l-interface/l-interface/l-interfaces/l-interface/sub-interface",
+ subInterfaceURI.build().toString());
+ }
+
+ @Test
+ public void audit_Vserver_Second_Not_Found_Test() throws JsonParseException, JsonMappingException, IOException {
+ doReturn(true).when(aaiResourcesMock).exists(vserverURI);
+ doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_trusted_port_0_uri);
+ doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_service1_port_0_uri);
+ doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_1_uri);
+ doReturn(Optional.of(ssc_1_mgmt_port_0)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_0_uri);
+ doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_service2_port_0_uri);
+ doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class,
+ ssc_1_int_ha_port_0_uri);
+ doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri);
+ doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri);
+ doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri);
+ doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri);
+ doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri);
+
+ doReturn(false).when(aaiResourcesMock).exists(vserverURI2);
+ Optional<AAIObjectAuditList> actual =
+ auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion);
+ String actualString = objectMapper.writeValueAsString(actual.get());
+ String expected = getJson("VServer_Found_Sec_Server_Not_Found2.json");
+
+ JSONAssert.assertEquals(expected, actualString, false);
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get("src/test/resources/" + filename)));
+ }
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java
index e728cfd0d4..bc7ce53b8d 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java
@@ -24,7 +24,6 @@ import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
-
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
@@ -35,7 +34,6 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -48,7 +46,6 @@ import org.onap.aai.domain.yang.Vserver;
import org.onap.so.openstack.utils.MsoHeatUtils;
import org.onap.so.openstack.utils.MsoNeutronUtils;
import org.skyscreamer.jsonassert.JSONAssert;
-
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -61,191 +58,238 @@ import com.woorea.openstack.quantum.model.Port;
@RunWith(MockitoJUnitRunner.Silent.class)
public class HeatStackAuditTest extends HeatStackAudit {
- @InjectMocks
- private HeatStackAudit heatStackAudit = new HeatStackAudit();
-
- @Mock
- private MsoHeatUtils msoHeatUtilsMock;
-
- @Mock
- private MsoNeutronUtils neutronUtilsMock;
-
- @Mock
- private AuditVServer auditVserver;
-
- private static final String cloudRegion = "cloudRegion";
- private static final String tenantId = "tenantId";
-
- private Resources resources = new Resources();
-
- private ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).setSerializationInclusion(Include.NON_NULL);
-
- private ObjectMapper stackObjectMapper = new ObjectMapper().configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true).setSerializationInclusion(Include.NON_NULL);
-
- private List<Optional<Port>> portList = new ArrayList<>();
-
- @Before
- public void setup() throws Exception{
- resources= objectMapper.readValue(new File("src/test/resources/GetResources.json"), Resources.class);
- Port neutronPort1 =stackObjectMapper.readValue(new File("src/test/resources/NeutronPort1.json"), Port.class);
- doReturn(Optional.of(neutronPort1)).when(neutronUtilsMock).getNeutronPort("7ee06d9d-3d18-411c-9d3e-aec930f70413", cloudRegion,tenantId);
- Port neutronPort2 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort2.json"), Port.class);
- doReturn(Optional.of(neutronPort2)).when(neutronUtilsMock).getNeutronPort("27391d94-33af-474a-927d-d409249e8fd3", cloudRegion,tenantId);
- Port neutronPort3 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort3.json"), Port.class);
- doReturn(Optional.of(neutronPort3)).when(neutronUtilsMock).getNeutronPort("fdeedf37-c01e-4ab0-bdd6-8d5fc4913943", cloudRegion,tenantId);
- Port neutronPort4 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort4.json"), Port.class);
- doReturn(Optional.of(neutronPort4)).when(neutronUtilsMock).getNeutronPort("8d93f63e-e972-48c7-ad98-b2122da47315", cloudRegion,tenantId);
- Port neutronPort5 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort5.json"), Port.class);
- doReturn(Optional.of(neutronPort5)).when(neutronUtilsMock).getNeutronPort("0594a2f2-7ea4-42eb-abc2-48ea49677fca", cloudRegion,tenantId);
- Port neutronPort6 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort6.json"), Port.class);
- doReturn(Optional.of(neutronPort6)).when(neutronUtilsMock).getNeutronPort("00bb8407-650e-48b5-b919-33b88d6f8fe3", cloudRegion,tenantId);
-
-
- portList.add(Optional.empty());
- portList.add(Optional.of(neutronPort1));
- portList.add(Optional.of(neutronPort2));
- portList.add(Optional.of(neutronPort3));
- portList.add(Optional.of(neutronPort4));
- portList.add(Optional.of(neutronPort5));
- portList.add(Optional.of(neutronPort6));
- }
-
- @Test
- public void extract_proper_path_Test(){
- Optional<String> actualResult = extractStackPathFromHref("https://orchestration.com:8004/v1/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81");
- assertEquals("/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81", actualResult.get());
- }
-
- @Test
- public void extract_proper_resources_path_Test(){
- Optional<String> actualResult = extractResourcePathFromHref("https://orchestration.com:8004/v1/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81");
- assertEquals("/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81/resources", actualResult.get());
- }
-
- @Test
- public void extract_invalid_uri_Test(){
- Optional<String> actualResult = extractStackPathFromHref("orchestrn.com:8004/v18b44d60a6f94bdcb2738f9e//stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81");
- assertEquals(false, actualResult.isPresent());
- }
-
- @Test
- public void createVserverSet_Test() throws Exception{
- List<Resource> novaResources = resources.getList().stream()
- .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList());
-
- List<Resource> resourceGroups = resources.getList().stream()
- .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType())).collect(Collectors.toList());
-
- Resources service1QueryResponse = objectMapper.readValue(new File("src/test/resources/Service1ResourceGroupResponse.json"), Resources.class);
- doReturn(service1QueryResponse).when(msoHeatUtilsMock).executeHeatClientRequest("/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672/resources", cloudRegion, tenantId, Resources.class);
-
- Resources service2QueryResponse =objectMapper.readValue(new File("src/test/resources/Service2ResourceGroupResponse.json"), Resources.class);
- doReturn(service2QueryResponse).when(msoHeatUtilsMock).executeHeatClientRequest("/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst/447a9b41-714e-434b-b1d0-6cce8d9f0f0c/resources", cloudRegion, tenantId, Resources.class);
-
-
- Stack service2StackQuerySubInt = stackObjectMapper.readValue(new File("src/test/resources/Service2SubInterface0.json"), Stack.class);
- doReturn(service2StackQuerySubInt).when(msoHeatUtilsMock).executeHeatClientRequest("/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", cloudRegion,tenantId, Stack.class);
- Resources service2ResourceQuerySubInt = objectMapper.readValue(new File("src/test/resources/Service2SubInterface1Resources.json"), Resources.class);
- doReturn(service2ResourceQuerySubInt).when(msoHeatUtilsMock).executeHeatClientRequest("/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources", cloudRegion,tenantId, Resources.class);
-
- Stack service1StackQuerySubInt1 =stackObjectMapper.readValue(new File("src/test/resources/Service1SubInterface0.json"), Stack.class);
- doReturn(service1StackQuerySubInt1).when(msoHeatUtilsMock).executeHeatClientRequest("/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-1-fmn5laetg5cs/0d9cd813-2ae1-46c0-9ebb-48081f6cffbb", cloudRegion,tenantId, Stack.class);
- Resources service1ResourceQuerySubInt1 = objectMapper.readValue(new File("src/test/resources/Service1SubInterface0Resources.json"), Resources.class);
- doReturn(service1ResourceQuerySubInt1).when(msoHeatUtilsMock).executeHeatClientRequest("/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-1-fmn5laetg5cs/0d9cd813-2ae1-46c0-9ebb-48081f6cffbb/resources", cloudRegion,tenantId, Resources.class);
-
-
- Stack service1StackQuerySubInt2 =stackObjectMapper.readValue(new File("src/test/resources/Service1SubInterface1.json"), Stack.class);
- doReturn(service1StackQuerySubInt2).when(msoHeatUtilsMock).executeHeatClientRequest("/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m/b7019dd0-2ee9-4447-bdef-ac25676b205a", cloudRegion,tenantId, Stack.class);
- Resources service1ResourceQuerySubInt2 = objectMapper.readValue(new File("src/test/resources/Service1SubInterface1Resources.json"), Resources.class);
- doReturn(service1ResourceQuerySubInt2).when(msoHeatUtilsMock).executeHeatClientRequest("/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m/b7019dd0-2ee9-4447-bdef-ac25676b205a/resources", cloudRegion,tenantId, Resources.class);
-
- Stack service1StackQuerySubInt3 =stackObjectMapper.readValue(new File("src/test/resources/Service1SubInterface2.json"), Stack.class);
- doReturn(service1StackQuerySubInt3).when(msoHeatUtilsMock).executeHeatClientRequest("/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c", cloudRegion,tenantId, Stack.class);
- Resources service1ResourceQuerySubInt3 = objectMapper.readValue(new File("src/test/resources/Service1SubInterface2Resources.json"), Resources.class);
- doReturn(service1ResourceQuerySubInt3).when(msoHeatUtilsMock).executeHeatClientRequest("/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c/resources", cloudRegion,tenantId, Resources.class);
-
- Set<Vserver> vServersToAudit = heatStackAudit.createVserverSet(resources, novaResources,portList);
- Set<Vserver> vserversWithSubInterfaces = heatStackAudit.processSubInterfaces(cloudRegion,tenantId,resourceGroups, vServersToAudit);
-
- String actualValue = objectMapper.writeValueAsString(vserversWithSubInterfaces);
- String expectedValue = getJson("ExpectedVserversToAudit.json");
- JSONAssert.assertEquals(expectedValue, actualValue, false);
- }
-
- @Test
- public void auditHeatStackNoServers_Test() throws Exception{
- Resources getResource = objectMapper.readValue(new File("src/test/resources/Service1ResourceGroupResponse.json"), Resources.class);
- doReturn(getResource).when(msoHeatUtilsMock).queryStackResources(cloudRegion, tenantId, "heatStackName", 3);
-
- Optional<AAIObjectAuditList> actual = heatStackAudit.auditHeatStack(cloudRegion, "cloudOwner", tenantId, "heatStackName");
- assertEquals(true, actual.get().getAuditList().isEmpty());
- }
-
- @Test
- public void auditHeatStackNestedServers_Test() throws Exception{
- Resources getResource = objectMapper.readValue(new File("src/test/resources/GetNestedResources.json"), Resources.class);
- List<Resource> novaResources = getResource.getList().stream()
- .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList());
- List<Resource> resourceGroups = getResource.getList().stream()
- .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType())).collect(Collectors.toList());
-
- doReturn(getResource).when(msoHeatUtilsMock).queryStackResources(cloudRegion, tenantId, "heatStackName", 3);
- Set<Vserver> vServersToAudit = heatStackAudit.createVserverSet(resources, novaResources,portList);
- Set<Vserver> vserversWithSubInterfaces = heatStackAudit.processSubInterfaces(cloudRegion,tenantId,resourceGroups, vServersToAudit);
- String actualValue = objectMapper.writeValueAsString(vserversWithSubInterfaces);
- String expectedValue = getJson("NestedExpectedValue.json");
- JSONAssert.assertEquals(expectedValue, actualValue, false);
- }
-
-
- @Test
- public void findInterfaceInformation_Test(){
- List<Resource> novaResources = resources.getList().stream()
- .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList());
- Set<Vserver> expectedVservers = new HashSet<>();
- Vserver vServer1= new Vserver();
- vServer1.setVserverId("92272b67-d23f-42ca-87fa-7b06a9ec81f3");
- LInterfaces vServer1Linterfaces = new LInterfaces();
- vServer1.setLInterfaces(vServer1Linterfaces);
-
- LInterface ssc_1_trusted_port_0 = new LInterface();
- ssc_1_trusted_port_0.setInterfaceId("7ee06d9d-3d18-411c-9d3e-aec930f70413");
- ssc_1_trusted_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port");
- vServer1.getLInterfaces().getLInterface().add(ssc_1_trusted_port_0);
-
- LInterface ssc_1_svc2_port_0 = new LInterface();
- ssc_1_svc2_port_0.setInterfaceId("27391d94-33af-474a-927d-d409249e8fd3");
- ssc_1_svc2_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port");
- vServer1.getLInterfaces().getLInterface().add(ssc_1_svc2_port_0);
-
- LInterface ssc_1_mgmt_port_1 = new LInterface();
- ssc_1_mgmt_port_1.setInterfaceId("fdeedf37-c01e-4ab0-bdd6-8d5fc4913943");
- ssc_1_mgmt_port_1.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port");
- vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_1);
-
- LInterface ssc_1_mgmt_port_0 = new LInterface();
- ssc_1_mgmt_port_0.setInterfaceId("8d93f63e-e972-48c7-ad98-b2122da47315");
- ssc_1_mgmt_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port");
- vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_0);
-
- LInterface ssc_1_svc1_port_0 = new LInterface();
- ssc_1_svc1_port_0.setInterfaceId("0594a2f2-7ea4-42eb-abc2-48ea49677fca");
- ssc_1_svc1_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port");
- vServer1.getLInterfaces().getLInterface().add(ssc_1_svc1_port_0);
-
- LInterface ssc_1_int_ha_port_0 = new LInterface();
- ssc_1_int_ha_port_0.setInterfaceId("00bb8407-650e-48b5-b919-33b88d6f8fe3");
- ssc_1_int_ha_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port");
- vServer1.getLInterfaces().getLInterface().add(ssc_1_int_ha_port_0);
-
- expectedVservers.add(vServer1);
-
- Set<Vserver> actualVservers = heatStackAudit.createVserverSet(resources, novaResources,portList);
-
- assertThat(actualVservers, sameBeanAs(expectedVservers));
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get("src/test/resources/" + filename)));
- }
+ @InjectMocks
+ private HeatStackAudit heatStackAudit = new HeatStackAudit();
+
+ @Mock
+ private MsoHeatUtils msoHeatUtilsMock;
+
+ @Mock
+ private MsoNeutronUtils neutronUtilsMock;
+
+ @Mock
+ private AuditVServer auditVserver;
+
+ private static final String cloudRegion = "cloudRegion";
+ private static final String tenantId = "tenantId";
+
+ private Resources resources = new Resources();
+
+ private ObjectMapper objectMapper =
+ new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
+ .setSerializationInclusion(Include.NON_NULL);
+
+ private ObjectMapper stackObjectMapper = new ObjectMapper()
+ .configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true).setSerializationInclusion(Include.NON_NULL);
+
+ private List<Optional<Port>> portList = new ArrayList<>();
+
+ @Before
+ public void setup() throws Exception {
+ resources = objectMapper.readValue(new File("src/test/resources/GetResources.json"), Resources.class);
+ Port neutronPort1 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort1.json"), Port.class);
+ doReturn(Optional.of(neutronPort1)).when(neutronUtilsMock)
+ .getNeutronPort("7ee06d9d-3d18-411c-9d3e-aec930f70413", cloudRegion, tenantId);
+ Port neutronPort2 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort2.json"), Port.class);
+ doReturn(Optional.of(neutronPort2)).when(neutronUtilsMock)
+ .getNeutronPort("27391d94-33af-474a-927d-d409249e8fd3", cloudRegion, tenantId);
+ Port neutronPort3 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort3.json"), Port.class);
+ doReturn(Optional.of(neutronPort3)).when(neutronUtilsMock)
+ .getNeutronPort("fdeedf37-c01e-4ab0-bdd6-8d5fc4913943", cloudRegion, tenantId);
+ Port neutronPort4 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort4.json"), Port.class);
+ doReturn(Optional.of(neutronPort4)).when(neutronUtilsMock)
+ .getNeutronPort("8d93f63e-e972-48c7-ad98-b2122da47315", cloudRegion, tenantId);
+ Port neutronPort5 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort5.json"), Port.class);
+ doReturn(Optional.of(neutronPort5)).when(neutronUtilsMock)
+ .getNeutronPort("0594a2f2-7ea4-42eb-abc2-48ea49677fca", cloudRegion, tenantId);
+ Port neutronPort6 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort6.json"), Port.class);
+ doReturn(Optional.of(neutronPort6)).when(neutronUtilsMock)
+ .getNeutronPort("00bb8407-650e-48b5-b919-33b88d6f8fe3", cloudRegion, tenantId);
+
+
+ portList.add(Optional.empty());
+ portList.add(Optional.of(neutronPort1));
+ portList.add(Optional.of(neutronPort2));
+ portList.add(Optional.of(neutronPort3));
+ portList.add(Optional.of(neutronPort4));
+ portList.add(Optional.of(neutronPort5));
+ portList.add(Optional.of(neutronPort6));
+ }
+
+ @Test
+ public void extract_proper_path_Test() {
+ Optional<String> actualResult = extractStackPathFromHref(
+ "https://orchestration.com:8004/v1/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81");
+ assertEquals("/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81", actualResult.get());
+ }
+
+ @Test
+ public void extract_proper_resources_path_Test() {
+ Optional<String> actualResult = extractResourcePathFromHref(
+ "https://orchestration.com:8004/v1/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81");
+ assertEquals("/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81/resources", actualResult.get());
+ }
+
+ @Test
+ public void extract_invalid_uri_Test() {
+ Optional<String> actualResult = extractStackPathFromHref(
+ "orchestrn.com:8004/v18b44d60a6f94bdcb2738f9e//stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81");
+ assertEquals(false, actualResult.isPresent());
+ }
+
+ @Test
+ public void createVserverSet_Test() throws Exception {
+ List<Resource> novaResources = resources.getList().stream().filter(p -> "OS::Nova::Server".equals(p.getType()))
+ .collect(Collectors.toList());
+
+ List<Resource> resourceGroups = resources.getList().stream()
+ .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType())).collect(Collectors.toList());
+
+ Resources service1QueryResponse = objectMapper
+ .readValue(new File("src/test/resources/Service1ResourceGroupResponse.json"), Resources.class);
+ doReturn(service1QueryResponse).when(msoHeatUtilsMock).executeHeatClientRequest(
+ "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672/resources",
+ cloudRegion, tenantId, Resources.class);
+
+ Resources service2QueryResponse = objectMapper
+ .readValue(new File("src/test/resources/Service2ResourceGroupResponse.json"), Resources.class);
+ doReturn(service2QueryResponse).when(msoHeatUtilsMock).executeHeatClientRequest(
+ "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst/447a9b41-714e-434b-b1d0-6cce8d9f0f0c/resources",
+ cloudRegion, tenantId, Resources.class);
+
+
+ Stack service2StackQuerySubInt =
+ stackObjectMapper.readValue(new File("src/test/resources/Service2SubInterface0.json"), Stack.class);
+ doReturn(service2StackQuerySubInt).when(msoHeatUtilsMock).executeHeatClientRequest(
+ "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81",
+ cloudRegion, tenantId, Stack.class);
+ Resources service2ResourceQuerySubInt = objectMapper
+ .readValue(new File("src/test/resources/Service2SubInterface1Resources.json"), Resources.class);
+ doReturn(service2ResourceQuerySubInt).when(msoHeatUtilsMock).executeHeatClientRequest(
+ "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources",
+ cloudRegion, tenantId, Resources.class);
+
+ Stack service1StackQuerySubInt1 =
+ stackObjectMapper.readValue(new File("src/test/resources/Service1SubInterface0.json"), Stack.class);
+ doReturn(service1StackQuerySubInt1).when(msoHeatUtilsMock).executeHeatClientRequest(
+ "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-1-fmn5laetg5cs/0d9cd813-2ae1-46c0-9ebb-48081f6cffbb",
+ cloudRegion, tenantId, Stack.class);
+ Resources service1ResourceQuerySubInt1 = objectMapper
+ .readValue(new File("src/test/resources/Service1SubInterface0Resources.json"), Resources.class);
+ doReturn(service1ResourceQuerySubInt1).when(msoHeatUtilsMock).executeHeatClientRequest(
+ "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-1-fmn5laetg5cs/0d9cd813-2ae1-46c0-9ebb-48081f6cffbb/resources",
+ cloudRegion, tenantId, Resources.class);
+
+
+ Stack service1StackQuerySubInt2 =
+ stackObjectMapper.readValue(new File("src/test/resources/Service1SubInterface1.json"), Stack.class);
+ doReturn(service1StackQuerySubInt2).when(msoHeatUtilsMock).executeHeatClientRequest(
+ "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m/b7019dd0-2ee9-4447-bdef-ac25676b205a",
+ cloudRegion, tenantId, Stack.class);
+ Resources service1ResourceQuerySubInt2 = objectMapper
+ .readValue(new File("src/test/resources/Service1SubInterface1Resources.json"), Resources.class);
+ doReturn(service1ResourceQuerySubInt2).when(msoHeatUtilsMock).executeHeatClientRequest(
+ "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m/b7019dd0-2ee9-4447-bdef-ac25676b205a/resources",
+ cloudRegion, tenantId, Resources.class);
+
+ Stack service1StackQuerySubInt3 =
+ stackObjectMapper.readValue(new File("src/test/resources/Service1SubInterface2.json"), Stack.class);
+ doReturn(service1StackQuerySubInt3).when(msoHeatUtilsMock).executeHeatClientRequest(
+ "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c",
+ cloudRegion, tenantId, Stack.class);
+ Resources service1ResourceQuerySubInt3 = objectMapper
+ .readValue(new File("src/test/resources/Service1SubInterface2Resources.json"), Resources.class);
+ doReturn(service1ResourceQuerySubInt3).when(msoHeatUtilsMock).executeHeatClientRequest(
+ "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c/resources",
+ cloudRegion, tenantId, Resources.class);
+
+ Set<Vserver> vServersToAudit = heatStackAudit.createVserverSet(resources, novaResources, portList);
+ Set<Vserver> vserversWithSubInterfaces =
+ heatStackAudit.processSubInterfaces(cloudRegion, tenantId, resourceGroups, vServersToAudit);
+
+ String actualValue = objectMapper.writeValueAsString(vserversWithSubInterfaces);
+ String expectedValue = getJson("ExpectedVserversToAudit.json");
+ JSONAssert.assertEquals(expectedValue, actualValue, false);
+ }
+
+ @Test
+ public void auditHeatStackNoServers_Test() throws Exception {
+ Resources getResource = objectMapper
+ .readValue(new File("src/test/resources/Service1ResourceGroupResponse.json"), Resources.class);
+ doReturn(getResource).when(msoHeatUtilsMock).queryStackResources(cloudRegion, tenantId, "heatStackName", 3);
+
+ Optional<AAIObjectAuditList> actual =
+ heatStackAudit.auditHeatStack(cloudRegion, "cloudOwner", tenantId, "heatStackName");
+ assertEquals(true, actual.get().getAuditList().isEmpty());
+ }
+
+ @Test
+ public void auditHeatStackNestedServers_Test() throws Exception {
+ Resources getResource =
+ objectMapper.readValue(new File("src/test/resources/GetNestedResources.json"), Resources.class);
+ List<Resource> novaResources = getResource.getList().stream()
+ .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList());
+ List<Resource> resourceGroups = getResource.getList().stream()
+ .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType())).collect(Collectors.toList());
+
+ doReturn(getResource).when(msoHeatUtilsMock).queryStackResources(cloudRegion, tenantId, "heatStackName", 3);
+ Set<Vserver> vServersToAudit = heatStackAudit.createVserverSet(resources, novaResources, portList);
+ Set<Vserver> vserversWithSubInterfaces =
+ heatStackAudit.processSubInterfaces(cloudRegion, tenantId, resourceGroups, vServersToAudit);
+ String actualValue = objectMapper.writeValueAsString(vserversWithSubInterfaces);
+ String expectedValue = getJson("NestedExpectedValue.json");
+ JSONAssert.assertEquals(expectedValue, actualValue, false);
+ }
+
+
+ @Test
+ public void findInterfaceInformation_Test() {
+ List<Resource> novaResources = resources.getList().stream().filter(p -> "OS::Nova::Server".equals(p.getType()))
+ .collect(Collectors.toList());
+ Set<Vserver> expectedVservers = new HashSet<>();
+ Vserver vServer1 = new Vserver();
+ vServer1.setVserverId("92272b67-d23f-42ca-87fa-7b06a9ec81f3");
+ LInterfaces vServer1Linterfaces = new LInterfaces();
+ vServer1.setLInterfaces(vServer1Linterfaces);
+
+ LInterface ssc_1_trusted_port_0 = new LInterface();
+ ssc_1_trusted_port_0.setInterfaceId("7ee06d9d-3d18-411c-9d3e-aec930f70413");
+ ssc_1_trusted_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port");
+ vServer1.getLInterfaces().getLInterface().add(ssc_1_trusted_port_0);
+
+ LInterface ssc_1_svc2_port_0 = new LInterface();
+ ssc_1_svc2_port_0.setInterfaceId("27391d94-33af-474a-927d-d409249e8fd3");
+ ssc_1_svc2_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port");
+ vServer1.getLInterfaces().getLInterface().add(ssc_1_svc2_port_0);
+
+ LInterface ssc_1_mgmt_port_1 = new LInterface();
+ ssc_1_mgmt_port_1.setInterfaceId("fdeedf37-c01e-4ab0-bdd6-8d5fc4913943");
+ ssc_1_mgmt_port_1.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port");
+ vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_1);
+
+ LInterface ssc_1_mgmt_port_0 = new LInterface();
+ ssc_1_mgmt_port_0.setInterfaceId("8d93f63e-e972-48c7-ad98-b2122da47315");
+ ssc_1_mgmt_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port");
+ vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_0);
+
+ LInterface ssc_1_svc1_port_0 = new LInterface();
+ ssc_1_svc1_port_0.setInterfaceId("0594a2f2-7ea4-42eb-abc2-48ea49677fca");
+ ssc_1_svc1_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port");
+ vServer1.getLInterfaces().getLInterface().add(ssc_1_svc1_port_0);
+
+ LInterface ssc_1_int_ha_port_0 = new LInterface();
+ ssc_1_int_ha_port_0.setInterfaceId("00bb8407-650e-48b5-b919-33b88d6f8fe3");
+ ssc_1_int_ha_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port");
+ vServer1.getLInterfaces().getLInterface().add(ssc_1_int_ha_port_0);
+
+ expectedVservers.add(vServer1);
+
+ Set<Vserver> actualVservers = heatStackAudit.createVserverSet(resources, novaResources, portList);
+
+ assertThat(actualVservers, sameBeanAs(expectedVservers));
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get("src/test/resources/" + filename)));
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java
index 4d34d18727..0fd2bd4b7f 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java
@@ -24,13 +24,11 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
-
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.camunda.bpm.client.task.ExternalTask;
import org.hamcrest.Matchers;
import org.junit.Before;
@@ -46,77 +44,79 @@ import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.AAIResourcesClient;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CreateAAIInventoryTest extends CreateAAIInventory {
- @InjectMocks
- private CreateAAIInventory createAAIInventory = new CreateAAIInventory();
-
- @Mock
- private ExternalTask mockExternalTask;
-
- @Mock
- private AAIResourcesClient mockClient;
-
- private ObjectMapper objectMapper = new ObjectMapper();
-
- private AuditInventory auditInventory = new AuditInventory();
-
- AAIObjectAuditList auditListSuccess;
-
- AAIObjectAuditList auditListFailure;
-
- AAIObjectAuditList missingSubInterfaces;
-
- @Before
- public void setup() throws JsonParseException, JsonMappingException, IOException {
- auditInventory.setCloudOwner("cloudOwner");
- auditInventory.setCloudRegion("cloudRegion");
- auditInventory.setTenantId("tenantId");
- auditInventory.setHeatStackName("stackName");
- MockitoAnnotations.initMocks(this);
- auditListSuccess = objectMapper.readValue(new File("src/test/resources/ExpectedVServerFound.json"), AAIObjectAuditList.class);
- auditListFailure = objectMapper.readValue(new File("src/test/resources/Vserver2_Found_VServer1_Not_Found.json"), AAIObjectAuditList.class);
- missingSubInterfaces = objectMapper.readValue(new File("src/test/resources/AuditResultsMissSub.json"), AAIObjectAuditList.class);
- doReturn(auditInventory).when(mockExternalTask).getVariable("auditInventory");
- }
-
- @Test
- public void determineAuditResult_Test() throws Exception{
- boolean actual = createAAIInventory.didAuditFailVserverLInterfaces(auditListSuccess);
- assertEquals(false, actual);
- }
-
- @Test
- public void determineAuditResult_Failure_Test() throws Exception{
- boolean actual = createAAIInventory.didAuditFailVserverLInterfaces(auditListFailure);
- assertEquals(true, actual);
- }
-
- @Test
- public void missing_Sub_Interfaces_Test() throws Exception{
- AAIResourceUri aaiURI2 = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE,
- "cloudOwner", "regionOne", "0422ffb57ba042c0800a29dc85ca70f8", "92272b67-d23f-42ca-87fa-7b06a9ec81f3",
- "tsbc0005v_tsbc0005vm002_svc1_port_0","tsbc0005v_tsbc0005vm002_subint_untrusted_svc1_81");
- AAIResourceUri aaiURI1 = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE,
- "cloudOwner", "regionOne", "0422ffb57ba042c0800a29dc85ca70f8", "92272b67-d23f-42ca-87fa-7b06a9ec81f3",
- "tsbc0005v_tsbc0005vm002_svc2_port_0","tsbc0005v_tsbc0005vm002_subint_untrusted_svc2_103");
- ArgumentCaptor<Optional> captor = ArgumentCaptor.forClass(Optional.class);
- ArgumentCaptor<AAIResourceUri> uriCaptor = ArgumentCaptor.forClass(AAIResourceUri.class);
-
- createAAIInventory.setAaiClient(mockClient);
- createAAIInventory.createInventory(missingSubInterfaces);
- Mockito.verify(mockClient,times(2)).createIfNotExists(uriCaptor.capture(),captor.capture());
-
- List<AAIResourceUri> capturedURI = uriCaptor.getAllValues();
- assertTrue(capturedURI.stream().anyMatch(item -> aaiURI1.build().toString().equals(item.build().toString())));
- assertTrue(capturedURI.stream().anyMatch(item -> aaiURI2.build().toString().equals(item.build().toString())));
-
-
-
- }
+ @InjectMocks
+ private CreateAAIInventory createAAIInventory = new CreateAAIInventory();
+
+ @Mock
+ private ExternalTask mockExternalTask;
+
+ @Mock
+ private AAIResourcesClient mockClient;
+
+ private ObjectMapper objectMapper = new ObjectMapper();
+
+ private AuditInventory auditInventory = new AuditInventory();
+
+ AAIObjectAuditList auditListSuccess;
+
+ AAIObjectAuditList auditListFailure;
+
+ AAIObjectAuditList missingSubInterfaces;
+
+ @Before
+ public void setup() throws JsonParseException, JsonMappingException, IOException {
+ auditInventory.setCloudOwner("cloudOwner");
+ auditInventory.setCloudRegion("cloudRegion");
+ auditInventory.setTenantId("tenantId");
+ auditInventory.setHeatStackName("stackName");
+ MockitoAnnotations.initMocks(this);
+ auditListSuccess = objectMapper.readValue(new File("src/test/resources/ExpectedVServerFound.json"),
+ AAIObjectAuditList.class);
+ auditListFailure = objectMapper.readValue(new File("src/test/resources/Vserver2_Found_VServer1_Not_Found.json"),
+ AAIObjectAuditList.class);
+ missingSubInterfaces = objectMapper.readValue(new File("src/test/resources/AuditResultsMissSub.json"),
+ AAIObjectAuditList.class);
+ doReturn(auditInventory).when(mockExternalTask).getVariable("auditInventory");
+ }
+
+ @Test
+ public void determineAuditResult_Test() throws Exception {
+ boolean actual = createAAIInventory.didAuditFailVserverLInterfaces(auditListSuccess);
+ assertEquals(false, actual);
+ }
+
+ @Test
+ public void determineAuditResult_Failure_Test() throws Exception {
+ boolean actual = createAAIInventory.didAuditFailVserverLInterfaces(auditListFailure);
+ assertEquals(true, actual);
+ }
+
+ @Test
+ public void missing_Sub_Interfaces_Test() throws Exception {
+ AAIResourceUri aaiURI2 = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, "cloudOwner",
+ "regionOne", "0422ffb57ba042c0800a29dc85ca70f8", "92272b67-d23f-42ca-87fa-7b06a9ec81f3",
+ "tsbc0005v_tsbc0005vm002_svc1_port_0", "tsbc0005v_tsbc0005vm002_subint_untrusted_svc1_81");
+ AAIResourceUri aaiURI1 = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, "cloudOwner",
+ "regionOne", "0422ffb57ba042c0800a29dc85ca70f8", "92272b67-d23f-42ca-87fa-7b06a9ec81f3",
+ "tsbc0005v_tsbc0005vm002_svc2_port_0", "tsbc0005v_tsbc0005vm002_subint_untrusted_svc2_103");
+ ArgumentCaptor<Optional> captor = ArgumentCaptor.forClass(Optional.class);
+ ArgumentCaptor<AAIResourceUri> uriCaptor = ArgumentCaptor.forClass(AAIResourceUri.class);
+
+ createAAIInventory.setAaiClient(mockClient);
+ createAAIInventory.createInventory(missingSubInterfaces);
+ Mockito.verify(mockClient, times(2)).createIfNotExists(uriCaptor.capture(), captor.capture());
+
+ List<AAIResourceUri> capturedURI = uriCaptor.getAllValues();
+ assertTrue(capturedURI.stream().anyMatch(item -> aaiURI1.build().toString().equals(item.build().toString())));
+ assertTrue(capturedURI.stream().anyMatch(item -> aaiURI2.build().toString().equals(item.build().toString())));
+
+
+
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/EmbeddedMariaDbConfig.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/EmbeddedMariaDbConfig.java
index d552f8d893..66cee2d804 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/EmbeddedMariaDbConfig.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/EmbeddedMariaDbConfig.java
@@ -19,6 +19,7 @@
*/
package org.onap.so.adapters.msoopenstackadapters;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
@@ -40,21 +41,16 @@ public class EmbeddedMariaDbConfig {
@Bean
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/HealthCheckHandlerTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/HealthCheckHandlerTest.java
index 4df9a7af6d..61a8f627a6 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/HealthCheckHandlerTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/HealthCheckHandlerTest.java
@@ -21,9 +21,7 @@
package org.onap.so.adapters.msoopenstackadapters;
import static org.junit.Assert.assertEquals;
-
import javax.ws.rs.core.Response;
-
import org.json.JSONException;
import org.junit.Test;
import org.onap.so.adapters.vnf.BaseRestTestUtils;
@@ -33,15 +31,15 @@ import org.springframework.http.ResponseEntity;
public class HealthCheckHandlerTest extends BaseRestTestUtils {
- @Test
- public void testHealthcheckVnf() throws JSONException {
+ @Test
+ public void testHealthcheckVnf() throws JSONException {
+
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ ResponseEntity<String> response =
+ restTemplate.exchange(createURLWithPort("/manage/health"), HttpMethod.GET, entity, String.class);
- ResponseEntity<String> response = restTemplate.exchange(createURLWithPort("/manage/health"),
- HttpMethod.GET, entity, String.class);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- }
-
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/TestRestTemplateFactory.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/TestRestTemplateFactory.java
index be76a9e365..8d1dd8b69a 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/TestRestTemplateFactory.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/msoopenstackadapters/TestRestTemplateFactory.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.msoopenstackadapters;
import java.util.ArrayList;
import java.util.List;
-
import org.onap.so.client.policy.JettisonStyleMapperProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
@@ -34,17 +33,18 @@ import org.springframework.http.converter.json.MappingJackson2HttpMessageConvert
@Configuration
public class TestRestTemplateFactory {
- @Autowired
- private JettisonStyleMapperProvider objectMapper;
+ @Autowired
+ private JettisonStyleMapperProvider objectMapper;
- @Bean("JettisonStyle")
- public TestRestTemplate createRestTemplate() {
- TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
- List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
- MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
- jsonMessageConverter.setObjectMapper(objectMapper.getMapper());
- restTemplate.getRestTemplate().getMessageConverters().removeIf(m -> m.getClass().getName().equals(MappingJackson2HttpMessageConverter.class.getName()));
- restTemplate.getRestTemplate().getMessageConverters().add(jsonMessageConverter);
- return restTemplate;
- }
+ @Bean("JettisonStyle")
+ public TestRestTemplate createRestTemplate() {
+ TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
+ List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
+ MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
+ jsonMessageConverter.setObjectMapper(objectMapper.getMapper());
+ restTemplate.getRestTemplate().getMessageConverters()
+ .removeIf(m -> m.getClass().getName().equals(MappingJackson2HttpMessageConverter.class.getName()));
+ restTemplate.getRestTemplate().getMessageConverters().add(jsonMessageConverter);
+ return restTemplate;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailPolicyRefSeqTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailPolicyRefSeqTest.java
index 46bf21722c..dd59121a39 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailPolicyRefSeqTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailPolicyRefSeqTest.java
@@ -21,16 +21,14 @@
package org.onap.so.adapters.network;
import static org.junit.Assert.assertTrue;
-
import org.junit.Test;
public class ContrailPolicyRefSeqTest {
- @Test
- public void ContrailPolicyRefSeqJson_Test()
- {
- ContrailPolicyRefSeq cprs = new ContrailPolicyRefSeq("majorVersion 1","minorVersion 0.02");
- assertTrue(cprs.toString().contains("majorVersion 1"));
- assertTrue(cprs.toString().contains("minorVersion 0.02"));
- }
-
+ @Test
+ public void ContrailPolicyRefSeqJson_Test() {
+ ContrailPolicyRefSeq cprs = new ContrailPolicyRefSeq("majorVersion 1", "minorVersion 0.02");
+ assertTrue(cprs.toString().contains("majorVersion 1"));
+ assertTrue(cprs.toString().contains("minorVersion 0.02"));
+ }
+
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailPolicyRefTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailPolicyRefTest.java
index 7a0f3d0551..e8e14417c0 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailPolicyRefTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailPolicyRefTest.java
@@ -21,19 +21,17 @@
package org.onap.so.adapters.network;
import static org.junit.Assert.assertTrue;
-
import org.junit.Test;
public class ContrailPolicyRefTest {
- @Test
- public void ContrailPolicyRef_Test()
- {
- ContrailPolicyRef ref = new ContrailPolicyRef();
- ref.populate("majorVersion 1", "minorVersion 0.02");
- String strJson = ref.toJsonString();
- assertTrue(strJson.contains("majorVersion 1"));
- assertTrue(strJson.contains("minorVersion 0.02"));
- }
-
-} \ No newline at end of file
+ @Test
+ public void ContrailPolicyRef_Test() {
+ ContrailPolicyRef ref = new ContrailPolicyRef();
+ ref.populate("majorVersion 1", "minorVersion 0.02");
+ String strJson = ref.toJsonString();
+ assertTrue(strJson.contains("majorVersion 1"));
+ assertTrue(strJson.contains("minorVersion 0.02"));
+ }
+
+}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailSubnetHostRouteTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailSubnetHostRouteTest.java
index ca8a45e8dc..eb8395cd9b 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailSubnetHostRouteTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailSubnetHostRouteTest.java
@@ -1,26 +1,20 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.adapters.network;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.openstack.beans.HostRoute;
@@ -28,6 +22,7 @@ public class ContrailSubnetHostRouteTest {
private ContrailSubnetHostRoute cshr = new ContrailSubnetHostRoute();
HostRoute hr = new HostRoute();
+
@Test
public void testContrailSubnetHostRoute() {
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailSubnetHostRoutesTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailSubnetHostRoutesTest.java
index fd17c37e6d..eb8912f56d 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailSubnetHostRoutesTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/ContrailSubnetHostRoutesTest.java
@@ -1,29 +1,22 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.adapters.network;
import static org.junit.Assert.*;
-
import java.util.List;
-
import org.junit.Test;
public class ContrailSubnetHostRoutesTest {
@@ -31,6 +24,7 @@ public class ContrailSubnetHostRoutesTest {
ContrailSubnetHostRoutes cshr = new ContrailSubnetHostRoutes();
List<ContrailSubnetHostRoute> host_routes;
StringBuilder buf = new StringBuilder();
+
@Test
public void testContrailSubnetHostRoutes() {
cshr.setHost_routes(host_routes);
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MSONetworkAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MSONetworkAdapterImplTest.java
index 7bfb8c1d76..4dcb7c8710 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MSONetworkAdapterImplTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MSONetworkAdapterImplTest.java
@@ -27,13 +27,11 @@ import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import static org.junit.Assert.assertEquals;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackDeleteNeutronNetwork;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackDeleteStack_200;
@@ -57,419 +55,455 @@ import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenstackPost;
public class MSONetworkAdapterImplTest extends BaseRestTestUtils {
- public static final String NETWORK_ID = "43173f6a-d699-414b-888f-ab243dda6dfe";
- public static final String NETWORK_NAME = "vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0";
+ public static final String NETWORK_ID = "43173f6a-d699-414b-888f-ab243dda6dfe";
+ public static final String NETWORK_NAME = "vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0";
+
+ @Test
+ public void createNetworkByModelNameNeutronModeGetNetworkException() throws IOException {
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- @Test
- public void createNetworkByModelNameNeutronModeGetNetworkException() throws IOException{
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenstackGet(wireMockServer, "/mockPublicUrl/v2.0/networks", HttpStatus.SC_INTERNAL_SERVER_ERROR);
- mockOpenstackGet(wireMockServer, "/mockPublicUrl/v2.0/networks",HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/CreateNetwork_NEUTRON_Mode.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork_NEUTRON_Mode.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void createNetworkByModelNameNeutronModeCreateNetworkException() throws IOException {
- @Test
- public void createNetworkByModelNameNeutronModeCreateNetworkException() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetNeutronNetwork_404(wireMockServer, "dvspg-VCE_VPE-mtjnj40avbc");
- mockOpenStackGetNeutronNetwork_404(wireMockServer, "dvspg-VCE_VPE-mtjnj40avbc");
+ mockOpenStackGetAllNeutronNetworks_404(wireMockServer);
- mockOpenStackGetAllNeutronNetworks_404(wireMockServer);
+ mockOpenstackPost(wireMockServer, "/mockPublicUrl/v2.0/networks", HttpStatus.SC_INTERNAL_SERVER_ERROR);
- mockOpenstackPost(wireMockServer, "/mockPublicUrl/v2.0/networks", HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/CreateNetwork_NEUTRON_Mode.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork_NEUTRON_Mode.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void createNetworkByModelNameNeutronMode() throws IOException {
- @Test
- public void createNetworkByModelNameNeutronMode() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetNeutronNetwork_404(wireMockServer, "dvspg-VCE_VPE-mtjnj40avbc");
- mockOpenStackGetNeutronNetwork_404(wireMockServer, "dvspg-VCE_VPE-mtjnj40avbc");
+ mockOpenStackGetAllNeutronNetworks_404(wireMockServer);
- mockOpenStackGetAllNeutronNetworks_404(wireMockServer);
+ mockOpenStackPostNeutronNetwork_200(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json");
- mockOpenStackPostNeutronNetwork_200(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json");
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/CreateNetwork_NEUTRON_Mode.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork_NEUTRON_Mode.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void createNetworkByModelNameAlreadyExistNeutronMode() throws IOException {
- @Test
- public void createNetworkByModelNameAlreadyExistNeutronMode() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetAllNeutronNetworks_200(wireMockServer, "OpenstackGetNeutronNetworks.json");
- mockOpenStackGetAllNeutronNetworks_200(wireMockServer, "OpenstackGetNeutronNetworks.json");
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/CreateNetwork_NEUTRON_Mode.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork_NEUTRON_Mode.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void createNetworkByModelNameAlreadyExistNeutronModeFailIfExistTrue() throws IOException {
- @Test
- public void createNetworkByModelNameAlreadyExistNeutronModeFailIfExistTrue() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetAllNeutronNetworks_200(wireMockServer, "OpenstackGetNeutronNetworks.json");
- mockOpenStackGetAllNeutronNetworks_200(wireMockServer, "OpenstackGetNeutronNetworks.json");
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/CreateNetwork_NEUTRON_Mode_Fail_If_Exist_True.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork_NEUTRON_Mode_Fail_If_Exist_True.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void createNetworkByModelNameHeatMode() throws IOException {
- @Test
- public void createNetworkByModelNameHeatMode() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStack_404(wireMockServer, "dvspg-VCE_VPE-mtjnj40avbc");
- mockOpenStackGetStack_404(wireMockServer, "dvspg-VCE_VPE-mtjnj40avbc");
+ mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack.json");
- mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack.json");
+ mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json",
+ "dvspg-VCE_VPE-mtjnj40avbc/stackId");
- mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", "dvspg-VCE_VPE-mtjnj40avbc/stackId");
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void createNetworkByModelNameAlreadyExistHeatMode() throws IOException {
- @Test
- public void createNetworkByModelNameAlreadyExistHeatMode() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack.json");
- mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack.json");
+ mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json",
+ "dvspg-VCE_VPE-mtjnj40avbc");
- mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", "dvspg-VCE_VPE-mtjnj40avbc");
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void createNetworkByModelNameAlreadyExistHeatModeFailIfExistTrue() throws IOException {
- @Test
- public void createNetworkByModelNameAlreadyExistHeatModeFailIfExistTrue() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json",
+ "dvspg-VCE_VPE-mtjnj40avbc");
- mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", "dvspg-VCE_VPE-mtjnj40avbc");
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/CreateNetwork_Fail_If_Exist_True.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork_Fail_If_Exist_True.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void createNetworkByModelNameHeatModeQueryNetworkException() throws IOException {
- @Test
- public void createNetworkByModelNameHeatModeQueryNetworkException() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenstackGet(wireMockServer, "/mockPublicUrl/stacks/dvspg-VCE_VPE-mtjnj40avbc",
+ HttpStatus.SC_INTERNAL_SERVER_ERROR);
- mockOpenstackGet(wireMockServer, "/mockPublicUrl/stacks/dvspg-VCE_VPE-mtjnj40avbc",HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void createNetworkByModelNameHeatModeCreateNetworkException() throws IOException {
- @Test
- public void createNetworkByModelNameHeatModeCreateNetworkException() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStack_404(wireMockServer, "dvspg-VCE_VPE-mtjnj40avbc");
- mockOpenStackGetStack_404(wireMockServer, "dvspg-VCE_VPE-mtjnj40avbc");
+ mockOpenstackPost(wireMockServer, "/mockPublicUrl/stacks", HttpStatus.SC_INTERNAL_SERVER_ERROR);
- mockOpenstackPost(wireMockServer, "/mockPublicUrl/stacks",HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void createNetworkByModelNameCloudSiteNotPresentError() throws IOException {
- @Test
- public void createNetworkByModelNameCloudSiteNotPresentError() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack.json");
- mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack.json");
+ mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json",
+ "dvspg-VCE_VPE-mtjnj40avbc");
- mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", "dvspg-VCE_VPE-mtjnj40avbc");
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/CreateNetwork_InvalidCloudSiteId.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/CreateNetwork_InvalidCloudSiteId.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void deleteNetworkHeatModeSuccess() throws IOException {
- @Test
- public void deleteNetworkHeatModeSuccess() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackDeleteOrUpdateComplete_200(wireMockServer, "OpenstackResponse_Stack_DeleteComplete.json");
- mockOpenStackGetStackDeleteOrUpdateComplete_200(wireMockServer, "OpenstackResponse_Stack_DeleteComplete.json");
+ mockOpenStackDeleteStack_200(wireMockServer);
- mockOpenStackDeleteStack_200(wireMockServer);
+ mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
- mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response = sendXMLRequest(inputStream("/DeleteNetwork.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/DeleteNetwork.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void deleteNetworkDeleteStackException() throws IOException {
- @Test
- public void deleteNetworkDeleteStackException() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackDeleteOrUpdateComplete_200(wireMockServer, "OpenstackResponse_Stack_DeleteComplete.json");
- mockOpenStackGetStackDeleteOrUpdateComplete_200(wireMockServer, "OpenstackResponse_Stack_DeleteComplete.json");
+ mockOpenStackDeleteStack_500(wireMockServer);
- mockOpenStackDeleteStack_500(wireMockServer);
+ mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
- mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response = sendXMLRequest(inputStream("/DeleteNetwork.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/DeleteNetwork.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void deleteNetworkError() throws IOException {
- @Test
- public void deleteNetworkError() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackDeleteOrUpdateComplete_200(wireMockServer, "OpenstackResponse_Stack_DeleteComplete.json");
- mockOpenStackGetStackDeleteOrUpdateComplete_200(wireMockServer, "OpenstackResponse_Stack_DeleteComplete.json");
+ mockOpenStackDeleteStack_200(wireMockServer);
- mockOpenStackDeleteStack_200(wireMockServer);
+ mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json",
+ "43173f6a-d699-414b-888f-ab243dda6dfe");
- mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", "43173f6a-d699-414b-888f-ab243dda6dfe");
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/DeleteNetwork.xml").replace("mtn13", ""), uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/DeleteNetwork.xml").replace("mtn13",""), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ @Test
+ public void deleteNetworkNeureonMode() throws IOException {
- @Test
- public void deleteNetworkNeureonMode() throws IOException{
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", NETWORK_ID, HttpStatus.SC_OK);
- mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",NETWORK_ID,HttpStatus.SC_OK);
+ mockOpenStackDeleteNeutronNetwork(wireMockServer, NETWORK_ID, HttpStatus.SC_OK);
- mockOpenStackDeleteNeutronNetwork(wireMockServer, NETWORK_ID,HttpStatus.SC_OK);
-
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/DeleteNetwork.xml").replace("CONTRAIL30_BASIC","CONTRAIL31_GNDIRECT"), uri, HttpMethod.POST);
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/DeleteNetwork.xml").replace("CONTRAIL30_BASIC", "CONTRAIL31_GNDIRECT"),
+ uri, HttpMethod.POST);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
- @Test
- public void deleteNetworkNeutronModeDeleteStackException() throws IOException{
+ @Test
+ public void deleteNetworkNeutronModeDeleteStackException() throws IOException {
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",NETWORK_ID,HttpStatus.SC_OK);
+ mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", NETWORK_ID, HttpStatus.SC_OK);
- mockOpenStackDeleteNeutronNetwork(wireMockServer, NETWORK_ID,HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ mockOpenStackDeleteNeutronNetwork(wireMockServer, NETWORK_ID, HttpStatus.SC_INTERNAL_SERVER_ERROR);
- //mockOpenStackGetStackCreated_200("OpenstackResponse_Stack_Created.json", NETWORK_ID);
+ // mockOpenStackGetStackCreated_200("OpenstackResponse_Stack_Created.json", NETWORK_ID);
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/DeleteNetwork.xml").replace("CONTRAIL30_BASIC","CONTRAIL31_GNDIRECT"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/DeleteNetwork.xml").replace("CONTRAIL30_BASIC", "CONTRAIL31_GNDIRECT"),
+ uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- @Test
- public void updateNetworkNeutronModeSuccess() throws IOException{
+ @Test
+ public void updateNetworkNeutronModeSuccess() throws IOException {
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",NETWORK_ID,HttpStatus.SC_OK);
- mockOpenStackPutNeutronNetwork_200(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json",NETWORK_ID);
+ mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", NETWORK_ID, HttpStatus.SC_OK);
+ mockOpenStackPutNeutronNetwork_200(wireMockServer, "OpenstackCreateNeutronNetworkResponse.json", NETWORK_ID);
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/UpdateNetwork.xml").replace("CONTRAIL30_BASIC","CONTRAIL31_GNDIRECT"), uri, HttpMethod.POST);
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/UpdateNetwork.xml").replace("CONTRAIL30_BASIC", "CONTRAIL31_GNDIRECT"),
+ uri, HttpMethod.POST);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
- @Test
- public void updateNetworkNeutronUpdateException() throws IOException{
+ @Test
+ public void updateNetworkNeutronUpdateException() throws IOException {
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",NETWORK_ID,HttpStatus.SC_OK);
- mockOpenStackPutNeutronNetwork(wireMockServer, NETWORK_ID,HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", NETWORK_ID, HttpStatus.SC_OK);
+ mockOpenStackPutNeutronNetwork(wireMockServer, NETWORK_ID, HttpStatus.SC_INTERNAL_SERVER_ERROR);
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/UpdateNetwork.xml").replace("CONTRAIL30_BASIC","CONTRAIL31_GNDIRECT"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/UpdateNetwork.xml").replace("CONTRAIL30_BASIC", "CONTRAIL31_GNDIRECT"),
+ uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- @Test
- public void updateNetworkHeatUpdateException() throws IOException{
+ @Test
+ public void updateNetworkHeatUpdateException() throws IOException {
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", NETWORK_NAME);
+ mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", NETWORK_NAME);
- mockOpenStackPutStack(wireMockServer, NETWORK_ID,HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ mockOpenStackPutStack(wireMockServer, NETWORK_ID, HttpStatus.SC_INTERNAL_SERVER_ERROR);
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/UpdateNetwork.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response = sendXMLRequest(inputStream("/UpdateNetwork.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- @Test
- public void updateNetworkHeatQueryException() throws IOException{
+ @Test
+ public void updateNetworkHeatQueryException() throws IOException {
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStack_500(wireMockServer, NETWORK_NAME);
+ mockOpenStackGetStack_500(wireMockServer, NETWORK_NAME);
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/UpdateNetwork.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response = sendXMLRequest(inputStream("/UpdateNetwork.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- @Test
- public void updateNetworkHeatStackNotFound() throws IOException{
+ @Test
+ public void updateNetworkHeatStackNotFound() throws IOException {
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStack_404(wireMockServer, NETWORK_NAME);
+ mockOpenStackGetStack_404(wireMockServer, NETWORK_NAME);
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/UpdateNetwork.xml"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response = sendXMLRequest(inputStream("/UpdateNetwork.xml"), uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- @Test
- public void updateNetworkNeutronQueryException() throws IOException{
+ @Test
+ public void updateNetworkNeutronQueryException() throws IOException {
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetNeutronNetwork(wireMockServer, NETWORK_ID,HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ mockOpenStackGetNeutronNetwork(wireMockServer, NETWORK_ID, HttpStatus.SC_INTERNAL_SERVER_ERROR);
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/UpdateNetwork.xml").replace("CONTRAIL30_BASIC","CONTRAIL31_GNDIRECT"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/UpdateNetwork.xml").replace("CONTRAIL30_BASIC", "CONTRAIL31_GNDIRECT"),
+ uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- @Test
- public void updateNetworkNeutronStackNotFound() throws IOException{
+ @Test
+ public void updateNetworkNeutronStackNotFound() throws IOException {
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetNeutronNetwork(wireMockServer, NETWORK_ID,HttpStatus.SC_NOT_FOUND);
+ mockOpenStackGetNeutronNetwork(wireMockServer, NETWORK_ID, HttpStatus.SC_NOT_FOUND);
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/UpdateNetwork.xml").replace("CONTRAIL30_BASIC","CONTRAIL31_GNDIRECT"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/UpdateNetwork.xml").replace("CONTRAIL30_BASIC", "CONTRAIL31_GNDIRECT"),
+ uri, HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- @Test
- public void queryNetworkHeatModesuccess() throws IOException{
+ @Test
+ public void queryNetworkHeatModesuccess() throws IOException {
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", NETWORK_ID);
+ mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", NETWORK_ID);
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/QueryNetwork.xml").replace("CONTRAIL30_BASIC","CONTRAIL31_GNDIRECT"), uri, HttpMethod.POST);
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/QueryNetwork.xml").replace("CONTRAIL30_BASIC", "CONTRAIL31_GNDIRECT"), uri,
+ HttpMethod.POST);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
- @Test
- public void queryNetworkHeatModeQueryException() throws IOException{
+ @Test
+ public void queryNetworkHeatModeQueryException() throws IOException {
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStack_500(wireMockServer, NETWORK_ID);
+ mockOpenStackGetStack_500(wireMockServer, NETWORK_ID);
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/QueryNetwork.xml").replace("CONTRAIL30_BASIC","CONTRAIL31_GNDIRECT"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/QueryNetwork.xml").replace("CONTRAIL30_BASIC", "CONTRAIL31_GNDIRECT"), uri,
+ HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- @Test
- public void queryNetworkNeutronModeSuccess() throws IOException{
+ @Test
+ public void queryNetworkNeutronModeSuccess() throws IOException {
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json",NETWORK_ID,HttpStatus.SC_OK);
+ mockOpenStackGetNeutronNetwork(wireMockServer, "GetNeutronNetwork.json", NETWORK_ID, HttpStatus.SC_OK);
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/QueryNetwork.xml").replace("CONTRAIL30_BASIC","CONTRAIL31_GNDIRECT"), uri, HttpMethod.POST);
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/QueryNetwork.xml").replace("CONTRAIL30_BASIC", "CONTRAIL31_GNDIRECT"), uri,
+ HttpMethod.POST);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
- @Test
- public void queryNetworkNeutronModeException() throws IOException{
+ @Test
+ public void queryNetworkNeutronModeException() throws IOException {
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetNeutronNetwork(wireMockServer, NETWORK_ID,HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ mockOpenStackGetNeutronNetwork(wireMockServer, NETWORK_ID, HttpStatus.SC_INTERNAL_SERVER_ERROR);
- String uri = "/services/NetworkAdapter";
- headers.set("X-ECOMP-RequestID", "123456789456127");
- ResponseEntity<String> response = sendXMLRequest(inputStream("/QueryNetwork.xml").replace("CONTRAIL30_BASIC","CONTRAIL31_GNDIRECT"), uri, HttpMethod.POST);
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- }
+ String uri = "/services/NetworkAdapter";
+ headers.set("X-ECOMP-RequestID", "123456789456127");
+ ResponseEntity<String> response =
+ sendXMLRequest(inputStream("/QueryNetwork.xml").replace("CONTRAIL30_BASIC", "CONTRAIL31_GNDIRECT"), uri,
+ HttpMethod.POST);
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ }
- public ResponseEntity<String> sendXMLRequest(String requestJson, String uriPath, HttpMethod reqMethod){
- headers.set("Accept", MediaType.APPLICATION_XML);
- headers.set("Content-Type", MediaType.APPLICATION_XML);
+ public ResponseEntity<String> sendXMLRequest(String requestJson, String uriPath, HttpMethod reqMethod) {
+ headers.set("Accept", MediaType.APPLICATION_XML);
+ headers.set("Content-Type", MediaType.APPLICATION_XML);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath));
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath));
- HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
- ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(),
- reqMethod, request, String.class);
+ HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), reqMethod, request, String.class);
- return response;
- }
+ return response;
+ }
- public String inputStream(String JsonInput)throws IOException{
- JsonInput = "src/test/resources/" + JsonInput;
- String input = new String(Files.readAllBytes(Paths.get(JsonInput)));
- return input;
- }
+ public String inputStream(String JsonInput) throws IOException {
+ JsonInput = "src/test/resources/" + JsonInput;
+ String input = new String(Files.readAllBytes(Paths.get(JsonInput)));
+ return input;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImplTest.java
index 21ca860b54..727f18902a 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImplTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImplTest.java
@@ -31,11 +31,9 @@ import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackDeleteOrU
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPostStacks_200;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPutPublicUrlStackByNameAndID_NETWORK2_200;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccessQueryNetwork;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
-
import org.apache.http.HttpStatus;
import org.junit.Test;
import org.onap.so.adapters.vnf.BaseRestTestUtils;
@@ -45,233 +43,224 @@ import org.onap.so.openstack.beans.Subnet;
import org.springframework.beans.factory.annotation.Autowired;
public class MsoNetworkAdapterAsyncImplTest extends BaseRestTestUtils {
- @Autowired
- MsoNetworkAdapterAsyncImpl impl;
+ @Autowired
+ MsoNetworkAdapterAsyncImpl impl;
- @Test
- public void healthCheckATest() {
- MsoNetworkAdapterAsyncImpl mNAAimpl = new MsoNetworkAdapterAsyncImpl();
- mNAAimpl.healthCheckA();
- }
+ @Test
+ public void healthCheckATest() {
+ MsoNetworkAdapterAsyncImpl mNAAimpl = new MsoNetworkAdapterAsyncImpl();
+ mNAAimpl.healthCheckA();
+ }
- @Test
- public void rollbackNetworkATest() throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
- .withRequestBody(containing("tenantId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/notificationUrl"))
- .withRequestBody(containing("<completed>true</completed>"))
- .willReturn(aResponse()
- .withBody("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:net=\"http://org.onap.so/networkNotify\">\n" +
- " <soapenv:Header/>\n" +
- " <soapenv:Body>\n" +
- " <net:rollbackNetworkNotificationResponse>\n" +
- " </net:rollbackNetworkNotificationResponse>\n" +
- " </soapenv:Body>\n" +
- "</soapenv:Envelope>")
- .withStatus(HttpStatus.SC_OK)));
- NetworkRollback nrb = getNetworkRollback("mtn13");
- impl.rollbackNetworkA(nrb, "messageId", "http://localhost:"+wireMockPort+"/notificationUrl");
- }
+ @Test
+ public void rollbackNetworkATest() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).withRequestBody(containing("tenantId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/notificationUrl"))
+ .withRequestBody(containing("<completed>true</completed>"))
+ .willReturn(aResponse().withBody(
+ "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:net=\"http://org.onap.so/networkNotify\">\n"
+ + " <soapenv:Header/>\n" + " <soapenv:Body>\n"
+ + " <net:rollbackNetworkNotificationResponse>\n"
+ + " </net:rollbackNetworkNotificationResponse>\n" + " </soapenv:Body>\n"
+ + "</soapenv:Envelope>")
+ .withStatus(HttpStatus.SC_OK)));
+ NetworkRollback nrb = getNetworkRollback("mtn13");
+ impl.rollbackNetworkA(nrb, "messageId", "http://localhost:" + wireMockPort + "/notificationUrl");
+ }
- @Test
- public void rollbackNetworkATest_NotifyException() throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
- .withRequestBody(containing("tenantId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/notificationUrl"))
- .withRequestBody(containing("<completed>true</completed>"))
- .willReturn(aResponse()
- .withStatus(HttpStatus.SC_NOT_FOUND)));
- NetworkRollback nrb = getNetworkRollback("mtn13");
- impl.rollbackNetworkA(nrb, "messageId", "http://localhost:"+wireMockPort+"/notificationUrl");
- }
+ @Test
+ public void rollbackNetworkATest_NotifyException() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).withRequestBody(containing("tenantId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(
+ post(urlPathEqualTo("/notificationUrl")).withRequestBody(containing("<completed>true</completed>"))
+ .willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
+ NetworkRollback nrb = getNetworkRollback("mtn13");
+ impl.rollbackNetworkA(nrb, "messageId", "http://localhost:" + wireMockPort + "/notificationUrl");
+ }
- private NetworkRollback getNetworkRollback(String cloudId) {
- NetworkRollback nrb = new NetworkRollback();
- nrb.setCloudId(cloudId);
- nrb.setMsoRequest(new MsoRequest());
- nrb.setModelCustomizationUuid("3bdbb104-476c-483e-9f8b-c095b3d3068c");
- nrb.setNetworkCreated(true);
- nrb.setNetworkId("networkId");
- nrb.setNetworkName("networkName");
- nrb.setNetworkStackId("networkStackId");
- nrb.setNetworkType("networkType");
- nrb.setNeutronNetworkId("neutronNetworkId");
- nrb.setPhysicalNetwork("physicalNetwork");
- nrb.setTenantId("tenantId");
- nrb.setVlans(new ArrayList<>());
- return nrb;
- }
+ private NetworkRollback getNetworkRollback(String cloudId) {
+ NetworkRollback nrb = new NetworkRollback();
+ nrb.setCloudId(cloudId);
+ nrb.setMsoRequest(new MsoRequest());
+ nrb.setModelCustomizationUuid("3bdbb104-476c-483e-9f8b-c095b3d3068c");
+ nrb.setNetworkCreated(true);
+ nrb.setNetworkId("networkId");
+ nrb.setNetworkName("networkName");
+ nrb.setNetworkStackId("networkStackId");
+ nrb.setNetworkType("networkType");
+ nrb.setNeutronNetworkId("neutronNetworkId");
+ nrb.setPhysicalNetwork("physicalNetwork");
+ nrb.setTenantId("tenantId");
+ nrb.setVlans(new ArrayList<>());
+ return nrb;
+ }
- @Test
- public void rollbackNetworkATestNetworkException() {
- NetworkRollback nrb = getNetworkRollback("cloudId");
+ @Test
+ public void rollbackNetworkATestNetworkException() {
+ NetworkRollback nrb = getNetworkRollback("cloudId");
- impl.rollbackNetworkA(nrb, "messageId", "http://localhost");
- }
+ impl.rollbackNetworkA(nrb, "messageId", "http://localhost");
+ }
- @Test
- public void noRollbackNetworkATest() {
- impl.rollbackNetworkA(null, "messageId", "http://localhost");
- }
+ @Test
+ public void noRollbackNetworkATest() {
+ impl.rollbackNetworkA(null, "messageId", "http://localhost");
+ }
- @Test
- public void deleteNetworkATest() throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
- .withRequestBody(containing("tenantId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/notificationUrl"))
- .withRequestBody(containing("<completed>true</completed>"))
- .willReturn(aResponse()
- .withBody("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:net=\"http://org.onap.so/networkNotify\">\n" +
- " <soapenv:Header/>\n" +
- " <soapenv:Body>\n" +
- " <net:deleteNetworkNotificationResponse>\n" +
- " </net:deleteNetworkNotificationResponse>\n" +
- " </soapenv:Body>\n" +
- "</soapenv:Envelope>")
- .withStatus(HttpStatus.SC_OK)));
- impl.deleteNetworkA("mtn13", "tenantId", "networkType", "modelCustomizationUuid", "networkId",
- "messageId", new MsoRequest(), "http://localhost:"+wireMockPort+"/notificationUrl");
- }
+ @Test
+ public void deleteNetworkATest() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).withRequestBody(containing("tenantId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/notificationUrl"))
+ .withRequestBody(containing("<completed>true</completed>"))
+ .willReturn(aResponse().withBody(
+ "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:net=\"http://org.onap.so/networkNotify\">\n"
+ + " <soapenv:Header/>\n" + " <soapenv:Body>\n"
+ + " <net:deleteNetworkNotificationResponse>\n"
+ + " </net:deleteNetworkNotificationResponse>\n" + " </soapenv:Body>\n"
+ + "</soapenv:Envelope>")
+ .withStatus(HttpStatus.SC_OK)));
+ impl.deleteNetworkA("mtn13", "tenantId", "networkType", "modelCustomizationUuid", "networkId", "messageId",
+ new MsoRequest(), "http://localhost:" + wireMockPort + "/notificationUrl");
+ }
- @Test
- public void deleteNetworkATest_NotifyException() throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
- .withRequestBody(containing("tenantId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/notificationUrl"))
- .withRequestBody(containing("<completed>true</completed>"))
- .willReturn(aResponse()
- .withStatus(HttpStatus.SC_NOT_FOUND)));
- impl.deleteNetworkA("mtn13", "tenantId", "networkType", "modelCustomizationUuid", "networkId",
- "messageId", new MsoRequest(), "http://localhost:"+wireMockPort+"/notificationUrl");
- }
+ @Test
+ public void deleteNetworkATest_NotifyException() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).withRequestBody(containing("tenantId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(
+ post(urlPathEqualTo("/notificationUrl")).withRequestBody(containing("<completed>true</completed>"))
+ .willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
+ impl.deleteNetworkA("mtn13", "tenantId", "networkType", "modelCustomizationUuid", "networkId", "messageId",
+ new MsoRequest(), "http://localhost:" + wireMockPort + "/notificationUrl");
+ }
- @Test
- public void deleteNetworkATest_NetworkException() {
- impl.deleteNetworkA("cloudSiteId", "tenantId", "networkType", "modelCustomizationUuid", "networkId",
- "messageId", new MsoRequest(), "http://localhost:"+wireMockPort+"/notificationUrl");
- }
+ @Test
+ public void deleteNetworkATest_NetworkException() {
+ impl.deleteNetworkA("cloudSiteId", "tenantId", "networkType", "modelCustomizationUuid", "networkId",
+ "messageId", new MsoRequest(), "http://localhost:" + wireMockPort + "/notificationUrl");
+ }
- @Test
- public void updateNetworkATest() throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
- .withRequestBody(containing("tenantId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
- mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", "dvspg-VCE_VPE-mtjnj40avbc");
- mockOpenStackGetStackDeleteOrUpdateComplete_200(wireMockServer, "OpenstackResponse_Stack_UpdateComplete.json");
- mockOpenStackPutPublicUrlStackByNameAndID_NETWORK2_200(wireMockServer);
- wireMockServer.stubFor(post(urlPathEqualTo("/notificationUrl"))
- .withRequestBody(containing("updateNetworkNotification"))
- .willReturn(aResponse()
- .withBody("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:net=\"http://org.onap.so/networkNotify\">\n" +
- " <soapenv:Header/>\n" +
- " <soapenv:Body>\n" +
- " <net:updateNetworkNotificationResponse>\n" +
- " </net:updateNetworkNotificationResponse>\n" +
- " </soapenv:Body>\n" +
- "</soapenv:Envelope>")
- .withStatus(HttpStatus.SC_OK)));
- HashMap<String,String> networkParams = new HashMap<String,String>();
- networkParams.put("shared", "true");
- networkParams.put("external", "false");
- impl.updateNetworkA("mtn13", "tenantId", "networkType", "3bdbb104-476c-483e-9f8b-c095b3d3068c", "dvspg-VCE_VPE-mtjnj40avbc",
- "dvspg-VCE_VPE-mtjnj40avbc", "physicalNetworkName", new ArrayList<>(), new ArrayList<Subnet>(), networkParams, "messageId",
- new MsoRequest(), "http://localhost:"+wireMockPort+"/notificationUrl");
- }
+ @Test
+ public void updateNetworkATest() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).withRequestBody(containing("tenantId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
+ mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json",
+ "dvspg-VCE_VPE-mtjnj40avbc");
+ mockOpenStackGetStackDeleteOrUpdateComplete_200(wireMockServer, "OpenstackResponse_Stack_UpdateComplete.json");
+ mockOpenStackPutPublicUrlStackByNameAndID_NETWORK2_200(wireMockServer);
+ wireMockServer.stubFor(post(urlPathEqualTo("/notificationUrl"))
+ .withRequestBody(containing("updateNetworkNotification"))
+ .willReturn(aResponse().withBody(
+ "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:net=\"http://org.onap.so/networkNotify\">\n"
+ + " <soapenv:Header/>\n" + " <soapenv:Body>\n"
+ + " <net:updateNetworkNotificationResponse>\n"
+ + " </net:updateNetworkNotificationResponse>\n" + " </soapenv:Body>\n"
+ + "</soapenv:Envelope>")
+ .withStatus(HttpStatus.SC_OK)));
+ HashMap<String, String> networkParams = new HashMap<String, String>();
+ networkParams.put("shared", "true");
+ networkParams.put("external", "false");
+ impl.updateNetworkA("mtn13", "tenantId", "networkType", "3bdbb104-476c-483e-9f8b-c095b3d3068c",
+ "dvspg-VCE_VPE-mtjnj40avbc", "dvspg-VCE_VPE-mtjnj40avbc", "physicalNetworkName", new ArrayList<>(),
+ new ArrayList<Subnet>(), networkParams, "messageId", new MsoRequest(),
+ "http://localhost:" + wireMockPort + "/notificationUrl");
+ }
- @Test
- public void updateNetworkATest_NotifyExcpetion() throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
- .withRequestBody(containing("tenantId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
- mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", "dvspg-VCE_VPE-mtjnj40avbc");
- mockOpenStackGetStackDeleteOrUpdateComplete_200(wireMockServer, "OpenstackResponse_Stack_UpdateComplete.json");
- mockOpenStackPutPublicUrlStackByNameAndID_NETWORK2_200(wireMockServer);
- HashMap<String,String> networkParams = new HashMap<String,String>();
- networkParams.put("shared", "true");
- networkParams.put("external", "false");
- impl.updateNetworkA("mtn13", "tenantId", "networkType", "3bdbb104-476c-483e-9f8b-c095b3d3068c", "dvspg-VCE_VPE-mtjnj40avbc",
- "dvspg-VCE_VPE-mtjnj40avbc", "physicalNetworkName", new ArrayList<>(), new ArrayList<>(), networkParams, "messageId",
- new MsoRequest(), "http://localhost:"+wireMockPort+"/notificationUrl"); }
+ @Test
+ public void updateNetworkATest_NotifyExcpetion() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).withRequestBody(containing("tenantId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
+ mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json",
+ "dvspg-VCE_VPE-mtjnj40avbc");
+ mockOpenStackGetStackDeleteOrUpdateComplete_200(wireMockServer, "OpenstackResponse_Stack_UpdateComplete.json");
+ mockOpenStackPutPublicUrlStackByNameAndID_NETWORK2_200(wireMockServer);
+ HashMap<String, String> networkParams = new HashMap<String, String>();
+ networkParams.put("shared", "true");
+ networkParams.put("external", "false");
+ impl.updateNetworkA("mtn13", "tenantId", "networkType", "3bdbb104-476c-483e-9f8b-c095b3d3068c",
+ "dvspg-VCE_VPE-mtjnj40avbc", "dvspg-VCE_VPE-mtjnj40avbc", "physicalNetworkName", new ArrayList<>(),
+ new ArrayList<>(), networkParams, "messageId", new MsoRequest(),
+ "http://localhost:" + wireMockPort + "/notificationUrl");
+ }
- @Test
- public void updateNetworkATest_NetworkException() {
- impl.updateNetworkA("cloudSiteId", "tenantId", "networkType", "3bdbb104-476c-483e-9f8b-c095b3d3068c", "networkId",
- "dvspg-VCE_VPE-mtjnj40avbc", "physicalNetworkName", new ArrayList<>(), new ArrayList<>(), new HashMap<String,String>(), "messageId",
- new MsoRequest(), "http://localhost:"+wireMockPort+"/notificationUrl");
- }
+ @Test
+ public void updateNetworkATest_NetworkException() {
+ impl.updateNetworkA("cloudSiteId", "tenantId", "networkType", "3bdbb104-476c-483e-9f8b-c095b3d3068c",
+ "networkId", "dvspg-VCE_VPE-mtjnj40avbc", "physicalNetworkName", new ArrayList<>(), new ArrayList<>(),
+ new HashMap<String, String>(), "messageId", new MsoRequest(),
+ "http://localhost:" + wireMockPort + "/notificationUrl");
+ }
- @Test
- public void queryNetworkATest() throws IOException {
- mockOpenStackResponseAccessQueryNetwork(wireMockServer, wireMockPort);
- impl.queryNetworkA("mtn13", "tenantId", "networkId", "messageId", new MsoRequest(),
- "http://localhost:"+wireMockPort+"/notificationUrl");
- }
+ @Test
+ public void queryNetworkATest() throws IOException {
+ mockOpenStackResponseAccessQueryNetwork(wireMockServer, wireMockPort);
+ impl.queryNetworkA("mtn13", "tenantId", "networkId", "messageId", new MsoRequest(),
+ "http://localhost:" + wireMockPort + "/notificationUrl");
+ }
- @Test
- public void createNetworkATest() throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
- .withRequestBody(containing("tenantId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/notificationUrl"))
- .withRequestBody(containing("createNetworkNotification"))
- .willReturn(aResponse()
- .withBody("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:net=\"http://org.onap.so/networkNotify\">\n" +
- " <soapenv:Header/>\n" +
- " <soapenv:Body>\n" +
- " <net:createNetworkNotificationResponse>\n" +
- " </net:createNetworkNotificationResponse>\n" +
- " </soapenv:Body>\n" +
- "</soapenv:Envelope>")
- .withStatus(HttpStatus.SC_OK)));
- mockOpenStackGetStackCreatedVUSP_200(wireMockServer);
- mockOpenStackPostStacks_200(wireMockServer);
- mockOpenStackPostStacks_200(wireMockServer);
- HashMap<String,String> networkParams = new HashMap<String,String>();
- impl.createNetworkA("mtn13", "tenantId", "networkType", "3bdbb104-476c-483e-9f8b-c095b3d3068c", "vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0",
- "physicalNetworkName", new ArrayList<>(), false, false, new ArrayList<>(), networkParams, "messageId",
- new MsoRequest(), "http://localhost:"+wireMockPort+"/notificationUrl");
- }
+ @Test
+ public void createNetworkATest() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).withRequestBody(containing("tenantId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/notificationUrl"))
+ .withRequestBody(containing("createNetworkNotification"))
+ .willReturn(aResponse().withBody(
+ "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:net=\"http://org.onap.so/networkNotify\">\n"
+ + " <soapenv:Header/>\n" + " <soapenv:Body>\n"
+ + " <net:createNetworkNotificationResponse>\n"
+ + " </net:createNetworkNotificationResponse>\n" + " </soapenv:Body>\n"
+ + "</soapenv:Envelope>")
+ .withStatus(HttpStatus.SC_OK)));
+ mockOpenStackGetStackCreatedVUSP_200(wireMockServer);
+ mockOpenStackPostStacks_200(wireMockServer);
+ mockOpenStackPostStacks_200(wireMockServer);
+ HashMap<String, String> networkParams = new HashMap<String, String>();
+ impl.createNetworkA("mtn13", "tenantId", "networkType", "3bdbb104-476c-483e-9f8b-c095b3d3068c",
+ "vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0", "physicalNetworkName", new ArrayList<>(), false,
+ false, new ArrayList<>(), networkParams, "messageId", new MsoRequest(),
+ "http://localhost:" + wireMockPort + "/notificationUrl");
+ }
- @Test
- public void createNetworkATest_NotifyException() throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
- .withRequestBody(containing("tenantId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
- mockOpenStackGetStackCreatedVUSP_200(wireMockServer);
- mockOpenStackPostStacks_200(wireMockServer);
- HashMap<String,String> networkParams = new HashMap<String,String>();
- networkParams.put("shared", "true");
- networkParams.put("external", "false");
- impl.createNetworkA("mtn13", "tenantId", "networkType", "3bdbb104-476c-483e-9f8b-c095b3d3068c", "vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0",
- "physicalNetworkName", new ArrayList<>(), false, false, new ArrayList<>(), networkParams, "messageId",
- new MsoRequest(), "http://localhost:"+wireMockPort+"/notificationUrl");
- }
+ @Test
+ public void createNetworkATest_NotifyException() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).withRequestBody(containing("tenantId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", wireMockPort, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
+ mockOpenStackGetStackCreatedVUSP_200(wireMockServer);
+ mockOpenStackPostStacks_200(wireMockServer);
+ HashMap<String, String> networkParams = new HashMap<String, String>();
+ networkParams.put("shared", "true");
+ networkParams.put("external", "false");
+ impl.createNetworkA("mtn13", "tenantId", "networkType", "3bdbb104-476c-483e-9f8b-c095b3d3068c",
+ "vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0", "physicalNetworkName", new ArrayList<>(), false,
+ false, new ArrayList<>(), networkParams, "messageId", new MsoRequest(),
+ "http://localhost:" + wireMockPort + "/notificationUrl");
+ }
- @Test
- public void createNetworkATest_NetworkException() {
- impl.createNetworkA("mtn13", "tenantId", "networkType", "3bdbb104-476c-483e-9f8b-c095b3d3068c", "vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0",
- "physicalNetworkName", new ArrayList<>(), false, false, new ArrayList<>(), new HashMap<String,String>(), "messageId",
- new MsoRequest(), "http://localhost:"+wireMockPort+"/notificationUrl");
- }
+ @Test
+ public void createNetworkATest_NetworkException() {
+ impl.createNetworkA("mtn13", "tenantId", "networkType", "3bdbb104-476c-483e-9f8b-c095b3d3068c",
+ "vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0", "physicalNetworkName", new ArrayList<>(), false,
+ false, new ArrayList<>(), new HashMap<String, String>(), "messageId", new MsoRequest(),
+ "http://localhost:" + wireMockPort + "/notificationUrl");
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/NetworkAdapterRestTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/NetworkAdapterRestTest.java
index 97392adeef..1f4c205e7a 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/NetworkAdapterRestTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/NetworkAdapterRestTest.java
@@ -36,15 +36,12 @@ import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPublicUrlStackByI
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPublicUrlStackByName_200;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPutPublicUrlStackByNameAndID_200;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccess;
-
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.json.JSONException;
import org.junit.Test;
import org.onap.so.adapters.nwrest.CreateNetworkRequest;
@@ -64,302 +61,306 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
public class NetworkAdapterRestTest extends BaseRestTestUtils {
- @Autowired
- private JettisonStyleMapperProvider jettisonTypeObjectMapper;
- private static final String CLOUDSITE_ID = "mtn13";
- private static final String TENANT_ID = "ba38bc24a2ef4fb2ad2810c894f1938f";
- private static final String NETWORK_ID = "da886914-efb2-4917-b335-c8381528d90b";
- private static final String NETWORK_TYPE = "CONTRAIL30_BASIC";
- private static final String MODEL_CUSTOMIZATION_UUID = "3bdbb104-476c-483e-9f8b-c095b3d308ac";
- private static final String MSO_SERVICE_INSTANCE_ID = "05869d5f-47df-4b45-bbfc-4f03ce0a50bf";
- private static final String MSO_REQUEST_ID = "requestId";
- private static final String NETWORK_NAME = "vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0";
-
- @Test
- public void testCreateNetwork() throws JSONException, JsonParseException, JsonMappingException, IOException {
-
- CreateNetworkRequest request = new CreateNetworkRequest();
- request.setBackout(true);
- request.setSkipAAI(true);
- request.setFailIfExists(false);
- MsoRequest msoReq = new MsoRequest();
- String networkTechnology = "CONTRAIL";
-
- msoReq.setRequestId(MSO_REQUEST_ID);
- msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
- request.setMsoRequest(msoReq);
- request.setCloudSiteId(CLOUDSITE_ID);
- request.setTenantId(TENANT_ID);
- request.setNetworkId(NETWORK_ID);
- request.setNetworkName(NETWORK_NAME);
- request.setNetworkType(NETWORK_TYPE);
- request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
- request.setNetworkTechnology(networkTechnology);
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackPostPublicUrlWithBodyFile_200(wireMockServer);
-
- mockOpenStackGetStackCreatedVUSP_200(wireMockServer);
-
- mockOpenStackGetStackVUSP_404(wireMockServer);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<CreateNetworkRequest> entity = new HttpEntity<CreateNetworkRequest>(request, headers);
- ResponseEntity<CreateNetworkResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/networks"), HttpMethod.POST, entity, CreateNetworkResponse.class);
-
- CreateNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/CreateNetworkResponse.json"), CreateNetworkResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- }
-
- @Test
- public void testCreateNetwork_JSON() throws JSONException, JsonParseException, JsonMappingException, IOException {
-
-
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackPostPublicUrlWithBodyFile_200(wireMockServer);
-
- mockOpenStackGetStackCreatedAppC_200(wireMockServer);
-
- mockOpenStackGetStackAppC_404(wireMockServer);
-
- headers.add("Content-Type", MediaType.APPLICATION_JSON);
- headers.add("Accept", MediaType.APPLICATION_JSON);
-
- String request = readJsonFileAsString("src/test/resources/CreateNetwork.json");
- HttpEntity<String> entity = new HttpEntity<String>(request, headers);
-
- ResponseEntity<CreateNetworkResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/networks"), HttpMethod.POST, entity, CreateNetworkResponse.class);
-
- CreateNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/CreateNetworkResponse2.json"), CreateNetworkResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- }
-
-
-
- @Test
- public void testDeleteNetwork() throws IOException{
-
- DeleteNetworkRequest request = new DeleteNetworkRequest();
-
- MsoRequest msoReq = new MsoRequest();
-
- msoReq.setRequestId(MSO_REQUEST_ID);
- msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
- request.setMsoRequest(msoReq);
- request.setCloudSiteId(CLOUDSITE_ID);
- request.setTenantId(TENANT_ID);
- request.setNetworkId(NETWORK_ID);
- request.setNetworkType(NETWORK_TYPE);
- request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
- request.setNetworkStackId(NETWORK_ID);
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackPublicUrlStackByID_200(wireMockServer, wireMockPort);
-
- mockOpenStackGetPublicUrlStackByNameAndID_204(wireMockServer, wireMockPort);
-
- mockOpenStackDeletePublicUrlStackByNameAndID_204(wireMockServer);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
-
- HttpEntity<DeleteNetworkRequest> entity = new HttpEntity<DeleteNetworkRequest>(request, headers);
-
- ResponseEntity<DeleteNetworkResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/networks/da886914-efb2-4917-b335-c8381528d90b"), HttpMethod.DELETE, entity, DeleteNetworkResponse.class);
-
- DeleteNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/DeleteNetworkResponse.json"), DeleteNetworkResponse.class);
-
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
-
- }
-
- @Test
- public void testRollbackNetwork() throws IOException {
-
- RollbackNetworkRequest request = new RollbackNetworkRequest();
-
- MsoRequest msoReq = new MsoRequest();
-
- msoReq.setRequestId(MSO_REQUEST_ID);
- msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackPublicUrlStackByID_200(wireMockServer, wireMockPort);
-
- mockOpenStackGetPublicUrlStackByNameAndID_204(wireMockServer, wireMockPort);
-
- mockOpenStackDeletePublicUrlStackByNameAndID_204(wireMockServer);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
-
- HttpEntity<RollbackNetworkRequest> entity = new HttpEntity<>(request, headers);
-
- ResponseEntity<RollbackNetworkResponse> response = restTemplate
- .exchange(createURLWithPort("/services/rest/v1/networks/da886914-efb2-4917-b335-c8381528d90b/rollback"),
- HttpMethod.DELETE, entity, RollbackNetworkResponse.class);
-
- RollbackNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper()
- .readValue(new File("src/test/resources/__files/RollbackNetworkResponse.json"), RollbackNetworkResponse.class);
-
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
-
- }
-
- @Test
- public void testQueryNetwork_Exception() throws IOException{
- MsoRequest msoReq = new MsoRequest();
- msoReq.setRequestId(MSO_REQUEST_ID);
- msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
- headers.add("Accept", MediaType.APPLICATION_JSON);
-
- HttpEntity<DeleteNetworkRequest> entity = new HttpEntity<DeleteNetworkRequest>(headers);
-
- ResponseEntity<QueryNetworkError> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/networks/da886914-efb2-4917-b335-c8381528d90b"), HttpMethod.GET,
- entity, QueryNetworkError.class);
-
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
-
- }
-
- @Test
- public void testQueryNetwork() throws IOException{
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_200(wireMockServer);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<DeleteNetworkRequest> entity = new HttpEntity<DeleteNetworkRequest>(headers);
-
- ResponseEntity<QueryNetworkResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/networks/da886914-efb2-4917-b335-c8381528d90b"+"?cloudSiteId=" + CLOUDSITE_ID + "&tenantId=" + TENANT_ID
- + "&aaiNetworkId=aaiNetworkId"), HttpMethod.GET,
- entity, QueryNetworkResponse.class);
-
- assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
-
- }
-
- @Test
- public void testUpdateNetwork() throws IOException{
-
- UpdateNetworkRequest request = new UpdateNetworkRequest();
-
- MsoRequest msoReq = new MsoRequest();
-
- msoReq.setRequestId(MSO_REQUEST_ID);
- msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
- request.setMsoRequest(msoReq);
- request.setCloudSiteId(CLOUDSITE_ID);
- request.setTenantId(TENANT_ID);
- request.setNetworkId(NETWORK_ID);
- request.setNetworkName(NETWORK_NAME);
- request.setNetworkType(NETWORK_TYPE);
- request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
- request.setNetworkStackId(NETWORK_ID);
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackPublicUrlStackByName_200(wireMockServer, wireMockPort);
-
- mockOpenStackPublicUrlStackByID_200(wireMockServer, wireMockPort);
-
- mockOpenStackGetPublicUrlStackByNameAndID_200(wireMockServer, wireMockPort);
-
- mockOpenStackPutPublicUrlStackByNameAndID_200(wireMockServer);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
-
- HttpEntity<UpdateNetworkRequest> entity = new HttpEntity<UpdateNetworkRequest>(request, headers);
-
- ResponseEntity<UpdateNetworkResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/networks/da886914-efb2-4917-b335-c8381528d90b"), HttpMethod.PUT, entity, UpdateNetworkResponse.class);
-
- UpdateNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/UpdateNetworkResponse.json"), UpdateNetworkResponse.class);
-
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- }
-
- @Test
- public void testCreateNetworkCNRC_JSON() throws JSONException, JsonParseException, JsonMappingException, IOException {
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackPostPublicUrlWithBodyFile_200(wireMockServer);
-
- mockOpenStackGetStackCreatedAppC_200(wireMockServer);
-
- mockOpenStackGetStackAppC_404(wireMockServer);
-
- headers.add("Content-Type", MediaType.APPLICATION_JSON);
- headers.add("Accept", MediaType.APPLICATION_JSON);
-
- String request = readJsonFileAsString("src/test/resources/CreateNetwork3.json");
- HttpEntity<String> entity = new HttpEntity<String>(request, headers);
-
- ResponseEntity<CreateNetworkResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/networks"), HttpMethod.POST, entity, CreateNetworkResponse.class);
-
- CreateNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/CreateNetworkResponse3.json"), CreateNetworkResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- }
-
- @Test
- public void testCreateNetworkNC_Shared_JSON() throws JSONException, JsonParseException, JsonMappingException, IOException {
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackPostPublicUrlWithBodyFile_200(wireMockServer);
-
- mockOpenStackGetStackCreatedAppC_200(wireMockServer);
-
- mockOpenStackGetStackAppC_404(wireMockServer);
-
- headers.add("Content-Type", MediaType.APPLICATION_JSON);
- headers.add("Accept", MediaType.APPLICATION_JSON);
-
- String request = readJsonFileAsString("src/test/resources/CreateNetwork4.json");
- HttpEntity<String> entity = new HttpEntity<String>(request, headers);
-
- ResponseEntity<CreateNetworkResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/networks"), HttpMethod.POST, entity, CreateNetworkResponse.class);
-
- CreateNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/CreateNetworkResponse4.json"), CreateNetworkResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- }
-
- @Override
- protected String readJsonFileAsString(String fileLocation) throws JsonParseException, JsonMappingException, IOException{
- return new String(Files.readAllBytes(Paths.get(fileLocation)));
- }
+ @Autowired
+ private JettisonStyleMapperProvider jettisonTypeObjectMapper;
+ private static final String CLOUDSITE_ID = "mtn13";
+ private static final String TENANT_ID = "ba38bc24a2ef4fb2ad2810c894f1938f";
+ private static final String NETWORK_ID = "da886914-efb2-4917-b335-c8381528d90b";
+ private static final String NETWORK_TYPE = "CONTRAIL30_BASIC";
+ private static final String MODEL_CUSTOMIZATION_UUID = "3bdbb104-476c-483e-9f8b-c095b3d308ac";
+ private static final String MSO_SERVICE_INSTANCE_ID = "05869d5f-47df-4b45-bbfc-4f03ce0a50bf";
+ private static final String MSO_REQUEST_ID = "requestId";
+ private static final String NETWORK_NAME = "vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0";
+
+ @Test
+ public void testCreateNetwork() throws JSONException, JsonParseException, JsonMappingException, IOException {
+
+ CreateNetworkRequest request = new CreateNetworkRequest();
+ request.setBackout(true);
+ request.setSkipAAI(true);
+ request.setFailIfExists(false);
+ MsoRequest msoReq = new MsoRequest();
+ String networkTechnology = "CONTRAIL";
+
+ msoReq.setRequestId(MSO_REQUEST_ID);
+ msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
+ request.setMsoRequest(msoReq);
+ request.setCloudSiteId(CLOUDSITE_ID);
+ request.setTenantId(TENANT_ID);
+ request.setNetworkId(NETWORK_ID);
+ request.setNetworkName(NETWORK_NAME);
+ request.setNetworkType(NETWORK_TYPE);
+ request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
+ request.setNetworkTechnology(networkTechnology);
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackPostPublicUrlWithBodyFile_200(wireMockServer);
+
+ mockOpenStackGetStackCreatedVUSP_200(wireMockServer);
+
+ mockOpenStackGetStackVUSP_404(wireMockServer);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<CreateNetworkRequest> entity = new HttpEntity<CreateNetworkRequest>(request, headers);
+ ResponseEntity<CreateNetworkResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/networks"), HttpMethod.POST, entity, CreateNetworkResponse.class);
+
+ CreateNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/CreateNetworkResponse.json"), CreateNetworkResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ }
+
+ @Test
+ public void testCreateNetwork_JSON() throws JSONException, JsonParseException, JsonMappingException, IOException {
+
+
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackPostPublicUrlWithBodyFile_200(wireMockServer);
+
+ mockOpenStackGetStackCreatedAppC_200(wireMockServer);
+
+ mockOpenStackGetStackAppC_404(wireMockServer);
+
+ headers.add("Content-Type", MediaType.APPLICATION_JSON);
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+
+ String request = readJsonFileAsString("src/test/resources/CreateNetwork.json");
+ HttpEntity<String> entity = new HttpEntity<String>(request, headers);
+
+ ResponseEntity<CreateNetworkResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/networks"), HttpMethod.POST, entity, CreateNetworkResponse.class);
+
+ CreateNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/CreateNetworkResponse2.json"), CreateNetworkResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ }
+
+
+
+ @Test
+ public void testDeleteNetwork() throws IOException {
+
+ DeleteNetworkRequest request = new DeleteNetworkRequest();
+
+ MsoRequest msoReq = new MsoRequest();
+
+ msoReq.setRequestId(MSO_REQUEST_ID);
+ msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
+ request.setMsoRequest(msoReq);
+ request.setCloudSiteId(CLOUDSITE_ID);
+ request.setTenantId(TENANT_ID);
+ request.setNetworkId(NETWORK_ID);
+ request.setNetworkType(NETWORK_TYPE);
+ request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
+ request.setNetworkStackId(NETWORK_ID);
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackPublicUrlStackByID_200(wireMockServer, wireMockPort);
+
+ mockOpenStackGetPublicUrlStackByNameAndID_204(wireMockServer, wireMockPort);
+
+ mockOpenStackDeletePublicUrlStackByNameAndID_204(wireMockServer);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+
+ HttpEntity<DeleteNetworkRequest> entity = new HttpEntity<DeleteNetworkRequest>(request, headers);
+
+ ResponseEntity<DeleteNetworkResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/networks/da886914-efb2-4917-b335-c8381528d90b"), HttpMethod.DELETE,
+ entity, DeleteNetworkResponse.class);
+
+ DeleteNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/DeleteNetworkResponse.json"), DeleteNetworkResponse.class);
+
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+
+ }
+
+ @Test
+ public void testRollbackNetwork() throws IOException {
+
+ RollbackNetworkRequest request = new RollbackNetworkRequest();
+
+ MsoRequest msoReq = new MsoRequest();
+
+ msoReq.setRequestId(MSO_REQUEST_ID);
+ msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackPublicUrlStackByID_200(wireMockServer, wireMockPort);
+
+ mockOpenStackGetPublicUrlStackByNameAndID_204(wireMockServer, wireMockPort);
+
+ mockOpenStackDeletePublicUrlStackByNameAndID_204(wireMockServer);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+
+ HttpEntity<RollbackNetworkRequest> entity = new HttpEntity<>(request, headers);
+
+ ResponseEntity<RollbackNetworkResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/networks/da886914-efb2-4917-b335-c8381528d90b/rollback"),
+ HttpMethod.DELETE, entity, RollbackNetworkResponse.class);
+
+ RollbackNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/RollbackNetworkResponse.json"), RollbackNetworkResponse.class);
+
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+
+ }
+
+ @Test
+ public void testQueryNetwork_Exception() throws IOException {
+ MsoRequest msoReq = new MsoRequest();
+ msoReq.setRequestId(MSO_REQUEST_ID);
+ msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+
+ HttpEntity<DeleteNetworkRequest> entity = new HttpEntity<DeleteNetworkRequest>(headers);
+
+ ResponseEntity<QueryNetworkError> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/networks/da886914-efb2-4917-b335-c8381528d90b"), HttpMethod.GET,
+ entity, QueryNetworkError.class);
+
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+
+ }
+
+ @Test
+ public void testQueryNetwork() throws IOException {
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<DeleteNetworkRequest> entity = new HttpEntity<DeleteNetworkRequest>(headers);
+
+ ResponseEntity<QueryNetworkResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/networks/da886914-efb2-4917-b335-c8381528d90b" + "?cloudSiteId="
+ + CLOUDSITE_ID + "&tenantId=" + TENANT_ID + "&aaiNetworkId=aaiNetworkId"),
+ HttpMethod.GET, entity, QueryNetworkResponse.class);
+
+ assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
+
+ }
+
+ @Test
+ public void testUpdateNetwork() throws IOException {
+
+ UpdateNetworkRequest request = new UpdateNetworkRequest();
+
+ MsoRequest msoReq = new MsoRequest();
+
+ msoReq.setRequestId(MSO_REQUEST_ID);
+ msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
+ request.setMsoRequest(msoReq);
+ request.setCloudSiteId(CLOUDSITE_ID);
+ request.setTenantId(TENANT_ID);
+ request.setNetworkId(NETWORK_ID);
+ request.setNetworkName(NETWORK_NAME);
+ request.setNetworkType(NETWORK_TYPE);
+ request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
+ request.setNetworkStackId(NETWORK_ID);
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackPublicUrlStackByName_200(wireMockServer, wireMockPort);
+
+ mockOpenStackPublicUrlStackByID_200(wireMockServer, wireMockPort);
+
+ mockOpenStackGetPublicUrlStackByNameAndID_200(wireMockServer, wireMockPort);
+
+ mockOpenStackPutPublicUrlStackByNameAndID_200(wireMockServer);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+
+ HttpEntity<UpdateNetworkRequest> entity = new HttpEntity<UpdateNetworkRequest>(request, headers);
+
+ ResponseEntity<UpdateNetworkResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/networks/da886914-efb2-4917-b335-c8381528d90b"), HttpMethod.PUT,
+ entity, UpdateNetworkResponse.class);
+
+ UpdateNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/UpdateNetworkResponse.json"), UpdateNetworkResponse.class);
+
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
+
+ @Test
+ public void testCreateNetworkCNRC_JSON()
+ throws JSONException, JsonParseException, JsonMappingException, IOException {
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackPostPublicUrlWithBodyFile_200(wireMockServer);
+
+ mockOpenStackGetStackCreatedAppC_200(wireMockServer);
+
+ mockOpenStackGetStackAppC_404(wireMockServer);
+
+ headers.add("Content-Type", MediaType.APPLICATION_JSON);
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+
+ String request = readJsonFileAsString("src/test/resources/CreateNetwork3.json");
+ HttpEntity<String> entity = new HttpEntity<String>(request, headers);
+
+ ResponseEntity<CreateNetworkResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/networks"), HttpMethod.POST, entity, CreateNetworkResponse.class);
+
+ CreateNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/CreateNetworkResponse3.json"), CreateNetworkResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ }
+
+ @Test
+ public void testCreateNetworkNC_Shared_JSON()
+ throws JSONException, JsonParseException, JsonMappingException, IOException {
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackPostPublicUrlWithBodyFile_200(wireMockServer);
+
+ mockOpenStackGetStackCreatedAppC_200(wireMockServer);
+
+ mockOpenStackGetStackAppC_404(wireMockServer);
+
+ headers.add("Content-Type", MediaType.APPLICATION_JSON);
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+
+ String request = readJsonFileAsString("src/test/resources/CreateNetwork4.json");
+ HttpEntity<String> entity = new HttpEntity<String>(request, headers);
+
+ ResponseEntity<CreateNetworkResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/networks"), HttpMethod.POST, entity, CreateNetworkResponse.class);
+
+ CreateNetworkResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/CreateNetworkResponse4.json"), CreateNetworkResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ }
+
+ @Override
+ protected String readJsonFileAsString(String fileLocation)
+ throws JsonParseException, JsonMappingException, IOException {
+ return new String(Files.readAllBytes(Paths.get(fileLocation)));
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBeanTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBeanTest.java
index a1e0a16819..01fbc308b9 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBeanTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBeanTest.java
@@ -1,41 +1,35 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.adapters.network.exceptions;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
public class NetworkExceptionBeanTest {
-
- NetworkExceptionBean neb=new NetworkExceptionBean();
- MsoExceptionCategory msc=MsoExceptionCategory.INTERNAL;
-
- @Test
- public void test() {
- neb.setRolledBack(true);
- neb.setMessage("message");
- neb.setCategory(msc);
- assertEquals("message", neb.getMessage());
- assertEquals(msc, neb.getCategory());
- assertEquals(true, neb.isRolledBack());
- }
+
+ NetworkExceptionBean neb = new NetworkExceptionBean();
+ MsoExceptionCategory msc = MsoExceptionCategory.INTERNAL;
+
+ @Test
+ public void test() {
+ neb.setRolledBack(true);
+ neb.setMessage("message");
+ neb.setCategory(msc);
+ assertEquals("message", neb.getMessage());
+ assertEquals(msc, neb.getCategory());
+ assertEquals(true, neb.isRolledBack());
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/exceptions/NetworkExceptionTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/exceptions/NetworkExceptionTest.java
index bd5b07de1f..268d6b4c51 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/exceptions/NetworkExceptionTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/exceptions/NetworkExceptionTest.java
@@ -1,50 +1,44 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.adapters.network.exceptions;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.openstack.exceptions.MsoException;
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
-public class NetworkExceptionTest{
-
- NetworkException ne=new NetworkException("msg");
- NetworkExceptionBean neb =new NetworkExceptionBean();
- MsoException msoException= new MsoException("msoException") {
- private static final long serialVersionUID = 1L;
- };
- MsoExceptionCategory msc=MsoExceptionCategory.INTERNAL;
- NetworkException ne1=new NetworkException(msoException);
- NetworkException ne2=new NetworkException(ne);
- NetworkException ne3=new NetworkException("msg", ne);
- NetworkException ne4=new NetworkException("msg", msoException);
- NetworkException ne5=new NetworkException("msg", msc);
- NetworkException ne6=new NetworkException("msg", msc, ne);
-
- @Test
- public void test() {
- ne.setFaultInfo(neb);
- assertEquals(ne.getFaultInfo(), neb);
- }
+public class NetworkExceptionTest {
+
+ NetworkException ne = new NetworkException("msg");
+ NetworkExceptionBean neb = new NetworkExceptionBean();
+ MsoException msoException = new MsoException("msoException") {
+ private static final long serialVersionUID = 1L;
+ };
+ MsoExceptionCategory msc = MsoExceptionCategory.INTERNAL;
+ NetworkException ne1 = new NetworkException(msoException);
+ NetworkException ne2 = new NetworkException(ne);
+ NetworkException ne3 = new NetworkException("msg", ne);
+ NetworkException ne4 = new NetworkException("msg", msoException);
+ NetworkException ne5 = new NetworkException("msg", msc);
+ NetworkException ne6 = new NetworkException("msg", msc, ne);
+
+ @Test
+ public void test() {
+ ne.setFaultInfo(neb);
+ assertEquals(ne.getFaultInfo(), neb);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/MsoTenantAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/MsoTenantAdapterImplTest.java
index df7e415724..b695a538bb 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/MsoTenantAdapterImplTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/MsoTenantAdapterImplTest.java
@@ -20,9 +20,7 @@
package org.onap.so.adapters.tenant;
import java.util.HashMap;
-
import javax.xml.ws.Holder;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
@@ -35,10 +33,10 @@ import org.onap.so.entity.MsoRequest;
@RunWith(MockitoJUnitRunner.class)
public class MsoTenantAdapterImplTest {
-
+
@Mock
- private CloudConfig cloudConfig;
-
+ private CloudConfig cloudConfig;
+
@Spy
@InjectMocks
private MsoTenantAdapterImpl msoTenantAdapter;
@@ -50,14 +48,14 @@ public class MsoTenantAdapterImplTest {
@Test(expected = NullPointerException.class)
public void createTenant() throws Exception {
- msoTenantAdapter.createTenant("site", "tenant", new HashMap<>(),
- true, true, new MsoRequest(), new Holder<String>(), new Holder<TenantRollback>());
+ msoTenantAdapter.createTenant("site", "tenant", new HashMap<>(), true, true, new MsoRequest(),
+ new Holder<String>(), new Holder<TenantRollback>());
}
@Test(expected = NullPointerException.class)
public void queryTenant() throws Exception {
- msoTenantAdapter.queryTenant("site", "tenant", new MsoRequest(),
- new Holder<>(), new Holder<>(), new Holder<>());
+ msoTenantAdapter.queryTenant("site", "tenant", new MsoRequest(), new Holder<>(), new Holder<>(),
+ new Holder<>());
}
@Test(expected = NullPointerException.class)
@@ -70,4 +68,4 @@ public class MsoTenantAdapterImplTest {
msoTenantAdapter.rollbackTenant(new TenantRollback());
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/TenantAdapterRestTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/TenantAdapterRestTest.java
index f24a5a5292..e481f0d03f 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/TenantAdapterRestTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/TenantAdapterRestTest.java
@@ -36,15 +36,12 @@ import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPostTenantWithBod
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPostTenant_200;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPutRolesAdmin_200;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccessAdmin;
-
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.junit.Ignore;
import org.junit.Test;
import org.onap.so.adapters.tenantrest.CreateTenantRequest;
@@ -58,189 +55,186 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
public class TenantAdapterRestTest extends BaseRestTestUtils {
- @Autowired
- private JettisonStyleMapperProvider jettisonTypeObjectMapper;
-
- @Test
- public void testCreateTenantCreated() throws JsonParseException, JsonMappingException, IOException {
-
- CreateTenantRequest request = new CreateTenantRequest();
- String cloudSiteId = "MTN13";
- String requestId = "62265093-277d-4388-9ba6-449838ade586";
- String serviceInstanceId = "4147e06f-1b89-49c5-b21f-4faf8dc9805a";
- String tenantName = "testingTenantName";
- boolean failIfExists = true;
- boolean backout = true;
- Map<String, String> metaData = new HashMap<>();
- metaData.put("key1", "value2");
- MsoRequest msoReq = new MsoRequest();
- msoReq.setRequestId(requestId);
- msoReq.setServiceInstanceId(serviceInstanceId);
-
- request.setCloudSiteId(cloudSiteId);
- request.setMsoRequest(msoReq);
- request.setTenantName(tenantName);
- request.setMetadata(metaData);
- request.setBackout(backout);
- request.setFailIfExists(failIfExists);
-
- mockOpenStackResponseAccessAdmin(wireMockServer, wireMockPort);
-
- mockOpenStackGetTenantByName_404(wireMockServer, tenantName);
-
- mockOpenStackPostTenantWithBodyFile_200(wireMockServer);
-
- mockOpenStackGetUser_200(wireMockServer, "m93945");
-
- mockOpenStackGetRoles_200(wireMockServer, "OS-KSADM");
-
- mockOpenStackPutRolesAdmin_200(wireMockServer, "OS-KSADM");
-
- mockOpenStackPostMetadata_200(wireMockServer);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<CreateTenantRequest> entity = new HttpEntity<CreateTenantRequest>(request, headers);
-
- ResponseEntity<CreateTenantResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/tenants"), HttpMethod.POST,
- entity, CreateTenantResponse.class);
-
- CreateTenantResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/CreateTenantResponse_Created.json"), CreateTenantResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- }
-
- @Test
- public void testCreateTenantExists() throws JsonParseException, JsonMappingException, IOException {
-
- CreateTenantRequest request = new CreateTenantRequest();
- String cloudSiteId = "MTN13";
- String requestId = "62265093-277d-4388-9ba6-449838ade586";
- String serviceInstanceId = "4147e06f-1b89-49c5-b21f-4faf8dc9805a";
- String tenantName = "testingTenantName";
- boolean failIfExists = false;
- boolean backout = true;
- Map<String, String> metadata = new HashMap<>();
-
- MsoRequest msoReq = new MsoRequest();
- msoReq.setRequestId(requestId);
- msoReq.setServiceInstanceId(serviceInstanceId);
-
- request.setCloudSiteId(cloudSiteId);
- request.setMsoRequest(msoReq);
- request.setTenantName(tenantName);
- request.setMetadata(metadata);
- request.setBackout(backout);
- request.setFailIfExists(failIfExists);
-
- mockOpenStackResponseAccessAdmin(wireMockServer, wireMockPort);
-
- mockOpenStackGetTenantByName_200(wireMockServer, tenantName);
-
- mockOpenStackPostTenant_200(wireMockServer);
-
- mockOpenStackGetMetadata_200(wireMockServer);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<CreateTenantRequest> entity = new HttpEntity<CreateTenantRequest>(request, headers);
-
- ResponseEntity<CreateTenantResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/tenants"), HttpMethod.POST,
- entity, CreateTenantResponse.class);
-
- CreateTenantResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/CreateTenantResponse_Exists.json"), CreateTenantResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- }
-
- @Test
- public void testDeleteTenant() throws IOException {
-
- DeleteTenantRequest request = new DeleteTenantRequest();
- String cloudSiteId = "mtn13";
- String tenantId = "tenantId";
- String requestId = "ra1";
- String serviceInstanceId = "sa1";
-
- MsoRequest msoReq = new MsoRequest();
- msoReq.setRequestId(requestId);
- msoReq.setServiceInstanceId(serviceInstanceId);
-
- request.setCloudSiteId(cloudSiteId);
- request.setTenantId(tenantId);
- request.setMsoRequest(msoReq);
-
- mockOpenStackResponseAccessAdmin(wireMockServer, wireMockPort);
-
- mockOpenStackGetTenantById_200(wireMockServer, tenantId);
-
- mockOpenStackDeleteTenantById_200(wireMockServer, tenantId);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<DeleteTenantRequest> entity = new HttpEntity<DeleteTenantRequest>(request, headers);
-
- ResponseEntity<DeleteTenantResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/tenants/tenantId"), HttpMethod.DELETE,
- entity, DeleteTenantResponse.class);
-
- DeleteTenantResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/DeleteTenantResponse_Success.json"), DeleteTenantResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- }
-
- //@Ignore
- @Test
- public void testDeleteTenantFails() throws IOException {
-
- DeleteTenantRequest request = new DeleteTenantRequest();
- String cloudSiteId = "mtn13";
- String tenantId = "tenantId";
- String requestId = "ra1";
- String serviceInstanceId = "sa1";
-
- MsoRequest msoReq = new MsoRequest();
- msoReq.setRequestId(requestId);
- msoReq.setServiceInstanceId(serviceInstanceId);
-
- request.setCloudSiteId(cloudSiteId);
- request.setTenantId(tenantId);
- request.setMsoRequest(msoReq);
-
- mockOpenStackResponseAccessAdmin(wireMockServer, wireMockPort);
-
- mockOpenStackGetTenantById_404(wireMockServer, tenantId);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<DeleteTenantRequest> entity = new HttpEntity<DeleteTenantRequest>(request, headers);
-
- ResponseEntity<DeleteTenantResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/tenants/tenantId"), HttpMethod.DELETE,
- entity, DeleteTenantResponse.class);
-
- DeleteTenantResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/DeleteTenantResponse_Failed.json"), DeleteTenantResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- }
-
- @Ignore
- @Test
- public void testQuaryTenant() {
-
-
-
- }
+ @Autowired
+ private JettisonStyleMapperProvider jettisonTypeObjectMapper;
+
+ @Test
+ public void testCreateTenantCreated() throws JsonParseException, JsonMappingException, IOException {
+
+ CreateTenantRequest request = new CreateTenantRequest();
+ String cloudSiteId = "MTN13";
+ String requestId = "62265093-277d-4388-9ba6-449838ade586";
+ String serviceInstanceId = "4147e06f-1b89-49c5-b21f-4faf8dc9805a";
+ String tenantName = "testingTenantName";
+ boolean failIfExists = true;
+ boolean backout = true;
+ Map<String, String> metaData = new HashMap<>();
+ metaData.put("key1", "value2");
+ MsoRequest msoReq = new MsoRequest();
+ msoReq.setRequestId(requestId);
+ msoReq.setServiceInstanceId(serviceInstanceId);
+
+ request.setCloudSiteId(cloudSiteId);
+ request.setMsoRequest(msoReq);
+ request.setTenantName(tenantName);
+ request.setMetadata(metaData);
+ request.setBackout(backout);
+ request.setFailIfExists(failIfExists);
+
+ mockOpenStackResponseAccessAdmin(wireMockServer, wireMockPort);
+
+ mockOpenStackGetTenantByName_404(wireMockServer, tenantName);
+
+ mockOpenStackPostTenantWithBodyFile_200(wireMockServer);
+
+ mockOpenStackGetUser_200(wireMockServer, "m93945");
+
+ mockOpenStackGetRoles_200(wireMockServer, "OS-KSADM");
+
+ mockOpenStackPutRolesAdmin_200(wireMockServer, "OS-KSADM");
+
+ mockOpenStackPostMetadata_200(wireMockServer);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<CreateTenantRequest> entity = new HttpEntity<CreateTenantRequest>(request, headers);
+
+ ResponseEntity<CreateTenantResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/tenants"), HttpMethod.POST, entity, CreateTenantResponse.class);
+
+ CreateTenantResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/CreateTenantResponse_Created.json"), CreateTenantResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ }
+
+ @Test
+ public void testCreateTenantExists() throws JsonParseException, JsonMappingException, IOException {
+
+ CreateTenantRequest request = new CreateTenantRequest();
+ String cloudSiteId = "MTN13";
+ String requestId = "62265093-277d-4388-9ba6-449838ade586";
+ String serviceInstanceId = "4147e06f-1b89-49c5-b21f-4faf8dc9805a";
+ String tenantName = "testingTenantName";
+ boolean failIfExists = false;
+ boolean backout = true;
+ Map<String, String> metadata = new HashMap<>();
+
+ MsoRequest msoReq = new MsoRequest();
+ msoReq.setRequestId(requestId);
+ msoReq.setServiceInstanceId(serviceInstanceId);
+
+ request.setCloudSiteId(cloudSiteId);
+ request.setMsoRequest(msoReq);
+ request.setTenantName(tenantName);
+ request.setMetadata(metadata);
+ request.setBackout(backout);
+ request.setFailIfExists(failIfExists);
+
+ mockOpenStackResponseAccessAdmin(wireMockServer, wireMockPort);
+
+ mockOpenStackGetTenantByName_200(wireMockServer, tenantName);
+
+ mockOpenStackPostTenant_200(wireMockServer);
+
+ mockOpenStackGetMetadata_200(wireMockServer);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<CreateTenantRequest> entity = new HttpEntity<CreateTenantRequest>(request, headers);
+
+ ResponseEntity<CreateTenantResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/tenants"), HttpMethod.POST, entity, CreateTenantResponse.class);
+
+ CreateTenantResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/CreateTenantResponse_Exists.json"), CreateTenantResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ }
+
+ @Test
+ public void testDeleteTenant() throws IOException {
+
+ DeleteTenantRequest request = new DeleteTenantRequest();
+ String cloudSiteId = "mtn13";
+ String tenantId = "tenantId";
+ String requestId = "ra1";
+ String serviceInstanceId = "sa1";
+
+ MsoRequest msoReq = new MsoRequest();
+ msoReq.setRequestId(requestId);
+ msoReq.setServiceInstanceId(serviceInstanceId);
+
+ request.setCloudSiteId(cloudSiteId);
+ request.setTenantId(tenantId);
+ request.setMsoRequest(msoReq);
+
+ mockOpenStackResponseAccessAdmin(wireMockServer, wireMockPort);
+
+ mockOpenStackGetTenantById_200(wireMockServer, tenantId);
+
+ mockOpenStackDeleteTenantById_200(wireMockServer, tenantId);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<DeleteTenantRequest> entity = new HttpEntity<DeleteTenantRequest>(request, headers);
+
+ ResponseEntity<DeleteTenantResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v1/tenants/tenantId"), HttpMethod.DELETE,
+ entity, DeleteTenantResponse.class);
+
+ DeleteTenantResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/DeleteTenantResponse_Success.json"), DeleteTenantResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ }
+
+ // @Ignore
+ @Test
+ public void testDeleteTenantFails() throws IOException {
+
+ DeleteTenantRequest request = new DeleteTenantRequest();
+ String cloudSiteId = "mtn13";
+ String tenantId = "tenantId";
+ String requestId = "ra1";
+ String serviceInstanceId = "sa1";
+
+ MsoRequest msoReq = new MsoRequest();
+ msoReq.setRequestId(requestId);
+ msoReq.setServiceInstanceId(serviceInstanceId);
+
+ request.setCloudSiteId(cloudSiteId);
+ request.setTenantId(tenantId);
+ request.setMsoRequest(msoReq);
+
+ mockOpenStackResponseAccessAdmin(wireMockServer, wireMockPort);
+
+ mockOpenStackGetTenantById_404(wireMockServer, tenantId);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<DeleteTenantRequest> entity = new HttpEntity<DeleteTenantRequest>(request, headers);
+
+ ResponseEntity<DeleteTenantResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v1/tenants/tenantId"), HttpMethod.DELETE,
+ entity, DeleteTenantResponse.class);
+
+ DeleteTenantResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/DeleteTenantResponse_Failed.json"), DeleteTenantResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ }
+
+ @Ignore
+ @Test
+ public void testQuaryTenant() {
+
+
+
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExistsTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExistsTest.java
index 6288dc9573..6e3312b1d3 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExistsTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExistsTest.java
@@ -1,22 +1,17 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.adapters.tenant.exceptions;
@@ -24,9 +19,9 @@ import org.junit.Test;
public class TenantAlreadyExistsTest {
- @Test
- public void test() {
- TenantAlreadyExists tar= new TenantAlreadyExists("name", "cloudId", "tenantId");
- assert(tar!=null);
- }
+ @Test
+ public void test() {
+ TenantAlreadyExists tar = new TenantAlreadyExists("name", "cloudId", "tenantId");
+ assert (tar != null);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBeanTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBeanTest.java
index 178495105b..7314a9f1e2 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBeanTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBeanTest.java
@@ -1,22 +1,17 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.adapters.tenant.exceptions;
@@ -27,21 +22,21 @@ import org.onap.so.openstack.exceptions.MsoExceptionCategory;
public class TenantExceptionBeanTest {
-@Mock
-private MsoExceptionCategory mec;
+ @Mock
+ private MsoExceptionCategory mec;
-@InjectMocks
-private TenantExceptionBean teb;
+ @InjectMocks
+ private TenantExceptionBean teb;
-@Test
- public void test() {
- teb =new TenantExceptionBean("message",mec);
+ @Test
+ public void test() {
+ teb = new TenantExceptionBean("message", mec);
teb.setMessage("message");
teb.setCategory(MsoExceptionCategory.INTERNAL);
teb.setCategory(MsoExceptionCategory.IO);
teb.setCategory(MsoExceptionCategory.OPENSTACK);
teb.setCategory(MsoExceptionCategory.USERDATA);
- assert(teb.getMessage().equals("message"));
- assert(teb.getCategory()!=null);
- }
+ assert (teb.getMessage().equals("message"));
+ assert (teb.getCategory() != null);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionTest.java
index 73614a3628..83eb1f1bdc 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionTest.java
@@ -1,22 +1,17 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.adapters.tenant.exceptions;
@@ -26,24 +21,24 @@ import org.mockito.Mock;
import org.onap.so.openstack.exceptions.MsoExceptionCategory;
public class TenantExceptionTest {
-
- @Mock
- private TenantExceptionBean teb;
-
- @Mock
- private MsoExceptionCategory mec;
-
- @InjectMocks
- private TenantException te;
-
- @Test
- public void test() {
- teb=new TenantExceptionBean("message");
- teb.setMessage("message");
- teb.setCategory(MsoExceptionCategory.INTERNAL);
- te = new TenantException("message", mec);
- te.setFaultInfo(teb);
- assert(te.getFaultInfo()!=null);
- assert(te.getFaultInfo().equals(teb));
- }
+
+ @Mock
+ private TenantExceptionBean teb;
+
+ @Mock
+ private MsoExceptionCategory mec;
+
+ @InjectMocks
+ private TenantException te;
+
+ @Test
+ public void test() {
+ teb = new TenantExceptionBean("message");
+ teb.setMessage("message");
+ teb.setCategory(MsoExceptionCategory.INTERNAL);
+ te = new TenantException("message", mec);
+ te.setFaultInfo(teb);
+ assert (te.getFaultInfo() != null);
+ assert (te.getFaultInfo().equals(teb));
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/valet/ValetClientTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/valet/ValetClientTest.java
index 0b83386ccc..61d2d08590 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/valet/ValetClientTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/valet/ValetClientTest.java
@@ -27,9 +27,7 @@ import static org.onap.so.bpmn.mock.StubOpenStack.mockValetCreatePostResponse_20
import static org.onap.so.bpmn.mock.StubOpenStack.mockValetCreatePutResponse_200;
import static org.onap.so.bpmn.mock.StubOpenStack.mockValetDeleteDeleteResponse_200;
import static org.onap.so.bpmn.mock.StubOpenStack.mockValetRollbackPutRequest_200;
-
import java.io.File;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
@@ -40,77 +38,90 @@ import org.onap.so.adapters.valet.beans.ValetRollbackResponse;
import org.onap.so.adapters.valet.beans.ValetUpdateResponse;
import org.onap.so.adapters.vnf.BaseRestTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.ObjectMapper;
public class ValetClientTest extends BaseRestTestUtils {
- @Autowired
- protected ValetClient client;
-
- private ObjectMapper mapper = new ObjectMapper();
-
- @Before
- public void init() {
- client.baseUrl = "http://localhost:" + wireMockPort;
- }
-
- @Test
- public void testCallValetCreateRequest() throws Exception {
- ValetCreateResponse vcr = mapper.readValue(new File("src/test/resources/__files/ValetCreateRequest.json"), ValetCreateResponse.class);
- GenericValetResponse<ValetCreateResponse> expected = new GenericValetResponse<ValetCreateResponse>(HttpStatus.SC_OK, ValetClient.NO_STATUS_RETURNED, vcr);
-
- mockValetCreatePostResponse_200(wireMockServer, "requestId", mapper.writeValueAsString(vcr));
-
- GenericValetResponse<ValetCreateResponse> actual = client.callValetCreateRequest("requestId", "regionId", "ownerId", "tenantId", "serviceInstanceId", "vnfId", "vnfName", "vfModuleId", "vfModuleName", "keystoneUrl", null);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testCallValetUpdateRequest() throws Exception {
- ValetUpdateResponse vur = mapper.readValue(new File("src/test/resources/__files/ValetCreateRequest.json"), ValetUpdateResponse.class);
- GenericValetResponse<ValetUpdateResponse> expected = new GenericValetResponse<ValetUpdateResponse>(HttpStatus.SC_OK, ValetClient.NO_STATUS_RETURNED, vur);
-
- mockValetCreatePutResponse_200(wireMockServer, "requestId", mapper.writeValueAsString(vur));
-
- GenericValetResponse<ValetUpdateResponse> actual = client.callValetUpdateRequest("requestId", "regionId", "ownerId", "tenantId", "serviceInstanceId", "vnfId", "vnfName", "vfModuleId", "vfModuleName", "keystoneUrl", null);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testCallValetDeleteRequest() throws Exception {
- ValetDeleteResponse vdr = mapper.readValue(new File("src/test/resources/__files/ValetDeleteRequest.json"), ValetDeleteResponse.class);
- GenericValetResponse<ValetDeleteResponse> expected = new GenericValetResponse<ValetDeleteResponse>(HttpStatus.SC_OK, ValetClient.NO_STATUS_RETURNED, vdr);
-
- mockValetDeleteDeleteResponse_200(wireMockServer, "requestId", mapper.writeValueAsString(vdr));
-
- GenericValetResponse<ValetDeleteResponse> actual = client.callValetDeleteRequest("requestId", "regionId", "ownerId", "tenantId", "vfModuleId", "vfModuleName");
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testCallValetConfirmRequest() throws Exception {
- ValetConfirmResponse vcr = new ValetConfirmResponse();
- GenericValetResponse<ValetConfirmResponse> expected = new GenericValetResponse<ValetConfirmResponse>(HttpStatus.SC_OK, ValetClient.NO_STATUS_RETURNED, vcr);
-
- mockValetConfirmPutRequest_200(wireMockServer, "requestId", "{}");
-
- GenericValetResponse<ValetConfirmResponse> actual = client.callValetConfirmRequest("requestId", "stackId");
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testCallValetRollbackRequest() throws Exception {
- ValetRollbackResponse vrr = new ValetRollbackResponse();
- GenericValetResponse<ValetRollbackResponse> expected = new GenericValetResponse<ValetRollbackResponse>(HttpStatus.SC_OK, ValetClient.NO_STATUS_RETURNED, vrr);
-
- mockValetRollbackPutRequest_200(wireMockServer, "requestId", "{}");
-
- GenericValetResponse<ValetRollbackResponse> actual = client.callValetRollbackRequest("requestId", "stackId", true, "error");
-
- assertThat(actual, sameBeanAs(expected));
- }
+ @Autowired
+ protected ValetClient client;
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Before
+ public void init() {
+ client.baseUrl = "http://localhost:" + wireMockPort;
+ }
+
+ @Test
+ public void testCallValetCreateRequest() throws Exception {
+ ValetCreateResponse vcr = mapper.readValue(new File("src/test/resources/__files/ValetCreateRequest.json"),
+ ValetCreateResponse.class);
+ GenericValetResponse<ValetCreateResponse> expected =
+ new GenericValetResponse<ValetCreateResponse>(HttpStatus.SC_OK, ValetClient.NO_STATUS_RETURNED, vcr);
+
+ mockValetCreatePostResponse_200(wireMockServer, "requestId", mapper.writeValueAsString(vcr));
+
+ GenericValetResponse<ValetCreateResponse> actual =
+ client.callValetCreateRequest("requestId", "regionId", "ownerId", "tenantId", "serviceInstanceId",
+ "vnfId", "vnfName", "vfModuleId", "vfModuleName", "keystoneUrl", null);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testCallValetUpdateRequest() throws Exception {
+ ValetUpdateResponse vur = mapper.readValue(new File("src/test/resources/__files/ValetCreateRequest.json"),
+ ValetUpdateResponse.class);
+ GenericValetResponse<ValetUpdateResponse> expected =
+ new GenericValetResponse<ValetUpdateResponse>(HttpStatus.SC_OK, ValetClient.NO_STATUS_RETURNED, vur);
+
+ mockValetCreatePutResponse_200(wireMockServer, "requestId", mapper.writeValueAsString(vur));
+
+ GenericValetResponse<ValetUpdateResponse> actual =
+ client.callValetUpdateRequest("requestId", "regionId", "ownerId", "tenantId", "serviceInstanceId",
+ "vnfId", "vnfName", "vfModuleId", "vfModuleName", "keystoneUrl", null);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testCallValetDeleteRequest() throws Exception {
+ ValetDeleteResponse vdr = mapper.readValue(new File("src/test/resources/__files/ValetDeleteRequest.json"),
+ ValetDeleteResponse.class);
+ GenericValetResponse<ValetDeleteResponse> expected =
+ new GenericValetResponse<ValetDeleteResponse>(HttpStatus.SC_OK, ValetClient.NO_STATUS_RETURNED, vdr);
+
+ mockValetDeleteDeleteResponse_200(wireMockServer, "requestId", mapper.writeValueAsString(vdr));
+
+ GenericValetResponse<ValetDeleteResponse> actual = client.callValetDeleteRequest("requestId", "regionId",
+ "ownerId", "tenantId", "vfModuleId", "vfModuleName");
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testCallValetConfirmRequest() throws Exception {
+ ValetConfirmResponse vcr = new ValetConfirmResponse();
+ GenericValetResponse<ValetConfirmResponse> expected =
+ new GenericValetResponse<ValetConfirmResponse>(HttpStatus.SC_OK, ValetClient.NO_STATUS_RETURNED, vcr);
+
+ mockValetConfirmPutRequest_200(wireMockServer, "requestId", "{}");
+
+ GenericValetResponse<ValetConfirmResponse> actual = client.callValetConfirmRequest("requestId", "stackId");
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testCallValetRollbackRequest() throws Exception {
+ ValetRollbackResponse vrr = new ValetRollbackResponse();
+ GenericValetResponse<ValetRollbackResponse> expected =
+ new GenericValetResponse<ValetRollbackResponse>(HttpStatus.SC_OK, ValetClient.NO_STATUS_RETURNED, vrr);
+
+ mockValetRollbackPutRequest_200(wireMockServer, "requestId", "{}");
+
+ GenericValetResponse<ValetRollbackResponse> actual =
+ client.callValetRollbackRequest("requestId", "stackId", true, "error");
+
+ assertThat(actual, sameBeanAs(expected));
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapperTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapperTest.java
index c982f8beb1..a9c57598b0 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapperTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapperTest.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters.vdu.mapper;
import static org.assertj.core.api.Assertions.assertThat;
-
import com.google.common.collect.Lists;
import java.util.List;
import org.junit.Test;
@@ -55,14 +54,13 @@ public class VfModuleCustomizationToVduMapperTest {
VfModuleCustomization vfModuleCustomization = createVfModuleCustomization();
vfModuleCustomization.setHeatEnvironment(createHeatEnvironment(HEAT_ENV_NAME, HEAT_ENV_CONTENT));
VfModule vfModule = createVfModule();
- vfModule.setModuleHeatTemplate(createHeatTemplate(
- MODULE_HEAT_TEMPLATE_NAME, MODULE_HEAT_TEMPLATE_BODY,
- NESTED_TEMPLATE_NAME, NESTED_TEMPLATE_BODY));
+ vfModule.setModuleHeatTemplate(createHeatTemplate(MODULE_HEAT_TEMPLATE_NAME, MODULE_HEAT_TEMPLATE_BODY,
+ NESTED_TEMPLATE_NAME, NESTED_TEMPLATE_BODY));
vfModuleCustomization.setVfModule(vfModule);
// WHEN
- VduModelInfo vduModelInfo = new VfModuleCustomizationToVduMapper()
- .mapVfModuleCustomizationToVdu(vfModuleCustomization);
+ VduModelInfo vduModelInfo =
+ new VfModuleCustomizationToVduMapper().mapVfModuleCustomizationToVdu(vfModuleCustomization);
// THEN
assertThat(vduModelInfo.getModelCustomizationUUID()).isEqualTo(MODEL_CUSTOMIZATION_UUID);
@@ -76,14 +74,13 @@ public class VfModuleCustomizationToVduMapperTest {
VfModuleCustomization vfModuleCustomization = createVfModuleCustomization();
vfModuleCustomization.setVolumeHeatEnv(createHeatEnvironment(HEAT_ENV_NAME, HEAT_ENV_CONTENT));
VfModule vfModule = createVfModule();
- vfModule.setVolumeHeatTemplate(createHeatTemplate(
- MODULE_HEAT_TEMPLATE_NAME, MODULE_HEAT_TEMPLATE_BODY,
- NESTED_TEMPLATE_NAME, NESTED_TEMPLATE_BODY));
+ vfModule.setVolumeHeatTemplate(createHeatTemplate(MODULE_HEAT_TEMPLATE_NAME, MODULE_HEAT_TEMPLATE_BODY,
+ NESTED_TEMPLATE_NAME, NESTED_TEMPLATE_BODY));
vfModuleCustomization.setVfModule(vfModule);
// WHEN
- VduModelInfo vduModelInfo = new VfModuleCustomizationToVduMapper()
- .mapVfModuleCustVolumeToVdu(vfModuleCustomization);
+ VduModelInfo vduModelInfo =
+ new VfModuleCustomizationToVduMapper().mapVfModuleCustVolumeToVdu(vfModuleCustomization);
// THEN
assertThat(vduModelInfo.getModelCustomizationUUID()).isEqualTo(MODEL_CUSTOMIZATION_UUID);
@@ -119,7 +116,7 @@ public class VfModuleCustomizationToVduMapperTest {
}
private HeatTemplate createHeatTemplate(String moduleHeatTemplateName, String moduleHeatTemplateBody,
- String childTemplateName, String childTemplateBody) {
+ String childTemplateName, String childTemplateBody) {
HeatTemplate heatTemplate = new HeatTemplate();
heatTemplate.setTemplateName(moduleHeatTemplateName);
heatTemplate.setTemplateBody(moduleHeatTemplateBody);
@@ -137,10 +134,10 @@ public class VfModuleCustomizationToVduMapperTest {
private List<VduArtifact> createExpectedVduArtifacts() {
return Lists.newArrayList(
- new VduArtifact(MODULE_HEAT_TEMPLATE_NAME, MODULE_HEAT_TEMPLATE_BODY.getBytes(),
- ArtifactType.MAIN_TEMPLATE),
- new VduArtifact(NESTED_TEMPLATE_NAME, NESTED_TEMPLATE_BODY.getBytes(), ArtifactType.NESTED_TEMPLATE),
- new VduArtifact(CLOUD_FILE_NAME, CLOUD_FILE_BODY.getBytes(), ArtifactType.TEXT_FILE),
- new VduArtifact(HEAT_ENV_NAME, HEAT_ENV_CONTENT.getBytes(), ArtifactType.ENVIRONMENT));
+ new VduArtifact(MODULE_HEAT_TEMPLATE_NAME, MODULE_HEAT_TEMPLATE_BODY.getBytes(),
+ ArtifactType.MAIN_TEMPLATE),
+ new VduArtifact(NESTED_TEMPLATE_NAME, NESTED_TEMPLATE_BODY.getBytes(), ArtifactType.NESTED_TEMPLATE),
+ new VduArtifact(CLOUD_FILE_NAME, CLOUD_FILE_BODY.getBytes(), ArtifactType.TEXT_FILE),
+ new VduArtifact(HEAT_ENV_NAME, HEAT_ENV_CONTENT.getBytes(), ArtifactType.ENVIRONMENT));
}
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/AllTestsTestSuite.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/AllTestsTestSuite.java
index f086653fea..a7bddd3ada 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/AllTestsTestSuite.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/AllTestsTestSuite.java
@@ -19,14 +19,14 @@
*/
package org.onap.so.adapters.vnf;
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses("**/*Test.class")
public class AllTestsTestSuite {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BaseRestTestUtils.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BaseRestTestUtils.java
index b9edb68bb1..102d748d56 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BaseRestTestUtils.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BaseRestTestUtils.java
@@ -23,14 +23,11 @@ package org.onap.so.adapters.vnf;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
-
import javax.ws.rs.core.MediaType;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
@@ -51,7 +48,6 @@ import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
@@ -59,108 +55,111 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.WireMockServer;
@RunWith(SpringRunner.class)
-@SpringBootTest(classes = MsoOpenstackAdaptersApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@SpringBootTest(classes = MsoOpenstackAdaptersApplication.class,
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@AutoConfigureWireMock(port = 0)
public abstract class BaseRestTestUtils {
- @Value("${wiremock.server.port}")
+ @Value("${wiremock.server.port}")
protected int wireMockPort;
-
- @Autowired
- protected WireMockServer wireMockServer;
-
- @Autowired
- CloudConfig cloudConfig;
-
- @Autowired
- @Qualifier("JettisonStyle")
- protected TestRestTemplate restTemplate;
-
- protected HttpHeaders headers = new HttpHeaders();
-
- @LocalServerPort
- private int port;
-
- public ObjectMapper mapper;
-
- public String orchestrator = "orchestrator";
- public String cloudEndpoint = "/v2.0";
-
-
- protected String readJsonFileAsString(String fileLocation) throws JsonParseException, JsonMappingException, IOException{
- ObjectMapper mapper = new ObjectMapper();
- JsonNode jsonNode = mapper.readTree(new File(fileLocation));
- return jsonNode.asText();
- }
-
- protected String createURLWithPort(String uri) {
- return "http://localhost:" + port + uri;
- }
-
- protected String readFile(String fileName) throws IOException {
- try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
- StringBuilder sb = new StringBuilder();
- String line = br.readLine();
-
- while (line != null) {
- sb.append(line);
- sb.append("\n");
- line = br.readLine();
- }
- return sb.toString();
- }
- }
-
- /***
- * Before each test execution, updating IdentityUrl port value to the ramdom wireMockPort
- * Since URL will be used as a rest call and required to be mocked in unit tests
- */
- @Before
- public void setUp() throws Exception {
- wireMockServer.resetAll();
- mapper = new ObjectMapper();
- CloudIdentity identity = new CloudIdentity();
- identity.setId("MTN13");
- identity.setMsoId("m93945");
- identity.setMsoPass("93937EA01B94A10A49279D4572B48369");
- identity.setAdminTenant("admin");
- identity.setMemberRole("admin");
- identity.setTenantMetadata(new Boolean(true));
- identity.setIdentityUrl("http://localhost:" + wireMockPort + cloudEndpoint);
-
- identity.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
-
- CloudSite cloudSite = new CloudSite();
- cloudSite.setId("MTN13");
- cloudSite.setCloudVersion("3.0");
- cloudSite.setClli("MDT13");
- cloudSite.setRegionId("mtn13");
- cloudSite.setOrchestrator(orchestrator);
- identity.setIdentityServerType(ServerType.KEYSTONE);
- cloudSite.setIdentityService(identity);
-
- wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/MTN13")).willReturn(aResponse()
- .withBody(getBody(mapper.writeValueAsString(cloudSite),wireMockPort, ""))
- .withHeader(org.apache.http.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/DEFAULT")).willReturn(aResponse()
- .withBody(getBody(mapper.writeValueAsString(cloudSite),wireMockPort, ""))
- .withHeader(org.apache.http.HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/cloudIdentity/MTN13")).willReturn(aResponse()
- .withBody(getBody(mapper.writeValueAsString(identity),wireMockPort, ""))
- .withHeader(org.apache.http.HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- cloudConfig.getCloudSite("MTN13").get().getIdentityService().setIdentityUrl("http://localhost:" + wireMockPort + cloudEndpoint);
- }
-
- protected static String getBody(String body, int port, String urlPath) throws IOException {
- return body.replaceAll("port", "http://localhost:" + port + urlPath);
- }
-
- @Test
- public void testNothing(){
-
- }
+
+ @Autowired
+ protected WireMockServer wireMockServer;
+
+ @Autowired
+ CloudConfig cloudConfig;
+
+ @Autowired
+ @Qualifier("JettisonStyle")
+ protected TestRestTemplate restTemplate;
+
+ protected HttpHeaders headers = new HttpHeaders();
+
+ @LocalServerPort
+ private int port;
+
+ public ObjectMapper mapper;
+
+ public String orchestrator = "orchestrator";
+ public String cloudEndpoint = "/v2.0";
+
+
+ protected String readJsonFileAsString(String fileLocation)
+ throws JsonParseException, JsonMappingException, IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ JsonNode jsonNode = mapper.readTree(new File(fileLocation));
+ return jsonNode.asText();
+ }
+
+ protected String createURLWithPort(String uri) {
+ return "http://localhost:" + port + uri;
+ }
+
+ protected String readFile(String fileName) throws IOException {
+ try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+
+ while (line != null) {
+ sb.append(line);
+ sb.append("\n");
+ line = br.readLine();
+ }
+ return sb.toString();
+ }
+ }
+
+ /***
+ * Before each test execution, updating IdentityUrl port value to the ramdom wireMockPort Since URL will be used as
+ * a rest call and required to be mocked in unit tests
+ */
+ @Before
+ public void setUp() throws Exception {
+ wireMockServer.resetAll();
+ mapper = new ObjectMapper();
+ CloudIdentity identity = new CloudIdentity();
+ identity.setId("MTN13");
+ identity.setMsoId("m93945");
+ identity.setMsoPass("93937EA01B94A10A49279D4572B48369");
+ identity.setAdminTenant("admin");
+ identity.setMemberRole("admin");
+ identity.setTenantMetadata(new Boolean(true));
+ identity.setIdentityUrl("http://localhost:" + wireMockPort + cloudEndpoint);
+
+ identity.setIdentityAuthenticationType(AuthenticationType.USERNAME_PASSWORD);
+
+ CloudSite cloudSite = new CloudSite();
+ cloudSite.setId("MTN13");
+ cloudSite.setCloudVersion("3.0");
+ cloudSite.setClli("MDT13");
+ cloudSite.setRegionId("mtn13");
+ cloudSite.setOrchestrator(orchestrator);
+ identity.setIdentityServerType(ServerType.KEYSTONE);
+ cloudSite.setIdentityService(identity);
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/MTN13"))
+ .willReturn(aResponse().withBody(getBody(mapper.writeValueAsString(cloudSite), wireMockPort, ""))
+ .withHeader(org.apache.http.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/cloudSite/DEFAULT"))
+ .willReturn(aResponse().withBody(getBody(mapper.writeValueAsString(cloudSite), wireMockPort, ""))
+ .withHeader(org.apache.http.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/cloudIdentity/MTN13"))
+ .willReturn(aResponse().withBody(getBody(mapper.writeValueAsString(identity), wireMockPort, ""))
+ .withHeader(org.apache.http.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+ cloudConfig.getCloudSite("MTN13").get().getIdentityService()
+ .setIdentityUrl("http://localhost:" + wireMockPort + cloudEndpoint);
+ }
+
+ protected static String getBody(String body, int port, String urlPath) throws IOException {
+ return body.replaceAll("port", "http://localhost:" + port + urlPath);
+ }
+
+ @Test
+ public void testNothing() {
+
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BpelRestClientTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BpelRestClientTest.java
index 4b2fa8138a..883009216f 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BpelRestClientTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/BpelRestClientTest.java
@@ -21,33 +21,31 @@
package org.onap.so.adapters.vnf;
import static org.junit.Assert.assertEquals;
-
import javax.inject.Provider;
-
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.web.server.LocalServerPort;
-public class BpelRestClientTest extends BaseRestTestUtils{
-
-
- @LocalServerPort
- private int port;
- @Autowired
- private Provider<BpelRestClient> clientProvider;
-
- @Test
- public void verifyPropertiesRead() {
- BpelRestClient client = clientProvider.get();
-
- assertEquals(5, client.getRetryCount());
- assertEquals(30, client.getConnectTimeout());
- assertEquals("test:test", client.getCredentials());
- assertEquals(30, client.getSocketTimeout());
- assertEquals("408, 429, 500, 502, 503, 504, 900", client.getRetryList());
- assertEquals(-15, client.getRetryInterval());
-
- }
+public class BpelRestClientTest extends BaseRestTestUtils {
+
+
+ @LocalServerPort
+ private int port;
+ @Autowired
+ private Provider<BpelRestClient> clientProvider;
+
+ @Test
+ public void verifyPropertiesRead() {
+ BpelRestClient client = clientProvider.get();
+
+ assertEquals(5, client.getRetryCount());
+ assertEquals(30, client.getConnectTimeout());
+ assertEquals("test:test", client.getCredentials());
+ assertEquals(30, client.getSocketTimeout());
+ assertEquals("408, 429, 500, 502, 503, 504, 900", client.getRetryList());
+ assertEquals(-15, client.getRetryInterval());
+
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImplTest.java
index 02fbe2c530..46d9f89303 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImplTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImplTest.java
@@ -29,10 +29,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackVfModule_200;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccess;
-
import java.util.HashMap;
import java.util.Map;
-
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
@@ -43,110 +41,109 @@ import org.springframework.beans.factory.annotation.Autowired;
public class MsoVnfAdapterAsyncImplTest extends BaseRestTestUtils {
- @Autowired
- MsoVnfAdapterAsyncImpl instance;
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Test
- public void healthCheckVNFTest() {
- instance.healthCheckA();
- }
-
- @Test
- public void createVNFTest() throws Exception {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_200(wireMockServer);
- wireMockServer.stubFor(post(urlPathEqualTo("/notify/adapterNotify/updateVnfNotificationRequest")).withRequestBody
- (containing("messageId"))
- .willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
-
- String vnfName = "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId";
- String notificationUrl = "http://localhost:"+wireMockPort+"/notify/adapterNotify/updateVnfNotificationRequest";
- instance.createVnfA("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
- "volumeGroupHeatStackId|1", new HashMap<String, Object>(), Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, "messageId",
- msoRequest, notificationUrl);
-
- wireMockServer.verify(1,postRequestedFor(urlEqualTo("/notify/adapterNotify/updateVnfNotificationRequest")));
- }
-
- @Test
- public void createVNFTest_Exception() throws Exception {
- String notificationUrl = "http://localhost:"+wireMockPort+"/notify/adapterNotify/updateVnfNotificationRequest";
- instance.createVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD",
- "volumeGroupHeatStackId|1", new HashMap<String, Object>(), Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, "messageId",
- null, notificationUrl);
-
- wireMockServer.verify(1,postRequestedFor(urlEqualTo("/notify/adapterNotify/updateVnfNotificationRequest")));
-
- }
-
- @Test
- public void updateVnfTest() throws Exception{
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- wireMockServer.stubFor(post(urlPathEqualTo("/notify/adapterNotify/updateVnfNotificationRequest")).withRequestBody
- (containing("messageId"))
- .willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
- String notificationUrl = "http://localhost:"+wireMockPort+"/notify/adapterNotify/updateVnfNotificationRequest";
- instance.updateVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD",
- "volumeGroupHeatStackId|1", map, "messageId", msoRequest,
- notificationUrl);
- }
-
- @Test
- public void updateVnfTest_Exception() throws Exception{
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- wireMockServer.stubFor(post(urlPathEqualTo("/notify/adapterNotify/updateVnfNotificationRequest")).withRequestBody
- (containing("messageId"))
- .willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
- String notificationUrl = "http://localhost:"+wireMockPort+"/notify/adapterNotify/updateVnfNotificationRequest";
- instance.updateVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD",
- "volumeGroupHeatStackId|1", map, "messageId", msoRequest,
- notificationUrl);
- wireMockServer.verify(1,postRequestedFor(urlEqualTo("/notify/adapterNotify/updateVnfNotificationRequest")));
- }
-
- @Test
- public void queryVnfTest() {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
- instance.queryVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", "messageId", msoRequest,
- "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest");
- }
-
- @Test
- public void deleteVnfTest() {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
- instance.deleteVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", "messageId", msoRequest,
- "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest");
- }
-
- @Test
- public void rollbackVnfTest() {
- VnfRollback vnfRollBack = new VnfRollback();
- vnfRollBack.setCloudSiteId("mdt1");
- vnfRollBack.setCloudOwner("CloudOwner");
- vnfRollBack.setTenantId("88a6ca3ee0394ade9403f075db23167e");
- vnfRollBack.setVnfId("ff5256d1-5a33-55df-13ab-12abad84e7ff");
- instance.rollbackVnfA(vnfRollBack, "messageId",
- "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest");
- }
+ @Autowired
+ MsoVnfAdapterAsyncImpl instance;
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Test
+ public void healthCheckVNFTest() {
+ instance.healthCheckA();
+ }
+
+ @Test
+ public void createVNFTest() throws Exception {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+ wireMockServer.stubFor(post(urlPathEqualTo("/notify/adapterNotify/updateVnfNotificationRequest"))
+ .withRequestBody(containing("messageId")).willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
+
+ String vnfName = "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId";
+ String notificationUrl =
+ "http://localhost:" + wireMockPort + "/notify/adapterNotify/updateVnfNotificationRequest";
+ instance.createVnfA("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
+ "volumeGroupHeatStackId|1", new HashMap<String, Object>(), Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
+ "messageId", msoRequest, notificationUrl);
+
+ wireMockServer.verify(1, postRequestedFor(urlEqualTo("/notify/adapterNotify/updateVnfNotificationRequest")));
+ }
+
+ @Test
+ public void createVNFTest_Exception() throws Exception {
+ String notificationUrl =
+ "http://localhost:" + wireMockPort + "/notify/adapterNotify/updateVnfNotificationRequest";
+ instance.createVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD",
+ "volumeGroupHeatStackId|1", new HashMap<String, Object>(), Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
+ "messageId", null, notificationUrl);
+
+ wireMockServer.verify(1, postRequestedFor(urlEqualTo("/notify/adapterNotify/updateVnfNotificationRequest")));
+
+ }
+
+ @Test
+ public void updateVnfTest() throws Exception {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ wireMockServer.stubFor(post(urlPathEqualTo("/notify/adapterNotify/updateVnfNotificationRequest"))
+ .withRequestBody(containing("messageId")).willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
+ String notificationUrl =
+ "http://localhost:" + wireMockPort + "/notify/adapterNotify/updateVnfNotificationRequest";
+ instance.updateVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD",
+ "volumeGroupHeatStackId|1", map, "messageId", msoRequest, notificationUrl);
+ }
+
+ @Test
+ public void updateVnfTest_Exception() throws Exception {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ wireMockServer.stubFor(post(urlPathEqualTo("/notify/adapterNotify/updateVnfNotificationRequest"))
+ .withRequestBody(containing("messageId")).willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
+ String notificationUrl =
+ "http://localhost:" + wireMockPort + "/notify/adapterNotify/updateVnfNotificationRequest";
+ instance.updateVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD",
+ "volumeGroupHeatStackId|1", map, "messageId", msoRequest, notificationUrl);
+ wireMockServer.verify(1, postRequestedFor(urlEqualTo("/notify/adapterNotify/updateVnfNotificationRequest")));
+ }
+
+ @Test
+ public void queryVnfTest() {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+ instance.queryVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", "messageId", msoRequest,
+ "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest");
+ }
+
+ @Test
+ public void deleteVnfTest() {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+ instance.deleteVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", "messageId",
+ msoRequest, "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest");
+ }
+
+ @Test
+ public void rollbackVnfTest() {
+ VnfRollback vnfRollBack = new VnfRollback();
+ vnfRollBack.setCloudSiteId("mdt1");
+ vnfRollBack.setCloudOwner("CloudOwner");
+ vnfRollBack.setTenantId("88a6ca3ee0394ade9403f075db23167e");
+ vnfRollBack.setVnfId("ff5256d1-5a33-55df-13ab-12abad84e7ff");
+ instance.rollbackVnfA(vnfRollBack, "messageId",
+ "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest");
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java
index e40aab9ba1..f314d32328 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java
@@ -30,14 +30,11 @@ import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackVfModule_
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPutStack;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccess;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenstackGetWithResponse;
-
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
-
import javax.xml.ws.Holder;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Ignore;
@@ -61,493 +58,510 @@ import org.onap.so.openstack.beans.VnfRollback;
import org.onap.so.openstack.exceptions.MsoException;
import org.onap.so.openstack.utils.MsoHeatUtils;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.github.tomakehurst.wiremock.client.WireMock;
public class MsoVnfAdapterImplTest extends BaseRestTestUtils {
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Autowired
- private MsoHeatUtils heatUtils;
-
- @Autowired
- MsoVnfAdapterImpl instance;
-
- String vnfName = "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId";
-
- @Test
- @Ignore
- public void healthCheckVNFTest() {
- MsoVnfAdapterImpl instance = new MsoVnfAdapterImpl();
- instance.healthCheck();
- }
-
- @Test
- public void createVnfTest() throws Exception {
- StackInfo info = new StackInfo();
- info.setStatus(HeatStatus.CREATED);
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_200(wireMockServer);
-
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("MTN13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void createVnfTest_HeatStatusUpdating() throws Exception {
- expectedException.expect(VnfAlreadyExists.class);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Stack_Updating_VfModule.json")
- .withStatus(HttpStatus.SC_OK)));
-
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void createVnfTest_HeatStatusUpdated() throws Exception {
- expectedException.expect(VnfAlreadyExists.class);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_StackId.json")
- .withStatus(HttpStatus.SC_OK)));
-
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void createVnfTest_HeatStatusFailed() throws Exception {
- expectedException.expect(VnfAlreadyExists.class);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Stack_Failed_VfModule.json")
- .withStatus(HttpStatus.SC_OK)));
-
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void createVnfTest_HeatStatusCreated() throws Exception {
- expectedException.expect(VnfAlreadyExists.class);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackGetStackVfModule_200(wireMockServer);
-
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
-
- @Test
- public void createVnfTest_ExceptionInGettingHeat() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void createVnfTest_NestedHeatStatusNotFound() throws Exception {
- expectedException.expect(VnfException.class);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_404(wireMockServer);
-
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void createVnfTest_ExceptionInGettingNestedHeat() throws Exception {
- expectedException.expect(VnfException.class);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_404(wireMockServer);
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
-
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void createVnfTest_NestedBaseHeatStatus_NotFound() throws Exception {
- expectedException.expect(VnfException.class);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_404(wireMockServer);
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json")
- .withStatus(HttpStatus.SC_OK)));
-
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void createVnfTest_ExceptionInGettingBaseNestedHeat() throws Exception {
- expectedException.expect(VnfException.class);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_404(wireMockServer);
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId")).willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/baseVfHeatStackId")).willReturn(aResponse().withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
-
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void createVnfTest_ExceptionInCreateStack() throws Exception {
- expectedException.expect(VnfException.class);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_404(wireMockServer);
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId")).willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/baseVfHeatStackId")).willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
-
- VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
- VfModule vfModule = new VfModule();
- vfModule.setIsBase(false);
-
- HeatTemplate heatTemplate = new HeatTemplate();
- heatTemplate.setTemplateBody("");
- heatTemplate.setTimeoutMinutes(200);
- vfModule.setModuleHeatTemplate(heatTemplate);
- vfModuleCustomization.setVfModule(vfModule);
-
- HeatEnvironment heatEnvironment = new HeatEnvironment();
- heatEnvironment.setEnvironment("ist");
- vfModuleCustomization.setHeatEnvironment(heatEnvironment);
-
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void createVnfTest_ModelCustUuidIsNull() throws Exception {
- expectedException.expect(VnfException.class);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_404(wireMockServer);
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId")).willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/baseVfHeatStackId")).willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
-
- VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
- VfModule vfModule = new VfModule();
- vfModule.setIsBase(false);
-
- HeatTemplate heatTemplate = new HeatTemplate();
- heatTemplate.setTemplateBody("");
- heatTemplate.setTimeoutMinutes(200);
- vfModule.setModuleHeatTemplate(heatTemplate);
- vfModuleCustomization.setVfModule(vfModule);
-
- HeatEnvironment heatEnvironment = new HeatEnvironment();
- heatEnvironment.setEnvironment("ist");
- vfModuleCustomization.setHeatEnvironment(heatEnvironment);
-
- VnfResource vnfResource = new VnfResource();
- vnfResource.setAicVersionMin("1");
- vnfResource.setAicVersionMin("3");
-
-
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "XVFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", null, map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void createVnfTest_HeatEnvironment_ContainsParameters() throws Exception {
- expectedException.expect(VnfException.class);
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_404(wireMockServer);
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId")).willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/baseVfHeatStackId")).willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
-
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- private MsoRequest getMsoRequest() {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
- return msoRequest;
- }
-
- @Test
- public void updateVnfTest_CloudSiteIdNotFound() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = getMsoRequest();
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.updateVfModule("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD",
- "volumeGroupHeatStackId|1", "baseVfHeatStackId", "vfModuleStackId",
- "88a6ca3ee0394ade9403f075db23167e", map, msoRequest, new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void updateVnfTest_HeatStackNotFound() throws Exception {
- expectedException.expect(VnfNotFound.class);
- MsoRequest msoRequest = getMsoRequest();
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId",
- "88a6ca3ee0394ade9403f075db23167e", map, msoRequest, new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void updateVnfTest_ExceptionInGettingNestedHeatStack() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = getMsoRequest();
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_200(wireMockServer);
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId",
- "88a6ca3ee0394ade9403f075db23167e", map, msoRequest, new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void updateVnfTest_NestedHeatStackNotFound() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = getMsoRequest();
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_200(wireMockServer);
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_NOT_FOUND)));
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId",
- "88a6ca3ee0394ade9403f075db23167e", map, msoRequest, new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void updateVnfTest_ExceptionInGettingNestedBaseHeatStack() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = getMsoRequest();
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_200(wireMockServer);
- mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/volumeGroupHeatStackId",HttpStatus.SC_OK,"OpenstackResponse_Stack_Created_VfModule.json");
- mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/baseVfHeatStackId",HttpStatus.SC_INTERNAL_SERVER_ERROR,"OpenstackResponse_Stack_Created_VfModule.json");
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId",
- "88a6ca3ee0394ade9403f075db23167e", map, msoRequest, new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void updateVnfTest_NestedBaseHeatStackNotFound() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = getMsoRequest();
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_200(wireMockServer);
- mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/volumeGroupHeatStackId",HttpStatus.SC_OK,"OpenstackResponse_Stack_Created_VfModule.json");
- mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/baseVfHeatStackId",HttpStatus.SC_NOT_FOUND,"OpenstackResponse_Stack_Created_VfModule.json");
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId",
- "88a6ca3ee0394ade9403f075db23167e", map, msoRequest, new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void updateVnfTest_MissingParams() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = getMsoRequest();
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_200(wireMockServer);
- mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/volumeGroupHeatStackId",HttpStatus.SC_OK,"OpenstackResponse_Stack_Created_VfModule.json");
- mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/baseVfHeatStackId",HttpStatus.SC_OK,"OpenstackResponse_Stack_Created_VfModule.json");
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId",
- "88a6ca3ee0394ade9403f075db23167e", map, msoRequest, new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void updateVnfTest_UpdateStackException() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = getMsoRequest();
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_200(wireMockServer);
- mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/volumeGroupHeatStackId",HttpStatus.SC_OK,"OpenstackResponse_Stack_Created_VfModule.json");
- mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/baseVfHeatStackId",HttpStatus.SC_OK,"OpenstackResponse_Stack_Created_VfModule.json");
-
- VfModuleCustomization vfModuleCustomization = getVfModuleCustomization();
- vfModuleCustomization.getVfModule().getModuleHeatTemplate().setParameters(new HashSet<>());
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId",
- "88a6ca3ee0394ade9403f075db23167e", map, msoRequest, new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- public void updateVnfTest() throws Exception {
- MsoRequest msoRequest = getMsoRequest();
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/"+vnfName,HttpStatus.SC_OK,"OpenstackResponse_Stack_UpdateComplete.json");
- mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/volumeGroupHeatStackId",HttpStatus.SC_OK,"OpenstackResponse_Stack_Created_VfModule.json");
- mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/baseVfHeatStackId",HttpStatus.SC_OK,"OpenstackResponse_Stack_Created_VfModule.json");
- mockOpenStackPutStack(wireMockServer, "null/stackId", HttpStatus.SC_OK);
- mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/null/stackId",HttpStatus.SC_OK,"OpenstackResponse_Stack_UpdateComplete.json");
-
- VfModuleCustomization vfModuleCustomization = getVfModuleCustomization();
- vfModuleCustomization.getVfModule().getModuleHeatTemplate().setParameters(new HashSet<>());
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- instance.updateVfModule("MTN13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId",
- "b4ea86b4-253f-11e7-93ae-92361f002671", map, msoRequest, new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
- }
-
- @Test
- @Ignore
- public void deleteVnfTest() throws MsoException {
-
- Map<String, Object> outputs = new HashMap<>();
- outputs.put("Key1", "value1");
- when(heatUtils.queryStackForOutputs("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12")).thenReturn(outputs);
-
- MsoVnfAdapterImpl instance = new MsoVnfAdapterImpl();
- MsoRequest msoRequest = getMsoRequest();
- try {
- instance.deleteVfModule("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", msoRequest,
- new Holder<Map<String, String>>());
- } catch (Exception e) {
-
- }
- }
-
- private VfModuleCustomization getVfModuleCustomization() {
- VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
- VfModule vfModule = new VfModule();
- vfModule.setIsBase(false);
-
- HeatTemplate heatTemplate = new HeatTemplate();
- heatTemplate.setTemplateBody("");
- heatTemplate.setTimeoutMinutes(200);
- HeatTemplateParam heatTemplateParam = new HeatTemplateParam();
- heatTemplateParam.setParamAlias("ParamAlias");
- heatTemplateParam.setRequired(true);
- heatTemplateParam.setParamName("test");
- Set set = new HashSet();
- set.add(heatTemplateParam);
- heatTemplate.setParameters(set);
- vfModule.setModuleHeatTemplate(heatTemplate);
- vfModuleCustomization.setVfModule(vfModule);
-
- HeatEnvironment heatEnvironment = new HeatEnvironment();
- heatEnvironment.setEnvironment("parameters:ist");
- vfModuleCustomization.setHeatEnvironment(heatEnvironment);
- return vfModuleCustomization;
- }
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Autowired
+ private MsoHeatUtils heatUtils;
+
+ @Autowired
+ MsoVnfAdapterImpl instance;
+
+ String vnfName = "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId";
+
+ @Test
+ @Ignore
+ public void healthCheckVNFTest() {
+ MsoVnfAdapterImpl instance = new MsoVnfAdapterImpl();
+ instance.healthCheck();
+ }
+
+ @Test
+ public void createVnfTest() throws Exception {
+ StackInfo info = new StackInfo();
+ info.setStatus(HeatStatus.CREATED);
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("MTN13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
+ Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void createVnfTest_HeatStatusUpdating() throws Exception {
+ expectedException.expect(VnfAlreadyExists.class);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ wireMockServer.stubFor(get(
+ urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_Stack_Updating_VfModule.json")
+ .withStatus(HttpStatus.SC_OK)));
+
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
+ Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void createVnfTest_HeatStatusUpdated() throws Exception {
+ expectedException.expect(VnfAlreadyExists.class);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ wireMockServer.stubFor(get(
+ urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK)));
+
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
+ Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void createVnfTest_HeatStatusFailed() throws Exception {
+ expectedException.expect(VnfAlreadyExists.class);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ wireMockServer.stubFor(get(
+ urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_Stack_Failed_VfModule.json")
+ .withStatus(HttpStatus.SC_OK)));
+
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
+ Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void createVnfTest_HeatStatusCreated() throws Exception {
+ expectedException.expect(VnfAlreadyExists.class);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
+ Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+
+ @Test
+ public void createVnfTest_ExceptionInGettingHeat() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
+ Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void createVnfTest_NestedHeatStatusNotFound() throws Exception {
+ expectedException.expect(VnfException.class);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_404(wireMockServer);
+
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "VFMOD", "volumeGroupHeatStackId", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
+ Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void createVnfTest_ExceptionInGettingNestedHeat() throws Exception {
+ expectedException.expect(VnfException.class);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_404(wireMockServer);
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "VFMOD", "volumeGroupHeatStackId", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
+ Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void createVnfTest_NestedBaseHeatStatus_NotFound() throws Exception {
+ expectedException.expect(VnfException.class);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_404(wireMockServer);
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
+
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "VFMOD", "volumeGroupHeatStackId", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
+ Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void createVnfTest_ExceptionInGettingBaseNestedHeat() throws Exception {
+ expectedException.expect(VnfException.class);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_404(wireMockServer);
+ wireMockServer
+ .stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId")).willReturn(aResponse()
+ .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/baseVfHeatStackId"))
+ .willReturn(aResponse().withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "VFMOD", "volumeGroupHeatStackId", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
+ Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void createVnfTest_ExceptionInCreateStack() throws Exception {
+ expectedException.expect(VnfException.class);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_404(wireMockServer);
+ wireMockServer
+ .stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId")).willReturn(aResponse()
+ .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/baseVfHeatStackId")).willReturn(aResponse()
+ .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
+
+ VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
+ VfModule vfModule = new VfModule();
+ vfModule.setIsBase(false);
+
+ HeatTemplate heatTemplate = new HeatTemplate();
+ heatTemplate.setTemplateBody("");
+ heatTemplate.setTimeoutMinutes(200);
+ vfModule.setModuleHeatTemplate(heatTemplate);
+ vfModuleCustomization.setVfModule(vfModule);
+
+ HeatEnvironment heatEnvironment = new HeatEnvironment();
+ heatEnvironment.setEnvironment("ist");
+ vfModuleCustomization.setHeatEnvironment(heatEnvironment);
+
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "VFMOD", "volumeGroupHeatStackId", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
+ Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void createVnfTest_ModelCustUuidIsNull() throws Exception {
+ expectedException.expect(VnfException.class);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_404(wireMockServer);
+ wireMockServer
+ .stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId")).willReturn(aResponse()
+ .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/baseVfHeatStackId")).willReturn(aResponse()
+ .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
+
+ VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
+ VfModule vfModule = new VfModule();
+ vfModule.setIsBase(false);
+
+ HeatTemplate heatTemplate = new HeatTemplate();
+ heatTemplate.setTemplateBody("");
+ heatTemplate.setTimeoutMinutes(200);
+ vfModule.setModuleHeatTemplate(heatTemplate);
+ vfModuleCustomization.setVfModule(vfModule);
+
+ HeatEnvironment heatEnvironment = new HeatEnvironment();
+ heatEnvironment.setEnvironment("ist");
+ vfModuleCustomization.setHeatEnvironment(heatEnvironment);
+
+ VnfResource vnfResource = new VnfResource();
+ vnfResource.setAicVersionMin("1");
+ vnfResource.setAicVersionMin("3");
+
+
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "XVFMOD", "volumeGroupHeatStackId", "baseVfHeatStackId", null, map, Boolean.FALSE, Boolean.TRUE,
+ Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
+ new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void createVnfTest_HeatEnvironment_ContainsParameters() throws Exception {
+ expectedException.expect(VnfException.class);
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_404(wireMockServer);
+ wireMockServer
+ .stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId")).willReturn(aResponse()
+ .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/baseVfHeatStackId")).willReturn(aResponse()
+ .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
+
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "",
+ "VFMOD", "volumeGroupHeatStackId", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
+ Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ private MsoRequest getMsoRequest() {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+ return msoRequest;
+ }
+
+ @Test
+ public void updateVnfTest_CloudSiteIdNotFound() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = getMsoRequest();
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.updateVfModule("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12",
+ "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "vfModuleStackId",
+ "88a6ca3ee0394ade9403f075db23167e", map, msoRequest, new Holder<Map<String, String>>(),
+ new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void updateVnfTest_HeatStackNotFound() throws Exception {
+ expectedException.expect(VnfNotFound.class);
+ MsoRequest msoRequest = getMsoRequest();
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
+ "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId", "88a6ca3ee0394ade9403f075db23167e",
+ map, msoRequest, new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void updateVnfTest_ExceptionInGettingNestedHeatStack() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = getMsoRequest();
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
+ "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId", "88a6ca3ee0394ade9403f075db23167e",
+ map, msoRequest, new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void updateVnfTest_NestedHeatStackNotFound() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = getMsoRequest();
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId")).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND)));
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
+ "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId", "88a6ca3ee0394ade9403f075db23167e",
+ map, msoRequest, new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void updateVnfTest_ExceptionInGettingNestedBaseHeatStack() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = getMsoRequest();
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+ mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/volumeGroupHeatStackId", HttpStatus.SC_OK,
+ "OpenstackResponse_Stack_Created_VfModule.json");
+ mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/baseVfHeatStackId",
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, "OpenstackResponse_Stack_Created_VfModule.json");
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
+ "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId", "88a6ca3ee0394ade9403f075db23167e",
+ map, msoRequest, new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void updateVnfTest_NestedBaseHeatStackNotFound() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = getMsoRequest();
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+ mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/volumeGroupHeatStackId", HttpStatus.SC_OK,
+ "OpenstackResponse_Stack_Created_VfModule.json");
+ mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/baseVfHeatStackId", HttpStatus.SC_NOT_FOUND,
+ "OpenstackResponse_Stack_Created_VfModule.json");
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
+ "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId", "88a6ca3ee0394ade9403f075db23167e",
+ map, msoRequest, new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void updateVnfTest_MissingParams() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = getMsoRequest();
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+ mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/volumeGroupHeatStackId", HttpStatus.SC_OK,
+ "OpenstackResponse_Stack_Created_VfModule.json");
+ mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/baseVfHeatStackId", HttpStatus.SC_OK,
+ "OpenstackResponse_Stack_Created_VfModule.json");
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
+ "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId", "88a6ca3ee0394ade9403f075db23167e",
+ map, msoRequest, new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void updateVnfTest_UpdateStackException() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = getMsoRequest();
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+ mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/volumeGroupHeatStackId", HttpStatus.SC_OK,
+ "OpenstackResponse_Stack_Created_VfModule.json");
+ mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/baseVfHeatStackId", HttpStatus.SC_OK,
+ "OpenstackResponse_Stack_Created_VfModule.json");
+
+ VfModuleCustomization vfModuleCustomization = getVfModuleCustomization();
+ vfModuleCustomization.getVfModule().getModuleHeatTemplate().setParameters(new HashSet<>());
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.updateVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
+ "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId", "88a6ca3ee0394ade9403f075db23167e",
+ map, msoRequest, new Holder<Map<String, String>>(), new Holder<VnfRollback>());
+ }
+
+ @Test
+ public void updateVnfTest() throws Exception {
+ MsoRequest msoRequest = getMsoRequest();
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/" + vnfName, HttpStatus.SC_OK,
+ "OpenstackResponse_Stack_UpdateComplete.json");
+ mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/volumeGroupHeatStackId", HttpStatus.SC_OK,
+ "OpenstackResponse_Stack_Created_VfModule.json");
+ mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/baseVfHeatStackId", HttpStatus.SC_OK,
+ "OpenstackResponse_Stack_Created_VfModule.json");
+ mockOpenStackPutStack(wireMockServer, "null/stackId", HttpStatus.SC_OK);
+ mockOpenstackGetWithResponse(wireMockServer, "/mockPublicUrl/stacks/null/stackId", HttpStatus.SC_OK,
+ "OpenstackResponse_Stack_UpdateComplete.json");
+
+ VfModuleCustomization vfModuleCustomization = getVfModuleCustomization();
+ vfModuleCustomization.getVfModule().getModuleHeatTemplate().setParameters(new HashSet<>());
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ instance.updateVfModule("MTN13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", vnfName, "VFMOD",
+ "volumeGroupHeatStackId", "baseVfHeatStackId", "vfModuleStackId",
+ "b4ea86b4-253f-11e7-93ae-92361f002671", map, msoRequest, new Holder<Map<String, String>>(),
+ new Holder<VnfRollback>());
+ }
+
+ @Test
+ @Ignore
+ public void deleteVnfTest() throws MsoException {
+
+ Map<String, Object> outputs = new HashMap<>();
+ outputs.put("Key1", "value1");
+ when(heatUtils.queryStackForOutputs("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12"))
+ .thenReturn(outputs);
+
+ MsoVnfAdapterImpl instance = new MsoVnfAdapterImpl();
+ MsoRequest msoRequest = getMsoRequest();
+ try {
+ instance.deleteVfModule("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", msoRequest,
+ new Holder<Map<String, String>>());
+ } catch (Exception e) {
+
+ }
+ }
+
+ private VfModuleCustomization getVfModuleCustomization() {
+ VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
+ VfModule vfModule = new VfModule();
+ vfModule.setIsBase(false);
+
+ HeatTemplate heatTemplate = new HeatTemplate();
+ heatTemplate.setTemplateBody("");
+ heatTemplate.setTimeoutMinutes(200);
+ HeatTemplateParam heatTemplateParam = new HeatTemplateParam();
+ heatTemplateParam.setParamAlias("ParamAlias");
+ heatTemplateParam.setRequired(true);
+ heatTemplateParam.setParamName("test");
+ Set set = new HashSet();
+ set.add(heatTemplateParam);
+ heatTemplate.setParameters(set);
+ vfModule.setModuleHeatTemplate(heatTemplate);
+ vfModuleCustomization.setVfModule(vfModule);
+
+ HeatEnvironment heatEnvironment = new HeatEnvironment();
+ heatEnvironment.setEnvironment("parameters:ist");
+ vfModuleCustomization.setHeatEnvironment(heatEnvironment);
+ return vfModuleCustomization;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImplTest.java
index 0ace6e4249..3e5d4ad29a 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImplTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImplTest.java
@@ -26,12 +26,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.junit.Assert.assertTrue;
-
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.ws.Holder;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Rule;
@@ -46,102 +43,96 @@ import org.springframework.beans.factory.annotation.Autowired;
public class MsoVnfCloudifyAdapterImplTest extends BaseRestTestUtils {
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Autowired
- private MsoVnfCloudifyAdapterImpl instance;
-
- @Autowired
- private CloudConfig cloudConfig;
-
- @Before
- public void before() throws Exception {
- super.setUp();
- CloudifyManager cloudifyManager = new CloudifyManager();
- cloudifyManager.setId("mtn13");
- cloudifyManager.setCloudifyUrl("http://localhost:"+wireMockPort+"/v2.0");
- cloudifyManager.setUsername("m93945");
- cloudifyManager.setPassword("93937EA01B94A10A49279D4572B48369");
- }
-
- @Test
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Autowired
+ private MsoVnfCloudifyAdapterImpl instance;
+
+ @Autowired
+ private CloudConfig cloudConfig;
+
+ @Before
+ public void before() throws Exception {
+ super.setUp();
+ CloudifyManager cloudifyManager = new CloudifyManager();
+ cloudifyManager.setId("mtn13");
+ cloudifyManager.setCloudifyUrl("http://localhost:" + wireMockPort + "/v2.0");
+ cloudifyManager.setUsername("m93945");
+ cloudifyManager.setPassword("93937EA01B94A10A49279D4572B48369");
+ }
+
+ @Test
public void queryVnfExceptionTest() throws Exception {
MsoRequest msoRequest = new MsoRequest();
msoRequest.setRequestId("12345");
msoRequest.setServiceInstanceId("12345");
- Holder <Map <String, String>> outputs = new Holder<>();
- instance.queryVnf("siteid", "CloudOwner", "1234", "vfname",
- msoRequest, new Holder<>(), new Holder<>(), new Holder<>(),
- outputs);
-
+ Holder<Map<String, String>> outputs = new Holder<>();
+ instance.queryVnf("siteid", "CloudOwner", "1234", "vfname", msoRequest, new Holder<>(), new Holder<>(),
+ new Holder<>(), outputs);
+
assertTrue(outputs.value.isEmpty());
}
- @Test
- public void queryVnfTest() throws Exception {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
- wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname")).willReturn(aResponse()
- .withBody("{ \"id\": \"123\" }")
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname/outputs")).willReturn(aResponse()
- .withBody("{ \"deployment_id\": \"123\",\"outputs\":{\"abc\":\"abc\"} }")
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching("/v2.0/api/v3/executions?.*")).willReturn(aResponse()
- .withBody("{ \"items\": {\"id\": \"123\",\"workflow_id\":\"install\",\"status\":\"terminated\" } } ")
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/tokens")).willReturn(aResponse()
- .withBodyFile("OpenstackResponse_Access.json")
- .withStatus(HttpStatus.SC_OK)));
-
- instance.queryVnf("mtn13", "CloudOwner", "1234", "vfname",
- msoRequest, new Holder<>(), new Holder<>(), new Holder<>(),
- new Holder<>());
- }
-
- @Test
- public void deleteVfModuleTest_ExceptionWhileQueryDeployment() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- instance.deleteVfModule("mtn13", "CloudOwner", "1234", "vfname", msoRequest, new Holder<>());
- }
-
- @Test
- public void deleteVfModuleTest_ExceptionWhileDeleteDeployment() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
- wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname")).willReturn(aResponse()
- .withBody("{ \"id\": \"123\" }")
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname/outputs")).willReturn(aResponse()
- .withBody("{ \"deployment_id\": \"123\",\"outputs\":{\"abc\":\"abc\"} }")
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching("/v2.0/api/v3/executions?.*")).willReturn(aResponse()
- .withBody("{ \"items\": {\"id\": \"123\",\"workflow_id\":\"install\",\"status\":\"terminated\" } } ")
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/tokens")).willReturn(aResponse()
- .withBodyFile("OpenstackResponse_Access.json")
- .withStatus(HttpStatus.SC_OK)));
-
- instance.deleteVfModule("mtn13", "CloudOwner", "1234", "vfname", msoRequest, new Holder<>());
- }
-
- @Test
+ @Test
+ public void queryVnfTest() throws Exception {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+ wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname"))
+ .willReturn(aResponse().withBody("{ \"id\": \"123\" }").withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname/outputs"))
+ .willReturn(aResponse().withBody("{ \"deployment_id\": \"123\",\"outputs\":{\"abc\":\"abc\"} }")
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching("/v2.0/api/v3/executions?.*")).willReturn(aResponse()
+ .withBody("{ \"items\": {\"id\": \"123\",\"workflow_id\":\"install\",\"status\":\"terminated\" } } ")
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/tokens"))
+ .willReturn(aResponse().withBodyFile("OpenstackResponse_Access.json").withStatus(HttpStatus.SC_OK)));
+
+ instance.queryVnf("mtn13", "CloudOwner", "1234", "vfname", msoRequest, new Holder<>(), new Holder<>(),
+ new Holder<>(), new Holder<>());
+ }
+
+ @Test
+ public void deleteVfModuleTest_ExceptionWhileQueryDeployment() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ instance.deleteVfModule("mtn13", "CloudOwner", "1234", "vfname", msoRequest, new Holder<>());
+ }
+
+ @Test
+ public void deleteVfModuleTest_ExceptionWhileDeleteDeployment() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+ wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname"))
+ .willReturn(aResponse().withBody("{ \"id\": \"123\" }").withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname/outputs"))
+ .willReturn(aResponse().withBody("{ \"deployment_id\": \"123\",\"outputs\":{\"abc\":\"abc\"} }")
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching("/v2.0/api/v3/executions?.*")).willReturn(aResponse()
+ .withBody("{ \"items\": {\"id\": \"123\",\"workflow_id\":\"install\",\"status\":\"terminated\" } } ")
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/tokens"))
+ .willReturn(aResponse().withBodyFile("OpenstackResponse_Access.json").withStatus(HttpStatus.SC_OK)));
+
+ instance.deleteVfModule("mtn13", "CloudOwner", "1234", "vfname", msoRequest, new Holder<>());
+ }
+
+ @Test
public void deleteVnfVnfExceptionTest() throws Exception {
- expectedException.expect(VnfException.class);
+ expectedException.expect(VnfException.class);
MsoRequest msoRequest = new MsoRequest();
msoRequest.setRequestId("12345");
msoRequest.setServiceInstanceId("12345");
@@ -150,165 +141,169 @@ public class MsoVnfCloudifyAdapterImplTest extends BaseRestTestUtils {
}
- @Test
- public void rollbackVnf() throws Exception {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
+ @Test
+ public void rollbackVnf() throws Exception {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ VnfRollback vnfRollback = new VnfRollback();
+ vnfRollback.setModelCustomizationUuid("1234");
+ vnfRollback.setVfModuleStackId("2134");
+ vnfRollback.setVnfId("123");
+ vnfRollback.setModelCustomizationUuid("1234");
+
+ instance.rollbackVnf(vnfRollback);
+ }
+
+ @Test
+ public void rollbackVnf_Created() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
VnfRollback vnfRollback = new VnfRollback();
vnfRollback.setModelCustomizationUuid("1234");
vnfRollback.setVfModuleStackId("2134");
vnfRollback.setVnfId("123");
vnfRollback.setModelCustomizationUuid("1234");
+ vnfRollback.setVnfCreated(true);
instance.rollbackVnf(vnfRollback);
- }
-
- @Test
- public void rollbackVnf_Created() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- VnfRollback vnfRollback = new VnfRollback();
- vnfRollback.setModelCustomizationUuid("1234");
- vnfRollback.setVfModuleStackId("2134");
- vnfRollback.setVnfId("123");
- vnfRollback.setModelCustomizationUuid("1234");
- vnfRollback.setVnfCreated(true);
-
- instance.rollbackVnf(vnfRollback);
- }
-
- @Test
- public void createVfModuleVnfException() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- instance.createVfModule("123", "CloudOwner", "123", "vf", "v1", "", "module-005", "", "create", "3245", "234", "123", new HashMap<>(), true, true, true, msoRequest, new Holder<>(), new Holder<>(), new Holder<>());
- }
-
- @Test
- public void createVfModule_ModelCustUuidIsNull() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- instance.createVfModule("123", "CloudOwner", "123", "vf", "v1", "", "module-005", "", "create", "3245", "234", null, new
- HashMap<>(), true, true, true, msoRequest, new Holder<>(), new Holder<>(), new Holder<>());
- }
-
- @Test
- public void createVfModule_CloudSiteIdNotFound() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- instance.createVfModule("123", "CloudOwner", "123", "vf", "v1", "", "module-005", "", "create", "3245", "234", "9b339a61-69ca-465f-86b8-1c72c582b8e8", new HashMap<>(), true, true, true, msoRequest, new Holder<>(), new Holder<>(), new Holder<>());
- }
-
- @Test
- public void createVfModule_MsoCloudifyManagerNotFound() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- instance.createVfModule("mtn13", "CloudOwner", "123", "vf", "v1", "", "module-005", "", "create", "3245", "234", "9b339a61-69ca-465f-86b8-1c72c582b8e8", new HashMap<>(), true, true, true, msoRequest, new Holder<>(), new Holder<>(), new Holder<>());
- }
-
- @Test
- public void createVfModule() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname")).willReturn(aResponse()
- .withBody("{ \"id\": \"123\" }")
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname/outputs")).willReturn(aResponse()
- .withBody("{ \"deployment_id\": \"123\",\"outputs\":{\"abc\":\"abc\"} }")
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching("/v2.0/api/v3/executions?.*")).willReturn(aResponse()
- .withBody("{ \"items\": {\"id\": \"123\",\"workflow_id\":\"install\",\"status\":\"terminated\" } } ")
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/tokens")).willReturn(aResponse()
- .withBodyFile("OpenstackResponse_Access.json")
- .withStatus(HttpStatus.SC_OK)));
-
- instance.createVfModule("mtn13", "CloudOwner", "123", "vf", "v1", "", "vfname", "", "create", "3245", "234", "9b339a61-69ca-465f-86b8-1c72c582b8e8", new HashMap<>(), true, true, true, msoRequest, new Holder<>(), new Holder<>(), new Holder<>());
- }
-
- @Test
- public void updateVfModuleVnfException() throws Exception {
- expectedException.expect(VnfException.class);
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- instance.updateVfModule("123", "CloudOwner", "1234", "fw", "v2", "vnf1", "create", "123", "12", "233", "234", new HashMap<>(), msoRequest, new Holder<>(), new Holder<>());
- }
-
- @Test
- public void healthCheckVNFTest() {
- instance.healthCheck();
- }
-
- @Test
- public void createVnfTest() {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- Map<String, Object> map = new HashMap<>();
- map.put("key1", "value1");
- try {
- instance.createVnf("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD",
- "volumeGroupHeatStackId|1", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.TRUE, msoRequest, new Holder<>(), new Holder<>(),
- new Holder<>());
- } catch (Exception e) {
- }
- }
-
- @Test
- public void updateVnfTest() {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
-
- Map<String, Object> map = new HashMap<>();
-
- map.put("key1", "value1");
- try {
- instance.updateVnf("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD",
- "volumeGroupHeatStackId|1", map, msoRequest, new Holder<>(),
- new Holder<>());
- } catch (Exception e) {
-
- }
- }
-
- @Test
- public void deleteVnfTest() {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("12345");
- msoRequest.setServiceInstanceId("12345");
- try {
- instance.deleteVnf("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", msoRequest);
- } catch (Exception e) {
-
- }
- }
+ }
+
+ @Test
+ public void createVfModuleVnfException() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ instance.createVfModule("123", "CloudOwner", "123", "vf", "v1", "", "module-005", "", "create", "3245", "234",
+ "123", new HashMap<>(), true, true, true, msoRequest, new Holder<>(), new Holder<>(), new Holder<>());
+ }
+
+ @Test
+ public void createVfModule_ModelCustUuidIsNull() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ instance.createVfModule("123", "CloudOwner", "123", "vf", "v1", "", "module-005", "", "create", "3245", "234",
+ null, new HashMap<>(), true, true, true, msoRequest, new Holder<>(), new Holder<>(), new Holder<>());
+ }
+
+ @Test
+ public void createVfModule_CloudSiteIdNotFound() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ instance.createVfModule("123", "CloudOwner", "123", "vf", "v1", "", "module-005", "", "create", "3245", "234",
+ "9b339a61-69ca-465f-86b8-1c72c582b8e8", new HashMap<>(), true, true, true, msoRequest, new Holder<>(),
+ new Holder<>(), new Holder<>());
+ }
+
+ @Test
+ public void createVfModule_MsoCloudifyManagerNotFound() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ instance.createVfModule("mtn13", "CloudOwner", "123", "vf", "v1", "", "module-005", "", "create", "3245", "234",
+ "9b339a61-69ca-465f-86b8-1c72c582b8e8", new HashMap<>(), true, true, true, msoRequest, new Holder<>(),
+ new Holder<>(), new Holder<>());
+ }
+
+ @Test
+ public void createVfModule() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname"))
+ .willReturn(aResponse().withBody("{ \"id\": \"123\" }").withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname/outputs"))
+ .willReturn(aResponse().withBody("{ \"deployment_id\": \"123\",\"outputs\":{\"abc\":\"abc\"} }")
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching("/v2.0/api/v3/executions?.*")).willReturn(aResponse()
+ .withBody("{ \"items\": {\"id\": \"123\",\"workflow_id\":\"install\",\"status\":\"terminated\" } } ")
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/tokens"))
+ .willReturn(aResponse().withBodyFile("OpenstackResponse_Access.json").withStatus(HttpStatus.SC_OK)));
+
+ instance.createVfModule("mtn13", "CloudOwner", "123", "vf", "v1", "", "vfname", "", "create", "3245", "234",
+ "9b339a61-69ca-465f-86b8-1c72c582b8e8", new HashMap<>(), true, true, true, msoRequest, new Holder<>(),
+ new Holder<>(), new Holder<>());
+ }
+
+ @Test
+ public void updateVfModuleVnfException() throws Exception {
+ expectedException.expect(VnfException.class);
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ instance.updateVfModule("123", "CloudOwner", "1234", "fw", "v2", "vnf1", "create", "123", "12", "233", "234",
+ new HashMap<>(), msoRequest, new Holder<>(), new Holder<>());
+ }
+
+ @Test
+ public void healthCheckVNFTest() {
+ instance.healthCheck();
+ }
+
+ @Test
+ public void createVnfTest() {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("key1", "value1");
+ try {
+ instance.createVnf("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD",
+ "volumeGroupHeatStackId|1", map, Boolean.FALSE, Boolean.TRUE, Boolean.TRUE, msoRequest,
+ new Holder<>(), new Holder<>(), new Holder<>());
+ } catch (Exception e) {
+ }
+ }
+
+ @Test
+ public void updateVnfTest() {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+
+ Map<String, Object> map = new HashMap<>();
+
+ map.put("key1", "value1");
+ try {
+ instance.updateVnf("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD",
+ "volumeGroupHeatStackId|1", map, msoRequest, new Holder<>(), new Holder<>());
+ } catch (Exception e) {
+
+ }
+ }
+
+ @Test
+ public void deleteVnfTest() {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId("12345");
+ msoRequest.setServiceInstanceId("12345");
+ try {
+ instance.deleteVnf("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", msoRequest);
+ } catch (Exception e) {
+
+ }
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfMulticloudAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfMulticloudAdapterImplTest.java
index 507251bb80..9d13cc10a3 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfMulticloudAdapterImplTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfMulticloudAdapterImplTest.java
@@ -28,12 +28,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.ws.Holder;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Rule;
@@ -47,7 +44,7 @@ import org.onap.so.openstack.beans.StackInfo;
import org.onap.so.openstack.exceptions.MsoException;
import org.springframework.beans.factory.annotation.Autowired;
-public class MsoVnfMulticloudAdapterImplTest extends BaseRestTestUtils{
+public class MsoVnfMulticloudAdapterImplTest extends BaseRestTestUtils {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@@ -59,17 +56,20 @@ public class MsoVnfMulticloudAdapterImplTest extends BaseRestTestUtils{
private static final String CREATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": "
+ "\"workload-id\", \"template_response\": {\"stack\": {\"id\": \"TEST-stack\", \"links\": []}}}";
- private static final String UPDATE_STACK_RESPONSE = "{\"template_type\": \"heat\", \"workload_id\": "
- + "\"workload-id\"}";
+ private static final String UPDATE_STACK_RESPONSE =
+ "{\"template_type\": \"heat\", \"workload_id\": " + "\"workload-id\"}";
private static final String GET_CREATE_STACK_RESPONSE = "{\"template_type\": \"heat\", \"workload_id\": "
+ "\"workload-id\", \"workload_status\": \"CREATE_COMPLETE\"}";
private static final String GET_UPDATE_STACK_RESPONSE = "{\"template_type\": \"heat\", \"workload_id\": "
+ "\"workload-id\", \"workload_status\": \"UPDATE_COMPLETE\"}";
private static final String MULTICLOUD_CREATE_PATH = "/api/multicloud/v1/CloudOwner/MTN13/infra_workload";
- private static final String MULTICLOUD_UPDATE_PATH = "/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id";
- private static final String MULTICLOUD_GET_PATH_BY_NAME = "/api/multicloud/v1/CloudOwner/MTN13/infra_workload/vfname";
- private static final String MULTICLOUD_GET_PATH_BY_ID = "/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id";
+ private static final String MULTICLOUD_UPDATE_PATH =
+ "/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id";
+ private static final String MULTICLOUD_GET_PATH_BY_NAME =
+ "/api/multicloud/v1/CloudOwner/MTN13/infra_workload/vfname";
+ private static final String MULTICLOUD_GET_PATH_BY_ID =
+ "/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id";
@Before
public void before() throws Exception {
@@ -92,41 +92,31 @@ public class MsoVnfMulticloudAdapterImplTest extends BaseRestTestUtils{
msoRequest.setRequestId("12345");
msoRequest.setServiceInstanceId("12345");
- wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_NAME))
- .willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_NOT_FOUND)));
-
- wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_ID))
- .inScenario("CREATE").whenScenarioStateIs("CREATING")
- .willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBody(GET_CREATE_STACK_RESPONSE)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_ID))
- .inScenario("CREATE").whenScenarioStateIs("UPDATING")
- .willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBody(GET_UPDATE_STACK_RESPONSE)
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_NAME)).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_ID)).inScenario("CREATE")
+ .whenScenarioStateIs("CREATING").willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(GET_CREATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_ID)).inScenario("CREATE")
+ .whenScenarioStateIs("UPDATING").willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(GET_UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK)));
wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).inScenario("CREATE")
- .willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("MulticloudResponse_Stack_Create.json")
- .withStatus(HttpStatus.SC_CREATED))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("MulticloudResponse_Stack_Create.json").withStatus(HttpStatus.SC_CREATED))
.willSetStateTo("CREATING"));
- wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_UPDATE_PATH)).inScenario("CREATE")
- .willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBody(UPDATE_STACK_RESPONSE)
- .withStatus(HttpStatus.SC_ACCEPTED))
+ wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_UPDATE_PATH))
+ .inScenario("CREATE").willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_ACCEPTED))
.willSetStateTo("UPDATING"));
try {
- instance.createVfModule("MTN13", "CloudOwner", "123", "vf", "v1", "genericVnfId", "vfname", "vfModuleId", "create", null, "234", "9b339a61-69ca-465f-86b8-1c72c582b8e8", stackInputs, true, true, true, msoRequest, new Holder<>(), new Holder<>(), new Holder<>());
+ instance.createVfModule("MTN13", "CloudOwner", "123", "vf", "v1", "genericVnfId", "vfname", "vfModuleId",
+ "create", null, "234", "9b339a61-69ca-465f-86b8-1c72c582b8e8", stackInputs, true, true, true,
+ msoRequest, new Holder<>(), new Holder<>(), new Holder<>());
} catch (VnfException e) {
fail("createVfModule success expected, failed with exception: " + e.toString());
}
@@ -147,15 +137,18 @@ public class MsoVnfMulticloudAdapterImplTest extends BaseRestTestUtils{
msoRequest.setRequestId("12345");
msoRequest.setServiceInstanceId("12345");
- wireMockServer.stubFor(get(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/vfname")).willReturn(aResponse()
- //.withHeader()
- .withBodyFile("MulticloudResponse_Stack.json")
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(
+ get(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/vfname")).willReturn(aResponse()
+ // .withHeader()
+ .withBodyFile("MulticloudResponse_Stack.json").withStatus(HttpStatus.SC_OK)));
try {
- instance.createVfModule("MTN13", "CloudOwner", "123", "vf", "v1", "genericVnfId", "vfname", "vfModuleId", "create", null, "234", "9b339a61-69ca-465f-86b8-1c72c582b8e8", stackInputs, true, true, true, msoRequest, new Holder<>(), new Holder<>(), new Holder<>());
+ instance.createVfModule("MTN13", "CloudOwner", "123", "vf", "v1", "genericVnfId", "vfname", "vfModuleId",
+ "create", null, "234", "9b339a61-69ca-465f-86b8-1c72c582b8e8", stackInputs, true, true, true,
+ msoRequest, new Holder<>(), new Holder<>(), new Holder<>());
} catch (VnfException e) {
- assertTrue(e.toString().contains("Resource vfname already exists in owner/cloud/tenant CloudOwner/MTN13/123 with ID vfname/vfname"));
+ assertTrue(e.toString().contains(
+ "Resource vfname already exists in owner/cloud/tenant CloudOwner/MTN13/123 with ID vfname/vfname"));
return;
}
fail("VnfAlreadyExists Exception expected!");
@@ -167,12 +160,11 @@ public class MsoVnfMulticloudAdapterImplTest extends BaseRestTestUtils{
msoRequest.setRequestId("12345");
msoRequest.setServiceInstanceId("12345");
- wireMockServer.stubFor(get(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id")).willReturn(aResponse()
- .withBodyFile("MulticloudResponse_Stack.json")
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id"))
+ .willReturn(aResponse().withBodyFile("MulticloudResponse_Stack.json").withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(delete(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id")).willReturn(aResponse()
- .withStatus(HttpStatus.SC_NO_CONTENT)));
+ wireMockServer.stubFor(delete(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id"))
+ .willReturn(aResponse().withStatus(HttpStatus.SC_NO_CONTENT)));
instance.deleteVfModule("MTN13", "CloudOwner", "123", "workload-id", msoRequest, new Holder<>());
}
@@ -183,11 +175,11 @@ public class MsoVnfMulticloudAdapterImplTest extends BaseRestTestUtils{
msoRequest.setRequestId("12345");
msoRequest.setServiceInstanceId("12345");
- wireMockServer.stubFor(get(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id")).willReturn(aResponse()
- .withBodyFile("MulticloudResponse_Stack.json")
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id"))
+ .willReturn(aResponse().withBodyFile("MulticloudResponse_Stack.json").withStatus(HttpStatus.SC_OK)));
- instance.queryVnf("MTN13", "CloudOwner", "123", "workload-id", msoRequest, new Holder<>(), new Holder<>(), new Holder<>(), new Holder<>());
+ instance.queryVnf("MTN13", "CloudOwner", "123", "workload-id", msoRequest, new Holder<>(), new Holder<>(),
+ new Holder<>(), new Holder<>());
}
// TODO Error Tests
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImplTest.java
index 50272dca20..be565deb9e 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImplTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImplTest.java
@@ -27,12 +27,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackVfModule_200;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackVfModule_404;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccess;
-
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.ws.Holder;
-
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
@@ -58,9 +55,9 @@ public class MsoVnfPluginAdapterImplTest extends BaseRestTestUtils {
MsoRequest msoRequest = getMsoRequest();
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
- msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId|1", "baseVfHeatStackId", null, map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
+ msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "",
+ vnfName, "", "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", null, map, Boolean.FALSE,
+ Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
new Holder<VnfRollback>());
}
@@ -70,10 +67,10 @@ public class MsoVnfPluginAdapterImplTest extends BaseRestTestUtils {
MsoRequest msoRequest = getMsoRequest();
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
- msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
+ msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "",
+ vnfName, "", "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId",
+ "88a6ca3ee0394ade9403f075db23167e", map, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest,
+ new Holder<>(), new Holder<Map<String, String>>(), new Holder<VnfRollback>());
}
@Test
@@ -82,10 +79,10 @@ public class MsoVnfPluginAdapterImplTest extends BaseRestTestUtils {
MsoRequest msoRequest = getMsoRequest();
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
- msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId|1", "baseVfHeatStackId", "9b339a61-69ca-465f-86b8-1c72c582b8e8", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
+ msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "",
+ vnfName, "", "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId",
+ "9b339a61-69ca-465f-86b8-1c72c582b8e8", map, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest,
+ new Holder<>(), new Holder<Map<String, String>>(), new Holder<VnfRollback>());
}
@Test
@@ -96,10 +93,10 @@ public class MsoVnfPluginAdapterImplTest extends BaseRestTestUtils {
MsoRequest msoRequest = getMsoRequest();
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
- msoVnfPluginAdapter.createVfModule("MTN13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- null, "baseVfHeatStackId", "9b339a61-69ca-465f-86b8-1c72c582b8e8", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
+ msoVnfPluginAdapter.createVfModule("MTN13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "",
+ vnfName, "", "VFMOD", null, "baseVfHeatStackId", "9b339a61-69ca-465f-86b8-1c72c582b8e8", map,
+ Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(),
+ new Holder<Map<String, String>>(), new Holder<VnfRollback>());
}
@Test
@@ -109,10 +106,10 @@ public class MsoVnfPluginAdapterImplTest extends BaseRestTestUtils {
MsoRequest msoRequest = getMsoRequest();
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
- msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId|1", "baseVfHeatStackId", "9b339a61-69ca-465f-86b8-1c72c582b8e8", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
+ msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "",
+ vnfName, "", "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId",
+ "9b339a61-69ca-465f-86b8-1c72c582b8e8", map, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest,
+ new Holder<>(), new Holder<Map<String, String>>(), new Holder<VnfRollback>());
}
@Test
@@ -122,23 +119,22 @@ public class MsoVnfPluginAdapterImplTest extends BaseRestTestUtils {
mockOpenStackGetStackVfModule_404(wireMockServer);
wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId"))
.willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json")
- .withStatus(HttpStatus.SC_OK)));
+ .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
MsoRequest msoRequest = getMsoRequest();
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
- msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", "VFMOD",
- "volumeGroupHeatStackId", "baseVfHeatStackId", "9b339a61-69ca-465f-86b8-1c72c582b8e8", map,
- Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(),
- new Holder<VnfRollback>());
+ msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "",
+ vnfName, "", "VFMOD", "volumeGroupHeatStackId", "baseVfHeatStackId",
+ "9b339a61-69ca-465f-86b8-1c72c582b8e8", map, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest,
+ new Holder<>(), new Holder<Map<String, String>>(), new Holder<VnfRollback>());
}
@Test
public void deleteVfModule_QueryVduException() throws Exception {
expectedException.expect(VnfException.class);
MsoRequest msoRequest = getMsoRequest();
- msoVnfPluginAdapter.deleteVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", msoRequest,
- new Holder<Map<String, String>>());
+ msoVnfPluginAdapter.deleteVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12",
+ msoRequest, new Holder<Map<String, String>>());
}
@Test
@@ -148,14 +144,14 @@ public class MsoVnfPluginAdapterImplTest extends BaseRestTestUtils {
mockOpenStackGetStackVfModule_200(wireMockServer);
wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/vSAMP12"))
.willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json")
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+ .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(delete(
+ urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
MsoRequest msoRequest = getMsoRequest();
- msoVnfPluginAdapter.deleteVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", msoRequest,
- new Holder<Map<String, String>>());
+ msoVnfPluginAdapter.deleteVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12",
+ msoRequest, new Holder<Map<String, String>>());
}
private MsoRequest getMsoRequest() {
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/QueryTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/QueryTest.java
index 232f5b3afe..7e7c130e33 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/QueryTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/QueryTest.java
@@ -25,11 +25,8 @@ import static org.hamcrest.Matchers.hasProperty;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
-
import java.util.Map;
-
import javax.xml.ws.Holder;
-
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -48,64 +45,66 @@ import org.onap.so.openstack.utils.MsoHeatUtils;
@RunWith(MockitoJUnitRunner.class)
public class QueryTest {
-
- @Mock
- private MsoHeatUtils heat;
- @InjectMocks
- private MsoVnfAdapterImpl vnfAdapter = new MsoVnfAdapterImpl();
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
- @Test
- public void testQueryCreatedVnf() throws VnfException, MsoException {
- StackInfo info = new StackInfo("stackName", HeatStatus.CREATED);
- when(heat.queryStack(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(info);
- String cloudId = "MT";
- String cloudOwner = "CloudOwner";
- String tenantId = "MSO_Test";
- String vnfName = "VNF_TEST1";
- Holder<Boolean> vnfExists = new Holder<>();
- Holder<String> vnfId = new Holder<>();
- Holder<VnfStatus> status = new Holder<>();
- Holder<Map<String, String>> outputs = new Holder<>();
- vnfAdapter.queryVnf(cloudId, cloudOwner, tenantId, vnfName, null, vnfExists, vnfId, status, outputs);
+ @Mock
+ private MsoHeatUtils heat;
+ @InjectMocks
+ private MsoVnfAdapterImpl vnfAdapter = new MsoVnfAdapterImpl();
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testQueryCreatedVnf() throws VnfException, MsoException {
+ StackInfo info = new StackInfo("stackName", HeatStatus.CREATED);
+ when(heat.queryStack(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(info);
+ String cloudId = "MT";
+ String cloudOwner = "CloudOwner";
+ String tenantId = "MSO_Test";
+ String vnfName = "VNF_TEST1";
+ Holder<Boolean> vnfExists = new Holder<>();
+ Holder<String> vnfId = new Holder<>();
+ Holder<VnfStatus> status = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
+
+ vnfAdapter.queryVnf(cloudId, cloudOwner, tenantId, vnfName, null, vnfExists, vnfId, status, outputs);
- assertTrue(vnfExists.value);
- }
+ assertTrue(vnfExists.value);
+ }
- @Test
- public void testQueryNotFoundVnf() throws VnfException, MsoException {
- StackInfo info = new StackInfo("stackName", HeatStatus.NOTFOUND);
- when(heat.queryStack(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(info);
- String cloudId = "MT";
- String cloudOwner = "CloudOwner";
- String tenantId = "MSO_Test";
- String vnfName = "VNF_TEST1";
- Holder<Boolean> vnfExists = new Holder<>();
- Holder<String> vnfId = new Holder<>();
- Holder<VnfStatus> status = new Holder<>();
- Holder<Map<String, String>> outputs = new Holder<>();
+ @Test
+ public void testQueryNotFoundVnf() throws VnfException, MsoException {
+ StackInfo info = new StackInfo("stackName", HeatStatus.NOTFOUND);
+ when(heat.queryStack(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(info);
+ String cloudId = "MT";
+ String cloudOwner = "CloudOwner";
+ String tenantId = "MSO_Test";
+ String vnfName = "VNF_TEST1";
+ Holder<Boolean> vnfExists = new Holder<>();
+ Holder<String> vnfId = new Holder<>();
+ Holder<VnfStatus> status = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
- vnfAdapter.queryVnf(cloudId, cloudOwner, tenantId, vnfName, null, vnfExists, vnfId, status, outputs);
+ vnfAdapter.queryVnf(cloudId, cloudOwner, tenantId, vnfName, null, vnfExists, vnfId, status, outputs);
- assertFalse(vnfExists.value);
- }
+ assertFalse(vnfExists.value);
+ }
- @Test()
- // @Ignore // 1802 merge
- public void testQueryVnfWithException() throws VnfException, MsoException {
- String cloudId = "MT";
- String cloudOwner = "CloudOwner";
- String tenantId = "MSO_Test";
- String vnfName = "VNF_TEST1";
- Holder<Boolean> vnfExists = new Holder<>();
- Holder<String> vnfId = new Holder<>();
- Holder<VnfStatus> status = new Holder<>();
- Holder<Map<String, String>> outputs = new Holder<>();
- thrown.expect(VnfException.class);
- thrown.expectCause(hasProperty("context", is("QueryVNF")));
- when(heat.queryStack(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenThrow(new MsoOpenstackException(1, "test messsage", "test detail"));
- vnfAdapter.queryVnf(cloudId, cloudOwner, tenantId, vnfName, null, vnfExists, vnfId, status, outputs);
- }
+ @Test()
+ // @Ignore // 1802 merge
+ public void testQueryVnfWithException() throws VnfException, MsoException {
+ String cloudId = "MT";
+ String cloudOwner = "CloudOwner";
+ String tenantId = "MSO_Test";
+ String vnfName = "VNF_TEST1";
+ Holder<Boolean> vnfExists = new Holder<>();
+ Holder<String> vnfId = new Holder<>();
+ Holder<VnfStatus> status = new Holder<>();
+ Holder<Map<String, String>> outputs = new Holder<>();
+ thrown.expect(VnfException.class);
+ thrown.expectCause(hasProperty("context", is("QueryVNF")));
+ when(heat.queryStack(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
+ .thenThrow(new MsoOpenstackException(1, "test messsage", "test detail"));
+ vnfAdapter.queryVnf(cloudId, cloudOwner, tenantId, vnfName, null, vnfExists, vnfId, status, outputs);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VfRollbackTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VfRollbackTest.java
index a59de7695c..df2d798cda 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VfRollbackTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VfRollbackTest.java
@@ -1,70 +1,66 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.adapters.vnf;
-import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertEquals;
import org.junit.Test;
+
public class VfRollbackTest {
- private VfRollback vfRollback = new VfRollback();
+ private VfRollback vfRollback = new VfRollback();
+
+ @Test
+ public void test() {
+ vfRollback.setVnfId("vnfId");
+ vfRollback.setTenantId("tenantId");
+ vfRollback.setCloudSiteId("cloudId");
+ vfRollback.setTenantCreated(true);
+ vfRollback.setVnfCreated(true);
+ vfRollback.setMsoRequest(null);
+ vfRollback.setVolumeGroupName("volumeGroupName");
+ vfRollback.setVolumeGroupId("volumeGroupId");
+ vfRollback.setRequestType("requestType");
+ vfRollback.setVolumeGroupHeatStackId("volumeGroupHeatStackId");
+ vfRollback.setBaseGroupHeatStackId("baseGroupHeatStackId");
+ vfRollback.setIsBase(true);
+ vfRollback.setVfModuleStackId("vfModuleStackId");
+ assert (vfRollback.getVnfId() != null);
+ assert (vfRollback.getTenantId() != null);
+ assert (vfRollback.getCloudSiteId() != null);
+ assert (vfRollback.getVolumeGroupName() != null);
+ assert (vfRollback.getVolumeGroupId() != null);
+ assert (vfRollback.getRequestType() != null);
+ assert (vfRollback.getVolumeGroupHeatStackId() != null);
+ assert (vfRollback.getBaseGroupHeatStackId() != null);
+ assert (vfRollback.getVfModuleStackId() != null);
+ assertEquals("vnfId", vfRollback.getVnfId());
+ assertEquals("tenantId", vfRollback.getTenantId());
+ assertEquals("cloudId", vfRollback.getCloudSiteId());
+ assertEquals(true, vfRollback.getTenantCreated());
+ assertEquals(true, vfRollback.getVnfCreated());
+ assertEquals(null, vfRollback.getMsoRequest());
+ assertEquals("volumeGroupName", vfRollback.getVolumeGroupName());
+ assertEquals("volumeGroupId", vfRollback.getVolumeGroupId());
+ assertEquals("requestType", vfRollback.getRequestType());
+ assertEquals("volumeGroupHeatStackId", vfRollback.getVolumeGroupHeatStackId());
+ assertEquals("baseGroupHeatStackId", vfRollback.getBaseGroupHeatStackId());
+ assertEquals(true, vfRollback.isBase());
+ assertEquals("vfModuleStackId", vfRollback.getVfModuleStackId());
+ }
- @Test
- public void test() {
- vfRollback.setVnfId("vnfId");
- vfRollback.setTenantId("tenantId");
- vfRollback.setCloudSiteId("cloudId");
- vfRollback.setTenantCreated(true);
- vfRollback.setVnfCreated(true);
- vfRollback.setMsoRequest(null);
- vfRollback.setVolumeGroupName("volumeGroupName");
- vfRollback.setVolumeGroupId("volumeGroupId");
- vfRollback.setRequestType("requestType");
- vfRollback.setVolumeGroupHeatStackId("volumeGroupHeatStackId");
- vfRollback.setBaseGroupHeatStackId("baseGroupHeatStackId");
- vfRollback.setIsBase(true);
- vfRollback.setVfModuleStackId("vfModuleStackId");
- assert(vfRollback.getVnfId() != null);
- assert(vfRollback.getTenantId() != null);
- assert(vfRollback.getCloudSiteId() != null);
- assert(vfRollback.getVolumeGroupName() != null);
- assert(vfRollback.getVolumeGroupId() != null);
- assert(vfRollback.getRequestType() != null);
- assert(vfRollback.getVolumeGroupHeatStackId() != null);
- assert(vfRollback.getBaseGroupHeatStackId() != null);
- assert(vfRollback.getVfModuleStackId() != null);
- assertEquals("vnfId", vfRollback.getVnfId());
- assertEquals("tenantId", vfRollback.getTenantId());
- assertEquals("cloudId", vfRollback.getCloudSiteId());
- assertEquals(true, vfRollback.getTenantCreated());
- assertEquals(true, vfRollback.getVnfCreated());
- assertEquals(null, vfRollback.getMsoRequest());
- assertEquals("volumeGroupName", vfRollback.getVolumeGroupName());
- assertEquals("volumeGroupId", vfRollback.getVolumeGroupId());
- assertEquals("requestType", vfRollback.getRequestType());
- assertEquals("volumeGroupHeatStackId", vfRollback.getVolumeGroupHeatStackId());
- assertEquals("baseGroupHeatStackId", vfRollback.getBaseGroupHeatStackId());
- assertEquals(true, vfRollback.isBase());
- assertEquals("vfModuleStackId", vfRollback.getVfModuleStackId());
- }
-
- @Test
- public void testtoString() {
- assert(vfRollback.toString() != null);
- }
+ @Test
+ public void testtoString() {
+ assert (vfRollback.toString() != null);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VnfAdapterRestTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VnfAdapterRestTest.java
index bf00faa41b..89adafd280 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VnfAdapterRestTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VnfAdapterRestTest.java
@@ -42,7 +42,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
@@ -50,7 +49,6 @@ import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
-
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
@@ -73,480 +71,477 @@ import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPutStacks_200;
import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccess;
public class VnfAdapterRestTest extends BaseRestTestUtils {
-
-
- @Autowired
- private JettisonStyleMapperProvider jettisonTypeObjectMapper;
- private static final String MESSAGE_ID = "62265093-277d-4388-9ba6-449838ade586-1517252396874";
- private static final String AAI_VNF_ID = "c93e0d34-5b63-45de-bbae-b0fe49dd3bd9";
- private static final String MSO_REQUEST_ID = "62265093-277d-4388-9ba6-449838ade586";
- private static final String MSO_SERVICE_INSTANCE_ID = "4147e06f-1b89-49c5-b21f-4faf8dc9805a";
- private static final String CLOUDSITE_ID = "mtn13";
- private static final String CLOUD_OWNER = "CloudOwner";
- private static final String TENANT_ID = "0422ffb57ba042c0800a29dc85ca70f8";
- private static final String VNF_TYPE = "MSOTADevInfra_vSAMP10a_Service/vSAMP10a 1";
- private static final String VNF_NAME = "MSO-DEV-VNF-1802-it3-pwt3-vSAMP10a-1XXX-Replace";
- private static final String VNF_VERSION = "1.0";
- private static final String VF_MODULE_ID = "1d48aaec-b7f3-4c24-ba4a-4e798ed3223c";
- private static final String VF_MODULE_NAME = "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001";
- private static final String VF_MODULE_TYPE = "vSAMP10aDEV::PCM::module-2";
- private static final String MODEL_CUSTOMIZATION_UUID = "cb82ffd8-252a-11e7-93ae-92361f002671";
- private static final String BASE_VF_MODULE_ID = "3d7ff7b4-720b-4604-be0a-1974fc58ed96";
- // vfModuleParams specific variables
- private static final String NETWORK_NAME = "Dev-vSAMP10a-ntwk-1802-pwt3-v6-Replace-1001";
- private static final String SERVER_NAME = "Dev-vSAMP10a-addon2-1802-pwt3-v6-Replace-1001";
- private static final String IMAGE = "ubuntu_14.04_IPv6";
- private static final String EXN_DIRECT_NET_FQDN = "direct";
- private static final String EXN_HSL_NET_FQDN = "hsl";
- private static final String AVAILABILITY_ZONE_0 = "nova";
- private static final String VF_MODULE_INDEX = "0";
- private static final String REQUEST_TYPE = "";
-
- @Test
- public void testCreateVfModule() throws JSONException, JsonParseException, JsonMappingException, IOException {
-
- CreateVfModuleRequest request = populateCreateVfModuleRequest();
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackGetStackVfModule_404(wireMockServer);
-
- mockOpenStackPostStacks_200(wireMockServer);
-
- mockOpenStackGetStackVfModule_200(wireMockServer);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<CreateVfModuleRequest> entity = new HttpEntity<CreateVfModuleRequest>(request, headers);
-
- ResponseEntity<CreateVfModuleResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), HttpMethod.POST,
- entity, CreateVfModuleResponse.class);
-
- ResponseEntity<CreateVfModuleResponse> responseV2 = restTemplate.exchange(
- createURLWithPort("/services/rest/v2/vnfs/" + AAI_VNF_ID + "/vf-modules"), HttpMethod.POST,
- entity, CreateVfModuleResponse.class);
-
- CreateVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/CreateVfModuleResponse.json"), CreateVfModuleResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
-
- assertEquals(Response.Status.OK.getStatusCode(), responseV2.getStatusCode().value());
- assertThat(responseV2.getBody(), sameBeanAs(expectedResponse));
- }
-
- @Test
- public void testCreateVfModuleAsyncCall() throws Exception {
- CreateVfModuleRequest request = populateCreateVfModuleRequest();
- request.setNotificationUrl( createURLWithPort("/mso/WorkflowMesssage"));
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
- mockOpenStackGetStackVfModule_404(wireMockServer);
- mockOpenStackPostStacks_200(wireMockServer);
- mockOpenStackGetStackVfModule_200(wireMockServer);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<CreateVfModuleRequest> entity = new HttpEntity<CreateVfModuleRequest>(request, headers);
-
- ResponseEntity<CreateVfModuleResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), HttpMethod.POST,
- entity, CreateVfModuleResponse.class);
-
- CreateVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/CreateVfModuleResponse.json"), CreateVfModuleResponse.class);
-
- assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
- }
-
- @Test
- public void testCreateVfModuleWithEnableBridgeNull()
- throws JSONException, JsonParseException, JsonMappingException, IOException {
-
- CreateVfModuleRequest request = new CreateVfModuleRequest();
- request.setBackout(true);
- request.setSkipAAI(true);
- request.setFailIfExists(false);
- MsoRequest msoReq = new MsoRequest();
- boolean failIfExists = true;
- Boolean enableBridge = null;
- Map<String, Object> vfModuleParams = new HashMap<>();
-
-
- vfModuleParams.put("vf_module_id", VF_MODULE_ID);
- vfModuleParams.put("vnf_id", AAI_VNF_ID);
- vfModuleParams.put("network_name", NETWORK_NAME);
- vfModuleParams.put("vnf_name", VNF_NAME);
- vfModuleParams.put("environment_context", "");
- vfModuleParams.put("server_name", SERVER_NAME);
- vfModuleParams.put("image", IMAGE);
- vfModuleParams.put("workload_context", "");
- vfModuleParams.put("vf_module_index", VF_MODULE_INDEX);
- vfModuleParams.put("vf_module_name", VF_MODULE_NAME);
- vfModuleParams.put("availability_zone_0", AVAILABILITY_ZONE_0);
- vfModuleParams.put("exn_direct_net_fqdn", EXN_DIRECT_NET_FQDN);
- vfModuleParams.put("exn_hsl_net_fqdn", EXN_HSL_NET_FQDN);
-
- msoReq.setRequestId(MSO_REQUEST_ID);
- msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
- request.setMsoRequest(msoReq);
- request.setRequestType(REQUEST_TYPE);
- request.setCloudSiteId(CLOUDSITE_ID);
- request.setTenantId(TENANT_ID);
- request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
- request.setVnfId(AAI_VNF_ID);
- request.setVnfVersion(VNF_VERSION);
- request.setVfModuleId(VF_MODULE_ID);
- request.setVfModuleName(VF_MODULE_NAME);
- request.setBaseVfModuleId(BASE_VF_MODULE_ID);
- request.setFailIfExists(failIfExists);
- request.setEnableBridge(enableBridge);
- request.setVfModuleParams(vfModuleParams);
- request.setMessageId(MESSAGE_ID);
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackGetStackVfModule_404(wireMockServer);
-
- mockOpenStackPostStacks_200(wireMockServer);
-
- mockOpenStackGetStackVfModule_200(wireMockServer);
-
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<CreateVfModuleRequest> entity = new HttpEntity<CreateVfModuleRequest>(request, headers);
-
- ResponseEntity<CreateVfModuleResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), HttpMethod.POST,
- entity, CreateVfModuleResponse.class);
-
- CreateVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/CreateVfModuleResponse.json"), CreateVfModuleResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- }
-
- @Test
- public void testCreateVfModuleFail() throws IOException{
-
- CreateVfModuleRequest request = new CreateVfModuleRequest();
- request.setBackout(true);
- request.setSkipAAI(true);
- request.setFailIfExists(false);
- MsoRequest msoReq = new MsoRequest();
- boolean failIfExists = true;
- boolean enableBridge = false;
- Map<String, Object> vfModuleParams = new HashMap<>();
-
- vfModuleParams.put("vf_module_id", VF_MODULE_ID);
- vfModuleParams.put("vnf_id", AAI_VNF_ID);
- vfModuleParams.put("network_name", NETWORK_NAME);
- vfModuleParams.put("vnf_name", VNF_NAME);
- vfModuleParams.put("environment_context", "");
- vfModuleParams.put("server_name", SERVER_NAME);
- vfModuleParams.put("image", IMAGE);
- vfModuleParams.put("workload_context", "");
- vfModuleParams.put("vf_module_index", VF_MODULE_INDEX);
- vfModuleParams.put("vf_module_name", VF_MODULE_NAME);
- vfModuleParams.put("availability_zone_0", AVAILABILITY_ZONE_0);
- vfModuleParams.put("exn_direct_net_fqdn", EXN_DIRECT_NET_FQDN);
- vfModuleParams.put("exn_hsl_net_fqdn", EXN_HSL_NET_FQDN);
-
- msoReq.setRequestId(MSO_REQUEST_ID);
- msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
- request.setMsoRequest(msoReq);
- request.setRequestType(REQUEST_TYPE);
- request.setCloudSiteId(CLOUDSITE_ID);
- request.setTenantId(TENANT_ID);
- request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
- request.setVnfId(AAI_VNF_ID);
- request.setVnfType(VNF_TYPE);
- request.setVnfVersion(VNF_VERSION);
- request.setVfModuleId(VF_MODULE_ID);
- request.setVfModuleName(VF_MODULE_NAME);
- request.setVfModuleType(VF_MODULE_TYPE);
- request.setBaseVfModuleStackId(BASE_VF_MODULE_ID);
- request.setFailIfExists(failIfExists);
- request.setEnableBridge(enableBridge);
- request.setVfModuleParams(vfModuleParams);
- request.setMessageId(MESSAGE_ID);
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackGetStackVfModule_404(wireMockServer);
-
- mockOpenStackGetStacks_404(wireMockServer);
-
- mockOpenStackPostStacks_200(wireMockServer);
-
- mockOpenStackGetStackVfModule_200(wireMockServer);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<CreateVfModuleRequest> entity = new HttpEntity<CreateVfModuleRequest>(request, headers);
-
- ResponseEntity<VfModuleExceptionResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), HttpMethod.POST,
- entity, VfModuleExceptionResponse.class);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
-
- mockOpenStackGetStacksWithBody_200(wireMockServer, "DELETE_IN_PROGRESS");
-
- response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), HttpMethod.POST,
- entity, VfModuleExceptionResponse.class);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
-
- mockOpenStackGetStacksWithBody_200(wireMockServer, "DELETE_FAILED");
-
- response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), HttpMethod.POST,
- entity, VfModuleExceptionResponse.class);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
-
- mockOpenStackGetStacksWithBody_200(wireMockServer, "UPDATE_COMPLETE");
-
- response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), HttpMethod.POST,
- entity, VfModuleExceptionResponse.class);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
-
- mockOpenStackGetStacksWithBody_404(wireMockServer);
-
- response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), HttpMethod.POST,
- entity, VfModuleExceptionResponse.class);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
-
- }
-
- @Test
- public void testDeleteVfModule() throws IOException{
-
- DeleteVfModuleRequest request = new DeleteVfModuleRequest();
- MsoRequest msoRequest = new MsoRequest();
- String vfModuleStackId = "stackId";
-
- msoRequest.setRequestId(MSO_REQUEST_ID);
- msoRequest.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
- request.setCloudSiteId(CLOUDSITE_ID);
- request.setTenantId(TENANT_ID);
- request.setVfModuleId(VF_MODULE_ID);
- request.setVfModuleStackId(vfModuleStackId);
- request.setVnfId(AAI_VNF_ID);
- request.setMsoRequest(msoRequest);
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackPostStacks_200(wireMockServer);
-
- mockOpenStackGetStacksStackId_404(wireMockServer);
-
- mockOpenStackGetPublicUrlStackByNameAndID_200(wireMockServer, wireMockPort);
-
- mockOpenStackDeletePublicUrlStackByNameAndID_204(wireMockServer);
-
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<DeleteVfModuleRequest> entity = new HttpEntity<DeleteVfModuleRequest>(request, headers);
-
- ResponseEntity<DeleteVfModuleResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID), HttpMethod.DELETE,
- entity, DeleteVfModuleResponse.class);
-
- ResponseEntity<DeleteVfModuleResponse> responseV2 = restTemplate.exchange(
- createURLWithPort("/services/rest/v2/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID), HttpMethod.DELETE,
- entity, DeleteVfModuleResponse.class);
-
-
- DeleteVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/DeleteVfModuleResponse.json"), DeleteVfModuleResponse.class);
-
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
-
- assertEquals(Response.Status.OK.getStatusCode(), responseV2.getStatusCode().value());
- assertThat(responseV2.getBody(), sameBeanAs(expectedResponse));
- }
-
- @Test
- public void testUpdateVfModule() throws IOException{
-
- UpdateVfModuleRequest request = new UpdateVfModuleRequest();
- MsoRequest msoRequest = new MsoRequest();
- String vfModuleStackId = "vfModuleStackId";
- Boolean failIfExists = false;
- Boolean backout = false;
- msoRequest.setRequestId(MSO_REQUEST_ID);
- msoRequest.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
-
- Map<String, Object> vfModuleParams = new HashMap<>();
-
- vfModuleParams.put("exn_direct_net_fqdn", EXN_DIRECT_NET_FQDN);
- vfModuleParams.put("exn_hsl_net_fqdn", EXN_HSL_NET_FQDN);
-
- Map<String, String> vfModuleOutputs = new HashMap<String, String>();
-
- vfModuleOutputs.put("output name", "output value");
-
- request.setBackout(backout);
- request.setCloudSiteId(CLOUDSITE_ID);
- request.setFailIfExists(failIfExists);
- request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
- request.setMsoRequest(msoRequest);
- request.setRequestType(REQUEST_TYPE);
- request.setTenantId(TENANT_ID);
- request.setVfModuleId(VF_MODULE_ID);
- request.setVfModuleName(VF_MODULE_NAME);
- request.setVfModuleStackId(vfModuleStackId);
- request.setBackout(backout);
- request.setVfModuleParams(vfModuleParams);
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackGetStacksVfModuleWithLocationHeader_200(wireMockServer, wireMockPort);
-
- mockOpenStackGetStacksVfModule_200(wireMockServer, wireMockPort);
-
- mockOpenStackGetStacksBaseStack_200(wireMockServer, wireMockPort);
-
- mockOpenStackPutStacks_200(wireMockServer);
-
- UpdateVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/UpdateVfModuleResponse.json"), UpdateVfModuleResponse.class);
- expectedResponse.setVfModuleOutputs(vfModuleOutputs);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<UpdateVfModuleRequest> entity = new HttpEntity<UpdateVfModuleRequest>(request, headers);
-
- ResponseEntity<UpdateVfModuleResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_TYPE), HttpMethod.PUT,
- entity, UpdateVfModuleResponse.class);
-
- ResponseEntity<UpdateVfModuleResponse> responseV2 = restTemplate.exchange(
- createURLWithPort("/services/rest/v2/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_TYPE), HttpMethod.PUT,
- entity, UpdateVfModuleResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
-
- assertEquals(Response.Status.OK.getStatusCode(), responseV2.getStatusCode().value());
- assertThat(responseV2.getBody(), sameBeanAs(expectedResponse));
-
- }
-
- @Test
- public void testRollbackVfModule() throws IOException {
-
-
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId(MSO_REQUEST_ID);
- msoRequest.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
-
- VfModuleRollback vfModuleRollback = new VfModuleRollback(AAI_VNF_ID, VF_MODULE_ID,
- "StackId", false, TENANT_ID, CLOUD_OWNER, CLOUDSITE_ID, msoRequest, "messageId");
-
- RollbackVfModuleRequest request = new RollbackVfModuleRequest();
- request.setVfModuleRollback(vfModuleRollback);
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
- mockOpenStackGetStacksStackId_200(wireMockServer, wireMockPort);
-
- mockOpenStackDeleteStacks(wireMockServer);
-
- mockOpenStackGetStacksVUSP_404(wireMockServer);
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- HttpEntity<RollbackVfModuleRequest> entity = new HttpEntity<RollbackVfModuleRequest>(request, headers);
-
- ResponseEntity<RollbackVfModuleResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID + "/rollback"), HttpMethod.DELETE,
- entity, RollbackVfModuleResponse.class);
-
- RollbackVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/RollbackVfModuleResponse.json"),RollbackVfModuleResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
-
- }
-
- @Ignore
- @Test
- public void testQueryVfModule() throws IOException{
-
- String testUrl = createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID);
- String testUri = UriBuilder.fromPath("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID )
- .host("localhost").port(wireMockPort).scheme("http")
- //.queryParam("cloudSiteId", CLOUDSITE_ID).queryParam("tenantId", TENANT_ID)
- .build().toString();
- System.out.println(testUri);
-
- mockOpenStackResponseAccess(wireMockServer, wireMockPort);
-
-
- headers.add("Accept", MediaType.APPLICATION_JSON);
- //HttpEntity entity = new HttpEntity(null, headers);
- ResponseEntity<QueryVfModuleResponse> response = restTemplate.getForEntity(testUri, QueryVfModuleResponse.class);
- //System.out.println(response);
-
- QueryVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
- new File("src/test/resources/__files/QueryVfModuleResponse.json"),QueryVfModuleResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(), sameBeanAs(expectedResponse));
- }
-
- private CreateVfModuleRequest populateCreateVfModuleRequest(){
- CreateVfModuleRequest request = new CreateVfModuleRequest();
- request.setBackout(true);
- request.setSkipAAI(true);
- request.setFailIfExists(false);
- MsoRequest msoReq = new MsoRequest();
- boolean failIfExists = true;
- boolean enableBridge = false;
- Map<String, Object> vfModuleParams = new HashMap<>();
-
- vfModuleParams.put("vf_module_id", VF_MODULE_ID);
- vfModuleParams.put("vnf_id", AAI_VNF_ID);
- vfModuleParams.put("network_name", NETWORK_NAME);
- vfModuleParams.put("vnf_name", VNF_NAME);
- vfModuleParams.put("environment_context", "");
- vfModuleParams.put("server_name", SERVER_NAME);
- vfModuleParams.put("image", IMAGE);
- vfModuleParams.put("workload_context", "");
- vfModuleParams.put("vf_module_index", VF_MODULE_INDEX);
- vfModuleParams.put("vf_module_name", VF_MODULE_NAME);
- vfModuleParams.put("availability_zone_0", AVAILABILITY_ZONE_0);
- vfModuleParams.put("exn_direct_net_fqdn", EXN_DIRECT_NET_FQDN);
- vfModuleParams.put("exn_hsl_net_fqdn", EXN_HSL_NET_FQDN);
-
- msoReq.setRequestId(MSO_REQUEST_ID);
- msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
- request.setMsoRequest(msoReq);
- request.setRequestType(REQUEST_TYPE);
- request.setCloudSiteId(CLOUDSITE_ID);
- request.setTenantId(TENANT_ID);
- request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
- request.setVnfId(AAI_VNF_ID);
- request.setVnfType(VNF_TYPE);
- request.setVnfVersion(VNF_VERSION);
- request.setVfModuleId(VF_MODULE_ID);
- request.setVfModuleName(VF_MODULE_NAME);
- request.setVfModuleType(VF_MODULE_TYPE);
- request.setBaseVfModuleId(BASE_VF_MODULE_ID);
- request.setFailIfExists(failIfExists);
- request.setEnableBridge(enableBridge);
- request.setVfModuleParams(vfModuleParams);
- request.setMessageId(MESSAGE_ID);
-
- return request;
- }
+
+
+ @Autowired
+ private JettisonStyleMapperProvider jettisonTypeObjectMapper;
+ private static final String MESSAGE_ID = "62265093-277d-4388-9ba6-449838ade586-1517252396874";
+ private static final String AAI_VNF_ID = "c93e0d34-5b63-45de-bbae-b0fe49dd3bd9";
+ private static final String MSO_REQUEST_ID = "62265093-277d-4388-9ba6-449838ade586";
+ private static final String MSO_SERVICE_INSTANCE_ID = "4147e06f-1b89-49c5-b21f-4faf8dc9805a";
+ private static final String CLOUDSITE_ID = "mtn13";
+ private static final String CLOUD_OWNER = "CloudOwner";
+ private static final String TENANT_ID = "0422ffb57ba042c0800a29dc85ca70f8";
+ private static final String VNF_TYPE = "MSOTADevInfra_vSAMP10a_Service/vSAMP10a 1";
+ private static final String VNF_NAME = "MSO-DEV-VNF-1802-it3-pwt3-vSAMP10a-1XXX-Replace";
+ private static final String VNF_VERSION = "1.0";
+ private static final String VF_MODULE_ID = "1d48aaec-b7f3-4c24-ba4a-4e798ed3223c";
+ private static final String VF_MODULE_NAME = "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001";
+ private static final String VF_MODULE_TYPE = "vSAMP10aDEV::PCM::module-2";
+ private static final String MODEL_CUSTOMIZATION_UUID = "cb82ffd8-252a-11e7-93ae-92361f002671";
+ private static final String BASE_VF_MODULE_ID = "3d7ff7b4-720b-4604-be0a-1974fc58ed96";
+ // vfModuleParams specific variables
+ private static final String NETWORK_NAME = "Dev-vSAMP10a-ntwk-1802-pwt3-v6-Replace-1001";
+ private static final String SERVER_NAME = "Dev-vSAMP10a-addon2-1802-pwt3-v6-Replace-1001";
+ private static final String IMAGE = "ubuntu_14.04_IPv6";
+ private static final String EXN_DIRECT_NET_FQDN = "direct";
+ private static final String EXN_HSL_NET_FQDN = "hsl";
+ private static final String AVAILABILITY_ZONE_0 = "nova";
+ private static final String VF_MODULE_INDEX = "0";
+ private static final String REQUEST_TYPE = "";
+
+ @Test
+ public void testCreateVfModule() throws JSONException, JsonParseException, JsonMappingException, IOException {
+
+ CreateVfModuleRequest request = populateCreateVfModuleRequest();
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackGetStackVfModule_404(wireMockServer);
+
+ mockOpenStackPostStacks_200(wireMockServer);
+
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<CreateVfModuleRequest> entity = new HttpEntity<CreateVfModuleRequest>(request, headers);
+
+ ResponseEntity<CreateVfModuleResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"),
+ HttpMethod.POST, entity, CreateVfModuleResponse.class);
+
+ ResponseEntity<CreateVfModuleResponse> responseV2 =
+ restTemplate.exchange(createURLWithPort("/services/rest/v2/vnfs/" + AAI_VNF_ID + "/vf-modules"),
+ HttpMethod.POST, entity, CreateVfModuleResponse.class);
+
+ CreateVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/CreateVfModuleResponse.json"), CreateVfModuleResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+
+ assertEquals(Response.Status.OK.getStatusCode(), responseV2.getStatusCode().value());
+ assertThat(responseV2.getBody(), sameBeanAs(expectedResponse));
+ }
+
+ @Test
+ public void testCreateVfModuleAsyncCall() throws Exception {
+ CreateVfModuleRequest request = populateCreateVfModuleRequest();
+ request.setNotificationUrl(createURLWithPort("/mso/WorkflowMesssage"));
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+ mockOpenStackGetStackVfModule_404(wireMockServer);
+ mockOpenStackPostStacks_200(wireMockServer);
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<CreateVfModuleRequest> entity = new HttpEntity<CreateVfModuleRequest>(request, headers);
+
+ ResponseEntity<CreateVfModuleResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"),
+ HttpMethod.POST, entity, CreateVfModuleResponse.class);
+
+ CreateVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/CreateVfModuleResponse.json"), CreateVfModuleResponse.class);
+
+ assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
+ }
+
+ @Test
+ public void testCreateVfModuleWithEnableBridgeNull()
+ throws JSONException, JsonParseException, JsonMappingException, IOException {
+
+ CreateVfModuleRequest request = new CreateVfModuleRequest();
+ request.setBackout(true);
+ request.setSkipAAI(true);
+ request.setFailIfExists(false);
+ MsoRequest msoReq = new MsoRequest();
+ boolean failIfExists = true;
+ Boolean enableBridge = null;
+ Map<String, Object> vfModuleParams = new HashMap<>();
+
+
+ vfModuleParams.put("vf_module_id", VF_MODULE_ID);
+ vfModuleParams.put("vnf_id", AAI_VNF_ID);
+ vfModuleParams.put("network_name", NETWORK_NAME);
+ vfModuleParams.put("vnf_name", VNF_NAME);
+ vfModuleParams.put("environment_context", "");
+ vfModuleParams.put("server_name", SERVER_NAME);
+ vfModuleParams.put("image", IMAGE);
+ vfModuleParams.put("workload_context", "");
+ vfModuleParams.put("vf_module_index", VF_MODULE_INDEX);
+ vfModuleParams.put("vf_module_name", VF_MODULE_NAME);
+ vfModuleParams.put("availability_zone_0", AVAILABILITY_ZONE_0);
+ vfModuleParams.put("exn_direct_net_fqdn", EXN_DIRECT_NET_FQDN);
+ vfModuleParams.put("exn_hsl_net_fqdn", EXN_HSL_NET_FQDN);
+
+ msoReq.setRequestId(MSO_REQUEST_ID);
+ msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
+ request.setMsoRequest(msoReq);
+ request.setRequestType(REQUEST_TYPE);
+ request.setCloudSiteId(CLOUDSITE_ID);
+ request.setTenantId(TENANT_ID);
+ request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
+ request.setVnfId(AAI_VNF_ID);
+ request.setVnfVersion(VNF_VERSION);
+ request.setVfModuleId(VF_MODULE_ID);
+ request.setVfModuleName(VF_MODULE_NAME);
+ request.setBaseVfModuleId(BASE_VF_MODULE_ID);
+ request.setFailIfExists(failIfExists);
+ request.setEnableBridge(enableBridge);
+ request.setVfModuleParams(vfModuleParams);
+ request.setMessageId(MESSAGE_ID);
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackGetStackVfModule_404(wireMockServer);
+
+ mockOpenStackPostStacks_200(wireMockServer);
+
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<CreateVfModuleRequest> entity = new HttpEntity<CreateVfModuleRequest>(request, headers);
+
+ ResponseEntity<CreateVfModuleResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"),
+ HttpMethod.POST, entity, CreateVfModuleResponse.class);
+
+ CreateVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/CreateVfModuleResponse.json"), CreateVfModuleResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ }
+
+ @Test
+ public void testCreateVfModuleFail() throws IOException {
+
+ CreateVfModuleRequest request = new CreateVfModuleRequest();
+ request.setBackout(true);
+ request.setSkipAAI(true);
+ request.setFailIfExists(false);
+ MsoRequest msoReq = new MsoRequest();
+ boolean failIfExists = true;
+ boolean enableBridge = false;
+ Map<String, Object> vfModuleParams = new HashMap<>();
+
+ vfModuleParams.put("vf_module_id", VF_MODULE_ID);
+ vfModuleParams.put("vnf_id", AAI_VNF_ID);
+ vfModuleParams.put("network_name", NETWORK_NAME);
+ vfModuleParams.put("vnf_name", VNF_NAME);
+ vfModuleParams.put("environment_context", "");
+ vfModuleParams.put("server_name", SERVER_NAME);
+ vfModuleParams.put("image", IMAGE);
+ vfModuleParams.put("workload_context", "");
+ vfModuleParams.put("vf_module_index", VF_MODULE_INDEX);
+ vfModuleParams.put("vf_module_name", VF_MODULE_NAME);
+ vfModuleParams.put("availability_zone_0", AVAILABILITY_ZONE_0);
+ vfModuleParams.put("exn_direct_net_fqdn", EXN_DIRECT_NET_FQDN);
+ vfModuleParams.put("exn_hsl_net_fqdn", EXN_HSL_NET_FQDN);
+
+ msoReq.setRequestId(MSO_REQUEST_ID);
+ msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
+ request.setMsoRequest(msoReq);
+ request.setRequestType(REQUEST_TYPE);
+ request.setCloudSiteId(CLOUDSITE_ID);
+ request.setTenantId(TENANT_ID);
+ request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
+ request.setVnfId(AAI_VNF_ID);
+ request.setVnfType(VNF_TYPE);
+ request.setVnfVersion(VNF_VERSION);
+ request.setVfModuleId(VF_MODULE_ID);
+ request.setVfModuleName(VF_MODULE_NAME);
+ request.setVfModuleType(VF_MODULE_TYPE);
+ request.setBaseVfModuleStackId(BASE_VF_MODULE_ID);
+ request.setFailIfExists(failIfExists);
+ request.setEnableBridge(enableBridge);
+ request.setVfModuleParams(vfModuleParams);
+ request.setMessageId(MESSAGE_ID);
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackGetStackVfModule_404(wireMockServer);
+
+ mockOpenStackGetStacks_404(wireMockServer);
+
+ mockOpenStackPostStacks_200(wireMockServer);
+
+ mockOpenStackGetStackVfModule_200(wireMockServer);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<CreateVfModuleRequest> entity = new HttpEntity<CreateVfModuleRequest>(request, headers);
+
+ ResponseEntity<VfModuleExceptionResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"),
+ HttpMethod.POST, entity, VfModuleExceptionResponse.class);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+
+ mockOpenStackGetStacksWithBody_200(wireMockServer, "DELETE_IN_PROGRESS");
+
+ response = restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"),
+ HttpMethod.POST, entity, VfModuleExceptionResponse.class);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+
+ mockOpenStackGetStacksWithBody_200(wireMockServer, "DELETE_FAILED");
+
+ response = restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"),
+ HttpMethod.POST, entity, VfModuleExceptionResponse.class);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+
+ mockOpenStackGetStacksWithBody_200(wireMockServer, "UPDATE_COMPLETE");
+
+ response = restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"),
+ HttpMethod.POST, entity, VfModuleExceptionResponse.class);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+
+ mockOpenStackGetStacksWithBody_404(wireMockServer);
+
+ response = restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"),
+ HttpMethod.POST, entity, VfModuleExceptionResponse.class);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+
+ }
+
+ @Test
+ public void testDeleteVfModule() throws IOException {
+
+ DeleteVfModuleRequest request = new DeleteVfModuleRequest();
+ MsoRequest msoRequest = new MsoRequest();
+ String vfModuleStackId = "stackId";
+
+ msoRequest.setRequestId(MSO_REQUEST_ID);
+ msoRequest.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
+ request.setCloudSiteId(CLOUDSITE_ID);
+ request.setTenantId(TENANT_ID);
+ request.setVfModuleId(VF_MODULE_ID);
+ request.setVfModuleStackId(vfModuleStackId);
+ request.setVnfId(AAI_VNF_ID);
+ request.setMsoRequest(msoRequest);
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackPostStacks_200(wireMockServer);
+
+ mockOpenStackGetStacksStackId_404(wireMockServer);
+
+ mockOpenStackGetPublicUrlStackByNameAndID_200(wireMockServer, wireMockPort);
+
+ mockOpenStackDeletePublicUrlStackByNameAndID_204(wireMockServer);
+
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<DeleteVfModuleRequest> entity = new HttpEntity<DeleteVfModuleRequest>(request, headers);
+
+ ResponseEntity<DeleteVfModuleResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID),
+ HttpMethod.DELETE, entity, DeleteVfModuleResponse.class);
+
+ ResponseEntity<DeleteVfModuleResponse> responseV2 = restTemplate.exchange(
+ createURLWithPort("/services/rest/v2/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID),
+ HttpMethod.DELETE, entity, DeleteVfModuleResponse.class);
+
+
+ DeleteVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/DeleteVfModuleResponse.json"), DeleteVfModuleResponse.class);
+
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+
+ assertEquals(Response.Status.OK.getStatusCode(), responseV2.getStatusCode().value());
+ assertThat(responseV2.getBody(), sameBeanAs(expectedResponse));
+ }
+
+ @Test
+ public void testUpdateVfModule() throws IOException {
+
+ UpdateVfModuleRequest request = new UpdateVfModuleRequest();
+ MsoRequest msoRequest = new MsoRequest();
+ String vfModuleStackId = "vfModuleStackId";
+ Boolean failIfExists = false;
+ Boolean backout = false;
+ msoRequest.setRequestId(MSO_REQUEST_ID);
+ msoRequest.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
+
+ Map<String, Object> vfModuleParams = new HashMap<>();
+
+ vfModuleParams.put("exn_direct_net_fqdn", EXN_DIRECT_NET_FQDN);
+ vfModuleParams.put("exn_hsl_net_fqdn", EXN_HSL_NET_FQDN);
+
+ Map<String, String> vfModuleOutputs = new HashMap<String, String>();
+
+ vfModuleOutputs.put("output name", "output value");
+
+ request.setBackout(backout);
+ request.setCloudSiteId(CLOUDSITE_ID);
+ request.setFailIfExists(failIfExists);
+ request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
+ request.setMsoRequest(msoRequest);
+ request.setRequestType(REQUEST_TYPE);
+ request.setTenantId(TENANT_ID);
+ request.setVfModuleId(VF_MODULE_ID);
+ request.setVfModuleName(VF_MODULE_NAME);
+ request.setVfModuleStackId(vfModuleStackId);
+ request.setBackout(backout);
+ request.setVfModuleParams(vfModuleParams);
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackGetStacksVfModuleWithLocationHeader_200(wireMockServer, wireMockPort);
+
+ mockOpenStackGetStacksVfModule_200(wireMockServer, wireMockPort);
+
+ mockOpenStackGetStacksBaseStack_200(wireMockServer, wireMockPort);
+
+ mockOpenStackPutStacks_200(wireMockServer);
+
+ UpdateVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/UpdateVfModuleResponse.json"), UpdateVfModuleResponse.class);
+ expectedResponse.setVfModuleOutputs(vfModuleOutputs);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<UpdateVfModuleRequest> entity = new HttpEntity<UpdateVfModuleRequest>(request, headers);
+
+ ResponseEntity<UpdateVfModuleResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_TYPE),
+ HttpMethod.PUT, entity, UpdateVfModuleResponse.class);
+
+ ResponseEntity<UpdateVfModuleResponse> responseV2 = restTemplate.exchange(
+ createURLWithPort("/services/rest/v2/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_TYPE),
+ HttpMethod.PUT, entity, UpdateVfModuleResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+
+ assertEquals(Response.Status.OK.getStatusCode(), responseV2.getStatusCode().value());
+ assertThat(responseV2.getBody(), sameBeanAs(expectedResponse));
+
+ }
+
+ @Test
+ public void testRollbackVfModule() throws IOException {
+
+
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId(MSO_REQUEST_ID);
+ msoRequest.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
+
+ VfModuleRollback vfModuleRollback = new VfModuleRollback(AAI_VNF_ID, VF_MODULE_ID, "StackId", false, TENANT_ID,
+ CLOUD_OWNER, CLOUDSITE_ID, msoRequest, "messageId");
+
+ RollbackVfModuleRequest request = new RollbackVfModuleRequest();
+ request.setVfModuleRollback(vfModuleRollback);
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+ mockOpenStackGetStacksStackId_200(wireMockServer, wireMockPort);
+
+ mockOpenStackDeleteStacks(wireMockServer);
+
+ mockOpenStackGetStacksVUSP_404(wireMockServer);
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ HttpEntity<RollbackVfModuleRequest> entity = new HttpEntity<RollbackVfModuleRequest>(request, headers);
+
+ ResponseEntity<RollbackVfModuleResponse> response = restTemplate.exchange(
+ createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID + "/rollback"),
+ HttpMethod.DELETE, entity, RollbackVfModuleResponse.class);
+
+ RollbackVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/RollbackVfModuleResponse.json"), RollbackVfModuleResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+
+ }
+
+ @Ignore
+ @Test
+ public void testQueryVfModule() throws IOException {
+
+ String testUrl = createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID);
+ String testUri = UriBuilder.fromPath("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID)
+ .host("localhost").port(wireMockPort).scheme("http")
+ // .queryParam("cloudSiteId", CLOUDSITE_ID).queryParam("tenantId", TENANT_ID)
+ .build().toString();
+ System.out.println(testUri);
+
+ mockOpenStackResponseAccess(wireMockServer, wireMockPort);
+
+
+ headers.add("Accept", MediaType.APPLICATION_JSON);
+ // HttpEntity entity = new HttpEntity(null, headers);
+ ResponseEntity<QueryVfModuleResponse> response =
+ restTemplate.getForEntity(testUri, QueryVfModuleResponse.class);
+ // System.out.println(response);
+
+ QueryVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue(
+ new File("src/test/resources/__files/QueryVfModuleResponse.json"), QueryVfModuleResponse.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ assertThat(response.getBody(), sameBeanAs(expectedResponse));
+ }
+
+ private CreateVfModuleRequest populateCreateVfModuleRequest() {
+ CreateVfModuleRequest request = new CreateVfModuleRequest();
+ request.setBackout(true);
+ request.setSkipAAI(true);
+ request.setFailIfExists(false);
+ MsoRequest msoReq = new MsoRequest();
+ boolean failIfExists = true;
+ boolean enableBridge = false;
+ Map<String, Object> vfModuleParams = new HashMap<>();
+
+ vfModuleParams.put("vf_module_id", VF_MODULE_ID);
+ vfModuleParams.put("vnf_id", AAI_VNF_ID);
+ vfModuleParams.put("network_name", NETWORK_NAME);
+ vfModuleParams.put("vnf_name", VNF_NAME);
+ vfModuleParams.put("environment_context", "");
+ vfModuleParams.put("server_name", SERVER_NAME);
+ vfModuleParams.put("image", IMAGE);
+ vfModuleParams.put("workload_context", "");
+ vfModuleParams.put("vf_module_index", VF_MODULE_INDEX);
+ vfModuleParams.put("vf_module_name", VF_MODULE_NAME);
+ vfModuleParams.put("availability_zone_0", AVAILABILITY_ZONE_0);
+ vfModuleParams.put("exn_direct_net_fqdn", EXN_DIRECT_NET_FQDN);
+ vfModuleParams.put("exn_hsl_net_fqdn", EXN_HSL_NET_FQDN);
+
+ msoReq.setRequestId(MSO_REQUEST_ID);
+ msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID);
+ request.setMsoRequest(msoReq);
+ request.setRequestType(REQUEST_TYPE);
+ request.setCloudSiteId(CLOUDSITE_ID);
+ request.setTenantId(TENANT_ID);
+ request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID);
+ request.setVnfId(AAI_VNF_ID);
+ request.setVnfType(VNF_TYPE);
+ request.setVnfVersion(VNF_VERSION);
+ request.setVfModuleId(VF_MODULE_ID);
+ request.setVfModuleName(VF_MODULE_NAME);
+ request.setVfModuleType(VF_MODULE_TYPE);
+ request.setBaseVfModuleId(BASE_VF_MODULE_ID);
+ request.setFailIfExists(failIfExists);
+ request.setEnableBridge(enableBridge);
+ request.setVfModuleParams(vfModuleParams);
+ request.setMessageId(MESSAGE_ID);
+
+ return request;
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestTest.java
index 20372b81d9..523a6903cc 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestTest.java
@@ -56,9 +56,9 @@ public class VolumeAdapterRestTest extends VolumeGroupAdapterCommon {
CreateVolumeGroupRequest request = buildCreateVfModuleRequest();
HttpEntity<CreateVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
- ResponseEntity<CreateVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/volume-groups"), HttpMethod.POST,
- entity, CreateVolumeGroupResponse.class);
+ ResponseEntity<CreateVolumeGroupResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v1/volume-groups"), HttpMethod.POST, entity,
+ CreateVolumeGroupResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
}
@@ -72,43 +72,43 @@ public class VolumeAdapterRestTest extends VolumeGroupAdapterCommon {
request.setNotificationUrl("http://localhost:8080");
HttpEntity<CreateVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
- ResponseEntity<CreateVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/volume-groups"), HttpMethod.POST,
- entity, CreateVolumeGroupResponse.class);
+ ResponseEntity<CreateVolumeGroupResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v1/volume-groups"), HttpMethod.POST, entity,
+ CreateVolumeGroupResponse.class);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
}
@Test
- public void testDeleteVNFVolumes() throws IOException {
+ public void testDeleteVNFVolumes() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
DeleteVolumeGroupRequest request = buildDeleteVolumeGroupRequest();
HttpEntity<DeleteVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
- ResponseEntity<DeleteVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/volume-groups/"+VOLUME_GROUP_ID), HttpMethod.DELETE,
- entity, DeleteVolumeGroupResponse.class);
+ ResponseEntity<DeleteVolumeGroupResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID),
+ HttpMethod.DELETE, entity, DeleteVolumeGroupResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
}
@Test
- public void testDeleteVNFVolumesAsync() throws IOException {
+ public void testDeleteVNFVolumesAsync() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
DeleteVolumeGroupRequest request = buildDeleteVolumeGroupRequest();
request.setNotificationUrl("http://localhost:8080");
HttpEntity<DeleteVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
- ResponseEntity<DeleteVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/volume-groups/"+VOLUME_GROUP_ID), HttpMethod.DELETE,
- entity, DeleteVolumeGroupResponse.class);
+ ResponseEntity<DeleteVolumeGroupResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID),
+ HttpMethod.DELETE, entity, DeleteVolumeGroupResponse.class);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
}
@Test
- public void testRollbackVNFVolumes() throws IOException {
+ public void testRollbackVNFVolumes() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
RollbackVolumeGroupRequest request = buildRollbackVolumeGroupRequest();
HttpEntity<RollbackVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
ResponseEntity<RollbackVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/volume-groups/"+VOLUME_GROUP_ID+"/rollback"), HttpMethod.DELETE,
- entity, RollbackVolumeGroupResponse.class);
+ createURLWithPort("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID + "/rollback"),
+ HttpMethod.DELETE, entity, RollbackVolumeGroupResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
}
@@ -119,13 +119,13 @@ public class VolumeAdapterRestTest extends VolumeGroupAdapterCommon {
request.setNotificationUrl("http://localhost:8080");
HttpEntity<RollbackVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
ResponseEntity<RollbackVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/volume-groups/"+VOLUME_GROUP_ID+"/rollback"), HttpMethod.DELETE,
- entity, RollbackVolumeGroupResponse.class);
+ createURLWithPort("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID + "/rollback"),
+ HttpMethod.DELETE, entity, RollbackVolumeGroupResponse.class);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
}
@Test
- public void testQueryVNFVolumes() throws IOException{
+ public void testQueryVNFVolumes() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
mockOpenStackGetStacksWithBody_200(wireMockServer, "UPDATE_COMPLETE");
javax.ws.rs.core.UriBuilder builder = UriBuilder.fromPath("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID);
@@ -135,24 +135,22 @@ public class VolumeAdapterRestTest extends VolumeGroupAdapterCommon {
.queryParam("msoRequest.serviceInstanceId", MSO_SERVICE_INSTANCE_ID);
ResponseEntity<QueryVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort(builder.build().toString()), HttpMethod.GET,
- null,QueryVolumeGroupResponse.class);
+ createURLWithPort(builder.build().toString()), HttpMethod.GET, null, QueryVolumeGroupResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
}
@Test
- public void testQueryVNFVolumesError() throws IOException{
+ public void testQueryVNFVolumesError() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
mockOpenStackGetStacksWithBody_200(wireMockServer, "UPDATE_COMPLETE");
javax.ws.rs.core.UriBuilder builder = UriBuilder.fromPath("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID);
- builder.queryParam("tenantId", TENANT_ID)
- .queryParam("volumeGroupStackId", VOUME_GROUP_NAME).queryParam("skipAAI", true)
- .queryParam("msoRequest.requestId", MSO_REQUEST_ID)
+ builder.queryParam("tenantId", TENANT_ID).queryParam("volumeGroupStackId", VOUME_GROUP_NAME)
+ .queryParam("skipAAI", true).queryParam("msoRequest.requestId", MSO_REQUEST_ID)
.queryParam("msoRequest.serviceInstanceId", MSO_SERVICE_INSTANCE_ID);
- ResponseEntity<VolumeGroupExceptionResponse> response = restTemplate.exchange(
- createURLWithPort(builder.build().toString()), HttpMethod.GET,
- null,VolumeGroupExceptionResponse.class);
+ ResponseEntity<VolumeGroupExceptionResponse> response =
+ restTemplate.exchange(createURLWithPort(builder.build().toString()), HttpMethod.GET, null,
+ VolumeGroupExceptionResponse.class);
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
}
@@ -160,13 +158,13 @@ public class VolumeAdapterRestTest extends VolumeGroupAdapterCommon {
public void testUpdateVNFVolumes() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
mockOpenStackGetStacksWithBody_200(wireMockServer, "CREATE_COMPLETE");
- mockOpenStackPutStack(wireMockServer, VOUME_GROUP_NAME+"/stackId",200);
+ mockOpenStackPutStack(wireMockServer, VOUME_GROUP_NAME + "/stackId", 200);
mockOpenStackGetStackWithBody_200(wireMockServer, "UPDATE_COMPLETE");
UpdateVolumeGroupRequest request = buildUpdateVolumeGroupRequest();
HttpEntity<UpdateVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
- ResponseEntity<UpdateVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/volume-groups/"+VOLUME_GROUP_ID), HttpMethod.PUT,
- entity,UpdateVolumeGroupResponse.class);
+ ResponseEntity<UpdateVolumeGroupResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID),
+ HttpMethod.PUT, entity, UpdateVolumeGroupResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
}
@@ -174,14 +172,14 @@ public class VolumeAdapterRestTest extends VolumeGroupAdapterCommon {
public void testUpdateVNFVolumesAsync() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
mockOpenStackGetStacksWithBody_200(wireMockServer, "CREATE_COMPLETE");
- mockOpenStackPutStack(wireMockServer, VOUME_GROUP_NAME+"/stackId",200);
+ mockOpenStackPutStack(wireMockServer, VOUME_GROUP_NAME + "/stackId", 200);
mockOpenStackGetStackWithBody_200(wireMockServer, "UPDATE_COMPLETE");
UpdateVolumeGroupRequest request = buildUpdateVolumeGroupRequest();
request.setNotificationUrl("http://localhost:8080");
HttpEntity<UpdateVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
- ResponseEntity<UpdateVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v1/volume-groups/"+VOLUME_GROUP_ID), HttpMethod.PUT,
- entity,UpdateVolumeGroupResponse.class);
+ ResponseEntity<UpdateVolumeGroupResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID),
+ HttpMethod.PUT, entity, UpdateVolumeGroupResponse.class);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2Test.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2Test.java
index abdc2609a1..fb4bec69ed 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2Test.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2Test.java
@@ -55,9 +55,9 @@ public class VolumeAdapterRestV2Test extends VolumeGroupAdapterCommon {
CreateVolumeGroupRequest request = buildCreateVfModuleRequest();
HttpEntity<CreateVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
- ResponseEntity<CreateVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v2/volume-groups"), HttpMethod.POST,
- entity, CreateVolumeGroupResponse.class);
+ ResponseEntity<CreateVolumeGroupResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v2/volume-groups"), HttpMethod.POST, entity,
+ CreateVolumeGroupResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
}
@@ -70,60 +70,60 @@ public class VolumeAdapterRestV2Test extends VolumeGroupAdapterCommon {
CreateVolumeGroupRequest request = buildCreateVfModuleRequest();
request.setNotificationUrl("http://localhost:8080");
HttpEntity<CreateVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
- ResponseEntity<CreateVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v2/volume-groups"), HttpMethod.POST,
- entity, CreateVolumeGroupResponse.class);
+ ResponseEntity<CreateVolumeGroupResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v2/volume-groups"), HttpMethod.POST, entity,
+ CreateVolumeGroupResponse.class);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
}
@Test
- public void testDeleteVNFVolumes() throws IOException {
+ public void testDeleteVNFVolumes() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
DeleteVolumeGroupRequest request = buildDeleteVolumeGroupRequest();
HttpEntity<DeleteVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
- ResponseEntity<DeleteVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v2/volume-groups/"+VOLUME_GROUP_ID), HttpMethod.DELETE,
- entity, DeleteVolumeGroupResponse.class);
+ ResponseEntity<DeleteVolumeGroupResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID),
+ HttpMethod.DELETE, entity, DeleteVolumeGroupResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
}
@Test
- public void testDeleteVNFVolumesAsync() throws IOException {
+ public void testDeleteVNFVolumesAsync() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
DeleteVolumeGroupRequest request = buildDeleteVolumeGroupRequest();
request.setNotificationUrl("http://localhost:8080");
HttpEntity<DeleteVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
- ResponseEntity<DeleteVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v2/volume-groups/"+VOLUME_GROUP_ID), HttpMethod.DELETE,
- entity, DeleteVolumeGroupResponse.class);
+ ResponseEntity<DeleteVolumeGroupResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID),
+ HttpMethod.DELETE, entity, DeleteVolumeGroupResponse.class);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
}
@Test
- public void testRollbackVNFVolumes() throws IOException {
+ public void testRollbackVNFVolumes() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
RollbackVolumeGroupRequest request = buildRollbackVolumeGroupRequest();
HttpEntity<RollbackVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
ResponseEntity<RollbackVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v2/volume-groups/"+VOLUME_GROUP_ID+"/rollback"), HttpMethod.DELETE,
- entity, RollbackVolumeGroupResponse.class);
+ createURLWithPort("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID + "/rollback"),
+ HttpMethod.DELETE, entity, RollbackVolumeGroupResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
}
@Test
- public void testRollbackVNFVolumesAsync() throws IOException {
+ public void testRollbackVNFVolumesAsync() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
RollbackVolumeGroupRequest request = buildRollbackVolumeGroupRequest();
request.setNotificationUrl("http://localhost:8080");
HttpEntity<RollbackVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
ResponseEntity<RollbackVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v2/volume-groups/"+VOLUME_GROUP_ID+"/rollback"), HttpMethod.DELETE,
- entity, RollbackVolumeGroupResponse.class);
+ createURLWithPort("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID + "/rollback"),
+ HttpMethod.DELETE, entity, RollbackVolumeGroupResponse.class);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
}
@Test
- public void testQueryVNFVolumes() throws IOException{
+ public void testQueryVNFVolumes() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
mockOpenStackGetStacksWithBody_200(wireMockServer, "UPDATE_COMPLETE");
javax.ws.rs.core.UriBuilder builder = UriBuilder.fromPath("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID);
@@ -133,37 +133,36 @@ public class VolumeAdapterRestV2Test extends VolumeGroupAdapterCommon {
.queryParam("msoRequest.serviceInstanceId", MSO_SERVICE_INSTANCE_ID);
ResponseEntity<QueryVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort(builder.build().toString()), HttpMethod.GET,
- null,QueryVolumeGroupResponse.class);
+ createURLWithPort(builder.build().toString()), HttpMethod.GET, null, QueryVolumeGroupResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
}
@Test
- public void testQueryVNFVolumesError() throws IOException{
+ public void testQueryVNFVolumesError() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
mockOpenStackGetStacksWithBody_200(wireMockServer, "UPDATE_COMPLETE");
javax.ws.rs.core.UriBuilder builder = UriBuilder.fromPath("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID);
- builder.queryParam("tenantId", TENANT_ID)
- .queryParam("volumeGroupStackId", VOUME_GROUP_NAME).queryParam("skipAAI", true)
- .queryParam("msoRequest.requestId", MSO_REQUEST_ID)
+ builder.queryParam("tenantId", TENANT_ID).queryParam("volumeGroupStackId", VOUME_GROUP_NAME)
+ .queryParam("skipAAI", true).queryParam("msoRequest.requestId", MSO_REQUEST_ID)
.queryParam("msoRequest.serviceInstanceId", MSO_SERVICE_INSTANCE_ID);
- ResponseEntity<VolumeGroupExceptionResponse> response = restTemplate.exchange(
- createURLWithPort(builder.build().toString()), HttpMethod.GET,
- null,VolumeGroupExceptionResponse.class);
+ ResponseEntity<VolumeGroupExceptionResponse> response =
+ restTemplate.exchange(createURLWithPort(builder.build().toString()), HttpMethod.GET, null,
+ VolumeGroupExceptionResponse.class);
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
}
+
@Test
public void testUpdateVNFVolumes() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
mockOpenStackGetStacksWithBody_200(wireMockServer, "CREATE_COMPLETE");
- mockOpenStackPutStack(wireMockServer, VOUME_GROUP_NAME+"/stackId",200);
+ mockOpenStackPutStack(wireMockServer, VOUME_GROUP_NAME + "/stackId", 200);
mockOpenStackGetStackWithBody_200(wireMockServer, "UPDATE_COMPLETE");
UpdateVolumeGroupRequest request = buildUpdateVolumeGroupRequest();
HttpEntity<UpdateVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
- ResponseEntity<UpdateVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v2/volume-groups/"+VOLUME_GROUP_ID), HttpMethod.PUT,
- entity,UpdateVolumeGroupResponse.class);
+ ResponseEntity<UpdateVolumeGroupResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID),
+ HttpMethod.PUT, entity, UpdateVolumeGroupResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
}
@@ -171,14 +170,14 @@ public class VolumeAdapterRestV2Test extends VolumeGroupAdapterCommon {
public void testUpdateVNFVolumesAsync() throws IOException {
mockOpenStackResponseAccess(wireMockServer, wireMockPort);
mockOpenStackGetStacksWithBody_200(wireMockServer, "CREATE_COMPLETE");
- mockOpenStackPutStack(wireMockServer, VOUME_GROUP_NAME+"/stackId",200);
+ mockOpenStackPutStack(wireMockServer, VOUME_GROUP_NAME + "/stackId", 200);
mockOpenStackGetStackWithBody_200(wireMockServer, "UPDATE_COMPLETE");
UpdateVolumeGroupRequest request = buildUpdateVolumeGroupRequest();
request.setNotificationUrl("http://localhost:8080");
HttpEntity<UpdateVolumeGroupRequest> entity = new HttpEntity<>(request, headers);
- ResponseEntity<UpdateVolumeGroupResponse> response = restTemplate.exchange(
- createURLWithPort("/services/rest/v2/volume-groups/"+VOLUME_GROUP_ID), HttpMethod.PUT,
- entity,UpdateVolumeGroupResponse.class);
+ ResponseEntity<UpdateVolumeGroupResponse> response =
+ restTemplate.exchange(createURLWithPort("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID),
+ HttpMethod.PUT, entity, UpdateVolumeGroupResponse.class);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
}
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeGroupAdapterCommon.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeGroupAdapterCommon.java
index d0d06aed6c..14fa1df6c9 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeGroupAdapterCommon.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeGroupAdapterCommon.java
@@ -26,7 +26,6 @@ import org.onap.so.adapters.vnfrest.RollbackVolumeGroupRequest;
import org.onap.so.adapters.vnfrest.UpdateVolumeGroupRequest;
import org.onap.so.adapters.vnfrest.VolumeGroupRollback;
import org.onap.so.entity.MsoRequest;
-
import java.util.HashMap;
import java.util.Map;
@@ -113,11 +112,11 @@ public class VolumeGroupAdapterCommon extends BaseRestTestUtils {
}
private Map<String, Object> getVolumeGroupParamsMap() {
- Map<String, Object> volumeGroupParams = new HashMap<>();
- volumeGroupParams.put("fsb_volume_type_0","volume_type");
- volumeGroupParams.put("fsb_volume_image_name_1","vol_img_1");
- volumeGroupParams.put("fsb_volume_image_name_0","vol_img_0");
- volumeGroupParams.put("fsb_volume_size_0","100");
+ Map<String, Object> volumeGroupParams = new HashMap<>();
+ volumeGroupParams.put("fsb_volume_type_0", "volume_type");
+ volumeGroupParams.put("fsb_volume_image_name_1", "vol_img_1");
+ volumeGroupParams.put("fsb_volume_image_name_0", "vol_img_0");
+ volumeGroupParams.put("fsb_volume_size_0", "100");
return volumeGroupParams;
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/bpmn/mock/StubOpenStack.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/bpmn/mock/StubOpenStack.java
index de12f2cfbe..bb00700b60 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/bpmn/mock/StubOpenStack.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/bpmn/mock/StubOpenStack.java
@@ -29,464 +29,484 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
-
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
-
import org.apache.http.HttpStatus;
-
import com.github.tomakehurst.wiremock.WireMockServer;
public class StubOpenStack {
- private static final String NETWORK_NAME = "vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0";
- private static final String NETWORK_ID = "da886914-efb2-4917-b335-c8381528d90b";
- private static final String NETWORK_NAME_2 = "stackname";
- private static final String NETWORK_ID_2 = "stackId";
-
- public static void mockOpenStackResponseAccess(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackResponseAccessMulticloud(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_AccessMulticloud.json", port, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackResponseAccessQueryNetwork(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
- .withRequestBody(containing("tenantId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access_queryNetwork.json", port, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackResponseAccessAdmin(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFile("OpenstackResponse_Access_Admin.json", port, "/mockPublicUrl"))
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackPublicUrlStackByName_200(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/"+NETWORK_NAME)).willReturn(aResponse()
- .withHeader("X-Openstack-Request-Id", "openstackRquest")
- .withHeader("location", "http://localhost:" + port + "/mockPublicUrl/stacks/"+NETWORK_NAME)
- .withBody(getBodyFromFile("OpenstackResponse_StackId.json", port, "/mockPublicUrl/stacks/" + NETWORK_NAME))
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackPublicUrlStackByID_200(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/"+NETWORK_ID)).willReturn(aResponse()
- .withHeader("X-Openstack-Request-Id", "openstackRquest")
- .withHeader("location", "http://localhost:" + port + "/mockPublicUrl/stacks/"+NETWORK_NAME)
- .withBody(getBodyFromFile("OpenstackResponse_StackId.json", port, "/mockPublicUrl/stacks/" + NETWORK_NAME))
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetPublicUrlStackByNameAndID_200(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/"+NETWORK_NAME+"/"+NETWORK_ID)).willReturn(aResponse()
- .withHeader("X-Openstack-Request-Id", "openstackRquest")
- .withHeader("location", "http://localhost:" + port + "/mockPublicUrl/stacks/"+NETWORK_NAME)
- .withBody(getBodyFromFile("OpenstackResponse_StackId.json", port, "/mockPublicUrl/stacks/" + NETWORK_NAME))
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetPublicUrlStackByNameAndID_204(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/"+NETWORK_NAME+"/"+NETWORK_ID)).willReturn(aResponse()
- .withHeader("X-Openstack-Request-Id", "openstackRquest")
- .withHeader("location", "http://localhost:" + port + "/mockPublicUrl/stacks/"+NETWORK_NAME+"/"+NETWORK_ID)
- .withBody(getBodyFromFile("OpenstackResponse_StackId.json", port, "/mockPublicUrl/stacks/" + NETWORK_NAME))
- .withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenStackPutPublicUrlStackByNameAndID_200(WireMockServer wireMockServer) {
- wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/stacks/"+NETWORK_NAME+"/"+NETWORK_ID)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackPutPublicUrlStackByNameAndID_NETWORK2_200(WireMockServer wireMockServer) {
- wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/stacks/"+NETWORK_NAME_2+"/"+NETWORK_ID_2)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackDeletePublicUrlStackByNameAndID_204(WireMockServer wireMockServer) {
- wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/stacks/"+NETWORK_NAME+"/"+NETWORK_ID)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NO_CONTENT)));
- }
-
- public static void mockOpenStackPostPublicUrlWithBodyFile_200(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/stacks"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Stack.json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetStackCreatedAppC_200(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/APP-C-24595-T-IST-04AShared_untrusted_vDBE_net_3/stackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Stack_Created.json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetStackAppC_404(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/APP-C-24595-T-IST-04AShared_untrusted_vDBE_net_3"))
- .willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenStackGetStackCreatedVUSP_200(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0/stackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Stack_Created.json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetStackVUSP_404(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0"))
- .willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenStackPostStack_200(WireMockServer wireMockServer, String filename) {
- wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/stacks")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackPostNeutronNetwork_200(WireMockServer wireMockServer, String filename) {
- wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/v2.0/networks")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackPutNeutronNetwork_200(WireMockServer wireMockServer, String filename,String networkId) {
- wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+networkId)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackPutNeutronNetwork(WireMockServer wireMockServer, String networkId, int responseCode) {
- wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+networkId)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withStatus(responseCode)));
- }
-
- public static void mockOpenStackGetAllNeutronNetworks_200(WireMockServer wireMockServer, String filename){
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetNeutronNetwork_404(WireMockServer wireMockServer, String networkName) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+networkName)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenStackGetAllNeutronNetworks_404(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenstackGetWithResponse(WireMockServer wireMockServer, String url,int responseCode, String responseFile) {
- wireMockServer.stubFor(get(urlPathEqualTo(url)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)
- .withStatus(responseCode)));
- }
-
- public static void mockOpenstackPostWithResponse(WireMockServer wireMockServer, String url,int responseCode, String responseFile) {
- wireMockServer.stubFor(post(urlPathEqualTo(url)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)
- .withStatus(responseCode)));
- }
-
- public static void mockOpenstackGet(WireMockServer wireMockServer, String url,int responseCode) {
- wireMockServer.stubFor(get(urlPathEqualTo(url)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withStatus(responseCode)));
- }
-
- public static void mockOpenstackPost(WireMockServer wireMockServer, String url,int responseCode) {
- wireMockServer.stubFor(post(urlPathEqualTo(url)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withStatus(responseCode)));
- }
-
- public static void mockOpenStackGetStackVfModule_200(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json")
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetStackVfModule_404(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenStackPostStacks_200(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/stacks"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Stack.json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetStacks_404(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/3d7ff7b4-720b-4604-be0a-1974fc58ed96"))
- .willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenStackGetStacksWithBody_200(WireMockServer wireMockServer, String replaceWith) throws IOException {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFileVnfAdapter(replaceWith))
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetStackWithBody_200(WireMockServer wireMockServer, String replaceWith) throws IOException {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFileVnfAdapter(replaceWith))
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetStacksWithBody_404(WireMockServer wireMockServer) throws IOException {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(getBodyFromFileVnfAdapter(null))
- .withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenStackGetStacksStackId_404(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/stackId"))
- .willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenStackGetStacksVfModule_200(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001")).willReturn(aResponse()
- .withHeader("X-Openstack-Request-Id", "openstackRquest")
- .withBody(getBodyFromFile("OpenstackResponse_VnfStackId.json", port, "/mockPublicUrl/stacks/stackId")).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetStacksVfModuleWithLocationHeader_200(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001")).willReturn(aResponse()
- .withHeader("X-Openstack-Request-Id", "openstackRquest")
- .withHeader("location", "http://localhost:" + port + "/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001")
- .withBody(getBodyFromFile("OpenstackResponse_VnfStackId.json", port, "/mockPublicUrl/stacks/stackId")).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetStacksBaseStack_200(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/baseVfModuleStackId")).willReturn(aResponse()
- .withHeader("X-Openstack-Request-Id", "openstackRquest")
- .withHeader("location", "http://localhost:" + port + "/mockPublicUrl/stacks/baseVfModuleStackId")
- .withBody(getBodyFromFile("OpenstackResponse_VnfBaseStackId.json", port, "/mockPublicUrl/stacks/stackId")).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackPutStacks_200(WireMockServer wireMockServer) {
- wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackPutStack(WireMockServer wireMockServer, String networkId,int responseCode) {
- wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/stacks/"+networkId))
- .willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withStatus(responseCode)));
- }
-
- public static void mockOpenStackGetStacksStackId_200(WireMockServer wireMockServer, int port) throws IOException {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/StackId")).willReturn(aResponse()
- .withHeader("X-Openstack-Request-Id", "openstackRquest")
- .withHeader("location", "http://localhost:" + port + "/mockPublicUrl/stacks/stackId")
- .withBody(getBodyFromFile("OpenstackResponse_StackId.json", port, "/mockPublicUrl/stacks/stackId")).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackDeleteStacks(WireMockServer wireMockServer) {
- wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/stacks/vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0/da886914-efb2-4917-b335-c8381528d90b"))
- .willReturn(aResponse().withHeader("X-Openstack-Request-Id", "openstackRquest")));
- }
-
- public static void mockOpenStackGetStacksVUSP_404(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0/da886914-efb2-4917-b335-c8381528d90b"))
- .willReturn(aResponse()
- .withHeader("X-Openstack-Request-Id", "openstackRquest")
- .withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenStackGetStackCreated_200(WireMockServer wireMockServer, String filename, String networkName) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + networkName))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetStack_404(WireMockServer wireMockServer, String networkName) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + networkName))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenStackGetStack_500(WireMockServer wireMockServer, String networkName) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + networkName))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
- }
-
- public static void mockOpenStackGetStackDeleteOrUpdateComplete_200(WireMockServer wireMockServer, String filename) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_NAME_2 + "/" + NETWORK_ID_2))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetNeutronNetwork(WireMockServer wireMockServer, String filename,String networkId,int status) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+ networkId))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile(filename).withStatus(status)));
- }
-
- public static void mockOpenStackGetNeutronNetwork(WireMockServer wireMockServer, String networkId,int status) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/"+ networkId))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withStatus(status)));
- }
-
- public static void mockOpenStackDeleteStack_200(WireMockServer wireMockServer) {
- wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_NAME_2 + "/" + NETWORK_ID_2))
- .willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackDeleteStack_500(WireMockServer wireMockServer) {
- wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_NAME_2 + "/" + NETWORK_ID_2))
- .willReturn(aResponse().withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
- }
-
- public static void mockOpenStackDeleteNeutronNetwork(WireMockServer wireMockServer, String networkId,int responseCode) {
- wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId))
- .willReturn(aResponse().withStatus(responseCode)));
- }
-
- public static void mockOpenStackPostMetadata_200(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/tenants/tenantId/metadata")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Metadata.json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetMetadata_200(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/tenants/tenantId/metadata")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Metadata.json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackPostTenantWithBodyFile_200(WireMockServer wireMockServer) throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/tenants"))
- .withRequestBody(equalToJson(readFile("src/test/resources/__files/OpenstackRequest_Tenant.json"))).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackPostTenant_200(WireMockServer wireMockServer) throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/tenants")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetTenantByName_200(WireMockServer wireMockServer, String tenantName) {
- wireMockServer.stubFor(get(urlEqualTo("/mockPublicUrl/tenants/?name=" + tenantName)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetTenantByName_404(WireMockServer wireMockServer, String tenantName) {
- wireMockServer.stubFor(get(urlEqualTo("/mockPublicUrl/tenants/?name=" + tenantName)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenStackGetTenantById_200(WireMockServer wireMockServer, String tenantId) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/tenants/" + tenantId)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetTenantById_404(WireMockServer wireMockServer, String tenantId) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/tenants/" + tenantId)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND)));
- }
-
- public static void mockOpenStackDeleteTenantById_200(WireMockServer wireMockServer, String tenantId) {
- wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/tenants/" + tenantId)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetUser_200(WireMockServer wireMockServer, String user) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/users/" + user)).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackGetRoles_200(WireMockServer wireMockServer, String roleFor) {
- wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/" + roleFor + "/roles")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("OpenstackResponse_Roles.json").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockOpenStackPutRolesAdmin_200(WireMockServer wireMockServer, String roleFor) {
- wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/tenants/tenantId/users/msoId/roles/" + roleFor + "/admin")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json")
- .withBody("").withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockValetCreatePostResponse_200(WireMockServer wireMockServer, String requestId, String body) {
- wireMockServer.stubFor(post(urlEqualTo("/api/valet/placement/v1/?requestId=" + requestId))
+ private static final String NETWORK_NAME = "vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0";
+ private static final String NETWORK_ID = "da886914-efb2-4917-b335-c8381528d90b";
+ private static final String NETWORK_NAME_2 = "stackname";
+ private static final String NETWORK_ID_2 = "stackId";
+
+ public static void mockOpenStackResponseAccess(WireMockServer wireMockServer, int port) throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access.json", port, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackResponseAccessMulticloud(WireMockServer wireMockServer, int port)
+ throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_AccessMulticloud.json", port, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackResponseAccessQueryNetwork(WireMockServer wireMockServer, int port)
+ throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens")).withRequestBody(containing("tenantId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access_queryNetwork.json", port, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackResponseAccessAdmin(WireMockServer wireMockServer, int port) throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/v2.0/tokens"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFile("OpenstackResponse_Access_Admin.json", port, "/mockPublicUrl"))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackPublicUrlStackByName_200(WireMockServer wireMockServer, int port)
+ throws IOException {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_NAME))
+ .willReturn(aResponse().withHeader("X-Openstack-Request-Id", "openstackRquest")
+ .withHeader("location", "http://localhost:" + port + "/mockPublicUrl/stacks/" + NETWORK_NAME)
+ .withBody(getBodyFromFile("OpenstackResponse_StackId.json", port,
+ "/mockPublicUrl/stacks/" + NETWORK_NAME))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackPublicUrlStackByID_200(WireMockServer wireMockServer, int port) throws IOException {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_ID))
+ .willReturn(aResponse().withHeader("X-Openstack-Request-Id", "openstackRquest")
+ .withHeader("location", "http://localhost:" + port + "/mockPublicUrl/stacks/" + NETWORK_NAME)
+ .withBody(getBodyFromFile("OpenstackResponse_StackId.json", port,
+ "/mockPublicUrl/stacks/" + NETWORK_NAME))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetPublicUrlStackByNameAndID_200(WireMockServer wireMockServer, int port)
+ throws IOException {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_NAME + "/" + NETWORK_ID))
+ .willReturn(aResponse().withHeader("X-Openstack-Request-Id", "openstackRquest")
+ .withHeader("location", "http://localhost:" + port + "/mockPublicUrl/stacks/" + NETWORK_NAME)
+ .withBody(getBodyFromFile("OpenstackResponse_StackId.json", port,
+ "/mockPublicUrl/stacks/" + NETWORK_NAME))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetPublicUrlStackByNameAndID_204(WireMockServer wireMockServer, int port)
+ throws IOException {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_NAME + "/" + NETWORK_ID))
+ .willReturn(aResponse().withHeader("X-Openstack-Request-Id", "openstackRquest")
+ .withHeader("location",
+ "http://localhost:" + port + "/mockPublicUrl/stacks/" + NETWORK_NAME + "/" + NETWORK_ID)
+ .withBody(getBodyFromFile("OpenstackResponse_StackId.json", port,
+ "/mockPublicUrl/stacks/" + NETWORK_NAME))
+ .withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenStackPutPublicUrlStackByNameAndID_200(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_NAME + "/" + NETWORK_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackPutPublicUrlStackByNameAndID_NETWORK2_200(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_NAME_2 + "/" + NETWORK_ID_2))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackDeletePublicUrlStackByNameAndID_204(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_NAME + "/" + NETWORK_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_NO_CONTENT)));
+ }
+
+ public static void mockOpenStackPostPublicUrlWithBodyFile_200(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/stacks"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_Stack.json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetStackCreatedAppC_200(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(
+ get(urlPathEqualTo("/mockPublicUrl/stacks/APP-C-24595-T-IST-04AShared_untrusted_vDBE_net_3/stackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_Stack_Created.json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetStackAppC_404(WireMockServer wireMockServer) {
+ wireMockServer
+ .stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/APP-C-24595-T-IST-04AShared_untrusted_vDBE_net_3"))
+ .willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenStackGetStackCreatedVUSP_200(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(
+ get(urlPathEqualTo("/mockPublicUrl/stacks/vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0/stackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_Stack_Created.json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetStackVUSP_404(WireMockServer wireMockServer) {
+ wireMockServer
+ .stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0"))
+ .willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenStackPostStack_200(WireMockServer wireMockServer, String filename) {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/stacks")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackPostNeutronNetwork_200(WireMockServer wireMockServer, String filename) {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/v2.0/networks")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackPutNeutronNetwork_200(WireMockServer wireMockServer, String filename,
+ String networkId) {
+ wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId)).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackPutNeutronNetwork(WireMockServer wireMockServer, String networkId,
+ int responseCode) {
+ wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(responseCode)));
+ }
+
+ public static void mockOpenStackGetAllNeutronNetworks_200(WireMockServer wireMockServer, String filename) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetNeutronNetwork_404(WireMockServer wireMockServer, String networkName) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkName)).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenStackGetAllNeutronNetworks_404(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks")).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenstackGetWithResponse(WireMockServer wireMockServer, String url, int responseCode,
+ String responseFile) {
+ wireMockServer.stubFor(get(urlPathEqualTo(url)).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile(responseFile).withStatus(responseCode)));
+ }
+
+ public static void mockOpenstackPostWithResponse(WireMockServer wireMockServer, String url, int responseCode,
+ String responseFile) {
+ wireMockServer.stubFor(post(urlPathEqualTo(url)).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile(responseFile).withStatus(responseCode)));
+ }
+
+ public static void mockOpenstackGet(WireMockServer wireMockServer, String url, int responseCode) {
+ wireMockServer.stubFor(get(urlPathEqualTo(url))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(responseCode)));
+ }
+
+ public static void mockOpenstackPost(WireMockServer wireMockServer, String url, int responseCode) {
+ wireMockServer.stubFor(post(urlPathEqualTo(url))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(responseCode)));
+ }
+
+ public static void mockOpenStackGetStackVfModule_200(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(
+ urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json")
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetStackVfModule_404(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(
+ get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenStackPostStacks_200(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/stacks"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_Stack.json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetStacks_404(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/3d7ff7b4-720b-4604-be0a-1974fc58ed96"))
+ .willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenStackGetStacksWithBody_200(WireMockServer wireMockServer, String replaceWith)
+ throws IOException {
+ wireMockServer.stubFor(
+ get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFileVnfAdapter(replaceWith)).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetStackWithBody_200(WireMockServer wireMockServer, String replaceWith)
+ throws IOException {
+ wireMockServer.stubFor(get(
+ urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFileVnfAdapter(replaceWith)).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetStacksWithBody_404(WireMockServer wireMockServer) throws IOException {
+ wireMockServer.stubFor(
+ get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(getBodyFromFileVnfAdapter(null)).withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenStackGetStacksStackId_404(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/stackId"))
+ .willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenStackGetStacksVfModule_200(WireMockServer wireMockServer, int port) throws IOException {
+ wireMockServer.stubFor(get(urlPathEqualTo(
+ "/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001"))
+ .willReturn(aResponse().withHeader("X-Openstack-Request-Id", "openstackRquest")
+ .withBody(getBodyFromFile("OpenstackResponse_VnfStackId.json", port,
+ "/mockPublicUrl/stacks/stackId"))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetStacksVfModuleWithLocationHeader_200(WireMockServer wireMockServer, int port)
+ throws IOException {
+ wireMockServer.stubFor(
+ get(urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001"))
+ .willReturn(aResponse().withHeader("X-Openstack-Request-Id", "openstackRquest")
+ .withHeader("location", "http://localhost:" + port
+ + "/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001")
+ .withBody(getBodyFromFile("OpenstackResponse_VnfStackId.json", port,
+ "/mockPublicUrl/stacks/stackId"))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetStacksBaseStack_200(WireMockServer wireMockServer, int port) throws IOException {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/baseVfModuleStackId")).willReturn(aResponse()
+ .withHeader("X-Openstack-Request-Id", "openstackRquest")
+ .withHeader("location", "http://localhost:" + port + "/mockPublicUrl/stacks/baseVfModuleStackId")
+ .withBody(
+ getBodyFromFile("OpenstackResponse_VnfBaseStackId.json", port, "/mockPublicUrl/stacks/stackId"))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackPutStacks_200(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(put(urlPathEqualTo(
+ "/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackPutStack(WireMockServer wireMockServer, String networkId, int responseCode) {
+ wireMockServer.stubFor(put(urlPathEqualTo("/mockPublicUrl/stacks/" + networkId))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(responseCode)));
+ }
+
+ public static void mockOpenStackGetStacksStackId_200(WireMockServer wireMockServer, int port) throws IOException {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/StackId")).willReturn(aResponse()
+ .withHeader("X-Openstack-Request-Id", "openstackRquest")
+ .withHeader("location", "http://localhost:" + port + "/mockPublicUrl/stacks/stackId")
+ .withBody(getBodyFromFile("OpenstackResponse_StackId.json", port, "/mockPublicUrl/stacks/stackId"))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackDeleteStacks(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlPathEqualTo(
+ "/mockPublicUrl/stacks/vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0/da886914-efb2-4917-b335-c8381528d90b"))
+ .willReturn(aResponse().withHeader("X-Openstack-Request-Id", "openstackRquest")));
+ }
+
+ public static void mockOpenStackGetStacksVUSP_404(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlPathEqualTo(
+ "/mockPublicUrl/stacks/vUSP-23804-T-01-dpa2b_EVUSP-CORE-VIF-TSIG0_net_0/da886914-efb2-4917-b335-c8381528d90b"))
+ .willReturn(aResponse().withHeader("X-Openstack-Request-Id", "openstackRquest")
+ .withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenStackGetStackCreated_200(WireMockServer wireMockServer, String filename,
+ String networkName) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + networkName)).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile(filename).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetStack_404(WireMockServer wireMockServer, String networkName) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + networkName)).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenStackGetStack_500(WireMockServer wireMockServer, String networkName) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + networkName)).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+ }
+
+ public static void mockOpenStackGetStackDeleteOrUpdateComplete_200(WireMockServer wireMockServer, String filename) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_NAME_2 + "/" + NETWORK_ID_2))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile(filename)
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetNeutronNetwork(WireMockServer wireMockServer, String filename, String networkId,
+ int status) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId)).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withBodyFile(filename).withStatus(status)));
+ }
+
+ public static void mockOpenStackGetNeutronNetwork(WireMockServer wireMockServer, String networkId, int status) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(status)));
+ }
+
+ public static void mockOpenStackDeleteStack_200(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_NAME_2 + "/" + NETWORK_ID_2))
+ .willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackDeleteStack_500(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/stacks/" + NETWORK_NAME_2 + "/" + NETWORK_ID_2))
+ .willReturn(aResponse().withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+ }
+
+ public static void mockOpenStackDeleteNeutronNetwork(WireMockServer wireMockServer, String networkId,
+ int responseCode) {
+ wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/v2.0/networks/" + networkId))
+ .willReturn(aResponse().withStatus(responseCode)));
+ }
+
+ public static void mockOpenStackPostMetadata_200(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/tenants/tenantId/metadata"))
.willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(body).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockValetCreatePutResponse_200(WireMockServer wireMockServer, String requestId, String body) {
- wireMockServer.stubFor(put(urlEqualTo("/api/valet/placement/v1/?requestId=" + requestId))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(body).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockValetDeleteDeleteResponse_200(WireMockServer wireMockServer, String requestId, String body) {
- wireMockServer.stubFor(delete(urlEqualTo("/api/valet/placement/v1/?requestId=" + requestId))
+ .withBodyFile("OpenstackResponse_Metadata.json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetMetadata_200(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/tenants/tenantId/metadata"))
.willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(body).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockValetConfirmPutRequest_200(WireMockServer wireMockServer, String requestId, String body) {
- wireMockServer.stubFor(put(urlPathEqualTo("/api/valet/placement/v1/" + requestId + "/confirm/"))
+ .withBodyFile("OpenstackResponse_Metadata.json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackPostTenantWithBodyFile_200(WireMockServer wireMockServer) throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/tenants"))
+ .withRequestBody(equalToJson(readFile("src/test/resources/__files/OpenstackRequest_Tenant.json")))
.willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(body).withStatus(HttpStatus.SC_OK)));
- }
-
- public static void mockValetRollbackPutRequest_200(WireMockServer wireMockServer, String requestId, String body) {
- wireMockServer.stubFor(put(urlPathEqualTo("/api/valet/placement/v1/" + requestId + "/rollback/"))
+ .withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackPostTenant_200(WireMockServer wireMockServer) throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mockPublicUrl/tenants"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetTenantByName_200(WireMockServer wireMockServer, String tenantName) {
+ wireMockServer.stubFor(get(urlEqualTo("/mockPublicUrl/tenants/?name=" + tenantName))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetTenantByName_404(WireMockServer wireMockServer, String tenantName) {
+ wireMockServer.stubFor(get(urlEqualTo("/mockPublicUrl/tenants/?name=" + tenantName)).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenStackGetTenantById_200(WireMockServer wireMockServer, String tenantId) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/tenants/" + tenantId))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_Tenant.json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetTenantById_404(WireMockServer wireMockServer, String tenantId) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/tenants/" + tenantId)).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND)));
+ }
+
+ public static void mockOpenStackDeleteTenantById_200(WireMockServer wireMockServer, String tenantId) {
+ wireMockServer.stubFor(delete(urlPathEqualTo("/mockPublicUrl/tenants/" + tenantId))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetUser_200(WireMockServer wireMockServer, String user) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/users/" + user))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("OpenstackResponse_User.json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackGetRoles_200(WireMockServer wireMockServer, String roleFor) {
+ wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/" + roleFor + "/roles"))
.willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(body).withStatus(HttpStatus.SC_OK)));
- }
-
- private static String getBodyFromFileVnfAdapter(String replaceWith) throws IOException {
- String temp = readFile("src/test/resources/__files/OpenstackResponse_Stack_Created_VfModule.json");
- if (replaceWith == null) {
- return temp;
- }
- return temp.replaceAll("CREATE_COMPLETE", replaceWith);
- }
-
- private static String readFile(String fileName) throws IOException {
- try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
- StringBuilder sb = new StringBuilder();
- String line = br.readLine();
-
- while (line != null) {
- sb.append(line);
- sb.append("\n");
- line = br.readLine();
- }
- return sb.toString();
- }
- }
-
- public static String getBodyFromFile(String fileName, int port, String urlPath) throws IOException {
- return readFile("src/test/resources/__files/" + fileName).replaceAll("port", "http://localhost:" + port + urlPath);
- }
+ .withBodyFile("OpenstackResponse_Roles.json").withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockOpenStackPutRolesAdmin_200(WireMockServer wireMockServer, String roleFor) {
+ wireMockServer
+ .stubFor(put(urlPathEqualTo("/mockPublicUrl/tenants/tenantId/users/msoId/roles/" + roleFor + "/admin"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("")
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockValetCreatePostResponse_200(WireMockServer wireMockServer, String requestId, String body) {
+ wireMockServer
+ .stubFor(post(urlEqualTo("/api/valet/placement/v1/?requestId=" + requestId)).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody(body).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockValetCreatePutResponse_200(WireMockServer wireMockServer, String requestId, String body) {
+ wireMockServer.stubFor(put(urlEqualTo("/api/valet/placement/v1/?requestId=" + requestId)).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody(body).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockValetDeleteDeleteResponse_200(WireMockServer wireMockServer, String requestId, String body) {
+ wireMockServer
+ .stubFor(delete(urlEqualTo("/api/valet/placement/v1/?requestId=" + requestId)).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody(body).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockValetConfirmPutRequest_200(WireMockServer wireMockServer, String requestId, String body) {
+ wireMockServer.stubFor(
+ put(urlPathEqualTo("/api/valet/placement/v1/" + requestId + "/confirm/")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody(body).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public static void mockValetRollbackPutRequest_200(WireMockServer wireMockServer, String requestId, String body) {
+ wireMockServer.stubFor(
+ put(urlPathEqualTo("/api/valet/placement/v1/" + requestId + "/rollback/")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody(body).withStatus(HttpStatus.SC_OK)));
+ }
+
+ private static String getBodyFromFileVnfAdapter(String replaceWith) throws IOException {
+ String temp = readFile("src/test/resources/__files/OpenstackResponse_Stack_Created_VfModule.json");
+ if (replaceWith == null) {
+ return temp;
+ }
+ return temp.replaceAll("CREATE_COMPLETE", replaceWith);
+ }
+
+ private static String readFile(String fileName) throws IOException {
+ try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+
+ while (line != null) {
+ sb.append(line);
+ sb.append("\n");
+ line = br.readLine();
+ }
+ return sb.toString();
+ }
+ }
+
+ public static String getBodyFromFile(String fileName, int port, String urlPath) throws IOException {
+ return readFile("src/test/resources/__files/" + fileName).replaceAll("port",
+ "http://localhost:" + port + urlPath);
+ }
}
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java
index 3c777e17cb..0787cef75d 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java
@@ -1,17 +1,14 @@
/*
* Copyright (C) 2018 Bell Canada. All rights reserved.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
*/
package org.onap.so.heatbridge;
@@ -25,7 +22,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
@@ -35,7 +31,6 @@ import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
-
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Before;
@@ -69,7 +64,6 @@ import org.openstack4j.model.network.NetworkType;
import org.openstack4j.model.network.Port;
import org.openstack4j.openstack.heat.domain.HeatResource;
import org.openstack4j.openstack.heat.domain.HeatResource.Resources;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
@@ -86,14 +80,14 @@ public class HeatBridgeImplTest {
private OpenstackClient osClient;
private CloudIdentity cloudIdentity = new CloudIdentity();
-
+
@Mock
private AAIResourcesClient resourcesClient;
@Mock
private AAISingleTransactionClient transaction;
- private HeatBridgeImpl heatbridge;
-
+ private HeatBridgeImpl heatbridge;
+
@Before
public void setUp() throws HeatBridgeException, OpenstackClientException, BulkProcessFailed {
@@ -108,7 +102,7 @@ public class HeatBridgeImplTest {
String heatStackId = "1234567";
List<Resource> expectedResourceList = (List<Resource>) extractTestStackResources();
when(osClient.getStackBasedResources(heatStackId, HeatBridgeConstants.OS_DEFAULT_HEAT_NESTING))
- .thenReturn(expectedResourceList);
+ .thenReturn(expectedResourceList);
// Act
List<Resource> resourceList = heatbridge.queryNestedHeatStackResources(heatStackId);
@@ -122,12 +116,12 @@ public class HeatBridgeImplTest {
public void testExtractStackResourceIdsByResourceType() throws HeatBridgeException {
// Arrange
List<Resource> expectedResourceList = (List<Resource>) extractTestStackResources();
- List<String> expectedServerIds = Arrays.asList("43c2159b-2c04-46ac-bda5-594110cae2d3",
- "7cff109a-b2b7-4933-97b4-ec44a8365568");
+ List<String> expectedServerIds =
+ Arrays.asList("43c2159b-2c04-46ac-bda5-594110cae2d3", "7cff109a-b2b7-4933-97b4-ec44a8365568");
// Act
- List<String> serverIds = heatbridge
- .extractStackResourceIdsByResourceType(expectedResourceList, HeatBridgeConstants.OS_SERVER_RESOURCE_TYPE);
+ List<String> serverIds = heatbridge.extractStackResourceIdsByResourceType(expectedResourceList,
+ HeatBridgeConstants.OS_SERVER_RESOURCE_TYPE);
// Assert
assertEquals(expectedServerIds, serverIds);
@@ -205,7 +199,7 @@ public class HeatBridgeImplTest {
public void testUpdateVserversToAai() throws HeatBridgeException {
// Arrange
Server server1 = mock(Server.class);
-
+
when(server1.getId()).thenReturn("test-server1-id");
when(server1.getHypervisorHostname()).thenReturn("test-hypervisor");
when(server1.getName()).thenReturn("test-server1-name");
@@ -234,16 +228,16 @@ public class HeatBridgeImplTest {
// Act
heatbridge.buildAddVserversToAaiAction("test-genericVnf-id", "test-vfModule-id", servers);
-
+
// Assert
ArgumentCaptor<AAIResourceUri> captor = ArgumentCaptor.forClass(AAIResourceUri.class);
verify(transaction, times(2)).create(captor.capture(), any(Vserver.class));
-
+
List<AAIResourceUri> uris = captor.getAllValues();
- assertEquals(AAIUriFactory.createResourceUri(
- AAIObjectType.VSERVER, CLOUD_OWNER, REGION_ID, TENANT_ID, server1.getId()), uris.get(0));
- assertEquals(AAIUriFactory.createResourceUri(
- AAIObjectType.VSERVER, CLOUD_OWNER, REGION_ID, TENANT_ID, server2.getId()), uris.get(1));
+ assertEquals(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, CLOUD_OWNER, REGION_ID, TENANT_ID,
+ server1.getId()), uris.get(0));
+ assertEquals(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, CLOUD_OWNER, REGION_ID, TENANT_ID,
+ server2.getId()), uris.get(1));
}
@@ -315,11 +309,10 @@ public class HeatBridgeImplTest {
when(port.getMacAddress()).thenReturn("78:4f:43:68:e2:78");
when(port.getNetworkId()).thenReturn("890a203a-23gg-56jh-df67-731656a8f13a");
when(port.getDeviceId()).thenReturn("test-device-id");
- when(port.getVifDetails())
- .thenReturn(ImmutableMap.of(HeatBridgeConstants.OS_VLAN_NETWORK_KEY, "2345"));
+ when(port.getVifDetails()).thenReturn(ImmutableMap.of(HeatBridgeConstants.OS_VLAN_NETWORK_KEY, "2345"));
String pfPciId = "0000:08:00.0";
when(port.getProfile()).thenReturn(ImmutableMap.of(HeatBridgeConstants.OS_PCI_SLOT_KEY, pfPciId,
- HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY, "physical_network_id"));
+ HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY, "physical_network_id"));
Network network = mock(Network.class);
when(network.getId()).thenReturn("test-network-id");
@@ -351,8 +344,7 @@ public class HeatBridgeImplTest {
private List<? extends Resource> extractTestStackResources() {
List<HeatResource> stackResources = null;
try {
- stackResources = MAPPER.readValue(readTestResourceFile("stack-resources.json"), Resources.class)
- .getList();
+ stackResources = MAPPER.readValue(readTestResourceFile("stack-resources.json"), Resources.class).getList();
assertNotNull(stackResources);
assertFalse(stackResources.isEmpty());
} catch (IOException e) {
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/vdu/utils/VduBlueprintTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/vdu/utils/VduBlueprintTest.java
index b382b6bcf8..796d122505 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/vdu/utils/VduBlueprintTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/vdu/utils/VduBlueprintTest.java
@@ -22,7 +22,6 @@ package org.onap.so.vdu.utils;
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/vdu/utils/VduInfoTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/vdu/utils/VduInfoTest.java
index 6331563362..7041c7e949 100644
--- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/vdu/utils/VduInfoTest.java
+++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/vdu/utils/VduInfoTest.java
@@ -22,7 +22,6 @@ package org.onap.so.vdu.utils;
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java
index 09e8cf1d32..02b44efe1c 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java
@@ -27,7 +27,6 @@ import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
-
import org.onap.so.db.request.beans.ArchivedInfraRequests;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.db.request.data.repository.ArchivedInfraRequestsRepository;
@@ -41,122 +40,120 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
-
import net.javacrumbs.shedlock.core.SchedulerLock;
@Component
public class ArchiveInfraRequestsScheduler {
-
- private static Logger logger = LoggerFactory.getLogger(ArchiveInfraRequestsScheduler.class);
-
- @Autowired
- private InfraActiveRequestsRepository infraActiveRepo;
- @Autowired
- private ArchivedInfraRequestsRepository archivedInfraRepo;
-
- @Value("${mso.infra-requests.archived.period}")
- private int archivedPeriod;
-
- /**
- * Runs the scheduler nightly
- * [Seconds] [Minutes] [Hours] [Day of month] [Month] [Day of week] [Year]
- */
- @Scheduled(cron="0 0 1 * * ?")
- @SchedulerLock(name = "archiveInfraRequestsScheduler")
- public void infraRequestsScheduledTask() {
- logger.debug("Start of archiveInfraRequestsScheduler");
-
- Date currentDate= new Date();
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(currentDate);
- calendar.add(Calendar.DATE, -archivedPeriod);
- Date archivingDate = calendar.getTime();
-
- logger.debug("Date before 6 months: "+ (calendar.get(Calendar.MONTH) + 1) + "-"
- + calendar.get(Calendar.DATE) + "-" + calendar.get(Calendar.YEAR));
-
- List<InfraActiveRequests> requestsByEndTime = new ArrayList<>();
- PageRequest pageRequest = new PageRequest(0, 100);
- do {
- requestsByEndTime = infraActiveRepo.findByEndTimeLessThan(archivingDate, pageRequest);
- logger.debug("{} requests to be archived based on End Time", requestsByEndTime.size());
- archiveInfraRequests(requestsByEndTime);
- } while(!requestsByEndTime.isEmpty());
-
- List<InfraActiveRequests> requestsByStartTime = new ArrayList<>();
- do {
- requestsByStartTime = infraActiveRepo.findByStartTimeLessThanAndEndTime(archivingDate, null, pageRequest);
- logger.debug("{} requests to be archived based on Start Time", requestsByEndTime.size());
- archiveInfraRequests(requestsByStartTime);
- } while(!requestsByStartTime.isEmpty());
-
- logger.debug("End of archiveInfraRequestsScheduler");
- }
-
- protected void archiveInfraRequests(List<InfraActiveRequests> requests) {
- List<ArchivedInfraRequests> newArchivedReqs = new ArrayList<>();
- List<InfraActiveRequests> oldInfraReqs = new ArrayList<>();
-
- for(InfraActiveRequests iar: requests) {
- ArchivedInfraRequests archivedInfra = new ArchivedInfraRequests();
- try {
- archivedInfra.setAaiServiceId(iar.getAaiServiceId());
- archivedInfra.setAction(iar.getAction());
- archivedInfra.setAicCloudRegion(iar.getAicCloudRegion());
- archivedInfra.setAicNodeClli(iar.getAicNodeClli());
- archivedInfra.setCallBackUrl(iar.getCallBackUrl());
- archivedInfra.setClientRequestId(iar.getClientRequestId());
- archivedInfra.setConfigurationId(iar.getConfigurationId());
- archivedInfra.setConfigurationName(iar.getConfigurationName());
- archivedInfra.setCorrelator(iar.getCorrelator());
- archivedInfra.setEndTime(iar.getEndTime());
- archivedInfra.setLastModifiedBy(iar.getLastModifiedBy());
- archivedInfra.setNetworkId(iar.getNetworkId());
- archivedInfra.setNetworkName(iar.getNetworkName());
- archivedInfra.setNetworkType(iar.getNetworkType());
- archivedInfra.setOperationalEnvId(iar.getOperationalEnvId());
- archivedInfra.setOperationalEnvName(iar.getOperationalEnvName());
- archivedInfra.setRequestUrl(iar.getRequestUrl());
- archivedInfra.setProgress(iar.getProgress());
- archivedInfra.setProvStatus(iar.getProvStatus());
- archivedInfra.setRequestAction(iar.getRequestAction());
- archivedInfra.setRequestBody(iar.getRequestBody());
- archivedInfra.setRequestId(iar.getRequestId());
- archivedInfra.setRequestorId(iar.getRequestorId());
- archivedInfra.setRequestScope(iar.getRequestScope());
- archivedInfra.setRequestStatus(iar.getRequestStatus());
- archivedInfra.setRequestType(iar.getRequestType());
- archivedInfra.setResponseBody(iar.getResponseBody());
- archivedInfra.setServiceInstanceId(iar.getServiceInstanceId());
- archivedInfra.setServiceInstanceName(iar.getServiceInstanceName());
- archivedInfra.setServiceType(iar.getServiceType());
- archivedInfra.setSource(iar.getSource());
- archivedInfra.setStartTime(iar.getStartTime());
- archivedInfra.setStatusMessage(iar.getStatusMessage());
- archivedInfra.setTenantId(iar.getTenantId());
- archivedInfra.setVfModuleId(iar.getVfModuleId());
- archivedInfra.setVfModuleModelName(iar.getVfModuleModelName());
- archivedInfra.setVfModuleName(iar.getVfModuleName());
- archivedInfra.setVnfId(iar.getVnfId());
- archivedInfra.setVnfName(iar.getVnfName());
- archivedInfra.setVnfOutputs(iar.getVnfOutputs());
- archivedInfra.setVnfParams(iar.getVnfParams());
- archivedInfra.setVnfType(iar.getVnfType());
- archivedInfra.setVolumeGroupId(iar.getVolumeGroupId());
- archivedInfra.setVolumeGroupName(iar.getVolumeGroupName());
-
- newArchivedReqs.add(archivedInfra);
- oldInfraReqs.add(iar);
- } catch(Exception e) {
- logger.error("{} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), ErrorCode
- .UnknownError.getValue(), e);
- }
- }
-
- logger.info("Creating archivedInfraRequest records: {}", newArchivedReqs.size());
- archivedInfraRepo.saveAll(newArchivedReqs);
-
- logger.info("Deleting InfraActiveRequest records: {}", oldInfraReqs.size());
- infraActiveRepo.deleteAll(oldInfraReqs);
- }
+
+ private static Logger logger = LoggerFactory.getLogger(ArchiveInfraRequestsScheduler.class);
+
+ @Autowired
+ private InfraActiveRequestsRepository infraActiveRepo;
+ @Autowired
+ private ArchivedInfraRequestsRepository archivedInfraRepo;
+
+ @Value("${mso.infra-requests.archived.period}")
+ private int archivedPeriod;
+
+ /**
+ * Runs the scheduler nightly [Seconds] [Minutes] [Hours] [Day of month] [Month] [Day of week] [Year]
+ */
+ @Scheduled(cron = "0 0 1 * * ?")
+ @SchedulerLock(name = "archiveInfraRequestsScheduler")
+ public void infraRequestsScheduledTask() {
+ logger.debug("Start of archiveInfraRequestsScheduler");
+
+ Date currentDate = new Date();
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(currentDate);
+ calendar.add(Calendar.DATE, -archivedPeriod);
+ Date archivingDate = calendar.getTime();
+
+ logger.debug("Date before 6 months: " + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DATE)
+ + "-" + calendar.get(Calendar.YEAR));
+
+ List<InfraActiveRequests> requestsByEndTime = new ArrayList<>();
+ PageRequest pageRequest = new PageRequest(0, 100);
+ do {
+ requestsByEndTime = infraActiveRepo.findByEndTimeLessThan(archivingDate, pageRequest);
+ logger.debug("{} requests to be archived based on End Time", requestsByEndTime.size());
+ archiveInfraRequests(requestsByEndTime);
+ } while (!requestsByEndTime.isEmpty());
+
+ List<InfraActiveRequests> requestsByStartTime = new ArrayList<>();
+ do {
+ requestsByStartTime = infraActiveRepo.findByStartTimeLessThanAndEndTime(archivingDate, null, pageRequest);
+ logger.debug("{} requests to be archived based on Start Time", requestsByEndTime.size());
+ archiveInfraRequests(requestsByStartTime);
+ } while (!requestsByStartTime.isEmpty());
+
+ logger.debug("End of archiveInfraRequestsScheduler");
+ }
+
+ protected void archiveInfraRequests(List<InfraActiveRequests> requests) {
+ List<ArchivedInfraRequests> newArchivedReqs = new ArrayList<>();
+ List<InfraActiveRequests> oldInfraReqs = new ArrayList<>();
+
+ for (InfraActiveRequests iar : requests) {
+ ArchivedInfraRequests archivedInfra = new ArchivedInfraRequests();
+ try {
+ archivedInfra.setAaiServiceId(iar.getAaiServiceId());
+ archivedInfra.setAction(iar.getAction());
+ archivedInfra.setAicCloudRegion(iar.getAicCloudRegion());
+ archivedInfra.setAicNodeClli(iar.getAicNodeClli());
+ archivedInfra.setCallBackUrl(iar.getCallBackUrl());
+ archivedInfra.setClientRequestId(iar.getClientRequestId());
+ archivedInfra.setConfigurationId(iar.getConfigurationId());
+ archivedInfra.setConfigurationName(iar.getConfigurationName());
+ archivedInfra.setCorrelator(iar.getCorrelator());
+ archivedInfra.setEndTime(iar.getEndTime());
+ archivedInfra.setLastModifiedBy(iar.getLastModifiedBy());
+ archivedInfra.setNetworkId(iar.getNetworkId());
+ archivedInfra.setNetworkName(iar.getNetworkName());
+ archivedInfra.setNetworkType(iar.getNetworkType());
+ archivedInfra.setOperationalEnvId(iar.getOperationalEnvId());
+ archivedInfra.setOperationalEnvName(iar.getOperationalEnvName());
+ archivedInfra.setRequestUrl(iar.getRequestUrl());
+ archivedInfra.setProgress(iar.getProgress());
+ archivedInfra.setProvStatus(iar.getProvStatus());
+ archivedInfra.setRequestAction(iar.getRequestAction());
+ archivedInfra.setRequestBody(iar.getRequestBody());
+ archivedInfra.setRequestId(iar.getRequestId());
+ archivedInfra.setRequestorId(iar.getRequestorId());
+ archivedInfra.setRequestScope(iar.getRequestScope());
+ archivedInfra.setRequestStatus(iar.getRequestStatus());
+ archivedInfra.setRequestType(iar.getRequestType());
+ archivedInfra.setResponseBody(iar.getResponseBody());
+ archivedInfra.setServiceInstanceId(iar.getServiceInstanceId());
+ archivedInfra.setServiceInstanceName(iar.getServiceInstanceName());
+ archivedInfra.setServiceType(iar.getServiceType());
+ archivedInfra.setSource(iar.getSource());
+ archivedInfra.setStartTime(iar.getStartTime());
+ archivedInfra.setStatusMessage(iar.getStatusMessage());
+ archivedInfra.setTenantId(iar.getTenantId());
+ archivedInfra.setVfModuleId(iar.getVfModuleId());
+ archivedInfra.setVfModuleModelName(iar.getVfModuleModelName());
+ archivedInfra.setVfModuleName(iar.getVfModuleName());
+ archivedInfra.setVnfId(iar.getVnfId());
+ archivedInfra.setVnfName(iar.getVnfName());
+ archivedInfra.setVnfOutputs(iar.getVnfOutputs());
+ archivedInfra.setVnfParams(iar.getVnfParams());
+ archivedInfra.setVnfType(iar.getVnfType());
+ archivedInfra.setVolumeGroupId(iar.getVolumeGroupId());
+ archivedInfra.setVolumeGroupName(iar.getVolumeGroupName());
+
+ newArchivedReqs.add(archivedInfra);
+ oldInfraReqs.add(iar);
+ } catch (Exception e) {
+ logger.error("{} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), ErrorCode.UnknownError.getValue(),
+ e);
+ }
+ }
+
+ logger.info("Creating archivedInfraRequest records: {}", newArchivedReqs.size());
+ archivedInfraRepo.saveAll(newArchivedReqs);
+
+ logger.info("Deleting InfraActiveRequest records: {}", oldInfraReqs.size());
+ infraActiveRepo.deleteAll(oldInfraReqs);
+ }
}
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomController.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomController.java
index a476f890cc..f6a0aec86f 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomController.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomController.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.requestsdb;
import java.util.List;
import java.util.Map;
-
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.db.request.data.controller.InstanceNameDuplicateCheckRequest;
import org.onap.so.db.request.data.repository.InfraActiveRequestsRepository;
@@ -40,26 +39,35 @@ public class InfraActiveRequestsRepositoryCustomController {
@Autowired
InfraActiveRequestsRepository infraActiveRequestsRepository;
- @RequestMapping(method = RequestMethod.POST, value = "/infraActiveRequests/getCloudOrchestrationFiltersFromInfraActive")
- public List<InfraActiveRequests> getCloudOrchestrationFiltersFromInfraActive(@RequestBody Map<String, String> orchestrationMap) {
+ @RequestMapping(method = RequestMethod.POST,
+ value = "/infraActiveRequests/getCloudOrchestrationFiltersFromInfraActive")
+ public List<InfraActiveRequests> getCloudOrchestrationFiltersFromInfraActive(
+ @RequestBody Map<String, String> orchestrationMap) {
return infraActiveRequestsRepository.getCloudOrchestrationFiltersFromInfraActive(orchestrationMap);
}
@RequestMapping(method = RequestMethod.POST, value = "/infraActiveRequests/getOrchestrationFiltersFromInfraActive")
- public List<InfraActiveRequests> getOrchestrationFiltersFromInfraActive(@RequestBody Map<String, List<String>> orchestrationMap) {
+ public List<InfraActiveRequests> getOrchestrationFiltersFromInfraActive(
+ @RequestBody Map<String, List<String>> orchestrationMap) {
return infraActiveRequestsRepository.getOrchestrationFiltersFromInfraActive(orchestrationMap);
}
- @RequestMapping(method = RequestMethod.GET, value = "/infraActiveRequests/checkVnfIdStatus/{operationalEnvironmentId}")
- public InfraActiveRequests checkVnfIdStatus(@PathVariable("operationalEnvironmentId") String operationalEnvironmentId) {
+ @RequestMapping(method = RequestMethod.GET,
+ value = "/infraActiveRequests/checkVnfIdStatus/{operationalEnvironmentId}")
+ public InfraActiveRequests checkVnfIdStatus(
+ @PathVariable("operationalEnvironmentId") String operationalEnvironmentId) {
return infraActiveRequestsRepository.checkVnfIdStatus(operationalEnvironmentId);
}
@RequestMapping(method = RequestMethod.POST, value = "/infraActiveRequests/checkInstanceNameDuplicate")
- public InfraActiveRequests checkInstanceNameDuplicate(@RequestBody InstanceNameDuplicateCheckRequest instanceNameDuplicateCheckRequest) {
- return infraActiveRequestsRepository.checkInstanceNameDuplicate(instanceNameDuplicateCheckRequest.getInstanceIdMap(), instanceNameDuplicateCheckRequest.getInstanceName(), instanceNameDuplicateCheckRequest.getRequestScope());
+ public InfraActiveRequests checkInstanceNameDuplicate(
+ @RequestBody InstanceNameDuplicateCheckRequest instanceNameDuplicateCheckRequest) {
+ return infraActiveRequestsRepository.checkInstanceNameDuplicate(
+ instanceNameDuplicateCheckRequest.getInstanceIdMap(),
+ instanceNameDuplicateCheckRequest.getInstanceName(),
+ instanceNameDuplicateCheckRequest.getRequestScope());
}
-
+
@RequestMapping(method = RequestMethod.POST, value = "/infraActiveRequests/v1/getInfraActiveRequests")
public List<InfraActiveRequests> getInfraActiveRequests(@RequestBody Map<String, String[]> filters,
@RequestParam("from") long startTime, @RequestParam("to") long endTime,
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapter.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapter.java
index 0c2a49ae53..f4a9f711fd 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapter.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapter.java
@@ -24,7 +24,6 @@ import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlElement;
-
import org.onap.so.adapters.requestsdb.exceptions.MsoRequestsDbException;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.db.request.beans.ResourceOperationStatus;
@@ -35,79 +34,78 @@ import org.onap.so.db.request.beans.ResourceOperationStatus;
@WebService(name = "RequestsDbAdapter", targetNamespace = "http://org.onap.so/requestsdb")
public interface MsoRequestsDbAdapter {
- @WebMethod
- public void updateInfraRequest(@WebParam(name = "requestId") @XmlElement(required = true) String requestId,
- @WebParam(name = "lastModifiedBy") @XmlElement(required = true) String lastModifiedBy,
- @WebParam(name = "statusMessage") @XmlElement(required = false) String statusMessage,
- @WebParam(name = "responseBody") @XmlElement(required = false) String responseBody,
- @WebParam(name = "requestStatus") @XmlElement(required = false) RequestStatusType requestStatus,
- @WebParam(name = "progress") @XmlElement(required = false) String progress,
- @WebParam(name = "vnfOutputs") @XmlElement(required = false) String vnfOutputs,
- @WebParam(name = "serviceInstanceId") @XmlElement(required = false) String serviceInstanceId,
- @WebParam(name = "networkId") @XmlElement(required = false) String networkId,
- @WebParam(name = "vnfId") @XmlElement(required = false) String vnfId,
- @WebParam(name = "vfModuleId") @XmlElement(required = false) String vfModuleId,
- @WebParam(name = "volumeGroupId") @XmlElement(required = false) String volumeGroupId,
- @WebParam(name = "serviceInstanceName") @XmlElement(required = false) String serviceInstanceName,
- @WebParam(name = "configurationId") @XmlElement(required = false) String configurationId,
- @WebParam(name = "configurationName") @XmlElement(required = false) String configurationName,
- @WebParam(name = "vfModuleName") @XmlElement(required = false) String vfModuleName)
- throws MsoRequestsDbException;
+ @WebMethod
+ public void updateInfraRequest(@WebParam(name = "requestId") @XmlElement(required = true) String requestId,
+ @WebParam(name = "lastModifiedBy") @XmlElement(required = true) String lastModifiedBy,
+ @WebParam(name = "statusMessage") @XmlElement(required = false) String statusMessage,
+ @WebParam(name = "responseBody") @XmlElement(required = false) String responseBody,
+ @WebParam(name = "requestStatus") @XmlElement(required = false) RequestStatusType requestStatus,
+ @WebParam(name = "progress") @XmlElement(required = false) String progress,
+ @WebParam(name = "vnfOutputs") @XmlElement(required = false) String vnfOutputs,
+ @WebParam(name = "serviceInstanceId") @XmlElement(required = false) String serviceInstanceId,
+ @WebParam(name = "networkId") @XmlElement(required = false) String networkId,
+ @WebParam(name = "vnfId") @XmlElement(required = false) String vnfId,
+ @WebParam(name = "vfModuleId") @XmlElement(required = false) String vfModuleId,
+ @WebParam(name = "volumeGroupId") @XmlElement(required = false) String volumeGroupId,
+ @WebParam(name = "serviceInstanceName") @XmlElement(required = false) String serviceInstanceName,
+ @WebParam(name = "configurationId") @XmlElement(required = false) String configurationId,
+ @WebParam(name = "configurationName") @XmlElement(required = false) String configurationName,
+ @WebParam(name = "vfModuleName") @XmlElement(required = false) String vfModuleName)
+ throws MsoRequestsDbException;
- @WebMethod
- public InfraActiveRequests getInfraRequest(
- @WebParam(name = "requestId") @XmlElement(required = true) String requestId) throws MsoRequestsDbException;
+ @WebMethod
+ public InfraActiveRequests getInfraRequest(
+ @WebParam(name = "requestId") @XmlElement(required = true) String requestId) throws MsoRequestsDbException;
- @WebMethod
- public boolean getSiteStatus(@WebParam(name = "siteName") @XmlElement(required = true) String siteName);
+ @WebMethod
+ public boolean getSiteStatus(@WebParam(name = "siteName") @XmlElement(required = true) String siteName);
- @WebMethod
- public void updateServiceOperationStatus(
- @WebParam(name = "serviceId") @XmlElement(required = true) String serviceId,
- @WebParam(name = "operationId") @XmlElement(required = false) String operationId,
- @WebParam(name = "operationType") @XmlElement(required = false) String operationType,
- @WebParam(name = "userId") @XmlElement(required = false) String userId,
- @WebParam(name = "result") @XmlElement(required = false) String result,
- @WebParam(name = "operationContent") @XmlElement(required = false) String operationContent,
- @WebParam(name = "progress") @XmlElement(required = false) String progress,
- @WebParam(name = "reason") @XmlElement(required = false) String reason) throws MsoRequestsDbException;
+ @WebMethod
+ public void updateServiceOperationStatus(
+ @WebParam(name = "serviceId") @XmlElement(required = true) String serviceId,
+ @WebParam(name = "operationId") @XmlElement(required = false) String operationId,
+ @WebParam(name = "operationType") @XmlElement(required = false) String operationType,
+ @WebParam(name = "userId") @XmlElement(required = false) String userId,
+ @WebParam(name = "result") @XmlElement(required = false) String result,
+ @WebParam(name = "operationContent") @XmlElement(required = false) String operationContent,
+ @WebParam(name = "progress") @XmlElement(required = false) String progress,
+ @WebParam(name = "reason") @XmlElement(required = false) String reason) throws MsoRequestsDbException;
- @WebMethod
- public void initServiceOperationStatus(
- @WebParam(name = "serviceId") @XmlElement(required = true) String serviceId,
- @WebParam(name = "operationId") @XmlElement(required = false) String operationId,
- @WebParam(name = "operationType") @XmlElement(required = false) String operationType,
- @WebParam(name = "userId") @XmlElement(required = false) String userId,
- @WebParam(name = "result") @XmlElement(required = false) String result,
- @WebParam(name = "operationContent") @XmlElement(required = false) String operationContent,
- @WebParam(name = "progress") @XmlElement(required = false) String progress,
- @WebParam(name = "reason") @XmlElement(required = false) String reason) throws MsoRequestsDbException;
+ @WebMethod
+ public void initServiceOperationStatus(@WebParam(name = "serviceId") @XmlElement(required = true) String serviceId,
+ @WebParam(name = "operationId") @XmlElement(required = false) String operationId,
+ @WebParam(name = "operationType") @XmlElement(required = false) String operationType,
+ @WebParam(name = "userId") @XmlElement(required = false) String userId,
+ @WebParam(name = "result") @XmlElement(required = false) String result,
+ @WebParam(name = "operationContent") @XmlElement(required = false) String operationContent,
+ @WebParam(name = "progress") @XmlElement(required = false) String progress,
+ @WebParam(name = "reason") @XmlElement(required = false) String reason) throws MsoRequestsDbException;
- @WebMethod
- public void initResourceOperationStatus(@WebParam(name = "serviceId") @XmlElement(required = true) String serviceId,
- @WebParam(name = "operationId") @XmlElement(required = true) String operationId,
- @WebParam(name = "operationType") @XmlElement(required = true) String operationType,
- @WebParam(name = "resourceTemplateUUIDs") @XmlElement(required = true) String resourceTemplateUUIDs)
- throws MsoRequestsDbException;
+ @WebMethod
+ public void initResourceOperationStatus(@WebParam(name = "serviceId") @XmlElement(required = true) String serviceId,
+ @WebParam(name = "operationId") @XmlElement(required = true) String operationId,
+ @WebParam(name = "operationType") @XmlElement(required = true) String operationType,
+ @WebParam(name = "resourceTemplateUUIDs") @XmlElement(required = true) String resourceTemplateUUIDs)
+ throws MsoRequestsDbException;
- @WebMethod
- public ResourceOperationStatus getResourceOperationStatus(
- @WebParam(name = "serviceId") @XmlElement(required = true) String serviceId,
- @WebParam(name = "operationId") @XmlElement(required = true) String operationId,
- @WebParam(name = "resourceTemplateUUID") @XmlElement(required = true) String resourceTemplateUUID)
- throws MsoRequestsDbException;
+ @WebMethod
+ public ResourceOperationStatus getResourceOperationStatus(
+ @WebParam(name = "serviceId") @XmlElement(required = true) String serviceId,
+ @WebParam(name = "operationId") @XmlElement(required = true) String operationId,
+ @WebParam(name = "resourceTemplateUUID") @XmlElement(required = true) String resourceTemplateUUID)
+ throws MsoRequestsDbException;
- @WebMethod
- public void updateResourceOperationStatus(
- @WebParam(name = "serviceId") @XmlElement(required = true) String serviceId,
- @WebParam(name = "operationId") @XmlElement(required = true) String operationId,
- @WebParam(name = "resourceTemplateUUID") @XmlElement(required = true) String resourceTemplateUUID,
- @WebParam(name = "operType") @XmlElement(required = false) String operType,
- @WebParam(name = "resourceInstanceID") @XmlElement(required = false) String resourceInstanceID,
- @WebParam(name = "jobId") @XmlElement(required = false) String jobId,
- @WebParam(name = "status") @XmlElement(required = false) String status,
- @WebParam(name = "progress") @XmlElement(required = false) String progress,
- @WebParam(name = "errorCode") @XmlElement(required = false) String errorCode,
- @WebParam(name = "statusDescription") @XmlElement(required = false) String statusDescription)
- throws MsoRequestsDbException;
-} \ No newline at end of file
+ @WebMethod
+ public void updateResourceOperationStatus(
+ @WebParam(name = "serviceId") @XmlElement(required = true) String serviceId,
+ @WebParam(name = "operationId") @XmlElement(required = true) String operationId,
+ @WebParam(name = "resourceTemplateUUID") @XmlElement(required = true) String resourceTemplateUUID,
+ @WebParam(name = "operType") @XmlElement(required = false) String operType,
+ @WebParam(name = "resourceInstanceID") @XmlElement(required = false) String resourceInstanceID,
+ @WebParam(name = "jobId") @XmlElement(required = false) String jobId,
+ @WebParam(name = "status") @XmlElement(required = false) String status,
+ @WebParam(name = "progress") @XmlElement(required = false) String progress,
+ @WebParam(name = "errorCode") @XmlElement(required = false) String errorCode,
+ @WebParam(name = "statusDescription") @XmlElement(required = false) String statusDescription)
+ throws MsoRequestsDbException;
+}
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapterImpl.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapterImpl.java
index e3867d1b93..9d6a8b0529 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapterImpl.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapterImpl.java
@@ -25,7 +25,6 @@ package org.onap.so.adapters.requestsdb;
import java.sql.Timestamp;
import java.util.List;
-
import javax.jws.WebService;
import javax.transaction.Transactional;
import org.onap.so.adapters.requestsdb.exceptions.MsoRequestsDbException;
@@ -46,324 +45,321 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
-@WebService(serviceName = "RequestsDbAdapter", endpointInterface = "org.onap.so.adapters.requestsdb.MsoRequestsDbAdapter", targetNamespace = "http://org.onap.so/requestsdb")
+@WebService(serviceName = "RequestsDbAdapter",
+ endpointInterface = "org.onap.so.adapters.requestsdb.MsoRequestsDbAdapter",
+ targetNamespace = "http://org.onap.so/requestsdb")
@Component
@Primary
-public class MsoRequestsDbAdapterImpl implements MsoRequestsDbAdapter {
+public class MsoRequestsDbAdapterImpl implements MsoRequestsDbAdapter {
- private static Logger logger = LoggerFactory.getLogger(MsoRequestsDbAdapterImpl.class);
-
- @Autowired
- private InfraActiveRequestsRepository infraActive;
+ private static Logger logger = LoggerFactory.getLogger(MsoRequestsDbAdapterImpl.class);
- @Autowired
- private SiteStatusRepository siteRepo;
+ @Autowired
+ private InfraActiveRequestsRepository infraActive;
- @Autowired
- private OperationStatusRepository operationStatusRepository;
+ @Autowired
+ private SiteStatusRepository siteRepo;
- @Autowired
- private ResourceOperationStatusRepository resourceOperationStatusRepository;
+ @Autowired
+ private OperationStatusRepository operationStatusRepository;
- @Transactional
- @Override
- public void updateInfraRequest(String requestId, String lastModifiedBy, String statusMessage, String responseBody,
- RequestStatusType requestStatus, String progress, String vnfOutputs, String serviceInstanceId,
- String networkId, String vnfId, String vfModuleId, String volumeGroupId, String serviceInstanceName,
- String configurationId, String configurationName, String vfModuleName) throws MsoRequestsDbException {
- try {
- InfraActiveRequests request = infraActive.findOneByRequestIdOrClientRequestId(requestId, requestId);
- if (request == null) {
- String error = "Entity not found. Unable to retrieve MSO Infra Requests DB for Request ID " + requestId;
- throw new MsoRequestsDbException(error);
- }
- if (statusMessage != null) {
- request.setStatusMessage(statusMessage);
- }
- if (responseBody != null) {
- request.setResponseBody(responseBody);
- }
- if (requestStatus != null) {
- request.setRequestStatus(requestStatus.toString());
- }
- if (progress != null) {
- setProgress(progress, request);
- }
- if (vnfOutputs != null) {
- request.setVnfOutputs(vnfOutputs);
- }
- if (serviceInstanceId != null) {
- request.setServiceInstanceId(serviceInstanceId);
- }
- if (networkId != null) {
- request.setNetworkId(networkId);
- }
- if (vnfId != null) {
- request.setVnfId(vnfId);
- }
- if (vfModuleId != null) {
- request.setVfModuleId(vfModuleId);
- }
- if (volumeGroupId != null) {
- request.setVolumeGroupId(volumeGroupId);
- }
- if (serviceInstanceName != null) {
- request.setServiceInstanceName(serviceInstanceName);
- }
- if (vfModuleName != null) {
- request.setVfModuleName(vfModuleName);
- }
- if (configurationId != null) {
- request.setConfigurationId(configurationId);
- }
- if (configurationName != null) {
- request.setConfigurationName(configurationName);
- }
- if (requestStatus == RequestStatusType.COMPLETE || requestStatus == RequestStatusType.FAILED) {
- Timestamp nowTimeStamp = new Timestamp(System.currentTimeMillis());
- request.setEndTime(nowTimeStamp);
- }
- request.setLastModifiedBy(lastModifiedBy);
- infraActive.save(request);
- } catch (Exception e) {
- String error = "Error retrieving MSO Infra Requests DB for Request ID " + requestId;
- logger.error(error, e);
- throw new MsoRequestsDbException(error, ErrorCode.BusinessProcesssError, e);
- }
- }
+ @Autowired
+ private ResourceOperationStatusRepository resourceOperationStatusRepository;
- private void setProgress(String progress, InfraActiveRequests request) {
- try {
- request.setProgress(Long.parseLong(progress));
- } catch (NumberFormatException e) {
- logger.warn("UpdateInfraRequest", "Invalid value sent for progress");
- }
- }
+ @Transactional
+ @Override
+ public void updateInfraRequest(String requestId, String lastModifiedBy, String statusMessage, String responseBody,
+ RequestStatusType requestStatus, String progress, String vnfOutputs, String serviceInstanceId,
+ String networkId, String vnfId, String vfModuleId, String volumeGroupId, String serviceInstanceName,
+ String configurationId, String configurationName, String vfModuleName) throws MsoRequestsDbException {
+ try {
+ InfraActiveRequests request = infraActive.findOneByRequestIdOrClientRequestId(requestId, requestId);
+ if (request == null) {
+ String error = "Entity not found. Unable to retrieve MSO Infra Requests DB for Request ID " + requestId;
+ throw new MsoRequestsDbException(error);
+ }
+ if (statusMessage != null) {
+ request.setStatusMessage(statusMessage);
+ }
+ if (responseBody != null) {
+ request.setResponseBody(responseBody);
+ }
+ if (requestStatus != null) {
+ request.setRequestStatus(requestStatus.toString());
+ }
+ if (progress != null) {
+ setProgress(progress, request);
+ }
+ if (vnfOutputs != null) {
+ request.setVnfOutputs(vnfOutputs);
+ }
+ if (serviceInstanceId != null) {
+ request.setServiceInstanceId(serviceInstanceId);
+ }
+ if (networkId != null) {
+ request.setNetworkId(networkId);
+ }
+ if (vnfId != null) {
+ request.setVnfId(vnfId);
+ }
+ if (vfModuleId != null) {
+ request.setVfModuleId(vfModuleId);
+ }
+ if (volumeGroupId != null) {
+ request.setVolumeGroupId(volumeGroupId);
+ }
+ if (serviceInstanceName != null) {
+ request.setServiceInstanceName(serviceInstanceName);
+ }
+ if (vfModuleName != null) {
+ request.setVfModuleName(vfModuleName);
+ }
+ if (configurationId != null) {
+ request.setConfigurationId(configurationId);
+ }
+ if (configurationName != null) {
+ request.setConfigurationName(configurationName);
+ }
+ if (requestStatus == RequestStatusType.COMPLETE || requestStatus == RequestStatusType.FAILED) {
+ Timestamp nowTimeStamp = new Timestamp(System.currentTimeMillis());
+ request.setEndTime(nowTimeStamp);
+ }
+ request.setLastModifiedBy(lastModifiedBy);
+ infraActive.save(request);
+ } catch (Exception e) {
+ String error = "Error retrieving MSO Infra Requests DB for Request ID " + requestId;
+ logger.error(error, e);
+ throw new MsoRequestsDbException(error, ErrorCode.BusinessProcesssError, e);
+ }
+ }
- @Override
- @Transactional
- public InfraActiveRequests getInfraRequest(String requestId) throws MsoRequestsDbException {
- logger.debug("Call to MSO Infra RequestsDb adapter get method with request Id: {}", requestId);
- InfraActiveRequests request = null;
- try {
- request = infraActive.findOneByRequestIdOrClientRequestId(requestId, requestId);
- if (request == null) {
- String error = "Entity not found. Unable to retrieve MSO Infra Requests DB for Request ID " + requestId;
- throw new MsoRequestsDbException(error);
- }
- } catch (Exception e) {
- String error = "Error retrieving MSO Infra Requests DB for Request ID " + requestId;
- logger.error(error,e);
- throw new MsoRequestsDbException(error, ErrorCode.BusinessProcesssError , e);
- }
- return request;
- }
+ private void setProgress(String progress, InfraActiveRequests request) {
+ try {
+ request.setProgress(Long.parseLong(progress));
+ } catch (NumberFormatException e) {
+ logger.warn("UpdateInfraRequest", "Invalid value sent for progress");
+ }
+ }
- /**
- * Get SiteStatus by SiteName.
- *
- * @param siteName
- * The unique name of the site
- * @return Status of that site
- */
- @Override
- @Transactional
- public boolean getSiteStatus(String siteName) {
- SiteStatus siteStatus;
- logger.debug("Request database - get Site Status with Site name: {}", siteName);
- siteStatus = siteRepo.findOneBySiteName(siteName);
- if (siteStatus == null) {
- // if not exist in DB, it means the site is not disabled, thus
- // return true
- return true;
- } else {
- return siteStatus.getStatus();
- }
- }
+ @Override
+ @Transactional
+ public InfraActiveRequests getInfraRequest(String requestId) throws MsoRequestsDbException {
+ logger.debug("Call to MSO Infra RequestsDb adapter get method with request Id: {}", requestId);
+ InfraActiveRequests request = null;
+ try {
+ request = infraActive.findOneByRequestIdOrClientRequestId(requestId, requestId);
+ if (request == null) {
+ String error = "Entity not found. Unable to retrieve MSO Infra Requests DB for Request ID " + requestId;
+ throw new MsoRequestsDbException(error);
+ }
+ } catch (Exception e) {
+ String error = "Error retrieving MSO Infra Requests DB for Request ID " + requestId;
+ logger.error(error, e);
+ throw new MsoRequestsDbException(error, ErrorCode.BusinessProcesssError, e);
+ }
+ return request;
+ }
- /**
- * update operation status <br>
- *
- * @param serviceId
- * @param operationId
- * @param operationType
- * @param userId
- * @param result
- * @param operationContent
- * @param progress
- * @param reason
- * @throws MsoRequestsDbException
- * @since ONAP Amsterdam Release
- */
- @Override
- @Transactional
- public void updateServiceOperationStatus(String serviceId, String operationId, String operationType, String userId,
- String result, String operationContent, String progress, String reason) throws MsoRequestsDbException {
- OperationStatus operStatus = operationStatusRepository.findOneByServiceIdAndOperationId(serviceId, operationId);
- if (operStatus == null) {
- String error = "Entity not found. Unable to retrieve OperationStatus Object ServiceId: " + serviceId + " operationId: "
- + operationId;
- logger.error(error);
- operStatus = new OperationStatus();
- operStatus.setOperationId(operationId);
- operStatus.setServiceId(serviceId);
- }
+ /**
+ * Get SiteStatus by SiteName.
+ *
+ * @param siteName The unique name of the site
+ * @return Status of that site
+ */
+ @Override
+ @Transactional
+ public boolean getSiteStatus(String siteName) {
+ SiteStatus siteStatus;
+ logger.debug("Request database - get Site Status with Site name: {}", siteName);
+ siteStatus = siteRepo.findOneBySiteName(siteName);
+ if (siteStatus == null) {
+ // if not exist in DB, it means the site is not disabled, thus
+ // return true
+ return true;
+ } else {
+ return siteStatus.getStatus();
+ }
+ }
- operStatus.setUserId(userId);
- operStatus.setOperation(operationType);
- operStatus.setReason(reason);
- operStatus.setProgress(progress);
- operStatus.setResult(result);
- operStatus.setOperationContent(operationContent);
- operStatus.setResult(result);
- operationStatusRepository.save(operStatus);
- }
+ /**
+ * update operation status <br>
+ *
+ * @param serviceId
+ * @param operationId
+ * @param operationType
+ * @param userId
+ * @param result
+ * @param operationContent
+ * @param progress
+ * @param reason
+ * @throws MsoRequestsDbException
+ * @since ONAP Amsterdam Release
+ */
+ @Override
+ @Transactional
+ public void updateServiceOperationStatus(String serviceId, String operationId, String operationType, String userId,
+ String result, String operationContent, String progress, String reason) throws MsoRequestsDbException {
+ OperationStatus operStatus = operationStatusRepository.findOneByServiceIdAndOperationId(serviceId, operationId);
+ if (operStatus == null) {
+ String error = "Entity not found. Unable to retrieve OperationStatus Object ServiceId: " + serviceId
+ + " operationId: " + operationId;
+ logger.error(error);
+ operStatus = new OperationStatus();
+ operStatus.setOperationId(operationId);
+ operStatus.setServiceId(serviceId);
+ }
- /**
- * Init operation status <br>
- *
- * @param serviceId
- * @param operationId
- * @param operationType
- * @param userId
- * @param result
- * @param operationContent
- * @param progress
- * @param reason
- * @throws MsoRequestsDbException
- * @since ONAP Casablanca Release
- */
- @Override
- @Transactional
- public void initServiceOperationStatus(String serviceId, String operationId, String operationType, String userId,
- String result, String operationContent, String progress, String reason) throws MsoRequestsDbException {
- OperationStatus operStatus = new OperationStatus();
+ operStatus.setUserId(userId);
+ operStatus.setOperation(operationType);
+ operStatus.setReason(reason);
+ operStatus.setProgress(progress);
+ operStatus.setResult(result);
+ operStatus.setOperationContent(operationContent);
+ operStatus.setResult(result);
+ operationStatusRepository.save(operStatus);
+ }
+
+ /**
+ * Init operation status <br>
+ *
+ * @param serviceId
+ * @param operationId
+ * @param operationType
+ * @param userId
+ * @param result
+ * @param operationContent
+ * @param progress
+ * @param reason
+ * @throws MsoRequestsDbException
+ * @since ONAP Casablanca Release
+ */
+ @Override
+ @Transactional
+ public void initServiceOperationStatus(String serviceId, String operationId, String operationType, String userId,
+ String result, String operationContent, String progress, String reason) throws MsoRequestsDbException {
+ OperationStatus operStatus = new OperationStatus();
+
+ operStatus.setOperationId(operationId);
+ operStatus.setServiceId(serviceId);
+ operStatus.setUserId(userId);
+ operStatus.setOperation(operationType);
+ operStatus.setReason(reason);
+ operStatus.setProgress(progress);
+ operStatus.setResult(result);
+ operStatus.setOperationContent(operationContent);
+ operStatus.setResult(result);
+ operationStatusRepository.save(operStatus);
+ }
+
+ /**
+ * init the operation status of all the resources <br>
+ *
+ * @param serviceId the service Id
+ * @param operationId the operation Id
+ * @param operationType the operationType
+ * @param resourceTemplateUUIDs the resources, the UUID is split by ":"
+ * @throws MsoRequestsDbException
+ * @since ONAP Amsterdam Release
+ */
+ @Override
+ @Transactional
+ public void initResourceOperationStatus(String serviceId, String operationId, String operationType,
+ String resourceTemplateUUIDs) throws MsoRequestsDbException {
+ String[] resourceLst = resourceTemplateUUIDs.split(":");
+ for (String resource : resourceLst) {
+ if ("".equals(resource)) {
+ continue;
+ }
+ ResourceOperationStatus resourceStatus = new ResourceOperationStatus();
+ resourceStatus.setOperationId(operationId);
+ resourceStatus.setServiceId(serviceId);
+ resourceStatus.setResourceTemplateUUID(resource);
+ resourceStatus.setOperType(operationType);
+ resourceStatus.setStatus(RequestsDbConstant.Status.PROCESSING);
+ resourceStatus.setStatusDescription("Waiting for start");
+ resourceOperationStatusRepository.save(resourceStatus);
- operStatus.setOperationId(operationId);
- operStatus.setServiceId(serviceId);
- operStatus.setUserId(userId);
- operStatus.setOperation(operationType);
- operStatus.setReason(reason);
- operStatus.setProgress(progress);
- operStatus.setResult(result);
- operStatus.setOperationContent(operationContent);
- operStatus.setResult(result);
- operationStatusRepository.save(operStatus);
- }
+ }
+ }
+
+ /**
+ * get resource operation status <br>
+ *
+ * @param serviceId
+ * @param operationId
+ * @param resourceTemplateUUID
+ * @return
+ * @throws MsoRequestsDbException
+ * @since ONAP Amsterdam Release
+ */
+ @Override
+ public ResourceOperationStatus getResourceOperationStatus(String serviceId, String operationId,
+ String resourceTemplateUUID) throws MsoRequestsDbException {
- /**
- * init the operation status of all the resources <br>
- *
- * @param serviceId
- * the service Id
- * @param operationId
- * the operation Id
- * @param operationType
- * the operationType
- * @param resourceTemplateUUIDs
- * the resources, the UUID is split by ":"
- * @throws MsoRequestsDbException
- * @since ONAP Amsterdam Release
- */
- @Override
- @Transactional
- public void initResourceOperationStatus(String serviceId, String operationId, String operationType,
- String resourceTemplateUUIDs) throws MsoRequestsDbException {
- String[] resourceLst = resourceTemplateUUIDs.split(":");
- for (String resource : resourceLst) {
- if ("".equals(resource)) {
- continue;
- }
- ResourceOperationStatus resourceStatus = new ResourceOperationStatus();
- resourceStatus.setOperationId(operationId);
- resourceStatus.setServiceId(serviceId);
- resourceStatus.setResourceTemplateUUID(resource);
- resourceStatus.setOperType(operationType);
- resourceStatus.setStatus(RequestsDbConstant.Status.PROCESSING);
- resourceStatus.setStatusDescription("Waiting for start");
- resourceOperationStatusRepository.save(resourceStatus);
+ return resourceOperationStatusRepository
+ .findById(new ResourceOperationStatusId(serviceId, operationId, resourceTemplateUUID))
+ .orElseThrow(() -> new MsoRequestsDbException("Operation not found:" + operationId));
- }
- }
+ }
- /**
- * get resource operation status <br>
- *
- * @param serviceId
- * @param operationId
- * @param resourceTemplateUUID
- * @return
- * @throws MsoRequestsDbException
- * @since ONAP Amsterdam Release
- */
- @Override
- public ResourceOperationStatus getResourceOperationStatus(String serviceId, String operationId,
- String resourceTemplateUUID) throws MsoRequestsDbException {
+ /**
+ * update resource operation status <br>
+ *
+ * @param serviceId
+ * @param operationId
+ * @param resourceTemplateUUID
+ * @param operationType
+ * @param resourceInstanceID
+ * @param jobId
+ * @param status
+ * @param progress
+ * @param errorCode
+ * @param statusDescription
+ * @throws MsoRequestsDbException
+ * @since ONAP Amsterdam Release
+ */
+ @Override
+ public void updateResourceOperationStatus(String serviceId, String operationId, String resourceTemplateUUID,
+ String operationType, String resourceInstanceID, String jobId, String status, String progress,
+ String errorCode, String statusDescription) throws MsoRequestsDbException {
+ ResourceOperationStatus resStatus = new ResourceOperationStatus();
+ resStatus.setServiceId(serviceId);
+ resStatus.setOperationId(operationId);
+ resStatus.setResourceTemplateUUID(resourceTemplateUUID);
+ resStatus.setOperType(operationType);
+ resStatus.setResourceInstanceID(resourceInstanceID);
+ resStatus.setJobId(jobId);
+ resStatus.setStatus(status);
+ resStatus.setProgress(progress);
+ resStatus.setErrorCode(errorCode);
+ resStatus.setStatusDescription(statusDescription);
+ resourceOperationStatusRepository.save(resStatus);
- return resourceOperationStatusRepository
- .findById(new ResourceOperationStatusId(serviceId, operationId, resourceTemplateUUID)).
- orElseThrow( () -> new MsoRequestsDbException("Operation not found:" + operationId));
-
- }
+ updateOperationStatusBasedOnResourceStatus(resStatus);
+ }
- /**
- * update resource operation status <br>
- *
- * @param serviceId
- * @param operationId
- * @param resourceTemplateUUID
- * @param operationType
- * @param resourceInstanceID
- * @param jobId
- * @param status
- * @param progress
- * @param errorCode
- * @param statusDescription
- * @throws MsoRequestsDbException
- * @since ONAP Amsterdam Release
- */
- @Override
- public void updateResourceOperationStatus(String serviceId, String operationId, String resourceTemplateUUID,
- String operationType, String resourceInstanceID, String jobId, String status, String progress,
- String errorCode, String statusDescription) throws MsoRequestsDbException {
- ResourceOperationStatus resStatus = new ResourceOperationStatus();
- resStatus.setServiceId(serviceId);
- resStatus.setOperationId(operationId);
- resStatus.setResourceTemplateUUID(resourceTemplateUUID);
- resStatus.setOperType(operationType);
- resStatus.setResourceInstanceID(resourceInstanceID);
- resStatus.setJobId(jobId);
- resStatus.setStatus(status);
- resStatus.setProgress(progress);
- resStatus.setErrorCode(errorCode);
- resStatus.setStatusDescription(statusDescription);
- resourceOperationStatusRepository.save(resStatus);
-
- updateOperationStatusBasedOnResourceStatus(resStatus);
- }
-
/**
- * update service operation status when a operation resource status updated
- * <br>
+ * update service operation status when a operation resource status updated <br>
*
* @param operStatus the resource operation status
* @since ONAP Amsterdam Release
*/
private void updateOperationStatusBasedOnResourceStatus(ResourceOperationStatus operStatus) {
- String serviceId = operStatus.getServiceId();
+ String serviceId = operStatus.getServiceId();
String operationId = operStatus.getOperationId();
logger.debug("Request database - update Operation Status Based On Resource Operation Status with service Id: "
- + "{}, operationId: {}", serviceId, operationId);
-
- List<ResourceOperationStatus> lstResourceStatus = resourceOperationStatusRepository.findByServiceIdAndOperationId(serviceId, operationId);
- if (lstResourceStatus == null) {
- logger.error("Unable to retrieve resourceOperStatus Object by ServiceId: {} operationId: {}", serviceId,
- operationId);
- return;
- }
-
- // count the total progress
+ + "{}, operationId: {}", serviceId, operationId);
+
+ List<ResourceOperationStatus> lstResourceStatus =
+ resourceOperationStatusRepository.findByServiceIdAndOperationId(serviceId, operationId);
+ if (lstResourceStatus == null) {
+ logger.error("Unable to retrieve resourceOperStatus Object by ServiceId: {} operationId: {}", serviceId,
+ operationId);
+ return;
+ }
+
+ // count the total progress
int resourceCount = lstResourceStatus.size();
int progress = 0;
boolean isFinished = true;
@@ -373,26 +369,27 @@ public class MsoRequestsDbAdapterImpl implements MsoRequestsDbAdapter {
isFinished = false;
}
}
-
- OperationStatus serviceOperStatus = operationStatusRepository.findOneByServiceIdAndOperationId(serviceId, operationId);
- if (serviceOperStatus == null) {
- String error = "Entity not found. Unable to retrieve OperationStatus Object ServiceId: " + serviceId + " operationId: "
- + operationId;
- logger.error(error);
-
- serviceOperStatus = new OperationStatus();
- serviceOperStatus.setOperationId(operationId);
- serviceOperStatus.setServiceId(serviceId);
- }
-
+
+ OperationStatus serviceOperStatus =
+ operationStatusRepository.findOneByServiceIdAndOperationId(serviceId, operationId);
+ if (serviceOperStatus == null) {
+ String error = "Entity not found. Unable to retrieve OperationStatus Object ServiceId: " + serviceId
+ + " operationId: " + operationId;
+ logger.error(error);
+
+ serviceOperStatus = new OperationStatus();
+ serviceOperStatus.setOperationId(operationId);
+ serviceOperStatus.setServiceId(serviceId);
+ }
+
progress = progress > 100 ? 100 : progress;
serviceOperStatus.setProgress(String.valueOf(progress));
serviceOperStatus.setOperationContent(operStatus.getStatusDescription());
// if current resource failed. service failed.
- if(RequestsDbConstant.Status.ERROR.equals(operStatus.getStatus())) {
+ if (RequestsDbConstant.Status.ERROR.equals(operStatus.getStatus())) {
serviceOperStatus.setResult(RequestsDbConstant.Status.ERROR);
serviceOperStatus.setReason(operStatus.getStatusDescription());
- } else if(isFinished) {
+ } else if (isFinished) {
// if finished
serviceOperStatus.setResult(RequestsDbConstant.Status.FINISHED);
serviceOperStatus.setProgress(RequestsDbConstant.Progress.ONE_HUNDRED);
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/RequestStatusType.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/RequestStatusType.java
index 1d5b892ade..9c6bcf20e7 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/RequestStatusType.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/RequestStatusType.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.07.24 at 11:49:17 AM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.07.24 at 11:49:17 AM EDT
//
@@ -35,10 +35,13 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for request-status-type.
+ * <p>
+ * Java class for request-status-type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
* <p>
+ * The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ *
* <pre>
* &lt;simpleType name="request-status-type">
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
@@ -54,10 +57,7 @@ import javax.xml.bind.annotation.XmlType;
@XmlEnum
public enum RequestStatusType {
- COMPLETE,
- FAILED,
- IN_PROGRESS,
- PENDING_MANUAL_TASK;
+ COMPLETE, FAILED, IN_PROGRESS, PENDING_MANUAL_TASK;
public String value() {
return name();
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ResponseStatus.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ResponseStatus.java
index 5ee7119f35..5ce2a729ec 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ResponseStatus.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ResponseStatus.java
@@ -22,7 +22,7 @@ package org.onap.so.adapters.requestsdb;
/*
* Enum for Status values returned by API Handler to Tail-F
-*/
+ */
public enum ResponseStatus {
- SENDING_FINAL_NOTIFY, SUCCESS, FAILED, TIMEOUT
-} \ No newline at end of file
+ SENDING_FINAL_NOTIFY, SUCCESS, FAILED, TIMEOUT
+}
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/WebSecurityConfigImpl.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/WebSecurityConfigImpl.java
index 9f52160c8e..a2c1f135c2 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/WebSecurityConfigImpl.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/WebSecurityConfigImpl.java
@@ -30,22 +30,19 @@ import org.springframework.util.StringUtils;
@EnableWebSecurity
public class WebSecurityConfigImpl extends WebSecurityConfig {
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf().disable()
- .authorizeRequests()
- .antMatchers("/manage/health","/manage/info").permitAll()
- .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),",").toString())
- .and()
- .httpBasic();
- }
-
- @Override
- public void configure(WebSecurity web) throws Exception {
- super.configure(web);
- StrictHttpFirewall firewall = new MSOSpringFirewall();
- web.httpFirewall(firewall);
- }
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll()
+ .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",").toString())
+ .and().httpBasic();
+ }
+
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ super.configure(web);
+ StrictHttpFirewall firewall = new MSOSpringFirewall();
+ web.httpFirewall(firewall);
+ }
}
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/CXFConfiguration.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/CXFConfiguration.java
index 23a769bc21..06d75befd9 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/CXFConfiguration.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/CXFConfiguration.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters.requestsdb.application;
import javax.xml.ws.Endpoint;
-
import org.apache.cxf.Bus;
import org.apache.cxf.feature.LoggingFeature;
import org.apache.cxf.jaxrs.swagger.Swagger2Feature;
@@ -39,43 +38,43 @@ import org.springframework.context.annotation.Configuration;
@Configuration
public class CXFConfiguration {
- @Autowired
- private Bus bus;
+ @Autowired
+ private Bus bus;
+
+ @Autowired
+ private MsoRequestsDbAdapter requestDbAdapterImpl;
+
+ @Bean
+ public ServletRegistrationBean cxfServlet() {
- @Autowired
- private MsoRequestsDbAdapter requestDbAdapterImpl;
-
- @Bean
- public ServletRegistrationBean cxfServlet() {
-
- return new ServletRegistrationBean(new CXFServlet(), "/services/*");
- }
+ return new ServletRegistrationBean(new CXFServlet(), "/services/*");
+ }
- @Bean
- public Endpoint requestEndpointk() {
- EndpointImpl endpoint = new EndpointImpl(bus, requestDbAdapterImpl);
- endpoint.publish("/RequestsDbAdapter");
- LoggingFeature logFeature = new LoggingFeature();
- logFeature.setPrettyLogging(true);
- logFeature.initialize(bus);
- endpoint.getFeatures().add(logFeature);
- endpoint.getInInterceptors().add(new SOAPLoggingInInterceptor());
- endpoint.getOutInterceptors().add(new SOAPLoggingOutInterceptor());
- endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor());
- return endpoint;
- }
+ @Bean
+ public Endpoint requestEndpointk() {
+ EndpointImpl endpoint = new EndpointImpl(bus, requestDbAdapterImpl);
+ endpoint.publish("/RequestsDbAdapter");
+ LoggingFeature logFeature = new LoggingFeature();
+ logFeature.setPrettyLogging(true);
+ logFeature.initialize(bus);
+ endpoint.getFeatures().add(logFeature);
+ endpoint.getInInterceptors().add(new SOAPLoggingInInterceptor());
+ endpoint.getOutInterceptors().add(new SOAPLoggingOutInterceptor());
+ endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor());
+ return endpoint;
+ }
- @Bean
- public Swagger2Feature createSwaggerFeature() {
- Swagger2Feature swagger2Feature = new Swagger2Feature();
- swagger2Feature.setPrettyPrint(true);
- swagger2Feature.setTitle("SO Request Adapter");
- swagger2Feature.setContact("The ONAP SO team");
- swagger2Feature.setDescription("This project is the SO Orchestration Engine");
- swagger2Feature.setVersion("1.0.0");
- swagger2Feature.setResourcePackage("org.onap.so.adapters.requestdb");
- swagger2Feature.setScan(true);
- return swagger2Feature;
- }
+ @Bean
+ public Swagger2Feature createSwaggerFeature() {
+ Swagger2Feature swagger2Feature = new Swagger2Feature();
+ swagger2Feature.setPrettyPrint(true);
+ swagger2Feature.setTitle("SO Request Adapter");
+ swagger2Feature.setContact("The ONAP SO team");
+ swagger2Feature.setDescription("This project is the SO Orchestration Engine");
+ swagger2Feature.setVersion("1.0.0");
+ swagger2Feature.setResourcePackage("org.onap.so.adapters.requestdb");
+ swagger2Feature.setScan(true);
+ return swagger2Feature;
+ }
}
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java
index 700a371375..6dab6c188c 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java
@@ -23,13 +23,10 @@
package org.onap.so.adapters.requestsdb.application;
import java.time.Duration;
-
import javax.sql.DataSource;
-
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
-
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.ScheduledLockConfiguration;
@@ -40,35 +37,32 @@ import net.javacrumbs.shedlock.spring.ScheduledLockConfigurationBuilder;
*
*/
-@SpringBootApplication(scanBasePackages = { "org.onap.so"})
+@SpringBootApplication(scanBasePackages = {"org.onap.so"})
public class MSORequestDBApplication {
- private static final String LOGS_DIR = "logs_dir";
+ private static final String LOGS_DIR = "logs_dir";
+
+ private static void setLogsDir() {
+ if (System.getProperty(LOGS_DIR) == null) {
+ System.getProperties().setProperty(LOGS_DIR, "./logs/reqdb/");
+ }
+ }
- private static void setLogsDir() {
- if (System.getProperty(LOGS_DIR) == null) {
- System.getProperties().setProperty(LOGS_DIR, "./logs/reqdb/");
- }
- }
+ public static void main(String... args) {
+ SpringApplication.run(MSORequestDBApplication.class, args);
+ setLogsDir();
+ }
- public static void main(String... args) {
- SpringApplication.run(MSORequestDBApplication.class, args);
- setLogsDir();
- }
+ @Bean
+ public LockProvider lockProvider(DataSource dataSource) {
+ return new JdbcTemplateLockProvider(dataSource);
+ }
- @Bean
- public LockProvider lockProvider(DataSource dataSource) {
- return new JdbcTemplateLockProvider(dataSource);
- }
-
- @Bean
- public ScheduledLockConfiguration taskScheduler(LockProvider lockProvider) {
- return ScheduledLockConfigurationBuilder
- .withLockProvider(lockProvider)
- .withPoolSize(10)
- .withDefaultLockAtMostFor(Duration.ofMinutes(10))
- .build();
- }
+ @Bean
+ public ScheduledLockConfiguration taskScheduler(LockProvider lockProvider) {
+ return ScheduledLockConfigurationBuilder.withLockProvider(lockProvider).withPoolSize(10)
+ .withDefaultLockAtMostFor(Duration.ofMinutes(10)).build();
+ }
}
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/RequestDBConfig.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/RequestDBConfig.java
index 99fa770974..651cce8543 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/RequestDBConfig.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/RequestDBConfig.java
@@ -23,7 +23,6 @@ package org.onap.so.adapters.requestsdb.application;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
-
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -41,40 +40,30 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Profile({"!test"})
@Configuration
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager",
- basePackages = { "org.onap.so.db.request.data.repository" }
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory",
+ transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"})
public class RequestDBConfig {
- @Primary
- @Bean(name = "requestDataSource")
- @ConfigurationProperties(prefix = "spring.datasource")
- public DataSource dataSource() {
- return DataSourceBuilder.create().build();
- }
+ @Primary
+ @Bean(name = "requestDataSource")
+ @ConfigurationProperties(prefix = "spring.datasource")
+ public DataSource dataSource() {
+ return DataSourceBuilder.create().build();
+ }
- @Primary
- @Bean(name = "requestEntityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("requestDataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.request.beans")
- .persistenceUnit("requestDB")
- .build();
- }
+ @Primary
+ @Bean(name = "requestEntityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("requestDataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB")
+ .build();
+ }
- @Primary
- @Bean(name = "requestTransactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("requestEntityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
+ @Primary
+ @Bean(name = "requestTransactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
}
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/WebMvcConfig.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/WebMvcConfig.java
index e932bb2cca..579afe9243 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/WebMvcConfig.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/WebMvcConfig.java
@@ -36,7 +36,7 @@ public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public MappedInterceptor mappedLoggingInterceptor() {
- return new MappedInterceptor(new String[]{"/**"}, loggingInterceptor);
+ return new MappedInterceptor(new String[] {"/**"}, loggingInterceptor);
}
}
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/exceptions/MsoRequestsDbException.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/exceptions/MsoRequestsDbException.java
index 16a3a7d427..27580977b8 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/exceptions/MsoRequestsDbException.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/exceptions/MsoRequestsDbException.java
@@ -27,12 +27,14 @@ import org.onap.so.exceptions.MSOException;
import org.onap.so.logger.ErrorCode;
/**
- * This class simply extends Exception (without addition additional functionality)
- * to provide an identifier for RequestsDB related exceptions on create, delete, query.
+ * This class simply extends Exception (without addition additional functionality) to provide an identifier for
+ * RequestsDB related exceptions on create, delete, query.
*
*
*/
-@WebFault (name="MsoRequestsDbException", faultBean="org.onap.so.adapters.requestsdb.exceptions.MsoRequestsDbExceptionBean", targetNamespace="http://org.onap.so/requestsdb")
+@WebFault(name = "MsoRequestsDbException",
+ faultBean = "org.onap.so.adapters.requestsdb.exceptions.MsoRequestsDbExceptionBean",
+ targetNamespace = "http://org.onap.so/requestsdb")
public class MsoRequestsDbException extends MSOException {
private static final long serialVersionUID = 1L;
@@ -40,27 +42,27 @@ public class MsoRequestsDbException extends MSOException {
private MsoRequestsDbExceptionBean faultInfo;
- public MsoRequestsDbException (String msg) {
+ public MsoRequestsDbException(String msg) {
super(msg);
- faultInfo = new MsoRequestsDbExceptionBean (msg);
+ faultInfo = new MsoRequestsDbExceptionBean(msg);
}
- public MsoRequestsDbException (Throwable e) {
+ public MsoRequestsDbException(Throwable e) {
super(e);
- faultInfo = new MsoRequestsDbExceptionBean (e.getMessage());
+ faultInfo = new MsoRequestsDbExceptionBean(e.getMessage());
}
- public MsoRequestsDbException (String msg, Throwable e) {
- super (msg, e);
- faultInfo = new MsoRequestsDbExceptionBean (msg);
+ public MsoRequestsDbException(String msg, Throwable e) {
+ super(msg, e);
+ faultInfo = new MsoRequestsDbExceptionBean(msg);
}
public MsoRequestsDbException(String msg, ErrorCode errorCode) {
- super(msg,errorCode.getValue());
+ super(msg, errorCode.getValue());
}
public MsoRequestsDbException(String msg, ErrorCode errorCode, Throwable t) {
- super(msg,errorCode.getValue(), t);
+ super(msg, errorCode.getValue(), t);
}
public MsoRequestsDbExceptionBean getFaultInfo() {
diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/exceptions/MsoRequestsDbExceptionBean.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/exceptions/MsoRequestsDbExceptionBean.java
index c836a6b374..9844662b51 100644
--- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/exceptions/MsoRequestsDbExceptionBean.java
+++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/exceptions/MsoRequestsDbExceptionBean.java
@@ -32,19 +32,19 @@ public class MsoRequestsDbExceptionBean implements Serializable {
private String message;
- public MsoRequestsDbExceptionBean () {
- /* Empty constructor */
- }
+ public MsoRequestsDbExceptionBean() {
+ /* Empty constructor */
+ }
- public MsoRequestsDbExceptionBean (String message) {
- this.message = message;
- }
+ public MsoRequestsDbExceptionBean(String message) {
+ this.message = message;
+ }
- public String getMessage() {
- return message;
- }
+ public String getMessage() {
+ return message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
}
diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestdb/rest/RequestProcessingDataRequestDbQueryTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestdb/rest/RequestProcessingDataRequestDbQueryTest.java
index 34643a428d..abc70ed6bf 100644
--- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestdb/rest/RequestProcessingDataRequestDbQueryTest.java
+++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestdb/rest/RequestProcessingDataRequestDbQueryTest.java
@@ -21,12 +21,9 @@
package org.onap.so.adapters.requestdb.rest;
import static org.junit.Assert.assertEquals;
-
import java.util.ArrayList;
import java.util.List;
-
import javax.transaction.Transactional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -43,50 +40,50 @@ import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = MSORequestDBApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class RequestProcessingDataRequestDbQueryTest {
- @Autowired
- private RequestsDbClient client;
-
- @LocalServerPort
- private int port;
-
- @Before
- public void setPort() {
- client.removePortFromEndpoint();
- client.setPortToEndpoint(Integer.toString(port));
- }
-
- @Test
- @Transactional
- public void RequestProcessingDataBySoRequestIdTest() {
- String soRequestId = "00032ab7-na18-42e5-965d-8ea592502018";
- String tag = "pincFabricConfigRequest";
- RequestProcessingData firstEntry = new RequestProcessingData();
- RequestProcessingData secondEntry = new RequestProcessingData();
- List<RequestProcessingData> expectedList = new ArrayList<>();
- firstEntry.setSoRequestId(soRequestId);
- firstEntry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca715");
- firstEntry.setName("configurationId");
- firstEntry.setValue("52234bc0-d6a6-41d4-a901-79015e4877e2");
- firstEntry.setTag(tag);
- secondEntry.setSoRequestId(soRequestId);
- secondEntry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca714");
- secondEntry.setName("requestAction");
- secondEntry.setValue("assign");
- secondEntry.setTag(tag);
- expectedList.add(firstEntry);
- expectedList.add(secondEntry);
+ @Autowired
+ private RequestsDbClient client;
+
+ @LocalServerPort
+ private int port;
+
+ @Before
+ public void setPort() {
+ client.removePortFromEndpoint();
+ client.setPortToEndpoint(Integer.toString(port));
+ }
+
+ @Test
+ @Transactional
+ public void RequestProcessingDataBySoRequestIdTest() {
+ String soRequestId = "00032ab7-na18-42e5-965d-8ea592502018";
+ String tag = "pincFabricConfigRequest";
+ RequestProcessingData firstEntry = new RequestProcessingData();
+ RequestProcessingData secondEntry = new RequestProcessingData();
+ List<RequestProcessingData> expectedList = new ArrayList<>();
+ firstEntry.setSoRequestId(soRequestId);
+ firstEntry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca715");
+ firstEntry.setName("configurationId");
+ firstEntry.setValue("52234bc0-d6a6-41d4-a901-79015e4877e2");
+ firstEntry.setTag(tag);
+ secondEntry.setSoRequestId(soRequestId);
+ secondEntry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca714");
+ secondEntry.setName("requestAction");
+ secondEntry.setValue("assign");
+ secondEntry.setTag(tag);
+ expectedList.add(firstEntry);
+ expectedList.add(secondEntry);
- List<RequestProcessingData> dataFound = client.getRequestProcessingDataBySoRequestId(soRequestId);
- //bean comparison with shazam fails serialization: Forgot to register a type adapter?
- assertEquals(dataFound.get(0).getSoRequestId(), firstEntry.getSoRequestId());
- assertEquals(dataFound.get(0).getGroupingId(), firstEntry.getGroupingId());
- assertEquals(dataFound.get(0).getName(), firstEntry.getName());
- assertEquals(dataFound.get(0).getValue(), firstEntry.getValue());
- assertEquals(dataFound.get(0).getTag(), firstEntry.getTag());
- assertEquals(dataFound.get(1).getSoRequestId(), secondEntry.getSoRequestId());
- assertEquals(dataFound.get(1).getGroupingId(), secondEntry.getGroupingId());
- assertEquals(dataFound.get(1).getName(), secondEntry.getName());
- assertEquals(dataFound.get(1).getValue(), secondEntry.getValue());
- assertEquals(dataFound.get(1).getTag(), secondEntry.getTag());
- }
+ List<RequestProcessingData> dataFound = client.getRequestProcessingDataBySoRequestId(soRequestId);
+ // bean comparison with shazam fails serialization: Forgot to register a type adapter?
+ assertEquals(dataFound.get(0).getSoRequestId(), firstEntry.getSoRequestId());
+ assertEquals(dataFound.get(0).getGroupingId(), firstEntry.getGroupingId());
+ assertEquals(dataFound.get(0).getName(), firstEntry.getName());
+ assertEquals(dataFound.get(0).getValue(), firstEntry.getValue());
+ assertEquals(dataFound.get(0).getTag(), firstEntry.getTag());
+ assertEquals(dataFound.get(1).getSoRequestId(), secondEntry.getSoRequestId());
+ assertEquals(dataFound.get(1).getGroupingId(), secondEntry.getGroupingId());
+ assertEquals(dataFound.get(1).getName(), secondEntry.getName());
+ assertEquals(dataFound.get(1).getValue(), secondEntry.getValue());
+ assertEquals(dataFound.get(1).getTag(), secondEntry.getTag());
+ }
}
diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/AllTestsTestSuite.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/AllTestsTestSuite.java
index f15a93eaeb..ac520c24e3 100644
--- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/AllTestsTestSuite.java
+++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/AllTestsTestSuite.java
@@ -19,14 +19,14 @@
*/
package org.onap.so.adapters.requestsdb;
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses("**/*Test.class")
public class AllTestsTestSuite {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsSchedulerTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsSchedulerTest.java
index 4b783a781c..663be24318 100644
--- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsSchedulerTest.java
+++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsSchedulerTest.java
@@ -21,10 +21,8 @@
package org.onap.so.adapters.requestsdb;
import static org.junit.Assert.assertEquals;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.db.request.data.repository.ArchivedInfraRequestsRepository;
@@ -34,45 +32,45 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
public class ArchiveInfraRequestsSchedulerTest extends RequestsAdapterBase {
-
- @Autowired
- private ArchiveInfraRequestsScheduler scheduler;
-
- @Autowired
- private InfraActiveRequestsRepository iarRepo;
-
- @Autowired
- private ArchivedInfraRequestsRepository archivedRepo;
-
- @Value("${mso.infra-requests.archived.period}")
- private int archivedPeriod;
-
- @Test
- @Transactional
- public void testArchiveInfraRequests() throws Exception {
- String requestId1 = "requestId1";
- String requestId2 = "requestId2";
-
- InfraActiveRequests iar1 = new InfraActiveRequests();
- iar1.setRequestId(requestId1);
- iar1.setAction("action1");
-
- InfraActiveRequests iar2 = new InfraActiveRequests();
- iar2.setRequestId(requestId2);
- iar2.setAction("action2");
-
- List<InfraActiveRequests> requests = new ArrayList<>();
- requests.add(iar1);
- requests.add(iar2);
- iarRepo.saveAll(requests);
-
- scheduler.archiveInfraRequests(requests);
-
- assertEquals(2, archivedRepo.count());
- assertEquals(requestId1, archivedRepo.findById(requestId1)
- .orElseThrow( () -> new Exception("Request Not Found")).getRequestId());
- assertEquals(requestId2, archivedRepo.findById(requestId2).
- orElseThrow( () -> new Exception("Request Not Found")).getRequestId());
- }
+
+ @Autowired
+ private ArchiveInfraRequestsScheduler scheduler;
+
+ @Autowired
+ private InfraActiveRequestsRepository iarRepo;
+
+ @Autowired
+ private ArchivedInfraRequestsRepository archivedRepo;
+
+ @Value("${mso.infra-requests.archived.period}")
+ private int archivedPeriod;
+
+ @Test
+ @Transactional
+ public void testArchiveInfraRequests() throws Exception {
+ String requestId1 = "requestId1";
+ String requestId2 = "requestId2";
+
+ InfraActiveRequests iar1 = new InfraActiveRequests();
+ iar1.setRequestId(requestId1);
+ iar1.setAction("action1");
+
+ InfraActiveRequests iar2 = new InfraActiveRequests();
+ iar2.setRequestId(requestId2);
+ iar2.setAction("action2");
+
+ List<InfraActiveRequests> requests = new ArrayList<>();
+ requests.add(iar1);
+ requests.add(iar2);
+ iarRepo.saveAll(requests);
+
+ scheduler.archiveInfraRequests(requests);
+
+ assertEquals(2, archivedRepo.count());
+ assertEquals(requestId1,
+ archivedRepo.findById(requestId1).orElseThrow(() -> new Exception("Request Not Found")).getRequestId());
+ assertEquals(requestId2,
+ archivedRepo.findById(requestId2).orElseThrow(() -> new Exception("Request Not Found")).getRequestId());
+ }
}
diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java
index c7804c8e0c..4ed3285a70 100644
--- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java
+++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java
@@ -23,15 +23,12 @@ package org.onap.so.adapters.requestsdb;
import static org.junit.Assert.assertEquals;
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.UUID;
-
import javax.ws.rs.core.MediaType;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.so.db.request.beans.InfraActiveRequests;
@@ -52,7 +49,7 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA
@LocalServerPort
private int port;
-
+
@Value("${mso.adapters.requestDb.auth}")
private String msoAdaptersAuth;
@@ -68,7 +65,8 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA
private void verifyInfraActiveRequests() {
assertEquals(infraActiveRequests.getRequestId(), infraActiveRequestsResponse.getRequestId());
assertEquals(infraActiveRequests.getServiceInstanceId(), infraActiveRequestsResponse.getServiceInstanceId());
- assertEquals(infraActiveRequests.getServiceInstanceName(), infraActiveRequestsResponse.getServiceInstanceName());
+ assertEquals(infraActiveRequests.getServiceInstanceName(),
+ infraActiveRequestsResponse.getServiceInstanceName());
assertEquals(infraActiveRequests.getVnfId(), infraActiveRequestsResponse.getVnfId());
assertEquals(infraActiveRequests.getVnfName(), infraActiveRequestsResponse.getVnfName());
assertEquals(infraActiveRequests.getVfModuleId(), infraActiveRequestsResponse.getVfModuleId());
@@ -88,7 +86,7 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA
assertEquals(infraActiveRequests.getOperationalEnvName(), infraActiveRequestsResponse.getOperationalEnvName());
assertEquals(infraActiveRequests.getRequestStatus(), infraActiveRequestsResponse.getRequestStatus());
assertEquals(infraActiveRequests.getAction(), infraActiveRequestsResponse.getAction());
- assertEquals(infraActiveRequests.getRequestUrl(), infraActiveRequestsResponse.getRequestUrl());
+ assertEquals(infraActiveRequests.getRequestUrl(), infraActiveRequestsResponse.getRequestUrl());
}
@Before
@@ -125,14 +123,14 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA
infraActiveRequests.setOperationalEnvName(UUID.randomUUID().toString());
infraActiveRequests.setRequestStatus("IN_PROGRESS");
infraActiveRequests.setAction("create");
- infraActiveRequests.setRequestUrl("http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances");
+ infraActiveRequests
+ .setRequestUrl("http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances");
HttpEntity<String> entity = new HttpEntity(infraActiveRequests, headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("/infraActiveRequests"));
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
assertEquals(201, response.getStatusCodeValue());
}
@@ -148,12 +146,11 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA
HttpEntity<Map<String, String>> entity = new HttpEntity<>(requestMap, headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("/infraActiveRequests") + "/getCloudOrchestrationFiltersFromInfraActive");
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(
+ createURLWithPort("/infraActiveRequests") + "/getCloudOrchestrationFiltersFromInfraActive");
- ResponseEntity<List<InfraActiveRequests>> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, new ParameterizedTypeReference<List<InfraActiveRequests>>() {
- });
+ ResponseEntity<List<InfraActiveRequests>> response = restTemplate.exchange(builder.toUriString(),
+ HttpMethod.POST, entity, new ParameterizedTypeReference<List<InfraActiveRequests>>() {});
List<InfraActiveRequests> iarr = response.getBody();
assertEquals(200, response.getStatusCodeValue());
@@ -180,12 +177,11 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA
requestMap.put("serviceInstanceName", values);
HttpEntity<Map<String, List<String>>> entityList = new HttpEntity(requestMap, headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("/infraActiveRequests") + "/getOrchestrationFiltersFromInfraActive");
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort("/infraActiveRequests") + "/getOrchestrationFiltersFromInfraActive");
- ResponseEntity<List<InfraActiveRequests>> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entityList, new ParameterizedTypeReference<List<InfraActiveRequests>>() {
- });
+ ResponseEntity<List<InfraActiveRequests>> response = restTemplate.exchange(builder.toUriString(),
+ HttpMethod.POST, entityList, new ParameterizedTypeReference<List<InfraActiveRequests>>() {});
List<InfraActiveRequests> iarr = response.getBody();
@@ -200,13 +196,13 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA
@Test
public void checkVnfIdStatusTest() {
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("/infraActiveRequests" + "/checkVnfIdStatus/" + infraActiveRequests.getOperationalEnvId()));
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(
+ "/infraActiveRequests" + "/checkVnfIdStatus/" + infraActiveRequests.getOperationalEnvId()));
HttpEntity<String> entity = new HttpEntity(HttpEntity.EMPTY, headers);
- ResponseEntity<InfraActiveRequests> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET,entity , InfraActiveRequests.class);
+ ResponseEntity<InfraActiveRequests> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, InfraActiveRequests.class);
infraActiveRequestsResponse = response.getBody();
@@ -218,17 +214,17 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA
@Test
public void checkInstanceNameDuplicateTest() {
- InstanceNameDuplicateCheckRequest instanceNameDuplicateCheckRequest = new InstanceNameDuplicateCheckRequest((HashMap<String, String>) null,
- infraActiveRequests.getOperationalEnvName(),
- infraActiveRequests.getRequestScope());
+ InstanceNameDuplicateCheckRequest instanceNameDuplicateCheckRequest =
+ new InstanceNameDuplicateCheckRequest((HashMap<String, String>) null,
+ infraActiveRequests.getOperationalEnvName(), infraActiveRequests.getRequestScope());
- HttpEntity<InstanceNameDuplicateCheckRequest> entityList = new HttpEntity(instanceNameDuplicateCheckRequest, headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("/infraActiveRequests") + "/checkInstanceNameDuplicate");
+ HttpEntity<InstanceNameDuplicateCheckRequest> entityList =
+ new HttpEntity(instanceNameDuplicateCheckRequest, headers);
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort("/infraActiveRequests") + "/checkInstanceNameDuplicate");
- ResponseEntity<InfraActiveRequests> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entityList, new ParameterizedTypeReference<InfraActiveRequests>() {
- });
+ ResponseEntity<InfraActiveRequests> response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST,
+ entityList, new ParameterizedTypeReference<InfraActiveRequests>() {});
infraActiveRequestsResponse = response.getBody();
@@ -243,17 +239,16 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA
Map<String, String> requestMap = new HashMap<>();
requestMap.put("operationalEnvironmentId", infraActiveRequests.getOperationalEnvId());
- InstanceNameDuplicateCheckRequest instanceNameDuplicateCheckRequest = new InstanceNameDuplicateCheckRequest((HashMap<String, String>) requestMap,
- null,
- infraActiveRequests.getRequestScope());
+ InstanceNameDuplicateCheckRequest instanceNameDuplicateCheckRequest = new InstanceNameDuplicateCheckRequest(
+ (HashMap<String, String>) requestMap, null, infraActiveRequests.getRequestScope());
- HttpEntity<InstanceNameDuplicateCheckRequest> entityList = new HttpEntity(instanceNameDuplicateCheckRequest, headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("/infraActiveRequests") + "/checkInstanceNameDuplicate");
+ HttpEntity<InstanceNameDuplicateCheckRequest> entityList =
+ new HttpEntity(instanceNameDuplicateCheckRequest, headers);
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort("/infraActiveRequests") + "/checkInstanceNameDuplicate");
- ResponseEntity<InfraActiveRequests> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entityList, new ParameterizedTypeReference<InfraActiveRequests>() {
- });
+ ResponseEntity<InfraActiveRequests> response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST,
+ entityList, new ParameterizedTypeReference<InfraActiveRequests>() {});
infraActiveRequestsResponse = response.getBody();
@@ -265,15 +260,16 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA
@Test
public void checkInstanceNameDuplicateTestNotFound() {
- String instanceNameDuplicateCheckRequest = "{\r\n\t \"instanceName\":\"TestNotFoundInstanceName\",\r\n\t \"requestScope\":\"testasdfasdfasdf\"\r\n}";
+ String instanceNameDuplicateCheckRequest =
+ "{\r\n\t \"instanceName\":\"TestNotFoundInstanceName\",\r\n\t \"requestScope\":\"testasdfasdfasdf\"\r\n}";
- HttpEntity<InstanceNameDuplicateCheckRequest> entityList = new HttpEntity(instanceNameDuplicateCheckRequest, headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("/infraActiveRequests") + "/checkInstanceNameDuplicate");
+ HttpEntity<InstanceNameDuplicateCheckRequest> entityList =
+ new HttpEntity(instanceNameDuplicateCheckRequest, headers);
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort("/infraActiveRequests") + "/checkInstanceNameDuplicate");
- ResponseEntity<InfraActiveRequests> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entityList, new ParameterizedTypeReference<InfraActiveRequests>() {
- });
+ ResponseEntity<InfraActiveRequests> response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST,
+ entityList, new ParameterizedTypeReference<InfraActiveRequests>() {});
assertEquals(200, response.getStatusCodeValue());
assertEquals(null, response.getBody());
@@ -285,17 +281,16 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA
Map<String, String> requestMap = new HashMap<>();
requestMap.put("operationalEnvironmentId", "NotFoundOperationalEnvId");
- InstanceNameDuplicateCheckRequest instanceNameDuplicateCheckRequest = new InstanceNameDuplicateCheckRequest((HashMap<String, String>) requestMap,
- null,
- infraActiveRequests.getRequestScope());
+ InstanceNameDuplicateCheckRequest instanceNameDuplicateCheckRequest = new InstanceNameDuplicateCheckRequest(
+ (HashMap<String, String>) requestMap, null, infraActiveRequests.getRequestScope());
- HttpEntity<InstanceNameDuplicateCheckRequest> entityList = new HttpEntity(instanceNameDuplicateCheckRequest, headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("/infraActiveRequests") + "/checkInstanceNameDuplicate");
+ HttpEntity<InstanceNameDuplicateCheckRequest> entityList =
+ new HttpEntity(instanceNameDuplicateCheckRequest, headers);
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort("/infraActiveRequests") + "/checkInstanceNameDuplicate");
- ResponseEntity<InfraActiveRequests> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entityList, new ParameterizedTypeReference<InfraActiveRequests>() {
- });
+ ResponseEntity<InfraActiveRequests> response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST,
+ entityList, new ParameterizedTypeReference<InfraActiveRequests>() {});
infraActiveRequestsResponse = response.getBody();
diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/HealthCheckHandlerTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/HealthCheckHandlerTest.java
index b911396370..514e5ad923 100644
--- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/HealthCheckHandlerTest.java
+++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/HealthCheckHandlerTest.java
@@ -22,11 +22,8 @@ package org.onap.so.adapters.requestsdb.adapters;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.util.Map;
-
import javax.ws.rs.core.Response;
-
import org.json.JSONException;
import org.junit.Test;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
@@ -38,55 +35,53 @@ import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
-
import ch.qos.logback.classic.spi.ILoggingEvent;
public class HealthCheckHandlerTest extends RequestsAdapterBase {
-
- @LocalServerPort
- private int port;
- TestRestTemplate restTemplate = new TestRestTemplate();
+ @LocalServerPort
+ private int port;
+
+ TestRestTemplate restTemplate = new TestRestTemplate();
- HttpHeaders headers = new HttpHeaders();
+ HttpHeaders headers = new HttpHeaders();
-
- @Test
- public void testHealthcheck() throws JSONException {
- TestAppender.events.clear();
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
- ResponseEntity<String> response = restTemplate.exchange(
- createURLWithPort("/manage/health"),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- for(ILoggingEvent logEvent : TestAppender.events)
- if(logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor") &&
- logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")
- ){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+ @Test
+ public void testHealthcheck() throws JSONException {
+ TestAppender.events.clear();
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(createURLWithPort("/manage/health"), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ for (ILoggingEvent logEvent : TestAppender.events)
+ if (logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor")
+ && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.INSTANCE_UUID));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID));
- assertEquals("",mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME));
- assertEquals("/manage/health",mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME));
- assertEquals("INPROGRESS",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
- }else if(logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor") &&
- logEvent.getMarker() != null && logEvent.getMarker()!= null && logEvent.getMarker().getName().equals("EXIT")){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+ assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME));
+ assertEquals("/manage/health", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME));
+ assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ } else if (logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor")
+ && logEvent.getMarker() != null && logEvent.getMarker() != null
+ && logEvent.getMarker().getName().equals("EXIT")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID));
- assertEquals("200",mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE));
- assertEquals("",mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME));
- assertEquals("/manage/health",mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME));
- assertEquals("COMPLETED",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ assertEquals("200", mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE));
+ assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME));
+ assertEquals("/manage/health", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME));
+ assertEquals("COMPLETED", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
}
TestAppender.events.clear();
- }
-
- private String createURLWithPort(String uri) {
- return "http://localhost:" + port + uri;
- }
+ }
+
+ private String createURLWithPort(String uri) {
+ return "http://localhost:" + port + uri;
+ }
}
diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java
index f6950d9777..e53b957210 100644
--- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java
+++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java
@@ -25,11 +25,9 @@ import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.junit.Before;
import org.junit.Rule;
@@ -49,469 +47,422 @@ import org.onap.so.db.request.data.repository.ResourceOperationStatusRepository;
import org.onap.so.requestsdb.RequestsDbConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.server.LocalServerPort;
-
import ch.qos.logback.classic.spi.ILoggingEvent;
public class MSORequestDBImplTest extends RequestsAdapterBase {
- @LocalServerPort
- private int port;
+ @LocalServerPort
+ private int port;
+
+ private MsoRequestsDbAdapter dbAdapter;
- private MsoRequestsDbAdapter dbAdapter;
-
@Autowired
private OperationStatusRepository operationStatusRepository;
-
+
@Autowired
private ResourceOperationStatusRepository resourceOperationStatusRepo;
@Rule
public ExpectedException thrown = ExpectedException.none();
-
- public InfraActiveRequests setupTestEntities() {
- return buildTestRequest();
- }
-
- @Before
- public void before() throws MsoRequestsDbException{
+
+ public InfraActiveRequests setupTestEntities() {
+ return buildTestRequest();
+ }
+
+ @Before
+ public void before() throws MsoRequestsDbException {
JaxWsProxyFactoryBean jaxWsProxyFactory = new JaxWsProxyFactoryBean();
jaxWsProxyFactory.setServiceClass(MsoRequestsDbAdapter.class);
jaxWsProxyFactory.setAddress("http://localhost:" + port + "/services/RequestsDbAdapter");
jaxWsProxyFactory.setUsername("bpel");
jaxWsProxyFactory.setPassword("mso-db-1507!");
dbAdapter = (MsoRequestsDbAdapter) jaxWsProxyFactory.create();
-
+
InfraActiveRequests testRequest = this.buildTestRequest();
- dbAdapter.updateInfraRequest ( testRequest.getRequestId(),
- testRequest.getLastModifiedBy(),
- testRequest.getStatusMessage(),
- testRequest.getResponseBody(),
- RequestStatusType.valueOf(testRequest.getRequestStatus()),
- testRequest.getProgress().toString(),
- testRequest.getVnfOutputs(),
- testRequest.getServiceInstanceId(),
- testRequest.getNetworkId(),
- testRequest.getVnfId(),
- testRequest.getVfModuleId(),
- testRequest.getVolumeGroupId(),
- testRequest.getServiceInstanceName(),
- testRequest.getConfigurationId(),
- testRequest.getConfigurationName(),
- testRequest.getVfModuleName());
-
-
- }
-
- private InfraActiveRequests buildTestRequest() {
- InfraActiveRequests testRequest= new InfraActiveRequests();
- testRequest.setRequestId("00032ab7-3fb3-42e5-965d-8ea592502017");
- testRequest.setClientRequestId("00032ab7-3fb3-42e5-965d-8ea592502016");
- testRequest.setRequestStatus("COMPLETE");
- testRequest.setStatusMessage("Vf Module has been deleted successfully.");
- testRequest.setProgress((long) 100);
- testRequest.setSource("VID");
- testRequest.setTenantId("6accefef3cb442ff9e644d589fb04107");
- testRequest.setServiceInstanceId("e3b5744d-2ad1-4cdd-8390-c999a38829bc");
- testRequest.setRequestAction("deleteInstance");
- testRequest.setRequestScope("vfModule");
- testRequest.setAction("deleteInstance");
- testRequest.setAicCloudRegion("mtn6");
- testRequest.setLastModifiedBy("BPMN");
- testRequest.setVfModuleId("c7d527b1-7a91-49fd-b97d-1c8c0f4a7992");
- testRequest.setVfModuleModelName("vSAMP10aDEV::base::module-0");
- testRequest.setVnfId("b92f60c8-8de3-46c1-8dc1-e4390ac2b005");
- testRequest.setRequestUrl("http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances");
- testRequest.setVolumeGroupId("volumeGroupId");
- testRequest.setServiceInstanceName("serviceInstanceName");
- testRequest.setConfigurationId("configurationId");
- testRequest.setConfigurationName("configurationName");
- testRequest.setNetworkId("networkId");
- testRequest.setResponseBody("responseBody");
- testRequest.setVfModuleName("vfModuleName");
- testRequest.setVnfOutputs("vnfOutputs");
- return testRequest;
- }
-
- @Test
- public void getByRequestId() throws MsoRequestsDbException {
-
- InfraActiveRequests testRequest = setupTestEntities();
- // Given
- String requestId = "00032ab7-3fb3-42e5-965d-8ea592502017";
-
- // When
- InfraActiveRequests infraRequest = dbAdapter.getInfraRequest(requestId);
- if(infraRequest ==null)
- fail("Null infraRequest");
-
- // Then
- assertThat(infraRequest, sameBeanAs(testRequest).ignoring("requestBody").ignoring("endTime").ignoring("startTime").ignoring("modifyTime"));
- }
-
-
- @Test
- public void getByInvalidRequestId() throws MsoRequestsDbException {
- // Given
- String requestId = "invalidRequestId";
-
- try {
- dbAdapter.getInfraRequest(requestId);
- fail("Expected MsoRequestsDbException to be thrown");
- } catch (Exception e) {
- assertEquals(e.getMessage(),"Error retrieving MSO Infra Requests DB for Request ID invalidRequestId");
- }
- }
-
- @Test
- public void getByClientRequestId() throws MsoRequestsDbException {
- InfraActiveRequests testRequest = setupTestEntities();
- // Given
- String clientRequestId = "00032ab7-3fb3-42e5-965d-8ea592502016";
-
- // When
- InfraActiveRequests infraRequest = dbAdapter.getInfraRequest(clientRequestId);
- if(infraRequest ==null)
- fail("Null infraRequest");
-
- // Then
- assertEquals(clientRequestId, infraRequest.getClientRequestId());
- }
-
-
- @Test
- public void updateInfraRequest() throws MsoRequestsDbException {
- InfraActiveRequests testRequest = setupTestEntities();
- // Given
- String clientRequestId = "00032ab7-3fb3-42e5-965d-8ea592502016";
-
-
- // When
- String lastModifiedBy = "UNIT TEST";
- String statusMessage = "TESTING THE UDPATES";
- String progress = "50";
- String vnfOutputs = "VNF OUTPUTS";
- String networkId = "New NetworkID";
- String vnfId = "NEWVNFID";
- String volumeGroupId = "NewVolumeGroupId";
- String serviceInstanceName = "NewServiceInstanceName";
- String configurationId = "NewConfigurationId";
- String configurationName = "NewConfigurationName";
- String vfModuleName = "VFModuleName";
- RequestStatusType requestStatus = RequestStatusType.COMPLETE ;
- String responseBody = "NewResponseBody";
- String vfModuleId = "NEW VF MODULEID";
- String serviceInstanceId = " new serv ind";
-
-
- testRequest.setVolumeGroupId(volumeGroupId);
- testRequest.setServiceInstanceName(serviceInstanceName);
- testRequest.setConfigurationId(configurationId);
- testRequest.setConfigurationName(configurationName);
- testRequest.setNetworkId(networkId);
- testRequest.setResponseBody(responseBody);
- testRequest.setStatusMessage(statusMessage);
- testRequest.setProgress((long) 50);
- testRequest.setServiceInstanceId(lastModifiedBy);
- testRequest.setLastModifiedBy(lastModifiedBy);
- testRequest.setVfModuleId(vfModuleId);
- testRequest.setVfModuleName(vfModuleName);
- testRequest.setVnfId(vnfId);
- testRequest.setServiceInstanceId(serviceInstanceId);
- testRequest.setVfModuleName(vfModuleName);
- testRequest.setVnfOutputs(vnfOutputs);
-
-
- dbAdapter.updateInfraRequest ( testRequest.getRequestId(),
- lastModifiedBy,
- statusMessage,
- responseBody,
- requestStatus,
- progress,
- vnfOutputs,
- serviceInstanceId,
- networkId,
- vnfId,
- vfModuleId,
- volumeGroupId,
- serviceInstanceName,
- configurationId,
- configurationName,
- vfModuleName);
- InfraActiveRequests infraRequest = dbAdapter.getInfraRequest(clientRequestId);
- // Then
- assertThat(infraRequest, sameBeanAs(testRequest).ignoring("requestBody").ignoring("endTime").ignoring("startTime").ignoring("modifyTime"));
-
-
- }
-
- @Test
- public void UpdateByInvalidRequestId() throws MsoRequestsDbException {
- // Given
- String requestId = "invalidRequestId";
-
- try {
- dbAdapter.updateInfraRequest ( requestId,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null);
- fail("Expected MsoRequestsDbException to be thrown");
- } catch (Exception e) {
- assertEquals(e.getMessage(),"Error retrieving MSO Infra Requests DB for Request ID invalidRequestId");
- }
- }
-
-
- @Test
- public void updateInfraRequestNulls() throws MsoRequestsDbException {
- InfraActiveRequests testRequest = setupTestEntities();
- // Given
- String clientRequestId = "00032ab7-3fb3-42e5-965d-8ea592502016";
-
- // When
- dbAdapter.updateInfraRequest ( testRequest.getRequestId(),
- testRequest.getLastModifiedBy(),
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null);
- InfraActiveRequests infraRequest = dbAdapter.getInfraRequest(clientRequestId);
- // Then
- assertThat(infraRequest, sameBeanAs(testRequest).ignoring("requestBody").ignoring("endTime").ignoring("startTime").ignoring("modifyTime"));
- }
-
- @Test
- public void getSiteStatusNotDisabled() throws MsoRequestsDbException {
- setupTestEntities();
- // Given
- String siteName = "siteName";
-
- // When
- boolean siteDisabled = dbAdapter.getSiteStatus(siteName);
-
- // Then
- assertEquals(siteDisabled, true);
- }
-
- @Test
- public void getSiteStatusDisabled() throws MsoRequestsDbException {
- setupTestEntities();
- // Given
- String siteName = "testSite";
-
- // When
- boolean siteDisabled = dbAdapter.getSiteStatus(siteName);
-
- // Then
- assertEquals(siteDisabled, false);
- }
-
- @Test
- public void updateServiceOperation() throws MsoRequestsDbException{
- String serviceId = "serviceid";
- String operationId = "operationid";
- String serviceName = "servicename";
- String operation = "newOperationType";
- String userId = "NewUserId";
- String result = "NewResult";
- String operationContent = "newOperationContent";
- String progress = "Newprogress";
- String reason = "NewReason";
-
- OperationStatus updatedOperationStatus = new OperationStatus();
-
-
-
- updatedOperationStatus.setServiceId(serviceId);
- updatedOperationStatus.setServiceName(serviceName);
- updatedOperationStatus.setOperationId(operationId);
- updatedOperationStatus.setOperation(operation);
- updatedOperationStatus.setUserId(userId);
- updatedOperationStatus.setResult(result);
- updatedOperationStatus.setProgress(progress);
- updatedOperationStatus.setReason(reason);
- updatedOperationStatus.setOperationContent(operationContent);
-
- dbAdapter.updateServiceOperationStatus(serviceId, operationId, operation, userId,
- result, operationContent, progress, reason);
- OperationStatus dbOpStatus = operationStatusRepository.findOneByServiceIdAndOperationId(serviceId,operationId);
- assertThat(dbOpStatus, sameBeanAs(updatedOperationStatus).ignoring("operateAt").ignoring("finishedAt"));
- }
-
-
- @Test
- public void updateServiceOperation_Not_Found() throws MsoRequestsDbException{
- TestAppender.events.clear();
- String serviceId = "badserviceId";
- String operationId = "operationid";
- String operation = "newOperationType";
- String userId = "NewUserId";
- String result = "NewResult";
- String operationContent = "newOperationContent";
- String progress = "Newprogress";
- String reason = "NewReason";
-
- OperationStatus updatedOperationStatus = new OperationStatus();
-
-
-
- updatedOperationStatus.setServiceId(serviceId);
- updatedOperationStatus.setOperationId(operationId);
- updatedOperationStatus.setOperation(operation);
- updatedOperationStatus.setUserId(userId);
- updatedOperationStatus.setResult(result);
- updatedOperationStatus.setProgress(progress);
- updatedOperationStatus.setReason(reason);
- updatedOperationStatus.setOperationContent(operationContent);
-
- dbAdapter.updateServiceOperationStatus(serviceId, operationId, operation, userId,
- result, operationContent, progress, reason);
- OperationStatus dbOpStatus = operationStatusRepository.findOneByServiceIdAndOperationId(serviceId,operationId);
- assertThat(dbOpStatus, sameBeanAs(updatedOperationStatus).ignoring("operateAt").ignoring("finishedAt"));
- }
-
- @Test
- public void initResourceOperationStatus() throws MsoRequestsDbException{
- String resourceTemplateUUIDs = "template1:template2:template3:";
- String serviceId = "serviceId";
- String operationId = "operationId";
- String operationType = "operationType";
-
- ResourceOperationStatus resource1 = new ResourceOperationStatus();
- resource1.setOperationId(operationId);
- resource1.setServiceId(serviceId);
- resource1.setResourceTemplateUUID("template1");
- resource1.setOperType(operationType);
- resource1.setStatus(RequestsDbConstant.Status.PROCESSING);
- resource1.setStatusDescription("Waiting for start");
-
- ResourceOperationStatus resource2 = new ResourceOperationStatus();
- resource2.setOperationId(operationId);
- resource2.setServiceId(serviceId);
- resource2.setResourceTemplateUUID("template2");
- resource2.setOperType(operationType);
- resource2.setStatus(RequestsDbConstant.Status.PROCESSING);
- resource2.setStatusDescription("Waiting for start");
-
- ResourceOperationStatus resource3 = new ResourceOperationStatus();
- resource3.setOperationId(operationId);
- resource3.setServiceId(serviceId);
- resource3.setResourceTemplateUUID("template3");
- resource3.setOperType(operationType);
- resource3.setStatus(RequestsDbConstant.Status.PROCESSING);
- resource3.setStatusDescription("Waiting for start");
-
- List<ResourceOperationStatus> expectedResult = new ArrayList<ResourceOperationStatus>();
- expectedResult.add(resource1);
- expectedResult.add(resource2);
- expectedResult.add(resource3);
-
- dbAdapter.initResourceOperationStatus(serviceId, operationId, operationType,resourceTemplateUUIDs);
- List<ResourceOperationStatus> testList = resourceOperationStatusRepo.findByServiceIdAndOperationId(serviceId,operationId);
- assertThat(testList, sameBeanAs(expectedResult));
- }
-
- @Test
- public void getResourceOperationStatus() throws MsoRequestsDbException{
- String resourceTemplateUUIDs = "template1";
- String serviceId = "serviceId";
- String operationId = "operationId";
- String operationType = "operationType";
-
- ResourceOperationStatus resource1 = new ResourceOperationStatus();
- resource1.setOperationId(operationId);
- resource1.setServiceId(serviceId);
- resource1.setResourceTemplateUUID("template1");
- resource1.setOperType(operationType);
- resource1.setStatus(RequestsDbConstant.Status.PROCESSING);
- resource1.setStatusDescription("Waiting for start");
-
-
- dbAdapter.initResourceOperationStatus(serviceId, operationId, operationType,resourceTemplateUUIDs);
-
- ResourceOperationStatus actualResource = dbAdapter.getResourceOperationStatus(serviceId, operationId,"template1");
- assertThat(actualResource, sameBeanAs(resource1));
- }
-
- @Test
- public void updateResourceOperationStatus() throws MsoRequestsDbException{
- TestAppender.events.clear();
- String resourceTemplateUUID = "template1";
- String serviceId = "serviceId";
- String operationId = "operationId";
- String operationType = "operationType";
- String resourceInstanceID = "resourceInstanceID";
- String jobId = "jobId";
- String status = RequestsDbConstant.Status.FINISHED;
- String progress = "50";
- String errorCode = "errorCode";
- String statusDescription = "statusDescription";
-
-
- ResourceOperationStatus expectedResource = new ResourceOperationStatus();
- expectedResource.setOperationId(operationId);
- expectedResource.setServiceId(serviceId);
- expectedResource.setResourceTemplateUUID(resourceTemplateUUID);
- expectedResource.setOperType(operationType);
- expectedResource.setJobId(jobId);
- expectedResource.setErrorCode(errorCode);
- expectedResource.setStatus(RequestsDbConstant.Status.FINISHED);
- expectedResource.setStatusDescription(statusDescription);
- expectedResource.setProgress(progress);
- expectedResource.setResourceInstanceID(resourceInstanceID);
-
-
- dbAdapter.updateResourceOperationStatus(serviceId, operationId, resourceTemplateUUID,
- operationType, resourceInstanceID, jobId, status, progress,
- errorCode, statusDescription);
-
- ResourceOperationStatus actualResource = dbAdapter.getResourceOperationStatus(serviceId, operationId,"template1");
- assertThat(actualResource, sameBeanAs(expectedResource));
-
- for(ILoggingEvent logEvent : TestAppender.events)
- if(logEvent.getLoggerName().equals("org.onap.so.logging.cxf.interceptor.SOAPLoggingInInterceptor") &&
- logEvent.getMarker().getName().equals("ENTRY")
- ){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+ dbAdapter.updateInfraRequest(testRequest.getRequestId(), testRequest.getLastModifiedBy(),
+ testRequest.getStatusMessage(), testRequest.getResponseBody(),
+ RequestStatusType.valueOf(testRequest.getRequestStatus()), testRequest.getProgress().toString(),
+ testRequest.getVnfOutputs(), testRequest.getServiceInstanceId(), testRequest.getNetworkId(),
+ testRequest.getVnfId(), testRequest.getVfModuleId(), testRequest.getVolumeGroupId(),
+ testRequest.getServiceInstanceName(), testRequest.getConfigurationId(),
+ testRequest.getConfigurationName(), testRequest.getVfModuleName());
+
+
+ }
+
+ private InfraActiveRequests buildTestRequest() {
+ InfraActiveRequests testRequest = new InfraActiveRequests();
+ testRequest.setRequestId("00032ab7-3fb3-42e5-965d-8ea592502017");
+ testRequest.setClientRequestId("00032ab7-3fb3-42e5-965d-8ea592502016");
+ testRequest.setRequestStatus("COMPLETE");
+ testRequest.setStatusMessage("Vf Module has been deleted successfully.");
+ testRequest.setProgress((long) 100);
+ testRequest.setSource("VID");
+ testRequest.setTenantId("6accefef3cb442ff9e644d589fb04107");
+ testRequest.setServiceInstanceId("e3b5744d-2ad1-4cdd-8390-c999a38829bc");
+ testRequest.setRequestAction("deleteInstance");
+ testRequest.setRequestScope("vfModule");
+ testRequest.setAction("deleteInstance");
+ testRequest.setAicCloudRegion("mtn6");
+ testRequest.setLastModifiedBy("BPMN");
+ testRequest.setVfModuleId("c7d527b1-7a91-49fd-b97d-1c8c0f4a7992");
+ testRequest.setVfModuleModelName("vSAMP10aDEV::base::module-0");
+ testRequest.setVnfId("b92f60c8-8de3-46c1-8dc1-e4390ac2b005");
+ testRequest.setRequestUrl("http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances");
+ testRequest.setVolumeGroupId("volumeGroupId");
+ testRequest.setServiceInstanceName("serviceInstanceName");
+ testRequest.setConfigurationId("configurationId");
+ testRequest.setConfigurationName("configurationName");
+ testRequest.setNetworkId("networkId");
+ testRequest.setResponseBody("responseBody");
+ testRequest.setVfModuleName("vfModuleName");
+ testRequest.setVnfOutputs("vnfOutputs");
+ return testRequest;
+ }
+
+ @Test
+ public void getByRequestId() throws MsoRequestsDbException {
+
+ InfraActiveRequests testRequest = setupTestEntities();
+ // Given
+ String requestId = "00032ab7-3fb3-42e5-965d-8ea592502017";
+
+ // When
+ InfraActiveRequests infraRequest = dbAdapter.getInfraRequest(requestId);
+ if (infraRequest == null)
+ fail("Null infraRequest");
+
+ // Then
+ assertThat(infraRequest, sameBeanAs(testRequest).ignoring("requestBody").ignoring("endTime")
+ .ignoring("startTime").ignoring("modifyTime"));
+ }
+
+
+ @Test
+ public void getByInvalidRequestId() throws MsoRequestsDbException {
+ // Given
+ String requestId = "invalidRequestId";
+
+ try {
+ dbAdapter.getInfraRequest(requestId);
+ fail("Expected MsoRequestsDbException to be thrown");
+ } catch (Exception e) {
+ assertEquals(e.getMessage(), "Error retrieving MSO Infra Requests DB for Request ID invalidRequestId");
+ }
+ }
+
+ @Test
+ public void getByClientRequestId() throws MsoRequestsDbException {
+ InfraActiveRequests testRequest = setupTestEntities();
+ // Given
+ String clientRequestId = "00032ab7-3fb3-42e5-965d-8ea592502016";
+
+ // When
+ InfraActiveRequests infraRequest = dbAdapter.getInfraRequest(clientRequestId);
+ if (infraRequest == null)
+ fail("Null infraRequest");
+
+ // Then
+ assertEquals(clientRequestId, infraRequest.getClientRequestId());
+ }
+
+
+ @Test
+ public void updateInfraRequest() throws MsoRequestsDbException {
+ InfraActiveRequests testRequest = setupTestEntities();
+ // Given
+ String clientRequestId = "00032ab7-3fb3-42e5-965d-8ea592502016";
+
+
+ // When
+ String lastModifiedBy = "UNIT TEST";
+ String statusMessage = "TESTING THE UDPATES";
+ String progress = "50";
+ String vnfOutputs = "VNF OUTPUTS";
+ String networkId = "New NetworkID";
+ String vnfId = "NEWVNFID";
+ String volumeGroupId = "NewVolumeGroupId";
+ String serviceInstanceName = "NewServiceInstanceName";
+ String configurationId = "NewConfigurationId";
+ String configurationName = "NewConfigurationName";
+ String vfModuleName = "VFModuleName";
+ RequestStatusType requestStatus = RequestStatusType.COMPLETE;
+ String responseBody = "NewResponseBody";
+ String vfModuleId = "NEW VF MODULEID";
+ String serviceInstanceId = " new serv ind";
+
+
+ testRequest.setVolumeGroupId(volumeGroupId);
+ testRequest.setServiceInstanceName(serviceInstanceName);
+ testRequest.setConfigurationId(configurationId);
+ testRequest.setConfigurationName(configurationName);
+ testRequest.setNetworkId(networkId);
+ testRequest.setResponseBody(responseBody);
+ testRequest.setStatusMessage(statusMessage);
+ testRequest.setProgress((long) 50);
+ testRequest.setServiceInstanceId(lastModifiedBy);
+ testRequest.setLastModifiedBy(lastModifiedBy);
+ testRequest.setVfModuleId(vfModuleId);
+ testRequest.setVfModuleName(vfModuleName);
+ testRequest.setVnfId(vnfId);
+ testRequest.setServiceInstanceId(serviceInstanceId);
+ testRequest.setVfModuleName(vfModuleName);
+ testRequest.setVnfOutputs(vnfOutputs);
+
+
+ dbAdapter.updateInfraRequest(testRequest.getRequestId(), lastModifiedBy, statusMessage, responseBody,
+ requestStatus, progress, vnfOutputs, serviceInstanceId, networkId, vnfId, vfModuleId, volumeGroupId,
+ serviceInstanceName, configurationId, configurationName, vfModuleName);
+ InfraActiveRequests infraRequest = dbAdapter.getInfraRequest(clientRequestId);
+ // Then
+ assertThat(infraRequest, sameBeanAs(testRequest).ignoring("requestBody").ignoring("endTime")
+ .ignoring("startTime").ignoring("modifyTime"));
+
+
+ }
+
+ @Test
+ public void UpdateByInvalidRequestId() throws MsoRequestsDbException {
+ // Given
+ String requestId = "invalidRequestId";
+
+ try {
+ dbAdapter.updateInfraRequest(requestId, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null);
+ fail("Expected MsoRequestsDbException to be thrown");
+ } catch (Exception e) {
+ assertEquals(e.getMessage(), "Error retrieving MSO Infra Requests DB for Request ID invalidRequestId");
+ }
+ }
+
+
+ @Test
+ public void updateInfraRequestNulls() throws MsoRequestsDbException {
+ InfraActiveRequests testRequest = setupTestEntities();
+ // Given
+ String clientRequestId = "00032ab7-3fb3-42e5-965d-8ea592502016";
+
+ // When
+ dbAdapter.updateInfraRequest(testRequest.getRequestId(), testRequest.getLastModifiedBy(), null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null);
+ InfraActiveRequests infraRequest = dbAdapter.getInfraRequest(clientRequestId);
+ // Then
+ assertThat(infraRequest, sameBeanAs(testRequest).ignoring("requestBody").ignoring("endTime")
+ .ignoring("startTime").ignoring("modifyTime"));
+ }
+
+ @Test
+ public void getSiteStatusNotDisabled() throws MsoRequestsDbException {
+ setupTestEntities();
+ // Given
+ String siteName = "siteName";
+
+ // When
+ boolean siteDisabled = dbAdapter.getSiteStatus(siteName);
+
+ // Then
+ assertEquals(siteDisabled, true);
+ }
+
+ @Test
+ public void getSiteStatusDisabled() throws MsoRequestsDbException {
+ setupTestEntities();
+ // Given
+ String siteName = "testSite";
+
+ // When
+ boolean siteDisabled = dbAdapter.getSiteStatus(siteName);
+
+ // Then
+ assertEquals(siteDisabled, false);
+ }
+
+ @Test
+ public void updateServiceOperation() throws MsoRequestsDbException {
+ String serviceId = "serviceid";
+ String operationId = "operationid";
+ String serviceName = "servicename";
+ String operation = "newOperationType";
+ String userId = "NewUserId";
+ String result = "NewResult";
+ String operationContent = "newOperationContent";
+ String progress = "Newprogress";
+ String reason = "NewReason";
+
+ OperationStatus updatedOperationStatus = new OperationStatus();
+
+
+
+ updatedOperationStatus.setServiceId(serviceId);
+ updatedOperationStatus.setServiceName(serviceName);
+ updatedOperationStatus.setOperationId(operationId);
+ updatedOperationStatus.setOperation(operation);
+ updatedOperationStatus.setUserId(userId);
+ updatedOperationStatus.setResult(result);
+ updatedOperationStatus.setProgress(progress);
+ updatedOperationStatus.setReason(reason);
+ updatedOperationStatus.setOperationContent(operationContent);
+
+ dbAdapter.updateServiceOperationStatus(serviceId, operationId, operation, userId, result, operationContent,
+ progress, reason);
+ OperationStatus dbOpStatus = operationStatusRepository.findOneByServiceIdAndOperationId(serviceId, operationId);
+ assertThat(dbOpStatus, sameBeanAs(updatedOperationStatus).ignoring("operateAt").ignoring("finishedAt"));
+ }
+
+
+ @Test
+ public void updateServiceOperation_Not_Found() throws MsoRequestsDbException {
+ TestAppender.events.clear();
+ String serviceId = "badserviceId";
+ String operationId = "operationid";
+ String operation = "newOperationType";
+ String userId = "NewUserId";
+ String result = "NewResult";
+ String operationContent = "newOperationContent";
+ String progress = "Newprogress";
+ String reason = "NewReason";
+
+ OperationStatus updatedOperationStatus = new OperationStatus();
+
+
+
+ updatedOperationStatus.setServiceId(serviceId);
+ updatedOperationStatus.setOperationId(operationId);
+ updatedOperationStatus.setOperation(operation);
+ updatedOperationStatus.setUserId(userId);
+ updatedOperationStatus.setResult(result);
+ updatedOperationStatus.setProgress(progress);
+ updatedOperationStatus.setReason(reason);
+ updatedOperationStatus.setOperationContent(operationContent);
+
+ dbAdapter.updateServiceOperationStatus(serviceId, operationId, operation, userId, result, operationContent,
+ progress, reason);
+ OperationStatus dbOpStatus = operationStatusRepository.findOneByServiceIdAndOperationId(serviceId, operationId);
+ assertThat(dbOpStatus, sameBeanAs(updatedOperationStatus).ignoring("operateAt").ignoring("finishedAt"));
+ }
+
+ @Test
+ public void initResourceOperationStatus() throws MsoRequestsDbException {
+ String resourceTemplateUUIDs = "template1:template2:template3:";
+ String serviceId = "serviceId";
+ String operationId = "operationId";
+ String operationType = "operationType";
+
+ ResourceOperationStatus resource1 = new ResourceOperationStatus();
+ resource1.setOperationId(operationId);
+ resource1.setServiceId(serviceId);
+ resource1.setResourceTemplateUUID("template1");
+ resource1.setOperType(operationType);
+ resource1.setStatus(RequestsDbConstant.Status.PROCESSING);
+ resource1.setStatusDescription("Waiting for start");
+
+ ResourceOperationStatus resource2 = new ResourceOperationStatus();
+ resource2.setOperationId(operationId);
+ resource2.setServiceId(serviceId);
+ resource2.setResourceTemplateUUID("template2");
+ resource2.setOperType(operationType);
+ resource2.setStatus(RequestsDbConstant.Status.PROCESSING);
+ resource2.setStatusDescription("Waiting for start");
+
+ ResourceOperationStatus resource3 = new ResourceOperationStatus();
+ resource3.setOperationId(operationId);
+ resource3.setServiceId(serviceId);
+ resource3.setResourceTemplateUUID("template3");
+ resource3.setOperType(operationType);
+ resource3.setStatus(RequestsDbConstant.Status.PROCESSING);
+ resource3.setStatusDescription("Waiting for start");
+
+ List<ResourceOperationStatus> expectedResult = new ArrayList<ResourceOperationStatus>();
+ expectedResult.add(resource1);
+ expectedResult.add(resource2);
+ expectedResult.add(resource3);
+
+ dbAdapter.initResourceOperationStatus(serviceId, operationId, operationType, resourceTemplateUUIDs);
+ List<ResourceOperationStatus> testList =
+ resourceOperationStatusRepo.findByServiceIdAndOperationId(serviceId, operationId);
+ assertThat(testList, sameBeanAs(expectedResult));
+ }
+
+ @Test
+ public void getResourceOperationStatus() throws MsoRequestsDbException {
+ String resourceTemplateUUIDs = "template1";
+ String serviceId = "serviceId";
+ String operationId = "operationId";
+ String operationType = "operationType";
+
+ ResourceOperationStatus resource1 = new ResourceOperationStatus();
+ resource1.setOperationId(operationId);
+ resource1.setServiceId(serviceId);
+ resource1.setResourceTemplateUUID("template1");
+ resource1.setOperType(operationType);
+ resource1.setStatus(RequestsDbConstant.Status.PROCESSING);
+ resource1.setStatusDescription("Waiting for start");
+
+
+ dbAdapter.initResourceOperationStatus(serviceId, operationId, operationType, resourceTemplateUUIDs);
+
+ ResourceOperationStatus actualResource =
+ dbAdapter.getResourceOperationStatus(serviceId, operationId, "template1");
+ assertThat(actualResource, sameBeanAs(resource1));
+ }
+
+ @Test
+ public void updateResourceOperationStatus() throws MsoRequestsDbException {
+ TestAppender.events.clear();
+ String resourceTemplateUUID = "template1";
+ String serviceId = "serviceId";
+ String operationId = "operationId";
+ String operationType = "operationType";
+ String resourceInstanceID = "resourceInstanceID";
+ String jobId = "jobId";
+ String status = RequestsDbConstant.Status.FINISHED;
+ String progress = "50";
+ String errorCode = "errorCode";
+ String statusDescription = "statusDescription";
+
+
+ ResourceOperationStatus expectedResource = new ResourceOperationStatus();
+ expectedResource.setOperationId(operationId);
+ expectedResource.setServiceId(serviceId);
+ expectedResource.setResourceTemplateUUID(resourceTemplateUUID);
+ expectedResource.setOperType(operationType);
+ expectedResource.setJobId(jobId);
+ expectedResource.setErrorCode(errorCode);
+ expectedResource.setStatus(RequestsDbConstant.Status.FINISHED);
+ expectedResource.setStatusDescription(statusDescription);
+ expectedResource.setProgress(progress);
+ expectedResource.setResourceInstanceID(resourceInstanceID);
+
+
+ dbAdapter.updateResourceOperationStatus(serviceId, operationId, resourceTemplateUUID, operationType,
+ resourceInstanceID, jobId, status, progress, errorCode, statusDescription);
+
+ ResourceOperationStatus actualResource =
+ dbAdapter.getResourceOperationStatus(serviceId, operationId, "template1");
+ assertThat(actualResource, sameBeanAs(expectedResource));
+
+ for (ILoggingEvent logEvent : TestAppender.events)
+ if (logEvent.getLoggerName().equals("org.onap.so.logging.cxf.interceptor.SOAPLoggingInInterceptor")
+ && logEvent.getMarker().getName().equals("ENTRY")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.INSTANCE_UUID));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID));
- assertEquals("",mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME));
- assertEquals("/services/RequestsDbAdapter",mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME));
- assertEquals("INPROGRESS",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
- }else if(logEvent.getLoggerName().equals("org.onap.so.logging.cxf.interceptor.SOAPLoggingOutInterceptor") &&
- logEvent.getMarker().getName().equals("EXIT")){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+ assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME));
+ assertEquals("/services/RequestsDbAdapter", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME));
+ assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ } else if (logEvent.getLoggerName().equals("org.onap.so.logging.cxf.interceptor.SOAPLoggingOutInterceptor")
+ && logEvent.getMarker().getName().equals("EXIT")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID));
- assertEquals(null,mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE));
- assertEquals("",mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME));
- assertEquals("/services/RequestsDbAdapter",mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME));
- assertEquals("COMPLETED",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ assertEquals(null, mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE));
+ assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME));
+ assertEquals("/services/RequestsDbAdapter", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME));
+ assertEquals("COMPLETED", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
}
- }
+ }
}
diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/application/EmbeddedMariaDbConfig.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/application/EmbeddedMariaDbConfig.java
index c1848e3aad..ad405984e3 100644
--- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/application/EmbeddedMariaDbConfig.java
+++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/application/EmbeddedMariaDbConfig.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.adapters.requestsdb.application;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
-
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
@@ -37,17 +37,14 @@ import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
-
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration
@Profile({"test"})
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager",
- basePackages = { "org.onap.so.db.request.data.repository"}
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory",
+ transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"})
public class EmbeddedMariaDbConfig {
@Bean
@@ -56,47 +53,34 @@ public class EmbeddedMariaDbConfig {
}
@Primary
- @Bean(name = "requestDataSource")
- @ConfigurationProperties(prefix = "spring.datasource")
+ @Bean(name = "requestDataSource")
+ @ConfigurationProperties(prefix = "spring.datasource")
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
- @Primary
- @Bean(name = "requestEntityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("requestDataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.request.beans")
- .persistenceUnit("requestDB")
- .build();
- }
+ @Primary
+ @Bean(name = "requestEntityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("requestDataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB")
+ .build();
+ }
- @Primary
- @Bean(name = "requestTransactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("requestEntityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
+ @Primary
+ @Bean(name = "requestTransactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
}
diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/application/TestAppender.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/application/TestAppender.java
index 0da1fd7565..5607c12b83 100644
--- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/application/TestAppender.java
+++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/application/TestAppender.java
@@ -27,11 +27,11 @@ import ch.qos.logback.core.AppenderBase;
-public class TestAppender extends AppenderBase<ILoggingEvent> {
+public class TestAppender extends AppenderBase<ILoggingEvent> {
public static List<ILoggingEvent> events = new ArrayList<>();
-
- @Override
- public void append(ILoggingEvent loggingEvent) {
- events.add(loggingEvent);
- }
+
+ @Override
+ public void append(ILoggingEvent loggingEvent) {
+ events.add(loggingEvent);
+ }
}
diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestDbClientPortChanger.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestDbClientPortChanger.java
index bd15396c03..1ccd44d384 100644
--- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestDbClientPortChanger.java
+++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestDbClientPortChanger.java
@@ -24,6 +24,7 @@ package org.onap.so.adapters.requestsdb.client;
import org.onap.so.db.request.client.RequestsDbClient;
import org.springframework.stereotype.Component;
import java.net.URI;
+
@Component
public class RequestDbClientPortChanger extends RequestsDbClient {
private int port;
diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java
index 467cb1ed23..3b737c6768 100644
--- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java
+++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java
@@ -40,7 +40,6 @@ import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
-
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -86,13 +85,14 @@ public class RequestsDbClientTest extends RequestsAdapterBase {
infraActiveRequests.setRequestStatus("IN_PROGRESS");
infraActiveRequests.setAction("create");
infraActiveRequests.setRequestAction("someaction");
- infraActiveRequests.setRequestUrl("http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances");
+ infraActiveRequests
+ .setRequestUrl("http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances");
requestsDbClient.save(infraActiveRequests);
}
- private void verifyOperationStatus(OperationStatus request,OperationStatus response){
+ private void verifyOperationStatus(OperationStatus request, OperationStatus response) {
assertThat(request, sameBeanAs(response).ignoring("operateAt").ignoring("finishedAt"));
- }
+ }
private void verifyInfraActiveRequests(InfraActiveRequests infraActiveRequestsResponse) {
@@ -116,14 +116,16 @@ public class RequestsDbClientTest extends RequestsAdapterBase {
@Test
public void checkVnfIdStatusTest() {
- InfraActiveRequests infraActiveRequestsResponse = requestsDbClient.checkVnfIdStatus(infraActiveRequests.getOperationalEnvId());
+ InfraActiveRequests infraActiveRequestsResponse =
+ requestsDbClient.checkVnfIdStatus(infraActiveRequests.getOperationalEnvId());
verifyInfraActiveRequests(infraActiveRequestsResponse);
assertNull(requestsDbClient.checkVnfIdStatus(UUID.randomUUID().toString()));
}
@Test
public void checkInstanceNameDuplicateTest() {
- InfraActiveRequests infraActiveRequestsResponse = requestsDbClient.checkInstanceNameDuplicate(null,infraActiveRequests.getOperationalEnvName(),infraActiveRequests.getRequestScope());
+ InfraActiveRequests infraActiveRequestsResponse = requestsDbClient.checkInstanceNameDuplicate(null,
+ infraActiveRequests.getOperationalEnvName(), infraActiveRequests.getRequestScope());
verifyInfraActiveRequests(infraActiveRequestsResponse);
}
@@ -133,7 +135,8 @@ public class RequestsDbClientTest extends RequestsAdapterBase {
Map<String, String> requestMap = new HashMap<>();
requestMap.put("operationalEnvironmentId", infraActiveRequests.getOperationalEnvId());
- InfraActiveRequests infraActiveRequestsResponse = requestsDbClient.checkInstanceNameDuplicate((HashMap<String, String>)requestMap,null,infraActiveRequests.getRequestScope());
+ InfraActiveRequests infraActiveRequestsResponse = requestsDbClient.checkInstanceNameDuplicate(
+ (HashMap<String, String>) requestMap, null, infraActiveRequests.getRequestScope());
verifyInfraActiveRequests(infraActiveRequestsResponse);
}
@@ -165,27 +168,30 @@ public class RequestsDbClientTest extends RequestsAdapterBase {
}
@Test
- public void getInfraActiveRequestbyRequestIdTest(){
- InfraActiveRequests infraActiveRequestsResponse = requestsDbClient.getInfraActiveRequestbyRequestId(infraActiveRequests.getRequestId());
- verifyInfraActiveRequests(infraActiveRequestsResponse);
- infraActiveRequestsResponse = requestsDbClient.getInfraActiveRequestbyRequestId(infraActiveRequests.getRequestId());
-
+ public void getInfraActiveRequestbyRequestIdTest() {
+ InfraActiveRequests infraActiveRequestsResponse =
+ requestsDbClient.getInfraActiveRequestbyRequestId(infraActiveRequests.getRequestId());
+ verifyInfraActiveRequests(infraActiveRequestsResponse);
+ infraActiveRequestsResponse =
+ requestsDbClient.getInfraActiveRequestbyRequestId(infraActiveRequests.getRequestId());
+
assertNull(requestsDbClient.getInfraActiveRequestbyRequestId(UUID.randomUUID().toString()));
}
-
+
@Test
- public void getInfraActiveRequestbyRequestIdWhereRequestUrlNullTest(){
+ public void getInfraActiveRequestbyRequestIdWhereRequestUrlNullTest() {
// requestUrl setup to null and save
- infraActiveRequests.setRequestUrl(null);
+ infraActiveRequests.setRequestUrl(null);
requestsDbClient.save(infraActiveRequests);
- InfraActiveRequests infraActiveRequestsResponse = requestsDbClient.getInfraActiveRequestbyRequestId(infraActiveRequests.getRequestId());
+ InfraActiveRequests infraActiveRequestsResponse =
+ requestsDbClient.getInfraActiveRequestbyRequestId(infraActiveRequests.getRequestId());
verifyInfraActiveRequests(infraActiveRequestsResponse);
assertNull(infraActiveRequestsResponse.getRequestUrl());
}
-
+
@Test
- public void getOneByServiceIdAndOperationIdTest(){
+ public void getOneByServiceIdAndOperationIdTest() {
OperationStatus operationStatus = new OperationStatus();
operationStatus.setProgress("IN_PROGRESS");
operationStatus.setResult("FAILED");
@@ -198,51 +204,59 @@ public class RequestsDbClientTest extends RequestsAdapterBase {
operationStatus.setServiceName("test-service");
requestsDbClient.save(operationStatus);
- OperationStatus operationStatusResponse = requestsDbClient.getOneByServiceIdAndOperationId(operationStatus.getServiceId(),operationStatus.getOperationId());
+ OperationStatus operationStatusResponse = requestsDbClient
+ .getOneByServiceIdAndOperationId(operationStatus.getServiceId(), operationStatus.getOperationId());
- verifyOperationStatus(operationStatus,operationStatusResponse);
+ verifyOperationStatus(operationStatus, operationStatusResponse);
- assertNull(requestsDbClient.getOneByServiceIdAndOperationId(UUID.randomUUID().toString(),operationStatus.getOperationId()));
+ assertNull(requestsDbClient.getOneByServiceIdAndOperationId(UUID.randomUUID().toString(),
+ operationStatus.getOperationId()));
}
@Test
- public void getRequestProcessingDataBySoRequestIdTest(){
- List<RequestProcessingData> requestProcessingDataList = requestsDbClient
- .getRequestProcessingDataBySoRequestId("00032ab7-na18-42e5-965d-8ea592502018");
+ public void getRequestProcessingDataBySoRequestIdTest() {
+ List<RequestProcessingData> requestProcessingDataList =
+ requestsDbClient.getRequestProcessingDataBySoRequestId("00032ab7-na18-42e5-965d-8ea592502018");
assertNotNull(requestProcessingDataList);
assertFalse(requestProcessingDataList.isEmpty());
- assertEquals(2,requestProcessingDataList.size());
+ assertEquals(2, requestProcessingDataList.size());
}
@Test
- public void findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestIdTest(){
- OperationalEnvServiceModelStatus operationalEnvServiceModelStatus =requestsDbClient.findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId("1234","TEST1234", "00032ab7-3fb3-42e5-965d-8ea592502017");
+ public void findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestIdTest() {
+ OperationalEnvServiceModelStatus operationalEnvServiceModelStatus =
+ requestsDbClient.findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId("1234", "TEST1234",
+ "00032ab7-3fb3-42e5-965d-8ea592502017");
assertNotNull(operationalEnvServiceModelStatus);
- assertEquals("1234",operationalEnvServiceModelStatus.getOperationalEnvId());
- assertEquals("TEST1234",operationalEnvServiceModelStatus.getServiceModelVersionId());
-
- OperationalEnvServiceModelStatus operationalEnvServiceModelStatus1 =requestsDbClient.findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId("1234","TEST1235", "00032ab7-3fb3-42e5-965d-8ea592502018");
+ assertEquals("1234", operationalEnvServiceModelStatus.getOperationalEnvId());
+ assertEquals("TEST1234", operationalEnvServiceModelStatus.getServiceModelVersionId());
+
+ OperationalEnvServiceModelStatus operationalEnvServiceModelStatus1 =
+ requestsDbClient.findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId("1234", "TEST1235",
+ "00032ab7-3fb3-42e5-965d-8ea592502018");
assertNotNull(operationalEnvServiceModelStatus1);
- assertEquals("00032ab7-3fb3-42e5-965d-8ea592502018",operationalEnvServiceModelStatus1.getRequestId());
- assertEquals("1234",operationalEnvServiceModelStatus1.getOperationalEnvId());
- assertEquals("TEST1235",operationalEnvServiceModelStatus1.getServiceModelVersionId());
+ assertEquals("00032ab7-3fb3-42e5-965d-8ea592502018", operationalEnvServiceModelStatus1.getRequestId());
+ assertEquals("1234", operationalEnvServiceModelStatus1.getOperationalEnvId());
+ assertEquals("TEST1235", operationalEnvServiceModelStatus1.getServiceModelVersionId());
}
@Test
- public void getAllByOperationalEnvIdAndRequestId(){
- List<OperationalEnvServiceModelStatus> operationalEnvServiceModelStatuses =requestsDbClient.getAllByOperationalEnvIdAndRequestId("1234","00032ab7-3fb3-42e5-965d-8ea592502017");
+ public void getAllByOperationalEnvIdAndRequestId() {
+ List<OperationalEnvServiceModelStatus> operationalEnvServiceModelStatuses =
+ requestsDbClient.getAllByOperationalEnvIdAndRequestId("1234", "00032ab7-3fb3-42e5-965d-8ea592502017");
assertNotNull(operationalEnvServiceModelStatuses);
assertFalse(operationalEnvServiceModelStatuses.isEmpty());
- assertEquals(2,operationalEnvServiceModelStatuses.size());
+ assertEquals(2, operationalEnvServiceModelStatuses.size());
}
@Test
- public void getDistributionStatusByIdTest(){
- OperationalEnvDistributionStatus operationalEnvDistributionStatus =requestsDbClient.getDistributionStatusById("111");
+ public void getDistributionStatusByIdTest() {
+ OperationalEnvDistributionStatus operationalEnvDistributionStatus =
+ requestsDbClient.getDistributionStatusById("111");
assertNotNull(operationalEnvDistributionStatus);
- assertEquals("111",operationalEnvDistributionStatus.getDistributionId());
- assertEquals("ERROR",operationalEnvDistributionStatus.getDistributionIdErrorReason());
- assertEquals("00032ab7-3fb3-42e5-965d-8ea592502017",operationalEnvDistributionStatus.getRequestId());
+ assertEquals("111", operationalEnvDistributionStatus.getDistributionId());
+ assertEquals("ERROR", operationalEnvDistributionStatus.getDistributionIdErrorReason());
+ assertEquals("00032ab7-3fb3-42e5-965d-8ea592502017", operationalEnvDistributionStatus.getRequestId());
}
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/CXFConfiguration.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/CXFConfiguration.java
index 2c84ed4fd0..6149f7ed25 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/CXFConfiguration.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/CXFConfiguration.java
@@ -21,9 +21,7 @@
package org.onap.so.adapters.sdnc;
import java.util.Arrays;
-
import javax.xml.ws.Endpoint;
-
import org.apache.cxf.Bus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.feature.LoggingFeature;
@@ -39,7 +37,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
@@ -47,24 +44,24 @@ import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
@Configuration("CXFConfiguration")
public class CXFConfiguration {
-
- JAXRSServerFactoryBean endpoint;
-
+
+ JAXRSServerFactoryBean endpoint;
+
@Autowired
private Bus bus;
-
- @Autowired
- private JaxRsFilterLogging jaxRsFilterLogging;
-
- @Autowired
- private SDNCAdapterPortType sdncAdapterPortImpl;
-
- @Autowired
- private SNIROResponse sniroResponse;
-
- @Autowired
- private ObjectMapper mapper;
-
+
+ @Autowired
+ private JaxRsFilterLogging jaxRsFilterLogging;
+
+ @Autowired
+ private SDNCAdapterPortType sdncAdapterPortImpl;
+
+ @Autowired
+ private SNIROResponse sniroResponse;
+
+ @Autowired
+ private ObjectMapper mapper;
+
@Bean
public Server rsServer() {
endpoint = new JAXRSServerFactoryBean();
@@ -73,7 +70,7 @@ public class CXFConfiguration {
endpoint.setServiceBeans(Arrays.<Object>asList(sniroResponse));
endpoint.setAddress("/rest");
endpoint.setFeatures(Arrays.asList(createSwaggerFeature(), new LoggingFeature()));
- endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(mapper),jaxRsFilterLogging));
+ endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(mapper), jaxRsFilterLogging));
return endpoint.create();
}
@@ -95,8 +92,8 @@ public class CXFConfiguration {
@Bean
public Swagger2Feature createSwaggerFeature() {
- Swagger2Feature swagger2Feature= new Swagger2Feature();
- swagger2Feature.setBasePath("/services/rest");
+ Swagger2Feature swagger2Feature = new Swagger2Feature();
+ swagger2Feature.setBasePath("/services/rest");
swagger2Feature.setPrettyPrint(true);
swagger2Feature.setTitle("SO Orchestration Application");
swagger2Feature.setContact("The ONAP SO team");
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/ObjectFactory.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/ObjectFactory.java
index eab7d5bf6f..4a1349bfd8 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/ObjectFactory.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/ObjectFactory.java
@@ -25,17 +25,13 @@ import javax.xml.bind.annotation.XmlRegistry;
/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the org.onap.so.adapters.sdnc package.
- * <p>An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
- * provided in this class.
+ * This object contains factory methods for each Java content interface and Java element interface generated in the
+ * org.onap.so.adapters.sdnc package.
+ * <p>
+ * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content.
+ * The Java representation of XML content can consist of schema derived interfaces and classes representing the binding
+ * of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in
+ * this class.
*
*/
@XmlRegistry
@@ -43,7 +39,8 @@ public class ObjectFactory {
/**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.so.adapters.sdnc
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
+ * org.onap.so.adapters.sdnc
*
*/
public ObjectFactory() {
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/RequestHeader.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/RequestHeader.java
index 1f1b85f34b..2b255b36f6 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/RequestHeader.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/RequestHeader.java
@@ -29,9 +29,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -51,16 +53,9 @@ import javax.xml.bind.annotation.XmlType;
*
*
*/
-//BPEL to SDNCAdapter request header
+// BPEL to SDNCAdapter request header
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "requestId",
- "svcInstanceId",
- "svcAction",
- "svcOperation",
- "callbackUrl",
- "msoAction"
-})
+@XmlType(name = "", propOrder = {"requestId", "svcInstanceId", "svcAction", "svcOperation", "callbackUrl", "msoAction"})
@XmlRootElement(name = "RequestHeader")
public class RequestHeader {
@@ -80,9 +75,7 @@ public class RequestHeader {
/**
* Gets the value of the requestId property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getRequestId() {
@@ -92,9 +85,7 @@ public class RequestHeader {
/**
* Sets the value of the requestId property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setRequestId(String value) {
@@ -102,19 +93,17 @@ public class RequestHeader {
}
public String getSvcInstanceId() {
- return svcInstanceId;
- }
+ return svcInstanceId;
+ }
- public void setSvcInstanceId(String svcInstanceId) {
- this.svcInstanceId = svcInstanceId;
- }
+ public void setSvcInstanceId(String svcInstanceId) {
+ this.svcInstanceId = svcInstanceId;
+ }
- /**
+ /**
* Gets the value of the svcAction property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getSvcAction() {
@@ -124,9 +113,7 @@ public class RequestHeader {
/**
* Sets the value of the svcAction property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setSvcAction(String value) {
@@ -136,9 +123,7 @@ public class RequestHeader {
/**
* Gets the value of the svcOperation property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getSvcOperation() {
@@ -148,9 +133,7 @@ public class RequestHeader {
/**
* Sets the value of the svcOperation property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setSvcOperation(String value) {
@@ -160,9 +143,7 @@ public class RequestHeader {
/**
* Gets the value of the callbackUrl property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getCallbackUrl() {
@@ -172,9 +153,7 @@ public class RequestHeader {
/**
* Sets the value of the callbackUrl property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setCallbackUrl(String value) {
@@ -184,9 +163,7 @@ public class RequestHeader {
/**
* Gets the value of the callbackUrl property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getMsoAction() {
@@ -196,9 +173,7 @@ public class RequestHeader {
/**
* Sets the value of the callbackUrl property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setMsoAction(String value) {
@@ -206,14 +181,10 @@ public class RequestHeader {
}
- @Override
- public String toString() {
- return "RequestHeader [requestId=" + requestId +
- ", svcInstanceId=" + svcInstanceId +
- ", svcAction=" + svcAction +
- ", svcOperation=" + svcOperation +
- ", callbackUrl=" + callbackUrl +
- ", msoAction=" + msoAction + "]";
- }
+ @Override
+ public String toString() {
+ return "RequestHeader [requestId=" + requestId + ", svcInstanceId=" + svcInstanceId + ", svcAction=" + svcAction
+ + ", svcOperation=" + svcOperation + ", callbackUrl=" + callbackUrl + ", msoAction=" + msoAction + "]";
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java
index 2fd0a58dda..a38d057e49 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters.sdnc;
import java.util.concurrent.Executor;
-
import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@@ -31,43 +30,43 @@ import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
-@SpringBootApplication(scanBasePackages = { "org.onap" })
+@SpringBootApplication(scanBasePackages = {"org.onap"})
public class SDNCAdapterApplication {
- @Value("${mso.async.core-pool-size}")
- private int corePoolSize;
+ @Value("${mso.async.core-pool-size}")
+ private int corePoolSize;
- @Value("${mso.async.max-pool-size}")
- private int maxPoolSize;
+ @Value("${mso.async.max-pool-size}")
+ private int maxPoolSize;
- @Value("${mso.async.queue-capacity}")
- private int queueCapacity;
+ @Value("${mso.async.queue-capacity}")
+ private int queueCapacity;
- private static final String LOGS_DIR = "logs_dir";
+ private static final String LOGS_DIR = "logs_dir";
- private static void setLogsDir() {
- if (System.getProperty(LOGS_DIR) == null) {
- System.getProperties().setProperty(LOGS_DIR, "./logs/sdnc/");
- }
- }
+ private static void setLogsDir() {
+ if (System.getProperty(LOGS_DIR) == null) {
+ System.getProperties().setProperty(LOGS_DIR, "./logs/sdnc/");
+ }
+ }
- public static void main(String[] args) {
- SpringApplication.run(SDNCAdapterApplication.class, args);
- System.getProperties().setProperty("server.name", "Springboot");
- setLogsDir();
- }
+ public static void main(String[] args) {
+ SpringApplication.run(SDNCAdapterApplication.class, args);
+ System.getProperties().setProperty("server.name", "Springboot");
+ setLogsDir();
+ }
- @Bean
- public Executor asyncExecutor() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setTaskDecorator(new MDCTaskDecorator());
- executor.setCorePoolSize(corePoolSize);
- executor.setMaxPoolSize(maxPoolSize);
- executor.setQueueCapacity(queueCapacity);
- executor.setThreadNamePrefix("SDNCAdapter-");
- executor.initialize();
- return executor;
- }
+ @Bean
+ public Executor asyncExecutor() {
+ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+ executor.setTaskDecorator(new MDCTaskDecorator());
+ executor.setCorePoolSize(corePoolSize);
+ executor.setMaxPoolSize(maxPoolSize);
+ executor.setQueueCapacity(queueCapacity);
+ executor.setThreadNamePrefix("SDNCAdapter-");
+ executor.initialize();
+ return executor;
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterPortType.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterPortType.java
index 66f93ab87f..9c0c55f3ae 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterPortType.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterPortType.java
@@ -30,24 +30,22 @@ import javax.xml.bind.annotation.XmlSeeAlso;
/**
- * This class was generated by Apache CXF 2.7.11.redhat-3
- * 2015-01-27T18:25:50.914-05:00
- * Generated source version: 2.7.11.redhat-3
+ * This class was generated by Apache CXF 2.7.11.redhat-3 2015-01-27T18:25:50.914-05:00 Generated source version:
+ * 2.7.11.redhat-3
*
*/
-//BPEL SDNCAdapter SOAP WebService - impl class in impl pkg
+// BPEL SDNCAdapter SOAP WebService - impl class in impl pkg
@WebService(targetNamespace = "http://org.onap/workflow/sdnc/adapter/wsdl/v1", name = "SDNCAdapterPortType")
@XmlSeeAlso({ObjectFactory.class})
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface SDNCAdapterPortType {
- @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterResponse")
+ @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1",
+ partName = "SDNCAdapterResponse")
@WebMethod(operationName = "SDNCAdapter")
- public SDNCAdapterResponse sdncAdapter(
- @WebParam(partName = "SDNCAdapterRequest", name = "SDNCAdapterRequest", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1")
- SDNCAdapterRequest sdncAdapterRequest
- );
+ public SDNCAdapterResponse sdncAdapter(@WebParam(partName = "SDNCAdapterRequest", name = "SDNCAdapterRequest",
+ targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1") SDNCAdapterRequest sdncAdapterRequest);
@WebMethod
- public void healthCheck();
+ public void healthCheck();
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterRequest.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterRequest.java
index d204f0c2dd..055d1cd031 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterRequest.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterRequest.java
@@ -26,14 +26,16 @@ import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
-
import org.onap.so.adapters.sdnc.impl.Utils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
+
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -50,12 +52,9 @@ import org.w3c.dom.Node;
*
*
*/
-//BPEL to SDNCAdapter request
+// BPEL to SDNCAdapter request
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "requestHeader",
- "requestData"
-})
+@XmlType(name = "", propOrder = {"requestHeader", "requestData"})
@XmlRootElement(name = "SDNCAdapterRequest")
public class SDNCAdapterRequest {
@@ -67,9 +66,7 @@ public class SDNCAdapterRequest {
/**
* Gets the value of the requestHeader property.
*
- * @return
- * possible object is
- * {@link RequestHeader }
+ * @return possible object is {@link RequestHeader }
*
*/
public RequestHeader getRequestHeader() {
@@ -79,9 +76,7 @@ public class SDNCAdapterRequest {
/**
* Sets the value of the requestHeader property.
*
- * @param value
- * allowed object is
- * {@link RequestHeader }
+ * @param value allowed object is {@link RequestHeader }
*
*/
public void setRequestHeader(RequestHeader value) {
@@ -91,9 +86,7 @@ public class SDNCAdapterRequest {
/**
* Gets the value of the requestData property.
*
- * @return
- * possible object is
- * {@link Object }
+ * @return possible object is {@link Object }
*
*/
public Object getRequestData() {
@@ -103,26 +96,22 @@ public class SDNCAdapterRequest {
/**
* Sets the value of the requestData property.
*
- * @param value
- * allowed object is
- * {@link Object }
+ * @param value allowed object is {@link Object }
*
*/
public void setRequestData(Object value) {
this.requestData = value;
}
- @Override
- public String toString() {
+ @Override
+ public String toString() {
- String rd = "";
- if (requestData != null)
- {
- Node node = (Node) requestData;
- Document doc = node.getOwnerDocument();
- rd = Utils.domToStr(doc);
- }
- return "SDNCAdapterRequest [requestHeader=" + requestHeader.toString()
- + ", requestData=" + rd + "]";
- }
+ String rd = "";
+ if (requestData != null) {
+ Node node = (Node) requestData;
+ Document doc = node.getOwnerDocument();
+ rd = Utils.domToStr(doc);
+ }
+ return "SDNCAdapterRequest [requestHeader=" + requestHeader.toString() + ", requestData=" + rd + "]";
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterResponse.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterResponse.java
index c67fbc0ae0..3f6db9b98e 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterResponse.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterResponse.java
@@ -28,9 +28,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -43,7 +45,7 @@ import javax.xml.bind.annotation.XmlType;
*
*
*/
-//SDNCAdapter to BPEL Sync Response(ACK) - async response(s) follow
+// SDNCAdapter to BPEL Sync Response(ACK) - async response(s) follow
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "SDNCAdapterResponse")
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java
index 26e67c8507..d48013b80d 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java
@@ -25,56 +25,55 @@ package org.onap.so.adapters.sdnc;
import java.net.URL;
-
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
-
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * This class was generated by Apache CXF 2.7.11.redhat-3
- * 2015-01-27T18:25:50.994-05:00
- * Generated source version: 2.7.11.redhat-3
+ * This class was generated by Apache CXF 2.7.11.redhat-3 2015-01-27T18:25:50.994-05:00 Generated source version:
+ * 2.7.11.redhat-3
*
*/
-//BPEL SDNCAdapter SOAP WebService
-@WebServiceClient(name = "SDNCAdapterService",
- wsdlLocation = "main/resources/SDNCAdapter.wsdl",
- targetNamespace = "http://org.onap/workflow/sdnc/adapter/wsdl/v1")
+// BPEL SDNCAdapter SOAP WebService
+@WebServiceClient(name = "SDNCAdapterService", wsdlLocation = "main/resources/SDNCAdapter.wsdl",
+ targetNamespace = "http://org.onap/workflow/sdnc/adapter/wsdl/v1")
public class SDNCAdapterService extends Service {
- private static Logger logger = LoggerFactory.getLogger(SDNCAdapterService.class);
- private static final String SDNC_ADAPTER_WSDL="SDNCAdapter.wsdl";
-
+ private static Logger logger = LoggerFactory.getLogger(SDNCAdapterService.class);
+ private static final String SDNC_ADAPTER_WSDL = "SDNCAdapter.wsdl";
+
public static final URL WSDL_LOCATION;
- public static final QName SERVICE = new QName("http://org.onap/workflow/sdnc/adapter/wsdl/v1", "SDNCAdapterService");
- public static final QName SDNCAdapterSoapHttpPort = new QName("http://org.onap/workflow/sdnc/adapter/wsdl/v1", "SDNCAdapterSoapHttpPort");
+ public static final QName SERVICE =
+ new QName("http://org.onap/workflow/sdnc/adapter/wsdl/v1", "SDNCAdapterService");
+ public static final QName SDNCAdapterSoapHttpPort =
+ new QName("http://org.onap/workflow/sdnc/adapter/wsdl/v1", "SDNCAdapterSoapHttpPort");
static {
URL wsdlUrl = null;
try {
- wsdlUrl = Thread.currentThread().getContextClassLoader().getResource("main/resources/SDNCAdapter.wsdl");
+ wsdlUrl = Thread.currentThread().getContextClassLoader().getResource("main/resources/SDNCAdapter.wsdl");
} catch (Exception e) {
logger.error("{} {} {} {}", MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_ADAPTER_WSDL,
- ErrorCode.DataError.getValue(), "Exception - WSDL not found", e);
+ ErrorCode.DataError.getValue(), "Exception - WSDL not found", e);
}
- if(wsdlUrl == null) {
+ if (wsdlUrl == null) {
logger.error("{} {} {} {}", MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_ADAPTER_WSDL,
- ErrorCode.DataError.getValue(), "WSDL not found");
+ ErrorCode.DataError.getValue(), "WSDL not found");
} else {
- try {
- logger.info("{} {} {}", MessageEnum.RA_PRINT_URL.toString(), SDNC_ADAPTER_WSDL, wsdlUrl.toURI().toString());
- } catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.RA_WSDL_URL_CONVENTION_EXC.toString(), SDNC_ADAPTER_WSDL,
- ErrorCode.DataError.getValue(), "Exception - print URL", e);
+ try {
+ logger.info("{} {} {}", MessageEnum.RA_PRINT_URL.toString(), SDNC_ADAPTER_WSDL,
+ wsdlUrl.toURI().toString());
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.RA_WSDL_URL_CONVENTION_EXC.toString(), SDNC_ADAPTER_WSDL,
+ ErrorCode.DataError.getValue(), "Exception - print URL", e);
+ }
}
- }
WSDL_LOCATION = wsdlUrl;
}
@@ -90,31 +89,30 @@ public class SDNCAdapterService extends Service {
super(WSDL_LOCATION, SERVICE);
}
- //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
- //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
- //compliant code instead.
- public SDNCAdapterService(WebServiceFeature ... features) {
+ // This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
+ // API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
+ // compliant code instead.
+ public SDNCAdapterService(WebServiceFeature... features) {
super(WSDL_LOCATION, SERVICE, features);
}
- //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
- //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
- //compliant code instead.
- public SDNCAdapterService(URL wsdlLocation, WebServiceFeature ... features) {
+ // This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
+ // API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
+ // compliant code instead.
+ public SDNCAdapterService(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, SERVICE, features);
}
- //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
- //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
- //compliant code instead.
- public SDNCAdapterService(URL wsdlLocation, QName serviceName, WebServiceFeature ... features) {
+ // This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
+ // API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
+ // compliant code instead.
+ public SDNCAdapterService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
- * @return
- * returns SDNCAdapterPortType
+ * @return returns SDNCAdapterPortType
*/
@WebEndpoint(name = "SDNCAdapterSoapHttpPort")
public SDNCAdapterPortType getSDNCAdapterSoapHttpPort() {
@@ -123,10 +121,9 @@ public class SDNCAdapterService extends Service {
/**
*
- * @param features
- * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
- * @return
- * returns SDNCAdapterPortType
+ * @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features
+ * not in the <code>features</code> parameter will have their default values.
+ * @return returns SDNCAdapterPortType
*/
@WebEndpoint(name = "SDNCAdapterSoapHttpPort")
public SDNCAdapterPortType getSDNCAdapterSoapHttpPort(WebServiceFeature... features) {
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/WebSecurityConfigImpl.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/WebSecurityConfigImpl.java
index 60e37294b1..e1eb9ecef9 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/WebSecurityConfigImpl.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/WebSecurityConfigImpl.java
@@ -31,21 +31,18 @@ import org.springframework.util.StringUtils;
@EnableWebSecurity
public class WebSecurityConfigImpl extends WebSecurityConfig {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf().disable()
- .authorizeRequests()
- .antMatchers("/manage/health","/manage/info","/services").permitAll()
- .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),",").toString())
- .and()
- .httpBasic();
- }
-
- @Override
- public void configure(WebSecurity web) throws Exception {
- super.configure(web);
- StrictHttpFirewall firewall = new MSOSpringFirewall();
- web.httpFirewall(firewall);
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info", "/services").permitAll()
+ .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",").toString())
+ .and().httpBasic();
+ }
+
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ super.configure(web);
+ StrictHttpFirewall firewall = new MSOSpringFirewall();
+ web.httpFirewall(firewall);
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/CallbackHeader.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/CallbackHeader.java
index 67f5516daa..a37602d1fc 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/CallbackHeader.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/CallbackHeader.java
@@ -28,9 +28,11 @@ import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -48,13 +50,9 @@ import javax.xml.bind.annotation.XmlType;
*
*
*/
-//SDNCAdapter to BPEL Async response header
+// SDNCAdapter to BPEL Async response header
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "requestId",
- "responseCode",
- "responseMessage"
-})
+@XmlType(name = "", propOrder = {"requestId", "responseCode", "responseMessage"})
@XmlRootElement(name = "CallbackHeader")
public class CallbackHeader {
@@ -70,17 +68,15 @@ public class CallbackHeader {
}
public CallbackHeader(String reqId, String respCode, String respMsg) {
- this.requestId = reqId;
- this.responseCode = respCode;
- this.responseMessage = respMsg;
+ this.requestId = reqId;
+ this.responseCode = respCode;
+ this.responseMessage = respMsg;
}
/**
* Gets the value of the requestId property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getRequestId() {
@@ -90,9 +86,7 @@ public class CallbackHeader {
/**
* Sets the value of the requestId property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setRequestId(String value) {
@@ -102,9 +96,7 @@ public class CallbackHeader {
/**
* Gets the value of the responseCode property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getResponseCode() {
@@ -114,9 +106,7 @@ public class CallbackHeader {
/**
* Sets the value of the responseCode property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setResponseCode(String value) {
@@ -126,9 +116,7 @@ public class CallbackHeader {
/**
* Gets the value of the responseMessage property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getResponseMessage() {
@@ -138,18 +126,16 @@ public class CallbackHeader {
/**
* Sets the value of the responseMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setResponseMessage(String value) {
this.responseMessage = value;
}
- @Override
- public String toString() {
- return "CallbackHeader [requestId=" + requestId + ", responseCode="
- + responseCode + ", responseMessage=" + responseMessage + "]";
- }
+ @Override
+ public String toString() {
+ return "CallbackHeader [requestId=" + requestId + ", responseCode=" + responseCode + ", responseMessage="
+ + responseMessage + "]";
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/ObjectFactory.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/ObjectFactory.java
index 238b6a7b1c..3877195fbc 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/ObjectFactory.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/ObjectFactory.java
@@ -25,17 +25,13 @@ import javax.xml.bind.annotation.XmlRegistry;
/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the org.onap.so.adapters.sdnc.client package.
- * <p>An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
- * provided in this class.
+ * This object contains factory methods for each Java content interface and Java element interface generated in the
+ * org.onap.so.adapters.sdnc.client package.
+ * <p>
+ * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content.
+ * The Java representation of XML content can consist of schema derived interfaces and classes representing the binding
+ * of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in
+ * this class.
*
*/
@XmlRegistry
@@ -43,11 +39,11 @@ public class ObjectFactory {
/**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.so.adapters.sdnc.client
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
+ * org.onap.so.adapters.sdnc.client
*
*/
- public ObjectFactory() {
- }
+ public ObjectFactory() {}
/**
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java
index 2703060761..97a6860dfe 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java
@@ -24,7 +24,6 @@ package org.onap.so.adapters.sdnc.client;
import java.io.StringWriter;
-
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
@@ -32,16 +31,17 @@ import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
-
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -58,12 +58,9 @@ import org.slf4j.LoggerFactory;
*
*
*/
-//SDNCAdapter to BPEL Async response
+// SDNCAdapter to BPEL Async response
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "callbackHeader",
- "requestData"
-})
+@XmlType(name = "", propOrder = {"callbackHeader", "requestData"})
@XmlRootElement(name = "SDNCAdapterCallbackRequest")
public class SDNCAdapterCallbackRequest {
@@ -77,9 +74,7 @@ public class SDNCAdapterCallbackRequest {
/**
* Gets the value of the callbackHeader property.
*
- * @return
- * possible object is
- * {@link CallbackHeader }
+ * @return possible object is {@link CallbackHeader }
*
*/
public CallbackHeader getCallbackHeader() {
@@ -89,9 +84,7 @@ public class SDNCAdapterCallbackRequest {
/**
* Sets the value of the callbackHeader property.
*
- * @param value
- * allowed object is
- * {@link CallbackHeader }
+ * @param value allowed object is {@link CallbackHeader }
*
*/
public void setCallbackHeader(CallbackHeader value) {
@@ -101,9 +94,7 @@ public class SDNCAdapterCallbackRequest {
/**
* Gets the value of the requestData property.
*
- * @return
- * possible object is
- * {@link Object }
+ * @return possible object is {@link Object }
*
*/
public Object getRequestData() {
@@ -113,31 +104,27 @@ public class SDNCAdapterCallbackRequest {
/**
* Sets the value of the requestData property.
*
- * @param value
- * allowed object is
- * {@link Object }
+ * @param value allowed object is {@link Object }
*
*/
public void setRequestData(Object value) {
this.requestData = value;
}
- @Override
- public String toString() {
- try {
- JAXBContext ctx = JAXBContext.newInstance("org.onap.so.adapters.sdnc.client");
- Marshaller m = ctx.createMarshaller();
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
- StringWriter w = new StringWriter();
- m.marshal(this, w);
- return w.toString();
- }
- catch (Exception e)
- {
- logger.error("{} {} {}", MessageEnum.RA_MARSHING_ERROR.toString(), ErrorCode.DataError.getValue(),
- "Exception - MARSHING_ERROR", e);
+ @Override
+ public String toString() {
+ try {
+ JAXBContext ctx = JAXBContext.newInstance("org.onap.so.adapters.sdnc.client");
+ Marshaller m = ctx.createMarshaller();
+ m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+ m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
+ StringWriter w = new StringWriter();
+ m.marshal(this, w);
+ return w.toString();
+ } catch (Exception e) {
+ logger.error("{} {} {}", MessageEnum.RA_MARSHING_ERROR.toString(), ErrorCode.DataError.getValue(),
+ "Exception - MARSHING_ERROR", e);
+ }
+ return "";
}
- return "";
- }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterPortType.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterPortType.java
index 369610ce0f..d072a9af6d 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterPortType.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterPortType.java
@@ -27,27 +27,26 @@ import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
-
import org.onap.so.adapters.sdnc.SDNCAdapterResponse;
/**
- * This class was generated by Apache CXF 2.7.11.redhat-3
- * 2015-01-28T11:07:01.997-05:00
- * Generated source version: 2.7.11.redhat-3
+ * This class was generated by Apache CXF 2.7.11.redhat-3 2015-01-28T11:07:01.997-05:00 Generated source version:
+ * 2.7.11.redhat-3
*
*/
-//SDNCAdapter to BPEL Async response WEB Service
-@WebService(targetNamespace = "http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1", name = "SDNCCallbackAdapterPortType")
+// SDNCAdapter to BPEL Async response WEB Service
+@WebService(targetNamespace = "http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1",
+ name = "SDNCCallbackAdapterPortType")
@XmlSeeAlso({ObjectFactory.class})
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@FunctionalInterface
public interface SDNCCallbackAdapterPortType {
- @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackResponse")
+ @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1",
+ partName = "SDNCAdapterCallbackResponse")
@WebMethod(operationName = "SDNCAdapterCallback")
- public SDNCAdapterResponse sdncAdapterCallback(
- @WebParam(partName = "SDNCAdapterCallbackRequest", name = "SDNCAdapterCallbackRequest", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1")
- SDNCAdapterCallbackRequest sdncAdapterCallbackRequest
- );
+ public SDNCAdapterResponse sdncAdapterCallback(@WebParam(partName = "SDNCAdapterCallbackRequest",
+ name = "SDNCAdapterCallbackRequest",
+ targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1") SDNCAdapterCallbackRequest sdncAdapterCallbackRequest);
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java
index ee7a467357..72d18bd1ce 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java
@@ -24,55 +24,55 @@ package org.onap.so.adapters.sdnc.client;
import java.net.URL;
-
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
-
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * This class was generated by Apache CXF 2.7.11.redhat-3
- * 2015-01-28T11:07:02.074-05:00
- * Generated source version: 2.7.11.redhat-3
+ * This class was generated by Apache CXF 2.7.11.redhat-3 2015-01-28T11:07:02.074-05:00 Generated source version:
+ * 2.7.11.redhat-3
*
*/
-//SDNCAdapter to BPEL Async response WEB Service
-@WebServiceClient(name = "SDNCCallbackAdapterService",
- wsdlLocation = "main/resources/SDNCCallbackAdapter.wsdl",
- targetNamespace = "http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1")
+// SDNCAdapter to BPEL Async response WEB Service
+@WebServiceClient(name = "SDNCCallbackAdapterService", wsdlLocation = "main/resources/SDNCCallbackAdapter.wsdl",
+ targetNamespace = "http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1")
public class SDNCCallbackAdapterService extends Service {
- private static Logger logger = LoggerFactory.getLogger(SDNCCallbackAdapterService.class);
- private static final String SDNC_CALLBACK_ADAPTER_WSDL="SDNCCallbackAdapter.wsdl";
+ private static Logger logger = LoggerFactory.getLogger(SDNCCallbackAdapterService.class);
+ private static final String SDNC_CALLBACK_ADAPTER_WSDL = "SDNCCallbackAdapter.wsdl";
public static final URL WSDL_LOCATION;
- public static final QName SERVICE = new QName("http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1", "SDNCCallbackAdapterService");
- public static final QName SDNCCallbackAdapterSoapHttpPort = new QName("http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1", "SDNCCallbackAdapterSoapHttpPort");
+ public static final QName SERVICE =
+ new QName("http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1", "SDNCCallbackAdapterService");
+ public static final QName SDNCCallbackAdapterSoapHttpPort =
+ new QName("http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1", "SDNCCallbackAdapterSoapHttpPort");
static {
URL wsdlUrl = null;
try {
- wsdlUrl = Thread.currentThread().getContextClassLoader().getResource("main/resources/SDNCCallbackAdapter.wsdl");
+ wsdlUrl = Thread.currentThread().getContextClassLoader()
+ .getResource("main/resources/SDNCCallbackAdapter.wsdl");
} catch (Exception e) {
logger.error("{} {} {} {} {}", MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_CALLBACK_ADAPTER_WSDL, "SDNC",
- ErrorCode.DataError.getValue(), "Exception - WSDL not found", e);
+ ErrorCode.DataError.getValue(), "Exception - WSDL not found", e);
}
- if(wsdlUrl == null) {
+ if (wsdlUrl == null) {
logger.error("{} {} {} {} {}", MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_CALLBACK_ADAPTER_WSDL, "SDNC",
- ErrorCode.DataError.getValue(), "WSDL not found");
+ ErrorCode.DataError.getValue(), "WSDL not found");
} else {
- try {
- logger.info("{} {} {} {}", MessageEnum.RA_PRINT_URL.toString(), SDNC_CALLBACK_ADAPTER_WSDL,
- wsdlUrl.toURI().toString(), "SDNC");
- } catch (Exception e) {
- logger.error("{} {} {} {} {}", MessageEnum.RA_WSDL_URL_CONVENTION_EXC.toString(), SDNC_CALLBACK_ADAPTER_WSDL,
- "SDNC", ErrorCode.DataError.getValue(), "Exception - URL convention problem", e);
+ try {
+ logger.info("{} {} {} {}", MessageEnum.RA_PRINT_URL.toString(), SDNC_CALLBACK_ADAPTER_WSDL,
+ wsdlUrl.toURI().toString(), "SDNC");
+ } catch (Exception e) {
+ logger.error("{} {} {} {} {}", MessageEnum.RA_WSDL_URL_CONVENTION_EXC.toString(),
+ SDNC_CALLBACK_ADAPTER_WSDL, "SDNC", ErrorCode.DataError.getValue(),
+ "Exception - URL convention problem", e);
+ }
}
- }
WSDL_LOCATION = wsdlUrl;
}
@@ -88,31 +88,30 @@ public class SDNCCallbackAdapterService extends Service {
super(WSDL_LOCATION, SERVICE);
}
- //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
- //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
- //compliant code instead.
- public SDNCCallbackAdapterService(WebServiceFeature ... features) {
+ // This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
+ // API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
+ // compliant code instead.
+ public SDNCCallbackAdapterService(WebServiceFeature... features) {
super(WSDL_LOCATION, SERVICE, features);
}
- //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
- //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
- //compliant code instead.
- public SDNCCallbackAdapterService(URL wsdlLocation, WebServiceFeature ... features) {
+ // This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
+ // API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
+ // compliant code instead.
+ public SDNCCallbackAdapterService(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, SERVICE, features);
}
- //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
- //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
- //compliant code instead.
- public SDNCCallbackAdapterService(URL wsdlLocation, QName serviceName, WebServiceFeature ... features) {
+ // This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
+ // API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
+ // compliant code instead.
+ public SDNCCallbackAdapterService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
- * @return
- * returns SDNCCallbackAdapterPortType
+ * @return returns SDNCCallbackAdapterPortType
*/
@WebEndpoint(name = "SDNCCallbackAdapterSoapHttpPort")
public SDNCCallbackAdapterPortType getSDNCCallbackAdapterSoapHttpPort() {
@@ -121,10 +120,9 @@ public class SDNCCallbackAdapterService extends Service {
/**
*
- * @param features
- * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
- * @return
- * returns SDNCCallbackAdapterPortType
+ * @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features
+ * not in the <code>features</code> parameter will have their default values.
+ * @return returns SDNCCallbackAdapterPortType
*/
@WebEndpoint(name = "SDNCCallbackAdapterSoapHttpPort")
public SDNCCallbackAdapterPortType getSDNCCallbackAdapterSoapHttpPort(WebServiceFeature... features) {
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/package-info.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/package-info.java
index 368c824caa..f5d494f40c 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/package-info.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/package-info.java
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
-@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
+@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1",
+ elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.onap.so.adapters.sdnc.client;
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/exception/SDNCAdapterException.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/exception/SDNCAdapterException.java
index e45c4ce569..3a03f454f7 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/exception/SDNCAdapterException.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/exception/SDNCAdapterException.java
@@ -22,9 +22,9 @@ package org.onap.so.adapters.sdnc.exception;
public class SDNCAdapterException extends Exception {
- private static final long serialVersionUID = -7913634772004514998L;
+ private static final long serialVersionUID = -7913634772004514998L;
- public SDNCAdapterException(String message) {
- super(message);
- }
+ public SDNCAdapterException(String message) {
+ super(message);
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Constants.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Constants.java
index 09597b26b7..91c7c7c65f 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Constants.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Constants.java
@@ -23,21 +23,21 @@ package org.onap.so.adapters.sdnc.impl;
public interface Constants {
- public static final String BPEL_REST_URL_PROP = "org.onap.so.adapters.sdnc.rest.bpelurl";
- public static final String BPEL_URL_PROP = "org.onap.so.adapters.sdnc.bpelurl";
- public static final String DEFAULT_BPEL_URL = "http://localhost:8080//active-bpel/services/SDNCAdapterCallbackV1";
+ public static final String BPEL_REST_URL_PROP = "org.onap.so.adapters.sdnc.rest.bpelurl";
+ public static final String BPEL_URL_PROP = "org.onap.so.adapters.sdnc.bpelurl";
+ public static final String DEFAULT_BPEL_URL = "http://localhost:8080//active-bpel/services/SDNCAdapterCallbackV1";
- public static final String MY_URL_PROP = "org.onap.so.adapters.sdnc.myurl";
- public static final String SDNC_AUTH_PROP = "org.onap.so.adapters.sdnc.sdncauth";
- public static final String BPEL_AUTH_PROP = "org.onap.so.adapters.sdnc.bpelauth";
+ public static final String MY_URL_PROP = "org.onap.so.adapters.sdnc.myurl";
+ public static final String SDNC_AUTH_PROP = "org.onap.so.adapters.sdnc.sdncauth";
+ public static final String BPEL_AUTH_PROP = "org.onap.so.adapters.sdnc.bpelauth";
- public static final String SDNC_SVCCFGRESP_ROOT = "input";
- public static final String SDNC_REQ_ID = "/svc-request-id";
- public static final String SDNC_RESP_CODE = "/response-code";
- public static final String SDNC_RESP_MSG = "/response-message";
- public static final String SDNC_CONNECTTIME_PROP = "org.onap.so.adapters.sdnc.sdncconnecttime";
- public static final String ENCRYPTION_KEY_PROP = "org.onap.so.adapters.network.encryptionKey";
+ public static final String SDNC_SVCCFGRESP_ROOT = "input";
+ public static final String SDNC_REQ_ID = "/svc-request-id";
+ public static final String SDNC_RESP_CODE = "/response-code";
+ public static final String SDNC_RESP_MSG = "/response-message";
+ public static final String SDNC_CONNECTTIME_PROP = "org.onap.so.adapters.sdnc.sdncconnecttime";
+ public static final String ENCRYPTION_KEY_PROP = "org.onap.so.adapters.network.encryptionKey";
- public static final String REQUEST_TUNABLES = "org.onap.so.adapters.sdnc";
+ public static final String REQUEST_TUNABLES = "org.onap.so.adapters.sdnc";
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java
index 401f5c5b2b..2d43385700 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java
@@ -33,77 +33,82 @@ import org.springframework.stereotype.Component;
@Component
public class MapRequestTunables {
-
- private static Logger logger = LoggerFactory.getLogger(MapRequestTunables.class);
- public static final String GENERATED_KEY = "Generated key: ";
-
- @Autowired
- private Environment env;
- public RequestTunables setTunables(RequestTunables reqTunableOriginal)
- {
- RequestTunables reqTunable = new RequestTunables(reqTunableOriginal);
- String error = null;
- String key;
- if ("query".equals(reqTunable.getAction())) { //due to variable format for reqTunable.getOperation() eg services/layer3-service-list/8fe4ba4f-35cf-4d9b-a04a-fd3f5d4c5cc9
- key = Constants.REQUEST_TUNABLES + "." + reqTunable.getMsoAction() + ".." + reqTunable.getAction();
- logger.debug(GENERATED_KEY + key);
- }
- else if ("put".equals(reqTunable.getAction()) || "restdelete".equals(reqTunable.getAction())) { //due to variable format for reqTunable.getOperation() eg services/layer3-service-list/8fe4ba4f-35cf-4d9b-a04a-fd3f5d4c5cc9
- key = Constants.REQUEST_TUNABLES + "..." + reqTunable.getAction();
- logger.debug(GENERATED_KEY + key);
- } else {
- key = Constants.REQUEST_TUNABLES + "." + reqTunable.getMsoAction() + "." + reqTunable.getOperation() +"." + reqTunable.getAction();
- logger.debug(GENERATED_KEY + key);
- }
+ private static Logger logger = LoggerFactory.getLogger(MapRequestTunables.class);
+ public static final String GENERATED_KEY = "Generated key: ";
- String value;
- value = env.getProperty(key, "");
+ @Autowired
+ private Environment env;
- if (value != null && value.length() > 0) {
+ public RequestTunables setTunables(RequestTunables reqTunableOriginal) {
+ RequestTunables reqTunable = new RequestTunables(reqTunableOriginal);
+ String error = null;
+ String key;
+ if ("query".equals(reqTunable.getAction())) { // due to variable format for reqTunable.getOperation() eg
+ // services/layer3-service-list/8fe4ba4f-35cf-4d9b-a04a-fd3f5d4c5cc9
+ key = Constants.REQUEST_TUNABLES + "." + reqTunable.getMsoAction() + ".." + reqTunable.getAction();
+ logger.debug(GENERATED_KEY + key);
+ } else if ("put".equals(reqTunable.getAction()) || "restdelete".equals(reqTunable.getAction())) { // due to
+ // variable
+ // format for
+ // reqTunable.getOperation()
+ // eg
+ // services/layer3-service-list/8fe4ba4f-35cf-4d9b-a04a-fd3f5d4c5cc9
+ key = Constants.REQUEST_TUNABLES + "..." + reqTunable.getAction();
+ logger.debug(GENERATED_KEY + key);
+ } else {
+ key = Constants.REQUEST_TUNABLES + "." + reqTunable.getMsoAction() + "." + reqTunable.getOperation() + "."
+ + reqTunable.getAction();
+ logger.debug(GENERATED_KEY + key);
+ }
- String[] parts = value.split("\\|"); //escape pipe
- if (parts.length < 3) {
- logger.warn("{} {} {} {} {} {}", MessageEnum.RA_SDNC_INVALID_CONFIG.toString(), key, value, "SDNC",
- ErrorCode.DataError.getValue(), "Invalid config");
- }
+ String value;
+ value = env.getProperty(key, "");
- for (int i = 0; i < parts.length; i++) {
- if (i == 0) {
- reqTunable.setReqMethod(parts[i]) ;
- logger.debug("Request Method is set to: {}", reqTunable.getReqMethod());
- } else if (i == 1) {
- reqTunable.setTimeout( parts[i]);
- logger.debug("Timeout is set to: {}", reqTunable.getTimeout());
- } else if (i == 2) {
- reqTunable.setSdncUrl(env.getProperty(Constants.REQUEST_TUNABLES + "." + parts[i],""));
- if (reqTunable.getOperation() != null && reqTunable.getSdncUrl() != null) {
- reqTunable.setSdncUrl(reqTunable.getSdncUrl() + reqTunable.getOperation());
- }
- logger.debug("SDNC Url is set to: {}", reqTunable.getSdncUrl());
- } else if (i == 3) {
- reqTunable.setHeaderName(parts[i]);
- logger.debug("HeaderName is set to: {}", reqTunable.getHeaderName());
- } else if (i == 4) {
- reqTunable.setNamespace(parts[i]);
- logger.debug("NameSpace is set to: {}", reqTunable.getNamespace());
- } else if (i == 5) {
- reqTunable.setAsyncInd(parts[i]);
- logger.debug("AsyncInd is set to: {}", reqTunable.getAsyncInd());
- }
- }
+ if (value != null && value.length() > 0) {
- if (reqTunable.getSdncUrl() == null || ("").equals(reqTunable.getSdncUrl())) {
- error = "Invalid configuration, sdncUrl required for:" + key + " value:" + value;
- }
- } else {
- error = "Missing configuration for:" + key;
- }
- if (error != null) {
- logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), key, "SDNC",
- ErrorCode.DataError.getValue(), "Missing config param");
- }
- logger.debug("RequestTunables Key:{} Value:{} Tunables:{}", key, value, this.toString());
- return reqTunable;
- }
+ String[] parts = value.split("\\|"); // escape pipe
+ if (parts.length < 3) {
+ logger.warn("{} {} {} {} {} {}", MessageEnum.RA_SDNC_INVALID_CONFIG.toString(), key, value, "SDNC",
+ ErrorCode.DataError.getValue(), "Invalid config");
+ }
+
+ for (int i = 0; i < parts.length; i++) {
+ if (i == 0) {
+ reqTunable.setReqMethod(parts[i]);
+ logger.debug("Request Method is set to: {}", reqTunable.getReqMethod());
+ } else if (i == 1) {
+ reqTunable.setTimeout(parts[i]);
+ logger.debug("Timeout is set to: {}", reqTunable.getTimeout());
+ } else if (i == 2) {
+ reqTunable.setSdncUrl(env.getProperty(Constants.REQUEST_TUNABLES + "." + parts[i], ""));
+ if (reqTunable.getOperation() != null && reqTunable.getSdncUrl() != null) {
+ reqTunable.setSdncUrl(reqTunable.getSdncUrl() + reqTunable.getOperation());
+ }
+ logger.debug("SDNC Url is set to: {}", reqTunable.getSdncUrl());
+ } else if (i == 3) {
+ reqTunable.setHeaderName(parts[i]);
+ logger.debug("HeaderName is set to: {}", reqTunable.getHeaderName());
+ } else if (i == 4) {
+ reqTunable.setNamespace(parts[i]);
+ logger.debug("NameSpace is set to: {}", reqTunable.getNamespace());
+ } else if (i == 5) {
+ reqTunable.setAsyncInd(parts[i]);
+ logger.debug("AsyncInd is set to: {}", reqTunable.getAsyncInd());
+ }
+ }
+
+ if (reqTunable.getSdncUrl() == null || ("").equals(reqTunable.getSdncUrl())) {
+ error = "Invalid configuration, sdncUrl required for:" + key + " value:" + value;
+ }
+ } else {
+ error = "Missing configuration for:" + key;
+ }
+ if (error != null) {
+ logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), key, "SDNC",
+ ErrorCode.DataError.getValue(), "Missing config param");
+ }
+ logger.debug("RequestTunables Key:{} Value:{} Tunables:{}", key, value, this.toString());
+ return reqTunable;
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/RequestTunables.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/RequestTunables.java
index 6947b870d7..bfd2aea33f 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/RequestTunables.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/RequestTunables.java
@@ -24,136 +24,151 @@ package org.onap.so.adapters.sdnc.impl;
public class RequestTunables {
-
-
- public static final String GENERATED_KEY = "Generated key: ";
-
- //criteria
- private String reqId = "";
- private String msoAction = "";
- private String operation = "";
- private String action = "";
-
- //tunables
- private String reqMethod = "POST";
- private String sdncUrl = null;
- private String timeout = "60000";
- private String headerName = "sdnc-request-header";
- private String namespace = "";
- private String asyncInd = "N"; //future use
-
- private String sdncaNotificationUrl = null;
-
- public RequestTunables(String reqId, String msoAction, String operation, String action) {
- super();
- if (reqId != null) {
+
+
+ public static final String GENERATED_KEY = "Generated key: ";
+
+ // criteria
+ private String reqId = "";
+ private String msoAction = "";
+ private String operation = "";
+ private String action = "";
+
+ // tunables
+ private String reqMethod = "POST";
+ private String sdncUrl = null;
+ private String timeout = "60000";
+ private String headerName = "sdnc-request-header";
+ private String namespace = "";
+ private String asyncInd = "N"; // future use
+
+ private String sdncaNotificationUrl = null;
+
+ public RequestTunables(String reqId, String msoAction, String operation, String action) {
+ super();
+ if (reqId != null) {
this.reqId = reqId;
}
- if (msoAction != null) {
+ if (msoAction != null) {
this.msoAction = msoAction;
}
- if (operation != null) {
+ if (operation != null) {
this.operation = operation;
}
- if (action != null) {
+ if (action != null) {
this.action = action;
}
- }
-
- public RequestTunables(RequestTunables original) {
- this.reqId = original.reqId;
- this.action = original.action;
- this.msoAction = original.msoAction;
- this.operation = original.operation;
- this.reqMethod = original.reqMethod;
- this.sdncUrl = original.sdncUrl;
- this.timeout = original.timeout;
- this.headerName = original.headerName;
- this.namespace = original.namespace;
- this.asyncInd = original.asyncInd;
- this.sdncaNotificationUrl = original.sdncaNotificationUrl;
- }
-
- public String getReqId() {
- return reqId;
- }
- public void setReqId(String reqId) {
- this.reqId = reqId;
- }
- public String getReqMethod() {
- return reqMethod;
- }
- public void setReqMethod(String reqMethod) {
- this.reqMethod = reqMethod;
- }
- public String getMsoAction() {
- return msoAction;
- }
- public void setMsoAction(String msoAction) {
- this.msoAction = msoAction;
- }
- public String getAction() {
- return action;
- }
- public void setAction(String action) {
- this.action = action;
- }
- public String getOperation() {
- return operation;
- }
- public void setOperation(String operation) {
- this.operation = operation;
- }
- public String getSdncUrl() {
- return sdncUrl;
- }
- public void setSdncUrl(String sdncUrl) {
- this.sdncUrl = sdncUrl;
- }
- public String getTimeout() {
- return timeout;
- }
- public void setTimeout(String timeout) {
- this.timeout = timeout;
- }
- public String getAsyncInd() {
- return asyncInd;
- }
- public void setAsyncInd(String asyncInd) {
- this.asyncInd = asyncInd;
- }
- public String getHeaderName() {
- return headerName;
- }
- public void setHeaderName(String headerName) {
- this.headerName = headerName;
- }
-
-
- public String getSdncaNotificationUrl() {
- return sdncaNotificationUrl;
- }
-
- public void setSdncaNotificationUrl(String sdncaNotificationUrl) {
- this.sdncaNotificationUrl = sdncaNotificationUrl;
- }
-
- public String getNamespace() {
- return namespace;
- }
-
- public void setNamespace(String namespace) {
- this.namespace = namespace;
- }
-
- @Override
- public String toString() {
- return "RequestTunables [reqId=" + reqId + ", msoAction=" + msoAction
- + ", operation=" + operation + ", action=" + action
- + ", reqMethod=" + reqMethod + ", sdncUrl=" + sdncUrl
- + ", timeout=" + timeout + ", headerName=" + headerName
- + ", sdncaNotificationUrl=" + sdncaNotificationUrl
- + ", namespace=" + namespace + "]";
- }
-
+ }
+
+ public RequestTunables(RequestTunables original) {
+ this.reqId = original.reqId;
+ this.action = original.action;
+ this.msoAction = original.msoAction;
+ this.operation = original.operation;
+ this.reqMethod = original.reqMethod;
+ this.sdncUrl = original.sdncUrl;
+ this.timeout = original.timeout;
+ this.headerName = original.headerName;
+ this.namespace = original.namespace;
+ this.asyncInd = original.asyncInd;
+ this.sdncaNotificationUrl = original.sdncaNotificationUrl;
+ }
+
+ public String getReqId() {
+ return reqId;
+ }
+
+ public void setReqId(String reqId) {
+ this.reqId = reqId;
+ }
+
+ public String getReqMethod() {
+ return reqMethod;
+ }
+
+ public void setReqMethod(String reqMethod) {
+ this.reqMethod = reqMethod;
+ }
+
+ public String getMsoAction() {
+ return msoAction;
+ }
+
+ public void setMsoAction(String msoAction) {
+ this.msoAction = msoAction;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getOperation() {
+ return operation;
+ }
+
+ public void setOperation(String operation) {
+ this.operation = operation;
+ }
+
+ public String getSdncUrl() {
+ return sdncUrl;
+ }
+
+ public void setSdncUrl(String sdncUrl) {
+ this.sdncUrl = sdncUrl;
+ }
+
+ public String getTimeout() {
+ return timeout;
+ }
+
+ public void setTimeout(String timeout) {
+ this.timeout = timeout;
+ }
+
+ public String getAsyncInd() {
+ return asyncInd;
+ }
+
+ public void setAsyncInd(String asyncInd) {
+ this.asyncInd = asyncInd;
+ }
+
+ public String getHeaderName() {
+ return headerName;
+ }
+
+ public void setHeaderName(String headerName) {
+ this.headerName = headerName;
+ }
+
+
+ public String getSdncaNotificationUrl() {
+ return sdncaNotificationUrl;
+ }
+
+ public void setSdncaNotificationUrl(String sdncaNotificationUrl) {
+ this.sdncaNotificationUrl = sdncaNotificationUrl;
+ }
+
+ public String getNamespace() {
+ return namespace;
+ }
+
+ public void setNamespace(String namespace) {
+ this.namespace = namespace;
+ }
+
+ @Override
+ public String toString() {
+ return "RequestTunables [reqId=" + reqId + ", msoAction=" + msoAction + ", operation=" + operation + ", action="
+ + action + ", reqMethod=" + reqMethod + ", sdncUrl=" + sdncUrl + ", timeout=" + timeout
+ + ", headerName=" + headerName + ", sdncaNotificationUrl=" + sdncaNotificationUrl + ", namespace="
+ + namespace + "]";
+ }
+
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java
index 104b4ebcc7..3e3ec6f9bb 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java
@@ -25,63 +25,60 @@ package org.onap.so.adapters.sdnc.impl;
import javax.annotation.PostConstruct;
import javax.jws.WebService;
import javax.servlet.http.HttpServletResponse;
-
import org.onap.so.adapters.sdnc.SDNCAdapterPortType;
import org.onap.so.adapters.sdnc.SDNCAdapterRequest;
import org.onap.so.adapters.sdnc.SDNCAdapterResponse;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-//BPEL SDNCAdapter SOAP Web Service implementation
-@WebService(serviceName = "SDNCAdapterService", endpointInterface = "org.onap.so.adapters.sdnc.SDNCAdapterPortType", targetNamespace = "http://org.onap/workflow/sdnc/adapter/wsdl/v1")
+// BPEL SDNCAdapter SOAP Web Service implementation
+@WebService(serviceName = "SDNCAdapterService", endpointInterface = "org.onap.so.adapters.sdnc.SDNCAdapterPortType",
+ targetNamespace = "http://org.onap/workflow/sdnc/adapter/wsdl/v1")
@Component
public class SDNCAdapterPortTypeImpl implements SDNCAdapterPortType {
- private static Logger logger = LoggerFactory.getLogger(SDNCAdapterPortTypeImpl.class);
+ private static Logger logger = LoggerFactory.getLogger(SDNCAdapterPortTypeImpl.class);
+
+
+ @Autowired
+ private SDNCRestClient sdncClient;
-
- @Autowired
- private SDNCRestClient sdncClient;
-
- @PostConstruct
- public void init () {
- logger.info("{} {} {}", MessageEnum.RA_INIT_SDNC_ADAPTER.toString(), "SDNC", "SDNCAdapterPortType");
- }
+ @PostConstruct
+ public void init() {
+ logger.info("{} {} {}", MessageEnum.RA_INIT_SDNC_ADAPTER.toString(), "SDNC", "SDNCAdapterPortType");
+ }
- /**
- * Health Check web method. Does nothing but return to show the adapter is deployed.
- */
- @Override
- public void healthCheck ()
- {
- logger.debug("Health check call in SDNC Adapter");
- }
+ /**
+ * Health Check web method. Does nothing but return to show the adapter is deployed.
+ */
+ @Override
+ public void healthCheck() {
+ logger.debug("Health check call in SDNC Adapter");
+ }
- @Override
- public SDNCAdapterResponse sdncAdapter(SDNCAdapterRequest bpelRequest) {
- String bpelReqId = bpelRequest.getRequestHeader().getRequestId();
- String callbackUrl = bpelRequest.getRequestHeader().getCallbackUrl();
- try {
- sdncClient.executeRequest(bpelRequest);
- }
- catch (Exception e){
- String respMsg = "Error sending request to SDNC. Failed to start SDNC Client thread " + e.getMessage();
- logger.error("{} {} {} {}", MessageEnum.RA_SEND_REQUEST_SDNC_ERR.toString(), "SDNC",
- ErrorCode.DataError.getValue(), respMsg, e);
+ @Override
+ public SDNCAdapterResponse sdncAdapter(SDNCAdapterRequest bpelRequest) {
+ String bpelReqId = bpelRequest.getRequestHeader().getRequestId();
+ String callbackUrl = bpelRequest.getRequestHeader().getCallbackUrl();
+ try {
+ sdncClient.executeRequest(bpelRequest);
+ } catch (Exception e) {
+ String respMsg = "Error sending request to SDNC. Failed to start SDNC Client thread " + e.getMessage();
+ logger.error("{} {} {} {}", MessageEnum.RA_SEND_REQUEST_SDNC_ERR.toString(), "SDNC",
+ ErrorCode.DataError.getValue(), respMsg, e);
- SDNCResponse sdncResp = new SDNCResponse(bpelReqId);
- sdncResp.setRespCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- sdncResp.setRespMsg(respMsg);
- sdncClient.sendRespToBpel(callbackUrl, sdncResp);
- }
- return (new SDNCAdapterResponse());
- }
+ SDNCResponse sdncResp = new SDNCResponse(bpelReqId);
+ sdncResp.setRespCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ sdncResp.setRespMsg(respMsg);
+ sdncClient.sendRespToBpel(callbackUrl, sdncResp);
+ }
+ return (new SDNCAdapterResponse());
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCResponse.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCResponse.java
index c0a737cf78..df753ccfe9 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCResponse.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCResponse.java
@@ -25,49 +25,57 @@ import java.io.Serializable;
public class SDNCResponse implements Serializable {
- private static final long serialVersionUID = 1L;
- private String reqId = null;
- private int respCode = 0;
- private String respMsg = null;
- private String sdncRespXml = null;
-
- public SDNCResponse(String reqId) {
- this.reqId = reqId;
- }
- public SDNCResponse(String reqId, int respCode, String respMsg) {
- this.reqId = reqId;
- this.respCode = respCode;
- this.respMsg = respMsg;
- }
-
- public String getReqId() {
- return reqId;
- }
- public void setReqId(String reqId) {
- this.reqId = reqId;
- }
- public int getRespCode() {
- return respCode;
- }
- public void setRespCode(int respCode) {
- this.respCode = respCode;
- }
- public String getRespMsg() {
- return respMsg;
- }
- public void setRespMsg(String respMsg) {
- this.respMsg = respMsg;
- }
- public String getSdncRespXml() {
- return sdncRespXml;
- }
- public void setSdncRespXml(String sdncRespXml) {
- this.sdncRespXml = sdncRespXml;
- }
-
- @Override
- public String toString() {
- return "SDNCResponse [reqId=" + reqId + ", respCode=" + respCode
- + ", respMsg=" + respMsg + ", sdncRespXml=" + sdncRespXml + "]";
- }
+ private static final long serialVersionUID = 1L;
+ private String reqId = null;
+ private int respCode = 0;
+ private String respMsg = null;
+ private String sdncRespXml = null;
+
+ public SDNCResponse(String reqId) {
+ this.reqId = reqId;
+ }
+
+ public SDNCResponse(String reqId, int respCode, String respMsg) {
+ this.reqId = reqId;
+ this.respCode = respCode;
+ this.respMsg = respMsg;
+ }
+
+ public String getReqId() {
+ return reqId;
+ }
+
+ public void setReqId(String reqId) {
+ this.reqId = reqId;
+ }
+
+ public int getRespCode() {
+ return respCode;
+ }
+
+ public void setRespCode(int respCode) {
+ this.respCode = respCode;
+ }
+
+ public String getRespMsg() {
+ return respMsg;
+ }
+
+ public void setRespMsg(String respMsg) {
+ this.respMsg = respMsg;
+ }
+
+ public String getSdncRespXml() {
+ return sdncRespXml;
+ }
+
+ public void setSdncRespXml(String sdncRespXml) {
+ this.sdncRespXml = sdncRespXml;
+ }
+
+ @Override
+ public String toString() {
+ return "SDNCResponse [reqId=" + reqId + ", respCode=" + respCode + ", respMsg=" + respMsg + ", sdncRespXml="
+ + sdncRespXml + "]";
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java
index 80f111b570..21ce06eaf1 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java
@@ -36,7 +36,6 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.xml.XMLConstants;
import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.DocumentBuilder;
@@ -46,7 +45,6 @@ import javax.xml.ws.handler.MessageContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
-
import org.onap.so.logger.ErrorCode;
import org.onap.so.utils.CryptoUtils;
import org.onap.so.adapters.sdnc.SDNCAdapterRequest;
@@ -55,7 +53,6 @@ import org.onap.so.adapters.sdnc.client.SDNCAdapterCallbackRequest;
import org.onap.so.adapters.sdnc.client.SDNCCallbackAdapterPortType;
import org.onap.so.adapters.sdnc.client.SDNCCallbackAdapterService;
import org.onap.so.logger.MessageEnum;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -69,289 +66,273 @@ import org.w3c.dom.NodeList;
@Component
-public class SDNCRestClient{
-
- @Autowired
- private Environment env;
-
- @Autowired
- private MapRequestTunables tunablesMapper;
-
- private static Logger logger = LoggerFactory.getLogger(SDNCRestClient.class);
-
- private static final String EXCEPTION_MSG="Exception while evaluate xpath";
- private static final String MSO_INTERNAL_ERROR="MsoInternalError";
- private static final String CAMUNDA="Camunda";
- @Async
- public void executeRequest(SDNCAdapterRequest bpelRequest)
- {
-
- logger.debug("BPEL Request:" + bpelRequest.toString());
-
- // Added delay to allow completion of create request to SDNC
- // before executing activate of create request.
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "SDNC",
- ErrorCode.UnknownError.getValue(), "Exception processing request to SDNC", e);
-
- Thread.currentThread().interrupt();
- }
-
- String action = bpelRequest.getRequestHeader().getSvcAction();
- String operation = bpelRequest.getRequestHeader().getSvcOperation();
- String bpelReqId = bpelRequest.getRequestHeader().getRequestId();
- String callbackUrl = bpelRequest.getRequestHeader().getCallbackUrl();
-
- String sdncReqBody = null;
-
- RequestTunables rt = new RequestTunables(bpelReqId,
- bpelRequest.getRequestHeader().getMsoAction(),
- bpelRequest.getRequestHeader().getSvcOperation(),
- bpelRequest.getRequestHeader().getSvcAction());
- rt = tunablesMapper.setTunables(rt);
- rt.setSdncaNotificationUrl(env.getProperty(Constants.MY_URL_PROP));
-
-
- if ("POST".equals(rt.getReqMethod()))
- {
- Node node = (Node) bpelRequest.getRequestData();
- Document reqDoc = node.getOwnerDocument();
- sdncReqBody = Utils.genSdncReq(reqDoc, rt);
- }
- else if("PUT".equals(rt.getReqMethod())){
- Node node = (Node) bpelRequest.getRequestData();
- Document reqDoc = node.getOwnerDocument();
- sdncReqBody = Utils.genSdncPutReq(reqDoc, rt);
- }
- long sdncStartTime = System.currentTimeMillis();
- SDNCResponse sdncResp = getSdncResp(sdncReqBody, rt);
- logger.debug ("Got the SDNC Response: {}", sdncResp.getSdncRespXml());
- long bpelStartTime = System.currentTimeMillis();
- sendRespToBpel(callbackUrl, sdncResp);
- return;
- }
-
- public SDNCResponse getSdncResp(String sdncReqBody, RequestTunables rt)
- {
-
- URL url;
- HttpURLConnection con = null;
- DataOutputStream out = null;
- BufferedReader in = null;
- SDNCResponse sdncResp = new SDNCResponse(rt.getReqId());
- StringBuilder response = new StringBuilder();
-
- logger.info("{} :\n {} {}", MessageEnum.RA_SEND_REQUEST_SDNC.name(), rt.toString(), "SDNC");
- logger.trace("SDNC Request Body:{} \n", sdncReqBody);
-
- try {
-
- url = new URL(rt.getSdncUrl());
-
- con = (HttpURLConnection) url.openConnection();
- con.setConnectTimeout(Integer.parseInt(env.getProperty(Constants.SDNC_CONNECTTIME_PROP)));
- con.setReadTimeout(Integer.parseInt(rt.getTimeout()));
- con.setRequestProperty("Accept", "application/yang.data+xml"); //for response in xml
- String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.SDNC_AUTH_PROP), env.getProperty(Constants.ENCRYPTION_KEY_PROP));
-
- String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
- con.setRequestProperty ("Authorization", basicAuth);
- con.setRequestMethod(rt.getReqMethod());
-
- // Add request headers
- if ("POST".equals(rt.getReqMethod()) || "PUT".equals(rt.getReqMethod()))
- {
- con.setRequestProperty("Content-type", "application/xml");
- con.setRequestProperty("Content-length",String.valueOf(sdncReqBody.length()));
- con.setDoOutput(true);
- out = new DataOutputStream(con.getOutputStream());
- out.writeBytes(sdncReqBody);
- out.flush();
- out.close();
- }
-
- //Get response
- sdncResp.setRespCode(con.getResponseCode());
- sdncResp.setRespMsg(con.getResponseMessage());
-
- if (con.getResponseCode()>= 200 && con.getResponseCode()<=299) {
- in = new BufferedReader(new InputStreamReader(con.getInputStream()));
- String inputLine;
- //Not parsing the response -it contains a responseHdr section and data section
- while ((inputLine = in.readLine()) != null) {
- response.append(inputLine);
- }
- in.close();
- }
-
- sdncResp.setSdncRespXml(response.toString());
- logger.info("{} :\n {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.name(), sdncResp.toString(), "SDNC");
- return(sdncResp);
- }
- catch (Exception e)
- {
- logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC",
- ErrorCode.BusinessProcesssError.getValue(), "Exception processing request to SDNC", e);
- //default
- sdncResp.setRespCode(HttpURLConnection.HTTP_INTERNAL_ERROR);
- String respMsg = "Error processing request to SDNC. ";
- StringBuilder sdncErrMsg = new StringBuilder();
-
- if (e instanceof java.net.SocketTimeoutException )
- {
- sdncResp.setRespCode(HttpURLConnection.HTTP_CLIENT_TIMEOUT);
- respMsg = "Request to SDNC timed out. ";
- }
- if (con != null)
- {
- try { //e1
- if (con.getResponseCode() != HttpURLConnection.HTTP_OK) //seen in SocketException connection reset
- sdncResp.setRespCode(con.getResponseCode());
- respMsg = respMsg + con.getResponseMessage() + ". ";
- InputStream is = con.getErrorStream();
- if (is != null)
- {
- XPathFactory xpathFactory = XPathFactory.newInstance();
- XPath xpath = xpathFactory.newXPath();
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setFeature (XMLConstants.FEATURE_SECURE_PROCESSING, true);
- dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
- dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
- DocumentBuilder db;
- Document doc = null;
- try { //e2
- db = dbf.newDocumentBuilder();
- doc = db.parse(is);
- NodeList errors = (NodeList)xpath.evaluate("errors/error", doc, XPathConstants.NODESET);
- for (int i = 0; i < errors.getLength(); i++)
- {
- Element error = (Element) errors.item(i);
- String eType = null;
- try {
- eType = xpath.evaluate("error-type", error);
- sdncErrMsg = new StringBuilder(". SDNC Returned-[error-type:" + eType);
- } catch (Exception e3) {
- logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-type",
- error.toString(), "SDNC", ErrorCode.DataError.getValue(), EXCEPTION_MSG, e3);
- }
-
- String eTag = null;
- try {
- eTag = xpath.evaluate( "error-tag", error);
- sdncErrMsg.append(", error-tag:").append(eTag);
- } catch (Exception e3) {
- logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-tag",
- error.toString(), "SDNC", ErrorCode.DataError.getValue(), EXCEPTION_MSG, e3);
- }
-
- String eMsg = null;
- try {
- eMsg = xpath.evaluate("error-message", error);
- sdncErrMsg.append(", error-message:").append(eMsg).append("]");
- } catch (Exception e3) {
- logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-message", error.toString(),
- "SDNC", ErrorCode.DataError.getValue(), EXCEPTION_MSG, e3);
- }
- }
- } catch (Exception e2) {
- logger.error("{} {} {} {}", MessageEnum.RA_ANALYZE_ERROR_EXC.toString(), "SDNC",
- ErrorCode.DataError.getValue(), "Exception while analyse error", e2);
- }
- } //is != null
- } catch (Exception e1) {
- logger.error("{} {} {} {}", MessageEnum.RA_ERROR_GET_RESPONSE_SDNC.toString(), "SDNC",
- ErrorCode.BusinessProcesssError.getValue(), "Exception while get SDNC response", e1);
- }
- } //con != null
-
- if (e.getMessage() != null) {
+public class SDNCRestClient {
+
+ @Autowired
+ private Environment env;
+
+ @Autowired
+ private MapRequestTunables tunablesMapper;
+
+ private static Logger logger = LoggerFactory.getLogger(SDNCRestClient.class);
+
+ private static final String EXCEPTION_MSG = "Exception while evaluate xpath";
+ private static final String MSO_INTERNAL_ERROR = "MsoInternalError";
+ private static final String CAMUNDA = "Camunda";
+
+ @Async
+ public void executeRequest(SDNCAdapterRequest bpelRequest) {
+
+ logger.debug("BPEL Request:" + bpelRequest.toString());
+
+ // Added delay to allow completion of create request to SDNC
+ // before executing activate of create request.
+ try {
+ Thread.sleep(5000);
+ } catch (InterruptedException e) {
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "SDNC",
+ ErrorCode.UnknownError.getValue(), "Exception processing request to SDNC", e);
+
+ Thread.currentThread().interrupt();
+ }
+
+ String action = bpelRequest.getRequestHeader().getSvcAction();
+ String operation = bpelRequest.getRequestHeader().getSvcOperation();
+ String bpelReqId = bpelRequest.getRequestHeader().getRequestId();
+ String callbackUrl = bpelRequest.getRequestHeader().getCallbackUrl();
+
+ String sdncReqBody = null;
+
+ RequestTunables rt = new RequestTunables(bpelReqId, bpelRequest.getRequestHeader().getMsoAction(),
+ bpelRequest.getRequestHeader().getSvcOperation(), bpelRequest.getRequestHeader().getSvcAction());
+ rt = tunablesMapper.setTunables(rt);
+ rt.setSdncaNotificationUrl(env.getProperty(Constants.MY_URL_PROP));
+
+
+ if ("POST".equals(rt.getReqMethod())) {
+ Node node = (Node) bpelRequest.getRequestData();
+ Document reqDoc = node.getOwnerDocument();
+ sdncReqBody = Utils.genSdncReq(reqDoc, rt);
+ } else if ("PUT".equals(rt.getReqMethod())) {
+ Node node = (Node) bpelRequest.getRequestData();
+ Document reqDoc = node.getOwnerDocument();
+ sdncReqBody = Utils.genSdncPutReq(reqDoc, rt);
+ }
+ long sdncStartTime = System.currentTimeMillis();
+ SDNCResponse sdncResp = getSdncResp(sdncReqBody, rt);
+ logger.debug("Got the SDNC Response: {}", sdncResp.getSdncRespXml());
+ long bpelStartTime = System.currentTimeMillis();
+ sendRespToBpel(callbackUrl, sdncResp);
+ return;
+ }
+
+ public SDNCResponse getSdncResp(String sdncReqBody, RequestTunables rt) {
+
+ URL url;
+ HttpURLConnection con = null;
+ DataOutputStream out = null;
+ BufferedReader in = null;
+ SDNCResponse sdncResp = new SDNCResponse(rt.getReqId());
+ StringBuilder response = new StringBuilder();
+
+ logger.info("{} :\n {} {}", MessageEnum.RA_SEND_REQUEST_SDNC.name(), rt.toString(), "SDNC");
+ logger.trace("SDNC Request Body:{} \n", sdncReqBody);
+
+ try {
+
+ url = new URL(rt.getSdncUrl());
+
+ con = (HttpURLConnection) url.openConnection();
+ con.setConnectTimeout(Integer.parseInt(env.getProperty(Constants.SDNC_CONNECTTIME_PROP)));
+ con.setReadTimeout(Integer.parseInt(rt.getTimeout()));
+ con.setRequestProperty("Accept", "application/yang.data+xml"); // for response in xml
+ String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.SDNC_AUTH_PROP),
+ env.getProperty(Constants.ENCRYPTION_KEY_PROP));
+
+ String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
+ con.setRequestProperty("Authorization", basicAuth);
+ con.setRequestMethod(rt.getReqMethod());
+
+ // Add request headers
+ if ("POST".equals(rt.getReqMethod()) || "PUT".equals(rt.getReqMethod())) {
+ con.setRequestProperty("Content-type", "application/xml");
+ con.setRequestProperty("Content-length", String.valueOf(sdncReqBody.length()));
+ con.setDoOutput(true);
+ out = new DataOutputStream(con.getOutputStream());
+ out.writeBytes(sdncReqBody);
+ out.flush();
+ out.close();
+ }
+
+ // Get response
+ sdncResp.setRespCode(con.getResponseCode());
+ sdncResp.setRespMsg(con.getResponseMessage());
+
+ if (con.getResponseCode() >= 200 && con.getResponseCode() <= 299) {
+ in = new BufferedReader(new InputStreamReader(con.getInputStream()));
+ String inputLine;
+ // Not parsing the response -it contains a responseHdr section and data section
+ while ((inputLine = in.readLine()) != null) {
+ response.append(inputLine);
+ }
+ in.close();
+ }
+
+ sdncResp.setSdncRespXml(response.toString());
+ logger.info("{} :\n {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.name(), sdncResp.toString(), "SDNC");
+ return (sdncResp);
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception processing request to SDNC", e);
+ // default
+ sdncResp.setRespCode(HttpURLConnection.HTTP_INTERNAL_ERROR);
+ String respMsg = "Error processing request to SDNC. ";
+ StringBuilder sdncErrMsg = new StringBuilder();
+
+ if (e instanceof java.net.SocketTimeoutException) {
+ sdncResp.setRespCode(HttpURLConnection.HTTP_CLIENT_TIMEOUT);
+ respMsg = "Request to SDNC timed out. ";
+ }
+ if (con != null) {
+ try { // e1
+ if (con.getResponseCode() != HttpURLConnection.HTTP_OK) // seen in SocketException connection reset
+ sdncResp.setRespCode(con.getResponseCode());
+ respMsg = respMsg + con.getResponseMessage() + ". ";
+ InputStream is = con.getErrorStream();
+ if (is != null) {
+ XPathFactory xpathFactory = XPathFactory.newInstance();
+ XPath xpath = xpathFactory.newXPath();
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ DocumentBuilder db;
+ Document doc = null;
+ try { // e2
+ db = dbf.newDocumentBuilder();
+ doc = db.parse(is);
+ NodeList errors = (NodeList) xpath.evaluate("errors/error", doc, XPathConstants.NODESET);
+ for (int i = 0; i < errors.getLength(); i++) {
+ Element error = (Element) errors.item(i);
+ String eType = null;
+ try {
+ eType = xpath.evaluate("error-type", error);
+ sdncErrMsg = new StringBuilder(". SDNC Returned-[error-type:" + eType);
+ } catch (Exception e3) {
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(),
+ "error-type", error.toString(), "SDNC", ErrorCode.DataError.getValue(),
+ EXCEPTION_MSG, e3);
+ }
+
+ String eTag = null;
+ try {
+ eTag = xpath.evaluate("error-tag", error);
+ sdncErrMsg.append(", error-tag:").append(eTag);
+ } catch (Exception e3) {
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(),
+ "error-tag", error.toString(), "SDNC", ErrorCode.DataError.getValue(),
+ EXCEPTION_MSG, e3);
+ }
+
+ String eMsg = null;
+ try {
+ eMsg = xpath.evaluate("error-message", error);
+ sdncErrMsg.append(", error-message:").append(eMsg).append("]");
+ } catch (Exception e3) {
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(),
+ "error-message", error.toString(), "SDNC", ErrorCode.DataError.getValue(),
+ EXCEPTION_MSG, e3);
+ }
+ }
+ } catch (Exception e2) {
+ logger.error("{} {} {} {}", MessageEnum.RA_ANALYZE_ERROR_EXC.toString(), "SDNC",
+ ErrorCode.DataError.getValue(), "Exception while analyse error", e2);
+ }
+ } // is != null
+ } catch (Exception e1) {
+ logger.error("{} {} {} {}", MessageEnum.RA_ERROR_GET_RESPONSE_SDNC.toString(), "SDNC",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception while get SDNC response", e1);
+ }
+ } // con != null
+
+ if (e.getMessage() != null) {
respMsg = respMsg + e.getMessage();
}
respMsg = respMsg + sdncErrMsg;
- sdncResp.setRespMsg(respMsg);
+ sdncResp.setRespMsg(respMsg);
- logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC",
- ErrorCode.AvailabilityError.getValue(), "Exception while communicate with SDNC", e);
+ logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC",
+ ErrorCode.AvailabilityError.getValue(), "Exception while communicate with SDNC", e);
- return sdncResp;
- }
- finally
- {
- if (con != null) {
+ return sdncResp;
+ } finally {
+ if (con != null) {
con.disconnect();
}
- }
- }
-
- public void sendRespToBpel(String bpelUrl, SDNCResponse sdncResp)
- {
- String error;
- try
- {
- SDNCAdapterCallbackRequest cbReq = new SDNCAdapterCallbackRequest();
- cbReq.setCallbackHeader(new CallbackHeader(sdncResp.getReqId(), Integer.toString(sdncResp.getRespCode()), sdncResp.getRespMsg()));
- if (sdncResp.getSdncRespXml() != null)
- {
- cbReq.setRequestData(sdncResp.getSdncRespXml());
- }
- logger.info("{} :\n {} {}", MessageEnum.RA_CALLBACK_BPEL.name(), cbReq.toString(), CAMUNDA);
-
- URL wsdlUrl = null;
- try {
- wsdlUrl = new URL (bpelUrl);
- } catch (MalformedURLException e1) {
- error = "Caught exception initializing Callback wsdl " + e1.getMessage();
- logger.error("{} {} {} {}", MessageEnum.RA_INIT_CALLBACK_WSDL_ERR.toString(), CAMUNDA,
- ErrorCode.DataError.getValue(), "Exception initializing Callback wsdl", e1);
-
- }
-
- SDNCCallbackAdapterService cbSvc = new SDNCCallbackAdapterService();
-
- SDNCCallbackAdapterPortType cbPort = cbSvc.getSDNCCallbackAdapterSoapHttpPort();
-
- BindingProvider bp = (BindingProvider)cbPort;
-
- if(null != wsdlUrl) {
- bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, wsdlUrl.toExternalForm());
- }
- else {
- logger.debug("wsdlUrl is NULL:");
- }
-
- //authentication
- try
- {
- Map<String, Object> reqCtx = bp.getRequestContext();
- Map<String, List<String>> headers = new HashMap<>();
- String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.BPEL_AUTH_PROP), env.getProperty(Constants.ENCRYPTION_KEY_PROP));
-
- String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
- reqCtx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
- headers.put ("Authorization", Collections.singletonList(basicAuth));
- }
- catch (Exception e2) {
- error = "Unable to set authorization in callback request " + e2.getMessage();
- logger.error("{} {} {} {}", MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA,
- ErrorCode.BusinessProcesssError.getValue(),
- "Exception - Unable to set authorization in callback request", e2);
-
- }
-
- logger.debug("Invoking Bpel Callback. BpelCallbackUrl:{}", bpelUrl);
- cbPort.sdncAdapterCallback(cbReq);
-
- }
- catch (Exception e)
- {
- error = "Error sending BpelCallback request" + e.getMessage();
- logger.error("Error {} - {} - {}", ErrorCode.BusinessProcesssError.getValue(),
- MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), error, e);
- }
- logger.info(MessageEnum.RA_CALLBACK_BPEL_COMPLETE.name(), CAMUNDA);
- return;
- }
+ }
+ }
+
+ public void sendRespToBpel(String bpelUrl, SDNCResponse sdncResp) {
+ String error;
+ try {
+ SDNCAdapterCallbackRequest cbReq = new SDNCAdapterCallbackRequest();
+ cbReq.setCallbackHeader(new CallbackHeader(sdncResp.getReqId(), Integer.toString(sdncResp.getRespCode()),
+ sdncResp.getRespMsg()));
+ if (sdncResp.getSdncRespXml() != null) {
+ cbReq.setRequestData(sdncResp.getSdncRespXml());
+ }
+ logger.info("{} :\n {} {}", MessageEnum.RA_CALLBACK_BPEL.name(), cbReq.toString(), CAMUNDA);
+
+ URL wsdlUrl = null;
+ try {
+ wsdlUrl = new URL(bpelUrl);
+ } catch (MalformedURLException e1) {
+ error = "Caught exception initializing Callback wsdl " + e1.getMessage();
+ logger.error("{} {} {} {}", MessageEnum.RA_INIT_CALLBACK_WSDL_ERR.toString(), CAMUNDA,
+ ErrorCode.DataError.getValue(), "Exception initializing Callback wsdl", e1);
+
+ }
+
+ SDNCCallbackAdapterService cbSvc = new SDNCCallbackAdapterService();
+
+ SDNCCallbackAdapterPortType cbPort = cbSvc.getSDNCCallbackAdapterSoapHttpPort();
+
+ BindingProvider bp = (BindingProvider) cbPort;
+
+ if (null != wsdlUrl) {
+ bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, wsdlUrl.toExternalForm());
+ } else {
+ logger.debug("wsdlUrl is NULL:");
+ }
+
+ // authentication
+ try {
+ Map<String, Object> reqCtx = bp.getRequestContext();
+ Map<String, List<String>> headers = new HashMap<>();
+ String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.BPEL_AUTH_PROP),
+ env.getProperty(Constants.ENCRYPTION_KEY_PROP));
+
+ String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
+ reqCtx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
+ headers.put("Authorization", Collections.singletonList(basicAuth));
+ } catch (Exception e2) {
+ error = "Unable to set authorization in callback request " + e2.getMessage();
+ logger.error("{} {} {} {}", MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA,
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Exception - Unable to set authorization in callback request", e2);
+
+ }
+
+ logger.debug("Invoking Bpel Callback. BpelCallbackUrl:{}", bpelUrl);
+ cbPort.sdncAdapterCallback(cbReq);
+
+ } catch (Exception e) {
+ error = "Error sending BpelCallback request" + e.getMessage();
+ logger.error("Error {} - {} - {}", ErrorCode.BusinessProcesssError.getValue(),
+ MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), error, e);
+ }
+ logger.info(MessageEnum.RA_CALLBACK_BPEL_COMPLETE.name(), CAMUNDA);
+ return;
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java
index daa83d27f8..52164bdac7 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java
@@ -24,7 +24,6 @@ package org.onap.so.adapters.sdnc.impl;
import java.io.StringWriter;
-
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
@@ -32,7 +31,6 @@ import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
-
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.slf4j.Logger;
@@ -41,167 +39,162 @@ import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
+
public class Utils {
- private static Logger logger = LoggerFactory.getLogger(Utils.class);
-
- private Utils() {
- }
-
- public static String genSdncReq(Document reqDoc, RequestTunables rt) {
- try {
-
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- DocumentBuilder db = dbf.newDocumentBuilder();
-
- //NewDoc for output
- //Root
- Document newdoc = db.newDocument();
- Element root = newdoc.createElementNS(rt.getNamespace(), "input");
- newdoc.appendChild(root);
-
- //Header
- Element hdr = newdoc.createElement(rt.getHeaderName());
- root.appendChild(hdr);
-
- String elemData = rt.getReqId();
- Element hdrChild;
- if (elemData != null && elemData.length() > 0)
- {
- hdrChild = newdoc.createElement("svc-request-id");
- hdrChild.appendChild(newdoc.createTextNode(elemData));
- hdr.appendChild(hdrChild);
- }
-
- elemData = rt.getAction();
- if (elemData != null && elemData.length() > 0)
- {
- hdrChild = newdoc.createElement("svc-action");
- hdrChild.appendChild(newdoc.createTextNode(elemData));
- hdr.appendChild(hdrChild);
- }
-
- elemData = rt.getSdncaNotificationUrl();
- if (elemData != null && elemData.length() > 0)
- {
- hdrChild = newdoc.createElement("svc-notification-url");
- hdrChild.appendChild(newdoc.createTextNode(elemData));
- hdr.appendChild(hdrChild);
- }
-
- //RequestData
- NodeList nodes = reqDoc.getDocumentElement().getChildNodes();
- for (int i = 0; i < nodes.getLength(); i++) {
- Node n = nodes.item(i);
- Node newNode = newdoc.importNode(n, true);
- root.appendChild(newNode);
- }
-
- String s = domToStr(newdoc);
- logger.debug("Formatted SdncReq:\n", s);
- return s;
-
- } catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC",
- ErrorCode.BusinessProcesssError.getValue(), "Exception in genSdncReq", e);
- }
- return null;
- }
-
- public static String genSdncPutReq(Document reqDoc, RequestTunables rt) {
- try {
-
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- DocumentBuilder db = dbf.newDocumentBuilder();
-
- //NewDoc for output
- //Root
- Document newdoc = db.newDocument();
-
- //RequestData
- NodeList nodes = reqDoc.getDocumentElement().getChildNodes();
-
- Element root = newdoc.createElementNS(nodes.item(0).getNamespaceURI(), nodes.item(0).getNodeName());
- newdoc.appendChild(root);
-
- NodeList childNodes = nodes.item(0).getChildNodes();
- for (int i = 0; i < childNodes.getLength(); i++) {
- Node n = childNodes.item(i);
- Node newNode = newdoc.importNode(n, true);
- root.appendChild(newNode);
- }
-
- String s = domToStr(newdoc);
- logger.debug("Formatted SdncPutReq:\n {}", s);
- return s;
-
- } catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC",
- ErrorCode.DataError.getValue(), "Exception in genSdncPutReq", e);
- }
- return null;
- }
-
- public static String genMsoFailResp(SDNCResponse resp) {
- try {
-
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- DocumentBuilder db = dbf.newDocumentBuilder();
-
- //NewDoc for output
- //Root
- Document newdoc = db.newDocument();
- Element root = newdoc.createElement("output");
- newdoc.appendChild(root);
-
- Element elem1 = newdoc.createElement("svc-request-id");
- elem1.appendChild(newdoc.createTextNode(resp.getReqId()));
- root.appendChild(elem1);
-
- Element elem2 = newdoc.createElement("response-code");
- elem2.appendChild(newdoc.createTextNode(String.valueOf(resp.getRespCode())));
- root.appendChild(elem2);
-
- Element elem3 = newdoc.createElement("response-message");
- elem3.appendChild(newdoc.createTextNode(String.valueOf(resp.getRespMsg())));
- root.appendChild(elem3);
-
- String s = domToStr(newdoc);
- logger.debug("Formatted SdncReq: {}", s);
- return s;
-
- } catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_RESPONSE.toString(), "SDNC",
- ErrorCode.DataError.getValue(), "Exception in genMsoFailResp", e);
- }
- return null;
- }
-
-
- public static String domToStr(Document doc)
- {
- if (doc != null)
- {
- try {
- DOMSource ds = new DOMSource(doc);
- StringWriter sw = new StringWriter();
- StreamResult sr = new StreamResult(sw);
- TransformerFactory tf = TransformerFactory.newInstance();
- tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
- tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
- Transformer t = tf.newTransformer();
- //t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//<?xml version="1.0" encoding="UTF-8"?>
- t.transform(ds, sr);
- String s = sw.toString();
-
- // This is an awful fix for now but we don't want that xmlns="" to be generated
- s = s.replaceAll("xmlns=\"\"", "");
- return s;
- } catch (Exception e) {
- logger.error("{} {} {}", MessageEnum.RA_ERROR_CONVERT_XML2STR.toString(), ErrorCode.DataError
- .getValue(), "Exception - domToStr", e);
- }
- }
- return null;
- }
+ private static Logger logger = LoggerFactory.getLogger(Utils.class);
+
+ private Utils() {}
+
+ public static String genSdncReq(Document reqDoc, RequestTunables rt) {
+ try {
+
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ DocumentBuilder db = dbf.newDocumentBuilder();
+
+ // NewDoc for output
+ // Root
+ Document newdoc = db.newDocument();
+ Element root = newdoc.createElementNS(rt.getNamespace(), "input");
+ newdoc.appendChild(root);
+
+ // Header
+ Element hdr = newdoc.createElement(rt.getHeaderName());
+ root.appendChild(hdr);
+
+ String elemData = rt.getReqId();
+ Element hdrChild;
+ if (elemData != null && elemData.length() > 0) {
+ hdrChild = newdoc.createElement("svc-request-id");
+ hdrChild.appendChild(newdoc.createTextNode(elemData));
+ hdr.appendChild(hdrChild);
+ }
+
+ elemData = rt.getAction();
+ if (elemData != null && elemData.length() > 0) {
+ hdrChild = newdoc.createElement("svc-action");
+ hdrChild.appendChild(newdoc.createTextNode(elemData));
+ hdr.appendChild(hdrChild);
+ }
+
+ elemData = rt.getSdncaNotificationUrl();
+ if (elemData != null && elemData.length() > 0) {
+ hdrChild = newdoc.createElement("svc-notification-url");
+ hdrChild.appendChild(newdoc.createTextNode(elemData));
+ hdr.appendChild(hdrChild);
+ }
+
+ // RequestData
+ NodeList nodes = reqDoc.getDocumentElement().getChildNodes();
+ for (int i = 0; i < nodes.getLength(); i++) {
+ Node n = nodes.item(i);
+ Node newNode = newdoc.importNode(n, true);
+ root.appendChild(newNode);
+ }
+
+ String s = domToStr(newdoc);
+ logger.debug("Formatted SdncReq:\n", s);
+ return s;
+
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception in genSdncReq", e);
+ }
+ return null;
+ }
+
+ public static String genSdncPutReq(Document reqDoc, RequestTunables rt) {
+ try {
+
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ DocumentBuilder db = dbf.newDocumentBuilder();
+
+ // NewDoc for output
+ // Root
+ Document newdoc = db.newDocument();
+
+ // RequestData
+ NodeList nodes = reqDoc.getDocumentElement().getChildNodes();
+
+ Element root = newdoc.createElementNS(nodes.item(0).getNamespaceURI(), nodes.item(0).getNodeName());
+ newdoc.appendChild(root);
+
+ NodeList childNodes = nodes.item(0).getChildNodes();
+ for (int i = 0; i < childNodes.getLength(); i++) {
+ Node n = childNodes.item(i);
+ Node newNode = newdoc.importNode(n, true);
+ root.appendChild(newNode);
+ }
+
+ String s = domToStr(newdoc);
+ logger.debug("Formatted SdncPutReq:\n {}", s);
+ return s;
+
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC",
+ ErrorCode.DataError.getValue(), "Exception in genSdncPutReq", e);
+ }
+ return null;
+ }
+
+ public static String genMsoFailResp(SDNCResponse resp) {
+ try {
+
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ DocumentBuilder db = dbf.newDocumentBuilder();
+
+ // NewDoc for output
+ // Root
+ Document newdoc = db.newDocument();
+ Element root = newdoc.createElement("output");
+ newdoc.appendChild(root);
+
+ Element elem1 = newdoc.createElement("svc-request-id");
+ elem1.appendChild(newdoc.createTextNode(resp.getReqId()));
+ root.appendChild(elem1);
+
+ Element elem2 = newdoc.createElement("response-code");
+ elem2.appendChild(newdoc.createTextNode(String.valueOf(resp.getRespCode())));
+ root.appendChild(elem2);
+
+ Element elem3 = newdoc.createElement("response-message");
+ elem3.appendChild(newdoc.createTextNode(String.valueOf(resp.getRespMsg())));
+ root.appendChild(elem3);
+
+ String s = domToStr(newdoc);
+ logger.debug("Formatted SdncReq: {}", s);
+ return s;
+
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_RESPONSE.toString(), "SDNC",
+ ErrorCode.DataError.getValue(), "Exception in genMsoFailResp", e);
+ }
+ return null;
+ }
+
+
+ public static String domToStr(Document doc) {
+ if (doc != null) {
+ try {
+ DOMSource ds = new DOMSource(doc);
+ StringWriter sw = new StringWriter();
+ StreamResult sr = new StreamResult(sw);
+ TransformerFactory tf = TransformerFactory.newInstance();
+ tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
+ tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
+ Transformer t = tf.newTransformer();
+ // t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//<?xml version="1.0" encoding="UTF-8"?>
+ t.transform(ds, sr);
+ String s = sw.toString();
+
+ // This is an awful fix for now but we don't want that xmlns="" to be generated
+ s = s.replaceAll("xmlns=\"\"", "");
+ return s;
+ } catch (Exception e) {
+ logger.error("{} {} {}", MessageEnum.RA_ERROR_CONVERT_XML2STR.toString(),
+ ErrorCode.DataError.getValue(), "Exception - domToStr", e);
+ }
+ }
+ return null;
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/package-info.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/package-info.java
index bd1f34eadd..3cff95727b 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/package-info.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/package-info.java
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
-@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
+@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1",
+ elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.onap.so.adapters.sdnc;
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java
index cf52972d8f..6808230474 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java
@@ -25,7 +25,6 @@
package org.onap.so.adapters.sdnc.sdncrest;
import javax.xml.bind.DatatypeConverter;
-
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
@@ -38,7 +37,6 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.onap.so.adapters.sdnc.impl.Constants;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -52,132 +50,125 @@ import org.springframework.core.env.Environment;
*/
@Component
public class BPRestCallback {
- private static final Logger logger = LoggerFactory.getLogger(BPRestCallback.class);
-
- private static final String CAMUNDA="Camunda";
- private static final String MSO_INTERNAL_ERROR="MsoInternalError";
- @Autowired
- private Environment env;
-
- /**
- * Sends a message to the BPMN workflow message service. The URL path is
- * constructed using the specified message type and correlator.
- * @param workflowMessageUrl the base BPMN WorkflowMessage URL
- * @param messageType the message type
- * @param correlator the message correlator
- * @param message the JSON content
- * @return true if the message was consumed successfully by the endpoint
- */
- public boolean send(String workflowMessageUrl, String messageType, String correlator, String message) {
- logger.debug(getClass().getSimpleName() + ".send("
- + "workflowMessageUrl=" + workflowMessageUrl
- + " messageType=" + messageType
- + " correlator=" + correlator
- + " message=" + message
- + ")");
-
- while (workflowMessageUrl.endsWith("/")) {
- workflowMessageUrl = workflowMessageUrl.substring(0, workflowMessageUrl.length()-1);
- }
-
- String endpoint = workflowMessageUrl + "/" + SDNCAdapterUtils.encodeURLPathSegment(messageType)
- + "/" + SDNCAdapterUtils.encodeURLPathSegment(correlator);
-
- return send(endpoint, message);
- }
-
- /**
- * Sends a message to the BPMN workflow message service. The specified URL
- * must have the message type and correlator already embedded in it.
- * @param url the endpoint URL
- * @param message the JSON content
- * @return true if the message was consumed successfully by the endpoint
- */
- public boolean send(String url, String message) {
- logger.debug(getClass().getSimpleName() + ".send("
- + "url=" + url
- + " message=" + message
- + ")");
-
- logger.info("{} {} {}", MessageEnum.RA_CALLBACK_BPEL.toString(), message == null ? "[no content]" : message,
- CAMUNDA);
-
- HttpPost method = null;
- HttpResponse httpResponse = null;
-
- try {
- int timeout = 60 * 1000;
-
- RequestConfig requestConfig = RequestConfig.custom()
- .setSocketTimeout(timeout)
- .setConnectTimeout(timeout)
- .setConnectionRequestTimeout(timeout)
- .build();
-
- HttpClient client = HttpClientBuilder.create().build();
- method = new HttpPost(url);
- method.setConfig(requestConfig);
-
- if (message != null) {
- method.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));
- }
-
- boolean error = false;
-
- try {
- String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.BPEL_AUTH_PROP),
- env.getProperty(Constants.ENCRYPTION_KEY_PROP));
- String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
- method.setHeader("Authorization", authorization);
- method.setHeader(ONAPLogConstants.Headers.REQUEST_ID,MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
- method.setHeader(ONAPLogConstants.Headers.INVOCATION_ID,MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID));
- method.setHeader(ONAPLogConstants.Headers.PARTNER_NAME,"SO-SDNCAdapter");
- } catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA,
- ErrorCode.BusinessProcesssError.getValue(), "Unable to set authorization in callback request", e);
- error = true;
- }
-
- if (!error) {
- httpResponse = client.execute(method);
-
- @SuppressWarnings("unused")
- String responseContent = null;
-
- if (httpResponse.getEntity() != null) {
- responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
- }
-
- if (httpResponse.getStatusLine().getStatusCode() >= 300) {
- String msg = "Received error response to callback request: " + httpResponse.getStatusLine();
- logger.error("{} {} {} {}", MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, ErrorCode
- .BusinessProcesssError.getValue(), msg);
-
- }
- }
- return true;
- } catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA,
- ErrorCode.BusinessProcesssError.getValue(), "Error sending callback request", e);
- return false;
- } finally {
- if (httpResponse != null) {
- try {
- EntityUtils.consume(httpResponse.getEntity());
- httpResponse = null;
- } catch (Exception e) {
- logger.debug("Exception:", e);
- }
- }
-
- if (method != null) {
- try {
- method.reset();
- } catch (Exception e) {
- logger.debug("Exception:", e);
- }
- }
- logger.info("{} {}", MessageEnum.RA_CALLBACK_BPEL_COMPLETE.toString(), CAMUNDA);
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(BPRestCallback.class);
+
+ private static final String CAMUNDA = "Camunda";
+ private static final String MSO_INTERNAL_ERROR = "MsoInternalError";
+ @Autowired
+ private Environment env;
+
+ /**
+ * Sends a message to the BPMN workflow message service. The URL path is constructed using the specified message
+ * type and correlator.
+ *
+ * @param workflowMessageUrl the base BPMN WorkflowMessage URL
+ * @param messageType the message type
+ * @param correlator the message correlator
+ * @param message the JSON content
+ * @return true if the message was consumed successfully by the endpoint
+ */
+ public boolean send(String workflowMessageUrl, String messageType, String correlator, String message) {
+ logger.debug(getClass().getSimpleName() + ".send(" + "workflowMessageUrl=" + workflowMessageUrl
+ + " messageType=" + messageType + " correlator=" + correlator + " message=" + message + ")");
+
+ while (workflowMessageUrl.endsWith("/")) {
+ workflowMessageUrl = workflowMessageUrl.substring(0, workflowMessageUrl.length() - 1);
+ }
+
+ String endpoint = workflowMessageUrl + "/" + SDNCAdapterUtils.encodeURLPathSegment(messageType) + "/"
+ + SDNCAdapterUtils.encodeURLPathSegment(correlator);
+
+ return send(endpoint, message);
+ }
+
+ /**
+ * Sends a message to the BPMN workflow message service. The specified URL must have the message type and correlator
+ * already embedded in it.
+ *
+ * @param url the endpoint URL
+ * @param message the JSON content
+ * @return true if the message was consumed successfully by the endpoint
+ */
+ public boolean send(String url, String message) {
+ logger.debug(getClass().getSimpleName() + ".send(" + "url=" + url + " message=" + message + ")");
+
+ logger.info("{} {} {}", MessageEnum.RA_CALLBACK_BPEL.toString(), message == null ? "[no content]" : message,
+ CAMUNDA);
+
+ HttpPost method = null;
+ HttpResponse httpResponse = null;
+
+ try {
+ int timeout = 60 * 1000;
+
+ RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
+ .setConnectionRequestTimeout(timeout).build();
+
+ HttpClient client = HttpClientBuilder.create().build();
+ method = new HttpPost(url);
+ method.setConfig(requestConfig);
+
+ if (message != null) {
+ method.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));
+ }
+
+ boolean error = false;
+
+ try {
+ String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.BPEL_AUTH_PROP),
+ env.getProperty(Constants.ENCRYPTION_KEY_PROP));
+ String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
+ method.setHeader("Authorization", authorization);
+ method.setHeader(ONAPLogConstants.Headers.REQUEST_ID, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
+ method.setHeader(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID));
+ method.setHeader(ONAPLogConstants.Headers.PARTNER_NAME, "SO-SDNCAdapter");
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA,
+ ErrorCode.BusinessProcesssError.getValue(), "Unable to set authorization in callback request",
+ e);
+ error = true;
+ }
+
+ if (!error) {
+ httpResponse = client.execute(method);
+
+ @SuppressWarnings("unused")
+ String responseContent = null;
+
+ if (httpResponse.getEntity() != null) {
+ responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
+ }
+
+ if (httpResponse.getStatusLine().getStatusCode() >= 300) {
+ String msg = "Received error response to callback request: " + httpResponse.getStatusLine();
+ logger.error("{} {} {} {}", MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA,
+ ErrorCode.BusinessProcesssError.getValue(), msg);
+
+ }
+ }
+ return true;
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA,
+ ErrorCode.BusinessProcesssError.getValue(), "Error sending callback request", e);
+ return false;
+ } finally {
+ if (httpResponse != null) {
+ try {
+ EntityUtils.consume(httpResponse.getEntity());
+ httpResponse = null;
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ }
+ }
+
+ if (method != null) {
+ try {
+ method.reset();
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ }
+ }
+ logger.info("{} {}", MessageEnum.RA_CALLBACK_BPEL_COMPLETE.toString(), CAMUNDA);
+ }
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java
index d4c2c57510..70943c206f 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java
@@ -27,7 +27,6 @@ import org.onap.so.adapters.sdnc.exception.SDNCAdapterException;
import org.onap.so.adapters.sdnc.impl.Constants;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -36,83 +35,83 @@ import org.springframework.stereotype.Component;
@Component
public class MapTypedRequestTunablesData {
-
- private static Logger logger = LoggerFactory.getLogger(MapTypedRequestTunablesData.class);
-
- private static final String MISSING_CONFIGURATION_ERROR_MSG= "Missing configuration for: ";
- private static final String MISSING_CONFIG_PARAM_ERROR_MSG="Missing config param";
- private static final String MSO_INTERNAL_ERROR="MsoInternalError";
-
- @Autowired
- private Environment env;
-
-
- public TypedRequestTunables setTunables(TypedRequestTunables reqTunableOriginal) throws SDNCAdapterException {
- TypedRequestTunables reqTunable = new TypedRequestTunables(reqTunableOriginal);
-
- String error;
- String value = env.getProperty(reqTunable.getKey().toLowerCase(), "");
-
- if ("".equals(value)) {
- error= MISSING_CONFIGURATION_ERROR_MSG + reqTunable.getKey();
- logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), reqTunable.getKey(), "SDNC",
- ErrorCode.DataError.getValue(), MISSING_CONFIG_PARAM_ERROR_MSG);
-
- throw new SDNCAdapterException(error);
- }
-
- String[] parts = value.split("\\|");
-
- if (parts.length != 5) {
- error="Invalid configuration for: " + reqTunable.getKey();
- logger.error("{} {} {} {} {} {}", MessageEnum.RA_SDNC_INVALID_CONFIG.toString(), reqTunable.getKey(), value, "SDNC",
- ErrorCode.DataError.getValue(), "Invalid config");
- throw new SDNCAdapterException(error);
- }
-
- reqTunable.setReqMethod(parts[0]);
- logger.trace("Request Method is set to: {}", reqTunable.getReqMethod());
-
- reqTunable.setTimeout(parts[1]);
- logger.trace("Timeout is set to: {}", reqTunable.getTimeout());
-
- String urlPropKey = Constants.REQUEST_TUNABLES + "." + parts[2];
- reqTunable.setSdncUrl(env.getProperty(urlPropKey, ""));
-
- if ("".equals(reqTunable.getSdncUrl())) {
- error=MISSING_CONFIGURATION_ERROR_MSG + urlPropKey;
- logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), urlPropKey, "SDNC",
- ErrorCode.DataError.getValue(), MISSING_CONFIG_PARAM_ERROR_MSG);
-
- throw new SDNCAdapterException(error);
- }
-
- logger.trace("SDNC Url is set to: {}", reqTunable.getSdncUrl());
-
- reqTunable.setHeaderName(parts[3]);
- logger.trace("Header Name is set to: {}", reqTunable.getHeaderName());
-
- reqTunable.setNamespace(parts[4]);
- logger.trace("Namespace is set to: {}", reqTunable.getNamespace());
-
- reqTunable.setMyUrl(env.getProperty(Constants.MY_URL_PROP, ""));
-
- if ("".equals(reqTunable.getMyUrl())) {
- error=MISSING_CONFIGURATION_ERROR_MSG + Constants.MY_URL_PROP;
- logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), Constants.MY_URL_PROP, "SDNC",
- ErrorCode.DataError.getValue(), MISSING_CONFIG_PARAM_ERROR_MSG);
-
- throw new SDNCAdapterException(error);
- }
-
- while (reqTunable.getMyUrl().endsWith("/")) {
- reqTunable.setMyUrl(reqTunable.getMyUrl().substring(0, reqTunable.getMyUrl().length()-1));
- }
-
- reqTunable.setMyUrl(reqTunable.getMyUrl().concat(reqTunable.getMyUrlSuffix()));
-
- logger.debug(reqTunable.toString());
- return reqTunable;
- }
+
+ private static Logger logger = LoggerFactory.getLogger(MapTypedRequestTunablesData.class);
+
+ private static final String MISSING_CONFIGURATION_ERROR_MSG = "Missing configuration for: ";
+ private static final String MISSING_CONFIG_PARAM_ERROR_MSG = "Missing config param";
+ private static final String MSO_INTERNAL_ERROR = "MsoInternalError";
+
+ @Autowired
+ private Environment env;
+
+
+ public TypedRequestTunables setTunables(TypedRequestTunables reqTunableOriginal) throws SDNCAdapterException {
+ TypedRequestTunables reqTunable = new TypedRequestTunables(reqTunableOriginal);
+
+ String error;
+ String value = env.getProperty(reqTunable.getKey().toLowerCase(), "");
+
+ if ("".equals(value)) {
+ error = MISSING_CONFIGURATION_ERROR_MSG + reqTunable.getKey();
+ logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), reqTunable.getKey(),
+ "SDNC", ErrorCode.DataError.getValue(), MISSING_CONFIG_PARAM_ERROR_MSG);
+
+ throw new SDNCAdapterException(error);
+ }
+
+ String[] parts = value.split("\\|");
+
+ if (parts.length != 5) {
+ error = "Invalid configuration for: " + reqTunable.getKey();
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_SDNC_INVALID_CONFIG.toString(), reqTunable.getKey(), value,
+ "SDNC", ErrorCode.DataError.getValue(), "Invalid config");
+ throw new SDNCAdapterException(error);
+ }
+
+ reqTunable.setReqMethod(parts[0]);
+ logger.trace("Request Method is set to: {}", reqTunable.getReqMethod());
+
+ reqTunable.setTimeout(parts[1]);
+ logger.trace("Timeout is set to: {}", reqTunable.getTimeout());
+
+ String urlPropKey = Constants.REQUEST_TUNABLES + "." + parts[2];
+ reqTunable.setSdncUrl(env.getProperty(urlPropKey, ""));
+
+ if ("".equals(reqTunable.getSdncUrl())) {
+ error = MISSING_CONFIGURATION_ERROR_MSG + urlPropKey;
+ logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), urlPropKey, "SDNC",
+ ErrorCode.DataError.getValue(), MISSING_CONFIG_PARAM_ERROR_MSG);
+
+ throw new SDNCAdapterException(error);
+ }
+
+ logger.trace("SDNC Url is set to: {}", reqTunable.getSdncUrl());
+
+ reqTunable.setHeaderName(parts[3]);
+ logger.trace("Header Name is set to: {}", reqTunable.getHeaderName());
+
+ reqTunable.setNamespace(parts[4]);
+ logger.trace("Namespace is set to: {}", reqTunable.getNamespace());
+
+ reqTunable.setMyUrl(env.getProperty(Constants.MY_URL_PROP, ""));
+
+ if ("".equals(reqTunable.getMyUrl())) {
+ error = MISSING_CONFIGURATION_ERROR_MSG + Constants.MY_URL_PROP;
+ logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), Constants.MY_URL_PROP,
+ "SDNC", ErrorCode.DataError.getValue(), MISSING_CONFIG_PARAM_ERROR_MSG);
+
+ throw new SDNCAdapterException(error);
+ }
+
+ while (reqTunable.getMyUrl().endsWith("/")) {
+ reqTunable.setMyUrl(reqTunable.getMyUrl().substring(0, reqTunable.getMyUrl().length() - 1));
+ }
+
+ reqTunable.setMyUrl(reqTunable.getMyUrl().concat(reqTunable.getMyUrlSuffix()));
+
+ logger.debug(reqTunable.toString());
+ return reqTunable;
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCAdapterUtils.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCAdapterUtils.java
index 8cafbda325..eaea15cf0d 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCAdapterUtils.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCAdapterUtils.java
@@ -25,7 +25,6 @@ package org.onap.so.adapters.sdnc.sdncrest;
import java.util.ArrayList;
import java.util.List;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriUtils;
@@ -38,35 +37,36 @@ import org.w3c.dom.NodeList;
*/
public final class SDNCAdapterUtils {
private static final Logger logger = LoggerFactory.getLogger(SDNCAdapterUtils.class);
+
/**
* Instantiation is not allowed.
*/
- private SDNCAdapterUtils() {
- }
-
+ private SDNCAdapterUtils() {}
+
/**
- * Returns a node's child elements in a list.
- */
- public static List<Element> childElements(Node node) {
- List<Element> elements = new ArrayList<>();
+ * Returns a node's child elements in a list.
+ */
+ public static List<Element> childElements(Node node) {
+ List<Element> elements = new ArrayList<>();
- NodeList nodeList = node.getChildNodes();
- for (int i = 0; i < nodeList.getLength(); i++) {
- Node child = nodeList.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- elements.add((Element) child);
- }
- }
+ NodeList nodeList = node.getChildNodes();
+ for (int i = 0; i < nodeList.getLength(); i++) {
+ Node child = nodeList.item(i);
+ if (child.getNodeType() == Node.ELEMENT_NODE) {
+ elements.add((Element) child);
+ }
+ }
- return elements;
- }
+ return elements;
+ }
- /**
- * Encodes a URL path segment according to RFC 3986 Section 2.
- * @param pathSegment the path segment to encode
- * @return the encoded path segment
- */
- public static String encodeURLPathSegment(String pathSegment) {
- return UriUtils.encodePathSegment(pathSegment, "UTF-8");
- }
+ /**
+ * Encodes a URL path segment according to RFC 3986 Section 2.
+ *
+ * @param pathSegment the path segment to encode
+ * @return the encoded path segment
+ */
+ public static String encodeURLPathSegment(String pathSegment) {
+ return UriUtils.encodePathSegment(pathSegment, "UTF-8");
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java
index 7cc5b8e14e..a7c65d87a4 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java
@@ -27,7 +27,6 @@ package org.onap.so.adapters.sdnc.sdncrest;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
-
import javax.xml.XMLConstants;
import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.DocumentBuilderFactory;
@@ -35,7 +34,6 @@ import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
-
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
@@ -54,7 +52,6 @@ import org.onap.so.adapters.sdncrest.SDNCErrorCommon;
import org.onap.so.adapters.sdncrest.SDNCResponseCommon;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -71,263 +68,260 @@ import org.springframework.core.env.Environment;
*/
@Component
public abstract class SDNCConnector {
- private static final Logger logger = LoggerFactory.getLogger(SDNCConnector.class);
-
- private static final String MSO_INTERNAL_ERROR="MsoInternalError";
- private static final String XPATH_EXCEPTION="XPath Exception";
- @Autowired
- private Environment env;
-
- public SDNCResponseCommon send(String content, TypedRequestTunables rt) {
- logger.debug("SDNC URL: {}", rt.getSdncUrl());
- logger.debug("SDNC Request Body:\n {}", content);
-
- HttpRequestBase method = null;
- HttpResponse httpResponse = null;
-
- try {
- int timeout = Integer.parseInt(rt.getTimeout());
-
- RequestConfig requestConfig = RequestConfig.custom()
- .setSocketTimeout(timeout)
- .setConnectTimeout(timeout)
- .setConnectionRequestTimeout(timeout)
- .build();
-
- HttpClient client = HttpClientBuilder.create().build();
-
- if ("POST".equals(rt.getReqMethod())) {
- HttpPost httpPost = new HttpPost(rt.getSdncUrl());
- httpPost.setConfig(requestConfig);
- httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_XML));
- method = httpPost;
- } else if ("PUT".equals(rt.getReqMethod())) {
- HttpPut httpPut = new HttpPut(rt.getSdncUrl());
- httpPut.setConfig(requestConfig);
- httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_XML));
- method = httpPut;
- } else if ("GET".equals(rt.getReqMethod())) {
- HttpGet httpGet = new HttpGet(rt.getSdncUrl());
- httpGet.setConfig(requestConfig);
- method = httpGet;
- } else if ("DELETE".equals(rt.getReqMethod())) {
- HttpDelete httpDelete = new HttpDelete(rt.getSdncUrl());
- httpDelete.setConfig(requestConfig);
- method = httpDelete;
- }
-
-
- String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.SDNC_AUTH_PROP),
- env.getProperty(Constants.ENCRYPTION_KEY_PROP));
- String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
- if(null != method) {
- method.setHeader("Authorization", authorization);
- method.setHeader("Accept", "application/yang.data+xml");
- }
- else {
- logger.debug("method is NULL:");
- }
-
-
-
- httpResponse = client.execute(method);
-
- String responseContent = null;
- if (httpResponse.getEntity() != null) {
- responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
- }
-
- int statusCode = httpResponse.getStatusLine().getStatusCode();
- String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
-
- logger.debug("SDNC Response: {} {}", statusCode,
- statusMessage + (responseContent == null ? "" : System.lineSeparator() + responseContent));
-
- if (httpResponse.getStatusLine().getStatusCode() >= 300) {
- String errMsg = "SDNC returned " + statusCode + " " + statusMessage;
-
- String errors = analyzeErrors(responseContent);
- if (errors != null) {
- errMsg += " " + errors;
- }
-
- logError(errMsg);
-
- return createErrorResponse(statusCode, errMsg, rt);
- }
-
- httpResponse = null;
-
- if(null != method) {
- method.reset();
- }
- else {
+ private static final Logger logger = LoggerFactory.getLogger(SDNCConnector.class);
+
+ private static final String MSO_INTERNAL_ERROR = "MsoInternalError";
+ private static final String XPATH_EXCEPTION = "XPath Exception";
+ @Autowired
+ private Environment env;
+
+ public SDNCResponseCommon send(String content, TypedRequestTunables rt) {
+ logger.debug("SDNC URL: {}", rt.getSdncUrl());
+ logger.debug("SDNC Request Body:\n {}", content);
+
+ HttpRequestBase method = null;
+ HttpResponse httpResponse = null;
+
+ try {
+ int timeout = Integer.parseInt(rt.getTimeout());
+
+ RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
+ .setConnectionRequestTimeout(timeout).build();
+
+ HttpClient client = HttpClientBuilder.create().build();
+
+ if ("POST".equals(rt.getReqMethod())) {
+ HttpPost httpPost = new HttpPost(rt.getSdncUrl());
+ httpPost.setConfig(requestConfig);
+ httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_XML));
+ method = httpPost;
+ } else if ("PUT".equals(rt.getReqMethod())) {
+ HttpPut httpPut = new HttpPut(rt.getSdncUrl());
+ httpPut.setConfig(requestConfig);
+ httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_XML));
+ method = httpPut;
+ } else if ("GET".equals(rt.getReqMethod())) {
+ HttpGet httpGet = new HttpGet(rt.getSdncUrl());
+ httpGet.setConfig(requestConfig);
+ method = httpGet;
+ } else if ("DELETE".equals(rt.getReqMethod())) {
+ HttpDelete httpDelete = new HttpDelete(rt.getSdncUrl());
+ httpDelete.setConfig(requestConfig);
+ method = httpDelete;
+ }
+
+
+ String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.SDNC_AUTH_PROP),
+ env.getProperty(Constants.ENCRYPTION_KEY_PROP));
+ String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
+ if (null != method) {
+ method.setHeader("Authorization", authorization);
+ method.setHeader("Accept", "application/yang.data+xml");
+ } else {
logger.debug("method is NULL:");
}
- method = null;
-
- logger.info("{} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), responseContent, "SDNC");
- return createResponseFromContent(statusCode, statusMessage, responseContent, rt);
-
- } catch (SocketTimeoutException | ConnectTimeoutException e) {
- String errMsg = "Request to SDNC timed out";
- logError(errMsg, e);
- return createErrorResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg, rt);
-
- } catch (Exception e) {
- String errMsg = "Error processing request to SDNC";
- logError(errMsg, e);
- return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg, rt);
-
- } finally {
- if (httpResponse != null) {
- try {
- EntityUtils.consume(httpResponse.getEntity());
- } catch (Exception e) {
- logger.debug("Exception:", e);
- }
- }
-
- if (method != null) {
- try {
- method.reset();
- } catch (Exception e) {
- logger.debug("Exception:", e);
- }
- }
- }
- }
-
- protected void logError(String errMsg) {
- logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC",
- ErrorCode.AvailabilityError.getValue(), errMsg);
- }
-
- protected void logError(String errMsg, Throwable t) {
- logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC",
- ErrorCode.AvailabilityError.getValue(), errMsg, t);
- }
-
- /**
- * Generates a response object from content received from SDNC. The response
- * object may be a success response object or an error response object. This
- * method must be overridden by the subclass to return the correct object type.
- * @param statusCode the response status code from SDNC (e.g. 200)
- * @param statusMessage the response status message from SDNC (e.g. "OK")
- * @param responseContent the body of the response from SDNC (possibly null)
- * @param rt request tunables
- * @return a response object
- */
- protected abstract SDNCResponseCommon createResponseFromContent(int statusCode,
- String statusMessage, String responseContent, TypedRequestTunables rt);
-
- /**
- * Generates an error response object. This method must be overridden by the
- * subclass to return the correct object type.
- * @param statusCode the response status code (from SDNC, or internally generated)
- * @param errMsg the error message (normally a verbose explanation of the error)
- * @param rt request tunables
- * @return an error response object
- */
- protected abstract SDNCErrorCommon createErrorResponse(int statusCode,
- String errMsg, TypedRequestTunables rt);
-
- /**
- * Called by the send() method to analyze errors that may be encoded in the
- * content of non-2XX responses. By default, this method tries to parse the
- * content as a restconf error.
- * <pre>
- * xmlns="urn:ietf:params:xml:ns:yang:ietf-restconf"
- * </pre>
- * If an error (or errors) can be obtained from the content, then the result
- * is a string in this format:
- * <pre>
- * [error-type:TYPE, error-tag:TAG, error-message:MESSAGE] ...
- * </pre>
- * If no error could be obtained from the content, then the result is null.
- * <p>
- * The subclass can override this method to provide another implementation.
- */
- protected String analyzeErrors(String content) {
- if (content == null || content.isEmpty()) {
- return null;
- }
-
- // Confirmed with Andrew Shen on 11/1/16 that SDNC will send content like
- // this in error responses (non-2XX response codes) to "agnostic" service
- // requests.
- //
- // <errors xmlns="urn:ietf:params:xml:ns:yang:ietf-restconf">
- // <error>
- // <error-type>protocol</error-type>
- // <error-tag>malformed-message</error-tag>
- // <error-message>Error parsing input: The element type "input" must be terminated by the matching end-tag "&lt;/input&gt;".</error-message>
- // </error>
- // </errors>
-
- StringBuilder output = null;
-
- try {
- XPathFactory xpathFactory = XPathFactory.newInstance();
- XPath xpath = xpathFactory.newXPath();
- DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
- documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
- documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
- InputSource source = new InputSource(new StringReader(content));
- Document doc = documentBuilderFactory.newDocumentBuilder().parse(source);
- NodeList errors = (NodeList) xpath.evaluate("errors/error", doc, XPathConstants.NODESET);
-
- for (int i = 0; i < errors.getLength(); i++)
- {
- Element error = (Element) errors.item(i);
-
- String info = "";
-
- try {
- String errorType = xpath.evaluate("error-type", error);
- info += "error-type:" + errorType;
- } catch (XPathExpressionException e) {
- logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-type", error.toString(),
- "SDNC", ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e);
- }
-
- try {
- String errorTag = xpath.evaluate( "error-tag", error);
- if (!info.isEmpty()) {
- info += ", ";
- }
- info += "error-tag:" + errorTag;
- } catch (XPathExpressionException e) {
- logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-tag", error.toString(),
- "SDNC", ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e);
- }
-
- try {
- String errorMessage = xpath.evaluate("error-message", error);
- if (!info.isEmpty()) {
- info += ", ";
- }
- info += "error-message:" + errorMessage;
- } catch (Exception e) {
- logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-message",
- error.toString(), "SDNC", ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e);
- }
-
- if (!info.isEmpty()) {
- if (output == null) {
- output = new StringBuilder("[" + info + "]");
- } else {
- output.append(" [").append(info).append("]");
- }
- }
- }
- } catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.RA_ANALYZE_ERROR_EXC.toString(), "SDNC",
- ErrorCode.DataError.getValue(), "Exception while analyzing errors", e);
- }
-
- return output.toString();
- }
+
+
+ httpResponse = client.execute(method);
+
+ String responseContent = null;
+ if (httpResponse.getEntity() != null) {
+ responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
+ }
+
+ int statusCode = httpResponse.getStatusLine().getStatusCode();
+ String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
+
+ logger.debug("SDNC Response: {} {}", statusCode,
+ statusMessage + (responseContent == null ? "" : System.lineSeparator() + responseContent));
+
+ if (httpResponse.getStatusLine().getStatusCode() >= 300) {
+ String errMsg = "SDNC returned " + statusCode + " " + statusMessage;
+
+ String errors = analyzeErrors(responseContent);
+ if (errors != null) {
+ errMsg += " " + errors;
+ }
+
+ logError(errMsg);
+
+ return createErrorResponse(statusCode, errMsg, rt);
+ }
+
+ httpResponse = null;
+
+ if (null != method) {
+ method.reset();
+ } else {
+ logger.debug("method is NULL:");
+ }
+
+ method = null;
+
+ logger.info("{} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), responseContent, "SDNC");
+ return createResponseFromContent(statusCode, statusMessage, responseContent, rt);
+
+ } catch (SocketTimeoutException | ConnectTimeoutException e) {
+ String errMsg = "Request to SDNC timed out";
+ logError(errMsg, e);
+ return createErrorResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg, rt);
+
+ } catch (Exception e) {
+ String errMsg = "Error processing request to SDNC";
+ logError(errMsg, e);
+ return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg, rt);
+
+ } finally {
+ if (httpResponse != null) {
+ try {
+ EntityUtils.consume(httpResponse.getEntity());
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ }
+ }
+
+ if (method != null) {
+ try {
+ method.reset();
+ } catch (Exception e) {
+ logger.debug("Exception:", e);
+ }
+ }
+ }
+ }
+
+ protected void logError(String errMsg) {
+ logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC",
+ ErrorCode.AvailabilityError.getValue(), errMsg);
+ }
+
+ protected void logError(String errMsg, Throwable t) {
+ logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC",
+ ErrorCode.AvailabilityError.getValue(), errMsg, t);
+ }
+
+ /**
+ * Generates a response object from content received from SDNC. The response object may be a success response object
+ * or an error response object. This method must be overridden by the subclass to return the correct object type.
+ *
+ * @param statusCode the response status code from SDNC (e.g. 200)
+ * @param statusMessage the response status message from SDNC (e.g. "OK")
+ * @param responseContent the body of the response from SDNC (possibly null)
+ * @param rt request tunables
+ * @return a response object
+ */
+ protected abstract SDNCResponseCommon createResponseFromContent(int statusCode, String statusMessage,
+ String responseContent, TypedRequestTunables rt);
+
+ /**
+ * Generates an error response object. This method must be overridden by the subclass to return the correct object
+ * type.
+ *
+ * @param statusCode the response status code (from SDNC, or internally generated)
+ * @param errMsg the error message (normally a verbose explanation of the error)
+ * @param rt request tunables
+ * @return an error response object
+ */
+ protected abstract SDNCErrorCommon createErrorResponse(int statusCode, String errMsg, TypedRequestTunables rt);
+
+ /**
+ * Called by the send() method to analyze errors that may be encoded in the content of non-2XX responses. By
+ * default, this method tries to parse the content as a restconf error.
+ *
+ * <pre>
+ * xmlns = "urn:ietf:params:xml:ns:yang:ietf-restconf"
+ * </pre>
+ *
+ * If an error (or errors) can be obtained from the content, then the result is a string in this format:
+ *
+ * <pre>
+ * [error-type:TYPE, error-tag:TAG, error-message:MESSAGE] ...
+ * </pre>
+ *
+ * If no error could be obtained from the content, then the result is null.
+ * <p>
+ * The subclass can override this method to provide another implementation.
+ */
+ protected String analyzeErrors(String content) {
+ if (content == null || content.isEmpty()) {
+ return null;
+ }
+
+ // Confirmed with Andrew Shen on 11/1/16 that SDNC will send content like
+ // this in error responses (non-2XX response codes) to "agnostic" service
+ // requests.
+ //
+ // <errors xmlns="urn:ietf:params:xml:ns:yang:ietf-restconf">
+ // <error>
+ // <error-type>protocol</error-type>
+ // <error-tag>malformed-message</error-tag>
+ // <error-message>Error parsing input: The element type "input" must be terminated by the matching end-tag
+ // "&lt;/input&gt;".</error-message>
+ // </error>
+ // </errors>
+
+ StringBuilder output = null;
+
+ try {
+ XPathFactory xpathFactory = XPathFactory.newInstance();
+ XPath xpath = xpathFactory.newXPath();
+ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+ documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ InputSource source = new InputSource(new StringReader(content));
+ Document doc = documentBuilderFactory.newDocumentBuilder().parse(source);
+ NodeList errors = (NodeList) xpath.evaluate("errors/error", doc, XPathConstants.NODESET);
+
+ for (int i = 0; i < errors.getLength(); i++) {
+ Element error = (Element) errors.item(i);
+
+ String info = "";
+
+ try {
+ String errorType = xpath.evaluate("error-type", error);
+ info += "error-type:" + errorType;
+ } catch (XPathExpressionException e) {
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-type",
+ error.toString(), "SDNC", ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e);
+ }
+
+ try {
+ String errorTag = xpath.evaluate("error-tag", error);
+ if (!info.isEmpty()) {
+ info += ", ";
+ }
+ info += "error-tag:" + errorTag;
+ } catch (XPathExpressionException e) {
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-tag",
+ error.toString(), "SDNC", ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e);
+ }
+
+ try {
+ String errorMessage = xpath.evaluate("error-message", error);
+ if (!info.isEmpty()) {
+ info += ", ";
+ }
+ info += "error-message:" + errorMessage;
+ } catch (Exception e) {
+ logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-message",
+ error.toString(), "SDNC", ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e);
+ }
+
+ if (!info.isEmpty()) {
+ if (output == null) {
+ output = new StringBuilder("[" + info + "]");
+ } else {
+ output.append(" [").append(info).append("]");
+ }
+ }
+ }
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.RA_ANALYZE_ERROR_EXC.toString(), "SDNC",
+ ErrorCode.DataError.getValue(), "Exception while analyzing errors", e);
+ }
+
+ return output.toString();
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java
index 57051e570e..6f76ea1eab 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java
@@ -30,11 +30,9 @@ import java.net.HttpURLConnection;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
-
import org.onap.so.adapters.sdncrest.SDNCErrorCommon;
import org.onap.so.adapters.sdncrest.SDNCResponseCommon;
import org.onap.so.adapters.sdncrest.SDNCServiceError;
@@ -55,157 +53,156 @@ import org.xml.sax.SAXException;
public class SDNCServiceRequestConnector extends SDNCConnector {
private static final Logger logger = LoggerFactory.getLogger(SDNCServiceRequestConnector.class);
- @Override
- protected SDNCResponseCommon createResponseFromContent(int statusCode, String statusMessage,
- String responseContent, TypedRequestTunables rt) {
- try {
- return parseResponseContent(responseContent);
- } catch (ParseException e) {
- logger.error("Error occured:", e);
- return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage(), rt);
- }catch (Exception e) {
- logger.error("Error occured:", e);
- return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage(), rt);
- }
- }
-
- @Override
- protected SDNCErrorCommon createErrorResponse(int statusCode, String errMsg,
- TypedRequestTunables rt) {
- return new SDNCServiceError(rt.getReqId(), String.valueOf(statusCode), errMsg, "Y");
- }
-
- /**
- * Parses SDNC synchronous service response content or service notification content.
- * If the content can be parsed and contains all required elements, then an object
- * is returned. The type of the returned object depends on the response code
- * contained in the content. For 2XX response codes, an SDNCServiceResponse is
- * returned. Otherwise, an SDNCServiceError is returned. If the content cannot
- * be parsed, or if the content does not contain all required elements, a parse
- * exception is thrown. This method performs no logging or alarming.
- * @throws ParseException on error
- */
- public static SDNCResponseCommon parseResponseContent(String responseContent)
- throws ParseException,ParserConfigurationException, SAXException, IOException{
-
- // Note: this document builder is not namespace-aware, so namespaces are ignored.
- DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
- documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
- documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
- InputSource source = new InputSource(new StringReader(responseContent));
- Document doc = documentBuilderFactory.newDocumentBuilder().parse(source);
-
- // Find the configuration-response-common child under the root element.
- // The root element is expected to be an "output" element, but we don't really care.
-
- Element root = doc.getDocumentElement();
- Element configurationResponseCommon = null;
-
- for (Element child : SDNCAdapterUtils.childElements(root)) {
- if ("configuration-response-common".equals(child.getNodeName())) {
- configurationResponseCommon = child;
- break;
- }
- }
-
- if (configurationResponseCommon == null) {
- throw new ParseException("No configuration-response-common element in SDNC response", 0);
- }
-
- // Process the children of configuration-response-common.
-
- String responseCode = null;
- String responseMessage = null;
- String svcRequestId = null;
- String ackFinalIndicator = null;
- List<Element> responseParameters = new ArrayList<>();
-
- for (Element child : SDNCAdapterUtils.childElements(configurationResponseCommon)) {
- if ("response-code".equals(child.getNodeName())) {
- responseCode = child.getTextContent();
- } else if ("response-message".equals(child.getNodeName())) {
- responseMessage = child.getTextContent();
- } else if ("svc-request-id".equals(child.getNodeName())) {
- svcRequestId = child.getTextContent();
- } else if ("ack-final-indicator".equals(child.getNodeName())) {
- ackFinalIndicator = child.getTextContent();
- } else if ("response-parameters".equals(child.getNodeName())) {
- responseParameters.add(child);
- }
- }
-
- // svc-request-id is mandatory.
-
- if (svcRequestId == null || svcRequestId.isEmpty()) {
- throw new ParseException("No svc-request-id in SDNC response", 0);
- }
-
- // response-code is mandatory.
-
- if (responseCode == null || responseCode.isEmpty()) {
- throw new ParseException("No response-code in SDNC response", 0);
- }
-
- // ack-final-indicator is optional: default to "Y".
-
- if (ackFinalIndicator == null || ackFinalIndicator.trim().isEmpty()) {
- ackFinalIndicator = "Y";
- }
-
- if (!"Y".equals(ackFinalIndicator) && !"N".equals(ackFinalIndicator)) {
- throw new ParseException("Invalid ack-final-indicator in SDNC response: '" + ackFinalIndicator + "'", 0);
- }
-
- // response-message is optional. If the value is empty, omit it from the response object.
-
- if (responseMessage != null && responseMessage.isEmpty()) {
- responseMessage = null;
- }
-
- // If the response code in the message from SDNC was not 2XX, return SDNCServiceError.
-
- if (!responseCode.matches("2[0-9][0-9]") && !("0").equals(responseCode)) {
- // Not a 2XX response. Return SDNCServiceError.
- return new SDNCServiceError(svcRequestId, responseCode, responseMessage, ackFinalIndicator);
- }
-
- // Create a success response object.
-
- SDNCServiceResponse response = new SDNCServiceResponse(svcRequestId,
- responseCode, responseMessage, ackFinalIndicator);
-
- // Process any response-parameters that might be present.
-
- for (Element element : responseParameters) {
- String tagName = null;
- String tagValue = null;
-
- for (Element child : SDNCAdapterUtils.childElements(element)) {
- if ("tag-name".equals(child.getNodeName())) {
- tagName = child.getTextContent();
- } else if ("tag-value".equals(child.getNodeName())) {
- tagValue = child.getTextContent();
- }
- }
- // tag-name is mandatory
+ @Override
+ protected SDNCResponseCommon createResponseFromContent(int statusCode, String statusMessage, String responseContent,
+ TypedRequestTunables rt) {
+ try {
+ return parseResponseContent(responseContent);
+ } catch (ParseException e) {
+ logger.error("Error occured:", e);
+ return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage(), rt);
+ } catch (Exception e) {
+ logger.error("Error occured:", e);
+ return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage(), rt);
+ }
+ }
+
+ @Override
+ protected SDNCErrorCommon createErrorResponse(int statusCode, String errMsg, TypedRequestTunables rt) {
+ return new SDNCServiceError(rt.getReqId(), String.valueOf(statusCode), errMsg, "Y");
+ }
+
+ /**
+ * Parses SDNC synchronous service response content or service notification content. If the content can be parsed
+ * and contains all required elements, then an object is returned. The type of the returned object depends on the
+ * response code contained in the content. For 2XX response codes, an SDNCServiceResponse is returned. Otherwise, an
+ * SDNCServiceError is returned. If the content cannot be parsed, or if the content does not contain all required
+ * elements, a parse exception is thrown. This method performs no logging or alarming.
+ *
+ * @throws ParseException on error
+ */
+ public static SDNCResponseCommon parseResponseContent(String responseContent)
+ throws ParseException, ParserConfigurationException, SAXException, IOException {
+
+ // Note: this document builder is not namespace-aware, so namespaces are ignored.
+ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+ documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ InputSource source = new InputSource(new StringReader(responseContent));
+ Document doc = documentBuilderFactory.newDocumentBuilder().parse(source);
+
+ // Find the configuration-response-common child under the root element.
+ // The root element is expected to be an "output" element, but we don't really care.
+
+ Element root = doc.getDocumentElement();
+ Element configurationResponseCommon = null;
+
+ for (Element child : SDNCAdapterUtils.childElements(root)) {
+ if ("configuration-response-common".equals(child.getNodeName())) {
+ configurationResponseCommon = child;
+ break;
+ }
+ }
+
+ if (configurationResponseCommon == null) {
+ throw new ParseException("No configuration-response-common element in SDNC response", 0);
+ }
+
+ // Process the children of configuration-response-common.
+
+ String responseCode = null;
+ String responseMessage = null;
+ String svcRequestId = null;
+ String ackFinalIndicator = null;
+ List<Element> responseParameters = new ArrayList<>();
+
+ for (Element child : SDNCAdapterUtils.childElements(configurationResponseCommon)) {
+ if ("response-code".equals(child.getNodeName())) {
+ responseCode = child.getTextContent();
+ } else if ("response-message".equals(child.getNodeName())) {
+ responseMessage = child.getTextContent();
+ } else if ("svc-request-id".equals(child.getNodeName())) {
+ svcRequestId = child.getTextContent();
+ } else if ("ack-final-indicator".equals(child.getNodeName())) {
+ ackFinalIndicator = child.getTextContent();
+ } else if ("response-parameters".equals(child.getNodeName())) {
+ responseParameters.add(child);
+ }
+ }
- if (tagName == null) {
- throw new ParseException("Missing tag-name in SDNC response parameter", 0);
- }
+ // svc-request-id is mandatory.
+
+ if (svcRequestId == null || svcRequestId.isEmpty()) {
+ throw new ParseException("No svc-request-id in SDNC response", 0);
+ }
+
+ // response-code is mandatory.
+
+ if (responseCode == null || responseCode.isEmpty()) {
+ throw new ParseException("No response-code in SDNC response", 0);
+ }
+
+ // ack-final-indicator is optional: default to "Y".
+
+ if (ackFinalIndicator == null || ackFinalIndicator.trim().isEmpty()) {
+ ackFinalIndicator = "Y";
+ }
+
+ if (!"Y".equals(ackFinalIndicator) && !"N".equals(ackFinalIndicator)) {
+ throw new ParseException("Invalid ack-final-indicator in SDNC response: '" + ackFinalIndicator + "'", 0);
+ }
+
+ // response-message is optional. If the value is empty, omit it from the response object.
- // tag-value is optional. If absent, make it an empty string so we don't
- // end up with null values in the parameter map.
+ if (responseMessage != null && responseMessage.isEmpty()) {
+ responseMessage = null;
+ }
- if (tagValue == null) {
- tagValue = "";
+ // If the response code in the message from SDNC was not 2XX, return SDNCServiceError.
+
+ if (!responseCode.matches("2[0-9][0-9]") && !("0").equals(responseCode)) {
+ // Not a 2XX response. Return SDNCServiceError.
+ return new SDNCServiceError(svcRequestId, responseCode, responseMessage, ackFinalIndicator);
+ }
+
+ // Create a success response object.
+
+ SDNCServiceResponse response =
+ new SDNCServiceResponse(svcRequestId, responseCode, responseMessage, ackFinalIndicator);
+
+ // Process any response-parameters that might be present.
+
+ for (Element element : responseParameters) {
+ String tagName = null;
+ String tagValue = null;
+
+ for (Element child : SDNCAdapterUtils.childElements(element)) {
+ if ("tag-name".equals(child.getNodeName())) {
+ tagName = child.getTextContent();
+ } else if ("tag-value".equals(child.getNodeName())) {
+ tagValue = child.getTextContent();
}
+ }
- response.addParam(tagName, tagValue);
+ // tag-name is mandatory
+
+ if (tagName == null) {
+ throw new ParseException("Missing tag-name in SDNC response parameter", 0);
+ }
+
+ // tag-value is optional. If absent, make it an empty string so we don't
+ // end up with null values in the parameter map.
+
+ if (tagValue == null) {
+ tagValue = "";
}
- return response;
-
- }
+ response.addParam(tagName, tagValue);
+ }
+
+ return response;
+
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java
index a42e92db4b..7e82adf064 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java
@@ -23,7 +23,6 @@
package org.onap.so.adapters.sdnc.sdncrest;
import java.io.StringWriter;
-
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
@@ -32,7 +31,6 @@ import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
-
import org.apache.http.HttpStatus;
import org.onap.so.adapters.sdnc.exception.SDNCAdapterException;
import org.onap.so.adapters.sdncrest.RequestInformation;
@@ -51,171 +49,167 @@ import org.w3c.dom.Element;
@Component
public class SDNCServiceRequestTask {
- private static final Logger logger = LoggerFactory.getLogger(SDNCServiceRequestTask.class);
-
- @Autowired
- private SDNCServiceRequestConnector connector;
-
- @Autowired
- MapTypedRequestTunablesData mapTunables;
-
- @Autowired
- private BPRestCallback bpRestCallback;
-
- @Async
- public void runRequest(SDNCServiceRequest request,String msoRequestId,String msoServiceInstanceId,String myUrlSuffix)
- {
-
- String sdncRequestId = request.getSdncRequestId();
- String sdncService = request.getSdncService();
- String sdncOperation = request.getSdncOperation();
-
- TypedRequestTunables rt = new TypedRequestTunables(sdncRequestId, myUrlSuffix);
- rt.setServiceKey(sdncService, sdncOperation);
- TypedRequestTunables mappedTunables;
- try {
- mappedTunables = mapTunables.setTunables(rt);
- } catch(SDNCAdapterException e) {
- bpRestCallback.send(request.getBPNotificationUrl(), e.getMessage());
- return;
- }
- if (!mappedTunables.getError().isEmpty()) {
- // Note that the error was logged and alarmed by setTunables()
- SDNCServiceError error = new SDNCServiceError(request.getSdncRequestId(),
- String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR), mappedTunables.getError(), "Y");
- bpRestCallback.send(request.getBPNotificationUrl(), error.toJson());
- return;
- }
-
- String xml = genSdncReq(request, mappedTunables);
-
- long sdncStartTime = System.currentTimeMillis();
- SDNCResponseCommon response = connector.send(xml, mappedTunables);
-
- long bpStartTime = System.currentTimeMillis();
- boolean callbackSuccess = bpRestCallback.send(request.getBPNotificationUrl(), response.toJson());
- }
-
- private Element addChild(Element parent, String tag) {
- Element child = parent.getOwnerDocument().createElement(tag);
- parent.appendChild(child);
- return child;
- }
-
- private void addTextChild(Element parent, String tag, String text) {
- if (text != null) {
- Element child = parent.getOwnerDocument().createElement(tag);
- child.setTextContent(text);
- parent.appendChild(child);
- }
- }
-
- private String genSdncReq(SDNCServiceRequest request, TypedRequestTunables rt) {
- Document doc;
-
- try {
- DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
-
- doc = documentBuilder.newDocument();
- Element root = doc.createElementNS(rt.getNamespace(), "input");
- doc.appendChild(root);
-
- Element hdr = addChild(root, rt.getHeaderName());
- addTextChild(hdr, "svc-request-id", rt.getReqId());
- addTextChild(hdr, "svc-notification-url", rt.getMyUrl());
-
- RequestInformation requestInfo = request.getRequestInformation();
- Element requestInformation = addChild(root, "request-information");
- addTextChild(requestInformation, "request-id", requestInfo.getRequestId());
-
-
- if(requestInfo.getRequestAction()!= null) {
- addTextChild(requestInformation, "request-action",
- requestInfo.getRequestAction());
- }
- if(requestInfo.getRequestSubAction()!= null) {
- addTextChild(requestInformation, "request-sub-action",
- requestInfo.getRequestSubAction());
- }
- if(requestInfo.getOrderNumber() != null &&
- !requestInfo.getOrderNumber().isEmpty() ) {
- addTextChild(requestInformation, "order-number",
- requestInfo.getOrderNumber());
- }
-
- if(requestInfo.getOrderVersion() != null &&
- !requestInfo.getOrderVersion().isEmpty() ) {
- addTextChild(requestInformation, "order-version",
- requestInfo.getOrderVersion());
- }
-
-
- addTextChild(requestInformation, "source", requestInfo.getSource());
- addTextChild(requestInformation, "notification-url", requestInfo.getNotificationUrl());
-
- Element serviceInformation = addChild(root, "service-information");
- addTextChild(serviceInformation, "service-type", request.getServiceInformation().getServiceType());
- addTextChild(serviceInformation, "service-instance-id", request.getServiceInformation().getServiceInstanceId());
- addTextChild(serviceInformation, "subscriber-name", request.getServiceInformation().getSubscriberName());
- addTextChild(serviceInformation, "subscriber-global-id", request.getServiceInformation().getSubscriberGlobalId());
-
- Element agnosticServiceInformation = addChild(root, "agnostic-service-information");
- addTextChild(agnosticServiceInformation, "operation", request.getSdncOperation());
- addTextChild(agnosticServiceInformation, "service", request.getSdncService());
-
- // anydata is mandatory in the SDNC schema, so if the data we got is null,
- // set use an empty string instead to ensure we generate an empty element.
-
- String anydata = request.getSdncServiceData();
- if (anydata == null) {
- anydata = "";
- }
-
- // content-type is also mandatory.
-
- String contentType = request.getSdncServiceDataType();
-
- if (contentType == null || contentType.isEmpty()) {
- if (anydata.isEmpty()) {
- contentType = "XML";
- } else {
- if (anydata.startsWith("<")) {
- contentType = "XML";
- } else {
- contentType = "JSON";
- }
- }
- }
-
- addTextChild(agnosticServiceInformation, "content-type", contentType);
- addTextChild(agnosticServiceInformation, "anydata", anydata);
- } catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC",
- ErrorCode.BusinessProcesssError.getValue(), "Exception in genSdncReq", e);
- return null;
- }
-
- String xml;
-
- try {
- StringWriter writer = new StringWriter();
- TransformerFactory factory = TransformerFactory.newInstance();
- factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD,"");
- factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET,"");
- Transformer transformer = factory.newTransformer();
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
- transformer.transform(new DOMSource(doc), new StreamResult(writer));
- xml = writer.toString();
- } catch (Exception e) {
- logger.error("{} {} {}", MessageEnum.RA_ERROR_CONVERT_XML2STR.toString(), ErrorCode.DataError.getValue(),
- "Exception - domToStr", e);
- return null;
- }
-
- logger.trace("Formatted SDNC service request XML:\n {}", xml);
- return xml;
- }
+ private static final Logger logger = LoggerFactory.getLogger(SDNCServiceRequestTask.class);
+
+ @Autowired
+ private SDNCServiceRequestConnector connector;
+
+ @Autowired
+ MapTypedRequestTunablesData mapTunables;
+
+ @Autowired
+ private BPRestCallback bpRestCallback;
+
+ @Async
+ public void runRequest(SDNCServiceRequest request, String msoRequestId, String msoServiceInstanceId,
+ String myUrlSuffix) {
+
+ String sdncRequestId = request.getSdncRequestId();
+ String sdncService = request.getSdncService();
+ String sdncOperation = request.getSdncOperation();
+
+ TypedRequestTunables rt = new TypedRequestTunables(sdncRequestId, myUrlSuffix);
+ rt.setServiceKey(sdncService, sdncOperation);
+ TypedRequestTunables mappedTunables;
+ try {
+ mappedTunables = mapTunables.setTunables(rt);
+ } catch (SDNCAdapterException e) {
+ bpRestCallback.send(request.getBPNotificationUrl(), e.getMessage());
+ return;
+ }
+ if (!mappedTunables.getError().isEmpty()) {
+ // Note that the error was logged and alarmed by setTunables()
+ SDNCServiceError error = new SDNCServiceError(request.getSdncRequestId(),
+ String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR), mappedTunables.getError(), "Y");
+ bpRestCallback.send(request.getBPNotificationUrl(), error.toJson());
+ return;
+ }
+
+ String xml = genSdncReq(request, mappedTunables);
+
+ long sdncStartTime = System.currentTimeMillis();
+ SDNCResponseCommon response = connector.send(xml, mappedTunables);
+
+ long bpStartTime = System.currentTimeMillis();
+ boolean callbackSuccess = bpRestCallback.send(request.getBPNotificationUrl(), response.toJson());
+ }
+
+ private Element addChild(Element parent, String tag) {
+ Element child = parent.getOwnerDocument().createElement(tag);
+ parent.appendChild(child);
+ return child;
+ }
+
+ private void addTextChild(Element parent, String tag, String text) {
+ if (text != null) {
+ Element child = parent.getOwnerDocument().createElement(tag);
+ child.setTextContent(text);
+ parent.appendChild(child);
+ }
+ }
+
+ private String genSdncReq(SDNCServiceRequest request, TypedRequestTunables rt) {
+ Document doc;
+
+ try {
+ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
+
+ doc = documentBuilder.newDocument();
+ Element root = doc.createElementNS(rt.getNamespace(), "input");
+ doc.appendChild(root);
+
+ Element hdr = addChild(root, rt.getHeaderName());
+ addTextChild(hdr, "svc-request-id", rt.getReqId());
+ addTextChild(hdr, "svc-notification-url", rt.getMyUrl());
+
+ RequestInformation requestInfo = request.getRequestInformation();
+ Element requestInformation = addChild(root, "request-information");
+ addTextChild(requestInformation, "request-id", requestInfo.getRequestId());
+
+
+ if (requestInfo.getRequestAction() != null) {
+ addTextChild(requestInformation, "request-action", requestInfo.getRequestAction());
+ }
+ if (requestInfo.getRequestSubAction() != null) {
+ addTextChild(requestInformation, "request-sub-action", requestInfo.getRequestSubAction());
+ }
+ if (requestInfo.getOrderNumber() != null && !requestInfo.getOrderNumber().isEmpty()) {
+ addTextChild(requestInformation, "order-number", requestInfo.getOrderNumber());
+ }
+
+ if (requestInfo.getOrderVersion() != null && !requestInfo.getOrderVersion().isEmpty()) {
+ addTextChild(requestInformation, "order-version", requestInfo.getOrderVersion());
+ }
+
+
+ addTextChild(requestInformation, "source", requestInfo.getSource());
+ addTextChild(requestInformation, "notification-url", requestInfo.getNotificationUrl());
+
+ Element serviceInformation = addChild(root, "service-information");
+ addTextChild(serviceInformation, "service-type", request.getServiceInformation().getServiceType());
+ addTextChild(serviceInformation, "service-instance-id",
+ request.getServiceInformation().getServiceInstanceId());
+ addTextChild(serviceInformation, "subscriber-name", request.getServiceInformation().getSubscriberName());
+ addTextChild(serviceInformation, "subscriber-global-id",
+ request.getServiceInformation().getSubscriberGlobalId());
+
+ Element agnosticServiceInformation = addChild(root, "agnostic-service-information");
+ addTextChild(agnosticServiceInformation, "operation", request.getSdncOperation());
+ addTextChild(agnosticServiceInformation, "service", request.getSdncService());
+
+ // anydata is mandatory in the SDNC schema, so if the data we got is null,
+ // set use an empty string instead to ensure we generate an empty element.
+
+ String anydata = request.getSdncServiceData();
+ if (anydata == null) {
+ anydata = "";
+ }
+
+ // content-type is also mandatory.
+
+ String contentType = request.getSdncServiceDataType();
+
+ if (contentType == null || contentType.isEmpty()) {
+ if (anydata.isEmpty()) {
+ contentType = "XML";
+ } else {
+ if (anydata.startsWith("<")) {
+ contentType = "XML";
+ } else {
+ contentType = "JSON";
+ }
+ }
+ }
+
+ addTextChild(agnosticServiceInformation, "content-type", contentType);
+ addTextChild(agnosticServiceInformation, "anydata", anydata);
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception in genSdncReq", e);
+ return null;
+ }
+
+ String xml;
+
+ try {
+ StringWriter writer = new StringWriter();
+ TransformerFactory factory = TransformerFactory.newInstance();
+ factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
+ factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
+ Transformer transformer = factory.newTransformer();
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
+ transformer.transform(new DOMSource(doc), new StreamResult(writer));
+ xml = writer.toString();
+ } catch (Exception e) {
+ logger.error("{} {} {}", MessageEnum.RA_ERROR_CONVERT_XML2STR.toString(), ErrorCode.DataError.getValue(),
+ "Exception - domToStr", e);
+ return null;
+ }
+
+ logger.trace("Formatted SDNC service request XML:\n {}", xml);
+ return xml;
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java
index 96153a18fa..3921891ced 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java
@@ -31,11 +31,9 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.onap.so.adapters.sdnc.impl.Constants;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -43,39 +41,38 @@ import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
- * A temporary interface to support notifications from SNIRO to BPMN.
- * We added this to the SDNC adapter because we didn't have time to
- * develop a SNIRO adapter in 1702.
+ * A temporary interface to support notifications from SNIRO to BPMN. We added this to the SDNC adapter because we
+ * didn't have time to develop a SNIRO adapter in 1702.
*/
@Path("/")
@Component
public class SNIROResponse {
- private static final Logger logger = LoggerFactory.getLogger(SNIROResponse.class);
+ private static final Logger logger = LoggerFactory.getLogger(SNIROResponse.class);
+
+
+ @Autowired
+ private Environment env;
-
- @Autowired
- private Environment env;
-
- @Autowired
- private BPRestCallback callback;
+ @Autowired
+ private BPRestCallback callback;
- @POST
- @Path("/SDNCNotify/SNIROResponse/{correlator}")
- @Consumes("*/*")
- @Produces({MediaType.TEXT_PLAIN})
- public Response serviceNotification(@PathParam("correlator") String correlator, String content) {
- logger.info("{} {} {} {}", MessageEnum.RA_RECEIVE_SDNC_NOTIF.toString(), content, "SDNC",
- "SDNCNotify/SNIROResponse");
+ @POST
+ @Path("/SDNCNotify/SNIROResponse/{correlator}")
+ @Consumes("*/*")
+ @Produces({MediaType.TEXT_PLAIN})
+ public Response serviceNotification(@PathParam("correlator") String correlator, String content) {
+ logger.info("{} {} {} {}", MessageEnum.RA_RECEIVE_SDNC_NOTIF.toString(), content, "SDNC",
+ "SDNCNotify/SNIROResponse");
- String bpUrl = env.getProperty(Constants.BPEL_REST_URL_PROP, "");
+ String bpUrl = env.getProperty(Constants.BPEL_REST_URL_PROP, "");
- if (bpUrl == null || ("").equals(bpUrl)) {
- String error = "Missing configuration for: " + Constants.BPEL_REST_URL_PROP;
- logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), Constants.BPEL_REST_URL_PROP,
- "SDNC", ErrorCode.DataError.getValue(), "Missing config param");
+ if (bpUrl == null || ("").equals(bpUrl)) {
+ String error = "Missing configuration for: " + Constants.BPEL_REST_URL_PROP;
+ logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(),
+ Constants.BPEL_REST_URL_PROP, "SDNC", ErrorCode.DataError.getValue(), "Missing config param");
- return Response.status(HttpServletResponse.SC_BAD_REQUEST).entity(error).build();
- }
- return Response.status(204).build();
- }
+ return Response.status(HttpServletResponse.SC_BAD_REQUEST).entity(error).build();
+ }
+ return Response.status(204).build();
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/TypedRequestTunables.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/TypedRequestTunables.java
index 4ff6dbc9a6..6fb69af85a 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/TypedRequestTunables.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/TypedRequestTunables.java
@@ -28,156 +28,161 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Typed Request Tunables. Each entry is identified by a TYPE in the property name.
- * Different types can have different keys.
+ * Typed Request Tunables. Each entry is identified by a TYPE in the property name. Different types can have different
+ * keys.
* <p>
* General format:
+ *
* <pre>
* org.onap.so.adapters.sdnc.TYPE.KEY1[.KEY2...]=METHOD|TIMEOUT|URL|HEADER|NAMESPACE
* </pre>
+ *
* Currently supported type(s): service
+ *
* <pre>
- * org.onap.so.adapters.sdnc.service.SERVICE.OPERATION=METHOD|TIMEOUT|URL|HEADER|NAMESPACE
+ * org.onap.so.adapters.sdnc.service.SERVICE.OPERATION = METHOD | TIMEOUT | URL | HEADER | NAMESPACE
* </pre>
*/
-public class TypedRequestTunables {
-
- private static final Logger logger = LoggerFactory.getLogger(TypedRequestTunables.class);
-
- private String reqId;
- private String myUrlSuffix;
- private String key = null;
- private String error = "";
-
- // tunables (all are required)
- private String reqMethod = null;
- private String timeout = null;
- private String sdncUrl = null;
- private String headerName = null;
- private String namespace = null;
- private String myUrl = null;
-
- public TypedRequestTunables(TypedRequestTunables reqTunableOriginal) {
- this.reqId = reqTunableOriginal.getReqId();
- this.myUrlSuffix = reqTunableOriginal.getMyUrlSuffix();
- this.key = reqTunableOriginal.getKey();
- this.error = reqTunableOriginal.getError();
- this.reqMethod = reqTunableOriginal.getReqMethod();
- this.timeout = reqTunableOriginal.getTimeout();
- this.sdncUrl = reqTunableOriginal.getSdncUrl();
- this.headerName = reqTunableOriginal.getHeaderName();
- this.namespace = reqTunableOriginal.getNamespace();
- this.myUrl = reqTunableOriginal.getMyUrl();
- }
-
- public TypedRequestTunables(String reqId, String myUrlSuffix) {
- this.reqId = reqId;
- this.myUrlSuffix = myUrlSuffix;
- }
-
- /**
- * Sets the key for a service request:
- * <pre>
- * org.onap.so.adapters.sdnc.service.SERVICE.OPERATION
- * </pre>
- * @param service the sdncService
- * @param operation the sdncOperation
- */
- public void setServiceKey(String service, String operation) {
- key = Constants.REQUEST_TUNABLES + ".service." + service + "." + operation;
- logger.debug("Generated {} key: {}", getClass().getSimpleName(), key);
- }
-
- /**
- * Gets the SDNC request ID.
- */
- public String getReqId() {
- return reqId;
- }
-
- /**
- * Gets the generated key.
- */
- public String getKey() {
- return key;
- }
-
- /**
- * Gets the most recent error, or null if there was no error.
- */
- public String getError() {
- return error;
- }
-
- public String getReqMethod() {
- return reqMethod;
- }
-
- public String getTimeout() {
- return timeout;
- }
-
- public String getSdncUrl() {
- return sdncUrl;
- }
-
- public String getHeaderName() {
- return headerName;
- }
-
- public String getNamespace() {
- return namespace;
- }
-
- /**
- * Gets the SDNC adapter notification URL, trimmed of trailing '/' characters.
- */
- public String getMyUrl() {
- return myUrl;
- }
-
- public String getMyUrlSuffix() {
- return myUrlSuffix;
- }
-
- public void setKey(String key) {
- this.key = key;
- }
-
- public void setError(String error) {
- this.error = error;
- }
-
- public void setReqMethod(String reqMethod) {
- this.reqMethod = reqMethod;
- }
-
- public void setTimeout(String timeout) {
- this.timeout = timeout;
- }
-
- public void setSdncUrl(String sdncUrl) {
- this.sdncUrl = sdncUrl;
- }
-
- public void setHeaderName(String headerName) {
- this.headerName = headerName;
- }
-
- public void setNamespace(String namespace) {
- this.namespace = namespace;
- }
-
- public void setMyUrl(String myUrl) {
- this.myUrl = myUrl;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("reqId", reqId).append("myUrlSuffix", myUrlSuffix).append("key", key)
- .append("error", error).append("reqMethod", reqMethod).append("timeout", timeout)
- .append("sdncUrl", sdncUrl).append("headerName", headerName).append("namespace", namespace)
- .append("myUrl", myUrl).toString();
- }
-
+public class TypedRequestTunables {
+
+ private static final Logger logger = LoggerFactory.getLogger(TypedRequestTunables.class);
+
+ private String reqId;
+ private String myUrlSuffix;
+ private String key = null;
+ private String error = "";
+
+ // tunables (all are required)
+ private String reqMethod = null;
+ private String timeout = null;
+ private String sdncUrl = null;
+ private String headerName = null;
+ private String namespace = null;
+ private String myUrl = null;
+
+ public TypedRequestTunables(TypedRequestTunables reqTunableOriginal) {
+ this.reqId = reqTunableOriginal.getReqId();
+ this.myUrlSuffix = reqTunableOriginal.getMyUrlSuffix();
+ this.key = reqTunableOriginal.getKey();
+ this.error = reqTunableOriginal.getError();
+ this.reqMethod = reqTunableOriginal.getReqMethod();
+ this.timeout = reqTunableOriginal.getTimeout();
+ this.sdncUrl = reqTunableOriginal.getSdncUrl();
+ this.headerName = reqTunableOriginal.getHeaderName();
+ this.namespace = reqTunableOriginal.getNamespace();
+ this.myUrl = reqTunableOriginal.getMyUrl();
+ }
+
+ public TypedRequestTunables(String reqId, String myUrlSuffix) {
+ this.reqId = reqId;
+ this.myUrlSuffix = myUrlSuffix;
+ }
+
+ /**
+ * Sets the key for a service request:
+ *
+ * <pre>
+ * org.onap.so.adapters.sdnc.service.SERVICE.OPERATION
+ * </pre>
+ *
+ * @param service the sdncService
+ * @param operation the sdncOperation
+ */
+ public void setServiceKey(String service, String operation) {
+ key = Constants.REQUEST_TUNABLES + ".service." + service + "." + operation;
+ logger.debug("Generated {} key: {}", getClass().getSimpleName(), key);
+ }
+
+ /**
+ * Gets the SDNC request ID.
+ */
+ public String getReqId() {
+ return reqId;
+ }
+
+ /**
+ * Gets the generated key.
+ */
+ public String getKey() {
+ return key;
+ }
+
+ /**
+ * Gets the most recent error, or null if there was no error.
+ */
+ public String getError() {
+ return error;
+ }
+
+ public String getReqMethod() {
+ return reqMethod;
+ }
+
+ public String getTimeout() {
+ return timeout;
+ }
+
+ public String getSdncUrl() {
+ return sdncUrl;
+ }
+
+ public String getHeaderName() {
+ return headerName;
+ }
+
+ public String getNamespace() {
+ return namespace;
+ }
+
+ /**
+ * Gets the SDNC adapter notification URL, trimmed of trailing '/' characters.
+ */
+ public String getMyUrl() {
+ return myUrl;
+ }
+
+ public String getMyUrlSuffix() {
+ return myUrlSuffix;
+ }
+
+ public void setKey(String key) {
+ this.key = key;
+ }
+
+ public void setError(String error) {
+ this.error = error;
+ }
+
+ public void setReqMethod(String reqMethod) {
+ this.reqMethod = reqMethod;
+ }
+
+ public void setTimeout(String timeout) {
+ this.timeout = timeout;
+ }
+
+ public void setSdncUrl(String sdncUrl) {
+ this.sdncUrl = sdncUrl;
+ }
+
+ public void setHeaderName(String headerName) {
+ this.headerName = headerName;
+ }
+
+ public void setNamespace(String namespace) {
+ this.namespace = namespace;
+ }
+
+ public void setMyUrl(String myUrl) {
+ this.myUrl = myUrl;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("reqId", reqId).append("myUrlSuffix", myUrlSuffix).append("key", key)
+ .append("error", error).append("reqMethod", reqMethod).append("timeout", timeout)
+ .append("sdncUrl", sdncUrl).append("headerName", headerName).append("namespace", namespace)
+ .append("myUrl", myUrl).toString();
+ }
+
}
diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtil.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtil.java
index 991126f868..ccf3c8df82 100644
--- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtil.java
+++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtil.java
@@ -22,18 +22,20 @@ package org.onap.so.adapters.sdnc.util;
public class SDNCRequestIdUtil {
- // Add private constructor to prevent instance creation.
- private SDNCRequestIdUtil () {}
+ // Add private constructor to prevent instance creation.
+ private SDNCRequestIdUtil() {}
- public static String getSDNCOriginalRequestId (String newRequestId) {
-
- // Camunda scripts will add postfix, such as -1, -2, on the original requestID, to make sure requestID is unique while sending request to SDNC
- // In order to use the unique requestID in logging, need to remove the postfix added by the Camunda scripts
- // Verify whether the requestId is a valid UUID with postfix (-1, -2). If yes, it should contain 5 times char '-', since valid UUID contains 4 times '-'
- // If the requestId is not a valid UUID with postfix, we do nothing
- if (newRequestId.split("-").length == 6) {
- return newRequestId.substring(0, newRequestId.lastIndexOf('-'));
- }
- return newRequestId;
+ public static String getSDNCOriginalRequestId(String newRequestId) {
+
+ // Camunda scripts will add postfix, such as -1, -2, on the original requestID, to make sure requestID is unique
+ // while sending request to SDNC
+ // In order to use the unique requestID in logging, need to remove the postfix added by the Camunda scripts
+ // Verify whether the requestId is a valid UUID with postfix (-1, -2). If yes, it should contain 5 times char
+ // '-', since valid UUID contains 4 times '-'
+ // If the requestId is not a valid UUID with postfix, we do nothing
+ if (newRequestId.split("-").length == 6) {
+ return newRequestId.substring(0, newRequestId.lastIndexOf('-'));
+ }
+ return newRequestId;
}
}
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/AllTestsTestSuite.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/AllTestsTestSuite.java
index 50a661a695..a15163bbcb 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/AllTestsTestSuite.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/AllTestsTestSuite.java
@@ -19,14 +19,14 @@
*/
package org.onap.so.adapters.sdnc;
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses("**/*Test.class")
public class AllTestsTestSuite {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/BaseTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/BaseTest.java
index 29921934dd..a65ddc5bb8 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/BaseTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/BaseTest.java
@@ -31,7 +31,6 @@ import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
-
import com.github.tomakehurst.wiremock.WireMockServer;
@RunWith(SpringRunner.class)
@@ -41,15 +40,15 @@ import com.github.tomakehurst.wiremock.WireMockServer;
public abstract class BaseTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
-
+
@Autowired
protected WireMockServer wireMockServer;
-
+
protected TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
@Value("${wiremock.server.port}")
protected String wireMockPort;
-
+
@After
public void after() {
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/FileUtil.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/FileUtil.java
index d72775399f..114618f0b4 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/FileUtil.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/FileUtil.java
@@ -24,7 +24,6 @@ package org.onap.so.adapters.sdnc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.io.InputStream;
@@ -48,7 +47,7 @@ public class FileUtil {
stream = getResourceAsStream(fileName);
byte[] bytes;
bytes = new byte[stream.available()];
- if(stream.read(bytes) > 0) {
+ if (stream.read(bytes) > 0) {
stream.close();
return new String(bytes);
} else {
@@ -69,8 +68,7 @@ public class FileUtil {
* @throws IOException If we can't get the InputStream for whatever reason.
*/
private static InputStream getResourceAsStream(String resourceName) throws IOException {
- InputStream stream =
- FileUtil.class.getClassLoader().getResourceAsStream(resourceName);
+ InputStream stream = FileUtil.class.getClassLoader().getResourceAsStream(resourceName);
if (stream == null) {
throw new IOException("Can't access resource '" + resourceName + "'");
}
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/ObjectFactoryTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/ObjectFactoryTest.java
index 7a9b039089..4a6eb61287 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/ObjectFactoryTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/ObjectFactoryTest.java
@@ -26,17 +26,14 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
-
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
-
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
-
import org.junit.Test;
public class ObjectFactoryTest {
@@ -48,45 +45,44 @@ public class ObjectFactoryTest {
* Test method for {@link org.onap.so.adapters.sdnc.ObjectFactory#createRequestHeader()}.
*/
@Test
- public final void testCreateRequestHeader () {
- ObjectFactory of = new ObjectFactory ();
- RequestHeader rh = of.createRequestHeader ();
- rh.setCallbackUrl ("callback");
- rh.setMsoAction ("action");
- rh.setRequestId ("reqid");
- rh.setSvcAction ("svcAction");
- rh.setSvcInstanceId ("svcId");
- rh.setSvcOperation ("op");
-
+ public final void testCreateRequestHeader() {
+ ObjectFactory of = new ObjectFactory();
+ RequestHeader rh = of.createRequestHeader();
+ rh.setCallbackUrl("callback");
+ rh.setMsoAction("action");
+ rh.setRequestId("reqid");
+ rh.setSvcAction("svcAction");
+ rh.setSvcInstanceId("svcId");
+ rh.setSvcOperation("op");
+
try {
JAXBContext jaxbContext = JAXBContext.newInstance(RequestHeader.class);
jaxbMarshaller = jaxbContext.createMarshaller();
-
+
JAXBContext jaxbContext2 = JAXBContext.newInstance(RequestHeader.class);
jaxbUnmarshaller = jaxbContext2.createUnmarshaller();
- }
- catch (JAXBException e) {
- e.printStackTrace ();
+ } catch (JAXBException e) {
+ e.printStackTrace();
fail();
return;
}
StringWriter writer = new StringWriter();
try {
- jaxbMarshaller.marshal (rh, writer);
+ jaxbMarshaller.marshal(rh, writer);
} catch (JAXBException e) {
e.printStackTrace();
- fail ();
+ fail();
}
- String marshalled = writer.toString ();
+ String marshalled = writer.toString();
assertThat(marshalled, containsString("<RequestId>reqid</RequestId>"));
-
+
InputStream inputStream = new ByteArrayInputStream(marshalled.getBytes(Charset.forName("UTF-8")));
try {
- RequestHeader res2 = (RequestHeader) jaxbUnmarshaller.unmarshal (inputStream);
- assertEquals("callback", res2.getCallbackUrl ());
- assertEquals("action", res2.getMsoAction ());
- assertEquals("op", res2.getSvcOperation ());
+ RequestHeader res2 = (RequestHeader) jaxbUnmarshaller.unmarshal(inputStream);
+ assertEquals("callback", res2.getCallbackUrl());
+ assertEquals("action", res2.getMsoAction());
+ assertEquals("op", res2.getSvcOperation());
} catch (JAXBException e) {
e.printStackTrace();
fail();
@@ -97,17 +93,17 @@ public class ObjectFactoryTest {
* Test method for {@link org.onap.so.adapters.sdnc.ObjectFactory#createSDNCAdapterResponse()}.
*/
@Test
- public final void testCreateSDNCAdapterResponse () {
- ObjectFactory of = new ObjectFactory ();
- SDNCAdapterResponse ar = of.createSDNCAdapterResponse ();
+ public final void testCreateSDNCAdapterResponse() {
+ ObjectFactory of = new ObjectFactory();
+ SDNCAdapterResponse ar = of.createSDNCAdapterResponse();
assertNotNull(ar);
}
-
+
@Test
- public final void testCreateSDNCAdapterRequest () {
- ObjectFactory of = new ObjectFactory ();
- SDNCAdapterRequest ar = of.createSDNCAdapterRequest ();
+ public final void testCreateSDNCAdapterRequest() {
+ ObjectFactory of = new ObjectFactory();
+ SDNCAdapterRequest ar = of.createSDNCAdapterRequest();
assertNotNull(ar);
}
-
+
}
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/SDNCAdapterRequestTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/SDNCAdapterRequestTest.java
index e0a1982db1..ce3a55470b 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/SDNCAdapterRequestTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/SDNCAdapterRequestTest.java
@@ -23,7 +23,6 @@ package org.onap.so.adapters.sdnc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.so.adapters.sdnc.SDNCAdapterRequest;
@@ -32,26 +31,26 @@ import org.onap.so.adapters.sdnc.RequestHeader;
public class SDNCAdapterRequestTest {
- static Object sd= new SDNCAdapterRequest();
- static RequestHeader rh=new RequestHeader();
-
- @BeforeClass
- public static final void RHeader()
- {
- rh.setCallbackUrl("callback");
- rh.setMsoAction ("action");
- rh.setRequestId ("reqid");
- rh.setSvcAction ("svcAction");
- rh.setSvcInstanceId ("svcId");
- rh.setSvcOperation ("op");
- }
- @Test
- public final void testtoString(){
- ((SDNCAdapterRequest) sd).setRequestData("data");
- ((SDNCAdapterRequest) sd).setRequestHeader(rh);
- assertNotNull(((SDNCAdapterRequest) sd).getRequestData()) ;
+ static Object sd = new SDNCAdapterRequest();
+ static RequestHeader rh = new RequestHeader();
+
+ @BeforeClass
+ public static final void RHeader() {
+ rh.setCallbackUrl("callback");
+ rh.setMsoAction("action");
+ rh.setRequestId("reqid");
+ rh.setSvcAction("svcAction");
+ rh.setSvcInstanceId("svcId");
+ rh.setSvcOperation("op");
+ }
+
+ @Test
+ public final void testtoString() {
+ ((SDNCAdapterRequest) sd).setRequestData("data");
+ ((SDNCAdapterRequest) sd).setRequestHeader(rh);
+ assertNotNull(((SDNCAdapterRequest) sd).getRequestData());
assertEquals("data", ((SDNCAdapterRequest) sd).getRequestData());
assertEquals(rh, ((SDNCAdapterRequest) sd).getRequestHeader());
- }
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/client/CallbackHeaderTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/client/CallbackHeaderTest.java
index dbb5c9aa44..6ad340921f 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/client/CallbackHeaderTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/client/CallbackHeaderTest.java
@@ -1,28 +1,22 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.adapters.sdnc.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import org.junit.Test;
public class CallbackHeaderTest {
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequestTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequestTest.java
index d7f4f8e6f7..35a505d844 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequestTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequestTest.java
@@ -23,35 +23,32 @@ package org.onap.so.adapters.sdnc.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import org.junit.Test;
import org.onap.so.adapters.sdnc.client.CallbackHeader;
import org.onap.so.adapters.sdnc.client.SDNCAdapterCallbackRequest;
public class SDNCAdapterCallbackRequestTest {
- static SDNCAdapterCallbackRequest sdc = new SDNCAdapterCallbackRequest();
- static CallbackHeader ch = new CallbackHeader("413658f4-7f42-482e-b834-23a5c15657da-1474471336781","200","OK");
-
- @Test
- public void testSDNCAdapterCallbackRequest()
- {
- sdc.setCallbackHeader(ch);
- sdc.setRequestData("data");
- assertNotNull(sdc.getCallbackHeader());
- assertNotNull(sdc.getRequestData());
- assertEquals(ch, sdc.getCallbackHeader());
- assertEquals("data", sdc.getRequestData());
-
- }
-
- @Test
- public void testtoString()
- {
- assertNotNull(ch.toString());
- assertNotNull(sdc.toString());
- }
-
+ static SDNCAdapterCallbackRequest sdc = new SDNCAdapterCallbackRequest();
+ static CallbackHeader ch = new CallbackHeader("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", "200", "OK");
+
+ @Test
+ public void testSDNCAdapterCallbackRequest() {
+ sdc.setCallbackHeader(ch);
+ sdc.setRequestData("data");
+ assertNotNull(sdc.getCallbackHeader());
+ assertNotNull(sdc.getRequestData());
+ assertEquals(ch, sdc.getCallbackHeader());
+ assertEquals("data", sdc.getRequestData());
+
+ }
+
+ @Test
+ public void testtoString() {
+ assertNotNull(ch.toString());
+ assertNotNull(sdc.toString());
+ }
+
}
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/MapRequestTunablesTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/MapRequestTunablesTest.java
index cd93f6e71b..cab2e27252 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/MapRequestTunablesTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/MapRequestTunablesTest.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.sdnc.impl;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.adapters.sdnc.SDNCAdapterApplication;
@@ -35,94 +34,94 @@ import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = SDNCAdapterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class MapRequestTunablesTest {
-
- @Autowired
- private MapRequestTunables tunableMapper;
-
- @Test
- public void test_setTunables(){
- RequestTunables expectedResult = new RequestTunables("testReqId", "","vnf-topology-operation","assign");
- expectedResult.setAsyncInd("N");
- expectedResult.setSdncUrl("https://localhost:8443/restconf/operations/VNF-API:vnf-topology-operation");
- expectedResult.setTimeout("270000");
- expectedResult.setReqMethod("POST");
- expectedResult.setHeaderName("sdnc-request-header");
- expectedResult.setNamespace("org:openecomp:sdnctl:vnf");
-
- RequestTunables testMapper = new RequestTunables("testReqId", "","vnf-topology-operation","assign");
-
- RequestTunables mappedTunable = tunableMapper.setTunables(testMapper);
-
- assertThat(mappedTunable, sameBeanAs(expectedResult));
- }
-
- @Test
- public void test_setTunables_EmptyOperation_EmptyMSOAction(){
- RequestTunables expectedResult = new RequestTunables("testReqId", "","","query");
- expectedResult.setAsyncInd("N");
- expectedResult.setSdncUrl("http://localhost:8443/restconf/operations/GENERIC-RESOURCE-API:");
- expectedResult.setTimeout("60000");
- expectedResult.setReqMethod("GET");
- expectedResult.setHeaderName("sdnc-request-header");
- expectedResult.setNamespace("");
-
- RequestTunables testMapper = new RequestTunables("testReqId", "","","query");
-
- RequestTunables mappedTunable = tunableMapper.setTunables(testMapper);
-
- assertThat(mappedTunable, sameBeanAs(expectedResult));
- }
-
- @Test
- public void test_setTunables_EmptyOperation(){
- RequestTunables expectedResult = new RequestTunables("testReqId", "infra","","query");
- expectedResult.setAsyncInd("N");
- expectedResult.setSdncUrl("https://localhost:8443/restconf/config");
- expectedResult.setTimeout("60000");
- expectedResult.setReqMethod("GET");
- expectedResult.setHeaderName("sdnc-request-header");
- expectedResult.setNamespace("");
-
- RequestTunables testMapper = new RequestTunables("testReqId", "infra","","query");
-
- RequestTunables mappedTunable = tunableMapper.setTunables(testMapper);
-
- assertThat(mappedTunable, sameBeanAs(expectedResult));
- }
-
- @Test
- public void test_setTunables_EmptyOperation_EmptyMSOActionPUT(){
- RequestTunables expectedResult = new RequestTunables("testReqId", "","","put");
- expectedResult.setAsyncInd("N");
- expectedResult.setSdncUrl("https://localhost:8443/restconf/config");
- expectedResult.setTimeout("60000");
- expectedResult.setReqMethod("PUT");
- expectedResult.setHeaderName("sdnc-request-header");
- expectedResult.setNamespace("");
-
- RequestTunables testMapper = new RequestTunables("testReqId", "","","put");
-
- RequestTunables mappedTunable = tunableMapper.setTunables(testMapper);
-
- assertThat(mappedTunable, sameBeanAs(expectedResult));
- }
-
-
- @Test
- public void test_setTunables_EmptyOperation_EmptyMSOActionRESTDELETE(){
- RequestTunables expectedResult = new RequestTunables("testReqId", "","","restdelete");
- expectedResult.setAsyncInd("N");
- expectedResult.setSdncUrl("https://localhost:8443/restconf/config");
- expectedResult.setTimeout("60000");
- expectedResult.setReqMethod("DELETE");
- expectedResult.setHeaderName("sdnc-request-header");
- expectedResult.setNamespace("");
-
- RequestTunables testMapper = new RequestTunables("testReqId", "","","restdelete");
-
- RequestTunables mappedTunable = tunableMapper.setTunables(testMapper);
-
- assertThat(mappedTunable, sameBeanAs(expectedResult));
- }
+
+ @Autowired
+ private MapRequestTunables tunableMapper;
+
+ @Test
+ public void test_setTunables() {
+ RequestTunables expectedResult = new RequestTunables("testReqId", "", "vnf-topology-operation", "assign");
+ expectedResult.setAsyncInd("N");
+ expectedResult.setSdncUrl("https://localhost:8443/restconf/operations/VNF-API:vnf-topology-operation");
+ expectedResult.setTimeout("270000");
+ expectedResult.setReqMethod("POST");
+ expectedResult.setHeaderName("sdnc-request-header");
+ expectedResult.setNamespace("org:openecomp:sdnctl:vnf");
+
+ RequestTunables testMapper = new RequestTunables("testReqId", "", "vnf-topology-operation", "assign");
+
+ RequestTunables mappedTunable = tunableMapper.setTunables(testMapper);
+
+ assertThat(mappedTunable, sameBeanAs(expectedResult));
+ }
+
+ @Test
+ public void test_setTunables_EmptyOperation_EmptyMSOAction() {
+ RequestTunables expectedResult = new RequestTunables("testReqId", "", "", "query");
+ expectedResult.setAsyncInd("N");
+ expectedResult.setSdncUrl("http://localhost:8443/restconf/operations/GENERIC-RESOURCE-API:");
+ expectedResult.setTimeout("60000");
+ expectedResult.setReqMethod("GET");
+ expectedResult.setHeaderName("sdnc-request-header");
+ expectedResult.setNamespace("");
+
+ RequestTunables testMapper = new RequestTunables("testReqId", "", "", "query");
+
+ RequestTunables mappedTunable = tunableMapper.setTunables(testMapper);
+
+ assertThat(mappedTunable, sameBeanAs(expectedResult));
+ }
+
+ @Test
+ public void test_setTunables_EmptyOperation() {
+ RequestTunables expectedResult = new RequestTunables("testReqId", "infra", "", "query");
+ expectedResult.setAsyncInd("N");
+ expectedResult.setSdncUrl("https://localhost:8443/restconf/config");
+ expectedResult.setTimeout("60000");
+ expectedResult.setReqMethod("GET");
+ expectedResult.setHeaderName("sdnc-request-header");
+ expectedResult.setNamespace("");
+
+ RequestTunables testMapper = new RequestTunables("testReqId", "infra", "", "query");
+
+ RequestTunables mappedTunable = tunableMapper.setTunables(testMapper);
+
+ assertThat(mappedTunable, sameBeanAs(expectedResult));
+ }
+
+ @Test
+ public void test_setTunables_EmptyOperation_EmptyMSOActionPUT() {
+ RequestTunables expectedResult = new RequestTunables("testReqId", "", "", "put");
+ expectedResult.setAsyncInd("N");
+ expectedResult.setSdncUrl("https://localhost:8443/restconf/config");
+ expectedResult.setTimeout("60000");
+ expectedResult.setReqMethod("PUT");
+ expectedResult.setHeaderName("sdnc-request-header");
+ expectedResult.setNamespace("");
+
+ RequestTunables testMapper = new RequestTunables("testReqId", "", "", "put");
+
+ RequestTunables mappedTunable = tunableMapper.setTunables(testMapper);
+
+ assertThat(mappedTunable, sameBeanAs(expectedResult));
+ }
+
+
+ @Test
+ public void test_setTunables_EmptyOperation_EmptyMSOActionRESTDELETE() {
+ RequestTunables expectedResult = new RequestTunables("testReqId", "", "", "restdelete");
+ expectedResult.setAsyncInd("N");
+ expectedResult.setSdncUrl("https://localhost:8443/restconf/config");
+ expectedResult.setTimeout("60000");
+ expectedResult.setReqMethod("DELETE");
+ expectedResult.setHeaderName("sdnc-request-header");
+ expectedResult.setNamespace("");
+
+ RequestTunables testMapper = new RequestTunables("testReqId", "", "", "restdelete");
+
+ RequestTunables mappedTunable = tunableMapper.setTunables(testMapper);
+
+ assertThat(mappedTunable, sameBeanAs(expectedResult));
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImplTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImplTest.java
index 8f73c02285..6370bb4831 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImplTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImplTest.java
@@ -21,11 +21,9 @@
package org.onap.so.adapters.sdnc.impl;
import static org.junit.Assert.fail;
-
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
-
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
@@ -36,7 +34,6 @@ import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.adapters.sdnc.RequestHeader;
@@ -53,26 +50,28 @@ import org.xml.sax.SAXException;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SDNCAdapterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
-@ActiveProfiles({"test","non-async"})
+@ActiveProfiles({"test", "non-async"})
public class SDNCAdapterPortTypeImplTest {
- @Autowired
- private SDNCAdapterPortType sdncAdapter;
-
-
- SDNCAdapterRequest sdncAdapterRequest;
-
- public void setupTestEntities() throws ParserConfigurationException, SAXException, IOException, TransformerException {
- buildTestRequest();
- }
+ @Autowired
+ private SDNCAdapterPortType sdncAdapter;
+
+
+ SDNCAdapterRequest sdncAdapterRequest;
+
+ public void setupTestEntities()
+ throws ParserConfigurationException, SAXException, IOException, TransformerException {
+ buildTestRequest();
+ }
- private void buildTestRequest() throws ParserConfigurationException, SAXException, IOException, TransformerException {
- sdncAdapterRequest= new SDNCAdapterRequest();
- File fXmlFile = new File("src/test/resources/sdncTestPayload.xml");
- DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
- Document doc = dBuilder.parse(fXmlFile);
- StringWriter sw = new StringWriter();
+ private void buildTestRequest()
+ throws ParserConfigurationException, SAXException, IOException, TransformerException {
+ sdncAdapterRequest = new SDNCAdapterRequest();
+ File fXmlFile = new File("src/test/resources/sdncTestPayload.xml");
+ DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
+ Document doc = dBuilder.parse(fXmlFile);
+ StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
@@ -81,31 +80,32 @@ public class SDNCAdapterPortTypeImplTest {
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(doc), new StreamResult(sw));
- System.out.println(sw.toString());
- sdncAdapterRequest.setRequestData(sw.toString());
- RequestHeader requestHeader = new RequestHeader();
- requestHeader.setCallbackUrl("http://localhost:9090/callback");
- requestHeader.setMsoAction("gammainternet");
- requestHeader.setRequestId("testReqId");
- requestHeader.setSvcAction("assign");
- requestHeader.setSvcInstanceId("servInstanceId");
- requestHeader.setSvcOperation("svc-topology-operation");
- sdncAdapterRequest.setRequestHeader(requestHeader );
- }
-
-
-
- @Test
- public void sendRequest() throws ParserConfigurationException, SAXException, IOException, TransformerException {
- // Given
- setupTestEntities();
-
- // When
- SDNCAdapterResponse response = sdncAdapter.sdncAdapter(sdncAdapterRequest);
- if(response ==null)
- fail("Null infraRequest");
-
- // Then
- //assertThat(infraRequest, sameBeanAs(testRequest).ignoring("requestBody").ignoring("endTime").ignoring("startTime").ignoring("modifyTime"));
- }
+ System.out.println(sw.toString());
+ sdncAdapterRequest.setRequestData(sw.toString());
+ RequestHeader requestHeader = new RequestHeader();
+ requestHeader.setCallbackUrl("http://localhost:9090/callback");
+ requestHeader.setMsoAction("gammainternet");
+ requestHeader.setRequestId("testReqId");
+ requestHeader.setSvcAction("assign");
+ requestHeader.setSvcInstanceId("servInstanceId");
+ requestHeader.setSvcOperation("svc-topology-operation");
+ sdncAdapterRequest.setRequestHeader(requestHeader);
+ }
+
+
+
+ @Test
+ public void sendRequest() throws ParserConfigurationException, SAXException, IOException, TransformerException {
+ // Given
+ setupTestEntities();
+
+ // When
+ SDNCAdapterResponse response = sdncAdapter.sdncAdapter(sdncAdapterRequest);
+ if (response == null)
+ fail("Null infraRequest");
+
+ // Then
+ // assertThat(infraRequest,
+ // sameBeanAs(testRequest).ignoring("requestBody").ignoring("endTime").ignoring("startTime").ignoring("modifyTime"));
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCResponseTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCResponseTest.java
index 498fa3fa6d..a69589ac28 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCResponseTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCResponseTest.java
@@ -1,49 +1,41 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.adapters.sdnc.impl;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class SDNCResponseTest {
-
- private SDNCResponse sdncresponse = new SDNCResponse(null, 0, null);
-
- @Test
- public void testSDNCResponse()
- {
- sdncresponse.setReqId("reqId");
- sdncresponse.setRespCode(0);
- sdncresponse.setRespMsg("respMsg");
- sdncresponse.setSdncRespXml("sdncRespXml");
- assertEquals(sdncresponse.getReqId(), "reqId");
- assertEquals(sdncresponse.getRespCode(), 0);
- assertEquals(sdncresponse.getRespMsg(), "respMsg");
- assertEquals(sdncresponse.getSdncRespXml(),"sdncRespXml");
+
+ private SDNCResponse sdncresponse = new SDNCResponse(null, 0, null);
+
+ @Test
+ public void testSDNCResponse() {
+ sdncresponse.setReqId("reqId");
+ sdncresponse.setRespCode(0);
+ sdncresponse.setRespMsg("respMsg");
+ sdncresponse.setSdncRespXml("sdncRespXml");
+ assertEquals(sdncresponse.getReqId(), "reqId");
+ assertEquals(sdncresponse.getRespCode(), 0);
+ assertEquals(sdncresponse.getRespMsg(), "respMsg");
+ assertEquals(sdncresponse.getSdncRespXml(), "sdncRespXml");
+ }
+
+ @Test
+ public void testtoString() {
+ assertNotNull(sdncresponse.toString());
}
-
- @Test
- public void testtoString()
- {
- assertNotNull(sdncresponse.toString());
- }
}
-
+
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCRestClientTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCRestClientTest.java
index 76dd003883..b9d8d8df63 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCRestClientTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/SDNCRestClientTest.java
@@ -27,7 +27,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
import org.apache.http.HttpStatus;
import org.junit.Test;
import org.onap.so.adapters.sdnc.BaseTest;
@@ -47,8 +46,9 @@ public class SDNCRestClientTest extends BaseTest {
rt.setReqMethod("POST");
rt.setSdncUrl("http://localhost:" + wireMockPort + "/sdnc");
- wireMockServer.stubFor(post(urlPathEqualTo("/sdnc"))
- .willReturn(aResponse().withHeader("Content-Type", "application/xml").withBody("").withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+ wireMockServer.stubFor(
+ post(urlPathEqualTo("/sdnc")).willReturn(aResponse().withHeader("Content-Type", "application/xml")
+ .withBody("").withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
SDNCResponse response = sdncClient.getSdncResp("", rt);
assertNotNull(response);
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/UtilsTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/UtilsTest.java
index 596f26caa6..4a3db26443 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/UtilsTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/impl/UtilsTest.java
@@ -31,34 +31,34 @@ import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class UtilsTest {
-
+
@Test
- public final void testUnmarshal () {
-
- String expectedXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><feature-list xmlns=\"com:att:sdnctl:l3api\"><feature-type>FIREWALL-LITE</feature-type><feature-instance-id>mtjnj40evbc0eceb</feature-instance-id><feature-sub-type>SHARED</feature-sub-type><feature-instance-xpath>/restconf/config/Firewall-API:feature-model/feature-list/FIREWALL-LITE/mtjnj40evbc0eceb/</feature-instance-xpath> </feature-list>";
-
- try {
+ public final void testUnmarshal() {
+
+ String expectedXml =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><feature-list xmlns=\"com:att:sdnctl:l3api\"><feature-type>FIREWALL-LITE</feature-type><feature-instance-id>mtjnj40evbc0eceb</feature-instance-id><feature-sub-type>SHARED</feature-sub-type><feature-instance-xpath>/restconf/config/Firewall-API:feature-model/feature-list/FIREWALL-LITE/mtjnj40evbc0eceb/</feature-instance-xpath> </feature-list>";
+
+ try {
+
+ File file = new File("src/test/resources/sdncBpmnAdiodFirewallRequest.xml");
+ JAXBContext jaxbContext = JAXBContext.newInstance(SDNCAdapterRequest.class);
+
+ Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
+ SDNCAdapterRequest request = (SDNCAdapterRequest) jaxbUnmarshaller.unmarshal(file);
- File file = new File("src/test/resources/sdncBpmnAdiodFirewallRequest.xml");
- JAXBContext jaxbContext = JAXBContext.newInstance(SDNCAdapterRequest.class);
+ RequestTunables rt = new RequestTunables("0460ba40-60c8-4b07-8878-c8e8d87cde04-1527983610512", "",
+ "/L3SDN-API:services/layer3-service-list/MIS%2F1806%2F25057%2FSW_INTERNET/service-data/feature-list/FIREWALL-LITE/",
+ "put");
- Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
- SDNCAdapterRequest request = (SDNCAdapterRequest) jaxbUnmarshaller.unmarshal(file);
-
- RequestTunables rt = new RequestTunables("0460ba40-60c8-4b07-8878-c8e8d87cde04-1527983610512",
- "",
- "/L3SDN-API:services/layer3-service-list/MIS%2F1806%2F25057%2FSW_INTERNET/service-data/feature-list/FIREWALL-LITE/",
- "put");
+ Node node = (Node) request.getRequestData();
+ Document reqDoc = node.getOwnerDocument();
+ String sdncReqBody = Utils.genSdncPutReq(reqDoc, rt);
+ assertEquals(sdncReqBody.replaceAll("[\\t\\n\\r]+", ""), expectedXml);
- Node node = (Node) request.getRequestData();
- Document reqDoc = node.getOwnerDocument();
- String sdncReqBody = Utils.genSdncPutReq(reqDoc, rt);
- assertEquals(sdncReqBody.replaceAll("[\\t\\n\\r]+", ""), expectedXml);
+ } catch (JAXBException e) {
+ e.printStackTrace();
+ }
- } catch (JAXBException e) {
- e.printStackTrace();
- }
-
}
}
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallbackTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallbackTest.java
index f8685738e0..c1bbb9ae9a 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallbackTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallbackTest.java
@@ -25,7 +25,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import org.apache.http.HttpStatus;
import org.junit.Test;
import org.onap.so.adapters.sdnc.BaseTest;
@@ -37,20 +36,19 @@ public class BPRestCallbackTest extends BaseTest {
private BPRestCallback bpRestCallback;
@Test
- public void sendTest(){
- String response = "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">\n" +
- "\t\t// <error>\n" +
- "\t\t// <error-type>protocol</error-type>\n" +
- "\t\t// <error-tag>malformed-message</error-tag>\n" +
- "\t\t// <error-message>Error parsing input: The element type \"input\" must be terminated by the matching end-tag \"&lt;/input&gt;\".</error-message>\n" +
- "\t\t// </error>\n" +
- "\t\t// </errors>";
+ public void sendTest() {
+ String response = "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">\n" + "\t\t// <error>\n"
+ + "\t\t// <error-type>protocol</error-type>\n"
+ + "\t\t// <error-tag>malformed-message</error-tag>\n"
+ + "\t\t// <error-message>Error parsing input: The element type \"input\" must be terminated by the matching end-tag \"&lt;/input&gt;\".</error-message>\n"
+ + "\t\t// </error>\n" + "\t\t// </errors>";
- wireMockServer.stubFor(post(urlPathEqualTo("/sdnc"))
- .willReturn(aResponse().withHeader("Content-Type", "application/xml").withBody(response).withStatus(HttpStatus.SC_MULTIPLE_CHOICES)));
+ wireMockServer.stubFor(
+ post(urlPathEqualTo("/sdnc")).willReturn(aResponse().withHeader("Content-Type", "application/xml")
+ .withBody(response).withStatus(HttpStatus.SC_MULTIPLE_CHOICES)));
boolean responseCommon = bpRestCallback.send("http://localhost:" + wireMockPort + "/sdnc", "Test");
assertNotNull(responseCommon);
- assertEquals(true,responseCommon);
+ assertEquals(true, responseCommon);
}
}
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/ObjectMappingTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/ObjectMappingTest.java
index 88849015e0..521d2bc80f 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/ObjectMappingTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/ObjectMappingTest.java
@@ -23,19 +23,16 @@ package org.onap.so.adapters.sdnc.sdncrest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
-
import org.junit.Test;
import org.onap.so.adapters.sdncrest.SDNCEvent;
import org.onap.so.adapters.sdncrest.SDNCServiceError;
import org.onap.so.adapters.sdncrest.SDNCServiceRequest;
import org.onap.so.adapters.sdncrest.SDNCServiceResponse;
-
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
@@ -46,434 +43,406 @@ import com.fasterxml.jackson.databind.SerializationFeature;
* JSON object mapping tests.
*/
public class ObjectMappingTest {
- private static final String EOL = "\n";
-
- private final String SDNC_SERVICE_REQUEST =
- "{" + EOL +
- " \"SDNCServiceRequest\": {" + EOL +
- " \"requestInformation\": {" + EOL +
- " \"requestId\": \"413658f4-7f42-482e-b834-23a5c15657da\"," + EOL +
- " \"source\": \"CCD\"," + EOL +
- " \"notificationUrl\": \"https://ccd-host:8080/notifications\"" + EOL +
- " }," + EOL +
- " \"serviceInformation\": {" + EOL +
- " \"serviceType\": \"vHNFaaS\"," + EOL +
- " \"serviceInstanceId\": \"74e65b2b637441bca078e63e44bb511b\"," + EOL +
- " \"subscriberName\": \"IST_SG_0902_3003\"," + EOL +
- " \"subscriberGlobalId\": \"IST15_0902_3003\"" + EOL +
- " }," + EOL +
- " \"bpNotificationUrl\": \"http://localhost:8080/mso/SDNCAdapterCallbackService\"," + EOL +
- "((BP-TIMEOUT))" +
- " \"sdncRequestId\": \"413658f4-7f42-482e-b834-23a5c15657da-1474471336781\"," + EOL +
- " \"sdncService\": \"vhnf\"," + EOL +
- " \"sdncOperation\": \"service-topology-cust-assign-operation\"," + EOL +
- " \"sdncServiceDataType\": \"XML\"," + EOL +
- " \"sdncServiceData\": \"<vhnf-cust-stage-information><dhv-service-instance-id>c26dfed652164d60a17461734422b085</dhv-service-instance-id><hnportal-primary-vnf-host-name>HOSTNAME</hnportal-primary-vnf-host-name></vhnf-cust-stage-information>\"" + EOL +
- " }" + EOL +
- "}" + EOL;
-
- private final String SDNC_SERVICE_RESPONSE =
- "{" + EOL +
- " \"SDNCServiceResponse\": {" + EOL +
- " \"sdncRequestId\": \"413658f4-7f42-482e-b834-23a5c15657da-1474471336781\"," + EOL +
- " \"responseCode\": \"200\"," + EOL +
- "((RESPONSE-MESSAGE))" +
- " \"ackFinalIndicator\": \"Y\"" + EOL +
- "((RESPONSE-PARAMS))" +
- " }" + EOL +
- "}" + EOL;
-
- private final String SDNC_SERVICE_ERROR =
- "{" + EOL +
- " \"SDNCServiceError\": {" + EOL +
- " \"sdncRequestId\": \"413658f4-7f42-482e-b834-23a5c15657da-1474471336781\"," + EOL +
- " \"responseCode\": \"500\"," + EOL +
- "((RESPONSE-MESSAGE))" +
- " \"ackFinalIndicator\": \"Y\"" + EOL +
- " }" + EOL +
- "}" + EOL;
-
- private final String SDNC_EVENT =
- "{" + EOL +
- " \"SDNCEvent\": {" + EOL +
- " \"eventType\": \"ACTIVATION\"," + EOL +
- " \"eventCorrelatorType\": \"HOST-NAME\"," + EOL +
- " \"eventCorrelator\": \"USOSTCDALTX0101UJZZ31\"" + EOL +
- "((EVENT-PARAMS))" +
- " }" + EOL +
- "}" + EOL;
-
- private final String PARAMS =
- "{\"P1\":\"V1\",\"P2\":\"V2\",\"P3\":\"V3\"}";
-
- @Test
- public final void jsonToSDNCServiceRequest() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- String json = SDNC_SERVICE_REQUEST;
- json = json.replace("((BP-TIMEOUT))", "\"bpTimeout\": \"" + "PT5M" + "\"," + EOL);
-
- SDNCServiceRequest object = mapper.readValue(json, SDNCServiceRequest.class);
- assertEquals("413658f4-7f42-482e-b834-23a5c15657da", object.getRequestInformation().getRequestId());
- assertEquals("CCD", object.getRequestInformation().getSource());
- assertEquals("https://ccd-host:8080/notifications", object.getRequestInformation().getNotificationUrl());
- assertEquals("vHNFaaS", object.getServiceInformation().getServiceType());
- assertEquals("74e65b2b637441bca078e63e44bb511b", object.getServiceInformation().getServiceInstanceId());
- assertEquals("IST_SG_0902_3003", object.getServiceInformation().getSubscriberName());
- assertEquals("IST15_0902_3003", object.getServiceInformation().getSubscriberGlobalId());
- assertEquals("http://localhost:8080/mso/SDNCAdapterCallbackService", object.getBPNotificationUrl());
- assertEquals("PT5M", object.getBPTimeout());
- assertEquals("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", object.getSdncRequestId());
- assertEquals("vhnf", object.getSdncService());
- assertEquals("service-topology-cust-assign-operation", object.getSdncOperation());
- assertEquals("XML", object.getSdncServiceDataType());
- assertTrue(object.getSdncServiceData().startsWith("<vhnf-cust-stage-information>"));
- }
-
- @Test
- public final void jsonToSDNCServiceRequestWithoutOptionalFields() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- // bpTimeout is optional.
- String json = SDNC_SERVICE_REQUEST;
- json = json.replace("((BP-TIMEOUT))", "");
-
- SDNCServiceRequest object = mapper.readValue(json, SDNCServiceRequest.class);
- assertEquals("413658f4-7f42-482e-b834-23a5c15657da", object.getRequestInformation().getRequestId());
- assertEquals("CCD", object.getRequestInformation().getSource());
- assertEquals("https://ccd-host:8080/notifications", object.getRequestInformation().getNotificationUrl());
- assertEquals("vHNFaaS", object.getServiceInformation().getServiceType());
- assertEquals("74e65b2b637441bca078e63e44bb511b", object.getServiceInformation().getServiceInstanceId());
- assertEquals("IST_SG_0902_3003", object.getServiceInformation().getSubscriberName());
- assertEquals("IST15_0902_3003", object.getServiceInformation().getSubscriberGlobalId());
- assertEquals("http://localhost:8080/mso/SDNCAdapterCallbackService", object.getBPNotificationUrl());
- assertNull(object.getBPTimeout());
- assertEquals("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", object.getSdncRequestId());
- assertEquals("vhnf", object.getSdncService());
- assertEquals("service-topology-cust-assign-operation", object.getSdncOperation());
- assertEquals("XML", object.getSdncServiceDataType());
- assertTrue(object.getSdncServiceData().startsWith("<vhnf-cust-stage-information>"));
- }
-
- @Test
- public final void jsonFromSDNCServiceRequest() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- // Convert source json string to object.
- String json1 = SDNC_SERVICE_REQUEST;
- json1 = json1.replace("((BP-TIMEOUT))", "\"bpTimeout\": \"" + "PT5M" + "\"," + EOL);
- SDNCServiceRequest object1 = mapper.readValue(json1, SDNCServiceRequest.class);
-
- // Convert resulting object back to json.
- String json2 = object1.toJson();
- System.out.println("Generated JSON for " + object1.getClass().getSimpleName()
- + ":" + System.lineSeparator() + json2);
- assertTrue(json2.replaceAll("\\s+","").startsWith("{\"SDNCServiceRequest\":{"));
-
- // Convert generated json string to another object.
- SDNCServiceRequest object2 = mapper.readValue(json2, SDNCServiceRequest.class);
-
- // Compare the first object to the second object.
- assertTrue(serializedEquals(object1, object2));
- }
-
- @Test
- public final void jsonFromSDNCServiceRequestWithoutOptionalFields() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- // Convert source json string to object.
- String json1 = SDNC_SERVICE_REQUEST;
- json1 = json1.replace("((BP-TIMEOUT))", "");
- SDNCServiceRequest object1 = mapper.readValue(json1, SDNCServiceRequest.class);
-
- // Convert resulting object back to json.
- String json2 = object1.toJson();
- System.out.println("Generated JSON for " + object1.getClass().getSimpleName()
- + ":" + System.lineSeparator() + json2);
- assertTrue(json2.replaceAll("\\s+","").startsWith("{\"SDNCServiceRequest\":{"));
-
- // Convert generated json string to another object.
- SDNCServiceRequest object2 = mapper.readValue(json2, SDNCServiceRequest.class);
-
- // Compare the first object to the second object.
- assertTrue(serializedEquals(object1, object2));
- }
-
- @Test
- public final void jsonToSDNCServiceResponse() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- String json = SDNC_SERVICE_RESPONSE;
- json = json.replace("((RESPONSE-MESSAGE))", " \"responseMessage\": \"" + "OK" + "\"," + EOL);
- json = json.replace(EOL + "((RESPONSE-PARAMS))", "," + EOL + " \"params\": " + PARAMS + EOL);
-
- SDNCServiceResponse object = mapper.readValue(json, SDNCServiceResponse.class);
- assertEquals("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", object.getSdncRequestId());
- assertEquals("200", object.getResponseCode());
- assertEquals("OK", object.getResponseMessage());
- assertEquals("Y", object.getAckFinalIndicator());
- assertEquals("V1", object.getParams().get("P1"));
- assertEquals("V2", object.getParams().get("P2"));
- assertEquals("V3", object.getParams().get("P3"));
- }
-
- @Test
- public final void jsonToSDNCServiceResponseWithoutOptionalFields() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- // responseMessage is optional.
- String json = SDNC_SERVICE_RESPONSE;
- json = json.replace("((RESPONSE-MESSAGE))", "");
- json = json.replace("((RESPONSE-PARAMS))", "");
-
- SDNCServiceResponse object = mapper.readValue(json, SDNCServiceResponse.class);
- assertEquals("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", object.getSdncRequestId());
- assertEquals("200", object.getResponseCode());
- assertNull(object.getResponseMessage());
- assertEquals("Y", object.getAckFinalIndicator());
- assertNull(object.getParams());
- }
-
- @Test
- public final void jsonFromSDNCServiceResponse() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- // Convert source json string to object.
- String json1 = SDNC_SERVICE_RESPONSE;
- json1 = json1.replace("((RESPONSE-MESSAGE))", "\"responseMessage\": \"" + "OK" + "\"," + EOL);
- json1 = json1.replace(EOL + "((RESPONSE-PARAMS))", "," + EOL + " \"params\": " + PARAMS + EOL);
- SDNCServiceResponse object1 = mapper.readValue(json1, SDNCServiceResponse.class);
-
- // Convert resulting object back to json.
- String json2 = object1.toJson();
- System.out.println("Generated JSON for " + object1.getClass().getSimpleName()
- + ":" + System.lineSeparator() + json2);
- assertTrue(json2.replaceAll("\\s+","").startsWith("{\"SDNCServiceResponse\":{"));
-
- // Convert generated json string to another object.
- SDNCServiceResponse object2 = mapper.readValue(json2, SDNCServiceResponse.class);
-
- // Compare the first object to the second object.
- assertTrue(serializedEquals(object1, object2));
- }
-
- @Test
- public final void jsonFromSDNCServiceResponseWithoutOptionalFields() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- // Convert source json string to object.
- String json1 = SDNC_SERVICE_RESPONSE;
- json1 = json1.replace("((RESPONSE-MESSAGE))", "");
- json1 = json1.replace("((RESPONSE-PARAMS))", "");
- SDNCServiceResponse object1 = mapper.readValue(json1, SDNCServiceResponse.class);
-
- // Convert resulting object back to json.
- String json2 = object1.toJson();
- System.out.println("Generated JSON for " + object1.getClass().getSimpleName()
- + ":" + System.lineSeparator() + json2);
- assertTrue(json2.replaceAll("\\s+","").startsWith("{\"SDNCServiceResponse\":{"));
-
- // Convert generated json string to another object.
- SDNCServiceResponse object2 = mapper.readValue(json2, SDNCServiceResponse.class);
-
- // Compare the first object to the second object.
- assertTrue(serializedEquals(object1, object2));
- }
-
- @Test
- public final void jsonToSDNCServiceError() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- String json = SDNC_SERVICE_ERROR;
- json = json.replace("((RESPONSE-MESSAGE))", "\"responseMessage\": \"" + "SOMETHING BAD" + "\"," + EOL);
-
- SDNCServiceError object = mapper.readValue(json, SDNCServiceError.class);
- assertEquals("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", object.getSdncRequestId());
- assertEquals("500", object.getResponseCode());
- assertEquals("SOMETHING BAD", object.getResponseMessage());
- assertEquals("Y", object.getAckFinalIndicator());
- }
-
- @Test
- public final void jsonToSDNCServiceErrorWithoutOptionalFields() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- // responseMessage is optional.
- String json = SDNC_SERVICE_ERROR;
- json = json.replace("((RESPONSE-MESSAGE))", "");
-
- SDNCServiceError object = mapper.readValue(json, SDNCServiceError.class);
- assertEquals("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", object.getSdncRequestId());
- assertEquals("500", object.getResponseCode());
- assertNull(object.getResponseMessage());
- assertEquals("Y", object.getAckFinalIndicator());
- }
-
- @Test
- public final void jsonFromSDNCServiceError() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- // Convert source json string to object.
- String json1 = SDNC_SERVICE_ERROR;
- json1 = json1.replace("((RESPONSE-MESSAGE))", "\"responseMessage\": \"" + "OK" + "\"," + EOL);
- SDNCServiceError object1 = mapper.readValue(json1, SDNCServiceError.class);
-
- // Convert resulting object back to json.
- String json2 = object1.toJson();
- System.out.println("Generated JSON for " + object1.getClass().getSimpleName()
- + ":" + System.lineSeparator() + json2);
- assertTrue(json2.replaceAll("\\s+","").startsWith("{\"SDNCServiceError\":{"));
-
- // Convert generated json string to another object.
- SDNCServiceError object2 = mapper.readValue(json2, SDNCServiceError.class);
-
- // Compare the first object to the second object.
- assertTrue(serializedEquals(object1, object2));
- }
-
- @Test
- public final void jsonFromSDNCServiceErrorWithoutOptionalFields() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- // Convert source json string to object.
- String json1 = SDNC_SERVICE_ERROR;
- json1 = json1.replace("((RESPONSE-MESSAGE))", "");
- SDNCServiceError object1 = mapper.readValue(json1, SDNCServiceError.class);
-
- // Convert resulting object back to json.
- String json2 = object1.toJson();
- System.out.println("Generated JSON for " + object1.getClass().getSimpleName()
- + ":" + System.lineSeparator() + json2);
- assertTrue(json2.replaceAll("\\s+","").startsWith("{\"SDNCServiceError\":{"));
-
- // Convert generated json string to another object.
- SDNCServiceError object2 = mapper.readValue(json2, SDNCServiceError.class);
-
- // Compare the first object to the second object.
- assertTrue(serializedEquals(object1, object2));
- }
-
- @Test
- public final void jsonToSDNCEvent() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- String json = SDNC_EVENT;
- json = json.replace(EOL + "((EVENT-PARAMS))", "," + EOL + " \"params\": " + PARAMS + EOL);
-
- SDNCEvent object = mapper.readValue(json, SDNCEvent.class);
- assertEquals("ACTIVATION", object.getEventType());
- assertEquals("HOST-NAME", object.getEventCorrelatorType());
- assertEquals("USOSTCDALTX0101UJZZ31", object.getEventCorrelator());
- assertEquals("V1", object.getParams().get("P1"));
- assertEquals("V2", object.getParams().get("P2"));
- assertEquals("V3", object.getParams().get("P3"));
- }
-
- @Test
- public final void jsonToSDNCEventWithoutOptionalFields() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- // params are optional.
- String json = SDNC_EVENT;
- json = json.replace("((EVENT-PARAMS))", "");
-
- SDNCEvent object = mapper.readValue(json, SDNCEvent.class);
- assertEquals("ACTIVATION", object.getEventType());
- assertEquals("HOST-NAME", object.getEventCorrelatorType());
- assertEquals("USOSTCDALTX0101UJZZ31", object.getEventCorrelator());
- assertNull(object.getParams());
- }
-
- @Test
- public final void jsonFromSDNCEvent() throws Exception {
- logTest();
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
- mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
-
- // Convert source json string to object.
- String json1 = SDNC_EVENT;
- json1 = json1.replace(EOL + "((EVENT-PARAMS))", "," + EOL + " \"params\": " + PARAMS + EOL);
- SDNCEvent object1 = mapper.readValue(json1, SDNCEvent.class);
-
- // Convert resulting object back to json.
- String json2 = object1.toJson();
- System.out.println("Generated JSON for " + object1.getClass().getSimpleName()
- + ":" + System.lineSeparator() + json2);
- assertTrue(json2.replaceAll("\\s+","").startsWith("{\"SDNCEvent\":{"));
-
- // Convert generated json string to another object.
- SDNCEvent object2 = mapper.readValue(json2, SDNCEvent.class);
-
- // Compare the first object to the second object.
- assertTrue(serializedEquals(object1, object2));
- }
-
- /**
- * Tests equality of two objects by comparing their serialized form.
- * WARNING: this works pretty well as long as the objects don't contain
- * collections like maps and sets that are semantically equal, but have
- * different internal ordering of elements.
- */
- private boolean serializedEquals(Serializable object1, Serializable object2) throws IOException {
- ByteArrayOutputStream byteStream1 = new ByteArrayOutputStream();
- ObjectOutputStream objectStream1 = new ObjectOutputStream(byteStream1);
- objectStream1.writeObject(object1);
- objectStream1.close();
-
- ByteArrayOutputStream byteStream2 = new ByteArrayOutputStream();
- ObjectOutputStream objectStream2 = new ObjectOutputStream(byteStream2);
- objectStream2.writeObject(object2);
- objectStream2.close();
-
- return Arrays.equals(byteStream1.toByteArray(), byteStream2.toByteArray());
- }
-
- private void logTest() {
- StackTraceElement[] st = Thread.currentThread().getStackTrace();
- String method = st[2].getMethodName();
- System.out.println("RUNNING TEST: " + method);
- }
+ private static final String EOL = "\n";
+
+ private final String SDNC_SERVICE_REQUEST = "{" + EOL + " \"SDNCServiceRequest\": {" + EOL
+ + " \"requestInformation\": {" + EOL + " \"requestId\": \"413658f4-7f42-482e-b834-23a5c15657da\","
+ + EOL + " \"source\": \"CCD\"," + EOL
+ + " \"notificationUrl\": \"https://ccd-host:8080/notifications\"" + EOL + " }," + EOL
+ + " \"serviceInformation\": {" + EOL + " \"serviceType\": \"vHNFaaS\"," + EOL
+ + " \"serviceInstanceId\": \"74e65b2b637441bca078e63e44bb511b\"," + EOL
+ + " \"subscriberName\": \"IST_SG_0902_3003\"," + EOL + " \"subscriberGlobalId\": \"IST15_0902_3003\""
+ + EOL + " }," + EOL + " \"bpNotificationUrl\": \"http://localhost:8080/mso/SDNCAdapterCallbackService\","
+ + EOL + "((BP-TIMEOUT))" + " \"sdncRequestId\": \"413658f4-7f42-482e-b834-23a5c15657da-1474471336781\","
+ + EOL + " \"sdncService\": \"vhnf\"," + EOL
+ + " \"sdncOperation\": \"service-topology-cust-assign-operation\"," + EOL
+ + " \"sdncServiceDataType\": \"XML\"," + EOL
+ + " \"sdncServiceData\": \"<vhnf-cust-stage-information><dhv-service-instance-id>c26dfed652164d60a17461734422b085</dhv-service-instance-id><hnportal-primary-vnf-host-name>HOSTNAME</hnportal-primary-vnf-host-name></vhnf-cust-stage-information>\""
+ + EOL + " }" + EOL + "}" + EOL;
+
+ private final String SDNC_SERVICE_RESPONSE = "{" + EOL + " \"SDNCServiceResponse\": {" + EOL
+ + " \"sdncRequestId\": \"413658f4-7f42-482e-b834-23a5c15657da-1474471336781\"," + EOL
+ + " \"responseCode\": \"200\"," + EOL + "((RESPONSE-MESSAGE))" + " \"ackFinalIndicator\": \"Y\"" + EOL
+ + "((RESPONSE-PARAMS))" + " }" + EOL + "}" + EOL;
+
+ private final String SDNC_SERVICE_ERROR = "{" + EOL + " \"SDNCServiceError\": {" + EOL
+ + " \"sdncRequestId\": \"413658f4-7f42-482e-b834-23a5c15657da-1474471336781\"," + EOL
+ + " \"responseCode\": \"500\"," + EOL + "((RESPONSE-MESSAGE))" + " \"ackFinalIndicator\": \"Y\"" + EOL
+ + " }" + EOL + "}" + EOL;
+
+ private final String SDNC_EVENT = "{" + EOL + " \"SDNCEvent\": {" + EOL + " \"eventType\": \"ACTIVATION\","
+ + EOL + " \"eventCorrelatorType\": \"HOST-NAME\"," + EOL
+ + " \"eventCorrelator\": \"USOSTCDALTX0101UJZZ31\"" + EOL + "((EVENT-PARAMS))" + " }" + EOL + "}" + EOL;
+
+ private final String PARAMS = "{\"P1\":\"V1\",\"P2\":\"V2\",\"P3\":\"V3\"}";
+
+ @Test
+ public final void jsonToSDNCServiceRequest() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ String json = SDNC_SERVICE_REQUEST;
+ json = json.replace("((BP-TIMEOUT))", "\"bpTimeout\": \"" + "PT5M" + "\"," + EOL);
+
+ SDNCServiceRequest object = mapper.readValue(json, SDNCServiceRequest.class);
+ assertEquals("413658f4-7f42-482e-b834-23a5c15657da", object.getRequestInformation().getRequestId());
+ assertEquals("CCD", object.getRequestInformation().getSource());
+ assertEquals("https://ccd-host:8080/notifications", object.getRequestInformation().getNotificationUrl());
+ assertEquals("vHNFaaS", object.getServiceInformation().getServiceType());
+ assertEquals("74e65b2b637441bca078e63e44bb511b", object.getServiceInformation().getServiceInstanceId());
+ assertEquals("IST_SG_0902_3003", object.getServiceInformation().getSubscriberName());
+ assertEquals("IST15_0902_3003", object.getServiceInformation().getSubscriberGlobalId());
+ assertEquals("http://localhost:8080/mso/SDNCAdapterCallbackService", object.getBPNotificationUrl());
+ assertEquals("PT5M", object.getBPTimeout());
+ assertEquals("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", object.getSdncRequestId());
+ assertEquals("vhnf", object.getSdncService());
+ assertEquals("service-topology-cust-assign-operation", object.getSdncOperation());
+ assertEquals("XML", object.getSdncServiceDataType());
+ assertTrue(object.getSdncServiceData().startsWith("<vhnf-cust-stage-information>"));
+ }
+
+ @Test
+ public final void jsonToSDNCServiceRequestWithoutOptionalFields() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ // bpTimeout is optional.
+ String json = SDNC_SERVICE_REQUEST;
+ json = json.replace("((BP-TIMEOUT))", "");
+
+ SDNCServiceRequest object = mapper.readValue(json, SDNCServiceRequest.class);
+ assertEquals("413658f4-7f42-482e-b834-23a5c15657da", object.getRequestInformation().getRequestId());
+ assertEquals("CCD", object.getRequestInformation().getSource());
+ assertEquals("https://ccd-host:8080/notifications", object.getRequestInformation().getNotificationUrl());
+ assertEquals("vHNFaaS", object.getServiceInformation().getServiceType());
+ assertEquals("74e65b2b637441bca078e63e44bb511b", object.getServiceInformation().getServiceInstanceId());
+ assertEquals("IST_SG_0902_3003", object.getServiceInformation().getSubscriberName());
+ assertEquals("IST15_0902_3003", object.getServiceInformation().getSubscriberGlobalId());
+ assertEquals("http://localhost:8080/mso/SDNCAdapterCallbackService", object.getBPNotificationUrl());
+ assertNull(object.getBPTimeout());
+ assertEquals("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", object.getSdncRequestId());
+ assertEquals("vhnf", object.getSdncService());
+ assertEquals("service-topology-cust-assign-operation", object.getSdncOperation());
+ assertEquals("XML", object.getSdncServiceDataType());
+ assertTrue(object.getSdncServiceData().startsWith("<vhnf-cust-stage-information>"));
+ }
+
+ @Test
+ public final void jsonFromSDNCServiceRequest() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ // Convert source json string to object.
+ String json1 = SDNC_SERVICE_REQUEST;
+ json1 = json1.replace("((BP-TIMEOUT))", "\"bpTimeout\": \"" + "PT5M" + "\"," + EOL);
+ SDNCServiceRequest object1 = mapper.readValue(json1, SDNCServiceRequest.class);
+
+ // Convert resulting object back to json.
+ String json2 = object1.toJson();
+ System.out.println(
+ "Generated JSON for " + object1.getClass().getSimpleName() + ":" + System.lineSeparator() + json2);
+ assertTrue(json2.replaceAll("\\s+", "").startsWith("{\"SDNCServiceRequest\":{"));
+
+ // Convert generated json string to another object.
+ SDNCServiceRequest object2 = mapper.readValue(json2, SDNCServiceRequest.class);
+
+ // Compare the first object to the second object.
+ assertTrue(serializedEquals(object1, object2));
+ }
+
+ @Test
+ public final void jsonFromSDNCServiceRequestWithoutOptionalFields() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ // Convert source json string to object.
+ String json1 = SDNC_SERVICE_REQUEST;
+ json1 = json1.replace("((BP-TIMEOUT))", "");
+ SDNCServiceRequest object1 = mapper.readValue(json1, SDNCServiceRequest.class);
+
+ // Convert resulting object back to json.
+ String json2 = object1.toJson();
+ System.out.println(
+ "Generated JSON for " + object1.getClass().getSimpleName() + ":" + System.lineSeparator() + json2);
+ assertTrue(json2.replaceAll("\\s+", "").startsWith("{\"SDNCServiceRequest\":{"));
+
+ // Convert generated json string to another object.
+ SDNCServiceRequest object2 = mapper.readValue(json2, SDNCServiceRequest.class);
+
+ // Compare the first object to the second object.
+ assertTrue(serializedEquals(object1, object2));
+ }
+
+ @Test
+ public final void jsonToSDNCServiceResponse() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ String json = SDNC_SERVICE_RESPONSE;
+ json = json.replace("((RESPONSE-MESSAGE))", " \"responseMessage\": \"" + "OK" + "\"," + EOL);
+ json = json.replace(EOL + "((RESPONSE-PARAMS))", "," + EOL + " \"params\": " + PARAMS + EOL);
+
+ SDNCServiceResponse object = mapper.readValue(json, SDNCServiceResponse.class);
+ assertEquals("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", object.getSdncRequestId());
+ assertEquals("200", object.getResponseCode());
+ assertEquals("OK", object.getResponseMessage());
+ assertEquals("Y", object.getAckFinalIndicator());
+ assertEquals("V1", object.getParams().get("P1"));
+ assertEquals("V2", object.getParams().get("P2"));
+ assertEquals("V3", object.getParams().get("P3"));
+ }
+
+ @Test
+ public final void jsonToSDNCServiceResponseWithoutOptionalFields() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ // responseMessage is optional.
+ String json = SDNC_SERVICE_RESPONSE;
+ json = json.replace("((RESPONSE-MESSAGE))", "");
+ json = json.replace("((RESPONSE-PARAMS))", "");
+
+ SDNCServiceResponse object = mapper.readValue(json, SDNCServiceResponse.class);
+ assertEquals("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", object.getSdncRequestId());
+ assertEquals("200", object.getResponseCode());
+ assertNull(object.getResponseMessage());
+ assertEquals("Y", object.getAckFinalIndicator());
+ assertNull(object.getParams());
+ }
+
+ @Test
+ public final void jsonFromSDNCServiceResponse() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ // Convert source json string to object.
+ String json1 = SDNC_SERVICE_RESPONSE;
+ json1 = json1.replace("((RESPONSE-MESSAGE))", "\"responseMessage\": \"" + "OK" + "\"," + EOL);
+ json1 = json1.replace(EOL + "((RESPONSE-PARAMS))", "," + EOL + " \"params\": " + PARAMS + EOL);
+ SDNCServiceResponse object1 = mapper.readValue(json1, SDNCServiceResponse.class);
+
+ // Convert resulting object back to json.
+ String json2 = object1.toJson();
+ System.out.println(
+ "Generated JSON for " + object1.getClass().getSimpleName() + ":" + System.lineSeparator() + json2);
+ assertTrue(json2.replaceAll("\\s+", "").startsWith("{\"SDNCServiceResponse\":{"));
+
+ // Convert generated json string to another object.
+ SDNCServiceResponse object2 = mapper.readValue(json2, SDNCServiceResponse.class);
+
+ // Compare the first object to the second object.
+ assertTrue(serializedEquals(object1, object2));
+ }
+
+ @Test
+ public final void jsonFromSDNCServiceResponseWithoutOptionalFields() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ // Convert source json string to object.
+ String json1 = SDNC_SERVICE_RESPONSE;
+ json1 = json1.replace("((RESPONSE-MESSAGE))", "");
+ json1 = json1.replace("((RESPONSE-PARAMS))", "");
+ SDNCServiceResponse object1 = mapper.readValue(json1, SDNCServiceResponse.class);
+
+ // Convert resulting object back to json.
+ String json2 = object1.toJson();
+ System.out.println(
+ "Generated JSON for " + object1.getClass().getSimpleName() + ":" + System.lineSeparator() + json2);
+ assertTrue(json2.replaceAll("\\s+", "").startsWith("{\"SDNCServiceResponse\":{"));
+
+ // Convert generated json string to another object.
+ SDNCServiceResponse object2 = mapper.readValue(json2, SDNCServiceResponse.class);
+
+ // Compare the first object to the second object.
+ assertTrue(serializedEquals(object1, object2));
+ }
+
+ @Test
+ public final void jsonToSDNCServiceError() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ String json = SDNC_SERVICE_ERROR;
+ json = json.replace("((RESPONSE-MESSAGE))", "\"responseMessage\": \"" + "SOMETHING BAD" + "\"," + EOL);
+
+ SDNCServiceError object = mapper.readValue(json, SDNCServiceError.class);
+ assertEquals("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", object.getSdncRequestId());
+ assertEquals("500", object.getResponseCode());
+ assertEquals("SOMETHING BAD", object.getResponseMessage());
+ assertEquals("Y", object.getAckFinalIndicator());
+ }
+
+ @Test
+ public final void jsonToSDNCServiceErrorWithoutOptionalFields() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ // responseMessage is optional.
+ String json = SDNC_SERVICE_ERROR;
+ json = json.replace("((RESPONSE-MESSAGE))", "");
+
+ SDNCServiceError object = mapper.readValue(json, SDNCServiceError.class);
+ assertEquals("413658f4-7f42-482e-b834-23a5c15657da-1474471336781", object.getSdncRequestId());
+ assertEquals("500", object.getResponseCode());
+ assertNull(object.getResponseMessage());
+ assertEquals("Y", object.getAckFinalIndicator());
+ }
+
+ @Test
+ public final void jsonFromSDNCServiceError() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ // Convert source json string to object.
+ String json1 = SDNC_SERVICE_ERROR;
+ json1 = json1.replace("((RESPONSE-MESSAGE))", "\"responseMessage\": \"" + "OK" + "\"," + EOL);
+ SDNCServiceError object1 = mapper.readValue(json1, SDNCServiceError.class);
+
+ // Convert resulting object back to json.
+ String json2 = object1.toJson();
+ System.out.println(
+ "Generated JSON for " + object1.getClass().getSimpleName() + ":" + System.lineSeparator() + json2);
+ assertTrue(json2.replaceAll("\\s+", "").startsWith("{\"SDNCServiceError\":{"));
+
+ // Convert generated json string to another object.
+ SDNCServiceError object2 = mapper.readValue(json2, SDNCServiceError.class);
+
+ // Compare the first object to the second object.
+ assertTrue(serializedEquals(object1, object2));
+ }
+
+ @Test
+ public final void jsonFromSDNCServiceErrorWithoutOptionalFields() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ // Convert source json string to object.
+ String json1 = SDNC_SERVICE_ERROR;
+ json1 = json1.replace("((RESPONSE-MESSAGE))", "");
+ SDNCServiceError object1 = mapper.readValue(json1, SDNCServiceError.class);
+
+ // Convert resulting object back to json.
+ String json2 = object1.toJson();
+ System.out.println(
+ "Generated JSON for " + object1.getClass().getSimpleName() + ":" + System.lineSeparator() + json2);
+ assertTrue(json2.replaceAll("\\s+", "").startsWith("{\"SDNCServiceError\":{"));
+
+ // Convert generated json string to another object.
+ SDNCServiceError object2 = mapper.readValue(json2, SDNCServiceError.class);
+
+ // Compare the first object to the second object.
+ assertTrue(serializedEquals(object1, object2));
+ }
+
+ @Test
+ public final void jsonToSDNCEvent() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ String json = SDNC_EVENT;
+ json = json.replace(EOL + "((EVENT-PARAMS))", "," + EOL + " \"params\": " + PARAMS + EOL);
+
+ SDNCEvent object = mapper.readValue(json, SDNCEvent.class);
+ assertEquals("ACTIVATION", object.getEventType());
+ assertEquals("HOST-NAME", object.getEventCorrelatorType());
+ assertEquals("USOSTCDALTX0101UJZZ31", object.getEventCorrelator());
+ assertEquals("V1", object.getParams().get("P1"));
+ assertEquals("V2", object.getParams().get("P2"));
+ assertEquals("V3", object.getParams().get("P3"));
+ }
+
+ @Test
+ public final void jsonToSDNCEventWithoutOptionalFields() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ // params are optional.
+ String json = SDNC_EVENT;
+ json = json.replace("((EVENT-PARAMS))", "");
+
+ SDNCEvent object = mapper.readValue(json, SDNCEvent.class);
+ assertEquals("ACTIVATION", object.getEventType());
+ assertEquals("HOST-NAME", object.getEventCorrelatorType());
+ assertEquals("USOSTCDALTX0101UJZZ31", object.getEventCorrelator());
+ assertNull(object.getParams());
+ }
+
+ @Test
+ public final void jsonFromSDNCEvent() throws Exception {
+ logTest();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+
+ // Convert source json string to object.
+ String json1 = SDNC_EVENT;
+ json1 = json1.replace(EOL + "((EVENT-PARAMS))", "," + EOL + " \"params\": " + PARAMS + EOL);
+ SDNCEvent object1 = mapper.readValue(json1, SDNCEvent.class);
+
+ // Convert resulting object back to json.
+ String json2 = object1.toJson();
+ System.out.println(
+ "Generated JSON for " + object1.getClass().getSimpleName() + ":" + System.lineSeparator() + json2);
+ assertTrue(json2.replaceAll("\\s+", "").startsWith("{\"SDNCEvent\":{"));
+
+ // Convert generated json string to another object.
+ SDNCEvent object2 = mapper.readValue(json2, SDNCEvent.class);
+
+ // Compare the first object to the second object.
+ assertTrue(serializedEquals(object1, object2));
+ }
+
+ /**
+ * Tests equality of two objects by comparing their serialized form. WARNING: this works pretty well as long as the
+ * objects don't contain collections like maps and sets that are semantically equal, but have different internal
+ * ordering of elements.
+ */
+ private boolean serializedEquals(Serializable object1, Serializable object2) throws IOException {
+ ByteArrayOutputStream byteStream1 = new ByteArrayOutputStream();
+ ObjectOutputStream objectStream1 = new ObjectOutputStream(byteStream1);
+ objectStream1.writeObject(object1);
+ objectStream1.close();
+
+ ByteArrayOutputStream byteStream2 = new ByteArrayOutputStream();
+ ObjectOutputStream objectStream2 = new ObjectOutputStream(byteStream2);
+ objectStream2.writeObject(object2);
+ objectStream2.close();
+
+ return Arrays.equals(byteStream1.toByteArray(), byteStream2.toByteArray());
+ }
+
+ private void logTest() {
+ StackTraceElement[] st = Thread.currentThread().getStackTrace();
+ String method = st[2].getMethodName();
+ System.out.println("RUNNING TEST: " + method);
+ }
}
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnectorTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnectorTest.java
index 1de281bde4..e5b439228d 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnectorTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnectorTest.java
@@ -24,7 +24,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.junit.Assert.assertNotNull;
-
import org.apache.http.HttpStatus;
import org.junit.Test;
import org.onap.so.adapters.sdnc.BaseTest;
@@ -40,21 +39,20 @@ public class SDNCConnectorTest extends BaseTest {
public void sendTest() {
String content = "<dummy><service-instance-id>1234</service-instance-id></dummy>";
- String response = "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">\n" +
- "\t\t// <error>\n" +
- "\t\t// <error-type>protocol</error-type>\n" +
- "\t\t// <error-tag>malformed-message</error-tag>\n" +
- "\t\t// <error-message>Error parsing input: The element type \"input\" must be terminated by the matching end-tag \"&lt;/input&gt;\".</error-message>\n" +
- "\t\t// </error>\n" +
- "\t\t// </errors>";
+ String response = "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">\n" + "\t\t// <error>\n"
+ + "\t\t// <error-type>protocol</error-type>\n"
+ + "\t\t// <error-tag>malformed-message</error-tag>\n"
+ + "\t\t// <error-message>Error parsing input: The element type \"input\" must be terminated by the matching end-tag \"&lt;/input&gt;\".</error-message>\n"
+ + "\t\t// </error>\n" + "\t\t// </errors>";
TypedRequestTunables rt = new TypedRequestTunables("", "");
rt.setTimeout("1000");
rt.setReqMethod("POST");
rt.setSdncUrl("http://localhost:" + wireMockPort + "/sdnc");
- wireMockServer.stubFor(post(urlPathEqualTo("/sdnc"))
- .willReturn(aResponse().withHeader("Content-Type", "application/xml").withBody(response).withStatus(HttpStatus.SC_MULTIPLE_CHOICES)));
+ wireMockServer.stubFor(
+ post(urlPathEqualTo("/sdnc")).willReturn(aResponse().withHeader("Content-Type", "application/xml")
+ .withBody(response).withStatus(HttpStatus.SC_MULTIPLE_CHOICES)));
SDNCResponseCommon responseCommon = sdncConnector.send(content, rt);
assertNotNull(responseCommon);
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnectorTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnectorTest.java
index eddd74b213..9911cae677 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnectorTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnectorTest.java
@@ -23,7 +23,6 @@ package org.onap.so.adapters.sdnc.sdncrest;
import org.junit.Test;
import org.onap.so.adapters.sdnc.FileUtil;
import org.onap.so.adapters.sdncrest.SDNCResponseCommon;
-
import static org.junit.Assert.assertNotNull;
public class SDNCServiceRequestConnectorTest {
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtilTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtilTest.java
index 7ba8b68602..aa856acd2e 100644
--- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtilTest.java
+++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/util/SDNCRequestIdUtilTest.java
@@ -21,9 +21,7 @@
package org.onap.so.adapters.sdnc.util;
import static org.junit.Assert.assertEquals;
-
import java.util.UUID;
-
import org.junit.Test;
@@ -33,14 +31,14 @@ public class SDNCRequestIdUtilTest {
* Test method for {@link org.onap.so.adapters.sdnc.SDNCRequestIdUtil#getSDNCOriginalRequestId()}.
*/
@Test
- public final void testGetSDNCOriginalRequestId () {
- String originalRequestId = UUID.randomUUID().toString();
- String postfixedRequestId = originalRequestId + "-1466203712068";
- String postfixedRequestId2 = originalRequestId + "-1466203712068-2";
+ public final void testGetSDNCOriginalRequestId() {
+ String originalRequestId = UUID.randomUUID().toString();
+ String postfixedRequestId = originalRequestId + "-1466203712068";
+ String postfixedRequestId2 = originalRequestId + "-1466203712068-2";
assertEquals(originalRequestId, SDNCRequestIdUtil.getSDNCOriginalRequestId(postfixedRequestId));
assertEquals(postfixedRequestId2, SDNCRequestIdUtil.getSDNCOriginalRequestId(postfixedRequestId2));
-
+
}
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/CXFConfiguration.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/CXFConfiguration.java
index 656a246afc..5ea68f08a2 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/CXFConfiguration.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/CXFConfiguration.java
@@ -21,7 +21,6 @@
package org.onap.so.adapters.vfc;
import java.util.Arrays;
-
import org.apache.cxf.Bus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.feature.LoggingFeature;
@@ -34,7 +33,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
@@ -42,45 +40,45 @@ import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
@Configuration
public class CXFConfiguration {
- @Autowired
- private Bus bus;
+ @Autowired
+ private Bus bus;
- @Autowired
+ @Autowired
private VfcAdapterRest vfcAdapterRest;
-
+
@Autowired
private JaxRsFilterLogging jaxRsFilterLogging;
-
+
@Autowired
- private ObjectMapper mapper;
-
- @Bean
- public ServletRegistrationBean cxfServlet() {
- return new ServletRegistrationBean(new CXFServlet(), "/services/*");
- }
-
+ private ObjectMapper mapper;
+
+ @Bean
+ public ServletRegistrationBean cxfServlet() {
+ return new ServletRegistrationBean(new CXFServlet(), "/services/*");
+ }
+
@Bean
public Server rsServer() {
JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
endpoint.setBus(bus);
endpoint.setServiceBeans(Arrays.<Object>asList(vfcAdapterRest));
- endpoint.setAddress("/");
+ endpoint.setAddress("/");
endpoint.setFeatures(Arrays.asList(createSwaggerFeature(), new LoggingFeature()));
- endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(mapper),jaxRsFilterLogging));
+ endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(mapper), jaxRsFilterLogging));
return endpoint.create();
}
-
- @Bean
- public Swagger2Feature createSwaggerFeature() {
- Swagger2Feature swagger2Feature = new Swagger2Feature();
- swagger2Feature.setPrettyPrint(true);
- swagger2Feature.setTitle("SO VFC Adapter");
- swagger2Feature.setContact("The ONAP SO team");
- swagger2Feature.setDescription("This project is the SO Orchestration Engine");
- swagger2Feature.setVersion("1.0.0");
- swagger2Feature.setResourcePackage("org.onap.so.adapters.vfc.rest");
- swagger2Feature.setScan(true);
- return swagger2Feature;
- }
+
+ @Bean
+ public Swagger2Feature createSwaggerFeature() {
+ Swagger2Feature swagger2Feature = new Swagger2Feature();
+ swagger2Feature.setPrettyPrint(true);
+ swagger2Feature.setTitle("SO VFC Adapter");
+ swagger2Feature.setContact("The ONAP SO team");
+ swagger2Feature.setDescription("This project is the SO Orchestration Engine");
+ swagger2Feature.setVersion("1.0.0");
+ swagger2Feature.setResourcePackage("org.onap.so.adapters.vfc.rest");
+ swagger2Feature.setScan(true);
+ return swagger2Feature;
+ }
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/RequestDBConfig.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/RequestDBConfig.java
index 8db210f62a..d7397c8df3 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/RequestDBConfig.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/RequestDBConfig.java
@@ -23,7 +23,6 @@ package org.onap.so.adapters.vfc;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
-
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -41,40 +40,30 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Profile({"!test"})
@Configuration
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager",
- basePackages = { "org.onap.so.db.request.data.repository" }
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory",
+ transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"})
public class RequestDBConfig {
- @Primary
- @Bean(name = "requestDataSource")
- @ConfigurationProperties(prefix = "spring.datasource")
- public DataSource dataSource() {
- return DataSourceBuilder.create().build();
- }
+ @Primary
+ @Bean(name = "requestDataSource")
+ @ConfigurationProperties(prefix = "spring.datasource")
+ public DataSource dataSource() {
+ return DataSourceBuilder.create().build();
+ }
- @Primary
- @Bean(name = "requestEntityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("requestDataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.request.beans")
- .persistenceUnit("requestDB")
- .build();
- }
+ @Primary
+ @Bean(name = "requestEntityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("requestDataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB")
+ .build();
+ }
- @Primary
- @Bean(name = "requestTransactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("requestEntityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
+ @Primary
+ @Bean(name = "requestTransactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/WebSecurityConfigImpl.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/WebSecurityConfigImpl.java
index 37a5633d8d..4270be4897 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/WebSecurityConfigImpl.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/WebSecurityConfigImpl.java
@@ -31,21 +31,18 @@ import org.springframework.util.StringUtils;
@EnableWebSecurity
public class WebSecurityConfigImpl extends WebSecurityConfig {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf().disable()
- .authorizeRequests()
- .antMatchers("/manage/health","/manage/info","/services").permitAll()
- .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),",").toString())
- .and()
- .httpBasic();
- }
-
- @Override
- public void configure(WebSecurity web) throws Exception {
- super.configure(web);
- StrictHttpFirewall firewall = new MSOSpringFirewall();
- web.httpFirewall(firewall);
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info", "/services").permitAll()
+ .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",").toString())
+ .and().httpBasic();
+ }
-} \ No newline at end of file
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ super.configure(web);
+ StrictHttpFirewall firewall = new MSOSpringFirewall();
+ web.httpFirewall(firewall);
+ }
+
+}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/constant/CommonConstant.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/constant/CommonConstant.java
index 128dc52d36..04c6749b61 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/constant/CommonConstant.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/constant/CommonConstant.java
@@ -21,16 +21,15 @@
package org.onap.so.adapters.vfc.constant;
/**
- * CommonConstant
- * <br>
+ * CommonConstant <br>
* <p>
* </p>
*
* @author
- * @version ONAP Amsterdam Release 2017-08-28
+ * @version ONAP Amsterdam Release 2017-08-28
*/
public class CommonConstant {
-
+
public static final String STR_EMPTY = "";
public static final String NFVO_CREATE_URL = "/api/nslcm/v1/ns";
@@ -52,7 +51,7 @@ public class CommonConstant {
* </p>
*
* @author
- * @version ONAP Amsterdam Release 2017-08-28
+ * @version ONAP Amsterdam Release 2017-08-28
*/
public static class MethodType {
@@ -76,7 +75,7 @@ public class CommonConstant {
* </p>
*
* @author
- * @version ONAP Amsterdam Release 2017-08-28
+ * @version ONAP Amsterdam Release 2017-08-28
*/
public static class Step {
@@ -133,7 +132,7 @@ public class CommonConstant {
}
}
-
+
private CommonConstant() {
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/constant/DriverExceptionID.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/constant/DriverExceptionID.java
index f82a38e324..61330027c5 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/constant/DriverExceptionID.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/constant/DriverExceptionID.java
@@ -31,34 +31,32 @@ package org.onap.so.adapters.vfc.constant;
*/
public class DriverExceptionID {
- public static final String INVALID_RESPONSE_FROM_INSTANTIATE_OPERATION =
- "Invalid response from instantiate operation";
+ public static final String INVALID_RESPONSE_FROM_INSTANTIATE_OPERATION =
+ "Invalid response from instantiate operation";
- public static final String INVALID_RESPONSEE_FROM_CREATE_OPERATION =
- "Invalid response from create operation";
+ public static final String INVALID_RESPONSEE_FROM_CREATE_OPERATION = "Invalid response from create operation";
- public static final String FAIL_TO_INSTANTIATE_NS = "Fail to instantiate ns";
+ public static final String FAIL_TO_INSTANTIATE_NS = "Fail to instantiate ns";
- public static final String FAIL_TO_CREATE_NS = "Fail to create ns";
+ public static final String FAIL_TO_CREATE_NS = "Fail to create ns";
- public static final String INVALID_RESPONSE_FROM_TERMINATE_OPERATION =
- "Invalid response from terminate operation";
+ public static final String INVALID_RESPONSE_FROM_TERMINATE_OPERATION = "Invalid response from terminate operation";
- public static final String FAIL_TO_DELETE_NS = "Fail to delete ns";
+ public static final String FAIL_TO_DELETE_NS = "Fail to delete ns";
- public static final String FAIL_TO_TERMINATE_NS = "Fail to terminate ns";
+ public static final String FAIL_TO_TERMINATE_NS = "Fail to terminate ns";
- public static final String JOB_STATUS_ERROR = "Job status error";
+ public static final String JOB_STATUS_ERROR = "Job status error";
- public static final String FAIL_TO_QUERY_JOB_STATUS = "Fail to query job status";
+ public static final String FAIL_TO_QUERY_JOB_STATUS = "Fail to query job status";
- public static final String FAIL_TO_SCALE_NS = "Fail to scale network service";
+ public static final String FAIL_TO_SCALE_NS = "Fail to scale network service";
- public static final String INVALID_RESPONSE_FROM_SCALE_OPERATION = "Invalid response from scale operation";
+ public static final String INVALID_RESPONSE_FROM_SCALE_OPERATION = "Invalid response from scale operation";
- private DriverExceptionID() {
+ private DriverExceptionID() {
- }
+ }
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/exceptions/ApplicationException.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/exceptions/ApplicationException.java
index 1e712cb76b..88260a7100 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/exceptions/ApplicationException.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/exceptions/ApplicationException.java
@@ -64,8 +64,7 @@ public class ApplicationException extends Exception {
}
/**
- * build error Response
- * <br>
+ * build error Response <br>
*
* @return
* @since ONAP Amsterdam Release
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/CustomerModel.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/CustomerModel.java
index 986d168482..e54f0dfb6d 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/CustomerModel.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/CustomerModel.java
@@ -21,21 +21,20 @@
package org.onap.so.adapters.vfc.model;
/**
- * The Customer Model
- * <br>
+ * The Customer Model <br>
* <p>
* </p>
*
* @author
- * @version ONAP Amsterdam Release 2017-10-12
+ * @version ONAP Amsterdam Release 2017-10-12
*/
public class CustomerModel {
-
+
String globalCustomerId;
String serviceType;
-
+
/**
* @return Returns the globalCustomerId.
*/
@@ -43,7 +42,7 @@ public class CustomerModel {
return globalCustomerId;
}
-
+
/**
* @param globalCustomerId The globalCustomerId to set.
*/
@@ -51,7 +50,7 @@ public class CustomerModel {
this.globalCustomerId = globalCustomerId;
}
-
+
/**
* @return Returns the serviceType.
*/
@@ -59,12 +58,12 @@ public class CustomerModel {
return serviceType;
}
-
+
/**
* @param serviceType The serviceType to set.
*/
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
-
+
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/LocationConstraint.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/LocationConstraint.java
index a28bd9a501..b79565d7a9 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/LocationConstraint.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/LocationConstraint.java
@@ -54,7 +54,7 @@ public class LocationConstraint {
this.vnfProfileId = vnfProfileId;
}
-
+
/**
* @return Returns the locationConstraints.
*/
@@ -62,7 +62,7 @@ public class LocationConstraint {
return locationConstraints;
}
-
+
/**
* @param locationConstraints The locationConstraints to set.
*/
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NSResourceInputParameter.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NSResourceInputParameter.java
index 5d9b7ce558..266e5ee5d8 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NSResourceInputParameter.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NSResourceInputParameter.java
@@ -23,10 +23,8 @@
package org.onap.so.adapters.vfc.model;
import java.io.ByteArrayOutputStream;
-
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.slf4j.Logger;
@@ -42,20 +40,20 @@ import org.slf4j.LoggerFactory;
public class NSResourceInputParameter {
private static final Logger logger = LoggerFactory.getLogger(NSResourceInputParameter.class);
-
+
private NsOperationKey nsOperationKey;
private String nsServiceName;
private String nsServiceDescription;
-
+
private String nsServiceModelUUID;
private NsParameters nsParameters;
private NsScaleParameters nsScaleParameters;
-
+
/**
* @return Returns the nsServiceName.
*/
@@ -63,7 +61,7 @@ public class NSResourceInputParameter {
return nsServiceName;
}
-
+
/**
* @param nsServiceName The nsServiceName to set.
*/
@@ -71,7 +69,7 @@ public class NSResourceInputParameter {
this.nsServiceName = nsServiceName;
}
-
+
/**
* @return Returns the nsServiceDescription.
*/
@@ -79,7 +77,7 @@ public class NSResourceInputParameter {
return nsServiceDescription;
}
-
+
/**
* @param nsServiceDescription The nsServiceDescription to set.
*/
@@ -108,6 +106,7 @@ public class NSResourceInputParameter {
public void setNsOperationKey(NsOperationKey nsOperationKey) {
this.nsOperationKey = nsOperationKey;
}
+
public String toJsonString() {
String jsonString = null;
try {
@@ -125,7 +124,7 @@ public class NSResourceInputParameter {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
JAXBContext context = JAXBContext.newInstance(this.getClass());
Marshaller marshaller = context.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //pretty print XML
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // pretty print XML
marshaller.marshal(this, bs);
return bs.toString();
} catch (Exception e) {
@@ -143,13 +142,13 @@ public class NSResourceInputParameter {
}
- public String getNsServiceModelUUID() {
- return nsServiceModelUUID;
- }
+ public String getNsServiceModelUUID() {
+ return nsServiceModelUUID;
+ }
+
+ public void setNsServiceModelUUID(String nsServiceModelUUID) {
+ this.nsServiceModelUUID = nsServiceModelUUID;
+ }
- public void setNsServiceModelUUID(String nsServiceModelUUID) {
- this.nsServiceModelUUID = nsServiceModelUUID;
- }
-
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsCreateReq.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsCreateReq.java
index 2d09f55de2..63358cb384 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsCreateReq.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsCreateReq.java
@@ -31,14 +31,14 @@ package org.onap.so.adapters.vfc.model;
public class NsCreateReq {
CustomerModel context;
-
+
String csarId;
String nsName;
String description;
-
-
+
+
/**
* @return Returns the context.
*/
@@ -47,7 +47,7 @@ public class NsCreateReq {
}
-
+
/**
* @param context The context to set.
*/
@@ -63,7 +63,7 @@ public class NsCreateReq {
return csarId;
}
-
+
/**
* @param csarId The csarId to set.
*/
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsOperationKey.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsOperationKey.java
index bc67832cb2..2088d68b56 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsOperationKey.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsOperationKey.java
@@ -21,8 +21,7 @@
package org.onap.so.adapters.vfc.model;
/**
- * The operation key object for NS
- * <br>
+ * The operation key object for NS <br>
* <p>
* </p>
*
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsParameters.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsParameters.java
index 5da3d806f1..e82ee2a79a 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsParameters.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsParameters.java
@@ -37,6 +37,7 @@ public class NsParameters {
private List<LocationConstraint> locationConstraints;
private Map<String, Object> additionalParamForNs = new HashMap<>();
+
/**
* @return Returns the locationConstraints.
*/
@@ -51,7 +52,7 @@ public class NsParameters {
this.locationConstraints = locationConstraints;
}
-
+
/**
* @return Returns the additionalParamForNs.
*/
@@ -59,7 +60,7 @@ public class NsParameters {
return additionalParamForNs;
}
-
+
/**
* @param additionalParamForNs The additionalParamForNs to set.
*/
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsScaleParameters.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsScaleParameters.java
index e4e217a9f5..6d089c0479 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsScaleParameters.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/NsScaleParameters.java
@@ -38,29 +38,29 @@ public class NsScaleParameters {
/**
* @return Returns the scaleNsByStepsData.
*/
- public List<ScaleNsByStepsData> getScaleNsByStepsData() {
- return scaleNsByStepsData;
- }
+ public List<ScaleNsByStepsData> getScaleNsByStepsData() {
+ return scaleNsByStepsData;
+ }
- /**
- * @param scaleNsByStepsData The scaleNsByStepsData to set.
- */
- public void setScaleNsByStepsData(List<ScaleNsByStepsData> scaleNsByStepsData) {
- this.scaleNsByStepsData = scaleNsByStepsData;
- }
+ /**
+ * @param scaleNsByStepsData The scaleNsByStepsData to set.
+ */
+ public void setScaleNsByStepsData(List<ScaleNsByStepsData> scaleNsByStepsData) {
+ this.scaleNsByStepsData = scaleNsByStepsData;
+ }
- /**
- * @return Returns the scale Type.
- */
- public String getScaleType() {
- return scaleType;
- }
+ /**
+ * @return Returns the scale Type.
+ */
+ public String getScaleType() {
+ return scaleType;
+ }
- /**
- * @param scaleType The scaleType to set.
- */
- public void setScaleType(String scaleType) {
- this.scaleType = scaleType;
- }
+ /**
+ * @param scaleType The scaleType to set.
+ */
+ public void setScaleType(String scaleType) {
+ this.scaleType = scaleType;
+ }
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ResponseDescriptor.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ResponseDescriptor.java
index 08e3dcae4f..3ea51c107b 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ResponseDescriptor.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ResponseDescriptor.java
@@ -19,6 +19,7 @@
*/
package org.onap.so.adapters.vfc.model;
+
/**
* <br>
* <p>
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/RestfulResponse.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/RestfulResponse.java
index ee5ecd6e19..27c9a89282 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/RestfulResponse.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/RestfulResponse.java
@@ -23,23 +23,22 @@ package org.onap.so.adapters.vfc.model;
import java.util.Map;
/**
- * The Unified Restful Reponse Class
- * <br>
+ * The Unified Restful Reponse Class <br>
* <p>
* </p>
*
* @author
- * @version ONAP Amsterdam Release 2017-09-06
+ * @version ONAP Amsterdam Release 2017-09-06
*/
public class RestfulResponse {
// the response content
private String responseContent;
- //the response status
+ // the response status
private int status;
- //the response header
+ // the response header
private Map<String, String> respHeaderMap;
public RestfulResponse() {
@@ -65,9 +64,9 @@ public class RestfulResponse {
}
public int getRespHeaderInt(String key) {
- if(this.respHeaderMap != null) {
+ if (this.respHeaderMap != null) {
String result = this.respHeaderMap.get(key);
- if(result != null) {
+ if (result != null) {
return Integer.parseInt(result);
}
}
@@ -75,9 +74,9 @@ public class RestfulResponse {
}
public long getRespHeaderLong(String key) {
- if(this.respHeaderMap != null) {
+ if (this.respHeaderMap != null) {
String result = this.respHeaderMap.get(key);
- if(result != null) {
+ if (result != null) {
return Long.parseLong(result);
}
}
@@ -85,7 +84,7 @@ public class RestfulResponse {
}
public String getRespHeaderStr(String key) {
- if(this.respHeaderMap != null) {
+ if (this.respHeaderMap != null) {
return this.respHeaderMap.get(key);
}
return null;
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ScaleNsByStepsData.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ScaleNsByStepsData.java
index 938064d3a2..f9d6274643 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ScaleNsByStepsData.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ScaleNsByStepsData.java
@@ -33,12 +33,12 @@ public class ScaleNsByStepsData {
* scaling Direction
*/
private String scalingDirection;
-
+
/**
* aspect ID
*/
private String aspectId;
-
+
/**
* number of Steps
*/
@@ -61,28 +61,28 @@ public class ScaleNsByStepsData {
/**
* @return Returns the aspectId.
*/
- public String getAspectId() {
- return aspectId;
- }
+ public String getAspectId() {
+ return aspectId;
+ }
/**
* @param aspectId The aspectId to set.
*/
- public void setAspectId(String aspectId) {
- this.aspectId = aspectId;
- }
+ public void setAspectId(String aspectId) {
+ this.aspectId = aspectId;
+ }
/**
* @return Returns the numberOfSteps.
*/
- public Integer getNumberOfSteps() {
- return numberOfSteps;
- }
+ public Integer getNumberOfSteps() {
+ return numberOfSteps;
+ }
/**
* @param numberOfSteps The numberOfSteps to set.
*/
- public void setNumberOfSteps(int numberOfSteps) {
- this.numberOfSteps = numberOfSteps;
- }
+ public void setNumberOfSteps(int numberOfSteps) {
+ this.numberOfSteps = numberOfSteps;
+ }
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ScaleNsData.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ScaleNsData.java
index b0ad26ae3f..bd50827549 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ScaleNsData.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/ScaleNsData.java
@@ -23,11 +23,10 @@ package org.onap.so.adapters.vfc.model;
import java.util.List;
/**
- * aim to wrap List<ScaleNsByStepsData> as a new list
- * then be provided for the usage of vfc json
+ * aim to wrap List<ScaleNsByStepsData> as a new list then be provided for the usage of vfc json
*
* added on 2018/01/30 by Qihui Zhao from CMCC
- * */
+ */
public class ScaleNsData {
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/VFCScaleData.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/VFCScaleData.java
index 4a393e1064..1939fa4ec4 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/VFCScaleData.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/VFCScaleData.java
@@ -24,10 +24,10 @@ import java.util.ArrayList;
import java.util.List;
/**
- * Object totally matches required VFC input json format
- * JsonUtil.marshal will convert this Object to string
+ * Object totally matches required VFC input json format JsonUtil.marshal will convert this Object to string
*
- * added on 2018/01/30 by Qihui Zhao from CMCC*/
+ * added on 2018/01/30 by Qihui Zhao from CMCC
+ */
public class VFCScaleData {
@@ -66,14 +66,16 @@ public class VFCScaleData {
}
/**
- *@return Returns the scaleNsDate.
+ * @return Returns the scaleNsDate.
*/
- public List<ScaleNsData> getScaleNsData(){return scaleNsData;}
+ public List<ScaleNsData> getScaleNsData() {
+ return scaleNsData;
+ }
/**
* The scaleNsData to set.
*/
- public void setScaleNsData(List<ScaleNsByStepsData> scaleNsByStepsData){
+ public void setScaleNsData(List<ScaleNsByStepsData> scaleNsByStepsData) {
ScaleNsData scaleNsDataObj = new ScaleNsData();
scaleNsDataObj.setScaleNsByStepsData(scaleNsByStepsData);
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/VimLocation.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/VimLocation.java
index 9f6f8ec274..456835b431 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/VimLocation.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/model/VimLocation.java
@@ -27,12 +27,12 @@ package org.onap.so.adapters.vfc.model;
* </p>
*
* @author
- * @version ONAP Amsterdam Release 2017-10-18
+ * @version ONAP Amsterdam Release 2017-10-18
*/
public class VimLocation {
private String vimId;
-
+
/**
* @return Returns the vimId.
*/
@@ -40,12 +40,12 @@ public class VimLocation {
return vimId;
}
-
+
/**
* @param vimId The vimId to set.
*/
public void setVimId(String vimId) {
this.vimId = vimId;
}
-
+
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/AaiUtil.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/AaiUtil.java
index 6ae2ba0aca..7f81dfbdaf 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/AaiUtil.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/AaiUtil.java
@@ -32,16 +32,16 @@ import org.onap.so.adapters.vfc.model.RestfulResponse;
*/
public class AaiUtil {
- public static RestfulResponse addRelation(String globalSubsriberId, String serviceType,
- String serviceInstanceId, String resourceInstanceId) {
- // sent rest to aai to add relation for service and ns.
-
- return null;
- }
+ public static RestfulResponse addRelation(String globalSubsriberId, String serviceType, String serviceInstanceId,
+ String resourceInstanceId) {
+ // sent rest to aai to add relation for service and ns.
- public static RestfulResponse removeRelation(String globalSubsriberId, String serviceType,
- String serviceInstanceId, String resourceInstanceId) {
- // sent rest to aai to remove relation between service an ns.
- return null;
- }
+ return null;
+ }
+
+ public static RestfulResponse removeRelation(String globalSubsriberId, String serviceType, String serviceInstanceId,
+ String resourceInstanceId) {
+ // sent rest to aai to remove relation between service an ns.
+ return null;
+ }
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/HealthCheckHandler.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/HealthCheckHandler.java
index 52fd8fb103..cff36061b1 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/HealthCheckHandler.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/HealthCheckHandler.java
@@ -27,20 +27,18 @@ import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
- * Health Check
- * <br>
+ * Health Check <br>
* <p>
* </p>
*
* @author
- * @version ONAP Amsterdam Release 2017-08-28
+ * @version ONAP Amsterdam Release 2017-08-28
*/
@Path("/")
@Component
@@ -48,12 +46,11 @@ public class HealthCheckHandler {
private static Logger logger = LoggerFactory.getLogger(HealthCheckHandler.class);
-
- private static final String CHECK_HTML = "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Health Check</title></head><body>Application ready</body></html>";
- public static final Response HEALTH_CHECK_RESPONSE = Response.status (HttpStatus.SC_OK)
- .entity (CHECK_HTML)
- .build ();
+ private static final String CHECK_HTML =
+ "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Health Check</title></head><body>Application ready</body></html>";
+
+ public static final Response HEALTH_CHECK_RESPONSE = Response.status(HttpStatus.SC_OK).entity(CHECK_HTML).build();
@HEAD
@Path("/healthcheck")
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcAdapterRest.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcAdapterRest.java
index db613ea988..bb9ae69f51 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcAdapterRest.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcAdapterRest.java
@@ -55,10 +55,10 @@ import org.springframework.stereotype.Component;
public class VfcAdapterRest {
private static final Logger logger = LoggerFactory.getLogger(VfcAdapterRest.class);
- private static final String REQUEST_DEBUG_MSG="body from request is {}";
- private static final String APPLICATION_EXCEPTION="ApplicationException: ";
+ private static final String REQUEST_DEBUG_MSG = "body from request is {}";
+ private static final String APPLICATION_EXCEPTION = "ApplicationException: ";
@Autowired
- private VfcManager driverMgr ;
+ private VfcManager driverMgr;
public VfcAdapterRest() {
@@ -82,7 +82,7 @@ public class VfcAdapterRest {
NSResourceInputParameter nsInput = JsonUtil.unMarshal(data, NSResourceInputParameter.class);
RestfulResponse rsp = driverMgr.createNs(nsInput);
return buildResponse(rsp);
- } catch(ApplicationException e) {
+ } catch (ApplicationException e) {
logger.debug(APPLICATION_EXCEPTION, e);
return e.buildErrorResponse();
}
@@ -92,7 +92,7 @@ public class VfcAdapterRest {
* Delete NS instance<br>
*
* @param data The http request
- * @param nsInstanceId The NS instance id
+ * @param nsInstanceId The NS instance id
* @return response
* @since ONAP Amsterdam Release
*/
@@ -108,7 +108,7 @@ public class VfcAdapterRest {
NsOperationKey nsOperationKey = JsonUtil.unMarshal(data, NsOperationKey.class);
RestfulResponse rsp = driverMgr.deleteNs(nsOperationKey, nsInstanceId);
return buildResponse(rsp);
- } catch(ApplicationException e) {
+ } catch (ApplicationException e) {
logger.debug(APPLICATION_EXCEPTION, e);
return e.buildErrorResponse();
}
@@ -133,7 +133,7 @@ public class VfcAdapterRest {
NsOperationKey nsOperationKey = JsonUtil.unMarshal(data, NsOperationKey.class);
RestfulResponse rsp = driverMgr.getNsProgress(nsOperationKey, jobId);
return buildResponse(rsp);
- } catch(ApplicationException e) {
+ } catch (ApplicationException e) {
logger.debug(APPLICATION_EXCEPTION, e);
return e.buildErrorResponse();
}
@@ -158,7 +158,7 @@ public class VfcAdapterRest {
NSResourceInputParameter nsInput = JsonUtil.unMarshal(data, NSResourceInputParameter.class);
RestfulResponse rsp = driverMgr.instantiateNs(nsInstanceId, nsInput);
return buildResponse(rsp);
- } catch(ApplicationException e) {
+ } catch (ApplicationException e) {
logger.debug(APPLICATION_EXCEPTION, e);
return e.buildErrorResponse();
}
@@ -183,15 +183,14 @@ public class VfcAdapterRest {
NsOperationKey nsOperationKey = JsonUtil.unMarshal(data, NsOperationKey.class);
RestfulResponse rsp = driverMgr.terminateNs(nsOperationKey, nsInstanceId);
return buildResponse(rsp);
- } catch(ApplicationException e) {
+ } catch (ApplicationException e) {
logger.debug(APPLICATION_EXCEPTION, e);
return e.buildErrorResponse();
}
}
/**
- * Scale NS instance
- * <br>
+ * Scale NS instance <br>
*
* @param servletReq The http request
* @param nsInstanceId The NS instance id
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcManager.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcManager.java
index 86aba2f84b..b817b5bf9a 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcManager.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/rest/VfcManager.java
@@ -22,7 +22,6 @@ package org.onap.so.adapters.vfc.rest;
import java.util.HashMap;
import java.util.Map;
-
import org.onap.so.adapters.vfc.constant.CommonConstant;
import org.onap.so.adapters.vfc.constant.CommonConstant.Step;
import org.onap.so.adapters.vfc.constant.DriverExceptionID;
@@ -64,363 +63,357 @@ import org.springframework.stereotype.Component;
@Primary
public class VfcManager {
- private static final Logger LOGGER = LoggerFactory.getLogger(VfcManager.class);
-
- /**
- * nfvo url map
- */
- private Map<String, String> nfvoUrlMap;
-
- @Autowired
- private ResourceOperationStatusRepository resourceOperationStatusRepository;
-
- @Autowired
- private RestfulUtil restfulUtil;
-
-
- public VfcManager() {
- nfvoUrlMap = new HashMap<>();
- nfvoUrlMap.put(Step.CREATE, CommonConstant.NFVO_CREATE_URL);
- nfvoUrlMap.put(Step.INSTANTIATE, CommonConstant.NFVO_INSTANTIATE_URL);
- nfvoUrlMap.put(Step.TERMINATE, CommonConstant.NFVO_TERMINATE_URL);
- nfvoUrlMap.put(Step.DELETE, CommonConstant.NFVO_DELETE_URL);
- nfvoUrlMap.put(Step.QUERY, CommonConstant.NFVO_QUERY_URL);
- nfvoUrlMap.put(Step.SCALE, CommonConstant.NFVO_SCALE_URL);
- }
-
- /**
- * create network service <br>
- *
- * @param segInput input parameters for current node from http request
- * @return
- * @since ONAP Amsterdam Release
- */
- public RestfulResponse createNs(NSResourceInputParameter segInput) throws ApplicationException {
-
- // Step1: get service template by node type
- String csarId = segInput.getNsServiceModelUUID();
- // nsdId for NFVO is "id" in the response, while for SDNO is "servcice template id"
- LOGGER.info("serviceTemplateId is {}, id is {}", csarId, csarId);
-
- LOGGER.info("create ns -> begin");
- // Step2: Prepare url and method type
- String url = getUrl(null, CommonConstant.Step.CREATE);
- String methodType = CommonConstant.MethodType.POST;
-
- // Step3: Prepare restful parameters and options
- NsCreateReq oRequest = new NsCreateReq();
- oRequest.setCsarId(csarId);
- oRequest.setNsName(segInput.getNsServiceName());
- oRequest.setDescription(segInput.getNsServiceDescription());
- CustomerModel context = new CustomerModel();
- context.setGlobalCustomerId(segInput.getNsOperationKey().getGlobalSubscriberId());
- context.setServiceType(segInput.getNsOperationKey().getServiceType());
- oRequest.setContext(context);
- String createReq = JsonUtil.marshal(oRequest);
-
- // Step4: Call NFVO or SDNO lcm to create ns
- RestfulResponse createRsp = restfulUtil.send(url, methodType, createReq);
- ValidateUtil.assertObjectNotNull(createRsp);
- LOGGER.info("create ns response status is : {}", createRsp.getStatus());
- LOGGER.info("create ns response content is : {}", createRsp.getResponseContent());
-
- // Step 5: save resource operation information
- ResourceOperationStatus status = new ResourceOperationStatus(segInput.getNsOperationKey().getServiceId(), segInput.getNsOperationKey().getOperationId(), segInput.getNsOperationKey().getNodeTemplateUUID());
- status.setStatus(RequestsDbConstant.Status.PROCESSING);
- status = resourceOperationStatusRepository.save(status);
- if (!HttpCode.isSucess(createRsp.getStatus())) {
- LOGGER.error("update segment operation status : fail to create ns");
- status.setProgress("40");
- status.setStatusDescription("NS is created");
- status.setStatus(RequestsDbConstant.Status.ERROR);
- status.setErrorCode(String.valueOf(createRsp.getStatus()));
- resourceOperationStatusRepository.save(status);
- throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR,
- DriverExceptionID.FAIL_TO_CREATE_NS);
- }
- @SuppressWarnings("unchecked")
- Map<String, String> rsp = JsonUtil.unMarshal(createRsp.getResponseContent(), Map.class);
- String nsInstanceId = rsp.get(CommonConstant.NS_INSTANCE_ID);
- if (ValidateUtil.isStrEmpty(nsInstanceId)) {
- LOGGER.error("Invalid instanceId from create operation");
- throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR,
- DriverExceptionID.INVALID_RESPONSEE_FROM_CREATE_OPERATION);
+ private static final Logger LOGGER = LoggerFactory.getLogger(VfcManager.class);
+
+ /**
+ * nfvo url map
+ */
+ private Map<String, String> nfvoUrlMap;
+
+ @Autowired
+ private ResourceOperationStatusRepository resourceOperationStatusRepository;
+
+ @Autowired
+ private RestfulUtil restfulUtil;
+
+
+ public VfcManager() {
+ nfvoUrlMap = new HashMap<>();
+ nfvoUrlMap.put(Step.CREATE, CommonConstant.NFVO_CREATE_URL);
+ nfvoUrlMap.put(Step.INSTANTIATE, CommonConstant.NFVO_INSTANTIATE_URL);
+ nfvoUrlMap.put(Step.TERMINATE, CommonConstant.NFVO_TERMINATE_URL);
+ nfvoUrlMap.put(Step.DELETE, CommonConstant.NFVO_DELETE_URL);
+ nfvoUrlMap.put(Step.QUERY, CommonConstant.NFVO_QUERY_URL);
+ nfvoUrlMap.put(Step.SCALE, CommonConstant.NFVO_SCALE_URL);
}
- LOGGER.info("create ns -> end");
- LOGGER.info("save segment and operaton info -> begin");
- // Step 6: add relation between service and NS
- AaiUtil.addRelation(segInput.getNsOperationKey().getGlobalSubscriberId(),
- segInput.getNsOperationKey().getServiceType(), segInput.getNsOperationKey().getServiceId(),
- nsInstanceId);
- LOGGER.info("save segment and operation info -> end");
- return createRsp;
- }
-
- /**
- * delete network service <br>
- *
- * @param nsOperationKey The operation key of the NS resource
- * @param nsInstanceId The NS instance id
- * @return
- * @since ONAP Amsterdam Release
- */
- public RestfulResponse deleteNs(NsOperationKey nsOperationKey, String nsInstanceId)
- throws ApplicationException {
- LOGGER.info("delete ns -> begin");
- // Step1: prepare url and methodType
- String url = getUrl(nsInstanceId, CommonConstant.Step.DELETE);
- String methodType = CommonConstant.MethodType.DELETE;
-
- // Step2: prepare restful parameters and options
- RestfulResponse deleteRsp = restfulUtil.send(url, methodType, "");
- ValidateUtil.assertObjectNotNull(deleteRsp);
- LOGGER.info("delete ns response status is : {}", deleteRsp.getStatus());
- LOGGER.info("delete ns response content is : {}", deleteRsp.getResponseContent());
- LOGGER.info("delete ns -> end");
-
- ResourceOperationStatus status = new ResourceOperationStatus(nsOperationKey.getServiceId(), nsOperationKey.getOperationId(), nsOperationKey.getNodeTemplateUUID());
- if (!HttpCode.isSucess(deleteRsp.getStatus())) {
- LOGGER.error("fail to delete ns");
-
- status.setStatus(RequestsDbConstant.Status.ERROR);
- status.setErrorCode(String.valueOf(deleteRsp.getStatus()));
- status.setStatusDescription(CommonConstant.StatusDesc.TERMINATE_NS_FAILED);
- resourceOperationStatusRepository.save(status);
- throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR,
- DriverExceptionID.FAIL_TO_DELETE_NS);
+
+ /**
+ * create network service <br>
+ *
+ * @param segInput input parameters for current node from http request
+ * @return
+ * @since ONAP Amsterdam Release
+ */
+ public RestfulResponse createNs(NSResourceInputParameter segInput) throws ApplicationException {
+
+ // Step1: get service template by node type
+ String csarId = segInput.getNsServiceModelUUID();
+ // nsdId for NFVO is "id" in the response, while for SDNO is "servcice template id"
+ LOGGER.info("serviceTemplateId is {}, id is {}", csarId, csarId);
+
+ LOGGER.info("create ns -> begin");
+ // Step2: Prepare url and method type
+ String url = getUrl(null, CommonConstant.Step.CREATE);
+ String methodType = CommonConstant.MethodType.POST;
+
+ // Step3: Prepare restful parameters and options
+ NsCreateReq oRequest = new NsCreateReq();
+ oRequest.setCsarId(csarId);
+ oRequest.setNsName(segInput.getNsServiceName());
+ oRequest.setDescription(segInput.getNsServiceDescription());
+ CustomerModel context = new CustomerModel();
+ context.setGlobalCustomerId(segInput.getNsOperationKey().getGlobalSubscriberId());
+ context.setServiceType(segInput.getNsOperationKey().getServiceType());
+ oRequest.setContext(context);
+ String createReq = JsonUtil.marshal(oRequest);
+
+ // Step4: Call NFVO or SDNO lcm to create ns
+ RestfulResponse createRsp = restfulUtil.send(url, methodType, createReq);
+ ValidateUtil.assertObjectNotNull(createRsp);
+ LOGGER.info("create ns response status is : {}", createRsp.getStatus());
+ LOGGER.info("create ns response content is : {}", createRsp.getResponseContent());
+
+ // Step 5: save resource operation information
+ ResourceOperationStatus status = new ResourceOperationStatus(segInput.getNsOperationKey().getServiceId(),
+ segInput.getNsOperationKey().getOperationId(), segInput.getNsOperationKey().getNodeTemplateUUID());
+ status.setStatus(RequestsDbConstant.Status.PROCESSING);
+ status = resourceOperationStatusRepository.save(status);
+ if (!HttpCode.isSucess(createRsp.getStatus())) {
+ LOGGER.error("update segment operation status : fail to create ns");
+ status.setProgress("40");
+ status.setStatusDescription("NS is created");
+ status.setStatus(RequestsDbConstant.Status.ERROR);
+ status.setErrorCode(String.valueOf(createRsp.getStatus()));
+ resourceOperationStatusRepository.save(status);
+ throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, DriverExceptionID.FAIL_TO_CREATE_NS);
+ }
+ @SuppressWarnings("unchecked")
+ Map<String, String> rsp = JsonUtil.unMarshal(createRsp.getResponseContent(), Map.class);
+ String nsInstanceId = rsp.get(CommonConstant.NS_INSTANCE_ID);
+ if (ValidateUtil.isStrEmpty(nsInstanceId)) {
+ LOGGER.error("Invalid instanceId from create operation");
+ throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR,
+ DriverExceptionID.INVALID_RESPONSEE_FROM_CREATE_OPERATION);
+ }
+ LOGGER.info("create ns -> end");
+ LOGGER.info("save segment and operaton info -> begin");
+ // Step 6: add relation between service and NS
+ AaiUtil.addRelation(segInput.getNsOperationKey().getGlobalSubscriberId(),
+ segInput.getNsOperationKey().getServiceType(), segInput.getNsOperationKey().getServiceId(),
+ nsInstanceId);
+ LOGGER.info("save segment and operation info -> end");
+ return createRsp;
}
- // Step3: remove relation info between service and ns
- AaiUtil.removeRelation(nsOperationKey.getGlobalSubscriberId(), nsOperationKey.getServiceType(),
- nsOperationKey.getServiceId(), nsInstanceId);
- LOGGER.info("delete segment information -> end");
-
- // Step4: update service segment operation status
- status.setStatus(RequestsDbConstant.Status.FINISHED);
- status.setErrorCode(String.valueOf(deleteRsp.getStatus()));
- status.setProgress("100");
- status.setStatusDescription("VFC resource deletion finished");
- resourceOperationStatusRepository.save(status);
- LOGGER.info("update segment operaton status for delete -> end");
-
- return deleteRsp;
-
- }
-
- /**
- * instantiate network service <br>
- *
- * @param nsInstanceId The NS instance id
- * @param segInput input parameters for current node from http request
- * @return
- * @since ONAP Amsterdam Release
- */
- public RestfulResponse instantiateNs(String nsInstanceId, NSResourceInputParameter segInput)
- throws ApplicationException {
- // Call the NFVO or SDNO service to instantiate service
- LOGGER.info("instantiate ns -> begin");
-
- // Step1: Prepare restful parameters and options
- NsInstantiateReq oRequest = new NsInstantiateReq();
- oRequest.setNsInstanceId(nsInstanceId);
- NsParameters nsParameters = segInput.getNsParameters();
- oRequest.setLocationConstraints(nsParameters.getLocationConstraints());
- oRequest.setAdditionalParamForNs(nsParameters.getAdditionalParamForNs());
- String instReq = JsonUtil.marshal(oRequest);
- // Step2: prepare url and
- String url = getUrl(nsInstanceId, CommonConstant.Step.INSTANTIATE);
- String methodType = CommonConstant.MethodType.POST;
-
- RestfulResponse instRsp = restfulUtil.send(url, methodType, instReq);
- ResourceOperationStatus status = new ResourceOperationStatus(segInput.getNsOperationKey().getServiceId(), segInput.getNsOperationKey().getOperationId(), segInput.getNsOperationKey().getNodeTemplateUUID());
- ValidateUtil.assertObjectNotNull(instRsp);
- if (!HttpCode.isSucess(instRsp.getStatus())) {
- LOGGER.error("update segment operation status : fail to instantiate ns");
- status.setStatus(RequestsDbConstant.Status.ERROR);
- status.setErrorCode(String.valueOf(instRsp.getStatus()));
- status.setStatusDescription(CommonConstant.StatusDesc.INSTANTIATE_NS_FAILED);
+ /**
+ * delete network service <br>
+ *
+ * @param nsOperationKey The operation key of the NS resource
+ * @param nsInstanceId The NS instance id
+ * @return
+ * @since ONAP Amsterdam Release
+ */
+ public RestfulResponse deleteNs(NsOperationKey nsOperationKey, String nsInstanceId) throws ApplicationException {
+ LOGGER.info("delete ns -> begin");
+ // Step1: prepare url and methodType
+ String url = getUrl(nsInstanceId, CommonConstant.Step.DELETE);
+ String methodType = CommonConstant.MethodType.DELETE;
+
+ // Step2: prepare restful parameters and options
+ RestfulResponse deleteRsp = restfulUtil.send(url, methodType, "");
+ ValidateUtil.assertObjectNotNull(deleteRsp);
+ LOGGER.info("delete ns response status is : {}", deleteRsp.getStatus());
+ LOGGER.info("delete ns response content is : {}", deleteRsp.getResponseContent());
+ LOGGER.info("delete ns -> end");
+
+ ResourceOperationStatus status = new ResourceOperationStatus(nsOperationKey.getServiceId(),
+ nsOperationKey.getOperationId(), nsOperationKey.getNodeTemplateUUID());
+ if (!HttpCode.isSucess(deleteRsp.getStatus())) {
+ LOGGER.error("fail to delete ns");
+
+ status.setStatus(RequestsDbConstant.Status.ERROR);
+ status.setErrorCode(String.valueOf(deleteRsp.getStatus()));
+ status.setStatusDescription(CommonConstant.StatusDesc.TERMINATE_NS_FAILED);
+ resourceOperationStatusRepository.save(status);
+ throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, DriverExceptionID.FAIL_TO_DELETE_NS);
+ }
+
+ // Step3: remove relation info between service and ns
+ AaiUtil.removeRelation(nsOperationKey.getGlobalSubscriberId(), nsOperationKey.getServiceType(),
+ nsOperationKey.getServiceId(), nsInstanceId);
+ LOGGER.info("delete segment information -> end");
+
+ // Step4: update service segment operation status
+ status.setStatus(RequestsDbConstant.Status.FINISHED);
+ status.setErrorCode(String.valueOf(deleteRsp.getStatus()));
+ status.setProgress("100");
+ status.setStatusDescription("VFC resource deletion finished");
resourceOperationStatusRepository.save(status);
- throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR,
- DriverExceptionID.FAIL_TO_INSTANTIATE_NS);
- }
- LOGGER.info("instantiate ns response status is : {}", instRsp.getStatus());
- LOGGER.info("instantiate ns response content is : {}", instRsp.getResponseContent());
- ValidateUtil.assertObjectNotNull(instRsp.getResponseContent());
- @SuppressWarnings("unchecked")
- Map<String, String> rsp = JsonUtil.unMarshal(instRsp.getResponseContent(), Map.class);
- String jobId = rsp.get(CommonConstant.JOB_ID);
- if (ValidateUtil.isStrEmpty(jobId)) {
- LOGGER.error("Invalid jobId from instantiate operation");
- status.setStatus(RequestsDbConstant.Status.ERROR);
- status.setErrorCode(String.valueOf(instRsp.getStatus()));
- status.setStatusDescription(CommonConstant.StatusDesc.INSTANTIATE_NS_FAILED);
- resourceOperationStatusRepository.save(status);
- throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR,
- DriverExceptionID.INVALID_RESPONSE_FROM_INSTANTIATE_OPERATION);
- }
- LOGGER.info("instantiate ns -> end");
- // Step 3: update segment operation job id
- LOGGER.info("update resource operation status job id -> begin");
- status.setJobId(jobId);
- status.setProgress("100");
- status.setStatusDescription("NS initiation completed.");
- resourceOperationStatusRepository.save(status);
- LOGGER.info("update segment operation job id -> end");
-
- return instRsp;
- }
-
- /**
- * terminate network service <br>
- *
- * @param nsOperationKey The operation key for NS resource
- * @param nsInstanceId The NS instance id
- * @return
- * @since ONAP Amsterdam Release
- */
- public RestfulResponse terminateNs(NsOperationKey nsOperationKey, String nsInstanceId)
- throws ApplicationException {
- // Step1: save segment operation info for delete process
- LOGGER.info("save segment operation for delete process");
- ResourceOperationStatus status = new ResourceOperationStatus(nsOperationKey.getServiceId(), nsOperationKey.getOperationId(), nsOperationKey.getNodeTemplateUUID());
- status.setStatus(RequestsDbConstant.Status.PROCESSING);
- resourceOperationStatusRepository.save(status);
-
- LOGGER.info("terminate ns -> begin");
- // Step2: prepare url and method type
- String url = getUrl(nsInstanceId, CommonConstant.Step.TERMINATE);
- String methodType = CommonConstant.MethodType.POST;
-
- // Step3: prepare restful parameters and options
- Map<String, String> reqBody = new HashMap<>();
- reqBody.put("nsInstanceId", nsInstanceId);
- reqBody.put("terminationType", "graceful");
- reqBody.put("gracefulTerminationTimeout", "60");
-
- // Step4: Call the NFVO or SDNO service to terminate service
- RestfulResponse terminateRsp = restfulUtil.send(url, methodType, JsonUtil.marshal(reqBody));
- ValidateUtil.assertObjectNotNull(terminateRsp);
- LOGGER.info("terminate ns response status is : {}", terminateRsp.getStatus());
- LOGGER.info("terminate ns response content is : {}", terminateRsp.getResponseContent());
- // Step 3: update segment operation
- if (!HttpCode.isSucess(terminateRsp.getStatus())) {
- LOGGER.error("fail to instantiate ns");
- status.setStatus(RequestsDbConstant.Status.ERROR);
- status.setErrorCode(String.valueOf(terminateRsp.getStatus()));
- status.setStatusDescription(CommonConstant.StatusDesc.TERMINATE_NS_FAILED);
- resourceOperationStatusRepository.save(status);
-
- throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR,
- DriverExceptionID.FAIL_TO_TERMINATE_NS);
- }
- @SuppressWarnings("unchecked")
- Map<String, String> rsp = JsonUtil.unMarshal(terminateRsp.getResponseContent(), Map.class);
- String jobId = rsp.get(CommonConstant.JOB_ID);
- if (ValidateUtil.isStrEmpty(jobId)) {
- LOGGER.error("Invalid jobId from terminate operation");
- status.setStatus(RequestsDbConstant.Status.ERROR);
- status.setErrorCode(String.valueOf(terminateRsp.getStatus()));
- status.setStatusDescription(CommonConstant.StatusDesc.TERMINATE_NS_FAILED);
- resourceOperationStatusRepository.save(status);
- throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR,
- DriverExceptionID.INVALID_RESPONSE_FROM_TERMINATE_OPERATION);
+ LOGGER.info("update segment operaton status for delete -> end");
+
+ return deleteRsp;
+
}
- LOGGER.info("terminate ns -> end");
-
- LOGGER.info("update segment job id -> begin");
- status.setProgress("60");
- status.setStatusDescription("NS is termination completed");
- status.setJobId(jobId);
- resourceOperationStatusRepository.save(status);
- LOGGER.info("update segment job id -> end");
-
- return terminateRsp;
- }
-
- /**
- * get ns progress by job Id <br>
- *
- * @param nsOperationKey The OperationKey for NS resource
- * @param jobId the job id
- * @return
- * @since ONAP Amsterdam Release
- */
- public RestfulResponse getNsProgress(NsOperationKey nsOperationKey, String jobId)
- throws ApplicationException {
-
- ValidateUtil.assertObjectNotNull(jobId);
- // Step 1: query the current resource operation status
- ResourceOperationStatus status = new ResourceOperationStatus(nsOperationKey.getServiceId(), nsOperationKey.getOperationId(), nsOperationKey.getNodeTemplateUUID());
- status = resourceOperationStatusRepository.findOne(Example.of(status))
- .orElseThrow( () -> new ApplicationException(404,"Cannot Find Operation Status"));
- // Step 2: start query
- LOGGER.info("query ns status -> begin");
- String url = getUrl(jobId, CommonConstant.Step.QUERY);
- String methodType = CommonConstant.MethodType.GET;
- // prepare restful parameters and options
- RestfulResponse rsp = restfulUtil.send(url, methodType, "");
- ValidateUtil.assertObjectNotNull(rsp);
- LOGGER.info("query ns progress response status is : {}", rsp.getStatus());
- LOGGER.info("query ns progress response content is : {}", rsp.getResponseContent());
- // Step 3:check the response staus
- if (!HttpCode.isSucess(rsp.getStatus())) {
- LOGGER.info("fail to query job status");
- status.setErrorCode(String.valueOf(rsp.getStatus()));
- status.setStatus(RequestsDbConstant.Status.ERROR);
- status.setStatusDescription(CommonConstant.StatusDesc.QUERY_JOB_STATUS_FAILED);
- resourceOperationStatusRepository.save(status);
- throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR,
- DriverExceptionID.FAIL_TO_QUERY_JOB_STATUS);
+
+ /**
+ * instantiate network service <br>
+ *
+ * @param nsInstanceId The NS instance id
+ * @param segInput input parameters for current node from http request
+ * @return
+ * @since ONAP Amsterdam Release
+ */
+ public RestfulResponse instantiateNs(String nsInstanceId, NSResourceInputParameter segInput)
+ throws ApplicationException {
+ // Call the NFVO or SDNO service to instantiate service
+ LOGGER.info("instantiate ns -> begin");
+
+ // Step1: Prepare restful parameters and options
+ NsInstantiateReq oRequest = new NsInstantiateReq();
+ oRequest.setNsInstanceId(nsInstanceId);
+ NsParameters nsParameters = segInput.getNsParameters();
+ oRequest.setLocationConstraints(nsParameters.getLocationConstraints());
+ oRequest.setAdditionalParamForNs(nsParameters.getAdditionalParamForNs());
+ String instReq = JsonUtil.marshal(oRequest);
+ // Step2: prepare url and
+ String url = getUrl(nsInstanceId, CommonConstant.Step.INSTANTIATE);
+ String methodType = CommonConstant.MethodType.POST;
+
+ RestfulResponse instRsp = restfulUtil.send(url, methodType, instReq);
+ ResourceOperationStatus status = new ResourceOperationStatus(segInput.getNsOperationKey().getServiceId(),
+ segInput.getNsOperationKey().getOperationId(), segInput.getNsOperationKey().getNodeTemplateUUID());
+ ValidateUtil.assertObjectNotNull(instRsp);
+ if (!HttpCode.isSucess(instRsp.getStatus())) {
+ LOGGER.error("update segment operation status : fail to instantiate ns");
+ status.setStatus(RequestsDbConstant.Status.ERROR);
+ status.setErrorCode(String.valueOf(instRsp.getStatus()));
+ status.setStatusDescription(CommonConstant.StatusDesc.INSTANTIATE_NS_FAILED);
+ resourceOperationStatusRepository.save(status);
+ throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, DriverExceptionID.FAIL_TO_INSTANTIATE_NS);
+ }
+ LOGGER.info("instantiate ns response status is : {}", instRsp.getStatus());
+ LOGGER.info("instantiate ns response content is : {}", instRsp.getResponseContent());
+ ValidateUtil.assertObjectNotNull(instRsp.getResponseContent());
+ @SuppressWarnings("unchecked")
+ Map<String, String> rsp = JsonUtil.unMarshal(instRsp.getResponseContent(), Map.class);
+ String jobId = rsp.get(CommonConstant.JOB_ID);
+ if (ValidateUtil.isStrEmpty(jobId)) {
+ LOGGER.error("Invalid jobId from instantiate operation");
+ status.setStatus(RequestsDbConstant.Status.ERROR);
+ status.setErrorCode(String.valueOf(instRsp.getStatus()));
+ status.setStatusDescription(CommonConstant.StatusDesc.INSTANTIATE_NS_FAILED);
+ resourceOperationStatusRepository.save(status);
+ throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR,
+ DriverExceptionID.INVALID_RESPONSE_FROM_INSTANTIATE_OPERATION);
+ }
+ LOGGER.info("instantiate ns -> end");
+ // Step 3: update segment operation job id
+ LOGGER.info("update resource operation status job id -> begin");
+ status.setJobId(jobId);
+ status.setProgress("100");
+ status.setStatusDescription("NS initiation completed.");
+ resourceOperationStatusRepository.save(status);
+ LOGGER.info("update segment operation job id -> end");
+
+ return instRsp;
}
- // Step 4: Process Network Service Instantiate Response
- NsProgressStatus nsProgress =
- JsonUtil.unMarshal(rsp.getResponseContent(), NsProgressStatus.class);
- ResponseDescriptor rspDesc = nsProgress.getResponseDescriptor();
- // Step 5: update segment operation progress
-
- status.setProgress(rspDesc.getProgress());
- status.setStatusDescription(rspDesc.getStatusDescription());
- resourceOperationStatusRepository.save(status);
-
- // Step 6: update segment operation status
- if (RequestsDbConstant.Progress.ONE_HUNDRED.equals(rspDesc.getProgress())
- && RequestsDbConstant.Status.FINISHED.equals(rspDesc.getStatus())) {
- LOGGER.info("job result is succeeded, operType is {}", status.getOperType());
- status.setErrorCode(String.valueOf(rsp.getStatus()));
- status.setStatusDescription(CommonConstant.StatusDesc.QUERY_JOB_STATUS_FAILED);
-
- if(RequestsDbConstant.OperationType.CREATE.equalsIgnoreCase(status.getOperType()) || "createInstance".equalsIgnoreCase (status.getOperType())) {
- status.setStatus(RequestsDbConstant.Status.FINISHED);
- }
- resourceOperationStatusRepository.save(status);
- } else if (RequestsDbConstant.Status.ERROR.equals(rspDesc.getStatus())) {
- LOGGER.error("job result is failed, operType is {}", status.getOperType());
- status.setErrorCode(String.valueOf(rsp.getStatus()));
- status.setStatusDescription(CommonConstant.StatusDesc.QUERY_JOB_STATUS_FAILED);
- status.setStatus(RequestsDbConstant.Status.ERROR);
- resourceOperationStatusRepository.save(status);
- throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR,
- DriverExceptionID.JOB_STATUS_ERROR);
- } else {
- LOGGER.error("unexcepted response status");
+
+ /**
+ * terminate network service <br>
+ *
+ * @param nsOperationKey The operation key for NS resource
+ * @param nsInstanceId The NS instance id
+ * @return
+ * @since ONAP Amsterdam Release
+ */
+ public RestfulResponse terminateNs(NsOperationKey nsOperationKey, String nsInstanceId) throws ApplicationException {
+ // Step1: save segment operation info for delete process
+ LOGGER.info("save segment operation for delete process");
+ ResourceOperationStatus status = new ResourceOperationStatus(nsOperationKey.getServiceId(),
+ nsOperationKey.getOperationId(), nsOperationKey.getNodeTemplateUUID());
+ status.setStatus(RequestsDbConstant.Status.PROCESSING);
+ resourceOperationStatusRepository.save(status);
+
+ LOGGER.info("terminate ns -> begin");
+ // Step2: prepare url and method type
+ String url = getUrl(nsInstanceId, CommonConstant.Step.TERMINATE);
+ String methodType = CommonConstant.MethodType.POST;
+
+ // Step3: prepare restful parameters and options
+ Map<String, String> reqBody = new HashMap<>();
+ reqBody.put("nsInstanceId", nsInstanceId);
+ reqBody.put("terminationType", "graceful");
+ reqBody.put("gracefulTerminationTimeout", "60");
+
+ // Step4: Call the NFVO or SDNO service to terminate service
+ RestfulResponse terminateRsp = restfulUtil.send(url, methodType, JsonUtil.marshal(reqBody));
+ ValidateUtil.assertObjectNotNull(terminateRsp);
+ LOGGER.info("terminate ns response status is : {}", terminateRsp.getStatus());
+ LOGGER.info("terminate ns response content is : {}", terminateRsp.getResponseContent());
+ // Step 3: update segment operation
+ if (!HttpCode.isSucess(terminateRsp.getStatus())) {
+ LOGGER.error("fail to instantiate ns");
+ status.setStatus(RequestsDbConstant.Status.ERROR);
+ status.setErrorCode(String.valueOf(terminateRsp.getStatus()));
+ status.setStatusDescription(CommonConstant.StatusDesc.TERMINATE_NS_FAILED);
+ resourceOperationStatusRepository.save(status);
+
+ throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, DriverExceptionID.FAIL_TO_TERMINATE_NS);
+ }
+ @SuppressWarnings("unchecked")
+ Map<String, String> rsp = JsonUtil.unMarshal(terminateRsp.getResponseContent(), Map.class);
+ String jobId = rsp.get(CommonConstant.JOB_ID);
+ if (ValidateUtil.isStrEmpty(jobId)) {
+ LOGGER.error("Invalid jobId from terminate operation");
+ status.setStatus(RequestsDbConstant.Status.ERROR);
+ status.setErrorCode(String.valueOf(terminateRsp.getStatus()));
+ status.setStatusDescription(CommonConstant.StatusDesc.TERMINATE_NS_FAILED);
+ resourceOperationStatusRepository.save(status);
+ throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR,
+ DriverExceptionID.INVALID_RESPONSE_FROM_TERMINATE_OPERATION);
+ }
+ LOGGER.info("terminate ns -> end");
+
+ LOGGER.info("update segment job id -> begin");
+ status.setProgress("60");
+ status.setStatusDescription("NS is termination completed");
+ status.setJobId(jobId);
+ resourceOperationStatusRepository.save(status);
+ LOGGER.info("update segment job id -> end");
+
+ return terminateRsp;
}
- LOGGER.info("query ns status -> end");
- return rsp;
- }
+ /**
+ * get ns progress by job Id <br>
+ *
+ * @param nsOperationKey The OperationKey for NS resource
+ * @param jobId the job id
+ * @return
+ * @since ONAP Amsterdam Release
+ */
+ public RestfulResponse getNsProgress(NsOperationKey nsOperationKey, String jobId) throws ApplicationException {
+
+ ValidateUtil.assertObjectNotNull(jobId);
+ // Step 1: query the current resource operation status
+ ResourceOperationStatus status = new ResourceOperationStatus(nsOperationKey.getServiceId(),
+ nsOperationKey.getOperationId(), nsOperationKey.getNodeTemplateUUID());
+ status = resourceOperationStatusRepository.findOne(Example.of(status))
+ .orElseThrow(() -> new ApplicationException(404, "Cannot Find Operation Status"));
+ // Step 2: start query
+ LOGGER.info("query ns status -> begin");
+ String url = getUrl(jobId, CommonConstant.Step.QUERY);
+ String methodType = CommonConstant.MethodType.GET;
+ // prepare restful parameters and options
+ RestfulResponse rsp = restfulUtil.send(url, methodType, "");
+ ValidateUtil.assertObjectNotNull(rsp);
+ LOGGER.info("query ns progress response status is : {}", rsp.getStatus());
+ LOGGER.info("query ns progress response content is : {}", rsp.getResponseContent());
+ // Step 3:check the response staus
+ if (!HttpCode.isSucess(rsp.getStatus())) {
+ LOGGER.info("fail to query job status");
+ status.setErrorCode(String.valueOf(rsp.getStatus()));
+ status.setStatus(RequestsDbConstant.Status.ERROR);
+ status.setStatusDescription(CommonConstant.StatusDesc.QUERY_JOB_STATUS_FAILED);
+ resourceOperationStatusRepository.save(status);
+ throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, DriverExceptionID.FAIL_TO_QUERY_JOB_STATUS);
+ }
+ // Step 4: Process Network Service Instantiate Response
+ NsProgressStatus nsProgress = JsonUtil.unMarshal(rsp.getResponseContent(), NsProgressStatus.class);
+ ResponseDescriptor rspDesc = nsProgress.getResponseDescriptor();
+ // Step 5: update segment operation progress
+
+ status.setProgress(rspDesc.getProgress());
+ status.setStatusDescription(rspDesc.getStatusDescription());
+ resourceOperationStatusRepository.save(status);
+
+ // Step 6: update segment operation status
+ if (RequestsDbConstant.Progress.ONE_HUNDRED.equals(rspDesc.getProgress())
+ && RequestsDbConstant.Status.FINISHED.equals(rspDesc.getStatus())) {
+ LOGGER.info("job result is succeeded, operType is {}", status.getOperType());
+ status.setErrorCode(String.valueOf(rsp.getStatus()));
+ status.setStatusDescription(CommonConstant.StatusDesc.QUERY_JOB_STATUS_FAILED);
+
+ if (RequestsDbConstant.OperationType.CREATE.equalsIgnoreCase(status.getOperType())
+ || "createInstance".equalsIgnoreCase(status.getOperType())) {
+ status.setStatus(RequestsDbConstant.Status.FINISHED);
+ }
+ resourceOperationStatusRepository.save(status);
+ } else if (RequestsDbConstant.Status.ERROR.equals(rspDesc.getStatus())) {
+ LOGGER.error("job result is failed, operType is {}", status.getOperType());
+ status.setErrorCode(String.valueOf(rsp.getStatus()));
+ status.setStatusDescription(CommonConstant.StatusDesc.QUERY_JOB_STATUS_FAILED);
+ status.setStatus(RequestsDbConstant.Status.ERROR);
+ resourceOperationStatusRepository.save(status);
+ throw new ApplicationException(HttpCode.INTERNAL_SERVER_ERROR, DriverExceptionID.JOB_STATUS_ERROR);
+ } else {
+ LOGGER.error("unexcepted response status");
+ }
+ LOGGER.info("query ns status -> end");
+
+ return rsp;
+ }
/**
- * Scale NS instance
- * <br>
+ * Scale NS instance <br>
*
* @param nsInstanceId The NS instance id
* @param segInput input parameters for current node from http request
* @return
* @since ONAP Amsterdam Release
*/
- public RestfulResponse scaleNs(String nsInstanceId, NSResourceInputParameter segInput)
- throws ApplicationException {
- // Call the NFVO to scale service
+ public RestfulResponse scaleNs(String nsInstanceId, NSResourceInputParameter segInput) throws ApplicationException {
+ // Call the NFVO to scale service
LOGGER.info("scale ns -> begin");
// Step1: Prepare restful parameters and options
@@ -430,19 +423,20 @@ public class VfcManager {
oRequest.setScaleType(nsScaleParameters.getScaleType());
oRequest.setScaleNsData(nsScaleParameters.getScaleNsByStepsData());
String scaleReq = JsonUtil.marshal(oRequest);
-
+
// Step2: prepare url and method type
String url = getUrl(nsInstanceId, CommonConstant.Step.SCALE);
String methodType = CommonConstant.MethodType.POST;
LOGGER.info("scale ns request is {}", scaleReq);
// Step3: Call NFVO lcm to scale ns
RestfulResponse scaleRsp = restfulUtil.send(url, methodType, scaleReq);
-
- ResourceOperationStatus status = new ResourceOperationStatus(segInput.getNsOperationKey().getServiceId(), segInput.getNsOperationKey().getOperationId(), segInput.getNsOperationKey().getNodeTemplateUUID());
+
+ ResourceOperationStatus status = new ResourceOperationStatus(segInput.getNsOperationKey().getServiceId(),
+ segInput.getNsOperationKey().getOperationId(), segInput.getNsOperationKey().getNodeTemplateUUID());
ResourceOperationStatus nsOperInfo = resourceOperationStatusRepository.findOne(Example.of(status))
- .orElseThrow( () -> new ApplicationException(404,"Cannot Find Operation Status"));
+ .orElseThrow(() -> new ApplicationException(404, "Cannot Find Operation Status"));
ValidateUtil.assertObjectNotNull(scaleRsp);
- if(!HttpCode.isSucess(scaleRsp.getStatus())) {
+ if (!HttpCode.isSucess(scaleRsp.getStatus())) {
LOGGER.error("update segment operation status : fail to scale ns");
nsOperInfo.setStatus(RequestsDbConstant.Status.ERROR);
nsOperInfo.setErrorCode(String.valueOf(scaleRsp.getStatus()));
@@ -457,7 +451,7 @@ public class VfcManager {
@SuppressWarnings("unchecked")
Map<String, String> rsp = JsonUtil.unMarshal(scaleRsp.getResponseContent(), Map.class);
String jobId = rsp.get(CommonConstant.JOB_ID);
- if(ValidateUtil.isStrEmpty(jobId)) {
+ if (ValidateUtil.isStrEmpty(jobId)) {
LOGGER.error("Invalid jobId from scale operation");
nsOperInfo.setStatus(RequestsDbConstant.Status.ERROR);
nsOperInfo.setErrorCode(String.valueOf(scaleRsp.getStatus()));
@@ -473,26 +467,26 @@ public class VfcManager {
resourceOperationStatusRepository.save(nsOperInfo);
LOGGER.info("update segment operation job id -> end");
LOGGER.info("scale ns -> end");
-
+
return scaleRsp;
}
-
- /**
- * get url for the operation <br>
- *
- * @param variable variable should be put in the url
- * @param step step of the operation (terminate,query,delete)
- * @return
- * @since ONAP Amsterdam Release
- */
- private String getUrl(String variable, String step) {
-
- String url;
- String originalUrl;
- originalUrl = nfvoUrlMap.get(step);
- url = String.format(originalUrl, variable);
- return url;
-
- }
+
+ /**
+ * get url for the operation <br>
+ *
+ * @param variable variable should be put in the url
+ * @param step step of the operation (terminate,query,delete)
+ * @return
+ * @since ONAP Amsterdam Release
+ */
+ private String getUrl(String variable, String step) {
+
+ String url;
+ String originalUrl;
+ originalUrl = nfvoUrlMap.get(step);
+ url = String.format(originalUrl, variable);
+ return url;
+
+ }
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java
index 2c1155ca6f..cefaadbb63 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java
@@ -24,12 +24,10 @@
package org.onap.so.adapters.vfc.util;
import java.io.IOException;
-
import org.onap.so.adapters.vfc.constant.HttpCode;
import org.onap.so.adapters.vfc.exceptions.ApplicationException;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -47,93 +45,92 @@ import org.slf4j.LoggerFactory;
*/
public class JsonUtil {
- /**
- * Log service
- */
- private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
+ /**
+ * Log service
+ */
+ private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
- /**
- * Mapper.
- */
- private static final ObjectMapper MAPPER = new ObjectMapper();
- private static final String UNMARSHAL_FAIL_MSG="fail to unMarshal json";
- static {
- MAPPER.setConfig(MAPPER.getDeserializationConfig().without(
- DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
- MAPPER.setSerializationInclusion(Include.NON_NULL);
- }
+ /**
+ * Mapper.
+ */
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String UNMARSHAL_FAIL_MSG = "fail to unMarshal json";
+ static {
+ MAPPER.setConfig(MAPPER.getDeserializationConfig().without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
+ MAPPER.setSerializationInclusion(Include.NON_NULL);
+ }
- /**
- * Constructor<br/>
- * <p>
- * </p>
- *
- * @since ONAP Amsterdam Release 2017-9-6
- */
- private JsonUtil() {
+ /**
+ * Constructor<br/>
+ * <p>
+ * </p>
+ *
+ * @since ONAP Amsterdam Release 2017-9-6
+ */
+ private JsonUtil() {
- }
+ }
- /**
- * Parse the string in form of json.<br/>
- *
- * @param jsonstr json string.
- * @param type that convert json string to
- * @return model object
- * @since ONAP Amsterdam Release 2017-9-6
- */
- public static <T> T unMarshal(String jsonstr, Class<T> type) throws ApplicationException {
- try {
- return MAPPER.readValue(jsonstr, type);
- } catch (IOException e) {
- logger.error("{} {} {}", MessageEnum.RA_NS_EXC.toString(), ErrorCode.BusinessProcesssError.getValue(),
- UNMARSHAL_FAIL_MSG, e);
- throw new ApplicationException(HttpCode.BAD_REQUEST, UNMARSHAL_FAIL_MSG);
+ /**
+ * Parse the string in form of json.<br/>
+ *
+ * @param jsonstr json string.
+ * @param type that convert json string to
+ * @return model object
+ * @since ONAP Amsterdam Release 2017-9-6
+ */
+ public static <T> T unMarshal(String jsonstr, Class<T> type) throws ApplicationException {
+ try {
+ return MAPPER.readValue(jsonstr, type);
+ } catch (IOException e) {
+ logger.error("{} {} {}", MessageEnum.RA_NS_EXC.toString(), ErrorCode.BusinessProcesssError.getValue(),
+ UNMARSHAL_FAIL_MSG, e);
+ throw new ApplicationException(HttpCode.BAD_REQUEST, UNMARSHAL_FAIL_MSG);
+ }
}
- }
- /**
- * Parse the string in form of json.<br/>
- *
- * @param jsonstr json string.
- * @param type that convert json string to
- * @return model object
- * @since ONAP Amsterdam Release 2017-9-6
- */
- public static <T> T unMarshal(String jsonstr, TypeReference<T> type) throws ApplicationException {
- try {
- return MAPPER.readValue(jsonstr, type);
- } catch (IOException e) {
- logger.error("{} {} {}", MessageEnum.RA_NS_EXC.toString(), ErrorCode.BusinessProcesssError.getValue(),
- UNMARSHAL_FAIL_MSG, e);
- throw new ApplicationException(HttpCode.BAD_REQUEST, UNMARSHAL_FAIL_MSG);
+ /**
+ * Parse the string in form of json.<br/>
+ *
+ * @param jsonstr json string.
+ * @param type that convert json string to
+ * @return model object
+ * @since ONAP Amsterdam Release 2017-9-6
+ */
+ public static <T> T unMarshal(String jsonstr, TypeReference<T> type) throws ApplicationException {
+ try {
+ return MAPPER.readValue(jsonstr, type);
+ } catch (IOException e) {
+ logger.error("{} {} {}", MessageEnum.RA_NS_EXC.toString(), ErrorCode.BusinessProcesssError.getValue(),
+ UNMARSHAL_FAIL_MSG, e);
+ throw new ApplicationException(HttpCode.BAD_REQUEST, UNMARSHAL_FAIL_MSG);
+ }
}
- }
- /**
- * Convert object to json string.<br/>
- *
- * @param srcObj data object
- * @return json string
- * @since ONAP Amsterdam Release 2017-9-6
- */
- public static String marshal(Object srcObj) throws ApplicationException {
- try {
- return MAPPER.writeValueAsString(srcObj);
- } catch (IOException e) {
- logger.error("{} {} {}", MessageEnum.RA_NS_EXC.toString(), ErrorCode.BusinessProcesssError.getValue(),
- "fail to marshal json", e);
- throw new ApplicationException(HttpCode.BAD_REQUEST, "srcObj marshal failed!");
+ /**
+ * Convert object to json string.<br/>
+ *
+ * @param srcObj data object
+ * @return json string
+ * @since ONAP Amsterdam Release 2017-9-6
+ */
+ public static String marshal(Object srcObj) throws ApplicationException {
+ try {
+ return MAPPER.writeValueAsString(srcObj);
+ } catch (IOException e) {
+ logger.error("{} {} {}", MessageEnum.RA_NS_EXC.toString(), ErrorCode.BusinessProcesssError.getValue(),
+ "fail to marshal json", e);
+ throw new ApplicationException(HttpCode.BAD_REQUEST, "srcObj marshal failed!");
+ }
}
- }
- /**
- * Get mapper.<br/>
- *
- * @return mapper
- * @since ONAP Amsterdam Release 2017-9-6
- */
- public static ObjectMapper getMapper() {
- return MAPPER;
- }
+ /**
+ * Get mapper.<br/>
+ *
+ * @return mapper
+ * @since ONAP Amsterdam Release 2017-9-6
+ */
+ public static ObjectMapper getMapper() {
+ return MAPPER;
+ }
}
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java
index a51564eef8..3419e6d20c 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java
@@ -26,9 +26,7 @@ package org.onap.so.adapters.vfc.util;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
-
import javax.ws.rs.core.UriBuilder;
-
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
@@ -71,29 +69,29 @@ public class RestfulUtil {
private static final int DEFAULT_TIME_OUT = 60000;
private static final String ONAP_IP = "ONAP_IP";
-
+
private static final String DEFAULT_MSB_IP = "127.0.0.1";
private static final Integer DEFAULT_MSB_PORT = 80;
-
- private static final String VFC_ADAPTER="VFC Adapter";
- @Autowired
- private Environment env;
+ private static final String VFC_ADAPTER = "VFC Adapter";
+
+ @Autowired
+ private Environment env;
public String getMsbHost() {
- // MSB_IP will be set as ONAP_IP environment parameter in install flow.
- String msbIp = System.getenv().get(ONAP_IP);
- // if ONAP IP is not set. get it from config file.
- if (null == msbIp || msbIp.isEmpty()) {
- msbIp = env.getProperty("mso.msb-ip", DEFAULT_MSB_IP);
- }
- Integer msbPort = env.getProperty("mso.msb-port", Integer.class, DEFAULT_MSB_PORT);
-
- String msbEndpoint = UriBuilder.fromPath("").host(msbIp).port(msbPort).scheme("http").build().toString();
- logger.debug("msbEndpoint in vfc adapter: {}", msbEndpoint);
-
- return msbEndpoint;
+ // MSB_IP will be set as ONAP_IP environment parameter in install flow.
+ String msbIp = System.getenv().get(ONAP_IP);
+ // if ONAP IP is not set. get it from config file.
+ if (null == msbIp || msbIp.isEmpty()) {
+ msbIp = env.getProperty("mso.msb-ip", DEFAULT_MSB_IP);
+ }
+ Integer msbPort = env.getProperty("mso.msb-port", Integer.class, DEFAULT_MSB_PORT);
+
+ String msbEndpoint = UriBuilder.fromPath("").host(msbIp).port(msbPort).scheme("http").build().toString();
+ logger.debug("msbEndpoint in vfc adapter: {}", msbEndpoint);
+
+ return msbEndpoint;
}
private RestfulUtil() {
@@ -115,21 +113,21 @@ public class RestfulUtil {
HttpClient client = HttpClientBuilder.create().build();
- if("POST".equalsIgnoreCase(methodType)) {
+ if ("POST".equalsIgnoreCase(methodType)) {
HttpPost httpPost = new HttpPost(msbUrl);
httpPost.setConfig(requestConfig);
httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
method = httpPost;
- } else if("PUT".equalsIgnoreCase(methodType)) {
+ } else if ("PUT".equalsIgnoreCase(methodType)) {
HttpPut httpPut = new HttpPut(msbUrl);
httpPut.setConfig(requestConfig);
httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
method = httpPut;
- } else if("GET".equalsIgnoreCase(methodType)) {
+ } else if ("GET".equalsIgnoreCase(methodType)) {
HttpGet httpGet = new HttpGet(msbUrl);
httpGet.setConfig(requestConfig);
method = httpGet;
- } else if("DELETE".equalsIgnoreCase(methodType)) {
+ } else if ("DELETE".equalsIgnoreCase(methodType)) {
HttpDelete httpDelete = new HttpDelete(msbUrl);
httpDelete.setConfig(requestConfig);
method = httpDelete;
@@ -138,17 +136,17 @@ public class RestfulUtil {
httpResponse = client.execute(method);
String responseContent = null;
- if(httpResponse.getEntity() != null) {
+ if (httpResponse.getEntity() != null) {
responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
- logger.debug("VFC Response: {} {}", statusCode, statusMessage
- + (responseContent == null ? "" : System.lineSeparator() + responseContent));
+ logger.debug("VFC Response: {} {}", statusCode,
+ statusMessage + (responseContent == null ? "" : System.lineSeparator() + responseContent));
- if(httpResponse.getStatusLine().getStatusCode() >= 300) {
+ if (httpResponse.getStatusLine().getStatusCode() >= 300) {
String errMsg = "VFC returned " + statusCode + " " + statusMessage;
logError(errMsg);
return createResponse(statusCode, errMsg);
@@ -156,7 +154,7 @@ public class RestfulUtil {
httpResponse = null;
- if(null != method) {
+ if (null != method) {
method.reset();
} else {
logger.debug("method is NULL:");
@@ -165,29 +163,29 @@ public class RestfulUtil {
method = null;
return createResponse(statusCode, responseContent);
- } catch(SocketTimeoutException | ConnectTimeoutException e) {
+ } catch (SocketTimeoutException | ConnectTimeoutException e) {
String errMsg = "Request to VFC timed out";
logError(errMsg, e);
return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
- } catch(Exception e) {
+ } catch (Exception e) {
String errMsg = "Error processing request to VFC";
logError(errMsg, e);
return createResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg);
} finally {
- if(httpResponse != null) {
+ if (httpResponse != null) {
try {
EntityUtils.consume(httpResponse.getEntity());
- } catch(Exception e) {
+ } catch (Exception e) {
logger.debug("Exception :", e);
}
}
- if(method != null) {
+ if (method != null) {
try {
method.reset();
- } catch(Exception e) {
+ } catch (Exception e) {
logger.debug("Exception :", e);
}
}
@@ -196,12 +194,12 @@ public class RestfulUtil {
private static void logError(String errMsg, Throwable t) {
logger.error("{} {} {} {}", MessageEnum.RA_NS_EXC.toString(), VFC_ADAPTER,
- ErrorCode.AvailabilityError.getValue(), errMsg, t);
+ ErrorCode.AvailabilityError.getValue(), errMsg, t);
}
private static void logError(String errMsg) {
logger.error("{} {} {} {}", MessageEnum.RA_NS_EXC.toString(), VFC_ADAPTER,
- ErrorCode.AvailabilityError.toString(), errMsg);
+ ErrorCode.AvailabilityError.toString(), errMsg);
}
private static RestfulResponse createResponse(int statusCode, String content) {
diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/ValidateUtil.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/ValidateUtil.java
index d920dbea36..f56f5af05b 100644
--- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/ValidateUtil.java
+++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/ValidateUtil.java
@@ -27,61 +27,60 @@ import org.slf4j.LoggerFactory;
public class ValidateUtil {
- /**
- * Log server.
- */
- private static final Logger LOGGER = LoggerFactory.getLogger(ValidateUtil.class);
+ /**
+ * Log server.
+ */
+ private static final Logger LOGGER = LoggerFactory.getLogger(ValidateUtil.class);
- /**
- * Constructor<br/>
- * <p>
- * </p>
- *
- * @since ONAP Amsterdam Release 2017-9-6
- */
- private ValidateUtil() {
+ /**
+ * Constructor<br/>
+ * <p>
+ * </p>
+ *
+ * @since ONAP Amsterdam Release 2017-9-6
+ */
+ private ValidateUtil() {
- }
-
- /**
- * Assert String parameter.<br/>
- *
- * @param paramValue parameter data
- * @param paramName parameter name
- * @since ONAP Amsterdam Release 2017-9-6
- */
- public static void assertStringNotNull(String paramValue, String paramName)
- throws ApplicationException {
- if (null != paramValue && !paramValue.isEmpty()) {
- return;
}
- LOGGER.error(paramName + ": Parameter is null or empty.");
- throw new ApplicationException(HttpCode.BAD_REQUEST, paramName + ": Invalid parameter.");
- }
+ /**
+ * Assert String parameter.<br/>
+ *
+ * @param paramValue parameter data
+ * @param paramName parameter name
+ * @since ONAP Amsterdam Release 2017-9-6
+ */
+ public static void assertStringNotNull(String paramValue, String paramName) throws ApplicationException {
+ if (null != paramValue && !paramValue.isEmpty()) {
+ return;
+ }
- /**
- * Assert object is null.<br/>
- *
- * @param object data object
- * @since ONAP Amsterdam Release 2017-9-6
- */
- public static void assertObjectNotNull(Object object) throws ApplicationException {
- if (null == object) {
- LOGGER.error("Object is null.");
- throw new ApplicationException(HttpCode.BAD_REQUEST, "Object is null.");
+ LOGGER.error(paramName + ": Parameter is null or empty.");
+ throw new ApplicationException(HttpCode.BAD_REQUEST, paramName + ": Invalid parameter.");
}
- }
+ /**
+ * Assert object is null.<br/>
+ *
+ * @param object data object
+ * @since ONAP Amsterdam Release 2017-9-6
+ */
+ public static void assertObjectNotNull(Object object) throws ApplicationException {
+ if (null == object) {
+ LOGGER.error("Object is null.");
+ throw new ApplicationException(HttpCode.BAD_REQUEST, "Object is null.");
+ }
+
+ }
- /**
- * <br>
- *
- * @param str
- * @return
- * @since ONAP Amsterdam Release
- */
- public static boolean isStrEmpty(String str) {
- return null == str || str.isEmpty();
- }
+ /**
+ * <br>
+ *
+ * @param str
+ * @return
+ * @since ONAP Amsterdam Release
+ */
+ public static boolean isStrEmpty(String str) {
+ return null == str || str.isEmpty();
+ }
}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/exceptions/ApplicationExceptionTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/exceptions/ApplicationExceptionTest.java
index efd3359821..c0305f18de 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/exceptions/ApplicationExceptionTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/exceptions/ApplicationExceptionTest.java
@@ -1,42 +1,36 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.adapters.vfc.exceptions;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class ApplicationExceptionTest {
- private ApplicationException application = new ApplicationException(500,null);
-
- @Test
- public void testApplicationException() {
- application.setErrorCode(500);
- application.setErrorMsg("ErrorMsg");
- assertEquals(application.getErrorCode(), 500);
- assertEquals(application.getErrorMsg(), "ErrorMsg");
- }
-
- @Test
- public void testbuildErrorResponse(){
- assert(application.buildErrorResponse()!=null);
- }
+ private ApplicationException application = new ApplicationException(500, null);
+
+ @Test
+ public void testApplicationException() {
+ application.setErrorCode(500);
+ application.setErrorMsg("ErrorMsg");
+ assertEquals(application.getErrorCode(), 500);
+ assertEquals(application.getErrorMsg(), "ErrorMsg");
+ }
+
+ @Test
+ public void testbuildErrorResponse() {
+ assert (application.buildErrorResponse() != null);
+ }
}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/CustomerModelTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/CustomerModelTest.java
index 2acd6c25ad..548d8b3645 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/CustomerModelTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/CustomerModelTest.java
@@ -46,4 +46,4 @@ public class CustomerModelTest {
customerModel.setServiceType("service");
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/LocationConstraintTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/LocationConstraintTest.java
index ef5eb2617e..2b217469e5 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/LocationConstraintTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/LocationConstraintTest.java
@@ -46,4 +46,4 @@ public class LocationConstraintTest {
locationConstraint.setLocationConstraints(new VimLocation());
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NSResourceInputParameterTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NSResourceInputParameterTest.java
index 2e720e47ad..082d4e69f4 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NSResourceInputParameterTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NSResourceInputParameterTest.java
@@ -66,4 +66,4 @@ public class NSResourceInputParameterTest {
nsResourceInputParameter.setNsOperationKey(new NsOperationKey());
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsCreateReqTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsCreateReqTest.java
index caf2d7e164..c2e6b583af 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsCreateReqTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsCreateReqTest.java
@@ -66,4 +66,4 @@ public class NsCreateReqTest {
nsCreateReq.setDescription("desc");
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsInstantiateReqTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsInstantiateReqTest.java
index 330e34d0cc..70e54a1c09 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsInstantiateReqTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsInstantiateReqTest.java
@@ -36,4 +36,4 @@ public class NsInstantiateReqTest {
nsInstantiateReq.setNsInstanceId("test");
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsOperationKeyTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsOperationKeyTest.java
index e315eefbcc..a8939f8996 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsOperationKeyTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsOperationKeyTest.java
@@ -76,4 +76,4 @@ public class NsOperationKeyTest {
nsOperationKey.setNodeTemplateUUID("nodeTemplateid");
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsParametersTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsParametersTest.java
index 852bac29a1..45c46edd0d 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsParametersTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsParametersTest.java
@@ -20,7 +20,6 @@
package org.onap.so.adapters.vfc.model;
import org.junit.Test;
-
import java.util.Collections;
import java.util.HashMap;
@@ -49,4 +48,4 @@ public class NsParametersTest {
nsParameters.setAdditionalParamForNs(new HashMap<>());
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsProgressStatusTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsProgressStatusTest.java
index e99d9aef38..b1040ef463 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsProgressStatusTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/NsProgressStatusTest.java
@@ -20,7 +20,6 @@
package org.onap.so.adapters.vfc.model;
import org.junit.Test;
-
import java.util.Arrays;
public class NsProgressStatusTest {
@@ -58,4 +57,4 @@ public class NsProgressStatusTest {
nsProgressStatus.setResponseHistoryList(Arrays.asList(new ResponseDescriptor()));
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/ResponseDescriptorTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/ResponseDescriptorTest.java
index a9f2f4ce3c..3f2f73531c 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/ResponseDescriptorTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/ResponseDescriptorTest.java
@@ -76,4 +76,4 @@ public class ResponseDescriptorTest {
responseDescriptor.setResponseId(1);
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/RestfulResponseTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/RestfulResponseTest.java
index 61ddac2707..64f8da65b4 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/RestfulResponseTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/RestfulResponseTest.java
@@ -20,7 +20,6 @@
package org.onap.so.adapters.vfc.model;
import org.junit.Test;
-
import java.util.HashMap;
public class RestfulResponseTest {
@@ -73,4 +72,4 @@ public class RestfulResponseTest {
restfulResponse.setResponseContent("responseString");
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/VimLocationTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/VimLocationTest.java
index e9b250717d..85d3a136af 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/VimLocationTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/model/VimLocationTest.java
@@ -36,4 +36,4 @@ public class VimLocationTest {
vimLocation.setVimId("vimid");
}
-} \ No newline at end of file
+}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/EmbeddedMariaDbConfig.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/EmbeddedMariaDbConfig.java
index 50bf3f97b0..feb40f73e0 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/EmbeddedMariaDbConfig.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/EmbeddedMariaDbConfig.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.adapters.vfc.rest;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
-
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
@@ -37,17 +37,14 @@ import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
-
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration
@Profile({"test"})
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager",
- basePackages = { "org.onap.so.db.request.data.repository"}
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory",
+ transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"})
public class EmbeddedMariaDbConfig {
@Bean
@@ -56,47 +53,34 @@ public class EmbeddedMariaDbConfig {
}
@Primary
- @Bean(name = "requestDataSource")
- @ConfigurationProperties(prefix = "spring.datasource")
+ @Bean(name = "requestDataSource")
+ @ConfigurationProperties(prefix = "spring.datasource")
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
- @Primary
- @Bean(name = "requestEntityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("requestDataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.request.beans")
- .persistenceUnit("requestDB")
- .build();
- }
+ @Primary
+ @Bean(name = "requestEntityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("requestDataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB")
+ .build();
+ }
- @Primary
- @Bean(name = "requestTransactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("requestEntityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
+ @Primary
+ @Bean(name = "requestTransactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/HealthCheckHandlerTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/HealthCheckHandlerTest.java
index 02922db007..fe2bd0bb98 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/HealthCheckHandlerTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/HealthCheckHandlerTest.java
@@ -21,11 +21,7 @@
package org.onap.so.adapters.vfc.rest;
import static org.junit.Assert.*;
-
-
-
import javax.ws.rs.core.Response;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.adapters.vfc.MSOVfcApplication;
@@ -45,28 +41,27 @@ import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = MSOVfcApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class HealthCheckHandlerTest {
-
- @LocalServerPort
- private int port;
- TestRestTemplate restTemplate = new TestRestTemplate();
+ @LocalServerPort
+ private int port;
+
+ TestRestTemplate restTemplate = new TestRestTemplate();
+
+ HttpHeaders headers = new HttpHeaders();
+
+
+ @Test
+ public void testHealthcheck() throws JSONException {
- HttpHeaders headers = new HttpHeaders();
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
-
- @Test
- public void testHealthcheck() throws JSONException {
+ ResponseEntity<String> response =
+ restTemplate.exchange(createURLWithPort("manage/health"), HttpMethod.GET, entity, String.class);
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
- ResponseEntity<String> response = restTemplate.exchange(
- createURLWithPort("manage/health"),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- }
-
- private String createURLWithPort(String uri) {
- return "http://localhost:" + port + uri;
- }
+ private String createURLWithPort(String uri) {
+ return "http://localhost:" + port + uri;
+ }
}
diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/VfcManagerTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/VfcManagerTest.java
index 22e6def28d..08fe6187ea 100644
--- a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/VfcManagerTest.java
+++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/rest/VfcManagerTest.java
@@ -36,7 +36,6 @@ import org.onap.so.adapters.vfc.util.RestfulUtil;
import org.onap.so.db.request.beans.ResourceOperationStatus;
import org.onap.so.db.request.data.repository.ResourceOperationStatusRepository;
import org.springframework.http.HttpStatus;
-
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@@ -122,12 +121,12 @@ public class VfcManagerTest {
RestfulResponse restfulResponse = new RestfulResponse();
restfulResponse.setStatus(HttpStatus.OK.value());
- restfulResponse
- .setResponseContent("{\"" + CommonConstant.JOB_ID + "\": \"someJobId\", " + "\"responseDescriptor\" : {}}");
+ restfulResponse.setResponseContent(
+ "{\"" + CommonConstant.JOB_ID + "\": \"someJobId\", " + "\"responseDescriptor\" : {}}");
when(restfulUtil.send(any(), any(), any())).thenReturn(restfulResponse);
when(resourceOperationStatusRepository.findOne(any()))
- .thenReturn(java.util.Optional.ofNullable(resourceOperationStatus));
+ .thenReturn(java.util.Optional.ofNullable(resourceOperationStatus));
RestfulResponse response = vfcManager.getNsProgress(nsOperationKey, "someJobId");
assertEquals(HttpStatus.OK.value(), response.getStatus());
@@ -148,7 +147,7 @@ public class VfcManagerTest {
when(restfulUtil.send(any(), any(), any())).thenReturn(restfulResponse);
when(resourceOperationStatusRepository.findOne(any()))
- .thenReturn(java.util.Optional.ofNullable(resourceOperationStatus));
+ .thenReturn(java.util.Optional.ofNullable(resourceOperationStatus));
RestfulResponse response = vfcManager.scaleNs("someNsInstanceId", segInput);
assertEquals(HttpStatus.OK.value(), restfulResponse.getStatus());
diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmAdapterApplication.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmAdapterApplication.java
index d7021e7eb8..27b076c6c7 100755
--- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmAdapterApplication.java
+++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmAdapterApplication.java
@@ -29,12 +29,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* The spring boot application for the VNFM (Virtual Network Function Manager) Adapter.
* <p>
- * The VNFM Adapter receives requests through its REST API {@link VnfmAdapterController} which it
- * adapts into ETSI SOL003 compliant LCM (Life Cycle Management) calls towards an ETSI compliant
- * VNFM.
+ * The VNFM Adapter receives requests through its REST API {@link VnfmAdapterController} which it adapts into ETSI
+ * SOL003 compliant LCM (Life Cycle Management) calls towards an ETSI compliant VNFM.
*
- * @see <a href=
- * "https://www.etsi.org/deliver/etsi_gs/NFV-SOL/001_099/003/02.05.01_60/gs_nfv-sol003v020501p.pdf">ETSI
+ * @see <a href= "https://www.etsi.org/deliver/etsi_gs/NFV-SOL/001_099/003/02.05.01_60/gs_nfv-sol003v020501p.pdf">ETSI
* SOL003 v2.5.1</a>
*/
@SpringBootApplication(scanBasePackages = {"org.onap.so"})
diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java
index 6baa672535..2b33e8b11d 100644
--- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java
+++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java
@@ -36,7 +36,7 @@ public class WebSecurityConfigImpl extends WebSecurityConfig {
@Override
protected void configure(final HttpSecurity http) throws Exception {
- http.csrf().disable().authorizeRequests().antMatchers("/manage/health","/manage/info").permitAll()
+ http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll()
.antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and()
.httpBasic();
}
diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java
index 77951062e8..9139d5e66c 100644
--- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java
+++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java
@@ -147,8 +147,8 @@ public class AaiHelper {
}
/**
- * Select a VNFM to use for the given generic VNF. Should only be used when no VNFM has already been
- * assigned to the VNF.
+ * Select a VNFM to use for the given generic VNF. Should only be used when no VNFM has already been assigned to the
+ * VNF.
*
* @param vnf the generic VNF
* @return the VNFM to use
diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/JobManager.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/JobManager.java
index 89356c1b67..7034b7f5ee 100644
--- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/JobManager.java
+++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/JobManager.java
@@ -37,8 +37,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
- * Manages jobs enabling the status of jobs to be queried. A job is associated with an operation on
- * a VNFM.
+ * Manages jobs enabling the status of jobs to be queried. A job is associated with an operation on a VNFM.
*/
@Component
public class JobManager {
@@ -57,9 +56,8 @@ public class JobManager {
*
* @param vnfmId the VNFM the operation relates to
* @param operationId the ID of the associated VNFM operation
- * @param waitForNotificationForSuccess if set to <code>true</code> the
- * {@link QueryJobResponse#getOperationState()} shall not return
- * {@link org.onap.vnfmadapter.v1.model.OperationStateEnum#COMPLETED} unless a required
+ * @param waitForNotificationForSuccess if set to <code>true</code> the {@link QueryJobResponse#getOperationState()}
+ * shall not return {@link org.onap.vnfmadapter.v1.model.OperationStateEnum#COMPLETED} unless a required
* notification has been processed
* @return the ID of the job. Can be used to query the job using {@link #getVnfmOperation(String)}
*/
@@ -75,8 +73,8 @@ public class JobManager {
* Get the operation, associated with the given job ID, from the VNFM.
*
* @param jobId the job ID
- * @return the associated operation from the VNFM, or <code>null</code> of no operation is
- * associated with the given job ID
+ * @return the associated operation from the VNFM, or <code>null</code> of no operation is associated with the given
+ * job ID
*/
public QueryJobResponse getVnfmOperation(final String jobId) {
final VnfmOperation vnfmOperation = mapOfJobIdToVnfmOperation.get(jobId);
diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/VnfmOperation.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/VnfmOperation.java
index e0ad327bd3..3ed66ad713 100644
--- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/VnfmOperation.java
+++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/VnfmOperation.java
@@ -57,8 +57,8 @@ public class VnfmOperation {
/**
* Set the required notification has been processed for the operation.
*
- * @param notificationProcessingWasSuccessful <code>true</code> if the notification processing was
- * successful, <code>false<code> otherwise
+ * @param notificationProcessingWasSuccessful <code>true</code> if the notification processing was successful,
+ * <code>false<code> otherwise
*/
public void setNotificationProcessed(final boolean notificationProcessingWasSuccessful) {
this.notificationStatus =
diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java
index b82ed86beb..a81451b141 100644
--- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java
+++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java
@@ -40,8 +40,8 @@ import org.onap.so.adapters.vnfmadapter.jobmanagement.JobManager;
import org.slf4j.Logger;
/**
- * Performs updates to AAI based on a received notification. The updates are executed in a separate
- * thread so as the notification response to the VNFM is not delayed.
+ * Performs updates to AAI based on a received notification. The updates are executed in a separate thread so as the
+ * notification response to the VNFM is not delayed.
*/
public class NotificationHandler implements Runnable {
private static Logger logger = getLogger(NotificationHandler.class);
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/ASDCControllerSingleton.java b/asdc-controller/src/main/java/org/onap/so/asdc/ASDCControllerSingleton.java
index 9e75c7c339..a5e3340c76 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/ASDCControllerSingleton.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/ASDCControllerSingleton.java
@@ -23,7 +23,6 @@
package org.onap.so.asdc;
import javax.annotation.PreDestroy;
-
import org.onap.so.asdc.client.ASDCController;
import org.onap.so.asdc.client.exceptions.ASDCControllerException;
import org.slf4j.Logger;
@@ -38,32 +37,32 @@ import java.security.SecureRandom;
@Component
@Profile("!test")
public class ASDCControllerSingleton {
-
-
+
+
@Autowired
private ASDCController asdcController;
private static Logger logger = LoggerFactory.getLogger(ASDCControllerSingleton.class);
-
- @Scheduled (fixedRate = 50000)
- public void periodicControllerTask() {
- try {
- int randomNumber = new SecureRandom().nextInt(Integer.MAX_VALUE);
- asdcController.setControllerName("mso-controller" + randomNumber);
- asdcController.initASDC();
- } catch (ASDCControllerException e) {
- logger.error("Exception occurred", e);
- }
- }
-
- @PreDestroy
- private void terminate () {
- try {
- asdcController.closeASDC();
- } catch (ASDCControllerException e) {
- logger.error("Exception occurred", e);
- }
- }
+
+ @Scheduled(fixedRate = 50000)
+ public void periodicControllerTask() {
+ try {
+ int randomNumber = new SecureRandom().nextInt(Integer.MAX_VALUE);
+ asdcController.setControllerName("mso-controller" + randomNumber);
+ asdcController.initASDC();
+ } catch (ASDCControllerException e) {
+ logger.error("Exception occurred", e);
+ }
+ }
+
+ @PreDestroy
+ private void terminate() {
+ try {
+ asdcController.closeASDC();
+ } catch (ASDCControllerException e) {
+ logger.error("Exception occurred", e);
+ }
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/Application.java b/asdc-controller/src/main/java/org/onap/so/asdc/Application.java
index 2f56668c74..1f66291283 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/Application.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/Application.java
@@ -24,29 +24,29 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
-@SpringBootApplication(scanBasePackages = { "org.onap.so" })
+@SpringBootApplication(scanBasePackages = {"org.onap.so"})
@EnableScheduling
public class Application {
- private static final String MSO_CONFIG_PATH = "mso.config.path";
- private static final String LOGS_DIR = "logs_dir";
-
- private static void setLogsDir() {
- if (System.getProperty(LOGS_DIR) == null) {
- System.getProperties().setProperty(LOGS_DIR, "./logs/asdc/");
- }
- }
-
- private static void setConfigPath() {
- if(System.getProperty(MSO_CONFIG_PATH) == null)
- System.getProperties().setProperty(MSO_CONFIG_PATH, ".");
- }
-
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- System.getProperties().setProperty("mso.db", "MARIADB");
-
- System.getProperties().setProperty("server.name", "Springboot");
- setLogsDir();
- }
+ private static final String MSO_CONFIG_PATH = "mso.config.path";
+ private static final String LOGS_DIR = "logs_dir";
+
+ private static void setLogsDir() {
+ if (System.getProperty(LOGS_DIR) == null) {
+ System.getProperties().setProperty(LOGS_DIR, "./logs/asdc/");
+ }
+ }
+
+ private static void setConfigPath() {
+ if (System.getProperty(MSO_CONFIG_PATH) == null)
+ System.getProperties().setProperty(MSO_CONFIG_PATH, ".");
+ }
+
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args);
+ System.getProperties().setProperty("mso.db", "MARIADB");
+
+ System.getProperties().setProperty("server.name", "Springboot");
+ setLogsDir();
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/CatalogDBConfig.java b/asdc-controller/src/main/java/org/onap/so/asdc/CatalogDBConfig.java
index 953c517702..3494945020 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/CatalogDBConfig.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/CatalogDBConfig.java
@@ -39,41 +39,31 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "entityManagerFactory",
- basePackages = {"org.onap.so.db.catalog.data.repository"}
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory",
+ basePackages = {"org.onap.so.db.catalog.data.repository"})
@Profile({"!test"})
public class CatalogDBConfig {
-
- @Primary
- @Bean(name = "dataSource")
- @ConfigurationProperties(prefix = "spring.datasource")
- public DataSource dataSource() {
- return DataSourceBuilder.create().build();
- }
- @Primary
- @Bean(name = "entityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("dataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.catalog.beans")
- .persistenceUnit("catalogDB")
- .build();
- }
+ @Primary
+ @Bean(name = "dataSource")
+ @ConfigurationProperties(prefix = "spring.datasource")
+ public DataSource dataSource() {
+ return DataSourceBuilder.create().build();
+ }
- @Primary
- @Bean(name = "transactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("entityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
+ @Primary
+ @Bean(name = "entityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("dataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.catalog.beans").persistenceUnit("catalogDB")
+ .build();
+ }
+
+ @Primary
+ @Bean(name = "transactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/JerseyConfiguration.java b/asdc-controller/src/main/java/org/onap/so/asdc/JerseyConfiguration.java
index 3a26b7b60c..902506974a 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/JerseyConfiguration.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/JerseyConfiguration.java
@@ -34,19 +34,19 @@ import io.swagger.jaxrs.listing.SwaggerSerializers;
public class JerseyConfiguration extends ResourceConfig {
- @PostConstruct
- public void setUp() {
- register(ASDCRestInterface.class);
- register(ApiListingResource.class);
- register(SwaggerSerializers.class);
-
- BeanConfig beanConfig = new BeanConfig();
- beanConfig.setVersion("1.0.2");
- beanConfig.setSchemes(new String[] { "http" });
- beanConfig.setHost("localhost:8080");
- beanConfig.setBasePath("/mso");
- beanConfig.setResourcePackage("org.onap.so.apihandlerinfra");
- beanConfig.setPrettyPrint(true);
- beanConfig.setScan(true);
- }
+ @PostConstruct
+ public void setUp() {
+ register(ASDCRestInterface.class);
+ register(ApiListingResource.class);
+ register(SwaggerSerializers.class);
+
+ BeanConfig beanConfig = new BeanConfig();
+ beanConfig.setVersion("1.0.2");
+ beanConfig.setSchemes(new String[] {"http"});
+ beanConfig.setHost("localhost:8080");
+ beanConfig.setBasePath("/mso");
+ beanConfig.setResourcePackage("org.onap.so.apihandlerinfra");
+ beanConfig.setPrettyPrint(true);
+ beanConfig.setScan(true);
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/RequestDBConfig.java b/asdc-controller/src/main/java/org/onap/so/asdc/RequestDBConfig.java
index c623552113..8320da01cf 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/RequestDBConfig.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/RequestDBConfig.java
@@ -23,7 +23,6 @@ package org.onap.so.asdc;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
-
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -39,40 +38,30 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager",
- basePackages = { "org.onap.so.db.request.data.repository" }
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory",
+ transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"})
@Profile({"!test"})
public class RequestDBConfig {
- @Bean(name = "requestDataSource")
- @ConfigurationProperties(prefix = "request.datasource")
- public DataSource dataSource() {
- return DataSourceBuilder.create().build();
- }
+ @Bean(name = "requestDataSource")
+ @ConfigurationProperties(prefix = "request.datasource")
+ public DataSource dataSource() {
+ return DataSourceBuilder.create().build();
+ }
- @Bean(name = "requestEntityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("requestDataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.request.beans")
- .persistenceUnit("requestDB")
- .build();
- }
+ @Bean(name = "requestEntityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("requestDataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB")
+ .build();
+ }
- @Bean(name = "requestTransactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("requestEntityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
+ @Bean(name = "requestTransactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java
index 2383e7d810..b45b4f0749 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java
@@ -31,21 +31,18 @@ import org.springframework.util.StringUtils;
@EnableWebSecurity
public class WebSecurityConfigImpl extends WebSecurityConfig {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf().disable()
- .authorizeRequests()
- .antMatchers("/manage/health","/manage/info").permitAll()
- .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),","))
- .and()
- .httpBasic();
- }
-
- @Override
- public void configure(WebSecurity web) throws Exception {
- super.configure(web);
- StrictHttpFirewall firewall = new MSOSpringFirewall();
- web.httpFirewall(firewall);
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll()
+ .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and()
+ .httpBasic();
+ }
+
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ super.configure(web);
+ StrictHttpFirewall firewall = new MSOSpringFirewall();
+ web.httpFirewall(firewall);
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java
index 20e7c873e6..7d92c637ad 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java
@@ -27,7 +27,6 @@ import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-
import org.onap.sdc.api.consumer.IConfiguration;
import org.onap.so.utils.CryptoUtils;
import org.slf4j.Logger;
@@ -44,7 +43,7 @@ public class ASDCConfiguration implements IConfiguration {
// echo -n "This is a test string" | openssl aes-128-ecb -e -K 546573746F736973546573746F736973 -nosalt | xxd
private static Logger logger = LoggerFactory.getLogger(ASDCConfiguration.class);
-
+
private String asdcControllerName;
@@ -66,199 +65,193 @@ public class ASDCConfiguration implements IConfiguration {
public static final String KEY_STORE_PASSWORD = "keyStorePassword";
public static final String KEY_STORE_PATH = "keyStorePath";
- public static final String HEAT="HEAT";
- public static final String HEAT_ARTIFACT="HEAT_ARTIFACT";
- public static final String HEAT_ENV="HEAT_ENV";
- public static final String HEAT_NESTED="HEAT_NESTED";
- public static final String HEAT_NET="HEAT_NET";
- public static final String HEAT_VOL="HEAT_VOL";
- public static final String OTHER="OTHER";
- public static final String TOSCA_CSAR="TOSCA_CSAR";
- public static final String WORKFLOWS="Workflows";
- public static final String VF_MODULES_METADATA="VF_MODULES_METADATA";
-
- private static final String[] SUPPORTED_ARTIFACT_TYPES = {HEAT,
- HEAT_ARTIFACT,
- HEAT_ENV,
- HEAT_NESTED,
- HEAT_NET,
- HEAT_VOL,
- OTHER,
- TOSCA_CSAR,
- VF_MODULES_METADATA};
-
- public static final List<String> SUPPORTED_ARTIFACT_TYPES_LIST = Collections.unmodifiableList(Arrays.asList(SUPPORTED_ARTIFACT_TYPES));
+ public static final String HEAT = "HEAT";
+ public static final String HEAT_ARTIFACT = "HEAT_ARTIFACT";
+ public static final String HEAT_ENV = "HEAT_ENV";
+ public static final String HEAT_NESTED = "HEAT_NESTED";
+ public static final String HEAT_NET = "HEAT_NET";
+ public static final String HEAT_VOL = "HEAT_VOL";
+ public static final String OTHER = "OTHER";
+ public static final String TOSCA_CSAR = "TOSCA_CSAR";
+ public static final String WORKFLOWS = "Workflows";
+ public static final String VF_MODULES_METADATA = "VF_MODULES_METADATA";
+
+ private static final String[] SUPPORTED_ARTIFACT_TYPES =
+ {HEAT, HEAT_ARTIFACT, HEAT_ENV, HEAT_NESTED, HEAT_NET, HEAT_VOL, OTHER, TOSCA_CSAR, VF_MODULES_METADATA};
+
+ public static final List<String> SUPPORTED_ARTIFACT_TYPES_LIST =
+ Collections.unmodifiableList(Arrays.asList(SUPPORTED_ARTIFACT_TYPES));
@Autowired
private Environment env;
-
+
@Value("${mso.asdc.config.key}")
private String configKey;
-
- @Value("${mso.asdc-connections.asdc-controller1.messageBusAddress}")
+
+ @Value("${mso.asdc-connections.asdc-controller1.messageBusAddress}")
private String[] messageBusAddress;
-
-
+
+
public void setAsdcControllerName(String asdcControllerName) {
- this.asdcControllerName = asdcControllerName;
- }
+ this.asdcControllerName = asdcControllerName;
+ }
- @Override
+ @Override
public java.lang.Boolean isUseHttpsWithDmaap() {
- return getBooleanPropertyWithDefault("mso.asdc-connections.asdc-controller1.useHttpsWithDmaap", true);
+ return getBooleanPropertyWithDefault("mso.asdc-connections.asdc-controller1.useHttpsWithDmaap", true);
}
-
+
@Override
- public boolean isConsumeProduceStatusTopic(){
- return true;
+ public boolean isConsumeProduceStatusTopic() {
+ return true;
}
-
+
@Override
- public List<String> getMsgBusAddress(){
+ public List<String> getMsgBusAddress() {
if (messageBusAddress.length > 0) {
- return Arrays.asList(messageBusAddress);
+ return Arrays.asList(messageBusAddress);
} else {
return Collections.emptyList();
- }
-
-
+ }
+
+
}
-
- public String getAsdcControllerName () {
+
+ public String getAsdcControllerName() {
return asdcControllerName;
}
- @Override
- public String getConsumerGroup() {
- return getPropertyOrNull("mso.asdc-connections.asdc-controller1.consumerGroup");
- }
-
- public int getWatchDogTimeout () {
- return getIntegerPropertyOrZero("mso.asdc-connections.asdc-controller1.watchDogTimeout");
-
+ @Override
+ public String getConsumerGroup() {
+ return getPropertyOrNull("mso.asdc-connections.asdc-controller1.consumerGroup");
+ }
+
+ public int getWatchDogTimeout() {
+ return getIntegerPropertyOrZero("mso.asdc-connections.asdc-controller1.watchDogTimeout");
+
}
@Override
- public String getConsumerID () {
- return getPropertyOrNull("mso.asdc-connections.asdc-controller1.consumerId");
+ public String getConsumerID() {
+ return getPropertyOrNull("mso.asdc-connections.asdc-controller1.consumerId");
}
-
- public int getIntegerPropertyOrZero (String propertyName) {
- String property = env.getProperty(propertyName);
- if (property == null || "NULL".equals(property) || property.isEmpty()) {
- return 0;
- } else {
- try {
- return Integer.parseInt(property);
- } catch (NumberFormatException e) {
- return 0;
- }
- }
+
+ public int getIntegerPropertyOrZero(String propertyName) {
+ String property = env.getProperty(propertyName);
+ if (property == null || "NULL".equals(property) || property.isEmpty()) {
+ return 0;
+ } else {
+ try {
+ return Integer.parseInt(property);
+ } catch (NumberFormatException e) {
+ return 0;
+ }
+ }
+ }
+
+ public String getPropertyOrNull(String propertyName) {
+ String config = env.getProperty(propertyName);
+ if (config == null || "NULL".equals(config) || config.isEmpty()) {
+ return null;
+ } else {
+ return config;
+ }
}
-
- public String getPropertyOrNull (String propertyName) {
- String config = env.getProperty(propertyName);
- if (config==null || "NULL".equals(config) || config.isEmpty()) {
- return null;
- } else {
- return config;
- }
+
+ public String getEncryptedPropertyOrNull(String propertyName) {
+ String decryptedKey;
+ String config = env.getProperty(propertyName);
+
+ if (config == null || "NULL".equals(config) || config.isEmpty()) {
+ return null;
+ }
+
+ try {
+ decryptedKey = CryptoUtils.decrypt(config, this.configKey);
+ } catch (GeneralSecurityException e) {
+ logger.debug("Exception while decrypting property: {}", propertyName, e);
+ return null;
+ }
+
+ if (decryptedKey.isEmpty()) {
+ return null;
+ } else {
+ return decryptedKey;
+ }
}
-
- public String getEncryptedPropertyOrNull (String propertyName) {
- String decryptedKey;
- String config = env.getProperty(propertyName);
-
- if (config==null || "NULL".equals(config) || config.isEmpty()) {
- return null;
- }
-
- try {
- decryptedKey = CryptoUtils.decrypt(config, this.configKey);
- } catch (GeneralSecurityException e) {
- logger.debug("Exception while decrypting property: {}", propertyName, e);
- return null;
- }
-
- if (decryptedKey.isEmpty ()) {
- return null;
- } else {
- return decryptedKey;
+
+ public boolean getBooleanPropertyWithDefault(String propertyName, boolean defaultValue) {
+ String config = env.getProperty(propertyName);
+ if (config == null || "NULL".equals(config) || config.isEmpty()) {
+ return defaultValue;
+ } else {
+ try {
+ return Boolean.valueOf(config);
+ } catch (Exception e) {
+ return defaultValue;
}
- }
-
- public boolean getBooleanPropertyWithDefault (String propertyName, boolean defaultValue) {
- String config = env.getProperty(propertyName);
- if (config == null || "NULL".equals(config) || config.isEmpty()) {
- return defaultValue;
- } else {
- try {
- return Boolean.valueOf(config);
- } catch (Exception e) {
- return defaultValue;
- }
- }
+ }
}
@Override
- public String getEnvironmentName () {
- return getPropertyOrNull("mso.asdc-connections.asdc-controller1.environmentName");
+ public String getEnvironmentName() {
+ return getPropertyOrNull("mso.asdc-connections.asdc-controller1.environmentName");
}
@Override
- public String getPassword () {
- return getEncryptedPropertyOrNull("mso.asdc-connections.asdc-controller1.password");
+ public String getPassword() {
+ return getEncryptedPropertyOrNull("mso.asdc-connections.asdc-controller1.password");
}
@Override
- public int getPollingInterval () {
- return getIntegerPropertyOrZero("mso.asdc-connections.asdc-controller1.pollingInterval");
+ public int getPollingInterval() {
+ return getIntegerPropertyOrZero("mso.asdc-connections.asdc-controller1.pollingInterval");
}
@Override
- public List <String> getRelevantArtifactTypes () {
- // DO not return the Static List SUPPORTED_ARTIFACT_TYPES_LIST because the ASDC Client will try to modify it !!!
- return Arrays.asList(SUPPORTED_ARTIFACT_TYPES);
+ public List<String> getRelevantArtifactTypes() {
+ // DO not return the Static List SUPPORTED_ARTIFACT_TYPES_LIST because the ASDC Client will try to modify it !!!
+ return Arrays.asList(SUPPORTED_ARTIFACT_TYPES);
}
@Override
- public String getUser () {
- return getPropertyOrNull("mso.asdc-connections.asdc-controller1.user");
+ public String getUser() {
+ return getPropertyOrNull("mso.asdc-connections.asdc-controller1.user");
}
@Override
- public String getAsdcAddress () {
- return getPropertyOrNull("mso.asdc-connections.asdc-controller1.asdcAddress");
+ public String getAsdcAddress() {
+ return getPropertyOrNull("mso.asdc-connections.asdc-controller1.asdcAddress");
}
@Override
- public int getPollingTimeout () {
- return getIntegerPropertyOrZero("mso.asdc-connections.asdc-controller1.pollingTimeout");
+ public int getPollingTimeout() {
+ return getIntegerPropertyOrZero("mso.asdc-connections.asdc-controller1.pollingTimeout");
}
- @Override
- public boolean activateServerTLSAuth() {
- return getBooleanPropertyWithDefault("mso.asdc-connections.asdc-controller1.activateServerTLSAuth", true);
- }
+ @Override
+ public boolean activateServerTLSAuth() {
+ return getBooleanPropertyWithDefault("mso.asdc-connections.asdc-controller1.activateServerTLSAuth", true);
+ }
- @Override
- public String getKeyStorePassword() {
- return getPropertyOrNull("mso.asdc-connections.asdc-controller1.keyStorePassword");
- }
+ @Override
+ public String getKeyStorePassword() {
+ return getPropertyOrNull("mso.asdc-connections.asdc-controller1.keyStorePassword");
+ }
- @Override
- public String getKeyStorePath() {
- return getPropertyOrNull("mso.asdc-connections.asdc-controller1.keyStorePath");
- }
+ @Override
+ public String getKeyStorePath() {
+ return getPropertyOrNull("mso.asdc-connections.asdc-controller1.keyStorePath");
+ }
/**
- * The flag allows the client to receive metadata for all resources of the service regardless of the artifacts associated to them.
- * Setting the flag to false will preserve legacy behavior.
+ * The flag allows the client to receive metadata for all resources of the service regardless of the artifacts
+ * associated to them. Setting the flag to false will preserve legacy behavior.
*/
- @Override
+ @Override
public boolean isFilterInEmptyResources() {
- return getBooleanPropertyWithDefault("mso.asdc-connections.asdc-controller1.isFilterInEmptyResources", true);
+ return getBooleanPropertyWithDefault("mso.asdc-connections.asdc-controller1.isFilterInEmptyResources", true);
}
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java
index c9332e8f84..92326b1907 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java
@@ -160,7 +160,7 @@ public class ASDCController {
}
public ASDCController(String controllerConfigName, IDistributionClient asdcClient,
- IVfResourceInstaller resourceinstaller) {
+ IVfResourceInstaller resourceinstaller) {
distributionClient = asdcClient;
}
@@ -181,7 +181,7 @@ public class ASDCController {
* This method initializes the ASDC Controller and the ASDC Client.
*
* @throws ASDCControllerException It throws an exception if the ASDC Client cannot be instantiated or if an init
- * attempt is done when already initialized
+ * attempt is done when already initialized
* @throws ASDCParametersException If there is an issue with the parameters provided
* @throws IOException In case of issues when trying to load the key file
*/
@@ -201,25 +201,25 @@ public class ASDCController {
distributionClient = DistributionClientFactory.createDistributionClient();
}
- IDistributionClientResult result = this.distributionClient.init(asdcConfig,
- asdcNotificationCallBack, asdcStatusCallBack);
+ IDistributionClientResult result =
+ this.distributionClient.init(asdcConfig, asdcNotificationCallBack, asdcStatusCallBack);
if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
- String endEvent = "ASDC distribution client init failed with reason:"
- + result.getDistributionMessageResult();
+ String endEvent =
+ "ASDC distribution client init failed with reason:" + result.getDistributionMessageResult();
logger.debug(endEvent);
this.changeControllerStatus(ASDCControllerStatus.STOPPED);
throw new ASDCControllerException("Initialization of the ASDC Controller failed with reason: "
- + result.getDistributionMessageResult());
+ + result.getDistributionMessageResult());
}
result = this.distributionClient.start();
if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
- String endEvent = "ASDC distribution client start failed with reason:"
- + result.getDistributionMessageResult();
+ String endEvent =
+ "ASDC distribution client start failed with reason:" + result.getDistributionMessageResult();
logger.debug(endEvent);
this.changeControllerStatus(ASDCControllerStatus.STOPPED);
- throw new ASDCControllerException("Startup of the ASDC Controller failed with reason: "
- + result.getDistributionMessageResult());
+ throw new ASDCControllerException(
+ "Startup of the ASDC Controller failed with reason: " + result.getDistributionMessageResult());
}
this.changeControllerStatus(ASDCControllerStatus.IDLE);
@@ -230,7 +230,7 @@ public class ASDCController {
* This method closes the ASDC Controller and the ASDC Client.
*
* @throws ASDCControllerException It throws an exception if the ASDC Client cannot be closed because it's currently
- * BUSY in processing notifications.
+ * BUSY in processing notifications.
*/
public void closeASDC() throws ASDCControllerException {
@@ -254,9 +254,8 @@ public class ASDCController {
if (toscaInstaller.isResourceAlreadyDeployed(resource)) {
logger.info("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_EXIST.toString(),
- resource.getResourceInstance().getResourceInstanceName(),
- resource.getResourceInstance().getResourceUUID(),
- resource.getResourceInstance().getResourceName());
+ resource.getResourceInstance().getResourceInstanceName(),
+ resource.getResourceInstance().getResourceUUID(), resource.getResourceInstance().getResourceName());
this.sendDeployNotificationsForResource(resource, DistributionStatusEnum.ALREADY_DOWNLOADED, null);
this.sendDeployNotificationsForResource(resource, DistributionStatusEnum.ALREADY_DEPLOYED, null);
@@ -268,11 +267,11 @@ public class ASDCController {
}
- protected IDistributionClientDownloadResult downloadTheArtifact(IArtifactInfo artifact,
- String distributionId) throws ASDCDownloadException {
+ protected IDistributionClientDownloadResult downloadTheArtifact(IArtifactInfo artifact, String distributionId)
+ throws ASDCDownloadException {
logger.info("Trying to download the artifact UUID: {} from URL: {}", artifact.getArtifactUUID(),
- artifact.getArtifactURL());
+ artifact.getArtifactURL());
IDistributionClientDownloadResult downloadResult;
try {
@@ -283,67 +282,47 @@ public class ASDCController {
}
} catch (RuntimeException e) {
logger.debug("Not able to download the artifact due to an exception: " + artifact.getArtifactURL());
- this.sendASDCNotification(NotificationType.DOWNLOAD,
- artifact.getArtifactURL(),
- asdcConfig.getConsumerID(),
- distributionId,
- DistributionStatusEnum.DOWNLOAD_ERROR,
- e.getMessage(),
- System.currentTimeMillis());
+ this.sendASDCNotification(NotificationType.DOWNLOAD, artifact.getArtifactURL(), asdcConfig.getConsumerID(),
+ distributionId, DistributionStatusEnum.DOWNLOAD_ERROR, e.getMessage(), System.currentTimeMillis());
throw new ASDCDownloadException("Exception caught when downloading the artifact", e);
}
if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult())) {
logger.info("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_DOWNLOAD_SUC.toString(), artifact.getArtifactURL(),
- artifact.getArtifactUUID(), String.valueOf(downloadResult.getArtifactPayload().length));
+ artifact.getArtifactUUID(), String.valueOf(downloadResult.getArtifactPayload().length));
} else {
logger.error("{} {} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL.toString(),
- artifact.getArtifactName(), artifact.getArtifactURL(), artifact.getArtifactUUID(),
- downloadResult.getDistributionMessageResult(), ErrorCode.DataError.getValue(),
- "ASDC artifact download fail");
-
- this.sendASDCNotification(NotificationType.DOWNLOAD,
- artifact.getArtifactURL(),
- asdcConfig.getConsumerID(),
- distributionId,
- DistributionStatusEnum.DOWNLOAD_ERROR,
- downloadResult.getDistributionMessageResult(),
- System.currentTimeMillis());
+ artifact.getArtifactName(), artifact.getArtifactURL(), artifact.getArtifactUUID(),
+ downloadResult.getDistributionMessageResult(), ErrorCode.DataError.getValue(),
+ "ASDC artifact download fail");
+
+ this.sendASDCNotification(NotificationType.DOWNLOAD, artifact.getArtifactURL(), asdcConfig.getConsumerID(),
+ distributionId, DistributionStatusEnum.DOWNLOAD_ERROR,
+ downloadResult.getDistributionMessageResult(), System.currentTimeMillis());
throw new ASDCDownloadException("Artifact " + artifact.getArtifactName()
- + " could not be downloaded from ASDC URL "
- + artifact.getArtifactURL()
- + UUID_PARAM
- + artifact.getArtifactUUID()
- + ")"
- + System.lineSeparator()
- + "Error message is "
- + downloadResult.getDistributionMessageResult()
- + System.lineSeparator());
+ + " could not be downloaded from ASDC URL " + artifact.getArtifactURL() + UUID_PARAM
+ + artifact.getArtifactUUID() + ")" + System.lineSeparator() + "Error message is "
+ + downloadResult.getDistributionMessageResult() + System.lineSeparator());
}
- this.sendASDCNotification(NotificationType.DOWNLOAD,
- artifact.getArtifactURL(),
- asdcConfig.getConsumerID(),
- distributionId,
- DistributionStatusEnum.DOWNLOAD_OK,
- null,
- System.currentTimeMillis());
+ this.sendASDCNotification(NotificationType.DOWNLOAD, artifact.getArtifactURL(), asdcConfig.getConsumerID(),
+ distributionId, DistributionStatusEnum.DOWNLOAD_OK, null, System.currentTimeMillis());
return downloadResult;
}
private void writeArtifactToFile(IArtifactInfo artifact, IDistributionClientDownloadResult resultArtifact) {
- String filePath = Paths
- .get(getMsoConfigPath(), "ASDC", artifact.getArtifactVersion(), artifact.getArtifactName()).normalize()
- .toString();
+ String filePath =
+ Paths.get(getMsoConfigPath(), "ASDC", artifact.getArtifactVersion(), artifact.getArtifactName())
+ .normalize().toString();
logger.info("Trying to write artifact UUID: {}, URL: {} to file: {}", artifact.getArtifactUUID(),
- artifact.getArtifactURL(), filePath);
+ artifact.getArtifactURL(), filePath);
// make parent directory
File file = new File(filePath);
@@ -356,101 +335,88 @@ public class ASDCController {
try (FileOutputStream outFile = new FileOutputStream(filePath)) {
logger.info("{} {} {} {}", MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), "***WRITE FILE ARTIFACT NAME",
- "ASDC", artifact.getArtifactName());
+ "ASDC", artifact.getArtifactName());
outFile.write(payloadBytes, 0, payloadBytes.length);
} catch (Exception e) {
logger.debug("Exception :", e);
logger.error("{} {} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL.toString(),
- artifact.getArtifactName(), artifact.getArtifactURL(), artifact.getArtifactUUID(),
- resultArtifact.getDistributionMessageResult(), ErrorCode.DataError.getValue(),
- "ASDC write to file failed");
+ artifact.getArtifactName(), artifact.getArtifactURL(), artifact.getArtifactUUID(),
+ resultArtifact.getDistributionMessageResult(), ErrorCode.DataError.getValue(),
+ "ASDC write to file failed");
}
}
protected void sendDeployNotificationsForResource(ResourceStructure resourceStructure,
- DistributionStatusEnum distribStatus, String errorReason) {
+ DistributionStatusEnum distribStatus, String errorReason) {
for (IArtifactInfo artifactInfo : resourceStructure.getResourceInstance().getArtifacts()) {
- if ((DistributionStatusEnum.DEPLOY_OK.equals(distribStatus) && !artifactInfo.getArtifactType()
- .equalsIgnoreCase("OTHER") && !resourceStructure.isAlreadyDeployed())
- // This could be NULL if the artifact is a VF module artifact, this won't be present in the MAP
- && resourceStructure.getArtifactsMapByUUID().get(artifactInfo.getArtifactUUID()) != null
- && resourceStructure.getArtifactsMapByUUID().get(artifactInfo.getArtifactUUID()).getDeployedInDb()
- == 0) {
- this.sendASDCNotification(NotificationType.DEPLOY,
- artifactInfo.getArtifactURL(),
- asdcConfig.getConsumerID(),
- resourceStructure.getNotification().getDistributionID(),
- DistributionStatusEnum.DEPLOY_ERROR,
- "The artifact has not been used by the modules defined in the resource",
- System.currentTimeMillis());
+ if ((DistributionStatusEnum.DEPLOY_OK.equals(distribStatus)
+ && !artifactInfo.getArtifactType().equalsIgnoreCase("OTHER")
+ && !resourceStructure.isAlreadyDeployed())
+ // This could be NULL if the artifact is a VF module artifact, this won't be present in the MAP
+ && resourceStructure.getArtifactsMapByUUID().get(artifactInfo.getArtifactUUID()) != null
+ && resourceStructure.getArtifactsMapByUUID().get(artifactInfo.getArtifactUUID())
+ .getDeployedInDb() == 0) {
+ this.sendASDCNotification(NotificationType.DEPLOY, artifactInfo.getArtifactURL(),
+ asdcConfig.getConsumerID(), resourceStructure.getNotification().getDistributionID(),
+ DistributionStatusEnum.DEPLOY_ERROR,
+ "The artifact has not been used by the modules defined in the resource",
+ System.currentTimeMillis());
} else {
- this.sendASDCNotification(NotificationType.DEPLOY,
- artifactInfo.getArtifactURL(),
- asdcConfig.getConsumerID(),
- resourceStructure.getNotification().getDistributionID(),
- distribStatus,
- errorReason,
- System.currentTimeMillis());
+ this.sendASDCNotification(NotificationType.DEPLOY, artifactInfo.getArtifactURL(),
+ asdcConfig.getConsumerID(), resourceStructure.getNotification().getDistributionID(),
+ distribStatus, errorReason, System.currentTimeMillis());
}
}
}
protected void sendCsarDeployNotification(INotificationData iNotif, ResourceStructure resourceStructure,
- ToscaResourceStructure toscaResourceStructure, boolean deploySuccessful, String errorReason) {
+ ToscaResourceStructure toscaResourceStructure, boolean deploySuccessful, String errorReason) {
IArtifactInfo csarArtifact = toscaResourceStructure.getToscaArtifact();
if (deploySuccessful) {
- this.sendASDCNotification(NotificationType.DEPLOY,
- csarArtifact.getArtifactURL(),
- asdcConfig.getConsumerID(),
- resourceStructure.getNotification().getDistributionID(),
- DistributionStatusEnum.DEPLOY_OK,
- errorReason,
- System.currentTimeMillis());
+ this.sendASDCNotification(NotificationType.DEPLOY, csarArtifact.getArtifactURL(),
+ asdcConfig.getConsumerID(), resourceStructure.getNotification().getDistributionID(),
+ DistributionStatusEnum.DEPLOY_OK, errorReason, System.currentTimeMillis());
} else {
- this.sendASDCNotification(NotificationType.DEPLOY,
- csarArtifact.getArtifactURL(),
- asdcConfig.getConsumerID(),
- resourceStructure.getNotification().getDistributionID(),
- DistributionStatusEnum.DEPLOY_ERROR,
- errorReason,
- System.currentTimeMillis());
+ this.sendASDCNotification(NotificationType.DEPLOY, csarArtifact.getArtifactURL(),
+ asdcConfig.getConsumerID(), resourceStructure.getNotification().getDistributionID(),
+ DistributionStatusEnum.DEPLOY_ERROR, errorReason, System.currentTimeMillis());
}
}
protected void deployResourceStructure(ResourceStructure resourceStructure,
- ToscaResourceStructure toscaResourceStructure) throws ArtifactInstallerException {
+ ToscaResourceStructure toscaResourceStructure) throws ArtifactInstallerException {
logger.info("{} {} {} {}", MessageEnum.ASDC_START_DEPLOY_ARTIFACT.toString(),
- resourceStructure.getResourceInstance().getResourceInstanceName(),
- resourceStructure.getResourceInstance().getResourceUUID(), "ASDC");
+ resourceStructure.getResourceInstance().getResourceInstanceName(),
+ resourceStructure.getResourceInstance().getResourceUUID(), "ASDC");
try {
resourceStructure.prepareInstall();
toscaInstaller.installTheResource(toscaResourceStructure, resourceStructure);
} catch (ArtifactInstallerException e) {
logger.info("{} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL.toString(),
- resourceStructure.getResourceInstance().getResourceName(),
- resourceStructure.getResourceInstance().getResourceUUID(),
- String.valueOf(resourceStructure.getNumberOfResources()), "ASDC", "deployResourceStructure");
+ resourceStructure.getResourceInstance().getResourceName(),
+ resourceStructure.getResourceInstance().getResourceUUID(),
+ String.valueOf(resourceStructure.getNumberOfResources()), "ASDC", "deployResourceStructure");
sendDeployNotificationsForResource(resourceStructure, DistributionStatusEnum.DEPLOY_ERROR, e.getMessage());
throw e;
}
if (resourceStructure.isDeployedSuccessfully() || toscaResourceStructure.isDeployedSuccessfully()) {
logger.info("{} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC.toString(),
- resourceStructure.getResourceInstance().getResourceName(),
- resourceStructure.getResourceInstance().getResourceUUID(),
- String.valueOf(resourceStructure.getNumberOfResources()), "ASDC", "deployResourceStructure");
+ resourceStructure.getResourceInstance().getResourceName(),
+ resourceStructure.getResourceInstance().getResourceUUID(),
+ String.valueOf(resourceStructure.getNumberOfResources()), "ASDC", "deployResourceStructure");
sendDeployNotificationsForResource(resourceStructure, DistributionStatusEnum.DEPLOY_OK, null);
}
@@ -461,35 +427,23 @@ public class ASDCController {
DOWNLOAD, DEPLOY
}
- protected void sendASDCNotification(NotificationType notificationType,
- String artifactURL,
- String consumerID,
- String distributionID,
- DistributionStatusEnum status,
- String errorReason,
- long timestamp) {
-
- String event = "Sending " + notificationType.name()
- + "("
- + status.name()
- + ")"
- + " notification to ASDC for artifact:"
- + artifactURL;
+ protected void sendASDCNotification(NotificationType notificationType, String artifactURL, String consumerID,
+ String distributionID, DistributionStatusEnum status, String errorReason, long timestamp) {
+
+ String event = "Sending " + notificationType.name() + "(" + status.name() + ")"
+ + " notification to ASDC for artifact:" + artifactURL;
if (errorReason != null) {
event = event + "(" + errorReason + ")";
}
logger.info("{} {} {} {} {} {}", MessageEnum.ASDC_SEND_NOTIF_ASDC.toString(), notificationType.name(),
- status.name(), artifactURL, "ASDC", "sendASDCNotification");
+ status.name(), artifactURL, "ASDC", "sendASDCNotification");
logger.debug(event);
String action = "";
try {
- IDistributionStatusMessage message = new DistributionStatusMessage(artifactURL,
- consumerID,
- distributionID,
- status,
- timestamp);
+ IDistributionStatusMessage message =
+ new DistributionStatusMessage(artifactURL, consumerID, distributionID, status, timestamp);
switch (notificationType) {
case DOWNLOAD:
@@ -513,25 +467,22 @@ public class ASDCController {
}
} catch (RuntimeException e) {
logger.warn("{} {} {} {} {}", MessageEnum.ASDC_SEND_NOTIF_ASDC_EXEC.toString(), "ASDC",
- "sendASDCNotification", ErrorCode.SchemaError.getValue(),
- "RuntimeException - sendASDCNotification", e);
+ "sendASDCNotification", ErrorCode.SchemaError.getValue(), "RuntimeException - sendASDCNotification",
+ e);
}
}
- protected void sendFinalDistributionStatus(
- String distributionID,
- DistributionStatusEnum status,
- String errorReason) {
+ protected void sendFinalDistributionStatus(String distributionID, DistributionStatusEnum status,
+ String errorReason) {
- logger.debug(
- "Enter sendFinalDistributionStatus with DistributionID " + distributionID + " and Status of " + status
- .name() + " and ErrorReason " + errorReason);
+ logger.debug("Enter sendFinalDistributionStatus with DistributionID " + distributionID + " and Status of "
+ + status.name() + " and ErrorReason " + errorReason);
long subStarttime = System.currentTimeMillis();
try {
IFinalDistrStatusMessage finalDistribution = new FinalDistributionStatusMessage(distributionID, status,
- subStarttime, asdcConfig.getConsumerID());
+ subStarttime, asdcConfig.getConsumerID());
if (errorReason == null) {
this.distributionClient.sendFinalDistrStatus(finalDistribution);
@@ -543,8 +494,8 @@ public class ASDCController {
} catch (RuntimeException e) {
logger.debug("Exception caught in sendFinalDistributionStatus {}", e.getMessage());
logger.warn("{} {} {} {} {}", MessageEnum.ASDC_SEND_NOTIF_ASDC_EXEC.toString(), "ASDC",
- "sendASDCNotification",
- ErrorCode.SchemaError.getValue(), "RuntimeException - sendASDCNotification", e);
+ "sendASDCNotification", ErrorCode.SchemaError.getValue(), "RuntimeException - sendASDCNotification",
+ e);
}
}
@@ -572,25 +523,24 @@ public class ASDCController {
noOfArtifacts += resource.getArtifacts().size();
}
logger.info("{} {} {} {}", MessageEnum.ASDC_RECEIVE_CALLBACK_NOTIF.toString(), String.valueOf(noOfArtifacts),
- iNotif.getServiceUUID(), "ASDC");
+ iNotif.getServiceUUID(), "ASDC");
try {
logger.debug(ASDCNotificationLogging.dumpASDCNotification(iNotif));
- logger
- .info("{} {} {} {}", MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), iNotif.getServiceUUID(), "ASDC",
- "treatNotification");
+ logger.info("{} {} {} {}", MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), iNotif.getServiceUUID(),
+ "ASDC", "treatNotification");
this.changeControllerStatus(ASDCControllerStatus.BUSY);
Optional<String> notificationMessage = getNotificationJson(iNotif);
toscaInstaller.processWatchdog(iNotif.getDistributionID(), iNotif.getServiceUUID(), notificationMessage,
- asdcConfig.getConsumerID());
+ asdcConfig.getConsumerID());
// Process only the Resource artifacts in MSO
this.processResourceNotification(iNotif);
- //********************************************************************************************************
- //Start Watchdog loop and wait for all components to complete before reporting final status back.
+ // ********************************************************************************************************
+ // Start Watchdog loop and wait for all components to complete before reporting final status back.
// **If timer expires first then we will report a Distribution Error back to ASDC
- //********************************************************************************************************
+ // ********************************************************************************************************
long initialStartTime = System.currentTimeMillis();
boolean componentsComplete = false;
String distributionStatus = null;
@@ -609,8 +559,8 @@ public class ASDCController {
Thread.sleep(watchDogTimeout / 10);
}
- if (distributionStatus != null && !distributionStatus
- .equalsIgnoreCase(DistributionStatus.INCOMPLETE.name())) {
+ if (distributionStatus != null
+ && !distributionStatus.equalsIgnoreCase(DistributionStatus.INCOMPLETE.name())) {
if (distributionStatus.equalsIgnoreCase(DistributionStatus.SUCCESS.name())) {
isDeploySuccess = true;
@@ -623,8 +573,8 @@ public class ASDCController {
}
if (!componentsComplete) {
- logger
- .debug("Timeout of {} seconds was reached before all components reported status", watchDogTimeout);
+ logger.debug("Timeout of {} seconds was reached before all components reported status",
+ watchDogTimeout);
watchdogError = "Timeout occurred while waiting for all components to report status";
overallStatus = DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name();
}
@@ -647,13 +597,13 @@ public class ASDCController {
if (isDeploySuccess && watchdogError == null) {
sendFinalDistributionStatus(iNotif.getDistributionID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_OK,
- null);
+ null);
WatchdogDistributionStatus wds = new WatchdogDistributionStatus(iNotif.getDistributionID());
wds.setDistributionIdStatus(DistributionStatusEnum.DISTRIBUTION_COMPLETE_OK.toString());
wdsRepo.save(wds);
} else {
sendFinalDistributionStatus(iNotif.getDistributionID(),
- DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR, watchdogError);
+ DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR, watchdogError);
WatchdogDistributionStatus wds = new WatchdogDistributionStatus(iNotif.getDistributionID());
wds.setDistributionIdStatus(DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.toString());
wdsRepo.save(wds);
@@ -662,25 +612,24 @@ public class ASDCController {
} catch (ObjectOptimisticLockingFailureException e) {
- logger.debug("OptimisticLockingFailure for DistributionId: {} Another process "
- + "has already altered this distribution, so not going to process it on this site.",
- iNotif.getDistributionID());
+ logger.debug(
+ "OptimisticLockingFailure for DistributionId: {} Another process "
+ + "has already altered this distribution, so not going to process it on this site.",
+ iNotif.getDistributionID());
logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(),
- "Database concurrency exception: ", "ASDC", "treatNotification",
- ErrorCode.BusinessProcesssError.getValue(), "RuntimeException in treatNotification", e);
+ "Database concurrency exception: ", "ASDC", "treatNotification",
+ ErrorCode.BusinessProcesssError.getValue(), "RuntimeException in treatNotification", e);
} catch (Exception e) {
logger.error("", MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(),
- "Unexpected exception caught during the notification processing", "ASDC",
- "treatNotification", ErrorCode.SchemaError.getValue(),
- "RuntimeException in treatNotification",
- e);
+ "Unexpected exception caught during the notification processing", "ASDC", "treatNotification",
+ ErrorCode.SchemaError.getValue(), "RuntimeException in treatNotification", e);
try {
wd.executePatchAAI(iNotif.getDistributionID(), iNotif.getServiceInvariantUUID(),
- DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name());
+ DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name());
logger.debug("A&AI Updated succefully with Distribution Status of {}",
- DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name());
+ DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.name());
} catch (Exception aaiException) {
logger.debug("Exception in executePatchAAI(): {}", aaiException);
if (aaiException.getCause() != null) {
@@ -689,7 +638,7 @@ public class ASDCController {
}
sendFinalDistributionStatus(iNotif.getDistributionID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR,
- e.getMessage());
+ e.getMessage());
WatchdogDistributionStatus wds = new WatchdogDistributionStatus(iNotif.getDistributionID());
wds.setDistributionIdStatus(DistributionStatusEnum.DISTRIBUTION_COMPLETE_ERROR.toString());
@@ -712,8 +661,7 @@ public class ASDCController {
this.processCsarServiceArtifacts(iNotif, toscaResourceStructure);
IArtifactInfo iArtifact = toscaResourceStructure.getToscaArtifact();
String filePath =
- msoConfigPath + "/ASDC/" + iArtifact.getArtifactVersion() + "/" + iArtifact
- .getArtifactName();
+ msoConfigPath + "/ASDC/" + iArtifact.getArtifactVersion() + "/" + iArtifact.getArtifactName();
File csarFile = new File(filePath);
String csarFilePath = csarFile.getAbsolutePath();
if (bpmnInstaller.containsWorkflows(csarFilePath)) {
@@ -739,14 +687,14 @@ public class ASDCController {
}
for (IArtifactInfo artifact : resource.getArtifacts()) {
- IDistributionClientDownloadResult resultArtifact = this.downloadTheArtifact(artifact,
- iNotif.getDistributionID());
+ IDistributionClientDownloadResult resultArtifact =
+ this.downloadTheArtifact(artifact, iNotif.getDistributionID());
if (resultArtifact != null) {
resourceStructure.addArtifactToStructure(distributionClient, artifact, resultArtifact);
}
}
- //Deploy VF resource and artifacts
+ // Deploy VF resource and artifacts
logger.debug("Preparing to deploy Service: {}", iNotif.getServiceUUID());
try {
this.deployResourceStructure(resourceStructure, toscaResourceStructure);
@@ -757,14 +705,14 @@ public class ASDCController {
}
this.sendCsarDeployNotification(iNotif, resourceStructure, toscaResourceStructure, deploySuccessful,
- errorMessage);
+ errorMessage);
}
} catch (ASDCDownloadException | UnsupportedEncodingException e) {
logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(),
- "Exception caught during Installation of artifact", "ASDC", "processResourceNotification",
- ErrorCode.BusinessProcesssError.getValue(), "Exception in processResourceNotification", e);
+ "Exception caught during Installation of artifact", "ASDC", "processResourceNotification",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception in processResourceNotification", e);
}
}
@@ -783,7 +731,7 @@ public class ASDCController {
}
protected void processCsarServiceArtifacts(INotificationData iNotif,
- ToscaResourceStructure toscaResourceStructure) {
+ ToscaResourceStructure toscaResourceStructure) {
List<IArtifactInfo> serviceArtifacts = iNotif.getServiceArtifacts();
@@ -795,8 +743,8 @@ public class ASDCController {
toscaResourceStructure.setToscaArtifact(artifact);
- IDistributionClientDownloadResult resultArtifact = this
- .downloadTheArtifact(artifact, iNotif.getDistributionID());
+ IDistributionClientDownloadResult resultArtifact =
+ this.downloadTheArtifact(artifact, iNotif.getDistributionID());
writeArtifactToFile(artifact, resultArtifact);
@@ -809,16 +757,16 @@ public class ASDCController {
} catch (Exception e) {
logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(),
- "Exception caught during processCsarServiceArtifacts", "ASDC", "processCsarServiceArtifacts",
- ErrorCode.BusinessProcesssError.getValue(),
- "Exception in processCsarServiceArtifacts", e);
+ "Exception caught during processCsarServiceArtifacts", "ASDC",
+ "processCsarServiceArtifacts", ErrorCode.BusinessProcesssError.getValue(),
+ "Exception in processCsarServiceArtifacts", e);
}
} else if (artifact.getArtifactType().equals(ASDCConfiguration.WORKFLOWS)) {
try {
- IDistributionClientDownloadResult resultArtifact = this
- .downloadTheArtifact(artifact, iNotif.getDistributionID());
+ IDistributionClientDownloadResult resultArtifact =
+ this.downloadTheArtifact(artifact, iNotif.getDistributionID());
writeArtifactToFile(artifact, resultArtifact);
@@ -830,10 +778,9 @@ public class ASDCController {
} catch (Exception e) {
logger.info("Whats the error {}", e.getMessage());
logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(),
- "Exception caught during processCsarServiceArtifacts", "ASDC", "processCsarServiceArtifacts",
- ErrorCode.BusinessProcesssError.getValue(),
- "Exception in processCsarServiceArtifacts",
- e);
+ "Exception caught during processCsarServiceArtifacts", "ASDC",
+ "processCsarServiceArtifacts", ErrorCode.BusinessProcesssError.getValue(),
+ "Exception in processCsarServiceArtifacts", e);
}
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCControllerStatus.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCControllerStatus.java
index e358fee4a1..9cc2a8fd14 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCControllerStatus.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCControllerStatus.java
@@ -23,5 +23,5 @@ package org.onap.so.asdc.client;
public enum ASDCControllerStatus {
- STOPPED, IDLE, BUSY
+ STOPPED, IDLE, BUSY
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCNotificationCallBack.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCNotificationCallBack.java
index 876c5e164f..48ae2f145d 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCNotificationCallBack.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCNotificationCallBack.java
@@ -37,19 +37,18 @@ import org.springframework.stereotype.Component;
@Component
public final class ASDCNotificationCallBack implements INotificationCallback {
- @Autowired
+ @Autowired
private ASDCController asdcController;
-
+
protected static final Logger logger = LoggerFactory.getLogger(ASDCNotificationCallBack.class);
/**
- * This method can be called multiple times at the same moment.
- * The controller must be thread safe !
+ * This method can be called multiple times at the same moment. The controller must be thread safe !
*/
@Override
- public void activateCallback (INotificationData iNotif) {
- String event = "Receive a callback notification in ASDC, nb of resources: " + iNotif.getResources ().size ();
+ public void activateCallback(INotificationData iNotif) {
+ String event = "Receive a callback notification in ASDC, nb of resources: " + iNotif.getResources().size();
logger.debug(event);
- asdcController.treatNotification (iNotif);
+ asdcController.treatNotification(iNotif);
}
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCStatusCallBack.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCStatusCallBack.java
index 612599b2ed..d0f86c722e 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCStatusCallBack.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCStatusCallBack.java
@@ -37,37 +37,39 @@ import org.springframework.stereotype.Component;
@Component
public final class ASDCStatusCallBack implements IStatusCallback {
- @Autowired
- private ToscaResourceInstaller toscaInstaller;
+ @Autowired
+ private ToscaResourceInstaller toscaInstaller;
- protected static final Logger logger = LoggerFactory.getLogger(ASDCStatusCallBack.class);
-
- @Autowired
- private WatchdogDistributionStatusRepository watchdogDistributionStatusRepository;
+ protected static final Logger logger = LoggerFactory.getLogger(ASDCStatusCallBack.class);
- @Override
- public void activateCallback (IStatusData iStatus) {
- String event = "Receive a callback componentStatus in ASDC, for componentName: " + iStatus.getComponentName() + " and status of " + iStatus.getStatus() + " distributionID of " + iStatus.getDistributionID();
+ @Autowired
+ private WatchdogDistributionStatusRepository watchdogDistributionStatusRepository;
- try{
+ @Override
+ public void activateCallback(IStatusData iStatus) {
+ String event = "Receive a callback componentStatus in ASDC, for componentName: " + iStatus.getComponentName()
+ + " and status of " + iStatus.getStatus() + " distributionID of " + iStatus.getDistributionID();
- if(iStatus.getStatus() != null){
- if(iStatus.getStatus().equals(DistributionStatusEnum.COMPONENT_DONE_OK) || iStatus.getStatus().equals(DistributionStatusEnum.COMPONENT_DONE_ERROR)) {
- WatchdogDistributionStatus watchdogDistributionStatus = watchdogDistributionStatusRepository.findById(iStatus.getDistributionID ())
- .orElseGet( () -> null);
- if(watchdogDistributionStatus==null){
- watchdogDistributionStatus = new WatchdogDistributionStatus();
- watchdogDistributionStatus.setDistributionId(iStatus.getDistributionID ());
- watchdogDistributionStatusRepository.save(watchdogDistributionStatus);
- }
- logger.debug(event);
- toscaInstaller.installTheComponentStatus(iStatus);
-
- }
- }
- }catch(ArtifactInstallerException e){
- logger.error("Error in ASDCStatusCallback {}", e.getMessage(), e);
- logger.debug("Error in ASDCStatusCallback {}", e.getMessage());
- }
- }
+ try {
+
+ if (iStatus.getStatus() != null) {
+ if (iStatus.getStatus().equals(DistributionStatusEnum.COMPONENT_DONE_OK)
+ || iStatus.getStatus().equals(DistributionStatusEnum.COMPONENT_DONE_ERROR)) {
+ WatchdogDistributionStatus watchdogDistributionStatus = watchdogDistributionStatusRepository
+ .findById(iStatus.getDistributionID()).orElseGet(() -> null);
+ if (watchdogDistributionStatus == null) {
+ watchdogDistributionStatus = new WatchdogDistributionStatus();
+ watchdogDistributionStatus.setDistributionId(iStatus.getDistributionID());
+ watchdogDistributionStatusRepository.save(watchdogDistributionStatus);
+ }
+ logger.debug(event);
+ toscaInstaller.installTheComponentStatus(iStatus);
+
+ }
+ }
+ } catch (ArtifactInstallerException e) {
+ logger.error("Error in ASDCStatusCallback {}", e.getMessage(), e);
+ logger.debug("Error in ASDCStatusCallback {}", e.getMessage());
+ }
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/DistributionStatusMessage.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/DistributionStatusMessage.java
index db2d2c3bd3..19e55615a1 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/DistributionStatusMessage.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/DistributionStatusMessage.java
@@ -26,52 +26,53 @@ import org.onap.sdc.utils.DistributionStatusEnum;
public class DistributionStatusMessage implements IDistributionStatusMessage {
- private String artifactURL;
-
- private String consumerID;
-
- private String distributionID;
-
- private DistributionStatusEnum distributionStatus;
-
- private long timestamp;
-
- public DistributionStatusMessage (final String artifactUrl, final String consumerId,final String distributionId, final DistributionStatusEnum distributionStatusEnum, final long timestampL) {
- artifactURL = artifactUrl;
- consumerID = consumerId;
- distributionID = distributionId;
- distributionStatus = distributionStatusEnum;
- timestamp = timestampL;
- }
-
- @Override
- public String getArtifactURL() {
-
- return artifactURL;
- }
-
- @Override
- public String getConsumerID() {
-
- return consumerID;
- }
-
- @Override
- public String getDistributionID() {
-
- return distributionID;
- }
-
- @Override
- public DistributionStatusEnum getStatus() {
-
- return distributionStatus;
- }
-
- @Override
- public long getTimestamp() {
-
- return timestamp;
- }
+ private String artifactURL;
+
+ private String consumerID;
+
+ private String distributionID;
+
+ private DistributionStatusEnum distributionStatus;
+
+ private long timestamp;
+
+ public DistributionStatusMessage(final String artifactUrl, final String consumerId, final String distributionId,
+ final DistributionStatusEnum distributionStatusEnum, final long timestampL) {
+ artifactURL = artifactUrl;
+ consumerID = consumerId;
+ distributionID = distributionId;
+ distributionStatus = distributionStatusEnum;
+ timestamp = timestampL;
+ }
+
+ @Override
+ public String getArtifactURL() {
+
+ return artifactURL;
+ }
+
+ @Override
+ public String getConsumerID() {
+
+ return consumerID;
+ }
+
+ @Override
+ public String getDistributionID() {
+
+ return distributionID;
+ }
+
+ @Override
+ public DistributionStatusEnum getStatus() {
+
+ return distributionStatus;
+ }
+
+ @Override
+ public long getTimestamp() {
+
+ return timestamp;
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/FinalDistributionStatusMessage.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/FinalDistributionStatusMessage.java
index 376b678c0e..13cace404e 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/FinalDistributionStatusMessage.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/FinalDistributionStatusMessage.java
@@ -23,64 +23,65 @@ package org.onap.so.asdc.client;
import org.onap.sdc.api.consumer.IFinalDistrStatusMessage;
import org.onap.sdc.utils.DistributionStatusEnum;
-public class FinalDistributionStatusMessage implements IFinalDistrStatusMessage{
-
- private String componentName;
-
- private String consumerID;
-
- private String distributionID;
-
- private DistributionStatusEnum status;
-
- private long timestamp;
-
- public FinalDistributionStatusMessage (String distributionId, final DistributionStatusEnum distributionStatusEnum, final long timestampL, String consumerId) {
- //componentName = componentname;
- consumerID = consumerId;
- distributionID = distributionId;
- status = distributionStatusEnum;
- timestamp = timestampL;
- }
-
- public DistributionStatusEnum getStatus() {
- return status;
- }
-
- public void setStatus(DistributionStatusEnum status) {
- this.status = status;
- }
-
- public String getDistributionID() {
- return distributionID;
- }
-
- public void setDistributionID(String distributionID) {
- this.distributionID = distributionID;
- }
-
- public long getTimestamp() {
- return timestamp;
- }
-
- public void setTimestamp(long timestamp) {
- this.timestamp = timestamp;
- }
-
- public String getComponentName() {
- return componentName;
- }
-
- public void setComponentName(String componentName) {
- this.componentName = componentName;
- }
-
- public String getConsumerID() {
- return consumerID;
- }
-
- public void setConsumerID(String consumerID) {
- this.consumerID = consumerID;
- }
+public class FinalDistributionStatusMessage implements IFinalDistrStatusMessage {
+
+ private String componentName;
+
+ private String consumerID;
+
+ private String distributionID;
+
+ private DistributionStatusEnum status;
+
+ private long timestamp;
+
+ public FinalDistributionStatusMessage(String distributionId, final DistributionStatusEnum distributionStatusEnum,
+ final long timestampL, String consumerId) {
+ // componentName = componentname;
+ consumerID = consumerId;
+ distributionID = distributionId;
+ status = distributionStatusEnum;
+ timestamp = timestampL;
+ }
+
+ public DistributionStatusEnum getStatus() {
+ return status;
+ }
+
+ public void setStatus(DistributionStatusEnum status) {
+ this.status = status;
+ }
+
+ public String getDistributionID() {
+ return distributionID;
+ }
+
+ public void setDistributionID(String distributionID) {
+ this.distributionID = distributionID;
+ }
+
+ public long getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(long timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getComponentName() {
+ return componentName;
+ }
+
+ public void setComponentName(String componentName) {
+ this.componentName = componentName;
+ }
+
+ public String getConsumerID() {
+ return consumerID;
+ }
+
+ public void setConsumerID(String consumerID) {
+ this.consumerID = consumerID;
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ResourceInstance.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ResourceInstance.java
index 9115ed3ef2..1e243e6d41 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/ResourceInstance.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ResourceInstance.java
@@ -21,59 +21,58 @@
package org.onap.so.asdc.client;
import java.util.ArrayList;
-
import org.onap.sdc.api.notification.IResourceInstance;
public class ResourceInstance implements IResourceInstance {
-
+
@Override
- public String getResourceInstanceName(){
- return new String();
+ public String getResourceInstanceName() {
+ return new String();
}
-
+
@Override
- public String getResourceName(){
- return new String();
+ public String getResourceName() {
+ return new String();
}
-
+
@Override
- public String getResourceVersion(){
- return new String();
+ public String getResourceVersion() {
+ return new String();
}
-
+
@Override
- public String getResourceType(){
- return new String();
+ public String getResourceType() {
+ return new String();
}
-
+
@Override
- public String getResourceUUID(){
- return new String();
+ public String getResourceUUID() {
+ return new String();
}
-
+
@Override
- public java.util.List getArtifacts(){
- return new ArrayList();
+ public java.util.List getArtifacts() {
+ return new ArrayList();
}
-
+
@Override
- public String getResourceInvariantUUID(){
- return new String();
+ public String getResourceInvariantUUID() {
+ return new String();
}
-
+
@Override
- public String getResourceCustomizationUUID(){
- return new String();
+ public String getResourceCustomizationUUID() {
+ return new String();
}
-
+
@Override
- public String getCategory(){
- return new String();
+ public String getCategory() {
+ return new String();
}
-
+
@Override
- public String getSubcategory(){
- return new String();
+ public String getSubcategory() {
+ return new String();
}
-
+
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCControllerException.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCControllerException.java
index 98257f761c..c80156b070 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCControllerException.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCControllerException.java
@@ -26,26 +26,26 @@ package org.onap.so.asdc.client.exceptions;
*/
public class ASDCControllerException extends Exception {
- /**
+ /**
* serialization id.
- */
- private static final long serialVersionUID = -4236006447255525130L;
+ */
+ private static final long serialVersionUID = -4236006447255525130L;
- /**
+ /**
* @param message The message to dump
* @param cause The Throwable cause object
*/
- public ASDCControllerException (final String message) {
- super (message);
-
+ public ASDCControllerException(final String message) {
+ super(message);
+
}
-
+
/**
* @param message The message to dump
* @param cause The Throwable cause object
*/
- public ASDCControllerException (final String message, final Throwable cause) {
- super (message, cause);
-
+ public ASDCControllerException(final String message, final Throwable cause) {
+ super(message, cause);
+
}
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCDownloadException.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCDownloadException.java
index f4e0bf0327..4271bb7779 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCDownloadException.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCDownloadException.java
@@ -26,26 +26,26 @@ package org.onap.so.asdc.client.exceptions;
*/
public class ASDCDownloadException extends Exception {
- /**
+ /**
* serialization id.
- */
- private static final long serialVersionUID = -5276848693231134901L;
+ */
+ private static final long serialVersionUID = -5276848693231134901L;
- /**
+ /**
* @param message The message to dump
* @param cause The Throwable cause object
*/
- public ASDCDownloadException (final String message) {
- super (message);
-
+ public ASDCDownloadException(final String message) {
+ super(message);
+
}
-
+
/**
* @param message The message to dump
* @param cause The Throwable cause object
*/
- public ASDCDownloadException (final String message, final Throwable cause) {
- super (message, cause);
-
+ public ASDCDownloadException(final String message, final Throwable cause) {
+ super(message, cause);
+
}
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCParametersException.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCParametersException.java
index aecb9223c9..51f51d2fe0 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCParametersException.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ASDCParametersException.java
@@ -26,26 +26,26 @@ package org.onap.so.asdc.client.exceptions;
*/
public class ASDCParametersException extends Exception {
- /**
+ /**
* serialization id.
- */
- private static final long serialVersionUID = 8425657297510362736L;
+ */
+ private static final long serialVersionUID = 8425657297510362736L;
/**
* @param message The message to dump
* @param cause The Throwable cause object
*/
- public ASDCParametersException (final String message) {
- super (message);
-
+ public ASDCParametersException(final String message) {
+ super(message);
+
}
-
+
/**
* @param message The message to dump
* @param cause The Throwable cause object
*/
- public ASDCParametersException (final String message, final Throwable cause) {
- super (message, cause);
-
+ public ASDCParametersException(final String message, final Throwable cause) {
+ super(message, cause);
+
}
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerException.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerException.java
index 78ccb5da0a..7d214d363e 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerException.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerException.java
@@ -26,26 +26,26 @@ package org.onap.so.asdc.client.exceptions;
*/
public class ArtifactInstallerException extends Exception {
- /**
+ /**
* serialization id.
- */
- private static final long serialVersionUID = 4095937499475915021L;
+ */
+ private static final long serialVersionUID = 4095937499475915021L;
/**
* @param message The message to dump
* @param cause The Throwable cause object
*/
- public ArtifactInstallerException (final String message) {
- super (message);
-
+ public ArtifactInstallerException(final String message) {
+ super(message);
+
}
-
+
/**
* @param message The message to dump
* @param cause The Throwable cause object
*/
- public ArtifactInstallerException (final String message, final Throwable cause) {
- super (message, cause);
-
+ public ArtifactInstallerException(final String message, final Throwable cause) {
+ super(message, cause);
+
}
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImpl.java
index 759d88f196..b3618a8095 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImpl.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImpl.java
@@ -22,171 +22,168 @@ package org.onap.so.asdc.client.test.emulators;
import java.util.ArrayList;
import java.util.List;
-
import org.onap.sdc.api.notification.IArtifactInfo;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
public class ArtifactInfoImpl implements IArtifactInfo {
- private String artifactName;
- private String artifactType;
- private String artifactURL;
- private String artifactChecksum;
- private String artifactDescription;
- private Integer artifactTimeout;
- private String artifactVersion;
- private String artifactUUID;
- private String generatedFromUUID;
- private ArtifactInfoImpl generatedArtifact;
- private List<IArtifactInfo> relatedArtifactsInfo;
- private List<ArtifactInfoImpl> relatedArtifactsImpl;
- public ArtifactInfoImpl(){}
-
- private ArtifactInfoImpl(IArtifactInfo iArtifactInfo){
- artifactName = iArtifactInfo.getArtifactName();
- artifactType = iArtifactInfo.getArtifactType();
- artifactURL = iArtifactInfo.getArtifactURL();
- artifactChecksum = iArtifactInfo.getArtifactChecksum();
- artifactDescription = iArtifactInfo.getArtifactDescription();
- artifactTimeout = iArtifactInfo.getArtifactTimeout();
- artifactVersion = iArtifactInfo.getArtifactVersion();
- artifactUUID = iArtifactInfo.getArtifactUUID();
- generatedArtifact = (ArtifactInfoImpl) iArtifactInfo.getGeneratedArtifact();
- relatedArtifactsInfo = iArtifactInfo.getRelatedArtifacts();
- }
-
- public static List<ArtifactInfoImpl> convertToArtifactInfoImpl(List<IArtifactInfo> list){
- List<ArtifactInfoImpl> ret = new ArrayList<ArtifactInfoImpl>();
- if( list != null ){
- for(IArtifactInfo artifactInfo : list ){
- ret.add(new ArtifactInfoImpl(artifactInfo));
- }
- }
- return ret;
- }
-
- public String getArtifactName() {
- return artifactName;
- }
-
- public void setArtifactName(String artifactName) {
- this.artifactName = artifactName;
- }
-
- public String getArtifactType() {
- return artifactType;
- }
-
- public void setArtifactType(String artifactType) {
- this.artifactType = artifactType;
- }
-
- public String getArtifactURL() {
- return artifactURL;
- }
-
- public void setArtifactURL(String artifactURL) {
- this.artifactURL = artifactURL;
- }
-
- public String getArtifactChecksum() {
- return artifactChecksum;
- }
-
- public void setArtifactChecksum(String artifactChecksum) {
- this.artifactChecksum = artifactChecksum;
- }
-
- public String getArtifactDescription() {
- return artifactDescription;
- }
-
- public void setArtifactDescription(String artifactDescription) {
- this.artifactDescription = artifactDescription;
- }
-
- public Integer getArtifactTimeout() {
- return artifactTimeout;
- }
-
- public void setArtifactTimeout(Integer artifactTimeout) {
- this.artifactTimeout = artifactTimeout;
- }
-
- @Override
- public String toString() {
- return "BaseArtifactInfoImpl [artifactName=" + artifactName
- + ", artifactType=" + artifactType + ", artifactURL="
- + artifactURL + ", artifactChecksum=" + artifactChecksum
- + ", artifactDescription=" + artifactDescription
- + ", artifactVersion=" + artifactVersion
- + ", artifactUUID=" + artifactUUID
- + ", artifactTimeout=" + artifactTimeout + "]";
- }
-
- public String getArtifactVersion() {
- return artifactVersion;
- }
-
- public void setArtifactVersion(String artifactVersion) {
- this.artifactVersion = artifactVersion;
- }
-
- public String getArtifactUUID() {
- return artifactUUID;
- }
-
- public void setArtifactUUID(String artifactUUID) {
- this.artifactUUID = artifactUUID;
- }
-
- public String getGeneratedFromUUID() {
- return generatedFromUUID;
- }
-
- public void setGeneratedFromUUID(String generatedFromUUID) {
- this.generatedFromUUID = generatedFromUUID;
- }
-
- @Override
- public ArtifactInfoImpl getGeneratedArtifact() {
- return generatedArtifact;
- }
-
- public void setGeneratedArtifact(ArtifactInfoImpl generatedArtifact) {
- this.generatedArtifact = generatedArtifact;
- }
-
- @Override
- public List<IArtifactInfo> getRelatedArtifacts(){
- List<IArtifactInfo> temp = new ArrayList<IArtifactInfo>();
- if( relatedArtifactsInfo != null ){
- temp.addAll(relatedArtifactsImpl);
- }
- return temp;
- }
-
- public void setRelatedArtifacts(List<ArtifactInfoImpl> relatedArtifacts) {
- this.relatedArtifactsImpl = relatedArtifacts;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ArtifactInfoImpl)) {
- return false;
- }
- ArtifactInfoImpl castOther = (ArtifactInfoImpl) other;
- return new EqualsBuilder().append(artifactUUID, castOther.artifactUUID)
- .append(artifactVersion, castOther.artifactVersion).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(artifactName).append(artifactType).append(artifactURL)
- .append(artifactChecksum).append(artifactDescription).append(artifactTimeout).append(artifactVersion)
- .append(artifactUUID).append(generatedFromUUID).append(generatedArtifact).append(relatedArtifactsInfo)
- .append(relatedArtifactsImpl).toHashCode();
- }
+ private String artifactName;
+ private String artifactType;
+ private String artifactURL;
+ private String artifactChecksum;
+ private String artifactDescription;
+ private Integer artifactTimeout;
+ private String artifactVersion;
+ private String artifactUUID;
+ private String generatedFromUUID;
+ private ArtifactInfoImpl generatedArtifact;
+ private List<IArtifactInfo> relatedArtifactsInfo;
+ private List<ArtifactInfoImpl> relatedArtifactsImpl;
+
+ public ArtifactInfoImpl() {}
+
+ private ArtifactInfoImpl(IArtifactInfo iArtifactInfo) {
+ artifactName = iArtifactInfo.getArtifactName();
+ artifactType = iArtifactInfo.getArtifactType();
+ artifactURL = iArtifactInfo.getArtifactURL();
+ artifactChecksum = iArtifactInfo.getArtifactChecksum();
+ artifactDescription = iArtifactInfo.getArtifactDescription();
+ artifactTimeout = iArtifactInfo.getArtifactTimeout();
+ artifactVersion = iArtifactInfo.getArtifactVersion();
+ artifactUUID = iArtifactInfo.getArtifactUUID();
+ generatedArtifact = (ArtifactInfoImpl) iArtifactInfo.getGeneratedArtifact();
+ relatedArtifactsInfo = iArtifactInfo.getRelatedArtifacts();
+ }
+
+ public static List<ArtifactInfoImpl> convertToArtifactInfoImpl(List<IArtifactInfo> list) {
+ List<ArtifactInfoImpl> ret = new ArrayList<ArtifactInfoImpl>();
+ if (list != null) {
+ for (IArtifactInfo artifactInfo : list) {
+ ret.add(new ArtifactInfoImpl(artifactInfo));
+ }
+ }
+ return ret;
+ }
+
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ public void setArtifactName(String artifactName) {
+ this.artifactName = artifactName;
+ }
+
+ public String getArtifactType() {
+ return artifactType;
+ }
+
+ public void setArtifactType(String artifactType) {
+ this.artifactType = artifactType;
+ }
+
+ public String getArtifactURL() {
+ return artifactURL;
+ }
+
+ public void setArtifactURL(String artifactURL) {
+ this.artifactURL = artifactURL;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public void setArtifactChecksum(String artifactChecksum) {
+ this.artifactChecksum = artifactChecksum;
+ }
+
+ public String getArtifactDescription() {
+ return artifactDescription;
+ }
+
+ public void setArtifactDescription(String artifactDescription) {
+ this.artifactDescription = artifactDescription;
+ }
+
+ public Integer getArtifactTimeout() {
+ return artifactTimeout;
+ }
+
+ public void setArtifactTimeout(Integer artifactTimeout) {
+ this.artifactTimeout = artifactTimeout;
+ }
+
+ @Override
+ public String toString() {
+ return "BaseArtifactInfoImpl [artifactName=" + artifactName + ", artifactType=" + artifactType
+ + ", artifactURL=" + artifactURL + ", artifactChecksum=" + artifactChecksum + ", artifactDescription="
+ + artifactDescription + ", artifactVersion=" + artifactVersion + ", artifactUUID=" + artifactUUID
+ + ", artifactTimeout=" + artifactTimeout + "]";
+ }
+
+ public String getArtifactVersion() {
+ return artifactVersion;
+ }
+
+ public void setArtifactVersion(String artifactVersion) {
+ this.artifactVersion = artifactVersion;
+ }
+
+ public String getArtifactUUID() {
+ return artifactUUID;
+ }
+
+ public void setArtifactUUID(String artifactUUID) {
+ this.artifactUUID = artifactUUID;
+ }
+
+ public String getGeneratedFromUUID() {
+ return generatedFromUUID;
+ }
+
+ public void setGeneratedFromUUID(String generatedFromUUID) {
+ this.generatedFromUUID = generatedFromUUID;
+ }
+
+ @Override
+ public ArtifactInfoImpl getGeneratedArtifact() {
+ return generatedArtifact;
+ }
+
+ public void setGeneratedArtifact(ArtifactInfoImpl generatedArtifact) {
+ this.generatedArtifact = generatedArtifact;
+ }
+
+ @Override
+ public List<IArtifactInfo> getRelatedArtifacts() {
+ List<IArtifactInfo> temp = new ArrayList<IArtifactInfo>();
+ if (relatedArtifactsInfo != null) {
+ temp.addAll(relatedArtifactsImpl);
+ }
+ return temp;
+ }
+
+ public void setRelatedArtifacts(List<ArtifactInfoImpl> relatedArtifacts) {
+ this.relatedArtifactsImpl = relatedArtifacts;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ArtifactInfoImpl)) {
+ return false;
+ }
+ ArtifactInfoImpl castOther = (ArtifactInfoImpl) other;
+ return new EqualsBuilder().append(artifactUUID, castOther.artifactUUID)
+ .append(artifactVersion, castOther.artifactVersion).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(artifactName).append(artifactType).append(artifactURL)
+ .append(artifactChecksum).append(artifactDescription).append(artifactTimeout).append(artifactVersion)
+ .append(artifactUUID).append(generatedFromUUID).append(generatedArtifact).append(relatedArtifactsInfo)
+ .append(relatedArtifactsImpl).toHashCode();
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulator.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulator.java
index ffb7f7a7f4..efa564c3e9 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulator.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulator.java
@@ -27,7 +27,6 @@ import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
-
import org.onap.so.asdc.installer.IVfModuleData;
import org.onap.sdc.api.IDistributionClient;
import org.onap.sdc.api.consumer.IComponentDoneStatusMessage;
@@ -48,143 +47,148 @@ import org.slf4j.LoggerFactory;
public class DistributionClientEmulator implements IDistributionClient {
- private String resourcePath;
-
- private List<IVfModuleData> listVFModuleMetaData;
-
- private List<IDistributionStatusMessage> distributionMessageReceived = new LinkedList<>();
-
-
- private static final Logger logger = LoggerFactory.getLogger(DistributionClientEmulator.class );
-
- public DistributionClientEmulator() {
- }
-
- public DistributionClientEmulator(String notifFolderInResource) {
- resourcePath = notifFolderInResource;
- }
-
- public List<IDistributionStatusMessage> getDistributionMessageReceived() {
- return distributionMessageReceived;
- }
-
- @Override
- public List<IVfModuleMetadata> decodeVfModuleArtifact(byte[] arg0) {
- return null;
- }
-
- public String getResourcePath() {
- return resourcePath;
- }
-
- public void setResourcePath(String resourcePath) {
- this.resourcePath = resourcePath;
- }
-
- public List<IVfModuleData> getListVFModuleMetaData() {
- return listVFModuleMetaData;
- }
-
- @Override
- public IDistributionClientDownloadResult download (IArtifactInfo arg0) {
-
- String filename = arg0.getArtifactURL();
-
- byte[] inputStream=null;
- try {
- inputStream = getData(filename);
- } catch (IOException e) {
- logger.error("IOException in DistributionClientEmulator.download() method", e);
- }
-
- return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name(),arg0.getArtifactName(),inputStream);
- }
-
- private byte[] getData(String filename) throws IOException {
- return Files.readAllBytes(Paths.get(resourcePath + filename));
- }
-
- @Override
- public IConfiguration getConfiguration() {
- return null;
- }
-
- @Override
- public IDistributionClientResult init(IConfiguration arg0, INotificationCallback arg1) {
- return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- }
-
- @Override
- public IDistributionClientResult init(IConfiguration arg0, INotificationCallback arg1, IStatusCallback arg2) {
- return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- }
-
- @Override
- public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage arg0) {
- this.distributionMessageReceived.add(arg0);
- return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- }
-
- @Override
- public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage arg0, String arg1) {
- this.distributionMessageReceived.add(arg0);
- return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- }
-
- @Override
- public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage arg0) {
- this.distributionMessageReceived.add(arg0);
- return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- }
-
- @Override
- public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage arg0, String arg1) {
- this.distributionMessageReceived.add(arg0);
- return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- }
-
- @Override
- public IDistributionClientResult start() {
- return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- }
-
- @Override
- public IDistributionClientResult stop() {
- return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
-
- }
-
- @Override
- public IDistributionClientResult updateConfiguration(IConfiguration arg0) {
- return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- }
-
- @Override
- public IDistributionClientResult sendComponentDoneStatus(
- IComponentDoneStatusMessage arg0) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IDistributionClientResult sendFinalDistrStatus(
- IFinalDistrStatusMessage arg0) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IDistributionClientResult sendComponentDoneStatus(
- IComponentDoneStatusMessage arg0, String arg1) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IDistributionClientResult sendFinalDistrStatus(
- IFinalDistrStatusMessage arg0, String arg1) {
- // TODO Auto-generated method stub
- return null;
- }
+ private String resourcePath;
+
+ private List<IVfModuleData> listVFModuleMetaData;
+
+ private List<IDistributionStatusMessage> distributionMessageReceived = new LinkedList<>();
+
+
+ private static final Logger logger = LoggerFactory.getLogger(DistributionClientEmulator.class);
+
+ public DistributionClientEmulator() {}
+
+ public DistributionClientEmulator(String notifFolderInResource) {
+ resourcePath = notifFolderInResource;
+ }
+
+ public List<IDistributionStatusMessage> getDistributionMessageReceived() {
+ return distributionMessageReceived;
+ }
+
+ @Override
+ public List<IVfModuleMetadata> decodeVfModuleArtifact(byte[] arg0) {
+ return null;
+ }
+
+ public String getResourcePath() {
+ return resourcePath;
+ }
+
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ public List<IVfModuleData> getListVFModuleMetaData() {
+ return listVFModuleMetaData;
+ }
+
+ @Override
+ public IDistributionClientDownloadResult download(IArtifactInfo arg0) {
+
+ String filename = arg0.getArtifactURL();
+
+ byte[] inputStream = null;
+ try {
+ inputStream = getData(filename);
+ } catch (IOException e) {
+ logger.error("IOException in DistributionClientEmulator.download() method", e);
+ }
+
+ return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS,
+ DistributionActionResultEnum.SUCCESS.name(), arg0.getArtifactName(), inputStream);
+ }
+
+ private byte[] getData(String filename) throws IOException {
+ return Files.readAllBytes(Paths.get(resourcePath + filename));
+ }
+
+ @Override
+ public IConfiguration getConfiguration() {
+ return null;
+ }
+
+ @Override
+ public IDistributionClientResult init(IConfiguration arg0, INotificationCallback arg1) {
+ return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,
+ DistributionActionResultEnum.SUCCESS.name());
+ }
+
+ @Override
+ public IDistributionClientResult init(IConfiguration arg0, INotificationCallback arg1, IStatusCallback arg2) {
+ return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,
+ DistributionActionResultEnum.SUCCESS.name());
+ }
+
+ @Override
+ public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage arg0) {
+ this.distributionMessageReceived.add(arg0);
+ return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,
+ DistributionActionResultEnum.SUCCESS.name());
+ }
+
+ @Override
+ public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage arg0, String arg1) {
+ this.distributionMessageReceived.add(arg0);
+ return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,
+ DistributionActionResultEnum.SUCCESS.name());
+ }
+
+ @Override
+ public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage arg0) {
+ this.distributionMessageReceived.add(arg0);
+ return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,
+ DistributionActionResultEnum.SUCCESS.name());
+ }
+
+ @Override
+ public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage arg0, String arg1) {
+ this.distributionMessageReceived.add(arg0);
+ return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,
+ DistributionActionResultEnum.SUCCESS.name());
+ }
+
+ @Override
+ public IDistributionClientResult start() {
+ return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,
+ DistributionActionResultEnum.SUCCESS.name());
+ }
+
+ @Override
+ public IDistributionClientResult stop() {
+ return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,
+ DistributionActionResultEnum.SUCCESS.name());
+
+ }
+
+ @Override
+ public IDistributionClientResult updateConfiguration(IConfiguration arg0) {
+ return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,
+ DistributionActionResultEnum.SUCCESS.name());
+ }
+
+ @Override
+ public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage arg0) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage arg0) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage arg0, String arg1) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage arg0, String arg1) {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonStatusData.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonStatusData.java
index 58193dbee6..7bd9c752a4 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonStatusData.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonStatusData.java
@@ -24,101 +24,100 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
-
import org.onap.sdc.api.notification.IStatusData;
import org.onap.sdc.utils.DistributionStatusEnum;
-
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonStatusData implements IStatusData {
-
- @JsonIgnore
- private static ObjectMapper mapper = new ObjectMapper();
-
- @JsonIgnore
- private Map<String,Object> attributesMap = new HashMap<>();
-
- public JsonStatusData() {
-
- }
-
- @Override
- public String getErrorReason(){
- return "MSO FAILURE";
- }
-
- @Override
- public String getDistributionID(){
- //return (String)this.attributesMap.get("distributionID");
- return "35120a87-1f82-4276-9735-f6de5a244d65";
- }
-
- @Override
- public String getConsumerID(){
- //return (String)this.attributesMap.get("consumerID");
- return "mso.123456";
- }
-
- @Override
- public String getComponentName(){
- //return (String)this.attributesMap.get("componentName");
- return "SDN-C";
- }
-
- @Override
- public Long getTimestamp(){
- //return (String)this.attributesMap.get("timestamp");
- return null;
- }
-
- @Override
- public String getArtifactURL(){
- //return (String)this.attributesMap.get("artifactURL");
- return "/sdc/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml";
- }
-
- @Override
- public DistributionStatusEnum getStatus(){
- //return (DistributionStatusEnum)this.attributesMap.get(DistributionStatusEnum.DEPLOY_OK);
- return DistributionStatusEnum.COMPONENT_DONE_OK;
- }
-
- /**
- * Method instantiate a INotificationData implementation from a JSON file.
- *
- * @param notifFilePath The file path in String
- * @return A JsonNotificationData instance
- * @throws IOException in case of the file is not readable or not accessible
- */
- public static JsonStatusData instantiateNotifFromJsonFile(String notifFilePath) throws IOException {
-
- InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(notifFilePath + "status-structure.json");
-
- //String fileLocation = System.getProperty("mso.config.path") + "notif-structure.json";
-
- //String source = fileLocation;
- //InputStream is = IOUtils.toInputStream(source, "UTF-8");
-
- //String myString = IOUtils.toString(is, "UTF-8");
-
-
- //System.out.println(myString);
-
- if (is == null) {
- //throw new FileExistsException("Resource Path does not exist: "+notifFilePath);
- }
- return mapper.readValue(is, JsonStatusData.class);
- }
-
- @SuppressWarnings("unused")
- @JsonAnySetter
- public final void setAttribute(String attrName, Object attrValue) {
- if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) {
- this.attributesMap.put(attrName,attrValue);
- }
- }
-
+
+ @JsonIgnore
+ private static ObjectMapper mapper = new ObjectMapper();
+
+ @JsonIgnore
+ private Map<String, Object> attributesMap = new HashMap<>();
+
+ public JsonStatusData() {
+
+ }
+
+ @Override
+ public String getErrorReason() {
+ return "MSO FAILURE";
+ }
+
+ @Override
+ public String getDistributionID() {
+ // return (String)this.attributesMap.get("distributionID");
+ return "35120a87-1f82-4276-9735-f6de5a244d65";
+ }
+
+ @Override
+ public String getConsumerID() {
+ // return (String)this.attributesMap.get("consumerID");
+ return "mso.123456";
+ }
+
+ @Override
+ public String getComponentName() {
+ // return (String)this.attributesMap.get("componentName");
+ return "SDN-C";
+ }
+
+ @Override
+ public Long getTimestamp() {
+ // return (String)this.attributesMap.get("timestamp");
+ return null;
+ }
+
+ @Override
+ public String getArtifactURL() {
+ // return (String)this.attributesMap.get("artifactURL");
+ return "/sdc/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml";
+ }
+
+ @Override
+ public DistributionStatusEnum getStatus() {
+ // return (DistributionStatusEnum)this.attributesMap.get(DistributionStatusEnum.DEPLOY_OK);
+ return DistributionStatusEnum.COMPONENT_DONE_OK;
+ }
+
+ /**
+ * Method instantiate a INotificationData implementation from a JSON file.
+ *
+ * @param notifFilePath The file path in String
+ * @return A JsonNotificationData instance
+ * @throws IOException in case of the file is not readable or not accessible
+ */
+ public static JsonStatusData instantiateNotifFromJsonFile(String notifFilePath) throws IOException {
+
+ InputStream is = Thread.currentThread().getContextClassLoader()
+ .getResourceAsStream(notifFilePath + "status-structure.json");
+
+ // String fileLocation = System.getProperty("mso.config.path") + "notif-structure.json";
+
+ // String source = fileLocation;
+ // InputStream is = IOUtils.toInputStream(source, "UTF-8");
+
+ // String myString = IOUtils.toString(is, "UTF-8");
+
+
+ // System.out.println(myString);
+
+ if (is == null) {
+ // throw new FileExistsException("Resource Path does not exist: "+notifFilePath);
+ }
+ return mapper.readValue(is, JsonStatusData.class);
+ }
+
+ @SuppressWarnings("unused")
+ @JsonAnySetter
+ public final void setAttribute(String attrName, Object attrValue) {
+ if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) {
+ this.attributesMap.put(attrName, attrValue);
+ }
+ }
+
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java
index 9202559868..f4d3e5ce48 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java
@@ -23,74 +23,72 @@ package org.onap.so.asdc.client.test.emulators;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.onap.so.asdc.installer.IVfModuleData;
-
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public class JsonVfModuleMetaData implements IVfModuleData {
- @JsonProperty("artifacts")
- private List<String> artifacts;
- @JsonProperty("properties")
- //private List<Map<String, Object>> properties = new ArrayList<>();
- private Map<String,String> properties = new HashMap<>();
-
- public Map<String, String> getProperties() {
- return properties;
- }
-
- @JsonIgnore
- private Map<String,Object> attributesMap = new HashMap<>();
-
- @Override
- public List<String> getArtifacts() {
- return artifacts;
- }
-
- @Override
- public String getVfModuleModelDescription() {
- return (String)attributesMap.get("vfModuleModelDescription");
- }
-
- @Override
- public String getVfModuleModelInvariantUUID() {
- return (String)attributesMap.get("vfModuleModelInvariantUUID");
- }
-
- @Override
- public String getVfModuleModelCustomizationUUID() {
- return (String)attributesMap.get("vfModuleModelCustomizationUUID");
- }
-
- @Override
- public String getVfModuleModelName() {
- return (String)attributesMap.get("vfModuleModelName");
- }
-
- @Override
- public String getVfModuleModelUUID() {
- return (String)attributesMap.get("vfModuleModelUUID");
- }
-
- @Override
- public String getVfModuleModelVersion() {
- return (String)attributesMap.get("vfModuleModelVersion");
- }
-
- @Override
- public boolean isBase() {
- return (boolean)attributesMap.get("isBase");
- }
-
- @SuppressWarnings("unused")
- @JsonAnySetter
- public final void setAttribute(String attrName, Object attrValue) {
- if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) {
- this.attributesMap.put(attrName,attrValue);
- }
- }
+ @JsonProperty("artifacts")
+ private List<String> artifacts;
+ @JsonProperty("properties")
+ // private List<Map<String, Object>> properties = new ArrayList<>();
+ private Map<String, String> properties = new HashMap<>();
+
+ public Map<String, String> getProperties() {
+ return properties;
+ }
+
+ @JsonIgnore
+ private Map<String, Object> attributesMap = new HashMap<>();
+
+ @Override
+ public List<String> getArtifacts() {
+ return artifacts;
+ }
+
+ @Override
+ public String getVfModuleModelDescription() {
+ return (String) attributesMap.get("vfModuleModelDescription");
+ }
+
+ @Override
+ public String getVfModuleModelInvariantUUID() {
+ return (String) attributesMap.get("vfModuleModelInvariantUUID");
+ }
+
+ @Override
+ public String getVfModuleModelCustomizationUUID() {
+ return (String) attributesMap.get("vfModuleModelCustomizationUUID");
+ }
+
+ @Override
+ public String getVfModuleModelName() {
+ return (String) attributesMap.get("vfModuleModelName");
+ }
+
+ @Override
+ public String getVfModuleModelUUID() {
+ return (String) attributesMap.get("vfModuleModelUUID");
+ }
+
+ @Override
+ public String getVfModuleModelVersion() {
+ return (String) attributesMap.get("vfModuleModelVersion");
+ }
+
+ @Override
+ public boolean isBase() {
+ return (boolean) attributesMap.get("isBase");
+ }
+
+ @SuppressWarnings("unused")
+ @JsonAnySetter
+ public final void setAttribute(String attrName, Object attrValue) {
+ if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) {
+ this.attributesMap.put(attrName, attrValue);
+ }
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java
index 9462cc85d8..f8d7bb09f5 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java
@@ -22,192 +22,192 @@ package org.onap.so.asdc.client.test.emulators;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.api.notification.INotificationData;
import org.onap.sdc.api.notification.IResourceInstance;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
@Component
-@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
+@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE,
+ setterVisibility = Visibility.NONE)
public class NotificationDataImpl implements INotificationData {
- @JsonProperty("distributionID")
- private String distributionID;
- @JsonProperty("serviceName")
- private String serviceName;
- @JsonProperty("serviceVersion")
- private String serviceVersion;
- @JsonProperty("serviceUUID")
- private String serviceUUID;
- @JsonProperty("serviceDescription")
- private String serviceDescription;
- @JsonProperty("serviceInvariantUUID")
- private String serviceInvariantUUID;
- @JsonProperty("resources")
- private List<ResourceInfoImpl> resources;
- @JsonProperty("serviceArtifacts")
- private List<ArtifactInfoImpl> serviceArtifacts;
- @JsonProperty("workloadContext")
- private String workloadContext;
-
- @Override
- public String getDistributionID() {
- return distributionID;
- }
-
- @Override
- public String getServiceName() {
- return serviceName;
- }
-
- @Override
- public String getServiceVersion() {
- return serviceVersion;
- }
-
- @Override
- public String getServiceUUID() {
- return serviceUUID;
- }
-
- public void setDistributionID(String distributionID) {
- this.distributionID = distributionID;
- }
-
- public void setServiceName(String serviceName) {
- this.serviceName = serviceName;
- }
-
- public void setServiceVersion(String serviceVersion) {
- this.serviceVersion = serviceVersion;
- }
-
- public void setServiceUUID(String serviceUUID) {
- this.serviceUUID = serviceUUID;
- }
-
-
-
- public String getServiceDescription() {
- return serviceDescription;
- }
-
- public void setServiceDescription(String serviceDescription) {
- this.serviceDescription = serviceDescription;
- }
-
- @Override
- public String getWorkloadContext() {
- return workloadContext;
- }
-
- @Override
- public void setWorkloadContext(String workloadContext) {
- this.workloadContext = workloadContext;
- }
-
- @Override
- public String toString() {
- return "NotificationDataImpl [distributionID=" + distributionID + ", serviceName=" + serviceName
- + ", serviceVersion=" + serviceVersion + ", serviceUUID=" + serviceUUID + ", serviceDescription="
- + serviceDescription + ", serviceInvariantUUID=" + serviceInvariantUUID + ", resources=" + resources
- + ", serviceArtifacts=" + serviceArtifacts + ", workloadContext=" + workloadContext + "]";
- }
-
- @Override
- public List<IResourceInstance> getResources() {
- List<IResourceInstance> ret = new ArrayList<IResourceInstance>();
- if( resources != null ){
- ret.addAll(resources);
- }
- return ret;
- }
-
- public void setResources(List<ResourceInfoImpl> resources){
- this.resources = resources;
- }
-
- public List<ResourceInfoImpl> getResourcesImpl(){
- return resources;
- }
-
- List<ArtifactInfoImpl> getServiceArtifactsImpl(){
- return serviceArtifacts;
- }
-
- @Override
- public List<IArtifactInfo> getServiceArtifacts() {
- List<IArtifactInfo> temp = new ArrayList<IArtifactInfo>();
- if( serviceArtifacts != null ){
- temp.addAll(serviceArtifacts);
- }
- return temp;
- }
-
- public void setServiceArtifacts(List<ArtifactInfoImpl> relevantServiceArtifacts) {
- serviceArtifacts = relevantServiceArtifacts;
-
- }
-
- @Override
- public String getServiceInvariantUUID() {
- return serviceInvariantUUID;
- }
-
-
- public void setServiceInvariantUUID(String serviceInvariantUUID) {
- this.serviceInvariantUUID = serviceInvariantUUID;
- }
- @Override
- public IArtifactInfo getArtifactMetadataByUUID(String artifactUUID){
- IArtifactInfo ret = findArtifactInfoByUUID(artifactUUID, serviceArtifacts);
- if( ret == null && resources != null ){
- for( ResourceInfoImpl currResourceInstance : resources ){
- ret = findArtifactInfoByUUID(artifactUUID, currResourceInstance.getArtifactsImpl());
- if( ret != null ){
- break;
- }
- }
- }
- return ret;
-
- }
-
- private IArtifactInfo findArtifactInfoByUUID(String artifactUUID, List<ArtifactInfoImpl> listToCheck) {
- IArtifactInfo ret = null;
- if( listToCheck != null ){
- for(IArtifactInfo curr: listToCheck ){
- if(curr.getArtifactUUID().equals(artifactUUID) ){
- ret = curr;
- break;
- }
- }
- }
- return ret;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof NotificationDataImpl)) {
- return false;
- }
- NotificationDataImpl castOther = (NotificationDataImpl) other;
- return new EqualsBuilder().append(serviceUUID, castOther.serviceUUID)
- .append(serviceVersion, castOther.serviceVersion).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(distributionID).append(serviceName).append(serviceVersion)
- .append(serviceUUID).append(serviceDescription).append(serviceInvariantUUID).append(resources)
- .append(serviceArtifacts).append(workloadContext).toHashCode();
- }
+ @JsonProperty("distributionID")
+ private String distributionID;
+ @JsonProperty("serviceName")
+ private String serviceName;
+ @JsonProperty("serviceVersion")
+ private String serviceVersion;
+ @JsonProperty("serviceUUID")
+ private String serviceUUID;
+ @JsonProperty("serviceDescription")
+ private String serviceDescription;
+ @JsonProperty("serviceInvariantUUID")
+ private String serviceInvariantUUID;
+ @JsonProperty("resources")
+ private List<ResourceInfoImpl> resources;
+ @JsonProperty("serviceArtifacts")
+ private List<ArtifactInfoImpl> serviceArtifacts;
+ @JsonProperty("workloadContext")
+ private String workloadContext;
+
+ @Override
+ public String getDistributionID() {
+ return distributionID;
+ }
+
+ @Override
+ public String getServiceName() {
+ return serviceName;
+ }
+
+ @Override
+ public String getServiceVersion() {
+ return serviceVersion;
+ }
+
+ @Override
+ public String getServiceUUID() {
+ return serviceUUID;
+ }
+
+ public void setDistributionID(String distributionID) {
+ this.distributionID = distributionID;
+ }
+
+ public void setServiceName(String serviceName) {
+ this.serviceName = serviceName;
+ }
+
+ public void setServiceVersion(String serviceVersion) {
+ this.serviceVersion = serviceVersion;
+ }
+
+ public void setServiceUUID(String serviceUUID) {
+ this.serviceUUID = serviceUUID;
+ }
+
+
+
+ public String getServiceDescription() {
+ return serviceDescription;
+ }
+
+ public void setServiceDescription(String serviceDescription) {
+ this.serviceDescription = serviceDescription;
+ }
+
+ @Override
+ public String getWorkloadContext() {
+ return workloadContext;
+ }
+
+ @Override
+ public void setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
+
+ @Override
+ public String toString() {
+ return "NotificationDataImpl [distributionID=" + distributionID + ", serviceName=" + serviceName
+ + ", serviceVersion=" + serviceVersion + ", serviceUUID=" + serviceUUID + ", serviceDescription="
+ + serviceDescription + ", serviceInvariantUUID=" + serviceInvariantUUID + ", resources=" + resources
+ + ", serviceArtifacts=" + serviceArtifacts + ", workloadContext=" + workloadContext + "]";
+ }
+
+ @Override
+ public List<IResourceInstance> getResources() {
+ List<IResourceInstance> ret = new ArrayList<IResourceInstance>();
+ if (resources != null) {
+ ret.addAll(resources);
+ }
+ return ret;
+ }
+
+ public void setResources(List<ResourceInfoImpl> resources) {
+ this.resources = resources;
+ }
+
+ public List<ResourceInfoImpl> getResourcesImpl() {
+ return resources;
+ }
+
+ List<ArtifactInfoImpl> getServiceArtifactsImpl() {
+ return serviceArtifacts;
+ }
+
+ @Override
+ public List<IArtifactInfo> getServiceArtifacts() {
+ List<IArtifactInfo> temp = new ArrayList<IArtifactInfo>();
+ if (serviceArtifacts != null) {
+ temp.addAll(serviceArtifacts);
+ }
+ return temp;
+ }
+
+ public void setServiceArtifacts(List<ArtifactInfoImpl> relevantServiceArtifacts) {
+ serviceArtifacts = relevantServiceArtifacts;
+
+ }
+
+ @Override
+ public String getServiceInvariantUUID() {
+ return serviceInvariantUUID;
+ }
+
+
+ public void setServiceInvariantUUID(String serviceInvariantUUID) {
+ this.serviceInvariantUUID = serviceInvariantUUID;
+ }
+
+ @Override
+ public IArtifactInfo getArtifactMetadataByUUID(String artifactUUID) {
+ IArtifactInfo ret = findArtifactInfoByUUID(artifactUUID, serviceArtifacts);
+ if (ret == null && resources != null) {
+ for (ResourceInfoImpl currResourceInstance : resources) {
+ ret = findArtifactInfoByUUID(artifactUUID, currResourceInstance.getArtifactsImpl());
+ if (ret != null) {
+ break;
+ }
+ }
+ }
+ return ret;
+
+ }
+
+ private IArtifactInfo findArtifactInfoByUUID(String artifactUUID, List<ArtifactInfoImpl> listToCheck) {
+ IArtifactInfo ret = null;
+ if (listToCheck != null) {
+ for (IArtifactInfo curr : listToCheck) {
+ if (curr.getArtifactUUID().equals(artifactUUID)) {
+ ret = curr;
+ break;
+ }
+ }
+ }
+ return ret;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof NotificationDataImpl)) {
+ return false;
+ }
+ NotificationDataImpl castOther = (NotificationDataImpl) other;
+ return new EqualsBuilder().append(serviceUUID, castOther.serviceUUID)
+ .append(serviceVersion, castOther.serviceVersion).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(distributionID).append(serviceName).append(serviceVersion)
+ .append(serviceUUID).append(serviceDescription).append(serviceInvariantUUID).append(resources)
+ .append(serviceArtifacts).append(workloadContext).toHashCode();
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java
index 9103ae132e..91597611fd 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java
@@ -22,159 +22,159 @@ package org.onap.so.asdc.client.test.emulators;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.api.notification.IResourceInstance;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
-public class ResourceInfoImpl implements IResourceInstance{
- public ResourceInfoImpl (){}
- private String resourceInstanceName;
- private String resourceCustomizationUUID;
- private String resourceName;
- private String resourceVersion;
- private String resourceType;
- private String resourceUUID;
- private String resourceInvariantUUID;
- private String category;
- private String subcategory;
- private List<ArtifactInfoImpl> artifacts;
-
- private ResourceInfoImpl(IResourceInstance resourceInstance){
- resourceInstanceName = resourceInstance.getResourceInstanceName();
- resourceCustomizationUUID = resourceInstance.getResourceCustomizationUUID();
- resourceName = resourceInstance.getResourceName();
- resourceVersion = resourceInstance.getResourceVersion();
- resourceType = resourceInstance.getResourceType();
- resourceUUID = resourceInstance.getResourceUUID();
- resourceInvariantUUID = resourceInstance.getResourceInvariantUUID();
- category = resourceInstance.getCategory();
- subcategory = resourceInstance.getSubcategory();
- artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(resourceInstance.getArtifacts());
- }
-
- public static List<ResourceInfoImpl> convertToJsonContainer(List<IResourceInstance> resources){
- List<ResourceInfoImpl> buildResources = new ArrayList<ResourceInfoImpl>();
- if( resources != null ){
- for( IResourceInstance resourceInstance : resources ){
- buildResources.add(new ResourceInfoImpl(resourceInstance));
- }
- }
- return buildResources;
- }
-
- @Override
- public String getResourceInstanceName() {
- return resourceInstanceName;
- }
-
- public void setResourceInstanceName(String resourceInstanceName) {
- this.resourceInstanceName = resourceInstanceName;
- }
-
- @Override
- public String getResourceName() {
- return resourceName;
- }
-
- public void setResourceName(String resourceName) {
- this.resourceName = resourceName;
- }
-
- @Override
- public String getResourceVersion() {
- return resourceVersion;
- }
-
- public void setResourceVersion(String resourceVersion) {
- this.resourceVersion = resourceVersion;
- }
-
- @Override
- public String getResourceType() {
- return resourceType;
- }
-
- public void setResoucreType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- @Override
- public String getResourceUUID() {
- return resourceUUID;
- }
-
- public void setResourceUUID(String resourceUUID) {
- this.resourceUUID = resourceUUID;
- }
-
- @Override
- public List<IArtifactInfo> getArtifacts() {
- List<IArtifactInfo> temp = new ArrayList<IArtifactInfo>();
- if( artifacts != null ){
- temp.addAll(artifacts);
- }
- return temp;
- }
-
- public void setArtifacts(List<ArtifactInfoImpl> artifacts) {
- this.artifacts = artifacts;
- }
-
- @JsonIgnore
- public List<ArtifactInfoImpl> getArtifactsImpl() {
- return artifacts;
- }
-
- @Override
- public String getResourceInvariantUUID() {
- return resourceInvariantUUID;
- }
-
- public void setResourceInvariantUUID(String resourceInvariantUUID) {
- this.resourceInvariantUUID = resourceInvariantUUID;
- }
- public String getResourceCustomizationUUID() {
- return resourceCustomizationUUID;
- }
-
- public void setResourceCustomizationUUID(String resourceCustomizationUUID) {
- this.resourceCustomizationUUID = resourceCustomizationUUID;
- }
-
- 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 boolean equals(final Object other) {
- if (!(other instanceof ResourceInfoImpl)) {
- return false;
- }
- ResourceInfoImpl castOther = (ResourceInfoImpl) other;
- return new EqualsBuilder().append(resourceUUID, castOther.resourceUUID)
- .append(resourceVersion, castOther.resourceVersion).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(resourceInstanceName).append(resourceCustomizationUUID).append(resourceName)
- .append(resourceVersion).append(resourceType).append(resourceUUID).append(resourceInvariantUUID)
- .append(category).append(subcategory).append(artifacts).toHashCode();
- }
+public class ResourceInfoImpl implements IResourceInstance {
+ public ResourceInfoImpl() {}
+
+ private String resourceInstanceName;
+ private String resourceCustomizationUUID;
+ private String resourceName;
+ private String resourceVersion;
+ private String resourceType;
+ private String resourceUUID;
+ private String resourceInvariantUUID;
+ private String category;
+ private String subcategory;
+ private List<ArtifactInfoImpl> artifacts;
+
+ private ResourceInfoImpl(IResourceInstance resourceInstance) {
+ resourceInstanceName = resourceInstance.getResourceInstanceName();
+ resourceCustomizationUUID = resourceInstance.getResourceCustomizationUUID();
+ resourceName = resourceInstance.getResourceName();
+ resourceVersion = resourceInstance.getResourceVersion();
+ resourceType = resourceInstance.getResourceType();
+ resourceUUID = resourceInstance.getResourceUUID();
+ resourceInvariantUUID = resourceInstance.getResourceInvariantUUID();
+ category = resourceInstance.getCategory();
+ subcategory = resourceInstance.getSubcategory();
+ artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(resourceInstance.getArtifacts());
+ }
+
+ public static List<ResourceInfoImpl> convertToJsonContainer(List<IResourceInstance> resources) {
+ List<ResourceInfoImpl> buildResources = new ArrayList<ResourceInfoImpl>();
+ if (resources != null) {
+ for (IResourceInstance resourceInstance : resources) {
+ buildResources.add(new ResourceInfoImpl(resourceInstance));
+ }
+ }
+ return buildResources;
+ }
+
+ @Override
+ public String getResourceInstanceName() {
+ return resourceInstanceName;
+ }
+
+ public void setResourceInstanceName(String resourceInstanceName) {
+ this.resourceInstanceName = resourceInstanceName;
+ }
+
+ @Override
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
+
+ @Override
+ public String getResourceVersion() {
+ return resourceVersion;
+ }
+
+ public void setResourceVersion(String resourceVersion) {
+ this.resourceVersion = resourceVersion;
+ }
+
+ @Override
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResoucreType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ @Override
+ public String getResourceUUID() {
+ return resourceUUID;
+ }
+
+ public void setResourceUUID(String resourceUUID) {
+ this.resourceUUID = resourceUUID;
+ }
+
+ @Override
+ public List<IArtifactInfo> getArtifacts() {
+ List<IArtifactInfo> temp = new ArrayList<IArtifactInfo>();
+ if (artifacts != null) {
+ temp.addAll(artifacts);
+ }
+ return temp;
+ }
+
+ public void setArtifacts(List<ArtifactInfoImpl> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ @JsonIgnore
+ public List<ArtifactInfoImpl> getArtifactsImpl() {
+ return artifacts;
+ }
+
+ @Override
+ public String getResourceInvariantUUID() {
+ return resourceInvariantUUID;
+ }
+
+ public void setResourceInvariantUUID(String resourceInvariantUUID) {
+ this.resourceInvariantUUID = resourceInvariantUUID;
+ }
+
+ public String getResourceCustomizationUUID() {
+ return resourceCustomizationUUID;
+ }
+
+ public void setResourceCustomizationUUID(String resourceCustomizationUUID) {
+ this.resourceCustomizationUUID = resourceCustomizationUUID;
+ }
+
+ 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 boolean equals(final Object other) {
+ if (!(other instanceof ResourceInfoImpl)) {
+ return false;
+ }
+ ResourceInfoImpl castOther = (ResourceInfoImpl) other;
+ return new EqualsBuilder().append(resourceUUID, castOther.resourceUUID)
+ .append(resourceVersion, castOther.resourceVersion).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(resourceInstanceName).append(resourceCustomizationUUID).append(resourceName)
+ .append(resourceVersion).append(resourceType).append(resourceUUID).append(resourceInvariantUUID)
+ .append(category).append(subcategory).append(artifacts).toHashCode();
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java
index e9e5372d98..14ea0cde4b 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java
@@ -24,7 +24,6 @@ package org.onap.so.asdc.client.test.rest;
import java.io.IOException;
-
import javax.transaction.Transactional;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
@@ -32,7 +31,6 @@ import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.onap.so.asdc.client.ASDCController;
import org.onap.so.asdc.client.exceptions.ASDCControllerException;
import org.onap.so.asdc.client.exceptions.ASDCParametersException;
@@ -49,8 +47,9 @@ import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
/**
- * This is a TEST only rest interface. It is not used in production, it is used to aid in testing the ASDC service on jboss without the need to be connected
- * to the ASDC service broker. It starts the test at the treatNotification step and simulates both the notification step as well as the artifact download step.
+ * This is a TEST only rest interface. It is not used in production, it is used to aid in testing the ASDC service on
+ * jboss without the need to be connected to the ASDC service broker. It starts the test at the treatNotification step
+ * and simulates both the notification step as well as the artifact download step.
*
* i.e. http://localhost:8080/asdc/treatNotification/v1
*
@@ -65,57 +64,58 @@ import org.springframework.stereotype.Component;
@Profile("test")
public class ASDCRestInterface {
- private static DistributionClientEmulator distributionClientEmulator;
-
- private static JsonStatusData statusData;
-
- private static final Logger logger = LoggerFactory.getLogger(ASDCRestInterface.class );
-
- @Autowired
- private ASDCController asdcController;
-
- @Autowired
- private ToscaResourceInstaller toscaInstaller;
+ private static DistributionClientEmulator distributionClientEmulator;
+
+ private static JsonStatusData statusData;
+
+ private static final Logger logger = LoggerFactory.getLogger(ASDCRestInterface.class);
+
+ @Autowired
+ private ASDCController asdcController;
+
+ @Autowired
+ private ToscaResourceInstaller toscaInstaller;
+
+ @POST
+ @Path("/treatNotification/v1")
+ @Produces(MediaType.APPLICATION_JSON)
+ @Transactional
+ public Response invokeASDCService(NotificationDataImpl request,
+ @HeaderParam("resource-location") String resourceLocation)
+ throws ASDCControllerException, ASDCParametersException, IOException {
+ distributionClientEmulator = new DistributionClientEmulator(resourceLocation);
+
+ asdcController.setControllerName("asdc-controller1");
+ asdcController.setDistributionClient(distributionClientEmulator);
+ asdcController.initASDC();
+ asdcController.treatNotification(request);
+ asdcController.closeASDC();
+ return Response.status(200).build();
+ }
+
+ @POST
+ @Path("/statusData/v1")
+ @Produces(MediaType.APPLICATION_JSON)
+ @Transactional
+ public Response invokeASDCStatusData(String request) {
+
+ try {
+ distributionClientEmulator = new DistributionClientEmulator("resource-examples/");
+ statusData = JsonStatusData.instantiateNotifFromJsonFile("resource-examples/");
- @POST
- @Path("/treatNotification/v1")
- @Produces(MediaType.APPLICATION_JSON)
- @Transactional
- public Response invokeASDCService(NotificationDataImpl request, @HeaderParam("resource-location") String resourceLocation)
- throws ASDCControllerException, ASDCParametersException, IOException {
- distributionClientEmulator = new DistributionClientEmulator(resourceLocation);
-
- asdcController.setControllerName("asdc-controller1");
- asdcController.setDistributionClient(distributionClientEmulator);
- asdcController.initASDC();
- asdcController.treatNotification(request);
- asdcController.closeASDC();
- return Response.status(200).build();
- }
-
- @POST
- @Path("/statusData/v1")
- @Produces(MediaType.APPLICATION_JSON)
- @Transactional
- public Response invokeASDCStatusData(String request) {
-
- try{
- distributionClientEmulator = new DistributionClientEmulator("resource-examples/");
- statusData = JsonStatusData.instantiateNotifFromJsonFile("resource-examples/");
-
- ASDCController asdcController = new ASDCController("asdc-controller1", distributionClientEmulator);
- asdcController.initASDC();
- toscaInstaller.installTheComponentStatus(statusData);
- asdcController.closeASDC();
- }catch(Exception e){
- logger.info("Error caught " + e.getMessage());
- logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION.toString(),
- "Exception caught during ASDCRestInterface", "ASDC", "invokeASDCService",
- ErrorCode.BusinessProcesssError.getValue(), "Exception in invokeASDCService", e);
- }
- logger.info("ASDC Updates are complete");
- logger.info("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC.toString(), statusData.getDistributionID(), "ASDC",
- "ASDC Updates Are Complete");
- return null;
- }
+ ASDCController asdcController = new ASDCController("asdc-controller1", distributionClientEmulator);
+ asdcController.initASDC();
+ toscaInstaller.installTheComponentStatus(statusData);
+ asdcController.closeASDC();
+ } catch (Exception e) {
+ logger.info("Error caught " + e.getMessage());
+ logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION.toString(),
+ "Exception caught during ASDCRestInterface", "ASDC", "invokeASDCService",
+ ErrorCode.BusinessProcesssError.getValue(), "Exception in invokeASDCService", e);
+ }
+ logger.info("ASDC Updates are complete");
+ logger.info("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC.toString(), statusData.getDistributionID(),
+ "ASDC", "ASDC Updates Are Complete");
+ return null;
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java
index 1e227aefa1..043055e23c 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java
@@ -25,7 +25,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-
import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.api.notification.IResourceInstance;
import org.onap.so.asdc.client.ASDCConfiguration;
@@ -35,177 +34,184 @@ import org.onap.so.asdc.client.ASDCConfiguration;
*/
public class ASDCElementInfo {
- /**
- * A default, empty instance used in case a source element was not correctly provided.
- */
- public static final ASDCElementInfo EMPTY_INSTANCE = new ASDCElementInfo();
-
- /**
- * Used to define the other possible ASDC Element types (usually in addition to existing artifact types, etc.).<br/>
- * <br/>
- * Possible types allowed:<br/>
- * <ul>
- * <li>{@link ASDCElementTypeEnum#VNF_RESOURCE}</li>
- * <ul>
- */
- public static enum ASDCElementTypeEnum {
- /**
- * The type VNF_RESOURCE. Represents a VNF_RESOURCE element.
- */
- VNF_RESOURCE
- };
-
- /**
- * The map of element information fields useful for logging. The complete contents of this list will be concatenated.
- */
- private final Map<String, String> elementInfoMap = new HashMap<>();
-
- /**
- * The type of this element.
- */
- private final String type;
-
- private ASDCElementInfo () {
- // Private parameterless constructor. Not visible, only used for EMPTY_INSTANCE.
- this.type = "";
- }
-
- /**
- * Artifact-type based constructor. Requires a valid artifact type.
- * @param artifactType The artifact type
- */
- private ASDCElementInfo (String artifactType) {
- // We need the exact type name here...
- this.type = artifactType;
- }
-
- /**
- * 'Other element type'-based constructor. Requires a valid element type.
- * @param elementType An ASDCElementTypeEnum entry. This will usually contain enumerated types not in the existing
- */
- private ASDCElementInfo (ASDCElementTypeEnum elementType) {
- // We need the exact type name here...
- this.type = elementType.name();
- }
-
- /**
- * Add an information entry (name, UUID, etc.) from an artifact/resource/..., once a at time.
- *
- * @param key The key (name) of the information entry (Artifact UUID, Resource Name, etc.)
- * @param value The value bound to the information entry.
- */
- public final void addElementInfo(String key, String value) {
- if ((key != null) && (value != null)) {
- this.getElementInfoMap().put(key, value);
- }
- }
-
- /**
- * Returns an aggregated, formatted list of the expected details about an ASDC element.
- * (non-Javadoc)
- * @return An aggregated list of element information entries, comma-separated.
- * @see java.lang.Object#toString()
- */
- @Override
- public final String toString() {
- StringBuilder sb = new StringBuilder();
- List<String> aggregatedElements = new ArrayList<>();
- for (Entry<String, String> entry : this.getElementInfoMap().entrySet()) {
- aggregatedElements.add(entry.getKey() + ": " + entry.getValue());
- }
- sb.append(aggregatedElements.size() > 0 ? aggregatedElements.get(0) : "");
- if (aggregatedElements.size() > 1) {
- for (int i = 1; i < aggregatedElements.size(); ++i) {
- sb.append (", ");
- sb.append(aggregatedElements.get(i));
- }
- }
- return sb.toString();
- }
-
- /**
- * The type that was defined at creation time. This is typically VNF_RESOURCE, VF_MODULE_METADATA, HEAT_ENV, etc.
- * @return The type of this element information type. This will usually be either an ArtifactTypeEnum entry name or an ASDCElementTypeEnum entry name.
- * @see ASDCElementInfo.ASDCElementTypeEnum
- */
- public String getType() {
- return type;
- }
-
- /**
- * Provides the map of all element information entries for this type.
- * @return A map of all element information entries which will be used by the toString() method.
- * @see ASDCElementInfo#toString()
- */
- protected Map<String, String> getElementInfoMap() {
- return elementInfoMap;
- }
-
- /**
- * Create an ASDCElementInfo object from a VNF Resource.<br/>
- * <br/>
- * <b>Used information:</b><br/>
- * <ul>
- * <li>Resource Instance Name</li>
- * <li>Resource Instance UUID</li>
- * </ul>
- *
- * @param vfResourceStructure The VfResourceStructure to use as source of information (see {@link VfResourceStructure}).
- * @return an ASDCElementInfo using the information held in the VNF Resource.
- */
- public static final ASDCElementInfo createElementFromVfResourceStructure (VfResourceStructure vfResourceStructure) {
- if (vfResourceStructure == null) {
- return EMPTY_INSTANCE;
- }
- ASDCElementInfo elementInfo = new ASDCElementInfo(ASDCElementTypeEnum.VNF_RESOURCE);
- IResourceInstance resourceInstance = vfResourceStructure.getResourceInstance();
- elementInfo.addElementInfo("Resource Instance Name", resourceInstance.getResourceInstanceName());
- elementInfo.addElementInfo("Resource Instance Invariant UUID", resourceInstance.getResourceInvariantUUID());
- return elementInfo;
- }
-
- /**
- * Create an ASDCElementInfo object from a VF Module.<br/>
- * <br/>
- * <b>Used information:</b><br/>
- * <ul>
- * <li>Module Model Name</li>
- * <li>Module Model UUID</li>
- * </ul>
- *
- * @param vfModuleStructure The VfModuleStructure to use as source of information (see {@link VfModuleStructure}).
- * @return an ASDCElementInfo using the information held in the VF Module.
- */
- public static final ASDCElementInfo createElementFromVfModuleStructure (VfModuleStructure vfModuleStructure) {
- if (vfModuleStructure == null) {
- return EMPTY_INSTANCE;
- }
- ASDCElementInfo elementInfo = new ASDCElementInfo(ASDCConfiguration.VF_MODULES_METADATA);
- IVfModuleData moduleMetadata = vfModuleStructure.getVfModuleMetadata();
- elementInfo.addElementInfo("Module Model Name", moduleMetadata.getVfModuleModelName());
- elementInfo.addElementInfo("Module Model Invariant UUID", moduleMetadata.getVfModuleModelInvariantUUID());
- return elementInfo;
- }
-
- /**
- * Create an ASDCElementInfo object from an IArtfiactInfo instance.<br/>
- * <br/>
- * <b>Used information:</b><br/>
- * <ul>
- * <li>IArtifactInfo Name</li>
- * <li>IArtifactInfo UUID</li>
- * </ul>
- *
- * @param artifactInfo The VfModuleStructure to use as source of information (see {@link IArtifactInfo}).
- * @return an ASDCElementInfo using the information held in the IArtifactInfo instance.
- */
- public static final ASDCElementInfo createElementFromVfArtifactInfo (IArtifactInfo artifactInfo) {
- if (artifactInfo == null) {
- return EMPTY_INSTANCE;
- }
- ASDCElementInfo elementInfo = new ASDCElementInfo(artifactInfo.getArtifactType());
- elementInfo.addElementInfo(elementInfo.getType() + " Name", artifactInfo.getArtifactName());
- elementInfo.addElementInfo(elementInfo.getType() + " UUID", artifactInfo.getArtifactUUID());
- return elementInfo;
- }
+ /**
+ * A default, empty instance used in case a source element was not correctly provided.
+ */
+ public static final ASDCElementInfo EMPTY_INSTANCE = new ASDCElementInfo();
+
+ /**
+ * Used to define the other possible ASDC Element types (usually in addition to existing artifact types, etc.).<br/>
+ * <br/>
+ * Possible types allowed:<br/>
+ * <ul>
+ * <li>{@link ASDCElementTypeEnum#VNF_RESOURCE}</li>
+ * <ul>
+ */
+ public static enum ASDCElementTypeEnum {
+ /**
+ * The type VNF_RESOURCE. Represents a VNF_RESOURCE element.
+ */
+ VNF_RESOURCE
+ };
+
+ /**
+ * The map of element information fields useful for logging. The complete contents of this list will be
+ * concatenated.
+ */
+ private final Map<String, String> elementInfoMap = new HashMap<>();
+
+ /**
+ * The type of this element.
+ */
+ private final String type;
+
+ private ASDCElementInfo() {
+ // Private parameterless constructor. Not visible, only used for EMPTY_INSTANCE.
+ this.type = "";
+ }
+
+ /**
+ * Artifact-type based constructor. Requires a valid artifact type.
+ *
+ * @param artifactType The artifact type
+ */
+ private ASDCElementInfo(String artifactType) {
+ // We need the exact type name here...
+ this.type = artifactType;
+ }
+
+ /**
+ * 'Other element type'-based constructor. Requires a valid element type.
+ *
+ * @param elementType An ASDCElementTypeEnum entry. This will usually contain enumerated types not in the existing
+ */
+ private ASDCElementInfo(ASDCElementTypeEnum elementType) {
+ // We need the exact type name here...
+ this.type = elementType.name();
+ }
+
+ /**
+ * Add an information entry (name, UUID, etc.) from an artifact/resource/..., once a at time.
+ *
+ * @param key The key (name) of the information entry (Artifact UUID, Resource Name, etc.)
+ * @param value The value bound to the information entry.
+ */
+ public final void addElementInfo(String key, String value) {
+ if ((key != null) && (value != null)) {
+ this.getElementInfoMap().put(key, value);
+ }
+ }
+
+ /**
+ * Returns an aggregated, formatted list of the expected details about an ASDC element. (non-Javadoc)
+ *
+ * @return An aggregated list of element information entries, comma-separated.
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public final String toString() {
+ StringBuilder sb = new StringBuilder();
+ List<String> aggregatedElements = new ArrayList<>();
+ for (Entry<String, String> entry : this.getElementInfoMap().entrySet()) {
+ aggregatedElements.add(entry.getKey() + ": " + entry.getValue());
+ }
+ sb.append(aggregatedElements.size() > 0 ? aggregatedElements.get(0) : "");
+ if (aggregatedElements.size() > 1) {
+ for (int i = 1; i < aggregatedElements.size(); ++i) {
+ sb.append(", ");
+ sb.append(aggregatedElements.get(i));
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * The type that was defined at creation time. This is typically VNF_RESOURCE, VF_MODULE_METADATA, HEAT_ENV, etc.
+ *
+ * @return The type of this element information type. This will usually be either an ArtifactTypeEnum entry name or
+ * an ASDCElementTypeEnum entry name.
+ * @see ASDCElementInfo.ASDCElementTypeEnum
+ */
+ public String getType() {
+ return type;
+ }
+
+ /**
+ * Provides the map of all element information entries for this type.
+ *
+ * @return A map of all element information entries which will be used by the toString() method.
+ * @see ASDCElementInfo#toString()
+ */
+ protected Map<String, String> getElementInfoMap() {
+ return elementInfoMap;
+ }
+
+ /**
+ * Create an ASDCElementInfo object from a VNF Resource.<br/>
+ * <br/>
+ * <b>Used information:</b><br/>
+ * <ul>
+ * <li>Resource Instance Name</li>
+ * <li>Resource Instance UUID</li>
+ * </ul>
+ *
+ * @param vfResourceStructure The VfResourceStructure to use as source of information (see
+ * {@link VfResourceStructure}).
+ * @return an ASDCElementInfo using the information held in the VNF Resource.
+ */
+ public static final ASDCElementInfo createElementFromVfResourceStructure(VfResourceStructure vfResourceStructure) {
+ if (vfResourceStructure == null) {
+ return EMPTY_INSTANCE;
+ }
+ ASDCElementInfo elementInfo = new ASDCElementInfo(ASDCElementTypeEnum.VNF_RESOURCE);
+ IResourceInstance resourceInstance = vfResourceStructure.getResourceInstance();
+ elementInfo.addElementInfo("Resource Instance Name", resourceInstance.getResourceInstanceName());
+ elementInfo.addElementInfo("Resource Instance Invariant UUID", resourceInstance.getResourceInvariantUUID());
+ return elementInfo;
+ }
+
+ /**
+ * Create an ASDCElementInfo object from a VF Module.<br/>
+ * <br/>
+ * <b>Used information:</b><br/>
+ * <ul>
+ * <li>Module Model Name</li>
+ * <li>Module Model UUID</li>
+ * </ul>
+ *
+ * @param vfModuleStructure The VfModuleStructure to use as source of information (see {@link VfModuleStructure}).
+ * @return an ASDCElementInfo using the information held in the VF Module.
+ */
+ public static final ASDCElementInfo createElementFromVfModuleStructure(VfModuleStructure vfModuleStructure) {
+ if (vfModuleStructure == null) {
+ return EMPTY_INSTANCE;
+ }
+ ASDCElementInfo elementInfo = new ASDCElementInfo(ASDCConfiguration.VF_MODULES_METADATA);
+ IVfModuleData moduleMetadata = vfModuleStructure.getVfModuleMetadata();
+ elementInfo.addElementInfo("Module Model Name", moduleMetadata.getVfModuleModelName());
+ elementInfo.addElementInfo("Module Model Invariant UUID", moduleMetadata.getVfModuleModelInvariantUUID());
+ return elementInfo;
+ }
+
+ /**
+ * Create an ASDCElementInfo object from an IArtfiactInfo instance.<br/>
+ * <br/>
+ * <b>Used information:</b><br/>
+ * <ul>
+ * <li>IArtifactInfo Name</li>
+ * <li>IArtifactInfo UUID</li>
+ * </ul>
+ *
+ * @param artifactInfo The VfModuleStructure to use as source of information (see {@link IArtifactInfo}).
+ * @return an ASDCElementInfo using the information held in the IArtifactInfo instance.
+ */
+ public static final ASDCElementInfo createElementFromVfArtifactInfo(IArtifactInfo artifactInfo) {
+ if (artifactInfo == null) {
+ return EMPTY_INSTANCE;
+ }
+ ASDCElementInfo elementInfo = new ASDCElementInfo(artifactInfo.getArtifactType());
+ elementInfo.addElementInfo(elementInfo.getType() + " Name", artifactInfo.getArtifactName());
+ elementInfo.addElementInfo(elementInfo.getType() + " UUID", artifactInfo.getArtifactUUID());
+ return elementInfo;
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/BigDecimalVersion.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/BigDecimalVersion.java
index 1dd92eac7a..616afe03d0 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/BigDecimalVersion.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/BigDecimalVersion.java
@@ -24,39 +24,39 @@ package org.onap.so.asdc.installer;
import java.math.BigDecimal;
public class BigDecimalVersion {
-
- /**
+
+ /**
* This method truncates and convert the version String provided in the notification.
*
* @param version The version to check
* @return A BigDecimal value checked and truncated
*/
public static BigDecimal castAndCheckNotificationVersion(String version) {
- // Truncate the version if bad type
- String[] splitVersion = version.split("\\.");
- StringBuilder newVersion = new StringBuilder();
- if (splitVersion.length > 1) {
- newVersion.append(splitVersion[0]);
- newVersion.append(".");
- newVersion.append(splitVersion[1]);
- } else {
- return new BigDecimal(splitVersion[0]);
- }
-
- for (int i=2;i<splitVersion.length;i++) {
- newVersion.append(splitVersion[i]);
- }
-
- return new BigDecimal(newVersion.toString());
+ // Truncate the version if bad type
+ String[] splitVersion = version.split("\\.");
+ StringBuilder newVersion = new StringBuilder();
+ if (splitVersion.length > 1) {
+ newVersion.append(splitVersion[0]);
+ newVersion.append(".");
+ newVersion.append(splitVersion[1]);
+ } else {
+ return new BigDecimal(splitVersion[0]);
+ }
+
+ for (int i = 2; i < splitVersion.length; i++) {
+ newVersion.append(splitVersion[i]);
+ }
+
+ return new BigDecimal(newVersion.toString());
}
-
+
/**
* This method truncates and convert the version String provided in the notification.
*
* @param version The version to check
* @return A String value checked and truncated to Decimal format
*/
- public static String castAndCheckNotificationVersionToString (String version) {
- return castAndCheckNotificationVersion(version).toString();
+ public static String castAndCheckNotificationVersionToString(String version) {
+ return castAndCheckNotificationVersion(version).toString();
}
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/IArtifactOrchestrator.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/IArtifactOrchestrator.java
index ac43a66ffa..f396d80191 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/IArtifactOrchestrator.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/IArtifactOrchestrator.java
@@ -30,8 +30,10 @@ import org.onap.so.asdc.client.exceptions.ArtifactInstallerException;
public interface IArtifactOrchestrator {
- void installTheArtifact (INotificationData iNotif, IResourceInstance resource, IArtifactInfo artifact, IDistributionClientDownloadResult downloadResult) throws ArtifactInstallerException;
+ void installTheArtifact(INotificationData iNotif, IResourceInstance resource, IArtifactInfo artifact,
+ IDistributionClientDownloadResult downloadResult) throws ArtifactInstallerException;
- boolean isArtifactAlreadyDeployed (INotificationData iNotif,IResourceInstance resource,IArtifactInfo artifact) throws ArtifactInstallerException;
+ boolean isArtifactAlreadyDeployed(INotificationData iNotif, IResourceInstance resource, IArtifactInfo artifact)
+ throws ArtifactInstallerException;
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfModuleData.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfModuleData.java
index f9524de2a1..5751c2b33b 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfModuleData.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfModuleData.java
@@ -22,30 +22,30 @@ package org.onap.so.asdc.installer;
public interface IVfModuleData {
- // Method descriptor #4 ()Ljava/lang/String;
- public abstract java.lang.String getVfModuleModelName();
+ // Method descriptor #4 ()Ljava/lang/String;
+ public abstract java.lang.String getVfModuleModelName();
- // Method descriptor #4 ()Ljava/lang/String;
- public abstract java.lang.String getVfModuleModelInvariantUUID();
+ // Method descriptor #4 ()Ljava/lang/String;
+ public abstract java.lang.String getVfModuleModelInvariantUUID();
- // Method descriptor #4 ()Ljava/lang/String;
- public abstract java.lang.String getVfModuleModelCustomizationUUID();
+ // Method descriptor #4 ()Ljava/lang/String;
+ public abstract java.lang.String getVfModuleModelCustomizationUUID();
- // Method descriptor #4 ()Ljava/lang/String;
- public abstract java.lang.String getVfModuleModelVersion();
+ // Method descriptor #4 ()Ljava/lang/String;
+ public abstract java.lang.String getVfModuleModelVersion();
- // Method descriptor #4 ()Ljava/lang/String;
- public abstract java.lang.String getVfModuleModelUUID();
+ // Method descriptor #4 ()Ljava/lang/String;
+ public abstract java.lang.String getVfModuleModelUUID();
- // Method descriptor #4 ()Ljava/lang/String;
- public abstract java.lang.String getVfModuleModelDescription();
+ // Method descriptor #4 ()Ljava/lang/String;
+ public abstract java.lang.String getVfModuleModelDescription();
- // Method descriptor #10 ()Z
- public abstract boolean isBase();
+ // Method descriptor #10 ()Z
+ public abstract boolean isBase();
- // Method descriptor #12 ()Ljava/util/List;
- // Signature: ()Ljava/util/List<Ljava/lang/String;>;
- public abstract java.util.List<String> getArtifacts();
+ // Method descriptor #12 ()Ljava/util/List;
+ // Signature: ()Ljava/util/List<Ljava/lang/String;>;
+ public abstract java.util.List<String> getArtifacts();
- public abstract java.util.Map<String,String> getProperties();
+ public abstract java.util.Map<String, String> getProperties();
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfResourceInstaller.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfResourceInstaller.java
index 445b10b588..6a173df2f3 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfResourceInstaller.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/IVfResourceInstaller.java
@@ -26,7 +26,7 @@ import org.onap.so.asdc.client.exceptions.ArtifactInstallerException;
public interface IVfResourceInstaller {
- boolean isResourceAlreadyDeployed (VfResourceStructure vfResourceStructure) throws ArtifactInstallerException;
+ boolean isResourceAlreadyDeployed(VfResourceStructure vfResourceStructure) throws ArtifactInstallerException;
- public void installTheResource (VfResourceStructure vfResourceStructure) throws ArtifactInstallerException;
+ public void installTheResource(VfResourceStructure vfResourceStructure) throws ArtifactInstallerException;
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/PnfResourceStructure.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/PnfResourceStructure.java
index 1c1351b272..8aa9684426 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/PnfResourceStructure.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/PnfResourceStructure.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.asdc.installer;
@@ -39,7 +34,7 @@ public class PnfResourceStructure extends ResourceStructure {
@Override
public void addArtifactToStructure(IDistributionClient distributionClient, IArtifactInfo artifactinfo,
- IDistributionClientDownloadResult clientResult) throws UnsupportedEncodingException {
+ IDistributionClientDownloadResult clientResult) throws UnsupportedEncodingException {
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceStructure.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceStructure.java
index 53cc74f7e4..9965a05294 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceStructure.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceStructure.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.asdc.installer;
@@ -88,7 +83,7 @@ public abstract class ResourceStructure {
* @throws UnsupportedEncodingException
*/
public abstract void addArtifactToStructure(IDistributionClient distributionClient, IArtifactInfo artifactinfo,
- IDistributionClientDownloadResult clientResult) throws UnsupportedEncodingException;
+ IDistributionClientDownloadResult clientResult) throws UnsupportedEncodingException;
/**
* Prepare the resource for installation.
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceType.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceType.java
index 8d55f57dfa..7e5b7c905b 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceType.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceType.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.asdc.installer;
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java
index 3efc503fcb..749a397ee0 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java
@@ -25,7 +25,6 @@ package org.onap.so.asdc.installer;
import java.io.File;
import java.nio.file.Paths;
import java.util.List;
-
import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
@@ -59,450 +58,443 @@ import org.springframework.beans.factory.annotation.Value;
public class ToscaResourceStructure {
- protected static final Logger logger = LoggerFactory.getLogger(ToscaResourceStructure.class);
-
- /**
- * mso config path, used for the config files, like download csar files.
- */
- private String msoConfigPath;
-
- Metadata serviceMetadata;
- private Service catalogService;
- ISdcCsarHelper sdcCsarHelper;
- List<NodeTemplate> allottedList;
- List<NodeTemplate> networkTypes;
- List<NodeTemplate> vfTypes;
- String heatTemplateUUID;
- String volHeatTemplateUUID;
- String volHeatEnvTemplateUUID;
- String envHeatTemplateUUID;
- String heatFilesUUID;
- String workloadPerformance;
- String serviceVersion;
- private boolean isDeployedSuccessfully=false;
-
-
- private NetworkResourceCustomization catalogNetworkResourceCustomization;
-
- private NetworkResource catalogNetworkResource;
-
- private List<NetworkInstanceGroup> catalogNetworkInstanceGroup;
-
- private CollectionNetworkResourceCustomization catalogCollectionNetworkResourceCustomization;
-
- private CollectionResource catalogCollectionResource;
-
- private CollectionResourceCustomization catalogCollectionResourceCustomization;
-
- private NetworkCollectionResourceCustomization catalogNetworkCollectionResourceCustomization;
-
- private ServiceProxyResourceCustomization catalogServiceProxyResourceCustomization;
-
- private ConfigurationResource catalogConfigurationResource;
-
- private ConfigurationResourceCustomization catalogConfigurationResourceCustomization;
-
- private AllottedResourceCustomization catalogResourceCustomization;
-
- private VfModule vfModule;
-
- private VfModuleCustomization vfModuleCustomization;
-
- private VnfResourceCustomization vnfResourceCustomization;
-
- private PnfResourceCustomization pnfResourceCustomization;
-
- private AllottedResource allottedResource;
-
- private AllottedResourceCustomization allottedResourceCustomization;
-
- private TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup;
-
- private IArtifactInfo toscaArtifact;
-
- private ToscaCsar toscaCsar;
-
- public ToscaResourceStructure(){
- this(System.getProperty("mso.config.path"));
- }
-
- public ToscaResourceStructure(final String msoConfigPath){
- this.msoConfigPath = msoConfigPath;
- logger.info("MSO config path is: {}", msoConfigPath);
- }
-
- public void updateResourceStructure(IArtifactInfo artifact) throws ASDCDownloadException {
-
- try {
- SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();//Autoclosable
-
- String filePath = Paths.get(msoConfigPath, "ASDC", artifact.getArtifactVersion(), artifact.getArtifactName()).normalize().toString();
-
- File spoolFile = new File(filePath);
-
- logger.debug("ASDC File path is: {}", spoolFile.getAbsolutePath());
- logger.info("{} {} {} {}", MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), "***PATH", "ASDC",
- spoolFile.getAbsolutePath());
-
- sdcCsarHelper = factory.getSdcCsarHelper(spoolFile.getAbsolutePath(),false);
-
- }catch(Exception e){
- logger.debug(e.getMessage(), e);
- logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(),
- "Exception caught during parser *****LOOK********* " + artifact.getArtifactName(), "ASDC",
- "processResourceNotification", ErrorCode.BusinessProcesssError.getValue(),
- "Exception in " + "processResourceNotification", e);
-
- throw new ASDCDownloadException ("Exception caught when passing the csar file to the parser ", e);
- }
-
- serviceMetadata = sdcCsarHelper.getServiceMetadata();
-
- }
-
- public String getHeatTemplateUUID() {
- return heatTemplateUUID;
- }
-
- public void setHeatTemplateUUID(String heatTemplateUUID) {
- this.heatTemplateUUID = heatTemplateUUID;
- }
-
- public List<NodeTemplate> getAllottedList() {
- return allottedList;
- }
-
- public void setAllottedList(List<NodeTemplate> allottedList) {
- this.allottedList = allottedList;
- }
-
- public ISdcCsarHelper getSdcCsarHelper() {
- return sdcCsarHelper;
- }
-
- public void setSdcCsarHelper(ISdcCsarHelper sdcCsarHelper) {
- this.sdcCsarHelper = sdcCsarHelper;
- }
-
- public Metadata getServiceMetadata() {
- return serviceMetadata;
- }
-
- public Service getCatalogService() {
- return catalogService;
- }
-
- public void setServiceMetadata(Metadata serviceMetadata) {
- this.serviceMetadata = serviceMetadata;
- }
-
- public void setCatalogService(Service catalogService) {
- this.catalogService = catalogService;
- }
-
- public List<NodeTemplate> getNetworkTypes() {
- return networkTypes;
- }
-
- public void setNetworkTypes(List<NodeTemplate> networkTypes) {
- this.networkTypes = networkTypes;
- }
-
- public List<NodeTemplate> getVfTypes() {
- return vfTypes;
- }
-
- public void setVfTypes(List<NodeTemplate> vfTypes) {
- this.vfTypes = vfTypes;
- }
-
- public AllottedResourceCustomization getCatalogResourceCustomization() {
- return catalogResourceCustomization;
- }
-
- public void setCatalogResourceCustomization(
- AllottedResourceCustomization catalogResourceCustomization) {
- this.catalogResourceCustomization = catalogResourceCustomization;
- }
-
- // Network Only
- public NetworkResourceCustomization getCatalogNetworkResourceCustomization() {
- return catalogNetworkResourceCustomization;
- }
- // Network Only
- public void setCatalogNetworkResourceCustomization(NetworkResourceCustomization catalogNetworkResourceCustomization) {
- this.catalogNetworkResourceCustomization = catalogNetworkResourceCustomization;
- }
-
- public NetworkResource getCatalogNetworkResource() {
- return catalogNetworkResource;
- }
-
- public void setCatalogNetworkResource(NetworkResource catalogNetworkResource) {
- this.catalogNetworkResource = catalogNetworkResource;
- }
-
- public VfModule getCatalogVfModule() {
- return vfModule;
- }
-
- public void setCatalogVfModule(VfModule vfModule) {
- this.vfModule = vfModule;
- }
-/*
- public VnfResource getCatalogVnfResource() {
- return vnfResource;
- }
-
- public void setCatalogVnfResource(VnfResource vnfResource) {
- this.vnfResource = vnfResource;
- }
-
- */
-
- public VnfResourceCustomization getCatalogVnfResourceCustomization() {
- return vnfResourceCustomization;
- }
-
- public void setCatalogVnfResourceCustomization(
- VnfResourceCustomization vnfResourceCustomization) {
- this.vnfResourceCustomization = vnfResourceCustomization;
- }
-
- public PnfResourceCustomization getPnfResourceCustomization() {
- return pnfResourceCustomization;
- }
-
- public void setPnfResourceCustomization(PnfResourceCustomization pnfResourceCustomization) {
- this.pnfResourceCustomization = pnfResourceCustomization;
- }
-
-
- public VfModuleCustomization getCatalogVfModuleCustomization() {
- return vfModuleCustomization;
- }
-
- public void setCatalogVfModuleCustomization(VfModuleCustomization vfModuleCustomization) {
- this.vfModuleCustomization = vfModuleCustomization;
- }
-
- public AllottedResource getAllottedResource() {
- return allottedResource;
- }
-
- public void setAllottedResource(AllottedResource allottedResource) {
- this.allottedResource = allottedResource;
- }
-
- public AllottedResourceCustomization getCatalogAllottedResourceCustomization() {
- return allottedResourceCustomization;
- }
-
- public void setCatalogAllottedResourceCustomization(
- AllottedResourceCustomization allottedResourceCustomization) {
- this.allottedResourceCustomization = allottedResourceCustomization;
- }
-
- public TempNetworkHeatTemplateLookup getCatalogTempNetworkHeatTemplateLookup() {
- return tempNetworkHeatTemplateLookup;
- }
-
- public void setCatalogTempNetworkHeatTemplateLookup(
- TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup) {
- this.tempNetworkHeatTemplateLookup = tempNetworkHeatTemplateLookup;
- }
-
- public String getHeatFilesUUID() {
- return heatFilesUUID;
- }
-
- public void setHeatFilesUUID(String heatFilesUUID) {
- this.heatFilesUUID = heatFilesUUID;
- }
-
- public IArtifactInfo getToscaArtifact() {
- return toscaArtifact;
- }
-
- public void setToscaArtifact(IArtifactInfo toscaArtifact) {
- this.toscaArtifact = toscaArtifact;
- }
-
- public ToscaCsar getCatalogToscaCsar() {
- return toscaCsar;
- }
-
- public void setCatalogToscaCsar(ToscaCsar toscaCsar) {
- this.toscaCsar = toscaCsar;
- }
-
- public String getVolHeatTemplateUUID() {
- return volHeatTemplateUUID;
- }
-
- public void setVolHeatTemplateUUID(String volHeatTemplateUUID) {
- this.volHeatTemplateUUID = volHeatTemplateUUID;
- }
-
- public String getEnvHeatTemplateUUID() {
- return envHeatTemplateUUID;
- }
-
- public void setEnvHeatTemplateUUID(String envHeatTemplateUUID) {
- this.envHeatTemplateUUID = envHeatTemplateUUID;
- }
-
- public String getVolHeatEnvTemplateUUID() {
- return volHeatEnvTemplateUUID;
- }
-
- public void setVolHeatEnvTemplateUUID(String volHeatEnvTemplateUUID) {
- this.volHeatEnvTemplateUUID = volHeatEnvTemplateUUID;
- }
-
- public String getServiceVersion() {
- return serviceVersion;
- }
-
- public void setServiceVersion(String serviceVersion) {
- this.serviceVersion = serviceVersion;
- }
-
- public String getWorkloadPerformance() {
- return workloadPerformance;
- }
-
- public void setWorkloadPerformance(String workloadPerformance) {
- this.workloadPerformance = workloadPerformance;
- }
-
- public VfModule getVfModule() {
- return vfModule;
- }
-
- public void setVfModule(VfModule vfModule) {
- this.vfModule = vfModule;
- }
-
- public VfModuleCustomization getVfModuleCustomization() {
- return vfModuleCustomization;
- }
-
- public void setVfModuleCustomization(VfModuleCustomization vfModuleCustomization) {
- this.vfModuleCustomization = vfModuleCustomization;
- }
-
-
- public VnfResourceCustomization getVnfResourceCustomization() {
- return vnfResourceCustomization;
- }
-
- public void setVnfResourceCustomization(
- VnfResourceCustomization vnfResourceCustomization) {
- this.vnfResourceCustomization = vnfResourceCustomization;
- }
-
- public AllottedResourceCustomization getAllottedResourceCustomization() {
- return allottedResourceCustomization;
- }
-
- public void setAllottedResourceCustomization(
- AllottedResourceCustomization allottedResourceCustomization) {
- this.allottedResourceCustomization = allottedResourceCustomization;
- }
-
- public TempNetworkHeatTemplateLookup getTempNetworkHeatTemplateLookup() {
- return tempNetworkHeatTemplateLookup;
- }
-
- public void setTempNetworkHeatTemplateLookup(
- TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup) {
- this.tempNetworkHeatTemplateLookup = tempNetworkHeatTemplateLookup;
- }
-
- public List<NetworkInstanceGroup> getCatalogNetworkInstanceGroup() {
- return catalogNetworkInstanceGroup;
- }
-
- public void setCatalogNetworkInstanceGroup(List<NetworkInstanceGroup> catalogNetworkInstanceGroup) {
- this.catalogNetworkInstanceGroup = catalogNetworkInstanceGroup;
- }
-
- public CollectionNetworkResourceCustomization getCatalogCollectionNetworkResourceCustomization() {
- return catalogCollectionNetworkResourceCustomization;
- }
-
- public void setCatalogCollectionNetworkResourceCustomization(
- CollectionNetworkResourceCustomization catalogCollectionNetworkResourceCustomization) {
- this.catalogCollectionNetworkResourceCustomization = catalogCollectionNetworkResourceCustomization;
- }
-
- public CollectionResource getCatalogCollectionResource() {
- return catalogCollectionResource;
- }
-
- public void setCatalogCollectionResource(CollectionResource catalogCollectionResource) {
- this.catalogCollectionResource = catalogCollectionResource;
- }
-
- public CollectionResourceCustomization getCatalogCollectionResourceCustomization() {
- return catalogCollectionResourceCustomization;
- }
-
- public void setCatalogCollectionResourceCustomization(
- CollectionResourceCustomization catalogCollectionResourceCustomization) {
- this.catalogCollectionResourceCustomization = catalogCollectionResourceCustomization;
- }
-
- public NetworkCollectionResourceCustomization getCatalogNetworkCollectionResourceCustomization() {
- return catalogNetworkCollectionResourceCustomization;
- }
-
- public void setCatalogNetworkCollectionResourceCustomization(
- NetworkCollectionResourceCustomization catalogNetworkCollectionResourceCustomization) {
- this.catalogNetworkCollectionResourceCustomization = catalogNetworkCollectionResourceCustomization;
- }
-
- public ServiceProxyResourceCustomization getCatalogServiceProxyResourceCustomization() {
- return catalogServiceProxyResourceCustomization;
- }
-
- public void setCatalogServiceProxyResourceCustomization(
- ServiceProxyResourceCustomization catalogServiceProxyResourceCustomization) {
- this.catalogServiceProxyResourceCustomization = catalogServiceProxyResourceCustomization;
- }
-
- public ConfigurationResource getCatalogConfigurationResource() {
- return catalogConfigurationResource;
- }
-
- public void setCatalogConfigurationResource(ConfigurationResource catalogConfigurationResource) {
- this.catalogConfigurationResource = catalogConfigurationResource;
- }
-
- public ConfigurationResourceCustomization getCatalogConfigurationResourceCustomization() {
- return catalogConfigurationResourceCustomization;
- }
-
- public void setCatalogConfigurationResourceCustomization(
- ConfigurationResourceCustomization catalogConfigurationResourceCustomization) {
- this.catalogConfigurationResourceCustomization = catalogConfigurationResourceCustomization;
- }
-
- public ToscaCsar getToscaCsar() {
- return toscaCsar;
- }
-
- public void setToscaCsar(ToscaCsar toscaCsar) {
- this.toscaCsar = toscaCsar;
- }
-
- public boolean isDeployedSuccessfully() {
- return isDeployedSuccessfully;
- }
-
- public void setSuccessfulDeployment() {
- isDeployedSuccessfully = true;
- }
+ protected static final Logger logger = LoggerFactory.getLogger(ToscaResourceStructure.class);
+
+ /**
+ * mso config path, used for the config files, like download csar files.
+ */
+ private String msoConfigPath;
+
+ Metadata serviceMetadata;
+ private Service catalogService;
+ ISdcCsarHelper sdcCsarHelper;
+ List<NodeTemplate> allottedList;
+ List<NodeTemplate> networkTypes;
+ List<NodeTemplate> vfTypes;
+ String heatTemplateUUID;
+ String volHeatTemplateUUID;
+ String volHeatEnvTemplateUUID;
+ String envHeatTemplateUUID;
+ String heatFilesUUID;
+ String workloadPerformance;
+ String serviceVersion;
+ private boolean isDeployedSuccessfully = false;
+
+
+ private NetworkResourceCustomization catalogNetworkResourceCustomization;
+
+ private NetworkResource catalogNetworkResource;
+
+ private List<NetworkInstanceGroup> catalogNetworkInstanceGroup;
+
+ private CollectionNetworkResourceCustomization catalogCollectionNetworkResourceCustomization;
+
+ private CollectionResource catalogCollectionResource;
+
+ private CollectionResourceCustomization catalogCollectionResourceCustomization;
+
+ private NetworkCollectionResourceCustomization catalogNetworkCollectionResourceCustomization;
+
+ private ServiceProxyResourceCustomization catalogServiceProxyResourceCustomization;
+
+ private ConfigurationResource catalogConfigurationResource;
+
+ private ConfigurationResourceCustomization catalogConfigurationResourceCustomization;
+
+ private AllottedResourceCustomization catalogResourceCustomization;
+
+ private VfModule vfModule;
+
+ private VfModuleCustomization vfModuleCustomization;
+
+ private VnfResourceCustomization vnfResourceCustomization;
+
+ private PnfResourceCustomization pnfResourceCustomization;
+
+ private AllottedResource allottedResource;
+
+ private AllottedResourceCustomization allottedResourceCustomization;
+
+ private TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup;
+
+ private IArtifactInfo toscaArtifact;
+
+ private ToscaCsar toscaCsar;
+
+ public ToscaResourceStructure() {
+ this(System.getProperty("mso.config.path"));
+ }
+
+ public ToscaResourceStructure(final String msoConfigPath) {
+ this.msoConfigPath = msoConfigPath;
+ logger.info("MSO config path is: {}", msoConfigPath);
+ }
+
+ public void updateResourceStructure(IArtifactInfo artifact) throws ASDCDownloadException {
+
+ try {
+ SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();// Autoclosable
+
+ String filePath =
+ Paths.get(msoConfigPath, "ASDC", artifact.getArtifactVersion(), artifact.getArtifactName())
+ .normalize().toString();
+
+ File spoolFile = new File(filePath);
+
+ logger.debug("ASDC File path is: {}", spoolFile.getAbsolutePath());
+ logger.info("{} {} {} {}", MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), "***PATH", "ASDC",
+ spoolFile.getAbsolutePath());
+
+ sdcCsarHelper = factory.getSdcCsarHelper(spoolFile.getAbsolutePath(), false);
+
+ } catch (Exception e) {
+ logger.debug(e.getMessage(), e);
+ logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(),
+ "Exception caught during parser *****LOOK********* " + artifact.getArtifactName(), "ASDC",
+ "processResourceNotification", ErrorCode.BusinessProcesssError.getValue(),
+ "Exception in " + "processResourceNotification", e);
+
+ throw new ASDCDownloadException("Exception caught when passing the csar file to the parser ", e);
+ }
+
+ serviceMetadata = sdcCsarHelper.getServiceMetadata();
+
+ }
+
+ public String getHeatTemplateUUID() {
+ return heatTemplateUUID;
+ }
+
+ public void setHeatTemplateUUID(String heatTemplateUUID) {
+ this.heatTemplateUUID = heatTemplateUUID;
+ }
+
+ public List<NodeTemplate> getAllottedList() {
+ return allottedList;
+ }
+
+ public void setAllottedList(List<NodeTemplate> allottedList) {
+ this.allottedList = allottedList;
+ }
+
+ public ISdcCsarHelper getSdcCsarHelper() {
+ return sdcCsarHelper;
+ }
+
+ public void setSdcCsarHelper(ISdcCsarHelper sdcCsarHelper) {
+ this.sdcCsarHelper = sdcCsarHelper;
+ }
+
+ public Metadata getServiceMetadata() {
+ return serviceMetadata;
+ }
+
+ public Service getCatalogService() {
+ return catalogService;
+ }
+
+ public void setServiceMetadata(Metadata serviceMetadata) {
+ this.serviceMetadata = serviceMetadata;
+ }
+
+ public void setCatalogService(Service catalogService) {
+ this.catalogService = catalogService;
+ }
+
+ public List<NodeTemplate> getNetworkTypes() {
+ return networkTypes;
+ }
+
+ public void setNetworkTypes(List<NodeTemplate> networkTypes) {
+ this.networkTypes = networkTypes;
+ }
+
+ public List<NodeTemplate> getVfTypes() {
+ return vfTypes;
+ }
+
+ public void setVfTypes(List<NodeTemplate> vfTypes) {
+ this.vfTypes = vfTypes;
+ }
+
+ public AllottedResourceCustomization getCatalogResourceCustomization() {
+ return catalogResourceCustomization;
+ }
+
+ public void setCatalogResourceCustomization(AllottedResourceCustomization catalogResourceCustomization) {
+ this.catalogResourceCustomization = catalogResourceCustomization;
+ }
+
+ // Network Only
+ public NetworkResourceCustomization getCatalogNetworkResourceCustomization() {
+ return catalogNetworkResourceCustomization;
+ }
+
+ // Network Only
+ public void setCatalogNetworkResourceCustomization(
+ NetworkResourceCustomization catalogNetworkResourceCustomization) {
+ this.catalogNetworkResourceCustomization = catalogNetworkResourceCustomization;
+ }
+
+ public NetworkResource getCatalogNetworkResource() {
+ return catalogNetworkResource;
+ }
+
+ public void setCatalogNetworkResource(NetworkResource catalogNetworkResource) {
+ this.catalogNetworkResource = catalogNetworkResource;
+ }
+
+ public VfModule getCatalogVfModule() {
+ return vfModule;
+ }
+
+ public void setCatalogVfModule(VfModule vfModule) {
+ this.vfModule = vfModule;
+ }
+ /*
+ * public VnfResource getCatalogVnfResource() { return vnfResource; }
+ *
+ * public void setCatalogVnfResource(VnfResource vnfResource) { this.vnfResource = vnfResource; }
+ *
+ */
+
+ public VnfResourceCustomization getCatalogVnfResourceCustomization() {
+ return vnfResourceCustomization;
+ }
+
+ public void setCatalogVnfResourceCustomization(VnfResourceCustomization vnfResourceCustomization) {
+ this.vnfResourceCustomization = vnfResourceCustomization;
+ }
+
+ public PnfResourceCustomization getPnfResourceCustomization() {
+ return pnfResourceCustomization;
+ }
+
+ public void setPnfResourceCustomization(PnfResourceCustomization pnfResourceCustomization) {
+ this.pnfResourceCustomization = pnfResourceCustomization;
+ }
+
+
+ public VfModuleCustomization getCatalogVfModuleCustomization() {
+ return vfModuleCustomization;
+ }
+
+ public void setCatalogVfModuleCustomization(VfModuleCustomization vfModuleCustomization) {
+ this.vfModuleCustomization = vfModuleCustomization;
+ }
+
+ public AllottedResource getAllottedResource() {
+ return allottedResource;
+ }
+
+ public void setAllottedResource(AllottedResource allottedResource) {
+ this.allottedResource = allottedResource;
+ }
+
+ public AllottedResourceCustomization getCatalogAllottedResourceCustomization() {
+ return allottedResourceCustomization;
+ }
+
+ public void setCatalogAllottedResourceCustomization(AllottedResourceCustomization allottedResourceCustomization) {
+ this.allottedResourceCustomization = allottedResourceCustomization;
+ }
+
+ public TempNetworkHeatTemplateLookup getCatalogTempNetworkHeatTemplateLookup() {
+ return tempNetworkHeatTemplateLookup;
+ }
+
+ public void setCatalogTempNetworkHeatTemplateLookup(TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup) {
+ this.tempNetworkHeatTemplateLookup = tempNetworkHeatTemplateLookup;
+ }
+
+ public String getHeatFilesUUID() {
+ return heatFilesUUID;
+ }
+
+ public void setHeatFilesUUID(String heatFilesUUID) {
+ this.heatFilesUUID = heatFilesUUID;
+ }
+
+ public IArtifactInfo getToscaArtifact() {
+ return toscaArtifact;
+ }
+
+ public void setToscaArtifact(IArtifactInfo toscaArtifact) {
+ this.toscaArtifact = toscaArtifact;
+ }
+
+ public ToscaCsar getCatalogToscaCsar() {
+ return toscaCsar;
+ }
+
+ public void setCatalogToscaCsar(ToscaCsar toscaCsar) {
+ this.toscaCsar = toscaCsar;
+ }
+
+ public String getVolHeatTemplateUUID() {
+ return volHeatTemplateUUID;
+ }
+
+ public void setVolHeatTemplateUUID(String volHeatTemplateUUID) {
+ this.volHeatTemplateUUID = volHeatTemplateUUID;
+ }
+
+ public String getEnvHeatTemplateUUID() {
+ return envHeatTemplateUUID;
+ }
+
+ public void setEnvHeatTemplateUUID(String envHeatTemplateUUID) {
+ this.envHeatTemplateUUID = envHeatTemplateUUID;
+ }
+
+ public String getVolHeatEnvTemplateUUID() {
+ return volHeatEnvTemplateUUID;
+ }
+
+ public void setVolHeatEnvTemplateUUID(String volHeatEnvTemplateUUID) {
+ this.volHeatEnvTemplateUUID = volHeatEnvTemplateUUID;
+ }
+
+ public String getServiceVersion() {
+ return serviceVersion;
+ }
+
+ public void setServiceVersion(String serviceVersion) {
+ this.serviceVersion = serviceVersion;
+ }
+
+ public String getWorkloadPerformance() {
+ return workloadPerformance;
+ }
+
+ public void setWorkloadPerformance(String workloadPerformance) {
+ this.workloadPerformance = workloadPerformance;
+ }
+
+ public VfModule getVfModule() {
+ return vfModule;
+ }
+
+ public void setVfModule(VfModule vfModule) {
+ this.vfModule = vfModule;
+ }
+
+ public VfModuleCustomization getVfModuleCustomization() {
+ return vfModuleCustomization;
+ }
+
+ public void setVfModuleCustomization(VfModuleCustomization vfModuleCustomization) {
+ this.vfModuleCustomization = vfModuleCustomization;
+ }
+
+
+ public VnfResourceCustomization getVnfResourceCustomization() {
+ return vnfResourceCustomization;
+ }
+
+ public void setVnfResourceCustomization(VnfResourceCustomization vnfResourceCustomization) {
+ this.vnfResourceCustomization = vnfResourceCustomization;
+ }
+
+ public AllottedResourceCustomization getAllottedResourceCustomization() {
+ return allottedResourceCustomization;
+ }
+
+ public void setAllottedResourceCustomization(AllottedResourceCustomization allottedResourceCustomization) {
+ this.allottedResourceCustomization = allottedResourceCustomization;
+ }
+
+ public TempNetworkHeatTemplateLookup getTempNetworkHeatTemplateLookup() {
+ return tempNetworkHeatTemplateLookup;
+ }
+
+ public void setTempNetworkHeatTemplateLookup(TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup) {
+ this.tempNetworkHeatTemplateLookup = tempNetworkHeatTemplateLookup;
+ }
+
+ public List<NetworkInstanceGroup> getCatalogNetworkInstanceGroup() {
+ return catalogNetworkInstanceGroup;
+ }
+
+ public void setCatalogNetworkInstanceGroup(List<NetworkInstanceGroup> catalogNetworkInstanceGroup) {
+ this.catalogNetworkInstanceGroup = catalogNetworkInstanceGroup;
+ }
+
+ public CollectionNetworkResourceCustomization getCatalogCollectionNetworkResourceCustomization() {
+ return catalogCollectionNetworkResourceCustomization;
+ }
+
+ public void setCatalogCollectionNetworkResourceCustomization(
+ CollectionNetworkResourceCustomization catalogCollectionNetworkResourceCustomization) {
+ this.catalogCollectionNetworkResourceCustomization = catalogCollectionNetworkResourceCustomization;
+ }
+
+ public CollectionResource getCatalogCollectionResource() {
+ return catalogCollectionResource;
+ }
+
+ public void setCatalogCollectionResource(CollectionResource catalogCollectionResource) {
+ this.catalogCollectionResource = catalogCollectionResource;
+ }
+
+ public CollectionResourceCustomization getCatalogCollectionResourceCustomization() {
+ return catalogCollectionResourceCustomization;
+ }
+
+ public void setCatalogCollectionResourceCustomization(
+ CollectionResourceCustomization catalogCollectionResourceCustomization) {
+ this.catalogCollectionResourceCustomization = catalogCollectionResourceCustomization;
+ }
+
+ public NetworkCollectionResourceCustomization getCatalogNetworkCollectionResourceCustomization() {
+ return catalogNetworkCollectionResourceCustomization;
+ }
+
+ public void setCatalogNetworkCollectionResourceCustomization(
+ NetworkCollectionResourceCustomization catalogNetworkCollectionResourceCustomization) {
+ this.catalogNetworkCollectionResourceCustomization = catalogNetworkCollectionResourceCustomization;
+ }
+
+ public ServiceProxyResourceCustomization getCatalogServiceProxyResourceCustomization() {
+ return catalogServiceProxyResourceCustomization;
+ }
+
+ public void setCatalogServiceProxyResourceCustomization(
+ ServiceProxyResourceCustomization catalogServiceProxyResourceCustomization) {
+ this.catalogServiceProxyResourceCustomization = catalogServiceProxyResourceCustomization;
+ }
+
+ public ConfigurationResource getCatalogConfigurationResource() {
+ return catalogConfigurationResource;
+ }
+
+ public void setCatalogConfigurationResource(ConfigurationResource catalogConfigurationResource) {
+ this.catalogConfigurationResource = catalogConfigurationResource;
+ }
+
+ public ConfigurationResourceCustomization getCatalogConfigurationResourceCustomization() {
+ return catalogConfigurationResourceCustomization;
+ }
+
+ public void setCatalogConfigurationResourceCustomization(
+ ConfigurationResourceCustomization catalogConfigurationResourceCustomization) {
+ this.catalogConfigurationResourceCustomization = catalogConfigurationResourceCustomization;
+ }
+
+ public ToscaCsar getToscaCsar() {
+ return toscaCsar;
+ }
+
+ public void setToscaCsar(ToscaCsar toscaCsar) {
+ this.toscaCsar = toscaCsar;
+ }
+
+ public boolean isDeployedSuccessfully() {
+ return isDeployedSuccessfully;
+ }
+
+ public void setSuccessfulDeployment() {
+ isDeployedSuccessfully = true;
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleArtifact.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleArtifact.java
index cb4761c557..a3b074f557 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleArtifact.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleArtifact.java
@@ -22,7 +22,6 @@ package org.onap.so.asdc.installer;
import java.io.UnsupportedEncodingException;
-
import org.onap.so.db.catalog.beans.HeatEnvironment;
import org.onap.so.db.catalog.beans.HeatFiles;
import org.onap.so.db.catalog.beans.HeatTemplate;
@@ -30,68 +29,70 @@ import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.api.results.IDistributionClientDownloadResult;
/**
- * The structure that contains the artifactInfo and its associated DownloadedResult.
+ * The structure that contains the artifactInfo and its associated DownloadedResult.
*
*/
public final class VfModuleArtifact {
- private final IArtifactInfo artifactInfo;
- private int deployedInDb=0;
- private final String result;
- private HeatFiles heatFiles;
- private HeatTemplate heatTemplate;
- private HeatEnvironment heatEnvironment;
-
- public VfModuleArtifact(IArtifactInfo artifactinfo,IDistributionClientDownloadResult clientResult) throws UnsupportedEncodingException {
- this(artifactinfo, clientResult, null);
- }
-
- public VfModuleArtifact(IArtifactInfo artifactinfo,IDistributionClientDownloadResult clientResult, String modifiedHeatTemplate) throws UnsupportedEncodingException {
- artifactInfo=artifactinfo;
- if(modifiedHeatTemplate != null){
- result = modifiedHeatTemplate;
- }else{
- result = new String(clientResult.getArtifactPayload(), "UTF-8");
- }
- }
-
- public HeatFiles getHeatFiles() {
- return heatFiles;
- }
-
- public void setHeatFiles(HeatFiles heatFiles) {
- this.heatFiles = heatFiles;
- }
-
- public HeatTemplate getHeatTemplate() {
- return heatTemplate;
- }
-
- public void setHeatTemplate(HeatTemplate heatTemplate) {
- this.heatTemplate = heatTemplate;
- }
-
- public IArtifactInfo getArtifactInfo() {
- return artifactInfo;
- }
-
- public String getResult() {
- return result;
- }
-
- public int getDeployedInDb() {
- return deployedInDb;
- }
-
- public void incrementDeployedInDB() {
- ++deployedInDb;
- }
-
- public HeatEnvironment getHeatEnvironment() {
- return heatEnvironment;
- }
-
- public void setHeatEnvironment(HeatEnvironment heatEnvironment) {
- this.heatEnvironment=heatEnvironment;
- }
-
+ private final IArtifactInfo artifactInfo;
+ private int deployedInDb = 0;
+ private final String result;
+ private HeatFiles heatFiles;
+ private HeatTemplate heatTemplate;
+ private HeatEnvironment heatEnvironment;
+
+ public VfModuleArtifact(IArtifactInfo artifactinfo, IDistributionClientDownloadResult clientResult)
+ throws UnsupportedEncodingException {
+ this(artifactinfo, clientResult, null);
+ }
+
+ public VfModuleArtifact(IArtifactInfo artifactinfo, IDistributionClientDownloadResult clientResult,
+ String modifiedHeatTemplate) throws UnsupportedEncodingException {
+ artifactInfo = artifactinfo;
+ if (modifiedHeatTemplate != null) {
+ result = modifiedHeatTemplate;
+ } else {
+ result = new String(clientResult.getArtifactPayload(), "UTF-8");
+ }
+ }
+
+ public HeatFiles getHeatFiles() {
+ return heatFiles;
+ }
+
+ public void setHeatFiles(HeatFiles heatFiles) {
+ this.heatFiles = heatFiles;
+ }
+
+ public HeatTemplate getHeatTemplate() {
+ return heatTemplate;
+ }
+
+ public void setHeatTemplate(HeatTemplate heatTemplate) {
+ this.heatTemplate = heatTemplate;
+ }
+
+ public IArtifactInfo getArtifactInfo() {
+ return artifactInfo;
+ }
+
+ public String getResult() {
+ return result;
+ }
+
+ public int getDeployedInDb() {
+ return deployedInDb;
+ }
+
+ public void incrementDeployedInDB() {
+ ++deployedInDb;
+ }
+
+ public HeatEnvironment getHeatEnvironment() {
+ return heatEnvironment;
+ }
+
+ public void setHeatEnvironment(HeatEnvironment heatEnvironment) {
+ this.heatEnvironment = heatEnvironment;
+ }
+
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleMetaData.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleMetaData.java
index 11000bec98..40f32f648b 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleMetaData.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleMetaData.java
@@ -23,74 +23,73 @@ package org.onap.so.asdc.installer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public class VfModuleMetaData implements IVfModuleData {
- @JsonProperty("artifacts")
- private List<String> artifacts;
+ @JsonProperty("artifacts")
+ private List<String> artifacts;
- @JsonProperty("properties")
- //private List<Map<String, Object>> properties = new ArrayList<>();
- private Map<String,String> properties = new HashMap<>();
+ @JsonProperty("properties")
+ // private List<Map<String, Object>> properties = new ArrayList<>();
+ private Map<String, String> properties = new HashMap<>();
- @JsonIgnore
- private Map<String,Object> attributesMap = new HashMap<>();
+ @JsonIgnore
+ private Map<String, Object> attributesMap = new HashMap<>();
- @Override
- public List<String> getArtifacts() {
- return artifacts;
- }
+ @Override
+ public List<String> getArtifacts() {
+ return artifacts;
+ }
- public Map<String, String> getProperties() {
- return properties;
- }
+ public Map<String, String> getProperties() {
+ return properties;
+ }
- @Override
- public String getVfModuleModelDescription() {
- return (String)attributesMap.get("vfModuleModelDescription");
- }
+ @Override
+ public String getVfModuleModelDescription() {
+ return (String) attributesMap.get("vfModuleModelDescription");
+ }
- @Override
- public String getVfModuleModelInvariantUUID() {
- return (String)attributesMap.get("vfModuleModelInvariantUUID");
- }
+ @Override
+ public String getVfModuleModelInvariantUUID() {
+ return (String) attributesMap.get("vfModuleModelInvariantUUID");
+ }
- public String getVfModuleModelCustomizationUUID() {
- return (String)attributesMap.get("vfModuleModelCustomizationUUID");
- }
+ public String getVfModuleModelCustomizationUUID() {
+ return (String) attributesMap.get("vfModuleModelCustomizationUUID");
+ }
- @Override
- public String getVfModuleModelName() {
- return (String)attributesMap.get("vfModuleModelName");
- }
+ @Override
+ public String getVfModuleModelName() {
+ return (String) attributesMap.get("vfModuleModelName");
+ }
- @Override
- public String getVfModuleModelUUID() {
- return (String)attributesMap.get("vfModuleModelUUID");
- }
+ @Override
+ public String getVfModuleModelUUID() {
+ return (String) attributesMap.get("vfModuleModelUUID");
+ }
- @Override
- public String getVfModuleModelVersion() {
- return (String)attributesMap.get("vfModuleModelVersion");
- }
+ @Override
+ public String getVfModuleModelVersion() {
+ return (String) attributesMap.get("vfModuleModelVersion");
+ }
- @Override
- public boolean isBase() {
- return (boolean)attributesMap.get("isBase");
- }
+ @Override
+ public boolean isBase() {
+ return (boolean) attributesMap.get("isBase");
+ }
- @SuppressWarnings("unused")
- @JsonAnySetter
- public final void setAttribute(String attrName, Object attrValue) {
- if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) {
- this.attributesMap.put(attrName,attrValue);
- }
- }
+ @SuppressWarnings("unused")
+ @JsonAnySetter
+ public final void setAttribute(String attrName, Object attrValue) {
+ if ((null != attrName) && (!attrName.isEmpty()) && (null != attrValue) && (null != attrValue.toString())) {
+ this.attributesMap.put(attrName, attrValue);
+ }
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleStructure.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleStructure.java
index 9f0525db3d..36d6ab96c0 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleStructure.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfModuleStructure.java
@@ -25,7 +25,6 @@ import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-
import org.onap.sdc.api.notification.IVfModuleMetadata;
import org.onap.so.asdc.client.ASDCConfiguration;
import org.onap.so.asdc.client.exceptions.ArtifactInstallerException;
@@ -33,82 +32,84 @@ import org.onap.so.db.catalog.beans.VfModule;
public final class VfModuleStructure {
- private final IVfModuleData vfModuleMetadata;
+ private final IVfModuleData vfModuleMetadata;
- private final VfResourceStructure parentVfResource;
+ private final VfResourceStructure parentVfResource;
- private VfModule catalogVfModule;
- /**
- * The list of artifact existing in this resource hashed by artifactType.
- */
- private final Map<String, List<VfModuleArtifact>> artifactsMap;
+ private VfModule catalogVfModule;
+ /**
+ * The list of artifact existing in this resource hashed by artifactType.
+ */
+ private final Map<String, List<VfModuleArtifact>> artifactsMap;
- public VfModuleStructure(VfResourceStructure vfParentResource,IVfModuleData vfmoduleMetadata) throws ArtifactInstallerException {
+ public VfModuleStructure(VfResourceStructure vfParentResource, IVfModuleData vfmoduleMetadata)
+ throws ArtifactInstallerException {
- vfModuleMetadata = vfmoduleMetadata;
- parentVfResource = vfParentResource;
+ vfModuleMetadata = vfmoduleMetadata;
+ parentVfResource = vfParentResource;
- artifactsMap = new HashMap<>();
+ artifactsMap = new HashMap<>();
- for (String artifactUUID:this.vfModuleMetadata.getArtifacts()) {
- if (vfParentResource.getArtifactsMapByUUID().containsKey(artifactUUID)) {
- this.addToStructure(vfParentResource.getArtifactsMapByUUID().get(artifactUUID));
- } else {
- throw new ArtifactInstallerException("Artifact (UUID:"+artifactUUID+ ") referenced in the VFModule UUID list has not been downloaded, cancelling the Resource deployment");
- }
- }
- }
+ for (String artifactUUID : this.vfModuleMetadata.getArtifacts()) {
+ if (vfParentResource.getArtifactsMapByUUID().containsKey(artifactUUID)) {
+ this.addToStructure(vfParentResource.getArtifactsMapByUUID().get(artifactUUID));
+ } else {
+ throw new ArtifactInstallerException("Artifact (UUID:" + artifactUUID
+ + ") referenced in the VFModule UUID list has not been downloaded, cancelling the Resource deployment");
+ }
+ }
+ }
- private void addToStructure(VfModuleArtifact vfModuleArtifact) {
+ private void addToStructure(VfModuleArtifact vfModuleArtifact) {
- if (artifactsMap.containsKey(vfModuleArtifact.getArtifactInfo().getArtifactType())) {
- artifactsMap.get(vfModuleArtifact.getArtifactInfo().getArtifactType()).add(vfModuleArtifact);
+ if (artifactsMap.containsKey(vfModuleArtifact.getArtifactInfo().getArtifactType())) {
+ artifactsMap.get(vfModuleArtifact.getArtifactInfo().getArtifactType()).add(vfModuleArtifact);
- } else {
- List<VfModuleArtifact> nestedList = new LinkedList<>();
- nestedList.add(vfModuleArtifact);
+ } else {
+ List<VfModuleArtifact> nestedList = new LinkedList<>();
+ nestedList.add(vfModuleArtifact);
- artifactsMap.put(vfModuleArtifact.getArtifactInfo().getArtifactType(), nestedList);
- }
- }
+ artifactsMap.put(vfModuleArtifact.getArtifactInfo().getArtifactType(), nestedList);
+ }
+ }
- public List<VfModuleArtifact> getOrderedArtifactList() {
+ public List<VfModuleArtifact> getOrderedArtifactList() {
- List <VfModuleArtifact> artifactsList = new LinkedList<>();
+ List<VfModuleArtifact> artifactsList = new LinkedList<>();
- artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT));
- artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_ENV));
- artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_VOL));
+ artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT));
+ artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_ENV));
+ artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_VOL));
- artifactsList.addAll((artifactsMap.get(ASDCConfiguration.HEAT_NESTED)));
+ artifactsList.addAll((artifactsMap.get(ASDCConfiguration.HEAT_NESTED)));
- artifactsList.addAll((artifactsMap.get(ASDCConfiguration.HEAT_ARTIFACT)));
+ artifactsList.addAll((artifactsMap.get(ASDCConfiguration.HEAT_ARTIFACT)));
- artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_VOL));
+ artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_VOL));
- return null;
- }
+ return null;
+ }
- public IVfModuleData getVfModuleMetadata() {
- return vfModuleMetadata;
- }
+ public IVfModuleData getVfModuleMetadata() {
+ return vfModuleMetadata;
+ }
- public VfResourceStructure getParentVfResource() {
- return parentVfResource;
- }
+ public VfResourceStructure getParentVfResource() {
+ return parentVfResource;
+ }
- public Map<String, List<VfModuleArtifact>> getArtifactsMap() {
- return artifactsMap;
- }
+ public Map<String, List<VfModuleArtifact>> getArtifactsMap() {
+ return artifactsMap;
+ }
- public VfModule getCatalogVfModule() {
- return catalogVfModule;
- }
+ public VfModule getCatalogVfModule() {
+ return catalogVfModule;
+ }
- public void setCatalogVfModule(VfModule catalogVfModule) {
- this.catalogVfModule = catalogVfModule;
- }
+ public void setCatalogVfModule(VfModule catalogVfModule) {
+ this.catalogVfModule = catalogVfModule;
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java
index 402af160c1..62408be922 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java
@@ -83,13 +83,13 @@ public class VfResourceStructure extends ResourceStructure {
}
public void addArtifactToStructure(IDistributionClient distributionClient, IArtifactInfo artifactinfo,
- IDistributionClientDownloadResult clientResult) throws UnsupportedEncodingException {
+ IDistributionClientDownloadResult clientResult) throws UnsupportedEncodingException {
this.addArtifactToStructure(distributionClient, artifactinfo, clientResult, null);
}
public void addArtifactToStructure(IDistributionClient distributionClient, IArtifactInfo artifactinfo,
- IDistributionClientDownloadResult clientResult, String modifiedHeatTemplate)
- throws UnsupportedEncodingException {
+ IDistributionClientDownloadResult clientResult, String modifiedHeatTemplate)
+ throws UnsupportedEncodingException {
VfModuleArtifact vfModuleArtifact = new VfModuleArtifact(artifactinfo, clientResult, modifiedHeatTemplate);
addArtifactByType(artifactinfo, clientResult, vfModuleArtifact);
if (ASDCConfiguration.VF_MODULES_METADATA.equals(artifactinfo.getArtifactType())) {
@@ -99,13 +99,13 @@ public class VfResourceStructure extends ResourceStructure {
}
protected void addArtifactByType(IArtifactInfo artifactinfo, IDistributionClientDownloadResult clientResult,
- VfModuleArtifact vfModuleArtifact) throws UnsupportedEncodingException {
+ VfModuleArtifact vfModuleArtifact) throws UnsupportedEncodingException {
switch (artifactinfo.getArtifactType()) {
case ASDCConfiguration.HEAT:
case ASDCConfiguration.HEAT_ENV:
case ASDCConfiguration.HEAT_VOL:
- case ASDCConfiguration.HEAT_NESTED: // For 1607 only 1 level tree is supported
+ case ASDCConfiguration.HEAT_NESTED: // For 1607 only 1 level tree is supported
case ASDCConfiguration.HEAT_ARTIFACT:
case ASDCConfiguration.HEAT_NET:
case ASDCConfiguration.OTHER:
@@ -119,17 +119,16 @@ public class VfResourceStructure extends ResourceStructure {
}
}
- public void prepareInstall() throws ArtifactInstallerException{
+ public void prepareInstall() throws ArtifactInstallerException {
createVfModuleStructures();
}
public void createVfModuleStructures() throws ArtifactInstallerException {
- //for vender tosca VNF there is no VFModule in VF
+ // for vender tosca VNF there is no VFModule in VF
if (vfModulesMetadataList == null) {
logger.info("{} {} {} {}", MessageEnum.ASDC_GENERAL_INFO.toString(), "There is no VF mudules in the VF.",
- "ASDC",
- "createVfModuleStructures");
+ "ASDC", "createVfModuleStructures");
return;
}
for (IVfModuleData vfModuleMeta : vfModulesMetadataList) {
@@ -165,7 +164,7 @@ public class VfResourceStructure extends ResourceStructure {
// Network Only
public void setCatalogNetworkResourceCustomization(
- NetworkResourceCustomization catalogNetworkResourceCustomization) {
+ NetworkResourceCustomization catalogNetworkResourceCustomization) {
this.catalogNetworkResourceCustomization = catalogNetworkResourceCustomization;
}
@@ -173,8 +172,7 @@ public class VfResourceStructure extends ResourceStructure {
return catalogResourceCustomization;
}
- public void setCatalogResourceCustomization(
- AllottedResourceCustomization catalogResourceCustomization) {
+ public void setCatalogResourceCustomization(AllottedResourceCustomization catalogResourceCustomization) {
this.catalogResourceCustomization = catalogResourceCustomization;
}
@@ -188,9 +186,8 @@ public class VfResourceStructure extends ResourceStructure {
public List<IVfModuleData> decodeVfModuleArtifact(byte[] arg0) {
try {
- List<IVfModuleData> listVFModuleMetaData = new ObjectMapper()
- .readValue(arg0, new TypeReference<List<VfModuleMetaData>>() {
- });
+ List<IVfModuleData> listVFModuleMetaData =
+ new ObjectMapper().readValue(arg0, new TypeReference<List<VfModuleMetaData>>() {});
return listVFModuleMetaData;
} catch (JsonParseException e) {
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java
index 8daa708ee7..c98fb9b619 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java
@@ -55,59 +55,56 @@ import org.springframework.stereotype.Component;
@Component
public class BpmnInstaller {
- protected static final Logger logger = LoggerFactory.getLogger(BpmnInstaller.class);
- private static final String BPMN_SUFFIX = ".bpmn";
- private static final String CAMUNDA_URL = "mso.camundaURL";
- private static final String CREATE_DEPLOYMENT_PATH = "/sobpmnengine/deployment/create";
-
- @Autowired
- private Environment env;
-
- public void installBpmn(String csarFilePath) {
- logger.info("Deploying BPMN files from {}", csarFilePath);
- try {
- ZipInputStream csarFile = new ZipInputStream(new FileInputStream(Paths.get(csarFilePath).normalize().toString()));
- ZipEntry entry = csarFile.getNextEntry();
-
- while (entry != null) {
- String name = entry.getName();
- if (name.endsWith(BPMN_SUFFIX)) {
- logger.debug("Attempting to deploy BPMN file: {}", name);
- try {
- Path p = Paths.get(name);
- String fileName = p.getFileName().toString();
- extractBpmnFileFromCsar(csarFile, fileName);
- HttpResponse response = sendDeploymentRequest(fileName);
- logger.debug("Response status line: {}", response.getStatusLine());
- logger.debug("Response entity: {}", response.getEntity().toString());
- if (response.getStatusLine().getStatusCode() != 200) {
- logger.debug("Failed deploying BPMN {}", name);
- logger
- .error("{} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), name, fileName,
- Integer.toString(response.getStatusLine().getStatusCode()), ErrorCode.DataError.getValue(),
- "ASDC BPMN deploy failed");
- }
- else {
- logger.debug("Successfully deployed to Camunda: {}", name);
- }
- }
- catch (Exception e) {
- logger.debug("Exception :", e);
- logger
- .error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), name, e.getMessage(),
- ErrorCode.DataError.getValue(), "ASDC BPMN deploy failed");
- }
- }
- entry = csarFile.getNextEntry();
- }
- csarFile.close();
- } catch (IOException ex) {
- logger.debug("Exception :", ex);
- logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), csarFilePath,
- ex.getMessage(), ErrorCode.DataError.getValue(), "ASDC reading CSAR with workflows failed");
- }
- return;
- }
+ protected static final Logger logger = LoggerFactory.getLogger(BpmnInstaller.class);
+ private static final String BPMN_SUFFIX = ".bpmn";
+ private static final String CAMUNDA_URL = "mso.camundaURL";
+ private static final String CREATE_DEPLOYMENT_PATH = "/sobpmnengine/deployment/create";
+
+ @Autowired
+ private Environment env;
+
+ public void installBpmn(String csarFilePath) {
+ logger.info("Deploying BPMN files from {}", csarFilePath);
+ try {
+ ZipInputStream csarFile =
+ new ZipInputStream(new FileInputStream(Paths.get(csarFilePath).normalize().toString()));
+ ZipEntry entry = csarFile.getNextEntry();
+
+ while (entry != null) {
+ String name = entry.getName();
+ if (name.endsWith(BPMN_SUFFIX)) {
+ logger.debug("Attempting to deploy BPMN file: {}", name);
+ try {
+ Path p = Paths.get(name);
+ String fileName = p.getFileName().toString();
+ extractBpmnFileFromCsar(csarFile, fileName);
+ HttpResponse response = sendDeploymentRequest(fileName);
+ logger.debug("Response status line: {}", response.getStatusLine());
+ logger.debug("Response entity: {}", response.getEntity().toString());
+ if (response.getStatusLine().getStatusCode() != 200) {
+ logger.debug("Failed deploying BPMN {}", name);
+ logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(),
+ name, fileName, Integer.toString(response.getStatusLine().getStatusCode()),
+ ErrorCode.DataError.getValue(), "ASDC BPMN deploy failed");
+ } else {
+ logger.debug("Successfully deployed to Camunda: {}", name);
+ }
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), name,
+ e.getMessage(), ErrorCode.DataError.getValue(), "ASDC BPMN deploy failed");
+ }
+ }
+ entry = csarFile.getNextEntry();
+ }
+ csarFile.close();
+ } catch (IOException ex) {
+ logger.debug("Exception :", ex);
+ logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), csarFilePath,
+ ex.getMessage(), ErrorCode.DataError.getValue(), "ASDC reading CSAR with workflows failed");
+ }
+ return;
+ }
public boolean containsWorkflows(String csarFilePath) {
boolean workflowsInCsar = false;
@@ -121,74 +118,79 @@ public class BpmnInstaller {
}
}
} catch (Exception e) {
- logger.debug("Exception :", e);
- logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), csarFilePath, e.getMessage(),
- ErrorCode.DataError.getValue(), "ASDC Unable to check CSAR entries");
- }
+ logger.debug("Exception :", e);
+ logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), csarFilePath, e.getMessage(),
+ ErrorCode.DataError.getValue(), "ASDC Unable to check CSAR entries");
+ }
return workflowsInCsar;
}
- protected HttpResponse sendDeploymentRequest(String bpmnFileName) throws Exception {
- HttpClient client = HttpClientBuilder.create().build();
- URI deploymentUri = new URI(this.env.getProperty(CAMUNDA_URL) + CREATE_DEPLOYMENT_PATH);
- HttpPost post = new HttpPost(deploymentUri);
- RequestConfig requestConfig =
- RequestConfig.custom().setSocketTimeout(1000000).setConnectTimeout(1000).setConnectionRequestTimeout(1000).build();
- post.setConfig(requestConfig);
- HttpEntity requestEntity = buildMimeMultipart(bpmnFileName);
- post.setEntity(requestEntity);
- return client.execute(post);
- }
-
- protected HttpEntity buildMimeMultipart(String bpmnFileName) throws Exception {
- FileInputStream bpmnFileStream = new FileInputStream (Paths.get(System.getProperty("mso.config.path"),"ASDC", bpmnFileName).normalize().toString());
+ protected HttpResponse sendDeploymentRequest(String bpmnFileName) throws Exception {
+ HttpClient client = HttpClientBuilder.create().build();
+ URI deploymentUri = new URI(this.env.getProperty(CAMUNDA_URL) + CREATE_DEPLOYMENT_PATH);
+ HttpPost post = new HttpPost(deploymentUri);
+ RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000000).setConnectTimeout(1000)
+ .setConnectionRequestTimeout(1000).build();
+ post.setConfig(requestConfig);
+ HttpEntity requestEntity = buildMimeMultipart(bpmnFileName);
+ post.setEntity(requestEntity);
+ return client.execute(post);
+ }
+
+ protected HttpEntity buildMimeMultipart(String bpmnFileName) throws Exception {
+ FileInputStream bpmnFileStream = new FileInputStream(
+ Paths.get(System.getProperty("mso.config.path"), "ASDC", bpmnFileName).normalize().toString());
- byte[] bytesToSend = IOUtils.toByteArray(bpmnFileStream);
- HttpEntity requestEntity = MultipartEntityBuilder.create()
- .addPart(FormBodyPartBuilder.create()
- .setName("deployment-name")
- .setBody(new StringBody("MSO Sample 1", ContentType.TEXT_PLAIN))
- .setField("Content-Disposition", String.format("form-data; name=\"%s\"", "deployment-name"))
- .build())
- .addPart(FormBodyPartBuilder.create()
- .setName("enable-duplicate-filtering")
- .setBody(new StringBody("false", ContentType.TEXT_PLAIN))
- .setField("Content-Disposition", String.format("form-data; name=\"%s\"", "enable-duplicate-filtering"))
- .build())
- .addPart(FormBodyPartBuilder.create()
- .setName("deplpy-changed-only")
- .setBody(new StringBody("false", ContentType.TEXT_PLAIN))
- .setField("Content-Disposition", String.format("form-data; name=\"%s\"", "deploy-changed-only"))
- .build())
- .addPart(FormBodyPartBuilder.create()
- .setName("deployment-source")
- .setBody(new StringBody("local", ContentType.TEXT_PLAIN))
- .setField("Content-Disposition", String.format("form-data; name=\"%s\"", "deployment-source"))
- .build())
- .addPart(FormBodyPartBuilder.create()
- .setName(bpmnFileName)
- .setBody(new ByteArrayBody(bytesToSend, ContentType.create("octet"), bpmnFileName))
- .setField("Content-Disposition", String.format("form-data; name=\"%s\"; filename=\"%s\"; size=%d", bpmnFileName, bpmnFileName, bytesToSend.length))
- .build())
- .build();
-
- IOUtils.closeQuietly(bpmnFileStream);
- return requestEntity;
- }
-
- /* protected void extractBpmnFileFromCsar(ZipInputStream zipIn, String fileName) throws IOException */
- protected void extractBpmnFileFromCsar(ZipInputStream zipIn, String fileName) {
- String filePath = Paths.get(System.getProperty("mso.config.path"), "ASDC", fileName).normalize().toString();
- /* BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath)); */
- try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath))){
- byte[] bytesIn = new byte[4096];
- int read = 0;
- while ((read = zipIn.read(bytesIn)) != -1) {
- outputStream.write(bytesIn, 0, read);
- }
- /* outputStream.close(); */
- } catch (IOException e) {
- logger.error("Unable to open file.", e);
+ byte[] bytesToSend = IOUtils.toByteArray(bpmnFileStream);
+ HttpEntity requestEntity =
+ MultipartEntityBuilder.create()
+ .addPart(FormBodyPartBuilder.create().setName("deployment-name")
+ .setBody(new StringBody("MSO Sample 1", ContentType.TEXT_PLAIN))
+ .setField("Content-Disposition",
+ String.format("form-data; name=\"%s\"", "deployment-name"))
+ .build())
+ .addPart(FormBodyPartBuilder.create().setName("enable-duplicate-filtering")
+ .setBody(new StringBody("false", ContentType.TEXT_PLAIN))
+ .setField("Content-Disposition",
+ String.format("form-data; name=\"%s\"", "enable-duplicate-filtering"))
+ .build())
+ .addPart(FormBodyPartBuilder.create().setName("deplpy-changed-only")
+ .setBody(new StringBody("false", ContentType.TEXT_PLAIN))
+ .setField("Content-Disposition",
+ String.format("form-data; name=\"%s\"", "deploy-changed-only"))
+ .build())
+ .addPart(FormBodyPartBuilder.create().setName("deployment-source")
+ .setBody(new StringBody("local", ContentType.TEXT_PLAIN))
+ .setField("Content-Disposition",
+ String.format("form-data; name=\"%s\"", "deployment-source"))
+ .build())
+ .addPart(
+ FormBodyPartBuilder.create().setName(bpmnFileName)
+ .setBody(new ByteArrayBody(bytesToSend, ContentType.create("octet"),
+ bpmnFileName))
+ .setField("Content-Disposition",
+ String.format("form-data; name=\"%s\"; filename=\"%s\"; size=%d",
+ bpmnFileName, bpmnFileName, bytesToSend.length))
+ .build())
+ .build();
+
+ IOUtils.closeQuietly(bpmnFileStream);
+ return requestEntity;
+ }
+
+ /* protected void extractBpmnFileFromCsar(ZipInputStream zipIn, String fileName) throws IOException */
+ protected void extractBpmnFileFromCsar(ZipInputStream zipIn, String fileName) {
+ String filePath = Paths.get(System.getProperty("mso.config.path"), "ASDC", fileName).normalize().toString();
+ /* BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath)); */
+ try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath))) {
+ byte[] bytesIn = new byte[4096];
+ int read = 0;
+ while ((read = zipIn.read(bytesIn)) != -1) {
+ outputStream.write(bytesIn, 0, read);
+ }
+ /* outputStream.close(); */
+ } catch (IOException e) {
+ logger.error("Unable to open file.", e);
}
- }
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java
index 04e3782bbe..0e30b77b01 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java
@@ -35,7 +35,6 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
-
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.LockAcquisitionException;
import org.onap.sdc.api.notification.IArtifactInfo;
@@ -141,2264 +140,2332 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class ToscaResourceInstaller {
- protected static final String NODES_VRF_ENTRY = "org.openecomp.nodes.VRFEntry";
-
- protected static final String VLAN_NETWORK_RECEPTOR = "org.openecomp.nodes.VLANNetworkReceptor";
-
- protected static final String ALLOTTED_RESOURCE = "Allotted Resource";
-
- protected static final String MULTI_STAGE_DESIGN = "multi_stage_design";
-
- protected static final String SCALABLE = "scalable";
-
- protected static final String BASIC = "BASIC";
-
- protected static final String PROVIDER = "PROVIDER";
-
- protected static final String HEAT = "HEAT";
-
- protected static final String MANUAL_RECORD = "MANUAL_RECORD";
-
- protected static final String MSO = "SO";
-
- protected static final String SDNC_MODEL_NAME = "sdnc_model_name";
-
- protected static final String SDNC_MODEL_VERSION = "sdnc_model_version";
-
- private static String CUSTOMIZATION_UUID = "customizationUUID";
-
- protected static final String SKIP_POST_INST_CONF = "skip_post_instantiation_configuration";
-
- @Autowired
- protected ServiceRepository serviceRepo;
-
- @Autowired
- protected InstanceGroupRepository instanceGroupRepo;
-
- @Autowired
- protected ServiceProxyResourceCustomizationRepository serviceProxyCustomizationRepo;
-
- @Autowired
- protected CollectionResourceRepository collectionRepo;
-
- @Autowired
- protected CollectionResourceCustomizationRepository collectionCustomizationRepo;
-
- @Autowired
- protected ConfigurationResourceCustomizationRepository configCustomizationRepo;
-
- @Autowired
- protected ConfigurationResourceRepository configRepo;
-
- @Autowired
- protected VnfResourceRepository vnfRepo;
-
- @Autowired
- protected VFModuleRepository vfModuleRepo;
-
- @Autowired
- protected VFModuleCustomizationRepository vfModuleCustomizationRepo;
-
- @Autowired
- protected VnfcInstanceGroupCustomizationRepository vnfcInstanceGroupCustomizationRepo;
-
- @Autowired
- protected VnfcCustomizationRepository vnfcCustomizationRepo;
-
- @Autowired
- protected CvnfcCustomizationRepository cvnfcCustomizationRepo;
-
- @Autowired
- protected AllottedResourceRepository allottedRepo;
-
- @Autowired
- protected AllottedResourceCustomizationRepository allottedCustomizationRepo;
-
- @Autowired
- protected NetworkResourceRepository networkRepo;
-
- @Autowired
- protected HeatTemplateRepository heatRepo;
-
- @Autowired
- protected NetworkResourceCustomizationRepository networkCustomizationRepo;
-
- @Autowired
- protected WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository;
- @Autowired
- protected WatchdogDistributionStatusRepository watchdogDistributionStatusRepository;
- @Autowired
- protected WatchdogServiceModVerIdLookupRepository watchdogModVerIdLookupRepository;
-
- @Autowired
- protected TempNetworkHeatTemplateRepository tempNetworkLookupRepo;
-
- @Autowired
- protected ExternalServiceToInternalServiceRepository externalServiceToInternalServiceRepository;
-
- @Autowired
- protected PnfResourceRepository pnfResourceRepository;
-
- @Autowired
- protected PnfCustomizationRepository pnfCustomizationRepository;
-
- protected static final Logger logger = LoggerFactory.getLogger(ToscaResourceInstaller.class);
-
- public boolean isResourceAlreadyDeployed(VfResourceStructure vfResourceStruct) throws ArtifactInstallerException {
- boolean status = false;
- VfResourceStructure vfResourceStructure = vfResourceStruct;
- try {
- status = vfResourceStructure.isDeployedSuccessfully();
- } catch (RuntimeException e) {
- status = false;
- }
- try {
- Service existingService = serviceRepo.findOneByModelUUID(vfResourceStructure.getNotification().getServiceUUID());
- if(existingService != null)
- status = true;
- if (status) {
- logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(),
- vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(),
- vfResourceStructure.getNotification().getServiceName(),
- BigDecimalVersion.castAndCheckNotificationVersionToString(
- vfResourceStructure.getNotification().getServiceVersion()),
- vfResourceStructure.getNotification().getServiceUUID(),
- vfResourceStructure.getResourceInstance().getResourceName(), "", "");
- WatchdogComponentDistributionStatus wdStatus = new WatchdogComponentDistributionStatus(vfResourceStruct.getNotification().getDistributionID(), MSO);
- wdStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
- watchdogCDStatusRepository.saveAndFlush(wdStatus);
- } else {
- logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(),
- vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(),
- vfResourceStructure.getNotification().getServiceName(),
- BigDecimalVersion.castAndCheckNotificationVersionToString(
- vfResourceStructure.getNotification().getServiceVersion()),
- vfResourceStructure.getNotification().getServiceUUID(),
- vfResourceStructure.getResourceInstance().getResourceName(), "", "");
- }
- return status;
- } catch (Exception e) {
- logger
- .error("{} {} {}", MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), ErrorCode.SchemaError.getValue(),
- "Exception - isResourceAlreadyDeployed");
- throw new ArtifactInstallerException("Exception caught during checking existence of the VNF Resource.", e);
- }
- }
-
- public void installTheComponentStatus(IStatusData iStatus) throws ArtifactInstallerException {
- logger.debug("Entering installTheComponentStatus for distributionId {} and ComponentName {}",
- iStatus.getDistributionID(), iStatus.getComponentName());
-
- try {
- WatchdogComponentDistributionStatus cdStatus = new WatchdogComponentDistributionStatus(iStatus.getDistributionID(),
- iStatus.getComponentName());
- cdStatus.setComponentDistributionStatus(iStatus.getStatus().toString());
- watchdogCDStatusRepository.save(cdStatus);
-
- } catch (Exception e) {
- logger.debug("Exception caught in installTheComponentStatus {}", e.getMessage());
- throw new ArtifactInstallerException("Exception caught in installTheComponentStatus " + e.getMessage());
- }
- }
-
- @Transactional(rollbackFor = {ArtifactInstallerException.class})
- public void installTheResource(ToscaResourceStructure toscaResourceStruct, ResourceStructure resourceStruct)
- throws ArtifactInstallerException {
- if (resourceStruct instanceof VfResourceStructure) {
- installTheVfResource(toscaResourceStruct, (VfResourceStructure) resourceStruct);
- } else if (resourceStruct instanceof PnfResourceStructure) {
- installPnfResource(toscaResourceStruct, (PnfResourceStructure) resourceStruct);
- } else {
- logger.warn("Unrecognized resource type");
- }
- }
-
- private void installPnfResource(ToscaResourceStructure toscaResourceStruct, PnfResourceStructure resourceStruct)
- throws ArtifactInstallerException {
-
- // PCLO: in case of deployment failure, use a string that will represent
- // the type of artifact that failed...
- List<ASDCElementInfo> artifactListForLogging = new ArrayList<>();
- try {
- createToscaCsar(toscaResourceStruct);
- Service service = createService(toscaResourceStruct, resourceStruct);
-
- processResourceSequence(toscaResourceStruct, service);
- processPnfResources(toscaResourceStruct, service, resourceStruct);
- serviceRepo.save(service);
-
- WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(
- resourceStruct.getNotification().getDistributionID(), MSO);
- status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
- watchdogCDStatusRepository.save(status);
-
- toscaResourceStruct.setSuccessfulDeployment();
-
- } catch (Exception e) {
- logger.debug("Exception :", e);
- WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(
- resourceStruct.getNotification().getDistributionID(), MSO);
- status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name());
- watchdogCDStatusRepository.save(status);
- Throwable dbExceptionToCapture = e;
- while (!(dbExceptionToCapture instanceof ConstraintViolationException
- || dbExceptionToCapture instanceof LockAcquisitionException)
- && (dbExceptionToCapture.getCause() != null)) {
- dbExceptionToCapture = dbExceptionToCapture.getCause();
- }
-
- if (dbExceptionToCapture instanceof ConstraintViolationException
- || dbExceptionToCapture instanceof LockAcquisitionException) {
- logger.warn("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(),
- resourceStruct.getResourceInstance().getResourceName(),
- resourceStruct.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(),
- "Exception - ASCDC Artifact already deployed", e);
- } else {
- String elementToLog = (!artifactListForLogging.isEmpty()
- ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString()
- : "No element listed");
- logger.error("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog,
- ErrorCode.DataError.getValue(),
- "Exception caught during installation of " + resourceStruct.getResourceInstance()
- .getResourceName()
- + ". Transaction rollback", e);
- throw new ArtifactInstallerException("Exception caught during installation of "
- + resourceStruct.getResourceInstance().getResourceName() + ". Transaction rollback.", e);
- }
- }
- }
- @Transactional(rollbackFor = { ArtifactInstallerException.class })
- public void installTheVfResource(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStruct)
- throws ArtifactInstallerException {
- VfResourceStructure vfResourceStructure = vfResourceStruct;
- extractHeatInformation(toscaResourceStruct, vfResourceStructure);
-
- // PCLO: in case of deployment failure, use a string that will represent
- // the type of artifact that failed...
- List<ASDCElementInfo> artifactListForLogging = new ArrayList<>();
- try {
- createToscaCsar(toscaResourceStruct);
- Service service = createService(toscaResourceStruct, vfResourceStruct);
- List<NodeTemplate> vfNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceVfList();
-
-
- for (NodeTemplate nodeTemplate : vfNodeTemplatesList) {
-
- Metadata metadata = nodeTemplate.getMetaData();
- String serviceType = toscaResourceStruct.getCatalogService().getServiceType();
- String vfCustomizationCategory = toscaResourceStruct.getSdcCsarHelper()
- .getMetadataPropertyValue(metadata, SdcPropertyNames.PROPERTY_NAME_CATEGORY);
- processVfModules(toscaResourceStruct, vfResourceStructure, service, nodeTemplate, metadata,
- vfCustomizationCategory);
- }
-
- processResourceSequence(toscaResourceStruct, service);
- processVFResources(toscaResourceStruct, service, vfResourceStructure);
- List<NodeTemplate> allottedResourceList = toscaResourceStruct.getSdcCsarHelper().getAllottedResources();
- processAllottedResources(toscaResourceStruct, service, allottedResourceList);
- processNetworks(toscaResourceStruct, service);
- // process Network Collections
- processNetworkCollections(toscaResourceStruct, service);
- // Process Service Proxy & Configuration
- processServiceProxyAndConfiguration(toscaResourceStruct, service);
-
- serviceRepo.save(service);
-
- WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(vfResourceStruct.getNotification().getDistributionID(), MSO);
- status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
- watchdogCDStatusRepository.save(status);
-
- toscaResourceStruct.setSuccessfulDeployment();
-
- } catch (Exception e) {
- logger.debug("Exception :", e);
- WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(vfResourceStruct.getNotification().getDistributionID(), MSO);
- status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name());
- watchdogCDStatusRepository.save(status);
- Throwable dbExceptionToCapture = e;
- while (!(dbExceptionToCapture instanceof ConstraintViolationException
- || dbExceptionToCapture instanceof LockAcquisitionException)
- && (dbExceptionToCapture.getCause() != null)) {
- dbExceptionToCapture = dbExceptionToCapture.getCause();
- }
-
- if (dbExceptionToCapture instanceof ConstraintViolationException
- || dbExceptionToCapture instanceof LockAcquisitionException) {
- logger.warn("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(),
- vfResourceStructure.getResourceInstance().getResourceName(),
- vfResourceStructure.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(),
- "Exception - ASCDC Artifact already deployed", e);
- } else {
- String elementToLog = (!artifactListForLogging.isEmpty()
- ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString()
- : "No element listed");
- logger.error("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog,
- ErrorCode.DataError.getValue(),
- "Exception caught during installation of " + vfResourceStructure.getResourceInstance().getResourceName()
- + ". Transaction rollback", e);
- throw new ArtifactInstallerException("Exception caught during installation of "
- + vfResourceStructure.getResourceInstance().getResourceName() + ". Transaction rollback.", e);
- }
- }
- }
-
-
- List<NodeTemplate> getRequirementList(List<NodeTemplate> resultList, List<NodeTemplate> nodeTemplates,
- ISdcCsarHelper iSdcCsarHelper) {
-
- List<NodeTemplate> nodes = new ArrayList<NodeTemplate>();
- nodes.addAll(nodeTemplates);
-
- for (NodeTemplate nodeTemplate : nodeTemplates) {
- RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate);
- List<RequirementAssignment> reqAs = requirement.getAll();
- for (RequirementAssignment ra : reqAs) {
- String reqNode = ra.getNodeTemplateName();
- for (NodeTemplate rNode : resultList) {
- if (rNode.getName().equals(reqNode)) {
- if(!resultList.contains(nodeTemplate)) {
- resultList.add(nodeTemplate);
- }
- if(nodes.contains(nodeTemplate)) {
- nodes.remove(nodeTemplate);
- }
- break;
- }
- }
- }
- }
-
- if (!nodes.isEmpty()) {
- getRequirementList(resultList, nodes, iSdcCsarHelper);
- }
-
- return resultList;
- }
-
- // This method retrieve resource sequence from csar file
- void processResourceSequence(ToscaResourceStructure toscaResourceStructure, Service service) {
- List<String> resouceSequence = new ArrayList<String>();
- List<NodeTemplate> resultList = new ArrayList<NodeTemplate>();
-
- ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper();
- List<NodeTemplate> nodeTemplates = iSdcCsarHelper.getServiceNodeTemplates();
- List<NodeTemplate> nodes = new ArrayList<NodeTemplate>();
- nodes.addAll(nodeTemplates);
-
- for (NodeTemplate nodeTemplate : nodeTemplates) {
- RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate);
-
- if (requirement == null || requirement.getAll() == null || requirement.getAll().isEmpty()) {
- resultList.add(nodeTemplate);
- nodes.remove(nodeTemplate);
- }
- }
-
- resultList = getRequirementList(resultList, nodes, iSdcCsarHelper);
-
- for (NodeTemplate node : resultList) {
- String templateName = node.getMetaData().getValue("name");
- if (!resouceSequence.contains(templateName)) {
- resouceSequence.add(templateName);
- }
- }
-
- String resourceSeqStr = resouceSequence.stream().collect(Collectors.joining(","));
- service.setResourceOrder(resourceSeqStr);
- logger.debug(" resourceSeq for service uuid(" + service.getModelUUID() + ") : " + resourceSeqStr);
- }
-
- private static String getValue(Object value, List<Input> servInputs) {
- String output = null;
- if(value instanceof Map) {
- // currently this logic handles only one level of nesting.
- return ((LinkedHashMap) value).values().toArray()[0].toString();
- } else if(value instanceof GetInput) {
- String inputName = ((GetInput)value).getInputName();
-
- for(Input input : servInputs) {
- if(input.getName().equals(inputName)) {
- // keep both input name and default value
- // if service input does not supplies value the use default value
- String defaultValue = input.getDefault() != null ? (String) input.getDefault().toString() : "";
- output = inputName + "|" + defaultValue;// return default value
- }
- }
-
- } else {
- output = value != null ? value.toString() : "";
- }
- return output; // return property value
- }
-
- String getResourceInput(ToscaResourceStructure toscaResourceStructure, String resourceCustomizationUuid) throws ArtifactInstallerException {
- Map<String, String> resouceRequest = new HashMap<>();
- ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper();
-
- List<Input> serInput = iSdcCsarHelper.getServiceInputs();
- Optional<NodeTemplate> nodeTemplateOpt = iSdcCsarHelper.getServiceNodeTemplates().stream()
- .filter(e -> e.getMetaData().getValue(CUSTOMIZATION_UUID).equals(resourceCustomizationUuid)).findFirst();
- if(nodeTemplateOpt.isPresent()) {
- NodeTemplate nodeTemplate = nodeTemplateOpt.get();
- LinkedHashMap<String, Property> resourceProperties = nodeTemplate.getProperties();
-
- for(String key : resourceProperties.keySet()) {
- Property property = resourceProperties.get(key);
-
- String value = getValue(property.getValue(), serInput);
- resouceRequest.put(key, value);
- }
- }
-
- try {
- ObjectMapper objectMapper = new ObjectMapper();
- String jsonStr = objectMapper.writeValueAsString(resouceRequest);
-
- jsonStr = jsonStr.replace("\"", "\\\"");
- logger.debug("resource request for resource customization id (" + resourceCustomizationUuid + ") : " + jsonStr);
- return jsonStr;
- } catch (JsonProcessingException e) {
- logger.error("resource input could not be deserialized for resource customization id ("
- + resourceCustomizationUuid + ")");
- throw new ArtifactInstallerException("resource input could not be parsed", e);
- }
- }
-
- protected void processNetworks (ToscaResourceStructure toscaResourceStruct,
- Service service) throws ArtifactInstallerException {
- List <NodeTemplate> nodeTemplatesVLList = toscaResourceStruct.getSdcCsarHelper ().getServiceVlList ();
-
- if (nodeTemplatesVLList != null) {
- for (NodeTemplate vlNode : nodeTemplatesVLList) {
- String networkResourceModelName = vlNode.getMetaData ().getValue (SdcPropertyNames.PROPERTY_NAME_NAME);
-
- TempNetworkHeatTemplateLookup tempNetworkLookUp =
- tempNetworkLookupRepo.findFirstBynetworkResourceModelName (networkResourceModelName);
-
- if (tempNetworkLookUp != null) {
- HeatTemplate heatTemplate =
- heatRepo.findByArtifactUuid (tempNetworkLookUp.getHeatTemplateArtifactUuid ());
- if (heatTemplate != null) {
- NetworkResourceCustomization networkCustomization =
- createNetwork (vlNode,
- toscaResourceStruct,
- heatTemplate,
- tempNetworkLookUp.getAicVersionMax (),
- tempNetworkLookUp.getAicVersionMin (),
- service);
- service.getNetworkCustomizations ().add (networkCustomization);
- } else {
- throw new ArtifactInstallerException ("No HeatTemplate found for artifactUUID: "
- + tempNetworkLookUp.getHeatTemplateArtifactUuid ());
- }
- } else {
- NetworkResourceCustomization networkCustomization = createNetwork (vlNode,
- toscaResourceStruct,
- null,
- null,
- null,
- service);
- service.getNetworkCustomizations().add (networkCustomization);
- logger.debug ("No NetworkResourceName found in TempNetworkHeatTemplateLookup for "
- + networkResourceModelName);
- }
-
- }
- }
- }
-
- protected void processAllottedResources(ToscaResourceStructure toscaResourceStruct, Service service,
- List<NodeTemplate> allottedResourceList) {
- if (allottedResourceList != null) {
- for (NodeTemplate allottedNode : allottedResourceList) {
- service.getAllottedCustomizations()
- .add(createAllottedResource(allottedNode, toscaResourceStruct, service));
- }
- }
- }
-
-
- protected ConfigurationResource getConfigurationResource(NodeTemplate nodeTemplate) {
- Metadata metadata = nodeTemplate.getMetaData();
- ConfigurationResource configResource = new ConfigurationResource();
- configResource.setModelName(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- configResource.setModelInvariantUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- configResource.setModelUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- configResource.setModelVersion(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- configResource.setDescription(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
- configResource.setToscaNodeType(nodeTemplate.getType());
- return configResource;
- }
-
- protected ConfigurationResourceCustomization getConfigurationResourceCustomization(NodeTemplate nodeTemplate, ToscaResourceStructure toscaResourceStructure,
- ServiceProxyResourceCustomization spResourceCustomization ) {
- Metadata metadata = nodeTemplate.getMetaData();
-
- ConfigurationResource configResource = getConfigurationResource(nodeTemplate);
-
- ConfigurationResourceCustomization configCustomizationResource = new ConfigurationResourceCustomization();
-
- Set<ConfigurationResourceCustomization> configResourceCustomizationSet = new HashSet<>();
-
- configCustomizationResource.setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
- configCustomizationResource.setModelInstanceName(nodeTemplate.getName());
-
- configCustomizationResource.setNfFunction(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
- configCustomizationResource.setNfRole(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE));
- configCustomizationResource.setNfType(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE));
- configCustomizationResource.setServiceProxyResourceCustomizationUUID(spResourceCustomization.getModelCustomizationUUID());
-
- configCustomizationResource.setConfigurationResource(configResource);
- configResourceCustomizationSet.add(configCustomizationResource);
-
- configResource.setConfigurationResourceCustomization(configResourceCustomizationSet);
- return configCustomizationResource;
- }
-
-
- protected Optional<ConfigurationResourceCustomization> getVnrNodeTemplate(List<NodeTemplate> configurationNodeTemplatesList,
- ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization) {
- Optional<ConfigurationResourceCustomization> configurationResourceCust = Optional.empty();
- for (NodeTemplate nodeTemplate : configurationNodeTemplatesList) {
- StatefulEntityType entityType = nodeTemplate.getTypeDefinition();
- String type = entityType.getType();
-
- if(VLAN_NETWORK_RECEPTOR.equals(type)) {
- configurationResourceCust= Optional.of(getConfigurationResourceCustomization(nodeTemplate,
- toscaResourceStructure,spResourceCustomization));
- break;
- }
- }
-
- return configurationResourceCust;
- }
-
- protected void processServiceProxyAndConfiguration(ToscaResourceStructure toscaResourceStruct, Service service) {
-
- List<NodeTemplate> serviceProxyResourceList = toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.SERVICE_PROXY);
-
- List<NodeTemplate> configurationNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION);
-
- List<ServiceProxyResourceCustomization> serviceProxyList = new ArrayList<ServiceProxyResourceCustomization>();
- List<ConfigurationResourceCustomization> configurationResourceList = new ArrayList<ConfigurationResourceCustomization>();
-
- ServiceProxyResourceCustomization serviceProxy = null;
-
- if (serviceProxyResourceList != null) {
- for (NodeTemplate spNode : serviceProxyResourceList) {
- serviceProxy = createServiceProxy(spNode, service, toscaResourceStruct);
- serviceProxyList.add(serviceProxy);
- Optional<ConfigurationResourceCustomization> vnrResourceCustomization = getVnrNodeTemplate(configurationNodeTemplatesList,toscaResourceStruct,serviceProxy);
-
- for (NodeTemplate configNode : configurationNodeTemplatesList) {
-
- List<RequirementAssignment> requirementsList = toscaResourceStruct.getSdcCsarHelper().getRequirementsOf(configNode).getAll();
- for (RequirementAssignment requirement : requirementsList) {
- if (requirement.getNodeTemplateName().equals(spNode.getName())) {
- ConfigurationResourceCustomization configurationResource = createConfiguration(configNode, toscaResourceStruct, serviceProxy, vnrResourceCustomization);
-
- Optional<ConfigurationResourceCustomization> matchingObject = configurationResourceList.stream()
- .filter(configurationResourceCustomization -> configNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID).equals(configurationResource.getModelCustomizationUUID()))
- .findFirst();
- if(!matchingObject.isPresent()){
- configurationResourceList.add(configurationResource);
- }
-
- break;
- }
- }
- }
-
- }
- }
-
- service.setConfigurationCustomizations(configurationResourceList);
- service.setServiceProxyCustomizations(serviceProxyList);
- }
-
- protected void processNetworkCollections(ToscaResourceStructure toscaResourceStruct, Service service) {
-
- List<NodeTemplate> networkCollectionList = toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CR);
-
- if (networkCollectionList != null) {
- for (NodeTemplate crNode : networkCollectionList) {
-
- createNetworkCollection(crNode, toscaResourceStruct, service);
- collectionRepo.saveAndFlush(toscaResourceStruct.getCatalogCollectionResource());
-
- List<NetworkInstanceGroup> networkInstanceGroupList = toscaResourceStruct.getCatalogNetworkInstanceGroup();
- for(NetworkInstanceGroup networkInstanceGroup : networkInstanceGroupList){
- instanceGroupRepo.saveAndFlush(networkInstanceGroup);
- }
-
- }
- }
- service.getCollectionResourceCustomizations().add(toscaResourceStruct.getCatalogCollectionResourceCustomization());
- }
-
-
- protected void processVFResources (ToscaResourceStructure toscaResourceStruct, Service service, VfResourceStructure vfResourceStructure)
- throws Exception{
- logger.debug("processVFResources");
-
- List<NodeTemplate> vfNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceVfList();
-// String servicecategory = toscaResourceStruct.getCatalogService().getCategory();
-// String serviceType = toscaResourceStruct.getCatalogService().getServiceType();
-
- for (NodeTemplate nodeTemplate : vfNodeTemplatesList) {
- Metadata metadata = nodeTemplate.getMetaData();
- String vfCustomizationCategory = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY);
- logger.debug("VF Category is : " + vfCustomizationCategory);
-
- // Do not treat Allotted Resources as VNF resources
- if(ALLOTTED_RESOURCE.equalsIgnoreCase(vfCustomizationCategory)){
- continue;
- }
-
- String vfCustomizationUUID = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
- logger.debug("VFCustomizationUUID=" + vfCustomizationUUID);
-
- IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance();
-
- // Make sure the VF ResourceCustomizationUUID from the notification and tosca
- // customizations match before comparing their VF Modules UUID's
- logger.debug("Checking if Notification VF ResourceCustomizationUUID: "
- + vfNotificationResource.getResourceCustomizationUUID() + " matches Tosca VF Customization UUID: "
- + vfCustomizationUUID);
-
- if (vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())) {
- logger.debug("vfCustomizationUUID: " + vfCustomizationUUID
- + " matches vfNotificationResource CustomizationUUID");
-
- processVfModules(toscaResourceStruct, vfResourceStructure, service, nodeTemplate, metadata,
- vfCustomizationCategory);
- } else {
- logger.debug("Notification VF ResourceCustomizationUUID: "
- + vfNotificationResource.getResourceCustomizationUUID() + " doesn't match "
- + "Tosca VF Customization UUID: " + vfCustomizationUUID);
- }
- }
- }
-
- /**
- * This is used to process the PNF specific resource, including resource and resource_customization. {@link
- * IEntityDetails} based API is used to retrieve information. Please check {@link ISdcCsarHelper} for details.
- */
- protected void processPnfResources(ToscaResourceStructure toscaResourceStruct, Service service,
- PnfResourceStructure resourceStructure) throws Exception {
- logger.info("Processing PNF resource: {}", resourceStructure.getResourceInstance().getResourceUUID());
-
- ISdcCsarHelper sdcCsarHelper = toscaResourceStruct.getSdcCsarHelper();
- EntityQuery entityQuery = EntityQuery.newBuilder(SdcTypes.PNF).build();
- TopologyTemplateQuery topologyTemplateQuery = TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build();
-
- List<IEntityDetails> entityDetailsList = sdcCsarHelper.getEntity(entityQuery, topologyTemplateQuery, false);
- for (IEntityDetails entityDetails : entityDetailsList) {
- Metadata metadata = entityDetails.getMetadata();
- String customizationUUID = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
- String modelUuid = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID);
- String notifCustomizationUUID = resourceStructure.getResourceInstance().getResourceCustomizationUUID();
- if (customizationUUID != null && customizationUUID.equals(notifCustomizationUUID)) {
- logger.info("Resource customization UUID: {} is the same as notified resource customizationUUID: {}",
- customizationUUID, notifCustomizationUUID);
-
- if (checkExistingPnfResourceCutomization(customizationUUID)) {
- logger.info("Resource customization UUID: {} already deployed", customizationUUID);
- } else {
- PnfResource pnfResource = findExistingPnfResource(service, modelUuid);
- if (pnfResource == null) {
- pnfResource = createPnfResource(entityDetails);
- }
- PnfResourceCustomization pnfResourceCustomization = createPnfResourceCustomization(entityDetails,
- pnfResource);
- pnfResource.getPnfResourceCustomizations().add(pnfResourceCustomization);
- toscaResourceStruct.setPnfResourceCustomization(pnfResourceCustomization);
- service.getPnfCustomizations().add(pnfResourceCustomization);
- }
- } else {
- logger
- .warn("Resource customization UUID: {} is NOT the same as notified resource customizationUUID: {}",
- customizationUUID, notifCustomizationUUID);
- }
- }
- }
-
- private PnfResource findExistingPnfResource(Service service, String modelUuid) {
- PnfResource pnfResource = null;
- for (PnfResourceCustomization pnfResourceCustomization : service.getPnfCustomizations()) {
- if (pnfResourceCustomization.getPnfResources() != null && pnfResourceCustomization.getPnfResources()
- .getModelUUID().equals(modelUuid)) {
- pnfResource = pnfResourceCustomization.getPnfResources();
- }
- }
- if (pnfResource == null) {
- pnfResource = pnfResourceRepository.findById(modelUuid).orElse(pnfResource);
- }
- return pnfResource;
- }
-
- private boolean checkExistingPnfResourceCutomization(String customizationUUID) {
- return pnfCustomizationRepository.findById(customizationUUID).isPresent();
- }
-
- /**
- * Construct the {@link PnfResource} from {@link IEntityDetails} object.
- */
- private PnfResource createPnfResource(IEntityDetails entity) {
- PnfResource pnfResource = new PnfResource();
- Metadata metadata = entity.getMetadata();
- pnfResource.setModelInvariantUUID(
- testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
- pnfResource.setModelName(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
- pnfResource.setModelUUID(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
- pnfResource.setModelVersion(
- testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
- pnfResource.setDescription(
- testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
- pnfResource.setCategory(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)));
- pnfResource.setSubCategory(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)));
- pnfResource.setToscaNodeType(entity.getToscaType());
- return pnfResource;
- }
-
- /**
- * Construct the {@link PnfResourceCustomization} from {@link IEntityDetails} object.
- */
- private PnfResourceCustomization createPnfResourceCustomization(IEntityDetails entityDetails,
- PnfResource pnfResource) {
-
- PnfResourceCustomization pnfResourceCustomization = new PnfResourceCustomization();
- Metadata metadata = entityDetails.getMetadata();
- Map<String, Property> properties = entityDetails.getProperties();
- pnfResourceCustomization
- .setModelCustomizationUUID(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
- pnfResourceCustomization.setModelInstanceName(entityDetails.getName());
- pnfResourceCustomization
- .setNfFunction(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)));
- pnfResourceCustomization.setNfNamingCode(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFCODE)));
- pnfResourceCustomization.setNfRole(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFROLE)));
- pnfResourceCustomization.setNfType(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFTYPE)));
- pnfResourceCustomization.setMultiStageDesign(getStringValue(properties.get(MULTI_STAGE_DESIGN)));
- pnfResourceCustomization.setBlueprintName(getStringValue(properties.get(SDNC_MODEL_NAME)));
- pnfResourceCustomization.setBlueprintVersion(getStringValue(properties.get(SDNC_MODEL_VERSION)));
- pnfResourceCustomization.setSkipPostInstConf(getBooleanValue(properties.get(SKIP_POST_INST_CONF)));
- pnfResourceCustomization.setPnfResources(pnfResource);
-
- return pnfResourceCustomization;
- }
-
- /**
- * Get value from {@link Property} and cast to boolean value. Return true if property is null.
- */
- private boolean getBooleanValue(Property property) {
- if (null == property) {
- return true;
- }
- Object value = property.getValue();
- return new Boolean(String.valueOf(value));
- }
-
- /**
- * Get value from {@link Property} and cast to String value. Return empty String if property is null value.
- */
- private String getStringValue(Property property) {
- if (null == property) {
- return "";
- }
- Object value = property.getValue();
- return String.valueOf(value);
- }
-
- protected void processVfModules(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStructure,
- Service service, NodeTemplate nodeTemplate, Metadata metadata, String vfCustomizationCategory) throws Exception {
-
- logger.debug("VF Category is : " + vfCustomizationCategory);
-
- if(vfResourceStructure.getVfModuleStructure() != null && !vfResourceStructure.getVfModuleStructure().isEmpty())
- {
-
- String vfCustomizationUUID = toscaResourceStruct.getSdcCsarHelper()
- .getMetadataPropertyValue(metadata, SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
- logger.debug("VFCustomizationUUID=" + vfCustomizationUUID);
-
- IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance();
-
- // Make sure the VF ResourceCustomizationUUID from the notification and tosca customizations match before comparing their VF Modules UUID's
- logger.debug("Checking if Notification VF ResourceCustomizationUUID: " + vfNotificationResource.getResourceCustomizationUUID() +
- " matches Tosca VF Customization UUID: " + vfCustomizationUUID);
-
- if(vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())){
-
- logger.debug("vfCustomizationUUID: " + vfCustomizationUUID + " matches vfNotificationResource CustomizationUUID");
-
- VnfResourceCustomization vnfResource = createVnfResource(nodeTemplate, toscaResourceStruct, service);
-
- Set<CvnfcCustomization> existingCvnfcSet = new HashSet<CvnfcCustomization>();
- Set<VnfcCustomization> existingVnfcSet = new HashSet<VnfcCustomization>();
-
- for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) {
-
- logger.debug("vfModuleStructure:" + vfModuleStructure.toString());
- List<org.onap.sdc.toscaparser.api.Group> vfGroups = toscaResourceStruct
- .getSdcCsarHelper().getVfModulesByVf(vfCustomizationUUID);
- IVfModuleData vfMetadata = vfModuleStructure.getVfModuleMetadata();
-
- logger.debug("Comparing Vf_Modules_Metadata CustomizationUUID : " + vfMetadata.getVfModuleModelCustomizationUUID());
-
- Optional<org.onap.sdc.toscaparser.api.Group> matchingObject = vfGroups.stream()
- .peek(group -> logger.debug("To Csar Group VFModuleModelCustomizationUUID " + group.getMetadata().getValue("vfModuleModelCustomizationUUID")))
- .filter(group -> group.getMetadata().getValue("vfModuleModelCustomizationUUID").equals(vfMetadata.getVfModuleModelCustomizationUUID()))
- .findFirst();
- if(matchingObject.isPresent()){
- VfModuleCustomization vfModuleCustomization = createVFModuleResource(matchingObject.get(), nodeTemplate, toscaResourceStruct,
- vfResourceStructure,vfMetadata, vnfResource, service, existingCvnfcSet, existingVnfcSet);
- vfModuleCustomization.getVfModule().setVnfResources(vnfResource.getVnfResources());
- }else
- throw new Exception("Cannot find matching VFModule Customization in Csar for Vf_Modules_Metadata: " + vfMetadata.getVfModuleModelCustomizationUUID());
-
- }
-
-
- // Check for VNFC Instance Group info and add it if there is
- List<Group> groupList = toscaResourceStruct.getSdcCsarHelper()
- .getGroupsOfOriginOfNodeTemplateByToscaGroupType(nodeTemplate,
- "org.openecomp.groups.VfcInstanceGroup");
-
- for (Group group : groupList) {
- VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization = createVNFCInstanceGroup(nodeTemplate, group, vnfResource, toscaResourceStruct);
- vnfcInstanceGroupCustomizationRepo.saveAndFlush(vnfcInstanceGroupCustomization);
- }
-
-
- service.getVnfCustomizations().add(vnfResource);
- } else{
- logger.debug("Notification VF ResourceCustomizationUUID: " + vfNotificationResource.getResourceCustomizationUUID() + " doesn't match " +
- "Tosca VF Customization UUID: " + vfCustomizationUUID);
- }
- }
- }
-
- public void processWatchdog(String distributionId, String servideUUID, Optional<String> distributionNotification,
- String consumerId) {
- WatchdogServiceModVerIdLookup modVerIdLookup = new WatchdogServiceModVerIdLookup(distributionId, servideUUID,
- distributionNotification, consumerId);
- watchdogModVerIdLookupRepository.saveAndFlush(modVerIdLookup);
-
- try{
-
- WatchdogDistributionStatus distributionStatus = new WatchdogDistributionStatus(distributionId);
- watchdogDistributionStatusRepository.saveAndFlush(distributionStatus);
-
- } catch(ObjectOptimisticLockingFailureException e){
- logger.debug("ObjectOptimisticLockingFailureException in processWatchdog : " + e.toString());
- throw e;
- }
- }
-
- protected void extractHeatInformation(ToscaResourceStructure toscaResourceStruct,
- VfResourceStructure vfResourceStructure) {
- for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
-
- switch (vfModuleArtifact.getArtifactInfo().getArtifactType()) {
- case ASDCConfiguration.HEAT:
- case ASDCConfiguration.HEAT_NESTED:
- createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct,
- vfModuleArtifact);
- break;
- case ASDCConfiguration.HEAT_VOL:
- createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct,
- vfModuleArtifact);
- VfModuleArtifact envModuleArtifact = getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact);
- createHeatEnvFromArtifact(vfResourceStructure, envModuleArtifact);
- break;
- case ASDCConfiguration.HEAT_ENV:
- createHeatEnvFromArtifact(vfResourceStructure, vfModuleArtifact);
- break;
- case ASDCConfiguration.HEAT_ARTIFACT:
- createHeatFileFromArtifact(vfResourceStructure, vfModuleArtifact,
- toscaResourceStruct);
- break;
- case ASDCConfiguration.HEAT_NET:
- case ASDCConfiguration.OTHER:
- logger.warn("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_TYPE_NOT_SUPPORT.toString(),
- vfModuleArtifact.getArtifactInfo().getArtifactType() + "(Artifact Name:" + vfModuleArtifact.getArtifactInfo()
- .getArtifactName() + ")", ErrorCode.DataError.getValue(), "Artifact type not supported");
- break;
- default:
- break;
-
- }
- }
- }
-
- protected VfModuleArtifact getHeatEnvArtifactFromGeneratedArtifact(VfResourceStructure vfResourceStructure,
- VfModuleArtifact vfModuleArtifact) {
- String artifactName = vfModuleArtifact.getArtifactInfo().getArtifactName();
- artifactName = artifactName.substring(0, artifactName.indexOf('.'));
- for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
- if (moduleArtifact.getArtifactInfo().getArtifactName().contains(artifactName)
- && moduleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) {
- return moduleArtifact;
- }
- }
- return null;
- }
-
- public String verifyTheFilePrefixInArtifacts(String filebody, VfResourceStructure vfResourceStructure,
- List<String> listTypes) {
- String newFileBody = filebody;
- for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
-
- if (listTypes.contains(moduleArtifact.getArtifactInfo().getArtifactType())) {
-
- newFileBody = verifyTheFilePrefixInString(newFileBody,
- moduleArtifact.getArtifactInfo().getArtifactName());
- }
- }
- return newFileBody;
- }
-
- public String verifyTheFilePrefixInString(final String body, final String filenameToVerify) {
-
- String needlePrefix = "file:///";
- String prefixedFilenameToVerify = needlePrefix + filenameToVerify;
-
- if ((body == null) || (body.length() == 0) || (filenameToVerify == null) || (filenameToVerify.length() == 0)) {
- return body;
- }
-
- StringBuilder sb = new StringBuilder(body.length());
-
- int currentIndex = 0;
- int startIndex = 0;
-
- while (currentIndex != -1) {
- startIndex = currentIndex;
- currentIndex = body.indexOf(prefixedFilenameToVerify, startIndex);
-
- if (currentIndex == -1) {
- break;
- }
- // We append from the startIndex up to currentIndex (start of File
- // Name)
- sb.append(body.substring(startIndex, currentIndex));
- sb.append(filenameToVerify);
-
- currentIndex += prefixedFilenameToVerify.length();
- }
-
- sb.append(body.substring(startIndex));
-
- return sb.toString();
- }
-
- protected void createHeatTemplateFromArtifact(VfResourceStructure vfResourceStructure,
- ToscaResourceStructure toscaResourceStruct, VfModuleArtifact vfModuleArtifact) {
- HeatTemplate heatTemplate = new HeatTemplate();
- List<String> typeList = new ArrayList<>();
- typeList.add(ASDCConfiguration.HEAT_NESTED);
- typeList.add(ASDCConfiguration.HEAT_ARTIFACT);
-
- heatTemplate.setTemplateBody(
- verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList));
- heatTemplate.setTemplateName(vfModuleArtifact.getArtifactInfo().getArtifactName());
-
- if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) {
- heatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout());
- } else {
- heatTemplate.setTimeoutMinutes(240);
- }
-
- heatTemplate.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
- heatTemplate.setVersion(BigDecimalVersion
- .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
- heatTemplate.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
-
- if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
- heatTemplate.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
- } else {
- heatTemplate.setArtifactChecksum(MANUAL_RECORD);
- }
-
- Set<HeatTemplateParam> heatParam = extractHeatTemplateParameters(
- vfModuleArtifact.getResult(), vfModuleArtifact.getArtifactInfo().getArtifactUUID());
- heatTemplate.setParameters(heatParam);
- vfModuleArtifact.setHeatTemplate(heatTemplate);
- }
-
- protected void createHeatEnvFromArtifact(VfResourceStructure vfResourceStructure,
- VfModuleArtifact vfModuleArtifact) {
- HeatEnvironment heatEnvironment = new HeatEnvironment();
- heatEnvironment.setName(vfModuleArtifact.getArtifactInfo().getArtifactName());
- List<String> typeList = new ArrayList<>();
- typeList.add(ASDCConfiguration.HEAT);
- typeList.add(ASDCConfiguration.HEAT_VOL);
- heatEnvironment.setEnvironment(
- verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList));
- heatEnvironment.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
- heatEnvironment.setVersion(BigDecimalVersion
- .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
- heatEnvironment.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
-
- if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
- heatEnvironment.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
- } else {
- heatEnvironment.setArtifactChecksum(MANUAL_RECORD);
- }
- vfModuleArtifact.setHeatEnvironment(heatEnvironment);
- }
-
- protected void createHeatFileFromArtifact(VfResourceStructure vfResourceStructure,
- VfModuleArtifact vfModuleArtifact, ToscaResourceStructure toscaResourceStruct) {
-
- HeatFiles heatFile = new HeatFiles();
- heatFile.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
- heatFile.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
- heatFile.setFileBody(vfModuleArtifact.getResult());
- heatFile.setFileName(vfModuleArtifact.getArtifactInfo().getArtifactName());
- heatFile.setVersion(BigDecimalVersion
- .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
- toscaResourceStruct.setHeatFilesUUID(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
- if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
- heatFile.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
- } else {
- heatFile.setArtifactChecksum(MANUAL_RECORD);
- }
- vfModuleArtifact.setHeatFiles(heatFile);
- }
-
- protected Service createService(ToscaResourceStructure toscaResourceStructure,
- ResourceStructure resourceStructure) {
-
- Metadata serviceMetadata = toscaResourceStructure.getServiceMetadata();
-
- Service service = new Service();
-
- if (serviceMetadata != null) {
-
- if (toscaResourceStructure.getServiceVersion() != null) {
- service.setModelVersion(toscaResourceStructure.getServiceVersion());
- }
-
- service.setServiceType(serviceMetadata.getValue("serviceType"));
- service.setServiceRole(serviceMetadata.getValue("serviceRole"));
- service.setCategory(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY));
-
- service.setDescription(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
- service.setModelName(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- service.setModelUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- service.setEnvironmentContext(serviceMetadata.getValue("environmentContext"));
-
- if (resourceStructure != null)
- service.setWorkloadContext(resourceStructure.getNotification().getWorkloadContext());
-
- service.setModelInvariantUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- service.setCsar(toscaResourceStructure.getCatalogToscaCsar());
- }
-
-
- toscaResourceStructure.setCatalogService(service);
- return service;
- }
-
- protected ServiceProxyResourceCustomization createServiceProxy(NodeTemplate nodeTemplate, Service service, ToscaResourceStructure toscaResourceStructure) {
-
- Metadata spMetadata = nodeTemplate.getMetaData();
-
- ServiceProxyResourceCustomization spCustomizationResource = new ServiceProxyResourceCustomization();
-
- Set<ServiceProxyResourceCustomization> serviceProxyCustomizationSet = new HashSet<>();
-
- spCustomizationResource.setModelName(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- spCustomizationResource.setModelInvariantUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- spCustomizationResource.setModelUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- spCustomizationResource.setModelVersion(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- spCustomizationResource.setDescription(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
-
- spCustomizationResource.setModelCustomizationUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
- spCustomizationResource.setModelInstanceName(nodeTemplate.getName());
- spCustomizationResource.setToscaNodeType(nodeTemplate.getType());
-
- String sourceServiceUUID = spMetadata.getValue("sourceModelUuid");
-
- Service sourceService = serviceRepo.findOneByModelUUID(sourceServiceUUID);
-
- spCustomizationResource.setSourceService(sourceService);
- spCustomizationResource.setToscaNodeType(nodeTemplate.getType());
- serviceProxyCustomizationSet.add(spCustomizationResource);
-
-
- toscaResourceStructure.setCatalogServiceProxyResourceCustomization(spCustomizationResource);
-
- return spCustomizationResource;
- }
-
- protected ConfigurationResourceCustomization createConfiguration(NodeTemplate nodeTemplate,
- ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization,
- Optional<ConfigurationResourceCustomization> vnrResourceCustomization) {
-
- ConfigurationResourceCustomization configCustomizationResource = getConfigurationResourceCustomization(nodeTemplate,
- toscaResourceStructure,spResourceCustomization);
-
- ConfigurationResource configResource = getConfigurationResource(nodeTemplate);
-
- Set<ConfigurationResourceCustomization> configResourceCustomizationSet = new HashSet<>();
-
- StatefulEntityType entityType = nodeTemplate.getTypeDefinition();
- String type = entityType.getType();
-
- if(NODES_VRF_ENTRY.equals(type)) {
- configCustomizationResource.setConfigResourceCustomization(vnrResourceCustomization.orElse(null));
- }
-
- configCustomizationResource.setConfigurationResource(configResource);
-
- configResourceCustomizationSet.add(configCustomizationResource);
-
- configResource.setConfigurationResourceCustomization(configResourceCustomizationSet);
-
- toscaResourceStructure.setCatalogConfigurationResource(configResource);
-
- toscaResourceStructure.setCatalogConfigurationResourceCustomization(configCustomizationResource);
-
- return configCustomizationResource;
- }
-
- protected ConfigurationResource createFabricConfiguration(NodeTemplate nodeTemplate, ToscaResourceStructure toscaResourceStructure) {
-
- Metadata fabricMetadata = nodeTemplate.getMetaData();
-
- ConfigurationResource configResource = new ConfigurationResource();
-
- configResource.setModelName(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- configResource.setModelInvariantUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- configResource.setModelUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- configResource.setModelVersion(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- configResource.setDescription(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
- configResource.setToscaNodeType(nodeTemplate.getType());
-
- return configResource;
- }
-
- protected void createToscaCsar(ToscaResourceStructure toscaResourceStructure) {
- ToscaCsar toscaCsar = new ToscaCsar();
- if (toscaResourceStructure.getToscaArtifact().getArtifactChecksum() != null) {
- toscaCsar.setArtifactChecksum(toscaResourceStructure.getToscaArtifact().getArtifactChecksum());
- } else {
- toscaCsar.setArtifactChecksum(MANUAL_RECORD);
- }
- toscaCsar.setArtifactUUID(toscaResourceStructure.getToscaArtifact().getArtifactUUID());
- toscaCsar.setName(toscaResourceStructure.getToscaArtifact().getArtifactName());
- toscaCsar.setVersion(toscaResourceStructure.getToscaArtifact().getArtifactVersion());
- toscaCsar.setDescription(toscaResourceStructure.getToscaArtifact().getArtifactDescription());
- toscaCsar.setUrl(toscaResourceStructure.getToscaArtifact().getArtifactURL());
-
- toscaResourceStructure.setCatalogToscaCsar(toscaCsar);
- }
-
- protected VnfcCustomization findExistingVfc(Set<VnfcCustomization> vnfcCustomizations, String customizationUUID) {
- VnfcCustomization vnfcCustomization = null;
- for(VnfcCustomization vnfcCustom : vnfcCustomizations){
- if (vnfcCustom != null && vnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) {
- vnfcCustomization = vnfcCustom;
- }
- }
-
- if(vnfcCustomization==null)
- vnfcCustomization = vnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID);
- //vnfcCustomization = new VnfcCustomization();
-
- return vnfcCustomization;
- }
-
- protected CvnfcCustomization findExistingCvfc(Set<CvnfcCustomization> cvnfcCustomizations, String customizationUUID) {
- CvnfcCustomization cvnfcCustomization = null;
- for(CvnfcCustomization cvnfcCustom : cvnfcCustomizations){
- if (cvnfcCustom != null && cvnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) {
- cvnfcCustomization = cvnfcCustom;
- }
- }
-
- if(cvnfcCustomization==null)
- cvnfcCustomization = cvnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID);
-
- return cvnfcCustomization;
- }
-
- protected NetworkResourceCustomization createNetwork(NodeTemplate networkNodeTemplate,
- ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin,Service service) {
-
- NetworkResourceCustomization networkResourceCustomization=networkCustomizationRepo.findOneByModelCustomizationUUID(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
-
- boolean networkUUIDsMatch = true;
- // Check to make sure the NetworkResourceUUID on the Customization record matches the NetworkResourceUUID from the distribution.
- // If not we'll update the Customization record with latest from the distribution
- if(networkResourceCustomization != null){
- String existingNetworkModelUUID = networkResourceCustomization.getNetworkResource().getModelUUID();
- String latestNetworkModelUUID = networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID);
-
- if(!existingNetworkModelUUID.equals(latestNetworkModelUUID)){
- networkUUIDsMatch = false;
- }
-
- }
-
- if (networkResourceCustomization!=null && !networkUUIDsMatch){
-
- NetworkResource networkResource = createNetworkResource(networkNodeTemplate, toscaResourceStructure, heatTemplate,
- aicMax, aicMin);
-
- networkResourceCustomization.setNetworkResource(networkResource);
-
- networkCustomizationRepo.saveAndFlush(networkResourceCustomization);
-
- }
- else if(networkResourceCustomization==null){
- networkResourceCustomization = createNetworkResourceCustomization(networkNodeTemplate,
- toscaResourceStructure);
-
- NetworkResource networkResource = findExistingNetworkResource(service,
- networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- if(networkResource == null)
- networkResource = createNetworkResource(networkNodeTemplate, toscaResourceStructure, heatTemplate,
- aicMax, aicMin);
-
- networkResource.addNetworkResourceCustomization(networkResourceCustomization);
- networkResourceCustomization.setNetworkResource(networkResource);
- }
-
- return networkResourceCustomization;
- }
-
- protected NetworkResource findExistingNetworkResource(Service service, String modelUUID) {
- NetworkResource networkResource = null;
- for(NetworkResourceCustomization networkCustom : service.getNetworkCustomizations()){
- if (networkCustom.getNetworkResource() != null
- && networkCustom.getNetworkResource().getModelUUID().equals(modelUUID)) {
- networkResource = networkCustom.getNetworkResource();
- }
- }
- if(networkResource==null)
- networkResource = networkRepo.findResourceByModelUUID(modelUUID);
-
- return networkResource;
- }
-
- protected NetworkResourceCustomization createNetworkResourceCustomization(NodeTemplate networkNodeTemplate,
- ToscaResourceStructure toscaResourceStructure) {
- NetworkResourceCustomization networkResourceCustomization = new NetworkResourceCustomization();
- networkResourceCustomization.setModelInstanceName(
- testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
- networkResourceCustomization.setModelCustomizationUUID(
- testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
-
- networkResourceCustomization.setNetworkTechnology(
- testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
- SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY)));
- networkResourceCustomization.setNetworkType(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE)));
- networkResourceCustomization.setNetworkRole(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE)));
- networkResourceCustomization.setNetworkScope(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE)));
- return networkResourceCustomization;
- }
-
- protected NetworkResource createNetworkResource(NodeTemplate networkNodeTemplate,
- ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin) {
- NetworkResource networkResource = new NetworkResource();
- String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(
- networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK);
-
- if ("true".equalsIgnoreCase(providerNetwork)) {
- networkResource.setNeutronNetworkType(PROVIDER);
- } else {
- networkResource.setNeutronNetworkType(BASIC);
- }
-
- networkResource.setModelName(
- testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
-
- networkResource.setModelInvariantUUID(
- testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
- networkResource.setModelUUID(
- testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
- networkResource.setModelVersion(
- testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
-
- networkResource.setAicVersionMax(aicMax);
- networkResource.setAicVersionMin(aicMin);
- networkResource.setToscaNodeType(networkNodeTemplate.getType());
- networkResource.setDescription(
- testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
- networkResource.setOrchestrationMode(HEAT);
- networkResource.setHeatTemplate(heatTemplate);
- return networkResource;
- }
-
- protected CollectionNetworkResourceCustomization createNetworkCollection(NodeTemplate networkNodeTemplate,
- ToscaResourceStructure toscaResourceStructure, Service service) {
-
- CollectionNetworkResourceCustomization collectionNetworkResourceCustomization = new CollectionNetworkResourceCustomization();
-
- // **** Build Object to populate Collection_Resource table
- CollectionResource collectionResource = new CollectionResource();
-
- collectionResource
- .setModelName(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- collectionResource.setModelInvariantUUID(
- networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- collectionResource
- .setModelUUID(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- collectionResource
- .setModelVersion(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- collectionResource
- .setDescription(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
- collectionResource.setToscaNodeType(networkNodeTemplate.getType());
-
- toscaResourceStructure.setCatalogCollectionResource(collectionResource);
-
- // **** Build object to populate Collection_Resource_Customization table
- NetworkCollectionResourceCustomization ncfc = new NetworkCollectionResourceCustomization();
-
- ncfc.setFunction(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
- "cr_function"));
- ncfc.setRole(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
- "cr_role"));
- ncfc.setType(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
- "cr_type"));
-
- ncfc.setModelInstanceName(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- ncfc.setModelCustomizationUUID(
- networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
-
- Set<CollectionNetworkResourceCustomization> networkResourceCustomizationSet = new HashSet<>();
- networkResourceCustomizationSet.add(collectionNetworkResourceCustomization);
-
- ncfc.setNetworkResourceCustomization(networkResourceCustomizationSet);
-
- ncfc.setCollectionResource(collectionResource);
- toscaResourceStructure.setCatalogCollectionResourceCustomization(ncfc);
-
- //*** Build object to populate the Instance_Group table
- List<Group> groupList = toscaResourceStructure.getSdcCsarHelper()
- .getGroupsOfOriginOfNodeTemplateByToscaGroupType(networkNodeTemplate,
- "org.openecomp.groups.NetworkCollection");
-
- List<NetworkInstanceGroup> networkInstanceGroupList = new ArrayList<>();
-
- List<CollectionResourceInstanceGroupCustomization> collectionResourceInstanceGroupCustomizationList = new ArrayList<CollectionResourceInstanceGroupCustomization>();
-
- for (Group group : groupList) {
-
- NetworkInstanceGroup networkInstanceGroup = new NetworkInstanceGroup();
- Metadata instanceMetadata = group.getMetadata();
- networkInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- networkInstanceGroup
- .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- networkInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- networkInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- networkInstanceGroup.setToscaNodeType(group.getType());
- networkInstanceGroup.setRole(SubType.SUB_INTERFACE.toString()); // Set
- // Role
- networkInstanceGroup.setType(InstanceGroupType.L3_NETWORK); // Set
- // type
- networkInstanceGroup.setCollectionResource(collectionResource);
-
- // ****Build object to populate
- // Collection_Resource_Instance_Group_Customization table
- CollectionResourceInstanceGroupCustomization crInstanceGroupCustomization = new CollectionResourceInstanceGroupCustomization();
- crInstanceGroupCustomization.setInstanceGroup(networkInstanceGroup);
- crInstanceGroupCustomization.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- crInstanceGroupCustomization.setModelCustomizationUUID(
- networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
-
- // Loop through the template policy to find the subinterface_network_quantity property name. Then extract the value for it.
- List<Policy> policyList = toscaResourceStructure.getSdcCsarHelper().getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(networkNodeTemplate, "org.openecomp.policies.scaling.Fixed");
-
- if(policyList != null){
- for(Policy policy : policyList){
- for(String policyNetworkCollection : policy.getTargets()){
-
- if(policyNetworkCollection.equalsIgnoreCase(group.getName())){
-
- Map<String, Object> propMap = policy.getPolicyProperties();
-
- if(propMap.get("quantity") != null){
-
- String quantity = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, getPropertyInput(propMap.get("quantity").toString()));
-
- if(quantity != null){
- crInstanceGroupCustomization.setSubInterfaceNetworkQuantity(Integer.parseInt(quantity));
- }
-
- }
-
- }
- }
- }
- }
-
- crInstanceGroupCustomization.setDescription(
- toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
- instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)
- + "_network_collection_description"));
- crInstanceGroupCustomization.setFunction(
- toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
- instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)
- + "_network_collection_function"));
- crInstanceGroupCustomization.setCollectionResourceCust(ncfc);
- collectionResourceInstanceGroupCustomizationList.add(crInstanceGroupCustomization);
-
- networkInstanceGroup
- .setCollectionInstanceGroupCustomizations(collectionResourceInstanceGroupCustomizationList);
-
- networkInstanceGroupList.add(networkInstanceGroup);
-
-
- toscaResourceStructure.setCatalogNetworkInstanceGroup(networkInstanceGroupList);
-
- List<NodeTemplate> vlNodeList = toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplateBySdcType(networkNodeTemplate, SdcTypes.VL);
-
- List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomizationList = new ArrayList<>();
-
- //*****Build object to populate the NetworkResource table
- NetworkResource networkResource = new NetworkResource();
-
- for(NodeTemplate vlNodeTemplate : vlNodeList){
-
- String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(
- vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK);
-
- if ("true".equalsIgnoreCase(providerNetwork)) {
- networkResource.setNeutronNetworkType(PROVIDER);
- } else {
- networkResource.setNeutronNetworkType(BASIC);
- }
-
- networkResource.setModelName(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
-
- networkResource.setModelInvariantUUID(
- vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- networkResource.setModelUUID(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- networkResource
- .setModelVersion(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
-
- networkResource.setAicVersionMax(
- vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES));
-
- TempNetworkHeatTemplateLookup tempNetworkLookUp = tempNetworkLookupRepo.findFirstBynetworkResourceModelName(
- vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
-
- if (tempNetworkLookUp != null ) {
-
- HeatTemplate heatTemplate = heatRepo
- .findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid());
- networkResource.setHeatTemplate(heatTemplate);
-
- networkResource.setAicVersionMin(tempNetworkLookUp.getAicVersionMin());
-
- }
-
- networkResource.setToscaNodeType(vlNodeTemplate.getType());
- networkResource
- .setDescription(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
- networkResource.setOrchestrationMode(HEAT);
-
- // Build object to populate the
- // Collection_Network_Resource_Customization table
- for (NodeTemplate memberNode : group.getMemberNodes()) {
- collectionNetworkResourceCustomization.setModelInstanceName(memberNode.getName());
- }
-
- collectionNetworkResourceCustomization.setModelCustomizationUUID(
- vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
-
- collectionNetworkResourceCustomization.setNetworkTechnology(
- toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNodeTemplate,
- SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY));
- collectionNetworkResourceCustomization.setNetworkType(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE));
- collectionNetworkResourceCustomization.setNetworkRole(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE));
- collectionNetworkResourceCustomization.setNetworkScope(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE));
- collectionNetworkResourceCustomization.setInstanceGroup(networkInstanceGroup);
- collectionNetworkResourceCustomization.setNetworkResource(networkResource);
- collectionNetworkResourceCustomization.setNetworkResourceCustomization(ncfc);
-
- collectionNetworkResourceCustomizationList.add(collectionNetworkResourceCustomization);
- }
-
- }
-
- return collectionNetworkResourceCustomization;
- }
-
- protected VnfcInstanceGroupCustomization createVNFCInstanceGroup(NodeTemplate vnfcNodeTemplate, Group group,
- VnfResourceCustomization vnfResourceCustomization, ToscaResourceStructure toscaResourceStructure) {
-
- Metadata instanceMetadata = group.getMetadata();
- // Populate InstanceGroup
- VFCInstanceGroup vfcInstanceGroup = new VFCInstanceGroup();
-
- vfcInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- vfcInstanceGroup.setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- vfcInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- vfcInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- vfcInstanceGroup.setToscaNodeType(group.getType());
- vfcInstanceGroup.setRole("SUB-INTERFACE"); // Set Role
- vfcInstanceGroup.setType(InstanceGroupType.VNFC); // Set type
-
- //Populate VNFCInstanceGroupCustomization
- VnfcInstanceGroupCustomization vfcInstanceGroupCustom = new VnfcInstanceGroupCustomization();
-
- vfcInstanceGroupCustom.setVnfResourceCust(vnfResourceCustomization);
- vnfResourceCustomization.getVnfcInstanceGroupCustomizations().add(vfcInstanceGroupCustom);
-
- vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup);
- vfcInstanceGroup.getVnfcInstanceGroupCustomizations().add(vfcInstanceGroupCustom);
-
- vfcInstanceGroupCustom.setDescription(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
-
- String getInputName = null;
- String groupProperty = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, "vfc_instance_group_function");
- if (groupProperty != null) {
- int getInputIndex = groupProperty.indexOf("{get_input=");
- if (getInputIndex > -1) {
- getInputName = groupProperty.substring(getInputIndex+11, groupProperty.length()-1);
- }
- }
- vfcInstanceGroupCustom.setFunction(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vnfcNodeTemplate, getInputName));
- vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup);
-
-
- return vfcInstanceGroupCustom;
-
- }
-
- protected VfModuleCustomization createVFModuleResource(Group group, NodeTemplate vfTemplate,
- ToscaResourceStructure toscaResourceStructure, VfResourceStructure vfResourceStructure,
- IVfModuleData vfModuleData, VnfResourceCustomization vnfResource, Service service,
- Set<CvnfcCustomization> existingCvnfcSet, Set<VnfcCustomization> existingVnfcSet) {
-
- VfModuleCustomization vfModuleCustomization = findExistingVfModuleCustomization(vnfResource,
- vfModuleData.getVfModuleModelCustomizationUUID());
- if (vfModuleCustomization == null) {
- VfModule vfModule = findExistingVfModule(vnfResource,
- vfTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID));
- Metadata vfMetadata = group.getMetadata();
- if (vfModule == null)
- vfModule = createVfModule(group, toscaResourceStructure, vfModuleData, vfMetadata);
-
- vfModuleCustomization = createVfModuleCustomization(group, toscaResourceStructure, vfModule, vfModuleData);
- vfModuleCustomization.setVnfCustomization(vnfResource);
- setHeatInformationForVfModule(toscaResourceStructure, vfResourceStructure, vfModule, vfModuleCustomization,
- vfMetadata);
- vfModuleCustomization.setVfModule(vfModule);
- vfModule.getVfModuleCustomization().add(vfModuleCustomization);
- vnfResource.getVfModuleCustomizations().add(vfModuleCustomization);
- } else {
- vfResourceStructure.setAlreadyDeployed(true);
- }
-
- // ******************************************************************************************************************
- // * Extract VFC's and CVFC's then add them to VFModule
- // ******************************************************************************************************************
-
- Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomizations = new HashSet<CvnfcConfigurationCustomization>();
- Set<CvnfcCustomization> cvnfcCustomizations = new HashSet<CvnfcCustomization>();
- Set<VnfcCustomization> vnfcCustomizations = new HashSet<VnfcCustomization>();
-
- // Only set the CVNFC if this vfModule group is a member of it.
- List<NodeTemplate> groupMembers = toscaResourceStructure.getSdcCsarHelper().getMembersOfVfModule(vfTemplate,
- group);
- String vfModuleMemberName = null;
-
- for (NodeTemplate node : groupMembers) {
- vfModuleMemberName = node.getName();
- }
-
- // Extract CVFC lists
- List<NodeTemplate> cvfcList = toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(vfTemplate,
- SdcTypes.CVFC);
-
- for (NodeTemplate cvfcTemplate : cvfcList) {
- boolean cvnfcVfModuleNameMatch = false;
-
- for(NodeTemplate node : groupMembers){
- vfModuleMemberName = node.getName();
-
- if(vfModuleMemberName.equalsIgnoreCase(cvfcTemplate.getName())){
- cvnfcVfModuleNameMatch = true;
- break;
- }
- }
-
- if(vfModuleMemberName != null && cvnfcVfModuleNameMatch){
-
- // Extract associated VFC - Should always be just one
- List<NodeTemplate> vfcList = toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplateBySdcType(cvfcTemplate, SdcTypes.VFC);
-
- for (NodeTemplate vfcTemplate : vfcList) {
-
- VnfcCustomization vnfcCustomization = new VnfcCustomization();
- VnfcCustomization existingVnfcCustomization = null;
-
- existingVnfcCustomization = findExistingVfc(existingVnfcSet,
- vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
-
- if (existingVnfcCustomization == null) {
- vnfcCustomization = new VnfcCustomization();
- } else {
- vnfcCustomization = existingVnfcCustomization;
- }
-
- // Only Add Abstract VNFC's to our DB, ignore all others
- if (existingVnfcCustomization == null && vfcTemplate.getMetaData()
- .getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY).equalsIgnoreCase("Abstract")) {
- vnfcCustomization.setModelCustomizationUUID(
- vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
- vnfcCustomization.setModelInstanceName(vfcTemplate.getName());
- vnfcCustomization.setModelInvariantUUID(
- vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- vnfcCustomization
- .setModelName(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- vnfcCustomization
- .setModelUUID(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
-
- vnfcCustomization.setModelVersion(
- testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
- vnfcCustomization.setDescription(testNull(
- vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
- vnfcCustomization.setToscaNodeType(testNull(vfcTemplate.getType()));
-
- vnfcCustomizations.add(vnfcCustomization);
- existingVnfcSet.add(vnfcCustomization);
- }
-
- // This check is needed incase the VFC subcategory is
- // something other than Abstract. In that case we want to
- // skip adding that record to our DB.
- if (vnfcCustomization.getModelCustomizationUUID() != null) {
- CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
- cvnfcCustomization.setModelCustomizationUUID(
- cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
- cvnfcCustomization.setModelInstanceName(cvfcTemplate.getName());
- cvnfcCustomization.setModelInvariantUUID(
- cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- cvnfcCustomization
- .setModelName(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- cvnfcCustomization
- .setModelUUID(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
-
- cvnfcCustomization.setModelVersion(
- testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
- cvnfcCustomization.setDescription(testNull(
- cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
- cvnfcCustomization.setToscaNodeType(testNull(cvfcTemplate.getType()));
-
- if (existingVnfcCustomization != null) {
- cvnfcCustomization.setVnfcCustomization(existingVnfcCustomization);
- } else {
- cvnfcCustomization.setVnfcCustomization(vnfcCustomization);
- }
-
- cvnfcCustomization.setNfcFunction(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(cvfcTemplate, "nfc_function"));
- cvnfcCustomization.setNfcNamingCode(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(cvfcTemplate, "nfc_naming_code"));
- cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization);
-
- cvnfcCustomizations.add(cvnfcCustomization);
- existingCvnfcSet.add(cvnfcCustomization);
-
- // *****************************************************************************************************************************************
- // * Extract Fabric Configuration
- // *****************************************************************************************************************************************
-
- List<NodeTemplate> fabricConfigList = toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplateBySdcType(vfTemplate, SdcTypes.CONFIGURATION);
-
- for (NodeTemplate fabricTemplate : fabricConfigList) {
-
- ConfigurationResource fabricConfig = null;
-
- ConfigurationResource existingConfig = findExistingConfiguration(service,
- fabricTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
-
- if (existingConfig == null) {
-
- fabricConfig = createFabricConfiguration(fabricTemplate, toscaResourceStructure);
-
- } else {
- fabricConfig = existingConfig;
- }
-
- CvnfcConfigurationCustomization cvnfcConfigurationCustomization = createCvnfcConfigurationCustomization(
- fabricTemplate, toscaResourceStructure, vnfResource, vfModuleCustomization,
- cvnfcCustomization, fabricConfig, vfTemplate, vfModuleMemberName);
- cvnfcConfigurationCustomizations.add(cvnfcConfigurationCustomization);
-
- fabricConfig.setCvnfcConfigurationCustomization(cvnfcConfigurationCustomizations);
- }
- cvnfcCustomization.setCvnfcConfigurationCustomization(cvnfcConfigurationCustomizations);
- }
-
- }
-
- }
- }
- vfModuleCustomization.setCvnfcCustomization(cvnfcCustomizations);
-
- return vfModuleCustomization;
- }
-
- protected CvnfcConfigurationCustomization createCvnfcConfigurationCustomization(NodeTemplate fabricTemplate, ToscaResourceStructure toscaResourceStruct,
- VnfResourceCustomization vnfResource, VfModuleCustomization vfModuleCustomization, CvnfcCustomization cvnfcCustomization,
+ protected static final String NODES_VRF_ENTRY = "org.openecomp.nodes.VRFEntry";
+
+ protected static final String VLAN_NETWORK_RECEPTOR = "org.openecomp.nodes.VLANNetworkReceptor";
+
+ protected static final String ALLOTTED_RESOURCE = "Allotted Resource";
+
+ protected static final String MULTI_STAGE_DESIGN = "multi_stage_design";
+
+ protected static final String SCALABLE = "scalable";
+
+ protected static final String BASIC = "BASIC";
+
+ protected static final String PROVIDER = "PROVIDER";
+
+ protected static final String HEAT = "HEAT";
+
+ protected static final String MANUAL_RECORD = "MANUAL_RECORD";
+
+ protected static final String MSO = "SO";
+
+ protected static final String SDNC_MODEL_NAME = "sdnc_model_name";
+
+ protected static final String SDNC_MODEL_VERSION = "sdnc_model_version";
+
+ private static String CUSTOMIZATION_UUID = "customizationUUID";
+
+ protected static final String SKIP_POST_INST_CONF = "skip_post_instantiation_configuration";
+
+ @Autowired
+ protected ServiceRepository serviceRepo;
+
+ @Autowired
+ protected InstanceGroupRepository instanceGroupRepo;
+
+ @Autowired
+ protected ServiceProxyResourceCustomizationRepository serviceProxyCustomizationRepo;
+
+ @Autowired
+ protected CollectionResourceRepository collectionRepo;
+
+ @Autowired
+ protected CollectionResourceCustomizationRepository collectionCustomizationRepo;
+
+ @Autowired
+ protected ConfigurationResourceCustomizationRepository configCustomizationRepo;
+
+ @Autowired
+ protected ConfigurationResourceRepository configRepo;
+
+ @Autowired
+ protected VnfResourceRepository vnfRepo;
+
+ @Autowired
+ protected VFModuleRepository vfModuleRepo;
+
+ @Autowired
+ protected VFModuleCustomizationRepository vfModuleCustomizationRepo;
+
+ @Autowired
+ protected VnfcInstanceGroupCustomizationRepository vnfcInstanceGroupCustomizationRepo;
+
+ @Autowired
+ protected VnfcCustomizationRepository vnfcCustomizationRepo;
+
+ @Autowired
+ protected CvnfcCustomizationRepository cvnfcCustomizationRepo;
+
+ @Autowired
+ protected AllottedResourceRepository allottedRepo;
+
+ @Autowired
+ protected AllottedResourceCustomizationRepository allottedCustomizationRepo;
+
+ @Autowired
+ protected NetworkResourceRepository networkRepo;
+
+ @Autowired
+ protected HeatTemplateRepository heatRepo;
+
+ @Autowired
+ protected NetworkResourceCustomizationRepository networkCustomizationRepo;
+
+ @Autowired
+ protected WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository;
+ @Autowired
+ protected WatchdogDistributionStatusRepository watchdogDistributionStatusRepository;
+ @Autowired
+ protected WatchdogServiceModVerIdLookupRepository watchdogModVerIdLookupRepository;
+
+ @Autowired
+ protected TempNetworkHeatTemplateRepository tempNetworkLookupRepo;
+
+ @Autowired
+ protected ExternalServiceToInternalServiceRepository externalServiceToInternalServiceRepository;
+
+ @Autowired
+ protected PnfResourceRepository pnfResourceRepository;
+
+ @Autowired
+ protected PnfCustomizationRepository pnfCustomizationRepository;
+
+ protected static final Logger logger = LoggerFactory.getLogger(ToscaResourceInstaller.class);
+
+ public boolean isResourceAlreadyDeployed(VfResourceStructure vfResourceStruct) throws ArtifactInstallerException {
+ boolean status = false;
+ VfResourceStructure vfResourceStructure = vfResourceStruct;
+ try {
+ status = vfResourceStructure.isDeployedSuccessfully();
+ } catch (RuntimeException e) {
+ status = false;
+ }
+ try {
+ Service existingService =
+ serviceRepo.findOneByModelUUID(vfResourceStructure.getNotification().getServiceUUID());
+ if (existingService != null)
+ status = true;
+ if (status) {
+ logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(),
+ vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(),
+ vfResourceStructure.getNotification().getServiceName(),
+ BigDecimalVersion.castAndCheckNotificationVersionToString(
+ vfResourceStructure.getNotification().getServiceVersion()),
+ vfResourceStructure.getNotification().getServiceUUID(),
+ vfResourceStructure.getResourceInstance().getResourceName(), "", "");
+ WatchdogComponentDistributionStatus wdStatus = new WatchdogComponentDistributionStatus(
+ vfResourceStruct.getNotification().getDistributionID(), MSO);
+ wdStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
+ watchdogCDStatusRepository.saveAndFlush(wdStatus);
+ } else {
+ logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(),
+ vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(),
+ vfResourceStructure.getNotification().getServiceName(),
+ BigDecimalVersion.castAndCheckNotificationVersionToString(
+ vfResourceStructure.getNotification().getServiceVersion()),
+ vfResourceStructure.getNotification().getServiceUUID(),
+ vfResourceStructure.getResourceInstance().getResourceName(), "", "");
+ }
+ return status;
+ } catch (Exception e) {
+ logger.error("{} {} {}", MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), ErrorCode.SchemaError.getValue(),
+ "Exception - isResourceAlreadyDeployed");
+ throw new ArtifactInstallerException("Exception caught during checking existence of the VNF Resource.", e);
+ }
+ }
+
+ public void installTheComponentStatus(IStatusData iStatus) throws ArtifactInstallerException {
+ logger.debug("Entering installTheComponentStatus for distributionId {} and ComponentName {}",
+ iStatus.getDistributionID(), iStatus.getComponentName());
+
+ try {
+ WatchdogComponentDistributionStatus cdStatus =
+ new WatchdogComponentDistributionStatus(iStatus.getDistributionID(), iStatus.getComponentName());
+ cdStatus.setComponentDistributionStatus(iStatus.getStatus().toString());
+ watchdogCDStatusRepository.save(cdStatus);
+
+ } catch (Exception e) {
+ logger.debug("Exception caught in installTheComponentStatus {}", e.getMessage());
+ throw new ArtifactInstallerException("Exception caught in installTheComponentStatus " + e.getMessage());
+ }
+ }
+
+ @Transactional(rollbackFor = {ArtifactInstallerException.class})
+ public void installTheResource(ToscaResourceStructure toscaResourceStruct, ResourceStructure resourceStruct)
+ throws ArtifactInstallerException {
+ if (resourceStruct instanceof VfResourceStructure) {
+ installTheVfResource(toscaResourceStruct, (VfResourceStructure) resourceStruct);
+ } else if (resourceStruct instanceof PnfResourceStructure) {
+ installPnfResource(toscaResourceStruct, (PnfResourceStructure) resourceStruct);
+ } else {
+ logger.warn("Unrecognized resource type");
+ }
+ }
+
+ private void installPnfResource(ToscaResourceStructure toscaResourceStruct, PnfResourceStructure resourceStruct)
+ throws ArtifactInstallerException {
+
+ // PCLO: in case of deployment failure, use a string that will represent
+ // the type of artifact that failed...
+ List<ASDCElementInfo> artifactListForLogging = new ArrayList<>();
+ try {
+ createToscaCsar(toscaResourceStruct);
+ Service service = createService(toscaResourceStruct, resourceStruct);
+
+ processResourceSequence(toscaResourceStruct, service);
+ processPnfResources(toscaResourceStruct, service, resourceStruct);
+ serviceRepo.save(service);
+
+ WatchdogComponentDistributionStatus status =
+ new WatchdogComponentDistributionStatus(resourceStruct.getNotification().getDistributionID(), MSO);
+ status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
+ watchdogCDStatusRepository.save(status);
+
+ toscaResourceStruct.setSuccessfulDeployment();
+
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ WatchdogComponentDistributionStatus status =
+ new WatchdogComponentDistributionStatus(resourceStruct.getNotification().getDistributionID(), MSO);
+ status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name());
+ watchdogCDStatusRepository.save(status);
+ Throwable dbExceptionToCapture = e;
+ while (!(dbExceptionToCapture instanceof ConstraintViolationException
+ || dbExceptionToCapture instanceof LockAcquisitionException)
+ && (dbExceptionToCapture.getCause() != null)) {
+ dbExceptionToCapture = dbExceptionToCapture.getCause();
+ }
+
+ if (dbExceptionToCapture instanceof ConstraintViolationException
+ || dbExceptionToCapture instanceof LockAcquisitionException) {
+ logger.warn("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(),
+ resourceStruct.getResourceInstance().getResourceName(),
+ resourceStruct.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(),
+ "Exception - ASCDC Artifact already deployed", e);
+ } else {
+ String elementToLog = (!artifactListForLogging.isEmpty()
+ ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString()
+ : "No element listed");
+ logger.error("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog,
+ ErrorCode.DataError.getValue(), "Exception caught during installation of "
+ + resourceStruct.getResourceInstance().getResourceName() + ". Transaction rollback",
+ e);
+ throw new ArtifactInstallerException(
+ "Exception caught during installation of "
+ + resourceStruct.getResourceInstance().getResourceName() + ". Transaction rollback.",
+ e);
+ }
+ }
+ }
+
+ @Transactional(rollbackFor = {ArtifactInstallerException.class})
+ public void installTheVfResource(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStruct)
+ throws ArtifactInstallerException {
+ VfResourceStructure vfResourceStructure = vfResourceStruct;
+ extractHeatInformation(toscaResourceStruct, vfResourceStructure);
+
+ // PCLO: in case of deployment failure, use a string that will represent
+ // the type of artifact that failed...
+ List<ASDCElementInfo> artifactListForLogging = new ArrayList<>();
+ try {
+ createToscaCsar(toscaResourceStruct);
+ Service service = createService(toscaResourceStruct, vfResourceStruct);
+ List<NodeTemplate> vfNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceVfList();
+
+
+ for (NodeTemplate nodeTemplate : vfNodeTemplatesList) {
+
+ Metadata metadata = nodeTemplate.getMetaData();
+ String serviceType = toscaResourceStruct.getCatalogService().getServiceType();
+ String vfCustomizationCategory = toscaResourceStruct.getSdcCsarHelper()
+ .getMetadataPropertyValue(metadata, SdcPropertyNames.PROPERTY_NAME_CATEGORY);
+ processVfModules(toscaResourceStruct, vfResourceStructure, service, nodeTemplate, metadata,
+ vfCustomizationCategory);
+ }
+
+ processResourceSequence(toscaResourceStruct, service);
+ processVFResources(toscaResourceStruct, service, vfResourceStructure);
+ List<NodeTemplate> allottedResourceList = toscaResourceStruct.getSdcCsarHelper().getAllottedResources();
+ processAllottedResources(toscaResourceStruct, service, allottedResourceList);
+ processNetworks(toscaResourceStruct, service);
+ // process Network Collections
+ processNetworkCollections(toscaResourceStruct, service);
+ // Process Service Proxy & Configuration
+ processServiceProxyAndConfiguration(toscaResourceStruct, service);
+
+ serviceRepo.save(service);
+
+ WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(
+ vfResourceStruct.getNotification().getDistributionID(), MSO);
+ status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
+ watchdogCDStatusRepository.save(status);
+
+ toscaResourceStruct.setSuccessfulDeployment();
+
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(
+ vfResourceStruct.getNotification().getDistributionID(), MSO);
+ status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name());
+ watchdogCDStatusRepository.save(status);
+ Throwable dbExceptionToCapture = e;
+ while (!(dbExceptionToCapture instanceof ConstraintViolationException
+ || dbExceptionToCapture instanceof LockAcquisitionException)
+ && (dbExceptionToCapture.getCause() != null)) {
+ dbExceptionToCapture = dbExceptionToCapture.getCause();
+ }
+
+ if (dbExceptionToCapture instanceof ConstraintViolationException
+ || dbExceptionToCapture instanceof LockAcquisitionException) {
+ logger.warn("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(),
+ vfResourceStructure.getResourceInstance().getResourceName(),
+ vfResourceStructure.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(),
+ "Exception - ASCDC Artifact already deployed", e);
+ } else {
+ String elementToLog = (!artifactListForLogging.isEmpty()
+ ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString()
+ : "No element listed");
+ logger.error("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog,
+ ErrorCode.DataError.getValue(),
+ "Exception caught during installation of "
+ + vfResourceStructure.getResourceInstance().getResourceName()
+ + ". Transaction rollback",
+ e);
+ throw new ArtifactInstallerException("Exception caught during installation of "
+ + vfResourceStructure.getResourceInstance().getResourceName() + ". Transaction rollback.", e);
+ }
+ }
+ }
+
+
+ List<NodeTemplate> getRequirementList(List<NodeTemplate> resultList, List<NodeTemplate> nodeTemplates,
+ ISdcCsarHelper iSdcCsarHelper) {
+
+ List<NodeTemplate> nodes = new ArrayList<NodeTemplate>();
+ nodes.addAll(nodeTemplates);
+
+ for (NodeTemplate nodeTemplate : nodeTemplates) {
+ RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate);
+ List<RequirementAssignment> reqAs = requirement.getAll();
+ for (RequirementAssignment ra : reqAs) {
+ String reqNode = ra.getNodeTemplateName();
+ for (NodeTemplate rNode : resultList) {
+ if (rNode.getName().equals(reqNode)) {
+ if (!resultList.contains(nodeTemplate)) {
+ resultList.add(nodeTemplate);
+ }
+ if (nodes.contains(nodeTemplate)) {
+ nodes.remove(nodeTemplate);
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ if (!nodes.isEmpty()) {
+ getRequirementList(resultList, nodes, iSdcCsarHelper);
+ }
+
+ return resultList;
+ }
+
+ // This method retrieve resource sequence from csar file
+ void processResourceSequence(ToscaResourceStructure toscaResourceStructure, Service service) {
+ List<String> resouceSequence = new ArrayList<String>();
+ List<NodeTemplate> resultList = new ArrayList<NodeTemplate>();
+
+ ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper();
+ List<NodeTemplate> nodeTemplates = iSdcCsarHelper.getServiceNodeTemplates();
+ List<NodeTemplate> nodes = new ArrayList<NodeTemplate>();
+ nodes.addAll(nodeTemplates);
+
+ for (NodeTemplate nodeTemplate : nodeTemplates) {
+ RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate);
+
+ if (requirement == null || requirement.getAll() == null || requirement.getAll().isEmpty()) {
+ resultList.add(nodeTemplate);
+ nodes.remove(nodeTemplate);
+ }
+ }
+
+ resultList = getRequirementList(resultList, nodes, iSdcCsarHelper);
+
+ for (NodeTemplate node : resultList) {
+ String templateName = node.getMetaData().getValue("name");
+ if (!resouceSequence.contains(templateName)) {
+ resouceSequence.add(templateName);
+ }
+ }
+
+ String resourceSeqStr = resouceSequence.stream().collect(Collectors.joining(","));
+ service.setResourceOrder(resourceSeqStr);
+ logger.debug(" resourceSeq for service uuid(" + service.getModelUUID() + ") : " + resourceSeqStr);
+ }
+
+ private static String getValue(Object value, List<Input> servInputs) {
+ String output = null;
+ if (value instanceof Map) {
+ // currently this logic handles only one level of nesting.
+ return ((LinkedHashMap) value).values().toArray()[0].toString();
+ } else if (value instanceof GetInput) {
+ String inputName = ((GetInput) value).getInputName();
+
+ for (Input input : servInputs) {
+ if (input.getName().equals(inputName)) {
+ // keep both input name and default value
+ // if service input does not supplies value the use default value
+ String defaultValue = input.getDefault() != null ? (String) input.getDefault().toString() : "";
+ output = inputName + "|" + defaultValue;// return default value
+ }
+ }
+
+ } else {
+ output = value != null ? value.toString() : "";
+ }
+ return output; // return property value
+ }
+
+ String getResourceInput(ToscaResourceStructure toscaResourceStructure, String resourceCustomizationUuid)
+ throws ArtifactInstallerException {
+ Map<String, String> resouceRequest = new HashMap<>();
+ ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper();
+
+ List<Input> serInput = iSdcCsarHelper.getServiceInputs();
+ Optional<NodeTemplate> nodeTemplateOpt = iSdcCsarHelper.getServiceNodeTemplates().stream()
+ .filter(e -> e.getMetaData().getValue(CUSTOMIZATION_UUID).equals(resourceCustomizationUuid))
+ .findFirst();
+ if (nodeTemplateOpt.isPresent()) {
+ NodeTemplate nodeTemplate = nodeTemplateOpt.get();
+ LinkedHashMap<String, Property> resourceProperties = nodeTemplate.getProperties();
+
+ for (String key : resourceProperties.keySet()) {
+ Property property = resourceProperties.get(key);
+
+ String value = getValue(property.getValue(), serInput);
+ resouceRequest.put(key, value);
+ }
+ }
+
+ try {
+ ObjectMapper objectMapper = new ObjectMapper();
+ String jsonStr = objectMapper.writeValueAsString(resouceRequest);
+
+ jsonStr = jsonStr.replace("\"", "\\\"");
+ logger.debug(
+ "resource request for resource customization id (" + resourceCustomizationUuid + ") : " + jsonStr);
+ return jsonStr;
+ } catch (JsonProcessingException e) {
+ logger.error("resource input could not be deserialized for resource customization id ("
+ + resourceCustomizationUuid + ")");
+ throw new ArtifactInstallerException("resource input could not be parsed", e);
+ }
+ }
+
+ protected void processNetworks(ToscaResourceStructure toscaResourceStruct, Service service)
+ throws ArtifactInstallerException {
+ List<NodeTemplate> nodeTemplatesVLList = toscaResourceStruct.getSdcCsarHelper().getServiceVlList();
+
+ if (nodeTemplatesVLList != null) {
+ for (NodeTemplate vlNode : nodeTemplatesVLList) {
+ String networkResourceModelName = vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME);
+
+ TempNetworkHeatTemplateLookup tempNetworkLookUp =
+ tempNetworkLookupRepo.findFirstBynetworkResourceModelName(networkResourceModelName);
+
+ if (tempNetworkLookUp != null) {
+ HeatTemplate heatTemplate =
+ heatRepo.findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid());
+ if (heatTemplate != null) {
+ NetworkResourceCustomization networkCustomization = createNetwork(vlNode, toscaResourceStruct,
+ heatTemplate, tempNetworkLookUp.getAicVersionMax(),
+ tempNetworkLookUp.getAicVersionMin(), service);
+ service.getNetworkCustomizations().add(networkCustomization);
+ } else {
+ throw new ArtifactInstallerException("No HeatTemplate found for artifactUUID: "
+ + tempNetworkLookUp.getHeatTemplateArtifactUuid());
+ }
+ } else {
+ NetworkResourceCustomization networkCustomization =
+ createNetwork(vlNode, toscaResourceStruct, null, null, null, service);
+ service.getNetworkCustomizations().add(networkCustomization);
+ logger.debug("No NetworkResourceName found in TempNetworkHeatTemplateLookup for "
+ + networkResourceModelName);
+ }
+
+ }
+ }
+ }
+
+ protected void processAllottedResources(ToscaResourceStructure toscaResourceStruct, Service service,
+ List<NodeTemplate> allottedResourceList) {
+ if (allottedResourceList != null) {
+ for (NodeTemplate allottedNode : allottedResourceList) {
+ service.getAllottedCustomizations()
+ .add(createAllottedResource(allottedNode, toscaResourceStruct, service));
+ }
+ }
+ }
+
+
+ protected ConfigurationResource getConfigurationResource(NodeTemplate nodeTemplate) {
+ Metadata metadata = nodeTemplate.getMetaData();
+ ConfigurationResource configResource = new ConfigurationResource();
+ configResource.setModelName(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ configResource.setModelInvariantUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ configResource.setModelUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ configResource.setModelVersion(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ configResource.setDescription(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+ configResource.setToscaNodeType(nodeTemplate.getType());
+ return configResource;
+ }
+
+ protected ConfigurationResourceCustomization getConfigurationResourceCustomization(NodeTemplate nodeTemplate,
+ ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization) {
+ Metadata metadata = nodeTemplate.getMetaData();
+
+ ConfigurationResource configResource = getConfigurationResource(nodeTemplate);
+
+ ConfigurationResourceCustomization configCustomizationResource = new ConfigurationResourceCustomization();
+
+ Set<ConfigurationResourceCustomization> configResourceCustomizationSet = new HashSet<>();
+
+ configCustomizationResource
+ .setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+ configCustomizationResource.setModelInstanceName(nodeTemplate.getName());
+
+ configCustomizationResource.setNfFunction(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
+ configCustomizationResource.setNfRole(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE));
+ configCustomizationResource.setNfType(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE));
+ configCustomizationResource
+ .setServiceProxyResourceCustomizationUUID(spResourceCustomization.getModelCustomizationUUID());
+
+ configCustomizationResource.setConfigurationResource(configResource);
+ configResourceCustomizationSet.add(configCustomizationResource);
+
+ configResource.setConfigurationResourceCustomization(configResourceCustomizationSet);
+ return configCustomizationResource;
+ }
+
+
+ protected Optional<ConfigurationResourceCustomization> getVnrNodeTemplate(
+ List<NodeTemplate> configurationNodeTemplatesList, ToscaResourceStructure toscaResourceStructure,
+ ServiceProxyResourceCustomization spResourceCustomization) {
+ Optional<ConfigurationResourceCustomization> configurationResourceCust = Optional.empty();
+ for (NodeTemplate nodeTemplate : configurationNodeTemplatesList) {
+ StatefulEntityType entityType = nodeTemplate.getTypeDefinition();
+ String type = entityType.getType();
+
+ if (VLAN_NETWORK_RECEPTOR.equals(type)) {
+ configurationResourceCust = Optional.of(getConfigurationResourceCustomization(nodeTemplate,
+ toscaResourceStructure, spResourceCustomization));
+ break;
+ }
+ }
+
+ return configurationResourceCust;
+ }
+
+ protected void processServiceProxyAndConfiguration(ToscaResourceStructure toscaResourceStruct, Service service) {
+
+ List<NodeTemplate> serviceProxyResourceList =
+ toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.SERVICE_PROXY);
+
+ List<NodeTemplate> configurationNodeTemplatesList =
+ toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION);
+
+ List<ServiceProxyResourceCustomization> serviceProxyList = new ArrayList<ServiceProxyResourceCustomization>();
+ List<ConfigurationResourceCustomization> configurationResourceList =
+ new ArrayList<ConfigurationResourceCustomization>();
+
+ ServiceProxyResourceCustomization serviceProxy = null;
+
+ if (serviceProxyResourceList != null) {
+ for (NodeTemplate spNode : serviceProxyResourceList) {
+ serviceProxy = createServiceProxy(spNode, service, toscaResourceStruct);
+ serviceProxyList.add(serviceProxy);
+ Optional<ConfigurationResourceCustomization> vnrResourceCustomization =
+ getVnrNodeTemplate(configurationNodeTemplatesList, toscaResourceStruct, serviceProxy);
+
+ for (NodeTemplate configNode : configurationNodeTemplatesList) {
+
+ List<RequirementAssignment> requirementsList =
+ toscaResourceStruct.getSdcCsarHelper().getRequirementsOf(configNode).getAll();
+ for (RequirementAssignment requirement : requirementsList) {
+ if (requirement.getNodeTemplateName().equals(spNode.getName())) {
+ ConfigurationResourceCustomization configurationResource = createConfiguration(configNode,
+ toscaResourceStruct, serviceProxy, vnrResourceCustomization);
+
+ Optional<ConfigurationResourceCustomization> matchingObject = configurationResourceList
+ .stream()
+ .filter(configurationResourceCustomization -> configNode.getMetaData()
+ .getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)
+ .equals(configurationResource.getModelCustomizationUUID()))
+ .findFirst();
+ if (!matchingObject.isPresent()) {
+ configurationResourceList.add(configurationResource);
+ }
+
+ break;
+ }
+ }
+ }
+
+ }
+ }
+
+ service.setConfigurationCustomizations(configurationResourceList);
+ service.setServiceProxyCustomizations(serviceProxyList);
+ }
+
+ protected void processNetworkCollections(ToscaResourceStructure toscaResourceStruct, Service service) {
+
+ List<NodeTemplate> networkCollectionList =
+ toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CR);
+
+ if (networkCollectionList != null) {
+ for (NodeTemplate crNode : networkCollectionList) {
+
+ createNetworkCollection(crNode, toscaResourceStruct, service);
+ collectionRepo.saveAndFlush(toscaResourceStruct.getCatalogCollectionResource());
+
+ List<NetworkInstanceGroup> networkInstanceGroupList =
+ toscaResourceStruct.getCatalogNetworkInstanceGroup();
+ for (NetworkInstanceGroup networkInstanceGroup : networkInstanceGroupList) {
+ instanceGroupRepo.saveAndFlush(networkInstanceGroup);
+ }
+
+ }
+ }
+ service.getCollectionResourceCustomizations()
+ .add(toscaResourceStruct.getCatalogCollectionResourceCustomization());
+ }
+
+
+ protected void processVFResources(ToscaResourceStructure toscaResourceStruct, Service service,
+ VfResourceStructure vfResourceStructure) throws Exception {
+ logger.debug("processVFResources");
+
+ List<NodeTemplate> vfNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceVfList();
+ // String servicecategory = toscaResourceStruct.getCatalogService().getCategory();
+ // String serviceType = toscaResourceStruct.getCatalogService().getServiceType();
+
+ for (NodeTemplate nodeTemplate : vfNodeTemplatesList) {
+ Metadata metadata = nodeTemplate.getMetaData();
+ String vfCustomizationCategory = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY);
+ logger.debug("VF Category is : " + vfCustomizationCategory);
+
+ // Do not treat Allotted Resources as VNF resources
+ if (ALLOTTED_RESOURCE.equalsIgnoreCase(vfCustomizationCategory)) {
+ continue;
+ }
+
+ String vfCustomizationUUID = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
+ logger.debug("VFCustomizationUUID=" + vfCustomizationUUID);
+
+ IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance();
+
+ // Make sure the VF ResourceCustomizationUUID from the notification and tosca
+ // customizations match before comparing their VF Modules UUID's
+ logger.debug("Checking if Notification VF ResourceCustomizationUUID: "
+ + vfNotificationResource.getResourceCustomizationUUID() + " matches Tosca VF Customization UUID: "
+ + vfCustomizationUUID);
+
+ if (vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())) {
+ logger.debug("vfCustomizationUUID: " + vfCustomizationUUID
+ + " matches vfNotificationResource CustomizationUUID");
+
+ processVfModules(toscaResourceStruct, vfResourceStructure, service, nodeTemplate, metadata,
+ vfCustomizationCategory);
+ } else {
+ logger.debug("Notification VF ResourceCustomizationUUID: "
+ + vfNotificationResource.getResourceCustomizationUUID() + " doesn't match "
+ + "Tosca VF Customization UUID: " + vfCustomizationUUID);
+ }
+ }
+ }
+
+ /**
+ * This is used to process the PNF specific resource, including resource and resource_customization.
+ * {@link IEntityDetails} based API is used to retrieve information. Please check {@link ISdcCsarHelper} for
+ * details.
+ */
+ protected void processPnfResources(ToscaResourceStructure toscaResourceStruct, Service service,
+ PnfResourceStructure resourceStructure) throws Exception {
+ logger.info("Processing PNF resource: {}", resourceStructure.getResourceInstance().getResourceUUID());
+
+ ISdcCsarHelper sdcCsarHelper = toscaResourceStruct.getSdcCsarHelper();
+ EntityQuery entityQuery = EntityQuery.newBuilder(SdcTypes.PNF).build();
+ TopologyTemplateQuery topologyTemplateQuery = TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build();
+
+ List<IEntityDetails> entityDetailsList = sdcCsarHelper.getEntity(entityQuery, topologyTemplateQuery, false);
+ for (IEntityDetails entityDetails : entityDetailsList) {
+ Metadata metadata = entityDetails.getMetadata();
+ String customizationUUID = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
+ String modelUuid = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID);
+ String notifCustomizationUUID = resourceStructure.getResourceInstance().getResourceCustomizationUUID();
+ if (customizationUUID != null && customizationUUID.equals(notifCustomizationUUID)) {
+ logger.info("Resource customization UUID: {} is the same as notified resource customizationUUID: {}",
+ customizationUUID, notifCustomizationUUID);
+
+ if (checkExistingPnfResourceCutomization(customizationUUID)) {
+ logger.info("Resource customization UUID: {} already deployed", customizationUUID);
+ } else {
+ PnfResource pnfResource = findExistingPnfResource(service, modelUuid);
+ if (pnfResource == null) {
+ pnfResource = createPnfResource(entityDetails);
+ }
+ PnfResourceCustomization pnfResourceCustomization =
+ createPnfResourceCustomization(entityDetails, pnfResource);
+ pnfResource.getPnfResourceCustomizations().add(pnfResourceCustomization);
+ toscaResourceStruct.setPnfResourceCustomization(pnfResourceCustomization);
+ service.getPnfCustomizations().add(pnfResourceCustomization);
+ }
+ } else {
+ logger.warn(
+ "Resource customization UUID: {} is NOT the same as notified resource customizationUUID: {}",
+ customizationUUID, notifCustomizationUUID);
+ }
+ }
+ }
+
+ private PnfResource findExistingPnfResource(Service service, String modelUuid) {
+ PnfResource pnfResource = null;
+ for (PnfResourceCustomization pnfResourceCustomization : service.getPnfCustomizations()) {
+ if (pnfResourceCustomization.getPnfResources() != null
+ && pnfResourceCustomization.getPnfResources().getModelUUID().equals(modelUuid)) {
+ pnfResource = pnfResourceCustomization.getPnfResources();
+ }
+ }
+ if (pnfResource == null) {
+ pnfResource = pnfResourceRepository.findById(modelUuid).orElse(pnfResource);
+ }
+ return pnfResource;
+ }
+
+ private boolean checkExistingPnfResourceCutomization(String customizationUUID) {
+ return pnfCustomizationRepository.findById(customizationUUID).isPresent();
+ }
+
+ /**
+ * Construct the {@link PnfResource} from {@link IEntityDetails} object.
+ */
+ private PnfResource createPnfResource(IEntityDetails entity) {
+ PnfResource pnfResource = new PnfResource();
+ Metadata metadata = entity.getMetadata();
+ pnfResource.setModelInvariantUUID(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
+ pnfResource.setModelName(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
+ pnfResource.setModelUUID(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
+ pnfResource.setModelVersion(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
+ pnfResource.setDescription(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
+ pnfResource.setCategory(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)));
+ pnfResource.setSubCategory(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)));
+ pnfResource.setToscaNodeType(entity.getToscaType());
+ return pnfResource;
+ }
+
+ /**
+ * Construct the {@link PnfResourceCustomization} from {@link IEntityDetails} object.
+ */
+ private PnfResourceCustomization createPnfResourceCustomization(IEntityDetails entityDetails,
+ PnfResource pnfResource) {
+
+ PnfResourceCustomization pnfResourceCustomization = new PnfResourceCustomization();
+ Metadata metadata = entityDetails.getMetadata();
+ Map<String, Property> properties = entityDetails.getProperties();
+ pnfResourceCustomization.setModelCustomizationUUID(
+ testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
+ pnfResourceCustomization.setModelInstanceName(entityDetails.getName());
+ pnfResourceCustomization
+ .setNfFunction(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)));
+ pnfResourceCustomization.setNfNamingCode(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFCODE)));
+ pnfResourceCustomization.setNfRole(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFROLE)));
+ pnfResourceCustomization.setNfType(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFTYPE)));
+ pnfResourceCustomization.setMultiStageDesign(getStringValue(properties.get(MULTI_STAGE_DESIGN)));
+ pnfResourceCustomization.setBlueprintName(getStringValue(properties.get(SDNC_MODEL_NAME)));
+ pnfResourceCustomization.setBlueprintVersion(getStringValue(properties.get(SDNC_MODEL_VERSION)));
+ pnfResourceCustomization.setSkipPostInstConf(getBooleanValue(properties.get(SKIP_POST_INST_CONF)));
+ pnfResourceCustomization.setPnfResources(pnfResource);
+
+ return pnfResourceCustomization;
+ }
+
+ /**
+ * Get value from {@link Property} and cast to boolean value. Return true if property is null.
+ */
+ private boolean getBooleanValue(Property property) {
+ if (null == property) {
+ return true;
+ }
+ Object value = property.getValue();
+ return new Boolean(String.valueOf(value));
+ }
+
+ /**
+ * Get value from {@link Property} and cast to String value. Return empty String if property is null value.
+ */
+ private String getStringValue(Property property) {
+ if (null == property) {
+ return "";
+ }
+ Object value = property.getValue();
+ return String.valueOf(value);
+ }
+
+ protected void processVfModules(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStructure,
+ Service service, NodeTemplate nodeTemplate, Metadata metadata, String vfCustomizationCategory)
+ throws Exception {
+
+ logger.debug("VF Category is : " + vfCustomizationCategory);
+
+ if (vfResourceStructure.getVfModuleStructure() != null
+ && !vfResourceStructure.getVfModuleStructure().isEmpty()) {
+
+ String vfCustomizationUUID = toscaResourceStruct.getSdcCsarHelper().getMetadataPropertyValue(metadata,
+ SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
+ logger.debug("VFCustomizationUUID=" + vfCustomizationUUID);
+
+ IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance();
+
+ // Make sure the VF ResourceCustomizationUUID from the notification and tosca customizations match before
+ // comparing their VF Modules UUID's
+ logger.debug("Checking if Notification VF ResourceCustomizationUUID: "
+ + vfNotificationResource.getResourceCustomizationUUID() + " matches Tosca VF Customization UUID: "
+ + vfCustomizationUUID);
+
+ if (vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())) {
+
+ logger.debug("vfCustomizationUUID: " + vfCustomizationUUID
+ + " matches vfNotificationResource CustomizationUUID");
+
+ VnfResourceCustomization vnfResource = createVnfResource(nodeTemplate, toscaResourceStruct, service);
+
+ Set<CvnfcCustomization> existingCvnfcSet = new HashSet<CvnfcCustomization>();
+ Set<VnfcCustomization> existingVnfcSet = new HashSet<VnfcCustomization>();
+
+ for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) {
+
+ logger.debug("vfModuleStructure:" + vfModuleStructure.toString());
+ List<org.onap.sdc.toscaparser.api.Group> vfGroups =
+ toscaResourceStruct.getSdcCsarHelper().getVfModulesByVf(vfCustomizationUUID);
+ IVfModuleData vfMetadata = vfModuleStructure.getVfModuleMetadata();
+
+ logger.debug("Comparing Vf_Modules_Metadata CustomizationUUID : "
+ + vfMetadata.getVfModuleModelCustomizationUUID());
+
+ Optional<org.onap.sdc.toscaparser.api.Group> matchingObject = vfGroups.stream()
+ .peek(group -> logger.debug("To Csar Group VFModuleModelCustomizationUUID "
+ + group.getMetadata().getValue("vfModuleModelCustomizationUUID")))
+ .filter(group -> group.getMetadata().getValue("vfModuleModelCustomizationUUID")
+ .equals(vfMetadata.getVfModuleModelCustomizationUUID()))
+ .findFirst();
+ if (matchingObject.isPresent()) {
+ VfModuleCustomization vfModuleCustomization = createVFModuleResource(matchingObject.get(),
+ nodeTemplate, toscaResourceStruct, vfResourceStructure, vfMetadata, vnfResource,
+ service, existingCvnfcSet, existingVnfcSet);
+ vfModuleCustomization.getVfModule().setVnfResources(vnfResource.getVnfResources());
+ } else
+ throw new Exception(
+ "Cannot find matching VFModule Customization in Csar for Vf_Modules_Metadata: "
+ + vfMetadata.getVfModuleModelCustomizationUUID());
+
+ }
+
+
+ // Check for VNFC Instance Group info and add it if there is
+ List<Group> groupList =
+ toscaResourceStruct.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType(
+ nodeTemplate, "org.openecomp.groups.VfcInstanceGroup");
+
+ for (Group group : groupList) {
+ VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization =
+ createVNFCInstanceGroup(nodeTemplate, group, vnfResource, toscaResourceStruct);
+ vnfcInstanceGroupCustomizationRepo.saveAndFlush(vnfcInstanceGroupCustomization);
+ }
+
+
+ service.getVnfCustomizations().add(vnfResource);
+ } else {
+ logger.debug("Notification VF ResourceCustomizationUUID: "
+ + vfNotificationResource.getResourceCustomizationUUID() + " doesn't match "
+ + "Tosca VF Customization UUID: " + vfCustomizationUUID);
+ }
+ }
+ }
+
+ public void processWatchdog(String distributionId, String servideUUID, Optional<String> distributionNotification,
+ String consumerId) {
+ WatchdogServiceModVerIdLookup modVerIdLookup =
+ new WatchdogServiceModVerIdLookup(distributionId, servideUUID, distributionNotification, consumerId);
+ watchdogModVerIdLookupRepository.saveAndFlush(modVerIdLookup);
+
+ try {
+
+ WatchdogDistributionStatus distributionStatus = new WatchdogDistributionStatus(distributionId);
+ watchdogDistributionStatusRepository.saveAndFlush(distributionStatus);
+
+ } catch (ObjectOptimisticLockingFailureException e) {
+ logger.debug("ObjectOptimisticLockingFailureException in processWatchdog : " + e.toString());
+ throw e;
+ }
+ }
+
+ protected void extractHeatInformation(ToscaResourceStructure toscaResourceStruct,
+ VfResourceStructure vfResourceStructure) {
+ for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
+
+ switch (vfModuleArtifact.getArtifactInfo().getArtifactType()) {
+ case ASDCConfiguration.HEAT:
+ case ASDCConfiguration.HEAT_NESTED:
+ createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, vfModuleArtifact);
+ break;
+ case ASDCConfiguration.HEAT_VOL:
+ createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, vfModuleArtifact);
+ VfModuleArtifact envModuleArtifact =
+ getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact);
+ createHeatEnvFromArtifact(vfResourceStructure, envModuleArtifact);
+ break;
+ case ASDCConfiguration.HEAT_ENV:
+ createHeatEnvFromArtifact(vfResourceStructure, vfModuleArtifact);
+ break;
+ case ASDCConfiguration.HEAT_ARTIFACT:
+ createHeatFileFromArtifact(vfResourceStructure, vfModuleArtifact, toscaResourceStruct);
+ break;
+ case ASDCConfiguration.HEAT_NET:
+ case ASDCConfiguration.OTHER:
+ logger.warn("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_TYPE_NOT_SUPPORT.toString(),
+ vfModuleArtifact.getArtifactInfo().getArtifactType() + "(Artifact Name:"
+ + vfModuleArtifact.getArtifactInfo().getArtifactName() + ")",
+ ErrorCode.DataError.getValue(), "Artifact type not supported");
+ break;
+ default:
+ break;
+
+ }
+ }
+ }
+
+ protected VfModuleArtifact getHeatEnvArtifactFromGeneratedArtifact(VfResourceStructure vfResourceStructure,
+ VfModuleArtifact vfModuleArtifact) {
+ String artifactName = vfModuleArtifact.getArtifactInfo().getArtifactName();
+ artifactName = artifactName.substring(0, artifactName.indexOf('.'));
+ for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
+ if (moduleArtifact.getArtifactInfo().getArtifactName().contains(artifactName)
+ && moduleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) {
+ return moduleArtifact;
+ }
+ }
+ return null;
+ }
+
+ public String verifyTheFilePrefixInArtifacts(String filebody, VfResourceStructure vfResourceStructure,
+ List<String> listTypes) {
+ String newFileBody = filebody;
+ for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
+
+ if (listTypes.contains(moduleArtifact.getArtifactInfo().getArtifactType())) {
+
+ newFileBody =
+ verifyTheFilePrefixInString(newFileBody, moduleArtifact.getArtifactInfo().getArtifactName());
+ }
+ }
+ return newFileBody;
+ }
+
+ public String verifyTheFilePrefixInString(final String body, final String filenameToVerify) {
+
+ String needlePrefix = "file:///";
+ String prefixedFilenameToVerify = needlePrefix + filenameToVerify;
+
+ if ((body == null) || (body.length() == 0) || (filenameToVerify == null) || (filenameToVerify.length() == 0)) {
+ return body;
+ }
+
+ StringBuilder sb = new StringBuilder(body.length());
+
+ int currentIndex = 0;
+ int startIndex = 0;
+
+ while (currentIndex != -1) {
+ startIndex = currentIndex;
+ currentIndex = body.indexOf(prefixedFilenameToVerify, startIndex);
+
+ if (currentIndex == -1) {
+ break;
+ }
+ // We append from the startIndex up to currentIndex (start of File
+ // Name)
+ sb.append(body.substring(startIndex, currentIndex));
+ sb.append(filenameToVerify);
+
+ currentIndex += prefixedFilenameToVerify.length();
+ }
+
+ sb.append(body.substring(startIndex));
+
+ return sb.toString();
+ }
+
+ protected void createHeatTemplateFromArtifact(VfResourceStructure vfResourceStructure,
+ ToscaResourceStructure toscaResourceStruct, VfModuleArtifact vfModuleArtifact) {
+ HeatTemplate heatTemplate = new HeatTemplate();
+ List<String> typeList = new ArrayList<>();
+ typeList.add(ASDCConfiguration.HEAT_NESTED);
+ typeList.add(ASDCConfiguration.HEAT_ARTIFACT);
+
+ heatTemplate.setTemplateBody(
+ verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList));
+ heatTemplate.setTemplateName(vfModuleArtifact.getArtifactInfo().getArtifactName());
+
+ if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) {
+ heatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout());
+ } else {
+ heatTemplate.setTimeoutMinutes(240);
+ }
+
+ heatTemplate.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
+ heatTemplate.setVersion(BigDecimalVersion
+ .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
+ heatTemplate.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
+
+ if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
+ heatTemplate.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
+ } else {
+ heatTemplate.setArtifactChecksum(MANUAL_RECORD);
+ }
+
+ Set<HeatTemplateParam> heatParam = extractHeatTemplateParameters(vfModuleArtifact.getResult(),
+ vfModuleArtifact.getArtifactInfo().getArtifactUUID());
+ heatTemplate.setParameters(heatParam);
+ vfModuleArtifact.setHeatTemplate(heatTemplate);
+ }
+
+ protected void createHeatEnvFromArtifact(VfResourceStructure vfResourceStructure,
+ VfModuleArtifact vfModuleArtifact) {
+ HeatEnvironment heatEnvironment = new HeatEnvironment();
+ heatEnvironment.setName(vfModuleArtifact.getArtifactInfo().getArtifactName());
+ List<String> typeList = new ArrayList<>();
+ typeList.add(ASDCConfiguration.HEAT);
+ typeList.add(ASDCConfiguration.HEAT_VOL);
+ heatEnvironment.setEnvironment(
+ verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList));
+ heatEnvironment.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
+ heatEnvironment.setVersion(BigDecimalVersion
+ .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
+ heatEnvironment.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
+
+ if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
+ heatEnvironment.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
+ } else {
+ heatEnvironment.setArtifactChecksum(MANUAL_RECORD);
+ }
+ vfModuleArtifact.setHeatEnvironment(heatEnvironment);
+ }
+
+ protected void createHeatFileFromArtifact(VfResourceStructure vfResourceStructure,
+ VfModuleArtifact vfModuleArtifact, ToscaResourceStructure toscaResourceStruct) {
+
+ HeatFiles heatFile = new HeatFiles();
+ heatFile.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
+ heatFile.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
+ heatFile.setFileBody(vfModuleArtifact.getResult());
+ heatFile.setFileName(vfModuleArtifact.getArtifactInfo().getArtifactName());
+ heatFile.setVersion(BigDecimalVersion
+ .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
+ toscaResourceStruct.setHeatFilesUUID(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
+ if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
+ heatFile.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
+ } else {
+ heatFile.setArtifactChecksum(MANUAL_RECORD);
+ }
+ vfModuleArtifact.setHeatFiles(heatFile);
+ }
+
+ protected Service createService(ToscaResourceStructure toscaResourceStructure,
+ ResourceStructure resourceStructure) {
+
+ Metadata serviceMetadata = toscaResourceStructure.getServiceMetadata();
+
+ Service service = new Service();
+
+ if (serviceMetadata != null) {
+
+ if (toscaResourceStructure.getServiceVersion() != null) {
+ service.setModelVersion(toscaResourceStructure.getServiceVersion());
+ }
+
+ service.setServiceType(serviceMetadata.getValue("serviceType"));
+ service.setServiceRole(serviceMetadata.getValue("serviceRole"));
+ service.setCategory(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY));
+
+ service.setDescription(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+ service.setModelName(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ service.setModelUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ service.setEnvironmentContext(serviceMetadata.getValue("environmentContext"));
+
+ if (resourceStructure != null)
+ service.setWorkloadContext(resourceStructure.getNotification().getWorkloadContext());
+
+ service.setModelInvariantUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ service.setCsar(toscaResourceStructure.getCatalogToscaCsar());
+ }
+
+
+ toscaResourceStructure.setCatalogService(service);
+ return service;
+ }
+
+ protected ServiceProxyResourceCustomization createServiceProxy(NodeTemplate nodeTemplate, Service service,
+ ToscaResourceStructure toscaResourceStructure) {
+
+ Metadata spMetadata = nodeTemplate.getMetaData();
+
+ ServiceProxyResourceCustomization spCustomizationResource = new ServiceProxyResourceCustomization();
+
+ Set<ServiceProxyResourceCustomization> serviceProxyCustomizationSet = new HashSet<>();
+
+ spCustomizationResource.setModelName(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ spCustomizationResource
+ .setModelInvariantUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ spCustomizationResource.setModelUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ spCustomizationResource.setModelVersion(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ spCustomizationResource.setDescription(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+
+ spCustomizationResource
+ .setModelCustomizationUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+ spCustomizationResource.setModelInstanceName(nodeTemplate.getName());
+ spCustomizationResource.setToscaNodeType(nodeTemplate.getType());
+
+ String sourceServiceUUID = spMetadata.getValue("sourceModelUuid");
+
+ Service sourceService = serviceRepo.findOneByModelUUID(sourceServiceUUID);
+
+ spCustomizationResource.setSourceService(sourceService);
+ spCustomizationResource.setToscaNodeType(nodeTemplate.getType());
+ serviceProxyCustomizationSet.add(spCustomizationResource);
+
+
+ toscaResourceStructure.setCatalogServiceProxyResourceCustomization(spCustomizationResource);
+
+ return spCustomizationResource;
+ }
+
+ protected ConfigurationResourceCustomization createConfiguration(NodeTemplate nodeTemplate,
+ ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization,
+ Optional<ConfigurationResourceCustomization> vnrResourceCustomization) {
+
+ ConfigurationResourceCustomization configCustomizationResource =
+ getConfigurationResourceCustomization(nodeTemplate, toscaResourceStructure, spResourceCustomization);
+
+ ConfigurationResource configResource = getConfigurationResource(nodeTemplate);
+
+ Set<ConfigurationResourceCustomization> configResourceCustomizationSet = new HashSet<>();
+
+ StatefulEntityType entityType = nodeTemplate.getTypeDefinition();
+ String type = entityType.getType();
+
+ if (NODES_VRF_ENTRY.equals(type)) {
+ configCustomizationResource.setConfigResourceCustomization(vnrResourceCustomization.orElse(null));
+ }
+
+ configCustomizationResource.setConfigurationResource(configResource);
+
+ configResourceCustomizationSet.add(configCustomizationResource);
+
+ configResource.setConfigurationResourceCustomization(configResourceCustomizationSet);
+
+ toscaResourceStructure.setCatalogConfigurationResource(configResource);
+
+ toscaResourceStructure.setCatalogConfigurationResourceCustomization(configCustomizationResource);
+
+ return configCustomizationResource;
+ }
+
+ protected ConfigurationResource createFabricConfiguration(NodeTemplate nodeTemplate,
+ ToscaResourceStructure toscaResourceStructure) {
+
+ Metadata fabricMetadata = nodeTemplate.getMetaData();
+
+ ConfigurationResource configResource = new ConfigurationResource();
+
+ configResource.setModelName(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ configResource.setModelInvariantUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ configResource.setModelUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ configResource.setModelVersion(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ configResource.setDescription(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+ configResource.setToscaNodeType(nodeTemplate.getType());
+
+ return configResource;
+ }
+
+ protected void createToscaCsar(ToscaResourceStructure toscaResourceStructure) {
+ ToscaCsar toscaCsar = new ToscaCsar();
+ if (toscaResourceStructure.getToscaArtifact().getArtifactChecksum() != null) {
+ toscaCsar.setArtifactChecksum(toscaResourceStructure.getToscaArtifact().getArtifactChecksum());
+ } else {
+ toscaCsar.setArtifactChecksum(MANUAL_RECORD);
+ }
+ toscaCsar.setArtifactUUID(toscaResourceStructure.getToscaArtifact().getArtifactUUID());
+ toscaCsar.setName(toscaResourceStructure.getToscaArtifact().getArtifactName());
+ toscaCsar.setVersion(toscaResourceStructure.getToscaArtifact().getArtifactVersion());
+ toscaCsar.setDescription(toscaResourceStructure.getToscaArtifact().getArtifactDescription());
+ toscaCsar.setUrl(toscaResourceStructure.getToscaArtifact().getArtifactURL());
+
+ toscaResourceStructure.setCatalogToscaCsar(toscaCsar);
+ }
+
+ protected VnfcCustomization findExistingVfc(Set<VnfcCustomization> vnfcCustomizations, String customizationUUID) {
+ VnfcCustomization vnfcCustomization = null;
+ for (VnfcCustomization vnfcCustom : vnfcCustomizations) {
+ if (vnfcCustom != null && vnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) {
+ vnfcCustomization = vnfcCustom;
+ }
+ }
+
+ if (vnfcCustomization == null)
+ vnfcCustomization = vnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID);
+ // vnfcCustomization = new VnfcCustomization();
+
+ return vnfcCustomization;
+ }
+
+ protected CvnfcCustomization findExistingCvfc(Set<CvnfcCustomization> cvnfcCustomizations,
+ String customizationUUID) {
+ CvnfcCustomization cvnfcCustomization = null;
+ for (CvnfcCustomization cvnfcCustom : cvnfcCustomizations) {
+ if (cvnfcCustom != null && cvnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) {
+ cvnfcCustomization = cvnfcCustom;
+ }
+ }
+
+ if (cvnfcCustomization == null)
+ cvnfcCustomization = cvnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID);
+
+ return cvnfcCustomization;
+ }
+
+ protected NetworkResourceCustomization createNetwork(NodeTemplate networkNodeTemplate,
+ ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin,
+ Service service) {
+
+ NetworkResourceCustomization networkResourceCustomization =
+ networkCustomizationRepo.findOneByModelCustomizationUUID(
+ networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+
+ boolean networkUUIDsMatch = true;
+ // Check to make sure the NetworkResourceUUID on the Customization record matches the NetworkResourceUUID from
+ // the distribution.
+ // If not we'll update the Customization record with latest from the distribution
+ if (networkResourceCustomization != null) {
+ String existingNetworkModelUUID = networkResourceCustomization.getNetworkResource().getModelUUID();
+ String latestNetworkModelUUID =
+ networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID);
+
+ if (!existingNetworkModelUUID.equals(latestNetworkModelUUID)) {
+ networkUUIDsMatch = false;
+ }
+
+ }
+
+ if (networkResourceCustomization != null && !networkUUIDsMatch) {
+
+ NetworkResource networkResource =
+ createNetworkResource(networkNodeTemplate, toscaResourceStructure, heatTemplate, aicMax, aicMin);
+
+ networkResourceCustomization.setNetworkResource(networkResource);
+
+ networkCustomizationRepo.saveAndFlush(networkResourceCustomization);
+
+ } else if (networkResourceCustomization == null) {
+ networkResourceCustomization =
+ createNetworkResourceCustomization(networkNodeTemplate, toscaResourceStructure);
+
+ NetworkResource networkResource = findExistingNetworkResource(service,
+ networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ if (networkResource == null)
+ networkResource = createNetworkResource(networkNodeTemplate, toscaResourceStructure, heatTemplate,
+ aicMax, aicMin);
+
+ networkResource.addNetworkResourceCustomization(networkResourceCustomization);
+ networkResourceCustomization.setNetworkResource(networkResource);
+ }
+
+ return networkResourceCustomization;
+ }
+
+ protected NetworkResource findExistingNetworkResource(Service service, String modelUUID) {
+ NetworkResource networkResource = null;
+ for (NetworkResourceCustomization networkCustom : service.getNetworkCustomizations()) {
+ if (networkCustom.getNetworkResource() != null
+ && networkCustom.getNetworkResource().getModelUUID().equals(modelUUID)) {
+ networkResource = networkCustom.getNetworkResource();
+ }
+ }
+ if (networkResource == null)
+ networkResource = networkRepo.findResourceByModelUUID(modelUUID);
+
+ return networkResource;
+ }
+
+ protected NetworkResourceCustomization createNetworkResourceCustomization(NodeTemplate networkNodeTemplate,
+ ToscaResourceStructure toscaResourceStructure) {
+ NetworkResourceCustomization networkResourceCustomization = new NetworkResourceCustomization();
+ networkResourceCustomization.setModelInstanceName(
+ testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
+ networkResourceCustomization.setModelCustomizationUUID(
+ testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
+
+ networkResourceCustomization.setNetworkTechnology(
+ testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
+ SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY)));
+ networkResourceCustomization.setNetworkType(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE)));
+ networkResourceCustomization.setNetworkRole(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE)));
+ networkResourceCustomization.setNetworkScope(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE)));
+ return networkResourceCustomization;
+ }
+
+ protected NetworkResource createNetworkResource(NodeTemplate networkNodeTemplate,
+ ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin) {
+ NetworkResource networkResource = new NetworkResource();
+ String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(
+ networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK);
+
+ if ("true".equalsIgnoreCase(providerNetwork)) {
+ networkResource.setNeutronNetworkType(PROVIDER);
+ } else {
+ networkResource.setNeutronNetworkType(BASIC);
+ }
+
+ networkResource.setModelName(
+ testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
+
+ networkResource.setModelInvariantUUID(
+ testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
+ networkResource.setModelUUID(
+ testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
+ networkResource.setModelVersion(
+ testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
+
+ networkResource.setAicVersionMax(aicMax);
+ networkResource.setAicVersionMin(aicMin);
+ networkResource.setToscaNodeType(networkNodeTemplate.getType());
+ networkResource.setDescription(
+ testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
+ networkResource.setOrchestrationMode(HEAT);
+ networkResource.setHeatTemplate(heatTemplate);
+ return networkResource;
+ }
+
+ protected CollectionNetworkResourceCustomization createNetworkCollection(NodeTemplate networkNodeTemplate,
+ ToscaResourceStructure toscaResourceStructure, Service service) {
+
+ CollectionNetworkResourceCustomization collectionNetworkResourceCustomization =
+ new CollectionNetworkResourceCustomization();
+
+ // **** Build Object to populate Collection_Resource table
+ CollectionResource collectionResource = new CollectionResource();
+
+ collectionResource
+ .setModelName(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ collectionResource.setModelInvariantUUID(
+ networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ collectionResource
+ .setModelUUID(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ collectionResource
+ .setModelVersion(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ collectionResource
+ .setDescription(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+ collectionResource.setToscaNodeType(networkNodeTemplate.getType());
+
+ toscaResourceStructure.setCatalogCollectionResource(collectionResource);
+
+ // **** Build object to populate Collection_Resource_Customization table
+ NetworkCollectionResourceCustomization ncfc = new NetworkCollectionResourceCustomization();
+
+ ncfc.setFunction(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
+ "cr_function"));
+ ncfc.setRole(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
+ "cr_role"));
+ ncfc.setType(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
+ "cr_type"));
+
+ ncfc.setModelInstanceName(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ ncfc.setModelCustomizationUUID(
+ networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+
+ Set<CollectionNetworkResourceCustomization> networkResourceCustomizationSet = new HashSet<>();
+ networkResourceCustomizationSet.add(collectionNetworkResourceCustomization);
+
+ ncfc.setNetworkResourceCustomization(networkResourceCustomizationSet);
+
+ ncfc.setCollectionResource(collectionResource);
+ toscaResourceStructure.setCatalogCollectionResourceCustomization(ncfc);
+
+ // *** Build object to populate the Instance_Group table
+ List<Group> groupList =
+ toscaResourceStructure.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType(
+ networkNodeTemplate, "org.openecomp.groups.NetworkCollection");
+
+ List<NetworkInstanceGroup> networkInstanceGroupList = new ArrayList<>();
+
+ List<CollectionResourceInstanceGroupCustomization> collectionResourceInstanceGroupCustomizationList =
+ new ArrayList<CollectionResourceInstanceGroupCustomization>();
+
+ for (Group group : groupList) {
+
+ NetworkInstanceGroup networkInstanceGroup = new NetworkInstanceGroup();
+ Metadata instanceMetadata = group.getMetadata();
+ networkInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ networkInstanceGroup
+ .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ networkInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ networkInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ networkInstanceGroup.setToscaNodeType(group.getType());
+ networkInstanceGroup.setRole(SubType.SUB_INTERFACE.toString()); // Set
+ // Role
+ networkInstanceGroup.setType(InstanceGroupType.L3_NETWORK); // Set
+ // type
+ networkInstanceGroup.setCollectionResource(collectionResource);
+
+ // ****Build object to populate
+ // Collection_Resource_Instance_Group_Customization table
+ CollectionResourceInstanceGroupCustomization crInstanceGroupCustomization =
+ new CollectionResourceInstanceGroupCustomization();
+ crInstanceGroupCustomization.setInstanceGroup(networkInstanceGroup);
+ crInstanceGroupCustomization.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ crInstanceGroupCustomization.setModelCustomizationUUID(
+ networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+
+ // Loop through the template policy to find the subinterface_network_quantity property name. Then extract
+ // the value for it.
+ List<Policy> policyList =
+ toscaResourceStructure.getSdcCsarHelper().getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(
+ networkNodeTemplate, "org.openecomp.policies.scaling.Fixed");
+
+ if (policyList != null) {
+ for (Policy policy : policyList) {
+ for (String policyNetworkCollection : policy.getTargets()) {
+
+ if (policyNetworkCollection.equalsIgnoreCase(group.getName())) {
+
+ Map<String, Object> propMap = policy.getPolicyProperties();
+
+ if (propMap.get("quantity") != null) {
+
+ String quantity = toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(networkNodeTemplate,
+ getPropertyInput(propMap.get("quantity").toString()));
+
+ if (quantity != null) {
+ crInstanceGroupCustomization
+ .setSubInterfaceNetworkQuantity(Integer.parseInt(quantity));
+ }
+
+ }
+
+ }
+ }
+ }
+ }
+
+ crInstanceGroupCustomization.setDescription(
+ toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
+ instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)
+ + "_network_collection_description"));
+ crInstanceGroupCustomization.setFunction(
+ toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
+ instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)
+ + "_network_collection_function"));
+ crInstanceGroupCustomization.setCollectionResourceCust(ncfc);
+ collectionResourceInstanceGroupCustomizationList.add(crInstanceGroupCustomization);
+
+ networkInstanceGroup
+ .setCollectionInstanceGroupCustomizations(collectionResourceInstanceGroupCustomizationList);
+
+ networkInstanceGroupList.add(networkInstanceGroup);
+
+
+ toscaResourceStructure.setCatalogNetworkInstanceGroup(networkInstanceGroupList);
+
+ List<NodeTemplate> vlNodeList = toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplateBySdcType(networkNodeTemplate, SdcTypes.VL);
+
+ List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomizationList = new ArrayList<>();
+
+ // *****Build object to populate the NetworkResource table
+ NetworkResource networkResource = new NetworkResource();
+
+ for (NodeTemplate vlNodeTemplate : vlNodeList) {
+
+ String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(
+ vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK);
+
+ if ("true".equalsIgnoreCase(providerNetwork)) {
+ networkResource.setNeutronNetworkType(PROVIDER);
+ } else {
+ networkResource.setNeutronNetworkType(BASIC);
+ }
+
+ networkResource
+ .setModelName(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+
+ networkResource.setModelInvariantUUID(
+ vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ networkResource
+ .setModelUUID(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ networkResource
+ .setModelVersion(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+
+ networkResource.setAicVersionMax(
+ vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES));
+
+ TempNetworkHeatTemplateLookup tempNetworkLookUp =
+ tempNetworkLookupRepo.findFirstBynetworkResourceModelName(
+ vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+
+ if (tempNetworkLookUp != null) {
+
+ HeatTemplate heatTemplate =
+ heatRepo.findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid());
+ networkResource.setHeatTemplate(heatTemplate);
+
+ networkResource.setAicVersionMin(tempNetworkLookUp.getAicVersionMin());
+
+ }
+
+ networkResource.setToscaNodeType(vlNodeTemplate.getType());
+ networkResource.setDescription(
+ vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+ networkResource.setOrchestrationMode(HEAT);
+
+ // Build object to populate the
+ // Collection_Network_Resource_Customization table
+ for (NodeTemplate memberNode : group.getMemberNodes()) {
+ collectionNetworkResourceCustomization.setModelInstanceName(memberNode.getName());
+ }
+
+ collectionNetworkResourceCustomization.setModelCustomizationUUID(
+ vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+
+ collectionNetworkResourceCustomization.setNetworkTechnology(
+ toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNodeTemplate,
+ SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY));
+ collectionNetworkResourceCustomization.setNetworkType(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE));
+ collectionNetworkResourceCustomization.setNetworkRole(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE));
+ collectionNetworkResourceCustomization.setNetworkScope(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE));
+ collectionNetworkResourceCustomization.setInstanceGroup(networkInstanceGroup);
+ collectionNetworkResourceCustomization.setNetworkResource(networkResource);
+ collectionNetworkResourceCustomization.setNetworkResourceCustomization(ncfc);
+
+ collectionNetworkResourceCustomizationList.add(collectionNetworkResourceCustomization);
+ }
+
+ }
+
+ return collectionNetworkResourceCustomization;
+ }
+
+ protected VnfcInstanceGroupCustomization createVNFCInstanceGroup(NodeTemplate vnfcNodeTemplate, Group group,
+ VnfResourceCustomization vnfResourceCustomization, ToscaResourceStructure toscaResourceStructure) {
+
+ Metadata instanceMetadata = group.getMetadata();
+ // Populate InstanceGroup
+ VFCInstanceGroup vfcInstanceGroup = new VFCInstanceGroup();
+
+ vfcInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ vfcInstanceGroup.setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ vfcInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ vfcInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ vfcInstanceGroup.setToscaNodeType(group.getType());
+ vfcInstanceGroup.setRole("SUB-INTERFACE"); // Set Role
+ vfcInstanceGroup.setType(InstanceGroupType.VNFC); // Set type
+
+ // Populate VNFCInstanceGroupCustomization
+ VnfcInstanceGroupCustomization vfcInstanceGroupCustom = new VnfcInstanceGroupCustomization();
+
+ vfcInstanceGroupCustom.setVnfResourceCust(vnfResourceCustomization);
+ vnfResourceCustomization.getVnfcInstanceGroupCustomizations().add(vfcInstanceGroupCustom);
+
+ vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup);
+ vfcInstanceGroup.getVnfcInstanceGroupCustomizations().add(vfcInstanceGroupCustom);
+
+ vfcInstanceGroupCustom.setDescription(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+
+ String getInputName = null;
+ String groupProperty = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
+ "vfc_instance_group_function");
+ if (groupProperty != null) {
+ int getInputIndex = groupProperty.indexOf("{get_input=");
+ if (getInputIndex > -1) {
+ getInputName = groupProperty.substring(getInputIndex + 11, groupProperty.length() - 1);
+ }
+ }
+ vfcInstanceGroupCustom.setFunction(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vnfcNodeTemplate, getInputName));
+ vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup);
+
+
+ return vfcInstanceGroupCustom;
+
+ }
+
+ protected VfModuleCustomization createVFModuleResource(Group group, NodeTemplate vfTemplate,
+ ToscaResourceStructure toscaResourceStructure, VfResourceStructure vfResourceStructure,
+ IVfModuleData vfModuleData, VnfResourceCustomization vnfResource, Service service,
+ Set<CvnfcCustomization> existingCvnfcSet, Set<VnfcCustomization> existingVnfcSet) {
+
+ VfModuleCustomization vfModuleCustomization =
+ findExistingVfModuleCustomization(vnfResource, vfModuleData.getVfModuleModelCustomizationUUID());
+ if (vfModuleCustomization == null) {
+ VfModule vfModule = findExistingVfModule(vnfResource,
+ vfTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID));
+ Metadata vfMetadata = group.getMetadata();
+ if (vfModule == null)
+ vfModule = createVfModule(group, toscaResourceStructure, vfModuleData, vfMetadata);
+
+ vfModuleCustomization = createVfModuleCustomization(group, toscaResourceStructure, vfModule, vfModuleData);
+ vfModuleCustomization.setVnfCustomization(vnfResource);
+ setHeatInformationForVfModule(toscaResourceStructure, vfResourceStructure, vfModule, vfModuleCustomization,
+ vfMetadata);
+ vfModuleCustomization.setVfModule(vfModule);
+ vfModule.getVfModuleCustomization().add(vfModuleCustomization);
+ vnfResource.getVfModuleCustomizations().add(vfModuleCustomization);
+ } else {
+ vfResourceStructure.setAlreadyDeployed(true);
+ }
+
+ // ******************************************************************************************************************
+ // * Extract VFC's and CVFC's then add them to VFModule
+ // ******************************************************************************************************************
+
+ Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomizations =
+ new HashSet<CvnfcConfigurationCustomization>();
+ Set<CvnfcCustomization> cvnfcCustomizations = new HashSet<CvnfcCustomization>();
+ Set<VnfcCustomization> vnfcCustomizations = new HashSet<VnfcCustomization>();
+
+ // Only set the CVNFC if this vfModule group is a member of it.
+ List<NodeTemplate> groupMembers =
+ toscaResourceStructure.getSdcCsarHelper().getMembersOfVfModule(vfTemplate, group);
+ String vfModuleMemberName = null;
+
+ for (NodeTemplate node : groupMembers) {
+ vfModuleMemberName = node.getName();
+ }
+
+ // Extract CVFC lists
+ List<NodeTemplate> cvfcList =
+ toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(vfTemplate, SdcTypes.CVFC);
+
+ for (NodeTemplate cvfcTemplate : cvfcList) {
+ boolean cvnfcVfModuleNameMatch = false;
+
+ for (NodeTemplate node : groupMembers) {
+ vfModuleMemberName = node.getName();
+
+ if (vfModuleMemberName.equalsIgnoreCase(cvfcTemplate.getName())) {
+ cvnfcVfModuleNameMatch = true;
+ break;
+ }
+ }
+
+ if (vfModuleMemberName != null && cvnfcVfModuleNameMatch) {
+
+ // Extract associated VFC - Should always be just one
+ List<NodeTemplate> vfcList =
+ toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(cvfcTemplate, SdcTypes.VFC);
+
+ for (NodeTemplate vfcTemplate : vfcList) {
+
+ VnfcCustomization vnfcCustomization = new VnfcCustomization();
+ VnfcCustomization existingVnfcCustomization = null;
+
+ existingVnfcCustomization = findExistingVfc(existingVnfcSet,
+ vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+
+ if (existingVnfcCustomization == null) {
+ vnfcCustomization = new VnfcCustomization();
+ } else {
+ vnfcCustomization = existingVnfcCustomization;
+ }
+
+ // Only Add Abstract VNFC's to our DB, ignore all others
+ if (existingVnfcCustomization == null && vfcTemplate.getMetaData()
+ .getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY).equalsIgnoreCase("Abstract")) {
+ vnfcCustomization.setModelCustomizationUUID(
+ vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+ vnfcCustomization.setModelInstanceName(vfcTemplate.getName());
+ vnfcCustomization.setModelInvariantUUID(
+ vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ vnfcCustomization
+ .setModelName(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ vnfcCustomization
+ .setModelUUID(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+
+ vnfcCustomization.setModelVersion(
+ testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
+ vnfcCustomization.setDescription(testNull(
+ vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
+ vnfcCustomization.setToscaNodeType(testNull(vfcTemplate.getType()));
+
+ vnfcCustomizations.add(vnfcCustomization);
+ existingVnfcSet.add(vnfcCustomization);
+ }
+
+ // This check is needed incase the VFC subcategory is
+ // something other than Abstract. In that case we want to
+ // skip adding that record to our DB.
+ if (vnfcCustomization.getModelCustomizationUUID() != null) {
+ CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
+ cvnfcCustomization.setModelCustomizationUUID(
+ cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+ cvnfcCustomization.setModelInstanceName(cvfcTemplate.getName());
+ cvnfcCustomization.setModelInvariantUUID(
+ cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ cvnfcCustomization
+ .setModelName(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ cvnfcCustomization
+ .setModelUUID(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+
+ cvnfcCustomization.setModelVersion(
+ testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
+ cvnfcCustomization.setDescription(testNull(
+ cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
+ cvnfcCustomization.setToscaNodeType(testNull(cvfcTemplate.getType()));
+
+ if (existingVnfcCustomization != null) {
+ cvnfcCustomization.setVnfcCustomization(existingVnfcCustomization);
+ } else {
+ cvnfcCustomization.setVnfcCustomization(vnfcCustomization);
+ }
+
+ cvnfcCustomization.setNfcFunction(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(cvfcTemplate, "nfc_function"));
+ cvnfcCustomization.setNfcNamingCode(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(cvfcTemplate, "nfc_naming_code"));
+ cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization);
+
+ cvnfcCustomizations.add(cvnfcCustomization);
+ existingCvnfcSet.add(cvnfcCustomization);
+
+ // *****************************************************************************************************************************************
+ // * Extract Fabric Configuration
+ // *****************************************************************************************************************************************
+
+ List<NodeTemplate> fabricConfigList = toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplateBySdcType(vfTemplate, SdcTypes.CONFIGURATION);
+
+ for (NodeTemplate fabricTemplate : fabricConfigList) {
+
+ ConfigurationResource fabricConfig = null;
+
+ ConfigurationResource existingConfig = findExistingConfiguration(service,
+ fabricTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+
+ if (existingConfig == null) {
+
+ fabricConfig = createFabricConfiguration(fabricTemplate, toscaResourceStructure);
+
+ } else {
+ fabricConfig = existingConfig;
+ }
+
+ CvnfcConfigurationCustomization cvnfcConfigurationCustomization =
+ createCvnfcConfigurationCustomization(fabricTemplate, toscaResourceStructure,
+ vnfResource, vfModuleCustomization, cvnfcCustomization, fabricConfig,
+ vfTemplate, vfModuleMemberName);
+ cvnfcConfigurationCustomizations.add(cvnfcConfigurationCustomization);
+
+ fabricConfig.setCvnfcConfigurationCustomization(cvnfcConfigurationCustomizations);
+ }
+ cvnfcCustomization.setCvnfcConfigurationCustomization(cvnfcConfigurationCustomizations);
+ }
+
+ }
+
+ }
+ }
+ vfModuleCustomization.setCvnfcCustomization(cvnfcCustomizations);
+
+ return vfModuleCustomization;
+ }
+
+ protected CvnfcConfigurationCustomization createCvnfcConfigurationCustomization(NodeTemplate fabricTemplate,
+ ToscaResourceStructure toscaResourceStruct, VnfResourceCustomization vnfResource,
+ VfModuleCustomization vfModuleCustomization, CvnfcCustomization cvnfcCustomization,
ConfigurationResource configResource, NodeTemplate vfTemplate, String vfModuleMemberName) {
- Metadata fabricMetadata = fabricTemplate.getMetaData();
-
- CvnfcConfigurationCustomization cvnfcConfigurationCustomization = new CvnfcConfigurationCustomization();
-
- cvnfcConfigurationCustomization.setConfigurationResource(configResource);
-
- cvnfcConfigurationCustomization.setCvnfcCustomization(cvnfcCustomization);
-
- cvnfcConfigurationCustomization.setModelCustomizationUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
- cvnfcConfigurationCustomization.setModelInstanceName(fabricTemplate.getName());
-
- List<Policy> policyList = toscaResourceStruct.getSdcCsarHelper().getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(vfTemplate, "org.openecomp.policies.External");
-
- if(policyList != null){
- for(Policy policy : policyList){
-
- for(String policyCvfcTarget : policy.getTargets()){
-
- if(policyCvfcTarget.equalsIgnoreCase(vfModuleMemberName)){
-
- Map<String, Object> propMap = policy.getPolicyProperties();
-
- if(propMap.get("type").toString().equalsIgnoreCase("Fabric Policy")){
- cvnfcConfigurationCustomization.setPolicyName(propMap.get("name").toString());
- }
- }
- }
- }
- }
-
- cvnfcConfigurationCustomization.setConfigurationFunction(toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "function"));
- cvnfcConfigurationCustomization.setConfigurationRole(toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "role"));
- cvnfcConfigurationCustomization.setConfigurationType(toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "type"));
-
- return cvnfcConfigurationCustomization;
- }
-
- protected ConfigurationResource findExistingConfiguration(Service service, String modelUUID) {
- ConfigurationResource configResource = null;
- for(ConfigurationResourceCustomization configurationResourceCustom : service.getConfigurationCustomizations()){
- if (configurationResourceCustom.getConfigurationResource() != null
- && configurationResourceCustom.getConfigurationResource().getModelUUID().equals(modelUUID)) {
- configResource = configurationResourceCustom.getConfigurationResource();
- }
- }
-
- return configResource;
- }
-
- protected VfModuleCustomization findExistingVfModuleCustomization(VnfResourceCustomization vnfResource,
- String vfModuleModelCustomizationUUID) {
- VfModuleCustomization vfModuleCustomization = null;
- for(VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()){
- if(vfModuleCustom.getModelCustomizationUUID().equalsIgnoreCase(vfModuleModelCustomizationUUID)){
- vfModuleCustomization = vfModuleCustom;
- }
- }
- return vfModuleCustomization;
- }
-
- protected VfModule findExistingVfModule(VnfResourceCustomization vnfResource, String modelUUID) {
- VfModule vfModule = null;
- for(VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()){
- if(vfModuleCustom.getVfModule() != null && vfModuleCustom.getVfModule().getModelUUID().equals(modelUUID)){
- vfModule = vfModuleCustom.getVfModule();
- }
- }
- if(vfModule==null)
- vfModule = vfModuleRepo.findByModelUUID(modelUUID);
-
- return vfModule;
- }
-
- protected VfModuleCustomization createVfModuleCustomization(Group group,
- ToscaResourceStructure toscaResourceStructure, VfModule vfModule, IVfModuleData vfModuleData) {
- VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
-
- vfModuleCustomization.setModelCustomizationUUID(vfModuleData.getVfModuleModelCustomizationUUID());
-
- vfModuleCustomization.setVfModule(vfModule);
-
- String initialCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
- SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT);
- if (initialCount != null && initialCount.length() > 0) {
- vfModuleCustomization.setInitialCount(Integer.valueOf(initialCount));
- }
-
- vfModuleCustomization.setInitialCount(Integer.valueOf(toscaResourceStructure.getSdcCsarHelper()
- .getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT)));
-
- String availabilityZoneCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
- SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT);
- if (availabilityZoneCount != null && availabilityZoneCount.length() > 0) {
- vfModuleCustomization.setAvailabilityZoneCount(Integer.valueOf(availabilityZoneCount));
- }
-
- vfModuleCustomization.setLabel(toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
- SdcPropertyNames.PROPERTY_NAME_VFMODULELABEL));
-
- String maxInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
- SdcPropertyNames.PROPERTY_NAME_MAXVFMODULEINSTANCES);
- if (maxInstances != null && maxInstances.length() > 0) {
- vfModuleCustomization.setMaxInstances(Integer.valueOf(maxInstances));
- }
-
- String minInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
- SdcPropertyNames.PROPERTY_NAME_MINVFMODULEINSTANCES);
- if (minInstances != null && minInstances.length() > 0) {
- vfModuleCustomization.setMinInstances(Integer.valueOf(minInstances));
- }
- return vfModuleCustomization;
- }
-
- protected VfModule createVfModule(Group group, ToscaResourceStructure toscaResourceStructure,
- IVfModuleData vfModuleData, Metadata vfMetadata) {
- VfModule vfModule = new VfModule();
- String vfModuleModelUUID = vfModuleData.getVfModuleModelUUID();
-
- if(vfModuleModelUUID == null) {
- vfModuleModelUUID = testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
- SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID));
- } else if (vfModuleModelUUID.indexOf('.') > -1) {
- vfModuleModelUUID = vfModuleModelUUID.substring(0, vfModuleModelUUID.indexOf('.'));
- }
-
- vfModule.setModelInvariantUUID(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)));
- vfModule.setModelName(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
- SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME)));
- vfModule.setModelUUID(vfModuleModelUUID);
- vfModule.setModelVersion(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
- SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION)));
- vfModule.setDescription(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
- SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
-
- String vfModuleType = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
- SdcPropertyNames.PROPERTY_NAME_VFMODULETYPE);
- if (vfModuleType != null && "Base".equalsIgnoreCase(vfModuleType)) {
- vfModule.setIsBase(true);
- } else {
- vfModule.setIsBase(false);
- }
- return vfModule;
- }
-
- protected void setHeatInformationForVfModule(ToscaResourceStructure toscaResourceStructure,
- VfResourceStructure vfResourceStructure, VfModule vfModule, VfModuleCustomization vfModuleCustomization,
- Metadata vfMetadata) {
-
- Optional<VfModuleStructure> matchingObject = vfResourceStructure.getVfModuleStructure().stream()
- .filter(vfModuleStruct -> vfModuleStruct.getVfModuleMetadata().getVfModuleModelUUID()
- .equalsIgnoreCase(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
- SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)))
- .findFirst();
-
- if (matchingObject.isPresent()) {
- List<HeatFiles> heatFilesList = new ArrayList<>();
- List<HeatTemplate> volumeHeatChildTemplates = new ArrayList<HeatTemplate>();
- List<HeatTemplate> heatChildTemplates = new ArrayList<HeatTemplate>();
- HeatTemplate parentHeatTemplate = new HeatTemplate();
- String parentArtifactType = null;
- Set<String> artifacts = new HashSet<>(matchingObject.get().getVfModuleMetadata().getArtifacts());
- for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
-
- List<HeatTemplate> childNestedHeatTemplates = new ArrayList<HeatTemplate>();
-
- if (artifacts.contains(vfModuleArtifact.getArtifactInfo().getArtifactUUID())) {
- checkVfModuleArtifactType(vfModule, vfModuleCustomization, heatFilesList, vfModuleArtifact,
- childNestedHeatTemplates, parentHeatTemplate, vfResourceStructure);
- }
-
- if(vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)){
- parentArtifactType = identifyParentOfNestedTemplate(matchingObject.get(), vfModuleArtifact);
-
- if(!childNestedHeatTemplates.isEmpty()){
-
- if (parentArtifactType != null && parentArtifactType.equalsIgnoreCase(ASDCConfiguration.HEAT_VOL)) {
- volumeHeatChildTemplates.add(childNestedHeatTemplates.get(0));
- } else {
- heatChildTemplates.add(childNestedHeatTemplates.get(0));
- }
- }
- }
-
- }
- if(!heatFilesList.isEmpty()){
- vfModule.setHeatFiles(heatFilesList);
- }
-
-
- // Set all Child Templates related to HEAT_VOLUME
- if(!volumeHeatChildTemplates.isEmpty()){
- if(vfModule.getVolumeHeatTemplate() != null){
- vfModule.getVolumeHeatTemplate().setChildTemplates(volumeHeatChildTemplates);
- }else{
- logger.debug("VolumeHeatTemplate not set in setHeatInformationForVfModule()");
- }
- }
-
- // Set all Child Templates related to HEAT
- if(!heatChildTemplates.isEmpty()){
- if(vfModule.getModuleHeatTemplate() != null){
- vfModule.getModuleHeatTemplate().setChildTemplates(heatChildTemplates);
- }else{
- logger.debug("ModuleHeatTemplate not set in setHeatInformationForVfModule()");
- }
- }
- }
- }
-
- protected void checkVfModuleArtifactType(VfModule vfModule, VfModuleCustomization vfModuleCustomization,
- List<HeatFiles> heatFilesList, VfModuleArtifact vfModuleArtifact, List<HeatTemplate> nestedHeatTemplates,
- HeatTemplate parentHeatTemplate, VfResourceStructure vfResourceStructure) {
- if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT)) {
- vfModuleArtifact.incrementDeployedInDB();
- vfModule.setModuleHeatTemplate(vfModuleArtifact.getHeatTemplate());
- } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_VOL)) {
- vfModule.setVolumeHeatTemplate(vfModuleArtifact.getHeatTemplate());
- VfModuleArtifact volVfModuleArtifact = this.getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact);
- vfModuleCustomization.setVolumeHeatEnv(volVfModuleArtifact.getHeatEnvironment());
- vfModuleArtifact.incrementDeployedInDB();
- } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) {
- if(vfModuleArtifact.getHeatEnvironment().getName().contains("volume")) {
- vfModuleCustomization.setVolumeHeatEnv(vfModuleArtifact.getHeatEnvironment());
- } else {
- vfModuleCustomization.setHeatEnvironment(vfModuleArtifact.getHeatEnvironment());
- }
- vfModuleArtifact.incrementDeployedInDB();
- } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ARTIFACT)) {
- heatFilesList.add(vfModuleArtifact.getHeatFiles());
- vfModuleArtifact.incrementDeployedInDB();
- } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) {
- nestedHeatTemplates.add(vfModuleArtifact.getHeatTemplate());
- vfModuleArtifact.incrementDeployedInDB();
- }
- }
-
- protected VnfResourceCustomization createVnfResource(NodeTemplate vfNodeTemplate,
- ToscaResourceStructure toscaResourceStructure, Service service) {
- VnfResourceCustomization vnfResourceCustomization = null;
- if(vnfResourceCustomization == null){
- VnfResource vnfResource = findExistingVnfResource(service,
- vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
-
- if(vnfResource==null)
- vnfResource=createVnfResource(vfNodeTemplate);
-
- vnfResourceCustomization = createVnfResourceCustomization(vfNodeTemplate, toscaResourceStructure,
- vnfResource);
- vnfResourceCustomization.setVnfResources(vnfResource);
- vnfResourceCustomization.setService(service);
- vnfResource.getVnfResourceCustomizations().add(vnfResourceCustomization);
-
- }
- return vnfResourceCustomization;
- }
-
- protected VnfResource findExistingVnfResource(Service service, String modelUUID) {
- VnfResource vnfResource = null;
- for(VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()){
- if (vnfResourceCustom.getVnfResources() != null
- && vnfResourceCustom.getVnfResources().getModelUUID().equals(modelUUID)) {
- vnfResource = vnfResourceCustom.getVnfResources();
- }
- }
- if(vnfResource==null)
- vnfResource = vnfRepo.findResourceByModelUUID(modelUUID);
-
- return vnfResource;
- }
-
- protected VnfResourceCustomization createVnfResourceCustomization(NodeTemplate vfNodeTemplate,
- ToscaResourceStructure toscaResourceStructure, VnfResource vnfResource) {
- VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization();
- vnfResourceCustomization.setModelCustomizationUUID(
- testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
- vnfResourceCustomization.setModelInstanceName(vfNodeTemplate.getName());
-
- vnfResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)));
- vnfResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(vfNodeTemplate, "nf_naming_code")));
- vnfResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)));
- vnfResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)));
-
- vnfResourceCustomization.setMultiStageDesign(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(vfNodeTemplate, MULTI_STAGE_DESIGN));
-
- vnfResourceCustomization.setBlueprintName(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SDNC_MODEL_NAME)));
-
- vnfResourceCustomization.setBlueprintVersion(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SDNC_MODEL_VERSION)));
-
- String skipPostInstConfText = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SKIP_POST_INST_CONF);
- if (skipPostInstConfText != null){
- vnfResourceCustomization.setSkipPostInstConf(Boolean.parseBoolean(skipPostInstConfText));
- }
-
- vnfResourceCustomization.setVnfResources(vnfResource);
- vnfResourceCustomization.setAvailabilityZoneMaxCount(Integer.getInteger(
- vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT)));
-
- CapabilityAssignments vnfCustomizationCapability = toscaResourceStructure.getSdcCsarHelper()
- .getCapabilitiesOf(vfNodeTemplate);
-
- if (vnfCustomizationCapability != null) {
- CapabilityAssignment capAssign = vnfCustomizationCapability.getCapabilityByName(SCALABLE);
-
- if (capAssign != null) {
- vnfResourceCustomization.setMinInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper()
- .getCapabilityPropertyLeafValue(capAssign, SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
- vnfResourceCustomization.setMaxInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper()
- .getCapabilityPropertyLeafValue(capAssign, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
- }
-
- }
-
- toscaResourceStructure.setCatalogVnfResourceCustomization(vnfResourceCustomization);
-
- return vnfResourceCustomization;
- }
-
- protected VnfResource createVnfResource(NodeTemplate vfNodeTemplate) {
- VnfResource vnfResource = new VnfResource();
- vnfResource.setModelInvariantUUID(
- testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
- vnfResource.setModelName(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
- vnfResource.setModelUUID(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
-
- vnfResource.setModelVersion(
- testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
- vnfResource.setDescription(
- testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
- vnfResource.setOrchestrationMode(HEAT);
- vnfResource.setToscaNodeType(testNull(vfNodeTemplate.getType()));
- vnfResource.setAicVersionMax(
- testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
- vnfResource.setAicVersionMin(
- testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
- vnfResource.setCategory(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY));
- vnfResource.setSubCategory(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY));
-
- return vnfResource;
- }
-
- protected AllottedResourceCustomization createAllottedResource(NodeTemplate nodeTemplate,
- ToscaResourceStructure toscaResourceStructure, Service service) {
- AllottedResourceCustomization allottedResourceCustomization = allottedCustomizationRepo
- .findOneByModelCustomizationUUID(
- nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
-
- if(allottedResourceCustomization == null){
- AllottedResource allottedResource = findExistingAllottedResource(service,
- nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
-
- if(allottedResource==null)
- allottedResource=createAR(nodeTemplate);
-
- toscaResourceStructure.setAllottedResource(allottedResource);
- allottedResourceCustomization = createAllottedResourceCustomization(nodeTemplate, toscaResourceStructure);
- allottedResourceCustomization.setAllottedResource(allottedResource);
- allottedResource.getAllotedResourceCustomization().add(allottedResourceCustomization);
- }
- return allottedResourceCustomization;
- }
-
- protected AllottedResource findExistingAllottedResource(Service service, String modelUUID) {
- AllottedResource allottedResource = null;
- for(AllottedResourceCustomization allottedResourceCustom : service.getAllottedCustomizations()){
- if (allottedResourceCustom.getAllottedResource() != null
- && allottedResourceCustom.getAllottedResource().getModelUUID().equals(modelUUID)) {
- allottedResource = allottedResourceCustom.getAllottedResource();
- }
- }
- if(allottedResource==null)
- allottedResource = allottedRepo.findResourceByModelUUID(modelUUID);
-
- return allottedResource;
- }
-
- protected AllottedResourceCustomization createAllottedResourceCustomization(NodeTemplate nodeTemplate,
- ToscaResourceStructure toscaResourceStructure) {
- AllottedResourceCustomization allottedResourceCustomization = new AllottedResourceCustomization();
- allottedResourceCustomization.setModelCustomizationUUID(
- testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
- allottedResourceCustomization.setModelInstanceName(nodeTemplate.getName());
-
-
- allottedResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)));
- allottedResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(nodeTemplate, "nf_naming_code")));
- allottedResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)));
- allottedResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper()
- .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)));
-
- List<NodeTemplate> vfcNodes = toscaResourceStructure.getSdcCsarHelper().getVfcListByVf(allottedResourceCustomization.getModelCustomizationUUID());
-
- if(vfcNodes != null){
- for(NodeTemplate vfcNode : vfcNodes){
-
- allottedResourceCustomization.setProvidingServiceModelUUID(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_uuid"));
- allottedResourceCustomization.setProvidingServiceModelInvariantUUID(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_invariant_uuid"));
- allottedResourceCustomization.setProvidingServiceModelName(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_name"));
- }
- }
-
-
- CapabilityAssignments arCustomizationCapability = toscaResourceStructure.getSdcCsarHelper()
- .getCapabilitiesOf(nodeTemplate);
-
- if (arCustomizationCapability != null) {
- CapabilityAssignment capAssign = arCustomizationCapability.getCapabilityByName(SCALABLE);
-
- if (capAssign != null) {
- allottedResourceCustomization.setMinInstances(
- Integer.getInteger(toscaResourceStructure.getSdcCsarHelper().getCapabilityPropertyLeafValue(
- capAssign, SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
- allottedResourceCustomization.setMaxInstances(
- Integer.getInteger(toscaResourceStructure.getSdcCsarHelper().getCapabilityPropertyLeafValue(
- capAssign, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
- }
- }
- return allottedResourceCustomization;
- }
-
- protected AllottedResource createAR(NodeTemplate nodeTemplate) {
- AllottedResource allottedResource = new AllottedResource();
- allottedResource
- .setModelUUID(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
- allottedResource.setModelInvariantUUID(
- testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
- allottedResource
- .setModelName(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
- allottedResource
- .setModelVersion(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
- allottedResource.setToscaNodeType(testNull(nodeTemplate.getType()));
- allottedResource.setSubcategory(
- testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)));
- allottedResource
- .setDescription(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
- return allottedResource;
- }
-
- protected Set<HeatTemplateParam> extractHeatTemplateParameters(String yamlFile, String artifactUUID) {
- // Scan the payload downloadResult and extract the HeatTemplate
- // parameters
- YamlEditor yamlEditor = new YamlEditor(yamlFile.getBytes());
- return yamlEditor.getParameterList(artifactUUID);
- }
-
- protected String testNull(Object object) {
-
- if (object == null) {
- return null;
- } else if (object.equals("NULL")) {
- return null;
- } else if (object instanceof Integer) {
- return object.toString();
- } else if (object instanceof String) {
- return (String) object;
- } else {
- return "Type not recognized";
- }
- }
-
- protected static String identifyParentOfNestedTemplate(VfModuleStructure vfModuleStructure,
- VfModuleArtifact heatNestedArtifact) {
-
- if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT) != null && vfModuleStructure
- .getArtifactsMap().get(ASDCConfiguration.HEAT).get(0).getArtifactInfo().getRelatedArtifacts() != null) {
- for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0)
- .getArtifactInfo().getRelatedArtifacts()) {
- if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) {
- return ASDCConfiguration.HEAT;
- }
-
- }
- }
-
- if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) != null
- && vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo()
- .getRelatedArtifacts() != null) {
- for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL)
- .get(0).getArtifactInfo().getRelatedArtifacts()) {
- if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) {
- return ASDCConfiguration.HEAT_VOL;
- }
-
- }
- }
-
- // Does not belong to anything
- return null;
-
- }
-
- protected static String createVNFName(VfResourceStructure vfResourceStructure) {
-
- return vfResourceStructure.getNotification().getServiceName() + "/"
- + vfResourceStructure.getResourceInstance().getResourceInstanceName();
- }
-
- protected static String createVfModuleName(VfModuleStructure vfModuleStructure) {
-
- return createVNFName(vfModuleStructure.getParentVfResource()) + "::"
- + vfModuleStructure.getVfModuleMetadata().getVfModuleModelName();
- }
-
- protected String getPropertyInput(String propertyName){
-
- String inputName = new String();
-
- if (propertyName != null) {
- int getInputIndex = propertyName.indexOf("{get_input=");
- if (getInputIndex > -1) {
- inputName = propertyName.substring(getInputIndex+11, propertyName.length()-1);
- }
- }
-
- return inputName;
- }
-
-
- protected static Timestamp getCurrentTimeStamp() {
-
- return new Timestamp(new Date().getTime());
- }
+ Metadata fabricMetadata = fabricTemplate.getMetaData();
+
+ CvnfcConfigurationCustomization cvnfcConfigurationCustomization = new CvnfcConfigurationCustomization();
+
+ cvnfcConfigurationCustomization.setConfigurationResource(configResource);
+
+ cvnfcConfigurationCustomization.setCvnfcCustomization(cvnfcCustomization);
+
+ cvnfcConfigurationCustomization
+ .setModelCustomizationUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+ cvnfcConfigurationCustomization.setModelInstanceName(fabricTemplate.getName());
+
+ List<Policy> policyList = toscaResourceStruct.getSdcCsarHelper()
+ .getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(vfTemplate, "org.openecomp.policies.External");
+
+ if (policyList != null) {
+ for (Policy policy : policyList) {
+
+ for (String policyCvfcTarget : policy.getTargets()) {
+
+ if (policyCvfcTarget.equalsIgnoreCase(vfModuleMemberName)) {
+
+ Map<String, Object> propMap = policy.getPolicyProperties();
+
+ if (propMap.get("type").toString().equalsIgnoreCase("Fabric Policy")) {
+ cvnfcConfigurationCustomization.setPolicyName(propMap.get("name").toString());
+ }
+ }
+ }
+ }
+ }
+
+ cvnfcConfigurationCustomization.setConfigurationFunction(
+ toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "function"));
+ cvnfcConfigurationCustomization.setConfigurationRole(
+ toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "role"));
+ cvnfcConfigurationCustomization.setConfigurationType(
+ toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "type"));
+
+ return cvnfcConfigurationCustomization;
+ }
+
+ protected ConfigurationResource findExistingConfiguration(Service service, String modelUUID) {
+ ConfigurationResource configResource = null;
+ for (ConfigurationResourceCustomization configurationResourceCustom : service
+ .getConfigurationCustomizations()) {
+ if (configurationResourceCustom.getConfigurationResource() != null
+ && configurationResourceCustom.getConfigurationResource().getModelUUID().equals(modelUUID)) {
+ configResource = configurationResourceCustom.getConfigurationResource();
+ }
+ }
+
+ return configResource;
+ }
+
+ protected VfModuleCustomization findExistingVfModuleCustomization(VnfResourceCustomization vnfResource,
+ String vfModuleModelCustomizationUUID) {
+ VfModuleCustomization vfModuleCustomization = null;
+ for (VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()) {
+ if (vfModuleCustom.getModelCustomizationUUID().equalsIgnoreCase(vfModuleModelCustomizationUUID)) {
+ vfModuleCustomization = vfModuleCustom;
+ }
+ }
+ return vfModuleCustomization;
+ }
+
+ protected VfModule findExistingVfModule(VnfResourceCustomization vnfResource, String modelUUID) {
+ VfModule vfModule = null;
+ for (VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()) {
+ if (vfModuleCustom.getVfModule() != null && vfModuleCustom.getVfModule().getModelUUID().equals(modelUUID)) {
+ vfModule = vfModuleCustom.getVfModule();
+ }
+ }
+ if (vfModule == null)
+ vfModule = vfModuleRepo.findByModelUUID(modelUUID);
+
+ return vfModule;
+ }
+
+ protected VfModuleCustomization createVfModuleCustomization(Group group,
+ ToscaResourceStructure toscaResourceStructure, VfModule vfModule, IVfModuleData vfModuleData) {
+ VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
+
+ vfModuleCustomization.setModelCustomizationUUID(vfModuleData.getVfModuleModelCustomizationUUID());
+
+ vfModuleCustomization.setVfModule(vfModule);
+
+ String initialCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
+ SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT);
+ if (initialCount != null && initialCount.length() > 0) {
+ vfModuleCustomization.setInitialCount(Integer.valueOf(initialCount));
+ }
+
+ vfModuleCustomization.setInitialCount(Integer.valueOf(toscaResourceStructure.getSdcCsarHelper()
+ .getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT)));
+
+ String availabilityZoneCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
+ SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT);
+ if (availabilityZoneCount != null && availabilityZoneCount.length() > 0) {
+ vfModuleCustomization.setAvailabilityZoneCount(Integer.valueOf(availabilityZoneCount));
+ }
+
+ vfModuleCustomization.setLabel(toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
+ SdcPropertyNames.PROPERTY_NAME_VFMODULELABEL));
+
+ String maxInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
+ SdcPropertyNames.PROPERTY_NAME_MAXVFMODULEINSTANCES);
+ if (maxInstances != null && maxInstances.length() > 0) {
+ vfModuleCustomization.setMaxInstances(Integer.valueOf(maxInstances));
+ }
+
+ String minInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
+ SdcPropertyNames.PROPERTY_NAME_MINVFMODULEINSTANCES);
+ if (minInstances != null && minInstances.length() > 0) {
+ vfModuleCustomization.setMinInstances(Integer.valueOf(minInstances));
+ }
+ return vfModuleCustomization;
+ }
+
+ protected VfModule createVfModule(Group group, ToscaResourceStructure toscaResourceStructure,
+ IVfModuleData vfModuleData, Metadata vfMetadata) {
+ VfModule vfModule = new VfModule();
+ String vfModuleModelUUID = vfModuleData.getVfModuleModelUUID();
+
+ if (vfModuleModelUUID == null) {
+ vfModuleModelUUID = testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
+ SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID));
+ } else if (vfModuleModelUUID.indexOf('.') > -1) {
+ vfModuleModelUUID = vfModuleModelUUID.substring(0, vfModuleModelUUID.indexOf('.'));
+ }
+
+ vfModule.setModelInvariantUUID(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)));
+ vfModule.setModelName(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
+ SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME)));
+ vfModule.setModelUUID(vfModuleModelUUID);
+ vfModule.setModelVersion(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
+ SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION)));
+ vfModule.setDescription(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
+ SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
+
+ String vfModuleType = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
+ SdcPropertyNames.PROPERTY_NAME_VFMODULETYPE);
+ if (vfModuleType != null && "Base".equalsIgnoreCase(vfModuleType)) {
+ vfModule.setIsBase(true);
+ } else {
+ vfModule.setIsBase(false);
+ }
+ return vfModule;
+ }
+
+ protected void setHeatInformationForVfModule(ToscaResourceStructure toscaResourceStructure,
+ VfResourceStructure vfResourceStructure, VfModule vfModule, VfModuleCustomization vfModuleCustomization,
+ Metadata vfMetadata) {
+
+ Optional<VfModuleStructure> matchingObject = vfResourceStructure.getVfModuleStructure().stream()
+ .filter(vfModuleStruct -> vfModuleStruct.getVfModuleMetadata().getVfModuleModelUUID()
+ .equalsIgnoreCase(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
+ SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)))
+ .findFirst();
+
+ if (matchingObject.isPresent()) {
+ List<HeatFiles> heatFilesList = new ArrayList<>();
+ List<HeatTemplate> volumeHeatChildTemplates = new ArrayList<HeatTemplate>();
+ List<HeatTemplate> heatChildTemplates = new ArrayList<HeatTemplate>();
+ HeatTemplate parentHeatTemplate = new HeatTemplate();
+ String parentArtifactType = null;
+ Set<String> artifacts = new HashSet<>(matchingObject.get().getVfModuleMetadata().getArtifacts());
+ for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
+
+ List<HeatTemplate> childNestedHeatTemplates = new ArrayList<HeatTemplate>();
+
+ if (artifacts.contains(vfModuleArtifact.getArtifactInfo().getArtifactUUID())) {
+ checkVfModuleArtifactType(vfModule, vfModuleCustomization, heatFilesList, vfModuleArtifact,
+ childNestedHeatTemplates, parentHeatTemplate, vfResourceStructure);
+ }
+
+ if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) {
+ parentArtifactType = identifyParentOfNestedTemplate(matchingObject.get(), vfModuleArtifact);
+
+ if (!childNestedHeatTemplates.isEmpty()) {
+
+ if (parentArtifactType != null
+ && parentArtifactType.equalsIgnoreCase(ASDCConfiguration.HEAT_VOL)) {
+ volumeHeatChildTemplates.add(childNestedHeatTemplates.get(0));
+ } else {
+ heatChildTemplates.add(childNestedHeatTemplates.get(0));
+ }
+ }
+ }
+
+ }
+ if (!heatFilesList.isEmpty()) {
+ vfModule.setHeatFiles(heatFilesList);
+ }
+
+
+ // Set all Child Templates related to HEAT_VOLUME
+ if (!volumeHeatChildTemplates.isEmpty()) {
+ if (vfModule.getVolumeHeatTemplate() != null) {
+ vfModule.getVolumeHeatTemplate().setChildTemplates(volumeHeatChildTemplates);
+ } else {
+ logger.debug("VolumeHeatTemplate not set in setHeatInformationForVfModule()");
+ }
+ }
+
+ // Set all Child Templates related to HEAT
+ if (!heatChildTemplates.isEmpty()) {
+ if (vfModule.getModuleHeatTemplate() != null) {
+ vfModule.getModuleHeatTemplate().setChildTemplates(heatChildTemplates);
+ } else {
+ logger.debug("ModuleHeatTemplate not set in setHeatInformationForVfModule()");
+ }
+ }
+ }
+ }
+
+ protected void checkVfModuleArtifactType(VfModule vfModule, VfModuleCustomization vfModuleCustomization,
+ List<HeatFiles> heatFilesList, VfModuleArtifact vfModuleArtifact, List<HeatTemplate> nestedHeatTemplates,
+ HeatTemplate parentHeatTemplate, VfResourceStructure vfResourceStructure) {
+ if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT)) {
+ vfModuleArtifact.incrementDeployedInDB();
+ vfModule.setModuleHeatTemplate(vfModuleArtifact.getHeatTemplate());
+ } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_VOL)) {
+ vfModule.setVolumeHeatTemplate(vfModuleArtifact.getHeatTemplate());
+ VfModuleArtifact volVfModuleArtifact =
+ this.getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact);
+ vfModuleCustomization.setVolumeHeatEnv(volVfModuleArtifact.getHeatEnvironment());
+ vfModuleArtifact.incrementDeployedInDB();
+ } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) {
+ if (vfModuleArtifact.getHeatEnvironment().getName().contains("volume")) {
+ vfModuleCustomization.setVolumeHeatEnv(vfModuleArtifact.getHeatEnvironment());
+ } else {
+ vfModuleCustomization.setHeatEnvironment(vfModuleArtifact.getHeatEnvironment());
+ }
+ vfModuleArtifact.incrementDeployedInDB();
+ } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ARTIFACT)) {
+ heatFilesList.add(vfModuleArtifact.getHeatFiles());
+ vfModuleArtifact.incrementDeployedInDB();
+ } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) {
+ nestedHeatTemplates.add(vfModuleArtifact.getHeatTemplate());
+ vfModuleArtifact.incrementDeployedInDB();
+ }
+ }
+
+ protected VnfResourceCustomization createVnfResource(NodeTemplate vfNodeTemplate,
+ ToscaResourceStructure toscaResourceStructure, Service service) {
+ VnfResourceCustomization vnfResourceCustomization = null;
+ if (vnfResourceCustomization == null) {
+ VnfResource vnfResource = findExistingVnfResource(service,
+ vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+
+ if (vnfResource == null)
+ vnfResource = createVnfResource(vfNodeTemplate);
+
+ vnfResourceCustomization =
+ createVnfResourceCustomization(vfNodeTemplate, toscaResourceStructure, vnfResource);
+ vnfResourceCustomization.setVnfResources(vnfResource);
+ vnfResourceCustomization.setService(service);
+ vnfResource.getVnfResourceCustomizations().add(vnfResourceCustomization);
+
+ }
+ return vnfResourceCustomization;
+ }
+
+ protected VnfResource findExistingVnfResource(Service service, String modelUUID) {
+ VnfResource vnfResource = null;
+ for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) {
+ if (vnfResourceCustom.getVnfResources() != null
+ && vnfResourceCustom.getVnfResources().getModelUUID().equals(modelUUID)) {
+ vnfResource = vnfResourceCustom.getVnfResources();
+ }
+ }
+ if (vnfResource == null)
+ vnfResource = vnfRepo.findResourceByModelUUID(modelUUID);
+
+ return vnfResource;
+ }
+
+ protected VnfResourceCustomization createVnfResourceCustomization(NodeTemplate vfNodeTemplate,
+ ToscaResourceStructure toscaResourceStructure, VnfResource vnfResource) {
+ VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization();
+ vnfResourceCustomization.setModelCustomizationUUID(
+ testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
+ vnfResourceCustomization.setModelInstanceName(vfNodeTemplate.getName());
+
+ vnfResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)));
+ vnfResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vfNodeTemplate, "nf_naming_code")));
+ vnfResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)));
+ vnfResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)));
+
+ vnfResourceCustomization.setMultiStageDesign(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vfNodeTemplate, MULTI_STAGE_DESIGN));
+
+ vnfResourceCustomization.setBlueprintName(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SDNC_MODEL_NAME)));
+
+ vnfResourceCustomization.setBlueprintVersion(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SDNC_MODEL_VERSION)));
+
+ String skipPostInstConfText = toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SKIP_POST_INST_CONF);
+ if (skipPostInstConfText != null) {
+ vnfResourceCustomization.setSkipPostInstConf(Boolean.parseBoolean(skipPostInstConfText));
+ }
+
+ vnfResourceCustomization.setVnfResources(vnfResource);
+ vnfResourceCustomization.setAvailabilityZoneMaxCount(Integer.getInteger(
+ vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT)));
+
+ CapabilityAssignments vnfCustomizationCapability =
+ toscaResourceStructure.getSdcCsarHelper().getCapabilitiesOf(vfNodeTemplate);
+
+ if (vnfCustomizationCapability != null) {
+ CapabilityAssignment capAssign = vnfCustomizationCapability.getCapabilityByName(SCALABLE);
+
+ if (capAssign != null) {
+ vnfResourceCustomization.setMinInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper()
+ .getCapabilityPropertyLeafValue(capAssign, SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
+ vnfResourceCustomization.setMaxInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper()
+ .getCapabilityPropertyLeafValue(capAssign, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
+ }
+
+ }
+
+ toscaResourceStructure.setCatalogVnfResourceCustomization(vnfResourceCustomization);
+
+ return vnfResourceCustomization;
+ }
+
+ protected VnfResource createVnfResource(NodeTemplate vfNodeTemplate) {
+ VnfResource vnfResource = new VnfResource();
+ vnfResource.setModelInvariantUUID(
+ testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
+ vnfResource.setModelName(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
+ vnfResource.setModelUUID(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
+
+ vnfResource.setModelVersion(
+ testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
+ vnfResource.setDescription(
+ testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
+ vnfResource.setOrchestrationMode(HEAT);
+ vnfResource.setToscaNodeType(testNull(vfNodeTemplate.getType()));
+ vnfResource.setAicVersionMax(
+ testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
+ vnfResource.setAicVersionMin(
+ testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
+ vnfResource.setCategory(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY));
+ vnfResource.setSubCategory(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY));
+
+ return vnfResource;
+ }
+
+ protected AllottedResourceCustomization createAllottedResource(NodeTemplate nodeTemplate,
+ ToscaResourceStructure toscaResourceStructure, Service service) {
+ AllottedResourceCustomization allottedResourceCustomization =
+ allottedCustomizationRepo.findOneByModelCustomizationUUID(
+ nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+
+ if (allottedResourceCustomization == null) {
+ AllottedResource allottedResource = findExistingAllottedResource(service,
+ nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+
+ if (allottedResource == null)
+ allottedResource = createAR(nodeTemplate);
+
+ toscaResourceStructure.setAllottedResource(allottedResource);
+ allottedResourceCustomization = createAllottedResourceCustomization(nodeTemplate, toscaResourceStructure);
+ allottedResourceCustomization.setAllottedResource(allottedResource);
+ allottedResource.getAllotedResourceCustomization().add(allottedResourceCustomization);
+ }
+ return allottedResourceCustomization;
+ }
+
+ protected AllottedResource findExistingAllottedResource(Service service, String modelUUID) {
+ AllottedResource allottedResource = null;
+ for (AllottedResourceCustomization allottedResourceCustom : service.getAllottedCustomizations()) {
+ if (allottedResourceCustom.getAllottedResource() != null
+ && allottedResourceCustom.getAllottedResource().getModelUUID().equals(modelUUID)) {
+ allottedResource = allottedResourceCustom.getAllottedResource();
+ }
+ }
+ if (allottedResource == null)
+ allottedResource = allottedRepo.findResourceByModelUUID(modelUUID);
+
+ return allottedResource;
+ }
+
+ protected AllottedResourceCustomization createAllottedResourceCustomization(NodeTemplate nodeTemplate,
+ ToscaResourceStructure toscaResourceStructure) {
+ AllottedResourceCustomization allottedResourceCustomization = new AllottedResourceCustomization();
+ allottedResourceCustomization.setModelCustomizationUUID(
+ testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
+ allottedResourceCustomization.setModelInstanceName(nodeTemplate.getName());
+
+
+ allottedResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)));
+ allottedResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(nodeTemplate, "nf_naming_code")));
+ allottedResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)));
+ allottedResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)));
+
+ List<NodeTemplate> vfcNodes = toscaResourceStructure.getSdcCsarHelper()
+ .getVfcListByVf(allottedResourceCustomization.getModelCustomizationUUID());
+
+ if (vfcNodes != null) {
+ for (NodeTemplate vfcNode : vfcNodes) {
+
+ allottedResourceCustomization.setProvidingServiceModelUUID(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_uuid"));
+ allottedResourceCustomization
+ .setProvidingServiceModelInvariantUUID(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_invariant_uuid"));
+ allottedResourceCustomization.setProvidingServiceModelName(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_name"));
+ }
+ }
+
+
+ CapabilityAssignments arCustomizationCapability =
+ toscaResourceStructure.getSdcCsarHelper().getCapabilitiesOf(nodeTemplate);
+
+ if (arCustomizationCapability != null) {
+ CapabilityAssignment capAssign = arCustomizationCapability.getCapabilityByName(SCALABLE);
+
+ if (capAssign != null) {
+ allottedResourceCustomization.setMinInstances(
+ Integer.getInteger(toscaResourceStructure.getSdcCsarHelper().getCapabilityPropertyLeafValue(
+ capAssign, SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
+ allottedResourceCustomization.setMaxInstances(
+ Integer.getInteger(toscaResourceStructure.getSdcCsarHelper().getCapabilityPropertyLeafValue(
+ capAssign, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
+ }
+ }
+ return allottedResourceCustomization;
+ }
+
+ protected AllottedResource createAR(NodeTemplate nodeTemplate) {
+ AllottedResource allottedResource = new AllottedResource();
+ allottedResource
+ .setModelUUID(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
+ allottedResource.setModelInvariantUUID(
+ testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
+ allottedResource
+ .setModelName(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
+ allottedResource
+ .setModelVersion(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
+ allottedResource.setToscaNodeType(testNull(nodeTemplate.getType()));
+ allottedResource.setSubcategory(
+ testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)));
+ allottedResource
+ .setDescription(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+ return allottedResource;
+ }
+
+ protected Set<HeatTemplateParam> extractHeatTemplateParameters(String yamlFile, String artifactUUID) {
+ // Scan the payload downloadResult and extract the HeatTemplate
+ // parameters
+ YamlEditor yamlEditor = new YamlEditor(yamlFile.getBytes());
+ return yamlEditor.getParameterList(artifactUUID);
+ }
+
+ protected String testNull(Object object) {
+
+ if (object == null) {
+ return null;
+ } else if (object.equals("NULL")) {
+ return null;
+ } else if (object instanceof Integer) {
+ return object.toString();
+ } else if (object instanceof String) {
+ return (String) object;
+ } else {
+ return "Type not recognized";
+ }
+ }
+
+ protected static String identifyParentOfNestedTemplate(VfModuleStructure vfModuleStructure,
+ VfModuleArtifact heatNestedArtifact) {
+
+ if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT) != null && vfModuleStructure
+ .getArtifactsMap().get(ASDCConfiguration.HEAT).get(0).getArtifactInfo().getRelatedArtifacts() != null) {
+ for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0)
+ .getArtifactInfo().getRelatedArtifacts()) {
+ if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) {
+ return ASDCConfiguration.HEAT;
+ }
+
+ }
+ }
+
+ if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) != null
+ && vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo()
+ .getRelatedArtifacts() != null) {
+ for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL)
+ .get(0).getArtifactInfo().getRelatedArtifacts()) {
+ if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) {
+ return ASDCConfiguration.HEAT_VOL;
+ }
+
+ }
+ }
+
+ // Does not belong to anything
+ return null;
+
+ }
+
+ protected static String createVNFName(VfResourceStructure vfResourceStructure) {
+
+ return vfResourceStructure.getNotification().getServiceName() + "/"
+ + vfResourceStructure.getResourceInstance().getResourceInstanceName();
+ }
+
+ protected static String createVfModuleName(VfModuleStructure vfModuleStructure) {
+
+ return createVNFName(vfModuleStructure.getParentVfResource()) + "::"
+ + vfModuleStructure.getVfModuleMetadata().getVfModuleModelName();
+ }
+
+ protected String getPropertyInput(String propertyName) {
+
+ String inputName = new String();
+
+ if (propertyName != null) {
+ int getInputIndex = propertyName.indexOf("{get_input=");
+ if (getInputIndex > -1) {
+ inputName = propertyName.substring(getInputIndex + 11, propertyName.length() - 1);
+ }
+ }
+
+ return inputName;
+ }
+
+
+ protected static Timestamp getCurrentTimeStamp() {
+
+ return new Timestamp(new Date().getTime());
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImpl.java
index 7b769bd532..6ca97c7c67 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImpl.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImpl.java
@@ -22,7 +22,6 @@ package org.onap.so.asdc.tenantIsolation;
import java.net.MalformedURLException;
import java.net.URL;
-
import org.onap.so.client.aai.AAIProperties;
import org.onap.so.client.aai.AAIVersion;
import org.onap.so.spring.SpringContextHelper;
@@ -30,42 +29,42 @@ import org.springframework.context.ApplicationContext;
public class AaiClientPropertiesImpl implements AAIProperties {
- private String aaiEndpoint;
- private String auth;
- private String key;
- private static final String SYSTEM_NAME = "MSO";
-
- public AaiClientPropertiesImpl() {
- ApplicationContext context = SpringContextHelper.getAppContext();
- aaiEndpoint = context.getEnvironment().getProperty("mso.aai.endpoint");
- this.auth = context.getEnvironment().getProperty("aai.auth");
- this.key = context.getEnvironment().getProperty("mso.msoKey");
- }
+ private String aaiEndpoint;
+ private String auth;
+ private String key;
+ private static final String SYSTEM_NAME = "MSO";
+
+ public AaiClientPropertiesImpl() {
+ ApplicationContext context = SpringContextHelper.getAppContext();
+ aaiEndpoint = context.getEnvironment().getProperty("mso.aai.endpoint");
+ this.auth = context.getEnvironment().getProperty("aai.auth");
+ this.key = context.getEnvironment().getProperty("mso.msoKey");
+ }
+
+ @Override
+ public URL getEndpoint() throws MalformedURLException {
+ ApplicationContext context = SpringContextHelper.getAppContext();
+ aaiEndpoint = context.getEnvironment().getProperty("mso.aai.endpoint");
+ return new URL(aaiEndpoint);
+ }
+
+ @Override
+ public String getSystemName() {
+ return SYSTEM_NAME;
+ }
- @Override
- public URL getEndpoint() throws MalformedURLException {
- ApplicationContext context = SpringContextHelper.getAppContext();
- aaiEndpoint = context.getEnvironment().getProperty("mso.aai.endpoint");
- return new URL(aaiEndpoint);
- }
+ @Override
+ public AAIVersion getDefaultVersion() {
+ return AAIVersion.LATEST;
+ }
- @Override
- public String getSystemName() {
- return SYSTEM_NAME;
- }
-
- @Override
- public AAIVersion getDefaultVersion() {
- return AAIVersion.LATEST;
- }
-
- @Override
- public String getAuth() {
- return this.auth;
- }
+ @Override
+ public String getAuth() {
+ return this.auth;
+ }
- @Override
- public String getKey() {
- return this.key;
- }
+ @Override
+ public String getKey() {
+ return this.key;
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/DistributionStatus.java b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/DistributionStatus.java
index d092712a8b..7be29718c0 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/DistributionStatus.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/DistributionStatus.java
@@ -22,8 +22,5 @@ package org.onap.so.asdc.tenantIsolation;
public enum DistributionStatus {
- SUCCESS,
- FAILURE,
- TIMEOUT,
- INCOMPLETE
+ SUCCESS, FAILURE, TIMEOUT, INCOMPLETE
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java
index c95d701cb2..3659ceed12 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java
@@ -25,7 +25,6 @@ package org.onap.so.asdc.tenantIsolation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.AAIResourcesClient;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
@@ -47,157 +46,166 @@ import org.springframework.stereotype.Component;
@Component
public class WatchdogDistribution {
- private static final Logger logger = LoggerFactory.getLogger(WatchdogDistribution.class);
-
- private AAIResourcesClient aaiClient;
-
- @Autowired
- private WatchdogDistributionStatusRepository watchdogDistributionStatusRepository;
-
- @Autowired
- private WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository;
-
- @Autowired
- private WatchdogServiceModVerIdLookupRepository watchdogModVerIdLookupRepository;
-
- @Autowired
- private ServiceRepository serviceRepo;
-
- @Value("${mso.asdc.config.components.componentNames}")
- private String[] componentNames;
-
- public String getOverallDistributionStatus(String distributionId) throws Exception {
- logger.debug("Entered getOverallDistributionStatus method for distrubutionId: {}", distributionId);
-
- String status = null;
- try {
- WatchdogDistributionStatus watchdogDistributionStatus = watchdogDistributionStatusRepository.findById(distributionId)
- .orElseGet( () -> null);
- if(watchdogDistributionStatus == null){
- watchdogDistributionStatus = new WatchdogDistributionStatus();
- watchdogDistributionStatus.setDistributionId(distributionId);
- watchdogDistributionStatusRepository.save(watchdogDistributionStatus);
- }
- String distributionStatus = watchdogDistributionStatus.getDistributionIdStatus();
-
- if(DistributionStatus.TIMEOUT.name().equalsIgnoreCase(distributionStatus)) {
- logger.debug("Ignoring to update WatchdogDistributionStatus as distributionId: {} status is set to: {}",
- distributionId, distributionStatus);
- return DistributionStatus.TIMEOUT.name();
- } else {
- List<WatchdogComponentDistributionStatus> results = watchdogCDStatusRepository.findByDistributionId(distributionId);
- logger.debug("Executed RequestDB getWatchdogComponentDistributionStatus for distrubutionId: {}",
- distributionId);
-
- //*************************************************************************************************************************************************
- //**** Compare config values verse DB watchdog component names to see if every component has reported status before returning final result back to ASDC
- //**************************************************************************************************************************************************
-
- List<WatchdogComponentDistributionStatus> cdStatuses = watchdogCDStatusRepository.findByDistributionId(distributionId);
-
- boolean allComponentsComplete = true;
-
- for(String name : componentNames ) {
-
- boolean match = false;
-
- for(WatchdogComponentDistributionStatus cdStatus: cdStatuses){
- if(name.equals(cdStatus.getComponentName())){
- logger.debug("Found componentName {} in the WatchDog Component DB", name);
- match = true;
- break;
- }
- }
- if(!match){
- logger.debug("{} has not be updated in the the WatchDog Component DB yet, so ending the loop", name);
- allComponentsComplete = false;
- break;
- }
- }
-
-
- if(allComponentsComplete) {
- logger.debug("Components Size matched with the WatchdogComponentDistributionStatus results.");
-
- for(WatchdogComponentDistributionStatus componentDist : results) {
- String componentDistributionStatus = componentDist.getComponentDistributionStatus();
- logger.debug("Component status: {} on componentName: ", componentDistributionStatus, componentDist
- .getComponentName());
- if(componentDistributionStatus.equalsIgnoreCase("COMPONENT_DONE_ERROR")) {
- status = DistributionStatus.FAILURE.name();
- break;
- } else if(componentDistributionStatus.equalsIgnoreCase("COMPONENT_DONE_OK")) {
- status = DistributionStatus.SUCCESS.name();
- } else {
- throw new Exception("Invalid Component distribution status: " + componentDistributionStatus);
- }
- }
-
- logger.debug("Updating overall DistributionStatus to: {} for distributionId: ", status, distributionId);
-
- watchdogDistributionStatus.setDistributionIdStatus(status);
- watchdogDistributionStatusRepository.save(watchdogDistributionStatus);
- } else {
- logger.debug("Components Size Didn't match with the WatchdogComponentDistributionStatus results.");
- status = DistributionStatus.INCOMPLETE.name();
- return status;
- }
- }
- }catch (Exception e) {
- logger.debug("Exception occurred on getOverallDistributionStatus : {}", e.getMessage());
- logger.error("Exception occurred", e);
- throw new Exception(e);
- }
- logger.debug("Exiting getOverallDistributionStatus method in WatchdogDistribution");
- return status;
- }
-
- public void executePatchAAI(String distributionId, String serviceModelInvariantUUID, String distributionStatus) throws Exception {
- logger.debug("Entered executePatchAAI method with distrubutionId: {} and distributionStatus: ", distributionId,
- distributionStatus);
-
- try {
- WatchdogServiceModVerIdLookup lookup = watchdogModVerIdLookupRepository.findOneByDistributionId(distributionId);
- String serviceModelVersionId = "";
-
- if(lookup != null) {
- serviceModelVersionId = lookup.getServiceModelVersionId();
- }
-
- logger.debug("Executed RequestDB getWatchdogServiceModVerIdLookup with distributionId: {} "
- + "and serviceModelVersionId: {}", distributionId, serviceModelVersionId);
- logger.debug("ASDC Notification ServiceModelInvariantUUID : {}", serviceModelInvariantUUID);
-
- if(serviceModelInvariantUUID == null || "".equals(serviceModelVersionId)) {
- String error = "No Service found with serviceModelInvariantUUID: " + serviceModelInvariantUUID;
- logger.debug(error);
- throw new Exception(error);
- }
-
- AAIResourceUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, serviceModelInvariantUUID, serviceModelVersionId);
- aaiUri.depth(Depth.ZERO); //Do not return relationships if any
- logger.debug("Target A&AI Resource URI: {}", aaiUri.build().toString());
-
- Map<String, String> payload = new HashMap<>();
- payload.put("distribution-status", distributionStatus);
- getAaiClient().update(aaiUri, payload);
-
- logger.debug("A&AI UPDATE MODEL Version is success!");
- } catch (Exception e) {
- logger.debug("Exception occurred on executePatchAAI : {}", e.getMessage());
- logger.error("Exception occurred", e);
- throw new Exception(e);
- }
- }
-
- public AAIResourcesClient getAaiClient() {
- if(aaiClient == null) {
- aaiClient = new AAIResourcesClient();
- }
- return aaiClient;
- }
-
- public void setAaiClient(AAIResourcesClient aaiClient) {
- this.aaiClient = aaiClient;
- }
+ private static final Logger logger = LoggerFactory.getLogger(WatchdogDistribution.class);
+
+ private AAIResourcesClient aaiClient;
+
+ @Autowired
+ private WatchdogDistributionStatusRepository watchdogDistributionStatusRepository;
+
+ @Autowired
+ private WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository;
+
+ @Autowired
+ private WatchdogServiceModVerIdLookupRepository watchdogModVerIdLookupRepository;
+
+ @Autowired
+ private ServiceRepository serviceRepo;
+
+ @Value("${mso.asdc.config.components.componentNames}")
+ private String[] componentNames;
+
+ public String getOverallDistributionStatus(String distributionId) throws Exception {
+ logger.debug("Entered getOverallDistributionStatus method for distrubutionId: {}", distributionId);
+
+ String status = null;
+ try {
+ WatchdogDistributionStatus watchdogDistributionStatus =
+ watchdogDistributionStatusRepository.findById(distributionId).orElseGet(() -> null);
+ if (watchdogDistributionStatus == null) {
+ watchdogDistributionStatus = new WatchdogDistributionStatus();
+ watchdogDistributionStatus.setDistributionId(distributionId);
+ watchdogDistributionStatusRepository.save(watchdogDistributionStatus);
+ }
+ String distributionStatus = watchdogDistributionStatus.getDistributionIdStatus();
+
+ if (DistributionStatus.TIMEOUT.name().equalsIgnoreCase(distributionStatus)) {
+ logger.debug("Ignoring to update WatchdogDistributionStatus as distributionId: {} status is set to: {}",
+ distributionId, distributionStatus);
+ return DistributionStatus.TIMEOUT.name();
+ } else {
+ List<WatchdogComponentDistributionStatus> results =
+ watchdogCDStatusRepository.findByDistributionId(distributionId);
+ logger.debug("Executed RequestDB getWatchdogComponentDistributionStatus for distrubutionId: {}",
+ distributionId);
+
+ // *************************************************************************************************************************************************
+ // **** Compare config values verse DB watchdog component names to see if every component has reported
+ // status before returning final result back to ASDC
+ // **************************************************************************************************************************************************
+
+ List<WatchdogComponentDistributionStatus> cdStatuses =
+ watchdogCDStatusRepository.findByDistributionId(distributionId);
+
+ boolean allComponentsComplete = true;
+
+ for (String name : componentNames) {
+
+ boolean match = false;
+
+ for (WatchdogComponentDistributionStatus cdStatus : cdStatuses) {
+ if (name.equals(cdStatus.getComponentName())) {
+ logger.debug("Found componentName {} in the WatchDog Component DB", name);
+ match = true;
+ break;
+ }
+ }
+ if (!match) {
+ logger.debug("{} has not be updated in the the WatchDog Component DB yet, so ending the loop",
+ name);
+ allComponentsComplete = false;
+ break;
+ }
+ }
+
+
+ if (allComponentsComplete) {
+ logger.debug("Components Size matched with the WatchdogComponentDistributionStatus results.");
+
+ for (WatchdogComponentDistributionStatus componentDist : results) {
+ String componentDistributionStatus = componentDist.getComponentDistributionStatus();
+ logger.debug("Component status: {} on componentName: ", componentDistributionStatus,
+ componentDist.getComponentName());
+ if (componentDistributionStatus.equalsIgnoreCase("COMPONENT_DONE_ERROR")) {
+ status = DistributionStatus.FAILURE.name();
+ break;
+ } else if (componentDistributionStatus.equalsIgnoreCase("COMPONENT_DONE_OK")) {
+ status = DistributionStatus.SUCCESS.name();
+ } else {
+ throw new Exception(
+ "Invalid Component distribution status: " + componentDistributionStatus);
+ }
+ }
+
+ logger.debug("Updating overall DistributionStatus to: {} for distributionId: ", status,
+ distributionId);
+
+ watchdogDistributionStatus.setDistributionIdStatus(status);
+ watchdogDistributionStatusRepository.save(watchdogDistributionStatus);
+ } else {
+ logger.debug("Components Size Didn't match with the WatchdogComponentDistributionStatus results.");
+ status = DistributionStatus.INCOMPLETE.name();
+ return status;
+ }
+ }
+ } catch (Exception e) {
+ logger.debug("Exception occurred on getOverallDistributionStatus : {}", e.getMessage());
+ logger.error("Exception occurred", e);
+ throw new Exception(e);
+ }
+ logger.debug("Exiting getOverallDistributionStatus method in WatchdogDistribution");
+ return status;
+ }
+
+ public void executePatchAAI(String distributionId, String serviceModelInvariantUUID, String distributionStatus)
+ throws Exception {
+ logger.debug("Entered executePatchAAI method with distrubutionId: {} and distributionStatus: ", distributionId,
+ distributionStatus);
+
+ try {
+ WatchdogServiceModVerIdLookup lookup =
+ watchdogModVerIdLookupRepository.findOneByDistributionId(distributionId);
+ String serviceModelVersionId = "";
+
+ if (lookup != null) {
+ serviceModelVersionId = lookup.getServiceModelVersionId();
+ }
+
+ logger.debug("Executed RequestDB getWatchdogServiceModVerIdLookup with distributionId: {} "
+ + "and serviceModelVersionId: {}", distributionId, serviceModelVersionId);
+ logger.debug("ASDC Notification ServiceModelInvariantUUID : {}", serviceModelInvariantUUID);
+
+ if (serviceModelInvariantUUID == null || "".equals(serviceModelVersionId)) {
+ String error = "No Service found with serviceModelInvariantUUID: " + serviceModelInvariantUUID;
+ logger.debug(error);
+ throw new Exception(error);
+ }
+
+ AAIResourceUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, serviceModelInvariantUUID,
+ serviceModelVersionId);
+ aaiUri.depth(Depth.ZERO); // Do not return relationships if any
+ logger.debug("Target A&AI Resource URI: {}", aaiUri.build().toString());
+
+ Map<String, String> payload = new HashMap<>();
+ payload.put("distribution-status", distributionStatus);
+ getAaiClient().update(aaiUri, payload);
+
+ logger.debug("A&AI UPDATE MODEL Version is success!");
+ } catch (Exception e) {
+ logger.debug("Exception occurred on executePatchAAI : {}", e.getMessage());
+ logger.error("Exception occurred", e);
+ throw new Exception(e);
+ }
+ }
+
+ public AAIResourcesClient getAaiClient() {
+ if (aaiClient == null) {
+ aaiClient = new AAIResourcesClient();
+ }
+ return aaiClient;
+ }
+
+ public void setAaiClient(AAIResourcesClient aaiClient) {
+ this.aaiClient = aaiClient;
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java b/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java
index 0d75c56c58..a154734690 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java
@@ -23,7 +23,6 @@ package org.onap.so.asdc.util;
import java.util.List;
import java.util.Map;
-
import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.api.notification.INotificationData;
import org.onap.sdc.api.notification.IResourceInstance;
@@ -39,905 +38,974 @@ import org.onap.so.db.catalog.beans.NetworkResourceCustomization;
public class ASDCNotificationLogging {
- public static String dumpASDCNotification(INotificationData asdcNotification) {
-
- if (asdcNotification == null) {
- return "NULL";
- }
- return "ASDC Notification:" + System.lineSeparator() +
- "DistributionID:" + testNull(asdcNotification.getDistributionID()) + System.lineSeparator() +
- "ServiceName:" + testNull(asdcNotification.getServiceName()) + System.lineSeparator() +
- "ServiceVersion:" + testNull(asdcNotification.getServiceVersion()) + System.lineSeparator() +
- "ServiceUUID:" + testNull(asdcNotification.getServiceUUID()) + System.lineSeparator() +
- "ServiceInvariantUUID:" + testNull(asdcNotification.getServiceInvariantUUID()) + System.lineSeparator() +
- "ServiceDescription:" + testNull(asdcNotification.getServiceDescription()) + System.lineSeparator() +
- "Service Artifacts List:" + System.lineSeparator() + testNull(dumpArtifactInfoList(asdcNotification.getServiceArtifacts())) + System.lineSeparator() +
- "Resource Instances List:" + System.lineSeparator() + testNull(dumpASDCResourcesList(asdcNotification)) + System.lineSeparator();
- }
-
- public static String dumpCSARNotification(INotificationData asdcNotification, ToscaResourceStructure toscaResourceStructure) {
-
- if (asdcNotification == null) {
- return "NULL";
- }
-
-
- StringBuilder buffer = new StringBuilder("CSAR Notification:");
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
-
-
- ISdcCsarHelper csarHelper = toscaResourceStructure.getSdcCsarHelper();
-
-
- buffer.append("Service Level Properties:");
- buffer.append(System.lineSeparator());
- buffer.append("Name:");
- buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
- buffer.append(System.lineSeparator());
- buffer.append("Description:");
- buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
- buffer.append(System.lineSeparator());
- buffer.append("Model UUID:");
- buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
- buffer.append(System.lineSeparator());
- buffer.append("Model Version:");
- buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
- buffer.append(System.lineSeparator());
- buffer.append("Model InvariantUuid:");
- buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
- buffer.append(System.lineSeparator());
- buffer.append("Service Type:");
- buffer.append(csarHelper.getServiceMetadata().getValue("serviceType"));
- buffer.append(System.lineSeparator());
- buffer.append("Service Role:");
- buffer.append(csarHelper.getServiceMetadata().getValue("serviceRole"));
- buffer.append(System.lineSeparator());
- buffer.append("WorkLoad Context:");
- buffer.append(asdcNotification.getWorkloadContext());
- buffer.append(System.lineSeparator());
- buffer.append("Environment Context:");
- buffer.append(csarHelper.getServiceMetadata().getValue("environmentContext"));
- buffer.append(System.lineSeparator());
-
-
- List<NodeTemplate> serviceProxyResourceList = toscaResourceStructure.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.SERVICE_PROXY);
-
- if(serviceProxyResourceList != null){
-
- for (NodeTemplate serviceProxyNodeTemplate : serviceProxyResourceList) {
-
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("Service Proxy Properties:");
- buffer.append(System.lineSeparator());
- buffer.append("Model Name:");
- buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- buffer.append(System.lineSeparator());
- buffer.append("Model UUID:");
- buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- buffer.append(System.lineSeparator());
- buffer.append("Description:");
- buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
- buffer.append(System.lineSeparator());
- buffer.append("Version:");
- buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- buffer.append(System.lineSeparator());
- buffer.append("InvariantUuid:");
- buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- buffer.append(System.lineSeparator());
-
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("Service Proxy Customization Properties:");
- buffer.append(System.lineSeparator());
-
- buffer.append("Model Customization UUID:");
- buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
- buffer.append(System.lineSeparator());
- buffer.append("Model Instance Name:");
- buffer.append(serviceProxyNodeTemplate.getName());
- buffer.append(System.lineSeparator());
- buffer.append("Tosca Node Type:");
- buffer.append(serviceProxyNodeTemplate.getType());
- buffer.append(System.lineSeparator());
- buffer.append("Version:");
- buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- buffer.append(System.lineSeparator());
- buffer.append("InvariantUuid:");
- buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- buffer.append(System.lineSeparator());
-
- }
- }
-
- List<NodeTemplate> configurationNodeTemplatesList = toscaResourceStructure.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION);
-
- if(configurationNodeTemplatesList != null){
- for (NodeTemplate configNodeTemplate : configurationNodeTemplatesList) {
-
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("Configuration Properties:");
- buffer.append(System.lineSeparator());
-
- buffer.append("Model Name:");
- buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- buffer.append(System.lineSeparator());
- buffer.append("Model UUID:");
- buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- buffer.append(System.lineSeparator());
- buffer.append("Description:");
- buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
- buffer.append(System.lineSeparator());
- buffer.append("Version:");
- buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- buffer.append(System.lineSeparator());
- buffer.append("InvariantUuid:");
- buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- buffer.append(System.lineSeparator());
- buffer.append("Tosca Node Type:");
- buffer.append(configNodeTemplate.getType());
-
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("Configuration Customization Properties:");
- buffer.append(System.lineSeparator());
-
- buffer.append("Model Customization UUID:");
- buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
- buffer.append(System.lineSeparator());
- buffer.append("Model Instance Name:");
- buffer.append(configNodeTemplate.getName());
- buffer.append(System.lineSeparator());
- buffer.append("NFFunction:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
- buffer.append(System.lineSeparator());
- buffer.append("NFRole:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE));
- buffer.append(System.lineSeparator());
- buffer.append("NFType:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE));
- buffer.append(System.lineSeparator());
-
- }
- }
-
+ public static String dumpASDCNotification(INotificationData asdcNotification) {
+
+ if (asdcNotification == null) {
+ return "NULL";
+ }
+ return "ASDC Notification:" + System.lineSeparator() + "DistributionID:"
+ + testNull(asdcNotification.getDistributionID()) + System.lineSeparator() + "ServiceName:"
+ + testNull(asdcNotification.getServiceName()) + System.lineSeparator() + "ServiceVersion:"
+ + testNull(asdcNotification.getServiceVersion()) + System.lineSeparator() + "ServiceUUID:"
+ + testNull(asdcNotification.getServiceUUID()) + System.lineSeparator() + "ServiceInvariantUUID:"
+ + testNull(asdcNotification.getServiceInvariantUUID()) + System.lineSeparator() + "ServiceDescription:"
+ + testNull(asdcNotification.getServiceDescription()) + System.lineSeparator()
+ + "Service Artifacts List:" + System.lineSeparator()
+ + testNull(dumpArtifactInfoList(asdcNotification.getServiceArtifacts())) + System.lineSeparator()
+ + "Resource Instances List:" + System.lineSeparator()
+ + testNull(dumpASDCResourcesList(asdcNotification)) + System.lineSeparator();
+ }
+
+ public static String dumpCSARNotification(INotificationData asdcNotification,
+ ToscaResourceStructure toscaResourceStructure) {
+
+ if (asdcNotification == null) {
+ return "NULL";
+ }
+
+
+ StringBuilder buffer = new StringBuilder("CSAR Notification:");
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+
+
+ ISdcCsarHelper csarHelper = toscaResourceStructure.getSdcCsarHelper();
+
+
+ buffer.append("Service Level Properties:");
+ buffer.append(System.lineSeparator());
+ buffer.append("Name:");
+ buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Description:");
+ buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model UUID:");
+ buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Version:");
+ buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model InvariantUuid:");
+ buffer.append(testNull(csarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Service Type:");
+ buffer.append(csarHelper.getServiceMetadata().getValue("serviceType"));
+ buffer.append(System.lineSeparator());
+ buffer.append("Service Role:");
+ buffer.append(csarHelper.getServiceMetadata().getValue("serviceRole"));
+ buffer.append(System.lineSeparator());
+ buffer.append("WorkLoad Context:");
+ buffer.append(asdcNotification.getWorkloadContext());
+ buffer.append(System.lineSeparator());
+ buffer.append("Environment Context:");
+ buffer.append(csarHelper.getServiceMetadata().getValue("environmentContext"));
+ buffer.append(System.lineSeparator());
+
+
+ List<NodeTemplate> serviceProxyResourceList =
+ toscaResourceStructure.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.SERVICE_PROXY);
+
+ if (serviceProxyResourceList != null) {
+
+ for (NodeTemplate serviceProxyNodeTemplate : serviceProxyResourceList) {
+
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("Service Proxy Properties:");
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Name:");
+ buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model UUID:");
+ buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Description:");
+ buffer.append(
+ serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+ buffer.append(System.lineSeparator());
+ buffer.append("Version:");
+ buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ buffer.append(System.lineSeparator());
+ buffer.append("InvariantUuid:");
+ buffer.append(
+ serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ buffer.append(System.lineSeparator());
+
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("Service Proxy Customization Properties:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("Model Customization UUID:");
+ buffer.append(serviceProxyNodeTemplate.getMetaData()
+ .getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Instance Name:");
+ buffer.append(serviceProxyNodeTemplate.getName());
+ buffer.append(System.lineSeparator());
+ buffer.append("Tosca Node Type:");
+ buffer.append(serviceProxyNodeTemplate.getType());
+ buffer.append(System.lineSeparator());
+ buffer.append("Version:");
+ buffer.append(serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ buffer.append(System.lineSeparator());
+ buffer.append("InvariantUuid:");
+ buffer.append(
+ serviceProxyNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ buffer.append(System.lineSeparator());
+
+ }
+ }
+
+ List<NodeTemplate> configurationNodeTemplatesList =
+ toscaResourceStructure.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION);
+
+ if (configurationNodeTemplatesList != null) {
+ for (NodeTemplate configNodeTemplate : configurationNodeTemplatesList) {
+
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("Configuration Properties:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("Model Name:");
+ buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model UUID:");
+ buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Description:");
+ buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+ buffer.append(System.lineSeparator());
+ buffer.append("Version:");
+ buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ buffer.append(System.lineSeparator());
+ buffer.append("InvariantUuid:");
+ buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Tosca Node Type:");
+ buffer.append(configNodeTemplate.getType());
+
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("Configuration Customization Properties:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("Model Customization UUID:");
+ buffer.append(
+ configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Instance Name:");
+ buffer.append(configNodeTemplate.getName());
+ buffer.append(System.lineSeparator());
+ buffer.append("NFFunction:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(
+ configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
+ buffer.append(System.lineSeparator());
+ buffer.append("NFRole:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE));
+ buffer.append(System.lineSeparator());
+ buffer.append("NFType:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE));
+ buffer.append(System.lineSeparator());
+
+ }
+ }
+
List<NodeTemplate> vfNodeTemplatesList = toscaResourceStructure.getSdcCsarHelper().getServiceVfList();
- for (NodeTemplate vfNodeTemplate : vfNodeTemplatesList) {
-
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("VNF Properties:");
- buffer.append(System.lineSeparator());
- buffer.append("Model Name:");
- buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
- buffer.append(System.lineSeparator());
- buffer.append("Model UUID:");
- buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
- buffer.append(System.lineSeparator());
- buffer.append("Description:");
- buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
- buffer.append(System.lineSeparator());
- buffer.append("Version:");
- buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
- buffer.append(System.lineSeparator());
- buffer.append("Type:");
- buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE)));
- buffer.append(System.lineSeparator());
- buffer.append("Category:");
- buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)));
- buffer.append(System.lineSeparator());
- buffer.append("InvariantUuid:");
- buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
- buffer.append(System.lineSeparator());
- buffer.append("Max Instances:");
- buffer.append(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES));
- buffer.append(System.lineSeparator());
- buffer.append("Min Instances:");
- buffer.append(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES));
- buffer.append(System.lineSeparator());
-
- buffer.append(System.lineSeparator());
- buffer.append("VNF Customization Properties:");
- buffer.append(System.lineSeparator());
-
- buffer.append("Customization UUID:");
- buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
- buffer.append(System.lineSeparator());
- buffer.append("NFFunction:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
- buffer.append(System.lineSeparator());
- buffer.append("NFCode:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, "nf_naming_code"));
- buffer.append(System.lineSeparator());
- buffer.append("NFRole:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE));
- buffer.append(System.lineSeparator());
- buffer.append("NFType:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE));
- buffer.append(System.lineSeparator());
- buffer.append("MultiStageDesign:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate, "multi_stage_design"));
- buffer.append(System.lineSeparator());
-
- List<Group> groupList = toscaResourceStructure.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType(vfNodeTemplate, "org.openecomp.groups.VfcInstanceGroup");
-
- if(groupList != null){
- for (Group group : groupList) {
- Metadata instanceMetadata = group.getMetadata();
-
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("VNFC Instance Group Properties:");
- buffer.append(System.lineSeparator());
-
- buffer.append("Model Name:");
- buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- buffer.append(System.lineSeparator());
- buffer.append("Version:");
- buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- buffer.append(System.lineSeparator());
- buffer.append("Type:");
- buffer.append(vfNodeTemplate.getType());
- buffer.append(System.lineSeparator());
- buffer.append("InvariantUuid:");
- buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- buffer.append(System.lineSeparator());
- }
-
- }
-
-
- List<Group> vfGroups = toscaResourceStructure.getSdcCsarHelper().getVfModulesByVf(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
-
- for(Group group : vfGroups){
-
- Metadata vfMetadata = group.getMetadata();
-
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("VF Module Properties:");
- buffer.append(System.lineSeparator());
- buffer.append("ModelInvariantUuid:");
- buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)));
- buffer.append(System.lineSeparator());
- buffer.append("ModelName:");
- buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME)));
- buffer.append(System.lineSeparator());
- buffer.append("ModelUuid:");
- buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)));
- buffer.append(System.lineSeparator());
- buffer.append("ModelVersion:");
- buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION)));
- buffer.append(System.lineSeparator());
- buffer.append("Description:");
- buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
- buffer.append(System.lineSeparator());
-
- List<NodeTemplate> groupMembers = toscaResourceStructure.getSdcCsarHelper().getMembersOfVfModule(vfNodeTemplate, group);
-
- for(NodeTemplate node : groupMembers){
- buffer.append("Member Name:");
- buffer.append(testNull(node.getName()));
- buffer.append(System.lineSeparator());
- }
-
- buffer.append(System.lineSeparator());
- buffer.append("VF Module Customization Properties:");
- buffer.append(System.lineSeparator());
- buffer.append("Model Customization UUID:");
- buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULECUSTOMIZATIONUUID)));
- buffer.append(System.lineSeparator());
-
- }
-
- List<NodeTemplate> vfConfigList = toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(vfNodeTemplate, SdcTypes.CONFIGURATION);
-
- if(vfConfigList != null){
- for (NodeTemplate configNodeTemplate : vfConfigList) {
-
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("Fabric Configuration Properties:");
- buffer.append(System.lineSeparator());
-
- buffer.append("Model Name:");
- buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- buffer.append(System.lineSeparator());
- buffer.append("Model UUID:");
- buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- buffer.append(System.lineSeparator());
- buffer.append("Description:");
- buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
- buffer.append(System.lineSeparator());
- buffer.append("Version:");
- buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- buffer.append(System.lineSeparator());
- buffer.append("InvariantUuid:");
- buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- buffer.append(System.lineSeparator());
- buffer.append("Tosca Node Type:");
- buffer.append(configNodeTemplate.getType());
-
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("Fabric Configuration Customization Properties:");
- buffer.append(System.lineSeparator());
-
- buffer.append("Model Customization UUID:");
- buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
- buffer.append(System.lineSeparator());
- buffer.append("Model Instance Name:");
- buffer.append(configNodeTemplate.getName());
- buffer.append(System.lineSeparator());
- buffer.append("NFFunction:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
- buffer.append(System.lineSeparator());
- buffer.append("NFRole:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE));
- buffer.append(System.lineSeparator());
- buffer.append("NFType:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE));
- buffer.append(System.lineSeparator());
-
- }
- }
-
- List<NodeTemplate> cvfcList = toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(vfNodeTemplate, SdcTypes.CVFC);
-
- for(NodeTemplate cvfcTemplate : cvfcList) {
-
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("CVNFC Properties:");
- buffer.append(System.lineSeparator());
- buffer.append("ModelCustomizationUuid:");
- buffer.append(testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
- buffer.append(System.lineSeparator());
- buffer.append("ModelInvariantUuid:");
- buffer.append(testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
- buffer.append(System.lineSeparator());
- buffer.append("ModelName:");
- buffer.append(testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
- buffer.append(System.lineSeparator());
- buffer.append("ModelUuid:");
- buffer.append(testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
- buffer.append(System.lineSeparator());
- buffer.append("ModelVersion:");
- buffer.append(testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
- buffer.append(System.lineSeparator());
- buffer.append("Description:");
- buffer.append(testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
- buffer.append(System.lineSeparator());
- buffer.append("Template Name:");
- buffer.append(testNull(cvfcTemplate.getName()));
- buffer.append(System.lineSeparator());
-
-
- List<NodeTemplate> vfcList = toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(cvfcTemplate, SdcTypes.VFC);
-
- for(NodeTemplate vfcTemplate : vfcList) {
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("VNFC Properties:");
- buffer.append(System.lineSeparator());
- buffer.append("ModelCustomizationUuid:");
- buffer.append(testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
- buffer.append(System.lineSeparator());
- buffer.append("ModelInvariantUuid:");
- buffer.append(testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
- buffer.append(System.lineSeparator());
- buffer.append("ModelName:");
- buffer.append(testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
- buffer.append(System.lineSeparator());
- buffer.append("ModelUuid:");
- buffer.append(testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
- buffer.append(System.lineSeparator());
- buffer.append("ModelVersion:");
- buffer.append(testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
- buffer.append(System.lineSeparator());
- buffer.append("Description:");
- buffer.append(testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
- buffer.append(System.lineSeparator());
- buffer.append("Sub Category:");
- buffer.append(testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)));
- buffer.append(System.lineSeparator());
-
- }
-
- }
-
- }
-
-
-
- List<NodeTemplate> nodeTemplatesVLList = toscaResourceStructure.getSdcCsarHelper().getServiceVlList();
-
- if(nodeTemplatesVLList != null){
-
- for(NodeTemplate vlNode : nodeTemplatesVLList){
-
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("NETWORK Level Properties:");
- buffer.append(System.lineSeparator());
- buffer.append("Model Name:");
- buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
- buffer.append(System.lineSeparator());
- buffer.append("Model InvariantUuid:");
- buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
- buffer.append(System.lineSeparator());
- buffer.append("Model UUID:");
- buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
- buffer.append(System.lineSeparator());
- buffer.append("Model Version:");
- buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
- buffer.append(System.lineSeparator());
- buffer.append("AIC Max Version:");
- buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
- buffer.append(System.lineSeparator());
- buffer.append("AIC Min Version:");
- buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
- buffer.append(System.lineSeparator());
- buffer.append("Tosca Node Type:");
- buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE)));
- buffer.append(System.lineSeparator());
- buffer.append("Description:");
- buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
- buffer.append(System.lineSeparator());
-
-
- buffer.append(System.lineSeparator());
- buffer.append("NETWORK Customization Properties:");
- buffer.append(System.lineSeparator());
- buffer.append("CustomizationUUID:");
- buffer.append(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
- buffer.append(System.lineSeparator());
- buffer.append("Network Technology:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNode, SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY));
- buffer.append(System.lineSeparator());
- buffer.append("Network Type:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNode, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE));
- buffer.append(System.lineSeparator());
- buffer.append("Network Role:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNode, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE));
- buffer.append(System.lineSeparator());
- buffer.append("Network Scope:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNode, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE));
- buffer.append(System.lineSeparator());
-
- }
-
- }
-
-
- List<NodeTemplate> networkCollectionList = toscaResourceStructure.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CR);
-
- if (networkCollectionList != null) {
- for (NodeTemplate crNode : networkCollectionList) {
- buffer.append(System.lineSeparator());
- buffer.append("Network Collection Properties:");
- buffer.append(System.lineSeparator());
- buffer.append("Model Name:");
- buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- buffer.append(System.lineSeparator());
- buffer.append("Model UUID:");
- buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- buffer.append(System.lineSeparator());
- buffer.append("InvariantUuid:");
- buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- buffer.append(System.lineSeparator());
- buffer.append("Description:");
- buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
- buffer.append(System.lineSeparator());
- buffer.append("Version:");
- buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- buffer.append(System.lineSeparator());
- buffer.append("Tosca Node Type:");
- buffer.append(crNode.getType());
- buffer.append(System.lineSeparator());
- buffer.append("CR Function:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, "cr_function"));
- buffer.append(System.lineSeparator());
- buffer.append("CR Role:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, "cr_role"));
- buffer.append(System.lineSeparator());
- buffer.append("CR Type:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, "cr_type"));
- buffer.append(System.lineSeparator());
-
- List<NodeTemplate> vlNodeList = toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(crNode, SdcTypes.VL);
-
- for(NodeTemplate vlNodeTemplate : vlNodeList){
-
- Metadata vlMetadata = vlNodeTemplate.getMetaData();
-
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("Network CR VL Properties:");
- buffer.append(System.lineSeparator());
-
- buffer.append("Model Name:");
- buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- buffer.append(System.lineSeparator());
- buffer.append("Model UUID:");
- buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- buffer.append(System.lineSeparator());
- buffer.append("InvariantUuid:");
- buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- buffer.append(System.lineSeparator());
- buffer.append("Version:");
- buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- buffer.append(System.lineSeparator());
- buffer.append("AIC Max Version:");
- buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES));
- buffer.append(System.lineSeparator());
- buffer.append("Description:");
- buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
- buffer.append(System.lineSeparator());
- buffer.append("Tosca Node Type:");
- buffer.append(vlNodeTemplate.getType());
- buffer.append(System.lineSeparator());
-
- }
-
-
- List<Group> groupList = toscaResourceStructure.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType(crNode, "org.openecomp.groups.NetworkCollection");
-
- if(groupList != null){
- for (Group group : groupList) {
- Metadata instanceMetadata = group.getMetadata();
- buffer.append(System.lineSeparator());
- buffer.append(System.lineSeparator());
- buffer.append("Network Instance Group Properties:");
- buffer.append(System.lineSeparator());
-
- buffer.append("Model Name:");
- buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
- buffer.append(System.lineSeparator());
- buffer.append("Model UUID:");
- buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
- buffer.append(System.lineSeparator());
- buffer.append("InvariantUuid:");
- buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
- buffer.append(System.lineSeparator());
- buffer.append("Version:");
- buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
- buffer.append(System.lineSeparator());
- }
-
- }
-
- buffer.append(System.lineSeparator());
- buffer.append("Network Collection Customization Properties:");
- buffer.append(System.lineSeparator());
-
- buffer.append("Model Customization UUID:");
- buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
- buffer.append(System.lineSeparator());
- buffer.append("Model Instance Name:");
- buffer.append(crNode.getName());
- buffer.append(System.lineSeparator());
- buffer.append("Network Scope:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE));
- buffer.append(System.lineSeparator());
- buffer.append("Network Role:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE));
- buffer.append(System.lineSeparator());
- buffer.append("Network Type:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE));
- buffer.append(System.lineSeparator());
- buffer.append("Network Technology:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY));
- buffer.append(System.lineSeparator());
-
- }
- }
-
+ for (NodeTemplate vfNodeTemplate : vfNodeTemplatesList) {
+
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("VNF Properties:");
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Name:");
+ buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model UUID:");
+ buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Description:");
+ buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Version:");
+ buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Type:");
+ buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Category:");
+ buffer.append(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)));
+ buffer.append(System.lineSeparator());
+ buffer.append("InvariantUuid:");
+ buffer.append(
+ testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Max Instances:");
+ buffer.append(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES));
+ buffer.append(System.lineSeparator());
+ buffer.append("Min Instances:");
+ buffer.append(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES));
+ buffer.append(System.lineSeparator());
+
+ buffer.append(System.lineSeparator());
+ buffer.append("VNF Customization Properties:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("Customization UUID:");
+ buffer.append(
+ testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("NFFunction:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate,
+ SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
+ buffer.append(System.lineSeparator());
+ buffer.append("NFCode:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate,
+ "nf_naming_code"));
+ buffer.append(System.lineSeparator());
+ buffer.append("NFRole:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate,
+ SdcPropertyNames.PROPERTY_NAME_NFROLE));
+ buffer.append(System.lineSeparator());
+ buffer.append("NFType:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate,
+ SdcPropertyNames.PROPERTY_NAME_NFTYPE));
+ buffer.append(System.lineSeparator());
+ buffer.append("MultiStageDesign:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfNodeTemplate,
+ "multi_stage_design"));
+ buffer.append(System.lineSeparator());
+
+ List<Group> groupList =
+ toscaResourceStructure.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType(
+ vfNodeTemplate, "org.openecomp.groups.VfcInstanceGroup");
+
+ if (groupList != null) {
+ for (Group group : groupList) {
+ Metadata instanceMetadata = group.getMetadata();
+
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("VNFC Instance Group Properties:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("Model Name:");
+ buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ buffer.append(System.lineSeparator());
+ buffer.append("Version:");
+ buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ buffer.append(System.lineSeparator());
+ buffer.append("Type:");
+ buffer.append(vfNodeTemplate.getType());
+ buffer.append(System.lineSeparator());
+ buffer.append("InvariantUuid:");
+ buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ buffer.append(System.lineSeparator());
+ }
+
+ }
+
+
+ List<Group> vfGroups = toscaResourceStructure.getSdcCsarHelper().getVfModulesByVf(
+ testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
+
+ for (Group group : vfGroups) {
+
+ Metadata vfMetadata = group.getMetadata();
+
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("VF Module Properties:");
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelInvariantUuid:");
+ buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
+ SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelName:");
+ buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
+ SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME)));
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelUuid:");
+ buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
+ SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelVersion:");
+ buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
+ SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Description:");
+ buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
+ SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
+ buffer.append(System.lineSeparator());
+
+ List<NodeTemplate> groupMembers =
+ toscaResourceStructure.getSdcCsarHelper().getMembersOfVfModule(vfNodeTemplate, group);
+
+ for (NodeTemplate node : groupMembers) {
+ buffer.append("Member Name:");
+ buffer.append(testNull(node.getName()));
+ buffer.append(System.lineSeparator());
+ }
+
+ buffer.append(System.lineSeparator());
+ buffer.append("VF Module Customization Properties:");
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Customization UUID:");
+ buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
+ SdcPropertyNames.PROPERTY_NAME_VFMODULECUSTOMIZATIONUUID)));
+ buffer.append(System.lineSeparator());
+
+ }
+
+ List<NodeTemplate> vfConfigList = toscaResourceStructure.getSdcCsarHelper()
+ .getNodeTemplateBySdcType(vfNodeTemplate, SdcTypes.CONFIGURATION);
+
+ if (vfConfigList != null) {
+ for (NodeTemplate configNodeTemplate : vfConfigList) {
+
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("Fabric Configuration Properties:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("Model Name:");
+ buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model UUID:");
+ buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Description:");
+ buffer.append(
+ configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+ buffer.append(System.lineSeparator());
+ buffer.append("Version:");
+ buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ buffer.append(System.lineSeparator());
+ buffer.append("InvariantUuid:");
+ buffer.append(
+ configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Tosca Node Type:");
+ buffer.append(configNodeTemplate.getType());
+
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("Fabric Configuration Customization Properties:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("Model Customization UUID:");
+ buffer.append(configNodeTemplate.getMetaData()
+ .getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Instance Name:");
+ buffer.append(configNodeTemplate.getName());
+ buffer.append(System.lineSeparator());
+ buffer.append("NFFunction:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(
+ configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
+ buffer.append(System.lineSeparator());
+ buffer.append("NFRole:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(
+ configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE));
+ buffer.append(System.lineSeparator());
+ buffer.append("NFType:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(
+ configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE));
+ buffer.append(System.lineSeparator());
+
+ }
+ }
+
+ List<NodeTemplate> cvfcList =
+ toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(vfNodeTemplate, SdcTypes.CVFC);
+
+ for (NodeTemplate cvfcTemplate : cvfcList) {
+
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("CVNFC Properties:");
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelCustomizationUuid:");
+ buffer.append(testNull(
+ cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelInvariantUuid:");
+ buffer.append(
+ testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelName:");
+ buffer.append(testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelUuid:");
+ buffer.append(testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelVersion:");
+ buffer.append(testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Description:");
+ buffer.append(
+ testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Template Name:");
+ buffer.append(testNull(cvfcTemplate.getName()));
+ buffer.append(System.lineSeparator());
+
+
+ List<NodeTemplate> vfcList =
+ toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(cvfcTemplate, SdcTypes.VFC);
+
+ for (NodeTemplate vfcTemplate : vfcList) {
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("VNFC Properties:");
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelCustomizationUuid:");
+ buffer.append(testNull(
+ vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelInvariantUuid:");
+ buffer.append(
+ testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelName:");
+ buffer.append(testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelUuid:");
+ buffer.append(testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("ModelVersion:");
+ buffer.append(testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Description:");
+ buffer.append(
+ testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Sub Category:");
+ buffer.append(
+ testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)));
+ buffer.append(System.lineSeparator());
+
+ }
+
+ }
+
+ }
+
+
+
+ List<NodeTemplate> nodeTemplatesVLList = toscaResourceStructure.getSdcCsarHelper().getServiceVlList();
+
+ if (nodeTemplatesVLList != null) {
+
+ for (NodeTemplate vlNode : nodeTemplatesVLList) {
+
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("NETWORK Level Properties:");
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Name:");
+ buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model InvariantUuid:");
+ buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model UUID:");
+ buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Version:");
+ buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
+ buffer.append(System.lineSeparator());
+ buffer.append("AIC Max Version:");
+ buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
+ buffer.append(System.lineSeparator());
+ buffer.append("AIC Min Version:");
+ buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Tosca Node Type:");
+ buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Description:");
+ buffer.append(testNull(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
+ buffer.append(System.lineSeparator());
+
+
+ buffer.append(System.lineSeparator());
+ buffer.append("NETWORK Customization Properties:");
+ buffer.append(System.lineSeparator());
+ buffer.append("CustomizationUUID:");
+ buffer.append(vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Network Technology:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNode,
+ SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY));
+ buffer.append(System.lineSeparator());
+ buffer.append("Network Type:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNode,
+ SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE));
+ buffer.append(System.lineSeparator());
+ buffer.append("Network Role:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNode,
+ SdcPropertyNames.PROPERTY_NAME_NETWORKROLE));
+ buffer.append(System.lineSeparator());
+ buffer.append("Network Scope:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNode,
+ SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE));
+ buffer.append(System.lineSeparator());
+
+ }
+
+ }
+
+
+ List<NodeTemplate> networkCollectionList =
+ toscaResourceStructure.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CR);
+
+ if (networkCollectionList != null) {
+ for (NodeTemplate crNode : networkCollectionList) {
+ buffer.append(System.lineSeparator());
+ buffer.append("Network Collection Properties:");
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Name:");
+ buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model UUID:");
+ buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("InvariantUuid:");
+ buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Description:");
+ buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+ buffer.append(System.lineSeparator());
+ buffer.append("Version:");
+ buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ buffer.append(System.lineSeparator());
+ buffer.append("Tosca Node Type:");
+ buffer.append(crNode.getType());
+ buffer.append(System.lineSeparator());
+ buffer.append("CR Function:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode,
+ "cr_function"));
+ buffer.append(System.lineSeparator());
+ buffer.append("CR Role:");
+ buffer.append(
+ toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, "cr_role"));
+ buffer.append(System.lineSeparator());
+ buffer.append("CR Type:");
+ buffer.append(
+ toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode, "cr_type"));
+ buffer.append(System.lineSeparator());
+
+ List<NodeTemplate> vlNodeList =
+ toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(crNode, SdcTypes.VL);
+
+ for (NodeTemplate vlNodeTemplate : vlNodeList) {
+
+ Metadata vlMetadata = vlNodeTemplate.getMetaData();
+
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("Network CR VL Properties:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("Model Name:");
+ buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model UUID:");
+ buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("InvariantUuid:");
+ buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Version:");
+ buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ buffer.append(System.lineSeparator());
+ buffer.append("AIC Max Version:");
+ buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES));
+ buffer.append(System.lineSeparator());
+ buffer.append("Description:");
+ buffer.append(vlMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+ buffer.append(System.lineSeparator());
+ buffer.append("Tosca Node Type:");
+ buffer.append(vlNodeTemplate.getType());
+ buffer.append(System.lineSeparator());
+
+ }
+
+
+ List<Group> groupList =
+ toscaResourceStructure.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType(
+ crNode, "org.openecomp.groups.NetworkCollection");
+
+ if (groupList != null) {
+ for (Group group : groupList) {
+ Metadata instanceMetadata = group.getMetadata();
+ buffer.append(System.lineSeparator());
+ buffer.append(System.lineSeparator());
+ buffer.append("Network Instance Group Properties:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("Model Name:");
+ buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model UUID:");
+ buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("InvariantUuid:");
+ buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Version:");
+ buffer.append(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
+ buffer.append(System.lineSeparator());
+ }
+
+ }
+
+ buffer.append(System.lineSeparator());
+ buffer.append("Network Collection Customization Properties:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("Model Customization UUID:");
+ buffer.append(crNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Instance Name:");
+ buffer.append(crNode.getName());
+ buffer.append(System.lineSeparator());
+ buffer.append("Network Scope:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode,
+ SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE));
+ buffer.append(System.lineSeparator());
+ buffer.append("Network Role:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode,
+ SdcPropertyNames.PROPERTY_NAME_NETWORKROLE));
+ buffer.append(System.lineSeparator());
+ buffer.append("Network Type:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode,
+ SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE));
+ buffer.append(System.lineSeparator());
+ buffer.append("Network Technology:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(crNode,
+ SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY));
+ buffer.append(System.lineSeparator());
+
+ }
+ }
+
List<NodeTemplate> allottedResourceList = toscaResourceStructure.getSdcCsarHelper().getAllottedResources();
-
- if(allottedResourceList != null){
-
- buffer.append(System.lineSeparator());
- buffer.append("Allotted Resource Properties:");
- buffer.append(System.lineSeparator());
-
- for(NodeTemplate allottedNode : allottedResourceList){
-
- buffer.append("Model Name:");
- buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
- buffer.append(System.lineSeparator());
- buffer.append("Model Name:");
- buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
- buffer.append(System.lineSeparator());
- buffer.append("Model InvariantUuid:");
- buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
- buffer.append(System.lineSeparator());
- buffer.append("Model Version:");
- buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
- buffer.append(System.lineSeparator());
- buffer.append("Model UUID:");
- buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
- buffer.append(System.lineSeparator());
- buffer.append("Model Subcategory:");
- buffer.append(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY));
- buffer.append(System.lineSeparator());
- buffer.append("Model Description:");
- buffer.append(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
- buffer.append(System.lineSeparator());
-
-
- buffer.append("Allotted Resource Customization Properties:");
- buffer.append(System.lineSeparator());
-
- buffer.append("Model Cutomization UUID:");
- buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
- buffer.append(System.lineSeparator());
- buffer.append("NFFunction:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
- buffer.append(System.lineSeparator());
- buffer.append("NFCode:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode, "nf_naming_code"));
- buffer.append(System.lineSeparator());
- buffer.append("NFRole:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode, SdcPropertyNames.PROPERTY_NAME_NFROLE));
- buffer.append(System.lineSeparator());
- buffer.append("NFType:");
- buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode, SdcPropertyNames.PROPERTY_NAME_NFTYPE));
- buffer.append(System.lineSeparator());
-
-
- }
- }
-
-
- return buffer.toString();
- }
-
- public static String dumpVfModuleMetaDataList(List<IVfModuleData> moduleMetaDataList) {
- if (moduleMetaDataList == null ) {
- return null;
- }
-
- StringBuilder buffer = new StringBuilder("VfModuleMetaData List:");
- buffer.append(System.lineSeparator());
-
- buffer.append("{");
-
- for (IVfModuleData moduleMetaData:moduleMetaDataList) {
- buffer.append(System.lineSeparator());
- buffer.append(testNull(dumpVfModuleMetaData(moduleMetaData)));
- buffer.append(System.lineSeparator());
- buffer.append(",");
-
- }
- buffer.replace(buffer.length()-1,buffer.length(), System.lineSeparator());
- buffer.append("}");
- buffer.append(System.lineSeparator());
-
- return buffer.toString();
- }
-
- private static String dumpVfModuleMetaData(IVfModuleData moduleMetaData) {
-
- if (moduleMetaData == null ) {
- return "NULL";
- }
-
- StringBuilder stringBuilder = new StringBuilder("VfModuleMetaData:");
- stringBuilder.append(System.lineSeparator());
-
- stringBuilder.append("VfModuleModelName:");
- stringBuilder.append(testNull(moduleMetaData.getVfModuleModelName()));
- stringBuilder.append(System.lineSeparator());
-
- stringBuilder.append("VfModuleModelVersion:");
- stringBuilder.append(testNull(moduleMetaData.getVfModuleModelVersion()));
- stringBuilder.append(System.lineSeparator());
-
- stringBuilder.append("VfModuleModelUUID:");
- stringBuilder.append(testNull(moduleMetaData.getVfModuleModelUUID()));
- stringBuilder.append(System.lineSeparator());
-
- stringBuilder.append("VfModuleModelInvariantUUID:");
- stringBuilder.append(testNull(moduleMetaData.getVfModuleModelInvariantUUID()));
- stringBuilder.append(System.lineSeparator());
-
- stringBuilder.append("VfModuleModelDescription:");
- stringBuilder.append(testNull(moduleMetaData.getVfModuleModelDescription()));
- stringBuilder.append(System.lineSeparator());
-
- stringBuilder.append("Artifacts UUID List:");
-
- if (moduleMetaData.getArtifacts() != null) {
- stringBuilder.append("{");
-
- for (String artifactUUID:moduleMetaData.getArtifacts()) {
- stringBuilder.append(System.lineSeparator());
- stringBuilder.append(testNull(artifactUUID));
- stringBuilder.append(System.lineSeparator());
- stringBuilder.append(",");
- }
- stringBuilder.replace(stringBuilder.length()-1,stringBuilder.length(), System.lineSeparator());
- stringBuilder.append("}");
- stringBuilder.append(System.lineSeparator());
- } else {
- stringBuilder.append("NULL");
- }
-
- if (moduleMetaData.getProperties() != null) {
- Map<String, String> vfModuleMap = moduleMetaData.getProperties();
- stringBuilder.append("Properties List:");
- stringBuilder.append("{");
-
- for (Map.Entry<String, String> entry : vfModuleMap.entrySet()) {
- stringBuilder.append(System.lineSeparator());
- stringBuilder.append(" ").append(entry.getKey()).append(" : ").append(entry.getValue());
- }
- stringBuilder.replace(stringBuilder.length()-1,stringBuilder.length(), System.lineSeparator());
- stringBuilder.append("}");
- stringBuilder.append(System.lineSeparator());
- } else {
- stringBuilder.append("NULL");
- }
-
-
- stringBuilder.append(System.lineSeparator());
-
- stringBuilder.append("isBase:");
- stringBuilder.append(moduleMetaData.isBase());
- stringBuilder.append(System.lineSeparator());
-
- return stringBuilder.toString();
- }
-
- private static String testNull(Object object) {
- if (object == null) {
- return "NULL";
- } else if (object instanceof Integer) {
- return object.toString();
- } else if (object instanceof String) {
- return (String)object;
- } else {
- return "Type not recognized";
- }
- }
-
- private static String dumpASDCResourcesList(INotificationData asdcNotification) {
- if (asdcNotification == null || asdcNotification.getResources() == null) {
- return null;
- }
-
- StringBuilder buffer = new StringBuilder();
- buffer.append("{");
-
- for (IResourceInstance resourceInstanceElem:asdcNotification.getResources()) {
- buffer.append(System.lineSeparator());
- buffer.append(testNull(dumpASDCResourceInstance(resourceInstanceElem)));
- buffer.append(System.lineSeparator());
- buffer.append(",");
- }
- buffer.replace(buffer.length()-1,buffer.length(), System.lineSeparator());
- buffer.append("}");
- buffer.append(System.lineSeparator());
-
- return buffer.toString();
-
- }
-
- private static String dumpASDCResourceInstance(IResourceInstance resourceInstance) {
-
- if (resourceInstance == null) {
- return null;
- }
-
- return "Resource Instance Info:" + System.lineSeparator() +
- "ResourceInstanceName:" + testNull(resourceInstance.getResourceInstanceName()) + System.lineSeparator() +
- "ResourceCustomizationUUID:" + testNull(resourceInstance.getResourceCustomizationUUID()) + System.lineSeparator() +
- "ResourceInvariantUUID:" + testNull(resourceInstance.getResourceInvariantUUID()) + System.lineSeparator() +
- "ResourceName:" + testNull(resourceInstance.getResourceName()) + System.lineSeparator() +
- "ResourceType:" + testNull(resourceInstance.getResourceType()) + System.lineSeparator() +
- "ResourceUUID:" + testNull(resourceInstance.getResourceUUID()) + System.lineSeparator() +
- "ResourceVersion:" + testNull(resourceInstance.getResourceVersion()) + System.lineSeparator() +
- "Category:" + testNull(resourceInstance.getCategory()) + System.lineSeparator() +
- "SubCategory:" + testNull(resourceInstance.getSubcategory()) + System.lineSeparator() +
- "Resource Artifacts List:" + System.lineSeparator() + testNull(dumpArtifactInfoList(resourceInstance.getArtifacts())) + System.lineSeparator();
- }
-
-
- private static String dumpArtifactInfoList(List<IArtifactInfo> artifactsList) {
-
- if (artifactsList == null || artifactsList.isEmpty()) {
- return null;
- }
-
- StringBuilder buffer = new StringBuilder();
- buffer.append("{");
- for (IArtifactInfo artifactInfoElem:artifactsList) {
- buffer.append(System.lineSeparator());
- buffer.append(testNull(dumpASDCArtifactInfo(artifactInfoElem)));
- buffer.append(System.lineSeparator());
- buffer.append(",");
-
- }
- buffer.replace(buffer.length()-1,buffer.length(), System.lineSeparator());
- buffer.append("}");
- buffer.append(System.lineSeparator());
-
- return buffer.toString();
- }
-
- private static String dumpASDCArtifactInfo(IArtifactInfo artifactInfo) {
-
- if (artifactInfo == null) {
- return null;
- }
-
- StringBuilder buffer = new StringBuilder("Service Artifacts Info:");
- buffer.append(System.lineSeparator());
-
- buffer.append("ArtifactName:");
- buffer.append(testNull(artifactInfo.getArtifactName()));
- buffer.append(System.lineSeparator());
-
- buffer.append("ArtifactVersion:");
- buffer.append(testNull(artifactInfo.getArtifactVersion()));
- buffer.append(System.lineSeparator());
-
- buffer.append("ArtifactType:");
- buffer.append(testNull(artifactInfo.getArtifactType()));
- buffer.append(System.lineSeparator());
-
- buffer.append("ArtifactDescription:");
- buffer.append(testNull(artifactInfo.getArtifactDescription()));
- buffer.append(System.lineSeparator());
-
- buffer.append("ArtifactTimeout:");
- buffer.append(testNull(artifactInfo.getArtifactTimeout()));
- buffer.append(System.lineSeparator());
-
- buffer.append("ArtifactURL:");
- buffer.append(testNull(artifactInfo.getArtifactURL()));
- buffer.append(System.lineSeparator());
-
- buffer.append("ArtifactUUID:");
- buffer.append(testNull(artifactInfo.getArtifactUUID()));
- buffer.append(System.lineSeparator());
-
- buffer.append("ArtifactChecksum:");
- buffer.append(testNull(artifactInfo.getArtifactChecksum()));
- buffer.append(System.lineSeparator());
-
- buffer.append("GeneratedArtifact:");
- buffer.append("{");
- buffer.append(testNull(dumpASDCArtifactInfo(artifactInfo.getGeneratedArtifact())));
- buffer.append(System.lineSeparator());
- buffer.append("}");
- buffer.append(System.lineSeparator());
-
- buffer.append("RelatedArtifacts:");
+ if (allottedResourceList != null) {
+
+ buffer.append(System.lineSeparator());
+ buffer.append("Allotted Resource Properties:");
+ buffer.append(System.lineSeparator());
+
+ for (NodeTemplate allottedNode : allottedResourceList) {
+
+ buffer.append("Model Name:");
+ buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Name:");
+ buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model InvariantUuid:");
+ buffer.append(
+ testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Version:");
+ buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model UUID:");
+ buffer.append(testNull(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Subcategory:");
+ buffer.append(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY));
+ buffer.append(System.lineSeparator());
+ buffer.append("Model Description:");
+ buffer.append(allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
+ buffer.append(System.lineSeparator());
+
+
+ buffer.append("Allotted Resource Customization Properties:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("Model Cutomization UUID:");
+ buffer.append(testNull(
+ allottedNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
+ buffer.append(System.lineSeparator());
+ buffer.append("NFFunction:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode,
+ SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
+ buffer.append(System.lineSeparator());
+ buffer.append("NFCode:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode,
+ "nf_naming_code"));
+ buffer.append(System.lineSeparator());
+ buffer.append("NFRole:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode,
+ SdcPropertyNames.PROPERTY_NAME_NFROLE));
+ buffer.append(System.lineSeparator());
+ buffer.append("NFType:");
+ buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(allottedNode,
+ SdcPropertyNames.PROPERTY_NAME_NFTYPE));
+ buffer.append(System.lineSeparator());
+
+
+ }
+ }
+
+
+ return buffer.toString();
+ }
+
+ public static String dumpVfModuleMetaDataList(List<IVfModuleData> moduleMetaDataList) {
+ if (moduleMetaDataList == null) {
+ return null;
+ }
+
+ StringBuilder buffer = new StringBuilder("VfModuleMetaData List:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("{");
+
+ for (IVfModuleData moduleMetaData : moduleMetaDataList) {
+ buffer.append(System.lineSeparator());
+ buffer.append(testNull(dumpVfModuleMetaData(moduleMetaData)));
+ buffer.append(System.lineSeparator());
+ buffer.append(",");
+
+ }
+ buffer.replace(buffer.length() - 1, buffer.length(), System.lineSeparator());
+ buffer.append("}");
+ buffer.append(System.lineSeparator());
+
+ return buffer.toString();
+ }
+
+ private static String dumpVfModuleMetaData(IVfModuleData moduleMetaData) {
+
+ if (moduleMetaData == null) {
+ return "NULL";
+ }
+
+ StringBuilder stringBuilder = new StringBuilder("VfModuleMetaData:");
+ stringBuilder.append(System.lineSeparator());
+
+ stringBuilder.append("VfModuleModelName:");
+ stringBuilder.append(testNull(moduleMetaData.getVfModuleModelName()));
+ stringBuilder.append(System.lineSeparator());
+
+ stringBuilder.append("VfModuleModelVersion:");
+ stringBuilder.append(testNull(moduleMetaData.getVfModuleModelVersion()));
+ stringBuilder.append(System.lineSeparator());
+
+ stringBuilder.append("VfModuleModelUUID:");
+ stringBuilder.append(testNull(moduleMetaData.getVfModuleModelUUID()));
+ stringBuilder.append(System.lineSeparator());
+
+ stringBuilder.append("VfModuleModelInvariantUUID:");
+ stringBuilder.append(testNull(moduleMetaData.getVfModuleModelInvariantUUID()));
+ stringBuilder.append(System.lineSeparator());
+
+ stringBuilder.append("VfModuleModelDescription:");
+ stringBuilder.append(testNull(moduleMetaData.getVfModuleModelDescription()));
+ stringBuilder.append(System.lineSeparator());
+
+ stringBuilder.append("Artifacts UUID List:");
+
+ if (moduleMetaData.getArtifacts() != null) {
+ stringBuilder.append("{");
+
+ for (String artifactUUID : moduleMetaData.getArtifacts()) {
+ stringBuilder.append(System.lineSeparator());
+ stringBuilder.append(testNull(artifactUUID));
+ stringBuilder.append(System.lineSeparator());
+ stringBuilder.append(",");
+ }
+ stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length(), System.lineSeparator());
+ stringBuilder.append("}");
+ stringBuilder.append(System.lineSeparator());
+ } else {
+ stringBuilder.append("NULL");
+ }
+
+ if (moduleMetaData.getProperties() != null) {
+ Map<String, String> vfModuleMap = moduleMetaData.getProperties();
+ stringBuilder.append("Properties List:");
+ stringBuilder.append("{");
+
+ for (Map.Entry<String, String> entry : vfModuleMap.entrySet()) {
+ stringBuilder.append(System.lineSeparator());
+ stringBuilder.append(" ").append(entry.getKey()).append(" : ").append(entry.getValue());
+ }
+ stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length(), System.lineSeparator());
+ stringBuilder.append("}");
+ stringBuilder.append(System.lineSeparator());
+ } else {
+ stringBuilder.append("NULL");
+ }
+
+
+ stringBuilder.append(System.lineSeparator());
+
+ stringBuilder.append("isBase:");
+ stringBuilder.append(moduleMetaData.isBase());
+ stringBuilder.append(System.lineSeparator());
+
+ return stringBuilder.toString();
+ }
+
+ private static String testNull(Object object) {
+ if (object == null) {
+ return "NULL";
+ } else if (object instanceof Integer) {
+ return object.toString();
+ } else if (object instanceof String) {
+ return (String) object;
+ } else {
+ return "Type not recognized";
+ }
+ }
+
+ private static String dumpASDCResourcesList(INotificationData asdcNotification) {
+ if (asdcNotification == null || asdcNotification.getResources() == null) {
+ return null;
+ }
+
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("{");
+
+ for (IResourceInstance resourceInstanceElem : asdcNotification.getResources()) {
+ buffer.append(System.lineSeparator());
+ buffer.append(testNull(dumpASDCResourceInstance(resourceInstanceElem)));
+ buffer.append(System.lineSeparator());
+ buffer.append(",");
+ }
+ buffer.replace(buffer.length() - 1, buffer.length(), System.lineSeparator());
+ buffer.append("}");
+ buffer.append(System.lineSeparator());
+
+ return buffer.toString();
+
+ }
+
+ private static String dumpASDCResourceInstance(IResourceInstance resourceInstance) {
+
+ if (resourceInstance == null) {
+ return null;
+ }
+
+ return "Resource Instance Info:" + System.lineSeparator() + "ResourceInstanceName:"
+ + testNull(resourceInstance.getResourceInstanceName()) + System.lineSeparator()
+ + "ResourceCustomizationUUID:" + testNull(resourceInstance.getResourceCustomizationUUID())
+ + System.lineSeparator() + "ResourceInvariantUUID:"
+ + testNull(resourceInstance.getResourceInvariantUUID()) + System.lineSeparator() + "ResourceName:"
+ + testNull(resourceInstance.getResourceName()) + System.lineSeparator() + "ResourceType:"
+ + testNull(resourceInstance.getResourceType()) + System.lineSeparator() + "ResourceUUID:"
+ + testNull(resourceInstance.getResourceUUID()) + System.lineSeparator() + "ResourceVersion:"
+ + testNull(resourceInstance.getResourceVersion()) + System.lineSeparator() + "Category:"
+ + testNull(resourceInstance.getCategory()) + System.lineSeparator() + "SubCategory:"
+ + testNull(resourceInstance.getSubcategory()) + System.lineSeparator() + "Resource Artifacts List:"
+ + System.lineSeparator() + testNull(dumpArtifactInfoList(resourceInstance.getArtifacts()))
+ + System.lineSeparator();
+ }
+
+
+ private static String dumpArtifactInfoList(List<IArtifactInfo> artifactsList) {
+
+ if (artifactsList == null || artifactsList.isEmpty()) {
+ return null;
+ }
+
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("{");
+ for (IArtifactInfo artifactInfoElem : artifactsList) {
+ buffer.append(System.lineSeparator());
+ buffer.append(testNull(dumpASDCArtifactInfo(artifactInfoElem)));
+ buffer.append(System.lineSeparator());
+ buffer.append(",");
+
+ }
+ buffer.replace(buffer.length() - 1, buffer.length(), System.lineSeparator());
+ buffer.append("}");
+ buffer.append(System.lineSeparator());
+
+ return buffer.toString();
+ }
+
+ private static String dumpASDCArtifactInfo(IArtifactInfo artifactInfo) {
+
+ if (artifactInfo == null) {
+ return null;
+ }
+
+ StringBuilder buffer = new StringBuilder("Service Artifacts Info:");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("ArtifactName:");
+ buffer.append(testNull(artifactInfo.getArtifactName()));
+ buffer.append(System.lineSeparator());
+
+ buffer.append("ArtifactVersion:");
+ buffer.append(testNull(artifactInfo.getArtifactVersion()));
+ buffer.append(System.lineSeparator());
+
+ buffer.append("ArtifactType:");
+ buffer.append(testNull(artifactInfo.getArtifactType()));
+ buffer.append(System.lineSeparator());
+
+ buffer.append("ArtifactDescription:");
+ buffer.append(testNull(artifactInfo.getArtifactDescription()));
+ buffer.append(System.lineSeparator());
+
+ buffer.append("ArtifactTimeout:");
+ buffer.append(testNull(artifactInfo.getArtifactTimeout()));
+ buffer.append(System.lineSeparator());
+
+ buffer.append("ArtifactURL:");
+ buffer.append(testNull(artifactInfo.getArtifactURL()));
+ buffer.append(System.lineSeparator());
+
+ buffer.append("ArtifactUUID:");
+ buffer.append(testNull(artifactInfo.getArtifactUUID()));
+ buffer.append(System.lineSeparator());
+
+ buffer.append("ArtifactChecksum:");
+ buffer.append(testNull(artifactInfo.getArtifactChecksum()));
+ buffer.append(System.lineSeparator());
+
+ buffer.append("GeneratedArtifact:");
+ buffer.append("{");
+ buffer.append(testNull(dumpASDCArtifactInfo(artifactInfo.getGeneratedArtifact())));
+ buffer.append(System.lineSeparator());
+ buffer.append("}");
+ buffer.append(System.lineSeparator());
+
+ buffer.append("RelatedArtifacts:");
- if (artifactInfo.getRelatedArtifacts() != null) {
- buffer.append("{");
- buffer.append(System.lineSeparator());
- for (IArtifactInfo artifactInfoElem:artifactInfo.getRelatedArtifacts()) {
- buffer.append(testNull(dumpASDCArtifactInfo(artifactInfoElem)));
- buffer.append(System.lineSeparator());
- buffer.append(",");
-
- }
- buffer.replace(buffer.length()-1,buffer.length(), System.lineSeparator());
- buffer.append("}");
- buffer.append(System.lineSeparator());
- } else {
- buffer.append("NULL");
- }
-
- buffer.append(System.lineSeparator());
+ if (artifactInfo.getRelatedArtifacts() != null) {
+ buffer.append("{");
+ buffer.append(System.lineSeparator());
+ for (IArtifactInfo artifactInfoElem : artifactInfo.getRelatedArtifacts()) {
+
+ buffer.append(testNull(dumpASDCArtifactInfo(artifactInfoElem)));
+ buffer.append(System.lineSeparator());
+ buffer.append(",");
+
+ }
+ buffer.replace(buffer.length() - 1, buffer.length(), System.lineSeparator());
+ buffer.append("}");
+ buffer.append(System.lineSeparator());
+ } else {
+ buffer.append("NULL");
+ }
+
+ buffer.append(System.lineSeparator());
- return buffer.toString();
- }
+ return buffer.toString();
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/util/NotificationLogging.java b/asdc-controller/src/main/java/org/onap/so/asdc/util/NotificationLogging.java
index fae1da374a..d2e5b07a07 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/util/NotificationLogging.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/util/NotificationLogging.java
@@ -35,138 +35,133 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.onap.sdc.api.notification.INotificationData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NotificationLogging implements InvocationHandler {
-
- private static Map<Object, List<Method>> objectMethodsToLog = new HashMap<>();
-
- protected static final Logger logger = LoggerFactory.getLogger(NotificationLogging.class);
-
- private static InvocationHandler handler = (arg0, arg1, arg2) -> {
- List<Method> methods = objectMethodsToLog.get(arg0);
- if ((methods == null) || (methods.isEmpty())) {
- // Do nothing for now...
- return null;
- }
- methods.add(arg1);
- return arg1.invoke(arg0, arg2);
- };
-
- public static InvocationHandler getHandler() {
- return handler;
- }
-
- /**
- *
- */
- private NotificationLogging() {}
-
- private static final String[] GETTER_PREFIXES = { "get", "is" };
-
- public static String logNotification(INotificationData iNotif) {
- if (iNotif == null) {
- return "NULL";
- }
-
- Class<? extends INotificationData> clazz = iNotif.getClass();
-
- Method[] declaredMethods = clazz.getDeclaredMethods();
-
- if (declaredMethods == null || declaredMethods.length == 0) {
- return "EMPTY"; // No declared methods in this class !!!
- }
-
- StringBuilder buffer = new StringBuilder("ASDC Notification:");
- buffer.append(System.lineSeparator());
-
- for (Method m : declaredMethods) {
- if ((m != null) && isGetter(m)) {
- for (String prefix : GETTER_PREFIXES) {
- if (m.getName().startsWith(prefix)) {
- buffer.append(m.getName().substring(prefix.length()));
- break;
- }
- }
- try {
- buffer.append(testNull(m.invoke(iNotif, (Object[])null)));
- } catch (IllegalAccessException | IllegalArgumentException
- | InvocationTargetException e) {
- logger.debug("Exception", e);
- buffer.append("UNREADABLE");
- }
- buffer.append(System.lineSeparator());
- }
- }
-
- return buffer.toString();
- }
-
- private static boolean isGetter(Method method) {
-
- // Must start with a valid (and known) prefix
- boolean prefixFound = false;
- for (String prefix : GETTER_PREFIXES) {
- if (method.getName().startsWith(prefix)) {
- prefixFound = true;
- break;
- }
- }
- if (!prefixFound) {
- return false;
- }
-
- // Must not take any input arguments
- if (method.getParameterTypes().length != 0) {
- return false;
- }
-
- // Must not have return type 'void'
- if (void.class.equals(method.getReturnType())) {
- return false;
- }
-
- // Must be public
- if (!Modifier.isPublic(method.getModifiers())) {
- return false;
- }
-
- return true;
- }
-
- private static String testNull(Object object) {
- if (object == null) {
- return "NULL";
- } else if (object instanceof Integer) {
- return object.toString();
- } else if (object instanceof String) {
- return (String) object;
- } else {
- return "Type not recognized";
- }
- }
-
- private static void registerForLog(INotificationData objectToLog) {
- INotificationData proxy = (INotificationData) Proxy.newProxyInstance(
- INotificationData.class.getClassLoader(),
- new Class[] { INotificationData.class },
- NotificationLogging.getHandler());
- objectMethodsToLog.put(proxy, new ArrayList<>());
- }
-
- private static <T> void methodToLog(T methodCall) {
- //
- }
-
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- // TODO Auto-generated method stub
- return null;
- }
+
+ private static Map<Object, List<Method>> objectMethodsToLog = new HashMap<>();
+
+ protected static final Logger logger = LoggerFactory.getLogger(NotificationLogging.class);
+
+ private static InvocationHandler handler = (arg0, arg1, arg2) -> {
+ List<Method> methods = objectMethodsToLog.get(arg0);
+ if ((methods == null) || (methods.isEmpty())) {
+ // Do nothing for now...
+ return null;
+ }
+ methods.add(arg1);
+ return arg1.invoke(arg0, arg2);
+ };
+
+ public static InvocationHandler getHandler() {
+ return handler;
+ }
+
+ /**
+ *
+ */
+ private NotificationLogging() {}
+
+ private static final String[] GETTER_PREFIXES = {"get", "is"};
+
+ public static String logNotification(INotificationData iNotif) {
+ if (iNotif == null) {
+ return "NULL";
+ }
+
+ Class<? extends INotificationData> clazz = iNotif.getClass();
+
+ Method[] declaredMethods = clazz.getDeclaredMethods();
+
+ if (declaredMethods == null || declaredMethods.length == 0) {
+ return "EMPTY"; // No declared methods in this class !!!
+ }
+
+ StringBuilder buffer = new StringBuilder("ASDC Notification:");
+ buffer.append(System.lineSeparator());
+
+ for (Method m : declaredMethods) {
+ if ((m != null) && isGetter(m)) {
+ for (String prefix : GETTER_PREFIXES) {
+ if (m.getName().startsWith(prefix)) {
+ buffer.append(m.getName().substring(prefix.length()));
+ break;
+ }
+ }
+ try {
+ buffer.append(testNull(m.invoke(iNotif, (Object[]) null)));
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+ logger.debug("Exception", e);
+ buffer.append("UNREADABLE");
+ }
+ buffer.append(System.lineSeparator());
+ }
+ }
+
+ return buffer.toString();
+ }
+
+ private static boolean isGetter(Method method) {
+
+ // Must start with a valid (and known) prefix
+ boolean prefixFound = false;
+ for (String prefix : GETTER_PREFIXES) {
+ if (method.getName().startsWith(prefix)) {
+ prefixFound = true;
+ break;
+ }
+ }
+ if (!prefixFound) {
+ return false;
+ }
+
+ // Must not take any input arguments
+ if (method.getParameterTypes().length != 0) {
+ return false;
+ }
+
+ // Must not have return type 'void'
+ if (void.class.equals(method.getReturnType())) {
+ return false;
+ }
+
+ // Must be public
+ if (!Modifier.isPublic(method.getModifiers())) {
+ return false;
+ }
+
+ return true;
+ }
+
+ private static String testNull(Object object) {
+ if (object == null) {
+ return "NULL";
+ } else if (object instanceof Integer) {
+ return object.toString();
+ } else if (object instanceof String) {
+ return (String) object;
+ } else {
+ return "Type not recognized";
+ }
+ }
+
+ private static void registerForLog(INotificationData objectToLog) {
+ INotificationData proxy = (INotificationData) Proxy.newProxyInstance(INotificationData.class.getClassLoader(),
+ new Class[] {INotificationData.class}, NotificationLogging.getHandler());
+ objectMethodsToLog.put(proxy, new ArrayList<>());
+ }
+
+ private static <T> void methodToLog(T methodCall) {
+ //
+ }
+
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/util/ToLog.java b/asdc-controller/src/main/java/org/onap/so/asdc/util/ToLog.java
index 1f67b9cd91..b69158d426 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/util/ToLog.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/util/ToLog.java
@@ -23,7 +23,6 @@ package org.onap.so.asdc.util;
-
public @interface ToLog {
}
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/util/YamlEditor.java b/asdc-controller/src/main/java/org/onap/so/asdc/util/YamlEditor.java
index 3418ee3295..acafaacd11 100644
--- a/asdc-controller/src/main/java/org/onap/so/asdc/util/YamlEditor.java
+++ b/asdc-controller/src/main/java/org/onap/so/asdc/util/YamlEditor.java
@@ -32,76 +32,74 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-
import org.yaml.snakeyaml.Yaml;
-
import org.onap.so.db.catalog.beans.HeatTemplateParam;
public class YamlEditor {
protected static final String REFER_PATTERN = "file:///";
- protected Map <String, Object> yml;
- protected Yaml yaml = new Yaml ();
+ protected Map<String, Object> yml;
+ protected Yaml yaml = new Yaml();
- public YamlEditor () {
+ public YamlEditor() {
}
- public YamlEditor (byte[] body) {
- init (body);
+ public YamlEditor(byte[] body) {
+ init(body);
}
-
- public YamlEditor (Yaml yaml) {
- this.yaml = yaml;
+
+ public YamlEditor(Yaml yaml) {
+ this.yaml = yaml;
}
@SuppressWarnings("unchecked")
- protected synchronized void init (byte[] body) {
- InputStream input = new ByteArrayInputStream (body);
- yml = (Map <String, Object>) yaml.load (input);
+ protected synchronized void init(byte[] body) {
+ InputStream input = new ByteArrayInputStream(body);
+ yml = (Map<String, Object>) yaml.load(input);
}
- public synchronized List <String> getYamlNestedFileResourceTypeList () {
- List <String> typeList = new ArrayList<>();
+ public synchronized List<String> getYamlNestedFileResourceTypeList() {
+ List<String> typeList = new ArrayList<>();
@SuppressWarnings("unchecked")
- Map <String, Object> resourceMap = (Map <String, Object>) yml.get ("resources");
- Iterator <Entry <String, Object>> it = resourceMap.entrySet ().iterator ();
- while (it.hasNext ()) {
- Map.Entry <String, Object> pair = it.next ();
+ Map<String, Object> resourceMap = (Map<String, Object>) yml.get("resources");
+ Iterator<Entry<String, Object>> it = resourceMap.entrySet().iterator();
+ while (it.hasNext()) {
+ Map.Entry<String, Object> pair = it.next();
@SuppressWarnings("unchecked")
- Map <String, String> resourceEntry = (Map <String, String>) pair.getValue ();
- String type = resourceEntry.get ("type");
+ Map<String, String> resourceEntry = (Map<String, String>) pair.getValue();
+ String type = resourceEntry.get("type");
- if (type.contains (REFER_PATTERN)) {
- typeList.add (type);
+ if (type.contains(REFER_PATTERN)) {
+ typeList.add(type);
}
- it.remove (); // avoids a ConcurrentModificationException
+ it.remove(); // avoids a ConcurrentModificationException
}
return typeList;
}
-
- public synchronized List <String> getYamlResourceTypeList () {
- List <String> typeList = new ArrayList<>();
+
+ public synchronized List<String> getYamlResourceTypeList() {
+ List<String> typeList = new ArrayList<>();
@SuppressWarnings("unchecked")
- Map <String, Object> resourceMap = (Map <String, Object>) yml.get ("resources");
+ Map<String, Object> resourceMap = (Map<String, Object>) yml.get("resources");
for (Entry<String, Object> pair : resourceMap.entrySet()) {
@SuppressWarnings("unchecked")
Map<String, String> resourceEntry = (Map<String, String>) pair.getValue();
typeList.add(resourceEntry.get("type"));
}
return typeList;
- }
+ }
// Generate the parameter list based on the Heat Template
// Based on the email from Ella Kvetny:
// Within Heat Template, under parameters catalog, it might indicate the default value of the parameter
// If default value exist, the parameter is not mandatory, otherwise its value should be set
- public synchronized Set <HeatTemplateParam> getParameterList (String artifactUUID) {
- Set <HeatTemplateParam> paramSet = new HashSet<>();
+ public synchronized Set<HeatTemplateParam> getParameterList(String artifactUUID) {
+ Set<HeatTemplateParam> paramSet = new HashSet<>();
@SuppressWarnings("unchecked")
- Map <String, Object> resourceMap = (Map <String, Object>) yml.get ("parameters");
+ Map<String, Object> resourceMap = (Map<String, Object>) yml.get("parameters");
for (Entry<String, Object> stringObjectEntry : resourceMap.entrySet()) {
HeatTemplateParam param = new HeatTemplateParam();
@@ -129,42 +127,42 @@ public class YamlEditor {
}
- public synchronized void addParameterList (Set <HeatTemplateParam> heatSet) {
+ public synchronized void addParameterList(Set<HeatTemplateParam> heatSet) {
@SuppressWarnings("unchecked")
- Map <String, Object> resourceMap = (Map <String, Object>) yml.get ("parameters");
+ Map<String, Object> resourceMap = (Map<String, Object>) yml.get("parameters");
if (resourceMap == null) {
resourceMap = new LinkedHashMap<>();
- this.yml.put ("parameters", resourceMap);
+ this.yml.put("parameters", resourceMap);
}
for (HeatTemplateParam heatParam : heatSet) {
- Map <String, Object> paramInfo = new HashMap<>();
- paramInfo.put ("type", heatParam.getParamType ());
+ Map<String, Object> paramInfo = new HashMap<>();
+ paramInfo.put("type", heatParam.getParamType());
- resourceMap.put (heatParam.getParamName (), paramInfo);
+ resourceMap.put(heatParam.getParamName(), paramInfo);
}
// this.yml.put("parameters", resourceMap);
}
- public boolean isParentTemplate (String templateBody) {
- return templateBody.contains (REFER_PATTERN);
+ public boolean isParentTemplate(String templateBody) {
+ return templateBody.contains(REFER_PATTERN);
}
- public boolean verifyTemplate () {
+ public boolean verifyTemplate() {
// Verify whether the heat template is for Vnf Resource
// We don't support other template installation yet
return true;
}
- public String encode (Map <String, Object> content) {
- return yaml.dump (content);
+ public String encode(Map<String, Object> content) {
+ return yaml.dump(content);
}
- public synchronized String encode () {
- return this.yaml.dump (this.yml);
+ public synchronized String encode() {
+ return this.yaml.dump(this.yml);
}
/**
@@ -172,9 +170,9 @@ public class YamlEditor {
*
*/
@Override
- public String toString () {
+ public String toString() {
- return encode ();
+ return encode();
}
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/ASDCPojoTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/ASDCPojoTest.java
index 354b6dac3c..dc51d46888 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/ASDCPojoTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/ASDCPojoTest.java
@@ -29,7 +29,6 @@ import org.onap.so.asdc.client.test.emulators.JsonVfModuleMetaData;
import org.onap.so.asdc.client.test.emulators.NotificationDataImpl;
import org.onap.so.asdc.client.test.emulators.ResourceInfoImpl;
import org.onap.so.asdc.installer.VfResourceStructure;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.impl.PojoClassFactory;
import com.openpojo.validation.Validator;
@@ -38,23 +37,20 @@ import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
public class ASDCPojoTest {
- @Test
- public void pojoStructure() {
- test(PojoClassFactory.getPojoClass(FinalDistributionStatusMessage.class));
- test(PojoClassFactory.getPojoClass(ArtifactInfoImpl.class));
- test(PojoClassFactory.getPojoClass(NotificationDataImpl.class));
- test(PojoClassFactory.getPojoClass(JsonVfModuleMetaData.class));
- test(PojoClassFactory.getPojoClass(ResourceInfoImpl.class));
- test(PojoClassFactory.getPojoClass(DistributionClientEmulator.class));
- test(PojoClassFactory.getPojoClass(JsonStatusData.class));
- test(PojoClassFactory.getPojoClass(VfResourceStructure.class));
- }
-
- private void test(PojoClass pojoClass) {
- Validator validator = ValidatorBuilder.create()
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
- validator.validate(pojoClass);
- }
+ @Test
+ public void pojoStructure() {
+ test(PojoClassFactory.getPojoClass(FinalDistributionStatusMessage.class));
+ test(PojoClassFactory.getPojoClass(ArtifactInfoImpl.class));
+ test(PojoClassFactory.getPojoClass(NotificationDataImpl.class));
+ test(PojoClassFactory.getPojoClass(JsonVfModuleMetaData.class));
+ test(PojoClassFactory.getPojoClass(ResourceInfoImpl.class));
+ test(PojoClassFactory.getPojoClass(DistributionClientEmulator.class));
+ test(PojoClassFactory.getPojoClass(JsonStatusData.class));
+ test(PojoClassFactory.getPojoClass(VfResourceStructure.class));
+ }
+
+ private void test(PojoClass pojoClass) {
+ Validator validator = ValidatorBuilder.create().with(new SetterTester()).with(new GetterTester()).build();
+ validator.validate(pojoClass);
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/AllTestsTestSuite.java b/asdc-controller/src/test/java/org/onap/so/asdc/AllTestsTestSuite.java
index a100f26d5a..fb8e5bbc2f 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/AllTestsTestSuite.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/AllTestsTestSuite.java
@@ -19,14 +19,14 @@
*/
package org.onap.so.asdc;
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses("**/*Test.class")
public class AllTestsTestSuite {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/BaseTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/BaseTest.java
index 83d60aefea..0fcf9b0559 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/BaseTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/BaseTest.java
@@ -21,7 +21,6 @@
package org.onap.so.asdc;
import static org.mockito.Mockito.reset;
-
import org.junit.After;
import org.junit.runner.RunWith;
import org.onap.so.asdc.installer.ToscaResourceStructure;
@@ -39,7 +38,6 @@ import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
-
import com.github.tomakehurst.wiremock.WireMockServer;
@RunWith(SpringRunner.class)
@@ -48,23 +46,23 @@ import com.github.tomakehurst.wiremock.WireMockServer;
@ContextConfiguration(classes = SpringContextHelper.class, initializers = ConfigFileApplicationContextInitializer.class)
@AutoConfigureWireMock(port = 0)
public abstract class BaseTest {
- @MockBean
- protected VfResourceStructure vfResourceStructure;
- @MockBean
- protected ToscaResourceStructure toscaResourceStruct;
- @SpyBean
- protected WatchdogDistribution watchdogDistributionSpy;
- @SpyBean
- protected ToscaResourceInstaller toscaInstaller;
- @Autowired
- protected WireMockServer wireMockServer;
-
- @Value("${wiremock.server.port}")
+ @MockBean
+ protected VfResourceStructure vfResourceStructure;
+ @MockBean
+ protected ToscaResourceStructure toscaResourceStruct;
+ @SpyBean
+ protected WatchdogDistribution watchdogDistributionSpy;
+ @SpyBean
+ protected ToscaResourceInstaller toscaInstaller;
+ @Autowired
+ protected WireMockServer wireMockServer;
+
+ @Value("${wiremock.server.port}")
protected String wireMockPort;
- @After
- public void after() {
- reset(vfResourceStructure);
- reset(toscaResourceStruct);
- }
+ @After
+ public void after() {
+ reset(vfResourceStructure);
+ reset(toscaResourceStruct);
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedCatalogDbConfig.java b/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedCatalogDbConfig.java
index 27b6c0ab53..e81a318e68 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedCatalogDbConfig.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedCatalogDbConfig.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.asdc;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
-
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
@@ -36,17 +36,14 @@ import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
-
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration
@Profile({"test"})
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "entityManagerFactory",
- basePackages = {"org.onap.so.db.catalog.data.repository"}
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory",
+ basePackages = {"org.onap.so.db.catalog.data.repository"})
public class EmbeddedCatalogDbConfig {
@Bean
@@ -54,49 +51,36 @@ public class EmbeddedCatalogDbConfig {
return new MariaDB4jSpringService();
}
- @Primary
- @Bean(name = "dataSource")
+ @Primary
+ @Bean(name = "dataSource")
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
-
- @Primary
- @Bean(name = "entityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("dataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.catalog.beans")
- .persistenceUnit("catalogDB")
- .build();
- }
- @Primary
- @Bean(name = "transactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("entityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
+ @Primary
+ @Bean(name = "entityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("dataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.catalog.beans").persistenceUnit("catalogDB")
+ .build();
+ }
+
+ @Primary
+ @Bean(name = "transactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedRequestDbConfig.java b/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedRequestDbConfig.java
index 2827f8721e..e60b8fe238 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedRequestDbConfig.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/EmbeddedRequestDbConfig.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.asdc;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
-
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
@@ -37,17 +37,14 @@ import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
-
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration
@Profile({"test"})
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager",
- basePackages = { "org.onap.so.db.request.data.repository" }
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory",
+ transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"})
public class EmbeddedRequestDbConfig {
@Bean
@@ -56,47 +53,34 @@ public class EmbeddedRequestDbConfig {
}
- @Bean(name = "requestDataSource")
- @ConfigurationProperties(prefix = "request.datasource")
+ @Bean(name = "requestDataSource")
+ @ConfigurationProperties(prefix = "request.datasource")
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName2}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName2}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
- @Bean(name = "requestEntityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("requestDataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.request.beans")
- .persistenceUnit("requestDB")
- .build();
- }
+ @Bean(name = "requestEntityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("requestDataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB")
+ .build();
+ }
- @Bean(name = "requestTransactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("requestEntityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
+ @Bean(name = "requestTransactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/TestApplication.java b/asdc-controller/src/test/java/org/onap/so/asdc/TestApplication.java
index 4298f9c5b5..c35e8e34d6 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/TestApplication.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/TestApplication.java
@@ -31,15 +31,15 @@ import org.springframework.context.annotation.Profile;
@SpringBootApplication
@Profile("test")
-@ComponentScan(basePackages = {"org.onap.so.asdc"}, excludeFilters = {
- @Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class),
- @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = RequestsDBHelper.class),
- @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = InfraActiveRequestsRepositoryImpl.class) })
+@ComponentScan(basePackages = {"org.onap.so.asdc"},
+ excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class),
+ @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = RequestsDBHelper.class),
+ @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = InfraActiveRequestsRepositoryImpl.class)})
public class TestApplication {
- public static void main(String... args) {
- SpringApplication.run(TestApplication.class, args);
- System.getProperties().setProperty("mso.db", "MARIADB");
- System.getProperties().setProperty("server.name", "Springboot");
- System.getProperties().setProperty("mso.config.path", "src/test/resources/");
- }
+ public static void main(String... args) {
+ SpringApplication.run(TestApplication.class, args);
+ System.getProperties().setProperty("mso.db", "MARIADB");
+ System.getProperties().setProperty("server.name", "Springboot");
+ System.getProperties().setProperty("mso.config.path", "src/test/resources/");
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCConfigurationTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCConfigurationTest.java
index 16bd97b409..40c403fd72 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCConfigurationTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCConfigurationTest.java
@@ -23,9 +23,7 @@ package org.onap.so.asdc.client;
import static org.junit.Assert.assertTrue;
-
import javax.transaction.Transactional;
-
import org.junit.Test;
import org.onap.so.asdc.BaseTest;
import org.springframework.beans.factory.annotation.Autowired;
@@ -36,24 +34,24 @@ import org.springframework.beans.factory.annotation.Autowired;
*
*/
public class ASDCConfigurationTest extends BaseTest {
-
+
@Autowired
private ASDCConfiguration config;
-
+
@Test
- @Transactional
- public void testInitASDCConfiguration() throws Exception {
- assertTrue("msopreist".equals(config.getUser()));
- assertTrue("msoasdc-id-local".equals(config.getConsumerGroup()));
- assertTrue("msoasdc-id-local".equals(config.getConsumerID()));
- assertTrue("Pre-IST".equals(config.getEnvironmentName()));
- assertTrue("localhost:8443".equals(config.getAsdcAddress()));
- assertTrue("msopreist".equals(config.getPassword()));
- assertTrue(config.getPollingInterval() == 30);
- assertTrue(config.getPollingTimeout() == 30);
- assertTrue(config.getRelevantArtifactTypes().size() == config.SUPPORTED_ARTIFACT_TYPES_LIST.size());
- assertTrue(config.getWatchDogTimeout() == 1);
- assertTrue(config.isUseHttpsWithDmaap() == true);
+ @Transactional
+ public void testInitASDCConfiguration() throws Exception {
+ assertTrue("msopreist".equals(config.getUser()));
+ assertTrue("msoasdc-id-local".equals(config.getConsumerGroup()));
+ assertTrue("msoasdc-id-local".equals(config.getConsumerID()));
+ assertTrue("Pre-IST".equals(config.getEnvironmentName()));
+ assertTrue("localhost:8443".equals(config.getAsdcAddress()));
+ assertTrue("msopreist".equals(config.getPassword()));
+ assertTrue(config.getPollingInterval() == 30);
+ assertTrue(config.getPollingTimeout() == 30);
+ assertTrue(config.getRelevantArtifactTypes().size() == config.SUPPORTED_ARTIFACT_TYPES_LIST.size());
+ assertTrue(config.getWatchDogTimeout() == 1);
+ assertTrue(config.isUseHttpsWithDmaap() == true);
}
-
+
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java
index 51559c2ffe..0681cd8aed 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.asdc.client;
@@ -26,15 +21,12 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
-
import javax.persistence.EntityNotFoundException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
@@ -120,7 +112,7 @@ public class ASDCControllerITTest extends BaseTest {
distributionId = UUID.randomUUID().toString();
artifactUuid = UUID.randomUUID().toString();
logger.info("Using distributionId: {}, artifactUUID: {} for testcase: {}", distributionId, artifactUuid,
- testName.getMethodName());
+ testName.getMethodName());
distributionClient = new DistributionClientEmulator();
distributionClient.setResourcePath("src/test/resources");
@@ -148,7 +140,7 @@ public class ASDCControllerITTest extends BaseTest {
*/
private void initMockAaiServer(final String serviceUuid, final String serviceInvariantUuid) {
String modelEndpoint = "/aai/v15/service-design-and-creation/models/model/" + serviceInvariantUuid
- + "/model-vers/model-ver/" + serviceUuid + "?depth=0";
+ + "/model-vers/model-ver/" + serviceUuid + "?depth=0";
wireMockServer.stubFor(post(urlEqualTo(modelEndpoint)).willReturn(ok()));
}
@@ -191,7 +183,7 @@ public class ASDCControllerITTest extends BaseTest {
* Check the tosca csar entity, it should be the same as provided from NotficationData.
*/
ToscaCsar toscaCsar = toscaCsarRepository.findById(artifactUuid)
- .orElseThrow(() -> new EntityNotFoundException("Tosca csar: " + artifactUuid + " not found"));
+ .orElseThrow(() -> new EntityNotFoundException("Tosca csar: " + artifactUuid + " not found"));
assertEquals("tosca csar UUID", artifactUuid, toscaCsar.getArtifactUUID());
assertEquals("tosca csar name", "service-Testservice140-csar.csar", toscaCsar.getName());
assertEquals("tosca csar version", "1.0", toscaCsar.getVersion());
@@ -200,17 +192,18 @@ public class ASDCControllerITTest extends BaseTest {
assertEquals("toscar csar URL", "/download/service-Testservice140-csar.csar", toscaCsar.getUrl());
/**
- * Check the service entity, it should be the same as global metadata information in service-Testservice140-template.yml inside csar.
+ * Check the service entity, it should be the same as global metadata information in
+ * service-Testservice140-template.yml inside csar.
*/
Service service = serviceRepository.findById(serviceUuid)
- .orElseThrow(() -> new EntityNotFoundException("Service: " + serviceUuid + " not found"));
+ .orElseThrow(() -> new EntityNotFoundException("Service: " + serviceUuid + " not found"));
assertEquals("model UUID", "efaea486-561f-4159-9191-a8d3cb346728", service.getModelUUID());
assertEquals("model name", "TestService140", service.getModelName());
assertEquals("model invariantUUID", "f2edfbf4-bb0a-4fe7-a57a-71362d4b0b23",
- service.getModelInvariantUUID());
+ service.getModelInvariantUUID());
assertEquals("model version", "1.0", service.getModelVersion());
assertEquals("description", "Test Service for extended attributes of PNF resource",
- service.getDescription().trim());
+ service.getDescription().trim());
assertEquals("tosca csar artifact UUID", artifactUuid, service.getCsar().getArtifactUUID());
assertEquals("service type", "Network", service.getServiceType());
assertEquals("service role", "nfv", service.getServiceRole());
@@ -220,18 +213,17 @@ public class ASDCControllerITTest extends BaseTest {
assertEquals("resource order", "Test140PNF", service.getResourceOrder());
/**
- * Check PNF resource, it should be the same as metadata in the topology template in service-Testservice140-template.yml
- * OR
- * global metadata in the resource-Test140pnf-template.yml
+ * Check PNF resource, it should be the same as metadata in the topology template in
+ * service-Testservice140-template.yml OR global metadata in the resource-Test140pnf-template.yml
*/
String pnfResourceKey = "9c54e269-122b-4e8a-8b2a-6eac849b441a";
PnfResource pnfResource = pnfResourceRepository.findById(pnfResourceKey)
- .orElseThrow(() -> new EntityNotFoundException("PNF resource:" + pnfResourceKey + " not found"));
+ .orElseThrow(() -> new EntityNotFoundException("PNF resource:" + pnfResourceKey + " not found"));
assertNull("orchestration mode", pnfResource.getOrchestrationMode());
assertEquals("Description", "Oracle", pnfResource.getDescription().trim());
assertEquals("model UUID", pnfResourceKey, pnfResource.getModelUUID());
assertEquals("model invariant UUID", "d832a027-75f3-455d-9de4-f02fcdee7e7e",
- pnfResource.getModelInvariantUUID());
+ pnfResource.getModelInvariantUUID());
assertEquals("model version", "1.0", pnfResource.getModelVersion());
assertEquals("model name", "Test140PNF", pnfResource.getModelName());
assertEquals("tosca node type", "org.openecomp.resource.pnf.Test140pnf", pnfResource.getToscaNodeType());
@@ -239,15 +231,13 @@ public class ASDCControllerITTest extends BaseTest {
assertEquals("resource sub category", "Call Control", pnfResource.getSubCategory());
/**
- * Check PNF resource customization, it should be the same as metadata in the topology template in service-Testservice140-template.yml
- * OR
- * global metadata in the resource-Test140pnf-template.yml
+ * Check PNF resource customization, it should be the same as metadata in the topology template in
+ * service-Testservice140-template.yml OR global metadata in the resource-Test140pnf-template.yml
*/
String pnfCustomizationKey = "428a3d73-f962-4cc2-ba62-2483c45d6b12";
- PnfResourceCustomization pnfCustomization = pnfCustomizationRepository
- .findById(pnfCustomizationKey).orElseThrow(
- () -> new EntityNotFoundException(
- "PNF resource customization: " + pnfCustomizationKey + " not found"));
+ PnfResourceCustomization pnfCustomization = pnfCustomizationRepository.findById(pnfCustomizationKey)
+ .orElseThrow(() -> new EntityNotFoundException(
+ "PNF resource customization: " + pnfCustomizationKey + " not found"));
assertEquals("model customizationUUID", pnfCustomizationKey, pnfCustomization.getModelCustomizationUUID());
assertEquals("model instance name", "Test140PNF 0", pnfCustomization.getModelInstanceName());
assertEquals("NF type", "", pnfCustomization.getNfType());
@@ -258,9 +248,9 @@ public class ASDCControllerITTest extends BaseTest {
assertEquals("Multi stage design", "", pnfCustomization.getMultiStageDesign());
assertNull("resource input", pnfCustomization.getResourceInput());
assertEquals("cds blueprint name(sdnc_model_name property)", pnfCustomization.getBlueprintName(),
- pnfCustomization.getBlueprintName());
+ pnfCustomization.getBlueprintName());
assertEquals("cds blueprint version(sdnc_model_version property)", pnfCustomization.getBlueprintVersion(),
- pnfCustomization.getBlueprintVersion());
+ pnfCustomization.getBlueprintVersion());
/**
* Check the pnf resource customization with service mapping
@@ -272,8 +262,8 @@ public class ASDCControllerITTest extends BaseTest {
/**
* Check the watchdog for component distribution status
*/
- List<WatchdogComponentDistributionStatus> distributionList = watchdogCDStatusRepository
- .findByDistributionId(this.distributionId);
+ List<WatchdogComponentDistributionStatus> distributionList =
+ watchdogCDStatusRepository.findByDistributionId(this.distributionId);
assertNotNull(distributionList);
assertEquals(1, distributionList.size());
WatchdogComponentDistributionStatus distributionStatus = distributionList.get(0);
@@ -353,7 +343,7 @@ public class ASDCControllerITTest extends BaseTest {
* Check the tosca csar entity, it should be the same as provided from NotficationData.
*/
ToscaCsar toscaCsar = toscaCsarRepository.findById(artifactUuid)
- .orElseThrow(() -> new EntityNotFoundException("Tosca csar: " + artifactUuid + " not found"));
+ .orElseThrow(() -> new EntityNotFoundException("Tosca csar: " + artifactUuid + " not found"));
assertEquals("tosca csar UUID", artifactUuid, toscaCsar.getArtifactUUID());
assertEquals("tosca csar name", "service-Svc140-VF-csar.csar", toscaCsar.getName());
assertEquals("tosca csar version", "1.0", toscaCsar.getVersion());
@@ -362,17 +352,16 @@ public class ASDCControllerITTest extends BaseTest {
assertEquals("toscar csar URL", "/download/service-Svc140-VF-csar.csar", toscaCsar.getUrl());
/**
- * Check the service entity, it should be the same as global metadata information in service-Testservice140-template.yml inside csar.
+ * Check the service entity, it should be the same as global metadata information in
+ * service-Testservice140-template.yml inside csar.
*/
Service service = serviceRepository.findById(serviceUuid)
- .orElseThrow(() -> new EntityNotFoundException("Service: " + serviceUuid + " not found"));
+ .orElseThrow(() -> new EntityNotFoundException("Service: " + serviceUuid + " not found"));
assertEquals("model UUID", serviceUuid, service.getModelUUID());
assertEquals("model name", "SVC140", service.getModelName());
- assertEquals("model invariantUUID", serviceInvariantUuid,
- service.getModelInvariantUUID());
+ assertEquals("model invariantUUID", serviceInvariantUuid, service.getModelInvariantUUID());
assertEquals("model version", "1.0", service.getModelVersion());
- assertEquals("description", "SVC140",
- service.getDescription().trim());
+ assertEquals("description", "SVC140", service.getDescription().trim());
assertEquals("tosca csar artifact UUID", artifactUuid, service.getCsar().getArtifactUUID());
assertEquals("service type", "ST", service.getServiceType());
assertEquals("service role", "Sr", service.getServiceRole());
@@ -382,18 +371,17 @@ public class ASDCControllerITTest extends BaseTest {
assertEquals("resource order", "TestVF140", service.getResourceOrder());
/**
- * Check VNF resource, it should be the same as metadata in the topology template in service-Testservice140-template.yml
- * OR
- * global metadata in the resource-Testservice140-template.yml
+ * Check VNF resource, it should be the same as metadata in the topology template in
+ * service-Testservice140-template.yml OR global metadata in the resource-Testservice140-template.yml
*/
String vnfResourceKey = "d20d3ea9-2f54-4071-8b5c-fd746dde245e";
VnfResource vnfResource = vnfResourceRepository.findById(vnfResourceKey)
- .orElseThrow(() -> new EntityNotFoundException("VNF resource:" + vnfResourceKey + " not found"));
+ .orElseThrow(() -> new EntityNotFoundException("VNF resource:" + vnfResourceKey + " not found"));
assertEquals("orchestration mode", "HEAT", vnfResource.getOrchestrationMode());
assertEquals("Description", "TestPNF140", vnfResource.getDescription().trim());
assertEquals("model UUID", vnfResourceKey, vnfResource.getModelUUID());
assertEquals("model invariant UUID", "7a4bffa2-fac5-4b8b-b348-0bdf313a1aeb",
- vnfResource.getModelInvariantUUID());
+ vnfResource.getModelInvariantUUID());
assertEquals("model version", "1.0", vnfResource.getModelVersion());
assertEquals("model name", "TestVF140", vnfResource.getModelName());
assertEquals("tosca node type", "org.openecomp.resource.vf.Testvf140", vnfResource.getToscaNodeType());
@@ -401,15 +389,14 @@ public class ASDCControllerITTest extends BaseTest {
assertEquals("resource sub category", "Database", vnfResource.getSubCategory());
/**
- * Check VNF resource customization, it should be the same as metadata in the topology template in service-Testservice140-template.yml
- * OR
- * global metadata in the resource-Testservice140-template.yml
+ * Check VNF resource customization, it should be the same as metadata in the topology template in
+ * service-Testservice140-template.yml OR global metadata in the resource-Testservice140-template.yml
*/
String vnfCustomizationKey = "ca1c8455-8ce2-4a76-a037-3f4cf01cffa0";
- VnfResourceCustomization vnfCustomization = Optional.ofNullable(vnfCustomizationRepository
- .findOneByModelCustomizationUUID(vnfCustomizationKey)).orElseThrow(
- () -> new EntityNotFoundException(
- "VNF resource customization: " + vnfCustomizationKey + " not found"));
+ VnfResourceCustomization vnfCustomization =
+ Optional.ofNullable(vnfCustomizationRepository.findOneByModelCustomizationUUID(vnfCustomizationKey))
+ .orElseThrow(() -> new EntityNotFoundException(
+ "VNF resource customization: " + vnfCustomizationKey + " not found"));
assertEquals("model customizationUUID", vnfCustomizationKey, vnfCustomization.getModelCustomizationUUID());
assertEquals("model instance name", "TestVF140 0", vnfCustomization.getModelInstanceName());
assertNull("NF type", vnfCustomization.getNfType());
@@ -420,9 +407,9 @@ public class ASDCControllerITTest extends BaseTest {
assertEquals("Multi stage design", "false", vnfCustomization.getMultiStageDesign());
assertNull("resource input", vnfCustomization.getResourceInput());
assertEquals("cds blueprint name(sdnc_model_name property)", vnfCustomization.getBlueprintName(),
- vnfCustomization.getBlueprintName());
+ vnfCustomization.getBlueprintName());
assertEquals("cds blueprint version(sdnc_model_version property)", vnfCustomization.getBlueprintVersion(),
- vnfCustomization.getBlueprintVersion());
+ vnfCustomization.getBlueprintVersion());
/**
* Check the vnf resource customization with service mapping
*/
@@ -433,8 +420,8 @@ public class ASDCControllerITTest extends BaseTest {
/**
* Check the watchdog for component distribution status
*/
- List<WatchdogComponentDistributionStatus> distributionList = watchdogCDStatusRepository
- .findByDistributionId(this.distributionId);
+ List<WatchdogComponentDistributionStatus> distributionList =
+ watchdogCDStatusRepository.findByDistributionId(this.distributionId);
assertNotNull(distributionList);
assertEquals(1, distributionList.size());
WatchdogComponentDistributionStatus distributionStatus = distributionList.get(0);
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerTest.java
index 580220aabb..104eed7c90 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerTest.java
@@ -28,21 +28,21 @@ import org.onap.so.asdc.client.exceptions.ASDCControllerException;
import org.springframework.beans.factory.annotation.Autowired;
public class ASDCControllerTest extends BaseTest {
- @Autowired
- private ASDCController asdcController;
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Test
- public void initASDCExceptionTest() throws Exception {
- expectedException.expect(ASDCControllerException.class);
-
- asdcController.changeControllerStatus(ASDCControllerStatus.IDLE);
-
- try {
- asdcController.initASDC();
- } finally {
- asdcController.closeASDC();
- }
- }
+ @Autowired
+ private ASDCController asdcController;
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Test
+ public void initASDCExceptionTest() throws Exception {
+ expectedException.expect(ASDCControllerException.class);
+
+ asdcController.changeControllerStatus(ASDCControllerStatus.IDLE);
+
+ try {
+ asdcController.initASDC();
+ } finally {
+ asdcController.closeASDC();
+ }
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCElementInfoTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCElementInfoTest.java
index fec3ae6362..6196691807 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCElementInfoTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCElementInfoTest.java
@@ -27,10 +27,8 @@ 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.Collections;
import java.util.UUID;
-
import org.junit.Test;
import org.mockito.Mockito;
import org.onap.sdc.api.notification.IArtifactInfo;
@@ -46,129 +44,132 @@ import org.onap.so.asdc.installer.IVfModuleData;
public class ASDCElementInfoTest {
- @Test
- public void createASDCElementInfoWithNullParameterTest() {
- ASDCElementInfo elementInfoFromNullVfArtifact = ASDCElementInfo.createElementFromVfArtifactInfo(null);
- ASDCElementInfo elementInfoFromNullVfModuleStructure = ASDCElementInfo.createElementFromVfModuleStructure(null);
- ASDCElementInfo elementInfoFromNullVfResourceStructure = ASDCElementInfo.createElementFromVfResourceStructure(null);
+ @Test
+ public void createASDCElementInfoWithNullParameterTest() {
+ ASDCElementInfo elementInfoFromNullVfArtifact = ASDCElementInfo.createElementFromVfArtifactInfo(null);
+ ASDCElementInfo elementInfoFromNullVfModuleStructure = ASDCElementInfo.createElementFromVfModuleStructure(null);
+ ASDCElementInfo elementInfoFromNullVfResourceStructure =
+ ASDCElementInfo.createElementFromVfResourceStructure(null);
- elementInfoFromNullVfArtifact.addElementInfo(null, null);
- elementInfoFromNullVfModuleStructure.addElementInfo(null, "someValue");
- elementInfoFromNullVfResourceStructure.addElementInfo("someKey", null);
+ elementInfoFromNullVfArtifact.addElementInfo(null, null);
+ elementInfoFromNullVfModuleStructure.addElementInfo(null, "someValue");
+ elementInfoFromNullVfResourceStructure.addElementInfo("someKey", null);
- assertEquals(elementInfoFromNullVfArtifact.toString(), "");
- assertEquals(elementInfoFromNullVfModuleStructure.toString(), "");
- assertEquals(elementInfoFromNullVfResourceStructure.toString(), "");
+ assertEquals(elementInfoFromNullVfArtifact.toString(), "");
+ assertEquals(elementInfoFromNullVfModuleStructure.toString(), "");
+ assertEquals(elementInfoFromNullVfResourceStructure.toString(), "");
- assertNotNull(elementInfoFromNullVfArtifact);
- assertNotNull(elementInfoFromNullVfModuleStructure);
- assertNotNull(elementInfoFromNullVfResourceStructure);
+ assertNotNull(elementInfoFromNullVfArtifact);
+ assertNotNull(elementInfoFromNullVfModuleStructure);
+ assertNotNull(elementInfoFromNullVfResourceStructure);
- assertNotNull(ASDCElementInfo.EMPTY_INSTANCE);
+ assertNotNull(ASDCElementInfo.EMPTY_INSTANCE);
- assertEquals(elementInfoFromNullVfArtifact, ASDCElementInfo.EMPTY_INSTANCE);
- assertEquals(elementInfoFromNullVfModuleStructure, ASDCElementInfo.EMPTY_INSTANCE);
- assertEquals(elementInfoFromNullVfResourceStructure, ASDCElementInfo.EMPTY_INSTANCE);
+ assertEquals(elementInfoFromNullVfArtifact, ASDCElementInfo.EMPTY_INSTANCE);
+ assertEquals(elementInfoFromNullVfModuleStructure, ASDCElementInfo.EMPTY_INSTANCE);
+ assertEquals(elementInfoFromNullVfResourceStructure, ASDCElementInfo.EMPTY_INSTANCE);
- assertEquals(ASDCElementInfo.EMPTY_INSTANCE.getType(), "");
- assertEquals(ASDCElementInfo.EMPTY_INSTANCE.toString(), "");
+ assertEquals(ASDCElementInfo.EMPTY_INSTANCE.getType(), "");
+ assertEquals(ASDCElementInfo.EMPTY_INSTANCE.toString(), "");
- assertEquals(elementInfoFromNullVfArtifact.getType(), ASDCElementInfo.EMPTY_INSTANCE.getType());
- assertEquals(elementInfoFromNullVfModuleStructure.getType(), ASDCElementInfo.EMPTY_INSTANCE.getType());
- assertEquals(elementInfoFromNullVfResourceStructure.getType(), ASDCElementInfo.EMPTY_INSTANCE.getType());
- }
+ assertEquals(elementInfoFromNullVfArtifact.getType(), ASDCElementInfo.EMPTY_INSTANCE.getType());
+ assertEquals(elementInfoFromNullVfModuleStructure.getType(), ASDCElementInfo.EMPTY_INSTANCE.getType());
+ assertEquals(elementInfoFromNullVfResourceStructure.getType(), ASDCElementInfo.EMPTY_INSTANCE.getType());
+ }
- @Test
- public void createASDCElementInfoFromVfResourceTest() {
+ @Test
+ public void createASDCElementInfoFromVfResourceTest() {
- String resourceInstanceName = "Resource 1";
+ String resourceInstanceName = "Resource 1";
- UUID generatedUUID = UUID.randomUUID();
+ UUID generatedUUID = UUID.randomUUID();
- INotificationData notificationData = Mockito.mock(INotificationData.class);
- IResourceInstance resourceInstance = Mockito.mock(IResourceInstance.class);
+ INotificationData notificationData = Mockito.mock(INotificationData.class);
+ IResourceInstance resourceInstance = Mockito.mock(IResourceInstance.class);
- Mockito.when(resourceInstance.getResourceInstanceName()).thenReturn(resourceInstanceName);
- Mockito.when(resourceInstance.getResourceInvariantUUID()).thenReturn(generatedUUID.toString());
+ Mockito.when(resourceInstance.getResourceInstanceName()).thenReturn(resourceInstanceName);
+ Mockito.when(resourceInstance.getResourceInvariantUUID()).thenReturn(generatedUUID.toString());
- VfResourceStructure vfResourceStructure = new VfResourceStructure(notificationData, resourceInstance);
+ VfResourceStructure vfResourceStructure = new VfResourceStructure(notificationData, resourceInstance);
- ASDCElementInfo elementInfoFromVfResource = ASDCElementInfo.createElementFromVfResourceStructure(vfResourceStructure);
+ ASDCElementInfo elementInfoFromVfResource =
+ ASDCElementInfo.createElementFromVfResourceStructure(vfResourceStructure);
- assertTrue(elementInfoFromVfResource.toString().contains(resourceInstanceName));
- assertTrue(elementInfoFromVfResource.toString().contains(generatedUUID.toString()));
+ assertTrue(elementInfoFromVfResource.toString().contains(resourceInstanceName));
+ assertTrue(elementInfoFromVfResource.toString().contains(generatedUUID.toString()));
- assertFalse(ASDCConfiguration.VF_MODULES_METADATA.equals(elementInfoFromVfResource.getType()));
- assertEquals(ASDCElementInfo.ASDCElementTypeEnum.VNF_RESOURCE.name(), elementInfoFromVfResource.getType());
+ assertFalse(ASDCConfiguration.VF_MODULES_METADATA.equals(elementInfoFromVfResource.getType()));
+ assertEquals(ASDCElementInfo.ASDCElementTypeEnum.VNF_RESOURCE.name(), elementInfoFromVfResource.getType());
- assertFalse(elementInfoFromVfResource.toString().contains("MyInfo1: someValue"));
- elementInfoFromVfResource.addElementInfo("MyInfo1", "someValue");
- assertTrue(elementInfoFromVfResource.toString().contains("MyInfo1: someValue"));
- }
+ assertFalse(elementInfoFromVfResource.toString().contains("MyInfo1: someValue"));
+ elementInfoFromVfResource.addElementInfo("MyInfo1", "someValue");
+ assertTrue(elementInfoFromVfResource.toString().contains("MyInfo1: someValue"));
+ }
- @Test
- public void createASDCElementInfoFromVfModuleTest() throws ArtifactInstallerException {
+ @Test
+ public void createASDCElementInfoFromVfModuleTest() throws ArtifactInstallerException {
- String resourceInstanceName = "Resource 1";
+ String resourceInstanceName = "Resource 1";
- UUID generatedUUID = UUID.randomUUID();
+ UUID generatedUUID = UUID.randomUUID();
- INotificationData notificationData = Mockito.mock(INotificationData.class);
- IResourceInstance resourceInstance = Mockito.mock(IResourceInstance.class);
+ INotificationData notificationData = Mockito.mock(INotificationData.class);
+ IResourceInstance resourceInstance = Mockito.mock(IResourceInstance.class);
- Mockito.when(resourceInstance.getResourceInstanceName()).thenReturn(resourceInstanceName);
- Mockito.when(resourceInstance.getResourceInvariantUUID()).thenReturn(generatedUUID.toString());
+ Mockito.when(resourceInstance.getResourceInstanceName()).thenReturn(resourceInstanceName);
+ Mockito.when(resourceInstance.getResourceInvariantUUID()).thenReturn(generatedUUID.toString());
- VfResourceStructure vfResourceStructure = new VfResourceStructure(notificationData, resourceInstance);
+ VfResourceStructure vfResourceStructure = new VfResourceStructure(notificationData, resourceInstance);
- // Create module structure now
+ // Create module structure now
- String vfModuleModelName = "Module Model XYZ";
+ String vfModuleModelName = "Module Model XYZ";
- UUID generatedUUIDForModule = UUID.randomUUID();
+ UUID generatedUUIDForModule = UUID.randomUUID();
- IVfModuleData moduleMetadata = Mockito.mock(IVfModuleData.class);
- Mockito.when(moduleMetadata.getVfModuleModelName()).thenReturn(vfModuleModelName);
- Mockito.when(moduleMetadata.getVfModuleModelInvariantUUID()).thenReturn(generatedUUIDForModule.toString());
- Mockito.when(moduleMetadata.getArtifacts()).thenReturn(Collections.<String> emptyList());
+ IVfModuleData moduleMetadata = Mockito.mock(IVfModuleData.class);
+ Mockito.when(moduleMetadata.getVfModuleModelName()).thenReturn(vfModuleModelName);
+ Mockito.when(moduleMetadata.getVfModuleModelInvariantUUID()).thenReturn(generatedUUIDForModule.toString());
+ Mockito.when(moduleMetadata.getArtifacts()).thenReturn(Collections.<String>emptyList());
- VfModuleStructure vfModuleStructure = new VfModuleStructure(vfResourceStructure, moduleMetadata);
+ VfModuleStructure vfModuleStructure = new VfModuleStructure(vfResourceStructure, moduleMetadata);
- ASDCElementInfo elementInfoFromVfModule = ASDCElementInfo.createElementFromVfModuleStructure(vfModuleStructure);
+ ASDCElementInfo elementInfoFromVfModule = ASDCElementInfo.createElementFromVfModuleStructure(vfModuleStructure);
- assertTrue(elementInfoFromVfModule.toString().contains(vfModuleModelName));
- assertTrue(elementInfoFromVfModule.toString().contains(generatedUUIDForModule.toString()));
+ assertTrue(elementInfoFromVfModule.toString().contains(vfModuleModelName));
+ assertTrue(elementInfoFromVfModule.toString().contains(generatedUUIDForModule.toString()));
- assertFalse(ASDCElementInfo.ASDCElementTypeEnum.VNF_RESOURCE.name().equals(elementInfoFromVfModule.getType()));
- assertEquals(ASDCConfiguration.VF_MODULES_METADATA, elementInfoFromVfModule.getType());
+ assertFalse(ASDCElementInfo.ASDCElementTypeEnum.VNF_RESOURCE.name().equals(elementInfoFromVfModule.getType()));
+ assertEquals(ASDCConfiguration.VF_MODULES_METADATA, elementInfoFromVfModule.getType());
- assertFalse(elementInfoFromVfModule.toString().contains("MyInfo2: someValue"));
- elementInfoFromVfModule.addElementInfo("MyInfo2", "someValue");
- assertTrue(elementInfoFromVfModule.toString().contains("MyInfo2: someValue"));
- }
+ assertFalse(elementInfoFromVfModule.toString().contains("MyInfo2: someValue"));
+ elementInfoFromVfModule.addElementInfo("MyInfo2", "someValue");
+ assertTrue(elementInfoFromVfModule.toString().contains("MyInfo2: someValue"));
+ }
- @Test
- public void createASDCElementInfoFromArtifact() {
- for (String eVal : ASDCConfiguration.SUPPORTED_ARTIFACT_TYPES_LIST) {
- String generatedArtifactName = eVal + " 1";
- UUID generatedUUIDForArtifact = UUID.randomUUID();
+ @Test
+ public void createASDCElementInfoFromArtifact() {
+ for (String eVal : ASDCConfiguration.SUPPORTED_ARTIFACT_TYPES_LIST) {
+ String generatedArtifactName = eVal + " 1";
+ UUID generatedUUIDForArtifact = UUID.randomUUID();
- IArtifactInfo artifactInfo = Mockito.mock(IArtifactInfo.class);
- Mockito.when(artifactInfo.getArtifactType()).thenReturn(eVal);
- Mockito.when(artifactInfo.getArtifactName()).thenReturn(generatedArtifactName);
- Mockito.when(artifactInfo.getArtifactUUID()).thenReturn(generatedUUIDForArtifact.toString());
+ IArtifactInfo artifactInfo = Mockito.mock(IArtifactInfo.class);
+ Mockito.when(artifactInfo.getArtifactType()).thenReturn(eVal);
+ Mockito.when(artifactInfo.getArtifactName()).thenReturn(generatedArtifactName);
+ Mockito.when(artifactInfo.getArtifactUUID()).thenReturn(generatedUUIDForArtifact.toString());
- ASDCElementInfo elementInfoFromArtifact = ASDCElementInfo.createElementFromVfArtifactInfo(artifactInfo);
+ ASDCElementInfo elementInfoFromArtifact = ASDCElementInfo.createElementFromVfArtifactInfo(artifactInfo);
- assertTrue(elementInfoFromArtifact.toString().contains(generatedArtifactName));
- assertTrue(elementInfoFromArtifact.toString().contains(generatedUUIDForArtifact.toString()));
+ assertTrue(elementInfoFromArtifact.toString().contains(generatedArtifactName));
+ assertTrue(elementInfoFromArtifact.toString().contains(generatedUUIDForArtifact.toString()));
- assertFalse(ASDCElementInfo.ASDCElementTypeEnum.VNF_RESOURCE.name().equals(elementInfoFromArtifact.getType()));
- assertEquals(eVal, elementInfoFromArtifact.getType());
+ assertFalse(
+ ASDCElementInfo.ASDCElementTypeEnum.VNF_RESOURCE.name().equals(elementInfoFromArtifact.getType()));
+ assertEquals(eVal, elementInfoFromArtifact.getType());
- assertFalse(elementInfoFromArtifact.toString().contains("MyInfo3: someValue"));
- elementInfoFromArtifact.addElementInfo("MyInfo3", "someValue");
- assertTrue(elementInfoFromArtifact.toString().contains("MyInfo3: someValue"));
- }
- }
+ assertFalse(elementInfoFromArtifact.toString().contains("MyInfo3: someValue"));
+ elementInfoFromArtifact.addElementInfo("MyInfo3", "someValue");
+ assertTrue(elementInfoFromArtifact.toString().contains("MyInfo3: someValue"));
+ }
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCStatusCallBackTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCStatusCallBackTest.java
index ba95a6ea24..24b1736fad 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCStatusCallBackTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCStatusCallBackTest.java
@@ -27,7 +27,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -41,51 +40,52 @@ import org.onap.so.asdc.client.test.emulators.JsonStatusData;
import org.springframework.beans.factory.annotation.Autowired;
public class ASDCStatusCallBackTest extends BaseTest {
- @Autowired
- private ASDCStatusCallBack statusCallback;
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Before
- public void before() {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void activateCallbackTest() throws Exception {
- JsonStatusData statusData = new JsonStatusData();
-
- doNothing().when(toscaInstaller).installTheComponentStatus(isA(JsonStatusData.class));
-
- statusCallback.activateCallback(statusData);
-
- verify(toscaInstaller, times(1)).installTheComponentStatus(statusData);
- }
-
- @Test
- public void activateCallbackDoneErrorStatusTest() throws Exception {
- IStatusData statusData = mock(IStatusData.class);
-
- doReturn("distributionId").when(statusData).getDistributionID();
- doReturn("componentName").when(statusData).getComponentName();
- doReturn(DistributionStatusEnum.COMPONENT_DONE_ERROR).when(statusData).getStatus();
- doNothing().when(toscaInstaller).installTheComponentStatus(isA(IStatusData.class));
-
- statusCallback.activateCallback(statusData);
-
- verify(toscaInstaller, times(1)).installTheComponentStatus(statusData);
- }
-
- @Test
- public void activateCallbackExceptionTest() throws Exception {
- IStatusData statusData = mock(IStatusData.class);
-
- doReturn("distributionId").when(statusData).getDistributionID();
- doReturn("componentName").when(statusData).getComponentName();
- doReturn(DistributionStatusEnum.COMPONENT_DONE_OK).when(statusData).getStatus();
- doThrow(ArtifactInstallerException.class).when(toscaInstaller).installTheComponentStatus(isA(IStatusData.class));
-
- statusCallback.activateCallback(statusData);
- }
+ @Autowired
+ private ASDCStatusCallBack statusCallback;
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Before
+ public void before() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void activateCallbackTest() throws Exception {
+ JsonStatusData statusData = new JsonStatusData();
+
+ doNothing().when(toscaInstaller).installTheComponentStatus(isA(JsonStatusData.class));
+
+ statusCallback.activateCallback(statusData);
+
+ verify(toscaInstaller, times(1)).installTheComponentStatus(statusData);
+ }
+
+ @Test
+ public void activateCallbackDoneErrorStatusTest() throws Exception {
+ IStatusData statusData = mock(IStatusData.class);
+
+ doReturn("distributionId").when(statusData).getDistributionID();
+ doReturn("componentName").when(statusData).getComponentName();
+ doReturn(DistributionStatusEnum.COMPONENT_DONE_ERROR).when(statusData).getStatus();
+ doNothing().when(toscaInstaller).installTheComponentStatus(isA(IStatusData.class));
+
+ statusCallback.activateCallback(statusData);
+
+ verify(toscaInstaller, times(1)).installTheComponentStatus(statusData);
+ }
+
+ @Test
+ public void activateCallbackExceptionTest() throws Exception {
+ IStatusData statusData = mock(IStatusData.class);
+
+ doReturn("distributionId").when(statusData).getDistributionID();
+ doReturn("componentName").when(statusData).getComponentName();
+ doReturn(DistributionStatusEnum.COMPONENT_DONE_OK).when(statusData).getStatus();
+ doThrow(ArtifactInstallerException.class).when(toscaInstaller)
+ .installTheComponentStatus(isA(IStatusData.class));
+
+ statusCallback.activateCallback(statusData);
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/BigDecimalVersionTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/BigDecimalVersionTest.java
index 4eb9ed5619..090f2e8968 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/BigDecimalVersionTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/BigDecimalVersionTest.java
@@ -24,30 +24,29 @@ package org.onap.so.asdc.client;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import org.junit.Test;
-
import org.onap.so.asdc.installer.BigDecimalVersion;
public class BigDecimalVersionTest {
@Test
- public final void versionCastTest () {
+ public final void versionCastTest() {
- BigDecimal versionDecimal = BigDecimalVersion.castAndCheckNotificationVersion("12.0");
- assertTrue(versionDecimal.equals(new BigDecimal("12.0")));
- assertTrue("12.0".equals(BigDecimalVersion.castAndCheckNotificationVersionToString("12.0")));
+ BigDecimal versionDecimal = BigDecimalVersion.castAndCheckNotificationVersion("12.0");
+ assertTrue(versionDecimal.equals(new BigDecimal("12.0")));
+ assertTrue("12.0".equals(BigDecimalVersion.castAndCheckNotificationVersionToString("12.0")));
- versionDecimal = BigDecimalVersion.castAndCheckNotificationVersion("12.0.2");
- assertTrue(versionDecimal.equals(new BigDecimal("12.02")));
- assertTrue("12.02".equals(BigDecimalVersion.castAndCheckNotificationVersionToString("12.0.2")));
+ versionDecimal = BigDecimalVersion.castAndCheckNotificationVersion("12.0.2");
+ assertTrue(versionDecimal.equals(new BigDecimal("12.02")));
+ assertTrue("12.02".equals(BigDecimalVersion.castAndCheckNotificationVersionToString("12.0.2")));
- versionDecimal = BigDecimalVersion.castAndCheckNotificationVersion("10");
- assertTrue(versionDecimal.equals(new BigDecimal("10")));
- assertTrue("10".equals(BigDecimalVersion.castAndCheckNotificationVersionToString("10")));
+ versionDecimal = BigDecimalVersion.castAndCheckNotificationVersion("10");
+ assertTrue(versionDecimal.equals(new BigDecimal("10")));
+ assertTrue("10".equals(BigDecimalVersion.castAndCheckNotificationVersionToString("10")));
- versionDecimal = BigDecimalVersion.castAndCheckNotificationVersion("10.1.2.6");
- assertTrue(versionDecimal.equals(new BigDecimal("10.126")));
- assertTrue("10.126".equals(BigDecimalVersion.castAndCheckNotificationVersionToString("10.1.2.6")));
+ versionDecimal = BigDecimalVersion.castAndCheckNotificationVersion("10.1.2.6");
+ assertTrue(versionDecimal.equals(new BigDecimal("10.126")));
+ assertTrue("10.126".equals(BigDecimalVersion.castAndCheckNotificationVersionToString("10.1.2.6")));
}
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/DistributionStatusMessageTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/DistributionStatusMessageTest.java
index 0c6476ddef..9c8929b76a 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/DistributionStatusMessageTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/DistributionStatusMessageTest.java
@@ -21,25 +21,24 @@
package org.onap.so.asdc.client;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.sdc.utils.DistributionStatusEnum;
public class DistributionStatusMessageTest {
-
- @Test
- public void distributionStatusMessageTest() {
- String artifactUrl = "artifactUrl";
- String consumerId = "consumerId";
- String distributionId = "distributionId";
- Long timestamp = 123L;
- DistributionStatusMessage distributionStatusMessage = new DistributionStatusMessage(
- artifactUrl, consumerId, distributionId, DistributionStatusEnum.DEPLOY_OK, timestamp);
-
- assertEquals(artifactUrl, distributionStatusMessage.getArtifactURL());
- assertEquals(consumerId, distributionStatusMessage.getConsumerID());
- assertEquals(distributionId, distributionStatusMessage.getDistributionID());
- assertEquals(DistributionStatusEnum.DEPLOY_OK, distributionStatusMessage.getStatus());
- assertEquals(123L, distributionStatusMessage.getTimestamp());
- }
+
+ @Test
+ public void distributionStatusMessageTest() {
+ String artifactUrl = "artifactUrl";
+ String consumerId = "consumerId";
+ String distributionId = "distributionId";
+ Long timestamp = 123L;
+ DistributionStatusMessage distributionStatusMessage = new DistributionStatusMessage(artifactUrl, consumerId,
+ distributionId, DistributionStatusEnum.DEPLOY_OK, timestamp);
+
+ assertEquals(artifactUrl, distributionStatusMessage.getArtifactURL());
+ assertEquals(consumerId, distributionStatusMessage.getConsumerID());
+ assertEquals(distributionId, distributionStatusMessage.getDistributionID());
+ assertEquals(DistributionStatusEnum.DEPLOY_OK, distributionStatusMessage.getStatus());
+ assertEquals(123L, distributionStatusMessage.getTimestamp());
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/YamlTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/YamlTest.java
index ed761c7f4d..d7316e57bd 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/YamlTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/YamlTest.java
@@ -22,7 +22,6 @@ package org.onap.so.asdc.client;
import static org.junit.Assert.*;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
@@ -36,118 +35,123 @@ import org.onap.so.db.catalog.beans.HeatTemplateParam;
public class YamlTest {
- @Test
- public void getYamlResourceTypeTestList() throws Exception {
-
- InputStream input = new FileInputStream(new File("src/test/resources/resource-examples/simpleTest.yaml"));
- YamlEditor decoder = new YamlEditor (IOUtils.toByteArray(input));
- List<String> typeList = decoder.getYamlNestedFileResourceTypeList();
-
- assertTrue(typeList.size() == 1 && typeList.get(0).equals("file:///my_test.yaml"));
- }
-
- @Test
- public void getParameterListTest() throws Exception {
-
- InputStream input = new FileInputStream(new File("src/test/resources/resource-examples/simpleTest.yaml"));
- YamlEditor decoder = new YamlEditor (IOUtils.toByteArray(input));
- Set <HeatTemplateParam> paramSet = decoder.getParameterList("123456");
-
- assertTrue(paramSet.size() == 5);
-
- for (HeatTemplateParam param : paramSet) {
- if ("ip_port_snmp_manager".equals(param.getParamName()) || "cor_direct_net_name".equals(param.getParamName()) || "cor_direct_net_RT".equals(param.getParamName())) {
-
- assertTrue(param.isRequired()==false);
- } else {
-
- assertTrue(param.isRequired()==true);
- }
-
- assertTrue("string".equals(param.getParamType()));
- }
- }
-
- @Test
- public void addParameterListWhenEmptyTest() throws Exception {
-
- InputStream input = new FileInputStream(new File("src/test/resources/resource-examples/simpleTestWithoutParam.yaml"));
- YamlEditor decoder = new YamlEditor (IOUtils.toByteArray(input));
-
- Set <HeatTemplateParam> newParamSet = new HashSet<>();
-
- HeatTemplateParam heatParam1 = new HeatTemplateParam();
- heatParam1.setHeatTemplateArtifactUuid("1");
- heatParam1.setParamName("testos1");
- heatParam1.setParamType("string");
-
- HeatTemplateParam heatParam2 = new HeatTemplateParam();
- heatParam2.setHeatTemplateArtifactUuid("2");
- heatParam2.setParamName("testos2");
- heatParam2.setParamType("number");
-
- newParamSet.add(heatParam1);
- newParamSet.add(heatParam2);
-
- decoder.addParameterList(newParamSet);
-
- Set <HeatTemplateParam> paramSet = decoder.getParameterList("123456");
- assertTrue(paramSet.size() == 2);
-
- assertTrue(decoder.encode().contains("testos1"));
- assertTrue(decoder.encode().contains("string"));
- assertTrue(decoder.encode().contains("testos2"));
- assertTrue(decoder.encode().contains("number"));
- }
-
- @Test
- public void addParameterListTest() throws Exception {
-
- InputStream input = new FileInputStream(new File("src/test/resources/resource-examples/simpleTest.yaml"));
- YamlEditor decoder = new YamlEditor (IOUtils.toByteArray(input));
-
- Set <HeatTemplateParam> newParamSet = new HashSet<>();
-
- HeatTemplateParam heatParam1 = new HeatTemplateParam();
- heatParam1.setHeatTemplateArtifactUuid("1");
- heatParam1.setParamName("testos1");
- heatParam1.setParamType("string");
-
- HeatTemplateParam heatParam2 = new HeatTemplateParam();
- heatParam2.setHeatTemplateArtifactUuid("2");
- heatParam2.setParamName("testos2");
- heatParam2.setParamType("number");
-
- newParamSet.add(heatParam1);
- newParamSet.add(heatParam2);
-
- decoder.addParameterList(newParamSet);
-
- Set <HeatTemplateParam> paramSet = decoder.getParameterList("123456");
-
- assertTrue(paramSet.size() == 7);
-
- Boolean check1 = Boolean.FALSE;
- Boolean check2 = Boolean.FALSE;
-
- for (HeatTemplateParam param : paramSet) {
- if ("ip_port_snmp_manager".equals(param.getParamName()) || "cor_direct_net_name".equals(param.getParamName()) || "cor_direct_net_RT".equals(param.getParamName())) {
- assertFalse(param.isRequired());
- } else {
- assertTrue(param.isRequired());
- }
-
- if ("testos1".equals(param.getParamName()) && "string".equals(param.getParamType())) {
- check1=Boolean.TRUE;
- }
-
- if ("testos2".equals(param.getParamName()) && "number".equals(param.getParamType())) {
- check2=Boolean.TRUE;
- }
-
- }
-
- assertTrue(check1);
- assertTrue(check2);
- }
+ @Test
+ public void getYamlResourceTypeTestList() throws Exception {
+
+ InputStream input = new FileInputStream(new File("src/test/resources/resource-examples/simpleTest.yaml"));
+ YamlEditor decoder = new YamlEditor(IOUtils.toByteArray(input));
+ List<String> typeList = decoder.getYamlNestedFileResourceTypeList();
+
+ assertTrue(typeList.size() == 1 && typeList.get(0).equals("file:///my_test.yaml"));
+ }
+
+ @Test
+ public void getParameterListTest() throws Exception {
+
+ InputStream input = new FileInputStream(new File("src/test/resources/resource-examples/simpleTest.yaml"));
+ YamlEditor decoder = new YamlEditor(IOUtils.toByteArray(input));
+ Set<HeatTemplateParam> paramSet = decoder.getParameterList("123456");
+
+ assertTrue(paramSet.size() == 5);
+
+ for (HeatTemplateParam param : paramSet) {
+ if ("ip_port_snmp_manager".equals(param.getParamName())
+ || "cor_direct_net_name".equals(param.getParamName())
+ || "cor_direct_net_RT".equals(param.getParamName())) {
+
+ assertTrue(param.isRequired() == false);
+ } else {
+
+ assertTrue(param.isRequired() == true);
+ }
+
+ assertTrue("string".equals(param.getParamType()));
+ }
+ }
+
+ @Test
+ public void addParameterListWhenEmptyTest() throws Exception {
+
+ InputStream input =
+ new FileInputStream(new File("src/test/resources/resource-examples/simpleTestWithoutParam.yaml"));
+ YamlEditor decoder = new YamlEditor(IOUtils.toByteArray(input));
+
+ Set<HeatTemplateParam> newParamSet = new HashSet<>();
+
+ HeatTemplateParam heatParam1 = new HeatTemplateParam();
+ heatParam1.setHeatTemplateArtifactUuid("1");
+ heatParam1.setParamName("testos1");
+ heatParam1.setParamType("string");
+
+ HeatTemplateParam heatParam2 = new HeatTemplateParam();
+ heatParam2.setHeatTemplateArtifactUuid("2");
+ heatParam2.setParamName("testos2");
+ heatParam2.setParamType("number");
+
+ newParamSet.add(heatParam1);
+ newParamSet.add(heatParam2);
+
+ decoder.addParameterList(newParamSet);
+
+ Set<HeatTemplateParam> paramSet = decoder.getParameterList("123456");
+ assertTrue(paramSet.size() == 2);
+
+ assertTrue(decoder.encode().contains("testos1"));
+ assertTrue(decoder.encode().contains("string"));
+ assertTrue(decoder.encode().contains("testos2"));
+ assertTrue(decoder.encode().contains("number"));
+ }
+
+ @Test
+ public void addParameterListTest() throws Exception {
+
+ InputStream input = new FileInputStream(new File("src/test/resources/resource-examples/simpleTest.yaml"));
+ YamlEditor decoder = new YamlEditor(IOUtils.toByteArray(input));
+
+ Set<HeatTemplateParam> newParamSet = new HashSet<>();
+
+ HeatTemplateParam heatParam1 = new HeatTemplateParam();
+ heatParam1.setHeatTemplateArtifactUuid("1");
+ heatParam1.setParamName("testos1");
+ heatParam1.setParamType("string");
+
+ HeatTemplateParam heatParam2 = new HeatTemplateParam();
+ heatParam2.setHeatTemplateArtifactUuid("2");
+ heatParam2.setParamName("testos2");
+ heatParam2.setParamType("number");
+
+ newParamSet.add(heatParam1);
+ newParamSet.add(heatParam2);
+
+ decoder.addParameterList(newParamSet);
+
+ Set<HeatTemplateParam> paramSet = decoder.getParameterList("123456");
+
+ assertTrue(paramSet.size() == 7);
+
+ Boolean check1 = Boolean.FALSE;
+ Boolean check2 = Boolean.FALSE;
+
+ for (HeatTemplateParam param : paramSet) {
+ if ("ip_port_snmp_manager".equals(param.getParamName())
+ || "cor_direct_net_name".equals(param.getParamName())
+ || "cor_direct_net_RT".equals(param.getParamName())) {
+ assertFalse(param.isRequired());
+ } else {
+ assertTrue(param.isRequired());
+ }
+
+ if ("testos1".equals(param.getParamName()) && "string".equals(param.getParamType())) {
+ check1 = Boolean.TRUE;
+ }
+
+ if ("testos2".equals(param.getParamName()) && "number".equals(param.getParamType())) {
+ check2 = Boolean.TRUE;
+ }
+
+ }
+
+ assertTrue(check1);
+ assertTrue(check2);
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCControllerExceptionTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCControllerExceptionTest.java
index e2aee6080e..927779c485 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCControllerExceptionTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCControllerExceptionTest.java
@@ -22,29 +22,28 @@ package org.onap.so.asdc.client.exceptions;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
-
import org.junit.Test;
public class ASDCControllerExceptionTest {
- private String exceptionMessage = "test message for exception";
- private String throwableMessage = "separate throwable that caused asdcDownloadException";
-
- @Test
- public void asdcParametersExceptionTest() {
- ASDCControllerException asdcDownloadException = new ASDCControllerException(exceptionMessage);
-
- Exception expectedException = new Exception(exceptionMessage);
-
- assertThat(asdcDownloadException, sameBeanAs(expectedException));
- }
-
- @Test
- public void asdcParametersExceptionThrowableTest() {
- Throwable throwableCause = new Throwable(throwableMessage);
- ASDCControllerException asdcDownloadException = new ASDCControllerException(exceptionMessage, throwableCause);
-
- Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage));
-
- assertThat(asdcDownloadException, sameBeanAs(expectedException));
- }
+ private String exceptionMessage = "test message for exception";
+ private String throwableMessage = "separate throwable that caused asdcDownloadException";
+
+ @Test
+ public void asdcParametersExceptionTest() {
+ ASDCControllerException asdcDownloadException = new ASDCControllerException(exceptionMessage);
+
+ Exception expectedException = new Exception(exceptionMessage);
+
+ assertThat(asdcDownloadException, sameBeanAs(expectedException));
+ }
+
+ @Test
+ public void asdcParametersExceptionThrowableTest() {
+ Throwable throwableCause = new Throwable(throwableMessage);
+ ASDCControllerException asdcDownloadException = new ASDCControllerException(exceptionMessage, throwableCause);
+
+ Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage));
+
+ assertThat(asdcDownloadException, sameBeanAs(expectedException));
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCDownloadExceptionTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCDownloadExceptionTest.java
index 98deb52a08..b022ed91d7 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCDownloadExceptionTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCDownloadExceptionTest.java
@@ -22,29 +22,28 @@ package org.onap.so.asdc.client.exceptions;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
-
import org.junit.Test;
public class ASDCDownloadExceptionTest {
- private String exceptionMessage = "test message for exception";
- private String throwableMessage = "separate throwable that caused asdcDownloadException";
-
- @Test
- public void asdcDownloadExceptionTest() {
- ASDCDownloadException asdcDownloadException = new ASDCDownloadException(exceptionMessage);
-
- Exception expectedException = new Exception(exceptionMessage);
-
- assertThat(asdcDownloadException, sameBeanAs(expectedException));
- }
-
- @Test
- public void asdcDownloadExceptionThrowableTest() {
- Throwable throwableCause = new Throwable(throwableMessage);
- ASDCDownloadException asdcDownloadException = new ASDCDownloadException(exceptionMessage, throwableCause);
-
- Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage));
-
- assertThat(asdcDownloadException, sameBeanAs(expectedException));
- }
+ private String exceptionMessage = "test message for exception";
+ private String throwableMessage = "separate throwable that caused asdcDownloadException";
+
+ @Test
+ public void asdcDownloadExceptionTest() {
+ ASDCDownloadException asdcDownloadException = new ASDCDownloadException(exceptionMessage);
+
+ Exception expectedException = new Exception(exceptionMessage);
+
+ assertThat(asdcDownloadException, sameBeanAs(expectedException));
+ }
+
+ @Test
+ public void asdcDownloadExceptionThrowableTest() {
+ Throwable throwableCause = new Throwable(throwableMessage);
+ ASDCDownloadException asdcDownloadException = new ASDCDownloadException(exceptionMessage, throwableCause);
+
+ Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage));
+
+ assertThat(asdcDownloadException, sameBeanAs(expectedException));
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCParametersExceptionTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCParametersExceptionTest.java
index bac05bd47c..2b4a0c956e 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCParametersExceptionTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ASDCParametersExceptionTest.java
@@ -22,29 +22,28 @@ package org.onap.so.asdc.client.exceptions;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
-
import org.junit.Test;
public class ASDCParametersExceptionTest {
- private String exceptionMessage = "test message for exception";
- private String throwableMessage = "separate throwable that caused asdcDownloadException";
-
- @Test
- public void asdcParametersExceptionTest() {
- ASDCParametersException asdcDownloadException = new ASDCParametersException(exceptionMessage);
-
- Exception expectedException = new Exception(exceptionMessage);
-
- assertThat(asdcDownloadException, sameBeanAs(expectedException));
- }
-
- @Test
- public void asdcParametersExceptionThrowableTest() {
- Throwable throwableCause = new Throwable(throwableMessage);
- ASDCParametersException asdcDownloadException = new ASDCParametersException(exceptionMessage, throwableCause);
-
- Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage));
-
- assertThat(asdcDownloadException, sameBeanAs(expectedException));
- }
+ private String exceptionMessage = "test message for exception";
+ private String throwableMessage = "separate throwable that caused asdcDownloadException";
+
+ @Test
+ public void asdcParametersExceptionTest() {
+ ASDCParametersException asdcDownloadException = new ASDCParametersException(exceptionMessage);
+
+ Exception expectedException = new Exception(exceptionMessage);
+
+ assertThat(asdcDownloadException, sameBeanAs(expectedException));
+ }
+
+ @Test
+ public void asdcParametersExceptionThrowableTest() {
+ Throwable throwableCause = new Throwable(throwableMessage);
+ ASDCParametersException asdcDownloadException = new ASDCParametersException(exceptionMessage, throwableCause);
+
+ Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage));
+
+ assertThat(asdcDownloadException, sameBeanAs(expectedException));
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerExceptionTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerExceptionTest.java
index f2227908f5..3e0dd27d07 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerExceptionTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/exceptions/ArtifactInstallerExceptionTest.java
@@ -22,29 +22,29 @@ package org.onap.so.asdc.client.exceptions;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
-
import org.junit.Test;
public class ArtifactInstallerExceptionTest {
- private String exceptionMessage = "test message for exception";
- private String throwableMessage = "separate throwable that caused asdcDownloadException";
-
- @Test
- public void asdcParametersExceptionTest() {
- ArtifactInstallerException asdcDownloadException = new ArtifactInstallerException(exceptionMessage);
-
- Exception expectedException = new Exception(exceptionMessage);
-
- assertThat(asdcDownloadException, sameBeanAs(expectedException));
- }
-
- @Test
- public void asdcParametersExceptionThrowableTest() {
- Throwable throwableCause = new Throwable(throwableMessage);
- ArtifactInstallerException asdcDownloadException = new ArtifactInstallerException(exceptionMessage, throwableCause);
-
- Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage));
-
- assertThat(asdcDownloadException, sameBeanAs(expectedException));
- }
+ private String exceptionMessage = "test message for exception";
+ private String throwableMessage = "separate throwable that caused asdcDownloadException";
+
+ @Test
+ public void asdcParametersExceptionTest() {
+ ArtifactInstallerException asdcDownloadException = new ArtifactInstallerException(exceptionMessage);
+
+ Exception expectedException = new Exception(exceptionMessage);
+
+ assertThat(asdcDownloadException, sameBeanAs(expectedException));
+ }
+
+ @Test
+ public void asdcParametersExceptionThrowableTest() {
+ Throwable throwableCause = new Throwable(throwableMessage);
+ ArtifactInstallerException asdcDownloadException =
+ new ArtifactInstallerException(exceptionMessage, throwableCause);
+
+ Exception expectedException = new Exception(exceptionMessage, new Throwable(throwableMessage));
+
+ assertThat(asdcDownloadException, sameBeanAs(expectedException));
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImplTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImplTest.java
index 3dc323559d..69d3fd103d 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImplTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ArtifactInfoImplTest.java
@@ -22,28 +22,26 @@ package org.onap.so.asdc.client.test.emulators;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
import org.mockito.Mock;
import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.so.asdc.BaseTest;
-public class ArtifactInfoImplTest extends BaseTest {
- @Mock
- private IArtifactInfo iArtifactInfo;
-
- @Test
- public void convertToArtifactInfoImplTest() {
- List<IArtifactInfo> list = new ArrayList<IArtifactInfo>();
- list.add(iArtifactInfo);
- assertEquals(1, ArtifactInfoImpl.convertToArtifactInfoImpl(list).size());
- }
-
- @Test
- public void convertToArtifactInfoImplNullListTest() {
- assertTrue(ArtifactInfoImpl.convertToArtifactInfoImpl(null).isEmpty());
- }
+public class ArtifactInfoImplTest extends BaseTest {
+ @Mock
+ private IArtifactInfo iArtifactInfo;
+
+ @Test
+ public void convertToArtifactInfoImplTest() {
+ List<IArtifactInfo> list = new ArrayList<IArtifactInfo>();
+ list.add(iArtifactInfo);
+ assertEquals(1, ArtifactInfoImpl.convertToArtifactInfoImpl(list).size());
+ }
+
+ @Test
+ public void convertToArtifactInfoImplNullListTest() {
+ assertTrue(ArtifactInfoImpl.convertToArtifactInfoImpl(null).isEmpty());
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulatorTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulatorTest.java
index 38c2564241..cfbf7724cc 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulatorTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/DistributionClientEmulatorTest.java
@@ -21,13 +21,11 @@
package org.onap.so.asdc.client.test.emulators;
import static org.junit.Assert.assertEquals;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.sdc.api.consumer.IDistributionStatusMessage;
@@ -43,136 +41,156 @@ import org.onap.so.asdc.client.ASDCStatusCallBack;
import org.onap.so.asdc.client.DistributionStatusMessage;
public class DistributionClientEmulatorTest {
-
- private DistributionClientEmulator distClientEmulator;
-
- @Before
- public void before() {
- distClientEmulator = new DistributionClientEmulator();
- }
-
- @Test
- public void getDistributionMessageReceived() {
- List<IDistributionStatusMessage> receivedMessages = distClientEmulator.getDistributionMessageReceived();
- assertEquals(new LinkedList<>(), receivedMessages);
-
- IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId", "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456);
- distClientEmulator.sendDeploymentStatus(message);
- assertEquals(message, receivedMessages.get(0));
-
- IDistributionStatusMessage message2 = new DistributionStatusMessage("testArtifactUrl2", "testConsumerId2", "testDistributionId2", DistributionStatusEnum.DOWNLOAD_OK, 1234567);
- distClientEmulator.sendDeploymentStatus(message2);
- assertEquals(message2, receivedMessages.get(1));
- }
-
- @Test
- public void sendDeploymentStatusPrimary() {
- IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId", "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456);
- IDistributionClientResult result = distClientEmulator.sendDeploymentStatus(message);
- IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- assertEquals(message, distClientEmulator.getDistributionMessageReceived().get(0));
- assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
- assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
- }
-
- @Test
- public void sendDeploymentStatusSecondary() {
- IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId", "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456);
- IDistributionClientResult result = distClientEmulator.sendDeploymentStatus(message, "test");
- IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- assertEquals(message, distClientEmulator.getDistributionMessageReceived().get(0));
- assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
- assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
- }
-
- @Test
- public void sendDownloadStatusPrimary() {
- IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId", "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456);
- IDistributionClientResult result = distClientEmulator.sendDownloadStatus(message);
- IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- assertEquals(message, distClientEmulator.getDistributionMessageReceived().get(0));
- assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
- assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
- }
-
- @Test
- public void sendDownloadStatusSecondary() {
- IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId", "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456);
- IDistributionClientResult result = distClientEmulator.sendDownloadStatus(message, "test");
- IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- assertEquals(message, distClientEmulator.getDistributionMessageReceived().get(0));
- assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
- assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
- }
-
- @Test
- public void initPrimary() {
- IDistributionClientResult result = distClientEmulator.init(new ASDCConfiguration(), new ASDCNotificationCallBack());
- IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
- assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
- }
-
- @Test
- public void initSecondary() {
- IDistributionClientResult result = distClientEmulator.init(new ASDCConfiguration(), new ASDCNotificationCallBack(), new ASDCStatusCallBack());
- IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
- assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
- }
-
- @Test
- public void start() {
- IDistributionClientResult result = distClientEmulator.start();
- IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
- assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
- }
-
- @Test
- public void stop() {
- IDistributionClientResult result = distClientEmulator.stop();
- IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
- assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
- }
-
- @Test
- public void updateConfiguration() {
- IDistributionClientResult result = distClientEmulator.updateConfiguration(new ASDCConfiguration());
- IDistributionClientResult expectedResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,DistributionActionResultEnum.SUCCESS.name());
- assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
- assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
- }
-
- @Test
- public void getResourcePath() {
- String testResourcePath = "testResourcePath";
- distClientEmulator = new DistributionClientEmulator(testResourcePath);
- assertEquals(testResourcePath, distClientEmulator.getResourcePath());
- }
-
- @Test
- public void setResourcePath() {
- String testResourcePath = "testResourcePath";
- distClientEmulator.setResourcePath(testResourcePath);
- assertEquals(testResourcePath, distClientEmulator.getResourcePath());
- }
-
- @Test
- public void downloadSuccess() throws IOException {
- ArtifactInfoImpl info = new ArtifactInfoImpl();
- info.setArtifactURL("mso.json");
- info.setArtifactName("testArtifactName");
-
- distClientEmulator.setResourcePath("src/test/resources/");
-
- IDistributionClientDownloadResult result = distClientEmulator.download(info);
-
- byte[] expectedInputStream = Files.readAllBytes(Paths.get(distClientEmulator.getResourcePath() + info.getArtifactURL()));
- IDistributionClientDownloadResult expectedResult = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name(), info.getArtifactName(), expectedInputStream);
-
- assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
- assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
- }
+
+ private DistributionClientEmulator distClientEmulator;
+
+ @Before
+ public void before() {
+ distClientEmulator = new DistributionClientEmulator();
+ }
+
+ @Test
+ public void getDistributionMessageReceived() {
+ List<IDistributionStatusMessage> receivedMessages = distClientEmulator.getDistributionMessageReceived();
+ assertEquals(new LinkedList<>(), receivedMessages);
+
+ IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId",
+ "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456);
+ distClientEmulator.sendDeploymentStatus(message);
+ assertEquals(message, receivedMessages.get(0));
+
+ IDistributionStatusMessage message2 = new DistributionStatusMessage("testArtifactUrl2", "testConsumerId2",
+ "testDistributionId2", DistributionStatusEnum.DOWNLOAD_OK, 1234567);
+ distClientEmulator.sendDeploymentStatus(message2);
+ assertEquals(message2, receivedMessages.get(1));
+ }
+
+ @Test
+ public void sendDeploymentStatusPrimary() {
+ IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId",
+ "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456);
+ IDistributionClientResult result = distClientEmulator.sendDeploymentStatus(message);
+ IDistributionClientResult expectedResult = new DistributionClientResultImpl(
+ DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name());
+ assertEquals(message, distClientEmulator.getDistributionMessageReceived().get(0));
+ assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
+ assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
+ }
+
+ @Test
+ public void sendDeploymentStatusSecondary() {
+ IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId",
+ "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456);
+ IDistributionClientResult result = distClientEmulator.sendDeploymentStatus(message, "test");
+ IDistributionClientResult expectedResult = new DistributionClientResultImpl(
+ DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name());
+ assertEquals(message, distClientEmulator.getDistributionMessageReceived().get(0));
+ assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
+ assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
+ }
+
+ @Test
+ public void sendDownloadStatusPrimary() {
+ IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId",
+ "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456);
+ IDistributionClientResult result = distClientEmulator.sendDownloadStatus(message);
+ IDistributionClientResult expectedResult = new DistributionClientResultImpl(
+ DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name());
+ assertEquals(message, distClientEmulator.getDistributionMessageReceived().get(0));
+ assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
+ assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
+ }
+
+ @Test
+ public void sendDownloadStatusSecondary() {
+ IDistributionStatusMessage message = new DistributionStatusMessage("testArtifactUrl", "testConsumerId",
+ "testDistributionId", DistributionStatusEnum.DOWNLOAD_OK, 123456);
+ IDistributionClientResult result = distClientEmulator.sendDownloadStatus(message, "test");
+ IDistributionClientResult expectedResult = new DistributionClientResultImpl(
+ DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name());
+ assertEquals(message, distClientEmulator.getDistributionMessageReceived().get(0));
+ assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
+ assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
+ }
+
+ @Test
+ public void initPrimary() {
+ IDistributionClientResult result =
+ distClientEmulator.init(new ASDCConfiguration(), new ASDCNotificationCallBack());
+ IDistributionClientResult expectedResult = new DistributionClientResultImpl(
+ DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name());
+ assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
+ assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
+ }
+
+ @Test
+ public void initSecondary() {
+ IDistributionClientResult result = distClientEmulator.init(new ASDCConfiguration(),
+ new ASDCNotificationCallBack(), new ASDCStatusCallBack());
+ IDistributionClientResult expectedResult = new DistributionClientResultImpl(
+ DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name());
+ assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
+ assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
+ }
+
+ @Test
+ public void start() {
+ IDistributionClientResult result = distClientEmulator.start();
+ IDistributionClientResult expectedResult = new DistributionClientResultImpl(
+ DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name());
+ assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
+ assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
+ }
+
+ @Test
+ public void stop() {
+ IDistributionClientResult result = distClientEmulator.stop();
+ IDistributionClientResult expectedResult = new DistributionClientResultImpl(
+ DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name());
+ assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
+ assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
+ }
+
+ @Test
+ public void updateConfiguration() {
+ IDistributionClientResult result = distClientEmulator.updateConfiguration(new ASDCConfiguration());
+ IDistributionClientResult expectedResult = new DistributionClientResultImpl(
+ DistributionActionResultEnum.SUCCESS, DistributionActionResultEnum.SUCCESS.name());
+ assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
+ assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
+ }
+
+ @Test
+ public void getResourcePath() {
+ String testResourcePath = "testResourcePath";
+ distClientEmulator = new DistributionClientEmulator(testResourcePath);
+ assertEquals(testResourcePath, distClientEmulator.getResourcePath());
+ }
+
+ @Test
+ public void setResourcePath() {
+ String testResourcePath = "testResourcePath";
+ distClientEmulator.setResourcePath(testResourcePath);
+ assertEquals(testResourcePath, distClientEmulator.getResourcePath());
+ }
+
+ @Test
+ public void downloadSuccess() throws IOException {
+ ArtifactInfoImpl info = new ArtifactInfoImpl();
+ info.setArtifactURL("mso.json");
+ info.setArtifactName("testArtifactName");
+
+ distClientEmulator.setResourcePath("src/test/resources/");
+
+ IDistributionClientDownloadResult result = distClientEmulator.download(info);
+
+ byte[] expectedInputStream =
+ Files.readAllBytes(Paths.get(distClientEmulator.getResourcePath() + info.getArtifactURL()));
+ IDistributionClientDownloadResult expectedResult =
+ new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS,
+ DistributionActionResultEnum.SUCCESS.name(), info.getArtifactName(), expectedInputStream);
+
+ assertEquals(expectedResult.getDistributionActionResult(), result.getDistributionActionResult());
+ assertEquals(expectedResult.getDistributionMessageResult(), result.getDistributionMessageResult());
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonStatusDataTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonStatusDataTest.java
index 5e2f1ad828..cf54656271 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonStatusDataTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonStatusDataTest.java
@@ -21,7 +21,6 @@
package org.onap.so.asdc.client.test.emulators;
import org.junit.Test;
-
import static org.junit.Assert.assertEquals;
public class JsonStatusDataTest {
@@ -39,17 +38,16 @@ public class JsonStatusDataTest {
}
@Test
- public void setGetAttributes()
- {
+ public void setGetAttributes() {
JsonStatusData jsonStatusData = new JsonStatusData();
- jsonStatusData.setAttribute("test","test");
+ jsonStatusData.setAttribute("test", "test");
jsonStatusData.getStatus();
jsonStatusData.getTimestamp();
jsonStatusData.getComponentName();
jsonStatusData.getConsumerID();
jsonStatusData.getDistributionID();
String errReason = jsonStatusData.getErrorReason();
- assertEquals(errReason,"MSO FAILURE");
+ assertEquals(errReason, "MSO FAILURE");
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaDataTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaDataTest.java
index 6da3a2c18c..bcef94336b 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaDataTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaDataTest.java
@@ -21,32 +21,30 @@
package org.onap.so.asdc.client.test.emulators;
import static org.junit.Assert.assertEquals;
-
import java.util.HashMap;
-
import org.junit.Test;
public class JsonVfModuleMetaDataTest {
-
- @Test
- public void attributesMapTest() {
- JsonVfModuleMetaData vfModuleMetadata = new JsonVfModuleMetaData();
- vfModuleMetadata.setAttribute("vfModuleModelDescription", "vfModuleModelDescription");
- vfModuleMetadata.setAttribute("vfModuleModelInvariantUUID", "vfModuleModelInvariantUUID");
- vfModuleMetadata.setAttribute("vfModuleModelCustomizationUUID", "vfModuleModelCustomizationUUID");
- vfModuleMetadata.setAttribute("vfModuleModelName", "vfModuleModelName");
- vfModuleMetadata.setAttribute("vfModuleModelUUID", "vfModuleModelUUID");
- vfModuleMetadata.setAttribute("vfModuleModelVersion", "vfModuleModelVersion");
- vfModuleMetadata.setAttribute("isBase", true);
-
- assertEquals("vfModuleModelDescription", vfModuleMetadata.getVfModuleModelDescription());
- assertEquals("vfModuleModelInvariantUUID", vfModuleMetadata.getVfModuleModelInvariantUUID());
- assertEquals("vfModuleModelCustomizationUUID", vfModuleMetadata.getVfModuleModelCustomizationUUID());
- assertEquals("vfModuleModelName", vfModuleMetadata.getVfModuleModelName());
- assertEquals("vfModuleModelUUID", vfModuleMetadata.getVfModuleModelUUID());
- assertEquals("vfModuleModelVersion", vfModuleMetadata.getVfModuleModelVersion());
- assertEquals(true, vfModuleMetadata.isBase());
- assertEquals(null, vfModuleMetadata.getArtifacts());
- assertEquals(new HashMap<String, String>(), vfModuleMetadata.getProperties());
- }
+
+ @Test
+ public void attributesMapTest() {
+ JsonVfModuleMetaData vfModuleMetadata = new JsonVfModuleMetaData();
+ vfModuleMetadata.setAttribute("vfModuleModelDescription", "vfModuleModelDescription");
+ vfModuleMetadata.setAttribute("vfModuleModelInvariantUUID", "vfModuleModelInvariantUUID");
+ vfModuleMetadata.setAttribute("vfModuleModelCustomizationUUID", "vfModuleModelCustomizationUUID");
+ vfModuleMetadata.setAttribute("vfModuleModelName", "vfModuleModelName");
+ vfModuleMetadata.setAttribute("vfModuleModelUUID", "vfModuleModelUUID");
+ vfModuleMetadata.setAttribute("vfModuleModelVersion", "vfModuleModelVersion");
+ vfModuleMetadata.setAttribute("isBase", true);
+
+ assertEquals("vfModuleModelDescription", vfModuleMetadata.getVfModuleModelDescription());
+ assertEquals("vfModuleModelInvariantUUID", vfModuleMetadata.getVfModuleModelInvariantUUID());
+ assertEquals("vfModuleModelCustomizationUUID", vfModuleMetadata.getVfModuleModelCustomizationUUID());
+ assertEquals("vfModuleModelName", vfModuleMetadata.getVfModuleModelName());
+ assertEquals("vfModuleModelUUID", vfModuleMetadata.getVfModuleModelUUID());
+ assertEquals("vfModuleModelVersion", vfModuleMetadata.getVfModuleModelVersion());
+ assertEquals(true, vfModuleMetadata.isBase());
+ assertEquals(null, vfModuleMetadata.getArtifacts());
+ assertEquals(new HashMap<String, String>(), vfModuleMetadata.getProperties());
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/NotificationDataImplTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/NotificationDataImplTest.java
index b1524e015f..94ba54db29 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/NotificationDataImplTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/NotificationDataImplTest.java
@@ -21,39 +21,38 @@
package org.onap.so.asdc.client.test.emulators;
import static org.junit.Assert.assertEquals;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
import org.mockito.Mock;
import org.onap.so.asdc.BaseTest;
import org.springframework.beans.factory.annotation.Autowired;
public class NotificationDataImplTest extends BaseTest {
- @Autowired
- private NotificationDataImpl notificationDataImpl;
-
- @Mock
- private ArtifactInfoImpl artifactInfoImpl;
-
- private static final String NOTIFICATION_DATA_IMPL_STRING = "NotificationDataImpl [distributionID=distributionID, serviceName=serviceName, "
- + "serviceVersion=serviceVersion, serviceUUID=serviceUUID, serviceDescription=serviceDescription, "
- + "serviceInvariantUUID=serviceInvariantUUID, resources=null, serviceArtifacts=[artifactInfoImpl], workloadContext=workloadContext]";
-
- @Test
- public void toStringTest() {
- List<ArtifactInfoImpl> relevantServiceArtifacts = new ArrayList<ArtifactInfoImpl>();
- relevantServiceArtifacts.add(artifactInfoImpl);
- notificationDataImpl.setDistributionID("distributionID");
- notificationDataImpl.setServiceName("serviceName");
- notificationDataImpl.setServiceVersion("serviceVersion");
- notificationDataImpl.setServiceDescription("serviceDescription");
- notificationDataImpl.setServiceUUID("serviceUUID");
- notificationDataImpl.setServiceInvariantUUID("serviceInvariantUUID");
- notificationDataImpl.setWorkloadContext("workloadContext");
- notificationDataImpl.setServiceArtifacts(relevantServiceArtifacts);
-
- assertEquals(NOTIFICATION_DATA_IMPL_STRING, notificationDataImpl.toString());
- }
+ @Autowired
+ private NotificationDataImpl notificationDataImpl;
+
+ @Mock
+ private ArtifactInfoImpl artifactInfoImpl;
+
+ private static final String NOTIFICATION_DATA_IMPL_STRING =
+ "NotificationDataImpl [distributionID=distributionID, serviceName=serviceName, "
+ + "serviceVersion=serviceVersion, serviceUUID=serviceUUID, serviceDescription=serviceDescription, "
+ + "serviceInvariantUUID=serviceInvariantUUID, resources=null, serviceArtifacts=[artifactInfoImpl], workloadContext=workloadContext]";
+
+ @Test
+ public void toStringTest() {
+ List<ArtifactInfoImpl> relevantServiceArtifacts = new ArrayList<ArtifactInfoImpl>();
+ relevantServiceArtifacts.add(artifactInfoImpl);
+ notificationDataImpl.setDistributionID("distributionID");
+ notificationDataImpl.setServiceName("serviceName");
+ notificationDataImpl.setServiceVersion("serviceVersion");
+ notificationDataImpl.setServiceDescription("serviceDescription");
+ notificationDataImpl.setServiceUUID("serviceUUID");
+ notificationDataImpl.setServiceInvariantUUID("serviceInvariantUUID");
+ notificationDataImpl.setWorkloadContext("workloadContext");
+ notificationDataImpl.setServiceArtifacts(relevantServiceArtifacts);
+
+ assertEquals(NOTIFICATION_DATA_IMPL_STRING, notificationDataImpl.toString());
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImplTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImplTest.java
index 423661770b..47662daab7 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImplTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImplTest.java
@@ -22,30 +22,28 @@ package org.onap.so.asdc.client.test.emulators;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
import org.mockito.Mock;
import org.onap.sdc.api.notification.IResourceInstance;
import org.onap.so.asdc.BaseTest;
public class ResourceInfoImplTest extends BaseTest {
- @Mock
- private IResourceInstance iResourceInstance;
-
- @Test
- public void convertToJsonContainerTest() {
- List<IResourceInstance> resources = new ArrayList<IResourceInstance>();
- resources.add(iResourceInstance);
- ResourceInfoImpl.convertToJsonContainer(resources);
-
- assertEquals(1, ResourceInfoImpl.convertToJsonContainer(resources).size());
- }
-
- @Test
- public void convertToJsonContainerNullListTest() {
- assertTrue(ResourceInfoImpl.convertToJsonContainer(null).isEmpty());
- }
+ @Mock
+ private IResourceInstance iResourceInstance;
+
+ @Test
+ public void convertToJsonContainerTest() {
+ List<IResourceInstance> resources = new ArrayList<IResourceInstance>();
+ resources.add(iResourceInstance);
+ ResourceInfoImpl.convertToJsonContainer(resources);
+
+ assertEquals(1, ResourceInfoImpl.convertToJsonContainer(resources).size());
+ }
+
+ @Test
+ public void convertToJsonContainerNullListTest() {
+ assertTrue(ResourceInfoImpl.convertToJsonContainer(null).isEmpty());
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/ASDCRestInterfaceTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/ASDCRestInterfaceTest.java
index 947da4f492..815f419c40 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/ASDCRestInterfaceTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/ASDCRestInterfaceTest.java
@@ -27,14 +27,11 @@ import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
-
import java.io.File;
import java.util.HashSet;
import java.util.Set;
-
import javax.transaction.Transactional;
import javax.ws.rs.core.Response;
-
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -55,105 +52,103 @@ import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
-
import com.fasterxml.jackson.databind.ObjectMapper;
public class ASDCRestInterfaceTest extends BaseTest {
- @Autowired
- private AllottedResourceRepository allottedRepo;
-
- @Autowired
- private ServiceRepository serviceRepo;
-
- @Autowired
- private NetworkResourceRepository networkRepo;
-
- @Autowired
- private ASDCRestInterface asdcRestInterface;
-
- private TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
-
- private HttpHeaders headers = new HttpHeaders();
-
- @Spy
- DistributionClientEmulator spyClient = new DistributionClientEmulator();
-
- @LocalServerPort
- private int port;
-
-
- @Rule
- public TemporaryFolder folder= new TemporaryFolder();
-
-
- @Before
- public void setUp() {
- //ASDC Controller writes to this path
- System.setProperty("mso.config.path", folder.getRoot().toString());
- }
-
- @Test
- @Transactional
- public void testAllottedResourceService() throws Exception {
-
- wireMockServer.stubFor(post(urlPathMatching("/aai/.*"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")));
-
- ObjectMapper mapper = new ObjectMapper();
- NotificationDataImpl request = mapper.readValue(new File("src/test/resources/resource-examples/allottedresource/notif-portm.json"), NotificationDataImpl.class);
- headers.add("resource-location", "src/test/resources/resource-examples/allottedresource/");
- HttpEntity<NotificationDataImpl> entity = new HttpEntity<NotificationDataImpl>(request, headers);
-
- ResponseEntity<String> response = restTemplate.exchange(createURLWithPort("test/treatNotification/v1"), HttpMethod.POST,
- entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
-
- AllottedResource expectedService = new AllottedResource();
- expectedService.setDescription("rege1802pnf");
- expectedService.setModelInvariantUUID("b8f83c3f-077c-4e2c-b489-c66382060436");
- expectedService.setModelName("rege1802pnf");
- expectedService.setModelUUID("5b18c75e-2d08-4bf2-ad58-4ea704ec648d");
- expectedService.setModelVersion("1.0");
- expectedService.setSubcategory("Contrail Route");
- expectedService.setToscaNodeType("org.openecomp.resource.pnf.Rege1802pnf");
- Set<AllottedResourceCustomization> arCustomizationSet = new HashSet<AllottedResourceCustomization>();
- AllottedResourceCustomization arCustomization = new AllottedResourceCustomization();
- arCustomization.setModelCustomizationUUID("f62bb612-c5d4-4406-865c-0abec30631ba");
- arCustomization.setModelInstanceName("rege1802pnf 0");
- arCustomizationSet.add(arCustomization);
-
- arCustomization.setAllottedResource(expectedService);
-
-
- expectedService.setAllotedResourceCustomization(arCustomizationSet);
-
- AllottedResource actualResponse = allottedRepo.findResourceByModelUUID("5b18c75e-2d08-4bf2-ad58-4ea704ec648d");
-
-
- if(actualResponse == null)
- throw new Exception("No Allotted Resource Written to database");
-
-
- assertThat(actualResponse, sameBeanAs(expectedService).ignoring("0x1.created").ignoring("0x1.allotedResourceCustomization.created"));
- }
-
- @Test
- public void invokeASDCStatusDataNullTest() {
- String request = "";
- Response response = asdcRestInterface.invokeASDCStatusData(request);
- assertNull(response);
-
- }
-
-
-
-
-
- protected String createURLWithPort(String uri) {
- return "http://localhost:" + port + uri;
- }
+ @Autowired
+ private AllottedResourceRepository allottedRepo;
+
+ @Autowired
+ private ServiceRepository serviceRepo;
+
+ @Autowired
+ private NetworkResourceRepository networkRepo;
+
+ @Autowired
+ private ASDCRestInterface asdcRestInterface;
+
+ private TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
+
+ private HttpHeaders headers = new HttpHeaders();
+
+ @Spy
+ DistributionClientEmulator spyClient = new DistributionClientEmulator();
+
+ @LocalServerPort
+ private int port;
+
+
+ @Rule
+ public TemporaryFolder folder = new TemporaryFolder();
+
+
+ @Before
+ public void setUp() {
+ // ASDC Controller writes to this path
+ System.setProperty("mso.config.path", folder.getRoot().toString());
+ }
+
+ @Test
+ @Transactional
+ public void testAllottedResourceService() throws Exception {
+
+ wireMockServer.stubFor(post(urlPathMatching("/aai/.*"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")));
+
+ ObjectMapper mapper = new ObjectMapper();
+ NotificationDataImpl request =
+ mapper.readValue(new File("src/test/resources/resource-examples/allottedresource/notif-portm.json"),
+ NotificationDataImpl.class);
+ headers.add("resource-location", "src/test/resources/resource-examples/allottedresource/");
+ HttpEntity<NotificationDataImpl> entity = new HttpEntity<NotificationDataImpl>(request, headers);
+
+ ResponseEntity<String> response = restTemplate.exchange(createURLWithPort("test/treatNotification/v1"),
+ HttpMethod.POST, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+
+ AllottedResource expectedService = new AllottedResource();
+ expectedService.setDescription("rege1802pnf");
+ expectedService.setModelInvariantUUID("b8f83c3f-077c-4e2c-b489-c66382060436");
+ expectedService.setModelName("rege1802pnf");
+ expectedService.setModelUUID("5b18c75e-2d08-4bf2-ad58-4ea704ec648d");
+ expectedService.setModelVersion("1.0");
+ expectedService.setSubcategory("Contrail Route");
+ expectedService.setToscaNodeType("org.openecomp.resource.pnf.Rege1802pnf");
+ Set<AllottedResourceCustomization> arCustomizationSet = new HashSet<AllottedResourceCustomization>();
+ AllottedResourceCustomization arCustomization = new AllottedResourceCustomization();
+ arCustomization.setModelCustomizationUUID("f62bb612-c5d4-4406-865c-0abec30631ba");
+ arCustomization.setModelInstanceName("rege1802pnf 0");
+ arCustomizationSet.add(arCustomization);
+
+ arCustomization.setAllottedResource(expectedService);
+
+
+ expectedService.setAllotedResourceCustomization(arCustomizationSet);
+
+ AllottedResource actualResponse = allottedRepo.findResourceByModelUUID("5b18c75e-2d08-4bf2-ad58-4ea704ec648d");
+
+
+ if (actualResponse == null)
+ throw new Exception("No Allotted Resource Written to database");
+
+
+ assertThat(actualResponse, sameBeanAs(expectedService).ignoring("0x1.created")
+ .ignoring("0x1.allotedResourceCustomization.created"));
+ }
+
+ @Test
+ public void invokeASDCStatusDataNullTest() {
+ String request = "";
+ Response response = asdcRestInterface.invokeASDCStatusData(request);
+ assertNull(response);
+
+ }
+
+
+
+ protected String createURLWithPort(String uri) {
+ return "http://localhost:" + port + uri;
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/HealthCheckTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/HealthCheckTest.java
index cd2c3ee7e6..adc55937b6 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/HealthCheckTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/HealthCheckTest.java
@@ -38,28 +38,27 @@ import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
public class HealthCheckTest extends BaseTest {
-
- @LocalServerPort
- private int port;
- TestRestTemplate restTemplate = new TestRestTemplate();
+ @LocalServerPort
+ private int port;
- HttpHeaders headers = new HttpHeaders();
-
- @Test
- public void testHealthcheck() throws JSONException {
+ TestRestTemplate restTemplate = new TestRestTemplate();
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+ HttpHeaders headers = new HttpHeaders();
- ResponseEntity<String> response = restTemplate.exchange(
- createURLWithPort("/manage/health"),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatusCode().value());
- }
-
- private String createURLWithPort(String uri) {
- return "http://localhost:" + port + uri;
- }
+ @Test
+ public void testHealthcheck() throws JSONException {
+
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(createURLWithPort("/manage/health"), HttpMethod.GET, entity, String.class);
+
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
+
+ private String createURLWithPort(String uri) {
+ return "http://localhost:" + port + uri;
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/tests/ASDCConfigurationTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/tests/ASDCConfigurationTest.java
index db797cff29..992d495369 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/client/tests/ASDCConfigurationTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/tests/ASDCConfigurationTest.java
@@ -24,12 +24,9 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-
import java.util.ArrayList;
import java.util.List;
-
import javax.transaction.Transactional;
-
import org.junit.Test;
import org.onap.so.asdc.BaseTest;
import org.onap.so.asdc.client.ASDCConfiguration;
@@ -42,111 +39,111 @@ import org.springframework.beans.factory.annotation.Autowired;
*/
@Transactional
public class ASDCConfigurationTest extends BaseTest {
-
+
@Autowired
private ASDCConfiguration config;
-
+
private List<String> msgBusAddressList = new ArrayList<String>();
-
+
private static final String MSO_PRE_IST = "msopreist";
private static final String MSO_ASDC_ID_LOCAL = "msoasdc-id-local";
private static final String PRE_IST = "Pre-IST";
private static final String ASDC_ADDRESS = "localhost:8443";
-
+
@Test
public void isUseHttpsWithDmaapTest() {
- assertTrue(config.isUseHttpsWithDmaap());
+ assertTrue(config.isUseHttpsWithDmaap());
}
-
+
@Test
public void isConsumeProduceStatusTopicTest() {
- assertTrue(config.isConsumeProduceStatusTopic());
+ assertTrue(config.isConsumeProduceStatusTopic());
}
-
+
@Test
public void getUserTest() {
- assertTrue(MSO_PRE_IST.equals(config.getUser()));
+ assertTrue(MSO_PRE_IST.equals(config.getUser()));
}
-
+
@Test
public void getConsumerGroupTest() {
- assertTrue(MSO_ASDC_ID_LOCAL.equals(config.getConsumerGroup()));
+ assertTrue(MSO_ASDC_ID_LOCAL.equals(config.getConsumerGroup()));
}
-
+
@Test
public void getConsumerIDTest() {
- assertTrue(MSO_ASDC_ID_LOCAL.equals(config.getConsumerID()));
+ assertTrue(MSO_ASDC_ID_LOCAL.equals(config.getConsumerID()));
}
-
+
@Test
public void getEnvironmentNameTest() {
- assertTrue(PRE_IST.equals(config.getEnvironmentName()));
+ assertTrue(PRE_IST.equals(config.getEnvironmentName()));
}
-
+
@Test
public void getAsdcAddress() {
- assertTrue(ASDC_ADDRESS.equals(config.getAsdcAddress()));
+ assertTrue(ASDC_ADDRESS.equals(config.getAsdcAddress()));
}
-
+
@Test
public void getPasswordTest() {
- assertTrue(MSO_PRE_IST.equals(config.getPassword()));
+ assertTrue(MSO_PRE_IST.equals(config.getPassword()));
}
-
+
@Test
public void getPollingIntervalTest() {
- assertTrue(config.getPollingInterval() == 30);
+ assertTrue(config.getPollingInterval() == 30);
}
-
+
@Test
public void getPollingTimeoutTest() {
- assertTrue(config.getPollingTimeout() == 30);
+ assertTrue(config.getPollingTimeout() == 30);
}
-
+
@Test
public void getRelevantArtifactTypesTest() {
- assertTrue(config.getRelevantArtifactTypes().size() == ASDCConfiguration.SUPPORTED_ARTIFACT_TYPES_LIST.size());
+ assertTrue(config.getRelevantArtifactTypes().size() == ASDCConfiguration.SUPPORTED_ARTIFACT_TYPES_LIST.size());
}
-
+
@Test
public void getWatchDogTimeoutTest() {
- assertTrue(config.getWatchDogTimeout() == 1);
+ assertTrue(config.getWatchDogTimeout() == 1);
}
-
+
@Test
public void activateServerTLSAuthTest() {
- assertFalse(config.activateServerTLSAuth());
+ assertFalse(config.activateServerTLSAuth());
}
-
+
@Test
public void getKeyStorePasswordTest() {
- assertNull(config.getKeyStorePassword());
+ assertNull(config.getKeyStorePassword());
}
-
+
@Test
public void getKeyStorePathTest() {
- assertNull(config.getKeyStorePath());
+ assertNull(config.getKeyStorePath());
}
-
+
@Test
public void isFilterInEmptyResourcesTest() {
- assertTrue(config.isFilterInEmptyResources());
+ assertTrue(config.isFilterInEmptyResources());
}
-
+
@Test
public void setGetAsdcControllerNameTest() {
- String asdcControllerName = "testAsdcControllerName";
- config.setAsdcControllerName(asdcControllerName);
- String actualAsdcControllerName = config.getAsdcControllerName();
- assertEquals(asdcControllerName, actualAsdcControllerName);
+ String asdcControllerName = "testAsdcControllerName";
+ config.setAsdcControllerName(asdcControllerName);
+ String actualAsdcControllerName = config.getAsdcControllerName();
+ assertEquals(asdcControllerName, actualAsdcControllerName);
}
-
+
@Test
public void getMsgBusAddressTest() {
- msgBusAddressList.add("localhost");
- msgBusAddressList.add("localhost");
-
- List<String> actualMsgBusAddress = config.getMsgBusAddress();
- assertEquals(msgBusAddressList, actualMsgBusAddress);
+ msgBusAddressList.add("localhost");
+ msgBusAddressList.add("localhost");
+
+ List<String> actualMsgBusAddress = config.getMsgBusAddress();
+ assertEquals(msgBusAddressList, actualMsgBusAddress);
}
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/installer/ToscaResourceStructureTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/installer/ToscaResourceStructureTest.java
index 1e8b72d145..d3990b9e7d 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/installer/ToscaResourceStructureTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/installer/ToscaResourceStructureTest.java
@@ -26,10 +26,8 @@ import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
-
import java.util.ArrayList;
import java.util.HashMap;
-
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -50,84 +48,89 @@ import org.onap.so.db.catalog.beans.VfModuleCustomization;
import org.onap.so.db.catalog.beans.VnfResourceCustomization;
public class ToscaResourceStructureTest {
- private ArtifactInfoImpl artifactInfo;
- private SdcCsarHelperImpl sdcCsarHelper;
-
- private ToscaResourceStructure toscaResourceStructure;
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Test
- public void toscaResourceStructureBeanTest() {
- artifactInfo = mock(ArtifactInfoImpl.class);
- sdcCsarHelper = mock(SdcCsarHelperImpl.class);
-
- toscaResourceStructure = new ToscaResourceStructure();
- toscaResourceStructure.setHeatTemplateUUID("heatTemplateUUID");
- toscaResourceStructure.setAllottedList(new ArrayList<NodeTemplate>());
- toscaResourceStructure.setSdcCsarHelper(sdcCsarHelper);
- toscaResourceStructure.setServiceMetadata(new Metadata(new HashMap<>()));
- toscaResourceStructure.setCatalogService(new Service());
- toscaResourceStructure.setNetworkTypes(new ArrayList<>());
- toscaResourceStructure.setVfTypes(new ArrayList<>());
- toscaResourceStructure.setCatalogResourceCustomization(new AllottedResourceCustomization());
- toscaResourceStructure.setCatalogNetworkResourceCustomization(new NetworkResourceCustomization());
- toscaResourceStructure.setCatalogNetworkResource(new NetworkResource());
- toscaResourceStructure.setCatalogVfModule(new VfModule());
- toscaResourceStructure.setVnfResourceCustomization(new VnfResourceCustomization());
- toscaResourceStructure.setVfModuleCustomization(new VfModuleCustomization());
- toscaResourceStructure.setAllottedResource(new AllottedResource());
- toscaResourceStructure.setAllottedResourceCustomization(new AllottedResourceCustomization());
- toscaResourceStructure.setCatalogTempNetworkHeatTemplateLookup(new TempNetworkHeatTemplateLookup());
- toscaResourceStructure.setHeatFilesUUID("heatFilesUUID");
- toscaResourceStructure.setToscaArtifact(artifactInfo);
- toscaResourceStructure.setToscaCsar(new ToscaCsar());
- toscaResourceStructure.setVolHeatTemplateUUID("volHeatTemplateUUID");
- toscaResourceStructure.setEnvHeatTemplateUUID("envHeatTemplateUUID");
- toscaResourceStructure.setServiceVersion("serviceVersion");
- toscaResourceStructure.setWorkloadPerformance("workloadPerformance");
- toscaResourceStructure.setVfModule(new VfModule());
- toscaResourceStructure.setTempNetworkHeatTemplateLookup(new TempNetworkHeatTemplateLookup());
- toscaResourceStructure.setSuccessfulDeployment();
-
- assertEquals("heatTemplateUUID", toscaResourceStructure.getHeatTemplateUUID());
- assertThat(toscaResourceStructure.getAllottedList(), sameBeanAs(new ArrayList<NodeTemplate>()));
- assertEquals(sdcCsarHelper, toscaResourceStructure.getSdcCsarHelper());
- assertThat(toscaResourceStructure.getServiceMetadata(), sameBeanAs(new Metadata(new HashMap<>())));
- assertThat(toscaResourceStructure.getCatalogService(), sameBeanAs(new Service()));
- assertThat(toscaResourceStructure.getNetworkTypes(), sameBeanAs(new ArrayList<>()));
- assertThat(toscaResourceStructure.getVfTypes(), sameBeanAs(new ArrayList<>()));
- assertThat(toscaResourceStructure.getCatalogResourceCustomization(), sameBeanAs(new AllottedResourceCustomization()));
- assertThat(toscaResourceStructure.getCatalogNetworkResourceCustomization(), sameBeanAs(new NetworkResourceCustomization()));
- assertThat(toscaResourceStructure.getCatalogNetworkResource(), sameBeanAs(new NetworkResource()));
- assertThat(toscaResourceStructure.getCatalogVfModule(), sameBeanAs(new VfModule()));
- assertThat(toscaResourceStructure.getVnfResourceCustomization(), sameBeanAs(new VnfResourceCustomization()));
- assertThat(toscaResourceStructure.getVfModuleCustomization(), sameBeanAs(new VfModuleCustomization()));
- assertThat(toscaResourceStructure.getAllottedResource(), sameBeanAs(new AllottedResource()));
- assertThat(toscaResourceStructure.getAllottedResourceCustomization(), sameBeanAs(new AllottedResourceCustomization()));
- assertThat(toscaResourceStructure.getCatalogTempNetworkHeatTemplateLookup(), sameBeanAs(new TempNetworkHeatTemplateLookup()));
- assertEquals("heatFilesUUID", toscaResourceStructure.getHeatFilesUUID());
- assertEquals(artifactInfo, toscaResourceStructure.getToscaArtifact());
- assertThat(toscaResourceStructure.getToscaCsar(), sameBeanAs(new ToscaCsar()));
- assertEquals("volHeatTemplateUUID", toscaResourceStructure.getVolHeatTemplateUUID());
- assertEquals("envHeatTemplateUUID", toscaResourceStructure.getEnvHeatTemplateUUID());
- assertEquals("serviceVersion", toscaResourceStructure.getServiceVersion());
- assertEquals("workloadPerformance", toscaResourceStructure.getWorkloadPerformance());
- assertThat(toscaResourceStructure.getVfModule(), sameBeanAs(new VfModule()));
- assertThat(toscaResourceStructure.getTempNetworkHeatTemplateLookup(), sameBeanAs(new TempNetworkHeatTemplateLookup()));
- assertEquals(true, toscaResourceStructure.isDeployedSuccessfully());
- }
-
- @Test
- public void updateResourceStructureExceptionTest() throws Exception {
- expectedException.expect(ASDCDownloadException.class);
-
- artifactInfo = mock(ArtifactInfoImpl.class);
- toscaResourceStructure = new ToscaResourceStructure();
+ private ArtifactInfoImpl artifactInfo;
+ private SdcCsarHelperImpl sdcCsarHelper;
+
+ private ToscaResourceStructure toscaResourceStructure;
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Test
+ public void toscaResourceStructureBeanTest() {
+ artifactInfo = mock(ArtifactInfoImpl.class);
+ sdcCsarHelper = mock(SdcCsarHelperImpl.class);
+
+ toscaResourceStructure = new ToscaResourceStructure();
+ toscaResourceStructure.setHeatTemplateUUID("heatTemplateUUID");
+ toscaResourceStructure.setAllottedList(new ArrayList<NodeTemplate>());
+ toscaResourceStructure.setSdcCsarHelper(sdcCsarHelper);
+ toscaResourceStructure.setServiceMetadata(new Metadata(new HashMap<>()));
+ toscaResourceStructure.setCatalogService(new Service());
+ toscaResourceStructure.setNetworkTypes(new ArrayList<>());
+ toscaResourceStructure.setVfTypes(new ArrayList<>());
+ toscaResourceStructure.setCatalogResourceCustomization(new AllottedResourceCustomization());
+ toscaResourceStructure.setCatalogNetworkResourceCustomization(new NetworkResourceCustomization());
+ toscaResourceStructure.setCatalogNetworkResource(new NetworkResource());
+ toscaResourceStructure.setCatalogVfModule(new VfModule());
+ toscaResourceStructure.setVnfResourceCustomization(new VnfResourceCustomization());
+ toscaResourceStructure.setVfModuleCustomization(new VfModuleCustomization());
+ toscaResourceStructure.setAllottedResource(new AllottedResource());
+ toscaResourceStructure.setAllottedResourceCustomization(new AllottedResourceCustomization());
+ toscaResourceStructure.setCatalogTempNetworkHeatTemplateLookup(new TempNetworkHeatTemplateLookup());
+ toscaResourceStructure.setHeatFilesUUID("heatFilesUUID");
+ toscaResourceStructure.setToscaArtifact(artifactInfo);
+ toscaResourceStructure.setToscaCsar(new ToscaCsar());
+ toscaResourceStructure.setVolHeatTemplateUUID("volHeatTemplateUUID");
+ toscaResourceStructure.setEnvHeatTemplateUUID("envHeatTemplateUUID");
+ toscaResourceStructure.setServiceVersion("serviceVersion");
+ toscaResourceStructure.setWorkloadPerformance("workloadPerformance");
+ toscaResourceStructure.setVfModule(new VfModule());
+ toscaResourceStructure.setTempNetworkHeatTemplateLookup(new TempNetworkHeatTemplateLookup());
+ toscaResourceStructure.setSuccessfulDeployment();
+
+ assertEquals("heatTemplateUUID", toscaResourceStructure.getHeatTemplateUUID());
+ assertThat(toscaResourceStructure.getAllottedList(), sameBeanAs(new ArrayList<NodeTemplate>()));
+ assertEquals(sdcCsarHelper, toscaResourceStructure.getSdcCsarHelper());
+ assertThat(toscaResourceStructure.getServiceMetadata(), sameBeanAs(new Metadata(new HashMap<>())));
+ assertThat(toscaResourceStructure.getCatalogService(), sameBeanAs(new Service()));
+ assertThat(toscaResourceStructure.getNetworkTypes(), sameBeanAs(new ArrayList<>()));
+ assertThat(toscaResourceStructure.getVfTypes(), sameBeanAs(new ArrayList<>()));
+ assertThat(toscaResourceStructure.getCatalogResourceCustomization(),
+ sameBeanAs(new AllottedResourceCustomization()));
+ assertThat(toscaResourceStructure.getCatalogNetworkResourceCustomization(),
+ sameBeanAs(new NetworkResourceCustomization()));
+ assertThat(toscaResourceStructure.getCatalogNetworkResource(), sameBeanAs(new NetworkResource()));
+ assertThat(toscaResourceStructure.getCatalogVfModule(), sameBeanAs(new VfModule()));
+ assertThat(toscaResourceStructure.getVnfResourceCustomization(), sameBeanAs(new VnfResourceCustomization()));
+ assertThat(toscaResourceStructure.getVfModuleCustomization(), sameBeanAs(new VfModuleCustomization()));
+ assertThat(toscaResourceStructure.getAllottedResource(), sameBeanAs(new AllottedResource()));
+ assertThat(toscaResourceStructure.getAllottedResourceCustomization(),
+ sameBeanAs(new AllottedResourceCustomization()));
+ assertThat(toscaResourceStructure.getCatalogTempNetworkHeatTemplateLookup(),
+ sameBeanAs(new TempNetworkHeatTemplateLookup()));
+ assertEquals("heatFilesUUID", toscaResourceStructure.getHeatFilesUUID());
+ assertEquals(artifactInfo, toscaResourceStructure.getToscaArtifact());
+ assertThat(toscaResourceStructure.getToscaCsar(), sameBeanAs(new ToscaCsar()));
+ assertEquals("volHeatTemplateUUID", toscaResourceStructure.getVolHeatTemplateUUID());
+ assertEquals("envHeatTemplateUUID", toscaResourceStructure.getEnvHeatTemplateUUID());
+ assertEquals("serviceVersion", toscaResourceStructure.getServiceVersion());
+ assertEquals("workloadPerformance", toscaResourceStructure.getWorkloadPerformance());
+ assertThat(toscaResourceStructure.getVfModule(), sameBeanAs(new VfModule()));
+ assertThat(toscaResourceStructure.getTempNetworkHeatTemplateLookup(),
+ sameBeanAs(new TempNetworkHeatTemplateLookup()));
+ assertEquals(true, toscaResourceStructure.isDeployedSuccessfully());
+ }
+
+ @Test
+ public void updateResourceStructureExceptionTest() throws Exception {
+ expectedException.expect(ASDCDownloadException.class);
+
+ artifactInfo = mock(ArtifactInfoImpl.class);
+ toscaResourceStructure = new ToscaResourceStructure();
+
+ doReturn("artifactName").when(artifactInfo).getArtifactName();
- doReturn("artifactName").when(artifactInfo).getArtifactName();
-
- toscaResourceStructure.updateResourceStructure(artifactInfo);
- }
+ toscaResourceStructure.updateResourceStructure(artifactInfo);
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/installer/bpmn/BpmnInstallerTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/installer/bpmn/BpmnInstallerTest.java
index e780a259ea..6efb04fc35 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/installer/bpmn/BpmnInstallerTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/installer/bpmn/BpmnInstallerTest.java
@@ -32,7 +32,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
@@ -77,27 +76,26 @@ public class BpmnInstallerTest {
public static void cleanup() {
System.clearProperty("mso.config.path");
}
-
+
@Test
public void buildMimeMultiPart_Test() throws Exception {
- Path tempFilePath = Paths.get(tempDirectoryPath.toAbsolutePath().toString(), "TestBB.bpmn");
- Files.createFile(tempFilePath);
- HttpEntity entity = bpmnInstaller.buildMimeMultipart("TestBB.bpmn");
- String mimeMultipartBodyFilePath = "src/test/resources" + "/mime-multipart-body.txt";
-
- File mimeMultipartBody = new File(mimeMultipartBodyFilePath);
- InputStream expectedContent = new FileInputStream(mimeMultipartBody);
-
- assertThat(IOUtils.contentEquals(expectedContent, entity.getContent()));
-
- IOUtils.closeQuietly(expectedContent);
+ Path tempFilePath = Paths.get(tempDirectoryPath.toAbsolutePath().toString(), "TestBB.bpmn");
+ Files.createFile(tempFilePath);
+ HttpEntity entity = bpmnInstaller.buildMimeMultipart("TestBB.bpmn");
+ String mimeMultipartBodyFilePath = "src/test/resources" + "/mime-multipart-body.txt";
+
+ File mimeMultipartBody = new File(mimeMultipartBodyFilePath);
+ InputStream expectedContent = new FileInputStream(mimeMultipartBody);
+
+ assertThat(IOUtils.contentEquals(expectedContent, entity.getContent()));
+
+ IOUtils.closeQuietly(expectedContent);
}
@Test
public void installBpmn_Test() throws Exception {
BpmnInstaller bpmnInstallerSpy = spy(bpmnInstaller);
- HttpResponse response = new BasicHttpResponse(
- new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, ""));
+ HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, ""));
HttpClient httpClient = mock(HttpClient.class);
doReturn(response).when(httpClient).execute(any(HttpPost.class));
bpmnInstallerSpy.installBpmn(TEST_CSAR);
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInputTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInputTest.java
index bc9275bb51..844adeede2 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInputTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInputTest.java
@@ -33,12 +33,10 @@ import org.onap.sdc.toscaparser.api.parameters.Input;
import org.onap.so.asdc.client.exceptions.ArtifactInstallerException;
import org.onap.so.asdc.installer.ToscaResourceStructure;
import org.onap.so.db.catalog.beans.Service;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
-
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java
index e4eb09782a..99833da3a3 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java
@@ -30,11 +30,9 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-
import org.hibernate.exception.LockAcquisitionException;
import org.junit.Before;
import org.junit.Rule;
@@ -69,310 +67,319 @@ import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatu
import org.springframework.beans.factory.annotation.Autowired;
public class ToscaResourceInstallerTest extends BaseTest {
- @Autowired
- private ToscaResourceInstaller toscaInstaller;
- @Autowired
- private WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository;
- @Autowired
- private AllottedResourceRepository allottedRepo;
- @Autowired
- private AllottedResourceCustomizationRepository allottedCustomizationRepo;
- @Autowired
- private ServiceRepository serviceRepo;
- @Mock
- private SdcCsarHelperImpl sdcCsarHelper;
- @Mock
- private Metadata metadata;
- @Mock
- private ArtifactInfoImpl artifactInfo;
- @Mock
- private List<Group> vfGroups;
- @Mock
- private IResourceInstance resourceInstance;
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
- @Mock
- private NodeTemplate nodeTemplate;
- @Mock
- private ToscaResourceStructure toscaResourceStructure;
- @Mock
- private ServiceProxyResourceCustomization spResourceCustomization;
- @Mock
- private ISdcCsarHelper csarHelper;
- @Mock
- private StatefulEntityType entityType;
-
- private NotificationDataImpl notificationData;
- private JsonStatusData statusData;
- private static final String MSO = "SO";
-
- @Before
- public void before() {
- MockitoAnnotations.initMocks(this);
-
- notificationData = new NotificationDataImpl();
- statusData = new JsonStatusData();
- }
-
- @Test
- public void isResourceAlreadyDeployedTest() throws Exception {
- notificationData.setServiceName("serviceName");
- notificationData.setServiceVersion("123456");
- notificationData.setServiceUUID("serviceUUID");
- notificationData.setDistributionID("testStatusSuccessTosca");
-
- WatchdogComponentDistributionStatus expectedComponentDistributionStatus =
- new WatchdogComponentDistributionStatus(notificationData.getDistributionID(), MSO);
- expectedComponentDistributionStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
-
- doReturn(true).when(vfResourceStructure).isDeployedSuccessfully();
- doReturn(notificationData).when(vfResourceStructure).getNotification();
- doReturn(resourceInstance).when(vfResourceStructure).getResourceInstance();
- doReturn("resourceInstanceName").when(resourceInstance).getResourceInstanceName();
- doReturn("resourceCustomizationUUID").when(resourceInstance).getResourceCustomizationUUID();
- doReturn("resourceName").when(resourceInstance).getResourceName();
-
- toscaInstaller.isResourceAlreadyDeployed(vfResourceStructure);
-
- WatchdogComponentDistributionStatus actualWatchdogComponentDistributionStatus = getWatchdogCDStatusWithName(watchdogCDStatusRepository.findByDistributionId(notificationData.getDistributionID()), MSO);
-
- verify(vfResourceStructure, times(3)).getResourceInstance();
- verify(vfResourceStructure, times(5)).getNotification();
- assertThat(actualWatchdogComponentDistributionStatus, sameBeanAs(expectedComponentDistributionStatus)
- .ignoring("createTime")
- .ignoring("modifyTime"));
- }
-
- @Test
- public void isResourceAlreadyDeployedFalseTest() throws Exception {
- notificationData.setServiceName("serviceName");
- notificationData.setServiceVersion("123456");
- notificationData.setServiceUUID("serviceUUID");
- notificationData.setDistributionID("testStatusSuccess");
-
- doThrow(RuntimeException.class).when(vfResourceStructure).isDeployedSuccessfully();
- doReturn(notificationData).when(vfResourceStructure).getNotification();
- doReturn(resourceInstance).when(vfResourceStructure).getResourceInstance();
- doReturn("resourceInstanceName").when(resourceInstance).getResourceInstanceName();
- doReturn("resourceCustomizationUUID").when(resourceInstance).getResourceCustomizationUUID();
- doReturn("resourceName").when(resourceInstance).getResourceName();
-
- toscaInstaller.isResourceAlreadyDeployed(vfResourceStructure);
-
- verify(vfResourceStructure, times(3)).getResourceInstance();
- verify(vfResourceStructure, times(4)).getNotification();
- }
-
- @Test
- public void isResourceAlreadyDeployedExceptionTest() throws ArtifactInstallerException {
- expectedException.expect(ArtifactInstallerException.class);
-
- toscaInstaller.isResourceAlreadyDeployed(vfResourceStructure);
- }
-
- @Test
- public void installTheComponentStatusTest() throws Exception {
- String distributionId = "testStatusSuccessTosca";
- String componentName = "testComponentName";
-
- statusData = spy(JsonStatusData.class);
- doReturn(distributionId).when(statusData).getDistributionID();
- doReturn(componentName).when(statusData).getComponentName();
-
- WatchdogComponentDistributionStatus expectedWatchdogComponentDistributionStatus =
- new WatchdogComponentDistributionStatus(distributionId, componentName);
- expectedWatchdogComponentDistributionStatus.setComponentDistributionStatus(statusData.getStatus().toString());
-
- WatchdogComponentDistributionStatus cdStatus = new WatchdogComponentDistributionStatus(statusData.getDistributionID(),
- statusData.getComponentName());
-
- toscaInstaller.installTheComponentStatus(statusData);
-
- WatchdogComponentDistributionStatus actualWatchdogComponentDistributionStatus = getWatchdogCDStatusWithName(watchdogCDStatusRepository.findByDistributionId("testStatusSuccessTosca"), statusData.getComponentName());
-
- assertEquals(statusData.getDistributionID(), cdStatus.getDistributionId());
- assertEquals(statusData.getComponentName(), cdStatus.getComponentName());
- assertThat(actualWatchdogComponentDistributionStatus, sameBeanAs(expectedWatchdogComponentDistributionStatus)
- .ignoring("createTime")
- .ignoring("modifyTime"));
- }
-
- @Test
- public void installTheComponentStatusExceptionTest() throws ArtifactInstallerException {
- expectedException.expect(ArtifactInstallerException.class);
-
- statusData = spy(JsonStatusData.class);
- doReturn(null).when(statusData).getStatus();
-
- toscaInstaller.installTheComponentStatus(statusData);
- }
-
- @Test
- public void installTheResourceExceptionTest() throws Exception {
- expectedException.expect(ArtifactInstallerException.class);
-
- notificationData.setDistributionID("testStatusFailureTosca");
- notificationData.setServiceVersion("123456");
- notificationData.setServiceUUID("serviceUUID");
- notificationData.setWorkloadContext("workloadContext");
-
- doReturn(notificationData).when(vfResourceStructure).getNotification();
- doReturn(resourceInstance).when(vfResourceStructure).getResourceInstance();
-
- toscaInstaller.installTheResource(toscaResourceStruct, vfResourceStructure);
- }
-
- @Test
- public void installTheResourceDBExceptionTest() throws Exception {
- notificationData.setDistributionID("testStatusSuccessTosca");
- notificationData.setServiceVersion("123456");
- notificationData.setServiceUUID("serviceUUID");
- notificationData.setWorkloadContext("workloadContext");
-
- doReturn(notificationData).when(vfResourceStructure).getNotification();
- doReturn(resourceInstance).when(vfResourceStructure).getResourceInstance();
- doThrow(LockAcquisitionException.class).when(toscaResourceStruct).getToscaArtifact();
-
- toscaInstaller.installTheResource(toscaResourceStruct, vfResourceStructure);
- }
-
- @Test
- public void verifyTheFilePrefixInStringTest() {
- String body = "abcabcabcfile:///testfile.txtabcbabacbcabc";
- String filenameToVerify = "testfile.txt";
- String expectedFileBody = "abcabcabctestfile.txtabcbabacbcabc";
-
- String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify);
-
- assertEquals(expectedFileBody, newFileBody);
- }
-
- @Test
- public void verifyTheFilePrefixInStringNullBodyTest() {
- String body = null;
- String filenameToVerify = "testfile.txt";
-
- String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify);
-
- assertEquals(body, newFileBody);
- }
-
- @Test
- public void verifyTheFilePrefixInStringEmptyBodyTest() {
- String body = "";
- String filenameToVerify = "testfile.txt";
-
- String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify);
-
- assertEquals(body, newFileBody);
- }
-
- @Test
- public void verifyTheFilePrefixInStringNullFilenameTest() {
- String body = "abcabcabcfile:///testfile.txtabcbabacbcabc";
- String filenameToVerify = null;
-
- String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify);
-
- assertEquals(body, newFileBody);
- }
-
- @Test
- public void verifyTheFilePrefixInStringEmptyFilenameTest() {
- String body = "abcabcabcfile:///testfile.txtabcbabacbcabc";
- String filenameToVerify = "";
-
- String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify);
-
- assertEquals(body, newFileBody);
- }
-
- private WatchdogComponentDistributionStatus getWatchdogCDStatusWithName(List<WatchdogComponentDistributionStatus> watchdogComponentDistributionStatuses, String componentName) {
- WatchdogComponentDistributionStatus actualWatchdogComponentDistributionStatus = new WatchdogComponentDistributionStatus();
- for(WatchdogComponentDistributionStatus watchdogComponentDistributionStatus : watchdogComponentDistributionStatuses) {
- if(componentName.equals(watchdogComponentDistributionStatus.getComponentName())) {
- actualWatchdogComponentDistributionStatus = watchdogComponentDistributionStatus;
- break;
- }
- }
- return actualWatchdogComponentDistributionStatus;
- }
-
-
-
-
- private void prepareConfigurationResource() {
- doReturn(metadata).when(nodeTemplate).getMetaData();
- doReturn(MockConstants.TEMPLATE_TYPE).when(nodeTemplate).getType();
-
- doReturn(MockConstants.MODEL_NAME).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_NAME);
- doReturn(MockConstants.MODEL_INVARIANT_UUID).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID);
- doReturn(MockConstants.MODEL_UUID).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_UUID);
- doReturn(MockConstants.MODEL_VERSION).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_VERSION);
- doReturn(MockConstants.MODEL_DESCRIPTION).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION);
- doReturn(MockConstants.MODEL_NAME).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_NAME);
- doReturn(MockConstants.MODEL_NAME).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_NAME);
- }
-
- @Test
- public void getConfigurationResourceTest() {
- prepareConfigurationResource();
-
- ConfigurationResource configResource=toscaInstaller.getConfigurationResource(nodeTemplate);
-
- assertNotNull(configResource);
- assertEquals(MockConstants.MODEL_NAME, configResource.getModelName());
- assertEquals(MockConstants.MODEL_INVARIANT_UUID, configResource.getModelInvariantUUID());
- assertEquals(MockConstants.MODEL_UUID, configResource.getModelUUID());
- assertEquals(MockConstants.MODEL_VERSION, configResource.getModelVersion());
- assertEquals(MockConstants.MODEL_DESCRIPTION, configResource.getDescription());
- assertEquals(MockConstants.TEMPLATE_TYPE, nodeTemplate.getType());
- }
-
- private void prepareConfigurationResourceCustomization() {
- prepareConfigurationResource();
- doReturn(MockConstants.MODEL_CUSTOMIZATIONUUID).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
- doReturn(csarHelper).when(toscaResourceStructure).getSdcCsarHelper();
- doReturn(null).when(csarHelper).getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION);
- doReturn(null).when(csarHelper).getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE);
- doReturn(null).when(csarHelper).getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE);
- doReturn(MockConstants.MODEL_CUSTOMIZATIONUUID).when(spResourceCustomization).getModelCustomizationUUID();
- }
-
-
- @Test
- public void getConfigurationResourceCustomizationTest() {
- prepareConfigurationResourceCustomization();
-
- ConfigurationResourceCustomization configurationResourceCustomization = toscaInstaller.getConfigurationResourceCustomization(
- nodeTemplate, toscaResourceStructure, spResourceCustomization);
- assertNotNull(configurationResourceCustomization);
- assertNotNull(configurationResourceCustomization.getConfigurationResource());
- assertEquals(MockConstants.MODEL_CUSTOMIZATIONUUID, configurationResourceCustomization.getServiceProxyResourceCustomizationUUID());
- }
-
- @Test
- public void getVnrNodeTemplateTest() {
- prepareConfigurationResourceCustomization();
- List<NodeTemplate> nodeTemplateList = new ArrayList<>();
- doReturn(ToscaResourceInstaller.VLAN_NETWORK_RECEPTOR).when(entityType).getType();
- doReturn(entityType).when(nodeTemplate).getTypeDefinition();
- nodeTemplateList.add(nodeTemplate);
- Optional<ConfigurationResourceCustomization> vnrResourceCustomization=
- toscaInstaller.getVnrNodeTemplate(nodeTemplateList, toscaResourceStructure, spResourceCustomization);
- assertTrue(vnrResourceCustomization.isPresent());
- assertEquals(ToscaResourceInstaller.VLAN_NETWORK_RECEPTOR, entityType.getType());
- }
-
- class MockConstants{
- public final static String MODEL_NAME = "VLAN Network Receptor Configuration";
- public final static String MODEL_INVARIANT_UUID = "1608eef4-de53-4334-a8d2-ba79cab4bde0";
- public final static String MODEL_UUID = "212ca27b-554c-474c-96b9-ddc2f1b1ddba";
- public final static String MODEL_VERSION = "30.0";
- public final static String MODEL_DESCRIPTION = "VLAN network receptor configuration object";
- public final static String MODEL_CUSTOMIZATIONUUID = "2db953e8-679d-437b-bff7-cb262638a8cd";
- public final static String TEMPLATE_TYPE = "org.openecomp.nodes.VLANNetworkReceptor";
- public final static String TEMPLATE_NAME = "VLAN Network Receptor Configuration 0";
-
- }
+ @Autowired
+ private ToscaResourceInstaller toscaInstaller;
+ @Autowired
+ private WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository;
+ @Autowired
+ private AllottedResourceRepository allottedRepo;
+ @Autowired
+ private AllottedResourceCustomizationRepository allottedCustomizationRepo;
+ @Autowired
+ private ServiceRepository serviceRepo;
+ @Mock
+ private SdcCsarHelperImpl sdcCsarHelper;
+ @Mock
+ private Metadata metadata;
+ @Mock
+ private ArtifactInfoImpl artifactInfo;
+ @Mock
+ private List<Group> vfGroups;
+ @Mock
+ private IResourceInstance resourceInstance;
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+ @Mock
+ private NodeTemplate nodeTemplate;
+ @Mock
+ private ToscaResourceStructure toscaResourceStructure;
+ @Mock
+ private ServiceProxyResourceCustomization spResourceCustomization;
+ @Mock
+ private ISdcCsarHelper csarHelper;
+ @Mock
+ private StatefulEntityType entityType;
+
+ private NotificationDataImpl notificationData;
+ private JsonStatusData statusData;
+ private static final String MSO = "SO";
+
+ @Before
+ public void before() {
+ MockitoAnnotations.initMocks(this);
+
+ notificationData = new NotificationDataImpl();
+ statusData = new JsonStatusData();
+ }
+
+ @Test
+ public void isResourceAlreadyDeployedTest() throws Exception {
+ notificationData.setServiceName("serviceName");
+ notificationData.setServiceVersion("123456");
+ notificationData.setServiceUUID("serviceUUID");
+ notificationData.setDistributionID("testStatusSuccessTosca");
+
+ WatchdogComponentDistributionStatus expectedComponentDistributionStatus =
+ new WatchdogComponentDistributionStatus(notificationData.getDistributionID(), MSO);
+ expectedComponentDistributionStatus
+ .setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
+
+ doReturn(true).when(vfResourceStructure).isDeployedSuccessfully();
+ doReturn(notificationData).when(vfResourceStructure).getNotification();
+ doReturn(resourceInstance).when(vfResourceStructure).getResourceInstance();
+ doReturn("resourceInstanceName").when(resourceInstance).getResourceInstanceName();
+ doReturn("resourceCustomizationUUID").when(resourceInstance).getResourceCustomizationUUID();
+ doReturn("resourceName").when(resourceInstance).getResourceName();
+
+ toscaInstaller.isResourceAlreadyDeployed(vfResourceStructure);
+
+ WatchdogComponentDistributionStatus actualWatchdogComponentDistributionStatus = getWatchdogCDStatusWithName(
+ watchdogCDStatusRepository.findByDistributionId(notificationData.getDistributionID()), MSO);
+
+ verify(vfResourceStructure, times(3)).getResourceInstance();
+ verify(vfResourceStructure, times(5)).getNotification();
+ assertThat(actualWatchdogComponentDistributionStatus,
+ sameBeanAs(expectedComponentDistributionStatus).ignoring("createTime").ignoring("modifyTime"));
+ }
+
+ @Test
+ public void isResourceAlreadyDeployedFalseTest() throws Exception {
+ notificationData.setServiceName("serviceName");
+ notificationData.setServiceVersion("123456");
+ notificationData.setServiceUUID("serviceUUID");
+ notificationData.setDistributionID("testStatusSuccess");
+
+ doThrow(RuntimeException.class).when(vfResourceStructure).isDeployedSuccessfully();
+ doReturn(notificationData).when(vfResourceStructure).getNotification();
+ doReturn(resourceInstance).when(vfResourceStructure).getResourceInstance();
+ doReturn("resourceInstanceName").when(resourceInstance).getResourceInstanceName();
+ doReturn("resourceCustomizationUUID").when(resourceInstance).getResourceCustomizationUUID();
+ doReturn("resourceName").when(resourceInstance).getResourceName();
+
+ toscaInstaller.isResourceAlreadyDeployed(vfResourceStructure);
+
+ verify(vfResourceStructure, times(3)).getResourceInstance();
+ verify(vfResourceStructure, times(4)).getNotification();
+ }
+
+ @Test
+ public void isResourceAlreadyDeployedExceptionTest() throws ArtifactInstallerException {
+ expectedException.expect(ArtifactInstallerException.class);
+
+ toscaInstaller.isResourceAlreadyDeployed(vfResourceStructure);
+ }
+
+ @Test
+ public void installTheComponentStatusTest() throws Exception {
+ String distributionId = "testStatusSuccessTosca";
+ String componentName = "testComponentName";
+
+ statusData = spy(JsonStatusData.class);
+ doReturn(distributionId).when(statusData).getDistributionID();
+ doReturn(componentName).when(statusData).getComponentName();
+
+ WatchdogComponentDistributionStatus expectedWatchdogComponentDistributionStatus =
+ new WatchdogComponentDistributionStatus(distributionId, componentName);
+ expectedWatchdogComponentDistributionStatus.setComponentDistributionStatus(statusData.getStatus().toString());
+
+ WatchdogComponentDistributionStatus cdStatus =
+ new WatchdogComponentDistributionStatus(statusData.getDistributionID(), statusData.getComponentName());
+
+ toscaInstaller.installTheComponentStatus(statusData);
+
+ WatchdogComponentDistributionStatus actualWatchdogComponentDistributionStatus =
+ getWatchdogCDStatusWithName(watchdogCDStatusRepository.findByDistributionId("testStatusSuccessTosca"),
+ statusData.getComponentName());
+
+ assertEquals(statusData.getDistributionID(), cdStatus.getDistributionId());
+ assertEquals(statusData.getComponentName(), cdStatus.getComponentName());
+ assertThat(actualWatchdogComponentDistributionStatus,
+ sameBeanAs(expectedWatchdogComponentDistributionStatus).ignoring("createTime").ignoring("modifyTime"));
+ }
+
+ @Test
+ public void installTheComponentStatusExceptionTest() throws ArtifactInstallerException {
+ expectedException.expect(ArtifactInstallerException.class);
+
+ statusData = spy(JsonStatusData.class);
+ doReturn(null).when(statusData).getStatus();
+
+ toscaInstaller.installTheComponentStatus(statusData);
+ }
+
+ @Test
+ public void installTheResourceExceptionTest() throws Exception {
+ expectedException.expect(ArtifactInstallerException.class);
+
+ notificationData.setDistributionID("testStatusFailureTosca");
+ notificationData.setServiceVersion("123456");
+ notificationData.setServiceUUID("serviceUUID");
+ notificationData.setWorkloadContext("workloadContext");
+
+ doReturn(notificationData).when(vfResourceStructure).getNotification();
+ doReturn(resourceInstance).when(vfResourceStructure).getResourceInstance();
+
+ toscaInstaller.installTheResource(toscaResourceStruct, vfResourceStructure);
+ }
+
+ @Test
+ public void installTheResourceDBExceptionTest() throws Exception {
+ notificationData.setDistributionID("testStatusSuccessTosca");
+ notificationData.setServiceVersion("123456");
+ notificationData.setServiceUUID("serviceUUID");
+ notificationData.setWorkloadContext("workloadContext");
+
+ doReturn(notificationData).when(vfResourceStructure).getNotification();
+ doReturn(resourceInstance).when(vfResourceStructure).getResourceInstance();
+ doThrow(LockAcquisitionException.class).when(toscaResourceStruct).getToscaArtifact();
+
+ toscaInstaller.installTheResource(toscaResourceStruct, vfResourceStructure);
+ }
+
+ @Test
+ public void verifyTheFilePrefixInStringTest() {
+ String body = "abcabcabcfile:///testfile.txtabcbabacbcabc";
+ String filenameToVerify = "testfile.txt";
+ String expectedFileBody = "abcabcabctestfile.txtabcbabacbcabc";
+
+ String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify);
+
+ assertEquals(expectedFileBody, newFileBody);
+ }
+
+ @Test
+ public void verifyTheFilePrefixInStringNullBodyTest() {
+ String body = null;
+ String filenameToVerify = "testfile.txt";
+
+ String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify);
+
+ assertEquals(body, newFileBody);
+ }
+
+ @Test
+ public void verifyTheFilePrefixInStringEmptyBodyTest() {
+ String body = "";
+ String filenameToVerify = "testfile.txt";
+
+ String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify);
+
+ assertEquals(body, newFileBody);
+ }
+
+ @Test
+ public void verifyTheFilePrefixInStringNullFilenameTest() {
+ String body = "abcabcabcfile:///testfile.txtabcbabacbcabc";
+ String filenameToVerify = null;
+
+ String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify);
+
+ assertEquals(body, newFileBody);
+ }
+
+ @Test
+ public void verifyTheFilePrefixInStringEmptyFilenameTest() {
+ String body = "abcabcabcfile:///testfile.txtabcbabacbcabc";
+ String filenameToVerify = "";
+
+ String newFileBody = toscaInstaller.verifyTheFilePrefixInString(body, filenameToVerify);
+
+ assertEquals(body, newFileBody);
+ }
+
+ private WatchdogComponentDistributionStatus getWatchdogCDStatusWithName(
+ List<WatchdogComponentDistributionStatus> watchdogComponentDistributionStatuses, String componentName) {
+ WatchdogComponentDistributionStatus actualWatchdogComponentDistributionStatus =
+ new WatchdogComponentDistributionStatus();
+ for (WatchdogComponentDistributionStatus watchdogComponentDistributionStatus : watchdogComponentDistributionStatuses) {
+ if (componentName.equals(watchdogComponentDistributionStatus.getComponentName())) {
+ actualWatchdogComponentDistributionStatus = watchdogComponentDistributionStatus;
+ break;
+ }
+ }
+ return actualWatchdogComponentDistributionStatus;
+ }
+
+
+
+ private void prepareConfigurationResource() {
+ doReturn(metadata).when(nodeTemplate).getMetaData();
+ doReturn(MockConstants.TEMPLATE_TYPE).when(nodeTemplate).getType();
+
+ doReturn(MockConstants.MODEL_NAME).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_NAME);
+ doReturn(MockConstants.MODEL_INVARIANT_UUID).when(metadata)
+ .getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID);
+ doReturn(MockConstants.MODEL_UUID).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_UUID);
+ doReturn(MockConstants.MODEL_VERSION).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_VERSION);
+ doReturn(MockConstants.MODEL_DESCRIPTION).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION);
+ doReturn(MockConstants.MODEL_NAME).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_NAME);
+ doReturn(MockConstants.MODEL_NAME).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_NAME);
+ }
+
+ @Test
+ public void getConfigurationResourceTest() {
+ prepareConfigurationResource();
+
+ ConfigurationResource configResource = toscaInstaller.getConfigurationResource(nodeTemplate);
+
+ assertNotNull(configResource);
+ assertEquals(MockConstants.MODEL_NAME, configResource.getModelName());
+ assertEquals(MockConstants.MODEL_INVARIANT_UUID, configResource.getModelInvariantUUID());
+ assertEquals(MockConstants.MODEL_UUID, configResource.getModelUUID());
+ assertEquals(MockConstants.MODEL_VERSION, configResource.getModelVersion());
+ assertEquals(MockConstants.MODEL_DESCRIPTION, configResource.getDescription());
+ assertEquals(MockConstants.TEMPLATE_TYPE, nodeTemplate.getType());
+ }
+
+ private void prepareConfigurationResourceCustomization() {
+ prepareConfigurationResource();
+ doReturn(MockConstants.MODEL_CUSTOMIZATIONUUID).when(metadata)
+ .getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
+ doReturn(csarHelper).when(toscaResourceStructure).getSdcCsarHelper();
+ doReturn(null).when(csarHelper).getNodeTemplatePropertyLeafValue(nodeTemplate,
+ SdcPropertyNames.PROPERTY_NAME_NFFUNCTION);
+ doReturn(null).when(csarHelper).getNodeTemplatePropertyLeafValue(nodeTemplate,
+ SdcPropertyNames.PROPERTY_NAME_NFROLE);
+ doReturn(null).when(csarHelper).getNodeTemplatePropertyLeafValue(nodeTemplate,
+ SdcPropertyNames.PROPERTY_NAME_NFTYPE);
+ doReturn(MockConstants.MODEL_CUSTOMIZATIONUUID).when(spResourceCustomization).getModelCustomizationUUID();
+ }
+
+
+ @Test
+ public void getConfigurationResourceCustomizationTest() {
+ prepareConfigurationResourceCustomization();
+
+ ConfigurationResourceCustomization configurationResourceCustomization = toscaInstaller
+ .getConfigurationResourceCustomization(nodeTemplate, toscaResourceStructure, spResourceCustomization);
+ assertNotNull(configurationResourceCustomization);
+ assertNotNull(configurationResourceCustomization.getConfigurationResource());
+ assertEquals(MockConstants.MODEL_CUSTOMIZATIONUUID,
+ configurationResourceCustomization.getServiceProxyResourceCustomizationUUID());
+ }
+
+ @Test
+ public void getVnrNodeTemplateTest() {
+ prepareConfigurationResourceCustomization();
+ List<NodeTemplate> nodeTemplateList = new ArrayList<>();
+ doReturn(ToscaResourceInstaller.VLAN_NETWORK_RECEPTOR).when(entityType).getType();
+ doReturn(entityType).when(nodeTemplate).getTypeDefinition();
+ nodeTemplateList.add(nodeTemplate);
+ Optional<ConfigurationResourceCustomization> vnrResourceCustomization =
+ toscaInstaller.getVnrNodeTemplate(nodeTemplateList, toscaResourceStructure, spResourceCustomization);
+ assertTrue(vnrResourceCustomization.isPresent());
+ assertEquals(ToscaResourceInstaller.VLAN_NETWORK_RECEPTOR, entityType.getType());
+ }
+
+ class MockConstants {
+ public final static String MODEL_NAME = "VLAN Network Receptor Configuration";
+ public final static String MODEL_INVARIANT_UUID = "1608eef4-de53-4334-a8d2-ba79cab4bde0";
+ public final static String MODEL_UUID = "212ca27b-554c-474c-96b9-ddc2f1b1ddba";
+ public final static String MODEL_VERSION = "30.0";
+ public final static String MODEL_DESCRIPTION = "VLAN network receptor configuration object";
+ public final static String MODEL_CUSTOMIZATIONUUID = "2db953e8-679d-437b-bff7-cb262638a8cd";
+ public final static String TEMPLATE_TYPE = "org.openecomp.nodes.VLANNetworkReceptor";
+ public final static String TEMPLATE_NAME = "VLAN Network Receptor Configuration 0";
+
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImplTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImplTest.java
index a20f6de579..9aad96cbc4 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImplTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/AaiClientPropertiesImplTest.java
@@ -21,38 +21,37 @@
package org.onap.so.asdc.tenantIsolation;
import static org.junit.Assert.assertEquals;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.so.asdc.BaseTest;
import org.onap.so.client.aai.AAIVersion;
public class AaiClientPropertiesImplTest extends BaseTest {
-
- private static final String SYSTEM_NAME = "MSO";
- private static final String LOCAL_HOST = "http://localhost:";
-
- @BeforeClass
- public static void setup() throws Exception {
- System.setProperty("mso.config.path", "src/test/resources");
- }
-
- @Test
- public void getEndpointTest() throws Exception {
- AaiClientPropertiesImpl aaiClientPropertiesImpl = new AaiClientPropertiesImpl();
- String aaiEndpoint = aaiClientPropertiesImpl.getEndpoint().toString();
- assertEquals(LOCAL_HOST + wireMockPort, aaiEndpoint);
- }
-
- @Test
- public void getSystemNameTest() {
- AaiClientPropertiesImpl aaiClientPropertiesImpl = new AaiClientPropertiesImpl();
- assertEquals(SYSTEM_NAME, aaiClientPropertiesImpl.getSystemName());
- }
-
- @Test
- public void getDefaultVersionTest() {
- AaiClientPropertiesImpl aaiClientPropertiesImpl = new AaiClientPropertiesImpl();
- assertEquals(AAIVersion.LATEST, aaiClientPropertiesImpl.getDefaultVersion());
- }
+
+ private static final String SYSTEM_NAME = "MSO";
+ private static final String LOCAL_HOST = "http://localhost:";
+
+ @BeforeClass
+ public static void setup() throws Exception {
+ System.setProperty("mso.config.path", "src/test/resources");
+ }
+
+ @Test
+ public void getEndpointTest() throws Exception {
+ AaiClientPropertiesImpl aaiClientPropertiesImpl = new AaiClientPropertiesImpl();
+ String aaiEndpoint = aaiClientPropertiesImpl.getEndpoint().toString();
+ assertEquals(LOCAL_HOST + wireMockPort, aaiEndpoint);
+ }
+
+ @Test
+ public void getSystemNameTest() {
+ AaiClientPropertiesImpl aaiClientPropertiesImpl = new AaiClientPropertiesImpl();
+ assertEquals(SYSTEM_NAME, aaiClientPropertiesImpl.getSystemName());
+ }
+
+ @Test
+ public void getDefaultVersionTest() {
+ AaiClientPropertiesImpl aaiClientPropertiesImpl = new AaiClientPropertiesImpl();
+ assertEquals(AAIVersion.LATEST, aaiClientPropertiesImpl.getDefaultVersion());
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/WatchdogDistributionTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/WatchdogDistributionTest.java
index cfce0f6a17..9ef41c7cbf 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/WatchdogDistributionTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/tenantIsolation/WatchdogDistributionTest.java
@@ -27,9 +27,7 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.HashMap;
-
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -43,99 +41,100 @@ import org.onap.so.db.catalog.beans.Service;
import org.springframework.beans.factory.annotation.Autowired;
public class WatchdogDistributionTest extends BaseTest {
- @Autowired
- private WatchdogDistribution watchdogDistribution;
-
- @Mock
- private AAIResourcesClient aaiResourceClient;
-
- private static final String SUCCESS_TEST = "watchdogTestStatusSuccess";
- private static final String FAILURE_TEST = "watchdogTestStatusFailure";
- private static final String TIMEOUT_TEST = "watchdogTestStatusTimeout";
- private static final String INCOMPLETE_TEST = "watchdogTestStatusIncomplete";
- private static final String EXCEPTION_TEST = "watchdogTestStatusException";
- private static final String NULL_TEST = "watchdogTestStatusNull";
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Before
- public void before() {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void getOverallDistributionStatusTimeoutTest() throws Exception {
- String status = watchdogDistribution.getOverallDistributionStatus(TIMEOUT_TEST);
- assertEquals(DistributionStatus.TIMEOUT.toString(), status);
- }
-
- @Test
- public void getOverallDistributionStatusSuccessTest() throws Exception {
- String status = watchdogDistribution.getOverallDistributionStatus(SUCCESS_TEST);
- assertEquals(DistributionStatus.SUCCESS.toString(), status);
- }
-
- @Test
- public void getOverallDistributionStatusFailureTest() throws Exception {
- String status = watchdogDistribution.getOverallDistributionStatus(FAILURE_TEST);
- assertEquals(DistributionStatus.FAILURE.toString(), status);
- }
-
- @Test
- public void getOverallDistributionStatusIncompleteTest() throws Exception {
- String status = watchdogDistribution.getOverallDistributionStatus(INCOMPLETE_TEST);
- assertEquals(DistributionStatus.INCOMPLETE.toString(), status);
- }
-
- @Test
- public void getOverallDistributionStatusInvalidComponentExceptionTest() throws Exception {
- expectedException.expect(Exception.class);
- watchdogDistribution.getOverallDistributionStatus(EXCEPTION_TEST);
- }
-
- @Test
- public void getOverallDistributionStatusNewStatusTest() throws Exception {
- String status = watchdogDistribution.getOverallDistributionStatus("newDistrubutionStatus");
- assertEquals(DistributionStatus.INCOMPLETE.toString(), status);
- }
-
- @Test
- public void getOverallDistributionStatusExceptionTest() throws Exception {
- expectedException.expect(Exception.class);
- watchdogDistribution.getOverallDistributionStatus(null);
- }
-
- @Test
- public void executePatchAAITest() throws Exception {
- Service service = new Service();
- service.setModelInvariantUUID("9647dfc4-2083-11e7-93ae-92361f002671");
-
- doReturn(aaiResourceClient).when(watchdogDistributionSpy).getAaiClient();
- doNothing().when(aaiResourceClient).update(isA(AAIResourceUri.class), isA(HashMap.class));
-
- watchdogDistribution.executePatchAAI(SUCCESS_TEST, service.getModelInvariantUUID(), DistributionStatus.SUCCESS.toString());
-
- verify(aaiResourceClient, times(1)).update(any(AAIResourceUri.class), any(HashMap.class));
- }
-
- @Test
- public void executePatchAAINullDistrubutionIdTest() throws Exception {
- expectedException.expect(Exception.class);
- watchdogDistribution.executePatchAAI(null, "", DistributionStatus.SUCCESS.toString());
- }
-
- @Test
- public void executePatchAAINullServiceTest() throws Exception {
- expectedException.expect(Exception.class);
- watchdogDistribution.executePatchAAI(NULL_TEST, null, DistributionStatus.SUCCESS.toString());
- }
-
- @Test
- public void getSetAaiClientTest() {
- aaiResourceClient = watchdogDistribution.getAaiClient();
- watchdogDistribution.setAaiClient(aaiResourceClient);
- AAIResourcesClient aaiResourceClient2 = watchdogDistribution.getAaiClient();
- assertEquals(aaiResourceClient, aaiResourceClient2);
- }
+ @Autowired
+ private WatchdogDistribution watchdogDistribution;
+
+ @Mock
+ private AAIResourcesClient aaiResourceClient;
+
+ private static final String SUCCESS_TEST = "watchdogTestStatusSuccess";
+ private static final String FAILURE_TEST = "watchdogTestStatusFailure";
+ private static final String TIMEOUT_TEST = "watchdogTestStatusTimeout";
+ private static final String INCOMPLETE_TEST = "watchdogTestStatusIncomplete";
+ private static final String EXCEPTION_TEST = "watchdogTestStatusException";
+ private static final String NULL_TEST = "watchdogTestStatusNull";
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Before
+ public void before() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void getOverallDistributionStatusTimeoutTest() throws Exception {
+ String status = watchdogDistribution.getOverallDistributionStatus(TIMEOUT_TEST);
+ assertEquals(DistributionStatus.TIMEOUT.toString(), status);
+ }
+
+ @Test
+ public void getOverallDistributionStatusSuccessTest() throws Exception {
+ String status = watchdogDistribution.getOverallDistributionStatus(SUCCESS_TEST);
+ assertEquals(DistributionStatus.SUCCESS.toString(), status);
+ }
+
+ @Test
+ public void getOverallDistributionStatusFailureTest() throws Exception {
+ String status = watchdogDistribution.getOverallDistributionStatus(FAILURE_TEST);
+ assertEquals(DistributionStatus.FAILURE.toString(), status);
+ }
+
+ @Test
+ public void getOverallDistributionStatusIncompleteTest() throws Exception {
+ String status = watchdogDistribution.getOverallDistributionStatus(INCOMPLETE_TEST);
+ assertEquals(DistributionStatus.INCOMPLETE.toString(), status);
+ }
+
+ @Test
+ public void getOverallDistributionStatusInvalidComponentExceptionTest() throws Exception {
+ expectedException.expect(Exception.class);
+ watchdogDistribution.getOverallDistributionStatus(EXCEPTION_TEST);
+ }
+
+ @Test
+ public void getOverallDistributionStatusNewStatusTest() throws Exception {
+ String status = watchdogDistribution.getOverallDistributionStatus("newDistrubutionStatus");
+ assertEquals(DistributionStatus.INCOMPLETE.toString(), status);
+ }
+
+ @Test
+ public void getOverallDistributionStatusExceptionTest() throws Exception {
+ expectedException.expect(Exception.class);
+ watchdogDistribution.getOverallDistributionStatus(null);
+ }
+
+ @Test
+ public void executePatchAAITest() throws Exception {
+ Service service = new Service();
+ service.setModelInvariantUUID("9647dfc4-2083-11e7-93ae-92361f002671");
+
+ doReturn(aaiResourceClient).when(watchdogDistributionSpy).getAaiClient();
+ doNothing().when(aaiResourceClient).update(isA(AAIResourceUri.class), isA(HashMap.class));
+
+ watchdogDistribution.executePatchAAI(SUCCESS_TEST, service.getModelInvariantUUID(),
+ DistributionStatus.SUCCESS.toString());
+
+ verify(aaiResourceClient, times(1)).update(any(AAIResourceUri.class), any(HashMap.class));
+ }
+
+ @Test
+ public void executePatchAAINullDistrubutionIdTest() throws Exception {
+ expectedException.expect(Exception.class);
+ watchdogDistribution.executePatchAAI(null, "", DistributionStatus.SUCCESS.toString());
+ }
+
+ @Test
+ public void executePatchAAINullServiceTest() throws Exception {
+ expectedException.expect(Exception.class);
+ watchdogDistribution.executePatchAAI(NULL_TEST, null, DistributionStatus.SUCCESS.toString());
+ }
+
+ @Test
+ public void getSetAaiClientTest() {
+ aaiResourceClient = watchdogDistribution.getAaiClient();
+ watchdogDistribution.setAaiClient(aaiResourceClient);
+ AAIResourcesClient aaiResourceClient2 = watchdogDistribution.getAaiClient();
+ assertEquals(aaiResourceClient, aaiResourceClient2);
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/util/ASDCNotificationLoggingTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/util/ASDCNotificationLoggingTest.java
index 3abc2e7a62..6fd853915e 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/util/ASDCNotificationLoggingTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/util/ASDCNotificationLoggingTest.java
@@ -21,10 +21,8 @@
package org.onap.so.asdc.util;
import static org.junit.Assert.assertTrue;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.api.notification.INotificationData;
@@ -34,153 +32,153 @@ import org.onap.so.asdc.installer.VfModuleMetaData;
import org.onap.so.asdc.util.ASDCNotificationLogging;
public class ASDCNotificationLoggingTest {
- @Test
- public void dumpASDCNotificationTestForNull() throws Exception {
- INotificationData asdcNotification = iNotificationDataObject();
-
- String result = ASDCNotificationLogging.dumpASDCNotification(asdcNotification);
-
- assertTrue(!result.equalsIgnoreCase("NULL"));
- }
-
- private INotificationData iNotificationDataObject() {
- INotificationData iNotification = new INotificationData() {
-
- @Override
- public String getServiceVersion() {
- return "DistributionID";
- }
-
- @Override
- public String getServiceUUID() {
- return "12343254";
- }
-
- @Override
- public String getServiceName() {
- return "servername";
- }
-
- @Override
- public String getServiceInvariantUUID() {
- return "ServiceInvariantUUID";
- }
-
- @Override
- public String getServiceDescription() {
- return "Description";
- }
-
- @Override
- public List<IArtifactInfo> getServiceArtifacts() {
- return new ArrayList();
- }
-
- @Override
- public List<IResourceInstance> getResources() {
- return new ArrayList();
- }
-
- @Override
- public String getDistributionID() {
- return "23434";
- }
-
- @Override
- public IArtifactInfo getArtifactMetadataByUUID(String arg0) {
- return null;
- }
-
- @Override
- public String getWorkloadContext() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public void setWorkloadContext(String arg0) {
- // TODO Auto-generated method stub
-
- }
- };
- return iNotification;
- }
-
- @Test
- public void dumpASDCNotificationTest() throws Exception {
- INotificationData asdcNotification = iNotificationDataObject();
- String result = ASDCNotificationLogging.dumpASDCNotification(asdcNotification);
-
- assertTrue(!result.equalsIgnoreCase("NULL"));
- }
-
- @Test
- public void dumpVfModuleMetaDataListTest() {
- INotificationData asdcNotification = iNotificationDataObject();
- List<IVfModuleData> list = new ArrayList<>();
- list.add(new VfModuleMetaData());
- String result = null;
- try {
- result = ASDCNotificationLogging.dumpVfModuleMetaDataList(list);
- } catch (Exception e) {
- }
-
- assertTrue(result == null);
-
- }
-
- public IArtifactInfo getIArtifactInfo() {
- return new IArtifactInfo() {
-
- @Override
- public List<IArtifactInfo> getRelatedArtifacts() {
- return null;
- }
-
- @Override
- public IArtifactInfo getGeneratedArtifact() {
- return null;
- }
-
- @Override
- public String getArtifactVersion() {
- return "version";
- }
-
- @Override
- public String getArtifactUUID() {
- return "123";
- }
-
- @Override
- public String getArtifactURL() {
- return "url";
- }
-
- @Override
- public String getArtifactType() {
- return "type";
- }
-
- @Override
- public Integer getArtifactTimeout() {
- return 12;
- }
-
- @Override
- public String getArtifactName() {
- return "name";
- }
-
- @Override
- public String getArtifactDescription() {
- return "desc";
- }
-
- @Override
- public String getArtifactChecksum() {
- return "true";
- }
- };
- }
+ @Test
+ public void dumpASDCNotificationTestForNull() throws Exception {
+ INotificationData asdcNotification = iNotificationDataObject();
+
+ String result = ASDCNotificationLogging.dumpASDCNotification(asdcNotification);
+
+ assertTrue(!result.equalsIgnoreCase("NULL"));
+ }
+
+ private INotificationData iNotificationDataObject() {
+ INotificationData iNotification = new INotificationData() {
+
+ @Override
+ public String getServiceVersion() {
+ return "DistributionID";
+ }
+
+ @Override
+ public String getServiceUUID() {
+ return "12343254";
+ }
+
+ @Override
+ public String getServiceName() {
+ return "servername";
+ }
+
+ @Override
+ public String getServiceInvariantUUID() {
+ return "ServiceInvariantUUID";
+ }
+
+ @Override
+ public String getServiceDescription() {
+ return "Description";
+ }
+
+ @Override
+ public List<IArtifactInfo> getServiceArtifacts() {
+ return new ArrayList();
+ }
+
+ @Override
+ public List<IResourceInstance> getResources() {
+ return new ArrayList();
+ }
+
+ @Override
+ public String getDistributionID() {
+ return "23434";
+ }
+
+ @Override
+ public IArtifactInfo getArtifactMetadataByUUID(String arg0) {
+ return null;
+ }
+
+ @Override
+ public String getWorkloadContext() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public void setWorkloadContext(String arg0) {
+ // TODO Auto-generated method stub
+
+ }
+ };
+ return iNotification;
+ }
+
+ @Test
+ public void dumpASDCNotificationTest() throws Exception {
+ INotificationData asdcNotification = iNotificationDataObject();
+ String result = ASDCNotificationLogging.dumpASDCNotification(asdcNotification);
+
+ assertTrue(!result.equalsIgnoreCase("NULL"));
+ }
+
+ @Test
+ public void dumpVfModuleMetaDataListTest() {
+ INotificationData asdcNotification = iNotificationDataObject();
+ List<IVfModuleData> list = new ArrayList<>();
+ list.add(new VfModuleMetaData());
+ String result = null;
+ try {
+ result = ASDCNotificationLogging.dumpVfModuleMetaDataList(list);
+ } catch (Exception e) {
+ }
+
+ assertTrue(result == null);
+
+ }
+
+ public IArtifactInfo getIArtifactInfo() {
+ return new IArtifactInfo() {
+
+ @Override
+ public List<IArtifactInfo> getRelatedArtifacts() {
+ return null;
+ }
+
+ @Override
+ public IArtifactInfo getGeneratedArtifact() {
+ return null;
+ }
+
+ @Override
+ public String getArtifactVersion() {
+ return "version";
+ }
+
+ @Override
+ public String getArtifactUUID() {
+ return "123";
+ }
+
+ @Override
+ public String getArtifactURL() {
+ return "url";
+ }
+
+ @Override
+ public String getArtifactType() {
+ return "type";
+ }
+
+ @Override
+ public Integer getArtifactTimeout() {
+ return 12;
+ }
+
+ @Override
+ public String getArtifactName() {
+ return "name";
+ }
+
+ @Override
+ public String getArtifactDescription() {
+ return "desc";
+ }
+
+ @Override
+ public String getArtifactChecksum() {
+ return "true";
+ }
+ };
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/util/NotificationLoggingTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/util/NotificationLoggingTest.java
index 8bd11d9f52..0bdb3a8bab 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/util/NotificationLoggingTest.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/util/NotificationLoggingTest.java
@@ -22,46 +22,45 @@ package org.onap.so.asdc.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.so.asdc.client.test.emulators.NotificationDataImpl;
public class NotificationLoggingTest {
- private NotificationDataImpl notificationData;
-
- @Before
- public void before() {
- notificationData = new NotificationDataImpl();
- }
-
- @Test
- public void logNotificationTest() {
- notificationData.setDistributionID("distributionID");
- notificationData.setServiceVersion("123456");
- notificationData.setServiceUUID("serviceUUID");
- notificationData.setWorkloadContext("workloadContext");
-
- String response = NotificationLogging.logNotification(notificationData);
+ private NotificationDataImpl notificationData;
+
+ @Before
+ public void before() {
+ notificationData = new NotificationDataImpl();
+ }
+
+ @Test
+ public void logNotificationTest() {
+ notificationData.setDistributionID("distributionID");
+ notificationData.setServiceVersion("123456");
+ notificationData.setServiceUUID("serviceUUID");
+ notificationData.setWorkloadContext("workloadContext");
+
+ String response = NotificationLogging.logNotification(notificationData);
+
+ assertTrue(response.contains("ASDC Notification"));
+ assertTrue(response.contains("ResourcesType not recognized"));
+ assertTrue(response.contains("ServiceNameNULL"));
+ assertTrue(response.contains("ServiceUUIDserviceUUID"));
+ assertTrue(response.contains("ResourcesImplNULL"));
+ assertTrue(response.contains("ServiceArtifactsType not recognized"));
+ assertTrue(response.contains("ServiceDescriptionNULL"));
+ assertTrue(response.contains("DistributionIDdistributionID"));
+ assertTrue(response.contains("ServiceInvariantUUIDNULL"));
+ assertTrue(response.contains("WorkloadContextworkloadContext"));
+ }
+
+ @Test
+ public void logNotificationNullTest() {
+ notificationData = null;
+
+ String response = NotificationLogging.logNotification(notificationData);
- assertTrue(response.contains("ASDC Notification"));
- assertTrue(response.contains("ResourcesType not recognized"));
- assertTrue(response.contains("ServiceNameNULL"));
- assertTrue(response.contains("ServiceUUIDserviceUUID"));
- assertTrue(response.contains("ResourcesImplNULL"));
- assertTrue(response.contains("ServiceArtifactsType not recognized"));
- assertTrue(response.contains("ServiceDescriptionNULL"));
- assertTrue(response.contains("DistributionIDdistributionID"));
- assertTrue(response.contains("ServiceInvariantUUIDNULL"));
- assertTrue(response.contains("WorkloadContextworkloadContext"));
- }
-
- @Test
- public void logNotificationNullTest() {
- notificationData = null;
-
- String response = NotificationLogging.logNotification(notificationData);
-
- assertEquals("NULL", response);
- }
+ assertEquals("NULL", response);
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingRunner.java b/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingRunner.java
index 2a77664714..b344f6230a 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingRunner.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingRunner.java
@@ -22,35 +22,31 @@ package org.onap.so.asdc.utils;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
-
import com.fasterxml.jackson.databind.JsonNode;
-public class ASDCLoggingRunner
-{
- public static void main( String[] args) throws Exception
- {
+public class ASDCLoggingRunner {
+ public static void main(String[] args) throws Exception {
String content = new String(Files.readAllBytes(Paths.get("src/test/resources/Heat_Nested_Notification.txt")));
ASDCLoggingLexer lexer = new ASDCLoggingLexer(CharStreams.fromString(content));
- CommonTokenStream tokens = new CommonTokenStream(lexer);
+ CommonTokenStream tokens = new CommonTokenStream(lexer);
+
+ ASDCLoggingParser parser = new ASDCLoggingParser(tokens);
+
+ ParseTree tree = parser.doc();
+
+ System.out.println(TreeUtils.printTree(tree, parser)); // print LISP-style tree
+
+ ASDCLoggingVisitorImpl v = new ASDCLoggingVisitorImpl();
- ASDCLoggingParser parser = new ASDCLoggingParser(tokens);
-
- ParseTree tree = parser.doc();
+ JsonNode node = v.visit(tree);
- System.out.println(TreeUtils.printTree(tree, parser)); // print LISP-style tree
-
- ASDCLoggingVisitorImpl v = new ASDCLoggingVisitorImpl();
-
- JsonNode node = v.visit(tree);
-
- System.out.println(node.toString());
+ System.out.println(node.toString());
- }
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingVisitorImpl.java b/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingVisitorImpl.java
index 51036e2a18..53d163a5bc 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingVisitorImpl.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/utils/ASDCLoggingVisitorImpl.java
@@ -22,7 +22,6 @@ package org.onap.so.asdc.utils;
import java.util.ArrayDeque;
import java.util.Deque;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ContainerNode;
@@ -32,73 +31,74 @@ import com.google.common.base.CaseFormat;
public class ASDCLoggingVisitorImpl extends ASDCLoggingBaseVisitor<ContainerNode> {
- private final ObjectMapper mapper = new ObjectMapper();
- private ObjectNode doc;
- private Deque<ContainerNode> nodeStore = new ArrayDeque<>();
-
- @Override
- public ContainerNode visitDoc(ASDCLoggingParser.DocContext ctx) {
- doc = mapper.createObjectNode();
- nodeStore.addFirst(doc);
- this.visitChildren(ctx);
- return doc;
- }
-
- @Override
- public ContainerNode visitValue(ASDCLoggingParser.ValueContext ctx) {
-
- return this.visitChildren(ctx);
-
- }
- @Override
- public ContainerNode visitSimplePair(ASDCLoggingParser.SimplePairContext ctx) {
- ObjectNode node = mapper.createObjectNode();
- ((ObjectNode)nodeStore.peekFirst()).put(this.toLowerCamel(ctx.key().getText()), ctx.keyValue().getText());
-
- return node;
- }
-
- @Override
- public ContainerNode visitComplexPair(ASDCLoggingParser.ComplexPairContext ctx) {
- ContainerNode container = nodeStore.peekFirst();
- if (container.isArray()) {
- ArrayNode array = (ArrayNode) container;
- ObjectNode node = mapper.createObjectNode();
- array.add(node);
- nodeStore.addFirst(node);
- } else {
- nodeStore.addFirst(((ObjectNode)nodeStore.peekFirst()).putObject(this.toLowerCamel(ctx.key().getText())));
- }
- this.visitChildren(ctx);
- return nodeStore.removeFirst();
-
-
- }
-
- @Override
- public ContainerNode visitList(ASDCLoggingParser.ListContext ctx) {
- nodeStore.addFirst(((ObjectNode)nodeStore.peekFirst()).putArray(this.keyMapper(ctx.listName().getText())));
- this.visitChildren(ctx);
- return nodeStore.removeFirst();
- }
-
- private String keyMapper(String key) {
- if ("Service Artifacts List".equals(key)) {
- return "serviceArtifacts";
- } else if ("Resource Instances List".equals(key)) {
- return "resources";
- } else if ("Resource Artifacts List".equals(key)) {
- return "artifacts";
- } else {
- return key;
- }
- }
-
- private String toLowerCamel(String key) {
- String result = key.replaceAll("\\s", "");
- if ("ServiceArtifactsInfo".equals(result)) {
- return "artifactInfo";
- }
- return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, result);
- }
+ private final ObjectMapper mapper = new ObjectMapper();
+ private ObjectNode doc;
+ private Deque<ContainerNode> nodeStore = new ArrayDeque<>();
+
+ @Override
+ public ContainerNode visitDoc(ASDCLoggingParser.DocContext ctx) {
+ doc = mapper.createObjectNode();
+ nodeStore.addFirst(doc);
+ this.visitChildren(ctx);
+ return doc;
+ }
+
+ @Override
+ public ContainerNode visitValue(ASDCLoggingParser.ValueContext ctx) {
+
+ return this.visitChildren(ctx);
+
+ }
+
+ @Override
+ public ContainerNode visitSimplePair(ASDCLoggingParser.SimplePairContext ctx) {
+ ObjectNode node = mapper.createObjectNode();
+ ((ObjectNode) nodeStore.peekFirst()).put(this.toLowerCamel(ctx.key().getText()), ctx.keyValue().getText());
+
+ return node;
+ }
+
+ @Override
+ public ContainerNode visitComplexPair(ASDCLoggingParser.ComplexPairContext ctx) {
+ ContainerNode container = nodeStore.peekFirst();
+ if (container.isArray()) {
+ ArrayNode array = (ArrayNode) container;
+ ObjectNode node = mapper.createObjectNode();
+ array.add(node);
+ nodeStore.addFirst(node);
+ } else {
+ nodeStore.addFirst(((ObjectNode) nodeStore.peekFirst()).putObject(this.toLowerCamel(ctx.key().getText())));
+ }
+ this.visitChildren(ctx);
+ return nodeStore.removeFirst();
+
+
+ }
+
+ @Override
+ public ContainerNode visitList(ASDCLoggingParser.ListContext ctx) {
+ nodeStore.addFirst(((ObjectNode) nodeStore.peekFirst()).putArray(this.keyMapper(ctx.listName().getText())));
+ this.visitChildren(ctx);
+ return nodeStore.removeFirst();
+ }
+
+ private String keyMapper(String key) {
+ if ("Service Artifacts List".equals(key)) {
+ return "serviceArtifacts";
+ } else if ("Resource Instances List".equals(key)) {
+ return "resources";
+ } else if ("Resource Artifacts List".equals(key)) {
+ return "artifacts";
+ } else {
+ return key;
+ }
+ }
+
+ private String toLowerCamel(String key) {
+ String result = key.replaceAll("\\s", "");
+ if ("ServiceArtifactsInfo".equals(result)) {
+ return "artifactInfo";
+ }
+ return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, result);
+ }
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreePrinterListener.java b/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreePrinterListener.java
index c4a84c0540..39119c7dca 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreePrinterListener.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreePrinterListener.java
@@ -25,7 +25,6 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RuleContext;
@@ -38,7 +37,7 @@ import org.antlr.v4.runtime.tree.Trees;
public class TreePrinterListener implements ParseTreeListener {
private final List<String> ruleNames;
private final StringBuilder builder = new StringBuilder();
- Map<RuleContext,ArrayList<String>> stack = new HashMap<RuleContext,ArrayList<String>>();
+ Map<RuleContext, ArrayList<String>> stack = new HashMap<RuleContext, ArrayList<String>>();
public TreePrinterListener(Parser parser) {
this.ruleNames = Arrays.asList(parser.getRuleNames());
@@ -50,10 +49,10 @@ public class TreePrinterListener implements ParseTreeListener {
@Override
public void visitTerminal(TerminalNode node) {
- String text = Utils.escapeWhitespace(Trees.getNodeText(node, ruleNames), false);
- if(text.startsWith(" ") || text.endsWith(" ")){
- text = "'" + text + "'";
- }
+ String text = Utils.escapeWhitespace(Trees.getNodeText(node, ruleNames), false);
+ if (text.startsWith(" ") || text.endsWith(" ")) {
+ text = "'" + text + "'";
+ }
stack.get(node.getParent()).add(text);
}
@@ -64,20 +63,19 @@ public class TreePrinterListener implements ParseTreeListener {
@Override
public void enterEveryRule(ParserRuleContext ctx) {
- if(!stack.containsKey(ctx.parent)){
- stack.put(ctx.parent, new ArrayList<String>());
- }
- if(!stack.containsKey(ctx)){
- stack.put(ctx, new ArrayList<String>());
- }
+ if (!stack.containsKey(ctx.parent)) {
+ stack.put(ctx.parent, new ArrayList<String>());
+ }
+ if (!stack.containsKey(ctx)) {
+ stack.put(ctx, new ArrayList<String>());
+ }
- final StringBuilder sb = new StringBuilder();
- int ruleIndex = ctx.getRuleIndex();
+ final StringBuilder sb = new StringBuilder();
+ int ruleIndex = ctx.getRuleIndex();
String ruleName;
if (ruleIndex >= 0 && ruleIndex < ruleNames.size()) {
ruleName = ruleNames.get(ruleIndex);
- }
- else {
+ } else {
ruleName = Integer.toString(ruleIndex);
}
sb.append(ruleName);
@@ -86,52 +84,52 @@ public class TreePrinterListener implements ParseTreeListener {
@Override
public void exitEveryRule(ParserRuleContext ctx) {
- ArrayList<String> ruleStack = stack.remove(ctx);
- StringBuilder sb = new StringBuilder();
- boolean brackit =ruleStack.size()>1;
- if(brackit){
- sb.append("(");
- }
- sb.append(ruleStack.get(0));
- for(int i=1; i<ruleStack.size(); i++){
- sb.append(" ");
- sb.append(ruleStack.get(i));
- }
- if(brackit){
- sb.append(")");
- }
- if(sb.length() < 80){
- stack.get(ctx.parent).add(sb.toString());
- }else{
- // Current line is too long, regenerate it using 1 line per item.
- sb.setLength(0);
- if(brackit){
- sb.append("(");
- }
- if(!ruleStack.isEmpty()){
- sb.append(ruleStack.remove(0)).append("\r\n");
- }
- while(!ruleStack.isEmpty()){
- sb.append(indent(ruleStack.remove(0))).append("\r\n");
- }
- if(brackit){
- sb.append(")");
- }
- stack.get(ctx.parent).add(sb.toString());
- }
- if(ctx.parent == null){
- builder.append(sb.toString());
- }
+ ArrayList<String> ruleStack = stack.remove(ctx);
+ StringBuilder sb = new StringBuilder();
+ boolean brackit = ruleStack.size() > 1;
+ if (brackit) {
+ sb.append("(");
+ }
+ sb.append(ruleStack.get(0));
+ for (int i = 1; i < ruleStack.size(); i++) {
+ sb.append(" ");
+ sb.append(ruleStack.get(i));
+ }
+ if (brackit) {
+ sb.append(")");
+ }
+ if (sb.length() < 80) {
+ stack.get(ctx.parent).add(sb.toString());
+ } else {
+ // Current line is too long, regenerate it using 1 line per item.
+ sb.setLength(0);
+ if (brackit) {
+ sb.append("(");
+ }
+ if (!ruleStack.isEmpty()) {
+ sb.append(ruleStack.remove(0)).append("\r\n");
+ }
+ while (!ruleStack.isEmpty()) {
+ sb.append(indent(ruleStack.remove(0))).append("\r\n");
+ }
+ if (brackit) {
+ sb.append(")");
+ }
+ stack.get(ctx.parent).add(sb.toString());
+ }
+ if (ctx.parent == null) {
+ builder.append(sb.toString());
+ }
}
-
- static String indent(String input){
- return " " + input.replaceAll("\r\n(.)","\r\n $1");
+
+ static String indent(String input) {
+ return " " + input.replaceAll("\r\n(.)", "\r\n $1");
}
@Override
public String toString() {
return builder.toString();
}
-
-
+
+
}
diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreeUtils.java b/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreeUtils.java
index 8de9f362b7..5a03b91959 100644
--- a/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreeUtils.java
+++ b/asdc-controller/src/test/java/org/onap/so/asdc/utils/TreeUtils.java
@@ -21,7 +21,6 @@
package org.onap.so.asdc.utils;
import java.util.Arrays;
-
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
@@ -29,19 +28,20 @@ import org.antlr.v4.runtime.tree.ParseTreeWalker;
public class TreeUtils {
- /**
- * Print the tree, splitting at appropriate points, instead of rendering a single long line.
- * @param parseTree
- * @param parser
- * @return
- */
- public static String printTree(final ParseTree parseTree, final Parser parser){
- final TreePrinterListener listener = new TreePrinterListener(Arrays.asList(parser.getRuleNames()));
+ /**
+ * Print the tree, splitting at appropriate points, instead of rendering a single long line.
+ *
+ * @param parseTree
+ * @param parser
+ * @return
+ */
+ public static String printTree(final ParseTree parseTree, final Parser parser) {
+ final TreePrinterListener listener = new TreePrinterListener(Arrays.asList(parser.getRuleNames()));
ParseTreeWalker.DEFAULT.walk(listener, parseTree);
return listener.toString();
- }
-
- public static String normalizeWhiteSpace(String input){
- return input.replaceAll("\\s+", " ").replaceAll("([^\\w])\\s+", "$1");
+ }
+
+ public static String normalizeWhiteSpace(String input) {
+ return input.replaceAll("\\s+", " ").replaceAll("([^\\w])\\s+", "$1");
}
}
diff --git a/basepath_marker b/basepath_marker
new file mode 100644
index 0000000000..89ec07c153
--- /dev/null
+++ b/basepath_marker
@@ -0,0 +1 @@
+//required for groovy base path script in pom.xml \ No newline at end of file
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/PayloadClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/PayloadClient.java
index 45bc27d840..3b768cbc3b 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/PayloadClient.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/PayloadClient.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.appc.payload;
import java.util.Optional;
-
import org.onap.so.bpmn.appc.payload.beans.ConfigurationParametersHealthCheck;
import org.onap.so.bpmn.appc.payload.beans.ConfigurationParametersQuiesce;
import org.onap.so.bpmn.appc.payload.beans.ConfigurationParametersResumeTraffic;
@@ -34,67 +33,69 @@ import org.onap.so.bpmn.appc.payload.beans.SnapshotAction;
import org.onap.so.bpmn.appc.payload.beans.StartStopAction;
import org.onap.so.bpmn.appc.payload.beans.UpgradeAction;
import org.onap.so.bpmn.core.json.JsonUtils;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class PayloadClient {
- protected static ObjectMapper mapper = new ObjectMapper();
-
- private PayloadClient() {}
-
- public static Optional<String> upgradeFormat(Optional<String> payload, String vnfName) throws JsonProcessingException{
- UpgradeAction payloadResult = new UpgradeAction();
- ConfigurationParametersUpgrade configParams = new ConfigurationParametersUpgrade();
- String payloadString = payload.isPresent() ? payload.get() : "";
- String existingSoftware = JsonUtils.getJsonValue(payloadString, "existing_software_version");
- String newSoftware = JsonUtils.getJsonValue(payloadString, "new_software_version");
- configParams.setExistingSoftwareVersion(existingSoftware);
- configParams.setNewSoftwareVersion(newSoftware);
- configParams.setVnfName(vnfName);
- payloadResult.setConfigurationParameters(configParams);
- return Optional.of(mapper.writeValueAsString(payloadResult));
- }
-
- public static Optional<String> resumeTrafficFormat(String vnfName) throws JsonProcessingException{
- ResumeTrafficAction payloadResult = new ResumeTrafficAction();
- ConfigurationParametersResumeTraffic configParams = new ConfigurationParametersResumeTraffic();
- configParams.setVnfName(vnfName);
- payloadResult.setConfigurationParameters(configParams);
- return Optional.of(mapper.writeValueAsString(payloadResult));
- }
-
- public static Optional<String> quiesceTrafficFormat(Optional<String> payload, String vnfName) throws JsonProcessingException{
- QuiesceTrafficAction payloadResult = new QuiesceTrafficAction();
- ConfigurationParametersQuiesce configParams = new ConfigurationParametersQuiesce();
- String payloadString = payload.isPresent() ? payload.get() : "";
- String operationsTimeout = JsonUtils.getJsonValue(payloadString, "operations_timeout");
- configParams.setOperationsTimeout(operationsTimeout);
- configParams.setVnfName(vnfName);
- payloadResult.setConfigurationParameters(configParams);
- return Optional.of(mapper.writeValueAsString(payloadResult));
- }
-
- public static Optional<String> startStopFormat(String aicIdentity) throws JsonProcessingException{
- StartStopAction payloadResult = new StartStopAction();
- payloadResult.setAicIdentity(aicIdentity);
- return Optional.of(mapper.writeValueAsString(payloadResult));
- }
-
- public static Optional<String> healthCheckFormat(String vnfName, String vnfHostIpAddress) throws JsonProcessingException{
- HealthCheckAction payloadResult = new HealthCheckAction();
- RequestParametersHealthCheck requestParams = new RequestParametersHealthCheck();
- requestParams.setHostIpAddress(vnfHostIpAddress);
- payloadResult.setRequestParameters(requestParams);
- return Optional.of((mapper.writeValueAsString(payloadResult)));
- }
-
- public static Optional<String> snapshotFormat(String vmId, String identityUrl)throws JsonProcessingException{
- SnapshotAction payloadResult = new SnapshotAction();
- payloadResult.setVmId(vmId);
- payloadResult.setIdentityUrl(identityUrl);
- return Optional.of(mapper.writeValueAsString(payloadResult));
- }
-
+ protected static ObjectMapper mapper = new ObjectMapper();
+
+ private PayloadClient() {}
+
+ public static Optional<String> upgradeFormat(Optional<String> payload, String vnfName)
+ throws JsonProcessingException {
+ UpgradeAction payloadResult = new UpgradeAction();
+ ConfigurationParametersUpgrade configParams = new ConfigurationParametersUpgrade();
+ String payloadString = payload.isPresent() ? payload.get() : "";
+ String existingSoftware = JsonUtils.getJsonValue(payloadString, "existing_software_version");
+ String newSoftware = JsonUtils.getJsonValue(payloadString, "new_software_version");
+ configParams.setExistingSoftwareVersion(existingSoftware);
+ configParams.setNewSoftwareVersion(newSoftware);
+ configParams.setVnfName(vnfName);
+ payloadResult.setConfigurationParameters(configParams);
+ return Optional.of(mapper.writeValueAsString(payloadResult));
+ }
+
+ public static Optional<String> resumeTrafficFormat(String vnfName) throws JsonProcessingException {
+ ResumeTrafficAction payloadResult = new ResumeTrafficAction();
+ ConfigurationParametersResumeTraffic configParams = new ConfigurationParametersResumeTraffic();
+ configParams.setVnfName(vnfName);
+ payloadResult.setConfigurationParameters(configParams);
+ return Optional.of(mapper.writeValueAsString(payloadResult));
+ }
+
+ public static Optional<String> quiesceTrafficFormat(Optional<String> payload, String vnfName)
+ throws JsonProcessingException {
+ QuiesceTrafficAction payloadResult = new QuiesceTrafficAction();
+ ConfigurationParametersQuiesce configParams = new ConfigurationParametersQuiesce();
+ String payloadString = payload.isPresent() ? payload.get() : "";
+ String operationsTimeout = JsonUtils.getJsonValue(payloadString, "operations_timeout");
+ configParams.setOperationsTimeout(operationsTimeout);
+ configParams.setVnfName(vnfName);
+ payloadResult.setConfigurationParameters(configParams);
+ return Optional.of(mapper.writeValueAsString(payloadResult));
+ }
+
+ public static Optional<String> startStopFormat(String aicIdentity) throws JsonProcessingException {
+ StartStopAction payloadResult = new StartStopAction();
+ payloadResult.setAicIdentity(aicIdentity);
+ return Optional.of(mapper.writeValueAsString(payloadResult));
+ }
+
+ public static Optional<String> healthCheckFormat(String vnfName, String vnfHostIpAddress)
+ throws JsonProcessingException {
+ HealthCheckAction payloadResult = new HealthCheckAction();
+ RequestParametersHealthCheck requestParams = new RequestParametersHealthCheck();
+ requestParams.setHostIpAddress(vnfHostIpAddress);
+ payloadResult.setRequestParameters(requestParams);
+ return Optional.of((mapper.writeValueAsString(payloadResult)));
+ }
+
+ public static Optional<String> snapshotFormat(String vmId, String identityUrl) throws JsonProcessingException {
+ SnapshotAction payloadResult = new SnapshotAction();
+ payloadResult.setVmId(vmId);
+ payloadResult.setIdentityUrl(identityUrl);
+ return Optional.of(mapper.writeValueAsString(payloadResult));
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigModifyAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigModifyAction.java
index 3c39a8d66c..4ca99c3b34 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigModifyAction.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigModifyAction.java
@@ -25,35 +25,32 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"request-parameters",
-"configuration-parameters"
-})
+@JsonPropertyOrder({"request-parameters", "configuration-parameters"})
public class ConfigModifyAction {
-@JsonProperty("request-parameters")
-private RequestParametersConfigModify requestParameters;
-@JsonProperty("configuration-parameters")
-private ConfigurationParametersConfigModify configurationParameters;
-
-@JsonProperty("request-parameters")
-public RequestParametersConfigModify getRequestParameters() {
-return requestParameters;
-}
-
-@JsonProperty("request-parameters")
-public void setRequestParameters(RequestParametersConfigModify requestParameters) {
-this.requestParameters = requestParameters;
-}
-
-@JsonProperty("configuration-parameters")
-public ConfigurationParametersConfigModify getConfigurationParameters() {
-return configurationParameters;
-}
-
-@JsonProperty("configuration-parameters")
-public void setConfigurationParameters(ConfigurationParametersConfigModify configurationParameters) {
-this.configurationParameters = configurationParameters;
-}
+ @JsonProperty("request-parameters")
+ private RequestParametersConfigModify requestParameters;
+ @JsonProperty("configuration-parameters")
+ private ConfigurationParametersConfigModify configurationParameters;
+
+ @JsonProperty("request-parameters")
+ public RequestParametersConfigModify getRequestParameters() {
+ return requestParameters;
+ }
+
+ @JsonProperty("request-parameters")
+ public void setRequestParameters(RequestParametersConfigModify requestParameters) {
+ this.requestParameters = requestParameters;
+ }
+
+ @JsonProperty("configuration-parameters")
+ public ConfigurationParametersConfigModify getConfigurationParameters() {
+ return configurationParameters;
+ }
+
+ @JsonProperty("configuration-parameters")
+ public void setConfigurationParameters(ConfigurationParametersConfigModify configurationParameters) {
+ this.configurationParameters = configurationParameters;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigScaleOutPayload.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigScaleOutPayload.java
index 9035f4d506..aa50a90265 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigScaleOutPayload.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigScaleOutPayload.java
@@ -1,19 +1,15 @@
-/* ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/*
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -21,38 +17,37 @@ package org.onap.so.bpmn.appc.payload.beans;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class ConfigScaleOutPayload {
- @JsonProperty("request-parameters")
- private RequestParametersConfigScaleOut requestParameters;
- @JsonProperty("configuration-parameters")
- private Map<String, String> configurationParameters = new HashMap<>();
-
- public RequestParametersConfigScaleOut getRequestParameters() {
- return requestParameters;
- }
-
- public void setRequestParameters(RequestParametersConfigScaleOut requestParameters) {
- this.requestParameters = requestParameters;
- }
-
- public Map<String, String> getConfigurationParameters() {
- return configurationParameters;
- }
-
- public void setConfigurationParameters(Map<String, String> configurationParameters) {
- this.configurationParameters = configurationParameters;
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder("ConfigScaleOutPayload{");
- sb.append("requestParameters=").append(requestParameters);
- sb.append(", configurationParameters='").append(configurationParameters);
- sb.append('}');
- return sb.toString();
- }
+ @JsonProperty("request-parameters")
+ private RequestParametersConfigScaleOut requestParameters;
+ @JsonProperty("configuration-parameters")
+ private Map<String, String> configurationParameters = new HashMap<>();
+
+ public RequestParametersConfigScaleOut getRequestParameters() {
+ return requestParameters;
+ }
+
+ public void setRequestParameters(RequestParametersConfigScaleOut requestParameters) {
+ this.requestParameters = requestParameters;
+ }
+
+ public Map<String, String> getConfigurationParameters() {
+ return configurationParameters;
+ }
+
+ public void setConfigurationParameters(Map<String, String> configurationParameters) {
+ this.configurationParameters = configurationParameters;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("ConfigScaleOutPayload{");
+ sb.append("requestParameters=").append(requestParameters);
+ sb.append(", configurationParameters='").append(configurationParameters);
+ sb.append('}');
+ return sb.toString();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersConfigModify.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersConfigModify.java
index c88169bb80..422a49c5ed 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersConfigModify.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersConfigModify.java
@@ -25,34 +25,31 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"node0_hostname",
-"node0_backup_router_address"
-})
+@JsonPropertyOrder({"node0_hostname", "node0_backup_router_address"})
public class ConfigurationParametersConfigModify {
-@JsonProperty("node0_hostname")
-private String node0Hostname;
-@JsonProperty("node0_backup_router_address")
-private String node0BackupRouterAddress;
-
-@JsonProperty("node0_hostname")
-public String getNode0Hostname() {
-return node0Hostname;
-}
-
-@JsonProperty("node0_hostname")
-public void setNode0Hostname(String node0Hostname) {
-this.node0Hostname = node0Hostname;
-}
-
-@JsonProperty("node0_backup_router_address")
-public String getNode0BackupRouterAddress() {
-return node0BackupRouterAddress;
-}
-
-@JsonProperty("node0_backup_router_address")
-public void setNode0BackupRouterAddress(String node0BackupRouterAddress) {
-this.node0BackupRouterAddress = node0BackupRouterAddress;
-}
+ @JsonProperty("node0_hostname")
+ private String node0Hostname;
+ @JsonProperty("node0_backup_router_address")
+ private String node0BackupRouterAddress;
+
+ @JsonProperty("node0_hostname")
+ public String getNode0Hostname() {
+ return node0Hostname;
+ }
+
+ @JsonProperty("node0_hostname")
+ public void setNode0Hostname(String node0Hostname) {
+ this.node0Hostname = node0Hostname;
+ }
+
+ @JsonProperty("node0_backup_router_address")
+ public String getNode0BackupRouterAddress() {
+ return node0BackupRouterAddress;
+ }
+
+ @JsonProperty("node0_backup_router_address")
+ public void setNode0BackupRouterAddress(String node0BackupRouterAddress) {
+ this.node0BackupRouterAddress = node0BackupRouterAddress;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersHealthCheck.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersHealthCheck.java
index a8964f3bc5..8c9e636d9e 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersHealthCheck.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersHealthCheck.java
@@ -25,21 +25,19 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"vnf_name"
-})
+@JsonPropertyOrder({"vnf_name"})
public class ConfigurationParametersHealthCheck {
-@JsonProperty("vnf_name")
-private String vnfName;
+ @JsonProperty("vnf_name")
+ private String vnfName;
-@JsonProperty("vnf_name")
-public String getVnfName() {
-return vnfName;
-}
+ @JsonProperty("vnf_name")
+ public String getVnfName() {
+ return vnfName;
+ }
-@JsonProperty("vnf_name")
-public void setVnfName(String vnfName) {
-this.vnfName = vnfName;
-}
+ @JsonProperty("vnf_name")
+ public void setVnfName(String vnfName) {
+ this.vnfName = vnfName;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersQuiesce.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersQuiesce.java
index 878a136962..2a6ff4874a 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersQuiesce.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersQuiesce.java
@@ -25,35 +25,32 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"vnf_name",
-"operations_timeout"
-})
+@JsonPropertyOrder({"vnf_name", "operations_timeout"})
public class ConfigurationParametersQuiesce {
-@JsonProperty("vnf_name")
-private String vnfName;
-@JsonProperty("operations_timeout")
-private String operationsTimeout;
-
-@JsonProperty("vnf_name")
-public String getVnfName() {
-return vnfName;
-}
-
-@JsonProperty("vnf_name")
-public void setVnfName(String vnfName) {
-this.vnfName = vnfName;
-}
-
-@JsonProperty("operations_timeout")
-public String getOperationsTimeout() {
-return operationsTimeout;
-}
-
-@JsonProperty("operations_timeout")
-public void setOperationsTimeout(String operationsTimeout) {
-this.operationsTimeout = operationsTimeout;
-}
+ @JsonProperty("vnf_name")
+ private String vnfName;
+ @JsonProperty("operations_timeout")
+ private String operationsTimeout;
+
+ @JsonProperty("vnf_name")
+ public String getVnfName() {
+ return vnfName;
+ }
+
+ @JsonProperty("vnf_name")
+ public void setVnfName(String vnfName) {
+ this.vnfName = vnfName;
+ }
+
+ @JsonProperty("operations_timeout")
+ public String getOperationsTimeout() {
+ return operationsTimeout;
+ }
+
+ @JsonProperty("operations_timeout")
+ public void setOperationsTimeout(String operationsTimeout) {
+ this.operationsTimeout = operationsTimeout;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersResumeTraffic.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersResumeTraffic.java
index 6b5e59f2e0..3875450c7d 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersResumeTraffic.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersResumeTraffic.java
@@ -25,21 +25,19 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"vnf_name"
-})
+@JsonPropertyOrder({"vnf_name"})
public class ConfigurationParametersResumeTraffic {
-@JsonProperty("vnf_name")
-private String vnfName;
+ @JsonProperty("vnf_name")
+ private String vnfName;
-@JsonProperty("vnf_name")
-public String getVnfName() {
-return vnfName;
-}
+ @JsonProperty("vnf_name")
+ public String getVnfName() {
+ return vnfName;
+ }
-@JsonProperty("vnf_name")
-public void setVnfName(String vnfName) {
-this.vnfName = vnfName;
-}
+ @JsonProperty("vnf_name")
+ public void setVnfName(String vnfName) {
+ this.vnfName = vnfName;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersUpgrade.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersUpgrade.java
index 6bd397a63a..1f1bdf91d5 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersUpgrade.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersUpgrade.java
@@ -25,47 +25,43 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"vnf_name",
-"existing_software_version",
-"new_software_version"
-})
+@JsonPropertyOrder({"vnf_name", "existing_software_version", "new_software_version"})
public class ConfigurationParametersUpgrade {
-@JsonProperty("vnf_name")
-private String vnfName;
-@JsonProperty("existing_software_version")
-private String existingSoftwareVersion;
-@JsonProperty("new_software_version")
-private String newSoftwareVersion;
+ @JsonProperty("vnf_name")
+ private String vnfName;
+ @JsonProperty("existing_software_version")
+ private String existingSoftwareVersion;
+ @JsonProperty("new_software_version")
+ private String newSoftwareVersion;
-@JsonProperty("vnf_name")
-public String getVnfName() {
-return vnfName;
-}
+ @JsonProperty("vnf_name")
+ public String getVnfName() {
+ return vnfName;
+ }
-@JsonProperty("vnf_name")
-public void setVnfName(String vnfName) {
-this.vnfName = vnfName;
-}
+ @JsonProperty("vnf_name")
+ public void setVnfName(String vnfName) {
+ this.vnfName = vnfName;
+ }
-@JsonProperty("existing_software_version")
-public String getExistingSoftwareVersion() {
-return existingSoftwareVersion;
-}
+ @JsonProperty("existing_software_version")
+ public String getExistingSoftwareVersion() {
+ return existingSoftwareVersion;
+ }
-@JsonProperty("existing_software_version")
-public void setExistingSoftwareVersion(String existingSoftwareVersion) {
-this.existingSoftwareVersion = existingSoftwareVersion;
-}
+ @JsonProperty("existing_software_version")
+ public void setExistingSoftwareVersion(String existingSoftwareVersion) {
+ this.existingSoftwareVersion = existingSoftwareVersion;
+ }
-@JsonProperty("new_software_version")
-public String getNewSoftwareVersion() {
-return newSoftwareVersion;
-}
+ @JsonProperty("new_software_version")
+ public String getNewSoftwareVersion() {
+ return newSoftwareVersion;
+ }
-@JsonProperty("new_software_version")
-public void setNewSoftwareVersion(String newSoftwareVersion) {
-this.newSoftwareVersion = newSoftwareVersion;
-}
+ @JsonProperty("new_software_version")
+ public void setNewSoftwareVersion(String newSoftwareVersion) {
+ this.newSoftwareVersion = newSoftwareVersion;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/HealthCheckAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/HealthCheckAction.java
index 4d194650c4..0964a09cb9 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/HealthCheckAction.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/HealthCheckAction.java
@@ -25,34 +25,31 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"request-parameters",
-"configuration-parameters"
-})
+@JsonPropertyOrder({"request-parameters", "configuration-parameters"})
public class HealthCheckAction {
-@JsonProperty("request-parameters")
-private RequestParametersHealthCheck requestParameters;
-@JsonProperty("configuration-parameters")
-private ConfigurationParametersHealthCheck configurationParameters;
-
-@JsonProperty("request-parameters")
-public RequestParametersHealthCheck getRequestParameters() {
-return requestParameters;
-}
-
-@JsonProperty("request-parameters")
-public void setRequestParameters(RequestParametersHealthCheck requestParameters) {
-this.requestParameters = requestParameters;
-}
-
-@JsonProperty("configuration-parameters")
-public ConfigurationParametersHealthCheck getConfigurationParameters() {
-return configurationParameters;
-}
-
-@JsonProperty("configuration-parameters")
-public void setConfigurationParameters(ConfigurationParametersHealthCheck configurationParameters) {
-this.configurationParameters = configurationParameters;
-}
+ @JsonProperty("request-parameters")
+ private RequestParametersHealthCheck requestParameters;
+ @JsonProperty("configuration-parameters")
+ private ConfigurationParametersHealthCheck configurationParameters;
+
+ @JsonProperty("request-parameters")
+ public RequestParametersHealthCheck getRequestParameters() {
+ return requestParameters;
+ }
+
+ @JsonProperty("request-parameters")
+ public void setRequestParameters(RequestParametersHealthCheck requestParameters) {
+ this.requestParameters = requestParameters;
+ }
+
+ @JsonProperty("configuration-parameters")
+ public ConfigurationParametersHealthCheck getConfigurationParameters() {
+ return configurationParameters;
+ }
+
+ @JsonProperty("configuration-parameters")
+ public void setConfigurationParameters(ConfigurationParametersHealthCheck configurationParameters) {
+ this.configurationParameters = configurationParameters;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/QuiesceTrafficAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/QuiesceTrafficAction.java
index 0b16c6ca90..7125ad77b8 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/QuiesceTrafficAction.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/QuiesceTrafficAction.java
@@ -25,21 +25,19 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"configuration-parameters"
-})
+@JsonPropertyOrder({"configuration-parameters"})
public class QuiesceTrafficAction {
-@JsonProperty("configuration-parameters")
-private ConfigurationParametersQuiesce configurationParameters;
+ @JsonProperty("configuration-parameters")
+ private ConfigurationParametersQuiesce configurationParameters;
-@JsonProperty("configuration-parameters")
-public ConfigurationParametersQuiesce getConfigurationParameters() {
-return configurationParameters;
-}
+ @JsonProperty("configuration-parameters")
+ public ConfigurationParametersQuiesce getConfigurationParameters() {
+ return configurationParameters;
+ }
-@JsonProperty("configuration-parameters")
-public void setConfigurationParameters(ConfigurationParametersQuiesce configurationParameters) {
-this.configurationParameters = configurationParameters;
-}
+ @JsonProperty("configuration-parameters")
+ public void setConfigurationParameters(ConfigurationParametersQuiesce configurationParameters) {
+ this.configurationParameters = configurationParameters;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersConfigModify.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersConfigModify.java
index 58c9234d60..2b314cb580 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersConfigModify.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersConfigModify.java
@@ -25,22 +25,20 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"vnf-host-ip-address"
-})
+@JsonPropertyOrder({"vnf-host-ip-address"})
public class RequestParametersConfigModify {
-@JsonProperty("vnf-host-ip-address")
-private String vnfHostIpAddress;
+ @JsonProperty("vnf-host-ip-address")
+ private String vnfHostIpAddress;
-@JsonProperty("vnf-host-ip-address")
-public String getVnfHostIpAddress() {
-return vnfHostIpAddress;
-}
+ @JsonProperty("vnf-host-ip-address")
+ public String getVnfHostIpAddress() {
+ return vnfHostIpAddress;
+ }
-@JsonProperty("vnf-host-ip-address")
-public void setVnfHostIpAddress(String vnfHostIpAddress) {
-this.vnfHostIpAddress = vnfHostIpAddress;
-}
+ @JsonProperty("vnf-host-ip-address")
+ public void setVnfHostIpAddress(String vnfHostIpAddress) {
+ this.vnfHostIpAddress = vnfHostIpAddress;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersConfigScaleOut.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersConfigScaleOut.java
index 0333fd7a78..1a9e04b9e2 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersConfigScaleOut.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersConfigScaleOut.java
@@ -1,19 +1,15 @@
-/* ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/*
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -23,33 +19,33 @@ import com.fasterxml.jackson.annotation.JsonProperty;
public class RequestParametersConfigScaleOut {
- @JsonProperty("vnf-host-ip-address")
- private String vnfHostIpAddress;
- @JsonProperty("vf-module-id")
- private String vfModuleId;
-
- public String getVnfHostIpAddress() {
- return vnfHostIpAddress;
- }
-
- public void setVnfHostIpAddress(String vnfHostIpAddress) {
- this.vnfHostIpAddress = vnfHostIpAddress;
- }
-
- public String getVfModuleId() {
- return vfModuleId;
- }
-
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder("RequestParametersConfigScaleOut{");
- sb.append("vnf-host-ip-address=").append(vnfHostIpAddress);
- sb.append(", vf-module-id='").append(vfModuleId);
- sb.append('}');
- return sb.toString();
- }
+ @JsonProperty("vnf-host-ip-address")
+ private String vnfHostIpAddress;
+ @JsonProperty("vf-module-id")
+ private String vfModuleId;
+
+ public String getVnfHostIpAddress() {
+ return vnfHostIpAddress;
+ }
+
+ public void setVnfHostIpAddress(String vnfHostIpAddress) {
+ this.vnfHostIpAddress = vnfHostIpAddress;
+ }
+
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("RequestParametersConfigScaleOut{");
+ sb.append("vnf-host-ip-address=").append(vnfHostIpAddress);
+ sb.append(", vf-module-id='").append(vfModuleId);
+ sb.append('}');
+ return sb.toString();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersHealthCheck.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersHealthCheck.java
index 60030ee3dd..2fe8e744f9 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersHealthCheck.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/RequestParametersHealthCheck.java
@@ -25,34 +25,32 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"vnf-name"
-})
+@JsonPropertyOrder({"vnf-name"})
public class RequestParametersHealthCheck {
-@JsonProperty("vnf-name")
-private String vnfName;
-@JsonProperty("host-ip-address")
-private String hostIpAddress;
-
-@JsonProperty("vnf-name")
-public String getVnfName() {
- return vnfName;
-}
-
-@JsonProperty("vnf-name")
-public void setVnfName(String vnfName) {
- this.vnfName = vnfName;
-}
-
-@JsonProperty("host-ip-address")
-public void setHostIpAddress(String hostIpAddress) {
- this.hostIpAddress = hostIpAddress;
-}
-
-@JsonProperty("host-ip-address")
-public String getHostIpAddress() {
- return hostIpAddress;
-}
+ @JsonProperty("vnf-name")
+ private String vnfName;
+ @JsonProperty("host-ip-address")
+ private String hostIpAddress;
+
+ @JsonProperty("vnf-name")
+ public String getVnfName() {
+ return vnfName;
+ }
+
+ @JsonProperty("vnf-name")
+ public void setVnfName(String vnfName) {
+ this.vnfName = vnfName;
+ }
+
+ @JsonProperty("host-ip-address")
+ public void setHostIpAddress(String hostIpAddress) {
+ this.hostIpAddress = hostIpAddress;
+ }
+
+ @JsonProperty("host-ip-address")
+ public String getHostIpAddress() {
+ return hostIpAddress;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ResumeTrafficAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ResumeTrafficAction.java
index b642a376fe..5afdc4198a 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ResumeTrafficAction.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ResumeTrafficAction.java
@@ -25,21 +25,19 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"configuration-parameters"
-})
+@JsonPropertyOrder({"configuration-parameters"})
public class ResumeTrafficAction {
-@JsonProperty("configuration-parameters")
-private ConfigurationParametersResumeTraffic configurationParameters;
+ @JsonProperty("configuration-parameters")
+ private ConfigurationParametersResumeTraffic configurationParameters;
-@JsonProperty("configuration-parameters")
-public ConfigurationParametersResumeTraffic getConfigurationParameters() {
-return configurationParameters;
-}
+ @JsonProperty("configuration-parameters")
+ public ConfigurationParametersResumeTraffic getConfigurationParameters() {
+ return configurationParameters;
+ }
-@JsonProperty("configuration-parameters")
-public void setConfigurationParameters(ConfigurationParametersResumeTraffic configurationParameters) {
-this.configurationParameters = configurationParameters;
-}
+ @JsonProperty("configuration-parameters")
+ public void setConfigurationParameters(ConfigurationParametersResumeTraffic configurationParameters) {
+ this.configurationParameters = configurationParameters;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/SnapshotAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/SnapshotAction.java
index 0499e5d6c0..431c97814e 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/SnapshotAction.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/SnapshotAction.java
@@ -25,35 +25,32 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"vm-id",
-"identity-url"
-})
+@JsonPropertyOrder({"vm-id", "identity-url"})
public class SnapshotAction {
-@JsonProperty("vm-id")
-private String vmId;
-@JsonProperty("identity-url")
-private String identityUrl;
-
-@JsonProperty("vm-id")
-public String getVmId() {
-return vmId;
-}
-
-@JsonProperty("vm-id")
-public void setVmId(String vmId) {
-this.vmId = vmId;
-}
-
-@JsonProperty("identity-url")
-public String getIdentityUrl() {
-return identityUrl;
-}
-
-@JsonProperty("identity-url")
-public void setIdentityUrl(String identityUrl) {
-this.identityUrl = identityUrl;
-}
+ @JsonProperty("vm-id")
+ private String vmId;
+ @JsonProperty("identity-url")
+ private String identityUrl;
+
+ @JsonProperty("vm-id")
+ public String getVmId() {
+ return vmId;
+ }
+
+ @JsonProperty("vm-id")
+ public void setVmId(String vmId) {
+ this.vmId = vmId;
+ }
+
+ @JsonProperty("identity-url")
+ public String getIdentityUrl() {
+ return identityUrl;
+ }
+
+ @JsonProperty("identity-url")
+ public void setIdentityUrl(String identityUrl) {
+ this.identityUrl = identityUrl;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/StartStopAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/StartStopAction.java
index f2b5b905a5..58231c0602 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/StartStopAction.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/StartStopAction.java
@@ -25,21 +25,19 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- " AICIdentity "
-})
+@JsonPropertyOrder({" AICIdentity "})
public class StartStopAction {
- @JsonProperty(" AICIdentity ")
- private String aicIdentity;
+ @JsonProperty(" AICIdentity ")
+ private String aicIdentity;
- @JsonProperty(" AICIdentity ")
- public String getAicIdentity() {
- return aicIdentity;
- }
+ @JsonProperty(" AICIdentity ")
+ public String getAicIdentity() {
+ return aicIdentity;
+ }
- @JsonProperty(" AICIdentity ")
- public void setAicIdentity(String aicIdentity) {
- this.aicIdentity = aicIdentity;
- }
+ @JsonProperty(" AICIdentity ")
+ public void setAicIdentity(String aicIdentity) {
+ this.aicIdentity = aicIdentity;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/UpgradeAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/UpgradeAction.java
index 3e07f328ce..e6a60a52f5 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/UpgradeAction.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/UpgradeAction.java
@@ -25,21 +25,19 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"configuration-parameters"
-})
+@JsonPropertyOrder({"configuration-parameters"})
public class UpgradeAction {
-@JsonProperty("configuration-parameters")
-private ConfigurationParametersUpgrade configurationParameters;
+ @JsonProperty("configuration-parameters")
+ private ConfigurationParametersUpgrade configurationParameters;
-@JsonProperty("configuration-parameters")
-public ConfigurationParametersUpgrade getConfigurationParameters() {
-return configurationParameters;
-}
+ @JsonProperty("configuration-parameters")
+ public ConfigurationParametersUpgrade getConfigurationParameters() {
+ return configurationParameters;
+ }
-@JsonProperty("configuration-parameters")
-public void setConfigurationParameters(ConfigurationParametersUpgrade configurationParameters) {
-this.configurationParameters = configurationParameters;
-}
+ @JsonProperty("configuration-parameters")
+ public void setConfigurationParameters(ConfigurationParametersUpgrade configurationParameters) {
+ this.configurationParameters = configurationParameters;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/BuildingBlockExecution.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/BuildingBlockExecution.java
index 1ffd9dd167..c087d586e7 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/BuildingBlockExecution.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/BuildingBlockExecution.java
@@ -22,17 +22,21 @@ package org.onap.so.bpmn.common;
import java.io.Serializable;
import java.util.Map;
-
import org.onap.so.bpmn.common.exceptions.RequiredExecutionVariableExeception;
import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
public interface BuildingBlockExecution {
- public GeneralBuildingBlock getGeneralBuildingBlock();
- public <T> T getVariable(String key);
- public <T> T getRequiredVariable(String key) throws RequiredExecutionVariableExeception;
- public void setVariable(String key, Serializable value);
- public Map<ResourceKey, String> getLookupMap();
- public String getFlowToBeCalled();
+ public GeneralBuildingBlock getGeneralBuildingBlock();
+
+ public <T> T getVariable(String key);
+
+ public <T> T getRequiredVariable(String key) throws RequiredExecutionVariableExeception;
+
+ public void setVariable(String key, Serializable value);
+
+ public Map<ResourceKey, String> getLookupMap();
+
+ public String getFlowToBeCalled();
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DefaultToShortClassNameBeanNameGenerator.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DefaultToShortClassNameBeanNameGenerator.java
index 5a126ffe7d..f09aae67d1 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DefaultToShortClassNameBeanNameGenerator.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DefaultToShortClassNameBeanNameGenerator.java
@@ -25,9 +25,9 @@ import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.util.ClassUtils;
public class DefaultToShortClassNameBeanNameGenerator extends AnnotationBeanNameGenerator {
-
- @Override
- protected String buildDefaultBeanName(BeanDefinition definition) {
- return ClassUtils.getShortName(definition.getBeanClassName());
- }
+
+ @Override
+ protected String buildDefaultBeanName(BeanDefinition definition) {
+ return ClassUtils.getShortName(definition.getBeanClassName());
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java
index 39a209efa8..31fef7c6f7 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java
@@ -23,14 +23,12 @@ package org.onap.so.bpmn.common;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.so.bpmn.common.exceptions.MalformedBuildingBlockInputException;
import org.onap.so.bpmn.common.exceptions.MissingBuildingBlockInputException;
import org.onap.so.bpmn.common.exceptions.RequiredExecutionVariableExeception;
import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/InjectExecution.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/InjectExecution.java
index 56b059ec16..036c054ed9 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/InjectExecution.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/InjectExecution.java
@@ -26,9 +26,9 @@ import org.springframework.stereotype.Component;
@Component
public class InjectExecution {
- public DelegateExecutionImpl execute (DelegateExecution execution, DelegateExecutionImpl impl) {
-
- impl.setDelegateExecution(execution);
- return impl;
- }
+ public DelegateExecutionImpl execute(DelegateExecution execution, DelegateExecutionImpl impl) {
+
+ impl.setDelegateExecution(execution);
+ return impl;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/InjectionHelper.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/InjectionHelper.java
index adf1dc01c0..3791c5d461 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/InjectionHelper.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/InjectionHelper.java
@@ -32,45 +32,42 @@ import org.onap.so.client.sdno.SDNOValidatorImpl;
import org.springframework.stereotype.Component;
/*
- * This object is intended to be a helper for acquiring classes
- * that cannot be acquired via Spring injection.
+ * This object is intended to be a helper for acquiring classes that cannot be acquired via Spring injection.
*
* It brings two benefits:
*
- * 1) Enforces acquisition of a new copy of these classes every
- * time to help with picking up properties files changes, etc
- * 2) The classes are exposed in such a way that mocks of them can
- * still be injected when testing the Spring objects that use
- * them
+ * 1) Enforces acquisition of a new copy of these classes every time to help with picking up properties files changes,
+ * etc 2) The classes are exposed in such a way that mocks of them can still be injected when testing the Spring objects
+ * that use them
*/
@Component
public class InjectionHelper {
- public AAIResourcesClient getAaiClient() {
- return new AAIResourcesClient();
- }
+ public AAIResourcesClient getAaiClient() {
+ return new AAIResourcesClient();
+ }
- public AAIQueryClient getAaiQueryClient() {
- return new AAIQueryClient();
- }
+ public AAIQueryClient getAaiQueryClient() {
+ return new AAIQueryClient();
+ }
- public SDNOValidator getSdnoValidator() {
- return new SDNOValidatorImpl();
- }
+ public SDNOValidator getSdnoValidator() {
+ return new SDNOValidatorImpl();
+ }
- public AAICommonObjectMapperProvider getAaiCommonObjectMapperProvider() {
- return new AAICommonObjectMapperProvider();
- }
+ public AAICommonObjectMapperProvider getAaiCommonObjectMapperProvider() {
+ return new AAICommonObjectMapperProvider();
+ }
- public AAIResultWrapper getAaiResultWrapper(String json) {
- return new AAIResultWrapper(json);
- }
+ public AAIResultWrapper getAaiResultWrapper(String json) {
+ return new AAIResultWrapper(json);
+ }
- public PolicyClientImpl getPolicyClient() {
- return new PolicyClientImpl();
- }
+ public PolicyClientImpl getPolicyClient() {
+ return new PolicyClientImpl();
+ }
- public CDSProcessingClient getCdsClient(CDSProcessingListener listener) {
- return new CDSProcessingClient(listener);
- }
+ public CDSProcessingClient getCdsClient(CDSProcessingListener listener) {
+ return new CDSProcessingClient(listener);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/baseclient/BaseClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/baseclient/BaseClient.java
index af93c1bfc0..73047cf961 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/baseclient/BaseClient.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/baseclient/BaseClient.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.common.baseclient;
import java.util.ArrayList;
import java.util.List;
-
import org.onap.so.logging.jaxrs.filter.SpringClientFilter;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
@@ -35,18 +34,18 @@ import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
-//TODO move to common location
-public class BaseClient<I,O> {
+// TODO move to common location
+public class BaseClient<I, O> {
+
+ private HttpHeaders httpHeader;
+ private String targetUrl;
- private HttpHeaders httpHeader;
- private String targetUrl;
+ public HttpHeaders getHttpHeader() {
+ return httpHeader;
+ }
- public HttpHeaders getHttpHeader() {
- return httpHeader;
- }
-
public HttpHeaders setDefaultHttpHeaders(String auth) {
- httpHeader = new HttpHeaders();
+ httpHeader = new HttpHeaders();
httpHeader.set("Authorization", auth);
httpHeader.setContentType(MediaType.APPLICATION_JSON);
List<MediaType> acceptMediaTypes = new ArrayList<MediaType>();
@@ -56,34 +55,36 @@ public class BaseClient<I,O> {
return httpHeader;
}
- public void setHttpHeader(HttpHeaders httpHeader) {
- this.httpHeader = httpHeader;
- }
+ public void setHttpHeader(HttpHeaders httpHeader) {
+ this.httpHeader = httpHeader;
+ }
- public String getTargetUrl() {
- return targetUrl;
- }
+ public String getTargetUrl() {
+ return targetUrl;
+ }
- public void setTargetUrl(String targetUrl) {
- this.targetUrl = targetUrl;
- }
+ public void setTargetUrl(String targetUrl) {
+ this.targetUrl = targetUrl;
+ }
- public O get(I data, ParameterizedTypeReference<O> typeRef, Object... uriVariables) throws RestClientException {
- return run(data, HttpMethod.GET, typeRef, uriVariables);
- }
+ public O get(I data, ParameterizedTypeReference<O> typeRef, Object... uriVariables) throws RestClientException {
+ return run(data, HttpMethod.GET, typeRef, uriVariables);
+ }
- public O post(I data, ParameterizedTypeReference<O> typeRef, Object... uriVariables) throws RestClientException {
- return run(data, HttpMethod.POST, typeRef, uriVariables);
- }
-
- public O run(I data, HttpMethod method, ParameterizedTypeReference<O> typeRef, Object... uriVariables) throws RestClientException {
- HttpEntity<I> requestEntity = new HttpEntity<I>(data, getHttpHeader());
- RestTemplate restTemplate = new RestTemplate();
- restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory()));
- restTemplate.getInterceptors().add(new SpringClientFilter());
- ResponseEntity<O> responseEntity = restTemplate.exchange(getTargetUrl(), method, requestEntity, typeRef,
- uriVariables);
- return responseEntity.getBody();
- }
+ public O post(I data, ParameterizedTypeReference<O> typeRef, Object... uriVariables) throws RestClientException {
+ return run(data, HttpMethod.POST, typeRef, uriVariables);
+ }
+
+ public O run(I data, HttpMethod method, ParameterizedTypeReference<O> typeRef, Object... uriVariables)
+ throws RestClientException {
+ HttpEntity<I> requestEntity = new HttpEntity<I>(data, getHttpHeader());
+ RestTemplate restTemplate = new RestTemplate();
+ restTemplate
+ .setRequestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory()));
+ restTemplate.getInterceptors().add(new SpringClientFilter());
+ ResponseEntity<O> responseEntity =
+ restTemplate.exchange(getTargetUrl(), method, requestEntity, typeRef, uriVariables);
+ return responseEntity.getBody();
+ }
-} \ No newline at end of file
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/MalformedBuildingBlockInputException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/MalformedBuildingBlockInputException.java
index 1da989bfb7..cedb8ecc33 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/MalformedBuildingBlockInputException.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/MalformedBuildingBlockInputException.java
@@ -21,27 +21,26 @@
package org.onap.so.bpmn.common.exceptions;
public class MalformedBuildingBlockInputException extends RuntimeException {
- private static final long serialVersionUID = -9168146273898271648L;
+ private static final long serialVersionUID = -9168146273898271648L;
- public MalformedBuildingBlockInputException() {
- super();
- }
+ public MalformedBuildingBlockInputException() {
+ super();
+ }
- public MalformedBuildingBlockInputException(String message) {
- super(message);
- }
+ public MalformedBuildingBlockInputException(String message) {
+ super(message);
+ }
- public MalformedBuildingBlockInputException(String message, Throwable cause) {
- super(message, cause);
- }
+ public MalformedBuildingBlockInputException(String message, Throwable cause) {
+ super(message, cause);
+ }
- public MalformedBuildingBlockInputException(Throwable cause) {
- super(cause);
- }
+ public MalformedBuildingBlockInputException(Throwable cause) {
+ super(cause);
+ }
- protected MalformedBuildingBlockInputException(String message, Throwable cause,
- boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
+ protected MalformedBuildingBlockInputException(String message, Throwable cause, boolean enableSuppression,
+ boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/MissingBuildingBlockInputException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/MissingBuildingBlockInputException.java
index 5ad28a5ba0..fdae8f64f8 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/MissingBuildingBlockInputException.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/MissingBuildingBlockInputException.java
@@ -21,27 +21,26 @@
package org.onap.so.bpmn.common.exceptions;
public class MissingBuildingBlockInputException extends RuntimeException {
- private static final long serialVersionUID = 7098084383189271401L;
+ private static final long serialVersionUID = 7098084383189271401L;
- public MissingBuildingBlockInputException() {
- super();
- }
+ public MissingBuildingBlockInputException() {
+ super();
+ }
- public MissingBuildingBlockInputException(String message) {
- super(message);
- }
+ public MissingBuildingBlockInputException(String message) {
+ super(message);
+ }
- public MissingBuildingBlockInputException(String message, Throwable cause) {
- super(message, cause);
- }
+ public MissingBuildingBlockInputException(String message, Throwable cause) {
+ super(message, cause);
+ }
- public MissingBuildingBlockInputException(Throwable cause) {
- super(cause);
- }
+ public MissingBuildingBlockInputException(Throwable cause) {
+ super(cause);
+ }
- protected MissingBuildingBlockInputException(String message, Throwable cause,
- boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
+ protected MissingBuildingBlockInputException(String message, Throwable cause, boolean enableSuppression,
+ boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/RequiredExecutionVariableExeception.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/RequiredExecutionVariableExeception.java
index 8c77bb445e..558ab27764 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/RequiredExecutionVariableExeception.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/exceptions/RequiredExecutionVariableExeception.java
@@ -22,17 +22,17 @@ package org.onap.so.bpmn.common.exceptions;
public class RequiredExecutionVariableExeception extends Exception {
- private static final long serialVersionUID = 5135274986874563746L;
+ private static final long serialVersionUID = 5135274986874563746L;
- public RequiredExecutionVariableExeception(String message) {
- super(message);
- }
-
- public RequiredExecutionVariableExeception(String message, Throwable t) {
- super(message, t);
- }
-
- public RequiredExecutionVariableExeception(Throwable t) {
- super(t);
- }
+ public RequiredExecutionVariableExeception(String message) {
+ super(message);
+ }
+
+ public RequiredExecutionVariableExeception(String message, Throwable t) {
+ super(message, t);
+ }
+
+ public RequiredExecutionVariableExeception(Throwable t) {
+ super(t);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnIntegerParam.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnIntegerParam.java
index 80479e19c0..8281fd9974 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnIntegerParam.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnIntegerParam.java
@@ -23,26 +23,25 @@ import com.fasterxml.jackson.annotation.JsonProperty;
public class BpmnIntegerParam {
- @JsonProperty("value")
- private int value;
- @JsonProperty("type")
- private final String type = "Integer";
+ @JsonProperty("value")
+ private int value;
+ @JsonProperty("type")
+ private final String type = "Integer";
- public BpmnIntegerParam() {
- }
+ public BpmnIntegerParam() {}
- @JsonProperty("value")
- public int getValue() {
- return value;
- }
+ @JsonProperty("value")
+ public int getValue() {
+ return value;
+ }
- @JsonProperty("type")
- public void setValue(int value) {
- this.value = value;
- }
+ @JsonProperty("type")
+ public void setValue(int value) {
+ this.value = value;
+ }
- @Override
- public String toString() {
- return "CamundaInput [value=" + Integer.toString(value) + ", type=" + type + "]";
- }
+ @Override
+ public String toString() {
+ return "CamundaInput [value=" + Integer.toString(value) + ", type=" + type + "]";
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnParam.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnParam.java
index 01285cd5ec..79b0f415ff 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnParam.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnParam.java
@@ -19,36 +19,37 @@
*/
package org.onap.so.bpmn.common.recipe;
+
import com.fasterxml.jackson.annotation.JsonProperty;
/**
- * The bpmn workflow input param object
+ * The bpmn workflow input param object
*/
public class BpmnParam {
-
- @JsonProperty("value")
- private String value;
- @JsonProperty("type")
- private String type = "String";
-
-
- public BpmnParam() {
- /* Empty constructor */
- }
-
- @JsonProperty("value")
- public String getValue() {
- return value;
- }
-
- @JsonProperty("value")
- public void setValue(String value) {
- this.value = value;
- }
-
- @Override
- public String toString() {
- return "CamundaInput [value=" + value + ", type=" + type + "]";
- }
-
+
+ @JsonProperty("value")
+ private String value;
+ @JsonProperty("type")
+ private String type = "String";
+
+
+ public BpmnParam() {
+ /* Empty constructor */
+ }
+
+ @JsonProperty("value")
+ public String getValue() {
+ return value;
+ }
+
+ @JsonProperty("value")
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return "CamundaInput [value=" + value + ", type=" + type + "]";
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java
index 526f5d5288..b9200e0640 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java
@@ -24,9 +24,7 @@ package org.onap.so.bpmn.common.recipe;
import java.io.IOException;
import java.security.GeneralSecurityException;
-
import javax.xml.bind.DatatypeConverter;
-
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
@@ -44,9 +42,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
- * Support to call resource recipes from the BPMN workflow.
- * Such as call resource recipe in service workflow.
- * <br>
+ * Support to call resource recipes from the BPMN workflow. Such as call resource recipe in service workflow. <br>
* <p>
* </p>
*
@@ -66,13 +62,13 @@ public class BpmnRestClient {
public static final String CAMUNDA_AUTH = "mso.camundaAuth";
- private static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
+ private static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
@Autowired
private UrnPropertiesReader urnPropertiesReader;
private static boolean noProperties = true;
- //because for NS it will take a long time the time out of the resouce will be 2 hours.
+ // because for NS it will take a long time the time out of the resouce will be 2 hours.
private static final String DEFAULT_TIME_OUT = "7200";
public synchronized final boolean getNoPropertiesState() {
@@ -80,8 +76,7 @@ public class BpmnRestClient {
}
/**
- * post the recipe Uri
- * <br>
+ * post the recipe Uri <br>
*
* @param recipeUri The request recipe uri
* @param requestId the request id
@@ -96,36 +91,39 @@ public class BpmnRestClient {
* @throws IOException
* @since ONAP Beijing Release
*/
- public HttpResponse post(String recipeUri, String requestId, int recipeTimeout, String requestAction, String serviceInstanceId, String serviceType,
- String requestDetails, String recipeParamXsd) throws ClientProtocolException, IOException {
+ public HttpResponse post(String recipeUri, String requestId, int recipeTimeout, String requestAction,
+ String serviceInstanceId, String serviceType, String requestDetails, String recipeParamXsd)
+ throws ClientProtocolException, IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(recipeUri);
- RequestConfig requestConfig =
- RequestConfig.custom().setSocketTimeout(recipeTimeout).setConnectTimeout(recipeTimeout).setConnectionRequestTimeout(recipeTimeout).build();
+ RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(recipeTimeout)
+ .setConnectTimeout(recipeTimeout).setConnectionRequestTimeout(recipeTimeout).build();
post.setConfig(requestConfig);
logger.debug("call the bpmn, url: {}", recipeUri);
- String jsonReq = wrapResourceRequest(requestId, recipeTimeout, requestAction, serviceInstanceId, serviceType, requestDetails, recipeParamXsd);
+ String jsonReq = wrapResourceRequest(requestId, recipeTimeout, requestAction, serviceInstanceId, serviceType,
+ requestDetails, recipeParamXsd);
StringEntity input = new StringEntity(jsonReq);
input.setContentType(CONTENT_TYPE_JSON);
String encryptedCredentials;
encryptedCredentials = urnPropertiesReader.getVariable(CAMUNDA_AUTH);
- if(encryptedCredentials != null) {
- String userCredentials = getEncryptedPropValue(encryptedCredentials, DEFAULT_BPEL_AUTH, ENCRYPTION_KEY_PROP);
- if(userCredentials != null) {
- post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()));
+ if (encryptedCredentials != null) {
+ String userCredentials =
+ getEncryptedPropValue(encryptedCredentials, DEFAULT_BPEL_AUTH, ENCRYPTION_KEY_PROP);
+ if (userCredentials != null) {
+ post.addHeader("Authorization",
+ "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()));
}
}
-
+
post.setEntity(input);
return client.execute(post);
}
/**
- * prepare the resource recipe bpmn request.
- * <br>
+ * prepare the resource recipe bpmn request. <br>
*
* @param requestId
* @param recipeTimeout
@@ -137,20 +135,20 @@ public class BpmnRestClient {
* @return
* @since ONAP Beijing Release
*/
- private String wrapResourceRequest(String requestId, int recipeTimeout, String requestAction, String serviceInstanceId, String serviceType,
- String requestDetails, String recipeParams) {
+ private String wrapResourceRequest(String requestId, int recipeTimeout, String requestAction,
+ String serviceInstanceId, String serviceType, String requestDetails, String recipeParams) {
String jsonReq = null;
- if(requestId == null) {
+ if (requestId == null) {
requestId = "";
}
- if(requestAction == null) {
+ if (requestAction == null) {
requestAction = "";
}
- if(serviceInstanceId == null) {
+ if (serviceInstanceId == null) {
serviceInstanceId = "";
}
- if(requestDetails == null) {
+ if (requestDetails == null) {
requestDetails = "";
}
@@ -182,9 +180,9 @@ public class BpmnRestClient {
recipeRequest.setRecipeTimeout(recipeTimeoutInput);
jsonReq = recipeRequest.toString();
logger.trace("request body is {}", jsonReq);
- } catch(Exception e) {
+ } catch (Exception e) {
logger.error("{} {} {} {} {}", MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapVIDRequest",
- ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e);
+ ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e);
}
return jsonReq;
}
@@ -201,7 +199,7 @@ public class BpmnRestClient {
protected String getEncryptedPropValue(String prop, String defaultValue, String encryptionKey) {
try {
return CryptoUtils.decrypt(prop, urnPropertiesReader.getVariable(encryptionKey));
- } catch(GeneralSecurityException e) {
+ } catch (GeneralSecurityException e) {
logger.debug("Security exception", e);
}
return defaultValue;
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceInput.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceInput.java
index 2119b2dfa8..2bb024897c 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceInput.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceInput.java
@@ -22,7 +22,6 @@
package org.onap.so.bpmn.common.recipe;
import org.onap.so.bpmn.core.domain.ModelInfo;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -33,57 +32,58 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * the inputs for the resource recipe
- * <br>
+ * the inputs for the resource recipe <br>
* <p>
* </p>
*
* @author
- * @version ONAP Beijing Release 2018-03-08
+ * @version ONAP Beijing Release 2018-03-08
*/
-@JsonPropertyOrder({"resourceInstanceName", "resourceInstanceDes", "globalSubscriberId", "serviceType", "serviceId", "operationId", "serviceModelInfo","resourceModelInfo", "resourceInstancenUuid","resourceParameters","operationType"})
+@JsonPropertyOrder({"resourceInstanceName", "resourceInstanceDes", "globalSubscriberId", "serviceType", "serviceId",
+ "operationId", "serviceModelInfo", "resourceModelInfo", "resourceInstancenUuid", "resourceParameters",
+ "operationType"})
@JsonRootName("variables")
public class ResourceInput {
- private static Logger logger = LoggerFactory.getLogger(ResourceInput.class);
-
+ private static Logger logger = LoggerFactory.getLogger(ResourceInput.class);
+
@JsonProperty("resourceInstanceName")
private String resourceInstanceName;
-
+
@JsonProperty("resourceInstanceDes")
private String resourceInstanceDes;
-
+
@JsonProperty("globalSubscriberId")
private String globalSubscriberId;
-
+
@JsonProperty("serviceType")
private String serviceType;
-
+
@JsonProperty("serviceInstanceId")
private String serviceInstanceId;
-
+
@JsonProperty("operationId")
private String operationId;
-
+
@JsonProperty("serviceModelInfo")
private ModelInfo serviceModelInfo;
-
+
@JsonProperty("resourceModelInfo")
private ModelInfo resourceModelInfo;
-
- //for delete resource
+
+ // for delete resource
@JsonProperty("resourceInstancenUuid")
private String resourceInstancenUuid;
-
+
@JsonProperty("resourceParameters")
private String resourceParameters;
-
+
@JsonProperty("requestsInputs")
private String requestsInputs;
-
+
@JsonProperty("operationType")
private String operationType;
-
+
/**
* @return Returns the requestsInputs.
*/
@@ -92,7 +92,7 @@ public class ResourceInput {
return requestsInputs;
}
-
+
/**
* @param requestsInputs The requestsInputs to set.
*/
@@ -101,7 +101,7 @@ public class ResourceInput {
this.requestsInputs = requestsInputs;
}
-
+
/**
* @return Returns the resourceInstanceName.
*/
@@ -110,7 +110,7 @@ public class ResourceInput {
return resourceInstanceName;
}
-
+
/**
* @param resourceInstanceName The resourceInstanceName to set.
*/
@@ -119,7 +119,7 @@ public class ResourceInput {
this.resourceInstanceName = resourceInstanceName;
}
-
+
/**
* @return Returns the resourceInstanceDes.
*/
@@ -128,7 +128,7 @@ public class ResourceInput {
return resourceInstanceDes;
}
-
+
/**
* @param resourceInstanceDes The resourceInstanceDes to set.
*/
@@ -137,7 +137,7 @@ public class ResourceInput {
this.resourceInstanceDes = resourceInstanceDes;
}
-
+
/**
* @return Returns the globalSubscriberId.
*/
@@ -146,7 +146,7 @@ public class ResourceInput {
return globalSubscriberId;
}
-
+
/**
* @param globalSubscriberId The globalSubscriberId to set.
*/
@@ -155,7 +155,7 @@ public class ResourceInput {
this.globalSubscriberId = globalSubscriberId;
}
-
+
/**
* @return Returns the serviceType.
*/
@@ -164,7 +164,7 @@ public class ResourceInput {
return serviceType;
}
-
+
/**
* @param serviceType The serviceType to set.
*/
@@ -173,7 +173,7 @@ public class ResourceInput {
this.serviceType = serviceType;
}
-
+
/**
* @return Returns the serviceId.
*/
@@ -182,7 +182,7 @@ public class ResourceInput {
return serviceInstanceId;
}
-
+
/**
* @param serviceId The serviceId to set.
*/
@@ -191,7 +191,7 @@ public class ResourceInput {
this.serviceInstanceId = serviceId;
}
-
+
/**
* @return Returns the operationId.
*/
@@ -200,7 +200,7 @@ public class ResourceInput {
return operationId;
}
-
+
/**
* @param operationId The operationId to set.
*/
@@ -208,7 +208,7 @@ public class ResourceInput {
public void setOperationId(String operationId) {
this.operationId = operationId;
}
-
+
/**
* @return Returns the serviceModelInfo.
*/
@@ -218,7 +218,7 @@ public class ResourceInput {
}
-
+
/**
* @param serviceModelInfo The serviceModelInfo to set.
*/
@@ -228,7 +228,7 @@ public class ResourceInput {
}
-
+
/**
* @return Returns the resourceModelInfo.
*/
@@ -238,7 +238,7 @@ public class ResourceInput {
}
-
+
/**
* @param resourceModelInfo The resourceModelInfo to set.
*/
@@ -256,7 +256,7 @@ public class ResourceInput {
return resourceParameters;
}
-
+
/**
* @param resourceParameters The resourceParameters to set.
*/
@@ -265,7 +265,7 @@ public class ResourceInput {
this.resourceParameters = resourceParameters;
}
-
+
/**
* @return Returns the operationType.
*/
@@ -274,7 +274,7 @@ public class ResourceInput {
return operationType;
}
-
+
/**
* @param operationType The operationType to set.
*/
@@ -284,7 +284,7 @@ public class ResourceInput {
}
-
+
/**
* @return Returns the resourceInstancenUuid.
*/
@@ -294,7 +294,7 @@ public class ResourceInput {
}
-
+
/**
* @param resourceInstancenUuid The resourceInstancenUuid to set.
*/
@@ -302,7 +302,7 @@ public class ResourceInput {
public void setResourceInstancenUuid(String resourceInstancenUuid) {
this.resourceInstancenUuid = resourceInstancenUuid;
}
-
+
@Override
public String toString() {
ObjectMapper mapper = new ObjectMapper();
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceRecipeRequest.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceRecipeRequest.java
index d1e26582a3..729793893b 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceRecipeRequest.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceRecipeRequest.java
@@ -32,15 +32,15 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * java object of the resource recipe , it
- * will be passed to the Camunda process
+ * java object of the resource recipe , it will be passed to the Camunda process
*/
-@JsonPropertyOrder({"resourceInput", "host", "requestId", "requestAction", "serviceInstanceId", "serviceType", "recipeParams"})
+@JsonPropertyOrder({"resourceInput", "host", "requestId", "requestAction", "serviceInstanceId", "serviceType",
+ "recipeParams"})
@JsonRootName("variables")
public class ResourceRecipeRequest {
- private static Logger logger = LoggerFactory.getLogger(ResourceRecipeRequest.class);
-
+ private static Logger logger = LoggerFactory.getLogger(ResourceRecipeRequest.class);
+
@JsonProperty("resourceInput")
private BpmnParam resourceInput;
@@ -64,7 +64,7 @@ public class ResourceRecipeRequest {
@JsonProperty("mso-service-request-timeout")
private BpmnIntegerParam recipeTimeout;
-
+
@JsonProperty("resourceInput")
public BpmnParam getResourceInput() {
return resourceInput;
@@ -137,24 +137,24 @@ public class ResourceRecipeRequest {
@JsonProperty("mso-service-request-timeout")
public BpmnIntegerParam getRecipeTimeout() {
- return recipeTimeout;
- }
-
+ return recipeTimeout;
+ }
+
@JsonProperty("mso-service-request-timeout")
- public void setRecipeTimeout(BpmnIntegerParam recipeTimeout) {
- this.recipeTimeout = recipeTimeout;
- }
+ public void setRecipeTimeout(BpmnIntegerParam recipeTimeout) {
+ this.recipeTimeout = recipeTimeout;
+ }
- @Override
+ @Override
public String toString() {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
- String jsonStr = "ResourceRecipeRequest";
- try {
- jsonStr = mapper.writeValueAsString(this);
- } catch (JsonProcessingException e) {
- logger.error("JsonProcessingException", e);
- }
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
+ String jsonStr = "ResourceRecipeRequest";
+ try {
+ jsonStr = mapper.writeValueAsString(this);
+ } catch (JsonProcessingException e) {
+ logger.error("JsonProcessingException", e);
+ }
return jsonStr;
}
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java
index 03f56b31f6..e7ab6e4606 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java
@@ -29,17 +29,14 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
-
import org.camunda.bpm.engine.runtime.Execution;
import org.onap.so.bpmn.core.UrnPropertiesReader;
import org.onap.so.bpmn.core.json.JsonUtils;
import org.onap.so.client.HttpClient;
import org.onap.so.client.HttpClientFactory;
import org.onap.so.utils.TargetEntity;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
@@ -58,7 +55,7 @@ public class ResourceRequestBuilder {
static JsonUtils jsonUtil = new JsonUtils();
- public static List<String> getResourceSequence(String serviceUuid) {
+ public static List<String> getResourceSequence(String serviceUuid) {
List<String> resourceSequence = new ArrayList();
try {
@@ -69,7 +66,7 @@ public class ResourceRequestBuilder {
if (serviceResources.containsKey("resourceOrder")) {
String resourceOrder = (String) serviceResources.get("resourceOrder");
- if (resourceOrder!= null) {
+ if (resourceOrder != null) {
resourceSequence.addAll(Arrays.asList(resourceOrder.split(",")));
}
}
@@ -78,32 +75,35 @@ public class ResourceRequestBuilder {
logger.error("not able to retrieve service order.");
}
return resourceSequence;
- }
-
- /* build the resource Parameters detail.
- * It's a json string for resource instantiant
- * {
- * "locationConstraints":[...]
- * "requestInputs":{K,V}
- * }
- * <br>
+ }
+
+ /*
+ * build the resource Parameters detail. It's a json string for resource instantiant { "locationConstraints":[...]
+ * "requestInputs":{K,V} } <br>
*
* @param execution Execution context
+ *
* @param serviceUuid The service template uuid
+ *
* @param resourceCustomizationUuid The resource customization uuid
+ *
* @param serviceParameters the service parameters passed from the API
+ *
* @return the resource instantiate parameters
+ *
* @since ONAP Beijing Release
*/
@SuppressWarnings("unchecked")
- public static String buildResourceRequestParameters(Execution execution, String serviceUuid, String resourceCustomizationUuid, String serviceParameters) {
- List<String> resourceList = jsonUtil.StringArrayToList(execution, (String)JsonUtils.getJsonValue(serviceParameters, "resources"));
- //Get the right location str for resource. default is an empty array.
- String locationConstraints ="[]";
+ public static String buildResourceRequestParameters(Execution execution, String serviceUuid,
+ String resourceCustomizationUuid, String serviceParameters) {
+ List<String> resourceList =
+ jsonUtil.StringArrayToList(execution, (String) JsonUtils.getJsonValue(serviceParameters, "resources"));
+ // Get the right location str for resource. default is an empty array.
+ String locationConstraints = "[]";
String resourceInputsFromUui = "";
- for(String resource: resourceList){
- String resCusUuid = (String)JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
- if(resourceCustomizationUuid.equals(resCusUuid)){
+ for (String resource : resourceList) {
+ String resCusUuid = (String) JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
+ if (resourceCustomizationUuid.equals(resCusUuid)) {
String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
locationConstraints = JsonUtils.getJsonValue(resourceParameters, "locationConstraints");
resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
@@ -111,7 +111,8 @@ public class ResourceRequestBuilder {
}
Map<String, Object> serviceInput = null;
if (JsonUtils.getJsonValue(serviceParameters, "requestInputs") != null) {
- serviceInput = getJsonObject((String)JsonUtils.getJsonValue(serviceParameters, "requestInputs"), Map.class);
+ serviceInput =
+ getJsonObject((String) JsonUtils.getJsonValue(serviceParameters, "requestInputs"), Map.class);
}
Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
@@ -124,42 +125,45 @@ public class ResourceRequestBuilder {
resourceInputsFromUuiMap = new HashMap();
}
- Map<String, Object> resourceInputsFromServiceDeclaredLevel = buildResouceRequest(serviceUuid, resourceCustomizationUuid, serviceInput);
+ Map<String, Object> resourceInputsFromServiceDeclaredLevel =
+ buildResouceRequest(serviceUuid, resourceCustomizationUuid, serviceInput);
resourceInputsFromUuiMap.putAll(resourceInputsFromServiceDeclaredLevel);
String resourceInputsStr = getJsonString(resourceInputsFromUuiMap);
- String result = "{\n"
- + "\"locationConstraints\":" + locationConstraints +",\n"
- + "\"requestInputs\":" + resourceInputsStr +"\n"
- +"}";
+ String result = "{\n" + "\"locationConstraints\":" + locationConstraints + ",\n" + "\"requestInputs\":"
+ + resourceInputsStr + "\n" + "}";
return result;
}
@SuppressWarnings("unchecked")
- public static Map<String, Object> buildResouceRequest(String serviceUuid, String resourceCustomizationUuid, Map<String, Object> serviceInputs) {
+ public static Map<String, Object> buildResouceRequest(String serviceUuid, String resourceCustomizationUuid,
+ Map<String, Object> serviceInputs) {
try {
Map<String, Object> serviceInstnace = getServiceInstnace(serviceUuid);
// find match of customization uuid in vnf
- Map<String, Map<String, Object>> serviceResources = (Map<String, Map<String, Object>>) serviceInstnace.get("serviceResources");
+ Map<String, Map<String, Object>> serviceResources =
+ (Map<String, Map<String, Object>>) serviceInstnace.get("serviceResources");
List<Map<String, Object>> serviceVnfCust = (List<Map<String, Object>>) serviceResources.get("serviceVnfs");
String resourceInputStr = getResourceInputStr(serviceVnfCust, resourceCustomizationUuid);
// find match in network resource
if (resourceInputStr == null) {
- List<Map<String, Object>> serviceNetworkCust = (List<Map<String, Object>>) serviceResources.get("serviceNetworks");
+ List<Map<String, Object>> serviceNetworkCust =
+ (List<Map<String, Object>>) serviceResources.get("serviceNetworks");
resourceInputStr = getResourceInputStr(serviceNetworkCust, resourceCustomizationUuid);
// find match in AR resource
if (resourceInputStr == null) {
- List<Map<String, Object>> serviceArCust = (List<Map<String, Object>>) serviceResources.get("serviceAllottedResources");
+ List<Map<String, Object>> serviceArCust =
+ (List<Map<String, Object>>) serviceResources.get("serviceAllottedResources");
resourceInputStr = getResourceInputStr(serviceArCust, resourceCustomizationUuid);
}
}
- if (resourceInputStr != null && !resourceInputStr.isEmpty()) {
+ if (resourceInputStr != null && !resourceInputStr.isEmpty()) {
return getResourceInput(resourceInputStr, serviceInputs);
- }
+ }
} catch (Exception e) {
logger.error("not able to retrieve service instance");
@@ -182,11 +186,11 @@ public class ResourceRequestBuilder {
// this method combines resource input with service input
private static Map<String, Object> getResourceInput(String resourceInputStr, Map<String, Object> serviceInputs) {
Gson gson = new Gson();
- Type type = new TypeToken<Map<String, String>>(){}.getType();
+ Type type = new TypeToken<Map<String, String>>() {}.getType();
Map<String, Object> resourceInput = gson.fromJson(resourceInputStr, type);
// replace value if key is available in service input
- for (String key: resourceInput.keySet()) {
+ for (String key : resourceInput.keySet()) {
String value = (String) resourceInput.get(key);
if (value.contains("|")) {
@@ -199,7 +203,7 @@ public class ResourceRequestBuilder {
value = split[1];
}
}
- resourceInput.put(key,value);
+ resourceInput.put(key, value);
}
return resourceInput;
}
@@ -207,8 +211,8 @@ public class ResourceRequestBuilder {
public static Map<String, Object> getServiceInstnace(String uuid) throws Exception {
String catalogEndPoint = UrnPropertiesReader.getVariable("mso.catalog.db.endpoint");
- HttpClient client = new HttpClientFactory().newJsonClient(
- UriBuilder.fromUri(catalogEndPoint).path(SERVICE_URL_SERVICE_INSTANCE).queryParam("serviceModelUuid", uuid).build().toURL(),
+ HttpClient client = new HttpClientFactory().newJsonClient(UriBuilder.fromUri(catalogEndPoint)
+ .path(SERVICE_URL_SERVICE_INSTANCE).queryParam("serviceModelUuid", uuid).build().toURL(),
TargetEntity.CATALOG_DB);
client.addAdditionalHeader("Accept", "application/json");
@@ -234,7 +238,7 @@ public class ResourceRequestBuilder {
return null;
}
- public static String getJsonString(Object srcObj) {
+ public static String getJsonString(Object srcObj) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
String jsonStr = null;
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/CryptoHandler.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/CryptoHandler.java
index 0fd0d9297d..dc2b3be073 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/CryptoHandler.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/CryptoHandler.java
@@ -22,50 +22,50 @@
*/
package org.onap.so.bpmn.common.util;
+
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Properties;
import org.onap.so.utils.CryptoUtils;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CryptoHandler implements ICryptoHandler {
- private static final Logger logger = LoggerFactory.getLogger(CryptoHandler.class);
- private static final String GENERAL_SECURITY_EXCEPTION_PREFIX = "GeneralSecurityException :";
- private static final String MSO_KEY = "aa3871669d893c7fb8abbcda31b88b4f";
- private static final String PROPERTY_KEY = "mso.AaiEncrypted.Pwd";
+ private static final Logger logger = LoggerFactory.getLogger(CryptoHandler.class);
+ private static final String GENERAL_SECURITY_EXCEPTION_PREFIX = "GeneralSecurityException :";
+ private static final String MSO_KEY = "aa3871669d893c7fb8abbcda31b88b4f";
+ private static final String PROPERTY_KEY = "mso.AaiEncrypted.Pwd";
@Override
- public String getMsoAaiPassword() {
- Properties keyProp = new Properties ();
- try {
- keyProp.load (Thread.currentThread ().getContextClassLoader ().getResourceAsStream ("urn.properties"));
- return CryptoUtils.decrypt((String) keyProp.get(PROPERTY_KEY), MSO_KEY);
- } catch (GeneralSecurityException | IOException e) {
- logger.error(GENERAL_SECURITY_EXCEPTION_PREFIX + e.getMessage(), e);
- return null;
- }
- }
+ public String getMsoAaiPassword() {
+ Properties keyProp = new Properties();
+ try {
+ keyProp.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("urn.properties"));
+ return CryptoUtils.decrypt((String) keyProp.get(PROPERTY_KEY), MSO_KEY);
+ } catch (GeneralSecurityException | IOException e) {
+ logger.error(GENERAL_SECURITY_EXCEPTION_PREFIX + e.getMessage(), e);
+ return null;
+ }
+ }
- @Override
- public String encryptMsoPassword(String plainMsoPwd) {
- try {
- return CryptoUtils.encrypt(plainMsoPwd, MSO_KEY);
- } catch (GeneralSecurityException e) {
- logger.error(GENERAL_SECURITY_EXCEPTION_PREFIX + e.getMessage(), e);
- return null;
- }
- }
+ @Override
+ public String encryptMsoPassword(String plainMsoPwd) {
+ try {
+ return CryptoUtils.encrypt(plainMsoPwd, MSO_KEY);
+ } catch (GeneralSecurityException e) {
+ logger.error(GENERAL_SECURITY_EXCEPTION_PREFIX + e.getMessage(), e);
+ return null;
+ }
+ }
- @Override
- public String decryptMsoPassword(String encryptedPwd) {
- try {
- return CryptoUtils.decrypt(encryptedPwd, MSO_KEY);
- } catch (GeneralSecurityException e) {
- logger.error(GENERAL_SECURITY_EXCEPTION_PREFIX + e.getMessage(), e);
- return null;
- }
- }
+ @Override
+ public String decryptMsoPassword(String encryptedPwd) {
+ try {
+ return CryptoUtils.decrypt(encryptedPwd, MSO_KEY);
+ } catch (GeneralSecurityException e) {
+ logger.error(GENERAL_SECURITY_EXCEPTION_PREFIX + e.getMessage(), e);
+ return null;
+ }
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/ICryptoHandler.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/ICryptoHandler.java
index 6314a849d2..479d2e82bd 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/ICryptoHandler.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/ICryptoHandler.java
@@ -21,7 +21,9 @@
package org.onap.so.bpmn.common.util;
public interface ICryptoHandler {
- public String getMsoAaiPassword();
- public String encryptMsoPassword(String plainPwd);
- public String decryptMsoPassword(String encryptedPwd);
+ public String getMsoAaiPassword();
+
+ public String encryptMsoPassword(String plainPwd);
+
+ public String decryptMsoPassword(String encryptedPwd);
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/OofInfraUtils.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/OofInfraUtils.java
index 6b178bd215..f25d4b440a 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/OofInfraUtils.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/OofInfraUtils.java
@@ -28,7 +28,6 @@ import org.onap.so.db.catalog.beans.HomingInstance;
import org.onap.so.db.catalog.client.CatalogDbClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
import java.util.Optional;
public class OofInfraUtils {
@@ -50,13 +49,13 @@ public class OofInfraUtils {
CatalogDbClient client = new CatalogDbClient(endpoint, auth);
- getCloudsite = Optional.ofNullable(client.getCloudSite(cloudSite.getId(), endpoint + "/cloudSite/")).orElse(new CloudSite());
+ getCloudsite = Optional.ofNullable(client.getCloudSite(cloudSite.getId(), endpoint + "/cloudSite/"))
+ .orElse(new CloudSite());
if (!cloudSite.getId().equals(getCloudsite.getId())) {
client.postCloudSite(cloudSite);
logger.debug("Did not findd cloudsite : {}", cloudSite.getId());
logger.debug("Will create cloudSite: {}", cloudSite.toString());
- }
- else {
+ } else {
logger.debug("Found cloudsite : {}", cloudSite.getId());
logger.debug("Will not create cloudSite: {}", cloudSite.toString());
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunner.java
index a5d871eeef..a8e43c51e5 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunner.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunner.java
@@ -27,10 +27,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
-
import javax.annotation.PostConstruct;
import javax.annotation.Priority;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.javatuples.Pair;
import org.onap.so.bpmn.common.BuildingBlockExecution;
@@ -46,29 +44,31 @@ import org.springframework.stereotype.Component;
/**
* Controls running all pre and post validation for building blocks.
*
- * To define a validation you must make it a spring bean and implement either {@link org.onap.so.bpmn.common.validation.PreBuildingBlockValidator} or
- * {@link org.onap.so.bpmn.common.validation.PostBuildingBlockValidator} your validation will automatically be
- * run by this class.
+ * To define a validation you must make it a spring bean and implement either
+ * {@link org.onap.so.bpmn.common.validation.PreBuildingBlockValidator} or
+ * {@link org.onap.so.bpmn.common.validation.PostBuildingBlockValidator} your validation will automatically be run by
+ * this class.
*
*/
@Component
-public class BuildingBlockValidatorRunner extends FlowValidatorRunner<PreBuildingBlockValidator, PostBuildingBlockValidator> {
-
- @PostConstruct
- protected void init() {
-
- preFlowValidators = new ArrayList<>(
- Optional.ofNullable(context.getBeansOfType(PreBuildingBlockValidator.class)).orElse(new HashMap<>()).values());
- postFlowValidators = new ArrayList<>(
- Optional.ofNullable(context.getBeansOfType(PostBuildingBlockValidator.class)).orElse(new HashMap<>()).values());
- }
-
- protected List<PreBuildingBlockValidator> getPreFlowValidators() {
- return this.preFlowValidators;
- }
-
- protected List<PostBuildingBlockValidator> getPostFlowValidators() {
- return this.postFlowValidators;
- }
-
+public class BuildingBlockValidatorRunner
+ extends FlowValidatorRunner<PreBuildingBlockValidator, PostBuildingBlockValidator> {
+
+ @PostConstruct
+ protected void init() {
+
+ preFlowValidators = new ArrayList<>(Optional.ofNullable(context.getBeansOfType(PreBuildingBlockValidator.class))
+ .orElse(new HashMap<>()).values());
+ postFlowValidators = new ArrayList<>(Optional
+ .ofNullable(context.getBeansOfType(PostBuildingBlockValidator.class)).orElse(new HashMap<>()).values());
+ }
+
+ protected List<PreBuildingBlockValidator> getPreFlowValidators() {
+ return this.preFlowValidators;
+ }
+
+ protected List<PostBuildingBlockValidator> getPostFlowValidators() {
+ return this.postFlowValidators;
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidator.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidator.java
index c457a349c2..66a8de9f8b 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidator.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidator.java
@@ -22,24 +22,24 @@ package org.onap.so.bpmn.common.validation;
import java.util.Optional;
import java.util.Set;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
public interface FlowValidator {
- /**
- * Should this validator run for given bb
- * @return
- */
- public boolean shouldRunFor(String bbName);
-
- /**
- * Determines whether or not the workflow should be executed
+ /**
+ * Should this validator run for given bb
+ *
+ * @return
+ */
+ public boolean shouldRunFor(String bbName);
+
+ /**
+ * Determines whether or not the workflow should be executed
+ *
+ *
+ * @param execution
+ * @return
+ */
+ public Optional<String> validate(BuildingBlockExecution execution);
- *
- * @param execution
- * @return
- */
- public Optional<String> validate(BuildingBlockExecution execution);
-
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidatorRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidatorRunner.java
index 2cc6415a50..0bdf4e35a2 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidatorRunner.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidatorRunner.java
@@ -26,9 +26,7 @@ import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
-
import javax.annotation.Priority;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.javatuples.Pair;
import org.onap.so.bpmn.common.BuildingBlockExecution;
@@ -45,116 +43,119 @@ import org.springframework.stereotype.Component;
/**
* Controls running all pre and post validation for flows.
*
- * To define a validation you must make it a spring bean and implement either {@link org.onap.so.bpmn.common.validation.PreFlowValidator} or
- * {@link org.onap.so.bpmn.common.validation.PostFlowValidator} your validation will automatically be
- * run by this class.
+ * To define a validation you must make it a spring bean and implement either
+ * {@link org.onap.so.bpmn.common.validation.PreFlowValidator} or
+ * {@link org.onap.so.bpmn.common.validation.PostFlowValidator} your validation will automatically be run by this class.
*
*/
@Component
public abstract class FlowValidatorRunner<S extends FlowValidator, E extends FlowValidator> {
- private static Logger logger = LoggerFactory.getLogger(FlowValidatorRunner.class);
- @Autowired
- protected ApplicationContext context;
-
- @Autowired
- protected ExceptionBuilder exceptionBuilder;
-
- protected List<S> preFlowValidators;
- protected List<E> postFlowValidators;
-
-
-
- /**
- * Changed to object because JUEL does not support overloaded methods
- *
- * @param bbName
- * @param execution
- * @return
- */
- public boolean preValidate(String bbName, Object execution) {
- return validateHelper(bbName, preFlowValidators, execution);
- }
-
- /**
- * Changed to object because JUEL does not support overloaded methods
- *
- * @param bbName
- * @param execution
- * @return
- */
- public boolean postValidate(String bbName, Object execution) {
- return validateHelper(bbName, postFlowValidators, execution);
- }
-
- protected boolean validateHelper(String bbName, List<? extends FlowValidator> validators, Object obj) {
-
- if (obj instanceof DelegateExecution) {
- return validate(validators, bbName, new DelegateExecutionImpl((DelegateExecution)obj));
- } else if (obj instanceof BuildingBlockExecution) {
- return validate(validators, bbName, (BuildingBlockExecution)obj);
- } else {
- return false;
- }
- }
-
- protected boolean validate(List<? extends FlowValidator> validators, String bbName, BuildingBlockExecution execution) {
- List<Pair<String, Optional<String>>> results = runValidations(validators, bbName, execution);
-
- if (!results.isEmpty()) {
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000,
- "Failed Validations:\n" + results.stream().map(item -> String.format("%s: %s", item.getValue0(), item.getValue1().get())).collect(Collectors.joining("\n")));
- }
-
- return true;
-
- }
- protected List<Pair<String, Optional<String>>> runValidations(List<? extends FlowValidator> validators, String bbName, BuildingBlockExecution execution) {
-
- List<FlowValidator> filtered = filterValidators(validators, bbName);
-
- List<Pair<String,Optional<String>>> results = new ArrayList<>();
- filtered.forEach(item -> results.add(new Pair<>(item.getClass().getName(), item.validate(execution))));
-
- return results.stream().filter(item -> item.getValue1().isPresent()).collect(Collectors.toList());
- }
-
- protected List<FlowValidator> filterValidators(List<? extends FlowValidator> validators, String bbName) {
- return validators.stream()
- .filter(item -> {
- return !item.getClass().isAnnotationPresent(Skip.class) && item.shouldRunFor(bbName);
- })
- .sorted(Comparator.comparing(item -> {
- Priority p = Optional.ofNullable(item.getClass().getAnnotation(Priority.class)).orElse(new Priority() {
- public int value() {
- return 1000;
- }
-
- @Override
- public Class<? extends Annotation> annotationType() {
- return Priority.class;
- }
- });
- return p.value();
- })).collect(Collectors.toList());
- }
-
- protected <T> List<T> buildalidatorList(Reflections reflections, Class<T> clazz) {
- List<T> result = new ArrayList<>();
- try {
- for (Class<? extends T> klass : reflections.getSubTypesOf(clazz)) {
- result.add(klass.newInstance());
- }
- } catch (InstantiationException | IllegalAccessException e) {
- logger.error("failed to build validator list for {}", clazz.getName(), e);
- throw new RuntimeException(e);
- }
-
- return result;
- }
-
- protected abstract List<S> getPreFlowValidators();
-
- protected abstract List<E> getPostFlowValidators();
-
+ private static Logger logger = LoggerFactory.getLogger(FlowValidatorRunner.class);
+ @Autowired
+ protected ApplicationContext context;
+
+ @Autowired
+ protected ExceptionBuilder exceptionBuilder;
+
+ protected List<S> preFlowValidators;
+ protected List<E> postFlowValidators;
+
+
+
+ /**
+ * Changed to object because JUEL does not support overloaded methods
+ *
+ * @param bbName
+ * @param execution
+ * @return
+ */
+ public boolean preValidate(String bbName, Object execution) {
+ return validateHelper(bbName, preFlowValidators, execution);
+ }
+
+ /**
+ * Changed to object because JUEL does not support overloaded methods
+ *
+ * @param bbName
+ * @param execution
+ * @return
+ */
+ public boolean postValidate(String bbName, Object execution) {
+ return validateHelper(bbName, postFlowValidators, execution);
+ }
+
+ protected boolean validateHelper(String bbName, List<? extends FlowValidator> validators, Object obj) {
+
+ if (obj instanceof DelegateExecution) {
+ return validate(validators, bbName, new DelegateExecutionImpl((DelegateExecution) obj));
+ } else if (obj instanceof BuildingBlockExecution) {
+ return validate(validators, bbName, (BuildingBlockExecution) obj);
+ } else {
+ return false;
+ }
+ }
+
+ protected boolean validate(List<? extends FlowValidator> validators, String bbName,
+ BuildingBlockExecution execution) {
+ List<Pair<String, Optional<String>>> results = runValidations(validators, bbName, execution);
+
+ if (!results.isEmpty()) {
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000,
+ "Failed Validations:\n" + results.stream()
+ .map(item -> String.format("%s: %s", item.getValue0(), item.getValue1().get()))
+ .collect(Collectors.joining("\n")));
+ }
+
+ return true;
+
+ }
+
+ protected List<Pair<String, Optional<String>>> runValidations(List<? extends FlowValidator> validators,
+ String bbName, BuildingBlockExecution execution) {
+
+ List<FlowValidator> filtered = filterValidators(validators, bbName);
+
+ List<Pair<String, Optional<String>>> results = new ArrayList<>();
+ filtered.forEach(item -> results.add(new Pair<>(item.getClass().getName(), item.validate(execution))));
+
+ return results.stream().filter(item -> item.getValue1().isPresent()).collect(Collectors.toList());
+ }
+
+ protected List<FlowValidator> filterValidators(List<? extends FlowValidator> validators, String bbName) {
+ return validators.stream().filter(item -> {
+ return !item.getClass().isAnnotationPresent(Skip.class) && item.shouldRunFor(bbName);
+ }).sorted(Comparator.comparing(item -> {
+ Priority p = Optional.ofNullable(item.getClass().getAnnotation(Priority.class)).orElse(new Priority() {
+ public int value() {
+ return 1000;
+ }
+
+ @Override
+ public Class<? extends Annotation> annotationType() {
+ return Priority.class;
+ }
+ });
+ return p.value();
+ })).collect(Collectors.toList());
+ }
+
+ protected <T> List<T> buildalidatorList(Reflections reflections, Class<T> clazz) {
+ List<T> result = new ArrayList<>();
+ try {
+ for (Class<? extends T> klass : reflections.getSubTypesOf(clazz)) {
+ result.add(klass.newInstance());
+ }
+ } catch (InstantiationException | IllegalAccessException e) {
+ logger.error("failed to build validator list for {}", clazz.getName(), e);
+ throw new RuntimeException(e);
+ }
+
+ return result;
+ }
+
+ protected abstract List<S> getPreFlowValidators();
+
+ protected abstract List<E> getPostFlowValidators();
+
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunner.java
index d8c8601865..6950618953 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunner.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunner.java
@@ -27,10 +27,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
-
import javax.annotation.PostConstruct;
import javax.annotation.Priority;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.javatuples.Pair;
import org.onap.so.client.exception.ExceptionBuilder;
@@ -45,29 +43,30 @@ import org.springframework.stereotype.Component;
/**
* Controls running all pre and post validation for workflows.
*
- * To define a validation you must make it a spring bean and implement either {@link org.onap.so.bpmn.common.validation.PreWorkflowValidator} or
- * {@link org.onap.so.bpmn.common.validation.PostWorkflowValidator} your validation will automatically be
- * run by this class.
+ * To define a validation you must make it a spring bean and implement either
+ * {@link org.onap.so.bpmn.common.validation.PreWorkflowValidator} or
+ * {@link org.onap.so.bpmn.common.validation.PostWorkflowValidator} your validation will automatically be run by this
+ * class.
*
*/
@Component
public class WorkflowValidatorRunner extends FlowValidatorRunner<PreWorkflowValidator, PostWorkflowValidator> {
- @PostConstruct
- protected void init() {
-
- preFlowValidators = new ArrayList<>(
- Optional.ofNullable(context.getBeansOfType(PreWorkflowValidator.class)).orElse(new HashMap<>()).values());
- postFlowValidators = new ArrayList<>(
- Optional.ofNullable(context.getBeansOfType(PostWorkflowValidator.class)).orElse(new HashMap<>()).values());
- }
+ @PostConstruct
+ protected void init() {
+
+ preFlowValidators = new ArrayList<>(Optional.ofNullable(context.getBeansOfType(PreWorkflowValidator.class))
+ .orElse(new HashMap<>()).values());
+ postFlowValidators = new ArrayList<>(Optional.ofNullable(context.getBeansOfType(PostWorkflowValidator.class))
+ .orElse(new HashMap<>()).values());
+ }
+
+ protected List<PreWorkflowValidator> getPreFlowValidators() {
+ return this.preFlowValidators;
+ }
+
+ protected List<PostWorkflowValidator> getPostFlowValidators() {
+ return this.postFlowValidators;
+ }
- protected List<PreWorkflowValidator> getPreFlowValidators() {
- return this.preFlowValidators;
- }
-
- protected List<PostWorkflowValidator> getPostFlowValidators() {
- return this.postFlowValidators;
- }
-
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowCallbackResponse.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowCallbackResponse.java
index 13d2126805..2a64b1ad2f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowCallbackResponse.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowCallbackResponse.java
@@ -21,32 +21,36 @@ package org.onap.so.bpmn.common.workflow.context;
/**
- * @version 1.0
- * Workflow Response bean to generate workflow response in JSON format
+ * @version 1.0 Workflow Response bean to generate workflow response in JSON format
*/
public class WorkflowCallbackResponse {
-
- private String response;
- private int statusCode;
- private String message;
-
- public String getResponse() {
- return response;
- }
- public void setResponse(String response) {
- this.response = response;
- }
- public int getStatusCode() {
- return statusCode;
- }
- public void setStatusCode(int statusCode) {
- this.statusCode = statusCode;
- }
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
+
+ private String response;
+ private int statusCode;
+ private String message;
+
+ public String getResponse() {
+ return response;
+ }
+
+ public void setResponse(String response) {
+ this.response = response;
+ }
+
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ public void setStatusCode(int statusCode) {
+ this.statusCode = statusCode;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContext.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContext.java
index 3ec7773791..2a10271e67 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContext.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContext.java
@@ -26,73 +26,72 @@ import java.util.concurrent.TimeUnit;
/**
- * @version 1.0
- * Workflow context object used to send timeout response, if workflow instance does not write the response in time
+ * @version 1.0 Workflow context object used to send timeout response, if workflow instance does not write the response
+ * in time
*/
public class WorkflowContext implements Delayed {
- private final String processKey;
- private final String requestId;
-
- private final long startTime;
- private final long timeout;
-
- private final WorkflowResponse workflowResponse;
-
- public WorkflowContext(String processKey, String requestId, long timeout, WorkflowResponse workflowResponse) {
- this.processKey = processKey;
- this.requestId = requestId;
- this.timeout = timeout;
- this.startTime = System.currentTimeMillis();
- this.workflowResponse = workflowResponse;
- }
-
- public String getRequestId() {
- return requestId;
- }
-
- public String getProcessKey() {
- return processKey;
- }
-
-
- public long getTimeout() {
- return timeout;
- }
-
- public long getStartTime() {
- return startTime;
- }
-
- public WorkflowResponse getWorkflowResponse() {
- return workflowResponse;
- }
-
- /**
- * Required implementation by Delay queue
- * Returns the elapsed time for this context
- */
- @Override
- public long getDelay(TimeUnit unit) {
- // 0 or negative means this object is considered to be expired
- return unit.convert(startTime + timeout - System.currentTimeMillis(), unit);
- }
-
- /**
- * Required implementation by Delay queue
- * Compares the object to determine whether the object can be marked as expired
- */
- @Override
- public int compareTo(Delayed object) {
- WorkflowContext that = (WorkflowContext) object;
- long thisEndTime = startTime + timeout;
- long thatEndTime = that.startTime + that.timeout;
-
- if (thisEndTime < thatEndTime) {
- return -1;
- } else if (thisEndTime > thatEndTime) {
- return 1;
- } else {
- return 0;
- }
- }
+ private final String processKey;
+ private final String requestId;
+
+ private final long startTime;
+ private final long timeout;
+
+ private final WorkflowResponse workflowResponse;
+
+ public WorkflowContext(String processKey, String requestId, long timeout, WorkflowResponse workflowResponse) {
+ this.processKey = processKey;
+ this.requestId = requestId;
+ this.timeout = timeout;
+ this.startTime = System.currentTimeMillis();
+ this.workflowResponse = workflowResponse;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public String getProcessKey() {
+ return processKey;
+ }
+
+
+ public long getTimeout() {
+ return timeout;
+ }
+
+ public long getStartTime() {
+ return startTime;
+ }
+
+ public WorkflowResponse getWorkflowResponse() {
+ return workflowResponse;
+ }
+
+ /**
+ * Required implementation by Delay queue Returns the elapsed time for this context
+ */
+ @Override
+ public long getDelay(TimeUnit unit) {
+ // 0 or negative means this object is considered to be expired
+ return unit.convert(startTime + timeout - System.currentTimeMillis(), unit);
+ }
+
+ /**
+ * Required implementation by Delay queue Compares the object to determine whether the object can be marked as
+ * expired
+ */
+ @Override
+ public int compareTo(Delayed object) {
+ WorkflowContext that = (WorkflowContext) object;
+ long thisEndTime = startTime + timeout;
+ long thatEndTime = that.startTime + that.timeout;
+
+ if (thisEndTime < thatEndTime) {
+ return -1;
+ } else if (thisEndTime > thatEndTime) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java
index 0de3414381..33fb78b306 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java
@@ -25,7 +25,6 @@ package org.onap.so.bpmn.common.workflow.context;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;
-
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.slf4j.Logger;
@@ -34,6 +33,7 @@ import org.springframework.stereotype.Component;
/**
* Workflow Context Holder instance which can be accessed elsewhere either in groovy scripts or Java
+ *
* @version 1.0
*
*/
@@ -41,100 +41,100 @@ import org.springframework.stereotype.Component;
@Component
public class WorkflowContextHolder {
- private static Logger logger = LoggerFactory.getLogger(WorkflowContextHolder.class);
- private static final String logMarker = "[WORKFLOW-CONTEXT-HOLDER]";
- private static WorkflowContextHolder instance = null;
-
-
- private long defaultContextTimeout=60000;
-
- /**
- * Delay Queue which holds workflow context holder objects
- */
- private final DelayQueue<WorkflowContext> responseQueue = new DelayQueue<>();
- private final TimeoutThread timeoutThread = new TimeoutThread();
-
- private WorkflowContextHolder() {
- timeoutThread.start();
- }
-
- /**
- * Singleton holder which eliminates hot lock
- * Since the JVM synchronizes static method there is no synchronization needed for this method
- * @return
- */
- public static synchronized WorkflowContextHolder getInstance() {
- if (instance == null) {
- instance = new WorkflowContextHolder();
- }
- return instance;
- }
-
- public void put(WorkflowContext context) {
- logger.debug("{} Adding context to the queue: {}", logMarker, context.getRequestId());
- responseQueue.put(context);
- }
-
- public void remove(WorkflowContext context) {
- logger.debug("{} Removing context from the queue: {}", logMarker, context.getRequestId());
- responseQueue.remove(context);
- }
-
- public WorkflowContext getWorkflowContext(String requestId) {
- // Note: DelayQueue interator is threadsafe
- for (WorkflowContext context : responseQueue) {
- if (requestId.equals(context.getRequestId())) {
- return context;
- }
- }
- return null;
- }
-
- /**
- * Builds the callback response object to respond to client
- * @param processKey
- * @param processInstanceId
- * @param requestId
- * @param callbackResponse
- * @return
- */
- public void processCallback(String processKey, String processInstanceId,
- String requestId, WorkflowCallbackResponse callbackResponse) {
- WorkflowResponse workflowResponse = new WorkflowResponse();
- workflowResponse.setResponse(callbackResponse.getResponse());
- workflowResponse.setProcessInstanceID(processInstanceId);
- workflowResponse.setMessageCode(callbackResponse.getStatusCode());
- workflowResponse.setMessage(callbackResponse.getMessage());
- WorkflowContext context = new WorkflowContext(processKey, requestId, defaultContextTimeout,workflowResponse);
- put(context);
- }
-
-
- /**
- * Timeout thread which monitors the delay queue for expired context and send timeout response
- * to client
- *
- * */
- private class TimeoutThread extends Thread {
- @Override
- public void run() {
- while (!isInterrupted()) {
- try {
- WorkflowContext requestObject = responseQueue.take();
- logger.debug("Time remaining for request id: {}:{}", requestObject.getRequestId(), requestObject
- .getDelay
- (TimeUnit.MILLISECONDS));
- logger.debug("Preparing timeout response for {}:{}", requestObject.getProcessKey(), requestObject
- .getRequestId());
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- } catch (Exception e) {
- logger.debug("WorkflowContextHolder timeout thread caught exception: ", e);
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
- ErrorCode.UnknownError.getValue(), "Error in WorkflowContextHolder timeout thread");
- }
- }
- logger.debug("WorkflowContextHolder timeout thread interrupted, quitting");
- }
- }
+ private static Logger logger = LoggerFactory.getLogger(WorkflowContextHolder.class);
+ private static final String logMarker = "[WORKFLOW-CONTEXT-HOLDER]";
+ private static WorkflowContextHolder instance = null;
+
+
+ private long defaultContextTimeout = 60000;
+
+ /**
+ * Delay Queue which holds workflow context holder objects
+ */
+ private final DelayQueue<WorkflowContext> responseQueue = new DelayQueue<>();
+ private final TimeoutThread timeoutThread = new TimeoutThread();
+
+ private WorkflowContextHolder() {
+ timeoutThread.start();
+ }
+
+ /**
+ * Singleton holder which eliminates hot lock Since the JVM synchronizes static method there is no synchronization
+ * needed for this method
+ *
+ * @return
+ */
+ public static synchronized WorkflowContextHolder getInstance() {
+ if (instance == null) {
+ instance = new WorkflowContextHolder();
+ }
+ return instance;
+ }
+
+ public void put(WorkflowContext context) {
+ logger.debug("{} Adding context to the queue: {}", logMarker, context.getRequestId());
+ responseQueue.put(context);
+ }
+
+ public void remove(WorkflowContext context) {
+ logger.debug("{} Removing context from the queue: {}", logMarker, context.getRequestId());
+ responseQueue.remove(context);
+ }
+
+ public WorkflowContext getWorkflowContext(String requestId) {
+ // Note: DelayQueue interator is threadsafe
+ for (WorkflowContext context : responseQueue) {
+ if (requestId.equals(context.getRequestId())) {
+ return context;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Builds the callback response object to respond to client
+ *
+ * @param processKey
+ * @param processInstanceId
+ * @param requestId
+ * @param callbackResponse
+ * @return
+ */
+ public void processCallback(String processKey, String processInstanceId, String requestId,
+ WorkflowCallbackResponse callbackResponse) {
+ WorkflowResponse workflowResponse = new WorkflowResponse();
+ workflowResponse.setResponse(callbackResponse.getResponse());
+ workflowResponse.setProcessInstanceID(processInstanceId);
+ workflowResponse.setMessageCode(callbackResponse.getStatusCode());
+ workflowResponse.setMessage(callbackResponse.getMessage());
+ WorkflowContext context = new WorkflowContext(processKey, requestId, defaultContextTimeout, workflowResponse);
+ put(context);
+ }
+
+
+ /**
+ * Timeout thread which monitors the delay queue for expired context and send timeout response to client
+ *
+ */
+ private class TimeoutThread extends Thread {
+ @Override
+ public void run() {
+ while (!isInterrupted()) {
+ try {
+ WorkflowContext requestObject = responseQueue.take();
+ logger.debug("Time remaining for request id: {}:{}", requestObject.getRequestId(),
+ requestObject.getDelay(TimeUnit.MILLISECONDS));
+ logger.debug("Preparing timeout response for {}:{}", requestObject.getProcessKey(),
+ requestObject.getRequestId());
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } catch (Exception e) {
+ logger.debug("WorkflowContextHolder timeout thread caught exception: ", e);
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
+ ErrorCode.UnknownError.getValue(), "Error in WorkflowContextHolder timeout thread");
+ }
+ }
+ logger.debug("WorkflowContextHolder timeout thread interrupted, quitting");
+ }
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowResponse.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowResponse.java
index f5aa0b33c6..22595a8b04 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowResponse.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowResponse.java
@@ -23,56 +23,63 @@ package org.onap.so.bpmn.common.workflow.context;
import java.util.Map;
/**
- * @version 1.0
- * Synchronous workflow response bean
+ * @version 1.0 Synchronous workflow response bean
*
*/
public class WorkflowResponse {
- private String response;
- private String message;
- private String processInstanceID;
- private Map<String,String> variables;
- private int messageCode;
-
- public String getResponse() {
- return response;
- }
- public void setResponse(String response) {
- this.response = response;
- }
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
- public String getProcessInstanceID() {
- return processInstanceID;
- }
- public void setProcessInstanceID(String pID) {
- this.processInstanceID = pID;
- }
- public Map<String, String> getVariables() {
- return variables;
- }
- public void setVariables(Map<String, String> variables) {
- this.variables = variables;
- }
- public void setMessageCode(int messageCode) {
- this.messageCode = messageCode;
- }
-
- public int getMessageCode() {
- return messageCode;
- }
-
- @Override
- public String toString() {
- return "WorkflowResponse [response=" + response + ", message=" + message + ", processInstanceID="
- + processInstanceID + ", variables=" + variables + ", messageCode=" + messageCode + "]";
- }
-
-
+ private String response;
+ private String message;
+ private String processInstanceID;
+ private Map<String, String> variables;
+ private int messageCode;
+
+ public String getResponse() {
+ return response;
+ }
+
+ public void setResponse(String response) {
+ this.response = response;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public String getProcessInstanceID() {
+ return processInstanceID;
+ }
+
+ public void setProcessInstanceID(String pID) {
+ this.processInstanceID = pID;
+ }
+
+ public Map<String, String> getVariables() {
+ return variables;
+ }
+
+ public void setVariables(Map<String, String> variables) {
+ this.variables = variables;
+ }
+
+ public void setMessageCode(int messageCode) {
+ this.messageCode = messageCode;
+ }
+
+ public int getMessageCode() {
+ return messageCode;
+ }
+
+ @Override
+ public String toString() {
+ return "WorkflowResponse [response=" + response + ", message=" + message + ", processInstanceID="
+ + processInstanceID + ", variables=" + variables + ", messageCode=" + messageCode + "]";
+ }
+
+
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/Metadata.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/Metadata.java
index 1f83c3135e..f56fad3bcf 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/Metadata.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/Metadata.java
@@ -23,18 +23,17 @@ package org.onap.so.bpmn.servicedecomposition;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import org.onap.so.bpmn.servicedecomposition.bbobjects.Metadatum;
-public class Metadata implements Serializable{
-
- private static final long serialVersionUID = 4981393122007858950L;
-
- @JsonProperty("metadatum")
- private List<Metadatum> metadatum = new ArrayList<Metadatum>();
+public class Metadata implements Serializable {
+
+ private static final long serialVersionUID = 4981393122007858950L;
+
+ @JsonProperty("metadatum")
+ private List<Metadatum> metadatum = new ArrayList<Metadatum>();
- public List<Metadatum> getMetadatum() {
- return metadatum;
- }
+ public List<Metadatum> getMetadatum() {
+ return metadatum;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/ShallowCopy.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/ShallowCopy.java
index 1263e7ba7c..3fc0808741 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/ShallowCopy.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/ShallowCopy.java
@@ -21,28 +21,27 @@
package org.onap.so.bpmn.servicedecomposition;
import com.fasterxml.jackson.databind.ObjectMapper;
-
import javax.persistence.Id;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public interface ShallowCopy<T> {
- default T shallowCopyId() {
- try {
- T obj = (T) this.getClass().newInstance();
- for (Field field : this.getClass().getDeclaredFields()) {
- if (field.isAnnotationPresent(Id.class)) {
- String fieldName = Character.toUpperCase(field.getName().charAt(0)) + field.getName().substring(1);
- Method setter = this.getClass().getMethod("set" + fieldName, field.getType());
- Method getter = this.getClass().getMethod("get" + fieldName, null);
- setter.invoke(obj, getter.invoke(this, null));
- }
- }
- return obj;
- }catch(Exception e){
- throw new RuntimeException(e);
- }
+ default T shallowCopyId() {
+ try {
+ T obj = (T) this.getClass().newInstance();
+ for (Field field : this.getClass().getDeclaredFields()) {
+ if (field.isAnnotationPresent(Id.class)) {
+ String fieldName = Character.toUpperCase(field.getName().charAt(0)) + field.getName().substring(1);
+ Method setter = this.getClass().getMethod("set" + fieldName, field.getType());
+ Method getter = this.getClass().getMethod("get" + fieldName, null);
+ setter.invoke(obj, getter.invoke(this, null));
+ }
+ }
+ return obj;
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
- }
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java
index cb9c681fd5..a5eb9d86a7 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java
@@ -21,87 +21,84 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import javax.persistence.Id;
-
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
@JsonRootName("aggregate-route")
-public class AggregateRoute implements Serializable, ShallowCopy<AggregateRoute>{
-
- private static final long serialVersionUID = -1059128545462701696L;
-
- @Id
- @JsonProperty("route-id")
- private String routeId;
- @JsonProperty("route-name")
- private String routeName;
- @JsonProperty("network-start-address")
- private String networkStartAddress;
- @JsonProperty("cidr-mask")
- private String cidrMask;
- @JsonProperty("ip-version")
- private String ipVersion;
-
-
- public String getRouteId(){
- return routeId;
- }
-
- public void setRouteId(String routeId){
- this.routeId = routeId;
- }
-
- public String getRouteName(){
- return routeName;
- }
-
- public void setRouteName(String routeName){
- this.routeName = routeName;
- }
-
- public String getNetworkStartAddress(){
- return networkStartAddress;
- }
-
- public void setNetworkStartAddress(String networkStartAddress){
- this.networkStartAddress = networkStartAddress;
- }
-
- public String getCidrMask(){
- return cidrMask;
- }
-
- public void setCidrMask(String cidrMask){
- this.cidrMask = cidrMask;
- }
-
- public String getIpVersion(){
- return ipVersion;
- }
-
- public void setIpVersion(String ipVersion){
- this.ipVersion = ipVersion;
- }
-
- @Override
- public boolean equals(final Object other){
- if(!(other instanceof AggregateRoute)){
- return false;
- }
- AggregateRoute castOther = (AggregateRoute) other;
- return new EqualsBuilder().append(routeId, castOther.routeId).isEquals();
- }
-
- @Override
- public int hashCode(){
- return new HashCodeBuilder().append(routeId).toHashCode();
- }
+public class AggregateRoute implements Serializable, ShallowCopy<AggregateRoute> {
+
+ private static final long serialVersionUID = -1059128545462701696L;
+
+ @Id
+ @JsonProperty("route-id")
+ private String routeId;
+ @JsonProperty("route-name")
+ private String routeName;
+ @JsonProperty("network-start-address")
+ private String networkStartAddress;
+ @JsonProperty("cidr-mask")
+ private String cidrMask;
+ @JsonProperty("ip-version")
+ private String ipVersion;
+
+
+ public String getRouteId() {
+ return routeId;
+ }
+
+ public void setRouteId(String routeId) {
+ this.routeId = routeId;
+ }
+
+ public String getRouteName() {
+ return routeName;
+ }
+
+ public void setRouteName(String routeName) {
+ this.routeName = routeName;
+ }
+
+ public String getNetworkStartAddress() {
+ return networkStartAddress;
+ }
+
+ public void setNetworkStartAddress(String networkStartAddress) {
+ this.networkStartAddress = networkStartAddress;
+ }
+
+ public String getCidrMask() {
+ return cidrMask;
+ }
+
+ public void setCidrMask(String cidrMask) {
+ this.cidrMask = cidrMask;
+ }
+
+ public String getIpVersion() {
+ return ipVersion;
+ }
+
+ public void setIpVersion(String ipVersion) {
+ this.ipVersion = ipVersion;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof AggregateRoute)) {
+ return false;
+ }
+ AggregateRoute castOther = (AggregateRoute) other;
+ return new EqualsBuilder().append(routeId, castOther.routeId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(routeId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AllottedResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AllottedResource.java
index 775d80db75..00f41ef1e3 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AllottedResource.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AllottedResource.java
@@ -21,14 +21,11 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import javax.persistence.Id;
-
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
import org.onap.so.bpmn.servicedecomposition.homingobjects.SolutionCandidates;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoAllottedResource;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.HashCodeBuilder;
@@ -37,93 +34,112 @@ import org.apache.commons.lang3.builder.EqualsBuilder;
@JsonRootName("allotted-resource")
public class AllottedResource extends SolutionCandidates implements Serializable, ShallowCopy<AllottedResource> {
- private static final long serialVersionUID = 8674239064804424306L;
-
- @Id
- @JsonProperty("id")
- private String id;
- @JsonProperty("target-network-role")
- private String targetNetworkRole;
- @JsonProperty("self-link")
- private String selflink;
- @JsonProperty("orchestration-status")
- private OrchestrationStatus orchestrationStatus;
- @JsonProperty("operational-status")
- private String operationalStatus;
- @JsonProperty("type")
+ private static final long serialVersionUID = 8674239064804424306L;
+
+ @Id
+ @JsonProperty("id")
+ private String id;
+ @JsonProperty("target-network-role")
+ private String targetNetworkRole;
+ @JsonProperty("self-link")
+ private String selflink;
+ @JsonProperty("orchestration-status")
+ private OrchestrationStatus orchestrationStatus;
+ @JsonProperty("operational-status")
+ private String operationalStatus;
+ @JsonProperty("type")
private String type;
- @JsonProperty("role")
+ @JsonProperty("role")
private String role;
@JsonProperty("model-info-allotted-resource")
private ModelInfoAllottedResource modelInfoAllottedResource;
@JsonProperty("service-instance")
private ServiceInstance parentServiceInstance;
- public ModelInfoAllottedResource getModelInfoAllottedResource() {
- return modelInfoAllottedResource;
- }
- public void setModelInfoAllottedResource(ModelInfoAllottedResource modelInfoAllottedResource) {
- this.modelInfoAllottedResource = modelInfoAllottedResource;
- }
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getTargetNetworkRole() {
- return targetNetworkRole;
- }
- public void setTargetNetworkRole(String targetNetworkRole) {
- this.targetNetworkRole = targetNetworkRole;
- }
- public String getSelflink() {
- return selflink;
- }
- public void setSelflink(String selflink) {
- this.selflink = selflink;
- }
- public String getOperationalStatus() {
- return operationalStatus;
- }
- public void setOperationalStatus(String operationalStatus) {
- this.operationalStatus = operationalStatus;
- }
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public String getType() {
- return type;
- }
- public void setType(String type) {
- this.type = type;
- }
- public String getRole() {
- return role;
- }
- public void setRole(String role) {
- this.role = role;
- }
- public ServiceInstance getParentServiceInstance() {
- return parentServiceInstance;
- }
- public void setParentServiceInstance(ServiceInstance parentServiceInstance) {
- this.parentServiceInstance = parentServiceInstance;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof AllottedResource)) {
- return false;
- }
- AllottedResource castOther = (AllottedResource) other;
- return new EqualsBuilder().append(id, castOther.id).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(id).toHashCode();
- }
+ public ModelInfoAllottedResource getModelInfoAllottedResource() {
+ return modelInfoAllottedResource;
+ }
+
+ public void setModelInfoAllottedResource(ModelInfoAllottedResource modelInfoAllottedResource) {
+ this.modelInfoAllottedResource = modelInfoAllottedResource;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getTargetNetworkRole() {
+ return targetNetworkRole;
+ }
+
+ public void setTargetNetworkRole(String targetNetworkRole) {
+ this.targetNetworkRole = targetNetworkRole;
+ }
+
+ public String getSelflink() {
+ return selflink;
+ }
+
+ public void setSelflink(String selflink) {
+ this.selflink = selflink;
+ }
+
+ public String getOperationalStatus() {
+ return operationalStatus;
+ }
+
+ public void setOperationalStatus(String operationalStatus) {
+ this.operationalStatus = operationalStatus;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+
+ public ServiceInstance getParentServiceInstance() {
+ return parentServiceInstance;
+ }
+
+ public void setParentServiceInstance(ServiceInstance parentServiceInstance) {
+ this.parentServiceInstance = parentServiceInstance;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof AllottedResource)) {
+ return false;
+ }
+ AllottedResource castOther = (AllottedResource) other;
+ return new EqualsBuilder().append(id, castOther.id).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(id).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/CloudRegion.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/CloudRegion.java
index df1eeae1b6..6439b5a65f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/CloudRegion.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/CloudRegion.java
@@ -21,9 +21,7 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import javax.persistence.Id;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
@@ -31,82 +29,95 @@ import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
public class CloudRegion implements Serializable, ShallowCopy<CloudRegion> {
- private static final long serialVersionUID = 680593168655326021L;
-
- @Id
- @JsonProperty("lcp-cloud-region-id")
- private String lcpCloudRegionId;
- @Id
- @JsonProperty("cloud-owner")
- private String cloudOwner;
- @JsonProperty("tenant-id")
- private String tenantId;
- @JsonProperty("complex")
- private String complex;
- @JsonProperty("cloud-region-version")
- private String cloudRegionVersion;
- @JsonProperty("orchestration-disabled")
- private Boolean orchestrationDisabled;
-
- public String getLcpCloudRegionId() {
- return lcpCloudRegionId;
- }
- public void setLcpCloudRegionId(String lcpCloudRegionId) {
- this.lcpCloudRegionId = lcpCloudRegionId;
- }
- public String getTenantId() {
- return tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getCloudOwner() {
- return cloudOwner;
- }
- public void setCloudOwner(String cloudOwner) {
- this.cloudOwner = cloudOwner;
- }
- /**
- * i.e. aic version
- */
- public String getCloudRegionVersion() {
- return cloudRegionVersion;
- }
- /**
- * i.e. aic version
- */
- public void setCloudRegionVersion(String cloudRegionVersion) {
- this.cloudRegionVersion = cloudRegionVersion;
- }
- /**
- * i.e. aic clli, physical location id, site id
- */
- public String getComplex() {
- return complex;
- }
- /**
- * i.e. aic clli, physical location id, site id
- */
- public void setComplex(String complex) {
- this.complex = complex;
- }
- public Boolean getOrchestrationDisabled() {
- return orchestrationDisabled;
- }
- public void setOrchestrationDisabled(Boolean orchestrationDisabled) {
- this.orchestrationDisabled = orchestrationDisabled;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof CloudRegion)) {
- return false;
- }
- CloudRegion castOther = (CloudRegion) other;
- return new EqualsBuilder().append(lcpCloudRegionId, castOther.lcpCloudRegionId)
- .append(cloudOwner, castOther.cloudOwner).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(lcpCloudRegionId).append(cloudOwner).toHashCode();
- }
+ private static final long serialVersionUID = 680593168655326021L;
+
+ @Id
+ @JsonProperty("lcp-cloud-region-id")
+ private String lcpCloudRegionId;
+ @Id
+ @JsonProperty("cloud-owner")
+ private String cloudOwner;
+ @JsonProperty("tenant-id")
+ private String tenantId;
+ @JsonProperty("complex")
+ private String complex;
+ @JsonProperty("cloud-region-version")
+ private String cloudRegionVersion;
+ @JsonProperty("orchestration-disabled")
+ private Boolean orchestrationDisabled;
+
+ public String getLcpCloudRegionId() {
+ return lcpCloudRegionId;
+ }
+
+ public void setLcpCloudRegionId(String lcpCloudRegionId) {
+ this.lcpCloudRegionId = lcpCloudRegionId;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getCloudOwner() {
+ return cloudOwner;
+ }
+
+ public void setCloudOwner(String cloudOwner) {
+ this.cloudOwner = cloudOwner;
+ }
+
+ /**
+ * i.e. aic version
+ */
+ public String getCloudRegionVersion() {
+ return cloudRegionVersion;
+ }
+
+ /**
+ * i.e. aic version
+ */
+ public void setCloudRegionVersion(String cloudRegionVersion) {
+ this.cloudRegionVersion = cloudRegionVersion;
+ }
+
+ /**
+ * i.e. aic clli, physical location id, site id
+ */
+ public String getComplex() {
+ return complex;
+ }
+
+ /**
+ * i.e. aic clli, physical location id, site id
+ */
+ public void setComplex(String complex) {
+ this.complex = complex;
+ }
+
+ public Boolean getOrchestrationDisabled() {
+ return orchestrationDisabled;
+ }
+
+ public void setOrchestrationDisabled(Boolean orchestrationDisabled) {
+ this.orchestrationDisabled = orchestrationDisabled;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof CloudRegion)) {
+ return false;
+ }
+ CloudRegion castOther = (CloudRegion) other;
+ return new EqualsBuilder().append(lcpCloudRegionId, castOther.lcpCloudRegionId)
+ .append(cloudOwner, castOther.cloudOwner).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(lcpCloudRegionId).append(cloudOwner).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Collection.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Collection.java
index 6bbdb1ed67..1d6f9272de 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Collection.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Collection.java
@@ -22,12 +22,10 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoCollection;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@@ -35,63 +33,74 @@ import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@JsonRootName("collection")
public class Collection implements Serializable, ShallowCopy<Collection> {
-
- private static final long serialVersionUID = 6389915895863066288L;
-
- @Id
- @JsonProperty("id")
- private String id;
- @JsonProperty("model-info-collection")
- private ModelInfoCollection modelInfoCollection;
- @JsonProperty("instance-group")
- private InstanceGroup instanceGroup;
- @JsonProperty("orchestration-status")
+
+ private static final long serialVersionUID = 6389915895863066288L;
+
+ @Id
+ @JsonProperty("id")
+ private String id;
+ @JsonProperty("model-info-collection")
+ private ModelInfoCollection modelInfoCollection;
+ @JsonProperty("instance-group")
+ private InstanceGroup instanceGroup;
+ @JsonProperty("orchestration-status")
private OrchestrationStatus orchestrationStatus;
- @JsonProperty("name")
- private String name;
-
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public ModelInfoCollection getModelInfoCollection() {
- return modelInfoCollection;
- }
- public void setModelInfoCollection(ModelInfoCollection modelInfoCollection) {
- this.modelInfoCollection = modelInfoCollection;
- }
- public InstanceGroup getInstanceGroup() {
- return instanceGroup;
- }
- public void setInstanceGroup(InstanceGroup instanceGroup) {
- this.instanceGroup = instanceGroup;
- }
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Collection)) {
- return false;
- }
- Collection castOther = (Collection) other;
- return new EqualsBuilder().append(id, castOther.id).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(id).toHashCode();
- }
+ @JsonProperty("name")
+ private String name;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public ModelInfoCollection getModelInfoCollection() {
+ return modelInfoCollection;
+ }
+
+ public void setModelInfoCollection(ModelInfoCollection modelInfoCollection) {
+ this.modelInfoCollection = modelInfoCollection;
+ }
+
+ public InstanceGroup getInstanceGroup() {
+ return instanceGroup;
+ }
+
+ public void setInstanceGroup(InstanceGroup instanceGroup) {
+ this.instanceGroup = instanceGroup;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Collection)) {
+ return false;
+ }
+ Collection castOther = (Collection) other;
+ return new EqualsBuilder().append(id, castOther.id).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(id).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Configuration.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Configuration.java
index 748d37d6e4..dff5a57040 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Configuration.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Configuration.java
@@ -27,7 +27,6 @@ import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.Metadata;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoConfiguration;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import javax.persistence.Id;
import java.io.Serializable;
import java.util.ArrayList;
@@ -36,205 +35,205 @@ import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@JsonRootName("configuration")
public class Configuration implements Serializable, ShallowCopy<Configuration> {
- private static final long serialVersionUID = 4525487672816730299L;
-
- @Id
- @JsonProperty("configuration-id")
- private String configurationId;
- @JsonProperty("orchestration-status")
- private OrchestrationStatus orchestrationStatus;
- @JsonProperty("tunnel-bandwidth")
- private String tunnelBandwidth;
- @JsonProperty("vendor-allowed-max-bandwidth")
- private String vendorAllowedMaxBandwidth;
- @JsonProperty("management-option")
- private String managementOption;
- @JsonProperty("configuration-name")
- private String configurationName;
- @JsonProperty("configuration-type")
- private String configurationType;
- @JsonProperty("configuration-sub-type")
- private String configurationSubType;
- @JsonProperty("operational-status")
- private String operationalStatus;
- @JsonProperty("configuration-selflink")
- private String configurationSelflink;
- @JsonProperty("metadata")
- private Metadata metadata;
- @JsonProperty("forwarder-evcs")
- private List<ForwarderEvc> forwarderEvcs = new ArrayList<>();
- @JsonProperty("evcs")
- private List<Evc> evcs = new ArrayList<>();
- @JsonProperty("vnfc")
- private Vnfc vnfc = new Vnfc();
- @JsonProperty("model-info-configuration")
- private ModelInfoConfiguration modelInfoConfiguration;
-
- @JsonProperty("related-configuration")
- private Configuration relatedConfiguration;
-
- @JsonProperty("l3-network")
- private L3Network network;
-
- @JsonProperty("l-interface")
- private LInterface lInterface;
-
- public ModelInfoConfiguration getModelInfoConfiguration() {
- return modelInfoConfiguration;
- }
-
- public void setModelInfoConfiguration(ModelInfoConfiguration modelInfoConfiguration) {
- this.modelInfoConfiguration = modelInfoConfiguration;
- }
-
- public List<ForwarderEvc> getForwarderEvcs() {
- return forwarderEvcs;
- }
-
- public Vnfc getVnfc() {
- return vnfc;
- }
-
- public void setVnfc(Vnfc vnfc) {
- this.vnfc = vnfc;
- }
-
- public List<Evc> getEvcs() {
- return evcs;
- }
-
- public String getConfigurationId() {
- return configurationId;
- }
-
- public void setConfigurationId(String configurationId) {
- this.configurationId = configurationId;
- }
-
- public String getManagementOption() {
- return managementOption;
- }
-
- public void setManagementOption(String managementOption) {
- this.managementOption = managementOption;
- }
-
- public String getConfigurationName() {
- return configurationName;
- }
-
- public void setConfigurationName(String configurationName) {
- this.configurationName = configurationName;
- }
-
- public String getConfigurationType() {
- return configurationType;
- }
-
- public void setConfigurationType(String configurationType) {
- this.configurationType = configurationType;
- }
-
- public String getConfigurationSubType() {
- return configurationSubType;
- }
-
- public void setConfigurationSubType(String configurationSubType) {
- this.configurationSubType = configurationSubType;
- }
-
- public String getOperationalStatus() {
- return operationalStatus;
- }
-
- public void setOperationalStatus(String operationalStatus) {
- this.operationalStatus = operationalStatus;
- }
-
- public String getConfigurationSelflink() {
- return configurationSelflink;
- }
-
- public void setConfigurationSelflink(String configurationSelflink) {
- this.configurationSelflink = configurationSelflink;
- }
-
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
-
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
-
- public String getTunnelBandwidth() {
- return tunnelBandwidth;
- }
-
- public void setTunnelBandwidth(String tunnelBandwidth) {
- this.tunnelBandwidth = tunnelBandwidth;
- }
-
- public String getVendorAllowedMaxBandwidth() {
- return vendorAllowedMaxBandwidth;
- }
-
- public void setVendorAllowedMaxBandwidth(String vendorAllowedMaxBandwidth) {
- this.vendorAllowedMaxBandwidth = vendorAllowedMaxBandwidth;
- }
-
- public Metadata getMetadata() {
- return metadata;
- }
-
- public void setMetadata(Metadata metadata) {
- this.metadata = metadata;
- }
-
- public Configuration getRelatedConfiguration() {
- return relatedConfiguration;
- }
-
- public void setRelatedConfiguration(Configuration relatedConfiguration) {
- this.relatedConfiguration = relatedConfiguration;
- }
-
- public void setForwarderEvcs(List<ForwarderEvc> forwarderEvcs) {
- this.forwarderEvcs = forwarderEvcs;
- }
-
- public void setEvcs(List<Evc> evcs) {
- this.evcs = evcs;
- }
-
- public L3Network getNetwork() {
- return network;
- }
-
- public void setNetwork(L3Network network) {
- this.network = network;
- }
-
- public LInterface getlInterface() {
- return lInterface;
- }
-
- public void setlInterface(LInterface lInterface) {
- this.lInterface = lInterface;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Configuration)) {
- return false;
- }
- Configuration castOther = (Configuration) other;
- return new EqualsBuilder().append(configurationId, castOther.configurationId).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(configurationId).toHashCode();
- }
-
+ private static final long serialVersionUID = 4525487672816730299L;
+
+ @Id
+ @JsonProperty("configuration-id")
+ private String configurationId;
+ @JsonProperty("orchestration-status")
+ private OrchestrationStatus orchestrationStatus;
+ @JsonProperty("tunnel-bandwidth")
+ private String tunnelBandwidth;
+ @JsonProperty("vendor-allowed-max-bandwidth")
+ private String vendorAllowedMaxBandwidth;
+ @JsonProperty("management-option")
+ private String managementOption;
+ @JsonProperty("configuration-name")
+ private String configurationName;
+ @JsonProperty("configuration-type")
+ private String configurationType;
+ @JsonProperty("configuration-sub-type")
+ private String configurationSubType;
+ @JsonProperty("operational-status")
+ private String operationalStatus;
+ @JsonProperty("configuration-selflink")
+ private String configurationSelflink;
+ @JsonProperty("metadata")
+ private Metadata metadata;
+ @JsonProperty("forwarder-evcs")
+ private List<ForwarderEvc> forwarderEvcs = new ArrayList<>();
+ @JsonProperty("evcs")
+ private List<Evc> evcs = new ArrayList<>();
+ @JsonProperty("vnfc")
+ private Vnfc vnfc = new Vnfc();
+ @JsonProperty("model-info-configuration")
+ private ModelInfoConfiguration modelInfoConfiguration;
+
+ @JsonProperty("related-configuration")
+ private Configuration relatedConfiguration;
+
+ @JsonProperty("l3-network")
+ private L3Network network;
+
+ @JsonProperty("l-interface")
+ private LInterface lInterface;
+
+ public ModelInfoConfiguration getModelInfoConfiguration() {
+ return modelInfoConfiguration;
+ }
+
+ public void setModelInfoConfiguration(ModelInfoConfiguration modelInfoConfiguration) {
+ this.modelInfoConfiguration = modelInfoConfiguration;
+ }
+
+ public List<ForwarderEvc> getForwarderEvcs() {
+ return forwarderEvcs;
+ }
+
+ public Vnfc getVnfc() {
+ return vnfc;
+ }
+
+ public void setVnfc(Vnfc vnfc) {
+ this.vnfc = vnfc;
+ }
+
+ public List<Evc> getEvcs() {
+ return evcs;
+ }
+
+ public String getConfigurationId() {
+ return configurationId;
+ }
+
+ public void setConfigurationId(String configurationId) {
+ this.configurationId = configurationId;
+ }
+
+ public String getManagementOption() {
+ return managementOption;
+ }
+
+ public void setManagementOption(String managementOption) {
+ this.managementOption = managementOption;
+ }
+
+ public String getConfigurationName() {
+ return configurationName;
+ }
+
+ public void setConfigurationName(String configurationName) {
+ this.configurationName = configurationName;
+ }
+
+ public String getConfigurationType() {
+ return configurationType;
+ }
+
+ public void setConfigurationType(String configurationType) {
+ this.configurationType = configurationType;
+ }
+
+ public String getConfigurationSubType() {
+ return configurationSubType;
+ }
+
+ public void setConfigurationSubType(String configurationSubType) {
+ this.configurationSubType = configurationSubType;
+ }
+
+ public String getOperationalStatus() {
+ return operationalStatus;
+ }
+
+ public void setOperationalStatus(String operationalStatus) {
+ this.operationalStatus = operationalStatus;
+ }
+
+ public String getConfigurationSelflink() {
+ return configurationSelflink;
+ }
+
+ public void setConfigurationSelflink(String configurationSelflink) {
+ this.configurationSelflink = configurationSelflink;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public String getTunnelBandwidth() {
+ return tunnelBandwidth;
+ }
+
+ public void setTunnelBandwidth(String tunnelBandwidth) {
+ this.tunnelBandwidth = tunnelBandwidth;
+ }
+
+ public String getVendorAllowedMaxBandwidth() {
+ return vendorAllowedMaxBandwidth;
+ }
+
+ public void setVendorAllowedMaxBandwidth(String vendorAllowedMaxBandwidth) {
+ this.vendorAllowedMaxBandwidth = vendorAllowedMaxBandwidth;
+ }
+
+ public Metadata getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(Metadata metadata) {
+ this.metadata = metadata;
+ }
+
+ public Configuration getRelatedConfiguration() {
+ return relatedConfiguration;
+ }
+
+ public void setRelatedConfiguration(Configuration relatedConfiguration) {
+ this.relatedConfiguration = relatedConfiguration;
+ }
+
+ public void setForwarderEvcs(List<ForwarderEvc> forwarderEvcs) {
+ this.forwarderEvcs = forwarderEvcs;
+ }
+
+ public void setEvcs(List<Evc> evcs) {
+ this.evcs = evcs;
+ }
+
+ public L3Network getNetwork() {
+ return network;
+ }
+
+ public void setNetwork(L3Network network) {
+ this.network = network;
+ }
+
+ public LInterface getlInterface() {
+ return lInterface;
+ }
+
+ public void setlInterface(LInterface lInterface) {
+ this.lInterface = lInterface;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Configuration)) {
+ return false;
+ }
+ Configuration castOther = (Configuration) other;
+ return new EqualsBuilder().append(configurationId, castOther.configurationId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(configurationId).toHashCode();
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/CtagAssignment.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/CtagAssignment.java
index 978f1e9324..8194485d2b 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/CtagAssignment.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/CtagAssignment.java
@@ -21,45 +21,43 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("ctag-assignment")
public class CtagAssignment implements Serializable, ShallowCopy<CtagAssignment> {
-
- private static final long serialVersionUID = 2314290576523243571L;
- @Id
- @JsonProperty("vlan-id-inner")
- private Long vlanIdInner;
-
- public Long getVlanIdInner() {
- return vlanIdInner;
- }
+ private static final long serialVersionUID = 2314290576523243571L;
+
+ @Id
+ @JsonProperty("vlan-id-inner")
+ private Long vlanIdInner;
+
+ public Long getVlanIdInner() {
+ return vlanIdInner;
+ }
+
+ public void setVlanIdInner(Long vlanIdInner) {
+ this.vlanIdInner = vlanIdInner;
+ }
- public void setVlanIdInner(Long vlanIdInner) {
- this.vlanIdInner = vlanIdInner;
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof CtagAssignment)) {
+ return false;
+ }
+ CtagAssignment castOther = (CtagAssignment) other;
+ return new EqualsBuilder().append(vlanIdInner, castOther.vlanIdInner).isEquals();
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof CtagAssignment)) {
- return false;
- }
- CtagAssignment castOther = (CtagAssignment) other;
- return new EqualsBuilder().append(vlanIdInner, castOther.vlanIdInner).isEquals();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(vlanIdInner).toHashCode();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(vlanIdInner).toHashCode();
- }
-
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Customer.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Customer.java
index 985f51035c..30492ddf61 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Customer.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Customer.java
@@ -23,9 +23,7 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import javax.persistence.Id;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
@@ -35,65 +33,77 @@ import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@JsonRootName("customer")
public class Customer implements Serializable, ShallowCopy<Customer> {
- private static final long serialVersionUID = 2006599484099139618L;
-
- @Id
- @JsonProperty("global-customer-id")
- private String globalCustomerId;
- @JsonProperty("subscriber-name")
- private String subscriberName;
- @JsonProperty("subscriber-type")
- private String subscriberType;
- @JsonProperty("subscriber-common-site-id")
- private String subscriberCommonSiteId;
- @JsonProperty("service-subscription")
+ private static final long serialVersionUID = 2006599484099139618L;
+
+ @Id
+ @JsonProperty("global-customer-id")
+ private String globalCustomerId;
+ @JsonProperty("subscriber-name")
+ private String subscriberName;
+ @JsonProperty("subscriber-type")
+ private String subscriberType;
+ @JsonProperty("subscriber-common-site-id")
+ private String subscriberCommonSiteId;
+ @JsonProperty("service-subscription")
private ServiceSubscription serviceSubscription;
@JsonProperty("vpn-bindings")
- private List<VpnBinding> vpnBindings = new ArrayList<>();
-
- public String getGlobalCustomerId() {
- return globalCustomerId;
- }
- public void setGlobalCustomerId(String globalCustomerId) {
- this.globalCustomerId = globalCustomerId;
- }
- public String getSubscriberName() {
- return subscriberName;
- }
- public void setSubscriberName(String subscriberName) {
- this.subscriberName = subscriberName;
- }
- public String getSubscriberType() {
- return subscriberType;
- }
- public void setSubscriberType(String subscriberType) {
- this.subscriberType = subscriberType;
- }
- public String getSubscriberCommonSiteId() {
- return subscriberCommonSiteId;
- }
- public void setSubscriberCommonSiteId(String subscriberCommonSiteId) {
- this.subscriberCommonSiteId = subscriberCommonSiteId;
- }
- public ServiceSubscription getServiceSubscription() {
- return serviceSubscription;
- }
- public void setServiceSubscription(ServiceSubscription serviceSubscription) {
- this.serviceSubscription = serviceSubscription;
- }
- public List<VpnBinding> getVpnBindings() {
- return vpnBindings;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Customer)) {
- return false;
- }
- Customer castOther = (Customer) other;
- return new EqualsBuilder().append(globalCustomerId, castOther.globalCustomerId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(globalCustomerId).toHashCode();
- }
+ private List<VpnBinding> vpnBindings = new ArrayList<>();
+
+ public String getGlobalCustomerId() {
+ return globalCustomerId;
+ }
+
+ public void setGlobalCustomerId(String globalCustomerId) {
+ this.globalCustomerId = globalCustomerId;
+ }
+
+ public String getSubscriberName() {
+ return subscriberName;
+ }
+
+ public void setSubscriberName(String subscriberName) {
+ this.subscriberName = subscriberName;
+ }
+
+ public String getSubscriberType() {
+ return subscriberType;
+ }
+
+ public void setSubscriberType(String subscriberType) {
+ this.subscriberType = subscriberType;
+ }
+
+ public String getSubscriberCommonSiteId() {
+ return subscriberCommonSiteId;
+ }
+
+ public void setSubscriberCommonSiteId(String subscriberCommonSiteId) {
+ this.subscriberCommonSiteId = subscriberCommonSiteId;
+ }
+
+ public ServiceSubscription getServiceSubscription() {
+ return serviceSubscription;
+ }
+
+ public void setServiceSubscription(ServiceSubscription serviceSubscription) {
+ this.serviceSubscription = serviceSubscription;
+ }
+
+ public List<VpnBinding> getVpnBindings() {
+ return vpnBindings;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Customer)) {
+ return false;
+ }
+ Customer castOther = (Customer) other;
+ return new EqualsBuilder().append(globalCustomerId, castOther.globalCustomerId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(globalCustomerId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Entitlement.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Entitlement.java
index fdcb59d3c3..dd97aa55ad 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Entitlement.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Entitlement.java
@@ -21,50 +21,53 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("entitlement")
-public class Entitlement implements Serializable, ShallowCopy<Entitlement>{
-
- private static final long serialVersionUID = 5186878328988717088L;
+public class Entitlement implements Serializable, ShallowCopy<Entitlement> {
- @Id
- @JsonProperty("group-uuid")
+ private static final long serialVersionUID = 5186878328988717088L;
+
+ @Id
+ @JsonProperty("group-uuid")
private String groupUuid;
- @Id
- @JsonProperty("resource-uuid")
+ @Id
+ @JsonProperty("resource-uuid")
private String resourceUuid;
- public String getGroupUuid() {
- return groupUuid;
- }
- public void setGroupUuid(String groupUuid) {
- this.groupUuid = groupUuid;
- }
- public String getResourceUuid() {
- return resourceUuid;
- }
- public void setResourceUuid(String resourceUuid) {
- this.resourceUuid = resourceUuid;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Entitlement)) {
- return false;
- }
- Entitlement castOther = (Entitlement) other;
- return new EqualsBuilder().append(groupUuid, castOther.groupUuid).append(resourceUuid, castOther.resourceUuid)
- .isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(groupUuid).append(resourceUuid).toHashCode();
- }
+ public String getGroupUuid() {
+ return groupUuid;
+ }
+
+ public void setGroupUuid(String groupUuid) {
+ this.groupUuid = groupUuid;
+ }
+
+ public String getResourceUuid() {
+ return resourceUuid;
+ }
+
+ public void setResourceUuid(String resourceUuid) {
+ this.resourceUuid = resourceUuid;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Entitlement)) {
+ return false;
+ }
+ Entitlement castOther = (Entitlement) other;
+ return new EqualsBuilder().append(groupUuid, castOther.groupUuid).append(resourceUuid, castOther.resourceUuid)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(groupUuid).append(resourceUuid).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Evc.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Evc.java
index 3ef0f71386..c7e6ebc9a7 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Evc.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Evc.java
@@ -21,40 +21,38 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("evc")
public class Evc implements Serializable, ShallowCopy<Evc> {
- private static final long serialVersionUID = -3556506672371317659L;
+ private static final long serialVersionUID = -3556506672371317659L;
- @Id
- @JsonProperty("evc-id")
+ @Id
+ @JsonProperty("evc-id")
private String evcId;
- @JsonProperty("forwarding-path-topology")
+ @JsonProperty("forwarding-path-topology")
private String forwardingPathTopology;
- @JsonProperty("cir-value")
+ @JsonProperty("cir-value")
private String cirValue;
- @JsonProperty("cir-units")
+ @JsonProperty("cir-units")
private String cirUnits;
- @JsonProperty("connection-diversity-group-id")
+ @JsonProperty("connection-diversity-group-id")
private String connectionDiversityGroupId;
- @JsonProperty("service-hours")
+ @JsonProperty("service-hours")
private String serviceHours;
- @JsonProperty("esp-evc-circuit-id")
+ @JsonProperty("esp-evc-circuit-id")
private String espEvcCircuitId;
- @JsonProperty("esp-evc-cir-value")
+ @JsonProperty("esp-evc-cir-value")
private String espEvcCirValue;
- @JsonProperty("esp-evc-cir-units")
+ @JsonProperty("esp-evc-cir-units")
private String espEvcCirUnits;
- @JsonProperty("esp-itu-code")
+ @JsonProperty("esp-itu-code")
private String espItuCode;
@JsonProperty("collector-pop-clli")
private String collectorPopClli;
@@ -65,100 +63,129 @@ public class Evc implements Serializable, ShallowCopy<Evc> {
@JsonProperty("tagmode-access-egress")
private String tagmodeAccessEgress;
- public String getEvcId() {
- return evcId;
- }
- public void setEvcId(String evcId) {
- this.evcId = evcId;
- }
- public String getForwardingPathTopology() {
- return forwardingPathTopology;
- }
- public void setForwardingPathTopology(String forwardingPathTopology) {
- this.forwardingPathTopology = forwardingPathTopology;
- }
- public String getCirValue() {
- return cirValue;
- }
- public void setCirValue(String cirValue) {
- this.cirValue = cirValue;
- }
- public String getCirUnits() {
- return cirUnits;
- }
- public void setCirUnits(String cirUnits) {
- this.cirUnits = cirUnits;
- }
- public String getConnectionDiversityGroupId() {
- return connectionDiversityGroupId;
- }
- public void setConnectionDiversityGroupId(String connectionDiversityGroupId) {
- this.connectionDiversityGroupId = connectionDiversityGroupId;
- }
- public String getServiceHours() {
- return serviceHours;
- }
- public void setServiceHours(String serviceHours) {
- this.serviceHours = serviceHours;
- }
- public String getEspEvcCircuitId() {
- return espEvcCircuitId;
- }
- public void setEspEvcCircuitId(String espEvcCircuitId) {
- this.espEvcCircuitId = espEvcCircuitId;
- }
- public String getEspEvcCirValue() {
- return espEvcCirValue;
- }
- public void setEspEvcCirValue(String espEvcCirValue) {
- this.espEvcCirValue = espEvcCirValue;
- }
- public String getEspEvcCirUnits() {
- return espEvcCirUnits;
- }
- public void setEspEvcCirUnits(String espEvcCirUnits) {
- this.espEvcCirUnits = espEvcCirUnits;
- }
- public String getEspItuCode() {
- return espItuCode;
- }
- public void setEspItuCode(String espItuCode) {
- this.espItuCode = espItuCode;
- }
- public String getCollectorPopClli() {
- return collectorPopClli;
- }
- public void setCollectorPopClli(String collectorPopClli) {
- this.collectorPopClli = collectorPopClli;
- }
- public String getInterConnectTypeIngress() {
- return interConnectTypeIngress;
- }
- public void setInterConnectTypeIngress(String interConnectTypeIngress) {
- this.interConnectTypeIngress = interConnectTypeIngress;
- }
- public String getTagmodeAccessIngress() {
- return tagmodeAccessIngress;
- }
- public void setTagmodeAccessIngress(String tagmodeAccessIngress) {
- this.tagmodeAccessIngress = tagmodeAccessIngress;
- }
- public String getTagmodeAccessEgress() {
- return tagmodeAccessEgress;
- }
- public void setTagmodeAccessEgress(String tagmodeAccessEgress) {
- this.tagmodeAccessEgress = tagmodeAccessEgress;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Evc)) {
- return false;
- }
- Evc castOther = (Evc) other;
- return new EqualsBuilder().append(evcId, castOther.evcId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(evcId).toHashCode();
- }
+ public String getEvcId() {
+ return evcId;
+ }
+
+ public void setEvcId(String evcId) {
+ this.evcId = evcId;
+ }
+
+ public String getForwardingPathTopology() {
+ return forwardingPathTopology;
+ }
+
+ public void setForwardingPathTopology(String forwardingPathTopology) {
+ this.forwardingPathTopology = forwardingPathTopology;
+ }
+
+ public String getCirValue() {
+ return cirValue;
+ }
+
+ public void setCirValue(String cirValue) {
+ this.cirValue = cirValue;
+ }
+
+ public String getCirUnits() {
+ return cirUnits;
+ }
+
+ public void setCirUnits(String cirUnits) {
+ this.cirUnits = cirUnits;
+ }
+
+ public String getConnectionDiversityGroupId() {
+ return connectionDiversityGroupId;
+ }
+
+ public void setConnectionDiversityGroupId(String connectionDiversityGroupId) {
+ this.connectionDiversityGroupId = connectionDiversityGroupId;
+ }
+
+ public String getServiceHours() {
+ return serviceHours;
+ }
+
+ public void setServiceHours(String serviceHours) {
+ this.serviceHours = serviceHours;
+ }
+
+ public String getEspEvcCircuitId() {
+ return espEvcCircuitId;
+ }
+
+ public void setEspEvcCircuitId(String espEvcCircuitId) {
+ this.espEvcCircuitId = espEvcCircuitId;
+ }
+
+ public String getEspEvcCirValue() {
+ return espEvcCirValue;
+ }
+
+ public void setEspEvcCirValue(String espEvcCirValue) {
+ this.espEvcCirValue = espEvcCirValue;
+ }
+
+ public String getEspEvcCirUnits() {
+ return espEvcCirUnits;
+ }
+
+ public void setEspEvcCirUnits(String espEvcCirUnits) {
+ this.espEvcCirUnits = espEvcCirUnits;
+ }
+
+ public String getEspItuCode() {
+ return espItuCode;
+ }
+
+ public void setEspItuCode(String espItuCode) {
+ this.espItuCode = espItuCode;
+ }
+
+ public String getCollectorPopClli() {
+ return collectorPopClli;
+ }
+
+ public void setCollectorPopClli(String collectorPopClli) {
+ this.collectorPopClli = collectorPopClli;
+ }
+
+ public String getInterConnectTypeIngress() {
+ return interConnectTypeIngress;
+ }
+
+ public void setInterConnectTypeIngress(String interConnectTypeIngress) {
+ this.interConnectTypeIngress = interConnectTypeIngress;
+ }
+
+ public String getTagmodeAccessIngress() {
+ return tagmodeAccessIngress;
+ }
+
+ public void setTagmodeAccessIngress(String tagmodeAccessIngress) {
+ this.tagmodeAccessIngress = tagmodeAccessIngress;
+ }
+
+ public String getTagmodeAccessEgress() {
+ return tagmodeAccessEgress;
+ }
+
+ public void setTagmodeAccessEgress(String tagmodeAccessEgress) {
+ this.tagmodeAccessEgress = tagmodeAccessEgress;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Evc)) {
+ return false;
+ }
+ Evc castOther = (Evc) other;
+ return new EqualsBuilder().append(evcId, castOther.evcId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(evcId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ForwarderEvc.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ForwarderEvc.java
index 70f7d5af42..716dd1a57b 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ForwarderEvc.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ForwarderEvc.java
@@ -21,83 +21,81 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("forwarder-evc")
public class ForwarderEvc implements Serializable, ShallowCopy<ForwarderEvc> {
- private static final long serialVersionUID = 3822241337439817708L;
-
- @Id
- @JsonProperty("forwarder-evc-id")
- private String forwarderEvcId;
- @JsonProperty("circuit-id")
- private String circuitId;
- @JsonProperty("ivlan")
- private String ivlan;
- @JsonProperty("svlan")
- private String svlan;
- @JsonProperty("cvlan")
- private String cvlan;
-
- public String getForwarderEvcId() {
- return forwarderEvcId;
- }
-
- public void setForwarderEvcId(String forwarderEvcId) {
- this.forwarderEvcId = forwarderEvcId;
- }
-
- public String getCircuitId() {
- return circuitId;
- }
-
- public void setCircuitId(String circuitId) {
- this.circuitId = circuitId;
- }
-
- public String getIvlan() {
- return ivlan;
- }
-
- public void setIvlan(String ivlan) {
- this.ivlan = ivlan;
- }
-
- public String getSvlan() {
- return svlan;
- }
-
- public void setSvlan(String svlan) {
- this.svlan = svlan;
- }
-
- public String getCvlan() {
- return cvlan;
- }
-
- public void setCvlan(String cvlan) {
- this.cvlan = cvlan;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ForwarderEvc)) {
- return false;
- }
- ForwarderEvc castOther = (ForwarderEvc) other;
- return new EqualsBuilder().append(forwarderEvcId, castOther.forwarderEvcId).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(forwarderEvcId).toHashCode();
- }
+ private static final long serialVersionUID = 3822241337439817708L;
+
+ @Id
+ @JsonProperty("forwarder-evc-id")
+ private String forwarderEvcId;
+ @JsonProperty("circuit-id")
+ private String circuitId;
+ @JsonProperty("ivlan")
+ private String ivlan;
+ @JsonProperty("svlan")
+ private String svlan;
+ @JsonProperty("cvlan")
+ private String cvlan;
+
+ public String getForwarderEvcId() {
+ return forwarderEvcId;
+ }
+
+ public void setForwarderEvcId(String forwarderEvcId) {
+ this.forwarderEvcId = forwarderEvcId;
+ }
+
+ public String getCircuitId() {
+ return circuitId;
+ }
+
+ public void setCircuitId(String circuitId) {
+ this.circuitId = circuitId;
+ }
+
+ public String getIvlan() {
+ return ivlan;
+ }
+
+ public void setIvlan(String ivlan) {
+ this.ivlan = ivlan;
+ }
+
+ public String getSvlan() {
+ return svlan;
+ }
+
+ public void setSvlan(String svlan) {
+ this.svlan = svlan;
+ }
+
+ public String getCvlan() {
+ return cvlan;
+ }
+
+ public void setCvlan(String cvlan) {
+ this.cvlan = cvlan;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ForwarderEvc)) {
+ return false;
+ }
+ ForwarderEvc castOther = (ForwarderEvc) other;
+ return new EqualsBuilder().append(forwarderEvcId, castOther.forwarderEvcId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(forwarderEvcId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java
index c6e7668f22..841546b3b1 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java
@@ -25,9 +25,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@@ -35,516 +33,515 @@ import org.onap.so.bpmn.servicedecomposition.generalobjects.License;
import org.onap.so.bpmn.servicedecomposition.homingobjects.SolutionInfo;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("generic-vnf")
public class GenericVnf implements Serializable, ShallowCopy<GenericVnf> {
- private static final long serialVersionUID = -5107610336831330403L;
-
- @Id
- @JsonProperty("vnf-id")
- private String vnfId;
- @JsonProperty("vnf-name")
- private String vnfName;
- @JsonProperty("vnf-type")
- private String vnfType;
- @JsonProperty("orchestration-status")
- private OrchestrationStatus orchestrationStatus;
- @JsonProperty("vf-modules")
- private List<VfModule> vfModules = new ArrayList<>();
- @JsonProperty("volume-groups")
- private List<VolumeGroup> volumeGroups = new ArrayList<>();
- @JsonProperty("line-of-business")
- private LineOfBusiness lineOfBusiness;
- @JsonProperty("platform")
- private Platform platform;
- @JsonProperty("cascaded")
- private Boolean cascaded;
- @JsonProperty("cloud-params")
- private Map<String, String> cloudParams = new HashMap<>();
- @JsonProperty("cloud-context")
- private CloudRegion cloudRegion;
- @JsonProperty("solution")
- private SolutionInfo solution;
- @JsonProperty("vnf-name-2")
- private String vnfName2;
- @JsonProperty("service-id")
- private String serviceId;
- @JsonProperty("regional-resource-zone")
- private String regionalResourceZone;
- @JsonProperty("prov-status")
- private String provStatus;
- @JsonProperty("operational-status")
- private String operationalStatus;
- @JsonProperty("equipment-role")
- private String equipmentRole;
- @JsonProperty("management-option")
- private String managementOption;
- @JsonProperty("ipv4-oam-address")
- private String ipv4OamAddress;
- @JsonProperty("ipv4-loopback0-address")
- private String ipv4Loopback0Address;
- @JsonProperty("nm-lan-v6-address")
- private String nmLanV6Address;
- @JsonProperty("management-v6-address")
- private String managementV6Address;
- @JsonProperty("vcpu")
- private Long vcpu;
- @JsonProperty("vcpu-units")
- private String vcpuUnits;
- @JsonProperty("vmemory")
- private Long vmemory;
- @JsonProperty("vmemory-units")
- private String vmemoryUnits;
- @JsonProperty("vdisk")
- private Long vdisk;
- @JsonProperty("vdisk-units")
- private String vdiskUnits;
- @JsonProperty("in-maint")
- private Boolean inMaint;
- @JsonProperty("is-closed-loop-disabled")
- private Boolean isClosedLoopDisabled;
- @JsonProperty("summary-status")
- private String summaryStatus;
- @JsonProperty("encrypted-access-flag")
- private Boolean encryptedAccessFlag;
- @JsonProperty("as-number")
- private String asNumber;
- @JsonProperty("regional-resource-subzone")
- private String regionalResourceSubzone;
- @JsonProperty("self-link")
- private String selflink;
- @JsonProperty("ipv4-oam-gateway-address")
- private String ipv4OamGatewayAddress;
- @JsonProperty("ipv4-oam-gateway-address-prefix-length")
- private Integer ipv4OamGatewayAddressPrefixLength;
- @JsonProperty("vlan-id-outer")
- private Long vlanIdOuter;
- @JsonProperty("nm-profile-name")
- private String nmProfileName;
- @JsonProperty("l-interfaces")
- private List<LInterface> lInterfaces = new ArrayList<>();
- @JsonProperty("lag-interfaces")
- private List<LagInterface> lagInterfaces = new ArrayList<>();
- @JsonProperty("license")
- private License license;
- @JsonProperty("entitlements") //TODO remove, duplicated
- private List<Entitlement> entitlements = new ArrayList<>();
- @JsonProperty("model-info-generic-vnf")
- private ModelInfoGenericVnf modelInfoGenericVnf;
- @JsonProperty("instance-groups")
+ private static final long serialVersionUID = -5107610336831330403L;
+
+ @Id
+ @JsonProperty("vnf-id")
+ private String vnfId;
+ @JsonProperty("vnf-name")
+ private String vnfName;
+ @JsonProperty("vnf-type")
+ private String vnfType;
+ @JsonProperty("orchestration-status")
+ private OrchestrationStatus orchestrationStatus;
+ @JsonProperty("vf-modules")
+ private List<VfModule> vfModules = new ArrayList<>();
+ @JsonProperty("volume-groups")
+ private List<VolumeGroup> volumeGroups = new ArrayList<>();
+ @JsonProperty("line-of-business")
+ private LineOfBusiness lineOfBusiness;
+ @JsonProperty("platform")
+ private Platform platform;
+ @JsonProperty("cascaded")
+ private Boolean cascaded;
+ @JsonProperty("cloud-params")
+ private Map<String, String> cloudParams = new HashMap<>();
+ @JsonProperty("cloud-context")
+ private CloudRegion cloudRegion;
+ @JsonProperty("solution")
+ private SolutionInfo solution;
+ @JsonProperty("vnf-name-2")
+ private String vnfName2;
+ @JsonProperty("service-id")
+ private String serviceId;
+ @JsonProperty("regional-resource-zone")
+ private String regionalResourceZone;
+ @JsonProperty("prov-status")
+ private String provStatus;
+ @JsonProperty("operational-status")
+ private String operationalStatus;
+ @JsonProperty("equipment-role")
+ private String equipmentRole;
+ @JsonProperty("management-option")
+ private String managementOption;
+ @JsonProperty("ipv4-oam-address")
+ private String ipv4OamAddress;
+ @JsonProperty("ipv4-loopback0-address")
+ private String ipv4Loopback0Address;
+ @JsonProperty("nm-lan-v6-address")
+ private String nmLanV6Address;
+ @JsonProperty("management-v6-address")
+ private String managementV6Address;
+ @JsonProperty("vcpu")
+ private Long vcpu;
+ @JsonProperty("vcpu-units")
+ private String vcpuUnits;
+ @JsonProperty("vmemory")
+ private Long vmemory;
+ @JsonProperty("vmemory-units")
+ private String vmemoryUnits;
+ @JsonProperty("vdisk")
+ private Long vdisk;
+ @JsonProperty("vdisk-units")
+ private String vdiskUnits;
+ @JsonProperty("in-maint")
+ private Boolean inMaint;
+ @JsonProperty("is-closed-loop-disabled")
+ private Boolean isClosedLoopDisabled;
+ @JsonProperty("summary-status")
+ private String summaryStatus;
+ @JsonProperty("encrypted-access-flag")
+ private Boolean encryptedAccessFlag;
+ @JsonProperty("as-number")
+ private String asNumber;
+ @JsonProperty("regional-resource-subzone")
+ private String regionalResourceSubzone;
+ @JsonProperty("self-link")
+ private String selflink;
+ @JsonProperty("ipv4-oam-gateway-address")
+ private String ipv4OamGatewayAddress;
+ @JsonProperty("ipv4-oam-gateway-address-prefix-length")
+ private Integer ipv4OamGatewayAddressPrefixLength;
+ @JsonProperty("vlan-id-outer")
+ private Long vlanIdOuter;
+ @JsonProperty("nm-profile-name")
+ private String nmProfileName;
+ @JsonProperty("l-interfaces")
+ private List<LInterface> lInterfaces = new ArrayList<>();
+ @JsonProperty("lag-interfaces")
+ private List<LagInterface> lagInterfaces = new ArrayList<>();
+ @JsonProperty("license")
+ private License license;
+ @JsonProperty("entitlements") // TODO remove, duplicated
+ private List<Entitlement> entitlements = new ArrayList<>();
+ @JsonProperty("model-info-generic-vnf")
+ private ModelInfoGenericVnf modelInfoGenericVnf;
+ @JsonProperty("instance-groups")
private List<InstanceGroup> instanceGroups = new ArrayList<InstanceGroup>();
- @JsonProperty("call-homing")
- private Boolean callHoming;
- @JsonProperty("nf-function")
- private String nfFunction;
- @JsonProperty("nf-role")
- private String nfRole;
- @JsonProperty("CDS_BLUEPRINT_NAME")
- private String blueprintName;
- @JsonProperty("CDS_BLUEPRINT_VERSION")
- private String blueprintVersion;
-
-
- public String getBlueprintName() {
- return blueprintName;
- }
-
- public void setBlueprintName(String blueprintName) {
- this.blueprintName = blueprintName;
- }
-
- public String getBlueprintVersion() {
- return blueprintVersion;
- }
-
- public void setBlueprintVersion(String blueprintVersion) {
- this.blueprintVersion = blueprintVersion;
- }
-
- public String getNfFunction() {
- return nfFunction;
- }
-
- public void setNfFunction(String nfFunction) {
- this.nfFunction = nfFunction;
- }
-
- public String getNfRole() {
- return nfRole;
- }
-
- public void setNfRole(String nfRole) {
- this.nfRole = nfRole;
- }
-
- public List<InstanceGroup> getInstanceGroups() {
- return instanceGroups;
- }
-
- public List<VolumeGroup> getVolumeGroups() {
- return volumeGroups;
- }
-
- public ModelInfoGenericVnf getModelInfoGenericVnf() {
- return modelInfoGenericVnf;
- }
-
- public void setModelInfoGenericVnf(ModelInfoGenericVnf modelInfoGenericVnf) {
- this.modelInfoGenericVnf = modelInfoGenericVnf;
- }
-
- public String getVnfName2() {
- return vnfName2;
- }
-
- public void setVnfName2(String vnfName2) {
- this.vnfName2 = vnfName2;
- }
-
- public String getServiceId() {
- return serviceId;
- }
-
- public void setServiceId(String serviceId) {
- this.serviceId = serviceId;
- }
-
- public String getRegionalResourceZone() {
- return regionalResourceZone;
- }
-
- public void setRegionalResourceZone(String regionalResourceZone) {
- this.regionalResourceZone = regionalResourceZone;
- }
-
- public String getProvStatus() {
- return provStatus;
- }
-
- public void setProvStatus(String provStatus) {
- this.provStatus = provStatus;
- }
-
- public String getOperationalStatus() {
- return operationalStatus;
- }
-
- public void setOperationalStatus(String operationalStatus) {
- this.operationalStatus = operationalStatus;
- }
-
- public String getEquipmentRole() {
- return equipmentRole;
- }
+ @JsonProperty("call-homing")
+ private Boolean callHoming;
+ @JsonProperty("nf-function")
+ private String nfFunction;
+ @JsonProperty("nf-role")
+ private String nfRole;
+ @JsonProperty("CDS_BLUEPRINT_NAME")
+ private String blueprintName;
+ @JsonProperty("CDS_BLUEPRINT_VERSION")
+ private String blueprintVersion;
+
+
+ public String getBlueprintName() {
+ return blueprintName;
+ }
+
+ public void setBlueprintName(String blueprintName) {
+ this.blueprintName = blueprintName;
+ }
+
+ public String getBlueprintVersion() {
+ return blueprintVersion;
+ }
+
+ public void setBlueprintVersion(String blueprintVersion) {
+ this.blueprintVersion = blueprintVersion;
+ }
+
+ public String getNfFunction() {
+ return nfFunction;
+ }
+
+ public void setNfFunction(String nfFunction) {
+ this.nfFunction = nfFunction;
+ }
+
+ public String getNfRole() {
+ return nfRole;
+ }
+
+ public void setNfRole(String nfRole) {
+ this.nfRole = nfRole;
+ }
+
+ public List<InstanceGroup> getInstanceGroups() {
+ return instanceGroups;
+ }
+
+ public List<VolumeGroup> getVolumeGroups() {
+ return volumeGroups;
+ }
+
+ public ModelInfoGenericVnf getModelInfoGenericVnf() {
+ return modelInfoGenericVnf;
+ }
+
+ public void setModelInfoGenericVnf(ModelInfoGenericVnf modelInfoGenericVnf) {
+ this.modelInfoGenericVnf = modelInfoGenericVnf;
+ }
+
+ public String getVnfName2() {
+ return vnfName2;
+ }
+
+ public void setVnfName2(String vnfName2) {
+ this.vnfName2 = vnfName2;
+ }
+
+ public String getServiceId() {
+ return serviceId;
+ }
+
+ public void setServiceId(String serviceId) {
+ this.serviceId = serviceId;
+ }
+
+ public String getRegionalResourceZone() {
+ return regionalResourceZone;
+ }
+
+ public void setRegionalResourceZone(String regionalResourceZone) {
+ this.regionalResourceZone = regionalResourceZone;
+ }
+
+ public String getProvStatus() {
+ return provStatus;
+ }
+
+ public void setProvStatus(String provStatus) {
+ this.provStatus = provStatus;
+ }
+
+ public String getOperationalStatus() {
+ return operationalStatus;
+ }
+
+ public void setOperationalStatus(String operationalStatus) {
+ this.operationalStatus = operationalStatus;
+ }
+
+ public String getEquipmentRole() {
+ return equipmentRole;
+ }
- public void setEquipmentRole(String equipmentRole) {
- this.equipmentRole = equipmentRole;
- }
+ public void setEquipmentRole(String equipmentRole) {
+ this.equipmentRole = equipmentRole;
+ }
- public String getManagementOption() {
- return managementOption;
- }
+ public String getManagementOption() {
+ return managementOption;
+ }
- public void setManagementOption(String managementOption) {
- this.managementOption = managementOption;
- }
+ public void setManagementOption(String managementOption) {
+ this.managementOption = managementOption;
+ }
- public String getIpv4OamAddress() {
- return ipv4OamAddress;
- }
+ public String getIpv4OamAddress() {
+ return ipv4OamAddress;
+ }
- public void setIpv4OamAddress(String ipv4OamAddress) {
- this.ipv4OamAddress = ipv4OamAddress;
- }
+ public void setIpv4OamAddress(String ipv4OamAddress) {
+ this.ipv4OamAddress = ipv4OamAddress;
+ }
- public String getIpv4Loopback0Address() {
- return ipv4Loopback0Address;
- }
+ public String getIpv4Loopback0Address() {
+ return ipv4Loopback0Address;
+ }
- public void setIpv4Loopback0Address(String ipv4Loopback0Address) {
- this.ipv4Loopback0Address = ipv4Loopback0Address;
- }
+ public void setIpv4Loopback0Address(String ipv4Loopback0Address) {
+ this.ipv4Loopback0Address = ipv4Loopback0Address;
+ }
- public String getNmLanV6Address() {
- return nmLanV6Address;
- }
+ public String getNmLanV6Address() {
+ return nmLanV6Address;
+ }
- public void setNmLanV6Address(String nmLanV6Address) {
- this.nmLanV6Address = nmLanV6Address;
- }
+ public void setNmLanV6Address(String nmLanV6Address) {
+ this.nmLanV6Address = nmLanV6Address;
+ }
- public String getManagementV6Address() {
- return managementV6Address;
- }
+ public String getManagementV6Address() {
+ return managementV6Address;
+ }
- public void setManagementV6Address(String managementV6Address) {
- this.managementV6Address = managementV6Address;
- }
+ public void setManagementV6Address(String managementV6Address) {
+ this.managementV6Address = managementV6Address;
+ }
- public Long getVcpu() {
- return vcpu;
- }
+ public Long getVcpu() {
+ return vcpu;
+ }
- public void setVcpu(Long vcpu) {
- this.vcpu = vcpu;
- }
+ public void setVcpu(Long vcpu) {
+ this.vcpu = vcpu;
+ }
- public String getVcpuUnits() {
- return vcpuUnits;
- }
+ public String getVcpuUnits() {
+ return vcpuUnits;
+ }
- public void setVcpuUnits(String vcpuUnits) {
- this.vcpuUnits = vcpuUnits;
- }
+ public void setVcpuUnits(String vcpuUnits) {
+ this.vcpuUnits = vcpuUnits;
+ }
- public List<LInterface> getlInterfaces() {
- return lInterfaces;
- }
+ public List<LInterface> getlInterfaces() {
+ return lInterfaces;
+ }
- public List<LagInterface> getLagInterfaces() {
- return lagInterfaces;
- }
+ public List<LagInterface> getLagInterfaces() {
+ return lagInterfaces;
+ }
- public List<Entitlement> getEntitlements() {
- return entitlements;
- }
+ public List<Entitlement> getEntitlements() {
+ return entitlements;
+ }
- public List<VfModule> getVfModules() {
- return vfModules;
- }
+ public List<VfModule> getVfModules() {
+ return vfModules;
+ }
- public Long getVmemory() {
- return vmemory;
- }
+ public Long getVmemory() {
+ return vmemory;
+ }
- public void setVmemory(Long vmemory) {
- this.vmemory = vmemory;
- }
+ public void setVmemory(Long vmemory) {
+ this.vmemory = vmemory;
+ }
- public String getVmemoryUnits() {
- return vmemoryUnits;
- }
+ public String getVmemoryUnits() {
+ return vmemoryUnits;
+ }
- public void setVmemoryUnits(String vmemoryUnits) {
- this.vmemoryUnits = vmemoryUnits;
- }
+ public void setVmemoryUnits(String vmemoryUnits) {
+ this.vmemoryUnits = vmemoryUnits;
+ }
- public Long getVdisk() {
- return vdisk;
- }
+ public Long getVdisk() {
+ return vdisk;
+ }
- public void setVdisk(Long vdisk) {
- this.vdisk = vdisk;
- }
+ public void setVdisk(Long vdisk) {
+ this.vdisk = vdisk;
+ }
- public String getVdiskUnits() {
- return vdiskUnits;
- }
+ public String getVdiskUnits() {
+ return vdiskUnits;
+ }
- public void setVdiskUnits(String vdiskUnits) {
- this.vdiskUnits = vdiskUnits;
- }
+ public void setVdiskUnits(String vdiskUnits) {
+ this.vdiskUnits = vdiskUnits;
+ }
- public Boolean isInMaint() {
- return inMaint;
- }
+ public Boolean isInMaint() {
+ return inMaint;
+ }
- public void setInMaint(Boolean inMaint) {
- this.inMaint = inMaint;
- }
+ public void setInMaint(Boolean inMaint) {
+ this.inMaint = inMaint;
+ }
- public Boolean isIsClosedLoopDisabled() {
- return isClosedLoopDisabled;
- }
+ public Boolean isIsClosedLoopDisabled() {
+ return isClosedLoopDisabled;
+ }
- public void setClosedLoopDisabled(Boolean isClosedLoopDisabled) {
- this.isClosedLoopDisabled = isClosedLoopDisabled;
- }
+ public void setClosedLoopDisabled(Boolean isClosedLoopDisabled) {
+ this.isClosedLoopDisabled = isClosedLoopDisabled;
+ }
- public String getSummaryStatus() {
- return summaryStatus;
- }
+ public String getSummaryStatus() {
+ return summaryStatus;
+ }
- public void setSummaryStatus(String summaryStatus) {
- this.summaryStatus = summaryStatus;
- }
+ public void setSummaryStatus(String summaryStatus) {
+ this.summaryStatus = summaryStatus;
+ }
- public Boolean getEncryptedAccessFlag() {
- return encryptedAccessFlag;
- }
+ public Boolean getEncryptedAccessFlag() {
+ return encryptedAccessFlag;
+ }
- public void setEncryptedAccessFlag(Boolean encryptedAccessFlag) {
- this.encryptedAccessFlag = encryptedAccessFlag;
- }
+ public void setEncryptedAccessFlag(Boolean encryptedAccessFlag) {
+ this.encryptedAccessFlag = encryptedAccessFlag;
+ }
- public String getAsNumber() {
- return asNumber;
- }
+ public String getAsNumber() {
+ return asNumber;
+ }
- public void setAsNumber(String asNumber) {
- this.asNumber = asNumber;
- }
+ public void setAsNumber(String asNumber) {
+ this.asNumber = asNumber;
+ }
- public String getRegionalResourceSubzone() {
- return regionalResourceSubzone;
- }
+ public String getRegionalResourceSubzone() {
+ return regionalResourceSubzone;
+ }
- public void setRegionalResourceSubzone(String regionalResourceSubzone) {
- this.regionalResourceSubzone = regionalResourceSubzone;
- }
+ public void setRegionalResourceSubzone(String regionalResourceSubzone) {
+ this.regionalResourceSubzone = regionalResourceSubzone;
+ }
- public License getLicense() {
- return license;
- }
+ public License getLicense() {
+ return license;
+ }
- public void setLicense(License license) {
- this.license = license;
- }
+ public void setLicense(License license) {
+ this.license = license;
+ }
- public String getSelflink() {
- return selflink;
- }
+ public String getSelflink() {
+ return selflink;
+ }
- public void setSelflink(String selflink) {
- this.selflink = selflink;
- }
+ public void setSelflink(String selflink) {
+ this.selflink = selflink;
+ }
- public String getIpv4OamGatewayAddress() {
- return ipv4OamGatewayAddress;
- }
+ public String getIpv4OamGatewayAddress() {
+ return ipv4OamGatewayAddress;
+ }
- public void setIpv4OamGatewayAddress(String ipv4OamGatewayAddress) {
- this.ipv4OamGatewayAddress = ipv4OamGatewayAddress;
- }
+ public void setIpv4OamGatewayAddress(String ipv4OamGatewayAddress) {
+ this.ipv4OamGatewayAddress = ipv4OamGatewayAddress;
+ }
- public Integer getIpv4OamGatewayAddressPrefixLength() {
- return ipv4OamGatewayAddressPrefixLength;
- }
+ public Integer getIpv4OamGatewayAddressPrefixLength() {
+ return ipv4OamGatewayAddressPrefixLength;
+ }
- public void setIpv4OamGatewayAddressPrefixLength(Integer ipv4OamGatewayAddressPrefixLength) {
- this.ipv4OamGatewayAddressPrefixLength = ipv4OamGatewayAddressPrefixLength;
- }
+ public void setIpv4OamGatewayAddressPrefixLength(Integer ipv4OamGatewayAddressPrefixLength) {
+ this.ipv4OamGatewayAddressPrefixLength = ipv4OamGatewayAddressPrefixLength;
+ }
- public Long getVlanIdOuter() {
- return vlanIdOuter;
- }
+ public Long getVlanIdOuter() {
+ return vlanIdOuter;
+ }
- public void setVlanIdOuter(Long vlanIdOuter) {
- this.vlanIdOuter = vlanIdOuter;
- }
+ public void setVlanIdOuter(Long vlanIdOuter) {
+ this.vlanIdOuter = vlanIdOuter;
+ }
- public String getNmProfileName() {
- return nmProfileName;
- }
-
- public void setNmProfileName(String nmProfileName) {
- this.nmProfileName = nmProfileName;
- }
-
- public String getVnfId() {
- return vnfId;
- }
-
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
-
- public String getVnfName() {
- return vnfName;
- }
-
- public void setVnfName(String vnfName) {
- this.vnfName = vnfName;
- }
-
- public String getVnfType() {
- return vnfType;
- }
-
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
-
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
-
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
-
- public LineOfBusiness getLineOfBusiness() {
- return lineOfBusiness;
- }
-
- public void setLineOfBusiness(LineOfBusiness lineOfBusiness) {
- this.lineOfBusiness = lineOfBusiness;
- }
-
- public Platform getPlatform() {
- return platform;
- }
-
- public void setPlatform(Platform platform) {
- this.platform = platform;
- }
-
- public Boolean isCascaded() {
- return cascaded;
- }
-
- public void setCascaded(Boolean cascaded) {
- this.cascaded = cascaded;
- }
-
- public Map<String, String> getCloudParams() {
- return cloudParams;
- }
-
- public void setCloudParams(Map<String, String> cloudParams) {
- this.cloudParams = cloudParams;
- }
-
- public SolutionInfo getSolution() {
- return solution;
- }
-
- public void setSolution(SolutionInfo solution) {
- this.solution = solution;
- }
-
- public CloudRegion getCloudRegion() {
- return cloudRegion;
- }
-
- public void setCloudRegion(CloudRegion cloudRegion) {
- this.cloudRegion = cloudRegion;
- }
-
- public Boolean isCallHoming() {
- return callHoming;
- }
-
- public void setCallHoming(Boolean callHoming) {
- this.callHoming = callHoming;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof GenericVnf)) {
- return false;
- }
- GenericVnf castOther = (GenericVnf) other;
- return new EqualsBuilder().append(vnfId, castOther.vnfId).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(vnfId).toHashCode();
- }
+ public String getNmProfileName() {
+ return nmProfileName;
+ }
+
+ public void setNmProfileName(String nmProfileName) {
+ this.nmProfileName = nmProfileName;
+ }
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getVnfName() {
+ return vnfName;
+ }
+
+ public void setVnfName(String vnfName) {
+ this.vnfName = vnfName;
+ }
+
+ public String getVnfType() {
+ return vnfType;
+ }
+
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public LineOfBusiness getLineOfBusiness() {
+ return lineOfBusiness;
+ }
+
+ public void setLineOfBusiness(LineOfBusiness lineOfBusiness) {
+ this.lineOfBusiness = lineOfBusiness;
+ }
+
+ public Platform getPlatform() {
+ return platform;
+ }
+
+ public void setPlatform(Platform platform) {
+ this.platform = platform;
+ }
+
+ public Boolean isCascaded() {
+ return cascaded;
+ }
+
+ public void setCascaded(Boolean cascaded) {
+ this.cascaded = cascaded;
+ }
+
+ public Map<String, String> getCloudParams() {
+ return cloudParams;
+ }
+
+ public void setCloudParams(Map<String, String> cloudParams) {
+ this.cloudParams = cloudParams;
+ }
+
+ public SolutionInfo getSolution() {
+ return solution;
+ }
+
+ public void setSolution(SolutionInfo solution) {
+ this.solution = solution;
+ }
+
+ public CloudRegion getCloudRegion() {
+ return cloudRegion;
+ }
+
+ public void setCloudRegion(CloudRegion cloudRegion) {
+ this.cloudRegion = cloudRegion;
+ }
+
+ public Boolean isCallHoming() {
+ return callHoming;
+ }
+
+ public void setCallHoming(Boolean callHoming) {
+ this.callHoming = callHoming;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof GenericVnf)) {
+ return false;
+ }
+ GenericVnf castOther = (GenericVnf) other;
+ return new EqualsBuilder().append(vnfId, castOther.vnfId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(vnfId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/HostRoute.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/HostRoute.java
index 75356ac9db..f8cc594d11 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/HostRoute.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/HostRoute.java
@@ -21,64 +21,71 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("host-route")
-public class HostRoute implements Serializable, ShallowCopy<HostRoute>{
+public class HostRoute implements Serializable, ShallowCopy<HostRoute> {
- private static final long serialVersionUID = -2468793257174064133L;
+ private static final long serialVersionUID = -2468793257174064133L;
- @Id
- @JsonProperty("host-route-id")
+ @Id
+ @JsonProperty("host-route-id")
private String hostRouteId;
- @JsonProperty("route-prefix")
+ @JsonProperty("route-prefix")
private String routePrefix;
- @JsonProperty("next-hop")
+ @JsonProperty("next-hop")
private String nextHop;
- @JsonProperty("next-hop-type")
+ @JsonProperty("next-hop-type")
private String nextHopType;
- public String getHostRouteId() {
- return hostRouteId;
- }
- public void setHostRouteId(String hostRouteId) {
- this.hostRouteId = hostRouteId;
- }
- public String getRoutePrefix() {
- return routePrefix;
- }
- public void setRoutePrefix(String routePrefix) {
- this.routePrefix = routePrefix;
- }
- public String getNextHop() {
- return nextHop;
- }
- public void setNextHop(String nextHop) {
- this.nextHop = nextHop;
- }
- public String getNextHopType() {
- return nextHopType;
- }
- public void setNextHopType(String nextHopType) {
- this.nextHopType = nextHopType;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof HostRoute)) {
- return false;
- }
- HostRoute castOther = (HostRoute) other;
- return new EqualsBuilder().append(hostRouteId, castOther.hostRouteId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(hostRouteId).toHashCode();
- }
+ public String getHostRouteId() {
+ return hostRouteId;
+ }
+
+ public void setHostRouteId(String hostRouteId) {
+ this.hostRouteId = hostRouteId;
+ }
+
+ public String getRoutePrefix() {
+ return routePrefix;
+ }
+
+ public void setRoutePrefix(String routePrefix) {
+ this.routePrefix = routePrefix;
+ }
+
+ public String getNextHop() {
+ return nextHop;
+ }
+
+ public void setNextHop(String nextHop) {
+ this.nextHop = nextHop;
+ }
+
+ public String getNextHopType() {
+ return nextHopType;
+ }
+
+ public void setNextHopType(String nextHopType) {
+ this.nextHopType = nextHopType;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof HostRoute)) {
+ return false;
+ }
+ HostRoute castOther = (HostRoute) other;
+ return new EqualsBuilder().append(hostRouteId, castOther.hostRouteId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(hostRouteId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/InstanceGroup.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/InstanceGroup.java
index 7a58f6db6b..4edaecdbca 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/InstanceGroup.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/InstanceGroup.java
@@ -23,99 +23,113 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoInstanceGroup;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("instance-group")
-public class InstanceGroup implements Serializable, ShallowCopy<InstanceGroup> {
-
- private static final long serialVersionUID = -2330859693128099141L;
-
- @Id
- @JsonProperty("id")
- private String id;
- @JsonProperty("description")
- private String description;
- @JsonProperty("resource-version")
- private String resourceVersion;
- @JsonProperty("instance-group-name")
- private String instanceGroupName;
- @JsonProperty("orchestration-status")
- private OrchestrationStatus orchestrationStatus = OrchestrationStatus.PRECREATED;
- @JsonProperty("model-info-instance-group")
- private ModelInfoInstanceGroup modelInfoInstanceGroup;
- @JsonProperty("instance-group-function")
- private String instanceGroupFunction;
- @JsonProperty("vnfs")
- private List<GenericVnf> vnfs = new ArrayList<>();
-
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- public String getResourceVersion() {
- return resourceVersion;
- }
- public void setResourceVersion(String resourceVersion) {
- this.resourceVersion = resourceVersion;
- }
- public String getInstanceGroupName() {
- return instanceGroupName;
- }
- public void setInstanceGroupName(String instanceGroupName) {
- this.instanceGroupName = instanceGroupName;
- }
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public ModelInfoInstanceGroup getModelInfoInstanceGroup() {
- return modelInfoInstanceGroup;
- }
- public void setModelInfoInstanceGroup(ModelInfoInstanceGroup modelInfoInstanceGroup) {
- this.modelInfoInstanceGroup = modelInfoInstanceGroup;
- }
- public String getInstanceGroupFunction() {
- return instanceGroupFunction;
- }
- public void setInstanceGroupFunction(String instanceGroupFunction) {
- this.instanceGroupFunction = instanceGroupFunction;
- }
- public List<GenericVnf> getVnfs() {
- return vnfs;
- }
- public void setVnfs(List<GenericVnf> vnfs) {
- this.vnfs = vnfs;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof InstanceGroup)) {
- return false;
- }
- InstanceGroup castOther = (InstanceGroup) other;
- return new EqualsBuilder().append(id, castOther.id).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(id).toHashCode();
- }
+public class InstanceGroup implements Serializable, ShallowCopy<InstanceGroup> {
+
+ private static final long serialVersionUID = -2330859693128099141L;
+
+ @Id
+ @JsonProperty("id")
+ private String id;
+ @JsonProperty("description")
+ private String description;
+ @JsonProperty("resource-version")
+ private String resourceVersion;
+ @JsonProperty("instance-group-name")
+ private String instanceGroupName;
+ @JsonProperty("orchestration-status")
+ private OrchestrationStatus orchestrationStatus = OrchestrationStatus.PRECREATED;
+ @JsonProperty("model-info-instance-group")
+ private ModelInfoInstanceGroup modelInfoInstanceGroup;
+ @JsonProperty("instance-group-function")
+ private String instanceGroupFunction;
+ @JsonProperty("vnfs")
+ private List<GenericVnf> vnfs = new ArrayList<>();
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getResourceVersion() {
+ return resourceVersion;
+ }
+
+ public void setResourceVersion(String resourceVersion) {
+ this.resourceVersion = resourceVersion;
+ }
+
+ public String getInstanceGroupName() {
+ return instanceGroupName;
+ }
+
+ public void setInstanceGroupName(String instanceGroupName) {
+ this.instanceGroupName = instanceGroupName;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public ModelInfoInstanceGroup getModelInfoInstanceGroup() {
+ return modelInfoInstanceGroup;
+ }
+
+ public void setModelInfoInstanceGroup(ModelInfoInstanceGroup modelInfoInstanceGroup) {
+ this.modelInfoInstanceGroup = modelInfoInstanceGroup;
+ }
+
+ public String getInstanceGroupFunction() {
+ return instanceGroupFunction;
+ }
+
+ public void setInstanceGroupFunction(String instanceGroupFunction) {
+ this.instanceGroupFunction = instanceGroupFunction;
+ }
+
+ public List<GenericVnf> getVnfs() {
+ return vnfs;
+ }
+
+ public void setVnfs(List<GenericVnf> vnfs) {
+ this.vnfs = vnfs;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof InstanceGroup)) {
+ return false;
+ }
+ InstanceGroup castOther = (InstanceGroup) other;
+ return new EqualsBuilder().append(id, castOther.id).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(id).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3InterfaceIpv4AddressList.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3InterfaceIpv4AddressList.java
index 55b8a752b6..b064d53945 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3InterfaceIpv4AddressList.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3InterfaceIpv4AddressList.java
@@ -21,88 +21,101 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("l3-interface-ipv4-address-list")
-public class L3InterfaceIpv4AddressList implements Serializable, ShallowCopy<L3InterfaceIpv4AddressList>{
+public class L3InterfaceIpv4AddressList implements Serializable, ShallowCopy<L3InterfaceIpv4AddressList> {
- private static final long serialVersionUID = -1566884527411610879L;
+ private static final long serialVersionUID = -1566884527411610879L;
- @Id
- @JsonProperty("l3-interface-ipv4-address")
+ @Id
+ @JsonProperty("l3-interface-ipv4-address")
private String l3InterfaceIpv4Address;
- @JsonProperty("l3-interface-ipv4-prefix-length")
+ @JsonProperty("l3-interface-ipv4-prefix-length")
private Long l3InterfaceIpv4PrefixLength;
- @JsonProperty("vlan-id-inner")
+ @JsonProperty("vlan-id-inner")
private Long vlanIdInner;
- @JsonProperty("vlan-id-outer")
+ @JsonProperty("vlan-id-outer")
private Long vlanIdOuter;
- @JsonProperty("is-floating")
+ @JsonProperty("is-floating")
private Boolean isFloating;
- @JsonProperty("neutron-network-id")
+ @JsonProperty("neutron-network-id")
private String neutronNetworkId;
- @JsonProperty("neutron-subnet-id")
+ @JsonProperty("neutron-subnet-id")
private String neutronSubnetId;
- public String getL3InterfaceIpv4Address() {
- return l3InterfaceIpv4Address;
- }
- public void setL3InterfaceIpv4Address(String l3InterfaceIpv4Address) {
- this.l3InterfaceIpv4Address = l3InterfaceIpv4Address;
- }
- public Long getL3InterfaceIpv4PrefixLength() {
- return l3InterfaceIpv4PrefixLength;
- }
- public void setL3InterfaceIpv4PrefixLength(Long l3InterfaceIpv4PrefixLength) {
- this.l3InterfaceIpv4PrefixLength = l3InterfaceIpv4PrefixLength;
- }
- public Long getVlanIdInner() {
- return vlanIdInner;
- }
- public void setVlanIdInner(Long vlanIdInner) {
- this.vlanIdInner = vlanIdInner;
- }
- public Long getVlanIdOuter() {
- return vlanIdOuter;
- }
- public void setVlanIdOuter(Long vlanIdOuter) {
- this.vlanIdOuter = vlanIdOuter;
- }
- public Boolean getIsFloating() {
- return isFloating;
- }
- public void setIsFloating(Boolean isFloating) {
- this.isFloating = isFloating;
- }
- public String getNeutronNetworkId() {
- return neutronNetworkId;
- }
- public void setNeutronNetworkId(String neutronNetworkId) {
- this.neutronNetworkId = neutronNetworkId;
- }
- public String getNeutronSubnetId() {
- return neutronSubnetId;
- }
- public void setNeutronSubnetId(String neutronSubnetId) {
- this.neutronSubnetId = neutronSubnetId;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof L3InterfaceIpv4AddressList)) {
- return false;
- }
- L3InterfaceIpv4AddressList castOther = (L3InterfaceIpv4AddressList) other;
- return new EqualsBuilder().append(l3InterfaceIpv4Address, castOther.l3InterfaceIpv4Address).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(l3InterfaceIpv4Address).toHashCode();
- }
+ public String getL3InterfaceIpv4Address() {
+ return l3InterfaceIpv4Address;
+ }
+
+ public void setL3InterfaceIpv4Address(String l3InterfaceIpv4Address) {
+ this.l3InterfaceIpv4Address = l3InterfaceIpv4Address;
+ }
+
+ public Long getL3InterfaceIpv4PrefixLength() {
+ return l3InterfaceIpv4PrefixLength;
+ }
+
+ public void setL3InterfaceIpv4PrefixLength(Long l3InterfaceIpv4PrefixLength) {
+ this.l3InterfaceIpv4PrefixLength = l3InterfaceIpv4PrefixLength;
+ }
+
+ public Long getVlanIdInner() {
+ return vlanIdInner;
+ }
+
+ public void setVlanIdInner(Long vlanIdInner) {
+ this.vlanIdInner = vlanIdInner;
+ }
+
+ public Long getVlanIdOuter() {
+ return vlanIdOuter;
+ }
+
+ public void setVlanIdOuter(Long vlanIdOuter) {
+ this.vlanIdOuter = vlanIdOuter;
+ }
+
+ public Boolean getIsFloating() {
+ return isFloating;
+ }
+
+ public void setIsFloating(Boolean isFloating) {
+ this.isFloating = isFloating;
+ }
+
+ public String getNeutronNetworkId() {
+ return neutronNetworkId;
+ }
+
+ public void setNeutronNetworkId(String neutronNetworkId) {
+ this.neutronNetworkId = neutronNetworkId;
+ }
+
+ public String getNeutronSubnetId() {
+ return neutronSubnetId;
+ }
+
+ public void setNeutronSubnetId(String neutronSubnetId) {
+ this.neutronSubnetId = neutronSubnetId;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof L3InterfaceIpv4AddressList)) {
+ return false;
+ }
+ L3InterfaceIpv4AddressList castOther = (L3InterfaceIpv4AddressList) other;
+ return new EqualsBuilder().append(l3InterfaceIpv4Address, castOther.l3InterfaceIpv4Address).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(l3InterfaceIpv4Address).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3InterfaceIpv6AddressList.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3InterfaceIpv6AddressList.java
index 209c64762f..ffdcad5a13 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3InterfaceIpv6AddressList.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3InterfaceIpv6AddressList.java
@@ -21,103 +21,101 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("l3-interface-ipv6-address-list")
public class L3InterfaceIpv6AddressList implements Serializable, ShallowCopy<L3InterfaceIpv6AddressList> {
- private static final long serialVersionUID = -414901751774739052L;
-
- @Id
- @JsonProperty("l3-interface-ipv6-address")
- private String l3InterfaceIpv6Address;
- @JsonProperty("l3-interface-ipv6-prefix-length")
- private Long l3InterfaceIpv6PrefixLength;
- @JsonProperty("vlan-id-inner")
- private Long vlanIdInner;
- @JsonProperty("vlan-id-outer")
- private Long vlanIdOuter;
- @JsonProperty("is-floating")
- private Boolean isFloating;
- @JsonProperty("neutron-network-id")
- private String neutronNetworkId;
- @JsonProperty("neutron-subnet-id")
- private String neutronSubnetId;
-
- public String getL3InterfaceIpv6Address() {
- return l3InterfaceIpv6Address;
- }
-
- public void setL3InterfaceIpv6Address(String l3InterfaceIpv6Address) {
- this.l3InterfaceIpv6Address = l3InterfaceIpv6Address;
- }
-
- public Long getL3InterfaceIpv6PrefixLength() {
- return l3InterfaceIpv6PrefixLength;
- }
-
- public void setL3InterfaceIpv6PrefixLength(Long l3InterfaceIpv6PrefixLength) {
- this.l3InterfaceIpv6PrefixLength = l3InterfaceIpv6PrefixLength;
- }
-
- public Long getVlanIdInner() {
- return vlanIdInner;
- }
-
- public void setVlanIdInner(Long vlanIdInner) {
- this.vlanIdInner = vlanIdInner;
- }
-
- public Long getVlanIdOuter() {
- return vlanIdOuter;
- }
-
- public void setVlanIdOuter(Long vlanIdOuter) {
- this.vlanIdOuter = vlanIdOuter;
- }
-
- public Boolean getIsFloating() {
- return isFloating;
- }
-
- public void setIsFloating(Boolean isFloating) {
- this.isFloating = isFloating;
- }
-
- public String getNeutronNetworkId() {
- return neutronNetworkId;
- }
-
- public void setNeutronNetworkId(String neutronNetworkId) {
- this.neutronNetworkId = neutronNetworkId;
- }
-
- public String getNeutronSubnetId() {
- return neutronSubnetId;
- }
-
- public void setNeutronSubnetId(String neutronSubnetId) {
- this.neutronSubnetId = neutronSubnetId;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof L3InterfaceIpv6AddressList)) {
- return false;
- }
- L3InterfaceIpv6AddressList castOther = (L3InterfaceIpv6AddressList) other;
- return new EqualsBuilder().append(l3InterfaceIpv6Address, castOther.l3InterfaceIpv6Address).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(l3InterfaceIpv6Address).toHashCode();
- }
+ private static final long serialVersionUID = -414901751774739052L;
+
+ @Id
+ @JsonProperty("l3-interface-ipv6-address")
+ private String l3InterfaceIpv6Address;
+ @JsonProperty("l3-interface-ipv6-prefix-length")
+ private Long l3InterfaceIpv6PrefixLength;
+ @JsonProperty("vlan-id-inner")
+ private Long vlanIdInner;
+ @JsonProperty("vlan-id-outer")
+ private Long vlanIdOuter;
+ @JsonProperty("is-floating")
+ private Boolean isFloating;
+ @JsonProperty("neutron-network-id")
+ private String neutronNetworkId;
+ @JsonProperty("neutron-subnet-id")
+ private String neutronSubnetId;
+
+ public String getL3InterfaceIpv6Address() {
+ return l3InterfaceIpv6Address;
+ }
+
+ public void setL3InterfaceIpv6Address(String l3InterfaceIpv6Address) {
+ this.l3InterfaceIpv6Address = l3InterfaceIpv6Address;
+ }
+
+ public Long getL3InterfaceIpv6PrefixLength() {
+ return l3InterfaceIpv6PrefixLength;
+ }
+
+ public void setL3InterfaceIpv6PrefixLength(Long l3InterfaceIpv6PrefixLength) {
+ this.l3InterfaceIpv6PrefixLength = l3InterfaceIpv6PrefixLength;
+ }
+
+ public Long getVlanIdInner() {
+ return vlanIdInner;
+ }
+
+ public void setVlanIdInner(Long vlanIdInner) {
+ this.vlanIdInner = vlanIdInner;
+ }
+
+ public Long getVlanIdOuter() {
+ return vlanIdOuter;
+ }
+
+ public void setVlanIdOuter(Long vlanIdOuter) {
+ this.vlanIdOuter = vlanIdOuter;
+ }
+
+ public Boolean getIsFloating() {
+ return isFloating;
+ }
+
+ public void setIsFloating(Boolean isFloating) {
+ this.isFloating = isFloating;
+ }
+
+ public String getNeutronNetworkId() {
+ return neutronNetworkId;
+ }
+
+ public void setNeutronNetworkId(String neutronNetworkId) {
+ this.neutronNetworkId = neutronNetworkId;
+ }
+
+ public String getNeutronSubnetId() {
+ return neutronSubnetId;
+ }
+
+ public void setNeutronSubnetId(String neutronSubnetId) {
+ this.neutronSubnetId = neutronSubnetId;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof L3InterfaceIpv6AddressList)) {
+ return false;
+ }
+ L3InterfaceIpv6AddressList castOther = (L3InterfaceIpv6AddressList) other;
+ return new EqualsBuilder().append(l3InterfaceIpv6Address, castOther.l3InterfaceIpv6Address).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(l3InterfaceIpv6Address).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3Network.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3Network.java
index 781eba3332..6b3ad1d528 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3Network.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3Network.java
@@ -25,258 +25,305 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoNetwork;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("l3Network")
public class L3Network implements Serializable, ShallowCopy<L3Network> {
- private static final long serialVersionUID = 4434492567957111317L;
+ private static final long serialVersionUID = 4434492567957111317L;
- @Id
- @JsonProperty("network-id")
- private String networkId;
- @JsonProperty("cascaded")
- private Boolean cascaded;
- @JsonProperty("cloud-params")
- private Map<String, String> cloudParams = new HashMap<>();
- @JsonProperty("network-name")
+ @Id
+ @JsonProperty("network-id")
+ private String networkId;
+ @JsonProperty("cascaded")
+ private Boolean cascaded;
+ @JsonProperty("cloud-params")
+ private Map<String, String> cloudParams = new HashMap<>();
+ @JsonProperty("network-name")
private String networkName;
- @JsonProperty("neutron-network-id")
- private String neutronNetworkId;
- @JsonProperty("network-type")
- private String networkType;
- @JsonProperty("network-technology")
- private String networkTechnology;
- @JsonProperty("network-role")
- private String networkRole;
- @JsonProperty("is-bound-to-vpn")
+ @JsonProperty("neutron-network-id")
+ private String neutronNetworkId;
+ @JsonProperty("network-type")
+ private String networkType;
+ @JsonProperty("network-technology")
+ private String networkTechnology;
+ @JsonProperty("network-role")
+ private String networkRole;
+ @JsonProperty("is-bound-to-vpn")
private Boolean isBoundToVpn;
- @JsonProperty("service-id")
+ @JsonProperty("service-id")
private String serviceId;
- @JsonProperty("network-role-instance")
+ @JsonProperty("network-role-instance")
private Long networkRoleInstance;
- @JsonProperty("orchestration-status")
+ @JsonProperty("orchestration-status")
private OrchestrationStatus orchestrationStatus;
- @JsonProperty("heat-stack-id")
+ @JsonProperty("heat-stack-id")
private String heatStackId;
- @JsonProperty("contrail-network-fqdn")
+ @JsonProperty("contrail-network-fqdn")
private String contrailNetworkFqdn;
- @JsonProperty("network-policies")
- private List<NetworkPolicy> networkPolicies = new ArrayList<>();
- @JsonProperty("contrail-network-route-table-references")
- private List<RouteTableReference> contrailNetworkRouteTableReferences = new ArrayList<>();
- @JsonProperty("widget-model-id")
+ @JsonProperty("network-policies")
+ private List<NetworkPolicy> networkPolicies = new ArrayList<>();
+ @JsonProperty("contrail-network-route-table-references")
+ private List<RouteTableReference> contrailNetworkRouteTableReferences = new ArrayList<>();
+ @JsonProperty("widget-model-id")
private String widgetModelId;
- @JsonProperty("widget-model-version")
+ @JsonProperty("widget-model-version")
private String widgetModelVersion;
- @JsonProperty("physical-network-name")
+ @JsonProperty("physical-network-name")
private String physicalNetworkName;
- @JsonProperty("is-provider-network")
+ @JsonProperty("is-provider-network")
private Boolean isProviderNetwork;
- @JsonProperty("is-shared-network")
+ @JsonProperty("is-shared-network")
private Boolean isSharedNetwork;
- @JsonProperty("is-external-network")
+ @JsonProperty("is-external-network")
private Boolean isExternalNetwork;
- @JsonProperty("self-link")
+ @JsonProperty("self-link")
private String selflink;
- @JsonProperty("operational-status")
+ @JsonProperty("operational-status")
private String operationalStatus;
- @JsonProperty("subnets")
+ @JsonProperty("subnets")
private List<Subnet> subnets = new ArrayList<>();
- @JsonProperty("ctag-assignments")
+ @JsonProperty("ctag-assignments")
private List<CtagAssignment> ctagAssignments = new ArrayList<>();
- @JsonProperty("segmentation-assignments")
+ @JsonProperty("segmentation-assignments")
private List<SegmentationAssignment> segmentationAssignments = new ArrayList<>();
- @JsonProperty("model-info-network")
- private ModelInfoNetwork modelInfoNetwork;
- @JsonProperty("aggregate-routes")
+ @JsonProperty("model-info-network")
+ private ModelInfoNetwork modelInfoNetwork;
+ @JsonProperty("aggregate-routes")
private List<AggregateRoute> aggregateRoutes = new ArrayList<>();
- @JsonProperty("vpn-binding")
+ @JsonProperty("vpn-binding")
private List<VpnBinding> vpnBindings = new ArrayList<>();
- public ModelInfoNetwork getModelInfoNetwork() {
- return modelInfoNetwork;
- }
- public void setModelInfoNetwork(ModelInfoNetwork modelInfoNetwork) {
- this.modelInfoNetwork = modelInfoNetwork;
- }
- public String getNeutronNetworkId() {
- return neutronNetworkId;
- }
- public void setNeutronNetworkId(String neutronNetworkId) {
- this.neutronNetworkId = neutronNetworkId;
- }
- public String getNetworkId() {
- return networkId;
- }
- public void setNetworkId(String networkId) {
- this.networkId = networkId;
- }
- public String getNetworkName() {
- return networkName;
- }
- public void setNetworkName(String networkName) {
- this.networkName = networkName;
- }
- public String getNetworkType() {
- return networkType;
- }
- public void setNetworkType(String networkType) {
- this.networkType = networkType;
- }
- public String getNetworkTechnology() {
- return networkTechnology;
- }
- public void setNetworkTechnology(String networkTechnology) {
- this.networkTechnology = networkTechnology;
- }
- public String getNetworkRole() {
- return networkRole;
- }
- public void setNetworkRole(String networkRole) {
- this.networkRole = networkRole;
- }
- public Boolean isIsBoundToVpn() {
- return isBoundToVpn;
- }
- public void setIsBoundToVpn(Boolean isBoundToVpn) {
- this.isBoundToVpn = isBoundToVpn;
- }
- public String getServiceId() {
- return serviceId;
- }
- public void setServiceId(String serviceId) {
- this.serviceId = serviceId;
- }
- public Long getNetworkRoleInstance() {
- return networkRoleInstance;
- }
- public void setNetworkRoleInstance(Long networkRoleInstance) {
- this.networkRoleInstance = networkRoleInstance;
- }
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public String getHeatStackId() {
- return heatStackId;
- }
- public void setHeatStackId(String heatStackId) {
- this.heatStackId = heatStackId;
- }
- public String getContrailNetworkFqdn() {
- return contrailNetworkFqdn;
- }
- public void setContrailNetworkFqdn(String contrailNetworkFqdn) {
- this.contrailNetworkFqdn = contrailNetworkFqdn;
- }
- public List<NetworkPolicy> getNetworkPolicies() {
- return networkPolicies;
- }
- public List<RouteTableReference> getContrailNetworkRouteTableReferences() {
- return contrailNetworkRouteTableReferences;
- }
- public String getWidgetModelId() {
- return widgetModelId;
- }
- public void setWidgetModelId(String widgetModelId) {
- this.widgetModelId = widgetModelId;
- }
- public String getWidgetModelVersion() {
- return widgetModelVersion;
- }
- public void setWidgetModelVersion(String widgetModelVersion) {
- this.widgetModelVersion = widgetModelVersion;
- }
- public String getPhysicalNetworkName() {
- return physicalNetworkName;
- }
- public void setPhysicalNetworkName(String physicalNetworkName) {
- this.physicalNetworkName = physicalNetworkName;
- }
- public Boolean isIsProviderNetwork() {
- return isProviderNetwork;
- }
- public void setIsProviderNetwork(Boolean isProviderNetwork) {
- this.isProviderNetwork = isProviderNetwork;
- }
- public Boolean isIsSharedNetwork() {
- return isSharedNetwork;
- }
- public void setIsSharedNetwork(Boolean isSharedNetwork) {
- this.isSharedNetwork = isSharedNetwork;
- }
- public Boolean isIsExternalNetwork() {
- return isExternalNetwork;
- }
- public void setIsExternalNetwork(Boolean isExternalNetwork) {
- this.isExternalNetwork = isExternalNetwork;
- }
- public String getSelflink() {
- return selflink;
- }
- public void setSelflink(String selflink) {
- this.selflink = selflink;
- }
- public String getOperationalStatus() {
- return operationalStatus;
- }
- public void setOperationalStatus(String operationalStatus) {
- this.operationalStatus = operationalStatus;
- }
-
- public List<Subnet> getSubnets() {
- return subnets;
- }
- public List<CtagAssignment> getCtagAssignments() {
- return ctagAssignments;
- }
- public List<SegmentationAssignment> getSegmentationAssignments() {
- return segmentationAssignments;
- }
- public Boolean isCascaded() {
- return cascaded;
- }
- public void setIsCascaded(Boolean cascaded) {
- this.cascaded = cascaded;
- }
- public Map<String, String> getCloudParams() {
- return cloudParams;
- }
- public void setCloudParams(Map<String, String> cloudParams) {
- this.cloudParams = cloudParams;
- }
-
- public List<AggregateRoute> getAggregateRoutes(){
- return aggregateRoutes;
- }
-
- public List<VpnBinding> getVpnBindings(){
- return vpnBindings;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof L3Network)) {
- return false;
- }
- L3Network castOther = (L3Network) other;
- return new EqualsBuilder().append(networkId, castOther.networkId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(networkId).toHashCode();
- }
+ public ModelInfoNetwork getModelInfoNetwork() {
+ return modelInfoNetwork;
+ }
+
+ public void setModelInfoNetwork(ModelInfoNetwork modelInfoNetwork) {
+ this.modelInfoNetwork = modelInfoNetwork;
+ }
+
+ public String getNeutronNetworkId() {
+ return neutronNetworkId;
+ }
+
+ public void setNeutronNetworkId(String neutronNetworkId) {
+ this.neutronNetworkId = neutronNetworkId;
+ }
+
+ public String getNetworkId() {
+ return networkId;
+ }
+
+ public void setNetworkId(String networkId) {
+ this.networkId = networkId;
+ }
+
+ public String getNetworkName() {
+ return networkName;
+ }
+
+ public void setNetworkName(String networkName) {
+ this.networkName = networkName;
+ }
+
+ public String getNetworkType() {
+ return networkType;
+ }
+
+ public void setNetworkType(String networkType) {
+ this.networkType = networkType;
+ }
+
+ public String getNetworkTechnology() {
+ return networkTechnology;
+ }
+
+ public void setNetworkTechnology(String networkTechnology) {
+ this.networkTechnology = networkTechnology;
+ }
+
+ public String getNetworkRole() {
+ return networkRole;
+ }
+
+ public void setNetworkRole(String networkRole) {
+ this.networkRole = networkRole;
+ }
+
+ public Boolean isIsBoundToVpn() {
+ return isBoundToVpn;
+ }
+
+ public void setIsBoundToVpn(Boolean isBoundToVpn) {
+ this.isBoundToVpn = isBoundToVpn;
+ }
+
+ public String getServiceId() {
+ return serviceId;
+ }
+
+ public void setServiceId(String serviceId) {
+ this.serviceId = serviceId;
+ }
+
+ public Long getNetworkRoleInstance() {
+ return networkRoleInstance;
+ }
+
+ public void setNetworkRoleInstance(Long networkRoleInstance) {
+ this.networkRoleInstance = networkRoleInstance;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public String getHeatStackId() {
+ return heatStackId;
+ }
+
+ public void setHeatStackId(String heatStackId) {
+ this.heatStackId = heatStackId;
+ }
+
+ public String getContrailNetworkFqdn() {
+ return contrailNetworkFqdn;
+ }
+
+ public void setContrailNetworkFqdn(String contrailNetworkFqdn) {
+ this.contrailNetworkFqdn = contrailNetworkFqdn;
+ }
+
+ public List<NetworkPolicy> getNetworkPolicies() {
+ return networkPolicies;
+ }
+
+ public List<RouteTableReference> getContrailNetworkRouteTableReferences() {
+ return contrailNetworkRouteTableReferences;
+ }
+
+ public String getWidgetModelId() {
+ return widgetModelId;
+ }
+
+ public void setWidgetModelId(String widgetModelId) {
+ this.widgetModelId = widgetModelId;
+ }
+
+ public String getWidgetModelVersion() {
+ return widgetModelVersion;
+ }
+
+ public void setWidgetModelVersion(String widgetModelVersion) {
+ this.widgetModelVersion = widgetModelVersion;
+ }
+
+ public String getPhysicalNetworkName() {
+ return physicalNetworkName;
+ }
+
+ public void setPhysicalNetworkName(String physicalNetworkName) {
+ this.physicalNetworkName = physicalNetworkName;
+ }
+
+ public Boolean isIsProviderNetwork() {
+ return isProviderNetwork;
+ }
+
+ public void setIsProviderNetwork(Boolean isProviderNetwork) {
+ this.isProviderNetwork = isProviderNetwork;
+ }
+
+ public Boolean isIsSharedNetwork() {
+ return isSharedNetwork;
+ }
+
+ public void setIsSharedNetwork(Boolean isSharedNetwork) {
+ this.isSharedNetwork = isSharedNetwork;
+ }
+
+ public Boolean isIsExternalNetwork() {
+ return isExternalNetwork;
+ }
+
+ public void setIsExternalNetwork(Boolean isExternalNetwork) {
+ this.isExternalNetwork = isExternalNetwork;
+ }
+
+ public String getSelflink() {
+ return selflink;
+ }
+
+ public void setSelflink(String selflink) {
+ this.selflink = selflink;
+ }
+
+ public String getOperationalStatus() {
+ return operationalStatus;
+ }
+
+ public void setOperationalStatus(String operationalStatus) {
+ this.operationalStatus = operationalStatus;
+ }
+
+ public List<Subnet> getSubnets() {
+ return subnets;
+ }
+
+ public List<CtagAssignment> getCtagAssignments() {
+ return ctagAssignments;
+ }
+
+ public List<SegmentationAssignment> getSegmentationAssignments() {
+ return segmentationAssignments;
+ }
+
+ public Boolean isCascaded() {
+ return cascaded;
+ }
+
+ public void setIsCascaded(Boolean cascaded) {
+ this.cascaded = cascaded;
+ }
+
+ public Map<String, String> getCloudParams() {
+ return cloudParams;
+ }
+
+ public void setCloudParams(Map<String, String> cloudParams) {
+ this.cloudParams = cloudParams;
+ }
+
+ public List<AggregateRoute> getAggregateRoutes() {
+ return aggregateRoutes;
+ }
+
+ public List<VpnBinding> getVpnBindings() {
+ return vpnBindings;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof L3Network)) {
+ return false;
+ }
+ L3Network castOther = (L3Network) other;
+ return new EqualsBuilder().append(networkId, castOther.networkId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(networkId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LInterface.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LInterface.java
index f102c15062..387d191409 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LInterface.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LInterface.java
@@ -23,169 +23,201 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("l-interface")
-public class LInterface implements Serializable, ShallowCopy<LInterface>{
+public class LInterface implements Serializable, ShallowCopy<LInterface> {
- private static final long serialVersionUID = 5629921809747079453L;
+ private static final long serialVersionUID = 5629921809747079453L;
- @Id
- @JsonProperty("interface-name")
+ @Id
+ @JsonProperty("interface-name")
private String interfaceName;
- @JsonProperty("interface-role")
+ @JsonProperty("interface-role")
private String interfaceRole;
- @JsonProperty("v6-wan-link-ip")
+ @JsonProperty("v6-wan-link-ip")
private String v6WanLinkIp;
- @JsonProperty("self-link")
+ @JsonProperty("self-link")
private String selflink;
- @JsonProperty("interface-id")
+ @JsonProperty("interface-id")
private String interfaceId;
- @JsonProperty("macaddr")
+ @JsonProperty("macaddr")
private String macaddr;
- @JsonProperty("network-name")
+ @JsonProperty("network-name")
private String networkName;
- @JsonProperty("management-option")
+ @JsonProperty("management-option")
private String managementOption;
- @JsonProperty("interface-description")
+ @JsonProperty("interface-description")
private String interfaceDescription;
- @JsonProperty("is-port-mirrored")
+ @JsonProperty("is-port-mirrored")
private Boolean isPortMirrored;
- @JsonProperty("in-maint")
+ @JsonProperty("in-maint")
private Boolean inMaint;
- @JsonProperty("prov-status")
+ @JsonProperty("prov-status")
private String provStatus;
- @JsonProperty("is-ip-unnumbered")
+ @JsonProperty("is-ip-unnumbered")
private Boolean isIpUnnumbered;
- @JsonProperty("allowed-address-pairs")
+ @JsonProperty("allowed-address-pairs")
private String allowedAddressPairs;
- @JsonProperty("vlans")
+ @JsonProperty("vlans")
private List<Vlan> vlans = new ArrayList<Vlan>();
- @JsonProperty("sriov-vfs")
+ @JsonProperty("sriov-vfs")
private List<SriovVf> sriovVfs = new ArrayList<SriovVf>();
- @JsonProperty("l-interfaces")
+ @JsonProperty("l-interfaces")
private List<LInterface> lInterfaces = new ArrayList<LInterface>();
- @JsonProperty("l3-interface-ipv4-address-list")
+ @JsonProperty("l3-interface-ipv4-address-list")
private List<L3InterfaceIpv4AddressList> l3InterfaceIpv4AddressList = new ArrayList<L3InterfaceIpv4AddressList>();
- @JsonProperty("l3-interface-ipv6-address-list")
+ @JsonProperty("l3-interface-ipv6-address-list")
private List<L3InterfaceIpv6AddressList> l3InterfaceIpv6AddressList = new ArrayList<L3InterfaceIpv6AddressList>();
- public String getInterfaceName() {
- return interfaceName;
- }
- public void setInterfaceName(String interfaceName) {
- this.interfaceName = interfaceName;
- }
- public String getInterfaceRole() {
- return interfaceRole;
- }
- public void setInterfaceRole(String interfaceRole) {
- this.interfaceRole = interfaceRole;
- }
- public String getV6WanLinkIp() {
- return v6WanLinkIp;
- }
- public void setV6WanLinkIp(String v6WanLinkIp) {
- this.v6WanLinkIp = v6WanLinkIp;
- }
- public String getSelflink() {
- return selflink;
- }
- public void setSelflink(String selflink) {
- this.selflink = selflink;
- }
- public String getInterfaceId() {
- return interfaceId;
- }
- public void setInterfaceId(String interfaceId) {
- this.interfaceId = interfaceId;
- }
- public String getMacaddr() {
- return macaddr;
- }
- public void setMacaddr(String macaddr) {
- this.macaddr = macaddr;
- }
- public String getNetworkName() {
- return networkName;
- }
- public void setNetworkName(String networkName) {
- this.networkName = networkName;
- }
- public String getManagementOption() {
- return managementOption;
- }
- public void setManagementOption(String managementOption) {
- this.managementOption = managementOption;
- }
- public String getInterfaceDescription() {
- return interfaceDescription;
- }
- public void setInterfaceDescription(String interfaceDescription) {
- this.interfaceDescription = interfaceDescription;
- }
- public Boolean isIsPortMirrored() {
- return isPortMirrored;
- }
- public void setPortMirrored(Boolean isPortMirrored) {
- this.isPortMirrored = isPortMirrored;
- }
- public Boolean isInMaint() {
- return inMaint;
- }
- public void setInMaint(boolean inMaint) {
- this.inMaint = inMaint;
- }
- public String getProvStatus() {
- return provStatus;
- }
- public void setProvStatus(String provStatus) {
- this.provStatus = provStatus;
- }
- public Boolean isIsIpUnnumbered() {
- return isIpUnnumbered;
- }
- public void setIpUnnumbered(Boolean isIpUnnumbered) {
- this.isIpUnnumbered = isIpUnnumbered;
- }
- public String getAllowedAddressPairs() {
- return allowedAddressPairs;
- }
- public void setAllowedAddressPairs(String allowedAddressPairs) {
- this.allowedAddressPairs = allowedAddressPairs;
- }
- public List<Vlan> getVlans() {
- return vlans;
- }
- public List<SriovVf> getSriovVfs() {
- return sriovVfs;
- }
- public List<LInterface> getlInterfaces() {
- return lInterfaces;
- }
- public List<L3InterfaceIpv4AddressList> getL3InterfaceIpv4AddressList() {
- return l3InterfaceIpv4AddressList;
- }
- public List<L3InterfaceIpv6AddressList> getL3InterfaceIpv6AddressList() {
- return l3InterfaceIpv6AddressList;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof LInterface)) {
- return false;
- }
- LInterface castOther = (LInterface) other;
- return new EqualsBuilder().append(interfaceName, castOther.interfaceName).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(interfaceName).toHashCode();
- }
+ public String getInterfaceName() {
+ return interfaceName;
+ }
+
+ public void setInterfaceName(String interfaceName) {
+ this.interfaceName = interfaceName;
+ }
+
+ public String getInterfaceRole() {
+ return interfaceRole;
+ }
+
+ public void setInterfaceRole(String interfaceRole) {
+ this.interfaceRole = interfaceRole;
+ }
+
+ public String getV6WanLinkIp() {
+ return v6WanLinkIp;
+ }
+
+ public void setV6WanLinkIp(String v6WanLinkIp) {
+ this.v6WanLinkIp = v6WanLinkIp;
+ }
+
+ public String getSelflink() {
+ return selflink;
+ }
+
+ public void setSelflink(String selflink) {
+ this.selflink = selflink;
+ }
+
+ public String getInterfaceId() {
+ return interfaceId;
+ }
+
+ public void setInterfaceId(String interfaceId) {
+ this.interfaceId = interfaceId;
+ }
+
+ public String getMacaddr() {
+ return macaddr;
+ }
+
+ public void setMacaddr(String macaddr) {
+ this.macaddr = macaddr;
+ }
+
+ public String getNetworkName() {
+ return networkName;
+ }
+
+ public void setNetworkName(String networkName) {
+ this.networkName = networkName;
+ }
+
+ public String getManagementOption() {
+ return managementOption;
+ }
+
+ public void setManagementOption(String managementOption) {
+ this.managementOption = managementOption;
+ }
+
+ public String getInterfaceDescription() {
+ return interfaceDescription;
+ }
+
+ public void setInterfaceDescription(String interfaceDescription) {
+ this.interfaceDescription = interfaceDescription;
+ }
+
+ public Boolean isIsPortMirrored() {
+ return isPortMirrored;
+ }
+
+ public void setPortMirrored(Boolean isPortMirrored) {
+ this.isPortMirrored = isPortMirrored;
+ }
+
+ public Boolean isInMaint() {
+ return inMaint;
+ }
+
+ public void setInMaint(boolean inMaint) {
+ this.inMaint = inMaint;
+ }
+
+ public String getProvStatus() {
+ return provStatus;
+ }
+
+ public void setProvStatus(String provStatus) {
+ this.provStatus = provStatus;
+ }
+
+ public Boolean isIsIpUnnumbered() {
+ return isIpUnnumbered;
+ }
+
+ public void setIpUnnumbered(Boolean isIpUnnumbered) {
+ this.isIpUnnumbered = isIpUnnumbered;
+ }
+
+ public String getAllowedAddressPairs() {
+ return allowedAddressPairs;
+ }
+
+ public void setAllowedAddressPairs(String allowedAddressPairs) {
+ this.allowedAddressPairs = allowedAddressPairs;
+ }
+
+ public List<Vlan> getVlans() {
+ return vlans;
+ }
+
+ public List<SriovVf> getSriovVfs() {
+ return sriovVfs;
+ }
+
+ public List<LInterface> getlInterfaces() {
+ return lInterfaces;
+ }
+
+ public List<L3InterfaceIpv4AddressList> getL3InterfaceIpv4AddressList() {
+ return l3InterfaceIpv4AddressList;
+ }
+
+ public List<L3InterfaceIpv6AddressList> getL3InterfaceIpv6AddressList() {
+ return l3InterfaceIpv6AddressList;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof LInterface)) {
+ return false;
+ }
+ LInterface castOther = (LInterface) other;
+ return new EqualsBuilder().append(interfaceName, castOther.interfaceName).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(interfaceName).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LagInterface.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LagInterface.java
index f69f4628fa..8fbee5f399 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LagInterface.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LagInterface.java
@@ -23,101 +23,117 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("lag-interface")
-public class LagInterface implements Serializable, ShallowCopy<LagInterface>{
+public class LagInterface implements Serializable, ShallowCopy<LagInterface> {
- private static final long serialVersionUID = -7493461787172382640L;
+ private static final long serialVersionUID = -7493461787172382640L;
- @Id
- @JsonProperty("interface-name")
+ @Id
+ @JsonProperty("interface-name")
private String interfaceName;
- @JsonProperty("interface-description")
+ @JsonProperty("interface-description")
private String interfaceDescription;
- @JsonProperty("speed-value")
+ @JsonProperty("speed-value")
private String speedValue;
- @JsonProperty("speed-units")
+ @JsonProperty("speed-units")
private String speedUnits;
- @JsonProperty("interface-id")
+ @JsonProperty("interface-id")
private String interfaceId;
- @JsonProperty("interface-role")
+ @JsonProperty("interface-role")
private String interfaceRole;
- @JsonProperty("prov-status")
+ @JsonProperty("prov-status")
private String provStatus;
- @JsonProperty("in-maint")
+ @JsonProperty("in-maint")
private Boolean inMaint;
- @JsonProperty("l-interfaces")
+ @JsonProperty("l-interfaces")
private List<LInterface> lInterfaces = new ArrayList<>();
- public String getInterfaceName() {
- return interfaceName;
- }
- public void setInterfaceName(String interfaceName) {
- this.interfaceName = interfaceName;
- }
- public String getInterfaceDescription() {
- return interfaceDescription;
- }
- public void setInterfaceDescription(String interfaceDescription) {
- this.interfaceDescription = interfaceDescription;
- }
- public String getSpeedValue() {
- return speedValue;
- }
- public void setSpeedValue(String speedValue) {
- this.speedValue = speedValue;
- }
- public String getSpeedUnits() {
- return speedUnits;
- }
- public void setSpeedUnits(String speedUnits) {
- this.speedUnits = speedUnits;
- }
- public String getInterfaceId() {
- return interfaceId;
- }
- public void setInterfaceId(String interfaceId) {
- this.interfaceId = interfaceId;
- }
- public String getInterfaceRole() {
- return interfaceRole;
- }
- public void setInterfaceRole(String interfaceRole) {
- this.interfaceRole = interfaceRole;
- }
- public String getProvStatus() {
- return provStatus;
- }
- public void setProvStatus(String provStatus) {
- this.provStatus = provStatus;
- }
- public Boolean isInMaint() {
- return inMaint;
- }
- public void setInMaint(boolean inMaint) {
- this.inMaint = inMaint;
- }
- public List<LInterface> getlInterfaces() {
- return lInterfaces;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof LagInterface)) {
- return false;
- }
- LagInterface castOther = (LagInterface) other;
- return new EqualsBuilder().append(interfaceName, castOther.interfaceName).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(interfaceName).toHashCode();
- }
+ public String getInterfaceName() {
+ return interfaceName;
+ }
+
+ public void setInterfaceName(String interfaceName) {
+ this.interfaceName = interfaceName;
+ }
+
+ public String getInterfaceDescription() {
+ return interfaceDescription;
+ }
+
+ public void setInterfaceDescription(String interfaceDescription) {
+ this.interfaceDescription = interfaceDescription;
+ }
+
+ public String getSpeedValue() {
+ return speedValue;
+ }
+
+ public void setSpeedValue(String speedValue) {
+ this.speedValue = speedValue;
+ }
+
+ public String getSpeedUnits() {
+ return speedUnits;
+ }
+
+ public void setSpeedUnits(String speedUnits) {
+ this.speedUnits = speedUnits;
+ }
+
+ public String getInterfaceId() {
+ return interfaceId;
+ }
+
+ public void setInterfaceId(String interfaceId) {
+ this.interfaceId = interfaceId;
+ }
+
+ public String getInterfaceRole() {
+ return interfaceRole;
+ }
+
+ public void setInterfaceRole(String interfaceRole) {
+ this.interfaceRole = interfaceRole;
+ }
+
+ public String getProvStatus() {
+ return provStatus;
+ }
+
+ public void setProvStatus(String provStatus) {
+ this.provStatus = provStatus;
+ }
+
+ public Boolean isInMaint() {
+ return inMaint;
+ }
+
+ public void setInMaint(boolean inMaint) {
+ this.inMaint = inMaint;
+ }
+
+ public List<LInterface> getlInterfaces() {
+ return lInterfaces;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof LagInterface)) {
+ return false;
+ }
+ LagInterface castOther = (LagInterface) other;
+ return new EqualsBuilder().append(interfaceName, castOther.interfaceName).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(interfaceName).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LineOfBusiness.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LineOfBusiness.java
index d2651e6055..1105572e3a 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LineOfBusiness.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LineOfBusiness.java
@@ -22,51 +22,48 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("line-of-business")
public class LineOfBusiness implements Serializable, ShallowCopy<LineOfBusiness> {
- private static final long serialVersionUID = -7697815326894443926L;
+ private static final long serialVersionUID = -7697815326894443926L;
+
+ @Id
+ @JsonProperty("line-of-business-name")
+ private String lineOfBusinessName;
- @Id
- @JsonProperty("line-of-business-name")
- private String lineOfBusinessName;
+ public LineOfBusiness() {}
- public LineOfBusiness() {
- }
-
- public LineOfBusiness(String lineOfBusinessName) {
- this.lineOfBusinessName = lineOfBusinessName;
- }
+ public LineOfBusiness(String lineOfBusinessName) {
+ this.lineOfBusinessName = lineOfBusinessName;
+ }
- public String getLineOfBusinessName() {
- return lineOfBusinessName;
- }
+ public String getLineOfBusinessName() {
+ return lineOfBusinessName;
+ }
- public void setLineOfBusinessName(String lineOfBusinessName) {
- this.lineOfBusinessName = lineOfBusinessName;
- }
+ public void setLineOfBusinessName(String lineOfBusinessName) {
+ this.lineOfBusinessName = lineOfBusinessName;
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof LineOfBusiness)) {
- return false;
- }
- LineOfBusiness castOther = (LineOfBusiness) other;
- return new EqualsBuilder().append(lineOfBusinessName, castOther.lineOfBusinessName).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof LineOfBusiness)) {
+ return false;
+ }
+ LineOfBusiness castOther = (LineOfBusiness) other;
+ return new EqualsBuilder().append(lineOfBusinessName, castOther.lineOfBusinessName).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(lineOfBusinessName).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(lineOfBusinessName).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Metadatum.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Metadatum.java
index 2e7d278901..46bc9eef8a 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Metadatum.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Metadatum.java
@@ -21,46 +21,49 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
-public class Metadatum implements Serializable, ShallowCopy<Metadatum>{
-
- private static final long serialVersionUID = -2259570072414712965L;
+public class Metadatum implements Serializable, ShallowCopy<Metadatum> {
+
+ private static final long serialVersionUID = -2259570072414712965L;
+
+ @Id
+ @JsonProperty("metaname")
+ private String metaname;
+ @JsonProperty("metaval")
+ private String metaval;
+
+ public String getMetaname() {
+ return metaname;
+ }
+
+ public void setMetaname(String metaname) {
+ this.metaname = metaname;
+ }
+
+ public String getMetaval() {
+ return metaval;
+ }
+
+ public void setMetaval(String metaval) {
+ this.metaval = metaval;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Metadatum)) {
+ return false;
+ }
+ Metadatum castOther = (Metadatum) other;
+ return new EqualsBuilder().append(metaname, castOther.metaname).isEquals();
+ }
- @Id
- @JsonProperty("metaname")
- private String metaname;
- @JsonProperty("metaval")
- private String metaval;
-
- public String getMetaname() {
- return metaname;
- }
- public void setMetaname(String metaname) {
- this.metaname = metaname;
- }
- public String getMetaval() {
- return metaval;
- }
- public void setMetaval(String metaval) {
- this.metaval = metaval;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Metadatum)) {
- return false;
- }
- Metadatum castOther = (Metadatum) other;
- return new EqualsBuilder().append(metaname, castOther.metaname).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(metaname).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(metaname).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/NetworkPolicy.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/NetworkPolicy.java
index a920a585cb..7b29e58393 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/NetworkPolicy.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/NetworkPolicy.java
@@ -21,71 +21,69 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import javax.persistence.Id;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-public class NetworkPolicy implements Serializable, ShallowCopy<NetworkPolicy>{
+public class NetworkPolicy implements Serializable, ShallowCopy<NetworkPolicy> {
+
+ private static final long serialVersionUID = 8925599588239522447L;
+
+ @Id
+ @JsonProperty("network-policy-id")
+ private String networkPolicyId;
+ @JsonProperty("network-policy-fqdn")
+ private String networkPolicyFqdn;
+ @JsonProperty("heat-stack-id")
+ private String heatStackId;
+ @JsonProperty("resource-version")
+ private String resourceVersion;
+
+ public String getNetworkPolicyId() {
+ return this.networkPolicyId;
+ }
+
+ public void setNetworkPolicyId(String networkPolicyId) {
+ this.networkPolicyId = networkPolicyId;
+ }
+
+ public String getNetworkPolicyFqdn() {
+ return this.networkPolicyFqdn;
+ }
+
+ public void setNetworkPolicyFqdn(String networkPolicyFqdn) {
+ this.networkPolicyFqdn = networkPolicyFqdn;
+ }
+
+ public String getHeatStackId() {
+ return this.heatStackId;
+ }
+
+ public void setHeatStackId(String heatStackId) {
+ this.heatStackId = heatStackId;
+ }
+
+ public String getResourceVersion() {
+ return this.resourceVersion;
+ }
- private static final long serialVersionUID = 8925599588239522447L;
-
- @Id
- @JsonProperty("network-policy-id")
- private String networkPolicyId;
- @JsonProperty("network-policy-fqdn")
- private String networkPolicyFqdn;
- @JsonProperty("heat-stack-id")
- private String heatStackId;
- @JsonProperty("resource-version")
- private String resourceVersion;
-
- public String getNetworkPolicyId() {
- return this.networkPolicyId;
- }
-
- public void setNetworkPolicyId(String networkPolicyId) {
- this.networkPolicyId = networkPolicyId;
- }
-
- public String getNetworkPolicyFqdn() {
- return this.networkPolicyFqdn;
- }
-
- public void setNetworkPolicyFqdn(String networkPolicyFqdn) {
- this.networkPolicyFqdn = networkPolicyFqdn;
- }
-
- public String getHeatStackId() {
- return this.heatStackId;
- }
-
- public void setHeatStackId(String heatStackId) {
- this.heatStackId = heatStackId;
- }
-
- public String getResourceVersion() {
- return this.resourceVersion;
- }
-
- public void setResourceVersion(String resourceVersion) {
- this.resourceVersion = resourceVersion;
- }
+ public void setResourceVersion(String resourceVersion) {
+ this.resourceVersion = resourceVersion;
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof NetworkPolicy)) {
- return false;
- }
- NetworkPolicy castOther = (NetworkPolicy) other;
- return new EqualsBuilder().append(networkPolicyId, castOther.networkPolicyId).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof NetworkPolicy)) {
+ return false;
+ }
+ NetworkPolicy castOther = (NetworkPolicy) other;
+ return new EqualsBuilder().append(networkPolicyId, castOther.networkPolicyId).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(networkPolicyId).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(networkPolicyId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/OwningEntity.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/OwningEntity.java
index e28e41ed46..efba0d4959 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/OwningEntity.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/OwningEntity.java
@@ -21,9 +21,7 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import javax.persistence.Id;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
@@ -33,36 +31,41 @@ import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@JsonRootName("owning-entity")
public class OwningEntity implements Serializable, ShallowCopy<OwningEntity> {
- private static final long serialVersionUID = -6565917570694869603L;
-
- @Id
- @JsonProperty("owning-entity-id")
- private String owningEntityId;
- @JsonProperty("owning-entity-name")
- private String owningEntityName;
+ private static final long serialVersionUID = -6565917570694869603L;
+
+ @Id
+ @JsonProperty("owning-entity-id")
+ private String owningEntityId;
+ @JsonProperty("owning-entity-name")
+ private String owningEntityName;
+
+ public String getOwningEntityId() {
+ return owningEntityId;
+ }
+
+ public void setOwningEntityId(String owningEntityId) {
+ this.owningEntityId = owningEntityId;
+ }
+
+ public String getOwningEntityName() {
+ return owningEntityName;
+ }
+
+ public void setOwningEntityName(String owningEntityName) {
+ this.owningEntityName = owningEntityName;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof OwningEntity)) {
+ return false;
+ }
+ OwningEntity castOther = (OwningEntity) other;
+ return new EqualsBuilder().append(owningEntityId, castOther.owningEntityId).isEquals();
+ }
- public String getOwningEntityId() {
- return owningEntityId;
- }
- public void setOwningEntityId(String owningEntityId) {
- this.owningEntityId = owningEntityId;
- }
- public String getOwningEntityName() {
- return owningEntityName;
- }
- public void setOwningEntityName(String owningEntityName) {
- this.owningEntityName = owningEntityName;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof OwningEntity)) {
- return false;
- }
- OwningEntity castOther = (OwningEntity) other;
- return new EqualsBuilder().append(owningEntityId, castOther.owningEntityId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(owningEntityId).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(owningEntityId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PServer.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PServer.java
index 498d096e65..d0bf1f588b 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PServer.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PServer.java
@@ -24,60 +24,59 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
public class PServer implements Serializable, ShallowCopy<PServer> {
- private static final long serialVersionUID = 1378547515775540874L;
+ private static final long serialVersionUID = 1378547515775540874L;
- @Id
+ @Id
@JsonProperty("pserver-id")
- private String pserverId;
+ private String pserverId;
@JsonProperty("hostname")
- private String hostname;
+ private String hostname;
@JsonProperty("physical-links")
- private List<PhysicalLink> physicalLinks = new ArrayList<PhysicalLink>(); //TODO techincally there is a pInterface between (pserver <--> physical-link) but dont really need that pojo
-
- public String getPserverId(){
- return pserverId;
- }
-
- public void setPserverId(String pserverId){
- this.pserverId = pserverId;
- }
-
- public String getHostname(){
- return hostname;
- }
-
- public void setHostname(String hostname){
- this.hostname = hostname;
- }
-
- public List<PhysicalLink> getPhysicalLinks(){
- return physicalLinks;
- }
-
- @Override
- public boolean equals(final Object other){
- if(!(other instanceof PServer)){
- return false;
- }
- PServer castOther = (PServer) other;
- return new EqualsBuilder().append(pserverId, castOther.pserverId).isEquals();
- }
-
- @Override
- public int hashCode(){
- return new HashCodeBuilder().append(pserverId).toHashCode();
- }
+ private List<PhysicalLink> physicalLinks = new ArrayList<PhysicalLink>(); // TODO techincally there is a pInterface
+ // between (pserver <--> physical-link)
+ // but dont really need that pojo
+
+ public String getPserverId() {
+ return pserverId;
+ }
+
+ public void setPserverId(String pserverId) {
+ this.pserverId = pserverId;
+ }
+
+ public String getHostname() {
+ return hostname;
+ }
+
+ public void setHostname(String hostname) {
+ this.hostname = hostname;
+ }
+
+ public List<PhysicalLink> getPhysicalLinks() {
+ return physicalLinks;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof PServer)) {
+ return false;
+ }
+ PServer castOther = (PServer) other;
+ return new EqualsBuilder().append(pserverId, castOther.pserverId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(pserverId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PhysicalLink.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PhysicalLink.java
index 742a541352..c669ce497a 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PhysicalLink.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PhysicalLink.java
@@ -21,129 +21,126 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("physical-link")
public class PhysicalLink implements Serializable, ShallowCopy<PhysicalLink> {
- private static final long serialVersionUID = -6378347998443741227L;
+ private static final long serialVersionUID = -6378347998443741227L;
- @Id
+ @Id
@JsonProperty("link-name")
- private String linkName;
+ private String linkName;
@JsonProperty("interface-name")
- private String interfaceName;
+ private String interfaceName;
@JsonProperty("service-provider-name")
- private String serviceProviderName;
+ private String serviceProviderName;
@JsonProperty("circuit-id")
- private String circuitId;
+ private String circuitId;
@JsonProperty("management-option")
- private String managementOption;
+ private String managementOption;
@JsonProperty("bandwidth-up")
- private Integer bandwidthUp;
+ private Integer bandwidthUp;
@JsonProperty("bandwidth-down")
- private Integer bandwidthDown;
+ private Integer bandwidthDown;
@JsonProperty("bandwidth-units")
- private String bandwidthUnits;
+ private String bandwidthUnits;
@JsonProperty("wan-port")
- private String wanPort;
+ private String wanPort;
- public String getLinkName(){
- return linkName;
- }
+ public String getLinkName() {
+ return linkName;
+ }
- public void setLinkName(String linkName){
- this.linkName = linkName;
- }
+ public void setLinkName(String linkName) {
+ this.linkName = linkName;
+ }
- public String getInterfaceName(){
- return interfaceName;
- }
+ public String getInterfaceName() {
+ return interfaceName;
+ }
- public void setInterfaceName(String interfaceName){
- this.interfaceName = interfaceName;
- }
+ public void setInterfaceName(String interfaceName) {
+ this.interfaceName = interfaceName;
+ }
- public String getServiceProviderName(){
- return serviceProviderName;
- }
+ public String getServiceProviderName() {
+ return serviceProviderName;
+ }
- public void setServiceProviderName(String serviceProviderName){
- this.serviceProviderName = serviceProviderName;
- }
+ public void setServiceProviderName(String serviceProviderName) {
+ this.serviceProviderName = serviceProviderName;
+ }
- public String getCircuitId(){
- return circuitId;
- }
+ public String getCircuitId() {
+ return circuitId;
+ }
- public void setCircuitId(String circuitId){
- this.circuitId = circuitId;
- }
+ public void setCircuitId(String circuitId) {
+ this.circuitId = circuitId;
+ }
- public String getManagementOption(){
- return managementOption;
- }
+ public String getManagementOption() {
+ return managementOption;
+ }
- public void setManagementOption(String managementOption){
- this.managementOption = managementOption;
- }
+ public void setManagementOption(String managementOption) {
+ this.managementOption = managementOption;
+ }
- public Integer getBandwidthUp(){
- return bandwidthUp;
- }
+ public Integer getBandwidthUp() {
+ return bandwidthUp;
+ }
- public void setBandwidthUp(Integer bandwidthUp){
- this.bandwidthUp = bandwidthUp;
- }
+ public void setBandwidthUp(Integer bandwidthUp) {
+ this.bandwidthUp = bandwidthUp;
+ }
- public Integer getBandwidthDown(){
- return bandwidthDown;
- }
+ public Integer getBandwidthDown() {
+ return bandwidthDown;
+ }
- public void setBandwidthDown(Integer bandwidthDown){
- this.bandwidthDown = bandwidthDown;
- }
+ public void setBandwidthDown(Integer bandwidthDown) {
+ this.bandwidthDown = bandwidthDown;
+ }
- public String getBandwidthUnits(){
- return bandwidthUnits;
- }
+ public String getBandwidthUnits() {
+ return bandwidthUnits;
+ }
- public void setBandwidthUnits(String bandwidthUnits){
- this.bandwidthUnits = bandwidthUnits;
- }
+ public void setBandwidthUnits(String bandwidthUnits) {
+ this.bandwidthUnits = bandwidthUnits;
+ }
- public String getWanPort(){
- return wanPort;
- }
+ public String getWanPort() {
+ return wanPort;
+ }
- public void setWanPort(String wanPort){
- this.wanPort = wanPort;
- }
+ public void setWanPort(String wanPort) {
+ this.wanPort = wanPort;
+ }
- @Override
- public boolean equals(final Object other){
- if(!(other instanceof PhysicalLink)){
- return false;
- }
- PhysicalLink castOther = (PhysicalLink) other;
- return new EqualsBuilder().append(linkName, castOther.linkName).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof PhysicalLink)) {
+ return false;
+ }
+ PhysicalLink castOther = (PhysicalLink) other;
+ return new EqualsBuilder().append(linkName, castOther.linkName).isEquals();
+ }
- @Override
- public int hashCode(){
- return new HashCodeBuilder().append(linkName).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(linkName).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Platform.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Platform.java
index d13707deb4..08cf97bcf9 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Platform.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Platform.java
@@ -21,51 +21,48 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("platform")
public class Platform implements Serializable, ShallowCopy<Platform> {
- private static final long serialVersionUID = -9127507763010448699L;
+ private static final long serialVersionUID = -9127507763010448699L;
+
+ @Id
+ @JsonProperty("platform-name")
+ private String platformName;
- @Id
- @JsonProperty("platform-name")
- private String platformName;
-
- public Platform() {
- }
+ public Platform() {}
- public Platform(String platformName) {
- this.platformName = platformName;
- }
+ public Platform(String platformName) {
+ this.platformName = platformName;
+ }
- public String getPlatformName() {
- return platformName;
- }
+ public String getPlatformName() {
+ return platformName;
+ }
- public void setPlatformName(String platformName) {
- this.platformName = platformName;
- }
+ public void setPlatformName(String platformName) {
+ this.platformName = platformName;
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Platform)) {
- return false;
- }
- Platform castOther = (Platform) other;
- return new EqualsBuilder().append(platformName, castOther.platformName).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Platform)) {
+ return false;
+ }
+ Platform castOther = (Platform) other;
+ return new EqualsBuilder().append(platformName, castOther.platformName).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(platformName).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(platformName).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Pnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Pnf.java
index 2ec4108343..772c61e48b 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Pnf.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Pnf.java
@@ -21,13 +21,10 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@@ -35,9 +32,9 @@ import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@JsonRootName("pnf")
public class Pnf implements Serializable, ShallowCopy<Pnf> {
- private static final long serialVersionUID = -2544848120774529501L;
+ private static final long serialVersionUID = -2544848120774529501L;
- @Id
+ @Id
@JsonProperty("pnf-id")
private String pnfId;
@@ -47,70 +44,70 @@ public class Pnf implements Serializable, ShallowCopy<Pnf> {
@JsonProperty("role")
private String role;
- @JsonProperty("orchestration-status")
- private OrchestrationStatus orchestrationStatus;
+ @JsonProperty("orchestration-status")
+ private OrchestrationStatus orchestrationStatus;
@JsonProperty("cloud-region")
private CloudRegion cloudRegion;
- public String getPnfId() {
- return pnfId;
- }
-
- public void setPnfId(String pnfId) {
- this.pnfId = pnfId;
- }
-
- public String getPnfName() {
- return pnfName;
- }
-
- public void setPnfName(String pnfName) {
- this.pnfName = pnfName;
- }
-
- /**
- * Distinguishes Primary or Secondary
- */
- public String getRole() {
- return role;
- }
-
- /**
- * Distinguishes Primary or Secondary
- */
- public void setRole(String role) {
- this.role = role;
- }
-
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
-
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
-
- public CloudRegion getCloudRegion() {
- return cloudRegion;
- }
-
- public void setCloudRegion(CloudRegion cloudRegion) {
- this.cloudRegion = cloudRegion;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Pnf)) {
- return false;
- }
- Pnf castOther = (Pnf) other;
- return new EqualsBuilder().append(pnfId, castOther.pnfId).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(pnfId).toHashCode();
- }
+ public String getPnfId() {
+ return pnfId;
+ }
+
+ public void setPnfId(String pnfId) {
+ this.pnfId = pnfId;
+ }
+
+ public String getPnfName() {
+ return pnfName;
+ }
+
+ public void setPnfName(String pnfName) {
+ this.pnfName = pnfName;
+ }
+
+ /**
+ * Distinguishes Primary or Secondary
+ */
+ public String getRole() {
+ return role;
+ }
+
+ /**
+ * Distinguishes Primary or Secondary
+ */
+ public void setRole(String role) {
+ this.role = role;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public CloudRegion getCloudRegion() {
+ return cloudRegion;
+ }
+
+ public void setCloudRegion(CloudRegion cloudRegion) {
+ this.cloudRegion = cloudRegion;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Pnf)) {
+ return false;
+ }
+ Pnf castOther = (Pnf) other;
+ return new EqualsBuilder().append(pnfId, castOther.pnfId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(pnfId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Project.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Project.java
index a815f6af1a..52636a678f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Project.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Project.java
@@ -21,9 +21,7 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import javax.persistence.Id;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
@@ -33,31 +31,31 @@ import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@JsonRootName("project")
public class Project implements Serializable, ShallowCopy<Project> {
- private static final long serialVersionUID = 2449880559554533585L;
-
- @Id
- @JsonProperty("project-name")
- private String projectName;
-
- public String getProjectName() {
- return projectName;
- }
-
- public void setProjectName(String projectName) {
- this.projectName = projectName;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Project)) {
- return false;
- }
- Project castOther = (Project) other;
- return new EqualsBuilder().append(projectName, castOther.projectName).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(projectName).toHashCode();
- }
+ private static final long serialVersionUID = 2449880559554533585L;
+
+ @Id
+ @JsonProperty("project-name")
+ private String projectName;
+
+ public String getProjectName() {
+ return projectName;
+ }
+
+ public void setProjectName(String projectName) {
+ this.projectName = projectName;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Project)) {
+ return false;
+ }
+ Project castOther = (Project) other;
+ return new EqualsBuilder().append(projectName, castOther.projectName).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(projectName).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/RouteTableReference.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/RouteTableReference.java
index 0d8c3201bc..a2f96e18ad 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/RouteTableReference.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/RouteTableReference.java
@@ -21,9 +21,7 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import javax.persistence.Id;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
@@ -31,44 +29,51 @@ import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
public class RouteTableReference implements Serializable, ShallowCopy<RouteTableReference> {
- private static final long serialVersionUID = -698474994443040491L;
-
- @Id
- @JsonProperty("route-table-reference-id")
- private String routeTableReferenceId;
- @JsonProperty("route-table-reference-fqdn")
- private String routeTableReferenceFqdn;
- @JsonProperty("resource-version")
- private String resourceVersion;
-
- public String getRouteTableReferenceId() {
- return routeTableReferenceId;
- }
- public void setRouteTableReferenceId(String routeTableReferenceId) {
- this.routeTableReferenceId = routeTableReferenceId;
- }
- public String getRouteTableReferenceFqdn() {
- return routeTableReferenceFqdn;
- }
- public void setRouteTableReferenceFqdn(String routeTableReferenceFqdn) {
- this.routeTableReferenceFqdn = routeTableReferenceFqdn;
- }
- public String getResourceVersion() {
- return resourceVersion;
- }
- public void setResourceVersion(String resourceVersion) {
- this.resourceVersion = resourceVersion;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof RouteTableReference)) {
- return false;
- }
- RouteTableReference castOther = (RouteTableReference) other;
- return new EqualsBuilder().append(routeTableReferenceId, castOther.routeTableReferenceId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(routeTableReferenceId).toHashCode();
- }
+ private static final long serialVersionUID = -698474994443040491L;
+
+ @Id
+ @JsonProperty("route-table-reference-id")
+ private String routeTableReferenceId;
+ @JsonProperty("route-table-reference-fqdn")
+ private String routeTableReferenceFqdn;
+ @JsonProperty("resource-version")
+ private String resourceVersion;
+
+ public String getRouteTableReferenceId() {
+ return routeTableReferenceId;
+ }
+
+ public void setRouteTableReferenceId(String routeTableReferenceId) {
+ this.routeTableReferenceId = routeTableReferenceId;
+ }
+
+ public String getRouteTableReferenceFqdn() {
+ return routeTableReferenceFqdn;
+ }
+
+ public void setRouteTableReferenceFqdn(String routeTableReferenceFqdn) {
+ this.routeTableReferenceFqdn = routeTableReferenceFqdn;
+ }
+
+ public String getResourceVersion() {
+ return resourceVersion;
+ }
+
+ public void setResourceVersion(String resourceVersion) {
+ this.resourceVersion = resourceVersion;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof RouteTableReference)) {
+ return false;
+ }
+ RouteTableReference castOther = (RouteTableReference) other;
+ return new EqualsBuilder().append(routeTableReferenceId, castOther.routeTableReferenceId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(routeTableReferenceId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/RouteTarget.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/RouteTarget.java
index fc97306cfe..d58825c77f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/RouteTarget.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/RouteTarget.java
@@ -21,9 +21,7 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import javax.persistence.Id;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
@@ -32,12 +30,12 @@ import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@JsonRootName("route-target")
public class RouteTarget implements Serializable, ShallowCopy<RouteTarget> {
- private static final long serialVersionUID = -4635525992843470461L;
-
- @Id
- @JsonProperty("global-route-target")
+ private static final long serialVersionUID = -4635525992843470461L;
+
+ @Id
+ @JsonProperty("global-route-target")
protected String globalRouteTarget;
- @Id
+ @Id
@JsonProperty("route-target-role")
protected String routeTargetRole;
@JsonProperty("resource-version")
@@ -67,18 +65,18 @@ public class RouteTarget implements Serializable, ShallowCopy<RouteTarget> {
this.resourceVersion = value;
}
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof RouteTarget)) {
- return false;
- }
- RouteTarget castOther = (RouteTarget) other;
- return new EqualsBuilder().append(globalRouteTarget, castOther.globalRouteTarget)
- .append(routeTargetRole, castOther.routeTargetRole).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof RouteTarget)) {
+ return false;
+ }
+ RouteTarget castOther = (RouteTarget) other;
+ return new EqualsBuilder().append(globalRouteTarget, castOther.globalRouteTarget)
+ .append(routeTargetRole, castOther.routeTargetRole).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(globalRouteTarget).append(routeTargetRole).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(globalRouteTarget).append(routeTargetRole).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/SegmentationAssignment.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/SegmentationAssignment.java
index a299f1ef42..c8136b2ac9 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/SegmentationAssignment.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/SegmentationAssignment.java
@@ -21,40 +21,41 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("segmentation-assignment")
-public class SegmentationAssignment implements Serializable, ShallowCopy<SegmentationAssignment>{
+public class SegmentationAssignment implements Serializable, ShallowCopy<SegmentationAssignment> {
- private static final long serialVersionUID = 5751570091375657521L;
+ private static final long serialVersionUID = 5751570091375657521L;
- @Id
- @JsonProperty("segmentation-id")
+ @Id
+ @JsonProperty("segmentation-id")
private String segmentationId;
- public String getSegmentationId() {
- return segmentationId;
- }
- public void setSegmentationId(String segmentationId) {
- this.segmentationId = segmentationId;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof SegmentationAssignment)) {
- return false;
- }
- SegmentationAssignment castOther = (SegmentationAssignment) other;
- return new EqualsBuilder().append(segmentationId, castOther.segmentationId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(segmentationId).toHashCode();
- }
+ public String getSegmentationId() {
+ return segmentationId;
+ }
+
+ public void setSegmentationId(String segmentationId) {
+ this.segmentationId = segmentationId;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof SegmentationAssignment)) {
+ return false;
+ }
+ SegmentationAssignment castOther = (SegmentationAssignment) other;
+ return new EqualsBuilder().append(segmentationId, castOther.segmentationId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(segmentationId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceInstance.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceInstance.java
index e2a8688395..6c3a0c43ed 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceInstance.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceInstance.java
@@ -23,15 +23,12 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.Metadata;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@@ -40,175 +37,191 @@ import org.onap.so.bpmn.servicedecomposition.homingobjects.SolutionInfo;
@JsonRootName("service-instance")
public class ServiceInstance implements Serializable, ShallowCopy<ServiceInstance> {
- private static final long serialVersionUID = -1843348234891739356L;
-
- @Id
- @JsonProperty("service-instance-id")
- private String serviceInstanceId;
- @JsonProperty("service-instance-name")
- private String serviceInstanceName;
- @JsonProperty("orchestration-status")
- private OrchestrationStatus orchestrationStatus;
- @JsonProperty("owning-entity")
- private OwningEntity owningEntity;
- @JsonProperty("project")
- private Project project;
- @JsonProperty("collection")
- private Collection collection;
- @JsonProperty("vnfs")
- private List<GenericVnf> vnfs = new ArrayList<>();
- @JsonProperty("pnfs")
- private List<Pnf> pnfs = new ArrayList<>();
- @JsonProperty("allotted-resources")
- private List<AllottedResource> allottedResources = new ArrayList<>();
- @JsonProperty("networks")
- private List<L3Network> networks = new ArrayList<>();
- @JsonProperty("vpn-bonding-links")
- private List<VpnBondingLink> vpnBondingLinks = new ArrayList<>();
- @JsonProperty("vhn-portal-url")
+ private static final long serialVersionUID = -1843348234891739356L;
+
+ @Id
+ @JsonProperty("service-instance-id")
+ private String serviceInstanceId;
+ @JsonProperty("service-instance-name")
+ private String serviceInstanceName;
+ @JsonProperty("orchestration-status")
+ private OrchestrationStatus orchestrationStatus;
+ @JsonProperty("owning-entity")
+ private OwningEntity owningEntity;
+ @JsonProperty("project")
+ private Project project;
+ @JsonProperty("collection")
+ private Collection collection;
+ @JsonProperty("vnfs")
+ private List<GenericVnf> vnfs = new ArrayList<>();
+ @JsonProperty("pnfs")
+ private List<Pnf> pnfs = new ArrayList<>();
+ @JsonProperty("allotted-resources")
+ private List<AllottedResource> allottedResources = new ArrayList<>();
+ @JsonProperty("networks")
+ private List<L3Network> networks = new ArrayList<>();
+ @JsonProperty("vpn-bonding-links")
+ private List<VpnBondingLink> vpnBondingLinks = new ArrayList<>();
+ @JsonProperty("vhn-portal-url")
private String vhnPortalUrl;
- @JsonProperty("service-instance-location-id")
+ @JsonProperty("service-instance-location-id")
private String serviceInstanceLocationId;
- @JsonProperty("selflink")
+ @JsonProperty("selflink")
private String selflink;
- @JsonProperty("metadata")
+ @JsonProperty("metadata")
private Metadata metadata;
- @JsonProperty("configurations")
- private List<Configuration> configurations = new ArrayList<>();
- @JsonProperty("solution-info")
- private SolutionInfo solutionInfo;
- @JsonProperty("model-info-service-instance")
- private ModelInfoServiceInstance modelInfoServiceInstance;
- @JsonProperty("instance-groups")
- private List<InstanceGroup> instanceGroups = new ArrayList<>();
-
- public List<GenericVnf> getVnfs() {
- return vnfs;
- }
- public List<AllottedResource> getAllottedResources() {
- return allottedResources;
- }
- public List<L3Network> getNetworks() {
- return networks;
- }
- public ModelInfoServiceInstance getModelInfoServiceInstance() {
- return modelInfoServiceInstance;
- }
- public void setModelInfoServiceInstance(ModelInfoServiceInstance modelInfoServiceInstance) {
- this.modelInfoServiceInstance = modelInfoServiceInstance;
- }
- public List<Configuration> getConfigurations() {
- return configurations;
- }
- public void setConfigurations(List<Configuration> configurations) {
- this.configurations = configurations;
- }
- public String getVhnPortalUrl() {
- return vhnPortalUrl;
- }
-
- public void setVhnPortalUrl(String vhnPortalUrl) {
- this.vhnPortalUrl = vhnPortalUrl;
- }
-
- public String getServiceInstanceLocationId() {
- return serviceInstanceLocationId;
- }
-
- public void setServiceInstanceLocationId(String serviceInstanceLocationId) {
- this.serviceInstanceLocationId = serviceInstanceLocationId;
- }
-
- public String getSelflink() {
- return selflink;
- }
-
- public void setSelflink(String selflink) {
- this.selflink = selflink;
- }
-
- public Metadata getMetadata() {
- return metadata;
- }
-
- public void setMetadata(Metadata metadata) {
- this.metadata = metadata;
- }
-
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
-
- public String getServiceInstanceName() {
- return serviceInstanceName;
- }
-
- public void setServiceInstanceName(String serviceInstanceName) {
- this.serviceInstanceName = serviceInstanceName;
- }
-
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
-
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
-
- public OwningEntity getOwningEntity() {
- return owningEntity;
- }
-
- public void setOwningEntity(OwningEntity owningEntity) {
- this.owningEntity = owningEntity;
- }
-
- public Project getProject() {
- return project;
- }
-
- public void setProject(Project project) {
- this.project = project;
- }
-
- public Collection getCollection() {
- return collection;
- }
- public void setCollection(Collection collection) {
- this.collection = collection;
- }
- public List<VpnBondingLink> getVpnBondingLinks() {
- return vpnBondingLinks;
- }
- public List<Pnf> getPnfs() {
- return pnfs;
- }
- public SolutionInfo getSolutionInfo() {
- return solutionInfo;
- }
- public void setSolutionInfo(SolutionInfo solutionInfo) {
- this.solutionInfo = solutionInfo;
- }
- public List<InstanceGroup> getInstanceGroups() {
- return instanceGroups;
- }
- public void setInstanceGroups(List<InstanceGroup> instanceGroups) {
- this.instanceGroups = instanceGroups;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ServiceInstance)) {
- return false;
- }
- ServiceInstance castOther = (ServiceInstance) other;
- return new EqualsBuilder().append(serviceInstanceId, castOther.serviceInstanceId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(serviceInstanceId).toHashCode();
- }
+ @JsonProperty("configurations")
+ private List<Configuration> configurations = new ArrayList<>();
+ @JsonProperty("solution-info")
+ private SolutionInfo solutionInfo;
+ @JsonProperty("model-info-service-instance")
+ private ModelInfoServiceInstance modelInfoServiceInstance;
+ @JsonProperty("instance-groups")
+ private List<InstanceGroup> instanceGroups = new ArrayList<>();
+
+ public List<GenericVnf> getVnfs() {
+ return vnfs;
+ }
+
+ public List<AllottedResource> getAllottedResources() {
+ return allottedResources;
+ }
+
+ public List<L3Network> getNetworks() {
+ return networks;
+ }
+
+ public ModelInfoServiceInstance getModelInfoServiceInstance() {
+ return modelInfoServiceInstance;
+ }
+
+ public void setModelInfoServiceInstance(ModelInfoServiceInstance modelInfoServiceInstance) {
+ this.modelInfoServiceInstance = modelInfoServiceInstance;
+ }
+
+ public List<Configuration> getConfigurations() {
+ return configurations;
+ }
+
+ public void setConfigurations(List<Configuration> configurations) {
+ this.configurations = configurations;
+ }
+
+ public String getVhnPortalUrl() {
+ return vhnPortalUrl;
+ }
+
+ public void setVhnPortalUrl(String vhnPortalUrl) {
+ this.vhnPortalUrl = vhnPortalUrl;
+ }
+
+ public String getServiceInstanceLocationId() {
+ return serviceInstanceLocationId;
+ }
+
+ public void setServiceInstanceLocationId(String serviceInstanceLocationId) {
+ this.serviceInstanceLocationId = serviceInstanceLocationId;
+ }
+
+ public String getSelflink() {
+ return selflink;
+ }
+
+ public void setSelflink(String selflink) {
+ this.selflink = selflink;
+ }
+
+ public Metadata getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(Metadata metadata) {
+ this.metadata = metadata;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getServiceInstanceName() {
+ return serviceInstanceName;
+ }
+
+ public void setServiceInstanceName(String serviceInstanceName) {
+ this.serviceInstanceName = serviceInstanceName;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public OwningEntity getOwningEntity() {
+ return owningEntity;
+ }
+
+ public void setOwningEntity(OwningEntity owningEntity) {
+ this.owningEntity = owningEntity;
+ }
+
+ public Project getProject() {
+ return project;
+ }
+
+ public void setProject(Project project) {
+ this.project = project;
+ }
+
+ public Collection getCollection() {
+ return collection;
+ }
+
+ public void setCollection(Collection collection) {
+ this.collection = collection;
+ }
+
+ public List<VpnBondingLink> getVpnBondingLinks() {
+ return vpnBondingLinks;
+ }
+
+ public List<Pnf> getPnfs() {
+ return pnfs;
+ }
+
+ public SolutionInfo getSolutionInfo() {
+ return solutionInfo;
+ }
+
+ public void setSolutionInfo(SolutionInfo solutionInfo) {
+ this.solutionInfo = solutionInfo;
+ }
+
+ public List<InstanceGroup> getInstanceGroups() {
+ return instanceGroups;
+ }
+
+ public void setInstanceGroups(List<InstanceGroup> instanceGroups) {
+ this.instanceGroups = instanceGroups;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ServiceInstance)) {
+ return false;
+ }
+ ServiceInstance castOther = (ServiceInstance) other;
+ return new EqualsBuilder().append(serviceInstanceId, castOther.serviceInstanceId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(serviceInstanceId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceProxy.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceProxy.java
index fa076770d7..6d6444f69c 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceProxy.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceProxy.java
@@ -22,14 +22,11 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
-
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
import org.onap.so.bpmn.servicedecomposition.homingobjects.SolutionCandidates;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceProxy;
-
import java.io.Serializable;
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
@@ -51,58 +48,56 @@ public class ServiceProxy extends SolutionCandidates implements Serializable, Sh
private ModelInfoServiceProxy modelInfoServiceProxy;
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- /**
- * Way to identify the type of proxy
- * i.e. "infrastructure", "transport", etc.
- */
- public String getType() {
- return type;
- }
-
- /**
- * Way to identify the type of proxy
- * i.e. "infrastructure", "transport", etc.
- */
- public void setType(String type) {
- this.type = type;
- }
-
- public ServiceInstance getServiceInstance() {
- return serviceInstance;
- }
-
- public void setServiceInstance(ServiceInstance serviceInstance) {
- this.serviceInstance = serviceInstance;
- }
-
- public ModelInfoServiceProxy getModelInfoServiceProxy() {
- return modelInfoServiceProxy;
- }
-
- public void setModelInfoServiceProxy(ModelInfoServiceProxy modelInfoServiceProxy) {
- this.modelInfoServiceProxy = modelInfoServiceProxy;
- }
-
- @Override
- public boolean equals(final Object other){
- if(!(other instanceof ServiceProxy)){
- return false;
- }
- ServiceProxy castOther = (ServiceProxy) other;
- return new EqualsBuilder().append(id, castOther.id).isEquals();
- }
-
- @Override
- public int hashCode(){
- return new HashCodeBuilder().append(id).toHashCode();
- }
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ /**
+ * Way to identify the type of proxy i.e. "infrastructure", "transport", etc.
+ */
+ public String getType() {
+ return type;
+ }
+
+ /**
+ * Way to identify the type of proxy i.e. "infrastructure", "transport", etc.
+ */
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public ServiceInstance getServiceInstance() {
+ return serviceInstance;
+ }
+
+ public void setServiceInstance(ServiceInstance serviceInstance) {
+ this.serviceInstance = serviceInstance;
+ }
+
+ public ModelInfoServiceProxy getModelInfoServiceProxy() {
+ return modelInfoServiceProxy;
+ }
+
+ public void setModelInfoServiceProxy(ModelInfoServiceProxy modelInfoServiceProxy) {
+ this.modelInfoServiceProxy = modelInfoServiceProxy;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ServiceProxy)) {
+ return false;
+ }
+ ServiceProxy castOther = (ServiceProxy) other;
+ return new EqualsBuilder().append(id, castOther.id).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(id).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceSubscription.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceSubscription.java
index 56f95516b1..05199b7f37 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceSubscription.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceSubscription.java
@@ -23,54 +23,57 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("service-subscription")
-public class ServiceSubscription implements Serializable, ShallowCopy<ServiceSubscription>{
+public class ServiceSubscription implements Serializable, ShallowCopy<ServiceSubscription> {
+
+ private static final long serialVersionUID = 9064449329296611436L;
+
+ @Id
+ @JsonProperty("service-type")
+ private String serviceType;
+ @JsonProperty("temp-ub-sub-account-id")
+ private String tempUbSubAccountId;
+ @JsonProperty("service-instances")
+ private List<ServiceInstance> serviceInstances = new ArrayList<ServiceInstance>();
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getTempUbSubAccountId() {
+ return tempUbSubAccountId;
+ }
- private static final long serialVersionUID = 9064449329296611436L;
+ public void setTempUbSubAccountId(String tempUbSubAccountId) {
+ this.tempUbSubAccountId = tempUbSubAccountId;
+ }
- @Id
- @JsonProperty("service-type")
- private String serviceType;
- @JsonProperty("temp-ub-sub-account-id")
- private String tempUbSubAccountId;
- @JsonProperty("service-instances")
- private List<ServiceInstance> serviceInstances = new ArrayList<ServiceInstance>();
+ public List<ServiceInstance> getServiceInstances() {
+ return serviceInstances;
+ }
- public String getServiceType() {
- return serviceType;
- }
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
- public String getTempUbSubAccountId() {
- return tempUbSubAccountId;
- }
- public void setTempUbSubAccountId(String tempUbSubAccountId) {
- this.tempUbSubAccountId = tempUbSubAccountId;
- }
- public List<ServiceInstance> getServiceInstances() {
- return serviceInstances;
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ServiceSubscription)) {
+ return false;
+ }
+ ServiceSubscription castOther = (ServiceSubscription) other;
+ return new EqualsBuilder().append(serviceType, castOther.serviceType).isEquals();
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ServiceSubscription)) {
- return false;
- }
- ServiceSubscription castOther = (ServiceSubscription) other;
- return new EqualsBuilder().append(serviceType, castOther.serviceType).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(serviceType).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(serviceType).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/SriovVf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/SriovVf.java
index fcea22819e..71d55311f3 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/SriovVf.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/SriovVf.java
@@ -21,136 +21,161 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("sriov-vf")
-public class SriovVf implements Serializable, ShallowCopy<SriovVf>{
+public class SriovVf implements Serializable, ShallowCopy<SriovVf> {
- private static final long serialVersionUID = -7790331637399859914L;
+ private static final long serialVersionUID = -7790331637399859914L;
- @Id
- @JsonProperty("pci-id")
+ @Id
+ @JsonProperty("pci-id")
private String pciId;
- @JsonProperty("vf-vlan-filter")
+ @JsonProperty("vf-vlan-filter")
private String vfVlanFilter;
- @JsonProperty("vf-mac-filter")
+ @JsonProperty("vf-mac-filter")
private String vfMacFilter;
- @JsonProperty("vf-vlan-strip")
+ @JsonProperty("vf-vlan-strip")
private Boolean vfVlanStrip;
- @JsonProperty("vf-vlan-anti-spoof-check")
+ @JsonProperty("vf-vlan-anti-spoof-check")
private Boolean vfVlanAntiSpoofCheck;
- @JsonProperty("vf-mac-anti-spoof-check")
+ @JsonProperty("vf-mac-anti-spoof-check")
private Boolean vfMacAntiSpoofCheck;
- @JsonProperty("vf-mirrors")
+ @JsonProperty("vf-mirrors")
private String vfMirrors;
- @JsonProperty("vf-broadcast-allow")
+ @JsonProperty("vf-broadcast-allow")
private Boolean vfBroadcastAllow;
- @JsonProperty("vf-unknown-multicast-allow")
+ @JsonProperty("vf-unknown-multicast-allow")
private Boolean vfUnknownMulticastAllow;
- @JsonProperty("vf-unknown-unicast-allow")
+ @JsonProperty("vf-unknown-unicast-allow")
private Boolean vfUnknownUnicastAllow;
- @JsonProperty("vf-insert-stag")
+ @JsonProperty("vf-insert-stag")
private Boolean vfInsertStag;
- @JsonProperty("vf-link-status")
+ @JsonProperty("vf-link-status")
private String vfLinkStatus;
- @JsonProperty("neutron-network-id")
+ @JsonProperty("neutron-network-id")
private String neutronNetworkId;
- public String getPciId() {
- return pciId;
- }
- public void setPciId(String pciId) {
- this.pciId = pciId;
- }
- public String getVfVlanFilter() {
- return vfVlanFilter;
- }
- public void setVfVlanFilter(String vfVlanFilter) {
- this.vfVlanFilter = vfVlanFilter;
- }
- public String getVfMacFilter() {
- return vfMacFilter;
- }
- public void setVfMacFilter(String vfMacFilter) {
- this.vfMacFilter = vfMacFilter;
- }
- public Boolean getVfVlanStrip() {
- return vfVlanStrip;
- }
- public void setVfVlanStrip(Boolean vfVlanStrip) {
- this.vfVlanStrip = vfVlanStrip;
- }
- public Boolean getVfVlanAntiSpoofCheck() {
- return vfVlanAntiSpoofCheck;
- }
- public void setVfVlanAntiSpoofCheck(Boolean vfVlanAntiSpoofCheck) {
- this.vfVlanAntiSpoofCheck = vfVlanAntiSpoofCheck;
- }
- public Boolean getVfMacAntiSpoofCheck() {
- return vfMacAntiSpoofCheck;
- }
- public void setVfMacAntiSpoofCheck(Boolean vfMacAntiSpoofCheck) {
- this.vfMacAntiSpoofCheck = vfMacAntiSpoofCheck;
- }
- public String getVfMirrors() {
- return vfMirrors;
- }
- public void setVfMirrors(String vfMirrors) {
- this.vfMirrors = vfMirrors;
- }
- public Boolean getVfBroadcastAllow() {
- return vfBroadcastAllow;
- }
- public void setVfBroadcastAllow(Boolean vfBroadcastAllow) {
- this.vfBroadcastAllow = vfBroadcastAllow;
- }
- public Boolean getVfUnknownMulticastAllow() {
- return vfUnknownMulticastAllow;
- }
- public void setVfUnknownMulticastAllow(Boolean vfUnknownMulticastAllow) {
- this.vfUnknownMulticastAllow = vfUnknownMulticastAllow;
- }
- public Boolean getVfUnknownUnicastAllow() {
- return vfUnknownUnicastAllow;
- }
- public void setVfUnknownUnicastAllow(Boolean vfUnknownUnicastAllow) {
- this.vfUnknownUnicastAllow = vfUnknownUnicastAllow;
- }
- public Boolean getVfInsertStag() {
- return vfInsertStag;
- }
- public void setVfInsertStag(Boolean vfInsertStag) {
- this.vfInsertStag = vfInsertStag;
- }
- public String getVfLinkStatus() {
- return vfLinkStatus;
- }
- public void setVfLinkStatus(String vfLinkStatus) {
- this.vfLinkStatus = vfLinkStatus;
- }
- public String getNeutronNetworkId() {
- return neutronNetworkId;
- }
- public void setNeutronNetworkId(String neutronNetworkId) {
- this.neutronNetworkId = neutronNetworkId;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof SriovVf)) {
- return false;
- }
- SriovVf castOther = (SriovVf) other;
- return new EqualsBuilder().append(pciId, castOther.pciId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(pciId).toHashCode();
- }
+ public String getPciId() {
+ return pciId;
+ }
+
+ public void setPciId(String pciId) {
+ this.pciId = pciId;
+ }
+
+ public String getVfVlanFilter() {
+ return vfVlanFilter;
+ }
+
+ public void setVfVlanFilter(String vfVlanFilter) {
+ this.vfVlanFilter = vfVlanFilter;
+ }
+
+ public String getVfMacFilter() {
+ return vfMacFilter;
+ }
+
+ public void setVfMacFilter(String vfMacFilter) {
+ this.vfMacFilter = vfMacFilter;
+ }
+
+ public Boolean getVfVlanStrip() {
+ return vfVlanStrip;
+ }
+
+ public void setVfVlanStrip(Boolean vfVlanStrip) {
+ this.vfVlanStrip = vfVlanStrip;
+ }
+
+ public Boolean getVfVlanAntiSpoofCheck() {
+ return vfVlanAntiSpoofCheck;
+ }
+
+ public void setVfVlanAntiSpoofCheck(Boolean vfVlanAntiSpoofCheck) {
+ this.vfVlanAntiSpoofCheck = vfVlanAntiSpoofCheck;
+ }
+
+ public Boolean getVfMacAntiSpoofCheck() {
+ return vfMacAntiSpoofCheck;
+ }
+
+ public void setVfMacAntiSpoofCheck(Boolean vfMacAntiSpoofCheck) {
+ this.vfMacAntiSpoofCheck = vfMacAntiSpoofCheck;
+ }
+
+ public String getVfMirrors() {
+ return vfMirrors;
+ }
+
+ public void setVfMirrors(String vfMirrors) {
+ this.vfMirrors = vfMirrors;
+ }
+
+ public Boolean getVfBroadcastAllow() {
+ return vfBroadcastAllow;
+ }
+
+ public void setVfBroadcastAllow(Boolean vfBroadcastAllow) {
+ this.vfBroadcastAllow = vfBroadcastAllow;
+ }
+
+ public Boolean getVfUnknownMulticastAllow() {
+ return vfUnknownMulticastAllow;
+ }
+
+ public void setVfUnknownMulticastAllow(Boolean vfUnknownMulticastAllow) {
+ this.vfUnknownMulticastAllow = vfUnknownMulticastAllow;
+ }
+
+ public Boolean getVfUnknownUnicastAllow() {
+ return vfUnknownUnicastAllow;
+ }
+
+ public void setVfUnknownUnicastAllow(Boolean vfUnknownUnicastAllow) {
+ this.vfUnknownUnicastAllow = vfUnknownUnicastAllow;
+ }
+
+ public Boolean getVfInsertStag() {
+ return vfInsertStag;
+ }
+
+ public void setVfInsertStag(Boolean vfInsertStag) {
+ this.vfInsertStag = vfInsertStag;
+ }
+
+ public String getVfLinkStatus() {
+ return vfLinkStatus;
+ }
+
+ public void setVfLinkStatus(String vfLinkStatus) {
+ this.vfLinkStatus = vfLinkStatus;
+ }
+
+ public String getNeutronNetworkId() {
+ return neutronNetworkId;
+ }
+
+ public void setNeutronNetworkId(String neutronNetworkId) {
+ this.neutronNetworkId = neutronNetworkId;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof SriovVf)) {
+ return false;
+ }
+ SriovVf castOther = (SriovVf) other;
+ return new EqualsBuilder().append(pciId, castOther.pciId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(pciId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Subnet.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Subnet.java
index 7277438102..8b01246067 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Subnet.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Subnet.java
@@ -23,151 +23,178 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("subnet")
-public class Subnet implements Serializable, ShallowCopy<Subnet>{
+public class Subnet implements Serializable, ShallowCopy<Subnet> {
- private static final long serialVersionUID = -6789344717555598319L;
+ private static final long serialVersionUID = -6789344717555598319L;
- @Id
- @JsonProperty("subnet-id")
+ @Id
+ @JsonProperty("subnet-id")
private String subnetId;
- @JsonProperty("subnet-name")
+ @JsonProperty("subnet-name")
private String subnetName;
- @JsonProperty("neutron-subnet-id")
+ @JsonProperty("neutron-subnet-id")
private String neutronSubnetId;
- @JsonProperty("gateway-address")
+ @JsonProperty("gateway-address")
private String gatewayAddress;
- @JsonProperty("network-start-address")
+ @JsonProperty("network-start-address")
private String networkStartAddress;
- @JsonProperty("cidr-mask")
+ @JsonProperty("cidr-mask")
private String cidrMask;
- @JsonProperty("ip-version")
+ @JsonProperty("ip-version")
private String ipVersion;
- @JsonProperty("orchestration-status")
+ @JsonProperty("orchestration-status")
private OrchestrationStatus orchestrationStatus;
- @JsonProperty("dhcp-enabled")
+ @JsonProperty("dhcp-enabled")
private Boolean dhcpEnabled;
- @JsonProperty("dhcp-start")
+ @JsonProperty("dhcp-start")
private String dhcpStart;
- @JsonProperty("dhcp-end")
+ @JsonProperty("dhcp-end")
private String dhcpEnd;
- @JsonProperty("subnet-role")
+ @JsonProperty("subnet-role")
private String subnetRole;
- @JsonProperty("ip-assignment-direction")
+ @JsonProperty("ip-assignment-direction")
private String ipAssignmentDirection;
- @JsonProperty("subnet-sequence")
+ @JsonProperty("subnet-sequence")
private Integer subnetSequence;
- @JsonProperty("host-routes")
+ @JsonProperty("host-routes")
private List<HostRoute> hostRoutes = new ArrayList<>();
- public String getSubnetId() {
- return subnetId;
- }
- public void setSubnetId(String subnetId) {
- this.subnetId = subnetId;
- }
- public String getSubnetName() {
- return subnetName;
- }
- public void setSubnetName(String subnetName) {
- this.subnetName = subnetName;
- }
- public String getNeutronSubnetId() {
- return neutronSubnetId;
- }
- public void setNeutronSubnetId(String neutronSubnetId) {
- this.neutronSubnetId = neutronSubnetId;
- }
- public String getGatewayAddress() {
- return gatewayAddress;
- }
- public void setGatewayAddress(String gatewayAddress) {
- this.gatewayAddress = gatewayAddress;
- }
- public String getNetworkStartAddress() {
- return networkStartAddress;
- }
- public void setNetworkStartAddress(String networkStartAddress) {
- this.networkStartAddress = networkStartAddress;
- }
- public String getCidrMask() {
- return cidrMask;
- }
- public void setCidrMask(String cidrMask) {
- this.cidrMask = cidrMask;
- }
- public String getIpVersion() {
- return ipVersion;
- }
- public void setIpVersion(String ipVersion) {
- this.ipVersion = ipVersion;
- }
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public Boolean isDhcpEnabled() {
- return dhcpEnabled;
- }
- public void setDhcpEnabled(Boolean dhcpEnabled) {
- this.dhcpEnabled = dhcpEnabled;
- }
- public String getDhcpStart() {
- return dhcpStart;
- }
- public void setDhcpStart(String dhcpStart) {
- this.dhcpStart = dhcpStart;
- }
- public String getDhcpEnd() {
- return dhcpEnd;
- }
- public void setDhcpEnd(String dhcpEnd) {
- this.dhcpEnd = dhcpEnd;
- }
- public String getSubnetRole() {
- return subnetRole;
- }
- public void setSubnetRole(String subnetRole) {
- this.subnetRole = subnetRole;
- }
- public String getIpAssignmentDirection() {
- return ipAssignmentDirection;
- }
- public void setIpAssignmentDirection(String ipAssignmentDirection) {
- this.ipAssignmentDirection = ipAssignmentDirection;
- }
- public Integer getSubnetSequence() {
- return subnetSequence;
- }
- public void setSubnetSequence(Integer subnetSequence) {
- this.subnetSequence = subnetSequence;
- }
- public List<HostRoute> getHostRoutes() {
- return hostRoutes;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Subnet)) {
- return false;
- }
- Subnet castOther = (Subnet) other;
- return new EqualsBuilder().append(subnetId, castOther.subnetId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(subnetId).toHashCode();
- }
+ public String getSubnetId() {
+ return subnetId;
+ }
+
+ public void setSubnetId(String subnetId) {
+ this.subnetId = subnetId;
+ }
+
+ public String getSubnetName() {
+ return subnetName;
+ }
+
+ public void setSubnetName(String subnetName) {
+ this.subnetName = subnetName;
+ }
+
+ public String getNeutronSubnetId() {
+ return neutronSubnetId;
+ }
+
+ public void setNeutronSubnetId(String neutronSubnetId) {
+ this.neutronSubnetId = neutronSubnetId;
+ }
+
+ public String getGatewayAddress() {
+ return gatewayAddress;
+ }
+
+ public void setGatewayAddress(String gatewayAddress) {
+ this.gatewayAddress = gatewayAddress;
+ }
+
+ public String getNetworkStartAddress() {
+ return networkStartAddress;
+ }
+
+ public void setNetworkStartAddress(String networkStartAddress) {
+ this.networkStartAddress = networkStartAddress;
+ }
+
+ public String getCidrMask() {
+ return cidrMask;
+ }
+
+ public void setCidrMask(String cidrMask) {
+ this.cidrMask = cidrMask;
+ }
+
+ public String getIpVersion() {
+ return ipVersion;
+ }
+
+ public void setIpVersion(String ipVersion) {
+ this.ipVersion = ipVersion;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public Boolean isDhcpEnabled() {
+ return dhcpEnabled;
+ }
+
+ public void setDhcpEnabled(Boolean dhcpEnabled) {
+ this.dhcpEnabled = dhcpEnabled;
+ }
+
+ public String getDhcpStart() {
+ return dhcpStart;
+ }
+
+ public void setDhcpStart(String dhcpStart) {
+ this.dhcpStart = dhcpStart;
+ }
+
+ public String getDhcpEnd() {
+ return dhcpEnd;
+ }
+
+ public void setDhcpEnd(String dhcpEnd) {
+ this.dhcpEnd = dhcpEnd;
+ }
+
+ public String getSubnetRole() {
+ return subnetRole;
+ }
+
+ public void setSubnetRole(String subnetRole) {
+ this.subnetRole = subnetRole;
+ }
+
+ public String getIpAssignmentDirection() {
+ return ipAssignmentDirection;
+ }
+
+ public void setIpAssignmentDirection(String ipAssignmentDirection) {
+ this.ipAssignmentDirection = ipAssignmentDirection;
+ }
+
+ public Integer getSubnetSequence() {
+ return subnetSequence;
+ }
+
+ public void setSubnetSequence(Integer subnetSequence) {
+ this.subnetSequence = subnetSequence;
+ }
+
+ public List<HostRoute> getHostRoutes() {
+ return hostRoutes;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Subnet)) {
+ return false;
+ }
+ Subnet castOther = (Subnet) other;
+ return new EqualsBuilder().append(subnetId, castOther.subnetId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(subnetId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Tenant.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Tenant.java
index d3f3dcd359..c5cc1b7dbd 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Tenant.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Tenant.java
@@ -21,58 +21,62 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class Tenant implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -8704478668505531590L;
- @Id
- @JsonProperty("tenant-id")
- private String tenantId;
- @JsonProperty("tenant-name")
- private String tenantName;
- @JsonProperty("tenant-context")
- private String tenantContext;
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Tenant)) {
- return false;
- }
- Tenant castOther = (Tenant) other;
- return new EqualsBuilder().append(tenantId, castOther.tenantId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(tenantId).toHashCode();
- }
- public String getTenantId() {
- return tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getTenantName() {
- return tenantName;
- }
- public void setTenantName(String tenantName) {
- this.tenantName = tenantName;
- }
- public String getTenantContext() {
- return tenantContext;
- }
- public void setTenantContext(String tenantContext) {
- this.tenantContext = tenantContext;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -8704478668505531590L;
+ @Id
+ @JsonProperty("tenant-id")
+ private String tenantId;
+ @JsonProperty("tenant-name")
+ private String tenantName;
+ @JsonProperty("tenant-context")
+ private String tenantContext;
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Tenant)) {
+ return false;
+ }
+ Tenant castOther = (Tenant) other;
+ return new EqualsBuilder().append(tenantId, castOther.tenantId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(tenantId).toHashCode();
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getTenantName() {
+ return tenantName;
+ }
+
+ public void setTenantName(String tenantName) {
+ this.tenantName = tenantName;
+ }
+
+ public String getTenantContext() {
+ return tenantContext;
+ }
+
+ public void setTenantContext(String tenantContext) {
+ this.tenantContext = tenantContext;
+ }
+
-
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VfModule.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VfModule.java
index ceca929806..ec6253be70 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VfModule.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VfModule.java
@@ -25,120 +25,139 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("vf-module")
public class VfModule implements Serializable, ShallowCopy<VfModule> {
-
- private static final long serialVersionUID = 6570087672008609773L;
-
- @Id
- @JsonProperty("vf-module-id")
- private String vfModuleId;
- @JsonProperty("vf-module-name")
- private String vfModuleName;
- @JsonProperty("orchestration-status")
- private OrchestrationStatus orchestrationStatus;
- @JsonProperty("cloud-params")
- private Map<String, String> cloudParams = new HashMap<>();
- @JsonProperty("cascaded")
- private Boolean cascaded;
- @JsonProperty("heat-stack-id")
+
+ private static final long serialVersionUID = 6570087672008609773L;
+
+ @Id
+ @JsonProperty("vf-module-id")
+ private String vfModuleId;
+ @JsonProperty("vf-module-name")
+ private String vfModuleName;
+ @JsonProperty("orchestration-status")
+ private OrchestrationStatus orchestrationStatus;
+ @JsonProperty("cloud-params")
+ private Map<String, String> cloudParams = new HashMap<>();
+ @JsonProperty("cascaded")
+ private Boolean cascaded;
+ @JsonProperty("heat-stack-id")
private String heatStackId;
- @JsonProperty("contrail-service-instance-fqdn")
+ @JsonProperty("contrail-service-instance-fqdn")
private String contrailServiceInstanceFqdn;
- @JsonProperty("module-index")
+ @JsonProperty("module-index")
private Integer moduleIndex;
- @JsonProperty("selflink")
+ @JsonProperty("selflink")
private String selflink;
- @JsonProperty("vnfcs")
- private List<Vnfc> vnfcs = new ArrayList<>();
- @JsonProperty("model-info-vf-module")
- private ModelInfoVfModule modelInfoVfModule;
-
- public ModelInfoVfModule getModelInfoVfModule() {
- return modelInfoVfModule;
- }
- public void setModelInfoVfModule(ModelInfoVfModule modelInfoVfModule) {
- this.modelInfoVfModule = modelInfoVfModule;
- }
- public String getHeatStackId() {
- return heatStackId;
- }
- public void setHeatStackId(String heatStackId) {
- this.heatStackId = heatStackId;
- }
- public String getContrailServiceInstanceFqdn() {
- return contrailServiceInstanceFqdn;
- }
- public void setContrailServiceInstanceFqdn(String contrailServiceInstanceFqdn) {
- this.contrailServiceInstanceFqdn = contrailServiceInstanceFqdn;
- }
- public Integer getModuleIndex() {
- return moduleIndex;
- }
- public void setModuleIndex(Integer moduleIndex) {
- this.moduleIndex = moduleIndex;
- }
- public String getSelflink() {
- return selflink;
- }
- public void setSelflink(String selflink) {
- this.selflink = selflink;
- }
- public String getVfModuleId() {
- return vfModuleId;
- }
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
- public String getVfModuleName() {
- return vfModuleName;
- }
- public void setVfModuleName(String vfModuleName) {
- this.vfModuleName = vfModuleName;
- }
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public Map<String, String> getCloudParams() {
- return cloudParams;
- }
- public void setCloudParams(Map<String, String> cloudParams) {
- this.cloudParams = cloudParams;
- }
- public Boolean isCascaded() {
- return cascaded;
- }
- public void setCascaded(boolean cascaded) {
- this.cascaded = cascaded;
- }
- public List<Vnfc> getVnfcs() {
- return vnfcs;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VfModule)) {
- return false;
- }
- VfModule castOther = (VfModule) other;
- return new EqualsBuilder().append(vfModuleId, castOther.vfModuleId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(vfModuleId).toHashCode();
- }
+ @JsonProperty("vnfcs")
+ private List<Vnfc> vnfcs = new ArrayList<>();
+ @JsonProperty("model-info-vf-module")
+ private ModelInfoVfModule modelInfoVfModule;
+
+ public ModelInfoVfModule getModelInfoVfModule() {
+ return modelInfoVfModule;
+ }
+
+ public void setModelInfoVfModule(ModelInfoVfModule modelInfoVfModule) {
+ this.modelInfoVfModule = modelInfoVfModule;
+ }
+
+ public String getHeatStackId() {
+ return heatStackId;
+ }
+
+ public void setHeatStackId(String heatStackId) {
+ this.heatStackId = heatStackId;
+ }
+
+ public String getContrailServiceInstanceFqdn() {
+ return contrailServiceInstanceFqdn;
+ }
+
+ public void setContrailServiceInstanceFqdn(String contrailServiceInstanceFqdn) {
+ this.contrailServiceInstanceFqdn = contrailServiceInstanceFqdn;
+ }
+
+ public Integer getModuleIndex() {
+ return moduleIndex;
+ }
+
+ public void setModuleIndex(Integer moduleIndex) {
+ this.moduleIndex = moduleIndex;
+ }
+
+ public String getSelflink() {
+ return selflink;
+ }
+
+ public void setSelflink(String selflink) {
+ this.selflink = selflink;
+ }
+
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ public String getVfModuleName() {
+ return vfModuleName;
+ }
+
+ public void setVfModuleName(String vfModuleName) {
+ this.vfModuleName = vfModuleName;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public Map<String, String> getCloudParams() {
+ return cloudParams;
+ }
+
+ public void setCloudParams(Map<String, String> cloudParams) {
+ this.cloudParams = cloudParams;
+ }
+
+ public Boolean isCascaded() {
+ return cascaded;
+ }
+
+ public void setCascaded(boolean cascaded) {
+ this.cascaded = cascaded;
+ }
+
+ public List<Vnfc> getVnfcs() {
+ return vnfcs;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VfModule)) {
+ return false;
+ }
+ VfModule castOther = (VfModule) other;
+ return new EqualsBuilder().append(vfModuleId, castOther.vfModuleId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(vfModuleId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vlan.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vlan.java
index a0788d4b0d..6951a23630 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vlan.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vlan.java
@@ -23,140 +23,164 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
-
import javax.persistence.Id;
@JsonRootName("vlan")
-public class Vlan implements Serializable, ShallowCopy<Vlan>{
+public class Vlan implements Serializable, ShallowCopy<Vlan> {
- private static final long serialVersionUID = 1260512753640402946L;
+ private static final long serialVersionUID = 1260512753640402946L;
- @Id
- @JsonProperty("vlan-interface")
+ @Id
+ @JsonProperty("vlan-interface")
private String vlanInterface;
- @JsonProperty("vlan-id-inner")
+ @JsonProperty("vlan-id-inner")
private Long vlanIdInner;
- @JsonProperty("vlan-id-outer")
+ @JsonProperty("vlan-id-outer")
private Long vlanIdOuter;
- @JsonProperty("speed-value")
+ @JsonProperty("speed-value")
private String speedValue;
- @JsonProperty("speed-units")
+ @JsonProperty("speed-units")
private String speedUnits;
- @JsonProperty("vlan-description")
+ @JsonProperty("vlan-description")
private String vlanDescription;
- @JsonProperty("backdoor-connection")
+ @JsonProperty("backdoor-connection")
private String backdoorConnection;
- @JsonProperty("vpn-key")
+ @JsonProperty("vpn-key")
private String vpnKey;
- @JsonProperty("orchestration-status")
+ @JsonProperty("orchestration-status")
private OrchestrationStatus orchestrationStatus;
- @JsonProperty("in-maint")
+ @JsonProperty("in-maint")
private Boolean inMaint;
- @JsonProperty("prov-status")
+ @JsonProperty("prov-status")
private String provStatus;
- @JsonProperty("is-ip-unnumbered")
+ @JsonProperty("is-ip-unnumbered")
private Boolean isIpUnnumbered;
- @JsonProperty("l3-interface-ipv4-address-list")
+ @JsonProperty("l3-interface-ipv4-address-list")
private List<L3InterfaceIpv4AddressList> l3InterfaceIpv4AddressList = new ArrayList<L3InterfaceIpv4AddressList>();
- @JsonProperty("l3-interface-ipv6-address-list")
+ @JsonProperty("l3-interface-ipv6-address-list")
private List<L3InterfaceIpv6AddressList> l3InterfaceIpv6AddressList = new ArrayList<L3InterfaceIpv6AddressList>();
- public String getVlanInterface() {
- return vlanInterface;
- }
- public void setVlanInterface(String vlanInterface) {
- this.vlanInterface = vlanInterface;
- }
- public Long getVlanIdInner() {
- return vlanIdInner;
- }
- public void setVlanIdInner(Long vlanIdInner) {
- this.vlanIdInner = vlanIdInner;
- }
- public Long getVlanIdOuter() {
- return vlanIdOuter;
- }
- public void setVlanIdOuter(Long vlanIdOuter) {
- this.vlanIdOuter = vlanIdOuter;
- }
- public String getSpeedValue() {
- return speedValue;
- }
- public void setSpeedValue(String speedValue) {
- this.speedValue = speedValue;
- }
- public String getSpeedUnits() {
- return speedUnits;
- }
- public void setSpeedUnits(String speedUnits) {
- this.speedUnits = speedUnits;
- }
- public String getVlanDescription() {
- return vlanDescription;
- }
- public void setVlanDescription(String vlanDescription) {
- this.vlanDescription = vlanDescription;
- }
- public String getBackdoorConnection() {
- return backdoorConnection;
- }
- public void setBackdoorConnection(String backdoorConnection) {
- this.backdoorConnection = backdoorConnection;
- }
- public String getVpnKey() {
- return vpnKey;
- }
- public void setVpnKey(String vpnKey) {
- this.vpnKey = vpnKey;
- }
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public Boolean isInMaint() {
- return inMaint;
- }
- public void setInMaint(boolean inMaint) {
- this.inMaint = inMaint;
- }
- public String getProvStatus() {
- return provStatus;
- }
- public void setProvStatus(String provStatus) {
- this.provStatus = provStatus;
- }
- public Boolean isIsIpUnnumbered() {
- return isIpUnnumbered;
- }
- public void setIpUnnumbered(Boolean isIpUnnumbered) {
- this.isIpUnnumbered = isIpUnnumbered;
- }
- public List<L3InterfaceIpv4AddressList> getL3InterfaceIpv4AddressList() {
- return l3InterfaceIpv4AddressList;
- }
- public List<L3InterfaceIpv6AddressList> getL3InterfaceIpv6AddressList() {
- return l3InterfaceIpv6AddressList;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Vlan)) {
- return false;
- }
- Vlan castOther = (Vlan) other;
- return new EqualsBuilder().append(vlanInterface, castOther.vlanInterface).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(vlanInterface).toHashCode();
- }
+ public String getVlanInterface() {
+ return vlanInterface;
+ }
+
+ public void setVlanInterface(String vlanInterface) {
+ this.vlanInterface = vlanInterface;
+ }
+
+ public Long getVlanIdInner() {
+ return vlanIdInner;
+ }
+
+ public void setVlanIdInner(Long vlanIdInner) {
+ this.vlanIdInner = vlanIdInner;
+ }
+
+ public Long getVlanIdOuter() {
+ return vlanIdOuter;
+ }
+
+ public void setVlanIdOuter(Long vlanIdOuter) {
+ this.vlanIdOuter = vlanIdOuter;
+ }
+
+ public String getSpeedValue() {
+ return speedValue;
+ }
+
+ public void setSpeedValue(String speedValue) {
+ this.speedValue = speedValue;
+ }
+
+ public String getSpeedUnits() {
+ return speedUnits;
+ }
+
+ public void setSpeedUnits(String speedUnits) {
+ this.speedUnits = speedUnits;
+ }
+
+ public String getVlanDescription() {
+ return vlanDescription;
+ }
+
+ public void setVlanDescription(String vlanDescription) {
+ this.vlanDescription = vlanDescription;
+ }
+
+ public String getBackdoorConnection() {
+ return backdoorConnection;
+ }
+
+ public void setBackdoorConnection(String backdoorConnection) {
+ this.backdoorConnection = backdoorConnection;
+ }
+
+ public String getVpnKey() {
+ return vpnKey;
+ }
+
+ public void setVpnKey(String vpnKey) {
+ this.vpnKey = vpnKey;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public Boolean isInMaint() {
+ return inMaint;
+ }
+
+ public void setInMaint(boolean inMaint) {
+ this.inMaint = inMaint;
+ }
+
+ public String getProvStatus() {
+ return provStatus;
+ }
+
+ public void setProvStatus(String provStatus) {
+ this.provStatus = provStatus;
+ }
+
+ public Boolean isIsIpUnnumbered() {
+ return isIpUnnumbered;
+ }
+
+ public void setIpUnnumbered(Boolean isIpUnnumbered) {
+ this.isIpUnnumbered = isIpUnnumbered;
+ }
+
+ public List<L3InterfaceIpv4AddressList> getL3InterfaceIpv4AddressList() {
+ return l3InterfaceIpv4AddressList;
+ }
+
+ public List<L3InterfaceIpv6AddressList> getL3InterfaceIpv6AddressList() {
+ return l3InterfaceIpv6AddressList;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Vlan)) {
+ return false;
+ }
+ Vlan castOther = (Vlan) other;
+ return new EqualsBuilder().append(vlanInterface, castOther.vlanInterface).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(vlanInterface).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vnfc.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vnfc.java
index b432fe10b7..087edff7c0 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vnfc.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vnfc.java
@@ -1,131 +1,153 @@
package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
-
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("vnfc")
public class Vnfc implements Serializable {
-
-
- /**
- *
- */
- private static final long serialVersionUID = -9170269565756850796L;
- @Id
- @JsonProperty("vnfc-name")
- private String vnfcName;
- @JsonProperty("nfc-naming-code")
- private String nfcNamingCode;
- @JsonProperty("nfc-function")
- private String nfcFunction;
- @JsonProperty("prov-status")
- private String provStatus;
- @JsonProperty("orchestration-status")
- private String orchestrationStatus;
- @JsonProperty("ipaddress-v4-oam-vip")
- private String ipaddressV4OamVip;
- @JsonProperty("in-maint")
- private String inMaint;
- @JsonProperty("is-closed-loop-disabled")
- private String isClosedLoopDisabled;
- @JsonProperty("group-notation")
- private String groupNotation;
- @JsonProperty("model-invariant-id")
- private String modelInvariantId;
- @JsonProperty("model-version-id")
- private String modelVersionId;
- @JsonProperty("model-customization-id")
- private String modelCustomizationId;
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Vnfc)) {
- return false;
- }
- Vnfc castOther = (Vnfc) other;
- return new EqualsBuilder().append(vnfcName, castOther.vnfcName).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(vnfcName).toHashCode();
- }
- public String getVnfcName() {
- return vnfcName;
- }
- public void setVnfcName(String vnfcName) {
- this.vnfcName = vnfcName;
- }
- public String getNfcNamingCode() {
- return nfcNamingCode;
- }
- public void setNfcNamingCode(String nfcNamingCode) {
- this.nfcNamingCode = nfcNamingCode;
- }
- public String getNfcFunction() {
- return nfcFunction;
- }
- public void setNfcFunction(String nfcFunction) {
- this.nfcFunction = nfcFunction;
- }
- public String getProvStatus() {
- return provStatus;
- }
- public void setProvStatus(String provStatus) {
- this.provStatus = provStatus;
- }
- public String getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(String orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public String getIpaddressV4OamVip() {
- return ipaddressV4OamVip;
- }
- public void setIpaddressV4OamVip(String ipaddressV4OamVip) {
- this.ipaddressV4OamVip = ipaddressV4OamVip;
- }
- public String getInMaint() {
- return inMaint;
- }
- public void setInMaint(String inMaint) {
- this.inMaint = inMaint;
- }
- public String getIsClosedLoopDisabled() {
- return isClosedLoopDisabled;
- }
- public void setIsClosedLoopDisabled(String isClosedLoopDisabled) {
- this.isClosedLoopDisabled = isClosedLoopDisabled;
- }
- public String getGroupNotation() {
- return groupNotation;
- }
- public void setGroupNotation(String groupNotation) {
- this.groupNotation = groupNotation;
- }
- public String getModelInvariantId() {
- return modelInvariantId;
- }
- public void setModelInvariantId(String modelInvariantId) {
- this.modelInvariantId = modelInvariantId;
- }
- public String getModelVersionId() {
- return modelVersionId;
- }
- public void setModelVersionId(String modelVersionId) {
- this.modelVersionId = modelVersionId;
- }
- public String getModelCustomizationId() {
- return modelCustomizationId;
- }
- public void setModelCustomizationId(String modelCustomizationId) {
- this.modelCustomizationId = modelCustomizationId;
- }
+
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -9170269565756850796L;
+ @Id
+ @JsonProperty("vnfc-name")
+ private String vnfcName;
+ @JsonProperty("nfc-naming-code")
+ private String nfcNamingCode;
+ @JsonProperty("nfc-function")
+ private String nfcFunction;
+ @JsonProperty("prov-status")
+ private String provStatus;
+ @JsonProperty("orchestration-status")
+ private String orchestrationStatus;
+ @JsonProperty("ipaddress-v4-oam-vip")
+ private String ipaddressV4OamVip;
+ @JsonProperty("in-maint")
+ private String inMaint;
+ @JsonProperty("is-closed-loop-disabled")
+ private String isClosedLoopDisabled;
+ @JsonProperty("group-notation")
+ private String groupNotation;
+ @JsonProperty("model-invariant-id")
+ private String modelInvariantId;
+ @JsonProperty("model-version-id")
+ private String modelVersionId;
+ @JsonProperty("model-customization-id")
+ private String modelCustomizationId;
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Vnfc)) {
+ return false;
+ }
+ Vnfc castOther = (Vnfc) other;
+ return new EqualsBuilder().append(vnfcName, castOther.vnfcName).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(vnfcName).toHashCode();
+ }
+
+ public String getVnfcName() {
+ return vnfcName;
+ }
+
+ public void setVnfcName(String vnfcName) {
+ this.vnfcName = vnfcName;
+ }
+
+ public String getNfcNamingCode() {
+ return nfcNamingCode;
+ }
+
+ public void setNfcNamingCode(String nfcNamingCode) {
+ this.nfcNamingCode = nfcNamingCode;
+ }
+
+ public String getNfcFunction() {
+ return nfcFunction;
+ }
+
+ public void setNfcFunction(String nfcFunction) {
+ this.nfcFunction = nfcFunction;
+ }
+
+ public String getProvStatus() {
+ return provStatus;
+ }
+
+ public void setProvStatus(String provStatus) {
+ this.provStatus = provStatus;
+ }
+
+ public String getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(String orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public String getIpaddressV4OamVip() {
+ return ipaddressV4OamVip;
+ }
+
+ public void setIpaddressV4OamVip(String ipaddressV4OamVip) {
+ this.ipaddressV4OamVip = ipaddressV4OamVip;
+ }
+
+ public String getInMaint() {
+ return inMaint;
+ }
+
+ public void setInMaint(String inMaint) {
+ this.inMaint = inMaint;
+ }
+
+ public String getIsClosedLoopDisabled() {
+ return isClosedLoopDisabled;
+ }
+
+ public void setIsClosedLoopDisabled(String isClosedLoopDisabled) {
+ this.isClosedLoopDisabled = isClosedLoopDisabled;
+ }
+
+ public String getGroupNotation() {
+ return groupNotation;
+ }
+
+ public void setGroupNotation(String groupNotation) {
+ this.groupNotation = groupNotation;
+ }
+
+ public String getModelInvariantId() {
+ return modelInvariantId;
+ }
+
+ public void setModelInvariantId(String modelInvariantId) {
+ this.modelInvariantId = modelInvariantId;
+ }
+
+ public String getModelVersionId() {
+ return modelVersionId;
+ }
+
+ public void setModelVersionId(String modelVersionId) {
+ this.modelVersionId = modelVersionId;
+ }
+
+ public String getModelCustomizationId() {
+ return modelCustomizationId;
+ }
+
+ public void setModelCustomizationId(String modelCustomizationId) {
+ this.modelCustomizationId = modelCustomizationId;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VolumeGroup.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VolumeGroup.java
index 99a643a129..82afe5fcfe 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VolumeGroup.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VolumeGroup.java
@@ -23,14 +23,11 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
-
import javax.persistence.Id;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@@ -38,84 +35,101 @@ import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@JsonRootName("volume-group")
public class VolumeGroup implements Serializable, ShallowCopy<VolumeGroup> {
- private static final long serialVersionUID = 870124265764370922L;
-
- @Id
- @JsonProperty("volume-group-id")
- private String volumeGroupId;
- @JsonProperty("volume-group-name")
- private String volumeGroupName;
- @JsonProperty("vnf-type")
- private String vnfType;
- @JsonProperty("orchestration-status")
- private OrchestrationStatus orchestrationStatus;
- @JsonProperty("cloud-params")
- private Map<String, String> cloudParams = new HashMap<>();
- @JsonProperty("cascaded")
- private Boolean cascaded;
- @JsonProperty("heat-stack-id")
- private String heatStackId;
- @JsonProperty("model-info-vf-module")
- private ModelInfoVfModule modelInfoVfModule;
-
- public ModelInfoVfModule getModelInfoVfModule() {
- return modelInfoVfModule;
- }
- public void setModelInfoVfModule(ModelInfoVfModule modelInfoVfModule) {
- this.modelInfoVfModule = modelInfoVfModule;
- }
- public String getHeatStackId() {
- return heatStackId;
- }
- public void setHeatStackId(String heatStackId) {
- this.heatStackId = heatStackId;
- }
- public String getVolumeGroupId() {
- return volumeGroupId;
- }
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
- public String getVolumeGroupName() {
- return volumeGroupName;
- }
- public void setVolumeGroupName(String volumeGroupName) {
- this.volumeGroupName = volumeGroupName;
- }
- public String getVnfType() {
- return vnfType;
- }
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public Map<String, String> getCloudParams() {
- return cloudParams;
- }
- public void setCloudParams(Map<String, String> cloudParams) {
- this.cloudParams = cloudParams;
- }
- public Boolean isCascaded() {
- return cascaded;
- }
- public void setCascaded(boolean cascaded) {
- this.cascaded = cascaded;
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VolumeGroup)) {
- return false;
- }
- VolumeGroup castOther = (VolumeGroup) other;
- return new EqualsBuilder().append(volumeGroupId, castOther.volumeGroupId).isEquals();
- }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(volumeGroupId).toHashCode();
- }
+ private static final long serialVersionUID = 870124265764370922L;
+
+ @Id
+ @JsonProperty("volume-group-id")
+ private String volumeGroupId;
+ @JsonProperty("volume-group-name")
+ private String volumeGroupName;
+ @JsonProperty("vnf-type")
+ private String vnfType;
+ @JsonProperty("orchestration-status")
+ private OrchestrationStatus orchestrationStatus;
+ @JsonProperty("cloud-params")
+ private Map<String, String> cloudParams = new HashMap<>();
+ @JsonProperty("cascaded")
+ private Boolean cascaded;
+ @JsonProperty("heat-stack-id")
+ private String heatStackId;
+ @JsonProperty("model-info-vf-module")
+ private ModelInfoVfModule modelInfoVfModule;
+
+ public ModelInfoVfModule getModelInfoVfModule() {
+ return modelInfoVfModule;
+ }
+
+ public void setModelInfoVfModule(ModelInfoVfModule modelInfoVfModule) {
+ this.modelInfoVfModule = modelInfoVfModule;
+ }
+
+ public String getHeatStackId() {
+ return heatStackId;
+ }
+
+ public void setHeatStackId(String heatStackId) {
+ this.heatStackId = heatStackId;
+ }
+
+ public String getVolumeGroupId() {
+ return volumeGroupId;
+ }
+
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ public String getVolumeGroupName() {
+ return volumeGroupName;
+ }
+
+ public void setVolumeGroupName(String volumeGroupName) {
+ this.volumeGroupName = volumeGroupName;
+ }
+
+ public String getVnfType() {
+ return vnfType;
+ }
+
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public Map<String, String> getCloudParams() {
+ return cloudParams;
+ }
+
+ public void setCloudParams(Map<String, String> cloudParams) {
+ this.cloudParams = cloudParams;
+ }
+
+ public Boolean isCascaded() {
+ return cascaded;
+ }
+
+ public void setCascaded(boolean cascaded) {
+ this.cascaded = cascaded;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VolumeGroup)) {
+ return false;
+ }
+ VolumeGroup castOther = (VolumeGroup) other;
+ return new EqualsBuilder().append(volumeGroupId, castOther.volumeGroupId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(volumeGroupId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBinding.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBinding.java
index 36e1af443c..6ae44dc676 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBinding.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBinding.java
@@ -23,9 +23,7 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import javax.persistence.Id;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.apache.commons.lang3.builder.EqualsBuilder;
@@ -35,10 +33,10 @@ import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@JsonRootName("vpn-binding")
public class VpnBinding implements Serializable, ShallowCopy<VpnBinding> {
- private static final long serialVersionUID = 3283413795353486924L;
+ private static final long serialVersionUID = 3283413795353486924L;
- @Id
- @JsonProperty("vpn-id")
+ @Id
+ @JsonProperty("vpn-id")
private String vpnId;
@JsonProperty("vpn-name")
private String vpnName;
@@ -125,17 +123,17 @@ public class VpnBinding implements Serializable, ShallowCopy<VpnBinding> {
return routeTargets;
}
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VpnBinding)) {
- return false;
- }
- VpnBinding castOther = (VpnBinding) other;
- return new EqualsBuilder().append(vpnId, castOther.vpnId).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VpnBinding)) {
+ return false;
+ }
+ VpnBinding castOther = (VpnBinding) other;
+ return new EqualsBuilder().append(vpnId, castOther.vpnId).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(vpnId).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(vpnId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBondingLink.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBondingLink.java
index dec3d48203..4ee8213e59 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBondingLink.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBondingLink.java
@@ -22,15 +22,11 @@ package org.onap.so.bpmn.servicedecomposition.bbobjects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
-
import javax.persistence.Id;
-
import static org.apache.commons.lang3.StringUtils.*;
-
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@@ -58,109 +54,110 @@ public class VpnBondingLink implements Serializable, ShallowCopy<VpnBondingLink>
this.vpnBondingLinkId = vpnBondingLinkId;
}
- public List<Configuration> getConfigurations() {
- return configurations;
- }
-
- public List<ServiceProxy> getServiceProxies() {
- return serviceProxies;
- }
-
- public ServiceProxy getServiceProxy(String id) {
- ServiceProxy serviceProxy = null;
- for(ServiceProxy s : serviceProxies){
- if(s.getId().equals(id)){
- serviceProxy = s;
- }
- }
- return serviceProxy;
- }
-
- //TODO temp solution until references are updated to use getConfigurationByType
+ public List<Configuration> getConfigurations() {
+ return configurations;
+ }
+
+ public List<ServiceProxy> getServiceProxies() {
+ return serviceProxies;
+ }
+
+ public ServiceProxy getServiceProxy(String id) {
+ ServiceProxy serviceProxy = null;
+ for (ServiceProxy s : serviceProxies) {
+ if (s.getId().equals(id)) {
+ serviceProxy = s;
+ }
+ }
+ return serviceProxy;
+ }
+
+ // TODO temp solution until references are updated to use getConfigurationByType
public Configuration getVnrConfiguration() {
- Configuration configuration = null;
- for(Configuration c:configurations){
- if(containsIgnoreCase(c.getConfigurationType(), "vlan") || containsIgnoreCase(c.getConfigurationType(), "vnr")){
- configuration = c;
- }
- }
+ Configuration configuration = null;
+ for (Configuration c : configurations) {
+ if (containsIgnoreCase(c.getConfigurationType(), "vlan")
+ || containsIgnoreCase(c.getConfigurationType(), "vnr")) {
+ configuration = c;
+ }
+ }
return configuration;
}
- //TODO temp solution until references are updatedd
+ // TODO temp solution until references are updatedd
public void setVnrConfiguration(Configuration vnrConfiguration) {
- if(vnrConfiguration.getConfigurationType() == null){
- vnrConfiguration.setConfigurationType("vlan");
- }
- configurations.add(vnrConfiguration);
+ if (vnrConfiguration.getConfigurationType() == null) {
+ vnrConfiguration.setConfigurationType("vlan");
+ }
+ configurations.add(vnrConfiguration);
}
- //TODO temp solution until references are updated to use getConfigurationByType
+ // TODO temp solution until references are updated to use getConfigurationByType
public Configuration getVrfConfiguration() {
- Configuration configuration = null;
- for(Configuration c:configurations){
- if(containsIgnoreCase(c.getConfigurationType(), "vrf")){
- configuration = c;
- }
- }
- return configuration;
- }
-
- //TODO temp solution until references are updated
+ Configuration configuration = null;
+ for (Configuration c : configurations) {
+ if (containsIgnoreCase(c.getConfigurationType(), "vrf")) {
+ configuration = c;
+ }
+ }
+ return configuration;
+ }
+
+ // TODO temp solution until references are updated
public void setVrfConfiguration(Configuration vrfConfiguration) {
- if(vrfConfiguration.getConfigurationType() == null){
- vrfConfiguration.setConfigurationType("vrf");
- }
- configurations.add(vrfConfiguration);
+ if (vrfConfiguration.getConfigurationType() == null) {
+ vrfConfiguration.setConfigurationType("vrf");
+ }
+ configurations.add(vrfConfiguration);
}
- //TODO temp solution until references are updated to use getServiceProxyByType
+ // TODO temp solution until references are updated to use getServiceProxyByType
public ServiceProxy getInfrastructureServiceProxy() {
- ServiceProxy serviceProxy = null;
- for(ServiceProxy sp:serviceProxies){
- if(sp.getType().equals("infrastructure")){
- serviceProxy = sp;
- }
- }
+ ServiceProxy serviceProxy = null;
+ for (ServiceProxy sp : serviceProxies) {
+ if (sp.getType().equals("infrastructure")) {
+ serviceProxy = sp;
+ }
+ }
return serviceProxy;
}
- //TODO temp solution until references are updated
+ // TODO temp solution until references are updated
public void setInfrastructureServiceProxy(ServiceProxy infrastructureServiceProxy) {
- infrastructureServiceProxy.setType("infrastructure");
- serviceProxies.add(infrastructureServiceProxy);
+ infrastructureServiceProxy.setType("infrastructure");
+ serviceProxies.add(infrastructureServiceProxy);
}
- //TODO temp solution until references are updated to use getServiceProxyByType
+ // TODO temp solution until references are updated to use getServiceProxyByType
public ServiceProxy getTransportServiceProxy() {
- ServiceProxy serviceProxy = null;
- for(ServiceProxy sp:serviceProxies){
- if(sp != null){
- if(sp.getType().equals("transport")){
- serviceProxy = sp;
- }
- }
- }
- return serviceProxy;
+ ServiceProxy serviceProxy = null;
+ for (ServiceProxy sp : serviceProxies) {
+ if (sp != null) {
+ if (sp.getType().equals("transport")) {
+ serviceProxy = sp;
+ }
+ }
+ }
+ return serviceProxy;
}
- //TODO temp solution until references are updated
+ // TODO temp solution until references are updated
public void setTransportServiceProxy(ServiceProxy transportServiceProxy) {
- transportServiceProxy.setType("transport");
- serviceProxies.add(transportServiceProxy);
+ transportServiceProxy.setType("transport");
+ serviceProxies.add(transportServiceProxy);
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VpnBondingLink)) {
+ return false;
+ }
+ VpnBondingLink castOther = (VpnBondingLink) other;
+ return new EqualsBuilder().append(vpnBondingLinkId, castOther.vpnBondingLinkId).isEquals();
}
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VpnBondingLink)) {
- return false;
- }
- VpnBondingLink castOther = (VpnBondingLink) other;
- return new EqualsBuilder().append(vpnBondingLinkId, castOther.vpnBondingLinkId).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(vpnBondingLinkId).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(vpnBondingLinkId).toHashCode();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/BuildingBlock.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/BuildingBlock.java
index 7b11e9f68e..1f689e97e3 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/BuildingBlock.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/BuildingBlock.java
@@ -21,54 +21,62 @@
package org.onap.so.bpmn.servicedecomposition.entities;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("buildingBlock")
-public class BuildingBlock implements Serializable{
-
- private static final long serialVersionUID = -1144315411128866052L;
-
- @JsonProperty("mso-id")
- private String msoId;
- @JsonProperty("bpmn-flow-name")
- private String bpmnFlowName;
- @JsonProperty("key")
- private String key;
- @JsonProperty("is-virtual-link")
- private Boolean isVirtualLink;
- @JsonProperty("virtual-link-key")
- private String virtualLinkKey;
+public class BuildingBlock implements Serializable {
+
+ private static final long serialVersionUID = -1144315411128866052L;
+
+ @JsonProperty("mso-id")
+ private String msoId;
+ @JsonProperty("bpmn-flow-name")
+ private String bpmnFlowName;
+ @JsonProperty("key")
+ private String key;
+ @JsonProperty("is-virtual-link")
+ private Boolean isVirtualLink;
+ @JsonProperty("virtual-link-key")
+ private String virtualLinkKey;
+
+ public String getBpmnFlowName() {
+ return bpmnFlowName;
+ }
+
+ public void setBpmnFlowName(String bpmnFlowName) {
+ this.bpmnFlowName = bpmnFlowName;
+ }
+
+ public String getMsoId() {
+ return msoId;
+ }
+
+ public void setMsoId(String msoId) {
+ this.msoId = msoId;
+ }
+
+ public String getKey() {
+ return key;
+ }
+
+ public void setKey(String key) {
+ this.key = key;
+ }
+
+ public Boolean getIsVirtualLink() {
+ return isVirtualLink;
+ }
+
+ public void setIsVirtualLink(Boolean isVirtualLink) {
+ this.isVirtualLink = isVirtualLink;
+ }
+
+ public String getVirtualLinkKey() {
+ return virtualLinkKey;
+ }
- public String getBpmnFlowName() {
- return bpmnFlowName;
- }
- public void setBpmnFlowName(String bpmnFlowName) {
- this.bpmnFlowName = bpmnFlowName;
- }
- public String getMsoId() {
- return msoId;
- }
- public void setMsoId(String msoId) {
- this.msoId = msoId;
- }
- public String getKey() {
- return key;
- }
- public void setKey(String key) {
- this.key = key;
- }
- public Boolean getIsVirtualLink() {
- return isVirtualLink;
- }
- public void setIsVirtualLink(Boolean isVirtualLink) {
- this.isVirtualLink = isVirtualLink;
- }
- public String getVirtualLinkKey() {
- return virtualLinkKey;
- }
- public void setVirtualLinkKey(String virtualLinkKey) {
- this.virtualLinkKey = virtualLinkKey;
- }
+ public void setVirtualLinkKey(String virtualLinkKey) {
+ this.virtualLinkKey = virtualLinkKey;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ConfigurationResourceKeys.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ConfigurationResourceKeys.java
index 00903ab782..40e0dd9654 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ConfigurationResourceKeys.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ConfigurationResourceKeys.java
@@ -22,41 +22,48 @@ package org.onap.so.bpmn.servicedecomposition.entities;
import java.io.Serializable;
-public class ConfigurationResourceKeys implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private String vfModuleCustomizationUUID;
- private String vnfResourceCustomizationUUID;
- private String cvnfcCustomizationUUID;
- private String vnfcName;
-
- public String getVfModuleCustomizationUUID() {
- return vfModuleCustomizationUUID;
- }
- public void setVfModuleCustomizationUUID(String vfModuleCustomizationUUID) {
- this.vfModuleCustomizationUUID = vfModuleCustomizationUUID;
- }
- public String getVnfResourceCustomizationUUID() {
- return vnfResourceCustomizationUUID;
- }
- public void setVnfResourceCustomizationUUID(String vnfResourceCustomizationUUID) {
- this.vnfResourceCustomizationUUID = vnfResourceCustomizationUUID;
- }
- public String getCvnfcCustomizationUUID() {
- return cvnfcCustomizationUUID;
- }
- public void setCvnfcCustomizationUUID(String cvnfcCustomizationUUID) {
- this.cvnfcCustomizationUUID = cvnfcCustomizationUUID;
- }
- public String getVnfcName() {
- return vnfcName;
- }
- public void setVnfcName(String vnfcName) {
- this.vnfcName = vnfcName;
- }
-
-
+public class ConfigurationResourceKeys implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private String vfModuleCustomizationUUID;
+ private String vnfResourceCustomizationUUID;
+ private String cvnfcCustomizationUUID;
+ private String vnfcName;
+
+ public String getVfModuleCustomizationUUID() {
+ return vfModuleCustomizationUUID;
+ }
+
+ public void setVfModuleCustomizationUUID(String vfModuleCustomizationUUID) {
+ this.vfModuleCustomizationUUID = vfModuleCustomizationUUID;
+ }
+
+ public String getVnfResourceCustomizationUUID() {
+ return vnfResourceCustomizationUUID;
+ }
+
+ public void setVnfResourceCustomizationUUID(String vnfResourceCustomizationUUID) {
+ this.vnfResourceCustomizationUUID = vnfResourceCustomizationUUID;
+ }
+
+ public String getCvnfcCustomizationUUID() {
+ return cvnfcCustomizationUUID;
+ }
+
+ public void setCvnfcCustomizationUUID(String cvnfcCustomizationUUID) {
+ this.cvnfcCustomizationUUID = cvnfcCustomizationUUID;
+ }
+
+ public String getVnfcName() {
+ return vnfcName;
+ }
+
+ public void setVnfcName(String vnfcName) {
+ this.vnfcName = vnfcName;
+ }
+
+
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ExecuteBuildingBlock.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ExecuteBuildingBlock.java
index be73b37f85..af9eb525aa 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ExecuteBuildingBlock.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ExecuteBuildingBlock.java
@@ -21,90 +21,110 @@
package org.onap.so.bpmn.servicedecomposition.entities;
import java.io.Serializable;
-
import org.onap.so.serviceinstancebeans.RequestDetails;
-public class ExecuteBuildingBlock implements Serializable{
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private BuildingBlock buildingBlock;
- private String requestId;
- private String apiVersion;
- private String resourceId;
- private String requestAction;
- private String vnfType;
- private Boolean aLaCarte;
- private Boolean homing;
- private WorkflowResourceIds workflowResourceIds;
- private RequestDetails requestDetails;
- private ConfigurationResourceKeys configurationResourceKeys;
-
- public BuildingBlock getBuildingBlock() {
- return buildingBlock;
- }
- public void setBuildingBlock(BuildingBlock buildingBlock) {
- this.buildingBlock = buildingBlock;
- }
- public String getRequestId() {
- return requestId;
- }
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
- public String getApiVersion() {
- return apiVersion;
- }
- public void setApiVersion(String apiVersion) {
- this.apiVersion = apiVersion;
- }
- public String getResourceId() {
- return resourceId;
- }
- public void setResourceId(String resourceId) {
- this.resourceId = resourceId;
- }
- public String getRequestAction() {
- return requestAction;
- }
- public void setRequestAction(String requestAction) {
- this.requestAction = requestAction;
- }
- public Boolean isaLaCarte() {
- return aLaCarte;
- }
- public void setaLaCarte(Boolean aLaCarte) {
- this.aLaCarte = aLaCarte;
- }
- public String getVnfType() {
- return vnfType;
- }
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
- public Boolean isHoming() {
- return homing;
- }
- public void setHoming(Boolean homing) {
- this.homing = homing;
- }
- public WorkflowResourceIds getWorkflowResourceIds() {
- return workflowResourceIds;
- }
- public void setWorkflowResourceIds(WorkflowResourceIds workflowResourceIds) {
- this.workflowResourceIds = workflowResourceIds;
- }
- public RequestDetails getRequestDetails() {
- return requestDetails;
- }
- public void setRequestDetails(RequestDetails requestDetails) {
- this.requestDetails = requestDetails;
- }
- public ConfigurationResourceKeys getConfigurationResourceKeys() {
- return configurationResourceKeys;
- }
- public void setConfigurationResourceKeys(ConfigurationResourceKeys configurationResourceKeys) {
- this.configurationResourceKeys = configurationResourceKeys;
- }
+public class ExecuteBuildingBlock implements Serializable {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private BuildingBlock buildingBlock;
+ private String requestId;
+ private String apiVersion;
+ private String resourceId;
+ private String requestAction;
+ private String vnfType;
+ private Boolean aLaCarte;
+ private Boolean homing;
+ private WorkflowResourceIds workflowResourceIds;
+ private RequestDetails requestDetails;
+ private ConfigurationResourceKeys configurationResourceKeys;
+
+ public BuildingBlock getBuildingBlock() {
+ return buildingBlock;
+ }
+
+ public void setBuildingBlock(BuildingBlock buildingBlock) {
+ this.buildingBlock = buildingBlock;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getApiVersion() {
+ return apiVersion;
+ }
+
+ public void setApiVersion(String apiVersion) {
+ this.apiVersion = apiVersion;
+ }
+
+ public String getResourceId() {
+ return resourceId;
+ }
+
+ public void setResourceId(String resourceId) {
+ this.resourceId = resourceId;
+ }
+
+ public String getRequestAction() {
+ return requestAction;
+ }
+
+ public void setRequestAction(String requestAction) {
+ this.requestAction = requestAction;
+ }
+
+ public Boolean isaLaCarte() {
+ return aLaCarte;
+ }
+
+ public void setaLaCarte(Boolean aLaCarte) {
+ this.aLaCarte = aLaCarte;
+ }
+
+ public String getVnfType() {
+ return vnfType;
+ }
+
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ public Boolean isHoming() {
+ return homing;
+ }
+
+ public void setHoming(Boolean homing) {
+ this.homing = homing;
+ }
+
+ public WorkflowResourceIds getWorkflowResourceIds() {
+ return workflowResourceIds;
+ }
+
+ public void setWorkflowResourceIds(WorkflowResourceIds workflowResourceIds) {
+ this.workflowResourceIds = workflowResourceIds;
+ }
+
+ public RequestDetails getRequestDetails() {
+ return requestDetails;
+ }
+
+ public void setRequestDetails(RequestDetails requestDetails) {
+ this.requestDetails = requestDetails;
+ }
+
+ public ConfigurationResourceKeys getConfigurationResourceKeys() {
+ return configurationResourceKeys;
+ }
+
+ public void setConfigurationResourceKeys(ConfigurationResourceKeys configurationResourceKeys) {
+ this.configurationResourceKeys = configurationResourceKeys;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/GeneralBuildingBlock.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/GeneralBuildingBlock.java
index 6d3be0f822..870c740c1f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/GeneralBuildingBlock.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/GeneralBuildingBlock.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.servicedecomposition.entities;
import java.io.Serializable;
import java.util.Map;
-
import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer;
import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance;
@@ -31,74 +30,76 @@ import org.onap.so.bpmn.servicedecomposition.generalobjects.OrchestrationContext
import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
public class GeneralBuildingBlock implements Serializable {
- private static final String INVALID_INPUT_MISSING = "Expected building block input of \"%s\" not found in decomposition";
- private static final String INVALID_INPUT_CLASS_CAST = "Expected building block input of \"%s\" was the wrong object type in the decomposition";
+ private static final String INVALID_INPUT_MISSING =
+ "Expected building block input of \"%s\" not found in decomposition";
+ private static final String INVALID_INPUT_CLASS_CAST =
+ "Expected building block input of \"%s\" was the wrong object type in the decomposition";
+
+ private static final long serialVersionUID = -429247436428110843L;
- private static final long serialVersionUID = -429247436428110843L;
+ private RequestContext requestContext;
+ private OrchestrationContext orchContext;
+ private Map<String, String> userInput;
+ private CloudRegion cloudRegion;
+ private Tenant tenant;
- private RequestContext requestContext;
- private OrchestrationContext orchContext;
- private Map<String, String> userInput;
- private CloudRegion cloudRegion;
- private Tenant tenant;
+ private Customer customer;
+ private ServiceInstance serviceInstance;
- private Customer customer;
- private ServiceInstance serviceInstance;
-
- public Tenant getTenant() {
- return tenant;
- }
+ public Tenant getTenant() {
+ return tenant;
+ }
- public void setTenant(Tenant tenant) {
- this.tenant = tenant;
- }
+ public void setTenant(Tenant tenant) {
+ this.tenant = tenant;
+ }
- public CloudRegion getCloudRegion() {
- return cloudRegion;
- }
+ public CloudRegion getCloudRegion() {
+ return cloudRegion;
+ }
- public void setCloudRegion(CloudRegion cloudRegion) {
- this.cloudRegion = cloudRegion;
- }
+ public void setCloudRegion(CloudRegion cloudRegion) {
+ this.cloudRegion = cloudRegion;
+ }
- public RequestContext getRequestContext() {
- return requestContext;
- }
+ public RequestContext getRequestContext() {
+ return requestContext;
+ }
- public void setRequestContext(RequestContext requestContext) {
- this.requestContext = requestContext;
- }
+ public void setRequestContext(RequestContext requestContext) {
+ this.requestContext = requestContext;
+ }
- public OrchestrationContext getOrchContext() {
- return orchContext;
- }
+ public OrchestrationContext getOrchContext() {
+ return orchContext;
+ }
- public void setOrchContext(OrchestrationContext orchContext) {
- this.orchContext = orchContext;
- }
+ public void setOrchContext(OrchestrationContext orchContext) {
+ this.orchContext = orchContext;
+ }
- public Map<String, String> getUserInput() {
- return userInput;
- }
+ public Map<String, String> getUserInput() {
+ return userInput;
+ }
- public void setUserInput(Map<String, String> userInput) {
- this.userInput = userInput;
- }
+ public void setUserInput(Map<String, String> userInput) {
+ this.userInput = userInput;
+ }
- public Customer getCustomer() {
- return customer;
- }
+ public Customer getCustomer() {
+ return customer;
+ }
- public void setCustomer(Customer customer) {
- this.customer = customer;
- }
+ public void setCustomer(Customer customer) {
+ this.customer = customer;
+ }
- public ServiceInstance getServiceInstance() {
- return serviceInstance;
- }
+ public ServiceInstance getServiceInstance() {
+ return serviceInstance;
+ }
- public void setServiceInstance(ServiceInstance serviceInstance) {
- this.serviceInstance = serviceInstance;
- }
+ public void setServiceInstance(ServiceInstance serviceInstance) {
+ this.serviceInstance = serviceInstance;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java
index 9709ccece0..9e95e79b70 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java
@@ -21,15 +21,5 @@
package org.onap.so.bpmn.servicedecomposition.entities;
public enum ResourceKey {
- SERVICE_INSTANCE_ID,
- GENERIC_VNF_ID,
- NETWORK_ID,
- VOLUME_GROUP_ID,
- VF_MODULE_ID,
- ALLOTTED_RESOURCE_ID,
- CONFIGURATION_ID,
- NETWORK_COLLECTION_ID,
- VPN_ID,
- VPN_BONDING_LINK_ID,
- INSTANCE_GROUP_ID;
+ SERVICE_INSTANCE_ID, GENERIC_VNF_ID, NETWORK_ID, VOLUME_GROUP_ID, VF_MODULE_ID, ALLOTTED_RESOURCE_ID, CONFIGURATION_ID, NETWORK_COLLECTION_ID, VPN_ID, VPN_BONDING_LINK_ID, INSTANCE_GROUP_ID;
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/WorkflowResourceIds.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/WorkflowResourceIds.java
index 15dfe85c1a..dc07d13acb 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/WorkflowResourceIds.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/WorkflowResourceIds.java
@@ -25,88 +25,88 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
public class WorkflowResourceIds implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 8591599114353940105L;
- private String serviceInstanceId;
- private String vnfId;
- private String networkId;
- private String volumeGroupId;
- private String vfModuleId;
- private String networkCollectionId;
- private String configurationId;
- private String instanceGroupId;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("serviceInstanceId", serviceInstanceId).append("vnfId", vnfId)
- .append("networkId", networkId).append("volumeGroupId", volumeGroupId).append("vfModuleId", vfModuleId)
- .append("networkCollectionId", networkCollectionId).append("configurationId", configurationId)
- .toString();
- }
-
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
-
- public String getVnfId() {
- return vnfId;
- }
-
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
-
- public String getNetworkId() {
- return networkId;
- }
-
- public void setNetworkId(String networkId) {
- this.networkId = networkId;
- }
-
- public String getVolumeGroupId() {
- return volumeGroupId;
- }
-
- public void setVolumeGroupId(String volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
-
- public String getVfModuleId() {
- return vfModuleId;
- }
-
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
-
- public String getNetworkCollectionId() {
- return networkCollectionId;
- }
-
- public void setNetworkCollectionId(String networkCollectionId) {
- this.networkCollectionId = networkCollectionId;
- }
-
- public String getConfigurationId() {
- return configurationId;
- }
-
- public void setConfigurationId(String configurationId) {
- this.configurationId = configurationId;
- }
-
- public String getInstanceGroupId() {
- return instanceGroupId;
- }
-
- public void setInstanceGroupId(String instanceGroupId) {
- this.instanceGroupId = instanceGroupId;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = 8591599114353940105L;
+ private String serviceInstanceId;
+ private String vnfId;
+ private String networkId;
+ private String volumeGroupId;
+ private String vfModuleId;
+ private String networkCollectionId;
+ private String configurationId;
+ private String instanceGroupId;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("serviceInstanceId", serviceInstanceId).append("vnfId", vnfId)
+ .append("networkId", networkId).append("volumeGroupId", volumeGroupId).append("vfModuleId", vfModuleId)
+ .append("networkCollectionId", networkCollectionId).append("configurationId", configurationId)
+ .toString();
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getNetworkId() {
+ return networkId;
+ }
+
+ public void setNetworkId(String networkId) {
+ this.networkId = networkId;
+ }
+
+ public String getVolumeGroupId() {
+ return volumeGroupId;
+ }
+
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ public String getNetworkCollectionId() {
+ return networkCollectionId;
+ }
+
+ public void setNetworkCollectionId(String networkCollectionId) {
+ this.networkCollectionId = networkCollectionId;
+ }
+
+ public String getConfigurationId() {
+ return configurationId;
+ }
+
+ public void setConfigurationId(String configurationId) {
+ this.configurationId = configurationId;
+ }
+
+ public String getInstanceGroupId() {
+ return instanceGroupId;
+ }
+
+ public void setInstanceGroupId(String instanceGroupId) {
+ this.instanceGroupId = instanceGroupId;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/exceptions/InvalidBuildingBlockInputException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/exceptions/InvalidBuildingBlockInputException.java
index 21828871db..50e43d247c 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/exceptions/InvalidBuildingBlockInputException.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/exceptions/InvalidBuildingBlockInputException.java
@@ -21,8 +21,8 @@
package org.onap.so.bpmn.servicedecomposition.entities.exceptions;
public class InvalidBuildingBlockInputException extends Exception {
- private static final long serialVersionUID = 221404474263656742L;
-
+ private static final long serialVersionUID = 221404474263656742L;
+
public InvalidBuildingBlockInputException() {
super();
}
@@ -39,9 +39,8 @@ public class InvalidBuildingBlockInputException extends Exception {
super(cause);
}
- protected InvalidBuildingBlockInputException(String message, Throwable cause,
- boolean enableSuppression,
- boolean writableStackTrace) {
+ protected InvalidBuildingBlockInputException(String message, Throwable cause, boolean enableSuppression,
+ boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/License.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/License.java
index e1a12bbad9..c9f7e5e948 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/License.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/License.java
@@ -23,7 +23,6 @@ package org.onap.so.bpmn.servicedecomposition.generalobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -32,25 +31,28 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonRootName("license")
public class License implements Serializable {
- private static final long serialVersionUID = 2345786874755685318L;
-
- @JsonProperty("entitlement-pool-uuids")
- private List<String> entitlementPoolUuids = new ArrayList<String>();
- @JsonProperty("license-key-group-uuids")
- private List<String> licenseKeyGroupUuids = new ArrayList<String>();
-
-
- public List<String> getEntitlementPoolUuids() {
- return entitlementPoolUuids;
- }
- public void setEntitlementPoolUuids(List<String> entitlementPoolUuids) {
- this.entitlementPoolUuids = entitlementPoolUuids;
- }
- public List<String> getLicenseKeyGroupUuids() {
- return licenseKeyGroupUuids;
- }
- public void setLicenseKeyGroupUuids(List<String> licenseKeyGroupUuids) {
- this.licenseKeyGroupUuids = licenseKeyGroupUuids;
- }
+ private static final long serialVersionUID = 2345786874755685318L;
+
+ @JsonProperty("entitlement-pool-uuids")
+ private List<String> entitlementPoolUuids = new ArrayList<String>();
+ @JsonProperty("license-key-group-uuids")
+ private List<String> licenseKeyGroupUuids = new ArrayList<String>();
+
+
+ public List<String> getEntitlementPoolUuids() {
+ return entitlementPoolUuids;
+ }
+
+ public void setEntitlementPoolUuids(List<String> entitlementPoolUuids) {
+ this.entitlementPoolUuids = entitlementPoolUuids;
+ }
+
+ public List<String> getLicenseKeyGroupUuids() {
+ return licenseKeyGroupUuids;
+ }
+
+ public void setLicenseKeyGroupUuids(List<String> licenseKeyGroupUuids) {
+ this.licenseKeyGroupUuids = licenseKeyGroupUuids;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/OrchestrationContext.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/OrchestrationContext.java
index 8f1262f70e..a98cdc712d 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/OrchestrationContext.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/OrchestrationContext.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.servicedecomposition.generalobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@@ -29,16 +28,16 @@ import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@JsonRootName("orchestration-context")
public class OrchestrationContext implements Serializable {
- private static final long serialVersionUID = 6843015923244810369L;
-
- @JsonProperty("is-rollback-enabled")
- private Boolean isRollbackEnabled;
+ private static final long serialVersionUID = 6843015923244810369L;
+
+ @JsonProperty("is-rollback-enabled")
+ private Boolean isRollbackEnabled;
- public Boolean getIsRollbackEnabled() {
- return this.isRollbackEnabled;
- }
+ public Boolean getIsRollbackEnabled() {
+ return this.isRollbackEnabled;
+ }
- public void setIsRollbackEnabled(Boolean isRollbackEnabled) {
- this.isRollbackEnabled = isRollbackEnabled;
- }
+ public void setIsRollbackEnabled(Boolean isRollbackEnabled) {
+ this.isRollbackEnabled = isRollbackEnabled;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java
index cd66e512a5..632e61b85c 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java
@@ -25,102 +25,122 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("request-context")
-public class RequestContext implements Serializable{
-
- private static final long serialVersionUID = -6482733428879732822L;
-
- @JsonProperty("product-family-id")
- private String productFamilyId;
- @JsonProperty("source")
- private String source;
- @JsonProperty("requestor-id")
- private String requestorId;
- @JsonProperty("subscription-service-type")
- private String subscriptionServiceType;
- @JsonProperty("user-params")
- private Map<String, Object> userParams = new HashMap<>();
- @JsonProperty("action")
- private String action;
- @JsonProperty("callback-url")
- private String callbackURL;
- @JsonProperty("service-uri")
- private String serviceURI;
- @JsonProperty("mso-request-id")
- private String msoRequestId;
- @JsonProperty("requestParameters")
- private RequestParameters requestParameters;
- @JsonProperty("configurationParameters")
- private List<Map<String, String>> configurationParameters = new ArrayList<>();
-
- public String getServiceURI() {
- return serviceURI;
- }
- public void setServiceURI(String serviceURI) {
- this.serviceURI = serviceURI;
- }
- public String getProductFamilyId() {
- return productFamilyId;
- }
- public void setProductFamilyId(String productFamilyId) {
- this.productFamilyId = productFamilyId;
- }
- public String getSource() {
- return source;
- }
- public void setSource(String source) {
- this.source = source;
- }
- public String getRequestorId() {
- return requestorId;
- }
- public void setRequestorId(String requestorId) {
- this.requestorId = requestorId;
- }
- public String getSubscriptionServiceType() {
- return subscriptionServiceType;
- }
- public void setSubscriptionServiceType(String subscriptionServiceType) {
- this.subscriptionServiceType = subscriptionServiceType;
- }
- public Map<String, Object> getUserParams() {
- return userParams;
- }
- public void setUserParams(Map<String, Object> userParams) {
- this.userParams = userParams;
- }
- public String getAction() {
- return action;
- }
- public void setAction(String action) {
- this.action = action;
- }
- public String getCallbackURL() {
- return callbackURL;
- }
- public void setCallbackURL(String callbackURL) {
- this.callbackURL = callbackURL;
- }
- public String getMsoRequestId() {
- return msoRequestId;
- }
- public void setMsoRequestId(String msoRequestId) {
- this.msoRequestId = msoRequestId;
- }
- public RequestParameters getRequestParameters() {
- return requestParameters;
- }
- public void setRequestParameters(RequestParameters requestParameters) {
- this.requestParameters = requestParameters;
- }
- public List<Map<String, String>> getConfigurationParameters() {
- return configurationParameters;
- }
- public void setConfigurationParameters(List<Map<String, String>> configurationParameters) {
- this.configurationParameters = configurationParameters;
- }
+public class RequestContext implements Serializable {
+
+ private static final long serialVersionUID = -6482733428879732822L;
+
+ @JsonProperty("product-family-id")
+ private String productFamilyId;
+ @JsonProperty("source")
+ private String source;
+ @JsonProperty("requestor-id")
+ private String requestorId;
+ @JsonProperty("subscription-service-type")
+ private String subscriptionServiceType;
+ @JsonProperty("user-params")
+ private Map<String, Object> userParams = new HashMap<>();
+ @JsonProperty("action")
+ private String action;
+ @JsonProperty("callback-url")
+ private String callbackURL;
+ @JsonProperty("service-uri")
+ private String serviceURI;
+ @JsonProperty("mso-request-id")
+ private String msoRequestId;
+ @JsonProperty("requestParameters")
+ private RequestParameters requestParameters;
+ @JsonProperty("configurationParameters")
+ private List<Map<String, String>> configurationParameters = new ArrayList<>();
+
+ public String getServiceURI() {
+ return serviceURI;
+ }
+
+ public void setServiceURI(String serviceURI) {
+ this.serviceURI = serviceURI;
+ }
+
+ public String getProductFamilyId() {
+ return productFamilyId;
+ }
+
+ public void setProductFamilyId(String productFamilyId) {
+ this.productFamilyId = productFamilyId;
+ }
+
+ public String getSource() {
+ return source;
+ }
+
+ public void setSource(String source) {
+ this.source = source;
+ }
+
+ public String getRequestorId() {
+ return requestorId;
+ }
+
+ public void setRequestorId(String requestorId) {
+ this.requestorId = requestorId;
+ }
+
+ public String getSubscriptionServiceType() {
+ return subscriptionServiceType;
+ }
+
+ public void setSubscriptionServiceType(String subscriptionServiceType) {
+ this.subscriptionServiceType = subscriptionServiceType;
+ }
+
+ public Map<String, Object> getUserParams() {
+ return userParams;
+ }
+
+ public void setUserParams(Map<String, Object> userParams) {
+ this.userParams = userParams;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getCallbackURL() {
+ return callbackURL;
+ }
+
+ public void setCallbackURL(String callbackURL) {
+ this.callbackURL = callbackURL;
+ }
+
+ public String getMsoRequestId() {
+ return msoRequestId;
+ }
+
+ public void setMsoRequestId(String msoRequestId) {
+ this.msoRequestId = msoRequestId;
+ }
+
+ public RequestParameters getRequestParameters() {
+ return requestParameters;
+ }
+
+ public void setRequestParameters(RequestParameters requestParameters) {
+ this.requestParameters = requestParameters;
+ }
+
+ public List<Map<String, String>> getConfigurationParameters() {
+ return configurationParameters;
+ }
+
+ public void setConfigurationParameters(List<Map<String, String>> configurationParameters) {
+ this.configurationParameters = configurationParameters;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestParameters.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestParameters.java
index 3761d26d0b..ca3f73a176 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestParameters.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestParameters.java
@@ -26,7 +26,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -40,99 +39,101 @@ import org.slf4j.LoggerFactory;
@JsonInclude(Include.NON_DEFAULT)
public class RequestParameters implements Serializable {
- private static final Logger logger = LoggerFactory.getLogger(RequestParameters.class);
-
- private static final long serialVersionUID = -5979049912538894930L;
- @JsonProperty("subscriptionServiceType")
- private String subscriptionServiceType;
- @JsonProperty("userParams")
- private List<Map<String, Object>> userParams = new ArrayList<>();
- @JsonProperty("aLaCarte")
- private Boolean aLaCarte;
- @JsonProperty("payload")
- private String payload;
- @JsonProperty("usePreload")
- private Boolean usePreload;
-
- public String getSubscriptionServiceType() {
- return subscriptionServiceType;
- }
-
- public void setSubscriptionServiceType(String subscriptionServiceType) {
- this.subscriptionServiceType = subscriptionServiceType;
- }
- @JsonProperty("aLaCarte")
- public Boolean getALaCarte() {
- return aLaCarte;
- }
- @JsonProperty("aLaCarte")
- public void setaLaCarte(Boolean aLaCarte) {
- this.aLaCarte = aLaCarte;
- }
-
- public Boolean isaLaCarte() {
- return aLaCarte;
- }
-
- public String getPayload(){
- return payload;
- }
- public void setPayload(String value){
- this.payload = value;
- }
-
- public List<Map<String, Object>> getUserParams() {
- return userParams;
- }
-
- public void setUserParams(List<Map<String, Object>> userParams) {
- this.userParams = userParams;
- }
-
- public Object getUserParamValue(String name) {
- if (userParams != null) {
- for (Map<String, Object> param : userParams) {
- if (param.get(name) != null) {
- return param.get(name);
- }
- }
- }
- return null;
- }
-
- public Boolean isUsePreload() {
- return usePreload;
- }
-
- @JsonProperty("usePreload")
- public Boolean getUsePreload() {
- return usePreload;
- }
-
- @JsonProperty("usePreload")
- public void setUsePreload(Boolean usePreload) {
- this.usePreload = usePreload;
- }
-
-
- @JsonInclude(Include.NON_NULL)
- public String toJsonString(){
- String json = "";
- ObjectMapper mapper = new ObjectMapper();
- mapper.setSerializationInclusion(Include.NON_NULL);
- ObjectWriter ow = mapper.writer();
- try{
- json = ow.writeValueAsString(this);
- }catch (Exception e){
- logger.error("Unable to convert Sniro Manager Request to string", e);
- }
- return json;
- }
-
- @Override
- public String toString() {
- return "RequestParameters [subscriptionServiceType="
- + subscriptionServiceType + ", userParams=" + userParams
- + ", aLaCarte=" + aLaCarte + "]";
- }
+ private static final Logger logger = LoggerFactory.getLogger(RequestParameters.class);
+
+ private static final long serialVersionUID = -5979049912538894930L;
+ @JsonProperty("subscriptionServiceType")
+ private String subscriptionServiceType;
+ @JsonProperty("userParams")
+ private List<Map<String, Object>> userParams = new ArrayList<>();
+ @JsonProperty("aLaCarte")
+ private Boolean aLaCarte;
+ @JsonProperty("payload")
+ private String payload;
+ @JsonProperty("usePreload")
+ private Boolean usePreload;
+
+ public String getSubscriptionServiceType() {
+ return subscriptionServiceType;
+ }
+
+ public void setSubscriptionServiceType(String subscriptionServiceType) {
+ this.subscriptionServiceType = subscriptionServiceType;
+ }
+
+ @JsonProperty("aLaCarte")
+ public Boolean getALaCarte() {
+ return aLaCarte;
+ }
+
+ @JsonProperty("aLaCarte")
+ public void setaLaCarte(Boolean aLaCarte) {
+ this.aLaCarte = aLaCarte;
+ }
+
+ public Boolean isaLaCarte() {
+ return aLaCarte;
+ }
+
+ public String getPayload() {
+ return payload;
+ }
+
+ public void setPayload(String value) {
+ this.payload = value;
+ }
+
+ public List<Map<String, Object>> getUserParams() {
+ return userParams;
+ }
+
+ public void setUserParams(List<Map<String, Object>> userParams) {
+ this.userParams = userParams;
+ }
+
+ public Object getUserParamValue(String name) {
+ if (userParams != null) {
+ for (Map<String, Object> param : userParams) {
+ if (param.get(name) != null) {
+ return param.get(name);
+ }
+ }
+ }
+ return null;
+ }
+
+ public Boolean isUsePreload() {
+ return usePreload;
+ }
+
+ @JsonProperty("usePreload")
+ public Boolean getUsePreload() {
+ return usePreload;
+ }
+
+ @JsonProperty("usePreload")
+ public void setUsePreload(Boolean usePreload) {
+ this.usePreload = usePreload;
+ }
+
+
+ @JsonInclude(Include.NON_NULL)
+ public String toJsonString() {
+ String json = "";
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(Include.NON_NULL);
+ ObjectWriter ow = mapper.writer();
+ try {
+ json = ow.writeValueAsString(this);
+ } catch (Exception e) {
+ logger.error("Unable to convert Sniro Manager Request to string", e);
+ }
+ return json;
+ }
+
+ @Override
+ public String toString() {
+ return "RequestParameters [subscriptionServiceType=" + subscriptionServiceType + ", userParams=" + userParams
+ + ", aLaCarte=" + aLaCarte + "]";
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/Candidate.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/Candidate.java
index a727162415..ed94c5380e 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/Candidate.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/Candidate.java
@@ -22,67 +22,62 @@ package org.onap.so.bpmn.servicedecomposition.homingobjects;
import java.io.Serializable;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class Candidate implements Serializable {
- private static final long serialVersionUID = -3959572501582849328L;
-
- @JsonProperty("identifierType")
- private CandidateType identifierType;
- @JsonProperty("identifiers")
- private List<String> identifiers;
- @JsonProperty("cloudOwner")
- private String cloudOwner;
-
- /**
- * list of candidates
- * i.e. actual serviceInstanceId, actual vnfName, actual cloudRegionId, etc.
- */
- public List<String> getIdentifiers() {
- return identifiers;
- }
-
- /**
- * list of candidates
- * i.e. actual serviceInstanceId, actual vnfName, actual cloudRegionId, etc.
- */
- public void setIdentifiers(List<String> identifiers) {
- this.identifiers = identifiers;
- }
-
- /**
- * Way to identify the type of candidate
- * i.e. "serviceInstanceId", "vnfName", "cloudRegionId", etc.
- */
- public CandidateType getIdentifierType(){
- return identifierType;
- }
-
- /**
- * Way to identify the type of candidate
- * i.e. "serviceInstanceId", "vnfName", "cloudRegionId", etc.
- */
- public void setIdentifierType(CandidateType identifierType){
- this.identifierType = identifierType;
- }
-
- /**
- * The name of the cloud owner. Required if candidateType is cloudRegionId
- */
- public String getCloudOwner(){
- return cloudOwner;
- }
-
- /**
- * The name of the cloud owner. Required if candidateType is cloudRegionId
- */
- public void setCloudOwner(String cloudOwner){
- this.cloudOwner = cloudOwner;
- }
+ private static final long serialVersionUID = -3959572501582849328L;
+
+ @JsonProperty("identifierType")
+ private CandidateType identifierType;
+ @JsonProperty("identifiers")
+ private List<String> identifiers;
+ @JsonProperty("cloudOwner")
+ private String cloudOwner;
+
+ /**
+ * list of candidates i.e. actual serviceInstanceId, actual vnfName, actual cloudRegionId, etc.
+ */
+ public List<String> getIdentifiers() {
+ return identifiers;
+ }
+
+ /**
+ * list of candidates i.e. actual serviceInstanceId, actual vnfName, actual cloudRegionId, etc.
+ */
+ public void setIdentifiers(List<String> identifiers) {
+ this.identifiers = identifiers;
+ }
+
+ /**
+ * Way to identify the type of candidate i.e. "serviceInstanceId", "vnfName", "cloudRegionId", etc.
+ */
+ public CandidateType getIdentifierType() {
+ return identifierType;
+ }
+
+ /**
+ * Way to identify the type of candidate i.e. "serviceInstanceId", "vnfName", "cloudRegionId", etc.
+ */
+ public void setIdentifierType(CandidateType identifierType) {
+ this.identifierType = identifierType;
+ }
+
+ /**
+ * The name of the cloud owner. Required if candidateType is cloudRegionId
+ */
+ public String getCloudOwner() {
+ return cloudOwner;
+ }
+
+ /**
+ * The name of the cloud owner. Required if candidateType is cloudRegionId
+ */
+ public void setCloudOwner(String cloudOwner) {
+ this.cloudOwner = cloudOwner;
+ }
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/CandidateType.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/CandidateType.java
index 6a4fa50020..ee97c054dd 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/CandidateType.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/CandidateType.java
@@ -22,23 +22,20 @@ package org.onap.so.bpmn.servicedecomposition.homingobjects;
import com.fasterxml.jackson.annotation.JsonValue;
-public enum CandidateType{
+public enum CandidateType {
- SERVICE_INSTANCE_ID("serviceInstanceId"),
- CLOUD_REGION_ID("cloudRegionId"),
- VNF_ID("vnfId"),
- VNF_NAME("vnfName");
+ SERVICE_INSTANCE_ID("serviceInstanceId"), CLOUD_REGION_ID("cloudRegionId"), VNF_ID("vnfId"), VNF_NAME("vnfName");
- private final String name;
+ private final String name;
- private CandidateType(String name) {
- this.name = name;
- }
+ private CandidateType(String name) {
+ this.name = name;
+ }
- @Override
- @JsonValue
- public String toString() {
- return name;
- }
+ @Override
+ @JsonValue
+ public String toString() {
+ return name;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionCandidates.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionCandidates.java
index 0cbd88b665..db5c11a954 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionCandidates.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionCandidates.java
@@ -23,43 +23,41 @@ package org.onap.so.bpmn.servicedecomposition.homingobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import org.onap.so.bpmn.servicedecomposition.homingobjects.Candidate;
-
import com.fasterxml.jackson.annotation.JsonProperty;
-public class SolutionCandidates implements Serializable{
+public class SolutionCandidates implements Serializable {
- private static final long serialVersionUID = 2188754118148819627L;
+ private static final long serialVersionUID = 2188754118148819627L;
- @JsonProperty("requiredCandidates")
- private List<Candidate> requiredCandidates = new ArrayList<Candidate>();
- @JsonProperty("excludedCandidates")
- private List<Candidate> excludedCandidates = new ArrayList<Candidate>();
- //TODO figure out best way to do this
- @JsonProperty("existingCandidates")
- private List<Candidate> existingCandidates = new ArrayList<Candidate>();
+ @JsonProperty("requiredCandidates")
+ private List<Candidate> requiredCandidates = new ArrayList<Candidate>();
+ @JsonProperty("excludedCandidates")
+ private List<Candidate> excludedCandidates = new ArrayList<Candidate>();
+ // TODO figure out best way to do this
+ @JsonProperty("existingCandidates")
+ private List<Candidate> existingCandidates = new ArrayList<Candidate>();
- public List<Candidate> getRequiredCandidates() {
- return requiredCandidates;
- }
- public void addRequiredCandidates(Candidate requiredCandidate) {
- this.requiredCandidates.add(requiredCandidate);
- }
- public List<Candidate> getExcludedCandidates() {
- return excludedCandidates;
- }
- public void addExcludedCandidates(Candidate excludedCandidate) {
- this.excludedCandidates.add(excludedCandidate);
- }
+ public List<Candidate> getRequiredCandidates() {
+ return requiredCandidates;
+ }
- public List<Candidate> getExistingCandidates(){
- return existingCandidates;
- }
+ public void addRequiredCandidates(Candidate requiredCandidate) {
+ this.requiredCandidates.add(requiredCandidate);
+ }
+ public List<Candidate> getExcludedCandidates() {
+ return excludedCandidates;
+ }
+ public void addExcludedCandidates(Candidate excludedCandidate) {
+ this.excludedCandidates.add(excludedCandidate);
+ }
+ public List<Candidate> getExistingCandidates() {
+ return existingCandidates;
+ }
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionInfo.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionInfo.java
index 3c8f0e933f..643113573e 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionInfo.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionInfo.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.servicedecomposition.homingobjects;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import org.onap.so.bpmn.servicedecomposition.ShallowCopy;
@@ -30,69 +29,63 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
@JsonRootName("solution")
public class SolutionInfo implements Serializable {
- private static final long serialVersionUID = 6903399488466840832L;
-
- @JsonProperty("solution-id") //identifies which solution
- private Integer solutionId;
- @JsonProperty("homed")
- private Boolean homed;
- @JsonProperty("is-rehome")
- private Boolean isRehome;
- @JsonProperty("targeted-cloud")
- private CloudRegion targetedCloudRegion;
-
-
- public Boolean isHomed() {
- return homed;
- }
-
- public void setHomed(Boolean homed) {
- this.homed = homed;
- }
-
- public Boolean isRehome() {
- return isRehome;
- }
-
- public void setRehome(Boolean isRehome) {
- this.isRehome = isRehome;
- }
-
- /**
- * Identifies which solution when multiple solutions exist for a
- * given resource or resource pair.
- * i.e. 1, 2, 3....
- */
- public Integer getSolutionId() {
- return solutionId;
- }
-
- /**
- * Identifies which solution when multiple solutions exist for a
- * given resource or resource pair.
- * i.e. 1, 2, 3....
- */
- public void setSolutionId(Integer solutionId) {
- this.solutionId = solutionId;
- }
-
- /**
- * Identifies where the resource should be created for
- * homed equals false scenarios. Will return null if resource
- * was homed.
- */
- public CloudRegion getTargetedCloudRegion() {
- return targetedCloudRegion;
- }
-
- /**
- * Identifies where the resource should be created for
- * homed equals false scenarios. Will return null if resource
- * was homed.
- */
- public void setTargetedCloudRegion(CloudRegion targetedCloudRegion) {
- this.targetedCloudRegion = targetedCloudRegion;
- }
+ private static final long serialVersionUID = 6903399488466840832L;
+
+ @JsonProperty("solution-id") // identifies which solution
+ private Integer solutionId;
+ @JsonProperty("homed")
+ private Boolean homed;
+ @JsonProperty("is-rehome")
+ private Boolean isRehome;
+ @JsonProperty("targeted-cloud")
+ private CloudRegion targetedCloudRegion;
+
+
+ public Boolean isHomed() {
+ return homed;
+ }
+
+ public void setHomed(Boolean homed) {
+ this.homed = homed;
+ }
+
+ public Boolean isRehome() {
+ return isRehome;
+ }
+
+ public void setRehome(Boolean isRehome) {
+ this.isRehome = isRehome;
+ }
+
+ /**
+ * Identifies which solution when multiple solutions exist for a given resource or resource pair. i.e. 1, 2, 3....
+ */
+ public Integer getSolutionId() {
+ return solutionId;
+ }
+
+ /**
+ * Identifies which solution when multiple solutions exist for a given resource or resource pair. i.e. 1, 2, 3....
+ */
+ public void setSolutionId(Integer solutionId) {
+ this.solutionId = solutionId;
+ }
+
+ /**
+ * Identifies where the resource should be created for homed equals false scenarios. Will return null if resource
+ * was homed.
+ */
+ public CloudRegion getTargetedCloudRegion() {
+ return targetedCloudRegion;
+ }
+
+ /**
+ * Identifies where the resource should be created for homed equals false scenarios. Will return null if resource
+ * was homed.
+ */
+ public void setTargetedCloudRegion(CloudRegion targetedCloudRegion) {
+ this.targetedCloudRegion = targetedCloudRegion;
+ }
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoAllottedResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoAllottedResource.java
index b4f2e85e55..a0a8408cfc 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoAllottedResource.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoAllottedResource.java
@@ -21,126 +21,152 @@
package org.onap.so.bpmn.servicedecomposition.modelinfo;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
-public class ModelInfoAllottedResource extends ModelInfoMetadata implements Serializable{
-
- private static final long serialVersionUID = -5240932898637922018L;
-
- @JsonProperty("max-instances")
- private String MaxInstances;
- @JsonProperty("min-instances")
- private String MinInstances;
- @JsonProperty("nf-naming-code")
- private String NfNamingCode;
- @JsonProperty("nf-role")
- private String NfRole;
- @JsonProperty("nf-type")
- private String NfType;
- @JsonProperty("nf-function")
- private String NfFunction;
- @JsonProperty("target-network-role")
- private String TarNetworkRole;
- @JsonProperty("providing-service-model-invariant-uuid")
- private String ProvidingServiceModelInvariantUUID;
- @JsonProperty("providing-service-model-name")
- private String ProvidingServiceModelName;
- @JsonProperty("providing-service-model-uuid")
- private String ProvidingServiceModelUUID;
- @JsonProperty("description")
- private String Description;
- @JsonProperty("created")
- private String Created;
- @JsonProperty("tosca-node-type")
- private String ToscaNodeType;
- @JsonProperty("subcategory")
- private String Subcategory;
-// private ModelInfoMetadata modelInfoMetadata;
-
-
- public String getMaxInstances() {
- return MaxInstances;
- }
- public void setMaxInstances(String maxInstances) {
- MaxInstances = maxInstances;
- }
- public String getMinInstances() {
- return MinInstances;
- }
- public void setMinInstances(String minInstances) {
- MinInstances = minInstances;
- }
- public String getNfNamingCode() {
- return NfNamingCode;
- }
- public void setNfNamingCode(String nfNamingCode) {
- NfNamingCode = nfNamingCode;
- }
- public String getNfRole() {
- return NfRole;
- }
- public void setNfRole(String nfRole) {
- NfRole = nfRole;
- }
- public String getNfType() {
- return NfType;
- }
- public void setNfType(String nfType) {
- NfType = nfType;
- }
- public String getNfFunction() {
- return NfFunction;
- }
- public void setNfFunction(String nfFunction) {
- NfFunction = nfFunction;
- }
- public String getTarNetworkRole() {
- return TarNetworkRole;
- }
- public void setTarNetworkRole(String tarNetworkRole) {
- TarNetworkRole = tarNetworkRole;
- }
- public String getProvidingServiceModelInvariantUUID() {
- return ProvidingServiceModelInvariantUUID;
- }
- public void setProvidingServiceModelInvariantUUID(String providingServiceModelInvariantUUID) {
- ProvidingServiceModelInvariantUUID = providingServiceModelInvariantUUID;
- }
- public String getProvidingServiceModelName() {
- return ProvidingServiceModelName;
- }
- public void setProvidingServiceModelName(String providingServiceModelName) {
- ProvidingServiceModelName = providingServiceModelName;
- }
- public String getProvidingServiceModelUUID() {
- return ProvidingServiceModelUUID;
- }
- public void setProvidingServiceModelUUID(String providingServiceModelUUID) {
- ProvidingServiceModelUUID = providingServiceModelUUID;
- }
- public String getDescription() {
- return Description;
- }
- public void setDescription(String description) {
- Description = description;
- }
- public String getCreated() {
- return Created;
- }
- public void setCreated(String created) {
- Created = created;
- }
- public String getToscaNodeType() {
- return ToscaNodeType;
- }
- public void setToscaNodeType(String toscaNodeType) {
- ToscaNodeType = toscaNodeType;
- }
- public String getSubcategory() {
- return Subcategory;
- }
- public void setSubcategory(String subcategory) {
- Subcategory = subcategory;
- }
+public class ModelInfoAllottedResource extends ModelInfoMetadata implements Serializable {
+
+ private static final long serialVersionUID = -5240932898637922018L;
+
+ @JsonProperty("max-instances")
+ private String MaxInstances;
+ @JsonProperty("min-instances")
+ private String MinInstances;
+ @JsonProperty("nf-naming-code")
+ private String NfNamingCode;
+ @JsonProperty("nf-role")
+ private String NfRole;
+ @JsonProperty("nf-type")
+ private String NfType;
+ @JsonProperty("nf-function")
+ private String NfFunction;
+ @JsonProperty("target-network-role")
+ private String TarNetworkRole;
+ @JsonProperty("providing-service-model-invariant-uuid")
+ private String ProvidingServiceModelInvariantUUID;
+ @JsonProperty("providing-service-model-name")
+ private String ProvidingServiceModelName;
+ @JsonProperty("providing-service-model-uuid")
+ private String ProvidingServiceModelUUID;
+ @JsonProperty("description")
+ private String Description;
+ @JsonProperty("created")
+ private String Created;
+ @JsonProperty("tosca-node-type")
+ private String ToscaNodeType;
+ @JsonProperty("subcategory")
+ private String Subcategory;
+ // private ModelInfoMetadata modelInfoMetadata;
+
+
+ public String getMaxInstances() {
+ return MaxInstances;
+ }
+
+ public void setMaxInstances(String maxInstances) {
+ MaxInstances = maxInstances;
+ }
+
+ public String getMinInstances() {
+ return MinInstances;
+ }
+
+ public void setMinInstances(String minInstances) {
+ MinInstances = minInstances;
+ }
+
+ public String getNfNamingCode() {
+ return NfNamingCode;
+ }
+
+ public void setNfNamingCode(String nfNamingCode) {
+ NfNamingCode = nfNamingCode;
+ }
+
+ public String getNfRole() {
+ return NfRole;
+ }
+
+ public void setNfRole(String nfRole) {
+ NfRole = nfRole;
+ }
+
+ public String getNfType() {
+ return NfType;
+ }
+
+ public void setNfType(String nfType) {
+ NfType = nfType;
+ }
+
+ public String getNfFunction() {
+ return NfFunction;
+ }
+
+ public void setNfFunction(String nfFunction) {
+ NfFunction = nfFunction;
+ }
+
+ public String getTarNetworkRole() {
+ return TarNetworkRole;
+ }
+
+ public void setTarNetworkRole(String tarNetworkRole) {
+ TarNetworkRole = tarNetworkRole;
+ }
+
+ public String getProvidingServiceModelInvariantUUID() {
+ return ProvidingServiceModelInvariantUUID;
+ }
+
+ public void setProvidingServiceModelInvariantUUID(String providingServiceModelInvariantUUID) {
+ ProvidingServiceModelInvariantUUID = providingServiceModelInvariantUUID;
+ }
+
+ public String getProvidingServiceModelName() {
+ return ProvidingServiceModelName;
+ }
+
+ public void setProvidingServiceModelName(String providingServiceModelName) {
+ ProvidingServiceModelName = providingServiceModelName;
+ }
+
+ public String getProvidingServiceModelUUID() {
+ return ProvidingServiceModelUUID;
+ }
+
+ public void setProvidingServiceModelUUID(String providingServiceModelUUID) {
+ ProvidingServiceModelUUID = providingServiceModelUUID;
+ }
+
+ public String getDescription() {
+ return Description;
+ }
+
+ public void setDescription(String description) {
+ Description = description;
+ }
+
+ public String getCreated() {
+ return Created;
+ }
+
+ public void setCreated(String created) {
+ Created = created;
+ }
+
+ public String getToscaNodeType() {
+ return ToscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ ToscaNodeType = toscaNodeType;
+ }
+
+ public String getSubcategory() {
+ return Subcategory;
+ }
+
+ public void setSubcategory(String subcategory) {
+ Subcategory = subcategory;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoCollection.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoCollection.java
index cb6fabde30..d31d84807d 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoCollection.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoCollection.java
@@ -21,79 +21,93 @@
package org.onap.so.bpmn.servicedecomposition.modelinfo;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
-public class ModelInfoCollection implements Serializable {
-
- private static final long serialVersionUID = 8380534468706675508L;
-
- @JsonProperty("model-customization-uuid")
- private String modelCustomizationUUID;
- @JsonProperty("model-version-id")
- private String modelVersionId;
- @JsonProperty("model-invariant-uuid")
- private String modelInvariantUUID;
- @JsonProperty("collection-function")
- private String collectionFunction;
- @JsonProperty("collection-role")
- private String collectionRole;
- @JsonProperty("collection-type")
- private String collectionType;
- @JsonProperty("description")
- private String description;
- @JsonProperty("quantity")
- private Integer quantity;
-
- public String getModelCustomizationUUID() {
- return modelCustomizationUUID;
- }
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
- public String getModelVersionId() {
- return modelVersionId;
- }
- public void setModelVersionId(String modelVersionId) {
- this.modelVersionId = modelVersionId;
- }
- public String getModelInvariantUUID() {
- return this.modelInvariantUUID;
- }
- public void setModelInvariantUUID(String modelInvariantUUID) {
- this.modelInvariantUUID = modelInvariantUUID;
- }
- public String getCollectionFunction() {
- return collectionFunction;
- }
- public void setCollectionFunction(String collectionFunction) {
- this.collectionFunction = collectionFunction;
- }
- public String getCollectionRole() {
- return collectionRole;
- }
- public void setCollectionRole(String collectionRole) {
- this.collectionRole = collectionRole;
- }
- public String getCollectionType() {
- return collectionType;
- }
- public void setCollectionType(String collectionType) {
- this.collectionType = collectionType;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- public Integer getQuantity() {
- return quantity;
- }
- public void setQuantity(Integer quantity) {
- this.quantity = quantity;
- }
-
-
-
+public class ModelInfoCollection implements Serializable {
+
+ private static final long serialVersionUID = 8380534468706675508L;
+
+ @JsonProperty("model-customization-uuid")
+ private String modelCustomizationUUID;
+ @JsonProperty("model-version-id")
+ private String modelVersionId;
+ @JsonProperty("model-invariant-uuid")
+ private String modelInvariantUUID;
+ @JsonProperty("collection-function")
+ private String collectionFunction;
+ @JsonProperty("collection-role")
+ private String collectionRole;
+ @JsonProperty("collection-type")
+ private String collectionType;
+ @JsonProperty("description")
+ private String description;
+ @JsonProperty("quantity")
+ private Integer quantity;
+
+ public String getModelCustomizationUUID() {
+ return modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ public String getModelVersionId() {
+ return modelVersionId;
+ }
+
+ public void setModelVersionId(String modelVersionId) {
+ this.modelVersionId = modelVersionId;
+ }
+
+ public String getModelInvariantUUID() {
+ return this.modelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ this.modelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getCollectionFunction() {
+ return collectionFunction;
+ }
+
+ public void setCollectionFunction(String collectionFunction) {
+ this.collectionFunction = collectionFunction;
+ }
+
+ public String getCollectionRole() {
+ return collectionRole;
+ }
+
+ public void setCollectionRole(String collectionRole) {
+ this.collectionRole = collectionRole;
+ }
+
+ public String getCollectionType() {
+ return collectionType;
+ }
+
+ public void setCollectionType(String collectionType) {
+ this.collectionType = collectionType;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Integer getQuantity() {
+ return quantity;
+ }
+
+ public void setQuantity(Integer quantity) {
+ this.quantity = quantity;
+ }
+
+
+
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoConfiguration.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoConfiguration.java
index 462664c612..21b8c74967 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoConfiguration.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoConfiguration.java
@@ -21,60 +21,70 @@
package org.onap.so.bpmn.servicedecomposition.modelinfo;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
-public class ModelInfoConfiguration implements Serializable{
-
- private static final long serialVersionUID = -387242776138157250L;
-
- @JsonProperty("model-invariant-id")
- private String modelInvariantId;
- @JsonProperty("model-version-id")
- private String modelVersionId;
- @JsonProperty("model-customization-id")
- private String modelCustomizationId;
- @JsonProperty("configuration-type")
- private String configurationType;
- @JsonProperty("configuration-role")
- private String configurationRole;
- @JsonProperty("policy-name")
- private String policyName;
-
- public String getConfigurationRole() {
- return configurationRole;
- }
- public void setConfigurationRole(String configurationRole) {
- this.configurationRole = configurationRole;
- }
- public String getConfigurationType() {
- return configurationType;
- }
- public void setConfigurationType(String configurationType) {
- this.configurationType = configurationType;
- }
- public String getModelInvariantId() {
- return modelInvariantId;
- }
- public void setModelInvariantId(String modelInvariantId) {
- this.modelInvariantId = modelInvariantId;
- }
- public String getModelVersionId() {
- return modelVersionId;
- }
- public void setModelVersionId(String modelVersionId) {
- this.modelVersionId = modelVersionId;
- }
- public String getModelCustomizationId() {
- return modelCustomizationId;
- }
- public void setModelCustomizationId(String modelCustomizationId) {
- this.modelCustomizationId = modelCustomizationId;
- }
- public String getPolicyName() {
- return policyName;
- }
- public void setPolicyName(String policyName) {
- this.policyName = policyName;
- }
+public class ModelInfoConfiguration implements Serializable {
+
+ private static final long serialVersionUID = -387242776138157250L;
+
+ @JsonProperty("model-invariant-id")
+ private String modelInvariantId;
+ @JsonProperty("model-version-id")
+ private String modelVersionId;
+ @JsonProperty("model-customization-id")
+ private String modelCustomizationId;
+ @JsonProperty("configuration-type")
+ private String configurationType;
+ @JsonProperty("configuration-role")
+ private String configurationRole;
+ @JsonProperty("policy-name")
+ private String policyName;
+
+ public String getConfigurationRole() {
+ return configurationRole;
+ }
+
+ public void setConfigurationRole(String configurationRole) {
+ this.configurationRole = configurationRole;
+ }
+
+ public String getConfigurationType() {
+ return configurationType;
+ }
+
+ public void setConfigurationType(String configurationType) {
+ this.configurationType = configurationType;
+ }
+
+ public String getModelInvariantId() {
+ return modelInvariantId;
+ }
+
+ public void setModelInvariantId(String modelInvariantId) {
+ this.modelInvariantId = modelInvariantId;
+ }
+
+ public String getModelVersionId() {
+ return modelVersionId;
+ }
+
+ public void setModelVersionId(String modelVersionId) {
+ this.modelVersionId = modelVersionId;
+ }
+
+ public String getModelCustomizationId() {
+ return modelCustomizationId;
+ }
+
+ public void setModelCustomizationId(String modelCustomizationId) {
+ this.modelCustomizationId = modelCustomizationId;
+ }
+
+ public String getPolicyName() {
+ return policyName;
+ }
+
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoGenericVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoGenericVnf.java
index 6b53272a75..14327a3583 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoGenericVnf.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoGenericVnf.java
@@ -21,125 +21,151 @@
package org.onap.so.bpmn.servicedecomposition.modelinfo;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
-public class ModelInfoGenericVnf extends ModelInfoMetadata implements Serializable{
-
- private static final long serialVersionUID = -5963022750248280669L;
-
- @JsonProperty("tosca-node-type")
- private String ToscaNodeType;
- @JsonProperty("description")
- private String Description;
- @JsonProperty("orchestration-mode")
- private String OrchestrationMode;
- @JsonProperty("aic-version-min")
- private String AicVersionMin;
- @JsonProperty("aic-version-max")
- private String AicVersionMax;
- @JsonProperty("min-instances")
- private String MinInstances;
- @JsonProperty("max-instances")
- private String MaxInstances;
- @JsonProperty("availability-zone-max-count")
- private String AvailabilityZoneMaxCount;
- @JsonProperty("nf-function")
- private String NfFunction;
- @JsonProperty("nf-type")
- private String NfType;
- @JsonProperty("nf-role")
- private String NfRole;
- @JsonProperty("nf-naming-code")
- private String NfNamingCode;
- @JsonProperty("multi-stage-design")
- private String MultiStageDesign;
- @JsonProperty("created")
- private String Created;
-
-
- public String getToscaNodeType() {
- return ToscaNodeType;
- }
- public void setToscaNodeType(String toscaNodeType) {
- ToscaNodeType = toscaNodeType;
- }
- public String getDescription() {
- return Description;
- }
- public void setDescription(String description) {
- Description = description;
- }
- public String getOrchestrationMode() {
- return OrchestrationMode;
- }
- public void setOrchestrationMode(String orchestrationMode) {
- OrchestrationMode = orchestrationMode;
- }
- public String getAicVersionMin() {
- return AicVersionMin;
- }
- public void setAicVersionMin(String aicVersionMin) {
- AicVersionMin = aicVersionMin;
- }
- public String getAicVersionMax() {
- return AicVersionMax;
- }
- public void setAicVersionMax(String aicVersionMax) {
- AicVersionMax = aicVersionMax;
- }
- public String getMinInstances() {
- return MinInstances;
- }
- public void setMinInstances(String minInstances) {
- MinInstances = minInstances;
- }
- public String getMaxInstances() {
- return MaxInstances;
- }
- public void setMaxInstances(String maxInstances) {
- MaxInstances = maxInstances;
- }
- public String getAvailabilityZoneMaxCount() {
- return AvailabilityZoneMaxCount;
- }
- public void setAvailabilityZoneMaxCount(String availabilityZoneMaxCount) {
- AvailabilityZoneMaxCount = availabilityZoneMaxCount;
- }
- public String getNfFunction() {
- return NfFunction;
- }
- public void setNfFunction(String nfFunction) {
- NfFunction = nfFunction;
- }
- public String getNfType() {
- return NfType;
- }
- public void setNfType(String nfType) {
- NfType = nfType;
- }
- public String getNfRole() {
- return NfRole;
- }
- public void setNfRole(String nfRole) {
- NfRole = nfRole;
- }
- public String getNfNamingCode() {
- return NfNamingCode;
- }
- public void setNfNamingCode(String nfNamingCode) {
- NfNamingCode = nfNamingCode;
- }
- public String getMultiStageDesign() {
- return MultiStageDesign;
- }
- public void setMultiStageDesign(String multiStageDesign) {
- MultiStageDesign = multiStageDesign;
- }
- public String getCreated() {
- return Created;
- }
- public void setCreated(String created) {
- Created = created;
- }
+public class ModelInfoGenericVnf extends ModelInfoMetadata implements Serializable {
+
+ private static final long serialVersionUID = -5963022750248280669L;
+
+ @JsonProperty("tosca-node-type")
+ private String ToscaNodeType;
+ @JsonProperty("description")
+ private String Description;
+ @JsonProperty("orchestration-mode")
+ private String OrchestrationMode;
+ @JsonProperty("aic-version-min")
+ private String AicVersionMin;
+ @JsonProperty("aic-version-max")
+ private String AicVersionMax;
+ @JsonProperty("min-instances")
+ private String MinInstances;
+ @JsonProperty("max-instances")
+ private String MaxInstances;
+ @JsonProperty("availability-zone-max-count")
+ private String AvailabilityZoneMaxCount;
+ @JsonProperty("nf-function")
+ private String NfFunction;
+ @JsonProperty("nf-type")
+ private String NfType;
+ @JsonProperty("nf-role")
+ private String NfRole;
+ @JsonProperty("nf-naming-code")
+ private String NfNamingCode;
+ @JsonProperty("multi-stage-design")
+ private String MultiStageDesign;
+ @JsonProperty("created")
+ private String Created;
+
+
+ public String getToscaNodeType() {
+ return ToscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ ToscaNodeType = toscaNodeType;
+ }
+
+ public String getDescription() {
+ return Description;
+ }
+
+ public void setDescription(String description) {
+ Description = description;
+ }
+
+ public String getOrchestrationMode() {
+ return OrchestrationMode;
+ }
+
+ public void setOrchestrationMode(String orchestrationMode) {
+ OrchestrationMode = orchestrationMode;
+ }
+
+ public String getAicVersionMin() {
+ return AicVersionMin;
+ }
+
+ public void setAicVersionMin(String aicVersionMin) {
+ AicVersionMin = aicVersionMin;
+ }
+
+ public String getAicVersionMax() {
+ return AicVersionMax;
+ }
+
+ public void setAicVersionMax(String aicVersionMax) {
+ AicVersionMax = aicVersionMax;
+ }
+
+ public String getMinInstances() {
+ return MinInstances;
+ }
+
+ public void setMinInstances(String minInstances) {
+ MinInstances = minInstances;
+ }
+
+ public String getMaxInstances() {
+ return MaxInstances;
+ }
+
+ public void setMaxInstances(String maxInstances) {
+ MaxInstances = maxInstances;
+ }
+
+ public String getAvailabilityZoneMaxCount() {
+ return AvailabilityZoneMaxCount;
+ }
+
+ public void setAvailabilityZoneMaxCount(String availabilityZoneMaxCount) {
+ AvailabilityZoneMaxCount = availabilityZoneMaxCount;
+ }
+
+ public String getNfFunction() {
+ return NfFunction;
+ }
+
+ public void setNfFunction(String nfFunction) {
+ NfFunction = nfFunction;
+ }
+
+ public String getNfType() {
+ return NfType;
+ }
+
+ public void setNfType(String nfType) {
+ NfType = nfType;
+ }
+
+ public String getNfRole() {
+ return NfRole;
+ }
+
+ public void setNfRole(String nfRole) {
+ NfRole = nfRole;
+ }
+
+ public String getNfNamingCode() {
+ return NfNamingCode;
+ }
+
+ public void setNfNamingCode(String nfNamingCode) {
+ NfNamingCode = nfNamingCode;
+ }
+
+ public String getMultiStageDesign() {
+ return MultiStageDesign;
+ }
+
+ public void setMultiStageDesign(String multiStageDesign) {
+ MultiStageDesign = multiStageDesign;
+ }
+
+ public String getCreated() {
+ return Created;
+ }
+
+ public void setCreated(String created) {
+ Created = created;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoInstanceGroup.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoInstanceGroup.java
index e03ee358f3..7b30858b25 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoInstanceGroup.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoInstanceGroup.java
@@ -23,60 +23,71 @@ package org.onap.so.bpmn.servicedecomposition.modelinfo;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonProperty;
-public class ModelInfoInstanceGroup implements Serializable {
-
- private static final long serialVersionUID = -8279040393230356226L;
-
- public static final String TYPE_L3_NETWORK = "L3-NETWORK";
- public static final String TYPE_VNFC = "VNFC";
-
- @JsonProperty("model-uuid")
- private String ModelUUID;
- @JsonProperty("model-invariant-uuid")
- private String ModelInvariantUUID;
- @JsonProperty("type")
- private String type;
- @JsonProperty("instance-group-role")
- private String instanceGroupRole;
- @JsonProperty("function")
- private String function;
- @JsonProperty("description")
- private String description;
-
- public String getModelUUID() {
- return ModelUUID;
- }
- public void setModelUUID(String modelUUID) {
- ModelUUID = modelUUID;
- }
- public String getModelInvariantUUID() {
- return ModelInvariantUUID;
- }
- public void setModelInvariantUUID(String modelInvariantUUID) {
- ModelInvariantUUID = modelInvariantUUID;
- }
- public String getType() {
- return type;
- }
- public void setType(String type) {
- this.type = type;
- }
- public String getInstanceGroupRole() {
- return instanceGroupRole;
- }
- public void setInstanceGroupRole(String instanceGroupRole) {
- this.instanceGroupRole = instanceGroupRole;
- }
- public String getFunction() {
- return function;
- }
- public void setFunction(String function) {
- this.function = function;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
+public class ModelInfoInstanceGroup implements Serializable {
+
+ private static final long serialVersionUID = -8279040393230356226L;
+
+ public static final String TYPE_L3_NETWORK = "L3-NETWORK";
+ public static final String TYPE_VNFC = "VNFC";
+
+ @JsonProperty("model-uuid")
+ private String ModelUUID;
+ @JsonProperty("model-invariant-uuid")
+ private String ModelInvariantUUID;
+ @JsonProperty("type")
+ private String type;
+ @JsonProperty("instance-group-role")
+ private String instanceGroupRole;
+ @JsonProperty("function")
+ private String function;
+ @JsonProperty("description")
+ private String description;
+
+ public String getModelUUID() {
+ return ModelUUID;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ ModelUUID = modelUUID;
+ }
+
+ public String getModelInvariantUUID() {
+ return ModelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ ModelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getInstanceGroupRole() {
+ return instanceGroupRole;
+ }
+
+ public void setInstanceGroupRole(String instanceGroupRole) {
+ this.instanceGroupRole = instanceGroupRole;
+ }
+
+ public String getFunction() {
+ return function;
+ }
+
+ public void setFunction(String function) {
+ this.function = function;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoMetadata.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoMetadata.java
index c873912922..7fc29a8fc1 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoMetadata.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoMetadata.java
@@ -21,63 +21,73 @@
package org.onap.so.bpmn.servicedecomposition.modelinfo;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
-public class ModelInfoMetadata implements Serializable{
-
- private static final long serialVersionUID = -2182850364281359289L;
-
- @JsonProperty("model-customization-uuid")
- private String modelCustomizationUuid;
- @JsonProperty("model-invariant-uuid")
- private String modelInvariantUuid;
- @JsonProperty("model-uuid")
- private String modelUuid;
- @JsonProperty("model-version")
- private String modelVersion;
- @JsonProperty("model-instance-name")
- private String modelInstanceName;
- @JsonProperty("model-name")
- private String modelName;
-
-
- public String getModelCustomizationUuid() {
- return modelCustomizationUuid;
- }
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
- public String getModelInvariantUuid() {
- return modelInvariantUuid;
- }
- public void setModelInvariantUuid(String modelInvariantUuid) {
- this.modelInvariantUuid = modelInvariantUuid;
- }
- public String getModelUuid() {
- return modelUuid;
- }
- public void setModelUuid(String modelUuid) {
- this.modelUuid = modelUuid;
- }
- public String getModelVersion() {
- return modelVersion;
- }
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
- public String getModelInstanceName() {
- return modelInstanceName;
- }
- public void setModelInstanceName(String modelInstanceName) {
- this.modelInstanceName = modelInstanceName;
- }
- public String getModelName() {
- return modelName;
- }
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
+public class ModelInfoMetadata implements Serializable {
+
+ private static final long serialVersionUID = -2182850364281359289L;
+
+ @JsonProperty("model-customization-uuid")
+ private String modelCustomizationUuid;
+ @JsonProperty("model-invariant-uuid")
+ private String modelInvariantUuid;
+ @JsonProperty("model-uuid")
+ private String modelUuid;
+ @JsonProperty("model-version")
+ private String modelVersion;
+ @JsonProperty("model-instance-name")
+ private String modelInstanceName;
+ @JsonProperty("model-name")
+ private String modelName;
+
+
+ public String getModelCustomizationUuid() {
+ return modelCustomizationUuid;
+ }
+
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ public String getModelInvariantUuid() {
+ return modelInvariantUuid;
+ }
+
+ public void setModelInvariantUuid(String modelInvariantUuid) {
+ this.modelInvariantUuid = modelInvariantUuid;
+ }
+
+ public String getModelUuid() {
+ return modelUuid;
+ }
+
+ public void setModelUuid(String modelUuid) {
+ this.modelUuid = modelUuid;
+ }
+
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ public String getModelInstanceName() {
+ return modelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ this.modelInstanceName = modelInstanceName;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoNetwork.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoNetwork.java
index 22233e94a5..955ad86561 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoNetwork.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoNetwork.java
@@ -22,148 +22,180 @@ package org.onap.so.bpmn.servicedecomposition.modelinfo;
import java.io.Serializable;
import java.sql.Timestamp;
-
import com.fasterxml.jackson.annotation.JsonProperty;
-public class ModelInfoNetwork implements Serializable{
-
- private static final long serialVersionUID = -3612850497900637132L;
-
- @JsonProperty("model-customization-uuid")
- private String ModelCustomizationUUID;
- @JsonProperty("model-instance-name")
- private String ModelInstanceName;
- @JsonProperty("network-technology")
- private String NetworkTechnology;
- @JsonProperty("network-type")
- private String NetworkType;
- @JsonProperty("network-scope")
- private String NetworkScope;
- @JsonProperty("network-role")
- private String NetworkRole;
- @JsonProperty("description")
- private String Description;
- @JsonProperty("created")
- private Timestamp Created;
- @JsonProperty("model-version")
- private String ModelVersion;
- @JsonProperty("model-invariant-uuid")
- private String ModelInvariantUUID;
- @JsonProperty("model-name")
- private String ModelName;
- @JsonProperty("model-uuid")
- private String ModelUUID;
- @JsonProperty("neutron-network-type")
- private String NeutronNetworkType;
- @JsonProperty("aic-version-min")
- private String AicVersionMin;
- @JsonProperty("aic-version-max")
- private String AicVersionMax;
- @JsonProperty("orchestration-mode")
- private String OrchestrationMode;
- @JsonProperty("tosca-node-type")
- private String ToscaNodeType;
-
- public String getModelCustomizationUUID() {
- return ModelCustomizationUUID;
- }
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- ModelCustomizationUUID = modelCustomizationUUID;
- }
- public String getModelInstanceName() {
- return ModelInstanceName;
- }
- public void setModelInstanceName(String modelInstanceName) {
- ModelInstanceName = modelInstanceName;
- }
- public String getNetworkTechnology() {
- return NetworkTechnology;
- }
- public void setNetworkTechnology(String networkTechnology) {
- NetworkTechnology = networkTechnology;
- }
- public String getNetworkType() {
- return NetworkType;
- }
- public void setNetworkType(String networkType) {
- NetworkType = networkType;
- }
- public String getNetworkScope() {
- return NetworkScope;
- }
- public void setNetworkScope(String networkScope) {
- NetworkScope = networkScope;
- }
- public String getNetworkRole() {
- return NetworkRole;
- }
- public void setNetworkRole(String networkRole) {
- NetworkRole = networkRole;
- }
- public String getDescription() {
- return Description;
- }
- public void setDescription(String description) {
- Description = description;
- }
- public Timestamp getCreated() {
- return Created;
- }
- public void setCreated(Timestamp created) {
- Created = created;
- }
- public String getModelVersion() {
- return ModelVersion;
- }
- public void setModelVersion(String modelVersion) {
- ModelVersion = modelVersion;
- }
- public String getModelInvariantUUID() {
- return ModelInvariantUUID;
- }
- public void setModelInvariantUUID(String modelInvariantUUID) {
- ModelInvariantUUID = modelInvariantUUID;
- }
- public String getModelName() {
- return ModelName;
- }
- public void setModelName(String modelName) {
- ModelName = modelName;
- }
- public String getModelUUID() {
- return ModelUUID;
- }
- public void setModelUUID(String modelUUID) {
- ModelUUID = modelUUID;
- }
- public String getNeutronNetworkType() {
- return NeutronNetworkType;
- }
- public void setNeutronNetworkType(String neutronNetworkType) {
- NeutronNetworkType = neutronNetworkType;
- }
- public String getAicVersionMin() {
- return AicVersionMin;
- }
- public void setAicVersionMin(String aicVersionMin) {
- AicVersionMin = aicVersionMin;
- }
- public String getAicVersionMax() {
- return AicVersionMax;
- }
- public void setAicVersionMax(String aicVersionMax) {
- AicVersionMax = aicVersionMax;
- }
- public String getOrchestrationMode() {
- return OrchestrationMode;
- }
- public void setOrchestrationMode(String orchestrationMode) {
- OrchestrationMode = orchestrationMode;
- }
- public String getToscaNodeType() {
- return ToscaNodeType;
- }
- public void setToscaNodeType(String toscaNodeType) {
- ToscaNodeType = toscaNodeType;
- }
+public class ModelInfoNetwork implements Serializable {
+
+ private static final long serialVersionUID = -3612850497900637132L;
+
+ @JsonProperty("model-customization-uuid")
+ private String ModelCustomizationUUID;
+ @JsonProperty("model-instance-name")
+ private String ModelInstanceName;
+ @JsonProperty("network-technology")
+ private String NetworkTechnology;
+ @JsonProperty("network-type")
+ private String NetworkType;
+ @JsonProperty("network-scope")
+ private String NetworkScope;
+ @JsonProperty("network-role")
+ private String NetworkRole;
+ @JsonProperty("description")
+ private String Description;
+ @JsonProperty("created")
+ private Timestamp Created;
+ @JsonProperty("model-version")
+ private String ModelVersion;
+ @JsonProperty("model-invariant-uuid")
+ private String ModelInvariantUUID;
+ @JsonProperty("model-name")
+ private String ModelName;
+ @JsonProperty("model-uuid")
+ private String ModelUUID;
+ @JsonProperty("neutron-network-type")
+ private String NeutronNetworkType;
+ @JsonProperty("aic-version-min")
+ private String AicVersionMin;
+ @JsonProperty("aic-version-max")
+ private String AicVersionMax;
+ @JsonProperty("orchestration-mode")
+ private String OrchestrationMode;
+ @JsonProperty("tosca-node-type")
+ private String ToscaNodeType;
+
+ public String getModelCustomizationUUID() {
+ return ModelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ ModelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ public String getModelInstanceName() {
+ return ModelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ ModelInstanceName = modelInstanceName;
+ }
+
+ public String getNetworkTechnology() {
+ return NetworkTechnology;
+ }
+
+ public void setNetworkTechnology(String networkTechnology) {
+ NetworkTechnology = networkTechnology;
+ }
+
+ public String getNetworkType() {
+ return NetworkType;
+ }
+
+ public void setNetworkType(String networkType) {
+ NetworkType = networkType;
+ }
+
+ public String getNetworkScope() {
+ return NetworkScope;
+ }
+
+ public void setNetworkScope(String networkScope) {
+ NetworkScope = networkScope;
+ }
+
+ public String getNetworkRole() {
+ return NetworkRole;
+ }
+
+ public void setNetworkRole(String networkRole) {
+ NetworkRole = networkRole;
+ }
+
+ public String getDescription() {
+ return Description;
+ }
+
+ public void setDescription(String description) {
+ Description = description;
+ }
+
+ public Timestamp getCreated() {
+ return Created;
+ }
+
+ public void setCreated(Timestamp created) {
+ Created = created;
+ }
+
+ public String getModelVersion() {
+ return ModelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ ModelVersion = modelVersion;
+ }
+
+ public String getModelInvariantUUID() {
+ return ModelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ ModelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getModelName() {
+ return ModelName;
+ }
+
+ public void setModelName(String modelName) {
+ ModelName = modelName;
+ }
+
+ public String getModelUUID() {
+ return ModelUUID;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ ModelUUID = modelUUID;
+ }
+
+ public String getNeutronNetworkType() {
+ return NeutronNetworkType;
+ }
+
+ public void setNeutronNetworkType(String neutronNetworkType) {
+ NeutronNetworkType = neutronNetworkType;
+ }
+
+ public String getAicVersionMin() {
+ return AicVersionMin;
+ }
+
+ public void setAicVersionMin(String aicVersionMin) {
+ AicVersionMin = aicVersionMin;
+ }
+
+ public String getAicVersionMax() {
+ return AicVersionMax;
+ }
+
+ public void setAicVersionMax(String aicVersionMax) {
+ AicVersionMax = aicVersionMax;
+ }
+
+ public String getOrchestrationMode() {
+ return OrchestrationMode;
+ }
+
+ public void setOrchestrationMode(String orchestrationMode) {
+ OrchestrationMode = orchestrationMode;
+ }
+
+ public String getToscaNodeType() {
+ return ToscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ ToscaNodeType = toscaNodeType;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceInstance.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceInstance.java
index ac206d3dd0..05cad456d0 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceInstance.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceInstance.java
@@ -21,61 +21,71 @@
package org.onap.so.bpmn.servicedecomposition.modelinfo;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class ModelInfoServiceInstance extends ModelInfoMetadata implements Serializable {
- private static final long serialVersionUID = -1812787934683419141L;
-
- @JsonProperty("description")
- private String description;
- @JsonProperty("created")
- private String created;
- @JsonProperty("service-type")
- private String serviceType;
- @JsonProperty("service-role")
- private String serviceRole;
- @JsonProperty("environment-context")
- private String environmentContext;
- @JsonProperty("workload-context")
- private String workloadContext;
-
-
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- public String getCreated() {
- return created;
- }
- public void setCreated(String created) {
- this.created = created;
- }
- public String getServiceType() {
- return serviceType;
- }
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
- public String getServiceRole() {
- return serviceRole;
- }
- public void setServiceRole(String serviceRole) {
- this.serviceRole = serviceRole;
- }
- public String getEnvironmentContext() {
- return environmentContext;
- }
- public void setEnvironmentContext(String environmentContext) {
- this.environmentContext = environmentContext;
- }
- public String getWorkloadContext() {
- return workloadContext;
- }
- public void setWorkloadContext(String workloadContext) {
- this.workloadContext = workloadContext;
- }
+ private static final long serialVersionUID = -1812787934683419141L;
+
+ @JsonProperty("description")
+ private String description;
+ @JsonProperty("created")
+ private String created;
+ @JsonProperty("service-type")
+ private String serviceType;
+ @JsonProperty("service-role")
+ private String serviceRole;
+ @JsonProperty("environment-context")
+ private String environmentContext;
+ @JsonProperty("workload-context")
+ private String workloadContext;
+
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getCreated() {
+ return created;
+ }
+
+ public void setCreated(String created) {
+ this.created = created;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getServiceRole() {
+ return serviceRole;
+ }
+
+ public void setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ }
+
+ public String getEnvironmentContext() {
+ return environmentContext;
+ }
+
+ public void setEnvironmentContext(String environmentContext) {
+ this.environmentContext = environmentContext;
+ }
+
+ public String getWorkloadContext() {
+ return workloadContext;
+ }
+
+ public void setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoVfModule.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoVfModule.java
index 593f8c2532..e1b7a543d8 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoVfModule.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoVfModule.java
@@ -21,116 +21,140 @@
package org.onap.so.bpmn.servicedecomposition.modelinfo;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class ModelInfoVfModule implements Serializable {
- private static final long serialVersionUID = 636556989022688657L;
-
- @JsonProperty("model-customization-uuid")
- private String ModelCustomizationUUID;
- @JsonProperty("model-name")
- private String ModelName;
- @JsonProperty("model-uuid")
- private String ModelUUID;
- @JsonProperty("model-invariant-uuid")
- private String ModelInvariantUUID;
- @JsonProperty("model-version")
- private String ModelVersion;
- @JsonProperty("description")
- private String Description;
- @JsonProperty("is-base-boolean")
- private Boolean IsBaseBoolean;
- @JsonProperty("min-instances")
- private String MinInstances;
- @JsonProperty("max-instances")
- private String MaxInstances;
- @JsonProperty("availability-zone-count")
- private String AvailabilityZoneCount;
- @JsonProperty("label")
- private String Label;
- @JsonProperty("initial-count")
- private String InitialCount;
- @JsonProperty("created")
- private String Created;
-
- public String getModelCustomizationUUID() {
- return ModelCustomizationUUID;
- }
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- ModelCustomizationUUID = modelCustomizationUUID;
- }
- public String getModelName() {
- return ModelName;
- }
- public void setModelName(String modelName) {
- ModelName = modelName;
- }
- public String getModelUUID() {
- return ModelUUID;
- }
- public void setModelUUID(String modelUUID) {
- ModelUUID = modelUUID;
- }
- public String getModelInvariantUUID() {
- return ModelInvariantUUID;
- }
- public void setModelInvariantUUID(String modelInvariantUUID) {
- ModelInvariantUUID = modelInvariantUUID;
- }
- public String getModelVersion() {
- return ModelVersion;
- }
- public void setModelVersion(String modelVersion) {
- ModelVersion = modelVersion;
- }
- public String getDescription() {
- return Description;
- }
- public void setDescription(String description) {
- Description = description;
- }
- public Boolean getIsBaseBoolean() {
- return IsBaseBoolean;
- }
- public void setIsBaseBoolean(Boolean isBaseBoolean) {
- IsBaseBoolean = isBaseBoolean;
- }
- public String getMinInstances() {
- return MinInstances;
- }
- public void setMinInstances(String minInstances) {
- MinInstances = minInstances;
- }
- public String getMaxInstances() {
- return MaxInstances;
- }
- public void setMaxInstances(String maxInstances) {
- MaxInstances = maxInstances;
- }
- public String getAvailabilityZoneCount() {
- return AvailabilityZoneCount;
- }
- public void setAvailabilityZoneCount(String availabilityZoneCount) {
- AvailabilityZoneCount = availabilityZoneCount;
- }
- public String getLabel() {
- return Label;
- }
- public void setLabel(String label) {
- Label = label;
- }
- public String getInitialCount() {
- return InitialCount;
- }
- public void setInitialCount(String initialCount) {
- InitialCount = initialCount;
- }
- public String getCreated() {
- return Created;
- }
- public void setCreated(String created) {
- Created = created;
- }
+ private static final long serialVersionUID = 636556989022688657L;
+
+ @JsonProperty("model-customization-uuid")
+ private String ModelCustomizationUUID;
+ @JsonProperty("model-name")
+ private String ModelName;
+ @JsonProperty("model-uuid")
+ private String ModelUUID;
+ @JsonProperty("model-invariant-uuid")
+ private String ModelInvariantUUID;
+ @JsonProperty("model-version")
+ private String ModelVersion;
+ @JsonProperty("description")
+ private String Description;
+ @JsonProperty("is-base-boolean")
+ private Boolean IsBaseBoolean;
+ @JsonProperty("min-instances")
+ private String MinInstances;
+ @JsonProperty("max-instances")
+ private String MaxInstances;
+ @JsonProperty("availability-zone-count")
+ private String AvailabilityZoneCount;
+ @JsonProperty("label")
+ private String Label;
+ @JsonProperty("initial-count")
+ private String InitialCount;
+ @JsonProperty("created")
+ private String Created;
+
+ public String getModelCustomizationUUID() {
+ return ModelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ ModelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ public String getModelName() {
+ return ModelName;
+ }
+
+ public void setModelName(String modelName) {
+ ModelName = modelName;
+ }
+
+ public String getModelUUID() {
+ return ModelUUID;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ ModelUUID = modelUUID;
+ }
+
+ public String getModelInvariantUUID() {
+ return ModelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ ModelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getModelVersion() {
+ return ModelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ ModelVersion = modelVersion;
+ }
+
+ public String getDescription() {
+ return Description;
+ }
+
+ public void setDescription(String description) {
+ Description = description;
+ }
+
+ public Boolean getIsBaseBoolean() {
+ return IsBaseBoolean;
+ }
+
+ public void setIsBaseBoolean(Boolean isBaseBoolean) {
+ IsBaseBoolean = isBaseBoolean;
+ }
+
+ public String getMinInstances() {
+ return MinInstances;
+ }
+
+ public void setMinInstances(String minInstances) {
+ MinInstances = minInstances;
+ }
+
+ public String getMaxInstances() {
+ return MaxInstances;
+ }
+
+ public void setMaxInstances(String maxInstances) {
+ MaxInstances = maxInstances;
+ }
+
+ public String getAvailabilityZoneCount() {
+ return AvailabilityZoneCount;
+ }
+
+ public void setAvailabilityZoneCount(String availabilityZoneCount) {
+ AvailabilityZoneCount = availabilityZoneCount;
+ }
+
+ public String getLabel() {
+ return Label;
+ }
+
+ public void setLabel(String label) {
+ Label = label;
+ }
+
+ public String getInitialCount() {
+ return InitialCount;
+ }
+
+ public void setInitialCount(String initialCount) {
+ InitialCount = initialCount;
+ }
+
+ public String getCreated() {
+ return Created;
+ }
+
+ public void setCreated(String created) {
+ Created = created;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoVolumeGroup.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoVolumeGroup.java
index d3bf99ccb8..bb493f5aa9 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoVolumeGroup.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoVolumeGroup.java
@@ -21,10 +21,9 @@
package org.onap.so.bpmn.servicedecomposition.modelinfo;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class ModelInfoVolumeGroup extends ModelInfoVfModule implements Serializable {
- private static final long serialVersionUID = -1157856848495642223L;
+ private static final long serialVersionUID = -1157856848495642223L;
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/AssignFlows.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/AssignFlows.java
index ac96aceec3..7ca6076b21 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/AssignFlows.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/AssignFlows.java
@@ -22,23 +22,19 @@ package org.onap.so.bpmn.servicedecomposition.tasks;
public enum AssignFlows {
- SERVICE_INSTANCE("AssignServiceInstanceBB"),
- VNF("AssignVnfBB"),
- VF_MODULE("AssignVfModuleBB"),
- NETWORK_A_LA_CARTE("AssignNetwork1802BB"),
- NETWORK_MACRO("AssignNetworkBB"),
- VOLUME_GROUP("AssignVolumeGroupBB"),
- NETWORK_COLLECTION("CreateNetworkCollectionBB"),
- FABRIC_CONFIGURATION("AssignFabricConfigurationBB");
-
- private final String flowName;
-
- private AssignFlows(String flowName) {
- this.flowName = flowName;
- }
-
- @Override
- public String toString() {
- return this.flowName;
- }
+ SERVICE_INSTANCE("AssignServiceInstanceBB"), VNF("AssignVnfBB"), VF_MODULE("AssignVfModuleBB"), NETWORK_A_LA_CARTE(
+ "AssignNetwork1802BB"), NETWORK_MACRO("AssignNetworkBB"), VOLUME_GROUP(
+ "AssignVolumeGroupBB"), NETWORK_COLLECTION(
+ "CreateNetworkCollectionBB"), FABRIC_CONFIGURATION("AssignFabricConfigurationBB");
+
+ private final String flowName;
+
+ private AssignFlows(String flowName) {
+ this.flowName = flowName;
+ }
+
+ @Override
+ public String toString() {
+ return this.flowName;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java
index f5b77781a4..de77ca66e7 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java
@@ -28,7 +28,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.javatuples.Pair;
@@ -96,1715 +95,1760 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
@Component("BBInputSetup")
public class BBInputSetup implements JavaDelegate {
- private static final Logger logger = LoggerFactory.getLogger(BBInputSetup.class);
- private static final String FLOW_VAR_NAME = "flowToBeCalled";
- private static final String LOOKUP_KEY_MAP_VAR_NAME = "lookupKeyMap";
- private static final String GBB_INPUT_VAR_NAME = "gBBInput";
- private static final String EXECUTE_BB_VAR_NAME = "buildingBlock";
- private static final String VOLUME_GROUP = "VolumeGroup";
- private static final String VF_MODULE = "VfModule";
- private static final String NETWORK = "Network";
- private static final String VNF = "Vnf";
- private static final String NETWORK_COLLECTION = "NetworkCollection";
- private static final String PREPROV = "PREPROV";
-
- @Autowired
- private BBInputSetupUtils bbInputSetupUtils;
-
- @Autowired
- private BBInputSetupMapperLayer mapperLayer;
-
- @Autowired
- private CloudInfoFromAAI cloudInfoFromAAI;
-
- @Autowired
- private ExceptionBuilder exceptionUtil;
-
- private ObjectMapper mapper = new ObjectMapper();
-
- public BBInputSetupUtils getBbInputSetupUtils() {
- return bbInputSetupUtils;
- }
-
- public void setCloudInfoFromAAI(CloudInfoFromAAI cloudInfoFromAAI) {
- this.cloudInfoFromAAI = cloudInfoFromAAI;
- }
-
- public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) {
- this.bbInputSetupUtils = bbInputSetupUtils;
- }
-
- public BBInputSetupMapperLayer getMapperLayer() {
- return mapperLayer;
- }
-
- public void setMapperLayer(BBInputSetupMapperLayer mapperLayer) {
- this.mapperLayer = mapperLayer;
- }
-
- @Override
- public void execute(DelegateExecution execution) throws Exception {
- try {
- GeneralBuildingBlock outputBB = null;
- ExecuteBuildingBlock executeBB = this.getExecuteBBFromExecution(execution);
- String resourceId = executeBB.getResourceId();
- String requestAction = executeBB.getRequestAction();
- String vnfType = executeBB.getVnfType();
- boolean aLaCarte = Boolean.TRUE.equals(executeBB.isaLaCarte());
- boolean homing = Boolean.TRUE.equals(executeBB.isHoming());
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- outputBB = this.getGBB(executeBB, lookupKeyMap, requestAction, aLaCarte, resourceId, vnfType);
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.INDENT_OUTPUT);
- logger.debug("GeneralBB: " + mapper.writeValueAsString(outputBB));
-
- setHomingFlag(outputBB, homing, lookupKeyMap);
-
- execution.setVariable(FLOW_VAR_NAME, executeBB.getBuildingBlock().getBpmnFlowName());
- execution.setVariable(GBB_INPUT_VAR_NAME, outputBB);
- execution.setVariable(LOOKUP_KEY_MAP_VAR_NAME, lookupKeyMap);
-
- BuildingBlockExecution gBuildingBlockExecution = new DelegateExecutionImpl(execution);
- execution.setVariable("gBuildingBlockExecution", gBuildingBlockExecution);
- execution.setVariable("RetryCount", 1);
- execution.setVariable("handlingCode", "Success");
- } catch (Exception e) {
- logger.error("Exception occurred", e);
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e.getMessage());
- }
- }
-
- protected void setHomingFlag(GeneralBuildingBlock outputBB, boolean homing, Map<ResourceKey, String> lookupKeyMap) {
-
- if (lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID) != null && homing && outputBB != null) {
- for (GenericVnf vnf : outputBB.getCustomer().getServiceSubscription().getServiceInstances().get(0).getVnfs()) {
- if (vnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
- vnf.setCallHoming(homing);
- }
- }
- }
- }
-
- protected ExecuteBuildingBlock getExecuteBBFromExecution(DelegateExecution execution) {
- return (ExecuteBuildingBlock) execution.getVariable(EXECUTE_BB_VAR_NAME);
- }
-
- protected GeneralBuildingBlock getGBB(ExecuteBuildingBlock executeBB, Map<ResourceKey, String> lookupKeyMap,
- String requestAction, boolean aLaCarte, String resourceId, String vnfType) throws Exception {
- String requestId = executeBB.getRequestId();
- this.populateLookupKeyMapWithIds(executeBB.getWorkflowResourceIds(), lookupKeyMap);
- RequestDetails requestDetails = executeBB.getRequestDetails();
- if(requestDetails == null) {
- requestDetails = bbInputSetupUtils.getRequestDetails(requestId);
- }
- if (requestDetails.getModelInfo() == null) {
- return this.getGBBCM(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId);
- }
- else {
- ModelType modelType = requestDetails.getModelInfo().getModelType();
- if (aLaCarte && modelType.equals(ModelType.service)) {
- return this.getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId);
- } else if (aLaCarte && !modelType.equals(ModelType.service)) {
- return this.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId,
- vnfType);
- } else {
- return this.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- }
- }
- }
-
- protected void populateLookupKeyMapWithIds(WorkflowResourceIds workflowResourceIds,
- Map<ResourceKey, String> lookupKeyMap) {
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, workflowResourceIds.getServiceInstanceId());
- lookupKeyMap.put(ResourceKey.NETWORK_ID, workflowResourceIds.getNetworkId());
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, workflowResourceIds.getVnfId());
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, workflowResourceIds.getVfModuleId());
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, workflowResourceIds.getVolumeGroupId());
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, workflowResourceIds.getConfigurationId());
- lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, workflowResourceIds.getInstanceGroupId());
- }
-
- protected GeneralBuildingBlock getGBBALaCarteNonService(ExecuteBuildingBlock executeBB,
- RequestDetails requestDetails, Map<ResourceKey, String> lookupKeyMap, String requestAction,
- String resourceId, String vnfType) throws Exception {
- String bbName = executeBB.getBuildingBlock().getBpmnFlowName();
- String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID);
- org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = null;
- if (serviceInstanceId != null) {
- aaiServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
- }
- Service service = null;
- if (aaiServiceInstance != null) {
- service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
- }
- if (aaiServiceInstance != null && service != null) {
- ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance);
- serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service));
- this.populateObjectsOnAssignAndCreateFlows(requestDetails, service, bbName, serviceInstance, lookupKeyMap,
- resourceId, vnfType, executeBB.getBuildingBlock().getKey(), executeBB.getConfigurationResourceKeys());
- return this.populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, null);
- } else {
- logger.debug("Related Service Instance from AAI: {}", aaiServiceInstance);
- logger.debug("Related Service Instance Model Info from AAI: {}", service);
- throw new Exception("Could not find relevant information for related Service Instance");
- }
- }
-
- protected GeneralBuildingBlock getGBBCM(ExecuteBuildingBlock executeBB,
- RequestDetails requestDetails, Map<ResourceKey, String> lookupKeyMap, String requestAction,
- String resourceId) throws Exception {
- ServiceInstance serviceInstance = new ServiceInstance();
- String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID);
- serviceInstance.setServiceInstanceId(serviceInstanceId);
- Customer customer = new Customer();
- List<GenericVnf> genericVnfs = serviceInstance.getVnfs();
-
- String vnfId = lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID);
- if(vnfId != null) {
- org.onap.aai.domain.yang.GenericVnf aaiGenericVnf = bbInputSetupUtils.getAAIGenericVnf(vnfId);
- GenericVnf genericVnf = this.mapperLayer.mapAAIGenericVnfIntoGenericVnf(aaiGenericVnf);
- genericVnfs.add(genericVnf);
- }
-
- String instanceGroupId = lookupKeyMap.get(ResourceKey.INSTANCE_GROUP_ID);
- if(instanceGroupId != null) {
- org.onap.aai.domain.yang.InstanceGroup aaiInstancegroup = bbInputSetupUtils.getAAIInstanceGroup(instanceGroupId);
- InstanceGroup instanceGroup = this.mapperLayer.mapAAIInstanceGroupIntoInstanceGroup(aaiInstancegroup);
- instanceGroup.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
-
- if(serviceInstanceId == null) {
- Optional<org.onap.aai.domain.yang.ServiceInstance> aaiServiceInstanceOpt = bbInputSetupUtils.getRelatedServiceInstanceFromInstanceGroup(instanceGroupId);
- if(aaiServiceInstanceOpt.isPresent()) {
- org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = aaiServiceInstanceOpt.get();
- serviceInstance = this.mapperLayer.mapAAIServiceInstanceIntoServiceInstance(aaiServiceInstance);
- WorkflowResourceIds workflowResourceIds = executeBB.getWorkflowResourceIds();
- workflowResourceIds.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, workflowResourceIds.getServiceInstanceId());
- } else {
- throw new NoServiceInstanceFoundException("Related ServiceInstance not found in A&AI.");
- }
- }
- RelatedInstanceList[] relatedInstanceList = requestDetails.getRelatedInstanceList();
- if (relatedInstanceList != null) {
- for (RelatedInstanceList relatedInstList : relatedInstanceList) {
- RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
- if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
- org.onap.aai.domain.yang.GenericVnf aaiVnf = bbInputSetupUtils.getAAIGenericVnf(relatedInstance.getInstanceId());
- GenericVnf vnf = this.mapperLayer.mapAAIGenericVnfIntoGenericVnf(aaiVnf);
- instanceGroup.getVnfs().add(vnf);
- }
- }
- }
-
- serviceInstance.getInstanceGroups().add(instanceGroup);
- customer.setServiceSubscription(new ServiceSubscription());
- }
- return this.populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, customer);
- }
-
- protected void populateObjectsOnAssignAndCreateFlows(RequestDetails requestDetails, Service service, String bbName,
- ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId, String vnfType,
- String configurationKey, ConfigurationResourceKeys configurationResourceKeys)
- throws Exception {
- ModelInfo modelInfo = requestDetails.getModelInfo();
- String instanceName = requestDetails.getRequestInfo().getInstanceName();
- String productFamilyId = requestDetails.getRequestInfo().getProductFamilyId();
- ModelType modelType = modelInfo.getModelType();
- RelatedInstanceList[] relatedInstanceList = requestDetails.getRelatedInstanceList();
-
- org.onap.so.serviceinstancebeans.Platform platform = requestDetails.getPlatform();
- org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness = requestDetails.getLineOfBusiness();
-
- if (modelType.equals(ModelType.network)) {
- lookupKeyMap.put(ResourceKey.NETWORK_ID, resourceId);
- this.populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, null);
- } else if (modelType.equals(ModelType.vnf)) {
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, resourceId);
- this.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance,
- lookupKeyMap, relatedInstanceList, resourceId, vnfType, null, productFamilyId);
- } else if (modelType.equals(ModelType.volumeGroup)) {
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, resourceId);
- this.populateVolumeGroup(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
- relatedInstanceList, instanceName, vnfType, null);
- } else if (modelType.equals(ModelType.vfModule)) {
- if(bbName.contains("Configuration")) {
- String configurationId = lookupKeyMap.get(ResourceKey.CONFIGURATION_ID);
- ModelInfo configurationModelInfo = new ModelInfo();
- configurationModelInfo.setModelCustomizationUuid(configurationKey);
- populateConfiguration(configurationModelInfo, service, bbName, serviceInstance,
- lookupKeyMap, configurationId, instanceName, configurationResourceKeys);
- } else {
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, resourceId);
- this.populateVfModule(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
- relatedInstanceList, instanceName, null, requestDetails.getCloudConfiguration());
- }
- } else if (modelType.equals(ModelType.instanceGroup)) {
- lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, resourceId);
- this.populateInstanceGroup(modelInfo, service, serviceInstance, resourceId, instanceName);
- } else {
- return;
- }
- }
-
- protected void populateInstanceGroup(ModelInfo modelInfo, Service service, ServiceInstance serviceInstance, String instanceGroupId, String instanceName) {
- InstanceGroup instanceGroup = new InstanceGroup();
- instanceGroup.setId(instanceGroupId);
- instanceGroup.setInstanceGroupName(instanceName);
- mapCatalogInstanceGroup(instanceGroup, modelInfo, service);
- serviceInstance.getInstanceGroups().add(instanceGroup);
- }
-
- protected void mapCatalogInstanceGroup(InstanceGroup instanceGroup, ModelInfo modelInfo, Service service) {
- // @TODO: this will populate the instanceGroup model info.
- // Dependent on MSO-5821 653458 US - MSO - Enhance Catalog DB Schema & Adapter to support VNF Groups
- }
-
- protected void populateConfiguration(ModelInfo modelInfo, Service service, String bbName,
- ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId, String instanceName, ConfigurationResourceKeys configurationResourceKeys) {
- Configuration configuration = null;
- for (Configuration configurationTemp : serviceInstance.getConfigurations()) {
- if (lookupKeyMap.get(ResourceKey.CONFIGURATION_ID) != null
- && configurationTemp.getConfigurationId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.CONFIGURATION_ID))) {
- configuration = configurationTemp;
- org.onap.aai.domain.yang.Configuration aaiConfiguration = bbInputSetupUtils.getAAIConfiguration(configuration.getConfigurationId());
- if(aaiConfiguration!=null){
- modelInfo.setModelCustomizationUuid(aaiConfiguration.getModelCustomizationId());
- }
- }
- }
- if (configuration == null && bbName.equalsIgnoreCase(AssignFlows.FABRIC_CONFIGURATION.toString())) {
- configuration = this.createConfiguration(lookupKeyMap, instanceName, resourceId);
- serviceInstance.getConfigurations().add(configuration);
- }
- if(configuration != null) {
- Vnfc vnfc = getVnfcToConfiguration(configurationResourceKeys.getVnfcName());
- configuration.setVnfc(vnfc);
- this.mapCatalogConfiguration(configuration, modelInfo, service, configurationResourceKeys);
- }
- }
-
- protected Vnfc getVnfcToConfiguration(String vnfcName) {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VNFC, vnfcName);
- Optional<org.onap.aai.domain.yang.Vnfc> vnfcOp = bbInputSetupUtils.getAAIResourceDepthOne(uri).asBean(org.onap.aai.domain.yang.Vnfc.class);
- if(vnfcOp.isPresent()) {
- org.onap.aai.domain.yang.Vnfc vnfcAAI = vnfcOp.get();
- return this.mapperLayer.mapAAIVnfc(vnfcAAI);
- } else {
- return null;
- }
- }
-
- protected Configuration createConfiguration(Map<ResourceKey, String> lookupKeyMap,
- String instanceName, String resourceId) {
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, resourceId);
- Configuration configuration = new Configuration();
- configuration.setConfigurationId(resourceId);
- configuration.setConfigurationName(instanceName);
- configuration.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- return configuration;
- }
-
- protected void mapCatalogConfiguration(Configuration configuration, ModelInfo modelInfo, Service service, ConfigurationResourceKeys configurationResourceKeys) {
- ConfigurationResourceCustomization configurationResourceCustomization = findConfigurationResourceCustomization(modelInfo, service);
- CvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization =
- findVnfVfmoduleCvnfcConfigurationCustomization(service.getModelUUID(),configurationResourceKeys.getVfModuleCustomizationUUID(),
- configurationResourceKeys.getVnfResourceCustomizationUUID(), configurationResourceKeys.getCvnfcCustomizationUUID(), configurationResourceCustomization);
- if (configurationResourceCustomization != null && vnfVfmoduleCvnfcConfigurationCustomization != null) {
- configuration.setModelInfoConfiguration(this.mapperLayer.mapCatalogConfigurationToConfiguration(configurationResourceCustomization
- , vnfVfmoduleCvnfcConfigurationCustomization));
- } else {
- logger.debug("for Fabric configuration mapping by VF MODULE CUST UUID: " + configurationResourceKeys.getVfModuleCustomizationUUID());
- vnfVfmoduleCvnfcConfigurationCustomization = findVnfVfmoduleCvnfcConfigurationCustomization(service.getModelUUID(),configurationResourceKeys.getVnfResourceCustomizationUUID(),
- configurationResourceKeys.getVfModuleCustomizationUUID(), configurationResourceKeys.getCvnfcCustomizationUUID());
- if (vnfVfmoduleCvnfcConfigurationCustomization != null){
- configuration.setModelInfoConfiguration(this.mapperLayer.mapCatalogConfigurationToConfiguration(vnfVfmoduleCvnfcConfigurationCustomization));
- }
- }
- }
-
- protected CvnfcConfigurationCustomization findVnfVfmoduleCvnfcConfigurationCustomization(String serviceModelUUID, String vfModuleCustomizationUUID,
- String vnfResourceCustomizationUUID, String cvnfcCustomizationUUID, ConfigurationResourceCustomization configurationResourceCustomization) {
- return bbInputSetupUtils.getCvnfcConfigurationCustomization(serviceModelUUID, vnfResourceCustomizationUUID, vfModuleCustomizationUUID, cvnfcCustomizationUUID);
- }
-
- protected ConfigurationResourceCustomization findConfigurationResourceCustomization(ModelInfo modelInfo, Service service) {
- for (ConfigurationResourceCustomization resourceCust : service.getConfigurationCustomizations()) {
- if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(modelInfo.getModelCustomizationUuid())) {
- return resourceCust;
- }
- }
- return null;
- }
-
- protected CvnfcConfigurationCustomization findVnfVfmoduleCvnfcConfigurationCustomization(String serviceModelUUID, String vnfResourceCustomizationUUID,
- String vfModuleCustomizationUUID, String cvnfcCustomizationUUID) {
- return bbInputSetupUtils.getCvnfcConfigurationCustomization(serviceModelUUID, vnfResourceCustomizationUUID, vfModuleCustomizationUUID, cvnfcCustomizationUUID);
- }
-
- protected void populateVfModule(ModelInfo modelInfo, Service service, String bbName,
- ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId,
- RelatedInstanceList[] relatedInstanceList, String instanceName, List<Map<String, String>> instanceParams, CloudConfiguration cloudConfiguration) throws Exception {
- String vnfModelCustomizationUUID = null;
- if (relatedInstanceList != null) {
- for (RelatedInstanceList relatedInstList : relatedInstanceList) {
- RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
- if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
- vnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId();
- }
- if (relatedInstance.getModelInfo().getModelType().equals(ModelType.volumeGroup)) {
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, relatedInstance.getInstanceId());
- }
- }
- }
- GenericVnf vnf = null;
- for (GenericVnf tempVnf : serviceInstance.getVnfs()) {
- if (tempVnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
- vnf = tempVnf;
- vnfModelCustomizationUUID = this.bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId())
- .getModelCustomizationId();
- ModelInfo vnfModelInfo = new ModelInfo();
- vnfModelInfo.setModelCustomizationUuid(vnfModelCustomizationUUID);
- this.mapCatalogVnf(tempVnf, vnfModelInfo, service);
- Optional<String> volumeGroupIdOp = getVolumeGroupIdRelatedToVfModule(tempVnf, modelInfo, cloudConfiguration.getCloudOwner(),
- cloudConfiguration.getLcpCloudRegionId(), lookupKeyMap);
- if(volumeGroupIdOp.isPresent()) {
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupIdOp.get());
- }
- break;
- }
- }
- if (vnf != null) {
- VfModule vfModule = null;
- for (VfModule vfModuleTemp : vnf.getVfModules()) {
- if (lookupKeyMap.get(ResourceKey.VF_MODULE_ID) != null
- && vfModuleTemp.getVfModuleId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.VF_MODULE_ID))) {
- vfModule = vfModuleTemp;
- }
- String vfModuleCustId = bbInputSetupUtils.getAAIVfModule(vnf.getVnfId(), vfModuleTemp.getVfModuleId()).getModelCustomizationId();
- ModelInfo modelInfoVfModule = new ModelInfo();
- modelInfoVfModule.setModelCustomizationId(vfModuleCustId);
- mapCatalogVfModule(vfModuleTemp, modelInfoVfModule, service, vnfModelCustomizationUUID);
- }
- if (vfModule == null && bbName.equalsIgnoreCase(AssignFlows.VF_MODULE.toString())) {
- vfModule = createVfModule(lookupKeyMap,
- resourceId, instanceName, instanceParams);
- vnf.getVfModules().add(vfModule);
- mapCatalogVfModule(vfModule, modelInfo, service, vnfModelCustomizationUUID);
- }
- } else {
- logger.debug("Related VNF instance Id not found: {}", lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID));
- throw new Exception("Could not find relevant information for related VNF");
- }
- }
-
- protected Optional<String> getVolumeGroupIdRelatedToVfModule(GenericVnf vnf, ModelInfo modelInfo,
- String cloudOwner, String cloudRegionId, Map<ResourceKey, String> lookupKeyMap) {
- if (lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID) == null) {
- for(VolumeGroup volumeGroup : vnf.getVolumeGroups()) {
- String volumeGroupCustId =
- bbInputSetupUtils.getAAIVolumeGroup(cloudOwner,
- cloudRegionId, volumeGroup.getVolumeGroupId()).getModelCustomizationId();
- if(modelInfo.getModelCustomizationId().equalsIgnoreCase(volumeGroupCustId)) {
- return Optional.of(volumeGroup.getVolumeGroupId());
- }
- }
- }
- return Optional.empty();
- }
-
- protected void mapCatalogVfModule(VfModule vfModule, ModelInfo modelInfo, Service service,
- String vnfModelCustomizationUUID) {
- if(modelInfo.getModelCustomizationUuid() != null) {
- modelInfo.setModelCustomizationId(modelInfo.getModelCustomizationUuid());
- }
- VnfResourceCustomization vnfResourceCustomization = null;
- for (VnfResourceCustomization resourceCust : service.getVnfCustomizations()) {
- if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(vnfModelCustomizationUUID)) {
- vnfResourceCustomization = resourceCust;
- break;
- }
- }
- if (vnfResourceCustomization != null) {
- VfModuleCustomization vfResourceCustomization = vnfResourceCustomization.getVfModuleCustomizations()
- .stream() // Convert to steam
- .filter(x -> modelInfo.getModelCustomizationId().equalsIgnoreCase(x.getModelCustomizationUUID()))// find
- // what
- // we
- // want
- .findAny() // If 'findAny' then return found
- .orElse(null);
- if (vfResourceCustomization != null) {
- vfModule.setModelInfoVfModule(this.mapperLayer.mapCatalogVfModuleToVfModule(vfResourceCustomization));
- }
- }
- }
-
- protected VfModule createVfModule(Map<ResourceKey, String> lookupKeyMap, String vfModuleId, String instanceName, List<Map<String, String>> instanceParams) {
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, vfModuleId);
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId(vfModuleId);
- vfModule.setVfModuleName(instanceName);
- vfModule.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- if(instanceParams != null) {
- for(Map<String, String> params : instanceParams) {
- vfModule.getCloudParams().putAll(params);
- }
- }
- return vfModule;
- }
-
- protected void populateVolumeGroup(ModelInfo modelInfo, Service service, String bbName,
- ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId,
- RelatedInstanceList[] relatedInstanceList, String instanceName, String vnfType, List<Map<String, String>> instanceParams) throws Exception {
- VolumeGroup volumeGroup = null;
- GenericVnf vnf = null;
- String vnfModelCustomizationUUID = null;
- String generatedVnfType = vnfType;
- if (generatedVnfType == null || generatedVnfType.isEmpty()) {
- generatedVnfType = service.getModelName() + "/" + modelInfo.getModelCustomizationName();
- }
- if (relatedInstanceList != null) {
- for (RelatedInstanceList relatedInstList : relatedInstanceList) {
- RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
- if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
- vnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationUuid();
- break;
- }
- }
- }
- for (GenericVnf tempVnf : serviceInstance.getVnfs()) {
- if (tempVnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
- vnf = tempVnf;
- vnfModelCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId())
- .getModelCustomizationId();
- ModelInfo vnfModelInfo = new ModelInfo();
- vnfModelInfo.setModelCustomizationUuid(vnfModelCustomizationUUID);
- mapCatalogVnf(tempVnf, vnfModelInfo, service);
- break;
- }
- }
- if (vnf != null && vnfModelCustomizationUUID != null) {
- for (VolumeGroup volumeGroupTemp : vnf.getVolumeGroups()) {
- if (lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID) != null && volumeGroupTemp.getVolumeGroupId()
- .equalsIgnoreCase(lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID))) {
- volumeGroup = volumeGroupTemp;
- break;
- }
- }
- if (volumeGroup == null && bbName.equalsIgnoreCase(AssignFlows.VOLUME_GROUP.toString())) {
- volumeGroup = createVolumeGroup(lookupKeyMap, resourceId, instanceName, generatedVnfType, instanceParams);
- vnf.getVolumeGroups().add(volumeGroup);
- }
- if(volumeGroup != null) {
- mapCatalogVolumeGroup(volumeGroup, modelInfo, service, vnfModelCustomizationUUID);
- }
- } else {
- logger.debug("Related VNF instance Id not found: {}", lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID));
- throw new Exception("Could not find relevant information for related VNF");
- }
- }
-
- protected VolumeGroup createVolumeGroup(Map<ResourceKey, String> lookupKeyMap, String volumeGroupId, String instanceName, String vnfType, List<Map<String, String>> instanceParams) {
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupId);
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId(volumeGroupId);
- volumeGroup.setVolumeGroupName(instanceName);
- volumeGroup.setVnfType(vnfType);
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- if(instanceParams != null) {
- for(Map<String, String> params : instanceParams) {
- volumeGroup.getCloudParams().putAll(params);
- }
- }
- return volumeGroup;
- }
-
- protected void mapCatalogVolumeGroup(VolumeGroup volumeGroup, ModelInfo modelInfo, Service service,
- String vnfModelCustomizationUUID) {
- VfModuleCustomization vfResourceCustomization = getVfResourceCustomization(modelInfo, service,
- vnfModelCustomizationUUID);
- if (vfResourceCustomization != null) {
- volumeGroup.setModelInfoVfModule(this.mapperLayer.mapCatalogVfModuleToVfModule(vfResourceCustomization));
- }
- }
-
- protected VfModuleCustomization getVfResourceCustomization(ModelInfo modelInfo, Service service,
- String vnfModelCustomizationUUID) {
- VnfResourceCustomization vnfResourceCustomization = null;
- for (VnfResourceCustomization resourceCust : service.getVnfCustomizations()) {
- if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(vnfModelCustomizationUUID)) {
- vnfResourceCustomization = resourceCust;
- break;
- }
- }
- if (vnfResourceCustomization != null) {
- for (VfModuleCustomization vfResourceCust : vnfResourceCustomization.getVfModuleCustomizations()) {
- if (vfResourceCust.getModelCustomizationUUID()
- .equalsIgnoreCase(modelInfo.getModelCustomizationUuid())) {
- return vfResourceCust;
- }
- }
-
- }
- return null;
- }
-
- protected void populateGenericVnf(ModelInfo modelInfo, String instanceName,
- org.onap.so.serviceinstancebeans.Platform platform,
- org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness, Service service, String bbName,
- ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap,
- RelatedInstanceList[] relatedInstanceList, String resourceId, String vnfType, List<Map<String, String>> instanceParams,
- String productFamilyId) {
- GenericVnf vnf = null;
- ModelInfo instanceGroupModelInfo = null;
- String instanceGroupId = null;
- String generatedVnfType = vnfType;
- if (generatedVnfType == null || generatedVnfType.isEmpty()) {
- generatedVnfType = service.getModelName() + "/" + modelInfo.getModelCustomizationName();
- }
- if (relatedInstanceList != null) {
- for (RelatedInstanceList relatedInstList : relatedInstanceList) {
- RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
- if (relatedInstance.getModelInfo().getModelType().equals(ModelType.networkInstanceGroup)) {
- instanceGroupModelInfo = relatedInstance.getModelInfo();
- instanceGroupId = relatedInstance.getInstanceId();
- }
- }
- }
- for (GenericVnf vnfTemp : serviceInstance.getVnfs()) {
- if (lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID) != null
- && vnfTemp.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
- String vnfModelCustId = bbInputSetupUtils.getAAIGenericVnf(vnfTemp.getVnfId()).getModelCustomizationId();
- modelInfo.setModelCustomizationUuid(vnfModelCustId);
- vnf = vnfTemp;
- break;
- }
- }
- if (vnf == null && bbName.equalsIgnoreCase(AssignFlows.VNF.toString())) {
- vnf = createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness,
- resourceId, generatedVnfType, instanceParams, productFamilyId);
- serviceInstance.getVnfs().add(vnf);
- mapVnfcCollectionInstanceGroup(vnf, modelInfo, service);
- }
- if(vnf != null) {
- mapCatalogVnf(vnf, modelInfo, service);
- if (instanceGroupId != null && instanceGroupModelInfo != null
- && instanceGroupModelInfo.getModelType().equals(ModelType.networkInstanceGroup)
- && !instanceGroupInList(vnf, instanceGroupId)) {
- mapNetworkCollectionInstanceGroup(vnf, instanceGroupId);
- }
- }
- }
-
- protected boolean instanceGroupInList(GenericVnf vnf, String instanceGroupId) {
- for(InstanceGroup instanceGroup : vnf.getInstanceGroups()) {
- if(instanceGroup.getId() != null && instanceGroup.getId().equalsIgnoreCase(instanceGroupId)) {
- return true;
- }
- }
- return false;
- }
-
- protected void mapVnfcCollectionInstanceGroup(GenericVnf genericVnf, ModelInfo modelInfo, Service service) {
- VnfResourceCustomization vnfResourceCustomization = getVnfResourceCustomizationFromService(modelInfo, service);
- if(vnfResourceCustomization != null) {
- List<VnfcInstanceGroupCustomization> vnfcInstanceGroups = vnfResourceCustomization
- .getVnfcInstanceGroupCustomizations();
- for (VnfcInstanceGroupCustomization vnfcInstanceGroupCust : vnfcInstanceGroups) {
- InstanceGroup instanceGroup = this.createInstanceGroup();
- org.onap.so.db.catalog.beans.InstanceGroup catalogInstanceGroup = bbInputSetupUtils.getCatalogInstanceGroup(vnfcInstanceGroupCust.getInstanceGroup().getModelUUID());
- instanceGroup.setModelInfoInstanceGroup(this.mapperLayer
- .mapCatalogInstanceGroupToInstanceGroup(null, catalogInstanceGroup));
- instanceGroup.getModelInfoInstanceGroup().setFunction(vnfcInstanceGroupCust.getFunction());
- instanceGroup.setDescription(vnfcInstanceGroupCust.getDescription());
- genericVnf.getInstanceGroups().add(instanceGroup);
- }
- }
- }
-
- protected void mapNetworkCollectionInstanceGroup(GenericVnf genericVnf, String instanceGroupId) {
- org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = bbInputSetupUtils
- .getAAIInstanceGroup(instanceGroupId);
- InstanceGroup instanceGroup = this.mapperLayer.mapAAIInstanceGroupIntoInstanceGroup(aaiInstanceGroup);
- instanceGroup.setModelInfoInstanceGroup(this.mapperLayer.mapCatalogInstanceGroupToInstanceGroup(
- null, this.bbInputSetupUtils.getCatalogInstanceGroup(aaiInstanceGroup.getModelVersionId())));
- genericVnf.getInstanceGroups().add(instanceGroup);
- }
-
- protected GenericVnf createGenericVnf(Map<ResourceKey, String> lookupKeyMap, String instanceName,
- org.onap.so.serviceinstancebeans.Platform platform,
- org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness, String vnfId, String vnfType, List<Map<String, String>> instanceParams,
- String productFamilyId) {
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnfId);
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId(vnfId);
- genericVnf.setVnfName(instanceName);
- genericVnf.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- genericVnf.setVnfType(vnfType);
- genericVnf.setProvStatus(PREPROV);
- genericVnf.setServiceId(productFamilyId);
- if (platform != null) {
- genericVnf.setPlatform(this.mapperLayer.mapRequestPlatform(platform));
- }
- if (lineOfBusiness != null) {
- genericVnf.setLineOfBusiness(this.mapperLayer.mapRequestLineOfBusiness(lineOfBusiness));
- }
- if(instanceParams != null) {
- for(Map<String, String> params : instanceParams) {
- genericVnf.getCloudParams().putAll(params);
- }
- }
- return genericVnf;
- }
-
- protected void mapCatalogVnf(GenericVnf genericVnf, ModelInfo modelInfo, Service service) {
- VnfResourceCustomization vnfResourceCustomization = getVnfResourceCustomizationFromService(modelInfo, service);
- if (vnfResourceCustomization != null) {
- genericVnf.setModelInfoGenericVnf(this.mapperLayer.mapCatalogVnfToVnf(vnfResourceCustomization));
- }
- }
-
- protected VnfResourceCustomization getVnfResourceCustomizationFromService(ModelInfo modelInfo, Service service) {
- VnfResourceCustomization vnfResourceCustomization = null;
- for (VnfResourceCustomization resourceCust : service.getVnfCustomizations()) {
- if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(modelInfo.getModelCustomizationUuid())) {
- vnfResourceCustomization = resourceCust;
- break;
- }
- }
- return vnfResourceCustomization;
- }
-
- protected void populateL3Network(String instanceName, ModelInfo modelInfo, Service service, String bbName,
- ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId, List<Map<String, String>> instanceParams) {
- L3Network network = null;
- for (L3Network networkTemp : serviceInstance.getNetworks()) {
- if (lookupKeyMap.get(ResourceKey.NETWORK_ID) != null
- && networkTemp.getNetworkId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.NETWORK_ID))) {
- network = networkTemp;
- break;
- }
- }
- if (network == null
- && (bbName.equalsIgnoreCase(AssignFlows.NETWORK_A_LA_CARTE.toString())
- || bbName.equalsIgnoreCase(AssignFlows.NETWORK_MACRO.toString()))) {
- network = createNetwork(lookupKeyMap, instanceName, resourceId, instanceParams);
- serviceInstance.getNetworks().add(network);
- }
- if(network != null) {
- mapCatalogNetwork(network, modelInfo, service);
- }
- }
-
- protected L3Network createNetwork(Map<ResourceKey, String> lookupKeyMap, String instanceName,
- String networkId, List<Map<String, String>> instanceParams) {
- lookupKeyMap.put(ResourceKey.NETWORK_ID, networkId);
- L3Network network = new L3Network();
- network.setNetworkId(networkId);
- network.setNetworkName(instanceName);
- network.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- if(instanceParams != null) {
- for(Map<String, String> params : instanceParams) {
- network.getCloudParams().putAll(params);
- }
- }
- return network;
- }
-
- protected void mapCatalogNetwork(L3Network network, ModelInfo modelInfo, Service service) {
- NetworkResourceCustomization networkResourceCustomization = null;
- for (NetworkResourceCustomization resourceCust : service.getNetworkCustomizations()) {
- if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(modelInfo.getModelCustomizationUuid())) {
- networkResourceCustomization = resourceCust;
- break;
- }
- }
- if (networkResourceCustomization != null) {
- network.setModelInfoNetwork(this.mapperLayer.mapCatalogNetworkToNetwork(networkResourceCustomization));
- }
- }
-
- protected GeneralBuildingBlock getGBBALaCarteService(ExecuteBuildingBlock executeBB, RequestDetails requestDetails,
- Map<ResourceKey, String> lookupKeyMap, String requestAction, String resourceId) throws Exception {
- Customer customer = getCustomerAndServiceSubscription(requestDetails, resourceId);
- if (customer != null) {
- Project project = null;
- OwningEntity owningEntity = null;
-
- if (requestDetails.getProject() != null)
- project = mapperLayer.mapRequestProject(requestDetails.getProject());
- if (requestDetails.getOwningEntity() != null)
- owningEntity = mapperLayer.mapRequestOwningEntity(requestDetails.getOwningEntity());
-
-
- Service service = bbInputSetupUtils
- .getCatalogServiceByModelUUID(requestDetails.getModelInfo().getModelVersionId());
- if (service == null) {
- service = bbInputSetupUtils.getCatalogServiceByModelVersionAndModelInvariantUUID(
- requestDetails.getModelInfo().getModelVersion(),
- requestDetails.getModelInfo().getModelInvariantId());
- if(service == null) {
- throw new Exception("Could not find service for model version Id: "
- + requestDetails.getModelInfo().getModelVersionId() + " and for model invariant Id: "
- + requestDetails.getModelInfo().getModelInvariantId());
- }
- }
- ServiceInstance serviceInstance = this.getALaCarteServiceInstance(service, requestDetails, customer,
- project, owningEntity, lookupKeyMap, resourceId, Boolean.TRUE.equals(executeBB.isaLaCarte()),
- executeBB.getBuildingBlock().getBpmnFlowName());
- return this.populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, customer);
- } else {
- throw new Exception("Could not find customer");
- }
- }
-
- protected Customer getCustomerAndServiceSubscription(RequestDetails requestDetails, String resourceId) {
- Customer customer;
- if (requestDetails.getSubscriberInfo() != null) {
- customer = this.getCustomerFromRequest(requestDetails);
- } else {
- customer = this.getCustomerFromURI(resourceId);
- }
- if (customer != null) {
- ServiceSubscription serviceSubscription = null;
- serviceSubscription = getServiceSubscription(requestDetails, customer);
- if (serviceSubscription == null) {
- serviceSubscription = getServiceSubscriptionFromURI(resourceId, customer);
- }
- customer.setServiceSubscription(serviceSubscription);
- return customer;
- } else {
- return null;
- }
- }
-
- protected ServiceSubscription getServiceSubscriptionFromURI(String resourceId, Customer customer) {
- Map<String, String> uriKeys = bbInputSetupUtils.getURIKeysFromServiceInstance(resourceId);
- String subscriptionServiceType = uriKeys.get("service-type");
- org.onap.aai.domain.yang.ServiceSubscription serviceSubscriptionAAI = bbInputSetupUtils
- .getAAIServiceSubscription(customer.getGlobalCustomerId(), subscriptionServiceType);
- if (serviceSubscriptionAAI != null) {
- return mapperLayer.mapAAIServiceSubscription(serviceSubscriptionAAI);
- } else {
- return null;
- }
- }
-
- protected Customer getCustomerFromURI(String resourceId) {
- Map<String, String> uriKeys = bbInputSetupUtils.getURIKeysFromServiceInstance(resourceId);
- String globalCustomerId = uriKeys.get("global-customer-id");
- org.onap.aai.domain.yang.Customer customerAAI = this.bbInputSetupUtils.getAAICustomer(globalCustomerId);
- if (customerAAI != null) {
- return mapperLayer.mapAAICustomer(customerAAI);
- } else {
- return null;
- }
- }
-
- protected GeneralBuildingBlock populateGBBWithSIAndAdditionalInfo(RequestDetails requestDetails,
- ServiceInstance serviceInstance, ExecuteBuildingBlock executeBB, String requestAction, Customer customer) throws Exception {
- GeneralBuildingBlock outputBB = new GeneralBuildingBlock();
- OrchestrationContext orchContext = mapperLayer.mapOrchestrationContext(requestDetails);
- RequestContext requestContext = mapperLayer.mapRequestContext(requestDetails);
- requestContext.setAction(requestAction);
- requestContext.setMsoRequestId(executeBB.getRequestId());
- org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = bbInputSetupUtils
- .getCloudRegion(requestDetails.getCloudConfiguration());
- CloudRegion cloudRegion = mapperLayer.mapCloudRegion(requestDetails.getCloudConfiguration(), aaiCloudRegion);
- Tenant tenant = getTenant(requestDetails.getCloudConfiguration(), aaiCloudRegion);
- outputBB.setOrchContext(orchContext);
- outputBB.setRequestContext(requestContext);
- outputBB.setCloudRegion(cloudRegion);
- outputBB.setTenant(tenant);
- if(customer == null){
- Map<String, String> uriKeys = bbInputSetupUtils.getURIKeysFromServiceInstance(serviceInstance.getServiceInstanceId());
- String globalCustomerId = uriKeys.get("global-customer-id");
- String subscriptionServiceType = uriKeys.get("service-type");
- customer = mapCustomer(globalCustomerId, subscriptionServiceType);
- }
- outputBB.setServiceInstance(serviceInstance);
- if (customer.getServiceSubscription() != null) {
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- }
- outputBB.setCustomer(customer);
- return outputBB;
- }
-
- protected Tenant getTenant(CloudConfiguration cloudConfiguration, org.onap.aai.domain.yang.CloudRegion aaiCloudRegion) throws Exception {
- Tenant tenant = new Tenant();
- if(cloudConfiguration != null && cloudConfiguration.getTenantId() != null
- && aaiCloudRegion != null && aaiCloudRegion.getTenants() != null) {
- for(org.onap.aai.domain.yang.Tenant aaiTenant : aaiCloudRegion.getTenants().getTenant()) {
- if(aaiTenant.getTenantId().equalsIgnoreCase(cloudConfiguration.getTenantId())) {
- tenant = mapperLayer.mapTenant(aaiTenant);
- }
- }
- if(tenant.getTenantId() == null || tenant.getTenantName() == null) {
- throw new Exception("Invalid tenant information retrieved: tenantId = " + tenant.getTenantId()
- + " tenantName = " + tenant.getTenantName());
- }
- }
- return tenant;
- }
-
- protected ServiceSubscription getServiceSubscription(RequestDetails requestDetails, Customer customer) {
- org.onap.aai.domain.yang.ServiceSubscription aaiServiceSubscription = bbInputSetupUtils
- .getAAIServiceSubscription(customer.getGlobalCustomerId(),
- requestDetails.getRequestParameters().getSubscriptionServiceType());
- if (aaiServiceSubscription != null) {
- return mapperLayer.mapAAIServiceSubscription(aaiServiceSubscription);
- } else {
- return null;
- }
- }
-
- protected Customer getCustomerFromRequest(RequestDetails requestDetails) {
- org.onap.aai.domain.yang.Customer aaiCustomer = bbInputSetupUtils
- .getAAICustomer(requestDetails.getSubscriberInfo().getGlobalSubscriberId());
- if (aaiCustomer != null) {
- return mapperLayer.mapAAICustomer(aaiCustomer);
- } else {
- return null;
- }
- }
-
- protected ServiceInstance getALaCarteServiceInstance(Service service, RequestDetails requestDetails,
- Customer customer, Project project, OwningEntity owningEntity, Map<ResourceKey, String> lookupKeyMap,
- String serviceInstanceId, boolean aLaCarte, String bbName) throws Exception {
- ServiceInstance serviceInstance = this.getServiceInstanceHelper(requestDetails, customer, project, owningEntity,
- lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
- org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = null;
- if(customer != null && customer.getServiceSubscription() != null) {
- serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceByIdAndCustomer(customer.getGlobalCustomerId(),
- customer.getServiceSubscription().getServiceType(), serviceInstanceId);
- } else {
- serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
- }
- if (serviceInstanceAAI != null
- && !serviceInstanceAAI.getModelVersionId().equalsIgnoreCase(service.getModelUUID())) {
- Service tempService = this.bbInputSetupUtils
- .getCatalogServiceByModelUUID(serviceInstanceAAI.getModelVersionId());
- if (tempService != null) {
- serviceInstance
- .setModelInfoServiceInstance(mapperLayer.mapCatalogServiceIntoServiceInstance(tempService));
- return serviceInstance;
- } else {
- throw new Exception(
- "Could not find model of existing SI. Service Instance in AAI already exists with different model version id: "
- + serviceInstanceAAI.getModelVersionId());
- }
- }
- serviceInstance.setModelInfoServiceInstance(mapperLayer.mapCatalogServiceIntoServiceInstance(service));
- return serviceInstance;
- }
-
- protected GeneralBuildingBlock getGBBMacro(ExecuteBuildingBlock executeBB, RequestDetails requestDetails,
- Map<ResourceKey, String> lookupKeyMap, String requestAction, String resourceId, String vnfType)
- throws Exception {
- String bbName = executeBB.getBuildingBlock().getBpmnFlowName();
- String key = executeBB.getBuildingBlock().getKey();
-
- if (requestAction.equalsIgnoreCase("deleteInstance")
- || requestAction.equalsIgnoreCase("unassignInstance")
- || requestAction.equalsIgnoreCase("activateInstance")
- || requestAction.equalsIgnoreCase("activateFabricConfiguration")
- || requestAction.equalsIgnoreCase("recreateInstance")
- || requestAction.equalsIgnoreCase("replaceInstance")) {
- return getGBBMacroExistingService(executeBB, lookupKeyMap, bbName, requestAction,
- requestDetails.getCloudConfiguration());
- }
-
- String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID);
- GeneralBuildingBlock gBB = this.getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction,
- serviceInstanceId);
- RequestParameters requestParams = requestDetails.getRequestParameters();
- Service service = null;
- if (gBB != null && gBB.getServiceInstance() != null
- && gBB.getServiceInstance().getModelInfoServiceInstance() != null
- && gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid() != null) {
- service = bbInputSetupUtils.getCatalogServiceByModelUUID(
- gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
- } else {
- throw new Exception("Could not get service instance for macro request");
- }
- if (requestParams != null && requestParams.getUserParams() != null) {
- for(Map<String, Object> userParams : requestParams.getUserParams()) {
- if(userParams.containsKey("service")) {
- String input = mapper.writeValueAsString(userParams.get("service"));
- return getGBBMacroUserParams(executeBB, requestDetails, lookupKeyMap, vnfType, bbName, key, gBB,
- requestParams, service, input);
- }
- }
- }
- if (requestAction.equalsIgnoreCase("deactivateInstance")) {
- return gBB;
- } else if (requestAction.equalsIgnoreCase("createInstance")) {
- return getGBBMacroNoUserParamsCreate(executeBB, lookupKeyMap, bbName, key, gBB, service);
- } else {
- throw new IllegalArgumentException(
- "No user params on requestAction: assignInstance. Please specify user params.");
- }
- }
-
- protected GeneralBuildingBlock getGBBMacroNoUserParamsCreate(ExecuteBuildingBlock executeBB,
- Map<ResourceKey, String> lookupKeyMap, String bbName, String key, GeneralBuildingBlock gBB, Service service)
- throws Exception {
- ServiceInstance serviceInstance = gBB.getServiceInstance();
- if (bbName.contains(NETWORK) && !bbName.contains(NETWORK_COLLECTION)) {
- String networkId = lookupKeyMap.get(ResourceKey.NETWORK_ID);
- ModelInfo networkModelInfo = new ModelInfo();
- if((!Boolean.TRUE.equals(executeBB.getBuildingBlock().getIsVirtualLink()))) {
- NetworkResourceCustomization networkCust = getNetworkCustomizationByKey(key, service);
- if (networkCust != null) {
- networkModelInfo.setModelCustomizationUuid(networkCust.getModelCustomizationUUID());
- this.populateL3Network(null, networkModelInfo, service, bbName, serviceInstance, lookupKeyMap,
- networkId, null);
- } else {
- logger.debug("Could not find a network customization with key: {}", key);
- }
- } else {
- logger.debug("Orchestrating on Collection Network Resource Customization");
- CollectionNetworkResourceCustomization collectionNetworkResourceCust = bbInputSetupUtils.getCatalogCollectionNetworkResourceCustByID(key);
- L3Network l3Network = getVirtualLinkL3Network(lookupKeyMap, bbName, key, networkId, collectionNetworkResourceCust, serviceInstance);
- NetworkResourceCustomization networkResourceCustomization =
- mapperLayer.mapCollectionNetworkResourceCustToNetworkResourceCust(collectionNetworkResourceCust);
- if(l3Network != null) {
- l3Network.setModelInfoNetwork(mapperLayer.mapCatalogNetworkToNetwork(networkResourceCustomization));
- }
- }
- } else if(bbName.contains("Configuration")) {
- String configurationId = lookupKeyMap.get(ResourceKey.CONFIGURATION_ID);
- ModelInfo configurationModelInfo = new ModelInfo();
- configurationModelInfo.setModelCustomizationUuid(key);
- this.populateConfiguration(configurationModelInfo, service, bbName, serviceInstance, lookupKeyMap, configurationId, null, executeBB.getConfigurationResourceKeys());
- }
- if (executeBB.getWorkflowResourceIds() != null) {
- this.populateNetworkCollectionAndInstanceGroupAssign(service, bbName, serviceInstance,
- executeBB.getWorkflowResourceIds().getNetworkCollectionId(), key);
- }
- return gBB;
- }
-
- protected L3Network getVirtualLinkL3Network(Map<ResourceKey, String> lookupKeyMap, String bbName, String key,
- String networkId, CollectionNetworkResourceCustomization collectionNetworkResourceCust, ServiceInstance serviceInstance) {
- if(collectionNetworkResourceCust != null) {
- if((bbName.equalsIgnoreCase(AssignFlows.NETWORK_A_LA_CARTE.toString())
- || bbName.equalsIgnoreCase(AssignFlows.NETWORK_MACRO.toString()))) {
- L3Network network = createNetwork(lookupKeyMap, null, networkId, null);
- serviceInstance.getNetworks().add(network);
- return network;
- } else {
- for (L3Network network : serviceInstance.getNetworks()) {
- if (network.getNetworkId().equalsIgnoreCase(networkId)) {
- return network;
- }
- }
- }
- }
- return null;
- }
-
- protected NetworkResourceCustomization getNetworkCustomizationByKey(String key, Service service) {
- for (NetworkResourceCustomization networkCust : service.getNetworkCustomizations()) {
- if (networkCust.getModelCustomizationUUID().equalsIgnoreCase(key)) {
- return networkCust;
- }
- }
- return null;
- }
-
- protected GeneralBuildingBlock getGBBMacroExistingService(ExecuteBuildingBlock executeBB,
- Map<ResourceKey, String> lookupKeyMap, String bbName, String requestAction, CloudConfiguration cloudConfiguration) throws Exception {
- org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = null;
- String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID);
- RequestDetails requestDetails = executeBB.getRequestDetails();
- GeneralBuildingBlock gBB = null;
- if (serviceInstanceId != null) {
- aaiServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
- }
- Service service = null;
- if (aaiServiceInstance != null) {
- service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
- }
- if (aaiServiceInstance != null && service != null) {
- ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance);
- serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service));
- gBB = populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, null);
- } else {
- logger.debug("Related Service Instance from AAI: {}", aaiServiceInstance);
- logger.debug("Related Service Instance Model Info from AAI: {}", service);
- throw new Exception("Could not find relevant information for related Service Instance");
- }
- ServiceInstance serviceInstance = gBB.getServiceInstance();
- CloudRegion cloudRegion = null;
- if(cloudConfiguration == null) {
- Optional<CloudRegion> cloudRegionOp = cloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance);
- if(cloudRegionOp.isPresent()) {
- cloudRegion = cloudRegionOp.get();
- }
- }
- if (cloudConfiguration != null) {
- org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = bbInputSetupUtils.getCloudRegion(cloudConfiguration);
- cloudRegion = mapperLayer.mapCloudRegion(cloudConfiguration, aaiCloudRegion);
- }
- gBB.setCloudRegion(cloudRegion);
- if (bbName.contains(VNF)) {
- for (GenericVnf genericVnf : serviceInstance.getVnfs()) {
- if (lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID) != null
- && genericVnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
- org.onap.aai.domain.yang.GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(genericVnf.getVnfId());
- ModelInfo modelInfo = new ModelInfo();
- if (vnf != null) {
- modelInfo.setModelCustomizationUuid(vnf.getModelCustomizationId());
- }
- this.mapCatalogVnf(genericVnf, modelInfo, service);
- }
- }
- } else if (bbName.contains(VF_MODULE)) {
- for (GenericVnf vnf : serviceInstance.getVnfs()) {
- for (VfModule vfModule : vnf.getVfModules()) {
- if (lookupKeyMap.get(ResourceKey.VF_MODULE_ID) != null
- && vfModule.getVfModuleId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.VF_MODULE_ID))) {
- String vnfModelCustomizationUUID = this.bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId())
- .getModelCustomizationId();
- ModelInfo vnfModelInfo = new ModelInfo();
- vnfModelInfo.setModelCustomizationUuid(vnfModelCustomizationUUID);
- this.mapCatalogVnf(vnf, vnfModelInfo, service);
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnf.getVnfId());
- String vfModuleCustomizationUUID = this.bbInputSetupUtils
- .getAAIVfModule(vnf.getVnfId(), vfModule.getVfModuleId()).getModelCustomizationId();
- ModelInfo vfModuleModelInfo = new ModelInfo();
- vfModuleModelInfo.setModelCustomizationId(vfModuleCustomizationUUID);
- this.mapCatalogVfModule(vfModule, vfModuleModelInfo, service, vnfModelCustomizationUUID);
- if(cloudRegion != null) {
- Optional<String> volumeGroupIdOp = getVolumeGroupIdRelatedToVfModule(vnf, vfModuleModelInfo, cloudRegion.getCloudOwner(),
- cloudRegion.getLcpCloudRegionId(), lookupKeyMap);
- if(volumeGroupIdOp.isPresent()) {
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupIdOp.get());
- }
- }
- break;
- }
- }
- }
- } else if (bbName.contains(VOLUME_GROUP)) {
- for (GenericVnf vnf : serviceInstance.getVnfs()) {
- for (VolumeGroup volumeGroup : vnf.getVolumeGroups()) {
- if (lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID) != null && volumeGroup.getVolumeGroupId()
- .equalsIgnoreCase(lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID))) {
- String vnfModelCustomizationUUID = this.bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId())
- .getModelCustomizationId();
- ModelInfo vnfModelInfo = new ModelInfo();
- vnfModelInfo.setModelCustomizationUuid(vnfModelCustomizationUUID);
- this.mapCatalogVnf(vnf, vnfModelInfo, service);
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnf.getVnfId());
- if (cloudRegion != null) {
- String volumeGroupCustomizationUUID = this.bbInputSetupUtils.getAAIVolumeGroup(cloudRegion.getCloudOwner(),
- cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId())
- .getModelCustomizationId();
- ModelInfo volumeGroupModelInfo = new ModelInfo();
- volumeGroupModelInfo.setModelCustomizationId(volumeGroupCustomizationUUID);
- this.mapCatalogVolumeGroup(volumeGroup, volumeGroupModelInfo, service,
- vnfModelCustomizationUUID);
- }
- break;
- }
- }
- }
- } else if (bbName.contains(NETWORK)) {
- for (L3Network network : serviceInstance.getNetworks()) {
- if (lookupKeyMap.get(ResourceKey.NETWORK_ID) != null
- && network.getNetworkId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.NETWORK_ID))) {
- String networkCustomizationUUID = this.bbInputSetupUtils.getAAIL3Network(network.getNetworkId())
- .getModelCustomizationId();
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelCustomizationUuid(networkCustomizationUUID);
- this.mapCatalogNetwork(network, modelInfo, service);
- break;
- }
- }
- } else if (bbName.contains("Fabric")) {
- for(Configuration configuration : serviceInstance.getConfigurations()) {
- if(lookupKeyMap.get(ResourceKey.CONFIGURATION_ID) != null
- && configuration.getConfigurationId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.CONFIGURATION_ID))) {
- String configurationCustUUID = this.bbInputSetupUtils.getAAIConfiguration(configuration.getConfigurationId())
- .getModelCustomizationId();
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelCustomizationUuid(configurationCustUUID);
- this.mapCatalogConfiguration(configuration, modelInfo, service, executeBB.getConfigurationResourceKeys());
- break;
- }
- }
- }
- if (executeBB.getWorkflowResourceIds() != null) {
- this.populateNetworkCollectionAndInstanceGroupAssign(service, bbName, serviceInstance,
- executeBB.getWorkflowResourceIds().getNetworkCollectionId(), executeBB.getBuildingBlock().getKey());
- }
- return gBB;
- }
-
- protected GeneralBuildingBlock getGBBMacroUserParams(ExecuteBuildingBlock executeBB, RequestDetails requestDetails,
- Map<ResourceKey, String> lookupKeyMap, String vnfType, String bbName, String key, GeneralBuildingBlock gBB,
- RequestParameters requestParams, Service service, String input) throws Exception {
- ServiceInstance serviceInstance = gBB.getServiceInstance();
- org.onap.so.serviceinstancebeans.Service serviceMacro = mapper.readValue(input,
- org.onap.so.serviceinstancebeans.Service.class);
-
- Resources resources = serviceMacro.getResources();
- Vnfs vnfs = null;
- VfModules vfModules = null;
- Networks networks = null;
- CloudConfiguration cloudConfiguration = requestDetails.getCloudConfiguration();
- CloudRegion cloudRegion = getCloudRegionFromMacroRequest(cloudConfiguration, resources);
- gBB.setCloudRegion(cloudRegion);
- if (bbName.contains(VNF)) {
- vnfs = findVnfsByKey(key, resources, vnfs);
- String vnfId = lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID);
- // This stores the vnf id in request db to be retrieved later when
- // working on a vf module or volume group
- InfraActiveRequests request = this.bbInputSetupUtils.getInfraActiveRequest(executeBB.getRequestId());
- if (request != null) {
- this.bbInputSetupUtils.updateInfraActiveRequestVnfId(request, vnfId);
- }
- String productFamilyId = requestDetails.getRequestInfo().getProductFamilyId();
- this.populateGenericVnf(vnfs.getModelInfo(), vnfs.getInstanceName(), vnfs.getPlatform(),
- vnfs.getLineOfBusiness(), service, bbName, serviceInstance, lookupKeyMap, null, vnfId, vnfType, vnfs.getInstanceParams(),
- productFamilyId);
- } else if (bbName.contains(VF_MODULE) || bbName.contains(VOLUME_GROUP)) {
- Pair<Vnfs, VfModules> vnfsAndVfModules = getVfModulesAndItsVnfsByKey(key, resources);
- vfModules = vnfsAndVfModules.getValue1();
- vnfs = vnfsAndVfModules.getValue0();
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, getVnfId(executeBB, lookupKeyMap));
- if (vnfs == null) {
- throw new Exception("Could not find Vnf to orchestrate VfModule");
- }
- ModelInfo modelInfo = vfModules.getModelInfo();
- if (bbName.contains(VOLUME_GROUP)) {
- String volumeGroupId = lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID);
- this.populateVolumeGroup(modelInfo, service, bbName, serviceInstance, lookupKeyMap, volumeGroupId, null,
- vfModules.getVolumeGroupInstanceName(), vnfType, vfModules.getInstanceParams());
- } else {
- String vfModuleId = lookupKeyMap.get(ResourceKey.VF_MODULE_ID);
- CloudConfiguration cloudConfig = new CloudConfiguration();
- cloudConfig.setLcpCloudRegionId(cloudRegion.getLcpCloudRegionId());
- cloudConfig.setCloudOwner(cloudRegion.getCloudOwner());
- this.populateVfModule(modelInfo, service, bbName, serviceInstance, lookupKeyMap, vfModuleId, null,
- vfModules.getInstanceName(), vfModules.getInstanceParams(), cloudConfig);
- }
- } else if (bbName.contains(NETWORK)) {
- networks = findNetworksByKey(key, resources);
- String networkId = lookupKeyMap.get(ResourceKey.NETWORK_ID);
- this.populateL3Network(networks.getInstanceName(), networks.getModelInfo(), service, bbName,
- serviceInstance, lookupKeyMap, networkId, networks.getInstanceParams());
- } else if (bbName.contains("Configuration")) {
- String configurationId = lookupKeyMap.get(ResourceKey.CONFIGURATION_ID);
- ModelInfo configurationModelInfo = new ModelInfo();
- configurationModelInfo.setModelCustomizationUuid(key);
- ConfigurationResourceCustomization configurationCust = findConfigurationResourceCustomization(configurationModelInfo, service);
- if(configurationCust != null) {
- this.populateConfiguration(configurationModelInfo, service, bbName, serviceInstance, lookupKeyMap, configurationId, null, executeBB.getConfigurationResourceKeys());
- } else {
- logger.debug("Could not find a configuration customization with key: {}", key);
- }
- }
- return gBB;
- }
-
- protected Networks findNetworksByKey(String key, Resources resources) {
- for (Networks networks : resources.getNetworks()) {
- if (networks.getModelInfo().getModelCustomizationId().equalsIgnoreCase(key)) {
- return networks;
- }
- }
- return null;
- }
-
- protected Pair<Vnfs, VfModules> getVfModulesAndItsVnfsByKey(String key, Resources resources) {
- for (Vnfs vnfs : resources.getVnfs()) {
- for (VfModules vfModules : vnfs.getVfModules()) {
- if (vfModules.getModelInfo().getModelCustomizationId().equalsIgnoreCase(key)) {
- return new Pair<Vnfs, VfModules>(vnfs, vfModules);
- }
- }
- }
- return null;
- }
-
- protected Vnfs findVnfsByKey(String key, Resources resources, Vnfs vnfs) {
- for (Vnfs tempVnfs : resources.getVnfs()) {
- if (tempVnfs.getModelInfo().getModelCustomizationId().equalsIgnoreCase(key)) {
- vnfs = tempVnfs;
- break;
- }
- }
- return vnfs;
- }
-
- protected CloudRegion getCloudRegionFromMacroRequest(CloudConfiguration cloudConfiguration, Resources resources) {
- if(cloudConfiguration == null) {
- for(Vnfs vnfs : resources.getVnfs()) {
- if(cloudConfiguration == null) {
- cloudConfiguration = vnfs.getCloudConfiguration();
- } else {
- break;
- }
- for(VfModules vfModules : vnfs.getVfModules()) {
- if(cloudConfiguration == null) {
- cloudConfiguration = vfModules.getCloudConfiguration();
- } else {
- break;
- }
- }
- }
- for(Networks networks : resources.getNetworks()) {
- if(cloudConfiguration == null) {
- cloudConfiguration = networks.getCloudConfiguration();
- } else {
- break;
- }
- }
- }
- if(cloudConfiguration != null) {
- org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = bbInputSetupUtils.getCloudRegion(cloudConfiguration);
- return mapperLayer.mapCloudRegion(cloudConfiguration, aaiCloudRegion);
- } else {
- logger.debug("Could not find any cloud configuration for this request.");
- return null;
- }
- }
-
- protected String getVnfId(ExecuteBuildingBlock executeBB, Map<ResourceKey, String> lookupKeyMap) {
- String vnfId = lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID);
- if (vnfId == null) {
- InfraActiveRequests request = this.bbInputSetupUtils.getInfraActiveRequest(executeBB.getRequestId());
- vnfId = request.getVnfId();
- }
-
- return vnfId;
- }
-
- protected String generateRandomUUID() {
- return UUID.randomUUID().toString();
- }
-
- protected ServiceInstance getServiceInstanceHelper(RequestDetails requestDetails, Customer customer,
- Project project, OwningEntity owningEntity, Map<ResourceKey, String> lookupKeyMap, String serviceInstanceId,
- boolean aLaCarte, Service service, String bbName) throws Exception {
- if (requestDetails.getRequestInfo().getInstanceName() == null && aLaCarte
- && bbName.equalsIgnoreCase(AssignFlows.SERVICE_INSTANCE.toString())) {
- throw new Exception("Request invalid missing: RequestInfo:InstanceName");
- } else {
- org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = null;
- if (aLaCarte && bbName.equalsIgnoreCase(AssignFlows.SERVICE_INSTANCE.toString())) {
- serviceInstanceAAI = bbInputSetupUtils
- .getAAIServiceInstanceByName(requestDetails.getRequestInfo().getInstanceName(), customer);
- }
- if (serviceInstanceId != null && serviceInstanceAAI == null) {
- if(customer != null && customer.getServiceSubscription() != null) {
- serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceByIdAndCustomer(customer.getGlobalCustomerId(),
- customer.getServiceSubscription().getServiceType(), serviceInstanceId);
- } else {
- serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
- }
- }
- if (serviceInstanceAAI != null) {
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstanceId);
- return this.getExistingServiceInstance(serviceInstanceAAI);
- } else {
- return createServiceInstance(requestDetails, project, owningEntity, lookupKeyMap,
- serviceInstanceId);
- }
- }
- }
-
- protected ServiceInstance createServiceInstance(RequestDetails requestDetails, Project project,
- OwningEntity owningEntity, Map<ResourceKey, String> lookupKeyMap, String serviceInstanceId) {
- ServiceInstance serviceInstance = new ServiceInstance();
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstanceId);
- serviceInstance.setServiceInstanceId(serviceInstanceId);
- if(requestDetails.getRequestInfo() != null) {
- serviceInstance.setServiceInstanceName(requestDetails.getRequestInfo().getInstanceName());
- }
- serviceInstance.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- serviceInstance.setProject(project);
- serviceInstance.setOwningEntity(owningEntity);
- return serviceInstance;
- }
-
- public ServiceInstance getExistingServiceInstance(org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI)
- throws Exception {
- ServiceInstance serviceInstance = mapperLayer.mapAAIServiceInstanceIntoServiceInstance(serviceInstanceAAI);
- if (serviceInstanceAAI.getRelationshipList() != null
- && serviceInstanceAAI.getRelationshipList().getRelationship() != null
- && !serviceInstanceAAI.getRelationshipList().getRelationship().isEmpty()) {
- addRelationshipsToSI(serviceInstanceAAI, serviceInstance);
- }
- return serviceInstance;
- }
-
- protected void populateNetworkCollectionAndInstanceGroupAssign(Service service, String bbName,
- ServiceInstance serviceInstance, String resourceId, String key) throws Exception {
- if (serviceInstance.getCollection() == null
- && bbName.equalsIgnoreCase(AssignFlows.NETWORK_COLLECTION.toString())) {
- Collection collection = this.createCollection(resourceId);
- serviceInstance.setCollection(collection);
- this.mapCatalogCollection(service, serviceInstance.getCollection(), key);
- if(isVlanTagging(service, key)) {
- InstanceGroup instanceGroup = this.createInstanceGroup();
- serviceInstance.getCollection().setInstanceGroup(instanceGroup);
- this.mapCatalogNetworkCollectionInstanceGroup(service,
- serviceInstance.getCollection().getInstanceGroup(), key);
- }
- }
- }
-
- protected CollectionResourceCustomization findCatalogNetworkCollection(Service service, String key) {
- for(CollectionResourceCustomization collectionCust : service.getCollectionResourceCustomizations()){
- if(collectionCust.getModelCustomizationUUID().equalsIgnoreCase(key)) {
- return collectionCust;
- }
- }
- return null;
- }
-
- protected boolean isVlanTagging(Service service, String key) {
- CollectionResourceCustomization collectionCust = findCatalogNetworkCollection(service, key);
- if (collectionCust != null) {
- CollectionResource collectionResource = collectionCust.getCollectionResource();
- if (collectionResource != null
- && collectionResource.getInstanceGroup() != null
- && collectionResource.getInstanceGroup().getToscaNodeType() != null
- && collectionResource.getInstanceGroup().getToscaNodeType().contains("NetworkCollection")) {
- return true;
- }
- }
- return false;
- }
-
- protected void mapCatalogNetworkCollectionInstanceGroup(Service service, InstanceGroup instanceGroup, String key) {
- CollectionResourceCustomization collectionCust = this.findCatalogNetworkCollection(service, key);
- org.onap.so.db.catalog.beans.InstanceGroup catalogInstanceGroup = collectionCust.getCollectionResource().getInstanceGroup();
- instanceGroup.setModelInfoInstanceGroup(
- mapperLayer.mapCatalogInstanceGroupToInstanceGroup(collectionCust, catalogInstanceGroup));
- }
-
- protected void mapCatalogCollection(Service service, Collection collection, String key) {
- CollectionResourceCustomization collectionCust = findCatalogNetworkCollection(service, key);
- if (collectionCust != null) {
- CollectionResource collectionResource = collectionCust.getCollectionResource();
- if (collectionResource != null) {
- collection.setModelInfoCollection(
- mapperLayer.mapCatalogCollectionToCollection(collectionCust, collectionResource));
- }
- }
- }
-
- protected Collection createCollection(String collectionId) {
- Collection collection = new Collection();
- collection.setId(collectionId);
- collection.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- return collection;
- }
-
- protected InstanceGroup createInstanceGroup() {
- InstanceGroup instanceGroup = new InstanceGroup();
- String instanceGroupId = this.generateRandomUUID();
- instanceGroup.setId(instanceGroupId);
- return instanceGroup;
- }
-
- protected void addRelationshipsToSI(org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI,
- ServiceInstance serviceInstance) throws Exception {
- AAIResultWrapper serviceInstanceWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(serviceInstanceAAI));
- Optional<Relationships> relationshipsOp = serviceInstanceWrapper.getRelationships();
- Relationships relationships = null;
- if (relationshipsOp.isPresent()) {
- relationships = relationshipsOp.get();
- } else {
- return;
- }
-
- this.mapProject(relationships.getByType(AAIObjectType.PROJECT), serviceInstance);
- this.mapOwningEntity(relationships.getByType(AAIObjectType.OWNING_ENTITY), serviceInstance);
- this.mapL3Networks(relationships.getRelatedAAIUris(AAIObjectType.L3_NETWORK), serviceInstance.getNetworks());
- this.mapGenericVnfs(relationships.getRelatedAAIUris(AAIObjectType.GENERIC_VNF), serviceInstance.getVnfs());
- this.mapCollection(relationships.getByType(AAIObjectType.COLLECTION), serviceInstance);
- this.mapConfigurations(relationships.getRelatedAAIUris(AAIObjectType.CONFIGURATION), serviceInstance.getConfigurations());
- }
-
- protected void mapConfigurations(List<AAIResourceUri> relatedAAIUris, List<Configuration> configurations) {
- for (AAIResourceUri aaiResourceUri : relatedAAIUris) {
- configurations.add(mapConfiguration(aaiResourceUri));
- }
- }
-
- protected Configuration mapConfiguration(AAIResourceUri aaiResourceUri) {
- AAIResultWrapper aaiConfigurationWrapper = this.bbInputSetupUtils.getAAIResourceDepthOne(aaiResourceUri);
- Optional<org.onap.aai.domain.yang.Configuration> aaiConfigurationOp = aaiConfigurationWrapper
- .asBean(org.onap.aai.domain.yang.Configuration.class);
- if (!aaiConfigurationOp.isPresent()) {
- return null;
- }
-
- return this.mapperLayer.mapAAIConfiguration(aaiConfigurationOp.get());
- }
-
- protected void mapGenericVnfs(List<AAIResourceUri> list, List<GenericVnf> genericVnfs) {
- for (AAIResourceUri aaiResourceUri : list) {
- genericVnfs.add(this.mapGenericVnf(aaiResourceUri));
- }
- }
-
- protected GenericVnf mapGenericVnf(AAIResourceUri aaiResourceUri) {
- AAIResultWrapper aaiGenericVnfWrapper = this.bbInputSetupUtils.getAAIResourceDepthOne(aaiResourceUri);
- Optional<org.onap.aai.domain.yang.GenericVnf> aaiGenericVnfOp = aaiGenericVnfWrapper
- .asBean(org.onap.aai.domain.yang.GenericVnf.class);
- if (!aaiGenericVnfOp.isPresent()) {
- return null;
- }
-
- GenericVnf genericVnf = this.mapperLayer.mapAAIGenericVnfIntoGenericVnf(aaiGenericVnfOp.get());
-
- Optional<Relationships> relationshipsOp = aaiGenericVnfWrapper.getRelationships();
- if (relationshipsOp.isPresent()) {
- Relationships relationships = relationshipsOp.get();
- this.mapPlatform(relationships.getByType(AAIObjectType.PLATFORM), genericVnf);
- this.mapLineOfBusiness(relationships.getByType(AAIObjectType.LINE_OF_BUSINESS), genericVnf);
- genericVnf.getVolumeGroups().addAll(mapVolumeGroups(relationships.getByType(AAIObjectType.VOLUME_GROUP)));
- genericVnf.getInstanceGroups().addAll(mapInstanceGroups(relationships.getByType(AAIObjectType.INSTANCE_GROUP)));
- }
-
- return genericVnf;
- }
-
- protected List<InstanceGroup> mapInstanceGroups(List<AAIResultWrapper> instanceGroups) {
- List<InstanceGroup> instanceGroupsList = new ArrayList<>();
- for (AAIResultWrapper volumeGroupWrapper : instanceGroups) {
- instanceGroupsList.add(this.mapInstanceGroup(volumeGroupWrapper));
- }
- return instanceGroupsList;
- }
-
- protected InstanceGroup mapInstanceGroup(AAIResultWrapper instanceGroupWrapper) {
- Optional<org.onap.aai.domain.yang.InstanceGroup> aaiInstanceGroupOp = instanceGroupWrapper
- .asBean(org.onap.aai.domain.yang.InstanceGroup.class);
- org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = null;
-
- if (!aaiInstanceGroupOp.isPresent()) {
- return null;
- }
-
- aaiInstanceGroup = aaiInstanceGroupOp.get();
- InstanceGroup instanceGroup = this.mapperLayer.mapAAIInstanceGroupIntoInstanceGroup(aaiInstanceGroup);
- instanceGroup.setModelInfoInstanceGroup(this.mapperLayer.mapCatalogInstanceGroupToInstanceGroup(null,
- this.bbInputSetupUtils.getCatalogInstanceGroup(aaiInstanceGroup.getModelVersionId())));
- return instanceGroup;
- }
-
- protected List<VolumeGroup> mapVolumeGroups(List<AAIResultWrapper> volumeGroups) {
- List<VolumeGroup> volumeGroupsList = new ArrayList<>();
- for (AAIResultWrapper volumeGroupWrapper : volumeGroups) {
- volumeGroupsList.add(this.mapVolumeGroup(volumeGroupWrapper));
- }
- return volumeGroupsList;
- }
-
- protected VolumeGroup mapVolumeGroup(AAIResultWrapper volumeGroupWrapper) {
- Optional<org.onap.aai.domain.yang.VolumeGroup> aaiVolumeGroupOp = volumeGroupWrapper
- .asBean(org.onap.aai.domain.yang.VolumeGroup.class);
- org.onap.aai.domain.yang.VolumeGroup aaiVolumeGroup = null;
-
- if (!aaiVolumeGroupOp.isPresent()) {
- return null;
- }
-
- aaiVolumeGroup = aaiVolumeGroupOp.get();
- return this.mapperLayer.mapAAIVolumeGroup(aaiVolumeGroup);
- }
-
- protected void mapLineOfBusiness(List<AAIResultWrapper> lineOfBusinesses, GenericVnf genericVnf) {
- if (!lineOfBusinesses.isEmpty()) {
- AAIResultWrapper lineOfBusinessWrapper = lineOfBusinesses.get(0);
- Optional<org.onap.aai.domain.yang.LineOfBusiness> aaiLineOfBusinessOp = lineOfBusinessWrapper
- .asBean(org.onap.aai.domain.yang.LineOfBusiness.class);
- org.onap.aai.domain.yang.LineOfBusiness aaiLineOfBusiness = null;
- if (!aaiLineOfBusinessOp.isPresent()) {
- return;
- }
- aaiLineOfBusiness = aaiLineOfBusinessOp.get();
-
- LineOfBusiness lineOfBusiness = this.mapperLayer.mapAAILineOfBusiness(aaiLineOfBusiness);
- genericVnf.setLineOfBusiness(lineOfBusiness);
- }
- }
-
- protected void mapPlatform(List<AAIResultWrapper> platforms, GenericVnf genericVnf) {
- if (!platforms.isEmpty()) {
- AAIResultWrapper platformWrapper = platforms.get(0);
- Optional<org.onap.aai.domain.yang.Platform> aaiPlatformOp = platformWrapper
- .asBean(org.onap.aai.domain.yang.Platform.class);
- org.onap.aai.domain.yang.Platform aaiPlatform = null;
- if (!aaiPlatformOp.isPresent()) {
- return;
- }
- aaiPlatform = aaiPlatformOp.get();
-
- Platform platform = this.mapperLayer.mapAAIPlatform(aaiPlatform);
- genericVnf.setPlatform(platform);
- }
- }
-
- protected void mapCollection(List<AAIResultWrapper> collections, ServiceInstance serviceInstance) {
- if (!collections.isEmpty()) {
- AAIResultWrapper collectionWrapper = collections.get(0);
- Optional<org.onap.aai.domain.yang.Collection> aaiCollectionOp = collectionWrapper
- .asBean(org.onap.aai.domain.yang.Collection.class);
- org.onap.aai.domain.yang.Collection aaiCollection = null;
- if (!aaiCollectionOp.isPresent()) {
- return;
- }
- aaiCollection = aaiCollectionOp.get();
-
- Collection collection = this.mapperLayer.mapAAICollectionIntoCollection(aaiCollection);
- NetworkCollectionResourceCustomization collectionResourceCust =
- bbInputSetupUtils.getCatalogNetworkCollectionResourceCustByID(aaiCollection.getCollectionCustomizationId());
- collection.setModelInfoCollection(mapperLayer.mapCatalogCollectionToCollection(collectionResourceCust, collectionResourceCust.getCollectionResource()));
- Optional<Relationships> relationshipsOp = collectionWrapper.getRelationships();
- Relationships relationships = null;
- if (relationshipsOp.isPresent()) {
- relationships = relationshipsOp.get();
- } else {
- serviceInstance.setCollection(collection);
- return;
- }
- List<InstanceGroup> instanceGroupsList = mapInstanceGroups(relationships.getByType(AAIObjectType.INSTANCE_GROUP));
- if(!instanceGroupsList.isEmpty()) {
- collection.setInstanceGroup(instanceGroupsList.get(0));
- }
- serviceInstance.setCollection(collection);
- }
- }
-
- protected void mapL3Networks(List<AAIResourceUri> list, List<L3Network> l3Networks) {
- for (AAIResourceUri aaiResourceUri : list) {
- l3Networks.add(this.mapL3Network(aaiResourceUri));
- }
- }
-
- protected L3Network mapL3Network(AAIResourceUri aaiResourceUri) {
- AAIResultWrapper aaiNetworkWrapper = this.bbInputSetupUtils.getAAIResourceDepthTwo(aaiResourceUri);
- Optional<org.onap.aai.domain.yang.L3Network> aaiL3NetworkOp = aaiNetworkWrapper
- .asBean(org.onap.aai.domain.yang.L3Network.class);
- org.onap.aai.domain.yang.L3Network aaiL3Network = null;
-
- if (!aaiL3NetworkOp.isPresent()) {
- return null;
- }
-
- aaiL3Network = aaiL3NetworkOp.get();
- L3Network network = this.mapperLayer.mapAAIL3Network(aaiL3Network);
-
- Optional<Relationships> relationshipsOp = aaiNetworkWrapper.getRelationships();
- if (relationshipsOp.isPresent()) {
- Relationships relationships = relationshipsOp.get();
- this.mapNetworkPolicies(relationships.getByType(AAIObjectType.NETWORK_POLICY),
- network.getNetworkPolicies());
- mapRouteTableReferences(relationships.getByType(AAIObjectType.ROUTE_TABLE_REFERENCE),
- network.getContrailNetworkRouteTableReferences());
- }
-
- return network;
- }
-
- protected void mapNetworkPolicies(List<AAIResultWrapper> aaiNetworkPolicies, List<NetworkPolicy> networkPolicies) {
- for (AAIResultWrapper networkPolicyWrapper : aaiNetworkPolicies) {
- networkPolicies.add(this.mapNetworkPolicy(networkPolicyWrapper));
- }
- }
-
- protected NetworkPolicy mapNetworkPolicy(AAIResultWrapper networkPolicyWrapper) {
- Optional<org.onap.aai.domain.yang.NetworkPolicy> aaiNetworkPolicyOp = networkPolicyWrapper
- .asBean(org.onap.aai.domain.yang.NetworkPolicy.class);
- org.onap.aai.domain.yang.NetworkPolicy aaiNetworkPolicy = null;
-
- if (!aaiNetworkPolicyOp.isPresent()) {
- return null;
- }
-
- aaiNetworkPolicy = aaiNetworkPolicyOp.get();
- return this.mapperLayer.mapAAINetworkPolicy(aaiNetworkPolicy);
- }
-
- protected void mapRouteTableReferences(List<AAIResultWrapper> routeTableReferences,
- List<RouteTableReference> contrailNetworkRouteTableReferences) {
- for (AAIResultWrapper routeTableReferenceWrapper : routeTableReferences) {
- contrailNetworkRouteTableReferences.add(this.mapRouteTableReference(routeTableReferenceWrapper));
- }
- }
-
- protected RouteTableReference mapRouteTableReference(AAIResultWrapper routeTableReferenceWrapper) {
- Optional<org.onap.aai.domain.yang.RouteTableReference> aaiRouteTableReferenceOp = routeTableReferenceWrapper
- .asBean(org.onap.aai.domain.yang.RouteTableReference.class);
- org.onap.aai.domain.yang.RouteTableReference aaiRouteTableReference = null;
-
- if (!aaiRouteTableReferenceOp.isPresent()) {
- return null;
- }
-
- aaiRouteTableReference = aaiRouteTableReferenceOp.get();
- return this.mapperLayer.mapAAIRouteTableReferenceIntoRouteTableReference(aaiRouteTableReference);
- }
-
- protected void mapOwningEntity(List<AAIResultWrapper> owningEntities, ServiceInstance serviceInstance) {
- if (!owningEntities.isEmpty()) {
- AAIResultWrapper owningEntityWrapper = owningEntities.get(0);
- Optional<org.onap.aai.domain.yang.OwningEntity> aaiOwningEntityOp = owningEntityWrapper
- .asBean(org.onap.aai.domain.yang.OwningEntity.class);
- org.onap.aai.domain.yang.OwningEntity aaiOwningEntity = null;
- if (!aaiOwningEntityOp.isPresent()) {
- return;
- }
- aaiOwningEntity = aaiOwningEntityOp.get();
-
- OwningEntity owningEntity = this.mapperLayer.mapAAIOwningEntity(aaiOwningEntity);
- serviceInstance.setOwningEntity(owningEntity);
- }
- }
-
- protected void mapProject(List<AAIResultWrapper> projects, ServiceInstance serviceInstance) {
- if (!projects.isEmpty()) {
- AAIResultWrapper projectWrapper = projects.get(0);
- Optional<org.onap.aai.domain.yang.Project> aaiProjectOp = projectWrapper
- .asBean(org.onap.aai.domain.yang.Project.class);
- org.onap.aai.domain.yang.Project aaiProject = null;
- if (!aaiProjectOp.isPresent()) {
- return;
- }
- aaiProject = aaiProjectOp.get();
-
- Project project = this.mapperLayer.mapAAIProject(aaiProject);
- serviceInstance.setProject(project);
- }
- }
- protected Customer mapCustomer(String globalCustomerId, String subscriptionServiceType) {
- org.onap.aai.domain.yang.Customer aaiCustomer = this.bbInputSetupUtils.getAAICustomer(globalCustomerId);
- org.onap.aai.domain.yang.ServiceSubscription aaiServiceSubscription = this.bbInputSetupUtils
- .getAAIServiceSubscription(globalCustomerId, subscriptionServiceType);
- Customer customer = this.mapperLayer.mapAAICustomer(aaiCustomer);
- ServiceSubscription serviceSubscription = this.mapperLayer.mapAAIServiceSubscription(aaiServiceSubscription);
- if(serviceSubscription != null){
- customer.setServiceSubscription(serviceSubscription);
- }
- return customer;
- }
+ private static final Logger logger = LoggerFactory.getLogger(BBInputSetup.class);
+ private static final String FLOW_VAR_NAME = "flowToBeCalled";
+ private static final String LOOKUP_KEY_MAP_VAR_NAME = "lookupKeyMap";
+ private static final String GBB_INPUT_VAR_NAME = "gBBInput";
+ private static final String EXECUTE_BB_VAR_NAME = "buildingBlock";
+ private static final String VOLUME_GROUP = "VolumeGroup";
+ private static final String VF_MODULE = "VfModule";
+ private static final String NETWORK = "Network";
+ private static final String VNF = "Vnf";
+ private static final String NETWORK_COLLECTION = "NetworkCollection";
+ private static final String PREPROV = "PREPROV";
+
+ @Autowired
+ private BBInputSetupUtils bbInputSetupUtils;
+
+ @Autowired
+ private BBInputSetupMapperLayer mapperLayer;
+
+ @Autowired
+ private CloudInfoFromAAI cloudInfoFromAAI;
+
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ public BBInputSetupUtils getBbInputSetupUtils() {
+ return bbInputSetupUtils;
+ }
+
+ public void setCloudInfoFromAAI(CloudInfoFromAAI cloudInfoFromAAI) {
+ this.cloudInfoFromAAI = cloudInfoFromAAI;
+ }
+
+ public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) {
+ this.bbInputSetupUtils = bbInputSetupUtils;
+ }
+
+ public BBInputSetupMapperLayer getMapperLayer() {
+ return mapperLayer;
+ }
+
+ public void setMapperLayer(BBInputSetupMapperLayer mapperLayer) {
+ this.mapperLayer = mapperLayer;
+ }
+
+ @Override
+ public void execute(DelegateExecution execution) throws Exception {
+ try {
+ GeneralBuildingBlock outputBB = null;
+ ExecuteBuildingBlock executeBB = this.getExecuteBBFromExecution(execution);
+ String resourceId = executeBB.getResourceId();
+ String requestAction = executeBB.getRequestAction();
+ String vnfType = executeBB.getVnfType();
+ boolean aLaCarte = Boolean.TRUE.equals(executeBB.isaLaCarte());
+ boolean homing = Boolean.TRUE.equals(executeBB.isHoming());
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ outputBB = this.getGBB(executeBB, lookupKeyMap, requestAction, aLaCarte, resourceId, vnfType);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.INDENT_OUTPUT);
+ logger.debug("GeneralBB: " + mapper.writeValueAsString(outputBB));
+
+ setHomingFlag(outputBB, homing, lookupKeyMap);
+
+ execution.setVariable(FLOW_VAR_NAME, executeBB.getBuildingBlock().getBpmnFlowName());
+ execution.setVariable(GBB_INPUT_VAR_NAME, outputBB);
+ execution.setVariable(LOOKUP_KEY_MAP_VAR_NAME, lookupKeyMap);
+
+ BuildingBlockExecution gBuildingBlockExecution = new DelegateExecutionImpl(execution);
+ execution.setVariable("gBuildingBlockExecution", gBuildingBlockExecution);
+ execution.setVariable("RetryCount", 1);
+ execution.setVariable("handlingCode", "Success");
+ } catch (Exception e) {
+ logger.error("Exception occurred", e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e.getMessage());
+ }
+ }
+
+ protected void setHomingFlag(GeneralBuildingBlock outputBB, boolean homing, Map<ResourceKey, String> lookupKeyMap) {
+
+ if (lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID) != null && homing && outputBB != null) {
+ for (GenericVnf vnf : outputBB.getCustomer().getServiceSubscription().getServiceInstances().get(0)
+ .getVnfs()) {
+ if (vnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
+ vnf.setCallHoming(homing);
+ }
+ }
+ }
+ }
+
+ protected ExecuteBuildingBlock getExecuteBBFromExecution(DelegateExecution execution) {
+ return (ExecuteBuildingBlock) execution.getVariable(EXECUTE_BB_VAR_NAME);
+ }
+
+ protected GeneralBuildingBlock getGBB(ExecuteBuildingBlock executeBB, Map<ResourceKey, String> lookupKeyMap,
+ String requestAction, boolean aLaCarte, String resourceId, String vnfType) throws Exception {
+ String requestId = executeBB.getRequestId();
+ this.populateLookupKeyMapWithIds(executeBB.getWorkflowResourceIds(), lookupKeyMap);
+ RequestDetails requestDetails = executeBB.getRequestDetails();
+ if (requestDetails == null) {
+ requestDetails = bbInputSetupUtils.getRequestDetails(requestId);
+ }
+ if (requestDetails.getModelInfo() == null) {
+ return this.getGBBCM(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId);
+ } else {
+ ModelType modelType = requestDetails.getModelInfo().getModelType();
+ if (aLaCarte && modelType.equals(ModelType.service)) {
+ return this.getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId);
+ } else if (aLaCarte && !modelType.equals(ModelType.service)) {
+ return this.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId,
+ vnfType);
+ } else {
+ return this.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ }
+ }
+ }
+
+ protected void populateLookupKeyMapWithIds(WorkflowResourceIds workflowResourceIds,
+ Map<ResourceKey, String> lookupKeyMap) {
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, workflowResourceIds.getServiceInstanceId());
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, workflowResourceIds.getNetworkId());
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, workflowResourceIds.getVnfId());
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, workflowResourceIds.getVfModuleId());
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, workflowResourceIds.getVolumeGroupId());
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, workflowResourceIds.getConfigurationId());
+ lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, workflowResourceIds.getInstanceGroupId());
+ }
+
+ protected GeneralBuildingBlock getGBBALaCarteNonService(ExecuteBuildingBlock executeBB,
+ RequestDetails requestDetails, Map<ResourceKey, String> lookupKeyMap, String requestAction,
+ String resourceId, String vnfType) throws Exception {
+ String bbName = executeBB.getBuildingBlock().getBpmnFlowName();
+ String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID);
+ org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = null;
+ if (serviceInstanceId != null) {
+ aaiServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
+ }
+ Service service = null;
+ if (aaiServiceInstance != null) {
+ service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
+ }
+ if (aaiServiceInstance != null && service != null) {
+ ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance);
+ serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service));
+ this.populateObjectsOnAssignAndCreateFlows(requestDetails, service, bbName, serviceInstance, lookupKeyMap,
+ resourceId, vnfType, executeBB.getBuildingBlock().getKey(),
+ executeBB.getConfigurationResourceKeys());
+ return this.populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction,
+ null);
+ } else {
+ logger.debug("Related Service Instance from AAI: {}", aaiServiceInstance);
+ logger.debug("Related Service Instance Model Info from AAI: {}", service);
+ throw new Exception("Could not find relevant information for related Service Instance");
+ }
+ }
+
+ protected GeneralBuildingBlock getGBBCM(ExecuteBuildingBlock executeBB, RequestDetails requestDetails,
+ Map<ResourceKey, String> lookupKeyMap, String requestAction, String resourceId) throws Exception {
+ ServiceInstance serviceInstance = new ServiceInstance();
+ String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID);
+ serviceInstance.setServiceInstanceId(serviceInstanceId);
+ Customer customer = new Customer();
+ List<GenericVnf> genericVnfs = serviceInstance.getVnfs();
+
+ String vnfId = lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID);
+ if (vnfId != null) {
+ org.onap.aai.domain.yang.GenericVnf aaiGenericVnf = bbInputSetupUtils.getAAIGenericVnf(vnfId);
+ GenericVnf genericVnf = this.mapperLayer.mapAAIGenericVnfIntoGenericVnf(aaiGenericVnf);
+ genericVnfs.add(genericVnf);
+ }
+
+ String instanceGroupId = lookupKeyMap.get(ResourceKey.INSTANCE_GROUP_ID);
+ if (instanceGroupId != null) {
+ org.onap.aai.domain.yang.InstanceGroup aaiInstancegroup =
+ bbInputSetupUtils.getAAIInstanceGroup(instanceGroupId);
+ InstanceGroup instanceGroup = this.mapperLayer.mapAAIInstanceGroupIntoInstanceGroup(aaiInstancegroup);
+ instanceGroup.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
+
+ if (serviceInstanceId == null) {
+ Optional<org.onap.aai.domain.yang.ServiceInstance> aaiServiceInstanceOpt =
+ bbInputSetupUtils.getRelatedServiceInstanceFromInstanceGroup(instanceGroupId);
+ if (aaiServiceInstanceOpt.isPresent()) {
+ org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = aaiServiceInstanceOpt.get();
+ serviceInstance = this.mapperLayer.mapAAIServiceInstanceIntoServiceInstance(aaiServiceInstance);
+ WorkflowResourceIds workflowResourceIds = executeBB.getWorkflowResourceIds();
+ workflowResourceIds.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, workflowResourceIds.getServiceInstanceId());
+ } else {
+ throw new NoServiceInstanceFoundException("Related ServiceInstance not found in A&AI.");
+ }
+ }
+ RelatedInstanceList[] relatedInstanceList = requestDetails.getRelatedInstanceList();
+ if (relatedInstanceList != null) {
+ for (RelatedInstanceList relatedInstList : relatedInstanceList) {
+ RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
+ if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
+ org.onap.aai.domain.yang.GenericVnf aaiVnf =
+ bbInputSetupUtils.getAAIGenericVnf(relatedInstance.getInstanceId());
+ GenericVnf vnf = this.mapperLayer.mapAAIGenericVnfIntoGenericVnf(aaiVnf);
+ instanceGroup.getVnfs().add(vnf);
+ }
+ }
+ }
+
+ serviceInstance.getInstanceGroups().add(instanceGroup);
+ customer.setServiceSubscription(new ServiceSubscription());
+ }
+ return this.populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction,
+ customer);
+ }
+
+ protected void populateObjectsOnAssignAndCreateFlows(RequestDetails requestDetails, Service service, String bbName,
+ ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId, String vnfType,
+ String configurationKey, ConfigurationResourceKeys configurationResourceKeys) throws Exception {
+ ModelInfo modelInfo = requestDetails.getModelInfo();
+ String instanceName = requestDetails.getRequestInfo().getInstanceName();
+ String productFamilyId = requestDetails.getRequestInfo().getProductFamilyId();
+ ModelType modelType = modelInfo.getModelType();
+ RelatedInstanceList[] relatedInstanceList = requestDetails.getRelatedInstanceList();
+
+ org.onap.so.serviceinstancebeans.Platform platform = requestDetails.getPlatform();
+ org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness = requestDetails.getLineOfBusiness();
+
+ if (modelType.equals(ModelType.network)) {
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, resourceId);
+ this.populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
+ null);
+ } else if (modelType.equals(ModelType.vnf)) {
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, resourceId);
+ this.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance,
+ lookupKeyMap, relatedInstanceList, resourceId, vnfType, null, productFamilyId);
+ } else if (modelType.equals(ModelType.volumeGroup)) {
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, resourceId);
+ this.populateVolumeGroup(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
+ relatedInstanceList, instanceName, vnfType, null);
+ } else if (modelType.equals(ModelType.vfModule)) {
+ if (bbName.contains("Configuration")) {
+ String configurationId = lookupKeyMap.get(ResourceKey.CONFIGURATION_ID);
+ ModelInfo configurationModelInfo = new ModelInfo();
+ configurationModelInfo.setModelCustomizationUuid(configurationKey);
+ populateConfiguration(configurationModelInfo, service, bbName, serviceInstance, lookupKeyMap,
+ configurationId, instanceName, configurationResourceKeys);
+ } else {
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, resourceId);
+ this.populateVfModule(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
+ relatedInstanceList, instanceName, null, requestDetails.getCloudConfiguration());
+ }
+ } else if (modelType.equals(ModelType.instanceGroup)) {
+ lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, resourceId);
+ this.populateInstanceGroup(modelInfo, service, serviceInstance, resourceId, instanceName);
+ } else {
+ return;
+ }
+ }
+
+ protected void populateInstanceGroup(ModelInfo modelInfo, Service service, ServiceInstance serviceInstance,
+ String instanceGroupId, String instanceName) {
+ InstanceGroup instanceGroup = new InstanceGroup();
+ instanceGroup.setId(instanceGroupId);
+ instanceGroup.setInstanceGroupName(instanceName);
+ mapCatalogInstanceGroup(instanceGroup, modelInfo, service);
+ serviceInstance.getInstanceGroups().add(instanceGroup);
+ }
+
+ protected void mapCatalogInstanceGroup(InstanceGroup instanceGroup, ModelInfo modelInfo, Service service) {
+ // @TODO: this will populate the instanceGroup model info.
+ // Dependent on MSO-5821 653458 US - MSO - Enhance Catalog DB Schema & Adapter to support VNF Groups
+ }
+
+ protected void populateConfiguration(ModelInfo modelInfo, Service service, String bbName,
+ ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId,
+ String instanceName, ConfigurationResourceKeys configurationResourceKeys) {
+ Configuration configuration = null;
+ for (Configuration configurationTemp : serviceInstance.getConfigurations()) {
+ if (lookupKeyMap.get(ResourceKey.CONFIGURATION_ID) != null && configurationTemp.getConfigurationId()
+ .equalsIgnoreCase(lookupKeyMap.get(ResourceKey.CONFIGURATION_ID))) {
+ configuration = configurationTemp;
+ org.onap.aai.domain.yang.Configuration aaiConfiguration =
+ bbInputSetupUtils.getAAIConfiguration(configuration.getConfigurationId());
+ if (aaiConfiguration != null) {
+ modelInfo.setModelCustomizationUuid(aaiConfiguration.getModelCustomizationId());
+ }
+ }
+ }
+ if (configuration == null && bbName.equalsIgnoreCase(AssignFlows.FABRIC_CONFIGURATION.toString())) {
+ configuration = this.createConfiguration(lookupKeyMap, instanceName, resourceId);
+ serviceInstance.getConfigurations().add(configuration);
+ }
+ if (configuration != null) {
+ Vnfc vnfc = getVnfcToConfiguration(configurationResourceKeys.getVnfcName());
+ configuration.setVnfc(vnfc);
+ this.mapCatalogConfiguration(configuration, modelInfo, service, configurationResourceKeys);
+ }
+ }
+
+ protected Vnfc getVnfcToConfiguration(String vnfcName) {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VNFC, vnfcName);
+ Optional<org.onap.aai.domain.yang.Vnfc> vnfcOp =
+ bbInputSetupUtils.getAAIResourceDepthOne(uri).asBean(org.onap.aai.domain.yang.Vnfc.class);
+ if (vnfcOp.isPresent()) {
+ org.onap.aai.domain.yang.Vnfc vnfcAAI = vnfcOp.get();
+ return this.mapperLayer.mapAAIVnfc(vnfcAAI);
+ } else {
+ return null;
+ }
+ }
+
+ protected Configuration createConfiguration(Map<ResourceKey, String> lookupKeyMap, String instanceName,
+ String resourceId) {
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, resourceId);
+ Configuration configuration = new Configuration();
+ configuration.setConfigurationId(resourceId);
+ configuration.setConfigurationName(instanceName);
+ configuration.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ return configuration;
+ }
+
+ protected void mapCatalogConfiguration(Configuration configuration, ModelInfo modelInfo, Service service,
+ ConfigurationResourceKeys configurationResourceKeys) {
+ ConfigurationResourceCustomization configurationResourceCustomization =
+ findConfigurationResourceCustomization(modelInfo, service);
+ CvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization =
+ findVnfVfmoduleCvnfcConfigurationCustomization(service.getModelUUID(),
+ configurationResourceKeys.getVfModuleCustomizationUUID(),
+ configurationResourceKeys.getVnfResourceCustomizationUUID(),
+ configurationResourceKeys.getCvnfcCustomizationUUID(), configurationResourceCustomization);
+ if (configurationResourceCustomization != null && vnfVfmoduleCvnfcConfigurationCustomization != null) {
+ configuration.setModelInfoConfiguration(this.mapperLayer.mapCatalogConfigurationToConfiguration(
+ configurationResourceCustomization, vnfVfmoduleCvnfcConfigurationCustomization));
+ } else {
+ logger.debug("for Fabric configuration mapping by VF MODULE CUST UUID: "
+ + configurationResourceKeys.getVfModuleCustomizationUUID());
+ vnfVfmoduleCvnfcConfigurationCustomization = findVnfVfmoduleCvnfcConfigurationCustomization(
+ service.getModelUUID(), configurationResourceKeys.getVnfResourceCustomizationUUID(),
+ configurationResourceKeys.getVfModuleCustomizationUUID(),
+ configurationResourceKeys.getCvnfcCustomizationUUID());
+ if (vnfVfmoduleCvnfcConfigurationCustomization != null) {
+ configuration.setModelInfoConfiguration(this.mapperLayer
+ .mapCatalogConfigurationToConfiguration(vnfVfmoduleCvnfcConfigurationCustomization));
+ }
+ }
+ }
+
+ protected CvnfcConfigurationCustomization findVnfVfmoduleCvnfcConfigurationCustomization(String serviceModelUUID,
+ String vfModuleCustomizationUUID, String vnfResourceCustomizationUUID, String cvnfcCustomizationUUID,
+ ConfigurationResourceCustomization configurationResourceCustomization) {
+ return bbInputSetupUtils.getCvnfcConfigurationCustomization(serviceModelUUID, vnfResourceCustomizationUUID,
+ vfModuleCustomizationUUID, cvnfcCustomizationUUID);
+ }
+
+ protected ConfigurationResourceCustomization findConfigurationResourceCustomization(ModelInfo modelInfo,
+ Service service) {
+ for (ConfigurationResourceCustomization resourceCust : service.getConfigurationCustomizations()) {
+ if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(modelInfo.getModelCustomizationUuid())) {
+ return resourceCust;
+ }
+ }
+ return null;
+ }
+
+ protected CvnfcConfigurationCustomization findVnfVfmoduleCvnfcConfigurationCustomization(String serviceModelUUID,
+ String vnfResourceCustomizationUUID, String vfModuleCustomizationUUID, String cvnfcCustomizationUUID) {
+ return bbInputSetupUtils.getCvnfcConfigurationCustomization(serviceModelUUID, vnfResourceCustomizationUUID,
+ vfModuleCustomizationUUID, cvnfcCustomizationUUID);
+ }
+
+ protected void populateVfModule(ModelInfo modelInfo, Service service, String bbName,
+ ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId,
+ RelatedInstanceList[] relatedInstanceList, String instanceName, List<Map<String, String>> instanceParams,
+ CloudConfiguration cloudConfiguration) throws Exception {
+ String vnfModelCustomizationUUID = null;
+ if (relatedInstanceList != null) {
+ for (RelatedInstanceList relatedInstList : relatedInstanceList) {
+ RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
+ if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
+ vnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId();
+ }
+ if (relatedInstance.getModelInfo().getModelType().equals(ModelType.volumeGroup)) {
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, relatedInstance.getInstanceId());
+ }
+ }
+ }
+ GenericVnf vnf = null;
+ for (GenericVnf tempVnf : serviceInstance.getVnfs()) {
+ if (tempVnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
+ vnf = tempVnf;
+ vnfModelCustomizationUUID =
+ this.bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId()).getModelCustomizationId();
+ ModelInfo vnfModelInfo = new ModelInfo();
+ vnfModelInfo.setModelCustomizationUuid(vnfModelCustomizationUUID);
+ this.mapCatalogVnf(tempVnf, vnfModelInfo, service);
+ Optional<String> volumeGroupIdOp = getVolumeGroupIdRelatedToVfModule(tempVnf, modelInfo,
+ cloudConfiguration.getCloudOwner(), cloudConfiguration.getLcpCloudRegionId(), lookupKeyMap);
+ if (volumeGroupIdOp.isPresent()) {
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupIdOp.get());
+ }
+ break;
+ }
+ }
+ if (vnf != null) {
+ VfModule vfModule = null;
+ for (VfModule vfModuleTemp : vnf.getVfModules()) {
+ if (lookupKeyMap.get(ResourceKey.VF_MODULE_ID) != null
+ && vfModuleTemp.getVfModuleId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.VF_MODULE_ID))) {
+ vfModule = vfModuleTemp;
+ }
+ String vfModuleCustId = bbInputSetupUtils.getAAIVfModule(vnf.getVnfId(), vfModuleTemp.getVfModuleId())
+ .getModelCustomizationId();
+ ModelInfo modelInfoVfModule = new ModelInfo();
+ modelInfoVfModule.setModelCustomizationId(vfModuleCustId);
+ mapCatalogVfModule(vfModuleTemp, modelInfoVfModule, service, vnfModelCustomizationUUID);
+ }
+ if (vfModule == null && bbName.equalsIgnoreCase(AssignFlows.VF_MODULE.toString())) {
+ vfModule = createVfModule(lookupKeyMap, resourceId, instanceName, instanceParams);
+ vnf.getVfModules().add(vfModule);
+ mapCatalogVfModule(vfModule, modelInfo, service, vnfModelCustomizationUUID);
+ }
+ } else {
+ logger.debug("Related VNF instance Id not found: {}", lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID));
+ throw new Exception("Could not find relevant information for related VNF");
+ }
+ }
+
+ protected Optional<String> getVolumeGroupIdRelatedToVfModule(GenericVnf vnf, ModelInfo modelInfo, String cloudOwner,
+ String cloudRegionId, Map<ResourceKey, String> lookupKeyMap) {
+ if (lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID) == null) {
+ for (VolumeGroup volumeGroup : vnf.getVolumeGroups()) {
+ String volumeGroupCustId =
+ bbInputSetupUtils.getAAIVolumeGroup(cloudOwner, cloudRegionId, volumeGroup.getVolumeGroupId())
+ .getModelCustomizationId();
+ if (modelInfo.getModelCustomizationId().equalsIgnoreCase(volumeGroupCustId)) {
+ return Optional.of(volumeGroup.getVolumeGroupId());
+ }
+ }
+ }
+ return Optional.empty();
+ }
+
+ protected void mapCatalogVfModule(VfModule vfModule, ModelInfo modelInfo, Service service,
+ String vnfModelCustomizationUUID) {
+ if (modelInfo.getModelCustomizationUuid() != null) {
+ modelInfo.setModelCustomizationId(modelInfo.getModelCustomizationUuid());
+ }
+ VnfResourceCustomization vnfResourceCustomization = null;
+ for (VnfResourceCustomization resourceCust : service.getVnfCustomizations()) {
+ if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(vnfModelCustomizationUUID)) {
+ vnfResourceCustomization = resourceCust;
+ break;
+ }
+ }
+ if (vnfResourceCustomization != null) {
+ VfModuleCustomization vfResourceCustomization = vnfResourceCustomization.getVfModuleCustomizations()
+ .stream() // Convert to steam
+ .filter(x -> modelInfo.getModelCustomizationId().equalsIgnoreCase(x.getModelCustomizationUUID()))// find
+ // what
+ // we
+ // want
+ .findAny() // If 'findAny' then return found
+ .orElse(null);
+ if (vfResourceCustomization != null) {
+ vfModule.setModelInfoVfModule(this.mapperLayer.mapCatalogVfModuleToVfModule(vfResourceCustomization));
+ }
+ }
+ }
+
+ protected VfModule createVfModule(Map<ResourceKey, String> lookupKeyMap, String vfModuleId, String instanceName,
+ List<Map<String, String>> instanceParams) {
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, vfModuleId);
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId(vfModuleId);
+ vfModule.setVfModuleName(instanceName);
+ vfModule.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ if (instanceParams != null) {
+ for (Map<String, String> params : instanceParams) {
+ vfModule.getCloudParams().putAll(params);
+ }
+ }
+ return vfModule;
+ }
+
+ protected void populateVolumeGroup(ModelInfo modelInfo, Service service, String bbName,
+ ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId,
+ RelatedInstanceList[] relatedInstanceList, String instanceName, String vnfType,
+ List<Map<String, String>> instanceParams) throws Exception {
+ VolumeGroup volumeGroup = null;
+ GenericVnf vnf = null;
+ String vnfModelCustomizationUUID = null;
+ String generatedVnfType = vnfType;
+ if (generatedVnfType == null || generatedVnfType.isEmpty()) {
+ generatedVnfType = service.getModelName() + "/" + modelInfo.getModelCustomizationName();
+ }
+ if (relatedInstanceList != null) {
+ for (RelatedInstanceList relatedInstList : relatedInstanceList) {
+ RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
+ if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
+ vnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationUuid();
+ break;
+ }
+ }
+ }
+ for (GenericVnf tempVnf : serviceInstance.getVnfs()) {
+ if (tempVnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
+ vnf = tempVnf;
+ vnfModelCustomizationUUID =
+ bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId()).getModelCustomizationId();
+ ModelInfo vnfModelInfo = new ModelInfo();
+ vnfModelInfo.setModelCustomizationUuid(vnfModelCustomizationUUID);
+ mapCatalogVnf(tempVnf, vnfModelInfo, service);
+ break;
+ }
+ }
+ if (vnf != null && vnfModelCustomizationUUID != null) {
+ for (VolumeGroup volumeGroupTemp : vnf.getVolumeGroups()) {
+ if (lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID) != null && volumeGroupTemp.getVolumeGroupId()
+ .equalsIgnoreCase(lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID))) {
+ volumeGroup = volumeGroupTemp;
+ break;
+ }
+ }
+ if (volumeGroup == null && bbName.equalsIgnoreCase(AssignFlows.VOLUME_GROUP.toString())) {
+ volumeGroup =
+ createVolumeGroup(lookupKeyMap, resourceId, instanceName, generatedVnfType, instanceParams);
+ vnf.getVolumeGroups().add(volumeGroup);
+ }
+ if (volumeGroup != null) {
+ mapCatalogVolumeGroup(volumeGroup, modelInfo, service, vnfModelCustomizationUUID);
+ }
+ } else {
+ logger.debug("Related VNF instance Id not found: {}", lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID));
+ throw new Exception("Could not find relevant information for related VNF");
+ }
+ }
+
+ protected VolumeGroup createVolumeGroup(Map<ResourceKey, String> lookupKeyMap, String volumeGroupId,
+ String instanceName, String vnfType, List<Map<String, String>> instanceParams) {
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupId);
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId(volumeGroupId);
+ volumeGroup.setVolumeGroupName(instanceName);
+ volumeGroup.setVnfType(vnfType);
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ if (instanceParams != null) {
+ for (Map<String, String> params : instanceParams) {
+ volumeGroup.getCloudParams().putAll(params);
+ }
+ }
+ return volumeGroup;
+ }
+
+ protected void mapCatalogVolumeGroup(VolumeGroup volumeGroup, ModelInfo modelInfo, Service service,
+ String vnfModelCustomizationUUID) {
+ VfModuleCustomization vfResourceCustomization =
+ getVfResourceCustomization(modelInfo, service, vnfModelCustomizationUUID);
+ if (vfResourceCustomization != null) {
+ volumeGroup.setModelInfoVfModule(this.mapperLayer.mapCatalogVfModuleToVfModule(vfResourceCustomization));
+ }
+ }
+
+ protected VfModuleCustomization getVfResourceCustomization(ModelInfo modelInfo, Service service,
+ String vnfModelCustomizationUUID) {
+ VnfResourceCustomization vnfResourceCustomization = null;
+ for (VnfResourceCustomization resourceCust : service.getVnfCustomizations()) {
+ if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(vnfModelCustomizationUUID)) {
+ vnfResourceCustomization = resourceCust;
+ break;
+ }
+ }
+ if (vnfResourceCustomization != null) {
+ for (VfModuleCustomization vfResourceCust : vnfResourceCustomization.getVfModuleCustomizations()) {
+ if (vfResourceCust.getModelCustomizationUUID()
+ .equalsIgnoreCase(modelInfo.getModelCustomizationUuid())) {
+ return vfResourceCust;
+ }
+ }
+
+ }
+ return null;
+ }
+
+ protected void populateGenericVnf(ModelInfo modelInfo, String instanceName,
+ org.onap.so.serviceinstancebeans.Platform platform,
+ org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness, Service service, String bbName,
+ ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap,
+ RelatedInstanceList[] relatedInstanceList, String resourceId, String vnfType,
+ List<Map<String, String>> instanceParams, String productFamilyId) {
+ GenericVnf vnf = null;
+ ModelInfo instanceGroupModelInfo = null;
+ String instanceGroupId = null;
+ String generatedVnfType = vnfType;
+ if (generatedVnfType == null || generatedVnfType.isEmpty()) {
+ generatedVnfType = service.getModelName() + "/" + modelInfo.getModelCustomizationName();
+ }
+ if (relatedInstanceList != null) {
+ for (RelatedInstanceList relatedInstList : relatedInstanceList) {
+ RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
+ if (relatedInstance.getModelInfo().getModelType().equals(ModelType.networkInstanceGroup)) {
+ instanceGroupModelInfo = relatedInstance.getModelInfo();
+ instanceGroupId = relatedInstance.getInstanceId();
+ }
+ }
+ }
+ for (GenericVnf vnfTemp : serviceInstance.getVnfs()) {
+ if (lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID) != null
+ && vnfTemp.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
+ String vnfModelCustId =
+ bbInputSetupUtils.getAAIGenericVnf(vnfTemp.getVnfId()).getModelCustomizationId();
+ modelInfo.setModelCustomizationUuid(vnfModelCustId);
+ vnf = vnfTemp;
+ break;
+ }
+ }
+ if (vnf == null && bbName.equalsIgnoreCase(AssignFlows.VNF.toString())) {
+ vnf = createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness, resourceId, generatedVnfType,
+ instanceParams, productFamilyId);
+ serviceInstance.getVnfs().add(vnf);
+ mapVnfcCollectionInstanceGroup(vnf, modelInfo, service);
+ }
+ if (vnf != null) {
+ mapCatalogVnf(vnf, modelInfo, service);
+ if (instanceGroupId != null && instanceGroupModelInfo != null
+ && instanceGroupModelInfo.getModelType().equals(ModelType.networkInstanceGroup)
+ && !instanceGroupInList(vnf, instanceGroupId)) {
+ mapNetworkCollectionInstanceGroup(vnf, instanceGroupId);
+ }
+ }
+ }
+
+ protected boolean instanceGroupInList(GenericVnf vnf, String instanceGroupId) {
+ for (InstanceGroup instanceGroup : vnf.getInstanceGroups()) {
+ if (instanceGroup.getId() != null && instanceGroup.getId().equalsIgnoreCase(instanceGroupId)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ protected void mapVnfcCollectionInstanceGroup(GenericVnf genericVnf, ModelInfo modelInfo, Service service) {
+ VnfResourceCustomization vnfResourceCustomization = getVnfResourceCustomizationFromService(modelInfo, service);
+ if (vnfResourceCustomization != null) {
+ List<VnfcInstanceGroupCustomization> vnfcInstanceGroups =
+ vnfResourceCustomization.getVnfcInstanceGroupCustomizations();
+ for (VnfcInstanceGroupCustomization vnfcInstanceGroupCust : vnfcInstanceGroups) {
+ InstanceGroup instanceGroup = this.createInstanceGroup();
+ org.onap.so.db.catalog.beans.InstanceGroup catalogInstanceGroup = bbInputSetupUtils
+ .getCatalogInstanceGroup(vnfcInstanceGroupCust.getInstanceGroup().getModelUUID());
+ instanceGroup.setModelInfoInstanceGroup(
+ this.mapperLayer.mapCatalogInstanceGroupToInstanceGroup(null, catalogInstanceGroup));
+ instanceGroup.getModelInfoInstanceGroup().setFunction(vnfcInstanceGroupCust.getFunction());
+ instanceGroup.setDescription(vnfcInstanceGroupCust.getDescription());
+ genericVnf.getInstanceGroups().add(instanceGroup);
+ }
+ }
+ }
+
+ protected void mapNetworkCollectionInstanceGroup(GenericVnf genericVnf, String instanceGroupId) {
+ org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup =
+ bbInputSetupUtils.getAAIInstanceGroup(instanceGroupId);
+ InstanceGroup instanceGroup = this.mapperLayer.mapAAIInstanceGroupIntoInstanceGroup(aaiInstanceGroup);
+ instanceGroup.setModelInfoInstanceGroup(this.mapperLayer.mapCatalogInstanceGroupToInstanceGroup(null,
+ this.bbInputSetupUtils.getCatalogInstanceGroup(aaiInstanceGroup.getModelVersionId())));
+ genericVnf.getInstanceGroups().add(instanceGroup);
+ }
+
+ protected GenericVnf createGenericVnf(Map<ResourceKey, String> lookupKeyMap, String instanceName,
+ org.onap.so.serviceinstancebeans.Platform platform,
+ org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness, String vnfId, String vnfType,
+ List<Map<String, String>> instanceParams, String productFamilyId) {
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnfId);
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId(vnfId);
+ genericVnf.setVnfName(instanceName);
+ genericVnf.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ genericVnf.setVnfType(vnfType);
+ genericVnf.setProvStatus(PREPROV);
+ genericVnf.setServiceId(productFamilyId);
+ if (platform != null) {
+ genericVnf.setPlatform(this.mapperLayer.mapRequestPlatform(platform));
+ }
+ if (lineOfBusiness != null) {
+ genericVnf.setLineOfBusiness(this.mapperLayer.mapRequestLineOfBusiness(lineOfBusiness));
+ }
+ if (instanceParams != null) {
+ for (Map<String, String> params : instanceParams) {
+ genericVnf.getCloudParams().putAll(params);
+ }
+ }
+ return genericVnf;
+ }
+
+ protected void mapCatalogVnf(GenericVnf genericVnf, ModelInfo modelInfo, Service service) {
+ VnfResourceCustomization vnfResourceCustomization = getVnfResourceCustomizationFromService(modelInfo, service);
+ if (vnfResourceCustomization != null) {
+ genericVnf.setModelInfoGenericVnf(this.mapperLayer.mapCatalogVnfToVnf(vnfResourceCustomization));
+ }
+ }
+
+ protected VnfResourceCustomization getVnfResourceCustomizationFromService(ModelInfo modelInfo, Service service) {
+ VnfResourceCustomization vnfResourceCustomization = null;
+ for (VnfResourceCustomization resourceCust : service.getVnfCustomizations()) {
+ if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(modelInfo.getModelCustomizationUuid())) {
+ vnfResourceCustomization = resourceCust;
+ break;
+ }
+ }
+ return vnfResourceCustomization;
+ }
+
+ protected void populateL3Network(String instanceName, ModelInfo modelInfo, Service service, String bbName,
+ ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId,
+ List<Map<String, String>> instanceParams) {
+ L3Network network = null;
+ for (L3Network networkTemp : serviceInstance.getNetworks()) {
+ if (lookupKeyMap.get(ResourceKey.NETWORK_ID) != null
+ && networkTemp.getNetworkId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.NETWORK_ID))) {
+ network = networkTemp;
+ break;
+ }
+ }
+ if (network == null && (bbName.equalsIgnoreCase(AssignFlows.NETWORK_A_LA_CARTE.toString())
+ || bbName.equalsIgnoreCase(AssignFlows.NETWORK_MACRO.toString()))) {
+ network = createNetwork(lookupKeyMap, instanceName, resourceId, instanceParams);
+ serviceInstance.getNetworks().add(network);
+ }
+ if (network != null) {
+ mapCatalogNetwork(network, modelInfo, service);
+ }
+ }
+
+ protected L3Network createNetwork(Map<ResourceKey, String> lookupKeyMap, String instanceName, String networkId,
+ List<Map<String, String>> instanceParams) {
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, networkId);
+ L3Network network = new L3Network();
+ network.setNetworkId(networkId);
+ network.setNetworkName(instanceName);
+ network.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ if (instanceParams != null) {
+ for (Map<String, String> params : instanceParams) {
+ network.getCloudParams().putAll(params);
+ }
+ }
+ return network;
+ }
+
+ protected void mapCatalogNetwork(L3Network network, ModelInfo modelInfo, Service service) {
+ NetworkResourceCustomization networkResourceCustomization = null;
+ for (NetworkResourceCustomization resourceCust : service.getNetworkCustomizations()) {
+ if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(modelInfo.getModelCustomizationUuid())) {
+ networkResourceCustomization = resourceCust;
+ break;
+ }
+ }
+ if (networkResourceCustomization != null) {
+ network.setModelInfoNetwork(this.mapperLayer.mapCatalogNetworkToNetwork(networkResourceCustomization));
+ }
+ }
+
+ protected GeneralBuildingBlock getGBBALaCarteService(ExecuteBuildingBlock executeBB, RequestDetails requestDetails,
+ Map<ResourceKey, String> lookupKeyMap, String requestAction, String resourceId) throws Exception {
+ Customer customer = getCustomerAndServiceSubscription(requestDetails, resourceId);
+ if (customer != null) {
+ Project project = null;
+ OwningEntity owningEntity = null;
+
+ if (requestDetails.getProject() != null)
+ project = mapperLayer.mapRequestProject(requestDetails.getProject());
+ if (requestDetails.getOwningEntity() != null)
+ owningEntity = mapperLayer.mapRequestOwningEntity(requestDetails.getOwningEntity());
+
+
+ Service service =
+ bbInputSetupUtils.getCatalogServiceByModelUUID(requestDetails.getModelInfo().getModelVersionId());
+ if (service == null) {
+ service = bbInputSetupUtils.getCatalogServiceByModelVersionAndModelInvariantUUID(
+ requestDetails.getModelInfo().getModelVersion(),
+ requestDetails.getModelInfo().getModelInvariantId());
+ if (service == null) {
+ throw new Exception("Could not find service for model version Id: "
+ + requestDetails.getModelInfo().getModelVersionId() + " and for model invariant Id: "
+ + requestDetails.getModelInfo().getModelInvariantId());
+ }
+ }
+ ServiceInstance serviceInstance = this.getALaCarteServiceInstance(service, requestDetails, customer,
+ project, owningEntity, lookupKeyMap, resourceId, Boolean.TRUE.equals(executeBB.isaLaCarte()),
+ executeBB.getBuildingBlock().getBpmnFlowName());
+ return this.populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction,
+ customer);
+ } else {
+ throw new Exception("Could not find customer");
+ }
+ }
+
+ protected Customer getCustomerAndServiceSubscription(RequestDetails requestDetails, String resourceId) {
+ Customer customer;
+ if (requestDetails.getSubscriberInfo() != null) {
+ customer = this.getCustomerFromRequest(requestDetails);
+ } else {
+ customer = this.getCustomerFromURI(resourceId);
+ }
+ if (customer != null) {
+ ServiceSubscription serviceSubscription = null;
+ serviceSubscription = getServiceSubscription(requestDetails, customer);
+ if (serviceSubscription == null) {
+ serviceSubscription = getServiceSubscriptionFromURI(resourceId, customer);
+ }
+ customer.setServiceSubscription(serviceSubscription);
+ return customer;
+ } else {
+ return null;
+ }
+ }
+
+ protected ServiceSubscription getServiceSubscriptionFromURI(String resourceId, Customer customer) {
+ Map<String, String> uriKeys = bbInputSetupUtils.getURIKeysFromServiceInstance(resourceId);
+ String subscriptionServiceType = uriKeys.get("service-type");
+ org.onap.aai.domain.yang.ServiceSubscription serviceSubscriptionAAI =
+ bbInputSetupUtils.getAAIServiceSubscription(customer.getGlobalCustomerId(), subscriptionServiceType);
+ if (serviceSubscriptionAAI != null) {
+ return mapperLayer.mapAAIServiceSubscription(serviceSubscriptionAAI);
+ } else {
+ return null;
+ }
+ }
+
+ protected Customer getCustomerFromURI(String resourceId) {
+ Map<String, String> uriKeys = bbInputSetupUtils.getURIKeysFromServiceInstance(resourceId);
+ String globalCustomerId = uriKeys.get("global-customer-id");
+ org.onap.aai.domain.yang.Customer customerAAI = this.bbInputSetupUtils.getAAICustomer(globalCustomerId);
+ if (customerAAI != null) {
+ return mapperLayer.mapAAICustomer(customerAAI);
+ } else {
+ return null;
+ }
+ }
+
+ protected GeneralBuildingBlock populateGBBWithSIAndAdditionalInfo(RequestDetails requestDetails,
+ ServiceInstance serviceInstance, ExecuteBuildingBlock executeBB, String requestAction, Customer customer)
+ throws Exception {
+ GeneralBuildingBlock outputBB = new GeneralBuildingBlock();
+ OrchestrationContext orchContext = mapperLayer.mapOrchestrationContext(requestDetails);
+ RequestContext requestContext = mapperLayer.mapRequestContext(requestDetails);
+ requestContext.setAction(requestAction);
+ requestContext.setMsoRequestId(executeBB.getRequestId());
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion =
+ bbInputSetupUtils.getCloudRegion(requestDetails.getCloudConfiguration());
+ CloudRegion cloudRegion = mapperLayer.mapCloudRegion(requestDetails.getCloudConfiguration(), aaiCloudRegion);
+ Tenant tenant = getTenant(requestDetails.getCloudConfiguration(), aaiCloudRegion);
+ outputBB.setOrchContext(orchContext);
+ outputBB.setRequestContext(requestContext);
+ outputBB.setCloudRegion(cloudRegion);
+ outputBB.setTenant(tenant);
+ if (customer == null) {
+ Map<String, String> uriKeys =
+ bbInputSetupUtils.getURIKeysFromServiceInstance(serviceInstance.getServiceInstanceId());
+ String globalCustomerId = uriKeys.get("global-customer-id");
+ String subscriptionServiceType = uriKeys.get("service-type");
+ customer = mapCustomer(globalCustomerId, subscriptionServiceType);
+ }
+ outputBB.setServiceInstance(serviceInstance);
+ if (customer.getServiceSubscription() != null) {
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ }
+ outputBB.setCustomer(customer);
+ return outputBB;
+ }
+
+ protected Tenant getTenant(CloudConfiguration cloudConfiguration,
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion) throws Exception {
+ Tenant tenant = new Tenant();
+ if (cloudConfiguration != null && cloudConfiguration.getTenantId() != null && aaiCloudRegion != null
+ && aaiCloudRegion.getTenants() != null) {
+ for (org.onap.aai.domain.yang.Tenant aaiTenant : aaiCloudRegion.getTenants().getTenant()) {
+ if (aaiTenant.getTenantId().equalsIgnoreCase(cloudConfiguration.getTenantId())) {
+ tenant = mapperLayer.mapTenant(aaiTenant);
+ }
+ }
+ if (tenant.getTenantId() == null || tenant.getTenantName() == null) {
+ throw new Exception("Invalid tenant information retrieved: tenantId = " + tenant.getTenantId()
+ + " tenantName = " + tenant.getTenantName());
+ }
+ }
+ return tenant;
+ }
+
+ protected ServiceSubscription getServiceSubscription(RequestDetails requestDetails, Customer customer) {
+ org.onap.aai.domain.yang.ServiceSubscription aaiServiceSubscription =
+ bbInputSetupUtils.getAAIServiceSubscription(customer.getGlobalCustomerId(),
+ requestDetails.getRequestParameters().getSubscriptionServiceType());
+ if (aaiServiceSubscription != null) {
+ return mapperLayer.mapAAIServiceSubscription(aaiServiceSubscription);
+ } else {
+ return null;
+ }
+ }
+
+ protected Customer getCustomerFromRequest(RequestDetails requestDetails) {
+ org.onap.aai.domain.yang.Customer aaiCustomer =
+ bbInputSetupUtils.getAAICustomer(requestDetails.getSubscriberInfo().getGlobalSubscriberId());
+ if (aaiCustomer != null) {
+ return mapperLayer.mapAAICustomer(aaiCustomer);
+ } else {
+ return null;
+ }
+ }
+
+ protected ServiceInstance getALaCarteServiceInstance(Service service, RequestDetails requestDetails,
+ Customer customer, Project project, OwningEntity owningEntity, Map<ResourceKey, String> lookupKeyMap,
+ String serviceInstanceId, boolean aLaCarte, String bbName) throws Exception {
+ ServiceInstance serviceInstance = this.getServiceInstanceHelper(requestDetails, customer, project, owningEntity,
+ lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
+ org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = null;
+ if (customer != null && customer.getServiceSubscription() != null) {
+ serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceByIdAndCustomer(customer.getGlobalCustomerId(),
+ customer.getServiceSubscription().getServiceType(), serviceInstanceId);
+ } else {
+ serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
+ }
+ if (serviceInstanceAAI != null
+ && !serviceInstanceAAI.getModelVersionId().equalsIgnoreCase(service.getModelUUID())) {
+ Service tempService =
+ this.bbInputSetupUtils.getCatalogServiceByModelUUID(serviceInstanceAAI.getModelVersionId());
+ if (tempService != null) {
+ serviceInstance
+ .setModelInfoServiceInstance(mapperLayer.mapCatalogServiceIntoServiceInstance(tempService));
+ return serviceInstance;
+ } else {
+ throw new Exception(
+ "Could not find model of existing SI. Service Instance in AAI already exists with different model version id: "
+ + serviceInstanceAAI.getModelVersionId());
+ }
+ }
+ serviceInstance.setModelInfoServiceInstance(mapperLayer.mapCatalogServiceIntoServiceInstance(service));
+ return serviceInstance;
+ }
+
+ protected GeneralBuildingBlock getGBBMacro(ExecuteBuildingBlock executeBB, RequestDetails requestDetails,
+ Map<ResourceKey, String> lookupKeyMap, String requestAction, String resourceId, String vnfType)
+ throws Exception {
+ String bbName = executeBB.getBuildingBlock().getBpmnFlowName();
+ String key = executeBB.getBuildingBlock().getKey();
+
+ if (requestAction.equalsIgnoreCase("deleteInstance") || requestAction.equalsIgnoreCase("unassignInstance")
+ || requestAction.equalsIgnoreCase("activateInstance")
+ || requestAction.equalsIgnoreCase("activateFabricConfiguration")
+ || requestAction.equalsIgnoreCase("recreateInstance")
+ || requestAction.equalsIgnoreCase("replaceInstance")) {
+ return getGBBMacroExistingService(executeBB, lookupKeyMap, bbName, requestAction,
+ requestDetails.getCloudConfiguration());
+ }
+
+ String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID);
+ GeneralBuildingBlock gBB =
+ this.getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction, serviceInstanceId);
+ RequestParameters requestParams = requestDetails.getRequestParameters();
+ Service service = null;
+ if (gBB != null && gBB.getServiceInstance() != null
+ && gBB.getServiceInstance().getModelInfoServiceInstance() != null
+ && gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid() != null) {
+ service = bbInputSetupUtils.getCatalogServiceByModelUUID(
+ gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
+ } else {
+ throw new Exception("Could not get service instance for macro request");
+ }
+ if (requestParams != null && requestParams.getUserParams() != null) {
+ for (Map<String, Object> userParams : requestParams.getUserParams()) {
+ if (userParams.containsKey("service")) {
+ String input = mapper.writeValueAsString(userParams.get("service"));
+ return getGBBMacroUserParams(executeBB, requestDetails, lookupKeyMap, vnfType, bbName, key, gBB,
+ requestParams, service, input);
+ }
+ }
+ }
+ if (requestAction.equalsIgnoreCase("deactivateInstance")) {
+ return gBB;
+ } else if (requestAction.equalsIgnoreCase("createInstance")) {
+ return getGBBMacroNoUserParamsCreate(executeBB, lookupKeyMap, bbName, key, gBB, service);
+ } else {
+ throw new IllegalArgumentException(
+ "No user params on requestAction: assignInstance. Please specify user params.");
+ }
+ }
+
+ protected GeneralBuildingBlock getGBBMacroNoUserParamsCreate(ExecuteBuildingBlock executeBB,
+ Map<ResourceKey, String> lookupKeyMap, String bbName, String key, GeneralBuildingBlock gBB, Service service)
+ throws Exception {
+ ServiceInstance serviceInstance = gBB.getServiceInstance();
+ if (bbName.contains(NETWORK) && !bbName.contains(NETWORK_COLLECTION)) {
+ String networkId = lookupKeyMap.get(ResourceKey.NETWORK_ID);
+ ModelInfo networkModelInfo = new ModelInfo();
+ if ((!Boolean.TRUE.equals(executeBB.getBuildingBlock().getIsVirtualLink()))) {
+ NetworkResourceCustomization networkCust = getNetworkCustomizationByKey(key, service);
+ if (networkCust != null) {
+ networkModelInfo.setModelCustomizationUuid(networkCust.getModelCustomizationUUID());
+ this.populateL3Network(null, networkModelInfo, service, bbName, serviceInstance, lookupKeyMap,
+ networkId, null);
+ } else {
+ logger.debug("Could not find a network customization with key: {}", key);
+ }
+ } else {
+ logger.debug("Orchestrating on Collection Network Resource Customization");
+ CollectionNetworkResourceCustomization collectionNetworkResourceCust =
+ bbInputSetupUtils.getCatalogCollectionNetworkResourceCustByID(key);
+ L3Network l3Network = getVirtualLinkL3Network(lookupKeyMap, bbName, key, networkId,
+ collectionNetworkResourceCust, serviceInstance);
+ NetworkResourceCustomization networkResourceCustomization = mapperLayer
+ .mapCollectionNetworkResourceCustToNetworkResourceCust(collectionNetworkResourceCust);
+ if (l3Network != null) {
+ l3Network.setModelInfoNetwork(mapperLayer.mapCatalogNetworkToNetwork(networkResourceCustomization));
+ }
+ }
+ } else if (bbName.contains("Configuration")) {
+ String configurationId = lookupKeyMap.get(ResourceKey.CONFIGURATION_ID);
+ ModelInfo configurationModelInfo = new ModelInfo();
+ configurationModelInfo.setModelCustomizationUuid(key);
+ this.populateConfiguration(configurationModelInfo, service, bbName, serviceInstance, lookupKeyMap,
+ configurationId, null, executeBB.getConfigurationResourceKeys());
+ }
+ if (executeBB.getWorkflowResourceIds() != null) {
+ this.populateNetworkCollectionAndInstanceGroupAssign(service, bbName, serviceInstance,
+ executeBB.getWorkflowResourceIds().getNetworkCollectionId(), key);
+ }
+ return gBB;
+ }
+
+ protected L3Network getVirtualLinkL3Network(Map<ResourceKey, String> lookupKeyMap, String bbName, String key,
+ String networkId, CollectionNetworkResourceCustomization collectionNetworkResourceCust,
+ ServiceInstance serviceInstance) {
+ if (collectionNetworkResourceCust != null) {
+ if ((bbName.equalsIgnoreCase(AssignFlows.NETWORK_A_LA_CARTE.toString())
+ || bbName.equalsIgnoreCase(AssignFlows.NETWORK_MACRO.toString()))) {
+ L3Network network = createNetwork(lookupKeyMap, null, networkId, null);
+ serviceInstance.getNetworks().add(network);
+ return network;
+ } else {
+ for (L3Network network : serviceInstance.getNetworks()) {
+ if (network.getNetworkId().equalsIgnoreCase(networkId)) {
+ return network;
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ protected NetworkResourceCustomization getNetworkCustomizationByKey(String key, Service service) {
+ for (NetworkResourceCustomization networkCust : service.getNetworkCustomizations()) {
+ if (networkCust.getModelCustomizationUUID().equalsIgnoreCase(key)) {
+ return networkCust;
+ }
+ }
+ return null;
+ }
+
+ protected GeneralBuildingBlock getGBBMacroExistingService(ExecuteBuildingBlock executeBB,
+ Map<ResourceKey, String> lookupKeyMap, String bbName, String requestAction,
+ CloudConfiguration cloudConfiguration) throws Exception {
+ org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = null;
+ String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID);
+ RequestDetails requestDetails = executeBB.getRequestDetails();
+ GeneralBuildingBlock gBB = null;
+ if (serviceInstanceId != null) {
+ aaiServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
+ }
+ Service service = null;
+ if (aaiServiceInstance != null) {
+ service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
+ }
+ if (aaiServiceInstance != null && service != null) {
+ ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance);
+ serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service));
+ gBB = populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, null);
+ } else {
+ logger.debug("Related Service Instance from AAI: {}", aaiServiceInstance);
+ logger.debug("Related Service Instance Model Info from AAI: {}", service);
+ throw new Exception("Could not find relevant information for related Service Instance");
+ }
+ ServiceInstance serviceInstance = gBB.getServiceInstance();
+ CloudRegion cloudRegion = null;
+ if (cloudConfiguration == null) {
+ Optional<CloudRegion> cloudRegionOp = cloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance);
+ if (cloudRegionOp.isPresent()) {
+ cloudRegion = cloudRegionOp.get();
+ }
+ }
+ if (cloudConfiguration != null) {
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = bbInputSetupUtils.getCloudRegion(cloudConfiguration);
+ cloudRegion = mapperLayer.mapCloudRegion(cloudConfiguration, aaiCloudRegion);
+ }
+ gBB.setCloudRegion(cloudRegion);
+ if (bbName.contains(VNF)) {
+ for (GenericVnf genericVnf : serviceInstance.getVnfs()) {
+ if (lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID) != null
+ && genericVnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
+ org.onap.aai.domain.yang.GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(genericVnf.getVnfId());
+ ModelInfo modelInfo = new ModelInfo();
+ if (vnf != null) {
+ modelInfo.setModelCustomizationUuid(vnf.getModelCustomizationId());
+ }
+ this.mapCatalogVnf(genericVnf, modelInfo, service);
+ }
+ }
+ } else if (bbName.contains(VF_MODULE)) {
+ for (GenericVnf vnf : serviceInstance.getVnfs()) {
+ for (VfModule vfModule : vnf.getVfModules()) {
+ if (lookupKeyMap.get(ResourceKey.VF_MODULE_ID) != null
+ && vfModule.getVfModuleId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.VF_MODULE_ID))) {
+ String vnfModelCustomizationUUID =
+ this.bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId()).getModelCustomizationId();
+ ModelInfo vnfModelInfo = new ModelInfo();
+ vnfModelInfo.setModelCustomizationUuid(vnfModelCustomizationUUID);
+ this.mapCatalogVnf(vnf, vnfModelInfo, service);
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnf.getVnfId());
+ String vfModuleCustomizationUUID = this.bbInputSetupUtils
+ .getAAIVfModule(vnf.getVnfId(), vfModule.getVfModuleId()).getModelCustomizationId();
+ ModelInfo vfModuleModelInfo = new ModelInfo();
+ vfModuleModelInfo.setModelCustomizationId(vfModuleCustomizationUUID);
+ this.mapCatalogVfModule(vfModule, vfModuleModelInfo, service, vnfModelCustomizationUUID);
+ if (cloudRegion != null) {
+ Optional<String> volumeGroupIdOp = getVolumeGroupIdRelatedToVfModule(vnf, vfModuleModelInfo,
+ cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), lookupKeyMap);
+ if (volumeGroupIdOp.isPresent()) {
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupIdOp.get());
+ }
+ }
+ break;
+ }
+ }
+ }
+ } else if (bbName.contains(VOLUME_GROUP)) {
+ for (GenericVnf vnf : serviceInstance.getVnfs()) {
+ for (VolumeGroup volumeGroup : vnf.getVolumeGroups()) {
+ if (lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID) != null && volumeGroup.getVolumeGroupId()
+ .equalsIgnoreCase(lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID))) {
+ String vnfModelCustomizationUUID =
+ this.bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId()).getModelCustomizationId();
+ ModelInfo vnfModelInfo = new ModelInfo();
+ vnfModelInfo.setModelCustomizationUuid(vnfModelCustomizationUUID);
+ this.mapCatalogVnf(vnf, vnfModelInfo, service);
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnf.getVnfId());
+ if (cloudRegion != null) {
+ String volumeGroupCustomizationUUID =
+ this.bbInputSetupUtils
+ .getAAIVolumeGroup(cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId())
+ .getModelCustomizationId();
+ ModelInfo volumeGroupModelInfo = new ModelInfo();
+ volumeGroupModelInfo.setModelCustomizationId(volumeGroupCustomizationUUID);
+ this.mapCatalogVolumeGroup(volumeGroup, volumeGroupModelInfo, service,
+ vnfModelCustomizationUUID);
+ }
+ break;
+ }
+ }
+ }
+ } else if (bbName.contains(NETWORK)) {
+ for (L3Network network : serviceInstance.getNetworks()) {
+ if (lookupKeyMap.get(ResourceKey.NETWORK_ID) != null
+ && network.getNetworkId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.NETWORK_ID))) {
+ String networkCustomizationUUID =
+ this.bbInputSetupUtils.getAAIL3Network(network.getNetworkId()).getModelCustomizationId();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationUuid(networkCustomizationUUID);
+ this.mapCatalogNetwork(network, modelInfo, service);
+ break;
+ }
+ }
+ } else if (bbName.contains("Fabric")) {
+ for (Configuration configuration : serviceInstance.getConfigurations()) {
+ if (lookupKeyMap.get(ResourceKey.CONFIGURATION_ID) != null && configuration.getConfigurationId()
+ .equalsIgnoreCase(lookupKeyMap.get(ResourceKey.CONFIGURATION_ID))) {
+ String configurationCustUUID = this.bbInputSetupUtils
+ .getAAIConfiguration(configuration.getConfigurationId()).getModelCustomizationId();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationUuid(configurationCustUUID);
+ this.mapCatalogConfiguration(configuration, modelInfo, service,
+ executeBB.getConfigurationResourceKeys());
+ break;
+ }
+ }
+ }
+ if (executeBB.getWorkflowResourceIds() != null) {
+ this.populateNetworkCollectionAndInstanceGroupAssign(service, bbName, serviceInstance,
+ executeBB.getWorkflowResourceIds().getNetworkCollectionId(), executeBB.getBuildingBlock().getKey());
+ }
+ return gBB;
+ }
+
+ protected GeneralBuildingBlock getGBBMacroUserParams(ExecuteBuildingBlock executeBB, RequestDetails requestDetails,
+ Map<ResourceKey, String> lookupKeyMap, String vnfType, String bbName, String key, GeneralBuildingBlock gBB,
+ RequestParameters requestParams, Service service, String input) throws Exception {
+ ServiceInstance serviceInstance = gBB.getServiceInstance();
+ org.onap.so.serviceinstancebeans.Service serviceMacro =
+ mapper.readValue(input, org.onap.so.serviceinstancebeans.Service.class);
+
+ Resources resources = serviceMacro.getResources();
+ Vnfs vnfs = null;
+ VfModules vfModules = null;
+ Networks networks = null;
+ CloudConfiguration cloudConfiguration = requestDetails.getCloudConfiguration();
+ CloudRegion cloudRegion = getCloudRegionFromMacroRequest(cloudConfiguration, resources);
+ gBB.setCloudRegion(cloudRegion);
+ if (bbName.contains(VNF)) {
+ vnfs = findVnfsByKey(key, resources, vnfs);
+ String vnfId = lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID);
+ // This stores the vnf id in request db to be retrieved later when
+ // working on a vf module or volume group
+ InfraActiveRequests request = this.bbInputSetupUtils.getInfraActiveRequest(executeBB.getRequestId());
+ if (request != null) {
+ this.bbInputSetupUtils.updateInfraActiveRequestVnfId(request, vnfId);
+ }
+ String productFamilyId = requestDetails.getRequestInfo().getProductFamilyId();
+ this.populateGenericVnf(vnfs.getModelInfo(), vnfs.getInstanceName(), vnfs.getPlatform(),
+ vnfs.getLineOfBusiness(), service, bbName, serviceInstance, lookupKeyMap, null, vnfId, vnfType,
+ vnfs.getInstanceParams(), productFamilyId);
+ } else if (bbName.contains(VF_MODULE) || bbName.contains(VOLUME_GROUP)) {
+ Pair<Vnfs, VfModules> vnfsAndVfModules = getVfModulesAndItsVnfsByKey(key, resources);
+ vfModules = vnfsAndVfModules.getValue1();
+ vnfs = vnfsAndVfModules.getValue0();
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, getVnfId(executeBB, lookupKeyMap));
+ if (vnfs == null) {
+ throw new Exception("Could not find Vnf to orchestrate VfModule");
+ }
+ ModelInfo modelInfo = vfModules.getModelInfo();
+ if (bbName.contains(VOLUME_GROUP)) {
+ String volumeGroupId = lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID);
+ this.populateVolumeGroup(modelInfo, service, bbName, serviceInstance, lookupKeyMap, volumeGroupId, null,
+ vfModules.getVolumeGroupInstanceName(), vnfType, vfModules.getInstanceParams());
+ } else {
+ String vfModuleId = lookupKeyMap.get(ResourceKey.VF_MODULE_ID);
+ CloudConfiguration cloudConfig = new CloudConfiguration();
+ cloudConfig.setLcpCloudRegionId(cloudRegion.getLcpCloudRegionId());
+ cloudConfig.setCloudOwner(cloudRegion.getCloudOwner());
+ this.populateVfModule(modelInfo, service, bbName, serviceInstance, lookupKeyMap, vfModuleId, null,
+ vfModules.getInstanceName(), vfModules.getInstanceParams(), cloudConfig);
+ }
+ } else if (bbName.contains(NETWORK)) {
+ networks = findNetworksByKey(key, resources);
+ String networkId = lookupKeyMap.get(ResourceKey.NETWORK_ID);
+ this.populateL3Network(networks.getInstanceName(), networks.getModelInfo(), service, bbName,
+ serviceInstance, lookupKeyMap, networkId, networks.getInstanceParams());
+ } else if (bbName.contains("Configuration")) {
+ String configurationId = lookupKeyMap.get(ResourceKey.CONFIGURATION_ID);
+ ModelInfo configurationModelInfo = new ModelInfo();
+ configurationModelInfo.setModelCustomizationUuid(key);
+ ConfigurationResourceCustomization configurationCust =
+ findConfigurationResourceCustomization(configurationModelInfo, service);
+ if (configurationCust != null) {
+ this.populateConfiguration(configurationModelInfo, service, bbName, serviceInstance, lookupKeyMap,
+ configurationId, null, executeBB.getConfigurationResourceKeys());
+ } else {
+ logger.debug("Could not find a configuration customization with key: {}", key);
+ }
+ }
+ return gBB;
+ }
+
+ protected Networks findNetworksByKey(String key, Resources resources) {
+ for (Networks networks : resources.getNetworks()) {
+ if (networks.getModelInfo().getModelCustomizationId().equalsIgnoreCase(key)) {
+ return networks;
+ }
+ }
+ return null;
+ }
+
+ protected Pair<Vnfs, VfModules> getVfModulesAndItsVnfsByKey(String key, Resources resources) {
+ for (Vnfs vnfs : resources.getVnfs()) {
+ for (VfModules vfModules : vnfs.getVfModules()) {
+ if (vfModules.getModelInfo().getModelCustomizationId().equalsIgnoreCase(key)) {
+ return new Pair<Vnfs, VfModules>(vnfs, vfModules);
+ }
+ }
+ }
+ return null;
+ }
+
+ protected Vnfs findVnfsByKey(String key, Resources resources, Vnfs vnfs) {
+ for (Vnfs tempVnfs : resources.getVnfs()) {
+ if (tempVnfs.getModelInfo().getModelCustomizationId().equalsIgnoreCase(key)) {
+ vnfs = tempVnfs;
+ break;
+ }
+ }
+ return vnfs;
+ }
+
+ protected CloudRegion getCloudRegionFromMacroRequest(CloudConfiguration cloudConfiguration, Resources resources) {
+ if (cloudConfiguration == null) {
+ for (Vnfs vnfs : resources.getVnfs()) {
+ if (cloudConfiguration == null) {
+ cloudConfiguration = vnfs.getCloudConfiguration();
+ } else {
+ break;
+ }
+ for (VfModules vfModules : vnfs.getVfModules()) {
+ if (cloudConfiguration == null) {
+ cloudConfiguration = vfModules.getCloudConfiguration();
+ } else {
+ break;
+ }
+ }
+ }
+ for (Networks networks : resources.getNetworks()) {
+ if (cloudConfiguration == null) {
+ cloudConfiguration = networks.getCloudConfiguration();
+ } else {
+ break;
+ }
+ }
+ }
+ if (cloudConfiguration != null) {
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = bbInputSetupUtils.getCloudRegion(cloudConfiguration);
+ return mapperLayer.mapCloudRegion(cloudConfiguration, aaiCloudRegion);
+ } else {
+ logger.debug("Could not find any cloud configuration for this request.");
+ return null;
+ }
+ }
+
+ protected String getVnfId(ExecuteBuildingBlock executeBB, Map<ResourceKey, String> lookupKeyMap) {
+ String vnfId = lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID);
+ if (vnfId == null) {
+ InfraActiveRequests request = this.bbInputSetupUtils.getInfraActiveRequest(executeBB.getRequestId());
+ vnfId = request.getVnfId();
+ }
+
+ return vnfId;
+ }
+
+ protected String generateRandomUUID() {
+ return UUID.randomUUID().toString();
+ }
+
+ protected ServiceInstance getServiceInstanceHelper(RequestDetails requestDetails, Customer customer,
+ Project project, OwningEntity owningEntity, Map<ResourceKey, String> lookupKeyMap, String serviceInstanceId,
+ boolean aLaCarte, Service service, String bbName) throws Exception {
+ if (requestDetails.getRequestInfo().getInstanceName() == null && aLaCarte
+ && bbName.equalsIgnoreCase(AssignFlows.SERVICE_INSTANCE.toString())) {
+ throw new Exception("Request invalid missing: RequestInfo:InstanceName");
+ } else {
+ org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = null;
+ if (aLaCarte && bbName.equalsIgnoreCase(AssignFlows.SERVICE_INSTANCE.toString())) {
+ serviceInstanceAAI = bbInputSetupUtils
+ .getAAIServiceInstanceByName(requestDetails.getRequestInfo().getInstanceName(), customer);
+ }
+ if (serviceInstanceId != null && serviceInstanceAAI == null) {
+ if (customer != null && customer.getServiceSubscription() != null) {
+ serviceInstanceAAI =
+ bbInputSetupUtils.getAAIServiceInstanceByIdAndCustomer(customer.getGlobalCustomerId(),
+ customer.getServiceSubscription().getServiceType(), serviceInstanceId);
+ } else {
+ serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
+ }
+ }
+ if (serviceInstanceAAI != null) {
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstanceId);
+ return this.getExistingServiceInstance(serviceInstanceAAI);
+ } else {
+ return createServiceInstance(requestDetails, project, owningEntity, lookupKeyMap, serviceInstanceId);
+ }
+ }
+ }
+
+ protected ServiceInstance createServiceInstance(RequestDetails requestDetails, Project project,
+ OwningEntity owningEntity, Map<ResourceKey, String> lookupKeyMap, String serviceInstanceId) {
+ ServiceInstance serviceInstance = new ServiceInstance();
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstanceId);
+ serviceInstance.setServiceInstanceId(serviceInstanceId);
+ if (requestDetails.getRequestInfo() != null) {
+ serviceInstance.setServiceInstanceName(requestDetails.getRequestInfo().getInstanceName());
+ }
+ serviceInstance.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ serviceInstance.setProject(project);
+ serviceInstance.setOwningEntity(owningEntity);
+ return serviceInstance;
+ }
+
+ public ServiceInstance getExistingServiceInstance(org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI)
+ throws Exception {
+ ServiceInstance serviceInstance = mapperLayer.mapAAIServiceInstanceIntoServiceInstance(serviceInstanceAAI);
+ if (serviceInstanceAAI.getRelationshipList() != null
+ && serviceInstanceAAI.getRelationshipList().getRelationship() != null
+ && !serviceInstanceAAI.getRelationshipList().getRelationship().isEmpty()) {
+ addRelationshipsToSI(serviceInstanceAAI, serviceInstance);
+ }
+ return serviceInstance;
+ }
+
+ protected void populateNetworkCollectionAndInstanceGroupAssign(Service service, String bbName,
+ ServiceInstance serviceInstance, String resourceId, String key) throws Exception {
+ if (serviceInstance.getCollection() == null
+ && bbName.equalsIgnoreCase(AssignFlows.NETWORK_COLLECTION.toString())) {
+ Collection collection = this.createCollection(resourceId);
+ serviceInstance.setCollection(collection);
+ this.mapCatalogCollection(service, serviceInstance.getCollection(), key);
+ if (isVlanTagging(service, key)) {
+ InstanceGroup instanceGroup = this.createInstanceGroup();
+ serviceInstance.getCollection().setInstanceGroup(instanceGroup);
+ this.mapCatalogNetworkCollectionInstanceGroup(service,
+ serviceInstance.getCollection().getInstanceGroup(), key);
+ }
+ }
+ }
+
+ protected CollectionResourceCustomization findCatalogNetworkCollection(Service service, String key) {
+ for (CollectionResourceCustomization collectionCust : service.getCollectionResourceCustomizations()) {
+ if (collectionCust.getModelCustomizationUUID().equalsIgnoreCase(key)) {
+ return collectionCust;
+ }
+ }
+ return null;
+ }
+
+ protected boolean isVlanTagging(Service service, String key) {
+ CollectionResourceCustomization collectionCust = findCatalogNetworkCollection(service, key);
+ if (collectionCust != null) {
+ CollectionResource collectionResource = collectionCust.getCollectionResource();
+ if (collectionResource != null && collectionResource.getInstanceGroup() != null
+ && collectionResource.getInstanceGroup().getToscaNodeType() != null
+ && collectionResource.getInstanceGroup().getToscaNodeType().contains("NetworkCollection")) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ protected void mapCatalogNetworkCollectionInstanceGroup(Service service, InstanceGroup instanceGroup, String key) {
+ CollectionResourceCustomization collectionCust = this.findCatalogNetworkCollection(service, key);
+ org.onap.so.db.catalog.beans.InstanceGroup catalogInstanceGroup =
+ collectionCust.getCollectionResource().getInstanceGroup();
+ instanceGroup.setModelInfoInstanceGroup(
+ mapperLayer.mapCatalogInstanceGroupToInstanceGroup(collectionCust, catalogInstanceGroup));
+ }
+
+ protected void mapCatalogCollection(Service service, Collection collection, String key) {
+ CollectionResourceCustomization collectionCust = findCatalogNetworkCollection(service, key);
+ if (collectionCust != null) {
+ CollectionResource collectionResource = collectionCust.getCollectionResource();
+ if (collectionResource != null) {
+ collection.setModelInfoCollection(
+ mapperLayer.mapCatalogCollectionToCollection(collectionCust, collectionResource));
+ }
+ }
+ }
+
+ protected Collection createCollection(String collectionId) {
+ Collection collection = new Collection();
+ collection.setId(collectionId);
+ collection.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ return collection;
+ }
+
+ protected InstanceGroup createInstanceGroup() {
+ InstanceGroup instanceGroup = new InstanceGroup();
+ String instanceGroupId = this.generateRandomUUID();
+ instanceGroup.setId(instanceGroupId);
+ return instanceGroup;
+ }
+
+ protected void addRelationshipsToSI(org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI,
+ ServiceInstance serviceInstance) throws Exception {
+ AAIResultWrapper serviceInstanceWrapper = new AAIResultWrapper(
+ new AAICommonObjectMapperProvider().getMapper().writeValueAsString(serviceInstanceAAI));
+ Optional<Relationships> relationshipsOp = serviceInstanceWrapper.getRelationships();
+ Relationships relationships = null;
+ if (relationshipsOp.isPresent()) {
+ relationships = relationshipsOp.get();
+ } else {
+ return;
+ }
+
+ this.mapProject(relationships.getByType(AAIObjectType.PROJECT), serviceInstance);
+ this.mapOwningEntity(relationships.getByType(AAIObjectType.OWNING_ENTITY), serviceInstance);
+ this.mapL3Networks(relationships.getRelatedAAIUris(AAIObjectType.L3_NETWORK), serviceInstance.getNetworks());
+ this.mapGenericVnfs(relationships.getRelatedAAIUris(AAIObjectType.GENERIC_VNF), serviceInstance.getVnfs());
+ this.mapCollection(relationships.getByType(AAIObjectType.COLLECTION), serviceInstance);
+ this.mapConfigurations(relationships.getRelatedAAIUris(AAIObjectType.CONFIGURATION),
+ serviceInstance.getConfigurations());
+ }
+
+ protected void mapConfigurations(List<AAIResourceUri> relatedAAIUris, List<Configuration> configurations) {
+ for (AAIResourceUri aaiResourceUri : relatedAAIUris) {
+ configurations.add(mapConfiguration(aaiResourceUri));
+ }
+ }
+
+ protected Configuration mapConfiguration(AAIResourceUri aaiResourceUri) {
+ AAIResultWrapper aaiConfigurationWrapper = this.bbInputSetupUtils.getAAIResourceDepthOne(aaiResourceUri);
+ Optional<org.onap.aai.domain.yang.Configuration> aaiConfigurationOp =
+ aaiConfigurationWrapper.asBean(org.onap.aai.domain.yang.Configuration.class);
+ if (!aaiConfigurationOp.isPresent()) {
+ return null;
+ }
+
+ return this.mapperLayer.mapAAIConfiguration(aaiConfigurationOp.get());
+ }
+
+ protected void mapGenericVnfs(List<AAIResourceUri> list, List<GenericVnf> genericVnfs) {
+ for (AAIResourceUri aaiResourceUri : list) {
+ genericVnfs.add(this.mapGenericVnf(aaiResourceUri));
+ }
+ }
+
+ protected GenericVnf mapGenericVnf(AAIResourceUri aaiResourceUri) {
+ AAIResultWrapper aaiGenericVnfWrapper = this.bbInputSetupUtils.getAAIResourceDepthOne(aaiResourceUri);
+ Optional<org.onap.aai.domain.yang.GenericVnf> aaiGenericVnfOp =
+ aaiGenericVnfWrapper.asBean(org.onap.aai.domain.yang.GenericVnf.class);
+ if (!aaiGenericVnfOp.isPresent()) {
+ return null;
+ }
+
+ GenericVnf genericVnf = this.mapperLayer.mapAAIGenericVnfIntoGenericVnf(aaiGenericVnfOp.get());
+
+ Optional<Relationships> relationshipsOp = aaiGenericVnfWrapper.getRelationships();
+ if (relationshipsOp.isPresent()) {
+ Relationships relationships = relationshipsOp.get();
+ this.mapPlatform(relationships.getByType(AAIObjectType.PLATFORM), genericVnf);
+ this.mapLineOfBusiness(relationships.getByType(AAIObjectType.LINE_OF_BUSINESS), genericVnf);
+ genericVnf.getVolumeGroups().addAll(mapVolumeGroups(relationships.getByType(AAIObjectType.VOLUME_GROUP)));
+ genericVnf.getInstanceGroups()
+ .addAll(mapInstanceGroups(relationships.getByType(AAIObjectType.INSTANCE_GROUP)));
+ }
+
+ return genericVnf;
+ }
+
+ protected List<InstanceGroup> mapInstanceGroups(List<AAIResultWrapper> instanceGroups) {
+ List<InstanceGroup> instanceGroupsList = new ArrayList<>();
+ for (AAIResultWrapper volumeGroupWrapper : instanceGroups) {
+ instanceGroupsList.add(this.mapInstanceGroup(volumeGroupWrapper));
+ }
+ return instanceGroupsList;
+ }
+
+ protected InstanceGroup mapInstanceGroup(AAIResultWrapper instanceGroupWrapper) {
+ Optional<org.onap.aai.domain.yang.InstanceGroup> aaiInstanceGroupOp =
+ instanceGroupWrapper.asBean(org.onap.aai.domain.yang.InstanceGroup.class);
+ org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = null;
+
+ if (!aaiInstanceGroupOp.isPresent()) {
+ return null;
+ }
+
+ aaiInstanceGroup = aaiInstanceGroupOp.get();
+ InstanceGroup instanceGroup = this.mapperLayer.mapAAIInstanceGroupIntoInstanceGroup(aaiInstanceGroup);
+ instanceGroup.setModelInfoInstanceGroup(this.mapperLayer.mapCatalogInstanceGroupToInstanceGroup(null,
+ this.bbInputSetupUtils.getCatalogInstanceGroup(aaiInstanceGroup.getModelVersionId())));
+ return instanceGroup;
+ }
+
+ protected List<VolumeGroup> mapVolumeGroups(List<AAIResultWrapper> volumeGroups) {
+ List<VolumeGroup> volumeGroupsList = new ArrayList<>();
+ for (AAIResultWrapper volumeGroupWrapper : volumeGroups) {
+ volumeGroupsList.add(this.mapVolumeGroup(volumeGroupWrapper));
+ }
+ return volumeGroupsList;
+ }
+
+ protected VolumeGroup mapVolumeGroup(AAIResultWrapper volumeGroupWrapper) {
+ Optional<org.onap.aai.domain.yang.VolumeGroup> aaiVolumeGroupOp =
+ volumeGroupWrapper.asBean(org.onap.aai.domain.yang.VolumeGroup.class);
+ org.onap.aai.domain.yang.VolumeGroup aaiVolumeGroup = null;
+
+ if (!aaiVolumeGroupOp.isPresent()) {
+ return null;
+ }
+
+ aaiVolumeGroup = aaiVolumeGroupOp.get();
+ return this.mapperLayer.mapAAIVolumeGroup(aaiVolumeGroup);
+ }
+
+ protected void mapLineOfBusiness(List<AAIResultWrapper> lineOfBusinesses, GenericVnf genericVnf) {
+ if (!lineOfBusinesses.isEmpty()) {
+ AAIResultWrapper lineOfBusinessWrapper = lineOfBusinesses.get(0);
+ Optional<org.onap.aai.domain.yang.LineOfBusiness> aaiLineOfBusinessOp =
+ lineOfBusinessWrapper.asBean(org.onap.aai.domain.yang.LineOfBusiness.class);
+ org.onap.aai.domain.yang.LineOfBusiness aaiLineOfBusiness = null;
+ if (!aaiLineOfBusinessOp.isPresent()) {
+ return;
+ }
+ aaiLineOfBusiness = aaiLineOfBusinessOp.get();
+
+ LineOfBusiness lineOfBusiness = this.mapperLayer.mapAAILineOfBusiness(aaiLineOfBusiness);
+ genericVnf.setLineOfBusiness(lineOfBusiness);
+ }
+ }
+
+ protected void mapPlatform(List<AAIResultWrapper> platforms, GenericVnf genericVnf) {
+ if (!platforms.isEmpty()) {
+ AAIResultWrapper platformWrapper = platforms.get(0);
+ Optional<org.onap.aai.domain.yang.Platform> aaiPlatformOp =
+ platformWrapper.asBean(org.onap.aai.domain.yang.Platform.class);
+ org.onap.aai.domain.yang.Platform aaiPlatform = null;
+ if (!aaiPlatformOp.isPresent()) {
+ return;
+ }
+ aaiPlatform = aaiPlatformOp.get();
+
+ Platform platform = this.mapperLayer.mapAAIPlatform(aaiPlatform);
+ genericVnf.setPlatform(platform);
+ }
+ }
+
+ protected void mapCollection(List<AAIResultWrapper> collections, ServiceInstance serviceInstance) {
+ if (!collections.isEmpty()) {
+ AAIResultWrapper collectionWrapper = collections.get(0);
+ Optional<org.onap.aai.domain.yang.Collection> aaiCollectionOp =
+ collectionWrapper.asBean(org.onap.aai.domain.yang.Collection.class);
+ org.onap.aai.domain.yang.Collection aaiCollection = null;
+ if (!aaiCollectionOp.isPresent()) {
+ return;
+ }
+ aaiCollection = aaiCollectionOp.get();
+
+ Collection collection = this.mapperLayer.mapAAICollectionIntoCollection(aaiCollection);
+ NetworkCollectionResourceCustomization collectionResourceCust = bbInputSetupUtils
+ .getCatalogNetworkCollectionResourceCustByID(aaiCollection.getCollectionCustomizationId());
+ collection.setModelInfoCollection(mapperLayer.mapCatalogCollectionToCollection(collectionResourceCust,
+ collectionResourceCust.getCollectionResource()));
+ Optional<Relationships> relationshipsOp = collectionWrapper.getRelationships();
+ Relationships relationships = null;
+ if (relationshipsOp.isPresent()) {
+ relationships = relationshipsOp.get();
+ } else {
+ serviceInstance.setCollection(collection);
+ return;
+ }
+ List<InstanceGroup> instanceGroupsList =
+ mapInstanceGroups(relationships.getByType(AAIObjectType.INSTANCE_GROUP));
+ if (!instanceGroupsList.isEmpty()) {
+ collection.setInstanceGroup(instanceGroupsList.get(0));
+ }
+ serviceInstance.setCollection(collection);
+ }
+ }
+
+ protected void mapL3Networks(List<AAIResourceUri> list, List<L3Network> l3Networks) {
+ for (AAIResourceUri aaiResourceUri : list) {
+ l3Networks.add(this.mapL3Network(aaiResourceUri));
+ }
+ }
+
+ protected L3Network mapL3Network(AAIResourceUri aaiResourceUri) {
+ AAIResultWrapper aaiNetworkWrapper = this.bbInputSetupUtils.getAAIResourceDepthTwo(aaiResourceUri);
+ Optional<org.onap.aai.domain.yang.L3Network> aaiL3NetworkOp =
+ aaiNetworkWrapper.asBean(org.onap.aai.domain.yang.L3Network.class);
+ org.onap.aai.domain.yang.L3Network aaiL3Network = null;
+
+ if (!aaiL3NetworkOp.isPresent()) {
+ return null;
+ }
+
+ aaiL3Network = aaiL3NetworkOp.get();
+ L3Network network = this.mapperLayer.mapAAIL3Network(aaiL3Network);
+
+ Optional<Relationships> relationshipsOp = aaiNetworkWrapper.getRelationships();
+ if (relationshipsOp.isPresent()) {
+ Relationships relationships = relationshipsOp.get();
+ this.mapNetworkPolicies(relationships.getByType(AAIObjectType.NETWORK_POLICY),
+ network.getNetworkPolicies());
+ mapRouteTableReferences(relationships.getByType(AAIObjectType.ROUTE_TABLE_REFERENCE),
+ network.getContrailNetworkRouteTableReferences());
+ }
+
+ return network;
+ }
+
+ protected void mapNetworkPolicies(List<AAIResultWrapper> aaiNetworkPolicies, List<NetworkPolicy> networkPolicies) {
+ for (AAIResultWrapper networkPolicyWrapper : aaiNetworkPolicies) {
+ networkPolicies.add(this.mapNetworkPolicy(networkPolicyWrapper));
+ }
+ }
+
+ protected NetworkPolicy mapNetworkPolicy(AAIResultWrapper networkPolicyWrapper) {
+ Optional<org.onap.aai.domain.yang.NetworkPolicy> aaiNetworkPolicyOp =
+ networkPolicyWrapper.asBean(org.onap.aai.domain.yang.NetworkPolicy.class);
+ org.onap.aai.domain.yang.NetworkPolicy aaiNetworkPolicy = null;
+
+ if (!aaiNetworkPolicyOp.isPresent()) {
+ return null;
+ }
+
+ aaiNetworkPolicy = aaiNetworkPolicyOp.get();
+ return this.mapperLayer.mapAAINetworkPolicy(aaiNetworkPolicy);
+ }
+
+ protected void mapRouteTableReferences(List<AAIResultWrapper> routeTableReferences,
+ List<RouteTableReference> contrailNetworkRouteTableReferences) {
+ for (AAIResultWrapper routeTableReferenceWrapper : routeTableReferences) {
+ contrailNetworkRouteTableReferences.add(this.mapRouteTableReference(routeTableReferenceWrapper));
+ }
+ }
+
+ protected RouteTableReference mapRouteTableReference(AAIResultWrapper routeTableReferenceWrapper) {
+ Optional<org.onap.aai.domain.yang.RouteTableReference> aaiRouteTableReferenceOp =
+ routeTableReferenceWrapper.asBean(org.onap.aai.domain.yang.RouteTableReference.class);
+ org.onap.aai.domain.yang.RouteTableReference aaiRouteTableReference = null;
+
+ if (!aaiRouteTableReferenceOp.isPresent()) {
+ return null;
+ }
+
+ aaiRouteTableReference = aaiRouteTableReferenceOp.get();
+ return this.mapperLayer.mapAAIRouteTableReferenceIntoRouteTableReference(aaiRouteTableReference);
+ }
+
+ protected void mapOwningEntity(List<AAIResultWrapper> owningEntities, ServiceInstance serviceInstance) {
+ if (!owningEntities.isEmpty()) {
+ AAIResultWrapper owningEntityWrapper = owningEntities.get(0);
+ Optional<org.onap.aai.domain.yang.OwningEntity> aaiOwningEntityOp =
+ owningEntityWrapper.asBean(org.onap.aai.domain.yang.OwningEntity.class);
+ org.onap.aai.domain.yang.OwningEntity aaiOwningEntity = null;
+ if (!aaiOwningEntityOp.isPresent()) {
+ return;
+ }
+ aaiOwningEntity = aaiOwningEntityOp.get();
+
+ OwningEntity owningEntity = this.mapperLayer.mapAAIOwningEntity(aaiOwningEntity);
+ serviceInstance.setOwningEntity(owningEntity);
+ }
+ }
+
+ protected void mapProject(List<AAIResultWrapper> projects, ServiceInstance serviceInstance) {
+ if (!projects.isEmpty()) {
+ AAIResultWrapper projectWrapper = projects.get(0);
+ Optional<org.onap.aai.domain.yang.Project> aaiProjectOp =
+ projectWrapper.asBean(org.onap.aai.domain.yang.Project.class);
+ org.onap.aai.domain.yang.Project aaiProject = null;
+ if (!aaiProjectOp.isPresent()) {
+ return;
+ }
+ aaiProject = aaiProjectOp.get();
+
+ Project project = this.mapperLayer.mapAAIProject(aaiProject);
+ serviceInstance.setProject(project);
+ }
+ }
+
+ protected Customer mapCustomer(String globalCustomerId, String subscriptionServiceType) {
+ org.onap.aai.domain.yang.Customer aaiCustomer = this.bbInputSetupUtils.getAAICustomer(globalCustomerId);
+ org.onap.aai.domain.yang.ServiceSubscription aaiServiceSubscription =
+ this.bbInputSetupUtils.getAAIServiceSubscription(globalCustomerId, subscriptionServiceType);
+ Customer customer = this.mapperLayer.mapAAICustomer(aaiCustomer);
+ ServiceSubscription serviceSubscription = this.mapperLayer.mapAAIServiceSubscription(aaiServiceSubscription);
+ if (serviceSubscription != null) {
+ customer.setServiceSubscription(serviceSubscription);
+ }
+ return customer;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java
index d8c80ced75..177c918305 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java
@@ -28,7 +28,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.onap.so.bpmn.servicedecomposition.bbobjects.AllottedResource;
@@ -90,432 +89,443 @@ import org.springframework.stereotype.Component;
@Component("BBInputSetupMapperLayer")
public class BBInputSetupMapperLayer {
- private static final String USER_PARAM_NAME_KEY = "name";
+ private static final String USER_PARAM_NAME_KEY = "name";
private static final String USER_PARAM_VALUE_KEY = "value";
- private static final Logger logger = LoggerFactory.getLogger(BBInputSetupMapperLayer.class);
-
- private ModelMapper modelMapper = new ModelMapper();
-
- public Customer mapAAICustomer(org.onap.aai.domain.yang.Customer customerAAI) {
- return modelMapper.map(customerAAI, Customer.class);
- }
-
- public ServiceSubscription mapAAIServiceSubscription(
- org.onap.aai.domain.yang.ServiceSubscription serviceSubscriptionAAI) {
- return modelMapper.map(serviceSubscriptionAAI, ServiceSubscription.class);
- }
-
- protected Project mapAAIProject(org.onap.aai.domain.yang.Project aaiProject) {
- return modelMapper.map(aaiProject, Project.class);
- }
-
- protected OwningEntity mapAAIOwningEntity(org.onap.aai.domain.yang.OwningEntity aaiOwningEntity) {
- return modelMapper.map(aaiOwningEntity, OwningEntity.class);
- }
-
- protected Platform mapAAIPlatform(org.onap.aai.domain.yang.Platform aaiPlatform) {
- return modelMapper.map(aaiPlatform, Platform.class);
- }
-
- protected LineOfBusiness mapAAILineOfBusiness(org.onap.aai.domain.yang.LineOfBusiness aaiLineOfBusiness) {
- return modelMapper.map(aaiLineOfBusiness, LineOfBusiness.class);
- }
-
- protected SegmentationAssignment mapAAISegmentationAssignment(
- org.onap.aai.domain.yang.SegmentationAssignment aaiSegmentationAssignment) {
- return modelMapper.map(aaiSegmentationAssignment, SegmentationAssignment.class);
- }
-
- protected CtagAssignment mapAAICtagAssignment(org.onap.aai.domain.yang.CtagAssignment aaiCtagAssignment) {
- return modelMapper.map(aaiCtagAssignment, CtagAssignment.class);
- }
-
- protected Subnet mapAAISubnet(org.onap.aai.domain.yang.Subnet aaiSubnet) {
- return modelMapper.map(aaiSubnet, Subnet.class);
- }
-
- protected License mapAAILicense(org.onap.aai.domain.yang.License aaiLicense) {
- return modelMapper.map(aaiLicense, License.class);
- }
-
- protected Entitlement mapAAIEntitlement(org.onap.aai.domain.yang.Entitlement aaiEntitlement) {
- return modelMapper.map(aaiEntitlement, Entitlement.class);
- }
-
- protected LagInterface mapAAILagInterface(org.onap.aai.domain.yang.LagInterface aaiLagInterface) {
- return modelMapper.map(aaiLagInterface, LagInterface.class);
- }
-
- protected VfModule mapAAIVfModule(org.onap.aai.domain.yang.VfModule aaiVfModule) {
- VfModule vfModule = modelMapper.map(aaiVfModule, VfModule.class);
- vfModule.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(aaiVfModule.getOrchestrationStatus()));
-
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setIsBaseBoolean(aaiVfModule.isIsBaseVfModule());
- vfModule.setModelInfoVfModule(modelInfoVfModule);
- return vfModule;
- }
-
- public NetworkPolicy mapAAINetworkPolicy(org.onap.aai.domain.yang.NetworkPolicy aaiNetworkPolicy) {
- return modelMapper.map(aaiNetworkPolicy, NetworkPolicy.class);
- }
-
- protected VolumeGroup mapAAIVolumeGroup(org.onap.aai.domain.yang.VolumeGroup aaiVolumeGroup) {
- VolumeGroup volumeGroup = modelMapper.map(aaiVolumeGroup, VolumeGroup.class);
- volumeGroup.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(aaiVolumeGroup.getOrchestrationStatus()));
- return volumeGroup;
- }
-
- protected void setPlatformAndLOBIntoServiceInstance(Platform platformMSO, LineOfBusiness lineOfBusinessMSO,
- ServiceInstance serviceInstance, Map<ResourceKey, String> resourcesToBeOrchestrated) {
- String vnfId = resourcesToBeOrchestrated.get(ResourceKey.GENERIC_VNF_ID);
- if (vnfId != null && !serviceInstance.getVnfs().isEmpty()) {
- for (GenericVnf vnf : serviceInstance.getVnfs()) {
- if (vnf.getVnfId().equalsIgnoreCase(vnfId)) {
- vnf.setPlatform(platformMSO);
- vnf.setLineOfBusiness(lineOfBusinessMSO);
- break;
- }
- }
- }
- }
-
- public ModelInfoServiceInstance mapCatalogServiceIntoServiceInstance(Service service) {
- return modelMapper.map(service, ModelInfoServiceInstance.class);
- }
-
- protected ModelInfoInstanceGroup mapCatalogInstanceGroupToInstanceGroup(CollectionResourceCustomization collectionCust, InstanceGroup instanceGroup) {
- ModelInfoInstanceGroup modelInfoInstanceGroup = modelMapper.map(instanceGroup, ModelInfoInstanceGroup.class);
- if(instanceGroup.getType() != null && instanceGroup.getType().equals(InstanceGroupType.L3_NETWORK))
- modelInfoInstanceGroup.setType(ModelInfoInstanceGroup.TYPE_L3_NETWORK);
- else
- modelInfoInstanceGroup.setType(ModelInfoInstanceGroup.TYPE_VNFC);
- if(collectionCust != null) {
- List<CollectionResourceInstanceGroupCustomization> instanceGroupCustList = instanceGroup.getCollectionInstanceGroupCustomizations();
- for(CollectionResourceInstanceGroupCustomization collectionInsatnceGroupCust : instanceGroupCustList) {
- if(collectionInsatnceGroupCust.getModelCustomizationUUID().equalsIgnoreCase(collectionCust.getModelCustomizationUUID())) {
- modelInfoInstanceGroup.setFunction(collectionInsatnceGroupCust.getFunction());
- modelInfoInstanceGroup.setDescription(collectionInsatnceGroupCust.getDescription());
- break;
- }
- }
- }
- return modelInfoInstanceGroup;
- }
-
- protected ModelInfoCollection mapCatalogCollectionToCollection(CollectionResourceCustomization collectionCust,
- CollectionResource collectionResource) {
- ModelInfoCollection modelInfoCollection = new ModelInfoCollection();
- modelInfoCollection.setCollectionFunction(collectionCust.getFunction());
- modelInfoCollection.setCollectionRole(collectionCust.getRole());
- modelInfoCollection.setCollectionType(collectionCust.getType());
- modelInfoCollection.setDescription(collectionResource.getDescription());
- modelInfoCollection.setModelInvariantUUID(collectionResource.getModelInvariantUUID());
- modelInfoCollection.setModelVersionId(collectionResource.getModelUUID());
- modelInfoCollection.setModelCustomizationUUID(collectionCust.getModelCustomizationUUID());
- return modelInfoCollection;
- }
-
- public ServiceInstance mapAAIServiceInstanceIntoServiceInstance(
- org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance) {
- ServiceInstance serviceInstance = modelMapper.map(aaiServiceInstance, ServiceInstance.class);
- if (aaiServiceInstance.getAllottedResources() != null) {
- for (org.onap.aai.domain.yang.AllottedResource allottedResource : aaiServiceInstance.getAllottedResources()
- .getAllottedResource()) {
- serviceInstance.getAllottedResources().add(mapAAIAllottedResource(allottedResource));
- }
- }
- serviceInstance.setOrchestrationStatus(
- this.mapOrchestrationStatusFromAAI(aaiServiceInstance.getOrchestrationStatus()));
- return serviceInstance;
- }
-
- protected AllottedResource mapAAIAllottedResource(org.onap.aai.domain.yang.AllottedResource aaiAllottedResource) {
- AllottedResource allottedResource = modelMapper.map(aaiAllottedResource, AllottedResource.class);
- return allottedResource;
- }
-
- protected L3Network mapAAIL3Network(org.onap.aai.domain.yang.L3Network aaiL3Network) {
- L3Network network = modelMapper.map(aaiL3Network, L3Network.class);
- mapAllSubnetsIntoL3Network(aaiL3Network, network);
- mapAllCtagAssignmentsIntoL3Network(aaiL3Network, network);
- mapAllSegmentationAssignmentsIntoL3Network(aaiL3Network, network);
- network.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(aaiL3Network.getOrchestrationStatus()));
- return network;
- }
-
- protected void mapAllSegmentationAssignmentsIntoL3Network(org.onap.aai.domain.yang.L3Network aaiL3Network,
- L3Network network) {
- if (aaiL3Network.getSegmentationAssignments() != null) {
- for (org.onap.aai.domain.yang.SegmentationAssignment aaiSegmentationAssignment : aaiL3Network
- .getSegmentationAssignments().getSegmentationAssignment()) {
- network.getSegmentationAssignments().add(mapAAISegmentationAssignment(aaiSegmentationAssignment));
- }
- }
- }
-
- protected void mapAllCtagAssignmentsIntoL3Network(org.onap.aai.domain.yang.L3Network aaiL3Network,
- L3Network network) {
- if (aaiL3Network.getCtagAssignments() != null) {
- for (org.onap.aai.domain.yang.CtagAssignment aaiCtagAssignment : aaiL3Network.getCtagAssignments()
- .getCtagAssignment()) {
- network.getCtagAssignments().add(mapAAICtagAssignment(aaiCtagAssignment));
- }
- }
- }
-
- protected void mapAllSubnetsIntoL3Network(org.onap.aai.domain.yang.L3Network aaiL3Network, L3Network network) {
- if (aaiL3Network.getSubnets() != null) {
- for (org.onap.aai.domain.yang.Subnet aaiSubnet : aaiL3Network.getSubnets().getSubnet()) {
- network.getSubnets().add(mapAAISubnet(aaiSubnet));
- }
- }
- }
-
- protected GenericVnf mapAAIGenericVnfIntoGenericVnf(org.onap.aai.domain.yang.GenericVnf aaiGenericVnf) {
- GenericVnf genericVnf = modelMapper.map(aaiGenericVnf, GenericVnf.class);
- mapAllVfModulesIntoGenericVnf(aaiGenericVnf, genericVnf);
- mapAllLagInterfacesIntoGenericVnf(aaiGenericVnf, genericVnf);
- mapAllEntitlementsIntoGenericVnf(aaiGenericVnf, genericVnf);
- mapAllLicensesIntoGenericVnf(aaiGenericVnf, genericVnf);
- genericVnf.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(aaiGenericVnf.getOrchestrationStatus()));
- return genericVnf;
- }
-
- protected void mapAllLicensesIntoGenericVnf(org.onap.aai.domain.yang.GenericVnf aaiGenericVnf,
- GenericVnf genericVnf) {
- if (aaiGenericVnf.getLicenses() != null) {
- for (org.onap.aai.domain.yang.License aaiLicense : aaiGenericVnf.getLicenses().getLicense()) {
- genericVnf.setLicense(mapAAILicense(aaiLicense));
- }
- }
- }
-
- protected void mapAllEntitlementsIntoGenericVnf(org.onap.aai.domain.yang.GenericVnf aaiGenericVnf,
- GenericVnf genericVnf) {
- if (aaiGenericVnf.getEntitlements() != null) {
- for (org.onap.aai.domain.yang.Entitlement aaiEntitlement : aaiGenericVnf.getEntitlements()
- .getEntitlement()) {
- genericVnf.getEntitlements().add(mapAAIEntitlement(aaiEntitlement));
- }
- }
- }
-
- protected void mapAllLagInterfacesIntoGenericVnf(org.onap.aai.domain.yang.GenericVnf aaiGenericVnf,
- GenericVnf genericVnf) {
- if (aaiGenericVnf.getLagInterfaces() != null) {
- for (org.onap.aai.domain.yang.LagInterface aaiLagInterface : aaiGenericVnf.getLagInterfaces()
- .getLagInterface()) {
- genericVnf.getLagInterfaces().add(mapAAILagInterface(aaiLagInterface));
- }
- }
- }
-
- protected void mapAllVfModulesIntoGenericVnf(org.onap.aai.domain.yang.GenericVnf aaiGenericVnf,
- GenericVnf genericVnf) {
- if (aaiGenericVnf.getVfModules() != null) {
- for (org.onap.aai.domain.yang.VfModule aaiVfModule : aaiGenericVnf.getVfModules().getVfModule()) {
- VfModule vfModule = mapAAIVfModule(aaiVfModule);
- genericVnf.getVfModules().add(vfModule);
- }
- }
- }
-
- public OrchestrationStatus mapOrchestrationStatusFromAAI(String orchestrationStatus) {
-
- Optional<OrchestrationStatus> result = Arrays.asList(OrchestrationStatus.values()).stream()
- .filter(item -> item.fuzzyMap(orchestrationStatus))
- .findFirst();
-
- return result.orElse(null);
-
- }
-
- public RequestContext mapRequestContext(RequestDetails requestDetails) {
- RequestContext context = new RequestContext();
- modelMapper.map(requestDetails.getRequestInfo(), context);
- org.onap.so.serviceinstancebeans.RequestParameters requestParameters = requestDetails.getRequestParameters();
- if (null != requestParameters) {
- context.setSubscriptionServiceType(requestParameters.getSubscriptionServiceType());
- context.setRequestParameters(this.mapRequestParameters(requestDetails.getRequestParameters()));
- context.setUserParams(this.mapNameValueUserParams(requestDetails.getRequestParameters()));
- }
- if (requestDetails.getConfigurationParameters() != null) {
- context.setConfigurationParameters(requestDetails.getConfigurationParameters());
- }
- return context;
- }
-
- protected RequestParameters mapRequestParameters(org.onap.so.serviceinstancebeans.RequestParameters requestParameters) {
- RequestParameters requestParams = new RequestParameters();
- requestParams.setaLaCarte(requestParameters.getALaCarte());
- requestParams.setUsePreload(requestParameters.getUsePreload());
- requestParams.setSubscriptionServiceType(requestParameters.getSubscriptionServiceType());
- requestParams.setUserParams(requestParameters.getUserParams());
- requestParams.setPayload(requestParameters.getPayload());
- return requestParams;
- }
-
- protected Map<String,Object> mapNameValueUserParams(org.onap.so.serviceinstancebeans.RequestParameters requestParameters) {
- Map<String,Object> userParamsResult = new HashMap<String,Object>();
- if (requestParameters.getUserParams() != null) {
- List<Map<String, Object>> userParams = requestParameters.getUserParams();
- for (Map<String, Object> userParamsMap : userParams) {
- if ( userParamsMap.containsKey(USER_PARAM_NAME_KEY) && (userParamsMap.get(USER_PARAM_NAME_KEY) instanceof String)
- && userParamsMap.containsKey(USER_PARAM_VALUE_KEY)) {
- userParamsResult.put((String) userParamsMap.get(USER_PARAM_NAME_KEY), userParamsMap.get(USER_PARAM_VALUE_KEY));
- }
- }
- }
- return userParamsResult;
- }
-
- protected OrchestrationContext mapOrchestrationContext(RequestDetails requestDetails) {
- OrchestrationContext context = new OrchestrationContext();
- context.setIsRollbackEnabled(!(requestDetails.getRequestInfo().getSuppressRollback()));
- return context;
- }
-
- protected CloudRegion mapCloudRegion(CloudConfiguration cloudConfiguration, org.onap.aai.domain.yang.CloudRegion aaiCloudRegion) {
- CloudRegion cloudRegion = new CloudRegion();
- if(cloudConfiguration != null)
- cloudRegion = modelMapper.map(cloudConfiguration, CloudRegion.class);
- if(aaiCloudRegion != null)
- modelMapper.map(aaiCloudRegion, cloudRegion);
- return cloudRegion;
- }
-
- protected Tenant mapTenant(org.onap.aai.domain.yang.Tenant aaiTenant) {
- Tenant tenant = new Tenant();
- if(aaiTenant != null) {
- modelMapper.map(aaiTenant, tenant);
- }
- return tenant;
- }
-
- protected Collection mapAAICollectionIntoCollection(org.onap.aai.domain.yang.Collection aaiCollection) {
- Collection collection = new Collection();
- collection.setId(aaiCollection.getCollectionId());
- collection.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(aaiCollection.getOrchestrationStatus()));
- return collection;
- }
-
- protected org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup mapAAIInstanceGroupIntoInstanceGroup(
- org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup) {
- return modelMapper.map(aaiInstanceGroup,
- org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup.class);
- }
-
- public RouteTableReference mapAAIRouteTableReferenceIntoRouteTableReference(
- org.onap.aai.domain.yang.RouteTableReference aaiRouteTableReference) {
- return modelMapper.map(aaiRouteTableReference, RouteTableReference.class);
- }
-
- protected ModelInfoNetwork mapCatalogNetworkToNetwork(NetworkResourceCustomization networkResourceCustomization) {
- modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
- ModelInfoNetwork modelInfoNetwork = modelMapper.map(networkResourceCustomization, ModelInfoNetwork.class);
- modelMapper.map(networkResourceCustomization.getNetworkResource(), modelInfoNetwork);
- modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STANDARD);
- return modelInfoNetwork;
- }
-
- protected ModelInfoGenericVnf mapCatalogVnfToVnf(VnfResourceCustomization vnfResourceCustomization) {
- ModelInfoGenericVnf modelInfoVnf = modelMapper.map(vnfResourceCustomization, ModelInfoGenericVnf.class);
- modelMapper.map(vnfResourceCustomization.getVnfResources(), modelInfoVnf);
- return modelInfoVnf;
- }
-
- protected ModelInfoVfModule mapCatalogVfModuleToVfModule(VfModuleCustomization vfResourceCustomization) {
- ModelInfoVfModule modelInfoVfModule = modelMapper.map(vfResourceCustomization, ModelInfoVfModule.class);
- modelMapper.map(vfResourceCustomization.getVfModule(), modelInfoVfModule);
- return modelInfoVfModule;
- }
-
- protected Platform mapRequestPlatform(org.onap.so.serviceinstancebeans.Platform platform) {
- return modelMapper.map(platform, Platform.class);
- }
-
- protected LineOfBusiness mapRequestLineOfBusiness(
- org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness) {
- return modelMapper.map(lineOfBusiness, LineOfBusiness.class);
- }
-
- public Configuration mapAAIConfiguration(org.onap.aai.domain.yang.Configuration configurationAAI) {
- modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
- Configuration configuration = modelMapper.map(configurationAAI, Configuration.class);
- modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STANDARD);
- configuration.getForwarderEvcs().addAll(mapAllForwarderEvcs(configurationAAI));
- configuration.getEvcs().addAll(mapAllEvcs(configurationAAI));
- configuration.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(configurationAAI.getOrchestrationStatus()));
- return configuration;
- }
-
- protected List<Evc> mapAllEvcs(org.onap.aai.domain.yang.Configuration configurationAAI) {
- List<Evc> listOfEvcs = new ArrayList<>();
- if (configurationAAI.getEvcs() != null) {
- for (org.onap.aai.domain.yang.Evc aaiEvc : configurationAAI.getEvcs().getEvc()) {
- listOfEvcs.add(mapEvc(aaiEvc));
- }
- }
- return listOfEvcs;
- }
-
- protected Evc mapEvc(org.onap.aai.domain.yang.Evc aaiEvc) {
- return modelMapper.map(aaiEvc, Evc.class);
- }
-
- protected List<ForwarderEvc> mapAllForwarderEvcs(org.onap.aai.domain.yang.Configuration configurationAAI) {
- List<ForwarderEvc> listOfForwarderEvcs = new ArrayList<>();
- if (configurationAAI.getForwarderEvcs() != null) {
- for (org.onap.aai.domain.yang.ForwarderEvc aaiForwarderEvc : configurationAAI.getForwarderEvcs().getForwarderEvc()) {
- listOfForwarderEvcs.add(mapForwarderEvc(aaiForwarderEvc));
- }
- }
- return listOfForwarderEvcs;
- }
-
- protected ForwarderEvc mapForwarderEvc(org.onap.aai.domain.yang.ForwarderEvc aaiForwarderEvc) {
- return modelMapper.map(aaiForwarderEvc, ForwarderEvc.class);
- }
-
- protected OwningEntity mapRequestOwningEntity(org.onap.so.serviceinstancebeans.OwningEntity owningEntity) {
- return modelMapper.map(owningEntity, OwningEntity.class);
- }
-
- protected Project mapRequestProject(org.onap.so.serviceinstancebeans.Project project) {
- return modelMapper.map(project, Project.class);
- }
-
- protected ModelInfoConfiguration mapCatalogConfigurationToConfiguration(
- ConfigurationResourceCustomization configurationResourceCustomization,
- CvnfcConfigurationCustomization cvnfcConfigurationCustomization) {
- ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
- modelInfoConfiguration.setModelVersionId(configurationResourceCustomization.getConfigurationResource().getModelUUID());
- modelInfoConfiguration.setModelCustomizationId(configurationResourceCustomization.getModelCustomizationUUID());
- modelInfoConfiguration.setModelInvariantId(configurationResourceCustomization.getConfigurationResource().getModelInvariantUUID());
- modelInfoConfiguration.setPolicyName(cvnfcConfigurationCustomization.getPolicyName());
- return modelInfoConfiguration;
- }
-
- protected ModelInfoConfiguration mapCatalogConfigurationToConfiguration(
- CvnfcConfigurationCustomization cvnfcConfigurationCustomization) {
- ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
- modelInfoConfiguration.setModelVersionId(cvnfcConfigurationCustomization.getConfigurationResource().getModelUUID());
- modelInfoConfiguration.setModelCustomizationId(cvnfcConfigurationCustomization.getModelCustomizationUUID());
- modelInfoConfiguration.setModelInvariantId(cvnfcConfigurationCustomization.getConfigurationResource().getModelInvariantUUID());
- modelInfoConfiguration.setPolicyName(cvnfcConfigurationCustomization.getPolicyName());
- modelInfoConfiguration.setConfigurationType(cvnfcConfigurationCustomization.getConfigurationType());
- modelInfoConfiguration.setConfigurationRole(cvnfcConfigurationCustomization.getConfigurationRole());
- return modelInfoConfiguration;
- }
-
- public NetworkResourceCustomization mapCollectionNetworkResourceCustToNetworkResourceCust(
- CollectionNetworkResourceCustomization collectionNetworkResourceCust) {
- return modelMapper.map(collectionNetworkResourceCust, NetworkResourceCustomization.class);
- }
-
- public Vnfc mapAAIVnfc(org.onap.aai.domain.yang.Vnfc vnfcAAI) {
- return modelMapper.map(vnfcAAI, Vnfc.class);
- }
+ private static final Logger logger = LoggerFactory.getLogger(BBInputSetupMapperLayer.class);
+
+ private ModelMapper modelMapper = new ModelMapper();
+
+ public Customer mapAAICustomer(org.onap.aai.domain.yang.Customer customerAAI) {
+ return modelMapper.map(customerAAI, Customer.class);
+ }
+
+ public ServiceSubscription mapAAIServiceSubscription(
+ org.onap.aai.domain.yang.ServiceSubscription serviceSubscriptionAAI) {
+ return modelMapper.map(serviceSubscriptionAAI, ServiceSubscription.class);
+ }
+
+ protected Project mapAAIProject(org.onap.aai.domain.yang.Project aaiProject) {
+ return modelMapper.map(aaiProject, Project.class);
+ }
+
+ protected OwningEntity mapAAIOwningEntity(org.onap.aai.domain.yang.OwningEntity aaiOwningEntity) {
+ return modelMapper.map(aaiOwningEntity, OwningEntity.class);
+ }
+
+ protected Platform mapAAIPlatform(org.onap.aai.domain.yang.Platform aaiPlatform) {
+ return modelMapper.map(aaiPlatform, Platform.class);
+ }
+
+ protected LineOfBusiness mapAAILineOfBusiness(org.onap.aai.domain.yang.LineOfBusiness aaiLineOfBusiness) {
+ return modelMapper.map(aaiLineOfBusiness, LineOfBusiness.class);
+ }
+
+ protected SegmentationAssignment mapAAISegmentationAssignment(
+ org.onap.aai.domain.yang.SegmentationAssignment aaiSegmentationAssignment) {
+ return modelMapper.map(aaiSegmentationAssignment, SegmentationAssignment.class);
+ }
+
+ protected CtagAssignment mapAAICtagAssignment(org.onap.aai.domain.yang.CtagAssignment aaiCtagAssignment) {
+ return modelMapper.map(aaiCtagAssignment, CtagAssignment.class);
+ }
+
+ protected Subnet mapAAISubnet(org.onap.aai.domain.yang.Subnet aaiSubnet) {
+ return modelMapper.map(aaiSubnet, Subnet.class);
+ }
+
+ protected License mapAAILicense(org.onap.aai.domain.yang.License aaiLicense) {
+ return modelMapper.map(aaiLicense, License.class);
+ }
+
+ protected Entitlement mapAAIEntitlement(org.onap.aai.domain.yang.Entitlement aaiEntitlement) {
+ return modelMapper.map(aaiEntitlement, Entitlement.class);
+ }
+
+ protected LagInterface mapAAILagInterface(org.onap.aai.domain.yang.LagInterface aaiLagInterface) {
+ return modelMapper.map(aaiLagInterface, LagInterface.class);
+ }
+
+ protected VfModule mapAAIVfModule(org.onap.aai.domain.yang.VfModule aaiVfModule) {
+ VfModule vfModule = modelMapper.map(aaiVfModule, VfModule.class);
+ vfModule.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(aaiVfModule.getOrchestrationStatus()));
+
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setIsBaseBoolean(aaiVfModule.isIsBaseVfModule());
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+ return vfModule;
+ }
+
+ public NetworkPolicy mapAAINetworkPolicy(org.onap.aai.domain.yang.NetworkPolicy aaiNetworkPolicy) {
+ return modelMapper.map(aaiNetworkPolicy, NetworkPolicy.class);
+ }
+
+ protected VolumeGroup mapAAIVolumeGroup(org.onap.aai.domain.yang.VolumeGroup aaiVolumeGroup) {
+ VolumeGroup volumeGroup = modelMapper.map(aaiVolumeGroup, VolumeGroup.class);
+ volumeGroup.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(aaiVolumeGroup.getOrchestrationStatus()));
+ return volumeGroup;
+ }
+
+ protected void setPlatformAndLOBIntoServiceInstance(Platform platformMSO, LineOfBusiness lineOfBusinessMSO,
+ ServiceInstance serviceInstance, Map<ResourceKey, String> resourcesToBeOrchestrated) {
+ String vnfId = resourcesToBeOrchestrated.get(ResourceKey.GENERIC_VNF_ID);
+ if (vnfId != null && !serviceInstance.getVnfs().isEmpty()) {
+ for (GenericVnf vnf : serviceInstance.getVnfs()) {
+ if (vnf.getVnfId().equalsIgnoreCase(vnfId)) {
+ vnf.setPlatform(platformMSO);
+ vnf.setLineOfBusiness(lineOfBusinessMSO);
+ break;
+ }
+ }
+ }
+ }
+
+ public ModelInfoServiceInstance mapCatalogServiceIntoServiceInstance(Service service) {
+ return modelMapper.map(service, ModelInfoServiceInstance.class);
+ }
+
+ protected ModelInfoInstanceGroup mapCatalogInstanceGroupToInstanceGroup(
+ CollectionResourceCustomization collectionCust, InstanceGroup instanceGroup) {
+ ModelInfoInstanceGroup modelInfoInstanceGroup = modelMapper.map(instanceGroup, ModelInfoInstanceGroup.class);
+ if (instanceGroup.getType() != null && instanceGroup.getType().equals(InstanceGroupType.L3_NETWORK))
+ modelInfoInstanceGroup.setType(ModelInfoInstanceGroup.TYPE_L3_NETWORK);
+ else
+ modelInfoInstanceGroup.setType(ModelInfoInstanceGroup.TYPE_VNFC);
+ if (collectionCust != null) {
+ List<CollectionResourceInstanceGroupCustomization> instanceGroupCustList =
+ instanceGroup.getCollectionInstanceGroupCustomizations();
+ for (CollectionResourceInstanceGroupCustomization collectionInsatnceGroupCust : instanceGroupCustList) {
+ if (collectionInsatnceGroupCust.getModelCustomizationUUID()
+ .equalsIgnoreCase(collectionCust.getModelCustomizationUUID())) {
+ modelInfoInstanceGroup.setFunction(collectionInsatnceGroupCust.getFunction());
+ modelInfoInstanceGroup.setDescription(collectionInsatnceGroupCust.getDescription());
+ break;
+ }
+ }
+ }
+ return modelInfoInstanceGroup;
+ }
+
+ protected ModelInfoCollection mapCatalogCollectionToCollection(CollectionResourceCustomization collectionCust,
+ CollectionResource collectionResource) {
+ ModelInfoCollection modelInfoCollection = new ModelInfoCollection();
+ modelInfoCollection.setCollectionFunction(collectionCust.getFunction());
+ modelInfoCollection.setCollectionRole(collectionCust.getRole());
+ modelInfoCollection.setCollectionType(collectionCust.getType());
+ modelInfoCollection.setDescription(collectionResource.getDescription());
+ modelInfoCollection.setModelInvariantUUID(collectionResource.getModelInvariantUUID());
+ modelInfoCollection.setModelVersionId(collectionResource.getModelUUID());
+ modelInfoCollection.setModelCustomizationUUID(collectionCust.getModelCustomizationUUID());
+ return modelInfoCollection;
+ }
+
+ public ServiceInstance mapAAIServiceInstanceIntoServiceInstance(
+ org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance) {
+ ServiceInstance serviceInstance = modelMapper.map(aaiServiceInstance, ServiceInstance.class);
+ if (aaiServiceInstance.getAllottedResources() != null) {
+ for (org.onap.aai.domain.yang.AllottedResource allottedResource : aaiServiceInstance.getAllottedResources()
+ .getAllottedResource()) {
+ serviceInstance.getAllottedResources().add(mapAAIAllottedResource(allottedResource));
+ }
+ }
+ serviceInstance.setOrchestrationStatus(
+ this.mapOrchestrationStatusFromAAI(aaiServiceInstance.getOrchestrationStatus()));
+ return serviceInstance;
+ }
+
+ protected AllottedResource mapAAIAllottedResource(org.onap.aai.domain.yang.AllottedResource aaiAllottedResource) {
+ AllottedResource allottedResource = modelMapper.map(aaiAllottedResource, AllottedResource.class);
+ return allottedResource;
+ }
+
+ protected L3Network mapAAIL3Network(org.onap.aai.domain.yang.L3Network aaiL3Network) {
+ L3Network network = modelMapper.map(aaiL3Network, L3Network.class);
+ mapAllSubnetsIntoL3Network(aaiL3Network, network);
+ mapAllCtagAssignmentsIntoL3Network(aaiL3Network, network);
+ mapAllSegmentationAssignmentsIntoL3Network(aaiL3Network, network);
+ network.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(aaiL3Network.getOrchestrationStatus()));
+ return network;
+ }
+
+ protected void mapAllSegmentationAssignmentsIntoL3Network(org.onap.aai.domain.yang.L3Network aaiL3Network,
+ L3Network network) {
+ if (aaiL3Network.getSegmentationAssignments() != null) {
+ for (org.onap.aai.domain.yang.SegmentationAssignment aaiSegmentationAssignment : aaiL3Network
+ .getSegmentationAssignments().getSegmentationAssignment()) {
+ network.getSegmentationAssignments().add(mapAAISegmentationAssignment(aaiSegmentationAssignment));
+ }
+ }
+ }
+
+ protected void mapAllCtagAssignmentsIntoL3Network(org.onap.aai.domain.yang.L3Network aaiL3Network,
+ L3Network network) {
+ if (aaiL3Network.getCtagAssignments() != null) {
+ for (org.onap.aai.domain.yang.CtagAssignment aaiCtagAssignment : aaiL3Network.getCtagAssignments()
+ .getCtagAssignment()) {
+ network.getCtagAssignments().add(mapAAICtagAssignment(aaiCtagAssignment));
+ }
+ }
+ }
+
+ protected void mapAllSubnetsIntoL3Network(org.onap.aai.domain.yang.L3Network aaiL3Network, L3Network network) {
+ if (aaiL3Network.getSubnets() != null) {
+ for (org.onap.aai.domain.yang.Subnet aaiSubnet : aaiL3Network.getSubnets().getSubnet()) {
+ network.getSubnets().add(mapAAISubnet(aaiSubnet));
+ }
+ }
+ }
+
+ protected GenericVnf mapAAIGenericVnfIntoGenericVnf(org.onap.aai.domain.yang.GenericVnf aaiGenericVnf) {
+ GenericVnf genericVnf = modelMapper.map(aaiGenericVnf, GenericVnf.class);
+ mapAllVfModulesIntoGenericVnf(aaiGenericVnf, genericVnf);
+ mapAllLagInterfacesIntoGenericVnf(aaiGenericVnf, genericVnf);
+ mapAllEntitlementsIntoGenericVnf(aaiGenericVnf, genericVnf);
+ mapAllLicensesIntoGenericVnf(aaiGenericVnf, genericVnf);
+ genericVnf.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(aaiGenericVnf.getOrchestrationStatus()));
+ return genericVnf;
+ }
+
+ protected void mapAllLicensesIntoGenericVnf(org.onap.aai.domain.yang.GenericVnf aaiGenericVnf,
+ GenericVnf genericVnf) {
+ if (aaiGenericVnf.getLicenses() != null) {
+ for (org.onap.aai.domain.yang.License aaiLicense : aaiGenericVnf.getLicenses().getLicense()) {
+ genericVnf.setLicense(mapAAILicense(aaiLicense));
+ }
+ }
+ }
+
+ protected void mapAllEntitlementsIntoGenericVnf(org.onap.aai.domain.yang.GenericVnf aaiGenericVnf,
+ GenericVnf genericVnf) {
+ if (aaiGenericVnf.getEntitlements() != null) {
+ for (org.onap.aai.domain.yang.Entitlement aaiEntitlement : aaiGenericVnf.getEntitlements()
+ .getEntitlement()) {
+ genericVnf.getEntitlements().add(mapAAIEntitlement(aaiEntitlement));
+ }
+ }
+ }
+
+ protected void mapAllLagInterfacesIntoGenericVnf(org.onap.aai.domain.yang.GenericVnf aaiGenericVnf,
+ GenericVnf genericVnf) {
+ if (aaiGenericVnf.getLagInterfaces() != null) {
+ for (org.onap.aai.domain.yang.LagInterface aaiLagInterface : aaiGenericVnf.getLagInterfaces()
+ .getLagInterface()) {
+ genericVnf.getLagInterfaces().add(mapAAILagInterface(aaiLagInterface));
+ }
+ }
+ }
+
+ protected void mapAllVfModulesIntoGenericVnf(org.onap.aai.domain.yang.GenericVnf aaiGenericVnf,
+ GenericVnf genericVnf) {
+ if (aaiGenericVnf.getVfModules() != null) {
+ for (org.onap.aai.domain.yang.VfModule aaiVfModule : aaiGenericVnf.getVfModules().getVfModule()) {
+ VfModule vfModule = mapAAIVfModule(aaiVfModule);
+ genericVnf.getVfModules().add(vfModule);
+ }
+ }
+ }
+
+ public OrchestrationStatus mapOrchestrationStatusFromAAI(String orchestrationStatus) {
+
+ Optional<OrchestrationStatus> result = Arrays.asList(OrchestrationStatus.values()).stream()
+ .filter(item -> item.fuzzyMap(orchestrationStatus)).findFirst();
+
+ return result.orElse(null);
+
+ }
+
+ public RequestContext mapRequestContext(RequestDetails requestDetails) {
+ RequestContext context = new RequestContext();
+ modelMapper.map(requestDetails.getRequestInfo(), context);
+ org.onap.so.serviceinstancebeans.RequestParameters requestParameters = requestDetails.getRequestParameters();
+ if (null != requestParameters) {
+ context.setSubscriptionServiceType(requestParameters.getSubscriptionServiceType());
+ context.setRequestParameters(this.mapRequestParameters(requestDetails.getRequestParameters()));
+ context.setUserParams(this.mapNameValueUserParams(requestDetails.getRequestParameters()));
+ }
+ if (requestDetails.getConfigurationParameters() != null) {
+ context.setConfigurationParameters(requestDetails.getConfigurationParameters());
+ }
+ return context;
+ }
+
+ protected RequestParameters mapRequestParameters(
+ org.onap.so.serviceinstancebeans.RequestParameters requestParameters) {
+ RequestParameters requestParams = new RequestParameters();
+ requestParams.setaLaCarte(requestParameters.getALaCarte());
+ requestParams.setUsePreload(requestParameters.getUsePreload());
+ requestParams.setSubscriptionServiceType(requestParameters.getSubscriptionServiceType());
+ requestParams.setUserParams(requestParameters.getUserParams());
+ requestParams.setPayload(requestParameters.getPayload());
+ return requestParams;
+ }
+
+ protected Map<String, Object> mapNameValueUserParams(
+ org.onap.so.serviceinstancebeans.RequestParameters requestParameters) {
+ Map<String, Object> userParamsResult = new HashMap<String, Object>();
+ if (requestParameters.getUserParams() != null) {
+ List<Map<String, Object>> userParams = requestParameters.getUserParams();
+ for (Map<String, Object> userParamsMap : userParams) {
+ if (userParamsMap.containsKey(USER_PARAM_NAME_KEY)
+ && (userParamsMap.get(USER_PARAM_NAME_KEY) instanceof String)
+ && userParamsMap.containsKey(USER_PARAM_VALUE_KEY)) {
+ userParamsResult.put((String) userParamsMap.get(USER_PARAM_NAME_KEY),
+ userParamsMap.get(USER_PARAM_VALUE_KEY));
+ }
+ }
+ }
+ return userParamsResult;
+ }
+
+ protected OrchestrationContext mapOrchestrationContext(RequestDetails requestDetails) {
+ OrchestrationContext context = new OrchestrationContext();
+ context.setIsRollbackEnabled(!(requestDetails.getRequestInfo().getSuppressRollback()));
+ return context;
+ }
+
+ protected CloudRegion mapCloudRegion(CloudConfiguration cloudConfiguration,
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion) {
+ CloudRegion cloudRegion = new CloudRegion();
+ if (cloudConfiguration != null)
+ cloudRegion = modelMapper.map(cloudConfiguration, CloudRegion.class);
+ if (aaiCloudRegion != null)
+ modelMapper.map(aaiCloudRegion, cloudRegion);
+ return cloudRegion;
+ }
+
+ protected Tenant mapTenant(org.onap.aai.domain.yang.Tenant aaiTenant) {
+ Tenant tenant = new Tenant();
+ if (aaiTenant != null) {
+ modelMapper.map(aaiTenant, tenant);
+ }
+ return tenant;
+ }
+
+ protected Collection mapAAICollectionIntoCollection(org.onap.aai.domain.yang.Collection aaiCollection) {
+ Collection collection = new Collection();
+ collection.setId(aaiCollection.getCollectionId());
+ collection.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(aaiCollection.getOrchestrationStatus()));
+ return collection;
+ }
+
+ protected org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup mapAAIInstanceGroupIntoInstanceGroup(
+ org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup) {
+ return modelMapper.map(aaiInstanceGroup, org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup.class);
+ }
+
+ public RouteTableReference mapAAIRouteTableReferenceIntoRouteTableReference(
+ org.onap.aai.domain.yang.RouteTableReference aaiRouteTableReference) {
+ return modelMapper.map(aaiRouteTableReference, RouteTableReference.class);
+ }
+
+ protected ModelInfoNetwork mapCatalogNetworkToNetwork(NetworkResourceCustomization networkResourceCustomization) {
+ modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
+ ModelInfoNetwork modelInfoNetwork = modelMapper.map(networkResourceCustomization, ModelInfoNetwork.class);
+ modelMapper.map(networkResourceCustomization.getNetworkResource(), modelInfoNetwork);
+ modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STANDARD);
+ return modelInfoNetwork;
+ }
+
+ protected ModelInfoGenericVnf mapCatalogVnfToVnf(VnfResourceCustomization vnfResourceCustomization) {
+ ModelInfoGenericVnf modelInfoVnf = modelMapper.map(vnfResourceCustomization, ModelInfoGenericVnf.class);
+ modelMapper.map(vnfResourceCustomization.getVnfResources(), modelInfoVnf);
+ return modelInfoVnf;
+ }
+
+ protected ModelInfoVfModule mapCatalogVfModuleToVfModule(VfModuleCustomization vfResourceCustomization) {
+ ModelInfoVfModule modelInfoVfModule = modelMapper.map(vfResourceCustomization, ModelInfoVfModule.class);
+ modelMapper.map(vfResourceCustomization.getVfModule(), modelInfoVfModule);
+ return modelInfoVfModule;
+ }
+
+ protected Platform mapRequestPlatform(org.onap.so.serviceinstancebeans.Platform platform) {
+ return modelMapper.map(platform, Platform.class);
+ }
+
+ protected LineOfBusiness mapRequestLineOfBusiness(org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness) {
+ return modelMapper.map(lineOfBusiness, LineOfBusiness.class);
+ }
+
+ public Configuration mapAAIConfiguration(org.onap.aai.domain.yang.Configuration configurationAAI) {
+ modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
+ Configuration configuration = modelMapper.map(configurationAAI, Configuration.class);
+ modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STANDARD);
+ configuration.getForwarderEvcs().addAll(mapAllForwarderEvcs(configurationAAI));
+ configuration.getEvcs().addAll(mapAllEvcs(configurationAAI));
+ configuration
+ .setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(configurationAAI.getOrchestrationStatus()));
+ return configuration;
+ }
+
+ protected List<Evc> mapAllEvcs(org.onap.aai.domain.yang.Configuration configurationAAI) {
+ List<Evc> listOfEvcs = new ArrayList<>();
+ if (configurationAAI.getEvcs() != null) {
+ for (org.onap.aai.domain.yang.Evc aaiEvc : configurationAAI.getEvcs().getEvc()) {
+ listOfEvcs.add(mapEvc(aaiEvc));
+ }
+ }
+ return listOfEvcs;
+ }
+
+ protected Evc mapEvc(org.onap.aai.domain.yang.Evc aaiEvc) {
+ return modelMapper.map(aaiEvc, Evc.class);
+ }
+
+ protected List<ForwarderEvc> mapAllForwarderEvcs(org.onap.aai.domain.yang.Configuration configurationAAI) {
+ List<ForwarderEvc> listOfForwarderEvcs = new ArrayList<>();
+ if (configurationAAI.getForwarderEvcs() != null) {
+ for (org.onap.aai.domain.yang.ForwarderEvc aaiForwarderEvc : configurationAAI.getForwarderEvcs()
+ .getForwarderEvc()) {
+ listOfForwarderEvcs.add(mapForwarderEvc(aaiForwarderEvc));
+ }
+ }
+ return listOfForwarderEvcs;
+ }
+
+ protected ForwarderEvc mapForwarderEvc(org.onap.aai.domain.yang.ForwarderEvc aaiForwarderEvc) {
+ return modelMapper.map(aaiForwarderEvc, ForwarderEvc.class);
+ }
+
+ protected OwningEntity mapRequestOwningEntity(org.onap.so.serviceinstancebeans.OwningEntity owningEntity) {
+ return modelMapper.map(owningEntity, OwningEntity.class);
+ }
+
+ protected Project mapRequestProject(org.onap.so.serviceinstancebeans.Project project) {
+ return modelMapper.map(project, Project.class);
+ }
+
+ protected ModelInfoConfiguration mapCatalogConfigurationToConfiguration(
+ ConfigurationResourceCustomization configurationResourceCustomization,
+ CvnfcConfigurationCustomization cvnfcConfigurationCustomization) {
+ ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
+ modelInfoConfiguration
+ .setModelVersionId(configurationResourceCustomization.getConfigurationResource().getModelUUID());
+ modelInfoConfiguration.setModelCustomizationId(configurationResourceCustomization.getModelCustomizationUUID());
+ modelInfoConfiguration.setModelInvariantId(
+ configurationResourceCustomization.getConfigurationResource().getModelInvariantUUID());
+ modelInfoConfiguration.setPolicyName(cvnfcConfigurationCustomization.getPolicyName());
+ return modelInfoConfiguration;
+ }
+
+ protected ModelInfoConfiguration mapCatalogConfigurationToConfiguration(
+ CvnfcConfigurationCustomization cvnfcConfigurationCustomization) {
+ ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
+ modelInfoConfiguration
+ .setModelVersionId(cvnfcConfigurationCustomization.getConfigurationResource().getModelUUID());
+ modelInfoConfiguration.setModelCustomizationId(cvnfcConfigurationCustomization.getModelCustomizationUUID());
+ modelInfoConfiguration.setModelInvariantId(
+ cvnfcConfigurationCustomization.getConfigurationResource().getModelInvariantUUID());
+ modelInfoConfiguration.setPolicyName(cvnfcConfigurationCustomization.getPolicyName());
+ modelInfoConfiguration.setConfigurationType(cvnfcConfigurationCustomization.getConfigurationType());
+ modelInfoConfiguration.setConfigurationRole(cvnfcConfigurationCustomization.getConfigurationRole());
+ return modelInfoConfiguration;
+ }
+
+ public NetworkResourceCustomization mapCollectionNetworkResourceCustToNetworkResourceCust(
+ CollectionNetworkResourceCustomization collectionNetworkResourceCust) {
+ return modelMapper.map(collectionNetworkResourceCust, NetworkResourceCustomization.class);
+ }
+
+ public Vnfc mapAAIVnfc(org.onap.aai.domain.yang.Vnfc vnfcAAI) {
+ return modelMapper.map(vnfcAAI, Vnfc.class);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java
index 9a08d1872d..5cf2bd7b39 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java
@@ -26,7 +26,6 @@ import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.onap.aai.domain.yang.CloudRegion;
import org.onap.aai.domain.yang.Configuration;
import org.onap.aai.domain.yang.GenericVnf;
@@ -49,7 +48,6 @@ import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.entities.AAIResultWrapper;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
-
import org.onap.so.client.graphinventory.entities.uri.Depth;
import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization;
import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization;
@@ -67,7 +65,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
@@ -75,379 +72,395 @@ import com.fasterxml.jackson.databind.SerializationFeature;
@Component("BBInputSetupUtils")
public class BBInputSetupUtils {
- private static final Logger logger = LoggerFactory.getLogger(BBInputSetupUtils.class);
- private ObjectMapper objectMapper = new ObjectMapper();
- private static final String REQUEST_ERROR = "Could not find request.";
-
- @Autowired
- protected CatalogDbClient catalogDbClient;
-
- @Autowired
- protected RequestsDbClient requestsDbClient;
-
- @Autowired
- protected InjectionHelper injectionHelper;
-
- public void updateInfraActiveRequestVnfId(InfraActiveRequests request, String vnfId) {
- if(request != null) {
- request.setVnfId(vnfId);
- this.requestsDbClient.updateInfraActiveRequests(request);
- } else {
- logger.debug(REQUEST_ERROR);
- }
- }
-
- public void updateInfraActiveRequestVfModuleId(InfraActiveRequests request, String vfModuleId) {
- if(request != null) {
- request.setVfModuleId(vfModuleId);
- this.requestsDbClient.updateInfraActiveRequests(request);
- } else {
- logger.debug(REQUEST_ERROR);
- }
- }
-
- public void updateInfraActiveRequestVolumeGroupId(InfraActiveRequests request, String volumeGroupId) {
- if(request != null) {
- request.setVolumeGroupId(volumeGroupId);
- this.requestsDbClient.updateInfraActiveRequests(request);
- } else {
- logger.debug(REQUEST_ERROR);
- }
- }
-
- public void updateInfraActiveRequestNetworkId(InfraActiveRequests request, String networkId) {
- if(request != null) {
- request.setNetworkId(networkId);
- this.requestsDbClient.updateInfraActiveRequests(request);
- } else {
- logger.debug(REQUEST_ERROR);
- }
- }
-
- public Service getCatalogServiceByModelUUID(String modelUUID) {
- return catalogDbClient.getServiceByID(modelUUID);
- }
-
- public Service getCatalogServiceByModelVersionAndModelInvariantUUID(String modelVersion, String modelInvariantUUID) {
- return catalogDbClient.getServiceByModelVersionAndModelInvariantUUID(modelVersion, modelInvariantUUID);
- }
-
- public CollectionNetworkResourceCustomization getCatalogCollectionNetworkResourceCustByID(String key) {
- return catalogDbClient.getCollectionNetworkResourceCustomizationByID(key);
- }
-
- public NetworkCollectionResourceCustomization getCatalogNetworkCollectionResourceCustByID(
- String collectionCustomizationId) {
- return catalogDbClient.getNetworkCollectionResourceCustomizationByID(collectionCustomizationId);
- }
-
- public VfModuleCustomization getVfModuleCustomizationByModelCuztomizationUUID(String modelCustomizationUUID) {
- return catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID(modelCustomizationUUID);
- }
-
- public CvnfcConfigurationCustomization getCvnfcConfigurationCustomization(String serviceModelUUID, String vnfCustomizationUuid,
- String vfModuleCustomizationUuid, String cvnfcCustomizationUuid){
- return catalogDbClient.getCvnfcCustomization(serviceModelUUID, vnfCustomizationUuid,vfModuleCustomizationUuid, cvnfcCustomizationUuid);
- }
-
- public List<VnfcInstanceGroupCustomization> getVnfcInstanceGroups(String modelCustomizationUUID) {
- return catalogDbClient.getVnfcInstanceGroupsByVnfResourceCust(modelCustomizationUUID);
- }
-
- public Map<String, String> getURIKeysFromServiceInstance(String serviceInstanceId) {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId);
- return uri.getURIKeys();
- }
-
- protected RequestDetails getRequestDetails(String requestId) throws IOException {
- if (requestId != null && !requestId.isEmpty()) {
- InfraActiveRequests activeRequest = this.getInfraActiveRequest(requestId);
- String requestBody = activeRequest.getRequestBody().replaceAll("\\\\", "");
- objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
- objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
- return objectMapper.readValue(requestBody, RequestDetails.class);
- } else {
- return null;
- }
- }
-
- protected InfraActiveRequests getInfraActiveRequest(String requestId) {
- if (requestId != null && !requestId.isEmpty()) {
- return requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
- } else {
- return null;
- }
- }
-
- protected CloudRegion getCloudRegion(CloudConfiguration cloudConfiguration) {
- if (cloudConfiguration != null) {
- String cloudRegionId = cloudConfiguration.getLcpCloudRegionId();
- String cloudOwner = cloudConfiguration.getCloudOwner();
- if (cloudRegionId != null && cloudOwner != null && !cloudRegionId.isEmpty() && !cloudOwner.isEmpty()) {
- return injectionHelper.getAaiClient().get(CloudRegion.class,
- AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudOwner,
- cloudRegionId).depth(Depth.TWO)).orElse(null);
-
- } else {
- return null;
- }
- } else {
- return null;
- }
- }
-
- protected InstanceGroup getAAIInstanceGroup(String instanceGroupId) {
- return injectionHelper.getAaiClient().get(InstanceGroup.class,
- AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId))
- .orElse(null);
- }
-
- public org.onap.aai.domain.yang.Customer getAAICustomer(String globalSubscriberId) {
- return injectionHelper.getAaiClient().get(org.onap.aai.domain.yang.Customer.class,
- AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId))
- .orElse(null);
- }
-
- public ServiceSubscription getAAIServiceSubscription(String globalSubscriberId, String subscriptionServiceType) {
-
- if(globalSubscriberId == null || globalSubscriberId.equals("") || subscriptionServiceType == null || subscriptionServiceType.equals("")) {
- return null;
- } else {
- return injectionHelper.getAaiClient().get(ServiceSubscription.class, AAIUriFactory.createResourceUri(
- AAIObjectType.SERVICE_SUBSCRIPTION, globalSubscriberId, subscriptionServiceType))
- .orElse(null);
- }
-
- }
-
- public ServiceInstance getAAIServiceInstanceById(String serviceInstanceId) {
- return injectionHelper.getAaiClient().get(ServiceInstance.class,
- AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId).depth(Depth.TWO))
- .orElse(null);
- }
-
- protected ServiceInstance getAAIServiceInstanceByIdAndCustomer(String globalCustomerId, String serviceType,
- String serviceInstanceId) {
- return injectionHelper.getAaiClient().get(ServiceInstance.class, AAIUriFactory.createResourceUri(
- AAIObjectType.SERVICE_INSTANCE, globalCustomerId, serviceType, serviceInstanceId).depth(Depth.TWO))
- .orElse(null);
- }
-
- protected org.onap.aai.domain.yang.ServiceInstances getAAIServiceInstancesByName(String serviceInstanceName,
- Customer customer) {
-
- return injectionHelper.getAaiClient().get(org.onap.aai.domain.yang.ServiceInstances.class,
- AAIUriFactory
- .createResourceUri(AAIObjectPlurals.SERVICE_INSTANCE, customer.getGlobalCustomerId(),
- customer.getServiceSubscription().getServiceType())
- .queryParam("service-instance-name", serviceInstanceName).depth(Depth.TWO))
- .orElseGet(() -> {
- logger.debug("No Service Instance matched by name");
- return null;
- });
- }
-
- public org.onap.aai.domain.yang.ServiceInstance getAAIServiceInstanceByName(String serviceInstanceName,
- Customer customer) throws Exception {
- org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = null;
- org.onap.aai.domain.yang.ServiceInstances aaiServiceInstances = null;
- aaiServiceInstances = getAAIServiceInstancesByName(serviceInstanceName, customer);
-
- if (aaiServiceInstances == null) {
- return null;
- } else if (aaiServiceInstances.getServiceInstance().size() > 1) {
- throw new Exception("Multiple Service Instances Returned");
- } else {
- aaiServiceInstance = aaiServiceInstances.getServiceInstance().get(0);
- }
- return aaiServiceInstance;
- }
-
- protected ServiceInstances getAAIServiceInstancesByName(String globalCustomerId, String serviceType,
- String serviceInstanceName) {
-
- return injectionHelper.getAaiClient().get(ServiceInstances.class,
- AAIUriFactory.createResourceUri(AAIObjectPlurals.SERVICE_INSTANCE, globalCustomerId, serviceType)
- .queryParam("service-instance-name", serviceInstanceName).depth(Depth.TWO))
- .orElseGet(() -> {
- logger.debug("No Service Instance matched by name");
- return null;
- });
- }
-
- public Optional<ServiceInstance> getAAIServiceInstanceByName(String globalCustomerId, String serviceType,
- String serviceInstanceName) throws Exception {
- ServiceInstance aaiServiceInstance = null;
- ServiceInstances aaiServiceInstances = null;
- aaiServiceInstances = getAAIServiceInstancesByName(globalCustomerId, serviceType, serviceInstanceName);
-
- if (aaiServiceInstances == null) {
- return Optional.empty();
- } else if (aaiServiceInstances.getServiceInstance().size() > 1) {
- throw new Exception("Multiple Service Instances Returned");
- } else {
- aaiServiceInstance = aaiServiceInstances.getServiceInstance().get(0);
- }
- return Optional.of(aaiServiceInstance);
- }
-
- public org.onap.so.db.catalog.beans.InstanceGroup getCatalogInstanceGroup(String modelUUID) {
- return this.catalogDbClient.getInstanceGroupByModelUUID(modelUUID);
- }
-
- public List<CollectionResourceInstanceGroupCustomization> getCollectionResourceInstanceGroupCustomization(
- String modelCustomizationUUID) {
- return this.catalogDbClient
- .getCollectionResourceInstanceGroupCustomizationByModelCustUUID(modelCustomizationUUID);
- }
-
- public AAIResultWrapper getAAIResourceDepthOne(AAIResourceUri aaiResourceUri) {
- AAIResourceUri clonedUri = aaiResourceUri.clone();
- return this.injectionHelper.getAaiClient().get(clonedUri.depth(Depth.ONE));
- }
-
- public AAIResultWrapper getAAIResourceDepthTwo(AAIResourceUri aaiResourceUri) {
- AAIResourceUri clonedUri = aaiResourceUri.clone();
- return this.injectionHelper.getAaiClient().get(clonedUri.depth(Depth.TWO));
- }
-
- public Configuration getAAIConfiguration(String configurationId) {
- return this.injectionHelper.getAaiClient().get(Configuration.class,
- AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId).depth(Depth.ONE))
- .orElseGet(() -> {
- logger.debug("No Configuration matched by id");
- return null;
- });
- }
-
- public GenericVnf getAAIGenericVnf(String vnfId) {
-
- return this.injectionHelper.getAaiClient().get(GenericVnf.class,
- AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE))
- .orElseGet(() -> {
- logger.debug("No Generic Vnf matched by id");
- return null;
- });
- }
-
- public VolumeGroup getAAIVolumeGroup(String cloudOwnerId, String cloudRegionId, String volumeGroupId) {
- return this.injectionHelper.getAaiClient().get(VolumeGroup.class,
- AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudOwnerId, cloudRegionId, volumeGroupId).depth(Depth.ONE))
- .orElseGet(() -> {
- logger.debug("No Generic Vnf matched by id");
- return null;
- });
- }
-
- public VfModule getAAIVfModule(String vnfId, String vfModuleId) {
- return this.injectionHelper.getAaiClient().get(VfModule.class,
- AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId).depth(Depth.ONE))
- .orElseGet(() -> {
- logger.debug("No Generic Vnf matched by id");
- return null;
- });
- }
-
- public L3Network getAAIL3Network(String networkId) {
-
- return this.injectionHelper.getAaiClient().get(L3Network.class,
- AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ONE))
- .orElseGet(() -> {
- logger.debug("No Generic Vnf matched by id");
- return null;
- });
-
- }
-
- public Optional<ServiceInstance> getRelatedServiceInstanceFromInstanceGroup(String instanceGroupId) throws Exception {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId);
- uri.relatedTo(AAIObjectPlurals.SERVICE_INSTANCE);
- Optional<ServiceInstances> serviceInstances = injectionHelper.getAaiClient().get(ServiceInstances.class, uri);
- ServiceInstance serviceInstance = null;
- if (!serviceInstances.isPresent()) {
- logger.debug("No ServiceInstances were found");
- return Optional.empty();
- } else {
- if (serviceInstances.get().getServiceInstance().isEmpty()) {
- throw new NoServiceInstanceFoundException("No ServiceInstances Returned");
- } else if (serviceInstances.get().getServiceInstance().size() > 1) {
- throw new MultipleObjectsFoundException("Multiple ServiceInstances Returned");
- } else {
- serviceInstance = serviceInstances.get().getServiceInstance().get(0);
- }
- return Optional.of(serviceInstance);
- }
- }
-
- public Optional<L3Network> getRelatedNetworkByNameFromServiceInstance(String serviceInstanceId, String networkName) throws Exception{
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId);
- uri.relatedTo(AAIObjectPlurals.L3_NETWORK).queryParam("network-name", networkName);
- Optional<L3Networks> networks = injectionHelper.getAaiClient().get(L3Networks.class, uri);
- L3Network network = null;
- if (!networks.isPresent()) {
- logger.debug("No Networks matched by name");
- return Optional.empty();
- } else {
- if (networks.get().getL3Network().size() > 1) {
- throw new Exception("Multiple Networks Returned");
- } else {
- network = networks.get().getL3Network().get(0);
- }
- return Optional.of(network);
- }
- }
-
- public Optional<GenericVnf> getRelatedVnfByNameFromServiceInstance(String serviceInstanceId, String vnfName) throws Exception {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId);
- uri.relatedTo(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", vnfName);
- Optional<GenericVnfs> vnfs = injectionHelper.getAaiClient().get(GenericVnfs.class, uri);
- GenericVnf vnf = null;
- if (!vnfs.isPresent()) {
- logger.debug("No Vnfs matched by name");
- return Optional.empty();
- } else {
- if (vnfs.get().getGenericVnf().size() > 1) {
- throw new Exception("Multiple Vnfs Returned");
- } else {
- vnf = vnfs.get().getGenericVnf().get(0);
- }
- return Optional.of(vnf);
- }
- }
-
- public Optional<VolumeGroup> getRelatedVolumeGroupByNameFromVnf(String vnfId, String volumeGroupName) throws Exception{
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
- uri.relatedTo(AAIObjectPlurals.VOLUME_GROUP).queryParam("volume-group-name", volumeGroupName);
- Optional<VolumeGroups> volumeGroups = injectionHelper.getAaiClient().get(VolumeGroups.class, uri);
- VolumeGroup volumeGroup = null;
- if (!volumeGroups.isPresent()) {
- logger.debug("No VolumeGroups matched by name");
- return Optional.empty();
- } else {
- if (volumeGroups.get().getVolumeGroup().size() > 1) {
- throw new Exception("Multiple VolumeGroups Returned");
- } else {
- volumeGroup = volumeGroups.get().getVolumeGroup().get(0);
- }
- return Optional.of(volumeGroup);
- }
- }
-
- public Optional<VolumeGroup> getRelatedVolumeGroupByNameFromVfModule(String vnfId, String vfModuleId, String volumeGroupName) throws Exception {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId);
- uri.relatedTo(AAIObjectPlurals.VOLUME_GROUP).queryParam("volume-group-name", volumeGroupName);
- Optional<VolumeGroups> volumeGroups = injectionHelper.getAaiClient().get(VolumeGroups.class, uri);
- VolumeGroup volumeGroup = null;
- if (!volumeGroups.isPresent()) {
- logger.debug("No VolumeGroups matched by name");
- return Optional.empty();
- } else {
- if (volumeGroups.get().getVolumeGroup().size() > 1) {
- throw new Exception("Multiple VolumeGroups Returned");
- } else {
- volumeGroup = volumeGroups.get().getVolumeGroup().get(0);
- }
- return Optional.of(volumeGroup);
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(BBInputSetupUtils.class);
+ private ObjectMapper objectMapper = new ObjectMapper();
+ private static final String REQUEST_ERROR = "Could not find request.";
+
+ @Autowired
+ protected CatalogDbClient catalogDbClient;
+
+ @Autowired
+ protected RequestsDbClient requestsDbClient;
+
+ @Autowired
+ protected InjectionHelper injectionHelper;
+
+ public void updateInfraActiveRequestVnfId(InfraActiveRequests request, String vnfId) {
+ if (request != null) {
+ request.setVnfId(vnfId);
+ this.requestsDbClient.updateInfraActiveRequests(request);
+ } else {
+ logger.debug(REQUEST_ERROR);
+ }
+ }
+
+ public void updateInfraActiveRequestVfModuleId(InfraActiveRequests request, String vfModuleId) {
+ if (request != null) {
+ request.setVfModuleId(vfModuleId);
+ this.requestsDbClient.updateInfraActiveRequests(request);
+ } else {
+ logger.debug(REQUEST_ERROR);
+ }
+ }
+
+ public void updateInfraActiveRequestVolumeGroupId(InfraActiveRequests request, String volumeGroupId) {
+ if (request != null) {
+ request.setVolumeGroupId(volumeGroupId);
+ this.requestsDbClient.updateInfraActiveRequests(request);
+ } else {
+ logger.debug(REQUEST_ERROR);
+ }
+ }
+
+ public void updateInfraActiveRequestNetworkId(InfraActiveRequests request, String networkId) {
+ if (request != null) {
+ request.setNetworkId(networkId);
+ this.requestsDbClient.updateInfraActiveRequests(request);
+ } else {
+ logger.debug(REQUEST_ERROR);
+ }
+ }
+
+ public Service getCatalogServiceByModelUUID(String modelUUID) {
+ return catalogDbClient.getServiceByID(modelUUID);
+ }
+
+ public Service getCatalogServiceByModelVersionAndModelInvariantUUID(String modelVersion,
+ String modelInvariantUUID) {
+ return catalogDbClient.getServiceByModelVersionAndModelInvariantUUID(modelVersion, modelInvariantUUID);
+ }
+
+ public CollectionNetworkResourceCustomization getCatalogCollectionNetworkResourceCustByID(String key) {
+ return catalogDbClient.getCollectionNetworkResourceCustomizationByID(key);
+ }
+
+ public NetworkCollectionResourceCustomization getCatalogNetworkCollectionResourceCustByID(
+ String collectionCustomizationId) {
+ return catalogDbClient.getNetworkCollectionResourceCustomizationByID(collectionCustomizationId);
+ }
+
+ public VfModuleCustomization getVfModuleCustomizationByModelCuztomizationUUID(String modelCustomizationUUID) {
+ return catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID(modelCustomizationUUID);
+ }
+
+ public CvnfcConfigurationCustomization getCvnfcConfigurationCustomization(String serviceModelUUID,
+ String vnfCustomizationUuid, String vfModuleCustomizationUuid, String cvnfcCustomizationUuid) {
+ return catalogDbClient.getCvnfcCustomization(serviceModelUUID, vnfCustomizationUuid, vfModuleCustomizationUuid,
+ cvnfcCustomizationUuid);
+ }
+
+ public List<VnfcInstanceGroupCustomization> getVnfcInstanceGroups(String modelCustomizationUUID) {
+ return catalogDbClient.getVnfcInstanceGroupsByVnfResourceCust(modelCustomizationUUID);
+ }
+
+ public Map<String, String> getURIKeysFromServiceInstance(String serviceInstanceId) {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId);
+ return uri.getURIKeys();
+ }
+
+ protected RequestDetails getRequestDetails(String requestId) throws IOException {
+ if (requestId != null && !requestId.isEmpty()) {
+ InfraActiveRequests activeRequest = this.getInfraActiveRequest(requestId);
+ String requestBody = activeRequest.getRequestBody().replaceAll("\\\\", "");
+ objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
+ objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
+ return objectMapper.readValue(requestBody, RequestDetails.class);
+ } else {
+ return null;
+ }
+ }
+
+ protected InfraActiveRequests getInfraActiveRequest(String requestId) {
+ if (requestId != null && !requestId.isEmpty()) {
+ return requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
+ } else {
+ return null;
+ }
+ }
+
+ protected CloudRegion getCloudRegion(CloudConfiguration cloudConfiguration) {
+ if (cloudConfiguration != null) {
+ String cloudRegionId = cloudConfiguration.getLcpCloudRegionId();
+ String cloudOwner = cloudConfiguration.getCloudOwner();
+ if (cloudRegionId != null && cloudOwner != null && !cloudRegionId.isEmpty() && !cloudOwner.isEmpty()) {
+ return injectionHelper.getAaiClient().get(CloudRegion.class, AAIUriFactory
+ .createResourceUri(AAIObjectType.CLOUD_REGION, cloudOwner, cloudRegionId).depth(Depth.TWO))
+ .orElse(null);
+
+ } else {
+ return null;
+ }
+ } else {
+ return null;
+ }
+ }
+
+ protected InstanceGroup getAAIInstanceGroup(String instanceGroupId) {
+ return injectionHelper.getAaiClient().get(InstanceGroup.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId)).orElse(null);
+ }
+
+ public org.onap.aai.domain.yang.Customer getAAICustomer(String globalSubscriberId) {
+ return injectionHelper.getAaiClient().get(org.onap.aai.domain.yang.Customer.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId)).orElse(null);
+ }
+
+ public ServiceSubscription getAAIServiceSubscription(String globalSubscriberId, String subscriptionServiceType) {
+
+ if (globalSubscriberId == null || globalSubscriberId.equals("") || subscriptionServiceType == null
+ || subscriptionServiceType.equals("")) {
+ return null;
+ } else {
+ return injectionHelper.getAaiClient().get(ServiceSubscription.class, AAIUriFactory
+ .createResourceUri(AAIObjectType.SERVICE_SUBSCRIPTION, globalSubscriberId, subscriptionServiceType))
+ .orElse(null);
+ }
+
+ }
+
+ public ServiceInstance getAAIServiceInstanceById(String serviceInstanceId) {
+ return injectionHelper.getAaiClient()
+ .get(ServiceInstance.class, AAIUriFactory
+ .createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId).depth(Depth.TWO))
+ .orElse(null);
+ }
+
+ protected ServiceInstance getAAIServiceInstanceByIdAndCustomer(String globalCustomerId, String serviceType,
+ String serviceInstanceId) {
+ return injectionHelper.getAaiClient().get(ServiceInstance.class, AAIUriFactory
+ .createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustomerId, serviceType, serviceInstanceId)
+ .depth(Depth.TWO)).orElse(null);
+ }
+
+ protected org.onap.aai.domain.yang.ServiceInstances getAAIServiceInstancesByName(String serviceInstanceName,
+ Customer customer) {
+
+ return injectionHelper.getAaiClient()
+ .get(org.onap.aai.domain.yang.ServiceInstances.class,
+ AAIUriFactory
+ .createResourceUri(AAIObjectPlurals.SERVICE_INSTANCE, customer.getGlobalCustomerId(),
+ customer.getServiceSubscription().getServiceType())
+ .queryParam("service-instance-name", serviceInstanceName).depth(Depth.TWO))
+ .orElseGet(() -> {
+ logger.debug("No Service Instance matched by name");
+ return null;
+ });
+ }
+
+ public org.onap.aai.domain.yang.ServiceInstance getAAIServiceInstanceByName(String serviceInstanceName,
+ Customer customer) throws Exception {
+ org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = null;
+ org.onap.aai.domain.yang.ServiceInstances aaiServiceInstances = null;
+ aaiServiceInstances = getAAIServiceInstancesByName(serviceInstanceName, customer);
+
+ if (aaiServiceInstances == null) {
+ return null;
+ } else if (aaiServiceInstances.getServiceInstance().size() > 1) {
+ throw new Exception("Multiple Service Instances Returned");
+ } else {
+ aaiServiceInstance = aaiServiceInstances.getServiceInstance().get(0);
+ }
+ return aaiServiceInstance;
+ }
+
+ protected ServiceInstances getAAIServiceInstancesByName(String globalCustomerId, String serviceType,
+ String serviceInstanceName) {
+
+ return injectionHelper.getAaiClient()
+ .get(ServiceInstances.class,
+ AAIUriFactory
+ .createResourceUri(AAIObjectPlurals.SERVICE_INSTANCE, globalCustomerId, serviceType)
+ .queryParam("service-instance-name", serviceInstanceName).depth(Depth.TWO))
+ .orElseGet(() -> {
+ logger.debug("No Service Instance matched by name");
+ return null;
+ });
+ }
+
+ public Optional<ServiceInstance> getAAIServiceInstanceByName(String globalCustomerId, String serviceType,
+ String serviceInstanceName) throws Exception {
+ ServiceInstance aaiServiceInstance = null;
+ ServiceInstances aaiServiceInstances = null;
+ aaiServiceInstances = getAAIServiceInstancesByName(globalCustomerId, serviceType, serviceInstanceName);
+
+ if (aaiServiceInstances == null) {
+ return Optional.empty();
+ } else if (aaiServiceInstances.getServiceInstance().size() > 1) {
+ throw new Exception("Multiple Service Instances Returned");
+ } else {
+ aaiServiceInstance = aaiServiceInstances.getServiceInstance().get(0);
+ }
+ return Optional.of(aaiServiceInstance);
+ }
+
+ public org.onap.so.db.catalog.beans.InstanceGroup getCatalogInstanceGroup(String modelUUID) {
+ return this.catalogDbClient.getInstanceGroupByModelUUID(modelUUID);
+ }
+
+ public List<CollectionResourceInstanceGroupCustomization> getCollectionResourceInstanceGroupCustomization(
+ String modelCustomizationUUID) {
+ return this.catalogDbClient
+ .getCollectionResourceInstanceGroupCustomizationByModelCustUUID(modelCustomizationUUID);
+ }
+
+ public AAIResultWrapper getAAIResourceDepthOne(AAIResourceUri aaiResourceUri) {
+ AAIResourceUri clonedUri = aaiResourceUri.clone();
+ return this.injectionHelper.getAaiClient().get(clonedUri.depth(Depth.ONE));
+ }
+
+ public AAIResultWrapper getAAIResourceDepthTwo(AAIResourceUri aaiResourceUri) {
+ AAIResourceUri clonedUri = aaiResourceUri.clone();
+ return this.injectionHelper.getAaiClient().get(clonedUri.depth(Depth.TWO));
+ }
+
+ public Configuration getAAIConfiguration(String configurationId) {
+ return this.injectionHelper.getAaiClient()
+ .get(Configuration.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId).depth(Depth.ONE))
+ .orElseGet(() -> {
+ logger.debug("No Configuration matched by id");
+ return null;
+ });
+ }
+
+ public GenericVnf getAAIGenericVnf(String vnfId) {
+
+ return this.injectionHelper.getAaiClient()
+ .get(GenericVnf.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE))
+ .orElseGet(() -> {
+ logger.debug("No Generic Vnf matched by id");
+ return null;
+ });
+ }
+
+ public VolumeGroup getAAIVolumeGroup(String cloudOwnerId, String cloudRegionId, String volumeGroupId) {
+ return this.injectionHelper.getAaiClient()
+ .get(VolumeGroup.class, AAIUriFactory
+ .createResourceUri(AAIObjectType.VOLUME_GROUP, cloudOwnerId, cloudRegionId, volumeGroupId)
+ .depth(Depth.ONE))
+ .orElseGet(() -> {
+ logger.debug("No Generic Vnf matched by id");
+ return null;
+ });
+ }
+
+ public VfModule getAAIVfModule(String vnfId, String vfModuleId) {
+ return this.injectionHelper.getAaiClient()
+ .get(VfModule.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId).depth(Depth.ONE))
+ .orElseGet(() -> {
+ logger.debug("No Generic Vnf matched by id");
+ return null;
+ });
+ }
+
+ public L3Network getAAIL3Network(String networkId) {
+
+ return this.injectionHelper.getAaiClient()
+ .get(L3Network.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ONE))
+ .orElseGet(() -> {
+ logger.debug("No Generic Vnf matched by id");
+ return null;
+ });
+
+ }
+
+ public Optional<ServiceInstance> getRelatedServiceInstanceFromInstanceGroup(String instanceGroupId)
+ throws Exception {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId);
+ uri.relatedTo(AAIObjectPlurals.SERVICE_INSTANCE);
+ Optional<ServiceInstances> serviceInstances = injectionHelper.getAaiClient().get(ServiceInstances.class, uri);
+ ServiceInstance serviceInstance = null;
+ if (!serviceInstances.isPresent()) {
+ logger.debug("No ServiceInstances were found");
+ return Optional.empty();
+ } else {
+ if (serviceInstances.get().getServiceInstance().isEmpty()) {
+ throw new NoServiceInstanceFoundException("No ServiceInstances Returned");
+ } else if (serviceInstances.get().getServiceInstance().size() > 1) {
+ throw new MultipleObjectsFoundException("Multiple ServiceInstances Returned");
+ } else {
+ serviceInstance = serviceInstances.get().getServiceInstance().get(0);
+ }
+ return Optional.of(serviceInstance);
+ }
+ }
+
+ public Optional<L3Network> getRelatedNetworkByNameFromServiceInstance(String serviceInstanceId, String networkName)
+ throws Exception {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId);
+ uri.relatedTo(AAIObjectPlurals.L3_NETWORK).queryParam("network-name", networkName);
+ Optional<L3Networks> networks = injectionHelper.getAaiClient().get(L3Networks.class, uri);
+ L3Network network = null;
+ if (!networks.isPresent()) {
+ logger.debug("No Networks matched by name");
+ return Optional.empty();
+ } else {
+ if (networks.get().getL3Network().size() > 1) {
+ throw new Exception("Multiple Networks Returned");
+ } else {
+ network = networks.get().getL3Network().get(0);
+ }
+ return Optional.of(network);
+ }
+ }
+
+ public Optional<GenericVnf> getRelatedVnfByNameFromServiceInstance(String serviceInstanceId, String vnfName)
+ throws Exception {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId);
+ uri.relatedTo(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", vnfName);
+ Optional<GenericVnfs> vnfs = injectionHelper.getAaiClient().get(GenericVnfs.class, uri);
+ GenericVnf vnf = null;
+ if (!vnfs.isPresent()) {
+ logger.debug("No Vnfs matched by name");
+ return Optional.empty();
+ } else {
+ if (vnfs.get().getGenericVnf().size() > 1) {
+ throw new Exception("Multiple Vnfs Returned");
+ } else {
+ vnf = vnfs.get().getGenericVnf().get(0);
+ }
+ return Optional.of(vnf);
+ }
+ }
+
+ public Optional<VolumeGroup> getRelatedVolumeGroupByNameFromVnf(String vnfId, String volumeGroupName)
+ throws Exception {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
+ uri.relatedTo(AAIObjectPlurals.VOLUME_GROUP).queryParam("volume-group-name", volumeGroupName);
+ Optional<VolumeGroups> volumeGroups = injectionHelper.getAaiClient().get(VolumeGroups.class, uri);
+ VolumeGroup volumeGroup = null;
+ if (!volumeGroups.isPresent()) {
+ logger.debug("No VolumeGroups matched by name");
+ return Optional.empty();
+ } else {
+ if (volumeGroups.get().getVolumeGroup().size() > 1) {
+ throw new Exception("Multiple VolumeGroups Returned");
+ } else {
+ volumeGroup = volumeGroups.get().getVolumeGroup().get(0);
+ }
+ return Optional.of(volumeGroup);
+ }
+ }
+
+ public Optional<VolumeGroup> getRelatedVolumeGroupByNameFromVfModule(String vnfId, String vfModuleId,
+ String volumeGroupName) throws Exception {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId);
+ uri.relatedTo(AAIObjectPlurals.VOLUME_GROUP).queryParam("volume-group-name", volumeGroupName);
+ Optional<VolumeGroups> volumeGroups = injectionHelper.getAaiClient().get(VolumeGroups.class, uri);
+ VolumeGroup volumeGroup = null;
+ if (!volumeGroups.isPresent()) {
+ logger.debug("No VolumeGroups matched by name");
+ return Optional.empty();
+ } else {
+ if (volumeGroups.get().getVolumeGroup().size() > 1) {
+ throw new Exception("Multiple VolumeGroups Returned");
+ } else {
+ volumeGroup = volumeGroups.get().getVolumeGroup().get(0);
+ }
+ return Optional.of(volumeGroup);
+ }
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/CloudInfoFromAAI.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/CloudInfoFromAAI.java
index 7fcc613913..e4012e1290 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/CloudInfoFromAAI.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/CloudInfoFromAAI.java
@@ -24,7 +24,6 @@ package org.onap.so.bpmn.servicedecomposition.tasks;
import java.util.List;
import java.util.Optional;
-
import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
import org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network;
@@ -37,80 +36,81 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
@Component
public class CloudInfoFromAAI {
- private static final Logger logger = LoggerFactory.getLogger(CloudInfoFromAAI.class);
- @Autowired
- private BBInputSetupUtils bbInputSetupUtils;
-
- public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) {
- this.bbInputSetupUtils = bbInputSetupUtils;
- }
-
- protected Optional<CloudRegion> getCloudInfoFromAAI(ServiceInstance serviceInstance) throws JsonProcessingException {
- Optional<Relationships> relationshipsOp = Optional.empty();
- if(!serviceInstance.getVnfs().isEmpty()) {
- GenericVnf vnf = serviceInstance.getVnfs().get(0);
- org.onap.aai.domain.yang.GenericVnf aaiVnf = bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId());
- AAIResultWrapper vnfWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiVnf));
- relationshipsOp = getRelationshipsFromWrapper(vnfWrapper);
- } else if(!serviceInstance.getNetworks().isEmpty()) {
- L3Network network = serviceInstance.getNetworks().get(0);
- org.onap.aai.domain.yang.L3Network aaiL3Network = bbInputSetupUtils.getAAIL3Network(network.getNetworkId());
- AAIResultWrapper networkWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiL3Network));
- relationshipsOp = getRelationshipsFromWrapper(networkWrapper);
- } else {
- logger.debug("BBInputSetup could not find a cloud region or tenant, since there are no resources under the SI.");
- return Optional.empty();
- }
- if (relationshipsOp.isPresent()) {
- return getRelatedCloudRegionAndTenant(relationshipsOp.get());
- } else {
- logger.debug("BBInputSetup could not find a cloud region or tenant");
- return Optional.empty();
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(CloudInfoFromAAI.class);
+ @Autowired
+ private BBInputSetupUtils bbInputSetupUtils;
+
+ public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) {
+ this.bbInputSetupUtils = bbInputSetupUtils;
+ }
+
+ protected Optional<CloudRegion> getCloudInfoFromAAI(ServiceInstance serviceInstance)
+ throws JsonProcessingException {
+ Optional<Relationships> relationshipsOp = Optional.empty();
+ if (!serviceInstance.getVnfs().isEmpty()) {
+ GenericVnf vnf = serviceInstance.getVnfs().get(0);
+ org.onap.aai.domain.yang.GenericVnf aaiVnf = bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId());
+ AAIResultWrapper vnfWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiVnf));
+ relationshipsOp = getRelationshipsFromWrapper(vnfWrapper);
+ } else if (!serviceInstance.getNetworks().isEmpty()) {
+ L3Network network = serviceInstance.getNetworks().get(0);
+ org.onap.aai.domain.yang.L3Network aaiL3Network = bbInputSetupUtils.getAAIL3Network(network.getNetworkId());
+ AAIResultWrapper networkWrapper = new AAIResultWrapper(
+ new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiL3Network));
+ relationshipsOp = getRelationshipsFromWrapper(networkWrapper);
+ } else {
+ logger.debug(
+ "BBInputSetup could not find a cloud region or tenant, since there are no resources under the SI.");
+ return Optional.empty();
+ }
+ if (relationshipsOp.isPresent()) {
+ return getRelatedCloudRegionAndTenant(relationshipsOp.get());
+ } else {
+ logger.debug("BBInputSetup could not find a cloud region or tenant");
+ return Optional.empty();
+ }
+ }
- protected Optional<Relationships> getRelationshipsFromWrapper(AAIResultWrapper wrapper) {
- Optional<Relationships> relationshipsOp;
- relationshipsOp = wrapper.getRelationships();
- if(relationshipsOp.isPresent()) {
- return relationshipsOp;
- }
- return Optional.empty();
- }
+ protected Optional<Relationships> getRelationshipsFromWrapper(AAIResultWrapper wrapper) {
+ Optional<Relationships> relationshipsOp;
+ relationshipsOp = wrapper.getRelationships();
+ if (relationshipsOp.isPresent()) {
+ return relationshipsOp;
+ }
+ return Optional.empty();
+ }
- protected Optional<CloudRegion> getRelatedCloudRegionAndTenant(Relationships relationships) {
- CloudRegion cloudRegion = new CloudRegion();
- List<AAIResultWrapper> cloudRegions = relationships.getByType(AAIObjectType.CLOUD_REGION);
- List<AAIResultWrapper> tenants = relationships.getByType(AAIObjectType.TENANT);
- if(!cloudRegions.isEmpty()) {
- AAIResultWrapper cloudRegionWrapper = cloudRegions.get(0);
- Optional<org.onap.aai.domain.yang.CloudRegion> aaiCloudRegionOp = cloudRegionWrapper
- .asBean(org.onap.aai.domain.yang.CloudRegion.class);
- if(aaiCloudRegionOp.isPresent()) {
- org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = aaiCloudRegionOp.get();
- cloudRegion.setCloudOwner(aaiCloudRegion.getCloudOwner());
- cloudRegion.setCloudRegionVersion(aaiCloudRegion.getCloudRegionVersion());
- cloudRegion.setLcpCloudRegionId(aaiCloudRegion.getCloudRegionId());
- cloudRegion.setComplex(aaiCloudRegion.getComplexName());
- }
- }
- if(!tenants.isEmpty()) {
- AAIResultWrapper tenantWrapper = tenants.get(0);
- Optional<org.onap.aai.domain.yang.Tenant> aaiTenantOp = tenantWrapper
- .asBean(org.onap.aai.domain.yang.Tenant.class);
- if(aaiTenantOp.isPresent()) {
- org.onap.aai.domain.yang.Tenant aaiTenant = aaiTenantOp.get();
- cloudRegion.setTenantId(aaiTenant.getTenantId());
- }
- }
- return Optional.of(cloudRegion);
- }
+ protected Optional<CloudRegion> getRelatedCloudRegionAndTenant(Relationships relationships) {
+ CloudRegion cloudRegion = new CloudRegion();
+ List<AAIResultWrapper> cloudRegions = relationships.getByType(AAIObjectType.CLOUD_REGION);
+ List<AAIResultWrapper> tenants = relationships.getByType(AAIObjectType.TENANT);
+ if (!cloudRegions.isEmpty()) {
+ AAIResultWrapper cloudRegionWrapper = cloudRegions.get(0);
+ Optional<org.onap.aai.domain.yang.CloudRegion> aaiCloudRegionOp =
+ cloudRegionWrapper.asBean(org.onap.aai.domain.yang.CloudRegion.class);
+ if (aaiCloudRegionOp.isPresent()) {
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = aaiCloudRegionOp.get();
+ cloudRegion.setCloudOwner(aaiCloudRegion.getCloudOwner());
+ cloudRegion.setCloudRegionVersion(aaiCloudRegion.getCloudRegionVersion());
+ cloudRegion.setLcpCloudRegionId(aaiCloudRegion.getCloudRegionId());
+ cloudRegion.setComplex(aaiCloudRegion.getComplexName());
+ }
+ }
+ if (!tenants.isEmpty()) {
+ AAIResultWrapper tenantWrapper = tenants.get(0);
+ Optional<org.onap.aai.domain.yang.Tenant> aaiTenantOp =
+ tenantWrapper.asBean(org.onap.aai.domain.yang.Tenant.class);
+ if (aaiTenantOp.isPresent()) {
+ org.onap.aai.domain.yang.Tenant aaiTenant = aaiTenantOp.get();
+ cloudRegion.setTenantId(aaiTenant.getTenantId());
+ }
+ }
+ return Optional.of(cloudRegion);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java
index aa992d6153..c8e296d5ac 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java
@@ -23,7 +23,6 @@
package org.onap.so.bpmn.servicedecomposition.tasks;
import java.util.Map;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.so.bpmn.core.WorkflowException;
@@ -44,154 +43,154 @@ import org.springframework.stereotype.Component;
@Component
public class ExecuteBuildingBlockRainyDay {
- private static final Logger logger = LoggerFactory.getLogger(ExecuteBuildingBlockRainyDay.class);
- public static final String HANDLING_CODE = "handlingCode";
+ private static final Logger logger = LoggerFactory.getLogger(ExecuteBuildingBlockRainyDay.class);
+ public static final String HANDLING_CODE = "handlingCode";
+
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+ @Autowired
+ private RequestsDbClient requestDbclient;
+ private static final String ASTERISK = "*";
+
+ @Autowired
+ private Environment environment;
+ protected String retryDurationPath = "mso.rainyDay.retryDurationMultiplier";
+ protected String defaultCode = "mso.rainyDay.defaultCode";
+ protected String maxRetries = "mso.rainyDay.maxRetries";
+
+ public void setRetryTimer(DelegateExecution execution) {
+ try {
+ int retryDurationMult = Integer.parseInt(this.environment.getProperty(retryDurationPath));
+ int retryCount = (int) execution.getVariable("retryCount");
+ int retryTimeToWait = (int) Math.pow(retryDurationMult, retryCount) * 10;
+ String RetryDuration = "PT" + retryTimeToWait + "S";
+ execution.setVariable("RetryDuration", RetryDuration);
+ } catch (Exception e) {
+ logger.error("Exception occurred", e);
+ throw new BpmnError("Unknown error incrementing retry counter");
+ }
+ }
+
+ public void queryRainyDayTable(DelegateExecution execution, boolean primaryPolicy) {
+ try {
+ ExecuteBuildingBlock ebb = (ExecuteBuildingBlock) execution.getVariable("buildingBlock");
+ String bbName = ebb.getBuildingBlock().getBpmnFlowName();
+ GeneralBuildingBlock gBBInput = (GeneralBuildingBlock) execution.getVariable("gBBInput");
+ String requestId = (String) execution.getVariable("mso-request-id");
+ Map<ResourceKey, String> lookupKeyMap = (Map<ResourceKey, String>) execution.getVariable("lookupKeyMap");
+ String serviceType = ASTERISK;
+ boolean aLaCarte = (boolean) execution.getVariable("aLaCarte");
+ boolean suppressRollback = (boolean) execution.getVariable("suppressRollback");
+ String handlingCode = "";
+
+ WorkflowException workflowException = (WorkflowException) execution.getVariable("WorkflowException");
+ try {
+ // Extract error data to be returned to WorkflowAction
+ execution.setVariable("WorkflowExceptionErrorMessage", workflowException.getErrorMessage());
+ } catch (Exception e) {
+ logger.error("No WorkflowException Found", e);
+ }
- @Autowired
- private CatalogDbClient catalogDbClient;
- @Autowired
- private RequestsDbClient requestDbclient;
- private static final String ASTERISK = "*";
+ if (suppressRollback) {
+ handlingCode = "Abort";
+ } else {
+ try {
+ serviceType = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0)
+ .getModelInfoServiceInstance().getServiceType();
+ } catch (Exception ex) {
+ // keep default serviceType value
+ }
+ String vnfType = ASTERISK;
+ try {
+ for (GenericVnf vnf : gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0)
+ .getVnfs()) {
+ if (vnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
+ vnfType = vnf.getVnfType();
+ }
+ }
+ } catch (Exception ex) {
+ // keep default vnfType value
+ }
- @Autowired
- private Environment environment;
- protected String retryDurationPath = "mso.rainyDay.retryDurationMultiplier";
- protected String defaultCode = "mso.rainyDay.defaultCode";
- protected String maxRetries = "mso.rainyDay.maxRetries";
+ String errorCode = ASTERISK;
+ try {
+ errorCode = "" + workflowException.getErrorCode();
+ } catch (Exception ex) {
+ // keep default errorCode value
+ }
+ try {
+ errorCode = "" + (String) execution.getVariable("WorkflowExceptionCode");
+ } catch (Exception ex) {
+ // keep default errorCode value
+ }
- public void setRetryTimer(DelegateExecution execution) {
- try {
- int retryDurationMult = Integer.parseInt(this.environment.getProperty(retryDurationPath));
- int retryCount = (int) execution.getVariable("retryCount");
- int retryTimeToWait = (int) Math.pow(retryDurationMult, retryCount) * 10;
- String RetryDuration = "PT" + retryTimeToWait + "S";
- execution.setVariable("RetryDuration", RetryDuration);
- } catch (Exception e) {
- logger.error("Exception occurred", e);
- throw new BpmnError("Unknown error incrementing retry counter");
- }
- }
+ String workStep = ASTERISK;
+ try {
+ workStep = workflowException.getWorkStep();
+ } catch (Exception ex) {
+ // keep default workStep value
+ }
- public void queryRainyDayTable(DelegateExecution execution, boolean primaryPolicy) {
- try {
- ExecuteBuildingBlock ebb = (ExecuteBuildingBlock) execution.getVariable("buildingBlock");
- String bbName = ebb.getBuildingBlock().getBpmnFlowName();
- GeneralBuildingBlock gBBInput = (GeneralBuildingBlock) execution.getVariable("gBBInput");
- String requestId = (String) execution.getVariable("mso-request-id");
- Map<ResourceKey, String> lookupKeyMap = (Map<ResourceKey, String>) execution.getVariable("lookupKeyMap");
- String serviceType = ASTERISK;
- boolean aLaCarte = (boolean) execution.getVariable("aLaCarte");
- boolean suppressRollback = (boolean) execution.getVariable("suppressRollback");
- String handlingCode = "";
-
- WorkflowException workflowException = (WorkflowException) execution.getVariable("WorkflowException");
- try {
- // Extract error data to be returned to WorkflowAction
- execution.setVariable("WorkflowExceptionErrorMessage", workflowException.getErrorMessage());
- } catch (Exception e) {
- logger.error("No WorkflowException Found",e);
- }
-
- if (suppressRollback) {
- handlingCode = "Abort";
- } else {
- try {
- serviceType = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0)
- .getModelInfoServiceInstance().getServiceType();
- } catch (Exception ex) {
- // keep default serviceType value
- }
- String vnfType = ASTERISK;
- try {
- for (GenericVnf vnf : gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0)
- .getVnfs()) {
- if (vnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
- vnfType = vnf.getVnfType();
- }
- }
- } catch (Exception ex) {
- // keep default vnfType value
- }
-
- String errorCode = ASTERISK;
- try {
- errorCode = "" + workflowException.getErrorCode();
- } catch (Exception ex) {
- // keep default errorCode value
- }
- try {
- errorCode = "" + (String) execution.getVariable("WorkflowExceptionCode");
- } catch (Exception ex) {
- // keep default errorCode value
- }
+ RainyDayHandlerStatus rainyDayHandlerStatus;
+ rainyDayHandlerStatus = catalogDbClient
+ .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(bbName,
+ serviceType, vnfType, errorCode, workStep);
+ if (rainyDayHandlerStatus == null) {
+ rainyDayHandlerStatus = catalogDbClient
+ .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(bbName,
+ ASTERISK, ASTERISK, errorCode, ASTERISK);
+ }
- String workStep = ASTERISK;
- try {
- workStep = workflowException.getWorkStep();
- } catch (Exception ex) {
- // keep default workStep value
- }
-
- RainyDayHandlerStatus rainyDayHandlerStatus;
- rainyDayHandlerStatus = catalogDbClient
- .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(bbName,
- serviceType, vnfType, errorCode, workStep);
- if (rainyDayHandlerStatus == null) {
- rainyDayHandlerStatus = catalogDbClient
- .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(bbName,
- ASTERISK, ASTERISK, errorCode, ASTERISK);
- }
-
- if (rainyDayHandlerStatus == null) {
- rainyDayHandlerStatus = catalogDbClient
- .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(bbName,
- ASTERISK, ASTERISK, ASTERISK, ASTERISK);
- if (rainyDayHandlerStatus == null) {
- handlingCode = "Abort";
- } else {
- if (primaryPolicy) {
- handlingCode = rainyDayHandlerStatus.getPolicy();
- } else {
- handlingCode = rainyDayHandlerStatus.getSecondaryPolicy();
- }
- }
- } else {
- if (primaryPolicy) {
- handlingCode = rainyDayHandlerStatus.getPolicy();
- } else {
- handlingCode = rainyDayHandlerStatus.getSecondaryPolicy();
- }
- }
- if (!primaryPolicy) {
- try {
- InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
- request.setRetryStatusMessage("Retries have been exhausted.");
- requestDbclient.updateInfraActiveRequests(request);
- } catch (Exception ex) {
- logger.error("Failed to update Request Db Infra Active Requests with Retry Status",ex);
- }
- }
- if (handlingCode.equals("RollbackToAssigned") && !aLaCarte) {
- handlingCode = "Rollback";
- }
- }
- logger.debug("RainyDayHandler Status Code is: {}", handlingCode);
- execution.setVariable(HANDLING_CODE, handlingCode);
- } catch (Exception e) {
- String code = this.environment.getProperty(defaultCode);
- logger.error("Failed to determine RainyDayHandler Status. Seting handlingCode = {}", code, e);
- execution.setVariable(HANDLING_CODE, code);
- }
- try{
- int envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
- execution.setVariable("maxRetries", envMaxRetries);
- } catch (Exception ex) {
- logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
- execution.setVariable("maxRetries", 5);
- }
- }
+ if (rainyDayHandlerStatus == null) {
+ rainyDayHandlerStatus = catalogDbClient
+ .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(bbName,
+ ASTERISK, ASTERISK, ASTERISK, ASTERISK);
+ if (rainyDayHandlerStatus == null) {
+ handlingCode = "Abort";
+ } else {
+ if (primaryPolicy) {
+ handlingCode = rainyDayHandlerStatus.getPolicy();
+ } else {
+ handlingCode = rainyDayHandlerStatus.getSecondaryPolicy();
+ }
+ }
+ } else {
+ if (primaryPolicy) {
+ handlingCode = rainyDayHandlerStatus.getPolicy();
+ } else {
+ handlingCode = rainyDayHandlerStatus.getSecondaryPolicy();
+ }
+ }
+ if (!primaryPolicy) {
+ try {
+ InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
+ request.setRetryStatusMessage("Retries have been exhausted.");
+ requestDbclient.updateInfraActiveRequests(request);
+ } catch (Exception ex) {
+ logger.error("Failed to update Request Db Infra Active Requests with Retry Status", ex);
+ }
+ }
+ if (handlingCode.equals("RollbackToAssigned") && !aLaCarte) {
+ handlingCode = "Rollback";
+ }
+ }
+ logger.debug("RainyDayHandler Status Code is: {}", handlingCode);
+ execution.setVariable(HANDLING_CODE, handlingCode);
+ } catch (Exception e) {
+ String code = this.environment.getProperty(defaultCode);
+ logger.error("Failed to determine RainyDayHandler Status. Seting handlingCode = {}", code, e);
+ execution.setVariable(HANDLING_CODE, code);
+ }
+ try {
+ int envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
+ execution.setVariable("maxRetries", envMaxRetries);
+ } catch (Exception ex) {
+ logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
+ execution.setVariable("maxRetries", 5);
+ }
+ }
- public void setHandlingStatusSuccess(DelegateExecution execution) {
- execution.setVariable(HANDLING_CODE, "Success");
- }
+ public void setHandlingStatusSuccess(DelegateExecution execution) {
+ execution.setVariable(HANDLING_CODE, "Success");
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java
index 8af6e809f4..4332a6cf4e 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java
@@ -26,9 +26,7 @@ import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Optional;
-
import javax.persistence.Id;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance;
@@ -38,111 +36,115 @@ import org.onap.so.client.exception.BBObjectNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-
import com.google.common.base.CaseFormat;
@Component
public class ExtractPojosForBB {
- private static final Logger logger = LoggerFactory.getLogger(ExtractPojosForBB.class);
-
- public <T> T extractByKey(BuildingBlockExecution execution, ResourceKey key) throws BBObjectNotFoundException {
- return extractByKey(execution, key, execution.getLookupMap().get(key));
- }
- public <T> T extractByKey(BuildingBlockExecution execution, ResourceKey key, String value)
- throws BBObjectNotFoundException {
+ private static final Logger logger = LoggerFactory.getLogger(ExtractPojosForBB.class);
+
+ public <T> T extractByKey(BuildingBlockExecution execution, ResourceKey key) throws BBObjectNotFoundException {
+ return extractByKey(execution, key, execution.getLookupMap().get(key));
+ }
+
+ public <T> T extractByKey(BuildingBlockExecution execution, ResourceKey key, String value)
+ throws BBObjectNotFoundException {
+
+ Optional<T> result = Optional.empty();
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ try {
+ ServiceInstance serviceInstance;
+ GenericVnf vnf;
+ switch (key) {
+ case SERVICE_INSTANCE_ID:
+ result = lookupObjectInList(gBBInput.getCustomer().getServiceSubscription().getServiceInstances(),
+ value);
+ break;
+ case GENERIC_VNF_ID:
+ serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ result = lookupObjectInList(serviceInstance.getVnfs(), value);
+ break;
+ case NETWORK_ID:
+ serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ result = lookupObjectInList(serviceInstance.getNetworks(), value);
+ break;
+ case VOLUME_GROUP_ID:
+ vnf = extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ result = lookupObjectInList(vnf.getVolumeGroups(), value);
+ break;
+ case VF_MODULE_ID:
+ vnf = extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ result = lookupObjectInList(vnf.getVfModules(), value);
+ break;
+ case ALLOTTED_RESOURCE_ID:
+ serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ result = lookupObjectInList(serviceInstance.getAllottedResources(), value);
+ break;
+ case CONFIGURATION_ID:
+ serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ result = lookupObjectInList(serviceInstance.getConfigurations(), value);
+ break;
+ case VPN_ID:
+ serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ result = lookupObjectInList(gBBInput.getCustomer().getVpnBindings(), value);
+ break;
+ case VPN_BONDING_LINK_ID:
+ serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ result = lookupObjectInList(serviceInstance.getVpnBondingLinks(), value);
+ break;
+ case INSTANCE_GROUP_ID:
+ serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ result = lookupObjectInList(serviceInstance.getInstanceGroups(), value);
+ break;
+ default:
+ throw new BBObjectNotFoundException(key, value);
+ }
+ } catch (BBObjectNotFoundException e) { // re-throw parent object not found
+ throw e;
+ } catch (Exception e) { // convert all other exceptions to object not found
+ logger.warn("BBObjectNotFoundException in ExtractPojosForBB",
+ "BBObject " + key + " was not found in " + "gBBInput using reference value: " + value);
+ throw new BBObjectNotFoundException(key, value);
+ }
+
+ if (result.isPresent()) {
+ return result.get();
+ } else {
+ throw new BBObjectNotFoundException(key, value);
+ }
+ }
+
+ protected <T> Optional<T> lookupObject(Object obj, String value) throws IllegalAccessException,
+ IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
+ return findValue(obj, value);
+ }
+
+ protected <T> Optional<T> lookupObjectInList(List<?> list, String value) throws IllegalAccessException,
+ IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
+ Optional<T> result = Optional.empty();
+ for (Object obj : list) {
+ result = findValue(obj, value);
+ if (result.isPresent()) {
+ break;
+ }
+ }
+ return result;
+
+ }
- Optional<T> result = Optional.empty();
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- try {
- ServiceInstance serviceInstance;
- GenericVnf vnf;
- switch (key) {
- case SERVICE_INSTANCE_ID:
- result = lookupObjectInList(gBBInput.getCustomer().getServiceSubscription().getServiceInstances(), value);
- break;
- case GENERIC_VNF_ID:
- serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- result = lookupObjectInList(serviceInstance.getVnfs(), value);
- break;
- case NETWORK_ID:
- serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- result = lookupObjectInList(serviceInstance.getNetworks(), value);
- break;
- case VOLUME_GROUP_ID:
- vnf = extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- result = lookupObjectInList(vnf.getVolumeGroups(), value);
- break;
- case VF_MODULE_ID:
- vnf = extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- result = lookupObjectInList(vnf.getVfModules(), value);
- break;
- case ALLOTTED_RESOURCE_ID:
- serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- result = lookupObjectInList(serviceInstance.getAllottedResources(), value);
- break;
- case CONFIGURATION_ID:
- serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- result = lookupObjectInList(serviceInstance.getConfigurations(), value);
- break;
- case VPN_ID:
- serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- result = lookupObjectInList(gBBInput.getCustomer().getVpnBindings(), value);
- break;
- case VPN_BONDING_LINK_ID:
- serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- result = lookupObjectInList(serviceInstance.getVpnBondingLinks(),value);
- break;
- case INSTANCE_GROUP_ID:
- serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- result = lookupObjectInList(serviceInstance.getInstanceGroups(), value);
- break;
- default:
- throw new BBObjectNotFoundException(key, value);
- }
- } catch (BBObjectNotFoundException e) { // re-throw parent object not found
- throw e;
- } catch (Exception e) { // convert all other exceptions to object not found
- logger.warn("BBObjectNotFoundException in ExtractPojosForBB", "BBObject " + key + " was not found in "
- + "gBBInput using reference value: " + value);
- throw new BBObjectNotFoundException(key, value);
- }
-
- if (result.isPresent()) {
- return result.get();
- } else {
- throw new BBObjectNotFoundException(key, value);
- }
- }
-
- protected <T> Optional<T> lookupObject(Object obj, String value) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
- return findValue(obj, value);
- }
+ protected <T> Optional<T> findValue(Object obj, String value) throws IllegalAccessException,
+ IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
+ for (Field field : obj.getClass().getDeclaredFields()) {
+ if (field.isAnnotationPresent(Id.class)) {
+ String fieldName = field.getName();
+ fieldName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, fieldName);
+ String fieldValue = (String) obj.getClass().getMethod("get" + fieldName).invoke(obj);
+ if (fieldValue.equals(value)) {
+ return Optional.of((T) obj);
+ }
+ }
+ }
- protected <T> Optional<T> lookupObjectInList(List<?> list, String value) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
- Optional<T> result = Optional.empty();
- for (Object obj : list) {
- result = findValue(obj, value);
- if (result.isPresent()) {
- break;
- }
- }
- return result;
-
- }
-
- protected <T> Optional<T> findValue(Object obj, String value) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
- for (Field field : obj.getClass().getDeclaredFields()) {
- if (field.isAnnotationPresent(Id.class)) {
- String fieldName = field.getName();
- fieldName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, fieldName);
- String fieldValue = (String) obj.getClass().getMethod("get" + fieldName).invoke(obj);
- if (fieldValue.equals(value)) {
- return Optional.of((T)obj);
- }
- }
- }
-
- return Optional.empty();
- }
+ return Optional.empty();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/MultipleObjectsFoundException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/MultipleObjectsFoundException.java
index d63f98b6ce..ab24cf155c 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/MultipleObjectsFoundException.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/MultipleObjectsFoundException.java
@@ -22,26 +22,26 @@ package org.onap.so.bpmn.servicedecomposition.tasks.exceptions;
public class MultipleObjectsFoundException extends Exception {
- private static final long serialVersionUID = -5045275644426587447L;
-
- public MultipleObjectsFoundException() {
- super();
- }
-
- public MultipleObjectsFoundException(String message) {
- super(message);
- }
-
- public MultipleObjectsFoundException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public MultipleObjectsFoundException(Throwable cause) {
- super(cause);
- }
-
- public MultipleObjectsFoundException(String message, Throwable cause, boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
+ private static final long serialVersionUID = -5045275644426587447L;
+
+ public MultipleObjectsFoundException() {
+ super();
+ }
+
+ public MultipleObjectsFoundException(String message) {
+ super(message);
+ }
+
+ public MultipleObjectsFoundException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public MultipleObjectsFoundException(Throwable cause) {
+ super(cause);
+ }
+
+ public MultipleObjectsFoundException(String message, Throwable cause, boolean enableSuppression,
+ boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/NoServiceInstanceFoundException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/NoServiceInstanceFoundException.java
index 2ef1a80cce..acf222566a 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/NoServiceInstanceFoundException.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/NoServiceInstanceFoundException.java
@@ -22,26 +22,26 @@ package org.onap.so.bpmn.servicedecomposition.tasks.exceptions;
public class NoServiceInstanceFoundException extends Exception {
- private static final long serialVersionUID = 3270499954054029908L;
-
- public NoServiceInstanceFoundException() {
- super();
- }
-
- public NoServiceInstanceFoundException(String message) {
- super(message);
- }
-
- public NoServiceInstanceFoundException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public NoServiceInstanceFoundException(Throwable cause) {
- super(cause);
- }
-
- public NoServiceInstanceFoundException(String message, Throwable cause, boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
+ private static final long serialVersionUID = 3270499954054029908L;
+
+ public NoServiceInstanceFoundException() {
+ super();
+ }
+
+ public NoServiceInstanceFoundException(String message) {
+ super(message);
+ }
+
+ public NoServiceInstanceFoundException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public NoServiceInstanceFoundException(Throwable cause) {
+ super(cause);
+ }
+
+ public NoServiceInstanceFoundException(String message, Throwable cause, boolean enableSuppression,
+ boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerAction.java
index a15e044818..eccd81217f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerAction.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerAction.java
@@ -23,7 +23,6 @@ package org.onap.so.client.appc;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
-
import org.onap.appc.client.lcm.model.Action;
import org.onap.appc.client.lcm.model.Status;
import org.onap.so.bpmn.appc.payload.PayloadClient;
@@ -32,154 +31,163 @@ import org.onap.so.client.appc.ApplicationControllerSupport.StatusCategory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class ApplicationControllerAction {
- protected ApplicationControllerOrchestrator client = new ApplicationControllerOrchestrator();
- private String errorCode = "1002";
- private String errorMessage = "Unable to reach App C Servers";
- private static Logger logger = LoggerFactory.getLogger(ApplicationControllerAction.class);
-
- public void runAppCCommand(Action action, String msoRequestId, String vnfId, Optional<String> payload, HashMap<String, String> payloadInfo, String controllerType){
- Status appCStatus = null;
- try{
- String vnfName = payloadInfo.getOrDefault("vnfName", "");
- String aicIdentity = payloadInfo.getOrDefault("vnfName","");
- String vnfHostIpAddress = payloadInfo.getOrDefault("vnfHostIpAddress","");
- String vmIdList = payloadInfo.getOrDefault("vmIdList", "");
- String vserverIdList = payloadInfo.getOrDefault("vserverIdList", "");
- String identityUrl = payloadInfo.getOrDefault("identityUrl", "");
- switch(action){
- case ResumeTraffic:
- appCStatus = resumeTrafficAction(msoRequestId, vnfId, vnfName, controllerType);
- break;
- case Start:
- case Stop:
- appCStatus = startStopAction(action, msoRequestId, vnfId, aicIdentity, controllerType);
- break;
- case Unlock:
- case Lock:
- appCStatus = client.vnfCommand(action, msoRequestId, vnfId, Optional.empty(), Optional.empty(), controllerType);
- break;
- case QuiesceTraffic:
- appCStatus = quiesceTrafficAction(msoRequestId, vnfId, payload, vnfName, controllerType);
- break;
- case HealthCheck:
- appCStatus = healthCheckAction(msoRequestId, vnfId, vnfName, vnfHostIpAddress, controllerType);
- break;
- case Snapshot:
- String vmIds = JsonUtils.getJsonValue(vmIdList, "vmIds");
- String vserverIds = JsonUtils.getJsonValue(vserverIdList, "vserverIds");
- String vmId = "";
- String vserverId = "";
- ObjectMapper mapper = new ObjectMapper();
- List<String> vmIdJsonList = mapper.readValue(vmIds, new TypeReference<List<String>>(){});
- List<String> vserverIdJsonList = mapper.readValue(vserverIds, new TypeReference<List<String>>(){});
- int i = 0;
- while(i < vmIdJsonList.size()){
- vmId = vmIdJsonList.get(i);
- vserverId = vserverIdJsonList.get(i);
- Optional<String> vserverIdString = Optional.of(vserverId);
- appCStatus = snapshotAction(msoRequestId, vnfId, vmId, vserverIdString, identityUrl, controllerType);
- i++;
- }
- break;
- case ConfigModify:
- case ConfigScaleOut:
- case DistributeTraffic:
- case DistributeTrafficCheck:
- appCStatus = payloadAction(action, msoRequestId, vnfId, payload, controllerType);
- break;
- case UpgradePreCheck:
- case UpgradePostCheck:
- case UpgradeSoftware:
- case UpgradeBackup:
- appCStatus = upgradeAction(action,msoRequestId, vnfId, payload, vnfName, controllerType);
- break;
- default:
- errorMessage = "Unable to idenify Action request for AppCClient";
- break;
- }
- if(appCStatus != null){
- errorCode = Integer.toString(appCStatus.getCode());
- errorMessage = appCStatus.getMessage();
-
- }
- if(ApplicationControllerSupport.getCategoryOf(appCStatus).equals(StatusCategory.NORMAL)){
- errorCode = "0";
- }
- }
- catch(JsonProcessingException e){
- logger.error("Incorrect Payload format for action request: {}", action.toString(),e);
- errorMessage = e.getMessage();
- }
- catch(ApplicationControllerOrchestratorException e){
- logger.error("Error building Appc request: {}",e.getMessage(), e);
- errorCode = "1002";
- errorMessage = e.getMessage();
- }
- catch (NoSuchMethodError e) {
- logger.error( "Error building Appc request: {}", e.getMessage(), e);
- errorMessage = e.getMessage();
- }
- catch(Exception e){
- logger.error("Error building Appc request: {}", e.getMessage(), e);
- errorMessage = e.getMessage();
- }
- }
-
- private Status payloadAction(Action action, String msoRequestId, String vnfId, Optional<String> payload, String controllerType) throws JsonProcessingException, IllegalArgumentException,ApplicationControllerOrchestratorException{
- if(!(payload.isPresent())){
- throw new IllegalArgumentException("Payload is not present for " + action.toString());
- }
- return client.vnfCommand(action, msoRequestId, vnfId, Optional.empty(), payload, controllerType);
- }
-
- private Status quiesceTrafficAction(String msoRequestId, String vnfId, Optional<String> payload, String vnfName, String controllerType) throws JsonProcessingException, IllegalArgumentException,ApplicationControllerOrchestratorException{
- if(!(payload.isPresent())){
- throw new IllegalArgumentException("Payload is not present for " + Action.QuiesceTraffic.toString());
- }
- payload = PayloadClient.quiesceTrafficFormat(payload, vnfName);
- return client.vnfCommand(Action.QuiesceTraffic, msoRequestId, vnfId, Optional.empty(), payload, controllerType);
- }
-
- private Status upgradeAction(Action action, String msoRequestId, String vnfId, Optional<String> payload, String vnfName, String controllerType) throws JsonProcessingException, IllegalArgumentException,ApplicationControllerOrchestratorException{
- if(!(payload.isPresent())){
- throw new IllegalArgumentException("Payload is not present for " + action.toString());
- }
- payload = PayloadClient.upgradeFormat(payload, vnfName);
- return client.vnfCommand(action, msoRequestId, vnfId, Optional.empty(), payload, controllerType);
- }
-
- private Status resumeTrafficAction(String msoRequestId, String vnfId, String vnfName, String controllerType)throws JsonProcessingException, ApplicationControllerOrchestratorException{
- Optional<String> payload = PayloadClient.resumeTrafficFormat(vnfName);
- return client.vnfCommand(Action.ResumeTraffic, msoRequestId, vnfId, Optional.empty(), payload, controllerType);
- }
-
- private Status startStopAction(Action action, String msoRequestId, String vnfId, String aicIdentity, String controllerType)throws JsonProcessingException, ApplicationControllerOrchestratorException{
- Optional<String> payload = PayloadClient.startStopFormat(aicIdentity);
- return client.vnfCommand(action, msoRequestId, vnfId, Optional.empty(), payload, controllerType);
- }
-
- private Status healthCheckAction(String msoRequestId, String vnfId, String vnfName, String vnfHostIpAddress, String controllerType)throws JsonProcessingException, ApplicationControllerOrchestratorException{
- Optional<String> payload = PayloadClient.healthCheckFormat(vnfName, vnfHostIpAddress);
- return client.vnfCommand(Action.HealthCheck, msoRequestId, vnfId, Optional.empty(), payload, controllerType);
- }
-
- private Status snapshotAction(String msoRequestId, String vnfId, String vmId, Optional<String> vserverId, String identityUrl, String controllerType) throws JsonProcessingException, ApplicationControllerOrchestratorException{
- Optional<String> payload = PayloadClient.snapshotFormat(vmId, identityUrl);
- return client.vnfCommand(Action.Snapshot, msoRequestId, vnfId, vserverId, payload, controllerType);
- }
-
- public String getErrorMessage(){
- return errorMessage;
- }
-
- public String getErrorCode(){
- return errorCode;
- }
+ protected ApplicationControllerOrchestrator client = new ApplicationControllerOrchestrator();
+ private String errorCode = "1002";
+ private String errorMessage = "Unable to reach App C Servers";
+ private static Logger logger = LoggerFactory.getLogger(ApplicationControllerAction.class);
+
+ public void runAppCCommand(Action action, String msoRequestId, String vnfId, Optional<String> payload,
+ HashMap<String, String> payloadInfo, String controllerType) {
+ Status appCStatus = null;
+ try {
+ String vnfName = payloadInfo.getOrDefault("vnfName", "");
+ String aicIdentity = payloadInfo.getOrDefault("vnfName", "");
+ String vnfHostIpAddress = payloadInfo.getOrDefault("vnfHostIpAddress", "");
+ String vmIdList = payloadInfo.getOrDefault("vmIdList", "");
+ String vserverIdList = payloadInfo.getOrDefault("vserverIdList", "");
+ String identityUrl = payloadInfo.getOrDefault("identityUrl", "");
+ switch (action) {
+ case ResumeTraffic:
+ appCStatus = resumeTrafficAction(msoRequestId, vnfId, vnfName, controllerType);
+ break;
+ case Start:
+ case Stop:
+ appCStatus = startStopAction(action, msoRequestId, vnfId, aicIdentity, controllerType);
+ break;
+ case Unlock:
+ case Lock:
+ appCStatus = client.vnfCommand(action, msoRequestId, vnfId, Optional.empty(), Optional.empty(),
+ controllerType);
+ break;
+ case QuiesceTraffic:
+ appCStatus = quiesceTrafficAction(msoRequestId, vnfId, payload, vnfName, controllerType);
+ break;
+ case HealthCheck:
+ appCStatus = healthCheckAction(msoRequestId, vnfId, vnfName, vnfHostIpAddress, controllerType);
+ break;
+ case Snapshot:
+ String vmIds = JsonUtils.getJsonValue(vmIdList, "vmIds");
+ String vserverIds = JsonUtils.getJsonValue(vserverIdList, "vserverIds");
+ String vmId = "";
+ String vserverId = "";
+ ObjectMapper mapper = new ObjectMapper();
+ List<String> vmIdJsonList = mapper.readValue(vmIds, new TypeReference<List<String>>() {});
+ List<String> vserverIdJsonList = mapper.readValue(vserverIds, new TypeReference<List<String>>() {});
+ int i = 0;
+ while (i < vmIdJsonList.size()) {
+ vmId = vmIdJsonList.get(i);
+ vserverId = vserverIdJsonList.get(i);
+ Optional<String> vserverIdString = Optional.of(vserverId);
+ appCStatus =
+ snapshotAction(msoRequestId, vnfId, vmId, vserverIdString, identityUrl, controllerType);
+ i++;
+ }
+ break;
+ case ConfigModify:
+ case ConfigScaleOut:
+ case DistributeTraffic:
+ case DistributeTrafficCheck:
+ appCStatus = payloadAction(action, msoRequestId, vnfId, payload, controllerType);
+ break;
+ case UpgradePreCheck:
+ case UpgradePostCheck:
+ case UpgradeSoftware:
+ case UpgradeBackup:
+ appCStatus = upgradeAction(action, msoRequestId, vnfId, payload, vnfName, controllerType);
+ break;
+ default:
+ errorMessage = "Unable to idenify Action request for AppCClient";
+ break;
+ }
+ if (appCStatus != null) {
+ errorCode = Integer.toString(appCStatus.getCode());
+ errorMessage = appCStatus.getMessage();
+
+ }
+ if (ApplicationControllerSupport.getCategoryOf(appCStatus).equals(StatusCategory.NORMAL)) {
+ errorCode = "0";
+ }
+ } catch (JsonProcessingException e) {
+ logger.error("Incorrect Payload format for action request: {}", action.toString(), e);
+ errorMessage = e.getMessage();
+ } catch (ApplicationControllerOrchestratorException e) {
+ logger.error("Error building Appc request: {}", e.getMessage(), e);
+ errorCode = "1002";
+ errorMessage = e.getMessage();
+ } catch (NoSuchMethodError e) {
+ logger.error("Error building Appc request: {}", e.getMessage(), e);
+ errorMessage = e.getMessage();
+ } catch (Exception e) {
+ logger.error("Error building Appc request: {}", e.getMessage(), e);
+ errorMessage = e.getMessage();
+ }
+ }
+
+ private Status payloadAction(Action action, String msoRequestId, String vnfId, Optional<String> payload,
+ String controllerType)
+ throws JsonProcessingException, IllegalArgumentException, ApplicationControllerOrchestratorException {
+ if (!(payload.isPresent())) {
+ throw new IllegalArgumentException("Payload is not present for " + action.toString());
+ }
+ return client.vnfCommand(action, msoRequestId, vnfId, Optional.empty(), payload, controllerType);
+ }
+
+ private Status quiesceTrafficAction(String msoRequestId, String vnfId, Optional<String> payload, String vnfName,
+ String controllerType)
+ throws JsonProcessingException, IllegalArgumentException, ApplicationControllerOrchestratorException {
+ if (!(payload.isPresent())) {
+ throw new IllegalArgumentException("Payload is not present for " + Action.QuiesceTraffic.toString());
+ }
+ payload = PayloadClient.quiesceTrafficFormat(payload, vnfName);
+ return client.vnfCommand(Action.QuiesceTraffic, msoRequestId, vnfId, Optional.empty(), payload, controllerType);
+ }
+
+ private Status upgradeAction(Action action, String msoRequestId, String vnfId, Optional<String> payload,
+ String vnfName, String controllerType)
+ throws JsonProcessingException, IllegalArgumentException, ApplicationControllerOrchestratorException {
+ if (!(payload.isPresent())) {
+ throw new IllegalArgumentException("Payload is not present for " + action.toString());
+ }
+ payload = PayloadClient.upgradeFormat(payload, vnfName);
+ return client.vnfCommand(action, msoRequestId, vnfId, Optional.empty(), payload, controllerType);
+ }
+
+ private Status resumeTrafficAction(String msoRequestId, String vnfId, String vnfName, String controllerType)
+ throws JsonProcessingException, ApplicationControllerOrchestratorException {
+ Optional<String> payload = PayloadClient.resumeTrafficFormat(vnfName);
+ return client.vnfCommand(Action.ResumeTraffic, msoRequestId, vnfId, Optional.empty(), payload, controllerType);
+ }
+
+ private Status startStopAction(Action action, String msoRequestId, String vnfId, String aicIdentity,
+ String controllerType) throws JsonProcessingException, ApplicationControllerOrchestratorException {
+ Optional<String> payload = PayloadClient.startStopFormat(aicIdentity);
+ return client.vnfCommand(action, msoRequestId, vnfId, Optional.empty(), payload, controllerType);
+ }
+
+ private Status healthCheckAction(String msoRequestId, String vnfId, String vnfName, String vnfHostIpAddress,
+ String controllerType) throws JsonProcessingException, ApplicationControllerOrchestratorException {
+ Optional<String> payload = PayloadClient.healthCheckFormat(vnfName, vnfHostIpAddress);
+ return client.vnfCommand(Action.HealthCheck, msoRequestId, vnfId, Optional.empty(), payload, controllerType);
+ }
+
+ private Status snapshotAction(String msoRequestId, String vnfId, String vmId, Optional<String> vserverId,
+ String identityUrl, String controllerType)
+ throws JsonProcessingException, ApplicationControllerOrchestratorException {
+ Optional<String> payload = PayloadClient.snapshotFormat(vmId, identityUrl);
+ return client.vnfCommand(Action.Snapshot, msoRequestId, vnfId, vserverId, payload, controllerType);
+ }
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public String getErrorCode() {
+ return errorCode;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerCallback.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerCallback.java
index cb3f144cd1..0f21c6c286 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerCallback.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerCallback.java
@@ -23,18 +23,18 @@ package org.onap.so.client.appc;
import org.onap.appc.client.lcm.api.ResponseHandler;
import org.onap.appc.client.lcm.exceptions.AppcClientException;
-public class ApplicationControllerCallback<T> implements ResponseHandler<T> {
-
- @Override
- public void onResponse(T response) {
-
-
- }
-
- @Override
- public void onException(AppcClientException exception) {
-
-
- }
+public class ApplicationControllerCallback<T> implements ResponseHandler<T> {
+
+ @Override
+ public void onResponse(T response) {
+
+
+ }
+
+ @Override
+ public void onException(AppcClientException exception) {
+
+
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerClient.java
index 89eff5f65a..e810fc0259 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerClient.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerClient.java
@@ -26,7 +26,6 @@ import java.time.Instant;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
-
import org.onap.so.bpmn.core.UrnPropertiesReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -47,160 +46,163 @@ import org.onap.appc.client.lcm.model.ZULU;
public class ApplicationControllerClient {
- public static final String DEFAULT_CONTROLLER_TYPE = "APPC";
-
- private static final String CLIENT_NAME = "MSO";
-
- private static final String API_VER = "2.00";
- private static final String ORIGINATOR_ID = "MSO";
- private static final int FLAGS_TTL = 65000;
- private static Logger logger = LoggerFactory.getLogger(ApplicationControllerClient.class);
-
- private ApplicationControllerSupport appCSupport;
-
- // APPC gave us an API where the controllerType is configured in the
- // client object, which is not what we asked for. We asked for an API
- // in which the client would have additional methods that could take
- // the controllerType as a parameter, so that we would not need to
- // maintain multiple client objects. This map should be removed when
- // the (hopefully short-term) controllerType becomes obsolete.
-
- private final String controllerType;
-
- private static ConcurrentHashMap<String, LifeCycleManagerStateful> appCClients = new ConcurrentHashMap<>();
-
- /**
- * Creates an ApplicationControllerClient for communication with APP-C.
- */
- public ApplicationControllerClient() {
- this(DEFAULT_CONTROLLER_TYPE);
- }
-
- /**
- * Creates an ApplicationControllerClient for the specified controller type.
- * @param controllerType the controller type: "appc" or "sdnc".
- */
- public ApplicationControllerClient(String controllerType) {
- if (controllerType == null) {
- controllerType = DEFAULT_CONTROLLER_TYPE;
- }
- this.controllerType = controllerType.toUpperCase();
- appCSupport = new ApplicationControllerSupport();
- }
-
- /**
- * Gets the controller type.
- * @return the controllertype
- */
- public String getControllerType() {
- return controllerType;
- }
-
- /**
- * Returns the AppC client object associated with this ApplicationControllerClient.
- * AppC client objects are shared objects. One is created if it does not exist.
- * @return the client object, or null if creation failed
- */
- public LifeCycleManagerStateful getAppCClient() {
- return appCClients.computeIfAbsent(controllerType, k -> createAppCClient(k));
- }
-
- protected LifeCycleManagerStateful createAppCClient(String controllerType) {
- try {
- if (controllerType == null) {
- controllerType = DEFAULT_CONTROLLER_TYPE;
- }
- controllerType = controllerType.toUpperCase();
- return AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class)
- .createLifeCycleManagerStateful(new ApplicationContext(), getLCMProperties(controllerType));
- } catch (AppcClientException e) {
- logger.error("Error in getting LifeCycleManagerStateful: {}",e.getMessage(), e);
- // This null value will cause NullPointerException when used later.
- // Error handling could certainly be improved here.
- return null;
- }
- }
-
- public Status runCommand(Action action, org.onap.appc.client.lcm.model.ActionIdentifiers actionIdentifiers,
- org.onap.appc.client.lcm.model.Payload payload, String requestID)
- throws ApplicationControllerOrchestratorException {
- Object requestObject;
- requestObject = createRequest(action, actionIdentifiers, payload, requestID);
- appCSupport.logLCMMessage(requestObject);
- LifeCycleManagerStateful client = getAppCClient();
- Method lcmMethod = appCSupport.getAPIMethod(action.name(), client, false);
- try {
- Object response = lcmMethod.invoke(client, requestObject);
- return appCSupport.getStatusFromGenericResponse(response);
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- throw new RuntimeException(String.format("%s : %s", "Unable to invoke action", action.toString()), e);
- }
- }
-
- protected Properties getLCMProperties() {
- return getLCMProperties("appc");
- }
-
- protected Properties getLCMProperties(String controllerType) {
- Properties properties = new Properties();
-
- properties.put("topic.read", UrnPropertiesReader.getVariable("appc.client.topic.read.name"));
- properties.put("topic.write", UrnPropertiesReader.getVariable("appc.client.topic.write"));
- properties.put("SDNC-topic.read", UrnPropertiesReader.getVariable("appc.client.topic.sdnc.read"));
- properties.put("SDNC-topic.write", UrnPropertiesReader.getVariable("appc.client.topic.sdnc.write"));
- properties.put("topic.read.timeout", UrnPropertiesReader.getVariable("appc.client.topic.read.timeout"));
- properties.put("client.response.timeout", UrnPropertiesReader.getVariable("appc.client.response.timeout"));
- properties.put("poolMembers", UrnPropertiesReader.getVariable("appc.client.poolMembers"));
- properties.put("controllerType", controllerType);
- properties.put("client.key", UrnPropertiesReader.getVariable("appc.client.key"));
- properties.put("client.secret", UrnPropertiesReader.getVariable("appc.client.secret"));
- properties.put("client.name", CLIENT_NAME);
- properties.put("service", UrnPropertiesReader.getVariable("appc.client.service"));
- return properties;
- }
-
- public Object createRequest(Action action, ActionIdentifiers identifier, Payload payload, String requestId) {
- Object requestObject = appCSupport.getInput(action.name());
- try {
- CommonHeader commonHeader = buildCommonHeader(requestId);
- requestObject.getClass().getDeclaredMethod("setCommonHeader", CommonHeader.class).invoke(requestObject,
- commonHeader);
- requestObject.getClass().getDeclaredMethod("setAction", Action.class).invoke(requestObject, action);
- requestObject.getClass().getDeclaredMethod("setActionIdentifiers", ActionIdentifiers.class)
- .invoke(requestObject, identifier);
- if (payload != null) {
- requestObject.getClass().getDeclaredMethod("setPayload", Payload.class).invoke(requestObject, payload);
- }
- } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
- logger.error("Error building Appc request", e);
- }
- return requestObject;
- }
-
- private CommonHeader buildCommonHeader(String requestId) {
- CommonHeader commonHeader = new CommonHeader();
- commonHeader.setApiVer(API_VER);
- commonHeader.setOriginatorId(ORIGINATOR_ID);
- commonHeader.setRequestId(requestId == null ? UUID.randomUUID().toString() : requestId);
- commonHeader.setSubRequestId(UUID.randomUUID().toString());
- Flags flags = new Flags();
- String flagsMode = "NORMAL";
- Mode mode = Mode.valueOf(flagsMode);
- flags.setMode(mode);
- String flagsForce = "FALSE";
- Force force = Force.valueOf(flagsForce);
- flags.setForce(force);
- flags.setTtl(FLAGS_TTL);
- commonHeader.setFlags(flags);
- Instant timestamp = Instant.now();
- ZULU zulu = new ZULU(timestamp.toString());
- commonHeader.setTimestamp(zulu);
- return commonHeader;
- }
-
- public Flags createRequestFlags() {
- Flags flags = new Flags();
- flags.setTtl(6000);
- return flags;
- }
+ public static final String DEFAULT_CONTROLLER_TYPE = "APPC";
+
+ private static final String CLIENT_NAME = "MSO";
+
+ private static final String API_VER = "2.00";
+ private static final String ORIGINATOR_ID = "MSO";
+ private static final int FLAGS_TTL = 65000;
+ private static Logger logger = LoggerFactory.getLogger(ApplicationControllerClient.class);
+
+ private ApplicationControllerSupport appCSupport;
+
+ // APPC gave us an API where the controllerType is configured in the
+ // client object, which is not what we asked for. We asked for an API
+ // in which the client would have additional methods that could take
+ // the controllerType as a parameter, so that we would not need to
+ // maintain multiple client objects. This map should be removed when
+ // the (hopefully short-term) controllerType becomes obsolete.
+
+ private final String controllerType;
+
+ private static ConcurrentHashMap<String, LifeCycleManagerStateful> appCClients = new ConcurrentHashMap<>();
+
+ /**
+ * Creates an ApplicationControllerClient for communication with APP-C.
+ */
+ public ApplicationControllerClient() {
+ this(DEFAULT_CONTROLLER_TYPE);
+ }
+
+ /**
+ * Creates an ApplicationControllerClient for the specified controller type.
+ *
+ * @param controllerType the controller type: "appc" or "sdnc".
+ */
+ public ApplicationControllerClient(String controllerType) {
+ if (controllerType == null) {
+ controllerType = DEFAULT_CONTROLLER_TYPE;
+ }
+ this.controllerType = controllerType.toUpperCase();
+ appCSupport = new ApplicationControllerSupport();
+ }
+
+ /**
+ * Gets the controller type.
+ *
+ * @return the controllertype
+ */
+ public String getControllerType() {
+ return controllerType;
+ }
+
+ /**
+ * Returns the AppC client object associated with this ApplicationControllerClient. AppC client objects are shared
+ * objects. One is created if it does not exist.
+ *
+ * @return the client object, or null if creation failed
+ */
+ public LifeCycleManagerStateful getAppCClient() {
+ return appCClients.computeIfAbsent(controllerType, k -> createAppCClient(k));
+ }
+
+ protected LifeCycleManagerStateful createAppCClient(String controllerType) {
+ try {
+ if (controllerType == null) {
+ controllerType = DEFAULT_CONTROLLER_TYPE;
+ }
+ controllerType = controllerType.toUpperCase();
+ return AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class)
+ .createLifeCycleManagerStateful(new ApplicationContext(), getLCMProperties(controllerType));
+ } catch (AppcClientException e) {
+ logger.error("Error in getting LifeCycleManagerStateful: {}", e.getMessage(), e);
+ // This null value will cause NullPointerException when used later.
+ // Error handling could certainly be improved here.
+ return null;
+ }
+ }
+
+ public Status runCommand(Action action, org.onap.appc.client.lcm.model.ActionIdentifiers actionIdentifiers,
+ org.onap.appc.client.lcm.model.Payload payload, String requestID)
+ throws ApplicationControllerOrchestratorException {
+ Object requestObject;
+ requestObject = createRequest(action, actionIdentifiers, payload, requestID);
+ appCSupport.logLCMMessage(requestObject);
+ LifeCycleManagerStateful client = getAppCClient();
+ Method lcmMethod = appCSupport.getAPIMethod(action.name(), client, false);
+ try {
+ Object response = lcmMethod.invoke(client, requestObject);
+ return appCSupport.getStatusFromGenericResponse(response);
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+ throw new RuntimeException(String.format("%s : %s", "Unable to invoke action", action.toString()), e);
+ }
+ }
+
+ protected Properties getLCMProperties() {
+ return getLCMProperties("appc");
+ }
+
+ protected Properties getLCMProperties(String controllerType) {
+ Properties properties = new Properties();
+
+ properties.put("topic.read", UrnPropertiesReader.getVariable("appc.client.topic.read.name"));
+ properties.put("topic.write", UrnPropertiesReader.getVariable("appc.client.topic.write"));
+ properties.put("SDNC-topic.read", UrnPropertiesReader.getVariable("appc.client.topic.sdnc.read"));
+ properties.put("SDNC-topic.write", UrnPropertiesReader.getVariable("appc.client.topic.sdnc.write"));
+ properties.put("topic.read.timeout", UrnPropertiesReader.getVariable("appc.client.topic.read.timeout"));
+ properties.put("client.response.timeout", UrnPropertiesReader.getVariable("appc.client.response.timeout"));
+ properties.put("poolMembers", UrnPropertiesReader.getVariable("appc.client.poolMembers"));
+ properties.put("controllerType", controllerType);
+ properties.put("client.key", UrnPropertiesReader.getVariable("appc.client.key"));
+ properties.put("client.secret", UrnPropertiesReader.getVariable("appc.client.secret"));
+ properties.put("client.name", CLIENT_NAME);
+ properties.put("service", UrnPropertiesReader.getVariable("appc.client.service"));
+ return properties;
+ }
+
+ public Object createRequest(Action action, ActionIdentifiers identifier, Payload payload, String requestId) {
+ Object requestObject = appCSupport.getInput(action.name());
+ try {
+ CommonHeader commonHeader = buildCommonHeader(requestId);
+ requestObject.getClass().getDeclaredMethod("setCommonHeader", CommonHeader.class).invoke(requestObject,
+ commonHeader);
+ requestObject.getClass().getDeclaredMethod("setAction", Action.class).invoke(requestObject, action);
+ requestObject.getClass().getDeclaredMethod("setActionIdentifiers", ActionIdentifiers.class)
+ .invoke(requestObject, identifier);
+ if (payload != null) {
+ requestObject.getClass().getDeclaredMethod("setPayload", Payload.class).invoke(requestObject, payload);
+ }
+ } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
+ logger.error("Error building Appc request", e);
+ }
+ return requestObject;
+ }
+
+ private CommonHeader buildCommonHeader(String requestId) {
+ CommonHeader commonHeader = new CommonHeader();
+ commonHeader.setApiVer(API_VER);
+ commonHeader.setOriginatorId(ORIGINATOR_ID);
+ commonHeader.setRequestId(requestId == null ? UUID.randomUUID().toString() : requestId);
+ commonHeader.setSubRequestId(UUID.randomUUID().toString());
+ Flags flags = new Flags();
+ String flagsMode = "NORMAL";
+ Mode mode = Mode.valueOf(flagsMode);
+ flags.setMode(mode);
+ String flagsForce = "FALSE";
+ Force force = Force.valueOf(flagsForce);
+ flags.setForce(force);
+ flags.setTtl(FLAGS_TTL);
+ commonHeader.setFlags(flags);
+ Instant timestamp = Instant.now();
+ ZULU zulu = new ZULU(timestamp.toString());
+ commonHeader.setTimestamp(zulu);
+ return commonHeader;
+ }
+
+ public Flags createRequestFlags() {
+ Flags flags = new Flags();
+ flags.setTtl(6000);
+ return flags;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerClientV2.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerClientV2.java
index d4599a5248..dc5b6308bb 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerClientV2.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerClientV2.java
@@ -32,7 +32,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@@ -44,111 +43,111 @@ import java.util.UUID;
@Deprecated
public class ApplicationControllerClientV2 {
- private static final String CLIENT_NAME = "MSO";
- private static final String API_VER = "2.00";
- private static final String ORIGINATOR_ID = "MSO";
- private static final int FLAGS_TTL = 65000;
- private static Logger logger = LoggerFactory.getLogger(ApplicationControllerClientV2.class);
+ private static final String CLIENT_NAME = "MSO";
+ private static final String API_VER = "2.00";
+ private static final String ORIGINATOR_ID = "MSO";
+ private static final int FLAGS_TTL = 65000;
+ private static Logger logger = LoggerFactory.getLogger(ApplicationControllerClientV2.class);
+
+ // @Autowired
+ ApplicationControllerConfiguration applicationControllerConfiguration;
- //@Autowired
- ApplicationControllerConfiguration applicationControllerConfiguration;
+ // @Autowired
+ private ApplicationControllerSupport appCSupport;
- //@Autowired
- private ApplicationControllerSupport appCSupport;
+ private static LifeCycleManagerStateful client;
- private static LifeCycleManagerStateful client;
+ // @PostConstruct
+ public void buildClient() {
+ client = this.getAppCClient("");
+ }
- //@PostConstruct
- public void buildClient() {
- client = this.getAppCClient("");
- }
-
- //@PostConstruct
- public void buildClient(String controllerType) {
- client = this.getAppCClient(controllerType);
- }
+ // @PostConstruct
+ public void buildClient(String controllerType) {
+ client = this.getAppCClient(controllerType);
+ }
- public Status runCommand(Action action, ActionIdentifiers actionIdentifiers, Payload payload, String requestID)
- throws ApplicationControllerOrchestratorException {
- Object requestObject;
- requestObject = createRequest(action, actionIdentifiers, payload, requestID);
- appCSupport.logLCMMessage(requestObject);
- Method lcmMethod = appCSupport.getAPIMethod(action.name(), client, false);
- try {
- Object response = lcmMethod.invoke(client, requestObject);
- return appCSupport.getStatusFromGenericResponse(response);
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- throw new RuntimeException(String.format("%s : %s", "Unable to invoke action", action.toString()), e);
- }
- }
+ public Status runCommand(Action action, ActionIdentifiers actionIdentifiers, Payload payload, String requestID)
+ throws ApplicationControllerOrchestratorException {
+ Object requestObject;
+ requestObject = createRequest(action, actionIdentifiers, payload, requestID);
+ appCSupport.logLCMMessage(requestObject);
+ Method lcmMethod = appCSupport.getAPIMethod(action.name(), client, false);
+ try {
+ Object response = lcmMethod.invoke(client, requestObject);
+ return appCSupport.getStatusFromGenericResponse(response);
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+ throw new RuntimeException(String.format("%s : %s", "Unable to invoke action", action.toString()), e);
+ }
+ }
- public LifeCycleManagerStateful getAppCClient(String controllerType) {
- if (client == null)
- try {
- client = AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class)
- .createLifeCycleManagerStateful(new ApplicationContext(), getLCMProperties(controllerType));
- } catch (AppcClientException e) {
- logger.error("Error in getting LifeCycleManagerStateful Client", e);
- }
- return client;
- }
+ public LifeCycleManagerStateful getAppCClient(String controllerType) {
+ if (client == null)
+ try {
+ client = AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class)
+ .createLifeCycleManagerStateful(new ApplicationContext(), getLCMProperties(controllerType));
+ } catch (AppcClientException e) {
+ logger.error("Error in getting LifeCycleManagerStateful Client", e);
+ }
+ return client;
+ }
- protected Properties getLCMProperties(String controllerType) {
- Properties properties = new Properties();
- properties.put("topic.read", applicationControllerConfiguration.getReadTopic());
- properties.put("topic.read.timeout", applicationControllerConfiguration.getReadTimeout());
- properties.put("client.response.timeout", applicationControllerConfiguration.getResponseTimeout());
- properties.put("topic.write", applicationControllerConfiguration.getWrite());
- properties.put("poolMembers", applicationControllerConfiguration.getPoolMembers());
- properties.put("client.key", applicationControllerConfiguration.getClientKey());
- properties.put("client.secret", applicationControllerConfiguration.getClientSecret());
- properties.put("client.name", CLIENT_NAME);
- properties.put("service", applicationControllerConfiguration.getService());
- return properties;
- }
+ protected Properties getLCMProperties(String controllerType) {
+ Properties properties = new Properties();
+ properties.put("topic.read", applicationControllerConfiguration.getReadTopic());
+ properties.put("topic.read.timeout", applicationControllerConfiguration.getReadTimeout());
+ properties.put("client.response.timeout", applicationControllerConfiguration.getResponseTimeout());
+ properties.put("topic.write", applicationControllerConfiguration.getWrite());
+ properties.put("poolMembers", applicationControllerConfiguration.getPoolMembers());
+ properties.put("client.key", applicationControllerConfiguration.getClientKey());
+ properties.put("client.secret", applicationControllerConfiguration.getClientSecret());
+ properties.put("client.name", CLIENT_NAME);
+ properties.put("service", applicationControllerConfiguration.getService());
+ return properties;
+ }
- public Object createRequest(Action action, ActionIdentifiers identifier, Payload payload, String requestId) {
- Object requestObject = appCSupport.getInput(action.name());
- try {
- CommonHeader commonHeader = buildCommonHeader(requestId);
- requestObject.getClass().getDeclaredMethod("setCommonHeader", CommonHeader.class).invoke(requestObject,
- commonHeader);
- requestObject.getClass().getDeclaredMethod("setAction", Action.class).invoke(requestObject, action);
- requestObject.getClass().getDeclaredMethod("setActionIdentifiers", ActionIdentifiers.class)
- .invoke(requestObject, identifier);
- if (payload != null) {
- requestObject.getClass().getDeclaredMethod("setPayload", Payload.class).invoke(requestObject, payload);
- }
- } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
- logger.error("Error building Appc request", e);
- }
- return requestObject;
- }
+ public Object createRequest(Action action, ActionIdentifiers identifier, Payload payload, String requestId) {
+ Object requestObject = appCSupport.getInput(action.name());
+ try {
+ CommonHeader commonHeader = buildCommonHeader(requestId);
+ requestObject.getClass().getDeclaredMethod("setCommonHeader", CommonHeader.class).invoke(requestObject,
+ commonHeader);
+ requestObject.getClass().getDeclaredMethod("setAction", Action.class).invoke(requestObject, action);
+ requestObject.getClass().getDeclaredMethod("setActionIdentifiers", ActionIdentifiers.class)
+ .invoke(requestObject, identifier);
+ if (payload != null) {
+ requestObject.getClass().getDeclaredMethod("setPayload", Payload.class).invoke(requestObject, payload);
+ }
+ } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
+ logger.error("Error building Appc request", e);
+ }
+ return requestObject;
+ }
- private CommonHeader buildCommonHeader(String requestId) {
- CommonHeader commonHeader = new CommonHeader();
- commonHeader.setApiVer(API_VER);
- commonHeader.setOriginatorId(ORIGINATOR_ID);
- commonHeader.setRequestId(requestId == null ? UUID.randomUUID().toString() : requestId);
- commonHeader.setSubRequestId(requestId);
- Flags flags = new Flags();
- String flagsMode = "NORMAL";
- Mode mode = Mode.valueOf(flagsMode);
- flags.setMode(mode);
- String flagsForce = "FALSE";
- Force force = Force.valueOf(flagsForce);
- flags.setForce(force);
- flags.setTtl(FLAGS_TTL);
- commonHeader.setFlags(flags);
- Instant timestamp = Instant.now();
- ZULU zulu = new ZULU(timestamp.toString());
- commonHeader.setTimestamp(zulu);
- return commonHeader;
- }
+ private CommonHeader buildCommonHeader(String requestId) {
+ CommonHeader commonHeader = new CommonHeader();
+ commonHeader.setApiVer(API_VER);
+ commonHeader.setOriginatorId(ORIGINATOR_ID);
+ commonHeader.setRequestId(requestId == null ? UUID.randomUUID().toString() : requestId);
+ commonHeader.setSubRequestId(requestId);
+ Flags flags = new Flags();
+ String flagsMode = "NORMAL";
+ Mode mode = Mode.valueOf(flagsMode);
+ flags.setMode(mode);
+ String flagsForce = "FALSE";
+ Force force = Force.valueOf(flagsForce);
+ flags.setForce(force);
+ flags.setTtl(FLAGS_TTL);
+ commonHeader.setFlags(flags);
+ Instant timestamp = Instant.now();
+ ZULU zulu = new ZULU(timestamp.toString());
+ commonHeader.setTimestamp(zulu);
+ return commonHeader;
+ }
- public Flags createRequestFlags() {
- Flags flags = new Flags();
- flags.setTtl(6000);
- return flags;
- }
+ public Flags createRequestFlags() {
+ Flags flags = new Flags();
+ flags.setTtl(6000);
+ return flags;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerConfiguration.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerConfiguration.java
index 430767f24a..165d9577af 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerConfiguration.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerConfiguration.java
@@ -26,60 +26,60 @@ import org.springframework.stereotype.Service;
@Configuration
public class ApplicationControllerConfiguration {
- @Value("${appc.client.topic.read.name}")
- private String readTopic;
+ @Value("${appc.client.topic.read.name}")
+ private String readTopic;
- @Value("${appc.client.topic.read.timeout}")
- private String readTimeout;
+ @Value("${appc.client.topic.read.timeout}")
+ private String readTimeout;
- @Value("${appc.client.response.timeout}")
- private String responseTimeout;
+ @Value("${appc.client.response.timeout}")
+ private String responseTimeout;
- @Value("${appc.client.topic.write}")
- private String write;
+ @Value("${appc.client.topic.write}")
+ private String write;
- @Value("${appc.client.poolMembers}")
- private String poolMembers;
+ @Value("${appc.client.poolMembers}")
+ private String poolMembers;
- @Value("${appc.client.key}")
- private String clientKey;
+ @Value("${appc.client.key}")
+ private String clientKey;
- @Value("${appc.client.secret}")
- private String clientSecret;
+ @Value("${appc.client.secret}")
+ private String clientSecret;
- @Value("${appc.client.service}")
- private String service;
+ @Value("${appc.client.service}")
+ private String service;
- public String getClientKey() {
- return clientKey;
- }
+ public String getClientKey() {
+ return clientKey;
+ }
- public String getClientSecret() {
- return clientSecret;
- }
+ public String getClientSecret() {
+ return clientSecret;
+ }
- public String getPoolMembers() {
- return poolMembers;
- }
-
- public String getReadTimeout() {
- return readTimeout;
- }
+ public String getPoolMembers() {
+ return poolMembers;
+ }
- public String getResponseTimeout() {
- return responseTimeout;
- }
+ public String getReadTimeout() {
+ return readTimeout;
+ }
- public String getReadTopic() {
- return readTopic;
- }
+ public String getResponseTimeout() {
+ return responseTimeout;
+ }
- public String getService() {
- return service;
- }
+ public String getReadTopic() {
+ return readTopic;
+ }
- public String getWrite() {
- return write;
- }
+ public String getService() {
+ return service;
+ }
+
+ public String getWrite() {
+ return write;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerOrchestrator.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerOrchestrator.java
index 84e0f93294..fd5f07b708 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerOrchestrator.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerOrchestrator.java
@@ -21,9 +21,7 @@
package org.onap.so.client.appc;
import java.util.Optional;
-
import org.onap.so.client.appc.ApplicationControllerSupport.StatusCategory;
-
import org.onap.appc.client.lcm.model.Action;
import org.onap.appc.client.lcm.model.ActionIdentifiers;
import org.onap.appc.client.lcm.model.Payload;
@@ -31,23 +29,24 @@ import org.onap.appc.client.lcm.model.Status;
public class ApplicationControllerOrchestrator {
- public Status vnfCommand(Action action, String requestId, String vnfId, Optional<String> vserverId, Optional<String> request, String controllerType) throws ApplicationControllerOrchestratorException {
- ApplicationControllerClient client = new ApplicationControllerClient(controllerType);
- Status status;
- ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
- actionIdentifiers.setVnfId(vnfId);
- if (vserverId.isPresent()) {
- actionIdentifiers.setVserverId(vserverId.get());
- }
- Payload payload = null;
- if (request.isPresent()) {
- payload = new Payload(request.get());
- }
- status = client.runCommand(action, actionIdentifiers, payload, requestId);
- if (ApplicationControllerSupport.getCategoryOf(status).equals(StatusCategory.ERROR)) {
- throw new ApplicationControllerOrchestratorException(status.getMessage(), status.getCode());
- } else {
- return status;
- }
- }
+ public Status vnfCommand(Action action, String requestId, String vnfId, Optional<String> vserverId,
+ Optional<String> request, String controllerType) throws ApplicationControllerOrchestratorException {
+ ApplicationControllerClient client = new ApplicationControllerClient(controllerType);
+ Status status;
+ ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
+ actionIdentifiers.setVnfId(vnfId);
+ if (vserverId.isPresent()) {
+ actionIdentifiers.setVserverId(vserverId.get());
+ }
+ Payload payload = null;
+ if (request.isPresent()) {
+ payload = new Payload(request.get());
+ }
+ status = client.runCommand(action, actionIdentifiers, payload, requestId);
+ if (ApplicationControllerSupport.getCategoryOf(status).equals(StatusCategory.ERROR)) {
+ throw new ApplicationControllerOrchestratorException(status.getMessage(), status.getCode());
+ } else {
+ return status;
+ }
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerOrchestratorException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerOrchestratorException.java
index 2532e485ed..58e566e096 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerOrchestratorException.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerOrchestratorException.java
@@ -22,15 +22,14 @@ package org.onap.so.client.appc;
public class ApplicationControllerOrchestratorException extends Exception {
- private final int appcCode;
-
- public ApplicationControllerOrchestratorException(String message, int code) {
- super(message);
- appcCode = code;
- }
-
- public int getAppcCode()
- {
- return appcCode;
- }
+ private final int appcCode;
+
+ public ApplicationControllerOrchestratorException(String message, int code) {
+ super(message);
+ appcCode = code;
+ }
+
+ public int getAppcCode() {
+ return appcCode;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerSupport.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerSupport.java
index ef8749ece9..10d3d85ffc 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerSupport.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerSupport.java
@@ -26,15 +26,12 @@ import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-
import org.springframework.stereotype.Component;
-
import org.onap.appc.client.lcm.api.LifeCycleManagerStateful;
import org.onap.appc.client.lcm.api.ResponseHandler;
import org.onap.appc.client.lcm.model.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -43,173 +40,173 @@ import org.springframework.stereotype.Service;
public class ApplicationControllerSupport {
- private static final int ACCEPT_SERIES = 100;
- private static final int ERROR_SERIES = 200;
- private static final int REJECT_SERIES = 300;
- private static final int SUCCESS_SERIES = 400;
- private static final int SUCCESS_STATUS = SUCCESS_SERIES;
- private static final int PARTIAL_SERIES = 500;
- private static final int PARTIAL_SUCCESS_STATUS = PARTIAL_SERIES;
- private static final int PARTIAL_FAILURE_STATUS = PARTIAL_SERIES + 1;
-
- private static Logger logger = LoggerFactory.getLogger(ApplicationControllerSupport.class);
- private String lcmModelPackage = "org.onap.appc.client.lcm.model";
-
- /**
- * @param action
- * @return
- * @throws ClassNotFoundException
- * @throws InstantiationException
- * @throws IllegalAccessException
- */
- public Object getInput(String action) {
- try {
- return getInputClass(action).newInstance();
- } catch (IllegalAccessException | InstantiationException e) {
- throw new RuntimeException(
- String.format("%s : %s", "Unable to instantiate viable LCM Kit input class for action", action), e);
- }
- }
-
- /**
- * @param action
- * @return
- * @throws ClassNotFoundException
- */
- public Method getAPIMethod(String action, LifeCycleManagerStateful lcmStateful, boolean async) {
- Method[] methods = lcmStateful.getClass().getMethods();
- for (Method method : methods) {
- if (method.getName().equalsIgnoreCase(action)) {
- Class<?>[] methodParameterTypes = method.getParameterTypes();
- if (methodParameterTypes.length > 0) {
- if (getInputClass(action).equals(methodParameterTypes[0])) {
- if (async) {
- if (methodParameterTypes.length == 2
- && ResponseHandler.class.isAssignableFrom(methodParameterTypes[1])) {
- return method;
- }
- } else if (methodParameterTypes.length == 1) {
- return method;
- }
- }
- }
- }
- }
- throw new RuntimeException(String.format("%s : %s, async=%b",
- "Unable to derive viable LCM Kit API method for action", action, async));
- }
-
- public Status getStatusFromGenericResponse(Object response) {
- Method statusReader = getBeanPropertyMethodFor(response.getClass(), "status", false);
- if (statusReader != null) {
- try {
- return (Status) statusReader.invoke(response);
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- logger.error("Unable to obtain status from LCM Kit response", e);
- }
- }
- return new Status();
- }
-
- public static StatusCategory getCategoryOf(Status status) {
- int codeSeries = status.getCode() - (status.getCode() % 100);
- switch (codeSeries) {
- case ACCEPT_SERIES:
- return StatusCategory.NORMAL;
- case ERROR_SERIES:
- case REJECT_SERIES:
- return StatusCategory.ERROR;
- case SUCCESS_SERIES:
- return status.getCode() == SUCCESS_STATUS ? StatusCategory.NORMAL : StatusCategory.ERROR;
- case PARTIAL_SERIES:
- switch (status.getCode()) {
- case PARTIAL_SUCCESS_STATUS:
- return StatusCategory.NORMAL;
- case PARTIAL_FAILURE_STATUS:
- return StatusCategory.ERROR;
- default:
- return StatusCategory.WARNING;
- }
- default:
- return StatusCategory.WARNING;
- }
- }
-
- public static boolean getFinalityOf(Status status) {
- int codeSeries = status.getCode() - (status.getCode() % 100);
- switch (codeSeries) {
- case ACCEPT_SERIES:
- case PARTIAL_SERIES:
- return false;
- case ERROR_SERIES:
- case REJECT_SERIES:
- case SUCCESS_SERIES:
- return true;
- default:
- return true;
- }
- }
-
- private Method getBeanPropertyMethodFor(Class<?> clazz, String propertyName, boolean isWriter) {
- BeanInfo beanInfo;
- try {
- beanInfo = Introspector.getBeanInfo(clazz, Object.class);
- } catch (IntrospectionException e) {
- throw new RuntimeException(
- String.format("Unable to produce bean property method for class : %s, property : %s, writer=%b",
- clazz.getName(), propertyName, isWriter),
- e);
- }
- PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
- for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
- if (propertyDescriptor.getName().equals(propertyName)) {
- return isWriter ? propertyDescriptor.getWriteMethod() : propertyDescriptor.getReadMethod();
- }
- }
- throw new RuntimeException(
- String.format("Unable to produce bean property method for class : %s, property : %s, writer=%b",
- clazz.getName(), propertyName, isWriter));
- }
-
- /**
- * @param action
- * @return
- * @throws ClassNotFoundException
- */
- private Class<?> getInputClass(String action) {
- try {
- return Class.forName(lcmModelPackage + '.' + action + "Input");
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(String.format("%s : %s using package : %s",
- "Unable to identify viable LCM Kit input class for action", action, lcmModelPackage), e);
- }
- }
-
- public enum StatusCategory {
- NORMAL("normal"), WARNING("warning"), ERROR("error");
-
- private final String category;
-
- private StatusCategory(final String category) {
- this.category = category;
- }
-
- @Override
- public String toString() {
- return category;
- }
- }
-
- public void logLCMMessage(Object message) {
- ObjectMapper objectMapper = new ObjectMapper();
- objectMapper.setSerializationInclusion(Include.NON_NULL);
- ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
- String inputAsJSON;
- try {
- inputAsJSON = writer.writeValueAsString(message);
- logger.info("LCM Kit input message follows: {}" , inputAsJSON);
- } catch (JsonProcessingException e) {
- logger.error("Error in logging LCM Message", e);
- }
- }
+ private static final int ACCEPT_SERIES = 100;
+ private static final int ERROR_SERIES = 200;
+ private static final int REJECT_SERIES = 300;
+ private static final int SUCCESS_SERIES = 400;
+ private static final int SUCCESS_STATUS = SUCCESS_SERIES;
+ private static final int PARTIAL_SERIES = 500;
+ private static final int PARTIAL_SUCCESS_STATUS = PARTIAL_SERIES;
+ private static final int PARTIAL_FAILURE_STATUS = PARTIAL_SERIES + 1;
+
+ private static Logger logger = LoggerFactory.getLogger(ApplicationControllerSupport.class);
+ private String lcmModelPackage = "org.onap.appc.client.lcm.model";
+
+ /**
+ * @param action
+ * @return
+ * @throws ClassNotFoundException
+ * @throws InstantiationException
+ * @throws IllegalAccessException
+ */
+ public Object getInput(String action) {
+ try {
+ return getInputClass(action).newInstance();
+ } catch (IllegalAccessException | InstantiationException e) {
+ throw new RuntimeException(
+ String.format("%s : %s", "Unable to instantiate viable LCM Kit input class for action", action), e);
+ }
+ }
+
+ /**
+ * @param action
+ * @return
+ * @throws ClassNotFoundException
+ */
+ public Method getAPIMethod(String action, LifeCycleManagerStateful lcmStateful, boolean async) {
+ Method[] methods = lcmStateful.getClass().getMethods();
+ for (Method method : methods) {
+ if (method.getName().equalsIgnoreCase(action)) {
+ Class<?>[] methodParameterTypes = method.getParameterTypes();
+ if (methodParameterTypes.length > 0) {
+ if (getInputClass(action).equals(methodParameterTypes[0])) {
+ if (async) {
+ if (methodParameterTypes.length == 2
+ && ResponseHandler.class.isAssignableFrom(methodParameterTypes[1])) {
+ return method;
+ }
+ } else if (methodParameterTypes.length == 1) {
+ return method;
+ }
+ }
+ }
+ }
+ }
+ throw new RuntimeException(String.format("%s : %s, async=%b",
+ "Unable to derive viable LCM Kit API method for action", action, async));
+ }
+
+ public Status getStatusFromGenericResponse(Object response) {
+ Method statusReader = getBeanPropertyMethodFor(response.getClass(), "status", false);
+ if (statusReader != null) {
+ try {
+ return (Status) statusReader.invoke(response);
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+ logger.error("Unable to obtain status from LCM Kit response", e);
+ }
+ }
+ return new Status();
+ }
+
+ public static StatusCategory getCategoryOf(Status status) {
+ int codeSeries = status.getCode() - (status.getCode() % 100);
+ switch (codeSeries) {
+ case ACCEPT_SERIES:
+ return StatusCategory.NORMAL;
+ case ERROR_SERIES:
+ case REJECT_SERIES:
+ return StatusCategory.ERROR;
+ case SUCCESS_SERIES:
+ return status.getCode() == SUCCESS_STATUS ? StatusCategory.NORMAL : StatusCategory.ERROR;
+ case PARTIAL_SERIES:
+ switch (status.getCode()) {
+ case PARTIAL_SUCCESS_STATUS:
+ return StatusCategory.NORMAL;
+ case PARTIAL_FAILURE_STATUS:
+ return StatusCategory.ERROR;
+ default:
+ return StatusCategory.WARNING;
+ }
+ default:
+ return StatusCategory.WARNING;
+ }
+ }
+
+ public static boolean getFinalityOf(Status status) {
+ int codeSeries = status.getCode() - (status.getCode() % 100);
+ switch (codeSeries) {
+ case ACCEPT_SERIES:
+ case PARTIAL_SERIES:
+ return false;
+ case ERROR_SERIES:
+ case REJECT_SERIES:
+ case SUCCESS_SERIES:
+ return true;
+ default:
+ return true;
+ }
+ }
+
+ private Method getBeanPropertyMethodFor(Class<?> clazz, String propertyName, boolean isWriter) {
+ BeanInfo beanInfo;
+ try {
+ beanInfo = Introspector.getBeanInfo(clazz, Object.class);
+ } catch (IntrospectionException e) {
+ throw new RuntimeException(
+ String.format("Unable to produce bean property method for class : %s, property : %s, writer=%b",
+ clazz.getName(), propertyName, isWriter),
+ e);
+ }
+ PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
+ for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
+ if (propertyDescriptor.getName().equals(propertyName)) {
+ return isWriter ? propertyDescriptor.getWriteMethod() : propertyDescriptor.getReadMethod();
+ }
+ }
+ throw new RuntimeException(
+ String.format("Unable to produce bean property method for class : %s, property : %s, writer=%b",
+ clazz.getName(), propertyName, isWriter));
+ }
+
+ /**
+ * @param action
+ * @return
+ * @throws ClassNotFoundException
+ */
+ private Class<?> getInputClass(String action) {
+ try {
+ return Class.forName(lcmModelPackage + '.' + action + "Input");
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException(String.format("%s : %s using package : %s",
+ "Unable to identify viable LCM Kit input class for action", action, lcmModelPackage), e);
+ }
+ }
+
+ public enum StatusCategory {
+ NORMAL("normal"), WARNING("warning"), ERROR("error");
+
+ private final String category;
+
+ private StatusCategory(final String category) {
+ this.category = category;
+ }
+
+ @Override
+ public String toString() {
+ return category;
+ }
+ }
+
+ public void logLCMMessage(Object message) {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.setSerializationInclusion(Include.NON_NULL);
+ ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
+ String inputAsJSON;
+ try {
+ inputAsJSON = writer.writeValueAsString(message);
+ logger.info("LCM Kit input message follows: {}", inputAsJSON);
+ } catch (JsonProcessingException e) {
+ logger.error("Error in logging LCM Message", e);
+ }
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/AVPNDmaapBean.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/AVPNDmaapBean.java
index fff818f09b..f839079338 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/AVPNDmaapBean.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/AVPNDmaapBean.java
@@ -25,16 +25,16 @@ import com.fasterxml.jackson.annotation.JsonProperty;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AVPNDmaapBean {
-
- @JsonProperty("asyncRequestStatus")
- private AsyncRequestStatus asyncRequestStatus;
- public AsyncRequestStatus getAsyncRequestStatus() {
- return asyncRequestStatus;
- }
+ @JsonProperty("asyncRequestStatus")
+ private AsyncRequestStatus asyncRequestStatus;
- public void setAsyncRequestStatus(AsyncRequestStatus asyncRequestStatus) {
- this.asyncRequestStatus = asyncRequestStatus;
- }
+ public AsyncRequestStatus getAsyncRequestStatus() {
+ return asyncRequestStatus;
+ }
+
+ public void setAsyncRequestStatus(AsyncRequestStatus asyncRequestStatus) {
+ this.asyncRequestStatus = asyncRequestStatus;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/AsyncRequestStatus.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/AsyncRequestStatus.java
index 13206e8c92..14e0cd0411 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/AsyncRequestStatus.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/AsyncRequestStatus.java
@@ -25,95 +25,95 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "asyncRequestStatus")
public class AsyncRequestStatus {
-
- @JsonProperty("requestId")
- private String requestId;
- @JsonProperty("clientSource")
- private String clientSource;
- @JsonProperty("correlator")
- private String correlator;
- @JsonProperty("instanceReferences")
- private InstanceReferences instanceReferences;
- @JsonProperty("startTime")
- private String startTime;
- @JsonProperty("finishTime")
- private String finishTime;
- @JsonProperty("requestScope")
- private String requestScope;
- @JsonProperty("requestType")
- private String requestType;
- @JsonProperty("requestStatus")
- private RequestStatus requestStatus;
-
- public String getRequestId() {
- return requestId;
- }
-
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
- public String getClientSource() {
- return clientSource;
- }
-
- public void setClientSource(String clientSource) {
- this.clientSource = clientSource;
- }
-
- public String getCorrelator() {
- return correlator;
- }
-
- public void setCorrelator(String correlator) {
- this.correlator = correlator;
- }
-
- public InstanceReferences getInstanceReferences() {
- return instanceReferences;
- }
-
- public void setInstanceReferences(InstanceReferences instanceReferences) {
- this.instanceReferences = instanceReferences;
- }
-
- public String getStartTime() {
- return startTime;
- }
-
- public void setStartTime(String startTime) {
- this.startTime = startTime;
- }
-
- public String getFinishTime() {
- return finishTime;
- }
-
- public void setFinishTime(String finishTime) {
- this.finishTime = finishTime;
- }
-
- public String getRequestScope() {
- return requestScope;
- }
-
- public void setRequestScope(String requestScope) {
- this.requestScope = requestScope;
- }
-
- public String getRequestType() {
- return requestType;
- }
-
- public void setRequestType(String requestType) {
- this.requestType = requestType;
- }
-
- public RequestStatus getRequestStatus() {
- return requestStatus;
- }
-
- public void setRequestStatus(RequestStatus requestStatus) {
- this.requestStatus = requestStatus;
- }
+
+ @JsonProperty("requestId")
+ private String requestId;
+ @JsonProperty("clientSource")
+ private String clientSource;
+ @JsonProperty("correlator")
+ private String correlator;
+ @JsonProperty("instanceReferences")
+ private InstanceReferences instanceReferences;
+ @JsonProperty("startTime")
+ private String startTime;
+ @JsonProperty("finishTime")
+ private String finishTime;
+ @JsonProperty("requestScope")
+ private String requestScope;
+ @JsonProperty("requestType")
+ private String requestType;
+ @JsonProperty("requestStatus")
+ private RequestStatus requestStatus;
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getClientSource() {
+ return clientSource;
+ }
+
+ public void setClientSource(String clientSource) {
+ this.clientSource = clientSource;
+ }
+
+ public String getCorrelator() {
+ return correlator;
+ }
+
+ public void setCorrelator(String correlator) {
+ this.correlator = correlator;
+ }
+
+ public InstanceReferences getInstanceReferences() {
+ return instanceReferences;
+ }
+
+ public void setInstanceReferences(InstanceReferences instanceReferences) {
+ this.instanceReferences = instanceReferences;
+ }
+
+ public String getStartTime() {
+ return startTime;
+ }
+
+ public void setStartTime(String startTime) {
+ this.startTime = startTime;
+ }
+
+ public String getFinishTime() {
+ return finishTime;
+ }
+
+ public void setFinishTime(String finishTime) {
+ this.finishTime = finishTime;
+ }
+
+ public String getRequestScope() {
+ return requestScope;
+ }
+
+ public void setRequestScope(String requestScope) {
+ this.requestScope = requestScope;
+ }
+
+ public String getRequestType() {
+ return requestType;
+ }
+
+ public void setRequestType(String requestType) {
+ this.requestType = requestType;
+ }
+
+ public RequestStatus getRequestStatus() {
+ return requestStatus;
+ }
+
+ public void setRequestStatus(RequestStatus requestStatus) {
+ this.requestStatus = requestStatus;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/InstanceReferences.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/InstanceReferences.java
index 322f41bf75..31189517aa 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/InstanceReferences.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/InstanceReferences.java
@@ -26,14 +26,14 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "instanceReferences")
public class InstanceReferences {
- @JsonProperty("serviceInstanceId")
- private String serviceInstanceId;
+ @JsonProperty("serviceInstanceId")
+ private String serviceInstanceId;
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/RequestStatus.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/RequestStatus.java
index edc8be7bfe..34f17c404f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/RequestStatus.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/avpn/dmaap/beans/RequestStatus.java
@@ -26,54 +26,54 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "requestStatus")
public class RequestStatus {
- @JsonProperty("timestamp")
- private String timestamp;
- @JsonProperty("requestState")
- private String requestState;
- @JsonProperty("statusMessage")
- private String statusMessage;
- @JsonProperty("percentProgress")
- private String percentProgress;
- @JsonProperty("wasRolledBack")
- private Boolean wasRolledBack;
-
- public String getTimestamp() {
- return timestamp;
- }
-
- public void setTimestamp(String timestamp) {
- this.timestamp = timestamp;
- }
-
- public String getRequestState() {
- return requestState;
- }
-
- public void setRequestState(String requestState) {
- this.requestState = requestState;
- }
-
- public String getStatusMessage() {
- return statusMessage;
- }
-
- public void setStatusMessage(String statusMessage) {
- this.statusMessage = statusMessage;
- }
-
- public String getPercentProgress() {
- return percentProgress;
- }
-
- public void setPercentProgress(String percentProgress) {
- this.percentProgress = percentProgress;
- }
+ @JsonProperty("timestamp")
+ private String timestamp;
+ @JsonProperty("requestState")
+ private String requestState;
+ @JsonProperty("statusMessage")
+ private String statusMessage;
+ @JsonProperty("percentProgress")
+ private String percentProgress;
+ @JsonProperty("wasRolledBack")
+ private Boolean wasRolledBack;
- public Boolean isWasRolledBack() {
- return wasRolledBack;
- }
+ public String getTimestamp() {
+ return timestamp;
+ }
- public void setWasRolledBack(Boolean wasRolledBack) {
- this.wasRolledBack = wasRolledBack;
- }
+ public void setTimestamp(String timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getRequestState() {
+ return requestState;
+ }
+
+ public void setRequestState(String requestState) {
+ this.requestState = requestState;
+ }
+
+ public String getStatusMessage() {
+ return statusMessage;
+ }
+
+ public void setStatusMessage(String statusMessage) {
+ this.statusMessage = statusMessage;
+ }
+
+ public String getPercentProgress() {
+ return percentProgress;
+ }
+
+ public void setPercentProgress(String percentProgress) {
+ this.percentProgress = percentProgress;
+ }
+
+ public Boolean isWasRolledBack() {
+ return wasRolledBack;
+ }
+
+ public void setWasRolledBack(Boolean wasRolledBack) {
+ this.wasRolledBack = wasRolledBack;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java
index 083a6b6e1f..6bfa67502d 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java
@@ -25,7 +25,6 @@ package org.onap.so.client.cds;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
@@ -40,12 +39,10 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Struct;
import com.google.protobuf.Struct.Builder;
import com.google.protobuf.util.JsonFormat;
-
import io.grpc.Status;
/**
@@ -67,28 +64,26 @@ public class AbstractCDSProcessingBBUtils implements CDSProcessingListener {
private ExceptionBuilder exceptionUtil;
/**
- * Extracting data from execution object and building the ExecutionServiceInput
- * Object
+ * Extracting data from execution object and building the ExecutionServiceInput Object
*
- * @param execution
- * DelegateExecution object
+ * @param execution DelegateExecution object
*/
public void constructExecutionServiceInputObject(DelegateExecution execution) {
logger.trace("Start AbstractCDSProcessingBBUtils.preProcessRequest ");
try {
- AbstractCDSPropertiesBean executionObject = (AbstractCDSPropertiesBean) execution
- .getVariable("executionObject");
+ AbstractCDSPropertiesBean executionObject =
+ (AbstractCDSPropertiesBean) execution.getVariable("executionObject");
String payload = executionObject.getRequestObject();
CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(executionObject.getOriginatorId())
.setRequestId(executionObject.getRequestId()).setSubRequestId(executionObject.getSubRequestId())
.build();
- ActionIdentifiers actionIdentifiers = ActionIdentifiers.newBuilder()
- .setBlueprintName(executionObject.getBlueprintName())
- .setBlueprintVersion(executionObject.getBlueprintVersion())
- .setActionName(executionObject.getActionName()).setMode(executionObject.getMode()).build();
+ ActionIdentifiers actionIdentifiers =
+ ActionIdentifiers.newBuilder().setBlueprintName(executionObject.getBlueprintName())
+ .setBlueprintVersion(executionObject.getBlueprintVersion())
+ .setActionName(executionObject.getActionName()).setMode(executionObject.getMode()).build();
Builder struct = Struct.newBuilder();
try {
@@ -99,9 +94,9 @@ public class AbstractCDSProcessingBBUtils implements CDSProcessingListener {
executionObject.getActionName(), e);
}
- ExecutionServiceInput executionServiceInput = ExecutionServiceInput.newBuilder()
- .setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers).setPayload(struct.build())
- .build();
+ ExecutionServiceInput executionServiceInput =
+ ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader)
+ .setActionIdentifiers(actionIdentifiers).setPayload(struct.build()).build();
execution.setVariable("executionServiceInput", executionServiceInput);
@@ -111,11 +106,9 @@ public class AbstractCDSProcessingBBUtils implements CDSProcessingListener {
}
/**
- * get the executionServiceInput object from execution and send a request to CDS
- * Client and wait for TIMEOUT period
+ * get the executionServiceInput object from execution and send a request to CDS Client and wait for TIMEOUT period
*
- * @param execution
- * DelegateExecution object
+ * @param execution DelegateExecution object
*/
public void sendRequestToCDSClient(DelegateExecution execution) {
@@ -127,13 +120,13 @@ public class AbstractCDSProcessingBBUtils implements CDSProcessingListener {
"No RestProperty.CDSProperties implementation found on classpath, can't create client.");
}
- ExecutionServiceInput executionServiceInput = (ExecutionServiceInput) execution
- .getVariable("executionServiceInput");
+ ExecutionServiceInput executionServiceInput =
+ (ExecutionServiceInput) execution.getVariable("executionServiceInput");
- try(CDSProcessingClient cdsClient = new CDSProcessingClient(this)) {
+ try (CDSProcessingClient cdsClient = new CDSProcessingClient(this)) {
CountDownLatch countDownLatch = cdsClient.sendRequest(executionServiceInput);
countDownLatch.await(props.getTimeout(), TimeUnit.SECONDS);
- } catch (InterruptedException ex){
+ } catch (InterruptedException ex) {
logger.error("Caught exception in sendRequestToCDSClient in AbstractCDSProcessingBBUtils : ", ex);
Thread.currentThread().interrupt();
}
@@ -158,21 +151,21 @@ public class AbstractCDSProcessingBBUtils implements CDSProcessingListener {
switch (eventType) {
- case EVENT_COMPONENT_FAILURE:
- // failed processing with failure
- cdsResponse.set(FAILED);
- break;
- case EVENT_COMPONENT_PROCESSING:
- // still processing
- cdsResponse.set(PROCESSING);
- break;
- case EVENT_COMPONENT_EXECUTED:
- // done with async processing
- cdsResponse.set(SUCCESS);
- break;
- default:
- cdsResponse.set(FAILED);
- break;
+ case EVENT_COMPONENT_FAILURE:
+ // failed processing with failure
+ cdsResponse.set(FAILED);
+ break;
+ case EVENT_COMPONENT_PROCESSING:
+ // still processing
+ cdsResponse.set(PROCESSING);
+ break;
+ case EVENT_COMPONENT_EXECUTED:
+ // done with async processing
+ cdsResponse.set(SUCCESS);
+ break;
+ default:
+ cdsResponse.set(FAILED);
+ break;
}
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/AbstractCDSPropertiesBean.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/AbstractCDSPropertiesBean.java
index 4b645984cf..2e84f384dc 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/AbstractCDSPropertiesBean.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/AbstractCDSPropertiesBean.java
@@ -4,86 +4,86 @@ import java.io.Serializable;
public class AbstractCDSPropertiesBean implements Serializable {
- private static final long serialVersionUID = -4800522372460352963L;
+ private static final long serialVersionUID = -4800522372460352963L;
- private String blueprintName;
+ private String blueprintName;
- private String blueprintVersion;
+ private String blueprintVersion;
- private String requestObject;
+ private String requestObject;
- private String originatorId;
+ private String originatorId;
- private String requestId;
+ private String requestId;
- private String subRequestId;
+ private String subRequestId;
- private String actionName;
+ private String actionName;
- private String mode;
+ private String mode;
- public String getBlueprintName() {
- return blueprintName;
- }
+ public String getBlueprintName() {
+ return blueprintName;
+ }
- public void setBlueprintName(String blueprintName) {
- this.blueprintName = blueprintName;
- }
+ public void setBlueprintName(String blueprintName) {
+ this.blueprintName = blueprintName;
+ }
- public String getBlueprintVersion() {
- return blueprintVersion;
- }
+ public String getBlueprintVersion() {
+ return blueprintVersion;
+ }
- public void setBlueprintVersion(String blueprintVersion) {
- this.blueprintVersion = blueprintVersion;
- }
+ public void setBlueprintVersion(String blueprintVersion) {
+ this.blueprintVersion = blueprintVersion;
+ }
- public String getRequestObject() {
- return requestObject;
- }
+ public String getRequestObject() {
+ return requestObject;
+ }
- public void setRequestObject(String requestObject) {
- this.requestObject = requestObject;
- }
+ public void setRequestObject(String requestObject) {
+ this.requestObject = requestObject;
+ }
- public String getOriginatorId() {
- return originatorId;
- }
+ public String getOriginatorId() {
+ return originatorId;
+ }
- public void setOriginatorId(String originatorId) {
- this.originatorId = originatorId;
- }
+ public void setOriginatorId(String originatorId) {
+ this.originatorId = originatorId;
+ }
- public String getRequestId() {
- return requestId;
- }
+ public String getRequestId() {
+ return requestId;
+ }
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
- public String getSubRequestId() {
- return subRequestId;
- }
+ public String getSubRequestId() {
+ return subRequestId;
+ }
- public void setSubRequestId(String subRequestId) {
- this.subRequestId = subRequestId;
- }
+ public void setSubRequestId(String subRequestId) {
+ this.subRequestId = subRequestId;
+ }
- public String getActionName() {
- return actionName;
- }
+ public String getActionName() {
+ return actionName;
+ }
- public void setActionName(String actionName) {
- this.actionName = actionName;
- }
+ public void setActionName(String actionName) {
+ this.actionName = actionName;
+ }
- public String getMode() {
- return mode;
- }
+ public String getMode() {
+ return mode;
+ }
- public void setMode(String mode) {
- this.mode = mode;
- }
+ public void setMode(String mode) {
+ this.mode = mode;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java
index bdb9161735..cb0b5663e6 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java
@@ -2,111 +2,104 @@ package org.onap.so.client.cds.beans;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"service-instance-id",
-"pnf-id",
-"pnf-name",
-"service-model-uuid",
-"pnf-customization-uuid"
-})
+@JsonPropertyOrder({"service-instance-id", "pnf-id", "pnf-name", "service-model-uuid", "pnf-customization-uuid"})
public class ConfigAssignPropertiesForPnf {
- @JsonProperty("service-instance-id")
- private String serviceInstanceId;
-
- @JsonProperty("pnf-id")
- private String pnfId;
-
- @JsonProperty("pnf-name")
- private String pnfName;
-
- @JsonProperty("service-model-uuid")
- private String serviceModelUuid;
-
- @JsonProperty("pnf-customization-uuid")
- private String pnfCustomizationUuid;
-
- @JsonIgnore
- private Map<String, Object> userParam = new HashMap<String, Object>();
-
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
-
- public String getPnfId() {
- return pnfId;
- }
-
- public void setPnfId(String pnfId) {
- this.pnfId = pnfId;
- }
-
- public String getPnfName() {
- return pnfName;
- }
-
- public void setPnfName(String pnfName) {
- this.pnfName = pnfName;
- }
-
- public String getServiceModelUuid() {
- return serviceModelUuid;
- }
-
- public void setServiceModelUuid(String serviceModelUuid) {
- this.serviceModelUuid = serviceModelUuid;
- }
-
- public String getPnfCustomizationUuid() {
- return pnfCustomizationUuid;
- }
-
- public void setPnfCustomizationUuid(String pnfCustomizationUuid) {
- this.pnfCustomizationUuid = pnfCustomizationUuid;
- }
-
- public Map<String, Object> getUserParam() {
- return this.userParam;
- }
-
- public void setUserParam(String name, Object value) {
- this.userParam.put(name, value);
- }
-
- @Override
- public String toString() {
-
- final StringBuilder sb = new StringBuilder("{");
- sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\"");
- sb.append(", \"pnf-id\":").append("\"").append(pnfId).append("\"");
- sb.append(", \"pnf-name\":").append("\"").append(pnfName).append("\"");
- sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\"");
- sb.append(", \"pnf-customization-uuid\":").append("\"").append(pnfCustomizationUuid).append("\"");
- for (Map.Entry<String, Object> entry : userParam.entrySet()) {
- sb.append(",");
- sb.append("\"");
- sb.append(entry.getKey());
- sb.append("\"");
- sb.append(":");
- sb.append("\"");
- sb.append(entry.getValue());
- sb.append("\"");
- }
- sb.append('}');
-
- return sb.toString();
- }
+ @JsonProperty("service-instance-id")
+ private String serviceInstanceId;
+
+ @JsonProperty("pnf-id")
+ private String pnfId;
+
+ @JsonProperty("pnf-name")
+ private String pnfName;
+
+ @JsonProperty("service-model-uuid")
+ private String serviceModelUuid;
+
+ @JsonProperty("pnf-customization-uuid")
+ private String pnfCustomizationUuid;
+
+ @JsonIgnore
+ private Map<String, Object> userParam = new HashMap<String, Object>();
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getPnfId() {
+ return pnfId;
+ }
+
+ public void setPnfId(String pnfId) {
+ this.pnfId = pnfId;
+ }
+
+ public String getPnfName() {
+ return pnfName;
+ }
+
+ public void setPnfName(String pnfName) {
+ this.pnfName = pnfName;
+ }
+
+ public String getServiceModelUuid() {
+ return serviceModelUuid;
+ }
+
+ public void setServiceModelUuid(String serviceModelUuid) {
+ this.serviceModelUuid = serviceModelUuid;
+ }
+
+ public String getPnfCustomizationUuid() {
+ return pnfCustomizationUuid;
+ }
+
+ public void setPnfCustomizationUuid(String pnfCustomizationUuid) {
+ this.pnfCustomizationUuid = pnfCustomizationUuid;
+ }
+
+ public Map<String, Object> getUserParam() {
+ return this.userParam;
+ }
+
+ public void setUserParam(String name, Object value) {
+ this.userParam.put(name, value);
+ }
+
+ @Override
+ public String toString() {
+
+ final StringBuilder sb = new StringBuilder("{");
+ sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\"");
+ sb.append(", \"pnf-id\":").append("\"").append(pnfId).append("\"");
+ sb.append(", \"pnf-name\":").append("\"").append(pnfName).append("\"");
+ sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\"");
+ sb.append(", \"pnf-customization-uuid\":").append("\"").append(pnfCustomizationUuid).append("\"");
+ for (Map.Entry<String, Object> entry : userParam.entrySet()) {
+ sb.append(",");
+ sb.append("\"");
+ sb.append(entry.getKey());
+ sb.append("\"");
+ sb.append(":");
+ sb.append("\"");
+ sb.append(entry.getValue());
+ sb.append("\"");
+ }
+ sb.append('}');
+
+ return sb.toString();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java
index 1ce26d8585..bd894e3e7f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java
@@ -2,23 +2,16 @@ package org.onap.so.client.cds.beans;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"service-instance-id",
-"vnf-id",
-"vnf-name",
-"service-model-uuid",
-"vnf-customization-uuid"
-})
+@JsonPropertyOrder({"service-instance-id", "vnf-id", "vnf-name", "service-model-uuid", "vnf-customization-uuid"})
public class ConfigAssignPropertiesForVnf {
-
+
@JsonProperty("service-instance-id")
private String serviceInstanceId;
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnf.java
index b96847f422..33b7187ac8 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnf.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnf.java
@@ -5,42 +5,39 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"config-assign-properties",
-"resolution-key"
-})
+@JsonPropertyOrder({"config-assign-properties", "resolution-key"})
public class ConfigAssignRequestPnf {
- @JsonProperty("resolution-key")
- private String resolutionKey;
- @JsonProperty("config-assign-properties")
- private ConfigAssignPropertiesForPnf configAssignPropertiesForPnf;
-
- public String getResolutionKey() {
- return resolutionKey;
- }
-
- public void setResolutionKey(String resolutionKey) {
- this.resolutionKey = resolutionKey;
- }
-
- public ConfigAssignPropertiesForPnf getConfigAssignPropertiesForPnf() {
- return configAssignPropertiesForPnf;
- }
-
- public void setConfigAssignPropertiesForPnf(ConfigAssignPropertiesForPnf configAssignPropertiesForPnf) {
- this.configAssignPropertiesForPnf = configAssignPropertiesForPnf;
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder("{\"config-assign-request\":{");
- sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\"");
- sb.append(", \"config-assign-properties\":").append(configAssignPropertiesForPnf.toString());
- sb.append('}');
- sb.append('}');
-
- return sb.toString();
- }
+ @JsonProperty("resolution-key")
+ private String resolutionKey;
+ @JsonProperty("config-assign-properties")
+ private ConfigAssignPropertiesForPnf configAssignPropertiesForPnf;
+
+ public String getResolutionKey() {
+ return resolutionKey;
+ }
+
+ public void setResolutionKey(String resolutionKey) {
+ this.resolutionKey = resolutionKey;
+ }
+
+ public ConfigAssignPropertiesForPnf getConfigAssignPropertiesForPnf() {
+ return configAssignPropertiesForPnf;
+ }
+
+ public void setConfigAssignPropertiesForPnf(ConfigAssignPropertiesForPnf configAssignPropertiesForPnf) {
+ this.configAssignPropertiesForPnf = configAssignPropertiesForPnf;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("{\"config-assign-request\":{");
+ sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\"");
+ sb.append(", \"config-assign-properties\":").append(configAssignPropertiesForPnf.toString());
+ sb.append('}');
+ sb.append('}');
+
+ return sb.toString();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnf.java
index b3a9601e2e..8512c4017f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnf.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnf.java
@@ -1,45 +1,43 @@
package org.onap.so.client.cds.beans;
+
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"config-assign-properties",
-"resolution-key"
-})
+@JsonPropertyOrder({"config-assign-properties", "resolution-key"})
public class ConfigAssignRequestVnf {
- @JsonProperty("resolution-key")
- private String resolutionKey;
- @JsonProperty("config-assign-properties")
- private ConfigAssignPropertiesForVnf configAssignPropertiesForVnf;
-
- public String getResolutionKey() {
- return resolutionKey;
- }
-
- public void setResolutionKey(String resolutionKey) {
- this.resolutionKey = resolutionKey;
- }
-
- public ConfigAssignPropertiesForVnf getConfigAssignPropertiesForVnf() {
- return configAssignPropertiesForVnf;
- }
-
- public void setConfigAssignPropertiesForVnf(ConfigAssignPropertiesForVnf configAssignPropertiesForVnf) {
- this.configAssignPropertiesForVnf = configAssignPropertiesForVnf;
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder("{\"config-assign-request\":{");
- sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\"");
- sb.append(", \"config-assign-properties\":").append(configAssignPropertiesForVnf.toString());
- sb.append('}');
- sb.append('}');
-
- return sb.toString();
- }
-
+ @JsonProperty("resolution-key")
+ private String resolutionKey;
+ @JsonProperty("config-assign-properties")
+ private ConfigAssignPropertiesForVnf configAssignPropertiesForVnf;
+
+ public String getResolutionKey() {
+ return resolutionKey;
+ }
+
+ public void setResolutionKey(String resolutionKey) {
+ this.resolutionKey = resolutionKey;
+ }
+
+ public ConfigAssignPropertiesForVnf getConfigAssignPropertiesForVnf() {
+ return configAssignPropertiesForVnf;
+ }
+
+ public void setConfigAssignPropertiesForVnf(ConfigAssignPropertiesForVnf configAssignPropertiesForVnf) {
+ this.configAssignPropertiesForVnf = configAssignPropertiesForVnf;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("{\"config-assign-request\":{");
+ sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\"");
+ sb.append(", \"config-assign-properties\":").append(configAssignPropertiesForVnf.toString());
+ sb.append('}');
+ sb.append('}');
+
+ return sb.toString();
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnf.java
index 6fadc7b55c..a9a3b0db15 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnf.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnf.java
@@ -5,114 +5,107 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"service-instance-id",
-"pnf-id",
-"pnf-name",
-"pnf-ipv4-address",
-"pnf-ipv6-address",
-"service-model-uuid",
-"pnf-customization-uuid"
-})
+@JsonPropertyOrder({"service-instance-id", "pnf-id", "pnf-name", "pnf-ipv4-address", "pnf-ipv6-address",
+ "service-model-uuid", "pnf-customization-uuid"})
public class ConfigDeployPropertiesForPnf {
- @JsonProperty("service-instance-id")
- private String serviceInstanceId;
+ @JsonProperty("service-instance-id")
+ private String serviceInstanceId;
- @JsonProperty("pnf-id")
- private String pnfId;
+ @JsonProperty("pnf-id")
+ private String pnfId;
- @JsonProperty("pnf-name")
- private String pnfName;
+ @JsonProperty("pnf-name")
+ private String pnfName;
- /**
- * Config Deploy require IP address of PNF.
- */
- @JsonProperty("pnf-ipv4-address")
- private String pnfIpV4Address;
+ /**
+ * Config Deploy require IP address of PNF.
+ */
+ @JsonProperty("pnf-ipv4-address")
+ private String pnfIpV4Address;
- @JsonProperty("pnf-ipv6-address")
- private String pnfIpV6Address;
+ @JsonProperty("pnf-ipv6-address")
+ private String pnfIpV6Address;
- @JsonProperty("service-model-uuid")
- private String serviceModelUuid;
+ @JsonProperty("service-model-uuid")
+ private String serviceModelUuid;
- @JsonProperty("pnf-customization-uuid")
- private String pnfCustomizationUuid;
+ @JsonProperty("pnf-customization-uuid")
+ private String pnfCustomizationUuid;
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
- public String getPnfId() {
- return pnfId;
- }
+ public String getPnfId() {
+ return pnfId;
+ }
- public void setPnfId(String pnfId) {
- this.pnfId = pnfId;
- }
+ public void setPnfId(String pnfId) {
+ this.pnfId = pnfId;
+ }
- public String getPnfName() {
- return pnfName;
- }
+ public String getPnfName() {
+ return pnfName;
+ }
- public void setPnfName(String pnfName) {
- this.pnfName = pnfName;
- }
+ public void setPnfName(String pnfName) {
+ this.pnfName = pnfName;
+ }
- public String getServiceModelUuid() {
- return serviceModelUuid;
- }
+ public String getServiceModelUuid() {
+ return serviceModelUuid;
+ }
- public void setServiceModelUuid(String serviceModelUuid) {
- this.serviceModelUuid = serviceModelUuid;
- }
+ public void setServiceModelUuid(String serviceModelUuid) {
+ this.serviceModelUuid = serviceModelUuid;
+ }
- public String getPnfCustomizationUuid() {
- return pnfCustomizationUuid;
- }
+ public String getPnfCustomizationUuid() {
+ return pnfCustomizationUuid;
+ }
- public void setPnfCustomizationUuid(String pnfCustomizationUuid) {
- this.pnfCustomizationUuid = pnfCustomizationUuid;
- }
+ public void setPnfCustomizationUuid(String pnfCustomizationUuid) {
+ this.pnfCustomizationUuid = pnfCustomizationUuid;
+ }
- public String getPnfIpV4Address() {
- return pnfIpV4Address;
- }
+ public String getPnfIpV4Address() {
+ return pnfIpV4Address;
+ }
- public void setPnfIpV4Address(String pnfIpV4Address) {
- this.pnfIpV4Address = pnfIpV4Address;
- }
+ public void setPnfIpV4Address(String pnfIpV4Address) {
+ this.pnfIpV4Address = pnfIpV4Address;
+ }
- public String getPnfIpV6Address() {
- return pnfIpV6Address;
- }
+ public String getPnfIpV6Address() {
+ return pnfIpV6Address;
+ }
- public void setPnfIpV6Address(String pnfIpV6Address) {
- this.pnfIpV6Address = pnfIpV6Address;
- }
+ public void setPnfIpV6Address(String pnfIpV6Address) {
+ this.pnfIpV6Address = pnfIpV6Address;
+ }
- @Override
- public String toString() {
+ @Override
+ public String toString() {
- final StringBuilder sb = new StringBuilder("{");
- sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\"");
- sb.append(", \"pnf-id\":").append("\"").append(pnfId).append("\"");
- sb.append(", \"pnf-name\":").append("\"").append(pnfName).append("\"");
- sb.append(", \"pnf-ipv4-address\":").append("\"").append(pnfIpV4Address).append("\"");
- sb.append(", \"pnf-ipv6-address\":").append("\"").append(pnfIpV6Address).append("\"");
- sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\"");
- sb.append(", \"pnf-customization-uuid\":").append("\"").append(pnfCustomizationUuid).append("\"");
+ final StringBuilder sb = new StringBuilder("{");
+ sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\"");
+ sb.append(", \"pnf-id\":").append("\"").append(pnfId).append("\"");
+ sb.append(", \"pnf-name\":").append("\"").append(pnfName).append("\"");
+ sb.append(", \"pnf-ipv4-address\":").append("\"").append(pnfIpV4Address).append("\"");
+ sb.append(", \"pnf-ipv6-address\":").append("\"").append(pnfIpV6Address).append("\"");
+ sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\"");
+ sb.append(", \"pnf-customization-uuid\":").append("\"").append(pnfCustomizationUuid).append("\"");
- sb.append('}');
+ sb.append('}');
- return sb.toString();
- }
+ return sb.toString();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnf.java
index ca2530b541..a3ac91ab9d 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnf.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnf.java
@@ -5,83 +5,77 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"service-instance-id",
-"vnf-id",
-"vnf-name",
-"service-model-uuid",
-"vnf-customization-uuid"
-})
+@JsonPropertyOrder({"service-instance-id", "vnf-id", "vnf-name", "service-model-uuid", "vnf-customization-uuid"})
public class ConfigDeployPropertiesForVnf {
- @JsonProperty("service-instance-id")
- private String serviceInstanceId;
+ @JsonProperty("service-instance-id")
+ private String serviceInstanceId;
- @JsonProperty("vnf-id")
- private String vnfId;
+ @JsonProperty("vnf-id")
+ private String vnfId;
- @JsonProperty("vnf-name")
- private String vnfName;
+ @JsonProperty("vnf-name")
+ private String vnfName;
- @JsonProperty("service-model-uuid")
- private String serviceModelUuid;
+ @JsonProperty("service-model-uuid")
+ private String serviceModelUuid;
- @JsonProperty("vnf-customization-uuid")
- private String vnfCustomizationUuid;
+ @JsonProperty("vnf-customization-uuid")
+ private String vnfCustomizationUuid;
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
- public String getVnfId() {
- return vnfId;
- }
+ public String getVnfId() {
+ return vnfId;
+ }
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
- public String getVnfName() {
- return vnfName;
- }
+ public String getVnfName() {
+ return vnfName;
+ }
- public void setVnfName(String vnfName) {
- this.vnfName = vnfName;
- }
+ public void setVnfName(String vnfName) {
+ this.vnfName = vnfName;
+ }
- public String getServiceModelUuid() {
- return serviceModelUuid;
- }
+ public String getServiceModelUuid() {
+ return serviceModelUuid;
+ }
- public void setServiceModelUuid(String serviceModelUuid) {
- this.serviceModelUuid = serviceModelUuid;
- }
+ public void setServiceModelUuid(String serviceModelUuid) {
+ this.serviceModelUuid = serviceModelUuid;
+ }
- public String getVnfCustomizationUuid() {
- return vnfCustomizationUuid;
- }
+ public String getVnfCustomizationUuid() {
+ return vnfCustomizationUuid;
+ }
- public void setVnfCustomizationUuid(String vnfCustomizationUuid) {
- this.vnfCustomizationUuid = vnfCustomizationUuid;
- }
+ public void setVnfCustomizationUuid(String vnfCustomizationUuid) {
+ this.vnfCustomizationUuid = vnfCustomizationUuid;
+ }
- @Override
- public String toString() {
+ @Override
+ public String toString() {
- final StringBuilder sb = new StringBuilder("{");
- sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\"");
- sb.append(", \"vnf-id\":").append("\"").append(vnfId).append("\"");
- sb.append(", \"vnf-name\":").append("\"").append(vnfName).append("\"");
- sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\"");
- sb.append(", \"vnf-customization-uuid\":").append("\"").append(vnfCustomizationUuid).append("\"");
+ final StringBuilder sb = new StringBuilder("{");
+ sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\"");
+ sb.append(", \"vnf-id\":").append("\"").append(vnfId).append("\"");
+ sb.append(", \"vnf-name\":").append("\"").append(vnfName).append("\"");
+ sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\"");
+ sb.append(", \"vnf-customization-uuid\":").append("\"").append(vnfCustomizationUuid).append("\"");
- sb.append('}');
+ sb.append('}');
- return sb.toString();
- }
+ return sb.toString();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnf.java
index 4635008d3f..817729ba4f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnf.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnf.java
@@ -5,42 +5,39 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"config-deploy-properties",
-"resolution-key"
-})
+@JsonPropertyOrder({"config-deploy-properties", "resolution-key"})
public class ConfigDeployRequestPnf {
- @JsonProperty("resolution-key")
- private String resolutionKey;
-
- @JsonProperty("config-deploy-properties")
- private ConfigDeployPropertiesForPnf configDeployPropertiesForPnf;
-
- public String getResolutionKey() {
- return resolutionKey;
- }
-
- public void setResolutionKey(String resolutionKey) {
- this.resolutionKey = resolutionKey;
- }
-
- public ConfigDeployPropertiesForPnf getConfigDeployPropertiesForPnf() {
- return configDeployPropertiesForPnf;
- }
-
- public void setConfigDeployPropertiesForPnf(ConfigDeployPropertiesForPnf configDeployPropertiesForPnf) {
- this.configDeployPropertiesForPnf = configDeployPropertiesForPnf;
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder("{\"config-deploy-request\":{");
- sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\"");
- sb.append(", \"config-deploy-properties\":").append(configDeployPropertiesForPnf.toString());
- sb.append('}');
- sb.append('}');
-
- return sb.toString();
- }
+ @JsonProperty("resolution-key")
+ private String resolutionKey;
+
+ @JsonProperty("config-deploy-properties")
+ private ConfigDeployPropertiesForPnf configDeployPropertiesForPnf;
+
+ public String getResolutionKey() {
+ return resolutionKey;
+ }
+
+ public void setResolutionKey(String resolutionKey) {
+ this.resolutionKey = resolutionKey;
+ }
+
+ public ConfigDeployPropertiesForPnf getConfigDeployPropertiesForPnf() {
+ return configDeployPropertiesForPnf;
+ }
+
+ public void setConfigDeployPropertiesForPnf(ConfigDeployPropertiesForPnf configDeployPropertiesForPnf) {
+ this.configDeployPropertiesForPnf = configDeployPropertiesForPnf;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("{\"config-deploy-request\":{");
+ sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\"");
+ sb.append(", \"config-deploy-properties\":").append(configDeployPropertiesForPnf.toString());
+ sb.append('}');
+ sb.append('}');
+
+ return sb.toString();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnf.java
index 53b956d3c4..c5fc0307b2 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnf.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnf.java
@@ -5,42 +5,39 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"config-deploy-properties",
-"resolution-key"
-})
+@JsonPropertyOrder({"config-deploy-properties", "resolution-key"})
public class ConfigDeployRequestVnf {
- @JsonProperty("resolution-key")
- private String resolutionKey;
-
- @JsonProperty("config-deploy-properties")
- private ConfigDeployPropertiesForVnf configDeployPropertiesForVnf;
-
- public String getResolutionKey() {
- return resolutionKey;
- }
-
- public void setResolutionKey(String resolutionKey) {
- this.resolutionKey = resolutionKey;
- }
-
- public ConfigDeployPropertiesForVnf getConfigDeployPropertiesForVnf() {
- return configDeployPropertiesForVnf;
- }
-
- public void setConfigDeployPropertiesForVnf(ConfigDeployPropertiesForVnf configDeployPropertiesForVnf) {
- this.configDeployPropertiesForVnf = configDeployPropertiesForVnf;
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder("{\"config-deploy-request\":{");
- sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\"");
- sb.append(", \"config-deploy-properties\":").append(configDeployPropertiesForVnf.toString());
- sb.append('}');
- sb.append('}');
-
- return sb.toString();
- }
+ @JsonProperty("resolution-key")
+ private String resolutionKey;
+
+ @JsonProperty("config-deploy-properties")
+ private ConfigDeployPropertiesForVnf configDeployPropertiesForVnf;
+
+ public String getResolutionKey() {
+ return resolutionKey;
+ }
+
+ public void setResolutionKey(String resolutionKey) {
+ this.resolutionKey = resolutionKey;
+ }
+
+ public ConfigDeployPropertiesForVnf getConfigDeployPropertiesForVnf() {
+ return configDeployPropertiesForVnf;
+ }
+
+ public void setConfigDeployPropertiesForVnf(ConfigDeployPropertiesForVnf configDeployPropertiesForVnf) {
+ this.configDeployPropertiesForVnf = configDeployPropertiesForVnf;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("{\"config-deploy-request\":{");
+ sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\"");
+ sb.append(", \"config-deploy-properties\":").append(configDeployPropertiesForVnf.toString());
+ sb.append('}');
+ sb.append('}');
+
+ return sb.toString();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DefaultDmaapPropertiesImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DefaultDmaapPropertiesImpl.java
index c5f08d4809..b037a86a78 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DefaultDmaapPropertiesImpl.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DefaultDmaapPropertiesImpl.java
@@ -17,24 +17,23 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.client.dmaapproperties;
import org.onap.so.client.dmaap.DmaapProperties;
-
import java.util.Map;
public class DefaultDmaapPropertiesImpl implements DmaapProperties {
- private final Map<String, String> properties;
+ private final Map<String, String> properties;
- public DefaultDmaapPropertiesImpl() {
- this.properties = new DmaapPropertiesMap();
- }
+ public DefaultDmaapPropertiesImpl() {
+ this.properties = new DmaapPropertiesMap();
+ }
- @Override
- public Map<String, String> getProperties() {
- return properties;
- }
+ @Override
+ public Map<String, String> getProperties() {
+ return properties;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DmaapPropertiesClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DmaapPropertiesClient.java
index cbedefe7eb..cc262b250f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DmaapPropertiesClient.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DmaapPropertiesClient.java
@@ -23,7 +23,6 @@
package org.onap.so.client.dmaapproperties;
import javax.inject.Provider;
-
import org.onap.so.client.avpn.dmaap.beans.AVPNDmaapBean;
import org.onap.so.client.avpn.dmaap.beans.AsyncRequestStatus;
import org.onap.so.client.avpn.dmaap.beans.InstanceReferences;
@@ -33,86 +32,90 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class DmaapPropertiesClient {
- private static final Logger logger = LoggerFactory.getLogger(DmaapPropertiesClient.class);
-
- @Autowired
- private Provider<GlobalDmaapPublisher> dmaapPublisher;
-
- protected AVPNDmaapBean buildRequestJson(String requestId, String clientSource, String correlator, String serviceInstanceId, String startTime, String finishTime,
- String requestScope, String requestType, String timestamp, String requestState, String statusMessage, String percentProgress, Boolean wasRolledBack) {
-
- RequestStatus requestStatus = buildRequestStatus(timestamp, requestState, statusMessage, percentProgress, wasRolledBack);
-
- InstanceReferences instanceReferences = buildInstanceReferences(serviceInstanceId);
-
- AsyncRequestStatus asyncRequestStatus = buildAsyncRequestStatus(requestId, clientSource, correlator, startTime, finishTime,
- requestScope, requestType, requestStatus, instanceReferences);
-
- AVPNDmaapBean dmaapBean = new AVPNDmaapBean();
- dmaapBean.setAsyncRequestStatus(asyncRequestStatus);
-
- return dmaapBean;
- }
-
- private String jsonToString(AVPNDmaapBean dmaapBean) throws JsonProcessingException, MapperException {
- try {
- return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(dmaapBean);
- } catch (JsonProcessingException e) {
- logger.error("Exception occurred", e);
- throw new MapperException(e.getMessage());
- }
- }
-
- private AsyncRequestStatus buildAsyncRequestStatus(String requestId, String clientSource, String correlator, String startTime,
- String finishTime, String requestScope, String requestType,
- RequestStatus requestStatus, InstanceReferences instanceReferences) {
-
- AsyncRequestStatus asyncRequestStatus = new AsyncRequestStatus();
- asyncRequestStatus.setRequestId(requestId);
- asyncRequestStatus.setClientSource(clientSource);
- asyncRequestStatus.setCorrelator(correlator);
- asyncRequestStatus.setStartTime(startTime);
- asyncRequestStatus.setFinishTime(finishTime);
- asyncRequestStatus.setRequestScope(requestScope);
- asyncRequestStatus.setRequestType(requestType);
- asyncRequestStatus.setInstanceReferences(instanceReferences);
- asyncRequestStatus.setRequestStatus(requestStatus);
-
- return asyncRequestStatus;
- }
-
- private InstanceReferences buildInstanceReferences(String serviceInstanceId) {
- InstanceReferences instanceReferences = new InstanceReferences();
- instanceReferences.setServiceInstanceId(serviceInstanceId);
- return instanceReferences;
- }
-
- private RequestStatus buildRequestStatus(String timestamp, String requestState, String statusMessage,
- String percentProgress, Boolean wasRolledBack) {
- RequestStatus requestStatus = new RequestStatus();
- requestStatus.setTimestamp(timestamp);
- requestStatus.setRequestState(requestState);
- requestStatus.setStatusMessage(statusMessage);
- requestStatus.setPercentProgress(percentProgress);
- requestStatus.setWasRolledBack(wasRolledBack);
- return requestStatus;
- }
-
- public void dmaapPublishRequest(String requestId, String clientSource, String correlator, String serviceInstanceId, String startTime,
- String finishTime, String requestScope, String requestType, String timestamp, String requestState,
- String statusMessage, String percentProgress, Boolean wasRolledBack) throws MapperException, JsonProcessingException {
-
- AVPNDmaapBean bean = this.buildRequestJson(requestId, clientSource, correlator, serviceInstanceId, startTime, finishTime,
- requestScope, requestType, timestamp, requestState, statusMessage, percentProgress, wasRolledBack);
-
- String request = jsonToString(bean);
- dmaapPublisher.get().send(request);
- }
+ private static final Logger logger = LoggerFactory.getLogger(DmaapPropertiesClient.class);
+
+ @Autowired
+ private Provider<GlobalDmaapPublisher> dmaapPublisher;
+
+ protected AVPNDmaapBean buildRequestJson(String requestId, String clientSource, String correlator,
+ String serviceInstanceId, String startTime, String finishTime, String requestScope, String requestType,
+ String timestamp, String requestState, String statusMessage, String percentProgress,
+ Boolean wasRolledBack) {
+
+ RequestStatus requestStatus =
+ buildRequestStatus(timestamp, requestState, statusMessage, percentProgress, wasRolledBack);
+
+ InstanceReferences instanceReferences = buildInstanceReferences(serviceInstanceId);
+
+ AsyncRequestStatus asyncRequestStatus = buildAsyncRequestStatus(requestId, clientSource, correlator, startTime,
+ finishTime, requestScope, requestType, requestStatus, instanceReferences);
+
+ AVPNDmaapBean dmaapBean = new AVPNDmaapBean();
+ dmaapBean.setAsyncRequestStatus(asyncRequestStatus);
+
+ return dmaapBean;
+ }
+
+ private String jsonToString(AVPNDmaapBean dmaapBean) throws JsonProcessingException, MapperException {
+ try {
+ return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(dmaapBean);
+ } catch (JsonProcessingException e) {
+ logger.error("Exception occurred", e);
+ throw new MapperException(e.getMessage());
+ }
+ }
+
+ private AsyncRequestStatus buildAsyncRequestStatus(String requestId, String clientSource, String correlator,
+ String startTime, String finishTime, String requestScope, String requestType, RequestStatus requestStatus,
+ InstanceReferences instanceReferences) {
+
+ AsyncRequestStatus asyncRequestStatus = new AsyncRequestStatus();
+ asyncRequestStatus.setRequestId(requestId);
+ asyncRequestStatus.setClientSource(clientSource);
+ asyncRequestStatus.setCorrelator(correlator);
+ asyncRequestStatus.setStartTime(startTime);
+ asyncRequestStatus.setFinishTime(finishTime);
+ asyncRequestStatus.setRequestScope(requestScope);
+ asyncRequestStatus.setRequestType(requestType);
+ asyncRequestStatus.setInstanceReferences(instanceReferences);
+ asyncRequestStatus.setRequestStatus(requestStatus);
+
+ return asyncRequestStatus;
+ }
+
+ private InstanceReferences buildInstanceReferences(String serviceInstanceId) {
+ InstanceReferences instanceReferences = new InstanceReferences();
+ instanceReferences.setServiceInstanceId(serviceInstanceId);
+ return instanceReferences;
+ }
+
+ private RequestStatus buildRequestStatus(String timestamp, String requestState, String statusMessage,
+ String percentProgress, Boolean wasRolledBack) {
+ RequestStatus requestStatus = new RequestStatus();
+ requestStatus.setTimestamp(timestamp);
+ requestStatus.setRequestState(requestState);
+ requestStatus.setStatusMessage(statusMessage);
+ requestStatus.setPercentProgress(percentProgress);
+ requestStatus.setWasRolledBack(wasRolledBack);
+ return requestStatus;
+ }
+
+ public void dmaapPublishRequest(String requestId, String clientSource, String correlator, String serviceInstanceId,
+ String startTime, String finishTime, String requestScope, String requestType, String timestamp,
+ String requestState, String statusMessage, String percentProgress, Boolean wasRolledBack)
+ throws MapperException, JsonProcessingException {
+
+ AVPNDmaapBean bean = this.buildRequestJson(requestId, clientSource, correlator, serviceInstanceId, startTime,
+ finishTime, requestScope, requestType, timestamp, requestState, statusMessage, percentProgress,
+ wasRolledBack);
+
+ String request = jsonToString(bean);
+ dmaapPublisher.get().send(request);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DmaapPropertiesMap.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DmaapPropertiesMap.java
index 796ccf18b7..b6ec2c5b9c 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DmaapPropertiesMap.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/DmaapPropertiesMap.java
@@ -21,27 +21,26 @@
package org.onap.so.client.dmaapproperties;
import org.onap.so.bpmn.core.UrnPropertiesReader;
-
import java.util.HashMap;
/**
- * This class is used when Dmaap Properties are to be accessed from
- * application.yaml and it delegates get calls to UrnPropertyReader class
- * for reading the value from active configuration
+ * This class is used when Dmaap Properties are to be accessed from application.yaml and it delegates get calls to
+ * UrnPropertyReader class for reading the value from active configuration
+ *
* @param <K> Key for Map Entry
* @param <V> Value for Map Entry
*/
-public class DmaapPropertiesMap<K,V> extends HashMap<K,V> {
+public class DmaapPropertiesMap<K, V> extends HashMap<K, V> {
@Override
public V get(Object key) {
- return (V)UrnPropertiesReader.getVariable((String)key);
+ return (V) UrnPropertiesReader.getVariable((String) key);
}
@Override
public V getOrDefault(Object key, V defaultValue) {
- String str = UrnPropertiesReader.getVariable((String)key);
- return str ==null ? defaultValue : (V)str;
+ String str = UrnPropertiesReader.getVariable((String) key);
+ return str == null ? defaultValue : (V) str;
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/GlobalDmaapPublisher.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/GlobalDmaapPublisher.java
index 17b99e2741..cb22fc5c7c 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/GlobalDmaapPublisher.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/dmaapproperties/GlobalDmaapPublisher.java
@@ -21,10 +21,8 @@ package org.onap.so.client.dmaapproperties;
import java.io.IOException;
import java.util.Optional;
-
import org.onap.so.bpmn.core.UrnPropertiesReader;
import org.onap.so.client.dmaap.DmaapPublisher;
-
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@@ -32,32 +30,32 @@ import org.springframework.stereotype.Component;
@Scope("prototype")
public class GlobalDmaapPublisher extends DmaapPublisher {
-
- public GlobalDmaapPublisher() throws IOException {
- super();
- }
-
- @Override
- public String getAuth() {
- return UrnPropertiesReader.getVariable("mso.global.dmaap.auth");
- }
+ public GlobalDmaapPublisher() throws IOException {
+ super();
+ }
+
+ @Override
+ public String getAuth() {
+
+ return UrnPropertiesReader.getVariable("mso.global.dmaap.auth");
+ }
- @Override
- public String getKey() {
+ @Override
+ public String getKey() {
- return UrnPropertiesReader.getVariable("mso.msoKey");
- }
+ return UrnPropertiesReader.getVariable("mso.msoKey");
+ }
- @Override
- public String getTopic() {
- return UrnPropertiesReader.getVariable("mso.global.dmaap.publisher.topic");
- }
+ @Override
+ public String getTopic() {
+ return UrnPropertiesReader.getVariable("mso.global.dmaap.publisher.topic");
+ }
- @Override
- public Optional<String> getHost() {
- return Optional.ofNullable(UrnPropertiesReader.getVariable("mso.global.dmaap.host"));
- }
+ @Override
+ public Optional<String> getHost() {
+ return Optional.ofNullable(UrnPropertiesReader.getVariable("mso.global.dmaap.host"));
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BBObjectNotFoundException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BBObjectNotFoundException.java
index 26c8d80075..8a1a110fac 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BBObjectNotFoundException.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BBObjectNotFoundException.java
@@ -22,24 +22,23 @@ package org.onap.so.client.exception;
import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
-public class BBObjectNotFoundException extends Exception{
- private ResourceKey resourceKey;
- private String resourceValue;
-
+public class BBObjectNotFoundException extends Exception {
+ private ResourceKey resourceKey;
+ private String resourceValue;
+
public BBObjectNotFoundException() {}
- public BBObjectNotFoundException(ResourceKey resourceKey, String resourceValue)
- {
- super("BBObject" + resourceKey + " was not found in gBBInput using reference value: " + resourceValue);
- this.resourceKey = resourceKey;
- this.resourceValue = resourceValue;
+ public BBObjectNotFoundException(ResourceKey resourceKey, String resourceValue) {
+ super("BBObject" + resourceKey + " was not found in gBBInput using reference value: " + resourceValue);
+ this.resourceKey = resourceKey;
+ this.resourceValue = resourceValue;
}
public ResourceKey getResourceKey() {
- return resourceKey;
+ return resourceKey;
}
-
+
public String getResourceValue() {
- return resourceValue;
+ return resourceValue;
}
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BadResponseException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BadResponseException.java
index ac8ff9efe4..333d99ed2e 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BadResponseException.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BadResponseException.java
@@ -20,13 +20,12 @@
package org.onap.so.client.exception;
-public class BadResponseException extends Exception{
+public class BadResponseException extends Exception {
- public BadResponseException() {}
+ public BadResponseException() {}
- public BadResponseException(String message)
- {
- super(message);
+ public BadResponseException(String message) {
+ super(message);
}
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java
index cb65f4d420..ae5e41f7ce 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java
@@ -35,96 +35,101 @@ import org.springframework.stereotype.Component;
@Component
public class ExceptionBuilder {
- private static final Logger logger = LoggerFactory.getLogger(ExceptionBuilder.class);
-
- public void buildAndThrowWorkflowException(BuildingBlockExecution execution, int errorCode, Exception exception) {
- String msg = "Exception in %s.%s ";
- try{
- logger.error("Exception occurred", exception);
-
- String errorVariable = "Error%s%s";
-
- StackTraceElement[] trace = Thread.currentThread().getStackTrace();
- for (StackTraceElement traceElement : trace) {
- if (!traceElement.getClassName().equals(this.getClass().getName()) && !traceElement.getClassName().equals(Thread.class.getName())) {
- msg = String.format(msg, traceElement.getClassName(), traceElement.getMethodName());
- String shortClassName = traceElement.getClassName().substring(traceElement.getClassName().lastIndexOf(".") + 1);
- errorVariable = String.format(errorVariable, shortClassName, traceElement.getMethodName());
- break;
- }
- }
-
- logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
- ErrorCode.UnknownError.getValue(), msg.toString());
- execution.setVariable(errorVariable, exception.getMessage());
- } catch (Exception ex){
- //log trace, allow process to complete gracefully
- logger.error("Exception occurred", ex);
- }
-
- if (exception.getMessage() != null)
- msg = msg.concat(exception.getMessage());
- buildAndThrowWorkflowException(execution, errorCode, msg);
- }
-
- public void buildAndThrowWorkflowException(DelegateExecution execution, int errorCode, Exception exception) {
- String msg = "Exception in %s.%s ";
- try{
- logger.error("Exception occurred", exception);
-
- String errorVariable = "Error%s%s";
-
- StackTraceElement[] trace = Thread.currentThread().getStackTrace();
- for (StackTraceElement traceElement : trace) {
- if (!traceElement.getClassName().equals(this.getClass().getName()) && !traceElement.getClassName().equals(Thread.class.getName())) {
- msg = String.format(msg, traceElement.getClassName(), traceElement.getMethodName());
- String shortClassName = traceElement.getClassName().substring(traceElement.getClassName().lastIndexOf(".") + 1);
- errorVariable = String.format(errorVariable, shortClassName, traceElement.getMethodName());
- break;
- }
- }
- logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
- ErrorCode.UnknownError.getValue(), msg.toString());
- execution.setVariable(errorVariable, exception.getMessage());
- } catch (Exception ex){
- //log trace, allow process to complete gracefully
- logger.error("Exception occurred", ex);
- }
-
- if (exception.getMessage() != null)
- msg = msg.concat(exception.getMessage());
- buildAndThrowWorkflowException(execution, errorCode, msg);
- }
-
- public void buildAndThrowWorkflowException(BuildingBlockExecution execution, int errorCode, String errorMessage) {
- if (execution instanceof DelegateExecutionImpl) {
- buildAndThrowWorkflowException(((DelegateExecutionImpl) execution).getDelegateExecution(), errorCode, errorMessage);
- }
- }
-
- public void buildAndThrowWorkflowException(DelegateExecution execution, int errorCode, String errorMessage) {
- String processKey = getProcessKey(execution);
- logger.info("Building a WorkflowException for Subflow");
-
- WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage);
- execution.setVariable("WorkflowException", exception);
- execution.setVariable("WorkflowExceptionErrorMessage", errorMessage);
- logger.info("Outgoing WorkflowException is {}", exception);
- logger.info("Throwing MSOWorkflowException");
- throw new BpmnError("MSOWorkflowException");
- }
-
- public void buildAndThrowWorkflowException(DelegateExecution execution, String errorCode, String errorMessage) {
- execution.setVariable("WorkflowExceptionErrorMessage", errorMessage);
- throw new BpmnError(errorCode,errorMessage);
- }
-
- public String getProcessKey(DelegateExecution execution) {
- String testKey = (String) execution.getVariable("testProcessKey");
- if (testKey != null) {
- return testKey;
- }
- return execution.getProcessEngineServices().getRepositoryService()
- .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
- }
+ private static final Logger logger = LoggerFactory.getLogger(ExceptionBuilder.class);
+
+ public void buildAndThrowWorkflowException(BuildingBlockExecution execution, int errorCode, Exception exception) {
+ String msg = "Exception in %s.%s ";
+ try {
+ logger.error("Exception occurred", exception);
+
+ String errorVariable = "Error%s%s";
+
+ StackTraceElement[] trace = Thread.currentThread().getStackTrace();
+ for (StackTraceElement traceElement : trace) {
+ if (!traceElement.getClassName().equals(this.getClass().getName())
+ && !traceElement.getClassName().equals(Thread.class.getName())) {
+ msg = String.format(msg, traceElement.getClassName(), traceElement.getMethodName());
+ String shortClassName =
+ traceElement.getClassName().substring(traceElement.getClassName().lastIndexOf(".") + 1);
+ errorVariable = String.format(errorVariable, shortClassName, traceElement.getMethodName());
+ break;
+ }
+ }
+
+ logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
+ ErrorCode.UnknownError.getValue(), msg.toString());
+ execution.setVariable(errorVariable, exception.getMessage());
+ } catch (Exception ex) {
+ // log trace, allow process to complete gracefully
+ logger.error("Exception occurred", ex);
+ }
+
+ if (exception.getMessage() != null)
+ msg = msg.concat(exception.getMessage());
+ buildAndThrowWorkflowException(execution, errorCode, msg);
+ }
+
+ public void buildAndThrowWorkflowException(DelegateExecution execution, int errorCode, Exception exception) {
+ String msg = "Exception in %s.%s ";
+ try {
+ logger.error("Exception occurred", exception);
+
+ String errorVariable = "Error%s%s";
+
+ StackTraceElement[] trace = Thread.currentThread().getStackTrace();
+ for (StackTraceElement traceElement : trace) {
+ if (!traceElement.getClassName().equals(this.getClass().getName())
+ && !traceElement.getClassName().equals(Thread.class.getName())) {
+ msg = String.format(msg, traceElement.getClassName(), traceElement.getMethodName());
+ String shortClassName =
+ traceElement.getClassName().substring(traceElement.getClassName().lastIndexOf(".") + 1);
+ errorVariable = String.format(errorVariable, shortClassName, traceElement.getMethodName());
+ break;
+ }
+ }
+ logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
+ ErrorCode.UnknownError.getValue(), msg.toString());
+ execution.setVariable(errorVariable, exception.getMessage());
+ } catch (Exception ex) {
+ // log trace, allow process to complete gracefully
+ logger.error("Exception occurred", ex);
+ }
+
+ if (exception.getMessage() != null)
+ msg = msg.concat(exception.getMessage());
+ buildAndThrowWorkflowException(execution, errorCode, msg);
+ }
+
+ public void buildAndThrowWorkflowException(BuildingBlockExecution execution, int errorCode, String errorMessage) {
+ if (execution instanceof DelegateExecutionImpl) {
+ buildAndThrowWorkflowException(((DelegateExecutionImpl) execution).getDelegateExecution(), errorCode,
+ errorMessage);
+ }
+ }
+
+ public void buildAndThrowWorkflowException(DelegateExecution execution, int errorCode, String errorMessage) {
+ String processKey = getProcessKey(execution);
+ logger.info("Building a WorkflowException for Subflow");
+
+ WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage);
+ execution.setVariable("WorkflowException", exception);
+ execution.setVariable("WorkflowExceptionErrorMessage", errorMessage);
+ logger.info("Outgoing WorkflowException is {}", exception);
+ logger.info("Throwing MSOWorkflowException");
+ throw new BpmnError("MSOWorkflowException");
+ }
+
+ public void buildAndThrowWorkflowException(DelegateExecution execution, String errorCode, String errorMessage) {
+ execution.setVariable("WorkflowExceptionErrorMessage", errorMessage);
+ throw new BpmnError(errorCode, errorMessage);
+ }
+
+ public String getProcessKey(DelegateExecution execution) {
+ String testKey = (String) execution.getVariable("testProcessKey");
+ if (testKey != null) {
+ return testKey;
+ }
+ return execution.getProcessEngineServices().getRepositoryService()
+ .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/MapperException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/MapperException.java
index 3f3beadb92..354c669d62 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/MapperException.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/MapperException.java
@@ -20,13 +20,12 @@
package org.onap.so.client.exception;
-public class MapperException extends Exception{
-
+public class MapperException extends Exception {
+
public MapperException() {}
- public MapperException(String message)
- {
- super(message);
+ public MapperException(String message) {
+ super(message);
}
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/OrchestrationStatusValidationException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/OrchestrationStatusValidationException.java
index fe7b079568..e9d1e1fba0 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/OrchestrationStatusValidationException.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/OrchestrationStatusValidationException.java
@@ -20,10 +20,10 @@
package org.onap.so.client.exception;
-public class OrchestrationStatusValidationException extends Exception{
- public OrchestrationStatusValidationException() {}
+public class OrchestrationStatusValidationException extends Exception {
+ public OrchestrationStatusValidationException() {}
public OrchestrationStatusValidationException(String message) {
- super(message);
+ super(message);
}
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/AAIPropertiesImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/AAIPropertiesImpl.java
index b7164e327e..c88e9ae34f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/AAIPropertiesImpl.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/AAIPropertiesImpl.java
@@ -22,7 +22,6 @@ package org.onap.so.client.restproperties;
import java.net.MalformedURLException;
import java.net.URL;
-
import org.onap.so.bpmn.core.UrnPropertiesReader;
import org.onap.so.client.aai.AAIProperties;
import org.onap.so.client.aai.AAIVersion;
@@ -31,33 +30,33 @@ import org.springframework.stereotype.Component;
@Component
public class AAIPropertiesImpl implements AAIProperties {
- public static final String MSO_MSO_KEY = "mso.msoKey";
- public static final String AAI_AUTH = "aai.auth";
- public static final String AAI_ENDPOINT = "aai.endpoint";
- private UrnPropertiesReader reader;
-
- @Override
- public URL getEndpoint() throws MalformedURLException {
- return new URL(reader.getVariable(AAI_ENDPOINT));
- }
-
- @Override
- public String getSystemName() {
- return "MSO";
- }
-
- @Override
- public AAIVersion getDefaultVersion() {
- return AAIVersion.LATEST;
- }
-
- @Override
- public String getAuth() {
- return reader.getVariable(AAI_AUTH);
- }
-
- @Override
- public String getKey() {
- return reader.getVariable(MSO_MSO_KEY);
- }
+ public static final String MSO_MSO_KEY = "mso.msoKey";
+ public static final String AAI_AUTH = "aai.auth";
+ public static final String AAI_ENDPOINT = "aai.endpoint";
+ private UrnPropertiesReader reader;
+
+ @Override
+ public URL getEndpoint() throws MalformedURLException {
+ return new URL(reader.getVariable(AAI_ENDPOINT));
+ }
+
+ @Override
+ public String getSystemName() {
+ return "MSO";
+ }
+
+ @Override
+ public AAIVersion getDefaultVersion() {
+ return AAIVersion.LATEST;
+ }
+
+ @Override
+ public String getAuth() {
+ return reader.getVariable(AAI_AUTH);
+ }
+
+ @Override
+ public String getKey() {
+ return reader.getVariable(MSO_MSO_KEY);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/CDSPropertiesImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/CDSPropertiesImpl.java
index d1888b17df..64c45653e1 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/CDSPropertiesImpl.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/CDSPropertiesImpl.java
@@ -75,9 +75,9 @@ public class CDSPropertiesImpl implements CDSProperties {
public boolean mapNotFoundToEmpty() {
return false;
}
-
+
@Override
- public int getTimeout() {
- return Integer.parseInt(Objects.requireNonNull(UrnPropertiesReader.getVariable(TIMEOUT)));
- }
+ public int getTimeout() {
+ return Integer.parseInt(Objects.requireNonNull(UrnPropertiesReader.getVariable(TIMEOUT)));
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/PolicyRestPropertiesImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/PolicyRestPropertiesImpl.java
index 1e43adceba..4bdb8bd0fb 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/PolicyRestPropertiesImpl.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/PolicyRestPropertiesImpl.java
@@ -22,44 +22,42 @@ package org.onap.so.client.restproperties;
import java.net.MalformedURLException;
import java.net.URL;
-
import org.onap.so.bpmn.core.UrnPropertiesReader;
import org.onap.so.client.policy.PolicyRestProperties;
public class PolicyRestPropertiesImpl implements PolicyRestProperties {
- public static final String POLICY_ENDPOINT = "policy.endpoint";
- public static final String POLICY_ENVIRONMENT = "policy.environment";
- public static final String POLICY_AUTH = "policy.auth";
- public static final String POLICY_CLIENT_AUTH = "policy.client.auth";
-
- public PolicyRestPropertiesImpl() {
- }
-
- @Override
- public URL getEndpoint() {
- try {
- return new URL(UrnPropertiesReader.getVariable(POLICY_ENDPOINT));
- } catch (MalformedURLException e) {
- return null;
- }
- }
-
- @Override
- public String getSystemName() {
- return "MSO";
- }
-
- public String getClientAuth() {
- return UrnPropertiesReader.getVariable(POLICY_CLIENT_AUTH);
- }
-
- public String getAuth() {
- return UrnPropertiesReader.getVariable(POLICY_AUTH);
- }
-
- public String getEnvironment() {
- return UrnPropertiesReader.getVariable(POLICY_ENVIRONMENT);
- }
+ public static final String POLICY_ENDPOINT = "policy.endpoint";
+ public static final String POLICY_ENVIRONMENT = "policy.environment";
+ public static final String POLICY_AUTH = "policy.auth";
+ public static final String POLICY_CLIENT_AUTH = "policy.client.auth";
+
+ public PolicyRestPropertiesImpl() {}
+
+ @Override
+ public URL getEndpoint() {
+ try {
+ return new URL(UrnPropertiesReader.getVariable(POLICY_ENDPOINT));
+ } catch (MalformedURLException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public String getSystemName() {
+ return "MSO";
+ }
+
+ public String getClientAuth() {
+ return UrnPropertiesReader.getVariable(POLICY_CLIENT_AUTH);
+ }
+
+ public String getAuth() {
+ return UrnPropertiesReader.getVariable(POLICY_AUTH);
+ }
+
+ public String getEnvironment() {
+ return UrnPropertiesReader.getVariable(POLICY_ENVIRONMENT);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/UrnPropertiesReaderWrapper.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/UrnPropertiesReaderWrapper.java
index 030eff92e2..5cd567a7e3 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/UrnPropertiesReaderWrapper.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/UrnPropertiesReaderWrapper.java
@@ -24,7 +24,7 @@ import org.onap.so.bpmn.core.UrnPropertiesReader;
public class UrnPropertiesReaderWrapper {
- public String getVariable(String key) {
- return UrnPropertiesReader.getVariable(key);
- }
+ public String getVariable(String key) {
+ return UrnPropertiesReader.getVariable(key);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowProcessorException.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowProcessorException.java
index 64283d78ca..528b10ef6f 100644
--- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowProcessorException.java
+++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowProcessorException.java
@@ -23,8 +23,8 @@ package org.openecomp.mso.bpmn.common.workflow.service;
import org.onap.so.bpmn.common.workflow.context.WorkflowResponse;
/**
- * Exception thrown when an error occurs while processing the workflow.
- * This encapsulates the workflow response so that the same can be sent back to api handler.
+ * Exception thrown when an error occurs while processing the workflow. This encapsulates the workflow response so that
+ * the same can be sent back to api handler.
*/
public class WorkflowProcessorException extends RuntimeException {
WorkflowResponse workflowResponse;
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllBaseTaskTestSuite.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllBaseTaskTestSuite.java
index cd9bdc9532..f56256fac8 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllBaseTaskTestSuite.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllBaseTaskTestSuite.java
@@ -21,13 +21,13 @@
package org.onap.so;
import org.junit.runner.RunWith;
-
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
-@SuiteClasses({"**/common/aai/tasks/*Test.class", "**/bpmn/sdno/tasks/*Test.class", "**/buildingblock/SniroHomingV2Test.class"})
+@SuiteClasses({"**/common/aai/tasks/*Test.class", "**/bpmn/sdno/tasks/*Test.class",
+ "**/buildingblock/SniroHomingV2Test.class"})
public class AllBaseTaskTestSuite {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllGroovyTestSuites.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllGroovyTestSuites.java
index 696323c4ad..2608fad987 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllGroovyTestSuites.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllGroovyTestSuites.java
@@ -19,14 +19,14 @@
*/
package org.onap.so;
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses({"**/bpmn/common/scripts/**/*Test.class"})
public class AllGroovyTestSuites {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllTestSuites.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllTestSuites.java
index fa70ccf23d..0bcae3f4cf 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllTestSuites.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/AllTestSuites.java
@@ -19,14 +19,14 @@
*/
package org.onap.so;
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses({"**/*Test.class", "!**/bpmn/common/scripts/**/*Test.class"})
public class AllTestSuites {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseTest.java
index 0f702fca2d..e7395b716e 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseTest.java
@@ -26,7 +26,6 @@ import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
-
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.junit.Before;
@@ -51,7 +50,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.WireMockServer;
@@ -63,88 +61,86 @@ import com.github.tomakehurst.wiremock.WireMockServer;
@AutoConfigureWireMock(port = 0)
@Category(SpringAware.class)
public abstract class BaseTest extends BuildingBlockTestDataSetup {
-
-
- protected Map<String, Object> variables = new HashMap<>();
-
- protected TestRestTemplate restTemplate = new TestRestTemplate();
-
- protected HttpHeaders headers = new HttpHeaders();
-
-
- @Autowired
- protected RuntimeService runtimeService;
-
- @Autowired
- private RepositoryService repositoryService;
-
- @Autowired
- protected WireMockServer wireMockServer;
- /*
- * Mocked for injection via autowiring
- */
-
- @Value("${mso.catalog.db.spring.endpoint}")
- protected String endpoint;
-
- @Value("${wiremock.server.port}")
- protected String wireMockPort;
-
- @MockBean
- protected CatalogDbClient MOCK_catalogDbClient;
-
- @SpyBean
- protected InjectionHelper MOCK_injectionHelper;
-
- @SpyBean
- protected ExceptionBuilder exceptionUtil;
-
- /*
- * Classes that cannot be simply mocked because they are both
- * needed for testing another class, and must be autowired when
- * being tested themselves....or classes with private methods that
- * must be stubbed during testing
- */
-
- @SpyBean
- protected BBInputSetupMapperLayer SPY_bbInputSetupMapperLayer;
- @SpyBean
- protected BBInputSetupUtils SPY_bbInputSetupUtils;
- @SpyBean
- protected BBInputSetup SPY_bbInputSetup;
-
- /*
- * Mocked for injection via the IntectionHelper
- */
-
-
-
- @Before
- public void baseTestBefore() {
- wireMockServer.resetAll();
- variables.put("gBuildingBlockExecution", execution);
- }
-
- @LocalServerPort
- private int port;
-
- protected String readFile(String path) throws IOException {
- return readFile(path, Charset.defaultCharset());
- }
-
- protected String readFile(String path, Charset encoding) throws IOException {
- byte[] encoded = Files.readAllBytes(Paths.get(path));
- return new String(encoded, encoding);
- }
-
- protected String readJsonFileAsString(String fileLocation) throws IOException{
- ObjectMapper mapper = new ObjectMapper();
- JsonNode jsonNode = mapper.readTree(new File(fileLocation));
- return jsonNode.asText();
- }
-
- protected String createURLWithPort(String uri) {
- return "http://localhost:" + port + uri;
- }
-
+
+
+ protected Map<String, Object> variables = new HashMap<>();
+
+ protected TestRestTemplate restTemplate = new TestRestTemplate();
+
+ protected HttpHeaders headers = new HttpHeaders();
+
+
+ @Autowired
+ protected RuntimeService runtimeService;
+
+ @Autowired
+ private RepositoryService repositoryService;
+
+ @Autowired
+ protected WireMockServer wireMockServer;
+ /*
+ * Mocked for injection via autowiring
+ */
+
+ @Value("${mso.catalog.db.spring.endpoint}")
+ protected String endpoint;
+
+ @Value("${wiremock.server.port}")
+ protected String wireMockPort;
+
+ @MockBean
+ protected CatalogDbClient MOCK_catalogDbClient;
+
+ @SpyBean
+ protected InjectionHelper MOCK_injectionHelper;
+
+ @SpyBean
+ protected ExceptionBuilder exceptionUtil;
+
+ /*
+ * Classes that cannot be simply mocked because they are both needed for testing another class, and must be
+ * autowired when being tested themselves....or classes with private methods that must be stubbed during testing
+ */
+
+ @SpyBean
+ protected BBInputSetupMapperLayer SPY_bbInputSetupMapperLayer;
+ @SpyBean
+ protected BBInputSetupUtils SPY_bbInputSetupUtils;
+ @SpyBean
+ protected BBInputSetup SPY_bbInputSetup;
+
+ /*
+ * Mocked for injection via the IntectionHelper
+ */
+
+
+
+ @Before
+ public void baseTestBefore() {
+ wireMockServer.resetAll();
+ variables.put("gBuildingBlockExecution", execution);
+ }
+
+ @LocalServerPort
+ private int port;
+
+ protected String readFile(String path) throws IOException {
+ return readFile(path, Charset.defaultCharset());
+ }
+
+ protected String readFile(String path, Charset encoding) throws IOException {
+ byte[] encoded = Files.readAllBytes(Paths.get(path));
+ return new String(encoded, encoding);
+ }
+
+ protected String readJsonFileAsString(String fileLocation) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ JsonNode jsonNode = mapper.readTree(new File(fileLocation));
+ return jsonNode.asText();
+ }
+
+ protected String createURLWithPort(String uri) {
+ return "http://localhost:" + port + uri;
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseUnitTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseUnitTest.java
index 5719ce15e2..fc5709d1be 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseUnitTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseUnitTest.java
@@ -20,6 +20,6 @@
package org.onap.so;
-public abstract class BaseUnitTest extends BuildingBlockTestDataSetup{
+public abstract class BaseUnitTest extends BuildingBlockTestDataSetup {
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java
index bf98648dbc..79a94d5298 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java
@@ -21,13 +21,11 @@ package org.onap.so;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import org.assertj.core.util.Arrays;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.impl.pvm.runtime.ExecutionImpl;
@@ -71,511 +69,513 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.AllottedResource;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoAllottedResource;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceProxy;
-public class BuildingBlockTestDataSetup{
- private int collectionCounter;
- private int configurationCounter;
- private int customerCounter;
- private int genericVnfCounter;
- private int instanceGroupCounter;
- private int l3NetworkCounter;
- private int owningEntityCounter;
- private int pnfCounter;
- private int projectCounter;
- private int serviceInstanceCounter;
- private int serviceProxyCounter;
- private int serviceSubscriptionCounter;
- private int vfModuleCounter;
- private int volumeGroupCounter;
- private int vpnBindingCounter;
- private int vpnBondingLinkCounter;
-
- protected BuildingBlockExecution execution;
-
- protected GeneralBuildingBlock gBBInput;
-
- protected HashMap<ResourceKey, String> lookupKeyMap;
-
- protected ExtractPojosForBB extractPojosForBB = new ExtractPojosForBB();
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- protected DelegateExecution delegateExecution;
-
- @Before
- public void buildingBlockTestDataSetupBefore() {
- collectionCounter = 0;
- configurationCounter = 0;
- customerCounter = 0;
- genericVnfCounter = 0;
- instanceGroupCounter = 0;
- l3NetworkCounter = 0;
- owningEntityCounter = 0;
- pnfCounter = 0;
- projectCounter = 0;
- serviceInstanceCounter = 0;
- serviceProxyCounter = 0;
- serviceSubscriptionCounter = 0;
- vfModuleCounter = 0;
- volumeGroupCounter = 0;
- vpnBindingCounter = 0;
- vpnBondingLinkCounter = 0;
-
- execution = new DelegateExecutionImpl(new ExecutionImpl());
- execution.setVariable("testProcessKey", "testProcessKeyValue");
-
- gBBInput = new GeneralBuildingBlock();
- execution.setVariable("gBBInput", gBBInput);
-
- lookupKeyMap = new HashMap<ResourceKey, String>();
- execution.setVariable("lookupKeyMap", lookupKeyMap);
-
- ExecutionImpl mockExecutionImpl = mock(ExecutionImpl.class);
- doReturn("test").when(mockExecutionImpl).getProcessInstanceId();
-
- ExecutionImpl executionImpl = new ExecutionImpl();
- executionImpl.setProcessInstance(mockExecutionImpl);
-
- delegateExecution = (DelegateExecution) executionImpl;
- delegateExecution.setVariable("testProcessKey", "testProcessKeyValue");
- }
-
- public Map<String, String> buildUserInput() {
- Map<String, String> userInput = new HashMap<>();
- userInput.put("testUserInputKey", "testUserInputValue");
-
- return userInput;
- }
-
- public Map<String, String> setUserInput() {
- Map<String, String> userInput = buildUserInput();
-
- gBBInput.setUserInput(userInput);
-
- return userInput;
- }
-
- public RequestContext buildRequestContext() {
- RequestContext requestContext = new RequestContext();
- requestContext.setMsoRequestId(UUID.randomUUID().toString());
- requestContext.setProductFamilyId("testProductFamilyId");
- requestContext.setRequestorId("testRequestorId");
-
- requestContext.setUserParams(new HashMap<>());
-
- Map<String,Object> dataMap = new HashMap<>();
- dataMap.put("vpnId","testVpnId");
- dataMap.put("vpnRegion","testVpnRegion");
- dataMap.put("vpnRt","testVpnRt");
- dataMap.put("vpnName","vpnName");
+public class BuildingBlockTestDataSetup {
+ private int collectionCounter;
+ private int configurationCounter;
+ private int customerCounter;
+ private int genericVnfCounter;
+ private int instanceGroupCounter;
+ private int l3NetworkCounter;
+ private int owningEntityCounter;
+ private int pnfCounter;
+ private int projectCounter;
+ private int serviceInstanceCounter;
+ private int serviceProxyCounter;
+ private int serviceSubscriptionCounter;
+ private int vfModuleCounter;
+ private int volumeGroupCounter;
+ private int vpnBindingCounter;
+ private int vpnBondingLinkCounter;
+
+ protected BuildingBlockExecution execution;
+
+ protected GeneralBuildingBlock gBBInput;
+
+ protected HashMap<ResourceKey, String> lookupKeyMap;
+
+ protected ExtractPojosForBB extractPojosForBB = new ExtractPojosForBB();
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ protected DelegateExecution delegateExecution;
+
+ @Before
+ public void buildingBlockTestDataSetupBefore() {
+ collectionCounter = 0;
+ configurationCounter = 0;
+ customerCounter = 0;
+ genericVnfCounter = 0;
+ instanceGroupCounter = 0;
+ l3NetworkCounter = 0;
+ owningEntityCounter = 0;
+ pnfCounter = 0;
+ projectCounter = 0;
+ serviceInstanceCounter = 0;
+ serviceProxyCounter = 0;
+ serviceSubscriptionCounter = 0;
+ vfModuleCounter = 0;
+ volumeGroupCounter = 0;
+ vpnBindingCounter = 0;
+ vpnBondingLinkCounter = 0;
+
+ execution = new DelegateExecutionImpl(new ExecutionImpl());
+ execution.setVariable("testProcessKey", "testProcessKeyValue");
+
+ gBBInput = new GeneralBuildingBlock();
+ execution.setVariable("gBBInput", gBBInput);
+
+ lookupKeyMap = new HashMap<ResourceKey, String>();
+ execution.setVariable("lookupKeyMap", lookupKeyMap);
+
+ ExecutionImpl mockExecutionImpl = mock(ExecutionImpl.class);
+ doReturn("test").when(mockExecutionImpl).getProcessInstanceId();
+
+ ExecutionImpl executionImpl = new ExecutionImpl();
+ executionImpl.setProcessInstance(mockExecutionImpl);
+
+ delegateExecution = (DelegateExecution) executionImpl;
+ delegateExecution.setVariable("testProcessKey", "testProcessKeyValue");
+ }
+
+ public Map<String, String> buildUserInput() {
+ Map<String, String> userInput = new HashMap<>();
+ userInput.put("testUserInputKey", "testUserInputValue");
+
+ return userInput;
+ }
+
+ public Map<String, String> setUserInput() {
+ Map<String, String> userInput = buildUserInput();
+
+ gBBInput.setUserInput(userInput);
+
+ return userInput;
+ }
+
+ public RequestContext buildRequestContext() {
+ RequestContext requestContext = new RequestContext();
+ requestContext.setMsoRequestId(UUID.randomUUID().toString());
+ requestContext.setProductFamilyId("testProductFamilyId");
+ requestContext.setRequestorId("testRequestorId");
+
+ requestContext.setUserParams(new HashMap<>());
+
+ Map<String, Object> dataMap = new HashMap<>();
+ dataMap.put("vpnId", "testVpnId");
+ dataMap.put("vpnRegion", "testVpnRegion");
+ dataMap.put("vpnRt", "testVpnRt");
+ dataMap.put("vpnName", "vpnName");
ArrayList<String> vpnRegions = new ArrayList<String>();
vpnRegions.add("USA");
vpnRegions.add("EMEA");
vpnRegions.add("APAC");
dataMap.put("vpnRegion", vpnRegions);
- HashMap<String,Object> userParams = new HashMap<>();
- userParams.put("vpnData",dataMap);
+ HashMap<String, Object> userParams = new HashMap<>();
+ userParams.put("vpnData", dataMap);
- List<Map<String,Object>> userParamsList = new ArrayList<>();
- userParamsList.add(userParams);
+ List<Map<String, Object>> userParamsList = new ArrayList<>();
+ userParamsList.add(userParams);
- RequestParameters requestParameters = new RequestParameters();
- requestParameters.setUserParams(userParamsList);
- requestContext.setRequestParameters(requestParameters);
+ RequestParameters requestParameters = new RequestParameters();
+ requestParameters.setUserParams(userParamsList);
+ requestContext.setRequestParameters(requestParameters);
- return requestContext;
- }
+ return requestContext;
+ }
- public RequestContext setRequestContext() {
- RequestContext requestContext = buildRequestContext();
+ public RequestContext setRequestContext() {
+ RequestContext requestContext = buildRequestContext();
- gBBInput.setRequestContext(requestContext);
+ gBBInput.setRequestContext(requestContext);
- return requestContext;
- }
+ return requestContext;
+ }
- public CloudRegion buildCloudRegion() {
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("testLcpCloudRegionId");
- cloudRegion.setTenantId("testTenantId");
- cloudRegion.setCloudOwner("testCloudOwner");
+ public CloudRegion buildCloudRegion() {
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("testLcpCloudRegionId");
+ cloudRegion.setTenantId("testTenantId");
+ cloudRegion.setCloudOwner("testCloudOwner");
- return cloudRegion;
- }
+ return cloudRegion;
+ }
- public CloudRegion setCloudRegion() {
- CloudRegion cloudRegion = buildCloudRegion();
+ public CloudRegion setCloudRegion() {
+ CloudRegion cloudRegion = buildCloudRegion();
- gBBInput.setCloudRegion(cloudRegion);
+ gBBInput.setCloudRegion(cloudRegion);
- return cloudRegion;
- }
+ return cloudRegion;
+ }
- public OrchestrationContext buildOrchestrationContext() {
- OrchestrationContext orchestrationContext = new OrchestrationContext();
+ public OrchestrationContext buildOrchestrationContext() {
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
- return orchestrationContext;
- }
+ return orchestrationContext;
+ }
- public OrchestrationContext setOrchestrationContext() {
- OrchestrationContext orchestrationContext = buildOrchestrationContext();
+ public OrchestrationContext setOrchestrationContext() {
+ OrchestrationContext orchestrationContext = buildOrchestrationContext();
- gBBInput.setOrchContext(orchestrationContext);
+ gBBInput.setOrchContext(orchestrationContext);
- return orchestrationContext;
- }
+ return orchestrationContext;
+ }
- public Collection buildCollection() {
- collectionCounter++;
+ public Collection buildCollection() {
+ collectionCounter++;
- Collection collection = new Collection();
- collection.setId("testId" + collectionCounter);
- collection.setInstanceGroup(buildInstanceGroup());
+ Collection collection = new Collection();
+ collection.setId("testId" + collectionCounter);
+ collection.setInstanceGroup(buildInstanceGroup());
- return collection;
- }
+ return collection;
+ }
- public Configuration buildConfiguration() {
- configurationCounter++;
+ public Configuration buildConfiguration() {
+ configurationCounter++;
- Configuration configuration = new Configuration();
- configuration.setConfigurationId("testConfigurationId" + configurationCounter);
- configuration.setConfigurationName("testConfigurationName" + configurationCounter);
+ Configuration configuration = new Configuration();
+ configuration.setConfigurationId("testConfigurationId" + configurationCounter);
+ configuration.setConfigurationName("testConfigurationName" + configurationCounter);
- ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
- modelInfoConfiguration.setModelVersionId("testModelVersionId" + configurationCounter);
- modelInfoConfiguration.setModelInvariantId("testModelInvariantId" + configurationCounter);
- modelInfoConfiguration.setModelCustomizationId("testModelCustomizationId" + configurationCounter);
+ ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
+ modelInfoConfiguration.setModelVersionId("testModelVersionId" + configurationCounter);
+ modelInfoConfiguration.setModelInvariantId("testModelInvariantId" + configurationCounter);
+ modelInfoConfiguration.setModelCustomizationId("testModelCustomizationId" + configurationCounter);
- configuration.setModelInfoConfiguration(modelInfoConfiguration);
+ configuration.setModelInfoConfiguration(modelInfoConfiguration);
- return configuration;
- }
+ return configuration;
+ }
- public OwningEntity buildOwningEntity() {
- owningEntityCounter++;
+ public OwningEntity buildOwningEntity() {
+ owningEntityCounter++;
- OwningEntity owningEntity = new OwningEntity();
- owningEntity.setOwningEntityId("testOwningEntityId" + owningEntityCounter);
- owningEntity.setOwningEntityName("testOwningEntityName" + owningEntityCounter);
+ OwningEntity owningEntity = new OwningEntity();
+ owningEntity.setOwningEntityId("testOwningEntityId" + owningEntityCounter);
+ owningEntity.setOwningEntityName("testOwningEntityName" + owningEntityCounter);
- return owningEntity;
- }
+ return owningEntity;
+ }
- public Project buildProject() {
- projectCounter++;
+ public Project buildProject() {
+ projectCounter++;
- Project project = new Project();
- project.setProjectName("testProjectName" + projectCounter);
+ Project project = new Project();
+ project.setProjectName("testProjectName" + projectCounter);
- return project;
- }
+ return project;
+ }
- public ServiceSubscription buildServiceSubscription() {
- serviceSubscriptionCounter++;
+ public ServiceSubscription buildServiceSubscription() {
+ serviceSubscriptionCounter++;
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- serviceSubscription.setTempUbSubAccountId("testTempUbSubAccountId" + serviceSubscriptionCounter);
- serviceSubscription.setServiceType("testServiceType" + serviceSubscriptionCounter);
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ serviceSubscription.setTempUbSubAccountId("testTempUbSubAccountId" + serviceSubscriptionCounter);
+ serviceSubscription.setServiceType("testServiceType" + serviceSubscriptionCounter);
- return serviceSubscription;
- }
+ return serviceSubscription;
+ }
- public Customer buildCustomer() {
- customerCounter++;
+ public Customer buildCustomer() {
+ customerCounter++;
- Customer customer = new Customer();
- customer.setGlobalCustomerId("testGlobalCustomerId" + customerCounter);
- customer.setSubscriberType("testSubscriberType" + customerCounter);
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("testGlobalCustomerId" + customerCounter);
+ customer.setSubscriberType("testSubscriberType" + customerCounter);
- customer.setServiceSubscription(buildServiceSubscription());
+ customer.setServiceSubscription(buildServiceSubscription());
- return customer;
- }
+ return customer;
+ }
- public ServiceInstance buildServiceInstance() {
- serviceInstanceCounter++;
+ public ServiceInstance buildServiceInstance() {
+ serviceInstanceCounter++;
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("testServiceInstanceId" + serviceInstanceCounter);
- serviceInstance.setServiceInstanceName("testServiceInstanceName" + serviceInstanceCounter);
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("testServiceInstanceId" + serviceInstanceCounter);
+ serviceInstance.setServiceInstanceName("testServiceInstanceName" + serviceInstanceCounter);
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("testModelInvariantUUID" + serviceInstanceCounter);
- modelInfoServiceInstance.setModelUuid("testModelUUID" + serviceInstanceCounter);
- modelInfoServiceInstance.setModelVersion("testModelVersion" + serviceInstanceCounter);
- modelInfoServiceInstance.setModelName("testModelName" + serviceInstanceCounter);
- modelInfoServiceInstance.setServiceType("testServiceType" + serviceInstanceCounter);
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("testModelInvariantUUID" + serviceInstanceCounter);
+ modelInfoServiceInstance.setModelUuid("testModelUUID" + serviceInstanceCounter);
+ modelInfoServiceInstance.setModelVersion("testModelVersion" + serviceInstanceCounter);
+ modelInfoServiceInstance.setModelName("testModelName" + serviceInstanceCounter);
+ modelInfoServiceInstance.setServiceType("testServiceType" + serviceInstanceCounter);
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
- serviceInstance.setProject(buildProject());
+ serviceInstance.setProject(buildProject());
- serviceInstance.setOwningEntity(buildOwningEntity());
+ serviceInstance.setOwningEntity(buildOwningEntity());
- serviceInstance.setCollection(buildCollection());
+ serviceInstance.setCollection(buildCollection());
- serviceInstance.getConfigurations().add(buildConfiguration());
+ serviceInstance.getConfigurations().add(buildConfiguration());
- return serviceInstance;
- }
+ return serviceInstance;
+ }
- public ServiceInstance setServiceInstance() {
- ServiceInstance serviceInstance = buildServiceInstance();
+ public ServiceInstance setServiceInstance() {
+ ServiceInstance serviceInstance = buildServiceInstance();
- if(gBBInput.getCustomer() == null) {
- gBBInput.setCustomer(buildCustomer());
- }
- gBBInput.getCustomer().getServiceSubscription().getServiceInstances().add(serviceInstance);
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstance.getServiceInstanceId());
+ if (gBBInput.getCustomer() == null) {
+ gBBInput.setCustomer(buildCustomer());
+ }
+ gBBInput.getCustomer().getServiceSubscription().getServiceInstances().add(serviceInstance);
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstance.getServiceInstanceId());
- return serviceInstance;
- }
+ return serviceInstance;
+ }
- public Customer setCustomer() {
- if(gBBInput.getCustomer() != null) return gBBInput.getCustomer();
- Customer customer = new Customer();
- customer.setGlobalCustomerId("testGlobalCustomerId");
- customer.setSubscriberType("testSubscriberType");
+ public Customer setCustomer() {
+ if (gBBInput.getCustomer() != null)
+ return gBBInput.getCustomer();
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("testGlobalCustomerId");
+ customer.setSubscriberType("testSubscriberType");
- customer.setServiceSubscription(buildServiceSubscription());
+ customer.setServiceSubscription(buildServiceSubscription());
- gBBInput.setCustomer(customer);
+ gBBInput.setCustomer(customer);
- return customer;
- }
+ return customer;
+ }
- public Collection setCollection() {
- Collection collection = new Collection();
- collection.setId("testId");
+ public Collection setCollection() {
+ Collection collection = new Collection();
+ collection.setId("testId");
- ServiceInstance serviceInstance = null;
+ ServiceInstance serviceInstance = null;
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
- serviceInstance.setCollection(collection);
+ serviceInstance.setCollection(collection);
- return collection;
- }
+ return collection;
+ }
- public InstanceGroup setInstanceGroup() {
- InstanceGroup instanceGroup = new InstanceGroup();
- instanceGroup.setId("testId");
- instanceGroup.setInstanceGroupFunction("testInstanceGroupFunction");
+ public InstanceGroup setInstanceGroup() {
+ InstanceGroup instanceGroup = new InstanceGroup();
+ instanceGroup.setId("testId");
+ instanceGroup.setInstanceGroupFunction("testInstanceGroupFunction");
- Collection collection = null;
+ Collection collection = null;
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- collection = serviceInstance.getCollection();
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ collection = serviceInstance.getCollection();
- if (collection == null) {
- collection = setCollection();
- }
- } catch(BBObjectNotFoundException e) {
- collection = setCollection();
- }
+ if (collection == null) {
+ collection = setCollection();
+ }
+ } catch (BBObjectNotFoundException e) {
+ collection = setCollection();
+ }
- collection.setInstanceGroup(instanceGroup);
+ collection.setInstanceGroup(instanceGroup);
- return instanceGroup;
- }
+ return instanceGroup;
+ }
- public VpnBinding buildVpnBinding() {
- vpnBindingCounter++;
+ public VpnBinding buildVpnBinding() {
+ vpnBindingCounter++;
- VpnBinding vpnBinding = new VpnBinding();
- vpnBinding.setVpnId("testVpnId" + vpnBindingCounter);
- vpnBinding.setVpnName("testVpnName" + vpnBindingCounter);
- vpnBinding.setCustomerVpnId("testCustomerVpnId" + vpnBindingCounter);
+ VpnBinding vpnBinding = new VpnBinding();
+ vpnBinding.setVpnId("testVpnId" + vpnBindingCounter);
+ vpnBinding.setVpnName("testVpnName" + vpnBindingCounter);
+ vpnBinding.setCustomerVpnId("testCustomerVpnId" + vpnBindingCounter);
- return vpnBinding;
- }
+ return vpnBinding;
+ }
- public VpnBinding setVpnBinding() {
- VpnBinding vpnBinding = buildVpnBinding();
+ public VpnBinding setVpnBinding() {
+ VpnBinding vpnBinding = buildVpnBinding();
- Customer customer = gBBInput.getCustomer();
+ Customer customer = gBBInput.getCustomer();
- if(customer == null){
- customer = buildCustomer();
- }
+ if (customer == null) {
+ customer = buildCustomer();
+ }
- customer.getVpnBindings().add(vpnBinding);
- lookupKeyMap.put(ResourceKey.VPN_ID, vpnBinding.getVpnId());
+ customer.getVpnBindings().add(vpnBinding);
+ lookupKeyMap.put(ResourceKey.VPN_ID, vpnBinding.getVpnId());
- return vpnBinding;
- }
+ return vpnBinding;
+ }
- public InstanceGroup buildInstanceGroup() {
- instanceGroupCounter++;
+ public InstanceGroup buildInstanceGroup() {
+ instanceGroupCounter++;
- InstanceGroup instanceGroup = new InstanceGroup();
- instanceGroup.setId("testId" + instanceGroupCounter);
- instanceGroup.setInstanceGroupFunction("testInstanceGroupFunction" + instanceGroupCounter);
+ InstanceGroup instanceGroup = new InstanceGroup();
+ instanceGroup.setId("testId" + instanceGroupCounter);
+ instanceGroup.setInstanceGroupFunction("testInstanceGroupFunction" + instanceGroupCounter);
- return instanceGroup;
- }
+ return instanceGroup;
+ }
- public L3Network buildL3Network() {
- l3NetworkCounter++;
+ public L3Network buildL3Network() {
+ l3NetworkCounter++;
- L3Network network = new L3Network();
- network.setNetworkId("testNetworkId" + l3NetworkCounter);
- network.setNetworkName("testNetworkName" + l3NetworkCounter);
- network.setNetworkType("testNetworkType" + l3NetworkCounter);
+ L3Network network = new L3Network();
+ network.setNetworkId("testNetworkId" + l3NetworkCounter);
+ network.setNetworkName("testNetworkName" + l3NetworkCounter);
+ network.setNetworkType("testNetworkType" + l3NetworkCounter);
- ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
- modelInfoNetwork.setModelInvariantUUID("testModelInvariantUUID" + l3NetworkCounter);
- modelInfoNetwork.setModelName("testModelName" + l3NetworkCounter);
- modelInfoNetwork.setModelVersion("testModelVersion" + l3NetworkCounter);
- modelInfoNetwork.setModelUUID("testModelUUID" + l3NetworkCounter);
- network.setModelInfoNetwork(modelInfoNetwork);
+ ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
+ modelInfoNetwork.setModelInvariantUUID("testModelInvariantUUID" + l3NetworkCounter);
+ modelInfoNetwork.setModelName("testModelName" + l3NetworkCounter);
+ modelInfoNetwork.setModelVersion("testModelVersion" + l3NetworkCounter);
+ modelInfoNetwork.setModelUUID("testModelUUID" + l3NetworkCounter);
+ network.setModelInfoNetwork(modelInfoNetwork);
- return network;
- }
+ return network;
+ }
- public L3Network setL3Network() {
- L3Network network = buildL3Network();
+ public L3Network setL3Network() {
+ L3Network network = buildL3Network();
- ServiceInstance serviceInstance = null;
+ ServiceInstance serviceInstance = null;
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
- serviceInstance.getNetworks().add(network);
- lookupKeyMap.put(ResourceKey.NETWORK_ID, network.getNetworkId());
+ serviceInstance.getNetworks().add(network);
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, network.getNetworkId());
- return network;
- }
+ return network;
+ }
- public GenericVnf buildGenericVnf() {
- genericVnfCounter++;
+ public GenericVnf buildGenericVnf() {
+ genericVnfCounter++;
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId("testVnfId" + genericVnfCounter);
- genericVnf.setVnfName("testVnfName" + genericVnfCounter);
- genericVnf.setVnfType("testVnfType" + genericVnfCounter);
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId("testVnfId" + genericVnfCounter);
+ genericVnf.setVnfName("testVnfName" + genericVnfCounter);
+ genericVnf.setVnfType("testVnfType" + genericVnfCounter);
- Platform platform = new Platform();
- platform.setPlatformName("testPlatformName");
- genericVnf.setPlatform(platform);
+ Platform platform = new Platform();
+ platform.setPlatformName("testPlatformName");
+ genericVnf.setPlatform(platform);
- LineOfBusiness lob = new LineOfBusiness();
- lob.setLineOfBusinessName("testLineOfBusinessName");
- genericVnf.setLineOfBusiness(lob);
+ LineOfBusiness lob = new LineOfBusiness();
+ lob.setLineOfBusinessName("testLineOfBusinessName");
+ genericVnf.setLineOfBusiness(lob);
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelName("testModelName" + genericVnfCounter);
- modelInfoGenericVnf.setModelCustomizationUuid("testModelCustomizationUUID" + genericVnfCounter);
- modelInfoGenericVnf.setModelInvariantUuid("testModelInvariantUUID" + genericVnfCounter);
- modelInfoGenericVnf.setModelVersion("testModelVersion" + genericVnfCounter);
- modelInfoGenericVnf.setModelUuid("testModelUUID" + genericVnfCounter);
- modelInfoGenericVnf.setModelInstanceName("testModelInstanceName" + genericVnfCounter);
- genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelName("testModelName" + genericVnfCounter);
+ modelInfoGenericVnf.setModelCustomizationUuid("testModelCustomizationUUID" + genericVnfCounter);
+ modelInfoGenericVnf.setModelInvariantUuid("testModelInvariantUUID" + genericVnfCounter);
+ modelInfoGenericVnf.setModelVersion("testModelVersion" + genericVnfCounter);
+ modelInfoGenericVnf.setModelUuid("testModelUUID" + genericVnfCounter);
+ modelInfoGenericVnf.setModelInstanceName("testModelInstanceName" + genericVnfCounter);
+ genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf);
- return genericVnf;
- }
+ return genericVnf;
+ }
- public GenericVnf setGenericVnf() {
- GenericVnf genericVnf = buildGenericVnf();
+ public GenericVnf setGenericVnf() {
+ GenericVnf genericVnf = buildGenericVnf();
- ServiceInstance serviceInstance = null;
+ ServiceInstance serviceInstance = null;
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
- serviceInstance.getVnfs().add(genericVnf);
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, genericVnf.getVnfId());
+ serviceInstance.getVnfs().add(genericVnf);
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, genericVnf.getVnfId());
- return genericVnf;
- }
+ return genericVnf;
+ }
- public VfModule buildVfModule() {
- vfModuleCounter++;
+ public VfModule buildVfModule() {
+ vfModuleCounter++;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("testVfModuleId" + vfModuleCounter);
- vfModule.setVfModuleName("testVfModuleName" + vfModuleCounter);
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("testVfModuleId" + vfModuleCounter);
+ vfModule.setVfModuleName("testVfModuleName" + vfModuleCounter);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("testModelInvariantUUID" + vfModuleCounter);
- modelInfoVfModule.setModelVersion("testModelVersion" + vfModuleCounter);
- modelInfoVfModule.setModelUUID("testModelUUID" + vfModuleCounter);
- modelInfoVfModule.setModelName("testModelName" + vfModuleCounter);
- modelInfoVfModule.setModelCustomizationUUID("testModelCustomizationUUID" + vfModuleCounter);
- vfModule.setModelInfoVfModule(modelInfoVfModule);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("testModelInvariantUUID" + vfModuleCounter);
+ modelInfoVfModule.setModelVersion("testModelVersion" + vfModuleCounter);
+ modelInfoVfModule.setModelUUID("testModelUUID" + vfModuleCounter);
+ modelInfoVfModule.setModelName("testModelName" + vfModuleCounter);
+ modelInfoVfModule.setModelCustomizationUUID("testModelCustomizationUUID" + vfModuleCounter);
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
- return vfModule;
- }
+ return vfModule;
+ }
- public VfModule setVfModule() {
- VfModule vfModule = buildVfModule();
+ public VfModule setVfModule() {
+ VfModule vfModule = buildVfModule();
- GenericVnf genericVnf = null;
+ GenericVnf genericVnf = null;
- try {
- genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- } catch(BBObjectNotFoundException e) {
- genericVnf = setGenericVnf();
- }
+ try {
+ genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ } catch (BBObjectNotFoundException e) {
+ genericVnf = setGenericVnf();
+ }
- genericVnf.getVfModules().add(vfModule);
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, vfModule.getVfModuleId());
+ genericVnf.getVfModules().add(vfModule);
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, vfModule.getVfModuleId());
- return vfModule;
- }
+ return vfModule;
+ }
- public VolumeGroup buildVolumeGroup() {
- volumeGroupCounter++;
+ public VolumeGroup buildVolumeGroup() {
+ volumeGroupCounter++;
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("testVolumeGroupId" + volumeGroupCounter);
- volumeGroup.setVolumeGroupName("testVolumeGroupName" + volumeGroupCounter);
- volumeGroup.setHeatStackId("testHeatStackId" + volumeGroupCounter);
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("testVolumeGroupId" + volumeGroupCounter);
+ volumeGroup.setVolumeGroupName("testVolumeGroupName" + volumeGroupCounter);
+ volumeGroup.setHeatStackId("testHeatStackId" + volumeGroupCounter);
- return volumeGroup;
- }
+ return volumeGroup;
+ }
- public VolumeGroup setVolumeGroup() {
- VolumeGroup volumeGroup = buildVolumeGroup();
+ public VolumeGroup setVolumeGroup() {
+ VolumeGroup volumeGroup = buildVolumeGroup();
- GenericVnf genericVnf = null;
+ GenericVnf genericVnf = null;
- try {
- genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- } catch(BBObjectNotFoundException e) {
- genericVnf = setGenericVnf();
- }
+ try {
+ genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ } catch (BBObjectNotFoundException e) {
+ genericVnf = setGenericVnf();
+ }
- genericVnf.getVolumeGroups().add(volumeGroup);
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroup.getVolumeGroupId());
+ genericVnf.getVolumeGroups().add(volumeGroup);
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroup.getVolumeGroupId());
- return volumeGroup;
- }
+ return volumeGroup;
+ }
- public Pnf buildPnf() {
- pnfCounter++;
+ public Pnf buildPnf() {
+ pnfCounter++;
- Pnf pnf = new Pnf();
- pnf.setPnfId("testPnfId" + pnfCounter);
- pnf.setPnfName("testPnfName" + pnfCounter);
+ Pnf pnf = new Pnf();
+ pnf.setPnfId("testPnfId" + pnfCounter);
+ pnf.setPnfName("testPnfName" + pnfCounter);
- return pnf;
- }
+ return pnf;
+ }
- public ServiceProxy buildServiceProxy() {
- serviceProxyCounter++;
+ public ServiceProxy buildServiceProxy() {
+ serviceProxyCounter++;
ServiceProxy serviceProxy = new ServiceProxy();
serviceProxy.setServiceInstance(buildServiceInstance());
@@ -590,106 +590,106 @@ public class BuildingBlockTestDataSetup{
serviceProxy.getServiceInstance().getPnfs().add(secondaryPnf);
return serviceProxy;
- }
+ }
- public VpnBondingLink buildVpnBondingLink() {
- vpnBondingLinkCounter++;
+ public VpnBondingLink buildVpnBondingLink() {
+ vpnBondingLinkCounter++;
- VpnBondingLink vpnBondingLink = new VpnBondingLink();
- vpnBondingLink.setVpnBondingLinkId("testVpnBondingLinkId" + vpnBondingLinkCounter);
+ VpnBondingLink vpnBondingLink = new VpnBondingLink();
+ vpnBondingLink.setVpnBondingLinkId("testVpnBondingLinkId" + vpnBondingLinkCounter);
- Configuration vnrConfiguration = buildConfiguration();
- vnrConfiguration.setNetwork(buildL3Network());
- vpnBondingLink.setVnrConfiguration(vnrConfiguration);
+ Configuration vnrConfiguration = buildConfiguration();
+ vnrConfiguration.setNetwork(buildL3Network());
+ vpnBondingLink.setVnrConfiguration(vnrConfiguration);
- vpnBondingLink.setVrfConfiguration(buildConfiguration());
+ vpnBondingLink.setVrfConfiguration(buildConfiguration());
vpnBondingLink.setInfrastructureServiceProxy(buildServiceProxy());
vpnBondingLink.setTransportServiceProxy(buildServiceProxy());
- return vpnBondingLink;
- }
-
- public VpnBondingLink setVpnBondingLink() {
- VpnBondingLink vpnBondingLink = buildVpnBondingLink();
-
- ServiceInstance serviceInstance = null;
-
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
-
- serviceInstance.getVpnBondingLinks().add(vpnBondingLink);
- lookupKeyMap.put(ResourceKey.VPN_BONDING_LINK_ID, vpnBondingLink.getVpnBondingLinkId());
-
-
- return vpnBondingLink;
- }
-
- public Customer setAvpnCustomer() {
- Customer customer = buildCustomer();
-
- gBBInput.setCustomer(customer);
-
- return customer;
- }
-
- public ServiceProxy setServiceProxy(String uniqueIdentifier, String type) {
- ServiceProxy serviceProxy = new ServiceProxy();
- serviceProxy.setId("testProxyId" + uniqueIdentifier);
- serviceProxy.setType(type);
-
- ModelInfoServiceProxy modelInfo = new ModelInfoServiceProxy();
- modelInfo.setModelInvariantUuid("testProxyModelInvariantUuid" + uniqueIdentifier);
- modelInfo.setModelName("testProxyModelName" + uniqueIdentifier);
- modelInfo.setModelUuid("testProxyModelUuid" + uniqueIdentifier);
- modelInfo.setModelVersion("testProxyModelVersion" + uniqueIdentifier);
- modelInfo.setModelInstanceName("testProxyInstanceName" + uniqueIdentifier);
-
- serviceProxy.setModelInfoServiceProxy(modelInfo);
-
- return serviceProxy;
- }
-
- public AllottedResource setAllottedResource(String uniqueIdentifier) {
- AllottedResource ar = new AllottedResource();
- ar.setId("testAllottedResourceId" + uniqueIdentifier);
-
- ModelInfoAllottedResource modelInfo = new ModelInfoAllottedResource();
- modelInfo.setModelInvariantUuid("testAllottedModelInvariantUuid" + uniqueIdentifier);
- modelInfo.setModelName("testAllottedModelName" + uniqueIdentifier);
- modelInfo.setModelUuid("testAllottedModelUuid" + uniqueIdentifier);
- modelInfo.setModelVersion("testAllottedModelVersion" + uniqueIdentifier);
- modelInfo.setModelInstanceName("testAllottedInstanceName" + uniqueIdentifier);
-
- ar.setModelInfoAllottedResource(modelInfo);
-
- return ar;
- }
-
- public Configuration setConfiguration () {
- Configuration config = new Configuration();
- config.setConfigurationId("testConfigurationId");
- ModelInfoConfiguration modelInfoConfig = new ModelInfoConfiguration();
- modelInfoConfig.setModelCustomizationId("modelCustomizationId");
- modelInfoConfig.setModelVersionId("modelVersionId");
- modelInfoConfig.setModelInvariantId("modelInvariantId");
- modelInfoConfig.setPolicyName("policyName");
- config.setModelInfoConfiguration(modelInfoConfig);
-
- List<Configuration> configurations = new ArrayList<>();
- configurations.add(config);
- ServiceInstance serviceInstance = new ServiceInstance();
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "testConfigurationId");
- serviceInstance.setConfigurations(configurations);
- return config;
- }
-} \ No newline at end of file
+ return vpnBondingLink;
+ }
+
+ public VpnBondingLink setVpnBondingLink() {
+ VpnBondingLink vpnBondingLink = buildVpnBondingLink();
+
+ ServiceInstance serviceInstance = null;
+
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
+
+ serviceInstance.getVpnBondingLinks().add(vpnBondingLink);
+ lookupKeyMap.put(ResourceKey.VPN_BONDING_LINK_ID, vpnBondingLink.getVpnBondingLinkId());
+
+
+ return vpnBondingLink;
+ }
+
+ public Customer setAvpnCustomer() {
+ Customer customer = buildCustomer();
+
+ gBBInput.setCustomer(customer);
+
+ return customer;
+ }
+
+ public ServiceProxy setServiceProxy(String uniqueIdentifier, String type) {
+ ServiceProxy serviceProxy = new ServiceProxy();
+ serviceProxy.setId("testProxyId" + uniqueIdentifier);
+ serviceProxy.setType(type);
+
+ ModelInfoServiceProxy modelInfo = new ModelInfoServiceProxy();
+ modelInfo.setModelInvariantUuid("testProxyModelInvariantUuid" + uniqueIdentifier);
+ modelInfo.setModelName("testProxyModelName" + uniqueIdentifier);
+ modelInfo.setModelUuid("testProxyModelUuid" + uniqueIdentifier);
+ modelInfo.setModelVersion("testProxyModelVersion" + uniqueIdentifier);
+ modelInfo.setModelInstanceName("testProxyInstanceName" + uniqueIdentifier);
+
+ serviceProxy.setModelInfoServiceProxy(modelInfo);
+
+ return serviceProxy;
+ }
+
+ public AllottedResource setAllottedResource(String uniqueIdentifier) {
+ AllottedResource ar = new AllottedResource();
+ ar.setId("testAllottedResourceId" + uniqueIdentifier);
+
+ ModelInfoAllottedResource modelInfo = new ModelInfoAllottedResource();
+ modelInfo.setModelInvariantUuid("testAllottedModelInvariantUuid" + uniqueIdentifier);
+ modelInfo.setModelName("testAllottedModelName" + uniqueIdentifier);
+ modelInfo.setModelUuid("testAllottedModelUuid" + uniqueIdentifier);
+ modelInfo.setModelVersion("testAllottedModelVersion" + uniqueIdentifier);
+ modelInfo.setModelInstanceName("testAllottedInstanceName" + uniqueIdentifier);
+
+ ar.setModelInfoAllottedResource(modelInfo);
+
+ return ar;
+ }
+
+ public Configuration setConfiguration() {
+ Configuration config = new Configuration();
+ config.setConfigurationId("testConfigurationId");
+ ModelInfoConfiguration modelInfoConfig = new ModelInfoConfiguration();
+ modelInfoConfig.setModelCustomizationId("modelCustomizationId");
+ modelInfoConfig.setModelVersionId("modelVersionId");
+ modelInfoConfig.setModelInvariantId("modelInvariantId");
+ modelInfoConfig.setPolicyName("policyName");
+ config.setModelInfoConfiguration(modelInfoConfig);
+
+ List<Configuration> configurations = new ArrayList<>();
+ configurations.add(config);
+ ServiceInstance serviceInstance = new ServiceInstance();
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "testConfigurationId");
+ serviceInstance.setConfigurations(configurations);
+ return config;
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
index fb08e5e830..62d9ecee44 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
@@ -19,6 +19,7 @@
*/
package org.onap.so;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
@@ -35,30 +36,25 @@ public class EmbeddedMariaDbConfig {
@Bean
MariaDB4jSpringService mariaDB4jSpringService() {
- MariaDB4jSpringService service = new MariaDB4jSpringService();
-
-
- service.getConfiguration().addArg("--lower_case_table_names=1");
+ MariaDB4jSpringService service = new MariaDB4jSpringService();
+
+
+ service.getConfiguration().addArg("--lower_case_table_names=1");
return service;
}
@Bean
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/NonSpringSuite.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/NonSpringSuite.java
index ee2848cf3a..4a9b3e1775 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/NonSpringSuite.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/NonSpringSuite.java
@@ -22,7 +22,6 @@ package org.onap.so;
import org.junit.runner.RunWith;
import org.onap.so.test.categories.SpringAware;
-
import com.googlecode.junittoolbox.ExcludeCategories;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/SerializableChecker.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/SerializableChecker.java
index 97c17d5238..47ddea1b4f 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/SerializableChecker.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/SerializableChecker.java
@@ -29,78 +29,65 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
-public final class SerializableChecker
-{
- public static class SerializationFailure
- {
+public final class SerializableChecker {
+ public static class SerializationFailure {
private final String mContainingClass;
private final String mMemberName;
- public SerializationFailure(String inNonSerializableClass, String inMemberName)
- {
+ public SerializationFailure(String inNonSerializableClass, String inMemberName) {
mContainingClass = inNonSerializableClass;
mMemberName = inMemberName;
}
- public String getContainingClass()
- {
+ public String getContainingClass() {
return mContainingClass;
}
- public String getMemberName()
- {
+ public String getMemberName() {
return mMemberName;
}
- public String getBadMemberString()
- {
+ public String getBadMemberString() {
if (mMemberName == null)
return mContainingClass;
return mContainingClass + "." + mMemberName;
}
@Override
- public String toString()
- {
- return "SerializationFailure [mNonSerializableClass=" + mContainingClass + ", mMemberName=" + mMemberName + "]";
+ public String toString() {
+ return "SerializationFailure [mNonSerializableClass=" + mContainingClass + ", mMemberName=" + mMemberName
+ + "]";
}
}
- private static class SerializationCheckerData
- {
+ private static class SerializationCheckerData {
private Set<Class<?>> mSerializableClasses;
- SerializationCheckerData()
- {
+ SerializationCheckerData() {
mSerializableClasses = new HashSet<Class<?>>();
}
- boolean isAlreadyChecked(Class<?> inClass)
- {
+ boolean isAlreadyChecked(Class<?> inClass) {
return mSerializableClasses.contains(inClass);
}
- void addSerializableClass(Class<?> inClass)
- {
+ void addSerializableClass(Class<?> inClass) {
mSerializableClasses.add(inClass);
}
}
- private SerializableChecker()
- { }
+ private SerializableChecker() {}
- public static SerializationFailure isFullySerializable(Class<?> inClass)
- {
+ public static SerializationFailure isFullySerializable(Class<?> inClass) {
if (!isSerializable(inClass))
return new SerializationFailure(inClass.getName(), null);
return isFullySerializable(inClass, new SerializationCheckerData());
}
- private static SerializationFailure isFullySerializable(Class<?> inClass, SerializationCheckerData inSerializationCheckerData)
- {
- for (Field field : declaredFields(inClass))
- {
+ private static SerializationFailure isFullySerializable(Class<?> inClass,
+ SerializationCheckerData inSerializationCheckerData) {
+ for (Field field : declaredFields(inClass)) {
Class<?> fieldDeclaringClass = field.getType();
if (field.getType() == Object.class)
@@ -121,8 +108,7 @@ public final class SerializableChecker
if (inSerializationCheckerData.isAlreadyChecked(fieldDeclaringClass))
continue;
- if (isSerializable(fieldDeclaringClass))
- {
+ if (isSerializable(fieldDeclaringClass)) {
inSerializationCheckerData.addSerializableClass(inClass);
SerializationFailure failure = isFullySerializable(field.getType(), inSerializationCheckerData);
@@ -140,8 +126,7 @@ public final class SerializableChecker
return null;
}
- private static boolean isSerializable(Class<?> inClass)
- {
+ private static boolean isSerializable(Class<?> inClass) {
Set<Class<?>> interfaces = getInterfaces(inClass);
if (interfaces == null)
return false;
@@ -149,8 +134,7 @@ public final class SerializableChecker
if (isSerializable)
return true;
- for (Class<?> classInterface : interfaces)
- {
+ for (Class<?> classInterface : interfaces) {
if (isSerializable(classInterface))
return true;
}
@@ -161,13 +145,11 @@ public final class SerializableChecker
return false;
}
- private static Set<Class<?>> getInterfaces(Class<?> inFieldDeclaringClass)
- {
+ private static Set<Class<?>> getInterfaces(Class<?> inFieldDeclaringClass) {
return new HashSet<Class<?>>(Arrays.asList(inFieldDeclaringClass.getInterfaces()));
}
- private static List<Field> declaredFields(Class<?> inClass)
- {
+ private static List<Field> declaredFields(Class<?> inClass) {
List<Field> fields = new ArrayList<Field>(Arrays.asList(inClass.getDeclaredFields()));
Class<?> parentClasses = inClass.getSuperclass();
@@ -177,5 +159,5 @@ public final class SerializableChecker
fields.addAll(declaredFields(parentClasses));
return fields;
- }
}
+}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/TestApplication.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/TestApplication.java
index 11309914ef..029b77319b 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/TestApplication.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/TestApplication.java
@@ -30,14 +30,14 @@ import org.springframework.context.annotation.Profile;
@SpringBootApplication
@Profile("test")
-@ComponentScan(basePackages = {"org.onap.so"}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class, excludeFilters = {
- @Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
+@ComponentScan(basePackages = {"org.onap.so"}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class,
+ excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
public class TestApplication {
- public static void main(String... args) {
- SpringApplication.run(TestApplication.class, args);
- System.getProperties().setProperty("mso.db", "MARIADB");
- System.getProperties().setProperty("server.name", "Springboot");
-
-
- }
+ public static void main(String... args) {
+ SpringApplication.run(TestApplication.class, args);
+ System.getProperties().setProperty("mso.db", "MARIADB");
+ System.getProperties().setProperty("server.name", "Springboot");
+
+
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/TestApplicationConfig.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/TestApplicationConfig.java
index c483f13887..d2bc728eb2 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/TestApplicationConfig.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/TestApplicationConfig.java
@@ -24,73 +24,71 @@ import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
-
import org.onap.so.bpmn.common.WorkflowTestTransformer;
import org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
-
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.extension.ResponseTransformer;
@Configuration
@Profile({"test"})
public class TestApplicationConfig {
-
- @Bean
- protected ResponseTransformer[] transformerArray() {
- // Process WorkflowTestTransformer annotations
- List<ResponseTransformer> transformerList = new ArrayList<ResponseTransformer>();
-
- for (Field field : getClass().getFields()) {
- WorkflowTestTransformer annotation = field.getAnnotation(WorkflowTestTransformer.class);
-
- if (annotation == null) {
- continue;
- }
-
- if (!Modifier.isStatic(field.getModifiers())) {
- throw new RuntimeException(field.getDeclaringClass().getName()
- + "#" + field.getName() + " has a @WorkflowTestTransformer "
- + " annotation but it is not declared static");
- }
-
- ResponseTransformer transformer;
-
- try {
- transformer = (ResponseTransformer) field.get(null);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(field.getDeclaringClass().getName()
- + "#" + field.getName() + " is not accessible", e);
- } catch (ClassCastException e) {
- throw new RuntimeException(field.getDeclaringClass().getName()
- + "#" + field.getName() + " is not a ResponseTransformer", e);
- }
-
- if (transformer == null) {
- continue;
- }
-
- transformerList.add(transformer);
- }
-
- ResponseTransformer[] transformerArray =
- transformerList.toArray(new ResponseTransformer[transformerList.size()]);
-
- optionsCustomizer(transformerArray);
-
- return transformerArray;
- }
-
- @Bean
- WireMockConfigurationCustomizer optionsCustomizer(ResponseTransformer[] transformerArray) {
- return new WireMockConfigurationCustomizer() {
- @Override
- public void customize(WireMockConfiguration options) {
- options.extensions(transformerArray);
- }
- };
- }
-
+
+ @Bean
+ protected ResponseTransformer[] transformerArray() {
+ // Process WorkflowTestTransformer annotations
+ List<ResponseTransformer> transformerList = new ArrayList<ResponseTransformer>();
+
+ for (Field field : getClass().getFields()) {
+ WorkflowTestTransformer annotation = field.getAnnotation(WorkflowTestTransformer.class);
+
+ if (annotation == null) {
+ continue;
+ }
+
+ if (!Modifier.isStatic(field.getModifiers())) {
+ throw new RuntimeException(field.getDeclaringClass().getName() + "#" + field.getName()
+ + " has a @WorkflowTestTransformer " + " annotation but it is not declared static");
+ }
+
+ ResponseTransformer transformer;
+
+ try {
+ transformer = (ResponseTransformer) field.get(null);
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException(
+ field.getDeclaringClass().getName() + "#" + field.getName() + " is not accessible", e);
+ } catch (ClassCastException e) {
+ throw new RuntimeException(
+ field.getDeclaringClass().getName() + "#" + field.getName() + " is not a ResponseTransformer",
+ e);
+ }
+
+ if (transformer == null) {
+ continue;
+ }
+
+ transformerList.add(transformer);
+ }
+
+ ResponseTransformer[] transformerArray =
+ transformerList.toArray(new ResponseTransformer[transformerList.size()]);
+
+ optionsCustomizer(transformerArray);
+
+ return transformerArray;
+ }
+
+ @Bean
+ WireMockConfigurationCustomizer optionsCustomizer(ResponseTransformer[] transformerArray) {
+ return new WireMockConfigurationCustomizer() {
+ @Override
+ public void customize(WireMockConfiguration options) {
+ options.extensions(transformerArray);
+ }
+ };
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/appc/payload/PayloadClientTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/appc/payload/PayloadClientTest.java
index 20c69fafe3..2ecf741869 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/appc/payload/PayloadClientTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/appc/payload/PayloadClientTest.java
@@ -21,61 +21,61 @@
package org.onap.so.bpmn.appc.payload;
import static org.junit.Assert.assertEquals;
-
import java.util.Optional;
-
import org.json.JSONObject;
import org.junit.Test;
public class PayloadClientTest {
- @Test
- public void upgradeFormatTest() throws Exception {
- String payloadResult = "{\"configuration-parameters\":{\"vnf_name\":\"vnfName1\",\"existing_software_version\":\"existingVersion\",\"new_software_version\":\"newVersion\"}}";
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("existing_software_version", "existingVersion");
- jsonObject.put("new_software_version", "newVersion");
- Optional<String> payload = Optional.of(jsonObject.toString());
- Optional<String> payloadClient = PayloadClient.upgradeFormat(payload, "vnfName1");
- assertEquals(payloadResult, payloadClient.get());
- }
+ @Test
+ public void upgradeFormatTest() throws Exception {
+ String payloadResult =
+ "{\"configuration-parameters\":{\"vnf_name\":\"vnfName1\",\"existing_software_version\":\"existingVersion\",\"new_software_version\":\"newVersion\"}}";
+ JSONObject jsonObject = new JSONObject();
+ jsonObject.put("existing_software_version", "existingVersion");
+ jsonObject.put("new_software_version", "newVersion");
+ Optional<String> payload = Optional.of(jsonObject.toString());
+ Optional<String> payloadClient = PayloadClient.upgradeFormat(payload, "vnfName1");
+ assertEquals(payloadResult, payloadClient.get());
+ }
+
+ @Test
+ public void resumeTrafficFormatTest() throws Exception {
+ String payloadResult = "{\"configuration-parameters\":{\"vnf_name\":\"vnfName1\"}}";
+ Optional<String> payloadClient = PayloadClient.resumeTrafficFormat("vnfName1");
+ assertEquals(payloadResult, payloadClient.get());
+ }
+
+ @Test
+ public void quiesceTrafficFormatTest() throws Exception {
+ String payloadResult =
+ "{\"configuration-parameters\":{\"vnf_name\":\"vnfName1\",\"operations_timeout\":\"operationTimeout\"}}";
+ JSONObject jsonObject = new JSONObject();
+ jsonObject.put("operations_timeout", "operationTimeout");
+ Optional<String> payload = Optional.of(jsonObject.toString());
+ Optional<String> payloadClient = PayloadClient.quiesceTrafficFormat(payload, "vnfName1");
+ assertEquals(payloadResult, payloadClient.get());
+ }
+
+ @Test
+ public void startStopFormatTest() throws Exception {
+ String payloadResult = "{\" AICIdentity \":\"aicIdentity1\"}";
+ Optional<String> payloadClient = PayloadClient.startStopFormat("aicIdentity1");
+ assertEquals(payloadResult, payloadClient.get());
+ }
+
+ @Test
+ public void healthCheckFormatTest() throws Exception {
+ String payloadResult = "{\"request-parameters\":{\"host-ip-address\":\"hostIpAddress1\"}}";
+ Optional<String> payloadClient = PayloadClient.healthCheckFormat("vnfName1", "hostIpAddress1");
+ assertEquals(payloadResult, payloadClient.get());
+ }
+
+ @Test
+ public void snapshotFormatTest() throws Exception {
+ String payloadResult = "{\"vm-id\":\"vmId1\",\"identity-url\":\"identityUrl1\"}";
+ Optional<String> payloadClient = PayloadClient.snapshotFormat("vmId1", "identityUrl1");
+ assertEquals(payloadResult, payloadClient.get());
+ }
- @Test
- public void resumeTrafficFormatTest() throws Exception {
- String payloadResult = "{\"configuration-parameters\":{\"vnf_name\":\"vnfName1\"}}";
- Optional<String> payloadClient = PayloadClient.resumeTrafficFormat("vnfName1");
- assertEquals(payloadResult, payloadClient.get());
- }
-
- @Test
- public void quiesceTrafficFormatTest() throws Exception {
- String payloadResult = "{\"configuration-parameters\":{\"vnf_name\":\"vnfName1\",\"operations_timeout\":\"operationTimeout\"}}";
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("operations_timeout", "operationTimeout");
- Optional<String> payload = Optional.of(jsonObject.toString());
- Optional<String> payloadClient = PayloadClient.quiesceTrafficFormat(payload, "vnfName1");
- assertEquals(payloadResult, payloadClient.get());
- }
-
- @Test
- public void startStopFormatTest() throws Exception {
- String payloadResult = "{\" AICIdentity \":\"aicIdentity1\"}";
- Optional<String> payloadClient = PayloadClient.startStopFormat("aicIdentity1");
- assertEquals(payloadResult, payloadClient.get());
- }
-
- @Test
- public void healthCheckFormatTest() throws Exception {
- String payloadResult = "{\"request-parameters\":{\"host-ip-address\":\"hostIpAddress1\"}}";
- Optional<String> payloadClient = PayloadClient.healthCheckFormat("vnfName1", "hostIpAddress1");
- assertEquals(payloadResult, payloadClient.get());
- }
-
- @Test
- public void snapshotFormatTest() throws Exception {
- String payloadResult = "{\"vm-id\":\"vmId1\",\"identity-url\":\"identityUrl1\"}";
- Optional<String> payloadClient = PayloadClient.snapshotFormat("vmId1", "identityUrl1");
- assertEquals(payloadResult, payloadClient.get());
- }
-
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/BeansTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/BeansTest.java
index 7949fd26e6..3f0d01d649 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/BeansTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/BeansTest.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.common;
import org.junit.Test;
import org.onap.so.openpojo.rules.ToStringTester;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterEnum;
@@ -38,37 +37,34 @@ import com.openpojo.validation.test.impl.SetterTester;
public class BeansTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
-
- private PojoClassFilter enumFilter = new FilterEnum();
-
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ private PojoClassFilter enumFilter = new FilterEnum();
+
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.bpmn.appc.payload.beans");
+ }
+
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule())
+
+ .with(new SetterTester()).with(new GetterTester())
+
+ .with(new SetterTester()).with(new GetterTester()).with(new ToStringTester())
+
+ .build();
+
- @Test
- public void pojoStructure() {
- test("org.onap.so.bpmn.appc.payload.beans");
- }
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, enumFilter,
+ new FilterNonConcrete());
+ }
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterMustExistRule())
-
- .with(new SetterTester())
- .with(new GetterTester())
-
- .with(new SetterTester())
- .with(new GetterTester())
- .with(new ToStringTester())
-
- .build();
-
-
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses,enumFilter,new FilterNonConcrete());
- }
- private static class FilterTestClasses implements PojoClassFilter {
- @Override
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private static class FilterTestClasses implements PojoClassFilter {
+ @Override
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DefaultToShortClassNameBeanNameGeneratorTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DefaultToShortClassNameBeanNameGeneratorTest.java
index 8a2c8fbfdd..d18170f828 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DefaultToShortClassNameBeanNameGeneratorTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DefaultToShortClassNameBeanNameGeneratorTest.java
@@ -23,9 +23,7 @@ package org.onap.so.bpmn.common;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.util.HashSet;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
@@ -37,29 +35,31 @@ import org.springframework.core.type.AnnotationMetadata;
public class DefaultToShortClassNameBeanNameGeneratorTest {
- @Mock
- private BeanDefinitionRegistry beanDefinitionRegistry;
-
- private DefaultToShortClassNameBeanNameGenerator customBeanNameGenerator = new DefaultToShortClassNameBeanNameGenerator();
-
- @Before
- public void before() {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void test_generateBeanName_notAnnotatedBeanDefinition() {
- String expectedBeanName = "BeanName";
-
- AnnotatedBeanDefinition annotatedBeanDefinition = mock(AnnotatedBeanDefinition.class);
- AnnotationMetadata metadata = mock(AnnotationMetadata.class);
- when(metadata.getAnnotationTypes()).thenReturn(new HashSet<String>());
- when(annotatedBeanDefinition.getBeanClassName()).thenReturn("org.onap.so.BeanName");
- when(annotatedBeanDefinition.getMetadata()).thenReturn(metadata);
- String actualBeanName = customBeanNameGenerator.generateBeanName(annotatedBeanDefinition, beanDefinitionRegistry);
-
- assertEquals(expectedBeanName, actualBeanName);
- }
-
+ @Mock
+ private BeanDefinitionRegistry beanDefinitionRegistry;
+
+ private DefaultToShortClassNameBeanNameGenerator customBeanNameGenerator =
+ new DefaultToShortClassNameBeanNameGenerator();
+
+ @Before
+ public void before() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void test_generateBeanName_notAnnotatedBeanDefinition() {
+ String expectedBeanName = "BeanName";
+
+ AnnotatedBeanDefinition annotatedBeanDefinition = mock(AnnotatedBeanDefinition.class);
+ AnnotationMetadata metadata = mock(AnnotationMetadata.class);
+ when(metadata.getAnnotationTypes()).thenReturn(new HashSet<String>());
+ when(annotatedBeanDefinition.getBeanClassName()).thenReturn("org.onap.so.BeanName");
+ when(annotatedBeanDefinition.getMetadata()).thenReturn(metadata);
+ String actualBeanName =
+ customBeanNameGenerator.generateBeanName(annotatedBeanDefinition, beanDefinitionRegistry);
+
+ assertEquals(expectedBeanName, actualBeanName);
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DelegateExecutionImplTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DelegateExecutionImplTest.java
index a30aadc1f8..44b6f35dae 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DelegateExecutionImplTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DelegateExecutionImplTest.java
@@ -25,13 +25,11 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
-
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
-
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Rule;
@@ -41,7 +39,6 @@ import org.onap.so.bpmn.common.exceptions.MalformedBuildingBlockInputException;
import org.onap.so.bpmn.common.exceptions.MissingBuildingBlockInputException;
import org.onap.so.bpmn.common.exceptions.RequiredExecutionVariableExeception;
import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MSOCommonApplication.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MSOCommonApplication.java
index 63e5ccbbf3..58ac7cacca 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MSOCommonApplication.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MSOCommonApplication.java
@@ -24,7 +24,6 @@ package org.onap.so.bpmn.common;
import java.util.List;
import java.util.concurrent.Executor;
-
import org.camunda.bpm.application.PostDeploy;
import org.camunda.bpm.application.PreUndeploy;
import org.camunda.bpm.application.ProcessApplicationInfo;
@@ -48,54 +47,52 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@SpringBootApplication
@EnableAsync
-@ComponentScan(basePackages = { "org.onap" }, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class, excludeFilters = {
- @Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
+@ComponentScan(basePackages = {"org.onap"}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class,
+ excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
public class MSOCommonApplication {
- private static final Logger logger = LoggerFactory.getLogger(MSOCommonApplication.class);
+ private static final Logger logger = LoggerFactory.getLogger(MSOCommonApplication.class);
- @Value("${mso.async.core-pool-size}")
- private int corePoolSize;
+ @Value("${mso.async.core-pool-size}")
+ private int corePoolSize;
- @Value("${mso.async.max-pool-size}")
- private int maxPoolSize;
+ @Value("${mso.async.max-pool-size}")
+ private int maxPoolSize;
- @Value("${mso.async.queue-capacity}")
- private int queueCapacity;
+ @Value("${mso.async.queue-capacity}")
+ private int queueCapacity;
- private static final String LOGS_DIR = "logs_dir";
+ private static final String LOGS_DIR = "logs_dir";
- private static void setLogsDir() {
- if (System.getProperty(LOGS_DIR) == null) {
- System.getProperties().setProperty(LOGS_DIR, "./logs/bpmn/");
- }
- }
+ private static void setLogsDir() {
+ if (System.getProperty(LOGS_DIR) == null) {
+ System.getProperties().setProperty(LOGS_DIR, "./logs/bpmn/");
+ }
+ }
- public static void main(String... args) {
- SpringApplication.run(MSOCommonApplication.class, args);
- System.getProperties().setProperty("mso.config.path", ".");
- setLogsDir();
- }
+ public static void main(String... args) {
+ SpringApplication.run(MSOCommonApplication.class, args);
+ System.getProperties().setProperty("mso.config.path", ".");
+ setLogsDir();
+ }
- @PostDeploy
- public void postDeploy(ProcessEngine processEngineInstance) {
- }
+ @PostDeploy
+ public void postDeploy(ProcessEngine processEngineInstance) {}
- @PreUndeploy
- public void cleanup(ProcessEngine processEngine, ProcessApplicationInfo processApplicationInfo,
- List<ProcessEngine> processEngines) {
- }
+ @PreUndeploy
+ public void cleanup(ProcessEngine processEngine, ProcessApplicationInfo processApplicationInfo,
+ List<ProcessEngine> processEngines) {}
- @Bean
- public Executor asyncExecutor() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+ @Bean
+ public Executor asyncExecutor() {
+ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setCorePoolSize(corePoolSize);
- executor.setMaxPoolSize(maxPoolSize);
- executor.setQueueCapacity(queueCapacity);
- executor.setThreadNamePrefix("Camunda-");
- executor.initialize();
- return executor;
- }
+ executor.setCorePoolSize(corePoolSize);
+ executor.setMaxPoolSize(maxPoolSize);
+ executor.setQueueCapacity(queueCapacity);
+ executor.setThreadNamePrefix("Camunda-");
+ executor.initialize();
+ return executor;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteGenericVnf.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteGenericVnf.java
index 052fd5dc94..45ef0add2b 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteGenericVnf.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteGenericVnf.java
@@ -23,18 +23,16 @@ package org.onap.so.bpmn.common;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.delete;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
-
import com.github.tomakehurst.wiremock.WireMockServer;
public class MockAAIDeleteGenericVnf {
- public MockAAIDeleteGenericVnf(WireMockServer wireMockServer){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/[?]resource-version=0000021"))
- .willReturn(aResponse()
- .withStatus(200)));
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/[?]resource-version=0000018"))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("aaiFault.xml")));
- }
+ public MockAAIDeleteGenericVnf(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/[?]resource-version=0000021"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/[?]resource-version=0000018"))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "text/xml")
+ .withBodyFile("aaiFault.xml")));
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteVfModule.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteVfModule.java
index 1cbe0b9244..f405fc943b 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteVfModule.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteVfModule.java
@@ -24,31 +24,30 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.delete;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
-
import com.github.tomakehurst.wiremock.WireMockServer;
public class MockAAIDeleteVfModule {
-
- public MockAAIDeleteVfModule(WireMockServer wireMockServer)
- {
- wireMockServer.stubFor(delete(urlMatching(
- "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73/[?]resource-version=0000073"))
- .willReturn(aResponse().withStatus(200)));
- wireMockServer.stubFor(delete(urlMatching(
- "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a75/[?]resource-version=0000075"))
- .willReturn(aResponse().withStatus(200)));
- wireMockServer.stubFor(delete(urlMatching(
- "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a78/[?]resource-version=0000078"))
- .willReturn(aResponse().withStatus(200)));
- wireMockServer.stubFor(delete(urlMatching(
- "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a77/[?]resource-version=0000077"))
- .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "text/xml")
- .withBodyFile("aaiFault.xml")));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*"))
- .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml")));
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*"))
- .willReturn(aResponse().withStatus(200)));
- }
+ public MockAAIDeleteVfModule(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73/[?]resource-version=0000073"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a75/[?]resource-version=0000075"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a78/[?]resource-version=0000078"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a77/[?]resource-version=0000077"))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "text/xml")
+ .withBodyFile("aaiFault.xml")));
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml")));
+
+ wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*"))
+ .willReturn(aResponse().withStatus(200)));
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIGenericVnfSearch.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIGenericVnfSearch.java
index 1d6337ffc4..a33268efbe 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIGenericVnfSearch.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockAAIGenericVnfSearch.java
@@ -23,319 +23,219 @@ package org.onap.so.bpmn.common;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
-
import com.github.tomakehurst.wiremock.WireMockServer;
public class MockAAIGenericVnfSearch {
-
- private static final String EOL = "\n";
- public MockAAIGenericVnfSearch(WireMockServer wireMockServer){
- String body;
-
- // The following stubs are for CreateAAIVfModule and UpdateAAIVfModule
-
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC23&depth=1"))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("aaiFault.xml")));
-
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC22&depth=1"))
- .willReturn(aResponse()
- .withStatus(404)
- .withHeader("Content-Type", "text/xml")
- .withBody("Generic VNF Not Found")));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/768073c7-f41f-4822-9323-b75962763d74[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(404)
- .withHeader("Content-Type", "text/xml")
- .withBody("Generic VNF Not Found")));
-
- body =
- "<generic-vnf xmlns=\"http://com.aai.inventory/v7\">" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>1508691</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>1508692</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC21&depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- body =
- "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL +
- " <vnf-id>2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>1508691</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>1508692</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>false</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>1508692</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC20&depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- // The following stubs are for DeleteAAIVfModule
-
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c723[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("aaiFault.xml")));
-
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c722[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(404)
- .withHeader("Content-Type", "text/xml")
- .withBody("Generic VNF Not Found")));
-
- body =
- "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>0000021</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000073</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- body =
- "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>0000020</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000074</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>false</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000075</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- body =
- "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c719</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC19</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>0000019</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC19-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000076</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC19-MMSC::module-1-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>false</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000077</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- body =
- "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c718</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC18</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>0000018</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC18-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000078</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- body =
- "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>0000021</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000073</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- }
+ private static final String EOL = "\n";
+
+ public MockAAIGenericVnfSearch(WireMockServer wireMockServer) {
+ String body;
+
+ // The following stubs are for CreateAAIVfModule and UpdateAAIVfModule
+
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC23&depth=1"))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "text/xml")
+ .withBodyFile("aaiFault.xml")));
+
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC22&depth=1"))
+ .willReturn(aResponse().withStatus(404).withHeader("Content-Type", "text/xml")
+ .withBody("Generic VNF Not Found")));
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/768073c7-f41f-4822-9323-b75962763d74[?]depth=1"))
+ .willReturn(aResponse().withStatus(404).withHeader("Content-Type", "text/xml")
+ .withBody("Generic VNF Not Found")));
+
+ body = "<generic-vnf xmlns=\"http://com.aai.inventory/v7\">" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>1508691</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>1508692</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC21&depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ body = "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL
+ + " <vnf-id>2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>1508691</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>1508692</resource-version>" + EOL + " </vf-module>" + EOL
+ + " <vf-module>" + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>"
+ + EOL + " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>false</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>1508692</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC20&depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ // The following stubs are for DeleteAAIVfModule
+
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c723[?]depth=1"))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "text/xml")
+ .withBodyFile("aaiFault.xml")));
+
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c722[?]depth=1"))
+ .willReturn(aResponse().withStatus(404).withHeader("Content-Type", "text/xml")
+ .withBody("Generic VNF Not Found")));
+
+ body = "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>0000021</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000073</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ body = "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>0000020</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000074</resource-version>" + EOL + " </vf-module>" + EOL
+ + " <vf-module>" + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</vf-module-id>"
+ + EOL + " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>false</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000075</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ body = "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c719</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC19</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>0000019</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC19-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000076</resource-version>" + EOL + " </vf-module>" + EOL
+ + " <vf-module>" + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</vf-module-id>"
+ + EOL + " <vf-module-name>STMTN5MMSC19-MMSC::module-1-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>false</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000077</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ body = "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c718</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC18</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>0000018</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC18-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000078</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ body = "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>0000021</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000073</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/SPIPropertiesTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/SPIPropertiesTest.java
index 9239889f28..96ea1cad9b 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/SPIPropertiesTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/SPIPropertiesTest.java
@@ -22,10 +22,8 @@ package org.onap.so.bpmn.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
-
import java.io.FileNotFoundException;
import java.io.IOException;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.so.client.RestPropertiesLoader;
@@ -36,34 +34,37 @@ import org.onap.so.client.sdno.dmaap.SDNOHealthCheckDmaapConsumer;
public class SPIPropertiesTest {
- @BeforeClass
- public static void beforeClass() {
- System.setProperty("mso.config.path", "src/test/resources");
- }
-
- @Test
- public void notEqual() {
- DmaapProperties one = DmaapPropertiesLoader.getInstance().getNewImpl();
- DmaapProperties two = DmaapPropertiesLoader.getInstance().getNewImpl();
- assertNotEquals(one, two);
- }
- @Test
- public void equal() {
- DmaapProperties one = DmaapPropertiesLoader.getInstance().getImpl();
- DmaapProperties two = DmaapPropertiesLoader.getInstance().getImpl();
- assertEquals(one, two);
- }
- @Test
- public void restNotEqual() {
- AAIProperties one = RestPropertiesLoader.getInstance().getNewImpl(AAIProperties.class);
- AAIProperties two = RestPropertiesLoader.getInstance().getNewImpl(AAIProperties.class);
- assertNotEquals(one, two);
- }
- @Test
- public void restEqual() {
- AAIProperties one = RestPropertiesLoader.getInstance().getImpl(AAIProperties.class);
- AAIProperties two = RestPropertiesLoader.getInstance().getImpl(AAIProperties.class);
- assertEquals(one, two);
- }
-
+ @BeforeClass
+ public static void beforeClass() {
+ System.setProperty("mso.config.path", "src/test/resources");
+ }
+
+ @Test
+ public void notEqual() {
+ DmaapProperties one = DmaapPropertiesLoader.getInstance().getNewImpl();
+ DmaapProperties two = DmaapPropertiesLoader.getInstance().getNewImpl();
+ assertNotEquals(one, two);
+ }
+
+ @Test
+ public void equal() {
+ DmaapProperties one = DmaapPropertiesLoader.getInstance().getImpl();
+ DmaapProperties two = DmaapPropertiesLoader.getInstance().getImpl();
+ assertEquals(one, two);
+ }
+
+ @Test
+ public void restNotEqual() {
+ AAIProperties one = RestPropertiesLoader.getInstance().getNewImpl(AAIProperties.class);
+ AAIProperties two = RestPropertiesLoader.getInstance().getNewImpl(AAIProperties.class);
+ assertNotEquals(one, two);
+ }
+
+ @Test
+ public void restEqual() {
+ AAIProperties one = RestPropertiesLoader.getInstance().getImpl(AAIProperties.class);
+ AAIProperties two = RestPropertiesLoader.getInstance().getImpl(AAIProperties.class);
+ assertEquals(one, two);
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/WorkflowContextHolderTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/WorkflowContextHolderTest.java
index 4a51d34c3e..23f9818669 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/WorkflowContextHolderTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/WorkflowContextHolderTest.java
@@ -16,7 +16,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
@@ -34,35 +34,35 @@ import org.onap.so.bpmn.common.workflow.context.WorkflowResponse;
public class WorkflowContextHolderTest {
- @Test
- public void testProcessCallback() throws Exception {
- String requestId = UUID.randomUUID().toString();
- String message = "TEST MESSATGE";
- String responseMessage = "Successfully processed request";
- int testCode = 200;
-
-
- WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();
-
- WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
- callbackResponse.setMessage(message);
- callbackResponse.setResponse(responseMessage);
- callbackResponse.setStatusCode(testCode);
-
- contextHolder.processCallback("testAsyncProcess","process-instance-id",requestId,callbackResponse);
-
- //same object returned
- WorkflowContext contextFound = contextHolder.getWorkflowContext(requestId);
- if(contextFound == null)
- throw new Exception("Expected to find Context Object");
-
- WorkflowResponse testResponse = contextFound.getWorkflowResponse();
- Assert.assertEquals(200,testResponse.getMessageCode());
- Assert.assertEquals(message, testResponse.getMessage());
- Assert.assertEquals(responseMessage, testResponse.getResponse());
-
-
-
- }
+ @Test
+ public void testProcessCallback() throws Exception {
+ String requestId = UUID.randomUUID().toString();
+ String message = "TEST MESSATGE";
+ String responseMessage = "Successfully processed request";
+ int testCode = 200;
+
+
+ WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();
+
+ WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
+ callbackResponse.setMessage(message);
+ callbackResponse.setResponse(responseMessage);
+ callbackResponse.setStatusCode(testCode);
+
+ contextHolder.processCallback("testAsyncProcess", "process-instance-id", requestId, callbackResponse);
+
+ // same object returned
+ WorkflowContext contextFound = contextHolder.getWorkflowContext(requestId);
+ if (contextFound == null)
+ throw new Exception("Expected to find Context Object");
+
+ WorkflowResponse testResponse = contextFound.getWorkflowResponse();
+ Assert.assertEquals(200, testResponse.getMessageCode());
+ Assert.assertEquals(message, testResponse.getMessage());
+ Assert.assertEquals(responseMessage, testResponse.getResponse());
+
+
+
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/WorkflowTestTransformer.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/WorkflowTestTransformer.java
index dbad35a6a4..794e772dcd 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/WorkflowTestTransformer.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/WorkflowTestTransformer.java
@@ -26,16 +26,15 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
- * Allows a subclass of WorkflowTest to specify one or more WireMock
- * response transformers. A transformer must be declared as a public
- * static field in the subclass. For example:
+ * Allows a subclass of WorkflowTest to specify one or more WireMock response transformers. A transformer must be
+ * declared as a public static field in the subclass. For example:
+ *
* <pre>
- * @WorkflowTestTransformer
- * public static final ResponseTransformer sdncAdapterMockTransformer =
- * new SDNCAdapterMockTransformer();
+ * &#64;WorkflowTestTransformer
+ * public static final ResponseTransformer sdncAdapterMockTransformer = new SDNCAdapterMockTransformer();
* </pre>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface WorkflowTestTransformer {
-} \ No newline at end of file
+}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/baseclient/BaseClientTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/baseclient/BaseClientTest.java
index 1be7c652b9..ee2c10ca4b 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/baseclient/BaseClientTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/baseclient/BaseClientTest.java
@@ -25,41 +25,39 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
-
import java.util.Map;
-
import javax.ws.rs.core.UriBuilder;
-
import org.junit.Test;
import org.onap.so.BaseTest;
import org.springframework.core.ParameterizedTypeReference;
-
import wiremock.org.apache.http.entity.ContentType;
public class BaseClientTest extends BaseTest {
- @Test
- public void verifyString() {
- BaseClient<String, String> client = new BaseClient<>();
- String response = "{\"hello\" : \"world\"}";
- client.setTargetUrl(UriBuilder.fromUri("http://localhost/test").port(Integer.parseInt(wireMockPort)).build().toString());
- wireMockServer.stubFor(get(urlEqualTo("/test"))
- .willReturn(aResponse().withStatus(200).withBody(response).withHeader("Content-Type", ContentType.APPLICATION_JSON.toString())));
-
- String result = client.get("", new ParameterizedTypeReference<String>() {});
- assertThat(result, equalTo(response));
- }
-
- @Test
- public void verifyMap() {
- BaseClient<String, Map<String, Object>> client = new BaseClient<>();
- String response = "{\"hello\" : \"world\"}";
- client.setTargetUrl(UriBuilder.fromUri("http://localhost/test").port(Integer.parseInt(wireMockPort)).build().toString());
- wireMockServer.stubFor(get(urlEqualTo("/test"))
- .willReturn(aResponse().withStatus(200).withBody(response).withHeader("Content-Type", ContentType.APPLICATION_JSON.toString())));
-
- Map<String, Object> result = client.get("", new ParameterizedTypeReference<Map<String, Object>>() {});
- assertThat("world", equalTo(result.get("hello")));
- }
+ @Test
+ public void verifyString() {
+ BaseClient<String, String> client = new BaseClient<>();
+ String response = "{\"hello\" : \"world\"}";
+ client.setTargetUrl(
+ UriBuilder.fromUri("http://localhost/test").port(Integer.parseInt(wireMockPort)).build().toString());
+ wireMockServer.stubFor(get(urlEqualTo("/test")).willReturn(aResponse().withStatus(200).withBody(response)
+ .withHeader("Content-Type", ContentType.APPLICATION_JSON.toString())));
+
+ String result = client.get("", new ParameterizedTypeReference<String>() {});
+ assertThat(result, equalTo(response));
+ }
+
+ @Test
+ public void verifyMap() {
+ BaseClient<String, Map<String, Object>> client = new BaseClient<>();
+ String response = "{\"hello\" : \"world\"}";
+ client.setTargetUrl(
+ UriBuilder.fromUri("http://localhost/test").port(Integer.parseInt(wireMockPort)).build().toString());
+ wireMockServer.stubFor(get(urlEqualTo("/test")).willReturn(aResponse().withStatus(200).withBody(response)
+ .withHeader("Content-Type", ContentType.APPLICATION_JSON.toString())));
+
+ Map<String, Object> result = client.get("", new ParameterizedTypeReference<Map<String, Object>>() {});
+ assertThat("world", equalTo(result.get("hello")));
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnParamTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnParamTest.java
index 5510e21b31..94320b75d7 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnParamTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnParamTest.java
@@ -1,41 +1,36 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.common.recipe;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
public class BpmnParamTest {
- BpmnParam bp=new BpmnParam();
-
- @Test
- public void test() {
- bp.setValue("testdata");
- assertEquals(bp.getValue(),"testdata");
- }
- @Test
- public void testToString(){
- assert(bp.toString()!=null);
- }
+ BpmnParam bp = new BpmnParam();
+
+ @Test
+ public void test() {
+ bp.setValue("testdata");
+ assertEquals(bp.getValue(), "testdata");
+ }
+
+ @Test
+ public void testToString() {
+ assert (bp.toString() != null);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnRestClientTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnRestClientTest.java
index 465ec416b5..730915a60c 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnRestClientTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnRestClientTest.java
@@ -25,36 +25,29 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.io.IOException;
-
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.junit.Test;
import org.onap.so.BaseTest;
import org.springframework.beans.factory.annotation.Autowired;
-public class BpmnRestClientTest extends BaseTest{
+public class BpmnRestClientTest extends BaseTest {
@Autowired
private BpmnRestClient bpmnRestClient;
@Test
- public void postTest() throws IOException, Exception{
+ public void postTest() throws IOException, Exception {
wireMockServer.stubFor(post(urlPathMatching("/testRecipeUri"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(org.springframework.http.HttpStatus.OK.value()).withBody("{}")));
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(org.springframework.http.HttpStatus.OK.value()).withBody("{}")));
- HttpResponse httpResponse = bpmnRestClient.post(
- "http://localhost:" + wireMockPort +"/testRecipeUri",
- "test-req-id",
- 1000,
- "testRequestAction",
- "1234",
- "testServiceType",
- "testRequestDetails",
- "testRecipeparamXsd");
+ HttpResponse httpResponse =
+ bpmnRestClient.post("http://localhost:" + wireMockPort + "/testRecipeUri", "test-req-id", 1000,
+ "testRequestAction", "1234", "testServiceType", "testRequestDetails", "testRecipeparamXsd");
assertNotNull(httpResponse);
- assertEquals(HttpStatus.SC_OK,httpResponse.getStatusLine().getStatusCode());
+ assertEquals(HttpStatus.SC_OK, httpResponse.getStatusLine().getStatusCode());
}
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/ResourceInputTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/ResourceInputTest.java
index 5da47c973e..d25e4437ce 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/ResourceInputTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/ResourceInputTest.java
@@ -1,66 +1,62 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.common.recipe;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.bpmn.core.domain.ModelInfo;
import org.onap.so.BaseTest;
-public class ResourceInputTest extends BaseTest{
-
- ResourceInput ri=new ResourceInput();
- @Test
- public void test() {
- ri.setResourceInstanceName("resourceInstanceName");
- ri.setResourceInstanceDes("resourceInstanceDes");
- ri.setGlobalSubscriberId("globalSubscriberId");
- ri.setServiceType("serviceType");
- ri.setServiceInstanceId("serviceId");
- ri.setOperationId("operationId");
- ModelInfo serviceModelInfo = new ModelInfo();
- serviceModelInfo.setModelCustomizationUuid("modelCustomizationUuid");
- serviceModelInfo.setModelInvariantUuid("modelInvariantUuid");
- serviceModelInfo.setModelUuid("modelUuid");
- ri.setServiceModelInfo(serviceModelInfo);
+public class ResourceInputTest extends BaseTest {
+
+ ResourceInput ri = new ResourceInput();
+
+ @Test
+ public void test() {
+ ri.setResourceInstanceName("resourceInstanceName");
+ ri.setResourceInstanceDes("resourceInstanceDes");
+ ri.setGlobalSubscriberId("globalSubscriberId");
+ ri.setServiceType("serviceType");
+ ri.setServiceInstanceId("serviceId");
+ ri.setOperationId("operationId");
+ ModelInfo serviceModelInfo = new ModelInfo();
+ serviceModelInfo.setModelCustomizationUuid("modelCustomizationUuid");
+ serviceModelInfo.setModelInvariantUuid("modelInvariantUuid");
+ serviceModelInfo.setModelUuid("modelUuid");
+ ri.setServiceModelInfo(serviceModelInfo);
ModelInfo resourceModelInfo = new ModelInfo();
resourceModelInfo.setModelCustomizationUuid("modelCustomizationUuid");
resourceModelInfo.setModelInvariantUuid("modelInvariantUuid");
resourceModelInfo.setModelUuid("modelUuid");
ri.setResourceModelInfo(resourceModelInfo);
- ri.setResourceInstancenUuid("resourceInstancenUuid");
- ri.setResourceParameters("resourceParameters");
- ri.setOperationType("operationType");
- assertEquals(ri.getResourceInstanceName(), "resourceInstanceName");
- assertEquals(ri.getResourceInstanceDes(), "resourceInstanceDes");
- assertEquals(ri.getGlobalSubscriberId(), "globalSubscriberId");
- assertEquals(ri.getServiceType(), "serviceType");
- assertEquals(ri.getServiceInstanceId(), "serviceId");
- assertEquals(ri.getOperationId(), "operationId");
- assertEquals(ri.getResourceInstancenUuid(), "resourceInstancenUuid");
- assertEquals(ri.getResourceParameters(), "resourceParameters");
- assertEquals(ri.getOperationType(), "operationType");
- }
- @Test
- public void testToString(){
- assert(ri.toString()!=null);
- }
+ ri.setResourceInstancenUuid("resourceInstancenUuid");
+ ri.setResourceParameters("resourceParameters");
+ ri.setOperationType("operationType");
+ assertEquals(ri.getResourceInstanceName(), "resourceInstanceName");
+ assertEquals(ri.getResourceInstanceDes(), "resourceInstanceDes");
+ assertEquals(ri.getGlobalSubscriberId(), "globalSubscriberId");
+ assertEquals(ri.getServiceType(), "serviceType");
+ assertEquals(ri.getServiceInstanceId(), "serviceId");
+ assertEquals(ri.getOperationId(), "operationId");
+ assertEquals(ri.getResourceInstancenUuid(), "resourceInstancenUuid");
+ assertEquals(ri.getResourceParameters(), "resourceParameters");
+ assertEquals(ri.getOperationType(), "operationType");
+ }
+
+ @Test
+ public void testToString() {
+ assert (ri.toString() != null);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/ResourceRecipeRequestTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/ResourceRecipeRequestTest.java
index f0f6fa79e0..7008791dd0 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/ResourceRecipeRequestTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/ResourceRecipeRequestTest.java
@@ -1,52 +1,48 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.common.recipe;
import static org.junit.Assert.*;
-
import org.junit.Test;
import org.onap.so.BaseTest;
-public class ResourceRecipeRequestTest extends BaseTest{
+public class ResourceRecipeRequestTest extends BaseTest {
+
+ ResourceRecipeRequest rr = new ResourceRecipeRequest();
+ BpmnParam bp = new BpmnParam();
+
+ @Test
+ public void test() {
+ rr.setResourceInput(bp);
+ rr.setHost(bp);
+ rr.setRequestId(bp);
+ rr.setRequestAction(bp);
+ rr.setServiceInstanceId(bp);
+ rr.setServiceType(bp);
+ rr.setRecipeParams(bp);
+ assertEquals(rr.getResourceInput(), bp);
+ assertEquals(rr.getHost(), bp);
+ assertEquals(rr.getRequestId(), bp);
+ assertEquals(rr.getRequestAction(), bp);
+ assertEquals(rr.getServiceInstanceId(), bp);
+ assertEquals(rr.getServiceType(), bp);
+ assertEquals(rr.getRecipeParams(), bp);
+ }
- ResourceRecipeRequest rr=new ResourceRecipeRequest();
- BpmnParam bp=new BpmnParam();
- @Test
- public void test() {
- rr.setResourceInput(bp);
- rr.setHost(bp);
- rr.setRequestId(bp);
- rr.setRequestAction(bp);
- rr.setServiceInstanceId(bp);
- rr.setServiceType(bp);
- rr.setRecipeParams(bp);
- assertEquals(rr.getResourceInput(),bp);
- assertEquals(rr.getHost(),bp);
- assertEquals(rr.getRequestId(),bp);
- assertEquals(rr.getRequestAction(),bp);
- assertEquals(rr.getServiceInstanceId(),bp);
- assertEquals(rr.getServiceType(),bp);
- assertEquals(rr.getRecipeParams(),bp);
- }
- @Test
- public void testToString(){
- assert(rr.toString()!=null);
- }
+ @Test
+ public void testToString() {
+ assert (rr.toString() != null);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilderTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilderTest.java
index a074174f6e..0c2862bf91 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilderTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilderTest.java
@@ -23,11 +23,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.ok;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.junit.Assert.assertEquals;
-
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.junit.Test;
import org.onap.so.BaseTest;
@@ -39,362 +37,283 @@ public class ResourceRequestBuilderTest extends BaseTest {
- wireMockServer.stubFor(get(urlEqualTo("/ecomp/mso/catalog/v2/serviceResources?serviceModelUuid=c3954379-4efe-431c-8258-f84905b158e5"))
- .willReturn(ok("{ \"serviceResources\" : {\n" +
- "\t\"modelInfo\" : {\n" +
- "\t\t\"modelName\" : \"demoVFWCL\",\n" +
- "\t\t\"modelUuid\" : \"c3954379-4efe-431c-8258-f84905b158e5\",\n" +
- "\t\t\"modelInvariantUuid\" : \"0cbff61e-3b0a-4eed-97ce-b1b4faa03493\",\n" +
- "\t\t\"modelVersion\" : \"1.0\"\n" +
- "\t},\n" +
- "\t\"serviceType\" : \"\",\n" +
- "\t\"serviceRole\" : \"\",\n" +
- "\t\"environmentContext\" : null,\n" +
- "\t\"resourceOrder\" : \"res1,res2\",\n" +
- "\t\"workloadContext\" : \"Production\",\n" +
- "\t\"serviceVnfs\": [\n" +
- "\t\n" +
- "\t\t{ \"modelInfo\" : {\n" +
- "\t\t\t\"modelName\" : \"15968a6e-2fe5-41bf-a481\",\n" +
- "\t\t\t\"modelUuid\" : \"808abda3-2023-4105-92d2-e62644b61d53\",\n" +
- "\t\t\t\"modelInvariantUuid\" : \"6e4ffc7c-497e-4a77-970d-af966e642d31\",\n" +
- "\t\t\t\"modelVersion\" : \"1.0\",\n" +
- "\t\t\t\"modelCustomizationUuid\" : \"a00404d5-d7eb-4c46-b6b6-9cf2d087e545\",\n" +
- "\t\t\t\"modelInstanceName\" : \"15968a6e-2fe5-41bf-a481 0\"\n" +
- "\t\t\t},\n" +
- "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.15968a6e2fe541bfA481\",\n" +
- "\t\t\"nfFunction\" \t: null,\n" +
- "\"resourceInput\":\"{\\\"a\\\":\\\"b\\\"}\"," +
- "\t\t\"nfType\" \t\t: null,\n" +
- "\t\t\"nfRole\" \t\t: null,\n" +
- "\t\t\"nfNamingCode\" \t: null,\n" +
- "\t\t\"multiStageDesign\" : \"false\",\n" +
- "\t\t\t\"vfModules\": [\n" +
- "\t\t\t\t{\n" +
- "\t\t\t\t\t\"modelInfo\" : { \n" +
- "\t\t\t\t\t\t\"modelName\" : \"15968a6e2fe541bfA481..base_vfw..module-0\",\n" +
- "\t\t\t\t\t\t\"modelUuid\" : \"ec7fadde-1e5a-42f7-8255-cb19e475ff45\",\n" +
- "\t\t\t\t\t\t\"modelInvariantUuid\" : \"61ab8b64-a014-4cf3-8a5a-b5ef388f8819\",\n" +
- "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n" +
- "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"123aff6b-854f-4026-ae1e-cc74a3924576\"\n" +
- "\t\t\t\t\t},\t\t\"isBase\" : true,\n" +
- "\t\t\t\t\t\"vfModuleLabel\" : \"base_vfw\",\n" +
- "\t\t\t\t\t\"initialCount\" : 1,\n" +
- "\t\t\t\t\t\"hasVolumeGroup\" : true\n" +
- "\t\t\t\t}\n" +
- "\t\t\t]\n" +
- "\t\t},\n" +
- "\t\n" +
- "\t\t{ \"modelInfo\" : {\n" +
- "\t\t\t\"modelName\" : \"f971106a-248f-4202-9d1f\",\n" +
- "\t\t\t\"modelUuid\" : \"4fbc08a4-35ed-4a59-9e47-79975e4add7e\",\n" +
- "\t\t\t\"modelInvariantUuid\" : \"c669799e-adf1-46ae-8c70-48b326fe89f3\",\n" +
- "\t\t\t\"modelVersion\" : \"1.0\",\n" +
- "\t\t\t\"modelCustomizationUuid\" : \"e776449e-2b10-45c5-9217-2775c88ca1a0\",\n" +
- "\t\t\t\"modelInstanceName\" : \"f971106a-248f-4202-9d1f 0\"\n" +
- "\t\t\t},\n" +
- "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.F971106a248f42029d1f\",\n" +
- "\t\t\"nfFunction\" \t: null,\n" +
- "\t\t\"nfType\" \t\t: null,\n" +
- "\t\t\"nfRole\" \t\t: null,\n" +
- "\"resourceInput\":\"{\\\"a\\\":\\\"key|default_value\\\"}\"," +
- "\t\t\"nfNamingCode\" \t: null,\n" +
- "\t\t\"multiStageDesign\" : \"false\",\n" +
- "\t\t\t\"vfModules\": [\n" +
- "\t\t\t\t{\n" +
- "\t\t\t\t\t\"modelInfo\" : { \n" +
- "\t\t\t\t\t\t\"modelName\" : \"F971106a248f42029d1f..base_vpkg..module-0\",\n" +
- "\t\t\t\t\t\t\"modelUuid\" : \"47d5273a-7456-4786-9035-b3911944cc35\",\n" +
- "\t\t\t\t\t\t\"modelInvariantUuid\" : \"0ea3e57e-ac7a-425a-928b-b4aee8806c15\",\n" +
- "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n" +
- "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"9ed9fef6-d3f8-4433-9807-7e23393a16bc\"\n" +
- "\t\t\t\t\t},\t\t\"isBase\" : true,\n" +
- "\t\t\t\t\t\"vfModuleLabel\" : \"base_vpkg\",\n" +
- "\t\t\t\t\t\"initialCount\" : 1,\n" +
- "\t\t\t\t\t\"hasVolumeGroup\" : true\n" +
- "\t\t\t\t}\n" +
- "\t\t\t]\n" +
- "\t\t}\n" +
- "\t],\n" +
- "\t\"serviceNetworks\": [],\n" +
- "\t\"serviceAllottedResources\": []\n" +
- "\t}}")));
+ wireMockServer.stubFor(get(urlEqualTo(
+ "/ecomp/mso/catalog/v2/serviceResources?serviceModelUuid=c3954379-4efe-431c-8258-f84905b158e5"))
+ .willReturn(ok("{ \"serviceResources\" : {\n" + "\t\"modelInfo\" : {\n"
+ + "\t\t\"modelName\" : \"demoVFWCL\",\n"
+ + "\t\t\"modelUuid\" : \"c3954379-4efe-431c-8258-f84905b158e5\",\n"
+ + "\t\t\"modelInvariantUuid\" : \"0cbff61e-3b0a-4eed-97ce-b1b4faa03493\",\n"
+ + "\t\t\"modelVersion\" : \"1.0\"\n" + "\t},\n"
+ + "\t\"serviceType\" : \"\",\n" + "\t\"serviceRole\" : \"\",\n"
+ + "\t\"environmentContext\" : null,\n" + "\t\"resourceOrder\" : \"res1,res2\",\n"
+ + "\t\"workloadContext\" : \"Production\",\n" + "\t\"serviceVnfs\": [\n" + "\t\n"
+ + "\t\t{ \"modelInfo\" : {\n"
+ + "\t\t\t\"modelName\" : \"15968a6e-2fe5-41bf-a481\",\n"
+ + "\t\t\t\"modelUuid\" : \"808abda3-2023-4105-92d2-e62644b61d53\",\n"
+ + "\t\t\t\"modelInvariantUuid\" : \"6e4ffc7c-497e-4a77-970d-af966e642d31\",\n"
+ + "\t\t\t\"modelVersion\" : \"1.0\",\n"
+ + "\t\t\t\"modelCustomizationUuid\" : \"a00404d5-d7eb-4c46-b6b6-9cf2d087e545\",\n"
+ + "\t\t\t\"modelInstanceName\" : \"15968a6e-2fe5-41bf-a481 0\"\n" + "\t\t\t},\n"
+ + "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.15968a6e2fe541bfA481\",\n"
+ + "\t\t\"nfFunction\" \t: null,\n"
+ + "\"resourceInput\":\"{\\\"a\\\":\\\"b\\\"}\","
+ + "\t\t\"nfType\" \t\t: null,\n"
+ + "\t\t\"nfRole\" \t\t: null,\n"
+ + "\t\t\"nfNamingCode\" \t: null,\n"
+ + "\t\t\"multiStageDesign\" : \"false\",\n" + "\t\t\t\"vfModules\": [\n"
+ + "\t\t\t\t{\n" + "\t\t\t\t\t\"modelInfo\" : { \n"
+ + "\t\t\t\t\t\t\"modelName\" : \"15968a6e2fe541bfA481..base_vfw..module-0\",\n"
+ + "\t\t\t\t\t\t\"modelUuid\" : \"ec7fadde-1e5a-42f7-8255-cb19e475ff45\",\n"
+ + "\t\t\t\t\t\t\"modelInvariantUuid\" : \"61ab8b64-a014-4cf3-8a5a-b5ef388f8819\",\n"
+ + "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n"
+ + "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"123aff6b-854f-4026-ae1e-cc74a3924576\"\n"
+ + "\t\t\t\t\t},\t\t\"isBase\" : true,\n"
+ + "\t\t\t\t\t\"vfModuleLabel\" : \"base_vfw\",\n"
+ + "\t\t\t\t\t\"initialCount\" : 1,\n"
+ + "\t\t\t\t\t\"hasVolumeGroup\" : true\n" + "\t\t\t\t}\n" + "\t\t\t]\n"
+ + "\t\t},\n" + "\t\n" + "\t\t{ \"modelInfo\" : {\n"
+ + "\t\t\t\"modelName\" : \"f971106a-248f-4202-9d1f\",\n"
+ + "\t\t\t\"modelUuid\" : \"4fbc08a4-35ed-4a59-9e47-79975e4add7e\",\n"
+ + "\t\t\t\"modelInvariantUuid\" : \"c669799e-adf1-46ae-8c70-48b326fe89f3\",\n"
+ + "\t\t\t\"modelVersion\" : \"1.0\",\n"
+ + "\t\t\t\"modelCustomizationUuid\" : \"e776449e-2b10-45c5-9217-2775c88ca1a0\",\n"
+ + "\t\t\t\"modelInstanceName\" : \"f971106a-248f-4202-9d1f 0\"\n" + "\t\t\t},\n"
+ + "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.F971106a248f42029d1f\",\n"
+ + "\t\t\"nfFunction\" \t: null,\n"
+ + "\t\t\"nfType\" \t\t: null,\n"
+ + "\t\t\"nfRole\" \t\t: null,\n"
+ + "\"resourceInput\":\"{\\\"a\\\":\\\"key|default_value\\\"}\","
+ + "\t\t\"nfNamingCode\" \t: null,\n"
+ + "\t\t\"multiStageDesign\" : \"false\",\n" + "\t\t\t\"vfModules\": [\n"
+ + "\t\t\t\t{\n" + "\t\t\t\t\t\"modelInfo\" : { \n"
+ + "\t\t\t\t\t\t\"modelName\" : \"F971106a248f42029d1f..base_vpkg..module-0\",\n"
+ + "\t\t\t\t\t\t\"modelUuid\" : \"47d5273a-7456-4786-9035-b3911944cc35\",\n"
+ + "\t\t\t\t\t\t\"modelInvariantUuid\" : \"0ea3e57e-ac7a-425a-928b-b4aee8806c15\",\n"
+ + "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n"
+ + "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"9ed9fef6-d3f8-4433-9807-7e23393a16bc\"\n"
+ + "\t\t\t\t\t},\t\t\"isBase\" : true,\n"
+ + "\t\t\t\t\t\"vfModuleLabel\" : \"base_vpkg\",\n"
+ + "\t\t\t\t\t\"initialCount\" : 1,\n"
+ + "\t\t\t\t\t\"hasVolumeGroup\" : true\n" + "\t\t\t\t}\n" + "\t\t\t]\n"
+ + "\t\t}\n" + "\t],\n" + "\t\"serviceNetworks\": [],\n"
+ + "\t\"serviceAllottedResources\": []\n" + "\t}}")));
-// when(UrnPropertiesReader.getVariable(anyString())).thenReturn("http://localhost:8080");
+ // when(UrnPropertiesReader.getVariable(anyString())).thenReturn("http://localhost:8080");
HashMap serviceInput = new HashMap();
serviceInput.put("key", "value");
- Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest("c3954379-4efe-431c-8258-f84905b158e5",
- "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput);
+ Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest(
+ "c3954379-4efe-431c-8258-f84905b158e5", "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput);
assertEquals(stringObjectMap.get("a"), "value");
}
@Test
public void getResourceInputDefaultValueTest() throws Exception {
- wireMockServer.stubFor(get(urlEqualTo("/ecomp/mso/catalog/v2/serviceResources?serviceModelUuid=c3954379-4efe-431c-8258-f84905b158e5"))
- .willReturn(ok("{ \"serviceResources\" : {\n" +
- "\t\"modelInfo\" : {\n" +
- "\t\t\"modelName\" : \"demoVFWCL\",\n" +
- "\t\t\"modelUuid\" : \"c3954379-4efe-431c-8258-f84905b158e5\",\n" +
- "\t\t\"modelInvariantUuid\" : \"0cbff61e-3b0a-4eed-97ce-b1b4faa03493\",\n" +
- "\t\t\"modelVersion\" : \"1.0\"\n" +
- "\t},\n" +
- "\t\"serviceType\" : \"\",\n" +
- "\t\"serviceRole\" : \"\",\n" +
- "\t\"environmentContext\" : null,\n" +
- "\t\"workloadContext\" : \"Production\",\n" +
- "\t\"serviceVnfs\": [\n" +
- "\t\n" +
- "\t\t{ \"modelInfo\" : {\n" +
- "\t\t\t\"modelName\" : \"15968a6e-2fe5-41bf-a481\",\n" +
- "\t\t\t\"modelUuid\" : \"808abda3-2023-4105-92d2-e62644b61d53\",\n" +
- "\t\t\t\"modelInvariantUuid\" : \"6e4ffc7c-497e-4a77-970d-af966e642d31\",\n" +
- "\t\t\t\"modelVersion\" : \"1.0\",\n" +
- "\t\t\t\"modelCustomizationUuid\" : \"a00404d5-d7eb-4c46-b6b6-9cf2d087e545\",\n" +
- "\t\t\t\"modelInstanceName\" : \"15968a6e-2fe5-41bf-a481 0\"\n" +
- "\t\t\t},\n" +
- "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.15968a6e2fe541bfA481\",\n" +
- "\t\t\"nfFunction\" \t: null,\n" +
- "\"resourceInput\":\"{\\\"a\\\":\\\"b\\\"}\"," +
- "\t\t\"nfType\" \t\t: null,\n" +
- "\t\t\"nfRole\" \t\t: null,\n" +
- "\t\t\"nfNamingCode\" \t: null,\n" +
- "\t\t\"multiStageDesign\" : \"false\",\n" +
- "\t\t\t\"vfModules\": [\n" +
- "\t\t\t\t{\n" +
- "\t\t\t\t\t\"modelInfo\" : { \n" +
- "\t\t\t\t\t\t\"modelName\" : \"15968a6e2fe541bfA481..base_vfw..module-0\",\n" +
- "\t\t\t\t\t\t\"modelUuid\" : \"ec7fadde-1e5a-42f7-8255-cb19e475ff45\",\n" +
- "\t\t\t\t\t\t\"modelInvariantUuid\" : \"61ab8b64-a014-4cf3-8a5a-b5ef388f8819\",\n" +
- "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n" +
- "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"123aff6b-854f-4026-ae1e-cc74a3924576\"\n" +
- "\t\t\t\t\t},\t\t\"isBase\" : true,\n" +
- "\t\t\t\t\t\"vfModuleLabel\" : \"base_vfw\",\n" +
- "\t\t\t\t\t\"initialCount\" : 1,\n" +
- "\t\t\t\t\t\"hasVolumeGroup\" : true\n" +
- "\t\t\t\t}\n" +
- "\t\t\t]\n" +
- "\t\t},\n" +
- "\t\n" +
- "\t\t{ \"modelInfo\" : {\n" +
- "\t\t\t\"modelName\" : \"f971106a-248f-4202-9d1f\",\n" +
- "\t\t\t\"modelUuid\" : \"4fbc08a4-35ed-4a59-9e47-79975e4add7e\",\n" +
- "\t\t\t\"modelInvariantUuid\" : \"c669799e-adf1-46ae-8c70-48b326fe89f3\",\n" +
- "\t\t\t\"modelVersion\" : \"1.0\",\n" +
- "\t\t\t\"modelCustomizationUuid\" : \"e776449e-2b10-45c5-9217-2775c88ca1a0\",\n" +
- "\t\t\t\"modelInstanceName\" : \"f971106a-248f-4202-9d1f 0\"\n" +
- "\t\t\t},\n" +
- "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.F971106a248f42029d1f\",\n" +
- "\t\t\"nfFunction\" \t: null,\n" +
- "\t\t\"nfType\" \t\t: null,\n" +
- "\t\t\"nfRole\" \t\t: null,\n" +
- "\"resourceInput\":\"{\\\"a\\\":\\\"key|default_value\\\"}\"," +
- "\t\t\"nfNamingCode\" \t: null,\n" +
- "\t\t\"multiStageDesign\" : \"false\",\n" +
- "\t\t\t\"vfModules\": [\n" +
- "\t\t\t\t{\n" +
- "\t\t\t\t\t\"modelInfo\" : { \n" +
- "\t\t\t\t\t\t\"modelName\" : \"F971106a248f42029d1f..base_vpkg..module-0\",\n" +
- "\t\t\t\t\t\t\"modelUuid\" : \"47d5273a-7456-4786-9035-b3911944cc35\",\n" +
- "\t\t\t\t\t\t\"modelInvariantUuid\" : \"0ea3e57e-ac7a-425a-928b-b4aee8806c15\",\n" +
- "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n" +
- "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"9ed9fef6-d3f8-4433-9807-7e23393a16bc\"\n" +
- "\t\t\t\t\t},\t\t\"isBase\" : true,\n" +
- "\t\t\t\t\t\"vfModuleLabel\" : \"base_vpkg\",\n" +
- "\t\t\t\t\t\"initialCount\" : 1,\n" +
- "\t\t\t\t\t\"hasVolumeGroup\" : true\n" +
- "\t\t\t\t}\n" +
- "\t\t\t]\n" +
- "\t\t}\n" +
- "\t],\n" +
- "\t\"serviceNetworks\": [],\n" +
- "\t\"serviceAllottedResources\": []\n" +
- "\t}}")));
+ wireMockServer.stubFor(get(urlEqualTo(
+ "/ecomp/mso/catalog/v2/serviceResources?serviceModelUuid=c3954379-4efe-431c-8258-f84905b158e5"))
+ .willReturn(ok("{ \"serviceResources\" : {\n" + "\t\"modelInfo\" : {\n"
+ + "\t\t\"modelName\" : \"demoVFWCL\",\n"
+ + "\t\t\"modelUuid\" : \"c3954379-4efe-431c-8258-f84905b158e5\",\n"
+ + "\t\t\"modelInvariantUuid\" : \"0cbff61e-3b0a-4eed-97ce-b1b4faa03493\",\n"
+ + "\t\t\"modelVersion\" : \"1.0\"\n" + "\t},\n"
+ + "\t\"serviceType\" : \"\",\n" + "\t\"serviceRole\" : \"\",\n"
+ + "\t\"environmentContext\" : null,\n" + "\t\"workloadContext\" : \"Production\",\n"
+ + "\t\"serviceVnfs\": [\n" + "\t\n" + "\t\t{ \"modelInfo\" : {\n"
+ + "\t\t\t\"modelName\" : \"15968a6e-2fe5-41bf-a481\",\n"
+ + "\t\t\t\"modelUuid\" : \"808abda3-2023-4105-92d2-e62644b61d53\",\n"
+ + "\t\t\t\"modelInvariantUuid\" : \"6e4ffc7c-497e-4a77-970d-af966e642d31\",\n"
+ + "\t\t\t\"modelVersion\" : \"1.0\",\n"
+ + "\t\t\t\"modelCustomizationUuid\" : \"a00404d5-d7eb-4c46-b6b6-9cf2d087e545\",\n"
+ + "\t\t\t\"modelInstanceName\" : \"15968a6e-2fe5-41bf-a481 0\"\n" + "\t\t\t},\n"
+ + "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.15968a6e2fe541bfA481\",\n"
+ + "\t\t\"nfFunction\" \t: null,\n"
+ + "\"resourceInput\":\"{\\\"a\\\":\\\"b\\\"}\","
+ + "\t\t\"nfType\" \t\t: null,\n"
+ + "\t\t\"nfRole\" \t\t: null,\n"
+ + "\t\t\"nfNamingCode\" \t: null,\n"
+ + "\t\t\"multiStageDesign\" : \"false\",\n" + "\t\t\t\"vfModules\": [\n"
+ + "\t\t\t\t{\n" + "\t\t\t\t\t\"modelInfo\" : { \n"
+ + "\t\t\t\t\t\t\"modelName\" : \"15968a6e2fe541bfA481..base_vfw..module-0\",\n"
+ + "\t\t\t\t\t\t\"modelUuid\" : \"ec7fadde-1e5a-42f7-8255-cb19e475ff45\",\n"
+ + "\t\t\t\t\t\t\"modelInvariantUuid\" : \"61ab8b64-a014-4cf3-8a5a-b5ef388f8819\",\n"
+ + "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n"
+ + "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"123aff6b-854f-4026-ae1e-cc74a3924576\"\n"
+ + "\t\t\t\t\t},\t\t\"isBase\" : true,\n"
+ + "\t\t\t\t\t\"vfModuleLabel\" : \"base_vfw\",\n"
+ + "\t\t\t\t\t\"initialCount\" : 1,\n"
+ + "\t\t\t\t\t\"hasVolumeGroup\" : true\n" + "\t\t\t\t}\n" + "\t\t\t]\n"
+ + "\t\t},\n" + "\t\n" + "\t\t{ \"modelInfo\" : {\n"
+ + "\t\t\t\"modelName\" : \"f971106a-248f-4202-9d1f\",\n"
+ + "\t\t\t\"modelUuid\" : \"4fbc08a4-35ed-4a59-9e47-79975e4add7e\",\n"
+ + "\t\t\t\"modelInvariantUuid\" : \"c669799e-adf1-46ae-8c70-48b326fe89f3\",\n"
+ + "\t\t\t\"modelVersion\" : \"1.0\",\n"
+ + "\t\t\t\"modelCustomizationUuid\" : \"e776449e-2b10-45c5-9217-2775c88ca1a0\",\n"
+ + "\t\t\t\"modelInstanceName\" : \"f971106a-248f-4202-9d1f 0\"\n" + "\t\t\t},\n"
+ + "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.F971106a248f42029d1f\",\n"
+ + "\t\t\"nfFunction\" \t: null,\n"
+ + "\t\t\"nfType\" \t\t: null,\n"
+ + "\t\t\"nfRole\" \t\t: null,\n"
+ + "\"resourceInput\":\"{\\\"a\\\":\\\"key|default_value\\\"}\","
+ + "\t\t\"nfNamingCode\" \t: null,\n"
+ + "\t\t\"multiStageDesign\" : \"false\",\n" + "\t\t\t\"vfModules\": [\n"
+ + "\t\t\t\t{\n" + "\t\t\t\t\t\"modelInfo\" : { \n"
+ + "\t\t\t\t\t\t\"modelName\" : \"F971106a248f42029d1f..base_vpkg..module-0\",\n"
+ + "\t\t\t\t\t\t\"modelUuid\" : \"47d5273a-7456-4786-9035-b3911944cc35\",\n"
+ + "\t\t\t\t\t\t\"modelInvariantUuid\" : \"0ea3e57e-ac7a-425a-928b-b4aee8806c15\",\n"
+ + "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n"
+ + "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"9ed9fef6-d3f8-4433-9807-7e23393a16bc\"\n"
+ + "\t\t\t\t\t},\t\t\"isBase\" : true,\n"
+ + "\t\t\t\t\t\"vfModuleLabel\" : \"base_vpkg\",\n"
+ + "\t\t\t\t\t\"initialCount\" : 1,\n"
+ + "\t\t\t\t\t\"hasVolumeGroup\" : true\n" + "\t\t\t\t}\n" + "\t\t\t]\n"
+ + "\t\t}\n" + "\t],\n" + "\t\"serviceNetworks\": [],\n"
+ + "\t\"serviceAllottedResources\": []\n" + "\t}}")));
-// when(UrnPropertiesReader.getVariable(anyString())).thenReturn("http://localhost:8080");
+ // when(UrnPropertiesReader.getVariable(anyString())).thenReturn("http://localhost:8080");
HashMap serviceInput = new HashMap();
serviceInput.put("key1", "value");
- Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest("c3954379-4efe-431c-8258-f84905b158e5",
- "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput);
+ Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest(
+ "c3954379-4efe-431c-8258-f84905b158e5", "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput);
assertEquals(stringObjectMap.get("a"), "default_value");
}
@Test
public void getResourceInputValueNoDefaultTest() throws Exception {
- wireMockServer.stubFor(get(urlEqualTo("/ecomp/mso/catalog/v2/serviceResources?serviceModelUuid=c3954379-4efe-431c-8258-f84905b158e5"))
- .willReturn(ok("{ \"serviceResources\" : {\n" +
- "\t\"modelInfo\" : {\n" +
- "\t\t\"modelName\" : \"demoVFWCL\",\n" +
- "\t\t\"modelUuid\" : \"c3954379-4efe-431c-8258-f84905b158e5\",\n" +
- "\t\t\"modelInvariantUuid\" : \"0cbff61e-3b0a-4eed-97ce-b1b4faa03493\",\n" +
- "\t\t\"modelVersion\" : \"1.0\"\n" +
- "\t},\n" +
- "\t\"serviceType\" : \"\",\n" +
- "\t\"serviceRole\" : \"\",\n" +
- "\t\"environmentContext\" : null,\n" +
- "\t\"workloadContext\" : \"Production\",\n" +
- "\t\"serviceVnfs\": [\n" +
- "\t\n" +
- "\t\t{ \"modelInfo\" : {\n" +
- "\t\t\t\"modelName\" : \"15968a6e-2fe5-41bf-a481\",\n" +
- "\t\t\t\"modelUuid\" : \"808abda3-2023-4105-92d2-e62644b61d53\",\n" +
- "\t\t\t\"modelInvariantUuid\" : \"6e4ffc7c-497e-4a77-970d-af966e642d31\",\n" +
- "\t\t\t\"modelVersion\" : \"1.0\",\n" +
- "\t\t\t\"modelCustomizationUuid\" : \"a00404d5-d7eb-4c46-b6b6-9cf2d087e545\",\n" +
- "\t\t\t\"modelInstanceName\" : \"15968a6e-2fe5-41bf-a481 0\"\n" +
- "\t\t\t},\n" +
- "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.15968a6e2fe541bfA481\",\n" +
- "\t\t\"nfFunction\" \t: null,\n" +
- "\"resourceInput\":\"{\\\"a\\\":\\\"b\\\"}\"," +
- "\t\t\"nfType\" \t\t: null,\n" +
- "\t\t\"nfRole\" \t\t: null,\n" +
- "\t\t\"nfNamingCode\" \t: null,\n" +
- "\t\t\"multiStageDesign\" : \"false\",\n" +
- "\t\t\t\"vfModules\": [\n" +
- "\t\t\t\t{\n" +
- "\t\t\t\t\t\"modelInfo\" : { \n" +
- "\t\t\t\t\t\t\"modelName\" : \"15968a6e2fe541bfA481..base_vfw..module-0\",\n" +
- "\t\t\t\t\t\t\"modelUuid\" : \"ec7fadde-1e5a-42f7-8255-cb19e475ff45\",\n" +
- "\t\t\t\t\t\t\"modelInvariantUuid\" : \"61ab8b64-a014-4cf3-8a5a-b5ef388f8819\",\n" +
- "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n" +
- "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"123aff6b-854f-4026-ae1e-cc74a3924576\"\n" +
- "\t\t\t\t\t},\t\t\"isBase\" : true,\n" +
- "\t\t\t\t\t\"vfModuleLabel\" : \"base_vfw\",\n" +
- "\t\t\t\t\t\"initialCount\" : 1,\n" +
- "\t\t\t\t\t\"hasVolumeGroup\" : true\n" +
- "\t\t\t\t}\n" +
- "\t\t\t]\n" +
- "\t\t},\n" +
- "\t\n" +
- "\t\t{ \"modelInfo\" : {\n" +
- "\t\t\t\"modelName\" : \"f971106a-248f-4202-9d1f\",\n" +
- "\t\t\t\"modelUuid\" : \"4fbc08a4-35ed-4a59-9e47-79975e4add7e\",\n" +
- "\t\t\t\"modelInvariantUuid\" : \"c669799e-adf1-46ae-8c70-48b326fe89f3\",\n" +
- "\t\t\t\"modelVersion\" : \"1.0\",\n" +
- "\t\t\t\"modelCustomizationUuid\" : \"e776449e-2b10-45c5-9217-2775c88ca1a0\",\n" +
- "\t\t\t\"modelInstanceName\" : \"f971106a-248f-4202-9d1f 0\"\n" +
- "\t\t\t},\n" +
- "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.F971106a248f42029d1f\",\n" +
- "\t\t\"nfFunction\" \t: null,\n" +
- "\t\t\"nfType\" \t\t: null,\n" +
- "\t\t\"nfRole\" \t\t: null,\n" +
- "\"resourceInput\":\"{\\\"a\\\":\\\"value\\\"}\"," +
- "\t\t\"nfNamingCode\" \t: null,\n" +
- "\t\t\"multiStageDesign\" : \"false\",\n" +
- "\t\t\t\"vfModules\": [\n" +
- "\t\t\t\t{\n" +
- "\t\t\t\t\t\"modelInfo\" : { \n" +
- "\t\t\t\t\t\t\"modelName\" : \"F971106a248f42029d1f..base_vpkg..module-0\",\n" +
- "\t\t\t\t\t\t\"modelUuid\" : \"47d5273a-7456-4786-9035-b3911944cc35\",\n" +
- "\t\t\t\t\t\t\"modelInvariantUuid\" : \"0ea3e57e-ac7a-425a-928b-b4aee8806c15\",\n" +
- "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n" +
- "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"9ed9fef6-d3f8-4433-9807-7e23393a16bc\"\n" +
- "\t\t\t\t\t},\t\t\"isBase\" : true,\n" +
- "\t\t\t\t\t\"vfModuleLabel\" : \"base_vpkg\",\n" +
- "\t\t\t\t\t\"initialCount\" : 1,\n" +
- "\t\t\t\t\t\"hasVolumeGroup\" : true\n" +
- "\t\t\t\t}\n" +
- "\t\t\t]\n" +
- "\t\t}\n" +
- "\t],\n" +
- "\t\"serviceNetworks\": [],\n" +
- "\t\"serviceAllottedResources\": []\n" +
- "\t}}")));
+ wireMockServer.stubFor(get(urlEqualTo(
+ "/ecomp/mso/catalog/v2/serviceResources?serviceModelUuid=c3954379-4efe-431c-8258-f84905b158e5"))
+ .willReturn(ok("{ \"serviceResources\" : {\n" + "\t\"modelInfo\" : {\n"
+ + "\t\t\"modelName\" : \"demoVFWCL\",\n"
+ + "\t\t\"modelUuid\" : \"c3954379-4efe-431c-8258-f84905b158e5\",\n"
+ + "\t\t\"modelInvariantUuid\" : \"0cbff61e-3b0a-4eed-97ce-b1b4faa03493\",\n"
+ + "\t\t\"modelVersion\" : \"1.0\"\n" + "\t},\n"
+ + "\t\"serviceType\" : \"\",\n" + "\t\"serviceRole\" : \"\",\n"
+ + "\t\"environmentContext\" : null,\n" + "\t\"workloadContext\" : \"Production\",\n"
+ + "\t\"serviceVnfs\": [\n" + "\t\n" + "\t\t{ \"modelInfo\" : {\n"
+ + "\t\t\t\"modelName\" : \"15968a6e-2fe5-41bf-a481\",\n"
+ + "\t\t\t\"modelUuid\" : \"808abda3-2023-4105-92d2-e62644b61d53\",\n"
+ + "\t\t\t\"modelInvariantUuid\" : \"6e4ffc7c-497e-4a77-970d-af966e642d31\",\n"
+ + "\t\t\t\"modelVersion\" : \"1.0\",\n"
+ + "\t\t\t\"modelCustomizationUuid\" : \"a00404d5-d7eb-4c46-b6b6-9cf2d087e545\",\n"
+ + "\t\t\t\"modelInstanceName\" : \"15968a6e-2fe5-41bf-a481 0\"\n" + "\t\t\t},\n"
+ + "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.15968a6e2fe541bfA481\",\n"
+ + "\t\t\"nfFunction\" \t: null,\n"
+ + "\"resourceInput\":\"{\\\"a\\\":\\\"b\\\"}\","
+ + "\t\t\"nfType\" \t\t: null,\n"
+ + "\t\t\"nfRole\" \t\t: null,\n"
+ + "\t\t\"nfNamingCode\" \t: null,\n"
+ + "\t\t\"multiStageDesign\" : \"false\",\n" + "\t\t\t\"vfModules\": [\n"
+ + "\t\t\t\t{\n" + "\t\t\t\t\t\"modelInfo\" : { \n"
+ + "\t\t\t\t\t\t\"modelName\" : \"15968a6e2fe541bfA481..base_vfw..module-0\",\n"
+ + "\t\t\t\t\t\t\"modelUuid\" : \"ec7fadde-1e5a-42f7-8255-cb19e475ff45\",\n"
+ + "\t\t\t\t\t\t\"modelInvariantUuid\" : \"61ab8b64-a014-4cf3-8a5a-b5ef388f8819\",\n"
+ + "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n"
+ + "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"123aff6b-854f-4026-ae1e-cc74a3924576\"\n"
+ + "\t\t\t\t\t},\t\t\"isBase\" : true,\n"
+ + "\t\t\t\t\t\"vfModuleLabel\" : \"base_vfw\",\n"
+ + "\t\t\t\t\t\"initialCount\" : 1,\n"
+ + "\t\t\t\t\t\"hasVolumeGroup\" : true\n" + "\t\t\t\t}\n" + "\t\t\t]\n"
+ + "\t\t},\n" + "\t\n" + "\t\t{ \"modelInfo\" : {\n"
+ + "\t\t\t\"modelName\" : \"f971106a-248f-4202-9d1f\",\n"
+ + "\t\t\t\"modelUuid\" : \"4fbc08a4-35ed-4a59-9e47-79975e4add7e\",\n"
+ + "\t\t\t\"modelInvariantUuid\" : \"c669799e-adf1-46ae-8c70-48b326fe89f3\",\n"
+ + "\t\t\t\"modelVersion\" : \"1.0\",\n"
+ + "\t\t\t\"modelCustomizationUuid\" : \"e776449e-2b10-45c5-9217-2775c88ca1a0\",\n"
+ + "\t\t\t\"modelInstanceName\" : \"f971106a-248f-4202-9d1f 0\"\n" + "\t\t\t},\n"
+ + "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.F971106a248f42029d1f\",\n"
+ + "\t\t\"nfFunction\" \t: null,\n"
+ + "\t\t\"nfType\" \t\t: null,\n"
+ + "\t\t\"nfRole\" \t\t: null,\n"
+ + "\"resourceInput\":\"{\\\"a\\\":\\\"value\\\"}\","
+ + "\t\t\"nfNamingCode\" \t: null,\n"
+ + "\t\t\"multiStageDesign\" : \"false\",\n" + "\t\t\t\"vfModules\": [\n"
+ + "\t\t\t\t{\n" + "\t\t\t\t\t\"modelInfo\" : { \n"
+ + "\t\t\t\t\t\t\"modelName\" : \"F971106a248f42029d1f..base_vpkg..module-0\",\n"
+ + "\t\t\t\t\t\t\"modelUuid\" : \"47d5273a-7456-4786-9035-b3911944cc35\",\n"
+ + "\t\t\t\t\t\t\"modelInvariantUuid\" : \"0ea3e57e-ac7a-425a-928b-b4aee8806c15\",\n"
+ + "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n"
+ + "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"9ed9fef6-d3f8-4433-9807-7e23393a16bc\"\n"
+ + "\t\t\t\t\t},\t\t\"isBase\" : true,\n"
+ + "\t\t\t\t\t\"vfModuleLabel\" : \"base_vpkg\",\n"
+ + "\t\t\t\t\t\"initialCount\" : 1,\n"
+ + "\t\t\t\t\t\"hasVolumeGroup\" : true\n" + "\t\t\t\t}\n" + "\t\t\t]\n"
+ + "\t\t}\n" + "\t],\n" + "\t\"serviceNetworks\": [],\n"
+ + "\t\"serviceAllottedResources\": []\n" + "\t}}")));
-// when(UrnPropertiesReader.getVariable(anyString())).thenReturn("http://localhost:8080");
+ // when(UrnPropertiesReader.getVariable(anyString())).thenReturn("http://localhost:8080");
HashMap serviceInput = new HashMap();
serviceInput.put("key1", "value");
- Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest("c3954379-4efe-431c-8258-f84905b158e5",
- "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput);
+ Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest(
+ "c3954379-4efe-431c-8258-f84905b158e5", "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput);
assertEquals(stringObjectMap.get("a"), "value");
}
@Test
public void getResourceSequenceTest() throws Exception {
- wireMockServer.stubFor(get(urlEqualTo("/ecomp/mso/catalog/v2/serviceResources?serviceModelUuid=c3954379-4efe-431c-8258-f84905b158e5"))
- .willReturn(ok("{ \"serviceResources\" : {\n" +
- "\t\"modelInfo\" : {\n" +
- "\t\t\"modelName\" : \"demoVFWCL\",\n" +
- "\t\t\"modelUuid\" : \"c3954379-4efe-431c-8258-f84905b158e5\",\n" +
- "\t\t\"modelInvariantUuid\" : \"0cbff61e-3b0a-4eed-97ce-b1b4faa03493\",\n" +
- "\t\t\"modelVersion\" : \"1.0\"\n" +
- "\t},\n" +
- "\t\"serviceType\" : \"\",\n" +
- "\t\"serviceRole\" : \"\",\n" +
- "\t\"environmentContext\" : null,\n" +
- "\t\"resourceOrder\" : \"res1,res2\",\n" +
- "\t\"workloadContext\" : \"Production\",\n" +
- "\t\"serviceVnfs\": [\n" +
- "\t\n" +
- "\t\t{ \"modelInfo\" : {\n" +
- "\t\t\t\"modelName\" : \"15968a6e-2fe5-41bf-a481\",\n" +
- "\t\t\t\"modelUuid\" : \"808abda3-2023-4105-92d2-e62644b61d53\",\n" +
- "\t\t\t\"modelInvariantUuid\" : \"6e4ffc7c-497e-4a77-970d-af966e642d31\",\n" +
- "\t\t\t\"modelVersion\" : \"1.0\",\n" +
- "\t\t\t\"modelCustomizationUuid\" : \"a00404d5-d7eb-4c46-b6b6-9cf2d087e545\",\n" +
- "\t\t\t\"modelInstanceName\" : \"15968a6e-2fe5-41bf-a481 0\"\n" +
- "\t\t\t},\n" +
- "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.15968a6e2fe541bfA481\",\n" +
- "\t\t\"nfFunction\" \t: null,\n" +
- "\"resourceInput\":\"{\\\"a\\\":\\\"b\\\"}\"," +
- "\t\t\"nfType\" \t\t: null,\n" +
- "\t\t\"nfRole\" \t\t: null,\n" +
- "\t\t\"nfNamingCode\" \t: null,\n" +
- "\t\t\"multiStageDesign\" : \"false\",\n" +
- "\t\t\t\"vfModules\": [\n" +
- "\t\t\t\t{\n" +
- "\t\t\t\t\t\"modelInfo\" : { \n" +
- "\t\t\t\t\t\t\"modelName\" : \"15968a6e2fe541bfA481..base_vfw..module-0\",\n" +
- "\t\t\t\t\t\t\"modelUuid\" : \"ec7fadde-1e5a-42f7-8255-cb19e475ff45\",\n" +
- "\t\t\t\t\t\t\"modelInvariantUuid\" : \"61ab8b64-a014-4cf3-8a5a-b5ef388f8819\",\n" +
- "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n" +
- "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"123aff6b-854f-4026-ae1e-cc74a3924576\"\n" +
- "\t\t\t\t\t},\t\t\"isBase\" : true,\n" +
- "\t\t\t\t\t\"vfModuleLabel\" : \"base_vfw\",\n" +
- "\t\t\t\t\t\"initialCount\" : 1,\n" +
- "\t\t\t\t\t\"hasVolumeGroup\" : true\n" +
- "\t\t\t\t}\n" +
- "\t\t\t]\n" +
- "\t\t},\n" +
- "\t\n" +
- "\t\t{ \"modelInfo\" : {\n" +
- "\t\t\t\"modelName\" : \"f971106a-248f-4202-9d1f\",\n" +
- "\t\t\t\"modelUuid\" : \"4fbc08a4-35ed-4a59-9e47-79975e4add7e\",\n" +
- "\t\t\t\"modelInvariantUuid\" : \"c669799e-adf1-46ae-8c70-48b326fe89f3\",\n" +
- "\t\t\t\"modelVersion\" : \"1.0\",\n" +
- "\t\t\t\"modelCustomizationUuid\" : \"e776449e-2b10-45c5-9217-2775c88ca1a0\",\n" +
- "\t\t\t\"modelInstanceName\" : \"f971106a-248f-4202-9d1f 0\"\n" +
- "\t\t\t},\n" +
- "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.F971106a248f42029d1f\",\n" +
- "\t\t\"nfFunction\" \t: null,\n" +
- "\t\t\"nfType\" \t\t: null,\n" +
- "\t\t\"nfRole\" \t\t: null,\n" +
- "\"resourceInput\":\"{\\\"a\\\":\\\"key|default_value\\\"}\"," +
- "\t\t\"nfNamingCode\" \t: null,\n" +
- "\t\t\"multiStageDesign\" : \"false\",\n" +
- "\t\t\t\"vfModules\": [\n" +
- "\t\t\t\t{\n" +
- "\t\t\t\t\t\"modelInfo\" : { \n" +
- "\t\t\t\t\t\t\"modelName\" : \"F971106a248f42029d1f..base_vpkg..module-0\",\n" +
- "\t\t\t\t\t\t\"modelUuid\" : \"47d5273a-7456-4786-9035-b3911944cc35\",\n" +
- "\t\t\t\t\t\t\"modelInvariantUuid\" : \"0ea3e57e-ac7a-425a-928b-b4aee8806c15\",\n" +
- "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n" +
- "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"9ed9fef6-d3f8-4433-9807-7e23393a16bc\"\n" +
- "\t\t\t\t\t},\t\t\"isBase\" : true,\n" +
- "\t\t\t\t\t\"vfModuleLabel\" : \"base_vpkg\",\n" +
- "\t\t\t\t\t\"initialCount\" : 1,\n" +
- "\t\t\t\t\t\"hasVolumeGroup\" : true\n" +
- "\t\t\t\t}\n" +
- "\t\t\t]\n" +
- "\t\t}\n" +
- "\t],\n" +
- "\t\"serviceNetworks\": [],\n" +
- "\t\"serviceAllottedResources\": []\n" +
- "\t}}")));
+ wireMockServer.stubFor(get(urlEqualTo(
+ "/ecomp/mso/catalog/v2/serviceResources?serviceModelUuid=c3954379-4efe-431c-8258-f84905b158e5"))
+ .willReturn(ok("{ \"serviceResources\" : {\n" + "\t\"modelInfo\" : {\n"
+ + "\t\t\"modelName\" : \"demoVFWCL\",\n"
+ + "\t\t\"modelUuid\" : \"c3954379-4efe-431c-8258-f84905b158e5\",\n"
+ + "\t\t\"modelInvariantUuid\" : \"0cbff61e-3b0a-4eed-97ce-b1b4faa03493\",\n"
+ + "\t\t\"modelVersion\" : \"1.0\"\n" + "\t},\n"
+ + "\t\"serviceType\" : \"\",\n" + "\t\"serviceRole\" : \"\",\n"
+ + "\t\"environmentContext\" : null,\n" + "\t\"resourceOrder\" : \"res1,res2\",\n"
+ + "\t\"workloadContext\" : \"Production\",\n" + "\t\"serviceVnfs\": [\n" + "\t\n"
+ + "\t\t{ \"modelInfo\" : {\n"
+ + "\t\t\t\"modelName\" : \"15968a6e-2fe5-41bf-a481\",\n"
+ + "\t\t\t\"modelUuid\" : \"808abda3-2023-4105-92d2-e62644b61d53\",\n"
+ + "\t\t\t\"modelInvariantUuid\" : \"6e4ffc7c-497e-4a77-970d-af966e642d31\",\n"
+ + "\t\t\t\"modelVersion\" : \"1.0\",\n"
+ + "\t\t\t\"modelCustomizationUuid\" : \"a00404d5-d7eb-4c46-b6b6-9cf2d087e545\",\n"
+ + "\t\t\t\"modelInstanceName\" : \"15968a6e-2fe5-41bf-a481 0\"\n" + "\t\t\t},\n"
+ + "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.15968a6e2fe541bfA481\",\n"
+ + "\t\t\"nfFunction\" \t: null,\n"
+ + "\"resourceInput\":\"{\\\"a\\\":\\\"b\\\"}\","
+ + "\t\t\"nfType\" \t\t: null,\n"
+ + "\t\t\"nfRole\" \t\t: null,\n"
+ + "\t\t\"nfNamingCode\" \t: null,\n"
+ + "\t\t\"multiStageDesign\" : \"false\",\n" + "\t\t\t\"vfModules\": [\n"
+ + "\t\t\t\t{\n" + "\t\t\t\t\t\"modelInfo\" : { \n"
+ + "\t\t\t\t\t\t\"modelName\" : \"15968a6e2fe541bfA481..base_vfw..module-0\",\n"
+ + "\t\t\t\t\t\t\"modelUuid\" : \"ec7fadde-1e5a-42f7-8255-cb19e475ff45\",\n"
+ + "\t\t\t\t\t\t\"modelInvariantUuid\" : \"61ab8b64-a014-4cf3-8a5a-b5ef388f8819\",\n"
+ + "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n"
+ + "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"123aff6b-854f-4026-ae1e-cc74a3924576\"\n"
+ + "\t\t\t\t\t},\t\t\"isBase\" : true,\n"
+ + "\t\t\t\t\t\"vfModuleLabel\" : \"base_vfw\",\n"
+ + "\t\t\t\t\t\"initialCount\" : 1,\n"
+ + "\t\t\t\t\t\"hasVolumeGroup\" : true\n" + "\t\t\t\t}\n" + "\t\t\t]\n"
+ + "\t\t},\n" + "\t\n" + "\t\t{ \"modelInfo\" : {\n"
+ + "\t\t\t\"modelName\" : \"f971106a-248f-4202-9d1f\",\n"
+ + "\t\t\t\"modelUuid\" : \"4fbc08a4-35ed-4a59-9e47-79975e4add7e\",\n"
+ + "\t\t\t\"modelInvariantUuid\" : \"c669799e-adf1-46ae-8c70-48b326fe89f3\",\n"
+ + "\t\t\t\"modelVersion\" : \"1.0\",\n"
+ + "\t\t\t\"modelCustomizationUuid\" : \"e776449e-2b10-45c5-9217-2775c88ca1a0\",\n"
+ + "\t\t\t\"modelInstanceName\" : \"f971106a-248f-4202-9d1f 0\"\n" + "\t\t\t},\n"
+ + "\t\t\"toscaNodeType\" : \"org.openecomp.resource.vf.F971106a248f42029d1f\",\n"
+ + "\t\t\"nfFunction\" \t: null,\n"
+ + "\t\t\"nfType\" \t\t: null,\n"
+ + "\t\t\"nfRole\" \t\t: null,\n"
+ + "\"resourceInput\":\"{\\\"a\\\":\\\"key|default_value\\\"}\","
+ + "\t\t\"nfNamingCode\" \t: null,\n"
+ + "\t\t\"multiStageDesign\" : \"false\",\n" + "\t\t\t\"vfModules\": [\n"
+ + "\t\t\t\t{\n" + "\t\t\t\t\t\"modelInfo\" : { \n"
+ + "\t\t\t\t\t\t\"modelName\" : \"F971106a248f42029d1f..base_vpkg..module-0\",\n"
+ + "\t\t\t\t\t\t\"modelUuid\" : \"47d5273a-7456-4786-9035-b3911944cc35\",\n"
+ + "\t\t\t\t\t\t\"modelInvariantUuid\" : \"0ea3e57e-ac7a-425a-928b-b4aee8806c15\",\n"
+ + "\t\t\t\t\t\t\"modelVersion\" : \"1\",\n"
+ + "\t\t\t\t\t\t\"modelCustomizationUuid\" : \"9ed9fef6-d3f8-4433-9807-7e23393a16bc\"\n"
+ + "\t\t\t\t\t},\t\t\"isBase\" : true,\n"
+ + "\t\t\t\t\t\"vfModuleLabel\" : \"base_vpkg\",\n"
+ + "\t\t\t\t\t\"initialCount\" : 1,\n"
+ + "\t\t\t\t\t\"hasVolumeGroup\" : true\n" + "\t\t\t\t}\n" + "\t\t\t]\n"
+ + "\t\t}\n" + "\t],\n" + "\t\"serviceNetworks\": [],\n"
+ + "\t\"serviceAllottedResources\": []\n" + "\t}}")));
- List<String> resourceSequence = ResourceRequestBuilder.getResourceSequence("c3954379-4efe-431c-8258-f84905b158e5");
+ List<String> resourceSequence =
+ ResourceRequestBuilder.getResourceSequence("c3954379-4efe-431c-8258-f84905b158e5");
assertEquals(resourceSequence.size(), 2);
assertEquals(resourceSequence.get(0), "res1");
assertEquals(resourceSequence.get(1), "res2");
@@ -403,27 +322,22 @@ public class ResourceRequestBuilderTest extends BaseTest {
@Test
public void getResourceInputWithEmptyServiceResourcesTest() throws Exception {
- wireMockServer.stubFor(get(urlEqualTo("/ecomp/mso/catalog/v2/serviceResources?serviceModelUuid=c3954379-4efe-431c-8258-f84905b158e5"))
- .willReturn(ok("{ \"serviceResources\" : {\n" +
- "\t\"modelInfo\" : {\n" +
- "\t\t\"modelName\" : \"demoVFWCL\",\n" +
- "\t\t\"modelUuid\" : \"c3954379-4efe-431c-8258-f84905b158e5\",\n" +
- "\t\t\"modelInvariantUuid\" : \"0cbff61e-3b0a-4eed-97ce-b1b4faa03493\",\n" +
- "\t\t\"modelVersion\" : \"1.0\"\n" +
- "\t},\n" +
- "\t\"serviceType\" : \"\",\n" +
- "\t\"serviceRole\" : \"\",\n" +
- "\t\"environmentContext\" : null,\n" +
- "\t\"workloadContext\" : \"Production\",\n" +
- "\t\"serviceVnfs\": [], \n" +
- "\t\"serviceNetworks\": [],\n" +
- "\t\"serviceAllottedResources\": []\n" +
- "\t}}")));
+ wireMockServer.stubFor(get(urlEqualTo(
+ "/ecomp/mso/catalog/v2/serviceResources?serviceModelUuid=c3954379-4efe-431c-8258-f84905b158e5"))
+ .willReturn(ok("{ \"serviceResources\" : {\n" + "\t\"modelInfo\" : {\n"
+ + "\t\t\"modelName\" : \"demoVFWCL\",\n"
+ + "\t\t\"modelUuid\" : \"c3954379-4efe-431c-8258-f84905b158e5\",\n"
+ + "\t\t\"modelInvariantUuid\" : \"0cbff61e-3b0a-4eed-97ce-b1b4faa03493\",\n"
+ + "\t\t\"modelVersion\" : \"1.0\"\n" + "\t},\n"
+ + "\t\"serviceType\" : \"\",\n" + "\t\"serviceRole\" : \"\",\n"
+ + "\t\"environmentContext\" : null,\n" + "\t\"workloadContext\" : \"Production\",\n"
+ + "\t\"serviceVnfs\": [], \n" + "\t\"serviceNetworks\": [],\n"
+ + "\t\"serviceAllottedResources\": []\n" + "\t}}")));
HashMap serviceInput = new HashMap();
serviceInput.put("key1", "value");
- Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest("c3954379-4efe-431c-8258-f84905b158e5",
- "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput);
+ Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest(
+ "c3954379-4efe-431c-8258-f84905b158e5", "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput);
assertEquals(0, stringObjectMap.size());
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java
index 76bc830d26..273e9f0e3c 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java
@@ -23,34 +23,33 @@ package org.onap.so.bpmn.common.util;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
-
import static org.junit.Assert.assertEquals;
public class CryptoHandlerTest {
- private static final String plainPswd = "mso0206";
- private CryptoHandler cryptoHandler;
- private static String encryptPwd;
-
-
- @Before
- public void setup() {
- cryptoHandler = new CryptoHandler();
- encryptPwd = cryptoHandler.encryptMsoPassword(plainPswd);
- }
-
- @Test
- @Ignore // ignored until we can mock the properties file.
- public void getMsoAaiPasswordTest() {
- assertEquals(plainPswd, cryptoHandler.getMsoAaiPassword());
- }
-
- @Test
- public void encryptMsoPasswordTest() {
- assertEquals(plainPswd,cryptoHandler.decryptMsoPassword(cryptoHandler.encryptMsoPassword(plainPswd)));
- }
-
- @Test
- public void decryptMsoPasswordTest() {
- assertEquals(plainPswd, cryptoHandler.decryptMsoPassword(encryptPwd));
- }
-} \ No newline at end of file
+ private static final String plainPswd = "mso0206";
+ private CryptoHandler cryptoHandler;
+ private static String encryptPwd;
+
+
+ @Before
+ public void setup() {
+ cryptoHandler = new CryptoHandler();
+ encryptPwd = cryptoHandler.encryptMsoPassword(plainPswd);
+ }
+
+ @Test
+ @Ignore // ignored until we can mock the properties file.
+ public void getMsoAaiPasswordTest() {
+ assertEquals(plainPswd, cryptoHandler.getMsoAaiPassword());
+ }
+
+ @Test
+ public void encryptMsoPasswordTest() {
+ assertEquals(plainPswd, cryptoHandler.decryptMsoPassword(cryptoHandler.encryptMsoPassword(plainPswd)));
+ }
+
+ @Test
+ public void decryptMsoPasswordTest() {
+ assertEquals(plainPswd, cryptoHandler.decryptMsoPassword(encryptPwd));
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunnerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunnerTest.java
index 617f63f6f8..f13bcb8a93 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunnerTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunnerTest.java
@@ -24,10 +24,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
-
import java.util.Arrays;
import java.util.List;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
import org.junit.Rule;
@@ -45,46 +43,48 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration(classes = {ValidationConfig.class})
public class BuildingBlockValidatorRunnerTest {
- @Rule
- public ExpectedException thrown= ExpectedException.none();
-
- @Autowired
- private BuildingBlockValidatorRunner runner;
-
- @Test
- public void filterValidatorTest() {
-
- MyPreValidatorOne one = new MyPreValidatorOne();
- MyPreValidatorTwo two = new MyPreValidatorTwo();
- MyPreValidatorThree three = new MyPreValidatorThree();
- List<FlowValidator> validators = Arrays.asList(one, two, three);
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Autowired
+ private BuildingBlockValidatorRunner runner;
+
+ @Test
+ public void filterValidatorTest() {
+
+ MyPreValidatorOne one = new MyPreValidatorOne();
+ MyPreValidatorTwo two = new MyPreValidatorTwo();
+ MyPreValidatorThree three = new MyPreValidatorThree();
+ List<FlowValidator> validators = Arrays.asList(one, two, three);
+
+ List<FlowValidator> result = runner.filterValidators(validators, "test");
+
+ List<FlowValidator> expected = Arrays.asList(two, one);
+
+ assertEquals(expected, result);
+ }
+
+ @Test
+ public void testValidate() {
+
+ BuildingBlockExecution execution = new DelegateExecutionImpl(new DelegateExecutionFake());
+ execution.setVariable("testProcessKey", "1234");
+ try {
+ runner.preValidate("test", execution);
+ fail("exception not thrown");
+ } catch (BpmnError e) {
+ WorkflowException workflowException = (WorkflowException) execution.getVariable("WorkflowException");
+ assertEquals(
+ "Failed Validations:\norg.onap.so.bpmn.common.validation.MyPreValidatorTwo: my-error-two\norg.onap.so.bpmn.common.validation.MyPreValidatorOne: my-error-one",
+ workflowException.getErrorMessage());
+ }
+ runner.preValidate("test2", mock(BuildingBlockExecution.class));
+ }
- List<FlowValidator> result = runner.filterValidators(validators, "test");
+ @Test
+ public void testEmptyList() {
+ boolean result = runner.preValidate("test3", mock(BuildingBlockExecution.class));
- List<FlowValidator> expected = Arrays.asList(two, one);
-
- assertEquals(expected, result);
- }
-
- @Test
- public void testValidate() {
-
- BuildingBlockExecution execution = new DelegateExecutionImpl(new DelegateExecutionFake());
- execution.setVariable("testProcessKey", "1234");
- try {
- runner.preValidate("test", execution);
- fail("exception not thrown");
- } catch (BpmnError e) {
- WorkflowException workflowException = (WorkflowException)execution.getVariable("WorkflowException");
- assertEquals("Failed Validations:\norg.onap.so.bpmn.common.validation.MyPreValidatorTwo: my-error-two\norg.onap.so.bpmn.common.validation.MyPreValidatorOne: my-error-one", workflowException.getErrorMessage());
- }
- runner.preValidate("test2", mock(BuildingBlockExecution.class));
- }
-
- @Test
- public void testEmptyList() {
- boolean result = runner.preValidate("test3", mock(BuildingBlockExecution.class));
-
- assertTrue(result);
- }
+ assertTrue(result);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyDisabledValidator.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyDisabledValidator.java
index 78e4791b1c..7572e930cd 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyDisabledValidator.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyDisabledValidator.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.common.validation;
import java.util.Collections;
import java.util.Optional;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.springframework.stereotype.Component;
@@ -30,15 +29,15 @@ import org.springframework.stereotype.Component;
@Skip
public class MyDisabledValidator implements PreBuildingBlockValidator {
- @Override
- public boolean shouldRunFor(String bbName) {
-
- return Collections.singleton("test").contains(bbName);
- }
+ @Override
+ public boolean shouldRunFor(String bbName) {
+
+ return Collections.singleton("test").contains(bbName);
+ }
- @Override
- public Optional<String> validate(BuildingBlockExecution exeuction) {
- return Optional.of("my-disabled-validator");
- }
+ @Override
+ public Optional<String> validate(BuildingBlockExecution exeuction) {
+ return Optional.of("my-disabled-validator");
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorFour.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorFour.java
index af45a129e2..85531719d5 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorFour.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorFour.java
@@ -23,21 +23,20 @@ package org.onap.so.bpmn.common.validation;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.springframework.stereotype.Component;
@Component
public class MyPreValidatorFour implements PreBuildingBlockValidator {
- @Override
- public boolean shouldRunFor(String bbName) {
- return Collections.singleton("test2").contains(bbName);
- }
+ @Override
+ public boolean shouldRunFor(String bbName) {
+ return Collections.singleton("test2").contains(bbName);
+ }
- @Override
- public Optional<String> validate(BuildingBlockExecution exeuction) {
- return Optional.of("my-error-four");
- }
+ @Override
+ public Optional<String> validate(BuildingBlockExecution exeuction) {
+ return Optional.of("my-error-four");
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorOne.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorOne.java
index d1d50e2a89..989a65fe47 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorOne.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorOne.java
@@ -23,22 +23,21 @@ package org.onap.so.bpmn.common.validation;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.springframework.stereotype.Component;
@Component
public class MyPreValidatorOne implements PreBuildingBlockValidator {
- @Override
- public boolean shouldRunFor(String bbName) {
-
- return Collections.singleton("test").contains(bbName);
- }
+ @Override
+ public boolean shouldRunFor(String bbName) {
+
+ return Collections.singleton("test").contains(bbName);
+ }
- @Override
- public Optional<String> validate(BuildingBlockExecution exeuction) {
- return Optional.of("my-error-one");
- }
+ @Override
+ public Optional<String> validate(BuildingBlockExecution exeuction) {
+ return Optional.of("my-error-one");
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorThree.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorThree.java
index 363020de71..a51d3836da 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorThree.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorThree.java
@@ -23,21 +23,20 @@ package org.onap.so.bpmn.common.validation;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.springframework.stereotype.Component;
@Component
public class MyPreValidatorThree implements PreBuildingBlockValidator {
- @Override
- public boolean shouldRunFor(String bbName) {
- return Collections.singleton("test2").contains(bbName);
- }
+ @Override
+ public boolean shouldRunFor(String bbName) {
+ return Collections.singleton("test2").contains(bbName);
+ }
- @Override
- public Optional<String> validate(BuildingBlockExecution exeuction) {
- return Optional.of("my-error-three");
- }
+ @Override
+ public Optional<String> validate(BuildingBlockExecution exeuction) {
+ return Optional.of("my-error-three");
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorTwo.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorTwo.java
index 4d78f4e458..1276d8f1d2 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorTwo.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorTwo.java
@@ -23,9 +23,7 @@ package org.onap.so.bpmn.common.validation;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
-
import javax.annotation.Priority;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.springframework.stereotype.Component;
@@ -33,14 +31,14 @@ import org.springframework.stereotype.Component;
@Component
public class MyPreValidatorTwo implements PreBuildingBlockValidator {
- @Override
- public boolean shouldRunFor(String bbName) {
- return Collections.singleton("test").contains(bbName);
- }
+ @Override
+ public boolean shouldRunFor(String bbName) {
+ return Collections.singleton("test").contains(bbName);
+ }
- @Override
- public Optional<String> validate(BuildingBlockExecution exeuction) {
- return Optional.of("my-error-two");
- }
+ @Override
+ public Optional<String> validate(BuildingBlockExecution exeuction) {
+ return Optional.of("my-error-two");
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/ValidationConfig.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/ValidationConfig.java
index 7570e4c915..90d094ce41 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/ValidationConfig.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/ValidationConfig.java
@@ -27,7 +27,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
-@ComponentScan(basePackages = {"org.onap.so.bpmn.common.validation"}, basePackageClasses = {ExceptionBuilder.class}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class)
+@ComponentScan(basePackages = {"org.onap.so.bpmn.common.validation"}, basePackageClasses = {ExceptionBuilder.class},
+ nameGenerator = DefaultToShortClassNameBeanNameGenerator.class)
public class ValidationConfig {
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorOne.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorOne.java
index 891496fa2b..485aae2fcc 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorOne.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorOne.java
@@ -23,22 +23,21 @@ package org.onap.so.bpmn.common.validation;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.springframework.stereotype.Component;
@Component
public class WorkflowPreValidatorOne implements PreWorkflowValidator {
- @Override
- public boolean shouldRunFor(String bbName) {
-
- return Collections.singleton("test").contains(bbName);
- }
+ @Override
+ public boolean shouldRunFor(String bbName) {
+
+ return Collections.singleton("test").contains(bbName);
+ }
- @Override
- public Optional<String> validate(BuildingBlockExecution exeuction) {
- return Optional.of("my-error-one");
- }
+ @Override
+ public Optional<String> validate(BuildingBlockExecution exeuction) {
+ return Optional.of("my-error-one");
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorTwo.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorTwo.java
index 80b55df8f5..9596524a56 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorTwo.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorTwo.java
@@ -23,9 +23,7 @@ package org.onap.so.bpmn.common.validation;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
-
import javax.annotation.Priority;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.springframework.stereotype.Component;
@@ -33,14 +31,14 @@ import org.springframework.stereotype.Component;
@Component
public class WorkflowPreValidatorTwo implements PreWorkflowValidator {
- @Override
- public boolean shouldRunFor(String bbName) {
- return Collections.singleton("test").contains(bbName);
- }
+ @Override
+ public boolean shouldRunFor(String bbName) {
+ return Collections.singleton("test").contains(bbName);
+ }
- @Override
- public Optional<String> validate(BuildingBlockExecution exeuction) {
- return Optional.of("my-error-two");
- }
+ @Override
+ public Optional<String> validate(BuildingBlockExecution exeuction) {
+ return Optional.of("my-error-two");
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunnerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunnerTest.java
index 5629f99feb..07cd790ed1 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunnerTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunnerTest.java
@@ -24,10 +24,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
-
import java.util.Arrays;
import java.util.List;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
@@ -45,45 +43,47 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration(classes = {ValidationConfig.class})
public class WorkflowValidatorRunnerTest {
- @Rule
- public ExpectedException thrown= ExpectedException.none();
-
- @Autowired
- private WorkflowValidatorRunner runner;
-
- @Test
- public void filterValidatorTest() {
-
- WorkflowPreValidatorOne one = new WorkflowPreValidatorOne();
- WorkflowPreValidatorTwo two = new WorkflowPreValidatorTwo();
- List<FlowValidator> validators = Arrays.asList(one, two);
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Autowired
+ private WorkflowValidatorRunner runner;
+
+ @Test
+ public void filterValidatorTest() {
+
+ WorkflowPreValidatorOne one = new WorkflowPreValidatorOne();
+ WorkflowPreValidatorTwo two = new WorkflowPreValidatorTwo();
+ List<FlowValidator> validators = Arrays.asList(one, two);
+
+ List<FlowValidator> result = runner.filterValidators(validators, "test");
+
+ List<FlowValidator> expected = Arrays.asList(two, one);
+
+ assertEquals(expected, result);
+ }
+
+ @Test
+ public void testValidate() {
+
+ DelegateExecution execution = new DelegateExecutionFake();
+ execution.setVariable("testProcessKey", "1234");
+ try {
+ runner.preValidate("test", execution);
+ fail("exception not thrown");
+ } catch (BpmnError e) {
+ WorkflowException workflowException = (WorkflowException) execution.getVariable("WorkflowException");
+ assertEquals(
+ "Failed Validations:\norg.onap.so.bpmn.common.validation.WorkflowPreValidatorTwo: my-error-two\norg.onap.so.bpmn.common.validation.WorkflowPreValidatorOne: my-error-one",
+ workflowException.getErrorMessage());
+ }
+ runner.preValidate("test2", mock(DelegateExecution.class));
+ }
- List<FlowValidator> result = runner.filterValidators(validators, "test");
+ @Test
+ public void testEmptyList() {
+ boolean result = runner.preValidate("test3", mock(DelegateExecution.class));
- List<FlowValidator> expected = Arrays.asList(two, one);
-
- assertEquals(expected, result);
- }
-
- @Test
- public void testValidate() {
-
- DelegateExecution execution = new DelegateExecutionFake();
- execution.setVariable("testProcessKey", "1234");
- try {
- runner.preValidate("test", execution);
- fail("exception not thrown");
- } catch (BpmnError e) {
- WorkflowException workflowException = (WorkflowException) execution.getVariable("WorkflowException");
- assertEquals("Failed Validations:\norg.onap.so.bpmn.common.validation.WorkflowPreValidatorTwo: my-error-two\norg.onap.so.bpmn.common.validation.WorkflowPreValidatorOne: my-error-one", workflowException.getErrorMessage());
- }
- runner.preValidate("test2", mock(DelegateExecution.class));
- }
-
- @Test
- public void testEmptyList() {
- boolean result = runner.preValidate("test3", mock(DelegateExecution.class));
-
- assertTrue(result);
- }
+ assertTrue(result);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/FileUtil.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/FileUtil.java
index 6a3668b175..e74dece785 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/FileUtil.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/FileUtil.java
@@ -34,51 +34,50 @@ import org.slf4j.LoggerFactory;
* </p>
*
* @author
- * @version ONAP Sep 15, 2017
+ * @version ONAP Sep 15, 2017
*/
public class FileUtil {
private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
-
- /**
- * Read the specified resource file and return the contents as a String.
- *
- * @param fileName Name of the resource file
- * @return the contents of the resource file as a String
- * @throws IOException if there is a problem reading the file
- */
- public static String readResourceFile(String fileName) {
- InputStream stream;
- try {
- stream = getResourceAsStream(fileName);
- byte[] bytes;
- bytes = new byte[stream.available()];
- if(stream.read(bytes) > 0) {
- stream.close();
- return new String(bytes);
- } else {
- stream.close();
- return "";
- }
- } catch (IOException e) {
- logger.debug("Exception:", e);
- return "";
- }
- }
-
- /**
- * Get an InputStream for the resource specified.
- *
- * @param resourceName Name of resource for which to get InputStream.
- * @return an InputStream for the resource specified.
- * @throws IOException If we can't get the InputStream for whatever reason.
- */
- private static InputStream getResourceAsStream(String resourceName) throws IOException {
- InputStream stream =
- FileUtil.class.getClassLoader().getResourceAsStream(resourceName);
- if (stream == null) {
- throw new IOException("Can't access resource '" + resourceName + "'");
- }
- return stream;
- }
+
+ /**
+ * Read the specified resource file and return the contents as a String.
+ *
+ * @param fileName Name of the resource file
+ * @return the contents of the resource file as a String
+ * @throws IOException if there is a problem reading the file
+ */
+ public static String readResourceFile(String fileName) {
+ InputStream stream;
+ try {
+ stream = getResourceAsStream(fileName);
+ byte[] bytes;
+ bytes = new byte[stream.available()];
+ if (stream.read(bytes) > 0) {
+ stream.close();
+ return new String(bytes);
+ } else {
+ stream.close();
+ return "";
+ }
+ } catch (IOException e) {
+ logger.debug("Exception:", e);
+ return "";
+ }
+ }
+
+ /**
+ * Get an InputStream for the resource specified.
+ *
+ * @param resourceName Name of resource for which to get InputStream.
+ * @return an InputStream for the resource specified.
+ * @throws IOException If we can't get the InputStream for whatever reason.
+ */
+ private static InputStream getResourceAsStream(String resourceName) throws IOException {
+ InputStream stream = FileUtil.class.getClassLoader().getResourceAsStream(resourceName);
+ if (stream == null) {
+ throw new IOException("Can't access resource '" + resourceName + "'");
+ }
+ return stream;
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseAAI.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseAAI.java
index 80625dd4d5..0d09a72edd 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseAAI.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseAAI.java
@@ -30,7 +30,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
-
import com.github.tomakehurst.wiremock.WireMockServer;
@@ -40,1059 +39,1027 @@ import com.github.tomakehurst.wiremock.WireMockServer;
*/
public class StubResponseAAI {
- public static void setupAllMocks() {
-
- }
-
-
- /**
- * Allotted Resource Mock StubResponses below
- */
- public static void MockGetAllottedResource(WireMockServer wireMockServer, String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId, String responseFile) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockPutAllottedResource(WireMockServer wireMockServer, String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void MockPutAllottedResource_500(WireMockServer wireMockServer, String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void MockDeleteAllottedResource(WireMockServer wireMockServer, String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId, String resourceVersion) {
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId + "[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(204)));
- }
-
- public static void MockPatchAllottedResource(WireMockServer wireMockServer, String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId) {
- wireMockServer.stubFor(patch(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void MockQueryAllottedResourceById(WireMockServer wireMockServer, String allottedResourceId, String responseFile){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=allotted-resource[&]filter=id:EQUALS:" + allottedResourceId))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
-
- /**
- * Service Instance Mock StubResponses below
- */
- public static void MockGetServiceInstance(WireMockServer wireMockServer, String globalCustId, String subscriptionType, String serviceInstanceId) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")));
- }
-
- /**
- * Service Instance Mock StubResponses below
- */
- public static void MockGetServiceInstance(WireMockServer wireMockServer, String globalCustId, String subscriptionType, String serviceInstanceId, String responseFile) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetServiceInstance_404(WireMockServer wireMockServer, String customer, String serviceSubscription, String serviceInstanceId){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId))
- .willReturn(aResponse()
- .withStatus(404)));
- }
-
- public static void MockGetServiceInstance_500(WireMockServer wireMockServer, String customer, String serviceSubscription, String serviceInstanceId){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void MockGetServiceInstance_500(WireMockServer wireMockServer, String customer, String serviceSubscription, String serviceInstanceId, String responseFile){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockNodeQueryServiceInstanceByName(WireMockServer wireMockServer, String serviceInstanceName, String responseFile){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance[&]filter=service-instance-name:EQUALS:" + serviceInstanceName))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockNodeQueryServiceInstanceByName_404(WireMockServer wireMockServer, String serviceInstanceName){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-name:EQUALS:" + serviceInstanceName))
- .willReturn(aResponse()
- .withStatus(404)));
- }
-
- public static void MockNodeQueryServiceInstanceByName_500(WireMockServer wireMockServer, String serviceInstanceName){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-name:EQUALS:" + serviceInstanceName))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void MockNodeQueryServiceInstanceById(WireMockServer wireMockServer, String serviceInstanceId, String responseFile){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance[&]filter=service-instance-id:EQUALS:" + serviceInstanceId))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockNodeQueryServiceInstanceById_404(WireMockServer wireMockServer, String serviceInstanceId){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId))
- .willReturn(aResponse()
- .withStatus(404)));
- }
-
- public static void MockNodeQueryServiceInstanceById_500(WireMockServer wireMockServer, String serviceInstanceId){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void MockDeleteServiceInstance(WireMockServer wireMockServer, String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(204)));
- }
-
- public static void MockGetServiceInstance(WireMockServer wireMockServer, String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion, int statusCode){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- public static void MockGetServiceInstance(WireMockServer wireMockServer, String customer, String serviceSubscription, int statusCode){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")));
- }
-
- public static void MockDeleteServiceInstance(WireMockServer wireMockServer, String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion, int statusCode){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- public static void MockDeleteServiceInstance(WireMockServer wireMockServer, String customer, String serviceSubscription, String resourceVersion, int statusCode){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "[?]resource-version=" +1234))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- public static void MockDeleteServiceInstance_404(WireMockServer wireMockServer, String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(404)));
- }
-
- public static void MockDeleteServiceInstance_500(WireMockServer wireMockServer, String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void MockPutServiceInstance(WireMockServer wireMockServer, String globalCustId, String subscriptionType, String serviceInstanceId, String responseFile) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockPutServiceInstance_500(WireMockServer wireMockServer, String globalCustId, String subscriptionType, String serviceInstanceId) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- /**
- * Service-Subscription Mock StubResponses below
- */
- public static void MockGetServiceSubscription(WireMockServer wireMockServer, String globalCustId, String subscriptionType, String responseFile) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockDeleteServiceSubscription(WireMockServer wireMockServer, String globalCustId, String subscriptionType, int statusCode) {
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- public static void MockDeleteServiceInstanceId(WireMockServer wireMockServer, String globalCustId, String subscriptionType, String serviceInstanceId) {
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void MockPutServiceSubscription(WireMockServer wireMockServer, String globalCustId, String subscriptionType) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void MockGetServiceSubscription(WireMockServer wireMockServer, String globalCustId, String subscriptionType, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- /**
- * Customer Mock StubResponses below
- */
- public static void MockGetCustomer(WireMockServer wireMockServer, String globalCustId, String responseFile) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockDeleteCustomer(WireMockServer wireMockServer, String globalCustId) {
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void MockPutCustomer(WireMockServer wireMockServer, String globalCustId) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void MockPutCustomer_500(WireMockServer wireMockServer, String globalCustId) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
-
- /**
- * Generic-Vnf Mock StubResponses below
- */
-
- public static void MockGetGenericVnfById(WireMockServer wireMockServer, String vnfId, String responseFile){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetGenericVnfById(WireMockServer wireMockServer, String vnfId, String responseFile, int statusCode){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetGenericVnfByIdWithPriority(WireMockServer wireMockServer, String vnfId, int statusCode, String responseFile) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId))
- .atPriority(1)
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetGenericVnfByIdWithPriority(WireMockServer wireMockServer, String vnfId, String vfModuleId, int statusCode, String responseFile, int priority) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
- .atPriority(priority)
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetGenericVnfByIdWithDepth(WireMockServer wireMockServer, String vnfId, int depth, String responseFile){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]depth=" + depth))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetGenericVnfById_404(WireMockServer wireMockServer, String vnfId){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
- .willReturn(aResponse()
- .withStatus(404)));
- }
-
- public static void MockGetGenericVnfById_500(WireMockServer wireMockServer, String vnfId){
- wireMockServer.stubFor(get(urlMatching("/aai/v9/network/generic-vnfs/generic-vnf/" + vnfId + "[?]depth=1"))
- .withQueryParam("depth", equalTo("1"))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void MockGetGenericVnfByName(WireMockServer wireMockServer, String vnfName, String responseFile){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetGenericVnfByNameWithDepth(WireMockServer wireMockServer, String vnfName, int depth, String responseFile){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName + "[&]depth=" + depth))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetGenericVnfByName_404(WireMockServer wireMockServer, String vnfName){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName))
- .willReturn(aResponse()
- .withStatus(404)));
- }
-
- public static void MockDeleteGenericVnf(WireMockServer wireMockServer, String vnfId, String resourceVersion){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(204)));
- }
-
- public static void MockDeleteGenericVnf(WireMockServer wireMockServer, String vnfId, String resourceVersion, int statusCode){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- public static void MockDeleteGenericVnf_500(WireMockServer wireMockServer, String vnfId, String resourceVersion){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void MockPutGenericVnf(WireMockServer wireMockServer, String vnfId){
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void MockPutGenericVnf(WireMockServer wireMockServer, String vnfId, String requestBodyContaining, int statusCode) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId))
- .withRequestBody(containing(requestBodyContaining))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- public static void MockPutGenericVnf(WireMockServer wireMockServer, String vnfId, int statusCode) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- public static void MockPutGenericVnf_Bad(WireMockServer wireMockServer, String vnfId, int statusCode){
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- public static void MockPatchGenericVnf(WireMockServer wireMockServer, String vnfId){
- wireMockServer.stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
- .willReturn(aResponse()
- .withStatus(200)));
- }
- /**
- * Vce Mock StubResponses below
- */
- public static void MockGetVceById(WireMockServer wireMockServer, String vnfId, String responseFile){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetVceByName(WireMockServer wireMockServer, String vnfName, String responseFile){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=" + vnfName))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockDeleteVce(WireMockServer wireMockServer, String vnfId, String resourceVersion, int statusCode){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId + "[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- public static void MockPutVce(WireMockServer wireMockServer, String vnfId){
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void MockGetGenericVceByNameWithDepth(WireMockServer wireMockServer, String vnfName, int depth, String responseFile){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=" + vnfName + "[&]depth=" + depth))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetVceGenericQuery(WireMockServer wireMockServer, String serviceInstanceName, int depth, int statusCode, String responseFile){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/search/generic-query[?]key=service-instance.service-instance-name:" + serviceInstanceName + "[&]start-node-type=service-instance[&]include=vce[&]depth=" + depth))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- /**
- * Tenant Mock StubResponses below
- */
- public static void MockGetTenantGenericQuery(WireMockServer wireMockServer, String customer, String serviceType, String responseFile) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/search/generic-query[?]key=customer.global-customer-id:" + customer + "&key=service-subscription.service-type:" + serviceType + "&start-node-type=service-subscription&include=tenant&include=service-subscription&depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetTenant(WireMockServer wireMockServer, String tenantId, String responseFile) {
- wireMockServer.stubFor(get(urlEqualTo("/aai/v2/cloud-infrastructure/tenants/tenant/" + tenantId))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- /**
- * Network Mock StubResponses below
- */
- public static void MockGetNetwork(WireMockServer wireMockServer, String networkId, String responseFile, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetNetworkByIdWithDepth(WireMockServer wireMockServer, String networkId, String responseFile, String depth) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId + "[?]depth=" + depth))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetNetworkCloudRegion(WireMockServer wireMockServer, String responseFile, String cloudRegion) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/"+cloudRegion))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetNetworkByName(WireMockServer wireMockServer, String networkName, String responseFile) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network[?]network-name="+networkName))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetNetworkByName_404(WireMockServer wireMockServer, String responseFile, String networkName) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network[?]network-name="+networkName))
- .willReturn(aResponse()
- .withStatus(404)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetNetworkCloudRegion_404(WireMockServer wireMockServer, String cloudRegion) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/"+cloudRegion))
- .willReturn(aResponse()
- .withStatus(404)));
- }
-
- public static void MockPutNetwork(WireMockServer wireMockServer, String networkId, int statusCode, String responseFile) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockPutNetwork(WireMockServer wireMockServer, String networkPolicyId, String responseFile, int statusCode) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/" + networkPolicyId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
+ public static void setupAllMocks() {
+
+ }
+
+
+ /**
+ * Allotted Resource Mock StubResponses below
+ */
+ public static void MockGetAllottedResource(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, String serviceInstanceId, String allottedResourceId, String responseFile) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType
+ + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/"
+ + allottedResourceId)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockPutAllottedResource(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, String serviceInstanceId, String allottedResourceId) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType
+ + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/"
+ + allottedResourceId)).willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void MockPutAllottedResource_500(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, String serviceInstanceId, String allottedResourceId) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType
+ + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/"
+ + allottedResourceId)).willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void MockDeleteAllottedResource(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, String serviceInstanceId, String allottedResourceId, String resourceVersion) {
+ wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType
+ + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/"
+ + allottedResourceId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse().withStatus(204)));
+ }
+
+ public static void MockPatchAllottedResource(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, String serviceInstanceId, String allottedResourceId) {
+ wireMockServer.stubFor(patch(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType
+ + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/"
+ + allottedResourceId)).willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void MockQueryAllottedResourceById(WireMockServer wireMockServer, String allottedResourceId,
+ String responseFile) {
+ wireMockServer.stubFor(get(
+ urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=allotted-resource[&]filter=id:EQUALS:"
+ + allottedResourceId))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+
+ /**
+ * Service Instance Mock StubResponses below
+ */
+ public static void MockGetServiceInstance(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, String serviceInstanceId) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType
+ + "/service-instances/service-instance/" + serviceInstanceId))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")));
+ }
+
+ /**
+ * Service Instance Mock StubResponses below
+ */
+ public static void MockGetServiceInstance(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, String serviceInstanceId, String responseFile) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType
+ + "/service-instances/service-instance/" + serviceInstanceId)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockGetServiceInstance_404(WireMockServer wireMockServer, String customer,
+ String serviceSubscription, String serviceInstanceId) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/"
+ + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId))
+ .willReturn(aResponse().withStatus(404)));
+ }
+
+ public static void MockGetServiceInstance_500(WireMockServer wireMockServer, String customer,
+ String serviceSubscription, String serviceInstanceId) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/"
+ + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId))
+ .willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void MockGetServiceInstance_500(WireMockServer wireMockServer, String customer,
+ String serviceSubscription, String serviceInstanceId, String responseFile) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/"
+ + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockNodeQueryServiceInstanceByName(WireMockServer wireMockServer, String serviceInstanceName,
+ String responseFile) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance[&]filter=service-instance-name:EQUALS:"
+ + serviceInstanceName))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockNodeQueryServiceInstanceByName_404(WireMockServer wireMockServer,
+ String serviceInstanceName) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-name:EQUALS:"
+ + serviceInstanceName)).willReturn(aResponse().withStatus(404)));
+ }
+
+ public static void MockNodeQueryServiceInstanceByName_500(WireMockServer wireMockServer,
+ String serviceInstanceName) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-name:EQUALS:"
+ + serviceInstanceName)).willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void MockNodeQueryServiceInstanceById(WireMockServer wireMockServer, String serviceInstanceId,
+ String responseFile) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance[&]filter=service-instance-id:EQUALS:"
+ + serviceInstanceId))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockNodeQueryServiceInstanceById_404(WireMockServer wireMockServer, String serviceInstanceId) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-id:EQUALS:"
+ + serviceInstanceId)).willReturn(aResponse().withStatus(404)));
+ }
+
+ public static void MockNodeQueryServiceInstanceById_500(WireMockServer wireMockServer, String serviceInstanceId) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-id:EQUALS:"
+ + serviceInstanceId)).willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void MockDeleteServiceInstance(WireMockServer wireMockServer, String customer,
+ String serviceSubscription, String serviceInstanceId, String resourceVersion) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/"
+ + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId
+ + "[?]resource-version=" + resourceVersion)).willReturn(aResponse().withStatus(204)));
+ }
+
+ public static void MockGetServiceInstance(WireMockServer wireMockServer, String customer,
+ String serviceSubscription, String serviceInstanceId, String resourceVersion, int statusCode) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/"
+ + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId
+ + "[?]resource-version=" + resourceVersion)).willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ public static void MockGetServiceInstance(WireMockServer wireMockServer, String customer,
+ String serviceSubscription, int statusCode) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer
+ + "/service-subscriptions/service-subscription/" + serviceSubscription))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")));
+ }
+
+ public static void MockDeleteServiceInstance(WireMockServer wireMockServer, String customer,
+ String serviceSubscription, String serviceInstanceId, String resourceVersion, int statusCode) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/"
+ + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId
+ + "[?]resource-version=" + resourceVersion)).willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ public static void MockDeleteServiceInstance(WireMockServer wireMockServer, String customer,
+ String serviceSubscription, String resourceVersion, int statusCode) {
+ wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer
+ + "/service-subscriptions/service-subscription/" + serviceSubscription + "[?]resource-version=" + 1234))
+ .willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ public static void MockDeleteServiceInstance_404(WireMockServer wireMockServer, String customer,
+ String serviceSubscription, String serviceInstanceId, String resourceVersion) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/"
+ + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId
+ + "[?]resource-version=" + resourceVersion)).willReturn(aResponse().withStatus(404)));
+ }
+
+ public static void MockDeleteServiceInstance_500(WireMockServer wireMockServer, String customer,
+ String serviceSubscription, String serviceInstanceId, String resourceVersion) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/"
+ + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId
+ + "[?]resource-version=" + resourceVersion)).willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void MockPutServiceInstance(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, String serviceInstanceId, String responseFile) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType
+ + "/service-instances/service-instance/" + serviceInstanceId)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockPutServiceInstance_500(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, String serviceInstanceId) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType
+ + "/service-instances/service-instance/" + serviceInstanceId)).willReturn(aResponse().withStatus(500)));
+ }
+
+ /**
+ * Service-Subscription Mock StubResponses below
+ */
+ public static void MockGetServiceSubscription(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, String responseFile) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockDeleteServiceSubscription(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, int statusCode) {
+ wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType))
+ .willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ public static void MockDeleteServiceInstanceId(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, String serviceInstanceId) {
+ wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType
+ + "/service-instances/service-instance/" + serviceInstanceId)).willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void MockPutServiceSubscription(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType))
+ .willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void MockGetServiceSubscription(WireMockServer wireMockServer, String globalCustId,
+ String subscriptionType, int statusCode) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId
+ + "/service-subscriptions/service-subscription/" + subscriptionType))
+ .willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ /**
+ * Customer Mock StubResponses below
+ */
+ public static void MockGetCustomer(WireMockServer wireMockServer, String globalCustId, String responseFile) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockDeleteCustomer(WireMockServer wireMockServer, String globalCustId) {
+ wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId))
+ .willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void MockPutCustomer(WireMockServer wireMockServer, String globalCustId) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId))
+ .willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void MockPutCustomer_500(WireMockServer wireMockServer, String globalCustId) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId))
+ .willReturn(aResponse().withStatus(500)));
+ }
+
+
+ /**
+ * Generic-Vnf Mock StubResponses below
+ */
+
+ public static void MockGetGenericVnfById(WireMockServer wireMockServer, String vnfId, String responseFile) {
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]depth=1")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfById(WireMockServer wireMockServer, String vnfId, String responseFile,
+ int statusCode) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId)).willReturn(
+ aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfByIdWithPriority(WireMockServer wireMockServer, String vnfId, int statusCode,
+ String responseFile) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId)).atPriority(1)
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfByIdWithPriority(WireMockServer wireMockServer, String vnfId, String vfModuleId,
+ int statusCode, String responseFile, int priority) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .atPriority(priority).willReturn(aResponse().withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfByIdWithDepth(WireMockServer wireMockServer, String vnfId, int depth,
+ String responseFile) {
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]depth=" + depth))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfById_404(WireMockServer wireMockServer, String vnfId) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
+ .willReturn(aResponse().withStatus(404)));
+ }
+
+ public static void MockGetGenericVnfById_500(WireMockServer wireMockServer, String vnfId) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v9/network/generic-vnfs/generic-vnf/" + vnfId + "[?]depth=1"))
+ .withQueryParam("depth", equalTo("1")).willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void MockGetGenericVnfByName(WireMockServer wireMockServer, String vnfName, String responseFile) {
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfByNameWithDepth(WireMockServer wireMockServer, String vnfName, int depth,
+ String responseFile) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName + "[&]depth=" + depth))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfByName_404(WireMockServer wireMockServer, String vnfName) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName))
+ .willReturn(aResponse().withStatus(404)));
+ }
+
+ public static void MockDeleteGenericVnf(WireMockServer wireMockServer, String vnfId, String resourceVersion) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse().withStatus(204)));
+ }
+
+ public static void MockDeleteGenericVnf(WireMockServer wireMockServer, String vnfId, String resourceVersion,
+ int statusCode) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ public static void MockDeleteGenericVnf_500(WireMockServer wireMockServer, String vnfId, String resourceVersion) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void MockPutGenericVnf(WireMockServer wireMockServer, String vnfId) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
+ .willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void MockPutGenericVnf(WireMockServer wireMockServer, String vnfId, String requestBodyContaining,
+ int statusCode) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId))
+ .withRequestBody(containing(requestBodyContaining)).willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ public static void MockPutGenericVnf(WireMockServer wireMockServer, String vnfId, int statusCode) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId))
+ .willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ public static void MockPutGenericVnf_Bad(WireMockServer wireMockServer, String vnfId, int statusCode) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
+ .willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ public static void MockPatchGenericVnf(WireMockServer wireMockServer, String vnfId) {
+ wireMockServer.stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId))
+ .willReturn(aResponse().withStatus(200)));
+ }
+
+ /**
+ * Vce Mock StubResponses below
+ */
+ public static void MockGetVceById(WireMockServer wireMockServer, String vnfId, String responseFile) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockGetVceByName(WireMockServer wireMockServer, String vnfName, String responseFile) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=" + vnfName)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockDeleteVce(WireMockServer wireMockServer, String vnfId, String resourceVersion,
+ int statusCode) {
+ wireMockServer.stubFor(
+ delete(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ public static void MockPutVce(WireMockServer wireMockServer, String vnfId) {
+ wireMockServer.stubFor(
+ put(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId)).willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void MockGetGenericVceByNameWithDepth(WireMockServer wireMockServer, String vnfName, int depth,
+ String responseFile) {
+ wireMockServer
+ .stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=" + vnfName + "[&]depth=" + depth))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetVceGenericQuery(WireMockServer wireMockServer, String serviceInstanceName, int depth,
+ int statusCode, String responseFile) {
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/search/generic-query[?]key=service-instance.service-instance-name:"
+ + serviceInstanceName + "[&]start-node-type=service-instance[&]include=vce[&]depth=" + depth))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ /**
+ * Tenant Mock StubResponses below
+ */
+ public static void MockGetTenantGenericQuery(WireMockServer wireMockServer, String customer, String serviceType,
+ String responseFile) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/search/generic-query[?]key=customer.global-customer-id:"
+ + customer + "&key=service-subscription.service-type:" + serviceType
+ + "&start-node-type=service-subscription&include=tenant&include=service-subscription&depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetTenant(WireMockServer wireMockServer, String tenantId, String responseFile) {
+ wireMockServer.stubFor(get(urlEqualTo("/aai/v2/cloud-infrastructure/tenants/tenant/" + tenantId)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ /**
+ * Network Mock StubResponses below
+ */
+ public static void MockGetNetwork(WireMockServer wireMockServer, String networkId, String responseFile,
+ int statusCode) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId)).willReturn(
+ aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkByIdWithDepth(WireMockServer wireMockServer, String networkId, String responseFile,
+ String depth) {
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId + "[?]depth=" + depth))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkCloudRegion(WireMockServer wireMockServer, String responseFile,
+ String cloudRegion) {
+ wireMockServer.stubFor(get(
+ urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegion))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkByName(WireMockServer wireMockServer, String networkName, String responseFile) {
+ wireMockServer
+ .stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network[?]network-name=" + networkName))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkByName_404(WireMockServer wireMockServer, String responseFile,
+ String networkName) {
+ wireMockServer
+ .stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network[?]network-name=" + networkName))
+ .willReturn(aResponse().withStatus(404).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkCloudRegion_404(WireMockServer wireMockServer, String cloudRegion) {
+ wireMockServer.stubFor(get(
+ urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegion))
+ .willReturn(aResponse().withStatus(404)));
+ }
+
+ public static void MockPutNetwork(WireMockServer wireMockServer, String networkId, int statusCode,
+ String responseFile) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId)).willReturn(
+ aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockPutNetwork(WireMockServer wireMockServer, String networkPolicyId, String responseFile,
+ int statusCode) {
+ wireMockServer
+ .stubFor(put(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/" + networkPolicyId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
public static void MockPostNetwork(WireMockServer wireMockServer, String networkId) {
wireMockServer.stubFor(post(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId))
- .willReturn(aResponse()
- .withStatus(201)
- .withHeader("Content-Type", "text/xml")));
+ .willReturn(aResponse().withStatus(201).withHeader("Content-Type", "text/xml")));
}
public static void MockPostNetworkSubnet(WireMockServer wireMockServer, String networkId, String subnetId) {
- wireMockServer.stubFor(post(urlMatching(
- "/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId + "/subnets/subnet/" + subnetId))
- .willReturn(aResponse()
- .withStatus(201)
- .withHeader("Content-Type", "text/xml")));
+ wireMockServer.stubFor(post(
+ urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId + "/subnets/subnet/" + subnetId))
+ .willReturn(aResponse().withStatus(201).withHeader("Content-Type", "text/xml")));
}
- public static void MockGetNetworkName(WireMockServer wireMockServer, String networkPolicyName, String responseFile, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network[?]network-name=" + networkPolicyName))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
+ public static void MockGetNetworkName(WireMockServer wireMockServer, String networkPolicyName, String responseFile,
+ int statusCode) {
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network[?]network-name=" + networkPolicyName))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
public static void MockGetNetworkVpnBinding(WireMockServer wireMockServer, String responseFile, String vpnBinding) {
MockGetNetworkVpnBindingWithDepth(wireMockServer, responseFile, vpnBinding, "all");
}
public static void MockGetNetworkVpnBindingWithDepth(WireMockServer wireMockServer, String responseFile,
- String vpnBinding, String depth) {
+ String vpnBinding, String depth) {
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/vpn-bindings/vpn-binding/" + vpnBinding + "[?]depth=" + depth))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkPolicy(WireMockServer wireMockServer, String responseFile, String policy) {
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/" + policy + "[?]depth=all"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkVpnBinding(WireMockServer wireMockServer, String networkBindingId,
+ String responseFile, int statusCode) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/vpn-bindings/vpn-binding/" + networkBindingId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkPolicy(WireMockServer wireMockServer, String networkPolicy, String responseFile,
+ int statusCode) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/" + networkPolicy))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkTableReference(WireMockServer wireMockServer, String responseFile,
+ String tableReference) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/route-table-references/route-table-reference/" + tableReference + "[?]depth=all"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockPutNetworkIdWithDepth(WireMockServer wireMockServer, String responseFile, String networkId,
+ String depth) {
+ wireMockServer.stubFor(
+ put(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId + "[?]depth=" + depth))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkPolicyfqdn(WireMockServer wireMockServer, String networkPolicy,
+ String responseFile, int statusCode) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/network-policies/network-policy[?]network-policy-fqdn=" + networkPolicy))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetNetworkRouteTable(WireMockServer wireMockServer, String networkRouteId,
+ String responseFile, int statusCode) {
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/route-table-references/route-table-reference/" + networkRouteId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockPatchVfModuleId(WireMockServer wireMockServer, String vnfId, String vfModuleId) {
+ wireMockServer.stubFor(patch(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .willReturn(aResponse().withStatus(200)));
+ }
+
+ /////////////
+
+ public static void MockVNFAdapterRestVfModule(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(put(urlEqualTo("/vnfs/v1/vnfs/skask/vf-modules/supercool"))
+ .willReturn(aResponse().withStatus(202).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(post(urlMatching("/vnfs/v1/vnfs/.*/vf-modules"))
+ .willReturn(aResponse().withStatus(202).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(post(urlEqualTo("/vnfs/v1/vnfs/skask/vf-modules"))
+ .willReturn(aResponse().withStatus(202).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(put(urlEqualTo("/vnfs/v1/volume-groups/78987"))
+ .willReturn(aResponse().withStatus(202).withHeader("Content-Type", "application/xml")));
+ }
+
+ public static void MockDBUpdateVfModule(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter")).willReturn(aResponse().withStatus(200)
+ .withHeader("Content-Type", "text/xml").withBodyFile("VfModularity/DBUpdateResponse.xml")));
+ }
+
+ // start of mocks used locally and by other VF Module unit tests
+ public static void MockSDNCAdapterVfModule(WireMockServer wireMockServer) {
+ // simplified the implementation to return "success" for all requests
+ wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter"))
+ // .withRequestBody(containing("SvcInstanceId><"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/StandardSDNCSynchResponse.xml")));
+
+ }
+
+ // start of mocks used locally and by other VF Module unit tests
+ public static void MockAAIVfModule(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/supercool"))
+ .atPriority(1).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/VfModule-supercool.xml")));
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/lukewarm"))
+ .atPriority(2).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/VfModule-lukewarm.xml")));
+ wireMockServer
+ .stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/.*"))
+ .atPriority(5).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/VfModule-new.xml")));
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/GenericVnf.xml")));
+ wireMockServer.stubFor(
+ patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/supercool"))
+ // .withRequestBody(containing("PCRF"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(
+ patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/.*"))
+ // .withRequestBody(containing("PCRF"))
+ .willReturn(aResponse().withStatus(200)));
+ // HTTP PUT stub still used by CreateAAIvfModuleVolumeGroup
+ wireMockServer
+ .stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/.*"))
+ .withRequestBody(containing("PCRF")).willReturn(aResponse().withStatus(200)));
+ // HTTP PUT stub still used by DoCreateVfModuleTest
+ wireMockServer
+ .stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/.*"))
+ .withRequestBody(containing("MODULELABEL")).willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/volume-groups/volume-group[?]volume-group-id=78987"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/ConfirmVolumeGroupTenantResponse.xml")));
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/volume-groups/volume-group[?]volume-group-id=78987"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/ConfirmVolumeGroupTenantResponse.xml")));
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/MDTWNJ21/volume-groups/volume-group/78987"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/VolumeGroup.xml")));
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/AAIAIC25/volume-groups/volume-group/78987"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/VolumeGroup.xml")));
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/cloud-infrastructure/volume-groups/volume-group/78987[?]resource-version=0000020"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("DeleteCinderVolumeV1/DeleteVolumeId_AAIResponse_Success.xml")));
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/AddNetworkPolicy_AAIResponse_Success.xml")));
+ wireMockServer.stubFor(patch(
+ urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/NEWvBNGModuleId"))
+ .withRequestBody(containing("NEWvBNGModuleId")).willReturn(aResponse().withStatus(200)));
+ }
+
+
+
+ //////////////
+
+ /**
+ * Cloud infrastructure below
+ */
+
+ public static void MockGetCloudRegion(WireMockServer wireMockServer, String cloudRegionId, int statusCode,
+ String responseFile) {
+ wireMockServer.stubFor(get(
+ urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegionId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ /**
+ * Volume Group StubResponse below
+ */
+ public static void MockGetVolumeGroupById(WireMockServer wireMockServer, String cloudRegionId, String volumeGroupId,
+ String responseFile) {
+ MockGetVolumeGroupById(wireMockServer, cloudRegionId, volumeGroupId, responseFile, 200);
+ }
+
+ public static void MockGetVolumeGroupById(WireMockServer wireMockServer, String cloudRegionId, String volumeGroupId,
+ String responseFile, int responseCode) {
+ wireMockServer
+ .stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/"
+ + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId))
+ .willReturn(aResponse().withStatus(responseCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockPutVolumeGroupById(WireMockServer wireMockServer, String cloudRegionId, String volumeGroupId,
+ String responseFile, int statusCode) {
+ wireMockServer
+ .stubFor(put(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/"
+ + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetVolumeGroupByName(WireMockServer wireMockServer, String cloudRegionId,
+ String volumeGroupName, String responseFile, int statusCode) {
+ wireMockServer
+ .stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/"
+ + cloudRegionId + "/volume-groups[?]volume-group-name=" + volumeGroupName))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockDeleteVolumeGroupById(WireMockServer wireMockServer, String cloudRegionId,
+ String volumeGroupId, String resourceVersion, int statusCode) {
+ wireMockServer.stubFor(delete(
+ urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegionId
+ + "/volume-groups/volume-group/" + volumeGroupId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ public static void MockGetVolumeGroupByName_404(WireMockServer wireMockServer, String cloudRegionId,
+ String volumeGroupName) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v9/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/"
+ + cloudRegionId + "/volume-groups[?]volume-group-name=" + volumeGroupName))
+ .willReturn(aResponse().withStatus(404)));
+ }
+
+ public static void MockDeleteVolumeGroup(WireMockServer wireMockServer, String cloudRegionId, String volumeGroupId,
+ String resourceVersion) {
+ wireMockServer.stubFor(delete(
+ urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegionId
+ + "/volume-groups/volume-group/" + volumeGroupId + "[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse().withStatus(200)));
+ }
+
+ /**
+ * VF-Module StubResponse below
+ *
+ * @param statusCode TODO
+ */
+ public static void MockGetVfModuleId(WireMockServer wireMockServer, String vnfId, String vfModuleId,
+ String responseFile, int statusCode) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetVfModuleByNameWithDepth(WireMockServer wireMockServer, String vnfId, String vfModuleName,
+ int depth, String responseFile, int statusCode) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId
+ + "/vf-modules/vf-module[?]vf-module-name=" + vfModuleName + "[?]depth=" + depth))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetVfModuleByName(WireMockServer wireMockServer, String vnfId, String vfModuleName,
+ String responseFile, int statusCode) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId
+ + "/vf-modules/vf-module[?]vf-module-name=" + vfModuleName))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetVfModuleIdNoResponse(WireMockServer wireMockServer, String vnfId,
+ String requestContaining, String vfModuleId) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .withRequestBody(containing(requestContaining))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")));
+ }
+
+ public static void MockPutVfModuleIdNoResponse(WireMockServer wireMockServer, String vnfId,
+ String requestContaining, String vfModuleId) {
+ wireMockServer.stubFor(put(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .withRequestBody(containing(requestContaining)).willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void MockPutVfModuleId(WireMockServer wireMockServer, String vnfId, String vfModuleId) {
+ wireMockServer.stubFor(put(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void MockPutVfModuleId(WireMockServer wireMockServer, String vnfId, String vfModuleId,
+ int returnCode) {
+ wireMockServer.stubFor(put(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
+ .willReturn(aResponse().withStatus(returnCode)));
+ }
+
+ public static void MockDeleteVfModuleId(WireMockServer wireMockServer, String vnfId, String vfModuleId,
+ String resourceVersion, int returnCode) {
+ wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId
+ + "/vf-modules/vf-module/" + vfModuleId + "/[?]resource-version=" + resourceVersion))
+ .willReturn(aResponse().withStatus(returnCode)));
+ }
+
+ public static void MockAAIVfModuleBadPatch(WireMockServer wireMockServer, String endpoint, int statusCode) {
+ wireMockServer.stubFor(patch(urlMatching(endpoint)).willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ /* AAI Pserver Queries */
+ public static void MockGetPserverByVnfId(WireMockServer wireMockServer, String vnfId, String responseFile,
+ int statusCode) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v1[0-9]/query.*")).willReturn(aResponse().withStatus(statusCode)
+ .withHeader("Content-Type", "application/json").withBodyFile(responseFile)));
+ }
+
+ public static void MockGetGenericVnfsByVnfId(WireMockServer wireMockServer, String vnfId, String responseFile,
+ int statusCode) {
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v1[0-9]/network/generic-vnfs/.*")).willReturn(aResponse().withStatus(statusCode)
+ .withHeader("Content-Type", "application/json; charset=utf-8").withBodyFile(responseFile)));
+ }
+
+ public static void MockSetInMaintFlagByVnfId(WireMockServer wireMockServer, String vnfId, int statusCode) {
+ wireMockServer.stubFor(patch(urlMatching("/aai/v1[0-9]/network/generic-vnfs/.*"))
+ .willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ public static void MockSetInMaintFlagByVnfId(WireMockServer wireMockServer, String vnfId, String responseFile,
+ int statusCode) {
+ wireMockServer.stubFor(post(urlMatching("/aai/v1[0-9]/network/generic-vnfs/.*"))
+ .willReturn(aResponse().withStatus(statusCode).withBodyFile(responseFile)));
+ }
+
+ public static void MockGetDefaultCloudRegionByCloudRegionId(WireMockServer wireMockServer, String cloudRegionId,
+ String responseFile, int statusCode) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v1[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegionId + ".*"))
+ .willReturn(aResponse().withStatus(statusCode)
+ .withHeader("Content-Type", "application/json; charset=utf-8")
+ .withBodyFile(responseFile)));
+ }
+
+ //// Deprecated Stubs below - to be deleted once unit test that reference them are refactored to use common ones
+ //// above ////
+ @Deprecated
+ public static void MockGetVceById(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123?depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getVceResponse.xml")));
+ }
+
+ @Deprecated
+ public static void MockGetVceByName(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=testVnfName123"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getVceByNameResponse.xml")));
+ }
+
+ @Deprecated
+ public static void MockPutVce(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(
+ put(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123")).willReturn(aResponse().withStatus(200)));
+ }
+
+ @Deprecated
+ public static void MockDeleteVce(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(
+ delete(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123[?]resource-version=testReVer123"))
+ .willReturn(aResponse().withStatus(204)));
+ }
+
+ @Deprecated
+ public static void MockDeleteVce_404(WireMockServer wireMockServer) {
wireMockServer.stubFor(
- get(urlMatching("/aai/v[0-9]+/network/vpn-bindings/vpn-binding/" + vpnBinding + "[?]depth=" + depth))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetNetworkPolicy(WireMockServer wireMockServer, String responseFile, String policy) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/"+policy + "[?]depth=all"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetNetworkVpnBinding(WireMockServer wireMockServer, String networkBindingId, String responseFile, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/vpn-bindings/vpn-binding/" + networkBindingId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetNetworkPolicy(WireMockServer wireMockServer, String networkPolicy, String responseFile, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/" + networkPolicy))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetNetworkTableReference(WireMockServer wireMockServer, String responseFile, String tableReference) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/route-table-references/route-table-reference/"+tableReference + "[?]depth=all"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockPutNetworkIdWithDepth(WireMockServer wireMockServer, String responseFile, String networkId, String depth) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/"+networkId+"[?]depth="+depth ))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetNetworkPolicyfqdn(WireMockServer wireMockServer, String networkPolicy, String responseFile, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy[?]network-policy-fqdn=" + networkPolicy))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetNetworkRouteTable(WireMockServer wireMockServer, String networkRouteId, String responseFile, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/route-table-references/route-table-reference/" + networkRouteId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockPatchVfModuleId(WireMockServer wireMockServer, String vnfId, String vfModuleId) {
- wireMockServer.stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- /////////////
-
- public static void MockVNFAdapterRestVfModule(WireMockServer wireMockServer) {
- wireMockServer.stubFor(put(urlEqualTo("/vnfs/v1/vnfs/skask/vf-modules/supercool"))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(post(urlMatching("/vnfs/v1/vnfs/.*/vf-modules"))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(post(urlEqualTo("/vnfs/v1/vnfs/skask/vf-modules"))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(put(urlEqualTo("/vnfs/v1/volume-groups/78987"))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/xml")));
- }
-
- public static void MockDBUpdateVfModule(WireMockServer wireMockServer){
- wireMockServer.stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/DBUpdateResponse.xml")));
- }
-
- // start of mocks used locally and by other VF Module unit tests
- public static void MockSDNCAdapterVfModule(WireMockServer wireMockServer) {
- // simplified the implementation to return "success" for all requests
- wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter"))
-// .withRequestBody(containing("SvcInstanceId><"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/StandardSDNCSynchResponse.xml")));
-
- }
-
- // start of mocks used locally and by other VF Module unit tests
- public static void MockAAIVfModule(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/supercool"))
- .atPriority(1)
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/VfModule-supercool.xml")));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/lukewarm"))
- .atPriority(2)
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/VfModule-lukewarm.xml")));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/.*"))
- .atPriority(5)
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/VfModule-new.xml")));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/GenericVnf.xml")));
- wireMockServer.stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/supercool"))
-// .withRequestBody(containing("PCRF"))
- .willReturn(aResponse()
- .withStatus(200)));
- wireMockServer.stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/.*"))
-// .withRequestBody(containing("PCRF"))
- .willReturn(aResponse()
- .withStatus(200)));
- // HTTP PUT stub still used by CreateAAIvfModuleVolumeGroup
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/.*"))
- .withRequestBody(containing("PCRF"))
- .willReturn(aResponse()
- .withStatus(200)));
- // HTTP PUT stub still used by DoCreateVfModuleTest
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/.*"))
- .withRequestBody(containing("MODULELABEL"))
- .willReturn(aResponse()
- .withStatus(200)));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/volume-groups/volume-group[?]volume-group-id=78987"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/ConfirmVolumeGroupTenantResponse.xml")));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/volume-groups/volume-group[?]volume-group-id=78987"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/ConfirmVolumeGroupTenantResponse.xml")));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/MDTWNJ21/volume-groups/volume-group/78987"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/VolumeGroup.xml")));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/AAIAIC25/volume-groups/volume-group/78987"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/VolumeGroup.xml")));
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/cloud-infrastructure/volume-groups/volume-group/78987[?]resource-version=0000020"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("DeleteCinderVolumeV1/DeleteVolumeId_AAIResponse_Success.xml")));
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/AddNetworkPolicy_AAIResponse_Success.xml")));
- wireMockServer.stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/NEWvBNGModuleId"))
- .withRequestBody(containing("NEWvBNGModuleId"))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
-
-
- //////////////
-
- /**
- * Cloud infrastructure below
- */
-
- public static void MockGetCloudRegion(WireMockServer wireMockServer, String cloudRegionId, int statusCode, String responseFile) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegionId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- /**
- * Volume Group StubResponse below
- */
- public static void MockGetVolumeGroupById(WireMockServer wireMockServer, String cloudRegionId, String volumeGroupId, String responseFile) {
- MockGetVolumeGroupById(wireMockServer, cloudRegionId, volumeGroupId, responseFile, 200);
- }
-
- public static void MockGetVolumeGroupById(WireMockServer wireMockServer, String cloudRegionId, String volumeGroupId, String responseFile, int responseCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId))
- .willReturn(aResponse()
- .withStatus(responseCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockPutVolumeGroupById(WireMockServer wireMockServer, String cloudRegionId, String volumeGroupId, String responseFile, int statusCode) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetVolumeGroupByName(WireMockServer wireMockServer, String cloudRegionId, String volumeGroupName, String responseFile, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegionId + "/volume-groups[?]volume-group-name=" + volumeGroupName))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockDeleteVolumeGroupById(WireMockServer wireMockServer, String cloudRegionId, String volumeGroupId, String resourceVersion, int statusCode) {
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId + "[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- public static void MockGetVolumeGroupByName_404(WireMockServer wireMockServer, String cloudRegionId, String volumeGroupName) {
- wireMockServer.stubFor(get(urlMatching("/aai/v9/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegionId + "/volume-groups[?]volume-group-name=" + volumeGroupName))
- .willReturn(aResponse()
- .withStatus(404)));
- }
-
- public static void MockDeleteVolumeGroup(WireMockServer wireMockServer, String cloudRegionId, String volumeGroupId, String resourceVersion) {
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId + "[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- /**
- * VF-Module StubResponse below
- * @param statusCode TODO
- */
- public static void MockGetVfModuleId(WireMockServer wireMockServer, String vnfId, String vfModuleId, String responseFile, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetVfModuleByNameWithDepth(WireMockServer wireMockServer, String vnfId, String vfModuleName, int depth, String responseFile, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module[?]vf-module-name=" + vfModuleName + "[?]depth=" + depth))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetVfModuleByName(WireMockServer wireMockServer, String vnfId, String vfModuleName, String responseFile, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module[?]vf-module-name=" + vfModuleName))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetVfModuleIdNoResponse(WireMockServer wireMockServer, String vnfId, String requestContaining, String vfModuleId) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
- .withRequestBody(containing(requestContaining))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")));
- }
-
- public static void MockPutVfModuleIdNoResponse(WireMockServer wireMockServer, String vnfId, String requestContaining, String vfModuleId) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId +"/vf-modules/vf-module/" +vfModuleId))
- .withRequestBody(containing(requestContaining))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void MockPutVfModuleId(WireMockServer wireMockServer, String vnfId, String vfModuleId) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void MockPutVfModuleId(WireMockServer wireMockServer, String vnfId, String vfModuleId, int returnCode) {
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId))
- .willReturn(aResponse()
- .withStatus(returnCode)));
- }
-
- public static void MockDeleteVfModuleId(WireMockServer wireMockServer, String vnfId, String vfModuleId, String resourceVersion, int returnCode) {
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId + "/[?]resource-version=" + resourceVersion))
- .willReturn(aResponse()
- .withStatus(returnCode)));
- }
-
- public static void MockAAIVfModuleBadPatch(WireMockServer wireMockServer, String endpoint, int statusCode) {
- wireMockServer.stubFor(patch(urlMatching(endpoint))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- /* AAI Pserver Queries */
- public static void MockGetPserverByVnfId(WireMockServer wireMockServer, String vnfId, String responseFile, int statusCode) {
- wireMockServer.stubFor(put(urlMatching("/aai/v1[0-9]/query.*"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetGenericVnfsByVnfId(WireMockServer wireMockServer, String vnfId, String responseFile, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v1[0-9]/network/generic-vnfs/.*"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/json; charset=utf-8")
- .withBodyFile(responseFile)));
- }
-
- public static void MockSetInMaintFlagByVnfId(WireMockServer wireMockServer, String vnfId, int statusCode) {
- wireMockServer.stubFor(patch(urlMatching("/aai/v1[0-9]/network/generic-vnfs/.*"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- ));
- }
-
- public static void MockSetInMaintFlagByVnfId(WireMockServer wireMockServer, String vnfId, String responseFile, int statusCode) {
- wireMockServer.stubFor(post(urlMatching("/aai/v1[0-9]/network/generic-vnfs/.*"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withBodyFile(responseFile)
- ));
- }
-
- public static void MockGetDefaultCloudRegionByCloudRegionId(WireMockServer wireMockServer, String cloudRegionId, String responseFile, int statusCode) {
- wireMockServer.stubFor(get(urlMatching("/aai/v1[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/"+cloudRegionId + ".*"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/json; charset=utf-8")
- .withBodyFile(responseFile)));
- }
-
- //// Deprecated Stubs below - to be deleted once unit test that reference them are refactored to use common ones above ////
- @Deprecated
- public static void MockGetVceById(WireMockServer wireMockServer){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123?depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("GenericFlows/getVceResponse.xml")));
- }
- @Deprecated
- public static void MockGetVceByName(WireMockServer wireMockServer){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=testVnfName123"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("GenericFlows/getVceByNameResponse.xml")));
- }
- @Deprecated
- public static void MockPutVce(WireMockServer wireMockServer){
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123"))
- .willReturn(aResponse()
- .withStatus(200)));
- }
- @Deprecated
- public static void MockDeleteVce(WireMockServer wireMockServer){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123[?]resource-version=testReVer123"))
- .willReturn(aResponse()
- .withStatus(204)));
- }
- @Deprecated
- public static void MockDeleteVce_404(WireMockServer wireMockServer){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123[?]resource-version=testReVer123"))
- .willReturn(aResponse()
- .withStatus(404)));
- }
-
- @Deprecated
- public static void MockDeleteServiceSubscription(WireMockServer wireMockServer){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET[?]resource-version=1234"))
- .willReturn(aResponse()
- .withStatus(204)));
- }
- @Deprecated
- public static void MockGetServiceSubscription(WireMockServer wireMockServer){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("GenericFlows/getServiceSubscription.xml")));
- }
- @Deprecated
- public static void MockGetServiceSubscription_200Empty(WireMockServer wireMockServer){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET[?]resource-version=1234"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(" ")));
- }
- @Deprecated
- public static void MockGetServiceSubscription_404(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET"))
- .willReturn(aResponse()
- .withStatus(404)));
- }
-
- @Deprecated
- public static void MockGetGenericVnfById(WireMockServer wireMockServer){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("GenericFlows/getGenericVnfByNameResponse.xml")));
- }
- @Deprecated
- public static void MockGetGenericVnfById_404(WireMockServer wireMockServer){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
- .willReturn(aResponse()
- .withStatus(404)));
- }
- @Deprecated
- public static void MockGetGenericVnfByName(WireMockServer wireMockServer){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("GenericFlows/getGenericVnfResponse.xml")));
- }
- @Deprecated
- public static void MockGetGenericVnfByName_hasRelationships(WireMockServer wireMockServer){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("GenericFlows/getGenericVnfResponse_hasRelationships.xml")));
- }
- @Deprecated
- public static void MockGetGenericVnfById_hasRelationships(WireMockServer wireMockServer){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("GenericFlows/getGenericVnfResponse_hasRelationships.xml")));
- }
- @Deprecated
- public static void MockGetGenericVnfById_500(WireMockServer wireMockServer){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
- .willReturn(aResponse()
- .withStatus(500)));
- }
- @Deprecated
- public static void MockGetGenericVnfByName_404(WireMockServer wireMockServer){
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123"))
- .willReturn(aResponse()
- .withStatus(404)));
- }
- @Deprecated
- public static void MockPutGenericVnf(WireMockServer wireMockServer){
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
- .willReturn(aResponse()
- .withStatus(200)));
- }
- @Deprecated
- public static void MockPutGenericVnf_400(WireMockServer wireMockServer){
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
- .willReturn(aResponse()
- .withStatus(400)));
- }
- @Deprecated
- public static void MockDeleteGenericVnf(WireMockServer wireMockServer){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123"))
- .willReturn(aResponse()
- .withStatus(204)));
- }
- @Deprecated
- public static void MockDeleteGenericVnf_404(WireMockServer wireMockServer){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123"))
- .willReturn(aResponse()
- .withStatus(404)));
- }
- @Deprecated
- public static void MockDeleteGenericVnf_500(WireMockServer wireMockServer){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123"))
- .willReturn(aResponse()
- .withStatus(500)));
- }
- @Deprecated
- public static void MockDeleteGenericVnf_412(WireMockServer wireMockServer){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[[?]]resource-version=testReVer123"))
- .willReturn(aResponse()
- .withStatus(412)));
- }
+ delete(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123[?]resource-version=testReVer123"))
+ .willReturn(aResponse().withStatus(404)));
+ }
+
+ @Deprecated
+ public static void MockDeleteServiceSubscription(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET[?]resource-version=1234"))
+ .willReturn(aResponse().withStatus(204)));
+ }
+
+ @Deprecated
+ public static void MockGetServiceSubscription(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getServiceSubscription.xml")));
+ }
+
+ @Deprecated
+ public static void MockGetServiceSubscription_200Empty(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET[?]resource-version=1234"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(" ")));
+ }
+
+ @Deprecated
+ public static void MockGetServiceSubscription_404(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET"))
+ .willReturn(aResponse().withStatus(404)));
+ }
+
+ @Deprecated
+ public static void MockGetGenericVnfById(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getGenericVnfByNameResponse.xml")));
+ }
+
+ @Deprecated
+ public static void MockGetGenericVnfById_404(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
+ .willReturn(aResponse().withStatus(404)));
+ }
+
+ @Deprecated
+ public static void MockGetGenericVnfByName(WireMockServer wireMockServer) {
+ wireMockServer
+ .stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getGenericVnfResponse.xml")));
+ }
+
+ @Deprecated
+ public static void MockGetGenericVnfByName_hasRelationships(WireMockServer wireMockServer) {
+ wireMockServer
+ .stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getGenericVnfResponse_hasRelationships.xml")));
+ }
+
+ @Deprecated
+ public static void MockGetGenericVnfById_hasRelationships(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("GenericFlows/getGenericVnfResponse_hasRelationships.xml")));
+ }
+
+ @Deprecated
+ public static void MockGetGenericVnfById_500(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
+ .willReturn(aResponse().withStatus(500)));
+ }
+
+ @Deprecated
+ public static void MockGetGenericVnfByName_404(WireMockServer wireMockServer) {
+ wireMockServer
+ .stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123"))
+ .willReturn(aResponse().withStatus(404)));
+ }
+
+ @Deprecated
+ public static void MockPutGenericVnf(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
+ .willReturn(aResponse().withStatus(200)));
+ }
+
+ @Deprecated
+ public static void MockPutGenericVnf_400(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123"))
+ .willReturn(aResponse().withStatus(400)));
+ }
+
+ @Deprecated
+ public static void MockDeleteGenericVnf(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123"))
+ .willReturn(aResponse().withStatus(204)));
+ }
+
+ @Deprecated
+ public static void MockDeleteGenericVnf_404(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123"))
+ .willReturn(aResponse().withStatus(404)));
+ }
+
+ @Deprecated
+ public static void MockDeleteGenericVnf_500(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123"))
+ .willReturn(aResponse().withStatus(500)));
+ }
+
+ @Deprecated
+ public static void MockDeleteGenericVnf_412(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[[?]]resource-version=testReVer123"))
+ .willReturn(aResponse().withStatus(412)));
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseAPPC.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseAPPC.java
index 2f2cf45814..53c08a3d6c 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseAPPC.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseAPPC.java
@@ -16,7 +16,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.mock;
@@ -24,7 +24,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
-
import com.github.tomakehurst.wiremock.WireMockServer;
/**
@@ -33,29 +32,25 @@ import com.github.tomakehurst.wiremock.WireMockServer;
*/
public class StubResponseAPPC {
- public static void setupAllMocks() {
-
- }
-
- // start of Policy mocks
- public static void MockAppcError(WireMockServer wireMockServer) {
- wireMockServer.stubFor(get(urlMatching("/events/.*"))
- // .withRequestBody(containing("APPC"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("APPC/appc_error.json")));
- wireMockServer.stubFor(put(urlMatching("/events/.*"))
- // .withRequestBody(containing("APPC"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("APPC/appc_error.json")));
-
-
-
- }
-
-
-
+ public static void setupAllMocks() {
+
+ }
+
+ // start of Policy mocks
+ public static void MockAppcError(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(get(urlMatching("/events/.*"))
+ // .withRequestBody(containing("APPC"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile("APPC/appc_error.json")));
+ wireMockServer.stubFor(put(urlMatching("/events/.*"))
+ // .withRequestBody(containing("APPC"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile("APPC/appc_error.json")));
+
+
+
+ }
+
+
+
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseDatabase.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseDatabase.java
index 8fd745d765..241b549101 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseDatabase.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseDatabase.java
@@ -24,96 +24,79 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
-
import com.github.tomakehurst.wiremock.WireMockServer;
/**
- * Stub response class for Database stubs
- * including database adapter, catalog db,
- * and other databases.
+ * Stub response class for Database stubs including database adapter, catalog db, and other databases.
*/
public class StubResponseDatabase {
- public static void setupAllMocks() {
+ public static void setupAllMocks() {
+
+ }
+
+ public static void MockUpdateRequestDB(WireMockServer wireMockServer, String fileName) {
+ wireMockServer.stubFor(post(urlEqualTo("/services/RequestsDbAdapter"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(fileName)));
+ }
+
+ public static void mockUpdateRequestDB(WireMockServer wireMockServer, int statusCode, String reponseFile) {
+ wireMockServer.stubFor(post(urlEqualTo("/services/RequestsDbAdapter")).willReturn(
+ aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml").withBodyFile(reponseFile)));
+ }
+
+ public static void MockGetAllottedResourcesByModelInvariantId(WireMockServer wireMockServer,
+ String modelInvariantId, String responseFile) {
+ wireMockServer
+ .stubFor(get(urlEqualTo("/v1/serviceAllottedResources?serviceModelInvariantUuid=" + modelInvariantId))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile(responseFile)));
+ }
+
+ public static void MockGetAllottedResourcesByModelInvariantId_500(WireMockServer wireMockServer,
+ String modelInvariantId, String responseFile) {
+ wireMockServer
+ .stubFor(get(urlEqualTo("/v1/serviceAllottedResources?serviceModelInvariantUuid=" + modelInvariantId))
+ .willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void MockGetVnfCatalogDataCustomizationUuid(WireMockServer wireMockServer,
+ String vnfModelCustomizationUuid, String responseFile) {
+ wireMockServer.stubFor(get(urlEqualTo("/v2/serviceVnfs?vnfModelCustomizationUuid=" + vnfModelCustomizationUuid))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile(responseFile)));
+ }
- }
+ public static void MockGetVfModuleByModelNameCatalogData(WireMockServer wireMockServer, String vfModuleModelName,
+ String responseFile) {
+ wireMockServer.stubFor(get(urlEqualTo("/v2/vfModules?vfModuleModelName=" + vfModuleModelName)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBodyFile(responseFile)));
+ }
- public static void MockUpdateRequestDB(WireMockServer wireMockServer, String fileName){
- wireMockServer.stubFor(post(urlEqualTo("/services/RequestsDbAdapter"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(fileName)));
- }
-
- public static void mockUpdateRequestDB(WireMockServer wireMockServer, int statusCode, String reponseFile) {
- wireMockServer.stubFor(post(urlEqualTo("/services/RequestsDbAdapter"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(reponseFile)));
- }
+ public static void MockGetServiceResourcesCatalogData(WireMockServer wireMockServer,
+ String serviceModelInvariantUuid, String serviceModelVersion, String responseFile) {
+ wireMockServer.stubFor(get(urlEqualTo("/ecomp/mso/catalog/v2/serviceResources?serviceModelInvariantUuid="
+ + serviceModelInvariantUuid + "&serviceModelVersion=" + serviceModelVersion))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile(responseFile)));
+ }
- public static void MockGetAllottedResourcesByModelInvariantId(WireMockServer wireMockServer, String modelInvariantId, String responseFile){
- wireMockServer.stubFor(get(urlEqualTo("/v1/serviceAllottedResources?serviceModelInvariantUuid=" + modelInvariantId))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)));
- }
+ public static void MockGetServiceResourcesCatalogData(WireMockServer wireMockServer,
+ String serviceModelInvariantUuid, String responseFile) {
+ wireMockServer.stubFor(get(urlEqualTo(
+ "/ecomp/mso/catalog/v2/serviceResources?serviceModelInvariantUuid=" + serviceModelInvariantUuid))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile(responseFile)));
+ }
- public static void MockGetAllottedResourcesByModelInvariantId_500(WireMockServer wireMockServer, String modelInvariantId, String responseFile){
- wireMockServer.stubFor(get(urlEqualTo("/v1/serviceAllottedResources?serviceModelInvariantUuid=" + modelInvariantId))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void MockGetVnfCatalogDataCustomizationUuid(WireMockServer wireMockServer, String vnfModelCustomizationUuid, String responseFile){
- wireMockServer.stubFor(get(urlEqualTo("/v2/serviceVnfs?vnfModelCustomizationUuid=" + vnfModelCustomizationUuid))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)));
- }
+ public static void MockGetServiceResourcesCatalogDataByModelUuid(WireMockServer wireMockServer,
+ String serviceModelUuid, String responseFile) {
+ wireMockServer.stubFor(get(urlEqualTo("/v2/serviceResources?serviceModelUuid=" + serviceModelUuid)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBodyFile(responseFile)));
+ }
- public static void MockGetVfModuleByModelNameCatalogData(WireMockServer wireMockServer, String vfModuleModelName, String responseFile){
- wireMockServer.stubFor(get(urlEqualTo("/v2/vfModules?vfModuleModelName=" + vfModuleModelName))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetServiceResourcesCatalogData(WireMockServer wireMockServer, String serviceModelInvariantUuid, String serviceModelVersion, String responseFile){
- wireMockServer.stubFor(get(urlEqualTo("/ecomp/mso/catalog/v2/serviceResources?serviceModelInvariantUuid=" +
- serviceModelInvariantUuid +
- "&serviceModelVersion=" + serviceModelVersion))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetServiceResourcesCatalogData(WireMockServer wireMockServer, String serviceModelInvariantUuid, String responseFile){
- wireMockServer.stubFor(get(urlEqualTo("/ecomp/mso/catalog/v2/serviceResources?serviceModelInvariantUuid=" + serviceModelInvariantUuid))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)));
- }
-
- public static void MockGetServiceResourcesCatalogDataByModelUuid(WireMockServer wireMockServer, String serviceModelUuid, String responseFile){
- wireMockServer.stubFor(get(urlEqualTo("/v2/serviceResources?serviceModelUuid=" + serviceModelUuid))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)));
- }
-
- public static void MockPostRequestDB(WireMockServer wireMockServer){
- wireMockServer.stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")));
- }
+ public static void MockPostRequestDB(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")));
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseNetworkAdapter.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseNetworkAdapter.java
index 3e1567412a..19c1a76f52 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseNetworkAdapter.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseNetworkAdapter.java
@@ -26,7 +26,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.delete;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
-
import com.github.tomakehurst.wiremock.WireMockServer;
/**
@@ -35,82 +34,62 @@ import com.github.tomakehurst.wiremock.WireMockServer;
*/
public class StubResponseNetworkAdapter {
- private static final String EOL = "\n";
-
- public static void setupAllMocks() {
-
- }
-
-
- public static void MockNetworkAdapter(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlEqualTo("/networks/NetworkAdapter"))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void MockNetworkAdapter(WireMockServer wireMockServer, String response) {
- wireMockServer.stubFor(post(urlEqualTo("/networks/NetworkAdapter"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(response)));
- }
-
- public static void MockNetworkAdapter_500(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlEqualTo("/networks/NetworkAdapter"))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void MockNetworkAdapterPost(WireMockServer wireMockServer, String responseFile, String requestContaining) {
- wireMockServer.stubFor(post(urlEqualTo("/networks/NetworkAdapter"))
- .withRequestBody(containing(requestContaining))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockNetworkAdapter(WireMockServer wireMockServer, String networkId, int statusCode, String responseFile) {
- wireMockServer.stubFor(delete(urlEqualTo("/networks/NetworkAdapter/" + networkId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockNetworkAdapterContainingRequest(WireMockServer wireMockServer, String requestContaining, int statusCode, String responseFile) {
- wireMockServer.stubFor(post(urlEqualTo("/networks/NetworkAdapter"))
- .withRequestBody(containing(requestContaining))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockPutNetworkAdapter(WireMockServer wireMockServer, String networkId, String requestContaining, int statusCode, String responseFile) {
- wireMockServer.stubFor(put(urlEqualTo("/networks/NetworkAdapter/" + networkId))
- .withRequestBody(containing(requestContaining))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockNetworkAdapterRestRollbackDelete(WireMockServer wireMockServer, String responseFile, String networkId) {
- wireMockServer.stubFor(delete(urlEqualTo("/networks/NetworkAdapter/"+networkId+"/rollback"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void MockNetworkAdapterRestPut(WireMockServer wireMockServer, String responseFile, String networkId) {
- wireMockServer.stubFor(put(urlEqualTo("/networks/NetworkAdapter/"+networkId))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
+ private static final String EOL = "\n";
+
+ public static void setupAllMocks() {
+
+ }
+
+
+ public static void MockNetworkAdapter(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/networks/NetworkAdapter")).willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void MockNetworkAdapter(WireMockServer wireMockServer, String response) {
+ wireMockServer.stubFor(post(urlEqualTo("/networks/NetworkAdapter"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(response)));
+ }
+
+ public static void MockNetworkAdapter_500(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/networks/NetworkAdapter")).willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void MockNetworkAdapterPost(WireMockServer wireMockServer, String responseFile,
+ String requestContaining) {
+ wireMockServer.stubFor(
+ post(urlEqualTo("/networks/NetworkAdapter")).withRequestBody(containing(requestContaining)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockNetworkAdapter(WireMockServer wireMockServer, String networkId, int statusCode,
+ String responseFile) {
+ wireMockServer.stubFor(delete(urlEqualTo("/networks/NetworkAdapter/" + networkId)).willReturn(aResponse()
+ .withStatus(statusCode).withHeader("Content-Type", "application/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockNetworkAdapterContainingRequest(WireMockServer wireMockServer, String requestContaining,
+ int statusCode, String responseFile) {
+ wireMockServer.stubFor(post(urlEqualTo("/networks/NetworkAdapter"))
+ .withRequestBody(containing(requestContaining)).willReturn(aResponse().withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockPutNetworkAdapter(WireMockServer wireMockServer, String networkId, String requestContaining,
+ int statusCode, String responseFile) {
+ wireMockServer.stubFor(put(urlEqualTo("/networks/NetworkAdapter/" + networkId))
+ .withRequestBody(containing(requestContaining)).willReturn(aResponse().withStatus(statusCode)
+ .withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockNetworkAdapterRestRollbackDelete(WireMockServer wireMockServer, String responseFile,
+ String networkId) {
+ wireMockServer.stubFor(delete(urlEqualTo("/networks/NetworkAdapter/" + networkId + "/rollback")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void MockNetworkAdapterRestPut(WireMockServer wireMockServer, String responseFile, String networkId) {
+ wireMockServer.stubFor(put(urlEqualTo("/networks/NetworkAdapter/" + networkId)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseOof.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseOof.java
index fe6c6a1396..aab2d38b35 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseOof.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseOof.java
@@ -23,7 +23,6 @@ package org.onap.so.bpmn.mock;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
-
import com.github.tomakehurst.wiremock.WireMockServer;
/**
@@ -37,31 +36,22 @@ public class StubResponseOof {
public static void mockOof(WireMockServer wireMockServer) {
wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement"))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/json")));
+ .willReturn(aResponse().withStatus(202).withHeader("Content-Type", "application/json")));
}
public static void mockOof(WireMockServer wireMockServer, String responseFile) {
- wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement"))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)));
+ wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement")).willReturn(
+ aResponse().withStatus(202).withHeader("Content-Type", "application/json").withBodyFile(responseFile)));
}
public static void mockOof_400(WireMockServer wireMockServer) {
wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement"))
- .willReturn(aResponse()
- .withStatus(400)
- .withHeader("Content-Type", "application/json")));
+ .willReturn(aResponse().withStatus(400).withHeader("Content-Type", "application/json")));
}
public static void mockOof_500(WireMockServer wireMockServer) {
wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement"))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "application/json")));
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "application/json")));
}
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponsePolicy.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponsePolicy.java
index a6c7fa57f0..bf3df503f3 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponsePolicy.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponsePolicy.java
@@ -24,7 +24,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
-
import com.github.tomakehurst.wiremock.WireMockServer;
/**
@@ -33,89 +32,59 @@ import com.github.tomakehurst.wiremock.WireMockServer;
*/
public class StubResponsePolicy {
- public static void setupAllMocks() {
-
- }
-
- // start of Policy mocks
- public static void MockPolicyAbort(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision"))
- .withRequestBody(containing("BB1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("policyAbortResponse.json")));
-
- wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision"))
- .withRequestBody(containing("UPDVnfI"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("policyAbortResponse.json")));
-
- wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision"))
- .withRequestBody(containing("RPLVnfI"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("policyAbortResponse.json")));
-
- wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision"))
- .withRequestBody(containing("VnfIPU"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("policyAbortResponse.json")));
-
- wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision"))
- .withRequestBody(containing("VnfCU"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("policyAbortResponse.json")));
-
-
-
- }
-
- public static void MockPolicySkip(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision"))
- .withRequestBody(containing("BB1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("Policy/policySkipResponse.json")));
-
- wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision"))
- .withRequestBody(containing("UPDVnfI"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("Policy/policySkipResponse.json")));
-
- wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision"))
- .withRequestBody(containing("RPLVnfI"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("Policy/policySkipResponse.json")));
-
- wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision"))
- .withRequestBody(containing("VnfIPU"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("Policy/policySkipResponse.json")));
-
- wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision"))
- .withRequestBody(containing("VnfCU"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("Policy/policySkipResponse.json")));
-
-
- }
-
-
+ public static void setupAllMocks() {
+
+ }
+
+ // start of Policy mocks
+ public static void MockPolicyAbort(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision")).withRequestBody(containing("BB1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile("policyAbortResponse.json")));
+
+ wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision")).withRequestBody(containing("UPDVnfI"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile("policyAbortResponse.json")));
+
+ wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision")).withRequestBody(containing("RPLVnfI"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile("policyAbortResponse.json")));
+
+ wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision")).withRequestBody(containing("VnfIPU"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile("policyAbortResponse.json")));
+
+ wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision")).withRequestBody(containing("VnfCU"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile("policyAbortResponse.json")));
+
+
+
+ }
+
+ public static void MockPolicySkip(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision")).withRequestBody(containing("BB1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile("Policy/policySkipResponse.json")));
+
+ wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision")).withRequestBody(containing("UPDVnfI"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile("Policy/policySkipResponse.json")));
+
+ wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision")).withRequestBody(containing("RPLVnfI"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile("Policy/policySkipResponse.json")));
+
+ wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision")).withRequestBody(containing("VnfIPU"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile("Policy/policySkipResponse.json")));
+
+ wireMockServer.stubFor(post(urlEqualTo("/pdp/api/getDecision")).withRequestBody(containing("VnfCU"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
+ .withBodyFile("Policy/policySkipResponse.json")));
+
+
+ }
+
+
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSDNCAdapter.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSDNCAdapter.java
index 10557ce091..9196e6a58c 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSDNCAdapter.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSDNCAdapter.java
@@ -25,7 +25,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
-
import com.github.tomakehurst.wiremock.WireMockServer;
/**
@@ -33,82 +32,60 @@ import com.github.tomakehurst.wiremock.WireMockServer;
*/
public class StubResponseSDNCAdapter {
- public static void setupAllMocks() {
-
- }
-
- public static void mockSDNCAdapter_500(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter"))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void mockSDNCAdapter_500(WireMockServer wireMockServer, String requestContaining) {
- wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter"))
- .withRequestBody(containing(requestContaining))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void mockSDNCAdapter(WireMockServer wireMockServer, int statusCode) {
- wireMockServer.stubFor(post(urlMatching(".*/SDNCAdapter"))
- .willReturn(aResponse()
- .withStatus(statusCode)));
- }
-
- public static void mockSDNCAdapter(WireMockServer wireMockServer, String endpoint, int statusCode, String responseFile) {
- wireMockServer.stubFor(post(urlEqualTo(endpoint))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void mockSDNCAdapter(WireMockServer wireMockServer, String responseFile) {
- wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void mockSDNCAdapter(WireMockServer wireMockServer, String endpoint, String requestContaining, int statusCode, String responseFile) {
- wireMockServer.stubFor(post(urlEqualTo(endpoint))
- .withRequestBody(containing(requestContaining))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void mockSDNCAdapterRest(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc/services"))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/json")));
- }
-
- public static void mockSDNCAdapterRest_500(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc/services"))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "application/json")));
- }
-
- public static void mockSDNCAdapterRest(WireMockServer wireMockServer, String requestContaining) {
- wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc/services"))
- .withRequestBody(containing(requestContaining))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/json")));
- }
-
- public static void mockSDNCAdapterRest_500(WireMockServer wireMockServer, String requestContaining) {
- wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc/services"))
- .withRequestBody(containing(requestContaining))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "application/json")));
- }
+ public static void setupAllMocks() {
+
+ }
+
+ public static void mockSDNCAdapter_500(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter")).willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void mockSDNCAdapter_500(WireMockServer wireMockServer, String requestContaining) {
+ wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter")).withRequestBody(containing(requestContaining))
+ .willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void mockSDNCAdapter(WireMockServer wireMockServer, int statusCode) {
+ wireMockServer.stubFor(post(urlMatching(".*/SDNCAdapter")).willReturn(aResponse().withStatus(statusCode)));
+ }
+
+ public static void mockSDNCAdapter(WireMockServer wireMockServer, String endpoint, int statusCode,
+ String responseFile) {
+ wireMockServer.stubFor(post(urlEqualTo(endpoint)).willReturn(
+ aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void mockSDNCAdapter(WireMockServer wireMockServer, String responseFile) {
+ wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void mockSDNCAdapter(WireMockServer wireMockServer, String endpoint, String requestContaining,
+ int statusCode, String responseFile) {
+ wireMockServer.stubFor(post(urlEqualTo(endpoint)).withRequestBody(containing(requestContaining)).willReturn(
+ aResponse().withStatus(statusCode).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void mockSDNCAdapterRest(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc/services"))
+ .willReturn(aResponse().withStatus(202).withHeader("Content-Type", "application/json")));
+ }
+
+ public static void mockSDNCAdapterRest_500(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc/services"))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "application/json")));
+ }
+
+ public static void mockSDNCAdapterRest(WireMockServer wireMockServer, String requestContaining) {
+ wireMockServer.stubFor(
+ post(urlEqualTo("/SDNCAdapter/v1/sdnc/services")).withRequestBody(containing(requestContaining))
+ .willReturn(aResponse().withStatus(202).withHeader("Content-Type", "application/json")));
+ }
+
+ public static void mockSDNCAdapterRest_500(WireMockServer wireMockServer, String requestContaining) {
+ wireMockServer.stubFor(
+ post(urlEqualTo("/SDNCAdapter/v1/sdnc/services")).withRequestBody(containing(requestContaining))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "application/json")));
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSNIRO.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSNIRO.java
index f040a0973c..e0ebf7d356 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSNIRO.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSNIRO.java
@@ -23,7 +23,6 @@ package org.onap.so.bpmn.mock;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
-
import com.github.tomakehurst.wiremock.WireMockServer;
/**
@@ -32,37 +31,28 @@ import com.github.tomakehurst.wiremock.WireMockServer;
*/
public class StubResponseSNIRO {
- public static void setupAllMocks() {
+ public static void setupAllMocks() {
- }
+ }
- public static void mockSNIRO(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/v2/placement"))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/json")));
- }
+ public static void mockSNIRO(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/v2/placement"))
+ .willReturn(aResponse().withStatus(202).withHeader("Content-Type", "application/json")));
+ }
- public static void mockSNIRO(WireMockServer wireMockServer, String responseFile) {
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/v2/placement"))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/json")
- .withBodyFile(responseFile)));
- }
+ public static void mockSNIRO(WireMockServer wireMockServer, String responseFile) {
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/v2/placement")).willReturn(
+ aResponse().withStatus(202).withHeader("Content-Type", "application/json").withBodyFile(responseFile)));
+ }
- public static void mockSNIRO_400(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/v2/placement"))
- .willReturn(aResponse()
- .withStatus(400)
- .withHeader("Content-Type", "application/json")));
- }
+ public static void mockSNIRO_400(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/v2/placement"))
+ .willReturn(aResponse().withStatus(400).withHeader("Content-Type", "application/json")));
+ }
- public static void mockSNIRO_500(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/v2/placement"))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "application/json")));
- }
+ public static void mockSNIRO_500(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/v2/placement"))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "application/json")));
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseVNFAdapter.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseVNFAdapter.java
index e90d358ba8..2501a8acd3 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseVNFAdapter.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseVNFAdapter.java
@@ -26,7 +26,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
-
import com.github.tomakehurst.wiremock.WireMockServer;
/**
@@ -34,150 +33,101 @@ import com.github.tomakehurst.wiremock.WireMockServer;
*/
public class StubResponseVNFAdapter {
- public static void mockVNFAdapter(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync"))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void mockVNFAdapter(WireMockServer wireMockServer, String responseFile) {
- wireMockServer.stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile(responseFile)));
- }
-
- public static void mockVNFAdapter_500(WireMockServer wireMockServer) {
- wireMockServer.stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync"))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void mockVNFPost(WireMockServer wireMockServer, String vfModuleId, int statusCode, String vnfId) {
- wireMockServer.stubFor(post(urlEqualTo("/services/rest/v1/vnfs" + vnfId + "/vf-modules" + vfModuleId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(post(urlEqualTo("/services/rest/v1/vnfs/" + vnfId + "/vf-modules" + vfModuleId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- }
-
- public static void mockVNFPut(WireMockServer wireMockServer, String vfModuleId, int statusCode) {
- wireMockServer.stubFor(put(urlEqualTo("/services/rest/v1/vnfsvnfId/vf-modules" + vfModuleId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(put(urlEqualTo("/services/rest/v1/vnfs/vnfId/vf-modules" + vfModuleId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- }
-
- public static void mockVNFPut(WireMockServer wireMockServer, String vnfId, String vfModuleId, int statusCode) {
- wireMockServer.stubFor(put(urlEqualTo("/services/rest/v1/vnfs" + vnfId + "/vf-modules" + vfModuleId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(put(urlEqualTo("/services/rest/v1/vnfs/" + vnfId + "/vf-modules" + vfModuleId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- }
-
- public static void mockVNFDelete(WireMockServer wireMockServer, String vnfId, String vfModuleId, int statusCode) {
- wireMockServer.stubFor(delete(urlEqualTo("/services/rest/v1/vnfs" + vnfId + "/vf-modules" + vfModuleId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(delete(urlEqualTo("/services/rest/v1/vnfs/" + vnfId + "/vf-modules" + vfModuleId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- }
-
- public static void mockVNFRollbackDelete(WireMockServer wireMockServer, String vfModuleId, int statusCode) {
- wireMockServer.stubFor(delete(urlEqualTo("/services/rest/v1/vnfsvnfId/vf-modules" + vfModuleId + "/rollback"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(delete(urlEqualTo("/services/rest/v1/vnfs/vnfId/vf-modules" + vfModuleId + "/rollback"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- }
-
- public static void mockPutVNFVolumeGroup(WireMockServer wireMockServer, String volumeGroupId, int statusCode) {
- wireMockServer.stubFor(put(urlEqualTo("/vnfs/v1/volume-groups/" + volumeGroupId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(put(urlEqualTo("/vnfs/rest/v1/volume-groups/" + volumeGroupId))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- }
-
- public static void mockPutVNFVolumeGroupRollback(WireMockServer wireMockServer, String volumeGroupId, int statusCode) {
- wireMockServer.stubFor(delete(urlMatching("/vnfs/v1/volume-groups/" + volumeGroupId + "/rollback"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(delete(urlMatching("/vnfs/rest/v1/volume-groups/" + volumeGroupId + "/rollback"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- }
- public static void mockPostVNFVolumeGroup(WireMockServer wireMockServer, int statusCode) {
- wireMockServer.stubFor(post(urlEqualTo("/vnfs/v1/volume-groups"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(post(urlEqualTo("/vnfs/rest/v1/volume-groups"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- }
-
- public static void mockVNFAdapterRest(WireMockServer wireMockServer, String vnfId) {
- wireMockServer.stubFor(post(urlEqualTo("/services/rest/v1/vnfs" + vnfId + "/vf-modules"))
- .willReturn(aResponse()
- .withStatus(200)));
- wireMockServer.stubFor(post(urlEqualTo("/services/rest/v1/vnfs/" + vnfId + "/vf-modules"))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
- public static void mockVNFAdapterRest_500(WireMockServer wireMockServer, String vnfId) {
- wireMockServer.stubFor(post(urlEqualTo("/services/rest/v1/vnfs" + vnfId + "/vf-modules"))
- .willReturn(aResponse()
- .withStatus(500)));
- wireMockServer.stubFor(post(urlEqualTo("/services/rest/v1/vnfs/" + vnfId + "/vf-modules"))
- .willReturn(aResponse()
- .withStatus(500)));
- }
-
- public static void mockVfModuleDelete(WireMockServer wireMockServer, String volumeGroupId) {
- wireMockServer.stubFor(delete(urlMatching("/vnfs/v1/volume-groups/"+ volumeGroupId))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(delete(urlMatching("/vnfs/rest/v1/volume-groups/"+ volumeGroupId))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/xml")));
- }
-
- public static void mockVfModuleDelete(WireMockServer wireMockServer, String volumeGroupId, int statusCode) {
- wireMockServer.stubFor(delete(urlMatching("/vnfs/v1/volume-groups/78987"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- wireMockServer.stubFor(delete(urlMatching("/vnfs/rest/v1/volume-groups/78987"))
- .willReturn(aResponse()
- .withStatus(statusCode)
- .withHeader("Content-Type", "application/xml")));
- }
+ public static void mockVNFAdapter(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync")).willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void mockVNFAdapter(WireMockServer wireMockServer, String responseFile) {
+ wireMockServer.stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBodyFile(responseFile)));
+ }
+
+ public static void mockVNFAdapter_500(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync")).willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void mockVNFPost(WireMockServer wireMockServer, String vfModuleId, int statusCode, String vnfId) {
+ wireMockServer.stubFor(post(urlEqualTo("/services/rest/v1/vnfs" + vnfId + "/vf-modules" + vfModuleId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(post(urlEqualTo("/services/rest/v1/vnfs/" + vnfId + "/vf-modules" + vfModuleId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ }
+
+ public static void mockVNFPut(WireMockServer wireMockServer, String vfModuleId, int statusCode) {
+ wireMockServer.stubFor(put(urlEqualTo("/services/rest/v1/vnfsvnfId/vf-modules" + vfModuleId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(put(urlEqualTo("/services/rest/v1/vnfs/vnfId/vf-modules" + vfModuleId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ }
+
+ public static void mockVNFPut(WireMockServer wireMockServer, String vnfId, String vfModuleId, int statusCode) {
+ wireMockServer.stubFor(put(urlEqualTo("/services/rest/v1/vnfs" + vnfId + "/vf-modules" + vfModuleId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(put(urlEqualTo("/services/rest/v1/vnfs/" + vnfId + "/vf-modules" + vfModuleId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ }
+
+ public static void mockVNFDelete(WireMockServer wireMockServer, String vnfId, String vfModuleId, int statusCode) {
+ wireMockServer.stubFor(delete(urlEqualTo("/services/rest/v1/vnfs" + vnfId + "/vf-modules" + vfModuleId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(delete(urlEqualTo("/services/rest/v1/vnfs/" + vnfId + "/vf-modules" + vfModuleId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ }
+
+ public static void mockVNFRollbackDelete(WireMockServer wireMockServer, String vfModuleId, int statusCode) {
+ wireMockServer.stubFor(delete(urlEqualTo("/services/rest/v1/vnfsvnfId/vf-modules" + vfModuleId + "/rollback"))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(delete(urlEqualTo("/services/rest/v1/vnfs/vnfId/vf-modules" + vfModuleId + "/rollback"))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ }
+
+ public static void mockPutVNFVolumeGroup(WireMockServer wireMockServer, String volumeGroupId, int statusCode) {
+ wireMockServer.stubFor(put(urlEqualTo("/vnfs/v1/volume-groups/" + volumeGroupId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(put(urlEqualTo("/vnfs/rest/v1/volume-groups/" + volumeGroupId))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ }
+
+ public static void mockPutVNFVolumeGroupRollback(WireMockServer wireMockServer, String volumeGroupId,
+ int statusCode) {
+ wireMockServer.stubFor(delete(urlMatching("/vnfs/v1/volume-groups/" + volumeGroupId + "/rollback"))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(delete(urlMatching("/vnfs/rest/v1/volume-groups/" + volumeGroupId + "/rollback"))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ }
+
+ public static void mockPostVNFVolumeGroup(WireMockServer wireMockServer, int statusCode) {
+ wireMockServer.stubFor(post(urlEqualTo("/vnfs/v1/volume-groups"))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(post(urlEqualTo("/vnfs/rest/v1/volume-groups"))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ }
+
+ public static void mockVNFAdapterRest(WireMockServer wireMockServer, String vnfId) {
+ wireMockServer.stubFor(post(urlEqualTo("/services/rest/v1/vnfs" + vnfId + "/vf-modules"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(post(urlEqualTo("/services/rest/v1/vnfs/" + vnfId + "/vf-modules"))
+ .willReturn(aResponse().withStatus(200)));
+ }
+
+ public static void mockVNFAdapterRest_500(WireMockServer wireMockServer, String vnfId) {
+ wireMockServer.stubFor(post(urlEqualTo("/services/rest/v1/vnfs" + vnfId + "/vf-modules"))
+ .willReturn(aResponse().withStatus(500)));
+ wireMockServer.stubFor(post(urlEqualTo("/services/rest/v1/vnfs/" + vnfId + "/vf-modules"))
+ .willReturn(aResponse().withStatus(500)));
+ }
+
+ public static void mockVfModuleDelete(WireMockServer wireMockServer, String volumeGroupId) {
+ wireMockServer.stubFor(delete(urlMatching("/vnfs/v1/volume-groups/" + volumeGroupId))
+ .willReturn(aResponse().withStatus(202).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(delete(urlMatching("/vnfs/rest/v1/volume-groups/" + volumeGroupId))
+ .willReturn(aResponse().withStatus(202).withHeader("Content-Type", "application/xml")));
+ }
+
+ public static void mockVfModuleDelete(WireMockServer wireMockServer, String volumeGroupId, int statusCode) {
+ wireMockServer.stubFor(delete(urlMatching("/vnfs/v1/volume-groups/78987"))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ wireMockServer.stubFor(delete(urlMatching("/vnfs/rest/v1/volume-groups/78987"))
+ .willReturn(aResponse().withStatus(statusCode).withHeader("Content-Type", "application/xml")));
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/BBDecompPojoTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/BBDecompPojoTest.java
index a72db062aa..7498044c53 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/BBDecompPojoTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/BBDecompPojoTest.java
@@ -32,24 +32,22 @@ import org.onap.so.openpojo.rules.HasEqualsAndHashCodeRule;
public class BBDecompPojoTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
- @Test
- public void pojoStructure() {
- test("org.onap.so.bpmn.servicedecomposition.bbobjects");
- }
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.bpmn.servicedecomposition.bbobjects");
+ }
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new EqualsAndHashCodeTester())
- .with(new HasEqualsAndHashCodeRule())
- .build();
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, new FilterNonConcrete());
- }
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new EqualsAndHashCodeTester())
+ .with(new HasEqualsAndHashCodeRule()).build();
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, new FilterNonConcrete());
+ }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/BBPojoTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/BBPojoTest.java
index eac6c0a8b7..d7c5ec9d55 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/BBPojoTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/BBPojoTest.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.servicedecomposition;
import org.junit.Test;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterNonConcrete;
@@ -36,31 +35,27 @@ import com.openpojo.validation.test.impl.SetterTester;
public class BBPojoTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
-
- @Test
- public void pojoStructure() {
- test("org.onap.so.bpmn.servicedecomposition.bbobjects");
- test("org.onap.so.bpmn.servicedecomposition.modelinfo");
- test("org.onap.so.bpmn.servicedecomposition.entities");
- test("org.onap.so.bpmn.servicedecomposition.homingobjects");
- test("org.onap.so.bpmn.servicedecomposition.generalobjects");
- }
-
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .with(new NoPrimitivesRule())
- .with(new SerializableMustHaveSerialVersionUIDRule())
- .build();
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, new FilterNonConcrete());
- }
-
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.bpmn.servicedecomposition.bbobjects");
+ test("org.onap.so.bpmn.servicedecomposition.modelinfo");
+ test("org.onap.so.bpmn.servicedecomposition.entities");
+ test("org.onap.so.bpmn.servicedecomposition.homingobjects");
+ test("org.onap.so.bpmn.servicedecomposition.generalobjects");
+ }
+
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterTester())
+ .with(new GetterTester()).with(new NoPrimitivesRule())
+ .with(new SerializableMustHaveSerialVersionUIDRule()).build();
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, new FilterNonConcrete());
+ }
+
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java
index 5de0903d65..8ab2c8e155 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java
@@ -21,10 +21,8 @@
package org.onap.so.bpmn.servicedecomposition;
import static org.junit.Assert.assertEquals;
-
import java.util.HashMap;
import java.util.List;
-
import org.camunda.bpm.engine.impl.pvm.runtime.ExecutionImpl;
import org.junit.Before;
import org.junit.Rule;
@@ -39,191 +37,194 @@ import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB;
import org.onap.so.client.exception.BBObjectNotFoundException;
import org.onap.so.BaseTest;
-public class ExtractPojosForBBTest extends BaseTest{
- ExtractPojosForBB extractPojos = new ExtractPojosForBB();
- private BuildingBlockExecution execution;
- private GeneralBuildingBlock gBBInput;
- private HashMap<ResourceKey, String> lookupKeyMap;
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Before
- public void before() {
- execution = new DelegateExecutionImpl(new ExecutionImpl());
- execution.setVariable("testProcessKey", "AAICreateTasksTests");
- gBBInput = new GeneralBuildingBlock();
- execution.setVariable("gBBInput", gBBInput);
- lookupKeyMap = new HashMap<>();
- execution.setVariable("lookupKeyMap", lookupKeyMap);
- }
-
- @Test
- public void get() throws BBObjectNotFoundException {
- ServiceInstance serviceInstancePend = new ServiceInstance();
- serviceInstancePend.setServiceInstanceId("abc");
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstancePend.getServiceInstanceId());
-
- VpnBondingLink vpnBondingLinkPend = new VpnBondingLink();
- vpnBondingLinkPend.setVpnBondingLinkId("testVpnBondingLink");
- serviceInstancePend.getVpnBondingLinks().add(vpnBondingLinkPend);
- lookupKeyMap.put(ResourceKey.VPN_BONDING_LINK_ID, vpnBondingLinkPend.getVpnBondingLinkId());
-
- Customer customer = new Customer();
- customer.setServiceSubscription(new ServiceSubscription());
- VpnBinding vpnBinding = new VpnBinding();
- vpnBinding.setVpnId("abc");
- customer.getVpnBindings().add(vpnBinding);
- lookupKeyMap.put(ResourceKey.VPN_ID, vpnBinding.getVpnId());
-
- List<GenericVnf> vnfsPend = serviceInstancePend.getVnfs();
- GenericVnf vnfPend = new GenericVnf();
- vnfPend.setVnfId("abc");
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnfPend.getVnfId());
-
- List<VfModule> vfModulesPend = vnfPend.getVfModules();
- VfModule vfModulePend = new VfModule();
- vfModulePend.setVfModuleId("abc");
- vfModulesPend.add(vfModulePend);
- vnfsPend.add(vnfPend);
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, vfModulePend.getVfModuleId());
-
- List<L3Network> networksPend = serviceInstancePend.getNetworks();
- L3Network networkPend = new L3Network();
- networkPend.setNetworkId("abc");
- networksPend.add(networkPend);
- lookupKeyMap.put(ResourceKey.NETWORK_ID, networkPend.getNetworkId());
-
- List<VolumeGroup> volumeGroupsPend = serviceInstancePend.getVnfs().get(0).getVolumeGroups();
- VolumeGroup volumeGroupPend = new VolumeGroup();
- volumeGroupPend.setVolumeGroupId("abc");
- volumeGroupsPend.add(volumeGroupPend);
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupPend.getVolumeGroupId());
-
- List<AllottedResource> allotedResourcesPend = serviceInstancePend.getAllottedResources();
- AllottedResource allotedResourcePend = new AllottedResource();
- allotedResourcePend.setId("abc");
- allotedResourcesPend.add(allotedResourcePend);
- lookupKeyMap.put(ResourceKey.ALLOTTED_RESOURCE_ID, allotedResourcePend.getId());
-
- Configuration configurationPend = new Configuration();
- configurationPend.setConfigurationId("abc");
- serviceInstancePend.getConfigurations().add(configurationPend);
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, configurationPend.getConfigurationId());
-
- List<InstanceGroup> instanceGroupsPend = serviceInstancePend.getInstanceGroups();
- InstanceGroup instanceGroupPend = new InstanceGroup();
- instanceGroupPend.setId("test-instance-group-1");
- instanceGroupsPend.add(instanceGroupPend);
- lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, instanceGroupPend.getId());
-
- customer.getServiceSubscription().getServiceInstances().add(serviceInstancePend);
- gBBInput.setCustomer(customer);
-
- ServiceInstance extractServPend = extractPojos.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- assertEquals(extractServPend.getServiceInstanceId(), serviceInstancePend.getServiceInstanceId());
- GenericVnf extractVnfPend = extractPojos.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- assertEquals(extractVnfPend.getVnfId(), vnfPend.getVnfId());
- L3Network extractNetworkPend = extractPojos.extractByKey(execution, ResourceKey.NETWORK_ID);
- assertEquals(extractNetworkPend.getNetworkId(), networkPend.getNetworkId());
- VolumeGroup extractVolumeGroupPend = extractPojos.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- assertEquals(extractVolumeGroupPend.getVolumeGroupId(), volumeGroupPend.getVolumeGroupId());
- AllottedResource extractallotedResourcePend = extractPojos.extractByKey(execution,
- ResourceKey.ALLOTTED_RESOURCE_ID);
- assertEquals(extractallotedResourcePend.getId(), allotedResourcePend.getId());
- Configuration extractConfigurationPend = extractPojos.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
- assertEquals(extractConfigurationPend.getConfigurationId(), configurationPend.getConfigurationId());
- VpnBinding extractVpnBinding = extractPojos.extractByKey(execution, ResourceKey.VPN_ID);
- assertEquals(extractVpnBinding.getVpnId(), vpnBinding.getVpnId());
-
- VfModule extractVfModulePend = extractPojos.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- assertEquals(extractVfModulePend.getVfModuleId(), vfModulePend.getVfModuleId());
-
- VpnBondingLink extractVpnBondingLinkPend = extractPojos.extractByKey(execution, ResourceKey.VPN_BONDING_LINK_ID);
- assertEquals(extractVpnBondingLinkPend.getVpnBondingLinkId(), vpnBondingLinkPend.getVpnBondingLinkId());
-
- InstanceGroup extractInstanceGroupPend = extractPojos.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID);
- assertEquals(instanceGroupPend.getId(), extractInstanceGroupPend.getId());
- }
-
- @Test
- public void siError() throws BBObjectNotFoundException {
- expectedException.expect(BBObjectNotFoundException.class);
-
- Customer customer = new Customer();
- customer.setServiceSubscription(new ServiceSubscription());
- ServiceInstance serviceInstance = new ServiceInstance();
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- gBBInput.setCustomer(customer);
-
- extractPojos.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- }
-
- @Test
- public void vnfError() throws BBObjectNotFoundException {
- expectedException.expect(BBObjectNotFoundException.class);
-
- Customer customer = new Customer();
- customer.setServiceSubscription(new ServiceSubscription());
- ServiceInstance serviceInstance = new ServiceInstance();
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- gBBInput.setCustomer(customer);
- extractPojos.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- }
-
- @Test
- public void vfModuleError() throws BBObjectNotFoundException {
- expectedException.expect(BBObjectNotFoundException.class);
-
- Customer customer = new Customer();
- customer.setServiceSubscription(new ServiceSubscription());
- ServiceInstance serviceInstance = new ServiceInstance();
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- gBBInput.setCustomer(customer);
- extractPojos.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- }
-
- @Test
- public void configurationError() throws BBObjectNotFoundException {
- expectedException.expect(BBObjectNotFoundException.class);
-
- Customer customer = new Customer();
- customer.setServiceSubscription(new ServiceSubscription());
- ServiceInstance serviceInstance = new ServiceInstance();
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- gBBInput.setCustomer(customer);
- extractPojos.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
- }
- @Test
- public void allotedError() throws BBObjectNotFoundException {
- expectedException.expect(BBObjectNotFoundException.class);
-
- Customer customer = new Customer();
- customer.setServiceSubscription(new ServiceSubscription());
- ServiceInstance serviceInstance = new ServiceInstance();
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- gBBInput.setCustomer(customer);
- extractPojos.extractByKey(execution, ResourceKey.ALLOTTED_RESOURCE_ID);
- }
- @Test
- public void vpnBindingError() throws BBObjectNotFoundException {
- expectedException.expect(BBObjectNotFoundException.class);
- Customer customer = new Customer();
- customer.setServiceSubscription(new ServiceSubscription());
- ServiceInstance serviceInstance = new ServiceInstance();
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- gBBInput.setCustomer(customer);
- extractPojos.extractByKey(execution, ResourceKey.VPN_ID);
- }
-
- @Test
- public void vpnBondingLinkError() throws BBObjectNotFoundException {
- expectedException.expect(BBObjectNotFoundException.class);
- Customer customer = new Customer();
- customer.setServiceSubscription(new ServiceSubscription());
- ServiceInstance serviceInstance = new ServiceInstance();
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- gBBInput.setCustomer(customer);
- extractPojos.extractByKey(execution, ResourceKey.VPN_BONDING_LINK_ID);
- }
+public class ExtractPojosForBBTest extends BaseTest {
+ ExtractPojosForBB extractPojos = new ExtractPojosForBB();
+ private BuildingBlockExecution execution;
+ private GeneralBuildingBlock gBBInput;
+ private HashMap<ResourceKey, String> lookupKeyMap;
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Before
+ public void before() {
+ execution = new DelegateExecutionImpl(new ExecutionImpl());
+ execution.setVariable("testProcessKey", "AAICreateTasksTests");
+ gBBInput = new GeneralBuildingBlock();
+ execution.setVariable("gBBInput", gBBInput);
+ lookupKeyMap = new HashMap<>();
+ execution.setVariable("lookupKeyMap", lookupKeyMap);
+ }
+
+ @Test
+ public void get() throws BBObjectNotFoundException {
+ ServiceInstance serviceInstancePend = new ServiceInstance();
+ serviceInstancePend.setServiceInstanceId("abc");
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstancePend.getServiceInstanceId());
+
+ VpnBondingLink vpnBondingLinkPend = new VpnBondingLink();
+ vpnBondingLinkPend.setVpnBondingLinkId("testVpnBondingLink");
+ serviceInstancePend.getVpnBondingLinks().add(vpnBondingLinkPend);
+ lookupKeyMap.put(ResourceKey.VPN_BONDING_LINK_ID, vpnBondingLinkPend.getVpnBondingLinkId());
+
+ Customer customer = new Customer();
+ customer.setServiceSubscription(new ServiceSubscription());
+ VpnBinding vpnBinding = new VpnBinding();
+ vpnBinding.setVpnId("abc");
+ customer.getVpnBindings().add(vpnBinding);
+ lookupKeyMap.put(ResourceKey.VPN_ID, vpnBinding.getVpnId());
+
+ List<GenericVnf> vnfsPend = serviceInstancePend.getVnfs();
+ GenericVnf vnfPend = new GenericVnf();
+ vnfPend.setVnfId("abc");
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnfPend.getVnfId());
+
+ List<VfModule> vfModulesPend = vnfPend.getVfModules();
+ VfModule vfModulePend = new VfModule();
+ vfModulePend.setVfModuleId("abc");
+ vfModulesPend.add(vfModulePend);
+ vnfsPend.add(vnfPend);
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, vfModulePend.getVfModuleId());
+
+ List<L3Network> networksPend = serviceInstancePend.getNetworks();
+ L3Network networkPend = new L3Network();
+ networkPend.setNetworkId("abc");
+ networksPend.add(networkPend);
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, networkPend.getNetworkId());
+
+ List<VolumeGroup> volumeGroupsPend = serviceInstancePend.getVnfs().get(0).getVolumeGroups();
+ VolumeGroup volumeGroupPend = new VolumeGroup();
+ volumeGroupPend.setVolumeGroupId("abc");
+ volumeGroupsPend.add(volumeGroupPend);
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupPend.getVolumeGroupId());
+
+ List<AllottedResource> allotedResourcesPend = serviceInstancePend.getAllottedResources();
+ AllottedResource allotedResourcePend = new AllottedResource();
+ allotedResourcePend.setId("abc");
+ allotedResourcesPend.add(allotedResourcePend);
+ lookupKeyMap.put(ResourceKey.ALLOTTED_RESOURCE_ID, allotedResourcePend.getId());
+
+ Configuration configurationPend = new Configuration();
+ configurationPend.setConfigurationId("abc");
+ serviceInstancePend.getConfigurations().add(configurationPend);
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, configurationPend.getConfigurationId());
+
+ List<InstanceGroup> instanceGroupsPend = serviceInstancePend.getInstanceGroups();
+ InstanceGroup instanceGroupPend = new InstanceGroup();
+ instanceGroupPend.setId("test-instance-group-1");
+ instanceGroupsPend.add(instanceGroupPend);
+ lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, instanceGroupPend.getId());
+
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstancePend);
+ gBBInput.setCustomer(customer);
+
+ ServiceInstance extractServPend = extractPojos.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ assertEquals(extractServPend.getServiceInstanceId(), serviceInstancePend.getServiceInstanceId());
+ GenericVnf extractVnfPend = extractPojos.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ assertEquals(extractVnfPend.getVnfId(), vnfPend.getVnfId());
+ L3Network extractNetworkPend = extractPojos.extractByKey(execution, ResourceKey.NETWORK_ID);
+ assertEquals(extractNetworkPend.getNetworkId(), networkPend.getNetworkId());
+ VolumeGroup extractVolumeGroupPend = extractPojos.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ assertEquals(extractVolumeGroupPend.getVolumeGroupId(), volumeGroupPend.getVolumeGroupId());
+ AllottedResource extractallotedResourcePend =
+ extractPojos.extractByKey(execution, ResourceKey.ALLOTTED_RESOURCE_ID);
+ assertEquals(extractallotedResourcePend.getId(), allotedResourcePend.getId());
+ Configuration extractConfigurationPend = extractPojos.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
+ assertEquals(extractConfigurationPend.getConfigurationId(), configurationPend.getConfigurationId());
+ VpnBinding extractVpnBinding = extractPojos.extractByKey(execution, ResourceKey.VPN_ID);
+ assertEquals(extractVpnBinding.getVpnId(), vpnBinding.getVpnId());
+
+ VfModule extractVfModulePend = extractPojos.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ assertEquals(extractVfModulePend.getVfModuleId(), vfModulePend.getVfModuleId());
+
+ VpnBondingLink extractVpnBondingLinkPend =
+ extractPojos.extractByKey(execution, ResourceKey.VPN_BONDING_LINK_ID);
+ assertEquals(extractVpnBondingLinkPend.getVpnBondingLinkId(), vpnBondingLinkPend.getVpnBondingLinkId());
+
+ InstanceGroup extractInstanceGroupPend = extractPojos.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID);
+ assertEquals(instanceGroupPend.getId(), extractInstanceGroupPend.getId());
+ }
+
+ @Test
+ public void siError() throws BBObjectNotFoundException {
+ expectedException.expect(BBObjectNotFoundException.class);
+
+ Customer customer = new Customer();
+ customer.setServiceSubscription(new ServiceSubscription());
+ ServiceInstance serviceInstance = new ServiceInstance();
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ gBBInput.setCustomer(customer);
+
+ extractPojos.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ }
+
+ @Test
+ public void vnfError() throws BBObjectNotFoundException {
+ expectedException.expect(BBObjectNotFoundException.class);
+
+ Customer customer = new Customer();
+ customer.setServiceSubscription(new ServiceSubscription());
+ ServiceInstance serviceInstance = new ServiceInstance();
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ gBBInput.setCustomer(customer);
+ extractPojos.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ }
+
+ @Test
+ public void vfModuleError() throws BBObjectNotFoundException {
+ expectedException.expect(BBObjectNotFoundException.class);
+
+ Customer customer = new Customer();
+ customer.setServiceSubscription(new ServiceSubscription());
+ ServiceInstance serviceInstance = new ServiceInstance();
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ gBBInput.setCustomer(customer);
+ extractPojos.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ }
+
+ @Test
+ public void configurationError() throws BBObjectNotFoundException {
+ expectedException.expect(BBObjectNotFoundException.class);
+
+ Customer customer = new Customer();
+ customer.setServiceSubscription(new ServiceSubscription());
+ ServiceInstance serviceInstance = new ServiceInstance();
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ gBBInput.setCustomer(customer);
+ extractPojos.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
+ }
+
+ @Test
+ public void allotedError() throws BBObjectNotFoundException {
+ expectedException.expect(BBObjectNotFoundException.class);
+
+ Customer customer = new Customer();
+ customer.setServiceSubscription(new ServiceSubscription());
+ ServiceInstance serviceInstance = new ServiceInstance();
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ gBBInput.setCustomer(customer);
+ extractPojos.extractByKey(execution, ResourceKey.ALLOTTED_RESOURCE_ID);
+ }
+
+ @Test
+ public void vpnBindingError() throws BBObjectNotFoundException {
+ expectedException.expect(BBObjectNotFoundException.class);
+ Customer customer = new Customer();
+ customer.setServiceSubscription(new ServiceSubscription());
+ ServiceInstance serviceInstance = new ServiceInstance();
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ gBBInput.setCustomer(customer);
+ extractPojos.extractByKey(execution, ResourceKey.VPN_ID);
+ }
+
+ @Test
+ public void vpnBondingLinkError() throws BBObjectNotFoundException {
+ expectedException.expect(BBObjectNotFoundException.class);
+ Customer customer = new Customer();
+ customer.setServiceSubscription(new ServiceSubscription());
+ ServiceInstance serviceInstance = new ServiceInstance();
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ gBBInput.setCustomer(customer);
+ extractPojos.extractByKey(execution, ResourceKey.VPN_BONDING_LINK_ID);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/SerializationTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/SerializationTest.java
index cfafe1622b..b970b95b97 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/SerializationTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/SerializationTest.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.servicedecomposition;
import static org.junit.Assert.assertEquals;
-
import java.io.ByteArrayOutputStream;
import java.io.Externalizable;
import java.io.File;
@@ -31,7 +30,6 @@ import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.impl.pvm.runtime.ExecutionImpl;
import org.junit.Test;
@@ -41,50 +39,44 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.common.DelegateExecutionImpl;
import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
-
import com.fasterxml.jackson.databind.ObjectMapper;
public class SerializationTest {
-
- private static final String RESOURCE_PATH = "src/test/resources/__files/ExecuteBuildingBlock/";
- private static final String FLOW_VAR_NAME = "flowToBeCalled";
- private static final String LOOKUP_KEY_MAP_VAR_NAME = "lookupKeyMap";
- private static final String GBB_INPUT_VAR_NAME = "gBBInput";
- protected ObjectMapper mapper = new ObjectMapper();
-
- @Test
- public void testSerializationOfAllPojos() throws IOException {
- GeneralBuildingBlock gbb = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- DelegateExecution execution = new ExecutionImpl();
- execution.setVariable(FLOW_VAR_NAME, "AssignServiceInstanceBB");
- execution.setVariable(GBB_INPUT_VAR_NAME, gbb);
- execution.setVariable(LOOKUP_KEY_MAP_VAR_NAME, lookupKeyMap);
- System.out.println(execution.getVariables());
- BuildingBlockExecution gBuildingBlockExecution = new DelegateExecutionImpl(execution);
- boolean isSerializable = SerializationTest.isSerializable(gBuildingBlockExecution);
- assertEquals(true, isSerializable);
- }
-
- public static boolean isSerializable(final Object o)
- {
+
+ private static final String RESOURCE_PATH = "src/test/resources/__files/ExecuteBuildingBlock/";
+ private static final String FLOW_VAR_NAME = "flowToBeCalled";
+ private static final String LOOKUP_KEY_MAP_VAR_NAME = "lookupKeyMap";
+ private static final String GBB_INPUT_VAR_NAME = "gBBInput";
+ protected ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ public void testSerializationOfAllPojos() throws IOException {
+ GeneralBuildingBlock gbb = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ DelegateExecution execution = new ExecutionImpl();
+ execution.setVariable(FLOW_VAR_NAME, "AssignServiceInstanceBB");
+ execution.setVariable(GBB_INPUT_VAR_NAME, gbb);
+ execution.setVariable(LOOKUP_KEY_MAP_VAR_NAME, lookupKeyMap);
+ System.out.println(execution.getVariables());
+ BuildingBlockExecution gBuildingBlockExecution = new DelegateExecutionImpl(execution);
+ boolean isSerializable = SerializationTest.isSerializable(gBuildingBlockExecution);
+ assertEquals(true, isSerializable);
+ }
+
+ public static boolean isSerializable(final Object o) {
final boolean retVal;
- if(implementsInterface(o))
- {
+ if (implementsInterface(o)) {
retVal = attemptToSerialize(o);
- }
- else
- {
+ } else {
retVal = false;
}
return (retVal);
}
- private static boolean implementsInterface(final Object o)
- {
+ private static boolean implementsInterface(final Object o) {
final boolean retVal;
retVal = ((o instanceof Serializable) || (o instanceof Externalizable));
@@ -92,34 +84,24 @@ public class SerializationTest {
return (retVal);
}
- private static boolean attemptToSerialize(final Object o)
- {
+ private static boolean attemptToSerialize(final Object o) {
final OutputStream sink;
ObjectOutputStream stream;
stream = null;
- try
- {
- sink = new ByteArrayOutputStream();
+ try {
+ sink = new ByteArrayOutputStream();
stream = new ObjectOutputStream(sink);
stream.writeObject(o);
// could also re-serilalize at this point too
- }
- catch(final IOException ex)
- {
+ } catch (final IOException ex) {
return (false);
- }
- finally
- {
- if(stream != null)
- {
- try
- {
+ } finally {
+ if (stream != null) {
+ try {
stream.close();
- }
- catch(final IOException ex)
- {
+ } catch (final IOException ex) {
// should not be able to happen
}
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/entities/exceptions/InvalidBuildingBlockInputExceptionTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/entities/exceptions/InvalidBuildingBlockInputExceptionTest.java
index 9d34a95e79..958eb069b8 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/entities/exceptions/InvalidBuildingBlockInputExceptionTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/entities/exceptions/InvalidBuildingBlockInputExceptionTest.java
@@ -21,47 +21,48 @@
package org.onap.so.bpmn.servicedecomposition.entities.exceptions;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
public class InvalidBuildingBlockInputExceptionTest {
- private static final String MESSAGE = "message";
- private static final Throwable CAUSE = new Throwable();
- private InvalidBuildingBlockInputException invalidBuildingBlockInputException;
-
- @Test
- public void defaultConstructorTest() {
- invalidBuildingBlockInputException = new InvalidBuildingBlockInputException();
- assertEquals(null, invalidBuildingBlockInputException.getMessage());
- assertEquals(null, invalidBuildingBlockInputException.getCause());
- }
-
- @Test
- public void messageConstructorTest() {
- invalidBuildingBlockInputException = new InvalidBuildingBlockInputException(MESSAGE);
- assertEquals(MESSAGE, invalidBuildingBlockInputException.getMessage());
- assertEquals(null, invalidBuildingBlockInputException.getCause());
- }
-
- @Test
- public void causeConstructorTest() {
- invalidBuildingBlockInputException = new InvalidBuildingBlockInputException(CAUSE);
- assertEquals(CAUSE.toString(), invalidBuildingBlockInputException.getMessage()); // CAUSE.toString because of the implementation of Exception(Throwable cause)
- assertEquals(CAUSE, invalidBuildingBlockInputException.getCause());
- }
-
- @Test
- public void messageAndCauseConstructorTest() {
- invalidBuildingBlockInputException = new InvalidBuildingBlockInputException(MESSAGE, CAUSE);
- assertEquals(MESSAGE, invalidBuildingBlockInputException.getMessage());
- assertEquals(CAUSE, invalidBuildingBlockInputException.getCause());
- }
-
- @Test
- public void messageAndCauseAndFlagsConstructorTest() {
- invalidBuildingBlockInputException = new InvalidBuildingBlockInputException(MESSAGE, CAUSE, true, true);
- assertEquals(MESSAGE, invalidBuildingBlockInputException.getMessage());
- assertEquals(CAUSE, invalidBuildingBlockInputException.getCause());
- }
+ private static final String MESSAGE = "message";
+ private static final Throwable CAUSE = new Throwable();
+ private InvalidBuildingBlockInputException invalidBuildingBlockInputException;
+
+ @Test
+ public void defaultConstructorTest() {
+ invalidBuildingBlockInputException = new InvalidBuildingBlockInputException();
+ assertEquals(null, invalidBuildingBlockInputException.getMessage());
+ assertEquals(null, invalidBuildingBlockInputException.getCause());
+ }
+
+ @Test
+ public void messageConstructorTest() {
+ invalidBuildingBlockInputException = new InvalidBuildingBlockInputException(MESSAGE);
+ assertEquals(MESSAGE, invalidBuildingBlockInputException.getMessage());
+ assertEquals(null, invalidBuildingBlockInputException.getCause());
+ }
+
+ @Test
+ public void causeConstructorTest() {
+ invalidBuildingBlockInputException = new InvalidBuildingBlockInputException(CAUSE);
+ assertEquals(CAUSE.toString(), invalidBuildingBlockInputException.getMessage()); // CAUSE.toString because of
+ // the implementation of
+ // Exception(Throwable cause)
+ assertEquals(CAUSE, invalidBuildingBlockInputException.getCause());
+ }
+
+ @Test
+ public void messageAndCauseConstructorTest() {
+ invalidBuildingBlockInputException = new InvalidBuildingBlockInputException(MESSAGE, CAUSE);
+ assertEquals(MESSAGE, invalidBuildingBlockInputException.getMessage());
+ assertEquals(CAUSE, invalidBuildingBlockInputException.getCause());
+ }
+
+ @Test
+ public void messageAndCauseAndFlagsConstructorTest() {
+ invalidBuildingBlockInputException = new InvalidBuildingBlockInputException(MESSAGE, CAUSE, true, true);
+ assertEquals(MESSAGE, invalidBuildingBlockInputException.getMessage());
+ assertEquals(CAUSE, invalidBuildingBlockInputException.getCause());
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayerTest.java
index 9ac148f5bd..e7afa9ec8b 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayerTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayerTest.java
@@ -26,7 +26,6 @@ import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@@ -34,7 +33,6 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.junit.Test;
import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
import org.onap.so.bpmn.servicedecomposition.bbobjects.Collection;
@@ -81,647 +79,665 @@ import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
import org.onap.so.db.catalog.beans.VnfcCustomization;
import org.onap.so.serviceinstancebeans.CloudConfiguration;
import org.onap.so.serviceinstancebeans.RequestDetails;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class BBInputSetupMapperLayerTest {
-
- BBInputSetupMapperLayer bbInputSetupMapperLayer = new BBInputSetupMapperLayer();
-
- ObjectMapper mapper = new ObjectMapper();
-
- private static final String RESOURCE_PATH = "src/test/resources/__files/ExecuteBuildingBlock/";
-
- @Test
- public void testMapOrchestrationStatusFromAAI() {
- OrchestrationStatus expected = OrchestrationStatus.INVENTORIED;
- String orchStatusInput = "Inventoried";
- OrchestrationStatus actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
- assertThat(actual, sameBeanAs(expected));
-
- expected = OrchestrationStatus.ASSIGNED;
- orchStatusInput = "Assigned";
- actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
- assertThat(actual, sameBeanAs(expected));
-
- expected = OrchestrationStatus.ACTIVE;
- orchStatusInput = "Active";
- actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
- assertThat(actual, sameBeanAs(expected));
-
- expected = OrchestrationStatus.CREATED;
- orchStatusInput = "Created";
- actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
- assertThat(actual, sameBeanAs(expected));
-
- expected = OrchestrationStatus.PRECREATED;
- orchStatusInput = "PreCreated";
- actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
- assertThat(actual, sameBeanAs(expected));
-
- expected = OrchestrationStatus.PENDING_CREATE;
- orchStatusInput = "PendingCreate";
- actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
- assertThat(actual, sameBeanAs(expected));
-
- expected = OrchestrationStatus.PENDING_DELETE;
- orchStatusInput = "PendingDelete";
- actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
- assertThat(actual, sameBeanAs(expected));
-
- expected = OrchestrationStatus.PENDING;
- orchStatusInput = "Pending";
- actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
- assertThat(actual, sameBeanAs(expected));
-
- expected = OrchestrationStatus.PENDING_ACTIVATION;
- orchStatusInput = "PendingActivation";
- actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapOrchestrationFuzzyCases() {
- List<String> values = Arrays.asList("pending-create", "pending_Create", "pendinggcreate", "PendingCreate");
- values.forEach(value -> {
- assertThat(bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(value), equalTo(OrchestrationStatus.PENDING_CREATE));
- });
- }
-
- @Test
- public void testMapAAICustomer() throws IOException {
- Customer expected = mapper.readValue(
- new File(RESOURCE_PATH+"Customer.json"),
- Customer.class);
-
- org.onap.aai.domain.yang.Customer customerAAI = mapper.readValue(
- new File(RESOURCE_PATH+"Customer_AAI.json"), org.onap.aai.domain.yang.Customer.class);
-
- Customer actual = bbInputSetupMapperLayer.mapAAICustomer(customerAAI);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapAAIServiceSubscription() throws IOException {
- ServiceSubscription expected = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceSubscriptionExpected.json"), ServiceSubscription.class);
-
- org.onap.aai.domain.yang.ServiceSubscription svcSubscriptionAAI = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceSubscription_AAI.json"), org.onap.aai.domain.yang.ServiceSubscription.class);
-
- ServiceSubscription actual = bbInputSetupMapperLayer.mapAAIServiceSubscription(svcSubscriptionAAI);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapAAIProject() throws IOException {
- Project expected = mapper.readValue(new File(RESOURCE_PATH+"Project.json"),Project.class);
-
- org.onap.aai.domain.yang.Project projectAAI = new org.onap.aai.domain.yang.Project();
- projectAAI.setProjectName("projectName");
-
- Project actual = bbInputSetupMapperLayer.mapAAIProject(projectAAI);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapRequestProject() throws IOException {
- Project expected = mapper.readValue(new File(RESOURCE_PATH+"Project.json"),Project.class);
-
- org.onap.so.serviceinstancebeans.Project requestProject = new org.onap.so.serviceinstancebeans.Project();
- requestProject.setProjectName("projectName");
-
- Project actual = bbInputSetupMapperLayer.mapRequestProject(requestProject);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapAAIOwningEntity() throws IOException {
- OwningEntity expected = mapper.readValue(new File(RESOURCE_PATH+"OwningEntity.json"),OwningEntity.class);
-
- org.onap.aai.domain.yang.OwningEntity entityAAI = new org.onap.aai.domain.yang.OwningEntity();
- entityAAI.setOwningEntityId("owningEntityId");
- entityAAI.setOwningEntityName("owningEntityName");
-
- OwningEntity actual = bbInputSetupMapperLayer.mapAAIOwningEntity(entityAAI);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapRequestOwningEntity() throws IOException {
- OwningEntity expected = mapper.readValue(new File(RESOURCE_PATH+"OwningEntity.json"),OwningEntity.class);
-
- org.onap.so.serviceinstancebeans.OwningEntity requestOwningEntity = new org.onap.so.serviceinstancebeans.OwningEntity();
- requestOwningEntity.setOwningEntityId("owningEntityId");
- requestOwningEntity.setOwningEntityName("owningEntityName");
-
- OwningEntity actual = bbInputSetupMapperLayer.mapRequestOwningEntity(requestOwningEntity);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapAAIPlatform() throws IOException {
- Platform expected = mapper.readValue(new File(RESOURCE_PATH+"Platform.json"),Platform.class);
-
- org.onap.aai.domain.yang.Platform platformAAI = new org.onap.aai.domain.yang.Platform();
- platformAAI.setPlatformName("platformName");
-
- Platform actual = bbInputSetupMapperLayer.mapAAIPlatform(platformAAI);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapAAILineOfBusiness() throws IOException {
- LineOfBusiness expected = mapper.readValue(new File(RESOURCE_PATH+"LineOfBusiness.json"),LineOfBusiness.class);
-
- org.onap.aai.domain.yang.LineOfBusiness lobAAI = new org.onap.aai.domain.yang.LineOfBusiness();
- lobAAI.setLineOfBusinessName("lineOfBusinessName");
-
- LineOfBusiness actual = bbInputSetupMapperLayer.mapAAILineOfBusiness(lobAAI);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapAAINetworkPolicy() throws JsonParseException, JsonMappingException, IOException {
- NetworkPolicy expectedNetworkPolicy = mapper.readValue(new File(RESOURCE_PATH + "NetworkPolicy.json"), NetworkPolicy.class);
-
- org.onap.aai.domain.yang.NetworkPolicy aaiNetworkPolicy = new org.onap.aai.domain.yang.NetworkPolicy();
- aaiNetworkPolicy.setNetworkPolicyId("networkPolicyId");
- aaiNetworkPolicy.setNetworkPolicyFqdn("networkPolicyFqdn");
- aaiNetworkPolicy.setHeatStackId("heatStackId");
- aaiNetworkPolicy.setResourceVersion("resourceVersion");
-
- NetworkPolicy actualNetworkPolicy = bbInputSetupMapperLayer.mapAAINetworkPolicy(aaiNetworkPolicy);
-
- assertThat(actualNetworkPolicy, sameBeanAs(expectedNetworkPolicy));
- }
-
- @Test
- public void testMapAAIVolumeGroup() throws JsonParseException, JsonMappingException, IOException {
- VolumeGroup expectedVolumeGroup = mapper.readValue(new File(RESOURCE_PATH + "VolumeGroup.json"), VolumeGroup.class);
-
- org.onap.aai.domain.yang.VolumeGroup aaiVolumeGroup = mapper.readValue(
- new File(RESOURCE_PATH + "VolumeGroup_AAI.json"), org.onap.aai.domain.yang.VolumeGroup.class);
-
- VolumeGroup actualVolumeGroup = bbInputSetupMapperLayer.mapAAIVolumeGroup(aaiVolumeGroup);
-
- assertThat(actualVolumeGroup, sameBeanAs(expectedVolumeGroup));
- }
-
- @Test
- public void testMapCatalogServiceIntoServiceInstance() throws IOException {
- ModelInfoServiceInstance expected = mapper.readValue(
- new File(RESOURCE_PATH + "ModelInfoServiceInstance.json"),
- ModelInfoServiceInstance.class);
-
- Service catalogService = mapper.readValue(
- new File(RESOURCE_PATH + "CatalogServiceInput.json"), Service.class);
-
- ModelInfoServiceInstance actual = bbInputSetupMapperLayer.mapCatalogServiceIntoServiceInstance(catalogService);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapCatalogInstanceGroupToInstanceGroup() throws IOException {
- ModelInfoInstanceGroup expected = mapper.readValue(
- new File(RESOURCE_PATH + "ModelInfoInstanceGroup.json"),
- ModelInfoInstanceGroup.class);
-
- InstanceGroup instanceGroup = mapper.readValue(
- new File(RESOURCE_PATH + "InstanceGroup.json"), InstanceGroup.class);
- instanceGroup.setCollectionInstanceGroupCustomizations(new ArrayList<>());
- CollectionResourceInstanceGroupCustomization collectionInstanceGroupCust = new CollectionResourceInstanceGroupCustomization();
- collectionInstanceGroupCust.setModelCustomizationUUID("modelCustomizationUUID");
- collectionInstanceGroupCust.setFunction("function");
- collectionInstanceGroupCust.setDescription("description");
- instanceGroup.getCollectionInstanceGroupCustomizations().add(collectionInstanceGroupCust);
- CollectionResourceCustomization collectionResourceCust = new CollectionResourceCustomization();
- collectionResourceCust.setModelCustomizationUUID("modelCustomizationUUID");
- ModelInfoInstanceGroup actual = bbInputSetupMapperLayer.mapCatalogInstanceGroupToInstanceGroup(collectionResourceCust, instanceGroup);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapCollectionNetworkResourceCustToNetworkResourceCust() {
- String modelCustomizationUUID = "modelCustomizationUUID";
- String modelInstanceName = "modelInstanceName";
- String networkRole = "networkRole";
- String networkScope = "networkScope";
- String networkTechnology = "networkTechnology";
- String networkType = "networkType";
-
- NetworkResourceCustomization expected = new NetworkResourceCustomization();
- expected.setModelCustomizationUUID(modelCustomizationUUID);
- expected.setModelInstanceName(modelInstanceName);
- expected.setNetworkRole(networkRole);
- expected.setNetworkScope(networkScope);
- expected.setNetworkTechnology(networkTechnology);
- expected.setNetworkType(networkType);
- CollectionNetworkResourceCustomization collectionNetworkResourceCust = new CollectionNetworkResourceCustomization();
- collectionNetworkResourceCust.setModelCustomizationUUID(modelCustomizationUUID);
- collectionNetworkResourceCust.setModelInstanceName(modelInstanceName);
- collectionNetworkResourceCust.setNetworkRole(networkRole);
- collectionNetworkResourceCust.setNetworkScope(networkScope);
- collectionNetworkResourceCust.setNetworkTechnology(networkTechnology);
- collectionNetworkResourceCust.setNetworkType(networkType);
- NetworkResourceCustomization actual = bbInputSetupMapperLayer.mapCollectionNetworkResourceCustToNetworkResourceCust(collectionNetworkResourceCust);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapCatalogCollectionToCollection() throws IOException {
- ModelInfoCollection expected = mapper.readValue(
- new File(RESOURCE_PATH + "ModelInfoCollection.json"),
- ModelInfoCollection.class);
-
- CollectionResourceCustomization collectionCust = mapper.readValue(
- new File(RESOURCE_PATH + "CollectionResourceCustomization.json"),
- CollectionResourceCustomization.class);
-
- CollectionResource collectionResource = mapper.readValue(
- new File(RESOURCE_PATH + "CollectionResource.json"),
- CollectionResource.class);
-
- ModelInfoCollection actual = bbInputSetupMapperLayer.mapCatalogCollectionToCollection(collectionCust, collectionResource);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapAAIServiceInstanceIntoServiceInstance() throws IOException {
- ServiceInstance expected = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceInstance_aaiServiceInstanceToSI.json"),
- ServiceInstance.class);
-
- org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceInstanceAAIInput.json"),
- org.onap.aai.domain.yang.ServiceInstance.class);
-
- ServiceInstance actual = bbInputSetupMapperLayer.mapAAIServiceInstanceIntoServiceInstance(serviceInstanceAAI);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testSetPlatformAndLOB() throws IOException {
- ServiceInstance expected = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceInstance_aaiPlatformAndLOBToSI.json"),
- ServiceInstance.class);
-
- Map<ResourceKey, String> resourcesToBeOrchestrated = new HashMap<>();
- resourcesToBeOrchestrated.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
- Platform platformMSO = new Platform();
- platformMSO.setPlatformName("platformName");
- LineOfBusiness lineOfBusinessMSO = new LineOfBusiness();
- lineOfBusinessMSO.setLineOfBusinessName("lineOfBusinessName");
-
- ServiceInstance actual = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceInstanceAAIPlatformAndLOBInput.json"),
- ServiceInstance.class);
-
- bbInputSetupMapperLayer.setPlatformAndLOBIntoServiceInstance(platformMSO, lineOfBusinessMSO, actual,
- resourcesToBeOrchestrated);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapAAIL3NetworkIntoL3Network() throws IOException {
- L3Network expected = mapper.readValue(
- new File(RESOURCE_PATH + "l3NetworkExpected.json"), L3Network.class);
-
- org.onap.aai.domain.yang.L3Network aaiL3Network = mapper.readValue(
- new File(RESOURCE_PATH + "aaiL3NetworkInput.json"),
- org.onap.aai.domain.yang.L3Network.class);
-
- L3Network actual = bbInputSetupMapperLayer.mapAAIL3Network(aaiL3Network);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapAAIGenericVnfIntoGenericVnf() throws IOException {
- GenericVnf expected = mapper.readValue(new File(RESOURCE_PATH + "GenericVnfExpected.json"), GenericVnf.class);
- org.onap.aai.domain.yang.GenericVnf aaiGenericVnf = mapper.readValue(
- new File(RESOURCE_PATH + "aaiGenericVnfInput.json"), org.onap.aai.domain.yang.GenericVnf.class);
-
- GenericVnf actual = bbInputSetupMapperLayer.mapAAIGenericVnfIntoGenericVnf(aaiGenericVnf);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapAAICollectionIntoCollection() throws JsonParseException, JsonMappingException, IOException {
- org.onap.aai.domain.yang.Collection aaiCollection = mapper.readValue(
- new File(RESOURCE_PATH + "CollectionInput.json"), org.onap.aai.domain.yang.Collection.class);
-
- Collection expectedCollection = mapper.readValue(new File(RESOURCE_PATH + "CollectionExpected.json"), Collection.class);
-
- Collection actualCollection = bbInputSetupMapperLayer.mapAAICollectionIntoCollection(aaiCollection);
-
- assertThat(actualCollection, sameBeanAs(expectedCollection));
- }
-
- @Test
- public void testMapAAIInstanceGroupIntoInstanceGroup() throws JsonParseException, JsonMappingException, IOException {
- org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = mapper.readValue(
- new File(RESOURCE_PATH + "InstanceGroupInput.json"), org.onap.aai.domain.yang.InstanceGroup.class);
-
- org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup expectedInstanceGroup = mapper.readValue(
- new File(RESOURCE_PATH + "InstanceGroupExpected.json"), org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup.class);
-
- org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup actualInstanceGroup =
- bbInputSetupMapperLayer.mapAAIInstanceGroupIntoInstanceGroup(aaiInstanceGroup);
-
- assertThat(actualInstanceGroup, sameBeanAs(expectedInstanceGroup));
- }
-
- @Test
- public void testMapAAIRouteTableReferenceIntoRouteTableReference() throws JsonParseException, JsonMappingException, IOException {
- org.onap.aai.domain.yang.RouteTableReference aaiRouteTableReference = mapper.readValue(
- new File(RESOURCE_PATH + "RouteTableReferenceInput.json"), org.onap.aai.domain.yang.RouteTableReference.class);
-
- RouteTableReference expectedRouteTableReference = mapper.readValue(
- new File(RESOURCE_PATH + "RouteTableReferenceExpected.json"), RouteTableReference.class);
-
- RouteTableReference actualRouteTableReference = bbInputSetupMapperLayer.mapAAIRouteTableReferenceIntoRouteTableReference(aaiRouteTableReference);
-
- assertThat(actualRouteTableReference, sameBeanAs(expectedRouteTableReference));
- }
-
- @Test
- public void testMapCatalogNetworkToNetwork() throws JsonParseException, JsonMappingException, IOException {
- NetworkResourceCustomization networkResourceCustomization = mapper.readValue(
- new File(RESOURCE_PATH + "NetworkResourceCustomizationInput.json"), NetworkResourceCustomization.class);
-
- ModelInfoNetwork expectedModelInfoNetwork = mapper.readValue(
- new File(RESOURCE_PATH + "ModelInfoNetworkExpected.json"), ModelInfoNetwork.class);
-
- ModelInfoNetwork actualModelInfoNetwork = bbInputSetupMapperLayer.mapCatalogNetworkToNetwork(networkResourceCustomization);
-
- assertThat(actualModelInfoNetwork, sameBeanAs(expectedModelInfoNetwork));
- }
-
- @Test
- public void testMapCatalogVnfToVnf() throws IOException {
- VnfResourceCustomization vnfResourceCustomization = mapper.readValue(
- new File(RESOURCE_PATH + "VnfResourceCustomizationInput.json"), VnfResourceCustomization.class);
-
- ModelInfoGenericVnf expectedModelInfoGenericVnf = mapper.readValue(
- new File(RESOURCE_PATH + "ModelInfoGenericVnfExpected.json"), ModelInfoGenericVnf.class);
-
- ModelInfoGenericVnf actualModelInfoGenericVnf = bbInputSetupMapperLayer.mapCatalogVnfToVnf(vnfResourceCustomization);
-
- assertThat(actualModelInfoGenericVnf, sameBeanAs(expectedModelInfoGenericVnf));
- }
-
- @Test
- public void testMapCatalogVfModuleToVfModule() throws JsonParseException, JsonMappingException, IOException {
- VfModuleCustomization vfResourceCustomization = mapper.readValue(
- new File(RESOURCE_PATH + "VfModuleCustomizationInput.json"), VfModuleCustomization.class);
-
- ModelInfoVfModule expectedModelInfoVfModule = mapper.readValue(new File(RESOURCE_PATH + "ModelInfoVfModuleExpected.json"), ModelInfoVfModule.class);
-
- ModelInfoVfModule actualModelInfoVfModule = bbInputSetupMapperLayer.mapCatalogVfModuleToVfModule(vfResourceCustomization);
-
- assertThat(actualModelInfoVfModule, sameBeanAs(expectedModelInfoVfModule));
- }
-
- @Test
- public void testMapRequestPlatform() throws JsonParseException, JsonMappingException, IOException {
- org.onap.so.serviceinstancebeans.Platform platform = mapper.readValue(
- new File(RESOURCE_PATH + "RequestPlatformInput.json"), org.onap.so.serviceinstancebeans.Platform.class);
-
- Platform expectedPlatform = mapper.readValue(new File(RESOURCE_PATH + "PlatformExpected.json"), Platform.class);
-
- Platform actualPlatform = bbInputSetupMapperLayer.mapRequestPlatform(platform);
-
- assertThat(actualPlatform, sameBeanAs(expectedPlatform));
- }
-
- @Test
- public void testMapRequestLineOfBusiness() throws JsonParseException, JsonMappingException, IOException {
- org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness = mapper.readValue(
- new File(RESOURCE_PATH + "RequestLineOfBusinessInput.json"), org.onap.so.serviceinstancebeans.LineOfBusiness.class);
-
- LineOfBusiness expectedLineOfBusiness = mapper.readValue(new File(RESOURCE_PATH + "LineOfBusinessExpected.json"), LineOfBusiness.class);
-
- LineOfBusiness actualLineOfBusiness = bbInputSetupMapperLayer.mapRequestLineOfBusiness(lineOfBusiness);
-
- assertThat(actualLineOfBusiness, sameBeanAs(expectedLineOfBusiness));
- }
-
- @Test
- public void testMapAAIConfiguration() throws JsonParseException, JsonMappingException, IOException {
- org.onap.aai.domain.yang.Configuration configurationAAI = mapper.readValue(
- new File(RESOURCE_PATH + "ConfigurationInput.json"), org.onap.aai.domain.yang.Configuration.class);
-
- Configuration expectedConfiguration = mapper.readValue(
- new File(RESOURCE_PATH + "ConfigurationExpected.json"), Configuration.class);
-
- Configuration actualConfiguration = bbInputSetupMapperLayer.mapAAIConfiguration(configurationAAI);
-
- assertThat(actualConfiguration, sameBeanAs(expectedConfiguration));
- }
-
- @Test
- public void testMapRequestContext() throws IOException {
- RequestContext expected = mapper.readValue(
- new File(RESOURCE_PATH + "RequestContextExpected.json"),
- RequestContext.class);
-
- RequestDetails requestDetails = mapper.readValue(
- new File(RESOURCE_PATH + "RequestDetailsInput_mapReqContext.json"),
- RequestDetails.class);
- RequestContext actual = bbInputSetupMapperLayer.mapRequestContext(requestDetails);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapOrchestrationContext() throws IOException {
- OrchestrationContext expected = new OrchestrationContext();
- expected.setIsRollbackEnabled(true);
-
- RequestDetails requestDetails = mapper.readValue(new File(RESOURCE_PATH + "RequestDetailsInput_mapReqContext.json"), RequestDetails.class);
-
- OrchestrationContext actual = bbInputSetupMapperLayer.mapOrchestrationContext(requestDetails);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapLocationContext() {
- CloudRegion expected = new CloudRegion();
- expected.setCloudOwner("test-owner-name");
- expected.setLcpCloudRegionId("cloudRegionId");
- expected.setComplex("complexName");
- expected.setTenantId("tenantId");
- CloudConfiguration cloudConfig = new CloudConfiguration();
- cloudConfig.setTenantId("tenantId");
- cloudConfig.setLcpCloudRegionId("cloudRegionId");
- cloudConfig.setAicNodeClli("aicNodeClli");
- org.onap.aai.domain.yang.CloudRegion cloudRegion = new org.onap.aai.domain.yang.CloudRegion();
- cloudRegion.setCloudOwner("test-owner-name");
- cloudRegion.setCloudRegionId("cloudRegionId");
- cloudRegion.setComplexName("complexName");
-
- CloudRegion actual = bbInputSetupMapperLayer.mapCloudRegion(cloudConfig, cloudRegion);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapCloudRegion() {
- CloudRegion expected = new CloudRegion();
- expected.setCloudOwner("test-owner-name");
- expected.setLcpCloudRegionId("cloudRegionId");
- expected.setTenantId("tenantId");
- expected.setCloudRegionVersion("cloudRegionVersion");
-
- CloudConfiguration cloudConfig = new CloudConfiguration();
- cloudConfig.setTenantId("tenantId");
- cloudConfig.setLcpCloudRegionId("cloudRegionId");
- cloudConfig.setAicNodeClli("aicNodeClli");
-
- org.onap.aai.domain.yang.CloudRegion cloudRegion = new org.onap.aai.domain.yang.CloudRegion();
- cloudRegion.setCloudOwner("test-owner-name");
- cloudRegion.setCloudRegionId("cloudRegionId");
- cloudRegion.setCloudRegionVersion("cloudRegionVersion");
-
- CloudRegion actual = bbInputSetupMapperLayer.mapCloudRegion(cloudConfig, cloudRegion);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapTenant() {
- Tenant expected = new Tenant();
- expected.setTenantId("tenantId");
- expected.setTenantName("tenantName");
- expected.setTenantContext("tenantContext");
-
- org.onap.aai.domain.yang.Tenant aaiTenant = new org.onap.aai.domain.yang.Tenant();
- aaiTenant.setTenantId("tenantId");
- aaiTenant.setTenantName("tenantName");
- aaiTenant.setTenantContext("tenantContext");
-
- Tenant actual = bbInputSetupMapperLayer.mapTenant(aaiTenant);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapCloudRegionWithNullCheck() {
- CloudRegion expected = new CloudRegion();
-
- CloudRegion actual = bbInputSetupMapperLayer.mapCloudRegion(null, null);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testmapCatalogConfigurationToConfiguration() {
- String modelCustUUID = "modelCustomizationUUID";
- String modelInvariantUUID = "modelInvariantUUID";
- String modelVersionUUID = "modelUUID";
- String policyName = "policyName";
- ModelInfoConfiguration expected = new ModelInfoConfiguration();
- expected.setModelCustomizationId(modelCustUUID);
- expected.setModelInvariantId(modelInvariantUUID);
- expected.setModelVersionId(modelVersionUUID);
- expected.setPolicyName(policyName);
- ConfigurationResourceCustomization configurationResourceCustomization = new ConfigurationResourceCustomization();
- configurationResourceCustomization.setModelCustomizationUUID(modelCustUUID);
- configurationResourceCustomization.setConfigurationResource(new ConfigurationResource());
- configurationResourceCustomization.getConfigurationResource().setModelInvariantUUID(modelInvariantUUID);
- configurationResourceCustomization.getConfigurationResource().setModelUUID(modelVersionUUID);
- CvnfcConfigurationCustomization policyNameTable = new CvnfcConfigurationCustomization();
- policyNameTable.setCvnfcCustomization(new CvnfcCustomization());
- policyNameTable.getCvnfcCustomization().setVnfcCustomization(new VnfcCustomization());
- policyNameTable.setPolicyName(policyName);
-
- ModelInfoConfiguration actual = bbInputSetupMapperLayer.mapCatalogConfigurationToConfiguration(configurationResourceCustomization, policyNameTable);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testmapCatalogConfigurationToFabricConfiguration() {
- String modelCustUUID = "modelCustomizationUUID";
- String modelInvariantUUID = "modelInvariantUUID";
- String modelVersionUUID = "modelUUID";
- String policyName = "policyName";
- ModelInfoConfiguration expected = new ModelInfoConfiguration();
- expected.setModelCustomizationId(modelCustUUID);
- expected.setModelInvariantId(modelInvariantUUID);
- expected.setModelVersionId(modelVersionUUID);
- expected.setPolicyName(policyName);
-
- CvnfcConfigurationCustomization fabricCustomization = new CvnfcConfigurationCustomization();
- fabricCustomization.setCvnfcCustomization(new CvnfcCustomization());
- fabricCustomization.getCvnfcCustomization().setVnfcCustomization(new VnfcCustomization());
- fabricCustomization.setPolicyName(policyName);
- fabricCustomization.setModelCustomizationUUID(modelCustUUID);
-
- ConfigurationResource configurationResource = new ConfigurationResource();
- configurationResource.setModelUUID(modelVersionUUID);
- configurationResource.setModelInvariantUUID(modelInvariantUUID);
- fabricCustomization.setConfigurationResource(configurationResource);
-
- ModelInfoConfiguration actual = bbInputSetupMapperLayer.mapCatalogConfigurationToConfiguration(fabricCustomization);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapNameValueUserParams() throws IOException {
- RequestDetails requestDetails = mapper.readValue(new File(RESOURCE_PATH + "RequestDetailsInput_mapReqContext.json"), RequestDetails.class);
- Map<String,Object> actual = bbInputSetupMapperLayer.mapNameValueUserParams(requestDetails.getRequestParameters());
-
- assertTrue(actual.containsKey("mns_vfw_protected_route_prefixes"));
- assertTrue(actual.get("mns_vfw_protected_route_prefixes").toString().contains("interface_route_table_routes_route"));
- assertTrue(actual.get("mns_vfw_protected_route_prefixes").toString().contains("1.1.1.1/32"));
- assertTrue(actual.get("mns_vfw_protected_route_prefixes").toString().contains("0::1/128"));
- assertTrue(actual.containsKey("name1"));
- assertTrue(actual.containsValue("value1"));
- assertTrue(actual.get("name1").equals("value1"));
-
- assertFalse(actual.containsKey("ignore"));
- assertFalse(actual.containsValue("ignore"));
- }
-
- @Test
- public void testMapRequestParameters() throws IOException {
- RequestDetails requestDetails = mapper.readValue(new File(RESOURCE_PATH + "RequestDetailsInput_mapReqContext.json"), RequestDetails.class);
- RequestParameters actual = bbInputSetupMapperLayer.mapRequestParameters(requestDetails.getRequestParameters());
-
- assertEquals(actual.getUsePreload(), requestDetails.getRequestParameters().getUsePreload());
- assertEquals(actual.getSubscriptionServiceType(), requestDetails.getRequestParameters().getSubscriptionServiceType());
- assertEquals(actual.getPayload(), requestDetails.getRequestParameters().getPayload());
- }
-
- protected RequestParameters mapRequestParameters(org.onap.so.serviceinstancebeans.RequestParameters requestParameters) {
- RequestParameters requestParams = new RequestParameters();
- requestParams.setaLaCarte(requestParameters.getALaCarte());
- requestParams.setUsePreload(requestParameters.getUsePreload());
- requestParams.setSubscriptionServiceType(requestParameters.getSubscriptionServiceType());
- requestParams.setUserParams(requestParameters.getUserParams());
- requestParams.setPayload(requestParameters.getPayload());
- return requestParams;
- }
-
+
+ BBInputSetupMapperLayer bbInputSetupMapperLayer = new BBInputSetupMapperLayer();
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ private static final String RESOURCE_PATH = "src/test/resources/__files/ExecuteBuildingBlock/";
+
+ @Test
+ public void testMapOrchestrationStatusFromAAI() {
+ OrchestrationStatus expected = OrchestrationStatus.INVENTORIED;
+ String orchStatusInput = "Inventoried";
+ OrchestrationStatus actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
+ assertThat(actual, sameBeanAs(expected));
+
+ expected = OrchestrationStatus.ASSIGNED;
+ orchStatusInput = "Assigned";
+ actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
+ assertThat(actual, sameBeanAs(expected));
+
+ expected = OrchestrationStatus.ACTIVE;
+ orchStatusInput = "Active";
+ actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
+ assertThat(actual, sameBeanAs(expected));
+
+ expected = OrchestrationStatus.CREATED;
+ orchStatusInput = "Created";
+ actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
+ assertThat(actual, sameBeanAs(expected));
+
+ expected = OrchestrationStatus.PRECREATED;
+ orchStatusInput = "PreCreated";
+ actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
+ assertThat(actual, sameBeanAs(expected));
+
+ expected = OrchestrationStatus.PENDING_CREATE;
+ orchStatusInput = "PendingCreate";
+ actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
+ assertThat(actual, sameBeanAs(expected));
+
+ expected = OrchestrationStatus.PENDING_DELETE;
+ orchStatusInput = "PendingDelete";
+ actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
+ assertThat(actual, sameBeanAs(expected));
+
+ expected = OrchestrationStatus.PENDING;
+ orchStatusInput = "Pending";
+ actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
+ assertThat(actual, sameBeanAs(expected));
+
+ expected = OrchestrationStatus.PENDING_ACTIVATION;
+ orchStatusInput = "PendingActivation";
+ actual = bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(orchStatusInput);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapOrchestrationFuzzyCases() {
+ List<String> values = Arrays.asList("pending-create", "pending_Create", "pendinggcreate", "PendingCreate");
+ values.forEach(value -> {
+ assertThat(bbInputSetupMapperLayer.mapOrchestrationStatusFromAAI(value),
+ equalTo(OrchestrationStatus.PENDING_CREATE));
+ });
+ }
+
+ @Test
+ public void testMapAAICustomer() throws IOException {
+ Customer expected = mapper.readValue(new File(RESOURCE_PATH + "Customer.json"), Customer.class);
+
+ org.onap.aai.domain.yang.Customer customerAAI = mapper.readValue(new File(RESOURCE_PATH + "Customer_AAI.json"),
+ org.onap.aai.domain.yang.Customer.class);
+
+ Customer actual = bbInputSetupMapperLayer.mapAAICustomer(customerAAI);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapAAIServiceSubscription() throws IOException {
+ ServiceSubscription expected = mapper.readValue(new File(RESOURCE_PATH + "ServiceSubscriptionExpected.json"),
+ ServiceSubscription.class);
+
+ org.onap.aai.domain.yang.ServiceSubscription svcSubscriptionAAI =
+ mapper.readValue(new File(RESOURCE_PATH + "ServiceSubscription_AAI.json"),
+ org.onap.aai.domain.yang.ServiceSubscription.class);
+
+ ServiceSubscription actual = bbInputSetupMapperLayer.mapAAIServiceSubscription(svcSubscriptionAAI);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapAAIProject() throws IOException {
+ Project expected = mapper.readValue(new File(RESOURCE_PATH + "Project.json"), Project.class);
+
+ org.onap.aai.domain.yang.Project projectAAI = new org.onap.aai.domain.yang.Project();
+ projectAAI.setProjectName("projectName");
+
+ Project actual = bbInputSetupMapperLayer.mapAAIProject(projectAAI);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapRequestProject() throws IOException {
+ Project expected = mapper.readValue(new File(RESOURCE_PATH + "Project.json"), Project.class);
+
+ org.onap.so.serviceinstancebeans.Project requestProject = new org.onap.so.serviceinstancebeans.Project();
+ requestProject.setProjectName("projectName");
+
+ Project actual = bbInputSetupMapperLayer.mapRequestProject(requestProject);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapAAIOwningEntity() throws IOException {
+ OwningEntity expected = mapper.readValue(new File(RESOURCE_PATH + "OwningEntity.json"), OwningEntity.class);
+
+ org.onap.aai.domain.yang.OwningEntity entityAAI = new org.onap.aai.domain.yang.OwningEntity();
+ entityAAI.setOwningEntityId("owningEntityId");
+ entityAAI.setOwningEntityName("owningEntityName");
+
+ OwningEntity actual = bbInputSetupMapperLayer.mapAAIOwningEntity(entityAAI);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapRequestOwningEntity() throws IOException {
+ OwningEntity expected = mapper.readValue(new File(RESOURCE_PATH + "OwningEntity.json"), OwningEntity.class);
+
+ org.onap.so.serviceinstancebeans.OwningEntity requestOwningEntity =
+ new org.onap.so.serviceinstancebeans.OwningEntity();
+ requestOwningEntity.setOwningEntityId("owningEntityId");
+ requestOwningEntity.setOwningEntityName("owningEntityName");
+
+ OwningEntity actual = bbInputSetupMapperLayer.mapRequestOwningEntity(requestOwningEntity);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapAAIPlatform() throws IOException {
+ Platform expected = mapper.readValue(new File(RESOURCE_PATH + "Platform.json"), Platform.class);
+
+ org.onap.aai.domain.yang.Platform platformAAI = new org.onap.aai.domain.yang.Platform();
+ platformAAI.setPlatformName("platformName");
+
+ Platform actual = bbInputSetupMapperLayer.mapAAIPlatform(platformAAI);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapAAILineOfBusiness() throws IOException {
+ LineOfBusiness expected =
+ mapper.readValue(new File(RESOURCE_PATH + "LineOfBusiness.json"), LineOfBusiness.class);
+
+ org.onap.aai.domain.yang.LineOfBusiness lobAAI = new org.onap.aai.domain.yang.LineOfBusiness();
+ lobAAI.setLineOfBusinessName("lineOfBusinessName");
+
+ LineOfBusiness actual = bbInputSetupMapperLayer.mapAAILineOfBusiness(lobAAI);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapAAINetworkPolicy() throws JsonParseException, JsonMappingException, IOException {
+ NetworkPolicy expectedNetworkPolicy =
+ mapper.readValue(new File(RESOURCE_PATH + "NetworkPolicy.json"), NetworkPolicy.class);
+
+ org.onap.aai.domain.yang.NetworkPolicy aaiNetworkPolicy = new org.onap.aai.domain.yang.NetworkPolicy();
+ aaiNetworkPolicy.setNetworkPolicyId("networkPolicyId");
+ aaiNetworkPolicy.setNetworkPolicyFqdn("networkPolicyFqdn");
+ aaiNetworkPolicy.setHeatStackId("heatStackId");
+ aaiNetworkPolicy.setResourceVersion("resourceVersion");
+
+ NetworkPolicy actualNetworkPolicy = bbInputSetupMapperLayer.mapAAINetworkPolicy(aaiNetworkPolicy);
+
+ assertThat(actualNetworkPolicy, sameBeanAs(expectedNetworkPolicy));
+ }
+
+ @Test
+ public void testMapAAIVolumeGroup() throws JsonParseException, JsonMappingException, IOException {
+ VolumeGroup expectedVolumeGroup =
+ mapper.readValue(new File(RESOURCE_PATH + "VolumeGroup.json"), VolumeGroup.class);
+
+ org.onap.aai.domain.yang.VolumeGroup aaiVolumeGroup = mapper.readValue(
+ new File(RESOURCE_PATH + "VolumeGroup_AAI.json"), org.onap.aai.domain.yang.VolumeGroup.class);
+
+ VolumeGroup actualVolumeGroup = bbInputSetupMapperLayer.mapAAIVolumeGroup(aaiVolumeGroup);
+
+ assertThat(actualVolumeGroup, sameBeanAs(expectedVolumeGroup));
+ }
+
+ @Test
+ public void testMapCatalogServiceIntoServiceInstance() throws IOException {
+ ModelInfoServiceInstance expected = mapper.readValue(new File(RESOURCE_PATH + "ModelInfoServiceInstance.json"),
+ ModelInfoServiceInstance.class);
+
+ Service catalogService = mapper.readValue(new File(RESOURCE_PATH + "CatalogServiceInput.json"), Service.class);
+
+ ModelInfoServiceInstance actual = bbInputSetupMapperLayer.mapCatalogServiceIntoServiceInstance(catalogService);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapCatalogInstanceGroupToInstanceGroup() throws IOException {
+ ModelInfoInstanceGroup expected =
+ mapper.readValue(new File(RESOURCE_PATH + "ModelInfoInstanceGroup.json"), ModelInfoInstanceGroup.class);
+
+ InstanceGroup instanceGroup =
+ mapper.readValue(new File(RESOURCE_PATH + "InstanceGroup.json"), InstanceGroup.class);
+ instanceGroup.setCollectionInstanceGroupCustomizations(new ArrayList<>());
+ CollectionResourceInstanceGroupCustomization collectionInstanceGroupCust =
+ new CollectionResourceInstanceGroupCustomization();
+ collectionInstanceGroupCust.setModelCustomizationUUID("modelCustomizationUUID");
+ collectionInstanceGroupCust.setFunction("function");
+ collectionInstanceGroupCust.setDescription("description");
+ instanceGroup.getCollectionInstanceGroupCustomizations().add(collectionInstanceGroupCust);
+ CollectionResourceCustomization collectionResourceCust = new CollectionResourceCustomization();
+ collectionResourceCust.setModelCustomizationUUID("modelCustomizationUUID");
+ ModelInfoInstanceGroup actual =
+ bbInputSetupMapperLayer.mapCatalogInstanceGroupToInstanceGroup(collectionResourceCust, instanceGroup);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapCollectionNetworkResourceCustToNetworkResourceCust() {
+ String modelCustomizationUUID = "modelCustomizationUUID";
+ String modelInstanceName = "modelInstanceName";
+ String networkRole = "networkRole";
+ String networkScope = "networkScope";
+ String networkTechnology = "networkTechnology";
+ String networkType = "networkType";
+
+ NetworkResourceCustomization expected = new NetworkResourceCustomization();
+ expected.setModelCustomizationUUID(modelCustomizationUUID);
+ expected.setModelInstanceName(modelInstanceName);
+ expected.setNetworkRole(networkRole);
+ expected.setNetworkScope(networkScope);
+ expected.setNetworkTechnology(networkTechnology);
+ expected.setNetworkType(networkType);
+ CollectionNetworkResourceCustomization collectionNetworkResourceCust =
+ new CollectionNetworkResourceCustomization();
+ collectionNetworkResourceCust.setModelCustomizationUUID(modelCustomizationUUID);
+ collectionNetworkResourceCust.setModelInstanceName(modelInstanceName);
+ collectionNetworkResourceCust.setNetworkRole(networkRole);
+ collectionNetworkResourceCust.setNetworkScope(networkScope);
+ collectionNetworkResourceCust.setNetworkTechnology(networkTechnology);
+ collectionNetworkResourceCust.setNetworkType(networkType);
+ NetworkResourceCustomization actual = bbInputSetupMapperLayer
+ .mapCollectionNetworkResourceCustToNetworkResourceCust(collectionNetworkResourceCust);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapCatalogCollectionToCollection() throws IOException {
+ ModelInfoCollection expected =
+ mapper.readValue(new File(RESOURCE_PATH + "ModelInfoCollection.json"), ModelInfoCollection.class);
+
+ CollectionResourceCustomization collectionCust =
+ mapper.readValue(new File(RESOURCE_PATH + "CollectionResourceCustomization.json"),
+ CollectionResourceCustomization.class);
+
+ CollectionResource collectionResource =
+ mapper.readValue(new File(RESOURCE_PATH + "CollectionResource.json"), CollectionResource.class);
+
+ ModelInfoCollection actual =
+ bbInputSetupMapperLayer.mapCatalogCollectionToCollection(collectionCust, collectionResource);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapAAIServiceInstanceIntoServiceInstance() throws IOException {
+ ServiceInstance expected = mapper.readValue(
+ new File(RESOURCE_PATH + "ServiceInstance_aaiServiceInstanceToSI.json"), ServiceInstance.class);
+
+ org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI =
+ mapper.readValue(new File(RESOURCE_PATH + "ServiceInstanceAAIInput.json"),
+ org.onap.aai.domain.yang.ServiceInstance.class);
+
+ ServiceInstance actual = bbInputSetupMapperLayer.mapAAIServiceInstanceIntoServiceInstance(serviceInstanceAAI);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testSetPlatformAndLOB() throws IOException {
+ ServiceInstance expected = mapper.readValue(
+ new File(RESOURCE_PATH + "ServiceInstance_aaiPlatformAndLOBToSI.json"), ServiceInstance.class);
+
+ Map<ResourceKey, String> resourcesToBeOrchestrated = new HashMap<>();
+ resourcesToBeOrchestrated.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
+ Platform platformMSO = new Platform();
+ platformMSO.setPlatformName("platformName");
+ LineOfBusiness lineOfBusinessMSO = new LineOfBusiness();
+ lineOfBusinessMSO.setLineOfBusinessName("lineOfBusinessName");
+
+ ServiceInstance actual = mapper.readValue(
+ new File(RESOURCE_PATH + "ServiceInstanceAAIPlatformAndLOBInput.json"), ServiceInstance.class);
+
+ bbInputSetupMapperLayer.setPlatformAndLOBIntoServiceInstance(platformMSO, lineOfBusinessMSO, actual,
+ resourcesToBeOrchestrated);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapAAIL3NetworkIntoL3Network() throws IOException {
+ L3Network expected = mapper.readValue(new File(RESOURCE_PATH + "l3NetworkExpected.json"), L3Network.class);
+
+ org.onap.aai.domain.yang.L3Network aaiL3Network = mapper.readValue(
+ new File(RESOURCE_PATH + "aaiL3NetworkInput.json"), org.onap.aai.domain.yang.L3Network.class);
+
+ L3Network actual = bbInputSetupMapperLayer.mapAAIL3Network(aaiL3Network);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapAAIGenericVnfIntoGenericVnf() throws IOException {
+ GenericVnf expected = mapper.readValue(new File(RESOURCE_PATH + "GenericVnfExpected.json"), GenericVnf.class);
+ org.onap.aai.domain.yang.GenericVnf aaiGenericVnf = mapper.readValue(
+ new File(RESOURCE_PATH + "aaiGenericVnfInput.json"), org.onap.aai.domain.yang.GenericVnf.class);
+
+ GenericVnf actual = bbInputSetupMapperLayer.mapAAIGenericVnfIntoGenericVnf(aaiGenericVnf);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapAAICollectionIntoCollection() throws JsonParseException, JsonMappingException, IOException {
+ org.onap.aai.domain.yang.Collection aaiCollection = mapper
+ .readValue(new File(RESOURCE_PATH + "CollectionInput.json"), org.onap.aai.domain.yang.Collection.class);
+
+ Collection expectedCollection =
+ mapper.readValue(new File(RESOURCE_PATH + "CollectionExpected.json"), Collection.class);
+
+ Collection actualCollection = bbInputSetupMapperLayer.mapAAICollectionIntoCollection(aaiCollection);
+
+ assertThat(actualCollection, sameBeanAs(expectedCollection));
+ }
+
+ @Test
+ public void testMapAAIInstanceGroupIntoInstanceGroup()
+ throws JsonParseException, JsonMappingException, IOException {
+ org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = mapper.readValue(
+ new File(RESOURCE_PATH + "InstanceGroupInput.json"), org.onap.aai.domain.yang.InstanceGroup.class);
+
+ org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup expectedInstanceGroup =
+ mapper.readValue(new File(RESOURCE_PATH + "InstanceGroupExpected.json"),
+ org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup.class);
+
+ org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup actualInstanceGroup =
+ bbInputSetupMapperLayer.mapAAIInstanceGroupIntoInstanceGroup(aaiInstanceGroup);
+
+ assertThat(actualInstanceGroup, sameBeanAs(expectedInstanceGroup));
+ }
+
+ @Test
+ public void testMapAAIRouteTableReferenceIntoRouteTableReference()
+ throws JsonParseException, JsonMappingException, IOException {
+ org.onap.aai.domain.yang.RouteTableReference aaiRouteTableReference =
+ mapper.readValue(new File(RESOURCE_PATH + "RouteTableReferenceInput.json"),
+ org.onap.aai.domain.yang.RouteTableReference.class);
+
+ RouteTableReference expectedRouteTableReference = mapper
+ .readValue(new File(RESOURCE_PATH + "RouteTableReferenceExpected.json"), RouteTableReference.class);
+
+ RouteTableReference actualRouteTableReference =
+ bbInputSetupMapperLayer.mapAAIRouteTableReferenceIntoRouteTableReference(aaiRouteTableReference);
+
+ assertThat(actualRouteTableReference, sameBeanAs(expectedRouteTableReference));
+ }
+
+ @Test
+ public void testMapCatalogNetworkToNetwork() throws JsonParseException, JsonMappingException, IOException {
+ NetworkResourceCustomization networkResourceCustomization = mapper.readValue(
+ new File(RESOURCE_PATH + "NetworkResourceCustomizationInput.json"), NetworkResourceCustomization.class);
+
+ ModelInfoNetwork expectedModelInfoNetwork =
+ mapper.readValue(new File(RESOURCE_PATH + "ModelInfoNetworkExpected.json"), ModelInfoNetwork.class);
+
+ ModelInfoNetwork actualModelInfoNetwork =
+ bbInputSetupMapperLayer.mapCatalogNetworkToNetwork(networkResourceCustomization);
+
+ assertThat(actualModelInfoNetwork, sameBeanAs(expectedModelInfoNetwork));
+ }
+
+ @Test
+ public void testMapCatalogVnfToVnf() throws IOException {
+ VnfResourceCustomization vnfResourceCustomization = mapper.readValue(
+ new File(RESOURCE_PATH + "VnfResourceCustomizationInput.json"), VnfResourceCustomization.class);
+
+ ModelInfoGenericVnf expectedModelInfoGenericVnf = mapper
+ .readValue(new File(RESOURCE_PATH + "ModelInfoGenericVnfExpected.json"), ModelInfoGenericVnf.class);
+
+ ModelInfoGenericVnf actualModelInfoGenericVnf =
+ bbInputSetupMapperLayer.mapCatalogVnfToVnf(vnfResourceCustomization);
+
+ assertThat(actualModelInfoGenericVnf, sameBeanAs(expectedModelInfoGenericVnf));
+ }
+
+ @Test
+ public void testMapCatalogVfModuleToVfModule() throws JsonParseException, JsonMappingException, IOException {
+ VfModuleCustomization vfResourceCustomization = mapper
+ .readValue(new File(RESOURCE_PATH + "VfModuleCustomizationInput.json"), VfModuleCustomization.class);
+
+ ModelInfoVfModule expectedModelInfoVfModule =
+ mapper.readValue(new File(RESOURCE_PATH + "ModelInfoVfModuleExpected.json"), ModelInfoVfModule.class);
+
+ ModelInfoVfModule actualModelInfoVfModule =
+ bbInputSetupMapperLayer.mapCatalogVfModuleToVfModule(vfResourceCustomization);
+
+ assertThat(actualModelInfoVfModule, sameBeanAs(expectedModelInfoVfModule));
+ }
+
+ @Test
+ public void testMapRequestPlatform() throws JsonParseException, JsonMappingException, IOException {
+ org.onap.so.serviceinstancebeans.Platform platform = mapper.readValue(
+ new File(RESOURCE_PATH + "RequestPlatformInput.json"), org.onap.so.serviceinstancebeans.Platform.class);
+
+ Platform expectedPlatform = mapper.readValue(new File(RESOURCE_PATH + "PlatformExpected.json"), Platform.class);
+
+ Platform actualPlatform = bbInputSetupMapperLayer.mapRequestPlatform(platform);
+
+ assertThat(actualPlatform, sameBeanAs(expectedPlatform));
+ }
+
+ @Test
+ public void testMapRequestLineOfBusiness() throws JsonParseException, JsonMappingException, IOException {
+ org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness =
+ mapper.readValue(new File(RESOURCE_PATH + "RequestLineOfBusinessInput.json"),
+ org.onap.so.serviceinstancebeans.LineOfBusiness.class);
+
+ LineOfBusiness expectedLineOfBusiness =
+ mapper.readValue(new File(RESOURCE_PATH + "LineOfBusinessExpected.json"), LineOfBusiness.class);
+
+ LineOfBusiness actualLineOfBusiness = bbInputSetupMapperLayer.mapRequestLineOfBusiness(lineOfBusiness);
+
+ assertThat(actualLineOfBusiness, sameBeanAs(expectedLineOfBusiness));
+ }
+
+ @Test
+ public void testMapAAIConfiguration() throws JsonParseException, JsonMappingException, IOException {
+ org.onap.aai.domain.yang.Configuration configurationAAI = mapper.readValue(
+ new File(RESOURCE_PATH + "ConfigurationInput.json"), org.onap.aai.domain.yang.Configuration.class);
+
+ Configuration expectedConfiguration =
+ mapper.readValue(new File(RESOURCE_PATH + "ConfigurationExpected.json"), Configuration.class);
+
+ Configuration actualConfiguration = bbInputSetupMapperLayer.mapAAIConfiguration(configurationAAI);
+
+ assertThat(actualConfiguration, sameBeanAs(expectedConfiguration));
+ }
+
+ @Test
+ public void testMapRequestContext() throws IOException {
+ RequestContext expected =
+ mapper.readValue(new File(RESOURCE_PATH + "RequestContextExpected.json"), RequestContext.class);
+
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_mapReqContext.json"), RequestDetails.class);
+ RequestContext actual = bbInputSetupMapperLayer.mapRequestContext(requestDetails);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapOrchestrationContext() throws IOException {
+ OrchestrationContext expected = new OrchestrationContext();
+ expected.setIsRollbackEnabled(true);
+
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_mapReqContext.json"), RequestDetails.class);
+
+ OrchestrationContext actual = bbInputSetupMapperLayer.mapOrchestrationContext(requestDetails);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapLocationContext() {
+ CloudRegion expected = new CloudRegion();
+ expected.setCloudOwner("test-owner-name");
+ expected.setLcpCloudRegionId("cloudRegionId");
+ expected.setComplex("complexName");
+ expected.setTenantId("tenantId");
+ CloudConfiguration cloudConfig = new CloudConfiguration();
+ cloudConfig.setTenantId("tenantId");
+ cloudConfig.setLcpCloudRegionId("cloudRegionId");
+ cloudConfig.setAicNodeClli("aicNodeClli");
+ org.onap.aai.domain.yang.CloudRegion cloudRegion = new org.onap.aai.domain.yang.CloudRegion();
+ cloudRegion.setCloudOwner("test-owner-name");
+ cloudRegion.setCloudRegionId("cloudRegionId");
+ cloudRegion.setComplexName("complexName");
+
+ CloudRegion actual = bbInputSetupMapperLayer.mapCloudRegion(cloudConfig, cloudRegion);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapCloudRegion() {
+ CloudRegion expected = new CloudRegion();
+ expected.setCloudOwner("test-owner-name");
+ expected.setLcpCloudRegionId("cloudRegionId");
+ expected.setTenantId("tenantId");
+ expected.setCloudRegionVersion("cloudRegionVersion");
+
+ CloudConfiguration cloudConfig = new CloudConfiguration();
+ cloudConfig.setTenantId("tenantId");
+ cloudConfig.setLcpCloudRegionId("cloudRegionId");
+ cloudConfig.setAicNodeClli("aicNodeClli");
+
+ org.onap.aai.domain.yang.CloudRegion cloudRegion = new org.onap.aai.domain.yang.CloudRegion();
+ cloudRegion.setCloudOwner("test-owner-name");
+ cloudRegion.setCloudRegionId("cloudRegionId");
+ cloudRegion.setCloudRegionVersion("cloudRegionVersion");
+
+ CloudRegion actual = bbInputSetupMapperLayer.mapCloudRegion(cloudConfig, cloudRegion);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapTenant() {
+ Tenant expected = new Tenant();
+ expected.setTenantId("tenantId");
+ expected.setTenantName("tenantName");
+ expected.setTenantContext("tenantContext");
+
+ org.onap.aai.domain.yang.Tenant aaiTenant = new org.onap.aai.domain.yang.Tenant();
+ aaiTenant.setTenantId("tenantId");
+ aaiTenant.setTenantName("tenantName");
+ aaiTenant.setTenantContext("tenantContext");
+
+ Tenant actual = bbInputSetupMapperLayer.mapTenant(aaiTenant);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapCloudRegionWithNullCheck() {
+ CloudRegion expected = new CloudRegion();
+
+ CloudRegion actual = bbInputSetupMapperLayer.mapCloudRegion(null, null);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testmapCatalogConfigurationToConfiguration() {
+ String modelCustUUID = "modelCustomizationUUID";
+ String modelInvariantUUID = "modelInvariantUUID";
+ String modelVersionUUID = "modelUUID";
+ String policyName = "policyName";
+ ModelInfoConfiguration expected = new ModelInfoConfiguration();
+ expected.setModelCustomizationId(modelCustUUID);
+ expected.setModelInvariantId(modelInvariantUUID);
+ expected.setModelVersionId(modelVersionUUID);
+ expected.setPolicyName(policyName);
+ ConfigurationResourceCustomization configurationResourceCustomization =
+ new ConfigurationResourceCustomization();
+ configurationResourceCustomization.setModelCustomizationUUID(modelCustUUID);
+ configurationResourceCustomization.setConfigurationResource(new ConfigurationResource());
+ configurationResourceCustomization.getConfigurationResource().setModelInvariantUUID(modelInvariantUUID);
+ configurationResourceCustomization.getConfigurationResource().setModelUUID(modelVersionUUID);
+ CvnfcConfigurationCustomization policyNameTable = new CvnfcConfigurationCustomization();
+ policyNameTable.setCvnfcCustomization(new CvnfcCustomization());
+ policyNameTable.getCvnfcCustomization().setVnfcCustomization(new VnfcCustomization());
+ policyNameTable.setPolicyName(policyName);
+
+ ModelInfoConfiguration actual = bbInputSetupMapperLayer
+ .mapCatalogConfigurationToConfiguration(configurationResourceCustomization, policyNameTable);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testmapCatalogConfigurationToFabricConfiguration() {
+ String modelCustUUID = "modelCustomizationUUID";
+ String modelInvariantUUID = "modelInvariantUUID";
+ String modelVersionUUID = "modelUUID";
+ String policyName = "policyName";
+ ModelInfoConfiguration expected = new ModelInfoConfiguration();
+ expected.setModelCustomizationId(modelCustUUID);
+ expected.setModelInvariantId(modelInvariantUUID);
+ expected.setModelVersionId(modelVersionUUID);
+ expected.setPolicyName(policyName);
+
+ CvnfcConfigurationCustomization fabricCustomization = new CvnfcConfigurationCustomization();
+ fabricCustomization.setCvnfcCustomization(new CvnfcCustomization());
+ fabricCustomization.getCvnfcCustomization().setVnfcCustomization(new VnfcCustomization());
+ fabricCustomization.setPolicyName(policyName);
+ fabricCustomization.setModelCustomizationUUID(modelCustUUID);
+
+ ConfigurationResource configurationResource = new ConfigurationResource();
+ configurationResource.setModelUUID(modelVersionUUID);
+ configurationResource.setModelInvariantUUID(modelInvariantUUID);
+ fabricCustomization.setConfigurationResource(configurationResource);
+
+ ModelInfoConfiguration actual =
+ bbInputSetupMapperLayer.mapCatalogConfigurationToConfiguration(fabricCustomization);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapNameValueUserParams() throws IOException {
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_mapReqContext.json"), RequestDetails.class);
+ Map<String, Object> actual =
+ bbInputSetupMapperLayer.mapNameValueUserParams(requestDetails.getRequestParameters());
+
+ assertTrue(actual.containsKey("mns_vfw_protected_route_prefixes"));
+ assertTrue(actual.get("mns_vfw_protected_route_prefixes").toString()
+ .contains("interface_route_table_routes_route"));
+ assertTrue(actual.get("mns_vfw_protected_route_prefixes").toString().contains("1.1.1.1/32"));
+ assertTrue(actual.get("mns_vfw_protected_route_prefixes").toString().contains("0::1/128"));
+ assertTrue(actual.containsKey("name1"));
+ assertTrue(actual.containsValue("value1"));
+ assertTrue(actual.get("name1").equals("value1"));
+
+ assertFalse(actual.containsKey("ignore"));
+ assertFalse(actual.containsValue("ignore"));
+ }
+
+ @Test
+ public void testMapRequestParameters() throws IOException {
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_mapReqContext.json"), RequestDetails.class);
+ RequestParameters actual = bbInputSetupMapperLayer.mapRequestParameters(requestDetails.getRequestParameters());
+
+ assertEquals(actual.getUsePreload(), requestDetails.getRequestParameters().getUsePreload());
+ assertEquals(actual.getSubscriptionServiceType(),
+ requestDetails.getRequestParameters().getSubscriptionServiceType());
+ assertEquals(actual.getPayload(), requestDetails.getRequestParameters().getPayload());
+ }
+
+ protected RequestParameters mapRequestParameters(
+ org.onap.so.serviceinstancebeans.RequestParameters requestParameters) {
+ RequestParameters requestParams = new RequestParameters();
+ requestParams.setaLaCarte(requestParameters.getALaCarte());
+ requestParams.setUsePreload(requestParameters.getUsePreload());
+ requestParams.setSubscriptionServiceType(requestParameters.getSubscriptionServiceType());
+ requestParams.setUserParams(requestParameters.getUserParams());
+ requestParams.setPayload(requestParameters.getPayload());
+ return requestParams;
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java
index 8d0b2f60e1..ad1918e6da 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java
@@ -34,7 +34,6 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@@ -43,7 +42,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.junit.Assert;
import org.junit.Before;
@@ -116,2624 +114,2684 @@ import org.onap.so.serviceinstancebeans.RequestInfo;
import org.onap.so.serviceinstancebeans.RequestParameters;
import org.onap.so.serviceinstancebeans.Resources;
import org.onap.so.serviceinstancebeans.SubscriberInfo;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
+
@RunWith(MockitoJUnitRunner.class)
public class BBInputSetupTest {
- private static final String RESOURCE_PATH = "src/test/resources/__files/ExecuteBuildingBlock/";
-
- protected ObjectMapper mapper = new ObjectMapper();
- private static final String CLOUD_OWNER = "CloudOwner";
-
- @Spy
- private BBInputSetup SPY_bbInputSetup = new BBInputSetup();
-
- @Mock
- private BBInputSetupUtils SPY_bbInputSetupUtils;
-
- @Mock
- private CloudInfoFromAAI SPY_cloudInfoFromAAI;
-
- @Spy
- private BBInputSetupMapperLayer bbInputSetupMapperLayer;
-
- @Before
- public void setup(){
- SPY_bbInputSetup.setBbInputSetupUtils(SPY_bbInputSetupUtils);
- SPY_bbInputSetup.setMapperLayer(bbInputSetupMapperLayer);
- SPY_bbInputSetup.setCloudInfoFromAAI(SPY_cloudInfoFromAAI);
- }
-
- @Test
- public void testGetVolumeGroupIdRelatedToVfModule() {
- String expected = "volumeGroupId";
- String modelCustomizationId = "modelCustomizationId";
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelCustomizationId(modelCustomizationId);
- String cloudOwner = "cloudOwner";
- String cloudRegionId = "cloudRegionId";
- String volumeGroupId = "volumeGroupId";
- GenericVnf vnf = new GenericVnf();
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId(expected);
- vnf.getVolumeGroups().add(volumeGroup);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, null);
- org.onap.aai.domain.yang.VolumeGroup aaiVolumeGroup = new org.onap.aai.domain.yang.VolumeGroup();
- aaiVolumeGroup.setModelCustomizationId(modelCustomizationId);
- doReturn(aaiVolumeGroup).when(SPY_bbInputSetupUtils).getAAIVolumeGroup(cloudOwner, cloudRegionId, volumeGroupId);
-
- Optional<String> actual = SPY_bbInputSetup.getVolumeGroupIdRelatedToVfModule(vnf, modelInfo, cloudOwner, cloudRegionId, lookupKeyMap);
-
- assertEquals(expected, actual.get());
- }
-
- @Test
- public void testGetAlaCarteServiceInstance() throws Exception {
- ServiceInstance expected = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
- ServiceInstance.class);
- RequestDetails requestDetails = new RequestDetails();
- RequestInfo requestInfo = new RequestInfo();
- requestInfo.setInstanceName("SharansInstanceName");
- requestDetails.setRequestInfo(requestInfo);
- Customer customer = new Customer();
- String serviceInstanceId = "SharansInstanceId";
- boolean aLaCarte = true;
- Service service = new Service();
- service.setModelUUID("modelUUID");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelUuid("modelUUID");
- expected.setModelInfoServiceInstance(modelInfoServiceInstance);
- org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
- serviceInstanceAAI.setModelVersionId("modelUUIDDifferent");
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String bbName = AssignFlows.SERVICE_INSTANCE.toString();
- Service differentService = new Service();
- differentService.setModelUUID("modelUUIDDifferent");
-
- doReturn(expected).when(SPY_bbInputSetup).getServiceInstanceHelper(requestDetails, customer, null, null,
- lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
- doReturn(serviceInstanceAAI).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(serviceInstanceId);
- doReturn(differentService).when(SPY_bbInputSetupUtils)
- .getCatalogServiceByModelUUID(serviceInstanceAAI.getModelVersionId());
- doReturn(expected.getModelInfoServiceInstance()).when(bbInputSetupMapperLayer)
- .mapCatalogServiceIntoServiceInstance(differentService);
-
- ServiceInstance actual = SPY_bbInputSetup.getALaCarteServiceInstance(service, requestDetails, customer, null,
- null, lookupKeyMap, serviceInstanceId, aLaCarte, bbName);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test(expected = Exception.class)
- public void testGetAlaCarteServiceInstanceException() throws Exception {
- ServiceInstance expected = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
- ServiceInstance.class);
- RequestDetails requestDetails = new RequestDetails();
- RequestInfo requestInfo = new RequestInfo();
- requestInfo.setInstanceName("SharansInstanceName");
- requestDetails.setRequestInfo(requestInfo);
- Customer customer = new Customer();
- String serviceInstanceId = "SharansInstanceId";
- boolean aLaCarte = true;
- Service service = new Service();
- service.setModelUUID("modelUUID");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelUuid("modelUUID");
- expected.setModelInfoServiceInstance(modelInfoServiceInstance);
- org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
- serviceInstanceAAI.setModelVersionId("modelUUIDDifferent");
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String bbName = AssignFlows.SERVICE_INSTANCE.toString();
- Service differentService = new Service();
- differentService.setModelUUID("modelUUIDDifferent");
-
- doReturn(expected).when(SPY_bbInputSetup).getServiceInstanceHelper(requestDetails, customer, null, null,
- lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
- doReturn(serviceInstanceAAI).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(serviceInstanceId);
- doReturn(null).when(SPY_bbInputSetupUtils)
- .getCatalogServiceByModelUUID(serviceInstanceAAI.getModelVersionId());
-
- ServiceInstance actual = SPY_bbInputSetup.getALaCarteServiceInstance(service, requestDetails, customer, null,
- null, lookupKeyMap, serviceInstanceId, aLaCarte, bbName);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetCustomerAndServiceSubscription() throws JsonParseException, JsonMappingException, IOException {
- RequestDetails requestDetails = mapper.readValue(
- new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
- SubscriberInfo subscriberInfo = new SubscriberInfo();
- subscriberInfo.setGlobalSubscriberId("globalSubscriberId");
- RequestParameters requestParams = new RequestParameters();
- requestParams.setSubscriptionServiceType("subscriptionServiceType");
- requestDetails.setRequestParameters(requestParams);
- requestDetails.setSubscriberInfo(subscriberInfo);
- String resourceId = "resourceId";
- Customer expected = new Customer();
- expected.setGlobalCustomerId("globalCustomerId");
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- serviceSubscription.setServiceType("subscriptionServiceType");
-
- doReturn(expected).when(this.SPY_bbInputSetup).getCustomerFromRequest(requestDetails);
- doReturn(serviceSubscription).when(this.SPY_bbInputSetup).getServiceSubscription(requestDetails, expected);
-
- Customer actual = this.SPY_bbInputSetup.getCustomerAndServiceSubscription(requestDetails, resourceId);
-
- assertThat(actual, sameBeanAs(expected));
-
- requestDetails.setSubscriberInfo(null);
-
-
- assertThat(actual, sameBeanAs(expected));
-
- }
-
- @Test
- public void testSetHomingFlag() throws JsonParseException, JsonMappingException, IOException {
- GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
- GenericVnf genericVnfExpected = new GenericVnf();
- genericVnfExpected.setVnfId("vnfId");
- genericVnfExpected.setCallHoming(true);
- expected.getCustomer().getServiceSubscription().getServiceInstances().get(0).getVnfs().add(genericVnfExpected);
- boolean homing = true;
- GenericVnf genericVnfActual = new GenericVnf();
- genericVnfActual.setVnfId("vnfId");
- genericVnfActual.setCallHoming(false);
- GeneralBuildingBlock actual = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- actual.getCustomer().getServiceSubscription().getServiceInstances().get(0).getVnfs().add(genericVnfActual);
-
- SPY_bbInputSetup.setHomingFlag(actual, homing, lookupKeyMap);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetExecuteBBFromExecution() throws IOException {
- ExecuteBuildingBlock expected = new ExecuteBuildingBlock();
- BuildingBlock bb = new BuildingBlock();
- bb.setBpmnFlowName("AssignServiceInstanceBB");
- expected.setBuildingBlock(bb);
- expected.setRequestId("00032ab7-3fb3-42e5-965d-8ea592502017");
- DelegateExecution execution = Mockito.mock(DelegateExecution.class);
- doReturn(expected).when(execution).getVariable(any(String.class));
- ExecuteBuildingBlock actual = SPY_bbInputSetup.getExecuteBBFromExecution(execution);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetGBB() throws Exception {
- GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
-
- ExecuteBuildingBlock executeBB = new ExecuteBuildingBlock();
- executeBB.setRequestId("requestId");
- RequestDetails requestDetails = new RequestDetails();
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelType(ModelType.service);
- requestDetails.setModelInfo(modelInfo);
- RequestParameters requestParams = new RequestParameters();
- requestParams.setaLaCarte(true);
- requestDetails.setRequestParameters(requestParams);
- doReturn(requestDetails).when(SPY_bbInputSetupUtils).getRequestDetails(executeBB.getRequestId());
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String resourceId = "123";
- String requestAction = "createInstance";
- doReturn(expected).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
- requestAction, resourceId);
- doNothing().when(SPY_bbInputSetup).populateLookupKeyMapWithIds(executeBB.getWorkflowResourceIds(),lookupKeyMap);
- boolean aLaCarte = true;
- GeneralBuildingBlock actual = SPY_bbInputSetup.getGBB(executeBB, lookupKeyMap, requestAction, aLaCarte,
- resourceId, null);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetGBBCM() throws Exception {
- GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockCMExpected.json"),
- GeneralBuildingBlock.class);
-
- ExecuteBuildingBlock executeBB = new ExecuteBuildingBlock();
- executeBB.setRequestId("requestId");
- RequestDetails requestDetails = new RequestDetails();
- requestDetails.setModelInfo(null);
- RequestParameters requestParams = new RequestParameters();
- requestParams.setaLaCarte(true);
- requestDetails.setRequestParameters(requestParams);
- RequestInfo requestInfo = new RequestInfo();
- requestInfo.setSuppressRollback(true);
- requestInfo.setSource("VID");
- requestDetails.setRequestInfo(requestInfo);
- CloudConfiguration cloudConfiguration = new CloudConfiguration();
- cloudConfiguration.setLcpCloudRegionId("myRegionId");
- requestDetails.setCloudConfiguration(cloudConfiguration);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String resourceId = "123";
- String requestAction = "createInstance";
-
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnf-001");
-
- doReturn(new org.onap.aai.domain.yang.GenericVnf()).when(SPY_bbInputSetupUtils).getAAIGenericVnf(ArgumentMatchers.isA(String.class));
- doReturn(null).when(bbInputSetupMapperLayer).mapAAIGenericVnfIntoGenericVnf(ArgumentMatchers.isA(org.onap.aai.domain.yang.GenericVnf.class));
- GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBCM(executeBB, requestDetails, lookupKeyMap, requestAction,
- resourceId);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetGBBCMAddMembersAction() throws Exception {
- GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockInstanceGroupExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper.readValue(
- new File(RESOURCE_PATH + "RequestDetailsInput_instanceGroupAddMembers.json"), RequestDetails.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String requestAction = "addMembers";
- String instanceGroupId = "instance-group-001";
-
- WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
- workflowResourceIds.setInstanceGroupId(instanceGroupId);
- executeBB.setWorkflowResourceIds(workflowResourceIds);
-
- lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, instanceGroupId);
-
- org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = new org.onap.aai.domain.yang.InstanceGroup();
- aaiInstanceGroup.setId(instanceGroupId);
- aaiInstanceGroup.setInstanceGroupName("test instance group 1");
-
- org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
- aaiServiceInstance.setServiceInstanceId("service-instance-001");
- aaiServiceInstance.setServiceInstanceName("test service instance 1");
- Optional<org.onap.aai.domain.yang.ServiceInstance> optSI = Optional.of(aaiServiceInstance);
-
- org.onap.aai.domain.yang.GenericVnf vnf1 = new org.onap.aai.domain.yang.GenericVnf();
- vnf1.setVnfId("vnf-001");
- vnf1.setVnfName("test vnf 1");
-
- org.onap.aai.domain.yang.GenericVnf vnf2 = new org.onap.aai.domain.yang.GenericVnf();
- vnf2.setVnfId("vnf-002");
- vnf2.setVnfName("test vnf 2");
-
- doReturn(aaiInstanceGroup).when(SPY_bbInputSetupUtils).getAAIInstanceGroup(instanceGroupId);
- doReturn(optSI).when(SPY_bbInputSetupUtils).getRelatedServiceInstanceFromInstanceGroup(instanceGroupId);
- doReturn(vnf1).when(SPY_bbInputSetupUtils).getAAIGenericVnf("vnf-001");
- doReturn(vnf2).when(SPY_bbInputSetupUtils).getAAIGenericVnf("vnf-002");
-
- GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBCM(executeBB, requestDetails, lookupKeyMap,
- requestAction, instanceGroupId);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetGBBALaCarteNonService() throws Exception {
- GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper.readValue(
- new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String requestAction = "createInstance";
- Service service = Mockito.mock(Service.class);
- ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class);
- String resourceId = "123";
- String vnfType = "vnfType";
- org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
- aaiServiceInstance.setModelVersionId("modelVersionId");
- org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "instanceId");
- doReturn(service).when(SPY_bbInputSetupUtils).getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
- doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("instanceId");
-
- doNothing().when(SPY_bbInputSetup).populateObjectsOnAssignAndCreateFlows(requestDetails, service, "bbName",
- serviceInstance, lookupKeyMap, resourceId, vnfType, null, null);
- doReturn(serviceInstance).when(SPY_bbInputSetup).getExistingServiceInstance(aaiServiceInstance);
- doReturn(expected).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
- executeBB, requestAction, null);
-
- GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap,
- requestAction, resourceId, vnfType);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test(expected = Exception.class)
- public void testGetGBBALaCarteNonServiceWithoutServiceModelInfo() throws Exception {
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper.readValue(
- new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String requestAction = "createInstance";
- org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
- aaiServiceInstance.setModelVersionId("modelVersionId");
- String resourceId = "123";
- String vnfType = "vnfType";
-
- SPY_bbInputSetup.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId,
- vnfType);
- }
-
- @Test
- public void testGetGBBALaCarteNonServiceWithoutRelatedInstances() throws Exception {
- GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper.readValue(
- new File(RESOURCE_PATH + "RequestDetailsInput_withoutRelatedInstanceList.json"), RequestDetails.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String requestAction = "createInstance";
- Service service = Mockito.mock(Service.class);
- String resourceId = "123";
- ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class);
- org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
- aaiServiceInstance.setModelVersionId("modelVersionId");
- org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
- String vnfType = "vnfType";
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "instanceId");
- doReturn(service).when(SPY_bbInputSetupUtils).getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
- doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("instanceId");
-
- doNothing().when(SPY_bbInputSetup).populateObjectsOnAssignAndCreateFlows(requestDetails, service, "bbName",
- serviceInstance, lookupKeyMap, resourceId, vnfType, null, null);
-
- doReturn(serviceInstance).when(SPY_bbInputSetup).getExistingServiceInstance(aaiServiceInstance);
- doReturn(expected).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
- executeBB, requestAction,null);
-
- GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap,
- requestAction, resourceId, vnfType);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetGBBALaCarteService() throws Exception {
- GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper.readValue(
- new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
-
- org.onap.so.serviceinstancebeans.Project requestProject = new org.onap.so.serviceinstancebeans.Project();
- org.onap.so.serviceinstancebeans.OwningEntity requestOwningEntity = new org.onap.so.serviceinstancebeans.OwningEntity();
- requestDetails.setProject(requestProject);
- requestDetails.setOwningEntity(requestOwningEntity);
-
- Service service = Mockito.mock(Service.class);
- Customer customer = Mockito.mock(Customer.class);
- ServiceSubscription serviceSubscription = Mockito.mock(ServiceSubscription.class);
- Project project = Mockito.mock(Project.class);
- OwningEntity owningEntity = Mockito.mock(OwningEntity.class);
- ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class);
- String resourceId = "123";
- String requestAction = "createInstance";
- executeBB.setaLaCarte(true);
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.SERVICE_INSTANCE.toString());
- org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
-
- doReturn(service).when(SPY_bbInputSetupUtils)
- .getCatalogServiceByModelUUID(requestDetails.getModelInfo().getModelVersionId());
- doReturn(project).when(bbInputSetupMapperLayer).mapRequestProject(requestDetails.getProject());
- doReturn(owningEntity).when(bbInputSetupMapperLayer)
- .mapRequestOwningEntity(requestDetails.getOwningEntity());
-
- doReturn(customer).when(SPY_bbInputSetup).getCustomerAndServiceSubscription(requestDetails, resourceId);
- doReturn(serviceInstance).when(SPY_bbInputSetup).getALaCarteServiceInstance(service, requestDetails, customer,
- project, owningEntity, lookupKeyMap, resourceId, Boolean.TRUE.equals(executeBB.isaLaCarte()),
- executeBB.getBuildingBlock().getBpmnFlowName());
- doReturn(expected).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
- executeBB, requestAction, customer);
-
- GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
- requestAction, resourceId);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetGBBALaCarteServiceFindServiceByModelVersionId() throws Exception {
- GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper.readValue(
- new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
-
- org.onap.so.serviceinstancebeans.Project requestProject = new org.onap.so.serviceinstancebeans.Project();
- org.onap.so.serviceinstancebeans.OwningEntity requestOwningEntity = new org.onap.so.serviceinstancebeans.OwningEntity();
- requestDetails.setProject(requestProject);
- requestDetails.setOwningEntity(requestOwningEntity);
-
- Service service = Mockito.mock(Service.class);
- Customer customer = Mockito.mock(Customer.class);
- ServiceSubscription serviceSubscription = Mockito.mock(ServiceSubscription.class);
- Project project = Mockito.mock(Project.class);
- OwningEntity owningEntity = Mockito.mock(OwningEntity.class);
- ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class);
- String resourceId = "123";
- String requestAction = "createInstance";
- executeBB.setaLaCarte(true);
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.SERVICE_INSTANCE.toString());
- org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
-
- doReturn(null).when(SPY_bbInputSetupUtils)
- .getCatalogServiceByModelUUID(requestDetails.getModelInfo().getModelVersionId());
- doReturn(service).when(SPY_bbInputSetupUtils).getCatalogServiceByModelVersionAndModelInvariantUUID(
- requestDetails.getModelInfo().getModelVersion(), requestDetails.getModelInfo().getModelInvariantId());
- doReturn(project).when(bbInputSetupMapperLayer).mapRequestProject(requestDetails.getProject());
- doReturn(owningEntity).when(bbInputSetupMapperLayer)
- .mapRequestOwningEntity(requestDetails.getOwningEntity());
-
- doReturn(customer).when(SPY_bbInputSetup).getCustomerAndServiceSubscription(requestDetails, resourceId);
- doReturn(serviceInstance).when(SPY_bbInputSetup).getALaCarteServiceInstance(service, requestDetails, customer,
- project, owningEntity, lookupKeyMap, resourceId, Boolean.TRUE.equals(executeBB.isaLaCarte()),
- executeBB.getBuildingBlock().getBpmnFlowName());
- doReturn(expected).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
- executeBB, requestAction,customer);
-
- GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
- requestAction, resourceId);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetGBBALaCarteServiceNoProjectNoOE() throws Exception {
- GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper.readValue(
- new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
-
- Service service = Mockito.mock(Service.class);
- Customer customer = Mockito.mock(Customer.class);
- ServiceSubscription serviceSubscription = Mockito.mock(ServiceSubscription.class);
- ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class);
- String resourceId = "123";
- String requestAction = "createInstance";
- executeBB.setaLaCarte(true);
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.SERVICE_INSTANCE.toString());
- org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
-
- Map<String, String> uriKeys = new HashMap<>();
- uriKeys.put("global-customer-id", "globalCustomerId");
- uriKeys.put("service-type", "serviceType");
-
- doReturn(service).when(SPY_bbInputSetupUtils)
- .getCatalogServiceByModelUUID(requestDetails.getModelInfo().getModelVersionId());
-
- doReturn(customer).when(SPY_bbInputSetup).getCustomerAndServiceSubscription(requestDetails, resourceId);
-
- doReturn(serviceInstance).when(SPY_bbInputSetup).getALaCarteServiceInstance(service, requestDetails, customer,
- null, null, lookupKeyMap, resourceId, Boolean.TRUE.equals(executeBB.isaLaCarte()),
- executeBB.getBuildingBlock().getBpmnFlowName());
- doReturn(expected).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
- executeBB, requestAction,customer);
-
- GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
- requestAction, resourceId);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetServiceInstanceHelperCreateScenario() throws Exception {
- RequestDetails requestDetails = new RequestDetails();
- RequestInfo requestInfo = new RequestInfo();
- requestInfo.setInstanceName("SharansInstanceName");
- requestDetails.setRequestInfo(requestInfo);
- Customer customer = new Customer();
- String serviceInstanceId = "SharansInstanceId";
- boolean aLaCarte = true;
- ServiceInstance expected = new ServiceInstance();
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- Service service = new Service();
- service.setModelUUID("modelUUID");
- String bbName = AssignFlows.SERVICE_INSTANCE.toString();
-
- doReturn(null).when(SPY_bbInputSetupUtils).getAAIServiceInstanceByName(requestInfo.getInstanceName(), customer);
- doReturn(null).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(serviceInstanceId);
-
-
- doReturn(expected).when(SPY_bbInputSetup).createServiceInstance(requestDetails, null, null,
- lookupKeyMap, serviceInstanceId);
-
- ServiceInstance actual = SPY_bbInputSetup.getServiceInstanceHelper(requestDetails, customer, null, null,
- lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetServiceInstanceHelperCreateScenarioExisting() throws Exception {
- RequestDetails requestDetails = new RequestDetails();
- RequestInfo requestInfo = new RequestInfo();
- requestInfo.setInstanceName("SharansInstanceName");
- requestDetails.setRequestInfo(requestInfo);
- Customer customer = new Customer();
- String serviceInstanceId = "SharansInstanceId";
- boolean aLaCarte = true;
- Service service = new Service();
- service.setModelUUID("modelUUID");
- ServiceInstance expected = new ServiceInstance();
- org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
- serviceInstanceAAI.setModelVersionId("modelUUID");
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String bbName = AssignFlows.SERVICE_INSTANCE.toString();
-
- doReturn(serviceInstanceAAI).when(SPY_bbInputSetupUtils)
- .getAAIServiceInstanceByName(requestInfo.getInstanceName(), customer);
- doReturn(expected).when(SPY_bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
-
- ServiceInstance actual = SPY_bbInputSetup.getServiceInstanceHelper(requestDetails, customer, null, null,
- lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetServiceInstanceHelperCreateScenarioExistingNoNameButWithId() throws Exception {
- RequestDetails requestDetails = new RequestDetails();
- RequestInfo requestInfo = new RequestInfo();
- requestInfo.setInstanceName("SharansInstanceName");
- requestDetails.setRequestInfo(requestInfo);
- Customer customer = new Customer();
- String serviceInstanceId = "SharansInstanceId";
- boolean aLaCarte = true;
- Service service = new Service();
- service.setModelUUID("modelUUID");
- ServiceInstance expected = new ServiceInstance();
- org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
- serviceInstanceAAI.setModelVersionId("modelUUID");
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String bbName = "ActivateServiceInstanceBB";
-
- doReturn(serviceInstanceAAI).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(serviceInstanceId);
- doReturn(expected).when(SPY_bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
-
- ServiceInstance actual = SPY_bbInputSetup.getServiceInstanceHelper(requestDetails, customer, null, null,
- lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetServiceInstanceHelperCreateScenarioExistingNoNameButWithIdDifferentModel() throws Exception {
- RequestDetails requestDetails = new RequestDetails();
- RequestInfo requestInfo = new RequestInfo();
- requestDetails.setRequestInfo(requestInfo);
- Customer customer = new Customer();
- String serviceInstanceId = "SharansInstanceId";
- boolean aLaCarte = true;
- Service service = new Service();
- service.setModelUUID("modelUUID");
- ServiceInstance expected = new ServiceInstance();
- org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
- serviceInstanceAAI.setModelVersionId("modelUUIDDifferent");
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String bbName = "ActivateServiceInstanceBB";
- Service differentService = new Service();
- differentService.setModelUUID("modelUUIDDifferent");
-
- doReturn(serviceInstanceAAI).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(serviceInstanceId);
-
-
- ServiceInstance actual = SPY_bbInputSetup.getServiceInstanceHelper(requestDetails, customer, null, null,
- lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test(expected = Exception.class)
- public void testGetServiceInstanceHelperCreateScenarioExistingNoNameButWithIdExceptionThrown() throws Exception {
- RequestDetails requestDetails = new RequestDetails();
- RequestInfo requestInfo = new RequestInfo();
- requestDetails.setRequestInfo(requestInfo);
- Customer customer = new Customer();
- String serviceInstanceId = "SharansInstanceId";
- boolean aLaCarte = true;
- Service service = new Service();
- service.setModelUUID("modelUUID");
- org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
- serviceInstanceAAI.setModelVersionId("modelUUIDDifferent");
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String bbName = AssignFlows.SERVICE_INSTANCE.toString();
-
- ServiceInstance actual = SPY_bbInputSetup.getServiceInstanceHelper(requestDetails, customer, null, null,
- lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
- }
-
- @Test
- public void testPopulateObjectsOnAssignAndCreateFlows() throws Exception {
- String bbName = AssignFlows.SERVICE_INSTANCE.toString();
- String instanceName = "instanceName";
- String vnfType = "vnfType";
- String resourceId = "networkId";
- String productFamilyId = "productFamilyId";
- Service service = Mockito.mock(Service.class);
- ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class);
- RequestDetails requestDetails = Mockito.mock(RequestDetails.class);
- ModelInfo modelInfo = Mockito.mock(ModelInfo.class);
- RequestInfo requestInfo = Mockito.mock(RequestInfo.class);
- RelatedInstanceList[] relatedInstanceList = new RelatedInstanceList[] {};
- CloudConfiguration cloudConfiguration = new CloudConfiguration();
- org.onap.so.serviceinstancebeans.Platform platform = Mockito
- .mock(org.onap.so.serviceinstancebeans.Platform.class);
- org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness = Mockito
- .mock(org.onap.so.serviceinstancebeans.LineOfBusiness.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
-
- doNothing().when(SPY_bbInputSetup).populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance,
- lookupKeyMap, resourceId, null);
- doReturn(modelInfo).when(requestDetails).getModelInfo();
- doReturn(productFamilyId).when(requestInfo).getProductFamilyId();
- doReturn(requestInfo).when(requestDetails).getRequestInfo();
- doReturn(instanceName).when(requestInfo).getInstanceName();
- doReturn(platform).when(requestDetails).getPlatform();
- doReturn(lineOfBusiness).when(requestDetails).getLineOfBusiness();
- doReturn(relatedInstanceList).when(requestDetails).getRelatedInstanceList();
- doReturn(cloudConfiguration).when(requestDetails).getCloudConfiguration();
-
- doReturn(ModelType.network).when(modelInfo).getModelType();
- SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(requestDetails, service, bbName, serviceInstance,
- lookupKeyMap, resourceId, vnfType, null, null);
- verify(SPY_bbInputSetup, times(1)).populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance,
- lookupKeyMap, resourceId, null);
- assertEquals("NetworkId populated", true, lookupKeyMap.get(ResourceKey.NETWORK_ID).equalsIgnoreCase(resourceId));
-
- doReturn(ModelType.vnf).when(modelInfo).getModelType();
- resourceId = "vnfId";
- doNothing().when(SPY_bbInputSetup).populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness,
- service, bbName, serviceInstance, lookupKeyMap, relatedInstanceList, resourceId, vnfType, null, productFamilyId);
- SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(requestDetails, service, bbName, serviceInstance,
- lookupKeyMap, resourceId, vnfType, null, null);
- verify(SPY_bbInputSetup, times(1)).populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness,
- service, bbName, serviceInstance, lookupKeyMap, relatedInstanceList, resourceId, vnfType, null, productFamilyId);
- assertEquals("VnfId populated", true, lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID).equalsIgnoreCase(resourceId));
-
- doReturn(ModelType.volumeGroup).when(modelInfo).getModelType();
- resourceId = "volumeGroupId";
- doNothing().when(SPY_bbInputSetup).populateVolumeGroup(modelInfo, service, bbName, serviceInstance,
- lookupKeyMap, resourceId, relatedInstanceList, instanceName, vnfType, null);
- SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(requestDetails, service, bbName, serviceInstance,
- lookupKeyMap, resourceId, vnfType, null, null);
- verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(modelInfo, service, bbName, serviceInstance,
- lookupKeyMap, resourceId, relatedInstanceList, instanceName, vnfType, null);
- assertEquals("VolumeGroupId populated", true, lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID).equalsIgnoreCase(resourceId));
-
- doReturn(ModelType.vfModule).when(modelInfo).getModelType();
- resourceId = "vfModuleId";
- doNothing().when(SPY_bbInputSetup).populateVfModule(modelInfo, service, bbName, serviceInstance, lookupKeyMap,
- resourceId, relatedInstanceList, instanceName, null, cloudConfiguration);
- SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(requestDetails, service, bbName, serviceInstance,
- lookupKeyMap, resourceId, vnfType, null, null);
- verify(SPY_bbInputSetup, times(1)).populateVfModule(modelInfo, service, bbName, serviceInstance, lookupKeyMap,
- resourceId, relatedInstanceList, instanceName, null, cloudConfiguration);
- assertEquals("VfModuleId populated", true, lookupKeyMap.get(ResourceKey.VF_MODULE_ID).equalsIgnoreCase(resourceId));
- }
-
- @Test
- public void testPopulateGBBWithSIAndAdditionalInfo() throws Exception {
- GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpectedWUserParamsInfo.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper.readValue(
- new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
- RequestContext requestContext = mapper.readValue(new File(RESOURCE_PATH + "RequestContextExpected.json"),
- RequestContext.class);
- ServiceInstance serviceInstance = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
- ServiceInstance.class);
- CloudConfiguration cloudConfiguration = new CloudConfiguration();
- cloudConfiguration.setTenantId("tenantId");
- requestDetails.setCloudConfiguration(cloudConfiguration);
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(false);
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setCloudOwner("test-owner-name");
- cloudRegion.setLcpCloudRegionId("lcpCloudRegionId");
- cloudRegion.setComplex("complexName");
- cloudRegion.setTenantId("tenantId");
-
- Map<String, String> uriKeys = new HashMap<>();
- uriKeys.put("global-customer-id","global-customer-id");
- uriKeys.put("service-type","service-type");
-
- Customer customer = new Customer();
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- serviceSubscription.setServiceType("subscriptionServiceType");
- customer.setGlobalCustomerId("globalCustomerId");
- customer.setSubscriberName("subscriberName");
- customer.setSubscriberType("subscriberType");
- customer.setServiceSubscription(serviceSubscription);
-
- org.onap.so.bpmn.servicedecomposition.bbobjects.Tenant tenant = new org.onap.so.bpmn.servicedecomposition.bbobjects.Tenant();
- tenant.setTenantContext("tenantContext");
- tenant.setTenantId("tenantId");
- tenant.setTenantName("tenantName");
-
- org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
- org.onap.aai.domain.yang.Tenants aaiTenants = Mockito.mock(org.onap.aai.domain.yang.Tenants.class);
- org.onap.aai.domain.yang.Tenant aaiTenant = new org.onap.aai.domain.yang.Tenant();
- aaiTenant.setTenantId("tenantId");
- List<org.onap.aai.domain.yang.Tenant> tenants = new ArrayList<>();
- tenants.add(aaiTenant);
-
- String requestAction = "createInstance";
-
- doReturn(uriKeys).when(SPY_bbInputSetupUtils).getURIKeysFromServiceInstance(serviceInstance.getServiceInstanceId());
- doReturn(customer).when(SPY_bbInputSetup).mapCustomer(uriKeys.get("global-customer-id"),uriKeys.get("service-type"));
- doReturn(aaiCloudRegion).when(SPY_bbInputSetupUtils).getCloudRegion(requestDetails.getCloudConfiguration());
- doReturn(orchestrationContext).when(bbInputSetupMapperLayer).mapOrchestrationContext(requestDetails);
- doReturn(requestContext).when(bbInputSetupMapperLayer).mapRequestContext(requestDetails);
- doReturn(cloudRegion).when(bbInputSetupMapperLayer).mapCloudRegion(requestDetails.getCloudConfiguration(), aaiCloudRegion);
- doReturn(tenant).when(bbInputSetupMapperLayer).mapTenant(aaiTenant);
- doReturn(aaiTenants).when(aaiCloudRegion).getTenants();
- doReturn(tenants).when(aaiTenants).getTenant();
-
- GeneralBuildingBlock actual = SPY_bbInputSetup.populateGBBWithSIAndAdditionalInfo(requestDetails,
- serviceInstance, executeBB, requestAction, null);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetServiceInstanceNOAAI() throws Exception {
- ServiceInstance expected = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
- ServiceInstance.class);
- Service service = mapper.readValue(
- new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
- Customer customer = mapper.readValue(new File(RESOURCE_PATH + "Customer.json"), Customer.class);
- Project project = mapper.readValue(new File(RESOURCE_PATH + "Project.json"), Project.class);
- OwningEntity owningEntity = mapper.readValue(new File(RESOURCE_PATH + "OwningEntity.json"), OwningEntity.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
-
- ExecuteBuildingBlock executeBB = new ExecuteBuildingBlock();
- executeBB.setaLaCarte(true);
- BuildingBlock buildingBlock = new BuildingBlock();
- buildingBlock.setBpmnFlowName(AssignFlows.SERVICE_INSTANCE.toString());
- executeBB.setBuildingBlock(buildingBlock);
- RequestDetails requestDetails = new RequestDetails();
- RequestInfo reqInfo = new RequestInfo();
- reqInfo.setInstanceName("serviceInstanceName");
- requestDetails.setRequestInfo(reqInfo);
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelType(ModelType.service);
- requestDetails.setModelInfo(modelInfo);
- doReturn(null).when(SPY_bbInputSetupUtils)
- .getAAIServiceInstanceByName(requestDetails.getRequestInfo().getInstanceName(), customer);
- doReturn(expected.getModelInfoServiceInstance()).when(bbInputSetupMapperLayer)
- .mapCatalogServiceIntoServiceInstance(service);
- doReturn(null).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(any(String.class));
- String serviceInstanceId = "3655a595-05d1-433c-93c0-3afd6b572545";
- boolean aLaCarte = true;
-
- ServiceInstance actual = SPY_bbInputSetup.getALaCarteServiceInstance(service, requestDetails, customer, project,
- owningEntity, lookupKeyMap, serviceInstanceId, aLaCarte,
- executeBB.getBuildingBlock().getBpmnFlowName());
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetServiceSubscription() throws IOException {
- ServiceSubscription expected = new ServiceSubscription();
- RequestDetails requestDetails = new RequestDetails();
- RequestParameters params = new RequestParameters();
- params.setSubscriptionServiceType("subscriptionServiceType");
- requestDetails.setRequestParameters(params);
- org.onap.aai.domain.yang.ServiceSubscription aaiServiceSubscription = new org.onap.aai.domain.yang.ServiceSubscription();
- Customer customer = new Customer();
- customer.setGlobalCustomerId("globalCustomerId");
- doReturn(aaiServiceSubscription).when(SPY_bbInputSetupUtils).getAAIServiceSubscription(
- customer.getGlobalCustomerId(), requestDetails.getRequestParameters().getSubscriptionServiceType());
- doReturn(expected).when(bbInputSetupMapperLayer).mapAAIServiceSubscription(aaiServiceSubscription);
-
- ServiceSubscription actual = SPY_bbInputSetup.getServiceSubscription(requestDetails, customer);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetCustomer() throws IOException {
- Customer expected = new Customer();
- RequestDetails requestDetails = new RequestDetails();
- SubscriberInfo subscriberInfo = new SubscriberInfo();
- subscriberInfo.setGlobalSubscriberId("globalSubscriberId");
- requestDetails.setSubscriberInfo(subscriberInfo);
- org.onap.aai.domain.yang.Customer aaiCustomer = new org.onap.aai.domain.yang.Customer();
- doReturn(aaiCustomer).when(SPY_bbInputSetupUtils)
- .getAAICustomer(requestDetails.getSubscriberInfo().getGlobalSubscriberId());
- doReturn(expected).when(bbInputSetupMapperLayer).mapAAICustomer(aaiCustomer);
-
- Customer actual = SPY_bbInputSetup.getCustomerFromRequest(requestDetails);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetExistingServiceInstance() throws Exception {
- org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
- ServiceInstance expected = new ServiceInstance();
-
- doReturn(expected).when(bbInputSetupMapperLayer)
- .mapAAIServiceInstanceIntoServiceInstance(serviceInstanceAAI);
-
-
- ServiceInstance actual = SPY_bbInputSetup.getExistingServiceInstance(serviceInstanceAAI);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testPopulateNetworkCollectionAndInstanceGroupAssign() throws Exception {
- Service service = Mockito.mock(Service.class);
- String key = "collectionCustId";
- ServiceInstance serviceInstance = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
- ServiceInstance.class);
- String resourceId = "123";
- Collection collection = SPY_bbInputSetup.createCollection(resourceId);
- InstanceGroup instanceGroup = SPY_bbInputSetup.createInstanceGroup();
- assertNull(serviceInstance.getCollection());
- doReturn(true).when(SPY_bbInputSetup).isVlanTagging(service, key);
- doReturn(collection).when(SPY_bbInputSetup).createCollection(resourceId);
- doReturn(instanceGroup).when(SPY_bbInputSetup).createInstanceGroup();
- doNothing().when(SPY_bbInputSetup).mapCatalogCollection(service, collection, key);
-
- NetworkCollectionResourceCustomization networkCollection = new NetworkCollectionResourceCustomization();
- networkCollection.setModelCustomizationUUID(key);
- networkCollection.setCollectionResource(new CollectionResource());
- networkCollection.getCollectionResource().setInstanceGroup(new org.onap.so.db.catalog.beans.InstanceGroup());
- networkCollection.getCollectionResource().getInstanceGroup().setToscaNodeType("NetworkCollectionResource");
- networkCollection.getCollectionResource().getInstanceGroup().setType(InstanceGroupType.L3_NETWORK);
- networkCollection.getCollectionResource().getInstanceGroup().setCollectionInstanceGroupCustomizations(new ArrayList<>());
- List<CollectionResourceCustomization> customizations = new ArrayList<>();
- customizations.add(networkCollection);
- doReturn(customizations).when(service).getCollectionResourceCustomizations();
-
- SPY_bbInputSetup.populateNetworkCollectionAndInstanceGroupAssign(service,
- AssignFlows.NETWORK_COLLECTION.toString(), serviceInstance, resourceId, key);
-
- assertNotNull(serviceInstance.getCollection());
- assertNotNull(serviceInstance.getCollection().getInstanceGroup());
-
- verify(SPY_bbInputSetup, times(1)).mapCatalogCollection(service, serviceInstance.getCollection(), key);
- verify(SPY_bbInputSetup, times(1)).mapCatalogNetworkCollectionInstanceGroup(service,
- serviceInstance.getCollection().getInstanceGroup(), key);
- }
-
- @Test
- public void testPopulateInstanceGroup() throws Exception {
- ModelInfo modelInfo = Mockito.mock(ModelInfo.class);
- Service service = Mockito.mock(Service.class);
- List<InstanceGroup> instanceGroups = Mockito.spy(new ArrayList<>());
- ServiceInstance serviceInstance = Mockito.spy(new ServiceInstance());
- serviceInstance.setServiceInstanceId("si-001");
- serviceInstance.setServiceInstanceName("test service instance");
- serviceInstance.setInstanceGroups(instanceGroups);
-
- SPY_bbInputSetup.populateInstanceGroup(modelInfo, service, serviceInstance, "instance-group-001", "test instance group");
- verify(SPY_bbInputSetup, times(1)).mapCatalogInstanceGroup(isA(InstanceGroup.class), isA(ModelInfo.class), isA(Service.class));
- verify(instanceGroups, times(1)).add(isA(InstanceGroup.class));
- }
-
- @Test
- public void testIsVlanTagging() throws Exception {
- boolean expected = true;
- Service service = Mockito.mock(Service.class);
- String key = "collectionCustId";
- NetworkCollectionResourceCustomization networkCollection = new NetworkCollectionResourceCustomization();
- networkCollection.setModelCustomizationUUID(key);
- networkCollection.setCollectionResource(new CollectionResource());
- networkCollection.getCollectionResource().setInstanceGroup(new org.onap.so.db.catalog.beans.InstanceGroup());
- networkCollection.getCollectionResource().getInstanceGroup().setToscaNodeType("org.openecomp.resource.cr.NetworkCollectionResource1806");
- List<CollectionResourceCustomization> customizations = new ArrayList<>();
- customizations.add(networkCollection);
- doReturn(customizations).when(service).getCollectionResourceCustomizations();
- boolean actual = SPY_bbInputSetup.isVlanTagging(service, key);
- assertEquals("Is Vlan Tagging check.", expected, actual);
- }
-
- @Test
- public void testPopulateVolumeGroup() throws Exception {
- RequestDetails requestDetails = new RequestDetails();
- RelatedInstanceList ril = new RelatedInstanceList();
- RelatedInstance ri = new RelatedInstance();
- ModelInfo mi = new ModelInfo();
- mi.setModelType(ModelType.vnf);
- mi.setModelCustomizationUuid("vnfModelCustomizationUUID");
- ri.setModelInfo(mi);
- ril.setRelatedInstance(ri);
- requestDetails.setRelatedInstanceList(new RelatedInstanceList[] { ril });
-
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelType(ModelType.volumeGroup);
-
- RequestInfo reqInfo = new RequestInfo();
- reqInfo.setInstanceName("volumeGroupName");
- requestDetails.setModelInfo(modelInfo);
- requestDetails.setRequestInfo(reqInfo);
-
- ServiceInstance serviceInstance = new ServiceInstance();
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("genericVnfId");
-
- VolumeGroup vg = new VolumeGroup();
- vg.setVolumeGroupName("volumeGroupName");
- vg.setVolumeGroupId("volumeGroupId");
- vnf.getVolumeGroups().add(vg);
- serviceInstance.getVnfs().add(vnf);
-
- Service service = mapper.readValue(
- new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "genericVnfId");
-
- String bbName = AssignFlows.VOLUME_GROUP.toString();
- String resourceId = "123";
- doNothing().when(SPY_bbInputSetup).mapCatalogVolumeGroup(isA(VolumeGroup.class), eq(modelInfo),
- eq(service), eq("vnfModelCustomizationUUID"));
- org.onap.aai.domain.yang.GenericVnf aaiGenericVnf = new org.onap.aai.domain.yang.GenericVnf();
- aaiGenericVnf.setModelCustomizationId("vnfModelCustomizationUUID");
- doReturn(aaiGenericVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId());
-
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
- SPY_bbInputSetup.populateVolumeGroup(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
- requestDetails.getRelatedInstanceList(), reqInfo.getInstanceName(), null, null);
- verify(SPY_bbInputSetup, times(1)).mapCatalogVolumeGroup(vg, modelInfo, service, "vnfModelCustomizationUUID");
- vnf.getVolumeGroups().clear();
- SPY_bbInputSetup.populateVolumeGroup(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
- requestDetails.getRelatedInstanceList(), reqInfo.getInstanceName(), null, null);
- verify(SPY_bbInputSetup, times(1)).mapCatalogVolumeGroup(vnf.getVolumeGroups().get(0), modelInfo, service,
- "vnfModelCustomizationUUID");
- }
-
- @Test
- public void testMapCatalogVolumeGroup() {
- VolumeGroup volumeGroup = new VolumeGroup();
- RequestDetails requestDetails = new RequestDetails();
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelCustomizationUuid("modelCustomizationUUID");
- requestDetails.setModelInfo(modelInfo);
- Service service = new Service();
- VnfResourceCustomization resourceCust = new VnfResourceCustomization();
- resourceCust.setModelCustomizationUUID("vnfModelCustomizationUUID");
- service.getVnfCustomizations().add(resourceCust);
- VfModuleCustomization vfResourceCust = new VfModuleCustomization();
- vfResourceCust.setModelCustomizationUUID("modelCustomizationUUID");
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- resourceCust.getVfModuleCustomizations().add(vfResourceCust);
-
- doReturn(modelInfoVfModule).when(bbInputSetupMapperLayer).mapCatalogVfModuleToVfModule(vfResourceCust);
-
- SPY_bbInputSetup.mapCatalogVolumeGroup(volumeGroup, modelInfo, service, "vnfModelCustomizationUUID");
-
- assertEquals(modelInfoVfModule, volumeGroup.getModelInfoVfModule());
- }
-
- @Test
- public void testPopulateL3Network() throws JsonParseException, JsonMappingException, IOException {
- String instanceName = "networkName";
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelType(ModelType.network);
-
- ServiceInstance serviceInstance = new ServiceInstance();
- L3Network network = new L3Network();
- network.setNetworkId("networkId");
- network.setNetworkName("networkName");
- serviceInstance.getNetworks().add(network);
- String resourceId = "123";
- // Mock service
- Service service = mapper.readValue(
- new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
- String bbName = AssignFlows.NETWORK_A_LA_CARTE.toString();
-
- doNothing().when(SPY_bbInputSetup).mapCatalogNetwork(network, modelInfo, service);
-
- SPY_bbInputSetup.populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance, lookupKeyMap,
- resourceId, null);
-
- lookupKeyMap.put(ResourceKey.NETWORK_ID, null);
-
- SPY_bbInputSetup.populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance, lookupKeyMap,
- resourceId, null);
- verify(SPY_bbInputSetup, times(1)).mapCatalogNetwork(network, modelInfo, service);
-
- instanceName = "networkName2";
- L3Network network2 = SPY_bbInputSetup.createNetwork(lookupKeyMap, instanceName, resourceId, null);
- SPY_bbInputSetup.populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance, lookupKeyMap,
- resourceId, null);
- verify(SPY_bbInputSetup, times(2)).mapCatalogNetwork(network2, modelInfo, service);
- }
-
- @Test
- public void testMapCatalogNetwork() {
- ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
- L3Network network = new L3Network();
-
- RequestDetails requestDetails = new RequestDetails();
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelCustomizationUuid("modelCustomizationUUID");
- requestDetails.setModelInfo(modelInfo);
- Service service = new Service();
- NetworkResourceCustomization resourceCust = new NetworkResourceCustomization();
- resourceCust.setModelCustomizationUUID("modelCustomizationUUID");
- service.setNetworkCustomizations(Arrays.asList(new NetworkResourceCustomization[] { resourceCust }));
-
- doReturn(modelInfoNetwork).when(bbInputSetupMapperLayer).mapCatalogNetworkToNetwork(resourceCust);
-
- SPY_bbInputSetup.mapCatalogNetwork(network, modelInfo, service);
-
- assertEquals(modelInfoNetwork, network.getModelInfoNetwork());
- }
-
- @Test
- public void testPopulateConfiguration() throws JsonParseException, JsonMappingException, IOException {
- String instanceName = "configurationName";
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelCustomizationUuid("72d9d1cd-f46d-447a-abdb-451d6fb05fa9");
-
- ServiceInstance serviceInstance = new ServiceInstance();
- Configuration configuration = new Configuration();
- configuration.setConfigurationId("configurationId");
- configuration.setConfigurationName("configurationName");
- serviceInstance.getConfigurations().add(configuration);
- String resourceId = "configurationId";
- String vnfcName = "vnfcName";
- // Mock service
- Service service = mapper.readValue(
- new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
- ConfigurationResourceCustomization configurationCust = new ConfigurationResourceCustomization();
- configurationCust.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa9");
- service.getConfigurationCustomizations().add(configurationCust);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId");
- String bbName = AssignFlows.FABRIC_CONFIGURATION.toString();
- ConfigurationResourceKeys configResourceKeys = new ConfigurationResourceKeys();
- configResourceKeys.setCvnfcCustomizationUUID("cvnfcCustomizationUUID");
- configResourceKeys.setVfModuleCustomizationUUID("vfModuleCustomizationUUID");
- configResourceKeys.setVnfResourceCustomizationUUID("vnfResourceCustomizationUUID");
- configResourceKeys.setVnfcName(vnfcName);
- Vnfc vnfc = new Vnfc();
- vnfc.setVnfcName(vnfcName);
-
- doNothing().when(SPY_bbInputSetup).mapCatalogConfiguration(configuration, modelInfo, service, configResourceKeys);
- doReturn(vnfc).when(SPY_bbInputSetup).getVnfcToConfiguration(vnfcName);
- SPY_bbInputSetup.populateConfiguration(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
- instanceName, configResourceKeys);
- verify(SPY_bbInputSetup, times(1)).mapCatalogConfiguration(configuration, modelInfo, service, configResourceKeys);
-
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, null);
-
- SPY_bbInputSetup.populateConfiguration(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
- instanceName, configResourceKeys);
- verify(SPY_bbInputSetup, times(2)).mapCatalogConfiguration(configuration, modelInfo, service, configResourceKeys);
-
- instanceName = "configurationName2";
- resourceId = "resourceId2";
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId2");
- Configuration configuration2 = SPY_bbInputSetup.createConfiguration(lookupKeyMap, instanceName, resourceId);
- doReturn(configuration2).when(SPY_bbInputSetup).createConfiguration(lookupKeyMap, instanceName, resourceId);
- doNothing().when(SPY_bbInputSetup).mapCatalogConfiguration(configuration2, modelInfo, service, configResourceKeys);
- SPY_bbInputSetup.populateConfiguration(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
- instanceName, configResourceKeys);
- verify(SPY_bbInputSetup, times(1)).mapCatalogConfiguration(configuration2, modelInfo, service, configResourceKeys);
- }
-
- @Test
- public void testMapCatalogConfiguration() {
- ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
- L3Network network = new L3Network();
-
- RequestDetails requestDetails = new RequestDetails();
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelCustomizationUuid("modelCustomizationUUID");
- requestDetails.setModelInfo(modelInfo);
- Service service = new Service();
- NetworkResourceCustomization resourceCust = new NetworkResourceCustomization();
- resourceCust.setModelCustomizationUUID("modelCustomizationUUID");
- service.setNetworkCustomizations(Arrays.asList(new NetworkResourceCustomization[] { resourceCust }));
-
- doReturn(modelInfoNetwork).when(bbInputSetupMapperLayer).mapCatalogNetworkToNetwork(resourceCust);
-
- SPY_bbInputSetup.mapCatalogNetwork(network, modelInfo, service);
-
- assertEquals(modelInfoNetwork, network.getModelInfoNetwork());
- }
-
- @Test
- public void testPopulateFabricConfiguration() throws JsonParseException, JsonMappingException, IOException {
- String instanceName = "configurationName";
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelCustomizationUuid("72d9d1cd-f46d-447a-abdb-451d6fb05fa9");
-
- ServiceInstance serviceInstance = new ServiceInstance();
- Configuration configuration = new Configuration();
- configuration.setConfigurationId("configurationId");
- configuration.setConfigurationName("configurationName");
- serviceInstance.getConfigurations().add(configuration);
- String resourceId = "configurationId";
- String vnfcName = "vnfcName";
- // Mock service
- Service service = mapper.readValue(
- new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId");
- String bbName = AssignFlows.FABRIC_CONFIGURATION.toString();
- ConfigurationResourceKeys configResourceKeys = new ConfigurationResourceKeys();
- configResourceKeys.setCvnfcCustomizationUUID("cvnfcCustomizationUUID");
- configResourceKeys.setVfModuleCustomizationUUID("vfModuleCustomizationUUID");
- configResourceKeys.setVnfResourceCustomizationUUID("vnfResourceCustomizationUUID");
- configResourceKeys.setVnfcName(vnfcName);
- Vnfc vnfc = new Vnfc();
- vnfc.setVnfcName(vnfcName);
-
- CvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization = new CvnfcConfigurationCustomization();
- ConfigurationResource configurationResource = new ConfigurationResource();
- configurationResource.setModelUUID("modelUUID");
- configurationResource.setModelInvariantUUID("modelInvariantUUID");
- vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationResource(configurationResource);
-
- doReturn(null).when(SPY_bbInputSetup).findConfigurationResourceCustomization(modelInfo, service);
- doReturn(vnfc).when(SPY_bbInputSetup).getVnfcToConfiguration(vnfcName);
-
- SPY_bbInputSetup.populateConfiguration(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
- instanceName, configResourceKeys);
- verify(SPY_bbInputSetup, times(1)).mapCatalogConfiguration(configuration, modelInfo, service, configResourceKeys);
- }
-
- @Test
- public void testPopulateGenericVnf() throws JsonParseException, JsonMappingException, IOException {
- org.onap.so.serviceinstancebeans.Platform platform = new org.onap.so.serviceinstancebeans.Platform();
- org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness = new org.onap.so.serviceinstancebeans.LineOfBusiness();
- String instanceName = "vnfName";
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelType(ModelType.vnf);
-
- ServiceInstance serviceInstance = new ServiceInstance();
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("genericVnfId");
- vnf.setVnfName("vnfName");
- serviceInstance.getVnfs().add(vnf);
- String vnfType = "vnfType";
- RequestDetails requestDetails = mapper.readValue(new File(RESOURCE_PATH + "RequestDetails_CreateVnf.json"),
- RequestDetails.class);
-
- Service service = mapper.readValue(
- new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "genericVnfId");
- String bbName = AssignFlows.VNF.toString();
-
- Platform expectedPlatform = new Platform();
- LineOfBusiness expectedLineOfBusiness = new LineOfBusiness();
- String resourceId = "123";
- doReturn(expectedPlatform).when(bbInputSetupMapperLayer).mapRequestPlatform(platform);
- doReturn(expectedLineOfBusiness).when(bbInputSetupMapperLayer).mapRequestLineOfBusiness(lineOfBusiness);
- org.onap.aai.domain.yang.GenericVnf vnfAAI = new org.onap.aai.domain.yang.GenericVnf();
- vnfAAI.setModelCustomizationId("modelCustId");
- doReturn(vnfAAI).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId());
- doNothing().when(SPY_bbInputSetup).mapCatalogVnf(vnf, modelInfo, service);
- org.onap.aai.domain.yang.InstanceGroup instanceGroupAAI = new org.onap.aai.domain.yang.InstanceGroup();
- doReturn(instanceGroupAAI).when(SPY_bbInputSetupUtils).getAAIInstanceGroup(any());
- org.onap.so.db.catalog.beans.InstanceGroup catalogInstanceGroup = new org.onap.so.db.catalog.beans.InstanceGroup();
- doReturn(catalogInstanceGroup).when(SPY_bbInputSetupUtils).getCatalogInstanceGroup(any());
-
- SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName,
- serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null,
- requestDetails.getRequestInfo().getProductFamilyId());
-
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
-
- SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName,
- serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null,
- requestDetails.getRequestInfo().getProductFamilyId());
- verify(SPY_bbInputSetup, times(1)).mapCatalogVnf(vnf, modelInfo, service);
-
- instanceName = "vnfName2";
- GenericVnf vnf2 = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness,
- resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId());
- doReturn(vnf2).when(SPY_bbInputSetup).createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness,
- resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId());
- doNothing().when(SPY_bbInputSetup).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}");
- doNothing().when(SPY_bbInputSetup).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service);
-
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "genericVnfId2");
-
- SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName,
- serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null,
- requestDetails.getRequestInfo().getProductFamilyId());
- verify(SPY_bbInputSetup, times(2)).mapCatalogVnf(vnf2, modelInfo, service);
- verify(SPY_bbInputSetup, times(2)).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}");
- verify(SPY_bbInputSetup, times(2)).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service);
- }
-
- @Test
- public void testMapVnfcCollectionInstanceGroup() {
- VnfResourceCustomization vnfResourceCust = Mockito.mock(VnfResourceCustomization.class);
- GenericVnf genericVnf = new GenericVnf();
- ModelInfo modelInfo = Mockito.mock(ModelInfo.class);
- Service service = Mockito.mock(Service.class);
- org.onap.so.db.catalog.beans.InstanceGroup instanceGroup = new org.onap.so.db.catalog.beans.InstanceGroup();
- instanceGroup.setModelUUID("modelUUID");
- List<VnfcInstanceGroupCustomization> vnfcInstanceGroups = new ArrayList<>();
- VnfcInstanceGroupCustomization vnfcInstanceGroupCust = new VnfcInstanceGroupCustomization();
- vnfcInstanceGroupCust.setInstanceGroup(instanceGroup);
- vnfcInstanceGroupCust.setFunction("function");
- vnfcInstanceGroupCust.setDescription("description");
- vnfcInstanceGroups.add(vnfcInstanceGroupCust);
-
- ModelInfoInstanceGroup modelInfoInstanceGroup = new ModelInfoInstanceGroup();
- modelInfoInstanceGroup.setModelUUID("modelUUID");
- doReturn(vnfResourceCust).when(SPY_bbInputSetup).getVnfResourceCustomizationFromService(modelInfo, service);
- doReturn(vnfcInstanceGroups).when(vnfResourceCust).getVnfcInstanceGroupCustomizations();
- doReturn(instanceGroup).when(SPY_bbInputSetupUtils).getCatalogInstanceGroup("modelUUID");
- doReturn(modelInfoInstanceGroup).when(bbInputSetupMapperLayer).mapCatalogInstanceGroupToInstanceGroup(null, instanceGroup);
-
- SPY_bbInputSetup.mapVnfcCollectionInstanceGroup(genericVnf, modelInfo, service);
-
- assertEquals("Instance Group was created", true, genericVnf.getInstanceGroups().size() == 1);
- }
- @Test
- public void testPopulateGenericVnfWhereVnfTypeIsNull()
- throws JsonParseException, JsonMappingException, IOException {
- org.onap.so.serviceinstancebeans.Platform platform = new org.onap.so.serviceinstancebeans.Platform();
- org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness = new org.onap.so.serviceinstancebeans.LineOfBusiness();
- String instanceName = "vnfName";
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelType(ModelType.vnf);
-
- ServiceInstance serviceInstance = new ServiceInstance();
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("genericVnfId");
- vnf.setVnfName("vnfName");
- serviceInstance.getVnfs().add(vnf);
- String vnfType = null;
- RequestDetails requestDetails = mapper.readValue(new File(RESOURCE_PATH + "RequestDetails_CreateVnf.json"),
- RequestDetails.class);
-
- Service service = mapper.readValue(
- new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "genericVnfId");
- String bbName = AssignFlows.VNF.toString();
-
- Platform expectedPlatform = new Platform();
- LineOfBusiness expectedLineOfBusiness = new LineOfBusiness();
- String resourceId = "123";
- doReturn(expectedPlatform).when(bbInputSetupMapperLayer).mapRequestPlatform(platform);
- doReturn(expectedLineOfBusiness).when(bbInputSetupMapperLayer).mapRequestLineOfBusiness(lineOfBusiness);
- org.onap.aai.domain.yang.GenericVnf vnfAAI = new org.onap.aai.domain.yang.GenericVnf();
- vnfAAI.setModelCustomizationId("modelCustId");
- doReturn(vnfAAI).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId());
- doNothing().when(SPY_bbInputSetup).mapCatalogVnf(vnf, modelInfo, service);
- org.onap.aai.domain.yang.InstanceGroup instanceGroupAAI = new org.onap.aai.domain.yang.InstanceGroup();
- doReturn(instanceGroupAAI).when(SPY_bbInputSetupUtils).getAAIInstanceGroup(any());
- org.onap.so.db.catalog.beans.InstanceGroup catalogInstanceGroup = new org.onap.so.db.catalog.beans.InstanceGroup();
- doReturn(catalogInstanceGroup).when(SPY_bbInputSetupUtils).getCatalogInstanceGroup(any());
-
- SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName,
- serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null,
- requestDetails.getRequestInfo().getProductFamilyId());
-
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
-
- SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName,
- serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null,
- requestDetails.getRequestInfo().getProductFamilyId());
- verify(SPY_bbInputSetup, times(1)).mapCatalogVnf(vnf, modelInfo, service);
-
- instanceName = "vnfName2";
- GenericVnf vnf2 = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness,
- resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId());
-
- org.onap.aai.domain.yang.GenericVnf vnf2AAI = new org.onap.aai.domain.yang.GenericVnf();
- vnfAAI.setModelCustomizationId("modelCustId2");
- doReturn(vnf2AAI).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf2.getVnfId());
- doNothing().when(SPY_bbInputSetup).mapCatalogVnf(vnf2, modelInfo, service);
- doNothing().when(SPY_bbInputSetup).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}");
- SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName,
- serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null,
- requestDetails.getRequestInfo().getProductFamilyId());
- verify(SPY_bbInputSetup, times(2)).mapCatalogVnf(vnf2, modelInfo, service);
- verify(SPY_bbInputSetup, times(2)).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}");
- verify(SPY_bbInputSetup, times(1)).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service);
- }
-
- @Test
- public void testMapCatalogVnf() {
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- GenericVnf genericVnf = new GenericVnf();
- RequestDetails requestDetails = new RequestDetails();
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelCustomizationUuid("modelCustomizationUUID");
- requestDetails.setModelInfo(modelInfo);
- Service service = new Service();
- VnfResourceCustomization resourceCust = new VnfResourceCustomization();
- resourceCust.setModelCustomizationUUID("vnfModelCustomizationUUID");
- service.getVnfCustomizations().add(resourceCust);
- resourceCust.setModelCustomizationUUID("modelCustomizationUUID");
-
- doReturn(modelInfoGenericVnf).when(bbInputSetupMapperLayer).mapCatalogVnfToVnf(resourceCust);
-
- SPY_bbInputSetup.mapCatalogVnf(genericVnf, modelInfo, service);
-
- assertEquals(modelInfoGenericVnf, genericVnf.getModelInfoGenericVnf());
- }
-
- @Test
- public void testMapCatalogCollectionAndInstanceGroup() {
- ModelInfoCollection modelInfoCollection = new ModelInfoCollection();
- modelInfoCollection.setCollectionFunction("collectionFunction");
- modelInfoCollection.setCollectionRole("collectionRole");
- modelInfoCollection.setCollectionType("collectionType");
- modelInfoCollection.setDescription("description");
- modelInfoCollection.setModelInvariantUUID("modelInvariantUUID");
- modelInfoCollection.setQuantity(0);
-
- ModelInfoInstanceGroup modelInfoInstanceGroup = new ModelInfoInstanceGroup();
- modelInfoInstanceGroup.setFunction("function");
- modelInfoInstanceGroup.setInstanceGroupRole("instanceGroupRole");
- modelInfoInstanceGroup.setModelInvariantUUID("modelInvariantUUID");
- modelInfoInstanceGroup.setModelUUID("modelUUID");
- modelInfoInstanceGroup.setType("VNFC");
- modelInfoInstanceGroup.setDescription("description");
-
- InstanceGroup instanceGroup = new InstanceGroup();
- Collection collection = new Collection();
- collection.setInstanceGroup(instanceGroup);
-
- CollectionResource collectionResource = new CollectionResource();
- org.onap.so.db.catalog.beans.InstanceGroup catalogInstanceGroup = new org.onap.so.db.catalog.beans.InstanceGroup();
- collectionResource.setToscaNodeType("NetworkCollection");
- collectionResource.setInstanceGroup(catalogInstanceGroup);
-
- CollectionResourceCustomization collectionCust = new NetworkCollectionResourceCustomization();
- collectionCust.setModelCustomizationUUID("modelCustomizationUUID");
- collectionCust.setCollectionResource(collectionResource);
-
- Service service = new Service();
- service.getCollectionResourceCustomizations().add(collectionCust);
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setCollection(collection);
-
- List<CollectionResourceInstanceGroupCustomization> instanceGroupCustList = new ArrayList<>();
- CollectionResourceInstanceGroupCustomization instanceGroupCust = new CollectionResourceInstanceGroupCustomization();
- instanceGroupCust.setFunction("function");
- instanceGroupCust.setDescription("description");
-
- doReturn(modelInfoCollection).when(bbInputSetupMapperLayer).mapCatalogCollectionToCollection(collectionCust,
- collectionResource);
-
- doReturn(modelInfoInstanceGroup).when(bbInputSetupMapperLayer).mapCatalogInstanceGroupToInstanceGroup(collectionCust,
- catalogInstanceGroup);
-
- SPY_bbInputSetup.mapCatalogCollection(service, serviceInstance.getCollection(), "modelCustomizationUUID");
- SPY_bbInputSetup.mapCatalogNetworkCollectionInstanceGroup(service,
- serviceInstance.getCollection().getInstanceGroup(), collectionCust.getModelCustomizationUUID());
-
- assertThat(collection.getModelInfoCollection(), sameBeanAs(modelInfoCollection));
- assertThat(instanceGroup.getModelInfoInstanceGroup(), sameBeanAs(modelInfoInstanceGroup));
- }
-
- @Test
- public void testAddRelationshipsToSI() throws Exception {
- ServiceInstance serviceInstance = new ServiceInstance();
- org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
- serviceInstanceAAI.setServiceInstanceId("serviceInstanceId");
-
- org.onap.aai.domain.yang.RelationshipList relationshipList = new org.onap.aai.domain.yang.RelationshipList();
- org.onap.aai.domain.yang.Relationship relationship = new org.onap.aai.domain.yang.Relationship();
- relationshipList.getRelationship().add(relationship);
- serviceInstanceAAI.setRelationshipList(relationshipList);
-
- Map<String, String> uriKeys = new HashMap<>();
- uriKeys.put("global-customer-id", "globalCustomerId");
- uriKeys.put("service-type", "serviceType");
-
-
- doNothing().when(SPY_bbInputSetup).mapProject(any(), eq(serviceInstance));
- doNothing().when(SPY_bbInputSetup).mapOwningEntity(any(), eq(serviceInstance));
- doNothing().when(SPY_bbInputSetup).mapL3Networks(any(), eq(serviceInstance.getNetworks()));
- doNothing().when(SPY_bbInputSetup).mapGenericVnfs(any(), eq(serviceInstance.getVnfs()));
- doNothing().when(SPY_bbInputSetup).mapCollection(any(), eq(serviceInstance));
-
- SPY_bbInputSetup.addRelationshipsToSI(serviceInstanceAAI, serviceInstance);
-
- verify(SPY_bbInputSetup, times(1)).mapProject(any(), eq(serviceInstance));
- verify(SPY_bbInputSetup, times(1)).mapOwningEntity(any(), eq(serviceInstance));
- verify(SPY_bbInputSetup, times(1)).mapL3Networks(any(), eq(serviceInstance.getNetworks()));
- verify(SPY_bbInputSetup, times(1)).mapGenericVnfs(any(), eq(serviceInstance.getVnfs()));
- verify(SPY_bbInputSetup, times(1)).mapCollection(any(), eq(serviceInstance));
- verify(SPY_bbInputSetup, times(1)).mapConfigurations(any(), eq(serviceInstance.getConfigurations()));
- }
-
- @Test
- public void testMapConfigurations() throws JsonProcessingException {
- org.onap.aai.domain.yang.Configuration expectedAAI = new org.onap.aai.domain.yang.Configuration();
- org.onap.aai.domain.yang.RelationshipList relationshipList = new org.onap.aai.domain.yang.RelationshipList();
- org.onap.aai.domain.yang.Relationship relationship = new org.onap.aai.domain.yang.Relationship();
- relationshipList.getRelationship().add(relationship);
- expectedAAI.setRelationshipList(relationshipList);
-
- Configuration expected = new Configuration();
- AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, "configurationId");
- AAIResultWrapper configurationWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
-
- doReturn(configurationWrapper).when(SPY_bbInputSetupUtils).getAAIResourceDepthOne(aaiResourceUri);
- doReturn(expected).when(bbInputSetupMapperLayer)
- .mapAAIConfiguration(isA(org.onap.aai.domain.yang.Configuration.class));
-
- List<Configuration> configurations = new ArrayList<>();
-
- SPY_bbInputSetup.mapConfigurations(Arrays.asList(new AAIResourceUri[] { aaiResourceUri }), configurations);
-
- assertEquals(expected, configurations.get(0));
- }
-
- @Test
- public void testMapGenericVnfs() throws JsonProcessingException {
- org.onap.aai.domain.yang.GenericVnf expectedAAI = new org.onap.aai.domain.yang.GenericVnf();
- org.onap.aai.domain.yang.RelationshipList relationshipList = new org.onap.aai.domain.yang.RelationshipList();
- org.onap.aai.domain.yang.Relationship relationship = new org.onap.aai.domain.yang.Relationship();
- relationshipList.getRelationship().add(relationship);
- expectedAAI.setRelationshipList(relationshipList);
-
- GenericVnf expected = new GenericVnf();
- AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId");
- AAIResultWrapper vnfWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
-
- doReturn(vnfWrapper).when(SPY_bbInputSetupUtils).getAAIResourceDepthOne(aaiResourceUri);
- doReturn(expected).when(bbInputSetupMapperLayer)
- .mapAAIGenericVnfIntoGenericVnf(isA(org.onap.aai.domain.yang.GenericVnf.class));
- doNothing().when(SPY_bbInputSetup).mapPlatform(any(), eq(expected));
- doNothing().when(SPY_bbInputSetup).mapLineOfBusiness(any(), eq(expected));
- doReturn(new ArrayList<>()).when(SPY_bbInputSetup).mapVolumeGroups(any());
-
- List<GenericVnf> genericVnfs = new ArrayList<>();
-
- SPY_bbInputSetup.mapGenericVnfs(Arrays.asList(new AAIResourceUri[] { aaiResourceUri }), genericVnfs);
-
- assertEquals(expected, genericVnfs.get(0));
- verify(SPY_bbInputSetup, times(1)).mapPlatform(any(), eq(expected));
- verify(SPY_bbInputSetup, times(1)).mapLineOfBusiness(any(), eq(expected));
- verify(SPY_bbInputSetup, times(1)).mapVolumeGroups(any());
- }
-
- @Test
- public void testMapVolumeGroups() throws JsonProcessingException {
- org.onap.aai.domain.yang.VolumeGroup expectedAAI = new org.onap.aai.domain.yang.VolumeGroup();
-
- VolumeGroup expected = new VolumeGroup();
- AAIResultWrapper vnfWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
-
- doReturn(expected).when(bbInputSetupMapperLayer)
- .mapAAIVolumeGroup(isA(org.onap.aai.domain.yang.VolumeGroup.class));
-
- List<VolumeGroup> volumeGroupsList =
- SPY_bbInputSetup.mapVolumeGroups(Arrays.asList(new AAIResultWrapper[] { vnfWrapper }));
-
- assertEquals(expected, volumeGroupsList.get(0));
- }
-
- @Test
- public void testMapLineOfBusiness() throws JsonProcessingException {
- org.onap.aai.domain.yang.LineOfBusiness expectedAAI = new org.onap.aai.domain.yang.LineOfBusiness();
-
- LineOfBusiness expected = new LineOfBusiness();
- AAIResultWrapper vnfWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
-
- doReturn(expected).when(bbInputSetupMapperLayer)
- .mapAAILineOfBusiness(isA(org.onap.aai.domain.yang.LineOfBusiness.class));
-
- GenericVnf vnf = new GenericVnf();
-
- SPY_bbInputSetup.mapLineOfBusiness(Arrays.asList(new AAIResultWrapper[] { vnfWrapper }), vnf);
-
- assertEquals(expected, vnf.getLineOfBusiness());
- }
-
- @Test
- public void testMapPlatform() throws JsonProcessingException {
- org.onap.aai.domain.yang.Platform expectedAAI = new org.onap.aai.domain.yang.Platform();
-
- Platform expected = new Platform();
- AAIResultWrapper vnfWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
-
- doReturn(expected).when(bbInputSetupMapperLayer)
- .mapAAIPlatform(isA(org.onap.aai.domain.yang.Platform.class));
-
- GenericVnf vnf = new GenericVnf();
-
- SPY_bbInputSetup.mapPlatform(Arrays.asList(new AAIResultWrapper[] { vnfWrapper }), vnf);
-
- assertEquals(expected, vnf.getPlatform());
- }
-
- @Test
- public void testMapCollection() throws JsonProcessingException {
- List<AAIResultWrapper> collections = new ArrayList<>();
- ServiceInstance serviceInstance = new ServiceInstance();
-
- org.onap.aai.domain.yang.Collection aaiCollection = new org.onap.aai.domain.yang.Collection();
- org.onap.aai.domain.yang.RelationshipList collectionRelationshipList = new org.onap.aai.domain.yang.RelationshipList();
- org.onap.aai.domain.yang.Relationship collectionInstanceGroupRelationship = new org.onap.aai.domain.yang.Relationship();
- collectionRelationshipList.getRelationship().add(collectionInstanceGroupRelationship);
- aaiCollection.setRelationshipList(collectionRelationshipList);
-
- collections.add(new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiCollection)));
-
- Collection collection = new Collection();
- ModelInfoCollection modelInfoCollection = new ModelInfoCollection();
- List<InstanceGroup> instanceGroupsList = new ArrayList<>();
- InstanceGroup instanceGroup = new InstanceGroup();
- instanceGroupsList.add(instanceGroup);
- NetworkCollectionResourceCustomization networkCollectionCust = Mockito.mock(NetworkCollectionResourceCustomization.class);
- CollectionResource collectionResource = new CollectionResource();
- doReturn(collection).when(bbInputSetupMapperLayer)
- .mapAAICollectionIntoCollection(isA(org.onap.aai.domain.yang.Collection.class));
- doReturn(instanceGroupsList).when(SPY_bbInputSetup).mapInstanceGroups(any());
- doReturn(networkCollectionCust).when(SPY_bbInputSetupUtils).getCatalogNetworkCollectionResourceCustByID(aaiCollection.getCollectionCustomizationId());
- doReturn(collectionResource).when(networkCollectionCust).getCollectionResource();
- doReturn(modelInfoCollection).when(bbInputSetupMapperLayer).mapCatalogCollectionToCollection(networkCollectionCust, collectionResource);
+ private static final String RESOURCE_PATH = "src/test/resources/__files/ExecuteBuildingBlock/";
+
+ protected ObjectMapper mapper = new ObjectMapper();
+ private static final String CLOUD_OWNER = "CloudOwner";
+
+ @Spy
+ private BBInputSetup SPY_bbInputSetup = new BBInputSetup();
+
+ @Mock
+ private BBInputSetupUtils SPY_bbInputSetupUtils;
+
+ @Mock
+ private CloudInfoFromAAI SPY_cloudInfoFromAAI;
+
+ @Spy
+ private BBInputSetupMapperLayer bbInputSetupMapperLayer;
+
+ @Before
+ public void setup() {
+ SPY_bbInputSetup.setBbInputSetupUtils(SPY_bbInputSetupUtils);
+ SPY_bbInputSetup.setMapperLayer(bbInputSetupMapperLayer);
+ SPY_bbInputSetup.setCloudInfoFromAAI(SPY_cloudInfoFromAAI);
+ }
+
+ @Test
+ public void testGetVolumeGroupIdRelatedToVfModule() {
+ String expected = "volumeGroupId";
+ String modelCustomizationId = "modelCustomizationId";
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationId(modelCustomizationId);
+ String cloudOwner = "cloudOwner";
+ String cloudRegionId = "cloudRegionId";
+ String volumeGroupId = "volumeGroupId";
+ GenericVnf vnf = new GenericVnf();
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId(expected);
+ vnf.getVolumeGroups().add(volumeGroup);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, null);
+ org.onap.aai.domain.yang.VolumeGroup aaiVolumeGroup = new org.onap.aai.domain.yang.VolumeGroup();
+ aaiVolumeGroup.setModelCustomizationId(modelCustomizationId);
+ doReturn(aaiVolumeGroup).when(SPY_bbInputSetupUtils).getAAIVolumeGroup(cloudOwner, cloudRegionId,
+ volumeGroupId);
+
+ Optional<String> actual = SPY_bbInputSetup.getVolumeGroupIdRelatedToVfModule(vnf, modelInfo, cloudOwner,
+ cloudRegionId, lookupKeyMap);
+
+ assertEquals(expected, actual.get());
+ }
+
+ @Test
+ public void testGetAlaCarteServiceInstance() throws Exception {
+ ServiceInstance expected =
+ mapper.readValue(new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
+ ServiceInstance.class);
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setInstanceName("SharansInstanceName");
+ requestDetails.setRequestInfo(requestInfo);
+ Customer customer = new Customer();
+ String serviceInstanceId = "SharansInstanceId";
+ boolean aLaCarte = true;
+ Service service = new Service();
+ service.setModelUUID("modelUUID");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelUuid("modelUUID");
+ expected.setModelInfoServiceInstance(modelInfoServiceInstance);
+ org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
+ serviceInstanceAAI.setModelVersionId("modelUUIDDifferent");
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String bbName = AssignFlows.SERVICE_INSTANCE.toString();
+ Service differentService = new Service();
+ differentService.setModelUUID("modelUUIDDifferent");
+
+ doReturn(expected).when(SPY_bbInputSetup).getServiceInstanceHelper(requestDetails, customer, null, null,
+ lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
+ doReturn(serviceInstanceAAI).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(serviceInstanceId);
+ doReturn(differentService).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(serviceInstanceAAI.getModelVersionId());
+ doReturn(expected.getModelInfoServiceInstance()).when(bbInputSetupMapperLayer)
+ .mapCatalogServiceIntoServiceInstance(differentService);
+
+ ServiceInstance actual = SPY_bbInputSetup.getALaCarteServiceInstance(service, requestDetails, customer, null,
+ null, lookupKeyMap, serviceInstanceId, aLaCarte, bbName);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test(expected = Exception.class)
+ public void testGetAlaCarteServiceInstanceException() throws Exception {
+ ServiceInstance expected =
+ mapper.readValue(new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
+ ServiceInstance.class);
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setInstanceName("SharansInstanceName");
+ requestDetails.setRequestInfo(requestInfo);
+ Customer customer = new Customer();
+ String serviceInstanceId = "SharansInstanceId";
+ boolean aLaCarte = true;
+ Service service = new Service();
+ service.setModelUUID("modelUUID");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelUuid("modelUUID");
+ expected.setModelInfoServiceInstance(modelInfoServiceInstance);
+ org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
+ serviceInstanceAAI.setModelVersionId("modelUUIDDifferent");
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String bbName = AssignFlows.SERVICE_INSTANCE.toString();
+ Service differentService = new Service();
+ differentService.setModelUUID("modelUUIDDifferent");
+
+ doReturn(expected).when(SPY_bbInputSetup).getServiceInstanceHelper(requestDetails, customer, null, null,
+ lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
+ doReturn(serviceInstanceAAI).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(serviceInstanceId);
+ doReturn(null).when(SPY_bbInputSetupUtils).getCatalogServiceByModelUUID(serviceInstanceAAI.getModelVersionId());
+
+ ServiceInstance actual = SPY_bbInputSetup.getALaCarteServiceInstance(service, requestDetails, customer, null,
+ null, lookupKeyMap, serviceInstanceId, aLaCarte, bbName);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetCustomerAndServiceSubscription() throws JsonParseException, JsonMappingException, IOException {
+ RequestDetails requestDetails = mapper.readValue(
+ new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
+ SubscriberInfo subscriberInfo = new SubscriberInfo();
+ subscriberInfo.setGlobalSubscriberId("globalSubscriberId");
+ RequestParameters requestParams = new RequestParameters();
+ requestParams.setSubscriptionServiceType("subscriptionServiceType");
+ requestDetails.setRequestParameters(requestParams);
+ requestDetails.setSubscriberInfo(subscriberInfo);
+ String resourceId = "resourceId";
+ Customer expected = new Customer();
+ expected.setGlobalCustomerId("globalCustomerId");
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ serviceSubscription.setServiceType("subscriptionServiceType");
+
+ doReturn(expected).when(this.SPY_bbInputSetup).getCustomerFromRequest(requestDetails);
+ doReturn(serviceSubscription).when(this.SPY_bbInputSetup).getServiceSubscription(requestDetails, expected);
+
+ Customer actual = this.SPY_bbInputSetup.getCustomerAndServiceSubscription(requestDetails, resourceId);
+
+ assertThat(actual, sameBeanAs(expected));
+
+ requestDetails.setSubscriberInfo(null);
+
+
+ assertThat(actual, sameBeanAs(expected));
+
+ }
+
+ @Test
+ public void testSetHomingFlag() throws JsonParseException, JsonMappingException, IOException {
+ GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
+ GenericVnf genericVnfExpected = new GenericVnf();
+ genericVnfExpected.setVnfId("vnfId");
+ genericVnfExpected.setCallHoming(true);
+ expected.getCustomer().getServiceSubscription().getServiceInstances().get(0).getVnfs().add(genericVnfExpected);
+ boolean homing = true;
+ GenericVnf genericVnfActual = new GenericVnf();
+ genericVnfActual.setVnfId("vnfId");
+ genericVnfActual.setCallHoming(false);
+ GeneralBuildingBlock actual = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ actual.getCustomer().getServiceSubscription().getServiceInstances().get(0).getVnfs().add(genericVnfActual);
+
+ SPY_bbInputSetup.setHomingFlag(actual, homing, lookupKeyMap);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetExecuteBBFromExecution() throws IOException {
+ ExecuteBuildingBlock expected = new ExecuteBuildingBlock();
+ BuildingBlock bb = new BuildingBlock();
+ bb.setBpmnFlowName("AssignServiceInstanceBB");
+ expected.setBuildingBlock(bb);
+ expected.setRequestId("00032ab7-3fb3-42e5-965d-8ea592502017");
+ DelegateExecution execution = Mockito.mock(DelegateExecution.class);
+ doReturn(expected).when(execution).getVariable(any(String.class));
+ ExecuteBuildingBlock actual = SPY_bbInputSetup.getExecuteBBFromExecution(execution);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetGBB() throws Exception {
+ GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+
+ ExecuteBuildingBlock executeBB = new ExecuteBuildingBlock();
+ executeBB.setRequestId("requestId");
+ RequestDetails requestDetails = new RequestDetails();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelType(ModelType.service);
+ requestDetails.setModelInfo(modelInfo);
+ RequestParameters requestParams = new RequestParameters();
+ requestParams.setaLaCarte(true);
+ requestDetails.setRequestParameters(requestParams);
+ doReturn(requestDetails).when(SPY_bbInputSetupUtils).getRequestDetails(executeBB.getRequestId());
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String resourceId = "123";
+ String requestAction = "createInstance";
+ doReturn(expected).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, resourceId);
+ doNothing().when(SPY_bbInputSetup).populateLookupKeyMapWithIds(executeBB.getWorkflowResourceIds(),
+ lookupKeyMap);
+ boolean aLaCarte = true;
+ GeneralBuildingBlock actual =
+ SPY_bbInputSetup.getGBB(executeBB, lookupKeyMap, requestAction, aLaCarte, resourceId, null);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetGBBCM() throws Exception {
+ GeneralBuildingBlock expected = mapper
+ .readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockCMExpected.json"), GeneralBuildingBlock.class);
+
+ ExecuteBuildingBlock executeBB = new ExecuteBuildingBlock();
+ executeBB.setRequestId("requestId");
+ RequestDetails requestDetails = new RequestDetails();
+ requestDetails.setModelInfo(null);
+ RequestParameters requestParams = new RequestParameters();
+ requestParams.setaLaCarte(true);
+ requestDetails.setRequestParameters(requestParams);
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setSuppressRollback(true);
+ requestInfo.setSource("VID");
+ requestDetails.setRequestInfo(requestInfo);
+ CloudConfiguration cloudConfiguration = new CloudConfiguration();
+ cloudConfiguration.setLcpCloudRegionId("myRegionId");
+ requestDetails.setCloudConfiguration(cloudConfiguration);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String resourceId = "123";
+ String requestAction = "createInstance";
+
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnf-001");
+
+ doReturn(new org.onap.aai.domain.yang.GenericVnf()).when(SPY_bbInputSetupUtils)
+ .getAAIGenericVnf(ArgumentMatchers.isA(String.class));
+ doReturn(null).when(bbInputSetupMapperLayer)
+ .mapAAIGenericVnfIntoGenericVnf(ArgumentMatchers.isA(org.onap.aai.domain.yang.GenericVnf.class));
+ GeneralBuildingBlock actual =
+ SPY_bbInputSetup.getGBBCM(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetGBBCMAddMembersAction() throws Exception {
+ GeneralBuildingBlock expected = mapper.readValue(
+ new File(RESOURCE_PATH + "GeneralBuildingBlockInstanceGroupExpected.json"), GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper.readValue(
+ new File(RESOURCE_PATH + "RequestDetailsInput_instanceGroupAddMembers.json"), RequestDetails.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String requestAction = "addMembers";
+ String instanceGroupId = "instance-group-001";
+
+ WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
+ workflowResourceIds.setInstanceGroupId(instanceGroupId);
+ executeBB.setWorkflowResourceIds(workflowResourceIds);
+
+ lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, instanceGroupId);
+
+ org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = new org.onap.aai.domain.yang.InstanceGroup();
+ aaiInstanceGroup.setId(instanceGroupId);
+ aaiInstanceGroup.setInstanceGroupName("test instance group 1");
+
+ org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
+ aaiServiceInstance.setServiceInstanceId("service-instance-001");
+ aaiServiceInstance.setServiceInstanceName("test service instance 1");
+ Optional<org.onap.aai.domain.yang.ServiceInstance> optSI = Optional.of(aaiServiceInstance);
+
+ org.onap.aai.domain.yang.GenericVnf vnf1 = new org.onap.aai.domain.yang.GenericVnf();
+ vnf1.setVnfId("vnf-001");
+ vnf1.setVnfName("test vnf 1");
+
+ org.onap.aai.domain.yang.GenericVnf vnf2 = new org.onap.aai.domain.yang.GenericVnf();
+ vnf2.setVnfId("vnf-002");
+ vnf2.setVnfName("test vnf 2");
+
+ doReturn(aaiInstanceGroup).when(SPY_bbInputSetupUtils).getAAIInstanceGroup(instanceGroupId);
+ doReturn(optSI).when(SPY_bbInputSetupUtils).getRelatedServiceInstanceFromInstanceGroup(instanceGroupId);
+ doReturn(vnf1).when(SPY_bbInputSetupUtils).getAAIGenericVnf("vnf-001");
+ doReturn(vnf2).when(SPY_bbInputSetupUtils).getAAIGenericVnf("vnf-002");
+
+ GeneralBuildingBlock actual =
+ SPY_bbInputSetup.getGBBCM(executeBB, requestDetails, lookupKeyMap, requestAction, instanceGroupId);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetGBBALaCarteNonService() throws Exception {
+ GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper.readValue(
+ new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String requestAction = "createInstance";
+ Service service = Mockito.mock(Service.class);
+ ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class);
+ String resourceId = "123";
+ String vnfType = "vnfType";
+ org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
+ aaiServiceInstance.setModelVersionId("modelVersionId");
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "instanceId");
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
+ doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("instanceId");
+
+ doNothing().when(SPY_bbInputSetup).populateObjectsOnAssignAndCreateFlows(requestDetails, service, "bbName",
+ serviceInstance, lookupKeyMap, resourceId, vnfType, null, null);
+ doReturn(serviceInstance).when(SPY_bbInputSetup).getExistingServiceInstance(aaiServiceInstance);
+ doReturn(expected).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
+ executeBB, requestAction, null);
+
+ GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, resourceId, vnfType);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test(expected = Exception.class)
+ public void testGetGBBALaCarteNonServiceWithoutServiceModelInfo() throws Exception {
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper.readValue(
+ new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String requestAction = "createInstance";
+ org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
+ aaiServiceInstance.setModelVersionId("modelVersionId");
+ String resourceId = "123";
+ String vnfType = "vnfType";
+
+ SPY_bbInputSetup.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId,
+ vnfType);
+ }
+
+ @Test
+ public void testGetGBBALaCarteNonServiceWithoutRelatedInstances() throws Exception {
+ GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper.readValue(
+ new File(RESOURCE_PATH + "RequestDetailsInput_withoutRelatedInstanceList.json"), RequestDetails.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String requestAction = "createInstance";
+ Service service = Mockito.mock(Service.class);
+ String resourceId = "123";
+ ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class);
+ org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
+ aaiServiceInstance.setModelVersionId("modelVersionId");
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
+ String vnfType = "vnfType";
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "instanceId");
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
+ doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("instanceId");
+
+ doNothing().when(SPY_bbInputSetup).populateObjectsOnAssignAndCreateFlows(requestDetails, service, "bbName",
+ serviceInstance, lookupKeyMap, resourceId, vnfType, null, null);
+
+ doReturn(serviceInstance).when(SPY_bbInputSetup).getExistingServiceInstance(aaiServiceInstance);
+ doReturn(expected).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
+ executeBB, requestAction, null);
+
+ GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, resourceId, vnfType);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetGBBALaCarteService() throws Exception {
+ GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper.readValue(
+ new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+
+ org.onap.so.serviceinstancebeans.Project requestProject = new org.onap.so.serviceinstancebeans.Project();
+ org.onap.so.serviceinstancebeans.OwningEntity requestOwningEntity =
+ new org.onap.so.serviceinstancebeans.OwningEntity();
+ requestDetails.setProject(requestProject);
+ requestDetails.setOwningEntity(requestOwningEntity);
+
+ Service service = Mockito.mock(Service.class);
+ Customer customer = Mockito.mock(Customer.class);
+ ServiceSubscription serviceSubscription = Mockito.mock(ServiceSubscription.class);
+ Project project = Mockito.mock(Project.class);
+ OwningEntity owningEntity = Mockito.mock(OwningEntity.class);
+ ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class);
+ String resourceId = "123";
+ String requestAction = "createInstance";
+ executeBB.setaLaCarte(true);
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.SERVICE_INSTANCE.toString());
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
+
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(requestDetails.getModelInfo().getModelVersionId());
+ doReturn(project).when(bbInputSetupMapperLayer).mapRequestProject(requestDetails.getProject());
+ doReturn(owningEntity).when(bbInputSetupMapperLayer).mapRequestOwningEntity(requestDetails.getOwningEntity());
+
+ doReturn(customer).when(SPY_bbInputSetup).getCustomerAndServiceSubscription(requestDetails, resourceId);
+ doReturn(serviceInstance).when(SPY_bbInputSetup).getALaCarteServiceInstance(service, requestDetails, customer,
+ project, owningEntity, lookupKeyMap, resourceId, Boolean.TRUE.equals(executeBB.isaLaCarte()),
+ executeBB.getBuildingBlock().getBpmnFlowName());
+ doReturn(expected).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
+ executeBB, requestAction, customer);
+
+ GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, resourceId);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetGBBALaCarteServiceFindServiceByModelVersionId() throws Exception {
+ GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper.readValue(
+ new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+
+ org.onap.so.serviceinstancebeans.Project requestProject = new org.onap.so.serviceinstancebeans.Project();
+ org.onap.so.serviceinstancebeans.OwningEntity requestOwningEntity =
+ new org.onap.so.serviceinstancebeans.OwningEntity();
+ requestDetails.setProject(requestProject);
+ requestDetails.setOwningEntity(requestOwningEntity);
+
+ Service service = Mockito.mock(Service.class);
+ Customer customer = Mockito.mock(Customer.class);
+ ServiceSubscription serviceSubscription = Mockito.mock(ServiceSubscription.class);
+ Project project = Mockito.mock(Project.class);
+ OwningEntity owningEntity = Mockito.mock(OwningEntity.class);
+ ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class);
+ String resourceId = "123";
+ String requestAction = "createInstance";
+ executeBB.setaLaCarte(true);
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.SERVICE_INSTANCE.toString());
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
+
+ doReturn(null).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(requestDetails.getModelInfo().getModelVersionId());
+ doReturn(service).when(SPY_bbInputSetupUtils).getCatalogServiceByModelVersionAndModelInvariantUUID(
+ requestDetails.getModelInfo().getModelVersion(), requestDetails.getModelInfo().getModelInvariantId());
+ doReturn(project).when(bbInputSetupMapperLayer).mapRequestProject(requestDetails.getProject());
+ doReturn(owningEntity).when(bbInputSetupMapperLayer).mapRequestOwningEntity(requestDetails.getOwningEntity());
+
+ doReturn(customer).when(SPY_bbInputSetup).getCustomerAndServiceSubscription(requestDetails, resourceId);
+ doReturn(serviceInstance).when(SPY_bbInputSetup).getALaCarteServiceInstance(service, requestDetails, customer,
+ project, owningEntity, lookupKeyMap, resourceId, Boolean.TRUE.equals(executeBB.isaLaCarte()),
+ executeBB.getBuildingBlock().getBpmnFlowName());
+ doReturn(expected).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
+ executeBB, requestAction, customer);
+
+ GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, resourceId);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetGBBALaCarteServiceNoProjectNoOE() throws Exception {
+ GeneralBuildingBlock expected = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper.readValue(
+ new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+
+ Service service = Mockito.mock(Service.class);
+ Customer customer = Mockito.mock(Customer.class);
+ ServiceSubscription serviceSubscription = Mockito.mock(ServiceSubscription.class);
+ ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class);
+ String resourceId = "123";
+ String requestAction = "createInstance";
+ executeBB.setaLaCarte(true);
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.SERVICE_INSTANCE.toString());
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
+
+ Map<String, String> uriKeys = new HashMap<>();
+ uriKeys.put("global-customer-id", "globalCustomerId");
+ uriKeys.put("service-type", "serviceType");
+
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(requestDetails.getModelInfo().getModelVersionId());
+
+ doReturn(customer).when(SPY_bbInputSetup).getCustomerAndServiceSubscription(requestDetails, resourceId);
+
+ doReturn(serviceInstance).when(SPY_bbInputSetup).getALaCarteServiceInstance(service, requestDetails, customer,
+ null, null, lookupKeyMap, resourceId, Boolean.TRUE.equals(executeBB.isaLaCarte()),
+ executeBB.getBuildingBlock().getBpmnFlowName());
+ doReturn(expected).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
+ executeBB, requestAction, customer);
+
+ GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, resourceId);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetServiceInstanceHelperCreateScenario() throws Exception {
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setInstanceName("SharansInstanceName");
+ requestDetails.setRequestInfo(requestInfo);
+ Customer customer = new Customer();
+ String serviceInstanceId = "SharansInstanceId";
+ boolean aLaCarte = true;
+ ServiceInstance expected = new ServiceInstance();
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ Service service = new Service();
+ service.setModelUUID("modelUUID");
+ String bbName = AssignFlows.SERVICE_INSTANCE.toString();
+
+ doReturn(null).when(SPY_bbInputSetupUtils).getAAIServiceInstanceByName(requestInfo.getInstanceName(), customer);
+ doReturn(null).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(serviceInstanceId);
+
+
+ doReturn(expected).when(SPY_bbInputSetup).createServiceInstance(requestDetails, null, null, lookupKeyMap,
+ serviceInstanceId);
+
+ ServiceInstance actual = SPY_bbInputSetup.getServiceInstanceHelper(requestDetails, customer, null, null,
+ lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetServiceInstanceHelperCreateScenarioExisting() throws Exception {
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setInstanceName("SharansInstanceName");
+ requestDetails.setRequestInfo(requestInfo);
+ Customer customer = new Customer();
+ String serviceInstanceId = "SharansInstanceId";
+ boolean aLaCarte = true;
+ Service service = new Service();
+ service.setModelUUID("modelUUID");
+ ServiceInstance expected = new ServiceInstance();
+ org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
+ serviceInstanceAAI.setModelVersionId("modelUUID");
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String bbName = AssignFlows.SERVICE_INSTANCE.toString();
+
+ doReturn(serviceInstanceAAI).when(SPY_bbInputSetupUtils)
+ .getAAIServiceInstanceByName(requestInfo.getInstanceName(), customer);
+ doReturn(expected).when(SPY_bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
+
+ ServiceInstance actual = SPY_bbInputSetup.getServiceInstanceHelper(requestDetails, customer, null, null,
+ lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetServiceInstanceHelperCreateScenarioExistingNoNameButWithId() throws Exception {
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setInstanceName("SharansInstanceName");
+ requestDetails.setRequestInfo(requestInfo);
+ Customer customer = new Customer();
+ String serviceInstanceId = "SharansInstanceId";
+ boolean aLaCarte = true;
+ Service service = new Service();
+ service.setModelUUID("modelUUID");
+ ServiceInstance expected = new ServiceInstance();
+ org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
+ serviceInstanceAAI.setModelVersionId("modelUUID");
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String bbName = "ActivateServiceInstanceBB";
+
+ doReturn(serviceInstanceAAI).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(serviceInstanceId);
+ doReturn(expected).when(SPY_bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
+
+ ServiceInstance actual = SPY_bbInputSetup.getServiceInstanceHelper(requestDetails, customer, null, null,
+ lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetServiceInstanceHelperCreateScenarioExistingNoNameButWithIdDifferentModel() throws Exception {
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestDetails.setRequestInfo(requestInfo);
+ Customer customer = new Customer();
+ String serviceInstanceId = "SharansInstanceId";
+ boolean aLaCarte = true;
+ Service service = new Service();
+ service.setModelUUID("modelUUID");
+ ServiceInstance expected = new ServiceInstance();
+ org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
+ serviceInstanceAAI.setModelVersionId("modelUUIDDifferent");
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String bbName = "ActivateServiceInstanceBB";
+ Service differentService = new Service();
+ differentService.setModelUUID("modelUUIDDifferent");
+
+ doReturn(serviceInstanceAAI).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(serviceInstanceId);
+
+
+ ServiceInstance actual = SPY_bbInputSetup.getServiceInstanceHelper(requestDetails, customer, null, null,
+ lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test(expected = Exception.class)
+ public void testGetServiceInstanceHelperCreateScenarioExistingNoNameButWithIdExceptionThrown() throws Exception {
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestDetails.setRequestInfo(requestInfo);
+ Customer customer = new Customer();
+ String serviceInstanceId = "SharansInstanceId";
+ boolean aLaCarte = true;
+ Service service = new Service();
+ service.setModelUUID("modelUUID");
+ org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
+ serviceInstanceAAI.setModelVersionId("modelUUIDDifferent");
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String bbName = AssignFlows.SERVICE_INSTANCE.toString();
+
+ ServiceInstance actual = SPY_bbInputSetup.getServiceInstanceHelper(requestDetails, customer, null, null,
+ lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
+ }
+
+ @Test
+ public void testPopulateObjectsOnAssignAndCreateFlows() throws Exception {
+ String bbName = AssignFlows.SERVICE_INSTANCE.toString();
+ String instanceName = "instanceName";
+ String vnfType = "vnfType";
+ String resourceId = "networkId";
+ String productFamilyId = "productFamilyId";
+ Service service = Mockito.mock(Service.class);
+ ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class);
+ RequestDetails requestDetails = Mockito.mock(RequestDetails.class);
+ ModelInfo modelInfo = Mockito.mock(ModelInfo.class);
+ RequestInfo requestInfo = Mockito.mock(RequestInfo.class);
+ RelatedInstanceList[] relatedInstanceList = new RelatedInstanceList[] {};
+ CloudConfiguration cloudConfiguration = new CloudConfiguration();
+ org.onap.so.serviceinstancebeans.Platform platform =
+ Mockito.mock(org.onap.so.serviceinstancebeans.Platform.class);
+ org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness =
+ Mockito.mock(org.onap.so.serviceinstancebeans.LineOfBusiness.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+
+ doNothing().when(SPY_bbInputSetup).populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance,
+ lookupKeyMap, resourceId, null);
+ doReturn(modelInfo).when(requestDetails).getModelInfo();
+ doReturn(productFamilyId).when(requestInfo).getProductFamilyId();
+ doReturn(requestInfo).when(requestDetails).getRequestInfo();
+ doReturn(instanceName).when(requestInfo).getInstanceName();
+ doReturn(platform).when(requestDetails).getPlatform();
+ doReturn(lineOfBusiness).when(requestDetails).getLineOfBusiness();
+ doReturn(relatedInstanceList).when(requestDetails).getRelatedInstanceList();
+ doReturn(cloudConfiguration).when(requestDetails).getCloudConfiguration();
+
+ doReturn(ModelType.network).when(modelInfo).getModelType();
+ SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(requestDetails, service, bbName, serviceInstance,
+ lookupKeyMap, resourceId, vnfType, null, null);
+ verify(SPY_bbInputSetup, times(1)).populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance,
+ lookupKeyMap, resourceId, null);
+ assertEquals("NetworkId populated", true,
+ lookupKeyMap.get(ResourceKey.NETWORK_ID).equalsIgnoreCase(resourceId));
+
+ doReturn(ModelType.vnf).when(modelInfo).getModelType();
+ resourceId = "vnfId";
+ doNothing().when(SPY_bbInputSetup).populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness,
+ service, bbName, serviceInstance, lookupKeyMap, relatedInstanceList, resourceId, vnfType, null,
+ productFamilyId);
+ SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(requestDetails, service, bbName, serviceInstance,
+ lookupKeyMap, resourceId, vnfType, null, null);
+ verify(SPY_bbInputSetup, times(1)).populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness,
+ service, bbName, serviceInstance, lookupKeyMap, relatedInstanceList, resourceId, vnfType, null,
+ productFamilyId);
+ assertEquals("VnfId populated", true,
+ lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID).equalsIgnoreCase(resourceId));
+
+ doReturn(ModelType.volumeGroup).when(modelInfo).getModelType();
+ resourceId = "volumeGroupId";
+ doNothing().when(SPY_bbInputSetup).populateVolumeGroup(modelInfo, service, bbName, serviceInstance,
+ lookupKeyMap, resourceId, relatedInstanceList, instanceName, vnfType, null);
+ SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(requestDetails, service, bbName, serviceInstance,
+ lookupKeyMap, resourceId, vnfType, null, null);
+ verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(modelInfo, service, bbName, serviceInstance,
+ lookupKeyMap, resourceId, relatedInstanceList, instanceName, vnfType, null);
+ assertEquals("VolumeGroupId populated", true,
+ lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID).equalsIgnoreCase(resourceId));
+
+ doReturn(ModelType.vfModule).when(modelInfo).getModelType();
+ resourceId = "vfModuleId";
+ doNothing().when(SPY_bbInputSetup).populateVfModule(modelInfo, service, bbName, serviceInstance, lookupKeyMap,
+ resourceId, relatedInstanceList, instanceName, null, cloudConfiguration);
+ SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(requestDetails, service, bbName, serviceInstance,
+ lookupKeyMap, resourceId, vnfType, null, null);
+ verify(SPY_bbInputSetup, times(1)).populateVfModule(modelInfo, service, bbName, serviceInstance, lookupKeyMap,
+ resourceId, relatedInstanceList, instanceName, null, cloudConfiguration);
+ assertEquals("VfModuleId populated", true,
+ lookupKeyMap.get(ResourceKey.VF_MODULE_ID).equalsIgnoreCase(resourceId));
+ }
+
+ @Test
+ public void testPopulateGBBWithSIAndAdditionalInfo() throws Exception {
+ GeneralBuildingBlock expected =
+ mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpectedWUserParamsInfo.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper.readValue(
+ new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class);
+ RequestContext requestContext =
+ mapper.readValue(new File(RESOURCE_PATH + "RequestContextExpected.json"), RequestContext.class);
+ ServiceInstance serviceInstance =
+ mapper.readValue(new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
+ ServiceInstance.class);
+ CloudConfiguration cloudConfiguration = new CloudConfiguration();
+ cloudConfiguration.setTenantId("tenantId");
+ requestDetails.setCloudConfiguration(cloudConfiguration);
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(false);
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setCloudOwner("test-owner-name");
+ cloudRegion.setLcpCloudRegionId("lcpCloudRegionId");
+ cloudRegion.setComplex("complexName");
+ cloudRegion.setTenantId("tenantId");
+
+ Map<String, String> uriKeys = new HashMap<>();
+ uriKeys.put("global-customer-id", "global-customer-id");
+ uriKeys.put("service-type", "service-type");
+
+ Customer customer = new Customer();
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ serviceSubscription.setServiceType("subscriptionServiceType");
+ customer.setGlobalCustomerId("globalCustomerId");
+ customer.setSubscriberName("subscriberName");
+ customer.setSubscriberType("subscriberType");
+ customer.setServiceSubscription(serviceSubscription);
+
+ org.onap.so.bpmn.servicedecomposition.bbobjects.Tenant tenant =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.Tenant();
+ tenant.setTenantContext("tenantContext");
+ tenant.setTenantId("tenantId");
+ tenant.setTenantName("tenantName");
+
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
+ org.onap.aai.domain.yang.Tenants aaiTenants = Mockito.mock(org.onap.aai.domain.yang.Tenants.class);
+ org.onap.aai.domain.yang.Tenant aaiTenant = new org.onap.aai.domain.yang.Tenant();
+ aaiTenant.setTenantId("tenantId");
+ List<org.onap.aai.domain.yang.Tenant> tenants = new ArrayList<>();
+ tenants.add(aaiTenant);
+
+ String requestAction = "createInstance";
+
+ doReturn(uriKeys).when(SPY_bbInputSetupUtils)
+ .getURIKeysFromServiceInstance(serviceInstance.getServiceInstanceId());
+ doReturn(customer).when(SPY_bbInputSetup).mapCustomer(uriKeys.get("global-customer-id"),
+ uriKeys.get("service-type"));
+ doReturn(aaiCloudRegion).when(SPY_bbInputSetupUtils).getCloudRegion(requestDetails.getCloudConfiguration());
+ doReturn(orchestrationContext).when(bbInputSetupMapperLayer).mapOrchestrationContext(requestDetails);
+ doReturn(requestContext).when(bbInputSetupMapperLayer).mapRequestContext(requestDetails);
+ doReturn(cloudRegion).when(bbInputSetupMapperLayer).mapCloudRegion(requestDetails.getCloudConfiguration(),
+ aaiCloudRegion);
+ doReturn(tenant).when(bbInputSetupMapperLayer).mapTenant(aaiTenant);
+ doReturn(aaiTenants).when(aaiCloudRegion).getTenants();
+ doReturn(tenants).when(aaiTenants).getTenant();
+
+ GeneralBuildingBlock actual = SPY_bbInputSetup.populateGBBWithSIAndAdditionalInfo(requestDetails,
+ serviceInstance, executeBB, requestAction, null);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetServiceInstanceNOAAI() throws Exception {
+ ServiceInstance expected =
+ mapper.readValue(new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
+ ServiceInstance.class);
+ Service service = mapper.readValue(
+ new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
+ Customer customer = mapper.readValue(new File(RESOURCE_PATH + "Customer.json"), Customer.class);
+ Project project = mapper.readValue(new File(RESOURCE_PATH + "Project.json"), Project.class);
+ OwningEntity owningEntity = mapper.readValue(new File(RESOURCE_PATH + "OwningEntity.json"), OwningEntity.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+
+ ExecuteBuildingBlock executeBB = new ExecuteBuildingBlock();
+ executeBB.setaLaCarte(true);
+ BuildingBlock buildingBlock = new BuildingBlock();
+ buildingBlock.setBpmnFlowName(AssignFlows.SERVICE_INSTANCE.toString());
+ executeBB.setBuildingBlock(buildingBlock);
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo reqInfo = new RequestInfo();
+ reqInfo.setInstanceName("serviceInstanceName");
+ requestDetails.setRequestInfo(reqInfo);
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelType(ModelType.service);
+ requestDetails.setModelInfo(modelInfo);
+ doReturn(null).when(SPY_bbInputSetupUtils)
+ .getAAIServiceInstanceByName(requestDetails.getRequestInfo().getInstanceName(), customer);
+ doReturn(expected.getModelInfoServiceInstance()).when(bbInputSetupMapperLayer)
+ .mapCatalogServiceIntoServiceInstance(service);
+ doReturn(null).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(any(String.class));
+ String serviceInstanceId = "3655a595-05d1-433c-93c0-3afd6b572545";
+ boolean aLaCarte = true;
+
+ ServiceInstance actual =
+ SPY_bbInputSetup.getALaCarteServiceInstance(service, requestDetails, customer, project, owningEntity,
+ lookupKeyMap, serviceInstanceId, aLaCarte, executeBB.getBuildingBlock().getBpmnFlowName());
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetServiceSubscription() throws IOException {
+ ServiceSubscription expected = new ServiceSubscription();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestParameters params = new RequestParameters();
+ params.setSubscriptionServiceType("subscriptionServiceType");
+ requestDetails.setRequestParameters(params);
+ org.onap.aai.domain.yang.ServiceSubscription aaiServiceSubscription =
+ new org.onap.aai.domain.yang.ServiceSubscription();
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("globalCustomerId");
+ doReturn(aaiServiceSubscription).when(SPY_bbInputSetupUtils).getAAIServiceSubscription(
+ customer.getGlobalCustomerId(), requestDetails.getRequestParameters().getSubscriptionServiceType());
+ doReturn(expected).when(bbInputSetupMapperLayer).mapAAIServiceSubscription(aaiServiceSubscription);
+
+ ServiceSubscription actual = SPY_bbInputSetup.getServiceSubscription(requestDetails, customer);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetCustomer() throws IOException {
+ Customer expected = new Customer();
+ RequestDetails requestDetails = new RequestDetails();
+ SubscriberInfo subscriberInfo = new SubscriberInfo();
+ subscriberInfo.setGlobalSubscriberId("globalSubscriberId");
+ requestDetails.setSubscriberInfo(subscriberInfo);
+ org.onap.aai.domain.yang.Customer aaiCustomer = new org.onap.aai.domain.yang.Customer();
+ doReturn(aaiCustomer).when(SPY_bbInputSetupUtils)
+ .getAAICustomer(requestDetails.getSubscriberInfo().getGlobalSubscriberId());
+ doReturn(expected).when(bbInputSetupMapperLayer).mapAAICustomer(aaiCustomer);
+
+ Customer actual = SPY_bbInputSetup.getCustomerFromRequest(requestDetails);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetExistingServiceInstance() throws Exception {
+ org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
+ ServiceInstance expected = new ServiceInstance();
+
+ doReturn(expected).when(bbInputSetupMapperLayer).mapAAIServiceInstanceIntoServiceInstance(serviceInstanceAAI);
+
+
+ ServiceInstance actual = SPY_bbInputSetup.getExistingServiceInstance(serviceInstanceAAI);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testPopulateNetworkCollectionAndInstanceGroupAssign() throws Exception {
+ Service service = Mockito.mock(Service.class);
+ String key = "collectionCustId";
+ ServiceInstance serviceInstance =
+ mapper.readValue(new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
+ ServiceInstance.class);
+ String resourceId = "123";
+ Collection collection = SPY_bbInputSetup.createCollection(resourceId);
+ InstanceGroup instanceGroup = SPY_bbInputSetup.createInstanceGroup();
+ assertNull(serviceInstance.getCollection());
+ doReturn(true).when(SPY_bbInputSetup).isVlanTagging(service, key);
+ doReturn(collection).when(SPY_bbInputSetup).createCollection(resourceId);
+ doReturn(instanceGroup).when(SPY_bbInputSetup).createInstanceGroup();
+ doNothing().when(SPY_bbInputSetup).mapCatalogCollection(service, collection, key);
+
+ NetworkCollectionResourceCustomization networkCollection = new NetworkCollectionResourceCustomization();
+ networkCollection.setModelCustomizationUUID(key);
+ networkCollection.setCollectionResource(new CollectionResource());
+ networkCollection.getCollectionResource().setInstanceGroup(new org.onap.so.db.catalog.beans.InstanceGroup());
+ networkCollection.getCollectionResource().getInstanceGroup().setToscaNodeType("NetworkCollectionResource");
+ networkCollection.getCollectionResource().getInstanceGroup().setType(InstanceGroupType.L3_NETWORK);
+ networkCollection.getCollectionResource().getInstanceGroup()
+ .setCollectionInstanceGroupCustomizations(new ArrayList<>());
+ List<CollectionResourceCustomization> customizations = new ArrayList<>();
+ customizations.add(networkCollection);
+ doReturn(customizations).when(service).getCollectionResourceCustomizations();
+
+ SPY_bbInputSetup.populateNetworkCollectionAndInstanceGroupAssign(service,
+ AssignFlows.NETWORK_COLLECTION.toString(), serviceInstance, resourceId, key);
+
+ assertNotNull(serviceInstance.getCollection());
+ assertNotNull(serviceInstance.getCollection().getInstanceGroup());
+
+ verify(SPY_bbInputSetup, times(1)).mapCatalogCollection(service, serviceInstance.getCollection(), key);
+ verify(SPY_bbInputSetup, times(1)).mapCatalogNetworkCollectionInstanceGroup(service,
+ serviceInstance.getCollection().getInstanceGroup(), key);
+ }
+
+ @Test
+ public void testPopulateInstanceGroup() throws Exception {
+ ModelInfo modelInfo = Mockito.mock(ModelInfo.class);
+ Service service = Mockito.mock(Service.class);
+ List<InstanceGroup> instanceGroups = Mockito.spy(new ArrayList<>());
+ ServiceInstance serviceInstance = Mockito.spy(new ServiceInstance());
+ serviceInstance.setServiceInstanceId("si-001");
+ serviceInstance.setServiceInstanceName("test service instance");
+ serviceInstance.setInstanceGroups(instanceGroups);
+
+ SPY_bbInputSetup.populateInstanceGroup(modelInfo, service, serviceInstance, "instance-group-001",
+ "test instance group");
+ verify(SPY_bbInputSetup, times(1)).mapCatalogInstanceGroup(isA(InstanceGroup.class), isA(ModelInfo.class),
+ isA(Service.class));
+ verify(instanceGroups, times(1)).add(isA(InstanceGroup.class));
+ }
+
+ @Test
+ public void testIsVlanTagging() throws Exception {
+ boolean expected = true;
+ Service service = Mockito.mock(Service.class);
+ String key = "collectionCustId";
+ NetworkCollectionResourceCustomization networkCollection = new NetworkCollectionResourceCustomization();
+ networkCollection.setModelCustomizationUUID(key);
+ networkCollection.setCollectionResource(new CollectionResource());
+ networkCollection.getCollectionResource().setInstanceGroup(new org.onap.so.db.catalog.beans.InstanceGroup());
+ networkCollection.getCollectionResource().getInstanceGroup()
+ .setToscaNodeType("org.openecomp.resource.cr.NetworkCollectionResource1806");
+ List<CollectionResourceCustomization> customizations = new ArrayList<>();
+ customizations.add(networkCollection);
+ doReturn(customizations).when(service).getCollectionResourceCustomizations();
+ boolean actual = SPY_bbInputSetup.isVlanTagging(service, key);
+ assertEquals("Is Vlan Tagging check.", expected, actual);
+ }
+
+ @Test
+ public void testPopulateVolumeGroup() throws Exception {
+ RequestDetails requestDetails = new RequestDetails();
+ RelatedInstanceList ril = new RelatedInstanceList();
+ RelatedInstance ri = new RelatedInstance();
+ ModelInfo mi = new ModelInfo();
+ mi.setModelType(ModelType.vnf);
+ mi.setModelCustomizationUuid("vnfModelCustomizationUUID");
+ ri.setModelInfo(mi);
+ ril.setRelatedInstance(ri);
+ requestDetails.setRelatedInstanceList(new RelatedInstanceList[] {ril});
+
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelType(ModelType.volumeGroup);
+
+ RequestInfo reqInfo = new RequestInfo();
+ reqInfo.setInstanceName("volumeGroupName");
+ requestDetails.setModelInfo(modelInfo);
+ requestDetails.setRequestInfo(reqInfo);
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("genericVnfId");
+
+ VolumeGroup vg = new VolumeGroup();
+ vg.setVolumeGroupName("volumeGroupName");
+ vg.setVolumeGroupId("volumeGroupId");
+ vnf.getVolumeGroups().add(vg);
+ serviceInstance.getVnfs().add(vnf);
+
+ Service service = mapper.readValue(
+ new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "genericVnfId");
+
+ String bbName = AssignFlows.VOLUME_GROUP.toString();
+ String resourceId = "123";
+ doNothing().when(SPY_bbInputSetup).mapCatalogVolumeGroup(isA(VolumeGroup.class), eq(modelInfo), eq(service),
+ eq("vnfModelCustomizationUUID"));
+ org.onap.aai.domain.yang.GenericVnf aaiGenericVnf = new org.onap.aai.domain.yang.GenericVnf();
+ aaiGenericVnf.setModelCustomizationId("vnfModelCustomizationUUID");
+ doReturn(aaiGenericVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId());
+
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
+ SPY_bbInputSetup.populateVolumeGroup(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
+ requestDetails.getRelatedInstanceList(), reqInfo.getInstanceName(), null, null);
+ verify(SPY_bbInputSetup, times(1)).mapCatalogVolumeGroup(vg, modelInfo, service, "vnfModelCustomizationUUID");
+ vnf.getVolumeGroups().clear();
+ SPY_bbInputSetup.populateVolumeGroup(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
+ requestDetails.getRelatedInstanceList(), reqInfo.getInstanceName(), null, null);
+ verify(SPY_bbInputSetup, times(1)).mapCatalogVolumeGroup(vnf.getVolumeGroups().get(0), modelInfo, service,
+ "vnfModelCustomizationUUID");
+ }
+
+ @Test
+ public void testMapCatalogVolumeGroup() {
+ VolumeGroup volumeGroup = new VolumeGroup();
+ RequestDetails requestDetails = new RequestDetails();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationUuid("modelCustomizationUUID");
+ requestDetails.setModelInfo(modelInfo);
+ Service service = new Service();
+ VnfResourceCustomization resourceCust = new VnfResourceCustomization();
+ resourceCust.setModelCustomizationUUID("vnfModelCustomizationUUID");
+ service.getVnfCustomizations().add(resourceCust);
+ VfModuleCustomization vfResourceCust = new VfModuleCustomization();
+ vfResourceCust.setModelCustomizationUUID("modelCustomizationUUID");
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ resourceCust.getVfModuleCustomizations().add(vfResourceCust);
+
+ doReturn(modelInfoVfModule).when(bbInputSetupMapperLayer).mapCatalogVfModuleToVfModule(vfResourceCust);
+
+ SPY_bbInputSetup.mapCatalogVolumeGroup(volumeGroup, modelInfo, service, "vnfModelCustomizationUUID");
+
+ assertEquals(modelInfoVfModule, volumeGroup.getModelInfoVfModule());
+ }
+
+ @Test
+ public void testPopulateL3Network() throws JsonParseException, JsonMappingException, IOException {
+ String instanceName = "networkName";
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelType(ModelType.network);
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ L3Network network = new L3Network();
+ network.setNetworkId("networkId");
+ network.setNetworkName("networkName");
+ serviceInstance.getNetworks().add(network);
+ String resourceId = "123";
+ // Mock service
+ Service service = mapper.readValue(
+ new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
+ String bbName = AssignFlows.NETWORK_A_LA_CARTE.toString();
+
+ doNothing().when(SPY_bbInputSetup).mapCatalogNetwork(network, modelInfo, service);
+
+ SPY_bbInputSetup.populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance, lookupKeyMap,
+ resourceId, null);
+
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, null);
+
+ SPY_bbInputSetup.populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance, lookupKeyMap,
+ resourceId, null);
+ verify(SPY_bbInputSetup, times(1)).mapCatalogNetwork(network, modelInfo, service);
+
+ instanceName = "networkName2";
+ L3Network network2 = SPY_bbInputSetup.createNetwork(lookupKeyMap, instanceName, resourceId, null);
+ SPY_bbInputSetup.populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance, lookupKeyMap,
+ resourceId, null);
+ verify(SPY_bbInputSetup, times(2)).mapCatalogNetwork(network2, modelInfo, service);
+ }
+
+ @Test
+ public void testMapCatalogNetwork() {
+ ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
+ L3Network network = new L3Network();
+
+ RequestDetails requestDetails = new RequestDetails();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationUuid("modelCustomizationUUID");
+ requestDetails.setModelInfo(modelInfo);
+ Service service = new Service();
+ NetworkResourceCustomization resourceCust = new NetworkResourceCustomization();
+ resourceCust.setModelCustomizationUUID("modelCustomizationUUID");
+ service.setNetworkCustomizations(Arrays.asList(new NetworkResourceCustomization[] {resourceCust}));
+
+ doReturn(modelInfoNetwork).when(bbInputSetupMapperLayer).mapCatalogNetworkToNetwork(resourceCust);
+
+ SPY_bbInputSetup.mapCatalogNetwork(network, modelInfo, service);
+
+ assertEquals(modelInfoNetwork, network.getModelInfoNetwork());
+ }
+
+ @Test
+ public void testPopulateConfiguration() throws JsonParseException, JsonMappingException, IOException {
+ String instanceName = "configurationName";
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationUuid("72d9d1cd-f46d-447a-abdb-451d6fb05fa9");
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ Configuration configuration = new Configuration();
+ configuration.setConfigurationId("configurationId");
+ configuration.setConfigurationName("configurationName");
+ serviceInstance.getConfigurations().add(configuration);
+ String resourceId = "configurationId";
+ String vnfcName = "vnfcName";
+ // Mock service
+ Service service = mapper.readValue(
+ new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
+ ConfigurationResourceCustomization configurationCust = new ConfigurationResourceCustomization();
+ configurationCust.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa9");
+ service.getConfigurationCustomizations().add(configurationCust);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId");
+ String bbName = AssignFlows.FABRIC_CONFIGURATION.toString();
+ ConfigurationResourceKeys configResourceKeys = new ConfigurationResourceKeys();
+ configResourceKeys.setCvnfcCustomizationUUID("cvnfcCustomizationUUID");
+ configResourceKeys.setVfModuleCustomizationUUID("vfModuleCustomizationUUID");
+ configResourceKeys.setVnfResourceCustomizationUUID("vnfResourceCustomizationUUID");
+ configResourceKeys.setVnfcName(vnfcName);
+ Vnfc vnfc = new Vnfc();
+ vnfc.setVnfcName(vnfcName);
+
+ doNothing().when(SPY_bbInputSetup).mapCatalogConfiguration(configuration, modelInfo, service,
+ configResourceKeys);
+ doReturn(vnfc).when(SPY_bbInputSetup).getVnfcToConfiguration(vnfcName);
+ SPY_bbInputSetup.populateConfiguration(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
+ instanceName, configResourceKeys);
+ verify(SPY_bbInputSetup, times(1)).mapCatalogConfiguration(configuration, modelInfo, service,
+ configResourceKeys);
+
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, null);
+
+ SPY_bbInputSetup.populateConfiguration(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
+ instanceName, configResourceKeys);
+ verify(SPY_bbInputSetup, times(2)).mapCatalogConfiguration(configuration, modelInfo, service,
+ configResourceKeys);
+
+ instanceName = "configurationName2";
+ resourceId = "resourceId2";
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId2");
+ Configuration configuration2 = SPY_bbInputSetup.createConfiguration(lookupKeyMap, instanceName, resourceId);
+ doReturn(configuration2).when(SPY_bbInputSetup).createConfiguration(lookupKeyMap, instanceName, resourceId);
+ doNothing().when(SPY_bbInputSetup).mapCatalogConfiguration(configuration2, modelInfo, service,
+ configResourceKeys);
+ SPY_bbInputSetup.populateConfiguration(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
+ instanceName, configResourceKeys);
+ verify(SPY_bbInputSetup, times(1)).mapCatalogConfiguration(configuration2, modelInfo, service,
+ configResourceKeys);
+ }
+
+ @Test
+ public void testMapCatalogConfiguration() {
+ ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
+ L3Network network = new L3Network();
+
+ RequestDetails requestDetails = new RequestDetails();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationUuid("modelCustomizationUUID");
+ requestDetails.setModelInfo(modelInfo);
+ Service service = new Service();
+ NetworkResourceCustomization resourceCust = new NetworkResourceCustomization();
+ resourceCust.setModelCustomizationUUID("modelCustomizationUUID");
+ service.setNetworkCustomizations(Arrays.asList(new NetworkResourceCustomization[] {resourceCust}));
+
+ doReturn(modelInfoNetwork).when(bbInputSetupMapperLayer).mapCatalogNetworkToNetwork(resourceCust);
+
+ SPY_bbInputSetup.mapCatalogNetwork(network, modelInfo, service);
+
+ assertEquals(modelInfoNetwork, network.getModelInfoNetwork());
+ }
+
+ @Test
+ public void testPopulateFabricConfiguration() throws JsonParseException, JsonMappingException, IOException {
+ String instanceName = "configurationName";
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationUuid("72d9d1cd-f46d-447a-abdb-451d6fb05fa9");
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ Configuration configuration = new Configuration();
+ configuration.setConfigurationId("configurationId");
+ configuration.setConfigurationName("configurationName");
+ serviceInstance.getConfigurations().add(configuration);
+ String resourceId = "configurationId";
+ String vnfcName = "vnfcName";
+ // Mock service
+ Service service = mapper.readValue(
+ new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId");
+ String bbName = AssignFlows.FABRIC_CONFIGURATION.toString();
+ ConfigurationResourceKeys configResourceKeys = new ConfigurationResourceKeys();
+ configResourceKeys.setCvnfcCustomizationUUID("cvnfcCustomizationUUID");
+ configResourceKeys.setVfModuleCustomizationUUID("vfModuleCustomizationUUID");
+ configResourceKeys.setVnfResourceCustomizationUUID("vnfResourceCustomizationUUID");
+ configResourceKeys.setVnfcName(vnfcName);
+ Vnfc vnfc = new Vnfc();
+ vnfc.setVnfcName(vnfcName);
+
+ CvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization =
+ new CvnfcConfigurationCustomization();
+ ConfigurationResource configurationResource = new ConfigurationResource();
+ configurationResource.setModelUUID("modelUUID");
+ configurationResource.setModelInvariantUUID("modelInvariantUUID");
+ vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationResource(configurationResource);
+
+ doReturn(null).when(SPY_bbInputSetup).findConfigurationResourceCustomization(modelInfo, service);
+ doReturn(vnfc).when(SPY_bbInputSetup).getVnfcToConfiguration(vnfcName);
+
+ SPY_bbInputSetup.populateConfiguration(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
+ instanceName, configResourceKeys);
+ verify(SPY_bbInputSetup, times(1)).mapCatalogConfiguration(configuration, modelInfo, service,
+ configResourceKeys);
+ }
+
+ @Test
+ public void testPopulateGenericVnf() throws JsonParseException, JsonMappingException, IOException {
+ org.onap.so.serviceinstancebeans.Platform platform = new org.onap.so.serviceinstancebeans.Platform();
+ org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness =
+ new org.onap.so.serviceinstancebeans.LineOfBusiness();
+ String instanceName = "vnfName";
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelType(ModelType.vnf);
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("genericVnfId");
+ vnf.setVnfName("vnfName");
+ serviceInstance.getVnfs().add(vnf);
+ String vnfType = "vnfType";
+ RequestDetails requestDetails =
+ mapper.readValue(new File(RESOURCE_PATH + "RequestDetails_CreateVnf.json"), RequestDetails.class);
+
+ Service service = mapper.readValue(
+ new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "genericVnfId");
+ String bbName = AssignFlows.VNF.toString();
+
+ Platform expectedPlatform = new Platform();
+ LineOfBusiness expectedLineOfBusiness = new LineOfBusiness();
+ String resourceId = "123";
+ doReturn(expectedPlatform).when(bbInputSetupMapperLayer).mapRequestPlatform(platform);
+ doReturn(expectedLineOfBusiness).when(bbInputSetupMapperLayer).mapRequestLineOfBusiness(lineOfBusiness);
+ org.onap.aai.domain.yang.GenericVnf vnfAAI = new org.onap.aai.domain.yang.GenericVnf();
+ vnfAAI.setModelCustomizationId("modelCustId");
+ doReturn(vnfAAI).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId());
+ doNothing().when(SPY_bbInputSetup).mapCatalogVnf(vnf, modelInfo, service);
+ org.onap.aai.domain.yang.InstanceGroup instanceGroupAAI = new org.onap.aai.domain.yang.InstanceGroup();
+ doReturn(instanceGroupAAI).when(SPY_bbInputSetupUtils).getAAIInstanceGroup(any());
+ org.onap.so.db.catalog.beans.InstanceGroup catalogInstanceGroup =
+ new org.onap.so.db.catalog.beans.InstanceGroup();
+ doReturn(catalogInstanceGroup).when(SPY_bbInputSetupUtils).getCatalogInstanceGroup(any());
+
+ SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName,
+ serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null,
+ requestDetails.getRequestInfo().getProductFamilyId());
+
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
+
+ SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName,
+ serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null,
+ requestDetails.getRequestInfo().getProductFamilyId());
+ verify(SPY_bbInputSetup, times(1)).mapCatalogVnf(vnf, modelInfo, service);
+
+ instanceName = "vnfName2";
+ GenericVnf vnf2 = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness,
+ resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId());
+ doReturn(vnf2).when(SPY_bbInputSetup).createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness,
+ resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId());
+ doNothing().when(SPY_bbInputSetup).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}");
+ doNothing().when(SPY_bbInputSetup).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service);
+
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "genericVnfId2");
+
+ SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName,
+ serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null,
+ requestDetails.getRequestInfo().getProductFamilyId());
+ verify(SPY_bbInputSetup, times(2)).mapCatalogVnf(vnf2, modelInfo, service);
+ verify(SPY_bbInputSetup, times(2)).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}");
+ verify(SPY_bbInputSetup, times(2)).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service);
+ }
+
+ @Test
+ public void testMapVnfcCollectionInstanceGroup() {
+ VnfResourceCustomization vnfResourceCust = Mockito.mock(VnfResourceCustomization.class);
+ GenericVnf genericVnf = new GenericVnf();
+ ModelInfo modelInfo = Mockito.mock(ModelInfo.class);
+ Service service = Mockito.mock(Service.class);
+ org.onap.so.db.catalog.beans.InstanceGroup instanceGroup = new org.onap.so.db.catalog.beans.InstanceGroup();
+ instanceGroup.setModelUUID("modelUUID");
+ List<VnfcInstanceGroupCustomization> vnfcInstanceGroups = new ArrayList<>();
+ VnfcInstanceGroupCustomization vnfcInstanceGroupCust = new VnfcInstanceGroupCustomization();
+ vnfcInstanceGroupCust.setInstanceGroup(instanceGroup);
+ vnfcInstanceGroupCust.setFunction("function");
+ vnfcInstanceGroupCust.setDescription("description");
+ vnfcInstanceGroups.add(vnfcInstanceGroupCust);
+
+ ModelInfoInstanceGroup modelInfoInstanceGroup = new ModelInfoInstanceGroup();
+ modelInfoInstanceGroup.setModelUUID("modelUUID");
+ doReturn(vnfResourceCust).when(SPY_bbInputSetup).getVnfResourceCustomizationFromService(modelInfo, service);
+ doReturn(vnfcInstanceGroups).when(vnfResourceCust).getVnfcInstanceGroupCustomizations();
+ doReturn(instanceGroup).when(SPY_bbInputSetupUtils).getCatalogInstanceGroup("modelUUID");
+ doReturn(modelInfoInstanceGroup).when(bbInputSetupMapperLayer).mapCatalogInstanceGroupToInstanceGroup(null,
+ instanceGroup);
+
+ SPY_bbInputSetup.mapVnfcCollectionInstanceGroup(genericVnf, modelInfo, service);
+
+ assertEquals("Instance Group was created", true, genericVnf.getInstanceGroups().size() == 1);
+ }
+
+ @Test
+ public void testPopulateGenericVnfWhereVnfTypeIsNull()
+ throws JsonParseException, JsonMappingException, IOException {
+ org.onap.so.serviceinstancebeans.Platform platform = new org.onap.so.serviceinstancebeans.Platform();
+ org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness =
+ new org.onap.so.serviceinstancebeans.LineOfBusiness();
+ String instanceName = "vnfName";
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelType(ModelType.vnf);
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("genericVnfId");
+ vnf.setVnfName("vnfName");
+ serviceInstance.getVnfs().add(vnf);
+ String vnfType = null;
+ RequestDetails requestDetails =
+ mapper.readValue(new File(RESOURCE_PATH + "RequestDetails_CreateVnf.json"), RequestDetails.class);
+
+ Service service = mapper.readValue(
+ new File(RESOURCE_PATH + "CatalogDBService_getServiceInstanceNOAAIInput.json"), Service.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "genericVnfId");
+ String bbName = AssignFlows.VNF.toString();
+
+ Platform expectedPlatform = new Platform();
+ LineOfBusiness expectedLineOfBusiness = new LineOfBusiness();
+ String resourceId = "123";
+ doReturn(expectedPlatform).when(bbInputSetupMapperLayer).mapRequestPlatform(platform);
+ doReturn(expectedLineOfBusiness).when(bbInputSetupMapperLayer).mapRequestLineOfBusiness(lineOfBusiness);
+ org.onap.aai.domain.yang.GenericVnf vnfAAI = new org.onap.aai.domain.yang.GenericVnf();
+ vnfAAI.setModelCustomizationId("modelCustId");
+ doReturn(vnfAAI).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId());
+ doNothing().when(SPY_bbInputSetup).mapCatalogVnf(vnf, modelInfo, service);
+ org.onap.aai.domain.yang.InstanceGroup instanceGroupAAI = new org.onap.aai.domain.yang.InstanceGroup();
+ doReturn(instanceGroupAAI).when(SPY_bbInputSetupUtils).getAAIInstanceGroup(any());
+ org.onap.so.db.catalog.beans.InstanceGroup catalogInstanceGroup =
+ new org.onap.so.db.catalog.beans.InstanceGroup();
+ doReturn(catalogInstanceGroup).when(SPY_bbInputSetupUtils).getCatalogInstanceGroup(any());
+
+ SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName,
+ serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null,
+ requestDetails.getRequestInfo().getProductFamilyId());
+
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
+
+ SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName,
+ serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null,
+ requestDetails.getRequestInfo().getProductFamilyId());
+ verify(SPY_bbInputSetup, times(1)).mapCatalogVnf(vnf, modelInfo, service);
+
+ instanceName = "vnfName2";
+ GenericVnf vnf2 = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness,
+ resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId());
+
+ org.onap.aai.domain.yang.GenericVnf vnf2AAI = new org.onap.aai.domain.yang.GenericVnf();
+ vnfAAI.setModelCustomizationId("modelCustId2");
+ doReturn(vnf2AAI).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf2.getVnfId());
+ doNothing().when(SPY_bbInputSetup).mapCatalogVnf(vnf2, modelInfo, service);
+ doNothing().when(SPY_bbInputSetup).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}");
+ SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName,
+ serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null,
+ requestDetails.getRequestInfo().getProductFamilyId());
+ verify(SPY_bbInputSetup, times(2)).mapCatalogVnf(vnf2, modelInfo, service);
+ verify(SPY_bbInputSetup, times(2)).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}");
+ verify(SPY_bbInputSetup, times(1)).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service);
+ }
+
+ @Test
+ public void testMapCatalogVnf() {
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ GenericVnf genericVnf = new GenericVnf();
+ RequestDetails requestDetails = new RequestDetails();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationUuid("modelCustomizationUUID");
+ requestDetails.setModelInfo(modelInfo);
+ Service service = new Service();
+ VnfResourceCustomization resourceCust = new VnfResourceCustomization();
+ resourceCust.setModelCustomizationUUID("vnfModelCustomizationUUID");
+ service.getVnfCustomizations().add(resourceCust);
+ resourceCust.setModelCustomizationUUID("modelCustomizationUUID");
+
+ doReturn(modelInfoGenericVnf).when(bbInputSetupMapperLayer).mapCatalogVnfToVnf(resourceCust);
+
+ SPY_bbInputSetup.mapCatalogVnf(genericVnf, modelInfo, service);
+
+ assertEquals(modelInfoGenericVnf, genericVnf.getModelInfoGenericVnf());
+ }
+
+ @Test
+ public void testMapCatalogCollectionAndInstanceGroup() {
+ ModelInfoCollection modelInfoCollection = new ModelInfoCollection();
+ modelInfoCollection.setCollectionFunction("collectionFunction");
+ modelInfoCollection.setCollectionRole("collectionRole");
+ modelInfoCollection.setCollectionType("collectionType");
+ modelInfoCollection.setDescription("description");
+ modelInfoCollection.setModelInvariantUUID("modelInvariantUUID");
+ modelInfoCollection.setQuantity(0);
+
+ ModelInfoInstanceGroup modelInfoInstanceGroup = new ModelInfoInstanceGroup();
+ modelInfoInstanceGroup.setFunction("function");
+ modelInfoInstanceGroup.setInstanceGroupRole("instanceGroupRole");
+ modelInfoInstanceGroup.setModelInvariantUUID("modelInvariantUUID");
+ modelInfoInstanceGroup.setModelUUID("modelUUID");
+ modelInfoInstanceGroup.setType("VNFC");
+ modelInfoInstanceGroup.setDescription("description");
+
+ InstanceGroup instanceGroup = new InstanceGroup();
+ Collection collection = new Collection();
+ collection.setInstanceGroup(instanceGroup);
+
+ CollectionResource collectionResource = new CollectionResource();
+ org.onap.so.db.catalog.beans.InstanceGroup catalogInstanceGroup =
+ new org.onap.so.db.catalog.beans.InstanceGroup();
+ collectionResource.setToscaNodeType("NetworkCollection");
+ collectionResource.setInstanceGroup(catalogInstanceGroup);
+
+ CollectionResourceCustomization collectionCust = new NetworkCollectionResourceCustomization();
+ collectionCust.setModelCustomizationUUID("modelCustomizationUUID");
+ collectionCust.setCollectionResource(collectionResource);
+
+ Service service = new Service();
+ service.getCollectionResourceCustomizations().add(collectionCust);
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setCollection(collection);
+
+ List<CollectionResourceInstanceGroupCustomization> instanceGroupCustList = new ArrayList<>();
+ CollectionResourceInstanceGroupCustomization instanceGroupCust =
+ new CollectionResourceInstanceGroupCustomization();
+ instanceGroupCust.setFunction("function");
+ instanceGroupCust.setDescription("description");
+
+ doReturn(modelInfoCollection).when(bbInputSetupMapperLayer).mapCatalogCollectionToCollection(collectionCust,
+ collectionResource);
+
+ doReturn(modelInfoInstanceGroup).when(bbInputSetupMapperLayer)
+ .mapCatalogInstanceGroupToInstanceGroup(collectionCust, catalogInstanceGroup);
+
+ SPY_bbInputSetup.mapCatalogCollection(service, serviceInstance.getCollection(), "modelCustomizationUUID");
+ SPY_bbInputSetup.mapCatalogNetworkCollectionInstanceGroup(service,
+ serviceInstance.getCollection().getInstanceGroup(), collectionCust.getModelCustomizationUUID());
+
+ assertThat(collection.getModelInfoCollection(), sameBeanAs(modelInfoCollection));
+ assertThat(instanceGroup.getModelInfoInstanceGroup(), sameBeanAs(modelInfoInstanceGroup));
+ }
+
+ @Test
+ public void testAddRelationshipsToSI() throws Exception {
+ ServiceInstance serviceInstance = new ServiceInstance();
+ org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = new org.onap.aai.domain.yang.ServiceInstance();
+ serviceInstanceAAI.setServiceInstanceId("serviceInstanceId");
+
+ org.onap.aai.domain.yang.RelationshipList relationshipList = new org.onap.aai.domain.yang.RelationshipList();
+ org.onap.aai.domain.yang.Relationship relationship = new org.onap.aai.domain.yang.Relationship();
+ relationshipList.getRelationship().add(relationship);
+ serviceInstanceAAI.setRelationshipList(relationshipList);
+
+ Map<String, String> uriKeys = new HashMap<>();
+ uriKeys.put("global-customer-id", "globalCustomerId");
+ uriKeys.put("service-type", "serviceType");
+
+
+ doNothing().when(SPY_bbInputSetup).mapProject(any(), eq(serviceInstance));
+ doNothing().when(SPY_bbInputSetup).mapOwningEntity(any(), eq(serviceInstance));
+ doNothing().when(SPY_bbInputSetup).mapL3Networks(any(), eq(serviceInstance.getNetworks()));
+ doNothing().when(SPY_bbInputSetup).mapGenericVnfs(any(), eq(serviceInstance.getVnfs()));
+ doNothing().when(SPY_bbInputSetup).mapCollection(any(), eq(serviceInstance));
+
+ SPY_bbInputSetup.addRelationshipsToSI(serviceInstanceAAI, serviceInstance);
+
+ verify(SPY_bbInputSetup, times(1)).mapProject(any(), eq(serviceInstance));
+ verify(SPY_bbInputSetup, times(1)).mapOwningEntity(any(), eq(serviceInstance));
+ verify(SPY_bbInputSetup, times(1)).mapL3Networks(any(), eq(serviceInstance.getNetworks()));
+ verify(SPY_bbInputSetup, times(1)).mapGenericVnfs(any(), eq(serviceInstance.getVnfs()));
+ verify(SPY_bbInputSetup, times(1)).mapCollection(any(), eq(serviceInstance));
+ verify(SPY_bbInputSetup, times(1)).mapConfigurations(any(), eq(serviceInstance.getConfigurations()));
+ }
+
+ @Test
+ public void testMapConfigurations() throws JsonProcessingException {
+ org.onap.aai.domain.yang.Configuration expectedAAI = new org.onap.aai.domain.yang.Configuration();
+ org.onap.aai.domain.yang.RelationshipList relationshipList = new org.onap.aai.domain.yang.RelationshipList();
+ org.onap.aai.domain.yang.Relationship relationship = new org.onap.aai.domain.yang.Relationship();
+ relationshipList.getRelationship().add(relationship);
+ expectedAAI.setRelationshipList(relationshipList);
+
+ Configuration expected = new Configuration();
+ AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, "configurationId");
+ AAIResultWrapper configurationWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
+
+ doReturn(configurationWrapper).when(SPY_bbInputSetupUtils).getAAIResourceDepthOne(aaiResourceUri);
+ doReturn(expected).when(bbInputSetupMapperLayer)
+ .mapAAIConfiguration(isA(org.onap.aai.domain.yang.Configuration.class));
+
+ List<Configuration> configurations = new ArrayList<>();
+
+ SPY_bbInputSetup.mapConfigurations(Arrays.asList(new AAIResourceUri[] {aaiResourceUri}), configurations);
+
+ assertEquals(expected, configurations.get(0));
+ }
+
+ @Test
+ public void testMapGenericVnfs() throws JsonProcessingException {
+ org.onap.aai.domain.yang.GenericVnf expectedAAI = new org.onap.aai.domain.yang.GenericVnf();
+ org.onap.aai.domain.yang.RelationshipList relationshipList = new org.onap.aai.domain.yang.RelationshipList();
+ org.onap.aai.domain.yang.Relationship relationship = new org.onap.aai.domain.yang.Relationship();
+ relationshipList.getRelationship().add(relationship);
+ expectedAAI.setRelationshipList(relationshipList);
+
+ GenericVnf expected = new GenericVnf();
+ AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId");
+ AAIResultWrapper vnfWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
+
+ doReturn(vnfWrapper).when(SPY_bbInputSetupUtils).getAAIResourceDepthOne(aaiResourceUri);
+ doReturn(expected).when(bbInputSetupMapperLayer)
+ .mapAAIGenericVnfIntoGenericVnf(isA(org.onap.aai.domain.yang.GenericVnf.class));
+ doNothing().when(SPY_bbInputSetup).mapPlatform(any(), eq(expected));
+ doNothing().when(SPY_bbInputSetup).mapLineOfBusiness(any(), eq(expected));
+ doReturn(new ArrayList<>()).when(SPY_bbInputSetup).mapVolumeGroups(any());
+
+ List<GenericVnf> genericVnfs = new ArrayList<>();
+
+ SPY_bbInputSetup.mapGenericVnfs(Arrays.asList(new AAIResourceUri[] {aaiResourceUri}), genericVnfs);
+
+ assertEquals(expected, genericVnfs.get(0));
+ verify(SPY_bbInputSetup, times(1)).mapPlatform(any(), eq(expected));
+ verify(SPY_bbInputSetup, times(1)).mapLineOfBusiness(any(), eq(expected));
+ verify(SPY_bbInputSetup, times(1)).mapVolumeGroups(any());
+ }
+
+ @Test
+ public void testMapVolumeGroups() throws JsonProcessingException {
+ org.onap.aai.domain.yang.VolumeGroup expectedAAI = new org.onap.aai.domain.yang.VolumeGroup();
+
+ VolumeGroup expected = new VolumeGroup();
+ AAIResultWrapper vnfWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
+
+ doReturn(expected).when(bbInputSetupMapperLayer)
+ .mapAAIVolumeGroup(isA(org.onap.aai.domain.yang.VolumeGroup.class));
+
+ List<VolumeGroup> volumeGroupsList =
+ SPY_bbInputSetup.mapVolumeGroups(Arrays.asList(new AAIResultWrapper[] {vnfWrapper}));
+
+ assertEquals(expected, volumeGroupsList.get(0));
+ }
+
+ @Test
+ public void testMapLineOfBusiness() throws JsonProcessingException {
+ org.onap.aai.domain.yang.LineOfBusiness expectedAAI = new org.onap.aai.domain.yang.LineOfBusiness();
+
+ LineOfBusiness expected = new LineOfBusiness();
+ AAIResultWrapper vnfWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
+
+ doReturn(expected).when(bbInputSetupMapperLayer)
+ .mapAAILineOfBusiness(isA(org.onap.aai.domain.yang.LineOfBusiness.class));
+
+ GenericVnf vnf = new GenericVnf();
+
+ SPY_bbInputSetup.mapLineOfBusiness(Arrays.asList(new AAIResultWrapper[] {vnfWrapper}), vnf);
+
+ assertEquals(expected, vnf.getLineOfBusiness());
+ }
+
+ @Test
+ public void testMapPlatform() throws JsonProcessingException {
+ org.onap.aai.domain.yang.Platform expectedAAI = new org.onap.aai.domain.yang.Platform();
+
+ Platform expected = new Platform();
+ AAIResultWrapper vnfWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
+
+ doReturn(expected).when(bbInputSetupMapperLayer).mapAAIPlatform(isA(org.onap.aai.domain.yang.Platform.class));
+
+ GenericVnf vnf = new GenericVnf();
+
+ SPY_bbInputSetup.mapPlatform(Arrays.asList(new AAIResultWrapper[] {vnfWrapper}), vnf);
+
+ assertEquals(expected, vnf.getPlatform());
+ }
+
+ @Test
+ public void testMapCollection() throws JsonProcessingException {
+ List<AAIResultWrapper> collections = new ArrayList<>();
+ ServiceInstance serviceInstance = new ServiceInstance();
+
+ org.onap.aai.domain.yang.Collection aaiCollection = new org.onap.aai.domain.yang.Collection();
+ org.onap.aai.domain.yang.RelationshipList collectionRelationshipList =
+ new org.onap.aai.domain.yang.RelationshipList();
+ org.onap.aai.domain.yang.Relationship collectionInstanceGroupRelationship =
+ new org.onap.aai.domain.yang.Relationship();
+ collectionRelationshipList.getRelationship().add(collectionInstanceGroupRelationship);
+ aaiCollection.setRelationshipList(collectionRelationshipList);
+
+ collections.add(new AAIResultWrapper(
+ new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiCollection)));
+
+ Collection collection = new Collection();
+ ModelInfoCollection modelInfoCollection = new ModelInfoCollection();
+ List<InstanceGroup> instanceGroupsList = new ArrayList<>();
+ InstanceGroup instanceGroup = new InstanceGroup();
+ instanceGroupsList.add(instanceGroup);
+ NetworkCollectionResourceCustomization networkCollectionCust =
+ Mockito.mock(NetworkCollectionResourceCustomization.class);
+ CollectionResource collectionResource = new CollectionResource();
+ doReturn(collection).when(bbInputSetupMapperLayer)
+ .mapAAICollectionIntoCollection(isA(org.onap.aai.domain.yang.Collection.class));
+ doReturn(instanceGroupsList).when(SPY_bbInputSetup).mapInstanceGroups(any());
+ doReturn(networkCollectionCust).when(SPY_bbInputSetupUtils)
+ .getCatalogNetworkCollectionResourceCustByID(aaiCollection.getCollectionCustomizationId());
+ doReturn(collectionResource).when(networkCollectionCust).getCollectionResource();
+ doReturn(modelInfoCollection).when(bbInputSetupMapperLayer)
+ .mapCatalogCollectionToCollection(networkCollectionCust, collectionResource);
+
+ SPY_bbInputSetup.mapCollection(collections, serviceInstance);
+
+ assertEquals(collection, serviceInstance.getCollection());
+ assertEquals(instanceGroup, collection.getInstanceGroup());
+
+ instanceGroupsList.clear();
+ collection = new Collection();
+
+ SPY_bbInputSetup.mapCollection(collections, serviceInstance);
+ assertEquals(collection, serviceInstance.getCollection());
+ assertNull(collection.getInstanceGroup());
+ }
- SPY_bbInputSetup.mapCollection(collections, serviceInstance);
+ @Test
+ public void testMapL3Networks() throws JsonProcessingException {
+ org.onap.aai.domain.yang.L3Network expectedAAI = new org.onap.aai.domain.yang.L3Network();
+ org.onap.aai.domain.yang.RelationshipList relationshipList = new org.onap.aai.domain.yang.RelationshipList();
+ org.onap.aai.domain.yang.Relationship relationship = new org.onap.aai.domain.yang.Relationship();
+ relationshipList.getRelationship().add(relationship);
+ expectedAAI.setRelationshipList(relationshipList);
- assertEquals(collection, serviceInstance.getCollection());
- assertEquals(instanceGroup, collection.getInstanceGroup());
-
- instanceGroupsList.clear();
- collection = new Collection();
-
- SPY_bbInputSetup.mapCollection(collections, serviceInstance);
- assertEquals(collection, serviceInstance.getCollection());
- assertNull(collection.getInstanceGroup());
- }
+ L3Network expected = new L3Network();
+ List<L3Network> l3Networks = new ArrayList<>();
+ AAIResultWrapper l3NetworksWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
+ AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, "networkId");
- @Test
- public void testMapL3Networks() throws JsonProcessingException {
- org.onap.aai.domain.yang.L3Network expectedAAI = new org.onap.aai.domain.yang.L3Network();
- org.onap.aai.domain.yang.RelationshipList relationshipList = new org.onap.aai.domain.yang.RelationshipList();
- org.onap.aai.domain.yang.Relationship relationship = new org.onap.aai.domain.yang.Relationship();
- relationshipList.getRelationship().add(relationship);
- expectedAAI.setRelationshipList(relationshipList);
+ doReturn(l3NetworksWrapper).when(SPY_bbInputSetupUtils).getAAIResourceDepthTwo(aaiResourceUri);
+ doReturn(expected).when(bbInputSetupMapperLayer).mapAAIL3Network(isA(org.onap.aai.domain.yang.L3Network.class));
+ doNothing().when(SPY_bbInputSetup).mapNetworkPolicies(any(), eq(expected.getNetworkPolicies()));
+ doNothing().when(SPY_bbInputSetup).mapRouteTableReferences(any(),
+ eq(expected.getContrailNetworkRouteTableReferences()));
+
+ SPY_bbInputSetup.mapL3Networks(Arrays.asList(new AAIResourceUri[] {aaiResourceUri}), l3Networks);
+
+ assertEquals(expected, l3Networks.get(0));
+ verify(SPY_bbInputSetup, times(1)).mapNetworkPolicies(any(), eq(expected.getNetworkPolicies()));
+ verify(SPY_bbInputSetup, times(1)).mapRouteTableReferences(any(),
+ eq(expected.getContrailNetworkRouteTableReferences()));
+ }
+
+ @Test
+ public void testMapRouteTableReferences() throws JsonProcessingException {
+ org.onap.aai.domain.yang.RouteTableReference expectedAAI = new org.onap.aai.domain.yang.RouteTableReference();
+
+ RouteTableReference expected = new RouteTableReference();
+ List<RouteTableReference> contrailNetworkRouteTableReferences = new ArrayList<>();
+ AAIResultWrapper vnfWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
+
+ doReturn(expected).when(bbInputSetupMapperLayer).mapAAIRouteTableReferenceIntoRouteTableReference(
+ isA(org.onap.aai.domain.yang.RouteTableReference.class));
+
+ SPY_bbInputSetup.mapRouteTableReferences(Arrays.asList(new AAIResultWrapper[] {vnfWrapper}),
+ contrailNetworkRouteTableReferences);
+
+ assertEquals(expected, contrailNetworkRouteTableReferences.get(0));
+ }
+
+ @Test
+ public void testMapOwningEntity() throws JsonProcessingException {
+ org.onap.aai.domain.yang.OwningEntity expectedAAI = new org.onap.aai.domain.yang.OwningEntity();
+
+ OwningEntity expected = new OwningEntity();
+ AAIResultWrapper vnfWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
+
+ doReturn(expected).when(bbInputSetupMapperLayer)
+ .mapAAIOwningEntity(isA(org.onap.aai.domain.yang.OwningEntity.class));
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+
+ SPY_bbInputSetup.mapOwningEntity(Arrays.asList(new AAIResultWrapper[] {vnfWrapper}), serviceInstance);
+
+ assertEquals(expected, serviceInstance.getOwningEntity());
+ }
+
+ @Test
+ public void testMapProject() throws JsonProcessingException {
+ org.onap.aai.domain.yang.Project expectedAAI = new org.onap.aai.domain.yang.Project();
+
+ Project expected = new Project();
+ AAIResultWrapper vnfWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
+
+ doReturn(expected).when(bbInputSetupMapperLayer).mapAAIProject(isA(org.onap.aai.domain.yang.Project.class));
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+
+ SPY_bbInputSetup.mapProject(Arrays.asList(new AAIResultWrapper[] {vnfWrapper}), serviceInstance);
+
+ assertEquals(expected, serviceInstance.getProject());
+ }
+
+ @Test
+ public void testMapCustomer() throws Exception {
+ org.onap.aai.domain.yang.Customer customerAAI = new org.onap.aai.domain.yang.Customer();
+ org.onap.aai.domain.yang.ServiceSubscription serviceSubscriptionAAI =
+ new org.onap.aai.domain.yang.ServiceSubscription();
+
+ Customer expected = new Customer();
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+
+ String globalCustomerId = "globalCustomerId";
+ String subscriptionServiceType = "subscriptionServiceType";
+
+ doReturn(customerAAI).when(SPY_bbInputSetupUtils).getAAICustomer(globalCustomerId);
+ doReturn(serviceSubscriptionAAI).when(SPY_bbInputSetupUtils).getAAIServiceSubscription(globalCustomerId,
+ subscriptionServiceType);
+ doReturn(expected).when(bbInputSetupMapperLayer).mapAAICustomer(isA(org.onap.aai.domain.yang.Customer.class));
+ doReturn(serviceSubscription).when(bbInputSetupMapperLayer)
+ .mapAAIServiceSubscription(isA(org.onap.aai.domain.yang.ServiceSubscription.class));
+
+ Customer actual = SPY_bbInputSetup.mapCustomer(globalCustomerId, subscriptionServiceType);
+
+ assertEquals(expected, actual);
+ assertEquals(serviceSubscription, expected.getServiceSubscription());
+ }
+
+ @Test
+ public void testPopulateLookupKeyMapWithIds() {
+ Map<ResourceKey, String> expected = new HashMap<>();
+ Map<ResourceKey, String> actual = new HashMap<>();
+ String serviceInstanceId = "serviceInstanceId";
+ String networkId = "networkId";
+ String vnfId = "vnfId";
+ String vfModuleId = "vfModuleId";
+ String volumeGroupId = "volumeGroupId";
+ String configurationId = "configurationId";
+ String instanceGroupId = "instancegroupId";
+
+ expected.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstanceId);
+ expected.put(ResourceKey.NETWORK_ID, networkId);
+ expected.put(ResourceKey.GENERIC_VNF_ID, vnfId);
+ expected.put(ResourceKey.VF_MODULE_ID, vfModuleId);
+ expected.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupId);
+ expected.put(ResourceKey.CONFIGURATION_ID, configurationId);
+ expected.put(ResourceKey.INSTANCE_GROUP_ID, instanceGroupId);
+
+ WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
+ workflowResourceIds.setServiceInstanceId(serviceInstanceId);
+ workflowResourceIds.setNetworkId(networkId);
+ workflowResourceIds.setVnfId(vnfId);
+ workflowResourceIds.setVfModuleId(vfModuleId);
+ workflowResourceIds.setVolumeGroupId(volumeGroupId);
+ workflowResourceIds.setConfigurationId(configurationId);
+ workflowResourceIds.setInstanceGroupId(instanceGroupId);
+
+ SPY_bbInputSetup.populateLookupKeyMapWithIds(workflowResourceIds, actual);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testgetGBBMacro() throws Exception {
+ GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
+ InfraActiveRequests request = Mockito.mock(InfraActiveRequests.class);
+ org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
+ aaiVnf.setModelCustomizationId("modelCustId");
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId");
+ String resourceId = "123";
+ String vnfType = "vnfType";
+ Service service = Mockito.mock(Service.class);
+ String requestAction = "createInstance";
+
+ ConfigurationResourceKeys configResourceKeys = new ConfigurationResourceKeys();
+ configResourceKeys.setCvnfcCustomizationUUID("cvnfcCustomizationUUID");
+ configResourceKeys.setVfModuleCustomizationUUID("vfModuleCustomizationUUID");
+ configResourceKeys.setVnfResourceCustomizationUUID("vnfResourceCustomizationUUID");
+ executeBB.setConfigurationResourceKeys(configResourceKeys);
+
+ executeBB.setRequestDetails(requestDetails);
+ doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
+ doReturn(request).when(SPY_bbInputSetupUtils).getInfraActiveRequest(executeBB.getRequestId());
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
+ doNothing().when(SPY_bbInputSetupUtils).updateInfraActiveRequestVnfId(request,
+ lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID));
+ doReturn("vnfId").when(SPY_bbInputSetup).getVnfId(executeBB, lookupKeyMap);
+ doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(any(String.class));
+
+
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString());
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateL3Network(any(String.class), isA(ModelInfo.class),
+ isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(String.class), any());
+
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VNF.toString());
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateGenericVnf(isA(ModelInfo.class), any(String.class),
+ isA(org.onap.so.serviceinstancebeans.Platform.class),
+ isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class),
+ isA(ServiceInstance.class), any(), any(), any(String.class), any(String.class), any(),
+ any(String.class));
+
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString());
+ executeBB.getBuildingBlock().setKey("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateVfModule(isA(ModelInfo.class), isA(Service.class), any(String.class),
+ isA(ServiceInstance.class), any(), any(String.class), any(), any(String.class), any(),
+ isA(CloudConfiguration.class));
+
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VOLUME_GROUP.toString());
+ executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(isA(ModelInfo.class), isA(Service.class),
+ any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(),
+ ArgumentMatchers.isNull(), any(String.class), any());
+
+ Configuration configuration = new Configuration();
+ configuration.setConfigurationId("configurationId");
+ gBB.getServiceInstance().getConfigurations().add(configuration);
+ List<ConfigurationResourceCustomization> configurationCustList = new ArrayList<>();
+ ConfigurationResourceCustomization configurationCust = new ConfigurationResourceCustomization();
+ configurationCust.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa9");
+ doReturn(configurationCustList).when(service).getConfigurationCustomizations();
+ configurationCustList.add(configurationCust);
+ doNothing().when(SPY_bbInputSetup).populateConfiguration(isA(ModelInfo.class), isA(Service.class),
+ any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(),
+ isA(ConfigurationResourceKeys.class));
+
+ executeBB.getBuildingBlock().setBpmnFlowName("AssignFabricConfigurationBB");
+ executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa9");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateConfiguration(isA(ModelInfo.class), isA(Service.class),
+ any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(),
+ isA(ConfigurationResourceKeys.class));
+ }
+
+ @Test
+ public void testgetGBBMacroCloudConfiguration() throws Exception {
+ org.onap.so.serviceinstancebeans.Service serviceMacro = mapper.readValue(
+ new File(RESOURCE_PATH + "ServiceMacroVfModules.json"), org.onap.so.serviceinstancebeans.Service.class);
+ CloudConfiguration cloudConfig = null;
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = new org.onap.aai.domain.yang.CloudRegion();
+ aaiCloudRegion.setCloudOwner("test-owner-name");
+ Resources resources = serviceMacro.getResources();
+ doReturn(aaiCloudRegion).when(SPY_bbInputSetupUtils).getCloudRegion(any(CloudConfiguration.class));
+ CloudRegion expected = new CloudRegion();
+ expected.setLcpCloudRegionId("mdt1");
+ expected.setCloudOwner("test-owner-name");
+ expected.setTenantId("88a6ca3ee0394ade9403f075db23167e");
+
+ CloudRegion actual = SPY_bbInputSetup.getCloudRegionFromMacroRequest(cloudConfig, resources);
+ assertThat(actual, sameBeanAs(expected));
+
+ serviceMacro = mapper.readValue(new File(RESOURCE_PATH + "ServiceMacroVnfs.json"),
+ org.onap.so.serviceinstancebeans.Service.class);
+ resources = serviceMacro.getResources();
+
+ actual = SPY_bbInputSetup.getCloudRegionFromMacroRequest(cloudConfig, resources);
+ assertThat(actual, sameBeanAs(expected));
+
+ serviceMacro = mapper.readValue(new File(RESOURCE_PATH + "ServiceMacroNetworks.json"),
+ org.onap.so.serviceinstancebeans.Service.class);
+ resources = serviceMacro.getResources();
+
+ actual = SPY_bbInputSetup.getCloudRegionFromMacroRequest(cloudConfig, resources);
+ assertThat(actual, sameBeanAs(expected));
+
+ serviceMacro = mapper.readValue(new File(RESOURCE_PATH + "ServiceMacroNoCloudConfig.json"),
+ org.onap.so.serviceinstancebeans.Service.class);
+ resources = serviceMacro.getResources();
+
+ actual = SPY_bbInputSetup.getCloudRegionFromMacroRequest(cloudConfig, resources);
+ assertNull(actual);
+ }
+
+ @Test
+ public void testgetGBBMacroWithEmptyUserParams() throws Exception {
+ GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
+ requestDetails.getRequestParameters().getUserParams().clear();
+ InfraActiveRequests request = Mockito.mock(InfraActiveRequests.class);
+ org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
+ aaiVnf.setModelCustomizationId("modelCustId");
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
+ String resourceId = "123";
+ String vnfType = "vnfType";
+ Service service = Mockito.mock(Service.class);
+ String requestAction = "createInstance";
+
+ doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
+
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString());
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ executeBB.getBuildingBlock().setIsVirtualLink(Boolean.FALSE);
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).getGBBMacroNoUserParamsCreate(any(ExecuteBuildingBlock.class), any(),
+ any(String.class), any(String.class), any(GeneralBuildingBlock.class), any(Service.class));
+ }
+
+ @Test(expected = Exception.class)
+ public void testgetGBBMacroException() throws Exception {
+ GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ String resourceId = "123";
+ String vnfType = "vnfType";
+ Service service = Mockito.mock(Service.class);
+ String requestAction = "createInstance";
+
+ executeBB.getBuildingBlock().setBpmnFlowName("Network");
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ }
+
+ @Test
+ public void testgetGBBMacroWithVnfTypeNull() throws Exception {
+ GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
+ org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
+ aaiVnf.setModelCustomizationId("modelCustId");
+ InfraActiveRequests request = Mockito.mock(InfraActiveRequests.class);
+ String resourceId = "123";
+ String vnfType = null;
+ Service service = Mockito.mock(Service.class);
+ String requestAction = "createInstance";
+
+
+ executeBB.setRequestDetails(requestDetails);
+ doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
+ doReturn(request).when(SPY_bbInputSetupUtils).getInfraActiveRequest(executeBB.getRequestId());
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
+ doNothing().when(SPY_bbInputSetupUtils).updateInfraActiveRequestVnfId(request,
+ lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID));
+ doReturn("vnfId").when(SPY_bbInputSetup).getVnfId(executeBB, lookupKeyMap);
+ doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(any(String.class));
+
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString());
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateL3Network(any(String.class), isA(ModelInfo.class),
+ isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(String.class), any());
+
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VNF.toString());
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateGenericVnf(isA(ModelInfo.class), any(String.class),
+ isA(org.onap.so.serviceinstancebeans.Platform.class),
+ isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class),
+ isA(ServiceInstance.class), any(), ArgumentMatchers.isNull(), any(String.class),
+ ArgumentMatchers.isNull(), any(), any(String.class));
+
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString());
+ executeBB.getBuildingBlock().setKey("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateVfModule(isA(ModelInfo.class), isA(Service.class), any(String.class),
+ isA(ServiceInstance.class), any(), any(String.class), any(), any(String.class), any(),
+ isA(CloudConfiguration.class));
+
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VOLUME_GROUP.toString());
+ executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(isA(ModelInfo.class), isA(Service.class),
+ any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(),
+ ArgumentMatchers.isNull(), ArgumentMatchers.isNull(), any());
+ }
+
+ @Test
+ public void testgetGBBMacroGetServiceWithInvariantId() throws Exception {
+ GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
+ org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
+ aaiVnf.setModelCustomizationId("modelCustId");
+ InfraActiveRequests request = Mockito.mock(InfraActiveRequests.class);
+ String resourceId = "123";
+ String vnfType = "vnfType";
+ Service service = Mockito.mock(Service.class);
+ String requestAction = "createInstance";
+
+ executeBB.setRequestDetails(requestDetails);
+ doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
+ doReturn(request).when(SPY_bbInputSetupUtils).getInfraActiveRequest(executeBB.getRequestId());
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
+ doNothing().when(SPY_bbInputSetupUtils).updateInfraActiveRequestVnfId(request,
+ lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID));
+ doReturn("vnfId").when(SPY_bbInputSetup).getVnfId(executeBB, lookupKeyMap);
+ doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(any(String.class));
+
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString());
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateL3Network(any(String.class), isA(ModelInfo.class),
+ isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(String.class), any());
+
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VNF.toString());
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateGenericVnf(isA(ModelInfo.class), any(String.class),
+ isA(org.onap.so.serviceinstancebeans.Platform.class),
+ isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class),
+ isA(ServiceInstance.class), any(), any(), any(String.class), any(String.class), any(),
+ any(String.class));
+
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString());
+ executeBB.getBuildingBlock().setKey("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateVfModule(isA(ModelInfo.class), isA(Service.class), any(String.class),
+ isA(ServiceInstance.class), any(), any(String.class), any(), any(String.class), any(),
+ isA(CloudConfiguration.class));
+
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VOLUME_GROUP.toString());
+ executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(isA(ModelInfo.class), isA(Service.class),
+ any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(),
+ ArgumentMatchers.isNull(), any(String.class), any());
+ }
+
+ @Test
+ public void testgetGBBMacroNoUserParamsDeactivateInstnace() throws Exception {
+ GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
+ requestDetails.getRequestParameters().setUserParams(null);
+ org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
+ aaiVnf.setModelCustomizationId("modelCustId");
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
+ String resourceId = "123";
+ String vnfType = "vnfType";
+ Service service = Mockito.mock(Service.class);
+ String requestAction = "deactivateInstance";
+ doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
+ String generatedId = "12131";
+
+ executeBB.getBuildingBlock().setBpmnFlowName("DeactivateServiceInstanceBB");
+ executeBB.getBuildingBlock().setKey("3c40d244-808e-42ca-b09a-256d83d19d0a");
+ GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap,
+ requestAction, resourceId, vnfType);
+ assertThat(actual, sameBeanAs(gBB));
+ }
+
+ @Test
+ public void testgetGBBMacroNoUserParamsCreateInstance() throws Exception {
+ GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
+ InfraActiveRequests request = Mockito.mock(InfraActiveRequests.class);
+ requestDetails.getRequestParameters().setUserParams(null);
+ org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
+ aaiVnf.setModelCustomizationId("modelCustId");
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId");
+
+ ConfigurationResourceKeys configResourceKeys = new ConfigurationResourceKeys();
+ configResourceKeys.setCvnfcCustomizationUUID("cvnfcCustomizationUUID");
+ configResourceKeys.setVfModuleCustomizationUUID("vfModuleCustomizationUUID");
+ configResourceKeys.setVnfResourceCustomizationUUID("vnfResourceCustomizationUUID");
+ executeBB.setConfigurationResourceKeys(configResourceKeys);
+
+ String resourceId = "123";
+ String vnfType = "vnfType";
+ Service service = Mockito.mock(Service.class);
+ String requestAction = "createInstance";
+ doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
+
+
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
+ List<NetworkResourceCustomization> networkCustList = new ArrayList<>();
+ NetworkResourceCustomization networkCust = Mockito.mock(NetworkResourceCustomization.class);
+ doReturn("ab153b6e-c364-44c0-bef6-1f2982117f04").when(networkCust).getModelCustomizationUUID();
+ networkCustList.add(networkCust);
+ doReturn(networkCustList).when(service).getNetworkCustomizations();
+ doNothing().when(SPY_bbInputSetup).populateL3Network(any(), isA(ModelInfo.class), isA(Service.class),
+ any(String.class), isA(ServiceInstance.class), any(), any(String.class), any());
+
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString());
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ executeBB.getBuildingBlock().setIsVirtualLink(false);
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).getGBBMacroNoUserParamsCreate(executeBB, lookupKeyMap,
+ executeBB.getBuildingBlock().getBpmnFlowName(), "ab153b6e-c364-44c0-bef6-1f2982117f04", gBB, service);
+
+ CollectionNetworkResourceCustomization collectionNetworkResourceCust =
+ Mockito.mock(CollectionNetworkResourceCustomization.class);
+ doReturn(collectionNetworkResourceCust).when(SPY_bbInputSetupUtils)
+ .getCatalogCollectionNetworkResourceCustByID(any(String.class));
+ NetworkResourceCustomization networkResourceCustomization = Mockito.mock(NetworkResourceCustomization.class);
+ doReturn(networkResourceCustomization).when(bbInputSetupMapperLayer)
+ .mapCollectionNetworkResourceCustToNetworkResourceCust(collectionNetworkResourceCust);
+ ModelInfoNetwork modelInfoNetwork = Mockito.mock(ModelInfoNetwork.class);
+ doReturn(modelInfoNetwork).when(bbInputSetupMapperLayer)
+ .mapCatalogNetworkToNetwork(networkResourceCustomization);
+
+ executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString());
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ executeBB.getBuildingBlock().setIsVirtualLink(true);
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(2)).getGBBMacroNoUserParamsCreate(executeBB, lookupKeyMap,
+ executeBB.getBuildingBlock().getBpmnFlowName(), "ab153b6e-c364-44c0-bef6-1f2982117f04", gBB, service);
+
+ executeBB.getBuildingBlock().setBpmnFlowName("CreateNetworkBB");
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ executeBB.getBuildingBlock().setIsVirtualLink(true);
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).getGBBMacroNoUserParamsCreate(executeBB, lookupKeyMap,
+ executeBB.getBuildingBlock().getBpmnFlowName(), "ab153b6e-c364-44c0-bef6-1f2982117f04", gBB, service);
+ }
+
+ @Test
+ public void testgetGBBMacroNoUserParamsOther() throws Exception {
+ GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
+ requestDetails.getRequestParameters().setUserParams(null);
+ org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
+ aaiVnf.setModelCustomizationId("modelCustId");
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
+ String resourceId = "123";
+ String vnfType = "vnfType";
+ Service service = Mockito.mock(Service.class);
+ String requestAction = "deleteInstance";
+
+ executeBB.setRequestDetails(requestDetails);
+ ServiceInstance serviceInstance = gBB.getServiceInstance();
+ org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
+ aaiServiceInstance.setModelVersionId("modelVersionId");
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
+ doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils)
+ .getAAIServiceInstanceById(lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
+ doReturn(serviceInstance).when(SPY_bbInputSetup).getExistingServiceInstance(aaiServiceInstance);
+ doReturn(gBB).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
+ executeBB, requestAction, null);
+
+ CloudConfiguration cloudConfig = new CloudConfiguration();
+ cloudConfig.setLcpCloudRegionId("lcpCloudRegionId");
+ requestDetails.setCloudConfiguration(cloudConfig);
+ org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
+ doReturn(aaiCloudRegion).when(SPY_bbInputSetupUtils).getCloudRegion(requestDetails.getCloudConfiguration());
+ executeBB.getBuildingBlock().setBpmnFlowName("DeleteNetworkBB");
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(1)).getGBBMacroExistingService(isA(ExecuteBuildingBlock.class), any(),
+ any(String.class), isA(String.class), isA(CloudConfiguration.class));
+
+ requestAction = "activateInstance";
+ doReturn(gBB).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
+ executeBB, requestAction, null);
+ executeBB.getBuildingBlock().setBpmnFlowName("ActivateNetworkBB");
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(2)).getGBBMacroExistingService(isA(ExecuteBuildingBlock.class), any(),
+ any(String.class), isA(String.class), isA(CloudConfiguration.class));
+
+ requestAction = "unassignInstance";
+ doReturn(gBB).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
+ executeBB, requestAction, null);
+ executeBB.getBuildingBlock().setBpmnFlowName("UnassignNetworkBB");
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(3)).getGBBMacroExistingService(isA(ExecuteBuildingBlock.class), any(),
+ any(String.class), isA(String.class), isA(CloudConfiguration.class));
+
+ requestAction = "activateFabricConfiguration";
+ doReturn(gBB).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
+ executeBB, requestAction, null);
+ executeBB.getBuildingBlock().setBpmnFlowName("ActivateFabricConfigurationBB");
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-134534656234");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ verify(SPY_bbInputSetup, times(4)).getGBBMacroExistingService(isA(ExecuteBuildingBlock.class), any(),
+ any(String.class), isA(String.class), isA(CloudConfiguration.class));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testgetGBBMacroNoUserParamsOtherException() throws Exception {
+ GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
+ requestDetails.getRequestParameters().setUserParams(null);
+ org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
+ aaiVnf.setModelCustomizationId("modelCustId");
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
+ String resourceId = "123";
+ String vnfType = "vnfType";
+ Service service = Mockito.mock(Service.class);
+ String requestAction = "assignInstance";
+ doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
+ requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
+ String generatedId = "12131";
+
+ executeBB.getBuildingBlock().setKey("3c40d244-808e-42ca-b09a-256d83d19d0a");
+ SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
+ }
+
+ @Test
+ public void testgetGBBMacroNoUserParamsExistingService() throws Exception {
+ GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
+ GeneralBuildingBlock.class);
+ ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
+ ExecuteBuildingBlock.class);
+ RequestDetails requestDetails = mapper
+ .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
+ requestDetails.getRequestParameters().setUserParams(null);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId");
+ Service service = Mockito.mock(Service.class);
+ CloudConfiguration cloudConfiguration = new CloudConfiguration();
+ cloudConfiguration.setLcpCloudRegionId("cloudRegionId");
+ String requestAction = "unassignInstance";
+ executeBB.setRequestDetails(requestDetails);
+
+ ConfigurationResourceKeys configResourceKeys = new ConfigurationResourceKeys();
+ configResourceKeys.setCvnfcCustomizationUUID("cvnfcCustomizationUUID");
+ configResourceKeys.setVfModuleCustomizationUUID("vfModuleCustomizationUUID");
+ configResourceKeys.setVnfResourceCustomizationUUID("vnfResourceCustomizationUUID");
+ executeBB.setConfigurationResourceKeys(configResourceKeys);
+
+ ServiceInstance serviceInstance = gBB.getServiceInstance();
+ org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
+ aaiServiceInstance.setModelVersionId("modelVersionId");
+ doReturn(service).when(SPY_bbInputSetupUtils)
+ .getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
+ doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils)
+ .getAAIServiceInstanceById(lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
+ doReturn(serviceInstance).when(SPY_bbInputSetup).getExistingServiceInstance(aaiServiceInstance);
+ doReturn(gBB).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
+ executeBB, requestAction, null);
+
+ L3Network network = new L3Network();
+ network.setNetworkId("networkId");
+ gBB.getServiceInstance().getNetworks().add(network);
+ org.onap.aai.domain.yang.L3Network aaiNetwork = new org.onap.aai.domain.yang.L3Network();
+ aaiNetwork.setModelCustomizationId("modelCustId");
+ doReturn(aaiNetwork).when(SPY_bbInputSetupUtils).getAAIL3Network(network.getNetworkId());
+ doNothing().when(SPY_bbInputSetup).mapCatalogNetwork(any(L3Network.class), any(ModelInfo.class),
+ any(Service.class));
+
+ executeBB.getBuildingBlock().setBpmnFlowName("DeleteNetworkBB");
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap,
+ executeBB.getBuildingBlock().getBpmnFlowName(), requestAction, null);
+ verify(SPY_bbInputSetup, times(1)).mapCatalogNetwork(any(L3Network.class), any(ModelInfo.class),
+ any(Service.class));
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnfId");
+ gBB.getServiceInstance().getVnfs().add(vnf);
+ org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
+ aaiVnf.setModelCustomizationId("modelCustId");
+ doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId());
+ doNothing().when(SPY_bbInputSetup).mapCatalogVnf(any(GenericVnf.class), any(ModelInfo.class),
+ any(Service.class));
+
+ executeBB.getBuildingBlock().setBpmnFlowName("ActivateVnfBB");
+ executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
+ SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap,
+ executeBB.getBuildingBlock().getBpmnFlowName(), requestAction, cloudConfiguration);
+ verify(SPY_bbInputSetup, times(1)).mapCatalogVnf(any(GenericVnf.class), any(ModelInfo.class),
+ any(Service.class));
+
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("vfModuleId");
+ gBB.getServiceInstance().getVnfs().get(0).getVfModules().add(vfModule);
+ org.onap.aai.domain.yang.VfModule aaiVfModule = new org.onap.aai.domain.yang.VfModule();
+ aaiVfModule.setModelCustomizationId("modelCustId");
+ doReturn(aaiVfModule).when(SPY_bbInputSetupUtils).getAAIVfModule(vnf.getVnfId(), vfModule.getVfModuleId());
+
+ executeBB.getBuildingBlock().setBpmnFlowName("UnassignVfModuleBB");
+ executeBB.getBuildingBlock().setKey("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
+ SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap,
+ executeBB.getBuildingBlock().getBpmnFlowName(), requestAction, cloudConfiguration);
+ verify(SPY_bbInputSetup, times(2)).mapCatalogVnf(any(GenericVnf.class), any(ModelInfo.class),
+ any(Service.class));
+ verify(SPY_bbInputSetup, times(1)).mapCatalogVfModule(any(VfModule.class), any(ModelInfo.class),
+ any(Service.class), any(String.class));
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("cloudRegionId");
+ cloudRegion.setCloudOwner("CloudOwner");
+ doReturn(Optional.of(cloudRegion)).when(SPY_cloudInfoFromAAI).getCloudInfoFromAAI(gBB.getServiceInstance());
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("volumeGroupId");
+ gBB.getServiceInstance().getVnfs().get(0).getVolumeGroups().add(volumeGroup);
+ org.onap.aai.domain.yang.VolumeGroup aaiVolumeGroup = new org.onap.aai.domain.yang.VolumeGroup();
+ aaiVolumeGroup.setModelCustomizationId("modelCustId");
+ doReturn(aaiVolumeGroup).when(SPY_bbInputSetupUtils).getAAIVolumeGroup(cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
+
+ executeBB.getBuildingBlock().setBpmnFlowName("UnassignVolumeGroupBB");
+ executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
+ SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap,
+ executeBB.getBuildingBlock().getBpmnFlowName(), requestAction, null);
+ verify(SPY_bbInputSetup, times(3)).mapCatalogVnf(any(GenericVnf.class), any(ModelInfo.class),
+ any(Service.class));
+ verify(SPY_bbInputSetup, times(1)).mapCatalogVolumeGroup(isA(VolumeGroup.class), isA(ModelInfo.class),
+ isA(Service.class), isA(String.class));
+
+ Configuration configuration = new Configuration();
+ configuration.setConfigurationId("configurationId");
+ gBB.getServiceInstance().getConfigurations().add(configuration);
+ org.onap.aai.domain.yang.Configuration aaiConfiguration = new org.onap.aai.domain.yang.Configuration();
+ aaiConfiguration.setModelCustomizationId("modelCustId");
+ doReturn(aaiConfiguration).when(SPY_bbInputSetupUtils).getAAIConfiguration(configuration.getConfigurationId());
+ doNothing().when(SPY_bbInputSetup).mapCatalogConfiguration(isA(Configuration.class), isA(ModelInfo.class),
+ isA(Service.class), isA(ConfigurationResourceKeys.class));
+
+ executeBB.getBuildingBlock().setBpmnFlowName("ActivateFabricConfigurationBB");
+ executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa9");
+ SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap,
+ executeBB.getBuildingBlock().getBpmnFlowName(), requestAction, cloudConfiguration);
+ verify(SPY_bbInputSetup, times(1)).mapCatalogConfiguration(any(Configuration.class), any(ModelInfo.class),
+ any(Service.class), isA(ConfigurationResourceKeys.class));
+ }
+
+ @Test
+ public void testGetVnfId() {
+ String expected = "vnfId";
+ ExecuteBuildingBlock executeBB = new ExecuteBuildingBlock();
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ executeBB.setRequestId("requestId");
+ InfraActiveRequests request = new InfraActiveRequests();
+ request.setVnfId(expected);
+ doReturn(request).when(SPY_bbInputSetupUtils).getInfraActiveRequest(executeBB.getRequestId());
+
+ String actual = SPY_bbInputSetup.getVnfId(executeBB, lookupKeyMap);
+
+ assertEquals("VnfId is set correctly", expected, actual);
+ }
+
+ @Test
+ public void testCreateVfModule() {
+ String vfModuleId = "vfModuleId";
+ String instanceName = "vfModuleName";
+ Map<String, String> cloudParams = new HashMap<>();
+ cloudParams.put("param1", "param1Value");
+ VfModule expected = new VfModule();
+ expected.setVfModuleId(vfModuleId);
+ expected.setVfModuleName(instanceName);
+ expected.setCloudParams(cloudParams);
+ expected.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ List<Map<String, String>> instanceParams = new ArrayList<>();
+ instanceParams.add(cloudParams);
+
+ VfModule actual = SPY_bbInputSetup.createVfModule(lookupKeyMap, vfModuleId, instanceName, instanceParams);
+
+ assertThat(actual, sameBeanAs(expected));
+ assertEquals("LookupKeyMap is populated", vfModuleId, lookupKeyMap.get(ResourceKey.VF_MODULE_ID));
+
+ expected.getCloudParams().clear();
+ actual = SPY_bbInputSetup.createVfModule(lookupKeyMap, vfModuleId, instanceName, null);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testCreateVolumeGroup() {
+ String volumeGroupId = "volumeGroupId";
+ String instanceName = "vfModuleName";
+ String vnfType = "vnfType";
+ Map<String, String> cloudParams = new HashMap<>();
+ cloudParams.put("param1", "param1Value");
+ VolumeGroup expected = new VolumeGroup();
+ expected.setVolumeGroupId(volumeGroupId);
+ expected.setVolumeGroupName(instanceName);
+ expected.setCloudParams(cloudParams);
+ expected.setVnfType(vnfType);
+ expected.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ List<Map<String, String>> instanceParams = new ArrayList<>();
+ instanceParams.add(cloudParams);
+
+ VolumeGroup actual =
+ SPY_bbInputSetup.createVolumeGroup(lookupKeyMap, volumeGroupId, instanceName, vnfType, instanceParams);
+
+ assertThat(actual, sameBeanAs(expected));
+ assertEquals("LookupKeyMap is populated", volumeGroupId, lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID));
+
+ expected.getCloudParams().clear();
+ actual = SPY_bbInputSetup.createVolumeGroup(lookupKeyMap, volumeGroupId, instanceName, vnfType, null);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testCreateNetwork() {
+ String networkId = "networkId";
+ String instanceName = "networkName";
+ Map<String, String> cloudParams = new HashMap<>();
+ cloudParams.put("param1", "param1Value");
+ L3Network expected = new L3Network();
+ expected.setNetworkId(networkId);
+ expected.setNetworkName(instanceName);
+ expected.setCloudParams(cloudParams);
+ expected.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ List<Map<String, String>> instanceParams = new ArrayList<>();
+ instanceParams.add(cloudParams);
+ L3Network actual = SPY_bbInputSetup.createNetwork(lookupKeyMap, instanceName, networkId, instanceParams);
+
+ assertThat(actual, sameBeanAs(expected));
+ assertEquals("LookupKeyMap is populated", networkId, lookupKeyMap.get(ResourceKey.NETWORK_ID));
+
+ expected.getCloudParams().clear();
+ actual = SPY_bbInputSetup.createNetwork(lookupKeyMap, instanceName, networkId, null);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testCreateGenericVnf() {
+ String vnfId = "vnfId";
+ String instanceName = "vnfName";
+ String vnfType = "vnfType";
+ String platformName = "platformName";
+ String lineOfBusinessName = "lineOfBusinessName";
+ String productFamilyId = "productFamilyId";
+ Platform platform = new Platform();
+ platform.setPlatformName(platformName);
+ LineOfBusiness lineOfBusiness = new LineOfBusiness();
+ lineOfBusiness.setLineOfBusinessName(lineOfBusinessName);
+ Map<String, String> cloudParams = new HashMap<>();
+ cloudParams.put("param1", "param1Value");
+ GenericVnf expected = new GenericVnf();
+ expected.setVnfId(vnfId);
+ expected.setVnfName(instanceName);
+ expected.setVnfType(vnfType);
+ expected.setCloudParams(cloudParams);
+ expected.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ expected.setPlatform(platform);
+ expected.setLineOfBusiness(lineOfBusiness);
+ expected.setProvStatus("PREPROV");
+ expected.setServiceId(productFamilyId);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ List<Map<String, String>> instanceParams = new ArrayList<>();
+ instanceParams.add(cloudParams);
+ org.onap.so.serviceinstancebeans.Platform requestPlatform = new org.onap.so.serviceinstancebeans.Platform();
+ platform.setPlatformName(platformName);
+ org.onap.so.serviceinstancebeans.LineOfBusiness requestLineOfBusiness =
+ new org.onap.so.serviceinstancebeans.LineOfBusiness();
+ lineOfBusiness.setLineOfBusinessName(lineOfBusinessName);
+
+ doReturn(platform).when(bbInputSetupMapperLayer).mapRequestPlatform(requestPlatform);
+ doReturn(lineOfBusiness).when(bbInputSetupMapperLayer).mapRequestLineOfBusiness(requestLineOfBusiness);
+
+ GenericVnf actual = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, requestPlatform,
+ requestLineOfBusiness, vnfId, vnfType, instanceParams, productFamilyId);
+
+ assertThat(actual, sameBeanAs(expected));
+ assertEquals("LookupKeyMap is populated", vnfId, lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID));
+
+ expected.getCloudParams().clear();
+ actual = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, requestPlatform, requestLineOfBusiness,
+ vnfId, vnfType, null, productFamilyId);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testMapCatalogVfModule() {
+ String vnfModelCustomizationUUID = "vnfResourceCustUUID";
+ String vfModuleCustomizationUUID = "vfModelCustomizationUUID";
+ VfModule vfModule = new VfModule();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationUuid(vfModuleCustomizationUUID);
+ Service service = new Service();
+ VnfResourceCustomization vnfResourceCust = new VnfResourceCustomization();
+ vnfResourceCust.setModelCustomizationUUID(vnfModelCustomizationUUID);
+ VfModuleCustomization vfModuleCust = new VfModuleCustomization();
+ vfModuleCust.setModelCustomizationUUID(vfModuleCustomizationUUID);
+ vnfResourceCust.getVfModuleCustomizations().add(vfModuleCust);
+ service.getVnfCustomizations().add(vnfResourceCust);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+
+ doReturn(modelInfoVfModule).when(bbInputSetupMapperLayer).mapCatalogVfModuleToVfModule(vfModuleCust);
+
+ SPY_bbInputSetup.mapCatalogVfModule(vfModule, modelInfo, service, vnfModelCustomizationUUID);
+
+ assertThat(vfModule.getModelInfoVfModule(), sameBeanAs(modelInfoVfModule));
+
+ modelInfo.setModelCustomizationUuid(null);
+ modelInfo.setModelCustomizationId(vfModuleCustomizationUUID);
+
+ SPY_bbInputSetup.mapCatalogVfModule(vfModule, modelInfo, service, vnfModelCustomizationUUID);
+
+ assertThat(vfModule.getModelInfoVfModule(), sameBeanAs(modelInfoVfModule));
+ }
+
+ @Test
+ public void testPopulateVfModule() throws Exception {
+ String vnfId = "vnfId";
+ String vfModuleId = "vfModuleId";
+ String volumeGroupId = "volumeGroupId";
+ String vfModuleCustomizationId = "vfModuleCustomizationId";
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationId(vfModuleCustomizationId);
+ Service service = new Service();
+ String bbName = AssignFlows.VF_MODULE.toString();
+ ServiceInstance serviceInstance = new ServiceInstance();
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId(vnfId);
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId(volumeGroupId);
+ vnf.getVolumeGroups().add(volumeGroup);
+ serviceInstance.getVnfs().add(vnf);
+ VfModule vfModule1 = new VfModule();
+ vfModule1.setVfModuleId("vfModuleId1");
+ VfModule vfModule2 = new VfModule();
+ vfModule2.setVfModuleId("vfModuleId2");
+ vnf.getVfModules().add(vfModule1);
+ vnf.getVfModules().add(vfModule2);
+ Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnfId);
+ String resourceId = vfModuleId;
+ RelatedInstanceList[] relatedInstanceList = null;
+ String instanceName = "vfModuleName";
+ List<Map<String, String>> instanceParams = null;
+ CloudConfiguration cloudConfiguration = new CloudConfiguration();
+
+ org.onap.aai.domain.yang.GenericVnf vnfAAI = new org.onap.aai.domain.yang.GenericVnf();
+ vnfAAI.setModelCustomizationId("vnfModelCustId");
+ org.onap.aai.domain.yang.VolumeGroup volumeGroupAAI = new org.onap.aai.domain.yang.VolumeGroup();
+ volumeGroupAAI.setModelCustomizationId(vfModuleCustomizationId);
+ org.onap.aai.domain.yang.VfModule vfModuleAAI = new org.onap.aai.domain.yang.VfModule();
+ vfModuleAAI.setModelCustomizationId(vfModuleCustomizationId);
+
+ doReturn(vnfAAI).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId());
+ doReturn(volumeGroupAAI).when(SPY_bbInputSetupUtils).getAAIVolumeGroup(CLOUD_OWNER,
+ cloudConfiguration.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
+ doReturn(vfModuleAAI).when(SPY_bbInputSetupUtils).getAAIVfModule(isA(String.class), isA(String.class));
+ doNothing().when(SPY_bbInputSetup).mapCatalogVnf(isA(GenericVnf.class), isA(ModelInfo.class),
+ isA(Service.class));
+ doNothing().when(SPY_bbInputSetup).mapCatalogVfModule(isA(VfModule.class), isA(ModelInfo.class),
+ isA(Service.class), isA(String.class));
+
+ SPY_bbInputSetup.populateVfModule(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId,
+ relatedInstanceList, instanceName, instanceParams, cloudConfiguration);
+
+ verify(SPY_bbInputSetup, times(3)).mapCatalogVfModule(isA(VfModule.class), isA(ModelInfo.class),
+ isA(Service.class), isA(String.class));
+ assertEquals("Lookup Key Map populated with VfModule Id", vfModuleId,
+ lookupKeyMap.get(ResourceKey.VF_MODULE_ID));
+ assertEquals("Lookup Key Map populated with VolumeGroup Id", volumeGroupId,
+ lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID));
+ }
+
+ @Test
+ public void testGettingVnfcToConfiguration() throws Exception {
+
+ String vnfcName = "vnfcName";
+ org.onap.aai.domain.yang.Configuration expectedAAI = new org.onap.aai.domain.yang.Configuration();
+ AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VNFC, vnfcName);
+ AAIResultWrapper configurationWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
+
+ doReturn(new AAIResultWrapper(null)).when(SPY_bbInputSetupUtils).getAAIResourceDepthOne(aaiResourceUri);
+ Vnfc vnfc = SPY_bbInputSetup.getVnfcToConfiguration(vnfcName);
+ Assert.assertNull(vnfc);
+
+ doReturn(configurationWrapper).when(SPY_bbInputSetupUtils).getAAIResourceDepthOne(aaiResourceUri);
+ vnfc = SPY_bbInputSetup.getVnfcToConfiguration(vnfcName);
+ Assert.assertNotNull(vnfc);
+ }
- L3Network expected = new L3Network();
- List<L3Network> l3Networks = new ArrayList<>();
- AAIResultWrapper l3NetworksWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
- AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, "networkId");
- doReturn(l3NetworksWrapper).when(SPY_bbInputSetupUtils).getAAIResourceDepthTwo(aaiResourceUri);
- doReturn(expected).when(bbInputSetupMapperLayer)
- .mapAAIL3Network(isA(org.onap.aai.domain.yang.L3Network.class));
- doNothing().when(SPY_bbInputSetup).mapNetworkPolicies(any(), eq(expected.getNetworkPolicies()));
- doNothing().when(SPY_bbInputSetup).mapRouteTableReferences(any(),
- eq(expected.getContrailNetworkRouteTableReferences()));
-
- SPY_bbInputSetup.mapL3Networks(Arrays.asList(new AAIResourceUri[] { aaiResourceUri }), l3Networks);
-
- assertEquals(expected, l3Networks.get(0));
- verify(SPY_bbInputSetup, times(1)).mapNetworkPolicies(any(), eq(expected.getNetworkPolicies()));
- verify(SPY_bbInputSetup, times(1)).mapRouteTableReferences(any(),
- eq(expected.getContrailNetworkRouteTableReferences()));
- }
-
- @Test
- public void testMapRouteTableReferences() throws JsonProcessingException {
- org.onap.aai.domain.yang.RouteTableReference expectedAAI = new org.onap.aai.domain.yang.RouteTableReference();
-
- RouteTableReference expected = new RouteTableReference();
- List<RouteTableReference> contrailNetworkRouteTableReferences = new ArrayList<>();
- AAIResultWrapper vnfWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
-
- doReturn(expected).when(bbInputSetupMapperLayer).mapAAIRouteTableReferenceIntoRouteTableReference(
- isA(org.onap.aai.domain.yang.RouteTableReference.class));
-
- SPY_bbInputSetup.mapRouteTableReferences(Arrays.asList(new AAIResultWrapper[] { vnfWrapper }),
- contrailNetworkRouteTableReferences);
-
- assertEquals(expected, contrailNetworkRouteTableReferences.get(0));
- }
-
- @Test
- public void testMapOwningEntity() throws JsonProcessingException {
- org.onap.aai.domain.yang.OwningEntity expectedAAI = new org.onap.aai.domain.yang.OwningEntity();
-
- OwningEntity expected = new OwningEntity();
- AAIResultWrapper vnfWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
-
- doReturn(expected).when(bbInputSetupMapperLayer)
- .mapAAIOwningEntity(isA(org.onap.aai.domain.yang.OwningEntity.class));
-
- ServiceInstance serviceInstance = new ServiceInstance();
-
- SPY_bbInputSetup.mapOwningEntity(Arrays.asList(new AAIResultWrapper[] { vnfWrapper }), serviceInstance);
-
- assertEquals(expected, serviceInstance.getOwningEntity());
- }
-
- @Test
- public void testMapProject() throws JsonProcessingException {
- org.onap.aai.domain.yang.Project expectedAAI = new org.onap.aai.domain.yang.Project();
-
- Project expected = new Project();
- AAIResultWrapper vnfWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
-
- doReturn(expected).when(bbInputSetupMapperLayer).mapAAIProject(isA(org.onap.aai.domain.yang.Project.class));
-
- ServiceInstance serviceInstance = new ServiceInstance();
-
- SPY_bbInputSetup.mapProject(Arrays.asList(new AAIResultWrapper[] { vnfWrapper }), serviceInstance);
-
- assertEquals(expected, serviceInstance.getProject());
- }
-
- @Test
- public void testMapCustomer() throws Exception {
- org.onap.aai.domain.yang.Customer customerAAI = new org.onap.aai.domain.yang.Customer();
- org.onap.aai.domain.yang.ServiceSubscription serviceSubscriptionAAI = new org.onap.aai.domain.yang.ServiceSubscription();
-
- Customer expected = new Customer();
- ServiceSubscription serviceSubscription = new ServiceSubscription();
-
- String globalCustomerId = "globalCustomerId";
- String subscriptionServiceType = "subscriptionServiceType";
-
- doReturn(customerAAI).when(SPY_bbInputSetupUtils).getAAICustomer(globalCustomerId);
- doReturn(serviceSubscriptionAAI).when(SPY_bbInputSetupUtils).getAAIServiceSubscription(globalCustomerId,
- subscriptionServiceType);
- doReturn(expected).when(bbInputSetupMapperLayer)
- .mapAAICustomer(isA(org.onap.aai.domain.yang.Customer.class));
- doReturn(serviceSubscription).when(bbInputSetupMapperLayer)
- .mapAAIServiceSubscription(isA(org.onap.aai.domain.yang.ServiceSubscription.class));
-
- Customer actual = SPY_bbInputSetup.mapCustomer(globalCustomerId, subscriptionServiceType);
-
- assertEquals(expected, actual);
- assertEquals(serviceSubscription, expected.getServiceSubscription());
- }
-
- @Test
- public void testPopulateLookupKeyMapWithIds() {
- Map<ResourceKey, String> expected = new HashMap<>();
- Map<ResourceKey, String> actual = new HashMap<>();
- String serviceInstanceId = "serviceInstanceId";
- String networkId = "networkId";
- String vnfId = "vnfId";
- String vfModuleId = "vfModuleId";
- String volumeGroupId = "volumeGroupId";
- String configurationId = "configurationId";
- String instanceGroupId = "instancegroupId";
-
- expected.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstanceId);
- expected.put(ResourceKey.NETWORK_ID, networkId);
- expected.put(ResourceKey.GENERIC_VNF_ID, vnfId);
- expected.put(ResourceKey.VF_MODULE_ID, vfModuleId);
- expected.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupId);
- expected.put(ResourceKey.CONFIGURATION_ID, configurationId);
- expected.put(ResourceKey.INSTANCE_GROUP_ID, instanceGroupId);
-
- WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
- workflowResourceIds.setServiceInstanceId(serviceInstanceId);
- workflowResourceIds.setNetworkId(networkId);
- workflowResourceIds.setVnfId(vnfId);
- workflowResourceIds.setVfModuleId(vfModuleId);
- workflowResourceIds.setVolumeGroupId(volumeGroupId);
- workflowResourceIds.setConfigurationId(configurationId);
- workflowResourceIds.setInstanceGroupId(instanceGroupId);
-
- SPY_bbInputSetup.populateLookupKeyMapWithIds(workflowResourceIds, actual);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testgetGBBMacro() throws Exception {
- GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper
- .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
- InfraActiveRequests request = Mockito.mock(InfraActiveRequests.class);
- org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
- aaiVnf.setModelCustomizationId("modelCustId");
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId");
- String resourceId = "123";
- String vnfType = "vnfType";
- Service service = Mockito.mock(Service.class);
- String requestAction = "createInstance";
-
- ConfigurationResourceKeys configResourceKeys = new ConfigurationResourceKeys();
- configResourceKeys.setCvnfcCustomizationUUID("cvnfcCustomizationUUID");
- configResourceKeys.setVfModuleCustomizationUUID("vfModuleCustomizationUUID");
- configResourceKeys.setVnfResourceCustomizationUUID("vnfResourceCustomizationUUID");
- executeBB.setConfigurationResourceKeys(configResourceKeys);
-
- executeBB.setRequestDetails(requestDetails);
- doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
- requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
- doReturn(request).when(SPY_bbInputSetupUtils).getInfraActiveRequest(executeBB.getRequestId());
- doReturn(service).when(SPY_bbInputSetupUtils)
- .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
- doNothing().when(SPY_bbInputSetupUtils).updateInfraActiveRequestVnfId(request,
- lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID));
- doReturn("vnfId").when(SPY_bbInputSetup).getVnfId(executeBB, lookupKeyMap);
- doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(any(String.class));
-
-
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString());
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateL3Network(any(String.class), isA(ModelInfo.class),
- isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(String.class), any());
-
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VNF.toString());
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateGenericVnf(isA(ModelInfo.class), any(String.class),
- isA(org.onap.so.serviceinstancebeans.Platform.class),
- isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class),
- isA(ServiceInstance.class), any(), any(), any(String.class), any(String.class), any(), any(String.class));
-
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString());
- executeBB.getBuildingBlock().setKey("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateVfModule(isA(ModelInfo.class), isA(Service.class), any(String.class),
- isA(ServiceInstance.class), any(), any(String.class), any(), any(String.class), any(), isA(CloudConfiguration.class));
-
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VOLUME_GROUP.toString());
- executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(isA(ModelInfo.class), isA(Service.class),
- any(String.class), isA(ServiceInstance.class), any(), any(String.class),ArgumentMatchers.isNull(),ArgumentMatchers.isNull(),
- any(String.class), any());
-
- Configuration configuration = new Configuration();
- configuration.setConfigurationId("configurationId");
- gBB.getServiceInstance().getConfigurations().add(configuration);
- List<ConfigurationResourceCustomization> configurationCustList = new ArrayList<>();
- ConfigurationResourceCustomization configurationCust = new ConfigurationResourceCustomization();
- configurationCust.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa9");
- doReturn(configurationCustList).when(service).getConfigurationCustomizations();
- configurationCustList.add(configurationCust);
- doNothing().when(SPY_bbInputSetup).populateConfiguration(isA(ModelInfo.class), isA(Service.class),
- any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(), isA(ConfigurationResourceKeys.class));
-
- executeBB.getBuildingBlock().setBpmnFlowName("AssignFabricConfigurationBB");
- executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa9");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateConfiguration(isA(ModelInfo.class), isA(Service.class),
- any(String.class), isA(ServiceInstance.class), any(), any(String.class),ArgumentMatchers.isNull(), isA(ConfigurationResourceKeys.class));
- }
-
- @Test
- public void testgetGBBMacroCloudConfiguration() throws Exception {
- org.onap.so.serviceinstancebeans.Service serviceMacro = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceMacroVfModules.json"), org.onap.so.serviceinstancebeans.Service.class);
- CloudConfiguration cloudConfig = null;
- org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = new org.onap.aai.domain.yang.CloudRegion();
- aaiCloudRegion.setCloudOwner("test-owner-name");
- Resources resources = serviceMacro.getResources();
- doReturn(aaiCloudRegion).when(SPY_bbInputSetupUtils).getCloudRegion(any(CloudConfiguration.class));
- CloudRegion expected = new CloudRegion();
- expected.setLcpCloudRegionId("mdt1");
- expected.setCloudOwner("test-owner-name");
- expected.setTenantId("88a6ca3ee0394ade9403f075db23167e");
-
- CloudRegion actual = SPY_bbInputSetup.getCloudRegionFromMacroRequest(cloudConfig, resources);
- assertThat(actual, sameBeanAs(expected));
-
- serviceMacro = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceMacroVnfs.json"), org.onap.so.serviceinstancebeans.Service.class);
- resources = serviceMacro.getResources();
-
- actual = SPY_bbInputSetup.getCloudRegionFromMacroRequest(cloudConfig, resources);
- assertThat(actual, sameBeanAs(expected));
-
- serviceMacro = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceMacroNetworks.json"), org.onap.so.serviceinstancebeans.Service.class);
- resources = serviceMacro.getResources();
-
- actual = SPY_bbInputSetup.getCloudRegionFromMacroRequest(cloudConfig, resources);
- assertThat(actual, sameBeanAs(expected));
-
- serviceMacro = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceMacroNoCloudConfig.json"), org.onap.so.serviceinstancebeans.Service.class);
- resources = serviceMacro.getResources();
-
- actual = SPY_bbInputSetup.getCloudRegionFromMacroRequest(cloudConfig, resources);
- assertNull(actual);
- }
-
- @Test
- public void testgetGBBMacroWithEmptyUserParams() throws Exception {
- GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper
- .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
- requestDetails.getRequestParameters().getUserParams().clear();
- InfraActiveRequests request = Mockito.mock(InfraActiveRequests.class);
- org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
- aaiVnf.setModelCustomizationId("modelCustId");
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
- String resourceId = "123";
- String vnfType = "vnfType";
- Service service = Mockito.mock(Service.class);
- String requestAction = "createInstance";
-
- doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
- requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
- doReturn(service).when(SPY_bbInputSetupUtils)
- .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
-
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString());
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- executeBB.getBuildingBlock().setIsVirtualLink(Boolean.FALSE);
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).getGBBMacroNoUserParamsCreate(any(ExecuteBuildingBlock.class), any(),
- any(String.class), any(String.class), any(GeneralBuildingBlock.class), any(Service.class));
- }
-
- @Test(expected = Exception.class)
- public void testgetGBBMacroException() throws Exception {
- GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper
- .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- String resourceId = "123";
- String vnfType = "vnfType";
- Service service = Mockito.mock(Service.class);
- String requestAction = "createInstance";
-
- executeBB.getBuildingBlock().setBpmnFlowName("Network");
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- }
-
- @Test
- public void testgetGBBMacroWithVnfTypeNull() throws Exception {
- GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper
- .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
- org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
- aaiVnf.setModelCustomizationId("modelCustId");
- InfraActiveRequests request = Mockito.mock(InfraActiveRequests.class);
- String resourceId = "123";
- String vnfType = null;
- Service service = Mockito.mock(Service.class);
- String requestAction = "createInstance";
-
-
- executeBB.setRequestDetails(requestDetails);
- doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
- requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
- doReturn(request).when(SPY_bbInputSetupUtils).getInfraActiveRequest(executeBB.getRequestId());
- doReturn(service).when(SPY_bbInputSetupUtils)
- .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
- doNothing().when(SPY_bbInputSetupUtils).updateInfraActiveRequestVnfId(request,
- lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID));
- doReturn("vnfId").when(SPY_bbInputSetup).getVnfId(executeBB, lookupKeyMap);
- doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(any(String.class));
-
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString());
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateL3Network(any(String.class), isA(ModelInfo.class),
- isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(String.class), any());
-
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VNF.toString());
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateGenericVnf(isA(ModelInfo.class), any(String.class),
- isA(org.onap.so.serviceinstancebeans.Platform.class),
- isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class),
- isA(ServiceInstance.class), any(),ArgumentMatchers.isNull(), any(String.class), ArgumentMatchers.isNull(), any(), any(String.class));
-
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString());
- executeBB.getBuildingBlock().setKey("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateVfModule(isA(ModelInfo.class), isA(Service.class), any(String.class),
- isA(ServiceInstance.class), any(), any(String.class), any(), any(String.class), any(), isA(CloudConfiguration.class));
-
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VOLUME_GROUP.toString());
- executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(isA(ModelInfo.class), isA(Service.class),
- any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(), ArgumentMatchers.isNull(),
- ArgumentMatchers.isNull(), any());
- }
-
- @Test
- public void testgetGBBMacroGetServiceWithInvariantId() throws Exception {
- GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper
- .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
- org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
- aaiVnf.setModelCustomizationId("modelCustId");
- InfraActiveRequests request = Mockito.mock(InfraActiveRequests.class);
- String resourceId = "123";
- String vnfType = "vnfType";
- Service service = Mockito.mock(Service.class);
- String requestAction = "createInstance";
-
- executeBB.setRequestDetails(requestDetails);
- doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
- requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
- doReturn(request).when(SPY_bbInputSetupUtils).getInfraActiveRequest(executeBB.getRequestId());
- doReturn(service).when(SPY_bbInputSetupUtils)
- .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
- doNothing().when(SPY_bbInputSetupUtils).updateInfraActiveRequestVnfId(request,
- lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID));
- doReturn("vnfId").when(SPY_bbInputSetup).getVnfId(executeBB, lookupKeyMap);
- doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(any(String.class));
-
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString());
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateL3Network(any(String.class), isA(ModelInfo.class),
- isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(String.class), any());
-
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VNF.toString());
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateGenericVnf(isA(ModelInfo.class), any(String.class),
- isA(org.onap.so.serviceinstancebeans.Platform.class),
- isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class),
- isA(ServiceInstance.class), any(), any(), any(String.class), any(String.class), any(),
- any(String.class));
-
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString());
- executeBB.getBuildingBlock().setKey("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateVfModule(isA(ModelInfo.class), isA(Service.class), any(String.class),
- isA(ServiceInstance.class), any(), any(String.class), any(), any(String.class), any(), isA(CloudConfiguration.class));
-
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null);
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VOLUME_GROUP.toString());
- executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(isA(ModelInfo.class), isA(Service.class),
- any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(), ArgumentMatchers.isNull(),
- any(String.class), any());
- }
-
- @Test
- public void testgetGBBMacroNoUserParamsDeactivateInstnace() throws Exception {
- GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper
- .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
- requestDetails.getRequestParameters().setUserParams(null);
- org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
- aaiVnf.setModelCustomizationId("modelCustId");
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
- String resourceId = "123";
- String vnfType = "vnfType";
- Service service = Mockito.mock(Service.class);
- String requestAction = "deactivateInstance";
- doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
- requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
- doReturn(service).when(SPY_bbInputSetupUtils)
- .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
- String generatedId = "12131";
-
- executeBB.getBuildingBlock().setBpmnFlowName("DeactivateServiceInstanceBB");
- executeBB.getBuildingBlock().setKey("3c40d244-808e-42ca-b09a-256d83d19d0a");
- GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap,
- requestAction, resourceId, vnfType);
- assertThat(actual, sameBeanAs(gBB));
- }
-
- @Test
- public void testgetGBBMacroNoUserParamsCreateInstance() throws Exception {
- GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper
- .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
- InfraActiveRequests request = Mockito.mock(InfraActiveRequests.class);
- requestDetails.getRequestParameters().setUserParams(null);
- org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
- aaiVnf.setModelCustomizationId("modelCustId");
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId");
-
- ConfigurationResourceKeys configResourceKeys = new ConfigurationResourceKeys();
- configResourceKeys.setCvnfcCustomizationUUID("cvnfcCustomizationUUID");
- configResourceKeys.setVfModuleCustomizationUUID("vfModuleCustomizationUUID");
- configResourceKeys.setVnfResourceCustomizationUUID("vnfResourceCustomizationUUID");
- executeBB.setConfigurationResourceKeys(configResourceKeys);
-
- String resourceId = "123";
- String vnfType = "vnfType";
- Service service = Mockito.mock(Service.class);
- String requestAction = "createInstance";
- doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
- requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
-
-
- doReturn(service).when(SPY_bbInputSetupUtils)
- .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
- List<NetworkResourceCustomization> networkCustList = new ArrayList<>();
- NetworkResourceCustomization networkCust = Mockito.mock(NetworkResourceCustomization.class);
- doReturn("ab153b6e-c364-44c0-bef6-1f2982117f04").when(networkCust).getModelCustomizationUUID();
- networkCustList.add(networkCust);
- doReturn(networkCustList).when(service).getNetworkCustomizations();
- doNothing().when(SPY_bbInputSetup).populateL3Network(any(), isA(ModelInfo.class), isA(Service.class),
- any(String.class), isA(ServiceInstance.class), any(), any(String.class), any());
-
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString());
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- executeBB.getBuildingBlock().setIsVirtualLink(false);
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).getGBBMacroNoUserParamsCreate(executeBB, lookupKeyMap,
- executeBB.getBuildingBlock().getBpmnFlowName(), "ab153b6e-c364-44c0-bef6-1f2982117f04", gBB, service);
-
- CollectionNetworkResourceCustomization collectionNetworkResourceCust = Mockito.mock(CollectionNetworkResourceCustomization.class);
- doReturn(collectionNetworkResourceCust).when(SPY_bbInputSetupUtils).getCatalogCollectionNetworkResourceCustByID(any(String.class));
- NetworkResourceCustomization networkResourceCustomization = Mockito.mock(NetworkResourceCustomization.class);
- doReturn(networkResourceCustomization).when(bbInputSetupMapperLayer).mapCollectionNetworkResourceCustToNetworkResourceCust(collectionNetworkResourceCust);
- ModelInfoNetwork modelInfoNetwork = Mockito.mock(ModelInfoNetwork.class);
- doReturn(modelInfoNetwork ).when(bbInputSetupMapperLayer).mapCatalogNetworkToNetwork(networkResourceCustomization);
-
- executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString());
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- executeBB.getBuildingBlock().setIsVirtualLink(true);
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(2)).getGBBMacroNoUserParamsCreate(executeBB, lookupKeyMap,
- executeBB.getBuildingBlock().getBpmnFlowName(), "ab153b6e-c364-44c0-bef6-1f2982117f04", gBB, service);
-
- executeBB.getBuildingBlock().setBpmnFlowName("CreateNetworkBB");
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- executeBB.getBuildingBlock().setIsVirtualLink(true);
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).getGBBMacroNoUserParamsCreate(executeBB, lookupKeyMap,
- executeBB.getBuildingBlock().getBpmnFlowName(), "ab153b6e-c364-44c0-bef6-1f2982117f04", gBB, service);
- }
-
- @Test
- public void testgetGBBMacroNoUserParamsOther() throws Exception {
- GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper
- .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
- requestDetails.getRequestParameters().setUserParams(null);
- org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
- aaiVnf.setModelCustomizationId("modelCustId");
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
- String resourceId = "123";
- String vnfType = "vnfType";
- Service service = Mockito.mock(Service.class);
- String requestAction = "deleteInstance";
-
- executeBB.setRequestDetails(requestDetails);
- ServiceInstance serviceInstance = gBB.getServiceInstance();
- org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
- aaiServiceInstance.setModelVersionId("modelVersionId");
- doReturn(service).when(SPY_bbInputSetupUtils).getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
- doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
- doReturn(serviceInstance).when(SPY_bbInputSetup).getExistingServiceInstance(aaiServiceInstance);
- doReturn(gBB).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
- executeBB, requestAction, null);
-
- CloudConfiguration cloudConfig = new CloudConfiguration();
- cloudConfig.setLcpCloudRegionId("lcpCloudRegionId");
- requestDetails.setCloudConfiguration(cloudConfig);
- org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class);
- doReturn(aaiCloudRegion).when(SPY_bbInputSetupUtils).getCloudRegion(requestDetails.getCloudConfiguration());
- executeBB.getBuildingBlock().setBpmnFlowName("DeleteNetworkBB");
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(1)).getGBBMacroExistingService(isA(ExecuteBuildingBlock.class), any(),
- any(String.class), isA(String.class),
- isA(CloudConfiguration.class));
-
- requestAction = "activateInstance";
- doReturn(gBB).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
- executeBB, requestAction, null);
- executeBB.getBuildingBlock().setBpmnFlowName("ActivateNetworkBB");
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(2)).getGBBMacroExistingService(isA(ExecuteBuildingBlock.class), any(),
- any(String.class), isA(String.class),
- isA(CloudConfiguration.class));
-
- requestAction = "unassignInstance";
- doReturn(gBB).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
- executeBB, requestAction, null);
- executeBB.getBuildingBlock().setBpmnFlowName("UnassignNetworkBB");
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(3)).getGBBMacroExistingService(isA(ExecuteBuildingBlock.class), any(),
- any(String.class), isA(String.class),
- isA(CloudConfiguration.class));
-
- requestAction = "activateFabricConfiguration";
- doReturn(gBB).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
- executeBB, requestAction, null);
- executeBB.getBuildingBlock().setBpmnFlowName("ActivateFabricConfigurationBB");
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-134534656234");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- verify(SPY_bbInputSetup, times(4)).getGBBMacroExistingService(isA(ExecuteBuildingBlock.class), any(),
- any(String.class), isA(String.class),
- isA(CloudConfiguration.class));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testgetGBBMacroNoUserParamsOtherException() throws Exception {
- GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper
- .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
- requestDetails.getRequestParameters().setUserParams(null);
- org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
- aaiVnf.setModelCustomizationId("modelCustId");
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
- String resourceId = "123";
- String vnfType = "vnfType";
- Service service = Mockito.mock(Service.class);
- String requestAction = "assignInstance";
- doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap,
- requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
- doReturn(service).when(SPY_bbInputSetupUtils)
- .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
- String generatedId = "12131";
-
- executeBB.getBuildingBlock().setKey("3c40d244-808e-42ca-b09a-256d83d19d0a");
- SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
- }
- @Test
- public void testgetGBBMacroNoUserParamsExistingService() throws Exception {
- GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"),
- GeneralBuildingBlock.class);
- ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"),
- ExecuteBuildingBlock.class);
- RequestDetails requestDetails = mapper
- .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacro.json"), RequestDetails.class);
- requestDetails.getRequestParameters().setUserParams(null);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.NETWORK_ID, "networkId");
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "vnfId");
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, "vfModuleId");
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, "volumeGroupId");
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId");
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId");
- Service service = Mockito.mock(Service.class);
- CloudConfiguration cloudConfiguration = new CloudConfiguration();
- cloudConfiguration.setLcpCloudRegionId("cloudRegionId");
- String requestAction = "unassignInstance";
- executeBB.setRequestDetails(requestDetails);
-
- ConfigurationResourceKeys configResourceKeys = new ConfigurationResourceKeys();
- configResourceKeys.setCvnfcCustomizationUUID("cvnfcCustomizationUUID");
- configResourceKeys.setVfModuleCustomizationUUID("vfModuleCustomizationUUID");
- configResourceKeys.setVnfResourceCustomizationUUID("vnfResourceCustomizationUUID");
- executeBB.setConfigurationResourceKeys(configResourceKeys);
-
- ServiceInstance serviceInstance = gBB.getServiceInstance();
- org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance();
- aaiServiceInstance.setModelVersionId("modelVersionId");
- doReturn(service).when(SPY_bbInputSetupUtils).getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
- doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID));
- doReturn(serviceInstance).when(SPY_bbInputSetup).getExistingServiceInstance(aaiServiceInstance);
- doReturn(gBB).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance,
- executeBB, requestAction, null);
-
- L3Network network = new L3Network();
- network.setNetworkId("networkId");
- gBB.getServiceInstance().getNetworks().add(network);
- org.onap.aai.domain.yang.L3Network aaiNetwork = new org.onap.aai.domain.yang.L3Network();
- aaiNetwork.setModelCustomizationId("modelCustId");
- doReturn(aaiNetwork).when(SPY_bbInputSetupUtils).getAAIL3Network(network.getNetworkId());
- doNothing().when(SPY_bbInputSetup).mapCatalogNetwork(any(L3Network.class), any(ModelInfo.class),
- any(Service.class));
-
- executeBB.getBuildingBlock().setBpmnFlowName("DeleteNetworkBB");
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap,
- executeBB.getBuildingBlock().getBpmnFlowName(), requestAction, null);
- verify(SPY_bbInputSetup, times(1)).mapCatalogNetwork(any(L3Network.class), any(ModelInfo.class),
- any(Service.class));
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnfId");
- gBB.getServiceInstance().getVnfs().add(vnf);
- org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
- aaiVnf.setModelCustomizationId("modelCustId");
- doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId());
- doNothing().when(SPY_bbInputSetup).mapCatalogVnf(any(GenericVnf.class), any(ModelInfo.class),
- any(Service.class));
-
- executeBB.getBuildingBlock().setBpmnFlowName("ActivateVnfBB");
- executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04");
- SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap,
- executeBB.getBuildingBlock().getBpmnFlowName(), requestAction, cloudConfiguration);
- verify(SPY_bbInputSetup, times(1)).mapCatalogVnf(any(GenericVnf.class), any(ModelInfo.class),
- any(Service.class));
-
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("vfModuleId");
- gBB.getServiceInstance().getVnfs().get(0).getVfModules().add(vfModule);
- org.onap.aai.domain.yang.VfModule aaiVfModule = new org.onap.aai.domain.yang.VfModule();
- aaiVfModule.setModelCustomizationId("modelCustId");
- doReturn(aaiVfModule).when(SPY_bbInputSetupUtils).getAAIVfModule(vnf.getVnfId(), vfModule.getVfModuleId());
-
- executeBB.getBuildingBlock().setBpmnFlowName("UnassignVfModuleBB");
- executeBB.getBuildingBlock().setKey("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
- SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap,
- executeBB.getBuildingBlock().getBpmnFlowName(), requestAction, cloudConfiguration);
- verify(SPY_bbInputSetup, times(2)).mapCatalogVnf(any(GenericVnf.class), any(ModelInfo.class),
- any(Service.class));
- verify(SPY_bbInputSetup, times(1)).mapCatalogVfModule(any(VfModule.class), any(ModelInfo.class),
- any(Service.class), any(String.class));
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("cloudRegionId");
- cloudRegion.setCloudOwner("CloudOwner");
- doReturn(Optional.of(cloudRegion)).when(SPY_cloudInfoFromAAI).getCloudInfoFromAAI(gBB.getServiceInstance());
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("volumeGroupId");
- gBB.getServiceInstance().getVnfs().get(0).getVolumeGroups().add(volumeGroup);
- org.onap.aai.domain.yang.VolumeGroup aaiVolumeGroup = new org.onap.aai.domain.yang.VolumeGroup();
- aaiVolumeGroup.setModelCustomizationId("modelCustId");
- doReturn(aaiVolumeGroup).when(SPY_bbInputSetupUtils).getAAIVolumeGroup(cloudRegion.getCloudOwner(),
- cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
-
- executeBB.getBuildingBlock().setBpmnFlowName("UnassignVolumeGroupBB");
- executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
- SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap,
- executeBB.getBuildingBlock().getBpmnFlowName(), requestAction, null);
- verify(SPY_bbInputSetup, times(3)).mapCatalogVnf(any(GenericVnf.class), any(ModelInfo.class),
- any(Service.class));
- verify(SPY_bbInputSetup, times(1)).mapCatalogVolumeGroup(isA(VolumeGroup.class), isA(ModelInfo.class),
- isA(Service.class), isA(String.class));
-
- Configuration configuration = new Configuration();
- configuration.setConfigurationId("configurationId");
- gBB.getServiceInstance().getConfigurations().add(configuration);
- org.onap.aai.domain.yang.Configuration aaiConfiguration = new org.onap.aai.domain.yang.Configuration();
- aaiConfiguration.setModelCustomizationId("modelCustId");
- doReturn(aaiConfiguration).when(SPY_bbInputSetupUtils).getAAIConfiguration(configuration.getConfigurationId());
- doNothing().when(SPY_bbInputSetup).mapCatalogConfiguration(isA(Configuration.class), isA(ModelInfo.class), isA(Service.class), isA(ConfigurationResourceKeys.class));
-
- executeBB.getBuildingBlock().setBpmnFlowName("ActivateFabricConfigurationBB");
- executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa9");
- SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap,
- executeBB.getBuildingBlock().getBpmnFlowName(), requestAction, cloudConfiguration);
- verify(SPY_bbInputSetup, times(1)).mapCatalogConfiguration(any(Configuration.class), any(ModelInfo.class),
- any(Service.class), isA(ConfigurationResourceKeys.class));
- }
-
- @Test
- public void testGetVnfId() {
- String expected = "vnfId";
- ExecuteBuildingBlock executeBB = new ExecuteBuildingBlock();
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- executeBB.setRequestId("requestId");
- InfraActiveRequests request = new InfraActiveRequests();
- request.setVnfId(expected);
- doReturn(request).when(SPY_bbInputSetupUtils).getInfraActiveRequest(executeBB.getRequestId());
-
- String actual = SPY_bbInputSetup.getVnfId(executeBB, lookupKeyMap);
-
- assertEquals("VnfId is set correctly", expected, actual);
- }
-
- @Test
- public void testCreateVfModule() {
- String vfModuleId = "vfModuleId";
- String instanceName = "vfModuleName";
- Map<String, String> cloudParams = new HashMap<>();
- cloudParams.put("param1", "param1Value");
- VfModule expected = new VfModule();
- expected.setVfModuleId(vfModuleId);
- expected.setVfModuleName(instanceName);
- expected.setCloudParams(cloudParams);
- expected.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- List<Map<String, String>> instanceParams = new ArrayList<>();
- instanceParams.add(cloudParams);
-
- VfModule actual = SPY_bbInputSetup.createVfModule(lookupKeyMap, vfModuleId, instanceName, instanceParams);
-
- assertThat(actual, sameBeanAs(expected));
- assertEquals("LookupKeyMap is populated", vfModuleId, lookupKeyMap.get(ResourceKey.VF_MODULE_ID));
-
- expected.getCloudParams().clear();
- actual = SPY_bbInputSetup.createVfModule(lookupKeyMap, vfModuleId, instanceName, null);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testCreateVolumeGroup() {
- String volumeGroupId = "volumeGroupId";
- String instanceName = "vfModuleName";
- String vnfType = "vnfType";
- Map<String, String> cloudParams = new HashMap<>();
- cloudParams.put("param1", "param1Value");
- VolumeGroup expected = new VolumeGroup();
- expected.setVolumeGroupId(volumeGroupId);
- expected.setVolumeGroupName(instanceName);
- expected.setCloudParams(cloudParams);
- expected.setVnfType(vnfType);
- expected.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- List<Map<String, String>> instanceParams = new ArrayList<>();
- instanceParams.add(cloudParams);
-
- VolumeGroup actual = SPY_bbInputSetup.createVolumeGroup(lookupKeyMap, volumeGroupId, instanceName, vnfType, instanceParams);
-
- assertThat(actual, sameBeanAs(expected));
- assertEquals("LookupKeyMap is populated", volumeGroupId, lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID));
-
- expected.getCloudParams().clear();
- actual = SPY_bbInputSetup.createVolumeGroup(lookupKeyMap, volumeGroupId, instanceName, vnfType, null);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testCreateNetwork() {
- String networkId = "networkId";
- String instanceName = "networkName";
- Map<String, String> cloudParams = new HashMap<>();
- cloudParams.put("param1", "param1Value");
- L3Network expected = new L3Network();
- expected.setNetworkId(networkId);
- expected.setNetworkName(instanceName);
- expected.setCloudParams(cloudParams);
- expected.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- List<Map<String, String>> instanceParams = new ArrayList<>();
- instanceParams.add(cloudParams);
- L3Network actual = SPY_bbInputSetup.createNetwork(lookupKeyMap, instanceName, networkId, instanceParams);
-
- assertThat(actual, sameBeanAs(expected));
- assertEquals("LookupKeyMap is populated", networkId, lookupKeyMap.get(ResourceKey.NETWORK_ID));
-
- expected.getCloudParams().clear();
- actual = SPY_bbInputSetup.createNetwork(lookupKeyMap, instanceName, networkId, null);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testCreateGenericVnf() {
- String vnfId = "vnfId";
- String instanceName = "vnfName";
- String vnfType = "vnfType";
- String platformName = "platformName";
- String lineOfBusinessName = "lineOfBusinessName";
- String productFamilyId = "productFamilyId";
- Platform platform = new Platform();
- platform.setPlatformName(platformName);
- LineOfBusiness lineOfBusiness = new LineOfBusiness();
- lineOfBusiness.setLineOfBusinessName(lineOfBusinessName);
- Map<String, String> cloudParams = new HashMap<>();
- cloudParams.put("param1", "param1Value");
- GenericVnf expected = new GenericVnf();
- expected.setVnfId(vnfId);
- expected.setVnfName(instanceName);
- expected.setVnfType(vnfType);
- expected.setCloudParams(cloudParams);
- expected.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- expected.setPlatform(platform);
- expected.setLineOfBusiness(lineOfBusiness);
- expected.setProvStatus("PREPROV");
- expected.setServiceId(productFamilyId);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- List<Map<String, String>> instanceParams = new ArrayList<>();
- instanceParams.add(cloudParams);
- org.onap.so.serviceinstancebeans.Platform requestPlatform = new org.onap.so.serviceinstancebeans.Platform();
- platform.setPlatformName(platformName);
- org.onap.so.serviceinstancebeans.LineOfBusiness requestLineOfBusiness = new org.onap.so.serviceinstancebeans.LineOfBusiness();
- lineOfBusiness.setLineOfBusinessName(lineOfBusinessName);
-
- doReturn(platform).when(bbInputSetupMapperLayer).mapRequestPlatform(requestPlatform);
- doReturn(lineOfBusiness).when(bbInputSetupMapperLayer).mapRequestLineOfBusiness(requestLineOfBusiness);
-
- GenericVnf actual = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, requestPlatform, requestLineOfBusiness, vnfId, vnfType, instanceParams,
- productFamilyId);
-
- assertThat(actual, sameBeanAs(expected));
- assertEquals("LookupKeyMap is populated", vnfId, lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID));
-
- expected.getCloudParams().clear();
- actual = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, requestPlatform, requestLineOfBusiness, vnfId, vnfType, null, productFamilyId);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testMapCatalogVfModule() {
- String vnfModelCustomizationUUID = "vnfResourceCustUUID";
- String vfModuleCustomizationUUID = "vfModelCustomizationUUID";
- VfModule vfModule = new VfModule();
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelCustomizationUuid(vfModuleCustomizationUUID);
- Service service = new Service();
- VnfResourceCustomization vnfResourceCust = new VnfResourceCustomization();
- vnfResourceCust.setModelCustomizationUUID(vnfModelCustomizationUUID);
- VfModuleCustomization vfModuleCust = new VfModuleCustomization();
- vfModuleCust.setModelCustomizationUUID(vfModuleCustomizationUUID);
- vnfResourceCust.getVfModuleCustomizations().add(vfModuleCust);
- service.getVnfCustomizations().add(vnfResourceCust);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
-
- doReturn(modelInfoVfModule).when(bbInputSetupMapperLayer).mapCatalogVfModuleToVfModule(vfModuleCust);
-
- SPY_bbInputSetup.mapCatalogVfModule(vfModule, modelInfo, service, vnfModelCustomizationUUID);
-
- assertThat(vfModule.getModelInfoVfModule(), sameBeanAs(modelInfoVfModule));
-
- modelInfo.setModelCustomizationUuid(null);
- modelInfo.setModelCustomizationId(vfModuleCustomizationUUID);
-
- SPY_bbInputSetup.mapCatalogVfModule(vfModule, modelInfo, service, vnfModelCustomizationUUID);
-
- assertThat(vfModule.getModelInfoVfModule(), sameBeanAs(modelInfoVfModule));
- }
-
- @Test
- public void testPopulateVfModule() throws Exception {
- String vnfId = "vnfId";
- String vfModuleId = "vfModuleId";
- String volumeGroupId = "volumeGroupId";
- String vfModuleCustomizationId = "vfModuleCustomizationId";
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelCustomizationId(vfModuleCustomizationId);
- Service service = new Service();
- String bbName = AssignFlows.VF_MODULE.toString();
- ServiceInstance serviceInstance = new ServiceInstance();
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId(vnfId);
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId(volumeGroupId);
- vnf.getVolumeGroups().add(volumeGroup);
- serviceInstance.getVnfs().add(vnf);
- VfModule vfModule1 = new VfModule();
- vfModule1.setVfModuleId("vfModuleId1");
- VfModule vfModule2 = new VfModule();
- vfModule2.setVfModuleId("vfModuleId2");
- vnf.getVfModules().add(vfModule1);
- vnf.getVfModules().add(vfModule2);
- Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnfId);
- String resourceId = vfModuleId;
- RelatedInstanceList[] relatedInstanceList = null;
- String instanceName = "vfModuleName";
- List<Map<String, String>> instanceParams = null;
- CloudConfiguration cloudConfiguration = new CloudConfiguration();
-
- org.onap.aai.domain.yang.GenericVnf vnfAAI = new org.onap.aai.domain.yang.GenericVnf();
- vnfAAI.setModelCustomizationId("vnfModelCustId");
- org.onap.aai.domain.yang.VolumeGroup volumeGroupAAI = new org.onap.aai.domain.yang.VolumeGroup();
- volumeGroupAAI.setModelCustomizationId(vfModuleCustomizationId);
- org.onap.aai.domain.yang.VfModule vfModuleAAI = new org.onap.aai.domain.yang.VfModule();
- vfModuleAAI.setModelCustomizationId(vfModuleCustomizationId);
-
- doReturn(vnfAAI).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId());
- doReturn(volumeGroupAAI).when(SPY_bbInputSetupUtils).getAAIVolumeGroup(CLOUD_OWNER,
- cloudConfiguration.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
- doReturn(vfModuleAAI).when(SPY_bbInputSetupUtils).getAAIVfModule(isA(String.class), isA(String.class));
- doNothing().when(SPY_bbInputSetup).mapCatalogVnf(isA(GenericVnf.class), isA(ModelInfo.class), isA(Service.class));
- doNothing().when(SPY_bbInputSetup).mapCatalogVfModule(isA(VfModule.class), isA(ModelInfo.class), isA(Service.class), isA(String.class));
-
- SPY_bbInputSetup.populateVfModule(modelInfo, service, bbName, serviceInstance, lookupKeyMap,
- resourceId, relatedInstanceList, instanceName, instanceParams, cloudConfiguration);
-
- verify(SPY_bbInputSetup, times(3)).mapCatalogVfModule(isA(VfModule.class), isA(ModelInfo.class), isA(Service.class), isA(String.class));
- assertEquals("Lookup Key Map populated with VfModule Id", vfModuleId, lookupKeyMap.get(ResourceKey.VF_MODULE_ID));
- assertEquals("Lookup Key Map populated with VolumeGroup Id", volumeGroupId, lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID));
- }
-
- @Test
- public void testGettingVnfcToConfiguration() throws Exception {
-
- String vnfcName = "vnfcName";
- org.onap.aai.domain.yang.Configuration expectedAAI = new org.onap.aai.domain.yang.Configuration();
- AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VNFC, vnfcName);
- AAIResultWrapper configurationWrapper =
- new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(expectedAAI));
-
- doReturn(new AAIResultWrapper(null)).when(SPY_bbInputSetupUtils).getAAIResourceDepthOne(aaiResourceUri);
- Vnfc vnfc = SPY_bbInputSetup.getVnfcToConfiguration(vnfcName);
- Assert.assertNull(vnfc);
-
- doReturn(configurationWrapper).when(SPY_bbInputSetupUtils).getAAIResourceDepthOne(aaiResourceUri);
- vnfc = SPY_bbInputSetup.getVnfcToConfiguration(vnfcName);
- Assert.assertNotNull(vnfc);
- }
-
-
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java
index 54e513e7d9..25135a0254 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java
@@ -30,13 +30,11 @@ import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -67,7 +65,6 @@ import org.onap.so.client.aai.AAIResourcesClient;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.onap.so.client.graphinventory.entities.uri.Depth;
-
import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization;
import org.onap.so.db.catalog.beans.Service;
import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization;
@@ -77,733 +74,762 @@ import org.onap.so.db.request.client.RequestsDbClient;
import org.onap.so.serviceinstancebeans.CloudConfiguration;
import org.onap.so.serviceinstancebeans.ModelInfo;
import org.onap.so.serviceinstancebeans.RequestDetails;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(MockitoJUnitRunner.class)
public class BBInputSetupUtilsTest {
- protected ObjectMapper mapper = new ObjectMapper();
- private static final String RESOURCE_PATH = "src/test/resources/__files/ExecuteBuildingBlock/";
-
- @InjectMocks
- BBInputSetupUtils bbInputSetupUtils = new BBInputSetupUtils();
-
- @Mock
- protected CatalogDbClient MOCK_catalogDbClient;
-
- @Mock
- protected RequestsDbClient MOCK_requestsDbClient;
-
- @Mock
- protected AAIResourcesClient MOCK_aaiResourcesClient;
-
- @Mock
- protected InjectionHelper MOCK_injectionHelper;
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Before
- public void setup(){
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- }
-
- @Test
- public void testGetCatalogServiceByModelUUID() throws JsonParseException, JsonMappingException, IOException {
- Service expected = mapper.readValue(
- new File(RESOURCE_PATH + "CatalogServiceExpected.json"), Service.class);
-
- RequestDetails requestDetails = new RequestDetails();
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelVersionId("modelUUID");
- requestDetails.setModelInfo(modelInfo);
- doReturn(expected).when(MOCK_catalogDbClient).getServiceByID("modelUUID");
- Service actual = bbInputSetupUtils.getCatalogServiceByModelUUID(modelInfo.getModelVersionId());
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void testGetCatalogServiceByModelVersionAndModelInvariantUUID() throws JsonParseException, JsonMappingException, IOException {
- String modelVersion = "modelVersion";
- String modelInvariantUUID = "modelInvariantUUID";
- Service expectedService = mapper.readValue(
- new File(RESOURCE_PATH + "CatalogServiceExpected.json"), Service.class);
-
- doReturn(expectedService).when(MOCK_catalogDbClient).getServiceByModelVersionAndModelInvariantUUID(isA(String.class), isA(String.class));
-
- Service actualService = bbInputSetupUtils.getCatalogServiceByModelVersionAndModelInvariantUUID(modelVersion, modelInvariantUUID);
-
- assertThat(actualService, sameBeanAs(expectedService));
- }
-
- @Test
- public void testGetVnfcInstanceGroups() throws JsonParseException, JsonMappingException, IOException {
- VnfcInstanceGroupCustomization vnfc = mapper.readValue(
- new File(RESOURCE_PATH + "VnfcInstanceGroupCustomization.json"), VnfcInstanceGroupCustomization.class);
- String modelCustomizationUUID = "modelCustomizationUUID";
-
- doReturn(Arrays.asList(vnfc)).when(MOCK_catalogDbClient).getVnfcInstanceGroupsByVnfResourceCust(isA(String.class));
-
- List<VnfcInstanceGroupCustomization> actualVnfcList = bbInputSetupUtils.getVnfcInstanceGroups(modelCustomizationUUID);
-
- assertThat(actualVnfcList, sameBeanAs(Arrays.asList(vnfc)));
- }
-
- @Test
- public void testGetRequestDetails() throws JsonParseException, JsonMappingException, IOException {
- InfraActiveRequests infraActiveRequest = mapper.readValue(
- new File(RESOURCE_PATH + "InfraActiveRequestExpected.json"),
- InfraActiveRequests.class);
-
- RequestDetails expected = mapper.readValue(
- new File(RESOURCE_PATH + "RequestDetailsExpected.json"),
- RequestDetails.class);
- String requestId = "requestId";
- doReturn(infraActiveRequest).when(MOCK_requestsDbClient).getInfraActiveRequestbyRequestId(requestId);
- RequestDetails actual = bbInputSetupUtils.getRequestDetails(requestId);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void getRequestDetailsNullTest() throws IOException {
- RequestDetails requestDetails = bbInputSetupUtils.getRequestDetails("");
-
- assertNull(requestDetails);
- }
-
- @Test
- public void testGetCloudRegion() {
- CloudConfiguration cloudConfig = new CloudConfiguration();
- cloudConfig.setLcpCloudRegionId("lcpCloudRegionId");
- Optional<org.onap.aai.domain.yang.CloudRegion> expected = Optional.of(new org.onap.aai.domain.yang.CloudRegion());
- expected.get().setCloudOwner("cloudOwner");
- expected.get().setCloudRegionId("lcpCloudRegionId");
- doReturn(expected).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.CloudRegion.class,
- AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudConfig.getCloudOwner(),
- cloudConfig.getLcpCloudRegionId()).depth(Depth.TWO));
-
- AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudConfig.getCloudOwner(),
- cloudConfig.getLcpCloudRegionId()).depth(Depth.TWO);
- bbInputSetupUtils.getCloudRegion(cloudConfig);
-
- verify(MOCK_aaiResourcesClient, times(1)).get(CloudRegion.class, expectedUri);
- }
-
- @Test
- public void testGetCloudRegionExceptionTest() {
-
- CloudConfiguration cloudConfig = new CloudConfiguration();
- cloudConfig.setLcpCloudRegionId("lcpCloudRegionId");
-
- RequestDetails requestDetails = new RequestDetails();
- requestDetails.setCloudConfiguration(cloudConfig);
-
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
-
- CloudRegion cloudRegion = bbInputSetupUtils.getCloudRegion(cloudConfig);
-
- assertNull(cloudRegion);
- }
-
- @Test
- public void testGetCloudRegionEmptyId() {
- CloudConfiguration cloudConfig = new CloudConfiguration();
- cloudConfig.setLcpCloudRegionId("");
-
- RequestDetails requestDetails = new RequestDetails();
- requestDetails.setCloudConfiguration(cloudConfig);
-
- CloudRegion cloudRegion = bbInputSetupUtils.getCloudRegion(cloudConfig);
-
- assertNull(cloudRegion);
- }
-
- @Test
- public void testGetCloudRegionEmptyConfiguration() {
- RequestDetails requestDetails = new RequestDetails();
-
- CloudRegion cloudRegion = bbInputSetupUtils.getCloudRegion(requestDetails.getCloudConfiguration());
-
- assertNull(cloudRegion);
- }
-
- @Test
- public void testGetAAIInstanceGroup() {
- Optional<org.onap.aai.domain.yang.InstanceGroup> expected = Optional.of(new org.onap.aai.domain.yang.InstanceGroup());
- String instanceGroupId = "instanceGroupId";
- expected.get().setId(instanceGroupId);
- doReturn(expected).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.InstanceGroup.class,
- AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId));
- AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId);
-
- bbInputSetupUtils.getAAIInstanceGroup(instanceGroupId);
- verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.InstanceGroup.class, expectedUri);
- }
-
- @Test
- public void testGetAAIInstanceGroupThrowNotFound() {
- String instanceGroupId = "instanceGroupId";
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.InstanceGroup.class,
- AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId));
-
- org.onap.aai.domain.yang.InstanceGroup actual = bbInputSetupUtils.getAAIInstanceGroup(instanceGroupId);
-
- assertNull(actual);
- }
-
- @Test
- public void testGetAAICustomer() {
- Optional<org.onap.aai.domain.yang.Customer> expected = Optional.of(new org.onap.aai.domain.yang.Customer());
- String globalSubscriberId = "globalSubscriberId";
- expected.get().setGlobalCustomerId(globalSubscriberId);
- doReturn(expected).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.Customer.class,
- AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId));
- AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId);
-
- bbInputSetupUtils.getAAICustomer(globalSubscriberId);
- verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.Customer.class, expectedUri);
- }
-
- @Test
- public void testGetAAICustomerThrowNotFound() {
- String globalSubscriberId = "globalSubscriberId";
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.Customer.class,
- AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId));
-
- org.onap.aai.domain.yang.Customer actual = bbInputSetupUtils.getAAICustomer(globalSubscriberId);
-
- assertNull(actual);
- }
-
- @Test
- public void testGetAAIServiceSubscription() {
- Optional<org.onap.aai.domain.yang.ServiceSubscription> expected = Optional.of(new org.onap.aai.domain.yang.ServiceSubscription());
- String globalSubscriberId = "globalSubscriberId";
- String subscriptionServiceType = "subscriptionServiceType";
- expected.get().setServiceType(subscriptionServiceType);
- doReturn(expected).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.ServiceSubscription.class,
- AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_SUBSCRIPTION, globalSubscriberId,
- subscriptionServiceType));
- AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_SUBSCRIPTION, globalSubscriberId,
- subscriptionServiceType);
-
- bbInputSetupUtils.getAAIServiceSubscription(globalSubscriberId, subscriptionServiceType);
- verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.ServiceSubscription.class, expectedUri);
- }
-
- @Test
- public void testGetAAIServiceSubscriptionErrors() {
- String globalSubId = null;
- String subServiceType = null;
- org.onap.aai.domain.yang.ServiceSubscription actual = bbInputSetupUtils.getAAIServiceSubscription(globalSubId, subServiceType);
- assertNull(actual);
-
- String globalSubId2 = "";
- String subServiceType2 = "";
- org.onap.aai.domain.yang.ServiceSubscription actual2 = bbInputSetupUtils.getAAIServiceSubscription(globalSubId2, subServiceType2);
- assertNull(actual2);
-
- String globalSubId3 = "";
- String subServiceType3 = null;
- org.onap.aai.domain.yang.ServiceSubscription actual3 = bbInputSetupUtils.getAAIServiceSubscription(globalSubId3, subServiceType3);
- assertNull(actual3);
-
- String globalSubId4 = null;
- String subServiceType4 = "";
- org.onap.aai.domain.yang.ServiceSubscription actual4 = bbInputSetupUtils.getAAIServiceSubscription(globalSubId4, subServiceType4);
- assertNull(actual4);
- }
-
- @Test
- public void testGetAAIServiceSubscriptionThrowNotFound() {
- String globalSubscriberId = "globalSubscriberId";
- String subscriptionServiceType = "subscriptionServiceType";
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient)
- .get(org.onap.aai.domain.yang.ServiceSubscription.class, AAIUriFactory.createResourceUri(
- AAIObjectType.SERVICE_SUBSCRIPTION, globalSubscriberId, subscriptionServiceType));
- org.onap.aai.domain.yang.ServiceSubscription actual = bbInputSetupUtils
- .getAAIServiceSubscription(globalSubscriberId, subscriptionServiceType);
- assertNull(actual);
- }
-
- @Test
- public void testGetAAIServiceInstanceById() {
- String serviceInstanceId = "serviceInstanceId";
-
- ServiceInstance expectedServiceInstance = new ServiceInstance();
-
- doReturn(Optional.of(expectedServiceInstance)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
-
- ServiceInstance actualServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
-
- assertThat(actualServiceInstance, sameBeanAs(expectedServiceInstance));
- }
-
- @Test
- public void testGetAAIServiceInstanceByIdThrowNotFound() {
- String serviceInstanceId = "serviceInstanceId";
-
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
-
- ServiceInstance actualServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
-
- assertNull(actualServiceInstance);
- }
-
- @Test
- public void testGetAAIServiceInstanceByIdAndCustomer() {
- String globalCustomerId = "globalCustomerId";
- String serviceType = "serviceType";
- String serviceInstanceId = "serviceInstanceId";
- ServiceInstance expected = new ServiceInstance();
- expected.setServiceInstanceId(serviceInstanceId);
- doReturn(Optional.of(expected)).when(MOCK_aaiResourcesClient).get(isA(Class.class),
- isA(AAIResourceUri.class));
- AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(
- AAIObjectType.SERVICE_INSTANCE, globalCustomerId, serviceType, serviceInstanceId).depth(Depth.TWO);
- this.bbInputSetupUtils.getAAIServiceInstanceByIdAndCustomer(globalCustomerId, serviceType, serviceInstanceId);
-
- verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.ServiceInstance.class, expectedUri);
-
- }
-
- @Test
- public void testGetAAIServiceInstanceByIdAndCustomerThrowNotFound() {
- String globalCustomerId = "globalCustomerId";
- String serviceType = "serviceType";
- String serviceInstanceId = "serviceInstanceId";
-
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class),
- isA(AAIResourceUri.class));
- ServiceInstance actual = this.bbInputSetupUtils
- .getAAIServiceInstanceByIdAndCustomer(globalCustomerId, serviceType, serviceInstanceId);
-
- assertNull(actual);
- }
-
- @Test
- public void testGetAAIServiceInstanceByName() throws Exception {
- String serviceInstanceName = "serviceInstanceName";
-
- ServiceInstance expectedServiceInstance = new ServiceInstance();
- expectedServiceInstance.setServiceInstanceId("serviceInstanceId");
-
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- serviceSubscription.setServiceType("serviceType");
-
- Customer customer = new Customer();
- customer.setGlobalCustomerId("globalCustomerId");
- customer.setServiceSubscription(serviceSubscription);
-
- ServiceInstances serviceInstances = new ServiceInstances();
- serviceInstances.getServiceInstance().add(expectedServiceInstance);
-
- doReturn(Optional.of(serviceInstances)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
- AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.SERVICE_INSTANCE, customer.getGlobalCustomerId(),
- customer.getServiceSubscription().getServiceType())
- .queryParam("service-instance-name", serviceInstanceName).depth(Depth.TWO);
- bbInputSetupUtils.getAAIServiceInstanceByName(serviceInstanceName, customer);
-
- verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.ServiceInstances.class, expectedUri);
- }
-
- @Test
- public void testGetAAIServiceInstanceByNameException() throws Exception {
- expectedException.expect(Exception.class);
-
- String serviceInstanceName = "serviceInstanceName";
-
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
-
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- serviceSubscription.setServiceType("serviceType");
-
- Customer customer = new Customer();
- customer.setGlobalCustomerId("globalCustomerId");
- customer.setServiceSubscription(serviceSubscription);
-
- ServiceInstances serviceInstances = new ServiceInstances();
- serviceInstances.getServiceInstance().add(serviceInstance);
- serviceInstances.getServiceInstance().add(serviceInstance);
-
- doReturn(Optional.of(serviceInstances)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
-
- bbInputSetupUtils.getAAIServiceInstanceByName(serviceInstanceName, customer);
- }
-
- @Test
- public void testGetAAIServiceInstanceByNameNull() throws Exception {
- String serviceInstanceName = "serviceInstanceName";
-
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
-
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- serviceSubscription.setServiceType("serviceType");
-
- Customer customer = new Customer();
- customer.setGlobalCustomerId("globalCustomerId");
- customer.setServiceSubscription(serviceSubscription);
-
- ServiceInstances serviceInstances = new ServiceInstances();
- serviceInstances.getServiceInstance().add(serviceInstance);
- serviceInstances.getServiceInstance().add(serviceInstance);
-
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
-
- ServiceInstance actualServiceInstance = bbInputSetupUtils.getAAIServiceInstanceByName(serviceInstanceName, customer);
-
- assertNull(actualServiceInstance);
- }
-
- @Test
- public void testGetOptionalAAIServiceInstanceByNameException() throws Exception {
- expectedException.expect(Exception.class);
-
- String globalCustomerId = "globalCustomerId";
- String serviceType = "serviceType";
- String serviceInstanceId = "serviceInstanceId";
-
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- serviceInstance.setServiceType(serviceType);
- serviceInstance.setServiceInstanceName("serviceInstanceName");
-
- ServiceInstances serviceInstances = new ServiceInstances();
- serviceInstances.getServiceInstance().add(serviceInstance);
- serviceInstances.getServiceInstance().add(serviceInstance);
-
- doReturn(Optional.of(serviceInstances)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
-
- bbInputSetupUtils.getAAIServiceInstanceByName(globalCustomerId, serviceType, serviceInstanceId);
- }
-
- @Test
- public void testGetOptionalAAIServiceInstanceByNameNull() throws Exception {
- String globalCustomerId = "globalCustomerId";
- String serviceType = "serviceType";
- String serviceInstanceId = "serviceInstanceId";
-
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
- Optional<ServiceInstance> actual = this.bbInputSetupUtils
- .getAAIServiceInstanceByName(globalCustomerId, serviceType, serviceInstanceId);
-
- assertThat(actual, sameBeanAs(Optional.empty()));
- }
-
- @Test
- public void testGetCatalogInstanceGroup() throws JsonParseException, JsonMappingException, IOException {
- String modelUUID = "modelUUID";
-
- org.onap.so.db.catalog.beans.InstanceGroup expectedInstanceGroup = mapper.readValue(
- new File(RESOURCE_PATH + "InstanceGroup.json"), org.onap.so.db.catalog.beans.InstanceGroup.class);
-
- doReturn(expectedInstanceGroup).when(MOCK_catalogDbClient).getInstanceGroupByModelUUID(isA(String.class));
-
- org.onap.so.db.catalog.beans.InstanceGroup actualInstanceGroup = bbInputSetupUtils.getCatalogInstanceGroup(modelUUID);
-
- assertThat(actualInstanceGroup, sameBeanAs(expectedInstanceGroup));
- }
-
- @Test
- public void testGetCollectionResourceInstanceGroupCustomization() {
- String modelCustomizationUUID = "modelCustomizationUUID";
-
- CollectionResourceInstanceGroupCustomization expectedCollection = new CollectionResourceInstanceGroupCustomization();
-
- doReturn(Arrays.asList(expectedCollection)).when(MOCK_catalogDbClient)
- .getCollectionResourceInstanceGroupCustomizationByModelCustUUID(modelCustomizationUUID);
-
- List<CollectionResourceInstanceGroupCustomization> actualCollection = bbInputSetupUtils
- .getCollectionResourceInstanceGroupCustomization(modelCustomizationUUID);
-
- assertThat(actualCollection, sameBeanAs(Arrays.asList(expectedCollection)));
- }
-
- @Test
- public void testGetAAIGenericVnf() throws JsonParseException, JsonMappingException, IOException {
- String vnfId = "vnfId";
-
- GenericVnf expectedAaiVnf = mapper.readValue(
- new File(RESOURCE_PATH + "aaiGenericVnfInput.json"), GenericVnf.class);
-
- doReturn(Optional.of(expectedAaiVnf)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
- AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE);
- GenericVnf actualAaiVnf = bbInputSetupUtils.getAAIGenericVnf(vnfId);
-
- assertThat(actualAaiVnf, sameBeanAs(expectedAaiVnf));
-
- verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.GenericVnf.class, expectedUri);
- }
-
- @Test
- public void testGetAAIConfiguration() throws JsonParseException, JsonMappingException, IOException {
- String configurationId = "configurationId";
-
- Configuration expectedAaiConfiguration = mapper.readValue(
- new File(RESOURCE_PATH + "ConfigurationInput.json"), Configuration.class);
-
- doReturn(Optional.of(expectedAaiConfiguration)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
- AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId).depth(Depth.ONE);
- bbInputSetupUtils.getAAIConfiguration(configurationId);
-
- verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.Configuration.class, expectedUri);
- }
-
- @Test
- public void testGetAAIGenericVnfThrowNotFound() throws JsonParseException, JsonMappingException, IOException {
- String vnfId = "vnfId";
-
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
-
- GenericVnf actualAaiVnf = bbInputSetupUtils.getAAIGenericVnf(vnfId);
-
- assertNull(actualAaiVnf);
- }
-
- @Test
- public void testGetAAIResourceDepthOne() {
- String vnfId = "vnfId";
- AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
- AAIResourceUri expectedUri = aaiResourceUri.clone().depth(Depth.ONE);
- AAIResourceUri aaiResourceUriClone = aaiResourceUri.clone();
- bbInputSetupUtils.getAAIResourceDepthOne(aaiResourceUri);
-
- verify(MOCK_aaiResourcesClient, times(1)).get(expectedUri);
- assertEquals("Uri should not have changed", aaiResourceUriClone.build(), aaiResourceUri.build());
- }
-
- @Test
- public void testGetAAIResourceDepthTwo() {
- String vnfId = "vnfId";
- AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
- AAIResourceUri expectedUri = aaiResourceUri.clone().depth(Depth.TWO);
- AAIResourceUri aaiResourceUriClone = aaiResourceUri.clone();
- bbInputSetupUtils.getAAIResourceDepthTwo(aaiResourceUri);
-
- verify(MOCK_aaiResourcesClient, times(1)).get(expectedUri);
- assertEquals("Uri should not have changed", aaiResourceUriClone.build(), aaiResourceUri.build());
- }
-
- @Test
- public void getRelatedNetworkByNameFromServiceInstanceTest() throws Exception {
- Optional<L3Networks> expected = Optional.of(new L3Networks());
- L3Network network = new L3Network();
- network.setNetworkId("id123");
- network.setNetworkName("name123");
- expected.get().getL3Network().add(network);
- doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class));
- Optional<L3Network> actual = this.bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance("id123", "name123");
- assertEquals(actual.get().getNetworkId(), expected.get().getL3Network().get(0).getNetworkId());
- }
-
- @Test
- public void getRelatedNetworkByNameFromServiceInstanceMultipleNetworksExceptionTest() throws Exception {
- expectedException.expect(Exception.class);
-
- String serviceInstanceId = "serviceInstanceId";
- String networkName = "networkName";
-
- L3Network network = new L3Network();
- network.setNetworkId("id123");
- network.setNetworkName("name123");
-
- L3Networks expected = new L3Networks();
- expected.getL3Network().add(network);
- expected.getL3Network().add(network);
-
- doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class));
-
- bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance(serviceInstanceId, networkName);
- }
-
- @Test
- public void getRelatedNetworkByNameFromServiceInstanceNotFoundTest() throws Exception {
- String serviceInstanceId = "serviceInstanceId";
- String networkName = "networkName";
-
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class));
-
- Optional<L3Network> actualNetwork = bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance(serviceInstanceId, networkName);
-
- assertEquals(Optional.empty(), actualNetwork);
- }
-
- @Test
- public void getRelatedServiceInstanceFromInstanceGroupTest() throws Exception {
- Optional<ServiceInstances> expected = Optional.of(new ServiceInstances());
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- serviceInstance.setServiceInstanceName("serviceInstanceName");
- expected.get().getServiceInstance().add(serviceInstance);
-
- doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(ServiceInstances.class), any(AAIResourceUri.class));
- Optional<ServiceInstance> actual = this.bbInputSetupUtils.getRelatedServiceInstanceFromInstanceGroup("ig-001");
- assertEquals(actual.get().getServiceInstanceId(), expected.get().getServiceInstance().get(0).getServiceInstanceId());
- }
-
- @Test
- public void getRelatedServiceInstanceFromInstanceGroupMultipleTest() throws Exception {
- expectedException.expect(MultipleObjectsFoundException.class);
- Optional<ServiceInstances> serviceInstances = Optional.of(new ServiceInstances());
- ServiceInstance si1 = Mockito.mock(ServiceInstance.class);
- ServiceInstance si2 = Mockito.mock(ServiceInstance.class);
- serviceInstances.get().getServiceInstance().add(si1);
- serviceInstances.get().getServiceInstance().add(si2);
-
- doReturn(serviceInstances).when(MOCK_aaiResourcesClient).get(eq(ServiceInstances.class), any(AAIResourceUri.class));
- this.bbInputSetupUtils.getRelatedServiceInstanceFromInstanceGroup("ig-001");
- }
-
- @Test
- public void getRelatedServiceInstanceFromInstanceGroupNotFoundTest() throws Exception {
- expectedException.expect(NoServiceInstanceFoundException.class);
- Optional<ServiceInstances> serviceInstances = Optional.of(new ServiceInstances());
-
- doReturn(serviceInstances).when(MOCK_aaiResourcesClient).get(eq(ServiceInstances.class), any(AAIResourceUri.class));
- this.bbInputSetupUtils.getRelatedServiceInstanceFromInstanceGroup("ig-001");
- }
-
- @Test
- public void getRelatedVnfByNameFromServiceInstanceTest() throws Exception {
- Optional<GenericVnfs> expected = Optional.of(new GenericVnfs());
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("id123");
- vnf.setVnfName("name123");
- expected.get().getGenericVnf().add(vnf);
- doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class));
- Optional<GenericVnf> actual = this.bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance("id123", "name123");
- assertEquals(actual.get().getVnfId(), expected.get().getGenericVnf().get(0).getVnfId());
- }
-
- @Test
- public void getRelatedVnfByNameFromServiceInstanceMultipleVnfsExceptionTest() throws Exception {
- expectedException.expect(Exception.class);
-
- String serviceInstanceId = "serviceInstanceId";
- String vnfName = "vnfName";
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("id123");
- vnf.setVnfName("name123");
-
- GenericVnfs expectedVnf = new GenericVnfs();
- expectedVnf.getGenericVnf().add(vnf);
- expectedVnf.getGenericVnf().add(vnf);
-
- doReturn(expectedVnf).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class));
-
- bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance(serviceInstanceId, vnfName);
- }
-
- @Test
- public void getRelatedVnfByNameFromServiceInstanceNotFoundTest() throws Exception {
- String serviceInstanceId = "serviceInstanceId";
- String vnfName = "vnfName";
-
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class));
-
- Optional<GenericVnf> actualVnf = this.bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance(serviceInstanceId, vnfName);
-
- assertEquals(actualVnf, Optional.empty());
- }
-
- @Test
- public void getRelatedVolumeGroupByNameFromVnfTest() throws Exception {
- Optional<VolumeGroups> expected = Optional.of(new VolumeGroups());
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("id123");
- volumeGroup.setVolumeGroupName("name123");
- expected.get().getVolumeGroup().add(volumeGroup);
- doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
- Optional<VolumeGroup> actual = this.bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf("id123", "name123");
- assertEquals(actual.get().getVolumeGroupId(), expected.get().getVolumeGroup().get(0).getVolumeGroupId());
- }
-
- @Test
- public void getRelatedVolumeGroupByNameFromVnfMultipleVolumeGroupsExceptionTest() throws Exception {
- expectedException.expect(Exception.class);
-
- String vnfId = "vnfId";
- String volumeGroupName = "volumeGroupName";
-
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("id123");
- volumeGroup.setVolumeGroupName("name123");
-
- VolumeGroups expectedVolumeGroup = new VolumeGroups();
- expectedVolumeGroup.getVolumeGroup().add(volumeGroup);
- expectedVolumeGroup.getVolumeGroup().add(volumeGroup);
-
- doReturn(expectedVolumeGroup).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
-
- bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf(vnfId, volumeGroupName);
- }
-
- @Test
- public void getRelatedVolumeGroupByNameFromVnfNotFoundTest() throws Exception {
- String vnfId = "vnfId";
- String volumeGroupName = "volumeGroupName";
-
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
-
- Optional<VolumeGroup> actualVolumeGroup = bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf(vnfId, volumeGroupName);
-
- assertEquals(actualVolumeGroup, Optional.empty());
- }
-
- @Test
- public void getRelatedVolumeGroupByNameFromVfModuleTest() throws Exception {
- Optional<VolumeGroups> expected = Optional.of(new VolumeGroups());
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("id123");
- volumeGroup.setVolumeGroupName("name123");
- expected.get().getVolumeGroup().add(volumeGroup);
- doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
- Optional<VolumeGroup> actual = this.bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule("id123", "id123", "name123");
- assertEquals(actual.get().getVolumeGroupId(), expected.get().getVolumeGroup().get(0).getVolumeGroupId());
- }
-
- @Test
- public void getRelatedVolumeGroupByNameFromVfModuleMultipleVolumeGroupsExceptionTest() throws Exception {
- expectedException.expect(Exception.class);
-
- String vnfId = "vnfId";
- String volumeGroupId = "volumeGroupId";
- String volumeGroupName = "volumeGroupName";
-
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("id123");
- volumeGroup.setVolumeGroupName("name123");
-
- VolumeGroups expectedVolumeGroup = new VolumeGroups();
- expectedVolumeGroup.getVolumeGroup().add(volumeGroup);
- expectedVolumeGroup.getVolumeGroup().add(volumeGroup);
-
- doReturn(expectedVolumeGroup).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
-
- bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule(vnfId, volumeGroupId, volumeGroupName);
- }
-
- @Test
- public void getRelatedVolumeGroupByNameFromVfModuleNotFoundTest() throws Exception {
- String vnfId = "vnfId";
- String volumeGroupId = "volumeGroupId";
- String volumeGroupName = "volumeGroupName";
-
- doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
-
- Optional<VolumeGroup> actualVolumeGroup = bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule(vnfId, volumeGroupId, volumeGroupName);
-
- assertEquals(actualVolumeGroup, Optional.empty());
- }
-} \ No newline at end of file
+ protected ObjectMapper mapper = new ObjectMapper();
+ private static final String RESOURCE_PATH = "src/test/resources/__files/ExecuteBuildingBlock/";
+
+ @InjectMocks
+ BBInputSetupUtils bbInputSetupUtils = new BBInputSetupUtils();
+
+ @Mock
+ protected CatalogDbClient MOCK_catalogDbClient;
+
+ @Mock
+ protected RequestsDbClient MOCK_requestsDbClient;
+
+ @Mock
+ protected AAIResourcesClient MOCK_aaiResourcesClient;
+
+ @Mock
+ protected InjectionHelper MOCK_injectionHelper;
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Before
+ public void setup() {
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ }
+
+ @Test
+ public void testGetCatalogServiceByModelUUID() throws JsonParseException, JsonMappingException, IOException {
+ Service expected = mapper.readValue(new File(RESOURCE_PATH + "CatalogServiceExpected.json"), Service.class);
+
+ RequestDetails requestDetails = new RequestDetails();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelVersionId("modelUUID");
+ requestDetails.setModelInfo(modelInfo);
+ doReturn(expected).when(MOCK_catalogDbClient).getServiceByID("modelUUID");
+ Service actual = bbInputSetupUtils.getCatalogServiceByModelUUID(modelInfo.getModelVersionId());
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testGetCatalogServiceByModelVersionAndModelInvariantUUID()
+ throws JsonParseException, JsonMappingException, IOException {
+ String modelVersion = "modelVersion";
+ String modelInvariantUUID = "modelInvariantUUID";
+ Service expectedService =
+ mapper.readValue(new File(RESOURCE_PATH + "CatalogServiceExpected.json"), Service.class);
+
+ doReturn(expectedService).when(MOCK_catalogDbClient)
+ .getServiceByModelVersionAndModelInvariantUUID(isA(String.class), isA(String.class));
+
+ Service actualService = bbInputSetupUtils.getCatalogServiceByModelVersionAndModelInvariantUUID(modelVersion,
+ modelInvariantUUID);
+
+ assertThat(actualService, sameBeanAs(expectedService));
+ }
+
+ @Test
+ public void testGetVnfcInstanceGroups() throws JsonParseException, JsonMappingException, IOException {
+ VnfcInstanceGroupCustomization vnfc = mapper.readValue(
+ new File(RESOURCE_PATH + "VnfcInstanceGroupCustomization.json"), VnfcInstanceGroupCustomization.class);
+ String modelCustomizationUUID = "modelCustomizationUUID";
+
+ doReturn(Arrays.asList(vnfc)).when(MOCK_catalogDbClient)
+ .getVnfcInstanceGroupsByVnfResourceCust(isA(String.class));
+
+ List<VnfcInstanceGroupCustomization> actualVnfcList =
+ bbInputSetupUtils.getVnfcInstanceGroups(modelCustomizationUUID);
+
+ assertThat(actualVnfcList, sameBeanAs(Arrays.asList(vnfc)));
+ }
+
+ @Test
+ public void testGetRequestDetails() throws JsonParseException, JsonMappingException, IOException {
+ InfraActiveRequests infraActiveRequest = mapper
+ .readValue(new File(RESOURCE_PATH + "InfraActiveRequestExpected.json"), InfraActiveRequests.class);
+
+ RequestDetails expected =
+ mapper.readValue(new File(RESOURCE_PATH + "RequestDetailsExpected.json"), RequestDetails.class);
+ String requestId = "requestId";
+ doReturn(infraActiveRequest).when(MOCK_requestsDbClient).getInfraActiveRequestbyRequestId(requestId);
+ RequestDetails actual = bbInputSetupUtils.getRequestDetails(requestId);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void getRequestDetailsNullTest() throws IOException {
+ RequestDetails requestDetails = bbInputSetupUtils.getRequestDetails("");
+
+ assertNull(requestDetails);
+ }
+
+ @Test
+ public void testGetCloudRegion() {
+ CloudConfiguration cloudConfig = new CloudConfiguration();
+ cloudConfig.setLcpCloudRegionId("lcpCloudRegionId");
+ Optional<org.onap.aai.domain.yang.CloudRegion> expected =
+ Optional.of(new org.onap.aai.domain.yang.CloudRegion());
+ expected.get().setCloudOwner("cloudOwner");
+ expected.get().setCloudRegionId("lcpCloudRegionId");
+ doReturn(expected).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.CloudRegion.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudConfig.getCloudOwner(),
+ cloudConfig.getLcpCloudRegionId()).depth(Depth.TWO));
+
+ AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION,
+ cloudConfig.getCloudOwner(), cloudConfig.getLcpCloudRegionId()).depth(Depth.TWO);
+ bbInputSetupUtils.getCloudRegion(cloudConfig);
+
+ verify(MOCK_aaiResourcesClient, times(1)).get(CloudRegion.class, expectedUri);
+ }
+
+ @Test
+ public void testGetCloudRegionExceptionTest() {
+
+ CloudConfiguration cloudConfig = new CloudConfiguration();
+ cloudConfig.setLcpCloudRegionId("lcpCloudRegionId");
+
+ RequestDetails requestDetails = new RequestDetails();
+ requestDetails.setCloudConfiguration(cloudConfig);
+
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
+
+ CloudRegion cloudRegion = bbInputSetupUtils.getCloudRegion(cloudConfig);
+
+ assertNull(cloudRegion);
+ }
+
+ @Test
+ public void testGetCloudRegionEmptyId() {
+ CloudConfiguration cloudConfig = new CloudConfiguration();
+ cloudConfig.setLcpCloudRegionId("");
+
+ RequestDetails requestDetails = new RequestDetails();
+ requestDetails.setCloudConfiguration(cloudConfig);
+
+ CloudRegion cloudRegion = bbInputSetupUtils.getCloudRegion(cloudConfig);
+
+ assertNull(cloudRegion);
+ }
+
+ @Test
+ public void testGetCloudRegionEmptyConfiguration() {
+ RequestDetails requestDetails = new RequestDetails();
+
+ CloudRegion cloudRegion = bbInputSetupUtils.getCloudRegion(requestDetails.getCloudConfiguration());
+
+ assertNull(cloudRegion);
+ }
+
+ @Test
+ public void testGetAAIInstanceGroup() {
+ Optional<org.onap.aai.domain.yang.InstanceGroup> expected =
+ Optional.of(new org.onap.aai.domain.yang.InstanceGroup());
+ String instanceGroupId = "instanceGroupId";
+ expected.get().setId(instanceGroupId);
+ doReturn(expected).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.InstanceGroup.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId));
+ AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId);
+
+ bbInputSetupUtils.getAAIInstanceGroup(instanceGroupId);
+ verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.InstanceGroup.class, expectedUri);
+ }
+
+ @Test
+ public void testGetAAIInstanceGroupThrowNotFound() {
+ String instanceGroupId = "instanceGroupId";
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.InstanceGroup.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId));
+
+ org.onap.aai.domain.yang.InstanceGroup actual = bbInputSetupUtils.getAAIInstanceGroup(instanceGroupId);
+
+ assertNull(actual);
+ }
+
+ @Test
+ public void testGetAAICustomer() {
+ Optional<org.onap.aai.domain.yang.Customer> expected = Optional.of(new org.onap.aai.domain.yang.Customer());
+ String globalSubscriberId = "globalSubscriberId";
+ expected.get().setGlobalCustomerId(globalSubscriberId);
+ doReturn(expected).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.Customer.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId));
+ AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId);
+
+ bbInputSetupUtils.getAAICustomer(globalSubscriberId);
+ verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.Customer.class, expectedUri);
+ }
+
+ @Test
+ public void testGetAAICustomerThrowNotFound() {
+ String globalSubscriberId = "globalSubscriberId";
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.Customer.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId));
+
+ org.onap.aai.domain.yang.Customer actual = bbInputSetupUtils.getAAICustomer(globalSubscriberId);
+
+ assertNull(actual);
+ }
+
+ @Test
+ public void testGetAAIServiceSubscription() {
+ Optional<org.onap.aai.domain.yang.ServiceSubscription> expected =
+ Optional.of(new org.onap.aai.domain.yang.ServiceSubscription());
+ String globalSubscriberId = "globalSubscriberId";
+ String subscriptionServiceType = "subscriptionServiceType";
+ expected.get().setServiceType(subscriptionServiceType);
+ doReturn(expected).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.ServiceSubscription.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_SUBSCRIPTION, globalSubscriberId,
+ subscriptionServiceType));
+ AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_SUBSCRIPTION,
+ globalSubscriberId, subscriptionServiceType);
+
+ bbInputSetupUtils.getAAIServiceSubscription(globalSubscriberId, subscriptionServiceType);
+ verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.ServiceSubscription.class, expectedUri);
+ }
+
+ @Test
+ public void testGetAAIServiceSubscriptionErrors() {
+ String globalSubId = null;
+ String subServiceType = null;
+ org.onap.aai.domain.yang.ServiceSubscription actual =
+ bbInputSetupUtils.getAAIServiceSubscription(globalSubId, subServiceType);
+ assertNull(actual);
+
+ String globalSubId2 = "";
+ String subServiceType2 = "";
+ org.onap.aai.domain.yang.ServiceSubscription actual2 =
+ bbInputSetupUtils.getAAIServiceSubscription(globalSubId2, subServiceType2);
+ assertNull(actual2);
+
+ String globalSubId3 = "";
+ String subServiceType3 = null;
+ org.onap.aai.domain.yang.ServiceSubscription actual3 =
+ bbInputSetupUtils.getAAIServiceSubscription(globalSubId3, subServiceType3);
+ assertNull(actual3);
+
+ String globalSubId4 = null;
+ String subServiceType4 = "";
+ org.onap.aai.domain.yang.ServiceSubscription actual4 =
+ bbInputSetupUtils.getAAIServiceSubscription(globalSubId4, subServiceType4);
+ assertNull(actual4);
+ }
+
+ @Test
+ public void testGetAAIServiceSubscriptionThrowNotFound() {
+ String globalSubscriberId = "globalSubscriberId";
+ String subscriptionServiceType = "subscriptionServiceType";
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.ServiceSubscription.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_SUBSCRIPTION, globalSubscriberId,
+ subscriptionServiceType));
+ org.onap.aai.domain.yang.ServiceSubscription actual =
+ bbInputSetupUtils.getAAIServiceSubscription(globalSubscriberId, subscriptionServiceType);
+ assertNull(actual);
+ }
+
+ @Test
+ public void testGetAAIServiceInstanceById() {
+ String serviceInstanceId = "serviceInstanceId";
+
+ ServiceInstance expectedServiceInstance = new ServiceInstance();
+
+ doReturn(Optional.of(expectedServiceInstance)).when(MOCK_aaiResourcesClient).get(isA(Class.class),
+ isA(AAIResourceUri.class));
+
+ ServiceInstance actualServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
+
+ assertThat(actualServiceInstance, sameBeanAs(expectedServiceInstance));
+ }
+
+ @Test
+ public void testGetAAIServiceInstanceByIdThrowNotFound() {
+ String serviceInstanceId = "serviceInstanceId";
+
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
+
+ ServiceInstance actualServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
+
+ assertNull(actualServiceInstance);
+ }
+
+ @Test
+ public void testGetAAIServiceInstanceByIdAndCustomer() {
+ String globalCustomerId = "globalCustomerId";
+ String serviceType = "serviceType";
+ String serviceInstanceId = "serviceInstanceId";
+ ServiceInstance expected = new ServiceInstance();
+ expected.setServiceInstanceId(serviceInstanceId);
+ doReturn(Optional.of(expected)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
+ AAIResourceUri expectedUri = AAIUriFactory
+ .createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustomerId, serviceType, serviceInstanceId)
+ .depth(Depth.TWO);
+ this.bbInputSetupUtils.getAAIServiceInstanceByIdAndCustomer(globalCustomerId, serviceType, serviceInstanceId);
+
+ verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.ServiceInstance.class, expectedUri);
+
+ }
+
+ @Test
+ public void testGetAAIServiceInstanceByIdAndCustomerThrowNotFound() {
+ String globalCustomerId = "globalCustomerId";
+ String serviceType = "serviceType";
+ String serviceInstanceId = "serviceInstanceId";
+
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
+ ServiceInstance actual = this.bbInputSetupUtils.getAAIServiceInstanceByIdAndCustomer(globalCustomerId,
+ serviceType, serviceInstanceId);
+
+ assertNull(actual);
+ }
+
+ @Test
+ public void testGetAAIServiceInstanceByName() throws Exception {
+ String serviceInstanceName = "serviceInstanceName";
+
+ ServiceInstance expectedServiceInstance = new ServiceInstance();
+ expectedServiceInstance.setServiceInstanceId("serviceInstanceId");
+
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ serviceSubscription.setServiceType("serviceType");
+
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("globalCustomerId");
+ customer.setServiceSubscription(serviceSubscription);
+
+ ServiceInstances serviceInstances = new ServiceInstances();
+ serviceInstances.getServiceInstance().add(expectedServiceInstance);
+
+ doReturn(Optional.of(serviceInstances)).when(MOCK_aaiResourcesClient).get(isA(Class.class),
+ isA(AAIResourceUri.class));
+ AAIResourceUri expectedUri = AAIUriFactory
+ .createResourceUri(AAIObjectPlurals.SERVICE_INSTANCE, customer.getGlobalCustomerId(),
+ customer.getServiceSubscription().getServiceType())
+ .queryParam("service-instance-name", serviceInstanceName).depth(Depth.TWO);
+ bbInputSetupUtils.getAAIServiceInstanceByName(serviceInstanceName, customer);
+
+ verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.ServiceInstances.class, expectedUri);
+ }
+
+ @Test
+ public void testGetAAIServiceInstanceByNameException() throws Exception {
+ expectedException.expect(Exception.class);
+
+ String serviceInstanceName = "serviceInstanceName";
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ serviceSubscription.setServiceType("serviceType");
+
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("globalCustomerId");
+ customer.setServiceSubscription(serviceSubscription);
+
+ ServiceInstances serviceInstances = new ServiceInstances();
+ serviceInstances.getServiceInstance().add(serviceInstance);
+ serviceInstances.getServiceInstance().add(serviceInstance);
+
+ doReturn(Optional.of(serviceInstances)).when(MOCK_aaiResourcesClient).get(isA(Class.class),
+ isA(AAIResourceUri.class));
+
+ bbInputSetupUtils.getAAIServiceInstanceByName(serviceInstanceName, customer);
+ }
+
+ @Test
+ public void testGetAAIServiceInstanceByNameNull() throws Exception {
+ String serviceInstanceName = "serviceInstanceName";
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ serviceSubscription.setServiceType("serviceType");
+
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("globalCustomerId");
+ customer.setServiceSubscription(serviceSubscription);
+
+ ServiceInstances serviceInstances = new ServiceInstances();
+ serviceInstances.getServiceInstance().add(serviceInstance);
+ serviceInstances.getServiceInstance().add(serviceInstance);
+
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
+
+ ServiceInstance actualServiceInstance =
+ bbInputSetupUtils.getAAIServiceInstanceByName(serviceInstanceName, customer);
+
+ assertNull(actualServiceInstance);
+ }
+
+ @Test
+ public void testGetOptionalAAIServiceInstanceByNameException() throws Exception {
+ expectedException.expect(Exception.class);
+
+ String globalCustomerId = "globalCustomerId";
+ String serviceType = "serviceType";
+ String serviceInstanceId = "serviceInstanceId";
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ serviceInstance.setServiceType(serviceType);
+ serviceInstance.setServiceInstanceName("serviceInstanceName");
+
+ ServiceInstances serviceInstances = new ServiceInstances();
+ serviceInstances.getServiceInstance().add(serviceInstance);
+ serviceInstances.getServiceInstance().add(serviceInstance);
+
+ doReturn(Optional.of(serviceInstances)).when(MOCK_aaiResourcesClient).get(isA(Class.class),
+ isA(AAIResourceUri.class));
+
+ bbInputSetupUtils.getAAIServiceInstanceByName(globalCustomerId, serviceType, serviceInstanceId);
+ }
+
+ @Test
+ public void testGetOptionalAAIServiceInstanceByNameNull() throws Exception {
+ String globalCustomerId = "globalCustomerId";
+ String serviceType = "serviceType";
+ String serviceInstanceId = "serviceInstanceId";
+
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
+ Optional<ServiceInstance> actual =
+ this.bbInputSetupUtils.getAAIServiceInstanceByName(globalCustomerId, serviceType, serviceInstanceId);
+
+ assertThat(actual, sameBeanAs(Optional.empty()));
+ }
+
+ @Test
+ public void testGetCatalogInstanceGroup() throws JsonParseException, JsonMappingException, IOException {
+ String modelUUID = "modelUUID";
+
+ org.onap.so.db.catalog.beans.InstanceGroup expectedInstanceGroup = mapper.readValue(
+ new File(RESOURCE_PATH + "InstanceGroup.json"), org.onap.so.db.catalog.beans.InstanceGroup.class);
+
+ doReturn(expectedInstanceGroup).when(MOCK_catalogDbClient).getInstanceGroupByModelUUID(isA(String.class));
+
+ org.onap.so.db.catalog.beans.InstanceGroup actualInstanceGroup =
+ bbInputSetupUtils.getCatalogInstanceGroup(modelUUID);
+
+ assertThat(actualInstanceGroup, sameBeanAs(expectedInstanceGroup));
+ }
+
+ @Test
+ public void testGetCollectionResourceInstanceGroupCustomization() {
+ String modelCustomizationUUID = "modelCustomizationUUID";
+
+ CollectionResourceInstanceGroupCustomization expectedCollection =
+ new CollectionResourceInstanceGroupCustomization();
+
+ doReturn(Arrays.asList(expectedCollection)).when(MOCK_catalogDbClient)
+ .getCollectionResourceInstanceGroupCustomizationByModelCustUUID(modelCustomizationUUID);
+
+ List<CollectionResourceInstanceGroupCustomization> actualCollection =
+ bbInputSetupUtils.getCollectionResourceInstanceGroupCustomization(modelCustomizationUUID);
+
+ assertThat(actualCollection, sameBeanAs(Arrays.asList(expectedCollection)));
+ }
+
+ @Test
+ public void testGetAAIGenericVnf() throws JsonParseException, JsonMappingException, IOException {
+ String vnfId = "vnfId";
+
+ GenericVnf expectedAaiVnf =
+ mapper.readValue(new File(RESOURCE_PATH + "aaiGenericVnfInput.json"), GenericVnf.class);
+
+ doReturn(Optional.of(expectedAaiVnf)).when(MOCK_aaiResourcesClient).get(isA(Class.class),
+ isA(AAIResourceUri.class));
+ AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE);
+ GenericVnf actualAaiVnf = bbInputSetupUtils.getAAIGenericVnf(vnfId);
+
+ assertThat(actualAaiVnf, sameBeanAs(expectedAaiVnf));
+
+ verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.GenericVnf.class, expectedUri);
+ }
+
+ @Test
+ public void testGetAAIConfiguration() throws JsonParseException, JsonMappingException, IOException {
+ String configurationId = "configurationId";
+
+ Configuration expectedAaiConfiguration =
+ mapper.readValue(new File(RESOURCE_PATH + "ConfigurationInput.json"), Configuration.class);
+
+ doReturn(Optional.of(expectedAaiConfiguration)).when(MOCK_aaiResourcesClient).get(isA(Class.class),
+ isA(AAIResourceUri.class));
+ AAIResourceUri expectedUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId).depth(Depth.ONE);
+ bbInputSetupUtils.getAAIConfiguration(configurationId);
+
+ verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.Configuration.class, expectedUri);
+ }
+
+ @Test
+ public void testGetAAIGenericVnfThrowNotFound() throws JsonParseException, JsonMappingException, IOException {
+ String vnfId = "vnfId";
+
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
+
+ GenericVnf actualAaiVnf = bbInputSetupUtils.getAAIGenericVnf(vnfId);
+
+ assertNull(actualAaiVnf);
+ }
+
+ @Test
+ public void testGetAAIResourceDepthOne() {
+ String vnfId = "vnfId";
+ AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
+ AAIResourceUri expectedUri = aaiResourceUri.clone().depth(Depth.ONE);
+ AAIResourceUri aaiResourceUriClone = aaiResourceUri.clone();
+ bbInputSetupUtils.getAAIResourceDepthOne(aaiResourceUri);
+
+ verify(MOCK_aaiResourcesClient, times(1)).get(expectedUri);
+ assertEquals("Uri should not have changed", aaiResourceUriClone.build(), aaiResourceUri.build());
+ }
+
+ @Test
+ public void testGetAAIResourceDepthTwo() {
+ String vnfId = "vnfId";
+ AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
+ AAIResourceUri expectedUri = aaiResourceUri.clone().depth(Depth.TWO);
+ AAIResourceUri aaiResourceUriClone = aaiResourceUri.clone();
+ bbInputSetupUtils.getAAIResourceDepthTwo(aaiResourceUri);
+
+ verify(MOCK_aaiResourcesClient, times(1)).get(expectedUri);
+ assertEquals("Uri should not have changed", aaiResourceUriClone.build(), aaiResourceUri.build());
+ }
+
+ @Test
+ public void getRelatedNetworkByNameFromServiceInstanceTest() throws Exception {
+ Optional<L3Networks> expected = Optional.of(new L3Networks());
+ L3Network network = new L3Network();
+ network.setNetworkId("id123");
+ network.setNetworkName("name123");
+ expected.get().getL3Network().add(network);
+ doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class));
+ Optional<L3Network> actual =
+ this.bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance("id123", "name123");
+ assertEquals(actual.get().getNetworkId(), expected.get().getL3Network().get(0).getNetworkId());
+ }
+
+ @Test
+ public void getRelatedNetworkByNameFromServiceInstanceMultipleNetworksExceptionTest() throws Exception {
+ expectedException.expect(Exception.class);
+
+ String serviceInstanceId = "serviceInstanceId";
+ String networkName = "networkName";
+
+ L3Network network = new L3Network();
+ network.setNetworkId("id123");
+ network.setNetworkName("name123");
+
+ L3Networks expected = new L3Networks();
+ expected.getL3Network().add(network);
+ expected.getL3Network().add(network);
+
+ doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class));
+
+ bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance(serviceInstanceId, networkName);
+ }
+
+ @Test
+ public void getRelatedNetworkByNameFromServiceInstanceNotFoundTest() throws Exception {
+ String serviceInstanceId = "serviceInstanceId";
+ String networkName = "networkName";
+
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class));
+
+ Optional<L3Network> actualNetwork =
+ bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance(serviceInstanceId, networkName);
+
+ assertEquals(Optional.empty(), actualNetwork);
+ }
+
+ @Test
+ public void getRelatedServiceInstanceFromInstanceGroupTest() throws Exception {
+ Optional<ServiceInstances> expected = Optional.of(new ServiceInstances());
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ serviceInstance.setServiceInstanceName("serviceInstanceName");
+ expected.get().getServiceInstance().add(serviceInstance);
+
+ doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(ServiceInstances.class), any(AAIResourceUri.class));
+ Optional<ServiceInstance> actual = this.bbInputSetupUtils.getRelatedServiceInstanceFromInstanceGroup("ig-001");
+ assertEquals(actual.get().getServiceInstanceId(),
+ expected.get().getServiceInstance().get(0).getServiceInstanceId());
+ }
+
+ @Test
+ public void getRelatedServiceInstanceFromInstanceGroupMultipleTest() throws Exception {
+ expectedException.expect(MultipleObjectsFoundException.class);
+ Optional<ServiceInstances> serviceInstances = Optional.of(new ServiceInstances());
+ ServiceInstance si1 = Mockito.mock(ServiceInstance.class);
+ ServiceInstance si2 = Mockito.mock(ServiceInstance.class);
+ serviceInstances.get().getServiceInstance().add(si1);
+ serviceInstances.get().getServiceInstance().add(si2);
+
+ doReturn(serviceInstances).when(MOCK_aaiResourcesClient).get(eq(ServiceInstances.class),
+ any(AAIResourceUri.class));
+ this.bbInputSetupUtils.getRelatedServiceInstanceFromInstanceGroup("ig-001");
+ }
+
+ @Test
+ public void getRelatedServiceInstanceFromInstanceGroupNotFoundTest() throws Exception {
+ expectedException.expect(NoServiceInstanceFoundException.class);
+ Optional<ServiceInstances> serviceInstances = Optional.of(new ServiceInstances());
+
+ doReturn(serviceInstances).when(MOCK_aaiResourcesClient).get(eq(ServiceInstances.class),
+ any(AAIResourceUri.class));
+ this.bbInputSetupUtils.getRelatedServiceInstanceFromInstanceGroup("ig-001");
+ }
+
+ @Test
+ public void getRelatedVnfByNameFromServiceInstanceTest() throws Exception {
+ Optional<GenericVnfs> expected = Optional.of(new GenericVnfs());
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("id123");
+ vnf.setVnfName("name123");
+ expected.get().getGenericVnf().add(vnf);
+ doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class));
+ Optional<GenericVnf> actual = this.bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance("id123", "name123");
+ assertEquals(actual.get().getVnfId(), expected.get().getGenericVnf().get(0).getVnfId());
+ }
+
+ @Test
+ public void getRelatedVnfByNameFromServiceInstanceMultipleVnfsExceptionTest() throws Exception {
+ expectedException.expect(Exception.class);
+
+ String serviceInstanceId = "serviceInstanceId";
+ String vnfName = "vnfName";
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("id123");
+ vnf.setVnfName("name123");
+
+ GenericVnfs expectedVnf = new GenericVnfs();
+ expectedVnf.getGenericVnf().add(vnf);
+ expectedVnf.getGenericVnf().add(vnf);
+
+ doReturn(expectedVnf).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class));
+
+ bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance(serviceInstanceId, vnfName);
+ }
+
+ @Test
+ public void getRelatedVnfByNameFromServiceInstanceNotFoundTest() throws Exception {
+ String serviceInstanceId = "serviceInstanceId";
+ String vnfName = "vnfName";
+
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class));
+
+ Optional<GenericVnf> actualVnf =
+ this.bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance(serviceInstanceId, vnfName);
+
+ assertEquals(actualVnf, Optional.empty());
+ }
+
+ @Test
+ public void getRelatedVolumeGroupByNameFromVnfTest() throws Exception {
+ Optional<VolumeGroups> expected = Optional.of(new VolumeGroups());
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("id123");
+ volumeGroup.setVolumeGroupName("name123");
+ expected.get().getVolumeGroup().add(volumeGroup);
+ doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
+ Optional<VolumeGroup> actual = this.bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf("id123", "name123");
+ assertEquals(actual.get().getVolumeGroupId(), expected.get().getVolumeGroup().get(0).getVolumeGroupId());
+ }
+
+ @Test
+ public void getRelatedVolumeGroupByNameFromVnfMultipleVolumeGroupsExceptionTest() throws Exception {
+ expectedException.expect(Exception.class);
+
+ String vnfId = "vnfId";
+ String volumeGroupName = "volumeGroupName";
+
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("id123");
+ volumeGroup.setVolumeGroupName("name123");
+
+ VolumeGroups expectedVolumeGroup = new VolumeGroups();
+ expectedVolumeGroup.getVolumeGroup().add(volumeGroup);
+ expectedVolumeGroup.getVolumeGroup().add(volumeGroup);
+
+ doReturn(expectedVolumeGroup).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class),
+ any(AAIResourceUri.class));
+
+ bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf(vnfId, volumeGroupName);
+ }
+
+ @Test
+ public void getRelatedVolumeGroupByNameFromVnfNotFoundTest() throws Exception {
+ String vnfId = "vnfId";
+ String volumeGroupName = "volumeGroupName";
+
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
+
+ Optional<VolumeGroup> actualVolumeGroup =
+ bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf(vnfId, volumeGroupName);
+
+ assertEquals(actualVolumeGroup, Optional.empty());
+ }
+
+ @Test
+ public void getRelatedVolumeGroupByNameFromVfModuleTest() throws Exception {
+ Optional<VolumeGroups> expected = Optional.of(new VolumeGroups());
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("id123");
+ volumeGroup.setVolumeGroupName("name123");
+ expected.get().getVolumeGroup().add(volumeGroup);
+ doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
+ Optional<VolumeGroup> actual =
+ this.bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule("id123", "id123", "name123");
+ assertEquals(actual.get().getVolumeGroupId(), expected.get().getVolumeGroup().get(0).getVolumeGroupId());
+ }
+
+ @Test
+ public void getRelatedVolumeGroupByNameFromVfModuleMultipleVolumeGroupsExceptionTest() throws Exception {
+ expectedException.expect(Exception.class);
+
+ String vnfId = "vnfId";
+ String volumeGroupId = "volumeGroupId";
+ String volumeGroupName = "volumeGroupName";
+
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("id123");
+ volumeGroup.setVolumeGroupName("name123");
+
+ VolumeGroups expectedVolumeGroup = new VolumeGroups();
+ expectedVolumeGroup.getVolumeGroup().add(volumeGroup);
+ expectedVolumeGroup.getVolumeGroup().add(volumeGroup);
+
+ doReturn(expectedVolumeGroup).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class),
+ any(AAIResourceUri.class));
+
+ bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule(vnfId, volumeGroupId, volumeGroupName);
+ }
+
+ @Test
+ public void getRelatedVolumeGroupByNameFromVfModuleNotFoundTest() throws Exception {
+ String vnfId = "vnfId";
+ String volumeGroupId = "volumeGroupId";
+ String volumeGroupName = "volumeGroupName";
+
+ doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
+
+ Optional<VolumeGroup> actualVolumeGroup =
+ bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule(vnfId, volumeGroupId, volumeGroupName);
+
+ assertEquals(actualVolumeGroup, Optional.empty());
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/CloudInfoFromAAITest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/CloudInfoFromAAITest.java
index af7dc582e0..1f4c8d3f1d 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/CloudInfoFromAAITest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/CloudInfoFromAAITest.java
@@ -26,13 +26,11 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
-
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -48,7 +46,6 @@ import org.onap.so.client.aai.AAICommonObjectMapperProvider;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.entities.AAIResultWrapper;
import org.onap.so.client.aai.entities.Relationships;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -57,106 +54,106 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(MockitoJUnitRunner.class)
public class CloudInfoFromAAITest {
- private static final String RESOURCE_PATH = "src/test/resources/__files/ExecuteBuildingBlock/";
-
- @Spy
- private CloudInfoFromAAI SPY_CloudInfoFromAAI = new CloudInfoFromAAI();
-
- protected ObjectMapper mapper = new ObjectMapper();
-
- @Mock
- private BBInputSetupUtils SPY_bbInputSetupUtils;
-
- @Before
- public void setup(){
- SPY_CloudInfoFromAAI.setBbInputSetupUtils(SPY_bbInputSetupUtils);
- }
-
- @Test
- public void testGetCloudInfoFromAAI() throws JsonParseException, JsonMappingException, IOException {
- //Test vnfs
- ServiceInstance serviceInstance = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
- ServiceInstance.class);
- CloudRegion expected = new CloudRegion();
- GenericVnf vnf = new GenericVnf();
- String vnfId = "vnfId";
- vnf.setVnfId(vnfId);
- serviceInstance.getVnfs().add(vnf);
- org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
- aaiVnf.setVnfId(vnfId);
- Relationships relationships = Mockito.mock(Relationships.class);
- Optional<Relationships> relationshipsOp= Optional.of(relationships);
- doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId());
- doReturn(relationshipsOp).when(SPY_CloudInfoFromAAI).getRelationshipsFromWrapper(isA(AAIResultWrapper.class));
- doReturn(Optional.of(expected)).when(SPY_CloudInfoFromAAI).getRelatedCloudRegionAndTenant(relationships);
- Optional<CloudRegion> actual = SPY_CloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance);
- assertThat(actual.get(), sameBeanAs(expected));
-
- //Test networks
- serviceInstance = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
- ServiceInstance.class);
- L3Network l3Network = new L3Network();
- String networkId = "networkId";
- l3Network.setNetworkId(networkId);
- serviceInstance.getNetworks().add(l3Network);
- org.onap.aai.domain.yang.L3Network aaiL3Network = new org.onap.aai.domain.yang.L3Network();
- aaiL3Network.setNetworkId(networkId);
- doReturn(aaiL3Network).when(SPY_bbInputSetupUtils).getAAIL3Network(l3Network.getNetworkId());
- actual = SPY_CloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance);
- assertThat(actual.get(), sameBeanAs(expected));
-
- //Test no relationships
-
- doReturn(Optional.empty()).when(SPY_CloudInfoFromAAI).getRelationshipsFromWrapper(isA(AAIResultWrapper.class));
- actual = SPY_CloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance);
- assertEquals(actual, Optional.empty());
-
- //Test null
- serviceInstance = mapper.readValue(
- new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
- ServiceInstance.class);
- actual = SPY_CloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance);
- assertEquals(actual, Optional.empty());
- }
-
- @Test
- public void testGetRelatedCloudRegionAndTenant() throws JsonProcessingException {
- String cloudOwner = "cloudOwner";
- String cloudRegionId = "cloudRegionId";
- String cloudRegionVersion = "cloudRegionVersion";
- String cloudRegionComplexName = "cloudRegionComplexName";
- String tenantId = "tenantId";
- CloudRegion expected = new CloudRegion();
- expected.setCloudOwner(cloudOwner);
- expected.setCloudRegionVersion(cloudRegionVersion);
- expected.setComplex(cloudRegionComplexName);
- expected.setLcpCloudRegionId(cloudRegionId);
- expected.setTenantId(tenantId);
-
- Relationships relationships = Mockito.mock(Relationships.class);
- List<AAIResultWrapper> cloudRegions = new ArrayList<>();
- org.onap.aai.domain.yang.CloudRegion cloudRegion = new org.onap.aai.domain.yang.CloudRegion();
- cloudRegion.setCloudOwner(cloudOwner);
- cloudRegion.setCloudRegionId(cloudRegionId);
- cloudRegion.setCloudRegionVersion(cloudRegionVersion);
- cloudRegion.setComplexName(cloudRegionComplexName);
- AAIResultWrapper cloudRegionWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(cloudRegion));
- cloudRegions.add(cloudRegionWrapper);
-
- doReturn(cloudRegions).when(relationships).getByType(AAIObjectType.CLOUD_REGION);
- List<AAIResultWrapper> tenants = new ArrayList<>();
- org.onap.aai.domain.yang.Tenant tenant = new org.onap.aai.domain.yang.Tenant();
- tenant.setTenantId(tenantId);
- AAIResultWrapper tenantWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(tenant));
- tenants.add(tenantWrapper);
- doReturn(tenants).when(relationships).getByType(AAIObjectType.TENANT);
-
- Optional<CloudRegion> actual = SPY_CloudInfoFromAAI.getRelatedCloudRegionAndTenant(relationships);
-
- assertThat(actual.get(), sameBeanAs(expected));
- }
+ private static final String RESOURCE_PATH = "src/test/resources/__files/ExecuteBuildingBlock/";
+
+ @Spy
+ private CloudInfoFromAAI SPY_CloudInfoFromAAI = new CloudInfoFromAAI();
+
+ protected ObjectMapper mapper = new ObjectMapper();
+
+ @Mock
+ private BBInputSetupUtils SPY_bbInputSetupUtils;
+
+ @Before
+ public void setup() {
+ SPY_CloudInfoFromAAI.setBbInputSetupUtils(SPY_bbInputSetupUtils);
+ }
+
+ @Test
+ public void testGetCloudInfoFromAAI() throws JsonParseException, JsonMappingException, IOException {
+ // Test vnfs
+ ServiceInstance serviceInstance =
+ mapper.readValue(new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
+ ServiceInstance.class);
+ CloudRegion expected = new CloudRegion();
+ GenericVnf vnf = new GenericVnf();
+ String vnfId = "vnfId";
+ vnf.setVnfId(vnfId);
+ serviceInstance.getVnfs().add(vnf);
+ org.onap.aai.domain.yang.GenericVnf aaiVnf = new org.onap.aai.domain.yang.GenericVnf();
+ aaiVnf.setVnfId(vnfId);
+ Relationships relationships = Mockito.mock(Relationships.class);
+ Optional<Relationships> relationshipsOp = Optional.of(relationships);
+ doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId());
+ doReturn(relationshipsOp).when(SPY_CloudInfoFromAAI).getRelationshipsFromWrapper(isA(AAIResultWrapper.class));
+ doReturn(Optional.of(expected)).when(SPY_CloudInfoFromAAI).getRelatedCloudRegionAndTenant(relationships);
+ Optional<CloudRegion> actual = SPY_CloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance);
+ assertThat(actual.get(), sameBeanAs(expected));
+
+ // Test networks
+ serviceInstance =
+ mapper.readValue(new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
+ ServiceInstance.class);
+ L3Network l3Network = new L3Network();
+ String networkId = "networkId";
+ l3Network.setNetworkId(networkId);
+ serviceInstance.getNetworks().add(l3Network);
+ org.onap.aai.domain.yang.L3Network aaiL3Network = new org.onap.aai.domain.yang.L3Network();
+ aaiL3Network.setNetworkId(networkId);
+ doReturn(aaiL3Network).when(SPY_bbInputSetupUtils).getAAIL3Network(l3Network.getNetworkId());
+ actual = SPY_CloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance);
+ assertThat(actual.get(), sameBeanAs(expected));
+
+ // Test no relationships
+
+ doReturn(Optional.empty()).when(SPY_CloudInfoFromAAI).getRelationshipsFromWrapper(isA(AAIResultWrapper.class));
+ actual = SPY_CloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance);
+ assertEquals(actual, Optional.empty());
+
+ // Test null
+ serviceInstance =
+ mapper.readValue(new File(RESOURCE_PATH + "ServiceInstance_getServiceInstanceNOAAIExpected.json"),
+ ServiceInstance.class);
+ actual = SPY_CloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance);
+ assertEquals(actual, Optional.empty());
+ }
+
+ @Test
+ public void testGetRelatedCloudRegionAndTenant() throws JsonProcessingException {
+ String cloudOwner = "cloudOwner";
+ String cloudRegionId = "cloudRegionId";
+ String cloudRegionVersion = "cloudRegionVersion";
+ String cloudRegionComplexName = "cloudRegionComplexName";
+ String tenantId = "tenantId";
+ CloudRegion expected = new CloudRegion();
+ expected.setCloudOwner(cloudOwner);
+ expected.setCloudRegionVersion(cloudRegionVersion);
+ expected.setComplex(cloudRegionComplexName);
+ expected.setLcpCloudRegionId(cloudRegionId);
+ expected.setTenantId(tenantId);
+
+ Relationships relationships = Mockito.mock(Relationships.class);
+ List<AAIResultWrapper> cloudRegions = new ArrayList<>();
+ org.onap.aai.domain.yang.CloudRegion cloudRegion = new org.onap.aai.domain.yang.CloudRegion();
+ cloudRegion.setCloudOwner(cloudOwner);
+ cloudRegion.setCloudRegionId(cloudRegionId);
+ cloudRegion.setCloudRegionVersion(cloudRegionVersion);
+ cloudRegion.setComplexName(cloudRegionComplexName);
+ AAIResultWrapper cloudRegionWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(cloudRegion));
+ cloudRegions.add(cloudRegionWrapper);
+
+ doReturn(cloudRegions).when(relationships).getByType(AAIObjectType.CLOUD_REGION);
+ List<AAIResultWrapper> tenants = new ArrayList<>();
+ org.onap.aai.domain.yang.Tenant tenant = new org.onap.aai.domain.yang.Tenant();
+ tenant.setTenantId(tenantId);
+ AAIResultWrapper tenantWrapper =
+ new AAIResultWrapper(new AAICommonObjectMapperProvider().getMapper().writeValueAsString(tenant));
+ tenants.add(tenantWrapper);
+ doReturn(tenants).when(relationships).getByType(AAIObjectType.TENANT);
+
+ Optional<CloudRegion> actual = SPY_CloudInfoFromAAI.getRelatedCloudRegionAndTenant(relationships);
+
+ assertThat(actual.get(), sameBeanAs(expected));
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java
index 6344a3f1a6..e8d597a823 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java
@@ -27,7 +27,6 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.junit.Before;
@@ -43,199 +42,215 @@ import org.onap.so.db.catalog.beans.macro.RainyDayHandlerStatus;
import org.springframework.beans.factory.annotation.Autowired;
public class ExecuteBuildlingBlockRainyDayTest extends BaseTest {
- @Autowired
- private ExecuteBuildingBlockRainyDay executeBuildingBlockRainyDay;
-
- private ServiceInstance serviceInstance;
- private Customer customer; //will build service sub
- private GenericVnf vnf;
- private BuildingBlock buildingBlock;
- private ExecuteBuildingBlock executeBuildingBlock;
- private static final String ASTERISK = "*";
-
- @Before
- public void before() {
- serviceInstance = setServiceInstance();
- customer = setCustomer();
- vnf = setGenericVnf();
-
- buildingBlock = new BuildingBlock();
- buildingBlock.setBpmnFlowName("AssignServiceInstanceBB");
-
- executeBuildingBlock = new ExecuteBuildingBlock();
- executeBuildingBlock.setBuildingBlock(buildingBlock);
-
- delegateExecution.setVariable("gBBInput", gBBInput);
- delegateExecution.setVariable("WorkflowException", new WorkflowException("", 7000, ""));
- delegateExecution.setVariable("buildingBlock", executeBuildingBlock);
- delegateExecution.setVariable("lookupKeyMap", lookupKeyMap);
- }
-
- @Test
- public void setRetryTimerTest() throws Exception{
- delegateExecution.setVariable("retryCount", 2);
- executeBuildingBlockRainyDay.setRetryTimer(delegateExecution);
- assertEquals("PT40S",delegateExecution.getVariable("RetryDuration"));
- }
-
- @Test
- public void setRetryTimerExceptionTest() {
- expectedException.expect(BpmnError.class);
- DelegateExecution execution = mock(DelegateExecution.class);
- when(execution.getVariable(eq("retryCount"))).thenThrow(BpmnError.class);
- executeBuildingBlockRainyDay.setRetryTimer(execution);
- }
-
- @Test
- public void queryRainyDayTableExists() throws Exception{
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
- vnf.setVnfType("vnft1");
- delegateExecution.setVariable("aLaCarte", true);
- delegateExecution.setVariable("suppressRollback", false);
- delegateExecution.setVariable("WorkflowExceptionCode", "7000");
- RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus();
- rainyDayHandlerStatus.setErrorCode("7000");
- rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB");
- rainyDayHandlerStatus.setServiceType("st1");
- rainyDayHandlerStatus.setVnfType("vnft1");
- rainyDayHandlerStatus.setPolicy("Rollback");
- rainyDayHandlerStatus.setWorkStep(ASTERISK);
-
- doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep("AssignServiceInstanceBB", "st1", "vnft1", "7000", "*");
-
- executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true);
-
- assertEquals("Rollback", delegateExecution.getVariable("handlingCode"));
- }
-
- @Test
- public void queryRainyDayTableDefault() throws Exception{
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
- vnf.setVnfType("vnft1");
- delegateExecution.setVariable("aLaCarte", true);
- delegateExecution.setVariable("suppressRollback", false);
- delegateExecution.setVariable("WorkflowExceptionCode", ASTERISK);
- RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus();
- rainyDayHandlerStatus.setErrorCode(ASTERISK);
- rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB");
- rainyDayHandlerStatus.setServiceType(ASTERISK);
- rainyDayHandlerStatus.setVnfType(ASTERISK);
- rainyDayHandlerStatus.setPolicy("Rollback");
- rainyDayHandlerStatus.setWorkStep(ASTERISK);
-
- doReturn(null).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep("AssignServiceInstanceBB", "st1", "vnft1", "7000", ASTERISK);
- doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep("AssignServiceInstanceBB", ASTERISK, ASTERISK, ASTERISK, ASTERISK);
-
- executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true);
-
- assertEquals("Rollback", delegateExecution.getVariable("handlingCode"));
- assertEquals(5,delegateExecution.getVariable("maxRetries"));
- }
-
- @Test
- public void queryRainyDayTableDoesNotExist() throws Exception{
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
- vnf.setVnfType("vnft1");
- delegateExecution.setVariable("aLaCarte", true);
- doReturn(null).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class));
- delegateExecution.setVariable("suppressRollback", false);
-
- executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true);
-
- assertEquals("Abort", delegateExecution.getVariable("handlingCode"));
- }
-
- @Test
- public void queryRainyDayTableExceptionTest() {
- doThrow(RuntimeException.class).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class));
- delegateExecution.setVariable("aLaCarte", true);
- executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true);
- delegateExecution.setVariable("suppressRollback", false);
-
- assertEquals("Abort", delegateExecution.getVariable("handlingCode"));
- }
-
- @Test
- public void queryRainyDayTableSecondaryPolicyExists() throws Exception{
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
- vnf.setVnfType("vnft1");
- delegateExecution.setVariable("aLaCarte", true);
- delegateExecution.setVariable("suppressRollback", false);
- delegateExecution.setVariable("WorkflowExceptionCode", "7000");
- RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus();
- rainyDayHandlerStatus.setErrorCode("7000");
- rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB");
- rainyDayHandlerStatus.setServiceType("st1");
- rainyDayHandlerStatus.setVnfType("vnft1");
- rainyDayHandlerStatus.setPolicy("Retry");
- rainyDayHandlerStatus.setWorkStep(ASTERISK);
- rainyDayHandlerStatus.setSecondaryPolicy("Abort");
-
- doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep("AssignServiceInstanceBB", "st1", "vnft1", "7000", "*");
-
- executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,false);
-
- assertEquals("Abort", delegateExecution.getVariable("handlingCode"));
- }
-
- @Test
- public void queryRainyDayTableRollbackToAssignedMacro() throws Exception{
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
- vnf.setVnfType("vnft1");
- delegateExecution.setVariable("aLaCarte", false);
- delegateExecution.setVariable("suppressRollback", false);
- delegateExecution.setVariable("WorkflowExceptionCode", "7000");
- RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus();
- rainyDayHandlerStatus.setErrorCode("7000");
- rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB");
- rainyDayHandlerStatus.setServiceType("st1");
- rainyDayHandlerStatus.setVnfType("vnft1");
- rainyDayHandlerStatus.setPolicy("RollbackToAssigned");
- rainyDayHandlerStatus.setWorkStep(ASTERISK);
- rainyDayHandlerStatus.setSecondaryPolicy("Abort");
-
- doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep("AssignServiceInstanceBB", "st1", "vnft1", "7000", "*");
-
- executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true);
-
- assertEquals("Rollback", delegateExecution.getVariable("handlingCode"));
- }
-
- @Test
- public void queryRainyDayTableRollbackToAssignedALaCarte() throws Exception{
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
- vnf.setVnfType("vnft1");
- delegateExecution.setVariable("aLaCarte", true);
- delegateExecution.setVariable("suppressRollback", false);
- delegateExecution.setVariable("WorkflowExceptionCode", "7000");
- RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus();
- rainyDayHandlerStatus.setErrorCode("7000");
- rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB");
- rainyDayHandlerStatus.setServiceType("st1");
- rainyDayHandlerStatus.setVnfType("vnft1");
- rainyDayHandlerStatus.setPolicy("RollbackToAssigned");
- rainyDayHandlerStatus.setWorkStep(ASTERISK);
- rainyDayHandlerStatus.setSecondaryPolicy("Abort");
-
- doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep("AssignServiceInstanceBB", "st1", "vnft1", "7000", "*");
-
- executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true);
-
- assertEquals("RollbackToAssigned", delegateExecution.getVariable("handlingCode"));
- }
-
- @Test
- public void suppressRollbackTest() throws Exception {
- delegateExecution.setVariable("suppressRollback", true);
- delegateExecution.setVariable("aLaCarte", true);
- executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true);
- assertEquals("Abort", delegateExecution.getVariable("handlingCode"));
- }
-
+ @Autowired
+ private ExecuteBuildingBlockRainyDay executeBuildingBlockRainyDay;
+
+ private ServiceInstance serviceInstance;
+ private Customer customer; // will build service sub
+ private GenericVnf vnf;
+ private BuildingBlock buildingBlock;
+ private ExecuteBuildingBlock executeBuildingBlock;
+ private static final String ASTERISK = "*";
+
+ @Before
+ public void before() {
+ serviceInstance = setServiceInstance();
+ customer = setCustomer();
+ vnf = setGenericVnf();
+
+ buildingBlock = new BuildingBlock();
+ buildingBlock.setBpmnFlowName("AssignServiceInstanceBB");
+
+ executeBuildingBlock = new ExecuteBuildingBlock();
+ executeBuildingBlock.setBuildingBlock(buildingBlock);
+
+ delegateExecution.setVariable("gBBInput", gBBInput);
+ delegateExecution.setVariable("WorkflowException", new WorkflowException("", 7000, ""));
+ delegateExecution.setVariable("buildingBlock", executeBuildingBlock);
+ delegateExecution.setVariable("lookupKeyMap", lookupKeyMap);
+ }
+
+ @Test
+ public void setRetryTimerTest() throws Exception {
+ delegateExecution.setVariable("retryCount", 2);
+ executeBuildingBlockRainyDay.setRetryTimer(delegateExecution);
+ assertEquals("PT40S", delegateExecution.getVariable("RetryDuration"));
+ }
+
+ @Test
+ public void setRetryTimerExceptionTest() {
+ expectedException.expect(BpmnError.class);
+ DelegateExecution execution = mock(DelegateExecution.class);
+ when(execution.getVariable(eq("retryCount"))).thenThrow(BpmnError.class);
+ executeBuildingBlockRainyDay.setRetryTimer(execution);
+ }
+
+ @Test
+ public void queryRainyDayTableExists() throws Exception {
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
+ vnf.setVnfType("vnft1");
+ delegateExecution.setVariable("aLaCarte", true);
+ delegateExecution.setVariable("suppressRollback", false);
+ delegateExecution.setVariable("WorkflowExceptionCode", "7000");
+ RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus();
+ rainyDayHandlerStatus.setErrorCode("7000");
+ rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB");
+ rainyDayHandlerStatus.setServiceType("st1");
+ rainyDayHandlerStatus.setVnfType("vnft1");
+ rainyDayHandlerStatus.setPolicy("Rollback");
+ rainyDayHandlerStatus.setWorkStep(ASTERISK);
+
+ doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient)
+ .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(
+ "AssignServiceInstanceBB", "st1", "vnft1", "7000", "*");
+
+ executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
+
+ assertEquals("Rollback", delegateExecution.getVariable("handlingCode"));
+ }
+
+ @Test
+ public void queryRainyDayTableDefault() throws Exception {
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
+ vnf.setVnfType("vnft1");
+ delegateExecution.setVariable("aLaCarte", true);
+ delegateExecution.setVariable("suppressRollback", false);
+ delegateExecution.setVariable("WorkflowExceptionCode", ASTERISK);
+ RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus();
+ rainyDayHandlerStatus.setErrorCode(ASTERISK);
+ rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB");
+ rainyDayHandlerStatus.setServiceType(ASTERISK);
+ rainyDayHandlerStatus.setVnfType(ASTERISK);
+ rainyDayHandlerStatus.setPolicy("Rollback");
+ rainyDayHandlerStatus.setWorkStep(ASTERISK);
+
+ doReturn(null).when(MOCK_catalogDbClient)
+ .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(
+ "AssignServiceInstanceBB", "st1", "vnft1", "7000", ASTERISK);
+ doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient)
+ .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(
+ "AssignServiceInstanceBB", ASTERISK, ASTERISK, ASTERISK, ASTERISK);
+
+ executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
+
+ assertEquals("Rollback", delegateExecution.getVariable("handlingCode"));
+ assertEquals(5, delegateExecution.getVariable("maxRetries"));
+ }
+
+ @Test
+ public void queryRainyDayTableDoesNotExist() throws Exception {
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
+ vnf.setVnfType("vnft1");
+ delegateExecution.setVariable("aLaCarte", true);
+ doReturn(null).when(MOCK_catalogDbClient)
+ .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(isA(String.class),
+ isA(String.class), isA(String.class), isA(String.class), isA(String.class));
+ delegateExecution.setVariable("suppressRollback", false);
+
+ executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
+
+ assertEquals("Abort", delegateExecution.getVariable("handlingCode"));
+ }
+
+ @Test
+ public void queryRainyDayTableExceptionTest() {
+ doThrow(RuntimeException.class).when(MOCK_catalogDbClient)
+ .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(isA(String.class),
+ isA(String.class), isA(String.class), isA(String.class), isA(String.class));
+ delegateExecution.setVariable("aLaCarte", true);
+ executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
+ delegateExecution.setVariable("suppressRollback", false);
+
+ assertEquals("Abort", delegateExecution.getVariable("handlingCode"));
+ }
+
+ @Test
+ public void queryRainyDayTableSecondaryPolicyExists() throws Exception {
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
+ vnf.setVnfType("vnft1");
+ delegateExecution.setVariable("aLaCarte", true);
+ delegateExecution.setVariable("suppressRollback", false);
+ delegateExecution.setVariable("WorkflowExceptionCode", "7000");
+ RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus();
+ rainyDayHandlerStatus.setErrorCode("7000");
+ rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB");
+ rainyDayHandlerStatus.setServiceType("st1");
+ rainyDayHandlerStatus.setVnfType("vnft1");
+ rainyDayHandlerStatus.setPolicy("Retry");
+ rainyDayHandlerStatus.setWorkStep(ASTERISK);
+ rainyDayHandlerStatus.setSecondaryPolicy("Abort");
+
+ doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient)
+ .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(
+ "AssignServiceInstanceBB", "st1", "vnft1", "7000", "*");
+
+ executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, false);
+
+ assertEquals("Abort", delegateExecution.getVariable("handlingCode"));
+ }
+
+ @Test
+ public void queryRainyDayTableRollbackToAssignedMacro() throws Exception {
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
+ vnf.setVnfType("vnft1");
+ delegateExecution.setVariable("aLaCarte", false);
+ delegateExecution.setVariable("suppressRollback", false);
+ delegateExecution.setVariable("WorkflowExceptionCode", "7000");
+ RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus();
+ rainyDayHandlerStatus.setErrorCode("7000");
+ rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB");
+ rainyDayHandlerStatus.setServiceType("st1");
+ rainyDayHandlerStatus.setVnfType("vnft1");
+ rainyDayHandlerStatus.setPolicy("RollbackToAssigned");
+ rainyDayHandlerStatus.setWorkStep(ASTERISK);
+ rainyDayHandlerStatus.setSecondaryPolicy("Abort");
+
+ doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient)
+ .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(
+ "AssignServiceInstanceBB", "st1", "vnft1", "7000", "*");
+
+ executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
+
+ assertEquals("Rollback", delegateExecution.getVariable("handlingCode"));
+ }
+
+ @Test
+ public void queryRainyDayTableRollbackToAssignedALaCarte() throws Exception {
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
+ vnf.setVnfType("vnft1");
+ delegateExecution.setVariable("aLaCarte", true);
+ delegateExecution.setVariable("suppressRollback", false);
+ delegateExecution.setVariable("WorkflowExceptionCode", "7000");
+ RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus();
+ rainyDayHandlerStatus.setErrorCode("7000");
+ rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB");
+ rainyDayHandlerStatus.setServiceType("st1");
+ rainyDayHandlerStatus.setVnfType("vnft1");
+ rainyDayHandlerStatus.setPolicy("RollbackToAssigned");
+ rainyDayHandlerStatus.setWorkStep(ASTERISK);
+ rainyDayHandlerStatus.setSecondaryPolicy("Abort");
+
+ doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient)
+ .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(
+ "AssignServiceInstanceBB", "st1", "vnft1", "7000", "*");
+
+ executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
+
+ assertEquals("RollbackToAssigned", delegateExecution.getVariable("handlingCode"));
+ }
+
+ @Test
+ public void suppressRollbackTest() throws Exception {
+ delegateExecution.setVariable("suppressRollback", true);
+ delegateExecution.setVariable("aLaCarte", true);
+ executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
+ assertEquals("Abort", delegateExecution.getVariable("handlingCode"));
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/MultipleObjectsFoundExceptionTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/MultipleObjectsFoundExceptionTest.java
index 1cf70d050a..75df1a08d9 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/MultipleObjectsFoundExceptionTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/MultipleObjectsFoundExceptionTest.java
@@ -21,47 +21,46 @@
package org.onap.so.bpmn.servicedecomposition.tasks.exceptions;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.MultipleObjectsFoundException;
public class MultipleObjectsFoundExceptionTest {
- private static final String MESSAGE = "message";
- private static final Throwable CAUSE = new Throwable();
- private MultipleObjectsFoundException MultipleObjectsFoundException;
-
- @Test
- public void defaultConstructorTest() {
- MultipleObjectsFoundException = new MultipleObjectsFoundException();
- assertEquals(null, MultipleObjectsFoundException.getMessage());
- assertEquals(null, MultipleObjectsFoundException.getCause());
- }
-
- @Test
- public void messageConstructorTest() {
- MultipleObjectsFoundException = new MultipleObjectsFoundException(MESSAGE);
- assertEquals(MESSAGE, MultipleObjectsFoundException.getMessage());
- assertEquals(null, MultipleObjectsFoundException.getCause());
- }
-
- @Test
- public void causeConstructorTest() {
- MultipleObjectsFoundException = new MultipleObjectsFoundException(CAUSE);
- assertEquals(CAUSE.toString(), MultipleObjectsFoundException.getMessage());
- assertEquals(CAUSE, MultipleObjectsFoundException.getCause());
- }
-
- @Test
- public void messageAndCauseConstructorTest() {
- MultipleObjectsFoundException = new MultipleObjectsFoundException(MESSAGE, CAUSE);
- assertEquals(MESSAGE, MultipleObjectsFoundException.getMessage());
- assertEquals(CAUSE, MultipleObjectsFoundException.getCause());
- }
-
- @Test
- public void messageAndCauseAndFlagsConstructorTest() {
- MultipleObjectsFoundException = new MultipleObjectsFoundException(MESSAGE, CAUSE, true, true);
- assertEquals(MESSAGE, MultipleObjectsFoundException.getMessage());
- assertEquals(CAUSE, MultipleObjectsFoundException.getCause());
- }
+ private static final String MESSAGE = "message";
+ private static final Throwable CAUSE = new Throwable();
+ private MultipleObjectsFoundException MultipleObjectsFoundException;
+
+ @Test
+ public void defaultConstructorTest() {
+ MultipleObjectsFoundException = new MultipleObjectsFoundException();
+ assertEquals(null, MultipleObjectsFoundException.getMessage());
+ assertEquals(null, MultipleObjectsFoundException.getCause());
+ }
+
+ @Test
+ public void messageConstructorTest() {
+ MultipleObjectsFoundException = new MultipleObjectsFoundException(MESSAGE);
+ assertEquals(MESSAGE, MultipleObjectsFoundException.getMessage());
+ assertEquals(null, MultipleObjectsFoundException.getCause());
+ }
+
+ @Test
+ public void causeConstructorTest() {
+ MultipleObjectsFoundException = new MultipleObjectsFoundException(CAUSE);
+ assertEquals(CAUSE.toString(), MultipleObjectsFoundException.getMessage());
+ assertEquals(CAUSE, MultipleObjectsFoundException.getCause());
+ }
+
+ @Test
+ public void messageAndCauseConstructorTest() {
+ MultipleObjectsFoundException = new MultipleObjectsFoundException(MESSAGE, CAUSE);
+ assertEquals(MESSAGE, MultipleObjectsFoundException.getMessage());
+ assertEquals(CAUSE, MultipleObjectsFoundException.getCause());
+ }
+
+ @Test
+ public void messageAndCauseAndFlagsConstructorTest() {
+ MultipleObjectsFoundException = new MultipleObjectsFoundException(MESSAGE, CAUSE, true, true);
+ assertEquals(MESSAGE, MultipleObjectsFoundException.getMessage());
+ assertEquals(CAUSE, MultipleObjectsFoundException.getCause());
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/NoServiceInstanceFoundExceptionTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/NoServiceInstanceFoundExceptionTest.java
index 344481dbed..c5970f64ee 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/NoServiceInstanceFoundExceptionTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/NoServiceInstanceFoundExceptionTest.java
@@ -21,46 +21,45 @@
package org.onap.so.bpmn.servicedecomposition.tasks.exceptions;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
public class NoServiceInstanceFoundExceptionTest {
- private static final String MESSAGE = "message";
- private static final Throwable CAUSE = new Throwable();
- private NoServiceInstanceFoundException NoObjectFoundException;
-
- @Test
- public void defaultConstructorTest() {
- NoObjectFoundException = new NoServiceInstanceFoundException();
- assertEquals(null, NoObjectFoundException.getMessage());
- assertEquals(null, NoObjectFoundException.getCause());
- }
-
- @Test
- public void messageConstructorTest() {
- NoObjectFoundException = new NoServiceInstanceFoundException(MESSAGE);
- assertEquals(MESSAGE, NoObjectFoundException.getMessage());
- assertEquals(null, NoObjectFoundException.getCause());
- }
-
- @Test
- public void causeConstructorTest() {
- NoObjectFoundException = new NoServiceInstanceFoundException(CAUSE);
- assertEquals(CAUSE.toString(), NoObjectFoundException.getMessage());
- assertEquals(CAUSE, NoObjectFoundException.getCause());
- }
-
- @Test
- public void messageAndCauseConstructorTest() {
- NoObjectFoundException = new NoServiceInstanceFoundException(MESSAGE, CAUSE);
- assertEquals(MESSAGE, NoObjectFoundException.getMessage());
- assertEquals(CAUSE, NoObjectFoundException.getCause());
- }
-
- @Test
- public void messageAndCauseAndFlagsConstructorTest() {
- NoObjectFoundException = new NoServiceInstanceFoundException(MESSAGE, CAUSE, true, true);
- assertEquals(MESSAGE, NoObjectFoundException.getMessage());
- assertEquals(CAUSE, NoObjectFoundException.getCause());
- }
+ private static final String MESSAGE = "message";
+ private static final Throwable CAUSE = new Throwable();
+ private NoServiceInstanceFoundException NoObjectFoundException;
+
+ @Test
+ public void defaultConstructorTest() {
+ NoObjectFoundException = new NoServiceInstanceFoundException();
+ assertEquals(null, NoObjectFoundException.getMessage());
+ assertEquals(null, NoObjectFoundException.getCause());
+ }
+
+ @Test
+ public void messageConstructorTest() {
+ NoObjectFoundException = new NoServiceInstanceFoundException(MESSAGE);
+ assertEquals(MESSAGE, NoObjectFoundException.getMessage());
+ assertEquals(null, NoObjectFoundException.getCause());
+ }
+
+ @Test
+ public void causeConstructorTest() {
+ NoObjectFoundException = new NoServiceInstanceFoundException(CAUSE);
+ assertEquals(CAUSE.toString(), NoObjectFoundException.getMessage());
+ assertEquals(CAUSE, NoObjectFoundException.getCause());
+ }
+
+ @Test
+ public void messageAndCauseConstructorTest() {
+ NoObjectFoundException = new NoServiceInstanceFoundException(MESSAGE, CAUSE);
+ assertEquals(MESSAGE, NoObjectFoundException.getMessage());
+ assertEquals(CAUSE, NoObjectFoundException.getCause());
+ }
+
+ @Test
+ public void messageAndCauseAndFlagsConstructorTest() {
+ NoObjectFoundException = new NoServiceInstanceFoundException(MESSAGE, CAUSE, true, true);
+ assertEquals(MESSAGE, NoObjectFoundException.getMessage());
+ assertEquals(CAUSE, NoObjectFoundException.getCause());
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/ResponseExceptionMapperImplTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/ResponseExceptionMapperImplTest.java
index 14a30391f9..cb98b1b603 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/ResponseExceptionMapperImplTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/ResponseExceptionMapperImplTest.java
@@ -22,11 +22,9 @@ package org.onap.so.client;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
-
import javax.ws.rs.BadRequestException;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.InternalServerErrorException;
@@ -38,85 +36,79 @@ import javax.ws.rs.NotSupportedException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
-
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
@RunWith(JUnitParamsRunner.class)
-public class ResponseExceptionMapperImplTest{
+public class ResponseExceptionMapperImplTest {
- private static final ResponseExceptionMapperImpl mapper = new ResponseExceptionMapperImpl();
+ private static final ResponseExceptionMapperImpl mapper = new ResponseExceptionMapperImpl();
- public static Object[][] statusesAndCorrespondingExceptions() {
- return new Object[][]{
- {Status.BAD_REQUEST, BadRequestException.class},
- {Status.UNAUTHORIZED, NotAuthorizedException.class},
- {Status.FORBIDDEN, ForbiddenException.class},
- {Status.NOT_FOUND, NotFoundException.class},
- {Status.METHOD_NOT_ALLOWED, NotAllowedException.class},
- {Status.NOT_ACCEPTABLE, NotAcceptableException.class},
- {Status.PRECONDITION_FAILED, PreconditionFailedException.class},
- {Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class},
- {Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class},
- {Status.SERVICE_UNAVAILABLE, WebApplicationException.class},
- {Status.BAD_GATEWAY, WebApplicationException.class},
- };
- }
+ public static Object[][] statusesAndCorrespondingExceptions() {
+ return new Object[][] {{Status.BAD_REQUEST, BadRequestException.class},
+ {Status.UNAUTHORIZED, NotAuthorizedException.class}, {Status.FORBIDDEN, ForbiddenException.class},
+ {Status.NOT_FOUND, NotFoundException.class}, {Status.METHOD_NOT_ALLOWED, NotAllowedException.class},
+ {Status.NOT_ACCEPTABLE, NotAcceptableException.class},
+ {Status.PRECONDITION_FAILED, PreconditionFailedException.class},
+ {Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class},
+ {Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class},
+ {Status.SERVICE_UNAVAILABLE, WebApplicationException.class},
+ {Status.BAD_GATEWAY, WebApplicationException.class},};
+ }
- @Rule
- public ExpectedException expectedExceptionTest = ExpectedException.none();
+ @Rule
+ public ExpectedException expectedExceptionTest = ExpectedException.none();
- @Test
- @Parameters(method = "statusesAndCorrespondingExceptions")
- public void shouldThrowExceptionWhenStatusIsNotOk(Status status, Class<Exception> expectedException) {
- // given
- Response response = createMockResponse(status);
- // when, then
- expectedExceptionTest.expect(expectedException);
- mapper.map(response);
- }
+ @Test
+ @Parameters(method = "statusesAndCorrespondingExceptions")
+ public void shouldThrowExceptionWhenStatusIsNotOk(Status status, Class<Exception> expectedException) {
+ // given
+ Response response = createMockResponse(status);
+ // when, then
+ expectedExceptionTest.expect(expectedException);
+ mapper.map(response);
+ }
+
+ @Test
+ public void shouldNotThrowExceptionWhenStatusIsOk() {
+ // given
+ Response response = createMockResponse(Status.OK);
+ // when, then
+ expectedExceptionTest.none();
+ mapper.map(response);
+ }
- @Test
- public void shouldNotThrowExceptionWhenStatusIsOk() {
- // given
- Response response = createMockResponse(Status.OK);
- // when, then
- expectedExceptionTest.none();
- mapper.map(response);
- }
-
@Test
public void shouldThrowExceptionWithCustomMessageWhenResponseHasEntity() throws UnsupportedEncodingException {
// given
- Response response = createMockResponse(Status.BAD_REQUEST);
+ Response response = createMockResponse(Status.BAD_REQUEST);
when(response.hasEntity()).thenReturn(true);
when(response.readEntity(String.class)).thenReturn("test message");
-
+
expectedExceptionTest.expect(BadRequestException.class);
expectedExceptionTest.expectMessage("test message");
- mapper.map(response);
+ mapper.map(response);
}
@Test
public void shouldThrowExceptionWithDefaultMessageWhenResponseHasNoEntity() {
// given
- Response response = createMockResponse(Status.BAD_REQUEST);
+ Response response = createMockResponse(Status.BAD_REQUEST);
when(response.hasEntity()).thenReturn(false);
// when, then
expectedExceptionTest.expect(BadRequestException.class);
expectedExceptionTest.expectMessage("");
- mapper.map(response);
+ mapper.map(response);
+ }
+
+ private static Response createMockResponse(Status status) {
+ Response responseContext = mock(Response.class);
+ when(responseContext.getStatusInfo()).thenReturn(status);
+ when(responseContext.getStatus()).thenReturn(status.getStatusCode());
+ return responseContext;
}
-
- private static Response createMockResponse(Status status) {
- Response responseContext = mock(Response.class);
- when(responseContext.getStatusInfo()).thenReturn(status);
- when(responseContext.getStatus()).thenReturn(status.getStatusCode());
- return responseContext;
- }
-} \ No newline at end of file
+}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerActionTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerActionTest.java
index 2f65f9ce66..32db3a7bf6 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerActionTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerActionTest.java
@@ -26,11 +26,9 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Optional;
-
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
@@ -43,420 +41,444 @@ import org.onap.so.BaseTest;
import com.fasterxml.jackson.core.JsonProcessingException;
-public class ApplicationControllerActionTest extends BaseTest{
-
- private ApplicationControllerAction appCAction;
-
- @Mock
- private ApplicationControllerOrchestrator client;
-
- @Before
- public void setup() {
- MockitoAnnotations.initMocks(this);
-
- appCAction = new ApplicationControllerAction();
- appCAction.client = client;
- }
-
- @Test
- public void runAppCCommand_ResumeTraffic_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
- //Prepare method
- Action action = Action.ResumeTraffic;
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.empty();
- Optional<String> vserverId = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName");
- String controllerType = "testControllerType";
-
- //Prepare mocks
- Status status = new Status();
- Optional<String> otherPayload = PayloadClient.resumeTrafficFormat(payloadInfo.get("vnfName"));
- doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify call
- verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
- }
-
- @Test
- public void runAppCCommand_Start_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
- runAppCCommand_StartStop_Test(Action.Start);
- }
-
- @Test
- public void runAppCCommand_Stop_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
- runAppCCommand_StartStop_Test(Action.Stop);
- }
-
- private void runAppCCommand_StartStop_Test(Action action) throws ApplicationControllerOrchestratorException, JsonProcessingException {
- //Prepare method
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.empty();
- Optional<String> vserverId = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName");
- String controllerType = "testControllerType";
-
- //Prepare mocks
- Status status = new Status();
- Optional<String> otherPayload = PayloadClient.startStopFormat(payloadInfo.get("vnfName"));
- doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify call
- verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
- }
-
- @Test
- public void runAppCCommand_Unlock_Test() throws ApplicationControllerOrchestratorException {
- runAppCCommand_LockUnlock_Test(Action.Unlock);
- }
-
- @Test
- public void runAppCCommand_Lock_Test() throws ApplicationControllerOrchestratorException {
- runAppCCommand_LockUnlock_Test(Action.Lock);
- }
-
- private void runAppCCommand_LockUnlock_Test(Action action) throws ApplicationControllerOrchestratorException {
- //Prepare method
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.empty();
- Optional<String> vserverId = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- String controllerType = "testControllerType";
-
- //Prepare mocks
- Status status = new Status();
- Optional<String> otherPayload = Optional.empty();
- doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify call
- verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
- }
-
- @Test
- public void runAppCCommand_QuiesceTraffic_PayloadPresent_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
- //Prepare method
- Action action = Action.QuiesceTraffic;
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.of("testPayload");
- Optional<String> vserverId = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName");
- String controllerType = "testControllerType";
-
- //Prepare mocks
- Status status = new Status();
- Optional<String> modifiedPayload = PayloadClient.quiesceTrafficFormat(payload, payloadInfo.get("vnfName"));
- doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, modifiedPayload, controllerType);
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify call
- verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, modifiedPayload, controllerType);
- }
-
- @Test
- public void runAppCCommand_QuiesceTraffic_NoPayload_Test() throws ApplicationControllerOrchestratorException {
- //Prepare method
- Action action = Action.QuiesceTraffic;
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- String controllerType = "testControllerType";
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify non call
- verify(client, times(0)).vnfCommand(any(), any(), any(), any(), any(), any());
- assertEquals("Payload is not present for " + action.toString(), appCAction.getErrorMessage());
- }
-
- @Test
- public void runAppCCommand_HealthCheck_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
- //Prepare method
- Action action = Action.HealthCheck;
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.empty();
- Optional<String> vserverId = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName");
- payloadInfo.put("vnfHostIpAddress", "testVnfHostIpAddress");
- String controllerType = "testControllerType";
-
- //Prepare mocks
- Status status = new Status();
- Optional<String> otherPayload = PayloadClient.healthCheckFormat(payloadInfo.get("vnfName"), payloadInfo.get("vnfHostIpAddress"));
- doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify call
- verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
- }
-
- @Test
- public void runAppCCommand_Snapshot_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
- //Prepare method
- Action action = Action.Snapshot;
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("identityUrl", "testIdentityUrl");
- ArrayList<String> vmIdList = new ArrayList<String>();
- String vmId1 = "testlink:testVmId1";
- vmIdList.add(vmId1);
- String vmId2 = "testlink:testVmId2";
- vmIdList.add(vmId2);
- JSONObject vmIdListJson = new JSONObject();
- vmIdListJson.put("vmIds", vmIdList);
- payloadInfo.put("vmIdList", vmIdListJson.toString());
- ArrayList<String> vserverIdList = new ArrayList<String>();
- String vserverId1 = "testVserverId1";
- Optional<String> vserverIdString1 = Optional.of(vserverId1);
- vserverIdList.add(vserverId1);
- String vserverId2 = "testVserverId2";
- Optional<String> vserverIdString2 = Optional.of(vserverId2);
- vserverIdList.add(vserverId2);
-
- JSONObject vserverIdListJson = new JSONObject();
- vserverIdListJson.put("vserverIds", vserverIdList);
- payloadInfo.put("vserverIdList", vserverIdListJson.toString());
- String controllerType = "testControllerType";
-
- //Prepare mocks
- Status status = new Status();
- Optional<String> otherPayloadVm1 = PayloadClient.snapshotFormat(vmId1, payloadInfo.get("identityUrl"));
- Optional<String> otherPayloadVm2 = PayloadClient.snapshotFormat(vmId2, payloadInfo.get("identityUrl"));
- doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverIdString1, otherPayloadVm1, controllerType);
- doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverIdString2, otherPayloadVm2, controllerType);
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify call
- verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverIdString1, otherPayloadVm1, controllerType);
- verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverIdString2, otherPayloadVm2, controllerType);
- }
-
- @Test
- public void runAppCCommand_ConfigModify__PayloadPresent_Test() throws ApplicationControllerOrchestratorException {
- //Prepare method
- Action action = Action.ConfigModify;
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.of("testPayload");
- Optional<String> vserverId = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- String controllerType = "testControllerType";
-
- //Prepare mocks
- Status status = new Status();
- doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, payload, controllerType);
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify call
- verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, payload, controllerType);
- }
-
- @Test
- public void runAppCCommand_ConfigModify__NoPayload_Test() throws ApplicationControllerOrchestratorException {
- //Prepare method
- Action action = Action.ConfigModify;
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- String controllerType = "testControllerType";
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify non call
- verify(client, times(0)).vnfCommand(any(), any(), any(), any(), any(), any());
- assertEquals("Payload is not present for " + action.toString(), appCAction.getErrorMessage());
- }
-
- @Test
- public void runAppCCommand_UpgradePreCheck_PayloadPresent_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
- runAppCCommand_Upgrade_PayloadPresent_Test(Action.UpgradePreCheck);
- }
-
- @Test
- public void runAppCCommand_UpgradePostCheck_PayloadPresent_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
- runAppCCommand_Upgrade_PayloadPresent_Test(Action.UpgradePostCheck);
- }
-
- @Test
- public void runAppCCommand_UpgradeSoftware_PayloadPresent_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
- runAppCCommand_Upgrade_PayloadPresent_Test(Action.UpgradeSoftware);
- }
-
- @Test
- public void runAppCCommand_UpgradeBackup_PayloadPresent_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
- runAppCCommand_Upgrade_PayloadPresent_Test(Action.UpgradeBackup);
- }
-
- private void runAppCCommand_Upgrade_PayloadPresent_Test(Action action) throws ApplicationControllerOrchestratorException, JsonProcessingException {
- //Prepare method
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.of("testPayload");
- Optional<String> vserverId = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName");
- String controllerType = "testControllerType";
-
- //Prepare mocks
- Status status = new Status();
- Optional<String> modifiedPayload = PayloadClient.upgradeFormat(payload, payloadInfo.get("vnfName"));
- doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, modifiedPayload, controllerType);
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify call
- verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, modifiedPayload, controllerType);
- }
-
- @Test
- public void runAppCCommand_UpgradePreCheck_NoPayload_Test() throws ApplicationControllerOrchestratorException {
- runAppCCommand_Upgrade_NoPayload_Test(Action.UpgradePreCheck);
- }
-
- @Test
- public void runAppCCommand_UpgradePostCheck_NoPayload_Test() throws ApplicationControllerOrchestratorException {
- runAppCCommand_Upgrade_NoPayload_Test(Action.UpgradePostCheck);
- }
-
- @Test
- public void runAppCCommand_UpgradeSoftware_NoPayload_Test() throws ApplicationControllerOrchestratorException {
- runAppCCommand_Upgrade_NoPayload_Test(Action.UpgradeSoftware);
- }
-
- @Test
- public void runAppCCommand_UpgradeBackup_NoPayload_Test() throws ApplicationControllerOrchestratorException {
- runAppCCommand_Upgrade_NoPayload_Test(Action.UpgradeBackup);
- }
-
- private void runAppCCommand_Upgrade_NoPayload_Test(Action action) throws ApplicationControllerOrchestratorException {
- //Prepare method
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- String controllerType = "testControllerType";
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify non call
- verify(client, times(0)).vnfCommand(any(), any(), any(), any(), any(), any());
- assertEquals("Payload is not present for " + action.toString(), appCAction.getErrorMessage());
- }
-
- @Test
- public void runAppCCommand_InvalidAppCAction_Test() throws ApplicationControllerOrchestratorException {
- //Prepare method
- Action action = Action.ActionStatus;
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- String controllerType = "testControllerType";
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify non call
- verify(client, times(0)).vnfCommand(any(), any(), any(), any(), any(), any());
- //TODO For original author/architect: it appears that whoever coded this wanted the error message to be "Unable to idenify Action request for AppCClient" and this is not the case because of the ApplicationControllerSupport.getCategoryOf(appCStatus) call with a null appCStatus, so this may be something worth looking into
- }
-
- @Test
- public void runAppCCommand_NormalAppCStatusGetErrorCode_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
- //Prepare method
- Action action = Action.Start;
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.empty();
- Optional<String> vserverId = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName");
- String controllerType = "testControllerType";
-
- //Prepare mocks
- Status status = new Status();
- status.setCode(100);
- Optional<String> otherPayload = PayloadClient.startStopFormat(payloadInfo.get("vnfName"));
- doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify call
- String expectedErrorCode = "0";
- assertEquals(expectedErrorCode, appCAction.getErrorCode());
- }
-
- @Test
- public void getErrorCode_Test() {
- String defaultErrorCode = "1002";
- //Verify default error code
- assertEquals(defaultErrorCode, appCAction.getErrorCode());
- }
-
- @Test
- public void getErrorMessage_Test() {
- String defaultErrorMessage = "Unable to reach App C Servers";
- //Verify default error message
- assertEquals(defaultErrorMessage, appCAction.getErrorMessage());
- }
-
- @Test
- public void applicationControllerOrchestratorExceptionCaught_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
- //Prepare method
- Action action = Action.Start;
- String msoRequestId = "testMsoRequestId";
- String vnfId = "testVnfId";
- Optional<String> payload = Optional.empty();
- Optional<String> vserverId = Optional.empty();
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName");
- String controllerType = "testControllerType";
-
- //Prepare mocks
- Optional<String> otherPayload = PayloadClient.startStopFormat(payloadInfo.get("vnfName"));
- String expectedErrorMessage = "Test appc orchestrator error message";
- doThrow(new ApplicationControllerOrchestratorException(expectedErrorMessage, 0)).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
-
- //Run method
- appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
-
- //Verify error
- assertEquals(expectedErrorMessage, appCAction.getErrorMessage());
- String expectedErrorCode = "1002";
- assertEquals(expectedErrorCode, appCAction.getErrorCode());
- }
-
+public class ApplicationControllerActionTest extends BaseTest {
+
+ private ApplicationControllerAction appCAction;
+
+ @Mock
+ private ApplicationControllerOrchestrator client;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+
+ appCAction = new ApplicationControllerAction();
+ appCAction.client = client;
+ }
+
+ @Test
+ public void runAppCCommand_ResumeTraffic_Test()
+ throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ // Prepare method
+ Action action = Action.ResumeTraffic;
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.empty();
+ Optional<String> vserverId = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName");
+ String controllerType = "testControllerType";
+
+ // Prepare mocks
+ Status status = new Status();
+ Optional<String> otherPayload = PayloadClient.resumeTrafficFormat(payloadInfo.get("vnfName"));
+ doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify call
+ verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
+ }
+
+ @Test
+ public void runAppCCommand_Start_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ runAppCCommand_StartStop_Test(Action.Start);
+ }
+
+ @Test
+ public void runAppCCommand_Stop_Test() throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ runAppCCommand_StartStop_Test(Action.Stop);
+ }
+
+ private void runAppCCommand_StartStop_Test(Action action)
+ throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ // Prepare method
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.empty();
+ Optional<String> vserverId = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName");
+ String controllerType = "testControllerType";
+
+ // Prepare mocks
+ Status status = new Status();
+ Optional<String> otherPayload = PayloadClient.startStopFormat(payloadInfo.get("vnfName"));
+ doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify call
+ verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
+ }
+
+ @Test
+ public void runAppCCommand_Unlock_Test() throws ApplicationControllerOrchestratorException {
+ runAppCCommand_LockUnlock_Test(Action.Unlock);
+ }
+
+ @Test
+ public void runAppCCommand_Lock_Test() throws ApplicationControllerOrchestratorException {
+ runAppCCommand_LockUnlock_Test(Action.Lock);
+ }
+
+ private void runAppCCommand_LockUnlock_Test(Action action) throws ApplicationControllerOrchestratorException {
+ // Prepare method
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.empty();
+ Optional<String> vserverId = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ String controllerType = "testControllerType";
+
+ // Prepare mocks
+ Status status = new Status();
+ Optional<String> otherPayload = Optional.empty();
+ doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify call
+ verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
+ }
+
+ @Test
+ public void runAppCCommand_QuiesceTraffic_PayloadPresent_Test()
+ throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ // Prepare method
+ Action action = Action.QuiesceTraffic;
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.of("testPayload");
+ Optional<String> vserverId = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName");
+ String controllerType = "testControllerType";
+
+ // Prepare mocks
+ Status status = new Status();
+ Optional<String> modifiedPayload = PayloadClient.quiesceTrafficFormat(payload, payloadInfo.get("vnfName"));
+ doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, modifiedPayload,
+ controllerType);
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify call
+ verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, modifiedPayload, controllerType);
+ }
+
+ @Test
+ public void runAppCCommand_QuiesceTraffic_NoPayload_Test() throws ApplicationControllerOrchestratorException {
+ // Prepare method
+ Action action = Action.QuiesceTraffic;
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ String controllerType = "testControllerType";
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify non call
+ verify(client, times(0)).vnfCommand(any(), any(), any(), any(), any(), any());
+ assertEquals("Payload is not present for " + action.toString(), appCAction.getErrorMessage());
+ }
+
+ @Test
+ public void runAppCCommand_HealthCheck_Test()
+ throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ // Prepare method
+ Action action = Action.HealthCheck;
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.empty();
+ Optional<String> vserverId = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName");
+ payloadInfo.put("vnfHostIpAddress", "testVnfHostIpAddress");
+ String controllerType = "testControllerType";
+
+ // Prepare mocks
+ Status status = new Status();
+ Optional<String> otherPayload =
+ PayloadClient.healthCheckFormat(payloadInfo.get("vnfName"), payloadInfo.get("vnfHostIpAddress"));
+ doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify call
+ verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
+ }
+
+ @Test
+ public void runAppCCommand_Snapshot_Test()
+ throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ // Prepare method
+ Action action = Action.Snapshot;
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("identityUrl", "testIdentityUrl");
+ ArrayList<String> vmIdList = new ArrayList<String>();
+ String vmId1 = "testlink:testVmId1";
+ vmIdList.add(vmId1);
+ String vmId2 = "testlink:testVmId2";
+ vmIdList.add(vmId2);
+ JSONObject vmIdListJson = new JSONObject();
+ vmIdListJson.put("vmIds", vmIdList);
+ payloadInfo.put("vmIdList", vmIdListJson.toString());
+ ArrayList<String> vserverIdList = new ArrayList<String>();
+ String vserverId1 = "testVserverId1";
+ Optional<String> vserverIdString1 = Optional.of(vserverId1);
+ vserverIdList.add(vserverId1);
+ String vserverId2 = "testVserverId2";
+ Optional<String> vserverIdString2 = Optional.of(vserverId2);
+ vserverIdList.add(vserverId2);
+
+ JSONObject vserverIdListJson = new JSONObject();
+ vserverIdListJson.put("vserverIds", vserverIdList);
+ payloadInfo.put("vserverIdList", vserverIdListJson.toString());
+ String controllerType = "testControllerType";
+
+ // Prepare mocks
+ Status status = new Status();
+ Optional<String> otherPayloadVm1 = PayloadClient.snapshotFormat(vmId1, payloadInfo.get("identityUrl"));
+ Optional<String> otherPayloadVm2 = PayloadClient.snapshotFormat(vmId2, payloadInfo.get("identityUrl"));
+ doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverIdString1, otherPayloadVm1,
+ controllerType);
+ doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverIdString2, otherPayloadVm2,
+ controllerType);
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify call
+ verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverIdString1, otherPayloadVm1,
+ controllerType);
+ verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverIdString2, otherPayloadVm2,
+ controllerType);
+ }
+
+ @Test
+ public void runAppCCommand_ConfigModify__PayloadPresent_Test() throws ApplicationControllerOrchestratorException {
+ // Prepare method
+ Action action = Action.ConfigModify;
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.of("testPayload");
+ Optional<String> vserverId = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ String controllerType = "testControllerType";
+
+ // Prepare mocks
+ Status status = new Status();
+ doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, payload, controllerType);
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify call
+ verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, payload, controllerType);
+ }
+
+ @Test
+ public void runAppCCommand_ConfigModify__NoPayload_Test() throws ApplicationControllerOrchestratorException {
+ // Prepare method
+ Action action = Action.ConfigModify;
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ String controllerType = "testControllerType";
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify non call
+ verify(client, times(0)).vnfCommand(any(), any(), any(), any(), any(), any());
+ assertEquals("Payload is not present for " + action.toString(), appCAction.getErrorMessage());
+ }
+
+ @Test
+ public void runAppCCommand_UpgradePreCheck_PayloadPresent_Test()
+ throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ runAppCCommand_Upgrade_PayloadPresent_Test(Action.UpgradePreCheck);
+ }
+
+ @Test
+ public void runAppCCommand_UpgradePostCheck_PayloadPresent_Test()
+ throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ runAppCCommand_Upgrade_PayloadPresent_Test(Action.UpgradePostCheck);
+ }
+
+ @Test
+ public void runAppCCommand_UpgradeSoftware_PayloadPresent_Test()
+ throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ runAppCCommand_Upgrade_PayloadPresent_Test(Action.UpgradeSoftware);
+ }
+
+ @Test
+ public void runAppCCommand_UpgradeBackup_PayloadPresent_Test()
+ throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ runAppCCommand_Upgrade_PayloadPresent_Test(Action.UpgradeBackup);
+ }
+
+ private void runAppCCommand_Upgrade_PayloadPresent_Test(Action action)
+ throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ // Prepare method
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.of("testPayload");
+ Optional<String> vserverId = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName");
+ String controllerType = "testControllerType";
+
+ // Prepare mocks
+ Status status = new Status();
+ Optional<String> modifiedPayload = PayloadClient.upgradeFormat(payload, payloadInfo.get("vnfName"));
+ doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, modifiedPayload,
+ controllerType);
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify call
+ verify(client, times(1)).vnfCommand(action, msoRequestId, vnfId, vserverId, modifiedPayload, controllerType);
+ }
+
+ @Test
+ public void runAppCCommand_UpgradePreCheck_NoPayload_Test() throws ApplicationControllerOrchestratorException {
+ runAppCCommand_Upgrade_NoPayload_Test(Action.UpgradePreCheck);
+ }
+
+ @Test
+ public void runAppCCommand_UpgradePostCheck_NoPayload_Test() throws ApplicationControllerOrchestratorException {
+ runAppCCommand_Upgrade_NoPayload_Test(Action.UpgradePostCheck);
+ }
+
+ @Test
+ public void runAppCCommand_UpgradeSoftware_NoPayload_Test() throws ApplicationControllerOrchestratorException {
+ runAppCCommand_Upgrade_NoPayload_Test(Action.UpgradeSoftware);
+ }
+
+ @Test
+ public void runAppCCommand_UpgradeBackup_NoPayload_Test() throws ApplicationControllerOrchestratorException {
+ runAppCCommand_Upgrade_NoPayload_Test(Action.UpgradeBackup);
+ }
+
+ private void runAppCCommand_Upgrade_NoPayload_Test(Action action)
+ throws ApplicationControllerOrchestratorException {
+ // Prepare method
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ String controllerType = "testControllerType";
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify non call
+ verify(client, times(0)).vnfCommand(any(), any(), any(), any(), any(), any());
+ assertEquals("Payload is not present for " + action.toString(), appCAction.getErrorMessage());
+ }
+
+ @Test
+ public void runAppCCommand_InvalidAppCAction_Test() throws ApplicationControllerOrchestratorException {
+ // Prepare method
+ Action action = Action.ActionStatus;
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ String controllerType = "testControllerType";
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify non call
+ verify(client, times(0)).vnfCommand(any(), any(), any(), any(), any(), any());
+ // TODO For original author/architect: it appears that whoever coded this wanted the error message to be "Unable
+ // to idenify Action request for AppCClient" and this is not the case because of the
+ // ApplicationControllerSupport.getCategoryOf(appCStatus) call with a null appCStatus, so this may be something
+ // worth looking into
+ }
+
+ @Test
+ public void runAppCCommand_NormalAppCStatusGetErrorCode_Test()
+ throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ // Prepare method
+ Action action = Action.Start;
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.empty();
+ Optional<String> vserverId = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName");
+ String controllerType = "testControllerType";
+
+ // Prepare mocks
+ Status status = new Status();
+ status.setCode(100);
+ Optional<String> otherPayload = PayloadClient.startStopFormat(payloadInfo.get("vnfName"));
+ doReturn(status).when(client).vnfCommand(action, msoRequestId, vnfId, vserverId, otherPayload, controllerType);
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify call
+ String expectedErrorCode = "0";
+ assertEquals(expectedErrorCode, appCAction.getErrorCode());
+ }
+
+ @Test
+ public void getErrorCode_Test() {
+ String defaultErrorCode = "1002";
+ // Verify default error code
+ assertEquals(defaultErrorCode, appCAction.getErrorCode());
+ }
+
+ @Test
+ public void getErrorMessage_Test() {
+ String defaultErrorMessage = "Unable to reach App C Servers";
+ // Verify default error message
+ assertEquals(defaultErrorMessage, appCAction.getErrorMessage());
+ }
+
+ @Test
+ public void applicationControllerOrchestratorExceptionCaught_Test()
+ throws ApplicationControllerOrchestratorException, JsonProcessingException {
+ // Prepare method
+ Action action = Action.Start;
+ String msoRequestId = "testMsoRequestId";
+ String vnfId = "testVnfId";
+ Optional<String> payload = Optional.empty();
+ Optional<String> vserverId = Optional.empty();
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName");
+ String controllerType = "testControllerType";
+
+ // Prepare mocks
+ Optional<String> otherPayload = PayloadClient.startStopFormat(payloadInfo.get("vnfName"));
+ String expectedErrorMessage = "Test appc orchestrator error message";
+ doThrow(new ApplicationControllerOrchestratorException(expectedErrorMessage, 0)).when(client).vnfCommand(action,
+ msoRequestId, vnfId, vserverId, otherPayload, controllerType);
+
+ // Run method
+ appCAction.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+
+ // Verify error
+ assertEquals(expectedErrorMessage, appCAction.getErrorMessage());
+ String expectedErrorCode = "1002";
+ assertEquals(expectedErrorCode, appCAction.getErrorCode());
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerClientV2Test.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerClientV2Test.java
index 77daee6050..c242017838 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerClientV2Test.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerClientV2Test.java
@@ -35,96 +35,98 @@ import org.onap.appc.client.lcm.model.Status;
import org.onap.so.BaseTest;
import java.util.Properties;
import java.util.UUID;
-
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ApplicationControllerClientV2Test {
- @Mock
- ApplicationControllerSupport applicationControllerSupport;
+ @Mock
+ ApplicationControllerSupport applicationControllerSupport;
+
+ @Mock
+ ApplicationControllerConfiguration applicationControllerConfiguration;
+
+ @InjectMocks
+ ApplicationControllerClientV2 client;
+
- @Mock
- ApplicationControllerConfiguration applicationControllerConfiguration;
+ @Before
+ public void setup() {
+ when(applicationControllerConfiguration.getReadTopic()).thenReturn("APPC-TEST-AMDOCS2");
+ when(applicationControllerConfiguration.getReadTimeout()).thenReturn("120000");
+ when(applicationControllerConfiguration.getResponseTimeout()).thenReturn("120000");
+ when(applicationControllerConfiguration.getWrite()).thenReturn("APPC-TEST-AMDOCS1-DEV3");
+ when(applicationControllerConfiguration.getService()).thenReturn("ueb");
+ when(applicationControllerConfiguration.getPoolMembers())
+ .thenReturn("localhost:3904,localhost:3904,localhost:3904");
+ when(applicationControllerConfiguration.getClientKey()).thenReturn("iaEMAfjsVsZnraBP");
+ when(applicationControllerConfiguration.getClientSecret()).thenReturn("wcivUjsjXzmGFBfxMmyJu9dz");
+ // client.buildClient();
+ }
- @InjectMocks
- ApplicationControllerClientV2 client;
+ @BeforeClass
+ public static void beforeClass() {
+ System.setProperty("mso.config.path", "src/test/resources");
+ }
+ @Ignore
+ @Test
+ public void createRequest_CheckLock_RequestBuilt() {
+ ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
+ actionIdentifiers.setVnfId("vnfId");
+ // when(applicationControllerSupport.getInput(eq(Action.CheckLock.name()))).thenReturn(new CheckLockInput());
+ CheckLockInput checkLockInput =
+ (CheckLockInput) client.createRequest(Action.CheckLock, actionIdentifiers, null, "requestId");
+ assertEquals(checkLockInput.getAction().name(), "CheckLock");
+ }
- @Before
- public void setup(){
- when(applicationControllerConfiguration.getReadTopic()).thenReturn("APPC-TEST-AMDOCS2");
- when(applicationControllerConfiguration.getReadTimeout()).thenReturn("120000");
- when(applicationControllerConfiguration.getResponseTimeout()).thenReturn("120000");
- when(applicationControllerConfiguration.getWrite()).thenReturn("APPC-TEST-AMDOCS1-DEV3");
- when(applicationControllerConfiguration.getService()).thenReturn("ueb");
- when(applicationControllerConfiguration.getPoolMembers()).thenReturn("localhost:3904,localhost:3904,localhost:3904");
- when(applicationControllerConfiguration.getClientKey()).thenReturn("iaEMAfjsVsZnraBP");
- when(applicationControllerConfiguration.getClientSecret()).thenReturn("wcivUjsjXzmGFBfxMmyJu9dz");
- //client.buildClient();
- }
- @BeforeClass
- public static void beforeClass() {
- System.setProperty("mso.config.path", "src/test/resources");
- }
- @Ignore
- @Test
- public void createRequest_CheckLock_RequestBuilt() {
- ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
- actionIdentifiers.setVnfId("vnfId");
- // when(applicationControllerSupport.getInput(eq(Action.CheckLock.name()))).thenReturn(new CheckLockInput());
- CheckLockInput checkLockInput = (CheckLockInput) client.createRequest(Action.CheckLock, actionIdentifiers, null,
- "requestId");
- assertEquals(checkLockInput.getAction().name(), "CheckLock");
- }
- @Ignore
- @Test
- public void runCommand_liveAppc() {
- ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
- //actionIdentifiers.setVnfId("ca522254-2ba4-4fbd-b15b-0ef0d9cfda5f");
- actionIdentifiers.setVnfId("2d2bf10e-81a5-");
- Status status;
- //when(applicationControllerSupport.getInput(eq(Action.Lock.name()))).thenReturn(new LockInput());
- //when(applicationControllerSupport.getAPIMethod(anyString(),any(),anyBoolean())).thenCallRealMethod();
- try {
- status = client.runCommand(Action.Lock, actionIdentifiers, null, UUID.randomUUID().toString());
- } catch (ApplicationControllerOrchestratorException e) {
- status = new Status();
- status.setCode(e.getAppcCode());
- status.setMessage(e.getMessage());
- }
- assertEquals("Status of run command is correct", status.getCode(), 306);
- }
+ @Ignore
+ @Test
+ public void runCommand_liveAppc() {
+ ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
+ // actionIdentifiers.setVnfId("ca522254-2ba4-4fbd-b15b-0ef0d9cfda5f");
+ actionIdentifiers.setVnfId("2d2bf10e-81a5-");
+ Status status;
+ // when(applicationControllerSupport.getInput(eq(Action.Lock.name()))).thenReturn(new LockInput());
+ // when(applicationControllerSupport.getAPIMethod(anyString(),any(),anyBoolean())).thenCallRealMethod();
+ try {
+ status = client.runCommand(Action.Lock, actionIdentifiers, null, UUID.randomUUID().toString());
+ } catch (ApplicationControllerOrchestratorException e) {
+ status = new Status();
+ status.setCode(e.getAppcCode());
+ status.setMessage(e.getMessage());
+ }
+ assertEquals("Status of run command is correct", status.getCode(), 306);
+ }
- @Ignore
- @Test
- public void runCommand_CheckLock_RequestBuilt() {
- ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
- actionIdentifiers.setVnfId("fusion-vpp-vnf-001");
- Status status;
- try {
- status = client.runCommand(Action.Unlock, actionIdentifiers, null, "requestId");
- } catch (ApplicationControllerOrchestratorException e) {
- status = new Status();
- status.setCode(e.getAppcCode());
- status.setMessage(e.getMessage());
- }
- assertEquals("Status of run command is correct", status.getCode(), 309);
- }
+ @Ignore
+ @Test
+ public void runCommand_CheckLock_RequestBuilt() {
+ ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
+ actionIdentifiers.setVnfId("fusion-vpp-vnf-001");
+ Status status;
+ try {
+ status = client.runCommand(Action.Unlock, actionIdentifiers, null, "requestId");
+ } catch (ApplicationControllerOrchestratorException e) {
+ status = new Status();
+ status.setCode(e.getAppcCode());
+ status.setMessage(e.getMessage());
+ }
+ assertEquals("Status of run command is correct", status.getCode(), 309);
+ }
- @Ignore
- @Test
- public void test_getLCMPropertiesHelper() {
- Properties properties = client.getLCMProperties("");
- assertEquals(properties.get("topic.write"), "APPC-TEST-AMDOCS1-DEV3");
- assertEquals(properties.get("topic.read.timeout"), "120000");
- assertEquals(properties.get("client.response.timeout"), "120000");
- assertEquals(properties.get("topic.read"), "APPC-TEST-AMDOCS2");
- assertEquals(properties.get("poolMembers"),
- "localhost:3904,localhost:3904,localhost:3904");
- assertEquals(properties.get("client.key"), "iaEMAfjsVsZnraBP");
- assertEquals(properties.get("client.secret"), "wcivUjsjXzmGFBfxMmyJu9dz");
- }
+ @Ignore
+ @Test
+ public void test_getLCMPropertiesHelper() {
+ Properties properties = client.getLCMProperties("");
+ assertEquals(properties.get("topic.write"), "APPC-TEST-AMDOCS1-DEV3");
+ assertEquals(properties.get("topic.read.timeout"), "120000");
+ assertEquals(properties.get("client.response.timeout"), "120000");
+ assertEquals(properties.get("topic.read"), "APPC-TEST-AMDOCS2");
+ assertEquals(properties.get("poolMembers"), "localhost:3904,localhost:3904,localhost:3904");
+ assertEquals(properties.get("client.key"), "iaEMAfjsVsZnraBP");
+ assertEquals(properties.get("client.secret"), "wcivUjsjXzmGFBfxMmyJu9dz");
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerSupportTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerSupportTest.java
index b388d8ba0a..9a7e1716cd 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerSupportTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerSupportTest.java
@@ -21,7 +21,6 @@
package org.onap.so.client.appc;
import static org.assertj.core.api.Assertions.assertThat;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.appc.client.lcm.model.Status;
@@ -31,54 +30,39 @@ import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
@RunWith(JUnitParamsRunner.class)
-public class ApplicationControllerSupportTest{
+public class ApplicationControllerSupportTest {
- public static Object[][] statusesAndCategories() {
- return new Object[][]{
- {100, StatusCategory.NORMAL},
- {200, StatusCategory.ERROR},
- {300, StatusCategory.ERROR},
- {400, StatusCategory.NORMAL},
- {401, StatusCategory.ERROR},
- {500, StatusCategory.NORMAL},
- {501, StatusCategory.ERROR},
- {502, StatusCategory.WARNING},
- {800, StatusCategory.WARNING},
- };
- }
+ public static Object[][] statusesAndCategories() {
+ return new Object[][] {{100, StatusCategory.NORMAL}, {200, StatusCategory.ERROR}, {300, StatusCategory.ERROR},
+ {400, StatusCategory.NORMAL}, {401, StatusCategory.ERROR}, {500, StatusCategory.NORMAL},
+ {501, StatusCategory.ERROR}, {502, StatusCategory.WARNING}, {800, StatusCategory.WARNING},};
+ }
- public static Object[][] statusesAndFinalities() {
- return new Object[][]{
- {100, false},
- {200, true},
- {300, true},
- {400, true},
- {500, false},
- {800, true},
- };
- }
+ public static Object[][] statusesAndFinalities() {
+ return new Object[][] {{100, false}, {200, true}, {300, true}, {400, true}, {500, false}, {800, true},};
+ }
- @Test
- @Parameters(method = "statusesAndCategories")
- public void shouldReturnCategoryForCode(int code, StatusCategory category) throws Exception {
- // when
- StatusCategory detectedCategory = ApplicationControllerSupport.getCategoryOf(createStatus(code));
- // then
- assertThat(detectedCategory).isEqualTo(category);
- }
+ @Test
+ @Parameters(method = "statusesAndCategories")
+ public void shouldReturnCategoryForCode(int code, StatusCategory category) throws Exception {
+ // when
+ StatusCategory detectedCategory = ApplicationControllerSupport.getCategoryOf(createStatus(code));
+ // then
+ assertThat(detectedCategory).isEqualTo(category);
+ }
- @Test
- @Parameters(method = "statusesAndFinalities")
- public void shouldReturnFinalityForCode(int code, boolean expectedFinality) throws Exception {
- // when
- boolean finality = ApplicationControllerSupport.getFinalityOf(createStatus(code));
- // then
- assertThat(finality).isEqualTo(expectedFinality);
- }
+ @Test
+ @Parameters(method = "statusesAndFinalities")
+ public void shouldReturnFinalityForCode(int code, boolean expectedFinality) throws Exception {
+ // when
+ boolean finality = ApplicationControllerSupport.getFinalityOf(createStatus(code));
+ // then
+ assertThat(finality).isEqualTo(expectedFinality);
+ }
- private Status createStatus(int code) {
- Status status = new Status();
- status.setCode(code);
- return status;
- }
-} \ No newline at end of file
+ private Status createStatus(int code) {
+ Status status = new Status();
+ status.setCode(code);
+ return status;
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/avpn/dmaap/beans/AVPNDmaapBeansTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/avpn/dmaap/beans/AVPNDmaapBeansTest.java
index 30ab21b2dd..cb0d31b8ff 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/avpn/dmaap/beans/AVPNDmaapBeansTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/avpn/dmaap/beans/AVPNDmaapBeansTest.java
@@ -21,13 +21,10 @@
package org.onap.so.client.avpn.dmaap.beans;
import static org.junit.Assert.assertNotNull;
-
import java.util.List;
-
import org.junit.Test;
import org.onap.so.BaseTest;
import org.onap.so.openpojo.rules.ToStringTester;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.filters.FilterPackageInfo;
import com.openpojo.reflection.impl.PojoClassFactory;
@@ -39,28 +36,22 @@ import com.openpojo.validation.rule.impl.SetterMustExistRule;
import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
-public class AVPNDmaapBeansTest extends BaseTest{
+public class AVPNDmaapBeansTest extends BaseTest {
- private static final int EXPECTED_CLASS_COUNT = 5;
- private static final String POJO_PACKAGE = "org.onap.so.client.avpn.dmaap.beans";
+ private static final int EXPECTED_CLASS_COUNT = 5;
+ private static final String POJO_PACKAGE = "org.onap.so.client.avpn.dmaap.beans";
- @Test
- public void ensureExpectedPojoCount() {
- List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses( POJO_PACKAGE,
- new FilterPackageInfo());
- Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size());
- }
+ @Test
+ public void ensureExpectedPojoCount() {
+ List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses(POJO_PACKAGE, new FilterPackageInfo());
+ Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size());
+ }
- @Test
- public void testPojoStructureAndBehavior() {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterMustExistRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .with(new ToStringTester())
- .build();
+ @Test
+ public void testPojoStructureAndBehavior() {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule())
+ .with(new SetterTester()).with(new GetterTester()).with(new ToStringTester()).build();
- validator.validate(POJO_PACKAGE, new FilterPackageInfo());
- }
+ validator.validate(POJO_PACKAGE, new FilterPackageInfo());
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtilsTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtilsTest.java
index 161f879716..f558932d33 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtilsTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtilsTest.java
@@ -26,9 +26,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.util.UUID;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.junit.Before;
import org.junit.Test;
@@ -49,8 +47,9 @@ public class AbstractCDSProcessingBBUtilsTest {
ExceptionBuilder exceptionUtil;
@Before
- public void init(){
- String requestObject = "{\"config-assign-request\":{\"resolution-key\":\"resolutionKey\", \"config-assign-properties\":{\"service-instance-id\":\"serviceInstanceId\", \"vnf-id\":\"vnfId\", \"vnf-name\":\"vnfName\", \"service-model-uuid\":\"serviceModelUuid\", \"vnf-customization-uuid\":\"vnfCustomizationUuid\",\"Instance1\":\"Instance1Value\",\"Instance2\":\"Instance2Value\",\"Param3\":\"Param3Value\"}}}";
+ public void init() {
+ String requestObject =
+ "{\"config-assign-request\":{\"resolution-key\":\"resolutionKey\", \"config-assign-properties\":{\"service-instance-id\":\"serviceInstanceId\", \"vnf-id\":\"vnfId\", \"vnf-name\":\"vnfName\", \"service-model-uuid\":\"serviceModelUuid\", \"vnf-customization-uuid\":\"vnfCustomizationUuid\",\"Instance1\":\"Instance1Value\",\"Instance2\":\"Instance2Value\",\"Param3\":\"Param3Value\"}}}";
String blueprintName = "blueprintName";
String blueprintVersion = "blueprintVersion";
String actionName = "actionName";
@@ -76,8 +75,8 @@ public class AbstractCDSProcessingBBUtilsTest {
when(execution.getVariable("executionObject")).thenReturn(abstractCDSPropertiesBean);
abstractCDSProcessingBBUtils.constructExecutionServiceInputObject(execution);
- verify(exceptionUtil, times(0))
- .buildAndThrowWorkflowException(any(DelegateExecution.class), anyInt(), any(Exception.class));
+ verify(exceptionUtil, times(0)).buildAndThrowWorkflowException(any(DelegateExecution.class), anyInt(),
+ any(Exception.class));
}
@Test
@@ -86,8 +85,8 @@ public class AbstractCDSProcessingBBUtilsTest {
DelegateExecution execution = mock(DelegateExecution.class);
when(execution.getVariable("executionServiceInput")).thenReturn(abstractCDSPropertiesBean);
abstractCDSProcessingBBUtils.sendRequestToCDSClient(execution);
- verify(exceptionUtil, times(1))
- .buildAndThrowWorkflowException(any(DelegateExecution.class), anyInt(), any(Exception.class));
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(DelegateExecution.class), anyInt(),
+ any(Exception.class));
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnfTest.java
index c294124e69..3eadd800ad 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnfTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnfTest.java
@@ -2,10 +2,8 @@ package org.onap.so.client.cds.beans;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Test;
public class ConfigAssignPropertiesForPnfTest {
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnfTest.java
index 8b732af6d0..4b91cdf803 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnfTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnfTest.java
@@ -2,10 +2,8 @@ package org.onap.so.client.cds.beans;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Test;
public class ConfigAssignPropertiesForVnfTest {
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnfTest.java
index e4f062ad05..da82721e5e 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnfTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnfTest.java
@@ -2,10 +2,8 @@ package org.onap.so.client.cds.beans;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Test;
public class ConfigAssignRequestPnfTest {
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnfTest.java
index ad3af47453..a73fa6c01e 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnfTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnfTest.java
@@ -2,10 +2,8 @@ package org.onap.so.client.cds.beans;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Test;
public class ConfigAssignRequestVnfTest {
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnfTest.java
index 8e16ce6337..771196d53c 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnfTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnfTest.java
@@ -2,7 +2,6 @@ package org.onap.so.client.cds.beans;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import org.junit.Before;
import org.junit.Test;
@@ -18,7 +17,7 @@ public class ConfigDeployPropertiesForPnfTest {
private static final String TEST_SERVICE_INSTANCE_ID = "service-instance-id";
@Before
- public void setUp(){
+ public void setUp() {
configDeployPropertiesForPnf.setServiceInstanceId(TEST_SERVICE_INSTANCE_ID);
configDeployPropertiesForPnf.setServiceModelUuid(TEST_SERVICE_MODEL_UUID);
configDeployPropertiesForPnf.setPnfCustomizationUuid(TEST_PNF_CUSTOMIZATION_UUID);
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnfTest.java
index 47c59b93e9..6039bd649c 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnfTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnfTest.java
@@ -2,7 +2,6 @@ package org.onap.so.client.cds.beans;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import org.junit.Test;
public class ConfigDeployPropertiesForVnfTest {
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnfTest.java
index df41bf23b8..a977f8dd9e 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnfTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnfTest.java
@@ -2,7 +2,6 @@ package org.onap.so.client.cds.beans;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import org.junit.Test;
public class ConfigDeployRequestPnfTest {
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnfTest.java
index f771710f8b..4b86eeb438 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnfTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnfTest.java
@@ -2,7 +2,6 @@ package org.onap.so.client.cds.beans;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import org.junit.Test;
public class ConfigDeployRequestVnfTest {
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/dmaapproperties/DmaapPropertiesClientTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/dmaapproperties/DmaapPropertiesClientTest.java
index 886025cb51..a6b97d086e 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/dmaapproperties/DmaapPropertiesClientTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/dmaapproperties/DmaapPropertiesClientTest.java
@@ -28,10 +28,8 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.io.File;
import java.io.IOException;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -41,61 +39,63 @@ import org.onap.so.client.avpn.dmaap.beans.AVPNDmaapBean;
import org.onap.so.client.exception.MapperException;
import org.onap.so.client.dmaapproperties.GlobalDmaapPublisher;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class DmaapPropertiesClientTest extends BaseTest{
-
- @Autowired
- private DmaapPropertiesClient dmaapPropertiesClient;
+public class DmaapPropertiesClientTest extends BaseTest {
+
+ @Autowired
+ private DmaapPropertiesClient dmaapPropertiesClient;
+
+
+ private final String file = "src/test/resources/org/onap/so/client/avpn/dmaap/avpnDmaapAsyncRequestStatus.json";
+ private String requestId = "rq1234d1-5a33-55df-13ab-12abad84e331";
+ private String clientSource = "SPP";
+ private String correlator = "myClientId123";
+ private String serviceInstanceId = "bc305d54-75b4-431b-adb2-eb6b9e546014";
+ private String startTime = "2017-11-17T09:30:47Z";
+ private String finishTime = "2017-11-17T09:30:47Z";
+ private String requestScope = "service";
+ private String requestType = "createInstance";
+ private String timestamp = "2017-11-17T09:30:47Z";
+ private String requestState = "COMPLETE";
+ private String statusMessage = "Success";
+ private String percentProgress = "100";
+
+ @Test
+ public void testBuildRequestJson() throws MapperException, IOException {
+ AVPNDmaapBean actualBean = dmaapPropertiesClient.buildRequestJson(requestId, clientSource, correlator,
+ serviceInstanceId, startTime, finishTime, requestScope, requestType, timestamp, requestState,
+ statusMessage, percentProgress, true);
+
+ AVPNDmaapBean expected = new ObjectMapper().readValue(new File(file), AVPNDmaapBean.class);
+
+ assertNotNull(actualBean);
+ assertThat(actualBean, sameBeanAs(expected));
+ }
+
+ @Test
+ public void testDmaapPublishRequest() throws JsonProcessingException, MapperException {
+ DmaapPropertiesClient client = Mockito.spy(DmaapPropertiesClient.class);
+ GlobalDmaapPublisher mockedClientDmaapPublisher = Mockito.mock(GlobalDmaapPublisher.class);
+ AVPNDmaapBean mockedDmaapBean = Mockito.mock(AVPNDmaapBean.class);
+ String request = "test";
+ doReturn(mockedDmaapBean).when(client).buildRequestJson(requestId, clientSource, correlator, serviceInstanceId,
+ startTime, finishTime, requestScope, requestType, timestamp, requestState, statusMessage,
+ percentProgress, false);
- private final String file = "src/test/resources/org/onap/so/client/avpn/dmaap/avpnDmaapAsyncRequestStatus.json";
- private String requestId = "rq1234d1-5a33-55df-13ab-12abad84e331";
- private String clientSource = "SPP";
- private String correlator = "myClientId123";
- private String serviceInstanceId = "bc305d54-75b4-431b-adb2-eb6b9e546014";
- private String startTime = "2017-11-17T09:30:47Z";
- private String finishTime = "2017-11-17T09:30:47Z";
- private String requestScope = "service";
- private String requestType = "createInstance";
- private String timestamp = "2017-11-17T09:30:47Z";
- private String requestState = "COMPLETE";
- private String statusMessage = "Success";
- private String percentProgress = "100";
-
- @Test
- public void testBuildRequestJson() throws MapperException, IOException {
- AVPNDmaapBean actualBean = dmaapPropertiesClient.buildRequestJson(requestId, clientSource, correlator, serviceInstanceId, startTime, finishTime, requestScope,
- requestType, timestamp, requestState, statusMessage, percentProgress, true);
+ AVPNDmaapBean actualDmaapBean =
+ client.buildRequestJson(requestId, clientSource, correlator, serviceInstanceId, startTime, finishTime,
+ requestScope, requestType, timestamp, requestState, statusMessage, percentProgress, false);
+ mockedClientDmaapPublisher.send(request);
- AVPNDmaapBean expected = new ObjectMapper().readValue(new File(file), AVPNDmaapBean.class);
+ doNothing().when(mockedClientDmaapPublisher).send(anyString());
- assertNotNull(actualBean);
- assertThat(actualBean, sameBeanAs(expected));
- }
+ verify(client, times(1)).buildRequestJson(requestId, clientSource, correlator, serviceInstanceId, startTime,
+ finishTime, requestScope, requestType, timestamp, requestState, statusMessage, percentProgress, false);
+ verify(mockedClientDmaapPublisher, times(1)).send(request);
- @Test
- public void testDmaapPublishRequest() throws JsonProcessingException, MapperException {
- DmaapPropertiesClient client = Mockito.spy(DmaapPropertiesClient.class);
- GlobalDmaapPublisher mockedClientDmaapPublisher = Mockito.mock(GlobalDmaapPublisher.class);
- AVPNDmaapBean mockedDmaapBean = Mockito.mock(AVPNDmaapBean.class);
- String request = "test";
-
- doReturn(mockedDmaapBean).when(client).buildRequestJson(requestId, clientSource, correlator, serviceInstanceId, startTime, finishTime, requestScope,
- requestType, timestamp, requestState, statusMessage, percentProgress, false);
-
- AVPNDmaapBean actualDmaapBean = client.buildRequestJson(requestId, clientSource, correlator, serviceInstanceId, startTime, finishTime, requestScope,
- requestType, timestamp, requestState, statusMessage, percentProgress, false);
- mockedClientDmaapPublisher.send(request);
-
- doNothing().when(mockedClientDmaapPublisher).send(anyString());
-
- verify(client, times(1)).buildRequestJson(requestId, clientSource, correlator, serviceInstanceId, startTime,
- finishTime, requestScope, requestType, timestamp, requestState, statusMessage, percentProgress, false);
- verify(mockedClientDmaapPublisher, times(1)).send(request);
-
- assertNotNull(actualDmaapBean);
- }
+ assertNotNull(actualDmaapBean);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/dmaapproperties/GlobalDmaapPublisherTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/dmaapproperties/GlobalDmaapPublisherTest.java
index 088b01873c..b71d5f9113 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/dmaapproperties/GlobalDmaapPublisherTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/dmaapproperties/GlobalDmaapPublisherTest.java
@@ -21,27 +21,28 @@
package org.onap.so.client.dmaapproperties;
import static org.junit.Assert.assertEquals;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.so.BaseTest;
import org.springframework.beans.factory.annotation.Autowired;
-public class GlobalDmaapPublisherTest extends BaseTest{
+public class GlobalDmaapPublisherTest extends BaseTest {
+
+ @BeforeClass
+ public static void setUp() throws Exception {
+ System.setProperty("mso.global.dmaap.host", "http://test:1234");
+ }
+
+ @Autowired
+ private GlobalDmaapPublisher globalDmaapPublisher;
- @BeforeClass
- public static void setUp() throws Exception {
- System.setProperty("mso.global.dmaap.host", "http://test:1234");
- }
-
- @Autowired
- private GlobalDmaapPublisher globalDmaapPublisher;
-
- @Test
- public void testGetters() {
- assertEquals("81B7E3533B91A6706830611FB9A8ECE529BBCCE754B1F1520FA7C8698B42F97235BEFA993A387E664D6352C63A6185D68DA7F0B1D360637CBA102CB166E3E62C11EB1F75386D3506BCECE51E54", globalDmaapPublisher.getAuth());
- assertEquals("07a7159d3bf51a0e53be7a8f89699be7", globalDmaapPublisher.getKey());
- assertEquals("com.att.mso.asyncStatusUpdate", globalDmaapPublisher.getTopic());
- assertEquals("http://test:1234", globalDmaapPublisher.getHost().get());
- }
+ @Test
+ public void testGetters() {
+ assertEquals(
+ "81B7E3533B91A6706830611FB9A8ECE529BBCCE754B1F1520FA7C8698B42F97235BEFA993A387E664D6352C63A6185D68DA7F0B1D360637CBA102CB166E3E62C11EB1F75386D3506BCECE51E54",
+ globalDmaapPublisher.getAuth());
+ assertEquals("07a7159d3bf51a0e53be7a8f89699be7", globalDmaapPublisher.getKey());
+ assertEquals("com.att.mso.asyncStatusUpdate", globalDmaapPublisher.getTopic());
+ assertEquals("http://test:1234", globalDmaapPublisher.getHost().get());
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/exception/ExceptionBuilderTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/exception/ExceptionBuilderTest.java
index 2e25449937..ef066853ca 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/exception/ExceptionBuilderTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/exception/ExceptionBuilderTest.java
@@ -29,49 +29,52 @@ import org.onap.so.BaseTest;
public class ExceptionBuilderTest extends BaseTest {
- private static final String RESOURCE_PATH = "__files/";
- private static final String VALID_ERROR_MESSAGE = "{test error message}";
+ private static final String RESOURCE_PATH = "__files/";
+ private static final String VALID_ERROR_MESSAGE = "{test error message}";
- @Test
- public void buildAndThrowWorkflowExceptionTest() {
- try {
- ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, new NullPointerException(VALID_ERROR_MESSAGE));
- } catch (BpmnError bpmnException){
- assertEquals("MSOWorkflowException", bpmnException.getErrorCode());
- }
- }
+ @Test
+ public void buildAndThrowWorkflowExceptionTest() {
+ try {
+ ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000,
+ new NullPointerException(VALID_ERROR_MESSAGE));
+ } catch (BpmnError bpmnException) {
+ assertEquals("MSOWorkflowException", bpmnException.getErrorCode());
+ }
+ }
- @Test
- public void buildAndThrowWorkflowExceptionInvalidMessageTest() {
- try{
- ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
- String invalidErrorMessage = FileUtil.readResourceFile(RESOURCE_PATH + "invalidErrorMessage.txt");
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, new NullPointerException(invalidErrorMessage));
- } catch (BpmnError bpmnException){
- assertEquals("MSOWorkflowException", bpmnException.getErrorCode());
- }
- }
-
- @Test
- public void buildAndThrowWorkflowExceptionInvalidMessageFlagTest() {
- try{
- ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
- String invalidErrorMessage = FileUtil.readResourceFile(RESOURCE_PATH + "invalidErrorMessageFlag.txt");
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, new NullPointerException(invalidErrorMessage));
- } catch (BpmnError bpmnException){
- assertEquals("MSOWorkflowException", bpmnException.getErrorCode());
- }
- }
-
- @Test
- public void buildAndThrowWorkflowExceptionNullMessageTest() {
- try{
- ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, new NullPointerException());
- } catch (BpmnError bpmnException){
- assertEquals("MSOWorkflowException", bpmnException.getErrorCode());
- }
- }
+ @Test
+ public void buildAndThrowWorkflowExceptionInvalidMessageTest() {
+ try {
+ ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
+ String invalidErrorMessage = FileUtil.readResourceFile(RESOURCE_PATH + "invalidErrorMessage.txt");
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000,
+ new NullPointerException(invalidErrorMessage));
+ } catch (BpmnError bpmnException) {
+ assertEquals("MSOWorkflowException", bpmnException.getErrorCode());
+ }
+ }
+
+ @Test
+ public void buildAndThrowWorkflowExceptionInvalidMessageFlagTest() {
+ try {
+ ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
+ String invalidErrorMessage = FileUtil.readResourceFile(RESOURCE_PATH + "invalidErrorMessageFlag.txt");
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000,
+ new NullPointerException(invalidErrorMessage));
+ } catch (BpmnError bpmnException) {
+ assertEquals("MSOWorkflowException", bpmnException.getErrorCode());
+ }
+ }
+
+ @Test
+ public void buildAndThrowWorkflowExceptionNullMessageTest() {
+ try {
+ ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, new NullPointerException());
+ } catch (BpmnError bpmnException) {
+ assertEquals("MSOWorkflowException", bpmnException.getErrorCode());
+ }
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/AAIPropertiesImplTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/AAIPropertiesImplTest.java
index 2e74d443bd..0d6fede4bf 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/AAIPropertiesImplTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/AAIPropertiesImplTest.java
@@ -21,30 +21,28 @@
package org.onap.so.client.restproperties;
import static org.junit.Assert.assertEquals;
-
import java.net.MalformedURLException;
import java.net.URL;
-
import org.junit.Test;
import org.onap.so.client.aai.AAIVersion;
-public class AAIPropertiesImplTest{
+public class AAIPropertiesImplTest {
+
+ private AAIPropertiesImpl aaiPropertiesImpl = new AAIPropertiesImpl();
+
+ @Test
+ public void getEndpointTest() throws MalformedURLException {
+ assertEquals("aai.endpoint", AAIPropertiesImpl.AAI_ENDPOINT);
+ }
+
+ @Test
+ public void getAuthTest() {
+ String expectedAuth = "aai.auth";
+ assertEquals(expectedAuth, AAIPropertiesImpl.AAI_AUTH);
+ }
- private AAIPropertiesImpl aaiPropertiesImpl = new AAIPropertiesImpl();
-
- @Test
- public void getEndpointTest() throws MalformedURLException {
- assertEquals("aai.endpoint", AAIPropertiesImpl.AAI_ENDPOINT);
- }
-
- @Test
- public void getAuthTest() {
- String expectedAuth = "aai.auth";
- assertEquals(expectedAuth, AAIPropertiesImpl.AAI_AUTH);
- }
-
- @Test
- public void getKeyTest() {
- assertEquals("mso.msoKey", AAIPropertiesImpl.MSO_MSO_KEY);
- }
+ @Test
+ public void getKeyTest() {
+ assertEquals("mso.msoKey", AAIPropertiesImpl.MSO_MSO_KEY);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/PolicyRestPropertiesImplTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/PolicyRestPropertiesImplTest.java
index d1de702a81..528e4f99cb 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/PolicyRestPropertiesImplTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/PolicyRestPropertiesImplTest.java
@@ -21,32 +21,30 @@
package org.onap.so.client.restproperties;
import static org.junit.Assert.assertEquals;
-
import java.net.MalformedURLException;
import java.net.URL;
-
import org.junit.Test;
public class PolicyRestPropertiesImplTest {
-
-
- @Test
- public void getEndpointTest() throws MalformedURLException {
- assertEquals("policy.endpoint", PolicyRestPropertiesImpl.POLICY_ENDPOINT);
- }
-
- @Test
- public void getEnvironmentTest() {
- assertEquals("policy.environment", PolicyRestPropertiesImpl.POLICY_ENVIRONMENT);
- }
-
- @Test
- public void getClientAuthTest() {
- assertEquals("policy.auth", PolicyRestPropertiesImpl.POLICY_AUTH);
- }
-
- @Test
- public void getAuthTest() {
- assertEquals("policy.client.auth", PolicyRestPropertiesImpl.POLICY_CLIENT_AUTH);
- }
+
+
+ @Test
+ public void getEndpointTest() throws MalformedURLException {
+ assertEquals("policy.endpoint", PolicyRestPropertiesImpl.POLICY_ENDPOINT);
+ }
+
+ @Test
+ public void getEnvironmentTest() {
+ assertEquals("policy.environment", PolicyRestPropertiesImpl.POLICY_ENVIRONMENT);
+ }
+
+ @Test
+ public void getClientAuthTest() {
+ assertEquals("policy.auth", PolicyRestPropertiesImpl.POLICY_AUTH);
+ }
+
+ @Test
+ public void getAuthTest() {
+ assertEquals("policy.client.auth", PolicyRestPropertiesImpl.POLICY_CLIENT_AUTH);
+ }
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/ThreadedReadTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/ThreadedReadTest.java
index 08c92d33f0..badf444fc6 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/ThreadedReadTest.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/ThreadedReadTest.java
@@ -22,7 +22,6 @@ package org.onap.so.client.restproperties;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
-
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
@@ -34,71 +33,70 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
-
import org.junit.Test;
import org.onap.so.client.RestPropertiesLoader;
import org.onap.so.client.aai.AAIProperties;
import org.onap.so.BaseTest;
public class ThreadedReadTest {
- @Test
- public void allAtOnce() throws InterruptedException {
- ExecutorService executorService = Executors.newFixedThreadPool(10);
-
- Callable<AAIProperties> callableTask = () -> {
- return RestPropertiesLoader.getInstance().getNewImpl(AAIProperties.class);
- };
- List<Callable<AAIProperties>> callableTasks = new ArrayList<>();
-
- callableTasks.add(callableTask);
- callableTasks.add(callableTask);
- callableTasks.add(callableTask);
- callableTasks.add(callableTask);
- callableTasks.add(callableTask);
-
- List<Future<AAIProperties>> futures = executorService.invokeAll(callableTasks);
-
- Set<AAIProperties> results = new HashSet<>();
- futures.forEach(item -> {
- try {
- results.add(item.get());
- } catch (InterruptedException | ExecutionException e) {
- throw new RuntimeException(e);
- }
- });
-
- assertThat("expect all unique results", results.size(), equalTo(callableTasks.size()));
-
- }
-
- @Test
- public void executeOverTime() {
- ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);
-
- Callable<AAIProperties> callableTask = () -> {
- TimeUnit.MILLISECONDS.sleep(500);
- return RestPropertiesLoader.getInstance().getNewImpl(AAIProperties.class);
- };
- List<Callable<AAIProperties>> callableTasks = new ArrayList<>();
-
- callableTasks.add(callableTask);
- callableTasks.add(callableTask);
- callableTasks.add(callableTask);
- callableTasks.add(callableTask);
- callableTasks.add(callableTask);
-
- Set<AAIProperties> results = new HashSet<>();
- callableTasks.forEach(callable -> {
- try {
- TimeUnit.MILLISECONDS.sleep(300);
- Future<AAIProperties> result = executorService.submit(callable);
- results.add(result.get());
- } catch (InterruptedException | ExecutionException e) {
- throw new RuntimeException(e);
- }
- });
-
- assertThat("expect all unique results", results.size(), equalTo(callableTasks.size()));
- }
-
+ @Test
+ public void allAtOnce() throws InterruptedException {
+ ExecutorService executorService = Executors.newFixedThreadPool(10);
+
+ Callable<AAIProperties> callableTask = () -> {
+ return RestPropertiesLoader.getInstance().getNewImpl(AAIProperties.class);
+ };
+ List<Callable<AAIProperties>> callableTasks = new ArrayList<>();
+
+ callableTasks.add(callableTask);
+ callableTasks.add(callableTask);
+ callableTasks.add(callableTask);
+ callableTasks.add(callableTask);
+ callableTasks.add(callableTask);
+
+ List<Future<AAIProperties>> futures = executorService.invokeAll(callableTasks);
+
+ Set<AAIProperties> results = new HashSet<>();
+ futures.forEach(item -> {
+ try {
+ results.add(item.get());
+ } catch (InterruptedException | ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ assertThat("expect all unique results", results.size(), equalTo(callableTasks.size()));
+
+ }
+
+ @Test
+ public void executeOverTime() {
+ ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);
+
+ Callable<AAIProperties> callableTask = () -> {
+ TimeUnit.MILLISECONDS.sleep(500);
+ return RestPropertiesLoader.getInstance().getNewImpl(AAIProperties.class);
+ };
+ List<Callable<AAIProperties>> callableTasks = new ArrayList<>();
+
+ callableTasks.add(callableTask);
+ callableTasks.add(callableTask);
+ callableTasks.add(callableTask);
+ callableTasks.add(callableTask);
+ callableTasks.add(callableTask);
+
+ Set<AAIProperties> results = new HashSet<>();
+ callableTasks.forEach(callable -> {
+ try {
+ TimeUnit.MILLISECONDS.sleep(300);
+ Future<AAIProperties> result = executorService.submit(callable);
+ results.add(result.get());
+ } catch (InterruptedException | ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ assertThat("expect all unique results", results.size(), equalTo(callableTasks.size()));
+ }
+
}
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/test/categories/SpringAware.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/test/categories/SpringAware.java
index 21035fcd4d..2462e678d9 100644
--- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/test/categories/SpringAware.java
+++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/test/categories/SpringAware.java
@@ -21,5 +21,5 @@
package org.onap.so.test.categories;
public interface SpringAware {
- /* category marker */
+ /* category marker */
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BadInjectedFieldException.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BadInjectedFieldException.java
index 3002d0e70a..7bf1a108a0 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BadInjectedFieldException.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BadInjectedFieldException.java
@@ -22,31 +22,28 @@ package org.onap.so.bpmn.core;
public class BadInjectedFieldException extends RuntimeException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- /**
- * Constructor.
- *
- * @param fieldName the field name
- * @param taskName the task name
- * @param info additional information, e.g. the field value
- */
- public BadInjectedFieldException(String fieldName, String taskName,
- Object info) {
- super(taskName + " injected field '" + fieldName + "' is bad: " + info);
- }
+ /**
+ * Constructor.
+ *
+ * @param fieldName the field name
+ * @param taskName the task name
+ * @param info additional information, e.g. the field value
+ */
+ public BadInjectedFieldException(String fieldName, String taskName, Object info) {
+ super(taskName + " injected field '" + fieldName + "' is bad: " + info);
+ }
- /**
- * Constructor.
- *
- * @param fieldName the field name
- * @param taskName the task name
- * @param info additional information, e.g. the field value
- * @param cause the cause
- */
- public BadInjectedFieldException(String fieldName,
- String taskName, Object info, Throwable cause) {
- super(taskName + " injected field '" + fieldName + "' is bad: "
- + info, cause);
- }
+ /**
+ * Constructor.
+ *
+ * @param fieldName the field name
+ * @param taskName the task name
+ * @param info additional information, e.g. the field value
+ * @param cause the cause
+ */
+ public BadInjectedFieldException(String fieldName, String taskName, Object info, Throwable cause) {
+ super(taskName + " injected field '" + fieldName + "' is bad: " + info, cause);
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java
index 99157410d5..2e66493a25 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java
@@ -31,31 +31,25 @@ import org.onap.so.bpmn.core.internal.VariableNameExtractor;
public class BaseTask implements JavaDelegate {
/**
- * Get the value of a required field. This method throws
- * MissingInjectedFieldException if the expression is null, and
- * BadInjectedFieldException if the expression evaluates to a null
- * value.
+ * Get the value of a required field. This method throws MissingInjectedFieldException if the expression is null,
+ * and BadInjectedFieldException if the expression evaluates to a null value.
*
* @param expression the expression
* @param execution the execution
* @param fieldName the field name (for logging and exceptions)
* @return the field value
*/
- protected Object getField(Expression expression,
- DelegateExecution execution, String fieldName) {
+ protected Object getField(Expression expression, DelegateExecution execution, String fieldName) {
return getFieldImpl(expression, execution, fieldName, false);
}
/**
- * Gets the value of an optional field. There are three conditions
- * in which this method returns null:
+ * Gets the value of an optional field. There are three conditions in which this method returns null:
* <p>
* <ol>
- * <li> The expression itself is null (i.e. the field is missing
- * altogether.</li>
+ * <li>The expression itself is null (i.e. the field is missing altogether.</li>
* <li>The expression evaluates to a null value.</li>
- * <li>The expression references a single variable which has not
- * been set.</li>
+ * <li>The expression references a single variable which has not been set.</li>
* </ol>
* <p>
* Examples:<br>
@@ -68,77 +62,65 @@ public class BaseTask implements JavaDelegate {
* @param fieldName the field name (for logging and exceptions)
* @return the field value, possibly null
*/
- protected Object getOptionalField(Expression expression,
- DelegateExecution execution, String fieldName) {
+ protected Object getOptionalField(Expression expression, DelegateExecution execution, String fieldName) {
return getFieldImpl(expression, execution, fieldName, true);
}
/**
- * Get the value of a required output variable field. This method
- * throws MissingInjectedFieldException if the expression is null, and
- * BadInjectedFieldException if the expression produces a null or
- * illegal variable name. Legal variable names contain only letters,
- * numbers, and the underscore character ('_').
+ * Get the value of a required output variable field. This method throws MissingInjectedFieldException if the
+ * expression is null, and BadInjectedFieldException if the expression produces a null or illegal variable name.
+ * Legal variable names contain only letters, numbers, and the underscore character ('_').
*
* @param expression the expression
* @param execution the execution
* @param fieldName the field name (for logging and exceptions)
* @return the output variable name
*/
- protected String getOutputField(Expression expression,
- DelegateExecution execution, String fieldName) {
+ protected String getOutputField(Expression expression, DelegateExecution execution, String fieldName) {
Object o = getFieldImpl(expression, execution, fieldName, false);
if (o instanceof String) {
String variable = (String) o;
if (!isLegalVariable(variable)) {
- throw new BadInjectedFieldException(
- fieldName, getTaskName(), "'" + variable
- + "' is not a legal variable name");
+ throw new BadInjectedFieldException(fieldName, getTaskName(),
+ "'" + variable + "' is not a legal variable name");
}
return variable;
} else {
- throw new BadInjectedFieldException(
- fieldName, getTaskName(), "expected a variable name string"
- + ", got object of type " + o.getClass().getName());
+ throw new BadInjectedFieldException(fieldName, getTaskName(),
+ "expected a variable name string" + ", got object of type " + o.getClass().getName());
}
}
/**
- * Get the value of an optional output variable field. This method
- * throws BadInjectedFieldException if the expression produces an illegal
- * variable name. Legal variable names contain only letters, numbers,
- * and the underscore character ('_').
+ * Get the value of an optional output variable field. This method throws BadInjectedFieldException if the
+ * expression produces an illegal variable name. Legal variable names contain only letters, numbers, and the
+ * underscore character ('_').
*
* @param expression the expression
* @param execution the execution
* @param fieldName the field name (for logging and exceptions)
* @return the output variable name, possibly null
*/
- protected String getOptionalOutputField(Expression expression,
- DelegateExecution execution, String fieldName) {
+ protected String getOptionalOutputField(Expression expression, DelegateExecution execution, String fieldName) {
Object o = getFieldImpl(expression, execution, fieldName, true);
if (o instanceof String) {
String variable = (String) o;
if (!isLegalVariable(variable)) {
- throw new BadInjectedFieldException(
- fieldName, getTaskName(), "'" + variable
- + "' is not a legal variable name");
+ throw new BadInjectedFieldException(fieldName, getTaskName(),
+ "'" + variable + "' is not a legal variable name");
}
return variable;
} else if (o == null) {
return null;
} else {
- throw new BadInjectedFieldException(
- fieldName, getTaskName(), "expected a variable name string"
- + ", got object of type " + o.getClass().getName());
+ throw new BadInjectedFieldException(fieldName, getTaskName(),
+ "expected a variable name string" + ", got object of type " + o.getClass().getName());
}
}
/**
- * Get the value of a required string field. This method throws
- * MissingInjectedFieldException if the expression is null, and
- * BadInjectedFieldException if the expression evaluates to a null
- * value.
+ * Get the value of a required string field. This method throws MissingInjectedFieldException if the expression is
+ * null, and BadInjectedFieldException if the expression evaluates to a null value.
* <p>
* Note: the result is coerced to a string value, if necessary.
*
@@ -147,28 +129,23 @@ public class BaseTask implements JavaDelegate {
* @param fieldName the field name (for logging and exceptions)
* @return the field value
*/
- protected String getStringField(Expression expression,
- DelegateExecution execution, String fieldName) {
+ protected String getStringField(Expression expression, DelegateExecution execution, String fieldName) {
Object o = getFieldImpl(expression, execution, fieldName, false);
if (o instanceof String) {
return (String) o;
} else {
- throw new BadInjectedFieldException(
- fieldName, getTaskName(), "cannot convert '" + o.toString()
- + "' to Integer");
+ throw new BadInjectedFieldException(fieldName, getTaskName(),
+ "cannot convert '" + o.toString() + "' to Integer");
}
}
/**
- * Gets the value of an optional string field. There are three conditions
- * in which this method returns null:
+ * Gets the value of an optional string field. There are three conditions in which this method returns null:
* <p>
* <ol>
- * <li> The expression itself is null (i.e. the field is missing
- * altogether.</li>
+ * <li>The expression itself is null (i.e. the field is missing altogether.</li>
* <li>The expression evaluates to a null value.</li>
- * <li>The expression references a single variable which has not
- * been set.</li>
+ * <li>The expression references a single variable which has not been set.</li>
* </ol>
* <p>
* Examples:<br>
@@ -183,8 +160,7 @@ public class BaseTask implements JavaDelegate {
* @param fieldName the field name (for logging and exceptions)
* @return the field value, possibly null
*/
- protected String getOptionalStringField(Expression expression,
- DelegateExecution execution, String fieldName) {
+ protected String getOptionalStringField(Expression expression, DelegateExecution execution, String fieldName) {
Object o = getFieldImpl(expression, execution, fieldName, true);
if (o instanceof String) {
return (String) o;
@@ -196,18 +172,16 @@ public class BaseTask implements JavaDelegate {
}
/**
- * Get the value of a required integer field. This method throws
- * MissingInjectedFieldException if the expression is null, and
- * BadInjectedFieldException if the expression evaluates to a null
- * value or a value that cannot be coerced to an integer.
+ * Get the value of a required integer field. This method throws MissingInjectedFieldException if the expression is
+ * null, and BadInjectedFieldException if the expression evaluates to a null value or a value that cannot be coerced
+ * to an integer.
*
* @param expression the expression
* @param execution the execution
* @param fieldName the field name (for logging and exceptions)
* @return the field value
*/
- protected Integer getIntegerField(Expression expression,
- DelegateExecution execution, String fieldName) {
+ protected Integer getIntegerField(Expression expression, DelegateExecution execution, String fieldName) {
Object o = getFieldImpl(expression, execution, fieldName, false);
if (o instanceof Integer) {
return (Integer) o;
@@ -215,23 +189,19 @@ public class BaseTask implements JavaDelegate {
try {
return Integer.parseInt(o.toString());
} catch (NumberFormatException e) {
- throw new BadInjectedFieldException(
- fieldName, getTaskName(), "cannot convert '" + o.toString()
- + "' to Integer");
+ throw new BadInjectedFieldException(fieldName, getTaskName(),
+ "cannot convert '" + o.toString() + "' to Integer");
}
}
}
/**
- * Gets the value of an optional integer field. There are three conditions
- * in which this method returns null:
+ * Gets the value of an optional integer field. There are three conditions in which this method returns null:
* <p>
* <ol>
- * <li> The expression itself is null (i.e. the field is missing
- * altogether.</li>
+ * <li>The expression itself is null (i.e. the field is missing altogether.</li>
* <li>The expression evaluates to a null value.</li>
- * <li>The expression references a single variable which has not
- * been set.</li>
+ * <li>The expression references a single variable which has not been set.</li>
* </ol>
* <p>
* Examples:<br>
@@ -239,17 +209,15 @@ public class BaseTask implements JavaDelegate {
* Expression ${x} when x is unset: return null<br>
* Expression ${x+y} when x and/or y are unset: exception<br>
* <p>
- * Note: the result is coerced to an integer value, if necessary. This
- * method throws BadInjectedFieldException if the result cannot be coerced
- * to an integer.
+ * Note: the result is coerced to an integer value, if necessary. This method throws BadInjectedFieldException if
+ * the result cannot be coerced to an integer.
*
* @param expression the expression
* @param execution the execution
* @param fieldName the field name (for logging and exceptions)
* @return the field value, possibly null
*/
- protected Integer getOptionalIntegerField(Expression expression,
- DelegateExecution execution, String fieldName) {
+ protected Integer getOptionalIntegerField(Expression expression, DelegateExecution execution, String fieldName) {
Object o = getFieldImpl(expression, execution, fieldName, true);
if (o instanceof Integer) {
return (Integer) o;
@@ -259,23 +227,19 @@ public class BaseTask implements JavaDelegate {
try {
return Integer.parseInt(o.toString());
} catch (NumberFormatException e) {
- throw new BadInjectedFieldException(
- fieldName, getTaskName(), "cannot convert '" + o.toString()
- + "' to Integer");
+ throw new BadInjectedFieldException(fieldName, getTaskName(),
+ "cannot convert '" + o.toString() + "' to Integer");
}
}
}
/**
- * Gets the value of an optional long field. There are three conditions
- * in which this method returns null:
+ * Gets the value of an optional long field. There are three conditions in which this method returns null:
* <p>
* <ol>
- * <li> The expression itself is null (i.e. the field is missing
- * altogether.</li>
+ * <li>The expression itself is null (i.e. the field is missing altogether.</li>
* <li>The expression evaluates to a null value.</li>
- * <li>The expression references a single variable which has not
- * been set.</li>
+ * <li>The expression references a single variable which has not been set.</li>
* </ol>
* <p>
* Examples:<br>
@@ -283,17 +247,15 @@ public class BaseTask implements JavaDelegate {
* Expression ${x} when x is unset: return null<br>
* Expression ${x+y} when x and/or y are unset: exception<br>
* <p>
- * Note: the result is coerced to a long value, if necessary. This
- * method throws BadInjectedFieldException if the result cannot be coerced
- * to a long.
+ * Note: the result is coerced to a long value, if necessary. This method throws BadInjectedFieldException if the
+ * result cannot be coerced to a long.
*
* @param expression the expression
* @param execution the execution
* @param fieldName the field name (for logging and exceptions)
* @return the field value, possibly null
*/
- protected Long getOptionalLongField(Expression expression,
- DelegateExecution execution, String fieldName) {
+ protected Long getOptionalLongField(Expression expression, DelegateExecution execution, String fieldName) {
Object o = getFieldImpl(expression, execution, fieldName, true);
if (o instanceof Long) {
return (Long) o;
@@ -303,26 +265,23 @@ public class BaseTask implements JavaDelegate {
try {
return Long.parseLong(o.toString());
} catch (NumberFormatException e) {
- throw new BadInjectedFieldException(
- fieldName, getTaskName(), "cannot convert '" + o.toString()
- + "' to Long");
+ throw new BadInjectedFieldException(fieldName, getTaskName(),
+ "cannot convert '" + o.toString() + "' to Long");
}
}
}
/**
- * Get the value of a required long field. This method throws
- * MissingInjectedFieldException if the expression is null, and
- * BadInjectedFieldException if the expression evaluates to a null
- * value or a value that cannot be coerced to a long.
+ * Get the value of a required long field. This method throws MissingInjectedFieldException if the expression is
+ * null, and BadInjectedFieldException if the expression evaluates to a null value or a value that cannot be coerced
+ * to a long.
*
* @param expression the expression
* @param execution the execution
* @param fieldName the field name (for logging and exceptions)
* @return the field value
*/
- protected Long getLongField(Expression expression,
- DelegateExecution execution, String fieldName) {
+ protected Long getLongField(Expression expression, DelegateExecution execution, String fieldName) {
Object o = getFieldImpl(expression, execution, fieldName, false);
if (o instanceof Long) {
return (Long) o;
@@ -330,9 +289,8 @@ public class BaseTask implements JavaDelegate {
try {
return Long.parseLong(o.toString());
} catch (NumberFormatException e) {
- throw new BadInjectedFieldException(
- fieldName, getTaskName(), "cannot convert '" + o.toString()
- + "' to Long");
+ throw new BadInjectedFieldException(fieldName, getTaskName(),
+ "cannot convert '" + o.toString() + "' to Long");
}
}
}
@@ -346,12 +304,11 @@ public class BaseTask implements JavaDelegate {
* @param optional true if the field is optional
* @return the field value, possibly null
*/
- private Object getFieldImpl(Expression expression,
- DelegateExecution execution, String fieldName, boolean optional) {
+ private Object getFieldImpl(Expression expression, DelegateExecution execution, String fieldName,
+ boolean optional) {
if (expression == null) {
if (!optional) {
- throw new MissingInjectedFieldException(
- fieldName, getTaskName());
+ throw new MissingInjectedFieldException(fieldName, getTaskName());
}
return null;
}
@@ -362,8 +319,7 @@ public class BaseTask implements JavaDelegate {
value = expression.getValue(execution);
} catch (Exception e) {
if (!optional) {
- throw new BadInjectedFieldException(
- fieldName, getTaskName(), e.getClass().getSimpleName(), e);
+ throw new BadInjectedFieldException(fieldName, getTaskName(), e.getClass().getSimpleName(), e);
}
// At this point, we have an exception that occurred while
@@ -373,7 +329,7 @@ public class BaseTask implements JavaDelegate {
// ${x}. The normal activiti behavior is to throw an exception,
// but we don't like that, so we have the following workaround,
// which parses the expression text to see if it is a "simple"
- // variable reference, and if so, returns null. If the
+ // variable reference, and if so, returns null. If the
// expression is anything other than a single variable
// reference, then an exception is thrown, as it would have
// been without this workaround.
@@ -382,15 +338,13 @@ public class BaseTask implements JavaDelegate {
String s = expression.getExpressionText();
new VariableNameExtractor(s).extract().ifPresent(name -> {
if (execution.hasVariable(name)) {
- throw new BadInjectedFieldException(
- fieldName, getTaskName(), e.getClass().getSimpleName(), e);
+ throw new BadInjectedFieldException(fieldName, getTaskName(), e.getClass().getSimpleName(), e);
}
});
}
if (value == null && !optional) {
- throw new BadInjectedFieldException(
- fieldName, getTaskName(), "required field has null value");
+ throw new BadInjectedFieldException(fieldName, getTaskName(), "required field has null value");
}
return value;
@@ -449,6 +403,5 @@ public class BaseTask implements JavaDelegate {
}
@Override
- public void execute(DelegateExecution execution) throws Exception {
- }
+ public void execute(DelegateExecution execution) throws Exception {}
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/MissingInjectedFieldException.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/MissingInjectedFieldException.java
index 17a78d37b8..f0b56364af 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/MissingInjectedFieldException.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/MissingInjectedFieldException.java
@@ -25,15 +25,15 @@ package org.onap.so.bpmn.core;
*/
public class MissingInjectedFieldException extends BadInjectedFieldException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- /**
- * Constructor.
- *
- * @param fieldName the field name
- * @param taskName the task name
- */
- public MissingInjectedFieldException(String fieldName, String taskName) {
- super(fieldName, taskName, "missing required field");
- }
+ /**
+ * Constructor.
+ *
+ * @param fieldName the field name
+ * @param taskName the task name
+ */
+ public MissingInjectedFieldException(String fieldName, String taskName) {
+ super(fieldName, taskName, "missing required field");
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java
index fb794e251d..a3f5253765 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java
@@ -27,11 +27,11 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Used in the output variable mapping configuration of subflow call activity
- * tasks to normalize subflow responses. The output mapping is normally set up
- * as follows. Note that the order of these mappings is important!
+ * Used in the output variable mapping configuration of subflow call activity tasks to normalize subflow responses. The
+ * output mapping is normally set up as follows. Note that the order of these mappings is important!
* <p>
* OUTPUT MAPPING
+ *
* <pre>
* SOURCE EXPRESSION TARGET
* ${ResponseBuilder.buildWorkflowException(execution)} WorkflowException
@@ -39,254 +39,254 @@ import org.slf4j.LoggerFactory;
* </pre>
*/
public class ResponseBuilder implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
- private static final Logger logger = LoggerFactory.getLogger(ResponseBuilder.class);
-
- /**
- * Creates a WorkflowException using data from the execution variables.
- * If the variables do not indicate that there was an error, null
- * is returned.
- * @param execution the execution
- */
- public WorkflowException buildWorkflowException(DelegateExecution execution) {
-
- String method = getClass().getSimpleName() + ".buildWorkflowException(" +
- "execution=" + execution.getId() +
- ")";
-
- logger.debug("Entered " + method);
-
- String prefix = (String) execution.getVariable("prefix");
- String processKey = getProcessKey(execution);
-
- logger.debug("processKey=" + processKey);
-
- // See if there"s already a WorkflowException object in the execution.
- WorkflowException theException = (WorkflowException) execution.getVariable("WorkflowException");
-
- if (theException != null) {
- logger.debug("Exited " + method + " - propagated " + theException);
- return theException;
- }
-
- // Look in the legacy variables: ErrorResponse and ResponseCode
-
- String errorResponse = trimString(execution.getVariable(prefix + "ErrorResponse"), null);
- String responseCode = trimString(execution.getVariable(prefix + "ResponseCode"), null);
- logger.debug("errorResponse=" + errorResponse);
- logger.debug("responseCode=" + responseCode);
- if (errorResponse != null || !isOneOf(responseCode, null, "0", "200", "201", "202", "204")) {
- // This is an error condition. We need to return a WorkflowExcpetion
-
- if (errorResponse == null) {
- // No errorResponse string. See if there"s something in the Response variable
- String response = trimString(execution.getVariable(processKey + "Response"), null);
- if (response == null) {
- errorResponse = "Received response code " + responseCode + " from " + processKey;
- } else {
- errorResponse = response;
- }
- }
-
- // Some subflows may try to return a WorkflowException as XML in the
- // errorResponse. If provided, use the errorCode and errorMessage
- // from the XML
-
- String maybeXML = removeXMLNamespaces(errorResponse);
-
- String xmlErrorMessage = trimString(getXMLTextElement(maybeXML, "ErrorMessage"), null);
- String xmlErrorCode = trimString(getXMLTextElement(maybeXML, "ErrorCode"), null);
-
- if (xmlErrorMessage != null || xmlErrorCode != null) {
- logger.debug("xmlErrorMessage=" + xmlErrorMessage);
- logger.debug("xmlErrorCode=" + xmlErrorCode);
-
- if (xmlErrorMessage == null) {
- errorResponse = "Received error code " + xmlErrorCode + " from " + processKey;
- } else {
- errorResponse = xmlErrorMessage;
- }
-
- if (xmlErrorCode != null) {
- responseCode = xmlErrorCode;
- }
- }
-
- // Convert the responseCode to an integer
-
- int intResponseCode;
-
- try {
- intResponseCode = Integer.valueOf(responseCode);
- } catch (NumberFormatException e) {
- // Internal Error
- intResponseCode = 2000;
- }
-
- // Convert 3-digit HTTP response codes (we should not be using them here)
- // to appropriate 4-digit response codes
-
- if (intResponseCode < 1000) {
- if (intResponseCode >= 400 && intResponseCode <= 499) {
- // Invalid Message
- intResponseCode = 1002;
- } else {
- // Internal Error
- intResponseCode = 2000;
- }
- }
-
- // Create a new WorkflowException object
-
- theException = new WorkflowException(processKey, intResponseCode, errorResponse);
- execution.setVariable("WorkflowException", theException);
- logger.debug("Exited " + method + " - created " + theException);
- return theException;
- }
-
- logger.debug("Exited " + method + " - no WorkflowException");
- return null;
- }
-
- /**
- * Returns the "Response" variable, unless the execution variables
- * indicate there was an error. In that case, null is returned.
- * @param execution the execution
- */
- public Object buildWorkflowResponse(DelegateExecution execution) {
-
- String method = getClass().getSimpleName() + ".buildWorkflowResponse(" +
- "execution=" + execution.getId() +
- ")";
- logger.debug("Entered " + method);
-
- String prefix = (String) execution.getVariable("prefix");
- String processKey = getProcessKey(execution);
-
- Object theResponse = null;
-
- WorkflowException theException = (WorkflowException) execution.getVariable("WorkflowException");
- String errorResponse = trimString(execution.getVariable(prefix + "ErrorResponse"), null);
- String responseCode = trimString(execution.getVariable(prefix + "ResponseCode"), null);
-
- if (theException == null && errorResponse == null &&
- isOneOf(responseCode, null, "0", "200", "201", "202", "204")) {
-
- theResponse = execution.getVariable("WorkflowResponse");
-
- if (theResponse == null) {
- theResponse = execution.getVariable(processKey + "Response");
- }
- }
-
- logger.debug("Exited " + method);
- return theResponse;
- }
-
- /**
- * Checks if the specified item is one of the specified values.
- * @param item the item
- * @param values the list of values
- * @return true if the item is in the list of values
- */
- private boolean isOneOf(Object item, Object ... values) {
- if (values == null) {
- return item == null;
- }
-
- for (Object value : values) {
- if (value == null) {
- if (item == null) {
- return true;
- }
- } else {
- if (value.equals(item)) {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * Creates a string value of the specified object, trimming whitespace in
- * the process. If the result is null or empty, the specified empty string
- * value is returned. Otherwise the trimmed value is returned. This method
- * helps ensure consistent treatment of empty and null strings.
- * @param object the object to convert (possibly null)
- * @param emptyStringValue the desired value for empty results
- */
- private String trimString(Object object, String emptyStringValue) {
- if (object == null) {
- return emptyStringValue;
- }
-
- String s = String.valueOf(object).trim();
- return s.equals("") ? emptyStringValue : s;
- }
-
- /**
- * Returns the process definition key (i.e. the process name) from the
- * execution.
- * @param execution the execution
- */
- private String getProcessKey(DelegateExecution execution) {
- Object testKey = execution.getVariable("testProcessKey");
-
- if (testKey instanceof String) {
- return (String) testKey;
- }
-
- return execution.getProcessEngineServices().getRepositoryService()
- .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
- }
-
- /**
- * Removes namespace definitions and prefixes from XML, if any.
- */
- private String removeXMLNamespaces(String xml) {
- // remove xmlns declaration
- xml = xml.replaceAll("xmlns.*?(\"|\').*?(\"|\')", "");
-
- // remove opening tag prefix
- xml = xml.replaceAll("(<)(\\w+:)(.*?>)", "$1$3");
-
- // remove closing tags prefix
- xml = xml.replaceAll("(</)(\\w+:)(.*?>)", "$1$3");
-
- // remove extra spaces left when xmlns declarations are removed
- xml = xml.replaceAll("\\s+>", ">");
-
- return xml;
- }
-
- /**
- * Extracts text from an XML element. This method is not namespace aware
- * (namespaces are ignored). The first matching element is selected.
- * @param xml the XML document or fragment
- * @param tag the desired element, e.g. "<name>"
- * @return the element text, or null if the element was not found
- */
- private String getXMLTextElement(String xml, String tag) {
- xml = removeXMLNamespaces(xml);
-
- if (!tag.startsWith("<")) {
- tag = "<" + tag + ">";
- }
-
- int start = xml.indexOf(tag);
-
- if (start == -1) {
- return null;
- }
-
- int end = xml.indexOf('<', start + tag.length());
-
- if (end == -1) {
- return null;
- }
-
- return xml.substring(start + tag.length(), end);
- }
+ private static final long serialVersionUID = 1L;
+ private static final Logger logger = LoggerFactory.getLogger(ResponseBuilder.class);
+
+ /**
+ * Creates a WorkflowException using data from the execution variables. If the variables do not indicate that there
+ * was an error, null is returned.
+ *
+ * @param execution the execution
+ */
+ public WorkflowException buildWorkflowException(DelegateExecution execution) {
+
+ String method =
+ getClass().getSimpleName() + ".buildWorkflowException(" + "execution=" + execution.getId() + ")";
+
+ logger.debug("Entered " + method);
+
+ String prefix = (String) execution.getVariable("prefix");
+ String processKey = getProcessKey(execution);
+
+ logger.debug("processKey=" + processKey);
+
+ // See if there"s already a WorkflowException object in the execution.
+ WorkflowException theException = (WorkflowException) execution.getVariable("WorkflowException");
+
+ if (theException != null) {
+ logger.debug("Exited " + method + " - propagated " + theException);
+ return theException;
+ }
+
+ // Look in the legacy variables: ErrorResponse and ResponseCode
+
+ String errorResponse = trimString(execution.getVariable(prefix + "ErrorResponse"), null);
+ String responseCode = trimString(execution.getVariable(prefix + "ResponseCode"), null);
+ logger.debug("errorResponse=" + errorResponse);
+ logger.debug("responseCode=" + responseCode);
+ if (errorResponse != null || !isOneOf(responseCode, null, "0", "200", "201", "202", "204")) {
+ // This is an error condition. We need to return a WorkflowExcpetion
+
+ if (errorResponse == null) {
+ // No errorResponse string. See if there"s something in the Response variable
+ String response = trimString(execution.getVariable(processKey + "Response"), null);
+ if (response == null) {
+ errorResponse = "Received response code " + responseCode + " from " + processKey;
+ } else {
+ errorResponse = response;
+ }
+ }
+
+ // Some subflows may try to return a WorkflowException as XML in the
+ // errorResponse. If provided, use the errorCode and errorMessage
+ // from the XML
+
+ String maybeXML = removeXMLNamespaces(errorResponse);
+
+ String xmlErrorMessage = trimString(getXMLTextElement(maybeXML, "ErrorMessage"), null);
+ String xmlErrorCode = trimString(getXMLTextElement(maybeXML, "ErrorCode"), null);
+
+ if (xmlErrorMessage != null || xmlErrorCode != null) {
+ logger.debug("xmlErrorMessage=" + xmlErrorMessage);
+ logger.debug("xmlErrorCode=" + xmlErrorCode);
+
+ if (xmlErrorMessage == null) {
+ errorResponse = "Received error code " + xmlErrorCode + " from " + processKey;
+ } else {
+ errorResponse = xmlErrorMessage;
+ }
+
+ if (xmlErrorCode != null) {
+ responseCode = xmlErrorCode;
+ }
+ }
+
+ // Convert the responseCode to an integer
+
+ int intResponseCode;
+
+ try {
+ intResponseCode = Integer.valueOf(responseCode);
+ } catch (NumberFormatException e) {
+ // Internal Error
+ intResponseCode = 2000;
+ }
+
+ // Convert 3-digit HTTP response codes (we should not be using them here)
+ // to appropriate 4-digit response codes
+
+ if (intResponseCode < 1000) {
+ if (intResponseCode >= 400 && intResponseCode <= 499) {
+ // Invalid Message
+ intResponseCode = 1002;
+ } else {
+ // Internal Error
+ intResponseCode = 2000;
+ }
+ }
+
+ // Create a new WorkflowException object
+
+ theException = new WorkflowException(processKey, intResponseCode, errorResponse);
+ execution.setVariable("WorkflowException", theException);
+ logger.debug("Exited " + method + " - created " + theException);
+ return theException;
+ }
+
+ logger.debug("Exited " + method + " - no WorkflowException");
+ return null;
+ }
+
+ /**
+ * Returns the "Response" variable, unless the execution variables indicate there was an error. In that case, null
+ * is returned.
+ *
+ * @param execution the execution
+ */
+ public Object buildWorkflowResponse(DelegateExecution execution) {
+
+ String method = getClass().getSimpleName() + ".buildWorkflowResponse(" + "execution=" + execution.getId() + ")";
+ logger.debug("Entered " + method);
+
+ String prefix = (String) execution.getVariable("prefix");
+ String processKey = getProcessKey(execution);
+
+ Object theResponse = null;
+
+ WorkflowException theException = (WorkflowException) execution.getVariable("WorkflowException");
+ String errorResponse = trimString(execution.getVariable(prefix + "ErrorResponse"), null);
+ String responseCode = trimString(execution.getVariable(prefix + "ResponseCode"), null);
+
+ if (theException == null && errorResponse == null
+ && isOneOf(responseCode, null, "0", "200", "201", "202", "204")) {
+
+ theResponse = execution.getVariable("WorkflowResponse");
+
+ if (theResponse == null) {
+ theResponse = execution.getVariable(processKey + "Response");
+ }
+ }
+
+ logger.debug("Exited " + method);
+ return theResponse;
+ }
+
+ /**
+ * Checks if the specified item is one of the specified values.
+ *
+ * @param item the item
+ * @param values the list of values
+ * @return true if the item is in the list of values
+ */
+ private boolean isOneOf(Object item, Object... values) {
+ if (values == null) {
+ return item == null;
+ }
+
+ for (Object value : values) {
+ if (value == null) {
+ if (item == null) {
+ return true;
+ }
+ } else {
+ if (value.equals(item)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Creates a string value of the specified object, trimming whitespace in the process. If the result is null or
+ * empty, the specified empty string value is returned. Otherwise the trimmed value is returned. This method helps
+ * ensure consistent treatment of empty and null strings.
+ *
+ * @param object the object to convert (possibly null)
+ * @param emptyStringValue the desired value for empty results
+ */
+ private String trimString(Object object, String emptyStringValue) {
+ if (object == null) {
+ return emptyStringValue;
+ }
+
+ String s = String.valueOf(object).trim();
+ return s.equals("") ? emptyStringValue : s;
+ }
+
+ /**
+ * Returns the process definition key (i.e. the process name) from the execution.
+ *
+ * @param execution the execution
+ */
+ private String getProcessKey(DelegateExecution execution) {
+ Object testKey = execution.getVariable("testProcessKey");
+
+ if (testKey instanceof String) {
+ return (String) testKey;
+ }
+
+ return execution.getProcessEngineServices().getRepositoryService()
+ .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
+ }
+
+ /**
+ * Removes namespace definitions and prefixes from XML, if any.
+ */
+ private String removeXMLNamespaces(String xml) {
+ // remove xmlns declaration
+ xml = xml.replaceAll("xmlns.*?(\"|\').*?(\"|\')", "");
+
+ // remove opening tag prefix
+ xml = xml.replaceAll("(<)(\\w+:)(.*?>)", "$1$3");
+
+ // remove closing tags prefix
+ xml = xml.replaceAll("(</)(\\w+:)(.*?>)", "$1$3");
+
+ // remove extra spaces left when xmlns declarations are removed
+ xml = xml.replaceAll("\\s+>", ">");
+
+ return xml;
+ }
+
+ /**
+ * Extracts text from an XML element. This method is not namespace aware (namespaces are ignored). The first
+ * matching element is selected.
+ *
+ * @param xml the XML document or fragment
+ * @param tag the desired element, e.g. "<name>"
+ * @return the element text, or null if the element was not found
+ */
+ private String getXMLTextElement(String xml, String tag) {
+ xml = removeXMLNamespaces(xml);
+
+ if (!tag.startsWith("<")) {
+ tag = "<" + tag + ">";
+ }
+
+ int start = xml.indexOf(tag);
+
+ if (start == -1) {
+ return null;
+ }
+
+ int end = xml.indexOf('<', start + tag.length());
+
+ if (end == -1) {
+ return null;
+ }
+
+ return xml.substring(start + tag.length(), end);
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/RollbackData.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/RollbackData.java
index 52207f2156..68ce85f7df 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/RollbackData.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/RollbackData.java
@@ -24,13 +24,11 @@ import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/**
- * An object that stores data for rollbacks. Data is organized by type. A type is simply a string
- * identifier. Multiple types of data may be stored in the same object for separate rollback
- * operations.
+ * An object that stores data for rollbacks. Data is organized by type. A type is simply a string identifier. Multiple
+ * types of data may be stored in the same object for separate rollback operations.
*/
public class RollbackData implements Serializable {
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/UrnPropertiesReader.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/UrnPropertiesReader.java
index 0c88e3ed88..78a73c5a10 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/UrnPropertiesReader.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/UrnPropertiesReader.java
@@ -23,7 +23,6 @@
package org.onap.so.bpmn.core;
import java.util.Optional;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -43,31 +42,30 @@ public class UrnPropertiesReader {
private static Environment environment;
@Autowired
- public void setEnvironment(Environment environment) {
- this.environment = environment;
- }
- /**
- * Return the URN property value
- * if property is present in the execution object, return the same
- * else search in the environment object. If found, add it to the execution object and return the value
- * otherwise return null
+ public void setEnvironment(Environment environment) {
+ this.environment = environment;
+ }
+
+ /**
+ * Return the URN property value if property is present in the execution object, return the same else search in the
+ * environment object. If found, add it to the execution object and return the value otherwise return null
*
* @param variableName URN property name
- * @param execution The flow's execution instance.
+ * @param execution The flow's execution instance.
* @return URN property value
*/
public static String getVariable(String variableName, DelegateExecution execution) {
Object value = execution.getVariable(variableName);
if (value != null) {
logger.trace("Retrieved value for the URN variable, {}, from the execution object: {}", variableName,
- String.valueOf(value));
+ String.valueOf(value));
return String.valueOf(value);
}
String variableValue = null;
if (environment != null && environment.getProperty(variableName) != null) {
variableValue = environment.getProperty(variableName);
logger.trace("Retrieved value for the URN variable, {}, from the environment variable: {}", variableName,
- variableValue);
+ variableValue);
execution.setVariable(variableName, variableValue);
return variableValue;
}
@@ -80,33 +78,35 @@ public class UrnPropertiesReader {
/**
* Return the URN property value from the environment object
+ *
* @param variableName URN property name
* @return URN property value
*/
- public static String getVariable(String variableName){
+ public static String getVariable(String variableName) {
if (environment != null) {
return environment.getProperty(variableName);
} else {
return null;
}
}
-
+
/**
* Return the String array URN property value from the environment object
+ *
* @param variableName URN property name
* @return URN property value
*/
- public static String[] getVariablesArray(String variableName){
+ public static String[] getVariablesArray(String variableName) {
if (environment != null) {
return environment.getProperty(variableName, String[].class);
} else {
return null;
}
}
-
+
public static String getVariable(String variableName, String defaultValue) {
- return Optional.ofNullable(getVariable(variableName)).orElse(defaultValue);
+ return Optional.ofNullable(getVariable(variableName)).orElse(defaultValue);
}
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java
index 8551007795..1692045d33 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java
@@ -26,69 +26,68 @@ import java.io.Serializable;
* An object that represents a workflow exception.
*/
public class WorkflowException implements Serializable {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- private final String processKey;
- private final int errorCode;
- private final String errorMessage;
- private final String workStep;
+ private final String processKey;
+ private final int errorCode;
+ private final String errorMessage;
+ private final String workStep;
- /**
- * Constructor
- * @param processKey the process key for the process that generated the exception
- * @param errorCode the numeric error code (normally 1xxx or greater)
- * @param errorMessage a short error message
- */
- public WorkflowException(String processKey, int errorCode,
- String errorMessage) {
- this.processKey = processKey;
- this.errorCode = errorCode;
- this.errorMessage = errorMessage;
- workStep = "*";
- }
-
- public WorkflowException(String processKey, int errorCode,
- String errorMessage, String workStep) {
- this.processKey = processKey;
- this.errorCode = errorCode;
- this.errorMessage = errorMessage;
- this.workStep = workStep;
- }
+ /**
+ * Constructor
+ *
+ * @param processKey the process key for the process that generated the exception
+ * @param errorCode the numeric error code (normally 1xxx or greater)
+ * @param errorMessage a short error message
+ */
+ public WorkflowException(String processKey, int errorCode, String errorMessage) {
+ this.processKey = processKey;
+ this.errorCode = errorCode;
+ this.errorMessage = errorMessage;
+ workStep = "*";
+ }
- /**
- * Returns the process key.
- */
- public String getProcessKey() {
- return processKey;
- }
+ public WorkflowException(String processKey, int errorCode, String errorMessage, String workStep) {
+ this.processKey = processKey;
+ this.errorCode = errorCode;
+ this.errorMessage = errorMessage;
+ this.workStep = workStep;
+ }
- /**
- * Returns the error code.
- */
- public int getErrorCode() {
- return errorCode;
- }
+ /**
+ * Returns the process key.
+ */
+ public String getProcessKey() {
+ return processKey;
+ }
- /**
- * Returns the error message.
- */
- public String getErrorMessage() {
- return errorMessage;
- }
-
- /**
- * Returns the error message.
- */
- public String getWorkStep() {
- return workStep;
- }
+ /**
+ * Returns the error code.
+ */
+ public int getErrorCode() {
+ return errorCode;
+ }
- /**
- * Returns a string representation of this object.
- */
+ /**
+ * Returns the error message.
+ */
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ /**
+ * Returns the error message.
+ */
+ public String getWorkStep() {
+ return workStep;
+ }
+
+ /**
+ * Returns a string representation of this object.
+ */
@Override
- public String toString() {
- return getClass().getSimpleName() + "[processKey=" + getProcessKey() + ",errorCode=" + getErrorCode()
- + ",errorMessage=" + getErrorMessage() + ",workStep=" + getWorkStep() + "]";
- }
+ public String toString() {
+ return getClass().getSimpleName() + "[processKey=" + getProcessKey() + ",errorCode=" + getErrorCode()
+ + ",errorMessage=" + getErrorMessage() + ",workStep=" + getWorkStep() + "]";
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java
index c7c7bba20c..841eaee675 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.core.domain;
import java.util.UUID;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -33,104 +32,122 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("allottedResource")
public class AllottedResource extends Resource {
- private static final long serialVersionUID = 1L;
-
- /*
- * set resourceType for this object
- */
- public AllottedResource(){
- resourceType = ResourceType.ALLOTTED_RESOURCE;
- setResourceId(UUID.randomUUID().toString());
- }
-
- /*
- * fields specific to Allotted Resource resource type
- */
- private String allottedResourceType;
- private String allottedResourceRole;
- private String providingServiceModelName;
- private String providingServiceModelInvariantUuid;
- private String providingServiceModelUuid;
- private String nfFunction;
- private String nfType;
- private String nfRole;
- private String nfNamingCode;
- private String orchestrationStatus;
-
- @JsonIgnore
- private String resourceInput;
-
- /*
- * GET and SET
- */
- public String getAllottedResourceType() {
- return allottedResourceType;
- }
- public void setAllottedResourceType(String allottedResourceType) {
- this.allottedResourceType = allottedResourceType;
- }
- public String getAllottedResourceRole() {
- return allottedResourceRole;
- }
- public void setAllottedResourceRole(String allottedResourceRole) {
- this.allottedResourceRole = allottedResourceRole;
- }
- public String getProvidingServiceModelName() {
- return providingServiceModelName;
- }
- public void setProvidingServiceModelName(String providingServiceModelName) {
- this.providingServiceModelName = providingServiceModelName;
- }
- public String getProvidingServiceModelInvariantUuid() {
- return providingServiceModelInvariantUuid;
- }
- public void setProvidingServiceModelInvariantUuid(
- String providingServiceModelInvariantUuid) {
- this.providingServiceModelInvariantUuid = providingServiceModelInvariantUuid;
- }
- public String getProvidingServiceModelUuid() {
- return providingServiceModelUuid;
- }
- public void setProvidingServiceModelUuid(String providingServiceModelUuid) {
- this.providingServiceModelUuid = providingServiceModelUuid;
- }
- public String getNfFunction() {
- return nfFunction;
- }
- public void setNfFunction(String nfFunction) {
- this.nfFunction = nfFunction;
- }
- public String getNfType() {
- return nfType;
- }
- public void setNfType(String nfType) {
- this.nfType = nfType;
- }
- public String getNfRole() {
- return nfRole;
- }
- public void setNfRole(String nfRole) {
- this.nfRole = nfRole;
- }
- public String getNfNamingCode() {
- return nfNamingCode;
- }
- public void setNfNamingCode(String nfNamingCode) {
- this.nfNamingCode = nfNamingCode;
- }
- public String getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(String orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
-
-
- public String getResourceInput() {
- return resourceInput;
- }
-
- public void setResourceInput(String resourceInput) {
- this.resourceInput = resourceInput;
- }
-} \ No newline at end of file
+ private static final long serialVersionUID = 1L;
+
+ /*
+ * set resourceType for this object
+ */
+ public AllottedResource() {
+ resourceType = ResourceType.ALLOTTED_RESOURCE;
+ setResourceId(UUID.randomUUID().toString());
+ }
+
+ /*
+ * fields specific to Allotted Resource resource type
+ */
+ private String allottedResourceType;
+ private String allottedResourceRole;
+ private String providingServiceModelName;
+ private String providingServiceModelInvariantUuid;
+ private String providingServiceModelUuid;
+ private String nfFunction;
+ private String nfType;
+ private String nfRole;
+ private String nfNamingCode;
+ private String orchestrationStatus;
+
+ @JsonIgnore
+ private String resourceInput;
+
+ /*
+ * GET and SET
+ */
+ public String getAllottedResourceType() {
+ return allottedResourceType;
+ }
+
+ public void setAllottedResourceType(String allottedResourceType) {
+ this.allottedResourceType = allottedResourceType;
+ }
+
+ public String getAllottedResourceRole() {
+ return allottedResourceRole;
+ }
+
+ public void setAllottedResourceRole(String allottedResourceRole) {
+ this.allottedResourceRole = allottedResourceRole;
+ }
+
+ public String getProvidingServiceModelName() {
+ return providingServiceModelName;
+ }
+
+ public void setProvidingServiceModelName(String providingServiceModelName) {
+ this.providingServiceModelName = providingServiceModelName;
+ }
+
+ public String getProvidingServiceModelInvariantUuid() {
+ return providingServiceModelInvariantUuid;
+ }
+
+ public void setProvidingServiceModelInvariantUuid(String providingServiceModelInvariantUuid) {
+ this.providingServiceModelInvariantUuid = providingServiceModelInvariantUuid;
+ }
+
+ public String getProvidingServiceModelUuid() {
+ return providingServiceModelUuid;
+ }
+
+ public void setProvidingServiceModelUuid(String providingServiceModelUuid) {
+ this.providingServiceModelUuid = providingServiceModelUuid;
+ }
+
+ public String getNfFunction() {
+ return nfFunction;
+ }
+
+ public void setNfFunction(String nfFunction) {
+ this.nfFunction = nfFunction;
+ }
+
+ public String getNfType() {
+ return nfType;
+ }
+
+ public void setNfType(String nfType) {
+ this.nfType = nfType;
+ }
+
+ public String getNfRole() {
+ return nfRole;
+ }
+
+ public void setNfRole(String nfRole) {
+ this.nfRole = nfRole;
+ }
+
+ public String getNfNamingCode() {
+ return nfNamingCode;
+ }
+
+ public void setNfNamingCode(String nfNamingCode) {
+ this.nfNamingCode = nfNamingCode;
+ }
+
+ public String getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(String orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+
+ public String getResourceInput() {
+ return resourceInput;
+ }
+
+ public void setResourceInput(String resourceInput) {
+ this.resourceInput = resourceInput;
+ }
+}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/CompareModelsResult.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/CompareModelsResult.java
index d021394731..7afd864062 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/CompareModelsResult.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/CompareModelsResult.java
@@ -23,31 +23,35 @@ package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
import java.util.List;
-public class CompareModelsResult extends JsonWrapper implements Serializable
-{
- private static final long serialVersionUID = 1L;
-
- private List<ResourceModelInfo> addedResourceList;
- private List<ResourceModelInfo> deletedResourceList;
- private List<String> requestInputs;
-
- public List<ResourceModelInfo> getAddedResourceList() {
- return addedResourceList;
- }
- public void setAddedResourceList(List<ResourceModelInfo> addedResourceList) {
- this.addedResourceList = addedResourceList;
- }
- public List<ResourceModelInfo> getDeletedResourceList() {
- return deletedResourceList;
- }
- public void setDeletedResourceList(List<ResourceModelInfo> deletedResourceList) {
- this.deletedResourceList = deletedResourceList;
- }
- public List<String> getRequestInputs() {
- return requestInputs;
- }
- public void setRequestInputs(List<String> requestInputs) {
- this.requestInputs = requestInputs;
- }
+public class CompareModelsResult extends JsonWrapper implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private List<ResourceModelInfo> addedResourceList;
+ private List<ResourceModelInfo> deletedResourceList;
+ private List<String> requestInputs;
+
+ public List<ResourceModelInfo> getAddedResourceList() {
+ return addedResourceList;
+ }
+
+ public void setAddedResourceList(List<ResourceModelInfo> addedResourceList) {
+ this.addedResourceList = addedResourceList;
+ }
+
+ public List<ResourceModelInfo> getDeletedResourceList() {
+ return deletedResourceList;
+ }
+
+ public void setDeletedResourceList(List<ResourceModelInfo> deletedResourceList) {
+ this.deletedResourceList = deletedResourceList;
+ }
+
+ public List<String> getRequestInputs() {
+ return requestInputs;
+ }
+
+ public void setRequestInputs(List<String> requestInputs) {
+ this.requestInputs = requestInputs;
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ConfigResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ConfigResource.java
index 1a8a1d83d9..95a82772db 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ConfigResource.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ConfigResource.java
@@ -21,25 +21,24 @@
package org.onap.so.bpmn.core.domain;
import java.util.UUID;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("configResource")
public class ConfigResource extends Resource {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- /*
- * set resourceType for this object
- */
- public ConfigResource(){
- resourceType = ResourceType.CONFIGURATION;
- setResourceId(UUID.randomUUID().toString());
- }
+ /*
+ * set resourceType for this object
+ */
+ public ConfigResource() {
+ resourceType = ResourceType.CONFIGURATION;
+ setResourceId(UUID.randomUUID().toString());
+ }
- /*
- * fields specific to Config Resource resource type
- */
+ /*
+ * fields specific to Config Resource resource type
+ */
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Configuration.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Configuration.java
index 815d85692e..baf7d198a1 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Configuration.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Configuration.java
@@ -21,68 +21,80 @@
package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonRootName;
/**
- * Stores configuration information and modeled off
- * of the AAI configuration object
+ * Stores configuration information and modeled off of the AAI configuration object
*
*/
@JsonRootName("configuration")
-public class Configuration extends JsonWrapper implements Serializable{
-
- private static final long serialVersionUID = 1L;
-
- private String id;
- private String name;
- private String type;
- private String orchestrationStatus;
- private String tunnelBandwidth;
- private String vendorAllowedMaxBandwidth;
- private String resourceVersion;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getType() {
- return type;
- }
- public void setType(String type) {
- this.type = type;
- }
- public String getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(String orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public String getTunnelBandwidth() {
- return tunnelBandwidth;
- }
- public void setTunnelBandwidth(String tunnelBandwidth) {
- this.tunnelBandwidth = tunnelBandwidth;
- }
- public String getVendorAllowedMaxBandwidth() {
- return vendorAllowedMaxBandwidth;
- }
- public void setVendorAllowedMaxBandwidth(String vendorAllowedMaxBandwidth) {
- this.vendorAllowedMaxBandwidth = vendorAllowedMaxBandwidth;
- }
- public String getResourceVersion() {
- return resourceVersion;
- }
- public void setResourceVersion(String resourceVersion) {
- this.resourceVersion = resourceVersion;
- }
+public class Configuration extends JsonWrapper implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String id;
+ private String name;
+ private String type;
+ private String orchestrationStatus;
+ private String tunnelBandwidth;
+ private String vendorAllowedMaxBandwidth;
+ private String resourceVersion;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(String orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public String getTunnelBandwidth() {
+ return tunnelBandwidth;
+ }
+
+ public void setTunnelBandwidth(String tunnelBandwidth) {
+ this.tunnelBandwidth = tunnelBandwidth;
+ }
+
+ public String getVendorAllowedMaxBandwidth() {
+ return vendorAllowedMaxBandwidth;
+ }
+
+ public void setVendorAllowedMaxBandwidth(String vendorAllowedMaxBandwidth) {
+ this.vendorAllowedMaxBandwidth = vendorAllowedMaxBandwidth;
+ }
+
+ public String getResourceVersion() {
+ return resourceVersion;
+ }
+
+ public void setResourceVersion(String resourceVersion) {
+ this.resourceVersion = resourceVersion;
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Customer.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Customer.java
index ca6d35cf46..f76ed9497c 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Customer.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Customer.java
@@ -21,9 +21,9 @@
package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
+
/**
- * This class is used to store customer
- * data of services aka ServiceDecomposition
+ * This class is used to store customer data of services aka ServiceDecomposition
*
* @author bb3476
*
@@ -31,22 +31,25 @@ import java.io.Serializable;
public class Customer extends JsonWrapper implements Serializable {
- private static final long serialVersionUID = 1L;
- private String subscriptionServiceType;
- private String globalSubscriberId;
-
-
- public String getSubscriptionServiceType() {
- return subscriptionServiceType;
- }
- public void setSubscriptionServiceType(String subscriptionServiceType) {
- this.subscriptionServiceType = subscriptionServiceType;
- }
- public String getGlobalSubscriberId() {
- return globalSubscriberId;
- }
- public void setGlobalSubscriberId(String globalSubscriberId) {
- this.globalSubscriberId = globalSubscriberId;
- }
-
+ private static final long serialVersionUID = 1L;
+ private String subscriptionServiceType;
+ private String globalSubscriberId;
+
+
+ public String getSubscriptionServiceType() {
+ return subscriptionServiceType;
+ }
+
+ public void setSubscriptionServiceType(String subscriptionServiceType) {
+ this.subscriptionServiceType = subscriptionServiceType;
+ }
+
+ public String getGlobalSubscriberId() {
+ return globalSubscriberId;
+ }
+
+ public void setGlobalSubscriberId(String globalSubscriberId) {
+ this.globalSubscriberId = globalSubscriberId;
+ }
+
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java
index e4eb01e7fb..897cbe3573 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -32,124 +31,127 @@ import com.fasterxml.jackson.annotation.JsonRootName;
*/
@JsonRootName("homingSolution")
@JsonInclude(JsonInclude.Include.NON_NULL)
-public class HomingSolution extends JsonWrapper implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- private InventoryType inventoryType;
- private boolean isRehome;
- private String serviceInstanceId; //TODO should start using si object instead
- private String cloudOwner;
- private String cloudRegionId;
- private String aicClli;
- private String aicVersion;
- private String tenant;
- private VnfResource vnf;
- private String oofDirectives;
- private License license = new License();
-
-
- /**
- * @return the inventoryType which indicates the solution type
- */
- public InventoryType getInventoryType() {
- return inventoryType;
- }
-
- public void setInventoryType(InventoryType inventoryType) {
- this.inventoryType = inventoryType;
- }
- public boolean isRehome() {
- return isRehome;
- }
- public void setRehome(boolean isRehome) {
- this.isRehome = isRehome;
- }
-
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
-
- public String getCloudOwner() {
- return cloudOwner;
- }
-
- public void setCloudOwner(String cloudOwner) {
- this.cloudOwner = cloudOwner;
- }
-
- public String getCloudRegionId() {
- return cloudRegionId;
- }
-
- public void setCloudRegionId(String cloudRegionId) {
- this.cloudRegionId = cloudRegionId;
- }
- /**
- * @return the aicClli (aka aic site, physical location id)
- */
- public String getAicClli() {
- return aicClli;
- }
-
- public void setAicClli(String aicClli) {
- this.aicClli = aicClli;
- }
-
- public String getAicVersion() {
- return aicVersion;
- }
-
- public void setAicVersion(String aicVersion) {
- this.aicVersion = aicVersion;
- }
-
- public String getTenant() {
- return tenant;
- }
-
- public void setTenant(String tenant) {
- this.tenant = tenant;
- }
-
- /**
- * @return the vnf that the resource was homed too.
- */
- public VnfResource getVnf() {
- return vnf;
- }
-
- public void setVnf(VnfResource vnf) {
- this.vnf = vnf;
- }
-
- /**
- * @return a map<string, string> key is label name, value is any flavor
- */
- public String getOofDirectives() {
- return oofDirectives;
- }
-
- public void setOofDirectives(String oofDirectives) {
- this.oofDirectives = oofDirectives;
- }
-
- public License getLicense() {
- return license;
- }
-
- public void setLicense(License license) {
- this.license = license;
- }
-
-
- public static long getSerialversionuid() {
- return serialVersionUID;
- }
-
-
-} \ No newline at end of file
+public class HomingSolution extends JsonWrapper implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private InventoryType inventoryType;
+ private boolean isRehome;
+ private String serviceInstanceId; // TODO should start using si object instead
+ private String cloudOwner;
+ private String cloudRegionId;
+ private String aicClli;
+ private String aicVersion;
+ private String tenant;
+ private VnfResource vnf;
+ private String oofDirectives;
+ private License license = new License();
+
+
+ /**
+ * @return the inventoryType which indicates the solution type
+ */
+ public InventoryType getInventoryType() {
+ return inventoryType;
+ }
+
+ public void setInventoryType(InventoryType inventoryType) {
+ this.inventoryType = inventoryType;
+ }
+
+ public boolean isRehome() {
+ return isRehome;
+ }
+
+ public void setRehome(boolean isRehome) {
+ this.isRehome = isRehome;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getCloudOwner() {
+ return cloudOwner;
+ }
+
+ public void setCloudOwner(String cloudOwner) {
+ this.cloudOwner = cloudOwner;
+ }
+
+ public String getCloudRegionId() {
+ return cloudRegionId;
+ }
+
+ public void setCloudRegionId(String cloudRegionId) {
+ this.cloudRegionId = cloudRegionId;
+ }
+
+ /**
+ * @return the aicClli (aka aic site, physical location id)
+ */
+ public String getAicClli() {
+ return aicClli;
+ }
+
+ public void setAicClli(String aicClli) {
+ this.aicClli = aicClli;
+ }
+
+ public String getAicVersion() {
+ return aicVersion;
+ }
+
+ public void setAicVersion(String aicVersion) {
+ this.aicVersion = aicVersion;
+ }
+
+ public String getTenant() {
+ return tenant;
+ }
+
+ public void setTenant(String tenant) {
+ this.tenant = tenant;
+ }
+
+ /**
+ * @return the vnf that the resource was homed too.
+ */
+ public VnfResource getVnf() {
+ return vnf;
+ }
+
+ public void setVnf(VnfResource vnf) {
+ this.vnf = vnf;
+ }
+
+ /**
+ * @return a map<string, string> key is label name, value is any flavor
+ */
+ public String getOofDirectives() {
+ return oofDirectives;
+ }
+
+ public void setOofDirectives(String oofDirectives) {
+ this.oofDirectives = oofDirectives;
+ }
+
+ public License getLicense() {
+ return license;
+ }
+
+ public void setLicense(License license) {
+ this.license = license;
+ }
+
+
+ public static long getSerialversionuid() {
+ return serialVersionUID;
+ }
+
+
+}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/InventoryType.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/InventoryType.java
index e56ca76b2b..494eb2a61d 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/InventoryType.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/InventoryType.java
@@ -20,18 +20,17 @@
package org.onap.so.bpmn.core.domain;
-public enum InventoryType{
+public enum InventoryType {
- cloud("CLOUD"),
- service("SERVICE");
+ cloud("CLOUD"), service("SERVICE");
- private String type;
+ private String type;
- InventoryType(String type){
- this.type = type;
- }
+ InventoryType(String type) {
+ this.type = type;
+ }
- public String type(){
- return type;
- }
-} \ No newline at end of file
+ public String type() {
+ return type;
+ }
+}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java
index c3eefcd3cd..602172f8a4 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java
@@ -25,10 +25,8 @@ package org.onap.so.bpmn.core.domain;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
-
import org.json.JSONException;
import org.json.JSONObject;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerationException;
@@ -36,100 +34,99 @@ import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Wrapper encapsulates needed JSON functionality
- * to be extended by MSO service decomposition objects
- * providing ways to convert to and from JSON
+ * Wrapper encapsulates needed JSON functionality to be extended by MSO service decomposition objects providing ways to
+ * convert to and from JSON
*
*/
@JsonInclude(Include.NON_NULL)
-public abstract class JsonWrapper implements Serializable {
-
- private static final Logger logger = LoggerFactory.getLogger(JsonWrapper.class);
- @JsonInclude(Include.NON_NULL)
- public String toJsonString(){
-
- String jsonString = "";
- //convert with Jackson
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
-
- mapper.setSerializationInclusion(Include.NON_NULL);
-
- ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
- try {
- jsonString = ow.writeValueAsString(this);
- } catch (Exception e){
-
- logger.debug("Exception :",e);
- }
- return jsonString;
- }
-
- @JsonInclude(Include.NON_NULL)
- public JSONObject toJsonObject(){
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
- JSONObject json = new JSONObject();
- try {
- json = new JSONObject(mapper.writeValueAsString(this));
- } catch (JsonGenerationException e) {
- logger.debug("Exception :",e);
- } catch (JsonMappingException e) {
- logger.debug("Exception :",e);
- } catch (JSONException e) {
- logger.debug("Exception :",e);
- } catch (IOException e) {
- logger.debug("Exception :",e);
- }
- return json;
- }
-
- public String listToJson(List list) {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
-
- String jsonString = "";
- try {
- jsonString = mapper.writeValueAsString(list);
- } catch (JsonGenerationException e) {
- logger.debug("Exception :",e);
- } catch (JsonMappingException e) {
- logger.debug("Exception :",e);
- } catch (IOException e) {
- logger.debug("Exception :",e);
- }
- return jsonString;
- }
-
- @JsonInclude(Include.NON_NULL)
- public String toJsonStringNoRootName(){
-
- String jsonString = "";
- //convert with Jackson
- ObjectMapper mapper = new ObjectMapper();
- mapper.setSerializationInclusion(Include.NON_NULL);
-
- ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
- try {
- jsonString = ow.writeValueAsString(this);
- } catch (Exception e){
-
- logger.debug("Exception :",e);
- }
- return jsonString;
- }
-
- /**
- * Returns a string representation of this object.
- */
- public String toString() {
- return this.toJsonString();
- }
+public abstract class JsonWrapper implements Serializable {
+
+ private static final Logger logger = LoggerFactory.getLogger(JsonWrapper.class);
+
+ @JsonInclude(Include.NON_NULL)
+ public String toJsonString() {
+
+ String jsonString = "";
+ // convert with Jackson
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
+
+ mapper.setSerializationInclusion(Include.NON_NULL);
+
+ ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
+ try {
+ jsonString = ow.writeValueAsString(this);
+ } catch (Exception e) {
+
+ logger.debug("Exception :", e);
+ }
+ return jsonString;
+ }
+
+ @JsonInclude(Include.NON_NULL)
+ public JSONObject toJsonObject() {
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
+ JSONObject json = new JSONObject();
+ try {
+ json = new JSONObject(mapper.writeValueAsString(this));
+ } catch (JsonGenerationException e) {
+ logger.debug("Exception :", e);
+ } catch (JsonMappingException e) {
+ logger.debug("Exception :", e);
+ } catch (JSONException e) {
+ logger.debug("Exception :", e);
+ } catch (IOException e) {
+ logger.debug("Exception :", e);
+ }
+ return json;
+ }
+
+ public String listToJson(List list) {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
+
+ String jsonString = "";
+ try {
+ jsonString = mapper.writeValueAsString(list);
+ } catch (JsonGenerationException e) {
+ logger.debug("Exception :", e);
+ } catch (JsonMappingException e) {
+ logger.debug("Exception :", e);
+ } catch (IOException e) {
+ logger.debug("Exception :", e);
+ }
+ return jsonString;
+ }
+
+ @JsonInclude(Include.NON_NULL)
+ public String toJsonStringNoRootName() {
+
+ String jsonString = "";
+ // convert with Jackson
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(Include.NON_NULL);
+
+ ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
+ try {
+ jsonString = ow.writeValueAsString(this);
+ } catch (Exception e) {
+
+ logger.debug("Exception :", e);
+ }
+ return jsonString;
+ }
+
+ /**
+ * Returns a string representation of this object.
+ */
+ public String toString() {
+ return this.toJsonString();
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java
index 93dfd4f1f1..1db360f391 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java
@@ -24,95 +24,88 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-
import org.json.JSONArray;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonRootName;
/**
- * Stores licensing information and is an attribute
- * of a <class>HomingSolution</class>
+ * Stores licensing information and is an attribute of a <class>HomingSolution</class>
*
*/
@JsonRootName("license")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
-public class License extends JsonWrapper implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- @JsonInclude(JsonInclude.Include.NON_EMPTY)
- private List<String> entitlementPoolList = new ArrayList<String>();
- @JsonInclude(JsonInclude.Include.NON_EMPTY)
- private List<String> licenseKeyGroupList = new ArrayList<String>();
-
-
- public List<String> getEntitlementPoolList() {
- return entitlementPoolList;
- }
-
- public void setEntitlementPoolList(List<String> entitlementPoolList) {
- this.entitlementPoolList = entitlementPoolList;
- }
-
- public List<String> getLicenseKeyGroupList() {
- return licenseKeyGroupList;
- }
-
- public void setLicenseKeyGroupList(List<String> licenseKeyGroupList) {
- this.licenseKeyGroupList = licenseKeyGroupList;
- }
-
- /**
- * This method adds a Entitlement Pool Uuid
- * to the EntitlementPoolList
- *
- * @param the EntitlementPoolUuid
- */
- public void addEntitlementPool(String entitlementPoolUuid) {
- entitlementPoolList.add(entitlementPoolUuid);
- }
-
- /**
- * This method adds a License Key Group Uuid
- * to the LicenseKeyGroupList
- *
- * @param the licenseKeyGroupUuid
- */
- public void addLicenseKeyGroup(String licenseKeyGroupUuid) {
- licenseKeyGroupList.add(licenseKeyGroupUuid);
- }
-
- /**
- * This method returns the licenseKeyGroupList
- * as a json array
- *
- * @return the strList
- */
- @JsonIgnore
- public JSONArray getLicenseKeyGroupListAsString() {
+public class License extends JsonWrapper implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @JsonInclude(JsonInclude.Include.NON_EMPTY)
+ private List<String> entitlementPoolList = new ArrayList<String>();
+ @JsonInclude(JsonInclude.Include.NON_EMPTY)
+ private List<String> licenseKeyGroupList = new ArrayList<String>();
+
+
+ public List<String> getEntitlementPoolList() {
+ return entitlementPoolList;
+ }
+
+ public void setEntitlementPoolList(List<String> entitlementPoolList) {
+ this.entitlementPoolList = entitlementPoolList;
+ }
+
+ public List<String> getLicenseKeyGroupList() {
+ return licenseKeyGroupList;
+ }
+
+ public void setLicenseKeyGroupList(List<String> licenseKeyGroupList) {
+ this.licenseKeyGroupList = licenseKeyGroupList;
+ }
+
+ /**
+ * This method adds a Entitlement Pool Uuid to the EntitlementPoolList
+ *
+ * @param the EntitlementPoolUuid
+ */
+ public void addEntitlementPool(String entitlementPoolUuid) {
+ entitlementPoolList.add(entitlementPoolUuid);
+ }
+
+ /**
+ * This method adds a License Key Group Uuid to the LicenseKeyGroupList
+ *
+ * @param the licenseKeyGroupUuid
+ */
+ public void addLicenseKeyGroup(String licenseKeyGroupUuid) {
+ licenseKeyGroupList.add(licenseKeyGroupUuid);
+ }
+
+ /**
+ * This method returns the licenseKeyGroupList as a json array
+ *
+ * @return the strList
+ */
+ @JsonIgnore
+ public JSONArray getLicenseKeyGroupListAsString() {
JSONArray array = new JSONArray(licenseKeyGroupList);
- return array;
- }
-
- /**
- * This method returns the entitlementPoolList
- * as a json array
- *
- * @return the strList
- */
- @JsonIgnore
- public JSONArray getEntitlementPoolListAsString() {
+ return array;
+ }
+
+ /**
+ * This method returns the entitlementPoolList as a json array
+ *
+ * @return the strList
+ */
+ @JsonIgnore
+ public JSONArray getEntitlementPoolListAsString() {
JSONArray array = new JSONArray(entitlementPoolList);
- return array;
- }
-
- /**
- * @return the serialversionuid
- */
- public static long getSerialversionuid() {
- return serialVersionUID;
- }
+ return array;
+ }
+
+ /**
+ * @return the serialversionuid
+ */
+ public static long getSerialversionuid() {
+ return serialVersionUID;
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModelInfo.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModelInfo.java
index 983fe50d88..4c8401335d 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModelInfo.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModelInfo.java
@@ -21,77 +21,90 @@
package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("modelInfo")
-public class ModelInfo extends JsonWrapper implements Serializable {
-
- /**
- * This is domain object defining structure for MODEL INFO
- * It will be valid for each Resource type object
- */
- private static final long serialVersionUID = 1L;
-
- private String modelName = "";
- private String modelUuid = "";
- private String modelInvariantUuid = "";
- private String modelVersion = "";
- //additionally on resource level
- private String modelCustomizationUuid = "";
- private String modelCustomizationName = "";
- private String modelInstanceName = "";
- private String modelType = "";
-
- //GET and SET methods
-
- public String getModelName() {
- return modelName;
- }
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
- public String getModelUuid() {
- return modelUuid;
- }
- public void setModelUuid(String modelUuid) {
- this.modelUuid = modelUuid;
- }
- public String getModelInvariantUuid() {
- return modelInvariantUuid;
- }
- public void setModelInvariantUuid(String modelInvariantUuid) {
- this.modelInvariantUuid = modelInvariantUuid;
- }
- public String getModelVersion() {
- return modelVersion;
- }
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
- public String getModelCustomizationUuid() {
- return modelCustomizationUuid;
- }
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
- public String getModelCustomizationName() {
- return modelCustomizationName;
- }
- public void setModelCustomizationName(String modelCustomizationName) {
- this.modelCustomizationName = modelCustomizationName;
- }
- public String getModelInstanceName() {
- return modelInstanceName;
- }
- public void setModelInstanceName(String modelInstanceName) {
- this.modelInstanceName = modelInstanceName;
- }
- public String getModelType() {
- return modelType;
- }
- public void setModelType(String modelType) {
- this.modelType = modelType;
- }
-
-} \ No newline at end of file
+public class ModelInfo extends JsonWrapper implements Serializable {
+
+ /**
+ * This is domain object defining structure for MODEL INFO It will be valid for each Resource type object
+ */
+ private static final long serialVersionUID = 1L;
+
+ private String modelName = "";
+ private String modelUuid = "";
+ private String modelInvariantUuid = "";
+ private String modelVersion = "";
+ // additionally on resource level
+ private String modelCustomizationUuid = "";
+ private String modelCustomizationName = "";
+ private String modelInstanceName = "";
+ private String modelType = "";
+
+ // GET and SET methods
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getModelUuid() {
+ return modelUuid;
+ }
+
+ public void setModelUuid(String modelUuid) {
+ this.modelUuid = modelUuid;
+ }
+
+ public String getModelInvariantUuid() {
+ return modelInvariantUuid;
+ }
+
+ public void setModelInvariantUuid(String modelInvariantUuid) {
+ this.modelInvariantUuid = modelInvariantUuid;
+ }
+
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ public String getModelCustomizationUuid() {
+ return modelCustomizationUuid;
+ }
+
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ public String getModelCustomizationName() {
+ return modelCustomizationName;
+ }
+
+ public void setModelCustomizationName(String modelCustomizationName) {
+ this.modelCustomizationName = modelCustomizationName;
+ }
+
+ public String getModelInstanceName() {
+ return modelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ this.modelInstanceName = modelInstanceName;
+ }
+
+ public String getModelType() {
+ return modelType;
+ }
+
+ public void setModelType(String modelType) {
+ this.modelType = modelType;
+ }
+
+}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModuleResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModuleResource.java
index 459d203325..a67149b71f 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModuleResource.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ModuleResource.java
@@ -23,72 +23,85 @@ package org.onap.so.bpmn.core.domain;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("vfModule")
-public class ModuleResource extends Resource {
-
- private static final long serialVersionUID = 1L;
-
- /*
- * set resourceType for this object
- */
- public ModuleResource(){
- resourceType = ResourceType.MODULE;
- }
-
- /*
- * fields specific to VF Module resource type
- */
- private String vfModuleName;
- private String vfModuleType;
- private String heatStackId;
- private boolean hasVolumeGroup;
- private boolean isBase;
- private String vfModuleLabel;
- private int initialCount;
-
- /*
- * GET && SET
- */
- public String getVfModuleName() {
- return vfModuleName;
- }
- public void setVfModuleName(String vfModuleName) {
- this.vfModuleName = vfModuleName;
- }
- public String getHeatStackId() {
- return heatStackId;
- }
- public void setHeatStackId(String heatStackId) {
- this.heatStackId = heatStackId;
- }
- public boolean getIsBase() {
- return isBase;
- }
- public void setIsBase(boolean isBase) {
- this.isBase = isBase;
- }
- public String getVfModuleLabel() {
- return vfModuleLabel;
- }
- public void setVfModuleLabel(String vfModuleLabel) {
- this.vfModuleLabel = vfModuleLabel;
- }
- public int getInitialCount() {
- return initialCount;
- }
- public void setInitialCount(int initialCount) {
- this.initialCount = initialCount;
- }
- public String getVfModuleType() {
- return vfModuleType;
- }
- public void setVfModuleType(String vfModuleType) {
- this.vfModuleType = vfModuleType;
- }
- public boolean isHasVolumeGroup() {
- return hasVolumeGroup;
- }
- public void setHasVolumeGroup(boolean hasVolumeGroup) {
- this.hasVolumeGroup = hasVolumeGroup;
- }
-
-} \ No newline at end of file
+public class ModuleResource extends Resource {
+
+ private static final long serialVersionUID = 1L;
+
+ /*
+ * set resourceType for this object
+ */
+ public ModuleResource() {
+ resourceType = ResourceType.MODULE;
+ }
+
+ /*
+ * fields specific to VF Module resource type
+ */
+ private String vfModuleName;
+ private String vfModuleType;
+ private String heatStackId;
+ private boolean hasVolumeGroup;
+ private boolean isBase;
+ private String vfModuleLabel;
+ private int initialCount;
+
+ /*
+ * GET && SET
+ */
+ public String getVfModuleName() {
+ return vfModuleName;
+ }
+
+ public void setVfModuleName(String vfModuleName) {
+ this.vfModuleName = vfModuleName;
+ }
+
+ public String getHeatStackId() {
+ return heatStackId;
+ }
+
+ public void setHeatStackId(String heatStackId) {
+ this.heatStackId = heatStackId;
+ }
+
+ public boolean getIsBase() {
+ return isBase;
+ }
+
+ public void setIsBase(boolean isBase) {
+ this.isBase = isBase;
+ }
+
+ public String getVfModuleLabel() {
+ return vfModuleLabel;
+ }
+
+ public void setVfModuleLabel(String vfModuleLabel) {
+ this.vfModuleLabel = vfModuleLabel;
+ }
+
+ public int getInitialCount() {
+ return initialCount;
+ }
+
+ public void setInitialCount(int initialCount) {
+ this.initialCount = initialCount;
+ }
+
+ public String getVfModuleType() {
+ return vfModuleType;
+ }
+
+ public void setVfModuleType(String vfModuleType) {
+ this.vfModuleType = vfModuleType;
+ }
+
+ public boolean isHasVolumeGroup() {
+ return hasVolumeGroup;
+ }
+
+ public void setHasVolumeGroup(boolean hasVolumeGroup) {
+ this.hasVolumeGroup = hasVolumeGroup;
+ }
+
+}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/NetworkResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/NetworkResource.java
index f0e97f15ef..7523c378e9 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/NetworkResource.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/NetworkResource.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.core.domain;
import java.util.UUID;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -34,58 +33,67 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("networkResource")
public class NetworkResource extends Resource {
- private static final long serialVersionUID = 1L;
- /*
- * set resourceType for this object
- */
- public NetworkResource(){
- resourceType = ResourceType.NETWORK;
- setResourceId(UUID.randomUUID().toString());
- }
- /*
- * fields specific to Network resource type
- */
- private String networkType;
- private String networkRole;
- private String networkTechnology;
- private String networkScope;
-
- @JsonIgnore
- private String resourceInput;
-
- /*
- * GET and SET
- */
- public String getNetworkType() {
- return networkType;
- }
- public void setNetworkType(String networkType) {
- this.networkType = networkType;
- }
- public String getNetworkRole() {
- return networkRole;
- }
- public void setNetworkRole(String networkRole) {
- this.networkRole = networkRole;
- }
- public String getNetworkTechnology() {
- return networkTechnology;
- }
- public void setNetworkTechnology(String networkTechnology) {
- this.networkTechnology = networkTechnology;
- }
- public String getNetworkScope() {
- return networkScope;
- }
- public void setNetworkScope(String networkScope) {
- this.networkScope = networkScope;
- }
-
- public String getResourceInput() {
- return resourceInput;
- }
-
- public void setResourceInput(String resourceInput) {
- this.resourceInput = resourceInput;
- }
-} \ No newline at end of file
+ private static final long serialVersionUID = 1L;
+
+ /*
+ * set resourceType for this object
+ */
+ public NetworkResource() {
+ resourceType = ResourceType.NETWORK;
+ setResourceId(UUID.randomUUID().toString());
+ }
+
+ /*
+ * fields specific to Network resource type
+ */
+ private String networkType;
+ private String networkRole;
+ private String networkTechnology;
+ private String networkScope;
+
+ @JsonIgnore
+ private String resourceInput;
+
+ /*
+ * GET and SET
+ */
+ public String getNetworkType() {
+ return networkType;
+ }
+
+ public void setNetworkType(String networkType) {
+ this.networkType = networkType;
+ }
+
+ public String getNetworkRole() {
+ return networkRole;
+ }
+
+ public void setNetworkRole(String networkRole) {
+ this.networkRole = networkRole;
+ }
+
+ public String getNetworkTechnology() {
+ return networkTechnology;
+ }
+
+ public void setNetworkTechnology(String networkTechnology) {
+ this.networkTechnology = networkTechnology;
+ }
+
+ public String getNetworkScope() {
+ return networkScope;
+ }
+
+ public void setNetworkScope(String networkScope) {
+ this.networkScope = networkScope;
+ }
+
+ public String getResourceInput() {
+ return resourceInput;
+ }
+
+ public void setResourceInput(String resourceInput) {
+ this.resourceInput = resourceInput;
+ }
+}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/OwningEntity.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/OwningEntity.java
index 903b84ac8a..de637fdcc6 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/OwningEntity.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/OwningEntity.java
@@ -21,12 +21,10 @@
package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonRootName;
/**
- * This class is used to store instance
- * data of owningEntity for ServiceDecomposition
+ * This class is used to store instance data of owningEntity for ServiceDecomposition
*
* @author bb3476
*
@@ -34,20 +32,24 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("owningEntity")
public class OwningEntity extends JsonWrapper implements Serializable {
- private static final long serialVersionUID = 1L;
- private String owningEntityId;
- private String owningEntityName;
- public String getOwningEntityId() {
- return owningEntityId;
- }
- public void setOwningEntityId(String owningEntityId) {
- this.owningEntityId = owningEntityId;
- }
- public String getOwningEntityName() {
- return owningEntityName;
- }
- public void setOwningEntityName(String owningEntityName) {
- this.owningEntityName = owningEntityName;
- }
-
+ private static final long serialVersionUID = 1L;
+ private String owningEntityId;
+ private String owningEntityName;
+
+ public String getOwningEntityId() {
+ return owningEntityId;
+ }
+
+ public void setOwningEntityId(String owningEntityId) {
+ this.owningEntityId = owningEntityId;
+ }
+
+ public String getOwningEntityName() {
+ return owningEntityName;
+ }
+
+ public void setOwningEntityName(String owningEntityName) {
+ this.owningEntityName = owningEntityName;
+ }
+
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Project.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Project.java
index 337626ec61..e05035a92d 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Project.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Project.java
@@ -21,12 +21,10 @@
package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonRootName;
/**
- * This class is used to store instance
- * data of projects for ServiceDecomposition
+ * This class is used to store instance data of projects for ServiceDecomposition
*
* @author bb3476
*
@@ -34,14 +32,15 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("project")
public class Project extends JsonWrapper implements Serializable {
- private static final long serialVersionUID = 1L;
- private String projectName;
+ private static final long serialVersionUID = 1L;
+ private String projectName;
+
+ public String getProjectName() {
+ return projectName;
+ }
+
+ public void setProjectName(String projectName) {
+ this.projectName = projectName;
+ }
- public String getProjectName() {
- return projectName;
- }
- public void setProjectName(String projectName) {
- this.projectName = projectName;
- }
-
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java
index dac7336013..6c33d37cfe 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java
@@ -21,12 +21,10 @@
package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonRootName;
/**
- * This class is used to store instance
- * data of services aka ServiceDecomposition
+ * This class is used to store instance data of services aka ServiceDecomposition
*
* @author bb3476
*
@@ -34,63 +32,78 @@ import com.fasterxml.jackson.annotation.JsonRootName;
public class Request extends JsonWrapper implements Serializable {
- private static final long serialVersionUID = 1L;
- private String sdncRequestId;
- private String requestId;
- private ModelInfo modelInfo;
- private String productFamilyId;
- private String callbackUrl;
- private String serviceId;
- private String tenantId;
- private String cloudRegion;
-
- public String getSdncRequestId() {
- return sdncRequestId;
- }
- public void setSdncRequestId(String sdncRequestId) {
- this.sdncRequestId = sdncRequestId;
- }
- public String getRequestId() {
- return requestId;
- }
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
- public ModelInfo getModelInfo() {
- return modelInfo;
- }
- public void setModelInfo(ModelInfo modelInfo) {
- this.modelInfo = modelInfo;
- }
- public String getProductFamilyId() {
- return productFamilyId;
- }
- public void setProductFamilyId(String productFamilyId) {
- this.productFamilyId = productFamilyId;
- }
- public String getCallbackUrl() {
- return callbackUrl;
- }
- public void setCallbackUrl(String callbackUrl) {
- this.callbackUrl = callbackUrl;
- }
- public String getServiceId() {
- return serviceId;
- }
- public void setServiceId(String serviceId) {
- this.serviceId = serviceId;
- }
- public String getCloudRegion() {
- return cloudRegion;
- }
- public void setCloudRegion(String cloudRegion) {
- this.cloudRegion = cloudRegion;
- }
- public String getTenantId() {
- return tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
-
+ private static final long serialVersionUID = 1L;
+ private String sdncRequestId;
+ private String requestId;
+ private ModelInfo modelInfo;
+ private String productFamilyId;
+ private String callbackUrl;
+ private String serviceId;
+ private String tenantId;
+ private String cloudRegion;
+
+ public String getSdncRequestId() {
+ return sdncRequestId;
+ }
+
+ public void setSdncRequestId(String sdncRequestId) {
+ this.sdncRequestId = sdncRequestId;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
+
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
+
+ public String getProductFamilyId() {
+ return productFamilyId;
+ }
+
+ public void setProductFamilyId(String productFamilyId) {
+ this.productFamilyId = productFamilyId;
+ }
+
+ public String getCallbackUrl() {
+ return callbackUrl;
+ }
+
+ public void setCallbackUrl(String callbackUrl) {
+ this.callbackUrl = callbackUrl;
+ }
+
+ public String getServiceId() {
+ return serviceId;
+ }
+
+ public void setServiceId(String serviceId) {
+ this.serviceId = serviceId;
+ }
+
+ public String getCloudRegion() {
+ return cloudRegion;
+ }
+
+ public void setCloudRegion(String cloudRegion) {
+ this.cloudRegion = cloudRegion;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Resource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Resource.java
index 00fdbec305..62a2e9370e 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Resource.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Resource.java
@@ -21,114 +21,126 @@
package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
-public abstract class Resource extends JsonWrapper implements Serializable {
-
- private static final long serialVersionUID = 1L;
- private String resourceId; // TODO name this field just id instead, should be the id of the object as it is in aai
- protected ResourceType resourceType; // Enum of vnf or network or allotted resource
- protected ModelInfo modelInfo;
- private long concurrencyCounter = 1L;
-
- //private List modules;
- private ResourceInstance resourceInstance = new ResourceInstance(); // TODO possibly remove
- private HomingSolution homingSolution = new HomingSolution();
- @JsonInclude(JsonInclude.Include.NON_NULL)
- private HomingSolution currentHomingSolution;
-
- //common parameters for all Resources
- private String toscaNodeType;
-
- // GET and SET
- public String getResourceId() {
- return resourceId;
- }
- public void setResourceId(String resourceId) {
- this.resourceId = resourceId;
- }
- public ModelInfo getModelInfo() {
- return modelInfo;
- }
- public void setModelInfo(ModelInfo modelInfo) {
- this.modelInfo = modelInfo;
- }
-
- public ResourceInstance getResourceInstance() {
- return resourceInstance;
- }
- public void setResourceInstance(ResourceInstance resourceInstance) {
- this.resourceInstance = resourceInstance;
- }
- public HomingSolution getHomingSolution(){
- return homingSolution;
- }
-
- public void setHomingSolution(HomingSolution homingSolution){
- this.homingSolution = homingSolution;
- }
- public HomingSolution getCurrentHomingSolution() {
- return currentHomingSolution;
- }
- public void setCurrentHomingSolution(HomingSolution currentHomingSolution) {
- this.currentHomingSolution = currentHomingSolution;
- }
- public void setResourceType(ResourceType resourceType) {
- this.resourceType = resourceType;
- }
-
- public ResourceType getResourceType(){
- return resourceType;
- }
-
- public String getToscaNodeType() {
- return toscaNodeType;
- }
- public void setToscaNodeType(String toscaNodeType) {
- this.toscaNodeType = toscaNodeType;
- }
-
- //Utility methods
-
- public String getResourceInstanceId() {
- return this.getResourceInstance().getInstanceId();
- }
- public String getResourceInstanceName() {
- return this.getResourceInstance().getInstanceName();
- }
- //TODO
-// @JsonIgnore
-// public String getResourceHomingSolution() {
-// }
-
- public void setResourceInstanceId(String newInstanceId){
- this.getResourceInstance().setInstanceId(newInstanceId);
- }
- public void setResourceInstanceName(String newInstanceName){
- this.getResourceInstance().setInstanceName(newInstanceName);
- }
-
- //TODO
-// @JsonIgnore
-// public String setResourceHomingSolution() {
-// }
- /**
- * To be used by macro flow to increment concurrency counter after update to it's structure was completed
- */
- public void incrementConcurrencyCounter(){
- this.concurrencyCounter ++;
- }
- /**
- * Method to get concurrency counter data
- * @return long value for the counter
- */
- @JsonIgnore
- public long getConcurrencyCounter(){
- return concurrencyCounter;
- }
-
-} \ No newline at end of file
+public abstract class Resource extends JsonWrapper implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+ private String resourceId; // TODO name this field just id instead, should be the id of the object as it is in aai
+ protected ResourceType resourceType; // Enum of vnf or network or allotted resource
+ protected ModelInfo modelInfo;
+ private long concurrencyCounter = 1L;
+
+ // private List modules;
+ private ResourceInstance resourceInstance = new ResourceInstance(); // TODO possibly remove
+ private HomingSolution homingSolution = new HomingSolution();
+ @JsonInclude(JsonInclude.Include.NON_NULL)
+ private HomingSolution currentHomingSolution;
+
+ // common parameters for all Resources
+ private String toscaNodeType;
+
+ // GET and SET
+ public String getResourceId() {
+ return resourceId;
+ }
+
+ public void setResourceId(String resourceId) {
+ this.resourceId = resourceId;
+ }
+
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
+
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
+
+ public ResourceInstance getResourceInstance() {
+ return resourceInstance;
+ }
+
+ public void setResourceInstance(ResourceInstance resourceInstance) {
+ this.resourceInstance = resourceInstance;
+ }
+
+ public HomingSolution getHomingSolution() {
+ return homingSolution;
+ }
+
+ public void setHomingSolution(HomingSolution homingSolution) {
+ this.homingSolution = homingSolution;
+ }
+
+ public HomingSolution getCurrentHomingSolution() {
+ return currentHomingSolution;
+ }
+
+ public void setCurrentHomingSolution(HomingSolution currentHomingSolution) {
+ this.currentHomingSolution = currentHomingSolution;
+ }
+
+ public void setResourceType(ResourceType resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public ResourceType getResourceType() {
+ return resourceType;
+ }
+
+ public String getToscaNodeType() {
+ return toscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ this.toscaNodeType = toscaNodeType;
+ }
+
+ // Utility methods
+
+ public String getResourceInstanceId() {
+ return this.getResourceInstance().getInstanceId();
+ }
+
+ public String getResourceInstanceName() {
+ return this.getResourceInstance().getInstanceName();
+ }
+ // TODO
+ // @JsonIgnore
+ // public String getResourceHomingSolution() {
+ // }
+
+ public void setResourceInstanceId(String newInstanceId) {
+ this.getResourceInstance().setInstanceId(newInstanceId);
+ }
+
+ public void setResourceInstanceName(String newInstanceName) {
+ this.getResourceInstance().setInstanceName(newInstanceName);
+ }
+
+ // TODO
+ // @JsonIgnore
+ // public String setResourceHomingSolution() {
+ // }
+ /**
+ * To be used by macro flow to increment concurrency counter after update to it's structure was completed
+ */
+ public void incrementConcurrencyCounter() {
+ this.concurrencyCounter++;
+ }
+
+ /**
+ * Method to get concurrency counter data
+ *
+ * @return long value for the counter
+ */
+ @JsonIgnore
+ public long getConcurrencyCounter() {
+ return concurrencyCounter;
+ }
+
+}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java
index 7cbd565c77..b291765252 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java
@@ -21,66 +21,71 @@
package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* Abstract superclass for all individual decomposition resources
*
*/
-//@JsonIgnoreProperties
-public abstract class ResourceDecomposition extends JsonWrapper implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- protected String resourceType; // Enum of vnf or network or allotted resource
- private ModelInfo modelInfo;
-
- //private List modules;
- private ResourceInstance instanceData = new ResourceInstance();
-
- // GET and SET
- public ModelInfo getModelInfo() {
- return modelInfo;
- }
- public void setModelInfo(ModelInfo modelInfo) {
- this.modelInfo = modelInfo;
- }
-
- public ResourceInstance getInstanceData() {
- return instanceData;
- }
- public void setInstanceData(ResourceInstance instanceData) {
- this.instanceData = instanceData;
- }
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- //Utility methods
- @JsonIgnore
- public ModelInfo getResourceModel() {
- return modelInfo;
- }
- @JsonIgnore
- public String getResourceInstanceId() {
- return this.getInstanceData().getInstanceId();
- }
- @JsonIgnore
- public String getResourceInstanceName() {
- return this.getInstanceData().getInstanceName();
- }
-// @JsonIgnore
-// public String getResourceHomingSolution() {
-// }
-
- public void setResourceInstanceId(String newInstanceId){
- this.getInstanceData().setInstanceId(newInstanceId);
- }
- public void setResourceInstanceName(String newInstanceName){
- this.getInstanceData().setInstanceName(newInstanceName);
- }
-// @JsonIgnore
-// public String setResourceHomingSolution() {
-// }
+// @JsonIgnoreProperties
+public abstract class ResourceDecomposition extends JsonWrapper implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ protected String resourceType; // Enum of vnf or network or allotted resource
+ private ModelInfo modelInfo;
+
+ // private List modules;
+ private ResourceInstance instanceData = new ResourceInstance();
+
+ // GET and SET
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
+
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
+
+ public ResourceInstance getInstanceData() {
+ return instanceData;
+ }
+
+ public void setInstanceData(ResourceInstance instanceData) {
+ this.instanceData = instanceData;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ // Utility methods
+ @JsonIgnore
+ public ModelInfo getResourceModel() {
+ return modelInfo;
+ }
+
+ @JsonIgnore
+ public String getResourceInstanceId() {
+ return this.getInstanceData().getInstanceId();
+ }
+
+ @JsonIgnore
+ public String getResourceInstanceName() {
+ return this.getInstanceData().getInstanceName();
+ }
+ // @JsonIgnore
+ // public String getResourceHomingSolution() {
+ // }
+
+ public void setResourceInstanceId(String newInstanceId) {
+ this.getInstanceData().setInstanceId(newInstanceId);
+ }
+
+ public void setResourceInstanceName(String newInstanceName) {
+ this.getInstanceData().setInstanceName(newInstanceName);
+ }
+ // @JsonIgnore
+ // public String setResourceHomingSolution() {
+ // }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceInstance.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceInstance.java
index 085e278e11..2c29ff882d 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceInstance.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceInstance.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
@@ -30,36 +29,37 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
* @author cb645j
*
*/
-//@JsonIgnoreProperties
-//TODO update any existing references then remove this pointless class
+// @JsonIgnoreProperties
+// TODO update any existing references then remove this pointless class
@Deprecated
-public class ResourceInstance extends JsonWrapper implements Serializable {
+public class ResourceInstance extends JsonWrapper implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String instanceId;
+ private String instanceName;
- private static final long serialVersionUID = 1L;
- private String instanceId;
- private String instanceName;
+ public String getInstanceId() {
+ return instanceId;
+ }
+ /**
+ * This class and method is deprecated so use resourceId field in resource class instead
+ *
+ * @author cb645j
+ *
+ */
+ public void setInstanceId(String instanceId) {
+ this.instanceId = instanceId;
+ }
- public String getInstanceId() {
- return instanceId;
- }
+ public String getInstanceName() {
+ return instanceName;
+ }
- /**
- * This class and method is deprecated so use
- * resourceId field in resource class instead
- *
- * @author cb645j
- *
- */
- public void setInstanceId(String instanceId) {
- this.instanceId = instanceId;
- }
- public String getInstanceName() {
- return instanceName;
- }
- public void setInstanceName(String instanceName) {
- this.instanceName = instanceName;
- }
+ public void setInstanceName(String instanceName) {
+ this.instanceName = instanceName;
+ }
-} \ No newline at end of file
+}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceModelInfo.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceModelInfo.java
index af36fa01df..95ecd7ee85 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceModelInfo.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceModelInfo.java
@@ -22,37 +22,44 @@ package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
-public class ResourceModelInfo extends JsonWrapper implements Serializable{
-
- private static final long serialVersionUID = 1L;
- String resourceName;
- String resourceInvariantUuid;
- String resourceUuid;
- String resourceCustomizationUuid;
-
- public String getResourceName() {
- return resourceName;
- }
- public void setResourceName(String resourceName) {
- this.resourceName = resourceName;
- }
- public String getResourceInvariantUuid() {
- return resourceInvariantUuid;
- }
- public void setResourceInvariantUuid(String resourceInvariantUuid) {
- this.resourceInvariantUuid = resourceInvariantUuid;
- }
- public String getResourceUuid() {
- return resourceUuid;
- }
- public void setResourceUuid(String resourceUuid) {
- this.resourceUuid = resourceUuid;
- }
- public String getResourceCustomizationUuid() {
- return resourceCustomizationUuid;
- }
- public void setResourceCustomizationUuid(String resourceCustomizationUuid) {
- this.resourceCustomizationUuid = resourceCustomizationUuid;
- }
+public class ResourceModelInfo extends JsonWrapper implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+ String resourceName;
+ String resourceInvariantUuid;
+ String resourceUuid;
+ String resourceCustomizationUuid;
+
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
+
+ public String getResourceInvariantUuid() {
+ return resourceInvariantUuid;
+ }
+
+ public void setResourceInvariantUuid(String resourceInvariantUuid) {
+ this.resourceInvariantUuid = resourceInvariantUuid;
+ }
+
+ public String getResourceUuid() {
+ return resourceUuid;
+ }
+
+ public void setResourceUuid(String resourceUuid) {
+ this.resourceUuid = resourceUuid;
+ }
+
+ public String getResourceCustomizationUuid() {
+ return resourceCustomizationUuid;
+ }
+
+ public void setResourceCustomizationUuid(String resourceCustomizationUuid) {
+ this.resourceCustomizationUuid = resourceCustomizationUuid;
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java
index 6147822d31..a30d0df825 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java
@@ -22,5 +22,5 @@ package org.onap.so.bpmn.core.domain;
public enum ResourceType {
- VNF, NETWORK, MODULE, ALLOTTED_RESOURCE, CONFIGURATION // etc.
-} \ No newline at end of file
+ VNF, NETWORK, MODULE, ALLOTTED_RESOURCE, CONFIGURATION // etc.
+}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/RollbackData.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/RollbackData.java
index 5be0fb4f59..633736a25a 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/RollbackData.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/RollbackData.java
@@ -24,24 +24,24 @@ import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
-public class RollbackData implements Serializable{
+public class RollbackData implements Serializable {
- private static final long serialVersionUID = -4811571658272937718L;
+ private static final long serialVersionUID = -4811571658272937718L;
- private String requestId;
- private Map<String, String> additionalData = new HashMap<String, String>();
+ private String requestId;
+ private Map<String, String> additionalData = new HashMap<String, String>();
- public String getRequestId(){
- return requestId;
- }
+ public String getRequestId() {
+ return requestId;
+ }
- public void setRequestId(String requestId){
- this.requestId = requestId;
- }
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
- public Map<String, String> getAdditionalData(){
- return additionalData;
- }
+ public Map<String, String> getAdditionalData() {
+ return additionalData;
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java
index 5e7a4796c4..0e03989e64 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java
@@ -26,7 +26,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -36,509 +35,556 @@ import org.onap.so.bpmn.core.json.JsonDecomposingException;
-
/**
- * Service Decomposition Structure
- * This Java object contains service information:
- * - Service model info
- * - Service type and role
- * - list of VNF resource's decompositon
- * - list of network resource's decompositon
- * - list of allotted resource's decompositon
+ * Service Decomposition Structure This Java object contains service information: - Service model info - Service type
+ * and role - list of VNF resource's decompositon - list of network resource's decompositon - list of allotted
+ * resource's decompositon
*/
@JsonRootName(value = "serviceResources")
-//@JsonTypeInfo(include=As.WRAPPER_OBJECT, use=Id.NAME)
+// @JsonTypeInfo(include=As.WRAPPER_OBJECT, use=Id.NAME)
public class ServiceDecomposition extends JsonWrapper implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @JsonProperty("modelInfo")
- private ModelInfo modelInfo;
- @JsonProperty("serviceType")
- private String serviceType;
- @JsonProperty("serviceRole")
- private String serviceRole;
- private ServiceInstance serviceInstance;
- private Request request;
- private Customer customer;
- private String callbackURN;
- private String sdncVersion;
- @JsonProperty("project")
- private Project project;
- @JsonProperty("owningEntity")
- private OwningEntity owningEntity;
- @JsonProperty("serviceVnfs")
- private List <VnfResource> vnfResources;
- @JsonProperty("serviceNetworks")
- private List <NetworkResource> networkResources;
- @JsonProperty("serviceAllottedResources")
- private List <AllottedResource> allottedResources;
- @JsonProperty("configResource")
- private List <ConfigResource> configResources;
-
- public ServiceDecomposition () {
- super();
- }
-
- public ServiceDecomposition (String catalogRestOutput) throws JsonDecomposingException {
- ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.jsonToServiceDecomposition(catalogRestOutput);
- this.modelInfo = serviceDecomposition.getModelInfo();
- this.vnfResources = serviceDecomposition.getVnfResources();
- this.allottedResources = serviceDecomposition.getAllottedResources();
- this.networkResources = serviceDecomposition.getNetworkResources();
- this.serviceRole = serviceDecomposition.getServiceRole();
- this.serviceType = serviceDecomposition.getServiceType();
- this.configResources = serviceDecomposition.getConfigResources();
- }
-
- /**
- * Constructor taking Catalog DB Adapter REST output (serviceResources model) + service Instance ID
- *
- * @param catalogRestOutput
- * @param serviceInstanceId
- */
- public ServiceDecomposition (String catalogRestOutput, String serviceInstanceId) throws JsonDecomposingException {
- ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.jsonToServiceDecomposition(catalogRestOutput);
- this.modelInfo = serviceDecomposition.getModelInfo();
- this.vnfResources = serviceDecomposition.getVnfResources();
- this.allottedResources = serviceDecomposition.getAllottedResources();
- this.configResources = serviceDecomposition.getConfigResources();
- this.networkResources = serviceDecomposition.getNetworkResources();
-
- this.serviceRole = serviceDecomposition.getServiceRole();
- this.serviceType = serviceDecomposition.getServiceType();
-
- this.serviceInstance = new ServiceInstance();
- this.serviceInstance.setInstanceId(serviceInstanceId);
-
- this.project = serviceDecomposition.getProject();
- this.owningEntity = serviceDecomposition.getOwningEntity();
- }
-
- /**
- * Constructor taking a Service Decomposition JSON serialization
- * @param catalogRestOutput
- * @param serviceInstanceId
- */
- public ServiceDecomposition (JSONObject jsonServiceDecomposition, String serviceInstanceId) {
- //TODO provide constructor implementation
-
- }
-
- //*****
- //GET and SET section
- /**
- * Return just the service model portion of the Service Decomposition as a Java object.
- * The service model object should support retrieval as JSON string that is formatted correctly for sending serviceModelInfo to Building Blocks.
- * @return
- */
- public ModelInfo getModelInfo() {
- return modelInfo;
- }
- public void setModelInfo(ModelInfo modelInfo) {
- this.modelInfo = modelInfo;
- }
- public ServiceInstance getServiceInstance() {
- return serviceInstance;
- }
- public void setServiceInstance(ServiceInstance serviceInstance) {
- this.serviceInstance = serviceInstance;
- }
- public Project getProject() {
- return project;
- }
- public OwningEntity getOwningEntity() {
- return owningEntity;
- }
- public void setProject(Project project) {
- this.project = project;
- }
- public void setOwningEntity(OwningEntity owningEntity) {
- this.owningEntity = owningEntity;
- }
- public List<VnfResource> getVnfResources() {
- return vnfResources;
- }
- public void setVnfResources(List<VnfResource> vnfResources) {
- this.vnfResources = vnfResources;
- }
- public void setConfigResources(List<ConfigResource> configResources) {
- this.configResources = configResources;
- }
- public List<ConfigResource> getConfigResources() {
- return configResources;
- }
- public void setNetworkResources(List<NetworkResource> networkResources) {
- this.networkResources = networkResources;
- }
- public List<NetworkResource> getNetworkResources() {
- return networkResources;
- }
- public List<AllottedResource> getAllottedResources() {
- return allottedResources;
- }
- public void setAllottedResources(List<AllottedResource> allottedResources) {
- this.allottedResources = allottedResources;
- }
- public String getServiceType() {
- return serviceType;
- }
-
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
-
- public String getServiceRole() {
- return serviceRole;
- }
-
- public void setServiceRole(String serviceRole) {
- this.serviceRole = serviceRole;
- }
- public Request getRequest() {
- return request;
- }
-
- public void setRequest(Request request) {
- this.request = request;
- }
- public Customer getCustomer() {
- return customer;
- }
- public void setCustomer(Customer customer) {
- this.customer = customer;
- }
- public String getCallbackURN() {
- return callbackURN;
- }
-
- public void setCallbackURN(String callbackURN) {
- this.callbackURN = callbackURN;
- }
- public String getSdncVersion() {
- return sdncVersion;
- }
-
- public void setSdncVersion(String sdncVersion) {
- this.sdncVersion = sdncVersion;
- }
-
- //*****
-
- //*****
- //Access methods
-
-
- /**
- * This method returns one combined list of Resources of All Types
- * @return
- */
- @JsonIgnore
- public List<Resource> getServiceResources(){
- ArrayList serviceResources = new ArrayList();
- if(this.getAllottedResources() != null){
- serviceResources.addAll(this.getAllottedResources());
- }
- if(this.getNetworkResources() != null){
- serviceResources.addAll(this.getNetworkResources());
- }
- if(this.getVnfResources() != null){
- serviceResources.addAll(this.getVnfResources());
- }
- if(this.getConfigResources() != null){
- serviceResources.addAll(this.getConfigResources());
- }
- return serviceResources;
- }
-
- /**
- * This method returns String representation of one combined list of Resources of All Types
- */
- @JsonIgnore
- public String getServiceResourcesJsonString() {
- return getServiceNetworksJson() +
- getServiceVnfsJson() +
- getServiceAllottedResourcesJson() +
- getServiceConfigResourcesJson();
- }
-
- /**
- * Returns a JSON list of all Network Resource structures (i.e. the serialized NetworkDecomposition objects).
- * @return
- */
- @JsonIgnore
- public String getServiceNetworksJson(){
- return listToJson(this.getNetworkResources());
- }
- /**
- * Returns a JSON list of all VnfResource structures (i.e. the serialized VnfResource objects).
- * @return
- */
- @JsonIgnore
- public String getServiceVnfsJson(){
- return listToJson(this.getVnfResources());
- }
- /**
- * Returns a JSON list of all Allotted Resource structures (i.e. the serialized AllottedResource objects).
- * @return
- */
- @JsonIgnore
- public String getServiceAllottedResourcesJson(){
- return listToJson(this.getAllottedResources());
- }
- /**
- * Returns a JSON list of all Config Resource structures (i.e. the serialized ConfigResource objects).
- * @return
- */
- @JsonIgnore
- public String getServiceConfigResourcesJson(){
- return listToJson(this.getConfigResources());
- }
-
- //TODO - define Resource Object ID
- @JsonIgnore
- public String getVnfResource(String resourceObjectId) {
+ private static final long serialVersionUID = 1L;
+
+ @JsonProperty("modelInfo")
+ private ModelInfo modelInfo;
+ @JsonProperty("serviceType")
+ private String serviceType;
+ @JsonProperty("serviceRole")
+ private String serviceRole;
+ private ServiceInstance serviceInstance;
+ private Request request;
+ private Customer customer;
+ private String callbackURN;
+ private String sdncVersion;
+ @JsonProperty("project")
+ private Project project;
+ @JsonProperty("owningEntity")
+ private OwningEntity owningEntity;
+ @JsonProperty("serviceVnfs")
+ private List<VnfResource> vnfResources;
+ @JsonProperty("serviceNetworks")
+ private List<NetworkResource> networkResources;
+ @JsonProperty("serviceAllottedResources")
+ private List<AllottedResource> allottedResources;
+ @JsonProperty("configResource")
+ private List<ConfigResource> configResources;
+
+ public ServiceDecomposition() {
+ super();
+ }
+
+ public ServiceDecomposition(String catalogRestOutput) throws JsonDecomposingException {
+ ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.jsonToServiceDecomposition(catalogRestOutput);
+ this.modelInfo = serviceDecomposition.getModelInfo();
+ this.vnfResources = serviceDecomposition.getVnfResources();
+ this.allottedResources = serviceDecomposition.getAllottedResources();
+ this.networkResources = serviceDecomposition.getNetworkResources();
+ this.serviceRole = serviceDecomposition.getServiceRole();
+ this.serviceType = serviceDecomposition.getServiceType();
+ this.configResources = serviceDecomposition.getConfigResources();
+ }
+
+ /**
+ * Constructor taking Catalog DB Adapter REST output (serviceResources model) + service Instance ID
+ *
+ * @param catalogRestOutput
+ * @param serviceInstanceId
+ */
+ public ServiceDecomposition(String catalogRestOutput, String serviceInstanceId) throws JsonDecomposingException {
+ ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.jsonToServiceDecomposition(catalogRestOutput);
+ this.modelInfo = serviceDecomposition.getModelInfo();
+ this.vnfResources = serviceDecomposition.getVnfResources();
+ this.allottedResources = serviceDecomposition.getAllottedResources();
+ this.configResources = serviceDecomposition.getConfigResources();
+ this.networkResources = serviceDecomposition.getNetworkResources();
+
+ this.serviceRole = serviceDecomposition.getServiceRole();
+ this.serviceType = serviceDecomposition.getServiceType();
+
+ this.serviceInstance = new ServiceInstance();
+ this.serviceInstance.setInstanceId(serviceInstanceId);
+
+ this.project = serviceDecomposition.getProject();
+ this.owningEntity = serviceDecomposition.getOwningEntity();
+ }
+
+ /**
+ * Constructor taking a Service Decomposition JSON serialization
+ *
+ * @param catalogRestOutput
+ * @param serviceInstanceId
+ */
+ public ServiceDecomposition(JSONObject jsonServiceDecomposition, String serviceInstanceId) {
+ // TODO provide constructor implementation
+
+ }
+
+ // *****
+ // GET and SET section
+ /**
+ * Return just the service model portion of the Service Decomposition as a Java object. The service model object
+ * should support retrieval as JSON string that is formatted correctly for sending serviceModelInfo to Building
+ * Blocks.
+ *
+ * @return
+ */
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
+
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
+
+ public ServiceInstance getServiceInstance() {
+ return serviceInstance;
+ }
+
+ public void setServiceInstance(ServiceInstance serviceInstance) {
+ this.serviceInstance = serviceInstance;
+ }
+
+ public Project getProject() {
+ return project;
+ }
+
+ public OwningEntity getOwningEntity() {
+ return owningEntity;
+ }
+
+ public void setProject(Project project) {
+ this.project = project;
+ }
+
+ public void setOwningEntity(OwningEntity owningEntity) {
+ this.owningEntity = owningEntity;
+ }
+
+ public List<VnfResource> getVnfResources() {
+ return vnfResources;
+ }
+
+ public void setVnfResources(List<VnfResource> vnfResources) {
+ this.vnfResources = vnfResources;
+ }
+
+ public void setConfigResources(List<ConfigResource> configResources) {
+ this.configResources = configResources;
+ }
+
+ public List<ConfigResource> getConfigResources() {
+ return configResources;
+ }
+
+ public void setNetworkResources(List<NetworkResource> networkResources) {
+ this.networkResources = networkResources;
+ }
+
+ public List<NetworkResource> getNetworkResources() {
+ return networkResources;
+ }
+
+ public List<AllottedResource> getAllottedResources() {
+ return allottedResources;
+ }
+
+ public void setAllottedResources(List<AllottedResource> allottedResources) {
+ this.allottedResources = allottedResources;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getServiceRole() {
+ return serviceRole;
+ }
+
+ public void setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ }
+
+ public Request getRequest() {
+ return request;
+ }
+
+ public void setRequest(Request request) {
+ this.request = request;
+ }
+
+ public Customer getCustomer() {
+ return customer;
+ }
+
+ public void setCustomer(Customer customer) {
+ this.customer = customer;
+ }
+
+ public String getCallbackURN() {
+ return callbackURN;
+ }
+
+ public void setCallbackURN(String callbackURN) {
+ this.callbackURN = callbackURN;
+ }
+
+ public String getSdncVersion() {
+ return sdncVersion;
+ }
+
+ public void setSdncVersion(String sdncVersion) {
+ this.sdncVersion = sdncVersion;
+ }
+
+ // *****
+
+ // *****
+ // Access methods
+
+
+ /**
+ * This method returns one combined list of Resources of All Types
+ *
+ * @return
+ */
+ @JsonIgnore
+ public List<Resource> getServiceResources() {
+ ArrayList serviceResources = new ArrayList();
+ if (this.getAllottedResources() != null) {
+ serviceResources.addAll(this.getAllottedResources());
+ }
+ if (this.getNetworkResources() != null) {
+ serviceResources.addAll(this.getNetworkResources());
+ }
+ if (this.getVnfResources() != null) {
+ serviceResources.addAll(this.getVnfResources());
+ }
+ if (this.getConfigResources() != null) {
+ serviceResources.addAll(this.getConfigResources());
+ }
+ return serviceResources;
+ }
+
+ /**
+ * This method returns String representation of one combined list of Resources of All Types
+ */
+ @JsonIgnore
+ public String getServiceResourcesJsonString() {
+ return getServiceNetworksJson() + getServiceVnfsJson() + getServiceAllottedResourcesJson()
+ + getServiceConfigResourcesJson();
+ }
+
+ /**
+ * Returns a JSON list of all Network Resource structures (i.e. the serialized NetworkDecomposition objects).
+ *
+ * @return
+ */
+ @JsonIgnore
+ public String getServiceNetworksJson() {
+ return listToJson(this.getNetworkResources());
+ }
+
+ /**
+ * Returns a JSON list of all VnfResource structures (i.e. the serialized VnfResource objects).
+ *
+ * @return
+ */
+ @JsonIgnore
+ public String getServiceVnfsJson() {
+ return listToJson(this.getVnfResources());
+ }
+
+ /**
+ * Returns a JSON list of all Allotted Resource structures (i.e. the serialized AllottedResource objects).
+ *
+ * @return
+ */
+ @JsonIgnore
+ public String getServiceAllottedResourcesJson() {
+ return listToJson(this.getAllottedResources());
+ }
+
+ /**
+ * Returns a JSON list of all Config Resource structures (i.e. the serialized ConfigResource objects).
+ *
+ * @return
+ */
+ @JsonIgnore
+ public String getServiceConfigResourcesJson() {
+ return listToJson(this.getConfigResources());
+ }
+
+ // TODO - define Resource Object ID
+ @JsonIgnore
+ public String getVnfResource(String resourceObjectId) {
for (Resource resource : getServiceResources()) {
- //resource.getModelInfo().getModelInvariantId();
+ // resource.getModelInfo().getModelInvariantId();
if ("extracted information".equals(resourceObjectId)) {
return resource.toJsonString();
}
}
- return "";
- }
-
- //Methods to add Resource to the list
- /**
- * Add VNF resource to the list
- * @param vnfResource
- */
- public void addVnfResource(Resource vnfResource) {
- if (vnfResources == null){
- vnfResources = new ArrayList<>();
- }
- this.vnfResources.add((VnfResource)vnfResource);
- }
- /**
- * Add Network resource to the list
- * @param networkResource
- */
- public void addNetworkResource(Resource networkResource) {
- if (networkResources == null){
- networkResources = new ArrayList<>();
- }
- this.networkResources.add((NetworkResource)networkResource);
- }
- /**
- * Add Allotted resource to the list
- * @param allottedResource
- */
- public void addAllottedResource(Resource allottedResource) {
- if (allottedResources == null){
- allottedResources = new ArrayList<>();
- }
- this.allottedResources.add((AllottedResource)allottedResource);
- }
- /**
- * Add Config resource to the list
- * @param allottedResource
- */
- public void addConfigResource(Resource configResource) {
- if (configResources == null){
- configResources = new ArrayList<>();
- }
- this.configResources.add((ConfigResource)configResource);
- }
- /**
- * Add resource to the list
- * Given a ResourceDecomposition (subclass) object, add it to the Service Decomposition (in the appropriate category, e.g. as a VNF, Network, or Allotted Resource).
- * As dependencies are not currently supported, add it to the end of any ordered lists.
- * @param resource
- */
- public void addResource(Resource resource) {
- //create resource based upon type
- switch (resource.resourceType) {
- case VNF:
- this.addVnfResource(resource);
- break;
- case NETWORK:
- this.addNetworkResource(resource);
- break;
- case ALLOTTED_RESOURCE:
- this.addAllottedResource(resource);
- break;
- case CONFIGURATION:
- this.addConfigResource(resource);
- break;
- default:
- throw new IllegalArgumentException("Invalid resource type: " + resource.resourceType);
- }
- }
-
- /**
- * Add resource to the list
- * @param jsonResource
- */
- public void addVnfResource(String jsonResource) throws JsonDecomposingException {
- VnfResource vnfResource = null;
- vnfResource = DecomposeJsonUtil.jsonToVnfResource(jsonResource);
- this.addVnfResource(vnfResource);
- }
- /**
- * Add resource to the list
- * @param jsonResource
- */
- public void addNetworkResource(String jsonResource) throws JsonDecomposingException {
- NetworkResource networkResource = null;
- networkResource = DecomposeJsonUtil.jsonToNetworkResource(jsonResource);
- this.addNetworkResource(networkResource);
- }
- /**
- * Add resource to the list
- * @param Resource
- */
- public void addAllottedResource(String jsonResource) throws JsonDecomposingException {
- AllottedResource allottedResource = null;
- allottedResource = DecomposeJsonUtil.jsonToAllottedResource(jsonResource);
- this.addAllottedResource(allottedResource);
- }
- /**
- * Add resource to the list
- * @param Resource
- */
- public void addConfigResource(String jsonResource) throws JsonDecomposingException {
- ConfigResource configResource = null;
- configResource = DecomposeJsonUtil.jsonToConfigResource(jsonResource);
- this.addConfigResource(configResource);
- }
- /**
- * Given a ResourceDecomposition (subclass) object, locate it in the Service Decomposition by its unique ID, and replace the current version with the new one.
- * This method should support concurrency control via an auto-incrementing field in the ResourceDecomposition class.
- * @param newResource
- * @return TRUE if replacement was a success
- */
- public boolean replaceResource(Resource newResource){
- List resources = getResourceList(newResource);
-
- boolean result = false;
- for (Resource resource : (Iterable<Resource>) resources) {
- System.out.println("resource found");
- if (resource.resourceType == newResource.resourceType) {
- System.out.println("resource type matches");
- if (resource.getResourceId().equalsIgnoreCase(newResource.getResourceId())) {
- System.out.println("resource id matches");
- //returns TRUE if replacement is a success
- result = Collections.replaceAll(resources, resource, newResource);
- }
- }
- }
- return result;
- }
-
- /**
- * Given a ResourceDecomposition as a JSON string, locate it in the Service Decomposition by its unique ID,
- * and replace the current version with the new one.
- * @param jsonString
- * @return
- */
- public boolean replaceResource(String jsonString){
- //TODO: define unique ID for the Resource!
- return false;
- }
-
- /**
- * Given a resource object ID, locate it in the Service Decomposition by its unique ID, and delete it.
- * @param resource
- * @return TRUE if delete was a success
- */
- public boolean deleteResource(Resource resource){
- List serviceResourceList = getResourceList(resource);
- for (Resource item : (Iterable<Resource>) serviceResourceList) {
- if (item.resourceType == resource.resourceType) {
- if (item.getResourceId().equalsIgnoreCase(resource.getResourceId())) {
- //returns TRUE if replacement is a success
- return serviceResourceList.remove(resource);
- }
- }
- }
-
- return false;
- }
-
- /**
- * Generic method to get List of Resource objects based on input resource's resourceType
- * @param resource
- * @return List matching the resourceType of resource
- */
- public List getResourceList(Resource resource) {
- List resourceList;
- switch(resource.getResourceType()) {
- case VNF:
- resourceList = getVnfResources();
- break;
- case NETWORK:
- resourceList = getNetworkResources();
- break;
- case ALLOTTED_RESOURCE:
- resourceList = getAllottedResources();
- break;
- case CONFIGURATION:
- resourceList = getConfigResources();
- break;
- default:
- resourceList = new ArrayList<>();
- }
- return resourceList;
- }
-
- /**
- * Generic method to set List of ResourceDecomposition objects
- * @param resources
- * @return
- */
- public boolean setResourceList(List<Resource> resources){
- if(resources != null && !resources.isEmpty()) {
- //create resource based upon type
- switch (resources.get(0).resourceType) {
- case VNF:
- this.setVnfResources((List<VnfResource>)(List<?>)resources);
- break;
- case NETWORK:
- this.setNetworkResources((List<NetworkResource>)(List<?>)resources);
- break;
- case ALLOTTED_RESOURCE:
- this.setAllottedResources((List<AllottedResource>)(List<?>)resources);
- break;
- case CONFIGURATION:
- this.setConfigResources((List<ConfigResource>)(List<?>)resources);
- break;
- default:
- throw new IllegalArgumentException("Invalid resource type: " + resources.get(0).resourceType);
- }
- }
-
- return false;
- }
-
- /**
- *
- * This method locates and returns a resource in a given
- * Service Decomposition object by its unique resource id.
- * Returns null if resource doesn't exist.
- *
- * @param resourceId - id of the resource
- * @return resource
- */
- @JsonIgnore
- public Resource getServiceResource(String resourceId){
- List<Resource> resources = getServiceResources();
- for (Resource resource : resources) {
- if (resource.getResourceId().equalsIgnoreCase(resourceId)) {
- //match
- return resource;
- }
- }
- return null;
- }
+ return "";
+ }
+
+ // Methods to add Resource to the list
+ /**
+ * Add VNF resource to the list
+ *
+ * @param vnfResource
+ */
+ public void addVnfResource(Resource vnfResource) {
+ if (vnfResources == null) {
+ vnfResources = new ArrayList<>();
+ }
+ this.vnfResources.add((VnfResource) vnfResource);
+ }
+
+ /**
+ * Add Network resource to the list
+ *
+ * @param networkResource
+ */
+ public void addNetworkResource(Resource networkResource) {
+ if (networkResources == null) {
+ networkResources = new ArrayList<>();
+ }
+ this.networkResources.add((NetworkResource) networkResource);
+ }
+
+ /**
+ * Add Allotted resource to the list
+ *
+ * @param allottedResource
+ */
+ public void addAllottedResource(Resource allottedResource) {
+ if (allottedResources == null) {
+ allottedResources = new ArrayList<>();
+ }
+ this.allottedResources.add((AllottedResource) allottedResource);
+ }
+
+ /**
+ * Add Config resource to the list
+ *
+ * @param allottedResource
+ */
+ public void addConfigResource(Resource configResource) {
+ if (configResources == null) {
+ configResources = new ArrayList<>();
+ }
+ this.configResources.add((ConfigResource) configResource);
+ }
+
+ /**
+ * Add resource to the list Given a ResourceDecomposition (subclass) object, add it to the Service Decomposition (in
+ * the appropriate category, e.g. as a VNF, Network, or Allotted Resource). As dependencies are not currently
+ * supported, add it to the end of any ordered lists.
+ *
+ * @param resource
+ */
+ public void addResource(Resource resource) {
+ // create resource based upon type
+ switch (resource.resourceType) {
+ case VNF:
+ this.addVnfResource(resource);
+ break;
+ case NETWORK:
+ this.addNetworkResource(resource);
+ break;
+ case ALLOTTED_RESOURCE:
+ this.addAllottedResource(resource);
+ break;
+ case CONFIGURATION:
+ this.addConfigResource(resource);
+ break;
+ default:
+ throw new IllegalArgumentException("Invalid resource type: " + resource.resourceType);
+ }
+ }
+
+ /**
+ * Add resource to the list
+ *
+ * @param jsonResource
+ */
+ public void addVnfResource(String jsonResource) throws JsonDecomposingException {
+ VnfResource vnfResource = null;
+ vnfResource = DecomposeJsonUtil.jsonToVnfResource(jsonResource);
+ this.addVnfResource(vnfResource);
+ }
+
+ /**
+ * Add resource to the list
+ *
+ * @param jsonResource
+ */
+ public void addNetworkResource(String jsonResource) throws JsonDecomposingException {
+ NetworkResource networkResource = null;
+ networkResource = DecomposeJsonUtil.jsonToNetworkResource(jsonResource);
+ this.addNetworkResource(networkResource);
+ }
+
+ /**
+ * Add resource to the list
+ *
+ * @param Resource
+ */
+ public void addAllottedResource(String jsonResource) throws JsonDecomposingException {
+ AllottedResource allottedResource = null;
+ allottedResource = DecomposeJsonUtil.jsonToAllottedResource(jsonResource);
+ this.addAllottedResource(allottedResource);
+ }
+
+ /**
+ * Add resource to the list
+ *
+ * @param Resource
+ */
+ public void addConfigResource(String jsonResource) throws JsonDecomposingException {
+ ConfigResource configResource = null;
+ configResource = DecomposeJsonUtil.jsonToConfigResource(jsonResource);
+ this.addConfigResource(configResource);
+ }
+
+ /**
+ * Given a ResourceDecomposition (subclass) object, locate it in the Service Decomposition by its unique ID, and
+ * replace the current version with the new one. This method should support concurrency control via an
+ * auto-incrementing field in the ResourceDecomposition class.
+ *
+ * @param newResource
+ * @return TRUE if replacement was a success
+ */
+ public boolean replaceResource(Resource newResource) {
+ List resources = getResourceList(newResource);
+
+ boolean result = false;
+ for (Resource resource : (Iterable<Resource>) resources) {
+ System.out.println("resource found");
+ if (resource.resourceType == newResource.resourceType) {
+ System.out.println("resource type matches");
+ if (resource.getResourceId().equalsIgnoreCase(newResource.getResourceId())) {
+ System.out.println("resource id matches");
+ // returns TRUE if replacement is a success
+ result = Collections.replaceAll(resources, resource, newResource);
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Given a ResourceDecomposition as a JSON string, locate it in the Service Decomposition by its unique ID, and
+ * replace the current version with the new one.
+ *
+ * @param jsonString
+ * @return
+ */
+ public boolean replaceResource(String jsonString) {
+ // TODO: define unique ID for the Resource!
+ return false;
+ }
+
+ /**
+ * Given a resource object ID, locate it in the Service Decomposition by its unique ID, and delete it.
+ *
+ * @param resource
+ * @return TRUE if delete was a success
+ */
+ public boolean deleteResource(Resource resource) {
+ List serviceResourceList = getResourceList(resource);
+ for (Resource item : (Iterable<Resource>) serviceResourceList) {
+ if (item.resourceType == resource.resourceType) {
+ if (item.getResourceId().equalsIgnoreCase(resource.getResourceId())) {
+ // returns TRUE if replacement is a success
+ return serviceResourceList.remove(resource);
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Generic method to get List of Resource objects based on input resource's resourceType
+ *
+ * @param resource
+ * @return List matching the resourceType of resource
+ */
+ public List getResourceList(Resource resource) {
+ List resourceList;
+ switch (resource.getResourceType()) {
+ case VNF:
+ resourceList = getVnfResources();
+ break;
+ case NETWORK:
+ resourceList = getNetworkResources();
+ break;
+ case ALLOTTED_RESOURCE:
+ resourceList = getAllottedResources();
+ break;
+ case CONFIGURATION:
+ resourceList = getConfigResources();
+ break;
+ default:
+ resourceList = new ArrayList<>();
+ }
+ return resourceList;
+ }
+
+ /**
+ * Generic method to set List of ResourceDecomposition objects
+ *
+ * @param resources
+ * @return
+ */
+ public boolean setResourceList(List<Resource> resources) {
+ if (resources != null && !resources.isEmpty()) {
+ // create resource based upon type
+ switch (resources.get(0).resourceType) {
+ case VNF:
+ this.setVnfResources((List<VnfResource>) (List<?>) resources);
+ break;
+ case NETWORK:
+ this.setNetworkResources((List<NetworkResource>) (List<?>) resources);
+ break;
+ case ALLOTTED_RESOURCE:
+ this.setAllottedResources((List<AllottedResource>) (List<?>) resources);
+ break;
+ case CONFIGURATION:
+ this.setConfigResources((List<ConfigResource>) (List<?>) resources);
+ break;
+ default:
+ throw new IllegalArgumentException("Invalid resource type: " + resources.get(0).resourceType);
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ *
+ * This method locates and returns a resource in a given Service Decomposition object by its unique resource id.
+ * Returns null if resource doesn't exist.
+ *
+ * @param resourceId - id of the resource
+ * @return resource
+ */
+ @JsonIgnore
+ public Resource getServiceResource(String resourceId) {
+ List<Resource> resources = getServiceResources();
+ for (Resource resource : resources) {
+ if (resource.getResourceId().equalsIgnoreCase(resourceId)) {
+ // match
+ return resource;
+ }
+ }
+ return null;
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceInstance.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceInstance.java
index 5cdbbcb7c9..b0b837b3b9 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceInstance.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceInstance.java
@@ -22,14 +22,12 @@ package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
/**
- * This class is used to store instance
- * data of services aka ServiceDecomposition
+ * This class is used to store instance data of services aka ServiceDecomposition
*
* @author cb645j
*
@@ -37,96 +35,118 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ServiceInstance extends JsonWrapper implements Serializable {
- private static final long serialVersionUID = 1L;
- private String instanceId;
- private String instanceName;
- private String orchestrationStatus;
- private Configuration configuration;
- private String serviceType;
- private String serviceRole;
- private String serviceId;
- private ModelInfo modelInfo;
- private String environmentContext;
- private String workloadContext;
- private Map serviceParams;
- private Customer customer = new Customer();
- private String e2eVpnKey;
-
- public String getServiceType() {
- return serviceType;
- }
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
- public String getServiceId() {
- return serviceId;
- }
- public void setServiceId(String serviceId) {
- this.serviceId = serviceId;
- }
- public Map getServiceParams() {
- return serviceParams;
- }
- public void setServiceParams(Map serviceParams) {
- this.serviceParams = serviceParams;
- }
- public String getInstanceId() {
- return instanceId;
- }
- public void setInstanceId(String instanceId) {
- this.instanceId = instanceId;
- }
- public String getInstanceName() {
- return instanceName;
- }
- public void setInstanceName(String instanceName) {
- this.instanceName = instanceName;
- }
- public String getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(String orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public Configuration getConfiguration() {
- return configuration;
- }
- public void setConfiguration(Configuration configuration) {
- this.configuration = configuration;
- }
- public ModelInfo getModelInfo() {
- return modelInfo;
- }
- public void setModelInfo(ModelInfo modelInfo) {
- this.modelInfo = modelInfo;
- }
- public String getEnvironmentContext() {
- return environmentContext;
- }
- public void setEnvironmentContext(String environmentContext) {
- this.environmentContext = environmentContext;
- }
- public String getWorkloadContext() {
- return workloadContext;
- }
- public void setWorkloadContext(String workloadContext) {
- this.workloadContext = workloadContext;
- }
- public String getServiceRole() {
- return serviceRole;
- }
- public void setServiceRole(String serviceRole) {
- this.serviceRole = serviceRole;
- }
- public Customer getCustomer(){
- return customer;
- }
-
- public String getE2eVpnKey(){
- return e2eVpnKey;
- }
-
- public void setE2eVpnKey(String e2eVpnKey){
- this.e2eVpnKey = e2eVpnKey;
- }
+ private static final long serialVersionUID = 1L;
+ private String instanceId;
+ private String instanceName;
+ private String orchestrationStatus;
+ private Configuration configuration;
+ private String serviceType;
+ private String serviceRole;
+ private String serviceId;
+ private ModelInfo modelInfo;
+ private String environmentContext;
+ private String workloadContext;
+ private Map serviceParams;
+ private Customer customer = new Customer();
+ private String e2eVpnKey;
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getServiceId() {
+ return serviceId;
+ }
+
+ public void setServiceId(String serviceId) {
+ this.serviceId = serviceId;
+ }
+
+ public Map getServiceParams() {
+ return serviceParams;
+ }
+
+ public void setServiceParams(Map serviceParams) {
+ this.serviceParams = serviceParams;
+ }
+
+ public String getInstanceId() {
+ return instanceId;
+ }
+
+ public void setInstanceId(String instanceId) {
+ this.instanceId = instanceId;
+ }
+
+ public String getInstanceName() {
+ return instanceName;
+ }
+
+ public void setInstanceName(String instanceName) {
+ this.instanceName = instanceName;
+ }
+
+ public String getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(String orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public Configuration getConfiguration() {
+ return configuration;
+ }
+
+ public void setConfiguration(Configuration configuration) {
+ this.configuration = configuration;
+ }
+
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
+
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
+
+ public String getEnvironmentContext() {
+ return environmentContext;
+ }
+
+ public void setEnvironmentContext(String environmentContext) {
+ this.environmentContext = environmentContext;
+ }
+
+ public String getWorkloadContext() {
+ return workloadContext;
+ }
+
+ public void setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
+
+ public String getServiceRole() {
+ return serviceRole;
+ }
+
+ public void setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ }
+
+ public Customer getCustomer() {
+ return customer;
+ }
+
+ public String getE2eVpnKey() {
+ return e2eVpnKey;
+ }
+
+ public void setE2eVpnKey(String e2eVpnKey) {
+ this.e2eVpnKey = e2eVpnKey;
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Subscriber.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Subscriber.java
index e9028ded17..620d8311e7 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Subscriber.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Subscriber.java
@@ -24,46 +24,46 @@ import java.io.Serializable;
public class Subscriber implements Serializable {
- private static final long serialVersionUID = -2416018315129127022L;
- private String globalId;
- private String name;
- private String commonSiteId;
+ private static final long serialVersionUID = -2416018315129127022L;
+ private String globalId;
+ private String name;
+ private String commonSiteId;
- public Subscriber(String globalId, String name, String commonSiteId){
- super();
- this.globalId = globalId;
- this.name = name;
- this.commonSiteId = commonSiteId;
- }
+ public Subscriber(String globalId, String name, String commonSiteId) {
+ super();
+ this.globalId = globalId;
+ this.name = name;
+ this.commonSiteId = commonSiteId;
+ }
- public String getGlobalId(){
- return globalId;
- }
+ public String getGlobalId() {
+ return globalId;
+ }
- public void setGlobalId(String globalId){
- this.globalId = globalId;
- }
+ public void setGlobalId(String globalId) {
+ this.globalId = globalId;
+ }
- public String getName(){
- return name;
- }
+ public String getName() {
+ return name;
+ }
- public void setName(String name){
- this.name = name;
- }
+ public void setName(String name) {
+ this.name = name;
+ }
- public String getCommonSiteId(){
- return commonSiteId;
- }
+ public String getCommonSiteId() {
+ return commonSiteId;
+ }
- public void setCommonSiteId(String commonSiteId){
- this.commonSiteId = commonSiteId;
- }
+ public void setCommonSiteId(String commonSiteId) {
+ this.commonSiteId = commonSiteId;
+ }
-} \ No newline at end of file
+}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Vnf.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Vnf.java
index 83043b3ec5..293378f969 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Vnf.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Vnf.java
@@ -21,12 +21,10 @@
package org.onap.so.bpmn.core.domain;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonRootName;
/**
- * This class is used to store instance
- * data of Vnf for ServiceDecomposition
+ * This class is used to store instance data of Vnf for ServiceDecomposition
*
* @author bb3476
*
@@ -34,106 +32,133 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("vnf")
public class Vnf extends JsonWrapper implements Serializable {
- private static final long serialVersionUID = 1L;
- private String vnfId;
- private String vnfName;
- private String serviceId;
- private String vnfType;
- private String orchStatus;
- private String modelInvariantId;
- private String modelVersionId;
- private String modelCustomizationId;
- private String nfType;
- private String nfRole;
- private String nfFunction;
- private String nfNamingCode;
- private String tenantId;
- private String cloudSiteId;
-
-
- public String getVnfName() {
- return vnfName;
- }
- public void setVnfName(String vnfName) {
- this.vnfName = vnfName;
- }
- public String getServiceId() {
- return serviceId;
- }
- public void setServiceId(String serviceId) {
- this.serviceId = serviceId;
- }
- public String getVnfType() {
- return vnfType;
- }
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
- public String getOrchStatus() {
- return orchStatus;
- }
- public void setOrchStatus(String orchStatus) {
- this.orchStatus = orchStatus;
- }
- public String getModelInvariantId() {
- return modelInvariantId;
- }
- public void setModelInvariantId(String modelInvariantId) {
- this.modelInvariantId = modelInvariantId;
- }
- public String getModelVersionId() {
- return modelVersionId;
- }
- public void setModelVersionId(String modelVersionId) {
- this.modelVersionId = modelVersionId;
- }
- public String getModelCustomizationId() {
- return modelCustomizationId;
- }
- public void setModelCustomizationId(String modelCustomizationId) {
- this.modelCustomizationId = modelCustomizationId;
- }
- public String getNfType() {
- return nfType;
- }
- public void setNfType(String nfType) {
- this.nfType = nfType;
- }
- public String getNfRole() {
- return nfRole;
- }
- public void setNfRole(String nfRole) {
- this.nfRole = nfRole;
- }
- public String getNfFunction() {
- return nfFunction;
- }
- public void setNfFunction(String nfFunction) {
- this.nfFunction = nfFunction;
- }
- public String getNfNamingCode() {
- return nfNamingCode;
- }
- public void setNfNamingCode(String nfNamingCode) {
- this.nfNamingCode = nfNamingCode;
- }
- public String getVnfId() {
- return vnfId;
- }
- public void setVnfId(String vnfId) {
- this.vnfId = vnfId;
- }
- public String getTenantId() {
- return tenantId;
- }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
- public String getCloudSiteId() {
- return cloudSiteId;
- }
- public void setCloudSiteId(String cloudSiteId) {
- this.cloudSiteId = cloudSiteId;
- }
-
+ private static final long serialVersionUID = 1L;
+ private String vnfId;
+ private String vnfName;
+ private String serviceId;
+ private String vnfType;
+ private String orchStatus;
+ private String modelInvariantId;
+ private String modelVersionId;
+ private String modelCustomizationId;
+ private String nfType;
+ private String nfRole;
+ private String nfFunction;
+ private String nfNamingCode;
+ private String tenantId;
+ private String cloudSiteId;
+
+
+ public String getVnfName() {
+ return vnfName;
+ }
+
+ public void setVnfName(String vnfName) {
+ this.vnfName = vnfName;
+ }
+
+ public String getServiceId() {
+ return serviceId;
+ }
+
+ public void setServiceId(String serviceId) {
+ this.serviceId = serviceId;
+ }
+
+ public String getVnfType() {
+ return vnfType;
+ }
+
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ public String getOrchStatus() {
+ return orchStatus;
+ }
+
+ public void setOrchStatus(String orchStatus) {
+ this.orchStatus = orchStatus;
+ }
+
+ public String getModelInvariantId() {
+ return modelInvariantId;
+ }
+
+ public void setModelInvariantId(String modelInvariantId) {
+ this.modelInvariantId = modelInvariantId;
+ }
+
+ public String getModelVersionId() {
+ return modelVersionId;
+ }
+
+ public void setModelVersionId(String modelVersionId) {
+ this.modelVersionId = modelVersionId;
+ }
+
+ public String getModelCustomizationId() {
+ return modelCustomizationId;
+ }
+
+ public void setModelCustomizationId(String modelCustomizationId) {
+ this.modelCustomizationId = modelCustomizationId;
+ }
+
+ public String getNfType() {
+ return nfType;
+ }
+
+ public void setNfType(String nfType) {
+ this.nfType = nfType;
+ }
+
+ public String getNfRole() {
+ return nfRole;
+ }
+
+ public void setNfRole(String nfRole) {
+ this.nfRole = nfRole;
+ }
+
+ public String getNfFunction() {
+ return nfFunction;
+ }
+
+ public void setNfFunction(String nfFunction) {
+ this.nfFunction = nfFunction;
+ }
+
+ public String getNfNamingCode() {
+ return nfNamingCode;
+ }
+
+ public void setNfNamingCode(String nfNamingCode) {
+ this.nfNamingCode = nfNamingCode;
+ }
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getCloudSiteId() {
+ return cloudSiteId;
+ }
+
+ public void setCloudSiteId(String cloudSiteId) {
+ this.cloudSiteId = cloudSiteId;
+ }
+
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java
index a7e5389583..f66ad36058 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java
@@ -23,7 +23,6 @@ package org.onap.so.bpmn.core.domain;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -36,154 +35,170 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("vnfResource")
public class VnfResource extends Resource {
- private static final long serialVersionUID = 1L;
-
- /*
- * set resourceType for this object
- */
- public VnfResource(){
- resourceType = ResourceType.VNF;
- setResourceId(UUID.randomUUID().toString());
- }
-
- /*
- * fields specific to VNF resource type
- */
- @JsonProperty("vfModules")
- private List <ModuleResource> vfModules;
- private String vnfHostname;
- private String vnfType;
- private String nfFunction;
- private String nfType;
- private String nfRole;
- private String nfNamingCode;
- private String multiStageDesign;
- private String orchestrationStatus;
-
- @JsonIgnore
- private String resourceInput;
-
- /*
- * GET and SET
- */
- public List<ModuleResource> getVfModules() {
- return vfModules;
- }
- public void setModules(List<ModuleResource> moduleResources) {
- this.vfModules = moduleResources;
- }
- public String getVnfHostname() {
- return vnfHostname;
- }
- public void setVnfHostname(String vnfHostname) {
- this.vnfHostname = vnfHostname;
- }
- @Deprecated
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
- public String getVnfType() {
- return vnfType;
- }
- public String getNfFunction() {
- return nfFunction;
- }
- public void setNfFunction(String nfFunction) {
- this.nfFunction = nfFunction;
- }
- public String getNfType() {
- return nfType;
- }
- public void setNfType(String nfType) {
- this.nfType = nfType;
- }
- public String getNfRole() {
- return nfRole;
- }
- public void setNfRole(String nfRole) {
- this.nfRole = nfRole;
- }
- public String getNfNamingCode() {
- return nfNamingCode;
- }
- public void setNfNamingCode(String nfNamingCode) {
- this.nfNamingCode = nfNamingCode;
- }
- public String getMultiStageDesign() {
- return multiStageDesign;
- }
- public void setMultiStageDesign(String multiStageDesign) {
- this.multiStageDesign = multiStageDesign;
- }
- /*
- * GET accessors per design requirements
- */
-
-
- public String getOrchestrationStatus(){
- return orchestrationStatus;
- }
-
- public void setOrchestrationStatus(String orchestrationStatus){
- this.orchestrationStatus = orchestrationStatus;
- }
-
- public String getResourceInput() {
- return resourceInput;
- }
-
- public void setResourceInput(String resourceInput) {
- this.resourceInput = resourceInput;
- }
-
- /**
- * Returns a list of all VfModule objects.
- * Base module is first entry in the list
- * @return ordered list of ModuleResources objects
- */
- @JsonIgnore
- public List<ModuleResource> getAllVfModuleObjects(){
- if (vfModules == null) {
- return null;
- }
-
- for (int i = 0; i < vfModules.size(); i++) {
- ModuleResource moduleResource = vfModules.get(i);
- if (moduleResource.getIsBase()){
- vfModules.remove(moduleResource);
- vfModules.add(0,moduleResource);
- }
- }
- return vfModules;
- }
-
- /**
- *
- * @return Returns JSON list of all VfModule structures.
- */
- @JsonIgnore
- public String getAllVfModulesJson(){
-
- return listToJson(vfModules);
- }
-
- // methods to add to the list
- public void addVfModule(ModuleResource moduleResource) {
- if (vfModules == null){
- vfModules = new ArrayList<>();
- }
- this.vfModules.add(moduleResource);
- }
-
-
- /**
- * Utility method to allow construction of the filed in the form of
- * <serviceResources.modelInfo.modelName>/<serviceVnfs.modelInfo.modelInstanceName>
- *
- * default setter for this field deprecated
- * @param modelName << serviceResources.modelInfo.modelName
- */
- public void constructVnfType(String modelName) {
- this.vnfType = modelName.concat("/").concat(this.modelInfo.getModelInstanceName());
- }
-} \ No newline at end of file
+ private static final long serialVersionUID = 1L;
+
+ /*
+ * set resourceType for this object
+ */
+ public VnfResource() {
+ resourceType = ResourceType.VNF;
+ setResourceId(UUID.randomUUID().toString());
+ }
+
+ /*
+ * fields specific to VNF resource type
+ */
+ @JsonProperty("vfModules")
+ private List<ModuleResource> vfModules;
+ private String vnfHostname;
+ private String vnfType;
+ private String nfFunction;
+ private String nfType;
+ private String nfRole;
+ private String nfNamingCode;
+ private String multiStageDesign;
+ private String orchestrationStatus;
+
+ @JsonIgnore
+ private String resourceInput;
+
+ /*
+ * GET and SET
+ */
+ public List<ModuleResource> getVfModules() {
+ return vfModules;
+ }
+
+ public void setModules(List<ModuleResource> moduleResources) {
+ this.vfModules = moduleResources;
+ }
+
+ public String getVnfHostname() {
+ return vnfHostname;
+ }
+
+ public void setVnfHostname(String vnfHostname) {
+ this.vnfHostname = vnfHostname;
+ }
+
+ @Deprecated
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ public String getVnfType() {
+ return vnfType;
+ }
+
+ public String getNfFunction() {
+ return nfFunction;
+ }
+
+ public void setNfFunction(String nfFunction) {
+ this.nfFunction = nfFunction;
+ }
+
+ public String getNfType() {
+ return nfType;
+ }
+
+ public void setNfType(String nfType) {
+ this.nfType = nfType;
+ }
+
+ public String getNfRole() {
+ return nfRole;
+ }
+
+ public void setNfRole(String nfRole) {
+ this.nfRole = nfRole;
+ }
+
+ public String getNfNamingCode() {
+ return nfNamingCode;
+ }
+
+ public void setNfNamingCode(String nfNamingCode) {
+ this.nfNamingCode = nfNamingCode;
+ }
+
+ public String getMultiStageDesign() {
+ return multiStageDesign;
+ }
+
+ public void setMultiStageDesign(String multiStageDesign) {
+ this.multiStageDesign = multiStageDesign;
+ }
+ /*
+ * GET accessors per design requirements
+ */
+
+
+ public String getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(String orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public String getResourceInput() {
+ return resourceInput;
+ }
+
+ public void setResourceInput(String resourceInput) {
+ this.resourceInput = resourceInput;
+ }
+
+ /**
+ * Returns a list of all VfModule objects. Base module is first entry in the list
+ *
+ * @return ordered list of ModuleResources objects
+ */
+ @JsonIgnore
+ public List<ModuleResource> getAllVfModuleObjects() {
+ if (vfModules == null) {
+ return null;
+ }
+
+ for (int i = 0; i < vfModules.size(); i++) {
+ ModuleResource moduleResource = vfModules.get(i);
+ if (moduleResource.getIsBase()) {
+ vfModules.remove(moduleResource);
+ vfModules.add(0, moduleResource);
+ }
+ }
+ return vfModules;
+ }
+
+ /**
+ *
+ * @return Returns JSON list of all VfModule structures.
+ */
+ @JsonIgnore
+ public String getAllVfModulesJson() {
+
+ return listToJson(vfModules);
+ }
+
+ // methods to add to the list
+ public void addVfModule(ModuleResource moduleResource) {
+ if (vfModules == null) {
+ vfModules = new ArrayList<>();
+ }
+ this.vfModules.add(moduleResource);
+ }
+
+
+ /**
+ * Utility method to allow construction of the filed in the form of
+ * <serviceResources.modelInfo.modelName>/<serviceVnfs.modelInfo.modelInstanceName>
+ *
+ * default setter for this field deprecated
+ *
+ * @param modelName << serviceResources.modelInfo.modelName
+ */
+ public void constructVnfType(String modelName) {
+ this.vnfType = modelName.concat("/").concat(this.modelInfo.getModelInstanceName());
+ }
+}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/internal/VariableNameExtractor.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/internal/VariableNameExtractor.java
index f63ab31496..1604e91979 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/internal/VariableNameExtractor.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/internal/VariableNameExtractor.java
@@ -25,27 +25,24 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
- * Extracts variable name from expression if entire expression is just
- * one variable, for example "${x}".
+ * Extracts variable name from expression if entire expression is just one variable, for example "${x}".
*
* Ignores all whitespaces, except inside variable name.
*
- * Examples:
- * "${x}", extracted variable name is "x"
- * " ${\t weird_NAME }", extracted variable name is "weird_NAME"
- * "${incorrect name}", no extracted name
- * "${two}+${two}", no extracted name
+ * Examples: "${x}", extracted variable name is "x" " ${\t weird_NAME }", extracted variable name is "weird_NAME"
+ * "${incorrect name}", no extracted name "${two}+${two}", no extracted name
*/
public class VariableNameExtractor {
- private static final Pattern VARIABLE_NAME_PATTERN = Pattern
- .compile("^\\s*\\$\\s*\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\s*$");
+ private static final Pattern VARIABLE_NAME_PATTERN =
+ Pattern.compile("^\\s*\\$\\s*\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\s*$");
private final String expression;
/**
* Creates new VariableNameExtractor
+ *
* @param expression expression to be parsed
*/
public VariableNameExtractor(String expression) {
@@ -54,6 +51,7 @@ public class VariableNameExtractor {
/**
* Extracts variable name from expression given in constructor
+ *
* @return Optional of variable name, empty if expression wasn't single variable
*/
public Optional<String> extract() {
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/DecomposeJsonUtil.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/DecomposeJsonUtil.java
index 89f61fec75..93a47ff6b1 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/DecomposeJsonUtil.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/DecomposeJsonUtil.java
@@ -24,14 +24,12 @@ package org.onap.so.bpmn.core.json;
import java.io.IOException;
import java.io.Serializable;
-
import org.onap.so.bpmn.core.domain.AllottedResource;
import org.onap.so.bpmn.core.domain.ConfigResource;
import org.onap.so.bpmn.core.domain.NetworkResource;
import org.onap.so.bpmn.core.domain.ServiceDecomposition;
import org.onap.so.bpmn.core.domain.ServiceInstance;
import org.onap.so.bpmn.core.domain.VnfResource;
-
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
@@ -39,16 +37,15 @@ import org.slf4j.LoggerFactory;
public class DecomposeJsonUtil implements Serializable {
- private static final Logger logger = LoggerFactory.getLogger(DecomposeJsonUtil.class);
- /**
- *
- */
- private static final long serialVersionUID = 1L;
+ private static final Logger logger = LoggerFactory.getLogger(DecomposeJsonUtil.class);
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
private static final ObjectMapper OBJECT_MAPPER = createObjectMapper();
- private DecomposeJsonUtil() {
- }
+ private DecomposeJsonUtil() {}
private static ObjectMapper createObjectMapper() {
ObjectMapper om = new ObjectMapper();
@@ -56,24 +53,24 @@ public class DecomposeJsonUtil implements Serializable {
return om;
}
- /**
+ /**
* Method to construct Service Decomposition object converting JSON structure
- *
+ *
* @param jsonString input in JSON format confirming ServiceDecomposition
* @return decoded object
* @throws JsonDecomposingException thrown when decoding json fails
- */
+ */
public static ServiceDecomposition jsonToServiceDecomposition(String jsonString) throws JsonDecomposingException {
try {
- ObjectMapper om = new ObjectMapper();
- om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
- om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ ObjectMapper om = new ObjectMapper();
+ om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
+ om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return om.readValue(jsonString, ServiceDecomposition.class);
- } catch (IOException e) {
+ } catch (IOException e) {
throw new JsonDecomposingException("Exception while converting json to service decomposition", e);
}
- }
-
+ }
+
/**
* Method to construct Service Decomposition object converting JSON structure
*
@@ -88,59 +85,59 @@ public class DecomposeJsonUtil implements Serializable {
ServiceInstance serviceInstance = new ServiceInstance();
serviceInstance.setInstanceId(serviceInstanceId);
serviceDecomposition.setServiceInstance(serviceInstance);
- return serviceDecomposition;
- }
-
- /**
+ return serviceDecomposition;
+ }
+
+ /**
* Method to construct Resource Decomposition object converting JSON structure
- *
+ *
* @param jsonString input in JSON format confirming ResourceDecomposition
* @return decoded object
* @throws JsonDecomposingException thrown when decoding json fails
- */
+ */
public static VnfResource jsonToVnfResource(String jsonString) throws JsonDecomposingException {
- try {
+ try {
return OBJECT_MAPPER.readValue(jsonString, VnfResource.class);
- } catch (IOException e) {
+ } catch (IOException e) {
throw new JsonDecomposingException("Exception while converting json to vnf resource", e);
- }
- }
-
- /**
+ }
+ }
+
+ /**
* Method to construct Resource Decomposition object converting JSON structure
- *
+ *
* @param jsonString input in JSON format confirming ResourceDecomposition
* @return decoded object
* @throws JsonDecomposingException thrown when decoding json fails
- */
+ */
public static NetworkResource jsonToNetworkResource(String jsonString) throws JsonDecomposingException {
- try {
+ try {
return OBJECT_MAPPER.readValue(jsonString, NetworkResource.class);
- } catch (IOException e) {
+ } catch (IOException e) {
throw new JsonDecomposingException("Exception while converting json to network resource", e);
- }
- }
-
- /**
+ }
+ }
+
+ /**
* Method to construct Resource Decomposition object converting JSON structure
- *
- * @param jsonString - input in JSON format confirming ResourceDecomposition
+ *
+ * @param jsonString - input in JSON format confirming ResourceDecomposition
* @return decoded object
* @throws JsonDecomposingException thrown when decoding json fails
- */
+ */
public static AllottedResource jsonToAllottedResource(String jsonString) throws JsonDecomposingException {
- try {
+ try {
return OBJECT_MAPPER.readValue(jsonString, AllottedResource.class);
- } catch (IOException e) {
+ } catch (IOException e) {
throw new JsonDecomposingException("Exception while converting json to allotted resource", e);
- }
- }
-
+ }
+ }
+
public static ConfigResource jsonToConfigResource(String jsonString) throws JsonDecomposingException {
- try {
+ try {
return OBJECT_MAPPER.readValue(jsonString, ConfigResource.class);
- } catch (IOException e) {
+ } catch (IOException e) {
throw new JsonDecomposingException("Exception while converting json to allotted resource", e);
- }
- }
+ }
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/JsonUtils.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/JsonUtils.java
index ccc5ea667e..d3d07f9014 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/JsonUtils.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/json/JsonUtils.java
@@ -30,7 +30,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.runtime.Execution;
import org.json.JSONArray;
@@ -39,7 +38,6 @@ import org.json.JSONObject;
import org.json.XML;
import org.onap.so.bpmn.core.xml.XmlTool;
import org.onap.so.exceptions.ValidationException;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
@@ -54,1016 +52,1019 @@ import org.slf4j.LoggerFactory;
*
* @version 1.0
*
- * Note: It was observed, that depending on the JSON implementation, an org.json.JSONException or a
- * java.util.NoSuchElementException will be thrown in the event of the key value being "not found"
- * in a JSON document. A general check has been added to the applicable catch blocks for this
- * this type of behavior to reduce the amount of logging. As a key value not being found is
- * expect behavior, it makes no sense to log the stack trace associated with this type of failure.
+ * Note: It was observed, that depending on the JSON implementation, an org.json.JSONException or a
+ * java.util.NoSuchElementException will be thrown in the event of the key value being "not found" in a JSON
+ * document. A general check has been added to the applicable catch blocks for this this type of behavior to
+ * reduce the amount of logging. As a key value not being found is expect behavior, it makes no sense to log
+ * the stack trace associated with this type of failure.
*/
public class JsonUtils {
- private static Logger logger = LoggerFactory.getLogger(JsonUtils.class);
- private static int MSOJsonIndentFactor = 3;
-
- /**
- * Uses the JSONObject static method to convert a XML doc to JSON.
- *
- * @param xml String containing the XML doc
- * @param pretty flag to determine if the output should be formatted
- * @return String containing the JSON translation
- */
- public static String xml2json(String xml, Boolean pretty) {
- try {
- // name spaces cause problems, so just remove them
- JSONObject jsonObj = XML.toJSONObject(XmlTool.removeNamespaces(xml));
- if (!pretty) {
- return jsonObj.toString();
- } else {
- // add an indent to make it 'pretty'
- return jsonObj.toString(MSOJsonIndentFactor);
- }
- } catch (Exception e){
- logger.debug("xml2json(): unable to parse xml and convert to json. Exception was: {}", e.toString(), e);
- return null;
- }
- }
-
- /**
- * Invokes xml2json(String, Boolean) defaulting to 'pretty' output.
- *
- * @param xml String containing the XML doc
- * @return String containing the JSON translation
- */
- public static String xml2json(String xml) {
- return xml2json(xml, true);
- }
-
- /**
- * Uses the JSONObject static method to convert a JSON doc to XML.
- * Note: this method may not generate valid XML if the JSONObject
- * contains JSONArrays which are used to represent XML attributes
- * in the JSON doc.
- *
- * @param jsonStr String containing the JSON doc
- * @param pretty flag to determine if the output should be formatted
- * @return String containing the XML translation
- */
- public static String json2xml(String jsonStr, Boolean pretty) {
-
- try {
- JSONObject jsonObj = new JSONObject(jsonStr);
- if (pretty) {
-// use the local class method which properly handles certain JSONArray content
- return XmlTool.normalize(toXMLString(jsonObj, null));
- } else {
-// use the local class method which properly handles certain JSONArray content
- return toXMLString(jsonObj, null);
- }
- } catch (Exception e){
- logger.debug("json2xml(): unable to parse json and convert to xml. Exception was: {}", e.toString(), e);
- return null;
- }
- }
-
- /**
- * Uses a modified version of the org.json.XML toString() algorithm
- * to convert a JSONObject to an XML Doc. The intent of this is to
- * correctly generate XML from JSON including TAGs for JSONArrays
- *
- * @param obj org.json.JSON object to be converted to XML
- * @param tagName optional XML tagname supplied primarily during recursive calls
- * @return String containing the XML translation
- */
- public static String toXMLString(Object obj, String tagName) throws JSONException {
- StringBuilder strBuf = new StringBuilder();
- int i;
- JSONArray jsonArr;
- JSONObject jsonObj;
- String key;
- Iterator<String> keys;
- int len;
- String str;
- Object curObj;
- if (obj instanceof JSONObject) {
- // append "<tagName>" to the XML output
- if (tagName != null) {
- strBuf.append("<");
- strBuf.append(tagName);
- strBuf.append(">");
- }
- // iterate thru the keys.
- jsonObj = (JSONObject) obj;
- keys = jsonObj.keys();
- while (keys.hasNext()) {
- key = keys.next();
- curObj = jsonObj.opt(key);
- if (curObj == null) {
- curObj = "";
- }
- if (curObj instanceof String) {
- str = (String) curObj;
- } else {
- str = null;
- }
- // append the content to the XML output
- if ("content".equals(key)) {
- if (curObj instanceof JSONArray) {
- jsonArr = (JSONArray) curObj;
- len = jsonArr.length();
- for (i = 0; i < len; i += 1) {
- if (i > 0) {
- strBuf.append('\n');
- }
- strBuf.append(XML.escape(jsonArr.get(i).toString()));
- }
- } else {
- strBuf.append(XML.escape(curObj.toString()));
- }
- // append an array of similar keys to the XML output
- } else if (curObj instanceof JSONArray) {
- jsonArr = (JSONArray) curObj;
- len = jsonArr.length();
- for (i = 0; i < len; i += 1) {
- curObj = jsonArr.get(i);
- if (curObj instanceof JSONArray) {
-// The XML tags for the nested array should be generated below when this method
-// is called recursively and the JSONArray object is passed
-// strBuf.append("<");
-// strBuf.append(key);
-// strBuf.append(">");
- strBuf.append(toXMLString(curObj, null));
-// strBuf.append("</");
-// strBuf.append(key);
-// strBuf.append(">");
- } else {
- // append the opening tag for the array (before 1st element)
- if (i == 0) {
- strBuf.append("<");
- strBuf.append(key);
- strBuf.append(">");
- }
- // append the opening tag for the array
- strBuf.append(toXMLString(curObj, null));
- // append the closing tag for the array (after last element)
- if (i == (len - 1)) {
- strBuf.append("</");
- strBuf.append(key);
- strBuf.append(">");
- }
- }
- }
- } else if (curObj.equals("")) {
- // append a closing tag "<key>" to the XML output
- strBuf.append("<");
- strBuf.append(key);
- strBuf.append("/>");
- } else {
- strBuf.append(toXMLString(curObj, key));
- }
- }
- if (tagName != null) {
- // append the closing tag "</tagName>" to the XML output
- strBuf.append("</");
- strBuf.append(tagName);
- strBuf.append(">");
- }
- return strBuf.toString();
- // XML does not have good support for arrays. If an array appears in a place
- // where XML is lacking, synthesize an < array > element.
- } else if (obj instanceof JSONArray) {
- jsonArr = (JSONArray) obj;
- len = jsonArr.length();
- for (i = 0; i < len; ++i) {
- curObj = jsonArr.opt(i);
- strBuf.append(toXMLString(curObj, (tagName == null) ? "array"
- : tagName));
- }
- return strBuf.toString();
- } else {
- str = (obj == null) ? "null" : XML.escape(obj.toString());
- return (tagName == null) ? "\"" + str + "\""
- : (str.length() == 0) ? "<" + tagName + "/>" : "<"
- + tagName + ">" + str + "</" + tagName + ">";
- }
- }
-
- /**
- * Invokes json2xml(String, Boolean) defaulting to 'pretty' output.
- *
- * @param jsonStr String containing the XML doc
- * @return String containing the JSON translation
- */
- public static String json2xml(String jsonStr) {
- return json2xml(jsonStr, true);
- }
-
- /**
- * Formats the JSON String using the value of MSOJsonIndentFactor.
- *
- * @param jsonStr String containing the JSON doc
- * @return String containing the formatted JSON doc
- */
- public static String prettyJson(String jsonStr) {
- try {
- JSONObject jsonObj = new JSONObject(jsonStr);
- return jsonObj.toString(MSOJsonIndentFactor);
- } catch (Exception e){
- logger.debug("prettyJson(): unable to parse/format json input. Exception was: {}", e.toString(), e);
- return null;
- }
- }
-
- /**
- * Returns an Iterator over the JSON keys in the specified JSON doc.
- *
- * @param jsonStr String containing the JSON doc
- * @return Iterator over the JSON keys
- * @throws JSONException if the doc cannot be parsed
- */
- public static Iterator <String> getJsonIterator(String jsonStr) throws JSONException {
- return new JSONObject(jsonStr).keys();
- }
-
- /**
- * Returns the name of the "root" property in the specified JSON doc. The
- * "root" property is the single top-level property in the JSON doc. An
- * exception is thrown if the doc is empty or if it contains more than one
- * top-level property.
- *
- * @param jsonStr String containing the JSON doc
- * @return the name of the "root" property
- * @throws JSONException if the doc cannot be parsed, or if it is empty, or if
- * it contains more than one top-level property
- */
- public static String getJsonRootProperty(String jsonStr) throws JSONException {
- Iterator<String> iter = getJsonIterator(jsonStr);
-
- if (!iter.hasNext()) {
- throw new JSONException("Empty JSON object");
- }
-
- String rootPropertyName = iter.next();
-
- if (iter.hasNext()) {
- throw new JSONException("JSON object has more than one root property");
- }
-
- return rootPropertyName;
- }
-
- /**
- * Invokes the getJsonRawValue() method and returns the String equivalent of
- * the object returned.
- *
- * TBD: May need separate methods for boolean, float, and integer fields if the
- * String representation is not sufficient to meet client needs.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @return String field value associated with keys
- */
- public static String getJsonValue(String jsonStr, String keys) {
- try {
- Object rawValue = getJsonRawValue(jsonStr, keys);
- if (rawValue == null) {
- return null;
- } else {
- if (rawValue instanceof String) {
- logger.debug("getJsonValue(): the raw value is a String Object={}", rawValue);
- return (String) rawValue;
- } else {
- logger.debug("getJsonValue(): the raw value is NOT a String Object={}", rawValue.toString());
- return rawValue.toString();
- }
- }
- } catch (Exception e) {
- logger.debug("getJsonValue(): unable to parse json to retrieve value for field={}. Exception was: {}", keys,
- e.toString(), e);
- }
- return null;
- }
-
- /**
- * Invokes the getJsonRawValue() method with the wrap flag set to true
- * and returns the String equivalent of the json node object returned.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @return String field value associated with keys
- */
- public static String getJsonNodeValue(String jsonStr, String keys) {
- try {
- Object rawValue = getJsonRawValue(jsonStr, keys, true);
- if (rawValue == null) {
- return null;
- } else {
- if (rawValue instanceof String) {
- logger.debug("getJsonNodeValue(): the raw value is a String Object={}", rawValue);
- return (String) rawValue;
- } else {
- logger.debug("getJsonNodeValue(): the raw value is NOT a String Object={}", rawValue.toString());
- return rawValue.toString();
- }
- }
- } catch (Exception e) {
- logger.debug("getJsonNodeValue(): unable to parse json to retrieve node for field={}. Exception was: {}", keys,
- e.toString(), e);
- }
- return null;
- }
-
- /**
- * Invokes the getJsonRawValue() method and returns the String equivalent of
- * the object returned.
- *
- * TBD: May need separate methods for boolean, float, and integer fields if the
- * String representation is not sufficient to meet client needs.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @return String field value associated with keys
- */
- public static int getJsonIntValue(String jsonStr, String keys) {
- try {
- Object rawValue = getJsonRawValue(jsonStr, keys);
- if (rawValue == null) {
- return 0;
- } else {
- if (rawValue instanceof Integer) {
- logger.debug("getJsonIntValue(): the raw value is an Integer Object={}", ((String) rawValue).toString());
- return (Integer) rawValue;
- } else {
- logger.debug("getJsonIntValue(): the raw value is NOT an Integer Object={}", rawValue.toString());
- return 0;
- }
- }
- } catch (Exception e) {
- logger.debug("getJsonIntValue(): unable to parse json to retrieve value for field={}. Exception was: {}", keys,
- e.toString(), e);
- }
- return 0;
- }
-
- /**
- * Invokes the getJsonRawValue() method and returns the boolean equivalent of
- * the object returned.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @return boolean field value associated with keys - default is false
- */
- public static boolean getJsonBooleanValue(String jsonStr, String keys) {
- try {
- Object rawValue = getJsonRawValue(jsonStr, keys);
- if (rawValue == null) {
- return false;
- } else {
- if (rawValue instanceof Boolean) {
- logger.debug("getJsonBooleanValue(): the raw value is a Boolean Object={}", rawValue);
- return (Boolean) rawValue;
- } else {
- logger.debug("getJsonBooleanValue(): the raw value is NOT an Boolean Object={}", rawValue.toString());
- return false;
- }
- }
- } catch (Exception e) {
- logger.debug("getJsonBooleanValue(): unable to parse json to retrieve value for field={}. Exception was: {}", keys,
- e.toString(), e);
- }
- return false;
- }
-
- /**
- * Invokes the getJsonParamValue() method to obtain the JSONArray associated with
- * the specified keys. The JSONArray is then walked to retrieve the first array
- * value associated with the specified field name (index=0).
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @param name field name for the param to be retrieved
- * @return String param value associated with field name
- */
- public static String getJsonParamValue(String jsonStr, String keys, String name) {
- return getJsonParamValue(jsonStr, keys, name, 0);
- }
-
- /**
- * Invokes the getJsonRawValue() method to obtain the JSONArray associated with
- * the specified keys. The JSONArray is then walked to retrieve the nth array
- * value associated with the specified field name and index.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @param name field name for the param to be retrieved
- * @param index the nth param associated with name starting at 0
- * @return String param value associated with field name
- */
- public static String getJsonParamValue(String jsonStr, String keys, String name, int index) {
- try {
- Object rawValue = getJsonRawValue(jsonStr, keys);
- if (rawValue == null) {
- return null;
- } else {
- if (rawValue instanceof JSONArray) {
- logger.debug("getJsonParamValue(): keys={} points to JSONArray: {}", keys, rawValue.toString());
- int arrayLen = ((JSONArray) rawValue).length();
- if (index < 0 || arrayLen < index+1) {
- logger.debug("getJsonParamValue(): index: {} is out of bounds for array size of {}", index, arrayLen);
- return null;
- }
- int foundCnt = 0;
- for (int i = 0; i < arrayLen; i++) {
- logger.debug("getJsonParamValue(): index: {}, value: {}", i, ((JSONArray) rawValue).get(i).toString());
- if (((JSONArray) rawValue).get(i) instanceof JSONObject) {
- JSONObject jsonObj = (JSONObject)((JSONArray) rawValue).get(i);
- String parmValue = jsonObj.get(name).toString();
- if (parmValue != null) {
- logger.debug("getJsonParamValue(): found value: {} for name: {} and index: {}", parmValue, name, i);
- if (foundCnt == index) {
- return parmValue;
- } else {
- foundCnt++;
- continue;
- }
- } else {
- continue;
- }
- } else {
- logger.debug("getJsonParamValue(): the JSONArray element is NOT a JSONObject={}", rawValue.toString());
- return null;
- }
- }
- logger.debug("getJsonParamValue(): content value NOT found for name: {}", name);
- return null;
- } else {
- logger.debug("getJsonParamValue(): the raw value is NOT a JSONArray Object={}", rawValue.toString());
- return null;
- }
- }
- } catch (Exception e) {
- if (e.getMessage().contains("not found")) {
- logger.debug("getJsonParamValue(): failed to retrieve param value for keys:{}, name={} : {}", keys, name,
- e.getMessage());
- } else {
- logger.debug("getJsonParamValue(): unable to parse json to retrieve value for field={}. Exception was: {}", keys,
- e.toString(), e);
- }
- }
- return null;
- }
-
- /**
- * Wrapper to generate the JSONObject to pass to the getJsonValueForKey(JSONObject, String)
- * method so that recursion over the subobjects can be supported there
- *
- * @param jsonStr String containing the JSON doc
- * @param key key to the target value
- * @return String field value associated with key
- */
- public static String getJsonValueForKey(String jsonStr, String key) {
-
- try {
- JSONObject jsonObj = new JSONObject(jsonStr);
- return getJsonValueForKey(jsonObj, key);
- } catch (Exception e) {
- logger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field={}. Exception was: {}", key,
- e.toString(), e);
- }
- return null;
- }
-
- /**
- * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the
- * single key/field name specified. Returns the associated value if found or null if the key is not found
- *
- * @param jsonObj JSONObject representation of the the JSON doc
- * @param key key to the target value
- * @return String field value associated with key
- */
- public static String getJsonValueForKey(JSONObject jsonObj, String key) {
-
- String keyValue = null;
- try {
- if (jsonObj.has(key)) {
- Object value = jsonObj.get(key);
- logger.debug("getJsonValueForKey(): found value={}, for key={}", (String) value, key);
- if (value == null) {
- return null;
- } else {
- return ((String) value);
- }
- } else {
- Iterator <String> itr = jsonObj.keys();
- while (itr.hasNext()) {
- String nextKey = itr.next();
- Object obj = jsonObj.get(nextKey);
- if (obj instanceof JSONObject) {
- keyValue = getJsonValueForKey((JSONObject) obj, key);
- if (keyValue != null) {
- break;
- }
- } else {
- logger.debug("getJsonValueForKey(): key={}, does not point to a JSONObject, next key", nextKey);
- }
- }
- }
- } catch (Exception e) {
- // JSONObject::get() throws a "not found" exception if one of the specified keys is not found
- if (e.getMessage().contains("not found")) {
- logger.debug("getJsonValueForKey(): failed to retrieve param value for key={}: {}", key, e.getMessage());
- } else {
- logger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field={}. Exception was {}", key,
- e.toString(), e);
- }
- keyValue = null;
- }
- return keyValue;
- }
-
- /**
- * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the
- * single key/field name specified. Returns the associated value if found or null if the key is not found
- *
- * @param jsonObj JSONObject representation of the the JSON doc
- * @param key key to the target value
- * @return String field value associated with key
- */
- public static Integer getJsonIntValueForKey(JSONObject jsonObj, String key) {
- Integer keyValue = null;
- try {
- if (jsonObj.has(key)) {
- Integer value = (Integer) jsonObj.get(key);
- logger.debug("getJsonIntValueForKey(): found value={}, for key={}", value, key);
- return value;
- } else {
- Iterator <String> itr = jsonObj.keys();
- while (itr.hasNext()) {
- String nextKey = itr.next();
- Object obj = jsonObj.get(nextKey);
- if (obj instanceof JSONObject) {
- keyValue = getJsonIntValueForKey((JSONObject) obj, key);
- if (keyValue != null) {
- break;
- }
- } else {
- logger.debug("getJsonIntValueForKey(): key={}, does not point to a JSONObject, next key", nextKey);
- }
- }
- }
- } catch (Exception e) {
- // JSONObject::get() throws a "not found" exception if one of the specified keys is not found
- if (e.getMessage().contains("not found")) {
- logger.debug("getJsonIntValueForKey(): failed to retrieve param value for key={}: {}", key, e.getMessage());
- } else {
- logger.debug("getJsonIntValueForKey(): unable to parse json to retrieve value for field={}. Exception was: {}", key,
- e.toString(), e);
- }
- keyValue = null;
- }
- return keyValue;
- }
-
- /**
- * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the
- * single key/field name specified. Returns the associated value if found or null if the key is not found
- *
- * @param jsonObj JSONObject representation of the the JSON doc
- * @param key key to the target value
- * @return String field value associated with key
- */
- public static Boolean getJsonBooleanValueForKey(JSONObject jsonObj, String key) {
- Boolean keyValue = null;
- try {
- if (jsonObj.has(key)) {
- Boolean value = (Boolean) jsonObj.get(key);
- logger.debug("getJsonBooleanValueForKey(): found value={}, for key={}", value, key);
- return value;
- } else {
- Iterator <String> itr = jsonObj.keys();
- while (itr.hasNext()) {
- String nextKey = itr.next();
- Object obj = jsonObj.get(nextKey);
- if (obj instanceof JSONObject) {
- keyValue = getJsonBooleanValueForKey((JSONObject) obj, key);
- if (keyValue != null) {
- break;
- }
- } else {
- logger.debug("getJsonBooleanValueForKey(): key={}, does not point to a JSONObject, next key", nextKey);
- }
- }
- }
- } catch (Exception e) {
- // JSONObject::get() throws a "not found" exception if one of the specified keys is not found
- if (e.getMessage().contains("not found")) {
- logger.debug("getJsonBooleanValueForKey(): failed to retrieve param value for key={}: {}", key, e.getMessage());
- } else {
- logger.debug("getJsonBooleanValueForKey(): unable to parse json to retrieve value for field={}. Exception was: {}",
- key, e.toString(), e);
- }
- keyValue = null;
- }
- return keyValue;
- }
+ private static Logger logger = LoggerFactory.getLogger(JsonUtils.class);
+ private static int MSOJsonIndentFactor = 3;
+
+ /**
+ * Uses the JSONObject static method to convert a XML doc to JSON.
+ *
+ * @param xml String containing the XML doc
+ * @param pretty flag to determine if the output should be formatted
+ * @return String containing the JSON translation
+ */
+ public static String xml2json(String xml, Boolean pretty) {
+ try {
+ // name spaces cause problems, so just remove them
+ JSONObject jsonObj = XML.toJSONObject(XmlTool.removeNamespaces(xml));
+ if (!pretty) {
+ return jsonObj.toString();
+ } else {
+ // add an indent to make it 'pretty'
+ return jsonObj.toString(MSOJsonIndentFactor);
+ }
+ } catch (Exception e) {
+ logger.debug("xml2json(): unable to parse xml and convert to json. Exception was: {}", e.toString(), e);
+ return null;
+ }
+ }
- /**
- * Boolean method to determine if a key path is valid for the JSON doc. Invokes
- * getJsonValue().
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @return Boolean true if keys points to value in the JSON doc
- */
- public static Boolean jsonValueExists(String jsonStr, String keys) {
- if (getJsonRawValue(jsonStr, keys) == null) {
- return false;
- } else {
- return true;
- }
- }
+ /**
+ * Invokes xml2json(String, Boolean) defaulting to 'pretty' output.
+ *
+ * @param xml String containing the XML doc
+ * @return String containing the JSON translation
+ */
+ public static String xml2json(String xml) {
+ return xml2json(xml, true);
+ }
- /**
- * Inserts the new key/value pair at the appropriate location in the JSON
- * document after first determining if keyed field already exists. If
- * it does exist, return the JSON unmodified, otherwise return the new JSON
- * Note: this method currently only supports String value inserts.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the value to be added in the format of "key1.key2.key3..."
- * @return String containing the updated JSON doc
- */
- public static String addJsonValue(String jsonStr, String keys, String value) {
+ /**
+ * Uses the JSONObject static method to convert a JSON doc to XML. Note: this method may not generate valid XML if
+ * the JSONObject contains JSONArrays which are used to represent XML attributes in the JSON doc.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param pretty flag to determine if the output should be formatted
+ * @return String containing the XML translation
+ */
+ public static String json2xml(String jsonStr, Boolean pretty) {
+
+ try {
+ JSONObject jsonObj = new JSONObject(jsonStr);
+ if (pretty) {
+ // use the local class method which properly handles certain JSONArray content
+ return XmlTool.normalize(toXMLString(jsonObj, null));
+ } else {
+ // use the local class method which properly handles certain JSONArray content
+ return toXMLString(jsonObj, null);
+ }
+ } catch (Exception e) {
+ logger.debug("json2xml(): unable to parse json and convert to xml. Exception was: {}", e.toString(), e);
+ return null;
+ }
+ }
- // only attempt to insert the key/value pair if it does not exist
- if (!jsonValueExists(jsonStr, keys)) {
- return putJsonValue(jsonStr, keys, value);
- } else {
- logger.debug("addJsonValue(): JSON add failed, key={}/value={} already exists", keys, value);
- return jsonStr;
- }
- }
+ /**
+ * Uses a modified version of the org.json.XML toString() algorithm to convert a JSONObject to an XML Doc. The
+ * intent of this is to correctly generate XML from JSON including TAGs for JSONArrays
+ *
+ * @param obj org.json.JSON object to be converted to XML
+ * @param tagName optional XML tagname supplied primarily during recursive calls
+ * @return String containing the XML translation
+ */
+ public static String toXMLString(Object obj, String tagName) throws JSONException {
+ StringBuilder strBuf = new StringBuilder();
+ int i;
+ JSONArray jsonArr;
+ JSONObject jsonObj;
+ String key;
+ Iterator<String> keys;
+ int len;
+ String str;
+ Object curObj;
+ if (obj instanceof JSONObject) {
+ // append "<tagName>" to the XML output
+ if (tagName != null) {
+ strBuf.append("<");
+ strBuf.append(tagName);
+ strBuf.append(">");
+ }
+ // iterate thru the keys.
+ jsonObj = (JSONObject) obj;
+ keys = jsonObj.keys();
+ while (keys.hasNext()) {
+ key = keys.next();
+ curObj = jsonObj.opt(key);
+ if (curObj == null) {
+ curObj = "";
+ }
+ if (curObj instanceof String) {
+ str = (String) curObj;
+ } else {
+ str = null;
+ }
+ // append the content to the XML output
+ if ("content".equals(key)) {
+ if (curObj instanceof JSONArray) {
+ jsonArr = (JSONArray) curObj;
+ len = jsonArr.length();
+ for (i = 0; i < len; i += 1) {
+ if (i > 0) {
+ strBuf.append('\n');
+ }
+ strBuf.append(XML.escape(jsonArr.get(i).toString()));
+ }
+ } else {
+ strBuf.append(XML.escape(curObj.toString()));
+ }
+ // append an array of similar keys to the XML output
+ } else if (curObj instanceof JSONArray) {
+ jsonArr = (JSONArray) curObj;
+ len = jsonArr.length();
+ for (i = 0; i < len; i += 1) {
+ curObj = jsonArr.get(i);
+ if (curObj instanceof JSONArray) {
+ // The XML tags for the nested array should be generated below when this method
+ // is called recursively and the JSONArray object is passed
+ // strBuf.append("<");
+ // strBuf.append(key);
+ // strBuf.append(">");
+ strBuf.append(toXMLString(curObj, null));
+ // strBuf.append("</");
+ // strBuf.append(key);
+ // strBuf.append(">");
+ } else {
+ // append the opening tag for the array (before 1st element)
+ if (i == 0) {
+ strBuf.append("<");
+ strBuf.append(key);
+ strBuf.append(">");
+ }
+ // append the opening tag for the array
+ strBuf.append(toXMLString(curObj, null));
+ // append the closing tag for the array (after last element)
+ if (i == (len - 1)) {
+ strBuf.append("</");
+ strBuf.append(key);
+ strBuf.append(">");
+ }
+ }
+ }
+ } else if (curObj.equals("")) {
+ // append a closing tag "<key>" to the XML output
+ strBuf.append("<");
+ strBuf.append(key);
+ strBuf.append("/>");
+ } else {
+ strBuf.append(toXMLString(curObj, key));
+ }
+ }
+ if (tagName != null) {
+ // append the closing tag "</tagName>" to the XML output
+ strBuf.append("</");
+ strBuf.append(tagName);
+ strBuf.append(">");
+ }
+ return strBuf.toString();
+ // XML does not have good support for arrays. If an array appears in a place
+ // where XML is lacking, synthesize an < array > element.
+ } else if (obj instanceof JSONArray) {
+ jsonArr = (JSONArray) obj;
+ len = jsonArr.length();
+ for (i = 0; i < len; ++i) {
+ curObj = jsonArr.opt(i);
+ strBuf.append(toXMLString(curObj, (tagName == null) ? "array" : tagName));
+ }
+ return strBuf.toString();
+ } else {
+ str = (obj == null) ? "null" : XML.escape(obj.toString());
+ return (tagName == null) ? "\"" + str + "\""
+ : (str.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + str + "</" + tagName + ">";
+ }
+ }
- /**
- * Updates the value for the specified key in the JSON document
- * after first determining if keyed field exists. If it does
- * not exist, return the JSON unmodified, otherwise return the updated JSON.
- * Note: this method currently only supports String value updates.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the value to be updated in the format of "key1.key2.key3..."
- * @return String containing the updated JSON doc
- */
- public static String updJsonValue(String jsonStr, String keys, String newValue) {
- // only attempt to modify the key/value pair if it exists
- if (jsonValueExists(jsonStr, keys)) {
- return putJsonValue(jsonStr, keys, newValue);
- } else {
- logger.debug("updJsonValue(): JSON update failed, no value exists for key={}", keys);
- return jsonStr;
- }
- }
+ /**
+ * Invokes json2xml(String, Boolean) defaulting to 'pretty' output.
+ *
+ * @param jsonStr String containing the XML doc
+ * @return String containing the JSON translation
+ */
+ public static String json2xml(String jsonStr) {
+ return json2xml(jsonStr, true);
+ }
- /**
- * Deletes the value for the specified key in the JSON document
- * after first determining if keyed field exists. If it does
- * not exist, return the JSON unmodified, otherwise return the updated JSON
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..."
- * @return String containing the updated JSON doc
- */
- public static String delJsonValue(String jsonStr, String keys) {
+ /**
+ * Formats the JSON String using the value of MSOJsonIndentFactor.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @return String containing the formatted JSON doc
+ */
+ public static String prettyJson(String jsonStr) {
+ try {
+ JSONObject jsonObj = new JSONObject(jsonStr);
+ return jsonObj.toString(MSOJsonIndentFactor);
+ } catch (Exception e) {
+ logger.debug("prettyJson(): unable to parse/format json input. Exception was: {}", e.toString(), e);
+ return null;
+ }
+ }
- // only attempt to remove the key/value pair if it exists
- if (jsonValueExists(jsonStr, keys)) {
- // passing a null value results in a delete
- return putJsonValue(jsonStr, keys, null);
- } else {
- logger.debug("delJsonValue(): JSON delete failed, no value exists for key={}", keys);
- return jsonStr;
- }
- }
+ /**
+ * Returns an Iterator over the JSON keys in the specified JSON doc.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @return Iterator over the JSON keys
+ * @throws JSONException if the doc cannot be parsed
+ */
+ public static Iterator<String> getJsonIterator(String jsonStr) throws JSONException {
+ return new JSONObject(jsonStr).keys();
+ }
- /**
- * Walks the JSON doc using the full key path to retrieve the associated
- * value. All but the last key points to the 'parent' object name(s) in order
- * in the JSON hierarchy with the last key pointing to the target value.
- * The value returned is a Java object.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @return Object field value associated with keys
- */
- private static Object getJsonRawValue(String jsonStr, String keys) {
- return getJsonRawValue(jsonStr, keys, false);
- }
+ /**
+ * Returns the name of the "root" property in the specified JSON doc. The "root" property is the single top-level
+ * property in the JSON doc. An exception is thrown if the doc is empty or if it contains more than one top-level
+ * property.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @return the name of the "root" property
+ * @throws JSONException if the doc cannot be parsed, or if it is empty, or if it contains more than one top-level
+ * property
+ */
+ public static String getJsonRootProperty(String jsonStr) throws JSONException {
+ Iterator<String> iter = getJsonIterator(jsonStr);
+
+ if (!iter.hasNext()) {
+ throw new JSONException("Empty JSON object");
+ }
+
+ String rootPropertyName = iter.next();
+
+ if (iter.hasNext()) {
+ throw new JSONException("JSON object has more than one root property");
+ }
+
+ return rootPropertyName;
+ }
- /**
- * Walks the JSON doc using the full key path to retrieve the associated
- * value. All but the last key points to the 'parent' object name(s) in order
- * in the JSON hierarchy with the last key pointing to the target value.
- * The value returned is a Java object.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @param wrap Boolean which determines if returned JSONObjects sould be "wrapped"
- * Note: wrap does not apply to returned scalar values
- * @return Object field value associated with keys
- */
- private static Object getJsonRawValue(String jsonStr, String keys, Boolean wrap) {
+ /**
+ * Invokes the getJsonRawValue() method and returns the String equivalent of the object returned.
+ *
+ * TBD: May need separate methods for boolean, float, and integer fields if the String representation is not
+ * sufficient to meet client needs.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."
+ * @return String field value associated with keys
+ */
+ public static String getJsonValue(String jsonStr, String keys) {
+ try {
+ Object rawValue = getJsonRawValue(jsonStr, keys);
+ if (rawValue == null) {
+ return null;
+ } else {
+ if (rawValue instanceof String) {
+ logger.debug("getJsonValue(): the raw value is a String Object={}", rawValue);
+ return (String) rawValue;
+ } else {
+ logger.debug("getJsonValue(): the raw value is NOT a String Object={}", rawValue.toString());
+ return rawValue.toString();
+ }
+ }
+ } catch (Exception e) {
+ logger.debug("getJsonValue(): unable to parse json to retrieve value for field={}. Exception was: {}", keys,
+ e.toString(), e);
+ }
+ return null;
+ }
- String keyStr = "";
- try {
- JSONObject jsonObj = new JSONObject(jsonStr);
- StringTokenizer keyTokens = new StringTokenizer(keys, ".");
- while (keyTokens.hasMoreElements()) {
- keyStr = keyTokens.nextToken();
- Object keyValue = jsonObj.get(keyStr);
- if (keyValue instanceof JSONObject) {
- jsonObj = (JSONObject) keyValue;
- } else {
- if (keyTokens.hasMoreElements()) {
- logger.debug("getJsonRawValue(): value found prior to last key for key={}", keyStr);
- }
- return keyValue;
- }
- }
- // return the json 'node' that the key points to
- // note: since this is a json object and not a scalar value,
- // use the wrap flag to determine if the object should
- // be wrapped with a root node value
- // (the last key in the keys String)
- if (wrap) {
- JSONObject wrappedJsonObj = new JSONObject();
- wrappedJsonObj.put(keyStr, jsonObj);
- return wrappedJsonObj.toString();
- } else {
- return jsonObj.toString();
- }
+ /**
+ * Invokes the getJsonRawValue() method with the wrap flag set to true and returns the String equivalent of the json
+ * node object returned.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."
+ * @return String field value associated with keys
+ */
+ public static String getJsonNodeValue(String jsonStr, String keys) {
+ try {
+ Object rawValue = getJsonRawValue(jsonStr, keys, true);
+ if (rawValue == null) {
+ return null;
+ } else {
+ if (rawValue instanceof String) {
+ logger.debug("getJsonNodeValue(): the raw value is a String Object={}", rawValue);
+ return (String) rawValue;
+ } else {
+ logger.debug("getJsonNodeValue(): the raw value is NOT a String Object={}", rawValue.toString());
+ return rawValue.toString();
+ }
+ }
+ } catch (Exception e) {
+ logger.debug("getJsonNodeValue(): unable to parse json to retrieve node for field={}. Exception was: {}",
+ keys, e.toString(), e);
+ }
+ return null;
+ }
- } catch (Exception e) {
- // JSONObject::get() throws a "not found" exception if one of the specified keys is not found
- if (e.getMessage().contains("not found")) {
- logger.debug("getJsonRawValue(): failed to retrieve param value for key={}: {}", keyStr, e.getMessage());
- } else {
- logger.debug("getJsonRawValue(): unable to parse json to retrieve value for field={}. Exception was: {}", keys,
- e.toString(), e);
- }
- }
- return null;
- }
+ /**
+ * Invokes the getJsonRawValue() method and returns the String equivalent of the object returned.
+ *
+ * TBD: May need separate methods for boolean, float, and integer fields if the String representation is not
+ * sufficient to meet client needs.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."
+ * @return String field value associated with keys
+ */
+ public static int getJsonIntValue(String jsonStr, String keys) {
+ try {
+ Object rawValue = getJsonRawValue(jsonStr, keys);
+ if (rawValue == null) {
+ return 0;
+ } else {
+ if (rawValue instanceof Integer) {
+ logger.debug("getJsonIntValue(): the raw value is an Integer Object={}",
+ ((String) rawValue).toString());
+ return (Integer) rawValue;
+ } else {
+ logger.debug("getJsonIntValue(): the raw value is NOT an Integer Object={}", rawValue.toString());
+ return 0;
+ }
+ }
+ } catch (Exception e) {
+ logger.debug("getJsonIntValue(): unable to parse json to retrieve value for field={}. Exception was: {}",
+ keys, e.toString(), e);
+ }
+ return 0;
+ }
- /**
- * Private method invoked by the public add, update, and delete methods.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..."
- * @return String containing the updated JSON doc
- */
- private static String putJsonValue(String jsonStr, String keys, String value) {
+ /**
+ * Invokes the getJsonRawValue() method and returns the boolean equivalent of the object returned.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."
+ * @return boolean field value associated with keys - default is false
+ */
+ public static boolean getJsonBooleanValue(String jsonStr, String keys) {
+ try {
+ Object rawValue = getJsonRawValue(jsonStr, keys);
+ if (rawValue == null) {
+ return false;
+ } else {
+ if (rawValue instanceof Boolean) {
+ logger.debug("getJsonBooleanValue(): the raw value is a Boolean Object={}", rawValue);
+ return (Boolean) rawValue;
+ } else {
+ logger.debug("getJsonBooleanValue(): the raw value is NOT an Boolean Object={}",
+ rawValue.toString());
+ return false;
+ }
+ }
+ } catch (Exception e) {
+ logger.debug(
+ "getJsonBooleanValue(): unable to parse json to retrieve value for field={}. Exception was: {}",
+ keys, e.toString(), e);
+ }
+ return false;
+ }
- String keyStr = "";
- try {
- JSONObject jsonObj = new JSONObject(jsonStr);
- JSONObject jsonObjOut = jsonObj;
- StringTokenizer keyTokens = new StringTokenizer(keys, ".");
- while (keyTokens.hasMoreElements()) {
- keyStr = keyTokens.nextToken();
- if (keyTokens.hasMoreElements()) {
- Object keyValue = jsonObj.get(keyStr);
- if (keyValue instanceof JSONObject) {
- jsonObj = (JSONObject) keyValue;
- } else {
- logger.debug("putJsonValue(): key={} not the last key but points to non-json object: {}", keyStr, keyValue);
- return null;
- }
- } else { // at the last/new key value
- jsonObj.put(keyStr, value);
- return jsonObjOut.toString(3);
- }
- }
- // should not hit this point if the key points to a valid key value
- return null;
+ /**
+ * Invokes the getJsonParamValue() method to obtain the JSONArray associated with the specified keys. The JSONArray
+ * is then walked to retrieve the first array value associated with the specified field name (index=0).
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."
+ * @param name field name for the param to be retrieved
+ * @return String param value associated with field name
+ */
+ public static String getJsonParamValue(String jsonStr, String keys, String name) {
+ return getJsonParamValue(jsonStr, keys, name, 0);
+ }
- } catch (Exception e) {
- // JSONObject::get() throws a "not found" exception if one of the specified keys is not found
- if (e.getMessage().contains("not found")) {
- logger.debug("putJsonValue(): failed to put param value for key={}: {}", keyStr, e.getMessage());
- } else {
- logger.debug("putJsonValue(): unable to parse json to put value for key={}. Exception was: {}", keys, e.toString(),
- e);
- }
- }
- return null;
- }
+ /**
+ * Invokes the getJsonRawValue() method to obtain the JSONArray associated with the specified keys. The JSONArray is
+ * then walked to retrieve the nth array value associated with the specified field name and index.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."
+ * @param name field name for the param to be retrieved
+ * @param index the nth param associated with name starting at 0
+ * @return String param value associated with field name
+ */
+ public static String getJsonParamValue(String jsonStr, String keys, String name, int index) {
+ try {
+ Object rawValue = getJsonRawValue(jsonStr, keys);
+ if (rawValue == null) {
+ return null;
+ } else {
+ if (rawValue instanceof JSONArray) {
+ logger.debug("getJsonParamValue(): keys={} points to JSONArray: {}", keys, rawValue.toString());
+ int arrayLen = ((JSONArray) rawValue).length();
+ if (index < 0 || arrayLen < index + 1) {
+ logger.debug("getJsonParamValue(): index: {} is out of bounds for array size of {}", index,
+ arrayLen);
+ return null;
+ }
+ int foundCnt = 0;
+ for (int i = 0; i < arrayLen; i++) {
+ logger.debug("getJsonParamValue(): index: {}, value: {}", i,
+ ((JSONArray) rawValue).get(i).toString());
+ if (((JSONArray) rawValue).get(i) instanceof JSONObject) {
+ JSONObject jsonObj = (JSONObject) ((JSONArray) rawValue).get(i);
+ String parmValue = jsonObj.get(name).toString();
+ if (parmValue != null) {
+ logger.debug("getJsonParamValue(): found value: {} for name: {} and index: {}",
+ parmValue, name, i);
+ if (foundCnt == index) {
+ return parmValue;
+ } else {
+ foundCnt++;
+ continue;
+ }
+ } else {
+ continue;
+ }
+ } else {
+ logger.debug("getJsonParamValue(): the JSONArray element is NOT a JSONObject={}",
+ rawValue.toString());
+ return null;
+ }
+ }
+ logger.debug("getJsonParamValue(): content value NOT found for name: {}", name);
+ return null;
+ } else {
+ logger.debug("getJsonParamValue(): the raw value is NOT a JSONArray Object={}",
+ rawValue.toString());
+ return null;
+ }
+ }
+ } catch (Exception e) {
+ if (e.getMessage().contains("not found")) {
+ logger.debug("getJsonParamValue(): failed to retrieve param value for keys:{}, name={} : {}", keys,
+ name, e.getMessage());
+ } else {
+ logger.debug(
+ "getJsonParamValue(): unable to parse json to retrieve value for field={}. Exception was: {}",
+ keys, e.toString(), e);
+ }
+ }
+ return null;
+ }
- /**
- * This json util method converts a json array of Key Value
- * pair objects into a Java Map.
- *
- * @param execution
- * @param entryArray - the getJsonValue of a json Array of key/value pairs
- *
- * @return Map - a Map containing the entries
- */
- public Map<String, String> jsonStringToMap(DelegateExecution execution, String entry) {
- logger.debug("Started Json String To Map Method");
+ /**
+ * Wrapper to generate the JSONObject to pass to the getJsonValueForKey(JSONObject, String) method so that recursion
+ * over the subobjects can be supported there
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param key key to the target value
+ * @return String field value associated with key
+ */
+ public static String getJsonValueForKey(String jsonStr, String key) {
+
+ try {
+ JSONObject jsonObj = new JSONObject(jsonStr);
+ return getJsonValueForKey(jsonObj, key);
+ } catch (Exception e) {
+ logger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field={}. Exception was: {}",
+ key, e.toString(), e);
+ }
+ return null;
+ }
- Map<String, String> map = new HashMap<>();
+ /**
+ * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the single
+ * key/field name specified. Returns the associated value if found or null if the key is not found
+ *
+ * @param jsonObj JSONObject representation of the the JSON doc
+ * @param key key to the target value
+ * @return String field value associated with key
+ */
+ public static String getJsonValueForKey(JSONObject jsonObj, String key) {
+
+ String keyValue = null;
+ try {
+ if (jsonObj.has(key)) {
+ Object value = jsonObj.get(key);
+ logger.debug("getJsonValueForKey(): found value={}, for key={}", (String) value, key);
+ if (value == null) {
+ return null;
+ } else {
+ return ((String) value);
+ }
+ } else {
+ Iterator<String> itr = jsonObj.keys();
+ while (itr.hasNext()) {
+ String nextKey = itr.next();
+ Object obj = jsonObj.get(nextKey);
+ if (obj instanceof JSONObject) {
+ keyValue = getJsonValueForKey((JSONObject) obj, key);
+ if (keyValue != null) {
+ break;
+ }
+ } else {
+ logger.debug("getJsonValueForKey(): key={}, does not point to a JSONObject, next key", nextKey);
+ }
+ }
+ }
+ } catch (Exception e) {
+ // JSONObject::get() throws a "not found" exception if one of the specified keys is not found
+ if (e.getMessage().contains("not found")) {
+ logger.debug("getJsonValueForKey(): failed to retrieve param value for key={}: {}", key,
+ e.getMessage());
+ } else {
+ logger.debug(
+ "getJsonValueForKey(): unable to parse json to retrieve value for field={}. Exception was {}",
+ key, e.toString(), e);
+ }
+ keyValue = null;
+ }
+ return keyValue;
+ }
- //Populate Map
- JSONObject obj = new JSONObject(entry);
+ /**
+ * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the single
+ * key/field name specified. Returns the associated value if found or null if the key is not found
+ *
+ * @param jsonObj JSONObject representation of the the JSON doc
+ * @param key key to the target value
+ * @return String field value associated with key
+ */
+ public static Integer getJsonIntValueForKey(JSONObject jsonObj, String key) {
+ Integer keyValue = null;
+ try {
+ if (jsonObj.has(key)) {
+ Integer value = (Integer) jsonObj.get(key);
+ logger.debug("getJsonIntValueForKey(): found value={}, for key={}", value, key);
+ return value;
+ } else {
+ Iterator<String> itr = jsonObj.keys();
+ while (itr.hasNext()) {
+ String nextKey = itr.next();
+ Object obj = jsonObj.get(nextKey);
+ if (obj instanceof JSONObject) {
+ keyValue = getJsonIntValueForKey((JSONObject) obj, key);
+ if (keyValue != null) {
+ break;
+ }
+ } else {
+ logger.debug("getJsonIntValueForKey(): key={}, does not point to a JSONObject, next key",
+ nextKey);
+ }
+ }
+ }
+ } catch (Exception e) {
+ // JSONObject::get() throws a "not found" exception if one of the specified keys is not found
+ if (e.getMessage().contains("not found")) {
+ logger.debug("getJsonIntValueForKey(): failed to retrieve param value for key={}: {}", key,
+ e.getMessage());
+ } else {
+ logger.debug(
+ "getJsonIntValueForKey(): unable to parse json to retrieve value for field={}. Exception was: {}",
+ key, e.toString(), e);
+ }
+ keyValue = null;
+ }
+ return keyValue;
+ }
- /* Wildfly is pushing a version of org.json which does not
- * auto cast to string. Leaving it as an object prevents
- * a method not found exception at runtime.
- */
- final Iterator<String> keys = obj.keys();
- while (keys.hasNext()) {
- final String key = keys.next();
- map.put(key, obj.getString(key));
- }
- logger.debug("Outgoing Map is: {}", map);
- logger.debug("Completed Json String To Map Method");
- return map;
- }
+ /**
+ * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the single
+ * key/field name specified. Returns the associated value if found or null if the key is not found
+ *
+ * @param jsonObj JSONObject representation of the the JSON doc
+ * @param key key to the target value
+ * @return String field value associated with key
+ */
+ public static Boolean getJsonBooleanValueForKey(JSONObject jsonObj, String key) {
+ Boolean keyValue = null;
+ try {
+ if (jsonObj.has(key)) {
+ Boolean value = (Boolean) jsonObj.get(key);
+ logger.debug("getJsonBooleanValueForKey(): found value={}, for key={}", value, key);
+ return value;
+ } else {
+ Iterator<String> itr = jsonObj.keys();
+ while (itr.hasNext()) {
+ String nextKey = itr.next();
+ Object obj = jsonObj.get(nextKey);
+ if (obj instanceof JSONObject) {
+ keyValue = getJsonBooleanValueForKey((JSONObject) obj, key);
+ if (keyValue != null) {
+ break;
+ }
+ } else {
+ logger.debug("getJsonBooleanValueForKey(): key={}, does not point to a JSONObject, next key",
+ nextKey);
+ }
+ }
+ }
+ } catch (Exception e) {
+ // JSONObject::get() throws a "not found" exception if one of the specified keys is not found
+ if (e.getMessage().contains("not found")) {
+ logger.debug("getJsonBooleanValueForKey(): failed to retrieve param value for key={}: {}", key,
+ e.getMessage());
+ } else {
+ logger.debug(
+ "getJsonBooleanValueForKey(): unable to parse json to retrieve value for field={}. Exception was: {}",
+ key, e.toString(), e);
+ }
+ keyValue = null;
+ }
+ return keyValue;
+ }
- /**
- * This json util method converts a json array of Key Value
- * pair objects into a Java Map.
- *
- * @param execution
- * @param entryArray - the getJsonValue of a json Array of key/value pairs
- * @param keyNode - the name of the node that represents the key
- * @param valueNode - the name of the node that represents the value
- * @return Map - a Map containing the entries
- *
- */
- public Map<String, String> entryArrayToMap(DelegateExecution execution, String entryArray, String keyNode, String valueNode) {
- logger.debug("Started Entry Array To Map Util Method");
+ /**
+ * Boolean method to determine if a key path is valid for the JSON doc. Invokes getJsonValue().
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."
+ * @return Boolean true if keys points to value in the JSON doc
+ */
+ public static Boolean jsonValueExists(String jsonStr, String keys) {
+ if (getJsonRawValue(jsonStr, keys) == null) {
+ return false;
+ } else {
+ return true;
+ }
+ }
- Map<String, String> map = new HashMap<>();
- //Populate Map
- String entryListJson = "{ \"wrapper\":" + entryArray + "}";
- JSONObject obj = new JSONObject(entryListJson);
- JSONArray arr = obj.getJSONArray("wrapper");
- for (int i = 0; i < arr.length(); i++){
- JSONObject jo = arr.getJSONObject(i);
- String key = jo.getString(keyNode);
- String value = jo.get(valueNode).toString();
- map.put(key, value);
- }
- logger.debug("Completed Entry Array To Map Util Method");
- return map;
- }
+ /**
+ * Inserts the new key/value pair at the appropriate location in the JSON document after first determining if keyed
+ * field already exists. If it does exist, return the JSON unmodified, otherwise return the new JSON Note: this
+ * method currently only supports String value inserts.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the value to be added in the format of "key1.key2.key3..."
+ * @return String containing the updated JSON doc
+ */
+ public static String addJsonValue(String jsonStr, String keys, String value) {
+
+ // only attempt to insert the key/value pair if it does not exist
+ if (!jsonValueExists(jsonStr, keys)) {
+ return putJsonValue(jsonStr, keys, value);
+ } else {
+ logger.debug("addJsonValue(): JSON add failed, key={}/value={} already exists", keys, value);
+ return jsonStr;
+ }
+ }
- /**
- * This json util method converts a json array of Key Value pair objects into a Java Map.
- *
- * @param entryArray - the json Array of key/value pairs objects
- * @param keyNode - the name of the node that represents the key
- * @param valueNode - the name of the node that represents the value
- * @return Map - a Map containing the entries
- * @author cb645j
- *
- */
- public Map<String, String> entryArrayToMap(String entryArray, String keyNode, String valueNode){
- logger.debug("Started Entry Array To Map Util Method");
+ /**
+ * Updates the value for the specified key in the JSON document after first determining if keyed field exists. If it
+ * does not exist, return the JSON unmodified, otherwise return the updated JSON. Note: this method currently only
+ * supports String value updates.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the value to be updated in the format of "key1.key2.key3..."
+ * @return String containing the updated JSON doc
+ */
+ public static String updJsonValue(String jsonStr, String keys, String newValue) {
+ // only attempt to modify the key/value pair if it exists
+ if (jsonValueExists(jsonStr, keys)) {
+ return putJsonValue(jsonStr, keys, newValue);
+ } else {
+ logger.debug("updJsonValue(): JSON update failed, no value exists for key={}", keys);
+ return jsonStr;
+ }
+ }
- Map<String, String> map = new HashMap<>();
- String entryListJson = "{ \"wrapper\":" + entryArray + "}";
- JSONObject obj = new JSONObject(entryListJson); // TODO just put in json array
- JSONArray arr = obj.getJSONArray("wrapper");
- for(int i = 0; i < arr.length(); i++){
- JSONObject jo = arr.getJSONObject(i);
- String key = jo.getString(keyNode);
- String value = jo.get(valueNode).toString();
- map.put(key, value);
- }
- logger.debug("Completed Entry Array To Map Util Method");
- return map;
- }
+ /**
+ * Deletes the value for the specified key in the JSON document after first determining if keyed field exists. If it
+ * does not exist, return the JSON unmodified, otherwise return the updated JSON
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..."
+ * @return String containing the updated JSON doc
+ */
+ public static String delJsonValue(String jsonStr, String keys) {
+
+ // only attempt to remove the key/value pair if it exists
+ if (jsonValueExists(jsonStr, keys)) {
+ // passing a null value results in a delete
+ return putJsonValue(jsonStr, keys, null);
+ } else {
+ logger.debug("delJsonValue(): JSON delete failed, no value exists for key={}", keys);
+ return jsonStr;
+ }
+ }
- /**
- * This json util method converts a json Array of Strings to a Java List. It takes each
- * String in the json Array and puts it in a Java List<String>.
- *
- * @param execution
- * @param jsonArray - string value of a json array
- * @return List - a java list containing the strings
- *
- * @author cb645j
- */
- public List<String> StringArrayToList(Execution execution, String jsonArray){
- logger.debug("Started String Array To List Util Method");
+ /**
+ * Walks the JSON doc using the full key path to retrieve the associated value. All but the last key points to the
+ * 'parent' object name(s) in order in the JSON hierarchy with the last key pointing to the target value. The value
+ * returned is a Java object.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."
+ * @return Object field value associated with keys
+ */
+ private static Object getJsonRawValue(String jsonStr, String keys) {
+ return getJsonRawValue(jsonStr, keys, false);
+ }
- List<String> list = new ArrayList<>();
- // Populate List
- // TODO
- String stringListJson = "{ \"strings\":" + jsonArray + "}";
- JSONObject obj = new JSONObject(stringListJson);
- JSONArray arr = obj.getJSONArray("strings");
- for(int i = 0; i < arr.length(); i++){
- String s = arr.get(i).toString();
- list.add(s);
- }
- logger.debug("Outgoing List is: {}", list);
- logger.debug("Completed String Array To List Util Method");
- return list;
- }
+ /**
+ * Walks the JSON doc using the full key path to retrieve the associated value. All but the last key points to the
+ * 'parent' object name(s) in order in the JSON hierarchy with the last key pointing to the target value. The value
+ * returned is a Java object.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."
+ * @param wrap Boolean which determines if returned JSONObjects sould be "wrapped" Note: wrap does not apply to
+ * returned scalar values
+ * @return Object field value associated with keys
+ */
+ private static Object getJsonRawValue(String jsonStr, String keys, Boolean wrap) {
+
+ String keyStr = "";
+ try {
+ JSONObject jsonObj = new JSONObject(jsonStr);
+ StringTokenizer keyTokens = new StringTokenizer(keys, ".");
+ while (keyTokens.hasMoreElements()) {
+ keyStr = keyTokens.nextToken();
+ Object keyValue = jsonObj.get(keyStr);
+ if (keyValue instanceof JSONObject) {
+ jsonObj = (JSONObject) keyValue;
+ } else {
+ if (keyTokens.hasMoreElements()) {
+ logger.debug("getJsonRawValue(): value found prior to last key for key={}", keyStr);
+ }
+ return keyValue;
+ }
+ }
+ // return the json 'node' that the key points to
+ // note: since this is a json object and not a scalar value,
+ // use the wrap flag to determine if the object should
+ // be wrapped with a root node value
+ // (the last key in the keys String)
+ if (wrap) {
+ JSONObject wrappedJsonObj = new JSONObject();
+ wrappedJsonObj.put(keyStr, jsonObj);
+ return wrappedJsonObj.toString();
+ } else {
+ return jsonObj.toString();
+ }
+
+ } catch (Exception e) {
+ // JSONObject::get() throws a "not found" exception if one of the specified keys is not found
+ if (e.getMessage().contains("not found")) {
+ logger.debug("getJsonRawValue(): failed to retrieve param value for key={}: {}", keyStr,
+ e.getMessage());
+ } else {
+ logger.debug(
+ "getJsonRawValue(): unable to parse json to retrieve value for field={}. Exception was: {}",
+ keys, e.toString(), e);
+ }
+ }
+ return null;
+ }
- /**
- * This json util method converts a json Array of Strings to a Java List. It takes each
- * String in the json Array and puts it in a Java List<String>.
- *
- * @param jsonArray - string value of a json array
- * @return List - a java list containing the strings
- *
- * @author cb645j
- */
- public List<String> StringArrayToList(String jsonArray){
- logger.debug("Started Json Util String Array To List");
- List<String> list = new ArrayList<>();
+ /**
+ * Private method invoked by the public add, update, and delete methods.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..."
+ * @return String containing the updated JSON doc
+ */
+ private static String putJsonValue(String jsonStr, String keys, String value) {
+
+ String keyStr = "";
+ try {
+ JSONObject jsonObj = new JSONObject(jsonStr);
+ JSONObject jsonObjOut = jsonObj;
+ StringTokenizer keyTokens = new StringTokenizer(keys, ".");
+ while (keyTokens.hasMoreElements()) {
+ keyStr = keyTokens.nextToken();
+ if (keyTokens.hasMoreElements()) {
+ Object keyValue = jsonObj.get(keyStr);
+ if (keyValue instanceof JSONObject) {
+ jsonObj = (JSONObject) keyValue;
+ } else {
+ logger.debug("putJsonValue(): key={} not the last key but points to non-json object: {}",
+ keyStr, keyValue);
+ return null;
+ }
+ } else { // at the last/new key value
+ jsonObj.put(keyStr, value);
+ return jsonObjOut.toString(3);
+ }
+ }
+ // should not hit this point if the key points to a valid key value
+ return null;
+
+ } catch (Exception e) {
+ // JSONObject::get() throws a "not found" exception if one of the specified keys is not found
+ if (e.getMessage().contains("not found")) {
+ logger.debug("putJsonValue(): failed to put param value for key={}: {}", keyStr, e.getMessage());
+ } else {
+ logger.debug("putJsonValue(): unable to parse json to put value for key={}. Exception was: {}", keys,
+ e.toString(), e);
+ }
+ }
+ return null;
+ }
- JSONArray arr = new JSONArray(jsonArray);
- for(int i = 0; i < arr.length(); i++){
- String s = arr.get(i).toString();
- list.add(s);
- }
- logger.debug("Completed Json Util String Array To List");
- return list;
- }
+ /**
+ * This json util method converts a json array of Key Value pair objects into a Java Map.
+ *
+ * @param execution
+ * @param entryArray - the getJsonValue of a json Array of key/value pairs
+ *
+ * @return Map - a Map containing the entries
+ */
+ public Map<String, String> jsonStringToMap(DelegateExecution execution, String entry) {
+ logger.debug("Started Json String To Map Method");
+
+ Map<String, String> map = new HashMap<>();
+
+ // Populate Map
+ JSONObject obj = new JSONObject(entry);
+
+ /*
+ * Wildfly is pushing a version of org.json which does not auto cast to string. Leaving it as an object prevents
+ * a method not found exception at runtime.
+ */
+ final Iterator<String> keys = obj.keys();
+ while (keys.hasNext()) {
+ final String key = keys.next();
+ map.put(key, obj.getString(key));
+ }
+ logger.debug("Outgoing Map is: {}", map);
+ logger.debug("Completed Json String To Map Method");
+ return map;
+ }
- /**
- * This json util method converts a json Array of Strings to a Java List. It takes each
- * String in the json Array and puts it in a Java List<String>.
- *
- * @param jsonArray - json array
- * @return List - a java list containing the strings
- *
- * @author cb645j
- */
- public List<String> StringArrayToList(JSONArray jsonArray){
- logger.debug("Started Json Util String Array To List");
- List<String> list = new ArrayList<>();
+ /**
+ * This json util method converts a json array of Key Value pair objects into a Java Map.
+ *
+ * @param execution
+ * @param entryArray - the getJsonValue of a json Array of key/value pairs
+ * @param keyNode - the name of the node that represents the key
+ * @param valueNode - the name of the node that represents the value
+ * @return Map - a Map containing the entries
+ *
+ */
+ public Map<String, String> entryArrayToMap(DelegateExecution execution, String entryArray, String keyNode,
+ String valueNode) {
+ logger.debug("Started Entry Array To Map Util Method");
+
+ Map<String, String> map = new HashMap<>();
+ // Populate Map
+ String entryListJson = "{ \"wrapper\":" + entryArray + "}";
+ JSONObject obj = new JSONObject(entryListJson);
+ JSONArray arr = obj.getJSONArray("wrapper");
+ for (int i = 0; i < arr.length(); i++) {
+ JSONObject jo = arr.getJSONObject(i);
+ String key = jo.getString(keyNode);
+ String value = jo.get(valueNode).toString();
+ map.put(key, value);
+ }
+ logger.debug("Completed Entry Array To Map Util Method");
+ return map;
+ }
- for(int i = 0; i < jsonArray.length(); i++){
- String s = jsonArray.get(i).toString();
- list.add(s);
- }
- logger.debug("Completed Json Util String Array To List");
- return list;
- }
+ /**
+ * This json util method converts a json array of Key Value pair objects into a Java Map.
+ *
+ * @param entryArray - the json Array of key/value pairs objects
+ * @param keyNode - the name of the node that represents the key
+ * @param valueNode - the name of the node that represents the value
+ * @return Map - a Map containing the entries
+ * @author cb645j
+ *
+ */
+ public Map<String, String> entryArrayToMap(String entryArray, String keyNode, String valueNode) {
+ logger.debug("Started Entry Array To Map Util Method");
+
+ Map<String, String> map = new HashMap<>();
+ String entryListJson = "{ \"wrapper\":" + entryArray + "}";
+ JSONObject obj = new JSONObject(entryListJson); // TODO just put in json array
+ JSONArray arr = obj.getJSONArray("wrapper");
+ for (int i = 0; i < arr.length(); i++) {
+ JSONObject jo = arr.getJSONObject(i);
+ String key = jo.getString(keyNode);
+ String value = jo.get(valueNode).toString();
+ map.put(key, value);
+ }
+ logger.debug("Completed Entry Array To Map Util Method");
+ return map;
+ }
- /**
- *
- * Invokes the getJsonRawValue() method to determine if the json element/variable exist.
- * Returns true if the json element exist
- *
- * @param jsonStr - String containing the JSON doc
- * @param keys - full key path to the target value in the format of "key1.key2.key3..."
- * @return boolean field value associated with keys
- *
- */
- public static boolean jsonElementExist(String jsonStr, String keys){
+ /**
+ * This json util method converts a json Array of Strings to a Java List. It takes each String in the json Array and
+ * puts it in a Java List<String>.
+ *
+ * @param execution
+ * @param jsonArray - string value of a json array
+ * @return List - a java list containing the strings
+ *
+ * @author cb645j
+ */
+ public List<String> StringArrayToList(Execution execution, String jsonArray) {
+ logger.debug("Started String Array To List Util Method");
+
+ List<String> list = new ArrayList<>();
+ // Populate List
+ // TODO
+ String stringListJson = "{ \"strings\":" + jsonArray + "}";
+ JSONObject obj = new JSONObject(stringListJson);
+ JSONArray arr = obj.getJSONArray("strings");
+ for (int i = 0; i < arr.length(); i++) {
+ String s = arr.get(i).toString();
+ list.add(s);
+ }
+ logger.debug("Outgoing List is: {}", list);
+ logger.debug("Completed String Array To List Util Method");
+ return list;
+ }
- try{
- Object rawValue = getJsonRawValue(jsonStr, keys);
+ /**
+ * This json util method converts a json Array of Strings to a Java List. It takes each String in the json Array and
+ * puts it in a Java List<String>.
+ *
+ * @param jsonArray - string value of a json array
+ * @return List - a java list containing the strings
+ *
+ * @author cb645j
+ */
+ public List<String> StringArrayToList(String jsonArray) {
+ logger.debug("Started Json Util String Array To List");
+ List<String> list = new ArrayList<>();
+
+ JSONArray arr = new JSONArray(jsonArray);
+ for (int i = 0; i < arr.length(); i++) {
+ String s = arr.get(i).toString();
+ list.add(s);
+ }
+ logger.debug("Completed Json Util String Array To List");
+ return list;
+ }
- return !(rawValue == null);
+ /**
+ * This json util method converts a json Array of Strings to a Java List. It takes each String in the json Array and
+ * puts it in a Java List<String>.
+ *
+ * @param jsonArray - json array
+ * @return List - a java list containing the strings
+ *
+ * @author cb645j
+ */
+ public List<String> StringArrayToList(JSONArray jsonArray) {
+ logger.debug("Started Json Util String Array To List");
+ List<String> list = new ArrayList<>();
+
+ for (int i = 0; i < jsonArray.length(); i++) {
+ String s = jsonArray.get(i).toString();
+ list.add(s);
+ }
+ logger.debug("Completed Json Util String Array To List");
+ return list;
+ }
- } catch(Exception e){
- logger.debug("jsonElementExist(): unable to determine if json element exist. Exception is: {}", e.toString(), e);
- }
- return true;
- }
+ /**
+ *
+ * Invokes the getJsonRawValue() method to determine if the json element/variable exist. Returns true if the json
+ * element exist
+ *
+ * @param jsonStr - String containing the JSON doc
+ * @param keys - full key path to the target value in the format of "key1.key2.key3..."
+ * @return boolean field value associated with keys
+ *
+ */
+ public static boolean jsonElementExist(String jsonStr, String keys) {
+
+ try {
+ Object rawValue = getJsonRawValue(jsonStr, keys);
+
+ return !(rawValue == null);
+
+ } catch (Exception e) {
+ logger.debug("jsonElementExist(): unable to determine if json element exist. Exception is: {}",
+ e.toString(), e);
+ }
+ return true;
+ }
- /**
- *
- * Validates the JSON document against a schema file.
- *
- * @param jsonStr String containing the JSON doc
- * @param jsonSchemaPath full path to a valid JSON schema file
- *
- */
+ /**
+ *
+ * Validates the JSON document against a schema file.
+ *
+ * @param jsonStr String containing the JSON doc
+ * @param jsonSchemaPath full path to a valid JSON schema file
+ *
+ */
public static String jsonSchemaValidation(String jsonStr, String jsonSchemaPath) throws ValidationException {
- try {
- logger.debug("JSON document to be validated: {}", jsonStr);
- JsonNode document = JsonLoader.fromString(jsonStr);
- JsonNode schema = JsonLoader.fromPath(jsonSchemaPath);
-
- JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
- JsonValidator validator = factory.getValidator();
-
- ProcessingReport report = validator.validate(schema, document);
- logger.debug("JSON schema validation report: {}", report.toString());
- return report.toString();
- } catch (IOException e) {
- logger.debug("IOException performing JSON schema validation on document: {}", e.toString());
- throw new ValidationException(e.getMessage());
- } catch (ProcessingException e) {
- logger.debug("ProcessingException performing JSON schema validation on document: {}", e.toString());
- throw new ValidationException(e.getMessage());
- }
+ try {
+ logger.debug("JSON document to be validated: {}", jsonStr);
+ JsonNode document = JsonLoader.fromString(jsonStr);
+ JsonNode schema = JsonLoader.fromPath(jsonSchemaPath);
+
+ JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
+ JsonValidator validator = factory.getValidator();
+
+ ProcessingReport report = validator.validate(schema, document);
+ logger.debug("JSON schema validation report: {}", report.toString());
+ return report.toString();
+ } catch (IOException e) {
+ logger.debug("IOException performing JSON schema validation on document: {}", e.toString());
+ throw new ValidationException(e.getMessage());
+ } catch (ProcessingException e) {
+ logger.debug("ProcessingException performing JSON schema validation on document: {}", e.toString());
+ throw new ValidationException(e.getMessage());
+ }
}
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/xml/XmlTool.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/xml/XmlTool.java
index 6c8070f9bd..da096e5461 100644
--- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/xml/XmlTool.java
+++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/xml/XmlTool.java
@@ -32,7 +32,6 @@ import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
@@ -49,7 +48,6 @@ import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
-
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -64,193 +62,194 @@ import org.xml.sax.SAXException;
*/
public final class XmlTool {
- private static final Map<String, Integer> ENTITIES = new HashMap<>();
- private static final Logger logger = LoggerFactory.getLogger(XmlTool.class);
- static {
- ENTITIES.put("amp", 38);
- ENTITIES.put("quot", 34);
- ENTITIES.put("lt", 60);
- ENTITIES.put("gt", 62);
- }
+ private static final Map<String, Integer> ENTITIES = new HashMap<>();
+ private static final Logger logger = LoggerFactory.getLogger(XmlTool.class);
+ static {
+ ENTITIES.put("amp", 38);
+ ENTITIES.put("quot", 34);
+ ENTITIES.put("lt", 60);
+ ENTITIES.put("gt", 62);
+ }
- /**
+ /**
* Instantiation is not allowed.
*/
- private XmlTool() {
+ private XmlTool() {}
+
+ /**
+ * Normalizes and formats XML. This method consolidates and moves all namespace declarations to the root element.
+ * The result will not have an XML prolog or a trailing newline.
+ *
+ * @param xml the XML to normalize
+ * @throws IOException
+ * @throws TransformerException
+ * @throws ParserConfigurationException
+ * @throws SAXException
+ * @throws XPathExpressionException
+ */
+ public static String normalize(Object xml) throws IOException, TransformerException, ParserConfigurationException,
+ SAXException, XPathExpressionException {
+
+ if (xml == null) {
+ return null;
+ }
+
+ Source xsltSource = new StreamSource(new StringReader(readResourceFile("normalize-namespaces.xsl")));
+
+ DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
+ dbFactory.setNamespaceAware(true);
+ dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ DocumentBuilder db = dbFactory.newDocumentBuilder();
+ InputSource source = new InputSource(new StringReader(String.valueOf(xml)));
+ Document doc = db.parse(source);
+
+ // Start of code to remove whitespace outside of tags
+ XPath xPath = XPathFactory.newInstance().newXPath();
+ NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", doc, XPathConstants.NODESET);
+
+ for (int i = 0; i < nodeList.getLength(); ++i) {
+ Node node = nodeList.item(i);
+ node.getParentNode().removeChild(node);
+ }
+ // End of code to remove whitespace outside of tags
+
+ // the factory pattern supports different XSLT processors
+ TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ Transformer transformer = transformerFactory.newTransformer(xsltSource);
+
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
+
+ StringWriter writer = new StringWriter();
+ transformer.transform(new DOMSource(doc), new StreamResult(writer));
+ return writer.toString().trim();
}
-
- /**
- * Normalizes and formats XML. This method consolidates and moves all namespace
- * declarations to the root element. The result will not have an XML prolog or
- * a trailing newline.
- * @param xml the XML to normalize
- * @throws IOException
- * @throws TransformerException
- * @throws ParserConfigurationException
- * @throws SAXException
- * @throws XPathExpressionException
- */
- public static String normalize(Object xml) throws IOException, TransformerException,
- ParserConfigurationException, SAXException, XPathExpressionException {
-
- if (xml == null) {
- return null;
- }
-
- Source xsltSource = new StreamSource(new StringReader(
- readResourceFile("normalize-namespaces.xsl")));
-
- DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
- dbFactory.setNamespaceAware(true);
- dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
- dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
- DocumentBuilder db = dbFactory.newDocumentBuilder();
- InputSource source = new InputSource(new StringReader(String.valueOf(xml)));
- Document doc = db.parse(source);
-
- // Start of code to remove whitespace outside of tags
- XPath xPath = XPathFactory.newInstance().newXPath();
- NodeList nodeList = (NodeList) xPath.evaluate(
- "//text()[normalize-space()='']", doc, XPathConstants.NODESET);
-
- for (int i = 0; i < nodeList.getLength(); ++i) {
- Node node = nodeList.item(i);
- node.getParentNode().removeChild(node);
- }
- // End of code to remove whitespace outside of tags
-
- // the factory pattern supports different XSLT processors
- TransformerFactory transformerFactory = TransformerFactory.newInstance();
- transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- Transformer transformer = transformerFactory.newTransformer(xsltSource);
-
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
- transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
-
- StringWriter writer = new StringWriter();
- transformer.transform(new DOMSource(doc), new StreamResult(writer));
- return writer.toString().trim();
- }
-
- /**
- * Encodes a value so it can be used inside an XML text element.
- * @param value the string to encode
- * @return the encoded string
- */
- public static String encode(Object value) {
- if (value == null) {
- return null;
- }
- return StringEscapeUtils.escapeXml11(value.toString());
- }
-
- /**
- * Removes the preamble, if present, from an XML document.
- * @param xml the XML document
- * @return a possibly modified document
- */
- public static String removePreamble(Object xml) {
- if (xml == null) {
- return null;
- }
-
- return String.valueOf(xml).replaceAll("(<\\?[^<]*\\?>\\s*[\\r\\n]*)?", "");
- }
- /**
- * Removes namespaces and namespace declarations from an XML document.
- * @param xml the XML document
- * @return a possibly modified document
- */
- public static String removeNamespaces(Object xml) {
- if (xml == null) {
- logger.debug("removeNamespaces input object is null , returning null");
- return null;
- }
-
- String text = String.valueOf(xml);
-
- // remove xmlns declaration
- text = text.replaceAll("xmlns.*?(\"|\').*?(\"|\')", "");
- // remove opening tag prefix
- text = text.replaceAll("(<)(\\w+:)(.*?>)", "$1$3");
- // remove closing tags prefix
- text = text.replaceAll("(</)(\\w+:)(.*?>)", "$1$3");
- // remove extra spaces left when xmlns declarations are removed
- text = text.replaceAll("\\s+>", ">");
-
- return text;
- }
+ /**
+ * Encodes a value so it can be used inside an XML text element.
+ *
+ * @param value the string to encode
+ * @return the encoded string
+ */
+ public static String encode(Object value) {
+ if (value == null) {
+ return null;
+ }
+ return StringEscapeUtils.escapeXml11(value.toString());
+ }
+ /**
+ * Removes the preamble, if present, from an XML document.
+ *
+ * @param xml the XML document
+ * @return a possibly modified document
+ */
+ public static String removePreamble(Object xml) {
+ if (xml == null) {
+ return null;
+ }
- /**
- * Reads the specified resource file and return the contents as a string.
- * @param file Name of the resource file
- * @return the contents of the resource file as a String
- * @throws IOException if there is a problem reading the file
- */
- private static String readResourceFile(String file) throws IOException {
+ return String.valueOf(xml).replaceAll("(<\\?[^<]*\\?>\\s*[\\r\\n]*)?", "");
+ }
- try (InputStream stream = XmlTool.class.getClassLoader().getResourceAsStream(file);
- Reader reader = new InputStreamReader(stream, "UTF-8")) {
+ /**
+ * Removes namespaces and namespace declarations from an XML document.
+ *
+ * @param xml the XML document
+ * @return a possibly modified document
+ */
+ public static String removeNamespaces(Object xml) {
+ if (xml == null) {
+ logger.debug("removeNamespaces input object is null , returning null");
+ return null;
+ }
+
+ String text = String.valueOf(xml);
+
+ // remove xmlns declaration
+ text = text.replaceAll("xmlns.*?(\"|\').*?(\"|\')", "");
+ // remove opening tag prefix
+ text = text.replaceAll("(<)(\\w+:)(.*?>)", "$1$3");
+ // remove closing tags prefix
+ text = text.replaceAll("(</)(\\w+:)(.*?>)", "$1$3");
+ // remove extra spaces left when xmlns declarations are removed
+ text = text.replaceAll("\\s+>", ">");
+
+ return text;
+ }
- StringBuilder out = new StringBuilder();
- char[] buf = new char[1024];
- int n;
- while ((n = reader.read(buf)) >= 0) {
- out.append(buf, 0, n);
- }
- return out.toString();
- } catch (Exception e) {
- logger.debug("Exception at readResourceFile stream: " + e);
- return null;
- }
- }
-
- /**
- * Parses the XML document String for the first occurrence of the specified element tag.
- * If found, the value associated with that element tag is replaced with the new value
- * and a String containing the modified XML document is returned. If the XML passed is
- * null or the element tag is not found in the document, null will be returned.
- * @param xml String containing the original XML document.
- * @param elementTag String containing the tag of the element to be modified.
- * @param newValue String containing the new value to be used to modify the corresponding element.
- * @return the contents of the modified XML document as a String or null/empty if the modification failed.
- * @throws IOException, TransformerException, ParserConfigurationException, SAXException
- */
- public static Optional<String> modifyElement(String xml, String elementTag, String newValue) throws IOException, TransformerException,
- ParserConfigurationException, SAXException {
+ /**
+ * Reads the specified resource file and return the contents as a string.
+ *
+ * @param file Name of the resource file
+ * @return the contents of the resource file as a String
+ * @throws IOException if there is a problem reading the file
+ */
+ private static String readResourceFile(String file) throws IOException {
+
+ try (InputStream stream = XmlTool.class.getClassLoader().getResourceAsStream(file);
+ Reader reader = new InputStreamReader(stream, "UTF-8")) {
+
+ StringBuilder out = new StringBuilder();
+ char[] buf = new char[1024];
+ int n;
+
+ while ((n = reader.read(buf)) >= 0) {
+ out.append(buf, 0, n);
+ }
+ return out.toString();
+ } catch (Exception e) {
+ logger.debug("Exception at readResourceFile stream: " + e);
+ return null;
+ }
+ }
- if (xml == null || xml.isEmpty()) {
- // no XML content to be modified, return empty
- return Optional.empty();
- }
-
- DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
- dbFactory.setNamespaceAware(true);
- dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
- dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
- DocumentBuilder db = dbFactory.newDocumentBuilder();
- InputSource source = new InputSource(new StringReader(xml));
- Document doc = db.parse(source);
-
- Node modNode = doc.getElementsByTagName(elementTag).item(0);
- if (modNode == null) {
- // did not find the specified element to be modified, return empty
- //System.out.println("Did not find element tag " + elementTag + " in XML");
- return Optional.empty();
- } else {
- modNode.setTextContent(newValue);
- }
-
- TransformerFactory transformerFactory = TransformerFactory.newInstance();
- Transformer transformer = transformerFactory.newTransformer();
- StringWriter writer = new StringWriter();
- transformer.transform(new DOMSource(doc), new StreamResult(writer));
- // return the modified String representation of the XML
- return Optional.of(writer.toString().trim());
- }
+ /**
+ * Parses the XML document String for the first occurrence of the specified element tag. If found, the value
+ * associated with that element tag is replaced with the new value and a String containing the modified XML document
+ * is returned. If the XML passed is null or the element tag is not found in the document, null will be returned.
+ *
+ * @param xml String containing the original XML document.
+ * @param elementTag String containing the tag of the element to be modified.
+ * @param newValue String containing the new value to be used to modify the corresponding element.
+ * @return the contents of the modified XML document as a String or null/empty if the modification failed.
+ * @throws IOException, TransformerException, ParserConfigurationException, SAXException
+ */
+ public static Optional<String> modifyElement(String xml, String elementTag, String newValue)
+ throws IOException, TransformerException, ParserConfigurationException, SAXException {
+
+ if (xml == null || xml.isEmpty()) {
+ // no XML content to be modified, return empty
+ return Optional.empty();
+ }
+
+ DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
+ dbFactory.setNamespaceAware(true);
+ dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ DocumentBuilder db = dbFactory.newDocumentBuilder();
+ InputSource source = new InputSource(new StringReader(xml));
+ Document doc = db.parse(source);
+
+ Node modNode = doc.getElementsByTagName(elementTag).item(0);
+ if (modNode == null) {
+ // did not find the specified element to be modified, return empty
+ // System.out.println("Did not find element tag " + elementTag + " in XML");
+ return Optional.empty();
+ } else {
+ modNode.setTextContent(newValue);
+ }
+
+ TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ Transformer transformer = transformerFactory.newTransformer();
+ StringWriter writer = new StringWriter();
+ transformer.transform(new DOMSource(doc), new StreamResult(writer));
+ // return the modified String representation of the XML
+ return Optional.of(writer.toString().trim());
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BadInjectedFiledExceptionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BadInjectedFiledExceptionTest.java
index b35e65485f..67b33602dd 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BadInjectedFiledExceptionTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BadInjectedFiledExceptionTest.java
@@ -1,22 +1,17 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core;
@@ -25,22 +20,22 @@ import org.junit.Test;
public class BadInjectedFiledExceptionTest {
- private BadInjectedFieldException badInjectedFieldException;
-
- @Test
- public void test() {
- String fieldName = "anyFieldName";
- String taskName = "anyTask";
- Object info = new String("info");
-
- String expectedMessage1 = taskName+" injected field '"+fieldName+"' is bad: "+(String)info;
- badInjectedFieldException = new BadInjectedFieldException(fieldName, taskName, info);
- assertEquals(expectedMessage1, badInjectedFieldException.getMessage());
-
- String expectedMessage2 = "java.lang.Throwable: anyCause";
- Throwable cause = new Throwable("anyCause");
- badInjectedFieldException = new BadInjectedFieldException(fieldName, taskName, info, cause);
- assertEquals(expectedMessage2, badInjectedFieldException.getCause().toString());
-
- }
+ private BadInjectedFieldException badInjectedFieldException;
+
+ @Test
+ public void test() {
+ String fieldName = "anyFieldName";
+ String taskName = "anyTask";
+ Object info = new String("info");
+
+ String expectedMessage1 = taskName + " injected field '" + fieldName + "' is bad: " + (String) info;
+ badInjectedFieldException = new BadInjectedFieldException(fieldName, taskName, info);
+ assertEquals(expectedMessage1, badInjectedFieldException.getMessage());
+
+ String expectedMessage2 = "java.lang.Throwable: anyCause";
+ Throwable cause = new Throwable("anyCause");
+ badInjectedFieldException = new BadInjectedFieldException(fieldName, taskName, info, cause);
+ assertEquals(expectedMessage2, badInjectedFieldException.getCause().toString());
+
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java
index 40fcb982c1..49f373c01e 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java
@@ -1,22 +1,17 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core;
@@ -24,7 +19,6 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.ProcessEngineServices;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.delegate.DelegateExecution;
@@ -33,215 +27,215 @@ import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-
import org.junit.rules.ExpectedException;
public class BaseTaskTest {
- private String prefix = "PRE_";
- private String processKey = "AnyProcessKey";
- private String definitionId = "100";
- private String anyVariable = "anyVariable";
- private String anyValueString = "anyValue";
- private String badValueString = "123abc";
- private int anyValueInt = 123;
- private Integer anyValueInteger = new Integer(anyValueInt);
- private long anyValuelong = 123L;
- private Long anyValueLong = new Long(anyValuelong);
-
- private DelegateExecution mockExecution;
- private Expression mockExpression;
- private BaseTask baseTask;
- private Object obj1;
- private Object obj2;
- private Object objectString;
- private Object objectInteger;
- private Object objectLong;
- private Object objectBoolean;
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Before
- public void before() throws Exception {
- baseTask = new BaseTask();
- ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class);
- when(mockProcessDefinition.getKey()).thenReturn(processKey);
- RepositoryService mockRepositoryService = mock(RepositoryService.class);
- when(mockRepositoryService.getProcessDefinition(definitionId)).thenReturn(mockProcessDefinition);
- ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class);
- when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService);
- mockExecution = mock(DelegateExecution.class);
- when(mockExecution.getId()).thenReturn(definitionId);
- when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices);
- when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition);
- when(mockExecution.getVariable("prefix")).thenReturn(prefix);
- when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true");
- mockExpression = mock(Expression.class);
- }
-
- @Test
- public void testExecution() throws Exception{
- baseTask.execute(mockExecution);
- assertEquals("BaseTask", baseTask.getTaskName());
- }
-
- @Test
- public void testGetFieldAndMissingInjectedException() throws Exception{
- objectString = new String(anyValueString);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
- obj1 = baseTask.getField(mockExpression, mockExecution, anyVariable);
- assertEquals(anyValueString, obj1.toString());
-
- expectedException.expect(MissingInjectedFieldException.class);
- obj2 = baseTask.getField(null, mockExecution, anyVariable);
- }
-
- @Test
- public void testGetFieldAndBadInjectedFieldException() throws Exception{
- expectedException.expect(BadInjectedFieldException.class);
- obj1 = baseTask.getField(mockExpression, mockExecution, null);
- }
-
- @Test
- public void testGetOptionalField() throws Exception{
- objectString = new String(anyValueString);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
- obj1 = baseTask.getOptionalField(mockExpression, mockExecution, anyVariable);
- assertEquals(anyValueString, obj1.toString());
- }
-
- @Test
- public void testGetStringFieldAndMissingInjectedFieldException() throws Exception{
- objectString = new String(anyValueString);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
- obj1 = baseTask.getStringField(mockExpression, mockExecution, anyVariable);
- assertEquals(anyValueString, obj1.toString());
-
- expectedException.expect(MissingInjectedFieldException.class);
- Object objectBoolean = new Boolean(true); // bad data
- when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean);
- obj2 = baseTask.getStringField(null, mockExecution, anyVariable);
- }
-
- @Test
- public void testGetStringFieldAndBadInjectedFieldException() throws Exception{
- expectedException.expect(BadInjectedFieldException.class);
- obj1 = baseTask.getStringField(mockExpression, mockExecution, null);
- }
-
- @Test
- public void testGetOptionalStringField() throws Exception{
- objectString = new String(anyValueString);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
- obj1 = baseTask.getOptionalStringField(mockExpression, mockExecution, anyVariable);
- assertEquals(anyValueString, obj1.toString());
- }
-
- @Test
- public void testGetIntegerFieldAndMissingInjectedFieldException() throws Exception{
- objectInteger = new Integer(anyValueInt);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectInteger);
- obj1 = baseTask.getIntegerField(mockExpression, mockExecution, anyVariable);
- assertEquals(anyValueInteger, (Integer)obj1);
-
- expectedException.expect(MissingInjectedFieldException.class);
- objectString = new String(badValueString);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
- obj2 = baseTask.getIntegerField(null, mockExecution, anyVariable);
- }
-
- @Test
- public void testGetIntegerFieldAndBadInjectedFieldException() throws Exception{
- expectedException.expect(BadInjectedFieldException.class);
- obj1 = baseTask.getIntegerField(mockExpression, mockExecution, null);
- }
-
-
- @Test
- public void testGetOptionalIntegerField() throws Exception{
- objectInteger = new Integer(anyValueInt);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectInteger);
- obj1 = baseTask.getOptionalIntegerField(mockExpression, mockExecution, anyVariable);
- assertEquals(anyValueInteger, (Integer)obj1);
- }
-
- @Test
- public void testGetOptionalIntegerFieldAndBadInjectedFieldException() throws Exception{
- expectedException.expect(BadInjectedFieldException.class);
- objectBoolean = new Boolean(true);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean);
- obj1 = baseTask.getOptionalIntegerField(mockExpression, mockExecution, anyVariable);
- }
-
- @Test
- public void testGetLongFieldAndMissingInjectedFieldException() throws Exception{
- objectLong = new Long(anyValuelong);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectLong);
- obj1 = baseTask.getLongField(mockExpression, mockExecution, anyVariable);
- assertEquals(anyValueLong, (Long)obj1);
-
- expectedException.expect(MissingInjectedFieldException.class);
- objectString = new String(badValueString);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
- obj2 = baseTask.getLongField(null, mockExecution, anyVariable);
- }
-
- @Test
- public void testGetLongFieldAndBadInjectedFieldException() throws Exception{
- expectedException.expect(BadInjectedFieldException.class);
- obj2 = baseTask.getLongField(mockExpression, mockExecution, null);
- }
-
- @Test
- public void testGetOptionalLongField() throws Exception{
- objectLong = new Long(anyValuelong);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectLong);
- obj1 = baseTask.getOptionalLongField(mockExpression, mockExecution, anyVariable);
- assertEquals(anyValueLong, (Long)obj1);
- }
-
- @Test
- public void testGetOptionalLongFieldAndBadInjectedFieldException() throws Exception{
- expectedException.expect(BadInjectedFieldException.class);
- objectBoolean = new Boolean(true);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean);
- obj1 = baseTask.getOptionalLongField(mockExpression, mockExecution, anyVariable);
- }
-
- @Test
- public void testGetOutputAndMissingInjectedFieldException() throws Exception{
- objectString = new String(anyValueString);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
- obj1 = baseTask.getOutputField(mockExpression, mockExecution, anyVariable);
- assertEquals(anyValueString, obj1.toString());
-
- expectedException.expect(MissingInjectedFieldException.class);
- objectString = new String(anyValueString);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
- obj2 = baseTask.getOutputField(null, mockExecution, anyVariable);
- }
-
- @Test
- public void testGetOutputAndBadInjectedFieldException() throws Exception{
- expectedException.expect(BadInjectedFieldException.class);
- obj2 = baseTask.getOutputField(null, mockExecution, anyVariable);
- }
-
- @Test
- public void testGetOptionalOutputField() throws Exception{
- objectString = new String(anyValueString);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
- obj1 = baseTask.getOptionalOutputField(mockExpression, mockExecution, anyVariable);
- assertEquals(anyValueString, obj1.toString());
- }
-
- @Test
- public void testGetOptionalOutputFieldAndBadInjectedFieldException() throws Exception{
- expectedException.expect(BadInjectedFieldException.class);
- objectBoolean = new Boolean(true);
- when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean);
- obj1 = baseTask.getOptionalOutputField(mockExpression, mockExecution, anyVariable);
- }
-
+ private String prefix = "PRE_";
+ private String processKey = "AnyProcessKey";
+ private String definitionId = "100";
+ private String anyVariable = "anyVariable";
+ private String anyValueString = "anyValue";
+ private String badValueString = "123abc";
+ private int anyValueInt = 123;
+ private Integer anyValueInteger = new Integer(anyValueInt);
+ private long anyValuelong = 123L;
+ private Long anyValueLong = new Long(anyValuelong);
+
+ private DelegateExecution mockExecution;
+ private Expression mockExpression;
+ private BaseTask baseTask;
+ private Object obj1;
+ private Object obj2;
+ private Object objectString;
+ private Object objectInteger;
+ private Object objectLong;
+ private Object objectBoolean;
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Before
+ public void before() throws Exception {
+ baseTask = new BaseTask();
+ ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class);
+ when(mockProcessDefinition.getKey()).thenReturn(processKey);
+ RepositoryService mockRepositoryService = mock(RepositoryService.class);
+ when(mockRepositoryService.getProcessDefinition(definitionId)).thenReturn(mockProcessDefinition);
+ ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class);
+ when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService);
+ mockExecution = mock(DelegateExecution.class);
+ when(mockExecution.getId()).thenReturn(definitionId);
+ when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices);
+ when(mockExecution.getProcessEngineServices().getRepositoryService()
+ .getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition);
+ when(mockExecution.getVariable("prefix")).thenReturn(prefix);
+ when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true");
+ mockExpression = mock(Expression.class);
+ }
+
+ @Test
+ public void testExecution() throws Exception {
+ baseTask.execute(mockExecution);
+ assertEquals("BaseTask", baseTask.getTaskName());
+ }
+
+ @Test
+ public void testGetFieldAndMissingInjectedException() throws Exception {
+ objectString = new String(anyValueString);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
+ obj1 = baseTask.getField(mockExpression, mockExecution, anyVariable);
+ assertEquals(anyValueString, obj1.toString());
+
+ expectedException.expect(MissingInjectedFieldException.class);
+ obj2 = baseTask.getField(null, mockExecution, anyVariable);
+ }
+
+ @Test
+ public void testGetFieldAndBadInjectedFieldException() throws Exception {
+ expectedException.expect(BadInjectedFieldException.class);
+ obj1 = baseTask.getField(mockExpression, mockExecution, null);
+ }
+
+ @Test
+ public void testGetOptionalField() throws Exception {
+ objectString = new String(anyValueString);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
+ obj1 = baseTask.getOptionalField(mockExpression, mockExecution, anyVariable);
+ assertEquals(anyValueString, obj1.toString());
+ }
+
+ @Test
+ public void testGetStringFieldAndMissingInjectedFieldException() throws Exception {
+ objectString = new String(anyValueString);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
+ obj1 = baseTask.getStringField(mockExpression, mockExecution, anyVariable);
+ assertEquals(anyValueString, obj1.toString());
+
+ expectedException.expect(MissingInjectedFieldException.class);
+ Object objectBoolean = new Boolean(true); // bad data
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean);
+ obj2 = baseTask.getStringField(null, mockExecution, anyVariable);
+ }
+
+ @Test
+ public void testGetStringFieldAndBadInjectedFieldException() throws Exception {
+ expectedException.expect(BadInjectedFieldException.class);
+ obj1 = baseTask.getStringField(mockExpression, mockExecution, null);
+ }
+
+ @Test
+ public void testGetOptionalStringField() throws Exception {
+ objectString = new String(anyValueString);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
+ obj1 = baseTask.getOptionalStringField(mockExpression, mockExecution, anyVariable);
+ assertEquals(anyValueString, obj1.toString());
+ }
+
+ @Test
+ public void testGetIntegerFieldAndMissingInjectedFieldException() throws Exception {
+ objectInteger = new Integer(anyValueInt);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectInteger);
+ obj1 = baseTask.getIntegerField(mockExpression, mockExecution, anyVariable);
+ assertEquals(anyValueInteger, (Integer) obj1);
+
+ expectedException.expect(MissingInjectedFieldException.class);
+ objectString = new String(badValueString);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
+ obj2 = baseTask.getIntegerField(null, mockExecution, anyVariable);
+ }
+
+ @Test
+ public void testGetIntegerFieldAndBadInjectedFieldException() throws Exception {
+ expectedException.expect(BadInjectedFieldException.class);
+ obj1 = baseTask.getIntegerField(mockExpression, mockExecution, null);
+ }
+
+
+ @Test
+ public void testGetOptionalIntegerField() throws Exception {
+ objectInteger = new Integer(anyValueInt);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectInteger);
+ obj1 = baseTask.getOptionalIntegerField(mockExpression, mockExecution, anyVariable);
+ assertEquals(anyValueInteger, (Integer) obj1);
+ }
+
+ @Test
+ public void testGetOptionalIntegerFieldAndBadInjectedFieldException() throws Exception {
+ expectedException.expect(BadInjectedFieldException.class);
+ objectBoolean = new Boolean(true);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean);
+ obj1 = baseTask.getOptionalIntegerField(mockExpression, mockExecution, anyVariable);
+ }
+
+ @Test
+ public void testGetLongFieldAndMissingInjectedFieldException() throws Exception {
+ objectLong = new Long(anyValuelong);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectLong);
+ obj1 = baseTask.getLongField(mockExpression, mockExecution, anyVariable);
+ assertEquals(anyValueLong, (Long) obj1);
+
+ expectedException.expect(MissingInjectedFieldException.class);
+ objectString = new String(badValueString);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
+ obj2 = baseTask.getLongField(null, mockExecution, anyVariable);
+ }
+
+ @Test
+ public void testGetLongFieldAndBadInjectedFieldException() throws Exception {
+ expectedException.expect(BadInjectedFieldException.class);
+ obj2 = baseTask.getLongField(mockExpression, mockExecution, null);
+ }
+
+ @Test
+ public void testGetOptionalLongField() throws Exception {
+ objectLong = new Long(anyValuelong);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectLong);
+ obj1 = baseTask.getOptionalLongField(mockExpression, mockExecution, anyVariable);
+ assertEquals(anyValueLong, (Long) obj1);
+ }
+
+ @Test
+ public void testGetOptionalLongFieldAndBadInjectedFieldException() throws Exception {
+ expectedException.expect(BadInjectedFieldException.class);
+ objectBoolean = new Boolean(true);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean);
+ obj1 = baseTask.getOptionalLongField(mockExpression, mockExecution, anyVariable);
+ }
+
+ @Test
+ public void testGetOutputAndMissingInjectedFieldException() throws Exception {
+ objectString = new String(anyValueString);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
+ obj1 = baseTask.getOutputField(mockExpression, mockExecution, anyVariable);
+ assertEquals(anyValueString, obj1.toString());
+
+ expectedException.expect(MissingInjectedFieldException.class);
+ objectString = new String(anyValueString);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
+ obj2 = baseTask.getOutputField(null, mockExecution, anyVariable);
+ }
+
+ @Test
+ public void testGetOutputAndBadInjectedFieldException() throws Exception {
+ expectedException.expect(BadInjectedFieldException.class);
+ obj2 = baseTask.getOutputField(null, mockExecution, anyVariable);
+ }
+
+ @Test
+ public void testGetOptionalOutputField() throws Exception {
+ objectString = new String(anyValueString);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
+ obj1 = baseTask.getOptionalOutputField(mockExpression, mockExecution, anyVariable);
+ assertEquals(anyValueString, obj1.toString());
+ }
+
+ @Test
+ public void testGetOptionalOutputFieldAndBadInjectedFieldException() throws Exception {
+ expectedException.expect(BadInjectedFieldException.class);
+ objectBoolean = new Boolean(true);
+ when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean);
+ obj1 = baseTask.getOptionalOutputField(mockExpression, mockExecution, anyVariable);
+ }
+
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BeansTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BeansTest.java
index 2415e619d7..965a9cc04d 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BeansTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BeansTest.java
@@ -24,17 +24,14 @@ import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.onap.so.openpojo.rules.HasAnnotationMatcher.hasAnnotation;
import static org.onap.so.openpojo.rules.HasAnnotationPropertyWithValueMatcher.hasAnnotationPropertyWithValue;
-
import javax.persistence.Column;
import javax.persistence.Temporal;
-
import org.junit.Test;
import org.onap.so.openpojo.rules.CustomSetterMustExistRule;
import org.onap.so.openpojo.rules.EqualsAndHashCodeTester;
import org.onap.so.openpojo.rules.HasEqualsAndHashCodeRule;
import org.onap.so.openpojo.rules.HasToStringRule;
import org.onap.so.openpojo.rules.ToStringTester;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterEnum;
@@ -55,37 +52,35 @@ import com.openpojo.validation.test.impl.SetterTester;
public class BeansTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
-
- private PojoClassFilter enumFilter = new FilterEnum();
-
-
-
- @Test
- public void pojoStructure() {
- test("org.onap.so.bpmn.core.domain");
-
- }
-
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new NoNestedClassRule())
- .with(new SerializableMustHaveSerialVersionUIDRule())
- .with(new NoPublicFieldsExceptStaticFinalRule())
- .with(new SetterTester())
- .with(new GetterTester())
-
-
-
- .build();
-
-
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses,enumFilter,new FilterNonConcrete());
- }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ private PojoClassFilter enumFilter = new FilterEnum();
+
+
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.bpmn.core.domain");
+
+ }
+
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new NoNestedClassRule())
+ .with(new SerializableMustHaveSerialVersionUIDRule()).with(new NoPublicFieldsExceptStaticFinalRule())
+ .with(new SetterTester()).with(new GetterTester())
+
+
+
+ .build();
+
+
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, enumFilter,
+ new FilterNonConcrete());
+ }
+
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/MissingInjectedFiledExceptionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/MissingInjectedFiledExceptionTest.java
index b0aa41b05d..1bc0153956 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/MissingInjectedFiledExceptionTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/MissingInjectedFiledExceptionTest.java
@@ -1,22 +1,17 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core;
@@ -25,15 +20,15 @@ import org.junit.Test;
public class MissingInjectedFiledExceptionTest {
- private MissingInjectedFieldException missingInjectedFieldException;
-
- @Test
- public void test() {
- String fieldName = "anyFieldName";
- String taskName = "anyTask";
- String info = "missing required field";
- String expectedMessage1 = taskName+" injected field '"+fieldName+"' is bad: "+info;
- missingInjectedFieldException = new MissingInjectedFieldException(fieldName, taskName);
- assertEquals(expectedMessage1, missingInjectedFieldException.getMessage());
- }
+ private MissingInjectedFieldException missingInjectedFieldException;
+
+ @Test
+ public void test() {
+ String fieldName = "anyFieldName";
+ String taskName = "anyTask";
+ String info = "missing required field";
+ String expectedMessage1 = taskName + " injected field '" + fieldName + "' is bad: " + info;
+ missingInjectedFieldException = new MissingInjectedFieldException(fieldName, taskName);
+ assertEquals(expectedMessage1, missingInjectedFieldException.getMessage());
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/ResponseBuilderTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/ResponseBuilderTest.java
index b605209739..b06837aa0d 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/ResponseBuilderTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/ResponseBuilderTest.java
@@ -1,29 +1,23 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.ProcessEngineServices;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.delegate.DelegateExecution;
@@ -33,78 +27,79 @@ import org.junit.Test;
public class ResponseBuilderTest {
- private String prefix = "PRE_";
- private String processKey = "AnyProcessKey";
- private String definitionId = "100";
- private int errorCode_200 = 200;
- private int errorCode_404 = 404;
- private String errorMessage = "any error message!";
- private String errorMessageXML = "<ErrorMessage>any error message!</ErrorMessage><ErrorCode>200</ErrorCode>";
- private String response = "<WorkflowResponse>bad</WorkflowResponse>";
-
- private DelegateExecution mockExecution;
- private ResponseBuilder responseBuilder;
- private WorkflowException workflowException;
- private Object obj;
-
- @Before
- public void before() throws Exception {
- responseBuilder = new ResponseBuilder();
- ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class);
- when(mockProcessDefinition.getKey()).thenReturn(processKey);
- RepositoryService mockRepositoryService = mock(RepositoryService.class);
- when(mockRepositoryService.getProcessDefinition(definitionId)).thenReturn(mockProcessDefinition);
- ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class);
- when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService);
- mockExecution = mock(DelegateExecution.class);
- when(mockExecution.getId()).thenReturn(definitionId);
- when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices);
- when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition);
- when(mockExecution.getVariable("prefix")).thenReturn(prefix);
- when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true");
- }
-
- @Test
- public void buildWorkflowException_WorkflowException_2000_Test() {
- when(mockExecution.getVariable(prefix+"ErrorResponse")).thenReturn(errorMessage);
- when(mockExecution.getVariable(prefix+"ResponseCode")).thenReturn(errorCode_200);
- workflowException = responseBuilder.buildWorkflowException(mockExecution);
- assertEquals(2000, workflowException.getErrorCode());
- assertEquals("any error message!", workflowException.getErrorMessage());
- }
+ private String prefix = "PRE_";
+ private String processKey = "AnyProcessKey";
+ private String definitionId = "100";
+ private int errorCode_200 = 200;
+ private int errorCode_404 = 404;
+ private String errorMessage = "any error message!";
+ private String errorMessageXML = "<ErrorMessage>any error message!</ErrorMessage><ErrorCode>200</ErrorCode>";
+ private String response = "<WorkflowResponse>bad</WorkflowResponse>";
+
+ private DelegateExecution mockExecution;
+ private ResponseBuilder responseBuilder;
+ private WorkflowException workflowException;
+ private Object obj;
+
+ @Before
+ public void before() throws Exception {
+ responseBuilder = new ResponseBuilder();
+ ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class);
+ when(mockProcessDefinition.getKey()).thenReturn(processKey);
+ RepositoryService mockRepositoryService = mock(RepositoryService.class);
+ when(mockRepositoryService.getProcessDefinition(definitionId)).thenReturn(mockProcessDefinition);
+ ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class);
+ when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService);
+ mockExecution = mock(DelegateExecution.class);
+ when(mockExecution.getId()).thenReturn(definitionId);
+ when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices);
+ when(mockExecution.getProcessEngineServices().getRepositoryService()
+ .getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition);
+ when(mockExecution.getVariable("prefix")).thenReturn(prefix);
+ when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true");
+ }
+
+ @Test
+ public void buildWorkflowException_WorkflowException_2000_Test() {
+ when(mockExecution.getVariable(prefix + "ErrorResponse")).thenReturn(errorMessage);
+ when(mockExecution.getVariable(prefix + "ResponseCode")).thenReturn(errorCode_200);
+ workflowException = responseBuilder.buildWorkflowException(mockExecution);
+ assertEquals(2000, workflowException.getErrorCode());
+ assertEquals("any error message!", workflowException.getErrorMessage());
+ }
+
+ @Test
+ public void buildWorkflowException_WorkflowException_XML_2000_Test() {
+ when(mockExecution.getVariable(prefix + "ErrorResponse")).thenReturn(errorMessageXML);
+ when(mockExecution.getVariable(prefix + "ResponseCode")).thenReturn(errorCode_200);
+ workflowException = responseBuilder.buildWorkflowException(mockExecution);
+ assertEquals(2000, workflowException.getErrorCode());
+ assertEquals("any error message!", workflowException.getErrorMessage());
+ }
+
+ @Test
+ public void buildWorkflowException_WorkflowException_NULL_Test() {
+ when(mockExecution.getVariable(prefix + "ErrorResponse")).thenReturn(null);
+ when(mockExecution.getVariable(prefix + "ResponseCode")).thenReturn(null);
+ workflowException = responseBuilder.buildWorkflowException(mockExecution);
+ assertEquals(null, workflowException);
+ }
+
+ @Test
+ public void buildWorkflowException_Response_1002_Test() {
+ when(mockExecution.getVariable(processKey + "Response")).thenReturn(response);
+ when(mockExecution.getVariable(prefix + "ResponseCode")).thenReturn(errorCode_404);
+ workflowException = responseBuilder.buildWorkflowException(mockExecution);
+ assertEquals(response, workflowException.getErrorMessage());
+ assertEquals(1002, workflowException.getErrorCode());
+ }
+
+ @Test
+ public void buildWorkflowResponse_Object_Test() {
+ String workflowResponse = "<WorkflowResponse>good</WorkflowResponse>";
+ when(mockExecution.getVariable("WorkflowResponse")).thenReturn(workflowResponse);
+ obj = responseBuilder.buildWorkflowResponse(mockExecution);
+ assertEquals(workflowResponse, obj);
+ }
- @Test
- public void buildWorkflowException_WorkflowException_XML_2000_Test() {
- when(mockExecution.getVariable(prefix+"ErrorResponse")).thenReturn(errorMessageXML);
- when(mockExecution.getVariable(prefix+"ResponseCode")).thenReturn(errorCode_200);
- workflowException = responseBuilder.buildWorkflowException(mockExecution);
- assertEquals(2000, workflowException.getErrorCode());
- assertEquals("any error message!", workflowException.getErrorMessage());
- }
-
- @Test
- public void buildWorkflowException_WorkflowException_NULL_Test() {
- when(mockExecution.getVariable(prefix+"ErrorResponse")).thenReturn(null);
- when(mockExecution.getVariable(prefix+"ResponseCode")).thenReturn(null);
- workflowException = responseBuilder.buildWorkflowException(mockExecution);
- assertEquals(null, workflowException);
- }
-
- @Test
- public void buildWorkflowException_Response_1002_Test() {
- when(mockExecution.getVariable(processKey+"Response")).thenReturn(response);
- when(mockExecution.getVariable(prefix+"ResponseCode")).thenReturn(errorCode_404);
- workflowException = responseBuilder.buildWorkflowException(mockExecution);
- assertEquals(response, workflowException.getErrorMessage());
- assertEquals(1002, workflowException.getErrorCode());
- }
-
- @Test
- public void buildWorkflowResponse_Object_Test() {
- String workflowResponse = "<WorkflowResponse>good</WorkflowResponse>";
- when(mockExecution.getVariable("WorkflowResponse")).thenReturn(workflowResponse);
- obj = responseBuilder.buildWorkflowResponse(mockExecution);
- assertEquals(workflowResponse, obj);
- }
-
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/RollbackDataTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/RollbackDataTest.java
index 875df6cf94..86a9ecf57e 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/RollbackDataTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/RollbackDataTest.java
@@ -29,7 +29,6 @@ import static org.junit.Assert.assertTrue;
import static org.hamcrest.Matchers.isIn;
import java.util.Arrays;
import java.util.Collections;
-
import org.junit.Test;
public class RollbackDataTest {
@@ -48,11 +47,11 @@ public class RollbackDataTest {
data.put(TYPE_A, "key2", "value2");
data.put(TYPE_B, "key3", "value3");
// when, then
- assertThat(data.toString(), isIn(Arrays.asList(
- "[typeB{key3=value3},typeA{key1=value1, key2=value2}]",
- "[typeB{key3=value3},typeA{key2=value2, key1=value1}]",
- "[typeA{key1=value1, key2=value2},typeB{key3=value3}]",
- "[typeA{key2=value2, key1=value1},typeB{key3=value3}]")));
+ assertThat(data.toString(),
+ isIn(Arrays.asList("[typeB{key3=value3},typeA{key1=value1, key2=value2}]",
+ "[typeB{key3=value3},typeA{key2=value2, key1=value1}]",
+ "[typeA{key1=value1, key2=value2},typeB{key3=value3}]",
+ "[typeA{key2=value2, key1=value1},typeB{key3=value3}]")));
}
@Test
@@ -89,4 +88,4 @@ public class RollbackDataTest {
assertEquals(VALUE_2, data.get(TYPE_B, KEY_1));
assertThat(data.get(TYPE_B), is(Collections.singletonMap(KEY_1, VALUE_2)));
}
-} \ No newline at end of file
+}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/UrnPropertiesReaderTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/UrnPropertiesReaderTest.java
index 5d9a1d61f2..f0c3d39625 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/UrnPropertiesReaderTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/UrnPropertiesReaderTest.java
@@ -24,36 +24,35 @@ import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.env.Environment;
-
import static org.mockito.Mockito.*;
public class UrnPropertiesReaderTest {
@Test
- public void testGetVariableFromExecution() {
+ public void testGetVariableFromExecution() {
ExecutionEntity mockExecution = mock(ExecutionEntity.class);
when(mockExecution.getVariable("testKey")).thenReturn("testValue");
- String value = UrnPropertiesReader.getVariable("testKey",mockExecution);
+ String value = UrnPropertiesReader.getVariable("testKey", mockExecution);
Assert.assertEquals("testValue", value);
verify(mockExecution).getVariable("testKey");
verify(mockExecution, never()).setVariable("testKey", value);
}
@Test
- public void testGetVariableFromEnvironment() {
+ public void testGetVariableFromEnvironment() {
ExecutionEntity mockExecution = mock(ExecutionEntity.class);
Environment mockEnvironment = mock(Environment.class);
when(mockEnvironment.getProperty("testKey")).thenReturn("testValue");
UrnPropertiesReader urnPropertiesReader = new UrnPropertiesReader();
urnPropertiesReader.setEnvironment(mockEnvironment);
- String value = UrnPropertiesReader.getVariable("testKey",mockExecution);
- Assert.assertEquals("testValue",value);
+ String value = UrnPropertiesReader.getVariable("testKey", mockExecution);
+ Assert.assertEquals("testValue", value);
verify(mockExecution).getVariable("testKey");
verify(mockExecution).setVariable("testKey", value);
}
@Test
- public void testGetVariableNotExist() {
+ public void testGetVariableNotExist() {
ExecutionEntity mockExecution = mock(ExecutionEntity.class);
String value = UrnPropertiesReader.getVariable("notExist", mockExecution);
Assert.assertEquals(null, value);
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/WorkflowExceptionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/WorkflowExceptionTest.java
index c1e9b8776b..2792b1bd73 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/WorkflowExceptionTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/WorkflowExceptionTest.java
@@ -1,47 +1,41 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
-
import org.junit.Test;
public class WorkflowExceptionTest {
- private WorkflowException workflowException;
-
- @Test
- public void test() {
- String processKey = "AnyProcessKey";
- int errorCode = 200;
- String errorMessage = "any error message!";
- workflowException = new WorkflowException(processKey, errorCode, errorMessage);
- assertEquals(errorCode, workflowException.getErrorCode());
- assertEquals(errorMessage, workflowException.getErrorMessage());
- assertEquals(processKey, workflowException.getProcessKey());
- assertEquals("*", workflowException.getWorkStep());
- String workStep = "one";
- workflowException = new WorkflowException(processKey, errorCode, errorMessage, workStep);
- assertEquals(workStep, workflowException.getWorkStep());
- assertNotEquals(null, workflowException.toString());
- }
+ private WorkflowException workflowException;
+
+ @Test
+ public void test() {
+ String processKey = "AnyProcessKey";
+ int errorCode = 200;
+ String errorMessage = "any error message!";
+ workflowException = new WorkflowException(processKey, errorCode, errorMessage);
+ assertEquals(errorCode, workflowException.getErrorCode());
+ assertEquals(errorMessage, workflowException.getErrorMessage());
+ assertEquals(processKey, workflowException.getProcessKey());
+ assertEquals("*", workflowException.getWorkStep());
+ String workStep = "one";
+ workflowException = new WorkflowException(processKey, errorCode, errorMessage, workStep);
+ assertEquals(workStep, workflowException.getWorkStep());
+ assertNotEquals(null, workflowException.toString());
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/AllottedResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/AllottedResourceTest.java
index cca28d411f..fcd502f982 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/AllottedResourceTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/AllottedResourceTest.java
@@ -1,66 +1,59 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
-
import java.io.IOException;
public class AllottedResourceTest {
- private AllottedResource ar = new AllottedResource();
-
- @Test
- public void testAllottedResource() {
- ar.setAllottedResourceType("allottedResourceType");
- ar.setAllottedResourceRole("allottedResourceRole");
- ar.setProvidingServiceModelName("providingServiceModelName");
- ar.setProvidingServiceModelInvariantUuid("providingServiceModelInvariantUuid");
- ar.setProvidingServiceModelUuid("providingServiceModelUuid");
- ar.setNfFunction("nfFunction");
- ar.setNfType("nfType");
- ar.setNfRole("nfRole");
- ar.setNfNamingCode("nfNamingCode");
- ar.setOrchestrationStatus("orchestrationStatus");
- assertEquals(ar.getAllottedResourceType(), "allottedResourceType");
- assertEquals(ar.getAllottedResourceRole(), "allottedResourceRole");
- assertEquals(ar.getProvidingServiceModelName(), "providingServiceModelName");
- assertEquals(ar.getProvidingServiceModelInvariantUuid(), "providingServiceModelInvariantUuid");
- assertEquals(ar.getProvidingServiceModelUuid(), "providingServiceModelUuid");
- assertEquals(ar.getNfFunction(), "nfFunction");
- assertEquals(ar.getNfType(), "nfType");
- assertEquals(ar.getNfRole(), "nfRole");
- assertEquals(ar.getNfNamingCode(), "nfNamingCode");
- assertEquals(ar.getOrchestrationStatus(), "orchestrationStatus");
-
- }
-
- @Test
- public void allottedResourceMapperTest() throws IOException {
- String jsonStr = "{\"allottedResourceType\": \"code123\", \"resourceInput\": \"sample\"}";
- ObjectMapper objectMapper = new ObjectMapper();
- AllottedResource vnfResource = objectMapper.readValue(jsonStr, AllottedResource.class);
-
- assertTrue(vnfResource != null);
- }
+ private AllottedResource ar = new AllottedResource();
+
+ @Test
+ public void testAllottedResource() {
+ ar.setAllottedResourceType("allottedResourceType");
+ ar.setAllottedResourceRole("allottedResourceRole");
+ ar.setProvidingServiceModelName("providingServiceModelName");
+ ar.setProvidingServiceModelInvariantUuid("providingServiceModelInvariantUuid");
+ ar.setProvidingServiceModelUuid("providingServiceModelUuid");
+ ar.setNfFunction("nfFunction");
+ ar.setNfType("nfType");
+ ar.setNfRole("nfRole");
+ ar.setNfNamingCode("nfNamingCode");
+ ar.setOrchestrationStatus("orchestrationStatus");
+ assertEquals(ar.getAllottedResourceType(), "allottedResourceType");
+ assertEquals(ar.getAllottedResourceRole(), "allottedResourceRole");
+ assertEquals(ar.getProvidingServiceModelName(), "providingServiceModelName");
+ assertEquals(ar.getProvidingServiceModelInvariantUuid(), "providingServiceModelInvariantUuid");
+ assertEquals(ar.getProvidingServiceModelUuid(), "providingServiceModelUuid");
+ assertEquals(ar.getNfFunction(), "nfFunction");
+ assertEquals(ar.getNfType(), "nfType");
+ assertEquals(ar.getNfRole(), "nfRole");
+ assertEquals(ar.getNfNamingCode(), "nfNamingCode");
+ assertEquals(ar.getOrchestrationStatus(), "orchestrationStatus");
+
+ }
+
+ @Test
+ public void allottedResourceMapperTest() throws IOException {
+ String jsonStr = "{\"allottedResourceType\": \"code123\", \"resourceInput\": \"sample\"}";
+ ObjectMapper objectMapper = new ObjectMapper();
+ AllottedResource vnfResource = objectMapper.readValue(jsonStr, AllottedResource.class);
+
+ assertTrue(vnfResource != null);
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CompareModelsResultTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CompareModelsResultTest.java
index af9c7a7fa6..4c371d3cff 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CompareModelsResultTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CompareModelsResultTest.java
@@ -1,83 +1,76 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Before;
import org.junit.Test;
public class CompareModelsResultTest {
-
- private CompareModelsResult modelsResult;
- private List<ResourceModelInfo> addedResourceList;
- private List<ResourceModelInfo> deletedResourceList;
- private ResourceModelInfo resourceModelInfo1;
- private ResourceModelInfo resourceModelInfo2;
- private List<String> requestInputs;
-
- @Before
- public void before() {
- resourceModelInfo1 = new ResourceModelInfo();
- resourceModelInfo1.setResourceCustomizationUuid("f1d563e8-e714-4393-8f99-cc480144a05e");
- resourceModelInfo1.setResourceInvariantUuid("e1d563e8-e714-4393-8f99-cc480144a05f");
- resourceModelInfo1.setResourceName("resourceName1");
- resourceModelInfo1.setResourceUuid("f1d563e8-e714-4393-8f99-cc480144a05g");
- resourceModelInfo2 = new ResourceModelInfo();
- resourceModelInfo2.setResourceCustomizationUuid("a1d563e8-e714-4393-8f99-cc480144a05d");
- resourceModelInfo2.setResourceInvariantUuid("b1d563e8-e714-4393-8f99-cc480144a05e");
- resourceModelInfo2.setResourceName("resourceName2");
- resourceModelInfo2.setResourceUuid("c1d563e8-e714-4393-8f99-cc480144a05f");
- }
-
- @Test
- public void testSetAddedResourceList() {
- addedResourceList = new ArrayList<ResourceModelInfo>();
- addedResourceList.add(resourceModelInfo1);
- addedResourceList.add(resourceModelInfo2);
- modelsResult = new CompareModelsResult();
- modelsResult.setAddedResourceList(addedResourceList);
- assertEquals(addedResourceList, modelsResult.getAddedResourceList());
- }
- @Test
- public void testSetDeletedResourceList() {
- deletedResourceList = new ArrayList<ResourceModelInfo>();
- deletedResourceList.add(resourceModelInfo1);
- deletedResourceList.add(resourceModelInfo2);
- modelsResult = new CompareModelsResult();
- modelsResult.setDeletedResourceList(deletedResourceList);
- assertEquals(deletedResourceList, modelsResult.getDeletedResourceList());
- }
+ private CompareModelsResult modelsResult;
+ private List<ResourceModelInfo> addedResourceList;
+ private List<ResourceModelInfo> deletedResourceList;
+ private ResourceModelInfo resourceModelInfo1;
+ private ResourceModelInfo resourceModelInfo2;
+ private List<String> requestInputs;
+
+ @Before
+ public void before() {
+ resourceModelInfo1 = new ResourceModelInfo();
+ resourceModelInfo1.setResourceCustomizationUuid("f1d563e8-e714-4393-8f99-cc480144a05e");
+ resourceModelInfo1.setResourceInvariantUuid("e1d563e8-e714-4393-8f99-cc480144a05f");
+ resourceModelInfo1.setResourceName("resourceName1");
+ resourceModelInfo1.setResourceUuid("f1d563e8-e714-4393-8f99-cc480144a05g");
+ resourceModelInfo2 = new ResourceModelInfo();
+ resourceModelInfo2.setResourceCustomizationUuid("a1d563e8-e714-4393-8f99-cc480144a05d");
+ resourceModelInfo2.setResourceInvariantUuid("b1d563e8-e714-4393-8f99-cc480144a05e");
+ resourceModelInfo2.setResourceName("resourceName2");
+ resourceModelInfo2.setResourceUuid("c1d563e8-e714-4393-8f99-cc480144a05f");
+ }
+
+ @Test
+ public void testSetAddedResourceList() {
+ addedResourceList = new ArrayList<ResourceModelInfo>();
+ addedResourceList.add(resourceModelInfo1);
+ addedResourceList.add(resourceModelInfo2);
+ modelsResult = new CompareModelsResult();
+ modelsResult.setAddedResourceList(addedResourceList);
+ assertEquals(addedResourceList, modelsResult.getAddedResourceList());
+ }
+
+ @Test
+ public void testSetDeletedResourceList() {
+ deletedResourceList = new ArrayList<ResourceModelInfo>();
+ deletedResourceList.add(resourceModelInfo1);
+ deletedResourceList.add(resourceModelInfo2);
+ modelsResult = new CompareModelsResult();
+ modelsResult.setDeletedResourceList(deletedResourceList);
+ assertEquals(deletedResourceList, modelsResult.getDeletedResourceList());
+ }
+
+ @Test
+ public void testSetRequestInputs() {
+ requestInputs = new ArrayList<String>();
+ requestInputs.add("requestInput1");
+ requestInputs.add("requestInput2");
+ modelsResult = new CompareModelsResult();
+ modelsResult.setRequestInputs(requestInputs);
+ assertEquals(requestInputs, modelsResult.getRequestInputs());
+ }
- @Test
- public void testSetRequestInputs() {
- requestInputs = new ArrayList<String>();
- requestInputs.add("requestInput1");
- requestInputs.add("requestInput2");
- modelsResult = new CompareModelsResult();
- modelsResult.setRequestInputs(requestInputs);
- assertEquals(requestInputs, modelsResult.getRequestInputs());
- }
-
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigResourceTest.java
index 13a30d26ee..1e1595f048 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigResourceTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigResourceTest.java
@@ -1,39 +1,34 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class ConfigResourceTest {
- private ConfigResource configresource = new ConfigResource();{
- configresource.resourceType = ResourceType.CONFIGURATION;
- }
+ private ConfigResource configresource = new ConfigResource();
+ {
+ configresource.resourceType = ResourceType.CONFIGURATION;
+ }
+
+ @Test
+ public void testConfigResource() {
+ configresource.setToscaNodeType("toscaNodeType");
+ assertEquals(configresource.getToscaNodeType(), "toscaNodeType");
+
- @Test
- public void testConfigResource() {
- configresource.setToscaNodeType("toscaNodeType");
- assertEquals(configresource.getToscaNodeType(), "toscaNodeType");
-
-
- }
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigurationTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigurationTest.java
index fe84a1b5a7..68839a7ad6 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigurationTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ConfigurationTest.java
@@ -1,47 +1,41 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class ConfigurationTest {
- private Configuration configuration = new Configuration();
+ private Configuration configuration = new Configuration();
- @Test
- public void testConfigurationTest() {
- configuration.setId("id");
- configuration.setName("name");
- configuration.setType("type");
- configuration.setOrchestrationStatus("orchestrationStatus");
- configuration.setTunnelBandwidth("tunnelBandwidth");
- configuration.setVendorAllowedMaxBandwidth("vendorAllowedMaxBandwidth");
- configuration.setResourceVersion("resourceVersion");
- assertEquals(configuration.getId(), "id");
- assertEquals(configuration.getName(), "name");
- assertEquals(configuration.getType(), "type");
- assertEquals(configuration.getOrchestrationStatus(), "orchestrationStatus");
- assertEquals(configuration.getTunnelBandwidth(), "tunnelBandwidth");
- assertEquals(configuration.getVendorAllowedMaxBandwidth(), "vendorAllowedMaxBandwidth");
- assertEquals(configuration.getResourceVersion(), "resourceVersion");
- }
+ @Test
+ public void testConfigurationTest() {
+ configuration.setId("id");
+ configuration.setName("name");
+ configuration.setType("type");
+ configuration.setOrchestrationStatus("orchestrationStatus");
+ configuration.setTunnelBandwidth("tunnelBandwidth");
+ configuration.setVendorAllowedMaxBandwidth("vendorAllowedMaxBandwidth");
+ configuration.setResourceVersion("resourceVersion");
+ assertEquals(configuration.getId(), "id");
+ assertEquals(configuration.getName(), "name");
+ assertEquals(configuration.getType(), "type");
+ assertEquals(configuration.getOrchestrationStatus(), "orchestrationStatus");
+ assertEquals(configuration.getTunnelBandwidth(), "tunnelBandwidth");
+ assertEquals(configuration.getVendorAllowedMaxBandwidth(), "vendorAllowedMaxBandwidth");
+ assertEquals(configuration.getResourceVersion(), "resourceVersion");
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CustomerTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CustomerTest.java
index 86eb717664..9640cfce07 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CustomerTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/CustomerTest.java
@@ -1,38 +1,32 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class CustomerTest {
- private Customer customer = new Customer();
+ private Customer customer = new Customer();
+
+ @Test
+ public void testCustomer() {
+ customer.setSubscriptionServiceType("subscriptionServiceType");
+ customer.setGlobalSubscriberId("globalSubscriberId");
+ assertEquals(customer.getSubscriptionServiceType(), "subscriptionServiceType");
+ assertEquals(customer.getGlobalSubscriberId(), "globalSubscriberId");
- @Test
- public void testCustomer() {
- customer.setSubscriptionServiceType("subscriptionServiceType");
- customer.setGlobalSubscriberId("globalSubscriberId");
- assertEquals(customer.getSubscriptionServiceType(), "subscriptionServiceType");
- assertEquals(customer.getGlobalSubscriberId(), "globalSubscriberId");
-
- }
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/DomainPojoTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/DomainPojoTest.java
index b4860c6323..ae1aff7275 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/DomainPojoTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/DomainPojoTest.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.core.domain;
import org.junit.Test;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterNonConcrete;
@@ -33,24 +32,21 @@ import com.openpojo.validation.test.impl.SetterTester;
public class DomainPojoTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
-
- @Test
- public void pojoStructure() {
- test("org.onap.so.bpmn.core.domain");
- }
-
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, new FilterNonConcrete());
- }
-
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.bpmn.core.domain");
+ }
+
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new SetterTester()).with(new GetterTester()).build();
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, new FilterNonConcrete());
+ }
+
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/HomingSolutionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/HomingSolutionTest.java
index 9750e03b4c..249307cbbc 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/HomingSolutionTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/HomingSolutionTest.java
@@ -1,58 +1,52 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class HomingSolutionTest {
-
- private HomingSolution homingsolution = new HomingSolution();
- InventoryType inventory = InventoryType.cloud;
- VnfResource vnfresource = new VnfResource();
- License license = new License();
- @Test
- public void testHomingSolution() {
- homingsolution.setInventoryType(inventory);
- homingsolution.setRehome(true);
- homingsolution.setServiceInstanceId("serviceInstanceId");
- homingsolution.setCloudOwner("cloudOwner");
- homingsolution.setCloudRegionId("cloudRegionId");
- homingsolution.setAicClli("aicClli");
- homingsolution.setAicVersion("aicVersion");
- homingsolution.setTenant("tenant");
- homingsolution.setVnf(vnfresource);
- homingsolution.setLicense(license);
- assertEquals(homingsolution.getInventoryType(), inventory);
- assertEquals(homingsolution.isRehome(), true);
- assertEquals(homingsolution.getServiceInstanceId(), "serviceInstanceId");
- assertEquals(homingsolution.getCloudOwner(), "cloudOwner");
- assertEquals(homingsolution.getCloudRegionId(), "cloudRegionId");
- assertEquals(homingsolution.getAicClli(), "aicClli");
- assertEquals(homingsolution.getAicVersion(), "aicVersion");
- assertEquals(homingsolution.getTenant(), "tenant");
- assertEquals(homingsolution.getVnf(), vnfresource);
- assertEquals(homingsolution.getLicense(), license);
-
- }
+ private HomingSolution homingsolution = new HomingSolution();
+ InventoryType inventory = InventoryType.cloud;
+ VnfResource vnfresource = new VnfResource();
+ License license = new License();
+
+ @Test
+ public void testHomingSolution() {
+ homingsolution.setInventoryType(inventory);
+ homingsolution.setRehome(true);
+ homingsolution.setServiceInstanceId("serviceInstanceId");
+ homingsolution.setCloudOwner("cloudOwner");
+ homingsolution.setCloudRegionId("cloudRegionId");
+ homingsolution.setAicClli("aicClli");
+ homingsolution.setAicVersion("aicVersion");
+ homingsolution.setTenant("tenant");
+ homingsolution.setVnf(vnfresource);
+ homingsolution.setLicense(license);
+ assertEquals(homingsolution.getInventoryType(), inventory);
+ assertEquals(homingsolution.isRehome(), true);
+ assertEquals(homingsolution.getServiceInstanceId(), "serviceInstanceId");
+ assertEquals(homingsolution.getCloudOwner(), "cloudOwner");
+ assertEquals(homingsolution.getCloudRegionId(), "cloudRegionId");
+ assertEquals(homingsolution.getAicClli(), "aicClli");
+ assertEquals(homingsolution.getAicVersion(), "aicVersion");
+ assertEquals(homingsolution.getTenant(), "tenant");
+ assertEquals(homingsolution.getVnf(), vnfresource);
+ assertEquals(homingsolution.getLicense(), license);
+
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/LicenseTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/LicenseTest.java
index f3a96bf4eb..bacaaf77c9 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/LicenseTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/LicenseTest.java
@@ -1,54 +1,47 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.assertEquals;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
-public class LicenseTest {
-
- private License license= new License();
- List<String> entitlementPoolList = new ArrayList<String>();
- private List<String> licenseKeyGroupList = new ArrayList<String>();
-
- Long serialVersionUID = 333L;
-
- @Test
- public void testLicense() {
- license.setEntitlementPoolList(entitlementPoolList);
- license.setLicenseKeyGroupList(licenseKeyGroupList);
- license.addLicenseKeyGroup("licenseKeyGroupUuid");
- assertEquals(license.getEntitlementPoolList(), entitlementPoolList);
- assertEquals(license.getLicenseKeyGroupList(), licenseKeyGroupList);
- assert(license.getEntitlementPoolListAsString()!= null);
- assert(license.getLicenseKeyGroupListAsString()!=null);
- license.addEntitlementPool("entitlementPoolUuid");
-
-
- }
-
+public class LicenseTest {
+
+ private License license = new License();
+ List<String> entitlementPoolList = new ArrayList<String>();
+ private List<String> licenseKeyGroupList = new ArrayList<String>();
+
+ Long serialVersionUID = 333L;
+
+ @Test
+ public void testLicense() {
+ license.setEntitlementPoolList(entitlementPoolList);
+ license.setLicenseKeyGroupList(licenseKeyGroupList);
+ license.addLicenseKeyGroup("licenseKeyGroupUuid");
+ assertEquals(license.getEntitlementPoolList(), entitlementPoolList);
+ assertEquals(license.getLicenseKeyGroupList(), licenseKeyGroupList);
+ assert (license.getEntitlementPoolListAsString() != null);
+ assert (license.getLicenseKeyGroupListAsString() != null);
+ license.addEntitlementPool("entitlementPoolUuid");
+
+
+ }
+
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModelInfoTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModelInfoTest.java
index 3d07f85c04..807338745f 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModelInfoTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModelInfoTest.java
@@ -1,47 +1,41 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class ModelInfoTest {
- private ModelInfo modelinfo = new ModelInfo();
+ private ModelInfo modelinfo = new ModelInfo();
- @Test
- public void testModelInfo() {
- modelinfo.setModelName("modelName");
- modelinfo.setModelUuid("modelUuid");
- modelinfo.setModelInvariantUuid("modelInvariantUuid");
- modelinfo.setModelVersion("modelVersion");
- modelinfo.setModelCustomizationUuid("modelCustomizationUuid");
- modelinfo.setModelInstanceName("modelInstanceName");
- modelinfo.setModelType("modelType");
- assertEquals(modelinfo.getModelName(), "modelName");
- assertEquals(modelinfo.getModelUuid(), "modelUuid");
- assertEquals(modelinfo.getModelInvariantUuid(), "modelInvariantUuid");
- assertEquals(modelinfo.getModelVersion(), "modelVersion");
- assertEquals(modelinfo.getModelCustomizationUuid(), "modelCustomizationUuid");
- assertEquals(modelinfo.getModelInstanceName(), "modelInstanceName");
- assertEquals(modelinfo.getModelType(), "modelType");
- }
+ @Test
+ public void testModelInfo() {
+ modelinfo.setModelName("modelName");
+ modelinfo.setModelUuid("modelUuid");
+ modelinfo.setModelInvariantUuid("modelInvariantUuid");
+ modelinfo.setModelVersion("modelVersion");
+ modelinfo.setModelCustomizationUuid("modelCustomizationUuid");
+ modelinfo.setModelInstanceName("modelInstanceName");
+ modelinfo.setModelType("modelType");
+ assertEquals(modelinfo.getModelName(), "modelName");
+ assertEquals(modelinfo.getModelUuid(), "modelUuid");
+ assertEquals(modelinfo.getModelInvariantUuid(), "modelInvariantUuid");
+ assertEquals(modelinfo.getModelVersion(), "modelVersion");
+ assertEquals(modelinfo.getModelCustomizationUuid(), "modelCustomizationUuid");
+ assertEquals(modelinfo.getModelInstanceName(), "modelInstanceName");
+ assertEquals(modelinfo.getModelType(), "modelType");
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModuleResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModuleResourceTest.java
index dcb62cfc40..6e915b2a60 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModuleResourceTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ModuleResourceTest.java
@@ -1,48 +1,42 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class ModuleResourceTest {
- private ModuleResource moduleresource = new ModuleResource();
+ private ModuleResource moduleresource = new ModuleResource();
+
+ @Test
+ public void testModuleResource() {
- @Test
- public void testModuleResource() {
-
- moduleresource.setVfModuleName("vfModuleName");
- moduleresource.setHeatStackId("heatStackId");
- moduleresource.setIsBase(true);
- moduleresource.setVfModuleLabel("vfModuleLabel");
- moduleresource.setInitialCount(0);
- moduleresource.setVfModuleType("vfModuleType");
- moduleresource.setHasVolumeGroup(true);
- assertEquals(moduleresource.getVfModuleName(), "vfModuleName");
- assertEquals(moduleresource.getHeatStackId(), "heatStackId");
- assertEquals(moduleresource.getIsBase(), true);
- assertEquals(moduleresource.getVfModuleLabel(), "vfModuleLabel");
- assertEquals(moduleresource.getInitialCount(), 0);
- assertEquals(moduleresource.getVfModuleType(), "vfModuleType");
- assertEquals(moduleresource.isHasVolumeGroup(), true);
- }
+ moduleresource.setVfModuleName("vfModuleName");
+ moduleresource.setHeatStackId("heatStackId");
+ moduleresource.setIsBase(true);
+ moduleresource.setVfModuleLabel("vfModuleLabel");
+ moduleresource.setInitialCount(0);
+ moduleresource.setVfModuleType("vfModuleType");
+ moduleresource.setHasVolumeGroup(true);
+ assertEquals(moduleresource.getVfModuleName(), "vfModuleName");
+ assertEquals(moduleresource.getHeatStackId(), "heatStackId");
+ assertEquals(moduleresource.getIsBase(), true);
+ assertEquals(moduleresource.getVfModuleLabel(), "vfModuleLabel");
+ assertEquals(moduleresource.getInitialCount(), 0);
+ assertEquals(moduleresource.getVfModuleType(), "vfModuleType");
+ assertEquals(moduleresource.isHasVolumeGroup(), true);
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/NetworkResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/NetworkResourceTest.java
index ee23ebd438..668d6dc1de 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/NetworkResourceTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/NetworkResourceTest.java
@@ -1,54 +1,47 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
-
import java.io.IOException;
public class NetworkResourceTest {
- private NetworkResource nr = new NetworkResource();
-
- @Test
- public void testNetworkResource() {
- nr.setNetworkType("networkType");
- nr.setNetworkRole("networkRole");
- nr.setNetworkTechnology("networkTechnology");
- nr.setNetworkScope("networkScope");
- assertEquals(nr.getNetworkType(), "networkType");
- assertEquals(nr.getNetworkRole(), "networkRole");
- assertEquals(nr.getNetworkTechnology(), "networkTechnology");
- assertEquals(nr.getNetworkScope(), "networkScope");
-
- }
-
- @Test
- public void networkResourceMapperTest() throws IOException {
- String jsonStr = "{\"networkScope\": \"code123\", \"resourceInput\": \"sample\"}";
- ObjectMapper objectMapper = new ObjectMapper();
- NetworkResource networkResource = objectMapper.readValue(jsonStr, NetworkResource.class);
-
- assertTrue(networkResource != null);
- }
+ private NetworkResource nr = new NetworkResource();
+
+ @Test
+ public void testNetworkResource() {
+ nr.setNetworkType("networkType");
+ nr.setNetworkRole("networkRole");
+ nr.setNetworkTechnology("networkTechnology");
+ nr.setNetworkScope("networkScope");
+ assertEquals(nr.getNetworkType(), "networkType");
+ assertEquals(nr.getNetworkRole(), "networkRole");
+ assertEquals(nr.getNetworkTechnology(), "networkTechnology");
+ assertEquals(nr.getNetworkScope(), "networkScope");
+
+ }
+
+ @Test
+ public void networkResourceMapperTest() throws IOException {
+ String jsonStr = "{\"networkScope\": \"code123\", \"resourceInput\": \"sample\"}";
+ ObjectMapper objectMapper = new ObjectMapper();
+ NetworkResource networkResource = objectMapper.readValue(jsonStr, NetworkResource.class);
+
+ assertTrue(networkResource != null);
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/OwningEntityTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/OwningEntityTest.java
index 396d866446..23a1d866a2 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/OwningEntityTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/OwningEntityTest.java
@@ -1,39 +1,33 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class OwningEntityTest {
- private OwningEntity oe = new OwningEntity();
+ private OwningEntity oe = new OwningEntity();
+
+ @Test
+ public void testOwingEntity() {
+ oe.setOwningEntityId("owningEntityId");
+ oe.setOwningEntityName("owningEntityName");
+ assertEquals(oe.getOwningEntityId(), "owningEntityId");
+ assertEquals(oe.getOwningEntityName(), "owningEntityName");
- @Test
- public void testOwingEntity() {
- oe.setOwningEntityId("owningEntityId");
- oe.setOwningEntityName("owningEntityName");
- assertEquals(oe.getOwningEntityId(), "owningEntityId");
- assertEquals(oe.getOwningEntityName(), "owningEntityName");
-
- }
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ProjectTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ProjectTest.java
index 9081f9dd14..47ce61b8fe 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ProjectTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ProjectTest.java
@@ -1,36 +1,30 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class ProjectTest {
-
- private Project project = new Project();
- @Test
- public void testProject() {
- project.setProjectName("projectName");
- assertEquals(project.getProjectName(), "projectName");
- }
+ private Project project = new Project();
+
+ @Test
+ public void testProject() {
+ project.setProjectName("projectName");
+ assertEquals(project.getProjectName(), "projectName");
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/RequestTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/RequestTest.java
index 0c552ce19e..a890289943 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/RequestTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/RequestTest.java
@@ -1,44 +1,38 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class RequestTest {
-
- private Request request = new Request();
- ModelInfo model = new ModelInfo();
- @Test
- public void testRequest() {
- request.setSdncRequestId("sdncRequestId");
- request.setRequestId("requestId");
- request.setModelInfo(model);
- request.setProductFamilyId("productFamilyId");
- assertEquals(request.getSdncRequestId(), "sdncRequestId");
- assertEquals(request.getRequestId(), "requestId");
- assertEquals(request.getModelInfo(), model);
- assertEquals(request.getProductFamilyId(), "productFamilyId");
-
- }
+ private Request request = new Request();
+ ModelInfo model = new ModelInfo();
+
+ @Test
+ public void testRequest() {
+ request.setSdncRequestId("sdncRequestId");
+ request.setRequestId("requestId");
+ request.setModelInfo(model);
+ request.setProductFamilyId("productFamilyId");
+ assertEquals(request.getSdncRequestId(), "sdncRequestId");
+ assertEquals(request.getRequestId(), "requestId");
+ assertEquals(request.getModelInfo(), model);
+ assertEquals(request.getProductFamilyId(), "productFamilyId");
+
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceDecompositionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceDecompositionTest.java
index 573ffab4aa..112139ce95 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceDecompositionTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceDecompositionTest.java
@@ -1,50 +1,44 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class ResourceDecompositionTest {
-
- private ResourceDecomposition rd = new ResourceDecomposition() {
- private static final long serialVersionUID = 1L;
- };
- ModelInfo model = new ModelInfo();
- ResourceInstance ri = new ResourceInstance();
-
-
- @Test
- public void testResourceDecomposition() {
- rd.setModelInfo(model);
- rd.setInstanceData(ri);
- rd.setResourceType("resourceType");
- rd.setResourceInstanceId("newInstanceId");
- rd.setResourceInstanceName("newInstanceName");
- assertEquals(rd.getResourceModel(), model);
- assertEquals(rd.getModelInfo(), model);
- assertEquals(rd.getInstanceData(), ri);
- assertEquals(rd.getResourceInstanceId(), "newInstanceId");
- assertEquals(rd.getResourceInstanceName(), "newInstanceName");
- }
+ private ResourceDecomposition rd = new ResourceDecomposition() {
+ private static final long serialVersionUID = 1L;
+ };
+ ModelInfo model = new ModelInfo();
+ ResourceInstance ri = new ResourceInstance();
+
+
+
+ @Test
+ public void testResourceDecomposition() {
+ rd.setModelInfo(model);
+ rd.setInstanceData(ri);
+ rd.setResourceType("resourceType");
+ rd.setResourceInstanceId("newInstanceId");
+ rd.setResourceInstanceName("newInstanceName");
+ assertEquals(rd.getResourceModel(), model);
+ assertEquals(rd.getModelInfo(), model);
+ assertEquals(rd.getInstanceData(), ri);
+ assertEquals(rd.getResourceInstanceId(), "newInstanceId");
+ assertEquals(rd.getResourceInstanceName(), "newInstanceName");
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceTest.java
index afdbcd9f98..271ed6b32e 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ResourceTest.java
@@ -1,68 +1,60 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class ResourceTest {
- private Resource resource = new Resource() {
- private static final long serialVersionUID = 1L;
-
-
- };
- ModelInfo model = new ModelInfo();
- ResourceInstance ri = new ResourceInstance();
- HomingSolution hs = new HomingSolution();
- ResourceType rt = ResourceType.VNF;
- public long concurrencyCounter = 1L;
- long initval = resource.getConcurrencyCounter();
+ private Resource resource = new Resource() {
+ private static final long serialVersionUID = 1L;
+
+
+ };
+ ModelInfo model = new ModelInfo();
+ ResourceInstance ri = new ResourceInstance();
+ HomingSolution hs = new HomingSolution();
+ ResourceType rt = ResourceType.VNF;
+ public long concurrencyCounter = 1L;
+ long initval = resource.getConcurrencyCounter();
+
+ @Test
+ public void testResource() {
+ resource.setResourceId("resourceId");
+ resource.setModelInfo(model);
+ resource.setResourceInstance(ri);
+ resource.setHomingSolution(hs);
+ resource.setCurrentHomingSolution(hs);
+ resource.setResourceType(rt);
+ resource.setToscaNodeType("toscaNodeType");
+ resource.setResourceInstanceId("newInstanceId");
+ resource.setResourceInstanceName("newInstanceName");
+ resource.incrementConcurrencyCounter();
+ assertEquals(resource.getResourceId(), "resourceId");
+ assertEquals(resource.getModelInfo(), model);
+ assertEquals(resource.getResourceInstance(), ri);
+ assertEquals(resource.getHomingSolution(), hs);
+ assertEquals(resource.getCurrentHomingSolution(), hs);
+ assertEquals(resource.getResourceType(), rt);
+ assertEquals(resource.getToscaNodeType(), "toscaNodeType");
+ assertEquals(resource.getResourceInstanceId(), "newInstanceId");
+ assertEquals(resource.getResourceInstanceName(), "newInstanceName");
+ assertEquals(resource.getConcurrencyCounter(), initval + 1);
+
+
- @Test
- public void testResource() {
- resource.setResourceId("resourceId");
- resource.setModelInfo(model);
- resource.setResourceInstance(ri);
- resource.setHomingSolution(hs);
- resource.setCurrentHomingSolution(hs);
- resource.setResourceType(rt);
- resource.setToscaNodeType("toscaNodeType");
- resource.setResourceInstanceId("newInstanceId");
- resource.setResourceInstanceName("newInstanceName");
- resource.incrementConcurrencyCounter();
- assertEquals(resource.getResourceId(), "resourceId");
- assertEquals(resource.getModelInfo(), model);
- assertEquals(resource.getResourceInstance(), ri);
- assertEquals(resource.getHomingSolution(), hs);
- assertEquals(resource.getCurrentHomingSolution(), hs);
- assertEquals(resource.getResourceType(), rt);
- assertEquals(resource.getToscaNodeType(), "toscaNodeType");
- assertEquals(resource.getResourceInstanceId(), "newInstanceId");
- assertEquals(resource.getResourceInstanceName(), "newInstanceName");
- assertEquals(resource.getConcurrencyCounter(), initval+1);
-
-
-
-
-
- }
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java
index 5d8d55152c..5db277628e 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java
@@ -1,22 +1,17 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
@@ -24,104 +19,109 @@ import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
-
import org.junit.Before;
import org.junit.Test;
-
import com.fasterxml.jackson.core.JsonProcessingException;
public class ServiceDecompositionTest {
- private static final String RESOURCE_PATH = "src/test/resources/json-examples/";
-
- VnfResource vnfResource;
- NetworkResource networkResource;
- AllottedResource allottedResource;
- ConfigResource configResource;
-
- @Before
- public void before() {
- vnfResource = new VnfResource();
- vnfResource.setResourceId("vnfResourceId");
- vnfResource.setModules(new ArrayList<>());
-
- networkResource = new NetworkResource();
- networkResource.setResourceId("networkResourceId");
-
- allottedResource = new AllottedResource();
- allottedResource.setResourceId("allottedResourceId");
-
- configResource = new ConfigResource();
- configResource.setResourceId("configResourceId");
- }
-
- @Test
- public void serviceDecompositionTest() throws JsonProcessingException, IOException {
- // covering methods not covered by openpojo test
- String catalogRestOutput = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceDecomposition.json")));
-
- ServiceDecomposition serviceDecomp = new ServiceDecomposition(catalogRestOutput);
- serviceDecomp.addVnfResource(vnfResource);
- serviceDecomp.addNetworkResource(networkResource);
- serviceDecomp.addAllottedResource(allottedResource);
- serviceDecomp.addConfigResource(configResource);
-
- assertThat(serviceDecomp.getServiceResource(vnfResource.getResourceId()), sameBeanAs(vnfResource));
- assertThat(serviceDecomp.getServiceResource(networkResource.getResourceId()), sameBeanAs(networkResource));
- assertThat(serviceDecomp.getServiceResource(allottedResource.getResourceId()), sameBeanAs(allottedResource));
- assertThat(serviceDecomp.getServiceResource(configResource.getResourceId()), sameBeanAs(configResource));
-
- VnfResource vnfResourceReplace = new VnfResource();
- vnfResourceReplace.setResourceId(vnfResource.getResourceId());
- vnfResourceReplace.setResourceInstanceName("vnfResourceReplaceInstanceName");
-
- assertTrue(serviceDecomp.replaceResource(vnfResourceReplace));
- assertTrue(serviceDecomp.getVnfResources().contains(vnfResourceReplace));
-
- assertTrue(serviceDecomp.deleteResource(vnfResourceReplace));
- assertFalse(serviceDecomp.deleteResource(vnfResourceReplace));
- assertFalse(serviceDecomp.deleteResource(new VnfResource()));
- }
-
- @Test
- public void serviceDecompositionJsonTest() throws IOException {
- String catalogRestOutput = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceDecomposition.json")));
- String expectedCatalogRestOutput = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceDecompositionExpected.json")));
- String vnfResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "VnfResource.json")));
- String networkResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "NetworkResource.json")));
- String allottedResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "AllottedResource.json")));
- String configResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ConfigResource.json")));
-
- ServiceDecomposition serviceDecomp = new ServiceDecomposition(catalogRestOutput, "serviceInstanceId");
- serviceDecomp.addResource(vnfResource);
- serviceDecomp.addResource(networkResource);
- serviceDecomp.addResource(allottedResource);
- serviceDecomp.addResource(configResource);
-
- System.out.println(serviceDecomp.toJsonString());
-
- assertThat(serviceDecomp.getServiceResource(vnfResource.getResourceId()), sameBeanAs(vnfResource));
- assertThat(serviceDecomp.getServiceResource(networkResource.getResourceId()), sameBeanAs(networkResource));
- assertThat(serviceDecomp.getServiceResource(allottedResource.getResourceId()), sameBeanAs(allottedResource));
- assertThat(serviceDecomp.getServiceResource(configResource.getResourceId()), sameBeanAs(configResource));
-
- serviceDecomp = new ServiceDecomposition(catalogRestOutput, "serviceInstanceId");
- serviceDecomp.addVnfResource(vnfResourceJson);
- serviceDecomp.addNetworkResource(networkResourceJson);
- serviceDecomp.addAllottedResource(allottedResourceJson);
- serviceDecomp.addConfigResource(configResourceJson);
-
- ServiceDecomposition expectedServiceDecomp = new ServiceDecomposition(expectedCatalogRestOutput, "serviceInstanceId");
-
- assertThat(serviceDecomp, sameBeanAs(expectedServiceDecomp));
- assertEquals(serviceDecomp.listToJson(Arrays.asList(networkResource)) + serviceDecomp.listToJson(Arrays.asList(vnfResource)) +
- serviceDecomp.listToJson(Arrays.asList(allottedResource)) + serviceDecomp.listToJson(Arrays.asList(configResource)),
- serviceDecomp.getServiceResourcesJsonString());
- }
+ private static final String RESOURCE_PATH = "src/test/resources/json-examples/";
+
+ VnfResource vnfResource;
+ NetworkResource networkResource;
+ AllottedResource allottedResource;
+ ConfigResource configResource;
+
+ @Before
+ public void before() {
+ vnfResource = new VnfResource();
+ vnfResource.setResourceId("vnfResourceId");
+ vnfResource.setModules(new ArrayList<>());
+
+ networkResource = new NetworkResource();
+ networkResource.setResourceId("networkResourceId");
+
+ allottedResource = new AllottedResource();
+ allottedResource.setResourceId("allottedResourceId");
+
+ configResource = new ConfigResource();
+ configResource.setResourceId("configResourceId");
+ }
+
+ @Test
+ public void serviceDecompositionTest() throws JsonProcessingException, IOException {
+ // covering methods not covered by openpojo test
+ String catalogRestOutput =
+ new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceDecomposition.json")));
+
+ ServiceDecomposition serviceDecomp = new ServiceDecomposition(catalogRestOutput);
+ serviceDecomp.addVnfResource(vnfResource);
+ serviceDecomp.addNetworkResource(networkResource);
+ serviceDecomp.addAllottedResource(allottedResource);
+ serviceDecomp.addConfigResource(configResource);
+
+ assertThat(serviceDecomp.getServiceResource(vnfResource.getResourceId()), sameBeanAs(vnfResource));
+ assertThat(serviceDecomp.getServiceResource(networkResource.getResourceId()), sameBeanAs(networkResource));
+ assertThat(serviceDecomp.getServiceResource(allottedResource.getResourceId()), sameBeanAs(allottedResource));
+ assertThat(serviceDecomp.getServiceResource(configResource.getResourceId()), sameBeanAs(configResource));
+
+ VnfResource vnfResourceReplace = new VnfResource();
+ vnfResourceReplace.setResourceId(vnfResource.getResourceId());
+ vnfResourceReplace.setResourceInstanceName("vnfResourceReplaceInstanceName");
+
+ assertTrue(serviceDecomp.replaceResource(vnfResourceReplace));
+ assertTrue(serviceDecomp.getVnfResources().contains(vnfResourceReplace));
+
+ assertTrue(serviceDecomp.deleteResource(vnfResourceReplace));
+ assertFalse(serviceDecomp.deleteResource(vnfResourceReplace));
+ assertFalse(serviceDecomp.deleteResource(new VnfResource()));
+ }
+
+ @Test
+ public void serviceDecompositionJsonTest() throws IOException {
+ String catalogRestOutput =
+ new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceDecomposition.json")));
+ String expectedCatalogRestOutput =
+ new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceDecompositionExpected.json")));
+ String vnfResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "VnfResource.json")));
+ String networkResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "NetworkResource.json")));
+ String allottedResourceJson =
+ new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "AllottedResource.json")));
+ String configResourceJson = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ConfigResource.json")));
+
+ ServiceDecomposition serviceDecomp = new ServiceDecomposition(catalogRestOutput, "serviceInstanceId");
+ serviceDecomp.addResource(vnfResource);
+ serviceDecomp.addResource(networkResource);
+ serviceDecomp.addResource(allottedResource);
+ serviceDecomp.addResource(configResource);
+
+ System.out.println(serviceDecomp.toJsonString());
+
+ assertThat(serviceDecomp.getServiceResource(vnfResource.getResourceId()), sameBeanAs(vnfResource));
+ assertThat(serviceDecomp.getServiceResource(networkResource.getResourceId()), sameBeanAs(networkResource));
+ assertThat(serviceDecomp.getServiceResource(allottedResource.getResourceId()), sameBeanAs(allottedResource));
+ assertThat(serviceDecomp.getServiceResource(configResource.getResourceId()), sameBeanAs(configResource));
+
+ serviceDecomp = new ServiceDecomposition(catalogRestOutput, "serviceInstanceId");
+ serviceDecomp.addVnfResource(vnfResourceJson);
+ serviceDecomp.addNetworkResource(networkResourceJson);
+ serviceDecomp.addAllottedResource(allottedResourceJson);
+ serviceDecomp.addConfigResource(configResourceJson);
+
+ ServiceDecomposition expectedServiceDecomp =
+ new ServiceDecomposition(expectedCatalogRestOutput, "serviceInstanceId");
+
+ assertThat(serviceDecomp, sameBeanAs(expectedServiceDecomp));
+ assertEquals(
+ serviceDecomp.listToJson(Arrays.asList(networkResource))
+ + serviceDecomp.listToJson(Arrays.asList(vnfResource))
+ + serviceDecomp.listToJson(Arrays.asList(allottedResource))
+ + serviceDecomp.listToJson(Arrays.asList(configResource)),
+ serviceDecomp.getServiceResourcesJsonString());
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceInstanceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceInstanceTest.java
index c04dc9d601..1fb51412f6 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceInstanceTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceInstanceTest.java
@@ -1,71 +1,64 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import java.io.IOException;
import java.util.Map;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
public class ServiceInstanceTest {
-
- private ServiceInstance si= new ServiceInstance();
- Map serviceParams;
- Configuration config= new Configuration();
- ModelInfo model= new ModelInfo();
- @Test
- public void testServiceInstance() {
- si.setServiceType("serviceType");
- si.setServiceId("serviceId");
- si.setServiceParams(serviceParams);
- si.setInstanceId("instanceId");
- si.setInstanceName("instanceName");
- si.setOrchestrationStatus("orchestrationStatus");
- si.setConfiguration(config);
- si.setModelInfo(model);
- si.setEnvironmentContext("environmentContext");
- si.setWorkloadContext("workloadContext");
- assertEquals(si.getServiceType(), "serviceType");
- assertEquals(si.getServiceId(), "serviceId");
- assertEquals(si.getServiceParams(), serviceParams);
- assertEquals(si.getInstanceId(), "instanceId");
- assertEquals(si.getInstanceName(), "instanceName");
- assertEquals(si.getOrchestrationStatus(), "orchestrationStatus");
- assertEquals(si.getConfiguration(), config);
- assertEquals(si.getModelInfo(), model);
- assertEquals(si.getEnvironmentContext(), "environmentContext");
- assertEquals(si.getWorkloadContext(), "workloadContext");
-
-
- }
+ private ServiceInstance si = new ServiceInstance();
+ Map serviceParams;
+ Configuration config = new Configuration();
+ ModelInfo model = new ModelInfo();
+
+ @Test
+ public void testServiceInstance() {
+ si.setServiceType("serviceType");
+ si.setServiceId("serviceId");
+ si.setServiceParams(serviceParams);
+ si.setInstanceId("instanceId");
+ si.setInstanceName("instanceName");
+ si.setOrchestrationStatus("orchestrationStatus");
+ si.setConfiguration(config);
+ si.setModelInfo(model);
+ si.setEnvironmentContext("environmentContext");
+ si.setWorkloadContext("workloadContext");
+ assertEquals(si.getServiceType(), "serviceType");
+ assertEquals(si.getServiceId(), "serviceId");
+ assertEquals(si.getServiceParams(), serviceParams);
+ assertEquals(si.getInstanceId(), "instanceId");
+ assertEquals(si.getInstanceName(), "instanceName");
+ assertEquals(si.getOrchestrationStatus(), "orchestrationStatus");
+ assertEquals(si.getConfiguration(), config);
+ assertEquals(si.getModelInfo(), model);
+ assertEquals(si.getEnvironmentContext(), "environmentContext");
+ assertEquals(si.getWorkloadContext(), "workloadContext");
+
+
+ }
- @Test
- public void serviceInstanceMapperTest() throws IOException {
- String jsonStr = "{\"workloadContext\": \"code123\", \"resourceOrder\": \"sample\"}";
- ObjectMapper objectMapper = new ObjectMapper();
- ServiceInstance serviceInstance = objectMapper.readValue(jsonStr, ServiceInstance.class);
- assertTrue(serviceInstance != null);
- }
+ @Test
+ public void serviceInstanceMapperTest() throws IOException {
+ String jsonStr = "{\"workloadContext\": \"code123\", \"resourceOrder\": \"sample\"}";
+ ObjectMapper objectMapper = new ObjectMapper();
+ ServiceInstance serviceInstance = objectMapper.readValue(jsonStr, ServiceInstance.class);
+ assertTrue(serviceInstance != null);
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/SubscriberTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/SubscriberTest.java
index b862c8704f..8f1b666d0b 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/SubscriberTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/SubscriberTest.java
@@ -1,41 +1,35 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class SubscriberTest {
- Subscriber subscriber= new Subscriber("globalId", "name", "commonSiteId");
+ Subscriber subscriber = new Subscriber("globalId", "name", "commonSiteId");
+
+ @Test
+ public void testSubscriber() {
+ subscriber.setGlobalId("globalId");
+ subscriber.setName("name");
+ subscriber.setCommonSiteId("commonSiteId");
+ assertEquals(subscriber.getGlobalId(), "globalId");
+ assertEquals(subscriber.getName(), "name");
+ assertEquals(subscriber.getCommonSiteId(), "commonSiteId");
+
- @Test
- public void testSubscriber() {
- subscriber.setGlobalId("globalId");
- subscriber.setName("name");
- subscriber.setCommonSiteId("commonSiteId");
- assertEquals(subscriber.getGlobalId(), "globalId");
- assertEquals(subscriber.getName(), "name");
- assertEquals(subscriber.getCommonSiteId(), "commonSiteId");
-
-
- }
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java
index 5271bb3c53..09bcfe8470 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java
@@ -1,100 +1,93 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.domain;
import static org.junit.Assert.*;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
public class VnfResourceTest {
- private final static String ALL_VF_MODULES_JSON =
- "{\"ArrayList\":[{\"resourceType\":\"MODULE\",\"resourceInstance\":{},\"homingSolution\":{\"license\":{},\"rehome\":false},\"vfModuleName\":\"vfModuleName\",\"vfModuleType\":\"vfModuleType\",\"heatStackId\":\"heatStackId\",\"hasVolumeGroup\":true,\"isBase\":true,\"vfModuleLabel\":\"vfModuleLabel\",\"initialCount\":0},{\"resourceType\":\"MODULE\",\"resourceInstance\":{},\"homingSolution\":{\"license\":{},\"rehome\":false},\"vfModuleName\":\"vfModuleName\",\"vfModuleType\":\"vfModuleType\",\"heatStackId\":\"heatStackId\",\"hasVolumeGroup\":true,\"isBase\":true,\"vfModuleLabel\":\"vfModuleLabel\",\"initialCount\":0}]}";
-
- private VnfResource vnf= new VnfResource();
- List<ModuleResource> moduleResources;
-
- @Test
- public void testVnfResource() {
- vnf.setModules(moduleResources);
- vnf.setVnfHostname("vnfHostname");
- vnf.setVnfType("vnfType");
- vnf.setNfFunction("nfFunction");
- vnf.setNfType("nfType");
- vnf.setNfRole("nfRole");
- vnf.setNfNamingCode("nfNamingCode");
- vnf.setMultiStageDesign("multiStageDesign");
- assertEquals(vnf.getVfModules(), moduleResources);
- assertEquals(vnf.getVnfHostname(), "vnfHostname");
- assertEquals(vnf.getVnfType(), "vnfType");
- assertEquals(vnf.getNfFunction(), "nfFunction");
- assertEquals(vnf.getNfType(), "nfType");
- assertEquals(vnf.getNfRole(), "nfRole");
- assertEquals(vnf.getNfNamingCode(), "nfNamingCode");
- assertEquals(vnf.getMultiStageDesign(), "multiStageDesign");
-
-
- }
-
- @Test
- public void vnfResourceMapperTest() throws IOException {
- String jsonStr = "{\"vnfHostname\": \"home\", \"resourceInput\": \"sample\"}";
- ObjectMapper objectMapper = new ObjectMapper();
- VnfResource vnfResource = objectMapper.readValue(jsonStr, VnfResource.class);
-
- assertTrue(vnfResource != null);
- }
-
- @Test
- public void testVfModules() {
-
- moduleResources = new ArrayList<>();
-
- ModuleResource moduleresource = new ModuleResource();
- moduleresource.setVfModuleName("vfModuleName");
- moduleresource.setHeatStackId("heatStackId");
- moduleresource.setIsBase(true);
- moduleresource.setVfModuleLabel("vfModuleLabel");
- moduleresource.setInitialCount(0);
- moduleresource.setVfModuleType("vfModuleType");
- moduleresource.setHasVolumeGroup(true);
-
- moduleResources.add(moduleresource);
-
- vnf.setModules(moduleResources);
- assertEquals(vnf.getVfModules(), moduleResources);
-
- List<ModuleResource> moduleResources = vnf.getAllVfModuleObjects();
- assertEquals(1, moduleResources.size());
-
- vnf.addVfModule(moduleresource);
- moduleResources = vnf.getAllVfModuleObjects();
- assertEquals(2, moduleResources.size());
-
- assertEquals(ALL_VF_MODULES_JSON, vnf.getAllVfModulesJson());
-
- }
+ private final static String ALL_VF_MODULES_JSON =
+ "{\"ArrayList\":[{\"resourceType\":\"MODULE\",\"resourceInstance\":{},\"homingSolution\":{\"license\":{},\"rehome\":false},\"vfModuleName\":\"vfModuleName\",\"vfModuleType\":\"vfModuleType\",\"heatStackId\":\"heatStackId\",\"hasVolumeGroup\":true,\"isBase\":true,\"vfModuleLabel\":\"vfModuleLabel\",\"initialCount\":0},{\"resourceType\":\"MODULE\",\"resourceInstance\":{},\"homingSolution\":{\"license\":{},\"rehome\":false},\"vfModuleName\":\"vfModuleName\",\"vfModuleType\":\"vfModuleType\",\"heatStackId\":\"heatStackId\",\"hasVolumeGroup\":true,\"isBase\":true,\"vfModuleLabel\":\"vfModuleLabel\",\"initialCount\":0}]}";
+
+ private VnfResource vnf = new VnfResource();
+ List<ModuleResource> moduleResources;
+
+ @Test
+ public void testVnfResource() {
+ vnf.setModules(moduleResources);
+ vnf.setVnfHostname("vnfHostname");
+ vnf.setVnfType("vnfType");
+ vnf.setNfFunction("nfFunction");
+ vnf.setNfType("nfType");
+ vnf.setNfRole("nfRole");
+ vnf.setNfNamingCode("nfNamingCode");
+ vnf.setMultiStageDesign("multiStageDesign");
+ assertEquals(vnf.getVfModules(), moduleResources);
+ assertEquals(vnf.getVnfHostname(), "vnfHostname");
+ assertEquals(vnf.getVnfType(), "vnfType");
+ assertEquals(vnf.getNfFunction(), "nfFunction");
+ assertEquals(vnf.getNfType(), "nfType");
+ assertEquals(vnf.getNfRole(), "nfRole");
+ assertEquals(vnf.getNfNamingCode(), "nfNamingCode");
+ assertEquals(vnf.getMultiStageDesign(), "multiStageDesign");
+
+
+ }
+
+ @Test
+ public void vnfResourceMapperTest() throws IOException {
+ String jsonStr = "{\"vnfHostname\": \"home\", \"resourceInput\": \"sample\"}";
+ ObjectMapper objectMapper = new ObjectMapper();
+ VnfResource vnfResource = objectMapper.readValue(jsonStr, VnfResource.class);
+
+ assertTrue(vnfResource != null);
+ }
+
+ @Test
+ public void testVfModules() {
+
+ moduleResources = new ArrayList<>();
+
+ ModuleResource moduleresource = new ModuleResource();
+ moduleresource.setVfModuleName("vfModuleName");
+ moduleresource.setHeatStackId("heatStackId");
+ moduleresource.setIsBase(true);
+ moduleresource.setVfModuleLabel("vfModuleLabel");
+ moduleresource.setInitialCount(0);
+ moduleresource.setVfModuleType("vfModuleType");
+ moduleresource.setHasVolumeGroup(true);
+
+ moduleResources.add(moduleresource);
+
+ vnf.setModules(moduleResources);
+ assertEquals(vnf.getVfModules(), moduleResources);
+
+ List<ModuleResource> moduleResources = vnf.getAllVfModuleObjects();
+ assertEquals(1, moduleResources.size());
+
+ vnf.addVfModule(moduleresource);
+ moduleResources = vnf.getAllVfModuleObjects();
+ assertEquals(2, moduleResources.size());
+
+ assertEquals(ALL_VF_MODULES_JSON, vnf.getAllVfModulesJson());
+
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/internal/VariableNameExtractorTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/internal/VariableNameExtractorTest.java
index 14b8c49655..e62ff09545 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/internal/VariableNameExtractorTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/internal/VariableNameExtractorTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.core.internal;
+
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.contains;
-
import java.util.Optional;
import org.junit.Test;
@@ -86,4 +86,4 @@ public class VariableNameExtractorTest {
// then
assertFalse(extracted.isPresent());
}
-} \ No newline at end of file
+}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/DecomposeJsonUtilTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/DecomposeJsonUtilTest.java
index c1f7cce30b..3a8948c00d 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/DecomposeJsonUtilTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/DecomposeJsonUtilTest.java
@@ -1,27 +1,21 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.json;
import static org.junit.Assert.assertEquals;
-
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -34,137 +28,140 @@ import org.onap.so.bpmn.core.domain.VnfResource;
public class DecomposeJsonUtilTest {
- private VnfResource vnfResource;
- private NetworkResource networkResource;
- private AllottedResource allottedResource;
- private ConfigResource configResource;
- private ServiceDecomposition serviceDecomposition;
-
- private String serviceInstanceId = "serviceInstanceId";
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Before
- public void before() throws Exception {
-
- }
-
- @Test
- public void testJsonToServiceDecomposition_twoParams() throws JsonDecomposingException {
- serviceDecomposition = createServiceDecompositionData();
- ServiceDecomposition serviceDecompositionObj = DecomposeJsonUtil.jsonToServiceDecomposition(serviceDecomposition.toString(), "serviceInstanceId");
- assertEquals(serviceInstanceId, serviceDecompositionObj.getServiceInstance().getInstanceId());
- }
-
- @Test
- public void testJsonToServiceDecomposition() throws JsonDecomposingException {
- serviceDecomposition = createServiceDecompositionData();
- ServiceDecomposition serviceDecompositionObj = DecomposeJsonUtil.jsonToServiceDecomposition(serviceDecomposition.toString());
- assertEquals(serviceDecomposition.getServiceType(), serviceDecompositionObj.getServiceType());
- }
-
- @Test
- public void testJsonToServiceDecomposition_JsonDecomposingException() throws JsonDecomposingException {
- expectedException.expect(JsonDecomposingException.class);
- vnfResource = createVnfResourceData(); // wrong object
- ServiceDecomposition serviceDecompositionObj = DecomposeJsonUtil.jsonToServiceDecomposition(vnfResource.toString());
- }
-
- @Test
- public void testJsonToVnfResource() throws JsonDecomposingException {
- vnfResource = createVnfResourceData();
- VnfResource vnfResourceObj = DecomposeJsonUtil.jsonToVnfResource(vnfResource.toString());
- assertEquals(vnfResource.getResourceId(), vnfResourceObj.getResourceId());
- }
-
- @Test
- public void testJsonToVnfResource_JsonDecomposingException() throws JsonDecomposingException {
- expectedException.expect(JsonDecomposingException.class);
- networkResource = createNetworkResourceData(); // wrong object
- VnfResource vnfResourceObj = DecomposeJsonUtil.jsonToVnfResource(networkResource.toString());
- }
-
- @Test
- public void testJsonToNetworkResource() throws JsonDecomposingException {
- networkResource = createNetworkResourceData();
- NetworkResource networkResourceObj = DecomposeJsonUtil.jsonToNetworkResource(networkResource.toString());
- assertEquals(networkResource.getResourceId(), networkResourceObj.getResourceId());
- }
-
- @Test
- public void testJsonToNetworkResource_JsonDecomposingException() throws JsonDecomposingException {
- expectedException.expect(JsonDecomposingException.class);
- vnfResource = createVnfResourceData(); // wrong object
- NetworkResource networkResourceObj = DecomposeJsonUtil.jsonToNetworkResource(vnfResource.toString());
- }
-
- @Test
- public void testJsonToAllottedResource() throws JsonDecomposingException {
- allottedResource = createAllottedResourceData();
- AllottedResource allottedResourceObj = DecomposeJsonUtil.jsonToAllottedResource(allottedResource.toString());
- assertEquals(allottedResource.getResourceId(), allottedResourceObj.getResourceId());
- }
-
- @Test
- public void testJsonToAllottedResource_JsonDecomposingException() throws JsonDecomposingException {
- expectedException.expect(JsonDecomposingException.class);
- configResource = createConfigResourceData(); // wrong object
- AllottedResource allottedResourceObj = DecomposeJsonUtil.jsonToAllottedResource(configResource.toString());
- }
-
- @Test
- public void testJsonToConfigResource() throws JsonDecomposingException {
- configResource = createConfigResourceData();
- ConfigResource configResourceObj = DecomposeJsonUtil.jsonToConfigResource(configResource.toString());
- assertEquals(configResource.getResourceId(), configResourceObj.getResourceId());
- }
-
- @Test
- public void testJsonToConfigResource_JsonDecomposingException() throws JsonDecomposingException {
- expectedException.expect(JsonDecomposingException.class);
- allottedResource = createAllottedResourceData(); // wrong object
- ConfigResource configResourceObj = DecomposeJsonUtil.jsonToConfigResource(allottedResource.toString());
- }
-
- // data creation section
- private VnfResource createVnfResourceData() {
- vnfResource = new VnfResource();
- vnfResource.setResourceId("resourceId");
- vnfResource.setNfFunction("nfFunction");
- vnfResource.setNfNamingCode("nfNamingCode");
- vnfResource.setNfRole("nfRole");
- return vnfResource;
- }
-
- private NetworkResource createNetworkResourceData() {
- networkResource = new NetworkResource();
- networkResource.setNetworkRole("networkRole");
- networkResource.setResourceId("resourceId");
- return networkResource;
- }
-
- private AllottedResource createAllottedResourceData() {
- allottedResource = new AllottedResource();
- allottedResource.setResourceId("resourceId");
- allottedResource.setNfFunction("nfFunction");
- allottedResource.setNfNamingCode("nfNamingCode");
- allottedResource.setNfRole("nfRole");
- return allottedResource;
- }
-
- private ConfigResource createConfigResourceData() {
- configResource = new ConfigResource();
- configResource.setResourceId("resourceId");
- configResource.setToscaNodeType("toscaNodeType");
- return configResource;
- }
-
- private ServiceDecomposition createServiceDecompositionData() {
- serviceDecomposition = new ServiceDecomposition();
- serviceDecomposition.setSdncVersion("sdncVersion");
- serviceDecomposition.setServiceRole("serviceRole");
- serviceDecomposition.setServiceType("serviceType");
- return serviceDecomposition;
- }
+ private VnfResource vnfResource;
+ private NetworkResource networkResource;
+ private AllottedResource allottedResource;
+ private ConfigResource configResource;
+ private ServiceDecomposition serviceDecomposition;
+
+ private String serviceInstanceId = "serviceInstanceId";
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Before
+ public void before() throws Exception {
+
+ }
+
+ @Test
+ public void testJsonToServiceDecomposition_twoParams() throws JsonDecomposingException {
+ serviceDecomposition = createServiceDecompositionData();
+ ServiceDecomposition serviceDecompositionObj =
+ DecomposeJsonUtil.jsonToServiceDecomposition(serviceDecomposition.toString(), "serviceInstanceId");
+ assertEquals(serviceInstanceId, serviceDecompositionObj.getServiceInstance().getInstanceId());
+ }
+
+ @Test
+ public void testJsonToServiceDecomposition() throws JsonDecomposingException {
+ serviceDecomposition = createServiceDecompositionData();
+ ServiceDecomposition serviceDecompositionObj =
+ DecomposeJsonUtil.jsonToServiceDecomposition(serviceDecomposition.toString());
+ assertEquals(serviceDecomposition.getServiceType(), serviceDecompositionObj.getServiceType());
+ }
+
+ @Test
+ public void testJsonToServiceDecomposition_JsonDecomposingException() throws JsonDecomposingException {
+ expectedException.expect(JsonDecomposingException.class);
+ vnfResource = createVnfResourceData(); // wrong object
+ ServiceDecomposition serviceDecompositionObj =
+ DecomposeJsonUtil.jsonToServiceDecomposition(vnfResource.toString());
+ }
+
+ @Test
+ public void testJsonToVnfResource() throws JsonDecomposingException {
+ vnfResource = createVnfResourceData();
+ VnfResource vnfResourceObj = DecomposeJsonUtil.jsonToVnfResource(vnfResource.toString());
+ assertEquals(vnfResource.getResourceId(), vnfResourceObj.getResourceId());
+ }
+
+ @Test
+ public void testJsonToVnfResource_JsonDecomposingException() throws JsonDecomposingException {
+ expectedException.expect(JsonDecomposingException.class);
+ networkResource = createNetworkResourceData(); // wrong object
+ VnfResource vnfResourceObj = DecomposeJsonUtil.jsonToVnfResource(networkResource.toString());
+ }
+
+ @Test
+ public void testJsonToNetworkResource() throws JsonDecomposingException {
+ networkResource = createNetworkResourceData();
+ NetworkResource networkResourceObj = DecomposeJsonUtil.jsonToNetworkResource(networkResource.toString());
+ assertEquals(networkResource.getResourceId(), networkResourceObj.getResourceId());
+ }
+
+ @Test
+ public void testJsonToNetworkResource_JsonDecomposingException() throws JsonDecomposingException {
+ expectedException.expect(JsonDecomposingException.class);
+ vnfResource = createVnfResourceData(); // wrong object
+ NetworkResource networkResourceObj = DecomposeJsonUtil.jsonToNetworkResource(vnfResource.toString());
+ }
+
+ @Test
+ public void testJsonToAllottedResource() throws JsonDecomposingException {
+ allottedResource = createAllottedResourceData();
+ AllottedResource allottedResourceObj = DecomposeJsonUtil.jsonToAllottedResource(allottedResource.toString());
+ assertEquals(allottedResource.getResourceId(), allottedResourceObj.getResourceId());
+ }
+
+ @Test
+ public void testJsonToAllottedResource_JsonDecomposingException() throws JsonDecomposingException {
+ expectedException.expect(JsonDecomposingException.class);
+ configResource = createConfigResourceData(); // wrong object
+ AllottedResource allottedResourceObj = DecomposeJsonUtil.jsonToAllottedResource(configResource.toString());
+ }
+
+ @Test
+ public void testJsonToConfigResource() throws JsonDecomposingException {
+ configResource = createConfigResourceData();
+ ConfigResource configResourceObj = DecomposeJsonUtil.jsonToConfigResource(configResource.toString());
+ assertEquals(configResource.getResourceId(), configResourceObj.getResourceId());
+ }
+
+ @Test
+ public void testJsonToConfigResource_JsonDecomposingException() throws JsonDecomposingException {
+ expectedException.expect(JsonDecomposingException.class);
+ allottedResource = createAllottedResourceData(); // wrong object
+ ConfigResource configResourceObj = DecomposeJsonUtil.jsonToConfigResource(allottedResource.toString());
+ }
+
+ // data creation section
+ private VnfResource createVnfResourceData() {
+ vnfResource = new VnfResource();
+ vnfResource.setResourceId("resourceId");
+ vnfResource.setNfFunction("nfFunction");
+ vnfResource.setNfNamingCode("nfNamingCode");
+ vnfResource.setNfRole("nfRole");
+ return vnfResource;
+ }
+
+ private NetworkResource createNetworkResourceData() {
+ networkResource = new NetworkResource();
+ networkResource.setNetworkRole("networkRole");
+ networkResource.setResourceId("resourceId");
+ return networkResource;
+ }
+
+ private AllottedResource createAllottedResourceData() {
+ allottedResource = new AllottedResource();
+ allottedResource.setResourceId("resourceId");
+ allottedResource.setNfFunction("nfFunction");
+ allottedResource.setNfNamingCode("nfNamingCode");
+ allottedResource.setNfRole("nfRole");
+ return allottedResource;
+ }
+
+ private ConfigResource createConfigResourceData() {
+ configResource = new ConfigResource();
+ configResource.setResourceId("resourceId");
+ configResource.setToscaNodeType("toscaNodeType");
+ return configResource;
+ }
+
+ private ServiceDecomposition createServiceDecompositionData() {
+ serviceDecomposition = new ServiceDecomposition();
+ serviceDecomposition.setSdncVersion("sdncVersion");
+ serviceDecomposition.setServiceRole("serviceRole");
+ serviceDecomposition.setServiceType("serviceType");
+ return serviceDecomposition;
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonDecomposingExceptionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonDecomposingExceptionTest.java
index 6c8b7326e2..a9df2d9ea6 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonDecomposingExceptionTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonDecomposingExceptionTest.java
@@ -1,22 +1,17 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.json;
@@ -25,14 +20,14 @@ import org.junit.Test;
public class JsonDecomposingExceptionTest {
- private JsonDecomposingException jsonDecomposingException;
-
- @Test
- public void test() {
- String expectedMessage = "java.lang.Throwable: anyCause";
- String message = "java.lang.Throwable: anyCause";
- Throwable cause = new Throwable("anyCause");
- jsonDecomposingException = new JsonDecomposingException(message, cause);
- assertEquals(expectedMessage, jsonDecomposingException.getMessage());
- }
+ private JsonDecomposingException jsonDecomposingException;
+
+ @Test
+ public void test() {
+ String expectedMessage = "java.lang.Throwable: anyCause";
+ String message = "java.lang.Throwable: anyCause";
+ Throwable cause = new Throwable("anyCause");
+ jsonDecomposingException = new JsonDecomposingException(message, cause);
+ assertEquals(expectedMessage, jsonDecomposingException.getMessage());
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtils2Test.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtils2Test.java
index 667027f8de..1a2ceb5b39 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtils2Test.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtils2Test.java
@@ -22,12 +22,10 @@ package org.onap.so.bpmn.core.json;
import static org.junit.Assert.*;
-
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
-
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.BeforeClass;
@@ -46,102 +44,78 @@ import org.xmlunit.diff.ElementSelectors;
public class JsonUtils2Test {
private static final String EOL = "\n";
- private static final String XML_REQ =
- "<vnf-request xmlns=\"http://org.onap/so/infra/vnf-request/v1\">" + EOL +
- " <request-info>" + EOL +
- " <request-id>DEV-VF-0021</request-id>" + EOL +
- " <action>CREATE_VF_MODULE</action>" + EOL +
- " <source>PORTAL</source>" + EOL +
- " </request-info>" + EOL +
- " <vnf-inputs>" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL +
- " <vnf-type>asc_heat-int</vnf-type>" + EOL +
- " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL +
- " <vf-module-model-name>STMTN5MMSC21-MMSC::model-1-0</vf-module-model-name>" + EOL +
- " <is-base-module>true</is-base-module>" + EOL +
- " <persona-model-id>00000000-0000-0000-0000-000000000000</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <vnf-persona-model-id>999999999-0000-0000-0000-000000000000</vnf-persona-model-id>" + EOL +
- " <vnf-persona-model-version>1.5</vnf-persona-model-version>" + EOL +
- " <service-id>00000000-0000-0000-0000-000000000000</service-id>" + EOL +
- " <service-type>SDN-ETHERNET-INTERNET</service-type>" + EOL +
- " <tenant-id>fba1bd1e195a404cacb9ce17a9b2b421</tenant-id>" + EOL +
- " <orchestration-status>pending-delete</orchestration-status>" + EOL +
- " <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region>" + EOL +
- " <asdc-service-model-version>1</asdc-service-model-version>" + EOL +
- " </vnf-inputs>" + EOL +
- " <vnf-params xmlns:tns=\"http://org.onap/so/infra/vnf-request/v1\">" + EOL +
- " <param name=\"network\">network1111</param>" + EOL +
- " <param name=\"server\">server1111</param>" + EOL +
- " </vnf-params> " + EOL +
- "</vnf-request>" + EOL;
-
- private static final String XML_REQ_NO_ATTRS =
- "<vnf-request xmlns=\"http://org.onap/so/infra/vnf-request/v1\">" + EOL +
- " <request-info>" + EOL +
- " <action>DELETE_VF_MODULE</action>" + EOL +
- " <source>PORTAL</source>" + EOL +
- " </request-info>" + EOL +
- " <vnf-inputs>" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL +
- " <vnf-type>asc_heat-int</vnf-type>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL +
- " <service-id>00000000-0000-0000-0000-000000000000</service-id>" + EOL +
- " <service-type>SDN-ETHERNET-INTERNET</service-type>" + EOL +
- " <tenant-id>fba1bd1e195a404cacb9ce17a9b2b421</tenant-id>" + EOL +
- " <orchestration-status>pending-delete</orchestration-status>" + EOL +
- " <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region>" + EOL +
- " </vnf-inputs>" + EOL +
- " <vnf-params xmlns:tns=\"http://org.onap/so/infra/vnf-request/v1\"/>" + EOL +
- "</vnf-request>" + EOL;
+ private static final String XML_REQ = "<vnf-request xmlns=\"http://org.onap/so/infra/vnf-request/v1\">" + EOL
+ + " <request-info>" + EOL + " <request-id>DEV-VF-0021</request-id>" + EOL
+ + " <action>CREATE_VF_MODULE</action>" + EOL + " <source>PORTAL</source>" + EOL + " </request-info>"
+ + EOL + " <vnf-inputs>" + EOL + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + " <vnf-type>asc_heat-int</vnf-type>" + EOL
+ + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <vf-module-model-name>STMTN5MMSC21-MMSC::model-1-0</vf-module-model-name>" + EOL
+ + " <is-base-module>true</is-base-module>" + EOL
+ + " <persona-model-id>00000000-0000-0000-0000-000000000000</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <vnf-persona-model-id>999999999-0000-0000-0000-000000000000</vnf-persona-model-id>" + EOL
+ + " <vnf-persona-model-version>1.5</vnf-persona-model-version>" + EOL
+ + " <service-id>00000000-0000-0000-0000-000000000000</service-id>" + EOL
+ + " <service-type>SDN-ETHERNET-INTERNET</service-type>" + EOL
+ + " <tenant-id>fba1bd1e195a404cacb9ce17a9b2b421</tenant-id>" + EOL
+ + " <orchestration-status>pending-delete</orchestration-status>" + EOL
+ + " <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region>" + EOL
+ + " <asdc-service-model-version>1</asdc-service-model-version>" + EOL + " </vnf-inputs>" + EOL
+ + " <vnf-params xmlns:tns=\"http://org.onap/so/infra/vnf-request/v1\">" + EOL
+ + " <param name=\"network\">network1111</param>" + EOL + " <param name=\"server\">server1111</param>"
+ + EOL + " </vnf-params> " + EOL + "</vnf-request>" + EOL;
+
+ private static final String XML_REQ_NO_ATTRS = "<vnf-request xmlns=\"http://org.onap/so/infra/vnf-request/v1\">"
+ + EOL + " <request-info>" + EOL + " <action>DELETE_VF_MODULE</action>" + EOL
+ + " <source>PORTAL</source>" + EOL + " </request-info>" + EOL + " <vnf-inputs>" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + " <vnf-type>asc_heat-int</vnf-type>" + EOL
+ + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <service-id>00000000-0000-0000-0000-000000000000</service-id>" + EOL
+ + " <service-type>SDN-ETHERNET-INTERNET</service-type>" + EOL
+ + " <tenant-id>fba1bd1e195a404cacb9ce17a9b2b421</tenant-id>" + EOL
+ + " <orchestration-status>pending-delete</orchestration-status>" + EOL
+ + " <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region>" + EOL + " </vnf-inputs>" + EOL
+ + " <vnf-params xmlns:tns=\"http://org.onap/so/infra/vnf-request/v1\"/>" + EOL + "</vnf-request>" + EOL;
private static final String XML_ARRAY_REQ =
- "<ucpeInfo>" + EOL +
- " <outOfBandManagementModem>BROADBAND</outOfBandManagementModem>" + EOL +
- " <internetTopology>IVLAN</internetTopology>" + EOL +
- " <ucpeAliasHostName>SHELLUCPE31</ucpeAliasHostName>" + EOL +
- " <wanList>" + EOL +
- " <wanInfo>" + EOL +
- " <wanType>AVPN</wanType>" + EOL +
- " <interfaceType>1000BASE-T</interfaceType>" + EOL +
- " <transportProviderName>ATT</transportProviderName>" + EOL +
- " <circuitId>BT/SLIR/70911</circuitId>" + EOL +
- " <dualMode>Active</dualMode>" + EOL +
- " <wanPortNumber>WAN1</wanPortNumber>" + EOL +
- " <transportManagementOption>ATT</transportManagementOption>" + EOL +
- " <transportVendorTotalBandwidth>100</transportVendorTotalBandwidth>" + EOL +
- " <mediaType>ELECTRICAL</mediaType>" + EOL +
- " </wanInfo>" + EOL +
- " <wanInfo>" + EOL +
- " <wanType>AVPN</wanType>" + EOL +
- " <interfaceType>10/100/1000BASE-T</interfaceType>" + EOL +
- " <transportProviderName>ATT</transportProviderName>" + EOL +
- " <circuitId>AS/KRFN/34611</circuitId>" + EOL +
- " <dualMode>Active</dualMode>" + EOL +
- " <wanPortNumber>WAN2</wanPortNumber>" + EOL +
- " <transportManagementOption>ATT</transportManagementOption>" + EOL +
- " <transportVendorTotalBandwidth>10000</transportVendorTotalBandwidth>" + EOL +
- " <mediaType>MMF</mediaType>" + EOL +
- " </wanInfo>" + EOL +
- " </wanList>" + EOL +
- " <ucpeActivationCode>ASD-987-M31</ucpeActivationCode>" + EOL +
- " <ucpeHostName>USOSTCDALTX0101UJZZ31</ucpeHostName>" + EOL +
- " <ucpePartNumber>FG-VM00*</ucpePartNumber>" + EOL +
- "</ucpeInfo>";
+ "<ucpeInfo>" + EOL + " <outOfBandManagementModem>BROADBAND</outOfBandManagementModem>" + EOL
+ + " <internetTopology>IVLAN</internetTopology>" + EOL
+ + " <ucpeAliasHostName>SHELLUCPE31</ucpeAliasHostName>" + EOL + " <wanList>" + EOL
+ + " <wanInfo>" + EOL + " <wanType>AVPN</wanType>" + EOL
+ + " <interfaceType>1000BASE-T</interfaceType>" + EOL
+ + " <transportProviderName>ATT</transportProviderName>" + EOL
+ + " <circuitId>BT/SLIR/70911</circuitId>" + EOL
+ + " <dualMode>Active</dualMode>" + EOL
+ + " <wanPortNumber>WAN1</wanPortNumber>" + EOL
+ + " <transportManagementOption>ATT</transportManagementOption>" + EOL
+ + " <transportVendorTotalBandwidth>100</transportVendorTotalBandwidth>" + EOL
+ + " <mediaType>ELECTRICAL</mediaType>" + EOL + " </wanInfo>" + EOL
+ + " <wanInfo>" + EOL + " <wanType>AVPN</wanType>" + EOL
+ + " <interfaceType>10/100/1000BASE-T</interfaceType>" + EOL
+ + " <transportProviderName>ATT</transportProviderName>" + EOL
+ + " <circuitId>AS/KRFN/34611</circuitId>" + EOL
+ + " <dualMode>Active</dualMode>" + EOL
+ + " <wanPortNumber>WAN2</wanPortNumber>" + EOL
+ + " <transportManagementOption>ATT</transportManagementOption>" + EOL
+ + " <transportVendorTotalBandwidth>10000</transportVendorTotalBandwidth>" + EOL
+ + " <mediaType>MMF</mediaType>" + EOL + " </wanInfo>" + EOL
+ + " </wanList>" + EOL + " <ucpeActivationCode>ASD-987-M31</ucpeActivationCode>" + EOL
+ + " <ucpeHostName>USOSTCDALTX0101UJZZ31</ucpeHostName>" + EOL
+ + " <ucpePartNumber>FG-VM00*</ucpePartNumber>" + EOL + "</ucpeInfo>";
// JSON request w/ embedded XML will be read from a file
private static String jsonReq;
private static String jsonReqArray;
-
+
@BeforeClass
public static void initialize() throws Exception {
jsonReq = readFileToString("src/test/resources/request.json");
jsonReqArray = readFileToString("src/test/resources/requestArray.json");
- }
-
+ }
+
private static String readFileToString(String path) throws IOException {
File file = new File(path);
return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
@@ -149,16 +123,16 @@ public class JsonUtils2Test {
@Test
public void shouldConvertXmlToJsonAndBackToSameXml() throws Exception {
- // Note: the current version of the JsonUtils.json2xml() method
- // does not support converting the JSONObject representation
- // of XML attributes (JSONArray) back to XML. So this test will
- // only succeed if the original XML does not contain attributes
-
+ // Note: the current version of the JsonUtils.json2xml() method
+ // does not support converting the JSONObject representation
+ // of XML attributes (JSONArray) back to XML. So this test will
+ // only succeed if the original XML does not contain attributes
+
// given
String xmlIn = XmlTool.removeNamespaces(XML_REQ_NO_ATTRS);
// when
String json = JsonUtils.xml2json(XML_REQ_NO_ATTRS);
- String xmlOut = JsonUtils.json2xml(json);
+ String xmlOut = JsonUtils.json2xml(json);
// then
Diff diffXml = DiffBuilder.compare(xmlIn).withTest(xmlOut).ignoreWhitespace()
.withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)).checkForSimilar().build();
@@ -214,7 +188,7 @@ public class JsonUtils2Test {
assertNull(JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "badParam"));
assertNull(JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "name", 2));
}
-
+
@Test
public void shouldAddJsonValue() throws Exception {
// given
@@ -265,11 +239,11 @@ public class JsonUtils2Test {
// then
String extractedValue = JsonUtils.getJsonValue(jsonUpd, key);
assertNull(extractedValue);
- JSONObject jsonObj = new JSONObject(json);
- Integer intValue = JsonUtils.getJsonIntValueForKey(jsonObj, "persona-model-version");
- Assert.assertTrue(intValue == 1);
- Boolean boolValue = JsonUtils.getJsonBooleanValueForKey(jsonObj, "is-base-module");
- Assert.assertTrue(boolValue);
+ JSONObject jsonObj = new JSONObject(json);
+ Integer intValue = JsonUtils.getJsonIntValueForKey(jsonObj, "persona-model-version");
+ Assert.assertTrue(intValue == 1);
+ Boolean boolValue = JsonUtils.getJsonBooleanValueForKey(jsonObj, "is-base-module");
+ Assert.assertTrue(boolValue);
}
@Test
@@ -282,26 +256,26 @@ public class JsonUtils2Test {
// then
assertEquals(json, jsonUpd);
}
-
+
@Test
public void shouldConvertXmlToJsonAndBackToSameXmlExtractedFromTheRequest() throws Exception {
// given
- String value = JsonUtils.getJsonValue(jsonReq, "variables.bpmnRequest.value");
- String xmlReq = XmlTool.removeNamespaces(XmlTool.normalize(value));
+ String value = JsonUtils.getJsonValue(jsonReq, "variables.bpmnRequest.value");
+ String xmlReq = XmlTool.removeNamespaces(XmlTool.normalize(value));
// when
- String json = JsonUtils.xml2json(xmlReq);
- String xmlOut = JsonUtils.json2xml(json);
+ String json = JsonUtils.xml2json(xmlReq);
+ String xmlOut = JsonUtils.json2xml(json);
// then
Diff diffXml = DiffBuilder.compare(xmlReq).withTest(xmlOut).ignoreWhitespace()
.withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)).checkForSimilar().build();
assertFalse(diffXml.hasDifferences());
- }
-
+ }
+
@Test
public void shouldConvertJsonContainingArrayToXml() throws Exception {
// when
- String jsonParm = JsonUtils.getJsonNodeValue(jsonReqArray, "requestDetails.requestParameters.ucpeInfo");
- String xmlOut = JsonUtils.json2xml(jsonParm);
+ String jsonParm = JsonUtils.getJsonNodeValue(jsonReqArray, "requestDetails.requestParameters.ucpeInfo");
+ String xmlOut = JsonUtils.json2xml(jsonParm);
// then
Diff diffXml = DiffBuilder.compare(XML_ARRAY_REQ).withTest(xmlOut).ignoreWhitespace()
.withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)).checkForSimilar().build();
@@ -311,19 +285,19 @@ public class JsonUtils2Test {
@Test
// Tests the jsonSchemaValidation() method
public void testJsonSchemaValidation() {
- try {
- String myReqArray = jsonReqArray;
- String result = JsonUtils.jsonSchemaValidation(myReqArray, "src/test/resources/requestSchema.json");
- System.out.println("Schema Validation Result: " + result);
- Assert.assertTrue(result.contains("success"));
- // remove a required parameter from the JSON doc so that validation fails
- myReqArray = JsonUtils.delJsonValue(myReqArray, "requestDetails.requestParameters.ucpeInfo.ucpeHostName");
- result = JsonUtils.jsonSchemaValidation(myReqArray, "src/test/resources/requestSchema.json");
- System.out.println("Schema Validation Result: " + result);
- Assert.assertTrue(result.contains("failure"));
- Assert.assertTrue(result.contains("error: object has missing required properties ([\"ucpeHostName\"])"));
- } catch (ValidationException e) {
- e.printStackTrace();
- }
+ try {
+ String myReqArray = jsonReqArray;
+ String result = JsonUtils.jsonSchemaValidation(myReqArray, "src/test/resources/requestSchema.json");
+ System.out.println("Schema Validation Result: " + result);
+ Assert.assertTrue(result.contains("success"));
+ // remove a required parameter from the JSON doc so that validation fails
+ myReqArray = JsonUtils.delJsonValue(myReqArray, "requestDetails.requestParameters.ucpeInfo.ucpeHostName");
+ result = JsonUtils.jsonSchemaValidation(myReqArray, "src/test/resources/requestSchema.json");
+ System.out.println("Schema Validation Result: " + result);
+ Assert.assertTrue(result.contains("failure"));
+ Assert.assertTrue(result.contains("error: object has missing required properties ([\"ucpeHostName\"])"));
+ } catch (ValidationException e) {
+ e.printStackTrace();
+ }
}
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtilsTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtilsTest.java
index 067ae9806d..36ffc0b04d 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtilsTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/json/JsonUtilsTest.java
@@ -23,13 +23,11 @@ package org.onap.so.bpmn.core.json;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.runtime.Execution;
import org.json.JSONArray;
@@ -43,203 +41,232 @@ import org.onap.so.exceptions.ValidationException;
public class JsonUtilsTest {
- @Mock public DelegateExecution execution;
- @Mock public Execution mockEexecution;
- private final String fileLocation = "src/test/resources/json-examples/";
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Test
- public void jsonStringToMapTest() throws IOException {
-
- JsonUtils utils = new JsonUtils();
- String response = this.getJson("SDNCServiceResponseExample.json");
- String entry = JsonUtils.getJsonValue(response, "SDNCServiceResponse.params");
- Map<String, String> map = utils.jsonStringToMap(execution, entry);
- assertEquals(map.get("e2e-vpn-key"), "my-key");
- }
-
- @Test
- public void entryArrayToMapTest() throws IOException {
- JsonUtils utils = new JsonUtils();
- String response = this.getJson("SNIROExample.json");
- String entry = JsonUtils.getJsonValue(response, "solutionInfo.placementInfo");
- JSONArray arr = new JSONArray(entry);
- JSONObject homingDataJson = arr.getJSONObject(0);
- JSONArray assignmentInfo = homingDataJson.getJSONArray("assignmentInfo");
- Map<String, String> map = utils.entryArrayToMap(execution, assignmentInfo.toString(), "variableName", "variableValue");
- assertEquals(map.get("cloudOwner"), "CloudOwner");
- }
- @Test
- public void entryArrayToMapStringTest() throws IOException {
- JsonUtils utils = new JsonUtils();
- String response = this.getJson("SNIROExample.json");
- String entry = JsonUtils.getJsonValue(response, "solutionInfo.placementInfo");
- JSONArray arr = new JSONArray(entry);
- JSONObject homingDataJson = arr.getJSONObject(0);
- JSONArray assignmentInfo = homingDataJson.getJSONArray("assignmentInfo");
- Map<String, String> map = utils.entryArrayToMap(assignmentInfo.toString(), "variableName", "variableValue");
- assertEquals(map.get("cloudOwner"), "CloudOwner");
- }
- @Test
- public void entryArrayToMapStringTestOof() throws IOException {
- JsonUtils utils = new JsonUtils();
- String response = this.getJson("OofExample.json");
- String entry = JsonUtils.getJsonValue(response, "solutions.placementSolutions");
- JSONArray arr = new JSONArray(entry);
- JSONArray arr2 = arr.getJSONArray(0);
- JSONObject homingDataJson = arr2.getJSONObject(0);
- JSONArray assignmentInfo = homingDataJson.getJSONArray("assignmentInfo");
- Map<String, String> map = utils.entryArrayToMap(assignmentInfo.toString(), "key", "value");
- assertEquals(map.get("cloudOwner"), "HPA-cloud");
- }
- @Test
- public void getJsonRootPropertyTest() throws IOException {
- String response = this.getJson("SDNCServiceResponseExample.json");
- assertEquals("SDNCServiceResponse",JsonUtils.getJsonRootProperty(response));
- }
- @Test
- public void getJsonRootProperty_ExceptionTest() throws IOException {
- expectedException.expect(JSONException.class);
- String response = this.getJson("SNIROExample.json");
- String root = JsonUtils.getJsonRootProperty(response);
- }
- @Test
- public void getJsonNodeValueTest() throws IOException {
- String response = this.getJson("SDNCServiceResponseExample.json");
- String code = JsonUtils.getJsonNodeValue(response,"SDNCServiceResponse.responseCode");
- assertEquals("200", code);
- }
- @Test
- public void stringArrayToList_jsonStringTest() throws IOException {
- String response = this.getJson("SNIROExample.json");
- String licenseInfo = JsonUtils.getJsonNodeValue(response,"solutionInfo.licenseInfo");
- JsonUtils utils = new JsonUtils();
- List<String> listString = utils.StringArrayToList(licenseInfo);
- assertNotNull(listString.get(0));
- }
- @Test
- public void stringArrayToList_JSONArrayTest() throws IOException {
- String response = this.getJson("SNIROExample.json");
- String licenseInfo = JsonUtils.getJsonNodeValue(response,"solutionInfo.licenseInfo");
- JSONArray jsonArray = new JSONArray(licenseInfo);
- JsonUtils utils = new JsonUtils();
- List<String> listString = utils.StringArrayToList(jsonArray);
- assertNotNull(listString.get(0));
- }
- @Test
- public void stringArrayToList_withExecutionTest() throws IOException {
- String response = this.getJson("SNIROExample.json");
- String licenseInfo = JsonUtils.getJsonNodeValue(response,"solutionInfo.licenseInfo");
- JsonUtils utils = new JsonUtils();
- List<String> listString = utils.StringArrayToList(mockEexecution, licenseInfo);
- assertNotNull(listString.get(0));
- }
- @Test
- public void jsonElementExist_trueTest() throws IOException {
- String response = this.getJson("SDNCServiceResponseExample.json");
- boolean isExist = JsonUtils.jsonElementExist(response,"SDNCServiceResponse.responseCode");
- assertEquals(true, isExist);
- }
- @Test
- public void jsonElementExist_falseTest() throws IOException {
- String response = this.getJson("SDNCServiceResponseExample.json");
- boolean isExist = JsonUtils.jsonElementExist(response,"SDNCServiceResponse.responseX");
- assertEquals(false, isExist);
- }
- @Test
- public void jsonElementExist_NullTest() throws IOException {
- String response = this.getJson("SDNCServiceResponseExample.json");
- boolean isExist = JsonUtils.jsonElementExist(response, null);
- assertEquals(true, isExist);
- }
- @Test
- public void jsonSchemaValidation_ExceptionTest() throws IOException, ValidationException {
- expectedException.expect(ValidationException.class);
- String response = this.getJson("SDNCServiceResponseExample.json");
- String isExist = JsonUtils.jsonSchemaValidation(response, fileLocation);
- }
- @Test
- public void getJsonIntValueTest() throws IOException {
- String response = this.getJson("SDNCServiceResponseExample.json");
- int intValue = JsonUtils.getJsonIntValue(response,"SDNCServiceResponse.responseCode");
- assertEquals(0, intValue);
- }
- @Test
- public void getJsonBooleanValueTest() throws IOException {
- String response = this.getJson("SDNCServiceResponseExample.json");
- boolean isBoolean = JsonUtils.getJsonBooleanValue(response,"SDNCServiceResponse.responseCode");
- assertEquals(false, isBoolean);
- }
- @Test
- public void prettyJsonTest() throws IOException {
- String response = this.getJson("SNIROExample.json");
- assertNotNull(JsonUtils.prettyJson(response));
- String malformedJson = "{\"name\" \"myName\"}";
- assertNull(JsonUtils.prettyJson(malformedJson));
- }
- @Test
- public void xml2jsonTest() throws IOException {
- String expectedJson = "{\"name\":\"myName\"}";
- String xml = "<name>myName</name>";
- assertEquals(expectedJson, JsonUtils.xml2json(xml,false));
- }
- @Test
- public void xml2jsonErrorTest() throws IOException {
- String malformedXml = "<name>myName<name>";
- assertNull(JsonUtils.xml2json(malformedXml));
- }
- @Test
- public void json2xmlTest() throws IOException {
- String expectedXml = "<name>myName</name>";
- String malformedJson = "{\"name\":\"myName\"}";
- assertEquals(expectedXml, JsonUtils.json2xml(malformedJson, false));
- }
- @Test
- public void json2xmlErrorTest() throws IOException {
- String malformedJson = "{\"name\" \"myName\"}";
- assertNull(JsonUtils.json2xml(malformedJson));
- }
- @Test
- public void getJsonValueErrorTest() throws IOException {
- String response = this.getJson("SDNCServiceResponseExample.json");
- assertNull(JsonUtils.getJsonValue(response,null));
- }
- @Test
- public void getJsonNodeValueErrorTest() throws IOException {
- String response = this.getJson("SDNCServiceResponseExample.json");
- assertNull(JsonUtils.getJsonNodeValue(response,null));
- }
- @Test
- public void getJsonIntValueErrorTest() throws IOException {
- String response = this.getJson("SDNCServiceResponseExample.json");
- assertEquals(0, JsonUtils.getJsonIntValue(response,null));
- }
- @Test
- public void getJsonBooleanValueErrorTest() throws IOException {
- String response = this.getJson("SDNCServiceResponseExample.json");
- assertEquals(false, JsonUtils.getJsonBooleanValue(response,null));
- }
- @Test
- public void getJsonValueForKeyErrorTest() throws IOException {
- String malformedJson = "{\"name\" \"myName\"}";
- assertNull(JsonUtils.getJsonValueForKey(malformedJson, "name"));
- }
- @Test
- public void updJsonValueTest() throws IOException {
- String expectedJson = "{\"name\": \"yourName\"}";
- String json = "{\"name\":\"myName\"}";
- assertEquals(expectedJson, JsonUtils.updJsonValue(json, "name", "yourName"));
- }
- @Test
- public void updJsonValueErrorTest() throws IOException {
- String expectedJson = "{\"name\" \"myName\"}";
- String json = "{\"name\" \"myName\"}";
- assertEquals(expectedJson, JsonUtils.updJsonValue(json, "name", "yourName"));
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get(fileLocation + filename)));
- }
+ @Mock
+ public DelegateExecution execution;
+ @Mock
+ public Execution mockEexecution;
+ private final String fileLocation = "src/test/resources/json-examples/";
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Test
+ public void jsonStringToMapTest() throws IOException {
+
+ JsonUtils utils = new JsonUtils();
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ String entry = JsonUtils.getJsonValue(response, "SDNCServiceResponse.params");
+ Map<String, String> map = utils.jsonStringToMap(execution, entry);
+ assertEquals(map.get("e2e-vpn-key"), "my-key");
+ }
+
+ @Test
+ public void entryArrayToMapTest() throws IOException {
+ JsonUtils utils = new JsonUtils();
+ String response = this.getJson("SNIROExample.json");
+ String entry = JsonUtils.getJsonValue(response, "solutionInfo.placementInfo");
+ JSONArray arr = new JSONArray(entry);
+ JSONObject homingDataJson = arr.getJSONObject(0);
+ JSONArray assignmentInfo = homingDataJson.getJSONArray("assignmentInfo");
+ Map<String, String> map =
+ utils.entryArrayToMap(execution, assignmentInfo.toString(), "variableName", "variableValue");
+ assertEquals(map.get("cloudOwner"), "CloudOwner");
+ }
+
+ @Test
+ public void entryArrayToMapStringTest() throws IOException {
+ JsonUtils utils = new JsonUtils();
+ String response = this.getJson("SNIROExample.json");
+ String entry = JsonUtils.getJsonValue(response, "solutionInfo.placementInfo");
+ JSONArray arr = new JSONArray(entry);
+ JSONObject homingDataJson = arr.getJSONObject(0);
+ JSONArray assignmentInfo = homingDataJson.getJSONArray("assignmentInfo");
+ Map<String, String> map = utils.entryArrayToMap(assignmentInfo.toString(), "variableName", "variableValue");
+ assertEquals(map.get("cloudOwner"), "CloudOwner");
+ }
+
+ @Test
+ public void entryArrayToMapStringTestOof() throws IOException {
+ JsonUtils utils = new JsonUtils();
+ String response = this.getJson("OofExample.json");
+ String entry = JsonUtils.getJsonValue(response, "solutions.placementSolutions");
+ JSONArray arr = new JSONArray(entry);
+ JSONArray arr2 = arr.getJSONArray(0);
+ JSONObject homingDataJson = arr2.getJSONObject(0);
+ JSONArray assignmentInfo = homingDataJson.getJSONArray("assignmentInfo");
+ Map<String, String> map = utils.entryArrayToMap(assignmentInfo.toString(), "key", "value");
+ assertEquals(map.get("cloudOwner"), "HPA-cloud");
+ }
+
+ @Test
+ public void getJsonRootPropertyTest() throws IOException {
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ assertEquals("SDNCServiceResponse", JsonUtils.getJsonRootProperty(response));
+ }
+
+ @Test
+ public void getJsonRootProperty_ExceptionTest() throws IOException {
+ expectedException.expect(JSONException.class);
+ String response = this.getJson("SNIROExample.json");
+ String root = JsonUtils.getJsonRootProperty(response);
+ }
+
+ @Test
+ public void getJsonNodeValueTest() throws IOException {
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ String code = JsonUtils.getJsonNodeValue(response, "SDNCServiceResponse.responseCode");
+ assertEquals("200", code);
+ }
+
+ @Test
+ public void stringArrayToList_jsonStringTest() throws IOException {
+ String response = this.getJson("SNIROExample.json");
+ String licenseInfo = JsonUtils.getJsonNodeValue(response, "solutionInfo.licenseInfo");
+ JsonUtils utils = new JsonUtils();
+ List<String> listString = utils.StringArrayToList(licenseInfo);
+ assertNotNull(listString.get(0));
+ }
+
+ @Test
+ public void stringArrayToList_JSONArrayTest() throws IOException {
+ String response = this.getJson("SNIROExample.json");
+ String licenseInfo = JsonUtils.getJsonNodeValue(response, "solutionInfo.licenseInfo");
+ JSONArray jsonArray = new JSONArray(licenseInfo);
+ JsonUtils utils = new JsonUtils();
+ List<String> listString = utils.StringArrayToList(jsonArray);
+ assertNotNull(listString.get(0));
+ }
+
+ @Test
+ public void stringArrayToList_withExecutionTest() throws IOException {
+ String response = this.getJson("SNIROExample.json");
+ String licenseInfo = JsonUtils.getJsonNodeValue(response, "solutionInfo.licenseInfo");
+ JsonUtils utils = new JsonUtils();
+ List<String> listString = utils.StringArrayToList(mockEexecution, licenseInfo);
+ assertNotNull(listString.get(0));
+ }
+
+ @Test
+ public void jsonElementExist_trueTest() throws IOException {
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ boolean isExist = JsonUtils.jsonElementExist(response, "SDNCServiceResponse.responseCode");
+ assertEquals(true, isExist);
+ }
+
+ @Test
+ public void jsonElementExist_falseTest() throws IOException {
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ boolean isExist = JsonUtils.jsonElementExist(response, "SDNCServiceResponse.responseX");
+ assertEquals(false, isExist);
+ }
+
+ @Test
+ public void jsonElementExist_NullTest() throws IOException {
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ boolean isExist = JsonUtils.jsonElementExist(response, null);
+ assertEquals(true, isExist);
+ }
+
+ @Test
+ public void jsonSchemaValidation_ExceptionTest() throws IOException, ValidationException {
+ expectedException.expect(ValidationException.class);
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ String isExist = JsonUtils.jsonSchemaValidation(response, fileLocation);
+ }
+
+ @Test
+ public void getJsonIntValueTest() throws IOException {
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ int intValue = JsonUtils.getJsonIntValue(response, "SDNCServiceResponse.responseCode");
+ assertEquals(0, intValue);
+ }
+
+ @Test
+ public void getJsonBooleanValueTest() throws IOException {
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ boolean isBoolean = JsonUtils.getJsonBooleanValue(response, "SDNCServiceResponse.responseCode");
+ assertEquals(false, isBoolean);
+ }
+
+ @Test
+ public void prettyJsonTest() throws IOException {
+ String response = this.getJson("SNIROExample.json");
+ assertNotNull(JsonUtils.prettyJson(response));
+ String malformedJson = "{\"name\" \"myName\"}";
+ assertNull(JsonUtils.prettyJson(malformedJson));
+ }
+
+ @Test
+ public void xml2jsonTest() throws IOException {
+ String expectedJson = "{\"name\":\"myName\"}";
+ String xml = "<name>myName</name>";
+ assertEquals(expectedJson, JsonUtils.xml2json(xml, false));
+ }
+
+ @Test
+ public void xml2jsonErrorTest() throws IOException {
+ String malformedXml = "<name>myName<name>";
+ assertNull(JsonUtils.xml2json(malformedXml));
+ }
+
+ @Test
+ public void json2xmlTest() throws IOException {
+ String expectedXml = "<name>myName</name>";
+ String malformedJson = "{\"name\":\"myName\"}";
+ assertEquals(expectedXml, JsonUtils.json2xml(malformedJson, false));
+ }
+
+ @Test
+ public void json2xmlErrorTest() throws IOException {
+ String malformedJson = "{\"name\" \"myName\"}";
+ assertNull(JsonUtils.json2xml(malformedJson));
+ }
+
+ @Test
+ public void getJsonValueErrorTest() throws IOException {
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ assertNull(JsonUtils.getJsonValue(response, null));
+ }
+
+ @Test
+ public void getJsonNodeValueErrorTest() throws IOException {
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ assertNull(JsonUtils.getJsonNodeValue(response, null));
+ }
+
+ @Test
+ public void getJsonIntValueErrorTest() throws IOException {
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ assertEquals(0, JsonUtils.getJsonIntValue(response, null));
+ }
+
+ @Test
+ public void getJsonBooleanValueErrorTest() throws IOException {
+ String response = this.getJson("SDNCServiceResponseExample.json");
+ assertEquals(false, JsonUtils.getJsonBooleanValue(response, null));
+ }
+
+ @Test
+ public void getJsonValueForKeyErrorTest() throws IOException {
+ String malformedJson = "{\"name\" \"myName\"}";
+ assertNull(JsonUtils.getJsonValueForKey(malformedJson, "name"));
+ }
+
+ @Test
+ public void updJsonValueTest() throws IOException {
+ String expectedJson = "{\"name\": \"yourName\"}";
+ String json = "{\"name\":\"myName\"}";
+ assertEquals(expectedJson, JsonUtils.updJsonValue(json, "name", "yourName"));
+ }
+
+ @Test
+ public void updJsonValueErrorTest() throws IOException {
+ String expectedJson = "{\"name\" \"myName\"}";
+ String json = "{\"name\" \"myName\"}";
+ assertEquals(expectedJson, JsonUtils.updJsonValue(json, "name", "yourName"));
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(fileLocation + filename)));
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/utils/CamundaDBSetup.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/utils/CamundaDBSetup.java
index 15f6fbe008..b6a2e789ba 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/utils/CamundaDBSetup.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/utils/CamundaDBSetup.java
@@ -25,7 +25,6 @@ package org.onap.so.bpmn.core.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -33,43 +32,42 @@ import org.slf4j.LoggerFactory;
* Sets up the unit test (H2) database for Camunda.
*/
public class CamundaDBSetup {
- private static boolean isDBConfigured = false;
- private static final Logger logger = LoggerFactory.getLogger(CamundaDBSetup.class);
-
- private CamundaDBSetup() {
- }
-
- public static synchronized void configure() throws SQLException {
- if (isDBConfigured) {
- return;
- }
+ private static boolean isDBConfigured = false;
+ private static final Logger logger = LoggerFactory.getLogger(CamundaDBSetup.class);
+
+ private CamundaDBSetup() {}
+
+ public static synchronized void configure() throws SQLException {
+ if (isDBConfigured) {
+ return;
+ }
+
+ logger.debug("Configuring the Camunda H2 database for MSO");
- logger.debug ("Configuring the Camunda H2 database for MSO");
+ Connection connection = null;
+ PreparedStatement stmt = null;
- Connection connection = null;
- PreparedStatement stmt = null;
+ try {
- try {
+ isDBConfigured = true;
- isDBConfigured = true;
-
- } finally {
- if (stmt != null) {
- try {
- stmt.close();
- } catch (Exception e) {
- logger.debug("Exception :",e);
- }
- }
+ } finally {
+ if (stmt != null) {
+ try {
+ stmt.close();
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ }
+ }
- if (connection != null) {
- try {
- connection.close();
- } catch (Exception e) {
- logger.debug("Exception :",e);
- }
- }
- }
- }
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ }
+ }
+ }
+ }
}
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/xml/XmlToolTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/xml/XmlToolTest.java
index 6bad0c6c29..d099cbebcc 100644
--- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/xml/XmlToolTest.java
+++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/xml/XmlToolTest.java
@@ -1,82 +1,72 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
-*/
+ */
package org.onap.so.bpmn.core.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.util.Optional;
-
import org.junit.Test;
public class XmlToolTest {
- private String response = "<Response>good</Response>";
- private String responseModified = "<Response>veryGood</Response>";
- private String encodeResponse = "&lt;Response&gt;good&lt;/Response&gt;";
- private String encodeResponseNamespace = "<Response xmlns:ns2=\"http://ecomp.att.com/mso/request/types/v1\">good</Response>";
- private String attribute = "<Response>good&\"bad\"</Response>";
- private String updatedAttribute = "&lt;Response&gt;good&amp;&quot;bad&quot;&lt;/Response&gt;";
+ private String response = "<Response>good</Response>";
+ private String responseModified = "<Response>veryGood</Response>";
+ private String encodeResponse = "&lt;Response&gt;good&lt;/Response&gt;";
+ private String encodeResponseNamespace =
+ "<Response xmlns:ns2=\"http://ecomp.att.com/mso/request/types/v1\">good</Response>";
+ private String attribute = "<Response>good&\"bad\"</Response>";
+ private String updatedAttribute = "&lt;Response&gt;good&amp;&quot;bad&quot;&lt;/Response&gt;";
+
+ private String content = "<dummy><configuration-event>" + "<event-type>test</event-type>"
+ + "<event-correlator-type>test</event-correlator-type>" + "<event-correlator>123</event-correlator>"
+ + "<event-parameters><event-parameter>" + "<tag-name>test</tag-name>"
+ + "<tag-value>test</tag-value></event-parameter></event-parameters>" + "</configuration-event></dummy>";
+
+ @Test
+ public void test() throws Exception {
+ Object xmlMessage = new String(response);
+ String xmlResponse = XmlTool.normalize(xmlMessage);
+ assertEquals(response, xmlResponse.toString());
+ String xmlEncode = XmlTool.encode(xmlMessage);
+ assertEquals(encodeResponse, xmlEncode.toString());
+ Optional<String> optXml = XmlTool.modifyElement(response, "Response", "veryGood");
+ Object obj1 = new String(optXml.get().toString());
+ String noPreamble = XmlTool.removePreamble(obj1);
+ assertEquals(responseModified, noPreamble.toString());
+ Object obj2 = new String(encodeResponseNamespace);
+ String noNamespace = XmlTool.removeNamespaces(obj2);
+ assertEquals(response, noNamespace.toString());
+ Object obj3 = new String(attribute);
- private String content = "<dummy><configuration-event>" +
- "<event-type>test</event-type>" +
- "<event-correlator-type>test</event-correlator-type>" +
- "<event-correlator>123</event-correlator>" +
- "<event-parameters><event-parameter>" +
- "<tag-name>test</tag-name>" +
- "<tag-value>test</tag-value></event-parameter></event-parameters>" +
- "</configuration-event></dummy>";
-
- @Test
- public void test() throws Exception {
- Object xmlMessage = new String(response);
- String xmlResponse = XmlTool.normalize(xmlMessage);
- assertEquals(response, xmlResponse.toString());
- String xmlEncode = XmlTool.encode(xmlMessage);
- assertEquals(encodeResponse, xmlEncode.toString());
- Optional<String> optXml = XmlTool.modifyElement(response, "Response", "veryGood");
- Object obj1 = new String(optXml.get().toString());
- String noPreamble = XmlTool.removePreamble(obj1);
- assertEquals(responseModified, noPreamble.toString());
- Object obj2 = new String(encodeResponseNamespace);
- String noNamespace = XmlTool.removeNamespaces(obj2);
- assertEquals(response, noNamespace.toString());
- Object obj3 = new String(attribute);
-
- assertEquals(null, XmlTool.normalize(null));
- assertEquals(null, XmlTool.encode(null));
- assertEquals(null, XmlTool.removePreamble(null));
- assertEquals(null, XmlTool.removeNamespaces(null));
- assertEquals(Optional.empty(), XmlTool.modifyElement(null, "Response", "veryGood"));
- }
+ assertEquals(null, XmlTool.normalize(null));
+ assertEquals(null, XmlTool.encode(null));
+ assertEquals(null, XmlTool.removePreamble(null));
+ assertEquals(null, XmlTool.removeNamespaces(null));
+ assertEquals(Optional.empty(), XmlTool.modifyElement(null, "Response", "veryGood"));
+ }
- @Test
- public void normalizeTest() throws Exception {
- String response = XmlTool.normalize(content);
- assertNotNull(response);
- }
+ @Test
+ public void normalizeTest() throws Exception {
+ String response = XmlTool.normalize(content);
+ assertNotNull(response);
+ }
- @Test
- public void modifyElementTest() throws Exception {
- String response = XmlTool.modifyElement(content, "event-type", "uCPE-VMS").get();
- assertNotNull(response);
- }
+ @Test
+ public void modifyElementTest() throws Exception {
+ String response = XmlTool.modifyElement(content, "event-type", "uCPE-VMS").get();
+ assertNotNull(response);
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/CallbackHeader.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/CallbackHeader.java
index bf4c59ca09..1172d77c13 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/CallbackHeader.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/CallbackHeader.java
@@ -28,9 +28,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -49,28 +51,24 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "requestId",
- "responseCode",
- "responseMessage"
-}, namespace="http://org.onap/workflow/sdnc/adapter/schema/v1")
+@XmlType(name = "", propOrder = {"requestId", "responseCode", "responseMessage"},
+ namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1")
@XmlRootElement(name = "CallbackHeader")
public class CallbackHeader {
- @XmlElement(name = "RequestId", required = true, namespace="http://org.onap/workflow/sdnc/adapter/schema/v1")
+ @XmlElement(name = "RequestId", required = true, namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1")
protected String requestId;
- @XmlElement(name = "ResponseCode", required = true,namespace="http://org.onap/workflow/sdnc/adapter/schema/v1")
+ @XmlElement(name = "ResponseCode", required = true, namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1")
protected String responseCode;
- @XmlElement(name = "ResponseMessage", required = true,namespace="http://org.onap/workflow/sdnc/adapter/schema/v1")
+ @XmlElement(name = "ResponseMessage", required = true,
+ namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1")
protected String responseMessage;
/**
* Gets the value of the requestId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getRequestId() {
return requestId;
@@ -79,10 +77,8 @@ public class CallbackHeader {
/**
* Sets the value of the requestId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setRequestId(String value) {
this.requestId = value;
@@ -91,10 +87,8 @@ public class CallbackHeader {
/**
* Gets the value of the responseCode property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getResponseCode() {
return responseCode;
@@ -103,10 +97,8 @@ public class CallbackHeader {
/**
* Sets the value of the responseCode property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setResponseCode(String value) {
this.responseCode = value;
@@ -115,10 +107,8 @@ public class CallbackHeader {
/**
* Gets the value of the responseMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getResponseMessage() {
return responseMessage;
@@ -127,10 +117,8 @@ public class CallbackHeader {
/**
* Sets the value of the responseMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setResponseMessage(String value) {
this.responseMessage = value;
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/ObjectFactory.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/ObjectFactory.java
index a72e23e57f..721bc1d4f3 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/ObjectFactory.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/ObjectFactory.java
@@ -24,17 +24,13 @@ import javax.xml.bind.annotation.XmlRegistry;
/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the org.openecomp.domain2.workflow.sdnc.adapter.schema.v1 package.
- * <p>An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
- * provided in this class.
+ * This object contains factory methods for each Java content interface and Java element interface generated in the
+ * org.openecomp.domain2.workflow.sdnc.adapter.schema.v1 package.
+ * <p>
+ * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content.
+ * The Java representation of XML content can consist of schema derived interfaces and classes representing the binding
+ * of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in
+ * this class.
*
*/
@XmlRegistry
@@ -42,11 +38,11 @@ public class ObjectFactory {
/**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.openecomp.domain2.workflow.sdnc.adapter.schema.v1
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
+ * org.openecomp.domain2.workflow.sdnc.adapter.schema.v1
*
*/
- public ObjectFactory() {
- }
+ public ObjectFactory() {}
/**
* Create an instance of {@link RequestHeader }
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/RequestHeader.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/RequestHeader.java
index 2c56a110db..58f5c468f5 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/RequestHeader.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/RequestHeader.java
@@ -28,9 +28,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -52,14 +54,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "requestId",
- "svcInstanceId",
- "svcAction",
- "svcOperation",
- "callbackUrl",
- "msoAction"
-})
+@XmlType(name = "", propOrder = {"requestId", "svcInstanceId", "svcAction", "svcOperation", "callbackUrl", "msoAction"})
@XmlRootElement(name = "RequestHeader")
public class RequestHeader {
@@ -79,10 +74,8 @@ public class RequestHeader {
/**
* Gets the value of the requestId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getRequestId() {
return requestId;
@@ -91,10 +84,8 @@ public class RequestHeader {
/**
* Sets the value of the requestId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setRequestId(String value) {
this.requestId = value;
@@ -103,10 +94,8 @@ public class RequestHeader {
/**
* Gets the value of the svcInstanceId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getSvcInstanceId() {
return svcInstanceId;
@@ -115,10 +104,8 @@ public class RequestHeader {
/**
* Sets the value of the svcInstanceId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setSvcInstanceId(String value) {
this.svcInstanceId = value;
@@ -127,10 +114,8 @@ public class RequestHeader {
/**
* Gets the value of the svcAction property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getSvcAction() {
return svcAction;
@@ -139,10 +124,8 @@ public class RequestHeader {
/**
* Sets the value of the svcAction property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setSvcAction(String value) {
this.svcAction = value;
@@ -151,10 +134,8 @@ public class RequestHeader {
/**
* Gets the value of the svcOperation property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getSvcOperation() {
return svcOperation;
@@ -163,10 +144,8 @@ public class RequestHeader {
/**
* Sets the value of the svcOperation property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setSvcOperation(String value) {
this.svcOperation = value;
@@ -175,10 +154,8 @@ public class RequestHeader {
/**
* Gets the value of the callbackUrl property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getCallbackUrl() {
return callbackUrl;
@@ -187,10 +164,8 @@ public class RequestHeader {
/**
* Sets the value of the callbackUrl property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setCallbackUrl(String value) {
this.callbackUrl = value;
@@ -199,10 +174,8 @@ public class RequestHeader {
/**
* Gets the value of the msoAction property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMsoAction() {
return msoAction;
@@ -211,10 +184,8 @@ public class RequestHeader {
/**
* Sets the value of the msoAction property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMsoAction(String value) {
this.msoAction = value;
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterCallbackRequest.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterCallbackRequest.java
index e77232510a..2b4b8cb90f 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterCallbackRequest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterCallbackRequest.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.common.adapter.sdnc;
import java.io.StringWriter;
-
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
@@ -33,9 +32,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -53,25 +54,21 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", namespace="http://org.onap/workflow/sdnc/adapter/schema/v1", propOrder = {
- "callbackHeader",
- "requestData"
-})
-@XmlRootElement(name = "SDNCAdapterCallbackRequest", namespace="http://org.onap/workflow/sdnc/adapter/schema/v1")
+@XmlType(name = "", namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1",
+ propOrder = {"callbackHeader", "requestData"})
+@XmlRootElement(name = "SDNCAdapterCallbackRequest", namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1")
public class SDNCAdapterCallbackRequest {
- @XmlElement(name = "CallbackHeader", required = true, namespace="http://org.onap/workflow/sdnc/adapter/schema/v1")
+ @XmlElement(name = "CallbackHeader", required = true, namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1")
protected CallbackHeader callbackHeader;
- @XmlElement(name = "RequestData", required=false, namespace="http://org.onap/workflow/sdnc/adapter/schema/v1")
+ @XmlElement(name = "RequestData", required = false, namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1")
protected Object requestData;
/**
* Gets the value of the callbackHeader property.
*
- * @return
- * possible object is
- * {@link CallbackHeader }
- *
+ * @return possible object is {@link CallbackHeader }
+ *
*/
public CallbackHeader getCallbackHeader() {
return callbackHeader;
@@ -80,10 +77,8 @@ public class SDNCAdapterCallbackRequest {
/**
* Sets the value of the callbackHeader property.
*
- * @param value
- * allowed object is
- * {@link CallbackHeader }
- *
+ * @param value allowed object is {@link CallbackHeader }
+ *
*/
public void setCallbackHeader(CallbackHeader value) {
this.callbackHeader = value;
@@ -92,10 +87,8 @@ public class SDNCAdapterCallbackRequest {
/**
* Gets the value of the requestData property.
*
- * @return
- * possible object is
- * {@link Object }
- *
+ * @return possible object is {@link Object }
+ *
*/
public Object getRequestData() {
return requestData;
@@ -104,27 +97,24 @@ public class SDNCAdapterCallbackRequest {
/**
* Sets the value of the requestData property.
*
- * @param value
- * allowed object is
- * {@link Object }
- *
+ * @param value allowed object is {@link Object }
+ *
*/
public void setRequestData(Object value) {
this.requestData = value;
}
@Override
- public String toString() {
- StringWriter writer = new StringWriter();
- try {
- JAXBContext context = JAXBContext
- .newInstance(SDNCAdapterCallbackRequest.class);
- Marshaller m = context.createMarshaller();
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
- m.marshal(this, writer);
- return writer.getBuffer().toString();
- } catch (JAXBException e) {
- return "";
- }
- }
+ public String toString() {
+ StringWriter writer = new StringWriter();
+ try {
+ JAXBContext context = JAXBContext.newInstance(SDNCAdapterCallbackRequest.class);
+ Marshaller m = context.createMarshaller();
+ m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
+ m.marshal(this, writer);
+ return writer.getBuffer().toString();
+ } catch (JAXBException e) {
+ return "";
+ }
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterRequest.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterRequest.java
index 179776d95d..0ae5f7a614 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterRequest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterRequest.java
@@ -28,9 +28,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -48,10 +50,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "requestHeader",
- "requestData"
-})
+@XmlType(name = "", propOrder = {"requestHeader", "requestData"})
@XmlRootElement(name = "SDNCAdapterRequest")
public class SDNCAdapterRequest {
@@ -63,10 +62,8 @@ public class SDNCAdapterRequest {
/**
* Gets the value of the requestHeader property.
*
- * @return
- * possible object is
- * {@link RequestHeader }
- *
+ * @return possible object is {@link RequestHeader }
+ *
*/
public RequestHeader getRequestHeader() {
return requestHeader;
@@ -75,10 +72,8 @@ public class SDNCAdapterRequest {
/**
* Sets the value of the requestHeader property.
*
- * @param value
- * allowed object is
- * {@link RequestHeader }
- *
+ * @param value allowed object is {@link RequestHeader }
+ *
*/
public void setRequestHeader(RequestHeader value) {
this.requestHeader = value;
@@ -87,10 +82,8 @@ public class SDNCAdapterRequest {
/**
* Gets the value of the requestData property.
*
- * @return
- * possible object is
- * {@link Object }
- *
+ * @return possible object is {@link Object }
+ *
*/
public Object getRequestData() {
return requestData;
@@ -99,10 +92,8 @@ public class SDNCAdapterRequest {
/**
* Sets the value of the requestData property.
*
- * @param value
- * allowed object is
- * {@link Object }
- *
+ * @param value allowed object is {@link Object }
+ *
*/
public void setRequestData(Object value) {
this.requestData = value;
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterResponse.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterResponse.java
index 3666cb56a6..332b3ebbbd 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterResponse.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCAdapterResponse.java
@@ -27,9 +27,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCCallbackAdapterPortType.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCCallbackAdapterPortType.java
index eff70f5b12..887b1994d5 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCCallbackAdapterPortType.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/SDNCCallbackAdapterPortType.java
@@ -28,12 +28,11 @@ import javax.jws.soap.SOAPBinding;
/**
- * This class was generated by the JAX-WS RI.
- * JAX-WS RI 2.2.4-b01
- * Generated source version: 2.2
+ * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.4-b01 Generated source version: 2.2
*
*/
-@WebService(name = "SDNCCallbackAdapterPortType", targetNamespace = "http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1")
+@WebService(name = "SDNCCallbackAdapterPortType",
+ targetNamespace = "http://org.onap/workflow/sdnc/adapter/callback/wsdl/v1")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface SDNCCallbackAdapterPortType {
@@ -41,13 +40,13 @@ public interface SDNCCallbackAdapterPortType {
/**
*
* @param sdncAdapterCallbackRequest
- * @return
- * returns org.openecomp.domain2.workflow.sdnc.adapter.schema.v1.SDNCAdapterResponse
+ * @return returns org.openecomp.domain2.workflow.sdnc.adapter.schema.v1.SDNCAdapterResponse
*/
@WebMethod(operationName = "SDNCAdapterCallback")
- @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackResponse")
- public SDNCAdapterResponse sdncAdapterCallback(
- @WebParam(name = "SDNCAdapterCallbackRequest", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackRequest")
- SDNCAdapterCallbackRequest sdncAdapterCallbackRequest);
+ @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1",
+ partName = "SDNCAdapterCallbackResponse")
+ public SDNCAdapterResponse sdncAdapterCallback(@WebParam(name = "SDNCAdapterCallbackRequest",
+ targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1",
+ partName = "SDNCAdapterCallbackRequest") SDNCAdapterCallbackRequest sdncAdapterCallbackRequest);
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/package-info.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/package-info.java
index ec341d82b5..88be09ee85 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/package-info.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/sdnc/package-info.java
@@ -18,5 +18,6 @@
* ============LICENSE_END=========================================================
*/
-@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
+@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/workflow/sdnc/adapter/schema/v1",
+ elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.onap.so.bpmn.common.adapter.sdnc;
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/CreateVnfNotification.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/CreateVnfNotification.java
index aa348c7765..e1cb6fd38e 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/CreateVnfNotification.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/CreateVnfNotification.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.common.adapter.vnf;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -30,9 +29,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for createVnfNotification complex type.
+ * <p>
+ * Java class for createVnfNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="createVnfNotification">
@@ -76,15 +77,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "createVnfNotification1", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage",
- "vnfId",
- "outputs",
- "rollback"
-})
+@XmlType(name = "createVnfNotification1",
+ propOrder = {"messageId", "completed", "exception", "errorMessage", "vnfId", "outputs", "rollback"})
public class CreateVnfNotification {
@XmlElement(required = true)
@@ -99,10 +93,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -111,10 +103,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -139,10 +129,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -151,10 +139,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -163,10 +149,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -175,10 +159,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
@@ -187,10 +169,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the vnfId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfId() {
return vnfId;
@@ -199,10 +179,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the vnfId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfId(String value) {
this.vnfId = value;
@@ -211,10 +189,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the outputs property.
*
- * @return
- * possible object is
- * {@link CreateVnfNotification.Outputs }
- *
+ * @return possible object is {@link CreateVnfNotification.Outputs }
+ *
*/
public CreateVnfNotification.Outputs getOutputs() {
return outputs;
@@ -223,10 +199,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the outputs property.
*
- * @param value
- * allowed object is
- * {@link CreateVnfNotification.Outputs }
- *
+ * @param value allowed object is {@link CreateVnfNotification.Outputs }
+ *
*/
public void setOutputs(CreateVnfNotification.Outputs value) {
this.outputs = value;
@@ -235,10 +209,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the rollback property.
*
- * @return
- * possible object is
- * {@link VnfRollback }
- *
+ * @return possible object is {@link VnfRollback }
+ *
*/
public VnfRollback getRollback() {
return rollback;
@@ -247,10 +219,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the rollback property.
*
- * @param value
- * allowed object is
- * {@link VnfRollback }
- *
+ * @param value allowed object is {@link VnfRollback }
+ *
*/
public void setRollback(VnfRollback value) {
this.rollback = value;
@@ -258,9 +228,11 @@ public class CreateVnfNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -288,32 +260,29 @@ public class CreateVnfNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "entry"
- })
+ @XmlType(name = "", propOrder = {"entry"})
public static class Outputs {
protected List<CreateVnfNotification.Outputs.Entry> entry;
-
+
/**
* Gets the value of the entry property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the entry property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you
+ * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE>
+ * method for the entry property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getEntry().add(newItem);
+ * getEntry().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link CreateVnfNotification.Outputs.Entry }
+ * Objects of the following type(s) are allowed in the list {@link CreateVnfNotification.Outputs.Entry }
*
*
*/
@@ -325,24 +294,26 @@ public class CreateVnfNotification {
}
// Not a generated method
- @Override
+ @Override
public String toString() {
- StringBuilder out = new StringBuilder();
- out.append("<outputs>\n");
- if (entry != null) {
- for (Entry e : entry) {
- out.append(e.toString());
- out.append('\n');
- }
- }
- out.append("</outputs>");
- return out.toString();
+ StringBuilder out = new StringBuilder();
+ out.append("<outputs>\n");
+ if (entry != null) {
+ for (Entry e : entry) {
+ out.append(e.toString());
+ out.append('\n');
+ }
+ }
+ out.append("</outputs>");
+ return out.toString();
}
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -360,10 +331,7 @@ public class CreateVnfNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "key",
- "value"
- })
+ @XmlType(name = "", propOrder = {"key", "value"})
public static class Entry {
protected String key;
@@ -372,10 +340,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the key property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getKey() {
return key;
@@ -384,10 +350,8 @@ public class CreateVnfNotification {
/**
* Sets the value of the key property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setKey(String value) {
this.key = value;
@@ -396,10 +360,8 @@ public class CreateVnfNotification {
/**
* Gets the value of the value property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getValue() {
return value;
@@ -408,55 +370,45 @@ public class CreateVnfNotification {
/**
* Sets the value of the value property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setValue(String value) {
this.value = value;
-
+
}
-
+
// Not a generated method
@Override
public String toString() {
- String entrystr;
- entrystr =
- "<entry>"+ '\n' +
- " <key>"+key+"</key>" + '\n' +
- " <value>"+value+"</value>" + '\n' +
- "</entry>";
- return entrystr;
+ String entrystr;
+ entrystr = "<entry>" + '\n' + " <key>" + key + "</key>" + '\n' + " <value>" + value + "</value>"
+ + '\n' + "</entry>";
+ return entrystr;
}
}
}
- // Not a generated method
- @Override
- public String toString() {
- String createVnfNotification;
- if (exception==null) {
- createVnfNotification = "<ns2:createVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n' +
- " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' +
- " <messageId>"+messageId+"</messageId>" + '\n' +
- " <completed>"+completed+"</completed>" + '\n' +
- " <vnfId>"+vnfId+"</vnfId>" + '\n' +
- (outputs == null ? "" : outputs.toString() + '\n') +
- " <rollback>"+rollback+"</rollback>" + '\n' +
- "</ns2:createVnfNotification>";
- } else {
- createVnfNotification = "<ns2:createVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n' +
- " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' +
- " <messageId>"+messageId+"</messageId>" + '\n' +
- " <completed>"+completed+"</completed>" + '\n' +
- (outputs == null ? "" : outputs.toString() + '\n') +
- " <exception>"+exception+"</exception>" + '\n' +
- " <errorMessage>"+errorMessage+"</errorMessage>" + '\n' +
- "</ns2:createVnfNotification>";
- }
- return createVnfNotification;
- }
+ // Not a generated method
+ @Override
+ public String toString() {
+ String createVnfNotification;
+ if (exception == null) {
+ createVnfNotification = "<ns2:createVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n'
+ + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' + " <messageId>"
+ + messageId + "</messageId>" + '\n' + " <completed>" + completed + "</completed>" + '\n'
+ + " <vnfId>" + vnfId + "</vnfId>" + '\n' + (outputs == null ? "" : outputs.toString() + '\n')
+ + " <rollback>" + rollback + "</rollback>" + '\n' + "</ns2:createVnfNotification>";
+ } else {
+ createVnfNotification = "<ns2:createVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n'
+ + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' + " <messageId>"
+ + messageId + "</messageId>" + '\n' + " <completed>" + completed + "</completed>" + '\n'
+ + (outputs == null ? "" : outputs.toString() + '\n') + " <exception>" + exception + "</exception>"
+ + '\n' + " <errorMessage>" + errorMessage + "</errorMessage>" + '\n'
+ + "</ns2:createVnfNotification>";
+ }
+ return createVnfNotification;
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/DeleteVnfNotification.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/DeleteVnfNotification.java
index 3ad217306d..cd4257ec60 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/DeleteVnfNotification.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/DeleteVnfNotification.java
@@ -27,9 +27,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for deleteVnfNotification complex type.
+ * <p>
+ * Java class for deleteVnfNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="deleteVnfNotification">
@@ -49,12 +51,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "deleteVnfNotification1", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage"
-})
+@XmlType(name = "deleteVnfNotification1", propOrder = {"messageId", "completed", "exception", "errorMessage"})
public class DeleteVnfNotification {
@XmlElement(required = true)
@@ -66,10 +63,8 @@ public class DeleteVnfNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -78,10 +73,8 @@ public class DeleteVnfNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -106,10 +99,8 @@ public class DeleteVnfNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -118,10 +109,8 @@ public class DeleteVnfNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -130,10 +119,8 @@ public class DeleteVnfNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -142,57 +129,43 @@ public class DeleteVnfNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
}
/**
- * Overrides toString() method
+ * Overrides toString() method
+ *
* @return String type (deleteVnfNotification)
*/
-
+
@Override
- public String toString() {
- String deleteVnfNotification;
- if (exception == null) {
- deleteVnfNotification = "<ns2:deleteVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n' +
- " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' +
- " <messageId>"+messageId+"</messageId>" + '\n' +
- " <completed>"+completed+"</completed>" + '\n' +
- "</ns2:deleteVnfNotification>";
- } else {
- deleteVnfNotification = "<ns2:deleteVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n' +
- " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' +
- " <messageId>"+messageId+"</messageId>" + '\n' +
- " <completed>"+completed+"</completed>" + '\n' +
- " <exception>"+exception+"</exception>" + '\n' +
- " <errorMessage>"+errorMessage+"</errorMessage>" + '\n' +
- "</ns2:deleteVnfNotification>";
- }
- return deleteVnfNotification;
- }
-
-/*
- public String toString() {
- StringWriter writer = new StringWriter();
- try {
- JAXBContext context = JAXBContext
- .newInstance(DeleteVnfNotification.class);
- Marshaller m = context.createMarshaller();
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
- m.marshal(this, writer);
- //System.out.println("toString() - " + writer.getBuffer().toString());
- return writer.getBuffer().toString();
- } catch (JAXBException e) {
- //System.out.println("JAXBException - " + e.getStackTrace());
- return "";
- }
- }
-*/
-
+ public String toString() {
+ String deleteVnfNotification;
+ if (exception == null) {
+ deleteVnfNotification = "<ns2:deleteVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n'
+ + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' + " <messageId>"
+ + messageId + "</messageId>" + '\n' + " <completed>" + completed + "</completed>" + '\n'
+ + "</ns2:deleteVnfNotification>";
+ } else {
+ deleteVnfNotification = "<ns2:deleteVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n'
+ + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' + " <messageId>"
+ + messageId + "</messageId>" + '\n' + " <completed>" + completed + "</completed>" + '\n'
+ + " <exception>" + exception + "</exception>" + '\n' + " <errorMessage>" + errorMessage
+ + "</errorMessage>" + '\n' + "</ns2:deleteVnfNotification>";
+ }
+ return deleteVnfNotification;
+ }
+
+ /*
+ * public String toString() { StringWriter writer = new StringWriter(); try { JAXBContext context = JAXBContext
+ * .newInstance(DeleteVnfNotification.class); Marshaller m = context.createMarshaller();
+ * m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.marshal(this, writer);
+ * //System.out.println("toString() - " + writer.getBuffer().toString()); return writer.getBuffer().toString(); }
+ * catch (JAXBException e) { //System.out.println("JAXBException - " + e.getStackTrace()); return ""; } }
+ */
+
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/MsoExceptionCategory.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/MsoExceptionCategory.java
index e4c95e82cd..aae624dde1 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/MsoExceptionCategory.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/MsoExceptionCategory.java
@@ -25,10 +25,13 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for msoExceptionCategory.
+ * <p>
+ * Java class for msoExceptionCategory.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
* <p>
+ * The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ *
* <pre>
* &lt;simpleType name="msoExceptionCategory">
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
@@ -45,10 +48,7 @@ import javax.xml.bind.annotation.XmlType;
@XmlEnum
public enum MsoExceptionCategory {
- OPENSTACK,
- IO,
- INTERNAL,
- USERDATA;
+ OPENSTACK, IO, INTERNAL, USERDATA;
public String value() {
return name();
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/MsoRequest.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/MsoRequest.java
index 6830109097..3db5ca159a 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/MsoRequest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/MsoRequest.java
@@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for msoRequest complex type.
+ * <p>
+ * Java class for msoRequest complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="msoRequest">
@@ -46,10 +48,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "msoRequest", propOrder = {
- "requestId",
- "serviceInstanceId"
-})
+@XmlType(name = "msoRequest", propOrder = {"requestId", "serviceInstanceId"})
public class MsoRequest {
protected String requestId;
@@ -58,10 +57,8 @@ public class MsoRequest {
/**
* Gets the value of the requestId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getRequestId() {
return requestId;
@@ -70,10 +67,8 @@ public class MsoRequest {
/**
* Sets the value of the requestId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setRequestId(String value) {
this.requestId = value;
@@ -82,10 +77,8 @@ public class MsoRequest {
/**
* Gets the value of the serviceInstanceId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getServiceInstanceId() {
return serviceInstanceId;
@@ -94,10 +87,8 @@ public class MsoRequest {
/**
* Sets the value of the serviceInstanceId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setServiceInstanceId(String value) {
this.serviceInstanceId = value;
@@ -106,7 +97,7 @@ public class MsoRequest {
@Override
public String toString() {
return "<requestId>" + requestId + "</requestId>" + '\n' + "<serviceInstanceId>" + serviceInstanceId
- + "</serviceInstanceId>";
+ + "</serviceInstanceId>";
}
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/ObjectFactory.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/ObjectFactory.java
index 21bd08fae7..c84a9356b8 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/ObjectFactory.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/ObjectFactory.java
@@ -27,22 +27,18 @@ import javax.xml.namespace.QName;
/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the org.onap.so.adapters.vnf.async.client package.
- * <p>An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
- * provided in this class.
+ * This object contains factory methods for each Java content interface and Java element interface generated in the
+ * org.onap.so.adapters.vnf.async.client package.
+ * <p>
+ * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content.
+ * The Java representation of XML content can consist of schema derived interfaces and classes representing the binding
+ * of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in
+ * this class.
*
*/
@XmlRegistry
public class ObjectFactory {
- private static final String VNF_NOTIFY = "http://org.onap.so/vnfNotify";
+ private static final String VNF_NOTIFY = "http://org.onap.so/vnfNotify";
private static final QName _RollbackVnfNotification_QNAME = new QName(VNF_NOTIFY, "rollbackVnfNotification");
private static final QName _DeleteVnfNotification_QNAME = new QName(VNF_NOTIFY, "deleteVnfNotification");
private static final QName _CreateVnfNotification_QNAME = new QName(VNF_NOTIFY, "createVnfNotification");
@@ -50,11 +46,11 @@ public class ObjectFactory {
private static final QName _QueryVnfNotification_QNAME = new QName(VNF_NOTIFY, "queryVnfNotification");
/**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.so.adapters.vnf.async.client
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
+ * org.onap.so.adapters.vnf.async.client
*
*/
- public ObjectFactory() {
- }
+ public ObjectFactory() {}
/**
* Create an instance of {@link UpdateVnfNotification }
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/QueryVnfNotification.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/QueryVnfNotification.java
index e7496b8028..d3ac2439c1 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/QueryVnfNotification.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/QueryVnfNotification.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.common.adapter.vnf;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -30,9 +29,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for queryVnfNotification complex type.
+ * <p>
+ * Java class for queryVnfNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="queryVnfNotification">
@@ -77,16 +78,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "queryVnfNotification1", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage",
- "vnfExists",
- "vnfId",
- "status",
- "outputs"
-})
+@XmlType(name = "queryVnfNotification1",
+ propOrder = {"messageId", "completed", "exception", "errorMessage", "vnfExists", "vnfId", "status", "outputs"})
public class QueryVnfNotification {
@XmlElement(required = true)
@@ -102,10 +95,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -114,10 +105,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -142,10 +131,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -154,10 +141,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -166,10 +151,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -178,10 +161,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
@@ -190,10 +171,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the vnfExists property.
*
- * @return
- * possible object is
- * {@link Boolean }
- *
+ * @return possible object is {@link Boolean }
+ *
*/
public Boolean isVnfExists() {
return vnfExists;
@@ -202,10 +181,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the vnfExists property.
*
- * @param value
- * allowed object is
- * {@link Boolean }
- *
+ * @param value allowed object is {@link Boolean }
+ *
*/
public void setVnfExists(Boolean value) {
this.vnfExists = value;
@@ -214,10 +191,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the vnfId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfId() {
return vnfId;
@@ -226,10 +201,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the vnfId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfId(String value) {
this.vnfId = value;
@@ -238,10 +211,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the status property.
*
- * @return
- * possible object is
- * {@link VnfStatus }
- *
+ * @return possible object is {@link VnfStatus }
+ *
*/
public VnfStatus getStatus() {
return status;
@@ -250,10 +221,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the status property.
*
- * @param value
- * allowed object is
- * {@link VnfStatus }
- *
+ * @param value allowed object is {@link VnfStatus }
+ *
*/
public void setStatus(VnfStatus value) {
this.status = value;
@@ -262,10 +231,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the outputs property.
*
- * @return
- * possible object is
- * {@link QueryVnfNotification.Outputs }
- *
+ * @return possible object is {@link QueryVnfNotification.Outputs }
+ *
*/
public QueryVnfNotification.Outputs getOutputs() {
return outputs;
@@ -274,10 +241,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the outputs property.
*
- * @param value
- * allowed object is
- * {@link QueryVnfNotification.Outputs }
- *
+ * @param value allowed object is {@link QueryVnfNotification.Outputs }
+ *
*/
public void setOutputs(QueryVnfNotification.Outputs value) {
this.outputs = value;
@@ -285,9 +250,11 @@ public class QueryVnfNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -315,9 +282,7 @@ public class QueryVnfNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "entry"
- })
+ @XmlType(name = "", propOrder = {"entry"})
public static class Outputs {
protected List<QueryVnfNotification.Outputs.Entry> entry;
@@ -326,21 +291,20 @@ public class QueryVnfNotification {
* Gets the value of the entry property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the entry property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you
+ * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE>
+ * method for the entry property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getEntry().add(newItem);
+ * getEntry().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link QueryVnfNotification.Outputs.Entry }
+ * Objects of the following type(s) are allowed in the list {@link QueryVnfNotification.Outputs.Entry }
*
*
*/
@@ -350,26 +314,28 @@ public class QueryVnfNotification {
}
return this.entry;
}
-
+
// Not a generated method
public String toString() {
- StringBuilder out = new StringBuilder();
- out.append("<outputs>\n");
- if (entry != null) {
- for (Entry e : entry) {
- out.append(e.toString());
- out.append('\n');
- }
- }
- out.append("</outputs>");
- return out.toString();
+ StringBuilder out = new StringBuilder();
+ out.append("<outputs>\n");
+ if (entry != null) {
+ for (Entry e : entry) {
+ out.append(e.toString());
+ out.append('\n');
+ }
+ }
+ out.append("</outputs>");
+ return out.toString();
}
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -387,10 +353,7 @@ public class QueryVnfNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "key",
- "value"
- })
+ @XmlType(name = "", propOrder = {"key", "value"})
public static class Entry {
protected String key;
@@ -399,10 +362,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the key property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getKey() {
return key;
@@ -411,10 +372,8 @@ public class QueryVnfNotification {
/**
* Sets the value of the key property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setKey(String value) {
this.key = value;
@@ -423,10 +382,8 @@ public class QueryVnfNotification {
/**
* Gets the value of the value property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getValue() {
return value;
@@ -435,54 +392,44 @@ public class QueryVnfNotification {
/**
* Sets the value of the value property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setValue(String value) {
this.value = value;
}
-
+
// Not a generated method
public String toString() {
- String entry = "";
- entry =
- "<entry>"+ '\n' +
- " <key>"+key+"</key>" + '\n' +
- " <value>"+value+"</value>" + '\n' +
- "</entry>";
- return entry;
+ String entry = "";
+ entry = "<entry>" + '\n' + " <key>" + key + "</key>" + '\n' + " <value>" + value + "</value>" + '\n'
+ + "</entry>";
+ return entry;
}
}
}
-
- // Not a generated method
- public String toString() {
- String queryVnfNotification = "";
- if (exception==null) {
- queryVnfNotification = "<ns2:queryVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n' +
- " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' +
- " <messageId>"+messageId+"</messageId>" + '\n' +
- " <completed>"+completed+"</completed>" + '\n' +
- " <vnfExists>"+vnfExists+"</vnfExists>" + '\n' +
- " <vnfId>"+vnfId+"</vnfId>" + '\n' +
- " <status>"+status+"</status>" + '\n' +
- (outputs == null ? "" : outputs.toString() + '\n') +
- "</ns2:queryVnfNotification>";
- } else {
- queryVnfNotification = "<ns2:queryVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n' +
- " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' +
- " <messageId>"+messageId+"</messageId>" + '\n' +
- " <completed>"+completed+"</completed>" + '\n' +
- (outputs == null ? "" : outputs.toString() + '\n') +
- " <exception>"+exception+"</exception>" + '\n' +
- " <errorMessage>"+errorMessage+"</errorMessage>" + '\n' +
- "</ns2:queryVnfNotification>";
- }
- return queryVnfNotification;
- }
+
+ // Not a generated method
+ public String toString() {
+ String queryVnfNotification = "";
+ if (exception == null) {
+ queryVnfNotification = "<ns2:queryVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n'
+ + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' + " <messageId>"
+ + messageId + "</messageId>" + '\n' + " <completed>" + completed + "</completed>" + '\n'
+ + " <vnfExists>" + vnfExists + "</vnfExists>" + '\n' + " <vnfId>" + vnfId + "</vnfId>" + '\n'
+ + " <status>" + status + "</status>" + '\n' + (outputs == null ? "" : outputs.toString() + '\n')
+ + "</ns2:queryVnfNotification>";
+ } else {
+ queryVnfNotification = "<ns2:queryVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n'
+ + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' + " <messageId>"
+ + messageId + "</messageId>" + '\n' + " <completed>" + completed + "</completed>" + '\n'
+ + (outputs == null ? "" : outputs.toString() + '\n') + " <exception>" + exception + "</exception>"
+ + '\n' + " <errorMessage>" + errorMessage + "</errorMessage>" + '\n'
+ + "</ns2:queryVnfNotification>";
+ }
+ return queryVnfNotification;
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/RollbackVnfNotification.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/RollbackVnfNotification.java
index 6b143a2494..70e8199e95 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/RollbackVnfNotification.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/RollbackVnfNotification.java
@@ -27,9 +27,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for rollbackVnfNotification complex type.
+ * <p>
+ * Java class for rollbackVnfNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="rollbackVnfNotification">
@@ -49,12 +51,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "rollbackVnfNotification1", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage"
-})
+@XmlType(name = "rollbackVnfNotification1", propOrder = {"messageId", "completed", "exception", "errorMessage"})
public class RollbackVnfNotification {
@XmlElement(required = true)
@@ -66,10 +63,8 @@ public class RollbackVnfNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -78,10 +73,8 @@ public class RollbackVnfNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -106,10 +99,8 @@ public class RollbackVnfNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
- *
+ * @return possible object is {@link MsoExceptionCategory }
+ *
*/
public MsoExceptionCategory getException() {
return exception;
@@ -118,10 +109,8 @@ public class RollbackVnfNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
- *
+ * @param value allowed object is {@link MsoExceptionCategory }
+ *
*/
public void setException(MsoExceptionCategory value) {
this.exception = value;
@@ -130,10 +119,8 @@ public class RollbackVnfNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -142,34 +129,29 @@ public class RollbackVnfNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
}
-
+
public String toString() {
- String rollbackVnfNotification = "";
- if (exception==null) {
- rollbackVnfNotification = "<ns2:rollbackVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n' +
- " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' +
- " <messageId>"+messageId+"</messageId>" + '\n' +
- " <completed>"+completed+"</completed>" + '\n' +
- "</ns2:rollbackVnfNotification>";
- } else {
- rollbackVnfNotification = "<ns2:rollbackVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n' +
- " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' +
- " <messageId>"+messageId+"</messageId>" + '\n' +
- " <completed>"+completed+"</completed>" + '\n' +
- " <exception>"+exception+"</exception>" + '\n' +
- " <errorMessage>"+errorMessage+"</errorMessage>" + '\n' +
- "</ns2:rollbackVnfNotification>";
- }
- return rollbackVnfNotification;
+ String rollbackVnfNotification = "";
+ if (exception == null) {
+ rollbackVnfNotification = "<ns2:rollbackVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n'
+ + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' + " <messageId>"
+ + messageId + "</messageId>" + '\n' + " <completed>" + completed + "</completed>" + '\n'
+ + "</ns2:rollbackVnfNotification>";
+ } else {
+ rollbackVnfNotification = "<ns2:rollbackVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n'
+ + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' + " <messageId>"
+ + messageId + "</messageId>" + '\n' + " <completed>" + completed + "</completed>" + '\n'
+ + " <exception>" + exception + "</exception>" + '\n' + " <errorMessage>" + errorMessage
+ + "</errorMessage>" + '\n' + "</ns2:rollbackVnfNotification>";
+ }
+ return rollbackVnfNotification;
}
-
- }
+
+}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/UpdateVnfNotification.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/UpdateVnfNotification.java
index b89135b865..dd86f340a2 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/UpdateVnfNotification.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/UpdateVnfNotification.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.common.adapter.vnf;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -30,9 +29,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for updateVnfNotification complex type.
+ * <p>
+ * Java class for updateVnfNotification complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="updateVnfNotification">
@@ -75,14 +76,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "updateVnfNotification1", propOrder = {
- "messageId",
- "completed",
- "exception",
- "errorMessage",
- "outputs",
- "rollback"
-})
+@XmlType(name = "updateVnfNotification1",
+ propOrder = {"messageId", "completed", "exception", "errorMessage", "outputs", "rollback"})
public class UpdateVnfNotification {
@XmlElement(required = true)
@@ -96,9 +91,7 @@ public class UpdateVnfNotification {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getMessageId() {
@@ -108,9 +101,7 @@ public class UpdateVnfNotification {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setMessageId(String value) {
@@ -136,9 +127,7 @@ public class UpdateVnfNotification {
/**
* Gets the value of the exception property.
*
- * @return
- * possible object is
- * {@link MsoExceptionCategory }
+ * @return possible object is {@link MsoExceptionCategory }
*
*/
public MsoExceptionCategory getException() {
@@ -148,9 +137,7 @@ public class UpdateVnfNotification {
/**
* Sets the value of the exception property.
*
- * @param value
- * allowed object is
- * {@link MsoExceptionCategory }
+ * @param value allowed object is {@link MsoExceptionCategory }
*
*/
public void setException(MsoExceptionCategory value) {
@@ -160,9 +147,7 @@ public class UpdateVnfNotification {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getErrorMessage() {
@@ -172,9 +157,7 @@ public class UpdateVnfNotification {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setErrorMessage(String value) {
@@ -184,9 +167,7 @@ public class UpdateVnfNotification {
/**
* Gets the value of the outputs property.
*
- * @return
- * possible object is
- * {@link UpdateVnfNotification.Outputs }
+ * @return possible object is {@link UpdateVnfNotification.Outputs }
*
*/
public UpdateVnfNotification.Outputs getOutputs() {
@@ -196,9 +177,7 @@ public class UpdateVnfNotification {
/**
* Sets the value of the outputs property.
*
- * @param value
- * allowed object is
- * {@link UpdateVnfNotification.Outputs }
+ * @param value allowed object is {@link UpdateVnfNotification.Outputs }
*
*/
public void setOutputs(UpdateVnfNotification.Outputs value) {
@@ -208,9 +187,7 @@ public class UpdateVnfNotification {
/**
* Gets the value of the rollback property.
*
- * @return
- * possible object is
- * {@link VnfRollback }
+ * @return possible object is {@link VnfRollback }
*
*/
public VnfRollback getRollback() {
@@ -220,9 +197,7 @@ public class UpdateVnfNotification {
/**
* Sets the value of the rollback property.
*
- * @param value
- * allowed object is
- * {@link VnfRollback }
+ * @param value allowed object is {@link VnfRollback }
*
*/
public void setRollback(VnfRollback value) {
@@ -231,9 +206,11 @@ public class UpdateVnfNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -261,9 +238,7 @@ public class UpdateVnfNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "entry"
- })
+ @XmlType(name = "", propOrder = {"entry"})
public static class Outputs {
protected List<UpdateVnfNotification.Outputs.Entry> entry;
@@ -272,21 +247,20 @@ public class UpdateVnfNotification {
* Gets the value of the entry property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the entry property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you
+ * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE>
+ * method for the entry property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getEntry().add(newItem);
+ * getEntry().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link UpdateVnfNotification.Outputs.Entry }
+ * Objects of the following type(s) are allowed in the list {@link UpdateVnfNotification.Outputs.Entry }
*
*
*/
@@ -299,9 +273,11 @@ public class UpdateVnfNotification {
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -319,10 +295,7 @@ public class UpdateVnfNotification {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "key",
- "value"
- })
+ @XmlType(name = "", propOrder = {"key", "value"})
public static class Entry {
protected String key;
@@ -331,9 +304,7 @@ public class UpdateVnfNotification {
/**
* Gets the value of the key property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getKey() {
@@ -343,9 +314,7 @@ public class UpdateVnfNotification {
/**
* Sets the value of the key property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setKey(String value) {
@@ -355,9 +324,7 @@ public class UpdateVnfNotification {
/**
* Gets the value of the value property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getValue() {
@@ -367,9 +334,7 @@ public class UpdateVnfNotification {
/**
* Sets the value of the value property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setValue(String value) {
@@ -377,36 +342,30 @@ public class UpdateVnfNotification {
}
public String toString() {
- String entry = "";
- entry =
- " <key>"+key+"</key>" + '\n' +
- " <value>"+value+"</value>";
- return entry;
+ String entry = "";
+ entry = " <key>" + key + "</key>" + '\n' + " <value>" + value + "</value>";
+ return entry;
}
}
}
- public String toString(){
- String updateVnfNotification = "";
- if (exception==null) {
- updateVnfNotification = "<ns2:updateVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n' +
- " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' +
- " <messageId>"+messageId+"</messageId>" + '\n' +
- " <completed>"+completed+"</completed>" + '\n' +
- " <rollback>"+rollback+"</rollback>" + '\n' +
- "</ns2:updateVnfNotification>";
- } else {
- updateVnfNotification = "<ns2:updateVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n' +
- " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' +
- " <messageId>"+messageId+"</messageId>" + '\n' +
- " <completed>"+completed+"</completed>" + '\n' +
- " <exception>"+exception+"</exception>" + '\n' +
- " <errorMessage>"+errorMessage+"</errorMessage>" + '\n' +
- "</ns2:updateVnfNotification>";
- }
-
- return updateVnfNotification;
+ public String toString() {
+ String updateVnfNotification = "";
+ if (exception == null) {
+ updateVnfNotification = "<ns2:updateVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n'
+ + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' + " <messageId>"
+ + messageId + "</messageId>" + '\n' + " <completed>" + completed + "</completed>" + '\n'
+ + " <rollback>" + rollback + "</rollback>" + '\n' + "</ns2:updateVnfNotification>";
+ } else {
+ updateVnfNotification = "<ns2:updateVnfNotification xmlns:ns2=\"http://org.onap.so/vnfNotify\"" + '\n'
+ + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + '\n' + " <messageId>"
+ + messageId + "</messageId>" + '\n' + " <completed>" + completed + "</completed>" + '\n'
+ + " <exception>" + exception + "</exception>" + '\n' + " <errorMessage>" + errorMessage
+ + "</errorMessage>" + '\n' + "</ns2:updateVnfNotification>";
+ }
+
+ return updateVnfNotification;
}
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfAdapterNotify.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfAdapterNotify.java
index adedca9ac5..1390b82c50 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfAdapterNotify.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfAdapterNotify.java
@@ -30,15 +30,11 @@ import javax.xml.ws.RequestWrapper;
/**
- * This class was generated by the JAX-WS RI.
- * JAX-WS RI 2.2.8
- * Generated source version: 2.2
+ * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.8 Generated source version: 2.2
*
*/
@WebService(name = "vnfAdapterNotify", targetNamespace = "http://org.onap.so/vnfNotify")
-@XmlSeeAlso({
- ObjectFactory.class
-})
+@XmlSeeAlso({ObjectFactory.class})
public interface VnfAdapterNotify {
@@ -51,17 +47,13 @@ public interface VnfAdapterNotify {
*/
@WebMethod
@Oneway
- @RequestWrapper(localName = "rollbackVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.RollbackVnfNotification")
+ @RequestWrapper(localName = "rollbackVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.RollbackVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/rollbackVnfNotificationRequest")
- public void rollbackVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage);
+ public void rollbackVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage);
/**
*
@@ -76,25 +68,17 @@ public interface VnfAdapterNotify {
*/
@WebMethod
@Oneway
- @RequestWrapper(localName = "queryVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.QueryVnfNotification")
+ @RequestWrapper(localName = "queryVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.QueryVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/queryVnfNotificationRequest")
- public void queryVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "vnfExists", targetNamespace = "")
- Boolean vnfExists,
- @WebParam(name = "vnfId", targetNamespace = "")
- String vnfId,
- @WebParam(name = "status", targetNamespace = "")
- VnfStatus status,
- @WebParam(name = "outputs", targetNamespace = "")
- org.onap.so.bpmn.common.adapter.vnf.QueryVnfNotification.Outputs outputs);
+ public void queryVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "vnfExists", targetNamespace = "") Boolean vnfExists,
+ @WebParam(name = "vnfId", targetNamespace = "") String vnfId,
+ @WebParam(name = "status", targetNamespace = "") VnfStatus status, @WebParam(name = "outputs",
+ targetNamespace = "") org.onap.so.bpmn.common.adapter.vnf.QueryVnfNotification.Outputs outputs);
/**
*
@@ -108,23 +92,17 @@ public interface VnfAdapterNotify {
*/
@WebMethod
@Oneway
- @RequestWrapper(localName = "createVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.CreateVnfNotification")
+ @RequestWrapper(localName = "createVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.CreateVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/createVnfNotificationRequest")
- public void createVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "vnfId", targetNamespace = "")
- String vnfId,
- @WebParam(name = "outputs", targetNamespace = "")
- org.onap.so.bpmn.common.adapter.vnf.CreateVnfNotification.Outputs outputs,
- @WebParam(name = "rollback", targetNamespace = "")
- VnfRollback rollback);
+ public void createVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "vnfId", targetNamespace = "") String vnfId,
+ @WebParam(name = "outputs",
+ targetNamespace = "") org.onap.so.bpmn.common.adapter.vnf.CreateVnfNotification.Outputs outputs,
+ @WebParam(name = "rollback", targetNamespace = "") VnfRollback rollback);
/**
*
@@ -137,21 +115,16 @@ public interface VnfAdapterNotify {
*/
@WebMethod
@Oneway
- @RequestWrapper(localName = "updateVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.UpdateVnfNotification")
+ @RequestWrapper(localName = "updateVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.UpdateVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest")
- public void updateVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "outputs", targetNamespace = "")
- org.onap.so.bpmn.common.adapter.vnf.UpdateVnfNotification.Outputs outputs,
- @WebParam(name = "rollback", targetNamespace = "")
- VnfRollback rollback);
+ public void updateVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "outputs",
+ targetNamespace = "") org.onap.so.bpmn.common.adapter.vnf.UpdateVnfNotification.Outputs outputs,
+ @WebParam(name = "rollback", targetNamespace = "") VnfRollback rollback);
/**
*
@@ -162,16 +135,12 @@ public interface VnfAdapterNotify {
*/
@WebMethod
@Oneway
- @RequestWrapper(localName = "deleteVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.DeleteVnfNotification")
+ @RequestWrapper(localName = "deleteVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.DeleteVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/deleteVnfNotificationRequest")
- public void deleteVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage);
+ public void deleteVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage);
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfAdapterNotify_Service.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfAdapterNotify_Service.java
index 667545d855..531b6d572e 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfAdapterNotify_Service.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfAdapterNotify_Service.java
@@ -30,24 +30,24 @@ import javax.xml.ws.WebServiceFeature;
/**
- * This class was generated by the JAX-WS RI.
- * JAX-WS RI 2.2.8
- * Generated source version: 2.2
+ * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.8 Generated source version: 2.2
*
*/
-@WebServiceClient(name = "vnfAdapterNotify", targetNamespace = "http://org.onap.so/vnfNotify", wsdlLocation = "/VnfAdapterNotify.wsdl")
-public class VnfAdapterNotify_Service extends Service
-{
+@WebServiceClient(name = "vnfAdapterNotify", targetNamespace = "http://org.onap.so/vnfNotify",
+ wsdlLocation = "/VnfAdapterNotify.wsdl")
+public class VnfAdapterNotify_Service extends Service {
private final static URL VNFADAPTERNOTIFY_WSDL_LOCATION;
private final static WebServiceException VNFADAPTERNOTIFY_EXCEPTION;
private final static QName VNFADAPTERNOTIFY_QNAME = new QName("http://org.onap.so/vnfNotify", "vnfAdapterNotify");
static {
- VNFADAPTERNOTIFY_WSDL_LOCATION = org.onap.so.bpmn.common.adapter.vnf.VnfAdapterNotify_Service.class.getResource("/VnfAdapterNotify.wsdl");
+ VNFADAPTERNOTIFY_WSDL_LOCATION = org.onap.so.bpmn.common.adapter.vnf.VnfAdapterNotify_Service.class
+ .getResource("/VnfAdapterNotify.wsdl");
WebServiceException e = null;
if (VNFADAPTERNOTIFY_WSDL_LOCATION == null) {
- e = new WebServiceException("Cannot find '/VnfAdapterNotify.wsdl' wsdl. Place the resource correctly in the classpath.");
+ e = new WebServiceException(
+ "Cannot find '/VnfAdapterNotify.wsdl' wsdl. Place the resource correctly in the classpath.");
}
VNFADAPTERNOTIFY_EXCEPTION = e;
}
@@ -78,28 +78,28 @@ public class VnfAdapterNotify_Service extends Service
/**
*
- * @return
- * returns VnfAdapterNotify
+ * @return returns VnfAdapterNotify
*/
@WebEndpoint(name = "MsoVnfAdapterAsyncImplPort")
public VnfAdapterNotify getMsoVnfAdapterAsyncImplPort() {
- return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"), VnfAdapterNotify.class);
+ return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"),
+ VnfAdapterNotify.class);
}
/**
*
- * @param features
- * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
- * @return
- * returns VnfAdapterNotify
+ * @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features
+ * not in the <code>features</code> parameter will have their default values.
+ * @return returns VnfAdapterNotify
*/
@WebEndpoint(name = "MsoVnfAdapterAsyncImplPort")
public VnfAdapterNotify getMsoVnfAdapterAsyncImplPort(WebServiceFeature... features) {
- return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"), VnfAdapterNotify.class, features);
+ return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"),
+ VnfAdapterNotify.class, features);
}
private static URL __getWsdlLocation() {
- if (VNFADAPTERNOTIFY_EXCEPTION!= null) {
+ if (VNFADAPTERNOTIFY_EXCEPTION != null) {
throw VNFADAPTERNOTIFY_EXCEPTION;
}
return VNFADAPTERNOTIFY_WSDL_LOCATION;
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfRollback.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfRollback.java
index 9fd3bc596f..1e02c0d07c 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfRollback.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfRollback.java
@@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for vnfRollback complex type.
+ * <p>
+ * Java class for vnfRollback complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="vnfRollback">
@@ -51,15 +53,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "vnfRollback", propOrder = {
- "cloudSiteId",
- "cloudOwner",
- "msoRequest",
- "tenantCreated",
- "tenantId",
- "vnfCreated",
- "vnfId"
-})
+@XmlType(name = "vnfRollback",
+ propOrder = {"cloudSiteId", "cloudOwner", "msoRequest", "tenantCreated", "tenantId", "vnfCreated", "vnfId"})
public class VnfRollback {
protected String cloudSiteId;
@@ -73,10 +68,8 @@ public class VnfRollback {
/**
* Gets the value of the cloudSiteId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getCloudSiteId() {
return cloudSiteId;
@@ -85,10 +78,8 @@ public class VnfRollback {
/**
* Sets the value of the cloudSiteId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setCloudSiteId(String value) {
this.cloudSiteId = value;
@@ -97,10 +88,8 @@ public class VnfRollback {
/**
* Gets the value of the cloudOwner property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getCloudOwner() {
return cloudOwner;
@@ -109,10 +98,8 @@ public class VnfRollback {
/**
* Sets the value of the cloudOwner property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setCloudOwner(String value) {
this.cloudOwner = value;
@@ -121,10 +108,8 @@ public class VnfRollback {
/**
* Gets the value of the msoRequest property.
*
- * @return
- * possible object is
- * {@link MsoRequest }
- *
+ * @return possible object is {@link MsoRequest }
+ *
*/
public MsoRequest getMsoRequest() {
return msoRequest;
@@ -133,10 +118,8 @@ public class VnfRollback {
/**
* Sets the value of the msoRequest property.
*
- * @param value
- * allowed object is
- * {@link MsoRequest }
- *
+ * @param value allowed object is {@link MsoRequest }
+ *
*/
public void setMsoRequest(MsoRequest value) {
this.msoRequest = value;
@@ -161,10 +144,8 @@ public class VnfRollback {
/**
* Gets the value of the tenantId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getTenantId() {
return tenantId;
@@ -173,10 +154,8 @@ public class VnfRollback {
/**
* Sets the value of the tenantId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setTenantId(String value) {
this.tenantId = value;
@@ -201,10 +180,8 @@ public class VnfRollback {
/**
* Gets the value of the vnfId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfId() {
return vnfId;
@@ -213,26 +190,19 @@ public class VnfRollback {
/**
* Sets the value of the vnfId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfId(String value) {
this.vnfId = value;
}
-
+
public String toString() {
- String msoRequestElement = msoRequest == null ? ""
- : "<msoRequest>"+msoRequest+"</msoRequest>" + '\n';
-
- return
- "<cloudSiteId>"+cloudSiteId+"</cloudSiteId>" + '\n' +
- "<cloudOwner>"+cloudOwner+"</cloudOwner>" + '\n' +
- msoRequestElement +
- "<tenantCreated>"+tenantCreated+"</tenantCreated>" + '\n' +
- "<tenantId>"+tenantId+"</tenantId>" + '\n' +
- "<vnfCreated>"+vnfCreated+"</vnfCreated>" + '\n' +
- "<vnfId>"+vnfId+"</vnfId>";
+ String msoRequestElement = msoRequest == null ? "" : "<msoRequest>" + msoRequest + "</msoRequest>" + '\n';
+
+ return "<cloudSiteId>" + cloudSiteId + "</cloudSiteId>" + '\n' + "<cloudOwner>" + cloudOwner + "</cloudOwner>"
+ + '\n' + msoRequestElement + "<tenantCreated>" + tenantCreated + "</tenantCreated>" + '\n'
+ + "<tenantId>" + tenantId + "</tenantId>" + '\n' + "<vnfCreated>" + vnfCreated + "</vnfCreated>" + '\n'
+ + "<vnfId>" + vnfId + "</vnfId>";
}
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfStatus.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfStatus.java
index d093f79e03..007b5ab487 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfStatus.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/VnfStatus.java
@@ -25,10 +25,13 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for vnfStatus.
+ * <p>
+ * Java class for vnfStatus.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
* <p>
+ * The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ *
* <pre>
* &lt;simpleType name="vnfStatus">
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
@@ -45,10 +48,7 @@ import javax.xml.bind.annotation.XmlType;
@XmlEnum
public enum VnfStatus {
- ACTIVE,
- FAILED,
- NOTFOUND,
- UNKNOWN;
+ ACTIVE, FAILED, NOTFOUND, UNKNOWN;
public String value() {
return name();
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerService.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerService.java
index 46a6fa3ef3..7c0c2f20b3 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerService.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerService.java
@@ -26,7 +26,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.camunda.bpm.engine.MismatchingMessageCorrelationException;
import org.camunda.bpm.engine.OptimisticLockingException;
import org.camunda.bpm.engine.RuntimeService;
@@ -46,372 +45,354 @@ import org.springframework.stereotype.Service;
*/
@Service
public class CallbackHandlerService {
- public static final long DEFAULT_TIMEOUT_SECONDS = 60;
- public static final long FAST_POLL_DUR_SECONDS = 5;
- public static final long FAST_POLL_INT_MS = 100;
- public static final long SLOW_POLL_INT_MS = 1000;
-
- private static final Logger logger = LoggerFactory.getLogger(CallbackHandlerService.class);
-
- private RuntimeService runtimeService;
-
- @Autowired
- public CallbackHandlerService(RuntimeService runtimeService) {
- this.runtimeService = runtimeService;
- }
-
- /**
- * Parameterized callback handler.
- */
- @Async
- protected CallbackResult handleCallback(String method, Object message,
- String messageEventName, String messageVariable,
- String correlationVariable, String correlationValue,
- String logMarker) {
-
- return handleCallback(method, message, messageEventName, messageVariable,
- correlationVariable, correlationValue, logMarker, null);
- }
-
- /**
- * Parameterized callback handler.
- */
- protected CallbackResult handleCallback(String method, Object message,
- String messageEventName, String messageVariable,
- String correlationVariable, String correlationValue,
- String logMarker, Map<String, Object> injectedVariables) {
-
- long startTime = System.currentTimeMillis();
-
- logger.debug(logMarker + " " + method + " received message: "
- + (message == null ? "" : System.lineSeparator()) + message);
-
- try {
- Map<String, Object> variables = new HashMap<>();
-
- if (injectedVariables != null) {
- variables.putAll(injectedVariables);
- }
-
- variables.put(correlationVariable, correlationValue);
- variables.put(messageVariable, message == null ? null : message.toString());
-
- boolean ok = correlate(messageEventName, correlationVariable,
- correlationValue, variables, logMarker);
-
- if (!ok) {
- String msg = "No process is waiting for " + messageEventName
- + " with " + correlationVariable + " = '" + correlationValue + "'";
- logCallbackError(method, startTime, msg);
- return new CallbackError(msg);
- }
-
- logCallbackSuccess(method, startTime);
- return new CallbackSuccess();
- } catch (Exception e) {
- logger.debug("Exception :",e);
- String msg = "Caught " + e.getClass().getSimpleName()
- + " processing " + messageEventName + " with " + correlationVariable
- + " = '" + correlationValue + "'";
- logCallbackError(method, startTime, msg);
- return new CallbackError(msg);
- }
- }
-
- /**
- * Performs message correlation. Waits a limited amount of time for
- * a process to become ready for correlation. The return value indicates
- * whether or not a process was found to receive the message. Due to the
- * synchronous nature of message injection in Camunda, by the time this
- * method returns, one of 3 things will have happened: (1) the process
- * received the message and ended, (2) the process received the message
- * and reached an activity that suspended, or (3) an exception occurred
- * during correlation or while the process was executing. Correlation
- * exceptions are handled differently from process execution exceptions.
- * Correlation exceptions are thrown so the client knows something went
- * wrong with the delivery of the message. Process execution exceptions
- * are logged but not thrown.
- * @param messageEventName the message event name
- * @param correlationVariable the process variable used as the correlator
- * @param correlationValue the correlation value
- * @param variables variables to inject into the process
- * @param logMarker a marker for debug logging
- * @return true if a process could be found, false if not
- */
- protected boolean correlate(String messageEventName, String correlationVariable,
- String correlationValue, Map<String, Object> variables, String logMarker) {
- try{
- logger.debug(logMarker + " Attempting to find process waiting"
- + " for " + messageEventName + " with " + correlationVariable
- + " = '" + correlationValue + "'");
-
-
-
- long timeout = DEFAULT_TIMEOUT_SECONDS;
-
- // The code is here in case we ever need to change the default.
- String correlationTimemout = UrnPropertiesReader.getVariable("mso.correlation.timeout");
- if (correlationTimemout != null) {
- try {
- timeout = Long.parseLong(correlationTimemout);
- } catch (NumberFormatException e) {
- // Ignore
- }
- }
-
- long now = System.currentTimeMillis();
- long fastPollEndTime = now + (FAST_POLL_DUR_SECONDS * 1000);
- long endTime = now + (timeout * 1000);
- long sleep = FAST_POLL_INT_MS;
-
- List<Execution> waitingProcesses = null;
- Exception queryException = null;
- int queryCount = 0;
- int queryFailCount = 0;
-
- while (true) {
- try {
- ++queryCount;
- waitingProcesses = runtimeService.createExecutionQuery()
- .messageEventSubscriptionName(messageEventName)
- .processVariableValueEquals(correlationVariable, correlationValue)
- .list();
- } catch (Exception e) {
- ++queryFailCount;
- queryException = e;
- }
-
- if (waitingProcesses != null && waitingProcesses.size() > 0) {
- break;
- }
-
- if (now > endTime - sleep) {
- break;
- }
-
- Thread.sleep(sleep);
- now = System.currentTimeMillis();
-
- if (now > fastPollEndTime) {
- sleep = SLOW_POLL_INT_MS;
- }
- }
-
- if (waitingProcesses == null) {
- waitingProcesses = new ArrayList<Execution>(0);
- }
-
- int count = waitingProcesses.size();
-
- List<ExecInfo> execInfoList = new ArrayList<>(count);
- for (Execution execution : waitingProcesses) {
- execInfoList.add(new ExecInfo(execution));
- }
-
- logger.debug(logMarker + " Found " + count + " process(es) waiting"
- + " for " + messageEventName + " with " + correlationVariable
- + " = '" + correlationValue + "': " + execInfoList);
-
- if (count == 0) {
- if (queryFailCount > 0) {
- String msg = queryFailCount + "/" + queryCount
- + " execution queries failed attempting to correlate "
- + messageEventName + " with " + correlationVariable
- + " = '" + correlationValue + "'; last exception was:"
- + queryException;
- logger.debug(msg);
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
- ErrorCode.UnknownError.getValue(), msg, queryException);
- }
-
- return false;
- }
-
- if (count > 1) {
- // Only one process should be waiting. Throw an exception back to the client.
- throw new MismatchingMessageCorrelationException(messageEventName,
- "more than 1 process is waiting with " + correlationVariable
- + " = '" + correlationValue + "'");
- }
-
- // We prototyped an asynchronous solution, i.e. resuming the process
- // flow in a separate thread, but this affected too many existing tests,
- // and we went back to the synchronous solution. The synchronous solution
- // has some troublesome characteristics though. For example, the
- // resumed flow may send request #2 to a remote system before MSO has
- // acknowledged the notification associated with request #1.
-
- try {
- logger.debug(logMarker + " Running " + execInfoList.get(0) + " to receive "
- + messageEventName + " with " + correlationVariable + " = '"
- + correlationValue + "'");
-
- @SuppressWarnings("unused")
- MessageCorrelationResult result = runtimeService
- .createMessageCorrelation(messageEventName)
- .setVariables(variables)
- .processInstanceVariableEquals(correlationVariable, correlationValue)
- .correlateWithResult();
-
- } catch (MismatchingMessageCorrelationException e) {
- // A correlation exception occurred even after we identified
- // one waiting process. Throw it back to the client.
- throw e;
- } catch (OptimisticLockingException ole) {
-
- String msg = "Caught " + ole.getClass().getSimpleName() + " after receiving " + messageEventName
- + " with " + correlationVariable + " = '" + correlationValue
- + "': " + ole;
- logger.debug(msg);
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN CORRELATION ERROR -",
- ErrorCode.UnknownError.getValue(), msg, ole);
-
- //Retry for OptimisticLocking Exceptions
- int retryCount = 0;
- String retryStr = UrnPropertiesReader.getVariable("mso.bpmn.optimisticlockingexception.retrycount");
- if (retryStr != null) {
- try {
- retryCount = Integer.parseInt(retryStr);
- } catch (NumberFormatException e) {
- // Ignore
- }
- }
-
- logger.debug("Retry correlate for OptimisticLockingException, retryCount:{}", retryCount);
-
- for (; retryCount >0 ; retryCount--) {
-
- try{
- Thread.sleep(SLOW_POLL_INT_MS);
-
- @SuppressWarnings("unused")
- MessageCorrelationResult result = runtimeService
- .createMessageCorrelation(messageEventName)
- .setVariables(variables)
- .processInstanceVariableEquals(correlationVariable, correlationValue)
- .correlateWithResult();
- retryCount = 0;
- logger.debug("OptimisticLockingException retry was successful, seting retryCount: {}", retryCount);
- } catch (OptimisticLockingException olex) {
- //oleFlag = ex instanceof org.camunda.bpm.engine.OptimisticLockingException;
- String strMsg = "Received exception, OptimisticLockingException retry failed, retryCount:" + retryCount + " | exception returned: " + olex;
- logger.debug(strMsg);
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
- ErrorCode.UnknownError.getValue(), strMsg, olex);
- } catch (Exception excep) {
- retryCount = 0;
- //oleFlag = ex instanceof org.camunda.bpm.engine.OptimisticLockingException;
- String strMsg = "Received exception, OptimisticLockingException retry failed, retryCount:" + retryCount + " | exception returned: " + excep;
- logger.debug(strMsg);
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
- ErrorCode.UnknownError.getValue(), strMsg, excep);
- }
-
- }
-
- }catch (Exception e) {
- // This must be an exception from the flow itself. Log it, but don't
- // report it back to the client.
- String msg = "Caught " + e.getClass().getSimpleName() + " running "
- + execInfoList.get(0) + " after receiving " + messageEventName
- + " with " + correlationVariable + " = '" + correlationValue
- + "': " + e;
- logger.debug(msg);
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
- ErrorCode.UnknownError.getValue(), msg, e);
- }
- } catch (Exception e) {
- // This must be an exception from the flow itself. Log it, but don't
- // report it back to the client.
- String msg = "Caught " + e.getClass().getSimpleName() + " after receiving " + messageEventName
- + " with " + correlationVariable + " = '" + correlationValue
- + "': " + e;
- logger.debug(msg);
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN CORRELATION ERROR -",
- ErrorCode.UnknownError.getValue(), msg, e);
- }
-
- return true;
- }
-
- /**
- * Records audit and metric events in the log for a callback success.
- * @param method the method name
- * @param startTime the request start time
- */
- protected void logCallbackSuccess(String method, long startTime) {
- }
-
- /**
- * Records error, audit and metric events in the log for a callback
- * internal error.
- * @param method the method name
- * @param startTime the request start time
- * @param msg the error message
- */
- protected void logCallbackError(String method, long startTime, String msg) {
- logCallbackError(method, startTime, msg, null);
- }
-
- /**
- * Records error, audit and metric events in the log for a callback
- * internal error.
- * @param method the method name
- * @param startTime the request start time
- * @param msg the error message
- * @param e the exception
- */
- protected void logCallbackError(String method, long startTime, String msg, Exception e) {
- if (e == null) {
- logger.error("{} {} {} {}", MessageEnum.BPMN_CALLBACK_EXCEPTION.toString(), "BPMN",
- ErrorCode.UnknownError.getValue(), msg);
- } else {
- logger.error("{} {} {} {}", MessageEnum.BPMN_CALLBACK_EXCEPTION.toString(), "BPMN",
- ErrorCode.UnknownError.getValue(), msg, e);
- }
- }
-
- /**
- * Abstract callback result object.
- */
- protected abstract class CallbackResult {
- }
-
- /**
- * Indicates that callback handling was successful.
- */
- protected class CallbackSuccess extends CallbackResult {
- }
-
- /**
- * Indicates that callback handling failed.
- */
- protected class CallbackError extends CallbackResult {
- private final String errorMessage;
-
- public CallbackError(String errorMessage) {
- this.errorMessage = errorMessage;
- }
-
- /**
- * Gets the error message.
- */
- public String getErrorMessage() {
- return errorMessage;
- }
- }
-
- private static class ExecInfo {
- private final Execution execution;
-
- public ExecInfo(Execution execution) {
- this.execution = execution;
- }
-
- @Override
- public String toString() {
- return "Process[" + execution.getProcessInstanceId()
- + ":" + execution.getId() + "]";
- }
- }
+ public static final long DEFAULT_TIMEOUT_SECONDS = 60;
+ public static final long FAST_POLL_DUR_SECONDS = 5;
+ public static final long FAST_POLL_INT_MS = 100;
+ public static final long SLOW_POLL_INT_MS = 1000;
+
+ private static final Logger logger = LoggerFactory.getLogger(CallbackHandlerService.class);
+
+ private RuntimeService runtimeService;
+
+ @Autowired
+ public CallbackHandlerService(RuntimeService runtimeService) {
+ this.runtimeService = runtimeService;
+ }
+
+ /**
+ * Parameterized callback handler.
+ */
+ @Async
+ protected CallbackResult handleCallback(String method, Object message, String messageEventName,
+ String messageVariable, String correlationVariable, String correlationValue, String logMarker) {
+
+ return handleCallback(method, message, messageEventName, messageVariable, correlationVariable, correlationValue,
+ logMarker, null);
+ }
+
+ /**
+ * Parameterized callback handler.
+ */
+ protected CallbackResult handleCallback(String method, Object message, String messageEventName,
+ String messageVariable, String correlationVariable, String correlationValue, String logMarker,
+ Map<String, Object> injectedVariables) {
+
+ long startTime = System.currentTimeMillis();
+
+ logger.debug(logMarker + " " + method + " received message: " + (message == null ? "" : System.lineSeparator())
+ + message);
+
+ try {
+ Map<String, Object> variables = new HashMap<>();
+
+ if (injectedVariables != null) {
+ variables.putAll(injectedVariables);
+ }
+
+ variables.put(correlationVariable, correlationValue);
+ variables.put(messageVariable, message == null ? null : message.toString());
+
+ boolean ok = correlate(messageEventName, correlationVariable, correlationValue, variables, logMarker);
+
+ if (!ok) {
+ String msg = "No process is waiting for " + messageEventName + " with " + correlationVariable + " = '"
+ + correlationValue + "'";
+ logCallbackError(method, startTime, msg);
+ return new CallbackError(msg);
+ }
+
+ logCallbackSuccess(method, startTime);
+ return new CallbackSuccess();
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ String msg = "Caught " + e.getClass().getSimpleName() + " processing " + messageEventName + " with "
+ + correlationVariable + " = '" + correlationValue + "'";
+ logCallbackError(method, startTime, msg);
+ return new CallbackError(msg);
+ }
+ }
+
+ /**
+ * Performs message correlation. Waits a limited amount of time for a process to become ready for correlation. The
+ * return value indicates whether or not a process was found to receive the message. Due to the synchronous nature
+ * of message injection in Camunda, by the time this method returns, one of 3 things will have happened: (1) the
+ * process received the message and ended, (2) the process received the message and reached an activity that
+ * suspended, or (3) an exception occurred during correlation or while the process was executing. Correlation
+ * exceptions are handled differently from process execution exceptions. Correlation exceptions are thrown so the
+ * client knows something went wrong with the delivery of the message. Process execution exceptions are logged but
+ * not thrown.
+ *
+ * @param messageEventName the message event name
+ * @param correlationVariable the process variable used as the correlator
+ * @param correlationValue the correlation value
+ * @param variables variables to inject into the process
+ * @param logMarker a marker for debug logging
+ * @return true if a process could be found, false if not
+ */
+ protected boolean correlate(String messageEventName, String correlationVariable, String correlationValue,
+ Map<String, Object> variables, String logMarker) {
+ try {
+ logger.debug(logMarker + " Attempting to find process waiting" + " for " + messageEventName + " with "
+ + correlationVariable + " = '" + correlationValue + "'");
+
+
+
+ long timeout = DEFAULT_TIMEOUT_SECONDS;
+
+ // The code is here in case we ever need to change the default.
+ String correlationTimemout = UrnPropertiesReader.getVariable("mso.correlation.timeout");
+ if (correlationTimemout != null) {
+ try {
+ timeout = Long.parseLong(correlationTimemout);
+ } catch (NumberFormatException e) {
+ // Ignore
+ }
+ }
+
+ long now = System.currentTimeMillis();
+ long fastPollEndTime = now + (FAST_POLL_DUR_SECONDS * 1000);
+ long endTime = now + (timeout * 1000);
+ long sleep = FAST_POLL_INT_MS;
+
+ List<Execution> waitingProcesses = null;
+ Exception queryException = null;
+ int queryCount = 0;
+ int queryFailCount = 0;
+
+ while (true) {
+ try {
+ ++queryCount;
+ waitingProcesses =
+ runtimeService.createExecutionQuery().messageEventSubscriptionName(messageEventName)
+ .processVariableValueEquals(correlationVariable, correlationValue).list();
+ } catch (Exception e) {
+ ++queryFailCount;
+ queryException = e;
+ }
+
+ if (waitingProcesses != null && waitingProcesses.size() > 0) {
+ break;
+ }
+
+ if (now > endTime - sleep) {
+ break;
+ }
+
+ Thread.sleep(sleep);
+ now = System.currentTimeMillis();
+
+ if (now > fastPollEndTime) {
+ sleep = SLOW_POLL_INT_MS;
+ }
+ }
+
+ if (waitingProcesses == null) {
+ waitingProcesses = new ArrayList<Execution>(0);
+ }
+
+ int count = waitingProcesses.size();
+
+ List<ExecInfo> execInfoList = new ArrayList<>(count);
+ for (Execution execution : waitingProcesses) {
+ execInfoList.add(new ExecInfo(execution));
+ }
+
+ logger.debug(logMarker + " Found " + count + " process(es) waiting" + " for " + messageEventName + " with "
+ + correlationVariable + " = '" + correlationValue + "': " + execInfoList);
+
+ if (count == 0) {
+ if (queryFailCount > 0) {
+ String msg =
+ queryFailCount + "/" + queryCount + " execution queries failed attempting to correlate "
+ + messageEventName + " with " + correlationVariable + " = '" + correlationValue
+ + "'; last exception was:" + queryException;
+ logger.debug(msg);
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
+ ErrorCode.UnknownError.getValue(), msg, queryException);
+ }
+
+ return false;
+ }
+
+ if (count > 1) {
+ // Only one process should be waiting. Throw an exception back to the client.
+ throw new MismatchingMessageCorrelationException(messageEventName,
+ "more than 1 process is waiting with " + correlationVariable + " = '" + correlationValue + "'");
+ }
+
+ // We prototyped an asynchronous solution, i.e. resuming the process
+ // flow in a separate thread, but this affected too many existing tests,
+ // and we went back to the synchronous solution. The synchronous solution
+ // has some troublesome characteristics though. For example, the
+ // resumed flow may send request #2 to a remote system before MSO has
+ // acknowledged the notification associated with request #1.
+
+ try {
+ logger.debug(logMarker + " Running " + execInfoList.get(0) + " to receive " + messageEventName
+ + " with " + correlationVariable + " = '" + correlationValue + "'");
+
+ @SuppressWarnings("unused")
+ MessageCorrelationResult result = runtimeService.createMessageCorrelation(messageEventName)
+ .setVariables(variables).processInstanceVariableEquals(correlationVariable, correlationValue)
+ .correlateWithResult();
+
+ } catch (MismatchingMessageCorrelationException e) {
+ // A correlation exception occurred even after we identified
+ // one waiting process. Throw it back to the client.
+ throw e;
+ } catch (OptimisticLockingException ole) {
+
+ String msg = "Caught " + ole.getClass().getSimpleName() + " after receiving " + messageEventName
+ + " with " + correlationVariable + " = '" + correlationValue + "': " + ole;
+ logger.debug(msg);
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN CORRELATION ERROR -",
+ ErrorCode.UnknownError.getValue(), msg, ole);
+
+ // Retry for OptimisticLocking Exceptions
+ int retryCount = 0;
+ String retryStr = UrnPropertiesReader.getVariable("mso.bpmn.optimisticlockingexception.retrycount");
+ if (retryStr != null) {
+ try {
+ retryCount = Integer.parseInt(retryStr);
+ } catch (NumberFormatException e) {
+ // Ignore
+ }
+ }
+
+ logger.debug("Retry correlate for OptimisticLockingException, retryCount:{}", retryCount);
+
+ for (; retryCount > 0; retryCount--) {
+
+ try {
+ Thread.sleep(SLOW_POLL_INT_MS);
+
+ @SuppressWarnings("unused")
+ MessageCorrelationResult result =
+ runtimeService.createMessageCorrelation(messageEventName).setVariables(variables)
+ .processInstanceVariableEquals(correlationVariable, correlationValue)
+ .correlateWithResult();
+ retryCount = 0;
+ logger.debug("OptimisticLockingException retry was successful, seting retryCount: {}",
+ retryCount);
+ } catch (OptimisticLockingException olex) {
+ // oleFlag = ex instanceof org.camunda.bpm.engine.OptimisticLockingException;
+ String strMsg = "Received exception, OptimisticLockingException retry failed, retryCount:"
+ + retryCount + " | exception returned: " + olex;
+ logger.debug(strMsg);
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
+ ErrorCode.UnknownError.getValue(), strMsg, olex);
+ } catch (Exception excep) {
+ retryCount = 0;
+ // oleFlag = ex instanceof org.camunda.bpm.engine.OptimisticLockingException;
+ String strMsg = "Received exception, OptimisticLockingException retry failed, retryCount:"
+ + retryCount + " | exception returned: " + excep;
+ logger.debug(strMsg);
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
+ ErrorCode.UnknownError.getValue(), strMsg, excep);
+ }
+
+ }
+
+ } catch (Exception e) {
+ // This must be an exception from the flow itself. Log it, but don't
+ // report it back to the client.
+ String msg = "Caught " + e.getClass().getSimpleName() + " running " + execInfoList.get(0)
+ + " after receiving " + messageEventName + " with " + correlationVariable + " = '"
+ + correlationValue + "': " + e;
+ logger.debug(msg);
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
+ ErrorCode.UnknownError.getValue(), msg, e);
+ }
+ } catch (Exception e) {
+ // This must be an exception from the flow itself. Log it, but don't
+ // report it back to the client.
+ String msg = "Caught " + e.getClass().getSimpleName() + " after receiving " + messageEventName + " with "
+ + correlationVariable + " = '" + correlationValue + "': " + e;
+ logger.debug(msg);
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN CORRELATION ERROR -",
+ ErrorCode.UnknownError.getValue(), msg, e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Records audit and metric events in the log for a callback success.
+ *
+ * @param method the method name
+ * @param startTime the request start time
+ */
+ protected void logCallbackSuccess(String method, long startTime) {}
+
+ /**
+ * Records error, audit and metric events in the log for a callback internal error.
+ *
+ * @param method the method name
+ * @param startTime the request start time
+ * @param msg the error message
+ */
+ protected void logCallbackError(String method, long startTime, String msg) {
+ logCallbackError(method, startTime, msg, null);
+ }
+
+ /**
+ * Records error, audit and metric events in the log for a callback internal error.
+ *
+ * @param method the method name
+ * @param startTime the request start time
+ * @param msg the error message
+ * @param e the exception
+ */
+ protected void logCallbackError(String method, long startTime, String msg, Exception e) {
+ if (e == null) {
+ logger.error("{} {} {} {}", MessageEnum.BPMN_CALLBACK_EXCEPTION.toString(), "BPMN",
+ ErrorCode.UnknownError.getValue(), msg);
+ } else {
+ logger.error("{} {} {} {}", MessageEnum.BPMN_CALLBACK_EXCEPTION.toString(), "BPMN",
+ ErrorCode.UnknownError.getValue(), msg, e);
+ }
+ }
+
+ /**
+ * Abstract callback result object.
+ */
+ protected abstract class CallbackResult {
+ }
+
+ /**
+ * Indicates that callback handling was successful.
+ */
+ protected class CallbackSuccess extends CallbackResult {
+ }
+
+ /**
+ * Indicates that callback handling failed.
+ */
+ protected class CallbackError extends CallbackResult {
+ private final String errorMessage;
+
+ public CallbackError(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ /**
+ * Gets the error message.
+ */
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+ }
+
+ private static class ExecInfo {
+ private final Execution execution;
+
+ public ExecInfo(Execution execution) {
+ this.execution = execution;
+ }
+
+ @Override
+ public String toString() {
+ return "Process[" + execution.getProcessInstanceId() + ":" + execution.getId() + "]";
+ }
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/ProcessEngineAwareService.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/ProcessEngineAwareService.java
index 8ceb1c1277..1134bc052b 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/ProcessEngineAwareService.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/ProcessEngineAwareService.java
@@ -22,45 +22,45 @@
package org.onap.so.bpmn.common.workflow.service;
import java.util.Optional;
-
import org.camunda.bpm.engine.ProcessEngineServices;
import org.camunda.bpm.engine.ProcessEngines;
import org.springframework.stereotype.Service;
/**
- * Base class for services that must be process-engine aware. The only
- * process engine currently supported is the "default" process engine.
+ * Base class for services that must be process-engine aware. The only process engine currently supported is the
+ * "default" process engine.
*/
@Service
public class ProcessEngineAwareService {
-
- private final String processEngineName = "default";
- private volatile Optional<ProcessEngineServices> pes4junit = Optional.empty();
-
- /**
- * Gets the process engine name.
- * @return the process engine name
- */
- public String getProcessEngineName() {
- return processEngineName;
- }
- /**
- * Gets process engine services.
- * @return process engine services
- */
- public ProcessEngineServices getProcessEngineServices() {
- return pes4junit.orElse(ProcessEngines.getProcessEngine(
- getProcessEngineName()));
- }
+ private final String processEngineName = "default";
+ private volatile Optional<ProcessEngineServices> pes4junit = Optional.empty();
+
+ /**
+ * Gets the process engine name.
+ *
+ * @return the process engine name
+ */
+ public String getProcessEngineName() {
+ return processEngineName;
+ }
+
+ /**
+ * Gets process engine services.
+ *
+ * @return process engine services
+ */
+ public ProcessEngineServices getProcessEngineServices() {
+ return pes4junit.orElse(ProcessEngines.getProcessEngine(getProcessEngineName()));
+ }
- /**
- * Allows a particular process engine to be specified, overriding the
- * usual process engine lookup by name. Intended primarily for the
- * unit test environment.
- * @param pes process engine services
- */
- public void setProcessEngineServices4junit(ProcessEngineServices pes) {
- pes4junit = Optional.ofNullable(pes);
- }
+ /**
+ * Allows a particular process engine to be specified, overriding the usual process engine lookup by name. Intended
+ * primarily for the unit test environment.
+ *
+ * @param pes process engine services
+ */
+ public void setProcessEngineServices4junit(ProcessEngineServices pes) {
+ pes4junit = Optional.ofNullable(pes);
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java
index a74bdfc649..b81506ead9 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java
@@ -28,7 +28,6 @@ import javax.jws.WebResult;
import javax.jws.WebService;
import javax.ws.rs.core.Context;
import javax.xml.ws.WebServiceContext;
-
import org.onap.so.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest;
import org.onap.so.bpmn.common.adapter.sdnc.SDNCAdapterResponse;
import org.onap.so.bpmn.common.adapter.sdnc.SDNCCallbackAdapterPortType;
@@ -40,50 +39,53 @@ import org.springframework.stereotype.Service;
/**
* Implementation of SDNCAdapterCallbackService.
*/
-@WebService(serviceName="SDNCAdapterCallbackService", targetNamespace="http://org.onap/workflow/sdnc/adapter/schema/v1")
+@WebService(serviceName = "SDNCAdapterCallbackService",
+ targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1")
@Service
public class SDNCAdapterCallbackServiceImpl extends ProcessEngineAwareService implements SDNCCallbackAdapterPortType {
- private final static String logMarker = "[SDNC-CALLBACK]";
+ private final static String logMarker = "[SDNC-CALLBACK]";
+
+ @Context
+ WebServiceContext wsContext;
- @Context WebServiceContext wsContext;
-
- @Autowired
- CallbackHandlerService callback;
+ @Autowired
+ CallbackHandlerService callback;
- @WebMethod(operationName = "SDNCAdapterCallback")
- @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackResponse")
- public SDNCAdapterResponse sdncAdapterCallback(
- @WebParam(name = "SDNCAdapterCallbackRequest", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackRequest")
- SDNCAdapterCallbackRequest sdncAdapterCallbackRequest) {
+ @WebMethod(operationName = "SDNCAdapterCallback")
+ @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1",
+ partName = "SDNCAdapterCallbackResponse")
+ public SDNCAdapterResponse sdncAdapterCallback(@WebParam(name = "SDNCAdapterCallbackRequest",
+ targetNamespace = "http://org.onap/workflow/sdnc/adapter/schema/v1",
+ partName = "SDNCAdapterCallbackRequest") SDNCAdapterCallbackRequest sdncAdapterCallbackRequest) {
- String method = "sdncAdapterCallback";
- Object message = sdncAdapterCallbackRequest;
- String messageEventName = "sdncAdapterCallbackRequest";
- String messageVariable = "sdncAdapterCallbackRequest";
- String correlationVariable = "SDNCA_requestId";
- String correlationValue = sdncAdapterCallbackRequest.getCallbackHeader().getRequestId();
+ String method = "sdncAdapterCallback";
+ Object message = sdncAdapterCallbackRequest;
+ String messageEventName = "sdncAdapterCallbackRequest";
+ String messageVariable = "sdncAdapterCallbackRequest";
+ String correlationVariable = "SDNCA_requestId";
+ String correlationValue = sdncAdapterCallbackRequest.getCallbackHeader().getRequestId();
- CallbackResult result = callback.handleCallback(method, message, messageEventName,
- messageVariable, correlationVariable, correlationValue, logMarker);
+ CallbackResult result = callback.handleCallback(method, message, messageEventName, messageVariable,
+ correlationVariable, correlationValue, logMarker);
- if (result instanceof CallbackError) {
- return new SDNCAdapterErrorResponse(((CallbackError)result).getErrorMessage());
- } else {
- return new SDNCAdapterResponse();
- }
- }
+ if (result instanceof CallbackError) {
+ return new SDNCAdapterErrorResponse(((CallbackError) result).getErrorMessage());
+ } else {
+ return new SDNCAdapterResponse();
+ }
+ }
- // This subclass allows unit tests to extract the error
- public class SDNCAdapterErrorResponse extends SDNCAdapterResponse {
- private String error;
+ // This subclass allows unit tests to extract the error
+ public class SDNCAdapterErrorResponse extends SDNCAdapterResponse {
+ private String error;
- public SDNCAdapterErrorResponse(String error) {
- this.error = error;
- }
+ public SDNCAdapterErrorResponse(String error) {
+ this.error = error;
+ }
- public String getError() {
- return error;
- }
- }
+ public String getError() {
+ return error;
+ }
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/VnfAdapterNotifyServiceImpl.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/VnfAdapterNotifyServiceImpl.java
index ed524c115e..5f70ab5924 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/VnfAdapterNotifyServiceImpl.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/VnfAdapterNotifyServiceImpl.java
@@ -30,7 +30,6 @@ import javax.ws.rs.core.Context;
import javax.xml.ws.Action;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.WebServiceContext;
-
import org.onap.so.bpmn.common.adapter.vnf.CreateVnfNotification;
import org.onap.so.bpmn.common.adapter.vnf.DeleteVnfNotification;
import org.onap.so.bpmn.common.adapter.vnf.MsoExceptionCategory;
@@ -48,195 +47,167 @@ import org.springframework.stereotype.Service;
*/
@WebService(serviceName = "vnfAdapterNotify", targetNamespace = "http://org.onap.so/vnfNotify")
@Service
-public class VnfAdapterNotifyServiceImpl extends ProcessEngineAwareService implements VnfAdapterNotify{
+public class VnfAdapterNotifyServiceImpl extends ProcessEngineAwareService implements VnfAdapterNotify {
+
+ private final String logMarker = "[VNF-NOTIFY]";
- private final String logMarker = "[VNF-NOTIFY]";
-
- @Autowired
- CallbackHandlerService callback;
+ @Autowired
+ CallbackHandlerService callback;
- @Context WebServiceContext wsContext;
+ @Context
+ WebServiceContext wsContext;
@WebMethod(operationName = "rollbackVnfNotification")
@Oneway
- @RequestWrapper(localName = "rollbackVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.RollbackVnfNotification")
+ @RequestWrapper(localName = "rollbackVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.RollbackVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/rollbackVnfNotificationRequest")
- public void rollbackVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage) {
-
- RollbackVnfNotification rollbackVnfNotification = new RollbackVnfNotification();
-
- rollbackVnfNotification.setMessageId(messageId);
- rollbackVnfNotification.setCompleted(completed);
- rollbackVnfNotification.setException(exception);
- rollbackVnfNotification.setErrorMessage(errorMessage);
-
- String method = "rollbackVnfNotification";
- Object message = rollbackVnfNotification;
- String messageEventName = "rollbackVnfNotificationCallback";
- String messageVariable = "rollbackVnfNotificationCallback";
- String correlationVariable = "VNFRB_messageId";
- String correlationValue = messageId;
-
- callback.handleCallback(method, message, messageEventName, messageVariable,
- correlationVariable, correlationValue, logMarker);
+ public void rollbackVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage) {
+
+ RollbackVnfNotification rollbackVnfNotification = new RollbackVnfNotification();
+
+ rollbackVnfNotification.setMessageId(messageId);
+ rollbackVnfNotification.setCompleted(completed);
+ rollbackVnfNotification.setException(exception);
+ rollbackVnfNotification.setErrorMessage(errorMessage);
+
+ String method = "rollbackVnfNotification";
+ Object message = rollbackVnfNotification;
+ String messageEventName = "rollbackVnfNotificationCallback";
+ String messageVariable = "rollbackVnfNotificationCallback";
+ String correlationVariable = "VNFRB_messageId";
+ String correlationValue = messageId;
+
+ callback.handleCallback(method, message, messageEventName, messageVariable, correlationVariable,
+ correlationValue, logMarker);
}
@WebMethod(operationName = "queryVnfNotification")
@Oneway
- @RequestWrapper(localName = "queryVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.QueryVnfNotification")
+ @RequestWrapper(localName = "queryVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.QueryVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/queryVnfNotificationRequest")
- public void queryVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "vnfExists", targetNamespace = "")
- Boolean vnfExists,
- @WebParam(name = "vnfId", targetNamespace = "")
- String vnfId,
- @WebParam(name = "status", targetNamespace = "")
- VnfStatus status,
- @WebParam(name = "outputs", targetNamespace = "")
- QueryVnfNotification.Outputs outputs){
-
- String method = "queryVnfNotification";
- String messageEventName = "queryVnfNotificationCallback";
- String messageVariable = "queryVnfNotificationCallback";
- String correlationVariable = "VNFQ_messageId";
- String correlationValue = messageId;
-
- QueryVnfNotification message = new QueryVnfNotification();
-
- message.setMessageId(messageId);
- message.setCompleted(completed);
- message.setException(exception);
- message.setErrorMessage(errorMessage);
- message.setVnfExists(vnfExists);
- message.setVnfId(vnfId);
- message.setStatus(status);
- message.setOutputs(outputs);
-
- callback.handleCallback(method, message, messageEventName, messageVariable,
- correlationVariable, correlationValue, logMarker);
+ public void queryVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "vnfExists", targetNamespace = "") Boolean vnfExists,
+ @WebParam(name = "vnfId", targetNamespace = "") String vnfId,
+ @WebParam(name = "status", targetNamespace = "") VnfStatus status,
+ @WebParam(name = "outputs", targetNamespace = "") QueryVnfNotification.Outputs outputs) {
+
+ String method = "queryVnfNotification";
+ String messageEventName = "queryVnfNotificationCallback";
+ String messageVariable = "queryVnfNotificationCallback";
+ String correlationVariable = "VNFQ_messageId";
+ String correlationValue = messageId;
+
+ QueryVnfNotification message = new QueryVnfNotification();
+
+ message.setMessageId(messageId);
+ message.setCompleted(completed);
+ message.setException(exception);
+ message.setErrorMessage(errorMessage);
+ message.setVnfExists(vnfExists);
+ message.setVnfId(vnfId);
+ message.setStatus(status);
+ message.setOutputs(outputs);
+
+ callback.handleCallback(method, message, messageEventName, messageVariable, correlationVariable,
+ correlationValue, logMarker);
}
- @WebMethod(operationName = "createVnfNotification")
+ @WebMethod(operationName = "createVnfNotification")
@Oneway
- @RequestWrapper(localName = "createVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.CreateVnfNotification")
+ @RequestWrapper(localName = "createVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.CreateVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/createVnfNotificationRequest")
- public void createVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "vnfId", targetNamespace = "")
- String vnfId,
- @WebParam(name = "outputs", targetNamespace = "")
- CreateVnfNotification.Outputs outputs,
- @WebParam(name = "rollback", targetNamespace = "")
- VnfRollback rollback){
-
- String method = "createVnfNotification";
- String messageEventName = "createVnfNotificationCallback";
- String messageVariable = "createVnfNotificationCallback";
- String correlationVariable = "VNFC_messageId";
- String correlationValue = messageId;
-
- CreateVnfNotification message = new CreateVnfNotification();
-
- message.setMessageId(messageId);
- message.setCompleted(completed);
- message.setException(exception);
- message.setErrorMessage(errorMessage);
- message.setVnfId(vnfId);
- message.setOutputs(outputs);
- message.setRollback(rollback);
-
- callback.handleCallback(method, message, messageEventName, messageVariable,
- correlationVariable, correlationValue, logMarker);
- }
-
- @WebMethod(operationName = "updateVnfNotification")
+ public void createVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "vnfId", targetNamespace = "") String vnfId,
+ @WebParam(name = "outputs", targetNamespace = "") CreateVnfNotification.Outputs outputs,
+ @WebParam(name = "rollback", targetNamespace = "") VnfRollback rollback) {
+
+ String method = "createVnfNotification";
+ String messageEventName = "createVnfNotificationCallback";
+ String messageVariable = "createVnfNotificationCallback";
+ String correlationVariable = "VNFC_messageId";
+ String correlationValue = messageId;
+
+ CreateVnfNotification message = new CreateVnfNotification();
+
+ message.setMessageId(messageId);
+ message.setCompleted(completed);
+ message.setException(exception);
+ message.setErrorMessage(errorMessage);
+ message.setVnfId(vnfId);
+ message.setOutputs(outputs);
+ message.setRollback(rollback);
+
+ callback.handleCallback(method, message, messageEventName, messageVariable, correlationVariable,
+ correlationValue, logMarker);
+ }
+
+ @WebMethod(operationName = "updateVnfNotification")
@Oneway
- @RequestWrapper(localName = "updateVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.UpdateVnfNotification")
+ @RequestWrapper(localName = "updateVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.UpdateVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest")
- public void updateVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage,
- @WebParam(name = "outputs", targetNamespace = "")
- UpdateVnfNotification.Outputs outputs,
- @WebParam(name = "rollback", targetNamespace = "")
- VnfRollback rollback){
-
- String method = "updateVnfNotification";
- String messageEventName = "updateVnfNotificationCallback";
- String messageVariable = "updateVnfNotificationCallback";
- String correlationVariable = "VNFU_messageId";
- String correlationValue = messageId;
-
- UpdateVnfNotification message = new UpdateVnfNotification();
-
- message.setMessageId(messageId);
- message.setCompleted(completed);
- message.setException(exception);
- message.setErrorMessage(errorMessage);
- message.setOutputs(outputs);
- message.setRollback(rollback);
-
- callback.handleCallback(method, message, messageEventName, messageVariable,
- correlationVariable, correlationValue, logMarker);
- }
+ public void updateVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage,
+ @WebParam(name = "outputs", targetNamespace = "") UpdateVnfNotification.Outputs outputs,
+ @WebParam(name = "rollback", targetNamespace = "") VnfRollback rollback) {
+
+ String method = "updateVnfNotification";
+ String messageEventName = "updateVnfNotificationCallback";
+ String messageVariable = "updateVnfNotificationCallback";
+ String correlationVariable = "VNFU_messageId";
+ String correlationValue = messageId;
+
+ UpdateVnfNotification message = new UpdateVnfNotification();
+
+ message.setMessageId(messageId);
+ message.setCompleted(completed);
+ message.setException(exception);
+ message.setErrorMessage(errorMessage);
+ message.setOutputs(outputs);
+ message.setRollback(rollback);
+
+ callback.handleCallback(method, message, messageEventName, messageVariable, correlationVariable,
+ correlationValue, logMarker);
+ }
@WebMethod(operationName = "deleteVnfNotification")
@Oneway
- @RequestWrapper(localName = "deleteVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.DeleteVnfNotification")
+ @RequestWrapper(localName = "deleteVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify",
+ className = "org.onap.so.adapters.vnf.async.client.DeleteVnfNotification")
@Action(input = "http://org.onap.so/notify/adapterNotify/deleteVnfNotificationRequest")
- public void deleteVnfNotification(
- @WebParam(name = "messageId", targetNamespace = "")
- String messageId,
- @WebParam(name = "completed", targetNamespace = "")
- boolean completed,
- @WebParam(name = "exception", targetNamespace = "")
- MsoExceptionCategory exception,
- @WebParam(name = "errorMessage", targetNamespace = "")
- String errorMessage) {
-
- String method = "deleteVnfNotification";
- String messageEventName = "deleteVnfACallback";
- String messageVariable = "deleteVnfACallback";
- String correlationVariable = "VNFDEL_uuid";
- String correlationValue = messageId;
-
- DeleteVnfNotification message = new DeleteVnfNotification();
-
- message.setMessageId(messageId);
- message.setCompleted(completed);
- message.setException(exception);
- message.setErrorMessage(errorMessage);
-
- callback.handleCallback(method, message, messageEventName, messageVariable,
- correlationVariable, correlationValue, logMarker);
- }
+ public void deleteVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId,
+ @WebParam(name = "completed", targetNamespace = "") boolean completed,
+ @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception,
+ @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage) {
+
+ String method = "deleteVnfNotification";
+ String messageEventName = "deleteVnfACallback";
+ String messageVariable = "deleteVnfACallback";
+ String correlationVariable = "VNFDEL_uuid";
+ String correlationValue = messageId;
+
+ DeleteVnfNotification message = new DeleteVnfNotification();
+
+ message.setMessageId(messageId);
+ message.setCompleted(completed);
+ message.setException(exception);
+ message.setErrorMessage(errorMessage);
+
+ callback.handleCallback(method, message, messageEventName, messageVariable, correlationVariable,
+ correlationValue, logMarker);
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java
index a9a3a63f2f..a534e57b3a 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java
@@ -26,8 +26,8 @@ import org.camunda.bpm.engine.ProcessEngines;
public class WorkflowAsyncCommonResource extends WorkflowAsyncResource {
- @Override
+ @Override
public String getProcessEngineName() {
- return "default";
- }
+ return "default";
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncResource.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncResource.java
index f9f06447a7..e8e4b85cae 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncResource.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncResource.java
@@ -26,7 +26,6 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
-
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@@ -34,7 +33,6 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
-
import org.camunda.bpm.engine.ProcessEngineServices;
import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
@@ -47,20 +45,19 @@ import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
*
- * @version 1.0
- * Asynchronous Workflow processing using JAX RS RESTeasy implementation
- * Both Synchronous and Asynchronous BPMN process can benefit from this implementation since the workflow gets executed in the background
- * and the server thread is freed up, server scales better to process more incoming requests
+ * @version 1.0 Asynchronous Workflow processing using JAX RS RESTeasy implementation Both Synchronous and Asynchronous
+ * BPMN process can benefit from this implementation since the workflow gets executed in the background and the
+ * server thread is freed up, server scales better to process more incoming requests
*
- * Usage: For synchronous process, when you are ready to send the response invoke the callback to write the response
- * For asynchronous process - the activity may send a acknowledgement response and then proceed further on executing the process
+ * Usage: For synchronous process, when you are ready to send the response invoke the callback to write the
+ * response For asynchronous process - the activity may send a acknowledgement response and then proceed
+ * further on executing the process
*/
@Path("/async")
@Api(value = "/async", description = "Provides asynchronous starting of a bpmn process")
@@ -68,81 +65,79 @@ import io.swagger.annotations.ApiOperation;
@Component
public class WorkflowAsyncResource extends ProcessEngineAwareService {
- private static final WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();
-
- long workflowPollInterval=1000;
-
- @Autowired
- private WorkflowProcessor processor;
-
- @Autowired
- private WorkflowContextHolder workflowContext;
-
- public void setProcessor(WorkflowProcessor processor) {
- this.processor = processor;
- }
-
- protected static final Logger logger = LoggerFactory.getLogger(WorkflowAsyncResource.class);
- protected static final long DEFAULT_WAIT_TIME = 60000; //default wait time
-
- /**
- * Asynchronous JAX-RS method that starts a process instance.
- * @param processKey the process key
- * @param variableMap input variables to the process
- * @return
- */
-
- @POST
- @Path("/services/{processKey}")
- @ApiOperation(
- value = "Starts a new process with the appropriate process Key",
- notes = "Aysnc fall outs are only logged"
- )
- @Produces("application/json")
- @Consumes("application/json")
- public Response startProcessInstanceByKey (
- @PathParam("processKey") String processKey, VariableMapImpl variableMap){
- Map<String, Object> inputVariables = getInputVariables(variableMap);
- try {
- MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, getRequestId(inputVariables));
- processor.startProcess(processKey, variableMap);
- WorkflowResponse response = waitForResponse(getRequestId(inputVariables));
- return Response.status(202).entity(response).build();
- } catch (WorkflowProcessorException e) {
- WorkflowResponse response = e.getWorkflowResponse();
- return Response.status(500).entity(response).build();
- }catch (Exception e) {
- WorkflowResponse response = buildUnkownError(getRequestId(inputVariables),e.getMessage());
- return Response.status(500).entity(response).build();
- }
- }
-
- private WorkflowResponse waitForResponse(String requestId) throws Exception {
- long currentWaitTime = 0;
- while (DEFAULT_WAIT_TIME > currentWaitTime ) {
- Thread.sleep(workflowPollInterval);
- currentWaitTime = currentWaitTime + workflowPollInterval;
- WorkflowContext foundContext = contextHolder.getWorkflowContext(requestId);
- if(foundContext!=null){
- contextHolder.remove(foundContext);
- return buildResponse(foundContext);
- }
- }
- throw new Exception("TimeOutOccured");
- }
-
- private WorkflowResponse buildUnkownError(String requestId,String error) {
- WorkflowResponse response = new WorkflowResponse();
- response.setMessage(error);
- response.setResponse("UnknownError, request id:" + requestId);
- response.setMessageCode(500);
- return response;
- }
-
- private WorkflowResponse buildResponse(WorkflowContext foundContext) {
- return foundContext.getWorkflowResponse();
- }
-
+ private static final WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();
+
+ long workflowPollInterval = 1000;
+
+ @Autowired
+ private WorkflowProcessor processor;
+
+ @Autowired
+ private WorkflowContextHolder workflowContext;
+
+ public void setProcessor(WorkflowProcessor processor) {
+ this.processor = processor;
+ }
+
+ protected static final Logger logger = LoggerFactory.getLogger(WorkflowAsyncResource.class);
+ protected static final long DEFAULT_WAIT_TIME = 60000; // default wait time
+
+ /**
+ * Asynchronous JAX-RS method that starts a process instance.
+ *
+ * @param processKey the process key
+ * @param variableMap input variables to the process
+ * @return
+ */
+
+ @POST
+ @Path("/services/{processKey}")
+ @ApiOperation(value = "Starts a new process with the appropriate process Key",
+ notes = "Aysnc fall outs are only logged")
+ @Produces("application/json")
+ @Consumes("application/json")
+ public Response startProcessInstanceByKey(@PathParam("processKey") String processKey, VariableMapImpl variableMap) {
+ Map<String, Object> inputVariables = getInputVariables(variableMap);
+ try {
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, getRequestId(inputVariables));
+ processor.startProcess(processKey, variableMap);
+ WorkflowResponse response = waitForResponse(getRequestId(inputVariables));
+ return Response.status(202).entity(response).build();
+ } catch (WorkflowProcessorException e) {
+ WorkflowResponse response = e.getWorkflowResponse();
+ return Response.status(500).entity(response).build();
+ } catch (Exception e) {
+ WorkflowResponse response = buildUnkownError(getRequestId(inputVariables), e.getMessage());
+ return Response.status(500).entity(response).build();
+ }
+ }
+
+ private WorkflowResponse waitForResponse(String requestId) throws Exception {
+ long currentWaitTime = 0;
+ while (DEFAULT_WAIT_TIME > currentWaitTime) {
+ Thread.sleep(workflowPollInterval);
+ currentWaitTime = currentWaitTime + workflowPollInterval;
+ WorkflowContext foundContext = contextHolder.getWorkflowContext(requestId);
+ if (foundContext != null) {
+ contextHolder.remove(foundContext);
+ return buildResponse(foundContext);
+ }
+ }
+ throw new Exception("TimeOutOccured");
+ }
+
+ private WorkflowResponse buildUnkownError(String requestId, String error) {
+ WorkflowResponse response = new WorkflowResponse();
+ response.setMessage(error);
+ response.setResponse("UnknownError, request id:" + requestId);
+ response.setMessageCode(500);
+ return response;
+ }
+
+ private WorkflowResponse buildResponse(WorkflowContext foundContext) {
+ return foundContext.getWorkflowResponse();
+ }
+
protected static String getOrCreate(Map<String, Object> inputVariables, String key) {
String value = Objects.toString(inputVariables.get(key), null);
if (value == null) {
@@ -152,27 +147,28 @@ public class WorkflowAsyncResource extends ProcessEngineAwareService {
return value;
}
- protected static String getRequestId(Map<String, Object> inputVariables) {
+ protected static String getRequestId(Map<String, Object> inputVariables) {
return getOrCreate(inputVariables, "mso-request-id");
- }
-
- protected boolean isProcessEnded(String processInstanceId) {
- ProcessEngineServices pes = getProcessEngineServices();
- return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null;
- }
-
- protected static Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
- Map<String, Object> inputVariables = new HashMap<>();
- @SuppressWarnings("unchecked")
- Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
- for (Map.Entry<String, Object> entry : vMap.entrySet()) {
- String vName = entry.getKey();
- Object value = entry.getValue();
- @SuppressWarnings("unchecked")
- Map<String, Object> valueMap = (Map<String,Object>)value; // value, type
- inputVariables.put(vName, valueMap.get("value"));
- }
- return inputVariables;
- }
+ }
+
+ protected boolean isProcessEnded(String processInstanceId) {
+ ProcessEngineServices pes = getProcessEngineServices();
+ return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId)
+ .singleResult() == null;
+ }
+
+ protected static Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
+ Map<String, Object> inputVariables = new HashMap<>();
+ @SuppressWarnings("unchecked")
+ Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
+ for (Map.Entry<String, Object> entry : vMap.entrySet()) {
+ String vName = entry.getKey();
+ Object value = entry.getValue();
+ @SuppressWarnings("unchecked")
+ Map<String, Object> valueMap = (Map<String, Object>) value; // value, type
+ inputVariables.put(vName, valueMap.get("value"));
+ }
+ return inputVariables;
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowMessageResource.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowMessageResource.java
index 075102331c..1e9ebdf0b2 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowMessageResource.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowMessageResource.java
@@ -24,7 +24,6 @@ package org.onap.so.bpmn.common.workflow.service;
import java.util.HashMap;
import java.util.Map;
-
import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
@@ -33,7 +32,6 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.onap.so.bpmn.common.workflow.service.CallbackHandlerService.CallbackError;
import org.onap.so.bpmn.common.workflow.service.CallbackHandlerService.CallbackResult;
import org.onap.so.logger.ErrorCode;
@@ -42,13 +40,12 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
- * Generalized REST interface that injects a message event into a waiting BPMN process.
- * Examples:
+ * Generalized REST interface that injects a message event into a waiting BPMN process. Examples:
+ *
* <pre>
* /WorkflowMessage/SDNCAResponse/6d10d075-100c-42d0-9d84-a52432681cae-1478486185286
* /WorkflowMessage/SDNCAEvent/USOSTCDALTX0101UJZZ01
@@ -57,70 +54,62 @@ import io.swagger.annotations.ApiOperation;
@Path("/")
@Api(description = "Provides a generic service to inject messages into a waiting BPMN Proccess")
@Component
-public class WorkflowMessageResource{
- private static final Logger logger = LoggerFactory.getLogger(WorkflowMessageResource.class);
- private static final String LOGMARKER = "[WORKFLOW-MESSAGE]";
-
- @Autowired
- CallbackHandlerService callback;
-
- @POST
- @Path("/WorkflowMessage/{messageType}/{correlator}")
- @ApiOperation(
- value = "Workflow message correlator",
- notes = ""
- )
- @Consumes("*/*")
- @Produces(MediaType.TEXT_PLAIN)
- public Response deliver(
- @HeaderParam("Content-Type") String contentType,
- @PathParam("messageType") String messageType,
- @PathParam("correlator") String correlator,
- String message) {
+public class WorkflowMessageResource {
+ private static final Logger logger = LoggerFactory.getLogger(WorkflowMessageResource.class);
+ private static final String LOGMARKER = "[WORKFLOW-MESSAGE]";
+
+ @Autowired
+ CallbackHandlerService callback;
+
+ @POST
+ @Path("/WorkflowMessage/{messageType}/{correlator}")
+ @ApiOperation(value = "Workflow message correlator", notes = "")
+ @Consumes("*/*")
+ @Produces(MediaType.TEXT_PLAIN)
+ public Response deliver(@HeaderParam("Content-Type") String contentType,
+ @PathParam("messageType") String messageType, @PathParam("correlator") String correlator, String message) {
- String method = "receiveWorkflowMessage";
+ String method = "receiveWorkflowMessage";
- logger.debug(LOGMARKER + " Received workflow message"
- + " type='" + messageType + "'"
- + " correlator='" + correlator + "'"
- + (contentType == null ? "" : " contentType='" + contentType + "'")
- + " message=" + System.lineSeparator() + message);
+ logger.debug(LOGMARKER + " Received workflow message" + " type='" + messageType + "'" + " correlator='"
+ + correlator + "'" + (contentType == null ? "" : " contentType='" + contentType + "'") + " message="
+ + System.lineSeparator() + message);
- if (messageType == null || messageType.isEmpty()) {
- String msg = "Missing message type";
- logger.debug(LOGMARKER + " " + msg);
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
- ErrorCode.DataError.getValue(), LOGMARKER + ":" + msg);
- return Response.status(400).entity(msg).build();
- }
+ if (messageType == null || messageType.isEmpty()) {
+ String msg = "Missing message type";
+ logger.debug(LOGMARKER + " " + msg);
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
+ ErrorCode.DataError.getValue(), LOGMARKER + ":" + msg);
+ return Response.status(400).entity(msg).build();
+ }
- if (correlator == null || correlator.isEmpty()) {
- String msg = "Missing correlator";
- logger.debug(LOGMARKER + " " + msg);
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
- ErrorCode.DataError.getValue(), LOGMARKER + ":" + msg);
- return Response.status(400).entity(msg).build();
- }
+ if (correlator == null || correlator.isEmpty()) {
+ String msg = "Missing correlator";
+ logger.debug(LOGMARKER + " " + msg);
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
+ ErrorCode.DataError.getValue(), LOGMARKER + ":" + msg);
+ return Response.status(400).entity(msg).build();
+ }
- String messageEventName = "WorkflowMessage";
- String messageVariable = messageType + "_MESSAGE";
- String correlationVariable = messageType + "_CORRELATOR";
- String correlationValue = correlator;
- String contentTypeVariable = messageType + "_CONTENT_TYPE";
+ String messageEventName = "WorkflowMessage";
+ String messageVariable = messageType + "_MESSAGE";
+ String correlationVariable = messageType + "_CORRELATOR";
+ String correlationValue = correlator;
+ String contentTypeVariable = messageType + "_CONTENT_TYPE";
- Map<String, Object> variables = new HashMap<>();
+ Map<String, Object> variables = new HashMap<>();
- if (contentType != null) {
- variables.put(contentTypeVariable, contentType);
- }
+ if (contentType != null) {
+ variables.put(contentTypeVariable, contentType);
+ }
- CallbackResult result = callback.handleCallback(method, message, messageEventName,
- messageVariable, correlationVariable, correlationValue, LOGMARKER, variables);
+ CallbackResult result = callback.handleCallback(method, message, messageEventName, messageVariable,
+ correlationVariable, correlationValue, LOGMARKER, variables);
- if (result instanceof CallbackError) {
- return Response.status(500).entity(((CallbackError)result).getErrorMessage()).build();
- } else {
- return Response.status(204).build();
- }
- }
+ if (result instanceof CallbackError) {
+ return Response.status(500).entity(((CallbackError) result).getErrorMessage()).build();
+ } else {
+ return Response.status(204).build();
+ }
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowProcessor.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowProcessor.java
index b1062962a6..4e9e9fdf0e 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowProcessor.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowProcessor.java
@@ -26,7 +26,6 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
-
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
@@ -39,65 +38,64 @@ import org.springframework.stereotype.Service;
@Service
public class WorkflowProcessor extends ProcessEngineAwareService {
-
- private static final Logger logger = LoggerFactory.getLogger(WorkflowProcessor.class);
- protected static final String logMarker = "[WRKFLOW-RESOURCE]";
-
- @Async
- public void startProcess( String processKey, VariableMapImpl variableMap)
- {
-
- long startTime = System.currentTimeMillis();
- Map<String, Object> inputVariables = null;
- String processInstanceId = null;
- try {
- inputVariables = getInputVariables(variableMap);
- // This variable indicates that the flow was invoked asynchronously
- inputVariables.put("isAsyncProcess", "true");
- // Note: this creates a random businessKey if it wasn't specified.
- String businessKey = getBusinessKey(inputVariables);
+ private static final Logger logger = LoggerFactory.getLogger(WorkflowProcessor.class);
+ protected static final String logMarker = "[WRKFLOW-RESOURCE]";
+
+ @Async
+ public void startProcess(String processKey, VariableMapImpl variableMap) {
+
+ long startTime = System.currentTimeMillis();
+ Map<String, Object> inputVariables = null;
+ String processInstanceId = null;
+ try {
+ inputVariables = getInputVariables(variableMap);
+ // This variable indicates that the flow was invoked asynchronously
+ inputVariables.put("isAsyncProcess", "true");
- logger.debug("***Received MSO startProcessInstanceByKey with processKey: {} and variables: {}", processKey,
- inputVariables);
+ // Note: this creates a random businessKey if it wasn't specified.
+ String businessKey = getBusinessKey(inputVariables);
- RuntimeService runtimeService = getProcessEngineServices().getRuntimeService();
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey, businessKey,
- inputVariables);
- processInstanceId = processInstance.getId();
+ logger.debug("***Received MSO startProcessInstanceByKey with processKey: {} and variables: {}", processKey,
+ inputVariables);
- logger.debug(logMarker + "Process " + processKey + ":" + processInstanceId + " "
- + (processInstance.isEnded() ? "ENDED" : "RUNNING"));
- } catch (Exception e) {
- WorkflowResponse workflowResponse = new WorkflowResponse();
- workflowResponse.setResponse("Error occurred while executing the process: " + e);
- workflowResponse.setProcessInstanceID(processInstanceId);
- workflowResponse.setMessageCode(500);
- workflowResponse.setMessage("Fail");
- throw new WorkflowProcessorException(workflowResponse);
- }
- }
+ RuntimeService runtimeService = getProcessEngineServices().getRuntimeService();
+ ProcessInstance processInstance =
+ runtimeService.startProcessInstanceByKey(processKey, businessKey, inputVariables);
+ processInstanceId = processInstance.getId();
+
+ logger.debug(logMarker + "Process " + processKey + ":" + processInstanceId + " "
+ + (processInstance.isEnded() ? "ENDED" : "RUNNING"));
+ } catch (Exception e) {
+ WorkflowResponse workflowResponse = new WorkflowResponse();
+ workflowResponse.setResponse("Error occurred while executing the process: " + e);
+ workflowResponse.setProcessInstanceID(processInstanceId);
+ workflowResponse.setMessageCode(500);
+ workflowResponse.setMessage("Fail");
+ throw new WorkflowProcessorException(workflowResponse);
+ }
+ }
- // Note: the business key is used to identify the process in unit tests
- protected static String getBusinessKey(Map<String, Object> inputVariables) {
+ // Note: the business key is used to identify the process in unit tests
+ protected static String getBusinessKey(Map<String, Object> inputVariables) {
return getOrCreate(inputVariables, "mso-business-key");
- }
+ }
+
+
+ protected static Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
+ Map<String, Object> inputVariables = new HashMap<>();
+ @SuppressWarnings("unchecked")
+ Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
+ for (Map.Entry<String, Object> entry : vMap.entrySet()) {
+ String vName = entry.getKey();
+ Object value = entry.getValue();
+ @SuppressWarnings("unchecked")
+ Map<String, Object> valueMap = (Map<String, Object>) value; // value, type
+ inputVariables.put(vName, valueMap.get("value"));
+ }
+ return inputVariables;
+ }
-
- protected static Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
- Map<String, Object> inputVariables = new HashMap<>();
- @SuppressWarnings("unchecked")
- Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
- for (Map.Entry<String, Object> entry : vMap.entrySet()) {
- String vName = entry.getKey();
- Object value = entry.getValue();
- @SuppressWarnings("unchecked")
- Map<String, Object> valueMap = (Map<String,Object>)value; // value, type
- inputVariables.put(vName, valueMap.get("value"));
- }
- return inputVariables;
- }
-
protected static String getOrCreate(Map<String, Object> inputVariables, String key) {
String value = Objects.toString(inputVariables.get(key), null);
if (value == null) {
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowResource.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowResource.java
index a5d479ae41..9d63e8eaf1 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowResource.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowResource.java
@@ -28,7 +28,6 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
-
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@@ -37,7 +36,6 @@ import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
-
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.ProcessEngineServices;
@@ -56,7 +54,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@@ -64,534 +61,531 @@ import io.swagger.annotations.ApiOperation;
@Api(value = "/workflow", description = "Root of workflow services")
@Component
public class WorkflowResource extends ProcessEngineAwareService {
-
- private static final Logger logger = LoggerFactory.getLogger(WorkflowResource.class);
- private static final String LOGMARKER = "[WRKFLOW-RESOURCE]";
-
- private static final int DEFAULT_WAIT_TIME = 30000;
-
- @Context
- private UriInfo uriInfo = null;
-
- /**
- * Starts the process instance and responds to client synchronously
- * If the request does not contain mso-service-request-timeout then it waits for the value specified in DEFAULT_WAIT_TIME
- * Note: value specified in mso-service-request-timeout is in seconds
- * During polling time, if there is an exception encountered in the process execution then polling is stopped and the error response is
- * returned to the client
- * @param processKey
- * @param variableMap
- * @return
- */
- @POST
- @Path("/services/{processKey}")
- @ApiOperation(
- value = "Starts a new process with the appropriate process synchronously",
- notes = "d"
- )
- @Produces("application/json")
- @Consumes("application/json")
- public Response startProcessInstanceByKey(@PathParam("processKey") String processKey,
- VariableMapImpl variableMap) {
-
- Map<String, Object> inputVariables = getInputVariables(variableMap);
- setLogContext(processKey, inputVariables);
-
- WorkflowResponse workflowResponse = new WorkflowResponse();
- long startTime = System.currentTimeMillis();
- ProcessInstance processInstance = null;
-
- try {
- //Kickoff the process
- ProcessThread thread = new ProcessThread(inputVariables,processKey);
- thread.start();
-
- Map<String, Object> responseMap = null;
-
- //wait for process to be completed
- long waitTime = getWaitTime(inputVariables);
- long now = System.currentTimeMillis();
- long start = now;
- long endTime = start + waitTime;
- long pollingInterval = 500;
-
- // TEMPORARY LOGIC FOR UNIT TEST REFACTORING
- // If this is a unit test (method is invoked directly), wait a max
- // of 5 seconds after process ended for a result. In production,
- // wait up to 60 seconds.
- long timeToWaitAfterProcessEnded = uriInfo == null ? 5000 : 60000;
- AtomicLong timeProcessEnded = new AtomicLong(0);
- boolean endedWithNoResponse = false;
-
- while (now <= endTime) {
- Thread.sleep(pollingInterval);
-
- now = System.currentTimeMillis();
-
- // Increase the polling interval over time
-
- long elapsed = now - start;
-
- if (elapsed > 60000) {
- pollingInterval = 5000;
- } else if (elapsed > 10000) {
- pollingInterval = 1000;
- }
- Exception exception = thread.getException();
- if (exception != null) {
- throw new Exception(exception);
- }
-
- processInstance = thread.getProcessInstance();
-
- if (processInstance == null) {
- logger.debug("{} process has not been created yet", LOGMARKER + processKey );
- continue;
- }
-
- String processInstanceId = processInstance.getId();
- workflowResponse.setProcessInstanceID(processInstanceId);
-
- responseMap = getResponseMap(processInstance, processKey, timeProcessEnded);
-
- if (responseMap == null) {
- logger.debug("{} has not produced a response yet", LOGMARKER + processKey);
-
- if (timeProcessEnded.longValue() != 0) {
- long elapsedSinceEnded = System.currentTimeMillis() - timeProcessEnded.longValue();
-
- if (elapsedSinceEnded > timeToWaitAfterProcessEnded) {
- endedWithNoResponse = true;
- break;
- }
- }
- } else {
- processResponseMap(workflowResponse, responseMap);
- recordEvents(processKey, workflowResponse, startTime);
- return Response.status(workflowResponse.getMessageCode()).entity(workflowResponse).build();
- }
- }
-
- //if we dont get response after waiting then send timeout response
-
- String state;
- String processInstanceId;
-
- if (processInstance == null) {
- processInstanceId = "N/A";
- state = "NOT STARTED";
- } else {
- processInstanceId = processInstance.getProcessInstanceId();
- state = isProcessEnded(processInstanceId) ? "ENDED" : "NOT ENDED";
- }
-
- workflowResponse.setMessage("Fail");
- if (endedWithNoResponse) {
- workflowResponse.setResponse("Process ended without producing a response");
- } else {
- workflowResponse.setResponse("Request timed out, process state: " + state);
- }
- workflowResponse.setProcessInstanceID(processInstanceId);
- recordEvents(processKey, workflowResponse, startTime);
- workflowResponse.setMessageCode(500);
- return Response.status(500).entity(workflowResponse).build();
- } catch (Exception ex) {
- logger.debug(LOGMARKER + "Exception in startProcessInstance by key",ex);
- workflowResponse.setMessage("Fail" );
- workflowResponse.setResponse("Error occurred while executing the process: " + ex.getMessage());
- if (processInstance != null) workflowResponse.setProcessInstanceID(processInstance.getId());
-
- logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "BPMN", MDC.get(processKey),
- ErrorCode.UnknownError.getValue(),
- LOGMARKER + workflowResponse.getMessage() + " for processKey: " + processKey + " with response: "
- + workflowResponse.getResponse());
-
- workflowResponse.setMessageCode(500);
- recordEvents(processKey, workflowResponse, startTime);
- return Response.status(500).entity(workflowResponse).build();
- }
- }
-
- /**
- * Returns the wait time, this is used by the resource on how long it should wait to send a response
- * If none specified DEFAULT_WAIT_TIME is used
- * @param inputVariables
- * @return
- */
- private int getWaitTime(Map<String, Object> inputVariables)
- {
- String timeout = inputVariables.get("mso-service-request-timeout") == null
- ? null : inputVariables.get("mso-service-request-timeout").toString();
-
- if (timeout != null) {
- try {
- return Integer.parseInt(timeout)*1000;
- } catch (NumberFormatException nex) {
- logger.debug("Invalid input for mso-service-request-timeout");
- }
- }
- return DEFAULT_WAIT_TIME;
- }
-
- private void recordEvents(String processKey, WorkflowResponse response, long startTime) {
- }
-
- private void setLogContext(String processKey, Map<String, Object> inputVariables) {
- }
-
- private String getValueFromInputVariables(Map<String,Object> inputVariables, String key) {
- Object value = inputVariables.get(key);
- if (value == null) {
- return "N/A";
- } else {
- return value.toString();
- }
- }
-
- /**
- * Checks to see if the specified process is ended.
- * @param processInstanceId the process instance ID
- * @return true if the process is ended
- */
- private boolean isProcessEnded(String processInstanceId) {
- ProcessEngineServices pes = getProcessEngineServices();
- try {
- return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null ? true : false ;
- } catch (Exception e) {
- logger.debug("Exception :",e);
- return true;
- }
- }
-
- private void processResponseMap(WorkflowResponse workflowResponse, Map<String, Object> responseMap) {
- Object object = responseMap.get("Response");
- String response = object == null ? null : String.valueOf(object);
- if(response == null){
- object = responseMap.get("WorkflowResponse");
- response = object == null ? null : String.valueOf(object);
- }
-
- workflowResponse.setResponse(response);
-
- object = responseMap.get("ResponseCode");
- String responseCode = object == null ? null : String.valueOf(object);
-
- try {
- workflowResponse.setMessageCode(Integer.parseInt(responseCode));
- } catch(NumberFormatException nex) {
- logger.debug(LOGMARKER + "Failed to parse ResponseCode: " + responseCode);
- workflowResponse.setMessageCode(-1);
- }
-
- Object status = responseMap.get("Status");
-
- if ("Success".equalsIgnoreCase(String.valueOf(status))) {
- workflowResponse.setMessage("Success");
- } else if ("Fail".equalsIgnoreCase(String.valueOf(status))) {
- workflowResponse.setMessage("Fail");
- } else {
- logger.debug(LOGMARKER + "Unrecognized Status: " + responseCode);
- workflowResponse.setMessage("Fail");
- }
- }
-
- /**
- * @version 1.0
- * Triggers the workflow in a separate thread
- */
- private class ProcessThread extends Thread {
- private final Map<String,Object> inputVariables;
- private final String processKey;
- private final String businessKey;
- private ProcessInstance processInstance = null;
- private Exception exception = null;
-
- public ProcessThread(Map<String, Object> inputVariables, String processKey) {
- this.inputVariables = inputVariables;
- this.processKey = processKey;
- this.businessKey = UUID.randomUUID().toString();
- }
-
- /**
- * If an exception occurs when starting the process instance, it may
- * be obtained by calling this method. Note that exceptions are only
- * recorded while the process is executing in its original thread.
- * Once a process is suspended, exception recording stops.
- * @return the exception, or null if none has occurred
- */
- public Exception getException() {
- return exception;
- }
-
-
- public ProcessInstance getProcessInstance() {
- return this.processInstance;
- }
-
- /**
- * Sets the process instance exception.
- * @param exception the exception
- */
- private void setException(Exception exception) {
- this.exception = exception;
- }
-
- public void run() {
- setLogContext(processKey, inputVariables);
-
- long startTime = System.currentTimeMillis();
-
- try {
-
- RuntimeService runtimeService = getProcessEngineServices().getRuntimeService();
-
- // Note that this method doesn't return until the process suspends
- // itself or finishes. We provide a business key so we can identify
- // the process instance immediately.
- processInstance = runtimeService.startProcessInstanceByKey(
- processKey, inputVariables);
-
- } catch (Exception e) {
- logger.debug(LOGMARKER + "ProcessThread caught an exception executing "
- + processKey + ": " + e);
- setException(e);
- }
- }
-
- }
-
- private Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
- VariableMap inputVariables = Variables.createVariables();
- @SuppressWarnings("unchecked")
- Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
- for (String key : vMap.keySet()) { //variabe name vn
- @SuppressWarnings("unchecked")
- Map<String, Object> valueMap = (Map<String,Object>)vMap.get(key); //value, type
- inputVariables.putValueTyped(key, Variables
- .objectValue(valueMap.get("value"))
- .serializationDataFormat(SerializationDataFormats.JAVA) // tells the engine to use java serialization for persisting the value
- .create());
- }
- return inputVariables;
- }
-
- /**
- * Attempts to get a response map from the specified process instance.
- * @return the response map, or null if it is unavailable
- */
- private Map<String, Object> getResponseMap(ProcessInstance processInstance,
- String processKey, AtomicLong timeProcessEnded) {
-
- String responseMapVariable = processKey + "ResponseMap";
- String processInstanceId = processInstance.getId();
-
- // Query the runtime service to see if a response map is ready.
-
-/* RuntimeService runtimeService = getProcessEngineServices().getRuntimeService();
- List<Execution> executions = runtimeService.createExecutionQuery()
- .processInstanceId(processInstanceId).list();
-
- for (Execution execution : executions) {
- @SuppressWarnings("unchecked")
- Map<String, Object> responseMap = (Map<String, Object>)
- getVariableFromExecution(runtimeService, execution.getId(),
- responseMapVariable);
-
- if (responseMap != null) {
- msoLogger.debug(LOGMARKER + "Obtained " + responseMapVariable
- + " from process " + processInstanceId + " execution "
- + execution.getId());
- return responseMap;
- }
- }
-*/
- //Querying history seem to return consistent results compared to querying the runtime service
-
- boolean alreadyEnded = timeProcessEnded.longValue() != 0;
-
- if (alreadyEnded || isProcessEnded(processInstance.getId())) {
- if (!alreadyEnded) {
- timeProcessEnded.set(System.currentTimeMillis());
- }
-
- // Query the history service to see if a response map exists.
-
- HistoryService historyService = getProcessEngineServices().getHistoryService();
- @SuppressWarnings("unchecked")
- Map<String, Object> responseMap = (Map<String, Object>)
- getVariableFromHistory(historyService, processInstance.getId(),
- responseMapVariable);
-
- if (responseMap != null) {
- logger.debug(LOGMARKER + "Obtained " + responseMapVariable
- + " from process " + processInstanceId + " history");
- return responseMap;
- }
-
- // Query the history service for old-style response variables.
-
- String prefix = (String) getVariableFromHistory(historyService, processInstanceId, "prefix");
-
- if (prefix != null) {
-
- // Check for 'WorkflowResponse' variable
- Object workflowResponseObject = getVariableFromHistory(historyService, processInstanceId, "WorkflowResponse");
- String workflowResponse = workflowResponseObject == null ? null : String.valueOf(workflowResponseObject);
- logger.debug(LOGMARKER + "WorkflowResponse: " + workflowResponse);
-
- if (workflowResponse != null) {
- Object responseCodeObject = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode");
- String responseCode = responseCodeObject == null ? null : String.valueOf(responseCodeObject);
- logger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode);
- responseMap = new HashMap<>();
- responseMap.put("WorkflowResponse", workflowResponse);
- responseMap.put("ResponseCode", responseCode);
- responseMap.put("Status", "Success");
- return responseMap;
- }
-
-
- // Check for 'WorkflowException' variable
- WorkflowException workflowException = null;
- String workflowExceptionText = null;
-
- Object workflowExceptionObject = getVariableFromHistory(historyService, processInstanceId, "WorkflowException");
- if(workflowExceptionObject != null) {
- if(workflowExceptionObject instanceof WorkflowException) {
- workflowException = (WorkflowException) workflowExceptionObject;
- workflowExceptionText = workflowException.toString();
- responseMap = new HashMap<>();
- responseMap.put("WorkflowException", workflowExceptionText);
- responseMap.put("ResponseCode", workflowException.getErrorCode());
- responseMap.put("Status", "Fail");
- return responseMap;
- }
- else if (workflowExceptionObject instanceof String) {
- Object object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode");
- String responseCode = object == null ? null : String.valueOf(object);
- workflowExceptionText = (String) workflowExceptionObject;
- responseMap = new HashMap<>();
- responseMap.put("WorkflowException", workflowExceptionText);
- responseMap.put("ResponseCode", responseCode);
- responseMap.put("Status", "Fail");
- return responseMap;
- }
-
- }
- logger.debug(LOGMARKER + "WorkflowException: " + workflowExceptionText);
-
- // BEGIN LEGACY SUPPORT. TODO: REMOVE THIS CODE
- Object object = getVariableFromHistory(historyService, processInstanceId, processKey + "Response");
- String response = object == null ? null : String.valueOf(object);
- logger.debug(LOGMARKER + processKey + "Response: " + response);
-
- if (response != null) {
- object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode");
- String responseCode = object == null ? null : String.valueOf(object);
- logger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode);
- responseMap = new HashMap<>();
- responseMap.put("Response", response);
- responseMap.put("ResponseCode", responseCode);
- responseMap.put("Status", "Success");
- return responseMap;
- }
-
- object = getVariableFromHistory(historyService, processInstanceId, prefix + "ErrorResponse");
- String errorResponse = object == null ? null : String.valueOf(object);
- logger.debug(LOGMARKER + prefix + "ErrorResponse: " + errorResponse);
-
- if (errorResponse != null) {
- object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode");
- String responseCode = object == null ? null : String.valueOf(object);
- logger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode);
- responseMap = new HashMap<>();
- responseMap.put("Response", errorResponse);
- responseMap.put("ResponseCode", responseCode);
- responseMap.put("Status", "Fail");
- return responseMap;
- }
- // END LEGACY SUPPORT. TODO: REMOVE THIS CODE
- }
- }
- return null;
- }
-
- /**
- * Gets a variable value from the specified execution.
- * @return the variable value, or null if the variable could not be
- * obtained
- */
- private Object getVariableFromExecution(RuntimeService runtimeService,
- String executionId, String variableName) {
- try {
- return runtimeService.getVariable(executionId, variableName);
- } catch (ProcessEngineException e) {
- // Most likely cause is that the execution no longer exists.
- logger.debug("Error retrieving execution " + executionId
- + " variable " + variableName + ": " + e);
- return null;
- }
- }
- /**
- * Gets a variable value from specified historical process instance.
- * @return the variable value, or null if the variable could not be
- * obtained
- */
- private Object getVariableFromHistory(HistoryService historyService,
- String processInstanceId, String variableName) {
- try {
- HistoricVariableInstance v = historyService.createHistoricVariableInstanceQuery()
- .processInstanceId(processInstanceId).variableName(variableName).singleResult();
- return v == null ? null : v.getValue();
- } catch (Exception e) {
- logger.debug("Error retrieving process {} variable {} from history: ", processInstanceId,
- variableName, e);
- return null;
- }
- }
-
- @POST
- @Path("/services/{processKey}/{processInstanceId}")
- @Produces("application/json")
- @Consumes("application/json")
- @ApiOperation(
- value = "Allows for retrieval of the variables for a given process",
- notes = ""
- )
- public WorkflowResponse getProcessVariables(@PathParam("processKey") String processKey, @PathParam("processInstanceId") String processInstanceId) {
- //TODO filter only set of variables
- WorkflowResponse response = new WorkflowResponse();
-
- long startTime = System.currentTimeMillis();
- try {
- ProcessEngineServices engine = getProcessEngineServices();
- List<HistoricVariableInstance> variables = engine.getHistoryService().createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).list();
- Map<String,String> variablesMap = new HashMap<>();
- for (HistoricVariableInstance variableInstance: variables) {
- variablesMap.put(variableInstance.getName(), variableInstance.getValue().toString());
- }
-
- logger.debug(LOGMARKER + "***Received MSO getProcessVariables with processKey:" + processKey + " and variables: " +
- variablesMap.toString());
-
- response.setVariables(variablesMap);
- response.setMessage("Success");
- response.setResponse("Successfully retrieved the variables");
- response.setProcessInstanceID(processInstanceId);
-
- logger.debug(LOGMARKER + response.getMessage() + " for processKey: " + processKey + " with response: " + response
- .getResponse());
- } catch (Exception ex) {
- response.setMessage("Fail");
- response.setResponse("Failed to retrieve the variables," + ex.getMessage());
- response.setProcessInstanceID(processInstanceId);
-
- logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "BPMN", MDC.get(processKey),
- ErrorCode.UnknownError.getValue(),
- LOGMARKER + response.getMessage() + " for processKey: " + processKey + " with response: " + response
- .getResponse());
- logger.debug("Exception :",ex);
- }
- return response;
- }
+
+ private static final Logger logger = LoggerFactory.getLogger(WorkflowResource.class);
+ private static final String LOGMARKER = "[WRKFLOW-RESOURCE]";
+
+ private static final int DEFAULT_WAIT_TIME = 30000;
+
+ @Context
+ private UriInfo uriInfo = null;
+
+ /**
+ * Starts the process instance and responds to client synchronously If the request does not contain
+ * mso-service-request-timeout then it waits for the value specified in DEFAULT_WAIT_TIME Note: value specified in
+ * mso-service-request-timeout is in seconds During polling time, if there is an exception encountered in the
+ * process execution then polling is stopped and the error response is returned to the client
+ *
+ * @param processKey
+ * @param variableMap
+ * @return
+ */
+ @POST
+ @Path("/services/{processKey}")
+ @ApiOperation(value = "Starts a new process with the appropriate process synchronously", notes = "d")
+ @Produces("application/json")
+ @Consumes("application/json")
+ public Response startProcessInstanceByKey(@PathParam("processKey") String processKey, VariableMapImpl variableMap) {
+
+ Map<String, Object> inputVariables = getInputVariables(variableMap);
+ setLogContext(processKey, inputVariables);
+
+ WorkflowResponse workflowResponse = new WorkflowResponse();
+ long startTime = System.currentTimeMillis();
+ ProcessInstance processInstance = null;
+
+ try {
+ // Kickoff the process
+ ProcessThread thread = new ProcessThread(inputVariables, processKey);
+ thread.start();
+
+ Map<String, Object> responseMap = null;
+
+ // wait for process to be completed
+ long waitTime = getWaitTime(inputVariables);
+ long now = System.currentTimeMillis();
+ long start = now;
+ long endTime = start + waitTime;
+ long pollingInterval = 500;
+
+ // TEMPORARY LOGIC FOR UNIT TEST REFACTORING
+ // If this is a unit test (method is invoked directly), wait a max
+ // of 5 seconds after process ended for a result. In production,
+ // wait up to 60 seconds.
+ long timeToWaitAfterProcessEnded = uriInfo == null ? 5000 : 60000;
+ AtomicLong timeProcessEnded = new AtomicLong(0);
+ boolean endedWithNoResponse = false;
+
+ while (now <= endTime) {
+ Thread.sleep(pollingInterval);
+
+ now = System.currentTimeMillis();
+
+ // Increase the polling interval over time
+
+ long elapsed = now - start;
+
+ if (elapsed > 60000) {
+ pollingInterval = 5000;
+ } else if (elapsed > 10000) {
+ pollingInterval = 1000;
+ }
+ Exception exception = thread.getException();
+ if (exception != null) {
+ throw new Exception(exception);
+ }
+
+ processInstance = thread.getProcessInstance();
+
+ if (processInstance == null) {
+ logger.debug("{} process has not been created yet", LOGMARKER + processKey);
+ continue;
+ }
+
+ String processInstanceId = processInstance.getId();
+ workflowResponse.setProcessInstanceID(processInstanceId);
+
+ responseMap = getResponseMap(processInstance, processKey, timeProcessEnded);
+
+ if (responseMap == null) {
+ logger.debug("{} has not produced a response yet", LOGMARKER + processKey);
+
+ if (timeProcessEnded.longValue() != 0) {
+ long elapsedSinceEnded = System.currentTimeMillis() - timeProcessEnded.longValue();
+
+ if (elapsedSinceEnded > timeToWaitAfterProcessEnded) {
+ endedWithNoResponse = true;
+ break;
+ }
+ }
+ } else {
+ processResponseMap(workflowResponse, responseMap);
+ recordEvents(processKey, workflowResponse, startTime);
+ return Response.status(workflowResponse.getMessageCode()).entity(workflowResponse).build();
+ }
+ }
+
+ // if we dont get response after waiting then send timeout response
+
+ String state;
+ String processInstanceId;
+
+ if (processInstance == null) {
+ processInstanceId = "N/A";
+ state = "NOT STARTED";
+ } else {
+ processInstanceId = processInstance.getProcessInstanceId();
+ state = isProcessEnded(processInstanceId) ? "ENDED" : "NOT ENDED";
+ }
+
+ workflowResponse.setMessage("Fail");
+ if (endedWithNoResponse) {
+ workflowResponse.setResponse("Process ended without producing a response");
+ } else {
+ workflowResponse.setResponse("Request timed out, process state: " + state);
+ }
+ workflowResponse.setProcessInstanceID(processInstanceId);
+ recordEvents(processKey, workflowResponse, startTime);
+ workflowResponse.setMessageCode(500);
+ return Response.status(500).entity(workflowResponse).build();
+ } catch (Exception ex) {
+ logger.debug(LOGMARKER + "Exception in startProcessInstance by key", ex);
+ workflowResponse.setMessage("Fail");
+ workflowResponse.setResponse("Error occurred while executing the process: " + ex.getMessage());
+ if (processInstance != null)
+ workflowResponse.setProcessInstanceID(processInstance.getId());
+
+ logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "BPMN",
+ MDC.get(processKey), ErrorCode.UnknownError.getValue(), LOGMARKER + workflowResponse.getMessage()
+ + " for processKey: " + processKey + " with response: " + workflowResponse.getResponse());
+
+ workflowResponse.setMessageCode(500);
+ recordEvents(processKey, workflowResponse, startTime);
+ return Response.status(500).entity(workflowResponse).build();
+ }
+ }
+
+ /**
+ * Returns the wait time, this is used by the resource on how long it should wait to send a response If none
+ * specified DEFAULT_WAIT_TIME is used
+ *
+ * @param inputVariables
+ * @return
+ */
+ private int getWaitTime(Map<String, Object> inputVariables) {
+ String timeout = inputVariables.get("mso-service-request-timeout") == null ? null
+ : inputVariables.get("mso-service-request-timeout").toString();
+
+ if (timeout != null) {
+ try {
+ return Integer.parseInt(timeout) * 1000;
+ } catch (NumberFormatException nex) {
+ logger.debug("Invalid input for mso-service-request-timeout");
+ }
+ }
+ return DEFAULT_WAIT_TIME;
+ }
+
+ private void recordEvents(String processKey, WorkflowResponse response, long startTime) {}
+
+ private void setLogContext(String processKey, Map<String, Object> inputVariables) {}
+
+ private String getValueFromInputVariables(Map<String, Object> inputVariables, String key) {
+ Object value = inputVariables.get(key);
+ if (value == null) {
+ return "N/A";
+ } else {
+ return value.toString();
+ }
+ }
+
+ /**
+ * Checks to see if the specified process is ended.
+ *
+ * @param processInstanceId the process instance ID
+ * @return true if the process is ended
+ */
+ private boolean isProcessEnded(String processInstanceId) {
+ ProcessEngineServices pes = getProcessEngineServices();
+ try {
+ return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId)
+ .singleResult() == null ? true : false;
+ } catch (Exception e) {
+ logger.debug("Exception :", e);
+ return true;
+ }
+ }
+
+ private void processResponseMap(WorkflowResponse workflowResponse, Map<String, Object> responseMap) {
+ Object object = responseMap.get("Response");
+ String response = object == null ? null : String.valueOf(object);
+ if (response == null) {
+ object = responseMap.get("WorkflowResponse");
+ response = object == null ? null : String.valueOf(object);
+ }
+
+ workflowResponse.setResponse(response);
+
+ object = responseMap.get("ResponseCode");
+ String responseCode = object == null ? null : String.valueOf(object);
+
+ try {
+ workflowResponse.setMessageCode(Integer.parseInt(responseCode));
+ } catch (NumberFormatException nex) {
+ logger.debug(LOGMARKER + "Failed to parse ResponseCode: " + responseCode);
+ workflowResponse.setMessageCode(-1);
+ }
+
+ Object status = responseMap.get("Status");
+
+ if ("Success".equalsIgnoreCase(String.valueOf(status))) {
+ workflowResponse.setMessage("Success");
+ } else if ("Fail".equalsIgnoreCase(String.valueOf(status))) {
+ workflowResponse.setMessage("Fail");
+ } else {
+ logger.debug(LOGMARKER + "Unrecognized Status: " + responseCode);
+ workflowResponse.setMessage("Fail");
+ }
+ }
+
+ /**
+ * @version 1.0 Triggers the workflow in a separate thread
+ */
+ private class ProcessThread extends Thread {
+ private final Map<String, Object> inputVariables;
+ private final String processKey;
+ private final String businessKey;
+ private ProcessInstance processInstance = null;
+ private Exception exception = null;
+
+ public ProcessThread(Map<String, Object> inputVariables, String processKey) {
+ this.inputVariables = inputVariables;
+ this.processKey = processKey;
+ this.businessKey = UUID.randomUUID().toString();
+ }
+
+ /**
+ * If an exception occurs when starting the process instance, it may be obtained by calling this method. Note
+ * that exceptions are only recorded while the process is executing in its original thread. Once a process is
+ * suspended, exception recording stops.
+ *
+ * @return the exception, or null if none has occurred
+ */
+ public Exception getException() {
+ return exception;
+ }
+
+
+ public ProcessInstance getProcessInstance() {
+ return this.processInstance;
+ }
+
+ /**
+ * Sets the process instance exception.
+ *
+ * @param exception the exception
+ */
+ private void setException(Exception exception) {
+ this.exception = exception;
+ }
+
+ public void run() {
+ setLogContext(processKey, inputVariables);
+
+ long startTime = System.currentTimeMillis();
+
+ try {
+
+ RuntimeService runtimeService = getProcessEngineServices().getRuntimeService();
+
+ // Note that this method doesn't return until the process suspends
+ // itself or finishes. We provide a business key so we can identify
+ // the process instance immediately.
+ processInstance = runtimeService.startProcessInstanceByKey(processKey, inputVariables);
+
+ } catch (Exception e) {
+ logger.debug(LOGMARKER + "ProcessThread caught an exception executing " + processKey + ": " + e);
+ setException(e);
+ }
+ }
+
+ }
+
+ private Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
+ VariableMap inputVariables = Variables.createVariables();
+ @SuppressWarnings("unchecked")
+ Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
+ for (String key : vMap.keySet()) { // variabe name vn
+ @SuppressWarnings("unchecked")
+ Map<String, Object> valueMap = (Map<String, Object>) vMap.get(key); // value, type
+ inputVariables.putValueTyped(key,
+ Variables.objectValue(valueMap.get("value")).serializationDataFormat(SerializationDataFormats.JAVA) // tells
+ // the
+ // engine
+ // to
+ // use
+ // java
+ // serialization
+ // for
+ // persisting
+ // the
+ // value
+ .create());
+ }
+ return inputVariables;
+ }
+
+ /**
+ * Attempts to get a response map from the specified process instance.
+ *
+ * @return the response map, or null if it is unavailable
+ */
+ private Map<String, Object> getResponseMap(ProcessInstance processInstance, String processKey,
+ AtomicLong timeProcessEnded) {
+
+ String responseMapVariable = processKey + "ResponseMap";
+ String processInstanceId = processInstance.getId();
+
+ // Query the runtime service to see if a response map is ready.
+
+ /*
+ * RuntimeService runtimeService = getProcessEngineServices().getRuntimeService(); List<Execution> executions =
+ * runtimeService.createExecutionQuery() .processInstanceId(processInstanceId).list();
+ *
+ * for (Execution execution : executions) {
+ *
+ * @SuppressWarnings("unchecked") Map<String, Object> responseMap = (Map<String, Object>)
+ * getVariableFromExecution(runtimeService, execution.getId(), responseMapVariable);
+ *
+ * if (responseMap != null) { msoLogger.debug(LOGMARKER + "Obtained " + responseMapVariable + " from process " +
+ * processInstanceId + " execution " + execution.getId()); return responseMap; } }
+ */
+ // Querying history seem to return consistent results compared to querying the runtime service
+
+ boolean alreadyEnded = timeProcessEnded.longValue() != 0;
+
+ if (alreadyEnded || isProcessEnded(processInstance.getId())) {
+ if (!alreadyEnded) {
+ timeProcessEnded.set(System.currentTimeMillis());
+ }
+
+ // Query the history service to see if a response map exists.
+
+ HistoryService historyService = getProcessEngineServices().getHistoryService();
+ @SuppressWarnings("unchecked")
+ Map<String, Object> responseMap = (Map<String, Object>) getVariableFromHistory(historyService,
+ processInstance.getId(), responseMapVariable);
+
+ if (responseMap != null) {
+ logger.debug(LOGMARKER + "Obtained " + responseMapVariable + " from process " + processInstanceId
+ + " history");
+ return responseMap;
+ }
+
+ // Query the history service for old-style response variables.
+
+ String prefix = (String) getVariableFromHistory(historyService, processInstanceId, "prefix");
+
+ if (prefix != null) {
+
+ // Check for 'WorkflowResponse' variable
+ Object workflowResponseObject =
+ getVariableFromHistory(historyService, processInstanceId, "WorkflowResponse");
+ String workflowResponse =
+ workflowResponseObject == null ? null : String.valueOf(workflowResponseObject);
+ logger.debug(LOGMARKER + "WorkflowResponse: " + workflowResponse);
+
+ if (workflowResponse != null) {
+ Object responseCodeObject =
+ getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode");
+ String responseCode = responseCodeObject == null ? null : String.valueOf(responseCodeObject);
+ logger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode);
+ responseMap = new HashMap<>();
+ responseMap.put("WorkflowResponse", workflowResponse);
+ responseMap.put("ResponseCode", responseCode);
+ responseMap.put("Status", "Success");
+ return responseMap;
+ }
+
+
+ // Check for 'WorkflowException' variable
+ WorkflowException workflowException = null;
+ String workflowExceptionText = null;
+
+ Object workflowExceptionObject =
+ getVariableFromHistory(historyService, processInstanceId, "WorkflowException");
+ if (workflowExceptionObject != null) {
+ if (workflowExceptionObject instanceof WorkflowException) {
+ workflowException = (WorkflowException) workflowExceptionObject;
+ workflowExceptionText = workflowException.toString();
+ responseMap = new HashMap<>();
+ responseMap.put("WorkflowException", workflowExceptionText);
+ responseMap.put("ResponseCode", workflowException.getErrorCode());
+ responseMap.put("Status", "Fail");
+ return responseMap;
+ } else if (workflowExceptionObject instanceof String) {
+ Object object =
+ getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode");
+ String responseCode = object == null ? null : String.valueOf(object);
+ workflowExceptionText = (String) workflowExceptionObject;
+ responseMap = new HashMap<>();
+ responseMap.put("WorkflowException", workflowExceptionText);
+ responseMap.put("ResponseCode", responseCode);
+ responseMap.put("Status", "Fail");
+ return responseMap;
+ }
+
+ }
+ logger.debug(LOGMARKER + "WorkflowException: " + workflowExceptionText);
+
+ // BEGIN LEGACY SUPPORT. TODO: REMOVE THIS CODE
+ Object object = getVariableFromHistory(historyService, processInstanceId, processKey + "Response");
+ String response = object == null ? null : String.valueOf(object);
+ logger.debug(LOGMARKER + processKey + "Response: " + response);
+
+ if (response != null) {
+ object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode");
+ String responseCode = object == null ? null : String.valueOf(object);
+ logger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode);
+ responseMap = new HashMap<>();
+ responseMap.put("Response", response);
+ responseMap.put("ResponseCode", responseCode);
+ responseMap.put("Status", "Success");
+ return responseMap;
+ }
+
+ object = getVariableFromHistory(historyService, processInstanceId, prefix + "ErrorResponse");
+ String errorResponse = object == null ? null : String.valueOf(object);
+ logger.debug(LOGMARKER + prefix + "ErrorResponse: " + errorResponse);
+
+ if (errorResponse != null) {
+ object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode");
+ String responseCode = object == null ? null : String.valueOf(object);
+ logger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode);
+ responseMap = new HashMap<>();
+ responseMap.put("Response", errorResponse);
+ responseMap.put("ResponseCode", responseCode);
+ responseMap.put("Status", "Fail");
+ return responseMap;
+ }
+ // END LEGACY SUPPORT. TODO: REMOVE THIS CODE
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Gets a variable value from the specified execution.
+ *
+ * @return the variable value, or null if the variable could not be obtained
+ */
+ private Object getVariableFromExecution(RuntimeService runtimeService, String executionId, String variableName) {
+ try {
+ return runtimeService.getVariable(executionId, variableName);
+ } catch (ProcessEngineException e) {
+ // Most likely cause is that the execution no longer exists.
+ logger.debug("Error retrieving execution " + executionId + " variable " + variableName + ": " + e);
+ return null;
+ }
+ }
+
+ /**
+ * Gets a variable value from specified historical process instance.
+ *
+ * @return the variable value, or null if the variable could not be obtained
+ */
+ private Object getVariableFromHistory(HistoryService historyService, String processInstanceId,
+ String variableName) {
+ try {
+ HistoricVariableInstance v = historyService.createHistoricVariableInstanceQuery()
+ .processInstanceId(processInstanceId).variableName(variableName).singleResult();
+ return v == null ? null : v.getValue();
+ } catch (Exception e) {
+ logger.debug("Error retrieving process {} variable {} from history: ", processInstanceId, variableName, e);
+ return null;
+ }
+ }
+
+ @POST
+ @Path("/services/{processKey}/{processInstanceId}")
+ @Produces("application/json")
+ @Consumes("application/json")
+ @ApiOperation(value = "Allows for retrieval of the variables for a given process", notes = "")
+ public WorkflowResponse getProcessVariables(@PathParam("processKey") String processKey,
+ @PathParam("processInstanceId") String processInstanceId) {
+ // TODO filter only set of variables
+ WorkflowResponse response = new WorkflowResponse();
+
+ long startTime = System.currentTimeMillis();
+ try {
+ ProcessEngineServices engine = getProcessEngineServices();
+ List<HistoricVariableInstance> variables = engine.getHistoryService().createHistoricVariableInstanceQuery()
+ .processInstanceId(processInstanceId).list();
+ Map<String, String> variablesMap = new HashMap<>();
+ for (HistoricVariableInstance variableInstance : variables) {
+ variablesMap.put(variableInstance.getName(), variableInstance.getValue().toString());
+ }
+
+ logger.debug(LOGMARKER + "***Received MSO getProcessVariables with processKey:" + processKey
+ + " and variables: " + variablesMap.toString());
+
+ response.setVariables(variablesMap);
+ response.setMessage("Success");
+ response.setResponse("Successfully retrieved the variables");
+ response.setProcessInstanceID(processInstanceId);
+
+ logger.debug(LOGMARKER + response.getMessage() + " for processKey: " + processKey + " with response: "
+ + response.getResponse());
+ } catch (Exception ex) {
+ response.setMessage("Fail");
+ response.setResponse("Failed to retrieve the variables," + ex.getMessage());
+ response.setProcessInstanceID(processInstanceId);
+
+ logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "BPMN",
+ MDC.get(processKey), ErrorCode.UnknownError.getValue(), LOGMARKER + response.getMessage()
+ + " for processKey: " + processKey + " with response: " + response.getResponse());
+ logger.debug("Exception :", ex);
+ }
+ return response;
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/LoggingAndURNMappingPlugin.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/LoggingAndURNMappingPlugin.java
index 3eed14bc30..296ab64df3 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/LoggingAndURNMappingPlugin.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/LoggingAndURNMappingPlugin.java
@@ -32,7 +32,6 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
-
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
@@ -53,8 +52,6 @@ import org.camunda.bpm.model.bpmn.impl.instance.FlowNodeImpl;
import org.camunda.bpm.model.bpmn.instance.EndEvent;
import org.camunda.bpm.model.bpmn.instance.FlowNode;
import org.camunda.bpm.model.bpmn.instance.StartEvent;
-
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -72,256 +69,259 @@ import org.springframework.stereotype.Component;
@Component
public class LoggingAndURNMappingPlugin extends AbstractProcessEnginePlugin {
- @Autowired
- private LoggingParseListener loggingParseListener;
-
- @Override
- public void preInit(
- ProcessEngineConfigurationImpl processEngineConfiguration) {
- List<BpmnParseListener> preParseListeners = processEngineConfiguration
- .getCustomPreBPMNParseListeners();
- if (preParseListeners == null) {
- preParseListeners = new ArrayList<>();
- processEngineConfiguration.setCustomPreBPMNParseListeners(preParseListeners);
- }
- preParseListeners.add(loggingParseListener);
- }
-
- /**
- * Called when a process flow is parsed so we can inject listeners.
- */
- @Component
- public class LoggingParseListener extends AbstractBpmnParseListener {
-
-
- private void injectLogExecutionListener(ActivityImpl activity) {
- activity.addListener(
- ExecutionListener.EVENTNAME_END,
- new LoggingExecutionListener("END"));
-
- activity.addListener(
- ExecutionListener.EVENTNAME_START,
- new LoggingExecutionListener("START"));
-
- activity.addListener(
- ExecutionListener.EVENTNAME_TAKE,
- new LoggingExecutionListener("TAKE"));
- }
-
- @Override
- public void parseProcess(Element processElement, ProcessDefinitionEntity processDefinition) {
- }
-
- @Override
- public void parseStartEvent(Element startEventElement, ScopeImpl scope, ActivityImpl startEventActivity) {
- // Inject these listeners only on the main start event for the flow, not on any embedded subflow start events
-
- injectLogExecutionListener(startEventActivity);
- }
-
- @Override
- public void parseServiceTask(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseExclusiveGateway(Element exclusiveGwElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseInclusiveGateway(Element inclusiveGwElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseParallelGateway(Element parallelGwElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseScriptTask(Element scriptTaskElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseBusinessRuleTask(Element businessRuleTaskElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseTask(Element taskElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseManualTask(Element manualTaskElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseUserTask(Element userTaskElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseEndEvent(Element endEventElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseBoundaryTimerEventDefinition(Element timerEventDefinition, boolean interrupting, ActivityImpl timerActivity) {
- injectLogExecutionListener(timerActivity);
- }
-
- @Override
- public void parseBoundaryErrorEventDefinition(Element errorEventDefinition, boolean interrupting, ActivityImpl activity, ActivityImpl nestedErrorEventActivity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseSubProcess(Element subProcessElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseCallActivity(Element callActivityElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseProperty(Element propertyElement, VariableDeclaration variableDeclaration, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseSequenceFlow(Element sequenceFlowElement, ScopeImpl scopeElement, TransitionImpl transition) {
- //injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseSendTask(Element sendTaskElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseMultiInstanceLoopCharacteristics(Element activityElement, Element multiInstanceLoopCharacteristicsElement, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseIntermediateTimerEventDefinition(Element timerEventDefinition, ActivityImpl timerActivity) {
- injectLogExecutionListener(timerActivity);
- }
-
- @Override
- public void parseRootElement(Element rootElement, List<ProcessDefinitionEntity> processDefinitions) {
-
- }
-
- @Override
- public void parseReceiveTask(Element receiveTaskElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseIntermediateSignalCatchEventDefinition(Element signalEventDefinition, ActivityImpl signalActivity) {
- injectLogExecutionListener(signalActivity);
- }
-
- @Override
- public void parseBoundarySignalEventDefinition(Element signalEventDefinition, boolean interrupting, ActivityImpl signalActivity) {
- injectLogExecutionListener(signalActivity);
- }
-
- @Override
- public void parseEventBasedGateway(Element eventBasedGwElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseCompensateEventDefinition(Element compensateEventDefinition, ActivityImpl compensationActivity) {
- injectLogExecutionListener(compensationActivity);
- }
-
- @Override
- public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseIntermediateCatchEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
- injectLogExecutionListener(activity);
- }
-
- @Override
- public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement, ActivityImpl nestedActivity) {
- injectLogExecutionListener(nestedActivity);
- }
-
- @Override
- public void parseIntermediateMessageCatchEventDefinition(Element messageEventDefinition, ActivityImpl nestedActivity) {
- injectLogExecutionListener(nestedActivity);
- }
-
- @Override
- public void parseBoundaryMessageEventDefinition(Element element, boolean interrupting, ActivityImpl messageActivity) {
- injectLogExecutionListener(messageActivity);
- }
- }
-
- /**
- * Logs details about the current activity.
- */
- public class LoggingExecutionListener implements ExecutionListener {
- private final Logger logger = LoggerFactory.getLogger(LoggingExecutionListener.class);
-
- private String event;
-
- public LoggingExecutionListener() {
- this.event = "";
- }
-
- public LoggingExecutionListener(String event) {
- this.event = event;
- }
-
- public String getEvent() {
- return event;
- }
-
- @Override
- public void notify(DelegateExecution execution) throws Exception {
- //required for legacy groovy processing in camunda
- execution.setVariable("isDebugLogEnabled", "true");
- if (!isBlank(execution.getCurrentActivityName())) {
- try {
-
- String id = execution.getId();
- if (id != null ) {
- RepositoryService repositoryService = execution.getProcessEngineServices().getRepositoryService();
- String processName = repositoryService.createProcessDefinitionQuery()
- .processDefinitionId(execution.getProcessDefinitionId())
- .singleResult()
- .getName();
-
-
- String requestId = (String) execution.getVariable("mso-request-id");
- String svcid = (String) execution.getVariable("mso-service-instance-id");
- }
- } catch(Exception e) {
- logger.error("Exception occurred", e);
- }
- }
- }
-
- private boolean isBlank(Object object) {
- return object == null || "".equals(object.toString().trim());
- }
- }
+ @Autowired
+ private LoggingParseListener loggingParseListener;
+
+ @Override
+ public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
+ List<BpmnParseListener> preParseListeners = processEngineConfiguration.getCustomPreBPMNParseListeners();
+ if (preParseListeners == null) {
+ preParseListeners = new ArrayList<>();
+ processEngineConfiguration.setCustomPreBPMNParseListeners(preParseListeners);
+ }
+ preParseListeners.add(loggingParseListener);
+ }
+
+ /**
+ * Called when a process flow is parsed so we can inject listeners.
+ */
+ @Component
+ public class LoggingParseListener extends AbstractBpmnParseListener {
+
+
+ private void injectLogExecutionListener(ActivityImpl activity) {
+ activity.addListener(ExecutionListener.EVENTNAME_END, new LoggingExecutionListener("END"));
+
+ activity.addListener(ExecutionListener.EVENTNAME_START, new LoggingExecutionListener("START"));
+
+ activity.addListener(ExecutionListener.EVENTNAME_TAKE, new LoggingExecutionListener("TAKE"));
+ }
+
+ @Override
+ public void parseProcess(Element processElement, ProcessDefinitionEntity processDefinition) {}
+
+ @Override
+ public void parseStartEvent(Element startEventElement, ScopeImpl scope, ActivityImpl startEventActivity) {
+ // Inject these listeners only on the main start event for the flow, not on any embedded subflow start
+ // events
+
+ injectLogExecutionListener(startEventActivity);
+ }
+
+ @Override
+ public void parseServiceTask(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseExclusiveGateway(Element exclusiveGwElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseInclusiveGateway(Element inclusiveGwElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseParallelGateway(Element parallelGwElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseScriptTask(Element scriptTaskElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseBusinessRuleTask(Element businessRuleTaskElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseTask(Element taskElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseManualTask(Element manualTaskElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseUserTask(Element userTaskElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseEndEvent(Element endEventElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseBoundaryTimerEventDefinition(Element timerEventDefinition, boolean interrupting,
+ ActivityImpl timerActivity) {
+ injectLogExecutionListener(timerActivity);
+ }
+
+ @Override
+ public void parseBoundaryErrorEventDefinition(Element errorEventDefinition, boolean interrupting,
+ ActivityImpl activity, ActivityImpl nestedErrorEventActivity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseSubProcess(Element subProcessElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseCallActivity(Element callActivityElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseProperty(Element propertyElement, VariableDeclaration variableDeclaration,
+ ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseSequenceFlow(Element sequenceFlowElement, ScopeImpl scopeElement, TransitionImpl transition) {
+ // injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseSendTask(Element sendTaskElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseMultiInstanceLoopCharacteristics(Element activityElement,
+ Element multiInstanceLoopCharacteristicsElement, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseIntermediateTimerEventDefinition(Element timerEventDefinition, ActivityImpl timerActivity) {
+ injectLogExecutionListener(timerActivity);
+ }
+
+ @Override
+ public void parseRootElement(Element rootElement, List<ProcessDefinitionEntity> processDefinitions) {
+
+ }
+
+ @Override
+ public void parseReceiveTask(Element receiveTaskElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseIntermediateSignalCatchEventDefinition(Element signalEventDefinition,
+ ActivityImpl signalActivity) {
+ injectLogExecutionListener(signalActivity);
+ }
+
+ @Override
+ public void parseBoundarySignalEventDefinition(Element signalEventDefinition, boolean interrupting,
+ ActivityImpl signalActivity) {
+ injectLogExecutionListener(signalActivity);
+ }
+
+ @Override
+ public void parseEventBasedGateway(Element eventBasedGwElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseCompensateEventDefinition(Element compensateEventDefinition,
+ ActivityImpl compensationActivity) {
+ injectLogExecutionListener(compensationActivity);
+ }
+
+ @Override
+ public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope,
+ ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseIntermediateCatchEvent(Element intermediateEventElement, ScopeImpl scope,
+ ActivityImpl activity) {
+ injectLogExecutionListener(activity);
+ }
+
+ @Override
+ public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement,
+ ActivityImpl nestedActivity) {
+ injectLogExecutionListener(nestedActivity);
+ }
+
+ @Override
+ public void parseIntermediateMessageCatchEventDefinition(Element messageEventDefinition,
+ ActivityImpl nestedActivity) {
+ injectLogExecutionListener(nestedActivity);
+ }
+
+ @Override
+ public void parseBoundaryMessageEventDefinition(Element element, boolean interrupting,
+ ActivityImpl messageActivity) {
+ injectLogExecutionListener(messageActivity);
+ }
+ }
+
+ /**
+ * Logs details about the current activity.
+ */
+ public class LoggingExecutionListener implements ExecutionListener {
+ private final Logger logger = LoggerFactory.getLogger(LoggingExecutionListener.class);
+
+ private String event;
+
+ public LoggingExecutionListener() {
+ this.event = "";
+ }
+
+ public LoggingExecutionListener(String event) {
+ this.event = event;
+ }
+
+ public String getEvent() {
+ return event;
+ }
+
+ @Override
+ public void notify(DelegateExecution execution) throws Exception {
+ // required for legacy groovy processing in camunda
+ execution.setVariable("isDebugLogEnabled", "true");
+ if (!isBlank(execution.getCurrentActivityName())) {
+ try {
+
+ String id = execution.getId();
+ if (id != null) {
+ RepositoryService repositoryService =
+ execution.getProcessEngineServices().getRepositoryService();
+ String processName = repositoryService.createProcessDefinitionQuery()
+ .processDefinitionId(execution.getProcessDefinitionId()).singleResult().getName();
+
+
+ String requestId = (String) execution.getVariable("mso-request-id");
+ String svcid = (String) execution.getVariable("mso-service-instance-id");
+ }
+ } catch (Exception e) {
+ logger.error("Exception occurred", e);
+ }
+ }
+ }
+
+ private boolean isBlank(Object object) {
+ return object == null || "".equals(object.toString().trim());
+ }
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/WorkflowExceptionPlugin.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/WorkflowExceptionPlugin.java
index 8bc0055343..ab21c0807e 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/WorkflowExceptionPlugin.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/WorkflowExceptionPlugin.java
@@ -25,7 +25,6 @@ package org.onap.so.bpmn.core.plugins;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
@@ -41,7 +40,6 @@ import org.camunda.bpm.engine.impl.pvm.PvmTransition;
import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl;
import org.camunda.bpm.engine.impl.pvm.process.TransitionImpl;
import org.camunda.bpm.engine.impl.util.xml.Element;
-
import org.onap.so.bpmn.core.WorkflowException;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
@@ -50,125 +48,115 @@ import org.slf4j.LoggerFactory;
/**
* This plugin does the following:
* <ol>
- * <li>
- * Adds logic at the start of every Call Activity to remove any existing
- * WorkflowException object from the execution (saving a copy of it in a
- * different variable).
- * </li>
- * <li>
- * Adds logic at the end of every Call Activity to generate a MSOWorkflowException
- * event if there is a WorkflowException object in the execution.
- * </li>
+ * <li>Adds logic at the start of every Call Activity to remove any existing WorkflowException object from the execution
+ * (saving a copy of it in a different variable).</li>
+ * <li>Adds logic at the end of every Call Activity to generate a MSOWorkflowException event if there is a
+ * WorkflowException object in the execution.</li>
* </ol>
*/
@Component
public class WorkflowExceptionPlugin extends AbstractProcessEnginePlugin {
- private static final Logger logger = LoggerFactory.getLogger(WorkflowExceptionPlugin.class);
-
- @Override
- public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
- List<BpmnParseListener> preParseListeners =
- processEngineConfiguration.getCustomPreBPMNParseListeners();
-
- if (preParseListeners == null) {
- preParseListeners = new ArrayList<>();
- processEngineConfiguration.setCustomPreBPMNParseListeners(preParseListeners);
- }
-
- preParseListeners.add(new WorkflowExceptionParseListener());
- }
-
- public static class WorkflowExceptionParseListener extends AbstractBpmnParseListener {
- @Override
- public void parseProcess(Element processElement, ProcessDefinitionEntity processDefinition) {
- AtomicInteger triggerTaskIndex = new AtomicInteger(1);
- List<ActivityImpl> activities = new ArrayList<>(processDefinition.getActivities());
- recurse(activities, triggerTaskIndex);
- }
-
- /**
- * Helper method that recurses (into subprocesses) over all the listed activities.
- * @param activities a list of workflow activities
- * @param triggerTaskIndex the index of the next trigger task (mutable)
- */
- private void recurse(List<ActivityImpl> activities, AtomicInteger triggerTaskIndex) {
- for (ActivityImpl activity : activities) {
- String type = (String) activity.getProperty("type");
-
- if ("callActivity".equals(type)) {
- // Add a WorkflowExceptionResetListener to clear the WorkflowException
- // variable when each Call Activity starts.
-
- activity.addListener(
- ExecutionListener.EVENTNAME_START,
- new WorkflowExceptionResetListener());
-
- // Add a WorkflowExceptionTriggerTask after the call activity.
- // It must be a task because a listener cannot be used to generate
- // an event. Throwing BpmnError from an execution listener will
- // cause the process to die.
-
- List<PvmTransition> outTransitions =
- new ArrayList<>(activity.getOutgoingTransitions());
-
- for (PvmTransition transition : outTransitions) {
- String triggerTaskId = "WorkflowExceptionTriggerTask_" + triggerTaskIndex;
-
- ActivityImpl triggerTask = activity.getFlowScope().createActivity(triggerTaskId);
-
- ClassDelegateActivityBehavior behavior = new ClassDelegateActivityBehavior(
- WorkflowExceptionTriggerTask.class.getName(),
- new ArrayList<>(0));
-
- triggerTask.setActivityBehavior(behavior);
- triggerTask.setName("Workflow Exception Trigger Task " + triggerTaskIndex);
- triggerTaskIndex.getAndIncrement();
-
- TransitionImpl transitionImpl = (TransitionImpl) transition;
- TransitionImpl triggerTaskOutTransition = triggerTask.createOutgoingTransition();
- triggerTaskOutTransition.setDestination((ActivityImpl)transitionImpl.getDestination());
- transitionImpl.setDestination(triggerTask);
- }
- } else if ("subProcess".equals(type)) {
- recurse(new ArrayList<>(activity.getActivities()), triggerTaskIndex);
- }
- }
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(WorkflowExceptionPlugin.class);
+
+ @Override
+ public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
+ List<BpmnParseListener> preParseListeners = processEngineConfiguration.getCustomPreBPMNParseListeners();
+
+ if (preParseListeners == null) {
+ preParseListeners = new ArrayList<>();
+ processEngineConfiguration.setCustomPreBPMNParseListeners(preParseListeners);
+ }
+
+ preParseListeners.add(new WorkflowExceptionParseListener());
+ }
+
+ public static class WorkflowExceptionParseListener extends AbstractBpmnParseListener {
+ @Override
+ public void parseProcess(Element processElement, ProcessDefinitionEntity processDefinition) {
+ AtomicInteger triggerTaskIndex = new AtomicInteger(1);
+ List<ActivityImpl> activities = new ArrayList<>(processDefinition.getActivities());
+ recurse(activities, triggerTaskIndex);
+ }
+
+ /**
+ * Helper method that recurses (into subprocesses) over all the listed activities.
+ *
+ * @param activities a list of workflow activities
+ * @param triggerTaskIndex the index of the next trigger task (mutable)
+ */
+ private void recurse(List<ActivityImpl> activities, AtomicInteger triggerTaskIndex) {
+ for (ActivityImpl activity : activities) {
+ String type = (String) activity.getProperty("type");
+
+ if ("callActivity".equals(type)) {
+ // Add a WorkflowExceptionResetListener to clear the WorkflowException
+ // variable when each Call Activity starts.
+
+ activity.addListener(ExecutionListener.EVENTNAME_START, new WorkflowExceptionResetListener());
+
+ // Add a WorkflowExceptionTriggerTask after the call activity.
+ // It must be a task because a listener cannot be used to generate
+ // an event. Throwing BpmnError from an execution listener will
+ // cause the process to die.
+
+ List<PvmTransition> outTransitions = new ArrayList<>(activity.getOutgoingTransitions());
+
+ for (PvmTransition transition : outTransitions) {
+ String triggerTaskId = "WorkflowExceptionTriggerTask_" + triggerTaskIndex;
+
+ ActivityImpl triggerTask = activity.getFlowScope().createActivity(triggerTaskId);
+
+ ClassDelegateActivityBehavior behavior = new ClassDelegateActivityBehavior(
+ WorkflowExceptionTriggerTask.class.getName(), new ArrayList<>(0));
+
+ triggerTask.setActivityBehavior(behavior);
+ triggerTask.setName("Workflow Exception Trigger Task " + triggerTaskIndex);
+ triggerTaskIndex.getAndIncrement();
+
+ TransitionImpl transitionImpl = (TransitionImpl) transition;
+ TransitionImpl triggerTaskOutTransition = triggerTask.createOutgoingTransition();
+ triggerTaskOutTransition.setDestination((ActivityImpl) transitionImpl.getDestination());
+ transitionImpl.setDestination(triggerTask);
+ }
+ } else if ("subProcess".equals(type)) {
+ recurse(new ArrayList<>(activity.getActivities()), triggerTaskIndex);
+ }
+ }
+ }
+ }
/**
- * If there is a WorkflowException object in the execution, this method
- * removes it (saving a copy of it in a different variable).
+ * If there is a WorkflowException object in the execution, this method removes it (saving a copy of it in a
+ * different variable).
*/
- public static class WorkflowExceptionResetListener implements ExecutionListener {
- public void notify(DelegateExecution execution) throws Exception {
- Object workflowException = execution.getVariable("WorkflowException");
+ public static class WorkflowExceptionResetListener implements ExecutionListener {
+ public void notify(DelegateExecution execution) throws Exception {
+ Object workflowException = execution.getVariable("WorkflowException");
- if (workflowException instanceof WorkflowException) {
- int index = 1;
- String saveName = "SavedWorkflowException" + index;
- while (execution.getVariable(saveName) != null) {
- saveName = "SavedWorkflowException" + (++index);
- }
+ if (workflowException instanceof WorkflowException) {
+ int index = 1;
+ String saveName = "SavedWorkflowException" + index;
+ while (execution.getVariable(saveName) != null) {
+ saveName = "SavedWorkflowException" + (++index);
+ }
- logger.debug("WorkflowExceptionResetTask is moving WorkflowException to " + saveName);
+ logger.debug("WorkflowExceptionResetTask is moving WorkflowException to " + saveName);
- execution.setVariable(saveName, workflowException);
- execution.setVariable("WorkflowException", null);
- }
- }
- }
+ execution.setVariable(saveName, workflowException);
+ execution.setVariable("WorkflowException", null);
+ }
+ }
+ }
/**
- * Generates an MSOWorkflowException event if there is a WorkflowException
- * object in the execution.
+ * Generates an MSOWorkflowException event if there is a WorkflowException object in the execution.
*/
- public static class WorkflowExceptionTriggerTask implements JavaDelegate {
- public void execute(DelegateExecution execution) throws Exception {
- if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
- logger.debug("WorkflowExceptionTriggerTask is generating a MSOWorkflowException event");
- throw new BpmnError("MSOWorkflowException");
- }
- }
- }
+ public static class WorkflowExceptionTriggerTask implements JavaDelegate {
+ public void execute(DelegateExecution execution) throws Exception {
+ if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
+ logger.debug("WorkflowExceptionTriggerTask is generating a MSOWorkflowException event");
+ throw new BpmnError("MSOWorkflowException");
+ }
+ }
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/CXFConfiguration.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/CXFConfiguration.java
index cb20ded8de..6572beaba9 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/CXFConfiguration.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/CXFConfiguration.java
@@ -23,9 +23,7 @@
package org.onap.so.bpmn.infrastructure;
import java.util.Arrays;
-
import javax.xml.ws.Endpoint;
-
import org.apache.cxf.Bus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.feature.LoggingFeature;
@@ -47,45 +45,44 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
@Configuration
public class CXFConfiguration {
-
- private static final Logger logger = LoggerFactory.getLogger(CXFConfiguration.class);
-
+
+ private static final Logger logger = LoggerFactory.getLogger(CXFConfiguration.class);
+
+ @Autowired
+ private Bus bus;
+
+ @Autowired
+ private WorkflowMessageResource wmr;
+
+ @Autowired
+ private WorkflowResource workflowResource;
+
+ @Autowired
+ private WorkflowAsyncResource workflowAsyncResource;
+
@Autowired
- private Bus bus;
-
- @Autowired
- private WorkflowMessageResource wmr;
-
- @Autowired
- private WorkflowResource workflowResource;
-
- @Autowired
- private WorkflowAsyncResource workflowAsyncResource;
-
- @Autowired
- private JaxRsFilterLogging jaxRsFilterLogging;
-
- @Autowired
- private ObjectMapper mapper;
-
- @Autowired
- private SDNCCallbackAdapterPortType sdncAdapterCallbackServiceImpl;
-
- @Autowired
- private VnfAdapterNotify vnfAdapterNotifyServiceImpl;
-
- @Bean
+ private JaxRsFilterLogging jaxRsFilterLogging;
+
+ @Autowired
+ private ObjectMapper mapper;
+
+ @Autowired
+ private SDNCCallbackAdapterPortType sdncAdapterCallbackServiceImpl;
+
+ @Autowired
+ private VnfAdapterNotify vnfAdapterNotifyServiceImpl;
+
+ @Bean
public ServletRegistrationBean cxfServlet() {
return new ServletRegistrationBean(new CXFServlet(), "/mso/*");
}
-
+
@Bean
public Endpoint vnfAdapterCallback() {
EndpointImpl endpoint = new EndpointImpl(bus, vnfAdapterNotifyServiceImpl);
@@ -95,7 +92,7 @@ public class CXFConfiguration {
endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor());
return endpoint;
}
-
+
@Bean
public Endpoint sndcAdapterCallback() {
EndpointImpl endpoint = new EndpointImpl(bus, sdncAdapterCallbackServiceImpl);
@@ -105,22 +102,22 @@ public class CXFConfiguration {
endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor());
return endpoint;
}
-
+
@Bean
public Server rsServer() {
JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
endpoint.setBus(bus);
endpoint.setServiceBeans(Arrays.<Object>asList(wmr, workflowResource, workflowAsyncResource));
- endpoint.setAddress("/");
+ endpoint.setAddress("/");
endpoint.setFeatures(Arrays.asList(createSwaggerFeature(), new LoggingFeature()));
- endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(mapper),jaxRsFilterLogging));
-
+ endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(mapper), jaxRsFilterLogging));
+
return endpoint.create();
}
@Bean
public Swagger2Feature createSwaggerFeature() {
- Swagger2Feature swagger2Feature= new Swagger2Feature();
+ Swagger2Feature swagger2Feature = new Swagger2Feature();
swagger2Feature.setPrettyPrint(true);
swagger2Feature.setTitle("SO Orchestration Application");
swagger2Feature.setContact("The ONAP SO team");
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java
index af9ab2899e..bd430fd679 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java
@@ -24,7 +24,6 @@ package org.onap.so.bpmn.infrastructure;
import java.util.List;
import java.util.concurrent.Executor;
-
import org.camunda.bpm.application.PostDeploy;
import org.camunda.bpm.application.PreUndeploy;
import org.camunda.bpm.application.ProcessApplicationInfo;
@@ -51,55 +50,53 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@SpringBootApplication
@EnableAsync
-@ComponentScan(basePackages = { "org.onap" }, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class, excludeFilters = {
- @Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class) })
+@ComponentScan(basePackages = {"org.onap"}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class,
+ excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
public class MSOInfrastructureApplication {
- private static final Logger logger = LoggerFactory.getLogger(MSOInfrastructureApplication.class);
+ private static final Logger logger = LoggerFactory.getLogger(MSOInfrastructureApplication.class);
- @Value("${mso.async.core-pool-size}")
- private int corePoolSize;
+ @Value("${mso.async.core-pool-size}")
+ private int corePoolSize;
- @Value("${mso.async.max-pool-size}")
- private int maxPoolSize;
+ @Value("${mso.async.max-pool-size}")
+ private int maxPoolSize;
- @Value("${mso.async.queue-capacity}")
- private int queueCapacity;
+ @Value("${mso.async.queue-capacity}")
+ private int queueCapacity;
- private static final String LOGS_DIR = "logs_dir";
+ private static final String LOGS_DIR = "logs_dir";
- private static void setLogsDir() {
- if (System.getProperty(LOGS_DIR) == null) {
- System.getProperties().setProperty(LOGS_DIR, "./logs/bpmn/");
- }
- }
+ private static void setLogsDir() {
+ if (System.getProperty(LOGS_DIR) == null) {
+ System.getProperties().setProperty(LOGS_DIR, "./logs/bpmn/");
+ }
+ }
- public static void main(String... args) {
- SpringApplication.run(MSOInfrastructureApplication.class, args);
- System.getProperties().setProperty("mso.config.path", ".");
- setLogsDir();
- }
+ public static void main(String... args) {
+ SpringApplication.run(MSOInfrastructureApplication.class, args);
+ System.getProperties().setProperty("mso.config.path", ".");
+ setLogsDir();
+ }
- @PostDeploy
- public void postDeploy(ProcessEngine processEngineInstance) {
- }
+ @PostDeploy
+ public void postDeploy(ProcessEngine processEngineInstance) {}
- @PreUndeploy
- public void cleanup(ProcessEngine processEngine, ProcessApplicationInfo processApplicationInfo,
- List<ProcessEngine> processEngines) {
- }
+ @PreUndeploy
+ public void cleanup(ProcessEngine processEngine, ProcessApplicationInfo processApplicationInfo,
+ List<ProcessEngine> processEngines) {}
- @Bean
- @Primary
- public Executor asyncExecutor() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setTaskDecorator(new MDCTaskDecorator());
- executor.setCorePoolSize(corePoolSize);
- executor.setMaxPoolSize(maxPoolSize);
- executor.setQueueCapacity(queueCapacity);
- executor.setThreadNamePrefix("Camunda-");
- executor.initialize();
- return executor;
- }
+ @Bean
+ @Primary
+ public Executor asyncExecutor() {
+ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+ executor.setTaskDecorator(new MDCTaskDecorator());
+ executor.setCorePoolSize(corePoolSize);
+ executor.setMaxPoolSize(maxPoolSize);
+ executor.setQueueCapacity(queueCapacity);
+ executor.setThreadNamePrefix("Camunda-");
+ executor.initialize();
+ return executor;
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java
index ad9e210452..c2af155d51 100644
--- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java
+++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java
@@ -31,22 +31,19 @@ import org.springframework.util.StringUtils;
@EnableWebSecurity
public class WebSecurityConfigImpl extends WebSecurityConfig {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf().disable()
- .authorizeRequests()
- .antMatchers("/manage/health","/manage/info").permitAll()
- .antMatchers("/async/services/**", "/workflow/services/*", "/SDNCAdapterCallbackService", "/WorkflowMessage", "/vnfAdapterNotify", "/vnfAdapterRestNotify")
- .hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),",").toString())
- .and()
- .httpBasic();
- }
-
- @Override
- public void configure(WebSecurity web) throws Exception {
- super.configure(web);
- StrictHttpFirewall firewall = new MSOSpringFirewall();
- web.httpFirewall(firewall);
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll()
+ .antMatchers("/async/services/**", "/workflow/services/*", "/SDNCAdapterCallbackService",
+ "/WorkflowMessage", "/vnfAdapterNotify", "/vnfAdapterRestNotify")
+ .hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",").toString()).and().httpBasic();
+ }
+
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ super.configure(web);
+ StrictHttpFirewall firewall = new MSOSpringFirewall();
+ web.httpFirewall(firewall);
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/RequestHeaderTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/RequestHeaderTest.java
index e56b45f19d..b185f80aaf 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/RequestHeaderTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/RequestHeaderTest.java
@@ -1,46 +1,40 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR 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 static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.bpmn.common.adapter.sdnc.RequestHeader;
-public class RequestHeaderTest{
- RequestHeader rh = new RequestHeader();
+public class RequestHeaderTest {
+ RequestHeader rh = new RequestHeader();
- @Test
- public void testRequestHeader() {
- rh.setRequestId("requestId");
- rh.setSvcInstanceId("svcInstanceId");
- rh.setSvcAction("svcAction");
- rh.setSvcOperation("svcOperation");
- rh.setCallbackUrl("callbackUrl");
- rh.setMsoAction("msoAction");
- assertEquals(rh.getRequestId(), "requestId");
- assertEquals(rh.getSvcInstanceId(), "svcInstanceId");
- assertEquals(rh.getSvcAction(), "svcAction");
- assertEquals(rh.getSvcOperation(), "svcOperation");
- assertEquals(rh.getCallbackUrl(), "callbackUrl");
- assertEquals(rh.getMsoAction(), "msoAction");
- assert(rh.toString()!=null);
- }
+ @Test
+ public void testRequestHeader() {
+ rh.setRequestId("requestId");
+ rh.setSvcInstanceId("svcInstanceId");
+ rh.setSvcAction("svcAction");
+ rh.setSvcOperation("svcOperation");
+ rh.setCallbackUrl("callbackUrl");
+ rh.setMsoAction("msoAction");
+ assertEquals(rh.getRequestId(), "requestId");
+ assertEquals(rh.getSvcInstanceId(), "svcInstanceId");
+ assertEquals(rh.getSvcAction(), "svcAction");
+ assertEquals(rh.getSvcOperation(), "svcOperation");
+ assertEquals(rh.getCallbackUrl(), "callbackUrl");
+ assertEquals(rh.getMsoAction(), "msoAction");
+ assert (rh.toString() != null);
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/SDNCAdapterCallbackRequestTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/SDNCAdapterCallbackRequestTest.java
index 884c2ac9c6..7ce82810be 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/SDNCAdapterCallbackRequestTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/SDNCAdapterCallbackRequestTest.java
@@ -1,44 +1,38 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import org.junit.Test;
import org.onap.so.bpmn.common.adapter.sdnc.CallbackHeader;
import org.onap.so.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest;
-public class SDNCAdapterCallbackRequestTest{
-
- SDNCAdapterCallbackRequest sdnccall = new SDNCAdapterCallbackRequest();
- CallbackHeader cbh = new CallbackHeader();
- String o = "test";
+public class SDNCAdapterCallbackRequestTest {
+
+ SDNCAdapterCallbackRequest sdnccall = new SDNCAdapterCallbackRequest();
+ CallbackHeader cbh = new CallbackHeader();
+ String o = "test";
- @Test
- public void testSDNCAdapterCallbackRequest() {
- sdnccall.setCallbackHeader(cbh);
- sdnccall.setRequestData(o);
- assertEquals(sdnccall.getCallbackHeader(), cbh);
- assertEquals(sdnccall.getRequestData(), o);
- assertNotNull(sdnccall.toString());
- }
+ @Test
+ public void testSDNCAdapterCallbackRequest() {
+ sdnccall.setCallbackHeader(cbh);
+ sdnccall.setRequestData(o);
+ assertEquals(sdnccall.getCallbackHeader(), cbh);
+ assertEquals(sdnccall.getRequestData(), o);
+ assertNotNull(sdnccall.toString());
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/SDNCAdapterRequestTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/SDNCAdapterRequestTest.java
index 79bffe40d0..8a976711c6 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/SDNCAdapterRequestTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/SDNCAdapterRequestTest.java
@@ -1,41 +1,35 @@
/*
-* ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 TechMahindra
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 TechMahindra
+ * ================================================================================ Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR 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 static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.bpmn.common.adapter.sdnc.RequestHeader;
import org.onap.so.bpmn.common.adapter.sdnc.SDNCAdapterRequest;
public class SDNCAdapterRequestTest {
-
- SDNCAdapterRequest adapter = new SDNCAdapterRequest();
- RequestHeader rh = new RequestHeader();
- Object o = new Object();
- @Test
- public void testSDNCAdapterRequest() {
- adapter.setRequestHeader(rh);
- adapter.setRequestData(o);
- assertEquals(adapter.getRequestHeader(), rh);
- assertEquals(adapter.getRequestData(), o);
- }
+ SDNCAdapterRequest adapter = new SDNCAdapterRequest();
+ RequestHeader rh = new RequestHeader();
+ Object o = new Object();
+
+ @Test
+ public void testSDNCAdapterRequest() {
+ adapter.setRequestHeader(rh);
+ adapter.setRequestData(o);
+ assertEquals(adapter.getRequestHeader(), rh);
+ assertEquals(adapter.getRequestData(), o);
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/BaseIntegrationTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/BaseIntegrationTest.java
index fc21ff905d..2176dd885b 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/BaseIntegrationTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/BaseIntegrationTest.java
@@ -31,7 +31,6 @@ import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
-
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
@@ -40,19 +39,19 @@ import com.github.tomakehurst.wiremock.client.WireMock;
@ActiveProfiles("test")
@ContextConfiguration
@AutoConfigureWireMock(port = 0)
-public abstract class BaseIntegrationTest extends WorkflowTest {
- @Autowired
- BPMNUtil bpmnUtil;
+public abstract class BaseIntegrationTest extends WorkflowTest {
+ @Autowired
+ BPMNUtil bpmnUtil;
+
+ @Value("${wiremock.server.port}")
+ protected String wiremockPort;
+
+ @Autowired
+ protected WireMockServer wireMockServer;
- @Value("${wiremock.server.port}")
- protected String wiremockPort;
-
- @Autowired
- protected WireMockServer wireMockServer;
-
- @After
- public void baseAfterTest() {
- wireMockServer.resetAll();
- }
+ @After
+ public void baseAfterTest() {
+ wireMockServer.resetAll();
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/InfraEmbeddedMariaDbConfig.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/InfraEmbeddedMariaDbConfig.java
index c28a86c49a..0a532663b8 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/InfraEmbeddedMariaDbConfig.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/InfraEmbeddedMariaDbConfig.java
@@ -19,6 +19,7 @@
*/
package org.onap.so.bpmn;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
@@ -35,38 +36,27 @@ import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
-
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager",
- basePackages = { "org.onap.so.db.request.data.repository"}
-)
+@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory",
+ transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"})
@Profile({"test"})
public class InfraEmbeddedMariaDbConfig {
@Primary
@Bean(name = "requestEntityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.request.beans")
- .persistenceUnit("requestDB")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB")
.build();
}
@Bean(name = "requestTransactionManager")
public PlatformTransactionManager transactionManager(
- @Qualifier("requestEntityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
+ @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/IntegrationTestSuite.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/IntegrationTestSuite.java
index f65cadae3c..bc002c7022 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/IntegrationTestSuite.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/IntegrationTestSuite.java
@@ -27,6 +27,6 @@ import org.junit.runner.RunWith;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses({"**/*IT.class"})
public class IntegrationTestSuite {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/BPMNUtil.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/BPMNUtil.java
index 5f0722aa3d..f417a550d1 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/BPMNUtil.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/BPMNUtil.java
@@ -25,14 +25,11 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.ws.rs.core.Response;
-
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.ProcessEngineServices;
import org.camunda.bpm.engine.RuntimeService;
@@ -52,306 +49,303 @@ import org.springframework.stereotype.Component;
@Component
public class BPMNUtil {
- private static WorkflowAsyncResource workflowResource;
-
- @Autowired
- public void setWorkflowResource(WorkflowAsyncResource workflowResource) {
- BPMNUtil.workflowResource = workflowResource;
- }
-
- public static String getVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) {
- String pID = getProcessInstanceId(processEngineServices,
- processDefinitionID);
- return getVariable( processEngineServices, processDefinitionID, name, pID);
- }
-
- public static String getVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name, String processInstanceId) {
- assertProcessInstanceFinished(processEngineServices, processInstanceId);
- HistoricVariableInstance responseData = processEngineServices.getHistoryService()
- .createHistoricVariableInstanceQuery().processInstanceId(processInstanceId)
- .variableName(name)
- .singleResult();
-
- if (responseData != null) {
- return (responseData.getValue() != null ? responseData.getValue().toString(): null);
- }
- return null;
- }
-
- /*
- @SuppressWarnings("unchecked")
- public static <T extends Object> T getRawVariable(HistoryService historyService, String processDefinitionID, String name) {
- //String pID = getProcessInstanceId(processEngineServices,
- // processDefinitionID);
- assertProcessInstanceFinished(historyService, pID);
- Object responseData = historyService
- .createHistoricVariableInstanceQuery().processInstanceId(pID)
- .variableName(name)
- .singleResult()
- .getValue();
- return (T) responseData;
- }
- */
-
- @SuppressWarnings("unchecked")
- public static <T> T getRawVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) {
- String pID = getProcessInstanceId(processEngineServices,
- processDefinitionID);
- return getRawVariable( processEngineServices, processDefinitionID, name, pID);
- }
-
- @SuppressWarnings("unchecked")
- public static <T> T getRawVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name, String processInstanceId) {
- assertProcessInstanceFinished(processEngineServices, processInstanceId);
- Object responseData = processEngineServices.getHistoryService()
- .createHistoricVariableInstanceQuery().processInstanceId(processInstanceId)
- .variableName(name)
- .singleResult()
- .getValue();
- return (T) responseData;
- }
-
-
- public static void assertAnyProcessInstanceFinished(ProcessEngineServices processEngineServices, String processDefinitionID) {
- String pID = getProcessInstanceId(processEngineServices,
- processDefinitionID);
- assertNotNull(pID);
- assertTrue(processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count() > 0);
- }
-
- public static void assertNoProcessInstance(ProcessEngineServices processEngineServices, String processDefinitionID) {
- assertNull(getProcessInstanceId(processEngineServices, processDefinitionID));
- }
-
- public static void assertProcessInstanceFinished(HistoryService historyService, String pid) {
- assertEquals(1, historyService.createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count());
- }
-
- public static void assertProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) {
- assertEquals(1, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count());
- }
-
- public static void assertProcessInstanceNotFinished(ProcessEngineServices processEngineServices, String processDefinitionID) {
- String pID = getProcessInstanceId(processEngineServices,
- processDefinitionID);
- assertEquals(0, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count());
- }
-
- private static String getProcessInstanceId(
- ProcessEngineServices processEngineServices, String processDefinitionID) {
- List<HistoricProcessInstance> historyList = processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().list();
- String pID = null;
- for (HistoricProcessInstance hInstance: historyList) {
- if (hInstance.getProcessDefinitionKey().equals(processDefinitionID)) {
- pID = hInstance.getId();
- break;
- }
- }
- return pID;
- }
-
- public static void cleanHistory(ProcessEngineServices processEngineServices) {
- List<HistoricProcessInstance> historyList = processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().list();
- List<String> pidList = new ArrayList<>();
- for (HistoricProcessInstance hInstance : historyList) {
- pidList.add(hInstance.getId());
- }
- if (pidList.size() > 0) {
- processEngineServices.getHistoryService().deleteHistoricProcessInstances(pidList);
- }
- }
-
- private static String getProcessInstanceId(
- HistoryService historyService, String processDefinitionID) {
- List<HistoricProcessInstance> historyList = historyService.createHistoricProcessInstanceQuery().list();
- String pID = null;
- for (HistoricProcessInstance hInstance: historyList) {
- if (hInstance.getProcessDefinitionKey().equals(processDefinitionID)) {
- pID = hInstance.getId();
- break;
- }
- }
- return pID;
- }
-
- public static boolean isProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) {
- return processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count() == 1 ? true: false;
- }
-
-
- private static void buildVariable(String key, String value, Map<String,Object> variableValueType) {
- Map<String, Object> host = new HashMap<>();
- host.put("value", value);
- host.put("type", "String");
- variableValueType.put(key, host);
- }
-
- public static WorkflowResponse executeWorkFlow(ProcessEngineServices processEngineServices, String processKey, Map<String,String> variables) {
- VariableMapImpl variableMap = new VariableMapImpl();
-
- Map<String, Object> variableValueType = new HashMap<>();
- for (String key : variables.keySet()) {
- buildVariable(key, variables.get(key), variableValueType);
- }
- buildVariable("mso-service-request-timeout","600", variableValueType);
- variableMap.put("variables", variableValueType);
-
- workflowResource.setProcessEngineServices4junit(processEngineServices);
- Response response = workflowResource.startProcessInstanceByKey(
- processKey, variableMap);
- WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity();
- return workflowResponse;
- }
-
- public static WorkflowResponse executeWorkFlow(RuntimeService runtimeService, String processKey, Map<String,String> variables, WorkflowResource workflowResource) {
-
- VariableMapImpl variableMap = new VariableMapImpl();
-
- Map<String, Object> variableValueType = new HashMap<String, Object>();
- for (String key : variables.keySet()) {
- buildVariable(key, variables.get(key), variableValueType);
- }
- buildVariable("mso-service-request-timeout","600", variableValueType);
- variableMap.put("variables", variableValueType);
-
-
- Response response = workflowResource.startProcessInstanceByKey(
- processKey, variableMap);
- WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity();
- return workflowResponse;
- }
-
- //Check the runtime service to see whether the process is completed
- public static void waitForWorkflowToFinish(ProcessEngineServices processEngineServices, String pid) throws InterruptedException {
- // Don't wait forever
- long waitTime = 120000;
- long endTime = System.currentTimeMillis() + waitTime;
-
- while (true) {
- if (processEngineServices.getRuntimeService().createProcessInstanceQuery().processInstanceId(pid).singleResult() == null) {
- break;
- }
-
- if (System.currentTimeMillis() >= endTime) {
- fail("Process " + pid + " did not finish in " + waitTime + "ms");
- }
-
- Thread.sleep(200);
- }
- }
-
-
- //Check the runtime service to see whether the process is completed
- public static void waitForWorkflowToFinish(RuntimeService runtimeService, String pid) throws InterruptedException {
- // Don't wait forever
- long waitTime = 120000;
- long endTime = System.currentTimeMillis() + waitTime;
-
- while (true) {
- if (runtimeService.createProcessInstanceQuery().processInstanceId(pid).singleResult() == null) {
- break;
- }
-
- if (System.currentTimeMillis() >= endTime) {
- fail("Process " + pid + " did not finish in " + waitTime + "ms");
- }
-
- Thread.sleep(200);
- }
- }
-
-
- /**
- * Executes the Asynchronous workflow in synchronous fashion and returns the WorkflowResponse object
- * @param processEngineServices
- * @param processKey
- * @param variables
- * @return
- * @throws InterruptedException
- */
- public static WorkflowResponse executeAsyncWorkflow(ProcessEngineServices processEngineServices, String processKey, Map<String,String> variables) throws InterruptedException {
- ProcessThread pthread = new ProcessThread(processKey, processEngineServices, variables);
- pthread.start();
- BPMNUtil.assertProcessInstanceNotFinished(processEngineServices, processKey);
- String pid = getProcessInstanceId(processEngineServices, processKey);
- //Caution: If there is a problem with workflow, this may wait for ever
- while (true) {
- pid = getProcessInstanceId(processEngineServices, processKey);
- if (!isProcessInstanceFinished(processEngineServices,pid)) {
- Thread.sleep(200);
- } else{
- break;
- }
- }
- //need to retrieve for second time ?
- pid = getProcessInstanceId(processEngineServices, processKey);
- waitForWorkflowToFinish(processEngineServices, pid);
- return pthread.workflowResponse;
- }
-
- /**
- * Execute workflow using async resource
- * @param processEngineServices
- * @param processKey
- * @param asyncResponse
- * @param variables
- * @throws InterruptedException
- */
- private static void executeAsyncFlow(ProcessEngineServices processEngineServices, String processKey, Map<String,String> variables) throws InterruptedException {
- VariableMapImpl variableMap = new VariableMapImpl();
-
- Map<String, Object> variableValueType = new HashMap<>();
- for (String key : variables.keySet()) {
- buildVariable(key, variables.get(key), variableValueType);
- }
- buildVariable("mso-service-request-timeout","600", variableValueType);
- variableMap.put("variables", variableValueType);
-
- workflowResource.setProcessEngineServices4junit(processEngineServices);
- workflowResource.startProcessInstanceByKey(processKey, variableMap);
- }
-
- /**
- * Helper class which executes workflow in a thread
- *
- */
- static class ProcessThread extends Thread {
-
- public WorkflowResponse workflowResponse = null;
- public String processKey;
- public boolean started;
- public ProcessEngineServices processEngineServices;
- public Map<String,String> variables;
-
- public ProcessThread(String processKey, ProcessEngineServices processEngineServices, Map<String,String> variables) {
- this.processKey = processKey;
- this.processEngineServices = processEngineServices;
- this.variables = variables;
- }
-
- public void run() {
- started = true;
- /*doAnswer(new Answer<Void>() {
- public Void answer(InvocationOnMock invocation) {
- Response response = (Response) invocation.getArguments()[0];
- try {
- workflowResponse = (WorkflowResponse) response.getEntity();
- } catch (ClassCastException e) {
- String workflowResponseString = (String)response.getEntity();
- workflowResponse = new WorkflowResponse();
- workflowResponse.setResponse(workflowResponseString);
- workflowResponse.setMessageCode(200);
- }
- return null;
- }
- }).when(asyncResponse).setResponse(any(Response.class));
- */
- try {
- executeAsyncFlow(processEngineServices, processKey, variables);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
+ private static WorkflowAsyncResource workflowResource;
+
+ @Autowired
+ public void setWorkflowResource(WorkflowAsyncResource workflowResource) {
+ BPMNUtil.workflowResource = workflowResource;
+ }
+
+ public static String getVariable(ProcessEngineServices processEngineServices, String processDefinitionID,
+ String name) {
+ String pID = getProcessInstanceId(processEngineServices, processDefinitionID);
+ return getVariable(processEngineServices, processDefinitionID, name, pID);
+ }
+
+ public static String getVariable(ProcessEngineServices processEngineServices, String processDefinitionID,
+ String name, String processInstanceId) {
+ assertProcessInstanceFinished(processEngineServices, processInstanceId);
+ HistoricVariableInstance responseData =
+ processEngineServices.getHistoryService().createHistoricVariableInstanceQuery()
+ .processInstanceId(processInstanceId).variableName(name).singleResult();
+
+ if (responseData != null) {
+ return (responseData.getValue() != null ? responseData.getValue().toString() : null);
+ }
+ return null;
+ }
+
+ /*
+ * @SuppressWarnings("unchecked") public static <T extends Object> T getRawVariable(HistoryService historyService,
+ * String processDefinitionID, String name) { //String pID = getProcessInstanceId(processEngineServices, //
+ * processDefinitionID); assertProcessInstanceFinished(historyService, pID); Object responseData = historyService
+ * .createHistoricVariableInstanceQuery().processInstanceId(pID) .variableName(name) .singleResult() .getValue();
+ * return (T) responseData; }
+ */
+
+ @SuppressWarnings("unchecked")
+ public static <T> T getRawVariable(ProcessEngineServices processEngineServices, String processDefinitionID,
+ String name) {
+ String pID = getProcessInstanceId(processEngineServices, processDefinitionID);
+ return getRawVariable(processEngineServices, processDefinitionID, name, pID);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> T getRawVariable(ProcessEngineServices processEngineServices, String processDefinitionID,
+ String name, String processInstanceId) {
+ assertProcessInstanceFinished(processEngineServices, processInstanceId);
+ Object responseData = processEngineServices.getHistoryService().createHistoricVariableInstanceQuery()
+ .processInstanceId(processInstanceId).variableName(name).singleResult().getValue();
+ return (T) responseData;
+ }
+
+
+ public static void assertAnyProcessInstanceFinished(ProcessEngineServices processEngineServices,
+ String processDefinitionID) {
+ String pID = getProcessInstanceId(processEngineServices, processDefinitionID);
+ assertNotNull(pID);
+ assertTrue(processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID)
+ .finished().count() > 0);
+ }
+
+ public static void assertNoProcessInstance(ProcessEngineServices processEngineServices,
+ String processDefinitionID) {
+ assertNull(getProcessInstanceId(processEngineServices, processDefinitionID));
+ }
+
+ public static void assertProcessInstanceFinished(HistoryService historyService, String pid) {
+ assertEquals(1, historyService.createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count());
+ }
+
+ public static void assertProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) {
+ assertEquals(1, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery()
+ .processInstanceId(pid).finished().count());
+ }
+
+ public static void assertProcessInstanceNotFinished(ProcessEngineServices processEngineServices,
+ String processDefinitionID) {
+ String pID = getProcessInstanceId(processEngineServices, processDefinitionID);
+ assertEquals(0, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery()
+ .processInstanceId(pID).finished().count());
+ }
+
+ private static String getProcessInstanceId(ProcessEngineServices processEngineServices,
+ String processDefinitionID) {
+ List<HistoricProcessInstance> historyList =
+ processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().list();
+ String pID = null;
+ for (HistoricProcessInstance hInstance : historyList) {
+ if (hInstance.getProcessDefinitionKey().equals(processDefinitionID)) {
+ pID = hInstance.getId();
+ break;
+ }
+ }
+ return pID;
+ }
+
+ public static void cleanHistory(ProcessEngineServices processEngineServices) {
+ List<HistoricProcessInstance> historyList =
+ processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().list();
+ List<String> pidList = new ArrayList<>();
+ for (HistoricProcessInstance hInstance : historyList) {
+ pidList.add(hInstance.getId());
+ }
+ if (pidList.size() > 0) {
+ processEngineServices.getHistoryService().deleteHistoricProcessInstances(pidList);
+ }
+ }
+
+ private static String getProcessInstanceId(HistoryService historyService, String processDefinitionID) {
+ List<HistoricProcessInstance> historyList = historyService.createHistoricProcessInstanceQuery().list();
+ String pID = null;
+ for (HistoricProcessInstance hInstance : historyList) {
+ if (hInstance.getProcessDefinitionKey().equals(processDefinitionID)) {
+ pID = hInstance.getId();
+ break;
+ }
+ }
+ return pID;
+ }
+
+ public static boolean isProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) {
+ return processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid)
+ .finished().count() == 1 ? true : false;
+ }
+
+
+ private static void buildVariable(String key, String value, Map<String, Object> variableValueType) {
+ Map<String, Object> host = new HashMap<>();
+ host.put("value", value);
+ host.put("type", "String");
+ variableValueType.put(key, host);
+ }
+
+ public static WorkflowResponse executeWorkFlow(ProcessEngineServices processEngineServices, String processKey,
+ Map<String, String> variables) {
+ VariableMapImpl variableMap = new VariableMapImpl();
+
+ Map<String, Object> variableValueType = new HashMap<>();
+ for (String key : variables.keySet()) {
+ buildVariable(key, variables.get(key), variableValueType);
+ }
+ buildVariable("mso-service-request-timeout", "600", variableValueType);
+ variableMap.put("variables", variableValueType);
+
+ workflowResource.setProcessEngineServices4junit(processEngineServices);
+ Response response = workflowResource.startProcessInstanceByKey(processKey, variableMap);
+ WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity();
+ return workflowResponse;
+ }
+
+ public static WorkflowResponse executeWorkFlow(RuntimeService runtimeService, String processKey,
+ Map<String, String> variables, WorkflowResource workflowResource) {
+
+ VariableMapImpl variableMap = new VariableMapImpl();
+
+ Map<String, Object> variableValueType = new HashMap<String, Object>();
+ for (String key : variables.keySet()) {
+ buildVariable(key, variables.get(key), variableValueType);
+ }
+ buildVariable("mso-service-request-timeout", "600", variableValueType);
+ variableMap.put("variables", variableValueType);
+
+
+ Response response = workflowResource.startProcessInstanceByKey(processKey, variableMap);
+ WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity();
+ return workflowResponse;
+ }
+
+ // Check the runtime service to see whether the process is completed
+ public static void waitForWorkflowToFinish(ProcessEngineServices processEngineServices, String pid)
+ throws InterruptedException {
+ // Don't wait forever
+ long waitTime = 120000;
+ long endTime = System.currentTimeMillis() + waitTime;
+
+ while (true) {
+ if (processEngineServices.getRuntimeService().createProcessInstanceQuery().processInstanceId(pid)
+ .singleResult() == null) {
+ break;
+ }
+
+ if (System.currentTimeMillis() >= endTime) {
+ fail("Process " + pid + " did not finish in " + waitTime + "ms");
+ }
+
+ Thread.sleep(200);
+ }
+ }
+
+
+ // Check the runtime service to see whether the process is completed
+ public static void waitForWorkflowToFinish(RuntimeService runtimeService, String pid) throws InterruptedException {
+ // Don't wait forever
+ long waitTime = 120000;
+ long endTime = System.currentTimeMillis() + waitTime;
+
+ while (true) {
+ if (runtimeService.createProcessInstanceQuery().processInstanceId(pid).singleResult() == null) {
+ break;
+ }
+
+ if (System.currentTimeMillis() >= endTime) {
+ fail("Process " + pid + " did not finish in " + waitTime + "ms");
+ }
+
+ Thread.sleep(200);
+ }
+ }
+
+
+ /**
+ * Executes the Asynchronous workflow in synchronous fashion and returns the WorkflowResponse object
+ *
+ * @param processEngineServices
+ * @param processKey
+ * @param variables
+ * @return
+ * @throws InterruptedException
+ */
+ public static WorkflowResponse executeAsyncWorkflow(ProcessEngineServices processEngineServices, String processKey,
+ Map<String, String> variables) throws InterruptedException {
+ ProcessThread pthread = new ProcessThread(processKey, processEngineServices, variables);
+ pthread.start();
+ BPMNUtil.assertProcessInstanceNotFinished(processEngineServices, processKey);
+ String pid = getProcessInstanceId(processEngineServices, processKey);
+ // Caution: If there is a problem with workflow, this may wait for ever
+ while (true) {
+ pid = getProcessInstanceId(processEngineServices, processKey);
+ if (!isProcessInstanceFinished(processEngineServices, pid)) {
+ Thread.sleep(200);
+ } else {
+ break;
+ }
+ }
+ // need to retrieve for second time ?
+ pid = getProcessInstanceId(processEngineServices, processKey);
+ waitForWorkflowToFinish(processEngineServices, pid);
+ return pthread.workflowResponse;
+ }
+
+ /**
+ * Execute workflow using async resource
+ *
+ * @param processEngineServices
+ * @param processKey
+ * @param asyncResponse
+ * @param variables
+ * @throws InterruptedException
+ */
+ private static void executeAsyncFlow(ProcessEngineServices processEngineServices, String processKey,
+ Map<String, String> variables) throws InterruptedException {
+ VariableMapImpl variableMap = new VariableMapImpl();
+
+ Map<String, Object> variableValueType = new HashMap<>();
+ for (String key : variables.keySet()) {
+ buildVariable(key, variables.get(key), variableValueType);
+ }
+ buildVariable("mso-service-request-timeout", "600", variableValueType);
+ variableMap.put("variables", variableValueType);
+
+ workflowResource.setProcessEngineServices4junit(processEngineServices);
+ workflowResource.startProcessInstanceByKey(processKey, variableMap);
+ }
+
+ /**
+ * Helper class which executes workflow in a thread
+ *
+ */
+ static class ProcessThread extends Thread {
+
+ public WorkflowResponse workflowResponse = null;
+ public String processKey;
+ public boolean started;
+ public ProcessEngineServices processEngineServices;
+ public Map<String, String> variables;
+
+ public ProcessThread(String processKey, ProcessEngineServices processEngineServices,
+ Map<String, String> variables) {
+ this.processKey = processKey;
+ this.processEngineServices = processEngineServices;
+ this.variables = variables;
+ }
+
+ public void run() {
+ started = true;
+ /*
+ * doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { Response response =
+ * (Response) invocation.getArguments()[0]; try { workflowResponse = (WorkflowResponse)
+ * response.getEntity(); } catch (ClassCastException e) { String workflowResponseString =
+ * (String)response.getEntity(); workflowResponse = new WorkflowResponse();
+ * workflowResponse.setResponse(workflowResponseString); workflowResponse.setMessageCode(200); } return
+ * null; } }).when(asyncResponse).setResponse(any(Response.class));
+ */
+ try {
+ executeAsyncFlow(processEngineServices, processKey, variables);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CompleteMsoProcessIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CompleteMsoProcessIT.java
index f528205d17..2be72184af 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CompleteMsoProcessIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CompleteMsoProcessIT.java
@@ -16,17 +16,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
import static org.onap.so.bpmn.common.BPMNUtil.waitForWorkflowToFinish;
import static org.onap.so.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB;
-
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.junit.Assert;
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
@@ -36,148 +34,140 @@ import org.onap.so.BaseIntegrationTest;
*/
public class CompleteMsoProcessIT extends BaseIntegrationTest {
-
- private void executeFlow(String inputRequestFile) throws InterruptedException {
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
- Map<String, Object> variables = new HashMap<>();
- variables.put("CompleteMsoProcessRequest",inputRequestFile);
- variables.put("mso-request-id", UUID.randomUUID().toString());
- String processId = invokeSubProcess( "CompleteMsoProcess", variables);
- waitForWorkflowToFinish(processEngine,processId);
- logEnd();
- }
-
- @Test
- public void msoCompletionRequestWithNotificationUrl_200() throws Exception {
- logStart();
-
- //Execute Flow
- executeFlow(gMsoCompletionRequestWithNotificationurl());
-
- //Verify Error
- String CMSO_ResponseCode = BPMNUtil.getVariable(processEngine, "CompleteMsoProcess", "CMSO_ResponseCode");
- Assert.assertEquals("200", CMSO_ResponseCode);
- Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngine, "CompleteMsoProcess", "CMSO_SuccessIndicator"));
- logEnd();
- }
-
- @Test
- public void msoCompletionRequestWithNoNotificationurl() throws Exception {
- logStart();
-
- //Execute Flow
- executeFlow(gMsoCompletionRequestWithNoNotificationurl());
-
- //Verify Error
- String CMSO_ResponseCode = BPMNUtil.getVariable(processEngine, "CompleteMsoProcess", "CMSO_ResponseCode");
- Assert.assertEquals("200", CMSO_ResponseCode);
- Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngine, "CompleteMsoProcess", "CMSO_SuccessIndicator"));
- logEnd();
- }
-
- @Test
- public void msoCompletionRequestWithNotificationurlNoRequestId() throws Exception {
- logStart();
-
- //Execute Flow
- executeFlow(gMsoCompletionRequestWithNotificationurlNoRequestId());
-
- //Verify Error
- String CMSO_ResponseCode = BPMNUtil.getVariable(processEngine, "CompleteMsoProcess", "CMSO_ResponseCode");
- Assert.assertEquals("200", CMSO_ResponseCode);
- Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngine, "CompleteMsoProcess", "CMSO_SuccessIndicator"));
- logEnd();
- }
-
- @Test
- public void msoCompletionRequestWithNoNotificationurlNoRequestId() throws Exception {
- logStart();
-
- //Execute Flow
- executeFlow(gMsoCompletionRequestWithNoNotificationurlNoRequestId());
-
- //Verify Error
- String CMSO_ResponseCode = BPMNUtil.getVariable(processEngine, "CompleteMsoProcess", "CMSO_ResponseCode");
- Assert.assertEquals("200", CMSO_ResponseCode);
- Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngine, "CompleteMsoProcess", "CMSO_SuccessIndicator"));
- logEnd();
- }
-
- public String gMsoCompletionRequestWithNotificationurl() {
- String xml = ""
- + "<sdncadapterworkflow:MsoCompletionRequest xmlns:ns=\"http://openecomp.org/mso/request/types/v1\" xmlns:sdncadapterworkflow=\"http://ecomp.openecomp.org.com/mso/workflow/schema/v1\">"
- + " <ns:request-information>"
- + " <ns:request-id>STUW105_5002</ns:request-id>"
- + " <ns:request-action>RequestAction</ns:request-action>"
- + " <ns:request-sub-action>COMPLETE</ns:request-sub-action>"
- + " <ns:source>SOURCE</ns:source>"
- + " <ns:notification-url>https://t3nap1a1.snt.bst.bls.com:9004/sdncontroller-sdncontroller-inbound-ws-war/sdncontroller-sdncontroller-inbound-ws.wsdl</ns:notification-url>"
- + " <ns:order-number>10205000</ns:order-number>"
- + " <ns:order-version>1</ns:order-version>"
- + " </ns:request-information>"
- + " <sdncadapterworkflow:mso-bpel-name>BPELNAME</sdncadapterworkflow:mso-bpel-name>"
- + "</sdncadapterworkflow:MsoCompletionRequest>";
-
- return xml;
- }
-
-
-
- public String gMsoCompletionRequestWithNoNotificationurl() {
- //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
- String xml = ""
- + "<sdncadapterworkflow:MsoCompletionRequest xmlns:ns=\"http://openecomp.org/mso/request/types/v1\" xmlns:sdncadapterworkflow=\"http://openecomp.org/mso/workflow/schema/v1\">"
- + " <ns:request-information>"
- + " <ns:request-id>STUW105_5002</ns:request-id>"
- + " <ns:request-action>RequestAction</ns:request-action>"
- + " <ns:request-sub-action>COMPLETE</ns:request-sub-action>"
- + " <ns:source>SOURCE</ns:source>"
- + " <ns:notification-url></ns:notification-url>"
- + " <ns:order-number>10205000</ns:order-number>"
- + " <ns:order-version>1</ns:order-version>"
- + " </ns:request-information>"
- + " <sdncadapterworkflow:mso-bpel-name>BPELNAME</sdncadapterworkflow:mso-bpel-name>"
- + "</sdncadapterworkflow:MsoCompletionRequest>";
-
- return xml;
- }
-
- public String gMsoCompletionRequestWithNoNotificationurlNoRequestId() {
- //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
- String xml = ""
- + "<sdncadapterworkflow:MsoCompletionRequest xmlns:ns=\"http://openecomp.org/mso/request/types/v1\" xmlns:sdncadapterworkflow=\"http://openecomp.org/mso/workflow/schema/v1\">"
- + " <ns:request-information>"
- + " <ns:request-id></ns:request-id>"
- + " <ns:request-action>RequestAction</ns:request-action>"
- + " <ns:request-sub-action>COMPLETE</ns:request-sub-action>"
- + " <ns:source>SOURCE</ns:source>"
- + " <ns:notification-url></ns:notification-url>"
- + " <ns:order-number>10205000</ns:order-number>"
- + " <ns:order-version>1</ns:order-version>"
- + " </ns:request-information>"
- + " <sdncadapterworkflow:mso-bpel-name>BPELNAME</sdncadapterworkflow:mso-bpel-name>"
- + "</sdncadapterworkflow:MsoCompletionRequest>";
-
- return xml;
- }
-
- public String gMsoCompletionRequestWithNotificationurlNoRequestId() {
- //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
- String xml = ""
- + "<sdncadapterworkflow:MsoCompletionRequest xmlns:ns=\"http://openecomp.org/mso/request/types/v1\" xmlns:sdncadapterworkflow=\"http://openecomp.org/mso/workflow/schema/v1\">"
- + " <ns:request-information>"
- + " <ns:request-id></ns:request-id>"
- + " <ns:request-action>RequestAction</ns:request-action>"
- + " <ns:request-sub-action>COMPLETE</ns:request-sub-action>"
- + " <ns:source>SOURCE</ns:source>"
- + " <ns:notification-url>https://t3nap1a1.snt.bst.bls.com:9004/sdncontroller-sdncontroller-inbound-ws-war/sdncontroller-sdncontroller-inbound-ws.wsdl</ns:notification-url>"
- + " <ns:order-number>10205000</ns:order-number>"
- + " <ns:order-version>1</ns:order-version>"
- + " </ns:request-information>"
- + " <sdncadapterworkflow:mso-bpel-name>BPELNAME</sdncadapterworkflow:mso-bpel-name>"
- + "</sdncadapterworkflow:MsoCompletionRequest>";
-
- return xml;
- }
+
+ private void executeFlow(String inputRequestFile) throws InterruptedException {
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("CompleteMsoProcessRequest", inputRequestFile);
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ String processId = invokeSubProcess("CompleteMsoProcess", variables);
+ waitForWorkflowToFinish(processEngine, processId);
+ logEnd();
+ }
+
+ @Test
+ public void msoCompletionRequestWithNotificationUrl_200() throws Exception {
+ logStart();
+
+ // Execute Flow
+ executeFlow(gMsoCompletionRequestWithNotificationurl());
+
+ // Verify Error
+ String CMSO_ResponseCode = BPMNUtil.getVariable(processEngine, "CompleteMsoProcess", "CMSO_ResponseCode");
+ Assert.assertEquals("200", CMSO_ResponseCode);
+ Assert.assertTrue(
+ (boolean) BPMNUtil.getRawVariable(processEngine, "CompleteMsoProcess", "CMSO_SuccessIndicator"));
+ logEnd();
+ }
+
+ @Test
+ public void msoCompletionRequestWithNoNotificationurl() throws Exception {
+ logStart();
+
+ // Execute Flow
+ executeFlow(gMsoCompletionRequestWithNoNotificationurl());
+
+ // Verify Error
+ String CMSO_ResponseCode = BPMNUtil.getVariable(processEngine, "CompleteMsoProcess", "CMSO_ResponseCode");
+ Assert.assertEquals("200", CMSO_ResponseCode);
+ Assert.assertTrue(
+ (boolean) BPMNUtil.getRawVariable(processEngine, "CompleteMsoProcess", "CMSO_SuccessIndicator"));
+ logEnd();
+ }
+
+ @Test
+ public void msoCompletionRequestWithNotificationurlNoRequestId() throws Exception {
+ logStart();
+
+ // Execute Flow
+ executeFlow(gMsoCompletionRequestWithNotificationurlNoRequestId());
+
+ // Verify Error
+ String CMSO_ResponseCode = BPMNUtil.getVariable(processEngine, "CompleteMsoProcess", "CMSO_ResponseCode");
+ Assert.assertEquals("200", CMSO_ResponseCode);
+ Assert.assertTrue(
+ (boolean) BPMNUtil.getRawVariable(processEngine, "CompleteMsoProcess", "CMSO_SuccessIndicator"));
+ logEnd();
+ }
+
+ @Test
+ public void msoCompletionRequestWithNoNotificationurlNoRequestId() throws Exception {
+ logStart();
+
+ // Execute Flow
+ executeFlow(gMsoCompletionRequestWithNoNotificationurlNoRequestId());
+
+ // Verify Error
+ String CMSO_ResponseCode = BPMNUtil.getVariable(processEngine, "CompleteMsoProcess", "CMSO_ResponseCode");
+ Assert.assertEquals("200", CMSO_ResponseCode);
+ Assert.assertTrue(
+ (boolean) BPMNUtil.getRawVariable(processEngine, "CompleteMsoProcess", "CMSO_SuccessIndicator"));
+ logEnd();
+ }
+
+ public String gMsoCompletionRequestWithNotificationurl() {
+ String xml = ""
+ + "<sdncadapterworkflow:MsoCompletionRequest xmlns:ns=\"http://openecomp.org/mso/request/types/v1\" xmlns:sdncadapterworkflow=\"http://ecomp.openecomp.org.com/mso/workflow/schema/v1\">"
+ + " <ns:request-information>" + " <ns:request-id>STUW105_5002</ns:request-id>"
+ + " <ns:request-action>RequestAction</ns:request-action>"
+ + " <ns:request-sub-action>COMPLETE</ns:request-sub-action>" + " <ns:source>SOURCE</ns:source>"
+ + " <ns:notification-url>https://t3nap1a1.snt.bst.bls.com:9004/sdncontroller-sdncontroller-inbound-ws-war/sdncontroller-sdncontroller-inbound-ws.wsdl</ns:notification-url>"
+ + " <ns:order-number>10205000</ns:order-number>" + " <ns:order-version>1</ns:order-version>"
+ + " </ns:request-information>"
+ + " <sdncadapterworkflow:mso-bpel-name>BPELNAME</sdncadapterworkflow:mso-bpel-name>"
+ + "</sdncadapterworkflow:MsoCompletionRequest>";
+
+ return xml;
+ }
+
+
+
+ public String gMsoCompletionRequestWithNoNotificationurl() {
+ // Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
+ String xml = ""
+ + "<sdncadapterworkflow:MsoCompletionRequest xmlns:ns=\"http://openecomp.org/mso/request/types/v1\" xmlns:sdncadapterworkflow=\"http://openecomp.org/mso/workflow/schema/v1\">"
+ + " <ns:request-information>" + " <ns:request-id>STUW105_5002</ns:request-id>"
+ + " <ns:request-action>RequestAction</ns:request-action>"
+ + " <ns:request-sub-action>COMPLETE</ns:request-sub-action>" + " <ns:source>SOURCE</ns:source>"
+ + " <ns:notification-url></ns:notification-url>"
+ + " <ns:order-number>10205000</ns:order-number>" + " <ns:order-version>1</ns:order-version>"
+ + " </ns:request-information>"
+ + " <sdncadapterworkflow:mso-bpel-name>BPELNAME</sdncadapterworkflow:mso-bpel-name>"
+ + "</sdncadapterworkflow:MsoCompletionRequest>";
+
+ return xml;
+ }
+
+ public String gMsoCompletionRequestWithNoNotificationurlNoRequestId() {
+ // Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
+ String xml = ""
+ + "<sdncadapterworkflow:MsoCompletionRequest xmlns:ns=\"http://openecomp.org/mso/request/types/v1\" xmlns:sdncadapterworkflow=\"http://openecomp.org/mso/workflow/schema/v1\">"
+ + " <ns:request-information>" + " <ns:request-id></ns:request-id>"
+ + " <ns:request-action>RequestAction</ns:request-action>"
+ + " <ns:request-sub-action>COMPLETE</ns:request-sub-action>" + " <ns:source>SOURCE</ns:source>"
+ + " <ns:notification-url></ns:notification-url>"
+ + " <ns:order-number>10205000</ns:order-number>" + " <ns:order-version>1</ns:order-version>"
+ + " </ns:request-information>"
+ + " <sdncadapterworkflow:mso-bpel-name>BPELNAME</sdncadapterworkflow:mso-bpel-name>"
+ + "</sdncadapterworkflow:MsoCompletionRequest>";
+
+ return xml;
+ }
+
+ public String gMsoCompletionRequestWithNotificationurlNoRequestId() {
+ // Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
+ String xml = ""
+ + "<sdncadapterworkflow:MsoCompletionRequest xmlns:ns=\"http://openecomp.org/mso/request/types/v1\" xmlns:sdncadapterworkflow=\"http://openecomp.org/mso/workflow/schema/v1\">"
+ + " <ns:request-information>" + " <ns:request-id></ns:request-id>"
+ + " <ns:request-action>RequestAction</ns:request-action>"
+ + " <ns:request-sub-action>COMPLETE</ns:request-sub-action>" + " <ns:source>SOURCE</ns:source>"
+ + " <ns:notification-url>https://t3nap1a1.snt.bst.bls.com:9004/sdncontroller-sdncontroller-inbound-ws-war/sdncontroller-sdncontroller-inbound-ws.wsdl</ns:notification-url>"
+ + " <ns:order-number>10205000</ns:order-number>" + " <ns:order-version>1</ns:order-version>"
+ + " </ns:request-information>"
+ + " <sdncadapterworkflow:mso-bpel-name>BPELNAME</sdncadapterworkflow:mso-bpel-name>"
+ + "</sdncadapterworkflow:MsoCompletionRequest>";
+
+ return xml;
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ConfirmVolumeGroupNameIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ConfirmVolumeGroupNameIT.java
index cc3ca941e4..ad0428c68e 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ConfirmVolumeGroupNameIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ConfirmVolumeGroupNameIT.java
@@ -16,17 +16,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
import static org.junit.Assert.assertEquals;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetVolumeGroupById;
-
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Ignore;
@@ -38,79 +36,83 @@ import org.onap.so.BaseIntegrationTest;
*/
public class ConfirmVolumeGroupNameIT extends BaseIntegrationTest {
- /**
- * Sunny day scenario.
- *
- * @throws Exception
- */
- @Test
- public void sunnyDay() throws Exception {
- logStart();
- MockGetVolumeGroupById(wireMockServer, "MDTWNJ21", "VOLUME_GROUP_ID_1", "aai-volume-group-id-info.xml");
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("ConfirmVolumeGroupName_volumeGroupId", "VOLUME_GROUP_ID_1");
- variables.put("ConfirmVolumeGroupName_volumeGroupName", "VOLUME_GROUP_ID_1_NAME");
- variables.put("ConfirmVolumeGroupName_aicCloudRegion", "MDTWNJ21");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- String processId = invokeSubProcess("ConfirmVolumeGroupName", variables);
- String responseCode = BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupName", "CVGN_queryVolumeGroupResponseCode",processId);
-
- assertEquals("200", responseCode);
-
- logEnd();
- }
-
- /**
- * Rainy day scenario - nonexisting volume group id.
- *
- * @throws Exception
- */
- @Test
- public void rainyDayNoVolumeGroupId() throws Exception {
- logStart();
-
- // does not exist would return a 404 from AAI
- MockGetVolumeGroupById(wireMockServer, "MDTWNJ21", "VOLUME_GROUP_ID_THAT_DOES_NOT_EXIST", "aai-volume-group-id-info.xml", 404);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("ConfirmVolumeGroupName_aicCloudRegion", "MDTWNJ21");
- variables.put("ConfirmVolumeGroupName_volumeGroupId", "VOLUME_GROUP_ID_THAT_DOES_NOT_EXIST");
- variables.put("ConfirmVolumeGroupName_volumeGroupName", "cee6d136-e378-4678-a024-2cd15f0ee0cg");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- String processId = invokeSubProcess("ConfirmVolumeGroupName", variables);
- String responseCode = BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupName", "CVGN_queryVolumeGroupResponseCode",processId);
-
- assertEquals("404", responseCode);
-
- logEnd();
- }
-
- /**
- * Rainy day scenario - volume group name does not match the name in AAI
- *
- *
- * @throws Exception
- */
- @Test
- public void rainyDayNameDoesNotMatch() throws Exception {
- logStart();
-
- MockGetVolumeGroupById(wireMockServer, "MDTWNJ21", "VOLUME_GROUP_ID_1", "aai-volume-group-id-info.xml", 200);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("ConfirmVolumeGroupName_volumeGroupId", "VOLUME_GROUP_ID_1");
- variables.put("ConfirmVolumeGroupName_volumeGroupName", "BAD_VOLUME_GROUP_NAME");
- variables.put("ConfirmVolumeGroupName_aicCloudRegion", "MDTWNJ21");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- String processId = invokeSubProcess("ConfirmVolumeGroupName", variables);
- String volumeGroupNameMatches = BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupName", "CVGN_volumeGroupNameMatches",processId);
-
- assertEquals("false", volumeGroupNameMatches);
-
- logEnd();
- }
+ /**
+ * Sunny day scenario.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void sunnyDay() throws Exception {
+ logStart();
+ MockGetVolumeGroupById(wireMockServer, "MDTWNJ21", "VOLUME_GROUP_ID_1", "aai-volume-group-id-info.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("ConfirmVolumeGroupName_volumeGroupId", "VOLUME_GROUP_ID_1");
+ variables.put("ConfirmVolumeGroupName_volumeGroupName", "VOLUME_GROUP_ID_1_NAME");
+ variables.put("ConfirmVolumeGroupName_aicCloudRegion", "MDTWNJ21");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ String processId = invokeSubProcess("ConfirmVolumeGroupName", variables);
+ String responseCode = BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupName",
+ "CVGN_queryVolumeGroupResponseCode", processId);
+
+ assertEquals("200", responseCode);
+
+ logEnd();
+ }
+
+ /**
+ * Rainy day scenario - nonexisting volume group id.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void rainyDayNoVolumeGroupId() throws Exception {
+ logStart();
+
+ // does not exist would return a 404 from AAI
+ MockGetVolumeGroupById(wireMockServer, "MDTWNJ21", "VOLUME_GROUP_ID_THAT_DOES_NOT_EXIST",
+ "aai-volume-group-id-info.xml", 404);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("ConfirmVolumeGroupName_aicCloudRegion", "MDTWNJ21");
+ variables.put("ConfirmVolumeGroupName_volumeGroupId", "VOLUME_GROUP_ID_THAT_DOES_NOT_EXIST");
+ variables.put("ConfirmVolumeGroupName_volumeGroupName", "cee6d136-e378-4678-a024-2cd15f0ee0cg");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ String processId = invokeSubProcess("ConfirmVolumeGroupName", variables);
+ String responseCode = BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupName",
+ "CVGN_queryVolumeGroupResponseCode", processId);
+
+ assertEquals("404", responseCode);
+
+ logEnd();
+ }
+
+ /**
+ * Rainy day scenario - volume group name does not match the name in AAI
+ *
+ *
+ * @throws Exception
+ */
+ @Test
+ public void rainyDayNameDoesNotMatch() throws Exception {
+ logStart();
+
+ MockGetVolumeGroupById(wireMockServer, "MDTWNJ21", "VOLUME_GROUP_ID_1", "aai-volume-group-id-info.xml", 200);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("ConfirmVolumeGroupName_volumeGroupId", "VOLUME_GROUP_ID_1");
+ variables.put("ConfirmVolumeGroupName_volumeGroupName", "BAD_VOLUME_GROUP_NAME");
+ variables.put("ConfirmVolumeGroupName_aicCloudRegion", "MDTWNJ21");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ String processId = invokeSubProcess("ConfirmVolumeGroupName", variables);
+ String volumeGroupNameMatches =
+ BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupName", "CVGN_volumeGroupNameMatches", processId);
+
+ assertEquals("false", volumeGroupNameMatches);
+
+ logEnd();
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ConfirmVolumeGroupTenantIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ConfirmVolumeGroupTenantIT.java
index fd1f7c1a2b..f190b6243b 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ConfirmVolumeGroupTenantIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ConfirmVolumeGroupTenantIT.java
@@ -19,17 +19,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
import static org.junit.Assert.assertEquals;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetVolumeGroupById;
-
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
@@ -40,49 +38,59 @@ import org.onap.so.BaseIntegrationTest;
public class ConfirmVolumeGroupTenantIT extends BaseIntegrationTest {
- @Test
- public void testRemoveLayer3Service_success() throws Exception{
- MockGetVolumeGroupById(wireMockServer, "MDTWNJ21", "a8399879-31b3-4973-be26-0a0cbe776b58", "CRTGVNF_queryAAIResponseVolume.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariables(variables);
-
- String processId = invokeSubProcess("ConfirmVolumeGroupTenant", variables);
-
- String actualNameMatch = BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupTenant", "groupNamesMatch",processId);
- String actualIdMatch = BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupTenant", "tenantIdsMatch",processId);
- String actualResponse = BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupTenant", "volumeHeatStackId",processId);
-
- assertEquals("Response", "true", actualNameMatch);
- assertEquals("Response", "true", actualIdMatch);
- assertEquals("Response", "MoG_CinderVolumes_2/19387dc6-060f-446e-b41f-dcfd29c73845", actualResponse);
- }
-
- @Test
- public void testRemoveLayer3Service_idsNotMatch() throws Exception{
- MockGetVolumeGroupById(wireMockServer, "MDTWNJ21", "a8399879-31b3-4973-be26-0a0cbe776b58", "CRTGVNF_queryAAIResponseVolume_idsNotMatch.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariables(variables);
-
- String processId = invokeSubProcess("ConfirmVolumeGroupTenant", variables);
-
-
- String actualNameMatch = BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupTenant", "groupNamesMatch",processId);
- String actualIdMatch = BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupTenant", "tenantIdsMatch",processId);
- String actualResponse = BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupTenant", "WorkflowException",processId);
-
- assertEquals("Response", "true", actualNameMatch);
- assertEquals("Response", "false", actualIdMatch);
- assertEquals("Response", "WorkflowException[processKey=ConfirmVolumeGroupTenant,errorCode=1,errorMessage=Volume Group a8399879-31b3-4973-be26-0a0cbe776b58 does not belong to your tenant,workStep=*]", actualResponse);
-
- }
-
- private void setVariables(Map<String, Object> variables) {
- variables.put("isDebugLogEnabled", "true");
- variables.put("volumeGroupId","a8399879-31b3-4973-be26-0a0cbe776b58");
- variables.put("tenantId", "7dd5365547234ee8937416c65507d266");
- variables.put("aicCloudRegion", "MDTWNJ21");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- }
+ @Test
+ public void testRemoveLayer3Service_success() throws Exception {
+ MockGetVolumeGroupById(wireMockServer, "MDTWNJ21", "a8399879-31b3-4973-be26-0a0cbe776b58",
+ "CRTGVNF_queryAAIResponseVolume.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariables(variables);
+
+ String processId = invokeSubProcess("ConfirmVolumeGroupTenant", variables);
+
+ String actualNameMatch =
+ BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupTenant", "groupNamesMatch", processId);
+ String actualIdMatch =
+ BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupTenant", "tenantIdsMatch", processId);
+ String actualResponse =
+ BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupTenant", "volumeHeatStackId", processId);
+
+ assertEquals("Response", "true", actualNameMatch);
+ assertEquals("Response", "true", actualIdMatch);
+ assertEquals("Response", "MoG_CinderVolumes_2/19387dc6-060f-446e-b41f-dcfd29c73845", actualResponse);
+ }
+
+ @Test
+ public void testRemoveLayer3Service_idsNotMatch() throws Exception {
+ MockGetVolumeGroupById(wireMockServer, "MDTWNJ21", "a8399879-31b3-4973-be26-0a0cbe776b58",
+ "CRTGVNF_queryAAIResponseVolume_idsNotMatch.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariables(variables);
+
+ String processId = invokeSubProcess("ConfirmVolumeGroupTenant", variables);
+
+
+ String actualNameMatch =
+ BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupTenant", "groupNamesMatch", processId);
+ String actualIdMatch =
+ BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupTenant", "tenantIdsMatch", processId);
+ String actualResponse =
+ BPMNUtil.getVariable(processEngine, "ConfirmVolumeGroupTenant", "WorkflowException", processId);
+
+ assertEquals("Response", "true", actualNameMatch);
+ assertEquals("Response", "false", actualIdMatch);
+ assertEquals("Response",
+ "WorkflowException[processKey=ConfirmVolumeGroupTenant,errorCode=1,errorMessage=Volume Group a8399879-31b3-4973-be26-0a0cbe776b58 does not belong to your tenant,workStep=*]",
+ actualResponse);
+
+ }
+
+ private void setVariables(Map<String, Object> variables) {
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("volumeGroupId", "a8399879-31b3-4973-be26-0a0cbe776b58");
+ variables.put("tenantId", "7dd5365547234ee8937416c65507d266");
+ variables.put("aicCloudRegion", "MDTWNJ21");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CreateAAIVfModuleIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CreateAAIVfModuleIT.java
index f6cd74a55b..47d3799e7d 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CreateAAIVfModuleIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CreateAAIVfModuleIT.java
@@ -18,7 +18,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
@@ -26,18 +26,15 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
-
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.junit.Assert;
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
import org.onap.so.bpmn.core.WorkflowException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
import com.github.tomakehurst.wiremock.WireMockServer;
/**
@@ -45,223 +42,228 @@ import com.github.tomakehurst.wiremock.WireMockServer;
*/
public class CreateAAIVfModuleIT extends BaseIntegrationTest {
-
- Logger logger = LoggerFactory.getLogger(CreateAAIVfModuleIT.class);
-
- @Test
- public void TestCreateGenericVnfSuccess_200() {
- new MockAAIGenericVnfSearch(wireMockServer);
- MockAAICreateGenericVnf(wireMockServer);
- MockAAIVfModulePUT(wireMockServer, true);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("isVidRequest", "false");
- variables.put("vnfName", "STMTN5MMSC22");
- variables.put("serviceId", "00000000-0000-0000-0000-000000000000");
- variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
- variables.put("personaModelVersion", "1.0");
- variables.put("vfModuleName", "STMTN5MMSC22-MMSC::module-0-0");
- variables.put("vfModuleModelName", "MMSC::module-0");
-
- String processId = invokeSubProcess("CreateAAIVfModule", variables);
- String response = BPMNUtil.getVariable(processEngine, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode",processId);
- String responseCode = BPMNUtil.getVariable(processEngine, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode",processId);
- Assert.assertEquals("201", responseCode);
- logger.debug(response);
- }
+ Logger logger = LoggerFactory.getLogger(CreateAAIVfModuleIT.class);
+
+ @Test
+ public void TestCreateGenericVnfSuccess_200() {
+
+ new MockAAIGenericVnfSearch(wireMockServer);
+ MockAAICreateGenericVnf(wireMockServer);
+ MockAAIVfModulePUT(wireMockServer, true);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("isVidRequest", "false");
+ variables.put("vnfName", "STMTN5MMSC22");
+ variables.put("serviceId", "00000000-0000-0000-0000-000000000000");
+ variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
+ variables.put("personaModelVersion", "1.0");
+ variables.put("vfModuleName", "STMTN5MMSC22-MMSC::module-0-0");
+ variables.put("vfModuleModelName", "MMSC::module-0");
+
+ String processId = invokeSubProcess("CreateAAIVfModule", variables);
+ String response = BPMNUtil.getVariable(processEngine, "CreateAAIVfModule",
+ "CAAIVfMod_createVfModuleResponseCode", processId);
+ String responseCode = BPMNUtil.getVariable(processEngine, "CreateAAIVfModule",
+ "CAAIVfMod_createVfModuleResponseCode", processId);
+ Assert.assertEquals("201", responseCode);
+ logger.debug(response);
+ }
+
+ @Test
+ public void TestCreateVfModuleSuccess_200() {
+ // create Add-on VF Module for existing Generic VNF
+ new MockAAIGenericVnfSearch(wireMockServer);
+ MockAAICreateGenericVnf(wireMockServer);
+ MockAAIVfModulePUT(wireMockServer, true);
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("isVidRequest", "false");
+ variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721");
+ variables.put("serviceId", "00000000-0000-0000-0000-000000000000");
+ variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
+ variables.put("personaModelVersion", "1.0");
+ variables.put("vfModuleName", "STMTN5MMSC21-MMSC::module-1-0");
+ variables.put("vfModuleModelName", "STMTN5MMSC21-MMSC::model-1-0");
+ String processId = invokeSubProcess("CreateAAIVfModule", variables);
+ String response = BPMNUtil.getVariable(processEngine, "CreateAAIVfModule",
+ "CAAIVfMod_createVfModuleResponseCode", processId);
+ String responseCode = BPMNUtil.getVariable(processEngine, "CreateAAIVfModule",
+ "CAAIVfMod_createVfModuleResponseCode", processId);
+ Assert.assertEquals("201", responseCode);
+ logger.debug(response);
+ }
+
+ @Test
+ public void TestQueryGenericVnfFailure_5000() {
+ new MockAAIGenericVnfSearch(wireMockServer);
+ MockAAICreateGenericVnf(wireMockServer);
+ MockAAIVfModulePUT(wireMockServer, true);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("isVidRequest", "false");
+ variables.put("vnfName", "STMTN5MMSC23");
+ variables.put("serviceId", "00000000-0000-0000-0000-000000000000");
+ variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
+ variables.put("personaModelVersion", "1.0");
+ variables.put("vfModuleName", "STMTN5MMSC23-MMSC::module-0-0");
+ variables.put("vfModuleModelName", "MMSC::module-0");
+ String processId = invokeSubProcess("CreateAAIVfModule", variables);
+ WorkflowException exception =
+ BPMNUtil.getRawVariable(processEngine, "CreateAAIVfModule", "WorkflowException", processId);
+ Assert.assertEquals(500, exception.getErrorCode());
+ Assert.assertEquals(true, exception.getErrorMessage().contains("Error occurred attempting to query AAI"));
+ logger.debug(exception.getErrorMessage());
+ }
+
+ @Test
+ public void TestCreateDupGenericVnfFailure_1002() {
+ new MockAAIGenericVnfSearch(wireMockServer);
+ MockAAICreateGenericVnf(wireMockServer);
+ MockAAIVfModulePUT(wireMockServer, true);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("isVidRequest", "false");
+ variables.put("vnfName", "STMTN5MMSC21");
+ variables.put("serviceId", "00000000-0000-0000-0000-000000000000");
+ variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
+ variables.put("personaModelVersion", "1.0");
+ variables.put("vfModuleName", "STMTN5MMSC21-MMSC::module-0-0");
+ variables.put("vfModuleModelName", "MMSC::module-0");
+ String processId = invokeSubProcess("CreateAAIVfModule", variables);
+ WorkflowException exception =
+ BPMNUtil.getRawVariable(processEngine, "CreateAAIVfModule", "WorkflowException", processId);
+ Assert.assertEquals(1002, exception.getErrorCode());
+ Assert.assertEquals(true,
+ exception.getErrorMessage().contains("Invalid request for new Generic VNF which already exists"));
+ logger.debug(exception.getErrorMessage());
+ }
+
+ @Test
+ public void TestCreateDupVfModuleFailure_1002() {
+ new MockAAIGenericVnfSearch(wireMockServer);
+ MockAAICreateGenericVnf(wireMockServer);
+ MockAAIVfModulePUT(wireMockServer, true);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("isVidRequest", "false");
+ variables.put("vnfId", "2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4");
+ variables.put("serviceId", "00000000-0000-0000-0000-000000000000");
+ variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
+ variables.put("personaModelVersion", "1.0");
+ variables.put("vfModuleName", "STMTN5MMSC20-MMSC::module-1-0");
+ variables.put("vfModuleModelName", "STMTN5MMSC20-MMSC::model-1-0");
+ String processId = invokeSubProcess("CreateAAIVfModule", variables);
+ WorkflowException exception =
+ BPMNUtil.getRawVariable(processEngine, "CreateAAIVfModule", "WorkflowException", processId);
+ Assert.assertEquals(1002, exception.getErrorCode());
+ Assert.assertEquals(true, exception.getErrorMessage().contains("already exists for Generic VNF"));
+ logger.debug(exception.getErrorMessage());
+ }
+
+ @Test
+ public void TestCreateGenericVnfFailure_5000() {
+ new MockAAIGenericVnfSearch(wireMockServer);
+ MockAAICreateGenericVnf(wireMockServer);
+ MockAAIVfModulePUT(wireMockServer, true);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("isVidRequest", "false");
+ variables.put("vnfName", "STMTN5MMSC22");
+ variables.put("serviceId", "99999999-9999-9999-9999-999999999999");
+ variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
+ variables.put("personaModelVersion", "1.0");
+ variables.put("vfModuleName", "STMTN5MMSC22-PCRF::module-1-0");
+ variables.put("vfModuleModelName", "PCRF::module-0");
+ String processId = invokeSubProcess("CreateAAIVfModule", variables);
+ WorkflowException exception =
+ BPMNUtil.getRawVariable(processEngine, "CreateAAIVfModule", "WorkflowException", processId);
+ Assert.assertEquals(5000, exception.getErrorCode());
+ Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>"));
+ logger.debug(exception.getErrorMessage());
+ }
- @Test
- public void TestCreateVfModuleSuccess_200() {
- // create Add-on VF Module for existing Generic VNF
- new MockAAIGenericVnfSearch(wireMockServer);
- MockAAICreateGenericVnf(wireMockServer);
- MockAAIVfModulePUT(wireMockServer, true);
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("isVidRequest", "false");
- variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721");
- variables.put("serviceId", "00000000-0000-0000-0000-000000000000");
- variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
- variables.put("personaModelVersion", "1.0");
- variables.put("vfModuleName", "STMTN5MMSC21-MMSC::module-1-0");
- variables.put("vfModuleModelName", "STMTN5MMSC21-MMSC::model-1-0");
- String processId = invokeSubProcess("CreateAAIVfModule", variables);
- String response = BPMNUtil.getVariable(processEngine, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode",processId);
- String responseCode = BPMNUtil.getVariable(processEngine, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode",processId);
- Assert.assertEquals("201", responseCode);
- logger.debug(response);
- }
+ @Test
+ public void TestCreateGenericVnfFailure_1002() {
+ new MockAAIGenericVnfSearch(wireMockServer);
+ MockAAICreateGenericVnf(wireMockServer);
+ MockAAIVfModulePUT(wireMockServer, true);
- @Test
- public void TestQueryGenericVnfFailure_5000() {
- new MockAAIGenericVnfSearch(wireMockServer);
- MockAAICreateGenericVnf(wireMockServer);
- MockAAIVfModulePUT(wireMockServer, true);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("isVidRequest", "false");
- variables.put("vnfName", "STMTN5MMSC23");
- variables.put("serviceId", "00000000-0000-0000-0000-000000000000");
- variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
- variables.put("personaModelVersion", "1.0");
- variables.put("vfModuleName", "STMTN5MMSC23-MMSC::module-0-0");
- variables.put("vfModuleModelName", "MMSC::module-0");
- String processId = invokeSubProcess("CreateAAIVfModule", variables);
- WorkflowException exception = BPMNUtil.getRawVariable(processEngine, "CreateAAIVfModule", "WorkflowException",processId);
- Assert.assertEquals(500, exception.getErrorCode());
- Assert.assertEquals(true, exception.getErrorMessage().contains("Error occurred attempting to query AAI"));
- logger.debug(exception.getErrorMessage());
- }
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("isVidRequest", "false");
+ variables.put("vnfId", "768073c7-f41f-4822-9323-b75962763d74");
+ variables.put("serviceId", "00000000-0000-0000-0000-000000000000");
+ variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
+ variables.put("personaModelVersion", "1.0");
+ variables.put("vfModuleName", "STMTN5MMSC22-PCRF::module-1-0");
+ variables.put("vfModuleModelName", "PCRF::module-0");
+ String processId = invokeSubProcess("CreateAAIVfModule", variables);
+ WorkflowException exception =
+ BPMNUtil.getRawVariable(processEngine, "CreateAAIVfModule", "WorkflowException", processId);
+ Assert.assertEquals(1002, exception.getErrorCode());
+ Assert.assertEquals(true, exception.getErrorMessage().contains("Generic VNF Not Found"));
+ logger.debug(exception.getErrorMessage());
+ }
- @Test
- public void TestCreateDupGenericVnfFailure_1002() {
- new MockAAIGenericVnfSearch(wireMockServer);
- MockAAICreateGenericVnf(wireMockServer);
- MockAAIVfModulePUT(wireMockServer, true);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("isVidRequest", "false");
- variables.put("vnfName", "STMTN5MMSC21");
- variables.put("serviceId", "00000000-0000-0000-0000-000000000000");
- variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
- variables.put("personaModelVersion", "1.0");
- variables.put("vfModuleName", "STMTN5MMSC21-MMSC::module-0-0");
- variables.put("vfModuleModelName", "MMSC::module-0");
- String processId = invokeSubProcess("CreateAAIVfModule", variables);
- WorkflowException exception = BPMNUtil.getRawVariable(processEngine, "CreateAAIVfModule", "WorkflowException",processId);
- Assert.assertEquals(1002, exception.getErrorCode());
- Assert.assertEquals(true, exception.getErrorMessage().contains("Invalid request for new Generic VNF which already exists"));
- logger.debug(exception.getErrorMessage());
- }
+ @Test
+ public void TestCreateVfModuleFailure_5000() {
+ new MockAAIGenericVnfSearch(wireMockServer);
+ MockAAICreateGenericVnf(wireMockServer);
+ MockAAIVfModulePUT(wireMockServer, true);
- @Test
- public void TestCreateDupVfModuleFailure_1002() {
- new MockAAIGenericVnfSearch(wireMockServer);
- MockAAICreateGenericVnf(wireMockServer);
- MockAAIVfModulePUT(wireMockServer, true);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("isVidRequest", "false");
- variables.put("vnfId", "2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4");
- variables.put("serviceId", "00000000-0000-0000-0000-000000000000");
- variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
- variables.put("personaModelVersion", "1.0");
- variables.put("vfModuleName", "STMTN5MMSC20-MMSC::module-1-0");
- variables.put("vfModuleModelName", "STMTN5MMSC20-MMSC::model-1-0");
- String processId = invokeSubProcess("CreateAAIVfModule", variables);
- WorkflowException exception = BPMNUtil.getRawVariable(processEngine, "CreateAAIVfModule", "WorkflowException",processId);
- Assert.assertEquals(1002, exception.getErrorCode());
- Assert.assertEquals(true, exception.getErrorMessage().contains("already exists for Generic VNF"));
- logger.debug(exception.getErrorMessage());
- }
-
- @Test
- public void TestCreateGenericVnfFailure_5000() {
- new MockAAIGenericVnfSearch(wireMockServer);
- MockAAICreateGenericVnf(wireMockServer);
- MockAAIVfModulePUT(wireMockServer, true);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("isVidRequest", "false");
- variables.put("vnfName", "STMTN5MMSC22");
- variables.put("serviceId", "99999999-9999-9999-9999-999999999999");
- variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
- variables.put("personaModelVersion", "1.0");
- variables.put("vfModuleName", "STMTN5MMSC22-PCRF::module-1-0");
- variables.put("vfModuleModelName", "PCRF::module-0");
- String processId = invokeSubProcess("CreateAAIVfModule", variables);
- WorkflowException exception = BPMNUtil.getRawVariable(processEngine, "CreateAAIVfModule", "WorkflowException",processId);
- Assert.assertEquals(5000, exception.getErrorCode());
- Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>"));
- logger.debug(exception.getErrorMessage());
- }
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("isVidRequest", "false");
+ variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721");
+ variables.put("serviceId", "99999999-9999-9999-9999-999999999999");
+ variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
+ variables.put("personaModelVersion", "1.0");
+ variables.put("vfModuleName", "STMTN5MMSC21-PCRF::module-1-0");
+ variables.put("vfModuleModelName", "STMTN5MMSC21-PCRF::model-1-0");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ String processId = invokeSubProcess("CreateAAIVfModule", variables);
+ WorkflowException exception =
+ BPMNUtil.getRawVariable(processEngine, "CreateAAIVfModule", "WorkflowException", processId);
+ Assert.assertEquals(5000, exception.getErrorCode());
+ Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>"));
+ logger.debug(exception.getErrorMessage());
+ }
- @Test
- public void TestCreateGenericVnfFailure_1002() {
- new MockAAIGenericVnfSearch(wireMockServer);
- MockAAICreateGenericVnf(wireMockServer);
- MockAAIVfModulePUT(wireMockServer, true);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("isVidRequest", "false");
- variables.put("vnfId", "768073c7-f41f-4822-9323-b75962763d74");
- variables.put("serviceId", "00000000-0000-0000-0000-000000000000");
- variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
- variables.put("personaModelVersion", "1.0");
- variables.put("vfModuleName", "STMTN5MMSC22-PCRF::module-1-0");
- variables.put("vfModuleModelName", "PCRF::module-0");
- String processId = invokeSubProcess("CreateAAIVfModule", variables);
- WorkflowException exception = BPMNUtil.getRawVariable(processEngine, "CreateAAIVfModule", "WorkflowException",processId);
- Assert.assertEquals(1002, exception.getErrorCode());
- Assert.assertEquals(true, exception.getErrorMessage().contains("Generic VNF Not Found"));
- logger.debug(exception.getErrorMessage());
- }
+ public static void MockAAICreateGenericVnf(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*"))
+ .withRequestBody(containing("<service-id>00000000-0000-0000-0000-000000000000</service-id>"))
+ .willReturn(aResponse().withStatus(201)));
+ wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*"))
+ .withRequestBody(containing("<service-id>99999999-9999-9999-9999-999999999999</service-id>"))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "text/xml")
+ .withBodyFile("aaiFault.xml")));
+ }
- @Test
- public void TestCreateVfModuleFailure_5000() {
- new MockAAIGenericVnfSearch(wireMockServer);
- MockAAICreateGenericVnf(wireMockServer);
- MockAAIVfModulePUT(wireMockServer, true);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("isVidRequest", "false");
- variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721");
- variables.put("serviceId", "99999999-9999-9999-9999-999999999999");
- variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73");
- variables.put("personaModelVersion", "1.0");
- variables.put("vfModuleName", "STMTN5MMSC21-PCRF::module-1-0");
- variables.put("vfModuleModelName", "STMTN5MMSC21-PCRF::model-1-0");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- String processId = invokeSubProcess("CreateAAIVfModule", variables);
- WorkflowException exception = BPMNUtil.getRawVariable(processEngine, "CreateAAIVfModule", "WorkflowException",processId);
- Assert.assertEquals(5000, exception.getErrorCode());
- Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>"));
- logger.debug(exception.getErrorMessage());
- }
+ // start of mocks used locally and by other VF Module unit tests
+ public static void MockAAIVfModulePUT(WireMockServer wireMockServer, boolean isCreate) {
+ wireMockServer
+ .stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*"))
+ .withRequestBody(containing("MMSC")).willReturn(aResponse().withStatus(isCreate ? 201 : 200)));
+ wireMockServer
+ .stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*"))
+ .withRequestBody(containing("PCRF")).willReturn(aResponse().withStatus(500)
+ .withHeader("Content-Type", "text/xml").withBodyFile("aaiFault.xml")));
+ wireMockServer.stubFor(
+ put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721"))
+ .willReturn(aResponse().withStatus(200)));
+ }
- public static void MockAAICreateGenericVnf(WireMockServer wireMockServer){
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*"))
- .withRequestBody(containing("<service-id>00000000-0000-0000-0000-000000000000</service-id>"))
- .willReturn(aResponse()
- .withStatus(201)));
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*"))
- .withRequestBody(containing("<service-id>99999999-9999-9999-9999-999999999999</service-id>"))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("aaiFault.xml")));
- }
-
- // start of mocks used locally and by other VF Module unit tests
- public static void MockAAIVfModulePUT(WireMockServer wireMockServer, boolean isCreate){
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*"))
- .withRequestBody(containing("MMSC"))
- .willReturn(aResponse()
- .withStatus(isCreate ? 201 : 200)));
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*"))
- .withRequestBody(containing("PCRF"))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("aaiFault.xml")));
- wireMockServer.stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721"))
- .willReturn(aResponse()
- .withStatus(200)));
- }
-
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CreateAAIVfModuleVolumeGroupIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CreateAAIVfModuleVolumeGroupIT.java
index 39a7e0c74b..b78c5b8aad 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CreateAAIVfModuleVolumeGroupIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/CreateAAIVfModuleVolumeGroupIT.java
@@ -26,12 +26,10 @@ import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPri
import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetVfModuleId;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutVfModuleId;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutVfModuleIdNoResponse;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.junit.Assert;
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
@@ -45,91 +43,95 @@ import org.slf4j.LoggerFactory;
public class CreateAAIVfModuleVolumeGroupIT extends BaseIntegrationTest {
- Logger logger = LoggerFactory.getLogger(CreateAAIVfModuleVolumeGroupIT.class);
-
- /**
- * Test the happy path through the flow.
- */
- @Test
- public void happyPath() throws IOException {
-
- logStart();
-
- String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/CreateAAIVfModuleVolumeGroupRequest.xml");
- MockGetGenericVnfByIdWithPriority(wireMockServer, "skask", "lukewarm", 200, "VfModularity/VfModule-lukewarm.xml", 2);
- MockPutVfModuleIdNoResponse(wireMockServer, "skask", "PCRF", "lukewarm");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", "999-99-9999");
- variables.put("isDebugLogEnabled","true");
- variables.put("CreateAAIVfModuleVolumeGroupRequest", updateAAIVfModuleRequest);
- invokeSubProcess("CreateAAIVfModuleVolumeGroup", businessKey, variables);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String response = (String) getVariableFromHistory(businessKey, "CAAIVfModVG_updateVfModuleResponse");
- Integer responseCode = (Integer) getVariableFromHistory(businessKey, "CAAIVfModVG_updateVfModuleResponseCode");
- logger.debug("Subflow response code: {}", responseCode);
- logger.debug("Subflow response: {}", response);
- Assert.assertEquals(200, responseCode.intValue());
-
- logEnd();
- }
-
- /**
- * Test the case where the GET to AAI returns a 404.
- */
- @Test
- public void badGet() throws IOException {
-
- logStart();
-
- String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/CreateAAIVfModuleVolumeGroupRequest.xml");
- MockGetVfModuleId(wireMockServer, "skask", ".*", "VfModularity/VfModule-supercool.xml", 404);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", "999-99-9999");
- variables.put("isDebugLogEnabled","true");
- variables.put("CreateAAIVfModuleVolumeGroupRequest", updateAAIVfModuleRequest);
- invokeSubProcess("CreateAAIVfModuleVolumeGroup", businessKey, variables);
- Assert.assertTrue(isProcessEnded(businessKey));
- String response = (String) getVariableFromHistory(businessKey, "CAAIVfModVG_getVfModuleResponse");
- Integer responseCode = (Integer) getVariableFromHistory(businessKey, "CAAIVfModVG_getVfModuleResponseCode");
- logger.debug("Subflow response code: {}", responseCode);
- logger.debug("Subflow response: {}", response);
- Assert.assertEquals(404, responseCode.intValue());
-
- logEnd();
- }
-
- /**
- * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404.
- */
- @Test
- public void badPatch() throws IOException {
-
- logStart();
-
- String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/CreateAAIVfModuleVolumeGroupRequest.xml");
- MockGetVfModuleId(wireMockServer, "skask", "lukewarm", "VfModularity/VfModule-lukewarm.xml", 200);
- MockPutVfModuleId(wireMockServer, "skask", "lukewarm", 404);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", "999-99-9999");
- variables.put("isDebugLogEnabled","true");
- variables.put("CreateAAIVfModuleVolumeGroupRequest", updateAAIVfModuleRequest);
- invokeSubProcess("CreateAAIVfModuleVolumeGroup", businessKey, variables);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String response = (String) getVariableFromHistory(businessKey, "CAAIVfModVG_updateVfModuleResponse");
- Integer responseCode = (Integer) getVariableFromHistory(businessKey, "CAAIVfModVG_updateVfModuleResponseCode");
- logger.debug("Subflow response code: {}", responseCode);
- logger.debug("Subflow response: {}", response);
- Assert.assertEquals(404, responseCode.intValue());
-
- logEnd();
- }
+ Logger logger = LoggerFactory.getLogger(CreateAAIVfModuleVolumeGroupIT.class);
+
+ /**
+ * Test the happy path through the flow.
+ */
+ @Test
+ public void happyPath() throws IOException {
+
+ logStart();
+
+ String updateAAIVfModuleRequest =
+ FileUtil.readResourceFile("__files/VfModularity/CreateAAIVfModuleVolumeGroupRequest.xml");
+ MockGetGenericVnfByIdWithPriority(wireMockServer, "skask", "lukewarm", 200,
+ "VfModularity/VfModule-lukewarm.xml", 2);
+ MockPutVfModuleIdNoResponse(wireMockServer, "skask", "PCRF", "lukewarm");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", "999-99-9999");
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("CreateAAIVfModuleVolumeGroupRequest", updateAAIVfModuleRequest);
+ invokeSubProcess("CreateAAIVfModuleVolumeGroup", businessKey, variables);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String response = (String) getVariableFromHistory(businessKey, "CAAIVfModVG_updateVfModuleResponse");
+ Integer responseCode = (Integer) getVariableFromHistory(businessKey, "CAAIVfModVG_updateVfModuleResponseCode");
+ logger.debug("Subflow response code: {}", responseCode);
+ logger.debug("Subflow response: {}", response);
+ Assert.assertEquals(200, responseCode.intValue());
+
+ logEnd();
+ }
+
+ /**
+ * Test the case where the GET to AAI returns a 404.
+ */
+ @Test
+ public void badGet() throws IOException {
+
+ logStart();
+
+ String updateAAIVfModuleRequest =
+ FileUtil.readResourceFile("__files/VfModularity/CreateAAIVfModuleVolumeGroupRequest.xml");
+ MockGetVfModuleId(wireMockServer, "skask", ".*", "VfModularity/VfModule-supercool.xml", 404);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", "999-99-9999");
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("CreateAAIVfModuleVolumeGroupRequest", updateAAIVfModuleRequest);
+ invokeSubProcess("CreateAAIVfModuleVolumeGroup", businessKey, variables);
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String response = (String) getVariableFromHistory(businessKey, "CAAIVfModVG_getVfModuleResponse");
+ Integer responseCode = (Integer) getVariableFromHistory(businessKey, "CAAIVfModVG_getVfModuleResponseCode");
+ logger.debug("Subflow response code: {}", responseCode);
+ logger.debug("Subflow response: {}", response);
+ Assert.assertEquals(404, responseCode.intValue());
+
+ logEnd();
+ }
+
+ /**
+ * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404.
+ */
+ @Test
+ public void badPatch() throws IOException {
+
+ logStart();
+
+ String updateAAIVfModuleRequest =
+ FileUtil.readResourceFile("__files/VfModularity/CreateAAIVfModuleVolumeGroupRequest.xml");
+ MockGetVfModuleId(wireMockServer, "skask", "lukewarm", "VfModularity/VfModule-lukewarm.xml", 200);
+ MockPutVfModuleId(wireMockServer, "skask", "lukewarm", 404);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", "999-99-9999");
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("CreateAAIVfModuleVolumeGroupRequest", updateAAIVfModuleRequest);
+ invokeSubProcess("CreateAAIVfModuleVolumeGroup", businessKey, variables);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String response = (String) getVariableFromHistory(businessKey, "CAAIVfModVG_updateVfModuleResponse");
+ Integer responseCode = (Integer) getVariableFromHistory(businessKey, "CAAIVfModVG_updateVfModuleResponseCode");
+ logger.debug("Subflow response code: {}", responseCode);
+ logger.debug("Subflow response: {}", response);
+ Assert.assertEquals(404, responseCode.intValue());
+
+ logEnd();
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/DecomposeServiceIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/DecomposeServiceIT.java
index 3d15a4b29b..0bfcbd370d 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/DecomposeServiceIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/DecomposeServiceIT.java
@@ -16,7 +16,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
@@ -25,7 +25,6 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Assert;
import org.junit.Ignore;
@@ -40,56 +39,55 @@ import org.onap.so.BaseIntegrationTest;
public class DecomposeServiceIT extends BaseIntegrationTest {
- public DecomposeServiceIT() throws IOException {
+ public DecomposeServiceIT() throws IOException {
+
+ }
- }
+ @Test
+ public void testDecomposeService_success() throws Exception {
+ MockGetServiceResourcesCatalogData(wireMockServer, "cmw-123-456-789", "1.0",
+ "/getCatalogServiceResourcesDataWithConfig.json");
- @Test
- public void testDecomposeService_success() throws Exception{
- MockGetServiceResourcesCatalogData(wireMockServer, "cmw-123-456-789", "1.0", "/getCatalogServiceResourcesDataWithConfig.json");
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, "testRequestId123", "ff5256d2-5a33-55df-13ab-12abad84e7ff");
+ invokeSubProcess("DecomposeService", businessKey, variables);
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, "testRequestId123", "ff5256d2-5a33-55df-13ab-12abad84e7ff");
- invokeSubProcess("DecomposeService", businessKey, variables);
+ waitForProcessEnd(businessKey, 10000);
- waitForProcessEnd(businessKey, 10000);
+ Assert.assertTrue(isProcessEnded(businessKey));
- Assert.assertTrue(isProcessEnded(businessKey));
+ }
- }
-
- //@Test
- @Test
- public void testDecomposeService_success_partial() throws Exception{
- MockGetServiceResourcesCatalogData(wireMockServer, "cmw-123-456-789", "1.0", "/getCatalogServiceResourcesDataNoNetwork.json");
+ // @Test
+ @Test
+ public void testDecomposeService_success_partial() throws Exception {
+ MockGetServiceResourcesCatalogData(wireMockServer, "cmw-123-456-789", "1.0",
+ "/getCatalogServiceResourcesDataNoNetwork.json");
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, "testRequestId123", "ff5256d2-5a33-55df-13ab-12abad84e7ff");
- invokeSubProcess("DecomposeService", businessKey, variables);
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, "testRequestId123", "ff5256d2-5a33-55df-13ab-12abad84e7ff");
+ invokeSubProcess("DecomposeService", businessKey, variables);
- waitForProcessEnd(businessKey, 10000);
+ waitForProcessEnd(businessKey, 10000);
- Assert.assertTrue(isProcessEnded(businessKey));
+ Assert.assertTrue(isProcessEnded(businessKey));
- }
+ }
- private void setVariablesSuccess(Map<String, Object> variables, String requestId, String siId) {
- variables.put("isDebugLogEnabled", "true");
- variables.put("mso-request-id", requestId);
- variables.put("msoRequestId", requestId);
- variables.put("serviceInstanceId",siId);
+ private void setVariablesSuccess(Map<String, Object> variables, String requestId, String siId) {
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("mso-request-id", requestId);
+ variables.put("msoRequestId", requestId);
+ variables.put("serviceInstanceId", siId);
- String serviceModelInfo = "{ "+ "\"modelType\": \"service\"," +
- "\"modelInvariantUuid\": \"cmw-123-456-789\"," +
- "\"modelVersionId\": \"ab6478e5-ea33-3346-ac12-ab121484a3fe\"," +
- "\"modelName\": \"ServicevSAMP12\"," +
- "\"modelVersion\": \"1.0\"," +
- "}";
- variables.put("serviceModelInfo", serviceModelInfo);
+ String serviceModelInfo = "{ " + "\"modelType\": \"service\"," + "\"modelInvariantUuid\": \"cmw-123-456-789\","
+ + "\"modelVersionId\": \"ab6478e5-ea33-3346-ac12-ab121484a3fe\"," + "\"modelName\": \"ServicevSAMP12\","
+ + "\"modelVersion\": \"1.0\"," + "}";
+ variables.put("serviceModelInfo", serviceModelInfo);
- }
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/DeleteAAIVfModuleIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/DeleteAAIVfModuleIT.java
index 99e4b8cbde..cac237aec4 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/DeleteAAIVfModuleIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/DeleteAAIVfModuleIT.java
@@ -16,14 +16,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.junit.Assert;
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
@@ -36,245 +35,227 @@ import org.slf4j.LoggerFactory;
*/
public class DeleteAAIVfModuleIT extends BaseIntegrationTest {
- private static final String EOL = "\n";
-
- Logger logger = LoggerFactory.getLogger(DeleteAAIVfModuleIT.class);
-
- @Test
- public void TestDeleteGenericVnfSuccess_200() {
- // delete the Base Module and Generic Vnf
- // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73
- new MockAAIGenericVnfSearch(wireMockServer);
- new MockAAIDeleteGenericVnf(wireMockServer);
- new MockAAIDeleteVfModule(wireMockServer);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("DeleteAAIVfModuleRequest","<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\"> <request-info> <action>DELETE_VF_MODULE</action> <source>PORTAL</source> </request-info> <vnf-inputs> <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id> <vnf-name>STMTN5MMSC21</vnf-name> <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id> <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name> </vnf-inputs> <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/> </vnf-request>");
- String processId = invokeSubProcess("DeleteAAIVfModule", variables);
- String response = BPMNUtil.getVariable(processEngine, "DeleteAAIVfModule", "DAAIVfMod_deleteGenericVnfResponseCode",processId);
- String responseCode = BPMNUtil.getVariable(processEngine, "DeleteAAIVfModule", "DAAIVfMod_deleteGenericVnfResponseCode",processId);
- Assert.assertEquals("200", responseCode);
- logger.debug(response);
- }
+ private static final String EOL = "\n";
+
+ Logger logger = LoggerFactory.getLogger(DeleteAAIVfModuleIT.class);
+
+ @Test
+ public void TestDeleteGenericVnfSuccess_200() {
+ // delete the Base Module and Generic Vnf
+ // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73
+ new MockAAIGenericVnfSearch(wireMockServer);
+ new MockAAIDeleteGenericVnf(wireMockServer);
+ new MockAAIDeleteVfModule(wireMockServer);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("DeleteAAIVfModuleRequest",
+ "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\"> <request-info> <action>DELETE_VF_MODULE</action> <source>PORTAL</source> </request-info> <vnf-inputs> <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id> <vnf-name>STMTN5MMSC21</vnf-name> <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id> <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name> </vnf-inputs> <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/> </vnf-request>");
+ String processId = invokeSubProcess("DeleteAAIVfModule", variables);
+ String response = BPMNUtil.getVariable(processEngine, "DeleteAAIVfModule",
+ "DAAIVfMod_deleteGenericVnfResponseCode", processId);
+ String responseCode = BPMNUtil.getVariable(processEngine, "DeleteAAIVfModule",
+ "DAAIVfMod_deleteGenericVnfResponseCode", processId);
+ Assert.assertEquals("200", responseCode);
+ logger.debug(response);
+ }
+
+ @Test
+ public void TestDeleteVfModuleSuccess_200() {
+ // delete Add-on Vf Module for existing Generic Vnf
+ // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a75
+ String request = "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL
+ + " <request-info>" + EOL + " <action>DELETE_VF_MODULE</action>" + EOL
+ + " <source>PORTAL</source>" + EOL + " </request-info>" + EOL + " <vnf-inputs>" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL
+ + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL + " </vnf-inputs>" + EOL
+ + " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL + "</vnf-request>"
+ + EOL;
+
+ new MockAAIGenericVnfSearch(wireMockServer);
+ new MockAAIDeleteGenericVnf(wireMockServer);
+ new MockAAIDeleteVfModule(wireMockServer);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("DeleteAAIVfModuleRequest", request);
+ String processId = invokeSubProcess("DeleteAAIVfModule", variables);
+ String response = BPMNUtil.getVariable(processEngine, "DeleteAAIVfModule",
+ "DAAIVfMod_deleteVfModuleResponseCode", processId);
+ String responseCode = BPMNUtil.getVariable(processEngine, "DeleteAAIVfModule",
+ "DAAIVfMod_deleteVfModuleResponseCode", processId);
+ Assert.assertEquals("200", responseCode);
+ logger.debug(response);
+ }
+
+ @Test
+ public void TestQueryGenericVnfFailure_5000() {
+ // query Generic Vnf failure (non-404) with A&AI
+ // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c723, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a71
+ String request = "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL
+ + " <request-info>" + EOL + " <action>DELETE_VF_MODULE</action>" + EOL
+ + " <source>PORTAL</source>" + EOL + " </request-info>" + EOL + " <vnf-inputs>" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c723</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC23</vnf-name>" + EOL
+ + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a71</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL + " </vnf-inputs>" + EOL
+ + " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL + "</vnf-request>"
+ + EOL;
+ new MockAAIGenericVnfSearch(wireMockServer);
+ new MockAAIDeleteGenericVnf(wireMockServer);
+ new MockAAIDeleteVfModule(wireMockServer);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("DeleteAAIVfModuleRequest", request);
+ String processId = invokeSubProcess("DeleteAAIVfModule", variables);
+ WorkflowException exception =
+ BPMNUtil.getRawVariable(processEngine, "DeleteAAIVfModule", "WorkflowException", processId);
+ Assert.assertEquals(5000, exception.getErrorCode());
+ Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>"));
+ logger.debug(exception.getErrorMessage());
+ }
+
+ @Test
+ public void TestQueryGenericVnfFailure_1002() {
+ // attempt to delete Vf Module for Generic Vnf that does not exist (A&AI returns 404)
+ // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c722, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a72
+ String request = "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL
+ + " <request-info>" + EOL + " <action>DELETE_VF_MODULE</action>" + EOL
+ + " <source>PORTAL</source>" + EOL + " </request-info>" + EOL + " <vnf-inputs>" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c722</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC22</vnf-name>" + EOL
+ + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a72</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC22-MMSC::module-1-0</vf-module-name>" + EOL + " </vnf-inputs>" + EOL
+ + " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL + "</vnf-request>"
+ + EOL;
+ new MockAAIGenericVnfSearch(wireMockServer);
+ new MockAAIDeleteGenericVnf(wireMockServer);
+ new MockAAIDeleteVfModule(wireMockServer);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("DeleteAAIVfModuleRequest", request);
+ String processId = invokeSubProcess("DeleteAAIVfModule", variables);
+ WorkflowException exception =
+ BPMNUtil.getRawVariable(processEngine, "DeleteAAIVfModule", "WorkflowException", processId);
+ Assert.assertEquals(1002, exception.getErrorCode());
+ Assert.assertEquals(true, exception.getErrorMessage().contains("Generic VNF Not Found"));
+ logger.debug(exception.getErrorMessage());
+ }
+
+ @Test
+ public void TestDeleteGenericVnfFailure_5000() {
+ // A&AI failure (non-200) when attempting to delete a Generic Vnf
+ // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c718, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a78
+ String request = "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL
+ + " <request-info>" + EOL + " <action>DELETE_VF_MODULE</action>" + EOL
+ + " <source>PORTAL</source>" + EOL + " </request-info>" + EOL + " <vnf-inputs>" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c718</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC18</vnf-name>" + EOL
+ + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC18-MMSC::module-0-0</vf-module-name>" + EOL + " </vnf-inputs>" + EOL
+ + " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL + "</vnf-request>"
+ + EOL;
+ new MockAAIGenericVnfSearch(wireMockServer);
+ new MockAAIDeleteGenericVnf(wireMockServer);
+ new MockAAIDeleteVfModule(wireMockServer);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("DeleteAAIVfModuleRequest", request);
+ String processId = invokeSubProcess("DeleteAAIVfModule", variables);
+ WorkflowException exception =
+ BPMNUtil.getRawVariable(processEngine, "DeleteAAIVfModule", "WorkflowException", processId);
+ Assert.assertEquals(5000, exception.getErrorCode());
+ Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>"));
+ logger.debug(exception.getErrorMessage());
+ }
- @Test
- public void TestDeleteVfModuleSuccess_200() {
- // delete Add-on Vf Module for existing Generic Vnf
- // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a75
- String request =
- "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL +
- " <request-info>" + EOL +
- " <action>DELETE_VF_MODULE</action>" + EOL +
- " <source>PORTAL</source>" + EOL +
- " </request-info>" + EOL +
- " <vnf-inputs>" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL +
- " </vnf-inputs>" + EOL +
- " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL +
- "</vnf-request>" + EOL;
+ @Test
+ public void TestDeleteVfModuleFailure_5000() {
+ // A&AI failure (non-200) when attempting to delete a Vf Module
+ // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c719, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a77
+ String request = "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL
+ + " <request-info>" + EOL + " <action>DELETE_VF_MODULE</action>" + EOL
+ + " <source>PORTAL</source>" + EOL + " </request-info>" + EOL + " <vnf-inputs>" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c719</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC19</vnf-name>" + EOL
+ + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC19-MMSC::module-1-0</vf-module-name>" + EOL + " </vnf-inputs>" + EOL
+ + " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL + "</vnf-request>"
+ + EOL;
+ new MockAAIGenericVnfSearch(wireMockServer);
+ new MockAAIDeleteGenericVnf(wireMockServer);
+ new MockAAIDeleteVfModule(wireMockServer);
- new MockAAIGenericVnfSearch(wireMockServer);
- new MockAAIDeleteGenericVnf(wireMockServer);
- new MockAAIDeleteVfModule(wireMockServer);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("DeleteAAIVfModuleRequest",request);
- String processId = invokeSubProcess("DeleteAAIVfModule", variables);
- String response = BPMNUtil.getVariable(processEngine, "DeleteAAIVfModule", "DAAIVfMod_deleteVfModuleResponseCode",processId);
- String responseCode = BPMNUtil.getVariable(processEngine, "DeleteAAIVfModule", "DAAIVfMod_deleteVfModuleResponseCode",processId);
- Assert.assertEquals("200", responseCode);
- logger.debug(response);
- }
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("DeleteAAIVfModuleRequest", request);
+ String processId = invokeSubProcess("DeleteAAIVfModule", variables);
+ WorkflowException exception =
+ BPMNUtil.getRawVariable(processEngine, "DeleteAAIVfModule", "WorkflowException", processId);
+ Assert.assertEquals(5000, exception.getErrorCode());
+ Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>"));
+ logger.debug(exception.getErrorMessage());
+ }
- @Test
- public void TestQueryGenericVnfFailure_5000() {
- // query Generic Vnf failure (non-404) with A&AI
- // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c723, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a71
- String request =
- "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL +
- " <request-info>" + EOL +
- " <action>DELETE_VF_MODULE</action>" + EOL +
- " <source>PORTAL</source>" + EOL +
- " </request-info>" + EOL +
- " <vnf-inputs>" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c723</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC23</vnf-name>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a71</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL +
- " </vnf-inputs>" + EOL +
- " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL +
- "</vnf-request>" + EOL;
- new MockAAIGenericVnfSearch(wireMockServer);
- new MockAAIDeleteGenericVnf(wireMockServer);
- new MockAAIDeleteVfModule(wireMockServer);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("DeleteAAIVfModuleRequest",request);
- String processId = invokeSubProcess("DeleteAAIVfModule", variables);
- WorkflowException exception = BPMNUtil.getRawVariable(processEngine, "DeleteAAIVfModule", "WorkflowException",processId);
- Assert.assertEquals(5000, exception.getErrorCode());
- Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>"));
- logger.debug(exception.getErrorMessage());
- }
+ @Test
+ public void TestDeleteVfModuleFailure_1002_1() {
+ // failure attempting to delete Base Module when not the last Vf Module
+ // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a74
+ String request = "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL
+ + " <request-info>" + EOL + " <action>DELETE_VF_MODULE</action>" + EOL
+ + " <source>PORTAL</source>" + EOL + " </request-info>" + EOL + " <vnf-inputs>" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL
+ + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL + " </vnf-inputs>" + EOL
+ + " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL + "</vnf-request>"
+ + EOL;
+ new MockAAIGenericVnfSearch(wireMockServer);
+ new MockAAIDeleteGenericVnf(wireMockServer);
+ new MockAAIDeleteVfModule(wireMockServer);
- @Test
- public void TestQueryGenericVnfFailure_1002() {
- // attempt to delete Vf Module for Generic Vnf that does not exist (A&AI returns 404)
- // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c722, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a72
- String request =
- "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL +
- " <request-info>" + EOL +
- " <action>DELETE_VF_MODULE</action>" + EOL +
- " <source>PORTAL</source>" + EOL +
- " </request-info>" + EOL +
- " <vnf-inputs>" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c722</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC22</vnf-name>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a72</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC22-MMSC::module-1-0</vf-module-name>" + EOL +
- " </vnf-inputs>" + EOL +
- " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL +
- "</vnf-request>" + EOL;
- new MockAAIGenericVnfSearch(wireMockServer);
- new MockAAIDeleteGenericVnf(wireMockServer);
- new MockAAIDeleteVfModule(wireMockServer);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("DeleteAAIVfModuleRequest",request);
- String processId = invokeSubProcess("DeleteAAIVfModule", variables);
- WorkflowException exception = BPMNUtil.getRawVariable(processEngine, "DeleteAAIVfModule", "WorkflowException",processId);
- Assert.assertEquals(1002, exception.getErrorCode());
- Assert.assertEquals(true, exception.getErrorMessage().contains("Generic VNF Not Found"));
- logger.debug(exception.getErrorMessage());
- }
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("DeleteAAIVfModuleRequest", request);
+ String processId = invokeSubProcess("DeleteAAIVfModule", variables);
+ WorkflowException exception =
+ BPMNUtil.getRawVariable(processEngine, "DeleteAAIVfModule", "WorkflowException", processId);
+ Assert.assertEquals(1002, exception.getErrorCode());
+ Assert.assertEquals(true, exception.getErrorMessage().contains("is Base Module, not Last Module"));
+ logger.debug(exception.getErrorMessage());
+ }
- @Test
- public void TestDeleteGenericVnfFailure_5000() {
- // A&AI failure (non-200) when attempting to delete a Generic Vnf
- // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c718, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a78
- String request =
- "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL +
- " <request-info>" + EOL +
- " <action>DELETE_VF_MODULE</action>" + EOL +
- " <source>PORTAL</source>" + EOL +
- " </request-info>" + EOL +
- " <vnf-inputs>" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c718</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC18</vnf-name>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC18-MMSC::module-0-0</vf-module-name>" + EOL +
- " </vnf-inputs>" + EOL +
- " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL +
- "</vnf-request>" + EOL;
- new MockAAIGenericVnfSearch(wireMockServer);
- new MockAAIDeleteGenericVnf(wireMockServer);
- new MockAAIDeleteVfModule(wireMockServer);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("DeleteAAIVfModuleRequest",request);
- String processId = invokeSubProcess("DeleteAAIVfModule", variables);
- WorkflowException exception = BPMNUtil.getRawVariable(processEngine, "DeleteAAIVfModule", "WorkflowException",processId);
- Assert.assertEquals(5000, exception.getErrorCode());
- Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>"));
- logger.debug(exception.getErrorMessage());
- }
-
- @Test
- public void TestDeleteVfModuleFailure_5000() {
- // A&AI failure (non-200) when attempting to delete a Vf Module
- // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c719, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a77
- String request =
- "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL +
- " <request-info>" + EOL +
- " <action>DELETE_VF_MODULE</action>" + EOL +
- " <source>PORTAL</source>" + EOL +
- " </request-info>" + EOL +
- " <vnf-inputs>" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c719</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC19</vnf-name>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC19-MMSC::module-1-0</vf-module-name>" + EOL +
- " </vnf-inputs>" + EOL +
- " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL +
- "</vnf-request>" + EOL;
- new MockAAIGenericVnfSearch(wireMockServer);
- new MockAAIDeleteGenericVnf(wireMockServer);
- new MockAAIDeleteVfModule(wireMockServer);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("DeleteAAIVfModuleRequest",request);
- String processId = invokeSubProcess("DeleteAAIVfModule", variables);
- WorkflowException exception = BPMNUtil.getRawVariable(processEngine, "DeleteAAIVfModule", "WorkflowException",processId);
- Assert.assertEquals(5000, exception.getErrorCode());
- Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>"));
- logger.debug(exception.getErrorMessage());
- }
-
- @Test
- public void TestDeleteVfModuleFailure_1002_1() {
- // failure attempting to delete Base Module when not the last Vf Module
- // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a74
- String request =
- "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL +
- " <request-info>" + EOL +
- " <action>DELETE_VF_MODULE</action>" + EOL +
- " <source>PORTAL</source>" + EOL +
- " </request-info>" + EOL +
- " <vnf-inputs>" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL +
- " </vnf-inputs>" + EOL +
- " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL +
- "</vnf-request>" + EOL;
- new MockAAIGenericVnfSearch(wireMockServer);
- new MockAAIDeleteGenericVnf(wireMockServer);
- new MockAAIDeleteVfModule(wireMockServer);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("DeleteAAIVfModuleRequest",request);
- String processId = invokeSubProcess("DeleteAAIVfModule", variables);
- WorkflowException exception = BPMNUtil.getRawVariable(processEngine, "DeleteAAIVfModule", "WorkflowException",processId);
- Assert.assertEquals(1002, exception.getErrorCode());
- Assert.assertEquals(true, exception.getErrorMessage().contains("is Base Module, not Last Module"));
- logger.debug(exception.getErrorMessage());
- }
+ @Test
+ public void TestDeleteVfModuleFailure_1002_2() {
+ // failure attempting to delete a Vf Module that does not exist (A&AI returns 404)
+ // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a76
+ new MockAAIGenericVnfSearch(wireMockServer);
+ new MockAAIDeleteGenericVnf(wireMockServer);
+ new MockAAIDeleteVfModule(wireMockServer);
- @Test
- public void TestDeleteVfModuleFailure_1002_2() {
- // failure attempting to delete a Vf Module that does not exist (A&AI returns 404)
- // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a76
- new MockAAIGenericVnfSearch(wireMockServer);
- new MockAAIDeleteGenericVnf(wireMockServer);
- new MockAAIDeleteVfModule(wireMockServer);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("DeleteAAIVfModuleRequest","<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\"> <request-info> <action>DELETE_VF_MODULE</action> <source>PORTAL</source> </request-info> <vnf-inputs> <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id> <vnf-name>STMTN5MMSC20</vnf-name> <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</vf-module-id> <vf-module-name>STMTN5MMSC20-MMSC::module-2-0</vf-module-name> </vnf-inputs> <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/> </vnf-request>");
- String processId = invokeSubProcess("DeleteAAIVfModule", variables);
- WorkflowException exception = BPMNUtil.getRawVariable(processEngine, "DeleteAAIVfModule", "WorkflowException",processId);
- Assert.assertEquals(1002, exception.getErrorCode());
- Assert.assertEquals(true, exception.getErrorMessage().contains("does not exist for Generic Vnf Id"));
- logger.debug(exception.getErrorMessage());
- }
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("DeleteAAIVfModuleRequest",
+ "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\"> <request-info> <action>DELETE_VF_MODULE</action> <source>PORTAL</source> </request-info> <vnf-inputs> <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id> <vnf-name>STMTN5MMSC20</vnf-name> <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</vf-module-id> <vf-module-name>STMTN5MMSC20-MMSC::module-2-0</vf-module-name> </vnf-inputs> <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/> </vnf-request>");
+ String processId = invokeSubProcess("DeleteAAIVfModule", variables);
+ WorkflowException exception =
+ BPMNUtil.getRawVariable(processEngine, "DeleteAAIVfModule", "WorkflowException", processId);
+ Assert.assertEquals(1002, exception.getErrorCode());
+ Assert.assertEquals(true, exception.getErrorMessage().contains("does not exist for Generic Vnf Id"));
+ logger.debug(exception.getErrorMessage());
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/FalloutHandlerIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/FalloutHandlerIT.java
index 88f8e5deb7..59f46b2a93 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/FalloutHandlerIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/FalloutHandlerIT.java
@@ -18,7 +18,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
@@ -26,11 +26,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.onap.so.bpmn.common.BPMNUtil.waitForWorkflowToFinish;
-
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.junit.Assert;
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
@@ -42,185 +40,164 @@ import org.slf4j.LoggerFactory;
*/
public class FalloutHandlerIT extends BaseIntegrationTest {
-
- Logger logger = LoggerFactory.getLogger(FalloutHandlerIT.class);
-
-
- private void setupMocks() {
- wireMockServer.stubFor(post(urlEqualTo("/dbadapters/AttRequestsDbAdapter"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody("<DbTag>Notified</DbTag>")));
- wireMockServer.stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody("<DbTag>Notified</DbTag>")));
- }
-
- private String executeFlow(String inputRequestFile) throws InterruptedException {
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("FalloutHandlerRequest",inputRequestFile); variables.put("mso-request-id", UUID.randomUUID().toString());
- String processId = invokeSubProcess( "FalloutHandler", variables);
- waitForWorkflowToFinish(processEngine,processId);
- logEnd();
- return processId;
- }
-
- @Test
- public void msoFalloutHandlerWithNotificationurl_200() throws Exception{
- //Setup Mocks
- setupMocks();
- //Execute Flow
- String processId = executeFlow(gMsoFalloutHandlerWithNotificationurl());
- //Verify Error
- String FH_ResponseCode = BPMNUtil.getVariable(processEngine, "FalloutHandler", "FH_ResponseCode",processId);
- Assert.assertEquals("200", FH_ResponseCode);
- Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngine, "FalloutHandler", "FH_SuccessIndicator",processId));
- }
-
- public String gMsoFalloutHandlerWithNotificationurl() {
- //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
- String xml = ""
- + "<sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns7=\"http://org.onap/so/request/types/v1\">"
- + " <ns7:request-information>"
- + " <ns7:request-id>1020_STUW105_5002</ns7:request-id>"
- + " <ns7:request-action>requestAction</ns7:request-action>"
- + " <ns7:request-sub-action>CANCEL</ns7:request-sub-action>"
- + " <ns7:source>source</ns7:source>"
- + " <ns7:notification-url>http://localhost:28090/CCD/StatusNotification</ns7:notification-url>"
- + " <ns7:order-number>10205000</ns7:order-number>"
- + " <ns7:order-version>1</ns7:order-version>"
- + " </ns7:request-information>"
- + " <sdncadapterworkflow:WorkflowException>"
- + " <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage>"
- + " <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode>"
- + " <sdncadapterworkflow:SourceSystemErrorCode>Some Source System Error Code- Fallout Handler</sdncadapterworkflow:SourceSystemErrorCode>"
- + " </sdncadapterworkflow:WorkflowException>"
- + "</sdncadapterworkflow:FalloutHandlerRequest>";
-
- return xml;
-
- }
-
-
-
-
- @Test
- public void msoFalloutHandlerWithNoNotificationurl() throws Exception{
-
- //Setup Mocks
- setupMocks();
- //Execute Flow
- executeFlow(gMsoFalloutHandlerWithNoNotificationurl());
- //Verify Error
- String FH_ResponseCode = BPMNUtil.getVariable(processEngine, "FalloutHandler", "FH_ResponseCode");
- Assert.assertEquals("200", FH_ResponseCode);
- Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngine, "FalloutHandler", "FH_SuccessIndicator"));
- }
-
- public String gMsoFalloutHandlerWithNoNotificationurl() {
- //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
- String xml = ""
- + "<sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns7=\"http://org.onap/so/request/types/v1\">"
- + " <ns7:request-information>"
- + " <ns7:request-id>1020_STUW105_5002</ns7:request-id>"
- + " <ns7:request-action>requestAction</ns7:request-action>"
- + " <ns7:request-sub-action>CANCEL</ns7:request-sub-action>"
- + " <ns7:source>source</ns7:source>"
- + " <ns7:notification-url></ns7:notification-url>"
- + " <ns7:order-number>10205000</ns7:order-number>"
- + " <ns7:order-version>1</ns7:order-version>"
- + " </ns7:request-information>"
- + " <sdncadapterworkflow:WorkflowException>"
- + " <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage>"
- + " <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode>"
- + " <sdncadapterworkflow:SourceSystemErrorCode>Some Source System Error Code- Fallout Handler</sdncadapterworkflow:SourceSystemErrorCode>"
- + " </sdncadapterworkflow:WorkflowException>"
- + "</sdncadapterworkflow:FalloutHandlerRequest>";
-
- return xml;
- }
-
- @Test
-
- public void msoFalloutHandlerWithNotificationurlNoRequestId() throws Exception{
- String method = getClass().getSimpleName() + "." + new Object() {
- }.getClass().getEnclosingMethod().getName();
- logger.debug("STARTED TEST: {}", method);
- //Setup Mocks
- setupMocks();
- //Execute Flow
- executeFlow(gMsoFalloutHandlerWithNotificationurlNoRequestId());
- //Verify Error
- String FH_ResponseCode = BPMNUtil.getVariable(processEngine, "FalloutHandler", "FH_ResponseCode");
- Assert.assertEquals("200", FH_ResponseCode);
- Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngine, "FalloutHandler", "FH_SuccessIndicator"));
- }
-
- public String gMsoFalloutHandlerWithNotificationurlNoRequestId() {
- //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
- String xml = ""
- + "<sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns7=\"http://org.onap/so/request/types/v1\">"
- + " <ns7:request-information>"
- + " <ns7:request-id></ns7:request-id>"
- + " <ns7:request-action>requestAction</ns7:request-action>"
- + " <ns7:request-sub-action>CANCEL</ns7:request-sub-action>"
- + " <ns7:source>source</ns7:source>"
- + " <ns7:notification-url>www.test.com</ns7:notification-url>"
- + " <ns7:order-number>10205000</ns7:order-number>"
- + " <ns7:order-version>1</ns7:order-version>"
- + " </ns7:request-information>"
- + " <sdncadapterworkflow:WorkflowException>"
- + " <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage>"
- + " <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode>"
- + " <sdncadapterworkflow:SourceSystemErrorCode>Some Source System Error Code- Fallout Handler</sdncadapterworkflow:SourceSystemErrorCode>"
- + " </sdncadapterworkflow:WorkflowException>"
- + "</sdncadapterworkflow:FalloutHandlerRequest>";
-
- return xml;
- }
-
- @Test
-
- public void msoFalloutHandlerWithNoNotificationurlNoRequestId() throws Exception{
- String method = getClass().getSimpleName() + "." + new Object() {
- }.getClass().getEnclosingMethod().getName();
- logger.debug("STARTED TEST: {}", method);
- //Setup Mocks
- setupMocks();
- //Execute Flow
- executeFlow(gMsoFalloutHandlerWithNoNotificationurlNoRequestId());
- //Verify Error
- String FH_ResponseCode = BPMNUtil.getVariable(processEngine, "FalloutHandler", "FH_ResponseCode");
- Assert.assertEquals("200", FH_ResponseCode);
- Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngine, "FalloutHandler", "FH_SuccessIndicator"));
- }
-
- public String gMsoFalloutHandlerWithNoNotificationurlNoRequestId() {
- //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
- String xml = ""
- + "<sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns7=\"http://org.onap/so/request/types/v1\">"
- + " <ns7:request-information>"
- + " <ns7:request-id></ns7:request-id>"
- + " <ns7:request-action>requestAction</ns7:request-action>"
- + " <ns7:request-sub-action>CANCEL</ns7:request-sub-action>"
- + " <ns7:source>source</ns7:source>"
- + " <ns7:notification-url></ns7:notification-url>"
- + " <ns7:order-number>10205000</ns7:order-number>"
- + " <ns7:order-version>1</ns7:order-version>"
- + " </ns7:request-information>"
- + " <sdncadapterworkflow:WorkflowException>"
- + " <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage>"
- + " <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode>"
- + " <sdncadapterworkflow:SourceSystemErrorCode>Some Source System Error Code- Fallout Handler</sdncadapterworkflow:SourceSystemErrorCode>"
- + " </sdncadapterworkflow:WorkflowException>"
- + "</sdncadapterworkflow:FalloutHandlerRequest>";
-
- return xml;
- }
-
+
+ Logger logger = LoggerFactory.getLogger(FalloutHandlerIT.class);
+
+
+ private void setupMocks() {
+ wireMockServer.stubFor(post(urlEqualTo("/dbadapters/AttRequestsDbAdapter")).willReturn(aResponse()
+ .withStatus(200).withHeader("Content-Type", "text/xml").withBody("<DbTag>Notified</DbTag>")));
+ wireMockServer.stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter")).willReturn(aResponse().withStatus(200)
+ .withHeader("Content-Type", "text/xml").withBody("<DbTag>Notified</DbTag>")));
+ }
+
+ private String executeFlow(String inputRequestFile) throws InterruptedException {
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("FalloutHandlerRequest", inputRequestFile);
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ String processId = invokeSubProcess("FalloutHandler", variables);
+ waitForWorkflowToFinish(processEngine, processId);
+ logEnd();
+ return processId;
+ }
+
+ @Test
+ public void msoFalloutHandlerWithNotificationurl_200() throws Exception {
+ // Setup Mocks
+ setupMocks();
+ // Execute Flow
+ String processId = executeFlow(gMsoFalloutHandlerWithNotificationurl());
+ // Verify Error
+ String FH_ResponseCode = BPMNUtil.getVariable(processEngine, "FalloutHandler", "FH_ResponseCode", processId);
+ Assert.assertEquals("200", FH_ResponseCode);
+ Assert.assertTrue(
+ (boolean) BPMNUtil.getRawVariable(processEngine, "FalloutHandler", "FH_SuccessIndicator", processId));
+ }
+
+ public String gMsoFalloutHandlerWithNotificationurl() {
+ // Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
+ String xml = ""
+ + "<sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns7=\"http://org.onap/so/request/types/v1\">"
+ + " <ns7:request-information>" + " <ns7:request-id>1020_STUW105_5002</ns7:request-id>"
+ + " <ns7:request-action>requestAction</ns7:request-action>"
+ + " <ns7:request-sub-action>CANCEL</ns7:request-sub-action>"
+ + " <ns7:source>source</ns7:source>"
+ + " <ns7:notification-url>http://localhost:28090/CCD/StatusNotification</ns7:notification-url>"
+ + " <ns7:order-number>10205000</ns7:order-number>"
+ + " <ns7:order-version>1</ns7:order-version>" + " </ns7:request-information>"
+ + " <sdncadapterworkflow:WorkflowException>"
+ + " <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage>"
+ + " <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode>"
+ + " <sdncadapterworkflow:SourceSystemErrorCode>Some Source System Error Code- Fallout Handler</sdncadapterworkflow:SourceSystemErrorCode>"
+ + " </sdncadapterworkflow:WorkflowException>" + "</sdncadapterworkflow:FalloutHandlerRequest>";
+
+ return xml;
+
+ }
+
+
+
+ @Test
+ public void msoFalloutHandlerWithNoNotificationurl() throws Exception {
+
+ // Setup Mocks
+ setupMocks();
+ // Execute Flow
+ executeFlow(gMsoFalloutHandlerWithNoNotificationurl());
+ // Verify Error
+ String FH_ResponseCode = BPMNUtil.getVariable(processEngine, "FalloutHandler", "FH_ResponseCode");
+ Assert.assertEquals("200", FH_ResponseCode);
+ Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngine, "FalloutHandler", "FH_SuccessIndicator"));
+ }
+
+ public String gMsoFalloutHandlerWithNoNotificationurl() {
+ // Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
+ String xml = ""
+ + "<sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns7=\"http://org.onap/so/request/types/v1\">"
+ + " <ns7:request-information>" + " <ns7:request-id>1020_STUW105_5002</ns7:request-id>"
+ + " <ns7:request-action>requestAction</ns7:request-action>"
+ + " <ns7:request-sub-action>CANCEL</ns7:request-sub-action>"
+ + " <ns7:source>source</ns7:source>" + " <ns7:notification-url></ns7:notification-url>"
+ + " <ns7:order-number>10205000</ns7:order-number>"
+ + " <ns7:order-version>1</ns7:order-version>" + " </ns7:request-information>"
+ + " <sdncadapterworkflow:WorkflowException>"
+ + " <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage>"
+ + " <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode>"
+ + " <sdncadapterworkflow:SourceSystemErrorCode>Some Source System Error Code- Fallout Handler</sdncadapterworkflow:SourceSystemErrorCode>"
+ + " </sdncadapterworkflow:WorkflowException>" + "</sdncadapterworkflow:FalloutHandlerRequest>";
+
+ return xml;
+ }
+
+ @Test
+
+ public void msoFalloutHandlerWithNotificationurlNoRequestId() throws Exception {
+ String method = getClass().getSimpleName() + "." + new Object() {}.getClass().getEnclosingMethod().getName();
+ logger.debug("STARTED TEST: {}", method);
+ // Setup Mocks
+ setupMocks();
+ // Execute Flow
+ executeFlow(gMsoFalloutHandlerWithNotificationurlNoRequestId());
+ // Verify Error
+ String FH_ResponseCode = BPMNUtil.getVariable(processEngine, "FalloutHandler", "FH_ResponseCode");
+ Assert.assertEquals("200", FH_ResponseCode);
+ Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngine, "FalloutHandler", "FH_SuccessIndicator"));
+ }
+
+ public String gMsoFalloutHandlerWithNotificationurlNoRequestId() {
+ // Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
+ String xml = ""
+ + "<sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns7=\"http://org.onap/so/request/types/v1\">"
+ + " <ns7:request-information>" + " <ns7:request-id></ns7:request-id>"
+ + " <ns7:request-action>requestAction</ns7:request-action>"
+ + " <ns7:request-sub-action>CANCEL</ns7:request-sub-action>"
+ + " <ns7:source>source</ns7:source>"
+ + " <ns7:notification-url>www.test.com</ns7:notification-url>"
+ + " <ns7:order-number>10205000</ns7:order-number>"
+ + " <ns7:order-version>1</ns7:order-version>" + " </ns7:request-information>"
+ + " <sdncadapterworkflow:WorkflowException>"
+ + " <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage>"
+ + " <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode>"
+ + " <sdncadapterworkflow:SourceSystemErrorCode>Some Source System Error Code- Fallout Handler</sdncadapterworkflow:SourceSystemErrorCode>"
+ + " </sdncadapterworkflow:WorkflowException>" + "</sdncadapterworkflow:FalloutHandlerRequest>";
+
+ return xml;
+ }
+
+ @Test
+
+ public void msoFalloutHandlerWithNoNotificationurlNoRequestId() throws Exception {
+ String method = getClass().getSimpleName() + "." + new Object() {}.getClass().getEnclosingMethod().getName();
+ logger.debug("STARTED TEST: {}", method);
+ // Setup Mocks
+ setupMocks();
+ // Execute Flow
+ executeFlow(gMsoFalloutHandlerWithNoNotificationurlNoRequestId());
+ // Verify Error
+ String FH_ResponseCode = BPMNUtil.getVariable(processEngine, "FalloutHandler", "FH_ResponseCode");
+ Assert.assertEquals("200", FH_ResponseCode);
+ Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngine, "FalloutHandler", "FH_SuccessIndicator"));
+ }
+
+ public String gMsoFalloutHandlerWithNoNotificationurlNoRequestId() {
+ // Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS
+ String xml = ""
+ + "<sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns7=\"http://org.onap/so/request/types/v1\">"
+ + " <ns7:request-information>" + " <ns7:request-id></ns7:request-id>"
+ + " <ns7:request-action>requestAction</ns7:request-action>"
+ + " <ns7:request-sub-action>CANCEL</ns7:request-sub-action>"
+ + " <ns7:source>source</ns7:source>" + " <ns7:notification-url></ns7:notification-url>"
+ + " <ns7:order-number>10205000</ns7:order-number>"
+ + " <ns7:order-version>1</ns7:order-version>" + " </ns7:request-information>"
+ + " <sdncadapterworkflow:WorkflowException>"
+ + " <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage>"
+ + " <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode>"
+ + " <sdncadapterworkflow:SourceSystemErrorCode>Some Source System Error Code- Fallout Handler</sdncadapterworkflow:SourceSystemErrorCode>"
+ + " </sdncadapterworkflow:WorkflowException>" + "</sdncadapterworkflow:FalloutHandlerRequest>";
+
+ return xml;
+ }
+
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/GenerateVfModuleNameIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/GenerateVfModuleNameIT.java
index 7299e0602e..ff0b318df9 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/GenerateVfModuleNameIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/GenerateVfModuleNameIT.java
@@ -22,10 +22,8 @@ package org.onap.so.bpmn.common;
import static org.junit.Assert.assertNotNull;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetGenericVnfById;
-
import java.util.HashMap;
import java.util.Map;
-
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Ignore;
@@ -37,42 +35,37 @@ import org.onap.so.BaseIntegrationTest;
*/
public class GenerateVfModuleNameIT extends BaseIntegrationTest {
- private static final String EOL = "\n";
-
- @Test
- public void TestGenerateVfModuleNameSuvvess() {
- //
- String request =
- "<vnf-request xmlns=\"http://ecomp.att.com/mso/infra/vnf-request/v1\">" + EOL +
- " <request-info>" + EOL +
- " <action>CREATE_VF_MODULE</action>" + EOL +
- " <source>PORTAL</source>" + EOL +
- " </request-info>" + EOL +
- " <vnf-inputs>" + EOL +
- " <vnf-name>STMTN5MMSC22</vnf-name>" + EOL +
- " <vf-module-name>STMTN5MMSC22-MMSC::module-0-0</vf-module-name>" + EOL +
- " <vf-module-model-name>MMSC::module-0</vf-module-model-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <service-id>00000000-0000-0000-0000-000000000000</service-id>" + EOL +
- " <aic-node-clli>MDTWNJ21</aic-node-clli>" + EOL +
- " <tenant-id>fba1bd1e195a404cacb9ce17a9b2b421</tenant-id>" + EOL +
- " </vnf-inputs>" + EOL +
- " <vnf-params xmlns:tns=\"http://ecomp.att.com/mso/infra/vnf-request/v1\"/>" + EOL +
- "</vnf-request>" + EOL;
+ private static final String EOL = "\n";
+
+ @Test
+ public void TestGenerateVfModuleNameSuvvess() {
+ //
+ String request =
+ "<vnf-request xmlns=\"http://ecomp.att.com/mso/infra/vnf-request/v1\">" + EOL + " <request-info>" + EOL
+ + " <action>CREATE_VF_MODULE</action>" + EOL + " <source>PORTAL</source>" + EOL
+ + " </request-info>" + EOL + " <vnf-inputs>" + EOL + " <vnf-name>STMTN5MMSC22</vnf-name>"
+ + EOL + " <vf-module-name>STMTN5MMSC22-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <vf-module-model-name>MMSC::module-0</vf-module-model-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <service-id>00000000-0000-0000-0000-000000000000</service-id>" + EOL
+ + " <aic-node-clli>MDTWNJ21</aic-node-clli>" + EOL
+ + " <tenant-id>fba1bd1e195a404cacb9ce17a9b2b421</tenant-id>" + EOL + " </vnf-inputs>" + EOL
+ + " <vnf-params xmlns:tns=\"http://ecomp.att.com/mso/infra/vnf-request/v1\"/>" + EOL
+ + "</vnf-request>" + EOL;
+
+ MockGetGenericVnfById(wireMockServer, ".*", "GenericFlows/getGenericVnfByNameResponse.xml");
+ RuntimeService runtimeService = processEngine.getRuntimeService();
+ Map<String, Object> variables = new HashMap<String, Object>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("vnfName", "STMTN5MMSC20");
+ variables.put("vfModuleLabel", "ModuleLabel1");
+ variables.put("personaModelId", "extrovert");
+ variables.put("vnfId", "12345678-f41f-4822-9323-b75962763d74");
+
+ runtimeService.startProcessInstanceByKey("GenerateVfModuleName", variables);
+ String response = BPMNUtil.getVariable(processEngine, "GenerateVfModuleName", "vfModuleName");
- MockGetGenericVnfById(wireMockServer, ".*", "GenericFlows/getGenericVnfByNameResponse.xml");
- RuntimeService runtimeService = processEngine.getRuntimeService();
- Map<String, Object> variables = new HashMap<String, Object>();
- variables.put("isDebugLogEnabled","true");
- variables.put("vnfName", "STMTN5MMSC20");
- variables.put("vfModuleLabel", "ModuleLabel1");
- variables.put("personaModelId", "extrovert");
- variables.put("vnfId", "12345678-f41f-4822-9323-b75962763d74");
-
- runtimeService.startProcessInstanceByKey("GenerateVfModuleName", variables);
- String response = BPMNUtil.getVariable(processEngine, "GenerateVfModuleName", "vfModuleName");
-
- assertNotNull(response);
- }
+ assertNotNull(response);
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ManualHandlingIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ManualHandlingIT.java
index 53d29c51bf..97a09d84aa 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ManualHandlingIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ManualHandlingIT.java
@@ -23,12 +23,10 @@
package org.onap.so.bpmn.common;
import static org.onap.so.bpmn.mock.StubResponseDatabase.MockPostRequestDB;
-
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.task.TaskQuery;
@@ -42,58 +40,58 @@ import org.slf4j.LoggerFactory;
* Unit test for RainyDayHandler.bpmn.
*/
public class ManualHandlingIT extends BaseIntegrationTest {
- Logger logger = LoggerFactory.getLogger(ManualHandlingIT.class);
-
- @Test
- public void TestManualHandlingSuccess() {
- MockPostRequestDB(wireMockServer);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("msoRequestId", "testRequestId");
- variables.put("serviceType", "X");
- variables.put("vnfType", "Y");
- variables.put("currentActivity", "BB1");
- variables.put("workStep", "1");
- variables.put("failedActivity", "AAI");
- variables.put("vnfName", "vSAMP12");
- variables.put("errorCode", "123");
- variables.put("errorText", "update failed");
- variables.put("validResponses", "Rollback");
- variables.put("vnfName", "vSAMP1");
-
-
- String businessKey = UUID.randomUUID().toString();
- invokeSubProcess("ManualHandling", businessKey, variables);
-
- try {
- Thread.sleep(5);
- } catch (Exception e) {
-
- }
-
- TaskService taskService = processEngine.getTaskService();
-
- TaskQuery q = taskService.createTaskQuery();
-
- List<Task> tasks = q.orderByTaskCreateTime().asc().list();
-
- for (Task task : tasks) {
- logger.debug("TASK ID: {}", task.getId());
- logger.debug("TASK NAME: {}", task.getName());
-
- try {
- logger.debug("Completing the task");
- Map<String,Object> completeVariables = new HashMap<>();
- completeVariables.put("responseValue", "skip");
- taskService.complete(task.getId(), completeVariables);
- } catch(Exception e) {
- logger.debug("GOT EXCEPTION: {}", e.getMessage());
- }
- }
-
- waitForProcessEnd(businessKey, 100000);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- }
+ Logger logger = LoggerFactory.getLogger(ManualHandlingIT.class);
+
+ @Test
+ public void TestManualHandlingSuccess() {
+ MockPostRequestDB(wireMockServer);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("msoRequestId", "testRequestId");
+ variables.put("serviceType", "X");
+ variables.put("vnfType", "Y");
+ variables.put("currentActivity", "BB1");
+ variables.put("workStep", "1");
+ variables.put("failedActivity", "AAI");
+ variables.put("vnfName", "vSAMP12");
+ variables.put("errorCode", "123");
+ variables.put("errorText", "update failed");
+ variables.put("validResponses", "Rollback");
+ variables.put("vnfName", "vSAMP1");
+
+
+ String businessKey = UUID.randomUUID().toString();
+ invokeSubProcess("ManualHandling", businessKey, variables);
+
+ try {
+ Thread.sleep(5);
+ } catch (Exception e) {
+
+ }
+
+ TaskService taskService = processEngine.getTaskService();
+
+ TaskQuery q = taskService.createTaskQuery();
+
+ List<Task> tasks = q.orderByTaskCreateTime().asc().list();
+
+ for (Task task : tasks) {
+ logger.debug("TASK ID: {}", task.getId());
+ logger.debug("TASK NAME: {}", task.getName());
+
+ try {
+ logger.debug("Completing the task");
+ Map<String, Object> completeVariables = new HashMap<>();
+ completeVariables.put("responseValue", "skip");
+ taskService.complete(task.getId(), completeVariables);
+ } catch (Exception e) {
+ logger.debug("GOT EXCEPTION: {}", e.getMessage());
+ }
+ }
+
+ waitForProcessEnd(businessKey, 100000);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteGenericVnf.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteGenericVnf.java
index 052fd5dc94..45ef0add2b 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteGenericVnf.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteGenericVnf.java
@@ -23,18 +23,16 @@ package org.onap.so.bpmn.common;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.delete;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
-
import com.github.tomakehurst.wiremock.WireMockServer;
public class MockAAIDeleteGenericVnf {
- public MockAAIDeleteGenericVnf(WireMockServer wireMockServer){
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/[?]resource-version=0000021"))
- .willReturn(aResponse()
- .withStatus(200)));
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/[?]resource-version=0000018"))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("aaiFault.xml")));
- }
+ public MockAAIDeleteGenericVnf(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/[?]resource-version=0000021"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/[?]resource-version=0000018"))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "text/xml")
+ .withBodyFile("aaiFault.xml")));
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteVfModule.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteVfModule.java
index 1cbe0b9244..f405fc943b 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteVfModule.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIDeleteVfModule.java
@@ -24,31 +24,30 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.delete;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
-
import com.github.tomakehurst.wiremock.WireMockServer;
public class MockAAIDeleteVfModule {
-
- public MockAAIDeleteVfModule(WireMockServer wireMockServer)
- {
- wireMockServer.stubFor(delete(urlMatching(
- "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73/[?]resource-version=0000073"))
- .willReturn(aResponse().withStatus(200)));
- wireMockServer.stubFor(delete(urlMatching(
- "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a75/[?]resource-version=0000075"))
- .willReturn(aResponse().withStatus(200)));
- wireMockServer.stubFor(delete(urlMatching(
- "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a78/[?]resource-version=0000078"))
- .willReturn(aResponse().withStatus(200)));
- wireMockServer.stubFor(delete(urlMatching(
- "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a77/[?]resource-version=0000077"))
- .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "text/xml")
- .withBodyFile("aaiFault.xml")));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*"))
- .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
- .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml")));
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*"))
- .willReturn(aResponse().withStatus(200)));
- }
+ public MockAAIDeleteVfModule(WireMockServer wireMockServer) {
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73/[?]resource-version=0000073"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a75/[?]resource-version=0000075"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a78/[?]resource-version=0000078"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(delete(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a77/[?]resource-version=0000077"))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "text/xml")
+ .withBodyFile("aaiFault.xml")));
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml")));
+
+ wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*"))
+ .willReturn(aResponse().withStatus(200)));
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIGenericVnfSearch.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIGenericVnfSearch.java
index 1d6337ffc4..a33268efbe 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIGenericVnfSearch.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockAAIGenericVnfSearch.java
@@ -23,319 +23,219 @@ package org.onap.so.bpmn.common;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
-
import com.github.tomakehurst.wiremock.WireMockServer;
public class MockAAIGenericVnfSearch {
-
- private static final String EOL = "\n";
- public MockAAIGenericVnfSearch(WireMockServer wireMockServer){
- String body;
-
- // The following stubs are for CreateAAIVfModule and UpdateAAIVfModule
-
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC23&depth=1"))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("aaiFault.xml")));
-
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC22&depth=1"))
- .willReturn(aResponse()
- .withStatus(404)
- .withHeader("Content-Type", "text/xml")
- .withBody("Generic VNF Not Found")));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/768073c7-f41f-4822-9323-b75962763d74[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(404)
- .withHeader("Content-Type", "text/xml")
- .withBody("Generic VNF Not Found")));
-
- body =
- "<generic-vnf xmlns=\"http://com.aai.inventory/v7\">" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>1508691</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>1508692</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC21&depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- body =
- "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL +
- " <vnf-id>2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>1508691</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>1508692</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>false</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>1508692</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC20&depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- // The following stubs are for DeleteAAIVfModule
-
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c723[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(500)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("aaiFault.xml")));
-
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c722[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(404)
- .withHeader("Content-Type", "text/xml")
- .withBody("Generic VNF Not Found")));
-
- body =
- "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>0000021</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000073</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- body =
- "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>0000020</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000074</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>false</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000075</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- body =
- "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c719</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC19</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>0000019</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC19-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000076</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC19-MMSC::module-1-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>false</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000077</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- body =
- "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c718</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC18</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>0000018</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC18-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000078</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718[?]depth=1"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- body =
- "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL +
- " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL +
- " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL +
- " <vnf-type>mmsc-capacity</vnf-type>" + EOL +
- " <service-id>SDN-MOBILITY</service-id>" + EOL +
- " <equipment-role>vMMSC</equipment-role>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <in-maint>false</in-maint>" + EOL +
- " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL +
- " <resource-version>0000021</resource-version>" + EOL +
- " <vf-modules>" + EOL +
- " <vf-module>" + EOL +
- " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL +
- " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL +
- " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL +
- " <persona-model-version>1.0</persona-model-version>" + EOL +
- " <is-base-vf-module>true</is-base-vf-module>" + EOL +
- " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL +
- " <orchestration-status>pending-create</orchestration-status>" + EOL +
- " <resource-version>0000073</resource-version>" + EOL +
- " </vf-module>" + EOL +
- " </vf-modules>" + EOL +
- " <relationship-list/>" + EOL +
- " <l-interfaces/>" + EOL +
- " <lag-interfaces/>" + EOL +
- "</generic-vnf>" + EOL;
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBody(body)));
-
- }
+ private static final String EOL = "\n";
+
+ public MockAAIGenericVnfSearch(WireMockServer wireMockServer) {
+ String body;
+
+ // The following stubs are for CreateAAIVfModule and UpdateAAIVfModule
+
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC23&depth=1"))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "text/xml")
+ .withBodyFile("aaiFault.xml")));
+
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC22&depth=1"))
+ .willReturn(aResponse().withStatus(404).withHeader("Content-Type", "text/xml")
+ .withBody("Generic VNF Not Found")));
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/768073c7-f41f-4822-9323-b75962763d74[?]depth=1"))
+ .willReturn(aResponse().withStatus(404).withHeader("Content-Type", "text/xml")
+ .withBody("Generic VNF Not Found")));
+
+ body = "<generic-vnf xmlns=\"http://com.aai.inventory/v7\">" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>1508691</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>1508692</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC21&depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ body = "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL
+ + " <vnf-id>2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>1508691</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>1508692</resource-version>" + EOL + " </vf-module>" + EOL
+ + " <vf-module>" + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>"
+ + EOL + " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>false</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>1508692</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(
+ get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC20&depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ // The following stubs are for DeleteAAIVfModule
+
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c723[?]depth=1"))
+ .willReturn(aResponse().withStatus(500).withHeader("Content-Type", "text/xml")
+ .withBodyFile("aaiFault.xml")));
+
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c722[?]depth=1"))
+ .willReturn(aResponse().withStatus(404).withHeader("Content-Type", "text/xml")
+ .withBody("Generic VNF Not Found")));
+
+ body = "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>0000021</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000073</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ body = "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>0000020</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000074</resource-version>" + EOL + " </vf-module>" + EOL
+ + " <vf-module>" + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</vf-module-id>"
+ + EOL + " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>false</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000075</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ body = "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c719</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC19</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>0000019</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC19-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000076</resource-version>" + EOL + " </vf-module>" + EOL
+ + " <vf-module>" + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</vf-module-id>"
+ + EOL + " <vf-module-name>STMTN5MMSC19-MMSC::module-1-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>false</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000077</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ body = "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c718</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC18</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>0000018</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC18-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000078</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718[?]depth=1"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ body = "<generic-vnf xmlns=\"http://org.openecomp.aai.inventory/v7\">" + EOL
+ + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL
+ + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + " <vnf-type>mmsc-capacity</vnf-type>" + EOL
+ + " <service-id>SDN-MOBILITY</service-id>" + EOL + " <equipment-role>vMMSC</equipment-role>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL + " <in-maint>false</in-maint>"
+ + EOL + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL
+ + " <resource-version>0000021</resource-version>" + EOL + " <vf-modules>" + EOL + " <vf-module>"
+ + EOL + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL
+ + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL
+ + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL
+ + " <persona-model-version>1.0</persona-model-version>" + EOL
+ + " <is-base-vf-module>true</is-base-vf-module>" + EOL
+ + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL
+ + " <orchestration-status>pending-create</orchestration-status>" + EOL
+ + " <resource-version>0000073</resource-version>" + EOL + " </vf-module>" + EOL
+ + " </vf-modules>" + EOL + " <relationship-list/>" + EOL + " <l-interfaces/>" + EOL
+ + " <lag-interfaces/>" + EOL + "</generic-vnf>" + EOL;
+ wireMockServer.stubFor(get(urlMatching(
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml").withBody(body)));
+
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockLoggerDelegate.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockLoggerDelegate.java
index 6a9ff2a4a8..0154f2eae7 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockLoggerDelegate.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/MockLoggerDelegate.java
@@ -24,12 +24,12 @@ import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
public class MockLoggerDelegate implements JavaDelegate {
- @Override
- public void execute(DelegateExecution execution) throws Exception {
- System.out.println("\n\n ..." + MockLoggerDelegate.class.getName() + " invoked by " + "processDefinitionId="
- + execution.getProcessDefinitionId() + ", activtyId=" + execution.getCurrentActivityId()
- + ", activtyName='" + execution.getCurrentActivityName() + "'" + ", processInstanceId="
- + execution.getProcessInstanceId() + ", businessKey=" + execution.getProcessBusinessKey()
- + ", executionId=" + execution.getId() + " \n\n");
- }
+ @Override
+ public void execute(DelegateExecution execution) throws Exception {
+ System.out.println("\n\n ..." + MockLoggerDelegate.class.getName() + " invoked by " + "processDefinitionId="
+ + execution.getProcessDefinitionId() + ", activtyId=" + execution.getCurrentActivityId()
+ + ", activtyName='" + execution.getCurrentActivityName() + "'" + ", processInstanceId="
+ + execution.getProcessInstanceId() + ", businessKey=" + execution.getProcessBusinessKey()
+ + ", executionId=" + execution.getId() + " \n\n");
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/OofHomingIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/OofHomingIT.java
index 4d7a127a85..c128f58103 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/OofHomingIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/OofHomingIT.java
@@ -25,14 +25,12 @@ import static org.junit.Assert.assertNull;
import static org.onap.so.bpmn.mock.StubResponseDatabase.MockGetServiceResourcesCatalogDataByModelUuid;
import static org.onap.so.bpmn.mock.StubResponseOof.mockOof;
import static org.onap.so.bpmn.mock.StubResponseOof.mockOof_500;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import org.junit.Ignore;
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
@@ -65,12 +63,12 @@ public class OofHomingIT extends BaseIntegrationTest {
String oofCallback2 = FileUtil.readResourceFile("__files/BuildingBlocks/oofCallback2AR1Vnf.json");
String oofCallback3 = FileUtil.readResourceFile("__files/BuildingBlocks/oofCallback2AR1Vnf2Net.json");
- String oofCallbackNoSolution = FileUtil.
- readResourceFile("__files/BuildingBlocks/oofCallbackNoSolutionFound.json");
- String oofCallbackPolicyException = FileUtil.
- readResourceFile("__files/BuildingBlocks/oofCallbackPolicyException.json");
- String oofCallbackServiceException = FileUtil.
- readResourceFile("__files/BuildingBlocks/oofCallbackServiceException.json");
+ String oofCallbackNoSolution =
+ FileUtil.readResourceFile("__files/BuildingBlocks/oofCallbackNoSolutionFound.json");
+ String oofCallbackPolicyException =
+ FileUtil.readResourceFile("__files/BuildingBlocks/oofCallbackPolicyException.json");
+ String oofCallbackServiceException =
+ FileUtil.readResourceFile("__files/BuildingBlocks/oofCallbackServiceException.json");
callbacks.put("oof", JSON, "oofResponse", oofCallback);
callbacks.put("oof2", JSON, "oofResponse", oofCallback2);
@@ -121,133 +119,73 @@ public class OofHomingIT extends BaseIntegrationTest {
VnfResource vnf = new VnfResource();
vnf.setResourceId("testResourceIdVNF");
vnf.setNfFunction("testVnfFunctionName");
- vnf.getHomingSolution().setOofDirectives(
- "{ \n" +
- " \"directives\":[ \n" +
- " { \n" +
- " \"vnfc_directives\":[ \n" +
- " { \n" +
- " \"vnfc_id\":\"<ID of VNFC>\",\n" +
- " \"directives\":[ \n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive,example flavor_directive>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute, such as flavor label>\",\n" +
- " \"attribute_value\":\"<value such as cloud specific flavor>\"\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive,example vnic-info>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute, such as vnic-type>\",\n" +
- " \"attribute_value\":\"<value such as direct/normal>\"\n" +
- " },\n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute, such as provider netweork>\",\n" +
- " \"attribute_value\":\"<value such as physnet>\"\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " { \n" +
- " \"vnf_directives\":{ \n" +
- " \"directives\":[ \n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute>\",\n" +
- " \"attribute_value\":\"<value>\"\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute>\",\n" +
- " \"attribute_value\":\"<value >\"\n" +
- " },\n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute>\",\n" +
- " \"attribute_value\":\"<value >\"\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " \"sdnc_directives\":{ \n" +
- " \"directives\":[ \n" +
- " { \n" +
- " \"vnfc_directives\":[ \n" +
- " { \n" +
- " \"vnfc_id\":\"<ID of VNFC>\",\n" +
- " \"directives\":[ \n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive,example flavor_directive>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute, such as flavor label>\",\n" +
- " \"attribute_value\":\"<value such as cloud specific flavor>\"\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive,example vnic-info>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute, such as vnic-type>\",\n" +
- " \"attribute_value\":\"<value such as direct/normal>\"\n" +
- " },\n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute, such as provider netweork>\",\n" +
- " \"attribute_value\":\"<value such as physnet>\"\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " { \n" +
- " \"vnf_directives\":{ \n" +
- " \"directives\":[ \n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute>\",\n" +
- " \"attribute_value\":\"<value>\"\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute>\",\n" +
- " \"attribute_value\":\"<value >\"\n" +
- " },\n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute>\",\n" +
- " \"attribute_value\":\"<value >\"\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
- " }");
+ vnf.getHomingSolution().setOofDirectives("{ \n" + " \"directives\":[ \n" + " { \n"
+ + " \"vnfc_directives\":[ \n" + " { \n"
+ + " \"vnfc_id\":\"<ID of VNFC>\",\n" + " \"directives\":[ \n"
+ + " { \n"
+ + " \"directive_name\":\"<Name of directive,example flavor_directive>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute, such as flavor label>\",\n"
+ + " \"attribute_value\":\"<value such as cloud specific flavor>\"\n"
+ + " }\n" + " ]\n" + " },\n"
+ + " { \n"
+ + " \"directive_name\":\"<Name of directive,example vnic-info>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute, such as vnic-type>\",\n"
+ + " \"attribute_value\":\"<value such as direct/normal>\"\n"
+ + " },\n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute, such as provider netweork>\",\n"
+ + " \"attribute_value\":\"<value such as physnet>\"\n"
+ + " }\n" + " ]\n" + " }\n"
+ + " ]\n" + " }\n" + " ]\n" + " },\n" + " { \n"
+ + " \"vnf_directives\":{ \n" + " \"directives\":[ \n"
+ + " { \n" + " \"directive_name\":\"<Name of directive>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute>\",\n"
+ + " \"attribute_value\":\"<value>\"\n" + " }\n"
+ + " ]\n" + " },\n" + " { \n"
+ + " \"directive_name\":\"<Name of directive>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute>\",\n"
+ + " \"attribute_value\":\"<value >\"\n" + " },\n"
+ + " { \n"
+ + " \"attribute_name\":\"<name of attribute>\",\n"
+ + " \"attribute_value\":\"<value >\"\n" + " }\n"
+ + " ]\n" + " }\n" + " ]\n" + " }\n"
+ + " }\n" + " ]\n" + " },\n" + " \"sdnc_directives\":{ \n" + " \"directives\":[ \n"
+ + " { \n" + " \"vnfc_directives\":[ \n" + " { \n"
+ + " \"vnfc_id\":\"<ID of VNFC>\",\n" + " \"directives\":[ \n"
+ + " { \n"
+ + " \"directive_name\":\"<Name of directive,example flavor_directive>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute, such as flavor label>\",\n"
+ + " \"attribute_value\":\"<value such as cloud specific flavor>\"\n"
+ + " }\n" + " ]\n" + " },\n"
+ + " { \n"
+ + " \"directive_name\":\"<Name of directive,example vnic-info>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute, such as vnic-type>\",\n"
+ + " \"attribute_value\":\"<value such as direct/normal>\"\n"
+ + " },\n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute, such as provider netweork>\",\n"
+ + " \"attribute_value\":\"<value such as physnet>\"\n"
+ + " }\n" + " ]\n" + " }\n"
+ + " ]\n" + " }\n" + " ]\n" + " },\n" + " { \n"
+ + " \"vnf_directives\":{ \n" + " \"directives\":[ \n"
+ + " { \n" + " \"directive_name\":\"<Name of directive>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute>\",\n"
+ + " \"attribute_value\":\"<value>\"\n" + " }\n"
+ + " ]\n" + " },\n" + " { \n"
+ + " \"directive_name\":\"<Name of directive>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute>\",\n"
+ + " \"attribute_value\":\"<value >\"\n" + " },\n"
+ + " { \n"
+ + " \"attribute_name\":\"<name of attribute>\",\n"
+ + " \"attribute_value\":\"<value >\"\n" + " }\n"
+ + " ]\n" + " }\n" + " ]\n" + " }\n"
+ + " }\n" + " ]\n" + " }");
ModelInfo vnfModel = new ModelInfo();
vnfModel.setModelCustomizationUuid("testModelCustomizationUuidVNF");
vnfModel.setModelInvariantUuid("testModelInvariantIdVNF");
@@ -264,11 +202,12 @@ public class OofHomingIT extends BaseIntegrationTest {
serviceDecomposition.setServiceInstance(si);
// Subscriber
- subscriber = "{\"globalSubscriberId\": \"SUB12_0322_DS_1201\",\"subscriberCommonSiteId\": \"DALTX0101\",\"subscriberName\": \"SUB_12_0322_DS_1201\"}";
+ subscriber =
+ "{\"globalSubscriberId\": \"SUB12_0322_DS_1201\",\"subscriberCommonSiteId\": \"DALTX0101\",\"subscriberName\": \"SUB_12_0322_DS_1201\"}";
subscriber2 = "{\"globalSubscriberId\": \"SUB12_0322_DS_1201\",\"subscriberName\": \"SUB_12_0322_DS_1201\"}";
}
- @Test
+ @Test
public void testHoming_success_2AR1Vnf() throws Exception {
mockOof(wireMockServer);
@@ -283,11 +222,11 @@ public class OofHomingIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
- ServiceDecomposition serviceDecompositionExp = (ServiceDecomposition) getVariableFromHistory(businessKey,
- "serviceDecomposition");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ ServiceDecomposition serviceDecompositionExp =
+ (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
String expectedOofRequest = (String) getVariableFromHistory(businessKey, "oofRequest");
Resource resourceAR = serviceDecompositionExp.getServiceResource("testResourceIdAR");
@@ -305,22 +244,23 @@ public class OofHomingIT extends BaseIntegrationTest {
expectedOofRequest = expectedOofRequest.replaceAll("\\s+", "");
assertNull(workflowException);
- assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01",
- resourceARHoming.getVnf().getResourceId(),"aic", "dfwtx",
- "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
+ assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01", resourceARHoming.getVnf().getResourceId(),
+ "aic", "dfwtx", "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
"\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
resourceARHomingString);
- assertEquals(homingSolutionService("service", "testSIID2", "testVnfHostname2",
- resourceARHoming2.getVnf().getResourceId(),"aic", "testCloudRegionId2",
- null, null), resourceARHoming2String);
- assertEquals(homingSolutionCloud("cloud","aic", "testCloudRegionId3",
- true, "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
- "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
+ assertEquals(
+ homingSolutionService("service", "testSIID2", "testVnfHostname2",
+ resourceARHoming2.getVnf().getResourceId(), "aic", "testCloudRegionId2", null, null),
+ resourceARHoming2String);
+ assertEquals(
+ homingSolutionCloud("cloud", "aic", "testCloudRegionId3", true,
+ "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
resourceVNFHomingString);
assertEquals(verifyOofRequest(), expectedOofRequest);
}
- @Test
+ @Test
public void testHoming_success_2AR1Vnf2Net() throws Exception {
mockOof(wireMockServer);
@@ -335,11 +275,11 @@ public class OofHomingIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
- ServiceDecomposition serviceDecompositionExp = (ServiceDecomposition) getVariableFromHistory(businessKey,
- "serviceDecomposition");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ ServiceDecomposition serviceDecompositionExp =
+ (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
String expectedOofRequest = (String) getVariableFromHistory(businessKey, "oofRequest");
Resource resourceAR = serviceDecompositionExp.getServiceResource("testResourceIdAR");
@@ -367,28 +307,27 @@ public class OofHomingIT extends BaseIntegrationTest {
assertNull(workflowException);
- assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01",
- resourceARHoming.getVnf().getResourceId(),"aic", "dfwtx",
- "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
+ assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01", resourceARHoming.getVnf().getResourceId(),
+ "aic", "dfwtx", "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
"\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
resourceARHomingString);
- assertEquals(homingSolutionService("service", "testSIID2", "testVnfHostname2",
- resourceARHoming2.getVnf().getResourceId(),
- "aic", "testCloudRegionId2",
- null, null), resourceARHoming2String);
- assertEquals(homingSolutionCloud("cloud","aic",
- "testCloudRegionId3",
- true, "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
- "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
+ assertEquals(
+ homingSolutionService("service", "testSIID2", "testVnfHostname2",
+ resourceARHoming2.getVnf().getResourceId(), "aic", "testCloudRegionId2", null, null),
+ resourceARHoming2String);
+ assertEquals(
+ homingSolutionCloud("cloud", "aic", "testCloudRegionId3", true,
+ "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
resourceVNFHomingString);
- assertEquals(homingSolutionService("service", "testServiceInstanceIdNet",
- "testVnfHostNameNet", resourceNetHoming.getVnf().getResourceId(),"aic",
- "testCloudRegionIdNet",
- null, null), resourceNetHomingString);
- assertEquals(homingSolutionCloud("cloud", "aic",
- "testCloudRegionIdNet2",
- false, "\"f1d563e8-e714-4393-8f99-cc480144a05n\", \"j1d563e8-e714-4393-8f99-cc480144a05n\"",
- "\"s1d563e8-e714-4393-8f99-cc480144a05n\", \"b1d563e8-e714-4393-8f99-cc480144a05n\""),
+ assertEquals(
+ homingSolutionService("service", "testServiceInstanceIdNet", "testVnfHostNameNet",
+ resourceNetHoming.getVnf().getResourceId(), "aic", "testCloudRegionIdNet", null, null),
+ resourceNetHomingString);
+ assertEquals(
+ homingSolutionCloud("cloud", "aic", "testCloudRegionIdNet2", false,
+ "\"f1d563e8-e714-4393-8f99-cc480144a05n\", \"j1d563e8-e714-4393-8f99-cc480144a05n\"",
+ "\"s1d563e8-e714-4393-8f99-cc480144a05n\", \"b1d563e8-e714-4393-8f99-cc480144a05n\""),
resourceNetHoming2String);
assertEquals(verifyOofRequest(), expectedOofRequest);
@@ -402,8 +341,7 @@ public class OofHomingIT extends BaseIntegrationTest {
"/BuildingBlocks/oofCatalogResp.json");
String busKey = UUID.randomUUID().toString();
Map<String, Object> vars = new HashMap<>();
- setVariablesForServiceDecomposition(vars, "testRequestId123",
- "ff5256d2-5a33-55df-13ab-12abad84e7ff");
+ setVariablesForServiceDecomposition(vars, "testRequestId123", "ff5256d2-5a33-55df-13ab-12abad84e7ff");
invokeSubProcess("DecomposeService", busKey, vars);
ServiceDecomposition sd = (ServiceDecomposition) getVariableFromHistory(busKey, "serviceDecomposition");
@@ -438,12 +376,12 @@ public class OofHomingIT extends BaseIntegrationTest {
injectWorkflowMessages(callbacks, "oof3");
waitForProcessEnd(businessKey, 10000);
- //Get Variables
+ // Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
- ServiceDecomposition serviceDecompositionExp = (ServiceDecomposition) getVariableFromHistory(businessKey,
- "serviceDecomposition");
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ ServiceDecomposition serviceDecompositionExp =
+ (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
System.out.println("serviceDecompositionExp is: " + serviceDecompositionExp);
Resource resourceVnf = serviceDecompositionExp.getServiceResource("test-resource-id-000");
@@ -457,26 +395,26 @@ public class OofHomingIT extends BaseIntegrationTest {
assertNull(workflowException);
- //Verify request
+ // Verify request
String oofRequest = (String) getVariableFromHistory(businessKey, "oofRequest");
System.out.println("oofRequest is: " + oofRequest);
- assertEquals(FileUtil.readResourceFile("__files/BuildingBlocks/oofRequest_infravnf").
- replaceAll("\n", "").replaceAll("\r", "").
- replaceAll("\t", ""), oofRequest.replaceAll("\n", "").
- replaceAll("\r", "").replaceAll("\t", ""));
-
- //System.out.println("resourceVnfHoming.getVnf().getResourceId() is: " + resourceVnfHoming.getVnf().getResourceId());
-
- assertEquals(homingSolutionService("service", "service-instance-01234",
- "MDTNJ01", "test-resource-id-000","CloudOwner",
- "mtmnj1a",
- "\"f1d563e8-e714-4393-8f99-cc480144a05e\"," +
- " \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
- "\"s1d563e8-e714-4393-8f99-cc480144a05e\"," +
- " \"b1d563e8-e714-4393-8f99-cc480144a05e\""), resourceVnfHomingString);
+ assertEquals(
+ FileUtil.readResourceFile("__files/BuildingBlocks/oofRequest_infravnf").replaceAll("\n", "")
+ .replaceAll("\r", "").replaceAll("\t", ""),
+ oofRequest.replaceAll("\n", "").replaceAll("\r", "").replaceAll("\t", ""));
+
+ // System.out.println("resourceVnfHoming.getVnf().getResourceId() is: " +
+ // resourceVnfHoming.getVnf().getResourceId());
+
+ assertEquals(
+ homingSolutionService("service", "service-instance-01234", "MDTNJ01", "test-resource-id-000",
+ "CloudOwner", "mtmnj1a",
+ "\"f1d563e8-e714-4393-8f99-cc480144a05e\"," + " \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"s1d563e8-e714-4393-8f99-cc480144a05e\"," + " \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
+ resourceVnfHomingString);
}
- @Test
+ @Test
public void testHoming_success_existingLicense() throws Exception {
mockOof(wireMockServer);
@@ -491,9 +429,11 @@ public class OofHomingIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- ServiceDecomposition serviceDecompositionExp = (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ ServiceDecomposition serviceDecompositionExp =
+ (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
String oofRequest = (String) getVariableFromHistory(businessKey, "sniroRequest");
Resource resourceAR = serviceDecompositionExp.getServiceResource("testResourceIdAR");
@@ -511,24 +451,25 @@ public class OofHomingIT extends BaseIntegrationTest {
oofRequest = oofRequest.replaceAll("\\s+", "");
assertNull(workflowException);
- assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01",
- "aic", "dfwtx", "KDTNJ01",
- "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
- "\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
+ assertEquals(
+ homingSolutionService("service", "testSIID1", "MDTNJ01", "aic", "dfwtx", "KDTNJ01",
+ "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
resourceARHomingString);
- assertEquals(homingSolutionService("service", "testSIID2", "testVnfHostname2",
- resourceARHoming2.getVnf().getResourceId(),"aic", "testCloudRegionId2",
- null, null), resourceARHoming2String);
- assertEquals(homingSolutionCloud("cloud", "aic",
- "testCloudRegionId3",
- false, "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
- "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
+ assertEquals(
+ homingSolutionService("service", "testSIID2", "testVnfHostname2",
+ resourceARHoming2.getVnf().getResourceId(), "aic", "testCloudRegionId2", null, null),
+ resourceARHoming2String);
+ assertEquals(
+ homingSolutionCloud("cloud", "aic", "testCloudRegionId3", false,
+ "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
resourceVNFHomingString);
assertEquals(verifyOofRequestExistingLicense(), oofRequest);
}
- @Test
+ @Test
public void testHoming_error_inputVariable() throws Exception {
String businessKey = UUID.randomUUID().toString();
@@ -539,15 +480,15 @@ public class OofHomingIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- assertEquals("WorkflowException[processKey=Homing,errorCode=4000,errorMessage=A required " +
- "input variable is missing or null,workStep=*]", workflowException.toString());
+ assertEquals("WorkflowException[processKey=Homing,errorCode=4000,errorMessage=A required "
+ + "input variable is missing or null,workStep=*]", workflowException.toString());
}
- @Test
+ @Test
public void testHoming_error_badResponse() throws Exception {
mockOof_500(wireMockServer);
@@ -559,14 +500,16 @@ public class OofHomingIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- assertEquals("WorkflowException[processKey=Homing,errorCode=401,errorMessage=Internal Error - BasicAuth value null,workStep=*]", workflowException.toString());
+ assertEquals(
+ "WorkflowException[processKey=Homing,errorCode=401,errorMessage=Internal Error - BasicAuth value null,workStep=*]",
+ workflowException.toString());
}
- @Test
+ @Test
public void testHoming_error_oofNoSolution() throws Exception {
mockOof(wireMockServer);
@@ -580,15 +523,16 @@ public class OofHomingIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
- Boolean errorMatch = workflowException.toString().contains("WorkflowException[processKey=Homing,errorCode=400,errorMessage=OOF Async Callback " +
- "Response contains error: Unable to find any candidate for demand *** Response:");
- assert(errorMatch);
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ Boolean errorMatch = workflowException.toString()
+ .contains("WorkflowException[processKey=Homing,errorCode=400,errorMessage=OOF Async Callback "
+ + "Response contains error: Unable to find any candidate for demand *** Response:");
+ assert (errorMatch);
}
- @Test
+ @Test
public void testHoming_error_oofPolicyException() throws Exception {
mockOof(wireMockServer);
@@ -602,16 +546,16 @@ public class OofHomingIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- assertEquals("WorkflowException[processKey=Homing,errorCode=400,errorMessage=OOF Async Callback " +
- "Response contains a Request Error Policy Exception: Message content size exceeds the allowable " +
- "limit]", workflowException.toString());
+ assertEquals("WorkflowException[processKey=Homing,errorCode=400,errorMessage=OOF Async Callback "
+ + "Response contains a Request Error Policy Exception: Message content size exceeds the allowable "
+ + "limit]", workflowException.toString());
}
- @Test
+ @Test
public void testHoming_error_oofServiceException() throws Exception {
mockOof(wireMockServer);
@@ -623,14 +567,15 @@ public class OofHomingIT extends BaseIntegrationTest {
injectWorkflowMessages(callbacks, "oofServiceEx");
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- assertEquals("WorkflowException[processKey=Homing,errorCode=400,errorMessage=OOF Async Callback " +
- "Response contains a Request Error Service Exception: OOF PlacementError: " +
- "requests.exceptions.HTTPError: 404 Client Error: Not Found for " +
- "url: http://192.168.171.200:8091/v1/plans/97b4e303-5f75-492c-8fb2-21098281c8b8]",
+ assertEquals(
+ "WorkflowException[processKey=Homing,errorCode=400,errorMessage=OOF Async Callback "
+ + "Response contains a Request Error Service Exception: OOF PlacementError: "
+ + "requests.exceptions.HTTPError: 404 Client Error: Not Found for "
+ + "url: http://192.168.171.200:8091/v1/plans/97b4e303-5f75-492c-8fb2-21098281c8b8]",
workflowException.toString());
}
@@ -649,7 +594,7 @@ public class OofHomingIT extends BaseIntegrationTest {
variables.put("cloudRegionId", "TNZED");
variables.put("vgMuxInfraModelInvariantId", "testModelInvariantIdAR");
variables.put("vgMuxInfraModelId", "testArModelUuid");
- // variables.put("mso-request-id", "testRequestId");
+ // variables.put("mso-request-id", "testRequestId");
variables.put("msoRequestId", "testRequestId");
variables.put("serviceInstanceId", "testServiceInstanceId123");
variables.put("serviceInstanceName", "testServiceName");
@@ -716,7 +661,7 @@ public class OofHomingIT extends BaseIntegrationTest {
variables.put("vgMuxInfraModelInvariantId", "testModelInvariantIdAR");
variables.put("vgMuxInfraModelId", "testArModelUuid");
variables.put("isDebugLogEnabled", "true");
- // variables.put("mso-request-id", "testRequestId");
+ // variables.put("mso-request-id", "testRequestId");
variables.put("msoRequestId", "testRequestId");
variables.put("serviceInstanceId", "testServiceInstanceId123");
variables.put("serviceInstanceName", "testServiceName");
@@ -727,11 +672,15 @@ public class OofHomingIT extends BaseIntegrationTest {
private void setVariablesExistingLicense(Map<String, Object> variables) {
HomingSolution currentHomingSolution = new HomingSolution();
serviceDecomposition.getVnfResources().get(0).setCurrentHomingSolution(currentHomingSolution);
- serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense().addEntitlementPool("testEntitlementPoolId1");
- serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense().addEntitlementPool("testEntitlementPoolId2");
+ serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense()
+ .addEntitlementPool("testEntitlementPoolId1");
+ serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense()
+ .addEntitlementPool("testEntitlementPoolId2");
- serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense().addLicenseKeyGroup("testLicenseKeyGroupId1");
- serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense().addLicenseKeyGroup("testLicenseKeyGroupId2");
+ serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense()
+ .addLicenseKeyGroup("testLicenseKeyGroupId1");
+ serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense()
+ .addLicenseKeyGroup("testLicenseKeyGroupId2");
variables.put("isDebugLogEnabled", "true");
variables.put("msoRequestId", "testRequestId");
@@ -742,56 +691,52 @@ public class OofHomingIT extends BaseIntegrationTest {
}
private String homingSolutionService(String type, String serviceInstanceId, String vnfHostname,
- String vnfResourceId, String cloudOwner,
- String cloudRegionId, String enList,
- String licenseList){
+ String vnfResourceId, String cloudOwner, String cloudRegionId, String enList, String licenseList) {
String solution = "";
- if(enList == null){
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"serviceInstanceId\" : \"" +
- serviceInstanceId + "\", \"cloudOwner\" : \"" + cloudOwner + "\", \"cloudRegionId\" : \"" +
- cloudRegionId + "\", " + "\"vnf\" : { \"resourceId\" : \"" + vnfResourceId +
- "\", \"resourceType\" : \"VNF\", \"resourceInstance\" : { }, \"homingSolution\" : { \"license\" :" +
- " { }, \"rehome\" : false }, \"vnfHostname\" : \"" + vnfHostname + "\" }, \"license\" : { }," +
- " \"rehome\" : false } }";
- }else{
- //language=JSON
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"serviceInstanceId\" : \"" +
- serviceInstanceId + "\", \"cloudOwner\" : \"" + cloudOwner + "\", \"cloudRegionId\" : \"" +
- cloudRegionId + "\", \"vnf\" : { \"resourceId\" : \"" + vnfResourceId + "\", \"resourceType\" :" +
- " \"VNF\", \"resourceInstance\" : { }, \"homingSolution\" : { \"license\" : { }, \"rehome\" :" +
- " false }, \"vnfHostname\" : \"" + vnfHostname + "\" }, \"license\" : { \"entitlementPoolList\" :" +
- " [ " + enList + " ], \"licenseKeyGroupList\" : [ " + licenseList + " ] }, \"rehome\" : false } }";
+ if (enList == null) {
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"serviceInstanceId\" : \""
+ + serviceInstanceId + "\", \"cloudOwner\" : \"" + cloudOwner + "\", \"cloudRegionId\" : \""
+ + cloudRegionId + "\", " + "\"vnf\" : { \"resourceId\" : \"" + vnfResourceId
+ + "\", \"resourceType\" : \"VNF\", \"resourceInstance\" : { }, \"homingSolution\" : { \"license\" :"
+ + " { }, \"rehome\" : false }, \"vnfHostname\" : \"" + vnfHostname + "\" }, \"license\" : { },"
+ + " \"rehome\" : false } }";
+ } else {
+ // language=JSON
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"serviceInstanceId\" : \""
+ + serviceInstanceId + "\", \"cloudOwner\" : \"" + cloudOwner + "\", \"cloudRegionId\" : \""
+ + cloudRegionId + "\", \"vnf\" : { \"resourceId\" : \"" + vnfResourceId + "\", \"resourceType\" :"
+ + " \"VNF\", \"resourceInstance\" : { }, \"homingSolution\" : { \"license\" : { }, \"rehome\" :"
+ + " false }, \"vnfHostname\" : \"" + vnfHostname + "\" }, \"license\" : { \"entitlementPoolList\" :"
+ + " [ " + enList + " ], \"licenseKeyGroupList\" : [ " + licenseList
+ + " ] }, \"rehome\" : false } }";
}
return solution;
}
- private String homingSolutionCloud(String type, String cloudOwner,
- String cloudRegionId, Boolean flavors, String enList,
- String licenseList){
+ private String homingSolutionCloud(String type, String cloudOwner, String cloudRegionId, Boolean flavors,
+ String enList, String licenseList) {
String solution = "";
- if(enList == null){
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" +
- cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId +
- "\", \"license\" : { }, \"rehome\" : false } }";
- } else if (flavors && enList == null){
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" +
- cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId +
- "\", \"flavors\" : [ { \"flavorLabel\" : \"flavorLabel2xxx\", \"flavor\" : \"vimFlavorxxx\" }, " +
- "{ \"flavorLabel\" : \"flavorLabel1xxx\", \"flavor\" : \"vimFlavorxxx\" } ], " +
- "\"license\" : { }, \"rehome\" : false } }";
+ if (enList == null) {
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" + cloudOwner
+ + "\", \"cloudRegionId\" : \"" + cloudRegionId + "\", \"license\" : { }, \"rehome\" : false } }";
+ } else if (flavors && enList == null) {
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" + cloudOwner
+ + "\", \"cloudRegionId\" : \"" + cloudRegionId
+ + "\", \"flavors\" : [ { \"flavorLabel\" : \"flavorLabel2xxx\", \"flavor\" : \"vimFlavorxxx\" }, "
+ + "{ \"flavorLabel\" : \"flavorLabel1xxx\", \"flavor\" : \"vimFlavorxxx\" } ], "
+ + "\"license\" : { }, \"rehome\" : false } }";
} else if (flavors) {
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" +
- cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId +
- "\", \"flavors\" : [ { \"flavorLabel\" : \"flavorLabel2xxx\", \"flavor\" : \"vimFlavorxxx\" }, " +
- "{ \"flavorLabel\" : \"flavorLabel1xxx\", \"flavor\" : \"vimFlavorxxx\" } ], " +
- "\"license\" : { \"entitlementPoolList\" : [ " + enList + " ], \"licenseKeyGroupList\" : [ " +
- licenseList + " ] }, \"rehome\" : false } }";
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" + cloudOwner
+ + "\", \"cloudRegionId\" : \"" + cloudRegionId
+ + "\", \"flavors\" : [ { \"flavorLabel\" : \"flavorLabel2xxx\", \"flavor\" : \"vimFlavorxxx\" }, "
+ + "{ \"flavorLabel\" : \"flavorLabel1xxx\", \"flavor\" : \"vimFlavorxxx\" } ], "
+ + "\"license\" : { \"entitlementPoolList\" : [ " + enList + " ], \"licenseKeyGroupList\" : [ "
+ + licenseList + " ] }, \"rehome\" : false } }";
} else {
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" +
- cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId +
- "\", \"license\" : { \"entitlementPoolList\" : [ " + enList + " ], \"licenseKeyGroupList\" : [ " +
- licenseList + " ] }, \"rehome\" : false } }";
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" + cloudOwner
+ + "\", \"cloudRegionId\" : \"" + cloudRegionId + "\", \"license\" : { \"entitlementPoolList\" : [ "
+ + enList + " ], \"licenseKeyGroupList\" : [ " + licenseList + " ] }, \"rehome\" : false } }";
}
return solution;
}
@@ -814,68 +759,67 @@ public class OofHomingIT extends BaseIntegrationTest {
variables.put("cloudRegionId", "TNZED");
- String serviceModelInfo = "{\"modelInvariantId\":\"1cc4e2e4-eb6e-404d-a66f-c8733cedcce8\",\"modelUuid\":" +
- "\"2f7f309d-c842-4644-a2e4-34167be5eeb4\",\"modelName\":\"vCPE Service\",\"modelVersion\":\"2.0\",}";
+ String serviceModelInfo = "{\"modelInvariantId\":\"1cc4e2e4-eb6e-404d-a66f-c8733cedcce8\",\"modelUuid\":"
+ + "\"2f7f309d-c842-4644-a2e4-34167be5eeb4\",\"modelName\":\"vCPE Service\",\"modelVersion\":\"2.0\",}";
variables.put("serviceModelInfo", serviceModelInfo);
}
private String verifyOofRequest() {
- String request = "{\"requestInfo\":{\"transactionId\":\"testRequestId\",\"requestId\":\"testRequestId\"," +
- "\"callbackUrl\":\"http://localhost:28090/workflows/messages/message/oofResponse/testRequestId\"," +
- "\"sourceId\":\"so\",\"requestType\":\"create\",\"numSolutions\":1,\"optimizers\":[\"placement\"]," +
- "\"timeout\":600},\"placementInfo\":{\"requestParameters\":{\"customerLatitude\":" +
- "\"32.89748\",\"customerLongitude\":\"-97.040443\",\"customerName\":\"xyz\"},\"subscriberInfo\":" +
- "{\"globalSubscriberId\":\"SUB12_0322_DS_1201\",\"subscriberName\":\"SUB_12_0322_DS_1201\"," +
- "\"subscriberCommonSiteId\":\"\"},\"placementDemands\":[{\"resourceModuleName\":\"testARFunctionName\"" +
- ",\"serviceResourceId\":\"testResourceIdAR\",\"tenantId\":" +
- "\"\",\"resourceModelInfo\":{\"modelInvariantId\":\"no-resourceModelInvariantId\"," +
- "\"modelVersionId\":\"no-resourceModelVersionId\",\"modelName\":\"\",\"modelType\":" +
- "\"\",\"modelVersion\":\"\",\"modelCustomizationName\":\"\"}}," +
- "{\"resourceModuleName\":\"testAR2FunctionName\",\"serviceResourceId\":\"testResourceIdAR2\"," +
- "\"tenantId\":\"\",\"resourceModelInfo\":{\"modelInvariantId\":\"no-resourceModelInvariantId\"," +
- "\"modelVersionId\":\"no-resourceModelVersionId\",\"modelName\":\"\"," +
- "\"modelType\":\"\",\"modelVersion\":\"\"," +
- "\"modelCustomizationName\":\"\"}},{\"resourceModuleName\":\"testVnfFunctionName\",\"serviceResourceId\":\"" +
- "testResourceIdVNF\",\"tenantId\":\"\",\"resourceModelInfo\":{\"modelInvariantId\"" +
- ":\"testModelInvariantIdVNF\",\"modelVersionId\":\"testVnfModelUuid\",\"modelName\":\"" +
- "testModelNameVNF\",\"modelType\":\"testModelTypeVNF\",\"modelVersion\":\"testModelVersionVNF\"" +
- ",\"modelCustomizationName\":\"\"}}]},\"serviceInfo\":" +
- "{\"serviceInstanceId\":\"testServiceInstanceId123\"," +
- "\"serviceName\":\"testServiceName\",\"modelInfo\":{\"modelType\":\"\",\"modelInvariantId\":" +
- "\"testModelInvariantId\",\"modelVersionId\":\"testModelUuid\",\"modelName\":\"testModelName\"," +
- "\"modelVersion\":\"testModelVersion\",\"modelCustomizationName\":\"" +
- "\"}}}";
+ String request = "{\"requestInfo\":{\"transactionId\":\"testRequestId\",\"requestId\":\"testRequestId\","
+ + "\"callbackUrl\":\"http://localhost:28090/workflows/messages/message/oofResponse/testRequestId\","
+ + "\"sourceId\":\"so\",\"requestType\":\"create\",\"numSolutions\":1,\"optimizers\":[\"placement\"],"
+ + "\"timeout\":600},\"placementInfo\":{\"requestParameters\":{\"customerLatitude\":"
+ + "\"32.89748\",\"customerLongitude\":\"-97.040443\",\"customerName\":\"xyz\"},\"subscriberInfo\":"
+ + "{\"globalSubscriberId\":\"SUB12_0322_DS_1201\",\"subscriberName\":\"SUB_12_0322_DS_1201\","
+ + "\"subscriberCommonSiteId\":\"\"},\"placementDemands\":[{\"resourceModuleName\":\"testARFunctionName\""
+ + ",\"serviceResourceId\":\"testResourceIdAR\",\"tenantId\":"
+ + "\"\",\"resourceModelInfo\":{\"modelInvariantId\":\"no-resourceModelInvariantId\","
+ + "\"modelVersionId\":\"no-resourceModelVersionId\",\"modelName\":\"\",\"modelType\":"
+ + "\"\",\"modelVersion\":\"\",\"modelCustomizationName\":\"\"}},"
+ + "{\"resourceModuleName\":\"testAR2FunctionName\",\"serviceResourceId\":\"testResourceIdAR2\","
+ + "\"tenantId\":\"\",\"resourceModelInfo\":{\"modelInvariantId\":\"no-resourceModelInvariantId\","
+ + "\"modelVersionId\":\"no-resourceModelVersionId\",\"modelName\":\"\","
+ + "\"modelType\":\"\",\"modelVersion\":\"\","
+ + "\"modelCustomizationName\":\"\"}},{\"resourceModuleName\":\"testVnfFunctionName\",\"serviceResourceId\":\""
+ + "testResourceIdVNF\",\"tenantId\":\"\",\"resourceModelInfo\":{\"modelInvariantId\""
+ + ":\"testModelInvariantIdVNF\",\"modelVersionId\":\"testVnfModelUuid\",\"modelName\":\""
+ + "testModelNameVNF\",\"modelType\":\"testModelTypeVNF\",\"modelVersion\":\"testModelVersionVNF\""
+ + ",\"modelCustomizationName\":\"\"}}]},\"serviceInfo\":"
+ + "{\"serviceInstanceId\":\"testServiceInstanceId123\","
+ + "\"serviceName\":\"testServiceName\",\"modelInfo\":{\"modelType\":\"\",\"modelInvariantId\":"
+ + "\"testModelInvariantId\",\"modelVersionId\":\"testModelUuid\",\"modelName\":\"testModelName\","
+ + "\"modelVersion\":\"testModelVersion\",\"modelCustomizationName\":\"" + "\"}}}";
return request;
}
- private String verifyOofRequestExistingLicense(){
- String request = "{\"requestInfo\":{\"transactionId\":\"testRequestId\",\"requestId\":\"testRequestId\"," +
- "\"callbackUrl\":\"http://localhost:28090/workflows/messages/message/SNIROResponse/testRequestId\"," +
- "\"sourceId\":\"mso\",\"requestType\":\"speedchanged\",\"optimizer\":[\"placement\",\"license\"]," +
- "\"numSolutions\":1,\"timeout\":1800},\"placementInfo\":{\"serviceModelInfo\":{\"modelType\":\"\"," +
- "\"modelInvariantId\":\"testModelInvariantId\",\"modelVersionId\":\"testModelUuid\",\"modelName\":" +
- "\"testModelName\",\"modelVersion\":\"testModelVersion\"},\"subscriberInfo\":" +
- "{\"globalSubscriberId\":\"SUB12_0322_DS_1201\",\"subscriberName\":\"SUB_12_0322_DS_1201\"," +
- "\"subscriberCommonSiteId\":\"\"},\"demandInfo\":{\"placementDemand\":[{\"resourceInstanceType\":" +
- "\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR\",\"resourceModuleName\":\"\"," +
- "\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR\"," +
- "\"modelInvariantId\":\"testModelInvariantIdAR\",\"modelName\":\"testModelNameAR\"," +
- "\"modelVersion\":\"testModelVersionAR\",\"modelVersionId\":\"testARModelUuid\",\"modelType\":" +
- "\"testModelTypeAR\"},\"tenantId\":\"\",\"tenantName\":\"\"},{\"resourceInstanceType\":" +
- "\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR2\",\"resourceModuleName\":" +
- "\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR2\"," +
- "\"modelInvariantId\":\"testModelInvariantIdAR2\",\"modelName\":\"testModelNameAR2\"," +
- "\"modelVersion\":\"testModelVersionAR2\",\"modelVersionId\":\"testAr2ModelUuid\"," +
- "\"modelType\":\"testModelTypeAR2\"},\"tenantId\":\"\",\"tenantName\":\"\"}],\"licenseDemand\":" +
- "[{\"resourceInstanceType\":\"VNF\",\"serviceResourceId\":\"testResourceIdVNF\"," +
- "\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":" +
- "\"testModelCustomizationUuidVNF\",\"modelInvariantId\":\"testModelInvariantIdVNF\"," +
- "\"modelName\":\"testModelNameVNF\",\"modelVersion\":\"testModelVersionVNF\"," +
- "\"modelVersionId\":\"testVnfModelUuid\",\"modelType\":\"testModelTypeVNF\"}," +
- "\"existingLicense\":[{\"entitlementPoolUUID\":[\"testEntitlementPoolId1\"," +
- "\"testEntitlementPoolId2\"],\"licenseKeyGroupUUID\":[\"testLicenseKeyGroupId1\"," +
- "\"testLicenseKeyGroupId2\"]}]}]},\"policyId\":[],\"serviceInstanceId\":" +
- "\"testServiceInstanceId123\",\"orderInfo\":\"{\\\"requestParameters\\\":null}\"}}";
+ private String verifyOofRequestExistingLicense() {
+ String request = "{\"requestInfo\":{\"transactionId\":\"testRequestId\",\"requestId\":\"testRequestId\","
+ + "\"callbackUrl\":\"http://localhost:28090/workflows/messages/message/SNIROResponse/testRequestId\","
+ + "\"sourceId\":\"mso\",\"requestType\":\"speedchanged\",\"optimizer\":[\"placement\",\"license\"],"
+ + "\"numSolutions\":1,\"timeout\":1800},\"placementInfo\":{\"serviceModelInfo\":{\"modelType\":\"\","
+ + "\"modelInvariantId\":\"testModelInvariantId\",\"modelVersionId\":\"testModelUuid\",\"modelName\":"
+ + "\"testModelName\",\"modelVersion\":\"testModelVersion\"},\"subscriberInfo\":"
+ + "{\"globalSubscriberId\":\"SUB12_0322_DS_1201\",\"subscriberName\":\"SUB_12_0322_DS_1201\","
+ + "\"subscriberCommonSiteId\":\"\"},\"demandInfo\":{\"placementDemand\":[{\"resourceInstanceType\":"
+ + "\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR\",\"resourceModuleName\":\"\","
+ + "\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR\","
+ + "\"modelInvariantId\":\"testModelInvariantIdAR\",\"modelName\":\"testModelNameAR\","
+ + "\"modelVersion\":\"testModelVersionAR\",\"modelVersionId\":\"testARModelUuid\",\"modelType\":"
+ + "\"testModelTypeAR\"},\"tenantId\":\"\",\"tenantName\":\"\"},{\"resourceInstanceType\":"
+ + "\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR2\",\"resourceModuleName\":"
+ + "\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR2\","
+ + "\"modelInvariantId\":\"testModelInvariantIdAR2\",\"modelName\":\"testModelNameAR2\","
+ + "\"modelVersion\":\"testModelVersionAR2\",\"modelVersionId\":\"testAr2ModelUuid\","
+ + "\"modelType\":\"testModelTypeAR2\"},\"tenantId\":\"\",\"tenantName\":\"\"}],\"licenseDemand\":"
+ + "[{\"resourceInstanceType\":\"VNF\",\"serviceResourceId\":\"testResourceIdVNF\","
+ + "\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":"
+ + "\"testModelCustomizationUuidVNF\",\"modelInvariantId\":\"testModelInvariantIdVNF\","
+ + "\"modelName\":\"testModelNameVNF\",\"modelVersion\":\"testModelVersionVNF\","
+ + "\"modelVersionId\":\"testVnfModelUuid\",\"modelType\":\"testModelTypeVNF\"},"
+ + "\"existingLicense\":[{\"entitlementPoolUUID\":[\"testEntitlementPoolId1\","
+ + "\"testEntitlementPoolId2\"],\"licenseKeyGroupUUID\":[\"testLicenseKeyGroupId1\","
+ + "\"testLicenseKeyGroupId2\"]}]}]},\"policyId\":[],\"serviceInstanceId\":"
+ + "\"testServiceInstanceId123\",\"orderInfo\":\"{\\\"requestParameters\\\":null}\"}}";
return request;
}
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/OofHomingTestIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/OofHomingTestIT.java
index 390f5294aa..39a8995607 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/OofHomingTestIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/OofHomingTestIT.java
@@ -38,14 +38,12 @@ import org.onap.so.bpmn.core.domain.VnfResource;
import org.onap.so.bpmn.mock.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.onap.so.bpmn.mock.StubResponseDatabase.MockGetServiceResourcesCatalogDataByModelUuid;
@@ -59,7 +57,7 @@ import static org.onap.so.bpmn.mock.StubResponseOof.mockOof_500;
@Ignore
public class OofHomingTestIT extends BaseIntegrationTest {
- Logger logger = LoggerFactory.getLogger(CreateAAIVfModuleIT.class);
+ Logger logger = LoggerFactory.getLogger(CreateAAIVfModuleIT.class);
ServiceDecomposition serviceDecomposition = new ServiceDecomposition();
String subscriber = "";
@@ -72,12 +70,11 @@ public class OofHomingTestIT extends BaseIntegrationTest {
String oofCallback2 = FileUtil.readResourceFile("__files/BuildingBlocks/oofCallback2AR1Vnf");
String oofCallback3 = FileUtil.readResourceFile("__files/BuildingBlocks/oofCallback2AR1Vnf2Net");
- String oofCallbackNoSolution = FileUtil.
- readResourceFile("__files/BuildingBlocks/oofCallbackNoSolutionFound");
- String oofCallbackPolicyException = FileUtil.
- readResourceFile("__files/BuildingBlocks/oofCallbackPolicyException");
- String oofCallbackServiceException = FileUtil.
- readResourceFile("__files/BuildingBlocks/oofCallbackServiceException");
+ String oofCallbackNoSolution = FileUtil.readResourceFile("__files/BuildingBlocks/oofCallbackNoSolutionFound");
+ String oofCallbackPolicyException =
+ FileUtil.readResourceFile("__files/BuildingBlocks/oofCallbackPolicyException");
+ String oofCallbackServiceException =
+ FileUtil.readResourceFile("__files/BuildingBlocks/oofCallbackServiceException");
callbacks.put("oof", JSON, "oofResponse", oofCallback);
callbacks.put("oof2", JSON, "oofResponse", oofCallback2);
@@ -128,133 +125,73 @@ public class OofHomingTestIT extends BaseIntegrationTest {
VnfResource vnf = new VnfResource();
vnf.setResourceId("testResourceIdVNF");
vnf.setResourceInstanceName("testVnfInstanceName");
- vnf.getHomingSolution().setOofDirectives(
- "{ \n" +
- " \"directives\":[ \n" +
- " { \n" +
- " \"vnfc_directives\":[ \n" +
- " { \n" +
- " \"vnfc_id\":\"<ID of VNFC>\",\n" +
- " \"directives\":[ \n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive,example flavor_directive>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute, such as flavor label>\",\n" +
- " \"attribute_value\":\"<value such as cloud specific flavor>\"\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive,example vnic-info>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute, such as vnic-type>\",\n" +
- " \"attribute_value\":\"<value such as direct/normal>\"\n" +
- " },\n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute, such as provider netweork>\",\n" +
- " \"attribute_value\":\"<value such as physnet>\"\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " { \n" +
- " \"vnf_directives\":{ \n" +
- " \"directives\":[ \n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute>\",\n" +
- " \"attribute_value\":\"<value>\"\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute>\",\n" +
- " \"attribute_value\":\"<value >\"\n" +
- " },\n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute>\",\n" +
- " \"attribute_value\":\"<value >\"\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " \"sdnc_directives\":{ \n" +
- " \"directives\":[ \n" +
- " { \n" +
- " \"vnfc_directives\":[ \n" +
- " { \n" +
- " \"vnfc_id\":\"<ID of VNFC>\",\n" +
- " \"directives\":[ \n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive,example flavor_directive>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute, such as flavor label>\",\n" +
- " \"attribute_value\":\"<value such as cloud specific flavor>\"\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive,example vnic-info>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute, such as vnic-type>\",\n" +
- " \"attribute_value\":\"<value such as direct/normal>\"\n" +
- " },\n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute, such as provider netweork>\",\n" +
- " \"attribute_value\":\"<value such as physnet>\"\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " { \n" +
- " \"vnf_directives\":{ \n" +
- " \"directives\":[ \n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute>\",\n" +
- " \"attribute_value\":\"<value>\"\n" +
- " }\n" +
- " ]\n" +
- " },\n" +
- " { \n" +
- " \"directive_name\":\"<Name of directive>\",\n" +
- " \"attributes\":[ \n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute>\",\n" +
- " \"attribute_value\":\"<value >\"\n" +
- " },\n" +
- " { \n" +
- " \"attribute_name\":\"<name of attribute>\",\n" +
- " \"attribute_value\":\"<value >\"\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
- " }");
+ vnf.getHomingSolution().setOofDirectives("{ \n" + " \"directives\":[ \n" + " { \n"
+ + " \"vnfc_directives\":[ \n" + " { \n"
+ + " \"vnfc_id\":\"<ID of VNFC>\",\n" + " \"directives\":[ \n"
+ + " { \n"
+ + " \"directive_name\":\"<Name of directive,example flavor_directive>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute, such as flavor label>\",\n"
+ + " \"attribute_value\":\"<value such as cloud specific flavor>\"\n"
+ + " }\n" + " ]\n" + " },\n"
+ + " { \n"
+ + " \"directive_name\":\"<Name of directive,example vnic-info>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute, such as vnic-type>\",\n"
+ + " \"attribute_value\":\"<value such as direct/normal>\"\n"
+ + " },\n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute, such as provider netweork>\",\n"
+ + " \"attribute_value\":\"<value such as physnet>\"\n"
+ + " }\n" + " ]\n" + " }\n"
+ + " ]\n" + " }\n" + " ]\n" + " },\n" + " { \n"
+ + " \"vnf_directives\":{ \n" + " \"directives\":[ \n"
+ + " { \n" + " \"directive_name\":\"<Name of directive>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute>\",\n"
+ + " \"attribute_value\":\"<value>\"\n" + " }\n"
+ + " ]\n" + " },\n" + " { \n"
+ + " \"directive_name\":\"<Name of directive>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute>\",\n"
+ + " \"attribute_value\":\"<value >\"\n" + " },\n"
+ + " { \n"
+ + " \"attribute_name\":\"<name of attribute>\",\n"
+ + " \"attribute_value\":\"<value >\"\n" + " }\n"
+ + " ]\n" + " }\n" + " ]\n" + " }\n"
+ + " }\n" + " ]\n" + " },\n" + " \"sdnc_directives\":{ \n" + " \"directives\":[ \n"
+ + " { \n" + " \"vnfc_directives\":[ \n" + " { \n"
+ + " \"vnfc_id\":\"<ID of VNFC>\",\n" + " \"directives\":[ \n"
+ + " { \n"
+ + " \"directive_name\":\"<Name of directive,example flavor_directive>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute, such as flavor label>\",\n"
+ + " \"attribute_value\":\"<value such as cloud specific flavor>\"\n"
+ + " }\n" + " ]\n" + " },\n"
+ + " { \n"
+ + " \"directive_name\":\"<Name of directive,example vnic-info>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute, such as vnic-type>\",\n"
+ + " \"attribute_value\":\"<value such as direct/normal>\"\n"
+ + " },\n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute, such as provider netweork>\",\n"
+ + " \"attribute_value\":\"<value such as physnet>\"\n"
+ + " }\n" + " ]\n" + " }\n"
+ + " ]\n" + " }\n" + " ]\n" + " },\n" + " { \n"
+ + " \"vnf_directives\":{ \n" + " \"directives\":[ \n"
+ + " { \n" + " \"directive_name\":\"<Name of directive>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute>\",\n"
+ + " \"attribute_value\":\"<value>\"\n" + " }\n"
+ + " ]\n" + " },\n" + " { \n"
+ + " \"directive_name\":\"<Name of directive>\",\n"
+ + " \"attributes\":[ \n" + " { \n"
+ + " \"attribute_name\":\"<name of attribute>\",\n"
+ + " \"attribute_value\":\"<value >\"\n" + " },\n"
+ + " { \n"
+ + " \"attribute_name\":\"<name of attribute>\",\n"
+ + " \"attribute_value\":\"<value >\"\n" + " }\n"
+ + " ]\n" + " }\n" + " ]\n" + " }\n"
+ + " }\n" + " ]\n" + " }");
ModelInfo vnfModel = new ModelInfo();
vnfModel.setModelCustomizationUuid("testModelCustomizationUuidVNF");
vnfModel.setModelInvariantUuid("testModelInvariantIdVNF");
@@ -271,7 +208,8 @@ public class OofHomingTestIT extends BaseIntegrationTest {
serviceDecomposition.setServiceInstance(si);
// Subscriber
- subscriber = "{\"globalSubscriberId\": \"SUB12_0322_DS_1201\",\"subscriberCommonSiteId\": \"DALTX0101\",\"subscriberName\": \"SUB_12_0322_DS_1201\"}";
+ subscriber =
+ "{\"globalSubscriberId\": \"SUB12_0322_DS_1201\",\"subscriberCommonSiteId\": \"DALTX0101\",\"subscriberName\": \"SUB_12_0322_DS_1201\"}";
subscriber2 = "{\"globalSubscriberId\": \"SUB12_0322_DS_1201\",\"subscriberName\": \"SUB_12_0322_DS_1201\"}";
}
@@ -285,17 +223,17 @@ public class OofHomingTestIT extends BaseIntegrationTest {
Map<String, Object> variables = new HashMap<>();
setVariables(variables);
- invokeSubProcess("Homing", businessKey, variables);
+ invokeSubProcess("Homing", businessKey, variables);
injectWorkflowMessages(callbacks, "oof2");
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
- ServiceDecomposition serviceDecompositionExp = (ServiceDecomposition) getVariableFromHistory(businessKey,
- "serviceDecomposition");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ ServiceDecomposition serviceDecompositionExp =
+ (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
String expectedOofRequest = (String) getVariableFromHistory(businessKey, "oofRequest");
Resource resourceAR = serviceDecompositionExp.getServiceResource("testResourceIdAR");
@@ -313,17 +251,18 @@ public class OofHomingTestIT extends BaseIntegrationTest {
expectedOofRequest = expectedOofRequest.replaceAll("\\s+", "");
assertNull(workflowException);
- assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01",
- resourceARHoming.getVnf().getResourceId(),"aic", "dfwtx",
- "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
+ assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01", resourceARHoming.getVnf().getResourceId(),
+ "aic", "dfwtx", "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
"\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
resourceARHomingString);
- assertEquals(homingSolutionService("service", "testSIID2", "testVnfHostname2",
- resourceARHoming2.getVnf().getResourceId(),"aic", "testCloudRegionId2",
- null, null), resourceARHoming2String);
- assertEquals(homingSolutionCloud("cloud","aic", "testCloudRegionId3",
- true, "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
- "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
+ assertEquals(
+ homingSolutionService("service", "testSIID2", "testVnfHostname2",
+ resourceARHoming2.getVnf().getResourceId(), "aic", "testCloudRegionId2", null, null),
+ resourceARHoming2String);
+ assertEquals(
+ homingSolutionCloud("cloud", "aic", "testCloudRegionId3", true,
+ "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
resourceVNFHomingString);
assertEquals(verifyOofRequest(), expectedOofRequest);
}
@@ -338,17 +277,17 @@ public class OofHomingTestIT extends BaseIntegrationTest {
Map<String, Object> variables = new HashMap<>();
setVariables2(variables);
- invokeSubProcess("Homing", businessKey, variables);
+ invokeSubProcess("Homing", businessKey, variables);
injectWorkflowMessages(callbacks, "oof3");
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
- ServiceDecomposition serviceDecompositionExp = (ServiceDecomposition) getVariableFromHistory(businessKey,
- "serviceDecomposition");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ ServiceDecomposition serviceDecompositionExp =
+ (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
String expectedOofRequest = (String) getVariableFromHistory(businessKey, "oofRequest");
Resource resourceAR = serviceDecompositionExp.getServiceResource("testResourceIdAR");
@@ -376,28 +315,27 @@ public class OofHomingTestIT extends BaseIntegrationTest {
assertNull(workflowException);
- assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01",
- resourceARHoming.getVnf().getResourceId(),"aic", "dfwtx",
- "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
+ assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01", resourceARHoming.getVnf().getResourceId(),
+ "aic", "dfwtx", "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
"\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
resourceARHomingString);
- assertEquals(homingSolutionService("service", "testSIID2", "testVnfHostname2",
- resourceARHoming2.getVnf().getResourceId(),
- "aic", "testCloudRegionId2",
- null, null), resourceARHoming2String);
- assertEquals(homingSolutionCloud("cloud","aic",
- "testCloudRegionId3",
- true, "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
- "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
+ assertEquals(
+ homingSolutionService("service", "testSIID2", "testVnfHostname2",
+ resourceARHoming2.getVnf().getResourceId(), "aic", "testCloudRegionId2", null, null),
+ resourceARHoming2String);
+ assertEquals(
+ homingSolutionCloud("cloud", "aic", "testCloudRegionId3", true,
+ "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
resourceVNFHomingString);
- assertEquals(homingSolutionService("service", "testServiceInstanceIdNet",
- "testVnfHostNameNet", resourceNetHoming.getVnf().getResourceId(),"aic",
- "testCloudRegionIdNet",
- null, null), resourceNetHomingString);
- assertEquals(homingSolutionCloud("cloud", "aic",
- "testCloudRegionIdNet2",
- false, "\"f1d563e8-e714-4393-8f99-cc480144a05n\", \"j1d563e8-e714-4393-8f99-cc480144a05n\"",
- "\"s1d563e8-e714-4393-8f99-cc480144a05n\", \"b1d563e8-e714-4393-8f99-cc480144a05n\""),
+ assertEquals(
+ homingSolutionService("service", "testServiceInstanceIdNet", "testVnfHostNameNet",
+ resourceNetHoming.getVnf().getResourceId(), "aic", "testCloudRegionIdNet", null, null),
+ resourceNetHomingString);
+ assertEquals(
+ homingSolutionCloud("cloud", "aic", "testCloudRegionIdNet2", false,
+ "\"f1d563e8-e714-4393-8f99-cc480144a05n\", \"j1d563e8-e714-4393-8f99-cc480144a05n\"",
+ "\"s1d563e8-e714-4393-8f99-cc480144a05n\", \"b1d563e8-e714-4393-8f99-cc480144a05n\""),
resourceNetHoming2String);
assertEquals(verifyOofRequest(), expectedOofRequest);
@@ -413,12 +351,10 @@ public class OofHomingTestIT extends BaseIntegrationTest {
"/BuildingBlocks/oofCatalogResp.json");
String busKey = UUID.randomUUID().toString();
Map<String, Object> vars = new HashMap<>();
- setVariablesForServiceDecomposition(vars, "testRequestId123",
- "ff5256d2-5a33-55df-13ab-12abad84e7ff");
+ setVariablesForServiceDecomposition(vars, "testRequestId123", "ff5256d2-5a33-55df-13ab-12abad84e7ff");
invokeSubProcess("DecomposeService", busKey, vars);
- ServiceDecomposition sd = (ServiceDecomposition) getVariableFromHistory(busKey,
- "serviceDecomposition");
+ ServiceDecomposition sd = (ServiceDecomposition) getVariableFromHistory(busKey, "serviceDecomposition");
logger.debug("In testHoming_success_vnfResourceList, ServiceDecomposition = {}", sd);
List<VnfResource> vnfResourceList = sd.getVnfResources();
vnfResourceList.get(0).setResourceId("test-resource-id-000");
@@ -450,12 +386,12 @@ public class OofHomingTestIT extends BaseIntegrationTest {
injectWorkflowMessages(callbacks, "oof3");
waitForProcessEnd(businessKey, 10000);
- //Get Variables
+ // Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
- ServiceDecomposition serviceDecompositionExp = (ServiceDecomposition) getVariableFromHistory(businessKey,
- "serviceDecomposition");
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ ServiceDecomposition serviceDecompositionExp =
+ (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
logger.debug("serviceDecompositionExp is: {}", serviceDecompositionExp);
Resource resourceVnf = serviceDecompositionExp.getServiceResource("test-resource-id-000");
@@ -469,21 +405,20 @@ public class OofHomingTestIT extends BaseIntegrationTest {
assertNull(workflowException);
- //Verify request
+ // Verify request
String oofRequest = (String) getVariableFromHistory(businessKey, "oofRequest");
logger.debug("oofRequest is: {}", oofRequest);
- assertEquals(FileUtil.readResourceFile("__files/BuildingBlocks/oofRequest_infravnf").
- replaceAll("\n", "").replaceAll("\r", "").
- replaceAll("\t", ""), oofRequest.replaceAll("\n", "").
- replaceAll("\r", "").replaceAll("\t", ""));
-
- assertEquals(homingSolutionService("service", "service-instance-01234",
- "MDTNJ01", "test-resource-id-000","CloudOwner",
- "mtmnj1a",
- "\"f1d563e8-e714-4393-8f99-cc480144a05e\"," +
- " \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
- "\"s1d563e8-e714-4393-8f99-cc480144a05e\"," +
- " \"b1d563e8-e714-4393-8f99-cc480144a05e\""), resourceVnfHomingString);
+ assertEquals(
+ FileUtil.readResourceFile("__files/BuildingBlocks/oofRequest_infravnf").replaceAll("\n", "")
+ .replaceAll("\r", "").replaceAll("\t", ""),
+ oofRequest.replaceAll("\n", "").replaceAll("\r", "").replaceAll("\t", ""));
+
+ assertEquals(
+ homingSolutionService("service", "service-instance-01234", "MDTNJ01", "test-resource-id-000",
+ "CloudOwner", "mtmnj1a",
+ "\"f1d563e8-e714-4393-8f99-cc480144a05e\"," + " \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"s1d563e8-e714-4393-8f99-cc480144a05e\"," + " \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
+ resourceVnfHomingString);
}
@Test
@@ -501,9 +436,11 @@ public class OofHomingTestIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- ServiceDecomposition serviceDecompositionExp = (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ ServiceDecomposition serviceDecompositionExp =
+ (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
String oofRequest = (String) getVariableFromHistory(businessKey, "sniroRequest");
Resource resourceAR = serviceDecompositionExp.getServiceResource("testResourceIdAR");
@@ -521,18 +458,19 @@ public class OofHomingTestIT extends BaseIntegrationTest {
oofRequest = oofRequest.replaceAll("\\s+", "");
assertNull(workflowException);
- assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01",
- "aic", "dfwtx", "KDTNJ01",
- "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
- "\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
+ assertEquals(
+ homingSolutionService("service", "testSIID1", "MDTNJ01", "aic", "dfwtx", "KDTNJ01",
+ "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
resourceARHomingString);
- assertEquals(homingSolutionService("service", "testSIID2", "testVnfHostname2",
- resourceARHoming2.getVnf().getResourceId(),"aic", "testCloudRegionId2",
- null, null), resourceARHoming2String);
- assertEquals(homingSolutionCloud("cloud", "aic",
- "testCloudRegionId3",
- false, "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
- "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
+ assertEquals(
+ homingSolutionService("service", "testSIID2", "testVnfHostname2",
+ resourceARHoming2.getVnf().getResourceId(), "aic", "testCloudRegionId2", null, null),
+ resourceARHoming2String);
+ assertEquals(
+ homingSolutionCloud("cloud", "aic", "testCloudRegionId3", false,
+ "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
resourceVNFHomingString);
assertEquals(verifyOofRequestExistingLicense(), oofRequest);
@@ -549,12 +487,12 @@ public class OofHomingTestIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- assertEquals("WorkflowException[processKey=Homing,errorCode=4000,errorMessage=A required " +
- "input variable is missing or null]", workflowException.toString());
+ assertEquals("WorkflowException[processKey=Homing,errorCode=4000,errorMessage=A required "
+ + "input variable is missing or null]", workflowException.toString());
}
@Test
@@ -570,12 +508,12 @@ public class OofHomingTestIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- assertEquals("WorkflowException[processKey=Homing,errorCode=500,errorMessage=Received a " +
- "Bad Sync Response from Sniro/OOF.]", workflowException.toString());
+ assertEquals("WorkflowException[processKey=Homing,errorCode=500,errorMessage=Received a "
+ + "Bad Sync Response from Sniro/OOF.]", workflowException.toString());
}
@Test
@@ -593,12 +531,12 @@ public class OofHomingTestIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- assertEquals("WorkflowException[processKey=Homing,errorCode=400,errorMessage=No solution found " +
- "for plan 08e1b8cf-144a-4bac-b293-d5e2eedc97e8]", workflowException.toString());
+ assertEquals("WorkflowException[processKey=Homing,errorCode=400,errorMessage=No solution found "
+ + "for plan 08e1b8cf-144a-4bac-b293-d5e2eedc97e8]", workflowException.toString());
}
@Test
@@ -616,13 +554,13 @@ public class OofHomingTestIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- assertEquals("WorkflowException[processKey=Homing,errorCode=400,errorMessage=OOF Async Callback " +
- "Response contains a Request Error Policy Exception: Message content size exceeds the allowable " +
- "limit]", workflowException.toString());
+ assertEquals("WorkflowException[processKey=Homing,errorCode=400,errorMessage=OOF Async Callback "
+ + "Response contains a Request Error Policy Exception: Message content size exceeds the allowable "
+ + "limit]", workflowException.toString());
}
@Test
@@ -640,14 +578,15 @@ public class OofHomingTestIT extends BaseIntegrationTest {
waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey,
- "WorkflowException");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- assertEquals("WorkflowException[processKey=Homing,errorCode=400,errorMessage=OOF Async Callback " +
- "Response contains a Request Error Service Exception: OOF PlacementError: " +
- "requests.exceptions.HTTPError: 404 Client Error: Not Found for " +
- "url: http://192.168.171.200:8091/v1/plans/97b4e303-5f75-492c-8fb2-21098281c8b8]",
+ assertEquals(
+ "WorkflowException[processKey=Homing,errorCode=400,errorMessage=OOF Async Callback "
+ + "Response contains a Request Error Service Exception: OOF PlacementError: "
+ + "requests.exceptions.HTTPError: 404 Client Error: Not Found for "
+ + "url: http://192.168.171.200:8091/v1/plans/97b4e303-5f75-492c-8fb2-21098281c8b8]",
workflowException.toString());
}
@@ -665,7 +604,7 @@ public class OofHomingTestIT extends BaseIntegrationTest {
variables.put("cloudOwner", "amazon");
variables.put("cloudRegionId", "TNZED");
variables.put("isDebugLogEnabled", "true");
- // variables.put("mso-request-id", "testRequestId");
+ // variables.put("mso-request-id", "testRequestId");
variables.put("msoRequestId", "testRequestId");
variables.put("serviceInstanceId", "testServiceInstanceId");
variables.put("serviceDecomposition", serviceDecomposition);
@@ -726,7 +665,7 @@ public class OofHomingTestIT extends BaseIntegrationTest {
variables.put("cloudOwner", "amazon");
variables.put("cloudRegionId", "TNZED");
variables.put("isDebugLogEnabled", "true");
- // variables.put("mso-request-id", "testRequestId");
+ // variables.put("mso-request-id", "testRequestId");
variables.put("msoRequestId", "testRequestId");
variables.put("serviceInstanceId", "testServiceInstanceId");
variables.put("serviceDecomposition", null);
@@ -736,11 +675,15 @@ public class OofHomingTestIT extends BaseIntegrationTest {
private void setVariablesExistingLicense(Map<String, Object> variables) {
HomingSolution currentHomingSolution = new HomingSolution();
serviceDecomposition.getVnfResources().get(0).setCurrentHomingSolution(currentHomingSolution);
- serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense().addEntitlementPool("testEntitlementPoolId1");
- serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense().addEntitlementPool("testEntitlementPoolId2");
+ serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense()
+ .addEntitlementPool("testEntitlementPoolId1");
+ serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense()
+ .addEntitlementPool("testEntitlementPoolId2");
- serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense().addLicenseKeyGroup("testLicenseKeyGroupId1");
- serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense().addLicenseKeyGroup("testLicenseKeyGroupId2");
+ serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense()
+ .addLicenseKeyGroup("testLicenseKeyGroupId1");
+ serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense()
+ .addLicenseKeyGroup("testLicenseKeyGroupId2");
variables.put("isDebugLogEnabled", "true");
variables.put("msoRequestId", "testRequestId");
@@ -751,56 +694,52 @@ public class OofHomingTestIT extends BaseIntegrationTest {
}
private String homingSolutionService(String type, String serviceInstanceId, String vnfHostname,
- String vnfResourceId, String cloudOwner,
- String cloudRegionId, String enList,
- String licenseList){
+ String vnfResourceId, String cloudOwner, String cloudRegionId, String enList, String licenseList) {
String solution = "";
- if(enList == null){
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"serviceInstanceId\" : \"" +
- serviceInstanceId + "\", \"cloudOwner\" : \"" + cloudOwner + "\", \"cloudRegionId\" : \"" +
- cloudRegionId + "\", " + "\"vnf\" : { \"resourceId\" : \"" + vnfResourceId +
- "\", \"resourceType\" : \"VNF\", \"resourceInstance\" : { }, \"homingSolution\" : { \"license\" :" +
- " { }, \"rehome\" : false }, \"vnfHostname\" : \"" + vnfHostname + "\" }, \"license\" : { }," +
- " \"rehome\" : false } }";
- }else{
- //language=JSON
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"serviceInstanceId\" : \"" +
- serviceInstanceId + "\", \"cloudOwner\" : \"" + cloudOwner + "\", \"cloudRegionId\" : \"" +
- cloudRegionId + "\", \"vnf\" : { \"resourceId\" : \"" + vnfResourceId + "\", \"resourceType\" :" +
- " \"VNF\", \"resourceInstance\" : { }, \"homingSolution\" : { \"license\" : { }, \"rehome\" :" +
- " false }, \"vnfHostname\" : \"" + vnfHostname + "\" }, \"license\" : { \"entitlementPoolList\" :" +
- " [ " + enList + " ], \"licenseKeyGroupList\" : [ " + licenseList + " ] }, \"rehome\" : false } }";
+ if (enList == null) {
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"serviceInstanceId\" : \""
+ + serviceInstanceId + "\", \"cloudOwner\" : \"" + cloudOwner + "\", \"cloudRegionId\" : \""
+ + cloudRegionId + "\", " + "\"vnf\" : { \"resourceId\" : \"" + vnfResourceId
+ + "\", \"resourceType\" : \"VNF\", \"resourceInstance\" : { }, \"homingSolution\" : { \"license\" :"
+ + " { }, \"rehome\" : false }, \"vnfHostname\" : \"" + vnfHostname + "\" }, \"license\" : { },"
+ + " \"rehome\" : false } }";
+ } else {
+ // language=JSON
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"serviceInstanceId\" : \""
+ + serviceInstanceId + "\", \"cloudOwner\" : \"" + cloudOwner + "\", \"cloudRegionId\" : \""
+ + cloudRegionId + "\", \"vnf\" : { \"resourceId\" : \"" + vnfResourceId + "\", \"resourceType\" :"
+ + " \"VNF\", \"resourceInstance\" : { }, \"homingSolution\" : { \"license\" : { }, \"rehome\" :"
+ + " false }, \"vnfHostname\" : \"" + vnfHostname + "\" }, \"license\" : { \"entitlementPoolList\" :"
+ + " [ " + enList + " ], \"licenseKeyGroupList\" : [ " + licenseList
+ + " ] }, \"rehome\" : false } }";
}
return solution;
}
- private String homingSolutionCloud(String type, String cloudOwner,
- String cloudRegionId, Boolean flavors, String enList,
- String licenseList){
+ private String homingSolutionCloud(String type, String cloudOwner, String cloudRegionId, Boolean flavors,
+ String enList, String licenseList) {
String solution = "";
- if(enList == null){
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" +
- cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId +
- "\", \"license\" : { }, \"rehome\" : false } }";
- } else if (flavors && enList == null){
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" +
- cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId +
- "\", \"flavors\" : [ { \"flavorLabel\" : \"flavorLabel2xxx\", \"flavor\" : \"vimFlavorxxx\" }, " +
- "{ \"flavorLabel\" : \"flavorLabel1xxx\", \"flavor\" : \"vimFlavorxxx\" } ], " +
- "\"license\" : { }, \"rehome\" : false } }";
+ if (enList == null) {
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" + cloudOwner
+ + "\", \"cloudRegionId\" : \"" + cloudRegionId + "\", \"license\" : { }, \"rehome\" : false } }";
+ } else if (flavors && enList == null) {
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" + cloudOwner
+ + "\", \"cloudRegionId\" : \"" + cloudRegionId
+ + "\", \"flavors\" : [ { \"flavorLabel\" : \"flavorLabel2xxx\", \"flavor\" : \"vimFlavorxxx\" }, "
+ + "{ \"flavorLabel\" : \"flavorLabel1xxx\", \"flavor\" : \"vimFlavorxxx\" } ], "
+ + "\"license\" : { }, \"rehome\" : false } }";
} else if (flavors) {
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" +
- cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId +
- "\", \"flavors\" : [ { \"flavorLabel\" : \"flavorLabel2xxx\", \"flavor\" : \"vimFlavorxxx\" }, " +
- "{ \"flavorLabel\" : \"flavorLabel1xxx\", \"flavor\" : \"vimFlavorxxx\" } ], " +
- "\"license\" : { \"entitlementPoolList\" : [ " + enList + " ], \"licenseKeyGroupList\" : [ " +
- licenseList + " ] }, \"rehome\" : false } }";
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" + cloudOwner
+ + "\", \"cloudRegionId\" : \"" + cloudRegionId
+ + "\", \"flavors\" : [ { \"flavorLabel\" : \"flavorLabel2xxx\", \"flavor\" : \"vimFlavorxxx\" }, "
+ + "{ \"flavorLabel\" : \"flavorLabel1xxx\", \"flavor\" : \"vimFlavorxxx\" } ], "
+ + "\"license\" : { \"entitlementPoolList\" : [ " + enList + " ], \"licenseKeyGroupList\" : [ "
+ + licenseList + " ] }, \"rehome\" : false } }";
} else {
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" +
- cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId +
- "\", \"license\" : { \"entitlementPoolList\" : [ " + enList + " ], \"licenseKeyGroupList\" : [ " +
- licenseList + " ] }, \"rehome\" : false } }";
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" + cloudOwner
+ + "\", \"cloudRegionId\" : \"" + cloudRegionId + "\", \"license\" : { \"entitlementPoolList\" : [ "
+ + enList + " ], \"licenseKeyGroupList\" : [ " + licenseList + " ] }, \"rehome\" : false } }";
}
return solution;
}
@@ -823,68 +762,68 @@ public class OofHomingTestIT extends BaseIntegrationTest {
variables.put("cloudRegionId", "TNZED");
- String serviceModelInfo = "{\"modelInvariantId\":\"1cc4e2e4-eb6e-404d-a66f-c8733cedcce8\",\"modelUuid\":" +
- "\"2f7f309d-c842-4644-a2e4-34167be5eeb4\",\"modelName\":\"vCPE Service\",\"modelVersion\":\"2.0\",}";
+ String serviceModelInfo = "{\"modelInvariantId\":\"1cc4e2e4-eb6e-404d-a66f-c8733cedcce8\",\"modelUuid\":"
+ + "\"2f7f309d-c842-4644-a2e4-34167be5eeb4\",\"modelName\":\"vCPE Service\",\"modelVersion\":\"2.0\",}";
variables.put("serviceModelInfo", serviceModelInfo);
}
private String verifyOofRequest() {
- String request = "{\"requestInfo\":{\"transactionId\":\"testRequestId\",\"requestId\":\"testRequestId\"," +
- "\"callbackUrl\":\"http://localhost:28090/workflows/messages/message/oofResponse/testRequestId\"," +
- "\"sourceId\":\"so\",\"requestType\":\"create\",\"numSolutions\":1,\"optimizers\":[\"placement\"]," +
- "\"timeout\":600},\"placementInfo\":{\"requestParameters\":{\"customerLatitude\":" +
- "\"32.89748\",\"customerLongitude\":\"-97.040443\",\"customerName\":\"xyz\"},\"subscriberInfo\":" +
- "{\"globalSubscriberId\":\"SUB12_0322_DS_1201\",\"subscriberName\":\"SUB_12_0322_DS_1201\"," +
- "\"subscriberCommonSiteId\":\"\"},\"placementDemands\":[{\"resourceModuleName\":\"ALLOTTED_RESOURCE\"" +
- ",\"serviceResourceId\":\"testResourceIdAR\",\"tenantId\":" +
- "\"null\",\"resourceModelInfo\":{\"modelInvariantId\":\"testModelInvariantIdAR\"," +
- "\"modelVersionId\":\"testARModelUuid\",\"modelName\":\"testModelNameAR\",\"modelType\":" +
- "\"testModelTypeAR\",\"modelVersion\":\"testModelVersionAR\",\"modelCustomizationName\":\"\"}}," +
- "{\"resourceModuleName\":\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR2\"," +
- "\"tenantId\":\"null\",\"resourceModelInfo\":{\"modelInvariantId\":\"testModelInvariantIdAR2\"," +
- "\"modelVersionId\":\"testAr2ModelUuid\",\"modelName\":\"testModelNameAR2\"," +
- "\"modelType\":\"testModelTypeAR2\",\"modelVersion\":\"testModelVersionAR2\"," +
- "\"modelCustomizationName\":\"\"}}]},\"serviceInfo\":" +
- "{\"serviceInstanceId\":\"testServiceInstanceId123\"," +
- "\"serviceName\":\"null\",\"modelInfo\":{\"modelType\":\"\",\"modelInvariantId\":" +
- "\"testModelInvariantId\",\"modelVersionId\":\"testModelUuid\",\"modelName\":\"testModelName\"," +
- "\"modelVersion\":\"testModelVersion\",\"modelCustomizationName\":\"" +
- "\"}},\"licenseInfo\":{\"licenseDemands\":[{\"resourceModuleName\":\"VNF\",\"serviceResourceId\":" +
- "\"testResourceIdVNF\",\"resourceInstanceType\":\"VNF\",\"resourceModelInfo\":{\"modelInvariantId\":" +
- "\"testModelInvariantIdVNF\",\"modelVersionId\":\"testVnfModelUuid\",\"modelName\":" +
- "\"testModelNameVNF\",\"modelType\":\"testModelTypeVNF\",\"modelVersion\":\"testModelVersionVNF\"," +
- "\"modelCustomizationName\":\"\"}}]}}";
+ String request = "{\"requestInfo\":{\"transactionId\":\"testRequestId\",\"requestId\":\"testRequestId\","
+ + "\"callbackUrl\":\"http://localhost:28090/workflows/messages/message/oofResponse/testRequestId\","
+ + "\"sourceId\":\"so\",\"requestType\":\"create\",\"numSolutions\":1,\"optimizers\":[\"placement\"],"
+ + "\"timeout\":600},\"placementInfo\":{\"requestParameters\":{\"customerLatitude\":"
+ + "\"32.89748\",\"customerLongitude\":\"-97.040443\",\"customerName\":\"xyz\"},\"subscriberInfo\":"
+ + "{\"globalSubscriberId\":\"SUB12_0322_DS_1201\",\"subscriberName\":\"SUB_12_0322_DS_1201\","
+ + "\"subscriberCommonSiteId\":\"\"},\"placementDemands\":[{\"resourceModuleName\":\"ALLOTTED_RESOURCE\""
+ + ",\"serviceResourceId\":\"testResourceIdAR\",\"tenantId\":"
+ + "\"null\",\"resourceModelInfo\":{\"modelInvariantId\":\"testModelInvariantIdAR\","
+ + "\"modelVersionId\":\"testARModelUuid\",\"modelName\":\"testModelNameAR\",\"modelType\":"
+ + "\"testModelTypeAR\",\"modelVersion\":\"testModelVersionAR\",\"modelCustomizationName\":\"\"}},"
+ + "{\"resourceModuleName\":\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR2\","
+ + "\"tenantId\":\"null\",\"resourceModelInfo\":{\"modelInvariantId\":\"testModelInvariantIdAR2\","
+ + "\"modelVersionId\":\"testAr2ModelUuid\",\"modelName\":\"testModelNameAR2\","
+ + "\"modelType\":\"testModelTypeAR2\",\"modelVersion\":\"testModelVersionAR2\","
+ + "\"modelCustomizationName\":\"\"}}]},\"serviceInfo\":"
+ + "{\"serviceInstanceId\":\"testServiceInstanceId123\","
+ + "\"serviceName\":\"null\",\"modelInfo\":{\"modelType\":\"\",\"modelInvariantId\":"
+ + "\"testModelInvariantId\",\"modelVersionId\":\"testModelUuid\",\"modelName\":\"testModelName\","
+ + "\"modelVersion\":\"testModelVersion\",\"modelCustomizationName\":\""
+ + "\"}},\"licenseInfo\":{\"licenseDemands\":[{\"resourceModuleName\":\"VNF\",\"serviceResourceId\":"
+ + "\"testResourceIdVNF\",\"resourceInstanceType\":\"VNF\",\"resourceModelInfo\":{\"modelInvariantId\":"
+ + "\"testModelInvariantIdVNF\",\"modelVersionId\":\"testVnfModelUuid\",\"modelName\":"
+ + "\"testModelNameVNF\",\"modelType\":\"testModelTypeVNF\",\"modelVersion\":\"testModelVersionVNF\","
+ + "\"modelCustomizationName\":\"\"}}]}}";
return request;
}
- private String verifyOofRequestExistingLicense(){
- String request = "{\"requestInfo\":{\"transactionId\":\"testRequestId\",\"requestId\":\"testRequestId\"," +
- "\"callbackUrl\":\"http://localhost:28090/workflows/messages/message/SNIROResponse/testRequestId\"," +
- "\"sourceId\":\"mso\",\"requestType\":\"speedchanged\",\"optimizer\":[\"placement\",\"license\"]," +
- "\"numSolutions\":1,\"timeout\":1800},\"placementInfo\":{\"serviceModelInfo\":{\"modelType\":\"\"," +
- "\"modelInvariantId\":\"testModelInvariantId\",\"modelVersionId\":\"testModelUuid\",\"modelName\":" +
- "\"testModelName\",\"modelVersion\":\"testModelVersion\"},\"subscriberInfo\":" +
- "{\"globalSubscriberId\":\"SUB12_0322_DS_1201\",\"subscriberName\":\"SUB_12_0322_DS_1201\"," +
- "\"subscriberCommonSiteId\":\"\"},\"demandInfo\":{\"placementDemand\":[{\"resourceInstanceType\":" +
- "\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR\",\"resourceModuleName\":\"\"," +
- "\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR\"," +
- "\"modelInvariantId\":\"testModelInvariantIdAR\",\"modelName\":\"testModelNameAR\"," +
- "\"modelVersion\":\"testModelVersionAR\",\"modelVersionId\":\"testARModelUuid\",\"modelType\":" +
- "\"testModelTypeAR\"},\"tenantId\":\"\",\"tenantName\":\"\"},{\"resourceInstanceType\":" +
- "\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR2\",\"resourceModuleName\":" +
- "\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR2\"," +
- "\"modelInvariantId\":\"testModelInvariantIdAR2\",\"modelName\":\"testModelNameAR2\"," +
- "\"modelVersion\":\"testModelVersionAR2\",\"modelVersionId\":\"testAr2ModelUuid\"," +
- "\"modelType\":\"testModelTypeAR2\"},\"tenantId\":\"\",\"tenantName\":\"\"}],\"licenseDemand\":" +
- "[{\"resourceInstanceType\":\"VNF\",\"serviceResourceId\":\"testResourceIdVNF\"," +
- "\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":" +
- "\"testModelCustomizationUuidVNF\",\"modelInvariantId\":\"testModelInvariantIdVNF\"," +
- "\"modelName\":\"testModelNameVNF\",\"modelVersion\":\"testModelVersionVNF\"," +
- "\"modelVersionId\":\"testVnfModelUuid\",\"modelType\":\"testModelTypeVNF\"}," +
- "\"existingLicense\":[{\"entitlementPoolUUID\":[\"testEntitlementPoolId1\"," +
- "\"testEntitlementPoolId2\"],\"licenseKeyGroupUUID\":[\"testLicenseKeyGroupId1\"," +
- "\"testLicenseKeyGroupId2\"]}]}]},\"policyId\":[],\"serviceInstanceId\":" +
- "\"testServiceInstanceId123\",\"orderInfo\":\"{\\\"requestParameters\\\":null}\"}}";
+ private String verifyOofRequestExistingLicense() {
+ String request = "{\"requestInfo\":{\"transactionId\":\"testRequestId\",\"requestId\":\"testRequestId\","
+ + "\"callbackUrl\":\"http://localhost:28090/workflows/messages/message/SNIROResponse/testRequestId\","
+ + "\"sourceId\":\"mso\",\"requestType\":\"speedchanged\",\"optimizer\":[\"placement\",\"license\"],"
+ + "\"numSolutions\":1,\"timeout\":1800},\"placementInfo\":{\"serviceModelInfo\":{\"modelType\":\"\","
+ + "\"modelInvariantId\":\"testModelInvariantId\",\"modelVersionId\":\"testModelUuid\",\"modelName\":"
+ + "\"testModelName\",\"modelVersion\":\"testModelVersion\"},\"subscriberInfo\":"
+ + "{\"globalSubscriberId\":\"SUB12_0322_DS_1201\",\"subscriberName\":\"SUB_12_0322_DS_1201\","
+ + "\"subscriberCommonSiteId\":\"\"},\"demandInfo\":{\"placementDemand\":[{\"resourceInstanceType\":"
+ + "\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR\",\"resourceModuleName\":\"\","
+ + "\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR\","
+ + "\"modelInvariantId\":\"testModelInvariantIdAR\",\"modelName\":\"testModelNameAR\","
+ + "\"modelVersion\":\"testModelVersionAR\",\"modelVersionId\":\"testARModelUuid\",\"modelType\":"
+ + "\"testModelTypeAR\"},\"tenantId\":\"\",\"tenantName\":\"\"},{\"resourceInstanceType\":"
+ + "\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR2\",\"resourceModuleName\":"
+ + "\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR2\","
+ + "\"modelInvariantId\":\"testModelInvariantIdAR2\",\"modelName\":\"testModelNameAR2\","
+ + "\"modelVersion\":\"testModelVersionAR2\",\"modelVersionId\":\"testAr2ModelUuid\","
+ + "\"modelType\":\"testModelTypeAR2\"},\"tenantId\":\"\",\"tenantName\":\"\"}],\"licenseDemand\":"
+ + "[{\"resourceInstanceType\":\"VNF\",\"serviceResourceId\":\"testResourceIdVNF\","
+ + "\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":"
+ + "\"testModelCustomizationUuidVNF\",\"modelInvariantId\":\"testModelInvariantIdVNF\","
+ + "\"modelName\":\"testModelNameVNF\",\"modelVersion\":\"testModelVersionVNF\","
+ + "\"modelVersionId\":\"testVnfModelUuid\",\"modelType\":\"testModelTypeVNF\"},"
+ + "\"existingLicense\":[{\"entitlementPoolUUID\":[\"testEntitlementPoolId1\","
+ + "\"testEntitlementPoolId2\"],\"licenseKeyGroupUUID\":[\"testLicenseKeyGroupId1\","
+ + "\"testLicenseKeyGroupId2\"]}]}]},\"policyId\":[],\"serviceInstanceId\":"
+ + "\"testServiceInstanceId123\",\"orderInfo\":\"{\\\"requestParameters\\\":null}\"}}";
return request;
}
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/PrepareUpdateAAIVfModuleIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/PrepareUpdateAAIVfModuleIT.java
index c994173cd7..ace5fdd15b 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/PrepareUpdateAAIVfModuleIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/PrepareUpdateAAIVfModuleIT.java
@@ -18,7 +18,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
@@ -27,12 +27,10 @@ import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDep
import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchVfModuleId;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutGenericVnf;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Assert;
import org.junit.Test;
@@ -47,164 +45,176 @@ import org.slf4j.LoggerFactory;
*/
public class PrepareUpdateAAIVfModuleIT extends BaseIntegrationTest {
-
- Logger logger = LoggerFactory.getLogger(PrepareUpdateAAIVfModuleIT.class);
-
- /**
- * Test the happy path through the flow.
- */
- @Test
-
- public void happyPath() throws IOException {
-
- logStart();
-
- String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml");
-
- MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
- MockPutGenericVnf(wireMockServer, "/skask/vf-modules/vf-module/supercool", "PCRF", 200);
- MockPatchVfModuleId(wireMockServer, "skask", "supercool");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest);
- invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponse");
- Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponseCode");
- logger.debug("Subflow response code: {}", responseCode);
- logger.debug("Subflow response: {}", response);
- Assert.assertEquals(200, responseCode.intValue());
- String heatStackId = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_heatStackId");
- logger.debug("Ouput heat-stack-id:{}", heatStackId);
- Assert.assertEquals("slowburn", heatStackId);
-
- logEnd();
- }
-
- /**
- * Test the case where the GET to AAI returns a 404.
- */
- @Test
-
- public void badGet() throws IOException {
-
- logStart();
-
- String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml");
- MockGetGenericVnfById_404(wireMockServer, "skask[?]depth=1");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest);
- invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_getVnfResponse");
- Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_getVnfResponseCode");
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- logger.debug("Subflow response code: {}", responseCode);
- logger.debug("Subflow response: {}", response);
- Assert.assertEquals(404, responseCode.intValue());
- Assert.assertNotNull(workflowException);
- logger.debug("Subflow WorkflowException error message: {}", workflowException.getErrorMessage());
-
- logEnd();
- }
-
- /**
- * Test the case where the validation of the VF Module fails.
- */
- @Test
-
- public void failValidation1() throws IOException {
-
- logStart();
-
- String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml").replaceFirst("supercool", "lukewarm");
-
- MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest);
- invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables);
-
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- Assert.assertNotNull(workflowException);
- logger.debug("Subflow WorkflowException error message: {}", workflowException.getErrorMessage());
- Assert.assertTrue(workflowException.getErrorMessage().startsWith("VF Module validation error: Orchestration"));
-
- logEnd();
- }
-
- /**
- * Test the case where the validation of the VF Module fails.
- */
- @Test
-
- public void failValidation2() throws IOException {
-
- logStart();
-
- String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml").replaceFirst("supercool", "notsocool");
-
- MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest);
- invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables);
-
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- Assert.assertNotNull(workflowException);
- logger.debug("Subflow WorkflowException error message: {}", workflowException.getErrorMessage());
- Assert.assertTrue(workflowException.getErrorMessage().startsWith("VF Module validation error: VF Module"));
-
- logEnd();
- }
-
- /**
- * Test the case where the GET to AAI is successful, but the subsequent PUT returns 404.
- */
- @Test
-
- public void badPatch() throws IOException {
-
- logStart();
-
- String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml");
-
- MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
- MockAAIVfModuleBadPatch(wireMockServer, "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/supercool", 404);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest);
- invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponse");
- Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponseCode");
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- logger.debug("Subflow response code: {}", responseCode);
- logger.debug("Subflow response: {}", response);
- Assert.assertEquals(404, responseCode.intValue());
- Assert.assertNotNull(workflowException);
- logger.debug("Subflow WorkflowException error message: {}", workflowException.getErrorMessage());
-
- logEnd();
- }
+
+ Logger logger = LoggerFactory.getLogger(PrepareUpdateAAIVfModuleIT.class);
+
+ /**
+ * Test the happy path through the flow.
+ */
+ @Test
+
+ public void happyPath() throws IOException {
+
+ logStart();
+
+ String prepareUpdateAAIVfModuleRequest =
+ FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml");
+
+ MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
+ MockPutGenericVnf(wireMockServer, "/skask/vf-modules/vf-module/supercool", "PCRF", 200);
+ MockPatchVfModuleId(wireMockServer, "skask", "supercool");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest);
+ invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponse");
+ Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponseCode");
+ logger.debug("Subflow response code: {}", responseCode);
+ logger.debug("Subflow response: {}", response);
+ Assert.assertEquals(200, responseCode.intValue());
+ String heatStackId = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_heatStackId");
+ logger.debug("Ouput heat-stack-id:{}", heatStackId);
+ Assert.assertEquals("slowburn", heatStackId);
+
+ logEnd();
+ }
+
+ /**
+ * Test the case where the GET to AAI returns a 404.
+ */
+ @Test
+
+ public void badGet() throws IOException {
+
+ logStart();
+
+ String prepareUpdateAAIVfModuleRequest =
+ FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml");
+ MockGetGenericVnfById_404(wireMockServer, "skask[?]depth=1");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest);
+ invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_getVnfResponse");
+ Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_getVnfResponseCode");
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ logger.debug("Subflow response code: {}", responseCode);
+ logger.debug("Subflow response: {}", response);
+ Assert.assertEquals(404, responseCode.intValue());
+ Assert.assertNotNull(workflowException);
+ logger.debug("Subflow WorkflowException error message: {}", workflowException.getErrorMessage());
+
+ logEnd();
+ }
+
+ /**
+ * Test the case where the validation of the VF Module fails.
+ */
+ @Test
+
+ public void failValidation1() throws IOException {
+
+ logStart();
+
+ String prepareUpdateAAIVfModuleRequest =
+ FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml")
+ .replaceFirst("supercool", "lukewarm");
+
+ MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest);
+ invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables);
+
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ Assert.assertNotNull(workflowException);
+ logger.debug("Subflow WorkflowException error message: {}", workflowException.getErrorMessage());
+ Assert.assertTrue(workflowException.getErrorMessage().startsWith("VF Module validation error: Orchestration"));
+
+ logEnd();
+ }
+
+ /**
+ * Test the case where the validation of the VF Module fails.
+ */
+ @Test
+
+ public void failValidation2() throws IOException {
+
+ logStart();
+
+ String prepareUpdateAAIVfModuleRequest =
+ FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml")
+ .replaceFirst("supercool", "notsocool");
+
+ MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest);
+ invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables);
+
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ Assert.assertNotNull(workflowException);
+ logger.debug("Subflow WorkflowException error message: {}", workflowException.getErrorMessage());
+ Assert.assertTrue(workflowException.getErrorMessage().startsWith("VF Module validation error: VF Module"));
+
+ logEnd();
+ }
+
+ /**
+ * Test the case where the GET to AAI is successful, but the subsequent PUT returns 404.
+ */
+ @Test
+
+ public void badPatch() throws IOException {
+
+ logStart();
+
+ String prepareUpdateAAIVfModuleRequest =
+ FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml");
+
+ MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
+ MockAAIVfModuleBadPatch(wireMockServer,
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/supercool", 404);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest);
+ invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponse");
+ Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponseCode");
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ logger.debug("Subflow response code: {}", responseCode);
+ logger.debug("Subflow response: {}", response);
+ Assert.assertEquals(404, responseCode.intValue());
+ Assert.assertNotNull(workflowException);
+ logger.debug("Subflow WorkflowException error message: {}", workflowException.getErrorMessage());
+
+ logEnd();
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/RainyDayHandlerIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/RainyDayHandlerIT.java
index 2f6d2ae85b..d669674297 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/RainyDayHandlerIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/RainyDayHandlerIT.java
@@ -16,16 +16,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
import static org.onap.so.bpmn.mock.StubResponsePolicy.MockPolicyAbort;
-
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.junit.Assert;
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
@@ -35,35 +33,35 @@ import org.onap.so.BaseIntegrationTest;
*/
public class RainyDayHandlerIT extends BaseIntegrationTest {
-
- @Test
-
- public void TestRainyDayHandlingSuccess() {
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled","true");
- variables.put("msoRequestId", "testRequestId");
- variables.put("serviceType", "X");
- variables.put("vnfType", "Y");
- variables.put("currentActivity", "BB1");
- variables.put("workStep", "1");
- variables.put("failedActivity", "");
- variables.put("errorCode", "123");
- variables.put("errorText", "update failed");
- variables.put("vnfName", "vSAMP1");
-
- MockPolicyAbort(wireMockServer);
-
-
- String businessKey = UUID.randomUUID().toString();
- invokeSubProcess("RainyDayHandler", businessKey, variables);
-
- waitForProcessEnd(businessKey, 10000);
-
- Assert.assertTrue(isProcessEnded(businessKey));
-
- }
-
-
-
-} \ No newline at end of file
+
+ @Test
+
+ public void TestRainyDayHandlingSuccess() {
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("msoRequestId", "testRequestId");
+ variables.put("serviceType", "X");
+ variables.put("vnfType", "Y");
+ variables.put("currentActivity", "BB1");
+ variables.put("workStep", "1");
+ variables.put("failedActivity", "");
+ variables.put("errorCode", "123");
+ variables.put("errorText", "update failed");
+ variables.put("vnfName", "vSAMP1");
+
+ MockPolicyAbort(wireMockServer);
+
+
+ String businessKey = UUID.randomUUID().toString();
+ invokeSubProcess("RainyDayHandler", businessKey, variables);
+
+ waitForProcessEnd(businessKey, 10000);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+
+ }
+
+
+
+}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ReceiveWorkflowMessageTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ReceiveWorkflowMessageTest.java
index 7f3e884601..d8e3264091 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ReceiveWorkflowMessageTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/ReceiveWorkflowMessageTest.java
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.bpmn.common;
import static org.junit.Assert.assertEquals;
@@ -25,12 +25,10 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Ignore;
import org.junit.Test;
@@ -44,102 +42,85 @@ import org.onap.so.bpmn.core.WorkflowException;
@Ignore
public class ReceiveWorkflowMessageTest extends WorkflowTest {
- private static final String EOL = "\n";
-
- private final CallbackSet callbacks = new CallbackSet();
-
- public ReceiveWorkflowMessageTest() throws IOException {
- callbacks.put("sdnc-event-success", JSON, "SDNCAEvent",
- "{" + EOL +
- " \"SDNCEvent\": {" + EOL +
- " \"eventType\": \"evenType\"," + EOL +
- " \"eventCorrelatorType\": \"HOST-NAME\"," + EOL +
- " \"eventCorrelator\": \"((CORRELATOR))\"," + EOL +
- " \"params\": {" + EOL +
- " \"success-indicator\":\"Y\"" + EOL +
- " }" +EOL +
- " }" + EOL +
- "}" + EOL);
-
- callbacks.put("sdnc-event-fail", JSON, "SDNCAEvent",
- "{" + EOL +
- " \"SDNCEvent\": {" + EOL +
- " \"eventType\": \"evenType\"," + EOL +
- " \"eventCorrelatorType\": \"HOST-NAME\"," + EOL +
- " \"eventCorrelator\": \"((CORRELATOR))\"," + EOL +
- " \"params\": {" + EOL +
- " \"success-indicator\":\"N\"," + EOL +
- " \"error-message\":\"SOMETHING BAD HAPPENED\"" + EOL +
- " }" +EOL +
- " }" + EOL +
- "}" + EOL);
- }
-
- /**
- * Test the happy path.
- */
- @Test
- @Deployment(resources = {
- "subprocess/ReceiveWorkflowMessage.bpmn"
- })
- public void happyPath() throws Exception {
-
- logStart();
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", "dffbae0e-5588-4bd6-9749-b0f0adb52312");
- variables.put("isDebugLogEnabled", "true");
- variables.put("RCVWFMSG_timeout", "PT1M");
- variables.put("RCVWFMSG_messageType", "SDNCAEvent");
- variables.put("RCVWFMSG_correlator", "USOSTCDALTX0101UJZZ31");
-
- invokeSubProcess("ReceiveWorkflowMessage", businessKey, variables);
- injectWorkflowMessages(callbacks, "sdnc-event-success");
- waitForProcessEnd(businessKey, 10000);
-
- String response = (String) getVariableFromHistory(businessKey, "WorkflowResponse");
- System.out.println("Response:\n" + response);
- assertTrue(response.contains("\"SDNCEvent\""));
- assertTrue((boolean)getVariableFromHistory(businessKey, "RCVWFMSG_SuccessIndicator"));
-
- logEnd();
- }
-
- /**
- * Test the timeout scenario.
- */
- @Test
- @Deployment(resources = {
- "subprocess/ReceiveWorkflowMessage.bpmn"
- })
- public void timeout() throws Exception {
-
- logStart();
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", "dffbae0e-5588-4bd6-9749-b0f0adb52312");
- variables.put("isDebugLogEnabled", "true");
- variables.put("RCVWFMSG_timeout", "PT5S");
- variables.put("RCVWFMSG_messageType", "SDNCAEvent");
- variables.put("RCVWFMSG_correlator", "USOSTCDALTX0101UJZZ31");
-
- invokeSubProcess("ReceiveWorkflowMessage", businessKey, variables);
-
- // No injection
-
- waitForProcessEnd(businessKey, 10000);
-
- // There is no response from SDNC, so the flow doesn't set WorkflowResponse.
- String response = (String) getVariableFromHistory(businessKey, "WorkflowResponse");
- assertNull(response);
- WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- assertNotNull(wfe);
- System.out.println(wfe.toString());
- assertEquals("Receive Workflow Message Timeout Error", wfe.getErrorMessage());
- assertFalse((boolean)getVariableFromHistory(businessKey, "RCVWFMSG_SuccessIndicator"));
-
- logEnd();
- }
+ private static final String EOL = "\n";
+
+ private final CallbackSet callbacks = new CallbackSet();
+
+ public ReceiveWorkflowMessageTest() throws IOException {
+ callbacks.put("sdnc-event-success", JSON, "SDNCAEvent",
+ "{" + EOL + " \"SDNCEvent\": {" + EOL + " \"eventType\": \"evenType\"," + EOL
+ + " \"eventCorrelatorType\": \"HOST-NAME\"," + EOL
+ + " \"eventCorrelator\": \"((CORRELATOR))\"," + EOL + " \"params\": {" + EOL
+ + " \"success-indicator\":\"Y\"" + EOL + " }" + EOL + " }" + EOL + "}" + EOL);
+
+ callbacks.put("sdnc-event-fail", JSON, "SDNCAEvent", "{" + EOL + " \"SDNCEvent\": {" + EOL
+ + " \"eventType\": \"evenType\"," + EOL + " \"eventCorrelatorType\": \"HOST-NAME\"," + EOL
+ + " \"eventCorrelator\": \"((CORRELATOR))\"," + EOL + " \"params\": {" + EOL
+ + " \"success-indicator\":\"N\"," + EOL + " \"error-message\":\"SOMETHING BAD HAPPENED\""
+ + EOL + " }" + EOL + " }" + EOL + "}" + EOL);
+ }
+
+ /**
+ * Test the happy path.
+ */
+ @Test
+ @Deployment(resources = {"subprocess/ReceiveWorkflowMessage.bpmn"})
+ public void happyPath() throws Exception {
+
+ logStart();
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", "dffbae0e-5588-4bd6-9749-b0f0adb52312");
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("RCVWFMSG_timeout", "PT1M");
+ variables.put("RCVWFMSG_messageType", "SDNCAEvent");
+ variables.put("RCVWFMSG_correlator", "USOSTCDALTX0101UJZZ31");
+
+ invokeSubProcess("ReceiveWorkflowMessage", businessKey, variables);
+ injectWorkflowMessages(callbacks, "sdnc-event-success");
+ waitForProcessEnd(businessKey, 10000);
+
+ String response = (String) getVariableFromHistory(businessKey, "WorkflowResponse");
+ System.out.println("Response:\n" + response);
+ assertTrue(response.contains("\"SDNCEvent\""));
+ assertTrue((boolean) getVariableFromHistory(businessKey, "RCVWFMSG_SuccessIndicator"));
+
+ logEnd();
+ }
+
+ /**
+ * Test the timeout scenario.
+ */
+ @Test
+ @Deployment(resources = {"subprocess/ReceiveWorkflowMessage.bpmn"})
+ public void timeout() throws Exception {
+
+ logStart();
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", "dffbae0e-5588-4bd6-9749-b0f0adb52312");
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("RCVWFMSG_timeout", "PT5S");
+ variables.put("RCVWFMSG_messageType", "SDNCAEvent");
+ variables.put("RCVWFMSG_correlator", "USOSTCDALTX0101UJZZ31");
+
+ invokeSubProcess("ReceiveWorkflowMessage", businessKey, variables);
+
+ // No injection
+
+ waitForProcessEnd(businessKey, 10000);
+
+ // There is no response from SDNC, so the flow doesn't set WorkflowResponse.
+ String response = (String) getVariableFromHistory(businessKey, "WorkflowResponse");
+ assertNull(response);
+ WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ assertNotNull(wfe);
+ System.out.println(wfe.toString());
+ assertEquals("Receive Workflow Message Timeout Error", wfe.getErrorMessage());
+ assertFalse((boolean) getVariableFromHistory(businessKey, "RCVWFMSG_SuccessIndicator"));
+
+ logEnd();
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SDNCAdapterCallbackRule.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SDNCAdapterCallbackRule.java
index dc5c36f5a7..36adccd758 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SDNCAdapterCallbackRule.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SDNCAdapterCallbackRule.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.common;
import javax.xml.ws.Endpoint;
-
import org.camunda.bpm.engine.ProcessEngineServices;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
@@ -29,56 +28,54 @@ import org.junit.runners.model.Statement;
import org.onap.so.bpmn.common.workflow.service.SDNCAdapterCallbackServiceImpl;
/**
- * A JUnit rule that starts the SDNC Adapter Callback Service before
- * every test, and tears it down after every test. Example:
+ * A JUnit rule that starts the SDNC Adapter Callback Service before every test, and tears it down after every test.
+ * Example:
+ *
* <pre>
- * @Rule
- * public final SDNCAdapterCallbackRule sdncAdapterCallbackRule =
- * new SDNCAdapterCallbackRule(processEngineRule);
+ * &#64;Rule
+ * public final SDNCAdapterCallbackRule sdncAdapterCallbackRule = new SDNCAdapterCallbackRule(processEngineRule);
* </pre>
*/
public class SDNCAdapterCallbackRule implements TestRule {
- public static final String DEFAULT_ENDPOINT_URL =
- "http://localhost:28080/mso/SDNCAdapterCallbackService";
+ public static final String DEFAULT_ENDPOINT_URL = "http://localhost:28080/mso/SDNCAdapterCallbackService";
- private final ProcessEngineServices processEngineServices;
- private final String endpointUrl;
+ private final ProcessEngineServices processEngineServices;
+ private final String endpointUrl;
- public SDNCAdapterCallbackRule(ProcessEngineServices processEngineServices) {
- this(processEngineServices, DEFAULT_ENDPOINT_URL);
- }
+ public SDNCAdapterCallbackRule(ProcessEngineServices processEngineServices) {
+ this(processEngineServices, DEFAULT_ENDPOINT_URL);
+ }
- public SDNCAdapterCallbackRule(ProcessEngineServices processEngineServices,
- String endpointUrl) {
- this.processEngineServices = processEngineServices;
- this.endpointUrl = endpointUrl;
- }
+ public SDNCAdapterCallbackRule(ProcessEngineServices processEngineServices, String endpointUrl) {
+ this.processEngineServices = processEngineServices;
+ this.endpointUrl = endpointUrl;
+ }
- @Override
- public Statement apply(final Statement baseStmt, Description description) {
- return new Statement() {
- @Override
- public void evaluate() throws Throwable {
- Endpoint endpoint = null;
+ @Override
+ public Statement apply(final Statement baseStmt, Description description) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ Endpoint endpoint = null;
- try {
- SDNCAdapterCallbackServiceImpl sdncCallbackService = new SDNCAdapterCallbackServiceImpl();
- sdncCallbackService.setProcessEngineServices4junit(processEngineServices);
+ try {
+ SDNCAdapterCallbackServiceImpl sdncCallbackService = new SDNCAdapterCallbackServiceImpl();
+ sdncCallbackService.setProcessEngineServices4junit(processEngineServices);
- System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
- System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
+ System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
+ System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
- System.out.println("Publishing Endpoint - " + endpointUrl);
- endpoint = Endpoint.publish(endpointUrl, sdncCallbackService);
+ System.out.println("Publishing Endpoint - " + endpointUrl);
+ endpoint = Endpoint.publish(endpointUrl, sdncCallbackService);
- baseStmt.evaluate();
- } finally {
- if (endpoint != null) {
- System.out.println("Stopping Endpoint - " + endpointUrl);
- endpoint.stop();
- }
- }
- }
- };
- }
-} \ No newline at end of file
+ baseStmt.evaluate();
+ } finally {
+ if (endpoint != null) {
+ System.out.println("Stopping Endpoint - " + endpointUrl);
+ endpoint.stop();
+ }
+ }
+ }
+ };
+ }
+}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SDNCAdapterRestV2IT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SDNCAdapterRestV2IT.java
index bf3fefdf9c..415e8096a3 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SDNCAdapterRestV2IT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SDNCAdapterRestV2IT.java
@@ -25,12 +25,10 @@ package org.onap.so.bpmn.common;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
@@ -42,81 +40,78 @@ import org.slf4j.LoggerFactory;
/**
* Unit tests for SDNCAdapterRestV2.bpmn.
*
- * This version of SDNCAdapterRest allows for interim notifications to be sent for
- * any non-final response received from SDNC.
+ * This version of SDNCAdapterRest allows for interim notifications to be sent for any non-final response received from
+ * SDNC.
*/
public class SDNCAdapterRestV2IT extends BaseIntegrationTest {
- private final CallbackSet callbacks = new CallbackSet();
-
- Logger logger = LoggerFactory.getLogger(SDNCAdapterRestV2IT.class);
-
-
- /**
- * Constructor. Insert callbacks.
- *
- * @throws IOException
- */
- public SDNCAdapterRestV2IT() throws IOException {
- String sdncCallbackFinal = FileUtil.readResourceFile("__files/SDNCAdapterRestCallbackFinal.json");
- String sdncCallbackNonFinal = FileUtil.readResourceFile("__files/SDNCAdapterRestCallbackNonFinal.json");
- callbacks.put("nonfinal", sdncCallbackNonFinal);
- callbacks.put("final", sdncCallbackFinal);
- }
-
- /**
- * Test the success path through the subflow.
- */
- @Test
- @Ignore
- public void success() throws IOException {
- logStart();
- mocks();
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<String, Object>();
- variables.put("mso-request-id", "a4383a52-b9de-4bc4-bedf-02f3f9466535");
- variables.put("mso-service-instance-id", "fd8bcdbb-b799-43ce-a7ff-ed8f2965a3b5");
- variables.put("isDebugLogEnabled", "true");
- variables.put("SDNCREST_Request",
- FileUtil.readResourceFile("__files/SDNCAdapterRestV2Request.json"));
- variables.put("SDNCREST_InterimNotification1",
- FileUtil.readResourceFile("__files/SDNCInterimNotification1.json"));
-
- invokeSubProcess("SDNCAdapterRestV2", businessKey, variables);
-
- injectSDNCRestCallbacks(callbacks, "nonfinal");
-
- // First non-final response will have done a notification
- Object interimNotification = getVariableFromHistory(businessKey, "SDNCREST_interimNotification");
- Assert.assertNotNull(interimNotification);
-
- injectSDNCRestCallbacks(callbacks, "nonfinal");
-
- // Second non-final response will not have done a notification
- interimNotification = getVariableFromHistory(businessKey, "SDNCREST_interimNotification");
- Assert.assertNull(interimNotification);
-
- injectSDNCRestCallbacks(callbacks, "final");
-
- interimNotification = this.getVariableFromHistory(businessKey, "SDNCREST_interimNotification");
- Assert.assertNull(interimNotification);
-
- waitForProcessEnd(businessKey, 10000);
-
- Assert.assertTrue(isProcessEnded(businessKey));
-
- logEnd();
- }
-
- /**
- * Defines WireMock stubs needed by these tests.
- */
- private void mocks() {
- wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc"))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", "application/json")));
- }
+ private final CallbackSet callbacks = new CallbackSet();
+
+ Logger logger = LoggerFactory.getLogger(SDNCAdapterRestV2IT.class);
+
+
+ /**
+ * Constructor. Insert callbacks.
+ *
+ * @throws IOException
+ */
+ public SDNCAdapterRestV2IT() throws IOException {
+ String sdncCallbackFinal = FileUtil.readResourceFile("__files/SDNCAdapterRestCallbackFinal.json");
+ String sdncCallbackNonFinal = FileUtil.readResourceFile("__files/SDNCAdapterRestCallbackNonFinal.json");
+ callbacks.put("nonfinal", sdncCallbackNonFinal);
+ callbacks.put("final", sdncCallbackFinal);
+ }
+
+ /**
+ * Test the success path through the subflow.
+ */
+ @Test
+ @Ignore
+ public void success() throws IOException {
+ logStart();
+ mocks();
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<String, Object>();
+ variables.put("mso-request-id", "a4383a52-b9de-4bc4-bedf-02f3f9466535");
+ variables.put("mso-service-instance-id", "fd8bcdbb-b799-43ce-a7ff-ed8f2965a3b5");
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("SDNCREST_Request", FileUtil.readResourceFile("__files/SDNCAdapterRestV2Request.json"));
+ variables.put("SDNCREST_InterimNotification1",
+ FileUtil.readResourceFile("__files/SDNCInterimNotification1.json"));
+
+ invokeSubProcess("SDNCAdapterRestV2", businessKey, variables);
+
+ injectSDNCRestCallbacks(callbacks, "nonfinal");
+
+ // First non-final response will have done a notification
+ Object interimNotification = getVariableFromHistory(businessKey, "SDNCREST_interimNotification");
+ Assert.assertNotNull(interimNotification);
+
+ injectSDNCRestCallbacks(callbacks, "nonfinal");
+
+ // Second non-final response will not have done a notification
+ interimNotification = getVariableFromHistory(businessKey, "SDNCREST_interimNotification");
+ Assert.assertNull(interimNotification);
+
+ injectSDNCRestCallbacks(callbacks, "final");
+
+ interimNotification = this.getVariableFromHistory(businessKey, "SDNCREST_interimNotification");
+ Assert.assertNull(interimNotification);
+
+ waitForProcessEnd(businessKey, 10000);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+
+ logEnd();
+ }
+
+ /**
+ * Defines WireMock stubs needed by these tests.
+ */
+ private void mocks() {
+ wireMockServer.stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc"))
+ .willReturn(aResponse().withStatus(202).withHeader("Content-Type", "application/json")));
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SPIPropertiesTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SPIPropertiesTest.java
index 9239889f28..96ea1cad9b 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SPIPropertiesTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SPIPropertiesTest.java
@@ -22,10 +22,8 @@ package org.onap.so.bpmn.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
-
import java.io.FileNotFoundException;
import java.io.IOException;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.so.client.RestPropertiesLoader;
@@ -36,34 +34,37 @@ import org.onap.so.client.sdno.dmaap.SDNOHealthCheckDmaapConsumer;
public class SPIPropertiesTest {
- @BeforeClass
- public static void beforeClass() {
- System.setProperty("mso.config.path", "src/test/resources");
- }
-
- @Test
- public void notEqual() {
- DmaapProperties one = DmaapPropertiesLoader.getInstance().getNewImpl();
- DmaapProperties two = DmaapPropertiesLoader.getInstance().getNewImpl();
- assertNotEquals(one, two);
- }
- @Test
- public void equal() {
- DmaapProperties one = DmaapPropertiesLoader.getInstance().getImpl();
- DmaapProperties two = DmaapPropertiesLoader.getInstance().getImpl();
- assertEquals(one, two);
- }
- @Test
- public void restNotEqual() {
- AAIProperties one = RestPropertiesLoader.getInstance().getNewImpl(AAIProperties.class);
- AAIProperties two = RestPropertiesLoader.getInstance().getNewImpl(AAIProperties.class);
- assertNotEquals(one, two);
- }
- @Test
- public void restEqual() {
- AAIProperties one = RestPropertiesLoader.getInstance().getImpl(AAIProperties.class);
- AAIProperties two = RestPropertiesLoader.getInstance().getImpl(AAIProperties.class);
- assertEquals(one, two);
- }
-
+ @BeforeClass
+ public static void beforeClass() {
+ System.setProperty("mso.config.path", "src/test/resources");
+ }
+
+ @Test
+ public void notEqual() {
+ DmaapProperties one = DmaapPropertiesLoader.getInstance().getNewImpl();
+ DmaapProperties two = DmaapPropertiesLoader.getInstance().getNewImpl();
+ assertNotEquals(one, two);
+ }
+
+ @Test
+ public void equal() {
+ DmaapProperties one = DmaapPropertiesLoader.getInstance().getImpl();
+ DmaapProperties two = DmaapPropertiesLoader.getInstance().getImpl();
+ assertEquals(one, two);
+ }
+
+ @Test
+ public void restNotEqual() {
+ AAIProperties one = RestPropertiesLoader.getInstance().getNewImpl(AAIProperties.class);
+ AAIProperties two = RestPropertiesLoader.getInstance().getNewImpl(AAIProperties.class);
+ assertNotEquals(one, two);
+ }
+
+ @Test
+ public void restEqual() {
+ AAIProperties one = RestPropertiesLoader.getInstance().getImpl(AAIProperties.class);
+ AAIProperties two = RestPropertiesLoader.getInstance().getImpl(AAIProperties.class);
+ assertEquals(one, two);
+ }
+
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SniroHomingV1IT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SniroHomingV1IT.java
index c7ba702212..6b253d2b4d 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SniroHomingV1IT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/SniroHomingV1IT.java
@@ -25,14 +25,12 @@ package org.onap.so.bpmn.common;
import static org.onap.so.bpmn.mock.StubResponseDatabase.MockGetServiceResourcesCatalogDataByModelUuid;
import static org.onap.so.bpmn.mock.StubResponseSNIRO.*;
import static org.junit.Assert.*;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Ignore;
import org.junit.Test;
@@ -49,504 +47,588 @@ import org.slf4j.LoggerFactory;
*/
@Ignore
public class SniroHomingV1IT extends BaseIntegrationTest {
-
- Logger logger = LoggerFactory.getLogger(SniroHomingV1IT.class);
-
-
- ServiceDecomposition serviceDecomposition = new ServiceDecomposition();
- String subscriber = "";
- String subscriber2 = "";
-
- private final CallbackSet callbacks = new CallbackSet();
-
- public SniroHomingV1IT() throws IOException {
- String sniroCallback = FileUtil.readResourceFile("__files/BuildingBlocks/sniroCallback2AR1Vnf");
- String sniroCallback2 = FileUtil.readResourceFile("__files/BuildingBlocks/sniroCallback2AR1Vnf2Net");
- String sniroCallback3 = FileUtil.readResourceFile("__files/BuildingBlocks/sniroCallbackInfraVnf");
- String sniroCallbackNoSolution = FileUtil.readResourceFile("__files/BuildingBlocks/sniroCallbackNoSolutionFound");
- String sniroCallbackPolicyException = FileUtil.readResourceFile("__files/BuildingBlocks/sniroCallbackPolicyException");
- String sniroCallbackServiceException = FileUtil.readResourceFile("__files/BuildingBlocks/sniroCallbackServiceException");
- callbacks.put("sniro", JSON, "SNIROResponse", sniroCallback);
- callbacks.put("sniro2", JSON, "SNIROResponse", sniroCallback2);
- callbacks.put("sniro3", JSON, "SNIROResponse", sniroCallback3);
- callbacks.put("sniroNoSol", JSON, "SNIROResponse", sniroCallbackNoSolution);
- callbacks.put("sniroPolicyEx", JSON, "SNIROResponse", sniroCallbackPolicyException);
- callbacks.put("sniroServiceEx", JSON, "SNIROResponse", sniroCallbackServiceException);
-
- // Service Model
- ModelInfo sModel = new ModelInfo();
- sModel.setModelCustomizationUuid("testModelCustomizationUuid");
- sModel.setModelInstanceName("testModelInstanceName");
- sModel.setModelInvariantUuid("testModelInvariantId");
- sModel.setModelName("testModelName");
- sModel.setModelUuid("testModelUuid");
- sModel.setModelVersion("testModelVersion");
- // Service Instance
- ServiceInstance si = new ServiceInstance();
- si.setInstanceId("testServiceInstanceId123");
- // Allotted Resources
- List<AllottedResource> arList = new ArrayList<AllottedResource>();
- AllottedResource ar = new AllottedResource();
- ar.setResourceId("testResourceIdAR");
- ar.setResourceInstanceName("testARInstanceName");
- ModelInfo arModel = new ModelInfo();
- arModel.setModelCustomizationUuid("testModelCustomizationUuidAR");
- arModel.setModelInvariantUuid("testModelInvariantIdAR");
- arModel.setModelName("testModelNameAR");
- arModel.setModelVersion("testModelVersionAR");
- arModel.setModelUuid("testARModelUuid");
- arModel.setModelType("testModelTypeAR");
- ar.setModelInfo(arModel);
- AllottedResource ar2 = new AllottedResource();
- ar2.setResourceId("testResourceIdAR2");
- ar2.setResourceInstanceName("testAR2InstanceName");
- ModelInfo arModel2 = new ModelInfo();
- arModel2.setModelCustomizationUuid("testModelCustomizationUuidAR2");
- arModel2.setModelInvariantUuid("testModelInvariantIdAR2");
- arModel2.setModelName("testModelNameAR2");
- arModel2.setModelVersion("testModelVersionAR2");
- arModel2.setModelUuid("testAr2ModelUuid");
- arModel2.setModelType("testModelTypeAR2");
- ar2.setModelInfo(arModel2);
- arList.add(ar);
- arList.add(ar2);
- // Vnfs
- List<VnfResource> vnfList = new ArrayList<VnfResource>();
- VnfResource vnf = new VnfResource();
- vnf.setResourceId("testResourceIdVNF");
- vnf.setResourceInstanceName("testVnfInstanceName");
- ModelInfo vnfModel = new ModelInfo();
- vnfModel.setModelCustomizationUuid("testModelCustomizationUuidVNF");
- vnfModel.setModelInvariantUuid("testModelInvariantIdVNF");
- vnfModel.setModelName("testModelNameVNF");
- vnfModel.setModelVersion("testModelVersionVNF");
- vnfModel.setModelUuid("testVnfModelUuid");
- vnfModel.setModelType("testModelTypeVNF");
- vnf.setModelInfo(vnfModel);
- vnfList.add(vnf);
- logger.debug("SERVICE DECOMP: {}", serviceDecomposition.getServiceResourcesJsonString());
- serviceDecomposition.setModelInfo(sModel);
- serviceDecomposition.setAllottedResources(arList);
- serviceDecomposition.setVnfResources(vnfList);
- serviceDecomposition.setServiceInstance(si);
-
- // Subscriber
- subscriber = "{\"globalSubscriberId\": \"SUB12_0322_DS_1201\",\"subscriberCommonSiteId\": \"DALTX0101\",\"subscriberName\": \"SUB_12_0322_DS_1201\"}";
- subscriber2 = "{\"globalSubscriberId\": \"SUB12_0322_DS_1201\",\"subscriberName\": \"SUB_12_0322_DS_1201\"}";
- }
-
- @Test
- // 1802 merge
-
- public void testHoming_success_2AR1Vnf() throws Exception {
-
- mockSNIRO(wireMockServer);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariables(variables);
-
- invokeSubProcess("Homing", businessKey, variables);
-
- injectWorkflowMessages(callbacks, "sniro");
-
- waitForProcessEnd(businessKey, 10000);
-
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- ServiceDecomposition serviceDecompositionExp = (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
- String expectedSniroRequest = (String) getVariableFromHistory(businessKey, "sniroRequest");
-
- Resource resourceAR = serviceDecompositionExp.getServiceResource("testResourceIdAR");
- HomingSolution resourceARHoming = resourceAR.getHomingSolution();
- Resource resourceAR2 = serviceDecompositionExp.getServiceResource("testResourceIdAR2");
- HomingSolution resourceARHoming2 = resourceAR2.getHomingSolution();
- Resource resourceVNF = serviceDecompositionExp.getServiceResource("testResourceIdVNF");
- HomingSolution resourceVNFHoming = resourceVNF.getHomingSolution();
- String resourceARHomingString = resourceARHoming.toString();
- resourceARHomingString = resourceARHomingString.replaceAll("\\s+", " ");
- String resourceARHoming2String = resourceARHoming2.toString();
- resourceARHoming2String = resourceARHoming2String.replaceAll("\\s+", " ");
- String resourceVNFHomingString = resourceVNFHoming.toString();
- resourceVNFHomingString = resourceVNFHomingString.replaceAll("\\s+", " ");
- expectedSniroRequest = expectedSniroRequest.replaceAll("\\s+", "");
-
- assertNull(workflowException);
- assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01", "aic", "dfwtx", "KDTNJ01", "3.0", "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"", "\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""), resourceARHomingString);
- assertEquals(homingSolutionService("service", "testSIID2", "testVnfHostname2", "aic", "testCloudRegionId2", "testAicClli2", "3.0", null, null), resourceARHoming2String);
- assertEquals(homingSolutionCloud("cloud", "", "", "aic", "testCloudRegionId3", "testAicClli3", "3.0", "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"", "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""), resourceVNFHomingString);
- assertEquals(verifySniroRequest(), expectedSniroRequest);
-
- }
-
- @Test
- // 1802 merge
-
- public void testHoming_success_2AR1Vnf2Net() throws Exception {
-
- mockSNIRO(wireMockServer);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariables2(variables);
-
- invokeSubProcess("Homing", businessKey, variables);
-
- injectWorkflowMessages(callbacks, "sniro2");
-
- waitForProcessEnd(businessKey, 10000);
-
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- ServiceDecomposition serviceDecompositionExp = (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
- String expectedSniroRequest = (String) getVariableFromHistory(businessKey, "sniroRequest");
-
- Resource resourceAR = serviceDecompositionExp.getServiceResource("testResourceIdAR");
- HomingSolution resourceARHoming = resourceAR.getHomingSolution();
- Resource resourceAR2 = serviceDecompositionExp.getServiceResource("testResourceIdAR2");
- HomingSolution resourceARHoming2 = resourceAR2.getHomingSolution();
- Resource resourceVNF = serviceDecompositionExp.getServiceResource("testResourceIdVNF");
- HomingSolution resourceVNFHoming = resourceVNF.getHomingSolution();
- Resource resourceNet = serviceDecompositionExp.getServiceResource("testResourceIdNet");
- HomingSolution resourceNetHoming = resourceNet.getHomingSolution();
- Resource resourceNet2 = serviceDecompositionExp.getServiceResource("testResourceIdNet2");
- HomingSolution resourceNetHoming2 = resourceNet2.getHomingSolution();
-
- String resourceARHomingString = resourceARHoming.toString();
- resourceARHomingString = resourceARHomingString.replaceAll("\\s+", " ");
- String resourceARHoming2String = resourceARHoming2.toString();
- resourceARHoming2String = resourceARHoming2String.replaceAll("\\s+", " ");
- String resourceVNFHomingString = resourceVNFHoming.toString();
- resourceVNFHomingString = resourceVNFHomingString.replaceAll("\\s+", " ");
- String resourceNetHomingString = resourceNetHoming.toString();
- resourceNetHomingString = resourceNetHomingString.replaceAll("\\s+", " ");
- String resourceNetHoming2String = resourceNetHoming2.toString();
- resourceNetHoming2String = resourceNetHoming2String.replaceAll("\\s+", " ");
- expectedSniroRequest = expectedSniroRequest.replaceAll("\\s+", "");
-
- assertNull(workflowException);
- assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01", "aic", "dfwtx", "KDTNJ01", "3.0", "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"", "\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""), resourceARHomingString);
- assertEquals(homingSolutionService("service", "testSIID2", "testVnfHostname2", "aic", "testCloudRegionId2", "testAicClli2", "3.0", null, null), resourceARHoming2String);
- assertEquals(homingSolutionCloud("cloud", "", "", "aic", "testCloudRegionId3", "testAicClli3", "3.0", "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"", "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""), resourceVNFHomingString);
- assertEquals(homingSolutionService("service", "testServiceInstanceIdNet", "testVnfHostNameNet", "aic", "testCloudRegionIdNet", "testAicClliNet", "3.0", null, null), resourceNetHomingString);
- assertEquals(homingSolutionCloud("cloud", "", "", "aic", "testCloudRegionIdNet2", "testAicClliNet2", "3.0", "\"f1d563e8-e714-4393-8f99-cc480144a05n\", \"j1d563e8-e714-4393-8f99-cc480144a05n\"", "\"s1d563e8-e714-4393-8f99-cc480144a05n\", \"b1d563e8-e714-4393-8f99-cc480144a05n\""), resourceNetHoming2String);
- assertEquals(verifySniroRequest(), expectedSniroRequest);
- }
-
- @Test
- // 1802 merge
-
- public void testHoming_success_vnfResourceList() throws Exception {
-
- // Create a Service Decomposition
- MockGetServiceResourcesCatalogDataByModelUuid(wireMockServer, "2f7f309d-c842-4644-a2e4-34167be5eeb4", "/BuildingBlocks/catalogResp.json");
- String busKey = UUID.randomUUID().toString();
- Map<String, Object> vars = new HashMap<>();
- setVariablesForServiceDecomposition(vars, "testRequestId123", "ff5256d2-5a33-55df-13ab-12abad84e7ff");
- invokeSubProcess("DecomposeService", busKey, vars);
-
- ServiceDecomposition sd = (ServiceDecomposition) getVariableFromHistory(busKey, "serviceDecomposition");
- List<VnfResource> vnfResourceList = sd.getVnfResources();
- vnfResourceList.get(0).setResourceId("test-resource-id-000");
-
- // Invoke Homing
-
- mockSNIRO(wireMockServer);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("homingService", "sniro");
- variables.put("isDebugLogEnabled", "true");
- variables.put("msoRequestId", "testRequestId");
- variables.put("serviceInstanceId", "testServiceInstanceId");
- variables.put("serviceDecomposition", sd);
- variables.put("subscriberInfo", subscriber2);
-
- invokeSubProcess("Homing", businessKey, variables);
- injectWorkflowMessages(callbacks, "sniro3");
- waitForProcessEnd(businessKey, 10000);
-
- //Get Variables
-
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- ServiceDecomposition serviceDecompositionExp = (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
-
- Resource resourceVnf = serviceDecompositionExp.getServiceResource("test-resource-id-000");
- HomingSolution resourceVnfHoming = resourceVnf.getHomingSolution();
-
- String resourceVnfHomingString = resourceVnfHoming.toString();
- resourceVnfHomingString = resourceVnfHomingString.replaceAll("\\s+", " ");
-
- assertNull(workflowException);
-
- //Verify request
- String sniroRequest = (String) getVariableFromHistory(businessKey, "sniroRequest");
- assertEquals(FileUtil.readResourceFile("__files/BuildingBlocks/sniroRequest_infravnf").replaceAll("\n", "").replaceAll("\r", "").replaceAll("\t", ""), sniroRequest.replaceAll("\n", "").replaceAll("\r", "").replaceAll("\t", ""));
-
- assertEquals(homingSolutionService("service", "service-instance-01234", "MDTNJ01", "CloudOwner", "mtmnj1a", "KDTNJ01", "3.0", "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"", "\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""), resourceVnfHomingString);
- }
-
- @Test
-
- public void testHoming_success_existingLicense() throws Exception {
-
- mockSNIRO(wireMockServer);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<String, Object>();
- setVariablesExistingLicense(variables);
-
- invokeSubProcess("Homing", businessKey, variables);
- injectWorkflowMessages(callbacks, "sniro");
+ Logger logger = LoggerFactory.getLogger(SniroHomingV1IT.class);
+
+
+ ServiceDecomposition serviceDecomposition = new ServiceDecomposition();
+ String subscriber = "";
+ String subscriber2 = "";
+
+ private final CallbackSet callbacks = new CallbackSet();
+
+ public SniroHomingV1IT() throws IOException {
+ String sniroCallback = FileUtil.readResourceFile("__files/BuildingBlocks/sniroCallback2AR1Vnf");
+ String sniroCallback2 = FileUtil.readResourceFile("__files/BuildingBlocks/sniroCallback2AR1Vnf2Net");
+ String sniroCallback3 = FileUtil.readResourceFile("__files/BuildingBlocks/sniroCallbackInfraVnf");
+ String sniroCallbackNoSolution =
+ FileUtil.readResourceFile("__files/BuildingBlocks/sniroCallbackNoSolutionFound");
+ String sniroCallbackPolicyException =
+ FileUtil.readResourceFile("__files/BuildingBlocks/sniroCallbackPolicyException");
+ String sniroCallbackServiceException =
+ FileUtil.readResourceFile("__files/BuildingBlocks/sniroCallbackServiceException");
+ callbacks.put("sniro", JSON, "SNIROResponse", sniroCallback);
+ callbacks.put("sniro2", JSON, "SNIROResponse", sniroCallback2);
+ callbacks.put("sniro3", JSON, "SNIROResponse", sniroCallback3);
+ callbacks.put("sniroNoSol", JSON, "SNIROResponse", sniroCallbackNoSolution);
+ callbacks.put("sniroPolicyEx", JSON, "SNIROResponse", sniroCallbackPolicyException);
+ callbacks.put("sniroServiceEx", JSON, "SNIROResponse", sniroCallbackServiceException);
+
+ // Service Model
+ ModelInfo sModel = new ModelInfo();
+ sModel.setModelCustomizationUuid("testModelCustomizationUuid");
+ sModel.setModelInstanceName("testModelInstanceName");
+ sModel.setModelInvariantUuid("testModelInvariantId");
+ sModel.setModelName("testModelName");
+ sModel.setModelUuid("testModelUuid");
+ sModel.setModelVersion("testModelVersion");
+ // Service Instance
+ ServiceInstance si = new ServiceInstance();
+ si.setInstanceId("testServiceInstanceId123");
+ // Allotted Resources
+ List<AllottedResource> arList = new ArrayList<AllottedResource>();
+ AllottedResource ar = new AllottedResource();
+ ar.setResourceId("testResourceIdAR");
+ ar.setResourceInstanceName("testARInstanceName");
+ ModelInfo arModel = new ModelInfo();
+ arModel.setModelCustomizationUuid("testModelCustomizationUuidAR");
+ arModel.setModelInvariantUuid("testModelInvariantIdAR");
+ arModel.setModelName("testModelNameAR");
+ arModel.setModelVersion("testModelVersionAR");
+ arModel.setModelUuid("testARModelUuid");
+ arModel.setModelType("testModelTypeAR");
+ ar.setModelInfo(arModel);
+ AllottedResource ar2 = new AllottedResource();
+ ar2.setResourceId("testResourceIdAR2");
+ ar2.setResourceInstanceName("testAR2InstanceName");
+ ModelInfo arModel2 = new ModelInfo();
+ arModel2.setModelCustomizationUuid("testModelCustomizationUuidAR2");
+ arModel2.setModelInvariantUuid("testModelInvariantIdAR2");
+ arModel2.setModelName("testModelNameAR2");
+ arModel2.setModelVersion("testModelVersionAR2");
+ arModel2.setModelUuid("testAr2ModelUuid");
+ arModel2.setModelType("testModelTypeAR2");
+ ar2.setModelInfo(arModel2);
+ arList.add(ar);
+ arList.add(ar2);
+ // Vnfs
+ List<VnfResource> vnfList = new ArrayList<VnfResource>();
+ VnfResource vnf = new VnfResource();
+ vnf.setResourceId("testResourceIdVNF");
+ vnf.setResourceInstanceName("testVnfInstanceName");
+ ModelInfo vnfModel = new ModelInfo();
+ vnfModel.setModelCustomizationUuid("testModelCustomizationUuidVNF");
+ vnfModel.setModelInvariantUuid("testModelInvariantIdVNF");
+ vnfModel.setModelName("testModelNameVNF");
+ vnfModel.setModelVersion("testModelVersionVNF");
+ vnfModel.setModelUuid("testVnfModelUuid");
+ vnfModel.setModelType("testModelTypeVNF");
+ vnf.setModelInfo(vnfModel);
+ vnfList.add(vnf);
+ logger.debug("SERVICE DECOMP: {}", serviceDecomposition.getServiceResourcesJsonString());
+ serviceDecomposition.setModelInfo(sModel);
+ serviceDecomposition.setAllottedResources(arList);
+ serviceDecomposition.setVnfResources(vnfList);
+ serviceDecomposition.setServiceInstance(si);
+
+ // Subscriber
+ subscriber =
+ "{\"globalSubscriberId\": \"SUB12_0322_DS_1201\",\"subscriberCommonSiteId\": \"DALTX0101\",\"subscriberName\": \"SUB_12_0322_DS_1201\"}";
+ subscriber2 = "{\"globalSubscriberId\": \"SUB12_0322_DS_1201\",\"subscriberName\": \"SUB_12_0322_DS_1201\"}";
+ }
+
+ @Test
+ // 1802 merge
+
+ public void testHoming_success_2AR1Vnf() throws Exception {
+
+ mockSNIRO(wireMockServer);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariables(variables);
+
+ invokeSubProcess("Homing", businessKey, variables);
+
+ injectWorkflowMessages(callbacks, "sniro");
+
+ waitForProcessEnd(businessKey, 10000);
+
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ ServiceDecomposition serviceDecompositionExp =
+ (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
+ String expectedSniroRequest = (String) getVariableFromHistory(businessKey, "sniroRequest");
+
+ Resource resourceAR = serviceDecompositionExp.getServiceResource("testResourceIdAR");
+ HomingSolution resourceARHoming = resourceAR.getHomingSolution();
+ Resource resourceAR2 = serviceDecompositionExp.getServiceResource("testResourceIdAR2");
+ HomingSolution resourceARHoming2 = resourceAR2.getHomingSolution();
+ Resource resourceVNF = serviceDecompositionExp.getServiceResource("testResourceIdVNF");
+ HomingSolution resourceVNFHoming = resourceVNF.getHomingSolution();
+ String resourceARHomingString = resourceARHoming.toString();
+ resourceARHomingString = resourceARHomingString.replaceAll("\\s+", " ");
+ String resourceARHoming2String = resourceARHoming2.toString();
+ resourceARHoming2String = resourceARHoming2String.replaceAll("\\s+", " ");
+ String resourceVNFHomingString = resourceVNFHoming.toString();
+ resourceVNFHomingString = resourceVNFHomingString.replaceAll("\\s+", " ");
+ expectedSniroRequest = expectedSniroRequest.replaceAll("\\s+", "");
+
+ assertNull(workflowException);
+ assertEquals(
+ homingSolutionService("service", "testSIID1", "MDTNJ01", "aic", "dfwtx", "KDTNJ01", "3.0",
+ "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
+ resourceARHomingString);
+ assertEquals(homingSolutionService("service", "testSIID2", "testVnfHostname2", "aic", "testCloudRegionId2",
+ "testAicClli2", "3.0", null, null), resourceARHoming2String);
+ assertEquals(
+ homingSolutionCloud("cloud", "", "", "aic", "testCloudRegionId3", "testAicClli3", "3.0",
+ "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
+ resourceVNFHomingString);
+ assertEquals(verifySniroRequest(), expectedSniroRequest);
+
+ }
+
+ @Test
+ // 1802 merge
+
+ public void testHoming_success_2AR1Vnf2Net() throws Exception {
+
+ mockSNIRO(wireMockServer);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariables2(variables);
+
+ invokeSubProcess("Homing", businessKey, variables);
+
+ injectWorkflowMessages(callbacks, "sniro2");
+
+ waitForProcessEnd(businessKey, 10000);
+
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ ServiceDecomposition serviceDecompositionExp =
+ (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
+ String expectedSniroRequest = (String) getVariableFromHistory(businessKey, "sniroRequest");
+
+ Resource resourceAR = serviceDecompositionExp.getServiceResource("testResourceIdAR");
+ HomingSolution resourceARHoming = resourceAR.getHomingSolution();
+ Resource resourceAR2 = serviceDecompositionExp.getServiceResource("testResourceIdAR2");
+ HomingSolution resourceARHoming2 = resourceAR2.getHomingSolution();
+ Resource resourceVNF = serviceDecompositionExp.getServiceResource("testResourceIdVNF");
+ HomingSolution resourceVNFHoming = resourceVNF.getHomingSolution();
+ Resource resourceNet = serviceDecompositionExp.getServiceResource("testResourceIdNet");
+ HomingSolution resourceNetHoming = resourceNet.getHomingSolution();
+ Resource resourceNet2 = serviceDecompositionExp.getServiceResource("testResourceIdNet2");
+ HomingSolution resourceNetHoming2 = resourceNet2.getHomingSolution();
+
+ String resourceARHomingString = resourceARHoming.toString();
+ resourceARHomingString = resourceARHomingString.replaceAll("\\s+", " ");
+ String resourceARHoming2String = resourceARHoming2.toString();
+ resourceARHoming2String = resourceARHoming2String.replaceAll("\\s+", " ");
+ String resourceVNFHomingString = resourceVNFHoming.toString();
+ resourceVNFHomingString = resourceVNFHomingString.replaceAll("\\s+", " ");
+ String resourceNetHomingString = resourceNetHoming.toString();
+ resourceNetHomingString = resourceNetHomingString.replaceAll("\\s+", " ");
+ String resourceNetHoming2String = resourceNetHoming2.toString();
+ resourceNetHoming2String = resourceNetHoming2String.replaceAll("\\s+", " ");
+ expectedSniroRequest = expectedSniroRequest.replaceAll("\\s+", "");
+
+ assertNull(workflowException);
+ assertEquals(
+ homingSolutionService("service", "testSIID1", "MDTNJ01", "aic", "dfwtx", "KDTNJ01", "3.0",
+ "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
+ resourceARHomingString);
+ assertEquals(homingSolutionService("service", "testSIID2", "testVnfHostname2", "aic", "testCloudRegionId2",
+ "testAicClli2", "3.0", null, null), resourceARHoming2String);
+ assertEquals(
+ homingSolutionCloud("cloud", "", "", "aic", "testCloudRegionId3", "testAicClli3", "3.0",
+ "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
+ resourceVNFHomingString);
+ assertEquals(homingSolutionService("service", "testServiceInstanceIdNet", "testVnfHostNameNet", "aic",
+ "testCloudRegionIdNet", "testAicClliNet", "3.0", null, null), resourceNetHomingString);
+ assertEquals(
+ homingSolutionCloud("cloud", "", "", "aic", "testCloudRegionIdNet2", "testAicClliNet2", "3.0",
+ "\"f1d563e8-e714-4393-8f99-cc480144a05n\", \"j1d563e8-e714-4393-8f99-cc480144a05n\"",
+ "\"s1d563e8-e714-4393-8f99-cc480144a05n\", \"b1d563e8-e714-4393-8f99-cc480144a05n\""),
+ resourceNetHoming2String);
+ assertEquals(verifySniroRequest(), expectedSniroRequest);
+ }
+
+ @Test
+ // 1802 merge
+
+ public void testHoming_success_vnfResourceList() throws Exception {
+
+ // Create a Service Decomposition
+ MockGetServiceResourcesCatalogDataByModelUuid(wireMockServer, "2f7f309d-c842-4644-a2e4-34167be5eeb4",
+ "/BuildingBlocks/catalogResp.json");
+ String busKey = UUID.randomUUID().toString();
+ Map<String, Object> vars = new HashMap<>();
+ setVariablesForServiceDecomposition(vars, "testRequestId123", "ff5256d2-5a33-55df-13ab-12abad84e7ff");
+ invokeSubProcess("DecomposeService", busKey, vars);
+
+ ServiceDecomposition sd = (ServiceDecomposition) getVariableFromHistory(busKey, "serviceDecomposition");
+ List<VnfResource> vnfResourceList = sd.getVnfResources();
+ vnfResourceList.get(0).setResourceId("test-resource-id-000");
+
+ // Invoke Homing
+
+ mockSNIRO(wireMockServer);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("homingService", "sniro");
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("msoRequestId", "testRequestId");
+ variables.put("serviceInstanceId", "testServiceInstanceId");
+ variables.put("serviceDecomposition", sd);
+ variables.put("subscriberInfo", subscriber2);
+
+ invokeSubProcess("Homing", businessKey, variables);
+ injectWorkflowMessages(callbacks, "sniro3");
+ waitForProcessEnd(businessKey, 10000);
+
+ // Get Variables
+
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ ServiceDecomposition serviceDecompositionExp =
+ (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
+
+ Resource resourceVnf = serviceDecompositionExp.getServiceResource("test-resource-id-000");
+ HomingSolution resourceVnfHoming = resourceVnf.getHomingSolution();
+
+ String resourceVnfHomingString = resourceVnfHoming.toString();
+ resourceVnfHomingString = resourceVnfHomingString.replaceAll("\\s+", " ");
+
+ assertNull(workflowException);
+
+ // Verify request
+ String sniroRequest = (String) getVariableFromHistory(businessKey, "sniroRequest");
+ assertEquals(
+ FileUtil.readResourceFile("__files/BuildingBlocks/sniroRequest_infravnf").replaceAll("\n", "")
+ .replaceAll("\r", "").replaceAll("\t", ""),
+ sniroRequest.replaceAll("\n", "").replaceAll("\r", "").replaceAll("\t", ""));
+
+ assertEquals(homingSolutionService("service", "service-instance-01234", "MDTNJ01", "CloudOwner", "mtmnj1a",
+ "KDTNJ01", "3.0", "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
+ resourceVnfHomingString);
+ }
+
+ @Test
+
+ public void testHoming_success_existingLicense() throws Exception {
+
+ mockSNIRO(wireMockServer);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<String, Object>();
+ setVariablesExistingLicense(variables);
+
+ invokeSubProcess("Homing", businessKey, variables);
+
+ injectWorkflowMessages(callbacks, "sniro");
+
+ waitForProcessEnd(businessKey, 10000);
+
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ ServiceDecomposition serviceDecompositionExp =
+ (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
+ String sniroRequest = (String) getVariableFromHistory(businessKey, "sniroRequest");
- waitForProcessEnd(businessKey, 10000);
+ Resource resourceAR = serviceDecompositionExp.getServiceResource("testResourceIdAR");
+ HomingSolution resourceARHoming = resourceAR.getHomingSolution();
+ Resource resourceAR2 = serviceDecompositionExp.getServiceResource("testResourceIdAR2");
+ HomingSolution resourceARHoming2 = resourceAR2.getHomingSolution();
+ Resource resourceVNF = serviceDecompositionExp.getServiceResource("testResourceIdVNF");
+ HomingSolution resourceVNFHoming = resourceVNF.getHomingSolution();
+ String resourceARHomingString = resourceARHoming.toString();
+ resourceARHomingString = resourceARHomingString.replaceAll("\\s+", " ");
+ String resourceARHoming2String = resourceARHoming2.toString();
+ resourceARHoming2String = resourceARHoming2String.replaceAll("\\s+", " ");
+ String resourceVNFHomingString = resourceVNFHoming.toString();
+ resourceVNFHomingString = resourceVNFHomingString.replaceAll("\\s+", " ");
+ sniroRequest = sniroRequest.replaceAll("\\s+", "");
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- ServiceDecomposition serviceDecompositionExp = (ServiceDecomposition) getVariableFromHistory(businessKey, "serviceDecomposition");
- String sniroRequest = (String) getVariableFromHistory(businessKey, "sniroRequest");
+ assertNull(workflowException);
+ assertEquals(
+ homingSolutionService("service", "testSIID1", "MDTNJ01", "aic", "dfwtx", "KDTNJ01", "3.0",
+ "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""),
+ resourceARHomingString);
+ assertEquals(homingSolutionService("service", "testSIID2", "testVnfHostname2", "aic", "testCloudRegionId2",
+ "testAicClli2", "3.0", null, null), resourceARHoming2String);
+ assertEquals(
+ homingSolutionCloud("cloud", "", "", "aic", "testCloudRegionId3", "testAicClli3", "3.0",
+ "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"",
+ "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""),
+ resourceVNFHomingString);
+ assertEquals(verifySniroRequest_existingLicense(), sniroRequest);
- Resource resourceAR = serviceDecompositionExp.getServiceResource("testResourceIdAR");
- HomingSolution resourceARHoming = resourceAR.getHomingSolution();
- Resource resourceAR2 = serviceDecompositionExp.getServiceResource("testResourceIdAR2");
- HomingSolution resourceARHoming2 = resourceAR2.getHomingSolution();
- Resource resourceVNF = serviceDecompositionExp.getServiceResource("testResourceIdVNF");
- HomingSolution resourceVNFHoming = resourceVNF.getHomingSolution();
- String resourceARHomingString = resourceARHoming.toString();
- resourceARHomingString = resourceARHomingString.replaceAll("\\s+", " ");
- String resourceARHoming2String = resourceARHoming2.toString();
- resourceARHoming2String = resourceARHoming2String.replaceAll("\\s+", " ");
- String resourceVNFHomingString = resourceVNFHoming.toString();
- resourceVNFHomingString = resourceVNFHomingString.replaceAll("\\s+", " ");
- sniroRequest = sniroRequest.replaceAll("\\s+", "");
+ }
- assertNull(workflowException);
- assertEquals(homingSolutionService("service", "testSIID1", "MDTNJ01", "aic", "dfwtx", "KDTNJ01", "3.0", "\"f1d563e8-e714-4393-8f99-cc480144a05e\", \"j1d563e8-e714-4393-8f99-cc480144a05e\"", "\"s1d563e8-e714-4393-8f99-cc480144a05e\", \"b1d563e8-e714-4393-8f99-cc480144a05e\""), resourceARHomingString);
- assertEquals(homingSolutionService("service", "testSIID2", "testVnfHostname2", "aic", "testCloudRegionId2", "testAicClli2", "3.0", null, null), resourceARHoming2String);
- assertEquals(homingSolutionCloud("cloud", "", "", "aic", "testCloudRegionId3", "testAicClli3", "3.0", "\"91d563e8-e714-4393-8f99-cc480144a05e\", \"21d563e8-e714-4393-8f99-cc480144a05e\"", "\"31d563e8-e714-4393-8f99-cc480144a05e\", \"71d563e8-e714-4393-8f99-cc480144a05e\""), resourceVNFHomingString);
- assertEquals(verifySniroRequest_existingLicense(), sniroRequest);
- }
+ @Test
+ public void testHoming_error_inputVariable() throws Exception {
- @Test
-
- public void testHoming_error_inputVariable() throws Exception {
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariables3(variables);
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariables3(variables);
+ invokeSubProcess("Homing", businessKey, variables);
- invokeSubProcess("Homing", businessKey, variables);
+ waitForProcessEnd(businessKey, 10000);
- waitForProcessEnd(businessKey, 10000);
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ assertEquals(
+ "WorkflowException[processKey=Homing,errorCode=4000,errorMessage=A required input variable is missing or null]",
+ workflowException.toString());
+ }
- assertEquals("WorkflowException[processKey=Homing,errorCode=4000,errorMessage=A required input variable is missing or null]", workflowException.toString());
- }
+ @Test
- @Test
-
- public void testHoming_error_badResponse() throws Exception {
- mockSNIRO_500(wireMockServer);
+ public void testHoming_error_badResponse() throws Exception {
+ mockSNIRO_500(wireMockServer);
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariables(variables);
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariables(variables);
- invokeSubProcess("Homing", businessKey, variables);
+ invokeSubProcess("Homing", businessKey, variables);
- waitForProcessEnd(businessKey, 10000);
+ waitForProcessEnd(businessKey, 10000);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- assertEquals("WorkflowException[processKey=Homing,errorCode=500,errorMessage=Received a Bad Sync Response from Sniro/OOF.]", workflowException.toString());
- }
+ assertEquals(
+ "WorkflowException[processKey=Homing,errorCode=500,errorMessage=Received a Bad Sync Response from Sniro/OOF.]",
+ workflowException.toString());
+ }
- @Test
- // 1802 merge
-
- public void testHoming_error_sniroNoSolution() throws Exception {
- mockSNIRO(wireMockServer);
+ @Test
+ // 1802 merge
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariables(variables);
+ public void testHoming_error_sniroNoSolution() throws Exception {
+ mockSNIRO(wireMockServer);
- invokeSubProcess("Homing", businessKey, variables);
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariables(variables);
- injectWorkflowMessages(callbacks, "sniroNoSol");
+ invokeSubProcess("Homing", businessKey, variables);
- waitForProcessEnd(businessKey, 10000);
+ injectWorkflowMessages(callbacks, "sniroNoSol");
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ waitForProcessEnd(businessKey, 10000);
- assertEquals("WorkflowException[processKey=Homing,errorCode=400,errorMessage=No solution found for plan 08e1b8cf-144a-4bac-b293-d5e2eedc97e8]", workflowException.toString());
- }
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+
+ assertEquals(
+ "WorkflowException[processKey=Homing,errorCode=400,errorMessage=No solution found for plan 08e1b8cf-144a-4bac-b293-d5e2eedc97e8]",
+ workflowException.toString());
+ }
- @Test
-
- public void testHoming_error_sniroPolicyException() throws Exception {
- mockSNIRO(wireMockServer);
+ @Test
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariables(variables);
+ public void testHoming_error_sniroPolicyException() throws Exception {
+ mockSNIRO(wireMockServer);
- invokeSubProcess("Homing", businessKey, variables);
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariables(variables);
- injectWorkflowMessages(callbacks, "sniroPolicyEx");
+ invokeSubProcess("Homing", businessKey, variables);
- waitForProcessEnd(businessKey, 10000);
+ injectWorkflowMessages(callbacks, "sniroPolicyEx");
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ waitForProcessEnd(businessKey, 10000);
- assertEquals("WorkflowException[processKey=Homing,errorCode=400,errorMessage=Sniro Async Callback Response contains a Request Error Policy Exception: Message content size exceeds the allowable limit]", workflowException.toString());
- }
-
- @Test
-
- public void testHoming_error_sniroServiceException() throws Exception {
- mockSNIRO(wireMockServer);
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariables(variables);
+ assertEquals(
+ "WorkflowException[processKey=Homing,errorCode=400,errorMessage=Sniro Async Callback Response contains a Request Error Policy Exception: Message content size exceeds the allowable limit]",
+ workflowException.toString());
+ }
- invokeSubProcess("Homing", businessKey, variables);
+ @Test
- injectWorkflowMessages(callbacks, "sniroServiceEx");
+ public void testHoming_error_sniroServiceException() throws Exception {
+ mockSNIRO(wireMockServer);
- waitForProcessEnd(businessKey, 10000);
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariables(variables);
- //Get Variables
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
-
- assertEquals("WorkflowException[processKey=Homing,errorCode=400,errorMessage=Sniro Async Callback Response contains a Request Error Service Exception: SNIROPlacementError: requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://135.21.171.200:8091/v1/plans/97b4e303-5f75-492c-8fb2-21098281c8b8]", workflowException.toString());
- }
-
-
-
- private void setVariables(Map<String, Object> variables) {
- variables.put("homingService", "sniro");
- variables.put("isDebugLogEnabled", "true");
- // variables.put("mso-request-id", "testRequestId");
- variables.put("msoRequestId", "testRequestId");
- variables.put("serviceInstanceId", "testServiceInstanceId");
- variables.put("serviceDecomposition", serviceDecomposition);
- variables.put("subscriberInfo", subscriber2);
-
- }
-
- private void setVariables2(Map<String, Object> variables) {
- List<NetworkResource> netList = new ArrayList<NetworkResource>();
- NetworkResource net = new NetworkResource();
- net.setResourceId("testResourceIdNet");
- ModelInfo netModel = new ModelInfo();
- netModel.setModelCustomizationUuid("testModelCustomizationUuidNet");
- netModel.setModelInvariantUuid("testModelInvariantIdNet");
- netModel.setModelName("testModelNameNet");
- netModel.setModelVersion("testModelVersionNet");
- net.setModelInfo(netModel);
- netList.add(net);
- NetworkResource net2 = new NetworkResource();
- net2.setResourceId("testResourceIdNet2");
- ModelInfo netModel2 = new ModelInfo();
- netModel2.setModelCustomizationUuid("testModelCustomizationUuidNet2");
- netModel2.setModelInvariantUuid("testModelInvariantIdNet2");
- netModel2.setModelName("testModelNameNet2");
- netModel2.setModelVersion("testModelVersionNet2");
- net2.setModelInfo(netModel2);
- netList.add(net2);
- serviceDecomposition.setNetworkResources(netList);
-
- variables.put("homingService", "sniro");
- variables.put("isDebugLogEnabled", "true");
- variables.put("msoRequestId", "testRequestId");
- variables.put("serviceInstanceId", "testServiceInstanceId");
- variables.put("serviceDecomposition", serviceDecomposition);
- variables.put("subscriberInfo", subscriber2);
- }
-
- private void setVariables3(Map<String, Object> variables) {
- variables.put("homingService", "sniro");
- variables.put("isDebugLogEnabled", "true");
- // variables.put("mso-request-id", "testRequestId");
- variables.put("msoRequestId", "testRequestId");
- variables.put("serviceInstanceId", "testServiceInstanceId");
- variables.put("serviceDecomposition", null);
- variables.put("subscriberInfo", subscriber2);
-
- }
-
- private void setVariablesExistingLicense(Map<String, Object> variables) {
- HomingSolution currentHomingSolution = new HomingSolution();
- serviceDecomposition.getVnfResources().get(0).setCurrentHomingSolution(currentHomingSolution);
- serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense().addEntitlementPool("testEntitlementPoolId1");
- serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense().addEntitlementPool("testEntitlementPoolId2");
-
- serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense().addLicenseKeyGroup("testLicenseKeyGroupId1");
- serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense().addLicenseKeyGroup("testLicenseKeyGroupId2");
-
- variables.put("isDebugLogEnabled", "true");
- // variables.put("mso-request-id", "testRequestId");
- variables.put("msoRequestId", "testRequestId");
- variables.put("serviceInstanceId", "testServiceInstanceId");
- variables.put("serviceDecomposition", serviceDecomposition);
- variables.put("subscriberInfo", subscriber2);
-
- }
-
- private String homingSolutionService(String type, String serviceInstanceId, String vnfHostname, String cloudOwner, String cloudRegionId, String aicClli, String aicVersion, String enList, String licenseList){
- String solution = "";
- if(enList == null){
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"serviceInstanceId\" : \"" + serviceInstanceId + "\", \"vnfHostname\" : \"" + vnfHostname + "\", \"cloudOwner\" : \"" + cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId + "\", \"aicClli\" : \"" + aicClli + "\", \"aicVersion\" : \"" + aicVersion + "\", \"license\" : { }, \"rehome\" : false } }";
- }else{
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"serviceInstanceId\" : \"" + serviceInstanceId + "\", \"vnfHostname\" : \"" + vnfHostname + "\", \"cloudOwner\" : \"" + cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId + "\", \"aicClli\" : \"" + aicClli + "\", \"aicVersion\" : \"" + aicVersion + "\", \"license\" : { \"entitlementPoolList\" : [ " + enList + " ], \"licenseKeyGroupList\" : [ " + licenseList + " ] }, \"rehome\" : false } }";
- }
- return solution;
- }
-
- private String homingSolutionCloud(String type, String serviceInstanceId, String vnfHostname, String cloudOwner, String cloudRegionId, String aicClli, String aicVersion, String enList, String licenseList){
- String solution = "";
- if(enList == null){
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" + cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId + "\", \"aicClli\" : \"" + aicClli + "\", \"aicVersion\" : \"" + aicVersion + "\", \"license\" : { }, \"rehome\" : false } }";
- }else{
- solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" + cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId + "\", \"aicClli\" : \"" + aicClli + "\", \"aicVersion\" : \"" + aicVersion + "\", \"license\" : { \"entitlementPoolList\" : [ " + enList + " ], \"licenseKeyGroupList\" : [ " + licenseList + " ] }, \"rehome\" : false } }";
- }
- return solution;
- }
-
- private void setVariablesForServiceDecomposition(Map<String, Object> variables, String requestId, String siId) {
- variables.put("homingService", "sniro");
- variables.put("isDebugLogEnabled", "true");
- variables.put("mso-request-id", requestId);
- variables.put("msoRequestId", requestId);
- variables.put("serviceInstanceId",siId);
-
- String serviceModelInfo = "{ "+ "\"modelType\": \"service\"," +
- "\"modelInvariantUuid\": \"1cc4e2e4-eb6e-404d-a66f-c8733cedcce8\"," +
- "\"modelUuid\": \"2f7f309d-c842-4644-a2e4-34167be5eeb4\"," +
- "\"modelName\": \"ADIOD vRouter vCE 011017 Service\"," +
- "\"modelVersion\": \"5.0\"," +
- "}";
- variables.put("serviceModelInfo", serviceModelInfo);
- }
-
- private String verifySniroRequest(){
- String request = "{\"requestInfo\":{\"transactionId\":\"testRequestId\",\"requestId\":\"testRequestId\",\"callbackUrl\":\"http://localhost:28090/workflows/messages/message/SNIROResponse/testRequestId\",\"sourceId\":\"mso\",\"requestType\":\"initial\",\"optimizer\":[\"placement\",\"license\"],\"numSolutions\":1,\"timeout\":1800},\"placementInfo\":{\"serviceModelInfo\":{\"modelType\":\"\",\"modelInvariantId\":\"testModelInvariantId\",\"modelVersionId\":\"testModelUuid\",\"modelName\":\"testModelName\",\"modelVersion\":\"testModelVersion\"},\"subscriberInfo\":{\"globalSubscriberId\":\"SUB12_0322_DS_1201\",\"subscriberName\":\"SUB_12_0322_DS_1201\",\"subscriberCommonSiteId\":\"\"},\"demandInfo\":{\"placementDemand\":[{\"resourceInstanceType\":\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR\",\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR\",\"modelInvariantId\":\"testModelInvariantIdAR\",\"modelName\":\"testModelNameAR\",\"modelVersion\":\"testModelVersionAR\",\"modelVersionId\":\"testARModelUuid\",\"modelType\":\"testModelTypeAR\"},\"tenantId\":\"\",\"tenantName\":\"\"},{\"resourceInstanceType\":\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR2\",\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR2\",\"modelInvariantId\":\"testModelInvariantIdAR2\",\"modelName\":\"testModelNameAR2\",\"modelVersion\":\"testModelVersionAR2\",\"modelVersionId\":\"testAr2ModelUuid\",\"modelType\":\"testModelTypeAR2\"},\"tenantId\":\"\",\"tenantName\":\"\"}],\"licenseDemand\":[{\"resourceInstanceType\":\"VNF\",\"serviceResourceId\":\"testResourceIdVNF\",\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidVNF\",\"modelInvariantId\":\"testModelInvariantIdVNF\",\"modelName\":\"testModelNameVNF\",\"modelVersion\":\"testModelVersionVNF\",\"modelVersionId\":\"testVnfModelUuid\",\"modelType\":\"testModelTypeVNF\"}}]},\"policyId\":[],\"serviceInstanceId\":\"testServiceInstanceId123\",\"orderInfo\":\"{\\\"requestParameters\\\":null}\"}}";
- return request;
- }
-
- private String verifySniroRequest_existingLicense(){
- String request = "{\"requestInfo\":{\"transactionId\":\"testRequestId\",\"requestId\":\"testRequestId\",\"callbackUrl\":\"http://localhost:28090/workflows/messages/message/SNIROResponse/testRequestId\",\"sourceId\":\"mso\",\"requestType\":\"speedchanged\",\"optimizer\":[\"placement\",\"license\"],\"numSolutions\":1,\"timeout\":1800},\"placementInfo\":{\"serviceModelInfo\":{\"modelType\":\"\",\"modelInvariantId\":\"testModelInvariantId\",\"modelVersionId\":\"testModelUuid\",\"modelName\":\"testModelName\",\"modelVersion\":\"testModelVersion\"},\"subscriberInfo\":{\"globalSubscriberId\":\"SUB12_0322_DS_1201\",\"subscriberName\":\"SUB_12_0322_DS_1201\",\"subscriberCommonSiteId\":\"\"},\"demandInfo\":{\"placementDemand\":[{\"resourceInstanceType\":\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR\",\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR\",\"modelInvariantId\":\"testModelInvariantIdAR\",\"modelName\":\"testModelNameAR\",\"modelVersion\":\"testModelVersionAR\",\"modelVersionId\":\"testARModelUuid\",\"modelType\":\"testModelTypeAR\"},\"tenantId\":\"\",\"tenantName\":\"\"},{\"resourceInstanceType\":\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR2\",\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR2\",\"modelInvariantId\":\"testModelInvariantIdAR2\",\"modelName\":\"testModelNameAR2\",\"modelVersion\":\"testModelVersionAR2\",\"modelVersionId\":\"testAr2ModelUuid\",\"modelType\":\"testModelTypeAR2\"},\"tenantId\":\"\",\"tenantName\":\"\"}],\"licenseDemand\":[{\"resourceInstanceType\":\"VNF\",\"serviceResourceId\":\"testResourceIdVNF\",\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidVNF\",\"modelInvariantId\":\"testModelInvariantIdVNF\",\"modelName\":\"testModelNameVNF\",\"modelVersion\":\"testModelVersionVNF\",\"modelVersionId\":\"testVnfModelUuid\",\"modelType\":\"testModelTypeVNF\"},\"existingLicense\":[{\"entitlementPoolUUID\":[\"testEntitlementPoolId1\",\"testEntitlementPoolId2\"],\"licenseKeyGroupUUID\":[\"testLicenseKeyGroupId1\",\"testLicenseKeyGroupId2\"]}]}]},\"policyId\":[],\"serviceInstanceId\":\"testServiceInstanceId123\",\"orderInfo\":\"{\\\"requestParameters\\\":null}\"}}";
- return request;
- }
+ invokeSubProcess("Homing", businessKey, variables);
+
+ injectWorkflowMessages(callbacks, "sniroServiceEx");
+
+ waitForProcessEnd(businessKey, 10000);
+
+ // Get Variables
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+
+ assertEquals(
+ "WorkflowException[processKey=Homing,errorCode=400,errorMessage=Sniro Async Callback Response contains a Request Error Service Exception: SNIROPlacementError: requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://135.21.171.200:8091/v1/plans/97b4e303-5f75-492c-8fb2-21098281c8b8]",
+ workflowException.toString());
+ }
+
+
+
+ private void setVariables(Map<String, Object> variables) {
+ variables.put("homingService", "sniro");
+ variables.put("isDebugLogEnabled", "true");
+ // variables.put("mso-request-id", "testRequestId");
+ variables.put("msoRequestId", "testRequestId");
+ variables.put("serviceInstanceId", "testServiceInstanceId");
+ variables.put("serviceDecomposition", serviceDecomposition);
+ variables.put("subscriberInfo", subscriber2);
+
+ }
+
+ private void setVariables2(Map<String, Object> variables) {
+ List<NetworkResource> netList = new ArrayList<NetworkResource>();
+ NetworkResource net = new NetworkResource();
+ net.setResourceId("testResourceIdNet");
+ ModelInfo netModel = new ModelInfo();
+ netModel.setModelCustomizationUuid("testModelCustomizationUuidNet");
+ netModel.setModelInvariantUuid("testModelInvariantIdNet");
+ netModel.setModelName("testModelNameNet");
+ netModel.setModelVersion("testModelVersionNet");
+ net.setModelInfo(netModel);
+ netList.add(net);
+ NetworkResource net2 = new NetworkResource();
+ net2.setResourceId("testResourceIdNet2");
+ ModelInfo netModel2 = new ModelInfo();
+ netModel2.setModelCustomizationUuid("testModelCustomizationUuidNet2");
+ netModel2.setModelInvariantUuid("testModelInvariantIdNet2");
+ netModel2.setModelName("testModelNameNet2");
+ netModel2.setModelVersion("testModelVersionNet2");
+ net2.setModelInfo(netModel2);
+ netList.add(net2);
+ serviceDecomposition.setNetworkResources(netList);
+
+ variables.put("homingService", "sniro");
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("msoRequestId", "testRequestId");
+ variables.put("serviceInstanceId", "testServiceInstanceId");
+ variables.put("serviceDecomposition", serviceDecomposition);
+ variables.put("subscriberInfo", subscriber2);
+ }
+
+ private void setVariables3(Map<String, Object> variables) {
+ variables.put("homingService", "sniro");
+ variables.put("isDebugLogEnabled", "true");
+ // variables.put("mso-request-id", "testRequestId");
+ variables.put("msoRequestId", "testRequestId");
+ variables.put("serviceInstanceId", "testServiceInstanceId");
+ variables.put("serviceDecomposition", null);
+ variables.put("subscriberInfo", subscriber2);
+
+ }
+
+ private void setVariablesExistingLicense(Map<String, Object> variables) {
+ HomingSolution currentHomingSolution = new HomingSolution();
+ serviceDecomposition.getVnfResources().get(0).setCurrentHomingSolution(currentHomingSolution);
+ serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense()
+ .addEntitlementPool("testEntitlementPoolId1");
+ serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense()
+ .addEntitlementPool("testEntitlementPoolId2");
+
+ serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense()
+ .addLicenseKeyGroup("testLicenseKeyGroupId1");
+ serviceDecomposition.getVnfResources().get(0).getCurrentHomingSolution().getLicense()
+ .addLicenseKeyGroup("testLicenseKeyGroupId2");
+
+ variables.put("isDebugLogEnabled", "true");
+ // variables.put("mso-request-id", "testRequestId");
+ variables.put("msoRequestId", "testRequestId");
+ variables.put("serviceInstanceId", "testServiceInstanceId");
+ variables.put("serviceDecomposition", serviceDecomposition);
+ variables.put("subscriberInfo", subscriber2);
+
+ }
+
+ private String homingSolutionService(String type, String serviceInstanceId, String vnfHostname, String cloudOwner,
+ String cloudRegionId, String aicClli, String aicVersion, String enList, String licenseList) {
+ String solution = "";
+ if (enList == null) {
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"serviceInstanceId\" : \""
+ + serviceInstanceId + "\", \"vnfHostname\" : \"" + vnfHostname + "\", \"cloudOwner\" : \""
+ + cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId + "\", \"aicClli\" : \"" + aicClli
+ + "\", \"aicVersion\" : \"" + aicVersion + "\", \"license\" : { }, \"rehome\" : false } }";
+ } else {
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"serviceInstanceId\" : \""
+ + serviceInstanceId + "\", \"vnfHostname\" : \"" + vnfHostname + "\", \"cloudOwner\" : \""
+ + cloudOwner + "\", \"cloudRegionId\" : \"" + cloudRegionId + "\", \"aicClli\" : \"" + aicClli
+ + "\", \"aicVersion\" : \"" + aicVersion + "\", \"license\" : { \"entitlementPoolList\" : [ "
+ + enList + " ], \"licenseKeyGroupList\" : [ " + licenseList + " ] }, \"rehome\" : false } }";
+ }
+ return solution;
+ }
+
+ private String homingSolutionCloud(String type, String serviceInstanceId, String vnfHostname, String cloudOwner,
+ String cloudRegionId, String aicClli, String aicVersion, String enList, String licenseList) {
+ String solution = "";
+ if (enList == null) {
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" + cloudOwner
+ + "\", \"cloudRegionId\" : \"" + cloudRegionId + "\", \"aicClli\" : \"" + aicClli
+ + "\", \"aicVersion\" : \"" + aicVersion + "\", \"license\" : { }, \"rehome\" : false } }";
+ } else {
+ solution = "{ \"homingSolution\" : { \"inventoryType\" : \"" + type + "\", \"cloudOwner\" : \"" + cloudOwner
+ + "\", \"cloudRegionId\" : \"" + cloudRegionId + "\", \"aicClli\" : \"" + aicClli
+ + "\", \"aicVersion\" : \"" + aicVersion + "\", \"license\" : { \"entitlementPoolList\" : [ "
+ + enList + " ], \"licenseKeyGroupList\" : [ " + licenseList + " ] }, \"rehome\" : false } }";
+ }
+ return solution;
+ }
+
+ private void setVariablesForServiceDecomposition(Map<String, Object> variables, String requestId, String siId) {
+ variables.put("homingService", "sniro");
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("mso-request-id", requestId);
+ variables.put("msoRequestId", requestId);
+ variables.put("serviceInstanceId", siId);
+
+ String serviceModelInfo = "{ " + "\"modelType\": \"service\","
+ + "\"modelInvariantUuid\": \"1cc4e2e4-eb6e-404d-a66f-c8733cedcce8\","
+ + "\"modelUuid\": \"2f7f309d-c842-4644-a2e4-34167be5eeb4\","
+ + "\"modelName\": \"ADIOD vRouter vCE 011017 Service\"," + "\"modelVersion\": \"5.0\"," + "}";
+ variables.put("serviceModelInfo", serviceModelInfo);
+ }
+
+ private String verifySniroRequest() {
+ String request =
+ "{\"requestInfo\":{\"transactionId\":\"testRequestId\",\"requestId\":\"testRequestId\",\"callbackUrl\":\"http://localhost:28090/workflows/messages/message/SNIROResponse/testRequestId\",\"sourceId\":\"mso\",\"requestType\":\"initial\",\"optimizer\":[\"placement\",\"license\"],\"numSolutions\":1,\"timeout\":1800},\"placementInfo\":{\"serviceModelInfo\":{\"modelType\":\"\",\"modelInvariantId\":\"testModelInvariantId\",\"modelVersionId\":\"testModelUuid\",\"modelName\":\"testModelName\",\"modelVersion\":\"testModelVersion\"},\"subscriberInfo\":{\"globalSubscriberId\":\"SUB12_0322_DS_1201\",\"subscriberName\":\"SUB_12_0322_DS_1201\",\"subscriberCommonSiteId\":\"\"},\"demandInfo\":{\"placementDemand\":[{\"resourceInstanceType\":\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR\",\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR\",\"modelInvariantId\":\"testModelInvariantIdAR\",\"modelName\":\"testModelNameAR\",\"modelVersion\":\"testModelVersionAR\",\"modelVersionId\":\"testARModelUuid\",\"modelType\":\"testModelTypeAR\"},\"tenantId\":\"\",\"tenantName\":\"\"},{\"resourceInstanceType\":\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR2\",\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR2\",\"modelInvariantId\":\"testModelInvariantIdAR2\",\"modelName\":\"testModelNameAR2\",\"modelVersion\":\"testModelVersionAR2\",\"modelVersionId\":\"testAr2ModelUuid\",\"modelType\":\"testModelTypeAR2\"},\"tenantId\":\"\",\"tenantName\":\"\"}],\"licenseDemand\":[{\"resourceInstanceType\":\"VNF\",\"serviceResourceId\":\"testResourceIdVNF\",\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidVNF\",\"modelInvariantId\":\"testModelInvariantIdVNF\",\"modelName\":\"testModelNameVNF\",\"modelVersion\":\"testModelVersionVNF\",\"modelVersionId\":\"testVnfModelUuid\",\"modelType\":\"testModelTypeVNF\"}}]},\"policyId\":[],\"serviceInstanceId\":\"testServiceInstanceId123\",\"orderInfo\":\"{\\\"requestParameters\\\":null}\"}}";
+ return request;
+ }
+
+ private String verifySniroRequest_existingLicense() {
+ String request =
+ "{\"requestInfo\":{\"transactionId\":\"testRequestId\",\"requestId\":\"testRequestId\",\"callbackUrl\":\"http://localhost:28090/workflows/messages/message/SNIROResponse/testRequestId\",\"sourceId\":\"mso\",\"requestType\":\"speedchanged\",\"optimizer\":[\"placement\",\"license\"],\"numSolutions\":1,\"timeout\":1800},\"placementInfo\":{\"serviceModelInfo\":{\"modelType\":\"\",\"modelInvariantId\":\"testModelInvariantId\",\"modelVersionId\":\"testModelUuid\",\"modelName\":\"testModelName\",\"modelVersion\":\"testModelVersion\"},\"subscriberInfo\":{\"globalSubscriberId\":\"SUB12_0322_DS_1201\",\"subscriberName\":\"SUB_12_0322_DS_1201\",\"subscriberCommonSiteId\":\"\"},\"demandInfo\":{\"placementDemand\":[{\"resourceInstanceType\":\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR\",\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR\",\"modelInvariantId\":\"testModelInvariantIdAR\",\"modelName\":\"testModelNameAR\",\"modelVersion\":\"testModelVersionAR\",\"modelVersionId\":\"testARModelUuid\",\"modelType\":\"testModelTypeAR\"},\"tenantId\":\"\",\"tenantName\":\"\"},{\"resourceInstanceType\":\"ALLOTTED_RESOURCE\",\"serviceResourceId\":\"testResourceIdAR2\",\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidAR2\",\"modelInvariantId\":\"testModelInvariantIdAR2\",\"modelName\":\"testModelNameAR2\",\"modelVersion\":\"testModelVersionAR2\",\"modelVersionId\":\"testAr2ModelUuid\",\"modelType\":\"testModelTypeAR2\"},\"tenantId\":\"\",\"tenantName\":\"\"}],\"licenseDemand\":[{\"resourceInstanceType\":\"VNF\",\"serviceResourceId\":\"testResourceIdVNF\",\"resourceModuleName\":\"\",\"resourceModelInfo\":{\"modelCustomizationId\":\"testModelCustomizationUuidVNF\",\"modelInvariantId\":\"testModelInvariantIdVNF\",\"modelName\":\"testModelNameVNF\",\"modelVersion\":\"testModelVersionVNF\",\"modelVersionId\":\"testVnfModelUuid\",\"modelType\":\"testModelTypeVNF\"},\"existingLicense\":[{\"entitlementPoolUUID\":[\"testEntitlementPoolId1\",\"testEntitlementPoolId2\"],\"licenseKeyGroupUUID\":[\"testLicenseKeyGroupId1\",\"testLicenseKeyGroupId2\"]}]}]},\"policyId\":[],\"serviceInstanceId\":\"testServiceInstanceId123\",\"orderInfo\":\"{\\\"requestParameters\\\":null}\"}}";
+ return request;
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/UpdateAAIGenericVnfIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/UpdateAAIGenericVnfIT.java
index 5015a1351a..fc991bd50e 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/UpdateAAIGenericVnfIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/UpdateAAIGenericVnfIT.java
@@ -18,7 +18,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
@@ -28,12 +28,10 @@ import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchGenericVnf;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutGenericVnf;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutGenericVnf_Bad;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Assert;
import org.junit.Ignore;
@@ -49,129 +47,134 @@ import org.slf4j.LoggerFactory;
*/
public class UpdateAAIGenericVnfIT extends BaseIntegrationTest {
-
- Logger logger = LoggerFactory.getLogger(CreateAAIVfModuleIT.class);
-
-
- /**
- * Test the happy path through the flow.
- */
- @Test
-
- public void happyPath() throws IOException {
- logStart();
-
- String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml");
- MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
- MockPutGenericVnf(wireMockServer, "/skask", 200);
- MockPatchGenericVnf(wireMockServer, "skask");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest);
- invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponse");
- Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponseCode");
- logger.debug("Subflow response code: {}", responseCode);
- logger.debug("Subflow response: {}", response);
- Assert.assertEquals(200, responseCode.intValue());
-
- logEnd();
- }
-
- /**
- * Test the happy path through the flow.
- */
- @Test
-
- public void personaMismatch() throws IOException {
-
- logStart();
-
- String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml");
- updateAAIGenericVnfRequest = updateAAIGenericVnfRequest.replaceFirst("introvert", "extrovert");
-
- MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest);
- invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- logger.debug("Workflow Exception: {}", workflowException);
- Assert.assertNotNull(workflowException);
-
- logEnd();
- }
-
- /**
- * Test the case where the GET to AAI returns a 404.
- */
- @Test
-
- public void badGet() throws IOException {
-
- logStart();
-
- String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml");
-
- MockGetGenericVnfById_404(wireMockServer, "skask[?]depth=1");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest);
- invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_getGenericVnfResponse");
- Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_getGenericVnfResponseCode");
- logger.debug("Subflow response code: {}", responseCode);
- logger.debug("Subflow response: {}", response);
- Assert.assertEquals(404, responseCode.intValue());
-
- logEnd();
- }
-
- /**
- * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404.
- */
- @Test
-
- public void badPatch() throws IOException {
-
- logStart();
-
- String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml");
-
- MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
- MockPutGenericVnf_Bad(wireMockServer, "skask", 404);
- MockAAIVfModuleBadPatch(wireMockServer, "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask", 404);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest);
- invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponse");
- Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponseCode");
- logger.debug("Subflow response code: {}", responseCode);
- logger.debug("Subflow response: {}", response);
- Assert.assertEquals(404, responseCode.intValue());
-
- logEnd();
- }
+
+ Logger logger = LoggerFactory.getLogger(CreateAAIVfModuleIT.class);
+
+
+ /**
+ * Test the happy path through the flow.
+ */
+ @Test
+
+ public void happyPath() throws IOException {
+ logStart();
+
+ String updateAAIGenericVnfRequest =
+ FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml");
+ MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
+ MockPutGenericVnf(wireMockServer, "/skask", 200);
+ MockPatchGenericVnf(wireMockServer, "skask");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest);
+ invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponse");
+ Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponseCode");
+ logger.debug("Subflow response code: {}", responseCode);
+ logger.debug("Subflow response: {}", response);
+ Assert.assertEquals(200, responseCode.intValue());
+
+ logEnd();
+ }
+
+ /**
+ * Test the happy path through the flow.
+ */
+ @Test
+
+ public void personaMismatch() throws IOException {
+
+ logStart();
+
+ String updateAAIGenericVnfRequest =
+ FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml");
+ updateAAIGenericVnfRequest = updateAAIGenericVnfRequest.replaceFirst("introvert", "extrovert");
+
+ MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest);
+ invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ WorkflowException workflowException =
+ (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ logger.debug("Workflow Exception: {}", workflowException);
+ Assert.assertNotNull(workflowException);
+
+ logEnd();
+ }
+
+ /**
+ * Test the case where the GET to AAI returns a 404.
+ */
+ @Test
+
+ public void badGet() throws IOException {
+
+ logStart();
+
+ String updateAAIGenericVnfRequest =
+ FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml");
+
+ MockGetGenericVnfById_404(wireMockServer, "skask[?]depth=1");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest);
+ invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_getGenericVnfResponse");
+ Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_getGenericVnfResponseCode");
+ logger.debug("Subflow response code: {}", responseCode);
+ logger.debug("Subflow response: {}", response);
+ Assert.assertEquals(404, responseCode.intValue());
+
+ logEnd();
+ }
+
+ /**
+ * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404.
+ */
+ @Test
+
+ public void badPatch() throws IOException {
+
+ logStart();
+
+ String updateAAIGenericVnfRequest =
+ FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml");
+
+ MockGetGenericVnfByIdWithDepth(wireMockServer, "skask", 1, "VfModularity/GenericVnf.xml");
+ MockPutGenericVnf_Bad(wireMockServer, "skask", 404);
+ MockAAIVfModuleBadPatch(wireMockServer, "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask", 404);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest);
+ invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponse");
+ Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponseCode");
+ logger.debug("Subflow response code: {}", responseCode);
+ logger.debug("Subflow response: {}", response);
+ Assert.assertEquals(404, responseCode.intValue());
+
+ logEnd();
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/UpdateAAIVfModuleIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/UpdateAAIVfModuleIT.java
index 0a3931a12f..ebf8799121 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/UpdateAAIVfModuleIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/UpdateAAIVfModuleIT.java
@@ -18,7 +18,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
@@ -28,12 +28,10 @@ import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPri
import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchVfModuleId;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutGenericVnf;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Assert;
import org.junit.Ignore;
@@ -48,98 +46,105 @@ import org.slf4j.LoggerFactory;
*/
public class UpdateAAIVfModuleIT extends BaseIntegrationTest {
-
- Logger logger = LoggerFactory.getLogger(CreateAAIVfModuleIT.class);
-
-
- /**
- * Test the happy path through the flow.
- */
- @Test
-
- public void happyPath() throws IOException {
- logStart();
-
- String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml");
- MockGetGenericVnfByIdWithPriority(wireMockServer, "/skask/vf-modules/vf-module/supercool", 200, "VfModularity/VfModule-supercool.xml");
- MockPutGenericVnf(wireMockServer, "/skask/vf-modules/vf-module/supercool", "PCRF", 200);
- MockPatchVfModuleId(wireMockServer, "skask", "supercool");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest);
- invokeSubProcess("UpdateAAIVfModule", businessKey, variables);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponse");
- Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponseCode");
- logger.debug("Subflow response code: {}", responseCode);
- logger.debug("Subflow response: {}", response);
- Assert.assertEquals(200, responseCode.intValue());
-
- logEnd();
- }
-
- /**
- * Test the case where the GET to AAI returns a 404.
- */
- @Test
-
- public void badGet() throws IOException {
-
- logStart();
-
- String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml");
- MockGetGenericVnfById(wireMockServer, "/skask/vf-modules/vf-module/.*", "VfModularity/VfModule-supercool.xml", 404);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest);
- invokeSubProcess("UpdateAAIVfModule", businessKey, variables);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_getVfModuleResponse");
- Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_getVfModuleResponseCode");
- logger.debug("Subflow response code: {}", responseCode);
- logger.debug("Subflow response: {}", response);
- Assert.assertEquals(404, responseCode.intValue());
-
- logEnd();
- }
-
- /**
- * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404.
- */
- @Test
-
- public void badPatch() throws IOException {
-
- logStart();
-
- String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml");
- MockGetGenericVnfById_404(wireMockServer, "/skask/vf-modules/vf-module/supercool");
- MockGetGenericVnfById(wireMockServer, "/skask/vf-modules/vf-module/supercool", "VfModularity/VfModule-supercool.xml", 200);
- MockAAIVfModuleBadPatch(wireMockServer, "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/supercool", 404);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("isDebugLogEnabled","true");
- variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest);
- invokeSubProcess("UpdateAAIVfModule", businessKey, variables);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponse");
- Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponseCode");
- logger.debug("Subflow response code: {}", responseCode);
- logger.debug("Subflow response: {}", response);
- Assert.assertEquals(404, responseCode.intValue());
-
- logEnd();
- }
+
+ Logger logger = LoggerFactory.getLogger(CreateAAIVfModuleIT.class);
+
+
+ /**
+ * Test the happy path through the flow.
+ */
+ @Test
+
+ public void happyPath() throws IOException {
+ logStart();
+
+ String updateAAIVfModuleRequest =
+ FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml");
+ MockGetGenericVnfByIdWithPriority(wireMockServer, "/skask/vf-modules/vf-module/supercool", 200,
+ "VfModularity/VfModule-supercool.xml");
+ MockPutGenericVnf(wireMockServer, "/skask/vf-modules/vf-module/supercool", "PCRF", 200);
+ MockPatchVfModuleId(wireMockServer, "skask", "supercool");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest);
+ invokeSubProcess("UpdateAAIVfModule", businessKey, variables);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponse");
+ Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponseCode");
+ logger.debug("Subflow response code: {}", responseCode);
+ logger.debug("Subflow response: {}", response);
+ Assert.assertEquals(200, responseCode.intValue());
+
+ logEnd();
+ }
+
+ /**
+ * Test the case where the GET to AAI returns a 404.
+ */
+ @Test
+
+ public void badGet() throws IOException {
+
+ logStart();
+
+ String updateAAIVfModuleRequest =
+ FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml");
+ MockGetGenericVnfById(wireMockServer, "/skask/vf-modules/vf-module/.*", "VfModularity/VfModule-supercool.xml",
+ 404);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest);
+ invokeSubProcess("UpdateAAIVfModule", businessKey, variables);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_getVfModuleResponse");
+ Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_getVfModuleResponseCode");
+ logger.debug("Subflow response code: {}", responseCode);
+ logger.debug("Subflow response: {}", response);
+ Assert.assertEquals(404, responseCode.intValue());
+
+ logEnd();
+ }
+
+ /**
+ * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404.
+ */
+ @Test
+
+ public void badPatch() throws IOException {
+
+ logStart();
+
+ String updateAAIVfModuleRequest =
+ FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml");
+ MockGetGenericVnfById_404(wireMockServer, "/skask/vf-modules/vf-module/supercool");
+ MockGetGenericVnfById(wireMockServer, "/skask/vf-modules/vf-module/supercool",
+ "VfModularity/VfModule-supercool.xml", 200);
+ MockAAIVfModuleBadPatch(wireMockServer,
+ "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/skask/vf-modules/vf-module/supercool", 404);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest);
+ invokeSubProcess("UpdateAAIVfModule", businessKey, variables);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponse");
+ Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponseCode");
+ logger.debug("Subflow response code: {}", responseCode);
+ logger.debug("Subflow response: {}", response);
+ Assert.assertEquals(404, responseCode.intValue());
+
+ logEnd();
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/VnfAdapterRestV1IT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/VnfAdapterRestV1IT.java
index c0482a52ca..0cefdca9ca 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/VnfAdapterRestV1IT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/VnfAdapterRestV1IT.java
@@ -18,7 +18,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
@@ -29,12 +29,10 @@ import static org.onap.so.bpmn.mock.StubResponseVNFAdapter.mockVNFDelete;
import static org.onap.so.bpmn.mock.StubResponseVNFAdapter.mockVNFPost;
import static org.onap.so.bpmn.mock.StubResponseVNFAdapter.mockVNFPut;
import static org.onap.so.bpmn.mock.StubResponseVNFAdapter.mockVNFRollbackDelete;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Ignore;
import org.junit.Test;
@@ -48,347 +46,261 @@ import org.slf4j.LoggerFactory;
*/
public class VnfAdapterRestV1IT extends BaseIntegrationTest {
-
- Logger logger = LoggerFactory.getLogger(VnfAdapterRestV1IT.class);
-
-
- private static final String EOL = "\n";
-
- private final CallbackSet callbacks = new CallbackSet();
-
- private final String CREATE_VF_MODULE_REQUEST =
- "<createVfModuleRequest>" + EOL +
- " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL +
- " <cloudOwner>cloudOwner</cloudOwner>" + EOL +
- " <tenantId>tenantId</tenantId>" + EOL +
- " <vnfId>vnfId</vnfId>" + EOL +
- " <vfModuleName>vfModuleName</vfModuleName>" + EOL +
- " <vfModuleId>vfModuleId</vfModuleId>" + EOL +
- " <vnfType>vnfType</vnfType>" + EOL +
- " <vnfVersion>vnfVersion</vnfVersion>" + EOL +
- " <vfModuleType>vfModuleType</vfModuleType>" + EOL +
- " <volumeGroupId>volumeGroupId</volumeGroupId>" + EOL +
- " <volumeGroupStackId>volumeGroupStackId</volumeGroupStackId>" + EOL +
- " <baseVfModuleId>baseVfModuleId</baseVfModuleId>" + EOL +
- " <baseVfModuleStackId>baseVfModuleStackId</baseVfModuleStackId>" + EOL +
- " <skipAAI>true</skipAAI>" + EOL +
- " <backout>false</backout>" + EOL +
- " <failIfExists>true</failIfExists>" + EOL +
- " <vfModuleParams>" + EOL +
- " <entry>" + EOL +
- " <key>key1</key>" + EOL +
- " <value>value1</value>" + EOL +
- " </entry>" + EOL +
- " <entry>" + EOL +
- " <key>key2</key>" + EOL +
- " <value>value2</value>" + EOL +
- " </entry>" + EOL +
- " </vfModuleParams>" + EOL +
- " <msoRequest>" + EOL +
- " <requestId>requestId</requestId>" + EOL +
- " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL +
- " </msoRequest>" + EOL +
- " <messageId>{{MESSAGE-ID}}</messageId>" + EOL +
- " <notificationUrl>http://localhost:28080/mso/WorkflowMessage</notificationUrl>" + EOL +
- "</createVfModuleRequest>" + EOL;
-
- private final String UPDATE_VF_MODULE_REQUEST =
- "<updateVfModuleRequest>" + EOL +
- " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL +
- " <cloudOwner>cloudOwner</cloudOwner>" + EOL +
- " <tenantId>tenantId</tenantId>" + EOL +
- " <vnfId>vnfId</vnfId>" + EOL +
- " <vfModuleName>vfModuleName</vfModuleName>" + EOL +
- " <vfModuleId>vfModuleId</vfModuleId>" + EOL +
- " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL +
- " <vnfType>vnfType</vnfType>" + EOL +
- " <vnfVersion>vnfVersion</vnfVersion>" + EOL +
- " <vfModuleType>vfModuleType</vfModuleType>" + EOL +
- " <volumeGroupId>volumeGroupId</volumeGroupId>" + EOL +
- " <volumeGroupStackId>volumeGroupStackId</volumeGroupStackId>" + EOL +
- " <baseVfModuleId>baseVfModuleId</baseVfModuleId>" + EOL +
- " <baseVfModuleStackId>baseVfModuleStackId</baseVfModuleStackId>" + EOL +
- " <skipAAI>true</skipAAI>" + EOL +
- " <backout>false</backout>" + EOL +
- " <failIfExists>true</failIfExists>" + EOL +
- " <vfModuleParams>" + EOL +
- " <entry>" + EOL +
- " <key>key1</key>" + EOL +
- " <value>value1</value>" + EOL +
- " </entry>" + EOL +
- " <entry>" + EOL +
- " <key>key2</key>" + EOL +
- " <value>value2</value>" + EOL +
- " </entry>" + EOL +
- " </vfModuleParams>" + EOL +
- " <msoRequest>" + EOL +
- " <requestId>requestId</requestId>" + EOL +
- " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL +
- " </msoRequest>" + EOL +
- " <messageId>{{MESSAGE-ID}}</messageId>" + EOL +
- " <notificationUrl>http://localhost:28080/mso/WorkflowMessage</notificationUrl>" + EOL +
- "</updateVfModuleRequest>" + EOL;
-
- private final String DELETE_VF_MODULE_REQUEST =
- "<deleteVfModuleRequest>" + EOL +
- " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL +
- " <cloudOwner>cloudOwner</cloudOwner>" + EOL +
- " <tenantId>tenantId</tenantId>" + EOL +
- " <vnfId>vnfId</vnfId>" + EOL +
- " <vfModuleId>vfModuleId</vfModuleId>" + EOL +
- " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL +
- " <skipAAI>true</skipAAI>" + EOL +
- " <msoRequest>" + EOL +
- " <requestId>requestId</requestId>" + EOL +
- " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL +
- " </msoRequest>" + EOL +
- " <messageId>{{MESSAGE-ID}}</messageId>" + EOL +
- " <notificationUrl>http://localhost:28080/mso/WorkflowMessage</notificationUrl>" + EOL +
- "</deleteVfModuleRequest>" + EOL;
-
- private final String ROLLBACK_VF_MODULE_REQUEST =
- "<rollbackVfModuleRequest>" + EOL +
- " <messageId>{{MESSAGE-ID}}</messageId>" + EOL +
- " <notificationUrl>http://localhost:28080/mso/WorkflowMessage</notificationUrl>" + EOL +
- " <skipAAI>true</skipAAI>" + EOL +
- " <vfModuleRollback>" + EOL +
- " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL +
- " <cloudOwner>cloudOwner</cloudOwner>" + EOL +
- " <tenantId>tenantId</tenantId>" + EOL +
- " <vnfId>vnfId</vnfId>" + EOL +
- " <vfModuleId>vfModuleId</vfModuleId>" + EOL +
- " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL +
- " <msoRequest>" + EOL +
- " <requestId>requestId</requestId>" + EOL +
- " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL +
- " </msoRequest>" + EOL +
- " <messageId>{{MESSAGE-ID}}</messageId>" + EOL +
- " <vfModuleCreated>true</vfModuleCreated>" + EOL +
- " </vfModuleRollback>" + EOL +
- "</rollbackVfModuleRequest>" + EOL;
-
- public VnfAdapterRestV1IT() throws IOException {
- callbacks.put("createVfModule",
- "<createVfModuleResponse>" + EOL +
- " <vnfId>vnfId</vnfId>" + EOL +
- " <vfModuleId>vfModuleId</vfModuleId>" + EOL +
- " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL +
- " <vfModuleCreated>true</vfModuleCreated>" + EOL +
- " <vfModuleOutputs>" + EOL +
- " <entry>" + EOL +
- " <key>key1</key>" + EOL +
- " <value>value1</value>" + EOL +
- " </entry>" + EOL +
- " <entry>" + EOL +
- " <key>key2</key>" + EOL +
- " <value>value2</value>" + EOL +
- " </entry>" + EOL +
- " </vfModuleOutputs>" + EOL +
- " <rollback>" + EOL +
- " <vnfId>vnfId</vnfId>" + EOL +
- " <vfModuleId>vfModuleId</vfModuleId>" + EOL +
- " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL +
- " <vfModuleCreated>true</vfModuleCreated>" + EOL +
- " <tenantId>tenantId</tenantId>" + EOL +
- " <cloudOwner>cloudOwner</cloudOwner>" + EOL +
- " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL +
- " <msoRequest>" + EOL +
- " <requestId>requestId</requestId>" + EOL +
- " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL +
- " </msoRequest>" + EOL +
- " <messageId>messageId</messageId>" + EOL +
- " </rollback>" + EOL +
- " <messageId>{{MESSAGE-ID}}</messageId>" + EOL +
- "</createVfModuleResponse>" + EOL);
-
- callbacks.put("updateVfModule",
- "<updateVfModuleResponse>" + EOL +
- " <vnfId>vnfId</vnfId>" + EOL +
- " <vfModuleId>vfModuleId</vfModuleId>" + EOL +
- " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL +
- " <vfModuleOutputs>" + EOL +
- " <entry>" + EOL +
- " <key>key1</key>" + EOL +
- " <value>value1</value>" + EOL +
- " </entry>" + EOL +
- " <entry>" + EOL +
- " <key>key2</key>" + EOL +
- " <value>value2</value>" + EOL +
- " </entry>" + EOL +
- " </vfModuleOutputs>" + EOL +
- " <messageId>{{MESSAGE-ID}}</messageId>" + EOL +
- "</updateVfModuleResponse>" + EOL);
-
- callbacks.put("deleteVfModule",
- "<deleteVfModuleResponse>" + EOL +
- " <vnfId>vnfId</vnfId>" + EOL +
- " <vfModuleId>vfModuleId</vfModuleId>" + EOL +
- " <vfModuleDeleted>true</vfModuleDeleted>" + EOL +
- " <messageId>{{MESSAGE-ID}}</messageId>" + EOL +
- "</deleteVfModuleResponse>" + EOL);
-
- callbacks.put("rollbackVfModule",
- "<rollbackVfModuleResponse>" + EOL +
- " <messageId>{{MESSAGE-ID}}</messageId>" + EOL +
- " <vfModuleRolledback>true</vfModuleRolledback>" + EOL +
- "</rollbackVfModuleResponse>" + EOL);
-
- callbacks.put("vfModuleException",
- "<vfModuleException>" + EOL +
- " <message>message</message>" + EOL +
- " <category>category</category>" + EOL +
- " <rolledBack>false</rolledBack>" + EOL +
- " <messageId>{{MESSAGE-ID}}</messageId>" + EOL +
- "</vfModuleException>" + EOL);
- }
-
- @Test
-
- public void testCreateVfModuleSuccess() throws Exception {
- logStart();
-
- mockVNFPost(wireMockServer, "", 202, "vnfId");
-
- String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312";
- String messageId = requestId + "-" + System.currentTimeMillis();
- String request = CREATE_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", requestId);
- variables.put("isDebugLogEnabled", "true");
- variables.put("vnfAdapterRestV1Request", request);
-
- invokeSubProcess("vnfAdapterRestV1", businessKey, variables);
- injectVNFRestCallbacks(callbacks, "createVfModule");
- waitForProcessEnd(businessKey, 10000);
-
- String response = (String) getVariableFromHistory(businessKey, "vnfAdapterRestV1Response");
- logger.debug("Response:\n{}", response);
- assertTrue(response!=null && response.contains("<createVfModuleResponse>"));
- assertTrue((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator"));
-
- logEnd();
- }
-
- @Test
-
- public void testUpdateVfModuleSuccess() throws Exception {
- logStart();
-
- mockVNFPut(wireMockServer, "/vfModuleId", 202);
-
- String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312";
- String messageId = requestId + "-" + System.currentTimeMillis();
- String request = UPDATE_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", requestId);
- variables.put("isDebugLogEnabled", "true");
- variables.put("vnfAdapterRestV1Request", request);
-
- invokeSubProcess("vnfAdapterRestV1", businessKey, variables);
- injectVNFRestCallbacks(callbacks, "updateVfModule");
- waitForProcessEnd(businessKey, 10000);
-
- String response = (String) getVariableFromHistory(businessKey, "vnfAdapterRestV1Response");
- logger.debug("Response:\n{}", response);
- assertTrue(response.contains("<updateVfModuleResponse>"));
- assertTrue((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator"));
-
- logEnd();
- }
-
- @Test
-
- public void testDeleteVfModuleSuccess() throws Exception {
- logStart();
-
- mockVNFDelete(wireMockServer, "vnfId", "/vfModuleId", 202);
-
- String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312";
- String messageId = requestId + "-" + System.currentTimeMillis();
- String request = DELETE_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", requestId);
- variables.put("isDebugLogEnabled", "true");
- variables.put("vnfAdapterRestV1Request", request);
-
- invokeSubProcess("vnfAdapterRestV1", businessKey, variables);
- injectVNFRestCallbacks(callbacks, "deleteVfModule");
- waitForProcessEnd(businessKey, 10000);
-
- String response = (String) getVariableFromHistory(businessKey, "vnfAdapterRestV1Response");
- logger.debug("Response:\n{}", response);
- assertTrue(response.contains("<deleteVfModuleResponse>"));
- assertTrue((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator"));
-
- logEnd();
- }
-
- @Test
-
- public void testRollbackVfModuleSuccess() throws Exception {
- logStart();
-
- mockVNFRollbackDelete(wireMockServer, "/vfModuleId", 202);
-
- String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312";
- String messageId = requestId + "-" + System.currentTimeMillis();
- String request = ROLLBACK_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", requestId);
- variables.put("isDebugLogEnabled", "true");
- variables.put("vnfAdapterRestV1Request", request);
-
- invokeSubProcess("vnfAdapterRestV1", businessKey, variables);
- injectVNFRestCallbacks(callbacks, "rollbackVfModule");
- waitForProcessEnd(businessKey, 10000);
-
- String response = (String) getVariableFromHistory(businessKey, "vnfAdapterRestV1Response");
- logger.debug("Response:\n{}", response);
- assertTrue(response.contains("<rollbackVfModuleResponse>"));
- assertTrue((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator"));
-
- logEnd();
- }
-
- @Test
-
- public void testCreateVfModuleException() throws Exception {
- logStart();
-
- mockVNFPost(wireMockServer, "", 202, "vnfId");
-
- String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312";
- String messageId = requestId + "-" + System.currentTimeMillis();
- String request = CREATE_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- variables.put("mso-request-id", requestId);
- variables.put("isDebugLogEnabled", "true");
- variables.put("vnfAdapterRestV1Request", request);
-
- invokeSubProcess("vnfAdapterRestV1", businessKey, variables);
- injectVNFRestCallbacks(callbacks, "vfModuleException");
- waitForProcessEnd(businessKey, 10000);
-
- WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
- assertNotNull(wfe);
- logger.debug(wfe.toString());
-
- String response = (String) getVariableFromHistory(businessKey, "WorkflowResponse");
- logger.debug("Response:\n{}", response);
- assertTrue(response.contains("<vfModuleException>"));
- assertFalse((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator"));
- logEnd();
- }
+ Logger logger = LoggerFactory.getLogger(VnfAdapterRestV1IT.class);
+
+
+ private static final String EOL = "\n";
+
+ private final CallbackSet callbacks = new CallbackSet();
+
+ private final String CREATE_VF_MODULE_REQUEST = "<createVfModuleRequest>" + EOL
+ + " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL + " <cloudOwner>cloudOwner</cloudOwner>" + EOL
+ + " <tenantId>tenantId</tenantId>" + EOL + " <vnfId>vnfId</vnfId>" + EOL
+ + " <vfModuleName>vfModuleName</vfModuleName>" + EOL + " <vfModuleId>vfModuleId</vfModuleId>" + EOL
+ + " <vnfType>vnfType</vnfType>" + EOL + " <vnfVersion>vnfVersion</vnfVersion>" + EOL
+ + " <vfModuleType>vfModuleType</vfModuleType>" + EOL + " <volumeGroupId>volumeGroupId</volumeGroupId>"
+ + EOL + " <volumeGroupStackId>volumeGroupStackId</volumeGroupStackId>" + EOL
+ + " <baseVfModuleId>baseVfModuleId</baseVfModuleId>" + EOL
+ + " <baseVfModuleStackId>baseVfModuleStackId</baseVfModuleStackId>" + EOL + " <skipAAI>true</skipAAI>"
+ + EOL + " <backout>false</backout>" + EOL + " <failIfExists>true</failIfExists>" + EOL
+ + " <vfModuleParams>" + EOL + " <entry>" + EOL + " <key>key1</key>" + EOL
+ + " <value>value1</value>" + EOL + " </entry>" + EOL + " <entry>" + EOL + " <key>key2</key>"
+ + EOL + " <value>value2</value>" + EOL + " </entry>" + EOL + " </vfModuleParams>" + EOL
+ + " <msoRequest>" + EOL + " <requestId>requestId</requestId>" + EOL
+ + " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL + " </msoRequest>" + EOL
+ + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL
+ + " <notificationUrl>http://localhost:28080/mso/WorkflowMessage</notificationUrl>" + EOL
+ + "</createVfModuleRequest>" + EOL;
+
+ private final String UPDATE_VF_MODULE_REQUEST = "<updateVfModuleRequest>" + EOL
+ + " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL + " <cloudOwner>cloudOwner</cloudOwner>" + EOL
+ + " <tenantId>tenantId</tenantId>" + EOL + " <vnfId>vnfId</vnfId>" + EOL
+ + " <vfModuleName>vfModuleName</vfModuleName>" + EOL + " <vfModuleId>vfModuleId</vfModuleId>" + EOL
+ + " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL + " <vnfType>vnfType</vnfType>" + EOL
+ + " <vnfVersion>vnfVersion</vnfVersion>" + EOL + " <vfModuleType>vfModuleType</vfModuleType>" + EOL
+ + " <volumeGroupId>volumeGroupId</volumeGroupId>" + EOL
+ + " <volumeGroupStackId>volumeGroupStackId</volumeGroupStackId>" + EOL
+ + " <baseVfModuleId>baseVfModuleId</baseVfModuleId>" + EOL
+ + " <baseVfModuleStackId>baseVfModuleStackId</baseVfModuleStackId>" + EOL + " <skipAAI>true</skipAAI>"
+ + EOL + " <backout>false</backout>" + EOL + " <failIfExists>true</failIfExists>" + EOL
+ + " <vfModuleParams>" + EOL + " <entry>" + EOL + " <key>key1</key>" + EOL
+ + " <value>value1</value>" + EOL + " </entry>" + EOL + " <entry>" + EOL + " <key>key2</key>"
+ + EOL + " <value>value2</value>" + EOL + " </entry>" + EOL + " </vfModuleParams>" + EOL
+ + " <msoRequest>" + EOL + " <requestId>requestId</requestId>" + EOL
+ + " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL + " </msoRequest>" + EOL
+ + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL
+ + " <notificationUrl>http://localhost:28080/mso/WorkflowMessage</notificationUrl>" + EOL
+ + "</updateVfModuleRequest>" + EOL;
+
+ private final String DELETE_VF_MODULE_REQUEST = "<deleteVfModuleRequest>" + EOL
+ + " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL + " <cloudOwner>cloudOwner</cloudOwner>" + EOL
+ + " <tenantId>tenantId</tenantId>" + EOL + " <vnfId>vnfId</vnfId>" + EOL
+ + " <vfModuleId>vfModuleId</vfModuleId>" + EOL + " <vfModuleStackId>vfModuleStackId</vfModuleStackId>"
+ + EOL + " <skipAAI>true</skipAAI>" + EOL + " <msoRequest>" + EOL + " <requestId>requestId</requestId>"
+ + EOL + " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL + " </msoRequest>" + EOL
+ + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL
+ + " <notificationUrl>http://localhost:28080/mso/WorkflowMessage</notificationUrl>" + EOL
+ + "</deleteVfModuleRequest>" + EOL;
+
+ private final String ROLLBACK_VF_MODULE_REQUEST = "<rollbackVfModuleRequest>" + EOL
+ + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL
+ + " <notificationUrl>http://localhost:28080/mso/WorkflowMessage</notificationUrl>" + EOL
+ + " <skipAAI>true</skipAAI>" + EOL + " <vfModuleRollback>" + EOL
+ + " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL + " <cloudOwner>cloudOwner</cloudOwner>" + EOL
+ + " <tenantId>tenantId</tenantId>" + EOL + " <vnfId>vnfId</vnfId>" + EOL
+ + " <vfModuleId>vfModuleId</vfModuleId>" + EOL + " <vfModuleStackId>vfModuleStackId</vfModuleStackId>"
+ + EOL + " <msoRequest>" + EOL + " <requestId>requestId</requestId>" + EOL
+ + " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL + " </msoRequest>" + EOL
+ + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + " <vfModuleCreated>true</vfModuleCreated>" + EOL
+ + " </vfModuleRollback>" + EOL + "</rollbackVfModuleRequest>" + EOL;
+
+ public VnfAdapterRestV1IT() throws IOException {
+ callbacks.put("createVfModule", "<createVfModuleResponse>" + EOL + " <vnfId>vnfId</vnfId>" + EOL
+ + " <vfModuleId>vfModuleId</vfModuleId>" + EOL + " <vfModuleStackId>vfModuleStackId</vfModuleStackId>"
+ + EOL + " <vfModuleCreated>true</vfModuleCreated>" + EOL + " <vfModuleOutputs>" + EOL + " <entry>"
+ + EOL + " <key>key1</key>" + EOL + " <value>value1</value>" + EOL + " </entry>" + EOL
+ + " <entry>" + EOL + " <key>key2</key>" + EOL + " <value>value2</value>" + EOL
+ + " </entry>" + EOL + " </vfModuleOutputs>" + EOL + " <rollback>" + EOL
+ + " <vnfId>vnfId</vnfId>" + EOL + " <vfModuleId>vfModuleId</vfModuleId>" + EOL
+ + " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL
+ + " <vfModuleCreated>true</vfModuleCreated>" + EOL + " <tenantId>tenantId</tenantId>" + EOL
+ + " <cloudOwner>cloudOwner</cloudOwner>" + EOL + " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL
+ + " <msoRequest>" + EOL + " <requestId>requestId</requestId>" + EOL
+ + " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL + " </msoRequest>" + EOL
+ + " <messageId>messageId</messageId>" + EOL + " </rollback>" + EOL
+ + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + "</createVfModuleResponse>" + EOL);
+
+ callbacks.put("updateVfModule",
+ "<updateVfModuleResponse>" + EOL + " <vnfId>vnfId</vnfId>" + EOL
+ + " <vfModuleId>vfModuleId</vfModuleId>" + EOL
+ + " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL + " <vfModuleOutputs>" + EOL
+ + " <entry>" + EOL + " <key>key1</key>" + EOL + " <value>value1</value>" + EOL
+ + " </entry>" + EOL + " <entry>" + EOL + " <key>key2</key>" + EOL
+ + " <value>value2</value>" + EOL + " </entry>" + EOL + " </vfModuleOutputs>" + EOL
+ + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + "</updateVfModuleResponse>" + EOL);
+
+ callbacks.put("deleteVfModule",
+ "<deleteVfModuleResponse>" + EOL + " <vnfId>vnfId</vnfId>" + EOL
+ + " <vfModuleId>vfModuleId</vfModuleId>" + EOL + " <vfModuleDeleted>true</vfModuleDeleted>"
+ + EOL + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + "</deleteVfModuleResponse>" + EOL);
+
+ callbacks.put("rollbackVfModule", "<rollbackVfModuleResponse>" + EOL + " <messageId>{{MESSAGE-ID}}</messageId>"
+ + EOL + " <vfModuleRolledback>true</vfModuleRolledback>" + EOL + "</rollbackVfModuleResponse>" + EOL);
+
+ callbacks.put("vfModuleException",
+ "<vfModuleException>" + EOL + " <message>message</message>" + EOL + " <category>category</category>"
+ + EOL + " <rolledBack>false</rolledBack>" + EOL + " <messageId>{{MESSAGE-ID}}</messageId>"
+ + EOL + "</vfModuleException>" + EOL);
+ }
+
+ @Test
+
+ public void testCreateVfModuleSuccess() throws Exception {
+ logStart();
+
+ mockVNFPost(wireMockServer, "", 202, "vnfId");
+
+ String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312";
+ String messageId = requestId + "-" + System.currentTimeMillis();
+ String request = CREATE_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", requestId);
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("vnfAdapterRestV1Request", request);
+
+ invokeSubProcess("vnfAdapterRestV1", businessKey, variables);
+ injectVNFRestCallbacks(callbacks, "createVfModule");
+ waitForProcessEnd(businessKey, 10000);
+
+ String response = (String) getVariableFromHistory(businessKey, "vnfAdapterRestV1Response");
+ logger.debug("Response:\n{}", response);
+ assertTrue(response != null && response.contains("<createVfModuleResponse>"));
+ assertTrue((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator"));
+
+ logEnd();
+ }
+
+ @Test
+
+ public void testUpdateVfModuleSuccess() throws Exception {
+ logStart();
+
+ mockVNFPut(wireMockServer, "/vfModuleId", 202);
+
+ String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312";
+ String messageId = requestId + "-" + System.currentTimeMillis();
+ String request = UPDATE_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", requestId);
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("vnfAdapterRestV1Request", request);
+
+ invokeSubProcess("vnfAdapterRestV1", businessKey, variables);
+ injectVNFRestCallbacks(callbacks, "updateVfModule");
+ waitForProcessEnd(businessKey, 10000);
+
+ String response = (String) getVariableFromHistory(businessKey, "vnfAdapterRestV1Response");
+ logger.debug("Response:\n{}", response);
+ assertTrue(response.contains("<updateVfModuleResponse>"));
+ assertTrue((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator"));
+
+ logEnd();
+ }
+
+ @Test
+
+ public void testDeleteVfModuleSuccess() throws Exception {
+ logStart();
+
+ mockVNFDelete(wireMockServer, "vnfId", "/vfModuleId", 202);
+
+ String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312";
+ String messageId = requestId + "-" + System.currentTimeMillis();
+ String request = DELETE_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", requestId);
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("vnfAdapterRestV1Request", request);
+
+ invokeSubProcess("vnfAdapterRestV1", businessKey, variables);
+ injectVNFRestCallbacks(callbacks, "deleteVfModule");
+ waitForProcessEnd(businessKey, 10000);
+
+ String response = (String) getVariableFromHistory(businessKey, "vnfAdapterRestV1Response");
+ logger.debug("Response:\n{}", response);
+ assertTrue(response.contains("<deleteVfModuleResponse>"));
+ assertTrue((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator"));
+
+ logEnd();
+ }
+
+ @Test
+
+ public void testRollbackVfModuleSuccess() throws Exception {
+ logStart();
+
+ mockVNFRollbackDelete(wireMockServer, "/vfModuleId", 202);
+
+ String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312";
+ String messageId = requestId + "-" + System.currentTimeMillis();
+ String request = ROLLBACK_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", requestId);
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("vnfAdapterRestV1Request", request);
+
+ invokeSubProcess("vnfAdapterRestV1", businessKey, variables);
+ injectVNFRestCallbacks(callbacks, "rollbackVfModule");
+ waitForProcessEnd(businessKey, 10000);
+
+ String response = (String) getVariableFromHistory(businessKey, "vnfAdapterRestV1Response");
+ logger.debug("Response:\n{}", response);
+ assertTrue(response.contains("<rollbackVfModuleResponse>"));
+ assertTrue((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator"));
+
+ logEnd();
+ }
+
+ @Test
+
+ public void testCreateVfModuleException() throws Exception {
+ logStart();
+
+ mockVNFPost(wireMockServer, "", 202, "vnfId");
+
+ String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312";
+ String messageId = requestId + "-" + System.currentTimeMillis();
+ String request = CREATE_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("mso-request-id", requestId);
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("vnfAdapterRestV1Request", request);
+
+ invokeSubProcess("vnfAdapterRestV1", businessKey, variables);
+ injectVNFRestCallbacks(callbacks, "vfModuleException");
+ waitForProcessEnd(businessKey, 10000);
+
+ WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException");
+ assertNotNull(wfe);
+ logger.debug(wfe.toString());
+
+ String response = (String) getVariableFromHistory(businessKey, "WorkflowResponse");
+ logger.debug("Response:\n{}", response);
+ assertTrue(response.contains("<vfModuleException>"));
+ assertFalse((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator"));
+
+ logEnd();
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowAsyncResourceTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowAsyncResourceTest.java
index a746bbb48e..cc2d6ab640 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowAsyncResourceTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowAsyncResourceTest.java
@@ -16,16 +16,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
import static org.junit.Assert.assertEquals;
-
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
import org.junit.Ignore;
@@ -36,49 +34,53 @@ import org.onap.so.bpmn.common.workflow.service.WorkflowAsyncResource;
@Ignore
public class WorkflowAsyncResourceTest extends WorkflowTest {
- @Test
- @Deployment(resources = { "testAsyncResource.bpmn" })
- public void asyncRequestSuccess() throws InterruptedException {
- //it can be any request which asynchronously processed by the workflow
- String request = "<aetgt:CreateTenantRequest xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\" xmlns:sdncadapterworkflow=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns5=\"http://org.onap/so/request/types/v1\"> <msoservtypes:service-information xmlns:msoservtypes=\"http://org.onap/so/request/types/v1\"> <msoservtypes:service-type>SDN-ETHERNET-INTERNET</msoservtypes:service-type> <msoservtypes:service-instance-id>HI/VLXM/950604//SW_INTERNET</msoservtypes:service-instance-id> <msoservtypes:subscriber-name>SubName01</msoservtypes:subscriber-name> </msoservtypes:service-information> </aetgt:CreateTenantRequest>";
-
- Map<String,String> variables = new HashMap<>();
- variables.put("testAsyncRequestMsg", request);
- variables.put("mso-request-id", UUID.randomUUID().toString());
- variables.put("mso-service-request-timeout", "5");
-
- WorkflowResponse workflowResponse = BPMNUtil.executeAsyncWorkflow(processEngineRule, "testAsyncProcess", variables);
- assertEquals("Received the request, the process is getting executed, request message<aetgt:CreateTenantRequest xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\" xmlns:sdncadapterworkflow=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns5=\"http://org.onap/so/request/types/v1\"> <msoservtypes:service-information xmlns:msoservtypes=\"http://org.onap/so/request/types/v1\"> <msoservtypes:service-type>SDN-ETHERNET-INTERNET</msoservtypes:service-type> <msoservtypes:service-instance-id>HI/VLXM/950604//SW_INTERNET</msoservtypes:service-instance-id> <msoservtypes:subscriber-name>SubName01</msoservtypes:subscriber-name> </msoservtypes:service-information> </aetgt:CreateTenantRequest>", workflowResponse.getResponse());
- assertEquals(200, workflowResponse.getMessageCode());
- }
-
- private void executeWorkflow(String request, String requestId, String processKey) throws InterruptedException {
- WorkflowAsyncResource workflowResource = new WorkflowAsyncResource();
- VariableMapImpl variableMap = new VariableMapImpl();
-
- Map<String, Object> variableValueType = new HashMap<>();
-
- Map<String, Object> requestMsg = new HashMap<>();
- requestMsg.put("value", request);
- requestMsg.put("type", "String");
-
- Map<String, Object> msorequestId = new HashMap<>();
- msorequestId.put("type", "String");
- msorequestId.put("value",requestId);
-
- Map<String, Object> timeout = new HashMap<>();
- timeout.put("type", "String");
- timeout.put("value","5");
-
- variableValueType.put("testAsyncRequestMsg", requestMsg);
- variableValueType.put("mso-request-id", msorequestId);
- variableValueType.put("mso-service-request-timeout", timeout);
-
- variableMap.put("variables", variableValueType);
-
- workflowResource.setProcessEngineServices4junit(processEngineRule);
- workflowResource.startProcessInstanceByKey( processKey, variableMap);
- }
-
-
+ @Test
+ @Deployment(resources = {"testAsyncResource.bpmn"})
+ public void asyncRequestSuccess() throws InterruptedException {
+ // it can be any request which asynchronously processed by the workflow
+ String request =
+ "<aetgt:CreateTenantRequest xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\" xmlns:sdncadapterworkflow=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns5=\"http://org.onap/so/request/types/v1\"> <msoservtypes:service-information xmlns:msoservtypes=\"http://org.onap/so/request/types/v1\"> <msoservtypes:service-type>SDN-ETHERNET-INTERNET</msoservtypes:service-type> <msoservtypes:service-instance-id>HI/VLXM/950604//SW_INTERNET</msoservtypes:service-instance-id> <msoservtypes:subscriber-name>SubName01</msoservtypes:subscriber-name> </msoservtypes:service-information> </aetgt:CreateTenantRequest>";
+
+ Map<String, String> variables = new HashMap<>();
+ variables.put("testAsyncRequestMsg", request);
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ variables.put("mso-service-request-timeout", "5");
+
+ WorkflowResponse workflowResponse =
+ BPMNUtil.executeAsyncWorkflow(processEngineRule, "testAsyncProcess", variables);
+ assertEquals(
+ "Received the request, the process is getting executed, request message<aetgt:CreateTenantRequest xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\" xmlns:sdncadapterworkflow=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns5=\"http://org.onap/so/request/types/v1\"> <msoservtypes:service-information xmlns:msoservtypes=\"http://org.onap/so/request/types/v1\"> <msoservtypes:service-type>SDN-ETHERNET-INTERNET</msoservtypes:service-type> <msoservtypes:service-instance-id>HI/VLXM/950604//SW_INTERNET</msoservtypes:service-instance-id> <msoservtypes:subscriber-name>SubName01</msoservtypes:subscriber-name> </msoservtypes:service-information> </aetgt:CreateTenantRequest>",
+ workflowResponse.getResponse());
+ assertEquals(200, workflowResponse.getMessageCode());
+ }
+
+ private void executeWorkflow(String request, String requestId, String processKey) throws InterruptedException {
+ WorkflowAsyncResource workflowResource = new WorkflowAsyncResource();
+ VariableMapImpl variableMap = new VariableMapImpl();
+
+ Map<String, Object> variableValueType = new HashMap<>();
+
+ Map<String, Object> requestMsg = new HashMap<>();
+ requestMsg.put("value", request);
+ requestMsg.put("type", "String");
+
+ Map<String, Object> msorequestId = new HashMap<>();
+ msorequestId.put("type", "String");
+ msorequestId.put("value", requestId);
+
+ Map<String, Object> timeout = new HashMap<>();
+ timeout.put("type", "String");
+ timeout.put("value", "5");
+
+ variableValueType.put("testAsyncRequestMsg", requestMsg);
+ variableValueType.put("mso-request-id", msorequestId);
+ variableValueType.put("mso-service-request-timeout", timeout);
+
+ variableMap.put("variables", variableValueType);
+
+ workflowResource.setProcessEngineServices4junit(processEngineRule);
+ workflowResource.startProcessInstanceByKey(processKey, variableMap);
+ }
+
+
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowContextHolderTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowContextHolderTest.java
index 0efecac254..23f9818669 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowContextHolderTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowContextHolderTest.java
@@ -16,14 +16,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common;
import java.util.UUID;
-
import org.junit.Assert;
import org.junit.Test;
import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
@@ -35,35 +34,35 @@ import org.onap.so.bpmn.common.workflow.context.WorkflowResponse;
public class WorkflowContextHolderTest {
- @Test
- public void testProcessCallback() throws Exception {
- String requestId = UUID.randomUUID().toString();
- String message = "TEST MESSATGE";
- String responseMessage = "Successfully processed request";
- int testCode = 200;
-
-
- WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();
-
- WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
- callbackResponse.setMessage(message);
- callbackResponse.setResponse(responseMessage);
- callbackResponse.setStatusCode(testCode);
-
- contextHolder.processCallback("testAsyncProcess","process-instance-id",requestId,callbackResponse);
-
- //same object returned
- WorkflowContext contextFound = contextHolder.getWorkflowContext(requestId);
- if(contextFound == null)
- throw new Exception("Expected to find Context Object");
-
- WorkflowResponse testResponse = contextFound.getWorkflowResponse();
- Assert.assertEquals(200,testResponse.getMessageCode());
- Assert.assertEquals(message, testResponse.getMessage());
- Assert.assertEquals(responseMessage, testResponse.getResponse());
-
-
-
- }
+ @Test
+ public void testProcessCallback() throws Exception {
+ String requestId = UUID.randomUUID().toString();
+ String message = "TEST MESSATGE";
+ String responseMessage = "Successfully processed request";
+ int testCode = 200;
+
+
+ WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();
+
+ WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
+ callbackResponse.setMessage(message);
+ callbackResponse.setResponse(responseMessage);
+ callbackResponse.setStatusCode(testCode);
+
+ contextHolder.processCallback("testAsyncProcess", "process-instance-id", requestId, callbackResponse);
+
+ // same object returned
+ WorkflowContext contextFound = contextHolder.getWorkflowContext(requestId);
+ if (contextFound == null)
+ throw new Exception("Expected to find Context Object");
+
+ WorkflowResponse testResponse = contextFound.getWorkflowResponse();
+ Assert.assertEquals(200, testResponse.getMessageCode());
+ Assert.assertEquals(message, testResponse.getMessage());
+ Assert.assertEquals(responseMessage, testResponse.getResponse());
+
+
+
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowTest.java
index eed2978bc7..389f931901 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowTest.java
@@ -26,7 +26,6 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.onap.so.bpmn.core.json.JsonUtils.getJsonValue;
import static org.onap.so.bpmn.core.json.JsonUtils.updJsonValue;
-
import java.io.IOException;
import java.io.StringReader;
import java.lang.management.ManagementFactory;
@@ -37,7 +36,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.NamespaceContext;
@@ -50,7 +48,6 @@ import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
-
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngineException;
@@ -98,2158 +95,2108 @@ import org.xml.sax.SAXException;
/**
* A base class for Workflow tests.
* <p>
- * WireMock response transformers may be specified by declaring public
- * static fields with the @WorkflowTestTransformer annotation. For example:
+ * WireMock response transformers may be specified by declaring public static fields with the @WorkflowTestTransformer
+ * annotation. For example:
+ *
* <pre>
- * @WorkflowTestTransformer
- * public static final ResponseTransformer sdncAdapterMockTransformer =
- * new SDNCAdapterMockTransformer();
+ * &#64;WorkflowTestTransformer
+ * public static final ResponseTransformer sdncAdapterMockTransformer = new SDNCAdapterMockTransformer();
* </pre>
*/
public abstract class WorkflowTest {
- private static final Logger logger = LoggerFactory.getLogger(WorkflowTest.class);
-
- //TODO this is not used anymore, can maybe be removed
- @Rule
- public ProcessEngineRule processEngineRule;
-
- @Autowired
- protected WorkflowResource workflowResourceSync;
-
- @Autowired
- protected ProcessEngine processEngine;
-
- @Autowired
- protected RuntimeService runtimeService;
-
- @Autowired
- protected HistoryService historyService;
-
- @Autowired
- private WorkflowAsyncResource workflowResource;
-
- @Autowired
- private WorkflowMessageResource workflowMessageResource;
-
- @Autowired
- SDNCAdapterCallbackServiceImpl callbackService;
- /**
- * Content-Type for XML.
- */
- protected static final String XML = "application/xml";
-
- /**
- * Content-Type for JSON.
- */
- protected static final String JSON = "application/json; charset=UTF-8";
-
- private static final int timeout = 2000;
-
- /**
- * Constructor.
- */
- public WorkflowTest() throws RuntimeException {
- }
-
- /**
- * The current request ID. Normally set when an "invoke" method is called.
- */
- protected volatile String msoRequestId = null;
-
- /**
- * The current service instance ID. Normally set when an "invoke" method
- * is called.
- */
- protected volatile String msoServiceInstanceId = null;
-
- /**
- * Logs a test start method.
- */
- protected void logStart() {
- logger.debug("STARTED TEST");
- }
-
- /**
- * Logs a test end method.
- */
- protected void logEnd() {
- logger.debug("ENDED TEST");
- }
-
- /**
- * Invokes a subprocess.
- * @param processKey the process key
- * @param businessKey a unique key that will identify the process instance
- * @param injectedVariables variables to inject into the process
- */
- protected void invokeSubProcess(String processKey, String businessKey, Map<String, Object> injectedVariables) {
- RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
- List<String> arguments = runtimeMxBean.getInputArguments();
- logger.debug("JVM args = {}", arguments);
-
- msoRequestId = (String) injectedVariables.get("mso-request-id");
- String requestId = (String) injectedVariables.get("msoRequestId");
-
- if (msoRequestId == null && requestId == null) {
- String msg = "mso-request-id variable was not provided";
- logger.debug(msg);
- fail(msg);
- }
-
- // Note: some scenarios don't have a service-instance-id, may be null
- msoServiceInstanceId = (String) injectedVariables.get("mso-service-instance-id");
-
-
- runtimeService.startProcessInstanceByKey(processKey, businessKey, injectedVariables);
- }
-
- protected String invokeSubProcess(String processKey, Map<String, Object> injectedVariables) {
- RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
- List<String> arguments = runtimeMxBean.getInputArguments();
- logger.debug("JVM args = {}", arguments);
-
- msoRequestId = (String) injectedVariables.get("mso-request-id");
- String requestId = (String) injectedVariables.get("msoRequestId");
-
- if (msoRequestId == null && requestId == null) {
- String msg = "mso-request-id variable was not provided";
- logger.debug(msg);
- fail(msg);
- }
-
- // Note: some scenarios don't have a service-instance-id, may be null
- msoServiceInstanceId = (String) injectedVariables.get("mso-service-instance-id");
-
-
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey, msoRequestId, injectedVariables);
- return processInstance.getId();
- }
-
- /**
- * Invokes an asynchronous process.
- * Errors are handled with junit assertions and will cause the test to fail.
- * @param processKey the process key
- * @param schemaVersion the API schema version, e.g. "v1"
- * @param businessKey a unique key that will identify the process instance
- * @param request the request
- * @return a TestAsyncResponse object associated with the test
- * @throws InterruptedException
- */
- protected TestAsyncResponse invokeAsyncProcess(String processKey,
- String schemaVersion, String businessKey, String request) throws InterruptedException {
- return invokeAsyncProcess(processKey, schemaVersion, businessKey, request, null);
- }
-
- /**
- * Invokes an asynchronous process.
- * Errors are handled with junit assertions and will cause the test to fail.
- * @param processKey the process key
- * @param schemaVersion the API schema version, e.g. "v1"
- * @param businessKey a unique key that will identify the process instance
- * @param request the request
- * @param injectedVariables optional variables to inject into the process
- * @return a TestAsyncResponse object associated with the test
- * @throws InterruptedException
- */
- protected TestAsyncResponse invokeAsyncProcess(String processKey,
- String schemaVersion, String businessKey, String request,
- Map<String, Object> injectedVariables) {
-
- RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
- List<String> arguments = runtimeMxBean.getInputArguments();
- logger.debug("JVM args = {}", arguments);
-
- Map<String, Object> variables = createVariables(schemaVersion, businessKey,
- request, injectedVariables, false);
- VariableMapImpl variableMapImpl = createVariableMapImpl(variables);
-
- logger.debug("Sending {} to {} process", request, processKey);
-
- TestAsyncResponse asyncResponse = new TestAsyncResponse();
-
- asyncResponse.setResponse(workflowResource.startProcessInstanceByKey( processKey, variableMapImpl));
-
- return asyncResponse;
- }
-
- /**
- * Invokes an asynchronous process.
- * Errors are handled with junit assertions and will cause the test to fail.
- * @param processKey the process key
- * @param schemaVersion the API schema version, e.g. "v1"
- * @param businessKey a unique key that will identify the process instance
- * @param request the request
- * @param injectedVariables optional variables to inject into the process
- * @param serviceInstantiationModel indicates whether this method is being
- * invoked for a flow that is designed using the service instantiation model
- * @return a TestAsyncResponse object associated with the test
- * @throws InterruptedException
- */
- protected Response invokeAsyncProcess(String processKey,
- String schemaVersion, String businessKey, String request,
- Map<String, Object> injectedVariables, boolean serviceInstantiationModel) {
-
- RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
- List<String> arguments = runtimeMxBean.getInputArguments();
- logger.debug("JVM args = {}", arguments);
-
- Map<String, Object> variables = createVariables(schemaVersion, businessKey,
- request, injectedVariables, serviceInstantiationModel);
- VariableMapImpl variableMapImpl = createVariableMapImpl(variables);
-
- logger.debug("Sending {} to {} process", request, processKey);
-
- return workflowResource.startProcessInstanceByKey( processKey, variableMapImpl);
-
- }
-
- /**
- * Private helper method that creates a variable map for a request.
- * Errors are handled with junit assertions and will cause the test to fail.
- * @param schemaVersion the API schema version, e.g. "v1"
- * @param businessKey a unique key that will identify the process instance
- * @param request the request
- * @param injectedVariables optional variables to inject into the process
- * @param serviceInstantiationModel indicates whether this method is being
- * invoked for a flow that is designed using the service instantiation model
- * @return a variable map
- */
- private Map<String, Object> createVariables(String schemaVersion,
- String businessKey, String request, Map<String, Object> injectedVariables,
- boolean serviceInstantiationModel) {
-
- Map<String, Object> variables = new HashMap<>();
-
- // These variables may be overridded by injected variables.
- variables.put("mso-service-request-timeout", "180");
- variables.put("isDebugLogEnabled", "true");
-
- // These variables may not be overridded by injected variables.
- String[] notAllowed = new String[] {
- "mso-schema-version",
- "mso-business-key",
- "bpmnRequest",
- "mso-request-id",
- "mso-service-instance-id"
- };
-
- if (injectedVariables != null) {
- for (String key : injectedVariables.keySet()) {
- for (String var : notAllowed) {
- if (var.equals(key)) {
- String msg = "Cannot specify " + var + " in injected variables";
- logger.debug(msg);
- fail(msg);
- }
- }
-
- variables.put(key, injectedVariables.get(key));
- }
- }
-
- variables.put("mso-schema-version", schemaVersion);
- variables.put("mso-business-key", businessKey);
- variables.put("bpmnRequest", request);
-
- if (serviceInstantiationModel) {
-
- /*
- * The request ID and the service instance ID are generated for flows
- * that follow the service instantiation model unless "requestId" and
- * "serviceInstanceId" are injected variables.
- */
-
- try {
- msoRequestId = (String) injectedVariables.get("requestId");
- variables.put("mso-request-id", msoRequestId);
- msoServiceInstanceId = (String) injectedVariables.get("serviceInstanceId");
- variables.put("mso-service-instance-id", msoServiceInstanceId);
- }
- catch(Exception e) {
- }
- if (msoRequestId == null || msoRequestId.trim().equals("")) {
- logger.debug("No requestId element in injectedVariables");
- variables.put("mso-request-id", UUID.randomUUID().toString());
- }
- if (msoServiceInstanceId == null || msoServiceInstanceId.trim().equals("")) {
- logger.debug("No seviceInstanceId element in injectedVariables");
- variables.put("mso-service-instance-id", UUID.randomUUID().toString());
- }
-
- } else {
- msoRequestId = getXMLTextElement(request, "request-id");
-
- if (msoRequestId == null) {
- //check in injected variables
- try {
- msoRequestId = (String) injectedVariables.get("requestId");
- }
- catch(Exception e) {
- }
- if (msoRequestId == null || msoRequestId.trim().equals("")) {
- String msg = "No request-id element in " + request;
- logger.debug(msg);
- fail(msg);
- }
- }
-
- variables.put("mso-request-id", msoRequestId);
-
- // Note: some request types don't have a service-instance-id
- msoServiceInstanceId = getXMLTextElement(request, "service-instance-id");
-
- if (msoServiceInstanceId != null) {
- variables.put("mso-service-instance-id", msoServiceInstanceId);
- }
- }
-
- return variables;
- }
-
- /**
- * Private helper method that creates a camunda VariableMapImpl from a simple
- * variable map.
- * @param variables the simple variable map
- * @return a VariableMap
- */
- private VariableMapImpl createVariableMapImpl(Map<String, Object> variables) {
- Map<String, Object> wrappedVariables = new HashMap<>();
-
- for (String key : variables.keySet()) {
- Object value = variables.get(key);
- wrappedVariables.put(key, wrapVariableValue(value));
- }
-
- VariableMapImpl variableMapImpl = new VariableMapImpl();
- variableMapImpl.put("variables", wrappedVariables);
- return variableMapImpl;
- }
-
- /**
- * Private helper method that wraps a variable value for inclusion in a
- * camunda VariableMapImpl.
- * @param value the variable value
- * @return the wrapped variable
- */
- private Map<String, Object> wrapVariableValue(Object value) {
- HashMap<String, Object> valueMap = new HashMap<>();
- valueMap.put("value", value);
- return valueMap;
- }
-
- /**
- * Receives a response from an asynchronous process.
- * Errors are handled with junit assertions and will cause the test to fail.
- * @param businessKey the process business key
- * @param asyncResponse the TestAsyncResponse object associated with the test
- * @param timeout the timeout in milliseconds
- * @return the WorkflowResponse
- */
- protected WorkflowResponse receiveResponse(String businessKey,
- TestAsyncResponse asyncResponse, long timeout) {
- logger.debug("Waiting {}ms for process with business key {} to send a response", timeout, businessKey);
-
- long now = System.currentTimeMillis() + timeout;
- long endTime = now + timeout;
-
- while (now <= endTime) {
- Response response = asyncResponse.getResponse();
-
- if (response != null) {
- logger.debug("Received a response from process with business key {}", businessKey);
-
- Object entity = response.getEntity();
-
- if (!(entity instanceof WorkflowResponse)) {
- String msg = "Response entity is " +
- (entity == null ? "null" : entity.getClass().getName()) +
- ", expected WorkflowResponse";
- logger.debug(msg);
- fail(msg);
- return null; // unreachable
- }
-
- return (WorkflowResponse) entity;
- }
-
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- String msg = "Interrupted waiting for a response from process with business key " +
- businessKey;
- logger.debug(msg);
- fail(msg);
- return null; // unreachable
- }
-
- now = System.currentTimeMillis();
- }
-
- String msg = "No response received from process with business key " + businessKey +
- " within " + timeout + "ms";
- logger.debug(msg);
- fail("Process with business key " + businessKey + " did not end within 10000ms");
- return null; // unreachable
- }
-
- /**
- * Runs a program to inject SDNC callback data into the test environment.
- * A program is essentially just a list of keys that identify callback data
- * to be injected, in sequence. An example program:
- * <pre>
- * reserve, assign, delete:ERR
- * </pre>
- * Errors are handled with junit assertions and will cause the test to fail.
- * @param callbacks an object containing callback data for the program
- * @param program the program to execute
- */
- protected void injectSDNCRestCallbacks(CallbackSet callbacks, String program) {
-
- String[] cmds = program.replaceAll("\\s+", "").split(",");
-
- for (String cmd : cmds) {
- String action = cmd;
- String modifier = "STD";
-
- if (cmd.contains(":")) {
- String[] parts = cmd.split(":");
- action = parts[0];
- modifier = parts[1];
- }
-
- String content = null;
- String contentType = null;
-
- if ("STD".equals(modifier)) {
- CallbackData callbackData = callbacks.get(action);
-
- if (callbackData == null) {
- String msg = "No callback defined for '" + action + "' SDNC request";
- logger.debug(msg);
- fail(msg);
- }
-
- content = callbackData.getContent();
- contentType = callbackData.getContentType();
- } else if ("ERR".equals(modifier)) {
- content = "{\"SDNCServiceError\":{\"sdncRequestId\":\"((REQUEST-ID))\",\"responseCode\":\"500\",\"responseMessage\":\"SIMULATED ERROR FROM SDNC ADAPTER\",\"ackFinalIndicator\":\"Y\"}}";
- contentType = JSON;
- } else {
- String msg = "Invalid SDNC program modifier: '" + modifier + "'";
- logger.debug(msg);
- fail(msg);
- }
-
- if (contentType == null) {
- // Default for backward compatibility with existing tests.
- contentType = JSON;
- }
-
- if (!injectSDNCRestCallback(contentType, content, 10000)) {
- fail("Failed to inject SDNC '" + action + "' callback");
- }
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- fail("Interrupted after injection of SDNC '" + action + "' callback");
- }
- }
- }
-
- /**
- * Runs a program to inject SDNC events into the test environment.
- * A program is essentially just a list of keys that identify event data
- * to be injected, in sequence. An example program:
- * <pre>
- * event1, event2
- * </pre>
- * NOTE: Each callback must have a message type associated with it, e.g.
- * "SDNCAEvent".
- * Errors are handled with junit assertions and will cause the test to fail.
- * @param callbacks an object containing event data for the program
- * @param program the program to execute
- */
- protected void injectSDNCEvents(CallbackSet callbacks, String program) {
- injectWorkflowMessages(callbacks, program);
- }
-
- /**
- * Runs a program to inject SDNC callback data into the test environment.
- * A program is essentially just a list of keys that identify callback data
- * to be injected, in sequence. An example program:
- * <pre>
- * reserve, assign, delete:ERR
- * </pre>
- * Errors are handled with junit assertions and will cause the test to fail.
- * Uses the static/default timeout value for backward compatibility.
- * @param callbacks an object containing callback data for the program
- * @param program the program to execute
- */
- protected void injectSDNCCallbacks(CallbackSet callbacks, String program) {
- injectSDNCCallbacks(callbacks, program, timeout);
- }
-
- /**
- * Runs a program to inject SDNC callback data into the test environment.
- * A program is essentially just a list of keys that identify callback data
- * to be injected, in sequence. An example program:
- * <pre>
- * reserve, assign, delete:ERR
- * </pre>
- * Errors are handled with junit assertions and will cause the test to fail.
- * @param callbacks an object containing callback data for the program
- * @param program the program to execute
- * @param timeout a timeout value to wait for the callback
- */
- protected void injectSDNCCallbacks(CallbackSet callbacks, String program, int timeout) {
-
- String[] cmds = program.replaceAll("\\s+", "").split(",");
-
- for (String cmd : cmds) {
- String action = cmd;
- String modifier = "STD";
-
- if (cmd.contains(":")) {
- String[] parts = cmd.split(":");
- action = parts[0];
- modifier = parts[1];
- }
-
- String content = null;
- int respCode = 200;
- String respMsg = "OK";
-
- if ("STD".equals(modifier)) {
- CallbackData callbackData = callbacks.get(action);
-
- if (callbackData == null) {
- String msg = "No callback defined for '" + action + "' SDNC request";
- logger.debug(msg);
- fail(msg);
- }
-
- content = callbackData.getContent();
- respCode = 200;
- respMsg = "OK";
- } else if ("CREATED".equals(modifier)) {
- CallbackData callbackData = callbacks.get(action);
-
- if (callbackData == null) {
- String msg = "No callback defined for '" + action + "' SDNC request";
- logger.debug(msg);
- fail(msg);
- }
-
- content = callbackData.getContent();
- respCode = 201;
- respMsg = "Created";
- } else if ("ERR".equals(modifier)) {
- content = "<svc-request-id>((REQUEST-ID))</svc-request-id><response-code>500</response-code><response-message>SIMULATED ERROR FROM SDNC ADAPTER</response-message>";
- respCode = 500;
- respMsg = "SERVER ERROR";
- } else {
- String msg = "Invalid SDNC program modifier: '" + modifier + "'";
- logger.debug(msg);
- fail(msg);
- }
-
- if (!injectSDNCCallback(respCode, respMsg, content, 10000)) {
- fail("Failed to inject SDNC '" + action + "' callback");
- }
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- fail("Interrupted after injection of SDNC '" + action + "' callback");
- }
- }
- }
-
- /**
- * Runs a program to inject VNF adapter REST callback data into the test environment.
- * A program is essentially just a list of keys that identify callback data
- * to be injected, in sequence. An example program:
- * <pre>
- * create, rollback
- * </pre>
- * Errors are handled with junit assertions and will cause the test to fail.
- * @param callbacks an object containing callback data for the program
- * @param program the program to execute
- */
- protected void injectVNFRestCallbacks(CallbackSet callbacks, String program) {
-
- String[] cmds = program.replaceAll("\\s+", "").split(",");
-
- for (String cmd : cmds) {
- String action = cmd;
- String modifier = "STD";
-
- if (cmd.contains(":")) {
- String[] parts = cmd.split(":");
- action = parts[0];
- modifier = parts[1];
- }
-
- String content = null;
- String contentType = null;
-
- if ("STD".equals(modifier)) {
- CallbackData callbackData = callbacks.get(action);
-
- if (callbackData == null) {
- String msg = "No callback defined for '" + action + "' VNF REST request";
- logger.debug(msg);
- fail(msg);
- }
-
- content = callbackData.getContent();
- contentType = callbackData.getContentType();
- } else if ("ERR".equals(modifier)) {
- content = "SIMULATED ERROR FROM VNF ADAPTER";
- contentType = "text/plain";
- } else {
- String msg = "Invalid VNF REST program modifier: '" + modifier + "'";
- logger.debug(msg);
- fail(msg);
- }
-
- if (contentType == null) {
- // Default for backward compatibility with existing tests.
- contentType = XML;
- }
-
- if (!injectVnfAdapterRestCallback(contentType, content, 10000)) {
- fail("Failed to inject VNF REST '" + action + "' callback");
- }
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- fail("Interrupted after injection of VNF REST '" + action + "' callback");
- }
- }
- }
-
- /**
- * Runs a program to inject VNF callback data into the test environment.
- * A program is essentially just a list of keys that identify callback data
- * to be injected, in sequence. An example program:
- * <pre>
- * createVnf, deleteVnf
- * </pre>
- * Errors are handled with junit assertions and will cause the test to fail.
- * @param callbacks an object containing callback data for the program
- * @param program the program to execute
- */
- protected void injectVNFCallbacks(CallbackSet callbacks, String program) {
-
- String[] cmds = program.replaceAll("\\s+", "").split(",");
-
- for (String cmd : cmds) {
- String action = cmd;
- String modifier = "STD";
-
- if (cmd.contains(":")) {
- String[] parts = cmd.split(":");
- action = parts[0];
- modifier = parts[1];
- }
-
- String content = null;
-
- if ("STD".equals(modifier)) {
- CallbackData callbackData = callbacks.get(action);
-
- if (callbackData == null) {
- String msg = "No callback defined for '" + action + "' VNF request";
- logger.debug(msg);
- fail(msg);
- }
-
- content = callbackData.getContent();
- } else if ("ERR".equals(modifier)) {
- String msg = "Currently unsupported VNF program modifier: '" + modifier + "'";
- logger.debug(msg);
- fail(msg);
- } else {
- String msg = "Invalid VNF program modifier: '" + modifier + "'";
- logger.debug(msg);
- fail(msg);
- }
-
- boolean injected = false;
-
- if (content.contains("createVnfNotification")) {
- injected = injectCreateVNFCallback(content, 10000);
- } else if (content.contains("deleteVnfNotification")) {
- injected = injectDeleteVNFCallback(content, 10000);
- } else if (content.contains("updateVnfNotification")) {
- injected = injectUpdateVNFCallback(content, 10000);
- }
-
- if (!injected) {
- String msg = "Failed to inject VNF '" + action + "' callback";
- logger.debug(msg);
- fail(msg);
- }
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- fail("Interrupted after injection of VNF '" + action + "' callback");
- }
- }
- }
-
- /**
- * Waits for the number of running processes with the specified process
- * definition key to equal a particular count.
- * @param processKey the process definition key
- * @param count the desired count
- * @param timeout the timeout in milliseconds
- */
- protected void waitForRunningProcessCount(String processKey, int count, long timeout) {
- logger.debug("Waiting {}ms for there to be {} {} instances", timeout, count, processKey);
-
- long now = System.currentTimeMillis() + timeout;
- long endTime = now + timeout;
- int last = -1;
-
- while (now <= endTime) {
- int actual = runtimeService
- .createProcessInstanceQuery()
- .processDefinitionKey(processKey)
- .list().size();
-
- if (actual != last) {
- logger.debug("There are now {} {} instances", actual, processKey);
- last = actual;
- }
-
- if (actual == count) {
- return;
- }
-
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- String msg = "Interrupted waiting for there to be " + count + " "
- + processKey + " instances";
- logger.debug(msg);
- fail(msg);
- }
-
- now = System.currentTimeMillis();
- }
-
- String msg = "Timed out waiting for there to be " + count + " "
- + processKey + " instances";
- logger.debug(msg);
- fail(msg);
- }
-
- /**
- * Waits for the specified process variable to be set.
- * @param processKey the process definition key
- * @param variable the variable name
- * @param timeout the timeout in milliseconds
- * @return the variable value, or null if it cannot be obtained
- * in the specified time
- */
- protected Object getProcessVariable(String processKey, String variable,
- long timeout) {
-
- logger.debug("Waiting " + timeout + "ms for " + processKey + "." + variable + " to be set");
-
- long now = System.currentTimeMillis() + timeout;
- long endTime = now + timeout;
-
- ProcessInstance processInstance = null;
- Object value = null;
-
- while (value == null) {
- if (now > endTime) {
- if (processInstance == null) {
- logger.debug("Timed out waiting for "
- + processKey + " to start");
- } else {
- logger.debug("Timed out waiting for "
- + processKey + "[" + processInstance.getId()
- + "]." + variable + " to be set");
- }
-
- return null;
- }
-
- ProcessInstanceQuery processInstanceQuery = null;
- if (processInstance == null) {
- processInstanceQuery = runtimeService
- .createProcessInstanceQuery()
- .processDefinitionKey(processKey);
- }
-
- if(processInstanceQuery.count() == 1 || processInstanceQuery.count() == 0){
- processInstance = processInstanceQuery.singleResult();
- }else{
- //TODO There shouldnt be more than one in the list but seems to be happening, need to figure out why happening and best way to get correct one from list
- logger.debug("Process Instance Query returned {} instance. Getting the last instance in the list",
- processInstanceQuery.count());
- List<ProcessInstance> processList = processInstanceQuery.list();
- processInstance = processList.get((processList.size() - 1));
- }
-
-
- if (processInstance != null) {
- value = runtimeService
- .getVariable(processInstance.getId(), variable);
- }
-
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- logger.debug("Interrupted waiting for {}.{} to be set", processKey, variable);
- return null;
- }
-
- now = System.currentTimeMillis();
- }
-
- logger.debug(processKey + "["
- + processInstance.getId() + "]." + variable + "="
- + value);
-
- return value;
- }
-
- /**
- * Injects a single SDNC adapter callback request. The specified callback data
- * may contain the placeholder string ((REQUEST-ID)) which is replaced with
- * the actual SDNC request ID. Note: this is not the requestId in the original
- * MSO request.
- * @param contentType the HTTP content type for the callback
- * @param content the content of the callback
- * @param timeout the timeout in milliseconds
- * @return true if the callback could be injected, false otherwise
- */
- protected boolean injectSDNCRestCallback(String contentType, String content, long timeout) {
- String sdncRequestId = (String) getProcessVariable("SDNCAdapterRestV1",
- "SDNCAResponse_CORRELATOR", timeout);
-
- if (sdncRequestId == null) {
- sdncRequestId = (String) getProcessVariable("SDNCAdapterRestV2",
- "SDNCAResponse_CORRELATOR", timeout);
- }
-
- if (sdncRequestId == null) {
- return false;
- }
-
- content = content.replace("((REQUEST-ID))", sdncRequestId);
- // Deprecated usage. All test code should switch to the (( ... )) syntax.
- content = content.replace("{{REQUEST-ID}}", sdncRequestId);
-
- logger.debug("Injecting SDNC adapter callback");
-
- Response response = workflowMessageResource.deliver(contentType, "SDNCAResponse", sdncRequestId, content);
- logger.debug("Workflow response to SDNC adapter callback: " + response);
- return true;
- }
-
- /**
- * Injects a single SDNC adapter callback request. The specified callback data
- * may contain the placeholder string ((REQUEST-ID)) which is replaced with
- * the actual SDNC request ID. Note: this is not the requestId in the original
- * MSO request.
- * @param content the content of the callback
- * @param respCode the response code (normally 200)
- * @param respMsg the response message (normally "OK")
- * @param timeout the timeout in milliseconds
- * @return true if the callback could be injected, false otherwise
- */
- protected boolean injectSDNCCallback(int respCode, String respMsg,
- String content, long timeout) {
-
- String sdncRequestId = (String) getProcessVariable("sdncAdapter",
- "SDNCA_requestId", timeout);
-
- if (sdncRequestId == null) {
- return false;
- }
-
- content = content.replace("((REQUEST-ID))", sdncRequestId);
- // Deprecated usage. All test code should switch to the (( ... )) syntax.
- content = content.replace("{{REQUEST-ID}}", sdncRequestId);
-
- // TODO this needs to be fixed. It is causing double tags and content
- // Need to parse content before setting below since content includes not just RequestData or modify callback files to only contain RequestData contents.
-
- logger.debug("Injecting SDNC adapter callback");
- CallbackHeader callbackHeader = new CallbackHeader();
- callbackHeader.setRequestId(sdncRequestId);
- callbackHeader.setResponseCode(String.valueOf(respCode));
- callbackHeader.setResponseMessage(respMsg);
- SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest();
- sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader);
- sdncAdapterCallbackRequest.setRequestData(content);
- SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest);
- logger.debug("Workflow response to SDNC adapter callback: " + sdncAdapterResponse);
-
- return true;
- }
-
- /**
- * Injects a single VNF adapter callback request. The specified callback data
- * may contain the placeholder string ((MESSAGE-ID)) which is replaced with
- * the actual message ID. Note: this is not the requestId in the original
- * MSO request.
- * @param contentType the HTTP content type for the callback
- * @param content the content of the callback
- * @param timeout the timeout in milliseconds
- * @return true if the callback could be injected, false otherwise
- */
- protected boolean injectVnfAdapterRestCallback(String contentType, String content, long timeout) {
- String messageId = (String) getProcessVariable("vnfAdapterRestV1",
- "VNFAResponse_CORRELATOR", timeout);
-
- if (messageId == null) {
- return false;
- }
-
- content = content.replace("((MESSAGE-ID))", messageId);
- // Deprecated usage. All test code should switch to the (( ... )) syntax.
- content = content.replace("{{MESSAGE-ID}}", messageId);
-
- logger.debug("Injecting VNF adapter callback");
-
- Response response = workflowMessageResource.deliver(contentType, "VNFAResponse", messageId, content);
- logger.debug("Workflow response to VNF adapter callback: {}", response);
- return true;
- }
-
- /**
- * Injects a Create VNF adapter callback request. The specified callback data
- * may contain the placeholder string ((MESSAGE-ID)) which is replaced with
- * the actual message ID. It may also contain the placeholder string
- * ((REQUEST-ID)) which is replaced request ID of the original MSO request.
- * @param content the content of the callback
- * @param timeout the timeout in milliseconds
- * @return true if the callback could be injected, false otherwise
- * @throws JAXBException if the content does not adhere to the schema
- */
- protected boolean injectCreateVNFCallback(String content, long timeout) {
-
- String messageId = (String) getProcessVariable("vnfAdapterCreateV1",
- "VNFC_messageId", timeout);
-
- if (messageId == null) {
- return false;
- }
-
- content = content.replace("((MESSAGE-ID))", messageId);
- // Deprecated usage. All test code should switch to the (( ... )) syntax.
- content = content.replace("{{MESSAGE-ID}}", messageId);
-
- if(content.contains("((REQUEST-ID))")){
- content = content.replace("((REQUEST-ID))", msoRequestId);
- // Deprecated usage. All test code should switch to the (( ... )) syntax.
- content = content.replace("{{REQUEST-ID}}", msoRequestId);
- }
-
- logger.debug("Injecting VNF adapter callback");
-
- // Is it possible to unmarshal this with JAXB? I couldn't.
-
- CreateVnfNotification createVnfNotification = new CreateVnfNotification();
- XPathTool xpathTool = new VnfNotifyXPathTool();
- xpathTool.setXML(content);
-
- try {
- String completed = xpathTool.evaluate(
- "/tns:createVnfNotification/tns:completed/text()");
- createVnfNotification.setCompleted("true".equals(completed));
-
- String vnfId = xpathTool.evaluate(
- "/tns:createVnfNotification/tns:vnfId/text()");
- createVnfNotification.setVnfId(vnfId);
-
- NodeList entries = (NodeList) xpathTool.evaluate(
- "/tns:createVnfNotification/tns:outputs/tns:entry",
- XPathConstants.NODESET);
-
- CreateVnfNotificationOutputs outputs = new CreateVnfNotificationOutputs();
-
- for (int i = 0; i < entries.getLength(); i++) {
- Node node = entries.item(i);
-
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element entry = (Element) node;
- String key = entry.getElementsByTagNameNS("*", "key").item(0).getTextContent();
- String value = entry.getElementsByTagNameNS("*", "value").item(0).getTextContent();
- outputs.add(key, value);
- }
- }
-
- createVnfNotification.setOutputs(outputs);
-
- VnfRollback rollback = new VnfRollback();
-
- String cloudSiteId = xpathTool.evaluate(
- "/tns:createVnfNotification/tns:rollback/tns:cloudSiteId/text()");
- rollback.setCloudSiteId(cloudSiteId);
-
- String cloudOwner = xpathTool.evaluate(
- "/tns:createVnfNotification/tns:rollback/tns:cloudOwner/text()");
- rollback.setCloudOwner(cloudOwner);
-
- String requestId = xpathTool.evaluate(
- "/tns:createVnfNotification/tns:rollback/tns:msoRequest/tns:requestId/text()");
- String serviceInstanceId = xpathTool.evaluate(
- "/tns:createVnfNotification/tns:rollback/tns:msoRequest/tns:serviceInstanceId/text()");
-
- if (requestId != null || serviceInstanceId != null) {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId(requestId);
- msoRequest.setServiceInstanceId(serviceInstanceId);
- rollback.setMsoRequest(msoRequest);
- }
-
- String tenantCreated = xpathTool.evaluate(
- "/tns:createVnfNotification/tns:rollback/tns:tenantCreated/text()");
- rollback.setTenantCreated("true".equals(tenantCreated));
-
- String tenantId = xpathTool.evaluate(
- "/tns:createVnfNotification/tns:rollback/tns:tenantId/text()");
- rollback.setTenantId(tenantId);
-
- String vnfCreated = xpathTool.evaluate(
- "/tns:createVnfNotification/tns:rollback/tns:vnfCreated/text()");
- rollback.setVnfCreated("true".equals(vnfCreated));
-
- String rollbackVnfId = xpathTool.evaluate(
- "/tns:createVnfNotification/tns:rollback/tns:vnfId/text()");
- rollback.setVnfId(rollbackVnfId);
-
- createVnfNotification.setRollback(rollback);
-
- } catch (Exception e) {
- logger.debug("Failed to unmarshal VNF callback content:");
- logger.debug(content);
- return false;
- }
-
- VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl();
-
-
- notifyService.createVnfNotification(
- messageId,
- createVnfNotification.isCompleted(),
- createVnfNotification.getException(),
- createVnfNotification.getErrorMessage(),
- createVnfNotification.getVnfId(),
- createVnfNotification.getOutputs(),
- createVnfNotification.getRollback());
-
- return true;
- }
-
- /**
- * Injects a Delete VNF adapter callback request. The specified callback data
- * may contain the placeholder string ((MESSAGE-ID)) which is replaced with
- * the actual message ID. It may also contain the placeholder string
- * ((REQUEST-ID)) which is replaced request ID of the original MSO request.
- * @param content the content of the callback
- * @param timeout the timeout in milliseconds
- * @return true if the callback could be injected, false otherwise
- * @throws JAXBException if the content does not adhere to the schema
- */
- protected boolean injectDeleteVNFCallback(String content, long timeout) {
-
- String messageId = (String) getProcessVariable("vnfAdapterDeleteV1",
- "VNFDEL_uuid", timeout);
-
- if (messageId == null) {
- return false;
- }
-
- content = content.replace("((MESSAGE-ID))", messageId);
- // Deprecated usage. All test code should switch to the (( ... )) syntax.
- content = content.replace("{{MESSAGE-ID}}", messageId);
-
- logger.debug("Injecting VNF adapter delete callback");
-
- // Is it possible to unmarshal this with JAXB? I couldn't.
-
- DeleteVnfNotification deleteVnfNotification = new DeleteVnfNotification();
- XPathTool xpathTool = new VnfNotifyXPathTool();
- xpathTool.setXML(content);
-
- try {
- String completed = xpathTool.evaluate(
- "/tns:deleteVnfNotification/tns:completed/text()");
- deleteVnfNotification.setCompleted("true".equals(completed));
- // if notification failure, set the exception and error message
- if (deleteVnfNotification.isCompleted() == false) {
- deleteVnfNotification.setException(MsoExceptionCategory.INTERNAL);
- deleteVnfNotification.setErrorMessage(xpathTool.evaluate(
- "/tns:deleteVnfNotification/tns:errorMessage/text()")) ;
- }
-
- } catch (Exception e) {
- logger.debug("Failed to unmarshal VNF Delete callback content:");
- logger.debug(content);
- return false;
- }
-
- VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl();
-
-
- notifyService.deleteVnfNotification(
- messageId,
- deleteVnfNotification.isCompleted(),
- deleteVnfNotification.getException(),
- deleteVnfNotification.getErrorMessage());
-
- return true;
- }
-
- /**
- * Injects a Update VNF adapter callback request. The specified callback data
- * may contain the placeholder string ((MESSAGE-ID)) which is replaced with
- * the actual message ID. It may also contain the placeholder string
- * ((REQUEST-ID)) which is replaced request ID of the original MSO request.
- * @param content the content of the callback
- * @param timeout the timeout in milliseconds
- * @return true if the callback could be injected, false otherwise
- * @throws JAXBException if the content does not adhere to the schema
- */
- protected boolean injectUpdateVNFCallback(String content, long timeout) {
-
- String messageId = (String) getProcessVariable("vnfAdapterUpdate",
- "VNFU_messageId", timeout);
-
- if (messageId == null) {
- return false;
- }
-
- content = content.replace("((MESSAGE-ID))", messageId);
- // Deprecated usage. All test code should switch to the (( ... )) syntax.
- content = content.replace("{{MESSAGE-ID}}", messageId);
-
- content = content.replace("((REQUEST-ID))", msoRequestId);
- // Deprecated usage. All test code should switch to the (( ... )) syntax.
- content = content.replace("{{REQUEST-ID}}", msoRequestId);
-
- logger.debug("Injecting VNF adapter callback");
-
- // Is it possible to unmarshal this with JAXB? I couldn't.
-
- UpdateVnfNotification updateVnfNotification = new UpdateVnfNotification();
- XPathTool xpathTool = new VnfNotifyXPathTool();
- xpathTool.setXML(content);
-
- try {
- String completed = xpathTool.evaluate(
- "/tns:updateVnfNotification/tns:completed/text()");
- updateVnfNotification.setCompleted("true".equals(completed));
-
- NodeList entries = (NodeList) xpathTool.evaluate(
- "/tns:updateVnfNotification/tns:outputs/tns:entry",
- XPathConstants.NODESET);
-
- UpdateVnfNotificationOutputs outputs = new UpdateVnfNotificationOutputs();
-
- for (int i = 0; i < entries.getLength(); i++) {
- Node node = entries.item(i);
-
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element entry = (Element) node;
- String key = entry.getElementsByTagNameNS("*", "key").item(0).getTextContent();
- String value = entry.getElementsByTagNameNS("*", "value").item(0).getTextContent();
- outputs.add(key, value);
- }
- }
-
- updateVnfNotification.setOutputs(outputs);
-
- VnfRollback rollback = new VnfRollback();
-
- String cloudSiteId = xpathTool.evaluate(
- "/tns:updateVnfNotification/tns:rollback/tns:cloudSiteId/text()");
- rollback.setCloudSiteId(cloudSiteId);
-
- String cloudOwner = xpathTool.evaluate(
- "/tns:updateVnfNotification/tns:rollback/tns:cloudOwner/text()");
- rollback.setCloudOwner(cloudOwner);
-
- String requestId = xpathTool.evaluate(
- "/tns:updateVnfNotification/tns:rollback/tns:msoRequest/tns:requestId/text()");
- String serviceInstanceId = xpathTool.evaluate(
- "/tns:updateVnfNotification/tns:rollback/tns:msoRequest/tns:serviceInstanceId/text()");
-
- if (requestId != null || serviceInstanceId != null) {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId(requestId);
- msoRequest.setServiceInstanceId(serviceInstanceId);
- rollback.setMsoRequest(msoRequest);
- }
-
- String tenantCreated = xpathTool.evaluate(
- "/tns:updateVnfNotification/tns:rollback/tns:tenantCreated/text()");
- rollback.setTenantCreated("true".equals(tenantCreated));
-
- String tenantId = xpathTool.evaluate(
- "/tns:updateVnfNotification/tns:rollback/tns:tenantId/text()");
- rollback.setTenantId(tenantId);
-
- String vnfCreated = xpathTool.evaluate(
- "/tns:updateVnfNotification/tns:rollback/tns:vnfCreated/text()");
- rollback.setVnfCreated("true".equals(vnfCreated));
-
- String rollbackVnfId = xpathTool.evaluate(
- "/tns:updateVnfNotification/tns:rollback/tns:vnfId/text()");
- rollback.setVnfId(rollbackVnfId);
-
- updateVnfNotification.setRollback(rollback);
-
- } catch (Exception e) {
- logger.debug("Failed to unmarshal VNF callback content:");
- logger.debug(content);
- return false;
- }
-
- VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl();
-
-
- notifyService.updateVnfNotification(
- messageId,
- updateVnfNotification.isCompleted(),
- updateVnfNotification.getException(),
- updateVnfNotification.getErrorMessage(),
- updateVnfNotification.getOutputs(),
- updateVnfNotification.getRollback());
-
- return true;
- }
-
- /**
- * Runs a program to inject workflow messages into the test environment.
- * A program is essentially just a list of keys that identify event data
- * to be injected, in sequence. An example program:
- * <pre>
- * event1, event2
- * </pre>
- * Errors are handled with junit assertions and will cause the test to fail.
- * NOTE: Each callback must have a workflow message type associated with it.
- * @param callbacks an object containing event data for the program
- * @param program the program to execute
- */
- protected void injectWorkflowMessages(CallbackSet callbacks, String program) {
-
- String[] cmds = program.replaceAll("\\s+", "").split(",");
-
- for (String cmd : cmds) {
- String action = cmd;
- String modifier = "STD";
-
- if (cmd.contains(":")) {
- String[] parts = cmd.split(":");
- action = parts[0];
- modifier = parts[1];
- }
-
- String messageType = null;
- String content = null;
- String contentType = null;
-
- if ("STD".equals(modifier)) {
- CallbackData callbackData = callbacks.get(action);
-
- if (callbackData == null) {
- String msg = "No '" + action + "' workflow message callback is defined";
- logger.debug(msg);
- fail(msg);
- }
-
- messageType = callbackData.getMessageType();
-
- if (messageType == null || messageType.trim().equals("")) {
- String msg = "No workflow message type is defined in the '" + action + "' callback";
- logger.debug(msg);
- fail(msg);
- }
-
- content = callbackData.getContent();
- contentType = callbackData.getContentType();
- } else {
- String msg = "Invalid workflow message program modifier: '" + modifier + "'";
- logger.debug(msg);
- fail(msg);
- }
-
- if (!injectWorkflowMessage(contentType, messageType, content, 10000)) {
- fail("Failed to inject '" + action + "' workflow message");
- }
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- fail("Interrupted after injection of '" + action + "' workflow message");
- }
- }
- }
-
- /**
- * Injects a workflow message. The specified callback data may contain the
- * placeholder string ((CORRELATOR)) which is replaced with the actual
- * correlator value.
- * @param contentType the HTTP contentType for the message (possibly null)
- * @param messageType the message type
- * @param content the message content (possibly null)
- * @param timeout the timeout in milliseconds
- * @return true if the message could be injected, false otherwise
- */
- protected boolean injectWorkflowMessage(String contentType, String messageType, String content, long timeout) {
- String correlator = (String) getProcessVariable("ReceiveWorkflowMessage",
- messageType + "_CORRELATOR", timeout);
-
- if (correlator == null) {
- return false;
- }
-
- if (content != null) {
- content = content.replace("((CORRELATOR))", correlator);
- }
-
- logger.debug("Injecting " + messageType + " message");
-
- Response response = workflowMessageResource.deliver(contentType, messageType, correlator, content);
- logger.debug("Workflow response to {} message: {}", messageType, response);
- return true;
- }
-
- /**
- * Runs a program to inject sniro workflow messages into the test environment.
- * A program is essentially just a list of keys that identify event data
- * to be injected, in sequence. For more details, see
- * injectSNIROCallbacks(String contentType, String messageType, String content, long timeout)
- *
- * Errors are handled with junit assertions and will cause the test to fail.
- * NOTE: Each callback must have a workflow message type associated with it.
- *
- * @param callbacks an object containing event data for the program
- * @param program the program to execute
- */
- protected void injectSNIROCallbacks(CallbackSet callbacks, String program) {
-
- String[] cmds = program.replaceAll("\\s+", "").split(",");
-
- for (String cmd : cmds) {
- String action = cmd;
- String modifier = "STD";
-
- if (cmd.contains(":")) {
- String[] parts = cmd.split(":");
- action = parts[0];
- modifier = parts[1];
- }
-
- String messageType = null;
- String content = null;
- String contentType = null;
-
- if ("STD".equals(modifier)) {
- CallbackData callbackData = callbacks.get(action);
-
- if (callbackData == null) {
- String msg = "No '" + action + "' workflow message callback is defined";
- logger.debug(msg);
- fail(msg);
- }
-
- messageType = callbackData.getMessageType();
-
- if (messageType == null || messageType.trim().equals("")) {
- String msg = "No workflow message type is defined in the '" + action + "' callback";
- logger.debug(msg);
- fail(msg);
- }
-
- content = callbackData.getContent();
- contentType = callbackData.getContentType();
- } else {
- String msg = "Invalid workflow message program modifier: '" + modifier + "'";
- logger.debug(msg);
- fail(msg);
- }
-
- if (!injectSNIROCallbacks(contentType, messageType, content, 10000)) {
- fail("Failed to inject '" + action + "' workflow message");
- }
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- fail("Interrupted after injection of '" + action + "' workflow message");
- }
- }
- }
-
- /**
- * Injects a sniro workflow message. The specified callback response may
- * contain the placeholder strings ((CORRELATOR)) and ((SERVICE_RESOURCE_ID))
- * The ((CORRELATOR)) is replaced with the actual correlator value from the
- * request. The ((SERVICE_RESOURCE_ID)) is replaced with the actual serviceResourceId
- * value from the sniro request. Currently this only works with sniro request
- * that contain only 1 resource.
- *
- * @param contentType the HTTP contentType for the message (possibly null)
- * @param messageType the message type
- * @param content the message content (possibly null)
- * @param timeout the timeout in milliseconds
- * @return true if the message could be injected, false otherwise
- */
- protected boolean injectSNIROCallbacks(String contentType, String messageType, String content, long timeout) {
- String correlator = (String) getProcessVariable("ReceiveWorkflowMessage",
- messageType + "_CORRELATOR", timeout);
-
- if (correlator == null) {
- return false;
- }
- if (content != null) {
- content = content.replace("((CORRELATOR))", correlator);
- if(messageType.equalsIgnoreCase("SNIROResponse")){
- ServiceDecomposition decomp = (ServiceDecomposition) getProcessVariable("Homing", "serviceDecomposition", timeout);
- List<Resource> resourceList = decomp.getServiceResources();
- if(resourceList.size() == 1){
- String resourceId = "";
- for(Resource resource:resourceList){
- resourceId = resource.getResourceId();
- }
- String homingList = getJsonValue(content, "solutionInfo.placementInfo");
- JSONArray placementArr = null;
- try {
- placementArr = new JSONArray(homingList);
- }
- catch (Exception e) {
- return false;
- }
- if(placementArr.length() == 1){
- content = content.replace("((SERVICE_RESOURCE_ID))", resourceId);
- }
- String licenseInfoList = getJsonValue(content, "solutionInfo.licenseInfo");
- JSONArray licenseArr = null;
- try {
- licenseArr = new JSONArray(licenseInfoList);
- }
- catch (Exception e) {
- return false;
- }
- if(licenseArr.length() == 1){
- content = content.replace("((SERVICE_RESOURCE_ID))", resourceId);
- }
- }
- else {
- try {
- String homingList = getJsonValue(content, "solutionInfo.placementInfo");
- String licenseInfoList = getJsonValue(content, "solutionInfo.licenseInfo");
- JSONArray placementArr = new JSONArray(homingList);
- JSONArray licenseArr = new JSONArray(licenseInfoList);
- for (Resource resource: resourceList) {
- String resourceModuleName = resource.getModelInfo().getModelInstanceName();
- String resourceId = resource.getResourceId();
-
- for (int i=0; i<placementArr.length(); i++) {
- JSONObject placementObj = placementArr.getJSONObject(i);
- String placementModuleName = placementObj.getString("resourceModuleName");
- if (placementModuleName.equalsIgnoreCase(resourceModuleName)) {
- String placementString = placementObj.toString();
- placementString = placementString.replace("((SERVICE_RESOURCE_ID))", resourceId);
- JSONObject newPlacementObj = new JSONObject(placementString);
- placementArr.put(i, newPlacementObj);
- }
- }
-
- for (int i=0; i<licenseArr.length(); i++) {
- JSONObject licenseObj = licenseArr.getJSONObject(i);
- String licenseModuleName = licenseObj.getString("resourceModuleName");
- if (licenseModuleName.equalsIgnoreCase(resourceModuleName)) {
- String licenseString = licenseObj.toString();
- licenseString = licenseString.replace("((SERVICE_RESOURCE_ID))", resourceId);
- JSONObject newLicenseObj = new JSONObject(licenseString);
- licenseArr.put(i, newLicenseObj);
- }
- }
- }
- String newPlacementInfos = placementArr.toString();
- String newLicenseInfos = licenseArr.toString();
- content = updJsonValue(content, "solutionInfo.placementInfo", newPlacementInfos);
- content = updJsonValue(content, "solutionInfo.licenseInfo", newLicenseInfos);
- }
- catch(Exception e) {
- return false;
- }
-
- }
- }
- }
- logger.debug("Injecting " + messageType + " message");
-
- Response response = workflowMessageResource.deliver(contentType, messageType, correlator, content);
- logger.debug("Workflow response to {} message: {}", messageType, response);
- return true;
- }
-
-
- /**
- * Wait for the process to end.
- * @param businessKey the process business key
- * @param timeout the amount of time to wait, in milliseconds
- */
- protected void waitForProcessEnd(String businessKey, long timeout) {
- logger.debug("Waiting {}ms for process with business key {} to end", timeout, businessKey);
-
- long now = System.currentTimeMillis() + timeout;
- long endTime = now + timeout;
-
- while (now <= endTime) {
- if (isProcessEnded(businessKey)) {
- logger.debug("Process with business key {} has ended", businessKey);
- return;
- }
-
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- String msg = "Interrupted waiting for process with business key " +
- businessKey + " to end";
- logger.debug(msg);
- fail(msg);
- }
-
- now = System.currentTimeMillis();
- }
-
- String msg = "Process with business key " + businessKey +
- " did not end within " + timeout + "ms";
- logger.debug(msg);
- fail(msg);
- }
-
- /**
- * Wait for the process to end. Must be used when multiple process instances exist with
- * this same business key such as when its passed to subflows or shared across multiple
- * processes.
- *
- * @param businessKey the process business key
- * @param processName the process definition name
- * @param timeout the amount of time to wait, in milliseconds
- * @author cb645j
- */
- protected void waitForProcessEnd(String businessKey, String processName, long timeout) {
- logger.debug("Waiting {}ms for process with business key {} to end", timeout, businessKey);
-
- long now = System.currentTimeMillis() + timeout;
- long endTime = now + timeout;
-
- while (now <= endTime) {
- if (isProcessEnded(businessKey, processName)) {
- logger.debug("Process with business key {} has ended", businessKey);
- return;
- }
-
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- String msg = "Interrupted waiting for process with business key " +
- businessKey + " to end";
- logger.debug(msg);
- fail(msg);
- }
-
- now = System.currentTimeMillis();
- }
-
- String msg = "Process with business key " + businessKey +
- " did not end within " + timeout + "ms";
- logger.debug(msg);
- fail(msg);
- }
-
- /**
- * Verifies that the specified historic process variable has the specified value.
- * If the variable does not have the specified value, the test is failed.
- *
- * @param businessKey the process business key
- * @param variable the variable name
- * @param value the expected variable value
- */
- protected void checkVariable(String businessKey, String variable, Object value) {
- if (!isProcessEnded(businessKey)) {
- fail("Cannot get historic variable " + variable + " because process with business key " +
- businessKey + " has not ended");
- }
-
- Object variableValue = getVariableFromHistory(businessKey, variable);
- assertEquals(value, variableValue);
- }
-
- /**
- * Checks to see if the specified process is ended.
- * @param businessKey the process business Key
- * @return true if the process is ended
- */
- protected boolean isProcessEnded(String businessKey) {
- HistoricProcessInstance processInstance = historyService
- .createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
- return processInstance != null && processInstance.getEndTime() != null;
- }
-
- /**
- * Checks to see if the specified process is ended.
- *
- * @param processInstanceId the process Instance Id
- * @return true if the process is ended
- */
- protected boolean isProcessEndedByProcessInstanceId(String processInstanceId) {
- HistoricProcessInstance processInstance = historyService
- .createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
- return processInstance != null && processInstance.getEndTime() != null;
- }
-
- /**
- * Checks to see if the specified process is ended.
- *
- * @author cb645j
- */
- //TODO combine into 1
- private boolean isProcessEnded(String businessKey, String processName) {
- HistoricProcessInstance processInstance = historyService
- .createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).processDefinitionName(processName).singleResult();
- return processInstance != null && processInstance.getEndTime() != null;
- }
-
- /**
- * Gets a variable value from a historical process instance. The business key must be unique.
- *
- * @param businessKey the process business key
- * @param variableName the variable name
- * @return the variable value or null if the variable does not exist
- */
- protected Object getVariableFromHistory(String businessKey, String variableName) {
- try {
- HistoricProcessInstance processInstance = historyService
- .createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
-
- if (processInstance == null) {
- return null;
- }
-
- HistoricVariableInstance v = historyService
- .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId())
- .variableName(variableName).singleResult();
- return v == null ? null : v.getValue();
- } catch (Exception e) {
- logger.debug("Error retrieving variable {} from historical process with business key {}: ", variableName, businessKey,
- e);
- return null;
- }
- }
-
- /**
- * Gets a variable value from a process instance based on businessKey and process name.
- * Must be used when multiple instances exist with the same business key such as when
- * business key is passed to subflows or shared across multiple processes. This method
- * can obtain variables from mainflows and from subflows.
- *
- * @param businessKey the process business key
- * @param processName the process definition name
- * @param variableName the variable name
- * @return the variable value or null if the variable does not exist
- * @author cb645j
- */
- protected Object getVariableFromHistory(String businessKey, String processName, String variableName){
- try{
- HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).processDefinitionName(processName)
- .singleResult();
-
- if(processInstance == null){
- return null;
- }
- HistoricVariableInstance variable = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).variableName(variableName).singleResult();
-
- return variable == null ? null : variable.getValue();
- }catch(ProcessEngineException e){
- logger.debug("Multiple proccess instances exist with process name {} and business key {}. Must pass instance "
- + "index as a parameter.", processName, businessKey);
- return null;
- }catch(Exception e){
- logger.debug("Error retrieving variable {} from historical process for process {} with business key {}: ",
- variableName, processName, businessKey, e);
- return null;
- }
- }
-
- /**
- * Gets the value of a process variable from x instance of y process. Must be used when
- * multiple instances exist with the same business key AND process name. This method
- * shall be used primarily for obtaining subflow variables when the business key is
- * passed to the subflow AND the subflow is called multiple times in a given flow.
- *
- * @param businessKey the process business key
- * @param processName the name of the subflow that contains the variable
- * @param variableName the variable name
- * @param processInstanceIndex the instance in which the subprocess was called
- * @return the variable value or null if the variable does not exist
- * @author cb645j
- */
- protected Object getVariableFromHistory(String businessKey, int subflowInstanceIndex, String processName, String variableName){
- try{
- List<HistoricProcessInstance> processInstanceList = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).processDefinitionName(processName)
- .list();
-
- if(processInstanceList == null){
- return null;
- }
- processInstanceList.sort((m1, m2) -> m1.getStartTime().compareTo(m2.getStartTime()));
-
- HistoricProcessInstance processInstance = processInstanceList.get(subflowInstanceIndex);
- HistoricVariableInstance variable = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId())
- .variableName(variableName).singleResult();
-
- return variable == null ? null : variable.getValue();
- }catch(Exception e) {
- logger.debug("Error retrieving variable {} from historical process for process {} with business key {}: ",
- variableName, processName, businessKey, e);
- return null;
- }
- }
-
-
- /**
- * Gets the value of a subflow variable from the specified subflow's
- * historical process instance.
- *
- * DEPRECATED - Use method getVariableFromHistory(businessKey, processName, variableName) instead
- *
- * @param subflowName - the name of the subflow that contains the variable
- * @param variableName the variable name
- *
- * @return the variable value, or null if the variable could not be obtained
- *
- */
- @Deprecated
- protected Object getVariableFromSubflowHistory(String subflowName, String variableName) {
- try {
- List<HistoricProcessInstance> processInstanceList = historyService
- .createHistoricProcessInstanceQuery().processDefinitionName(subflowName).list();
-
- if (processInstanceList == null) {
- return null;
- }
-
- processInstanceList.sort((m1, m2) -> m1.getStartTime().compareTo(m2.getStartTime()));
-
- HistoricProcessInstance processInstance = processInstanceList.get(0);
-
- HistoricVariableInstance v = historyService
- .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId())
- .variableName(variableName).singleResult();
- return v == null ? null : v.getValue();
- } catch (Exception e) {
- logger.debug("Error retrieving variable {} from sub flow: {}, Exception is: ", variableName, subflowName, e);
- return null;
- }
- }
-
- /**
- * Gets the value of a subflow variable from the subflow's
- * historical process x instance.
- *
- * DEPRECATED: Use method getVariableFromHistory(businessKey, processInstanceIndex, processName, variableName) instead
- *
- * @param subflowName - the name of the subflow that contains the variable
- * @param variableName the variable name
- * @param subflowInstanceIndex - the instance of the subflow (use when same subflow is called more than once from mainflow)
- *
- * @return the variable value, or null if the variable could not be obtained
- */
- @Deprecated
- protected Object getVariableFromSubflowHistory(int subflowInstanceIndex, String subflowName, String variableName) {
- try {
- List<HistoricProcessInstance> processInstanceList = historyService.createHistoricProcessInstanceQuery().processDefinitionName(subflowName).list();
-
- if (processInstanceList == null) {
- return null;
- }
-
- processInstanceList.sort((m1, m2) -> m1.getStartTime().compareTo(m2.getStartTime()));
-
- HistoricProcessInstance processInstance = processInstanceList.get(subflowInstanceIndex);
-
- HistoricVariableInstance v = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId())
- .variableName(variableName).singleResult();
- return v == null ? null : v.getValue();
- } catch (Exception e) {
- logger.debug("Error retrieving variable {} from {} instance index of sub flow: {}, Exception is: ", variableName,
- subflowInstanceIndex, subflowName, e);
- return null;
- }
- }
-
- /**
- * Extracts text from an XML element. This method is not namespace aware
- * (namespaces are ignored). The first matching element is selected.
- * @param xml the XML document or fragment
- * @param tag the desired element, e.g. "<name>"
- * @return the element text, or null if the element was not found
- */
- protected String getXMLTextElement(String xml, String tag) {
- xml = removeXMLNamespaces(xml);
-
- if (!tag.startsWith("<")) {
- tag = "<" + tag + ">";
- }
-
- int start = xml.indexOf(tag);
-
- if (start == -1) {
- return null;
- }
-
- int end = xml.indexOf('<', start + tag.length());
-
- if (end == -1) {
- return null;
- }
-
- return xml.substring(start + tag.length(), end);
- }
-
- /**
- * Removes namespace definitions and prefixes from XML, if any.
- */
- private String removeXMLNamespaces(String xml) {
- // remove xmlns declaration
- xml = xml.replaceAll("xmlns.*?(\"|\').*?(\"|\')", "");
-
- // remove opening tag prefix
- xml = xml.replaceAll("(<)(\\w+:)(.*?>)", "$1$3");
-
- // remove closing tags prefix
- xml = xml.replaceAll("(</)(\\w+:)(.*?>)", "$1$3");
-
- // remove extra spaces left when xmlns declarations are removed
- xml = xml.replaceAll("\\s+>", ">");
-
- return xml;
- }
-
- /**
- * Asserts that two XML documents are semantically equivalent. Differences
- * in whitespace or in namespace usage do not affect the comparison.
- * @param expected the expected XML
- * @param actual the XML to test
- * @throws SAXException
- * @throws IOException
- */
- public static void assertXMLEquals(String expected, String actual)
- throws SAXException, IOException {
- XMLUnit.setIgnoreWhitespace(true);
- XMLUnit.setIgnoreAttributeOrder(true);
- DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expected, actual));
- List<?> allDifferences = diff.getAllDifferences();
- assertEquals("Differences found: " + diff.toString(), 0, allDifferences.size());
+ private static final Logger logger = LoggerFactory.getLogger(WorkflowTest.class);
+
+ // TODO this is not used anymore, can maybe be removed
+ @Rule
+ public ProcessEngineRule processEngineRule;
+
+ @Autowired
+ protected WorkflowResource workflowResourceSync;
+
+ @Autowired
+ protected ProcessEngine processEngine;
+
+ @Autowired
+ protected RuntimeService runtimeService;
+
+ @Autowired
+ protected HistoryService historyService;
+
+ @Autowired
+ private WorkflowAsyncResource workflowResource;
+
+ @Autowired
+ private WorkflowMessageResource workflowMessageResource;
+
+ @Autowired
+ SDNCAdapterCallbackServiceImpl callbackService;
+ /**
+ * Content-Type for XML.
+ */
+ protected static final String XML = "application/xml";
+
+ /**
+ * Content-Type for JSON.
+ */
+ protected static final String JSON = "application/json; charset=UTF-8";
+
+ private static final int timeout = 2000;
+
+ /**
+ * Constructor.
+ */
+ public WorkflowTest() throws RuntimeException {}
+
+ /**
+ * The current request ID. Normally set when an "invoke" method is called.
+ */
+ protected volatile String msoRequestId = null;
+
+ /**
+ * The current service instance ID. Normally set when an "invoke" method is called.
+ */
+ protected volatile String msoServiceInstanceId = null;
+
+ /**
+ * Logs a test start method.
+ */
+ protected void logStart() {
+ logger.debug("STARTED TEST");
+ }
+
+ /**
+ * Logs a test end method.
+ */
+ protected void logEnd() {
+ logger.debug("ENDED TEST");
+ }
+
+ /**
+ * Invokes a subprocess.
+ *
+ * @param processKey the process key
+ * @param businessKey a unique key that will identify the process instance
+ * @param injectedVariables variables to inject into the process
+ */
+ protected void invokeSubProcess(String processKey, String businessKey, Map<String, Object> injectedVariables) {
+ RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
+ List<String> arguments = runtimeMxBean.getInputArguments();
+ logger.debug("JVM args = {}", arguments);
+
+ msoRequestId = (String) injectedVariables.get("mso-request-id");
+ String requestId = (String) injectedVariables.get("msoRequestId");
+
+ if (msoRequestId == null && requestId == null) {
+ String msg = "mso-request-id variable was not provided";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ // Note: some scenarios don't have a service-instance-id, may be null
+ msoServiceInstanceId = (String) injectedVariables.get("mso-service-instance-id");
+
+
+ runtimeService.startProcessInstanceByKey(processKey, businessKey, injectedVariables);
+ }
+
+ protected String invokeSubProcess(String processKey, Map<String, Object> injectedVariables) {
+ RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
+ List<String> arguments = runtimeMxBean.getInputArguments();
+ logger.debug("JVM args = {}", arguments);
+
+ msoRequestId = (String) injectedVariables.get("mso-request-id");
+ String requestId = (String) injectedVariables.get("msoRequestId");
+
+ if (msoRequestId == null && requestId == null) {
+ String msg = "mso-request-id variable was not provided";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ // Note: some scenarios don't have a service-instance-id, may be null
+ msoServiceInstanceId = (String) injectedVariables.get("mso-service-instance-id");
+
+
+ ProcessInstance processInstance =
+ runtimeService.startProcessInstanceByKey(processKey, msoRequestId, injectedVariables);
+ return processInstance.getId();
+ }
+
+ /**
+ * Invokes an asynchronous process. Errors are handled with junit assertions and will cause the test to fail.
+ *
+ * @param processKey the process key
+ * @param schemaVersion the API schema version, e.g. "v1"
+ * @param businessKey a unique key that will identify the process instance
+ * @param request the request
+ * @return a TestAsyncResponse object associated with the test
+ * @throws InterruptedException
+ */
+ protected TestAsyncResponse invokeAsyncProcess(String processKey, String schemaVersion, String businessKey,
+ String request) throws InterruptedException {
+ return invokeAsyncProcess(processKey, schemaVersion, businessKey, request, null);
+ }
+
+ /**
+ * Invokes an asynchronous process. Errors are handled with junit assertions and will cause the test to fail.
+ *
+ * @param processKey the process key
+ * @param schemaVersion the API schema version, e.g. "v1"
+ * @param businessKey a unique key that will identify the process instance
+ * @param request the request
+ * @param injectedVariables optional variables to inject into the process
+ * @return a TestAsyncResponse object associated with the test
+ * @throws InterruptedException
+ */
+ protected TestAsyncResponse invokeAsyncProcess(String processKey, String schemaVersion, String businessKey,
+ String request, Map<String, Object> injectedVariables) {
+
+ RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
+ List<String> arguments = runtimeMxBean.getInputArguments();
+ logger.debug("JVM args = {}", arguments);
+
+ Map<String, Object> variables = createVariables(schemaVersion, businessKey, request, injectedVariables, false);
+ VariableMapImpl variableMapImpl = createVariableMapImpl(variables);
+
+ logger.debug("Sending {} to {} process", request, processKey);
+
+ TestAsyncResponse asyncResponse = new TestAsyncResponse();
+
+ asyncResponse.setResponse(workflowResource.startProcessInstanceByKey(processKey, variableMapImpl));
+
+ return asyncResponse;
+ }
+
+ /**
+ * Invokes an asynchronous process. Errors are handled with junit assertions and will cause the test to fail.
+ *
+ * @param processKey the process key
+ * @param schemaVersion the API schema version, e.g. "v1"
+ * @param businessKey a unique key that will identify the process instance
+ * @param request the request
+ * @param injectedVariables optional variables to inject into the process
+ * @param serviceInstantiationModel indicates whether this method is being invoked for a flow that is designed using
+ * the service instantiation model
+ * @return a TestAsyncResponse object associated with the test
+ * @throws InterruptedException
+ */
+ protected Response invokeAsyncProcess(String processKey, String schemaVersion, String businessKey, String request,
+ Map<String, Object> injectedVariables, boolean serviceInstantiationModel) {
+
+ RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
+ List<String> arguments = runtimeMxBean.getInputArguments();
+ logger.debug("JVM args = {}", arguments);
+
+ Map<String, Object> variables =
+ createVariables(schemaVersion, businessKey, request, injectedVariables, serviceInstantiationModel);
+ VariableMapImpl variableMapImpl = createVariableMapImpl(variables);
+
+ logger.debug("Sending {} to {} process", request, processKey);
+
+ return workflowResource.startProcessInstanceByKey(processKey, variableMapImpl);
+
+ }
+
+ /**
+ * Private helper method that creates a variable map for a request. Errors are handled with junit assertions and
+ * will cause the test to fail.
+ *
+ * @param schemaVersion the API schema version, e.g. "v1"
+ * @param businessKey a unique key that will identify the process instance
+ * @param request the request
+ * @param injectedVariables optional variables to inject into the process
+ * @param serviceInstantiationModel indicates whether this method is being invoked for a flow that is designed using
+ * the service instantiation model
+ * @return a variable map
+ */
+ private Map<String, Object> createVariables(String schemaVersion, String businessKey, String request,
+ Map<String, Object> injectedVariables, boolean serviceInstantiationModel) {
+
+ Map<String, Object> variables = new HashMap<>();
+
+ // These variables may be overridded by injected variables.
+ variables.put("mso-service-request-timeout", "180");
+ variables.put("isDebugLogEnabled", "true");
+
+ // These variables may not be overridded by injected variables.
+ String[] notAllowed = new String[] {"mso-schema-version", "mso-business-key", "bpmnRequest", "mso-request-id",
+ "mso-service-instance-id"};
+
+ if (injectedVariables != null) {
+ for (String key : injectedVariables.keySet()) {
+ for (String var : notAllowed) {
+ if (var.equals(key)) {
+ String msg = "Cannot specify " + var + " in injected variables";
+ logger.debug(msg);
+ fail(msg);
+ }
+ }
+
+ variables.put(key, injectedVariables.get(key));
+ }
+ }
+
+ variables.put("mso-schema-version", schemaVersion);
+ variables.put("mso-business-key", businessKey);
+ variables.put("bpmnRequest", request);
+
+ if (serviceInstantiationModel) {
+
+ /*
+ * The request ID and the service instance ID are generated for flows that follow the service instantiation
+ * model unless "requestId" and "serviceInstanceId" are injected variables.
+ */
+
+ try {
+ msoRequestId = (String) injectedVariables.get("requestId");
+ variables.put("mso-request-id", msoRequestId);
+ msoServiceInstanceId = (String) injectedVariables.get("serviceInstanceId");
+ variables.put("mso-service-instance-id", msoServiceInstanceId);
+ } catch (Exception e) {
+ }
+ if (msoRequestId == null || msoRequestId.trim().equals("")) {
+ logger.debug("No requestId element in injectedVariables");
+ variables.put("mso-request-id", UUID.randomUUID().toString());
+ }
+ if (msoServiceInstanceId == null || msoServiceInstanceId.trim().equals("")) {
+ logger.debug("No seviceInstanceId element in injectedVariables");
+ variables.put("mso-service-instance-id", UUID.randomUUID().toString());
+ }
+
+ } else {
+ msoRequestId = getXMLTextElement(request, "request-id");
+
+ if (msoRequestId == null) {
+ // check in injected variables
+ try {
+ msoRequestId = (String) injectedVariables.get("requestId");
+ } catch (Exception e) {
+ }
+ if (msoRequestId == null || msoRequestId.trim().equals("")) {
+ String msg = "No request-id element in " + request;
+ logger.debug(msg);
+ fail(msg);
+ }
+ }
+
+ variables.put("mso-request-id", msoRequestId);
+
+ // Note: some request types don't have a service-instance-id
+ msoServiceInstanceId = getXMLTextElement(request, "service-instance-id");
+
+ if (msoServiceInstanceId != null) {
+ variables.put("mso-service-instance-id", msoServiceInstanceId);
+ }
+ }
+
+ return variables;
+ }
+
+ /**
+ * Private helper method that creates a camunda VariableMapImpl from a simple variable map.
+ *
+ * @param variables the simple variable map
+ * @return a VariableMap
+ */
+ private VariableMapImpl createVariableMapImpl(Map<String, Object> variables) {
+ Map<String, Object> wrappedVariables = new HashMap<>();
+
+ for (String key : variables.keySet()) {
+ Object value = variables.get(key);
+ wrappedVariables.put(key, wrapVariableValue(value));
+ }
+
+ VariableMapImpl variableMapImpl = new VariableMapImpl();
+ variableMapImpl.put("variables", wrappedVariables);
+ return variableMapImpl;
+ }
+
+ /**
+ * Private helper method that wraps a variable value for inclusion in a camunda VariableMapImpl.
+ *
+ * @param value the variable value
+ * @return the wrapped variable
+ */
+ private Map<String, Object> wrapVariableValue(Object value) {
+ HashMap<String, Object> valueMap = new HashMap<>();
+ valueMap.put("value", value);
+ return valueMap;
+ }
+
+ /**
+ * Receives a response from an asynchronous process. Errors are handled with junit assertions and will cause the
+ * test to fail.
+ *
+ * @param businessKey the process business key
+ * @param asyncResponse the TestAsyncResponse object associated with the test
+ * @param timeout the timeout in milliseconds
+ * @return the WorkflowResponse
+ */
+ protected WorkflowResponse receiveResponse(String businessKey, TestAsyncResponse asyncResponse, long timeout) {
+ logger.debug("Waiting {}ms for process with business key {} to send a response", timeout, businessKey);
+
+ long now = System.currentTimeMillis() + timeout;
+ long endTime = now + timeout;
+
+ while (now <= endTime) {
+ Response response = asyncResponse.getResponse();
+
+ if (response != null) {
+ logger.debug("Received a response from process with business key {}", businessKey);
+
+ Object entity = response.getEntity();
+
+ if (!(entity instanceof WorkflowResponse)) {
+ String msg = "Response entity is " + (entity == null ? "null" : entity.getClass().getName())
+ + ", expected WorkflowResponse";
+ logger.debug(msg);
+ fail(msg);
+ return null; // unreachable
+ }
+
+ return (WorkflowResponse) entity;
+ }
+
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ String msg = "Interrupted waiting for a response from process with business key " + businessKey;
+ logger.debug(msg);
+ fail(msg);
+ return null; // unreachable
+ }
+
+ now = System.currentTimeMillis();
+ }
+
+ String msg = "No response received from process with business key " + businessKey + " within " + timeout + "ms";
+ logger.debug(msg);
+ fail("Process with business key " + businessKey + " did not end within 10000ms");
+ return null; // unreachable
+ }
+
+ /**
+ * Runs a program to inject SDNC callback data into the test environment. A program is essentially just a list of
+ * keys that identify callback data to be injected, in sequence. An example program:
+ *
+ * <pre>
+ * reserve, assign, delete:ERR
+ * </pre>
+ *
+ * Errors are handled with junit assertions and will cause the test to fail.
+ *
+ * @param callbacks an object containing callback data for the program
+ * @param program the program to execute
+ */
+ protected void injectSDNCRestCallbacks(CallbackSet callbacks, String program) {
+
+ String[] cmds = program.replaceAll("\\s+", "").split(",");
+
+ for (String cmd : cmds) {
+ String action = cmd;
+ String modifier = "STD";
+
+ if (cmd.contains(":")) {
+ String[] parts = cmd.split(":");
+ action = parts[0];
+ modifier = parts[1];
+ }
+
+ String content = null;
+ String contentType = null;
+
+ if ("STD".equals(modifier)) {
+ CallbackData callbackData = callbacks.get(action);
+
+ if (callbackData == null) {
+ String msg = "No callback defined for '" + action + "' SDNC request";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ content = callbackData.getContent();
+ contentType = callbackData.getContentType();
+ } else if ("ERR".equals(modifier)) {
+ content =
+ "{\"SDNCServiceError\":{\"sdncRequestId\":\"((REQUEST-ID))\",\"responseCode\":\"500\",\"responseMessage\":\"SIMULATED ERROR FROM SDNC ADAPTER\",\"ackFinalIndicator\":\"Y\"}}";
+ contentType = JSON;
+ } else {
+ String msg = "Invalid SDNC program modifier: '" + modifier + "'";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ if (contentType == null) {
+ // Default for backward compatibility with existing tests.
+ contentType = JSON;
+ }
+
+ if (!injectSDNCRestCallback(contentType, content, 10000)) {
+ fail("Failed to inject SDNC '" + action + "' callback");
+ }
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ fail("Interrupted after injection of SDNC '" + action + "' callback");
+ }
+ }
+ }
+
+ /**
+ * Runs a program to inject SDNC events into the test environment. A program is essentially just a list of keys that
+ * identify event data to be injected, in sequence. An example program:
+ *
+ * <pre>
+ * event1, event2
+ * </pre>
+ *
+ * NOTE: Each callback must have a message type associated with it, e.g. "SDNCAEvent". Errors are handled with junit
+ * assertions and will cause the test to fail.
+ *
+ * @param callbacks an object containing event data for the program
+ * @param program the program to execute
+ */
+ protected void injectSDNCEvents(CallbackSet callbacks, String program) {
+ injectWorkflowMessages(callbacks, program);
+ }
+
+ /**
+ * Runs a program to inject SDNC callback data into the test environment. A program is essentially just a list of
+ * keys that identify callback data to be injected, in sequence. An example program:
+ *
+ * <pre>
+ * reserve, assign, delete:ERR
+ * </pre>
+ *
+ * Errors are handled with junit assertions and will cause the test to fail. Uses the static/default timeout value
+ * for backward compatibility.
+ *
+ * @param callbacks an object containing callback data for the program
+ * @param program the program to execute
+ */
+ protected void injectSDNCCallbacks(CallbackSet callbacks, String program) {
+ injectSDNCCallbacks(callbacks, program, timeout);
+ }
+
+ /**
+ * Runs a program to inject SDNC callback data into the test environment. A program is essentially just a list of
+ * keys that identify callback data to be injected, in sequence. An example program:
+ *
+ * <pre>
+ * reserve, assign, delete:ERR
+ * </pre>
+ *
+ * Errors are handled with junit assertions and will cause the test to fail.
+ *
+ * @param callbacks an object containing callback data for the program
+ * @param program the program to execute
+ * @param timeout a timeout value to wait for the callback
+ */
+ protected void injectSDNCCallbacks(CallbackSet callbacks, String program, int timeout) {
+
+ String[] cmds = program.replaceAll("\\s+", "").split(",");
+
+ for (String cmd : cmds) {
+ String action = cmd;
+ String modifier = "STD";
+
+ if (cmd.contains(":")) {
+ String[] parts = cmd.split(":");
+ action = parts[0];
+ modifier = parts[1];
+ }
+
+ String content = null;
+ int respCode = 200;
+ String respMsg = "OK";
+
+ if ("STD".equals(modifier)) {
+ CallbackData callbackData = callbacks.get(action);
+
+ if (callbackData == null) {
+ String msg = "No callback defined for '" + action + "' SDNC request";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ content = callbackData.getContent();
+ respCode = 200;
+ respMsg = "OK";
+ } else if ("CREATED".equals(modifier)) {
+ CallbackData callbackData = callbacks.get(action);
+
+ if (callbackData == null) {
+ String msg = "No callback defined for '" + action + "' SDNC request";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ content = callbackData.getContent();
+ respCode = 201;
+ respMsg = "Created";
+ } else if ("ERR".equals(modifier)) {
+ content =
+ "<svc-request-id>((REQUEST-ID))</svc-request-id><response-code>500</response-code><response-message>SIMULATED ERROR FROM SDNC ADAPTER</response-message>";
+ respCode = 500;
+ respMsg = "SERVER ERROR";
+ } else {
+ String msg = "Invalid SDNC program modifier: '" + modifier + "'";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ if (!injectSDNCCallback(respCode, respMsg, content, 10000)) {
+ fail("Failed to inject SDNC '" + action + "' callback");
+ }
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ fail("Interrupted after injection of SDNC '" + action + "' callback");
+ }
+ }
+ }
+
+ /**
+ * Runs a program to inject VNF adapter REST callback data into the test environment. A program is essentially just
+ * a list of keys that identify callback data to be injected, in sequence. An example program:
+ *
+ * <pre>
+ * create, rollback
+ * </pre>
+ *
+ * Errors are handled with junit assertions and will cause the test to fail.
+ *
+ * @param callbacks an object containing callback data for the program
+ * @param program the program to execute
+ */
+ protected void injectVNFRestCallbacks(CallbackSet callbacks, String program) {
+
+ String[] cmds = program.replaceAll("\\s+", "").split(",");
+
+ for (String cmd : cmds) {
+ String action = cmd;
+ String modifier = "STD";
+
+ if (cmd.contains(":")) {
+ String[] parts = cmd.split(":");
+ action = parts[0];
+ modifier = parts[1];
+ }
+
+ String content = null;
+ String contentType = null;
+
+ if ("STD".equals(modifier)) {
+ CallbackData callbackData = callbacks.get(action);
+
+ if (callbackData == null) {
+ String msg = "No callback defined for '" + action + "' VNF REST request";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ content = callbackData.getContent();
+ contentType = callbackData.getContentType();
+ } else if ("ERR".equals(modifier)) {
+ content = "SIMULATED ERROR FROM VNF ADAPTER";
+ contentType = "text/plain";
+ } else {
+ String msg = "Invalid VNF REST program modifier: '" + modifier + "'";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ if (contentType == null) {
+ // Default for backward compatibility with existing tests.
+ contentType = XML;
+ }
+
+ if (!injectVnfAdapterRestCallback(contentType, content, 10000)) {
+ fail("Failed to inject VNF REST '" + action + "' callback");
+ }
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ fail("Interrupted after injection of VNF REST '" + action + "' callback");
+ }
+ }
+ }
+
+ /**
+ * Runs a program to inject VNF callback data into the test environment. A program is essentially just a list of
+ * keys that identify callback data to be injected, in sequence. An example program:
+ *
+ * <pre>
+ * createVnf, deleteVnf
+ * </pre>
+ *
+ * Errors are handled with junit assertions and will cause the test to fail.
+ *
+ * @param callbacks an object containing callback data for the program
+ * @param program the program to execute
+ */
+ protected void injectVNFCallbacks(CallbackSet callbacks, String program) {
+
+ String[] cmds = program.replaceAll("\\s+", "").split(",");
+
+ for (String cmd : cmds) {
+ String action = cmd;
+ String modifier = "STD";
+
+ if (cmd.contains(":")) {
+ String[] parts = cmd.split(":");
+ action = parts[0];
+ modifier = parts[1];
+ }
+
+ String content = null;
+
+ if ("STD".equals(modifier)) {
+ CallbackData callbackData = callbacks.get(action);
+
+ if (callbackData == null) {
+ String msg = "No callback defined for '" + action + "' VNF request";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ content = callbackData.getContent();
+ } else if ("ERR".equals(modifier)) {
+ String msg = "Currently unsupported VNF program modifier: '" + modifier + "'";
+ logger.debug(msg);
+ fail(msg);
+ } else {
+ String msg = "Invalid VNF program modifier: '" + modifier + "'";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ boolean injected = false;
+
+ if (content.contains("createVnfNotification")) {
+ injected = injectCreateVNFCallback(content, 10000);
+ } else if (content.contains("deleteVnfNotification")) {
+ injected = injectDeleteVNFCallback(content, 10000);
+ } else if (content.contains("updateVnfNotification")) {
+ injected = injectUpdateVNFCallback(content, 10000);
+ }
+
+ if (!injected) {
+ String msg = "Failed to inject VNF '" + action + "' callback";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ fail("Interrupted after injection of VNF '" + action + "' callback");
+ }
+ }
+ }
+
+ /**
+ * Waits for the number of running processes with the specified process definition key to equal a particular count.
+ *
+ * @param processKey the process definition key
+ * @param count the desired count
+ * @param timeout the timeout in milliseconds
+ */
+ protected void waitForRunningProcessCount(String processKey, int count, long timeout) {
+ logger.debug("Waiting {}ms for there to be {} {} instances", timeout, count, processKey);
+
+ long now = System.currentTimeMillis() + timeout;
+ long endTime = now + timeout;
+ int last = -1;
+
+ while (now <= endTime) {
+ int actual = runtimeService.createProcessInstanceQuery().processDefinitionKey(processKey).list().size();
+
+ if (actual != last) {
+ logger.debug("There are now {} {} instances", actual, processKey);
+ last = actual;
+ }
+
+ if (actual == count) {
+ return;
+ }
+
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ String msg = "Interrupted waiting for there to be " + count + " " + processKey + " instances";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ now = System.currentTimeMillis();
+ }
+
+ String msg = "Timed out waiting for there to be " + count + " " + processKey + " instances";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ /**
+ * Waits for the specified process variable to be set.
+ *
+ * @param processKey the process definition key
+ * @param variable the variable name
+ * @param timeout the timeout in milliseconds
+ * @return the variable value, or null if it cannot be obtained in the specified time
+ */
+ protected Object getProcessVariable(String processKey, String variable, long timeout) {
+
+ logger.debug("Waiting " + timeout + "ms for " + processKey + "." + variable + " to be set");
+
+ long now = System.currentTimeMillis() + timeout;
+ long endTime = now + timeout;
+
+ ProcessInstance processInstance = null;
+ Object value = null;
+
+ while (value == null) {
+ if (now > endTime) {
+ if (processInstance == null) {
+ logger.debug("Timed out waiting for " + processKey + " to start");
+ } else {
+ logger.debug("Timed out waiting for " + processKey + "[" + processInstance.getId() + "]." + variable
+ + " to be set");
+ }
+
+ return null;
+ }
+
+ ProcessInstanceQuery processInstanceQuery = null;
+ if (processInstance == null) {
+ processInstanceQuery = runtimeService.createProcessInstanceQuery().processDefinitionKey(processKey);
+ }
+
+ if (processInstanceQuery.count() == 1 || processInstanceQuery.count() == 0) {
+ processInstance = processInstanceQuery.singleResult();
+ } else {
+ // TODO There shouldnt be more than one in the list but seems to be happening, need to figure out why
+ // happening and best way to get correct one from list
+ logger.debug("Process Instance Query returned {} instance. Getting the last instance in the list",
+ processInstanceQuery.count());
+ List<ProcessInstance> processList = processInstanceQuery.list();
+ processInstance = processList.get((processList.size() - 1));
+ }
+
+
+ if (processInstance != null) {
+ value = runtimeService.getVariable(processInstance.getId(), variable);
+ }
+
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ logger.debug("Interrupted waiting for {}.{} to be set", processKey, variable);
+ return null;
+ }
+
+ now = System.currentTimeMillis();
+ }
+
+ logger.debug(processKey + "[" + processInstance.getId() + "]." + variable + "=" + value);
+
+ return value;
+ }
+
+ /**
+ * Injects a single SDNC adapter callback request. The specified callback data may contain the placeholder string
+ * ((REQUEST-ID)) which is replaced with the actual SDNC request ID. Note: this is not the requestId in the original
+ * MSO request.
+ *
+ * @param contentType the HTTP content type for the callback
+ * @param content the content of the callback
+ * @param timeout the timeout in milliseconds
+ * @return true if the callback could be injected, false otherwise
+ */
+ protected boolean injectSDNCRestCallback(String contentType, String content, long timeout) {
+ String sdncRequestId = (String) getProcessVariable("SDNCAdapterRestV1", "SDNCAResponse_CORRELATOR", timeout);
+
+ if (sdncRequestId == null) {
+ sdncRequestId = (String) getProcessVariable("SDNCAdapterRestV2", "SDNCAResponse_CORRELATOR", timeout);
+ }
+
+ if (sdncRequestId == null) {
+ return false;
+ }
+
+ content = content.replace("((REQUEST-ID))", sdncRequestId);
+ // Deprecated usage. All test code should switch to the (( ... )) syntax.
+ content = content.replace("{{REQUEST-ID}}", sdncRequestId);
+
+ logger.debug("Injecting SDNC adapter callback");
+
+ Response response = workflowMessageResource.deliver(contentType, "SDNCAResponse", sdncRequestId, content);
+ logger.debug("Workflow response to SDNC adapter callback: " + response);
+ return true;
+ }
+
+ /**
+ * Injects a single SDNC adapter callback request. The specified callback data may contain the placeholder string
+ * ((REQUEST-ID)) which is replaced with the actual SDNC request ID. Note: this is not the requestId in the original
+ * MSO request.
+ *
+ * @param content the content of the callback
+ * @param respCode the response code (normally 200)
+ * @param respMsg the response message (normally "OK")
+ * @param timeout the timeout in milliseconds
+ * @return true if the callback could be injected, false otherwise
+ */
+ protected boolean injectSDNCCallback(int respCode, String respMsg, String content, long timeout) {
+
+ String sdncRequestId = (String) getProcessVariable("sdncAdapter", "SDNCA_requestId", timeout);
+
+ if (sdncRequestId == null) {
+ return false;
+ }
+
+ content = content.replace("((REQUEST-ID))", sdncRequestId);
+ // Deprecated usage. All test code should switch to the (( ... )) syntax.
+ content = content.replace("{{REQUEST-ID}}", sdncRequestId);
+
+ // TODO this needs to be fixed. It is causing double tags and content
+ // Need to parse content before setting below since content includes not just RequestData or modify callback
+ // files to only contain RequestData contents.
+
+ logger.debug("Injecting SDNC adapter callback");
+ CallbackHeader callbackHeader = new CallbackHeader();
+ callbackHeader.setRequestId(sdncRequestId);
+ callbackHeader.setResponseCode(String.valueOf(respCode));
+ callbackHeader.setResponseMessage(respMsg);
+ SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest();
+ sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader);
+ sdncAdapterCallbackRequest.setRequestData(content);
+ SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest);
+ logger.debug("Workflow response to SDNC adapter callback: " + sdncAdapterResponse);
+
+ return true;
+ }
+
+ /**
+ * Injects a single VNF adapter callback request. The specified callback data may contain the placeholder string
+ * ((MESSAGE-ID)) which is replaced with the actual message ID. Note: this is not the requestId in the original MSO
+ * request.
+ *
+ * @param contentType the HTTP content type for the callback
+ * @param content the content of the callback
+ * @param timeout the timeout in milliseconds
+ * @return true if the callback could be injected, false otherwise
+ */
+ protected boolean injectVnfAdapterRestCallback(String contentType, String content, long timeout) {
+ String messageId = (String) getProcessVariable("vnfAdapterRestV1", "VNFAResponse_CORRELATOR", timeout);
+
+ if (messageId == null) {
+ return false;
+ }
+
+ content = content.replace("((MESSAGE-ID))", messageId);
+ // Deprecated usage. All test code should switch to the (( ... )) syntax.
+ content = content.replace("{{MESSAGE-ID}}", messageId);
+
+ logger.debug("Injecting VNF adapter callback");
+
+ Response response = workflowMessageResource.deliver(contentType, "VNFAResponse", messageId, content);
+ logger.debug("Workflow response to VNF adapter callback: {}", response);
+ return true;
+ }
+
+ /**
+ * Injects a Create VNF adapter callback request. The specified callback data may contain the placeholder string
+ * ((MESSAGE-ID)) which is replaced with the actual message ID. It may also contain the placeholder string
+ * ((REQUEST-ID)) which is replaced request ID of the original MSO request.
+ *
+ * @param content the content of the callback
+ * @param timeout the timeout in milliseconds
+ * @return true if the callback could be injected, false otherwise
+ * @throws JAXBException if the content does not adhere to the schema
+ */
+ protected boolean injectCreateVNFCallback(String content, long timeout) {
+
+ String messageId = (String) getProcessVariable("vnfAdapterCreateV1", "VNFC_messageId", timeout);
+
+ if (messageId == null) {
+ return false;
+ }
+
+ content = content.replace("((MESSAGE-ID))", messageId);
+ // Deprecated usage. All test code should switch to the (( ... )) syntax.
+ content = content.replace("{{MESSAGE-ID}}", messageId);
+
+ if (content.contains("((REQUEST-ID))")) {
+ content = content.replace("((REQUEST-ID))", msoRequestId);
+ // Deprecated usage. All test code should switch to the (( ... )) syntax.
+ content = content.replace("{{REQUEST-ID}}", msoRequestId);
+ }
+
+ logger.debug("Injecting VNF adapter callback");
+
+ // Is it possible to unmarshal this with JAXB? I couldn't.
+
+ CreateVnfNotification createVnfNotification = new CreateVnfNotification();
+ XPathTool xpathTool = new VnfNotifyXPathTool();
+ xpathTool.setXML(content);
+
+ try {
+ String completed = xpathTool.evaluate("/tns:createVnfNotification/tns:completed/text()");
+ createVnfNotification.setCompleted("true".equals(completed));
+
+ String vnfId = xpathTool.evaluate("/tns:createVnfNotification/tns:vnfId/text()");
+ createVnfNotification.setVnfId(vnfId);
+
+ NodeList entries = (NodeList) xpathTool.evaluate("/tns:createVnfNotification/tns:outputs/tns:entry",
+ XPathConstants.NODESET);
+
+ CreateVnfNotificationOutputs outputs = new CreateVnfNotificationOutputs();
+
+ for (int i = 0; i < entries.getLength(); i++) {
+ Node node = entries.item(i);
+
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element entry = (Element) node;
+ String key = entry.getElementsByTagNameNS("*", "key").item(0).getTextContent();
+ String value = entry.getElementsByTagNameNS("*", "value").item(0).getTextContent();
+ outputs.add(key, value);
+ }
+ }
+
+ createVnfNotification.setOutputs(outputs);
+
+ VnfRollback rollback = new VnfRollback();
+
+ String cloudSiteId = xpathTool.evaluate("/tns:createVnfNotification/tns:rollback/tns:cloudSiteId/text()");
+ rollback.setCloudSiteId(cloudSiteId);
+
+ String cloudOwner = xpathTool.evaluate("/tns:createVnfNotification/tns:rollback/tns:cloudOwner/text()");
+ rollback.setCloudOwner(cloudOwner);
+
+ String requestId =
+ xpathTool.evaluate("/tns:createVnfNotification/tns:rollback/tns:msoRequest/tns:requestId/text()");
+ String serviceInstanceId = xpathTool
+ .evaluate("/tns:createVnfNotification/tns:rollback/tns:msoRequest/tns:serviceInstanceId/text()");
+
+ if (requestId != null || serviceInstanceId != null) {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId(requestId);
+ msoRequest.setServiceInstanceId(serviceInstanceId);
+ rollback.setMsoRequest(msoRequest);
+ }
+
+ String tenantCreated =
+ xpathTool.evaluate("/tns:createVnfNotification/tns:rollback/tns:tenantCreated/text()");
+ rollback.setTenantCreated("true".equals(tenantCreated));
+
+ String tenantId = xpathTool.evaluate("/tns:createVnfNotification/tns:rollback/tns:tenantId/text()");
+ rollback.setTenantId(tenantId);
+
+ String vnfCreated = xpathTool.evaluate("/tns:createVnfNotification/tns:rollback/tns:vnfCreated/text()");
+ rollback.setVnfCreated("true".equals(vnfCreated));
+
+ String rollbackVnfId = xpathTool.evaluate("/tns:createVnfNotification/tns:rollback/tns:vnfId/text()");
+ rollback.setVnfId(rollbackVnfId);
+
+ createVnfNotification.setRollback(rollback);
+
+ } catch (Exception e) {
+ logger.debug("Failed to unmarshal VNF callback content:");
+ logger.debug(content);
+ return false;
+ }
+
+ VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl();
+
+
+ notifyService.createVnfNotification(messageId, createVnfNotification.isCompleted(),
+ createVnfNotification.getException(), createVnfNotification.getErrorMessage(),
+ createVnfNotification.getVnfId(), createVnfNotification.getOutputs(),
+ createVnfNotification.getRollback());
+
+ return true;
}
- /**
- * A test implementation of AsynchronousResponse.
- */
- public class TestAsyncResponse {
- Response response = null;
-
- /**
- * {@inheritDoc}
- */
- public synchronized void setResponse(Response response) {
- this.response = response;
- }
-
- /**
- * Gets the response.
- * @return the response, or null if none has been produced yet
- */
- public synchronized Response getResponse() {
- return response;
- }
- }
-
- /**
- * An object that contains callback data for a "program".
- */
- public class CallbackSet {
- private final Map<String, CallbackData> map = new HashMap<>();
-
- /**
- * Add untyped callback data to the set.
- * @param action the action with which the data is associated
- * @param content the callback data
- */
- public void put(String action, String content) {
- map.put(action, new CallbackData(null, null, content));
- }
-
- /**
- * Add callback data to the set.
- * @param action the action with which the data is associated
- * @param messageType the callback message type
- * @param content the callback data
- */
- public void put(String action, String messageType, String content) {
- map.put(action, new CallbackData(null, messageType, content));
- }
-
- /**
- * Add callback data to the set.
- * @param action the action with which the data is associated
- * @param contentType the callback HTTP content type
- * @param messageType the callback message type
- * @param content the callback data
- */
- public void put(String action, String contentType, String messageType, String content) {
- map.put(action, new CallbackData(contentType, messageType, content));
- }
-
- /**
- * Retrieve callback data from the set.
- * @param action the action with which the data is associated
- * @return the callback data, or null if there is none for the specified operation
- */
- public CallbackData get(String action) {
- return map.get(action);
- }
- }
-
- /**
- * Represents a callback data item.
- */
- public class CallbackData {
- private final String contentType;
- private final String messageType;
- private final String content;
-
- /**
- * Constructor
- * @param contentType the HTTP content type (optional)
- * @param messageType the callback message type (optional)
- * @param content the content
- */
- public CallbackData(String contentType, String messageType, String content) {
- this.contentType = contentType;
- this.messageType = messageType;
- this.content = content;
- }
-
- /**
- * Gets the callback HTTP content type, possibly null.
- */
- public String getContentType() {
- return contentType;
- }
-
- /**
- * Gets the callback message type, possibly null.
- */
- public String getMessageType() {
- return messageType;
- }
-
- /**
- * Gets the callback content.
- */
- public String getContent() {
- return content;
- }
- }
-
- /**
- * A tool for evaluating XPath expressions.
- */
- protected class XPathTool {
- private final DocumentBuilderFactory factory;
- private final SimpleNamespaceContext context = new SimpleNamespaceContext();
- private final XPath xpath = XPathFactory.newInstance().newXPath();
- private String xml = null;
- private Document doc = null;
-
- /**
- * Constructor.
- */
- public XPathTool() {
- factory = DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
- xpath.setNamespaceContext(context);
- }
-
- /**
- * Adds a namespace.
- * @param prefix the namespace prefix
- * @param uri the namespace uri
- */
- public synchronized void addNamespace(String prefix, String uri) {
- context.add(prefix, uri);
- }
-
- /**
- * Sets the XML content to be operated on.
- * @param xml the XML content
- */
- public synchronized void setXML(String xml) {
- this.xml = xml;
- this.doc = null;
- }
-
- /**
- * Returns the document object.
- * @return the document object, or null if XML has not been set
- * @throws SAXException
- * @throws IOException
- * @throws ParserConfigurationException
- */
- public synchronized Document getDocument()
- throws ParserConfigurationException, IOException, SAXException {
- if (xml == null) {
- return null;
- }
-
- buildDocument();
- return doc;
- }
-
- /**
- * Evaluates the specified XPath expression and returns a string result.
- * This method throws exceptions on error.
- * @param expression the expression
- * @return the result object
- * @throws ParserConfigurationException
- * @throws IOException
- * @throws SAXException
- * @throws XPathExpressionException on error
- */
- public synchronized String evaluate(String expression)
- throws ParserConfigurationException, SAXException,
- IOException, XPathExpressionException {
- return (String) evaluate(expression, XPathConstants.STRING);
- }
-
- /**
- * Evaluates the specified XPath expression.
- * This method throws exceptions on error.
- * @param expression the expression
- * @param returnType the return type
- * @return the result object
- * @throws ParserConfigurationException
- * @throws IOException
- * @throws SAXException
- * @throws XPathExpressionException on error
- */
- public synchronized Object evaluate(String expression, QName returnType)
- throws ParserConfigurationException, SAXException,
- IOException, XPathExpressionException {
-
- buildDocument();
- XPathExpression expr = xpath.compile(expression);
- return expr.evaluate(doc, returnType);
- }
-
- /**
- * Private helper method that builds the document object.
- * Assumes the calling method is synchronized.
- * @throws ParserConfigurationException
- * @throws IOException
- * @throws SAXException
- */
- private void buildDocument() throws ParserConfigurationException,
- IOException, SAXException {
- if (doc == null) {
- if (xml == null) {
- throw new IOException("XML input is null");
- }
-
- DocumentBuilder builder = factory.newDocumentBuilder();
- InputSource source = new InputSource(new StringReader(xml));
- doc = builder.parse(source);
- }
- }
- }
-
- /**
- * A NamespaceContext class based on a Map.
- */
- private class SimpleNamespaceContext implements NamespaceContext {
- private Map<String, String> prefixMap = new HashMap<>();
- private Map<String, String> uriMap = new HashMap<>();
-
- public synchronized void add(String prefix, String uri) {
- prefixMap.put(prefix, uri);
- uriMap.put(uri, prefix);
- }
-
- @Override
- public synchronized String getNamespaceURI(String prefix) {
- return prefixMap.get(prefix);
- }
-
- @Override
- public Iterator<String> getPrefixes(String uri) {
- List<String> list = new ArrayList<>();
- String prefix = uriMap.get(uri);
- if (prefix != null) {
- list.add(prefix);
- }
- return list.iterator();
- }
-
- @Override
- public String getPrefix(String uri) {
- return uriMap.get(uri);
- }
- }
-
- /**
- * A VnfNotify XPathTool.
- */
- protected class VnfNotifyXPathTool extends XPathTool {
- public VnfNotifyXPathTool() {
- addNamespace("tns", "http://org.onap.so/vnfNotify");
- }
- }
-
- /**
- * Helper class to make it easier to create this type.
- */
- private static class CreateVnfNotificationOutputs
- extends CreateVnfNotification.Outputs {
- public void add(String key, String value) {
- Entry entry = new Entry();
- entry.setKey(key);
- entry.setValue(value);
- getEntry().add(entry);
- }
- }
-
- /**
- * Helper class to make it easier to create this type.
- */
- private static class UpdateVnfNotificationOutputs
- extends UpdateVnfNotification.Outputs {
- public void add(String key, String value) {
- Entry entry = new Entry();
- entry.setKey(key);
- entry.setValue(value);
- getEntry().add(entry);
- }
- }
+ /**
+ * Injects a Delete VNF adapter callback request. The specified callback data may contain the placeholder string
+ * ((MESSAGE-ID)) which is replaced with the actual message ID. It may also contain the placeholder string
+ * ((REQUEST-ID)) which is replaced request ID of the original MSO request.
+ *
+ * @param content the content of the callback
+ * @param timeout the timeout in milliseconds
+ * @return true if the callback could be injected, false otherwise
+ * @throws JAXBException if the content does not adhere to the schema
+ */
+ protected boolean injectDeleteVNFCallback(String content, long timeout) {
+
+ String messageId = (String) getProcessVariable("vnfAdapterDeleteV1", "VNFDEL_uuid", timeout);
+
+ if (messageId == null) {
+ return false;
+ }
+
+ content = content.replace("((MESSAGE-ID))", messageId);
+ // Deprecated usage. All test code should switch to the (( ... )) syntax.
+ content = content.replace("{{MESSAGE-ID}}", messageId);
+
+ logger.debug("Injecting VNF adapter delete callback");
+
+ // Is it possible to unmarshal this with JAXB? I couldn't.
+
+ DeleteVnfNotification deleteVnfNotification = new DeleteVnfNotification();
+ XPathTool xpathTool = new VnfNotifyXPathTool();
+ xpathTool.setXML(content);
+
+ try {
+ String completed = xpathTool.evaluate("/tns:deleteVnfNotification/tns:completed/text()");
+ deleteVnfNotification.setCompleted("true".equals(completed));
+ // if notification failure, set the exception and error message
+ if (deleteVnfNotification.isCompleted() == false) {
+ deleteVnfNotification.setException(MsoExceptionCategory.INTERNAL);
+ deleteVnfNotification
+ .setErrorMessage(xpathTool.evaluate("/tns:deleteVnfNotification/tns:errorMessage/text()"));
+ }
+
+ } catch (Exception e) {
+ logger.debug("Failed to unmarshal VNF Delete callback content:");
+ logger.debug(content);
+ return false;
+ }
+
+ VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl();
+
+
+ notifyService.deleteVnfNotification(messageId, deleteVnfNotification.isCompleted(),
+ deleteVnfNotification.getException(), deleteVnfNotification.getErrorMessage());
+
+ return true;
+ }
+
+ /**
+ * Injects a Update VNF adapter callback request. The specified callback data may contain the placeholder string
+ * ((MESSAGE-ID)) which is replaced with the actual message ID. It may also contain the placeholder string
+ * ((REQUEST-ID)) which is replaced request ID of the original MSO request.
+ *
+ * @param content the content of the callback
+ * @param timeout the timeout in milliseconds
+ * @return true if the callback could be injected, false otherwise
+ * @throws JAXBException if the content does not adhere to the schema
+ */
+ protected boolean injectUpdateVNFCallback(String content, long timeout) {
+
+ String messageId = (String) getProcessVariable("vnfAdapterUpdate", "VNFU_messageId", timeout);
+
+ if (messageId == null) {
+ return false;
+ }
+
+ content = content.replace("((MESSAGE-ID))", messageId);
+ // Deprecated usage. All test code should switch to the (( ... )) syntax.
+ content = content.replace("{{MESSAGE-ID}}", messageId);
+
+ content = content.replace("((REQUEST-ID))", msoRequestId);
+ // Deprecated usage. All test code should switch to the (( ... )) syntax.
+ content = content.replace("{{REQUEST-ID}}", msoRequestId);
+
+ logger.debug("Injecting VNF adapter callback");
+
+ // Is it possible to unmarshal this with JAXB? I couldn't.
+
+ UpdateVnfNotification updateVnfNotification = new UpdateVnfNotification();
+ XPathTool xpathTool = new VnfNotifyXPathTool();
+ xpathTool.setXML(content);
+
+ try {
+ String completed = xpathTool.evaluate("/tns:updateVnfNotification/tns:completed/text()");
+ updateVnfNotification.setCompleted("true".equals(completed));
+
+ NodeList entries = (NodeList) xpathTool.evaluate("/tns:updateVnfNotification/tns:outputs/tns:entry",
+ XPathConstants.NODESET);
+
+ UpdateVnfNotificationOutputs outputs = new UpdateVnfNotificationOutputs();
+
+ for (int i = 0; i < entries.getLength(); i++) {
+ Node node = entries.item(i);
+
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element entry = (Element) node;
+ String key = entry.getElementsByTagNameNS("*", "key").item(0).getTextContent();
+ String value = entry.getElementsByTagNameNS("*", "value").item(0).getTextContent();
+ outputs.add(key, value);
+ }
+ }
+
+ updateVnfNotification.setOutputs(outputs);
+
+ VnfRollback rollback = new VnfRollback();
+
+ String cloudSiteId = xpathTool.evaluate("/tns:updateVnfNotification/tns:rollback/tns:cloudSiteId/text()");
+ rollback.setCloudSiteId(cloudSiteId);
+
+ String cloudOwner = xpathTool.evaluate("/tns:updateVnfNotification/tns:rollback/tns:cloudOwner/text()");
+ rollback.setCloudOwner(cloudOwner);
+
+ String requestId =
+ xpathTool.evaluate("/tns:updateVnfNotification/tns:rollback/tns:msoRequest/tns:requestId/text()");
+ String serviceInstanceId = xpathTool
+ .evaluate("/tns:updateVnfNotification/tns:rollback/tns:msoRequest/tns:serviceInstanceId/text()");
+
+ if (requestId != null || serviceInstanceId != null) {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId(requestId);
+ msoRequest.setServiceInstanceId(serviceInstanceId);
+ rollback.setMsoRequest(msoRequest);
+ }
+
+ String tenantCreated =
+ xpathTool.evaluate("/tns:updateVnfNotification/tns:rollback/tns:tenantCreated/text()");
+ rollback.setTenantCreated("true".equals(tenantCreated));
+
+ String tenantId = xpathTool.evaluate("/tns:updateVnfNotification/tns:rollback/tns:tenantId/text()");
+ rollback.setTenantId(tenantId);
+
+ String vnfCreated = xpathTool.evaluate("/tns:updateVnfNotification/tns:rollback/tns:vnfCreated/text()");
+ rollback.setVnfCreated("true".equals(vnfCreated));
+
+ String rollbackVnfId = xpathTool.evaluate("/tns:updateVnfNotification/tns:rollback/tns:vnfId/text()");
+ rollback.setVnfId(rollbackVnfId);
+
+ updateVnfNotification.setRollback(rollback);
+
+ } catch (Exception e) {
+ logger.debug("Failed to unmarshal VNF callback content:");
+ logger.debug(content);
+ return false;
+ }
+
+ VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl();
+
+
+ notifyService.updateVnfNotification(messageId, updateVnfNotification.isCompleted(),
+ updateVnfNotification.getException(), updateVnfNotification.getErrorMessage(),
+ updateVnfNotification.getOutputs(), updateVnfNotification.getRollback());
+
+ return true;
+ }
+
+ /**
+ * Runs a program to inject workflow messages into the test environment. A program is essentially just a list of
+ * keys that identify event data to be injected, in sequence. An example program:
+ *
+ * <pre>
+ * event1, event2
+ * </pre>
+ *
+ * Errors are handled with junit assertions and will cause the test to fail. NOTE: Each callback must have a
+ * workflow message type associated with it.
+ *
+ * @param callbacks an object containing event data for the program
+ * @param program the program to execute
+ */
+ protected void injectWorkflowMessages(CallbackSet callbacks, String program) {
+
+ String[] cmds = program.replaceAll("\\s+", "").split(",");
+
+ for (String cmd : cmds) {
+ String action = cmd;
+ String modifier = "STD";
+
+ if (cmd.contains(":")) {
+ String[] parts = cmd.split(":");
+ action = parts[0];
+ modifier = parts[1];
+ }
+
+ String messageType = null;
+ String content = null;
+ String contentType = null;
+
+ if ("STD".equals(modifier)) {
+ CallbackData callbackData = callbacks.get(action);
+
+ if (callbackData == null) {
+ String msg = "No '" + action + "' workflow message callback is defined";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ messageType = callbackData.getMessageType();
+
+ if (messageType == null || messageType.trim().equals("")) {
+ String msg = "No workflow message type is defined in the '" + action + "' callback";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ content = callbackData.getContent();
+ contentType = callbackData.getContentType();
+ } else {
+ String msg = "Invalid workflow message program modifier: '" + modifier + "'";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ if (!injectWorkflowMessage(contentType, messageType, content, 10000)) {
+ fail("Failed to inject '" + action + "' workflow message");
+ }
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ fail("Interrupted after injection of '" + action + "' workflow message");
+ }
+ }
+ }
+
+ /**
+ * Injects a workflow message. The specified callback data may contain the placeholder string ((CORRELATOR)) which
+ * is replaced with the actual correlator value.
+ *
+ * @param contentType the HTTP contentType for the message (possibly null)
+ * @param messageType the message type
+ * @param content the message content (possibly null)
+ * @param timeout the timeout in milliseconds
+ * @return true if the message could be injected, false otherwise
+ */
+ protected boolean injectWorkflowMessage(String contentType, String messageType, String content, long timeout) {
+ String correlator = (String) getProcessVariable("ReceiveWorkflowMessage", messageType + "_CORRELATOR", timeout);
+
+ if (correlator == null) {
+ return false;
+ }
+
+ if (content != null) {
+ content = content.replace("((CORRELATOR))", correlator);
+ }
+
+ logger.debug("Injecting " + messageType + " message");
+
+ Response response = workflowMessageResource.deliver(contentType, messageType, correlator, content);
+ logger.debug("Workflow response to {} message: {}", messageType, response);
+ return true;
+ }
+
+ /**
+ * Runs a program to inject sniro workflow messages into the test environment. A program is essentially just a list
+ * of keys that identify event data to be injected, in sequence. For more details, see injectSNIROCallbacks(String
+ * contentType, String messageType, String content, long timeout)
+ *
+ * Errors are handled with junit assertions and will cause the test to fail. NOTE: Each callback must have a
+ * workflow message type associated with it.
+ *
+ * @param callbacks an object containing event data for the program
+ * @param program the program to execute
+ */
+ protected void injectSNIROCallbacks(CallbackSet callbacks, String program) {
+
+ String[] cmds = program.replaceAll("\\s+", "").split(",");
+
+ for (String cmd : cmds) {
+ String action = cmd;
+ String modifier = "STD";
+
+ if (cmd.contains(":")) {
+ String[] parts = cmd.split(":");
+ action = parts[0];
+ modifier = parts[1];
+ }
+
+ String messageType = null;
+ String content = null;
+ String contentType = null;
+
+ if ("STD".equals(modifier)) {
+ CallbackData callbackData = callbacks.get(action);
+
+ if (callbackData == null) {
+ String msg = "No '" + action + "' workflow message callback is defined";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ messageType = callbackData.getMessageType();
+
+ if (messageType == null || messageType.trim().equals("")) {
+ String msg = "No workflow message type is defined in the '" + action + "' callback";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ content = callbackData.getContent();
+ contentType = callbackData.getContentType();
+ } else {
+ String msg = "Invalid workflow message program modifier: '" + modifier + "'";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ if (!injectSNIROCallbacks(contentType, messageType, content, 10000)) {
+ fail("Failed to inject '" + action + "' workflow message");
+ }
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ fail("Interrupted after injection of '" + action + "' workflow message");
+ }
+ }
+ }
+
+ /**
+ * Injects a sniro workflow message. The specified callback response may contain the placeholder strings
+ * ((CORRELATOR)) and ((SERVICE_RESOURCE_ID)) The ((CORRELATOR)) is replaced with the actual correlator value from
+ * the request. The ((SERVICE_RESOURCE_ID)) is replaced with the actual serviceResourceId value from the sniro
+ * request. Currently this only works with sniro request that contain only 1 resource.
+ *
+ * @param contentType the HTTP contentType for the message (possibly null)
+ * @param messageType the message type
+ * @param content the message content (possibly null)
+ * @param timeout the timeout in milliseconds
+ * @return true if the message could be injected, false otherwise
+ */
+ protected boolean injectSNIROCallbacks(String contentType, String messageType, String content, long timeout) {
+ String correlator = (String) getProcessVariable("ReceiveWorkflowMessage", messageType + "_CORRELATOR", timeout);
+
+ if (correlator == null) {
+ return false;
+ }
+ if (content != null) {
+ content = content.replace("((CORRELATOR))", correlator);
+ if (messageType.equalsIgnoreCase("SNIROResponse")) {
+ ServiceDecomposition decomp =
+ (ServiceDecomposition) getProcessVariable("Homing", "serviceDecomposition", timeout);
+ List<Resource> resourceList = decomp.getServiceResources();
+ if (resourceList.size() == 1) {
+ String resourceId = "";
+ for (Resource resource : resourceList) {
+ resourceId = resource.getResourceId();
+ }
+ String homingList = getJsonValue(content, "solutionInfo.placementInfo");
+ JSONArray placementArr = null;
+ try {
+ placementArr = new JSONArray(homingList);
+ } catch (Exception e) {
+ return false;
+ }
+ if (placementArr.length() == 1) {
+ content = content.replace("((SERVICE_RESOURCE_ID))", resourceId);
+ }
+ String licenseInfoList = getJsonValue(content, "solutionInfo.licenseInfo");
+ JSONArray licenseArr = null;
+ try {
+ licenseArr = new JSONArray(licenseInfoList);
+ } catch (Exception e) {
+ return false;
+ }
+ if (licenseArr.length() == 1) {
+ content = content.replace("((SERVICE_RESOURCE_ID))", resourceId);
+ }
+ } else {
+ try {
+ String homingList = getJsonValue(content, "solutionInfo.placementInfo");
+ String licenseInfoList = getJsonValue(content, "solutionInfo.licenseInfo");
+ JSONArray placementArr = new JSONArray(homingList);
+ JSONArray licenseArr = new JSONArray(licenseInfoList);
+ for (Resource resource : resourceList) {
+ String resourceModuleName = resource.getModelInfo().getModelInstanceName();
+ String resourceId = resource.getResourceId();
+
+ for (int i = 0; i < placementArr.length(); i++) {
+ JSONObject placementObj = placementArr.getJSONObject(i);
+ String placementModuleName = placementObj.getString("resourceModuleName");
+ if (placementModuleName.equalsIgnoreCase(resourceModuleName)) {
+ String placementString = placementObj.toString();
+ placementString = placementString.replace("((SERVICE_RESOURCE_ID))", resourceId);
+ JSONObject newPlacementObj = new JSONObject(placementString);
+ placementArr.put(i, newPlacementObj);
+ }
+ }
+
+ for (int i = 0; i < licenseArr.length(); i++) {
+ JSONObject licenseObj = licenseArr.getJSONObject(i);
+ String licenseModuleName = licenseObj.getString("resourceModuleName");
+ if (licenseModuleName.equalsIgnoreCase(resourceModuleName)) {
+ String licenseString = licenseObj.toString();
+ licenseString = licenseString.replace("((SERVICE_RESOURCE_ID))", resourceId);
+ JSONObject newLicenseObj = new JSONObject(licenseString);
+ licenseArr.put(i, newLicenseObj);
+ }
+ }
+ }
+ String newPlacementInfos = placementArr.toString();
+ String newLicenseInfos = licenseArr.toString();
+ content = updJsonValue(content, "solutionInfo.placementInfo", newPlacementInfos);
+ content = updJsonValue(content, "solutionInfo.licenseInfo", newLicenseInfos);
+ } catch (Exception e) {
+ return false;
+ }
+
+ }
+ }
+ }
+ logger.debug("Injecting " + messageType + " message");
+
+ Response response = workflowMessageResource.deliver(contentType, messageType, correlator, content);
+ logger.debug("Workflow response to {} message: {}", messageType, response);
+ return true;
+ }
+
+
+ /**
+ * Wait for the process to end.
+ *
+ * @param businessKey the process business key
+ * @param timeout the amount of time to wait, in milliseconds
+ */
+ protected void waitForProcessEnd(String businessKey, long timeout) {
+ logger.debug("Waiting {}ms for process with business key {} to end", timeout, businessKey);
+
+ long now = System.currentTimeMillis() + timeout;
+ long endTime = now + timeout;
+
+ while (now <= endTime) {
+ if (isProcessEnded(businessKey)) {
+ logger.debug("Process with business key {} has ended", businessKey);
+ return;
+ }
+
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ String msg = "Interrupted waiting for process with business key " + businessKey + " to end";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ now = System.currentTimeMillis();
+ }
+
+ String msg = "Process with business key " + businessKey + " did not end within " + timeout + "ms";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ /**
+ * Wait for the process to end. Must be used when multiple process instances exist with this same business key such
+ * as when its passed to subflows or shared across multiple processes.
+ *
+ * @param businessKey the process business key
+ * @param processName the process definition name
+ * @param timeout the amount of time to wait, in milliseconds
+ * @author cb645j
+ */
+ protected void waitForProcessEnd(String businessKey, String processName, long timeout) {
+ logger.debug("Waiting {}ms for process with business key {} to end", timeout, businessKey);
+
+ long now = System.currentTimeMillis() + timeout;
+ long endTime = now + timeout;
+
+ while (now <= endTime) {
+ if (isProcessEnded(businessKey, processName)) {
+ logger.debug("Process with business key {} has ended", businessKey);
+ return;
+ }
+
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ String msg = "Interrupted waiting for process with business key " + businessKey + " to end";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ now = System.currentTimeMillis();
+ }
+
+ String msg = "Process with business key " + businessKey + " did not end within " + timeout + "ms";
+ logger.debug(msg);
+ fail(msg);
+ }
+
+ /**
+ * Verifies that the specified historic process variable has the specified value. If the variable does not have the
+ * specified value, the test is failed.
+ *
+ * @param businessKey the process business key
+ * @param variable the variable name
+ * @param value the expected variable value
+ */
+ protected void checkVariable(String businessKey, String variable, Object value) {
+ if (!isProcessEnded(businessKey)) {
+ fail("Cannot get historic variable " + variable + " because process with business key " + businessKey
+ + " has not ended");
+ }
+
+ Object variableValue = getVariableFromHistory(businessKey, variable);
+ assertEquals(value, variableValue);
+ }
+
+ /**
+ * Checks to see if the specified process is ended.
+ *
+ * @param businessKey the process business Key
+ * @return true if the process is ended
+ */
+ protected boolean isProcessEnded(String businessKey) {
+ HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery()
+ .processInstanceBusinessKey(businessKey).singleResult();
+ return processInstance != null && processInstance.getEndTime() != null;
+ }
+
+ /**
+ * Checks to see if the specified process is ended.
+ *
+ * @param processInstanceId the process Instance Id
+ * @return true if the process is ended
+ */
+ protected boolean isProcessEndedByProcessInstanceId(String processInstanceId) {
+ HistoricProcessInstance processInstance =
+ historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
+ return processInstance != null && processInstance.getEndTime() != null;
+ }
+
+ /**
+ * Checks to see if the specified process is ended.
+ *
+ * @author cb645j
+ */
+ // TODO combine into 1
+ private boolean isProcessEnded(String businessKey, String processName) {
+ HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery()
+ .processInstanceBusinessKey(businessKey).processDefinitionName(processName).singleResult();
+ return processInstance != null && processInstance.getEndTime() != null;
+ }
+
+ /**
+ * Gets a variable value from a historical process instance. The business key must be unique.
+ *
+ * @param businessKey the process business key
+ * @param variableName the variable name
+ * @return the variable value or null if the variable does not exist
+ */
+ protected Object getVariableFromHistory(String businessKey, String variableName) {
+ try {
+ HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery()
+ .processInstanceBusinessKey(businessKey).singleResult();
+
+ if (processInstance == null) {
+ return null;
+ }
+
+ HistoricVariableInstance v = historyService.createHistoricVariableInstanceQuery()
+ .processInstanceId(processInstance.getId()).variableName(variableName).singleResult();
+ return v == null ? null : v.getValue();
+ } catch (Exception e) {
+ logger.debug("Error retrieving variable {} from historical process with business key {}: ", variableName,
+ businessKey, e);
+ return null;
+ }
+ }
+
+ /**
+ * Gets a variable value from a process instance based on businessKey and process name. Must be used when multiple
+ * instances exist with the same business key such as when business key is passed to subflows or shared across
+ * multiple processes. This method can obtain variables from mainflows and from subflows.
+ *
+ * @param businessKey the process business key
+ * @param processName the process definition name
+ * @param variableName the variable name
+ * @return the variable value or null if the variable does not exist
+ * @author cb645j
+ */
+ protected Object getVariableFromHistory(String businessKey, String processName, String variableName) {
+ try {
+ HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery()
+ .processInstanceBusinessKey(businessKey).processDefinitionName(processName).singleResult();
+
+ if (processInstance == null) {
+ return null;
+ }
+ HistoricVariableInstance variable = historyService.createHistoricVariableInstanceQuery()
+ .processInstanceId(processInstance.getId()).variableName(variableName).singleResult();
+
+ return variable == null ? null : variable.getValue();
+ } catch (ProcessEngineException e) {
+ logger.debug(
+ "Multiple proccess instances exist with process name {} and business key {}. Must pass instance "
+ + "index as a parameter.",
+ processName, businessKey);
+ return null;
+ } catch (Exception e) {
+ logger.debug("Error retrieving variable {} from historical process for process {} with business key {}: ",
+ variableName, processName, businessKey, e);
+ return null;
+ }
+ }
+
+ /**
+ * Gets the value of a process variable from x instance of y process. Must be used when multiple instances exist
+ * with the same business key AND process name. This method shall be used primarily for obtaining subflow variables
+ * when the business key is passed to the subflow AND the subflow is called multiple times in a given flow.
+ *
+ * @param businessKey the process business key
+ * @param processName the name of the subflow that contains the variable
+ * @param variableName the variable name
+ * @param processInstanceIndex the instance in which the subprocess was called
+ * @return the variable value or null if the variable does not exist
+ * @author cb645j
+ */
+ protected Object getVariableFromHistory(String businessKey, int subflowInstanceIndex, String processName,
+ String variableName) {
+ try {
+ List<HistoricProcessInstance> processInstanceList = historyService.createHistoricProcessInstanceQuery()
+ .processInstanceBusinessKey(businessKey).processDefinitionName(processName).list();
+
+ if (processInstanceList == null) {
+ return null;
+ }
+ processInstanceList.sort((m1, m2) -> m1.getStartTime().compareTo(m2.getStartTime()));
+
+ HistoricProcessInstance processInstance = processInstanceList.get(subflowInstanceIndex);
+ HistoricVariableInstance variable = historyService.createHistoricVariableInstanceQuery()
+ .processInstanceId(processInstance.getId()).variableName(variableName).singleResult();
+
+ return variable == null ? null : variable.getValue();
+ } catch (Exception e) {
+ logger.debug("Error retrieving variable {} from historical process for process {} with business key {}: ",
+ variableName, processName, businessKey, e);
+ return null;
+ }
+ }
+
+
+ /**
+ * Gets the value of a subflow variable from the specified subflow's historical process instance.
+ *
+ * DEPRECATED - Use method getVariableFromHistory(businessKey, processName, variableName) instead
+ *
+ * @param subflowName - the name of the subflow that contains the variable
+ * @param variableName the variable name
+ *
+ * @return the variable value, or null if the variable could not be obtained
+ *
+ */
+ @Deprecated
+ protected Object getVariableFromSubflowHistory(String subflowName, String variableName) {
+ try {
+ List<HistoricProcessInstance> processInstanceList =
+ historyService.createHistoricProcessInstanceQuery().processDefinitionName(subflowName).list();
+
+ if (processInstanceList == null) {
+ return null;
+ }
+
+ processInstanceList.sort((m1, m2) -> m1.getStartTime().compareTo(m2.getStartTime()));
+
+ HistoricProcessInstance processInstance = processInstanceList.get(0);
+
+ HistoricVariableInstance v = historyService.createHistoricVariableInstanceQuery()
+ .processInstanceId(processInstance.getId()).variableName(variableName).singleResult();
+ return v == null ? null : v.getValue();
+ } catch (Exception e) {
+ logger.debug("Error retrieving variable {} from sub flow: {}, Exception is: ", variableName, subflowName,
+ e);
+ return null;
+ }
+ }
+
+ /**
+ * Gets the value of a subflow variable from the subflow's historical process x instance.
+ *
+ * DEPRECATED: Use method getVariableFromHistory(businessKey, processInstanceIndex, processName, variableName)
+ * instead
+ *
+ * @param subflowName - the name of the subflow that contains the variable
+ * @param variableName the variable name
+ * @param subflowInstanceIndex - the instance of the subflow (use when same subflow is called more than once from
+ * mainflow)
+ *
+ * @return the variable value, or null if the variable could not be obtained
+ */
+ @Deprecated
+ protected Object getVariableFromSubflowHistory(int subflowInstanceIndex, String subflowName, String variableName) {
+ try {
+ List<HistoricProcessInstance> processInstanceList =
+ historyService.createHistoricProcessInstanceQuery().processDefinitionName(subflowName).list();
+
+ if (processInstanceList == null) {
+ return null;
+ }
+
+ processInstanceList.sort((m1, m2) -> m1.getStartTime().compareTo(m2.getStartTime()));
+
+ HistoricProcessInstance processInstance = processInstanceList.get(subflowInstanceIndex);
+
+ HistoricVariableInstance v = historyService.createHistoricVariableInstanceQuery()
+ .processInstanceId(processInstance.getId()).variableName(variableName).singleResult();
+ return v == null ? null : v.getValue();
+ } catch (Exception e) {
+ logger.debug("Error retrieving variable {} from {} instance index of sub flow: {}, Exception is: ",
+ variableName, subflowInstanceIndex, subflowName, e);
+ return null;
+ }
+ }
+
+ /**
+ * Extracts text from an XML element. This method is not namespace aware (namespaces are ignored). The first
+ * matching element is selected.
+ *
+ * @param xml the XML document or fragment
+ * @param tag the desired element, e.g. "<name>"
+ * @return the element text, or null if the element was not found
+ */
+ protected String getXMLTextElement(String xml, String tag) {
+ xml = removeXMLNamespaces(xml);
+
+ if (!tag.startsWith("<")) {
+ tag = "<" + tag + ">";
+ }
+
+ int start = xml.indexOf(tag);
+
+ if (start == -1) {
+ return null;
+ }
+
+ int end = xml.indexOf('<', start + tag.length());
+
+ if (end == -1) {
+ return null;
+ }
+
+ return xml.substring(start + tag.length(), end);
+ }
+
+ /**
+ * Removes namespace definitions and prefixes from XML, if any.
+ */
+ private String removeXMLNamespaces(String xml) {
+ // remove xmlns declaration
+ xml = xml.replaceAll("xmlns.*?(\"|\').*?(\"|\')", "");
+
+ // remove opening tag prefix
+ xml = xml.replaceAll("(<)(\\w+:)(.*?>)", "$1$3");
+
+ // remove closing tags prefix
+ xml = xml.replaceAll("(</)(\\w+:)(.*?>)", "$1$3");
+
+ // remove extra spaces left when xmlns declarations are removed
+ xml = xml.replaceAll("\\s+>", ">");
+
+ return xml;
+ }
+
+ /**
+ * Asserts that two XML documents are semantically equivalent. Differences in whitespace or in namespace usage do
+ * not affect the comparison.
+ *
+ * @param expected the expected XML
+ * @param actual the XML to test
+ * @throws SAXException
+ * @throws IOException
+ */
+ public static void assertXMLEquals(String expected, String actual) throws SAXException, IOException {
+ XMLUnit.setIgnoreWhitespace(true);
+ XMLUnit.setIgnoreAttributeOrder(true);
+ DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expected, actual));
+ List<?> allDifferences = diff.getAllDifferences();
+ assertEquals("Differences found: " + diff.toString(), 0, allDifferences.size());
+ }
+
+ /**
+ * A test implementation of AsynchronousResponse.
+ */
+ public class TestAsyncResponse {
+ Response response = null;
+
+ /**
+ * {@inheritDoc}
+ */
+ public synchronized void setResponse(Response response) {
+ this.response = response;
+ }
+
+ /**
+ * Gets the response.
+ *
+ * @return the response, or null if none has been produced yet
+ */
+ public synchronized Response getResponse() {
+ return response;
+ }
+ }
+
+ /**
+ * An object that contains callback data for a "program".
+ */
+ public class CallbackSet {
+ private final Map<String, CallbackData> map = new HashMap<>();
+
+ /**
+ * Add untyped callback data to the set.
+ *
+ * @param action the action with which the data is associated
+ * @param content the callback data
+ */
+ public void put(String action, String content) {
+ map.put(action, new CallbackData(null, null, content));
+ }
+
+ /**
+ * Add callback data to the set.
+ *
+ * @param action the action with which the data is associated
+ * @param messageType the callback message type
+ * @param content the callback data
+ */
+ public void put(String action, String messageType, String content) {
+ map.put(action, new CallbackData(null, messageType, content));
+ }
+
+ /**
+ * Add callback data to the set.
+ *
+ * @param action the action with which the data is associated
+ * @param contentType the callback HTTP content type
+ * @param messageType the callback message type
+ * @param content the callback data
+ */
+ public void put(String action, String contentType, String messageType, String content) {
+ map.put(action, new CallbackData(contentType, messageType, content));
+ }
+
+ /**
+ * Retrieve callback data from the set.
+ *
+ * @param action the action with which the data is associated
+ * @return the callback data, or null if there is none for the specified operation
+ */
+ public CallbackData get(String action) {
+ return map.get(action);
+ }
+ }
+
+ /**
+ * Represents a callback data item.
+ */
+ public class CallbackData {
+ private final String contentType;
+ private final String messageType;
+ private final String content;
+
+ /**
+ * Constructor
+ *
+ * @param contentType the HTTP content type (optional)
+ * @param messageType the callback message type (optional)
+ * @param content the content
+ */
+ public CallbackData(String contentType, String messageType, String content) {
+ this.contentType = contentType;
+ this.messageType = messageType;
+ this.content = content;
+ }
+
+ /**
+ * Gets the callback HTTP content type, possibly null.
+ */
+ public String getContentType() {
+ return contentType;
+ }
+
+ /**
+ * Gets the callback message type, possibly null.
+ */
+ public String getMessageType() {
+ return messageType;
+ }
+
+ /**
+ * Gets the callback content.
+ */
+ public String getContent() {
+ return content;
+ }
+ }
+
+ /**
+ * A tool for evaluating XPath expressions.
+ */
+ protected class XPathTool {
+ private final DocumentBuilderFactory factory;
+ private final SimpleNamespaceContext context = new SimpleNamespaceContext();
+ private final XPath xpath = XPathFactory.newInstance().newXPath();
+ private String xml = null;
+ private Document doc = null;
+
+ /**
+ * Constructor.
+ */
+ public XPathTool() {
+ factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ xpath.setNamespaceContext(context);
+ }
+
+ /**
+ * Adds a namespace.
+ *
+ * @param prefix the namespace prefix
+ * @param uri the namespace uri
+ */
+ public synchronized void addNamespace(String prefix, String uri) {
+ context.add(prefix, uri);
+ }
+
+ /**
+ * Sets the XML content to be operated on.
+ *
+ * @param xml the XML content
+ */
+ public synchronized void setXML(String xml) {
+ this.xml = xml;
+ this.doc = null;
+ }
+
+ /**
+ * Returns the document object.
+ *
+ * @return the document object, or null if XML has not been set
+ * @throws SAXException
+ * @throws IOException
+ * @throws ParserConfigurationException
+ */
+ public synchronized Document getDocument() throws ParserConfigurationException, IOException, SAXException {
+ if (xml == null) {
+ return null;
+ }
+
+ buildDocument();
+ return doc;
+ }
+
+ /**
+ * Evaluates the specified XPath expression and returns a string result. This method throws exceptions on error.
+ *
+ * @param expression the expression
+ * @return the result object
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ * @throws XPathExpressionException on error
+ */
+ public synchronized String evaluate(String expression)
+ throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
+ return (String) evaluate(expression, XPathConstants.STRING);
+ }
+
+ /**
+ * Evaluates the specified XPath expression. This method throws exceptions on error.
+ *
+ * @param expression the expression
+ * @param returnType the return type
+ * @return the result object
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ * @throws XPathExpressionException on error
+ */
+ public synchronized Object evaluate(String expression, QName returnType)
+ throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
+
+ buildDocument();
+ XPathExpression expr = xpath.compile(expression);
+ return expr.evaluate(doc, returnType);
+ }
+
+ /**
+ * Private helper method that builds the document object. Assumes the calling method is synchronized.
+ *
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ */
+ private void buildDocument() throws ParserConfigurationException, IOException, SAXException {
+ if (doc == null) {
+ if (xml == null) {
+ throw new IOException("XML input is null");
+ }
+
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ InputSource source = new InputSource(new StringReader(xml));
+ doc = builder.parse(source);
+ }
+ }
+ }
+
+ /**
+ * A NamespaceContext class based on a Map.
+ */
+ private class SimpleNamespaceContext implements NamespaceContext {
+ private Map<String, String> prefixMap = new HashMap<>();
+ private Map<String, String> uriMap = new HashMap<>();
+
+ public synchronized void add(String prefix, String uri) {
+ prefixMap.put(prefix, uri);
+ uriMap.put(uri, prefix);
+ }
+
+ @Override
+ public synchronized String getNamespaceURI(String prefix) {
+ return prefixMap.get(prefix);
+ }
+
+ @Override
+ public Iterator<String> getPrefixes(String uri) {
+ List<String> list = new ArrayList<>();
+ String prefix = uriMap.get(uri);
+ if (prefix != null) {
+ list.add(prefix);
+ }
+ return list.iterator();
+ }
+
+ @Override
+ public String getPrefix(String uri) {
+ return uriMap.get(uri);
+ }
+ }
+
+ /**
+ * A VnfNotify XPathTool.
+ */
+ protected class VnfNotifyXPathTool extends XPathTool {
+ public VnfNotifyXPathTool() {
+ addNamespace("tns", "http://org.onap.so/vnfNotify");
+ }
+ }
+
+ /**
+ * Helper class to make it easier to create this type.
+ */
+ private static class CreateVnfNotificationOutputs extends CreateVnfNotification.Outputs {
+ public void add(String key, String value) {
+ Entry entry = new Entry();
+ entry.setKey(key);
+ entry.setValue(value);
+ getEntry().add(entry);
+ }
+ }
+
+ /**
+ * Helper class to make it easier to create this type.
+ */
+ private static class UpdateVnfNotificationOutputs extends UpdateVnfNotification.Outputs {
+ public void add(String key, String value) {
+ Entry entry = new Entry();
+ entry.setKey(key);
+ entry.setValue(value);
+ getEntry().add(entry);
+ }
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowTestTransformer.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowTestTransformer.java
index dbad35a6a4..794e772dcd 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowTestTransformer.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/WorkflowTestTransformer.java
@@ -26,16 +26,15 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
- * Allows a subclass of WorkflowTest to specify one or more WireMock
- * response transformers. A transformer must be declared as a public
- * static field in the subclass. For example:
+ * Allows a subclass of WorkflowTest to specify one or more WireMock response transformers. A transformer must be
+ * declared as a public static field in the subclass. For example:
+ *
* <pre>
- * @WorkflowTestTransformer
- * public static final ResponseTransformer sdncAdapterMockTransformer =
- * new SDNCAdapterMockTransformer();
+ * &#64;WorkflowTestTransformer
+ * public static final ResponseTransformer sdncAdapterMockTransformer = new SDNCAdapterMockTransformer();
* </pre>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface WorkflowTestTransformer {
-} \ No newline at end of file
+}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/adapter/sdnc/ObjectFactoryTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/adapter/sdnc/ObjectFactoryTest.java
index bdc48392af..d95a5883c8 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/adapter/sdnc/ObjectFactoryTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/adapter/sdnc/ObjectFactoryTest.java
@@ -20,7 +20,6 @@
package org.onap.so.bpmn.common.adapter.sdnc;
import static org.junit.Assert.assertEquals;
-
import org.junit.Before;
import org.junit.Test;
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerServiceTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerServiceTest.java
index 051107bb13..c58af6b02f 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerServiceTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerServiceTest.java
@@ -23,7 +23,6 @@ package org.onap.so.bpmn.common.workflow.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncResourceExceptionHandlingTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncResourceExceptionHandlingTest.java
index ff5e18c210..62b582ea8e 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncResourceExceptionHandlingTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/common/workflow/service/WorkflowAsyncResourceExceptionHandlingTest.java
@@ -16,20 +16,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
- */
+ */
package org.onap.so.bpmn.common.workflow.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import javax.ws.rs.core.Response;
-
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
import org.junit.Test;
@@ -38,41 +35,41 @@ import org.onap.so.bpmn.common.workflow.context.WorkflowResponse;
public class WorkflowAsyncResourceExceptionHandlingTest {
- @Test
- @Deployment(resources = { "testAsyncResource.bpmn" })
- public void asyncRequestSuccess() throws InterruptedException {
- VariableMapImpl variableMap = new VariableMapImpl();
+ @Test
+ @Deployment(resources = {"testAsyncResource.bpmn"})
+ public void asyncRequestSuccess() throws InterruptedException {
+ VariableMapImpl variableMap = new VariableMapImpl();
- Map<String, Object> variableValueType = new HashMap<>();
+ Map<String, Object> variableValueType = new HashMap<>();
- Map<String, Object> requestMsg = new HashMap<>();
- requestMsg.put("value", "");
- requestMsg.put("type", "String");
+ Map<String, Object> requestMsg = new HashMap<>();
+ requestMsg.put("value", "");
+ requestMsg.put("type", "String");
- Map<String, Object> msorequestId = new HashMap<>();
- msorequestId.put("type", "String");
- msorequestId.put("value",UUID.randomUUID().toString());
+ Map<String, Object> msorequestId = new HashMap<>();
+ msorequestId.put("type", "String");
+ msorequestId.put("value", UUID.randomUUID().toString());
- Map<String, Object> timeout = new HashMap<>();
- timeout.put("type", "String");
- timeout.put("value","5");
+ Map<String, Object> timeout = new HashMap<>();
+ timeout.put("type", "String");
+ timeout.put("value", "5");
- variableValueType.put("testAsyncRequestMsg", requestMsg);
- variableValueType.put("mso-request-id", msorequestId);
- variableValueType.put("mso-service-request-timeout", timeout);
+ variableValueType.put("testAsyncRequestMsg", requestMsg);
+ variableValueType.put("mso-request-id", msorequestId);
+ variableValueType.put("mso-service-request-timeout", timeout);
- variableMap.put("variables", variableValueType);
- WorkflowAsyncResource workflowAsyncResource = new WorkflowAsyncResource();
- workflowAsyncResource.setProcessor(new WorkflowProcessor());
- Response res = workflowAsyncResource.startProcessInstanceByKey("randomKey", variableMap);
- assertEquals(500,res.getStatus());
- WorkflowResponse workflowResponse = (WorkflowResponse)res.getEntity();
- assertNotNull(workflowResponse);
- assertEquals(500, workflowResponse.getMessageCode());
- assertTrue(workflowResponse.getResponse().startsWith("Error occurred while executing the process:"));
- assertEquals("Fail", workflowResponse.getMessage());
+ variableMap.put("variables", variableValueType);
+ WorkflowAsyncResource workflowAsyncResource = new WorkflowAsyncResource();
+ workflowAsyncResource.setProcessor(new WorkflowProcessor());
+ Response res = workflowAsyncResource.startProcessInstanceByKey("randomKey", variableMap);
+ assertEquals(500, res.getStatus());
+ WorkflowResponse workflowResponse = (WorkflowResponse) res.getEntity();
+ assertNotNull(workflowResponse);
+ assertEquals(500, workflowResponse.getMessageCode());
+ assertTrue(workflowResponse.getResponse().startsWith("Error occurred while executing the process:"));
+ assertEquals("Fail", workflowResponse.getMessage());
- }
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/FlakyTests.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/FlakyTests.java
index 5b5e17c5fc..1c3583d452 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/FlakyTests.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/FlakyTests.java
@@ -21,5 +21,5 @@
package org.onap.so.bpmn.infrastructure;
public interface FlakyTests {
- /* category marker */
+ /* category marker */
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java
index 5cc0281407..3734510eed 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java
@@ -25,10 +25,8 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate;
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_CORRELATION_ID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID;
-
import java.util.HashMap;
import java.util.Map;
-
import java.util.UUID;
import org.assertj.core.api.Assertions;
import org.assertj.core.data.MapEntry;
@@ -64,25 +62,17 @@ public class CreateAndActivatePnfResourceTest extends BaseIntegrationTest {
// given
variables.put(PNF_CORRELATION_ID, PnfManagementTestImpl.ID_WITH_ENTRY);
// when
- ProcessInstance instance = runtimeService
- .startProcessInstanceByKey("CreateAndActivatePnfResource", "businessKey", variables);
+ ProcessInstance instance =
+ runtimeService.startProcessInstanceByKey("CreateAndActivatePnfResource", "businessKey", variables);
assertThat(instance).isWaitingAt("WaitForDmaapPnfReadyNotification").isWaitingFor("WorkflowMessage");
dmaapClientTestImpl.sendMessage();
// then
- assertThat(instance).isEnded().hasPassedInOrder(
- "CreateAndActivatePnf_StartEvent",
- "CheckInputs",
- "CheckAiiForPnfCorrelationId",
- "DoesAaiContainInfoAboutPnf",
- "AaiEntryExists",
- "InformDmaapClient",
- "WaitForDmaapPnfReadyNotification",
- "CreateRelationId",
- "AaiEntryUpdated"
- );
- Assertions.assertThat(pnfManagementTest.getServiceAndPnfRelationMap()).
- containsOnly(MapEntry.entry(SERVICE_INSTANCE_ID, PnfManagementTestImpl.ID_WITH_ENTRY));
+ assertThat(instance).isEnded().hasPassedInOrder("CreateAndActivatePnf_StartEvent", "CheckInputs",
+ "CheckAiiForPnfCorrelationId", "DoesAaiContainInfoAboutPnf", "AaiEntryExists", "InformDmaapClient",
+ "WaitForDmaapPnfReadyNotification", "CreateRelationId", "AaiEntryUpdated");
+ Assertions.assertThat(pnfManagementTest.getServiceAndPnfRelationMap())
+ .containsOnly(MapEntry.entry(SERVICE_INSTANCE_ID, PnfManagementTestImpl.ID_WITH_ENTRY));
}
@Test
@@ -90,26 +80,17 @@ public class CreateAndActivatePnfResourceTest extends BaseIntegrationTest {
// given
variables.put(PNF_CORRELATION_ID, PnfManagementTestImpl.ID_WITHOUT_ENTRY);
// when
- ProcessInstance instance = runtimeService
- .startProcessInstanceByKey("CreateAndActivatePnfResource", "businessKey", variables);
+ ProcessInstance instance =
+ runtimeService.startProcessInstanceByKey("CreateAndActivatePnfResource", "businessKey", variables);
assertThat(instance).isWaitingAt("WaitForDmaapPnfReadyNotification").isWaitingFor("WorkflowMessage");
dmaapClientTestImpl.sendMessage();
// then
- assertThat(instance).isEnded().hasPassedInOrder(
- "CreateAndActivatePnf_StartEvent",
- "CheckInputs",
- "CheckAiiForPnfCorrelationId",
- "DoesAaiContainInfoAboutPnf",
- "CreatePnfEntryInAai",
- "AaiEntryExists",
- "InformDmaapClient",
- "WaitForDmaapPnfReadyNotification",
- "CreateRelationId",
- "AaiEntryUpdated"
- );
+ assertThat(instance).isEnded().hasPassedInOrder("CreateAndActivatePnf_StartEvent", "CheckInputs",
+ "CheckAiiForPnfCorrelationId", "DoesAaiContainInfoAboutPnf", "CreatePnfEntryInAai", "AaiEntryExists",
+ "InformDmaapClient", "WaitForDmaapPnfReadyNotification", "CreateRelationId", "AaiEntryUpdated");
Assertions.assertThat(pnfManagementTest.getCreated()).containsOnlyKeys(PnfManagementTestImpl.ID_WITHOUT_ENTRY);
- Assertions.assertThat(pnfManagementTest.getServiceAndPnfRelationMap()).
- containsOnly(MapEntry.entry(SERVICE_INSTANCE_ID, PnfManagementTestImpl.ID_WITHOUT_ENTRY));
+ Assertions.assertThat(pnfManagementTest.getServiceAndPnfRelationMap())
+ .containsOnly(MapEntry.entry(SERVICE_INSTANCE_ID, PnfManagementTestImpl.ID_WITHOUT_ENTRY));
}
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java
index 6a5f9fac74..e7ff69ab3b 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.infrastructure.pnf.delegate;
import java.util.Objects;
-
import org.onap.so.bpmn.infrastructure.pnf.dmaap.DmaapClient;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/AbstractTestBase.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/AbstractTestBase.java
index 8c31a021ae..65b1962048 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/AbstractTestBase.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/AbstractTestBase.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -22,26 +17,25 @@ package org.onap.so.bpmn.vcpe;
import org.onap.so.BaseIntegrationTest;
import org.onap.so.bpmn.infrastructure.FlakyTests;
-
import groovy.lang.Category;
@Category(FlakyTests.class)
public class AbstractTestBase extends BaseIntegrationTest {
-
-
- public static final String CUST = "SDN-ETHERNET-INTERNET";
- public static final String SVC = "123456789";
- public static final String INST = "MIS%252F1604%252F0026%252FSW_INTERNET";
- public static final String PARENT_INST = "MIS%252F1604%252F0027%252FSW_INTERNET";
- public static final String ARID = "arId-1";
- public static final String ARVERS = "1490627351232";
-
- public static final String DEC_INST = "MIS%2F1604%2F0026%2FSW_INTERNET";
- public static final String DEC_PARENT_INST = "MIS%2F1604%2F0027%2FSW_INTERNET";
-
- public static final String VAR_SUCCESS_IND = "SuccessIndicator";
- public static final String VAR_WFEX = "SavedWorkflowException1";
- public static final String VAR_RESP_CODE = "CMSO_ResponseCode";
- public static final String VAR_COMP_REQ = "CompleteMsoProcessRequest";
+
+
+ public static final String CUST = "SDN-ETHERNET-INTERNET";
+ public static final String SVC = "123456789";
+ public static final String INST = "MIS%252F1604%252F0026%252FSW_INTERNET";
+ public static final String PARENT_INST = "MIS%252F1604%252F0027%252FSW_INTERNET";
+ public static final String ARID = "arId-1";
+ public static final String ARVERS = "1490627351232";
+
+ public static final String DEC_INST = "MIS%2F1604%2F0026%2FSW_INTERNET";
+ public static final String DEC_PARENT_INST = "MIS%2F1604%2F0027%2FSW_INTERNET";
+
+ public static final String VAR_SUCCESS_IND = "SuccessIndicator";
+ public static final String VAR_WFEX = "SavedWorkflowException1";
+ public static final String VAR_RESP_CODE = "CMSO_ResponseCode";
+ public static final String VAR_COMP_REQ = "CompleteMsoProcessRequest";
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/CreateVcpeResCustServiceIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/CreateVcpeResCustServiceIT.java
index aa65474acc..bdc24875f0 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/CreateVcpeResCustServiceIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/CreateVcpeResCustServiceIT.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -50,12 +45,10 @@ import static org.onap.so.bpmn.mock.StubResponseDatabase.MockPostRequestDB;
import static org.onap.so.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB;
import static org.onap.so.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter;
import static org.onap.so.bpmn.mock.StubResponseVNFAdapter.mockVNFPost;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.so.bpmn.common.BPMNUtil;
@@ -65,58 +58,68 @@ import org.onap.so.bpmn.mock.StubResponseOof;
public class CreateVcpeResCustServiceIT extends AbstractTestBase {
- private static final String PROCNAME = "CreateVcpeResCustService";
- private static final String Prefix = "CVRCS_";
-
- private final CallbackSet callbacks = new CallbackSet();
- private final String request;
-
- @Before
- public void init(){
- BPMNUtil.cleanHistory(processEngine);
- }
-
- public CreateVcpeResCustServiceIT() throws IOException {
-
- callbacks.put("oof", JSON, "oofResponse", FileUtil.readResourceFile("__files/VCPE/CreateVcpeResCustService/oofCallbackInfraVnf.json"));
- callbacks.put("assign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyAssignCallback.xml"));
- callbacks.put("create", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyCreateCallback.xml"));
- callbacks.put("activate", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyActivateCallback.xml"));
- callbacks.put("queryTXC", FileUtil.readResourceFile("__files/VCPE/CreateVcpeResCustService/SDNCTopologyQueryTXCCallback.xml"));
- callbacks.put("queryBRG", FileUtil.readResourceFile("__files/VCPE/CreateVcpeResCustService/SDNCTopologyQueryBRGCallback.xml"));
- callbacks.put("deactivate", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallback.xml"));
- callbacks.put("delete", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeleteCallback.xml"));
- callbacks.put("unassign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyUnassignCallback.xml"));
-
- callbacks.put("query", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyQueryCallback.xml"));
- callbacks.put("queryVnf", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyQueryCallbackVnf.xml"));
- callbacks.put("queryModuleNoVnf", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyQueryCallbackVfModuleNoVnf.xml"));
- callbacks.put("queryModule", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyQueryCallbackVfModule.xml"));
- callbacks.put("vnfCreate", FileUtil.readResourceFile("__files/VfModularity/VNFAdapterRestCreateCallback.xml"));
-
- request = FileUtil.readResourceFile("__files/VCPE/CreateVcpeResCustService/requestNoSIName.json");
- }
-
- @Test
- public void testCreateVcpeResCustService_Success() throws Exception {
- System.out.println("starting: testCreateVcpeResCustService_Success\n");
- MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef", "2","VCPE/CreateVcpeResCustService/getCatalogServiceResourcesData.json");
- MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef", "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesData.json");
- MockGetCustomer(wireMockServer, CUST, "VCPE/CreateVcpeResCustService/getCustomer.xml");
- StubResponseOof.mockOof(wireMockServer);
- // TODO: the SI should NOT have to be URL-encoded yet again!
- MockPutServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"), "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"), "GenericFlows/getServiceInstance.xml");
-
- MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ private static final String PROCNAME = "CreateVcpeResCustService";
+ private static final String Prefix = "CVRCS_";
+
+ private final CallbackSet callbacks = new CallbackSet();
+ private final String request;
+
+ @Before
+ public void init() {
+ BPMNUtil.cleanHistory(processEngine);
+ }
+
+ public CreateVcpeResCustServiceIT() throws IOException {
+
+ callbacks.put("oof", JSON, "oofResponse",
+ FileUtil.readResourceFile("__files/VCPE/CreateVcpeResCustService/oofCallbackInfraVnf.json"));
+ callbacks.put("assign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyAssignCallback.xml"));
+ callbacks.put("create", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyCreateCallback.xml"));
+ callbacks.put("activate", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyActivateCallback.xml"));
+ callbacks.put("queryTXC",
+ FileUtil.readResourceFile("__files/VCPE/CreateVcpeResCustService/SDNCTopologyQueryTXCCallback.xml"));
+ callbacks.put("queryBRG",
+ FileUtil.readResourceFile("__files/VCPE/CreateVcpeResCustService/SDNCTopologyQueryBRGCallback.xml"));
+ callbacks.put("deactivate",
+ FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallback.xml"));
+ callbacks.put("delete", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeleteCallback.xml"));
+ callbacks.put("unassign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyUnassignCallback.xml"));
+
+ callbacks.put("query", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyQueryCallback.xml"));
+ callbacks.put("queryVnf", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyQueryCallbackVnf.xml"));
+ callbacks.put("queryModuleNoVnf",
+ FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyQueryCallbackVfModuleNoVnf.xml"));
+ callbacks.put("queryModule",
+ FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyQueryCallbackVfModule.xml"));
+ callbacks.put("vnfCreate", FileUtil.readResourceFile("__files/VfModularity/VNFAdapterRestCreateCallback.xml"));
+
+ request = FileUtil.readResourceFile("__files/VCPE/CreateVcpeResCustService/requestNoSIName.json");
+ }
+
+ @Test
+ public void testCreateVcpeResCustService_Success() throws Exception {
+ System.out.println("starting: testCreateVcpeResCustService_Success\n");
+ MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef", "2",
+ "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesData.json");
+ MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef",
+ "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesData.json");
+ MockGetCustomer(wireMockServer, CUST, "VCPE/CreateVcpeResCustService/getCustomer.xml");
+ StubResponseOof.mockOof(wireMockServer);
+ // TODO: the SI should NOT have to be URL-encoded yet again!
+ MockPutServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"),
+ "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"),
+ "GenericFlows/getServiceInstance.xml");
+
+ MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
MockGetGenericVnfByIdWithDepth(wireMockServer, ".*", 1, "VCPE/CreateVcpeResCustService/GenericVnf.xml");
- MockPutGenericVnf(wireMockServer, ".*");
+ MockPutGenericVnf(wireMockServer, ".*");
MockPatchGenericVnf(wireMockServer, ".*");
MockGetGenericVnfByIdWithPriority(wireMockServer, ".*", ".*", 200, "VfModularity/VfModule-new.xml", 5);
@@ -124,46 +127,52 @@ public class CreateVcpeResCustServiceIT extends AbstractTestBase {
MockPutVfModuleIdNoResponse(wireMockServer, ".*", "PCRF", ".*");
MockPutNetwork(wireMockServer, ".*", "VfModularity/AddNetworkPolicy_AAIResponse_Success.xml", 200);
- MockGetNetworkPolicyfqdn(wireMockServer, ".*","CreateNetworkV2/createNetwork_queryNetworkPolicy_AAIResponse_Success.xml",200);
- MockNodeQueryServiceInstanceByName_404(wireMockServer, ".*");
-
- mockVNFPost(wireMockServer, "", 202, ".*");
+ MockGetNetworkPolicyfqdn(wireMockServer, ".*",
+ "CreateNetworkV2/createNetwork_queryNetworkPolicy_AAIResponse_Success.xml", 200);
+ MockNodeQueryServiceInstanceByName_404(wireMockServer, ".*");
+
+ mockVNFPost(wireMockServer, "", 202, ".*");
+
+ wireMockServer.stubFor(post(urlMatching("/services/rest/v1/vnfs" + ".*" + "/vf-modules"))
+ .willReturn(aResponse().withStatus(202)));
+ wireMockServer
+ .stubFor(get(urlMatching(".*/business/owning-entities?.*")).willReturn(aResponse().withStatus(404)));
+ wireMockServer.stubFor(put(urlMatching(".*/business/owning-entities/owning-entity/.*"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(put(urlMatching(
+ ".*/business/owning-entities/owning-entity/038d99af-0427-42c2-9d15-971b99b9b489/relationship-list/relationship"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(put(urlMatching(".*/query?.*")).willReturn(aResponse().withStatus(200)));
+ MockPostRequestDB(wireMockServer);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+ mockSDNCAdapter(wireMockServer, 200);
- wireMockServer.stubFor(post(urlMatching("/services/rest/v1/vnfs" + ".*" + "/vf-modules" )).willReturn(aResponse().withStatus(202)));
- wireMockServer.stubFor(get(urlMatching(".*/business/owning-entities?.*")).willReturn(aResponse().withStatus(404)));
- wireMockServer.stubFor(put(urlMatching(".*/business/owning-entities/owning-entity/.*")).willReturn(aResponse().withStatus(200)));
- wireMockServer.stubFor(put(urlMatching(".*/business/owning-entities/owning-entity/038d99af-0427-42c2-9d15-971b99b9b489/relationship-list/relationship")).willReturn(aResponse().withStatus(200)));
- wireMockServer.stubFor(put(urlMatching(".*/query?.*")).willReturn(aResponse().withStatus(200)));
- MockPostRequestDB(wireMockServer);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
- mockSDNCAdapter(wireMockServer, 200);
-
- Map<String, Object> variables = setupVariables();
+ Map<String, Object> variables = setupVariables();
- String businessKey = UUID.randomUUID().toString();
- invokeAsyncProcess(PROCNAME, "v1", businessKey, request, variables);
+ String businessKey = UUID.randomUUID().toString();
+ invokeAsyncProcess(PROCNAME, "v1", businessKey, request, variables);
injectWorkflowMessages(callbacks, "oof");
- // for SI
- injectSDNCCallbacks(callbacks, "assign");
- // for TXC
- injectSDNCCallbacks(callbacks, "assign");
- injectSDNCCallbacks(callbacks, "create");
- injectSDNCCallbacks(callbacks, "activate");
- injectSDNCCallbacks(callbacks, "queryTXC");
+ // for SI
+ injectSDNCCallbacks(callbacks, "assign");
+ // for TXC
+ injectSDNCCallbacks(callbacks, "assign");
+ injectSDNCCallbacks(callbacks, "create");
+ injectSDNCCallbacks(callbacks, "activate");
+ injectSDNCCallbacks(callbacks, "queryTXC");
// For VNF
injectSDNCCallbacks(callbacks, "assign");
injectSDNCCallbacks(callbacks, "assign");
injectSDNCCallbacks(callbacks, "queryModule");
injectSDNCCallbacks(callbacks, "activate");
- //VF Module
+ // VF Module
injectSDNCCallbacks(callbacks, "queryModule");
injectSDNCCallbacks(callbacks, "assign");
injectSDNCCallbacks(callbacks, "queryModule");
injectSDNCCallbacks(callbacks, "queryModule");
- injectSDNCCallbacks(callbacks, "assign");
- injectSDNCCallbacks(callbacks, "queryModuleNoVnf");
+ injectSDNCCallbacks(callbacks, "assign");
+ injectSDNCCallbacks(callbacks, "queryModuleNoVnf");
injectVNFRestCallbacks(callbacks, "vnfCreate");
injectSDNCCallbacks(callbacks, "activate");
@@ -173,208 +182,233 @@ public class CreateVcpeResCustServiceIT extends AbstractTestBase {
injectSDNCCallbacks(callbacks, "activate");
injectSDNCCallbacks(callbacks, "queryBRG");
- waitForProcessEnd(businessKey, 10000);
-
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
- System.out.println("workflowException:\n" + workflowException);
-
- String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix+VAR_COMP_REQ);
- System.out.println("completionReq:\n" + completionReq);
-
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME+VAR_SUCCESS_IND));
- assertEquals("200", BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
- assertEquals(null, workflowException);
- assertTrue(completionReq.indexOf("request-id>testRequestId<") >= 0);
- assertTrue(completionReq.indexOf("action>CREATE<") >= 0);
- assertTrue(completionReq.indexOf("source>VID<") >= 0);
-
- assertEquals("1", BPMNUtil.getVariable(processEngine, PROCNAME, Prefix+"VnfsCreatedCount"));
- }
-
- @Test
- public void testCreateVcpeResCustService_NoParts() throws Exception {
- System.out.println("starting: testCreateVcpeResCustService_NoParts\n" );
- MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef", "2", "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesNoData.json");
- MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef", "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesNoData.json");
- MockGetCustomer(wireMockServer, CUST, "VCPE/CreateVcpeResCustService/getCustomer.xml");
-
- // TODO: the SI should NOT have to be URL-encoded yet again!
- MockPutServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"), "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"), "GenericFlows/getServiceInstance.xml");
-
- MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
-
- // TODO: should these really be PARENT_INST, or should they be INST?
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
-
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+ waitForProcessEnd(businessKey, 10000);
+
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
+ System.out.println("workflowException:\n" + workflowException);
+
+ String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix + VAR_COMP_REQ);
+ System.out.println("completionReq:\n" + completionReq);
+
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME + VAR_SUCCESS_IND));
+ assertEquals("200", BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
+ assertEquals(null, workflowException);
+ assertTrue(completionReq.indexOf("request-id>testRequestId<") >= 0);
+ assertTrue(completionReq.indexOf("action>CREATE<") >= 0);
+ assertTrue(completionReq.indexOf("source>VID<") >= 0);
+
+ assertEquals("1", BPMNUtil.getVariable(processEngine, PROCNAME, Prefix + "VnfsCreatedCount"));
+ }
+
+ @Test
+ public void testCreateVcpeResCustService_NoParts() throws Exception {
+ System.out.println("starting: testCreateVcpeResCustService_NoParts\n");
+ MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef", "2",
+ "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesNoData.json");
+ MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef",
+ "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesNoData.json");
+ MockGetCustomer(wireMockServer, CUST, "VCPE/CreateVcpeResCustService/getCustomer.xml");
+
+ // TODO: the SI should NOT have to be URL-encoded yet again!
+ MockPutServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"),
+ "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"),
+ "GenericFlows/getServiceInstance.xml");
+
+ MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+
+ // TODO: should these really be PARENT_INST, or should they be INST?
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
StubResponseOof.mockOof(wireMockServer);
- wireMockServer.stubFor(get(urlMatching(".*/business/owning-entities?.*")).willReturn(aResponse().withStatus(404)));
- wireMockServer.stubFor(put(urlMatching(".*/business/owning-entities/owning-entity/.*")).willReturn(aResponse().withStatus(200)));
- wireMockServer.stubFor(put(urlMatching(".*/business/owning-entities/owning-entity/038d99af-0427-42c2-9d15-971b99b9b489/relationship-list/relationship")).willReturn(aResponse().withStatus(200)));
+ wireMockServer
+ .stubFor(get(urlMatching(".*/business/owning-entities?.*")).willReturn(aResponse().withStatus(404)));
+ wireMockServer.stubFor(put(urlMatching(".*/business/owning-entities/owning-entity/.*"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(put(urlMatching(
+ ".*/business/owning-entities/owning-entity/038d99af-0427-42c2-9d15-971b99b9b489/relationship-list/relationship"))
+ .willReturn(aResponse().withStatus(200)));
wireMockServer.stubFor(put(urlMatching(".*/query?.*")).willReturn(aResponse().withStatus(200)));
MockPostRequestDB(wireMockServer);
mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = setupVariables();
- String businessKey = UUID.randomUUID().toString();
- invokeAsyncProcess(PROCNAME, "v1", businessKey, request, variables);
+ Map<String, Object> variables = setupVariables();
+
+ String businessKey = UUID.randomUUID().toString();
+ invokeAsyncProcess(PROCNAME, "v1", businessKey, request, variables);
+
+ injectWorkflowMessages(callbacks, "oof");
+ // for SI
+ injectSDNCCallbacks(callbacks, "assign");
+
+ waitForProcessEnd(businessKey, 10000);
+
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
+ System.out.println("workflowException:\n" + workflowException);
+
+ String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix + VAR_COMP_REQ);
+ System.out.println("completionReq:\n" + completionReq);
+
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME + VAR_SUCCESS_IND));
+ assertEquals("200", BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
+ assertEquals(null, workflowException);
+ assertTrue(completionReq.indexOf("request-id>testRequestId<") >= 0);
+ assertTrue(completionReq.indexOf("action>CREATE<") >= 0);
+ assertTrue(completionReq.indexOf("source>VID<") >= 0);
+
+ assertEquals("0", BPMNUtil.getVariable(processEngine, PROCNAME, Prefix + "VnfsCreatedCount"));
+ }
+
+ @Test
+ public void testCreateVcpeResCustService_Fault_NoRollback() throws Exception {
+ System.out.println("starting: testCreateVcpeResCustService_Fault_NoRollback\n");
+ MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef", "2",
+ "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesData.json");
+ MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef",
+ "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesData.json");
+ MockGetCustomer(wireMockServer, CUST, "VCPE/CreateVcpeResCustService/getCustomer.xml");
+
+ // TODO: the SI should NOT have to be URL-encoded yet again!
+ MockPutServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"),
+ "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"),
+ "GenericFlows/getServiceInstance.xml");
+
+ MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance_500(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+
+ mockSDNCAdapter(wireMockServer, 404);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ StubResponseOof.mockOof(wireMockServer);
+ wireMockServer
+ .stubFor(get(urlMatching(".*/business/owning-entities?.*")).willReturn(aResponse().withStatus(404)));
+ wireMockServer.stubFor(put(urlMatching(".*/business/owning-entities/owning-entity/.*"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(put(urlMatching(
+ ".*/business/owning-entities/owning-entity/038d99af-0427-42c2-9d15-971b99b9b489/relationship-list/relationship"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(put(urlMatching(".*/query?.*")).willReturn(aResponse().withStatus(200)));
+ MockPostRequestDB(wireMockServer);
+
+ Map<String, Object> variables = setupVariables();
+
+ String businessKey = UUID.randomUUID().toString();
+ invokeAsyncProcess(PROCNAME, "v1", businessKey, request, variables);
injectWorkflowMessages(callbacks, "oof");
- // for SI
- injectSDNCCallbacks(callbacks, "assign");
-
- waitForProcessEnd(businessKey, 10000);
-
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
- System.out.println("workflowException:\n" + workflowException);
-
- String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix+VAR_COMP_REQ);
- System.out.println("completionReq:\n" + completionReq);
-
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME+VAR_SUCCESS_IND));
- assertEquals("200", BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
- assertEquals(null, workflowException);
- assertTrue(completionReq.indexOf("request-id>testRequestId<") >= 0);
- assertTrue(completionReq.indexOf("action>CREATE<") >= 0);
- assertTrue(completionReq.indexOf("source>VID<") >= 0);
-
- assertEquals("0", BPMNUtil.getVariable(processEngine, PROCNAME, Prefix+"VnfsCreatedCount"));
- }
-
- @Test
- public void testCreateVcpeResCustService_Fault_NoRollback() throws Exception {
- System.out.println("starting: testCreateVcpeResCustService_Fault_NoRollback\n");
- MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef", "2", "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesData.json");
- MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef", "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesData.json");
- MockGetCustomer(wireMockServer, CUST, "VCPE/CreateVcpeResCustService/getCustomer.xml");
-
- // TODO: the SI should NOT have to be URL-encoded yet again!
- MockPutServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"), "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"), "GenericFlows/getServiceInstance.xml");
-
- MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance_500(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
-
- mockSDNCAdapter(wireMockServer, 404);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ waitForProcessEnd(businessKey, 100000);
+
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
+ System.out.println("workflowException:\n" + workflowException);
+
+ String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix + VAR_COMP_REQ);
+ System.out.println("completionReq:\n" + completionReq);
+
+ assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME + VAR_SUCCESS_IND));
+ assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
+ assertNotNull(workflowException);
+
+ BPMNUtil.assertNoProcessInstance(processEngine, "DoCreateAllottedResourceBRGRollback");
+ BPMNUtil.assertNoProcessInstance(processEngine, "DoCreateVnfAndModulesRollback");
+ BPMNUtil.assertNoProcessInstance(processEngine, "DoCreateAllottedResourceTXCRollback");
+ }
+
+ @Test
+ public void testCreateVcpeResCustService_Fault_Rollback() throws Exception {
+ System.out.println("starting: testCreateVcpeResCustService_Fault_Rollback\n");
+ MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef", "2",
+ "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesData.json");
+ MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef",
+ "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesData.json");
+ MockGetCustomer(wireMockServer, CUST, "VCPE/CreateVcpeResCustService/getCustomer.xml");
+
+ // TODO: the SI should NOT have to be URL-encoded yet again!
+ MockPutServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"),
+ "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"),
+ "GenericFlows/getServiceInstance.xml");
+
+ MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/CreateVcpeResCustService/arGetById.xml");
+ MockGetAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID,
+ "VCPE/CreateVcpeResCustService/arGetById.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID, ARVERS);
+
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
StubResponseOof.mockOof(wireMockServer);
- wireMockServer.stubFor(get(urlMatching(".*/business/owning-entities?.*")).willReturn(aResponse().withStatus(404)));
- wireMockServer.stubFor(put(urlMatching(".*/business/owning-entities/owning-entity/.*")).willReturn(aResponse().withStatus(200)));
- wireMockServer.stubFor(put(urlMatching(".*/business/owning-entities/owning-entity/038d99af-0427-42c2-9d15-971b99b9b489/relationship-list/relationship")).willReturn(aResponse().withStatus(200)));
+ wireMockServer
+ .stubFor(get(urlMatching(".*/business/owning-entities?.*")).willReturn(aResponse().withStatus(404)));
+ wireMockServer.stubFor(put(urlMatching(".*/business/owning-entities/owning-entity/.*"))
+ .willReturn(aResponse().withStatus(200)));
+ wireMockServer.stubFor(put(urlMatching(
+ ".*/business/owning-entities/owning-entity/038d99af-0427-42c2-9d15-971b99b9b489/relationship-list/relationship"))
+ .willReturn(aResponse().withStatus(200)));
wireMockServer.stubFor(put(urlMatching(".*/query?.*")).willReturn(aResponse().withStatus(200)));
MockPostRequestDB(wireMockServer);
-
- Map<String, Object> variables = setupVariables();
+ String req = FileUtil.readResourceFile("__files/VCPE/CreateVcpeResCustService/requestRollback.json");
+
+ Map<String, Object> variables = setupVariables();
- String businessKey = UUID.randomUUID().toString();
- invokeAsyncProcess(PROCNAME, "v1", businessKey, request, variables);
+ String businessKey = UUID.randomUUID().toString();
+ invokeAsyncProcess(PROCNAME, "v1", businessKey, req, variables);
injectWorkflowMessages(callbacks, "oof");
-
- waitForProcessEnd(businessKey, 100000);
-
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
- System.out.println("workflowException:\n" + workflowException);
-
- String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix+VAR_COMP_REQ);
- System.out.println("completionReq:\n" + completionReq);
-
- assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME+VAR_SUCCESS_IND));
- assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
- assertNotNull(workflowException);
-
- BPMNUtil.assertNoProcessInstance(processEngine, "DoCreateAllottedResourceBRGRollback");
- BPMNUtil.assertNoProcessInstance(processEngine, "DoCreateVnfAndModulesRollback");
- BPMNUtil.assertNoProcessInstance(processEngine, "DoCreateAllottedResourceTXCRollback");
- }
-
- @Test
- public void testCreateVcpeResCustService_Fault_Rollback() throws Exception {
- System.out.println("starting: testCreateVcpeResCustService_Fault_Rollback\n");
- MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef", "2", "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesData.json");
- MockGetServiceResourcesCatalogData(wireMockServer, "uuid-miu-svc-011-abcdef", "VCPE/CreateVcpeResCustService/getCatalogServiceResourcesData.json");
- MockGetCustomer(wireMockServer, CUST, "VCPE/CreateVcpeResCustService/getCustomer.xml");
-
- // TODO: the SI should NOT have to be URL-encoded yet again!
- MockPutServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"), "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST.replace("%", "%25"), "GenericFlows/getServiceInstance.xml");
-
- MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/CreateVcpeResCustService/arGetById.xml");
- MockGetAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID, "VCPE/CreateVcpeResCustService/arGetById.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID, ARVERS);
-
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- StubResponseOof.mockOof(wireMockServer);
- wireMockServer.stubFor(get(urlMatching(".*/business/owning-entities?.*")).willReturn(aResponse().withStatus(404)));
- wireMockServer.stubFor(put(urlMatching(".*/business/owning-entities/owning-entity/.*")).willReturn(aResponse().withStatus(200)));
- wireMockServer.stubFor(put(urlMatching(".*/business/owning-entities/owning-entity/038d99af-0427-42c2-9d15-971b99b9b489/relationship-list/relationship")).willReturn(aResponse().withStatus(200)));
- wireMockServer.stubFor(put(urlMatching(".*/query?.*")).willReturn(aResponse().withStatus(200)));
- MockPostRequestDB(wireMockServer);
- String req = FileUtil.readResourceFile("__files/VCPE/CreateVcpeResCustService/requestRollback.json");
-
- Map<String, Object> variables = setupVariables();
-
- String businessKey = UUID.randomUUID().toString();
- invokeAsyncProcess(PROCNAME, "v1", businessKey, req, variables);
-
- injectWorkflowMessages(callbacks, "oof");
- // for SI
- injectSDNCCallbacks(callbacks, "assign");
-
- // for TXC
- injectSDNCCallbacks(callbacks, "assign");
- injectSDNCCallbacks(callbacks, "create");
-
- waitForProcessEnd(businessKey, 10000);
-
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
- System.out.println("workflowException:\n" + workflowException);
-
- String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix+VAR_COMP_REQ);
- System.out.println("completionReq:\n" + completionReq);
-
- assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME+VAR_SUCCESS_IND));
- assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
- assertEquals(null, completionReq);
- assertNotNull(workflowException);
-
- BPMNUtil.assertAnyProcessInstanceFinished(processEngine, "DoCreateServiceInstanceRollback");
- }
-
- // *****************
- // Utility Section
- // *****************
-
- // Success Scenario
- private Map<String, Object> setupVariables() {
- Map<String, Object> variables = new HashMap<>();
- variables.put("requestId", "testRequestId");
- variables.put("request-id", "testRequestId");
- variables.put("serviceInstanceId", DEC_INST);
- variables.put("allottedResourceId", ARID);
- variables.put("URN_mso_workflow_aai_distribution_delay", "PT5S");
- return variables;
-
- }
+ // for SI
+ injectSDNCCallbacks(callbacks, "assign");
+
+ // for TXC
+ injectSDNCCallbacks(callbacks, "assign");
+ injectSDNCCallbacks(callbacks, "create");
+
+ waitForProcessEnd(businessKey, 10000);
+
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
+ System.out.println("workflowException:\n" + workflowException);
+
+ String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix + VAR_COMP_REQ);
+ System.out.println("completionReq:\n" + completionReq);
+
+ assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME + VAR_SUCCESS_IND));
+ assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
+ assertEquals(null, completionReq);
+ assertNotNull(workflowException);
+
+ BPMNUtil.assertAnyProcessInstanceFinished(processEngine, "DoCreateServiceInstanceRollback");
+ }
+
+ // *****************
+ // Utility Section
+ // *****************
+
+ // Success Scenario
+ private Map<String, Object> setupVariables() {
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("requestId", "testRequestId");
+ variables.put("request-id", "testRequestId");
+ variables.put("serviceInstanceId", DEC_INST);
+ variables.put("allottedResourceId", ARID);
+ variables.put("URN_mso_workflow_aai_distribution_delay", "PT5S");
+ return variables;
+
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DeleteVcpeResCustServiceIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DeleteVcpeResCustServiceIT.java
index aaabf59e6b..4a03aa9fd4 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DeleteVcpeResCustServiceIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DeleteVcpeResCustServiceIT.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -37,255 +32,244 @@ import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchAllottedResource;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockQueryAllottedResourceById;
import static org.onap.so.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB;
import static org.onap.so.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter;
-
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.so.bpmn.common.BPMNUtil;
import org.onap.so.bpmn.mock.FileUtil;
-
import com.github.tomakehurst.wiremock.stubbing.Scenario;
public class DeleteVcpeResCustServiceIT extends AbstractTestBase {
- private static final String PROCNAME = "DeleteVcpeResCustService";
- private static final String Prefix = "DVRCS_";
- private static final String AR_BRG_ID = "ar-brgB";
- private static final String AR_TXC_ID = "ar-txcA";
-
- private final CallbackSet callbacks = new CallbackSet();
- private final String request;
-
- public DeleteVcpeResCustServiceIT() throws IOException {
- callbacks.put("deactivate", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallback.xml"));
- callbacks.put("delete", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeleteCallback.xml"));
- callbacks.put("unassign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyUnassignCallback.xml"));
-
- request = FileUtil.readResourceFile("__files/VCPE/DeleteVcpeResCustService/request.json");
- }
-
- @Before
- public void init(){
- BPMNUtil.cleanHistory(processEngine);
- }
-
- @Test
- public void testDeleteVcpeResCustService_Success() throws Exception {
- logStart();
- MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
-
- // TODO: use INST instead of DEC_INST
- /*
- * Seems to be a bug as they
- * fail to URL-encode the SI id before performing the query so we'll
- * add a stub for that case, too.
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
-
- /*
- * cannot use MockGetServiceInstance(wireMockServer, ), because we need to return
- * different responses as we traverse through the flow
- */
-
- // initially, the SI includes the ARs
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + CUST + "/service-subscriptions/service-subscription/" + SVC + "/service-instances/service-instance/" + INST))
- .inScenario("SI retrieval")
- .whenScenarioStateIs(Scenario.STARTED)
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VCPE/DeleteVcpeResCustService/getSI.xml"))
- .willSetStateTo("ARs Deleted"));
-
- // once the ARs have been deleted, the SI should be empty
- wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + CUST + "/service-subscriptions/service-subscription/" + SVC + "/service-instances/service-instance/" + INST))
- .inScenario("SI retrieval")
- .whenScenarioStateIs("ARs Deleted")
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
- .withBodyFile("VCPE/DeleteVcpeResCustService/getSIAfterDelArs.xml")));
-
- // for BRG
- MockQueryAllottedResourceById(wireMockServer, AR_BRG_ID, "VCPE/DeleteVcpeResCustService/getBRGArUrlById.xml");
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, AR_BRG_ID, "VCPE/DeleteVcpeResCustService/arGetBRGById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, AR_BRG_ID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, AR_BRG_ID, ARVERS);
-
- // for TXC
- MockQueryAllottedResourceById(wireMockServer, AR_TXC_ID, "VCPE/DeleteVcpeResCustService/getTXCArUrlById.xml");
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, AR_TXC_ID, "VCPE/DeleteVcpeResCustService/arGetTXCById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, AR_TXC_ID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, AR_TXC_ID, ARVERS);
-
- //MockGetGenericVnfById("vnfX.*", "GenericFlows/getGenericVnfByNameResponse.xml");
+ private static final String PROCNAME = "DeleteVcpeResCustService";
+ private static final String Prefix = "DVRCS_";
+ private static final String AR_BRG_ID = "ar-brgB";
+ private static final String AR_TXC_ID = "ar-txcA";
+
+ private final CallbackSet callbacks = new CallbackSet();
+ private final String request;
+
+ public DeleteVcpeResCustServiceIT() throws IOException {
+ callbacks.put("deactivate",
+ FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallback.xml"));
+ callbacks.put("delete", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeleteCallback.xml"));
+ callbacks.put("unassign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyUnassignCallback.xml"));
+
+ request = FileUtil.readResourceFile("__files/VCPE/DeleteVcpeResCustService/request.json");
+ }
+
+ @Before
+ public void init() {
+ BPMNUtil.cleanHistory(processEngine);
+ }
+
+ @Test
+ public void testDeleteVcpeResCustService_Success() throws Exception {
+ logStart();
+ MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
+
+ // TODO: use INST instead of DEC_INST
+ /*
+ * Seems to be a bug as they fail to URL-encode the SI id before performing the query so we'll add a stub for
+ * that case, too.
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
+
+ /*
+ * cannot use MockGetServiceInstance(wireMockServer, ), because we need to return different responses as we
+ * traverse through the flow
+ */
+
+ // initially, the SI includes the ARs
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + CUST
+ + "/service-subscriptions/service-subscription/" + SVC + "/service-instances/service-instance/" + INST))
+ .inScenario("SI retrieval").whenScenarioStateIs(Scenario.STARTED)
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VCPE/DeleteVcpeResCustService/getSI.xml"))
+ .willSetStateTo("ARs Deleted"));
+
+ // once the ARs have been deleted, the SI should be empty
+ wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + CUST
+ + "/service-subscriptions/service-subscription/" + SVC + "/service-instances/service-instance/" + INST))
+ .inScenario("SI retrieval").whenScenarioStateIs("ARs Deleted")
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
+ .withBodyFile("VCPE/DeleteVcpeResCustService/getSIAfterDelArs.xml")));
+
+ // for BRG
+ MockQueryAllottedResourceById(wireMockServer, AR_BRG_ID, "VCPE/DeleteVcpeResCustService/getBRGArUrlById.xml");
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, AR_BRG_ID,
+ "VCPE/DeleteVcpeResCustService/arGetBRGById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, AR_BRG_ID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, AR_BRG_ID, ARVERS);
+
+ // for TXC
+ MockQueryAllottedResourceById(wireMockServer, AR_TXC_ID, "VCPE/DeleteVcpeResCustService/getTXCArUrlById.xml");
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, AR_TXC_ID,
+ "VCPE/DeleteVcpeResCustService/arGetTXCById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, AR_TXC_ID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, AR_TXC_ID, ARVERS);
+
+ // MockGetGenericVnfById("vnfX.*", "GenericFlows/getGenericVnfByNameResponse.xml");
wireMockServer.stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", "text/xml")
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/xml")
.withBodyFile("GenericFlows/getGenericVnfByNameResponse.xml")));
- wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*"))
- .willReturn(aResponse()
- .withStatus(204)
- .withHeader("Content-Type", "text/xml")));
+ wireMockServer.stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*"))
+ .willReturn(aResponse().withStatus(204).withHeader("Content-Type", "text/xml")));
- MockDeleteServiceInstance(wireMockServer, CUST,SVC,INST,SVC);
+ MockDeleteServiceInstance(wireMockServer, CUST, SVC, INST, SVC);
mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = setupVariables(businessKey);
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = setupVariables(businessKey);
- invokeAsyncProcess(PROCNAME, "v1", businessKey, request, variables);
+ invokeAsyncProcess(PROCNAME, "v1", businessKey, request, variables);
- // for BRG
- injectSDNCCallbacks(callbacks, "deactivate");
- injectSDNCCallbacks(callbacks, "delete");
- injectSDNCCallbacks(callbacks, "unassign");
+ // for BRG
+ injectSDNCCallbacks(callbacks, "deactivate");
+ injectSDNCCallbacks(callbacks, "delete");
+ injectSDNCCallbacks(callbacks, "unassign");
- // for VNF1
- injectSDNCCallbacks(callbacks, "deactivate");
- injectSDNCCallbacks(callbacks, "unassign");
+ // for VNF1
+ injectSDNCCallbacks(callbacks, "deactivate");
+ injectSDNCCallbacks(callbacks, "unassign");
- // for VNF2
- injectSDNCCallbacks(callbacks, "deactivate");
- injectSDNCCallbacks(callbacks, "unassign");
+ // for VNF2
+ injectSDNCCallbacks(callbacks, "deactivate");
+ injectSDNCCallbacks(callbacks, "unassign");
- // for TXC
- injectSDNCCallbacks(callbacks, "deactivate");
- injectSDNCCallbacks(callbacks, "delete");
- injectSDNCCallbacks(callbacks, "unassign");
+ // for TXC
+ injectSDNCCallbacks(callbacks, "deactivate");
+ injectSDNCCallbacks(callbacks, "delete");
+ injectSDNCCallbacks(callbacks, "unassign");
- // for SI
- injectSDNCCallbacks(callbacks, "deactivate");
- injectSDNCCallbacks(callbacks, "delete");
+ // for SI
+ injectSDNCCallbacks(callbacks, "deactivate");
+ injectSDNCCallbacks(callbacks, "delete");
- waitForProcessEnd(businessKey, 70000);
- assertTrue(isProcessEnded(businessKey));
+ waitForProcessEnd(businessKey, 70000);
+ assertTrue(isProcessEnded(businessKey));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
- System.out.println("workflowException:\n" + workflowException);
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
+ System.out.println("workflowException:\n" + workflowException);
- String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix+VAR_COMP_REQ);
- System.out.println("completionReq:\n" + completionReq);
+ String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix + VAR_COMP_REQ);
+ System.out.println("completionReq:\n" + completionReq);
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME+VAR_SUCCESS_IND));
- assertEquals("200", BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
- assertNull(workflowException);
- assertTrue(completionReq.contains("<request-id>"+businessKey+"<"));
- assertTrue(completionReq.contains("<action>DELETE<"));
- assertTrue(completionReq.contains("<source>VID<"));
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME + VAR_SUCCESS_IND));
+ assertEquals("200", BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
+ assertNull(workflowException);
+ assertTrue(completionReq.contains("<request-id>" + businessKey + "<"));
+ assertTrue(completionReq.contains("<action>DELETE<"));
+ assertTrue(completionReq.contains("<source>VID<"));
- assertEquals("2", BPMNUtil.getVariable(processEngine, PROCNAME, Prefix+"vnfsDeletedCount"));
+ assertEquals("2", BPMNUtil.getVariable(processEngine, PROCNAME, Prefix + "vnfsDeletedCount"));
- BPMNUtil.assertAnyProcessInstanceFinished(processEngine, "DoDeleteVnfAndModules");
- logEnd();
- }
+ BPMNUtil.assertAnyProcessInstanceFinished(processEngine, "DoDeleteVnfAndModules");
+ logEnd();
+ }
- @Test
- public void testDeleteVcpeResCustService_NoBRG_NoTXC_NoVNF() throws Exception {
- logStart();
- MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
+ @Test
+ public void testDeleteVcpeResCustService_NoBRG_NoTXC_NoVNF() throws Exception {
+ logStart();
+ MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
- // TODO: use INST instead of DEC_INST
- /*
- * Seems to be a bug as they
- * fail to URL-encode the SI id before performing the query so we'll
- * add a stub for that case, too.
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
+ // TODO: use INST instead of DEC_INST
+ /*
+ * Seems to be a bug as they fail to URL-encode the SI id before performing the query so we'll add a stub for
+ * that case, too.
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "VCPE/DeleteVcpeResCustService/getSIAfterDelArs.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "VCPE/DeleteVcpeResCustService/getSIAfterDelArs.xml");
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = setupVariables(businessKey);
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = setupVariables(businessKey);
- invokeAsyncProcess(PROCNAME, "v1", businessKey, request, variables);
+ invokeAsyncProcess(PROCNAME, "v1", businessKey, request, variables);
- // for SI
- injectSDNCCallbacks(callbacks, "deactivate");
- injectSDNCCallbacks(callbacks, "delete");
+ // for SI
+ injectSDNCCallbacks(callbacks, "deactivate");
+ injectSDNCCallbacks(callbacks, "delete");
- waitForProcessEnd(businessKey, 70000);
+ waitForProcessEnd(businessKey, 70000);
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
- System.out.println("workflowException:\n" + workflowException);
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
+ System.out.println("workflowException:\n" + workflowException);
- String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix+VAR_COMP_REQ);
- System.out.println("completionReq:\n" + completionReq);
+ String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix + VAR_COMP_REQ);
+ System.out.println("completionReq:\n" + completionReq);
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME+VAR_SUCCESS_IND));
- assertEquals("200", BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
- assertNull( workflowException);
- assertTrue(completionReq.contains("<request-id>"+businessKey+"<"));
- assertTrue(completionReq.contains("<action>DELETE<"));
- assertTrue(completionReq.contains("<source>VID<"));
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME + VAR_SUCCESS_IND));
+ assertEquals("200", BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
+ assertNull(workflowException);
+ assertTrue(completionReq.contains("<request-id>" + businessKey + "<"));
+ assertTrue(completionReq.contains("<action>DELETE<"));
+ assertTrue(completionReq.contains("<source>VID<"));
- assertEquals("0", BPMNUtil.getVariable(processEngine, PROCNAME, Prefix+"vnfsDeletedCount"));
+ assertEquals("0", BPMNUtil.getVariable(processEngine, PROCNAME, Prefix + "vnfsDeletedCount"));
- BPMNUtil.assertNoProcessInstance(processEngine, "DoDeleteVnfAndModules");
- logEnd();
- }
+ BPMNUtil.assertNoProcessInstance(processEngine, "DoDeleteVnfAndModules");
+ logEnd();
+ }
- @Test
- public void testDeleteVcpeResCustService_Fault() throws Exception {
- logStart();
- MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
+ @Test
+ public void testDeleteVcpeResCustService_Fault() throws Exception {
+ logStart();
+ MockNodeQueryServiceInstanceById(wireMockServer, INST, "GenericFlows/getSIUrlById.xml");
- // TODO: use INST instead of DEC_INST
- /*
- * Seems to be a bug as they
- * fail to URL-encode the SI id before performing the query so we'll
- * add a stub for that case, too.
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
+ // TODO: use INST instead of DEC_INST
+ /*
+ * Seems to be a bug as they fail to URL-encode the SI id before performing the query so we'll add a stub for
+ * that case, too.
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "VCPE/DeleteVcpeResCustService/getSIAfterDelArs.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "VCPE/DeleteVcpeResCustService/getSIAfterDelArs.xml");
- // generate failure
- mockSDNCAdapter(wireMockServer, 404);
+ // generate failure
+ mockSDNCAdapter(wireMockServer, 404);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = setupVariables(businessKey);
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = setupVariables(businessKey);
- invokeAsyncProcess(PROCNAME, "v1", businessKey, request, variables);
+ invokeAsyncProcess(PROCNAME, "v1", businessKey, request, variables);
- waitForProcessEnd(businessKey, 70000);
+ waitForProcessEnd(businessKey, 70000);
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
- System.out.println("workflowException:\n" + workflowException);
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
+ System.out.println("workflowException:\n" + workflowException);
- String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix+VAR_COMP_REQ);
- System.out.println("completionReq:\n" + completionReq);
+ String completionReq = BPMNUtil.getVariable(processEngine, PROCNAME, Prefix + VAR_COMP_REQ);
+ System.out.println("completionReq:\n" + completionReq);
- assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME+VAR_SUCCESS_IND));
- assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
- assertNotNull(workflowException);
- logEnd();
- }
+ assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, PROCNAME + VAR_SUCCESS_IND));
+ assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, VAR_RESP_CODE));
+ assertNotNull(workflowException);
+ logEnd();
+ }
- private Map<String, Object> setupVariables(String requestId) throws UnsupportedEncodingException {
- Map<String, Object> variables = new HashMap<>();
- variables.put("isDebugLogEnabled", "true");
- variables.put("requestId", requestId);
- variables.put("serviceInstanceId", DEC_INST);
- variables.put("sdncVersion", "1802");
- variables.put("serviceInstanceName", "some-junk-name");
- return variables;
- }
+ private Map<String, Object> setupVariables(String requestId) throws UnsupportedEncodingException {
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("requestId", requestId);
+ variables.put("serviceInstanceId", DEC_INST);
+ variables.put("sdncVersion", "1802");
+ variables.put("serviceInstanceName", "some-junk-name");
+ return variables;
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceBRGIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceBRGIT.java
index da9b45c8c8..291613bc1a 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceBRGIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceBRGIT.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -29,10 +24,8 @@ import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchAllottedResource;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutAllottedResource;
import static org.onap.so.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB;
import static org.onap.so.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter;
-
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Test;
import org.onap.so.bpmn.common.BPMNUtil;
import org.onap.so.bpmn.mock.FileUtil;
@@ -40,227 +33,223 @@ import org.onap.so.bpmn.mock.FileUtil;
public class DoCreateAllottedResourceBRGIT extends AbstractTestBase {
- private static final String PROCNAME = "DoCreateAllottedResourceBRG";
- private final CallbackSet callbacks = new CallbackSet();
-
- public DoCreateAllottedResourceBRGIT() {
- callbacks.put("assign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyAssignCallback.xml"));
- callbacks.put("create", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyCreateCallback.xml"));
- callbacks.put("activate", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyActivateCallback.xml"));
- callbacks.put("query", FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceBRG/SDNCTopologyQueryCallback.xml"));
- }
-
- @Test
- public void testDoCreateAllottedResourceBRG_Success() throws InterruptedException {
- logStart();
-
- // TODO: use INST instead of DEC_INST
- /*
- * should be INST instead of DEC_INST, but AAI utilities appear to
- * have a bug in that they don't URL-encode the SI id before using
- * it in the query
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
-
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables,"testRequestId123");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- injectSDNCCallbacks(callbacks, "assign");
- injectSDNCCallbacks(callbacks, "create");
- injectSDNCCallbacks(callbacks, "activate");
- injectSDNCCallbacks(callbacks, "query");
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- assertNull(workflowException);
-
- assertEquals("namefromrequest", BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceBRG_NoSI() throws Exception{
- logStart();
- // TODO: use INST instead of DEC_INST
- /*
- * should be INST instead of DEC_INST, but AAI utilities appear to
- * have a bug in that they don't URL-encode the SI id before using
- * it in the query
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getNotFound.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
-
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables,"testRequestId124");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- assertNotNull(workflowException);
-
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceBRG_ActiveAr() throws Exception{
- logStart();
- // TODO: use INST instead of DEC_INST
- /*
- * should be INST instead of DEC_INST, but AAI utilities appear to
- * have a bug in that they don't URL-encode the SI id before using
- * it in the query
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
-
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "VCPE/DoCreateAllottedResourceBRG/getSIandAR.xml");
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRG/getArBrg2.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables,"testRequestId125");
-
- variables.put("failExists", "false");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
-
-
- injectSDNCCallbacks(callbacks, "query");
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- assertNull( workflowException);
-
- assertEquals("namefromrequest", BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceBRG_NoParentSI() throws Exception{
- logStart();
- // TODO: use INST instead of DEC_INST
- /*
- * should be INST instead of DEC_INST, but AAI utilities appear to
- * have a bug in that they don't URL-encode the SI id before using
- * it in the query
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getNotFound.xml");
-
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables,"testRequestId126");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- assertNotNull(workflowException);
-
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceBRG_SubProcessError() throws Exception{
- logStart();
- // TODO: use INST instead of DEC_INST
- /*
- * should be INST instead of DEC_INST, but AAI utilities appear to
- * have a bug in that they don't URL-encode the SI id before using
- * it in the query
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
-
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- mockSDNCAdapter(wireMockServer, 404);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables,"testRequestId127");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- assertNotNull(workflowException);
-
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName",processId));
- logEnd();
- }
-
- private void setVariablesSuccess(Map<String, Object> variables, String requestId) {
- variables.put("isDebugLogEnabled", "true");
- variables.put("failExists", "true");
- variables.put("disableRollback", "true");
- variables.put("msoRequestId", requestId);
- variables.put("mso-request-id", "requestId");
- variables.put("sourceNetworkId", "snId");
- variables.put("sourceNetworkRole", "snRole");
- variables.put("allottedResourceRole", "txc");
- variables.put("allottedResourceType", "BRG");
- variables.put("allottedResourceId", ARID);
- variables.put("vni", "BRG");
- variables.put("vgmuxBearerIP", "bearerip");
- variables.put("brgWanMacAddress", "wanmac");
-
- variables.put("serviceInstanceId", DEC_INST);
- variables.put("parentServiceInstanceId", DEC_PARENT_INST);
-
- variables.put("serviceChainServiceInstanceId", "scsiId");
-
- String arModelInfo = "{ "+ "\"modelType\": \"allotted-resource\"," +
- "\"modelInvariantUuid\": \"ff5256d2-5a33-55df-13ab-12abad84e7ff\"," +
- "\"modelUuid\": \"fe6478e5-ea33-3346-ac12-ab121484a3fe\"," +
- "\"modelName\": \"vSAMP12\"," +
- "\"modelVersion\": \"1.0\"," +
- "\"modelCustomizationUuid\": \"MODEL-ID-1234\"," +
- "}";
- variables.put("allottedResourceModelInfo", arModelInfo);
- }
+ private static final String PROCNAME = "DoCreateAllottedResourceBRG";
+ private final CallbackSet callbacks = new CallbackSet();
+
+ public DoCreateAllottedResourceBRGIT() {
+ callbacks.put("assign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyAssignCallback.xml"));
+ callbacks.put("create", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyCreateCallback.xml"));
+ callbacks.put("activate", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyActivateCallback.xml"));
+ callbacks.put("query",
+ FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceBRG/SDNCTopologyQueryCallback.xml"));
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRG_Success() throws InterruptedException {
+ logStart();
+
+ // TODO: use INST instead of DEC_INST
+ /*
+ * should be INST instead of DEC_INST, but AAI utilities appear to have a bug in that they don't URL-encode the
+ * SI id before using it in the query
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
+
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, "testRequestId123");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ injectSDNCCallbacks(callbacks, "assign");
+ injectSDNCCallbacks(callbacks, "create");
+ injectSDNCCallbacks(callbacks, "activate");
+ injectSDNCCallbacks(callbacks, "query");
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ assertNull(workflowException);
+
+ assertEquals("namefromrequest",
+ BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRG_NoSI() throws Exception {
+ logStart();
+ // TODO: use INST instead of DEC_INST
+ /*
+ * should be INST instead of DEC_INST, but AAI utilities appear to have a bug in that they don't URL-encode the
+ * SI id before using it in the query
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getNotFound.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
+
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, "testRequestId124");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ assertNotNull(workflowException);
+
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRG_ActiveAr() throws Exception {
+ logStart();
+ // TODO: use INST instead of DEC_INST
+ /*
+ * should be INST instead of DEC_INST, but AAI utilities appear to have a bug in that they don't URL-encode the
+ * SI id before using it in the query
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
+
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "VCPE/DoCreateAllottedResourceBRG/getSIandAR.xml");
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceBRG/getArBrg2.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, "testRequestId125");
+
+ variables.put("failExists", "false");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+
+
+ injectSDNCCallbacks(callbacks, "query");
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ assertNull(workflowException);
+
+ assertEquals("namefromrequest",
+ BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRG_NoParentSI() throws Exception {
+ logStart();
+ // TODO: use INST instead of DEC_INST
+ /*
+ * should be INST instead of DEC_INST, but AAI utilities appear to have a bug in that they don't URL-encode the
+ * SI id before using it in the query
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getNotFound.xml");
+
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, "testRequestId126");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ assertNotNull(workflowException);
+
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRG_SubProcessError() throws Exception {
+ logStart();
+ // TODO: use INST instead of DEC_INST
+ /*
+ * should be INST instead of DEC_INST, but AAI utilities appear to have a bug in that they don't URL-encode the
+ * SI id before using it in the query
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
+
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ mockSDNCAdapter(wireMockServer, 404);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, "testRequestId127");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ assertNotNull(workflowException);
+
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName", processId));
+ logEnd();
+ }
+
+ private void setVariablesSuccess(Map<String, Object> variables, String requestId) {
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("failExists", "true");
+ variables.put("disableRollback", "true");
+ variables.put("msoRequestId", requestId);
+ variables.put("mso-request-id", "requestId");
+ variables.put("sourceNetworkId", "snId");
+ variables.put("sourceNetworkRole", "snRole");
+ variables.put("allottedResourceRole", "txc");
+ variables.put("allottedResourceType", "BRG");
+ variables.put("allottedResourceId", ARID);
+ variables.put("vni", "BRG");
+ variables.put("vgmuxBearerIP", "bearerip");
+ variables.put("brgWanMacAddress", "wanmac");
+
+ variables.put("serviceInstanceId", DEC_INST);
+ variables.put("parentServiceInstanceId", DEC_PARENT_INST);
+
+ variables.put("serviceChainServiceInstanceId", "scsiId");
+
+ String arModelInfo = "{ " + "\"modelType\": \"allotted-resource\","
+ + "\"modelInvariantUuid\": \"ff5256d2-5a33-55df-13ab-12abad84e7ff\","
+ + "\"modelUuid\": \"fe6478e5-ea33-3346-ac12-ab121484a3fe\"," + "\"modelName\": \"vSAMP12\","
+ + "\"modelVersion\": \"1.0\"," + "\"modelCustomizationUuid\": \"MODEL-ID-1234\"," + "}";
+ variables.put("allottedResourceModelInfo", arModelInfo);
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceBRGRollbackIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceBRGRollbackIT.java
index f0d275c5cc..cd7004e3aa 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceBRGRollbackIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceBRGRollbackIT.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -24,12 +19,10 @@ import org.junit.Test;
import org.onap.so.bpmn.common.BPMNUtil;
import org.onap.so.bpmn.core.RollbackData;
import org.onap.so.bpmn.mock.FileUtil;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -43,281 +36,295 @@ import static org.onap.so.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter;
public class DoCreateAllottedResourceBRGRollbackIT extends AbstractTestBase {
- private static final String PROCNAME = "DoCreateAllottedResourceBRGRollback";
- private static final String RbType = "DCARBRG_";
- private final CallbackSet callbacks = new CallbackSet();
-
- public DoCreateAllottedResourceBRGRollbackIT() throws IOException {
- callbacks.put("deactivate", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallback.xml"));
- callbacks.put("delete", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeleteCallback.xml"));
- callbacks.put("unassign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyUnassignCallback.xml"));
- }
-
- @Test
- public void testDoCreateAllottedResourceBRGRollback_Success() throws Exception {
+ private static final String PROCNAME = "DoCreateAllottedResourceBRGRollback";
+ private static final String RbType = "DCARBRG_";
+ private final CallbackSet callbacks = new CallbackSet();
+
+ public DoCreateAllottedResourceBRGRollbackIT() throws IOException {
+ callbacks.put("deactivate",
+ FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallback.xml"));
+ callbacks.put("delete", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeleteCallback.xml"));
+ callbacks.put("unassign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyUnassignCallback.xml"));
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRGRollback_Success() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, businessKey);
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ injectSDNCCallbacks(callbacks, "deactivate");
+ injectSDNCCallbacks(callbacks, "delete");
+ injectSDNCCallbacks(callbacks, "unassign");
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRGRollback_skipRollback() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
+
+ rollbackData.put(RbType, "rollbackAAI", "false");
+ rollbackData.put(RbType, "rollbackSDNCassign", "false");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRGRollback_DoNotRollBack() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
+
+ // this will cause "rollbackSDNC" to be set to false
+ rollbackData.put(RbType, "rollbackSDNCassign", "false");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRGRollback_NoDeactivate() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
+
+ rollbackData.put(RbType, "rollbackSDNCactivate", "false");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ injectSDNCCallbacks(callbacks, "delete");
+ injectSDNCCallbacks(callbacks, "unassign");
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRGRollback_NoDelete() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
+
+ rollbackData.put(RbType, "rollbackSDNCcreate", "false");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ injectSDNCCallbacks(callbacks, "deactivate");
+ injectSDNCCallbacks(callbacks, "unassign");
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRGRollback_NoUnassign() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
+
+ rollbackData.put(RbType, "rollbackSDNCassign", "false");
+
+ /*
+ * Note: if assign == false then the flow/script will set "skipRollback" to false, which will cause ALL of the
+ * SDNC steps to be skipped, not just the unassign step.
+ */
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRGRollback_SubProcessError() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ mockSDNCAdapter(wireMockServer, 404);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, businessKey);
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("false", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNotNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceBRGRollback_JavaException() throws Exception {
logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, businessKey);
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- injectSDNCCallbacks(callbacks, "deactivate");
- injectSDNCCallbacks(callbacks, "delete");
- injectSDNCCallbacks(callbacks, "unassign");
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceBRGRollback_skipRollback() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
-
- rollbackData.put(RbType, "rollbackAAI", "false");
- rollbackData.put(RbType, "rollbackSDNCassign", "false");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceBRGRollback_DoNotRollBack() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
-
- // this will cause "rollbackSDNC" to be set to false
- rollbackData.put(RbType, "rollbackSDNCassign", "false");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceBRGRollback_NoDeactivate() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
-
- rollbackData.put(RbType, "rollbackSDNCactivate", "false");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- injectSDNCCallbacks(callbacks, "delete");
- injectSDNCCallbacks(callbacks, "unassign");
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceBRGRollback_NoDelete() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
-
- rollbackData.put(RbType, "rollbackSDNCcreate", "false");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- injectSDNCCallbacks(callbacks, "deactivate");
- injectSDNCCallbacks(callbacks, "unassign");
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceBRGRollback_NoUnassign() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
-
- rollbackData.put(RbType, "rollbackSDNCassign", "false");
-
- /*
- * Note: if assign == false then the flow/script will set
- * "skipRollback" to false, which will cause ALL of the SDNC steps
- * to be skipped, not just the unassign step.
- */
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceBRGRollback_SubProcessError() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- mockSDNCAdapter(wireMockServer, 404);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, businessKey);
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("false", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNotNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceBRGRollback_JavaException() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, businessKey);
-
- variables.put("rollbackData", "string instead of rollback data");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("false", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNotNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- private RollbackData setVariablesSuccess(Map<String, Object> variables, String requestId) {
- variables.put("isDebugLogEnabled", "true");
- variables.put("failNotFound", "true");
- variables.put("msoRequestId", requestId);
- variables.put("mso-request-id", "requestId");
- variables.put("allottedResourceId", ARID);
-
- variables.put("serviceInstanceId", DEC_INST);
- variables.put("parentServiceInstanceId", DEC_PARENT_INST);
-
- RollbackData rollbackData = new RollbackData();
-
- rollbackData.put(RbType, "serviceInstanceId", DEC_INST);
- rollbackData.put(RbType, "serviceSubscriptionType", SVC);
- rollbackData.put(RbType, "disablerollback", "false");
- rollbackData.put(RbType, "rollbackAAI", "true");
- rollbackData.put(RbType, "rollbackSDNCassign", "true");
- rollbackData.put(RbType, "rollbackSDNCactivate", "true");
- rollbackData.put(RbType, "rollbackSDNCcreate", "true");
- rollbackData.put(RbType, "aaiARPath", "business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID);
-
- rollbackData.put(RbType, "sdncActivateRollbackReq", FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceBRGRollback/sdncActivateRollbackReq.xml"));
- rollbackData.put(RbType, "sdncCreateRollbackReq", FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceBRGRollback/sdncCreateRollbackReq.xml"));
- rollbackData.put(RbType, "sdncAssignRollbackReq", FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceBRGRollback/sdncAssignRollbackReq.xml"));
-
- variables.put("rollbackData",rollbackData);
-
- return rollbackData;
- }
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, businessKey);
+
+ variables.put("rollbackData", "string instead of rollback data");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("false", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNotNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ private RollbackData setVariablesSuccess(Map<String, Object> variables, String requestId) {
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("failNotFound", "true");
+ variables.put("msoRequestId", requestId);
+ variables.put("mso-request-id", "requestId");
+ variables.put("allottedResourceId", ARID);
+
+ variables.put("serviceInstanceId", DEC_INST);
+ variables.put("parentServiceInstanceId", DEC_PARENT_INST);
+
+ RollbackData rollbackData = new RollbackData();
+
+ rollbackData.put(RbType, "serviceInstanceId", DEC_INST);
+ rollbackData.put(RbType, "serviceSubscriptionType", SVC);
+ rollbackData.put(RbType, "disablerollback", "false");
+ rollbackData.put(RbType, "rollbackAAI", "true");
+ rollbackData.put(RbType, "rollbackSDNCassign", "true");
+ rollbackData.put(RbType, "rollbackSDNCactivate", "true");
+ rollbackData.put(RbType, "rollbackSDNCcreate", "true");
+ rollbackData.put(RbType, "aaiARPath",
+ "business/customers/customer/" + CUST + "/service-subscriptions/service-subscription/" + SVC
+ + "/service-instances/service-instance/" + INST + "/allotted-resources/allotted-resource/"
+ + ARID);
+
+ rollbackData.put(RbType, "sdncActivateRollbackReq", FileUtil
+ .readResourceFile("__files/VCPE/DoCreateAllottedResourceBRGRollback/sdncActivateRollbackReq.xml"));
+ rollbackData.put(RbType, "sdncCreateRollbackReq", FileUtil
+ .readResourceFile("__files/VCPE/DoCreateAllottedResourceBRGRollback/sdncCreateRollbackReq.xml"));
+ rollbackData.put(RbType, "sdncAssignRollbackReq", FileUtil
+ .readResourceFile("__files/VCPE/DoCreateAllottedResourceBRGRollback/sdncAssignRollbackReq.xml"));
+
+ variables.put("rollbackData", rollbackData);
+
+ return rollbackData;
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceTXCIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceTXCIT.java
index 6ecec3240d..80c3fa16e8 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceTXCIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceTXCIT.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -31,12 +26,10 @@ import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchAllottedResource;
import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutAllottedResource;
import static org.onap.so.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB;
import static org.onap.so.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Assert;
import org.junit.Ignore;
@@ -46,231 +39,227 @@ import org.onap.so.bpmn.mock.FileUtil;
public class DoCreateAllottedResourceTXCIT extends AbstractTestBase {
- private static final String PROCNAME = "DoCreateAllottedResourceTXC";
- private final CallbackSet callbacks = new CallbackSet();
-
- public DoCreateAllottedResourceTXCIT() throws IOException {
- callbacks.put("assign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyAssignCallback.xml"));
- callbacks.put("create", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyCreateCallback.xml"));
- callbacks.put("activate", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyActivateCallback.xml"));
- callbacks.put("query", FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceTXC/SDNCTopologyQueryCallback.xml"));
- }
-
- @Test
- public void testDoCreateAllottedResourceTXC_Success() throws Exception{
- logStart();
- // TODO: use INST instead of DEC_INST
- /*
- * should be INST instead of DEC_INST, but AAI utilities appear to
- * have a bug in that they don't URL-encode the SI id before using
- * it in the query
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
-
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, "testRequestId123");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- injectSDNCCallbacks(callbacks, "assign");
- injectSDNCCallbacks(callbacks, "create");
- injectSDNCCallbacks(callbacks, "activate");
- injectSDNCCallbacks(callbacks, "query");
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
-
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- assertEquals(null, workflowException);
-
- assertEquals("namefromrequest", BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName",processId));
- assertEquals("my-vni", BPMNUtil.getVariable(processEngine, PROCNAME, "vni",processId));
- assertEquals("my-bearer-ip", BPMNUtil.getVariable(processEngine, PROCNAME, "vgmuxBearerIP",processId));
- assertEquals("my-lan-ip", BPMNUtil.getVariable(processEngine, PROCNAME, "vgmuxLanIP",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceTXC_NoSI() throws Exception{
- logStart();
- // TODO: use INST instead of DEC_INST
- /*
- * should be INST instead of DEC_INST, but AAI utilities appear to
- * have a bug in that they don't URL-encode the SI id before using
- * it in the query
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getNotFound.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
-
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, "testRequestId123");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- Assert.assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- assertNotNull(workflowException);
-
- assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceTXC_ActiveAr() throws Exception{
- logStart();
- // TODO: use INST instead of DEC_INST
- /*
- * should be INST instead of DEC_INST, but AAI utilities appear to
- * have a bug in that they don't URL-encode the SI id before using
- * it in the query
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
-
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "VCPE/DoCreateAllottedResourceTXC/getSIandAR.xml");
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXC/getArTxc2.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, "testRequestId123");
-
- variables.put("failExists", "false");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- injectSDNCCallbacks(callbacks, "query");
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
- assertEquals(null, workflowException);
-
- assertEquals("namefromrequest", BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName",processId));
- assertEquals("my-vni", BPMNUtil.getVariable(processEngine, PROCNAME, "vni",processId));
- assertEquals("my-bearer-ip", BPMNUtil.getVariable(processEngine, PROCNAME, "vgmuxBearerIP",processId));
- assertEquals("my-lan-ip", BPMNUtil.getVariable(processEngine, PROCNAME, "vgmuxLanIP",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceTXC_NoParentSI() throws Exception{
- logStart();
- // TODO: use INST instead of DEC_INST
- /*
- * should be INST instead of DEC_INST, but AAI utilities appear to
- * have a bug in that they don't URL-encode the SI id before using
- * it in the query
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
-
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getNotFound.xml");
-
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, "testRequestId123");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- assertNotNull(workflowException);
-
- assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceTXC_SubProcessError() throws Exception{
- logStart();
- // TODO: use INST instead of DEC_INST
- /*
- * should be INST instead of DEC_INST, but AAI utilities appear to
- * have a bug in that they don't URL-encode the SI id before using
- * it in the query
- */
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
- MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
-
- MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
- MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
- MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
- mockSDNCAdapter(wireMockServer, 404);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, "testRequestId123");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- assertNotNull(workflowException);
-
- assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName",processId));
- logEnd();
- }
-
- private void setVariablesSuccess(Map<String, Object> variables, String requestId) {
- // TODO: need all of these?
- variables.put("isDebugLogEnabled", "true");
- variables.put("failExists", "true");
- variables.put("disableRollback", "true");
- variables.put("msoRequestId", requestId);
- variables.put("mso-request-id", "requestId");
- variables.put("sourceNetworkId", "snId");
- variables.put("sourceNetworkRole", "snRole");
- variables.put("allottedResourceRole", "brg");
- variables.put("allottedResourceType", "TXC");
- variables.put("allottedResourceId", ARID);
- variables.put("brgWanMacAddress", "wanmac");
-
- variables.put("serviceInstanceId", DEC_INST);
- variables.put("parentServiceInstanceId", DEC_PARENT_INST);
-
- variables.put("serviceChainServiceInstanceId", "scsiId");
-
- String arModelInfo = "{ "+ "\"modelType\": \"allotted-resource\"," +
- "\"modelInvariantUuid\": \"ff5256d2-5a33-55df-13ab-12abad84e7ff\"," +
- "\"modelUuid\": \"fe6478e5-ea33-3346-ac12-ab121484a3fe\"," +
- "\"modelName\": \"vSAMP12\"," +
- "\"modelVersion\": \"1.0\"," +
- "\"modelCustomizationUuid\": \"MODEL-ID-1234\"," +
- "}";
- variables.put("allottedResourceModelInfo", arModelInfo);
- }
+ private static final String PROCNAME = "DoCreateAllottedResourceTXC";
+ private final CallbackSet callbacks = new CallbackSet();
+
+ public DoCreateAllottedResourceTXCIT() throws IOException {
+ callbacks.put("assign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyAssignCallback.xml"));
+ callbacks.put("create", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyCreateCallback.xml"));
+ callbacks.put("activate", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyActivateCallback.xml"));
+ callbacks.put("query",
+ FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceTXC/SDNCTopologyQueryCallback.xml"));
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXC_Success() throws Exception {
+ logStart();
+ // TODO: use INST instead of DEC_INST
+ /*
+ * should be INST instead of DEC_INST, but AAI utilities appear to have a bug in that they don't URL-encode the
+ * SI id before using it in the query
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
+
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, "testRequestId123");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ injectSDNCCallbacks(callbacks, "assign");
+ injectSDNCCallbacks(callbacks, "create");
+ injectSDNCCallbacks(callbacks, "activate");
+ injectSDNCCallbacks(callbacks, "query");
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ assertEquals(null, workflowException);
+
+ assertEquals("namefromrequest",
+ BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName", processId));
+ assertEquals("my-vni", BPMNUtil.getVariable(processEngine, PROCNAME, "vni", processId));
+ assertEquals("my-bearer-ip", BPMNUtil.getVariable(processEngine, PROCNAME, "vgmuxBearerIP", processId));
+ assertEquals("my-lan-ip", BPMNUtil.getVariable(processEngine, PROCNAME, "vgmuxLanIP", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXC_NoSI() throws Exception {
+ logStart();
+ // TODO: use INST instead of DEC_INST
+ /*
+ * should be INST instead of DEC_INST, but AAI utilities appear to have a bug in that they don't URL-encode the
+ * SI id before using it in the query
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getNotFound.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
+
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, "testRequestId123");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ Assert.assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ assertNotNull(workflowException);
+
+ assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXC_ActiveAr() throws Exception {
+ logStart();
+ // TODO: use INST instead of DEC_INST
+ /*
+ * should be INST instead of DEC_INST, but AAI utilities appear to have a bug in that they don't URL-encode the
+ * SI id before using it in the query
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
+
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "VCPE/DoCreateAllottedResourceTXC/getSIandAR.xml");
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceTXC/getArTxc2.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, "testRequestId123");
+
+ variables.put("failExists", "false");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ injectSDNCCallbacks(callbacks, "query");
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
+ assertEquals(null, workflowException);
+
+ assertEquals("namefromrequest",
+ BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName", processId));
+ assertEquals("my-vni", BPMNUtil.getVariable(processEngine, PROCNAME, "vni", processId));
+ assertEquals("my-bearer-ip", BPMNUtil.getVariable(processEngine, PROCNAME, "vgmuxBearerIP", processId));
+ assertEquals("my-lan-ip", BPMNUtil.getVariable(processEngine, PROCNAME, "vgmuxLanIP", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXC_NoParentSI() throws Exception {
+ logStart();
+ // TODO: use INST instead of DEC_INST
+ /*
+ * should be INST instead of DEC_INST, but AAI utilities appear to have a bug in that they don't URL-encode the
+ * SI id before using it in the query
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
+
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getNotFound.xml");
+
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, "testRequestId123");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ assertNotNull(workflowException);
+
+ assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXC_SubProcessError() throws Exception {
+ logStart();
+ // TODO: use INST instead of DEC_INST
+ /*
+ * should be INST instead of DEC_INST, but AAI utilities appear to have a bug in that they don't URL-encode the
+ * SI id before using it in the query
+ */
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_INST, "GenericFlows/getSIUrlById.xml");
+ MockNodeQueryServiceInstanceById(wireMockServer, DEC_PARENT_INST, "GenericFlows/getParentSIUrlById.xml");
+
+ MockGetServiceInstance(wireMockServer, CUST, SVC, INST, "GenericFlows/getServiceInstance.xml");
+ MockGetServiceInstance(wireMockServer, CUST, SVC, PARENT_INST, "GenericFlows/getParentServiceInstance.xml");
+ MockPutAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, PARENT_INST, ARID);
+ mockSDNCAdapter(wireMockServer, 404);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, "testRequestId123");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ assertNotNull(workflowException);
+
+ assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, "allotedResourceName", processId));
+ logEnd();
+ }
+
+ private void setVariablesSuccess(Map<String, Object> variables, String requestId) {
+ // TODO: need all of these?
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("failExists", "true");
+ variables.put("disableRollback", "true");
+ variables.put("msoRequestId", requestId);
+ variables.put("mso-request-id", "requestId");
+ variables.put("sourceNetworkId", "snId");
+ variables.put("sourceNetworkRole", "snRole");
+ variables.put("allottedResourceRole", "brg");
+ variables.put("allottedResourceType", "TXC");
+ variables.put("allottedResourceId", ARID);
+ variables.put("brgWanMacAddress", "wanmac");
+
+ variables.put("serviceInstanceId", DEC_INST);
+ variables.put("parentServiceInstanceId", DEC_PARENT_INST);
+
+ variables.put("serviceChainServiceInstanceId", "scsiId");
+
+ String arModelInfo = "{ " + "\"modelType\": \"allotted-resource\","
+ + "\"modelInvariantUuid\": \"ff5256d2-5a33-55df-13ab-12abad84e7ff\","
+ + "\"modelUuid\": \"fe6478e5-ea33-3346-ac12-ab121484a3fe\"," + "\"modelName\": \"vSAMP12\","
+ + "\"modelVersion\": \"1.0\"," + "\"modelCustomizationUuid\": \"MODEL-ID-1234\"," + "}";
+ variables.put("allottedResourceModelInfo", arModelInfo);
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceTXCRollbackIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceTXCRollbackIT.java
index 4f81a4f725..0b64f4938e 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceTXCRollbackIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoCreateAllottedResourceTXCRollbackIT.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -24,12 +19,10 @@ import org.junit.Test;
import org.onap.so.bpmn.common.BPMNUtil;
import org.onap.so.bpmn.core.RollbackData;
import org.onap.so.bpmn.mock.FileUtil;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -43,281 +36,295 @@ import static org.onap.so.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter;
public class DoCreateAllottedResourceTXCRollbackIT extends AbstractTestBase {
- private static final String PROCNAME = "DoCreateAllottedResourceTXCRollback";
- private static final String RbType = "DCARTXC_";
- private final CallbackSet callbacks = new CallbackSet();
-
- public DoCreateAllottedResourceTXCRollbackIT() throws IOException {
- callbacks.put("deactivate", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallback.xml"));
- callbacks.put("delete", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeleteCallback.xml"));
- callbacks.put("unassign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyUnassignCallback.xml"));
- }
-
- @Test
- public void testDoCreateAllottedResourceTXCRollback_Success() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, businessKey);
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- injectSDNCCallbacks(callbacks, "deactivate");
- injectSDNCCallbacks(callbacks, "delete");
- injectSDNCCallbacks(callbacks, "unassign");
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceTXCRollback_skipRollback() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
-
- rollbackData.put(RbType, "rollbackAAI", "false");
- rollbackData.put(RbType, "rollbackSDNCassign", "false");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceTXCRollback_DoNotRollBack() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
-
- // this will cause "rollbackSDNC" to be set to false
- rollbackData.put(RbType, "rollbackSDNCassign", "false");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceTXCRollback_NoDeactivate() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
-
- rollbackData.put(RbType, "rollbackSDNCactivate", "false");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- injectSDNCCallbacks(callbacks, "delete");
- injectSDNCCallbacks(callbacks, "unassign");
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceTXCRollback_NoDelete() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
-
- rollbackData.put(RbType, "rollbackSDNCcreate", "false");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- injectSDNCCallbacks(callbacks, "deactivate");
- injectSDNCCallbacks(callbacks, "unassign");
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceTXCRollback_NoUnassign() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
-
- rollbackData.put(RbType, "rollbackSDNCassign", "false");
-
- /*
- * Note: if assign == false then the flow/script will set
- * "skipRollback" to false, which will cause ALL of the SDNC steps
- * to be skipped, not just the unassign step.
- */
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceTXCRollback_SubProcessError() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- mockSDNCAdapter(wireMockServer, 404);
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, businessKey);
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("false", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNotNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- @Test
- public void testDoCreateAllottedResourceTXCRollback_JavaException() throws Exception {
- logStart();
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables, businessKey);
-
- variables.put("rollbackData", "string instead of rollback data");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- waitForWorkflowToFinish(processEngine,processId);
-
- assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX,processId);
- System.out.println("workflowException:\n" + workflowException);
- assertEquals(null, workflowException);
- assertEquals("false", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack",processId));
- assertNotNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError",processId));
- logEnd();
- }
-
- private RollbackData setVariablesSuccess(Map<String, Object> variables, String requestId) {
- variables.put("isDebugLogEnabled", "true");
- variables.put("failNotFound", "true");
- variables.put("msoRequestId", requestId);
- variables.put("mso-request-id", "requestId");
- variables.put("allottedResourceId", ARID);
-
- variables.put("serviceInstanceId", DEC_INST);
- variables.put("parentServiceInstanceId", DEC_PARENT_INST);
-
- RollbackData rollbackData = new RollbackData();
-
- rollbackData.put(RbType, "serviceInstanceId", DEC_INST);
- rollbackData.put(RbType, "serviceSubscriptionType", SVC);
- rollbackData.put(RbType, "disablerollback", "false");
- rollbackData.put(RbType, "rollbackAAI", "true");
- rollbackData.put(RbType, "rollbackSDNCassign", "true");
- rollbackData.put(RbType, "rollbackSDNCactivate", "true");
- rollbackData.put(RbType, "rollbackSDNCcreate", "true");
- rollbackData.put(RbType, "aaiARPath", "/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID);
-
- rollbackData.put(RbType, "sdncActivateRollbackReq", FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceTXCRollback/sdncActivateRollbackReq.xml"));
- rollbackData.put(RbType, "sdncCreateRollbackReq", FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceTXCRollback/sdncCreateRollbackReq.xml"));
- rollbackData.put(RbType, "sdncAssignRollbackReq", FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceTXCRollback/sdncAssignRollbackReq.xml"));
-
- variables.put("rollbackData",rollbackData);
-
- return rollbackData;
- }
+ private static final String PROCNAME = "DoCreateAllottedResourceTXCRollback";
+ private static final String RbType = "DCARTXC_";
+ private final CallbackSet callbacks = new CallbackSet();
+
+ public DoCreateAllottedResourceTXCRollbackIT() throws IOException {
+ callbacks.put("deactivate",
+ FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallback.xml"));
+ callbacks.put("delete", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeleteCallback.xml"));
+ callbacks.put("unassign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyUnassignCallback.xml"));
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXCRollback_Success() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, businessKey);
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ injectSDNCCallbacks(callbacks, "deactivate");
+ injectSDNCCallbacks(callbacks, "delete");
+ injectSDNCCallbacks(callbacks, "unassign");
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXCRollback_skipRollback() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
+
+ rollbackData.put(RbType, "rollbackAAI", "false");
+ rollbackData.put(RbType, "rollbackSDNCassign", "false");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals(null, BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXCRollback_DoNotRollBack() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
+
+ // this will cause "rollbackSDNC" to be set to false
+ rollbackData.put(RbType, "rollbackSDNCassign", "false");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXCRollback_NoDeactivate() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
+
+ rollbackData.put(RbType, "rollbackSDNCactivate", "false");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ injectSDNCCallbacks(callbacks, "delete");
+ injectSDNCCallbacks(callbacks, "unassign");
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXCRollback_NoDelete() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
+
+ rollbackData.put(RbType, "rollbackSDNCcreate", "false");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ injectSDNCCallbacks(callbacks, "deactivate");
+ injectSDNCCallbacks(callbacks, "unassign");
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXCRollback_NoUnassign() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ RollbackData rollbackData = setVariablesSuccess(variables, businessKey);
+
+ rollbackData.put(RbType, "rollbackSDNCassign", "false");
+
+ /*
+ * Note: if assign == false then the flow/script will set "skipRollback" to false, which will cause ALL of the
+ * SDNC steps to be skipped, not just the unassign step.
+ */
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("true", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXCRollback_SubProcessError() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ mockSDNCAdapter(wireMockServer, 404);
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, businessKey);
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("false", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNotNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ @Test
+ public void testDoCreateAllottedResourceTXCRollback_JavaException() throws Exception {
+ logStart();
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables, businessKey);
+
+ variables.put("rollbackData", "string instead of rollback data");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ waitForWorkflowToFinish(processEngine, processId);
+
+ assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX, processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertEquals(null, workflowException);
+ assertEquals("false", BPMNUtil.getVariable(processEngine, PROCNAME, "rolledBack", processId));
+ assertNotNull(BPMNUtil.getVariable(processEngine, PROCNAME, "rollbackError", processId));
+ logEnd();
+ }
+
+ private RollbackData setVariablesSuccess(Map<String, Object> variables, String requestId) {
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("failNotFound", "true");
+ variables.put("msoRequestId", requestId);
+ variables.put("mso-request-id", "requestId");
+ variables.put("allottedResourceId", ARID);
+
+ variables.put("serviceInstanceId", DEC_INST);
+ variables.put("parentServiceInstanceId", DEC_PARENT_INST);
+
+ RollbackData rollbackData = new RollbackData();
+
+ rollbackData.put(RbType, "serviceInstanceId", DEC_INST);
+ rollbackData.put(RbType, "serviceSubscriptionType", SVC);
+ rollbackData.put(RbType, "disablerollback", "false");
+ rollbackData.put(RbType, "rollbackAAI", "true");
+ rollbackData.put(RbType, "rollbackSDNCassign", "true");
+ rollbackData.put(RbType, "rollbackSDNCactivate", "true");
+ rollbackData.put(RbType, "rollbackSDNCcreate", "true");
+ rollbackData.put(RbType, "aaiARPath",
+ "/business/customers/customer/" + CUST + "/service-subscriptions/service-subscription/" + SVC
+ + "/service-instances/service-instance/" + INST + "/allotted-resources/allotted-resource/"
+ + ARID);
+
+ rollbackData.put(RbType, "sdncActivateRollbackReq", FileUtil
+ .readResourceFile("__files/VCPE/DoCreateAllottedResourceTXCRollback/sdncActivateRollbackReq.xml"));
+ rollbackData.put(RbType, "sdncCreateRollbackReq", FileUtil
+ .readResourceFile("__files/VCPE/DoCreateAllottedResourceTXCRollback/sdncCreateRollbackReq.xml"));
+ rollbackData.put(RbType, "sdncAssignRollbackReq", FileUtil
+ .readResourceFile("__files/VCPE/DoCreateAllottedResourceTXCRollback/sdncAssignRollbackReq.xml"));
+
+ variables.put("rollbackData", rollbackData);
+
+ return rollbackData;
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoDeleteAllottedResourceBRGIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoDeleteAllottedResourceBRGIT.java
index 42f32b8ecc..e4dc5add03 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoDeleteAllottedResourceBRGIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoDeleteAllottedResourceBRGIT.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -24,11 +19,9 @@ import org.junit.Assert;
import org.junit.Test;
import org.onap.so.bpmn.common.BPMNUtil;
import org.onap.so.bpmn.mock.FileUtil;
-
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import static org.junit.Assert.*;
import static org.onap.so.bpmn.mock.StubResponseAAI.*;
import static org.onap.so.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB;
@@ -37,109 +30,114 @@ import static org.onap.so.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter;
public class DoDeleteAllottedResourceBRGIT extends AbstractTestBase {
- private static final String PROCNAME = "DoDeleteAllottedResourceBRG";
- private final CallbackSet callbacks = new CallbackSet();
-
- public DoDeleteAllottedResourceBRGIT() {
- callbacks.put("deactivate", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallback.xml"));
- callbacks.put("deactivateNF", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallbackNotFound.xml"));
- callbacks.put("delete", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeleteCallback.xml"));
- callbacks.put("unassign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyUnassignCallback.xml"));
- }
-
- @Test
- public void testDoDeleteAllottedResourceBRG_Success() {
- logStart();
- MockQueryAllottedResourceById(wireMockServer, ARID, "GenericFlows/getARUrlById.xml");
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables);
-
- invokeSubProcess(PROCNAME, businessKey, variables);
-
- injectSDNCCallbacks(callbacks, "deactivate");
- injectSDNCCallbacks(callbacks, "delete");
- injectSDNCCallbacks(callbacks, "unassign");
-
- waitForProcessEnd(businessKey, 10000);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
- System.out.println("workflowException:\n" + workflowException);
- assertNull(workflowException);
- logEnd();
- }
-
- @Test
- public void testDoDeleteAllottedResourceBRG_ARNotInSDNC() {
- logStart();
- MockQueryAllottedResourceById(wireMockServer, ARID, "GenericFlows/getARUrlById.xml");
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- String businessKey = UUID.randomUUID().toString();
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables);
-
- variables.put("failNotFound", "false");
-
- invokeSubProcess(PROCNAME, businessKey, variables);
-
- injectSDNCCallbacks(callbacks, "deactivateNF");
-
- waitForProcessEnd(businessKey, 10000);
-
- Assert.assertTrue(isProcessEnded(businessKey));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
- System.out.println("workflowException:\n" + workflowException);
- assertNull(workflowException);
- logEnd();
- }
-
-
- @Test
- public void testDoDeleteAllottedResourceBRG_SubProcessError() throws Exception {
- logStart();
- MockQueryAllottedResourceById(wireMockServer, ARID, "GenericFlows/getARUrlById.xml");
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- mockSDNCAdapter(wireMockServer, 500);
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables);
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
-
- BPMNUtil.waitForWorkflowToFinish(processEngine,processId);
-
- Assert.assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, "WorkflowException",processId);
- System.out.println("workflowException:\n" + workflowException);
- assertNotNull(workflowException);
- logEnd();
- }
-
- private void setVariablesSuccess(Map<String, Object> variables) {
- variables.put("isDebugLogEnabled", "true");
- variables.put("failNotFound", "true");
- variables.put("msoRequestId", "testRequestId1");
- variables.put("mso-request-id", "requestId");
- variables.put("allottedResourceId", ARID);
- variables.put("serviceInstanceId", DEC_INST);
- variables.put("parentServiceInstanceId", DEC_PARENT_INST);
- }
+ private static final String PROCNAME = "DoDeleteAllottedResourceBRG";
+ private final CallbackSet callbacks = new CallbackSet();
+
+ public DoDeleteAllottedResourceBRGIT() {
+ callbacks.put("deactivate",
+ FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallback.xml"));
+ callbacks.put("deactivateNF",
+ FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallbackNotFound.xml"));
+ callbacks.put("delete", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeleteCallback.xml"));
+ callbacks.put("unassign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyUnassignCallback.xml"));
+ }
+
+ @Test
+ public void testDoDeleteAllottedResourceBRG_Success() {
+ logStart();
+ MockQueryAllottedResourceById(wireMockServer, ARID, "GenericFlows/getARUrlById.xml");
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables);
+
+ invokeSubProcess(PROCNAME, businessKey, variables);
+
+ injectSDNCCallbacks(callbacks, "deactivate");
+ injectSDNCCallbacks(callbacks, "delete");
+ injectSDNCCallbacks(callbacks, "unassign");
+
+ waitForProcessEnd(businessKey, 10000);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
+ System.out.println("workflowException:\n" + workflowException);
+ assertNull(workflowException);
+ logEnd();
+ }
+
+ @Test
+ public void testDoDeleteAllottedResourceBRG_ARNotInSDNC() {
+ logStart();
+ MockQueryAllottedResourceById(wireMockServer, ARID, "GenericFlows/getARUrlById.xml");
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ String businessKey = UUID.randomUUID().toString();
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables);
+
+ variables.put("failNotFound", "false");
+
+ invokeSubProcess(PROCNAME, businessKey, variables);
+
+ injectSDNCCallbacks(callbacks, "deactivateNF");
+
+ waitForProcessEnd(businessKey, 10000);
+
+ Assert.assertTrue(isProcessEnded(businessKey));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, VAR_WFEX);
+ System.out.println("workflowException:\n" + workflowException);
+ assertNull(workflowException);
+ logEnd();
+ }
+
+
+ @Test
+ public void testDoDeleteAllottedResourceBRG_SubProcessError() throws Exception {
+ logStart();
+ MockQueryAllottedResourceById(wireMockServer, ARID, "GenericFlows/getARUrlById.xml");
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ mockSDNCAdapter(wireMockServer, 500);
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables);
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+
+ BPMNUtil.waitForWorkflowToFinish(processEngine, processId);
+
+ Assert.assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, "WorkflowException", processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertNotNull(workflowException);
+ logEnd();
+ }
+
+ private void setVariablesSuccess(Map<String, Object> variables) {
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("failNotFound", "true");
+ variables.put("msoRequestId", "testRequestId1");
+ variables.put("mso-request-id", "requestId");
+ variables.put("allottedResourceId", ARID);
+ variables.put("serviceInstanceId", DEC_INST);
+ variables.put("parentServiceInstanceId", DEC_PARENT_INST);
+ }
}
diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoDeleteAllottedResourceTXCIT.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoDeleteAllottedResourceTXCIT.java
index 13ca58be03..106c2f0611 100644
--- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoDeleteAllottedResourceTXCIT.java
+++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/vcpe/DoDeleteAllottedResourceTXCIT.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -24,10 +19,8 @@ import org.junit.Assert;
import org.junit.Test;
import org.onap.so.bpmn.common.BPMNUtil;
import org.onap.so.bpmn.mock.FileUtil;
-
import java.util.HashMap;
import java.util.Map;
-
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.onap.so.bpmn.mock.StubResponseAAI.*;
@@ -37,104 +30,109 @@ import static org.onap.so.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter;
public class DoDeleteAllottedResourceTXCIT extends AbstractTestBase {
- private static final String PROCNAME = "DoDeleteAllottedResourceTXC";
- private final CallbackSet callbacks = new CallbackSet();
-
- public DoDeleteAllottedResourceTXCIT() {
- callbacks.put("deactivate", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallback.xml"));
- callbacks.put("deactivateNF", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallbackNotFound.xml"));
- callbacks.put("delete", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeleteCallback.xml"));
- callbacks.put("unassign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyUnassignCallback.xml"));
- }
-
- @Test
- public void testDoDeleteAllottedResourceTXC_Success() throws Exception {
- logStart();
- MockQueryAllottedResourceById(wireMockServer, ARID, "GenericFlows/getARUrlById.xml");
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables);
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- injectSDNCCallbacks(callbacks, "deactivate");
- injectSDNCCallbacks(callbacks, "delete");
- injectSDNCCallbacks(callbacks, "unassign");
-
- BPMNUtil.waitForWorkflowToFinish(processEngine,processId);
-
- Assert.assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, "WorkflowException",processId);
- System.out.println("workflowException:\n" + workflowException);
- assertNull(workflowException);
- logEnd();
- }
-
- @Test
- public void testDoDeleteAllottedResourceTXC_ARNotInSDNC() throws Exception {
- logStart();
- MockQueryAllottedResourceById(wireMockServer, ARID, "GenericFlows/getARUrlById.xml");
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockSDNCAdapter(wireMockServer, 200);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables);
-
- variables.put("failNotFound", "false");
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- injectSDNCCallbacks(callbacks, "deactivateNF");
-
- BPMNUtil.waitForWorkflowToFinish(processEngine,processId);
-
- Assert.assertTrue(isProcessEndedByProcessInstanceId(processId));
- logEnd();
- }
-
-
- @Test
- public void testDoDeleteAllottedResourceTXC_SubProcessError() throws Exception {
- logStart();
- MockQueryAllottedResourceById(wireMockServer, ARID, "GenericFlows/getARUrlById.xml");
- MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml");
- MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
- MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
- mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
-
- mockSDNCAdapter(wireMockServer, 500);
-
- Map<String, Object> variables = new HashMap<>();
- setVariablesSuccess(variables);
-
- String processId = invokeSubProcess(PROCNAME, variables);
-
- BPMNUtil.waitForWorkflowToFinish(processEngine,processId);
-
- Assert.assertTrue(isProcessEndedByProcessInstanceId(processId));
- String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, "WorkflowException",processId);
- System.out.println("workflowException:\n" + workflowException);
- assertNotNull(workflowException);
- logEnd();
- }
-
- private void setVariablesSuccess(Map<String, Object> variables) {
- variables.put("isDebugLogEnabled", "true");
- variables.put("failNotFound", "true");
- variables.put("msoRequestId", "testRequestId1");
- variables.put("mso-request-id", "requestId");
- variables.put("allottedResourceId", ARID);
-
- variables.put("serviceInstanceId", DEC_INST);
- variables.put("parentServiceInstanceId", DEC_PARENT_INST);
- }
+ private static final String PROCNAME = "DoDeleteAllottedResourceTXC";
+ private final CallbackSet callbacks = new CallbackSet();
+
+ public DoDeleteAllottedResourceTXCIT() {
+ callbacks.put("deactivate",
+ FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallback.xml"));
+ callbacks.put("deactivateNF",
+ FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeactivateCallbackNotFound.xml"));
+ callbacks.put("delete", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyDeleteCallback.xml"));
+ callbacks.put("unassign", FileUtil.readResourceFile("__files/VfModularity/SDNCTopologyUnassignCallback.xml"));
+ }
+
+ @Test
+ public void testDoDeleteAllottedResourceTXC_Success() throws Exception {
+ logStart();
+ MockQueryAllottedResourceById(wireMockServer, ARID, "GenericFlows/getARUrlById.xml");
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables);
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ injectSDNCCallbacks(callbacks, "deactivate");
+ injectSDNCCallbacks(callbacks, "delete");
+ injectSDNCCallbacks(callbacks, "unassign");
+
+ BPMNUtil.waitForWorkflowToFinish(processEngine, processId);
+
+ Assert.assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, "WorkflowException", processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertNull(workflowException);
+ logEnd();
+ }
+
+ @Test
+ public void testDoDeleteAllottedResourceTXC_ARNotInSDNC() throws Exception {
+ logStart();
+ MockQueryAllottedResourceById(wireMockServer, ARID, "GenericFlows/getARUrlById.xml");
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockSDNCAdapter(wireMockServer, 200);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables);
+
+ variables.put("failNotFound", "false");
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ injectSDNCCallbacks(callbacks, "deactivateNF");
+
+ BPMNUtil.waitForWorkflowToFinish(processEngine, processId);
+
+ Assert.assertTrue(isProcessEndedByProcessInstanceId(processId));
+ logEnd();
+ }
+
+
+ @Test
+ public void testDoDeleteAllottedResourceTXC_SubProcessError() throws Exception {
+ logStart();
+ MockQueryAllottedResourceById(wireMockServer, ARID, "GenericFlows/getARUrlById.xml");
+ MockGetAllottedResource(wireMockServer, CUST, SVC, INST, ARID,
+ "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml");
+ MockPatchAllottedResource(wireMockServer, CUST, SVC, INST, ARID);
+ MockDeleteAllottedResource(wireMockServer, CUST, SVC, INST, ARID, ARVERS);
+ mockUpdateRequestDB(wireMockServer, 200, "Database/DBUpdateResponse.xml");
+
+ mockSDNCAdapter(wireMockServer, 500);
+
+ Map<String, Object> variables = new HashMap<>();
+ setVariablesSuccess(variables);
+
+ String processId = invokeSubProcess(PROCNAME, variables);
+
+ BPMNUtil.waitForWorkflowToFinish(processEngine, processId);
+
+ Assert.assertTrue(isProcessEndedByProcessInstanceId(processId));
+ String workflowException = BPMNUtil.getVariable(processEngine, PROCNAME, "WorkflowException", processId);
+ System.out.println("workflowException:\n" + workflowException);
+ assertNotNull(workflowException);
+ logEnd();
+ }
+
+ private void setVariablesSuccess(Map<String, Object> variables) {
+ variables.put("isDebugLogEnabled", "true");
+ variables.put("failNotFound", "true");
+ variables.put("msoRequestId", "testRequestId1");
+ variables.put("mso-request-id", "requestId");
+ variables.put("allottedResourceId", ARID);
+
+ variables.put("serviceInstanceId", DEC_INST);
+ variables.put("parentServiceInstanceId", DEC_PARENT_INST);
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/main/java/org/onap/so/bpmn/infrastructure/bpmn/activity/DeployActivitySpecs.java b/bpmn/so-bpmn-building-blocks/src/main/java/org/onap/so/bpmn/infrastructure/bpmn/activity/DeployActivitySpecs.java
index db1f7cb6f9..e4f1998c40 100644
--- a/bpmn/so-bpmn-building-blocks/src/main/java/org/onap/so/bpmn/infrastructure/bpmn/activity/DeployActivitySpecs.java
+++ b/bpmn/so-bpmn-building-blocks/src/main/java/org/onap/so/bpmn/infrastructure/bpmn/activity/DeployActivitySpecs.java
@@ -23,9 +23,7 @@ package org.onap.so.bpmn.infrastructure.bpmn.activity;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import javax.ws.rs.core.UriBuilder;
-
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
@@ -36,68 +34,65 @@ import org.springframework.stereotype.Component;
@Component
public class DeployActivitySpecs {
- private static final String ACTIVITY_FILE_LOCATION = "src/main/resources/ActivitySpec/";
- private static final String ACTIVITY_SPEC_URI = "/activityspec-api/v1.0/activity-spec";
- private static final String CONTENT_TYPE_JSON = "application/json";
-
- public static void main(String[] args) throws Exception {
-
- if (args == null || args.length == 0) {
- System.out.println("Please specify hostname argument");
- return;
- }
-
- String hostname = args[0];
-
- File dir = new File(ACTIVITY_FILE_LOCATION);
- if (!dir.isDirectory()) {
- System.out.println("ActivitySpec store is not a directory");
- return;
- }
-
- for (File f : dir.listFiles()) {
- String activitySpecName = f.getName();
- String errorMessage = deployActivitySpec(hostname, activitySpecName);
- if (errorMessage == null) {
- System.out.println("Deployed Activity Spec: " + activitySpecName);
- }
- else {
- System.out.println("Error deploying Activity Spec: " + activitySpecName + " : " + errorMessage);
- }
- }
- return;
- }
-
- protected static String deployActivitySpec(String hostname, String activitySpecName) throws Exception {
- String payload = new String(Files.readAllBytes(Paths.get(ACTIVITY_FILE_LOCATION + activitySpecName)));
- try {
- HttpClient client = HttpClientBuilder.create().build();
-
- String url = UriBuilder.fromUri(hostname).path(ACTIVITY_SPEC_URI).build().toString();
- HttpPost post = new HttpPost(url);
-
- StringEntity input = new StringEntity(payload);
- input.setContentType(CONTENT_TYPE_JSON);
- post.setEntity(input);
-
- HttpResponse response = client.execute(post);
- StatusLine statusLine = response.getStatusLine();
-
- if (statusLine != null) {
- if (statusLine.getStatusCode() != 200) {
- return (statusLine.toString());
- }
- else {
- return null;
- }
- }
- else {
- return("Empty response from the remote endpoint");
- }
-
- } catch (Exception e) {
- return e.getMessage();
- }
-
- }
+ private static final String ACTIVITY_FILE_LOCATION = "src/main/resources/ActivitySpec/";
+ private static final String ACTIVITY_SPEC_URI = "/activityspec-api/v1.0/activity-spec";
+ private static final String CONTENT_TYPE_JSON = "application/json";
+
+ public static void main(String[] args) throws Exception {
+
+ if (args == null || args.length == 0) {
+ System.out.println("Please specify hostname argument");
+ return;
+ }
+
+ String hostname = args[0];
+
+ File dir = new File(ACTIVITY_FILE_LOCATION);
+ if (!dir.isDirectory()) {
+ System.out.println("ActivitySpec store is not a directory");
+ return;
+ }
+
+ for (File f : dir.listFiles()) {
+ String activitySpecName = f.getName();
+ String errorMessage = deployActivitySpec(hostname, activitySpecName);
+ if (errorMessage == null) {
+ System.out.println("Deployed Activity Spec: " + activitySpecName);
+ } else {
+ System.out.println("Error deploying Activity Spec: " + activitySpecName + " : " + errorMessage);
+ }
+ }
+ return;
+ }
+
+ protected static String deployActivitySpec(String hostname, String activitySpecName) throws Exception {
+ String payload = new String(Files.readAllBytes(Paths.get(ACTIVITY_FILE_LOCATION + activitySpecName)));
+ try {
+ HttpClient client = HttpClientBuilder.create().build();
+
+ String url = UriBuilder.fromUri(hostname).path(ACTIVITY_SPEC_URI).build().toString();
+ HttpPost post = new HttpPost(url);
+
+ StringEntity input = new StringEntity(payload);
+ input.setContentType(CONTENT_TYPE_JSON);
+ post.setEntity(input);
+
+ HttpResponse response = client.execute(post);
+ StatusLine statusLine = response.getStatusLine();
+
+ if (statusLine != null) {
+ if (statusLine.getStatusCode() != 200) {
+ return (statusLine.toString());
+ } else {
+ return null;
+ }
+ } else {
+ return ("Empty response from the remote endpoint");
+ }
+
+ } catch (Exception e) {
+ return e.getMessage();
+ }
+
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/AllTestSuites.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/AllTestSuites.java
index 98e613efe6..8c8981e6e6 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/AllTestSuites.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/AllTestSuites.java
@@ -19,14 +19,14 @@
*/
package org.onap.so;
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses({"**/*Test.class"})
public class AllTestSuites {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BaseTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BaseTest.java
index 73aa0a7201..5451860a90 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BaseTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BaseTest.java
@@ -26,7 +26,6 @@ import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
-
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.model.bpmn.Bpmn;
@@ -62,7 +61,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -74,134 +72,126 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class BaseTest extends BuildingBlockTestDataSetup {
- protected Map<String, Object> variables = new HashMap<>();
-
- protected TestRestTemplate restTemplate = new TestRestTemplate();
-
- protected HttpHeaders headers = new HttpHeaders();
-
- @Value("${wiremock.server.port}")
- protected String wireMockPort;
+ protected Map<String, Object> variables = new HashMap<>();
- @Autowired
- protected RuntimeService runtimeService;
+ protected TestRestTemplate restTemplate = new TestRestTemplate();
- @Autowired
- private RepositoryService repositoryService;
- /*
- * Mocked for injection via autowiring
- */
+ protected HttpHeaders headers = new HttpHeaders();
- @Value("${mso.catalog.db.spring.endpoint}")
- protected String endpoint;
+ @Value("${wiremock.server.port}")
+ protected String wireMockPort;
- @MockBean
- protected CatalogDbClient MOCK_catalogDbClient;
+ @Autowired
+ protected RuntimeService runtimeService;
- @SpyBean
- protected InjectionHelper MOCK_injectionHelper;
+ @Autowired
+ private RepositoryService repositoryService;
+ /*
+ * Mocked for injection via autowiring
+ */
- @SpyBean
- protected NetworkAdapterObjectMapper MOCK_networkAdapterObjectMapper;
+ @Value("${mso.catalog.db.spring.endpoint}")
+ protected String endpoint;
- @SpyBean
- protected AAIObjectMapper MOCK_aaiObjectMapper;
- @SpyBean
- protected NetworkAdapterClientImpl MOCK_networkAdapterClient;
- @SpyBean
- protected SDNCClient MOCK_sdncClient;
+ @MockBean
+ protected CatalogDbClient MOCK_catalogDbClient;
- @SpyBean
- protected AAIFlagTasks aaiFlagTasks;
+ @SpyBean
+ protected InjectionHelper MOCK_injectionHelper;
- @SpyBean
- protected AAIVnfResources aaiVnfResources;
+ @SpyBean
+ protected NetworkAdapterObjectMapper MOCK_networkAdapterObjectMapper;
- @SpyBean
- protected ExceptionBuilder exceptionUtil;
+ @SpyBean
+ protected AAIObjectMapper MOCK_aaiObjectMapper;
+ @SpyBean
+ protected NetworkAdapterClientImpl MOCK_networkAdapterClient;
+ @SpyBean
+ protected SDNCClient MOCK_sdncClient;
- @SpyBean
- protected SDNOHealthCheckResources MOCK_sdnoHealthCheckResources;
+ @SpyBean
+ protected AAIFlagTasks aaiFlagTasks;
+ @SpyBean
+ protected AAIVnfResources aaiVnfResources;
+ @SpyBean
+ protected ExceptionBuilder exceptionUtil;
+ @SpyBean
+ protected SDNOHealthCheckResources MOCK_sdnoHealthCheckResources;
- /*
- * Classes that cannot be simply mocked because they are both
- * needed for testing another class, and must be autowired when
- * being tested themselves....or classes with private methods that
- * must be stubbed during testing
- */
+ /*
+ * Classes that cannot be simply mocked because they are both needed for testing another class, and must be
+ * autowired when being tested themselves....or classes with private methods that must be stubbed during testing
+ */
+ @SpyBean
+ protected BBInputSetupMapperLayer SPY_bbInputSetupMapperLayer;
+ @SpyBean
+ protected BBInputSetupUtils SPY_bbInputSetupUtils;
+ @SpyBean
+ protected BBInputSetup SPY_bbInputSetup;
+ @SpyBean
+ protected SniroHomingV2 sniroHoming;
- @SpyBean
- protected BBInputSetupMapperLayer SPY_bbInputSetupMapperLayer;
- @SpyBean
- protected BBInputSetupUtils SPY_bbInputSetupUtils;
- @SpyBean
- protected BBInputSetup SPY_bbInputSetup;
- @SpyBean
- protected SniroHomingV2 sniroHoming;
+ @SpyBean
+ protected SniroClient sniroClient;
- @SpyBean
- protected SniroClient sniroClient;
+ @SpyBean
+ protected SDNOHealthCheckTasks sdnoHealthCheckTasks;
- @SpyBean
- protected SDNOHealthCheckTasks sdnoHealthCheckTasks;
+ /*
+ * Mocked for injection via the IntectionHelper
+ */
- /*
- * Mocked for injection via the IntectionHelper
- */
+ @Before
+ public void baseTestBefore() {
+ variables.put("gBuildingBlockExecution", new DelegateExecutionImpl(new HashMap<>()));
- @Before
- public void baseTestBefore() {
- variables.put("gBuildingBlockExecution", new DelegateExecutionImpl(new HashMap<>()));
+ }
- }
+ @LocalServerPort
+ private int port;
- @LocalServerPort
- private int port;
+ protected String readFile(String path) throws IOException {
+ return readFile(path, Charset.defaultCharset());
+ }
- protected String readFile(String path) throws IOException {
- return readFile(path, Charset.defaultCharset());
- }
+ protected String readFile(String path, Charset encoding) throws IOException {
+ byte[] encoded = Files.readAllBytes(Paths.get(path));
+ return new String(encoded, encoding);
+ }
- protected String readFile(String path, Charset encoding) throws IOException {
- byte[] encoded = Files.readAllBytes(Paths.get(path));
- return new String(encoded, encoding);
- }
+ protected String readJsonFileAsString(String fileLocation) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ JsonNode jsonNode = mapper.readTree(new File(fileLocation));
+ return jsonNode.asText();
+ }
- protected String readJsonFileAsString(String fileLocation) throws IOException{
- ObjectMapper mapper = new ObjectMapper();
- JsonNode jsonNode = mapper.readTree(new File(fileLocation));
- return jsonNode.asText();
- }
+ protected String createURLWithPort(String uri) {
+ return "http://localhost:" + port + uri;
+ }
- protected String createURLWithPort(String uri) {
- return "http://localhost:" + port + uri;
- }
- /**
- * Create and deploy a process model with one logger delegate as service task.
- *
- * @param origProcessKey
- * key to call
- * @param mockProcessName
- * process name
- * @param fileName
- * file name without extension
- */
- protected void mockSubprocess(String origProcessKey, String mockProcessName, String fileName) {
- BpmnModelInstance modelInstance = Bpmn.createExecutableProcess(origProcessKey).name(mockProcessName)
- .startEvent().name("Start Point").serviceTask().name("Log Something for Test")
- .camundaClass(MockLoggerDelegate.class.getName()).endEvent().name("End Point").done();
- repositoryService.createDeployment().addModelInstance(fileName + ".bpmn", modelInstance).deploy();
- }
+ /**
+ * Create and deploy a process model with one logger delegate as service task.
+ *
+ * @param origProcessKey key to call
+ * @param mockProcessName process name
+ * @param fileName file name without extension
+ */
+ protected void mockSubprocess(String origProcessKey, String mockProcessName, String fileName) {
+ BpmnModelInstance modelInstance = Bpmn.createExecutableProcess(origProcessKey).name(mockProcessName)
+ .startEvent().name("Start Point").serviceTask().name("Log Something for Test")
+ .camundaClass(MockLoggerDelegate.class.getName()).endEvent().name("End Point").done();
+ repositoryService.createDeployment().addModelInstance(fileName + ".bpmn", modelInstance).deploy();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BaseUnitTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BaseUnitTest.java
index 5719ce15e2..fc5709d1be 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BaseUnitTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BaseUnitTest.java
@@ -20,6 +20,6 @@
package org.onap.so;
-public abstract class BaseUnitTest extends BuildingBlockTestDataSetup{
+public abstract class BaseUnitTest extends BuildingBlockTestDataSetup {
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java
index 6aa5cf3412..47b05f9690 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java
@@ -21,15 +21,12 @@ package org.onap.so;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.impl.pvm.runtime.ExecutionImpl;
import org.junit.Before;
@@ -72,507 +69,509 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.AllottedResource;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoAllottedResource;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceProxy;
-public class BuildingBlockTestDataSetup{
- private int collectionCounter;
- private int configurationCounter;
- private int customerCounter;
- private int genericVnfCounter;
- private int instanceGroupCounter;
- private int l3NetworkCounter;
- private int owningEntityCounter;
- private int pnfCounter;
- private int projectCounter;
- private int serviceInstanceCounter;
- private int serviceProxyCounter;
- private int serviceSubscriptionCounter;
- private int vfModuleCounter;
- private int volumeGroupCounter;
- private int vpnBindingCounter;
- private int vpnBondingLinkCounter;
-
- protected BuildingBlockExecution execution;
-
- protected GeneralBuildingBlock gBBInput;
-
- protected HashMap<ResourceKey, String> lookupKeyMap;
-
- protected ExtractPojosForBB extractPojosForBB = new ExtractPojosForBB();
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- protected DelegateExecution delegateExecution;
-
- @Before
- public void buildingBlockTestDataSetupBefore() {
- collectionCounter = 0;
- configurationCounter = 0;
- customerCounter = 0;
- genericVnfCounter = 0;
- instanceGroupCounter = 0;
- l3NetworkCounter = 0;
- owningEntityCounter = 0;
- pnfCounter = 0;
- projectCounter = 0;
- serviceInstanceCounter = 0;
- serviceProxyCounter = 0;
- serviceSubscriptionCounter = 0;
- vfModuleCounter = 0;
- volumeGroupCounter = 0;
- vpnBindingCounter = 0;
- vpnBondingLinkCounter = 0;
-
- execution = new DelegateExecutionImpl(new ExecutionImpl());
- execution.setVariable("testProcessKey", "testProcessKeyValue");
-
- gBBInput = new GeneralBuildingBlock();
- execution.setVariable("gBBInput", gBBInput);
-
- lookupKeyMap = new HashMap<ResourceKey, String>();
- execution.setVariable("lookupKeyMap", lookupKeyMap);
-
- ExecutionImpl mockExecutionImpl = mock(ExecutionImpl.class);
- doReturn("test").when(mockExecutionImpl).getProcessInstanceId();
-
- ExecutionImpl executionImpl = new ExecutionImpl();
- executionImpl.setProcessInstance(mockExecutionImpl);
-
- delegateExecution = (DelegateExecution) executionImpl;
- delegateExecution.setVariable("testProcessKey", "testProcessKeyValue");
- }
-
- public Map<String, String> buildUserInput() {
- Map<String, String> userInput = new HashMap<>();
- userInput.put("testUserInputKey", "testUserInputValue");
-
- return userInput;
- }
-
- public Map<String, String> setUserInput() {
- Map<String, String> userInput = buildUserInput();
-
- gBBInput.setUserInput(userInput);
-
- return userInput;
- }
-
- public RequestContext buildRequestContext() {
- RequestContext requestContext = new RequestContext();
- requestContext.setMsoRequestId(UUID.randomUUID().toString());
- requestContext.setProductFamilyId("testProductFamilyId");
- requestContext.setRequestorId("testRequestorId");
-
- requestContext.setUserParams(new HashMap<>());
-
- Map<String,Object> dataMap = new HashMap<>();
- dataMap.put("vpnId","testVpnId");
- dataMap.put("vpnRegion","testVpnRegion");
- dataMap.put("vpnRt","testVpnRt");
- dataMap.put("vpnName","vpnName");
+public class BuildingBlockTestDataSetup {
+ private int collectionCounter;
+ private int configurationCounter;
+ private int customerCounter;
+ private int genericVnfCounter;
+ private int instanceGroupCounter;
+ private int l3NetworkCounter;
+ private int owningEntityCounter;
+ private int pnfCounter;
+ private int projectCounter;
+ private int serviceInstanceCounter;
+ private int serviceProxyCounter;
+ private int serviceSubscriptionCounter;
+ private int vfModuleCounter;
+ private int volumeGroupCounter;
+ private int vpnBindingCounter;
+ private int vpnBondingLinkCounter;
+
+ protected BuildingBlockExecution execution;
+
+ protected GeneralBuildingBlock gBBInput;
+
+ protected HashMap<ResourceKey, String> lookupKeyMap;
+
+ protected ExtractPojosForBB extractPojosForBB = new ExtractPojosForBB();
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ protected DelegateExecution delegateExecution;
+
+ @Before
+ public void buildingBlockTestDataSetupBefore() {
+ collectionCounter = 0;
+ configurationCounter = 0;
+ customerCounter = 0;
+ genericVnfCounter = 0;
+ instanceGroupCounter = 0;
+ l3NetworkCounter = 0;
+ owningEntityCounter = 0;
+ pnfCounter = 0;
+ projectCounter = 0;
+ serviceInstanceCounter = 0;
+ serviceProxyCounter = 0;
+ serviceSubscriptionCounter = 0;
+ vfModuleCounter = 0;
+ volumeGroupCounter = 0;
+ vpnBindingCounter = 0;
+ vpnBondingLinkCounter = 0;
+
+ execution = new DelegateExecutionImpl(new ExecutionImpl());
+ execution.setVariable("testProcessKey", "testProcessKeyValue");
+
+ gBBInput = new GeneralBuildingBlock();
+ execution.setVariable("gBBInput", gBBInput);
+
+ lookupKeyMap = new HashMap<ResourceKey, String>();
+ execution.setVariable("lookupKeyMap", lookupKeyMap);
+
+ ExecutionImpl mockExecutionImpl = mock(ExecutionImpl.class);
+ doReturn("test").when(mockExecutionImpl).getProcessInstanceId();
+
+ ExecutionImpl executionImpl = new ExecutionImpl();
+ executionImpl.setProcessInstance(mockExecutionImpl);
+
+ delegateExecution = (DelegateExecution) executionImpl;
+ delegateExecution.setVariable("testProcessKey", "testProcessKeyValue");
+ }
+
+ public Map<String, String> buildUserInput() {
+ Map<String, String> userInput = new HashMap<>();
+ userInput.put("testUserInputKey", "testUserInputValue");
+
+ return userInput;
+ }
+
+ public Map<String, String> setUserInput() {
+ Map<String, String> userInput = buildUserInput();
+
+ gBBInput.setUserInput(userInput);
+
+ return userInput;
+ }
+
+ public RequestContext buildRequestContext() {
+ RequestContext requestContext = new RequestContext();
+ requestContext.setMsoRequestId(UUID.randomUUID().toString());
+ requestContext.setProductFamilyId("testProductFamilyId");
+ requestContext.setRequestorId("testRequestorId");
+
+ requestContext.setUserParams(new HashMap<>());
+
+ Map<String, Object> dataMap = new HashMap<>();
+ dataMap.put("vpnId", "testVpnId");
+ dataMap.put("vpnRegion", "testVpnRegion");
+ dataMap.put("vpnRt", "testVpnRt");
+ dataMap.put("vpnName", "vpnName");
dataMap.put("vpnRegion", Arrays.asList(new String[] {"USA", "EMEA", "APAC"}));
- HashMap<String,Object> userParams = new HashMap<>();
- userParams.put("vpnData",dataMap);
+ HashMap<String, Object> userParams = new HashMap<>();
+ userParams.put("vpnData", dataMap);
- List<Map<String,Object>> userParamsList = new ArrayList<>();
- userParamsList.add(userParams);
+ List<Map<String, Object>> userParamsList = new ArrayList<>();
+ userParamsList.add(userParams);
- RequestParameters requestParameters = new RequestParameters();
- requestParameters.setUserParams(userParamsList);
- requestContext.setRequestParameters(requestParameters);
+ RequestParameters requestParameters = new RequestParameters();
+ requestParameters.setUserParams(userParamsList);
+ requestContext.setRequestParameters(requestParameters);
- return requestContext;
- }
+ return requestContext;
+ }
- public RequestContext setRequestContext() {
- RequestContext requestContext = buildRequestContext();
+ public RequestContext setRequestContext() {
+ RequestContext requestContext = buildRequestContext();
- gBBInput.setRequestContext(requestContext);
+ gBBInput.setRequestContext(requestContext);
- return requestContext;
- }
+ return requestContext;
+ }
- public CloudRegion buildCloudRegion() {
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("testLcpCloudRegionId");
- cloudRegion.setTenantId("testTenantId");
- cloudRegion.setCloudOwner("testCloudOwner");
+ public CloudRegion buildCloudRegion() {
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("testLcpCloudRegionId");
+ cloudRegion.setTenantId("testTenantId");
+ cloudRegion.setCloudOwner("testCloudOwner");
- return cloudRegion;
- }
+ return cloudRegion;
+ }
- public CloudRegion setCloudRegion() {
- CloudRegion cloudRegion = buildCloudRegion();
+ public CloudRegion setCloudRegion() {
+ CloudRegion cloudRegion = buildCloudRegion();
- gBBInput.setCloudRegion(cloudRegion);
+ gBBInput.setCloudRegion(cloudRegion);
- return cloudRegion;
- }
+ return cloudRegion;
+ }
- public OrchestrationContext buildOrchestrationContext() {
- OrchestrationContext orchestrationContext = new OrchestrationContext();
+ public OrchestrationContext buildOrchestrationContext() {
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
- return orchestrationContext;
- }
+ return orchestrationContext;
+ }
- public OrchestrationContext setOrchestrationContext() {
- OrchestrationContext orchestrationContext = buildOrchestrationContext();
+ public OrchestrationContext setOrchestrationContext() {
+ OrchestrationContext orchestrationContext = buildOrchestrationContext();
- gBBInput.setOrchContext(orchestrationContext);
+ gBBInput.setOrchContext(orchestrationContext);
- return orchestrationContext;
- }
+ return orchestrationContext;
+ }
- public Collection buildCollection() {
- collectionCounter++;
+ public Collection buildCollection() {
+ collectionCounter++;
- Collection collection = new Collection();
- collection.setId("testId" + collectionCounter);
- collection.setInstanceGroup(buildInstanceGroup());
+ Collection collection = new Collection();
+ collection.setId("testId" + collectionCounter);
+ collection.setInstanceGroup(buildInstanceGroup());
- return collection;
- }
+ return collection;
+ }
- public Configuration buildConfiguration() {
- configurationCounter++;
+ public Configuration buildConfiguration() {
+ configurationCounter++;
- Configuration configuration = new Configuration();
- configuration.setConfigurationId("testConfigurationId" + configurationCounter);
- configuration.setConfigurationName("testConfigurationName" + configurationCounter);
+ Configuration configuration = new Configuration();
+ configuration.setConfigurationId("testConfigurationId" + configurationCounter);
+ configuration.setConfigurationName("testConfigurationName" + configurationCounter);
- ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
- modelInfoConfiguration.setModelVersionId("testModelVersionId" + configurationCounter);
- modelInfoConfiguration.setModelInvariantId("testModelInvariantId" + configurationCounter);
- modelInfoConfiguration.setModelCustomizationId("testModelCustomizationId" + configurationCounter);
+ ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
+ modelInfoConfiguration.setModelVersionId("testModelVersionId" + configurationCounter);
+ modelInfoConfiguration.setModelInvariantId("testModelInvariantId" + configurationCounter);
+ modelInfoConfiguration.setModelCustomizationId("testModelCustomizationId" + configurationCounter);
- configuration.setModelInfoConfiguration(modelInfoConfiguration);
+ configuration.setModelInfoConfiguration(modelInfoConfiguration);
- return configuration;
- }
+ return configuration;
+ }
- public OwningEntity buildOwningEntity() {
- owningEntityCounter++;
+ public OwningEntity buildOwningEntity() {
+ owningEntityCounter++;
- OwningEntity owningEntity = new OwningEntity();
- owningEntity.setOwningEntityId("testOwningEntityId" + owningEntityCounter);
- owningEntity.setOwningEntityName("testOwningEntityName" + owningEntityCounter);
+ OwningEntity owningEntity = new OwningEntity();
+ owningEntity.setOwningEntityId("testOwningEntityId" + owningEntityCounter);
+ owningEntity.setOwningEntityName("testOwningEntityName" + owningEntityCounter);
- return owningEntity;
- }
+ return owningEntity;
+ }
- public Project buildProject() {
- projectCounter++;
+ public Project buildProject() {
+ projectCounter++;
- Project project = new Project();
- project.setProjectName("testProjectName" + projectCounter);
+ Project project = new Project();
+ project.setProjectName("testProjectName" + projectCounter);
- return project;
- }
+ return project;
+ }
- public ServiceSubscription buildServiceSubscription() {
- serviceSubscriptionCounter++;
+ public ServiceSubscription buildServiceSubscription() {
+ serviceSubscriptionCounter++;
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- serviceSubscription.setTempUbSubAccountId("testTempUbSubAccountId" + serviceSubscriptionCounter);
- serviceSubscription.setServiceType("testServiceType" + serviceSubscriptionCounter);
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ serviceSubscription.setTempUbSubAccountId("testTempUbSubAccountId" + serviceSubscriptionCounter);
+ serviceSubscription.setServiceType("testServiceType" + serviceSubscriptionCounter);
- return serviceSubscription;
- }
+ return serviceSubscription;
+ }
- public Customer buildCustomer() {
- customerCounter++;
+ public Customer buildCustomer() {
+ customerCounter++;
- Customer customer = new Customer();
- customer.setGlobalCustomerId("testGlobalCustomerId" + customerCounter);
- customer.setSubscriberType("testSubscriberType" + customerCounter);
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("testGlobalCustomerId" + customerCounter);
+ customer.setSubscriberType("testSubscriberType" + customerCounter);
- customer.setServiceSubscription(buildServiceSubscription());
+ customer.setServiceSubscription(buildServiceSubscription());
- return customer;
- }
+ return customer;
+ }
- public ServiceInstance buildServiceInstance() {
- serviceInstanceCounter++;
+ public ServiceInstance buildServiceInstance() {
+ serviceInstanceCounter++;
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("testServiceInstanceId" + serviceInstanceCounter);
- serviceInstance.setServiceInstanceName("testServiceInstanceName" + serviceInstanceCounter);
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("testServiceInstanceId" + serviceInstanceCounter);
+ serviceInstance.setServiceInstanceName("testServiceInstanceName" + serviceInstanceCounter);
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("testModelInvariantUUID" + serviceInstanceCounter);
- modelInfoServiceInstance.setModelUuid("testModelUUID" + serviceInstanceCounter);
- modelInfoServiceInstance.setModelVersion("testModelVersion" + serviceInstanceCounter);
- modelInfoServiceInstance.setModelName("testModelName" + serviceInstanceCounter);
- modelInfoServiceInstance.setServiceType("testServiceType" + serviceInstanceCounter);
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("testModelInvariantUUID" + serviceInstanceCounter);
+ modelInfoServiceInstance.setModelUuid("testModelUUID" + serviceInstanceCounter);
+ modelInfoServiceInstance.setModelVersion("testModelVersion" + serviceInstanceCounter);
+ modelInfoServiceInstance.setModelName("testModelName" + serviceInstanceCounter);
+ modelInfoServiceInstance.setServiceType("testServiceType" + serviceInstanceCounter);
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
- serviceInstance.setProject(buildProject());
+ serviceInstance.setProject(buildProject());
- serviceInstance.setOwningEntity(buildOwningEntity());
+ serviceInstance.setOwningEntity(buildOwningEntity());
- serviceInstance.setCollection(buildCollection());
+ serviceInstance.setCollection(buildCollection());
- serviceInstance.getConfigurations().add(buildConfiguration());
+ serviceInstance.getConfigurations().add(buildConfiguration());
- return serviceInstance;
- }
+ return serviceInstance;
+ }
- public ServiceInstance setServiceInstance() {
- ServiceInstance serviceInstance = buildServiceInstance();
+ public ServiceInstance setServiceInstance() {
+ ServiceInstance serviceInstance = buildServiceInstance();
- if(gBBInput.getCustomer() == null) {
- gBBInput.setCustomer(buildCustomer());
- }
- gBBInput.getCustomer().getServiceSubscription().getServiceInstances().add(serviceInstance);
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstance.getServiceInstanceId());
+ if (gBBInput.getCustomer() == null) {
+ gBBInput.setCustomer(buildCustomer());
+ }
+ gBBInput.getCustomer().getServiceSubscription().getServiceInstances().add(serviceInstance);
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstance.getServiceInstanceId());
- return serviceInstance;
- }
+ return serviceInstance;
+ }
- public Customer setCustomer() {
- if(gBBInput.getCustomer() != null) return gBBInput.getCustomer();
- Customer customer = new Customer();
- customer.setGlobalCustomerId("testGlobalCustomerId");
- customer.setSubscriberType("testSubscriberType");
+ public Customer setCustomer() {
+ if (gBBInput.getCustomer() != null)
+ return gBBInput.getCustomer();
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("testGlobalCustomerId");
+ customer.setSubscriberType("testSubscriberType");
- customer.setServiceSubscription(buildServiceSubscription());
+ customer.setServiceSubscription(buildServiceSubscription());
- gBBInput.setCustomer(customer);
+ gBBInput.setCustomer(customer);
- return customer;
- }
+ return customer;
+ }
- public Collection setCollection() {
- Collection collection = new Collection();
- collection.setId("testId");
+ public Collection setCollection() {
+ Collection collection = new Collection();
+ collection.setId("testId");
- ServiceInstance serviceInstance = null;
+ ServiceInstance serviceInstance = null;
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
- serviceInstance.setCollection(collection);
+ serviceInstance.setCollection(collection);
- return collection;
- }
+ return collection;
+ }
- public InstanceGroup setInstanceGroup() {
- InstanceGroup instanceGroup = new InstanceGroup();
- instanceGroup.setId("testId");
- instanceGroup.setInstanceGroupFunction("testInstanceGroupFunction");
+ public InstanceGroup setInstanceGroup() {
+ InstanceGroup instanceGroup = new InstanceGroup();
+ instanceGroup.setId("testId");
+ instanceGroup.setInstanceGroupFunction("testInstanceGroupFunction");
- Collection collection = null;
+ Collection collection = null;
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- collection = serviceInstance.getCollection();
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ collection = serviceInstance.getCollection();
- if (collection == null) {
- collection = setCollection();
- }
- } catch(BBObjectNotFoundException e) {
- collection = setCollection();
- }
+ if (collection == null) {
+ collection = setCollection();
+ }
+ } catch (BBObjectNotFoundException e) {
+ collection = setCollection();
+ }
- collection.setInstanceGroup(instanceGroup);
+ collection.setInstanceGroup(instanceGroup);
- return instanceGroup;
- }
+ return instanceGroup;
+ }
- public VpnBinding buildVpnBinding() {
- vpnBindingCounter++;
+ public VpnBinding buildVpnBinding() {
+ vpnBindingCounter++;
- VpnBinding vpnBinding = new VpnBinding();
- vpnBinding.setVpnId("testVpnId" + vpnBindingCounter);
- vpnBinding.setVpnName("testVpnName" + vpnBindingCounter);
- vpnBinding.setCustomerVpnId("testCustomerVpnId" + vpnBindingCounter);
+ VpnBinding vpnBinding = new VpnBinding();
+ vpnBinding.setVpnId("testVpnId" + vpnBindingCounter);
+ vpnBinding.setVpnName("testVpnName" + vpnBindingCounter);
+ vpnBinding.setCustomerVpnId("testCustomerVpnId" + vpnBindingCounter);
- return vpnBinding;
- }
+ return vpnBinding;
+ }
- public VpnBinding setVpnBinding() {
- VpnBinding vpnBinding = buildVpnBinding();
+ public VpnBinding setVpnBinding() {
+ VpnBinding vpnBinding = buildVpnBinding();
- Customer customer = gBBInput.getCustomer();
+ Customer customer = gBBInput.getCustomer();
- if(customer == null){
- customer = buildCustomer();
- }
+ if (customer == null) {
+ customer = buildCustomer();
+ }
- customer.getVpnBindings().add(vpnBinding);
- lookupKeyMap.put(ResourceKey.VPN_ID, vpnBinding.getVpnId());
+ customer.getVpnBindings().add(vpnBinding);
+ lookupKeyMap.put(ResourceKey.VPN_ID, vpnBinding.getVpnId());
- return vpnBinding;
- }
+ return vpnBinding;
+ }
- public InstanceGroup buildInstanceGroup() {
- instanceGroupCounter++;
+ public InstanceGroup buildInstanceGroup() {
+ instanceGroupCounter++;
- InstanceGroup instanceGroup = new InstanceGroup();
- instanceGroup.setId("testId" + instanceGroupCounter);
- instanceGroup.setInstanceGroupFunction("testInstanceGroupFunction" + instanceGroupCounter);
+ InstanceGroup instanceGroup = new InstanceGroup();
+ instanceGroup.setId("testId" + instanceGroupCounter);
+ instanceGroup.setInstanceGroupFunction("testInstanceGroupFunction" + instanceGroupCounter);
- return instanceGroup;
- }
+ return instanceGroup;
+ }
- public L3Network buildL3Network() {
- l3NetworkCounter++;
+ public L3Network buildL3Network() {
+ l3NetworkCounter++;
- L3Network network = new L3Network();
- network.setNetworkId("testNetworkId" + l3NetworkCounter);
- network.setNetworkName("testNetworkName" + l3NetworkCounter);
- network.setNetworkType("testNetworkType" + l3NetworkCounter);
+ L3Network network = new L3Network();
+ network.setNetworkId("testNetworkId" + l3NetworkCounter);
+ network.setNetworkName("testNetworkName" + l3NetworkCounter);
+ network.setNetworkType("testNetworkType" + l3NetworkCounter);
- ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
- modelInfoNetwork.setModelInvariantUUID("testModelInvariantUUID" + l3NetworkCounter);
- modelInfoNetwork.setModelName("testModelName" + l3NetworkCounter);
- modelInfoNetwork.setModelVersion("testModelVersion" + l3NetworkCounter);
- modelInfoNetwork.setModelUUID("testModelUUID" + l3NetworkCounter);
- network.setModelInfoNetwork(modelInfoNetwork);
+ ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
+ modelInfoNetwork.setModelInvariantUUID("testModelInvariantUUID" + l3NetworkCounter);
+ modelInfoNetwork.setModelName("testModelName" + l3NetworkCounter);
+ modelInfoNetwork.setModelVersion("testModelVersion" + l3NetworkCounter);
+ modelInfoNetwork.setModelUUID("testModelUUID" + l3NetworkCounter);
+ network.setModelInfoNetwork(modelInfoNetwork);
- return network;
- }
+ return network;
+ }
- public L3Network setL3Network() {
- L3Network network = buildL3Network();
+ public L3Network setL3Network() {
+ L3Network network = buildL3Network();
- ServiceInstance serviceInstance = null;
+ ServiceInstance serviceInstance = null;
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
- serviceInstance.getNetworks().add(network);
- lookupKeyMap.put(ResourceKey.NETWORK_ID, network.getNetworkId());
+ serviceInstance.getNetworks().add(network);
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, network.getNetworkId());
- return network;
- }
+ return network;
+ }
- public GenericVnf buildGenericVnf() {
- genericVnfCounter++;
+ public GenericVnf buildGenericVnf() {
+ genericVnfCounter++;
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId("testVnfId" + genericVnfCounter);
- genericVnf.setVnfName("testVnfName" + genericVnfCounter);
- genericVnf.setVnfType("testVnfType" + genericVnfCounter);
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId("testVnfId" + genericVnfCounter);
+ genericVnf.setVnfName("testVnfName" + genericVnfCounter);
+ genericVnf.setVnfType("testVnfType" + genericVnfCounter);
- Platform platform = new Platform();
- platform.setPlatformName("testPlatformName");
- genericVnf.setPlatform(platform);
+ Platform platform = new Platform();
+ platform.setPlatformName("testPlatformName");
+ genericVnf.setPlatform(platform);
- LineOfBusiness lob = new LineOfBusiness();
- lob.setLineOfBusinessName("testLineOfBusinessName");
- genericVnf.setLineOfBusiness(lob);
+ LineOfBusiness lob = new LineOfBusiness();
+ lob.setLineOfBusinessName("testLineOfBusinessName");
+ genericVnf.setLineOfBusiness(lob);
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelName("testModelName" + genericVnfCounter);
- modelInfoGenericVnf.setModelCustomizationUuid("testModelCustomizationUUID" + genericVnfCounter);
- modelInfoGenericVnf.setModelInvariantUuid("testModelInvariantUUID" + genericVnfCounter);
- modelInfoGenericVnf.setModelVersion("testModelVersion" + genericVnfCounter);
- modelInfoGenericVnf.setModelUuid("testModelUUID" + genericVnfCounter);
- modelInfoGenericVnf.setModelInstanceName("testModelInstanceName" + genericVnfCounter);
- genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelName("testModelName" + genericVnfCounter);
+ modelInfoGenericVnf.setModelCustomizationUuid("testModelCustomizationUUID" + genericVnfCounter);
+ modelInfoGenericVnf.setModelInvariantUuid("testModelInvariantUUID" + genericVnfCounter);
+ modelInfoGenericVnf.setModelVersion("testModelVersion" + genericVnfCounter);
+ modelInfoGenericVnf.setModelUuid("testModelUUID" + genericVnfCounter);
+ modelInfoGenericVnf.setModelInstanceName("testModelInstanceName" + genericVnfCounter);
+ genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf);
- return genericVnf;
- }
+ return genericVnf;
+ }
- public GenericVnf setGenericVnf() {
- GenericVnf genericVnf = buildGenericVnf();
+ public GenericVnf setGenericVnf() {
+ GenericVnf genericVnf = buildGenericVnf();
- ServiceInstance serviceInstance = null;
+ ServiceInstance serviceInstance = null;
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
- serviceInstance.getVnfs().add(genericVnf);
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, genericVnf.getVnfId());
+ serviceInstance.getVnfs().add(genericVnf);
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, genericVnf.getVnfId());
- return genericVnf;
- }
+ return genericVnf;
+ }
- public VfModule buildVfModule() {
- vfModuleCounter++;
+ public VfModule buildVfModule() {
+ vfModuleCounter++;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("testVfModuleId" + vfModuleCounter);
- vfModule.setVfModuleName("testVfModuleName" + vfModuleCounter);
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("testVfModuleId" + vfModuleCounter);
+ vfModule.setVfModuleName("testVfModuleName" + vfModuleCounter);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("testModelInvariantUUID" + vfModuleCounter);
- modelInfoVfModule.setModelVersion("testModelVersion" + vfModuleCounter);
- modelInfoVfModule.setModelUUID("testModelUUID" + vfModuleCounter);
- modelInfoVfModule.setModelName("testModelName" + vfModuleCounter);
- modelInfoVfModule.setModelCustomizationUUID("testModelCustomizationUUID" + vfModuleCounter);
- vfModule.setModelInfoVfModule(modelInfoVfModule);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("testModelInvariantUUID" + vfModuleCounter);
+ modelInfoVfModule.setModelVersion("testModelVersion" + vfModuleCounter);
+ modelInfoVfModule.setModelUUID("testModelUUID" + vfModuleCounter);
+ modelInfoVfModule.setModelName("testModelName" + vfModuleCounter);
+ modelInfoVfModule.setModelCustomizationUUID("testModelCustomizationUUID" + vfModuleCounter);
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
- return vfModule;
- }
+ return vfModule;
+ }
- public VfModule setVfModule() {
- VfModule vfModule = buildVfModule();
+ public VfModule setVfModule() {
+ VfModule vfModule = buildVfModule();
- GenericVnf genericVnf = null;
+ GenericVnf genericVnf = null;
- try {
- genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- } catch(BBObjectNotFoundException e) {
- genericVnf = setGenericVnf();
- }
+ try {
+ genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ } catch (BBObjectNotFoundException e) {
+ genericVnf = setGenericVnf();
+ }
- genericVnf.getVfModules().add(vfModule);
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, vfModule.getVfModuleId());
+ genericVnf.getVfModules().add(vfModule);
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, vfModule.getVfModuleId());
- return vfModule;
- }
+ return vfModule;
+ }
- public VolumeGroup buildVolumeGroup() {
- volumeGroupCounter++;
+ public VolumeGroup buildVolumeGroup() {
+ volumeGroupCounter++;
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("testVolumeGroupId" + volumeGroupCounter);
- volumeGroup.setVolumeGroupName("testVolumeGroupName" + volumeGroupCounter);
- volumeGroup.setHeatStackId("testHeatStackId" + volumeGroupCounter);
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("testVolumeGroupId" + volumeGroupCounter);
+ volumeGroup.setVolumeGroupName("testVolumeGroupName" + volumeGroupCounter);
+ volumeGroup.setHeatStackId("testHeatStackId" + volumeGroupCounter);
- return volumeGroup;
- }
+ return volumeGroup;
+ }
- public VolumeGroup setVolumeGroup() {
- VolumeGroup volumeGroup = buildVolumeGroup();
+ public VolumeGroup setVolumeGroup() {
+ VolumeGroup volumeGroup = buildVolumeGroup();
- GenericVnf genericVnf = null;
+ GenericVnf genericVnf = null;
- try {
- genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- } catch(BBObjectNotFoundException e) {
- genericVnf = setGenericVnf();
- }
+ try {
+ genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ } catch (BBObjectNotFoundException e) {
+ genericVnf = setGenericVnf();
+ }
- genericVnf.getVolumeGroups().add(volumeGroup);
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroup.getVolumeGroupId());
+ genericVnf.getVolumeGroups().add(volumeGroup);
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroup.getVolumeGroupId());
- return volumeGroup;
- }
+ return volumeGroup;
+ }
- public Pnf buildPnf() {
- pnfCounter++;
+ public Pnf buildPnf() {
+ pnfCounter++;
- Pnf pnf = new Pnf();
- pnf.setPnfId("testPnfId" + pnfCounter);
- pnf.setPnfName("testPnfName" + pnfCounter);
+ Pnf pnf = new Pnf();
+ pnf.setPnfId("testPnfId" + pnfCounter);
+ pnf.setPnfName("testPnfName" + pnfCounter);
- return pnf;
- }
+ return pnf;
+ }
- public ServiceProxy buildServiceProxy() {
- serviceProxyCounter++;
+ public ServiceProxy buildServiceProxy() {
+ serviceProxyCounter++;
ServiceProxy serviceProxy = new ServiceProxy();
serviceProxy.setServiceInstance(buildServiceInstance());
@@ -587,83 +586,83 @@ public class BuildingBlockTestDataSetup{
serviceProxy.getServiceInstance().getPnfs().add(secondaryPnf);
return serviceProxy;
- }
+ }
- public VpnBondingLink buildVpnBondingLink() {
- vpnBondingLinkCounter++;
+ public VpnBondingLink buildVpnBondingLink() {
+ vpnBondingLinkCounter++;
- VpnBondingLink vpnBondingLink = new VpnBondingLink();
- vpnBondingLink.setVpnBondingLinkId("testVpnBondingLinkId" + vpnBondingLinkCounter);
+ VpnBondingLink vpnBondingLink = new VpnBondingLink();
+ vpnBondingLink.setVpnBondingLinkId("testVpnBondingLinkId" + vpnBondingLinkCounter);
- Configuration vnrConfiguration = buildConfiguration();
- vnrConfiguration.setNetwork(buildL3Network());
- vpnBondingLink.setVnrConfiguration(vnrConfiguration);
+ Configuration vnrConfiguration = buildConfiguration();
+ vnrConfiguration.setNetwork(buildL3Network());
+ vpnBondingLink.setVnrConfiguration(vnrConfiguration);
- vpnBondingLink.setVrfConfiguration(buildConfiguration());
+ vpnBondingLink.setVrfConfiguration(buildConfiguration());
vpnBondingLink.setInfrastructureServiceProxy(buildServiceProxy());
vpnBondingLink.setTransportServiceProxy(buildServiceProxy());
- return vpnBondingLink;
- }
+ return vpnBondingLink;
+ }
- public VpnBondingLink setVpnBondingLink() {
- VpnBondingLink vpnBondingLink = buildVpnBondingLink();
+ public VpnBondingLink setVpnBondingLink() {
+ VpnBondingLink vpnBondingLink = buildVpnBondingLink();
- ServiceInstance serviceInstance = null;
+ ServiceInstance serviceInstance = null;
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
- serviceInstance.getVpnBondingLinks().add(vpnBondingLink);
- lookupKeyMap.put(ResourceKey.VPN_BONDING_LINK_ID, vpnBondingLink.getVpnBondingLinkId());
+ serviceInstance.getVpnBondingLinks().add(vpnBondingLink);
+ lookupKeyMap.put(ResourceKey.VPN_BONDING_LINK_ID, vpnBondingLink.getVpnBondingLinkId());
- return vpnBondingLink;
- }
+ return vpnBondingLink;
+ }
- public Customer setAvpnCustomer() {
- Customer customer = buildCustomer();
+ public Customer setAvpnCustomer() {
+ Customer customer = buildCustomer();
- gBBInput.setCustomer(customer);
+ gBBInput.setCustomer(customer);
- return customer;
- }
+ return customer;
+ }
- public ServiceProxy setServiceProxy(String uniqueIdentifier, String type) {
- ServiceProxy serviceProxy = new ServiceProxy();
- serviceProxy.setId("testProxyId" + uniqueIdentifier);
- serviceProxy.setType(type);
+ public ServiceProxy setServiceProxy(String uniqueIdentifier, String type) {
+ ServiceProxy serviceProxy = new ServiceProxy();
+ serviceProxy.setId("testProxyId" + uniqueIdentifier);
+ serviceProxy.setType(type);
- ModelInfoServiceProxy modelInfo = new ModelInfoServiceProxy();
- modelInfo.setModelInvariantUuid("testProxyModelInvariantUuid" + uniqueIdentifier);
- modelInfo.setModelName("testProxyModelName" + uniqueIdentifier);
- modelInfo.setModelUuid("testProxyModelUuid" + uniqueIdentifier);
- modelInfo.setModelVersion("testProxyModelVersion" + uniqueIdentifier);
- modelInfo.setModelInstanceName("testProxyModelInstanceName" + uniqueIdentifier);
+ ModelInfoServiceProxy modelInfo = new ModelInfoServiceProxy();
+ modelInfo.setModelInvariantUuid("testProxyModelInvariantUuid" + uniqueIdentifier);
+ modelInfo.setModelName("testProxyModelName" + uniqueIdentifier);
+ modelInfo.setModelUuid("testProxyModelUuid" + uniqueIdentifier);
+ modelInfo.setModelVersion("testProxyModelVersion" + uniqueIdentifier);
+ modelInfo.setModelInstanceName("testProxyModelInstanceName" + uniqueIdentifier);
- serviceProxy.setModelInfoServiceProxy(modelInfo);
+ serviceProxy.setModelInfoServiceProxy(modelInfo);
- return serviceProxy;
- }
+ return serviceProxy;
+ }
- public AllottedResource setAllottedResource(String uniqueIdentifier) {
- AllottedResource ar = new AllottedResource();
- ar.setId("testAllottedResourceId" + uniqueIdentifier);
+ public AllottedResource setAllottedResource(String uniqueIdentifier) {
+ AllottedResource ar = new AllottedResource();
+ ar.setId("testAllottedResourceId" + uniqueIdentifier);
- ModelInfoAllottedResource modelInfo = new ModelInfoAllottedResource();
- modelInfo.setModelInvariantUuid("testAllottedModelInvariantUuid" + uniqueIdentifier);
- modelInfo.setModelName("testAllottedModelName" + uniqueIdentifier);
- modelInfo.setModelUuid("testAllottedModelUuid" + uniqueIdentifier);
- modelInfo.setModelVersion("testAllottedModelVersion" + uniqueIdentifier);
- modelInfo.setModelInstanceName("testAllottedModelInstanceName" + uniqueIdentifier);
+ ModelInfoAllottedResource modelInfo = new ModelInfoAllottedResource();
+ modelInfo.setModelInvariantUuid("testAllottedModelInvariantUuid" + uniqueIdentifier);
+ modelInfo.setModelName("testAllottedModelName" + uniqueIdentifier);
+ modelInfo.setModelUuid("testAllottedModelUuid" + uniqueIdentifier);
+ modelInfo.setModelVersion("testAllottedModelVersion" + uniqueIdentifier);
+ modelInfo.setModelInstanceName("testAllottedModelInstanceName" + uniqueIdentifier);
- ar.setModelInfoAllottedResource(modelInfo);
+ ar.setModelInfoAllottedResource(modelInfo);
- return ar;
- }
-} \ No newline at end of file
+ return ar;
+ }
+}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
index fb08e5e830..62d9ecee44 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
@@ -19,6 +19,7 @@
*/
package org.onap.so;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
@@ -35,30 +36,25 @@ public class EmbeddedMariaDbConfig {
@Bean
MariaDB4jSpringService mariaDB4jSpringService() {
- MariaDB4jSpringService service = new MariaDB4jSpringService();
-
-
- service.getConfiguration().addArg("--lower_case_table_names=1");
+ MariaDB4jSpringService service = new MariaDB4jSpringService();
+
+
+ service.getConfiguration().addArg("--lower_case_table_names=1");
return service;
}
@Bean
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/MockLoggerDelegate.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/MockLoggerDelegate.java
index 5d4d923426..7b049c63e3 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/MockLoggerDelegate.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/MockLoggerDelegate.java
@@ -24,12 +24,12 @@ import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
public class MockLoggerDelegate implements JavaDelegate {
- @Override
- public void execute(DelegateExecution execution) throws Exception {
- System.out.println("\n\n ..." + MockLoggerDelegate.class.getName() + " invoked by " + "processDefinitionId="
- + execution.getProcessDefinitionId() + ", activtyId=" + execution.getCurrentActivityId()
- + ", activtyName='" + execution.getCurrentActivityName() + "'" + ", processInstanceId="
- + execution.getProcessInstanceId() + ", businessKey=" + execution.getProcessBusinessKey()
- + ", executionId=" + execution.getId() + " \n\n");
- }
+ @Override
+ public void execute(DelegateExecution execution) throws Exception {
+ System.out.println("\n\n ..." + MockLoggerDelegate.class.getName() + " invoked by " + "processDefinitionId="
+ + execution.getProcessDefinitionId() + ", activtyId=" + execution.getCurrentActivityId()
+ + ", activtyName='" + execution.getCurrentActivityName() + "'" + ", processInstanceId="
+ + execution.getProcessInstanceId() + ", businessKey=" + execution.getProcessBusinessKey()
+ + ", executionId=" + execution.getId() + " \n\n");
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/SerializableChecker.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/SerializableChecker.java
index 97c17d5238..47ddea1b4f 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/SerializableChecker.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/SerializableChecker.java
@@ -29,78 +29,65 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
-public final class SerializableChecker
-{
- public static class SerializationFailure
- {
+public final class SerializableChecker {
+ public static class SerializationFailure {
private final String mContainingClass;
private final String mMemberName;
- public SerializationFailure(String inNonSerializableClass, String inMemberName)
- {
+ public SerializationFailure(String inNonSerializableClass, String inMemberName) {
mContainingClass = inNonSerializableClass;
mMemberName = inMemberName;
}
- public String getContainingClass()
- {
+ public String getContainingClass() {
return mContainingClass;
}
- public String getMemberName()
- {
+ public String getMemberName() {
return mMemberName;
}
- public String getBadMemberString()
- {
+ public String getBadMemberString() {
if (mMemberName == null)
return mContainingClass;
return mContainingClass + "." + mMemberName;
}
@Override
- public String toString()
- {
- return "SerializationFailure [mNonSerializableClass=" + mContainingClass + ", mMemberName=" + mMemberName + "]";
+ public String toString() {
+ return "SerializationFailure [mNonSerializableClass=" + mContainingClass + ", mMemberName=" + mMemberName
+ + "]";
}
}
- private static class SerializationCheckerData
- {
+ private static class SerializationCheckerData {
private Set<Class<?>> mSerializableClasses;
- SerializationCheckerData()
- {
+ SerializationCheckerData() {
mSerializableClasses = new HashSet<Class<?>>();
}
- boolean isAlreadyChecked(Class<?> inClass)
- {
+ boolean isAlreadyChecked(Class<?> inClass) {
return mSerializableClasses.contains(inClass);
}
- void addSerializableClass(Class<?> inClass)
- {
+ void addSerializableClass(Class<?> inClass) {
mSerializableClasses.add(inClass);
}
}
- private SerializableChecker()
- { }
+ private SerializableChecker() {}
- public static SerializationFailure isFullySerializable(Class<?> inClass)
- {
+ public static SerializationFailure isFullySerializable(Class<?> inClass) {
if (!isSerializable(inClass))
return new SerializationFailure(inClass.getName(), null);
return isFullySerializable(inClass, new SerializationCheckerData());
}
- private static SerializationFailure isFullySerializable(Class<?> inClass, SerializationCheckerData inSerializationCheckerData)
- {
- for (Field field : declaredFields(inClass))
- {
+ private static SerializationFailure isFullySerializable(Class<?> inClass,
+ SerializationCheckerData inSerializationCheckerData) {
+ for (Field field : declaredFields(inClass)) {
Class<?> fieldDeclaringClass = field.getType();
if (field.getType() == Object.class)
@@ -121,8 +108,7 @@ public final class SerializableChecker
if (inSerializationCheckerData.isAlreadyChecked(fieldDeclaringClass))
continue;
- if (isSerializable(fieldDeclaringClass))
- {
+ if (isSerializable(fieldDeclaringClass)) {
inSerializationCheckerData.addSerializableClass(inClass);
SerializationFailure failure = isFullySerializable(field.getType(), inSerializationCheckerData);
@@ -140,8 +126,7 @@ public final class SerializableChecker
return null;
}
- private static boolean isSerializable(Class<?> inClass)
- {
+ private static boolean isSerializable(Class<?> inClass) {
Set<Class<?>> interfaces = getInterfaces(inClass);
if (interfaces == null)
return false;
@@ -149,8 +134,7 @@ public final class SerializableChecker
if (isSerializable)
return true;
- for (Class<?> classInterface : interfaces)
- {
+ for (Class<?> classInterface : interfaces) {
if (isSerializable(classInterface))
return true;
}
@@ -161,13 +145,11 @@ public final class SerializableChecker
return false;
}
- private static Set<Class<?>> getInterfaces(Class<?> inFieldDeclaringClass)
- {
+ private static Set<Class<?>> getInterfaces(Class<?> inFieldDeclaringClass) {
return new HashSet<Class<?>>(Arrays.asList(inFieldDeclaringClass.getInterfaces()));
}
- private static List<Field> declaredFields(Class<?> inClass)
- {
+ private static List<Field> declaredFields(Class<?> inClass) {
List<Field> fields = new ArrayList<Field>(Arrays.asList(inClass.getDeclaredFields()));
Class<?> parentClasses = inClass.getSuperclass();
@@ -177,5 +159,5 @@ public final class SerializableChecker
fields.addAll(declaredFields(parentClasses));
return fields;
- }
}
+}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/TestApplication.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/TestApplication.java
index 11309914ef..029b77319b 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/TestApplication.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/TestApplication.java
@@ -30,14 +30,14 @@ import org.springframework.context.annotation.Profile;
@SpringBootApplication
@Profile("test")
-@ComponentScan(basePackages = {"org.onap.so"}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class, excludeFilters = {
- @Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
+@ComponentScan(basePackages = {"org.onap.so"}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class,
+ excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
public class TestApplication {
- public static void main(String... args) {
- SpringApplication.run(TestApplication.class, args);
- System.getProperties().setProperty("mso.db", "MARIADB");
- System.getProperties().setProperty("server.name", "Springboot");
-
-
- }
+ public static void main(String... args) {
+ SpringApplication.run(TestApplication.class, args);
+ System.getProperties().setProperty("mso.db", "MARIADB");
+ System.getProperties().setProperty("server.name", "Springboot");
+
+
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java
index deb985c62b..2a0fef0caa 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java
@@ -94,217 +94,209 @@ import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public abstract class BaseBPMNTest {
- @Autowired
- protected RuntimeService runtimeService;
+ @Autowired
+ protected RuntimeService runtimeService;
- @Autowired
- protected ExternalTaskService externalTaskService;
-
- @Autowired
- private RepositoryService repositoryService;
+ @Autowired
+ protected ExternalTaskService externalTaskService;
- protected Map<String, Object> variables = new HashMap<>();
+ @Autowired
+ private RepositoryService repositoryService;
- protected List<String> mockedSubprocessList = new ArrayList<>();
+ protected Map<String, Object> variables = new HashMap<>();
- protected TestRestTemplate restTemplate = new TestRestTemplate();
+ protected List<String> mockedSubprocessList = new ArrayList<>();
- protected HttpHeaders headers = new HttpHeaders();
+ protected TestRestTemplate restTemplate = new TestRestTemplate();
- @MockBean
- protected AAIUpdateTasks aaiUpdateTasks;
+ protected HttpHeaders headers = new HttpHeaders();
- @MockBean
- protected AAICreateTasks aaiCreateTasks;
+ @MockBean
+ protected AAIUpdateTasks aaiUpdateTasks;
- @MockBean
- protected AAIQueryTasks aaiQueryTasks;
+ @MockBean
+ protected AAICreateTasks aaiCreateTasks;
- @MockBean
- protected AAIDeleteTasks aaiDeleteTasks;
+ @MockBean
+ protected AAIQueryTasks aaiQueryTasks;
- @MockBean
- protected AAIFlagTasks aaiFlagTasks;
+ @MockBean
+ protected AAIDeleteTasks aaiDeleteTasks;
+ @MockBean
+ protected AAIFlagTasks aaiFlagTasks;
- @MockBean
- protected AppcRunTasks appcRunTasks;
- @MockBean
- protected SDNCActivateTasks sdncActivateTasks;
+ @MockBean
+ protected AppcRunTasks appcRunTasks;
- @MockBean
- protected SDNCAssignTasks sdncAssignTasks;
+ @MockBean
+ protected SDNCActivateTasks sdncActivateTasks;
- @MockBean
- protected SDNCUnassignTasks sdncUnassignTasks;
+ @MockBean
+ protected SDNCAssignTasks sdncAssignTasks;
- @MockBean
- protected SDNCDeactivateTasks sdncDeactivateTasks;
+ @MockBean
+ protected SDNCUnassignTasks sdncUnassignTasks;
- @MockBean
- protected SDNCQueryTasks sdncQueryTasks;
+ @MockBean
+ protected SDNCDeactivateTasks sdncDeactivateTasks;
- @MockBean
- protected SDNCChangeAssignTasks sdncChangeAssignTasks;
+ @MockBean
+ protected SDNCQueryTasks sdncQueryTasks;
- @MockBean
- protected NetworkAdapterDeleteTasks networkAdapterDeleteTasks;
+ @MockBean
+ protected SDNCChangeAssignTasks sdncChangeAssignTasks;
- @MockBean
- protected NetworkAdapterUpdateTasks networkAdapterUpdateTasks;
+ @MockBean
+ protected NetworkAdapterDeleteTasks networkAdapterDeleteTasks;
- @MockBean
- protected VnfAdapterCreateTasks vnfAdapterCreateTasks;
+ @MockBean
+ protected NetworkAdapterUpdateTasks networkAdapterUpdateTasks;
- @MockBean
- protected NetworkAdapterCreateTasks networkAdapterCreateTasks;
+ @MockBean
+ protected VnfAdapterCreateTasks vnfAdapterCreateTasks;
- @MockBean
- protected CreateNetwork createNetwork;
+ @MockBean
+ protected NetworkAdapterCreateTasks networkAdapterCreateTasks;
- @MockBean
- protected AssignNetworkBBUtils assignNetworkBBUtils;
+ @MockBean
+ protected CreateNetwork createNetwork;
- @MockBean
- protected AssignNetwork assignNetwork;
+ @MockBean
+ protected AssignNetworkBBUtils assignNetworkBBUtils;
- @MockBean
- protected CreateNetworkCollection createNetworkCollection;
+ @MockBean
+ protected AssignNetwork assignNetwork;
- @MockBean
- protected VnfAdapterDeleteTasks vnfAdapterDeleteTasks;
+ @MockBean
+ protected CreateNetworkCollection createNetworkCollection;
- @MockBean
- protected AAICommonTasks aaiCommonTasks;
+ @MockBean
+ protected VnfAdapterDeleteTasks vnfAdapterDeleteTasks;
- @MockBean
- protected ActivateVfModule activateVfModule;
-
- @MockBean
- protected AssignVnf assignVnf;
+ @MockBean
+ protected AAICommonTasks aaiCommonTasks;
- @MockBean
- protected UnassignVnf unassignVnf;
+ @MockBean
+ protected ActivateVfModule activateVfModule;
- @MockBean
- protected VnfAdapterImpl vnfAdapterImpl;
+ @MockBean
+ protected AssignVnf assignVnf;
- @MockBean
- protected UnassignNetworkBB unassignNetworkBB;
+ @MockBean
+ protected UnassignVnf unassignVnf;
- @MockBean
- protected OrchestrationStatusValidator orchestrationStatusValidator;
+ @MockBean
+ protected VnfAdapterImpl vnfAdapterImpl;
- @MockBean
- protected BBInputSetup bbInputSetup;
+ @MockBean
+ protected UnassignNetworkBB unassignNetworkBB;
- @MockBean
- protected BBInputSetupUtils bbInputSetupUtils;
+ @MockBean
+ protected OrchestrationStatusValidator orchestrationStatusValidator;
- @MockBean
- protected ExecuteBuildingBlockRainyDay executeBuildingBlockRainyDay;
+ @MockBean
+ protected BBInputSetup bbInputSetup;
- @MockBean
- protected WorkflowAction workflowAction;
-
- @MockBean
- protected WorkflowActionBBTasks workflowActionBBTasks;
-
- @MockBean
- protected GenericVnfHealthCheck genericVnfHealthCheck;
-
- @MockBean
- protected ConfigurationScaleOut configurationScaleOut;
-
- @MockBean
- protected FlowCompletionTasks flowCompletionTasks;
-
- @MockBean
- protected BuildingBlockValidatorRunner buildingBlockValidatorRunner;
-
- @MockBean
- protected SDNOHealthCheckTasks sdnoHealthCheckTasks;
-
- @MockBean
- protected SDNCClient sdncClient;
-
- @MockBean
- protected SniroHomingV2 sniroHoming;
-
- @MockBean
- protected NamingServiceDeleteTasks namingServiceDeleteTasks;
-
- @MockBean
- protected NamingServiceCreateTasks namingServiceCreateTasks;
-
- @MockBean
- protected WorkflowActionBBFailure workflowActionBBFailure;
-
- @MockBean
- protected AuditTasks auditTasks;
-
- @MockBean
- protected ManualHandlingTasks manualHandlingTasks;
-
- @LocalServerPort
- protected int port;
-
- protected String createURLWithPort(String uri) {
- return "http://localhost:" + port + uri;
- }
-
- @Before
- public void baseBefore() {
- variables.put("gBuildingBlockExecution", new DelegateExecutionImpl(new HashMap<>()));
- }
-
- @After
- public void baseAfter() {
- for (String deploymentId : mockedSubprocessList) {
- repositoryService.deleteDeployment(deploymentId);
- }
- mockedSubprocessList.clear();
- }
-
- /**
- * Create and deploy a process model with one logger delegate as service task.
- *
- * @param origProcessKey
- * key to call
- * @param mockProcessName
- * process name
- * @param fileName
- * file name without extension
- */
- protected void mockSubprocess(String origProcessKey, String mockProcessName, String fileName) {
- mockSubprocess(origProcessKey, mockProcessName, fileName, new HashMap<String, String>());
- }
-
- /**
- * Create and deploy a process model with one logger delegate as service task.
- *
- * @param origProcessKey
- * key to call
- * @param mockProcessName
- * process name
- * @param fileName
- * file name without extension
- * @param outParam
- * output parameters
- */
- protected void mockSubprocess(String origProcessKey, String mockProcessName, String fileName, Map<String, String> outParam) {
- ServiceTaskBuilder builder = Bpmn
- .createExecutableProcess(origProcessKey).name(mockProcessName)
- .startEvent().name("Start_Event")
- .serviceTask().name("Mock_Delegate")
- .camundaClass(FluentJavaDelegateMock.class);
-
- for (String key : outParam.keySet()) {
- builder.camundaOutputParameter(key, outParam.get(key));
- }
-
- BpmnModelInstance modelInstance = builder.endEvent().name("End_Event").done();
- mockedSubprocessList.add(repositoryService.createDeployment().addModelInstance(fileName + ".bpmn", modelInstance).deploy().getId());
- }
+ @MockBean
+ protected BBInputSetupUtils bbInputSetupUtils;
+
+ @MockBean
+ protected ExecuteBuildingBlockRainyDay executeBuildingBlockRainyDay;
+
+ @MockBean
+ protected WorkflowAction workflowAction;
+
+ @MockBean
+ protected WorkflowActionBBTasks workflowActionBBTasks;
+
+ @MockBean
+ protected GenericVnfHealthCheck genericVnfHealthCheck;
+
+ @MockBean
+ protected ConfigurationScaleOut configurationScaleOut;
+
+ @MockBean
+ protected FlowCompletionTasks flowCompletionTasks;
+
+ @MockBean
+ protected BuildingBlockValidatorRunner buildingBlockValidatorRunner;
+
+ @MockBean
+ protected SDNOHealthCheckTasks sdnoHealthCheckTasks;
+
+ @MockBean
+ protected SDNCClient sdncClient;
+
+ @MockBean
+ protected SniroHomingV2 sniroHoming;
+
+ @MockBean
+ protected NamingServiceDeleteTasks namingServiceDeleteTasks;
+
+ @MockBean
+ protected NamingServiceCreateTasks namingServiceCreateTasks;
+
+ @MockBean
+ protected WorkflowActionBBFailure workflowActionBBFailure;
+
+ @MockBean
+ protected AuditTasks auditTasks;
+
+ @MockBean
+ protected ManualHandlingTasks manualHandlingTasks;
+
+ @LocalServerPort
+ protected int port;
+
+ protected String createURLWithPort(String uri) {
+ return "http://localhost:" + port + uri;
+ }
+
+ @Before
+ public void baseBefore() {
+ variables.put("gBuildingBlockExecution", new DelegateExecutionImpl(new HashMap<>()));
+ }
+
+ @After
+ public void baseAfter() {
+ for (String deploymentId : mockedSubprocessList) {
+ repositoryService.deleteDeployment(deploymentId);
+ }
+ mockedSubprocessList.clear();
+ }
+
+ /**
+ * Create and deploy a process model with one logger delegate as service task.
+ *
+ * @param origProcessKey key to call
+ * @param mockProcessName process name
+ * @param fileName file name without extension
+ */
+ protected void mockSubprocess(String origProcessKey, String mockProcessName, String fileName) {
+ mockSubprocess(origProcessKey, mockProcessName, fileName, new HashMap<String, String>());
+ }
+
+ /**
+ * Create and deploy a process model with one logger delegate as service task.
+ *
+ * @param origProcessKey key to call
+ * @param mockProcessName process name
+ * @param fileName file name without extension
+ * @param outParam output parameters
+ */
+ protected void mockSubprocess(String origProcessKey, String mockProcessName, String fileName,
+ Map<String, String> outParam) {
+ ServiceTaskBuilder builder = Bpmn.createExecutableProcess(origProcessKey).name(mockProcessName).startEvent()
+ .name("Start_Event").serviceTask().name("Mock_Delegate").camundaClass(FluentJavaDelegateMock.class);
+
+ for (String key : outParam.keySet()) {
+ builder.camundaOutputParameter(key, outParam.get(key));
+ }
+
+ BpmnModelInstance modelInstance = builder.endEvent().name("End_Event").done();
+ mockedSubprocessList.add(repositoryService.createDeployment()
+ .addModelInstance(fileName + ".bpmn", modelInstance).deploy().getId());
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAICheckVnfInMaintBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAICheckVnfInMaintBBTest.java
index 1101fc85f5..11e6d7798d 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAICheckVnfInMaintBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAICheckVnfInMaintBBTest.java
@@ -23,37 +23,36 @@ package org.onap.so.bpmn.common;
import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import java.io.IOException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Ignore;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
-public class AAICheckVnfInMaintBBTest extends BaseBPMNTest{
-
-
- @Test
- public void sunnyDayAAICheckVnfInMaintBBTest() throws InterruptedException, IOException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("AAICheckVnfInMaintBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_AAICheckVnfInMaintBB", "Task_CheckVnfInMaint", "End_AAICheckVnfInMaintBB");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayAAISetVnfInMaintBBTest() {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks).checkVnfInMaintFlag(any(BuildingBlockExecution.class));
-
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("AAICheckVnfInMaintBB", variables);
- assertThat(processInstance).isNotNull();
- assertThat(processInstance).isStarted()
- .hasPassedInOrder("Start_AAICheckVnfInMaintBB", "Task_CheckVnfInMaint")
- .hasNotPassed("End_AAICheckVnfInMaintBB");
- assertThat(processInstance).isEnded();
- }
+public class AAICheckVnfInMaintBBTest extends BaseBPMNTest {
+
+
+ @Test
+ public void sunnyDayAAICheckVnfInMaintBBTest() throws InterruptedException, IOException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("AAICheckVnfInMaintBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_AAICheckVnfInMaintBB", "Task_CheckVnfInMaint",
+ "End_AAICheckVnfInMaintBB");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayAAISetVnfInMaintBBTest() {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
+ .checkVnfInMaintFlag(any(BuildingBlockExecution.class));
+
+ ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("AAICheckVnfInMaintBB", variables);
+ assertThat(processInstance).isNotNull();
+ assertThat(processInstance).isStarted().hasPassedInOrder("Start_AAICheckVnfInMaintBB", "Task_CheckVnfInMaint")
+ .hasNotPassed("End_AAICheckVnfInMaintBB");
+ assertThat(processInstance).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAISetVnfInMaintBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAISetVnfInMaintBBTest.java
index effd50fcf1..64aa06cd20 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAISetVnfInMaintBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAISetVnfInMaintBBTest.java
@@ -23,9 +23,7 @@ package org.onap.so.bpmn.common;
import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import java.io.IOException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Ignore;
@@ -33,25 +31,26 @@ import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
public class AAISetVnfInMaintBBTest extends BaseBPMNTest {
-
-
- @Test
- public void sunnyDayAAISetVnfInMaintBBTest() throws InterruptedException, IOException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("AAISetVnfInMaintBB", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_AAISetVnfInMaintBB", "Task_SetInMaint", "End_AAISetVnfInMaintBB");
- }
-
- @Test
- public void rainyDayAAISetVnfInMaintBBTest() {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks).modifyVnfInMaintFlag(any(BuildingBlockExecution.class), any(boolean.class));
-
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("AAISetVnfInMaintBB", variables);
- assertThat(processInstance).isNotNull();
- assertThat(processInstance).isStarted()
- .hasPassedInOrder("Start_AAISetVnfInMaintBB", "Task_SetInMaint")
- .hasNotPassed("End_AAISetVnfInMaintBB");
- assertThat(processInstance).isEnded();
- }
-
-
+
+
+ @Test
+ public void sunnyDayAAISetVnfInMaintBBTest() throws InterruptedException, IOException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("AAISetVnfInMaintBB", variables);
+ assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_AAISetVnfInMaintBB", "Task_SetInMaint",
+ "End_AAISetVnfInMaintBB");
+ }
+
+ @Test
+ public void rainyDayAAISetVnfInMaintBBTest() {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
+ .modifyVnfInMaintFlag(any(BuildingBlockExecution.class), any(boolean.class));
+
+ ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("AAISetVnfInMaintBB", variables);
+ assertThat(processInstance).isNotNull();
+ assertThat(processInstance).isStarted().hasPassedInOrder("Start_AAISetVnfInMaintBB", "Task_SetInMaint")
+ .hasNotPassed("End_AAISetVnfInMaintBB");
+ assertThat(processInstance).isEnded();
+ }
+
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAIUnsetVnfInMaintBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAIUnsetVnfInMaintBBTest.java
index 7da8823c56..c67db438d9 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAIUnsetVnfInMaintBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/AAIUnsetVnfInMaintBBTest.java
@@ -23,9 +23,7 @@ package org.onap.so.bpmn.common;
import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import java.io.IOException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Ignore;
@@ -33,27 +31,28 @@ import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
public class AAIUnsetVnfInMaintBBTest extends BaseBPMNTest {
-
-
- @Test
- public void sunnyDayAAISetVnftInMaintBBTest() throws InterruptedException, IOException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("AAIUnsetVnfInMaintBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_AAIUnsetVnfInMaintBB", "Task_UnsetInMaint", "End_AAIUnsetVnfInMaintBB");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayAAISetVnfInMaintBBTest() {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks).modifyVnfInMaintFlag(any(BuildingBlockExecution.class), any(boolean.class));
-
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("AAIUnsetVnfInMaintBB", variables);
- assertThat(processInstance).isNotNull();
- assertThat(processInstance).isStarted()
- .hasPassedInOrder("Start_AAIUnsetVnfInMaintBB", "Task_UnsetInMaint")
- .hasNotPassed("End_AAIUnsetVnfInMaintBB");
- assertThat(processInstance).isEnded();
- }
-
-
+
+
+ @Test
+ public void sunnyDayAAISetVnftInMaintBBTest() throws InterruptedException, IOException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("AAIUnsetVnfInMaintBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_AAIUnsetVnfInMaintBB", "Task_UnsetInMaint",
+ "End_AAIUnsetVnfInMaintBB");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayAAISetVnfInMaintBBTest() {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
+ .modifyVnfInMaintFlag(any(BuildingBlockExecution.class), any(boolean.class));
+
+ ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("AAIUnsetVnfInMaintBB", variables);
+ assertThat(processInstance).isNotNull();
+ assertThat(processInstance).isStarted().hasPassedInOrder("Start_AAIUnsetVnfInMaintBB", "Task_UnsetInMaint")
+ .hasNotPassed("End_AAIUnsetVnfInMaintBB");
+ assertThat(processInstance).isEnded();
+ }
+
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/SDNOHealthCheckBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/SDNOHealthCheckBBTest.java
index 70351f9aad..ed1fb3fd91 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/SDNOHealthCheckBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/common/SDNOHealthCheckBBTest.java
@@ -23,9 +23,7 @@ package org.onap.so.bpmn.common;
import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import java.io.IOException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Ignore;
@@ -33,27 +31,28 @@ import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
public class SDNOHealthCheckBBTest extends BaseBPMNTest {
-
- @Test
-
- public void sunnyDaySDNOHealthCheckTest() throws InterruptedException, IOException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("SDNOVnfHealthCheckBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_SDNOHealthCheckBB", "Task_SDNOHealthCheck", "End_SDNOHealthCheckBB");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDaySDNOHealthCheckTest() {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdnoHealthCheckTasks).sdnoHealthCheck(any(BuildingBlockExecution.class));
-
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("SDNOVnfHealthCheckBB", variables);
- assertThat(processInstance).isNotNull();
- assertThat(processInstance).isStarted()
- .hasPassedInOrder("Start_SDNOHealthCheckBB", "Task_SDNOHealthCheck")
- .hasNotPassed("End_SDNOHealthCheckBB");
- assertThat(processInstance).isEnded();
- }
-
-
+
+ @Test
+
+ public void sunnyDaySDNOHealthCheckTest() throws InterruptedException, IOException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("SDNOVnfHealthCheckBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_SDNOHealthCheckBB", "Task_SDNOHealthCheck",
+ "End_SDNOHealthCheckBB");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDaySDNOHealthCheckTest() {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdnoHealthCheckTasks)
+ .sdnoHealthCheck(any(BuildingBlockExecution.class));
+
+ ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("SDNOVnfHealthCheckBB", variables);
+ assertThat(processInstance).isNotNull();
+ assertThat(processInstance).isStarted().hasPassedInOrder("Start_SDNOHealthCheckBB", "Task_SDNOHealthCheck")
+ .hasNotPassed("End_SDNOHealthCheckBB");
+ assertThat(processInstance).isEnded();
+ }
+
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/activity/DeployActivitySpecsTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/activity/DeployActivitySpecsTest.java
index a346aaf571..64c0e54a10 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/activity/DeployActivitySpecsTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/activity/DeployActivitySpecsTest.java
@@ -24,7 +24,6 @@ import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.HttpClient;
@@ -35,34 +34,34 @@ import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
-public class DeployActivitySpecsTest extends BaseBPMNTest{
- private static final String RESULT_STRING = "HTTP/1.1 404 ";
+public class DeployActivitySpecsTest extends BaseBPMNTest {
+ private static final String RESULT_STRING = "HTTP/1.1 404 ";
+
-
- @Test
- public void DeployActivitySpecsMain_Test() throws Exception {
- String HOSTNAME = createURLWithPort("");
- ProtocolVersion protocolVersion = new ProtocolVersion("", 1, 1);
- HttpResponse response = new BasicHttpResponse(protocolVersion, 1, "");
- response.setStatusCode(404);
- response.setStatusLine(protocolVersion, 1, "");
- HttpClient clientMock = mock(HttpClient.class);
- when(clientMock.execute(any(HttpPost.class))).thenReturn(response);
- String[] args = new String[] {HOSTNAME};
- DeployActivitySpecs.main(args);
+ @Test
+ public void DeployActivitySpecsMain_Test() throws Exception {
+ String HOSTNAME = createURLWithPort("");
+ ProtocolVersion protocolVersion = new ProtocolVersion("", 1, 1);
+ HttpResponse response = new BasicHttpResponse(protocolVersion, 1, "");
+ response.setStatusCode(404);
+ response.setStatusLine(protocolVersion, 1, "");
+ HttpClient clientMock = mock(HttpClient.class);
+ when(clientMock.execute(any(HttpPost.class))).thenReturn(response);
+ String[] args = new String[] {HOSTNAME};
+ DeployActivitySpecs.main(args);
}
-
- @Test
- @Ignore
- public void DeployActivitySpec_Test() throws Exception {
- String HOSTNAME = createURLWithPort("");
- ProtocolVersion protocolVersion = new ProtocolVersion("", 1, 1);
- HttpResponse response = new BasicHttpResponse(protocolVersion, 1, "");
- response.setStatusCode(404);
- response.setStatusLine(protocolVersion, 1, "");
- HttpClient clientMock = mock(HttpClient.class);
- when(clientMock.execute(any(HttpPost.class))).thenReturn(response); ;
- String result = DeployActivitySpecs.deployActivitySpec(HOSTNAME, "VNFQuiesceTrafficActivitySpec.json");
- assertEquals(result, RESULT_STRING);
+
+ @Test
+ @Ignore
+ public void DeployActivitySpec_Test() throws Exception {
+ String HOSTNAME = createURLWithPort("");
+ ProtocolVersion protocolVersion = new ProtocolVersion("", 1, 1);
+ HttpResponse response = new BasicHttpResponse(protocolVersion, 1, "");
+ response.setStatusCode(404);
+ response.setStatusLine(protocolVersion, 1, "");
+ HttpClient clientMock = mock(HttpClient.class);
+ when(clientMock.execute(any(HttpPost.class))).thenReturn(response);;
+ String result = DeployActivitySpecs.deployActivitySpec(HOSTNAME, "VNFQuiesceTrafficActivitySpec.json");
+ assertEquals(result, RESULT_STRING);
}
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/process/WorkflowActionBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/process/WorkflowActionBBTest.java
index 3ab1c76ee6..051f373eaf 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/process/WorkflowActionBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/process/WorkflowActionBBTest.java
@@ -23,11 +23,9 @@ package org.onap.so.bpmn.infrastructure.bpmn.process;
import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.runtime.ProcessInstance;
@@ -37,99 +35,117 @@ import org.onap.so.bpmn.BaseBPMNTest;
@Ignore
public class WorkflowActionBBTest extends BaseBPMNTest {
-
- @Test
- public void sunnyDaySuccessIsTopLevelFlow() throws InterruptedException, IOException {
- variables.put("isTopLevelFlow", true);
- variables.put("completed", true);
-
- Map<String, String> map = new HashMap<>();
- map.put("handlingCode", "Success");
- mockSubprocess("ExecuteBuildingBlock", "Mocked ExecuteBuildingBlock", "GenericStub", map);
-
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_WorkflowActionBB", "Task_RetrieveBBExectuionList", "ExclusiveGateway_isTopLevelFlow", "Task_SendSync",
- "Task_SelectBB", "Call_ExecuteBB", "ExclusiveGateway_Finished", "ExclusiveGateway_isTopLevelFlowCompleted", "Task_UpdateRequestComplete",
- "End_WorkflowActionBB");
-
- }
-
- @Test
- public void sunnyDaySuccessNotTopLevelFlow() throws InterruptedException, IOException {
- variables.put("isTopLevelFlow", false);
- variables.put("completed", true);
-
- Map<String, String> map = new HashMap<>();
- map.put("handlingCode", "Success");
- mockSubprocess("ExecuteBuildingBlock", "Mocked ExecuteBuildingBlock", "GenericStub", map);
-
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_WorkflowActionBB", "Task_RetrieveBBExectuionList", "ExclusiveGateway_isTopLevelFlow",
- "Task_SelectBB", "Call_ExecuteBB", "ExclusiveGateway_Finished", "ExclusiveGateway_isTopLevelFlowCompleted", "End_WorkflowActionBB");
- }
-
- @Test
- public void sunnyDayRollback() throws InterruptedException, IOException {
- variables.put("isTopLevelFlow", false);
- variables.put("isRollbackNeeded", false);
-
- Map<String, String> map = new HashMap<>();
- map.put("handlingCode", "Rollback");
- mockSubprocess("ExecuteBuildingBlock", "Mocked ExecuteBuildingBlock", "GenericStub", map);
-
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_WorkflowActionBB", "Task_RetrieveBBExectuionList", "ExclusiveGateway_isTopLevelFlow",
- "Task_SelectBB", "Call_ExecuteBB", "ExclusiveGateway_Finished", "Task_RollbackExecutionPath", "Task_UpdateRequestToFailed", "End_RollbackFailed");
-
- }
-
- @Test
- public void rainyDayAbort() throws Exception {
- variables.put("isTopLevelFlow", true);
- variables.put("completed", false);
-
- Map<String, String> map = new HashMap<>();
- map.put("handlingCode", "Abort");
-
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(workflowActionBBFailure).abortCallErrorHandling(any(DelegateExecution.class));
- mockSubprocess("ExecuteBuildingBlock", "Mocked ExecuteBuildingBlock", "GenericStub", map);
-
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_WorkflowActionBB", "Task_RetrieveBBExectuionList", "ExclusiveGateway_isTopLevelFlow", "Task_SendSync",
- "Task_SelectBB", "Call_ExecuteBB", "ExclusiveGateway_Finished", "ExclusiveGateway_isTopLevelFlowAbort", "Task_AbortAndCallErrorHandling", "ErrorStart",
- "Task_UpdateDb", "ErrorEnd");
-
- }
-
- @Test
- public void retrieveBBExecutionListerrorHandling() throws Exception {
- variables.put("isTopLevelFlow", true);
- variables.put("sentSyncResponse", false);
- doThrow(new IllegalStateException("TESTING ERRORS")).when(workflowAction).selectExecutionList(any(DelegateExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_WorkflowActionBB", "Task_RetrieveBBExectuionList", "StartEvent_runtimeError", "ServiceTask_HandleRuntimeError", "EndEvent__runtimeError", "SubProcess_0rze15o");
-
- }
-
- @Test
- public void errorCatchSubprocessHandlingTest() throws Exception {
- variables.put("isTopLevelFlow", true);
- variables.put("sentSyncResponse", false);
- doThrow(new IllegalStateException("TESTING ERRORS")).when(workflowAction).selectExecutionList(any(DelegateExecution.class));
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(workflowAction).handleRuntimeException(any(DelegateExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_WorkflowActionBB", "Task_RetrieveBBExectuionList", "StartEvent_runtimeError", "ServiceTask_HandleRuntimeError", "SubProcess_0fuugr9", "ErrorStart", "ExclusiveGateway_10q79b6", "Task_SendSyncAckError", "Task_UpdateDb", "ErrorEnd", "SubProcess_18226x4");
-
- }
-
- @Test
- public void errorCatchBpmnSubprocessHandlingTest() throws Exception {
- variables.put("isTopLevelFlow", true);
- variables.put("sentSyncResponse", false);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(workflowActionBBTasks).selectBB(any(DelegateExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_WorkflowActionBB", "Task_RetrieveBBExectuionList","ExclusiveGateway_isTopLevelFlow","Task_SendSync","Task_SelectBB", "ErrorStart", "ExclusiveGateway_10q79b6", "Task_SendSyncAckError", "Task_UpdateDb", "ErrorEnd", "SubProcess_18226x4");
-
- }
+
+ @Test
+ public void sunnyDaySuccessIsTopLevelFlow() throws InterruptedException, IOException {
+ variables.put("isTopLevelFlow", true);
+ variables.put("completed", true);
+
+ Map<String, String> map = new HashMap<>();
+ map.put("handlingCode", "Success");
+ mockSubprocess("ExecuteBuildingBlock", "Mocked ExecuteBuildingBlock", "GenericStub", map);
+
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
+ assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_WorkflowActionBB",
+ "Task_RetrieveBBExectuionList", "ExclusiveGateway_isTopLevelFlow", "Task_SendSync", "Task_SelectBB",
+ "Call_ExecuteBB", "ExclusiveGateway_Finished", "ExclusiveGateway_isTopLevelFlowCompleted",
+ "Task_UpdateRequestComplete", "End_WorkflowActionBB");
+
+ }
+
+ @Test
+ public void sunnyDaySuccessNotTopLevelFlow() throws InterruptedException, IOException {
+ variables.put("isTopLevelFlow", false);
+ variables.put("completed", true);
+
+ Map<String, String> map = new HashMap<>();
+ map.put("handlingCode", "Success");
+ mockSubprocess("ExecuteBuildingBlock", "Mocked ExecuteBuildingBlock", "GenericStub", map);
+
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
+ assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_WorkflowActionBB",
+ "Task_RetrieveBBExectuionList", "ExclusiveGateway_isTopLevelFlow", "Task_SelectBB", "Call_ExecuteBB",
+ "ExclusiveGateway_Finished", "ExclusiveGateway_isTopLevelFlowCompleted", "End_WorkflowActionBB");
+ }
+
+ @Test
+ public void sunnyDayRollback() throws InterruptedException, IOException {
+ variables.put("isTopLevelFlow", false);
+ variables.put("isRollbackNeeded", false);
+
+ Map<String, String> map = new HashMap<>();
+ map.put("handlingCode", "Rollback");
+ mockSubprocess("ExecuteBuildingBlock", "Mocked ExecuteBuildingBlock", "GenericStub", map);
+
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
+ assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_WorkflowActionBB",
+ "Task_RetrieveBBExectuionList", "ExclusiveGateway_isTopLevelFlow", "Task_SelectBB", "Call_ExecuteBB",
+ "ExclusiveGateway_Finished", "Task_RollbackExecutionPath", "Task_UpdateRequestToFailed",
+ "End_RollbackFailed");
+
+ }
+
+ @Test
+ public void rainyDayAbort() throws Exception {
+ variables.put("isTopLevelFlow", true);
+ variables.put("completed", false);
+
+ Map<String, String> map = new HashMap<>();
+ map.put("handlingCode", "Abort");
+
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(workflowActionBBFailure)
+ .abortCallErrorHandling(any(DelegateExecution.class));
+ mockSubprocess("ExecuteBuildingBlock", "Mocked ExecuteBuildingBlock", "GenericStub", map);
+
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
+ assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_WorkflowActionBB",
+ "Task_RetrieveBBExectuionList", "ExclusiveGateway_isTopLevelFlow", "Task_SendSync", "Task_SelectBB",
+ "Call_ExecuteBB", "ExclusiveGateway_Finished", "ExclusiveGateway_isTopLevelFlowAbort",
+ "Task_AbortAndCallErrorHandling", "ErrorStart", "Task_UpdateDb", "ErrorEnd");
+
+ }
+
+ @Test
+ public void retrieveBBExecutionListerrorHandling() throws Exception {
+ variables.put("isTopLevelFlow", true);
+ variables.put("sentSyncResponse", false);
+ doThrow(new IllegalStateException("TESTING ERRORS")).when(workflowAction)
+ .selectExecutionList(any(DelegateExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_WorkflowActionBB", "Task_RetrieveBBExectuionList",
+ "StartEvent_runtimeError", "ServiceTask_HandleRuntimeError", "EndEvent__runtimeError",
+ "SubProcess_0rze15o");
+
+ }
+
+ @Test
+ public void errorCatchSubprocessHandlingTest() throws Exception {
+ variables.put("isTopLevelFlow", true);
+ variables.put("sentSyncResponse", false);
+ doThrow(new IllegalStateException("TESTING ERRORS")).when(workflowAction)
+ .selectExecutionList(any(DelegateExecution.class));
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(workflowAction)
+ .handleRuntimeException(any(DelegateExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
+ assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_WorkflowActionBB",
+ "Task_RetrieveBBExectuionList", "StartEvent_runtimeError", "ServiceTask_HandleRuntimeError",
+ "SubProcess_0fuugr9", "ErrorStart", "ExclusiveGateway_10q79b6", "Task_SendSyncAckError",
+ "Task_UpdateDb", "ErrorEnd", "SubProcess_18226x4");
+
+ }
+
+ @Test
+ public void errorCatchBpmnSubprocessHandlingTest() throws Exception {
+ variables.put("isTopLevelFlow", true);
+ variables.put("sentSyncResponse", false);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(workflowActionBBTasks)
+ .selectBB(any(DelegateExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("WorkflowActionBB", variables);
+ assertThat(pi).isNotNull().isStarted().hasPassedInOrder("Start_WorkflowActionBB",
+ "Task_RetrieveBBExectuionList", "ExclusiveGateway_isTopLevelFlow", "Task_SendSync", "Task_SelectBB",
+ "ErrorStart", "ExclusiveGateway_10q79b6", "Task_SendSyncAckError", "Task_UpdateDb", "ErrorEnd",
+ "SubProcess_18226x4");
+
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateNetworkBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateNetworkBBTest.java
index dcf679610e..affe1857bd 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateNetworkBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateNetworkBBTest.java
@@ -23,30 +23,30 @@ package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class ActivateNetworkBBTest extends BaseBPMNTest{
+public class ActivateNetworkBBTest extends BaseBPMNTest {
@Test
public void sunnyDayActivateNetwork_Test() throws InterruptedException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateNetworkBB", variables);
assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("activateNetwork_startEvent","Activate_Network_SDNC_ServiceTask","CallActivity_sdncHandler","Activate_Network_AAI_ServiceTask","activateNetwork_EndEvent");
+ assertThat(pi).isStarted().hasPassedInOrder("activateNetwork_startEvent", "Activate_Network_SDNC_ServiceTask",
+ "CallActivity_sdncHandler", "Activate_Network_AAI_ServiceTask", "activateNetwork_EndEvent");
assertThat(pi).isEnded();
}
- @Test
- public void rainyDayActivateNetwork_Test() throws Exception {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks).updateOrchestrationStatusActiveNetwork(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateNetworkBB", variables);
- assertThat(pi).isStarted()
- .hasPassedInOrder("activateNetwork_startEvent","Activate_Network_SDNC_ServiceTask","Activate_Network_AAI_ServiceTask")
- .hasNotPassed("activateNetwork_EndEvent").isEnded();
- }
+ @Test
+ public void rainyDayActivateNetwork_Test() throws Exception {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks)
+ .updateOrchestrationStatusActiveNetwork(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateNetworkBB", variables);
+ assertThat(pi).isStarted().hasPassedInOrder("activateNetwork_startEvent", "Activate_Network_SDNC_ServiceTask",
+ "Activate_Network_AAI_ServiceTask").hasNotPassed("activateNetwork_EndEvent").isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateNetworkCollectionBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateNetworkCollectionBBTest.java
index c6c301476e..0f0c373c03 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateNetworkCollectionBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateNetworkCollectionBBTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Ignore;
@@ -30,22 +30,23 @@ import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class ActivateNetworkCollectionBBTest extends BaseBPMNTest{
+public class ActivateNetworkCollectionBBTest extends BaseBPMNTest {
@Test
public void sunnyDayActivateNetworkCollection_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateNetworkCollectionBB",variables);
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateNetworkCollectionBB", variables);
assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("activateNetworkCollection_startEvent","Activate_Network_Collection_AAI_ServiceTask","activateNetworkCollection_EndEvent");
+ assertThat(pi).isStarted().hasPassedInOrder("activateNetworkCollection_startEvent",
+ "Activate_Network_Collection_AAI_ServiceTask", "activateNetworkCollection_EndEvent");
assertThat(pi).isEnded();
}
- @Test
-
- public void rainyDayActivateNetworkCollection_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks).updateOrchestrationStatusActiveNetworkCollection(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateNetworkCollectionBB", variables);
- assertThat(pi).isNotNull().isStarted()
- .hasPassedInOrder("activateNetworkCollection_startEvent")
- .hasNotPassed("activateNetworkCollection_EndEvent");
- }
+ @Test
+
+ public void rainyDayActivateNetworkCollection_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks)
+ .updateOrchestrationStatusActiveNetworkCollection(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateNetworkCollectionBB", variables);
+ assertThat(pi).isNotNull().isStarted().hasPassedInOrder("activateNetworkCollection_startEvent")
+ .hasNotPassed("activateNetworkCollection_EndEvent");
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateServiceInstanceBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateServiceInstanceBBTest.java
index efe7d87fb2..9eefaded9c 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateServiceInstanceBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateServiceInstanceBBTest.java
@@ -19,22 +19,21 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
-import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
+import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import java.io.IOException;
-
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
-public class ActivateServiceInstanceBBTest extends BaseBPMNTest{
-
- @Test
- public void sunnyDaySDNC() throws InterruptedException, IOException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateServiceInstanceBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_ActivateServiceInstanceBB", "Task_NoOpServiceInstance",
- "Task_UpdateServiceOrchestrationStatusToActive", "End_ActivateServiceInstanceBB");
- assertThat(pi).isEnded();
- }
+public class ActivateServiceInstanceBBTest extends BaseBPMNTest {
+
+ @Test
+ public void sunnyDaySDNC() throws InterruptedException, IOException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateServiceInstanceBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_ActivateServiceInstanceBB", "Task_NoOpServiceInstance",
+ "Task_UpdateServiceOrchestrationStatusToActive", "End_ActivateServiceInstanceBB");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVfModuleBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVfModuleBBTest.java
index deac50ca30..6f89f3c738 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVfModuleBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVfModuleBBTest.java
@@ -19,13 +19,13 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import java.io.IOException;
import java.util.List;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.externaltask.LockedExternalTask;
import org.camunda.bpm.engine.runtime.ProcessInstance;
@@ -34,52 +34,55 @@ import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class ActivateVfModuleBBTest extends BaseBPMNTest{
-
- @Before
- public void before() {
- variables.put("vfModuleActivateTimerDuration", "PT2S");
- variables.put("auditInventoryNeeded", "true");
- variables.put("auditIsSuccessful", "true");
- }
+public class ActivateVfModuleBBTest extends BaseBPMNTest {
+
+ @Before
+ public void before() {
+ variables.put("vfModuleActivateTimerDuration", "PT2S");
+ variables.put("auditInventoryNeeded", "true");
+ variables.put("auditIsSuccessful", "true");
+ }
- @Test
- public void sunnyDay() throws InterruptedException, IOException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateVfModuleBB", variables);
- List<LockedExternalTask> tasks = externalTaskService.fetchAndLock(100, "externalWorkerId")
+ @Test
+ public void sunnyDay() throws InterruptedException, IOException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateVfModuleBB", variables);
+ List<LockedExternalTask> tasks = externalTaskService.fetchAndLock(100, "externalWorkerId")
.topic("InventoryAddAudit", 60L * 1000L).execute();
while (!tasks.isEmpty()) {
for (LockedExternalTask task : tasks) {
externalTaskService.complete(task.getId(), "externalWorkerId");
}
- tasks = externalTaskService.fetchAndLock(100, "externalWorkerId")
- .topic("InventoryAddAudit", 60L * 1000L).execute();
+ tasks = externalTaskService.fetchAndLock(100, "externalWorkerId").topic("InventoryAddAudit", 60L * 1000L)
+ .execute();
}
-
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("ActivateVfModuleBB_Start","ExclusiveGateway_1v8bmbu","Setup_AAI_Inventory_Audit", "Audit_AAI_Inventory", "ActivateVfModule", "CallActivity_sdncHandler",
- "UpdateVfModuleActiveStatus", "ActivateVfModuleBB_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDay() throws Exception {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- doThrow(BpmnError.class).when(aaiUpdateTasks).updateOrchestrationStatusActivateVfModule(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateVfModuleBB", variables);
- List<LockedExternalTask> tasks = externalTaskService.fetchAndLock(100, "externalWorkerId")
+
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("ActivateVfModuleBB_Start", "ExclusiveGateway_1v8bmbu",
+ "Setup_AAI_Inventory_Audit", "Audit_AAI_Inventory", "ActivateVfModule", "CallActivity_sdncHandler",
+ "UpdateVfModuleActiveStatus", "ActivateVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDay() throws Exception {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ doThrow(BpmnError.class).when(aaiUpdateTasks)
+ .updateOrchestrationStatusActivateVfModule(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateVfModuleBB", variables);
+ List<LockedExternalTask> tasks = externalTaskService.fetchAndLock(100, "externalWorkerId")
.topic("InventoryAddAudit", 60L * 1000L).execute();
while (!tasks.isEmpty()) {
for (LockedExternalTask task : tasks) {
externalTaskService.complete(task.getId(), "externalWorkerId");
}
- tasks = externalTaskService.fetchAndLock(100, "externalWorkerId")
- .topic("InventoryAddAudit", 60L * 1000L).execute();
+ tasks = externalTaskService.fetchAndLock(100, "externalWorkerId").topic("InventoryAddAudit", 60L * 1000L)
+ .execute();
}
- assertThat(pi).isNotNull().isStarted()
- .hasPassedInOrder("ActivateVfModuleBB_Start","ExclusiveGateway_1v8bmbu","Setup_AAI_Inventory_Audit", "Audit_AAI_Inventory", "ActivateVfModule", "UpdateVfModuleActiveStatus")
- .hasNotPassed("ActivateVfModuleBB_End");
- }
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("ActivateVfModuleBB_Start", "ExclusiveGateway_1v8bmbu", "Setup_AAI_Inventory_Audit",
+ "Audit_AAI_Inventory", "ActivateVfModule", "UpdateVfModuleActiveStatus")
+ .hasNotPassed("ActivateVfModuleBB_End");
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVnfBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVnfBBTest.java
index d1d95fee71..7a78a6a6e2 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVnfBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVnfBBTest.java
@@ -19,23 +19,22 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
-import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
+import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import java.io.IOException;
-
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
-public class ActivateVnfBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDay() throws InterruptedException, IOException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateVnfBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_ActivateVnfBB", "Task_SDNCAdapterVnfTopologyActivate",
- "CallActivity_sdncHandler", "Task_ActivateOrchestrationStatusVnf", "End_ActivateVnfBB");
- assertThat(pi).isEnded();
- }
+public class ActivateVnfBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDay() throws InterruptedException, IOException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateVnfBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_ActivateVnfBB", "Task_SDNCAdapterVnfTopologyActivate",
+ "CallActivity_sdncHandler", "Task_ActivateOrchestrationStatusVnf", "End_ActivateVnfBB");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVolumeGroupBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVolumeGroupBBTest.java
index 8fc198ffcd..602f1c874f 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVolumeGroupBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ActivateVolumeGroupBBTest.java
@@ -19,33 +19,34 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class ActivateVolumeGroupBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDayAssignVolumeGroup_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("ActivateVolumeGroupBB_Start", "ActivateVolumeGroup", "ActivateVolumeGroupBB_End");
- assertThat(pi).isEnded();
- }
+public class ActivateVolumeGroupBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayAssignVolumeGroup_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("ActivateVolumeGroupBB_Start", "ActivateVolumeGroup",
+ "ActivateVolumeGroupBB_End");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDayAssignVolumeGroup_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks).updateOrchestrationStatusActiveVolumeGroup(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("ActivateVolumeGroupBB_Start", "ActivateVolumeGroup")
- .hasNotPassed("ActivateVolumeGroupBB_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayAssignVolumeGroup_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks)
+ .updateOrchestrationStatusActiveVolumeGroup(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ActivateVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("ActivateVolumeGroupBB_Start", "ActivateVolumeGroup")
+ .hasNotPassed("ActivateVolumeGroupBB_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignNetworkBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignNetworkBBTest.java
index c581a16349..42291a9593 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignNetworkBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignNetworkBBTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.test.Deployment;
@@ -30,26 +30,33 @@ import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class AssignNetworkBBTest extends BaseBPMNTest{
+public class AssignNetworkBBTest extends BaseBPMNTest {
@Test
- @Deployment(resources = { "subprocess/AssignNetworkRollbackBB.bpmn"})
+ @Deployment(resources = {"subprocess/AssignNetworkRollbackBB.bpmn"})
public void sunnyDayAssignNetwork_Test() throws InterruptedException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignNetworkBB",variables);
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignNetworkBB", variables);
assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("AssignNetworkBB_start","networkFoundByName_ExclusiveGateway","ServiceTask_put_network_in_AAI","ServiceTask_connect_to_Tenant","ServiceTask_connect_to_CloudRegion","ServiceTask_connect_to_NCIG","ServiceTask_connect_to_NCSI","ServiceTask_get_cloud_region","ServiceTask_assign_network_sdnc","CallActivity_sdncHandlerCall","ServiceTask_assign_network_aai","AssignNetworkBB_end");
+ assertThat(pi).isStarted().hasPassedInOrder("AssignNetworkBB_start", "networkFoundByName_ExclusiveGateway",
+ "ServiceTask_put_network_in_AAI", "ServiceTask_connect_to_Tenant", "ServiceTask_connect_to_CloudRegion",
+ "ServiceTask_connect_to_NCIG", "ServiceTask_connect_to_NCSI", "ServiceTask_get_cloud_region",
+ "ServiceTask_assign_network_sdnc", "CallActivity_sdncHandlerCall", "ServiceTask_assign_network_aai",
+ "AssignNetworkBB_end");
assertThat(pi).isEnded();
}
- @Test
- public void rainyDayAssignNetwork_Test() throws Exception {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks).updateOrchestrationStatusAssignedNetwork(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignNetworkBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("AssignNetworkBB_start", "networkFoundByName_ExclusiveGateway", "ServiceTask_put_network_in_AAI","ServiceTask_connect_to_Tenant","ServiceTask_connect_to_CloudRegion","ServiceTask_connect_to_NCIG","ServiceTask_connect_to_NCSI", "ServiceTask_get_cloud_region", "ServiceTask_assign_network_sdnc", "ServiceTask_assign_network_aai")
- .hasNotPassed("AssignNetworkBB_end");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayAssignNetwork_Test() throws Exception {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks)
+ .updateOrchestrationStatusAssignedNetwork(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignNetworkBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("AssignNetworkBB_start", "networkFoundByName_ExclusiveGateway",
+ "ServiceTask_put_network_in_AAI", "ServiceTask_connect_to_Tenant", "ServiceTask_connect_to_CloudRegion",
+ "ServiceTask_connect_to_NCIG", "ServiceTask_connect_to_NCSI", "ServiceTask_get_cloud_region",
+ "ServiceTask_assign_network_sdnc", "ServiceTask_assign_network_aai")
+ .hasNotPassed("AssignNetworkBB_end");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignServiceInstanceBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignServiceInstanceBBTest.java
index 2624cc0ccb..f45ed935a6 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignServiceInstanceBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignServiceInstanceBBTest.java
@@ -19,24 +19,23 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
-import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
+import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import java.io.IOException;
-
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
-public class AssignServiceInstanceBBTest extends BaseBPMNTest{
-
- @Test
- public void sunnyDaySDNC() throws InterruptedException, IOException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignServiceInstanceBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_AssignServiceInstanceBB", "Task_CreateServiceInstance",
- "Task_CreateProject", "Task_CreateOwningEntity", "Task_AssignServiceInstance", "CallActivity_sdncHandler",
- "Task_UpdateServiceOstatusToAssigned", "End_AssignServiceInstanceBB");
- assertThat(pi).isEnded();
- }
+public class AssignServiceInstanceBBTest extends BaseBPMNTest {
+
+ @Test
+ public void sunnyDaySDNC() throws InterruptedException, IOException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignServiceInstanceBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_AssignServiceInstanceBB", "Task_CreateServiceInstance",
+ "Task_CreateProject", "Task_CreateOwningEntity", "Task_AssignServiceInstance",
+ "CallActivity_sdncHandler", "Task_UpdateServiceOstatusToAssigned", "End_AssignServiceInstanceBB");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVfModuleBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVfModuleBBTest.java
index 44d17a350c..358d1a2789 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVfModuleBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVfModuleBBTest.java
@@ -19,40 +19,36 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class AssignVfModuleBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDayAssignVfModule_Test() throws InterruptedException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("AssignVfModuleBB_Start",
- "CreateVfModule",
- "ConnectVfModuleToVolumeGroup",
- "AssignVfModule",
- "CallActivity_sdncHandlerCall",
- "UpdateVfModuleStatus",
- "AssignVfModuleBB_End");
- assertThat(pi).isEnded();
- }
+public class AssignVfModuleBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayAssignVfModule_Test() throws InterruptedException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("AssignVfModuleBB_Start", "CreateVfModule",
+ "ConnectVfModuleToVolumeGroup", "AssignVfModule", "CallActivity_sdncHandlerCall",
+ "UpdateVfModuleStatus", "AssignVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDayAssignVfModule_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiCreateTasks).createVfModule(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("AssignVfModuleBB_Start", "CreateVfModule")
- .hasNotPassed("ConnectVfModuleToVolumeGroup", "AssignVfModule", "UpdateVfModuleStatus", "AssignVfModuleBB_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayAssignVfModule_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiCreateTasks)
+ .createVfModule(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("AssignVfModuleBB_Start", "CreateVfModule").hasNotPassed(
+ "ConnectVfModuleToVolumeGroup", "AssignVfModule", "UpdateVfModuleStatus", "AssignVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVnfBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVnfBBTest.java
index f4258f46b8..078b0ae4e2 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVnfBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVnfBBTest.java
@@ -19,12 +19,11 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import java.io.IOException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -32,27 +31,29 @@ import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
public class AssignVnfBBTest extends BaseBPMNTest {
- @Test
- public void sunnyDayAssignVnfBBTest() throws InterruptedException, IOException {
- variables.put("callHoming", true);
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignVnfBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_AssignVnfBB", "Task_CreateVnf", "ServiceTask_ConnectVnfToCloudRegion", "ServiceTask_ConnectVnfToTenant", "Task_createPlatform", "Task_createLineOfBusiness", "Task_createInstanceGroups",
- "Task_callHoming", "Task_SDNCAdapterVnfTopologyAssign","CallActivity_sdncAssign", "Task_UpdateVnfOrchestrationStatusAssigned",
- "End_AssignVnfBB");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void sunnyDayAssignVnfBBTest() throws InterruptedException, IOException {
+ variables.put("callHoming", true);
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignVnfBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_AssignVnfBB", "Task_CreateVnf",
+ "ServiceTask_ConnectVnfToCloudRegion", "ServiceTask_ConnectVnfToTenant", "Task_createPlatform",
+ "Task_createLineOfBusiness", "Task_createInstanceGroups", "Task_callHoming",
+ "Task_SDNCAdapterVnfTopologyAssign", "CallActivity_sdncAssign",
+ "Task_UpdateVnfOrchestrationStatusAssigned", "End_AssignVnfBB");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDayAssignVnfBBTest() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiCreateTasks)
- .createVnf(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignVnfBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_AssignVnfBB", "Task_CreateVnf").hasNotPassed(
- "Task_createPlatform", "Task_createLineOfBusiness", "Task_createInstanceGroups", "Task_SDNCAdapterVnfTopologyAssign",
- "Task_UpdateVnfOrchestrationStatusAssigned", "End_AssignVnfBB");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayAssignVnfBBTest() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiCreateTasks)
+ .createVnf(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignVnfBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_AssignVnfBB", "Task_CreateVnf").hasNotPassed(
+ "Task_createPlatform", "Task_createLineOfBusiness", "Task_createInstanceGroups",
+ "Task_SDNCAdapterVnfTopologyAssign", "Task_UpdateVnfOrchestrationStatusAssigned", "End_AssignVnfBB");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVolumeGroupBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVolumeGroupBBTest.java
index e39370b951..0de657ed7f 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVolumeGroupBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/AssignVolumeGroupBBTest.java
@@ -19,33 +19,34 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class AssignVolumeGroupBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDayAssignVolumeGroup_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("AssignVolumeGroupBB_Start", "AssignVolumeGroup", "AssignVolumeGroupBB_End");
- assertThat(pi).isEnded();
- }
+public class AssignVolumeGroupBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayAssignVolumeGroup_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("AssignVolumeGroupBB_Start", "AssignVolumeGroup",
+ "AssignVolumeGroupBB_End");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDayAssignVolumeGroup_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiCreateTasks).createVolumeGroup(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("AssignVolumeGroupBB_Start", "AssignVolumeGroup")
- .hasNotPassed("AssignVolumeGroupBB_End");
- assertThat(pi).isEnded();;
- }
+ @Test
+ public void rainyDayAssignVolumeGroup_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiCreateTasks)
+ .createVolumeGroup(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("AssignVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("AssignVolumeGroupBB_Start", "AssignVolumeGroup")
+ .hasNotPassed("AssignVolumeGroupBB_End");
+ assertThat(pi).isEnded();;
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/BuildingBlockValidatorRunnerTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/BuildingBlockValidatorRunnerTest.java
index a241ae5eff..a036f6713e 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/BuildingBlockValidatorRunnerTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/BuildingBlockValidatorRunnerTest.java
@@ -27,16 +27,16 @@ import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
-public class BuildingBlockValidatorRunnerTest extends BaseBPMNTest{
+public class BuildingBlockValidatorRunnerTest extends BaseBPMNTest {
@Test
public void sunnyDayActivateNetwork_Test() throws InterruptedException {
- variables.put("flowToBeCalled","CreateVolumeGroupBB");
+ variables.put("flowToBeCalled", "CreateVolumeGroupBB");
ProcessInstance pi = runtimeService.startProcessInstanceByKey("BuildingBlockValidatorRunnerTest", variables);
assertThat(pi).isNotNull();
-
+
execute(job());
execute(job());
- assertThat(pi).isStarted().hasPassedInOrder("ServiceTask_1","ServiceTask_2","ServiceTask_3");
+ assertThat(pi).isStarted().hasPassedInOrder("ServiceTask_1", "ServiceTask_2", "ServiceTask_3");
assertThat(pi).isEnded();
}
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelServiceInstanceBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelServiceInstanceBBTest.java
index 1772a3af4b..832ee528a1 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelServiceInstanceBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelServiceInstanceBBTest.java
@@ -19,35 +19,40 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class ChangeModelServiceInstanceBBTest extends BaseBPMNTest{
- @Test
- public void changeModelVnfBBTest() {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("ChangeModelServiceInstanceBB", variables);
- assertThat(processInstance).isNotNull();
- assertThat(processInstance).isStarted().hasPassedInOrder("ChangeModelServiceInstance_Start" ,"SDNCChangeModelServiceInstance", "CallActivity_sdncHandlerReq", "AAIUpdateModelServiceInstance", "ChangeModelServiceInstance_End");
- assertThat(processInstance).isEnded();
- }
-
- @Test
- public void changeModelVnfBBExceptionTest() {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncChangeAssignTasks).changeModelServiceInstance(any(BuildingBlockExecution.class));
-
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("ChangeModelServiceInstanceBB", variables);
- assertThat(processInstance).isNotNull();
- assertThat(processInstance).isStarted()
- .hasPassedInOrder("ChangeModelServiceInstance_Start", "SDNCChangeModelServiceInstance")
- .hasNotPassed("AAIUpdateModel", "ChangeModelServiceInstance_End");
- assertThat(processInstance).isEnded();
- }
+public class ChangeModelServiceInstanceBBTest extends BaseBPMNTest {
+ @Test
+ public void changeModelVnfBBTest() {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance processInstance =
+ runtimeService.startProcessInstanceByKey("ChangeModelServiceInstanceBB", variables);
+ assertThat(processInstance).isNotNull();
+ assertThat(processInstance).isStarted().hasPassedInOrder("ChangeModelServiceInstance_Start",
+ "SDNCChangeModelServiceInstance", "CallActivity_sdncHandlerReq", "AAIUpdateModelServiceInstance",
+ "ChangeModelServiceInstance_End");
+ assertThat(processInstance).isEnded();
+ }
+
+ @Test
+ public void changeModelVnfBBExceptionTest() {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncChangeAssignTasks)
+ .changeModelServiceInstance(any(BuildingBlockExecution.class));
+
+ ProcessInstance processInstance =
+ runtimeService.startProcessInstanceByKey("ChangeModelServiceInstanceBB", variables);
+ assertThat(processInstance).isNotNull();
+ assertThat(processInstance).isStarted()
+ .hasPassedInOrder("ChangeModelServiceInstance_Start", "SDNCChangeModelServiceInstance")
+ .hasNotPassed("AAIUpdateModel", "ChangeModelServiceInstance_End");
+ assertThat(processInstance).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelVfModuleBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelVfModuleBBTest.java
index 8549b6bc5a..42be6a5711 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelVfModuleBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelVfModuleBBTest.java
@@ -19,36 +19,37 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class ChangeModelVfModuleBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDayChangeModelVfModuleTest() throws InterruptedException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ChangeModelVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("ChangeModelVfModuleBB_Start", "ChangeModelVfModule", "CallActivity_sdncHandler", "UpdateVfModuleModel", "ChangeModelVfModuleBB_End");
- assertThat(pi).isEnded();
- }
+public class ChangeModelVfModuleBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayChangeModelVfModuleTest() throws InterruptedException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ChangeModelVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("ChangeModelVfModuleBB_Start", "ChangeModelVfModule",
+ "CallActivity_sdncHandler", "UpdateVfModuleModel", "ChangeModelVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayChangeModelVfModuleTest() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncChangeAssignTasks)
+ .changeAssignModelVfModule(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ChangeModelVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("ChangeModelVfModuleBB_Start", "ChangeModelVfModule")
+ .hasNotPassed("ChangeModelVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
+
- @Test
- public void rainyDayChangeModelVfModuleTest() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncChangeAssignTasks).changeAssignModelVfModule(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ChangeModelVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("ChangeModelVfModuleBB_Start", "ChangeModelVfModule")
- .hasNotPassed("ChangeModelVfModuleBB_End");
- assertThat(pi).isEnded();
- }
-
-
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelVnfBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelVnfBBTest.java
index 43ac1630df..a7835e30f0 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelVnfBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ChangeModelVnfBBTest.java
@@ -19,35 +19,36 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class ChangeModelVnfBBTest extends BaseBPMNTest{
- @Test
- public void changeModelVnfBBTest() {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("ChangeModelVnfBB", variables);
- assertThat(processInstance).isNotNull();
- assertThat(processInstance).isStarted().hasPassedInOrder("ChangeModelVnf_Start" ,"SDNCChangeModel", "CallActivity_sdncHandlerCall", "AAIUpdateModel", "ChangeModelVnf_End");
- assertThat(processInstance).isEnded();
- }
-
- @Test
- public void changeModelVnfBBExceptionTest() {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncChangeAssignTasks).changeModelVnf(any(BuildingBlockExecution.class));
-
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("ChangeModelVnfBB", variables);
- assertThat(processInstance).isNotNull();
- assertThat(processInstance).isStarted()
- .hasPassedInOrder("ChangeModelVnf_Start", "SDNCChangeModel")
- .hasNotPassed("AAIUpdateModel", "ChangeModelVnf_End");
- assertThat(processInstance).isEnded();
- }
+public class ChangeModelVnfBBTest extends BaseBPMNTest {
+ @Test
+ public void changeModelVnfBBTest() {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("ChangeModelVnfBB", variables);
+ assertThat(processInstance).isNotNull();
+ assertThat(processInstance).isStarted().hasPassedInOrder("ChangeModelVnf_Start", "SDNCChangeModel",
+ "CallActivity_sdncHandlerCall", "AAIUpdateModel", "ChangeModelVnf_End");
+ assertThat(processInstance).isEnded();
+ }
+
+ @Test
+ public void changeModelVnfBBExceptionTest() {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncChangeAssignTasks)
+ .changeModelVnf(any(BuildingBlockExecution.class));
+
+ ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("ChangeModelVnfBB", variables);
+ assertThat(processInstance).isNotNull();
+ assertThat(processInstance).isStarted().hasPassedInOrder("ChangeModelVnf_Start", "SDNCChangeModel")
+ .hasNotPassed("AAIUpdateModel", "ChangeModelVnf_End");
+ assertThat(processInstance).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ConfigurationScaleOutBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ConfigurationScaleOutBBTest.java
index 4602ff97ce..8a19bc2561 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ConfigurationScaleOutBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ConfigurationScaleOutBBTest.java
@@ -19,15 +19,13 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import java.io.IOException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
-
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
@@ -36,23 +34,23 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
public class ConfigurationScaleOutBBTest extends BaseBPMNTest {
- @Test
- public void sunnyDayConfigurationScaleOutBBTest() throws InterruptedException, IOException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ConfigurationScaleOutBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_ConfigScaleOutBB", "QueryVfModule", "GetConfigScaleOutParams",
- "Call-AppC-ConfigScaleOut", "End_ConfigScaleOutBB");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void configurationScaleOutBBExceptionTest() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncQueryTasks).queryVfModule(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ConfigurationScaleOutBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("Start_ConfigScaleOutBB", "QueryVfModule")
- .hasNotPassed("GetConfigScaleOutParams", "Call-AppC-ConfigScaleOut", "End_ConfigScaleOutBB");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void sunnyDayConfigurationScaleOutBBTest() throws InterruptedException, IOException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ConfigurationScaleOutBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_ConfigScaleOutBB", "QueryVfModule",
+ "GetConfigScaleOutParams", "Call-AppC-ConfigScaleOut", "End_ConfigScaleOutBB");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void configurationScaleOutBBExceptionTest() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncQueryTasks)
+ .queryVfModule(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ConfigurationScaleOutBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_ConfigScaleOutBB", "QueryVfModule")
+ .hasNotPassed("GetConfigScaleOutParams", "Call-AppC-ConfigScaleOut", "End_ConfigScaleOutBB");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateCustomerBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateCustomerBBTest.java
index 91d3fd20a2..ee85f9bc05 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateCustomerBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateCustomerBBTest.java
@@ -19,34 +19,35 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class CreateCustomerBBTest extends BaseBPMNTest{
- @Test
- public void createCustomerBBTest() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateCustomerBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("CreateCustomerBB_Start", "CreateCustomerAAI", "CreateCustomerBB_End");
- assertThat(pi).isEnded();
- }
+public class CreateCustomerBBTest extends BaseBPMNTest {
+ @Test
+ public void createCustomerBBTest() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateCustomerBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("CreateCustomerBB_Start", "CreateCustomerAAI",
+ "CreateCustomerBB_End");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void createCustomerBBExceptionTest() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiCreateTasks).createCustomer(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateCustomerBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("CreateCustomerBB_Start", "CreateCustomerAAI")
- .hasNotPassed("CreateCustomer_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void createCustomerBBExceptionTest() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiCreateTasks)
+ .createCustomer(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateCustomerBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("CreateCustomerBB_Start", "CreateCustomerAAI")
+ .hasNotPassed("CreateCustomer_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateNetworkBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateNetworkBBTest.java
index 0aba1cc484..ece5b93ee2 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateNetworkBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateNetworkBBTest.java
@@ -19,35 +19,37 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class CreateNetworkBBTest extends BaseBPMNTest{
+public class CreateNetworkBBTest extends BaseBPMNTest {
@Test
public void sunnyDayCreateNetwork_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateNetworkBB",variables);
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateNetworkBB", variables);
assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("createNetwork_startEvent", "ServiceTask_get_cloud_region", "QueryVpnBinding_ServiceTask", "QueryNetworkPolicy_ServiceTask", "QueryNetworkTableRef_ServiceTask", "QueryNetworkSubnet_ServiceTask", "Create_Network_ServiceTask", "Update_Network_AAI_ServiceTask", "createNetwork_EndEvent");
+ assertThat(pi).isStarted().hasPassedInOrder("createNetwork_startEvent", "ServiceTask_get_cloud_region",
+ "QueryVpnBinding_ServiceTask", "QueryNetworkPolicy_ServiceTask", "QueryNetworkTableRef_ServiceTask",
+ "QueryNetworkSubnet_ServiceTask", "Create_Network_ServiceTask", "Update_Network_AAI_ServiceTask",
+ "createNetwork_EndEvent");
assertThat(pi).isEnded();
}
- @Test
- public void rainyDayCreateNetwork_Test() throws Exception {
-
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(createNetwork).buildCreateNetworkRequest(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateNetworkBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("createNetwork_startEvent")
- .hasNotPassed("End Flow");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayCreateNetwork_Test() throws Exception {
+
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(createNetwork)
+ .buildCreateNetworkRequest(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateNetworkBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("createNetwork_startEvent").hasNotPassed("End Flow");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateNetworkCollectionBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateNetworkCollectionBBTest.java
index 5c67324e0a..1d9cf5ad69 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateNetworkCollectionBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateNetworkCollectionBBTest.java
@@ -19,33 +19,36 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class CreateNetworkCollectionBBTest extends BaseBPMNTest{
+public class CreateNetworkCollectionBBTest extends BaseBPMNTest {
@Test
public void sunnyDayCreateNetworkCollection_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateNetworkCollectionBB",variables);
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateNetworkCollectionBB", variables);
assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("createNetworkCollection_startEvent", "BuildName_ServiceTask", "ServiceTask_create_NetworkCollection", "ServiceTask_create_NetworkCollectionInstanceGroup", "ServiceTask_Connect_Collection_to_InstanceGroup", "ServiceTask_Connect_InstanceGroup_to_CloudRegion", "ServiceTask_Connect_Collection_to_ServiceInstance", "createNetworkCollection_EndEvent");
+ assertThat(pi).isStarted().hasPassedInOrder("createNetworkCollection_startEvent", "BuildName_ServiceTask",
+ "ServiceTask_create_NetworkCollection", "ServiceTask_create_NetworkCollectionInstanceGroup",
+ "ServiceTask_Connect_Collection_to_InstanceGroup", "ServiceTask_Connect_InstanceGroup_to_CloudRegion",
+ "ServiceTask_Connect_Collection_to_ServiceInstance", "createNetworkCollection_EndEvent");
assertThat(pi).isEnded();
}
- @Test
- public void rainyDayCreateNetworkCollection_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiCreateTasks).createNetworkCollectionInstanceGroup(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateNetworkCollectionBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("createNetworkCollection_startEvent", "BuildName_ServiceTask", "ServiceTask_create_NetworkCollection")
- .hasNotPassed("createNetworkCollection_EndEvent");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayCreateNetworkCollection_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiCreateTasks)
+ .createNetworkCollectionInstanceGroup(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateNetworkCollectionBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("createNetworkCollection_startEvent", "BuildName_ServiceTask",
+ "ServiceTask_create_NetworkCollection").hasNotPassed("createNetworkCollection_EndEvent");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateVfModuleBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateVfModuleBBTest.java
index 8c44309cca..4c5edade6e 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateVfModuleBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateVfModuleBBTest.java
@@ -19,100 +19,99 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class CreateVfModuleBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDayCreateVfModule_Test() throws InterruptedException {
- mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("CreateVfModuleBB_Start",
- "QueryVnf",
- "QueryVfModule",
- "CreateVfModule",
- "VnfAdapter",
- "CreateNetworkPolicies",
- "UpdateVnfIpv4OamAddress",
- "UpdateVnfManagementV6Address",
- "UpdateVfModuleContrailServiceInstanceFqdn",
- "UpdateVfModuleHeatStackId",
- "UpdateVfModuleStatus",
- "CreateVfModuleBB_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayCreateVfModuleSDNCQueryVnfError_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncQueryTasks).queryVnf(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("CreateVfModuleBB_Start", "QueryVnf")
- .hasNotPassed("QueryVfModule", "CreateVfModule", "VnfAdapter", "CreateNetworkPolicies", "UpdateVnfIpv4OamAddress",
- "UpdateVnfManagementV6Address","UpdateVfModuleContrailServiceInstanceFqdn","UpdateVfModuleHeatStackId",
- "UpdateVfModuleStatus", "CreateVfModuleBB_End");
- assertThat(pi).isEnded();
- }
+public class CreateVfModuleBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayCreateVfModule_Test() throws InterruptedException {
+ mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("CreateVfModuleBB_Start", "QueryVnf", "QueryVfModule",
+ "CreateVfModule", "VnfAdapter", "CreateNetworkPolicies", "UpdateVnfIpv4OamAddress",
+ "UpdateVnfManagementV6Address", "UpdateVfModuleContrailServiceInstanceFqdn",
+ "UpdateVfModuleHeatStackId", "UpdateVfModuleStatus", "CreateVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayCreateVfModuleSDNCQueryVnfError_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncQueryTasks)
+ .queryVnf(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("CreateVfModuleBB_Start", "QueryVnf").hasNotPassed("QueryVfModule",
+ "CreateVfModule", "VnfAdapter", "CreateNetworkPolicies", "UpdateVnfIpv4OamAddress",
+ "UpdateVnfManagementV6Address", "UpdateVfModuleContrailServiceInstanceFqdn",
+ "UpdateVfModuleHeatStackId", "UpdateVfModuleStatus", "CreateVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayCreateVfModuleSDNCQueryVnfModuleError_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncQueryTasks)
+ .queryVfModule(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("CreateVfModuleBB_Start", "QueryVnf", "QueryVfModule").hasNotPassed(
+ "CreateVfModule", "VnfAdapter", "CreateNetworkPolicies", "UpdateVnfIpv4OamAddress",
+ "UpdateVnfManagementV6Address", "UpdateVfModuleContrailServiceInstanceFqdn",
+ "UpdateVfModuleHeatStackId", "UpdateVfModuleStatus", "CreateVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayCreateVfModuleVnfAdapterCreateError_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(vnfAdapterCreateTasks)
+ .createVfModule(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("CreateVfModuleBB_Start", "QueryVnf", "QueryVfModule", "CreateVfModule")
+ .hasNotPassed("VnfAdapter", "CreateNetworkPolicies", "UpdateVnfIpv4OamAddress",
+ "UpdateVnfManagementV6Address", "UpdateVfModuleContrailServiceInstanceFqdn",
+ "UpdateVfModuleHeatStackId", "UpdateVfModuleStatus", "CreateVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayCreateVfModuleUpdateVfModuleHeatStackIdError_Test() throws Exception {
+ mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
+
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks)
+ .updateHeatStackIdVfModule(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("CreateVfModuleBB_Start", "QueryVnf", "QueryVfModule", "CreateVfModule", "VnfAdapter",
+ "CreateNetworkPolicies", "UpdateVnfIpv4OamAddress", "UpdateVnfManagementV6Address",
+ "UpdateVfModuleContrailServiceInstanceFqdn", "UpdateVfModuleHeatStackId")
+ .hasNotPassed("UpdateVfModuleStatus", "CreateVfModuleBB_End");
+ assertThat(pi).isEnded();
- @Test
- public void rainyDayCreateVfModuleSDNCQueryVnfModuleError_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncQueryTasks).queryVfModule(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("CreateVfModuleBB_Start", "QueryVnf", "QueryVfModule")
- .hasNotPassed("CreateVfModule", "VnfAdapter", "CreateNetworkPolicies", "UpdateVnfIpv4OamAddress", "UpdateVnfManagementV6Address",
- "UpdateVfModuleContrailServiceInstanceFqdn","UpdateVfModuleHeatStackId", "UpdateVfModuleStatus", "CreateVfModuleBB_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayCreateVfModuleVnfAdapterCreateError_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(vnfAdapterCreateTasks).createVfModule(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("CreateVfModuleBB_Start", "QueryVnf", "QueryVfModule", "CreateVfModule")
- .hasNotPassed("VnfAdapter", "CreateNetworkPolicies","UpdateVnfIpv4OamAddress", "UpdateVnfManagementV6Address",
- "UpdateVfModuleContrailServiceInstanceFqdn","UpdateVfModuleHeatStackId", "UpdateVfModuleStatus", "CreateVfModuleBB_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayCreateVfModuleUpdateVfModuleHeatStackIdError_Test() throws Exception {
- mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
+ }
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks).updateHeatStackIdVfModule(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("CreateVfModuleBB_Start", "QueryVnf", "QueryVfModule", "CreateVfModule", "VnfAdapter", "CreateNetworkPolicies",
- "UpdateVnfIpv4OamAddress", "UpdateVnfManagementV6Address", "UpdateVfModuleContrailServiceInstanceFqdn","UpdateVfModuleHeatStackId")
- .hasNotPassed("UpdateVfModuleStatus", "CreateVfModuleBB_End");
- assertThat(pi).isEnded();
-
- }
-
- @Test
- public void rainyDayCreateVfModuleUpdateVfModuleStatusError_Test() throws Exception {
- mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks).updateOrchestrationStatusCreatedVfModule(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("CreateVfModuleBB_Start", "QueryVnf", "QueryVfModule", "CreateVfModule", "VnfAdapter", "CreateNetworkPolicies",
- "UpdateVnfIpv4OamAddress", "UpdateVnfManagementV6Address", "UpdateVfModuleContrailServiceInstanceFqdn","UpdateVfModuleHeatStackId",
- "UpdateVfModuleStatus")
- .hasNotPassed("CreateVfModuleBB_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayCreateVfModuleUpdateVfModuleStatusError_Test() throws Exception {
+ mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks)
+ .updateOrchestrationStatusCreatedVfModule(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("CreateVfModuleBB_Start", "QueryVnf", "QueryVfModule", "CreateVfModule", "VnfAdapter",
+ "CreateNetworkPolicies", "UpdateVnfIpv4OamAddress", "UpdateVnfManagementV6Address",
+ "UpdateVfModuleContrailServiceInstanceFqdn", "UpdateVfModuleHeatStackId",
+ "UpdateVfModuleStatus")
+ .hasNotPassed("CreateVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateVolumeGroupBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateVolumeGroupBBTest.java
index 34a17cbb89..c7eb2ac3d1 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateVolumeGroupBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/CreateVolumeGroupBBTest.java
@@ -19,48 +19,54 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class CreateVolumeGroupBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDayCreateVolumeGroup_Test() throws InterruptedException {
- mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("CreateVolumeGroupBB_Start", "QueryVfModuleSDNC", "CreateVolumeGroupVnfAdapter", "Vnf_Adapter", "UpdateVolumeGroupHeatStackId", "UpdateVolumeGroupAAI", "CreateVolumeGroupBB_End");
- assertThat(pi).isEnded();
- assertThat(pi).hasPassedInOrder("CreateVolumeGroupBB_Start", "QueryVfModuleSDNC", "CreateVolumeGroupVnfAdapter", "Vnf_Adapter","UpdateVolumeGroupAAI", "CreateVolumeGroupBB_End");
- }
+public class CreateVolumeGroupBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayCreateVolumeGroup_Test() throws InterruptedException {
+ mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("CreateVolumeGroupBB_Start", "QueryVfModuleSDNC",
+ "CreateVolumeGroupVnfAdapter", "Vnf_Adapter", "UpdateVolumeGroupHeatStackId", "UpdateVolumeGroupAAI",
+ "CreateVolumeGroupBB_End");
+ assertThat(pi).isEnded();
+ assertThat(pi).hasPassedInOrder("CreateVolumeGroupBB_Start", "QueryVfModuleSDNC", "CreateVolumeGroupVnfAdapter",
+ "Vnf_Adapter", "UpdateVolumeGroupAAI", "CreateVolumeGroupBB_End");
+ }
+
+ @Test
+ public void rainyDayCreateVolumeGroup_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(vnfAdapterCreateTasks)
+ .createVolumeGroupRequest(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("CreateVolumeGroupBB_Start", "QueryVfModuleSDNC", "CreateVolumeGroupVnfAdapter")
+ .hasNotPassed("UpdateVolumeGroupHeatStackId", "UpdateVolumeGroupAAI", "CreateVolumeGroupBB_End");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDayCreateVolumeGroup_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(vnfAdapterCreateTasks).createVolumeGroupRequest(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("CreateVolumeGroupBB_Start", "QueryVfModuleSDNC", "CreateVolumeGroupVnfAdapter")
- .hasNotPassed("UpdateVolumeGroupHeatStackId", "UpdateVolumeGroupAAI", "CreateVolumeGroupBB_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayCreateVolumeGroupUpdateHeatStackIdError_Test() throws Exception {
- mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks).updateHeatStackIdVolumeGroup(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("CreateVolumeGroupBB_Start", "QueryVfModuleSDNC", "CreateVolumeGroupVnfAdapter", "Vnf_Adapter")
- .hasNotPassed("UpdateVolumeGroupAAI", "CreateVolumeGroupBB_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayCreateVolumeGroupUpdateHeatStackIdError_Test() throws Exception {
+ mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks)
+ .updateHeatStackIdVolumeGroup(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("CreateVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi)
+ .isStarted().hasPassedInOrder("CreateVolumeGroupBB_Start", "QueryVfModuleSDNC",
+ "CreateVolumeGroupVnfAdapter", "Vnf_Adapter")
+ .hasNotPassed("UpdateVolumeGroupAAI", "CreateVolumeGroupBB_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateNetworkBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateNetworkBBTest.java
index ad93eec514..548dca2225 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateNetworkBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateNetworkBBTest.java
@@ -19,35 +19,36 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class DeactivateNetworkBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDayDeactivateNetworkBB_Test() throws InterruptedException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateNetworkBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("DeactivateNetworkBB_Start", "DeactivateNetworkSDNC", "CallActivity_sdncHandler","DeactivateNetworkAAI", "DeactivateNetworkBB_End");
- assertThat(pi).isEnded();
- }
+public class DeactivateNetworkBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayDeactivateNetworkBB_Test() throws InterruptedException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateNetworkBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("DeactivateNetworkBB_Start", "DeactivateNetworkSDNC",
+ "CallActivity_sdncHandler", "DeactivateNetworkAAI", "DeactivateNetworkBB_End");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDayDeactivateNetworkBB_Test() throws Exception {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncDeactivateTasks).deactivateNetwork(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateNetworkBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("DeactivateNetworkBB_Start", "DeactivateNetworkSDNC")
- .hasNotPassed("DeactivateNetworkAAI", "DeactivateNetworkBB_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayDeactivateNetworkBB_Test() throws Exception {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncDeactivateTasks)
+ .deactivateNetwork(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateNetworkBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("DeactivateNetworkBB_Start", "DeactivateNetworkSDNC")
+ .hasNotPassed("DeactivateNetworkAAI", "DeactivateNetworkBB_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateServiceInstanceBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateServiceInstanceBBTest.java
index 428713d9a7..ba9beabce7 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateServiceInstanceBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateServiceInstanceBBTest.java
@@ -19,8 +19,8 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
-import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
+import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
@@ -28,13 +28,15 @@ import org.onap.so.bpmn.BaseBPMNTest;
/**
* Unit test cases for DeActivateServiceInstanceTest.bpmn
*/
-public class DeactivateServiceInstanceBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDayDeactivateServiceInstanceSDNC() throws InterruptedException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateServiceInstanceBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_DeactivateServiceInstanceBB", "Task_DeactivateServiceInstance_SDNC", "CallActivity_sdncHandler", "Task_DeactivateServiceInstance_AAI", "End_DeactivateServiceInstanceBB");
- assertThat(pi).isEnded();
- }
+public class DeactivateServiceInstanceBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayDeactivateServiceInstanceSDNC() throws InterruptedException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateServiceInstanceBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_DeactivateServiceInstanceBB",
+ "Task_DeactivateServiceInstance_SDNC", "CallActivity_sdncHandler", "Task_DeactivateServiceInstance_AAI",
+ "End_DeactivateServiceInstanceBB");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVfModuleBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVfModuleBBTest.java
index c7232e504e..945c212f90 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVfModuleBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVfModuleBBTest.java
@@ -19,39 +19,39 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import java.io.IOException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class DeactivateVfModuleBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDay() throws InterruptedException, IOException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("DeactivateVfModuleBB_Start", "DeactivateVfModule", "CallActivity_sdncHandler",
- "UpdateVfModuleDeactivateStatus", "DeactivateVfModuleBB_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDay() throws Exception {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- doThrow(BpmnError.class).when(aaiUpdateTasks).updateOrchestrationStatusDeactivateVfModule(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("DeactivateVfModuleBB_Start", "DeactivateVfModule", "UpdateVfModuleDeactivateStatus")
- .hasNotPassed("DeActivateVfModuleBB_End");
- assertThat(pi).isEnded();
-
- }
+public class DeactivateVfModuleBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDay() throws InterruptedException, IOException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("DeactivateVfModuleBB_Start", "DeactivateVfModule",
+ "CallActivity_sdncHandler", "UpdateVfModuleDeactivateStatus", "DeactivateVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDay() throws Exception {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ doThrow(BpmnError.class).when(aaiUpdateTasks)
+ .updateOrchestrationStatusDeactivateVfModule(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("DeactivateVfModuleBB_Start", "DeactivateVfModule", "UpdateVfModuleDeactivateStatus")
+ .hasNotPassed("DeActivateVfModuleBB_End");
+ assertThat(pi).isEnded();
+
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVnfBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVnfBBTest.java
index bf5e228cbf..0ecf0448e2 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVnfBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVnfBBTest.java
@@ -19,49 +19,48 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import java.io.IOException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class DeactivateVnfBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDay() throws InterruptedException, IOException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVnfBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_DeactivateVnfBB","Task_SDNCAdapterVnfTopologyDeactivate",
- "CallActivity_sdncHandler", "Task_DeactivateOrchestrationStatusVnf", "End_DeactivateVnfBB");
- assertThat(pi).isEnded();
- }
+public class DeactivateVnfBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDay() throws InterruptedException, IOException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVnfBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_DeactivateVnfBB", "Task_SDNCAdapterVnfTopologyDeactivate",
+ "CallActivity_sdncHandler", "Task_DeactivateOrchestrationStatusVnf", "End_DeactivateVnfBB");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDayDeactivateVnfSDNCError_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncDeactivateTasks).deactivateVnf(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVnfBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("Start_DeactivateVnfBB", "Task_SDNCAdapterVnfTopologyDeactivate")
- .hasNotPassed("Task_DeactivateOrchestrationStatusVnf", "End_DeactivateVnfBB");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayDeactivateVnfSDNCError_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncDeactivateTasks)
+ .deactivateVnf(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVnfBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_DeactivateVnfBB", "Task_SDNCAdapterVnfTopologyDeactivate")
+ .hasNotPassed("Task_DeactivateOrchestrationStatusVnf", "End_DeactivateVnfBB");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDayDeactivateVnfAAIError_Test() throws Exception {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks).updateOrchestrationStatusAssignedVnf(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVnfBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("Start_DeactivateVnfBB", "Task_SDNCAdapterVnfTopologyDeactivate","Task_DeactivateOrchestrationStatusVnf")
- .hasNotPassed("End_DeactivateVnfBB");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayDeactivateVnfAAIError_Test() throws Exception {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks)
+ .updateOrchestrationStatusAssignedVnf(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVnfBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_DeactivateVnfBB", "Task_SDNCAdapterVnfTopologyDeactivate",
+ "Task_DeactivateOrchestrationStatusVnf").hasNotPassed("End_DeactivateVnfBB");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVolumeGroupBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVolumeGroupBBTest.java
index 8ed3e0710f..ab0903d645 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVolumeGroupBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeactivateVolumeGroupBBTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,22 +30,23 @@ import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
public class DeactivateVolumeGroupBBTest extends BaseBPMNTest {
- @Test
- public void sunnyDayAssignVolumeGroup_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("DeactivateVolumeGroupBB_Start", "DeactivateVolumeGroup", "DeactivateVolumeGroupBB_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void sunnyDayAssignVolumeGroup_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("DeactivateVolumeGroupBB_Start", "DeactivateVolumeGroup",
+ "DeactivateVolumeGroupBB_End");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDayAssignVolumeGroup_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks).updateOrchestrationStatusCreatedVolumeGroup(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("DeactivateVolumeGroupBB_Start", "DeactivateVolumeGroup")
- .hasNotPassed("DeactivateVolumeGroupBB_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayAssignVolumeGroup_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks)
+ .updateOrchestrationStatusCreatedVolumeGroup(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeactivateVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("DeactivateVolumeGroupBB_Start", "DeactivateVolumeGroup")
+ .hasNotPassed("DeactivateVolumeGroupBB_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteInstanceGroupBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteInstanceGroupBBTest.java
index 6dc36ae100..b527e8887e 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteInstanceGroupBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteInstanceGroupBBTest.java
@@ -18,36 +18,35 @@
* ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import java.io.IOException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class DeleteInstanceGroupBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDay() throws InterruptedException, IOException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteInstanceGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("DeleteInstanceGroupBB_Start", "DeleteInstanceGroupNaming", "DeleteInstanceGroupAAI",
- "DeleteInstanceGroupBB_End");
- assertThat(pi).isEnded();
- }
+public class DeleteInstanceGroupBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDay() throws InterruptedException, IOException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteInstanceGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("DeleteInstanceGroupBB_Start", "DeleteInstanceGroupNaming",
+ "DeleteInstanceGroupAAI", "DeleteInstanceGroupBB_End");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDay() throws Exception {
- doThrow(BpmnError.class).when(aaiDeleteTasks).deleteInstanceGroup(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteInstanceGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("DeleteInstanceGroupBB_Start", "DeleteInstanceGroupNaming", "DeleteInstanceGroupAAI")
- .hasNotPassed("DeleteInstanceGroupBB_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDay() throws Exception {
+ doThrow(BpmnError.class).when(aaiDeleteTasks).deleteInstanceGroup(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteInstanceGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("DeleteInstanceGroupBB_Start", "DeleteInstanceGroupNaming", "DeleteInstanceGroupAAI")
+ .hasNotPassed("DeleteInstanceGroupBB_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteNetworkBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteNetworkBBTest.java
index ce25a42a26..5a62436bfc 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteNetworkBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteNetworkBBTest.java
@@ -19,33 +19,34 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class DeleteNetworkBBTest extends BaseBPMNTest{
+public class DeleteNetworkBBTest extends BaseBPMNTest {
@Test
public void sunnyDayDeleteNetwork_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteNetworkBB",variables);
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteNetworkBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("deleteNetwork_startEvent", "deleteNetworkAIC", "updateNetworkAAI",
+ "deleteNetwork_endEvent");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayDeleteNetwork_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(networkAdapterDeleteTasks)
+ .deleteNetwork(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteNetworkBB", variables);
assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("deleteNetwork_startEvent", "deleteNetworkAIC", "updateNetworkAAI", "deleteNetwork_endEvent");
+ assertThat(pi).isStarted().hasPassedInOrder("deleteNetwork_startEvent", "deleteNetworkAIC")
+ .hasNotPassed("updateNetworkAAI", "deleteNetwork_endEvent");
assertThat(pi).isEnded();
}
-
- @Test
- public void rainyDayDeleteNetwork_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(networkAdapterDeleteTasks).deleteNetwork(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteNetworkBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("deleteNetwork_startEvent", "deleteNetworkAIC")
- .hasNotPassed("updateNetworkAAI", "deleteNetwork_endEvent");
- assertThat(pi).isEnded();
- }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteNetworkCollectionBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteNetworkCollectionBBTest.java
index 388f169b9c..f1da33d75a 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteNetworkCollectionBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteNetworkCollectionBBTest.java
@@ -19,34 +19,36 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class DeleteNetworkCollectionBBTest extends BaseBPMNTest{
+public class DeleteNetworkCollectionBBTest extends BaseBPMNTest {
@Test
public void sunnyDayCreateNetworkCollection_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteNetworkCollectionBB",variables);
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteNetworkCollectionBB", variables);
assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("deleteNetworkCollection_startEvent", "ServiceTask_delete_NetworkCollectionInstanceGroup", "ServiceTask_delete_NetworkCollection", "deleteNetworkCollection_EndEvent");
+ assertThat(pi).isStarted().hasPassedInOrder("deleteNetworkCollection_startEvent",
+ "ServiceTask_delete_NetworkCollectionInstanceGroup", "ServiceTask_delete_NetworkCollection",
+ "deleteNetworkCollection_EndEvent");
assertThat(pi).isEnded();
}
- @Test
- public void rainyDayCreateNetworkCollection_Test() throws Exception {
-
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiDeleteTasks).deleteInstanceGroup(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteNetworkCollectionBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("deleteNetworkCollection_startEvent")
- .hasNotPassed("deleteNetworkCollection_EndEvent");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayCreateNetworkCollection_Test() throws Exception {
+
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiDeleteTasks)
+ .deleteInstanceGroup(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteNetworkCollectionBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("deleteNetworkCollection_startEvent")
+ .hasNotPassed("deleteNetworkCollection_EndEvent");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteVfModuleBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteVfModuleBBTest.java
index 48ae22cb1a..e88df73f39 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteVfModuleBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteVfModuleBBTest.java
@@ -18,13 +18,12 @@
* ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import java.io.IOException;
import java.util.List;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.externaltask.LockedExternalTask;
import org.camunda.bpm.engine.runtime.ProcessInstance;
@@ -33,55 +32,54 @@ import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class DeleteVfModuleBBTest extends BaseBPMNTest{
+public class DeleteVfModuleBBTest extends BaseBPMNTest {
- @Before
- public void before() {
- variables.put("auditInventoryNeeded", true);
- }
+ @Before
+ public void before() {
+ variables.put("auditInventoryNeeded", true);
+ }
- @Test
- public void sunnyDay() throws InterruptedException, IOException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteVfModuleBB", variables);
- List<LockedExternalTask> tasks = externalTaskService.fetchAndLock(100, "externalWorkerId")
+ @Test
+ public void sunnyDay() throws InterruptedException, IOException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteVfModuleBB", variables);
+ List<LockedExternalTask> tasks = externalTaskService.fetchAndLock(100, "externalWorkerId")
.topic("InventoryDeleteAudit", 60L * 1000L).execute();
while (!tasks.isEmpty()) {
for (LockedExternalTask task : tasks) {
externalTaskService.complete(task.getId(), "externalWorkerId");
}
- tasks = externalTaskService.fetchAndLock(100, "externalWorkerId")
- .topic("InventoryDeleteAudit", 60L * 1000L).execute();
+ tasks = externalTaskService.fetchAndLock(100, "externalWorkerId").topic("InventoryDeleteAudit", 60L * 1000L)
+ .execute();
}
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassed("DeleteVfModuleBB_Start","ExclusiveGateway_0xrgzm7","ExclusiveGateway_1yvh16a","Check_Audit",
- "Setup_Audit_Variable","Audit_Inventory","DeleteVfModuleVnfAdapter", "VnfAdapter",
- "DeleteNetworkPolicies", "UpdateVnfIpv4OamAddress", "UpdateVnfManagementV6Address",
- "UpdateVfModuleContrailServiceInstanceFqdn",
- "UpdateVfModuleHeatStackId", "UpdateVfModuleDeleteStatus", "DeleteVfModuleBB_End");
- assertThat(pi).isEnded();
- }
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassed("DeleteVfModuleBB_Start", "ExclusiveGateway_0xrgzm7",
+ "ExclusiveGateway_1yvh16a", "Check_Audit", "Setup_Audit_Variable", "Audit_Inventory",
+ "DeleteVfModuleVnfAdapter", "VnfAdapter", "DeleteNetworkPolicies", "UpdateVnfIpv4OamAddress",
+ "UpdateVnfManagementV6Address", "UpdateVfModuleContrailServiceInstanceFqdn",
+ "UpdateVfModuleHeatStackId", "UpdateVfModuleDeleteStatus", "DeleteVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDay() throws Exception {
- doThrow(BpmnError.class).when(vnfAdapterDeleteTasks).deleteVfModule(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteVfModuleBB", variables);
- List<LockedExternalTask> tasks = externalTaskService.fetchAndLock(100, "externalWorkerId")
+ @Test
+ public void rainyDay() throws Exception {
+ doThrow(BpmnError.class).when(vnfAdapterDeleteTasks).deleteVfModule(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteVfModuleBB", variables);
+ List<LockedExternalTask> tasks = externalTaskService.fetchAndLock(100, "externalWorkerId")
.topic("InventoryDeleteAudit", 60L * 1000L).execute();
while (!tasks.isEmpty()) {
for (LockedExternalTask task : tasks) {
externalTaskService.complete(task.getId(), "externalWorkerId");
}
- tasks = externalTaskService.fetchAndLock(100, "externalWorkerId")
- .topic("InventoryDeleteAudit", 60L * 1000L).execute();
+ tasks = externalTaskService.fetchAndLock(100, "externalWorkerId").topic("InventoryDeleteAudit", 60L * 1000L)
+ .execute();
}
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassed("DeleteVfModuleBB_Start", "DeleteVfModuleVnfAdapter")
- .hasNotPassed("VnfAdapter", "DeleteNetworkPolicies", "UpdateVnfIpv4OamAddress", "UpdateVnfManagementV6Address",
- "UpdateVfModuleContrailServiceInstanceFqdn","UpdateVfModuleHeatStackId", "UpdateVfModuleDeleteStatus",
- "DeleteVfModuleBB_End");
- assertThat(pi).isEnded();
- }
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassed("DeleteVfModuleBB_Start", "DeleteVfModuleVnfAdapter").hasNotPassed(
+ "VnfAdapter", "DeleteNetworkPolicies", "UpdateVnfIpv4OamAddress", "UpdateVnfManagementV6Address",
+ "UpdateVfModuleContrailServiceInstanceFqdn", "UpdateVfModuleHeatStackId", "UpdateVfModuleDeleteStatus",
+ "DeleteVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteVolumeGroupBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteVolumeGroupBBTest.java
index 2336bb54ca..00adcd2c59 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteVolumeGroupBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DeleteVolumeGroupBBTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,24 +30,26 @@ import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
public class DeleteVolumeGroupBBTest extends BaseBPMNTest {
- @Test
- public void sunnyDayDeleteVolumeGroup_Test() throws InterruptedException {
- mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("DeleteVolumeGroupBB_Start", "DeleteVolumeGroupVnfAdapter", "VnfAdapter", "UpdateVolumeGroupHeatStackId", "UpdateVolumeGroupAAI", "DeleteVolumeGroupBB_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void sunnyDayDeleteVolumeGroup_Test() throws InterruptedException {
+ mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("DeleteVolumeGroupBB_Start", "DeleteVolumeGroupVnfAdapter",
+ "VnfAdapter", "UpdateVolumeGroupHeatStackId", "UpdateVolumeGroupAAI", "DeleteVolumeGroupBB_End");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDayDeleteVolumeGroup_Test() throws Exception {
- mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks).updateOrchestrationStatusAssignedVolumeGroup(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("DeleteVolumeGroupBB_Start", "DeleteVolumeGroupVnfAdapter", "VnfAdapter", "UpdateVolumeGroupHeatStackId", "UpdateVolumeGroupAAI")
- .hasNotPassed("DeleteVolumeGroupBB_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayDeleteVolumeGroup_Test() throws Exception {
+ mockSubprocess("VnfAdapter", "Mocked VnfAdapter", "GenericStub");
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiUpdateTasks)
+ .updateOrchestrationStatusAssignedVolumeGroup(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DeleteVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("DeleteVolumeGroupBB_Start", "DeleteVolumeGroupVnfAdapter",
+ "VnfAdapter", "UpdateVolumeGroupHeatStackId", "UpdateVolumeGroupAAI")
+ .hasNotPassed("DeleteVolumeGroupBB_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DistributeTrafficActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DistributeTrafficActivityTest.java
index 35fbaa1a04..8306de4794 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DistributeTrafficActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DistributeTrafficActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,28 +30,25 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class DistributeTrafficActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayDistributeTrafficActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DistributeTrafficActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("DistributeTrafficActivity_Start",
- "TaskPreProcessActivity",
- "TaskDistributeTraffic",
- "DistributeTrafficActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayDistributeTrafficActivity_Test() throws Exception {
- variables.put("actionDistributeTraffic", Action.DistributeTraffic);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DistributeTrafficActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("DistributeTrafficActivity_Start",
- "TaskPreProcessActivity",
- "TaskDistributeTraffic").hasNotPassed(
- "DistributeTrafficActivity_End");
- }
-
+public class DistributeTrafficActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayDistributeTrafficActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DistributeTrafficActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("DistributeTrafficActivity_Start", "TaskPreProcessActivity",
+ "TaskDistributeTraffic", "DistributeTrafficActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayDistributeTrafficActivity_Test() throws Exception {
+ variables.put("actionDistributeTraffic", Action.DistributeTraffic);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DistributeTrafficActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("DistributeTrafficActivity_Start", "TaskPreProcessActivity", "TaskDistributeTraffic")
+ .hasNotPassed("DistributeTrafficActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DistributeTrafficCheckActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DistributeTrafficCheckActivityTest.java
index e360c83335..195a1ed809 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DistributeTrafficCheckActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/DistributeTrafficCheckActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,28 +30,26 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class DistributeTrafficCheckActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayDistributeTrafficCheckActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DistributeTrafficCheckActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("DistributeTrafficCheckActivity_Start",
- "TaskPreProcessActivity",
- "TaskDistributeTrafficCheck",
- "DistributeTrafficCheckActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayDistributeTrafficActivity_Test() throws Exception {
- variables.put("actionDistributeTrafficCheck", Action.DistributeTrafficCheck);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("DistributeTrafficCheckActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("DistributeTrafficCheckActivity_Start",
- "TaskPreProcessActivity",
- "TaskDistributeTrafficCheck").hasNotPassed(
- "DistributeTrafficCheckActivity_End");
- }
-
+public class DistributeTrafficCheckActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayDistributeTrafficCheckActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DistributeTrafficCheckActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("DistributeTrafficCheckActivity_Start", "TaskPreProcessActivity",
+ "TaskDistributeTrafficCheck", "DistributeTrafficCheckActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayDistributeTrafficActivity_Test() throws Exception {
+ variables.put("actionDistributeTrafficCheck", Action.DistributeTrafficCheck);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("DistributeTrafficCheckActivity", variables);
+ assertThat(pi)
+ .isNotNull().isStarted().hasPassedInOrder("DistributeTrafficCheckActivity_Start",
+ "TaskPreProcessActivity", "TaskDistributeTrafficCheck")
+ .hasNotPassed("DistributeTrafficCheckActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ExecuteBuildingBlockTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ExecuteBuildingBlockTest.java
index 03e50591c7..07554cdf97 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ExecuteBuildingBlockTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/ExecuteBuildingBlockTest.java
@@ -19,14 +19,13 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
-
import java.util.List;
-
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.delegate.BpmnError;
@@ -46,86 +45,98 @@ import org.onap.so.db.catalog.beans.OrchestrationStatusValidationDirective;
import org.springframework.beans.factory.annotation.Autowired;
public class ExecuteBuildingBlockTest extends BaseBPMNTest {
- @Autowired
- private TaskService taskService;
- @Autowired
- private ManagementService managementService;
-
- @Test
- public void runExecuteFlowTest() {
-
- variables.put("orchestrationStatusValidationResult", OrchestrationStatusValidationDirective.CONTINUE);
- variables.put("flowToBeCalled", "MockFlow");
-
- mockSubprocess("MockFlow", "My Mock Process Name", "GenericStub");
-
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ExecuteBuildingBlock", variables);
-
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("Start_ExecuteBuildingBlock", "Task_BBInputSetup", "StatusPolicy", "CheckOrchestrationStatusValidationResults", "Task_PreValidate", "Call_BBToExecute", "Task_PostValidate", "Task_setHandlingCodeSuccess", "End_ExecuteBuildingBlock");
- assertThat(pi).isEnded();
-
-
- }
- @Test
- public void test_sunnyDayExecuteBuildingBlock_silentSuccess() throws Exception {
- variables.put("orchestrationStatusValidationResult", OrchestrationStatusValidationDirective.SILENT_SUCCESS);
-
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ExecuteBuildingBlock", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("Start_ExecuteBuildingBlock", "Task_BBInputSetup", "StatusPolicy", "CheckOrchestrationStatusValidationResults","Task_setHandlingCodeSuccess", "End_ExecuteBuildingBlock")
- .hasNotPassed("Call_BBToExecute", "ErrorStart", "Task_QueryRainyDayTable", "ExclusiveGateway_1aonzik", "ExclusiveGateway_1aonzik", "ErrorEnd2", "Task_SetRetryTimer");
- assertThat(pi).isEnded();
- }
-
- @Test
- @Ignore
- public void test_rainyDayExecuteBuildingBlock_rollbackOrAbort() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(bbInputSetup).execute(any(DelegateExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ExecuteBuildingBlock", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("Start_ExecuteBuildingBlock", "Task_BBInputSetup", "StartEvent_0tmcs9g", "Task_QueryRainyDayTable", "ExclusiveGateway_1aonzik", "EndEvent_0mvmk3i", "SubProcess_0tv8zda")
- .hasNotPassed("StatusPolicy", "CheckOrchestrationStatusValidationResults", "Task_setHandlingCodeSuccess","Call_BBToExecute", "End_ExecuteBuildingBlock", "ExclusiveGateway_0ey4zpt", "Task_SetRetryTimer");
- assertThat(pi).isEnded();
- }
-
- @Test
- @Ignore
- public void test_rainyDayExecuteBuildingBlock_retryNoRetriesLeft() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(bbInputSetup).execute(any(DelegateExecution.class));
-
- variables.put("handlingCode", "Retry");
- variables.put("RetryCount", 5);
-
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ExecuteBuildingBlock", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("Start_ExecuteBuildingBlock", "Task_BBInputSetup", "StartEvent_0tmcs9g", "Task_QueryRainyDayTable", "ExclusiveGateway_1aonzik", "ExclusiveGateway_0ey4zpt", "ErrorEnd2")
- .hasNotPassed("StatusPolicy", "CheckOrchestrationStatusValidationResults", "Task_setHandlingCodeSuccess","Call_BBToExecute", "End_ExecuteBuildingBlock", "Task_SetRetryTimer");
- assertThat(pi).isEnded();
- }
-
- @Test
- @Ignore
- public void test_rainyDayExecuteBuildingBlock_retryRetriesLeft() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(bbInputSetup).execute(any(DelegateExecution.class));
-
- variables.put("handlingCode", "Retry");
- variables.put("RetryCount", 4);
- variables.put("RetryDuration", "PT1S");
-
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("ExecuteBuildingBlock", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted();
- assertThat(pi).isWaitingAt("IntermediateCatchEvent_RetryTimer");
- Job job = managementService.createJobQuery().activityId("IntermediateCatchEvent_RetryTimer").singleResult();
- assertNotNull(job);
- managementService.executeJob(job.getId());
- assertThat(pi).isEnded()
- .hasPassedInOrder("Start_ExecuteBuildingBlock", "Task_BBInputSetup", "BoundaryEvent_0i3q236", "Task_QueryRainyDayTable", "ExclusiveGateway_1aonzik", "ExclusiveGateway_0ey4zpt", "Task_SetRetryTimer", "EndEvent_1sez2lh")
- .hasNotPassed("StatusPolicy", "CheckOrchestrationStatusValidationResults", "Task_setHandlingCodeSuccess","Call_BBToExecute", "End_ExecuteBuildingBlock", "ErrorEnd2");
- }
+ @Autowired
+ private TaskService taskService;
+ @Autowired
+ private ManagementService managementService;
+
+ @Test
+ public void runExecuteFlowTest() {
+
+ variables.put("orchestrationStatusValidationResult", OrchestrationStatusValidationDirective.CONTINUE);
+ variables.put("flowToBeCalled", "MockFlow");
+
+ mockSubprocess("MockFlow", "My Mock Process Name", "GenericStub");
+
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ExecuteBuildingBlock", variables);
+
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_ExecuteBuildingBlock", "Task_BBInputSetup", "StatusPolicy",
+ "CheckOrchestrationStatusValidationResults", "Task_PreValidate", "Call_BBToExecute",
+ "Task_PostValidate", "Task_setHandlingCodeSuccess", "End_ExecuteBuildingBlock");
+ assertThat(pi).isEnded();
+
+
+ }
+
+ @Test
+ public void test_sunnyDayExecuteBuildingBlock_silentSuccess() throws Exception {
+ variables.put("orchestrationStatusValidationResult", OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ExecuteBuildingBlock", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_ExecuteBuildingBlock", "Task_BBInputSetup", "StatusPolicy",
+ "CheckOrchestrationStatusValidationResults", "Task_setHandlingCodeSuccess", "End_ExecuteBuildingBlock")
+ .hasNotPassed("Call_BBToExecute", "ErrorStart", "Task_QueryRainyDayTable", "ExclusiveGateway_1aonzik",
+ "ExclusiveGateway_1aonzik", "ErrorEnd2", "Task_SetRetryTimer");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ @Ignore
+ public void test_rainyDayExecuteBuildingBlock_rollbackOrAbort() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(bbInputSetup).execute(any(DelegateExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ExecuteBuildingBlock", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("Start_ExecuteBuildingBlock", "Task_BBInputSetup", "StartEvent_0tmcs9g",
+ "Task_QueryRainyDayTable", "ExclusiveGateway_1aonzik", "EndEvent_0mvmk3i", "SubProcess_0tv8zda")
+ .hasNotPassed("StatusPolicy", "CheckOrchestrationStatusValidationResults",
+ "Task_setHandlingCodeSuccess", "Call_BBToExecute", "End_ExecuteBuildingBlock",
+ "ExclusiveGateway_0ey4zpt", "Task_SetRetryTimer");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ @Ignore
+ public void test_rainyDayExecuteBuildingBlock_retryNoRetriesLeft() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(bbInputSetup).execute(any(DelegateExecution.class));
+
+ variables.put("handlingCode", "Retry");
+ variables.put("RetryCount", 5);
+
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ExecuteBuildingBlock", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("Start_ExecuteBuildingBlock", "Task_BBInputSetup", "StartEvent_0tmcs9g",
+ "Task_QueryRainyDayTable", "ExclusiveGateway_1aonzik", "ExclusiveGateway_0ey4zpt", "ErrorEnd2")
+ .hasNotPassed("StatusPolicy", "CheckOrchestrationStatusValidationResults",
+ "Task_setHandlingCodeSuccess", "Call_BBToExecute", "End_ExecuteBuildingBlock",
+ "Task_SetRetryTimer");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ @Ignore
+ public void test_rainyDayExecuteBuildingBlock_retryRetriesLeft() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(bbInputSetup).execute(any(DelegateExecution.class));
+
+ variables.put("handlingCode", "Retry");
+ variables.put("RetryCount", 4);
+ variables.put("RetryDuration", "PT1S");
+
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("ExecuteBuildingBlock", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted();
+ assertThat(pi).isWaitingAt("IntermediateCatchEvent_RetryTimer");
+ Job job = managementService.createJobQuery().activityId("IntermediateCatchEvent_RetryTimer").singleResult();
+ assertNotNull(job);
+ managementService.executeJob(job.getId());
+ assertThat(pi).isEnded()
+ .hasPassedInOrder("Start_ExecuteBuildingBlock", "Task_BBInputSetup", "BoundaryEvent_0i3q236",
+ "Task_QueryRainyDayTable", "ExclusiveGateway_1aonzik", "ExclusiveGateway_0ey4zpt",
+ "Task_SetRetryTimer", "EndEvent_1sez2lh")
+ .hasNotPassed("StatusPolicy", "CheckOrchestrationStatusValidationResults",
+ "Task_setHandlingCodeSuccess", "Call_BBToExecute", "End_ExecuteBuildingBlock", "ErrorEnd2");
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/FlowCompleteActivity.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/FlowCompleteActivity.java
index 26e8fcb5b9..1b0e8ed8a3 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/FlowCompleteActivity.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/FlowCompleteActivity.java
@@ -19,37 +19,35 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
-public class FlowCompleteActivity extends BaseBPMNTest{
- @Test
- public void sunnyDayFlowCompleteActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("FlowCompleteActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("FlowCompleteActivity_Start",
- "TaskUpdateRequestDB",
- "FlowCompleteActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayFlowCompleteActivity_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(flowCompletionTasks)
- .updateRequestDbStatus(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("FlowCompleteActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("FlowCompleteActivity_Start",
- "TaskUpdateRequestDB").hasNotPassed(
- "FlowCompleteActivity_End");
- assertThat(pi).isEnded();
- }
-
+public class FlowCompleteActivity extends BaseBPMNTest {
+ @Test
+ public void sunnyDayFlowCompleteActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("FlowCompleteActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("FlowCompleteActivity_Start", "TaskUpdateRequestDB",
+ "FlowCompleteActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayFlowCompleteActivity_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(flowCompletionTasks)
+ .updateRequestDbStatus(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("FlowCompleteActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("FlowCompleteActivity_Start", "TaskUpdateRequestDB")
+ .hasNotPassed("FlowCompleteActivity_End");
+ assertThat(pi).isEnded();
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/GenericVnfHealthCheckBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/GenericVnfHealthCheckBBTest.java
index c321ca1f71..b10a1007f5 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/GenericVnfHealthCheckBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/GenericVnfHealthCheckBBTest.java
@@ -19,12 +19,11 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import java.io.IOException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -34,27 +33,27 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
public class GenericVnfHealthCheckBBTest extends BaseBPMNTest {
-
- @Test
- public void sunnyDayGenericVnfHealthCheckBBTest() throws InterruptedException, IOException {
-
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("GenericVnfHealthCheckBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_GenericVnfHealthChkBB", "SetParamsHealthCheck",
- "Call-AppC-HealthCheck", "End_GenericVnfHealthChkBB");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void genericVnfHealthCheckBBExceptionTest() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(genericVnfHealthCheck).setParamsForGenericVnfHealthCheck(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("GenericVnfHealthCheckBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("Start_GenericVnfHealthChkBB", "SetParamsHealthCheck")
- .hasNotPassed("Call-AppC-HealthCheck", "End_GenericVnfHealthChkBB");
- assertThat(pi).isEnded();
- }
+
+ @Test
+ public void sunnyDayGenericVnfHealthCheckBBTest() throws InterruptedException, IOException {
+
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("GenericVnfHealthCheckBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_GenericVnfHealthChkBB", "SetParamsHealthCheck",
+ "Call-AppC-HealthCheck", "End_GenericVnfHealthChkBB");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void genericVnfHealthCheckBBExceptionTest() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(genericVnfHealthCheck)
+ .setParamsForGenericVnfHealthCheck(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("GenericVnfHealthCheckBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_GenericVnfHealthChkBB", "SetParamsHealthCheck")
+ .hasNotPassed("Call-AppC-HealthCheck", "End_GenericVnfHealthChkBB");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/HomingBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/HomingBBTest.java
index 27bb328177..f1bb1462d6 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/HomingBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/HomingBBTest.java
@@ -23,7 +23,6 @@ package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Ignore;
@@ -34,37 +33,36 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.springframework.boot.test.mock.mockito.MockBean;
-public class HomingBBTest extends BaseBPMNTest{
+public class HomingBBTest extends BaseBPMNTest {
+
+ @Test
+ public void testHomingV2_success() {
+ mockSubprocess("ReceiveWorkflowMessage", "Mock ReceiveWorkflowMessage", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("HomingBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("start", "sniroOofCheck", "callSniro", "ExclusiveGateway_1ckp059",
+ "receiveAsyncCallback", "sniroOofCheck2", "processSniroSolution", "ExclusiveGateway_1kvzxpb", "end");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void testHomingV2_success(){
- mockSubprocess("ReceiveWorkflowMessage", "Mock ReceiveWorkflowMessage", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("HomingBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("start", "sniroOofCheck", "callSniro", "ExclusiveGateway_1ckp059", "receiveAsyncCallback", "sniroOofCheck2", "processSniroSolution", "ExclusiveGateway_1kvzxpb", "end");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void testHomingV2_error_bpmnError() {
+ doThrow(new BpmnError("MSOWorkflowException")).when(sniroHoming).callSniro(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("HomingBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassed("start", "sniroOofCheck", "startBpmnError", "bpmnErrorSubprocess",
+ "processMsoWorkflowException", "endBpmnError").hasNotPassed("callReceiveAsync");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void testHomingV2_error_bpmnError(){
- doThrow(new BpmnError("MSOWorkflowException")).when(sniroHoming).callSniro(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("HomingBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassed("start", "sniroOofCheck", "startBpmnError", "bpmnErrorSubprocess", "processMsoWorkflowException", "endBpmnError")
- .hasNotPassed("callReceiveAsync");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void testHomingV2_error_javaException(){
- doThrow(new RuntimeException("Test")).when(sniroHoming).callSniro(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("HomingBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassed("start", "sniroOofCheck", "callSniro", "startJavaError", "processJavaException", "javaExceptionSubProcess", "endJavaError")
- .hasNotPassed("callReceiveAsync");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void testHomingV2_error_javaException() {
+ doThrow(new RuntimeException("Test")).when(sniroHoming).callSniro(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("HomingBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassed("start", "sniroOofCheck", "callSniro", "startJavaError",
+ "processJavaException", "javaExceptionSubProcess", "endJavaError").hasNotPassed("callReceiveAsync");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/PauseForManualTaskActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/PauseForManualTaskActivityTest.java
index faf485f0d7..484f9b8506 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/PauseForManualTaskActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/PauseForManualTaskActivityTest.java
@@ -19,11 +19,11 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.delegate.BpmnError;
@@ -37,67 +37,60 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.onap.so.bpmn.BaseBPMNTest;
-public class PauseForManualTaskActivityTest extends BaseBPMNTest{
- private static final String TIMEOUT_10_S = "PT10S";
-
- @Autowired
- protected ManagementService managementService;
-
- @Autowired
- protected TaskService taskService;
-
- @Test
- public void sunnyDayPauseForManualTaskTimeout_Test() throws InterruptedException {
- variables.put("taskTimeout", TIMEOUT_10_S);
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("PauseForManualTaskActivity", variables);
- assertThat(pi).isNotNull();
- BpmnAwareAssertions.assertThat(pi).isWaitingAt("ManualUserTask");
- Task task = taskService.createTaskQuery().active().list().get(0);
- assertThat(pi).task().isNotNull();
- assertNotNull(task);
-
- Job job = managementService.createJobQuery().activityId("ManualTaskTimer").singleResult();
- assertNotNull(job);
- managementService.executeJob(job.getId());
-
- assertThat(pi).isStarted().hasPassedInOrder("PauseForManualTaskActivity_Start",
- "UpdateDbStatusToPendingManualTask",
- "CreateExternalTicket",
- "ManualTaskTimer",
- "UpdateDBStatusToTimeout",
- "ThrowTimeoutError");
- }
-
- @Test
- public void sunnyDayPauseForManualTaskCompleted_Test() throws InterruptedException {
- variables.put("taskTimeout", TIMEOUT_10_S);
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("PauseForManualTaskActivity", variables);
- assertThat(pi).isNotNull();
- BpmnAwareAssertions.assertThat(pi).isWaitingAt("ManualUserTask");
- assertThat(pi).task().isNotNull();
- Task task = taskService.createTaskQuery().active().list().get(0);
- assertNotNull(task);
- taskService.complete(task.getId());
-
- assertThat(pi).isStarted().hasPassedInOrder("PauseForManualTaskActivity_Start",
- "UpdateDbStatusToPendingManualTask",
- "CreateExternalTicket",
- "ManualUserTask",
- "UpdateDbStatusToInProgress",
- "PauseForManualTaskActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayPauseForManualTask_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(manualHandlingTasks).createExternalTicket((any(DelegateExecution.class)));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("PauseForManualTaskActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("PauseForManualTaskActivity_Start",
- "UpdateDbStatusToPendingManualTask",
- "CreateExternalTicket").hasNotPassed(
- "ManualUserTask",
- "UpdateDbStatusToInProgress",
- "PauseForManualTaskActivity_End");
- }
-
+public class PauseForManualTaskActivityTest extends BaseBPMNTest {
+ private static final String TIMEOUT_10_S = "PT10S";
+
+ @Autowired
+ protected ManagementService managementService;
+
+ @Autowired
+ protected TaskService taskService;
+
+ @Test
+ public void sunnyDayPauseForManualTaskTimeout_Test() throws InterruptedException {
+ variables.put("taskTimeout", TIMEOUT_10_S);
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("PauseForManualTaskActivity", variables);
+ assertThat(pi).isNotNull();
+ BpmnAwareAssertions.assertThat(pi).isWaitingAt("ManualUserTask");
+ Task task = taskService.createTaskQuery().active().list().get(0);
+ assertThat(pi).task().isNotNull();
+ assertNotNull(task);
+
+ Job job = managementService.createJobQuery().activityId("ManualTaskTimer").singleResult();
+ assertNotNull(job);
+ managementService.executeJob(job.getId());
+
+ assertThat(pi).isStarted().hasPassedInOrder("PauseForManualTaskActivity_Start",
+ "UpdateDbStatusToPendingManualTask", "CreateExternalTicket", "ManualTaskTimer",
+ "UpdateDBStatusToTimeout", "ThrowTimeoutError");
+ }
+
+ @Test
+ public void sunnyDayPauseForManualTaskCompleted_Test() throws InterruptedException {
+ variables.put("taskTimeout", TIMEOUT_10_S);
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("PauseForManualTaskActivity", variables);
+ assertThat(pi).isNotNull();
+ BpmnAwareAssertions.assertThat(pi).isWaitingAt("ManualUserTask");
+ assertThat(pi).task().isNotNull();
+ Task task = taskService.createTaskQuery().active().list().get(0);
+ assertNotNull(task);
+ taskService.complete(task.getId());
+
+ assertThat(pi).isStarted().hasPassedInOrder("PauseForManualTaskActivity_Start",
+ "UpdateDbStatusToPendingManualTask", "CreateExternalTicket", "ManualUserTask",
+ "UpdateDbStatusToInProgress", "PauseForManualTaskActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayPauseForManualTask_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(manualHandlingTasks)
+ .createExternalTicket((any(DelegateExecution.class)));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("PauseForManualTaskActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("PauseForManualTaskActivity_Start", "UpdateDbStatusToPendingManualTask",
+ "CreateExternalTicket")
+ .hasNotPassed("ManualUserTask", "UpdateDbStatusToInProgress", "PauseForManualTaskActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/SDNCHandlerTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/SDNCHandlerTest.java
index ad9f97f951..199ada5909 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/SDNCHandlerTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/SDNCHandlerTest.java
@@ -22,13 +22,11 @@ package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
import static org.mockito.Mockito.doReturn;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
-
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.sdnc.northbound.client.model.GenericResourceApiServiceOperationInformation;
@@ -37,41 +35,45 @@ import org.onap.so.client.exception.BadResponseException;
import org.onap.so.client.exception.MapperException;
import org.onap.so.client.sdnc.beans.SDNCRequest;
import org.onap.so.client.sdnc.endpoint.SDNCTopology;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class SDNCHandlerTest extends BaseBPMNTest{
- @Test
- public void sunnyDay_SDNCHandler_Sync_Final_Test() throws InterruptedException, MapperException, BadResponseException, IOException {
- final String sdncResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/SDNCClientPut200Response.json")));
- doReturn(sdncResponse).when(sdncClient).post(createSDNCRequest().getSDNCPayload(),SDNCTopology.CONFIGURATION);
- Map<String, Object> startVariables = new HashMap<>();
- startVariables.put("SDNCRequest", createSDNCRequest());
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("SDNCHandler", startVariables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("SDNC_Start","SNDC_SetupCallback","Call_SDNC","isAsync_Gateway","SDNC_End").isEnded();
- }
+public class SDNCHandlerTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDay_SDNCHandler_Sync_Final_Test()
+ throws InterruptedException, MapperException, BadResponseException, IOException {
+ final String sdncResponse =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/SDNCClientPut200Response.json")));
+ doReturn(sdncResponse).when(sdncClient).post(createSDNCRequest().getSDNCPayload(), SDNCTopology.CONFIGURATION);
+ Map<String, Object> startVariables = new HashMap<>();
+ startVariables.put("SDNCRequest", createSDNCRequest());
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("SDNCHandler", startVariables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("SDNC_Start", "SNDC_SetupCallback", "Call_SDNC", "isAsync_Gateway", "SDNC_End")
+ .isEnded();
+ }
- public SDNCRequest createSDNCRequest(){
- SDNCRequest request = new SDNCRequest();
- request.setCorrelationName("correlationName");
- request.setCorrelationValue("correlationValue");
- request.setTopology(SDNCTopology.CONFIGURATION);
- ObjectMapper mapper = new ObjectMapper();
- try {
- GenericResourceApiServiceOperationInformation sdncReq =
- mapper.readValue(Files.readAllBytes(Paths.get("src/test/resources/SDNC_Client_Request.json")), GenericResourceApiServiceOperationInformation.class);
- request.setSDNCPayload(sdncReq);
- } catch (JsonParseException e) {
+ public SDNCRequest createSDNCRequest() {
+ SDNCRequest request = new SDNCRequest();
+ request.setCorrelationName("correlationName");
+ request.setCorrelationValue("correlationValue");
+ request.setTopology(SDNCTopology.CONFIGURATION);
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ GenericResourceApiServiceOperationInformation sdncReq =
+ mapper.readValue(Files.readAllBytes(Paths.get("src/test/resources/SDNC_Client_Request.json")),
+ GenericResourceApiServiceOperationInformation.class);
+ request.setSDNCPayload(sdncReq);
+ } catch (JsonParseException e) {
- } catch (JsonMappingException e) {
+ } catch (JsonMappingException e) {
- } catch (IOException e) {
+ } catch (IOException e) {
- }
+ }
- return request;
- }
+ return request;
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignNetworkBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignNetworkBBTest.java
index b65f30fa9a..c20a56af66 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignNetworkBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignNetworkBBTest.java
@@ -19,36 +19,38 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class UnassignNetworkBBTest extends BaseBPMNTest {
+public class UnassignNetworkBBTest extends BaseBPMNTest {
@Test
public void sunnyDayAssignNetwork_Test() throws InterruptedException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignNetworkBB",variables);
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignNetworkBB", variables);
assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_UnassignNetworkBB","Task_VfModuleRelatioship","Task_GetCloudRegionVersion","Task_SNDCUnAssign","CallActivity_sdncHandlerCall","Task_DeleteNetwork","End_UnassignNetworkBB");
+ assertThat(pi).isStarted().hasPassedInOrder("Start_UnassignNetworkBB", "Task_VfModuleRelatioship",
+ "Task_GetCloudRegionVersion", "Task_SNDCUnAssign", "CallActivity_sdncHandlerCall", "Task_DeleteNetwork",
+ "End_UnassignNetworkBB");
assertThat(pi).isEnded();
}
- @Test
- public void rainyDayAssignNetwork_Test() throws Exception {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(unassignNetworkBB).checkRelationshipRelatedTo(any(BuildingBlockExecution.class), eq("vf-module"));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignNetworkBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("Start_UnassignNetworkBB", "Task_VfModuleRelatioship")
- .hasNotPassed("End_UnassignNetworkBB");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayAssignNetwork_Test() throws Exception {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(unassignNetworkBB)
+ .checkRelationshipRelatedTo(any(BuildingBlockExecution.class), eq("vf-module"));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignNetworkBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_UnassignNetworkBB", "Task_VfModuleRelatioship")
+ .hasNotPassed("End_UnassignNetworkBB");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignServiceInstanceBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignServiceInstanceBBTest.java
index 854c4f9c2e..3b503618f1 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignServiceInstanceBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignServiceInstanceBBTest.java
@@ -19,8 +19,8 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
-import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
+import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import org.camunda.bpm.engine.impl.pvm.runtime.ExecutionImpl;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -28,15 +28,17 @@ import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.common.DelegateExecutionImpl;
-public class UnassignServiceInstanceBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDayUnassignServiceInstanceSDNC() throws InterruptedException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- BuildingBlockExecution bbe = new DelegateExecutionImpl(new ExecutionImpl());
- variables.put("gBuildingBlockExecution", bbe);
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignServiceInstanceBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("Start_UnassignServiceInstanceBB", "Task_SdncUnassignServiceInstance", "CallActivity_sdncHandlerCall", "Task_AAIDeleteServiceInstance", "End_UnassignServiceInstanceBB");
- assertThat(pi).isEnded();
- }
+public class UnassignServiceInstanceBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayUnassignServiceInstanceSDNC() throws InterruptedException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ BuildingBlockExecution bbe = new DelegateExecutionImpl(new ExecutionImpl());
+ variables.put("gBuildingBlockExecution", bbe);
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignServiceInstanceBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("Start_UnassignServiceInstanceBB",
+ "Task_SdncUnassignServiceInstance", "CallActivity_sdncHandlerCall", "Task_AAIDeleteServiceInstance",
+ "End_UnassignServiceInstanceBB");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVfModuleBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVfModuleBBTest.java
index 89089770b1..e6fae0b005 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVfModuleBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVfModuleBBTest.java
@@ -19,50 +19,47 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class UnassignVfModuleBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDayUnassignVfModule_Test() throws InterruptedException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("UnassignVfModuleBB_Start",
- "UnassignVfModule",
- "CallActivity_sdncHandler",
- "DeleteVfModule",
- "UnassignVfModuleBB_End");
- assertThat(pi).isEnded();
- }
+public class UnassignVfModuleBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayUnassignVfModule_Test() throws InterruptedException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("UnassignVfModuleBB_Start", "UnassignVfModule",
+ "CallActivity_sdncHandler", "DeleteVfModule", "UnassignVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayUnassignVfModuleAAIDeleteFailed_Test() throws Exception {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiDeleteTasks)
+ .deleteVfModule(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("UnassignVfModuleBB_Start", "UnassignVfModule", "DeleteVfModule")
+ .hasNotPassed("UnassignVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
- @Test
- public void rainyDayUnassignVfModuleAAIDeleteFailed_Test() throws Exception {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiDeleteTasks).deleteVfModule(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("UnassignVfModuleBB_Start", "UnassignVfModule", "DeleteVfModule")
- .hasNotPassed("UnassignVfModuleBB_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayUnassignVfModuleSDNCUnassignFailed_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncUnassignTasks).unassignVfModule(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVfModuleBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("UnassignVfModuleBB_Start", "UnassignVfModule")
- .hasNotPassed("DeleteVfModule", "UnassignVfModuleBB_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void rainyDayUnassignVfModuleSDNCUnassignFailed_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncUnassignTasks)
+ .unassignVfModule(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVfModuleBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("UnassignVfModuleBB_Start", "UnassignVfModule")
+ .hasNotPassed("DeleteVfModule", "UnassignVfModuleBB_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVnfBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVnfBBTest.java
index d508f4fcd7..2a6435218d 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVnfBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVnfBBTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Ignore;
@@ -30,49 +30,48 @@ import org.junit.Test;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
-public class UnassignVnfBBTest extends BaseBPMNTest{
- @Test
- public void sunnyDayUnassignVnf_Test() throws InterruptedException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVnfBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("UnassignVnfBB_Start",
- "UnassignVnf",
- "CallActivity_sdncHandlerCall",
- "DeleteVnfInstanceGroups",
- "DeleteVnf",
- "UnassignVnfBB_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- @Ignore
- public void rainyDayUnassignVnfInstanceGroupsDeleteFailed_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(unassignVnf).deleteInstanceGroups(any(BuildingBlockExecution.class)); //.deleteVnf(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVnfBB", variables);
- assertThat(pi).isNotNull().isStarted()
- .hasPassedInOrder("UnassignVnfBB_Start", "UnassignVnf", "DeleteVnfInstanceGroups")
- .hasNotPassed("DeleteVnf","UnassignVnfBB_End");
-
- }
-
- @Test
- public void rainyDayUnassignVnfAAIDeleteFailed_Test() throws Exception {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiDeleteTasks).deleteVnf(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVnfBB", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("UnassignVnfBB_Start", "UnassignVnf", "DeleteVnfInstanceGroups","DeleteVnf")
- .hasNotPassed("UnassignVnfBB_End");
- }
-
- @Test
- public void rainyDayUnassignVnfSDNCUnassignFailed_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncUnassignTasks).unassignVnf(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVnfBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("UnassignVnfBB_Start", "UnassignVnf")
- .hasNotPassed("DeleteVnfInstanceGroups","DeleteVnf", "UnassignVnfBB_End");
- assertThat(pi).isEnded();
- }
+public class UnassignVnfBBTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayUnassignVnf_Test() throws InterruptedException {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVnfBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("UnassignVnfBB_Start", "UnassignVnf",
+ "CallActivity_sdncHandlerCall", "DeleteVnfInstanceGroups", "DeleteVnf", "UnassignVnfBB_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ @Ignore
+ public void rainyDayUnassignVnfInstanceGroupsDeleteFailed_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(unassignVnf)
+ .deleteInstanceGroups(any(BuildingBlockExecution.class)); // .deleteVnf(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVnfBB", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("UnassignVnfBB_Start", "UnassignVnf", "DeleteVnfInstanceGroups")
+ .hasNotPassed("DeleteVnf", "UnassignVnfBB_End");
+
+ }
+
+ @Test
+ public void rainyDayUnassignVnfAAIDeleteFailed_Test() throws Exception {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiDeleteTasks)
+ .deleteVnf(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVnfBB", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("UnassignVnfBB_Start", "UnassignVnf", "DeleteVnfInstanceGroups", "DeleteVnf")
+ .hasNotPassed("UnassignVnfBB_End");
+ }
+
+ @Test
+ public void rainyDayUnassignVnfSDNCUnassignFailed_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(sdncUnassignTasks)
+ .unassignVnf(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVnfBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("UnassignVnfBB_Start", "UnassignVnf")
+ .hasNotPassed("DeleteVnfInstanceGroups", "DeleteVnf", "UnassignVnfBB_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVolumeGroupBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVolumeGroupBBTest.java
index 6b176293fe..1cc0788613 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVolumeGroupBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UnassignVolumeGroupBBTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,23 +30,24 @@ import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
public class UnassignVolumeGroupBBTest extends BaseBPMNTest {
- @Test
- public void sunnyDayUnassignVolumeGroup_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("UnassignVolumeGroupBB_Start", "UnassignVolumeGroup", "UnassignVolumeGroupBB_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayUnassignVolumeGroup_Test() throws InterruptedException {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiDeleteTasks).deleteVolumeGroup(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVolumeGroupBB", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted()
- .hasPassedInOrder("UnassignVolumeGroupBB_Start", "UnassignVolumeGroup")
- .hasNotPassed("UnassignVolumeGroupBB_End");
- assertThat(pi).isEnded();
- }
+ @Test
+ public void sunnyDayUnassignVolumeGroup_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("UnassignVolumeGroupBB_Start", "UnassignVolumeGroup",
+ "UnassignVolumeGroupBB_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayUnassignVolumeGroup_Test() throws InterruptedException {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiDeleteTasks)
+ .deleteVolumeGroup(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("UnassignVolumeGroupBB", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("UnassignVolumeGroupBB_Start", "UnassignVolumeGroup")
+ .hasNotPassed("UnassignVolumeGroupBB_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UpdateNetworkBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UpdateNetworkBBTest.java
index 1bb065ae06..d9194587c6 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UpdateNetworkBBTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/UpdateNetworkBBTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -33,27 +33,28 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
public class UpdateNetworkBBTest extends BaseBPMNTest {
@Test
public void updateNetworkBBTest() throws InterruptedException {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("UpdateNetworkBB", variables);
- assertThat(processInstance).isNotNull();
- assertThat(processInstance).isStarted().hasPassedInOrder(
- "UpdateNetworkBB_Start", "SDNCChangeAssignNetwork", "CallActivity_sdncHandlerCallChangeAssign",
- "QueryVpnBindingAAI", "QueryNetworkPolicyAAI", "QueryNetworkTableRefAAI",
- "Create_Network_ServiceTask", "CallActivity_NetworkAdapterRestV1", "ServiceTask_ProcessResponse", "Update_Network_AAI_ServiceTask", "UpdateNetworkBB_End");
- assertThat(processInstance).isEnded();
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("UpdateNetworkBB", variables);
+ assertThat(processInstance).isNotNull();
+ assertThat(processInstance).isStarted().hasPassedInOrder("UpdateNetworkBB_Start", "SDNCChangeAssignNetwork",
+ "CallActivity_sdncHandlerCallChangeAssign", "QueryVpnBindingAAI", "QueryNetworkPolicyAAI",
+ "QueryNetworkTableRefAAI", "Create_Network_ServiceTask", "CallActivity_NetworkAdapterRestV1",
+ "ServiceTask_ProcessResponse", "Update_Network_AAI_ServiceTask", "UpdateNetworkBB_End");
+ assertThat(processInstance).isEnded();
}
- @Test
- public void updateNetworkBBExceptionTest() throws Exception {
- mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiQueryTasks).queryNetworkVpnBinding(any(BuildingBlockExecution.class));
-
- ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("UpdateNetworkBB", variables);
- assertThat(processInstance).isStarted().hasPassedInOrder(
- "UpdateNetworkBB_Start", "SDNCChangeAssignNetwork", "CallActivity_sdncHandlerCallChangeAssign",
- "QueryVpnBindingAAI")
- .hasNotPassed("QueryNetworkPolicyAAI", "QueryNetworkTableRefAAI",
- "UpdateNetworkAdapter", "UpdateNetworkAAI", "UpdateNetworkBB_End");
- assertThat(processInstance).isEnded();
- }
+ @Test
+ public void updateNetworkBBExceptionTest() throws Exception {
+ mockSubprocess("SDNCHandler", "My Mock Process Name", "GenericStub");
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiQueryTasks)
+ .queryNetworkVpnBinding(any(BuildingBlockExecution.class));
+
+ ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("UpdateNetworkBB", variables);
+ assertThat(processInstance).isStarted()
+ .hasPassedInOrder("UpdateNetworkBB_Start", "SDNCChangeAssignNetwork",
+ "CallActivity_sdncHandlerCallChangeAssign", "QueryVpnBindingAAI")
+ .hasNotPassed("QueryNetworkPolicyAAI", "QueryNetworkTableRefAAI", "UpdateNetworkAdapter",
+ "UpdateNetworkAAI", "UpdateNetworkBB_End");
+ assertThat(processInstance).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckClosedLoopDisabledFlagActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckClosedLoopDisabledFlagActivityTest.java
index ac4499bf89..55d21471fc 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckClosedLoopDisabledFlagActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckClosedLoopDisabledFlagActivityTest.java
@@ -19,37 +19,39 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
-public class VNFCheckClosedLoopDisabledFlagActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFCheckClosedLoopDisabledFlagActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFCheckClosedLoopDisabledFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFCheckClosedLoopDisabledFlagActivity_Start",
- "TaskCheckClosedLoopDisabledFlagActivity",
- "VNFCheckClosedLoopDisabledFlagActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFCheckClosedLoopDisabledFlagActivity_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
- .checkVnfClosedLoopDisabledFlag(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFCheckClosedLoopDisabledFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFCheckClosedLoopDisabledFlagActivity_Start",
- "TaskCheckClosedLoopDisabledFlagActivity").hasNotPassed(
- "VNFCheckClosedLoopDisabledFlagActivity_End");
- assertThat(pi).isEnded();
- }
-
+public class VNFCheckClosedLoopDisabledFlagActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFCheckClosedLoopDisabledFlagActivity_Test() throws InterruptedException {
+ ProcessInstance pi =
+ runtimeService.startProcessInstanceByKey("VNFCheckClosedLoopDisabledFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFCheckClosedLoopDisabledFlagActivity_Start",
+ "TaskCheckClosedLoopDisabledFlagActivity", "VNFCheckClosedLoopDisabledFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFCheckClosedLoopDisabledFlagActivity_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
+ .checkVnfClosedLoopDisabledFlag(any(BuildingBlockExecution.class));
+ ProcessInstance pi =
+ runtimeService.startProcessInstanceByKey("VNFCheckClosedLoopDisabledFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("VNFCheckClosedLoopDisabledFlagActivity_Start",
+ "TaskCheckClosedLoopDisabledFlagActivity")
+ .hasNotPassed("VNFCheckClosedLoopDisabledFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckInMaintFlagActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckInMaintFlagActivityTest.java
index 050d3124f6..6f66df6c0d 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckInMaintFlagActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckInMaintFlagActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,27 +30,25 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
-public class VNFCheckInMaintFlagActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFCheckInMaintFlagActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFCheckInMaintFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFCheckInMaintFlagActivity_Start",
- "TaskCheckInMaintFlag",
- "VNFCheckInMaintFlagActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFCheckInMaintFlagActivity_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
- .checkVnfInMaintFlag(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFCheckInMaintFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFCheckInMaintFlagActivity_Start",
- "TaskCheckInMaintFlag").hasNotPassed(
- "VNFCheckInMaintFlagActivity_End");
- assertThat(pi).isEnded();
- }
-
+public class VNFCheckInMaintFlagActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFCheckInMaintFlagActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFCheckInMaintFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFCheckInMaintFlagActivity_Start", "TaskCheckInMaintFlag",
+ "VNFCheckInMaintFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFCheckInMaintFlagActivity_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
+ .checkVnfInMaintFlag(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFCheckInMaintFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFCheckInMaintFlagActivity_Start", "TaskCheckInMaintFlag")
+ .hasNotPassed("VNFCheckInMaintFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckPserversLockedFlagActivity.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckPserversLockedFlagActivity.java
index e43f47fa6a..8bfe6c020f 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckPserversLockedFlagActivity.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFCheckPserversLockedFlagActivity.java
@@ -19,37 +19,36 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
-public class VNFCheckPserversLockedFlagActivity extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFCheckInMaintFlagActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFCheckPserversLockedFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFCheckPserversLockedFlagActivity_Start",
- "TaskCheckPserversLockedFlagActivity",
- "VNFCheckPserversLockedFlagActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFCheckPserversLockedFlagActivity_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
- .checkVnfPserversLockedFlag(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFCheckPserversLockedFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFCheckPserversLockedFlagActivity_Start",
- "TaskCheckPserversLockedFlagActivity").hasNotPassed(
- "VNFCheckPserversLockedFlagActivity_End");
- assertThat(pi).isEnded();
- }
-
+public class VNFCheckPserversLockedFlagActivity extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFCheckInMaintFlagActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFCheckPserversLockedFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFCheckPserversLockedFlagActivity_Start",
+ "TaskCheckPserversLockedFlagActivity", "VNFCheckPserversLockedFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFCheckPserversLockedFlagActivity_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
+ .checkVnfPserversLockedFlag(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFCheckPserversLockedFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("VNFCheckPserversLockedFlagActivity_Start", "TaskCheckPserversLockedFlagActivity")
+ .hasNotPassed("VNFCheckPserversLockedFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFHealthCheckActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFHealthCheckActivityTest.java
index 8e76f8f4d1..0b17e3e099 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFHealthCheckActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFHealthCheckActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,28 +30,25 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class VNFHealthCheckActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFHealthCheckActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFHealthCheckActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFHealthCheckActivity_Start",
- "TaskPreProcessActivity",
- "TaskHealthCheck",
- "VNFHealthCheckActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFHealthCheckActivity_Test() throws Exception {
- variables.put("actionHealthCheck", Action.HealthCheck);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFHealthCheckActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFHealthCheckActivity_Start",
- "TaskPreProcessActivity",
- "TaskHealthCheck").hasNotPassed(
- "VNFHealthCheckActivity_End");
- }
-
+public class VNFHealthCheckActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFHealthCheckActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFHealthCheckActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFHealthCheckActivity_Start", "TaskPreProcessActivity",
+ "TaskHealthCheck", "VNFHealthCheckActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFHealthCheckActivity_Test() throws Exception {
+ variables.put("actionHealthCheck", Action.HealthCheck);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFHealthCheckActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("VNFHealthCheckActivity_Start", "TaskPreProcessActivity", "TaskHealthCheck")
+ .hasNotPassed("VNFHealthCheckActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFLockActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFLockActivityTest.java
index f36a72fc01..45cf44848f 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFLockActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFLockActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,28 +30,25 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class VNFLockActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFLockActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFLockActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFLockActivity_Start",
- "TaskPreProcessActivity",
- "TaskLock",
- "VNFLockActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFLockActivity_Test() throws Exception {
- variables.put("actionLock", Action.Lock);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFLockActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFLockActivity_Start",
- "TaskPreProcessActivity",
- "TaskLock").hasNotPassed(
- "VNFLockActivity_End");
- }
-
+public class VNFLockActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFLockActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFLockActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFLockActivity_Start", "TaskPreProcessActivity", "TaskLock",
+ "VNFLockActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFLockActivity_Test() throws Exception {
+ variables.put("actionLock", Action.Lock);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFLockActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("VNFLockActivity_Start", "TaskPreProcessActivity", "TaskLock")
+ .hasNotPassed("VNFLockActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFQuiesceTrafficActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFQuiesceTrafficActivityTest.java
index 2d9b952509..fb462bc02f 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFQuiesceTrafficActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFQuiesceTrafficActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,28 +30,25 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class VNFQuiesceTrafficActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFQuiesceTrafficActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFQuiesceTrafficActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFQuiesceTrafficActivity_Start",
- "TaskPreProcessActivity",
- "TaskQuiesceTraffic",
- "VNFQuiesceTrafficActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFQuiesceTrafficActivity_Test() throws Exception {
- variables.put("actionQuiesceTraffic", Action.QuiesceTraffic);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFQuiesceTrafficActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFQuiesceTrafficActivity_Start",
- "TaskPreProcessActivity",
- "TaskQuiesceTraffic").hasNotPassed(
- "VNFQuiesceTrafficActivity_End");
- }
-
+public class VNFQuiesceTrafficActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFQuiesceTrafficActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFQuiesceTrafficActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFQuiesceTrafficActivity_Start", "TaskPreProcessActivity",
+ "TaskQuiesceTraffic", "VNFQuiesceTrafficActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFQuiesceTrafficActivity_Test() throws Exception {
+ variables.put("actionQuiesceTraffic", Action.QuiesceTraffic);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFQuiesceTrafficActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("VNFQuiesceTrafficActivity_Start", "TaskPreProcessActivity", "TaskQuiesceTraffic")
+ .hasNotPassed("VNFQuiesceTrafficActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFResumeTrafficActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFResumeTrafficActivityTest.java
index d541cdf834..61d88a5770 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFResumeTrafficActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFResumeTrafficActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,29 +30,26 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class VNFResumeTrafficActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFResumeTrafficActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFResumeTrafficActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFResumeTrafficActivity_Start",
- "TaskPreProcessActivity",
- "TaskResumeTraffic",
- "VNFResumeTrafficActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFResumeTrafficActivity_Test() throws Exception {
- variables.put("actionResumeTraffic", Action.ResumeTraffic);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFResumeTrafficActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFResumeTrafficActivity_Start",
- "TaskPreProcessActivity",
- "TaskResumeTraffic").hasNotPassed(
- "VNFResumeTrafficActivity_End");
-
- }
-
+public class VNFResumeTrafficActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFResumeTrafficActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFResumeTrafficActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFResumeTrafficActivity_Start", "TaskPreProcessActivity",
+ "TaskResumeTraffic", "VNFResumeTrafficActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFResumeTrafficActivity_Test() throws Exception {
+ variables.put("actionResumeTraffic", Action.ResumeTraffic);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFResumeTrafficActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("VNFResumeTrafficActivity_Start", "TaskPreProcessActivity", "TaskResumeTraffic")
+ .hasNotPassed("VNFResumeTrafficActivity_End");
+
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSetClosedLoopDisabledFlagActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSetClosedLoopDisabledFlagActivityTest.java
index 8e56051f47..001dc70b54 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSetClosedLoopDisabledFlagActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSetClosedLoopDisabledFlagActivityTest.java
@@ -19,37 +19,38 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
-public class VNFSetClosedLoopDisabledFlagActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFSetClosedLoopDisabledFlagActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFSetClosedLoopDisabledFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFSetClosedLoopDisabledFlagActivity_Start",
- "TaskSetClosedLoopDisabledFlagActivity",
- "VNFSetClosedLoopDisabledFlagActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFSetClosedLoopDisabledFlagActivity_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
- .modifyVnfClosedLoopDisabledFlag(any(BuildingBlockExecution.class), any(boolean.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFSetClosedLoopDisabledFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFSetClosedLoopDisabledFlagActivity_Start",
- "TaskSetClosedLoopDisabledFlagActivity").hasNotPassed(
- "VNFSetInMaintFlagActivity_End");
- assertThat(pi).isEnded();
- }
+public class VNFSetClosedLoopDisabledFlagActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFSetClosedLoopDisabledFlagActivity_Test() throws InterruptedException {
+ ProcessInstance pi =
+ runtimeService.startProcessInstanceByKey("VNFSetClosedLoopDisabledFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFSetClosedLoopDisabledFlagActivity_Start",
+ "TaskSetClosedLoopDisabledFlagActivity", "VNFSetClosedLoopDisabledFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFSetClosedLoopDisabledFlagActivity_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
+ .modifyVnfClosedLoopDisabledFlag(any(BuildingBlockExecution.class), any(boolean.class));
+ ProcessInstance pi =
+ runtimeService.startProcessInstanceByKey("VNFSetClosedLoopDisabledFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("VNFSetClosedLoopDisabledFlagActivity_Start", "TaskSetClosedLoopDisabledFlagActivity")
+ .hasNotPassed("VNFSetInMaintFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSetInMaintFlagActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSetInMaintFlagActivityTest.java
index 2dc6420688..1df0ea2e65 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSetInMaintFlagActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSetInMaintFlagActivityTest.java
@@ -19,37 +19,35 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
-public class VNFSetInMaintFlagActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFSetInMaintFlagActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFSetInMaintFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFSetInMaintFlagActivity_Start",
- "TaskSetInMaint",
- "VNFSetInMaintFlagActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFSetInMaintFlagActivity_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
- .modifyVnfInMaintFlag(any(BuildingBlockExecution.class), any(boolean.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFSetInMaintFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFSetInMaintFlagActivity_Start",
- "TaskSetInMaint").hasNotPassed(
- "VNFSetInMaintFlagActivity_End");
- assertThat(pi).isEnded();
- }
-
+public class VNFSetInMaintFlagActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFSetInMaintFlagActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFSetInMaintFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFSetInMaintFlagActivity_Start", "TaskSetInMaint",
+ "VNFSetInMaintFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFSetInMaintFlagActivity_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
+ .modifyVnfInMaintFlag(any(BuildingBlockExecution.class), any(boolean.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFSetInMaintFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFSetInMaintFlagActivity_Start", "TaskSetInMaint")
+ .hasNotPassed("VNFSetInMaintFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSnapShotActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSnapShotActivityTest.java
index f6bfd04d03..6f1e076c02 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSnapShotActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFSnapShotActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,28 +30,25 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class VNFSnapShotActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFSnapShotActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFSnapShotActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFSnapShotActivity_Start",
- "TaskPreProcessActivity",
- "TaskSnapShot",
- "VNFSnapShotActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFSnapShotActivity_Test() throws Exception {
- variables.put("actionSnapshot", Action.Snapshot);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFSnapShotActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFSnapShotActivity_Start",
- "TaskPreProcessActivity",
- "TaskSnapShot").hasNotPassed(
- "VNFSnapShotActivity_End");
- }
-
+public class VNFSnapShotActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFSnapShotActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFSnapShotActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFSnapShotActivity_Start", "TaskPreProcessActivity",
+ "TaskSnapShot", "VNFSnapShotActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFSnapShotActivity_Test() throws Exception {
+ variables.put("actionSnapshot", Action.Snapshot);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFSnapShotActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("VNFSnapShotActivity_Start", "TaskPreProcessActivity", "TaskSnapShot")
+ .hasNotPassed("VNFSnapShotActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStartActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStartActivityTest.java
index 6e4be69a91..a8e974d63a 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStartActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStartActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,28 +30,25 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class VNFStartActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFStartActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFStartActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFStartActivity_Start",
- "TaskPreProcessActivity",
- "TaskStart",
- "VNFStartActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFStartActivity_Test() throws Exception {
- variables.put("actionStart", Action.Start);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFStartActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFStartActivity_Start",
- "TaskPreProcessActivity",
- "TaskStart").hasNotPassed(
- "VNFStartActivity_End");
- }
-
+public class VNFStartActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFStartActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFStartActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFStartActivity_Start", "TaskPreProcessActivity", "TaskStart",
+ "VNFStartActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFStartActivity_Test() throws Exception {
+ variables.put("actionStart", Action.Start);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFStartActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("VNFStartActivity_Start", "TaskPreProcessActivity", "TaskStart")
+ .hasNotPassed("VNFStartActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStopActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStopActivityTest.java
index 3bc5940493..58dfff8bd7 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStopActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStopActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,28 +30,25 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class VNFStopActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFStopActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFStopActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFStopActivity_Start",
- "TaskPreProcessActivity",
- "TaskStop",
- "VNFStopActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFStopActivity_Test() throws Exception {
- variables.put("actionStop", Action.Stop);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFStopActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFStopActivity_Start",
- "TaskPreProcessActivity",
- "TaskStop").hasNotPassed(
- "VNFStopActivity_End");
- }
-
+public class VNFStopActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFStopActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFStopActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFStopActivity_Start", "TaskPreProcessActivity", "TaskStop",
+ "VNFStopActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFStopActivity_Test() throws Exception {
+ variables.put("actionStop", Action.Stop);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFStopActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("VNFStopActivity_Start", "TaskPreProcessActivity", "TaskStop")
+ .hasNotPassed("VNFStopActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnlockActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnlockActivityTest.java
index d0db70b2aa..b6faf1b806 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnlockActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnlockActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,28 +30,25 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class VNFUnlockActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFUnlockActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUnlockActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFUnlockActivity_Start",
- "TaskPreProcessActivity",
- "TaskUnlock",
- "VNFUnlockActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFUnlockActivity_Test() throws Exception {
- variables.put("actionUnlock", Action.Unlock);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUnlockActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFUnlockActivity_Start",
- "TaskPreProcessActivity",
- "TaskUnlock").hasNotPassed(
- "VNFUnlockActivity_End");
- }
-
+public class VNFUnlockActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFUnlockActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUnlockActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFUnlockActivity_Start", "TaskPreProcessActivity", "TaskUnlock",
+ "VNFUnlockActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFUnlockActivity_Test() throws Exception {
+ variables.put("actionUnlock", Action.Unlock);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUnlockActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("VNFUnlockActivity_Start", "TaskPreProcessActivity", "TaskUnlock")
+ .hasNotPassed("VNFUnlockActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnsetClosedLoopDisabledFlagActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnsetClosedLoopDisabledFlagActivityTest.java
index 4c9b33c2c7..035d124402 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnsetClosedLoopDisabledFlagActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnsetClosedLoopDisabledFlagActivityTest.java
@@ -19,36 +19,38 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
-public class VNFUnsetClosedLoopDisabledFlagActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFUnsetClosedLoopDisabledFlagActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUnsetInClosedLoopDisabledFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFUnsetClosedLoopDisabledFlagActivity_Start",
- "TaskVNFUnsetClosedLoopDisabledFlagActivity",
- "VNFUnsetClosedLoopDisabledFlagActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFUnsetClosedLoopFlag_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
- .modifyVnfClosedLoopDisabledFlag(any(BuildingBlockExecution.class), any(boolean.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUnsetInClosedLoopDisabledFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFUnsetClosedLoopDisabledFlagActivity_Start",
- "TaskVNFUnsetClosedLoopDisabledFlagActivity").hasNotPassed(
- "VNFUnsetClosedLoopDisabledFlagActivity_End");
- assertThat(pi).isEnded();
- }
+public class VNFUnsetClosedLoopDisabledFlagActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFUnsetClosedLoopDisabledFlagActivity_Test() throws InterruptedException {
+ ProcessInstance pi =
+ runtimeService.startProcessInstanceByKey("VNFUnsetInClosedLoopDisabledFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFUnsetClosedLoopDisabledFlagActivity_Start",
+ "TaskVNFUnsetClosedLoopDisabledFlagActivity", "VNFUnsetClosedLoopDisabledFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFUnsetClosedLoopFlag_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
+ .modifyVnfClosedLoopDisabledFlag(any(BuildingBlockExecution.class), any(boolean.class));
+ ProcessInstance pi =
+ runtimeService.startProcessInstanceByKey("VNFUnsetInClosedLoopDisabledFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("VNFUnsetClosedLoopDisabledFlagActivity_Start",
+ "TaskVNFUnsetClosedLoopDisabledFlagActivity")
+ .hasNotPassed("VNFUnsetClosedLoopDisabledFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnsetInMaintFlagActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnsetInMaintFlagActivityTest.java
index fcb328fa0b..15623bab3d 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnsetInMaintFlagActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnsetInMaintFlagActivityTest.java
@@ -19,37 +19,35 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
-public class VNFUnsetInMaintFlagActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFUnsetInMaintFlagActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUnsetInMaintFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFUnsetInMaintFlagActivity_Start",
- "TaskUnsetInMaint",
- "VNFUnsetInMaintFlagActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFUnsetInMaintFlag_Test() throws Exception {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
- .modifyVnfInMaintFlag(any(BuildingBlockExecution.class), any(boolean.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUnsetInMaintFlagActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFUnsetInMaintFlagActivity_Start",
- "TaskUnsetInMaint").hasNotPassed(
- "VNFUnsetInMaintFlagActivity_End");
- assertThat(pi).isEnded();
- }
-
+public class VNFUnsetInMaintFlagActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFUnsetInMaintFlagActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUnsetInMaintFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFUnsetInMaintFlagActivity_Start", "TaskUnsetInMaint",
+ "VNFUnsetInMaintFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFUnsetInMaintFlag_Test() throws Exception {
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(aaiFlagTasks)
+ .modifyVnfInMaintFlag(any(BuildingBlockExecution.class), any(boolean.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUnsetInMaintFlagActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFUnsetInMaintFlagActivity_Start", "TaskUnsetInMaint")
+ .hasNotPassed("VNFUnsetInMaintFlagActivity_End");
+ assertThat(pi).isEnded();
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradeBackupActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradeBackupActivityTest.java
index c68196c3bf..4d99147761 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradeBackupActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradeBackupActivityTest.java
@@ -23,7 +23,6 @@ package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -31,30 +30,27 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class VNFUpgradeBackupActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFUpgradeBackupActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradeBackupActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFUpgradeBackupActivity_Start",
- "TaskPreProcessActivity",
- "TaskUpgradeBackup",
- "VNFUpgradeBackupActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFUpgradeBackupActivity_Test() throws Exception {
- variables.put("actionUpgradeBackup", Action.UpgradeBackup);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradeBackupActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFUpgradeBackupActivity_Start",
- "TaskPreProcessActivity",
- "TaskUpgradeBackup").hasNotPassed(
- "VNFUpgradeBackupActivity_End");
- assertThat(pi).isEnded();
- }
-
+public class VNFUpgradeBackupActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFUpgradeBackupActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradeBackupActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFUpgradeBackupActivity_Start", "TaskPreProcessActivity",
+ "TaskUpgradeBackup", "VNFUpgradeBackupActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFUpgradeBackupActivity_Test() throws Exception {
+ variables.put("actionUpgradeBackup", Action.UpgradeBackup);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradeBackupActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted()
+ .hasPassedInOrder("VNFUpgradeBackupActivity_Start", "TaskPreProcessActivity", "TaskUpgradeBackup")
+ .hasNotPassed("VNFUpgradeBackupActivity_End");
+ assertThat(pi).isEnded();
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradePostCheckActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradePostCheckActivityTest.java
index 5fa930712d..c87cc44f29 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradePostCheckActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradePostCheckActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,28 +30,25 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class VNFUpgradePostCheckActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFUpgradePostCheckActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradePostCheckActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFUpgradePostCheckActivity_Start",
- "TaskPreProcessActivity",
- "TaskUpgradePostCheck",
- "VNFUpgradePostCheckActivity_End");
-
- }
-
- @Test
- public void rainyDayVNFUpgradePostCheckActivity_Test() throws Exception {
- variables.put("actionUpgradePostCheck", Action.UpgradePostCheck);
-
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradePostCheckActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFUpgradePostCheckActivity_Start",
- "TaskPreProcessActivity",
- "TaskUpgradePostCheck").hasNotPassed(
- "VNFUpgradePostCheckActivity_End");
- }
-
+public class VNFUpgradePostCheckActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFUpgradePostCheckActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradePostCheckActivity", variables);
+ assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFUpgradePostCheckActivity_Start",
+ "TaskPreProcessActivity", "TaskUpgradePostCheck", "VNFUpgradePostCheckActivity_End");
+
+ }
+
+ @Test
+ public void rainyDayVNFUpgradePostCheckActivity_Test() throws Exception {
+ variables.put("actionUpgradePostCheck", Action.UpgradePostCheck);
+
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradePostCheckActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("VNFUpgradePostCheckActivity_Start", "TaskPreProcessActivity", "TaskUpgradePostCheck")
+ .hasNotPassed("VNFUpgradePostCheckActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradePreCheckActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradePreCheckActivityTest.java
index 40f5df8dae..79fc43396d 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradePreCheckActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradePreCheckActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,28 +30,25 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class VNFUpgradePreCheckActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFUpgradePreCheckActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradePreCheckActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFUpgradePreCheckActivity_Start",
- "TaskPreProcessActivity",
- "TaskUpgradePreCheck",
- "VNFUpgradePreCheckActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFUpgradePreCheckActivity_Test() throws Exception {
- variables.put("actionUpgradePreCheck", Action.UpgradePreCheck);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradePreCheckActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFUpgradePreCheckActivity_Start",
- "TaskPreProcessActivity",
- "TaskUpgradePreCheck").hasNotPassed(
- "VNFUpgradePreCheckActivity_End");
- }
-
+public class VNFUpgradePreCheckActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFUpgradePreCheckActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradePreCheckActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFUpgradePreCheckActivity_Start", "TaskPreProcessActivity",
+ "TaskUpgradePreCheck", "VNFUpgradePreCheckActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFUpgradePreCheckActivity_Test() throws Exception {
+ variables.put("actionUpgradePreCheck", Action.UpgradePreCheck);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradePreCheckActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("VNFUpgradePreCheckActivity_Start", "TaskPreProcessActivity", "TaskUpgradePreCheck")
+ .hasNotPassed("VNFUpgradePreCheckActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradeSoftwareActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradeSoftwareActivityTest.java
index 91e6bf40be..b550185702 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradeSoftwareActivityTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUpgradeSoftwareActivityTest.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -30,28 +30,25 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.BaseBPMNTest;
import org.onap.appc.client.lcm.model.Action;
-public class VNFUpgradeSoftwareActivityTest extends BaseBPMNTest{
- @Test
- public void sunnyDayVNFUpgradeSoftwareActivity_Test() throws InterruptedException {
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradeSoftwareActivity", variables);
- assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VNFUpgradeSoftwareActivity_Start",
- "TaskPreProcessActivity",
- "TaskUpgradeSoftware",
- "VNFUpgradeSoftwareActivity_End");
- assertThat(pi).isEnded();
- }
-
- @Test
- public void rainyDayVNFUpgradeSoftwareActivity_Test() throws Exception {
- variables.put("actionUpgradeSoftware", Action.UpgradeSoftware);
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
- .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradeSoftwareActivity", variables);
- assertThat(pi).isNotNull().isStarted().hasPassedInOrder("VNFUpgradeSoftwareActivity_Start",
- "TaskPreProcessActivity",
- "TaskUpgradeSoftware").hasNotPassed(
- "VNFUpgradeSoftwareActivity_End");
- }
-
+public class VNFUpgradeSoftwareActivityTest extends BaseBPMNTest {
+ @Test
+ public void sunnyDayVNFUpgradeSoftwareActivity_Test() throws InterruptedException {
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradeSoftwareActivity", variables);
+ assertThat(pi).isNotNull();
+ assertThat(pi).isStarted().hasPassedInOrder("VNFUpgradeSoftwareActivity_Start", "TaskPreProcessActivity",
+ "TaskUpgradeSoftware", "VNFUpgradeSoftwareActivity_End");
+ assertThat(pi).isEnded();
+ }
+
+ @Test
+ public void rainyDayVNFUpgradeSoftwareActivity_Test() throws Exception {
+ variables.put("actionUpgradeSoftware", Action.UpgradeSoftware);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(appcRunTasks)
+ .runAppcCommand(any(BuildingBlockExecution.class), any(Action.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VNFUpgradeSoftwareActivity", variables);
+ assertThat(pi).isNotNull().isStarted()
+ .hasPassedInOrder("VNFUpgradeSoftwareActivity_Start", "TaskPreProcessActivity", "TaskUpgradeSoftware")
+ .hasNotPassed("VNFUpgradeSoftwareActivity_End");
+ }
+
}
diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VnfAdapterTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VnfAdapterTest.java
index 39625ac9bf..8ad4e0f07f 100644
--- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VnfAdapterTest.java
+++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VnfAdapterTest.java
@@ -18,10 +18,10 @@
* ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.bpmn.subprocess;
+
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.junit.Test;
@@ -32,19 +32,22 @@ import org.onap.so.bpmn.common.BuildingBlockExecution;
public class VnfAdapterTest extends BaseBPMNTest {
@Test
public void vnfAdapterCreatedTest() {
- mockSubprocess("vnfAdapterRestV1", "Mocked vnfAdapterRestV1", "GenericStub");
+ mockSubprocess("vnfAdapterRestV1", "Mocked vnfAdapterRestV1", "GenericStub");
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VnfAdapter", variables);
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VnfAdapter", variables);
assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VnfAdapter_Start", "PreProcessRequest", "Call_vnfAdapterRestV1","PostProcessResponse", "VnfAdapter_End");
+ assertThat(pi).isStarted().hasPassedInOrder("VnfAdapter_Start", "PreProcessRequest", "Call_vnfAdapterRestV1",
+ "PostProcessResponse", "VnfAdapter_End");
assertThat(pi).isEnded();
}
-
+
@Test
public void vnfAdapterErrorTest() {
- doThrow(new BpmnError("7000", "TESTING ERRORS")).when(vnfAdapterImpl).preProcessVnfAdapter(any(BuildingBlockExecution.class));
- ProcessInstance pi = runtimeService.startProcessInstanceByKey("VnfAdapter", variables);
+ doThrow(new BpmnError("7000", "TESTING ERRORS")).when(vnfAdapterImpl)
+ .preProcessVnfAdapter(any(BuildingBlockExecution.class));
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("VnfAdapter", variables);
assertThat(pi).isNotNull();
- assertThat(pi).isStarted().hasPassedInOrder("VnfAdapter_Start", "PreProcessRequest").hasNotPassed("VnfAdapter_End");
+ assertThat(pi).isStarted().hasPassedInOrder("VnfAdapter_Start", "PreProcessRequest")
+ .hasNotPassed("VnfAdapter_End");
}
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResources.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResources.java
index a47b16fc33..d401522800 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResources.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResources.java
@@ -23,7 +23,6 @@ package org.onap.so.bpmn.infrastructure.aai;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.AAIResourcesClient;
@@ -34,57 +33,64 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory;
public class AAICreateResources extends AAIResource {
- public void createAAIProject (String projectName, String serviceInstance){
- AAIResourceUri projectURI = AAIUriFactory.createResourceUri(AAIObjectType.PROJECT, projectName);
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance);
- getAaiClient().createIfNotExists(projectURI, Optional.empty()).connect(projectURI, serviceInstanceURI);
-
- }
-
- public void createAAIOwningEntity(String owningEntityId, String owningEntityName,String serviceInstance){
- AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance);
- Map<String, String> hashMap= new HashMap<>();
- hashMap.put("owning-entity-name", owningEntityName);
- getAaiClient().createIfNotExists(owningEntityURI, Optional.of(hashMap)).connect(owningEntityURI, serviceInstanceURI);
- }
+ public void createAAIProject(String projectName, String serviceInstance) {
+ AAIResourceUri projectURI = AAIUriFactory.createResourceUri(AAIObjectType.PROJECT, projectName);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance);
+ getAaiClient().createIfNotExists(projectURI, Optional.empty()).connect(projectURI, serviceInstanceURI);
+
+ }
+
+ public void createAAIOwningEntity(String owningEntityId, String owningEntityName, String serviceInstance) {
+ AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance);
+ Map<String, String> hashMap = new HashMap<>();
+ hashMap.put("owning-entity-name", owningEntityName);
+ getAaiClient().createIfNotExists(owningEntityURI, Optional.of(hashMap)).connect(owningEntityURI,
+ serviceInstanceURI);
+ }
+
+ public boolean existsOwningEntity(String owningEntityId) {
+ AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
+ return getAaiClient().exists(owningEntityURI);
+ }
+
+ public void connectOwningEntityandServiceInstance(String owningEntityId, String serviceInstance) {
+ AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance);
+ getAaiClient().connect(owningEntityURI, serviceInstanceURI);
+ }
+
+ public void createAAIPlatform(String platformName, String vnfId) {
+ AAIResourceUri platformURI = AAIUriFactory.createResourceUri(AAIObjectType.PLATFORM, platformName);
+ AAIResourceUri genericVnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
+ getAaiClient().createIfNotExists(platformURI, Optional.empty()).connect(platformURI, genericVnfURI);
+ }
+
+ public void createAAILineOfBusiness(String lineOfBusiness, String vnfId) {
+ AAIResourceUri lineOfBusinessURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.LINE_OF_BUSINESS, lineOfBusiness);
+ AAIResourceUri genericVnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
+ getAaiClient().createIfNotExists(lineOfBusinessURI, Optional.empty()).connect(lineOfBusinessURI, genericVnfURI);
+ }
+
+ public void createAAIServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId) {
+ AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalCustomerId, serviceType, serviceInstanceId);
+ getAaiClient().createIfNotExists(serviceInstanceURI, Optional.empty());
+ }
+
+ public Optional<GenericVnf> getVnfInstance(String vnfId) {
+ try {
+ AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
+ AAIResultWrapper aaiResponse = getAaiClient().get(vnfURI);
+ Optional<GenericVnf> vnf = aaiResponse.asBean(GenericVnf.class);
+ return vnf;
+ } catch (Exception ex) {
+ return Optional.empty();
+ }
+ }
- public boolean existsOwningEntity(String owningEntityId){
- AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
- return getAaiClient().exists(owningEntityURI);
- }
-
- public void connectOwningEntityandServiceInstance (String owningEntityId, String serviceInstance){
- AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance);
- getAaiClient().connect(owningEntityURI, serviceInstanceURI);
- }
-
- public void createAAIPlatform(String platformName,String vnfId){
- AAIResourceUri platformURI = AAIUriFactory.createResourceUri(AAIObjectType.PLATFORM, platformName);
- AAIResourceUri genericVnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF,vnfId);
- getAaiClient().createIfNotExists(platformURI, Optional.empty()).connect(platformURI, genericVnfURI);
- }
-
- public void createAAILineOfBusiness(String lineOfBusiness,String vnfId){
- AAIResourceUri lineOfBusinessURI = AAIUriFactory.createResourceUri(AAIObjectType.LINE_OF_BUSINESS, lineOfBusiness);
- AAIResourceUri genericVnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF,vnfId);
- getAaiClient().createIfNotExists(lineOfBusinessURI, Optional.empty()).connect(lineOfBusinessURI, genericVnfURI);
- }
- public void createAAIServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId){
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustomerId,serviceType,serviceInstanceId);
- getAaiClient().createIfNotExists(serviceInstanceURI, Optional.empty());
- }
-
- public Optional<GenericVnf> getVnfInstance(String vnfId){
- try{
- AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
- AAIResultWrapper aaiResponse = getAaiClient().get(vnfURI);
- Optional<GenericVnf> vnf = aaiResponse.asBean(GenericVnf.class);
- return vnf;
- } catch (Exception ex){
- return Optional.empty();
- }
- }
-
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstance.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstance.java
index cea6fe740d..2526ca5c25 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstance.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstance.java
@@ -29,21 +29,23 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.springframework.stereotype.Component;
-public class AAIDeleteServiceInstance extends AAIResource implements JavaDelegate{
+public class AAIDeleteServiceInstance extends AAIResource implements JavaDelegate {
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil();
+
+ public void execute(DelegateExecution execution) throws Exception {
+ try {
+ String serviceInstanceId = (String) execution.getVariable("serviceInstanceId");
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId);
+ getAaiClient().delete(serviceInstanceURI);
+ execution.setVariable("GENDS_SuccessIndicator", true);
+ } catch (Exception ex) {
+ String msg = "Exception in Delete Serivce Instance. Service Instance could not be deleted in AAI."
+ + ex.getMessage();
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
+
+ }
- ExceptionUtil exceptionUtil = new ExceptionUtil();
- public void execute(DelegateExecution execution) throws Exception {
- try{
- String serviceInstanceId = (String) execution.getVariable("serviceInstanceId");
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstanceId);
- getAaiClient().delete(serviceInstanceURI);
- execution.setVariable("GENDS_SuccessIndicator",true);
- } catch(Exception ex){
- String msg = "Exception in Delete Serivce Instance. Service Instance could not be deleted in AAI." + ex.getMessage();
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
- }
-
- }
-
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIResource.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIResource.java
index 3bc02be476..1410752f76 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIResource.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIResource.java
@@ -24,17 +24,17 @@ import org.onap.so.client.aai.AAIResourcesClient;
import org.springframework.stereotype.Component;
@Component
-public abstract class AAIResource {
- private AAIResourcesClient aaiClient;
+public abstract class AAIResource {
+ private AAIResourcesClient aaiClient;
- public AAIResourcesClient getAaiClient() {
- if(aaiClient == null)
- return new AAIResourcesClient();
- else
- return aaiClient;
- }
+ public AAIResourcesClient getAaiClient() {
+ if (aaiClient == null)
+ return new AAIResourcesClient();
+ else
+ return aaiClient;
+ }
- public void setAaiClient(AAIResourcesClient aaiClient) {
- this.aaiClient = aaiClient;
- }
+ public void setAaiClient(AAIResourcesClient aaiClient) {
+ this.aaiClient = aaiClient;
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIServiceInstance.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIServiceInstance.java
index c5cd2c70da..376ca4dbdb 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIServiceInstance.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/AAIServiceInstance.java
@@ -21,129 +21,144 @@
package org.onap.so.bpmn.infrastructure.aai;
public class AAIServiceInstance {
- String serviceInstanceName;
- String serviceType;
- String serviceRole;
- String orchestrationStatus;
- String modelInvariantUuid;
- String modelVersionId;
- String environmentContext;
- String workloadContext;
-
- public static class AAIServiceInstanceBuilder {
- private String serviceInstanceName;
- private String serviceType;
- private String serviceRole;
- private String orchestrationStatus;
- private String modelInvariantUuid;
- private String modelVersionId;
- private String environmentContext;
- private String workloadContext;
-
- public AAIServiceInstanceBuilder setServiceInstanceName(String serviceInstanceName) {
- this.serviceInstanceName = serviceInstanceName;
- return this;
- }
-
- public AAIServiceInstanceBuilder setServiceType(String serviceType) {
- this.serviceType = serviceType;
- return this;
- }
-
- public AAIServiceInstanceBuilder setServiceRole(String serviceRole) {
- this.serviceRole = serviceRole;
- return this;
- }
-
- public AAIServiceInstanceBuilder setOrchestrationStatus(String orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- return this;
- }
-
- public AAIServiceInstanceBuilder setModelInvariantUuid(String modelInvariantUuid) {
- this.modelInvariantUuid = modelInvariantUuid;
- return this;
- }
-
- public AAIServiceInstanceBuilder setModelVersionId(String modelVersionId) {
- this.modelVersionId = modelVersionId;
- return this;
- }
-
- public AAIServiceInstanceBuilder setEnvironmentContext(String environmentContext) {
- this.environmentContext = environmentContext;
- return this;
- }
-
- public AAIServiceInstanceBuilder setWorkloadContext(String workloadContext) {
- this.workloadContext = workloadContext;
- return this;
- }
-
- public AAIServiceInstance createAAIServiceInstance() {
- return new AAIServiceInstance(this);
- }
- }
-
- public AAIServiceInstance(AAIServiceInstanceBuilder aaiServiceInstanceBuilder) {
- this.serviceInstanceName = aaiServiceInstanceBuilder.serviceInstanceName;
- this.serviceType = aaiServiceInstanceBuilder.serviceType;
- this.serviceRole = aaiServiceInstanceBuilder.serviceRole;
- this.orchestrationStatus = aaiServiceInstanceBuilder.orchestrationStatus;
- this.modelInvariantUuid = aaiServiceInstanceBuilder.modelInvariantUuid;
- this.modelVersionId = aaiServiceInstanceBuilder.modelVersionId;
- this.environmentContext = aaiServiceInstanceBuilder.environmentContext;
- this.workloadContext = aaiServiceInstanceBuilder.workloadContext;
- }
-
- public String getServiceInstanceName() {
- return serviceInstanceName;
- }
- public void setServiceInstanceName(String serviceInstanceName) {
- this.serviceInstanceName = serviceInstanceName;
- }
- public String getServiceType() {
- return serviceType;
- }
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
- public String getServiceRole() {
- return serviceRole;
- }
- public void setServiceRole(String serviceRole) {
- this.serviceRole = serviceRole;
- }
- public String getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(String orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public String getModelInvariantUuid() {
- return modelInvariantUuid;
- }
- public void setModelInvariantUuid(String modelInvariantUuid) {
- this.modelInvariantUuid = modelInvariantUuid;
- }
- public String getModelVersionId() {
- return modelVersionId;
- }
- public void setModelVersionId(String modelVersionId) {
- this.modelVersionId = modelVersionId;
- }
- public String getEnvironmentContext() {
- return environmentContext;
- }
- public void setEnvironmentContext(String environmentContext) {
- this.environmentContext = environmentContext;
- }
- public String getWorkloadContext() {
- return workloadContext;
- }
- public void setWorkloadContext(String workloadContext) {
- this.workloadContext = workloadContext;
- }
-
+ String serviceInstanceName;
+ String serviceType;
+ String serviceRole;
+ String orchestrationStatus;
+ String modelInvariantUuid;
+ String modelVersionId;
+ String environmentContext;
+ String workloadContext;
+
+ public static class AAIServiceInstanceBuilder {
+ private String serviceInstanceName;
+ private String serviceType;
+ private String serviceRole;
+ private String orchestrationStatus;
+ private String modelInvariantUuid;
+ private String modelVersionId;
+ private String environmentContext;
+ private String workloadContext;
+
+ public AAIServiceInstanceBuilder setServiceInstanceName(String serviceInstanceName) {
+ this.serviceInstanceName = serviceInstanceName;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setOrchestrationStatus(String orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setModelInvariantUuid(String modelInvariantUuid) {
+ this.modelInvariantUuid = modelInvariantUuid;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setModelVersionId(String modelVersionId) {
+ this.modelVersionId = modelVersionId;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setEnvironmentContext(String environmentContext) {
+ this.environmentContext = environmentContext;
+ return this;
+ }
+
+ public AAIServiceInstanceBuilder setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ return this;
+ }
+
+ public AAIServiceInstance createAAIServiceInstance() {
+ return new AAIServiceInstance(this);
+ }
+ }
+
+ public AAIServiceInstance(AAIServiceInstanceBuilder aaiServiceInstanceBuilder) {
+ this.serviceInstanceName = aaiServiceInstanceBuilder.serviceInstanceName;
+ this.serviceType = aaiServiceInstanceBuilder.serviceType;
+ this.serviceRole = aaiServiceInstanceBuilder.serviceRole;
+ this.orchestrationStatus = aaiServiceInstanceBuilder.orchestrationStatus;
+ this.modelInvariantUuid = aaiServiceInstanceBuilder.modelInvariantUuid;
+ this.modelVersionId = aaiServiceInstanceBuilder.modelVersionId;
+ this.environmentContext = aaiServiceInstanceBuilder.environmentContext;
+ this.workloadContext = aaiServiceInstanceBuilder.workloadContext;
+ }
+
+ public String getServiceInstanceName() {
+ return serviceInstanceName;
+ }
+
+ public void setServiceInstanceName(String serviceInstanceName) {
+ this.serviceInstanceName = serviceInstanceName;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getServiceRole() {
+ return serviceRole;
+ }
+
+ public void setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ }
+
+ public String getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(String orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public String getModelInvariantUuid() {
+ return modelInvariantUuid;
+ }
+
+ public void setModelInvariantUuid(String modelInvariantUuid) {
+ this.modelInvariantUuid = modelInvariantUuid;
+ }
+
+ public String getModelVersionId() {
+ return modelVersionId;
+ }
+
+ public void setModelVersionId(String modelVersionId) {
+ this.modelVersionId = modelVersionId;
+ }
+
+ public String getEnvironmentContext() {
+ return environmentContext;
+ }
+
+ public void setEnvironmentContext(String environmentContext) {
+ this.environmentContext = environmentContext;
+ }
+
+ public String getWorkloadContext() {
+ return workloadContext;
+ }
+
+ public void setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
+
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAICreateResources.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAICreateResources.java
index 0c519ef29f..bbca10be0f 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAICreateResources.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAICreateResources.java
@@ -25,7 +25,6 @@ package org.onap.so.bpmn.infrastructure.aai.groovyflows;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-
import org.onap.aai.domain.yang.OwningEntities;
import org.onap.aai.domain.yang.OwningEntity;
import org.onap.so.client.aai.AAIObjectPlurals;
@@ -37,85 +36,88 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AAICreateResources {
-
- private static final Logger logger = LoggerFactory.getLogger(AAICreateResources.class);
-
- public void createAAIProject (String projectName, String serviceInstance){
- AAIResourceUri projectURI = AAIUriFactory.createResourceUri(AAIObjectType.PROJECT, projectName);
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance);
- AAIResourcesClient aaiRC = new AAIResourcesClient();
- aaiRC.createIfNotExists(projectURI, Optional.empty()).connect(projectURI, serviceInstanceURI);
-
- }
-
- public void createAAIOwningEntity(String owningEntityId, String owningEntityName,String serviceInstance){
- AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createNodesUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance);
- Map<String, String> hashMap= new HashMap<>();
- hashMap.put("owning-entity-name", owningEntityName);
- AAIResourcesClient aaiRC = new AAIResourcesClient();
- aaiRC.createIfNotExists(owningEntityURI, Optional.of(hashMap)).connect(owningEntityURI, serviceInstanceURI);
- }
-
- public boolean existsOwningEntity(String owningEntityId){
- AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
- AAIResourcesClient aaiRC = new AAIResourcesClient();
- return aaiRC.exists(owningEntityURI);
- }
-
- protected OwningEntities getOwningEntityName(String owningEntityName){
-
- AAIResourcesClient aaiRC = new AAIResourcesClient();
- return aaiRC.get(OwningEntities.class,
- AAIUriFactory
- .createResourceUri(AAIObjectPlurals.OWNING_ENTITY)
- .queryParam("owning-entity-name", owningEntityName))
- .orElseGet(() -> {
- logger.debug("No Owning Entity matched by name");
- return null;
- });
-
- }
-
- public Optional<OwningEntity> getOwningEntityNames(String owningEntityName) throws Exception{
- OwningEntity owningEntity = null;
- OwningEntities owningEntities = null;
- owningEntities = getOwningEntityName(owningEntityName);
-
- if (owningEntities == null) {
- return Optional.empty();
- } else if (owningEntities.getOwningEntity().size() > 1) {
- throw new Exception("Multiple OwningEntities Returned");
- } else {
- owningEntity = owningEntities.getOwningEntity().get(0);
- }
- return Optional.of(owningEntity);
- }
-
- public void connectOwningEntityandServiceInstance (String owningEntityId, String serviceInstance){
- AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance);
- AAIResourcesClient aaiRC = new AAIResourcesClient();
- aaiRC.connect(owningEntityURI, serviceInstanceURI);
- }
-
- public void createAAIPlatform(String platformName,String vnfId){
- AAIResourceUri platformURI = AAIUriFactory.createResourceUri(AAIObjectType.PLATFORM, platformName);
- AAIResourceUri genericVnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF,vnfId);
- AAIResourcesClient aaiRC = new AAIResourcesClient();
- aaiRC.createIfNotExists(platformURI, Optional.empty()).connect(platformURI, genericVnfURI);
- }
-
- public void createAAILineOfBusiness(String lineOfBusiness,String vnfId){
- AAIResourceUri lineOfBusinessURI = AAIUriFactory.createResourceUri(AAIObjectType.LINE_OF_BUSINESS, lineOfBusiness);
- AAIResourceUri genericVnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF,vnfId);
- AAIResourcesClient aaiRC = new AAIResourcesClient();
- aaiRC.createIfNotExists(lineOfBusinessURI, Optional.empty()).connect(lineOfBusinessURI, genericVnfURI);
- }
- public void createAAIServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId){
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustomerId,serviceType,serviceInstanceId);
- AAIResourcesClient aaiRC = new AAIResourcesClient();
- aaiRC.createIfNotExists(serviceInstanceURI, Optional.empty());
- }
-
+
+ private static final Logger logger = LoggerFactory.getLogger(AAICreateResources.class);
+
+ public void createAAIProject(String projectName, String serviceInstance) {
+ AAIResourceUri projectURI = AAIUriFactory.createResourceUri(AAIObjectType.PROJECT, projectName);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance);
+ AAIResourcesClient aaiRC = new AAIResourcesClient();
+ aaiRC.createIfNotExists(projectURI, Optional.empty()).connect(projectURI, serviceInstanceURI);
+
+ }
+
+ public void createAAIOwningEntity(String owningEntityId, String owningEntityName, String serviceInstance) {
+ AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createNodesUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance);
+ Map<String, String> hashMap = new HashMap<>();
+ hashMap.put("owning-entity-name", owningEntityName);
+ AAIResourcesClient aaiRC = new AAIResourcesClient();
+ aaiRC.createIfNotExists(owningEntityURI, Optional.of(hashMap)).connect(owningEntityURI, serviceInstanceURI);
+ }
+
+ public boolean existsOwningEntity(String owningEntityId) {
+ AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
+ AAIResourcesClient aaiRC = new AAIResourcesClient();
+ return aaiRC.exists(owningEntityURI);
+ }
+
+ protected OwningEntities getOwningEntityName(String owningEntityName) {
+
+ AAIResourcesClient aaiRC = new AAIResourcesClient();
+ return aaiRC.get(OwningEntities.class, AAIUriFactory.createResourceUri(AAIObjectPlurals.OWNING_ENTITY)
+ .queryParam("owning-entity-name", owningEntityName)).orElseGet(() -> {
+ logger.debug("No Owning Entity matched by name");
+ return null;
+ });
+
+ }
+
+ public Optional<OwningEntity> getOwningEntityNames(String owningEntityName) throws Exception {
+ OwningEntity owningEntity = null;
+ OwningEntities owningEntities = null;
+ owningEntities = getOwningEntityName(owningEntityName);
+
+ if (owningEntities == null) {
+ return Optional.empty();
+ } else if (owningEntities.getOwningEntity().size() > 1) {
+ throw new Exception("Multiple OwningEntities Returned");
+ } else {
+ owningEntity = owningEntities.getOwningEntity().get(0);
+ }
+ return Optional.of(owningEntity);
+ }
+
+ public void connectOwningEntityandServiceInstance(String owningEntityId, String serviceInstance) {
+ AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance);
+ AAIResourcesClient aaiRC = new AAIResourcesClient();
+ aaiRC.connect(owningEntityURI, serviceInstanceURI);
+ }
+
+ public void createAAIPlatform(String platformName, String vnfId) {
+ AAIResourceUri platformURI = AAIUriFactory.createResourceUri(AAIObjectType.PLATFORM, platformName);
+ AAIResourceUri genericVnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
+ AAIResourcesClient aaiRC = new AAIResourcesClient();
+ aaiRC.createIfNotExists(platformURI, Optional.empty()).connect(platformURI, genericVnfURI);
+ }
+
+ public void createAAILineOfBusiness(String lineOfBusiness, String vnfId) {
+ AAIResourceUri lineOfBusinessURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.LINE_OF_BUSINESS, lineOfBusiness);
+ AAIResourceUri genericVnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
+ AAIResourcesClient aaiRC = new AAIResourcesClient();
+ aaiRC.createIfNotExists(lineOfBusinessURI, Optional.empty()).connect(lineOfBusinessURI, genericVnfURI);
+ }
+
+ public void createAAIServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId) {
+ AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalCustomerId, serviceType, serviceInstanceId);
+ AAIResourcesClient aaiRC = new AAIResourcesClient();
+ aaiRC.createIfNotExists(serviceInstanceURI, Optional.empty());
+ }
+
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIDeleteServiceInstance.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIDeleteServiceInstance.java
index 495c77255d..fb95ae3993 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIDeleteServiceInstance.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIDeleteServiceInstance.java
@@ -28,22 +28,24 @@ import org.onap.so.client.aai.AAIResourcesClient;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
-public class AAIDeleteServiceInstance implements JavaDelegate{
+public class AAIDeleteServiceInstance implements JavaDelegate {
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil();
+
+ public void execute(DelegateExecution execution) throws Exception {
+ try {
+ String serviceInstanceId = (String) execution.getVariable("serviceInstanceId");
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId);
+ AAIResourcesClient aaiRC = new AAIResourcesClient();
+ aaiRC.delete(serviceInstanceURI);
+ execution.setVariable("GENDS_SuccessIndicator", true);
+ } catch (Exception ex) {
+ String msg = "Exception in Delete Serivce Instance. Service Instance could not be deleted in AAI."
+ + ex.getMessage();
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
+
+ }
- ExceptionUtil exceptionUtil = new ExceptionUtil();
- public void execute(DelegateExecution execution) throws Exception {
- try{
- String serviceInstanceId = (String) execution.getVariable("serviceInstanceId");
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstanceId);
- AAIResourcesClient aaiRC = new AAIResourcesClient();
- aaiRC.delete(serviceInstanceURI);
- execution.setVariable("GENDS_SuccessIndicator",true);
- } catch(Exception ex){
- String msg = "Exception in Delete Serivce Instance. Service Instance could not be deleted in AAI." + ex.getMessage();
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
- }
-
- }
-
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIServiceInstance.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIServiceInstance.java
index 805ece9de8..2d69351744 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIServiceInstance.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/aai/groovyflows/AAIServiceInstance.java
@@ -21,74 +21,91 @@
package org.onap.so.bpmn.infrastructure.aai.groovyflows;
public class AAIServiceInstance {
- String serviceInstanceName;
- String serviceType;
- String serviceRole;
- String orchestrationStatus;
- String modelInvariantUuid;
- String modelVersionId;
- String environmentContext;
- String workloadContext;
- public AAIServiceInstance(String serviceInstanceName, String serviceType, String serviceRole,
- String orchestrationStatus, String modelInvariantUuid, String modelVersionId, String environmentContext,
- String workloadContext) {
- this.serviceInstanceName = serviceInstanceName;
- this.serviceType = serviceType;
- this.serviceRole = serviceRole;
- this.orchestrationStatus = orchestrationStatus;
- this.modelInvariantUuid = modelInvariantUuid;
- this.modelVersionId = modelVersionId;
- this.environmentContext = environmentContext;
- this.workloadContext = workloadContext;
- }
- public String getServiceInstanceName() {
- return serviceInstanceName;
- }
- public void setServiceInstanceName(String serviceInstanceName) {
- this.serviceInstanceName = serviceInstanceName;
- }
- public String getServiceType() {
- return serviceType;
- }
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
- public String getServiceRole() {
- return serviceRole;
- }
- public void setServiceRole(String serviceRole) {
- this.serviceRole = serviceRole;
- }
- public String getOrchestrationStatus() {
- return orchestrationStatus;
- }
- public void setOrchestrationStatus(String orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
- public String getModelInvariantUuid() {
- return modelInvariantUuid;
- }
- public void setModelInvariantUuid(String modelInvariantUuid) {
- this.modelInvariantUuid = modelInvariantUuid;
- }
- public String getModelVersionId() {
- return modelVersionId;
- }
- public void setModelVersionId(String modelVersionId) {
- this.modelVersionId = modelVersionId;
- }
- public String getEnvironmentContext() {
- return environmentContext;
- }
- public void setEnvironmentContext(String environmentContext) {
- this.environmentContext = environmentContext;
- }
- public String getWorkloadContext() {
- return workloadContext;
- }
- public void setWorkloadContext(String workloadContext) {
- this.workloadContext = workloadContext;
- }
-
+ String serviceInstanceName;
+ String serviceType;
+ String serviceRole;
+ String orchestrationStatus;
+ String modelInvariantUuid;
+ String modelVersionId;
+ String environmentContext;
+ String workloadContext;
+
+ public AAIServiceInstance(String serviceInstanceName, String serviceType, String serviceRole,
+ String orchestrationStatus, String modelInvariantUuid, String modelVersionId, String environmentContext,
+ String workloadContext) {
+ this.serviceInstanceName = serviceInstanceName;
+ this.serviceType = serviceType;
+ this.serviceRole = serviceRole;
+ this.orchestrationStatus = orchestrationStatus;
+ this.modelInvariantUuid = modelInvariantUuid;
+ this.modelVersionId = modelVersionId;
+ this.environmentContext = environmentContext;
+ this.workloadContext = workloadContext;
+ }
+
+ public String getServiceInstanceName() {
+ return serviceInstanceName;
+ }
+
+ public void setServiceInstanceName(String serviceInstanceName) {
+ this.serviceInstanceName = serviceInstanceName;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getServiceRole() {
+ return serviceRole;
+ }
+
+ public void setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ }
+
+ public String getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(String orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public String getModelInvariantUuid() {
+ return modelInvariantUuid;
+ }
+
+ public void setModelInvariantUuid(String modelInvariantUuid) {
+ this.modelInvariantUuid = modelInvariantUuid;
+ }
+
+ public String getModelVersionId() {
+ return modelVersionId;
+ }
+
+ public void setModelVersionId(String modelVersionId) {
+ this.modelVersionId = modelVersionId;
+ }
+
+ public String getEnvironmentContext() {
+ return environmentContext;
+ }
+
+ public void setEnvironmentContext(String environmentContext) {
+ this.environmentContext = environmentContext;
+ }
+
+ public String getWorkloadContext() {
+ return workloadContext;
+ }
+
+ public void setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
+
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/common/name/generation/AAIObjectInstanceNameGenerator.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/common/name/generation/AAIObjectInstanceNameGenerator.java
index 3b443cbaf2..55387d6a3d 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/common/name/generation/AAIObjectInstanceNameGenerator.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/common/name/generation/AAIObjectInstanceNameGenerator.java
@@ -27,14 +27,15 @@ import org.springframework.stereotype.Component;
@Component
public class AAIObjectInstanceNameGenerator {
- public String generateInstanceGroupName(InstanceGroup instanceGroup, GenericVnf vnf) {
- if(vnf.getVnfName() != null && instanceGroup.getModelInfoInstanceGroup().getFunction() != null) {
- return vnf.getVnfName() + "_" + instanceGroup.getModelInfoInstanceGroup().getFunction();
- } else {
- throw new IllegalArgumentException("Cannot generate instance group name because either one or both fields are null: "
- + " Vnf Instance Name: " + vnf.getVnfName()
- + ", Instance Group Function: " + instanceGroup.getModelInfoInstanceGroup().getFunction());
- }
- }
-
+ public String generateInstanceGroupName(InstanceGroup instanceGroup, GenericVnf vnf) {
+ if (vnf.getVnfName() != null && instanceGroup.getModelInfoInstanceGroup().getFunction() != null) {
+ return vnf.getVnfName() + "_" + instanceGroup.getModelInfoInstanceGroup().getFunction();
+ } else {
+ throw new IllegalArgumentException(
+ "Cannot generate instance group name because either one or both fields are null: "
+ + " Vnf Instance Name: " + vnf.getVnfName() + ", Instance Group Function: "
+ + instanceGroup.getModelInfoInstanceGroup().getFunction());
+ }
+ }
+
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForPnfCorrelationIdDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForPnfCorrelationIdDelegate.java
index e0fa41b7a1..493340c9ef 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForPnfCorrelationIdDelegate.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForPnfCorrelationIdDelegate.java
@@ -22,9 +22,7 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.AAI_CONTAINS_INFO_ABOUT_PNF;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_CORRELATION_ID;
-
import java.io.IOException;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.onap.so.bpmn.common.scripts.ExceptionUtil;
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegate.java
index 9b60a05e98..d67e6ef0db 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegate.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegate.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.pnf.delegate;
@@ -26,7 +21,6 @@ import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableName
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_INSTANCE_NAME;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.SERVICE_MODEL_INFO;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.SKIP_POST_INSTANTIATION_CONFIGURATION;
-
import java.util.List;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
@@ -50,7 +44,7 @@ public class ConfigCheckerDelegate implements JavaDelegate {
private Logger logger = LoggerFactory.getLogger(ConfigCheckerDelegate.class);
- //ERROR CODE for variable not found in the delegation Context
+ // ERROR CODE for variable not found in the delegation Context
private static int ERROR_CODE = 601;
@Autowired
@@ -63,34 +57,33 @@ public class ConfigCheckerDelegate implements JavaDelegate {
public void execute(DelegateExecution delegateExecution) throws Exception {
logger.debug("Running execute block for activity id:{}, name:{}", delegateExecution.getCurrentActivityId(),
- delegateExecution.getCurrentActivityName());
+ delegateExecution.getCurrentActivityName());
if (delegateExecution.hasVariable(SERVICE_MODEL_INFO)) {
String serviceModelInfo = (String) delegateExecution.getVariable(SERVICE_MODEL_INFO);
String serviceModelUuid = JsonUtils.getJsonValue(serviceModelInfo, MODEL_UUID);
delegateExecution.setVariable(MODEL_UUID, serviceModelUuid);
- List<PnfResourceCustomization> pnfCustomizations = catalogDbClient
- .getPnfResourceCustomizationByModelUuid(serviceModelUuid);
+ List<PnfResourceCustomization> pnfCustomizations =
+ catalogDbClient.getPnfResourceCustomizationByModelUuid(serviceModelUuid);
if (pnfCustomizations != null && pnfCustomizations.size() >= 1) {
PnfResourceCustomization pnfResourceCustomization = pnfCustomizations.get(0);
boolean skipPostInstantiationConfiguration = pnfResourceCustomization.isSkipPostInstConf();
- delegateExecution
- .setVariable(SKIP_POST_INSTANTIATION_CONFIGURATION, skipPostInstantiationConfiguration);
+ delegateExecution.setVariable(SKIP_POST_INSTANTIATION_CONFIGURATION,
+ skipPostInstantiationConfiguration);
delegateExecution.setVariable(PRC_BLUEPRINT_NAME, pnfResourceCustomization.getBlueprintName());
delegateExecution.setVariable(PRC_BLUEPRINT_VERSION, pnfResourceCustomization.getBlueprintVersion());
- delegateExecution
- .setVariable(PRC_CUSTOMIZATION_UUID, pnfResourceCustomization.getModelCustomizationUUID());
+ delegateExecution.setVariable(PRC_CUSTOMIZATION_UUID,
+ pnfResourceCustomization.getModelCustomizationUUID());
delegateExecution.setVariable(PRC_INSTANCE_NAME, pnfResourceCustomization.getModelInstanceName());
} else {
- logger
- .warn("Unable to find the PNF resource customizations of model service UUID: {}", serviceModelUuid);
+ logger.warn("Unable to find the PNF resource customizations of model service UUID: {}",
+ serviceModelUuid);
exceptionUtil.buildAndThrowWorkflowException(delegateExecution, ERROR_CODE,
- "Unable to find the PNF resource customizations of model service UUID: " + serviceModelUuid);
+ "Unable to find the PNF resource customizations of model service UUID: " + serviceModelUuid);
}
} else {
logger.warn("Unable to find the parameter: {} in the execution context", SERVICE_MODEL_INFO);
- exceptionUtil
- .buildAndThrowWorkflowException(delegateExecution, ERROR_CODE,
+ exceptionUtil.buildAndThrowWorkflowException(delegateExecution, ERROR_CODE,
"Unable to find parameter " + SERVICE_MODEL_INFO);
}
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegate.java
index e56cb83119..cb06085ee8 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegate.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegate.java
@@ -24,7 +24,6 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_CORRELATION_ID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.onap.aai.domain.yang.Pnf;
@@ -37,9 +36,7 @@ import org.springframework.stereotype.Component;
/**
* Implementation of "Create Pnf entry in AAI" task in CreateAndActivatePnfResource.bpmn
*
- * Inputs:
- * - pnfCorrelationId - String
- * - pnfUuid - String
+ * Inputs: - pnfCorrelationId - String - pnfUuid - String
*/
@Component
public class CreatePnfEntryInAaiDelegate implements JavaDelegate {
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateRelation.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateRelation.java
index a367bada02..6d73b61ab2 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateRelation.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateRelation.java
@@ -51,8 +51,8 @@ public class CreateRelation implements JavaDelegate {
new ExceptionUtil().buildAndThrowWorkflowException(delegateExecution, 9999,
"An exception occurred when making service and pnf relation. Exception: " + e.getMessage());
}
- logger.debug("The relation has been made between service with id: {} and pnf with name: {}",
- serviceInstanceId, pnfName);
+ logger.debug("The relation has been made between service with id: {} and pnf with name: {}", serviceInstanceId,
+ pnfName);
}
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegate.java
index f5483e489e..852ca4fcef 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegate.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegate.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.infrastructure.pnf.delegate;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID;
-
import java.util.UUID;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
@@ -35,7 +34,7 @@ public class GeneratePnfUuidDelegate implements JavaDelegate {
private static final Logger logger = LoggerFactory.getLogger(GeneratePnfUuidDelegate.class);
@Override
- public void execute(DelegateExecution delegateExecution){
+ public void execute(DelegateExecution delegateExecution) {
UUID uuid = UUID.randomUUID();
logger.debug("Generated UUID for pnf: {}, version: {}, variant: {}", uuid, uuid.version(), uuid.variant());
delegateExecution.setVariable(PNF_UUID, uuid.toString());
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClient.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClient.java
index 96455acb84..5cbd530a93 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClient.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClient.java
@@ -36,12 +36,8 @@ public class InformDmaapClient implements JavaDelegate {
public void execute(DelegateExecution execution) {
String pnfCorrelationId = (String) execution.getVariable(ExecutionVariableNames.PNF_CORRELATION_ID);
RuntimeService runtimeService = execution.getProcessEngineServices().getRuntimeService();
- dmaapClient.registerForUpdate(pnfCorrelationId, () ->
- runtimeService
- .createMessageCorrelation("WorkflowMessage")
- .processInstanceBusinessKey(execution.getProcessBusinessKey())
- .correlateWithResult()
- );
+ dmaapClient.registerForUpdate(pnfCorrelationId, () -> runtimeService.createMessageCorrelation("WorkflowMessage")
+ .processInstanceBusinessKey(execution.getProcessBusinessKey()).correlateWithResult());
}
@Autowired
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputs.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputs.java
index 1caadea0de..b52110ea82 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputs.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputs.java
@@ -26,7 +26,6 @@ import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableName
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.SERVICE_INSTANCE_ID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.TIMEOUT_FOR_NOTIFICATION;
-
import com.google.common.base.Strings;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
@@ -38,7 +37,8 @@ import org.springframework.stereotype.Component;
@Component
public class PnfCheckInputs implements JavaDelegate {
- public static final String UUID_REGEX = "(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[1-5]{1}[0-9a-f]{3}-[89ab]{1}[0-9a-f]{3}-[0-9a-f]{12}$";
+ public static final String UUID_REGEX =
+ "(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[1-5]{1}[0-9a-f]{3}-[89ab]{1}[0-9a-f]{3}-[0-9a-f]{12}$";
private String pnfEntryNotificationTimeout;
@@ -58,7 +58,8 @@ public class PnfCheckInputs implements JavaDelegate {
private void validatePnfCorrelationId(DelegateExecution execution) {
String pnfCorrelationId = (String) execution.getVariable(PNF_CORRELATION_ID);
if (Strings.isNullOrEmpty(pnfCorrelationId)) {
- new ExceptionUtil().buildAndThrowWorkflowException(execution, 9999, "pnfCorrelationId variable not defined");
+ new ExceptionUtil().buildAndThrowWorkflowException(execution, 9999,
+ "pnfCorrelationId variable not defined");
}
}
@@ -83,7 +84,8 @@ public class PnfCheckInputs implements JavaDelegate {
private void validateServiceInstanceId(DelegateExecution execution) {
String serviceInstanceId = (String) execution.getVariable(SERVICE_INSTANCE_ID);
if (Strings.isNullOrEmpty(serviceInstanceId)) {
- new ExceptionUtil().buildAndThrowWorkflowException(execution, 9999, "serviceInstanceId variable not defined");
+ new ExceptionUtil().buildAndThrowWorkflowException(execution, 9999,
+ "serviceInstanceId variable not defined");
}
}
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareCdsCallDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareCdsCallDelegate.java
index 49887af4be..c4c299d4b6 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareCdsCallDelegate.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareCdsCallDelegate.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.pnf.delegate;
@@ -24,7 +19,6 @@ import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableName
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_BLUEPRINT_NAME;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_BLUEPRINT_VERSION;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.onap.so.client.cds.beans.AbstractCDSPropertiesBean;
@@ -50,7 +44,7 @@ public abstract class PrepareCdsCallDelegate implements JavaDelegate {
protected ExceptionBuilder exceptionUtil;
@Override
- public void execute(DelegateExecution delegateExecution){
+ public void execute(DelegateExecution delegateExecution) {
logger.debug("Running execute block for activity:{}", delegateExecution.getCurrentActivityId());
AbstractCDSPropertiesBean cdsPropertiesBean = new AbstractCDSPropertiesBean();
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigAssignDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigAssignDelegate.java
index 5bf167ea7a..dd2601f0d0 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigAssignDelegate.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigAssignDelegate.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.pnf.delegate;
@@ -25,7 +20,6 @@ import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableName
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_CUSTOMIZATION_UUID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_INSTANCE_NAME;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.SERVICE_INSTANCE_ID;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.onap.so.client.cds.beans.AbstractCDSPropertiesBean;
@@ -48,7 +42,7 @@ public class PrepareConfigAssignDelegate extends PrepareCdsCallDelegate {
}
@Override
- protected String getRequestObject(final DelegateExecution delegateExecution){
+ protected String getRequestObject(final DelegateExecution delegateExecution) {
ConfigAssignPropertiesForPnf configAssignProperties = new ConfigAssignPropertiesForPnf();
configAssignProperties.setServiceInstanceId((String) delegateExecution.getVariable(SERVICE_INSTANCE_ID));
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigDeployDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigDeployDelegate.java
index 5fbed598e3..16f712fa66 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigDeployDelegate.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigDeployDelegate.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.pnf.delegate;
@@ -24,7 +19,6 @@ import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableName
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_CUSTOMIZATION_UUID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.SERVICE_INSTANCE_ID;
-
import java.io.IOException;
import java.util.Optional;
import org.camunda.bpm.engine.delegate.DelegateExecution;
@@ -55,7 +49,7 @@ public class PrepareConfigDeployDelegate extends PrepareCdsCallDelegate {
}
@Override
- protected String getRequestObject(DelegateExecution delegateExecution){
+ protected String getRequestObject(DelegateExecution delegateExecution) {
ConfigDeployPropertiesForPnf configDeployProperties = new ConfigDeployPropertiesForPnf();
@@ -85,7 +79,8 @@ public class PrepareConfigDeployDelegate extends PrepareCdsCallDelegate {
return configDeployRequest.toString();
}
- private void setIpAddress(ConfigDeployPropertiesForPnf configDeployProperties, DelegateExecution delegateExecution) {
+ private void setIpAddress(ConfigDeployPropertiesForPnf configDeployProperties,
+ DelegateExecution delegateExecution) {
/**
* Retrieve PNF entry from AAI.
@@ -93,21 +88,23 @@ public class PrepareConfigDeployDelegate extends PrepareCdsCallDelegate {
try {
String pnfName = (String) delegateExecution.getVariable(PNF_CORRELATION_ID);
Optional<Pnf> pnfOptional = pnfManagement.getEntryFor(pnfName);
- if ( pnfOptional.isPresent()){
+ if (pnfOptional.isPresent()) {
Pnf pnf = pnfOptional.get();
/**
- * PRH patches the AAI with oam address.
- * Use ipaddress-v4-oam and ipaddress-v6-oam for the config deploy request.
+ * PRH patches the AAI with oam address. Use ipaddress-v4-oam and ipaddress-v6-oam for the config deploy
+ * request.
*/
configDeployProperties.setPnfIpV4Address(pnf.getIpaddressV4Oam());
configDeployProperties.setPnfIpV6Address(pnf.getIpaddressV6Oam());
} else {
- exceptionUtil.buildAndThrowWorkflowException(delegateExecution, ERROR_CODE, "AAI entry for PNF: " + pnfName + " does not exist");
+ exceptionUtil.buildAndThrowWorkflowException(delegateExecution, ERROR_CODE,
+ "AAI entry for PNF: " + pnfName + " does not exist");
}
} catch (IOException e) {
logger.warn(e.getMessage(), e);
- exceptionUtil.buildAndThrowWorkflowException(delegateExecution, ERROR_CODE, "Unable to fetch from AAI" + e.getMessage());
+ exceptionUtil.buildAndThrowWorkflowException(delegateExecution, ERROR_CODE,
+ "Unable to fetch from AAI" + e.getMessage());
}
}
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationId.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationId.java
index fb5d04328f..7cb78a10e5 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationId.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationId.java
@@ -41,9 +41,8 @@ public final class JsonUtilForPnfCorrelationId {
List<String> list = new ArrayList<>();
Spliterator<JsonElement> spliterator = array.spliterator();
spliterator.forEachRemaining(jsonElement -> {
- handleEscapedCharacters(jsonElement)
- .ifPresent(jsonObject -> getPnfCorrelationId(jsonObject)
- .ifPresent(pnfCorrelationId -> list.add(pnfCorrelationId)));
+ handleEscapedCharacters(jsonElement).ifPresent(jsonObject -> getPnfCorrelationId(jsonObject)
+ .ifPresent(pnfCorrelationId -> list.add(pnfCorrelationId)));
});
return list;
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClient.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClient.java
index 6f828f6cb0..3de0f38b70 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClient.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClient.java
@@ -60,12 +60,10 @@ public class PnfEventReadyDmaapClient implements DmaapClient {
topicListenerDelayInSeconds = env.getProperty("pnf.dmaap.topicListenerDelayInSeconds", Integer.class);
executor = null;
getRequest = new HttpGet(UriBuilder.fromUri(env.getProperty("pnf.dmaap.uriPathPrefix"))
- .scheme(env.getProperty("pnf.dmaap.protocol"))
- .host(env.getProperty("pnf.dmaap.host"))
- .port(env.getProperty("pnf.dmaap.port", Integer.class))
- .path(env.getProperty("pnf.dmaap.topicName"))
- .path(env.getProperty("pnf.dmaap.consumerGroup"))
- .path(env.getProperty("pnf.dmaap.consumerId")).build());
+ .scheme(env.getProperty("pnf.dmaap.protocol")).host(env.getProperty("pnf.dmaap.host"))
+ .port(env.getProperty("pnf.dmaap.port", Integer.class)).path(env.getProperty("pnf.dmaap.topicName"))
+ .path(env.getProperty("pnf.dmaap.consumerGroup")).path(env.getProperty("pnf.dmaap.consumerId"))
+ .build());
}
@Override
@@ -92,8 +90,8 @@ public class PnfEventReadyDmaapClient implements DmaapClient {
executor = new ScheduledThreadPoolExecutor(1);
executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
- executor.scheduleWithFixedDelay(new DmaapTopicListenerThread(), 0,
- topicListenerDelayInSeconds, TimeUnit.SECONDS);
+ executor.scheduleWithFixedDelay(new DmaapTopicListenerThread(), 0, topicListenerDelayInSeconds,
+ TimeUnit.SECONDS);
dmaapThreadListenerIsRunning = true;
}
}
@@ -116,8 +114,7 @@ public class PnfEventReadyDmaapClient implements DmaapClient {
getPnfCorrelationIdListFromResponse(response).forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound);
} catch (IOException e) {
logger.error("Exception caught during sending rest request to dmaap for listening event topic", e);
- }
- finally {
+ } finally {
getRequest.reset();
}
}
@@ -136,7 +133,7 @@ public class PnfEventReadyDmaapClient implements DmaapClient {
Runnable runnable = unregister(pnfCorrelationId);
if (runnable != null) {
logger.debug("dmaap listener gets pnf ready event for pnfCorrelationId: {}", pnfCorrelationId);
- //runnable.run();
+ // runnable.run();
runnable = null;
}
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagementImpl.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagementImpl.java
index 32ea357817..b1af8b1e0b 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagementImpl.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/management/PnfManagementImpl.java
@@ -46,8 +46,8 @@ public class PnfManagementImpl implements PnfManagement {
@Override
public void createRelation(String serviceInstanceId, String pnfName) {
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstanceId);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId);
AAIResourceUri pnfUri = AAIUriFactory.createResourceUri(AAIObjectType.PNF, pnfName);
new AAIResourcesClient().connect(serviceInstanceURI, pnfUri);
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/properties/BPMNProperties.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/properties/BPMNProperties.java
index ee8743f846..8b2bb9a8de 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/properties/BPMNProperties.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/properties/BPMNProperties.java
@@ -22,22 +22,22 @@ package org.onap.so.bpmn.infrastructure.properties;
import java.util.Arrays;
import java.util.List;
import org.onap.so.bpmn.core.UrnPropertiesReader;
-
import org.onap.so.bpmn.core.UrnPropertiesReader;
public class BPMNProperties {
public static String getProperty(String key, String defaultValue) {
- String value = UrnPropertiesReader.getVariable(key);
- if (value == null) {
- return defaultValue;
- } else {
- return value;
- }
+ String value = UrnPropertiesReader.getVariable(key);
+ if (value == null) {
+ return defaultValue;
+ } else {
+ return value;
+ }
}
public static List<String> getResourceSequenceProp(String input) {
- String resourceSequence = UrnPropertiesReader.getVariable("mso.workflow.custom."+ input + ".resource.sequence");
+ String resourceSequence =
+ UrnPropertiesReader.getVariable("mso.workflow.custom." + input + ".resource.sequence");
if (resourceSequence != null) {
return Arrays.asList(resourceSequence.split(","));
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NSResourceInputParameter.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NSResourceInputParameter.java
index 292f6ef575..2995e24c00 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NSResourceInputParameter.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NSResourceInputParameter.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.vfcmodel;
-
/**
* NS Create Input Parameter For VFC Adapter<br>
* <p>
@@ -44,7 +43,6 @@ public class NSResourceInputParameter {
-
/**
* @return Returns the nsServiceName.
*/
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NsOperationKey.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NsOperationKey.java
index 81826a27eb..3e35952a9e 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NsOperationKey.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NsOperationKey.java
@@ -21,8 +21,7 @@ package org.onap.so.bpmn.infrastructure.vfcmodel;
/**
- * The operation key object for NS
- * <br>
+ * The operation key object for NS <br>
* <p>
* </p>
*
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NsParameters.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NsParameters.java
index 0d8f2fcbd7..ad388feffc 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NsParameters.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/NsParameters.java
@@ -37,7 +37,8 @@ public class NsParameters {
private List<LocationConstraint> locationConstraints;
- private Map<String, Object> additionalParamForNs = new HashMap<String,Object>();
+ private Map<String, Object> additionalParamForNs = new HashMap<String, Object>();
+
/**
* @return Returns the locationConstraints.
*/
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/VimLocation.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/VimLocation.java
index 970fa43d9f..8b9295b44f 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/VimLocation.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/vfcmodel/VimLocation.java
@@ -28,7 +28,7 @@ package org.onap.so.bpmn.infrastructure.vfcmodel;
* </p>
*
* @author
- * @version ONAP Amsterdam Release 2017-10-18
+ * @version ONAP Amsterdam Release 2017-10-18
*/
public class VimLocation {
private String vimId;
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java
index 9b878afb7c..896a8bd98c 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java
@@ -73,549 +73,550 @@ import org.springframework.web.util.UriUtils;
public class ServicePluginFactory {
- // SOTN calculate route
- public static final String OOF_DEFAULT_ENDPOINT = "http://192.168.1.223:8443/oof/sotncalc";
-
- public static final String THIRD_SP_DEFAULT_ENDPOINT = "http://192.168.1.223:8443/sp/resourcemgr/querytps";
-
- public static final String INVENTORY_OSS_DEFAULT_ENDPOINT = "http://192.168.1.199:8443/oss/inventory";
-
- private static final int DEFAULT_TIME_OUT = 60000;
-
- static JsonUtils jsonUtil = new JsonUtils();
-
- private static Logger logger = LoggerFactory.getLogger(ServicePluginFactory.class);
-
- private static ServicePluginFactory instance;
-
-
- public static synchronized ServicePluginFactory getInstance() {
- if (null == instance) {
- instance = new ServicePluginFactory();
- }
- return instance;
- }
-
- private ServicePluginFactory() {
-
- }
-
- private String getInventoryOSSEndPoint(){
- return UrnPropertiesReader.getVariable("mso.service-plugin.inventory-oss-endpoint", INVENTORY_OSS_DEFAULT_ENDPOINT);
- }
-
- private String getThirdSPEndPoint(){
- return UrnPropertiesReader.getVariable("mso.service-plugin.third-sp-endpoint", THIRD_SP_DEFAULT_ENDPOINT);
- }
-
- private String getOOFCalcEndPoint(){
- return UrnPropertiesReader.getVariable("mso.service-plugin.oof-calc-endpoint", OOF_DEFAULT_ENDPOINT);
- }
-
- @SuppressWarnings("unchecked")
- public String doProcessSiteLocation(ServiceDecomposition serviceDecomposition, String uuiRequest) {
- if(!isNeedProcessSite(uuiRequest)) {
- return uuiRequest;
- }
-
- Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
- if (uuiObject == null) {
- return uuiRequest;
- }
- Map<String, Object> serviceObject = (Map<String, Object>) uuiObject
- .getOrDefault("service", Collections.emptyMap());
- Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject
- .getOrDefault("parameters", Collections.emptyMap());
- Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject
- .getOrDefault("requestInputs", Collections.emptyMap());
- List<Object> resources = (List<Object>) serviceParametersObject.getOrDefault("resources", Collections.emptyList());
-
- if (isSiteLocationLocal(serviceRequestInputs, resources)) {
- // resources changed : added TP info
- return getJsonString(uuiObject);
- }
-
- List<Resource> addResourceList = new ArrayList<>();
- addResourceList.addAll(serviceDecomposition.getServiceResources());
-
- serviceDecomposition.setVnfResources(null);
- serviceDecomposition.setAllottedResources(null);
- serviceDecomposition.setNetworkResources(null);
- serviceDecomposition.setConfigResources(null);
- for (Resource resource : addResourceList) {
- String resourcemodelName = resource.getModelInfo().getModelName();
- if (StringUtils.containsIgnoreCase(resourcemodelName, "sppartner")) {
- // change serviceDecomposition
- serviceDecomposition.addResource(resource);
- break;
- }
- }
-
- return uuiRequest;
- }
-
- private boolean isNeedProcessSite(String uuiRequest) {
- return uuiRequest.toLowerCase().contains("site_address") && uuiRequest.toLowerCase().contains("sotncondition_clientsignal");
- }
-
- @SuppressWarnings("unchecked")
- private boolean isSiteLocationLocal(Map<String, Object> serviceRequestInputs, List<Object> resources) {
- Map<String, Object> tpInfoMap = getTPforVPNAttachment(serviceRequestInputs);
-
- if(tpInfoMap.isEmpty()) {
- return true;
- }
- String host = (String) tpInfoMap.get("host");
- // host is empty means TP is in local, not empty means TP is in remote ONAP
- if (!host.isEmpty()) {
- return false;
- }
-
- Map<String, Object> accessTPInfo = new HashMap<String, Object>();
- accessTPInfo.put("access-provider-id", tpInfoMap.get("access-provider-id"));
- accessTPInfo.put("access-client-id", tpInfoMap.get("access-client-id"));
- accessTPInfo.put("access-topology-id", tpInfoMap.get("access-topology-id"));
- accessTPInfo.put("access-node-id", tpInfoMap.get("access-node-id"));
- accessTPInfo.put("access-ltp-id", tpInfoMap.get("access-ltp-id"));
-
- // change resources
- String resourceName = (String) tpInfoMap.get("resourceName");
- for(Object curResource : resources) {
- Map<String, Object> resource = (Map<String, Object>)curResource;
- String curResourceName = (String) resource.get("resourceName");
- curResourceName = curResourceName.replaceAll(" ", "");
- if(resourceName.equalsIgnoreCase(curResourceName)) {
- putResourceRequestInputs(resource, accessTPInfo);
- break;
- }
- }
-
- return true;
- }
-
- @SuppressWarnings("unchecked")
- private Map<String, Object> getTPforVPNAttachment(Map<String, Object> serviceRequestInputs) {
- Object location = null;
- Object clientSignal = null;
- String vpnAttachmentResourceName = null;
-
- // support R2 uuiReq and R1 uuiReq
- // logic for R2 uuiRequest params in service level
- for (Entry<String, Object> entry : serviceRequestInputs.entrySet()) {
- String key = entry.getKey();
- if (key.toLowerCase().contains("site_address")) {
- location = entry.getValue();
- }
- if (key.toLowerCase().contains("sotncondition_clientsignal")) {
- clientSignal = entry.getValue();
- vpnAttachmentResourceName = key.substring(0, key.indexOf("_"));
- }
- }
-
- Map<String, Object> tpInfoMap = new HashMap<String, Object>();
-
- // Site resource has location param and SOTNAttachment resource has clientSignal param
- if(location == null || clientSignal == null ) {
- return tpInfoMap;
- }
-
- // Query terminal points from InventoryOSS system by location.
- String locationAddress = (String) location;
- List<Object> locationTPList = queryAccessTPbyLocationFromInventoryOSS(locationAddress);
- if(locationTPList != null && !locationTPList.isEmpty()) {
- for(Object tp: locationTPList) {
- Map<String, Object> tpJson = (Map<String, Object>) tp;
- String loc = (String)tpJson.get ("location");
- if(StringUtils.equalsIgnoreCase (locationAddress, loc)) {
- tpInfoMap = tpJson;
- // add resourceName
- tpInfoMap.put("resourceName", vpnAttachmentResourceName);
- break;
- }
- }
- logger.debug("Get Terminal TP from InventoryOSS");
- return tpInfoMap;
- }
-
- return tpInfoMap;
- }
-
- @SuppressWarnings("unchecked")
- private List<Object> queryAccessTPbyLocationFromInventoryOSS(String locationAddress) {
- String url = getInventoryOSSEndPoint();
- url += "/oss/inventory?location=" + UriUtils.encode(locationAddress,"UTF-8");
- String responseContent = sendRequest(url, "GET", "");
- List<Object> accessTPs = new ArrayList<>();
- if (null != responseContent) {
- accessTPs = getJsonObject(responseContent, List.class);
- }
- return accessTPs;
- }
-
- @SuppressWarnings("unchecked")
- private void putResourceRequestInputs(Map<String, Object> resource, Map<String, Object> resourceInputs) {
- Map<String, Object> resourceParametersObject = new HashMap<>();
- Map<String, Object> resourceRequestInputs = new HashMap<>();
- resourceRequestInputs.put("requestInputs", resourceInputs);
- resourceParametersObject.put("parameters", resourceRequestInputs);
-
- if(resource.containsKey("parameters")) {
- Map<String, Object> resParametersObject = (Map<String, Object>) resource.get("parameters");
- if(resParametersObject.containsKey("requestInputs")) {
- Map<String, Object> resRequestInputs = (Map<String, Object>) resourceRequestInputs.get("requestInputs");
- Map<String, Object> oldRequestInputs = (Map<String, Object>) resParametersObject.get("requestInputs");
- if(oldRequestInputs != null) {
- oldRequestInputs.putAll(resRequestInputs);
- }
- else {
- resParametersObject.put("requestInputs", resRequestInputs);
- }
- }
- else {
- resParametersObject.putAll(resourceRequestInputs);
- }
- }
- else {
- resource.putAll(resourceParametersObject);
- }
-
- return;
- }
-
-
-
- @SuppressWarnings("unchecked")
- public String doTPResourcesAllocation(DelegateExecution execution, String uuiRequest) {
- Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
- if (uuiObject == null) {
- return uuiRequest;
- }
- Map<String, Object> serviceObject = (Map<String, Object>) uuiObject
- .getOrDefault("service", Collections.emptyMap());
- Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject
- .getOrDefault("parameters", Collections.emptyMap());
- Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject
- .getOrDefault("requestInputs", Collections.emptyMap());
-
- if (!isNeedAllocateCrossTPResources(serviceRequestInputs)) {
- return uuiRequest;
- }
-
- allocateCrossTPResources(execution, serviceRequestInputs);
- return getJsonString(uuiObject);
- }
-
- @SuppressWarnings("unchecked")
- private boolean isNeedAllocateCrossTPResources(Map<String, Object> serviceRequestInputs) {
- if(serviceRequestInputs.containsKey("CallSource"))
- {
- String callSource = (String) serviceRequestInputs.get("CallSource");
- if("ExternalAPI".equalsIgnoreCase(callSource)) {
- return false;
- }
- }
- for (String input : serviceRequestInputs.keySet())
- {
- if(input.toLowerCase().contains("sotnconnectivity")) {
- return true;
- }
- }
- return false;
- }
-
- @SuppressWarnings("unchecked")
- private void allocateCrossTPResources(DelegateExecution execution, Map<String, Object> serviceRequestInputs) {
-
- Map<String, Object> crossTPs = this.getTPsfromAAI();
-
- if(crossTPs == null || crossTPs.isEmpty()) {
- serviceRequestInputs.put("local-access-provider-id", "");
- serviceRequestInputs.put("local-access-client-id", "");
- serviceRequestInputs.put("local-access-topology-id", "");
- serviceRequestInputs.put("local-access-node-id", "");
- serviceRequestInputs.put("local-access-ltp-id", "");
- serviceRequestInputs.put("remote-access-provider-id", "");
- serviceRequestInputs.put("remote-access-client-id", "");
- serviceRequestInputs.put("remote-access-topology-id", "");
- serviceRequestInputs.put("remote-access-node-id", "");
- serviceRequestInputs.put("remote-access-ltp-id", "");
- }
- else {
- serviceRequestInputs.put("local-access-provider-id", crossTPs.get("local-access-provider-id"));
- serviceRequestInputs.put("local-access-client-id", crossTPs.get("local-access-client-id"));
- serviceRequestInputs.put("local-access-topology-id", crossTPs.get("local-access-topology-id"));
- serviceRequestInputs.put("local-access-node-id", crossTPs.get("local-access-node-id"));
- serviceRequestInputs.put("local-access-ltp-id", crossTPs.get("local-access-ltp-id"));
- serviceRequestInputs.put("remote-access-provider-id", crossTPs.get("remote-access-provider-id"));
- serviceRequestInputs.put("remote-access-client-id", crossTPs.get("remote-client-id"));
- serviceRequestInputs.put("remote-access-topology-id", crossTPs.get("remote-topology-id"));
- serviceRequestInputs.put("remote-access-node-id", crossTPs.get("remote-node-id"));
- serviceRequestInputs.put("remote-access-ltp-id", crossTPs.get("remote-ltp-id"));
- }
-
- return;
- }
-
- // This method returns Local and remote TPs information from AAI
- public Map getTPsfromAAI() {
- Map<String, Object> tpInfo = new HashMap<>();
-
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.LOGICAL_LINK);
- AAIResourcesClient client = new AAIResourcesClient();
- Optional<LogicalLinks> result = client.get(LogicalLinks.class, uri);
-
- if (result.isPresent()) {
- LogicalLinks links = result.get();
- boolean isRemoteLink = false;
-
- links.getLogicalLink();
-
- for (LogicalLink link : links.getLogicalLink()) {
- AAIResultWrapper wrapper = new AAIResultWrapper(link);
- Optional<Relationships> optRelationships = wrapper.getRelationships();
- List<AAIResourceUri> pInterfaces = new ArrayList<>();
- if (optRelationships.isPresent()) {
- Relationships relationships = optRelationships.get();
- if (!relationships.getRelatedAAIUris(AAIObjectType.EXT_AAI_NETWORK).isEmpty()) {
- isRemoteLink = true;
- }
- pInterfaces.addAll(relationships.getRelatedAAIUris(AAIObjectType.P_INTERFACE));
- }
-
- if (isRemoteLink) {
- // find remote p interface
- AAIResourceUri localTP = null;
- AAIResourceUri remoteTP = null;
-
- AAIResourceUri pInterface0 = pInterfaces.get(0);
-
- if (isRemotePInterface(client, pInterface0)) {
- remoteTP = pInterfaces.get(0);
- localTP = pInterfaces.get(1);
- } else {
- localTP = pInterfaces.get(0);
- remoteTP = pInterfaces.get(1);
- }
-
- if (localTP != null && remoteTP != null) {
- // give local tp
- String tpUrl = localTP.build().toString();
- PInterface intfLocal = client.get(PInterface.class, localTP).get();
- tpInfo.put("local-access-node-id", tpUrl.split("/")[6]);
-
- String[] networkRef = intfLocal.getNetworkRef().split("/");
- if (networkRef.length == 6) {
- tpInfo.put("local-access-provider-id", networkRef[1]);
- tpInfo.put("local-access-client-id", networkRef[3]);
- tpInfo.put("local-access-topology-id", networkRef[5]);
- }
- String ltpIdStr = tpUrl.substring(tpUrl.lastIndexOf("/") + 1);
- if (ltpIdStr.contains("-")) {
- tpInfo.put("local-access-ltp-id", ltpIdStr.substring(ltpIdStr.lastIndexOf("-") + 1));
- }
-
- // give remote tp
- tpUrl = remoteTP.build().toString();
- PInterface intfRemote = client.get(PInterface.class, remoteTP).get();
- tpInfo.put("remote-access-node-id", tpUrl.split("/")[6]);
-
- String[] networkRefRemote = intfRemote.getNetworkRef().split("/");
-
- if (networkRefRemote.length == 6) {
- tpInfo.put("remote-access-provider-id", networkRefRemote[1]);
- tpInfo.put("remote-access-client-id", networkRefRemote[3]);
- tpInfo.put("remote-access-topology-id", networkRefRemote[5]);
- }
- String ltpIdStrR = tpUrl.substring(tpUrl.lastIndexOf("/") + 1);
- if (ltpIdStrR.contains("-")) {
- tpInfo.put("remote-access-ltp-id", ltpIdStrR.substring(ltpIdStr.lastIndexOf("-") + 1));
- }
- return tpInfo;
- }
- }
- }
- }
- return tpInfo;
- }
-
- // this method check if pInterface is remote
- private boolean isRemotePInterface(AAIResourcesClient client, AAIResourceUri uri) {
-
- String uriString = uri.build().toString();
-
- if (uriString != null) {
- // get the pnfname
- String[] token = uriString.split("/");
- AAIResourceUri parent = AAIUriFactory.createResourceUri(AAIObjectType.PNF, token[4]);
-
- AAIResultWrapper wrapper = client.get(parent);
- Optional<Relationships> optRelationships = wrapper.getRelationships();
- if (optRelationships.isPresent()) {
- Relationships relationships = optRelationships.get();
-
- return !relationships.getRelatedAAIUris(AAIObjectType.EXT_AAI_NETWORK).isEmpty();
- }
- }
-
- return false;
- }
-
- public String preProcessService(ServiceDecomposition serviceDecomposition, String uuiRequest) {
-
- // now only for sotn
- if (isSOTN(serviceDecomposition, uuiRequest)) {
- // We Need to query the terminalpoint of the VPN by site location
- // info
- return preProcessSOTNService(serviceDecomposition, uuiRequest);
- }
- return uuiRequest;
- }
-
- public String doServiceHoming(ServiceDecomposition serviceDecomposition, String uuiRequest) {
- // now only for sotn
- if (isSOTN(serviceDecomposition, uuiRequest)) {
- return doSOTNServiceHoming(serviceDecomposition, uuiRequest);
- }
- return uuiRequest;
- }
-
- private boolean isSOTN(ServiceDecomposition serviceDecomposition, String uuiRequest) {
- // there should be a register platform , we check it very simple here.
- return uuiRequest.contains("clientSignal") && uuiRequest.contains("vpnType");
- }
-
- @SuppressWarnings("unchecked")
- private String preProcessSOTNService(ServiceDecomposition serviceDecomposition, String uuiRequest) {
- Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
- if (uuiObject == null) {
- return uuiRequest;
- }
- Map<String, Object> serviceObject = (Map<String, Object>) uuiObject
- .getOrDefault("service", Collections.emptyMap());
- Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject
- .getOrDefault("parameters", Collections.emptyMap());
- Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject
- .getOrDefault("requestInputs", Collections.emptyMap());
- List<Object> resources = (List<Object>) serviceParametersObject.getOrDefault("resources", Collections.emptyList());
- // This is a logic for demo , it could not be finalized to community.
- String srcLocation = "";
- String dstLocation = "";
- String srcClientSignal = "";
- String dstClientSignal = "";
- // support R2 uuiReq and R1 uuiReq
- // logic for R2 uuiRequest params in service level
- for (Entry<String, Object> entry : serviceRequestInputs.entrySet()) {
- if (entry.getKey().toLowerCase().contains("location")) {
- if ("".equals(srcLocation)) {
- srcLocation = (String) entry.getValue();
- } else if ("".equals(dstLocation)) {
- dstLocation = (String) entry.getValue();
- }
- }
- if (entry.getKey().toLowerCase().contains("clientsignal")) {
- if ("".equals(srcClientSignal)) {
- srcClientSignal = (String) entry.getValue();
- } else if ("".equals(dstClientSignal)) {
- dstClientSignal = (String) entry.getValue();
- }
- }
- }
-
- // logic for R1 uuiRequest, params in resource level
- for (Object resource : resources) {
- Map<String, Object> resourceObject = (Map<String, Object>) resource;
- Map<String, Object> resourceParametersObject = (Map<String, Object>) resourceObject.get("parameters");
- Map<String, Object> resourceRequestInputs = (Map<String, Object>) resourceParametersObject.get("requestInputs");
- for (Entry<String, Object> entry : resourceRequestInputs.entrySet()) {
- if (entry.getKey().toLowerCase().contains("location")) {
- if ("".equals(srcLocation)) {
- srcLocation = (String) entry.getValue();
- } else if ("".equals(dstLocation)) {
- dstLocation = (String) entry.getValue();
- }
- }
- if (entry.getKey().toLowerCase().contains("clientsignal")) {
- if ("".equals(srcClientSignal)) {
- srcClientSignal = (String) entry.getValue();
- } else if ("".equals(dstClientSignal)) {
- dstClientSignal = (String) entry.getValue();
- }
- }
- }
- }
-
- Map<String, Object> vpnRequestInputs = getVPNResourceRequestInputs(resources);
- // here we put client signal to vpn resource inputs
- if(null!=vpnRequestInputs) {
- vpnRequestInputs.put("src-client-signal", srcClientSignal);
- vpnRequestInputs.put("dst-client-signal", dstClientSignal);
- }
-
-
- // Now we need to query terminal points from SP resourcemgr system.
- List<Object> locationTerminalPointList = queryTerminalPointsFromServiceProviderSystem(srcLocation, dstLocation);
- Map<String, Object> tpInfoMap = (Map<String, Object>) locationTerminalPointList.get(0);
-
- serviceRequestInputs.put("inner-src-access-provider-id", tpInfoMap.get("access-provider-id"));
- serviceRequestInputs.put("inner-src-access-client-id", tpInfoMap.get("access-client-id"));
- serviceRequestInputs.put("inner-src-access-topology-id", tpInfoMap.get("access-topology-id"));
- serviceRequestInputs.put("inner-src-access-node-id", tpInfoMap.get("access-node-id"));
- serviceRequestInputs.put("inner-src-access-ltp-id", tpInfoMap.get("access-ltp-id"));
- tpInfoMap = (Map<String, Object>) locationTerminalPointList.get(1);
-
- serviceRequestInputs.put("inner-dst-access-provider-id", tpInfoMap.get("access-provider-id"));
- serviceRequestInputs.put("inner-dst-access-client-id", tpInfoMap.get("access-client-id"));
- serviceRequestInputs.put("inner-dst-access-topology-id", tpInfoMap.get("access-topology-id"));
- serviceRequestInputs.put("inner-dst-access-node-id", tpInfoMap.get("access-node-id"));
- serviceRequestInputs.put("inner-dst-access-ltp-id", tpInfoMap.get("access-ltp-id"));
-
- String newRequest = getJsonString(uuiObject);
- return newRequest;
- }
-
- private List<Object> queryTerminalPointsFromServiceProviderSystem(String srcLocation, String dstLocation) {
- Map<String, String> locationSrc = new HashMap<>();
- locationSrc.put("location", srcLocation);
- Map<String, String> locationDst = new HashMap<>();
- locationDst.put("location", dstLocation);
- List<Map<String, String>> locations = new ArrayList<>();
- locations.add(locationSrc);
- locations.add(locationDst);
- List<Object> returnList = new ArrayList<>();
- String reqContent = getJsonString(locations);
- String url = getThirdSPEndPoint();
- String responseContent = sendRequest(url, "POST", reqContent);
- if (null != responseContent) {
- returnList = getJsonObject(responseContent, List.class);
- }
- return returnList;
- }
-
- @SuppressWarnings("unchecked")
- private Map<String, Object> getVPNResourceRequestInputs(List<Object> resources) {
- for (Object resource : resources) {
- Map<String, Object> resourceObject = (Map<String, Object>) resource;
- Map<String, Object> resourceParametersObject = (Map<String, Object>) resourceObject.get("parameters");
- Map<String, Object> resourceRequestInputs = (Map<String, Object>) resourceParametersObject.get("requestInputs");
- for (Entry<String, Object> entry : resourceRequestInputs.entrySet()) {
- if (entry.getKey().toLowerCase().contains("vpntype")) {
- return resourceRequestInputs;
- }
- }
- }
- return null;
- }
-
- public static void main(String args[]){
- String str = "restconf/config/GENERIC-RESOURCE-API:services/service/eca7e542-12ba-48de-8544-fac59303b14e/service-data/networks/network/aec07806-1671-4af2-b722-53c8e320a633/network-data/";
-
- int index1 = str.indexOf("/network/");
- int index2 = str.indexOf("/network-data");
-
- String str1 = str.substring(index1 + "/network/".length(), index2);
- System.out.println(str1);
-
- }
+ // SOTN calculate route
+ public static final String OOF_DEFAULT_ENDPOINT = "http://192.168.1.223:8443/oof/sotncalc";
+
+ public static final String THIRD_SP_DEFAULT_ENDPOINT = "http://192.168.1.223:8443/sp/resourcemgr/querytps";
+
+ public static final String INVENTORY_OSS_DEFAULT_ENDPOINT = "http://192.168.1.199:8443/oss/inventory";
+
+ private static final int DEFAULT_TIME_OUT = 60000;
+
+ static JsonUtils jsonUtil = new JsonUtils();
+
+ private static Logger logger = LoggerFactory.getLogger(ServicePluginFactory.class);
+
+ private static ServicePluginFactory instance;
+
+
+ public static synchronized ServicePluginFactory getInstance() {
+ if (null == instance) {
+ instance = new ServicePluginFactory();
+ }
+ return instance;
+ }
+
+ private ServicePluginFactory() {
+
+ }
+
+ private String getInventoryOSSEndPoint() {
+ return UrnPropertiesReader.getVariable("mso.service-plugin.inventory-oss-endpoint",
+ INVENTORY_OSS_DEFAULT_ENDPOINT);
+ }
+
+ private String getThirdSPEndPoint() {
+ return UrnPropertiesReader.getVariable("mso.service-plugin.third-sp-endpoint", THIRD_SP_DEFAULT_ENDPOINT);
+ }
+
+ private String getOOFCalcEndPoint() {
+ return UrnPropertiesReader.getVariable("mso.service-plugin.oof-calc-endpoint", OOF_DEFAULT_ENDPOINT);
+ }
+
+ @SuppressWarnings("unchecked")
+ public String doProcessSiteLocation(ServiceDecomposition serviceDecomposition, String uuiRequest) {
+ if (!isNeedProcessSite(uuiRequest)) {
+ return uuiRequest;
+ }
+
+ Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
+ if (uuiObject == null) {
+ return uuiRequest;
+ }
+ Map<String, Object> serviceObject =
+ (Map<String, Object>) uuiObject.getOrDefault("service", Collections.emptyMap());
+ Map<String, Object> serviceParametersObject =
+ (Map<String, Object>) serviceObject.getOrDefault("parameters", Collections.emptyMap());
+ Map<String, Object> serviceRequestInputs =
+ (Map<String, Object>) serviceParametersObject.getOrDefault("requestInputs", Collections.emptyMap());
+ List<Object> resources =
+ (List<Object>) serviceParametersObject.getOrDefault("resources", Collections.emptyList());
+
+ if (isSiteLocationLocal(serviceRequestInputs, resources)) {
+ // resources changed : added TP info
+ return getJsonString(uuiObject);
+ }
+
+ List<Resource> addResourceList = new ArrayList<>();
+ addResourceList.addAll(serviceDecomposition.getServiceResources());
+
+ serviceDecomposition.setVnfResources(null);
+ serviceDecomposition.setAllottedResources(null);
+ serviceDecomposition.setNetworkResources(null);
+ serviceDecomposition.setConfigResources(null);
+ for (Resource resource : addResourceList) {
+ String resourcemodelName = resource.getModelInfo().getModelName();
+ if (StringUtils.containsIgnoreCase(resourcemodelName, "sppartner")) {
+ // change serviceDecomposition
+ serviceDecomposition.addResource(resource);
+ break;
+ }
+ }
+
+ return uuiRequest;
+ }
+
+ private boolean isNeedProcessSite(String uuiRequest) {
+ return uuiRequest.toLowerCase().contains("site_address")
+ && uuiRequest.toLowerCase().contains("sotncondition_clientsignal");
+ }
+
+ @SuppressWarnings("unchecked")
+ private boolean isSiteLocationLocal(Map<String, Object> serviceRequestInputs, List<Object> resources) {
+ Map<String, Object> tpInfoMap = getTPforVPNAttachment(serviceRequestInputs);
+
+ if (tpInfoMap.isEmpty()) {
+ return true;
+ }
+ String host = (String) tpInfoMap.get("host");
+ // host is empty means TP is in local, not empty means TP is in remote ONAP
+ if (!host.isEmpty()) {
+ return false;
+ }
+
+ Map<String, Object> accessTPInfo = new HashMap<String, Object>();
+ accessTPInfo.put("access-provider-id", tpInfoMap.get("access-provider-id"));
+ accessTPInfo.put("access-client-id", tpInfoMap.get("access-client-id"));
+ accessTPInfo.put("access-topology-id", tpInfoMap.get("access-topology-id"));
+ accessTPInfo.put("access-node-id", tpInfoMap.get("access-node-id"));
+ accessTPInfo.put("access-ltp-id", tpInfoMap.get("access-ltp-id"));
+
+ // change resources
+ String resourceName = (String) tpInfoMap.get("resourceName");
+ for (Object curResource : resources) {
+ Map<String, Object> resource = (Map<String, Object>) curResource;
+ String curResourceName = (String) resource.get("resourceName");
+ curResourceName = curResourceName.replaceAll(" ", "");
+ if (resourceName.equalsIgnoreCase(curResourceName)) {
+ putResourceRequestInputs(resource, accessTPInfo);
+ break;
+ }
+ }
+
+ return true;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Map<String, Object> getTPforVPNAttachment(Map<String, Object> serviceRequestInputs) {
+ Object location = null;
+ Object clientSignal = null;
+ String vpnAttachmentResourceName = null;
+
+ // support R2 uuiReq and R1 uuiReq
+ // logic for R2 uuiRequest params in service level
+ for (Entry<String, Object> entry : serviceRequestInputs.entrySet()) {
+ String key = entry.getKey();
+ if (key.toLowerCase().contains("site_address")) {
+ location = entry.getValue();
+ }
+ if (key.toLowerCase().contains("sotncondition_clientsignal")) {
+ clientSignal = entry.getValue();
+ vpnAttachmentResourceName = key.substring(0, key.indexOf("_"));
+ }
+ }
+
+ Map<String, Object> tpInfoMap = new HashMap<String, Object>();
+
+ // Site resource has location param and SOTNAttachment resource has clientSignal param
+ if (location == null || clientSignal == null) {
+ return tpInfoMap;
+ }
+
+ // Query terminal points from InventoryOSS system by location.
+ String locationAddress = (String) location;
+ List<Object> locationTPList = queryAccessTPbyLocationFromInventoryOSS(locationAddress);
+ if (locationTPList != null && !locationTPList.isEmpty()) {
+ for (Object tp : locationTPList) {
+ Map<String, Object> tpJson = (Map<String, Object>) tp;
+ String loc = (String) tpJson.get("location");
+ if (StringUtils.equalsIgnoreCase(locationAddress, loc)) {
+ tpInfoMap = tpJson;
+ // add resourceName
+ tpInfoMap.put("resourceName", vpnAttachmentResourceName);
+ break;
+ }
+ }
+ logger.debug("Get Terminal TP from InventoryOSS");
+ return tpInfoMap;
+ }
+
+ return tpInfoMap;
+ }
+
+ @SuppressWarnings("unchecked")
+ private List<Object> queryAccessTPbyLocationFromInventoryOSS(String locationAddress) {
+ String url = getInventoryOSSEndPoint();
+ url += "/oss/inventory?location=" + UriUtils.encode(locationAddress, "UTF-8");
+ String responseContent = sendRequest(url, "GET", "");
+ List<Object> accessTPs = new ArrayList<>();
+ if (null != responseContent) {
+ accessTPs = getJsonObject(responseContent, List.class);
+ }
+ return accessTPs;
+ }
+
+ @SuppressWarnings("unchecked")
+ private void putResourceRequestInputs(Map<String, Object> resource, Map<String, Object> resourceInputs) {
+ Map<String, Object> resourceParametersObject = new HashMap<>();
+ Map<String, Object> resourceRequestInputs = new HashMap<>();
+ resourceRequestInputs.put("requestInputs", resourceInputs);
+ resourceParametersObject.put("parameters", resourceRequestInputs);
+
+ if (resource.containsKey("parameters")) {
+ Map<String, Object> resParametersObject = (Map<String, Object>) resource.get("parameters");
+ if (resParametersObject.containsKey("requestInputs")) {
+ Map<String, Object> resRequestInputs = (Map<String, Object>) resourceRequestInputs.get("requestInputs");
+ Map<String, Object> oldRequestInputs = (Map<String, Object>) resParametersObject.get("requestInputs");
+ if (oldRequestInputs != null) {
+ oldRequestInputs.putAll(resRequestInputs);
+ } else {
+ resParametersObject.put("requestInputs", resRequestInputs);
+ }
+ } else {
+ resParametersObject.putAll(resourceRequestInputs);
+ }
+ } else {
+ resource.putAll(resourceParametersObject);
+ }
+
+ return;
+ }
+
+
+
+ @SuppressWarnings("unchecked")
+ public String doTPResourcesAllocation(DelegateExecution execution, String uuiRequest) {
+ Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
+ if (uuiObject == null) {
+ return uuiRequest;
+ }
+ Map<String, Object> serviceObject =
+ (Map<String, Object>) uuiObject.getOrDefault("service", Collections.emptyMap());
+ Map<String, Object> serviceParametersObject =
+ (Map<String, Object>) serviceObject.getOrDefault("parameters", Collections.emptyMap());
+ Map<String, Object> serviceRequestInputs =
+ (Map<String, Object>) serviceParametersObject.getOrDefault("requestInputs", Collections.emptyMap());
+
+ if (!isNeedAllocateCrossTPResources(serviceRequestInputs)) {
+ return uuiRequest;
+ }
+
+ allocateCrossTPResources(execution, serviceRequestInputs);
+ return getJsonString(uuiObject);
+ }
+
+ @SuppressWarnings("unchecked")
+ private boolean isNeedAllocateCrossTPResources(Map<String, Object> serviceRequestInputs) {
+ if (serviceRequestInputs.containsKey("CallSource")) {
+ String callSource = (String) serviceRequestInputs.get("CallSource");
+ if ("ExternalAPI".equalsIgnoreCase(callSource)) {
+ return false;
+ }
+ }
+ for (String input : serviceRequestInputs.keySet()) {
+ if (input.toLowerCase().contains("sotnconnectivity")) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @SuppressWarnings("unchecked")
+ private void allocateCrossTPResources(DelegateExecution execution, Map<String, Object> serviceRequestInputs) {
+
+ Map<String, Object> crossTPs = this.getTPsfromAAI();
+
+ if (crossTPs == null || crossTPs.isEmpty()) {
+ serviceRequestInputs.put("local-access-provider-id", "");
+ serviceRequestInputs.put("local-access-client-id", "");
+ serviceRequestInputs.put("local-access-topology-id", "");
+ serviceRequestInputs.put("local-access-node-id", "");
+ serviceRequestInputs.put("local-access-ltp-id", "");
+ serviceRequestInputs.put("remote-access-provider-id", "");
+ serviceRequestInputs.put("remote-access-client-id", "");
+ serviceRequestInputs.put("remote-access-topology-id", "");
+ serviceRequestInputs.put("remote-access-node-id", "");
+ serviceRequestInputs.put("remote-access-ltp-id", "");
+ } else {
+ serviceRequestInputs.put("local-access-provider-id", crossTPs.get("local-access-provider-id"));
+ serviceRequestInputs.put("local-access-client-id", crossTPs.get("local-access-client-id"));
+ serviceRequestInputs.put("local-access-topology-id", crossTPs.get("local-access-topology-id"));
+ serviceRequestInputs.put("local-access-node-id", crossTPs.get("local-access-node-id"));
+ serviceRequestInputs.put("local-access-ltp-id", crossTPs.get("local-access-ltp-id"));
+ serviceRequestInputs.put("remote-access-provider-id", crossTPs.get("remote-access-provider-id"));
+ serviceRequestInputs.put("remote-access-client-id", crossTPs.get("remote-client-id"));
+ serviceRequestInputs.put("remote-access-topology-id", crossTPs.get("remote-topology-id"));
+ serviceRequestInputs.put("remote-access-node-id", crossTPs.get("remote-node-id"));
+ serviceRequestInputs.put("remote-access-ltp-id", crossTPs.get("remote-ltp-id"));
+ }
+
+ return;
+ }
+
+ // This method returns Local and remote TPs information from AAI
+ public Map getTPsfromAAI() {
+ Map<String, Object> tpInfo = new HashMap<>();
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.LOGICAL_LINK);
+ AAIResourcesClient client = new AAIResourcesClient();
+ Optional<LogicalLinks> result = client.get(LogicalLinks.class, uri);
+
+ if (result.isPresent()) {
+ LogicalLinks links = result.get();
+ boolean isRemoteLink = false;
+
+ links.getLogicalLink();
+
+ for (LogicalLink link : links.getLogicalLink()) {
+ AAIResultWrapper wrapper = new AAIResultWrapper(link);
+ Optional<Relationships> optRelationships = wrapper.getRelationships();
+ List<AAIResourceUri> pInterfaces = new ArrayList<>();
+ if (optRelationships.isPresent()) {
+ Relationships relationships = optRelationships.get();
+ if (!relationships.getRelatedAAIUris(AAIObjectType.EXT_AAI_NETWORK).isEmpty()) {
+ isRemoteLink = true;
+ }
+ pInterfaces.addAll(relationships.getRelatedAAIUris(AAIObjectType.P_INTERFACE));
+ }
+
+ if (isRemoteLink) {
+ // find remote p interface
+ AAIResourceUri localTP = null;
+ AAIResourceUri remoteTP = null;
+
+ AAIResourceUri pInterface0 = pInterfaces.get(0);
+
+ if (isRemotePInterface(client, pInterface0)) {
+ remoteTP = pInterfaces.get(0);
+ localTP = pInterfaces.get(1);
+ } else {
+ localTP = pInterfaces.get(0);
+ remoteTP = pInterfaces.get(1);
+ }
+
+ if (localTP != null && remoteTP != null) {
+ // give local tp
+ String tpUrl = localTP.build().toString();
+ PInterface intfLocal = client.get(PInterface.class, localTP).get();
+ tpInfo.put("local-access-node-id", tpUrl.split("/")[6]);
+
+ String[] networkRef = intfLocal.getNetworkRef().split("/");
+ if (networkRef.length == 6) {
+ tpInfo.put("local-access-provider-id", networkRef[1]);
+ tpInfo.put("local-access-client-id", networkRef[3]);
+ tpInfo.put("local-access-topology-id", networkRef[5]);
+ }
+ String ltpIdStr = tpUrl.substring(tpUrl.lastIndexOf("/") + 1);
+ if (ltpIdStr.contains("-")) {
+ tpInfo.put("local-access-ltp-id", ltpIdStr.substring(ltpIdStr.lastIndexOf("-") + 1));
+ }
+
+ // give remote tp
+ tpUrl = remoteTP.build().toString();
+ PInterface intfRemote = client.get(PInterface.class, remoteTP).get();
+ tpInfo.put("remote-access-node-id", tpUrl.split("/")[6]);
+
+ String[] networkRefRemote = intfRemote.getNetworkRef().split("/");
+
+ if (networkRefRemote.length == 6) {
+ tpInfo.put("remote-access-provider-id", networkRefRemote[1]);
+ tpInfo.put("remote-access-client-id", networkRefRemote[3]);
+ tpInfo.put("remote-access-topology-id", networkRefRemote[5]);
+ }
+ String ltpIdStrR = tpUrl.substring(tpUrl.lastIndexOf("/") + 1);
+ if (ltpIdStrR.contains("-")) {
+ tpInfo.put("remote-access-ltp-id", ltpIdStrR.substring(ltpIdStr.lastIndexOf("-") + 1));
+ }
+ return tpInfo;
+ }
+ }
+ }
+ }
+ return tpInfo;
+ }
+
+ // this method check if pInterface is remote
+ private boolean isRemotePInterface(AAIResourcesClient client, AAIResourceUri uri) {
+
+ String uriString = uri.build().toString();
+
+ if (uriString != null) {
+ // get the pnfname
+ String[] token = uriString.split("/");
+ AAIResourceUri parent = AAIUriFactory.createResourceUri(AAIObjectType.PNF, token[4]);
+
+ AAIResultWrapper wrapper = client.get(parent);
+ Optional<Relationships> optRelationships = wrapper.getRelationships();
+ if (optRelationships.isPresent()) {
+ Relationships relationships = optRelationships.get();
+
+ return !relationships.getRelatedAAIUris(AAIObjectType.EXT_AAI_NETWORK).isEmpty();
+ }
+ }
+
+ return false;
+ }
+
+ public String preProcessService(ServiceDecomposition serviceDecomposition, String uuiRequest) {
+
+ // now only for sotn
+ if (isSOTN(serviceDecomposition, uuiRequest)) {
+ // We Need to query the terminalpoint of the VPN by site location
+ // info
+ return preProcessSOTNService(serviceDecomposition, uuiRequest);
+ }
+ return uuiRequest;
+ }
+
+ public String doServiceHoming(ServiceDecomposition serviceDecomposition, String uuiRequest) {
+ // now only for sotn
+ if (isSOTN(serviceDecomposition, uuiRequest)) {
+ return doSOTNServiceHoming(serviceDecomposition, uuiRequest);
+ }
+ return uuiRequest;
+ }
+
+ private boolean isSOTN(ServiceDecomposition serviceDecomposition, String uuiRequest) {
+ // there should be a register platform , we check it very simple here.
+ return uuiRequest.contains("clientSignal") && uuiRequest.contains("vpnType");
+ }
+
+ @SuppressWarnings("unchecked")
+ private String preProcessSOTNService(ServiceDecomposition serviceDecomposition, String uuiRequest) {
+ Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
+ if (uuiObject == null) {
+ return uuiRequest;
+ }
+ Map<String, Object> serviceObject =
+ (Map<String, Object>) uuiObject.getOrDefault("service", Collections.emptyMap());
+ Map<String, Object> serviceParametersObject =
+ (Map<String, Object>) serviceObject.getOrDefault("parameters", Collections.emptyMap());
+ Map<String, Object> serviceRequestInputs =
+ (Map<String, Object>) serviceParametersObject.getOrDefault("requestInputs", Collections.emptyMap());
+ List<Object> resources =
+ (List<Object>) serviceParametersObject.getOrDefault("resources", Collections.emptyList());
+ // This is a logic for demo , it could not be finalized to community.
+ String srcLocation = "";
+ String dstLocation = "";
+ String srcClientSignal = "";
+ String dstClientSignal = "";
+ // support R2 uuiReq and R1 uuiReq
+ // logic for R2 uuiRequest params in service level
+ for (Entry<String, Object> entry : serviceRequestInputs.entrySet()) {
+ if (entry.getKey().toLowerCase().contains("location")) {
+ if ("".equals(srcLocation)) {
+ srcLocation = (String) entry.getValue();
+ } else if ("".equals(dstLocation)) {
+ dstLocation = (String) entry.getValue();
+ }
+ }
+ if (entry.getKey().toLowerCase().contains("clientsignal")) {
+ if ("".equals(srcClientSignal)) {
+ srcClientSignal = (String) entry.getValue();
+ } else if ("".equals(dstClientSignal)) {
+ dstClientSignal = (String) entry.getValue();
+ }
+ }
+ }
+
+ // logic for R1 uuiRequest, params in resource level
+ for (Object resource : resources) {
+ Map<String, Object> resourceObject = (Map<String, Object>) resource;
+ Map<String, Object> resourceParametersObject = (Map<String, Object>) resourceObject.get("parameters");
+ Map<String, Object> resourceRequestInputs =
+ (Map<String, Object>) resourceParametersObject.get("requestInputs");
+ for (Entry<String, Object> entry : resourceRequestInputs.entrySet()) {
+ if (entry.getKey().toLowerCase().contains("location")) {
+ if ("".equals(srcLocation)) {
+ srcLocation = (String) entry.getValue();
+ } else if ("".equals(dstLocation)) {
+ dstLocation = (String) entry.getValue();
+ }
+ }
+ if (entry.getKey().toLowerCase().contains("clientsignal")) {
+ if ("".equals(srcClientSignal)) {
+ srcClientSignal = (String) entry.getValue();
+ } else if ("".equals(dstClientSignal)) {
+ dstClientSignal = (String) entry.getValue();
+ }
+ }
+ }
+ }
+
+ Map<String, Object> vpnRequestInputs = getVPNResourceRequestInputs(resources);
+ // here we put client signal to vpn resource inputs
+ if (null != vpnRequestInputs) {
+ vpnRequestInputs.put("src-client-signal", srcClientSignal);
+ vpnRequestInputs.put("dst-client-signal", dstClientSignal);
+ }
+
+
+ // Now we need to query terminal points from SP resourcemgr system.
+ List<Object> locationTerminalPointList = queryTerminalPointsFromServiceProviderSystem(srcLocation, dstLocation);
+ Map<String, Object> tpInfoMap = (Map<String, Object>) locationTerminalPointList.get(0);
+
+ serviceRequestInputs.put("inner-src-access-provider-id", tpInfoMap.get("access-provider-id"));
+ serviceRequestInputs.put("inner-src-access-client-id", tpInfoMap.get("access-client-id"));
+ serviceRequestInputs.put("inner-src-access-topology-id", tpInfoMap.get("access-topology-id"));
+ serviceRequestInputs.put("inner-src-access-node-id", tpInfoMap.get("access-node-id"));
+ serviceRequestInputs.put("inner-src-access-ltp-id", tpInfoMap.get("access-ltp-id"));
+ tpInfoMap = (Map<String, Object>) locationTerminalPointList.get(1);
+
+ serviceRequestInputs.put("inner-dst-access-provider-id", tpInfoMap.get("access-provider-id"));
+ serviceRequestInputs.put("inner-dst-access-client-id", tpInfoMap.get("access-client-id"));
+ serviceRequestInputs.put("inner-dst-access-topology-id", tpInfoMap.get("access-topology-id"));
+ serviceRequestInputs.put("inner-dst-access-node-id", tpInfoMap.get("access-node-id"));
+ serviceRequestInputs.put("inner-dst-access-ltp-id", tpInfoMap.get("access-ltp-id"));
+
+ String newRequest = getJsonString(uuiObject);
+ return newRequest;
+ }
+
+ private List<Object> queryTerminalPointsFromServiceProviderSystem(String srcLocation, String dstLocation) {
+ Map<String, String> locationSrc = new HashMap<>();
+ locationSrc.put("location", srcLocation);
+ Map<String, String> locationDst = new HashMap<>();
+ locationDst.put("location", dstLocation);
+ List<Map<String, String>> locations = new ArrayList<>();
+ locations.add(locationSrc);
+ locations.add(locationDst);
+ List<Object> returnList = new ArrayList<>();
+ String reqContent = getJsonString(locations);
+ String url = getThirdSPEndPoint();
+ String responseContent = sendRequest(url, "POST", reqContent);
+ if (null != responseContent) {
+ returnList = getJsonObject(responseContent, List.class);
+ }
+ return returnList;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Map<String, Object> getVPNResourceRequestInputs(List<Object> resources) {
+ for (Object resource : resources) {
+ Map<String, Object> resourceObject = (Map<String, Object>) resource;
+ Map<String, Object> resourceParametersObject = (Map<String, Object>) resourceObject.get("parameters");
+ Map<String, Object> resourceRequestInputs =
+ (Map<String, Object>) resourceParametersObject.get("requestInputs");
+ for (Entry<String, Object> entry : resourceRequestInputs.entrySet()) {
+ if (entry.getKey().toLowerCase().contains("vpntype")) {
+ return resourceRequestInputs;
+ }
+ }
+ }
+ return null;
+ }
+
+ public static void main(String args[]) {
+ String str =
+ "restconf/config/GENERIC-RESOURCE-API:services/service/eca7e542-12ba-48de-8544-fac59303b14e/service-data/networks/network/aec07806-1671-4af2-b722-53c8e320a633/network-data/";
+
+ int index1 = str.indexOf("/network/");
+ int index2 = str.indexOf("/network-data");
+
+ String str1 = str.substring(index1 + "/network/".length(), index2);
+ System.out.println(str1);
+
+ }
@SuppressWarnings("unchecked")
private String doSOTNServiceHoming(ServiceDecomposition serviceDecomposition, String uuiRequest) {
@@ -624,15 +625,15 @@ public class ServicePluginFactory {
if (uuiObject == null) {
return uuiRequest;
}
- Map<String, Object> serviceObject = (Map<String, Object>) uuiObject
- .getOrDefault("service", Collections.emptyMap());
- Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject
- .getOrDefault("parameters", Collections.emptyMap());
- Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject
- .getOrDefault("requestInputs", Collections.emptyMap());
+ Map<String, Object> serviceObject =
+ (Map<String, Object>) uuiObject.getOrDefault("service", Collections.emptyMap());
+ Map<String, Object> serviceParametersObject =
+ (Map<String, Object>) serviceObject.getOrDefault("parameters", Collections.emptyMap());
+ Map<String, Object> serviceRequestInputs =
+ (Map<String, Object>) serviceParametersObject.getOrDefault("requestInputs", Collections.emptyMap());
Map<String, Object> oofQueryObject = new HashMap<>();
- List<Object> resources = (List<Object>) serviceParametersObject
- .getOrDefault("resources", Collections.emptyList());
+ List<Object> resources =
+ (List<Object>) serviceParametersObject.getOrDefault("resources", Collections.emptyList());
oofQueryObject.put("src-access-provider-id", serviceRequestInputs.get("inner-src-access-provider-id"));
oofQueryObject.put("src-access-client-id", serviceRequestInputs.get("inner-src-access-client-id"));
oofQueryObject.put("src-access-topology-id", serviceRequestInputs.get("inner-src-access-topology-id"));
@@ -660,147 +661,144 @@ public class ServicePluginFactory {
return getJsonString(uuiObject);
}
- private Map<String, Object> getReturnRoute(List<Object> returnList){
- Map<String, Object> returnRoute = new HashMap<>();
- for(Object returnVpn :returnList){
- Map<String, Object> returnVpnInfo = (Map<String, Object>) returnVpn;
- String accessTopoId = (String)returnVpnInfo.get("access-topology-id");
- if("100".equals(accessTopoId)){
- returnRoute.putAll(returnVpnInfo);
- }
- else if("101".equals(accessTopoId)){
- for(String key : returnVpnInfo.keySet()){
- returnRoute.put("domain1-" + key, returnVpnInfo.get(key));
- }
- }
- else if("102".equals(accessTopoId)){
- for(String key : returnVpnInfo.keySet()){
- returnRoute.put("domain2-" + key, returnVpnInfo.get(key));
- }
- }
- else{
- for(String key : returnVpnInfo.keySet()){
- returnRoute.put("domain" + accessTopoId +"-" + key, returnVpnInfo.get(key));
- }
- }
- }
- return returnRoute;
- }
-
- private Map<String, Object> getResourceParams(Execution execution, String resourceCustomizationUuid,
- String serviceParameters) {
- List<String> resourceList = jsonUtil.StringArrayToList(execution,
- JsonUtils.getJsonValue(serviceParameters, "resources"));
- // Get the right location str for resource. default is an empty array.
- String resourceInputsFromUui = "";
- for (String resource : resourceList) {
- String resCusUuid = JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
- if (resourceCustomizationUuid.equals(resCusUuid)) {
- String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
- resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
- }
- }
- Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
- return resourceInputsFromUuiMap;
- }
-
- private static <T> T getJsonObject(String jsonstr, Class<T> type) {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
- try {
- return mapper.readValue(jsonstr, type);
- } catch (IOException e) {
- logger.error("{} {} fail to unMarshal json", MessageEnum.RA_NS_EXC.toString(),
- ErrorCode.BusinessProcesssError.getValue(), e);
- }
- return null;
- }
-
- public static String getJsonString(Object srcObj) {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
- String jsonStr = null;
- try {
- jsonStr = mapper.writeValueAsString(srcObj);
- } catch (JsonProcessingException e) {
- logger.debug("SdcToscaParserException", e);
- }
- return jsonStr;
- }
-
- private static String sendRequest(String url, String methodType, String content) {
-
- String msbUrl = url;
- HttpRequestBase method = null;
- HttpResponse httpResponse = null;
-
- try {
- int timeout = DEFAULT_TIME_OUT;
-
- RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
- .setConnectionRequestTimeout(timeout).build();
-
- HttpClient client = HttpClientBuilder.create().build();
-
- if ("POST".equals(methodType.toUpperCase())) {
- HttpPost httpPost = new HttpPost(msbUrl);
- httpPost.setConfig(requestConfig);
- httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
- method = httpPost;
- } else if ("PUT".equals(methodType.toUpperCase())) {
- HttpPut httpPut = new HttpPut(msbUrl);
- httpPut.setConfig(requestConfig);
- httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
- method = httpPut;
- } else if ("GET".equals(methodType.toUpperCase())) {
- HttpGet httpGet = new HttpGet(msbUrl);
- httpGet.setConfig(requestConfig);
- httpGet.addHeader("X-FromAppId", "MSO");
- httpGet.addHeader("Accept","application/json");
- method = httpGet;
- } else if ("DELETE".equals(methodType.toUpperCase())) {
- HttpDelete httpDelete = new HttpDelete(msbUrl);
- httpDelete.setConfig(requestConfig);
- method = httpDelete;
- }
-
- httpResponse = client.execute(method);
- String responseContent = null;
- if (null != httpResponse && httpResponse.getEntity() != null) {
- try {
- responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
- } catch (ParseException e) {
- logger.debug("ParseException in sendrequest", e);
- } catch (IOException e) {
- logger.debug("IOException in sendrequest", e);
- }
- }
- if (null != method) {
- method.reset();
- }
- method = null;
- return responseContent;
-
- } catch (SocketTimeoutException | ConnectTimeoutException e) {
- return null;
-
- } catch (Exception e) {
- return null;
-
- } finally {
- if (httpResponse != null) {
- try {
- EntityUtils.consume(httpResponse.getEntity());
- } catch (Exception e) {
- }
- }
- if (method != null) {
- try {
- method.reset();
- } catch (Exception e) {
-
- }
- }
- }
- }
+ private Map<String, Object> getReturnRoute(List<Object> returnList) {
+ Map<String, Object> returnRoute = new HashMap<>();
+ for (Object returnVpn : returnList) {
+ Map<String, Object> returnVpnInfo = (Map<String, Object>) returnVpn;
+ String accessTopoId = (String) returnVpnInfo.get("access-topology-id");
+ if ("100".equals(accessTopoId)) {
+ returnRoute.putAll(returnVpnInfo);
+ } else if ("101".equals(accessTopoId)) {
+ for (String key : returnVpnInfo.keySet()) {
+ returnRoute.put("domain1-" + key, returnVpnInfo.get(key));
+ }
+ } else if ("102".equals(accessTopoId)) {
+ for (String key : returnVpnInfo.keySet()) {
+ returnRoute.put("domain2-" + key, returnVpnInfo.get(key));
+ }
+ } else {
+ for (String key : returnVpnInfo.keySet()) {
+ returnRoute.put("domain" + accessTopoId + "-" + key, returnVpnInfo.get(key));
+ }
+ }
+ }
+ return returnRoute;
+ }
+
+ private Map<String, Object> getResourceParams(Execution execution, String resourceCustomizationUuid,
+ String serviceParameters) {
+ List<String> resourceList =
+ jsonUtil.StringArrayToList(execution, JsonUtils.getJsonValue(serviceParameters, "resources"));
+ // Get the right location str for resource. default is an empty array.
+ String resourceInputsFromUui = "";
+ for (String resource : resourceList) {
+ String resCusUuid = JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
+ if (resourceCustomizationUuid.equals(resCusUuid)) {
+ String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
+ resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
+ }
+ }
+ Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
+ return resourceInputsFromUuiMap;
+ }
+
+ private static <T> T getJsonObject(String jsonstr, Class<T> type) {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
+ try {
+ return mapper.readValue(jsonstr, type);
+ } catch (IOException e) {
+ logger.error("{} {} fail to unMarshal json", MessageEnum.RA_NS_EXC.toString(),
+ ErrorCode.BusinessProcesssError.getValue(), e);
+ }
+ return null;
+ }
+
+ public static String getJsonString(Object srcObj) {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
+ String jsonStr = null;
+ try {
+ jsonStr = mapper.writeValueAsString(srcObj);
+ } catch (JsonProcessingException e) {
+ logger.debug("SdcToscaParserException", e);
+ }
+ return jsonStr;
+ }
+
+ private static String sendRequest(String url, String methodType, String content) {
+
+ String msbUrl = url;
+ HttpRequestBase method = null;
+ HttpResponse httpResponse = null;
+
+ try {
+ int timeout = DEFAULT_TIME_OUT;
+
+ RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
+ .setConnectionRequestTimeout(timeout).build();
+
+ HttpClient client = HttpClientBuilder.create().build();
+
+ if ("POST".equals(methodType.toUpperCase())) {
+ HttpPost httpPost = new HttpPost(msbUrl);
+ httpPost.setConfig(requestConfig);
+ httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
+ method = httpPost;
+ } else if ("PUT".equals(methodType.toUpperCase())) {
+ HttpPut httpPut = new HttpPut(msbUrl);
+ httpPut.setConfig(requestConfig);
+ httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
+ method = httpPut;
+ } else if ("GET".equals(methodType.toUpperCase())) {
+ HttpGet httpGet = new HttpGet(msbUrl);
+ httpGet.setConfig(requestConfig);
+ httpGet.addHeader("X-FromAppId", "MSO");
+ httpGet.addHeader("Accept", "application/json");
+ method = httpGet;
+ } else if ("DELETE".equals(methodType.toUpperCase())) {
+ HttpDelete httpDelete = new HttpDelete(msbUrl);
+ httpDelete.setConfig(requestConfig);
+ method = httpDelete;
+ }
+
+ httpResponse = client.execute(method);
+ String responseContent = null;
+ if (null != httpResponse && httpResponse.getEntity() != null) {
+ try {
+ responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
+ } catch (ParseException e) {
+ logger.debug("ParseException in sendrequest", e);
+ } catch (IOException e) {
+ logger.debug("IOException in sendrequest", e);
+ }
+ }
+ if (null != method) {
+ method.reset();
+ }
+ method = null;
+ return responseContent;
+
+ } catch (SocketTimeoutException | ConnectTimeoutException e) {
+ return null;
+
+ } catch (Exception e) {
+ return null;
+
+ } finally {
+ if (httpResponse != null) {
+ try {
+ EntityUtils.consume(httpResponse.getEntity());
+ } catch (Exception e) {
+ }
+ }
+ if (method != null) {
+ try {
+ method.reset();
+ } catch (Exception e) {
+
+ }
+ }
+ }
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java
index 4c9bb4259e..5451f9ff57 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java
@@ -27,7 +27,6 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
-
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
@@ -52,7 +51,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -69,30 +67,31 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
private static final String TOPOLOGY_PROPERTIES = "topology.properties";
public static final String ONAP_IP = "ONAP_IP";
- private static final String POST_BODY_TEMPLATE = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://org.onap.so/requestsdb\"><soapenv:Header/><soapenv:Body>\n"+
- " <ns:updateResourceOperationStatus>\n"+
- " <errorCode>$errorCode</errorCode>\n"+
- " <jobId>$jobId</jobId>\n"+
- " <operType>$operType</operType>\n"+
- " <operationId>$operationId</operationId>\n"+
- " <progress>$progress</progress>\n"+
- " <resourceTemplateUUID>$resourceTemplateUUID</resourceTemplateUUID>\n"+
- " <serviceId>$serviceId</serviceId>\n"+
- " <status>$status</status>\n"+
- " <statusDescription>$statusDescription</statusDescription>\n"+
- " </ns:updateResourceOperationStatus></soapenv:Body></soapenv:Envelope>";
-
- private static final String GET_BODY_TEMPLATE = " <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://org.onap.so/requestsdb\"><soapenv:Header/><soapenv:Body>\n" +
- " <ns:getResourceOperationStatus>\n" +
- " <operationId>$operationId</operationId>\n" +
- " <resourceTemplateUUID>$resourceTemplateUUID</resourceTemplateUUID>\n" +
- " <serviceId>$serviceId</serviceId>\n" +
- " </ns:getResourceOperationStatus></soapenv:Body></soapenv:Envelope>";
+ private static final String POST_BODY_TEMPLATE =
+ "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://org.onap.so/requestsdb\"><soapenv:Header/><soapenv:Body>\n"
+ + " <ns:updateResourceOperationStatus>\n"
+ + " <errorCode>$errorCode</errorCode>\n" + " <jobId>$jobId</jobId>\n"
+ + " <operType>$operType</operType>\n"
+ + " <operationId>$operationId</operationId>\n"
+ + " <progress>$progress</progress>\n"
+ + " <resourceTemplateUUID>$resourceTemplateUUID</resourceTemplateUUID>\n"
+ + " <serviceId>$serviceId</serviceId>\n"
+ + " <status>$status</status>\n"
+ + " <statusDescription>$statusDescription</statusDescription>\n"
+ + " </ns:updateResourceOperationStatus></soapenv:Body></soapenv:Envelope>";
+
+ private static final String GET_BODY_TEMPLATE =
+ " <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://org.onap.so/requestsdb\"><soapenv:Header/><soapenv:Body>\n"
+ + " <ns:getResourceOperationStatus>\n"
+ + " <operationId>$operationId</operationId>\n"
+ + " <resourceTemplateUUID>$resourceTemplateUUID</resourceTemplateUUID>\n"
+ + " <serviceId>$serviceId</serviceId>\n"
+ + " </ns:getResourceOperationStatus></soapenv:Body></soapenv:Envelope>";
private void updateResOperStatus(ResourceOperationStatus resourceOperationStatus) throws RouteException {
logger.info("AbstractSdncOperationTask.updateResOperStatus begin!");
- String requestsdbEndPoint = env.getProperty("mso.adapters.openecomp.db.endpoint");
+ String requestsdbEndPoint = env.getProperty("mso.adapters.openecomp.db.endpoint");
HttpPost httpPost = new HttpPost(requestsdbEndPoint);
httpPost.addHeader("Authorization", "Basic YnBlbDpwYXNzd29yZDEk");
httpPost.addHeader("Content-type", "application/soap+xml");
@@ -119,12 +118,13 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
String result = null;
String errorMsg;
- try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
+ try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost);
result = EntityUtils.toString(closeableHttpResponse.getEntity());
logger.info("result = {}", result);
- if(closeableHttpResponse.getStatusLine().getStatusCode() != 200) {
- logger.info("exception: fail for status code = {}", closeableHttpResponse.getStatusLine().getStatusCode());
+ if (closeableHttpResponse.getStatusLine().getStatusCode() != 200) {
+ logger.info("exception: fail for status code = {}",
+ closeableHttpResponse.getStatusLine().getStatusCode());
throw new RouteException(result, "SERVICE_GET_ERR");
}
@@ -171,9 +171,10 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
return getBody;
}
- private ResourceOperationStatus getResourceOperationStatus(String serviceId, String operationId, String resourceTemplateUUID) throws RouteException {
+ private ResourceOperationStatus getResourceOperationStatus(String serviceId, String operationId,
+ String resourceTemplateUUID) throws RouteException {
logger.info("AbstractSdncOperationTask.getResourceOperationStatus begin!");
- String requestsdbEndPoint = env.getProperty("mso.adapters.openecomp.db.endpoint");
+ String requestsdbEndPoint = env.getProperty("mso.adapters.openecomp.db.endpoint");
HttpPost httpPost = new HttpPost(requestsdbEndPoint);
httpPost.addHeader("Authorization", "Basic YnBlbDpwYXNzd29yZDEk");
httpPost.addHeader("Content-type", "application/soap+xml");
@@ -224,7 +225,8 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
logger.error("exception: AbstractSdncOperationTask.fail!:", e);
logger.error(Arrays.toString(e.getStackTrace()));
execution.setVariable("SDNCA_SuccessIndicator", false);
- updateProgress(execution, RequestsDbConstant.Status.ERROR, null, "100", "sendRestrequestAndHandleResponse finished!");
+ updateProgress(execution, RequestsDbConstant.Status.ERROR, null, "100",
+ "sendRestrequestAndHandleResponse finished!");
}
logger.info("AbstractSdncOperationTask.execute end!");
@@ -247,15 +249,11 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
return inputs;
}
- public abstract void sendRestrequestAndHandleResponse(DelegateExecution execution,
- Map<String, String> inputs,
- GenericResourceApi genericResourceApiClient) throws Exception;
+ public abstract void sendRestrequestAndHandleResponse(DelegateExecution execution, Map<String, String> inputs,
+ GenericResourceApi genericResourceApiClient) throws Exception;
- public void updateProgress(DelegateExecution execution,
- String status,
- String errorCode,
- String progress,
- String statusDescription) {
+ public void updateProgress(DelegateExecution execution, String status, String errorCode, String progress,
+ String statusDescription) {
logger.info("AbstractSdncOperationTask.updateProgress begin!");
String serviceId = (String) execution.getVariable("serviceId");
serviceId = StringUtils.isBlank(serviceId) ? (String) execution.getVariable("serviceInstanceId") : serviceId;
@@ -265,7 +263,8 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
resourceTemplateId = StringUtils.isBlank(resourceTemplateId) ? "" : resourceTemplateUUID;
resourceTemplateUUID = StringUtils.isBlank(resourceTemplateUUID) ? resourceTemplateId : resourceTemplateUUID;
try {
- ResourceOperationStatus resourceOperationStatus = getResourceOperationStatus(serviceId, operationId, resourceTemplateUUID);
+ ResourceOperationStatus resourceOperationStatus =
+ getResourceOperationStatus(serviceId, operationId, resourceTemplateUUID);
if (!StringUtils.isBlank(status)) {
resourceOperationStatus.setStatus(status);
}
@@ -284,8 +283,8 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
logger.info("exception: AbstractSdncOperationTask.updateProgress fail!");
logger.error("exception: AbstractSdncOperationTask.updateProgress fail:", exception);
logger.error("{} {} {} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(),
- " updateProgress catch exception: ", this.getTaskName(),
- ErrorCode.UnknownError.getValue(), exception.getClass().toString());
+ " updateProgress catch exception: ", this.getTaskName(), ErrorCode.UnknownError.getValue(),
+ exception.getClass().toString());
}
}
@@ -293,11 +292,11 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
protected boolean isSend2SdncDirectly() {
logger.info("AbstractSdncOperationTask.isSend2SdncDirectly begin!");
String sdncHost = UrnPropertiesReader.getVariable("sdnc.host");
- if (!StringUtils.isBlank(sdncHost)) {
- logger.info("AbstractSdncOperationTask.isSend2SdncDirectly = true.");
- return true;
- }
-
+ if (!StringUtils.isBlank(sdncHost)) {
+ logger.info("AbstractSdncOperationTask.isSend2SdncDirectly = true.");
+ return true;
+ }
+
logger.info("AbstractSdncOperationTask.isSend2SdncDirectly = false.");
return false;
}
@@ -305,7 +304,7 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
protected String getSdncIp() {
logger.info("AbstractSdncOperationTask.getSdncIp begin.");
String sdncIp = null;
- sdncIp = UrnPropertiesReader.getVariable("sdnc-ip");
+ sdncIp = UrnPropertiesReader.getVariable("sdnc-ip");
String returnIp = StringUtils.isBlank(sdncIp) || !isIp(sdncIp) ? null : sdncIp;
logger.info("AbstractSdncOperationTask.getSdncIp: sdncIp = {}", returnIp);
return returnIp;
@@ -340,7 +339,7 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
strMsbPort = env.getProperty("msb.port", String.valueOf(DEFAULT_MSB_PORT));
}
msbPort = Integer.valueOf(strMsbPort);
-
+
logger.info("AbstractSdncOperationTask.getGenericResourceApiClient msbIp = " + msbIp + " msbPort = " + msbPort);
MSBServiceClient msbClient = new MSBServiceClient(msbIp, msbPort);
RestServiceCreater restServiceCreater = new RestServiceCreater(msbClient);
@@ -353,6 +352,7 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
}
public String getProcessKey(DelegateExecution execution) {
- return execution.getProcessEngineServices().getRepositoryService().getProcessDefinition(execution.getProcessDefinitionId()).getKey();
+ return execution.getProcessEngineServices().getRepositoryService()
+ .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
}
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncNetworkTopologyOperationTask.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncNetworkTopologyOperationTask.java
index a5c609dc2a..4d58439fda 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncNetworkTopologyOperationTask.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncNetworkTopologyOperationTask.java
@@ -23,7 +23,6 @@
package org.onap.so.bpmn.infrastructure.workflow.serviceTask;
import java.util.Map;
-
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
@@ -49,29 +48,30 @@ public class SdncNetworkTopologyOperationTask extends AbstractSdncOperationTask
private static final String URL = "/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation";
@Override
- public void sendRestrequestAndHandleResponse(DelegateExecution execution,
- Map<String, String> inputs,
- GenericResourceApi genericResourceApiClient) throws Exception {
+ public void sendRestrequestAndHandleResponse(DelegateExecution execution, Map<String, String> inputs,
+ GenericResourceApi genericResourceApiClient) throws Exception {
logger.info("SdncNetworkTopologyOperationTask.sendRestrequestAndHandleResponse begin!");
- updateProgress(execution, RequestsDbConstant.Status.PROCESSING, null, "40", "sendRestrequestAndHandleResponse begin!");
+ updateProgress(execution, RequestsDbConstant.Status.PROCESSING, null, "40",
+ "sendRestrequestAndHandleResponse begin!");
NetworkRpcInputEntityBuilder builder = new NetworkRpcInputEntityBuilder();
RpcNetworkTopologyOperationInputEntity inputEntity = builder.build(execution, inputs);
updateProgress(execution, RequestsDbConstant.Status.PROCESSING, null, "50", "RequestBody build finished!");
RpcNetworkTopologyOperationOutputEntity outputEntity;
if (!isSend2SdncDirectly()) {
- outputEntity = genericResourceApiClient.postNetworkTopologyOperation
- (HeaderUtil.DefaulAuth, inputEntity).execute().body();
- updateProgress(execution, null, null, "90", "sendRestrequestAndHandleResponse finished!");
- saveOutput(execution, outputEntity);
+ outputEntity = genericResourceApiClient.postNetworkTopologyOperation(HeaderUtil.DefaulAuth, inputEntity)
+ .execute().body();
+ updateProgress(execution, null, null, "90", "sendRestrequestAndHandleResponse finished!");
+ saveOutput(execution, outputEntity);
} else {
send2SdncDirectly(HeaderUtil.DefaulAuth, inputEntity);
}
- updateProgress(execution, RequestsDbConstant.Status.FINISHED, null, RequestsDbConstant.Progress.ONE_HUNDRED, "execute finished!");
+ updateProgress(execution, RequestsDbConstant.Status.FINISHED, null, RequestsDbConstant.Progress.ONE_HUNDRED,
+ "execute finished!");
logger.info("SdncNetworkTopologyOperationTask.sendRestrequestAndHandleResponse end!");
}
- private void send2SdncDirectly(String defaulAuth,
- RpcNetworkTopologyOperationInputEntity inputEntity) throws RouteException {
+ private void send2SdncDirectly(String defaulAuth, RpcNetworkTopologyOperationInputEntity inputEntity)
+ throws RouteException {
logger.info("SdncNetworkTopologyOperationTask.send2SdncDirectly begin!");
String url = "http://" + getSdncIp() + ":" + getSdncPort() + URL;
HttpPost httpPost = new HttpPost(url);
@@ -84,7 +84,8 @@ public class SdncNetworkTopologyOperationTask extends AbstractSdncOperationTask
logger.info("SdncNetworkTopologyOperationTask.send2SdncDirectly end!");
}
- private void saveOutput(DelegateExecution execution, RpcNetworkTopologyOperationOutputEntity output) throws RouteException {
+ private void saveOutput(DelegateExecution execution, RpcNetworkTopologyOperationOutputEntity output)
+ throws RouteException {
logger.info("SdncNetworkTopologyOperationTask.saveOutput begin!");
String responseCode = output.getOutput().getResponseCode();
if (!"200".equals(responseCode)) {
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncServiceTopologyOperationTask.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncServiceTopologyOperationTask.java
index 2fd550dbb8..4fb6817a39 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncServiceTopologyOperationTask.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncServiceTopologyOperationTask.java
@@ -24,7 +24,6 @@ package org.onap.so.bpmn.infrastructure.workflow.serviceTask;
import java.util.Map;
-
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
@@ -50,9 +49,8 @@ public class SdncServiceTopologyOperationTask extends AbstractSdncOperationTask
private static final String URL = "/restconf/operations/GENERIC-RESOURCE-API:service-topology-operation";
@Override
- public void sendRestrequestAndHandleResponse(DelegateExecution execution,
- Map<String, String> inputs,
- GenericResourceApi genericResourceApiClient) throws Exception {
+ public void sendRestrequestAndHandleResponse(DelegateExecution execution, Map<String, String> inputs,
+ GenericResourceApi genericResourceApiClient) throws Exception {
logger.info("SdncServiceTopologyOperationTask.sendRestrequestAndHandleResponse begin!");
updateProgress(execution, null, null, "40", "sendRestrequestAndHandleResponse begin!");
ServiceRpcInputEntityBuilder builder = new ServiceRpcInputEntityBuilder();
@@ -60,10 +58,10 @@ public class SdncServiceTopologyOperationTask extends AbstractSdncOperationTask
updateProgress(execution, null, null, "50", "RequestBody build finished!");
RpcServiceTopologyOperationOutputEntity outputEntity;
if (!isSend2SdncDirectly()) {
- outputEntity = genericResourceApiClient.postServiceTopologyOperation
- (HeaderUtil.DefaulAuth, inputEntity).execute().body();
- updateProgress(execution, null, null, "90", "sendRestrequestAndHandleResponse finished!");
- saveOutput(execution, outputEntity);
+ outputEntity = genericResourceApiClient.postServiceTopologyOperation(HeaderUtil.DefaulAuth, inputEntity)
+ .execute().body();
+ updateProgress(execution, null, null, "90", "sendRestrequestAndHandleResponse finished!");
+ saveOutput(execution, outputEntity);
} else {
send2SdncDirectly(HeaderUtil.DefaulAuth, inputEntity);
}
@@ -71,8 +69,8 @@ public class SdncServiceTopologyOperationTask extends AbstractSdncOperationTask
}
- private void send2SdncDirectly(String defaulAuth,
- RpcServiceTopologyOperationInputEntity inputEntity) throws RouteException {
+ private void send2SdncDirectly(String defaulAuth, RpcServiceTopologyOperationInputEntity inputEntity)
+ throws RouteException {
logger.info("SdncServiceTopologyOperationTask.send2SdncDirectly begin!");
String url = getSdncHost() + URL;
HttpPost httpPost = new HttpPost(url);
@@ -85,7 +83,8 @@ public class SdncServiceTopologyOperationTask extends AbstractSdncOperationTask
logger.info("SdncServiceTopologyOperationTask.send2SdncDirectly end!");
}
- private void saveOutput(DelegateExecution execution, RpcServiceTopologyOperationOutputEntity output) throws Exception {
+ private void saveOutput(DelegateExecution execution, RpcServiceTopologyOperationOutputEntity output)
+ throws Exception {
logger.info("SdncServiceTopologyOperationTask.saveOutput begin!");
String responseCode = output.getOutput().getResponseCode();
if (!"200".equals(responseCode)) {
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnOperationClient.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnOperationClient.java
index f54d6692d6..001d8fb6c0 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnOperationClient.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnOperationClient.java
@@ -23,7 +23,6 @@
package org.onap.so.bpmn.infrastructure.workflow.serviceTask;
import java.util.Map;
-
import org.apache.commons.lang3.StringUtils;
import org.onap.msb.sdk.httpclient.RestServiceCreater;
import org.onap.msb.sdk.httpclient.msb.MSBServiceClient;
@@ -46,33 +45,32 @@ public class SdncUnderlayVpnOperationClient {
private static Logger logger = LoggerFactory.getLogger(SdncUnderlayVpnOperationClient.class);
- public boolean excute(String msbIp,
- int msbPort,
- Map<String, String> inputs,
- String iServiceID,
- String iOperationID,
- String resourceTemplateUUID_i){
- ResourceOperationStatusId id = new ResourceOperationStatusId(iServiceID, iOperationID, resourceTemplateUUID_i);
+ public boolean excute(String msbIp, int msbPort, Map<String, String> inputs, String iServiceID, String iOperationID,
+ String resourceTemplateUUID_i) {
+ ResourceOperationStatusId id = new ResourceOperationStatusId(iServiceID, iOperationID, resourceTemplateUUID_i);
GenericResourceApi genericResourceApiClient = getGenericResourceApiClient(msbIp, msbPort);
updateProgress(id, RequestsDbConstant.Status.PROCESSING, null, "10", "execute begin!");
return sendRestrequestAndHandleResponse(id, inputs, genericResourceApiClient);
}
- public boolean sendRestrequestAndHandleResponse(ResourceOperationStatusId id, Map<String, String> inputs, GenericResourceApi genericResourceApiClient){
+ public boolean sendRestrequestAndHandleResponse(ResourceOperationStatusId id, Map<String, String> inputs,
+ GenericResourceApi genericResourceApiClient) {
updateProgress(id, null, null, "40", "sendRestrequestAndHandleResponse begin!");
NetworkRpcInputEntityBuilder builder = new NetworkRpcInputEntityBuilder();
RpcNetworkTopologyOperationInputEntity body = builder.build(null, inputs);
updateProgress(id, null, null, "50", "RequestBody build finished!");
- //RpcNetworkTopologyOperationOutputEntity networkRpcOutputEntiy = null;
+ // RpcNetworkTopologyOperationOutputEntity networkRpcOutputEntiy = null;
try {
- genericResourceApiClient.postNetworkTopologyOperation(HeaderUtil.DefaulAuth ,body).execute().body();
+ genericResourceApiClient.postNetworkTopologyOperation(HeaderUtil.DefaulAuth, body).execute().body();
} catch (Exception e) {
logger.debug("Exception: ", e);
- updateProgress(id, RequestsDbConstant.Status.ERROR, null, null, "sendRestrequestAndHandleResponse exception:" + e.getMessage());
+ updateProgress(id, RequestsDbConstant.Status.ERROR, null, null,
+ "sendRestrequestAndHandleResponse exception:" + e.getMessage());
return false;
}
updateProgress(id, null, null, "90", "sendRestrequestAndHandleResponse finished!");
- updateProgress(id, RequestsDbConstant.Status.FINISHED, null, RequestsDbConstant.Progress.ONE_HUNDRED, "execute finished!");
+ updateProgress(id, RequestsDbConstant.Status.FINISHED, null, RequestsDbConstant.Progress.ONE_HUNDRED,
+ "execute finished!");
return true;
}
@@ -88,13 +86,11 @@ public class SdncUnderlayVpnOperationClient {
return restServiceCreater.createService(GenericResourceApi.class);
}
- public void updateProgress(ResourceOperationStatusId id, String status,
- String errorCode,
- String progress,
- String statusDescription) {
-
-
- ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus();//rosRepo.getOne(id);
+ public void updateProgress(ResourceOperationStatusId id, String status, String errorCode, String progress,
+ String statusDescription) {
+
+
+ ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus();// rosRepo.getOne(id);
if (!StringUtils.isBlank(status)) {
resourceOperationStatus.setStatus(status);
}
@@ -107,7 +103,7 @@ public class SdncUnderlayVpnOperationClient {
if (!StringUtils.isBlank(statusDescription)) {
resourceOperationStatus.setStatusDescription(statusDescription);
}
- //rosRepo.save(resourceOperationStatus);
+ // rosRepo.save(resourceOperationStatus);
}
private void saveOutput() {
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnPreprocessTask.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnPreprocessTask.java
index 8bc9dce966..5b7f3bb432 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnPreprocessTask.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnPreprocessTask.java
@@ -41,8 +41,13 @@ public class SdncUnderlayVpnPreprocessTask extends BaseTask {
serviceId = StringUtils.isBlank(serviceId) ? (String) execution.getVariable("serviceInstanceId") : serviceId;
String operationId = (String) execution.getVariable("operationId");
String resourceTemplateUUID = (String) execution.getVariable("resourceTemplateUUID");
- resourceTemplateUUID = StringUtils.isBlank(resourceTemplateUUID) ? (String) execution.getVariable("resourceTemplateId") : resourceTemplateUUID;
- ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus();//rosRepo.getOne(new ResourceOperationStatusId(serviceId, operationId, resourceTemplateUUID));
+ resourceTemplateUUID =
+ StringUtils.isBlank(resourceTemplateUUID) ? (String) execution.getVariable("resourceTemplateId")
+ : resourceTemplateUUID;
+ ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus();// rosRepo.getOne(new
+ // ResourceOperationStatusId(serviceId,
+ // operationId,
+ // resourceTemplateUUID));
return resourceOperationStatus.getOperType();
}
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/GenericResourceApi.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/GenericResourceApi.java
index a837782a2c..ca9269242c 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/GenericResourceApi.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/GenericResourceApi.java
@@ -34,15 +34,15 @@ public interface GenericResourceApi {
@POST("/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation")
Call<ResponseBody> postNetworkTopologyOperation(@Header("Authorization") String authorization,
- @Body RequestBody input);
+ @Body RequestBody input);
@POST("/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation")
- Call<RpcNetworkTopologyOperationOutputEntity> postNetworkTopologyOperation(@Header("Authorization") String authorization,
- @Body RpcNetworkTopologyOperationInputEntity input);
+ Call<RpcNetworkTopologyOperationOutputEntity> postNetworkTopologyOperation(
+ @Header("Authorization") String authorization, @Body RpcNetworkTopologyOperationInputEntity input);
@POST("/restconf/operations/GENERIC-RESOURCE-API:service-topology-operation")
- Call<RpcServiceTopologyOperationOutputEntity> postServiceTopologyOperation(@Header("Authorization") String authorization,
- @Body RpcServiceTopologyOperationInputEntity input);
+ Call<RpcServiceTopologyOperationOutputEntity> postServiceTopologyOperation(
+ @Header("Authorization") String authorization, @Body RpcServiceTopologyOperationInputEntity input);
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/HeaderUtil.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/HeaderUtil.java
index 696be02809..3da5b0de70 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/HeaderUtil.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/HeaderUtil.java
@@ -36,8 +36,7 @@ public class HeaderUtil {
private static String base64Encode(String str) {
String base64 = str;
try {
- base64 = Base64.getEncoder()
- .encodeToString(str.getBytes("utf-8"));
+ base64 = Base64.getEncoder().encodeToString(str.getBytes("utf-8"));
} catch (Exception ex) {
}
return base64;
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilder.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilder.java
index 961b846ace..21b14c35f9 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilder.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilder.java
@@ -24,7 +24,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity.OnapModelInformationEntity;
@@ -35,205 +34,206 @@ import org.onap.so.requestsdb.RequestsDbConstant;
public abstract class AbstractBuilder<I, O> {
- public static final String OPERATION_TYPE = "operationType";
- public static final String RESOURCE_TYPE = "resourceType";
-
- public enum RequestAction {
- CREATE_NETWORK_INSTANCE(0, "CreateNetworkInstance"),
- ACTIVATE_NETWORK_INSTANCE(1, "ActivateNetworkInstance"),
- CREATE_SERVICE_INSTANCE(2, "CreateServiceInstance"),
- DELETE_SERVICE_INSTANCE(3, "DeleteServiceInstance"),
- DELETE_NETWORK_INSTANCE(4, "DeleteNetworkInstance"),
- CREATE_VNF_INSTANCE(5, "CreateVnfInstance"),
- ACTIVATE_VNF_INSTANCE(6, "ActivateVnfInstance"),
- DELETE_VNF_INSTANCE(7, "DeleteVnfInstance"),
- CREATE_VF_MODULE_INSTANCE(8, "CreateVfModuleInstance"),
- ACTIVATE_VF_MODULE_INSTANCE(9, "ActivateVfModuleInstance"),
- DELETE_VF_MODULE_INSTANCE(10, "DeleteVfModuleInstance"),
- CREATE_CONTRAIL_ROUTE_INSTANCE(11, "CreateContrailRouteInstance"),
- DELETE_CONTRAIL_ROUTE_INSTANCE(12, "DeleteContrailRouteInstance"),
- CREATE_SECURITY_ZONE_INSTANCE(13, "CreateSecurityZoneInstance"),
- DELETE_SECURITY_ZONE_INSTANCE(14, "DeleteSecurityZoneInstance"),
- ACTIVATE_DCI_NETWORK_INSTANCE(15, "ActivateDCINetworkInstance"),
- DEACTIVATE_DCI_NETWORK_INSTANCE(16, "DeActivateDCINetworkInstance");
-
- String name;
- int value;
-
- private RequestAction(int value, String name) {
- this.value = value;
- this.name = name;
- }
-
- public String getName() {
- return this.name;
- }
-
- public int getIntValue() {
- return this.value;
- }
- }
-
- public enum SvcAction {
- RESERVE(0, "reserve"),
- ASSIGN(1, "assign"),
- ACTIVATE(2, "activate"),
- DELETE(3, "delete"),
- CHANGEASSIGN(4, "changeassign"),
- CHANGEDELETE(5, "changedelete"),
- ROLLBACK(6, "rollback"),
- DEACTIVATE(7, "deactivate"),
- UNASSIGN(8, "unassign"),
- CREATE(9, "create");
-
- String name;
- int value;
-
- private SvcAction(int value, String name) {
- this.value = value;
- this.name = name;
- }
-
- public String getName() {
- return this.name;
- }
-
- public int getIntValue() {
- return this.value;
- }
- }
-
- protected String requestId = null;
-
- abstract O build(DelegateExecution execution, I input) throws Exception;
-
- protected String getRequestAction(DelegateExecution execution) {
- String action = /*RequestInformation.*/RequestAction.CREATE_NETWORK_INSTANCE.getName();
- String operType = (String) execution.getVariable(OPERATION_TYPE);
- String resourceType = (String)execution.getVariable(RESOURCE_TYPE);
- if (!StringUtils.isBlank(operType)) {
- if (RequestsDbConstant.OperationType.DELETE.equalsIgnoreCase(operType)) {
- if (isOverlay(resourceType)) {
- action = /*RequestInformation.*/RequestAction.DEACTIVATE_DCI_NETWORK_INSTANCE.getName();
- } else if (isUnderlay(resourceType)) {
- action = /*RequestInformation.*/RequestAction.DELETE_NETWORK_INSTANCE.getName();
- } else {
- action = /*RequestInformation.*/RequestAction.DELETE_SERVICE_INSTANCE.getName();
- }
- } else if (RequestsDbConstant.OperationType.CREATE.equalsIgnoreCase(operType)) {
- if (isOverlay(resourceType)) {
- action = /*RequestInformation.*/RequestAction.ACTIVATE_DCI_NETWORK_INSTANCE.getName();
- } else if (isUnderlay(resourceType)) {
- action = /*RequestInformation.*/RequestAction.CREATE_NETWORK_INSTANCE.getName();
- } else {
- action = /*RequestInformation.*/RequestAction.CREATE_SERVICE_INSTANCE.getName();
- }
- }
- }
- return action;
- }
-
- private boolean isOverlay(String resourceType) {
- return !StringUtils.isBlank(resourceType) && resourceType.toLowerCase().contains("overlay");
- }
-
- private boolean isUnderlay(String resourceType) {
- return !StringUtils.isBlank(resourceType) && resourceType.toLowerCase().contains("underlay");
- }
-
- protected String getSvcAction(DelegateExecution execution) {
- String action = /*SdncRequestHeader.*/SvcAction.CREATE.getName();
- String operType = (String) execution.getVariable(OPERATION_TYPE);
- String resourceType = (String)execution.getVariable(RESOURCE_TYPE);
- if (!StringUtils.isBlank(operType)) {
- if (RequestsDbConstant.OperationType.DELETE.equalsIgnoreCase(operType)) {
- if (isOverlay(resourceType)) {
- action = /*SdncRequestHeader.*/SvcAction.DEACTIVATE.getName();
- } else if (isUnderlay(resourceType)) {
- action = /*SdncRequestHeader.*/SvcAction.DELETE.getName();
- } else {
- action = /*SdncRequestHeader.*/SvcAction.UNASSIGN.getName();
- }
- } else if (RequestsDbConstant.OperationType.CREATE.equalsIgnoreCase(operType)) {
- if (isOverlay(resourceType)) {
- action = /*SdncRequestHeader.*/SvcAction.ACTIVATE.getName();
- } else if (isUnderlay(resourceType)) {
- action = /*SdncRequestHeader.*/SvcAction.CREATE.getName();
- } else {
- action = /*SdncRequestHeader.*/SvcAction.ASSIGN.getName();
- }
- }
- }
- return action;
- }
-
- protected synchronized String getRequestId(DelegateExecution execution) {
- if (StringUtils.isBlank(requestId)) {
- requestId = (String) execution.getVariable("msoRequestId");
- if (StringUtils.isBlank(requestId)) {
- requestId = UUID.randomUUID().toString();
- }
- }
- return requestId;
- }
-
- protected OnapModelInformationEntity getOnapServiceModelInformationEntity(DelegateExecution execution) {
- OnapModelInformationEntity onapModelInformationEntity = new OnapModelInformationEntity();
- String modelInvariantUuid = (String) execution.getVariable("modelInvariantUuid");
- String modelVersion = (String) execution.getVariable("modelVersion");
- String modelUuid = (String) execution.getVariable("modelUuid");
- String modelName = (String) execution.getVariable("serviceModelName");
- onapModelInformationEntity.setModelInvariantUuid(modelInvariantUuid);
- onapModelInformationEntity.setModelVersion(modelVersion);
- onapModelInformationEntity.setModelUuid(modelUuid);
- onapModelInformationEntity.setModelName(modelName);
- return onapModelInformationEntity;
- }
-
- protected OnapModelInformationEntity getOnapNetworkModelInformationEntity(DelegateExecution execution) {
- OnapModelInformationEntity onapModelInformationEntity = new OnapModelInformationEntity();
- String modelInvariantUuid = (String) execution.getVariable("resourceInvariantUUID");
- String modelVersion = (String) execution.getVariable("modelVersion");
- String modelUuid = (String) execution.getVariable("resourceUUID");
- String modelName = (String) execution.getVariable(RESOURCE_TYPE);
- onapModelInformationEntity.setModelInvariantUuid(modelInvariantUuid);
- onapModelInformationEntity.setModelVersion(modelVersion);
- onapModelInformationEntity.setModelUuid(modelUuid);
- onapModelInformationEntity.setModelName(modelName);
- return onapModelInformationEntity;
+ public static final String OPERATION_TYPE = "operationType";
+ public static final String RESOURCE_TYPE = "resourceType";
+
+ public enum RequestAction {
+ CREATE_NETWORK_INSTANCE(0, "CreateNetworkInstance"), ACTIVATE_NETWORK_INSTANCE(1,
+ "ActivateNetworkInstance"), CREATE_SERVICE_INSTANCE(2,
+ "CreateServiceInstance"), DELETE_SERVICE_INSTANCE(3,
+ "DeleteServiceInstance"), DELETE_NETWORK_INSTANCE(4,
+ "DeleteNetworkInstance"), CREATE_VNF_INSTANCE(5,
+ "CreateVnfInstance"), ACTIVATE_VNF_INSTANCE(6,
+ "ActivateVnfInstance"), DELETE_VNF_INSTANCE(7,
+ "DeleteVnfInstance"), CREATE_VF_MODULE_INSTANCE(8,
+ "CreateVfModuleInstance"), ACTIVATE_VF_MODULE_INSTANCE(
+ 9,
+ "ActivateVfModuleInstance"), DELETE_VF_MODULE_INSTANCE(
+ 10,
+ "DeleteVfModuleInstance"), CREATE_CONTRAIL_ROUTE_INSTANCE(
+ 11,
+ "CreateContrailRouteInstance"), DELETE_CONTRAIL_ROUTE_INSTANCE(
+ 12,
+ "DeleteContrailRouteInstance"), CREATE_SECURITY_ZONE_INSTANCE(
+ 13,
+ "CreateSecurityZoneInstance"), DELETE_SECURITY_ZONE_INSTANCE(
+ 14,
+ "DeleteSecurityZoneInstance"), ACTIVATE_DCI_NETWORK_INSTANCE(
+ 15,
+ "ActivateDCINetworkInstance"), DEACTIVATE_DCI_NETWORK_INSTANCE(
+ 16,
+ "DeActivateDCINetworkInstance");
+
+ String name;
+ int value;
+
+ private RequestAction(int value, String name) {
+ this.value = value;
+ this.name = name;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public int getIntValue() {
+ return this.value;
+ }
+ }
+
+ public enum SvcAction {
+ RESERVE(0, "reserve"), ASSIGN(1, "assign"), ACTIVATE(2, "activate"), DELETE(3, "delete"), CHANGEASSIGN(4,
+ "changeassign"), CHANGEDELETE(5, "changedelete"), ROLLBACK(6,
+ "rollback"), DEACTIVATE(7, "deactivate"), UNASSIGN(8, "unassign"), CREATE(9, "create");
+
+ String name;
+ int value;
+
+ private SvcAction(int value, String name) {
+ this.value = value;
+ this.name = name;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public int getIntValue() {
+ return this.value;
+ }
+ }
+
+ protected String requestId = null;
+
+ abstract O build(DelegateExecution execution, I input) throws Exception;
+
+ protected String getRequestAction(DelegateExecution execution) {
+ String action = /* RequestInformation. */RequestAction.CREATE_NETWORK_INSTANCE.getName();
+ String operType = (String) execution.getVariable(OPERATION_TYPE);
+ String resourceType = (String) execution.getVariable(RESOURCE_TYPE);
+ if (!StringUtils.isBlank(operType)) {
+ if (RequestsDbConstant.OperationType.DELETE.equalsIgnoreCase(operType)) {
+ if (isOverlay(resourceType)) {
+ action = /* RequestInformation. */RequestAction.DEACTIVATE_DCI_NETWORK_INSTANCE.getName();
+ } else if (isUnderlay(resourceType)) {
+ action = /* RequestInformation. */RequestAction.DELETE_NETWORK_INSTANCE.getName();
+ } else {
+ action = /* RequestInformation. */RequestAction.DELETE_SERVICE_INSTANCE.getName();
+ }
+ } else if (RequestsDbConstant.OperationType.CREATE.equalsIgnoreCase(operType)) {
+ if (isOverlay(resourceType)) {
+ action = /* RequestInformation. */RequestAction.ACTIVATE_DCI_NETWORK_INSTANCE.getName();
+ } else if (isUnderlay(resourceType)) {
+ action = /* RequestInformation. */RequestAction.CREATE_NETWORK_INSTANCE.getName();
+ } else {
+ action = /* RequestInformation. */RequestAction.CREATE_SERVICE_INSTANCE.getName();
+ }
+ }
+ }
+ return action;
+ }
+
+ private boolean isOverlay(String resourceType) {
+ return !StringUtils.isBlank(resourceType) && resourceType.toLowerCase().contains("overlay");
+ }
+
+ private boolean isUnderlay(String resourceType) {
+ return !StringUtils.isBlank(resourceType) && resourceType.toLowerCase().contains("underlay");
+ }
+
+ protected String getSvcAction(DelegateExecution execution) {
+ String action = /* SdncRequestHeader. */SvcAction.CREATE.getName();
+ String operType = (String) execution.getVariable(OPERATION_TYPE);
+ String resourceType = (String) execution.getVariable(RESOURCE_TYPE);
+ if (!StringUtils.isBlank(operType)) {
+ if (RequestsDbConstant.OperationType.DELETE.equalsIgnoreCase(operType)) {
+ if (isOverlay(resourceType)) {
+ action = /* SdncRequestHeader. */SvcAction.DEACTIVATE.getName();
+ } else if (isUnderlay(resourceType)) {
+ action = /* SdncRequestHeader. */SvcAction.DELETE.getName();
+ } else {
+ action = /* SdncRequestHeader. */SvcAction.UNASSIGN.getName();
+ }
+ } else if (RequestsDbConstant.OperationType.CREATE.equalsIgnoreCase(operType)) {
+ if (isOverlay(resourceType)) {
+ action = /* SdncRequestHeader. */SvcAction.ACTIVATE.getName();
+ } else if (isUnderlay(resourceType)) {
+ action = /* SdncRequestHeader. */SvcAction.CREATE.getName();
+ } else {
+ action = /* SdncRequestHeader. */SvcAction.ASSIGN.getName();
+ }
+ }
+ }
+ return action;
+ }
+
+ protected synchronized String getRequestId(DelegateExecution execution) {
+ if (StringUtils.isBlank(requestId)) {
+ requestId = (String) execution.getVariable("msoRequestId");
+ if (StringUtils.isBlank(requestId)) {
+ requestId = UUID.randomUUID().toString();
+ }
+ }
+ return requestId;
+ }
+
+ protected OnapModelInformationEntity getOnapServiceModelInformationEntity(DelegateExecution execution) {
+ OnapModelInformationEntity onapModelInformationEntity = new OnapModelInformationEntity();
+ String modelInvariantUuid = (String) execution.getVariable("modelInvariantUuid");
+ String modelVersion = (String) execution.getVariable("modelVersion");
+ String modelUuid = (String) execution.getVariable("modelUuid");
+ String modelName = (String) execution.getVariable("serviceModelName");
+ onapModelInformationEntity.setModelInvariantUuid(modelInvariantUuid);
+ onapModelInformationEntity.setModelVersion(modelVersion);
+ onapModelInformationEntity.setModelUuid(modelUuid);
+ onapModelInformationEntity.setModelName(modelName);
+ return onapModelInformationEntity;
+ }
+
+ protected OnapModelInformationEntity getOnapNetworkModelInformationEntity(DelegateExecution execution) {
+ OnapModelInformationEntity onapModelInformationEntity = new OnapModelInformationEntity();
+ String modelInvariantUuid = (String) execution.getVariable("resourceInvariantUUID");
+ String modelVersion = (String) execution.getVariable("modelVersion");
+ String modelUuid = (String) execution.getVariable("resourceUUID");
+ String modelName = (String) execution.getVariable(RESOURCE_TYPE);
+ onapModelInformationEntity.setModelInvariantUuid(modelInvariantUuid);
+ onapModelInformationEntity.setModelVersion(modelVersion);
+ onapModelInformationEntity.setModelUuid(modelUuid);
+ onapModelInformationEntity.setModelName(modelName);
+ return onapModelInformationEntity;
}
- protected List<ParamEntity> getParamEntities(Map<String, String> inputs) {
- List<ParamEntity> paramEntityList = new ArrayList<>();
- if (inputs != null && !inputs.isEmpty()) {
- inputs.keySet().forEach(key -> {
- ParamEntity paramEntity = new ParamEntity();
- paramEntity.setName(key);
- paramEntity.setValue(inputs.get(key));
- paramEntityList.add(paramEntity);
- });
- }
- return paramEntityList;
- }
-
- protected RequestInformationEntity getRequestInformationEntity(DelegateExecution execution) {
- RequestInformationEntity requestInformationEntity = new RequestInformationEntity();
- requestInformationEntity.setRequestId(getRequestId(execution));
- requestInformationEntity.setRequestAction(getRequestAction(execution));
- return requestInformationEntity;
- }
-
- protected ServiceInformationEntity getServiceInformationEntity(DelegateExecution execution) {
- ServiceInformationEntity serviceInformationEntity = new ServiceInformationEntity();
- serviceInformationEntity.setServiceId((String) execution.getVariable("serviceInstanceId"));
- serviceInformationEntity.setSubscriptionServiceType((String) execution.getVariable("serviceType"));
- serviceInformationEntity.setOnapModelInformation(getOnapServiceModelInformationEntity(execution));
- serviceInformationEntity.setServiceInstanceId((String) execution.getVariable("serviceInstanceId"));
- serviceInformationEntity.setGlobalCustomerId((String) execution.getVariable("globalSubscriberId"));
- return serviceInformationEntity;
- }
-
- protected String getServiceInstanceName(DelegateExecution execution) {
- return (String) execution.getVariable("serviceInstanceName");
- }
+ protected List<ParamEntity> getParamEntities(Map<String, String> inputs) {
+ List<ParamEntity> paramEntityList = new ArrayList<>();
+ if (inputs != null && !inputs.isEmpty()) {
+ inputs.keySet().forEach(key -> {
+ ParamEntity paramEntity = new ParamEntity();
+ paramEntity.setName(key);
+ paramEntity.setValue(inputs.get(key));
+ paramEntityList.add(paramEntity);
+ });
+ }
+ return paramEntityList;
+ }
+
+ protected RequestInformationEntity getRequestInformationEntity(DelegateExecution execution) {
+ RequestInformationEntity requestInformationEntity = new RequestInformationEntity();
+ requestInformationEntity.setRequestId(getRequestId(execution));
+ requestInformationEntity.setRequestAction(getRequestAction(execution));
+ return requestInformationEntity;
+ }
+
+ protected ServiceInformationEntity getServiceInformationEntity(DelegateExecution execution) {
+ ServiceInformationEntity serviceInformationEntity = new ServiceInformationEntity();
+ serviceInformationEntity.setServiceId((String) execution.getVariable("serviceInstanceId"));
+ serviceInformationEntity.setSubscriptionServiceType((String) execution.getVariable("serviceType"));
+ serviceInformationEntity.setOnapModelInformation(getOnapServiceModelInformationEntity(execution));
+ serviceInformationEntity.setServiceInstanceId((String) execution.getVariable("serviceInstanceId"));
+ serviceInformationEntity.setGlobalCustomerId((String) execution.getVariable("globalSubscriberId"));
+ return serviceInformationEntity;
+ }
+
+ protected String getServiceInstanceName(DelegateExecution execution) {
+ return (String) execution.getVariable("serviceInstanceName");
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/NetworkRpcInputEntityBuilder.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/NetworkRpcInputEntityBuilder.java
index 547df2bb3a..4a2194ed3d 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/NetworkRpcInputEntityBuilder.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/NetworkRpcInputEntityBuilder.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder;
import java.util.List;
import java.util.Map;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity.NetworkInformationEntity;
import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity.NetworkInputParametersEntity;
@@ -35,44 +34,53 @@ import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity.RpcNet
import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity.SdncRequestHeaderEntity;
import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity.ServiceInformationEntity;
-public class NetworkRpcInputEntityBuilder extends AbstractBuilder<Map<String, String>, RpcNetworkTopologyOperationInputEntity> {
+public class NetworkRpcInputEntityBuilder
+ extends AbstractBuilder<Map<String, String>, RpcNetworkTopologyOperationInputEntity> {
@Override
public RpcNetworkTopologyOperationInputEntity build(DelegateExecution execution, Map<String, String> inputs) {
- RpcNetworkTopologyOperationInputEntity rpcNetworkTopologyOperationInputEntity = new RpcNetworkTopologyOperationInputEntity();
- NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity = getNetworkTopologyOperationInputEntity(execution, inputs);
+ RpcNetworkTopologyOperationInputEntity rpcNetworkTopologyOperationInputEntity =
+ new RpcNetworkTopologyOperationInputEntity();
+ NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity =
+ getNetworkTopologyOperationInputEntity(execution, inputs);
rpcNetworkTopologyOperationInputEntity.setInput(networkTopologyOperationInputEntity);
return rpcNetworkTopologyOperationInputEntity;
}
- private void loadNetwrokRequestInputEntity(Map<String, String> inputs, NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity) {
+ private void loadNetwrokRequestInputEntity(Map<String, String> inputs,
+ NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity) {
NetworkRequestInputEntity networkRequestInputEntity = new NetworkRequestInputEntity();
- NetworkInputParametersEntity networkInputParametersEntity = new NetworkInputParametersEntity();
+ NetworkInputParametersEntity networkInputParametersEntity = new NetworkInputParametersEntity();
List<ParamEntity> paramEntityList = getParamEntities(inputs);
networkInputParametersEntity.setParamList(paramEntityList);
- networkRequestInputEntity.setNetworkInputPaarameters(networkInputParametersEntity);
+ networkRequestInputEntity.setNetworkInputPaarameters(networkInputParametersEntity);
networkTopologyOperationInputEntity.setNetworkRequestInput(networkRequestInputEntity);
}
- private void loadRequestInformationEntity(NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity, DelegateExecution execution) {
+ private void loadRequestInformationEntity(NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity,
+ DelegateExecution execution) {
RequestInformationEntity requestInformationEntity = getRequestInformationEntity(execution);
networkTopologyOperationInputEntity.setRequestInformation(requestInformationEntity);
}
- private void loadSdncRequestHeaderEntity(NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity, DelegateExecution execution) {
+ private void loadSdncRequestHeaderEntity(NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity,
+ DelegateExecution execution) {
SdncRequestHeaderEntity sdncRequestHeaderEntity = new SdncRequestHeaderEntity();
sdncRequestHeaderEntity.setSvcRequestId(getRequestId(execution));
sdncRequestHeaderEntity.setSvcAction(getSvcAction(execution));
networkTopologyOperationInputEntity.setSdncRequestHeader(sdncRequestHeaderEntity);
}
- private void loadServiceInformation(NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity, DelegateExecution execution) {
+ private void loadServiceInformation(NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity,
+ DelegateExecution execution) {
ServiceInformationEntity serviceInformationEntity = getServiceInformationEntity(execution);
networkTopologyOperationInputEntity.setServiceInformation(serviceInformationEntity);
}
- private NetworkTopologyOperationInputEntity getNetworkTopologyOperationInputEntity(DelegateExecution execution, Map<String, String> inputs) {
- NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity = new NetworkTopologyOperationInputEntity();
+ private NetworkTopologyOperationInputEntity getNetworkTopologyOperationInputEntity(DelegateExecution execution,
+ Map<String, String> inputs) {
+ NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity =
+ new NetworkTopologyOperationInputEntity();
loadSdncRequestHeaderEntity(networkTopologyOperationInputEntity, execution);
loadRequestInformationEntity(networkTopologyOperationInputEntity, execution);
loadServiceInformation(networkTopologyOperationInputEntity, execution);
@@ -81,7 +89,8 @@ public class NetworkRpcInputEntityBuilder extends AbstractBuilder<Map<String, St
return networkTopologyOperationInputEntity;
}
- private void loadNetworkInformationEntity(DelegateExecution execution, NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity) {
+ private void loadNetworkInformationEntity(DelegateExecution execution,
+ NetworkTopologyOperationInputEntity networkTopologyOperationInputEntity) {
NetworkInformationEntity networkInformationEntity = new NetworkInformationEntity();
OnapModelInformationEntity onapModelInformationEntity = getOnapNetworkModelInformationEntity(execution);
networkInformationEntity.setOnapModelInformation(onapModelInformationEntity);
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/ServiceRpcInputEntityBuilder.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/ServiceRpcInputEntityBuilder.java
index 466652edff..944802372b 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/ServiceRpcInputEntityBuilder.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/ServiceRpcInputEntityBuilder.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder;
import java.util.Map;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity.RequestInformationEntity;
import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity.RpcServiceTopologyOperationInputEntity;
@@ -30,20 +29,26 @@ import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity.Servic
import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity.ServiceRequestInputEntity;
import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity.ServiceTopologyOperationInputEntity;
-public class ServiceRpcInputEntityBuilder extends AbstractBuilder<Map<String, String>, RpcServiceTopologyOperationInputEntity> {
+public class ServiceRpcInputEntityBuilder
+ extends AbstractBuilder<Map<String, String>, RpcServiceTopologyOperationInputEntity> {
@Override
- public RpcServiceTopologyOperationInputEntity build(DelegateExecution execution, Map<String, String> inputs) throws Exception {
- RpcServiceTopologyOperationInputEntity rpcServiceTopologyOperationInputEntity = new RpcServiceTopologyOperationInputEntity();
- ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity = new ServiceTopologyOperationInputEntity();
+ public RpcServiceTopologyOperationInputEntity build(DelegateExecution execution, Map<String, String> inputs)
+ throws Exception {
+ RpcServiceTopologyOperationInputEntity rpcServiceTopologyOperationInputEntity =
+ new RpcServiceTopologyOperationInputEntity();
+ ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity =
+ new ServiceTopologyOperationInputEntity();
loadSdncRequestHeaderEntity(serviceTopologyOperationInputEntity, execution);
loadRequestInformationEntity(serviceTopologyOperationInputEntity, execution);
loadServiceInformation(serviceTopologyOperationInputEntity, execution);
loadServiceRequestInputEntity(serviceTopologyOperationInputEntity, execution);
- rpcServiceTopologyOperationInputEntity.setServiceTopologyOperationInputEntity(serviceTopologyOperationInputEntity);
+ rpcServiceTopologyOperationInputEntity
+ .setServiceTopologyOperationInputEntity(serviceTopologyOperationInputEntity);
return rpcServiceTopologyOperationInputEntity;
}
- private void loadServiceRequestInputEntity(ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity, DelegateExecution execution) {
+ private void loadServiceRequestInputEntity(ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity,
+ DelegateExecution execution) {
ServiceRequestInputEntity serviceRequestInputEntity = getServiceRequestInputEntity(execution);
serviceTopologyOperationInputEntity.setServiceRequestInput(serviceRequestInputEntity);
}
@@ -54,17 +59,20 @@ public class ServiceRpcInputEntityBuilder extends AbstractBuilder<Map<String, St
return serviceRequestInputEntity;
}
- private void loadServiceInformation(ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity, DelegateExecution execution) {
+ private void loadServiceInformation(ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity,
+ DelegateExecution execution) {
ServiceInformationEntity serviceInformationEntity = getServiceInformationEntity(execution);
serviceTopologyOperationInputEntity.setServiceInformation(serviceInformationEntity);
}
- private void loadRequestInformationEntity(ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity, DelegateExecution execution) {
+ private void loadRequestInformationEntity(ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity,
+ DelegateExecution execution) {
RequestInformationEntity requestInformationEntity = getRequestInformationEntity(execution);
serviceTopologyOperationInputEntity.setRequestInformation(requestInformationEntity);
}
- private void loadSdncRequestHeaderEntity(ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity, DelegateExecution execution) {
+ private void loadSdncRequestHeaderEntity(ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity,
+ DelegateExecution execution) {
SdncRequestHeaderEntity sdncRequestHeaderEntity = new SdncRequestHeaderEntity();
sdncRequestHeaderEntity.setSvcRequestId(getRequestId(execution));
sdncRequestHeaderEntity.setSvcAction(getSvcAction(execution));
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/NetworkInputParametersEntity.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/NetworkInputParametersEntity.java
index 0863917f21..847aa72469 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/NetworkInputParametersEntity.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/NetworkInputParametersEntity.java
@@ -21,13 +21,12 @@
package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import java.util.List;
public class NetworkInputParametersEntity {
- @JsonProperty("GENERIC-RESOURCE-API:param")
+ @JsonProperty("GENERIC-RESOURCE-API:param")
private List<ParamEntity> paramList;
-
+
public List<ParamEntity> getParamList() {
return paramList;
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RequestInformationEntity.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RequestInformationEntity.java
index af448942cc..238a4f32c0 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RequestInformationEntity.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RequestInformationEntity.java
@@ -23,7 +23,7 @@ package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
public class RequestInformationEntity {
- @JsonProperty("GENERIC-RESOURCE-API:request-id")
+ @JsonProperty("GENERIC-RESOURCE-API:request-id")
private String requestId;
@JsonProperty("GENERIC-RESOURCE-API:request-action")
@@ -40,7 +40,7 @@ public class RequestInformationEntity {
@JsonProperty("GENERIC-RESOURCE-API:order-version")
private String orerVersion;
-
+
public String getRequestId() {
return requestId;
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcNetworkTopologyOperationInputEntity.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcNetworkTopologyOperationInputEntity.java
index 4e58a61750..76494f5585 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcNetworkTopologyOperationInputEntity.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcNetworkTopologyOperationInputEntity.java
@@ -23,9 +23,9 @@ package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
public class RpcNetworkTopologyOperationInputEntity {
- @JsonProperty("GENERIC-RESOURCE-API:input")
+ @JsonProperty("GENERIC-RESOURCE-API:input")
private NetworkTopologyOperationInputEntity input = null;
-
+
public NetworkTopologyOperationInputEntity getInput() {
return input;
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcNetworkTopologyOperationOutputEntity.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcNetworkTopologyOperationOutputEntity.java
index 915a8a5e39..c93b3f2ad9 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcNetworkTopologyOperationOutputEntity.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcNetworkTopologyOperationOutputEntity.java
@@ -23,9 +23,9 @@ package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
public class RpcNetworkTopologyOperationOutputEntity {
- @JsonProperty("GENERIC-RESOURCE-API:output")
+ @JsonProperty("GENERIC-RESOURCE-API:output")
private NetworkTopologyOperationOutputEntity output;
-
+
public NetworkTopologyOperationOutputEntity getOutput() {
return output;
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcServiceTopologyOperationInputEntity.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcServiceTopologyOperationInputEntity.java
index 145759e190..dbca00ae24 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcServiceTopologyOperationInputEntity.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/RpcServiceTopologyOperationInputEntity.java
@@ -23,14 +23,15 @@ package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
public class RpcServiceTopologyOperationInputEntity {
- @JsonProperty("GENERIC-RESOURCE-API:input")
+ @JsonProperty("GENERIC-RESOURCE-API:input")
private ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity;
-
+
public ServiceTopologyOperationInputEntity getServiceTopologyOperationInputEntity() {
return serviceTopologyOperationInputEntity;
}
- public void setServiceTopologyOperationInputEntity(ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity) {
+ public void setServiceTopologyOperationInputEntity(
+ ServiceTopologyOperationInputEntity serviceTopologyOperationInputEntity) {
this.serviceTopologyOperationInputEntity = serviceTopologyOperationInputEntity;
}
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/ServiceInputParametersEntity.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/ServiceInputParametersEntity.java
index c1ba7dc614..5c199bd413 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/ServiceInputParametersEntity.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/ServiceInputParametersEntity.java
@@ -21,13 +21,12 @@
package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import java.util.List;
public class ServiceInputParametersEntity {
- @JsonProperty("GENERIC-RESOURCE-API:param")
+ @JsonProperty("GENERIC-RESOURCE-API:param")
private List<ParamEntity> paramList;
-
+
public List<ParamEntity> getParamList() {
return paramList;
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllBPMNTestSuites.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllBPMNTestSuites.java
index 0f77e41120..03d9b37522 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllBPMNTestSuites.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllBPMNTestSuites.java
@@ -19,14 +19,14 @@
*/
package org.onap.so.bpmn;
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses({"**/service/*Test.class", "**/process/*Test.class", "**/subprocess/*Test.class"})
public class AllBPMNTestSuites {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllTasksTestsTestSuite.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllTasksTestsTestSuite.java
index 57d842f8b5..7f86709432 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllTasksTestsTestSuite.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllTasksTestsTestSuite.java
@@ -19,14 +19,14 @@
*/
package org.onap.so.bpmn;
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
-@SuiteClasses({"**/tasks/*Test.class","**/infrastructure/aai/*Test.class"})
+@SuiteClasses({"**/tasks/*Test.class", "**/infrastructure/aai/*Test.class"})
public class AllTasksTestsTestSuite {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllTestsTestSuite.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllTestsTestSuite.java
index ddcc6fe875..7123567247 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllTestsTestSuite.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/AllTestsTestSuite.java
@@ -23,19 +23,16 @@
package org.onap.so.bpmn;
import org.junit.runner.RunWith;
-
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
-@SuiteClasses({"!**/service/*Test.class", "!**/subprocess/*Test.class", "!**/process/*Test.class",
- "!**/tasks/*Test.class", "!**/infrastructure/aai/*Test.class",
- "!**/infrastructure/scripts/*Test.class",
- "**/infrastructure/scripts/DoDeleteVfModuleVolumeV2Test.class",
- "**/infrastructure/scripts/DoUpdateNetworkInstanceTest.class",
- "**/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.class",
- "**/*Test.class"})
+@SuiteClasses({"!**/service/*Test.class", "!**/subprocess/*Test.class", "!**/process/*Test.class",
+ "!**/tasks/*Test.class", "!**/infrastructure/aai/*Test.class", "!**/infrastructure/scripts/*Test.class",
+ "**/infrastructure/scripts/DoDeleteVfModuleVolumeV2Test.class",
+ "**/infrastructure/scripts/DoUpdateNetworkInstanceTest.class",
+ "**/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.class", "**/*Test.class"})
public class AllTestsTestSuite {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/BeansTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/BeansTest.java
index f69521fd76..1c4074cae1 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/BeansTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/BeansTest.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.infrastructure;
import org.junit.Test;
-
import com.openpojo.validation.Validator;
import com.openpojo.validation.ValidatorBuilder;
import com.openpojo.validation.rule.impl.GetterMustExistRule;
@@ -38,35 +37,31 @@ import com.openpojo.reflection.filters.FilterPackageInfo;
public class BeansTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
-
- private PojoClassFilter enumFilter = new FilterEnum();
-
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ private PojoClassFilter enumFilter = new FilterEnum();
+
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity");
+ }
+
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule())
+
+ .with(new SetterTester()).with(new GetterTester()).with(new SetterTester()).with(new GetterTester())
- @Test
- public void pojoStructure() {
- test("org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity");
- }
+ .build();
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterMustExistRule())
-
- .with(new SetterTester())
- .with(new GetterTester())
- .with(new SetterTester())
- .with(new GetterTester())
-
- .build();
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, enumFilter,
+ new FilterNonConcrete());
+ }
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses,enumFilter,new FilterNonConcrete());
- }
-
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java
index ad9e210452..c2af155d51 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java
@@ -31,22 +31,19 @@ import org.springframework.util.StringUtils;
@EnableWebSecurity
public class WebSecurityConfigImpl extends WebSecurityConfig {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf().disable()
- .authorizeRequests()
- .antMatchers("/manage/health","/manage/info").permitAll()
- .antMatchers("/async/services/**", "/workflow/services/*", "/SDNCAdapterCallbackService", "/WorkflowMessage", "/vnfAdapterNotify", "/vnfAdapterRestNotify")
- .hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),",").toString())
- .and()
- .httpBasic();
- }
-
- @Override
- public void configure(WebSecurity web) throws Exception {
- super.configure(web);
- StrictHttpFirewall firewall = new MSOSpringFirewall();
- web.httpFirewall(firewall);
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll()
+ .antMatchers("/async/services/**", "/workflow/services/*", "/SDNCAdapterCallbackService",
+ "/WorkflowMessage", "/vnfAdapterNotify", "/vnfAdapterRestNotify")
+ .hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",").toString()).and().httpBasic();
+ }
+
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ super.configure(web);
+ StrictHttpFirewall firewall = new MSOSpringFirewall();
+ web.httpFirewall(firewall);
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResourcesTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResourcesTest.java
index 2e588b7078..289d97108f 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResourcesTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResourcesTest.java
@@ -28,10 +28,8 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.HashMap;
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -48,150 +46,157 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory;
@RunWith(MockitoJUnitRunner.class)
public class AAICreateResourcesTest {
-
- private AAICreateResources aaiCreateResources;
-
- private String projectName;
- private String serviceInstanceId;
- private String owningEntityId;
- private String owningEntityName;
- private String platformName;
- private String vnfId;
- private String lineOfBusiness;
- private String globalCustomerId;
- private String serviceType;
-
- @Spy
- private AAIResourcesClient aaiResourcesClient;
-
- @Before
- public void before() {
-
-
- aaiCreateResources = new AAICreateResources();
- aaiCreateResources.setAaiClient(aaiResourcesClient);
-
- projectName = "projectName";
- serviceInstanceId = "serviceInstanceId";
- owningEntityId = "owningEntityId";
- owningEntityName = "owningEntityName";
- platformName = "platformName";
- vnfId = "vnfId";
- lineOfBusiness = "lineOfBusiness";
- globalCustomerId = "globalCustomerId";
- serviceType = "serviceType";
- }
-
- @Test
- public void createAAIProjectTest() {
- doReturn(aaiResourcesClient).when(aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class), isA(Optional.class));
- doNothing().when(aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
-
-
- aaiCreateResources.createAAIProject(projectName, serviceInstanceId);
-
- AAIResourceUri projectURI = AAIUriFactory.createResourceUri(AAIObjectType.PROJECT, projectName);
-
- verify(aaiResourcesClient, times(1)).createIfNotExists(projectURI, Optional.empty());
- verify(aaiResourcesClient, times(1)).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- }
-
- @Test
- public void createAAIOwningEntityTest() {
- doReturn(aaiResourcesClient).when(aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class), isA(Optional.class));
- doNothing().when(aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
-
- aaiCreateResources.createAAIOwningEntity(owningEntityId, owningEntityName, serviceInstanceId);
-
- HashMap<String, String> owningEntityMap = new HashMap<>();
- owningEntityMap.put("owning-entity-name", owningEntityName);
- AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
-
- verify(aaiResourcesClient, times(1)).createIfNotExists(owningEntityURI, Optional.of(owningEntityMap));
- verify(aaiResourcesClient, times(1)).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- }
-
- @Test
- public void existsOwningEntityTest() {
- doReturn(true).when(aaiResourcesClient).exists(isA(AAIResourceUri.class));
-
- boolean expectedBoolean = aaiCreateResources.existsOwningEntity(owningEntityId);
-
- AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
-
- verify(aaiResourcesClient, times(1)).exists(owningEntityURI);
- assertTrue(expectedBoolean);
- }
-
- @Test
- public void connectOwningEntityandServiceInstanceTest() {
- doNothing().when(aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
-
- aaiCreateResources.connectOwningEntityandServiceInstance(owningEntityId, serviceInstanceId);
-
- verify(aaiResourcesClient, times(1)).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- }
-
- @Test
- public void createAAIPlatformTest() {
- doReturn(aaiResourcesClient).when(aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class), isA(Optional.class));
- doNothing().when(aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
-
- aaiCreateResources.createAAIPlatform(platformName, vnfId);
-
- AAIResourceUri platformURI = AAIUriFactory.createResourceUri(AAIObjectType.PLATFORM, platformName);
-
- verify(aaiResourcesClient, times(1)).createIfNotExists(platformURI, Optional.empty());
- verify(aaiResourcesClient, times(1)).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- }
-
- @Test
- public void createAAILineOfBusinessTest() {
- doReturn(aaiResourcesClient).when(aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class), isA(Optional.class));
- doNothing().when(aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
-
- aaiCreateResources.createAAILineOfBusiness(lineOfBusiness, vnfId);
-
- AAIResourceUri lineOfBusinessURI = AAIUriFactory.createResourceUri(AAIObjectType.LINE_OF_BUSINESS, lineOfBusiness);
-
- verify(aaiResourcesClient, times(1)).createIfNotExists(lineOfBusinessURI, Optional.empty());
- verify(aaiResourcesClient, times(1)).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- }
-
- @Test
- public void createAAIServiceInstanceTest() {
- doReturn(aaiResourcesClient).when(aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class), isA(Optional.class));
-
- aaiCreateResources.createAAIServiceInstance(globalCustomerId, serviceType, serviceInstanceId);
-
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustomerId,serviceType,serviceInstanceId);
-
- verify(aaiResourcesClient, times(1)).createIfNotExists(serviceInstanceURI, Optional.empty());
- }
-
- @Test
- public void getVnfInstanceTest() {
- AAIResultWrapper aaiResultWrapper = new AAIResultWrapper("vnfUriAaiResponse");
-
- doReturn(aaiResultWrapper).when(aaiResourcesClient).get(isA(AAIResourceUri.class));
-
- Optional<GenericVnf> actualVnf = aaiCreateResources.getVnfInstance(vnfId);
-
- AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
-
- verify(aaiResourcesClient, times(1)).get(vnfURI);
- assertEquals(actualVnf, aaiResultWrapper.asBean(GenericVnf.class));
- }
-
- @Test
- public void getVnfInstanceExceptionTest() {
- doThrow(RuntimeException.class).when(aaiResourcesClient).get(isA(AAIResourceUri.class));
-
- Optional<GenericVnf> actualVnf = aaiCreateResources.getVnfInstance(vnfId);
-
- AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
-
- verify(aaiResourcesClient, times(1)).get(vnfURI);
- assertEquals(actualVnf, Optional.empty());
- }
+
+ private AAICreateResources aaiCreateResources;
+
+ private String projectName;
+ private String serviceInstanceId;
+ private String owningEntityId;
+ private String owningEntityName;
+ private String platformName;
+ private String vnfId;
+ private String lineOfBusiness;
+ private String globalCustomerId;
+ private String serviceType;
+
+ @Spy
+ private AAIResourcesClient aaiResourcesClient;
+
+ @Before
+ public void before() {
+
+
+ aaiCreateResources = new AAICreateResources();
+ aaiCreateResources.setAaiClient(aaiResourcesClient);
+
+ projectName = "projectName";
+ serviceInstanceId = "serviceInstanceId";
+ owningEntityId = "owningEntityId";
+ owningEntityName = "owningEntityName";
+ platformName = "platformName";
+ vnfId = "vnfId";
+ lineOfBusiness = "lineOfBusiness";
+ globalCustomerId = "globalCustomerId";
+ serviceType = "serviceType";
+ }
+
+ @Test
+ public void createAAIProjectTest() {
+ doReturn(aaiResourcesClient).when(aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class),
+ isA(Optional.class));
+ doNothing().when(aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+
+
+ aaiCreateResources.createAAIProject(projectName, serviceInstanceId);
+
+ AAIResourceUri projectURI = AAIUriFactory.createResourceUri(AAIObjectType.PROJECT, projectName);
+
+ verify(aaiResourcesClient, times(1)).createIfNotExists(projectURI, Optional.empty());
+ verify(aaiResourcesClient, times(1)).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+ }
+
+ @Test
+ public void createAAIOwningEntityTest() {
+ doReturn(aaiResourcesClient).when(aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class),
+ isA(Optional.class));
+ doNothing().when(aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+
+ aaiCreateResources.createAAIOwningEntity(owningEntityId, owningEntityName, serviceInstanceId);
+
+ HashMap<String, String> owningEntityMap = new HashMap<>();
+ owningEntityMap.put("owning-entity-name", owningEntityName);
+ AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
+
+ verify(aaiResourcesClient, times(1)).createIfNotExists(owningEntityURI, Optional.of(owningEntityMap));
+ verify(aaiResourcesClient, times(1)).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+ }
+
+ @Test
+ public void existsOwningEntityTest() {
+ doReturn(true).when(aaiResourcesClient).exists(isA(AAIResourceUri.class));
+
+ boolean expectedBoolean = aaiCreateResources.existsOwningEntity(owningEntityId);
+
+ AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntityId);
+
+ verify(aaiResourcesClient, times(1)).exists(owningEntityURI);
+ assertTrue(expectedBoolean);
+ }
+
+ @Test
+ public void connectOwningEntityandServiceInstanceTest() {
+ doNothing().when(aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+
+ aaiCreateResources.connectOwningEntityandServiceInstance(owningEntityId, serviceInstanceId);
+
+ verify(aaiResourcesClient, times(1)).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+ }
+
+ @Test
+ public void createAAIPlatformTest() {
+ doReturn(aaiResourcesClient).when(aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class),
+ isA(Optional.class));
+ doNothing().when(aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+
+ aaiCreateResources.createAAIPlatform(platformName, vnfId);
+
+ AAIResourceUri platformURI = AAIUriFactory.createResourceUri(AAIObjectType.PLATFORM, platformName);
+
+ verify(aaiResourcesClient, times(1)).createIfNotExists(platformURI, Optional.empty());
+ verify(aaiResourcesClient, times(1)).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+ }
+
+ @Test
+ public void createAAILineOfBusinessTest() {
+ doReturn(aaiResourcesClient).when(aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class),
+ isA(Optional.class));
+ doNothing().when(aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+
+ aaiCreateResources.createAAILineOfBusiness(lineOfBusiness, vnfId);
+
+ AAIResourceUri lineOfBusinessURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.LINE_OF_BUSINESS, lineOfBusiness);
+
+ verify(aaiResourcesClient, times(1)).createIfNotExists(lineOfBusinessURI, Optional.empty());
+ verify(aaiResourcesClient, times(1)).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+ }
+
+ @Test
+ public void createAAIServiceInstanceTest() {
+ doReturn(aaiResourcesClient).when(aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class),
+ isA(Optional.class));
+
+ aaiCreateResources.createAAIServiceInstance(globalCustomerId, serviceType, serviceInstanceId);
+
+ AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
+ globalCustomerId, serviceType, serviceInstanceId);
+
+ verify(aaiResourcesClient, times(1)).createIfNotExists(serviceInstanceURI, Optional.empty());
+ }
+
+ @Test
+ public void getVnfInstanceTest() {
+ AAIResultWrapper aaiResultWrapper = new AAIResultWrapper("vnfUriAaiResponse");
+
+ doReturn(aaiResultWrapper).when(aaiResourcesClient).get(isA(AAIResourceUri.class));
+
+ Optional<GenericVnf> actualVnf = aaiCreateResources.getVnfInstance(vnfId);
+
+ AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
+
+ verify(aaiResourcesClient, times(1)).get(vnfURI);
+ assertEquals(actualVnf, aaiResultWrapper.asBean(GenericVnf.class));
+ }
+
+ @Test
+ public void getVnfInstanceExceptionTest() {
+ doThrow(RuntimeException.class).when(aaiResourcesClient).get(isA(AAIResourceUri.class));
+
+ Optional<GenericVnf> actualVnf = aaiCreateResources.getVnfInstance(vnfId);
+
+ AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
+
+ verify(aaiResourcesClient, times(1)).get(vnfURI);
+ assertEquals(actualVnf, Optional.empty());
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstanceTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstanceTest.java
index a540a6d2cc..1aca331a17 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstanceTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstanceTest.java
@@ -26,7 +26,6 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.junit.Before;
@@ -38,47 +37,47 @@ import org.mockito.MockitoAnnotations;
import org.onap.so.client.aai.AAIResourcesClient;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
-public class AAIDeleteServiceInstanceTest {
- private AAIDeleteServiceInstance aaiDeleteServiceInstance;
- @Mock
- private DelegateExecution execution;
-
- @Mock
- private AAIResourcesClient aaiResourcesClient;
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
-
- @Before
- public void before() {
- MockitoAnnotations.initMocks(this);
-
- aaiDeleteServiceInstance = new AAIDeleteServiceInstance();
- aaiDeleteServiceInstance.setAaiClient(aaiResourcesClient);
- }
-
- @Test
- public void executeTest() throws Exception {
- doReturn("serviceInstanceId").when(execution).getVariable("serviceInstanceId");
- doNothing().when(aaiResourcesClient).delete(isA(AAIResourceUri.class));
- doNothing().when(execution).setVariable(isA(String.class), isA(Boolean.class));
-
- aaiDeleteServiceInstance.execute(execution);
-
- verify(execution, times(1)).getVariable("serviceInstanceId");
- verify(aaiResourcesClient, times(1)).delete(isA(AAIResourceUri.class));
- verify(execution, times(1)).setVariable("GENDS_SuccessIndicator", true);
- }
-
- @Test
- public void executeExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- doReturn("testProcessKey").when(execution).getVariable("testProcessKey");
- doReturn("serviceInstanceId").when(execution).getVariable("serviceInstanceId");
- doThrow(RuntimeException.class).when(aaiResourcesClient).delete(isA(AAIResourceUri.class));
-
- aaiDeleteServiceInstance.execute(execution);
- }
+public class AAIDeleteServiceInstanceTest {
+ private AAIDeleteServiceInstance aaiDeleteServiceInstance;
+ @Mock
+ private DelegateExecution execution;
+
+ @Mock
+ private AAIResourcesClient aaiResourcesClient;
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+
+ @Before
+ public void before() {
+ MockitoAnnotations.initMocks(this);
+
+ aaiDeleteServiceInstance = new AAIDeleteServiceInstance();
+ aaiDeleteServiceInstance.setAaiClient(aaiResourcesClient);
+ }
+
+ @Test
+ public void executeTest() throws Exception {
+ doReturn("serviceInstanceId").when(execution).getVariable("serviceInstanceId");
+ doNothing().when(aaiResourcesClient).delete(isA(AAIResourceUri.class));
+ doNothing().when(execution).setVariable(isA(String.class), isA(Boolean.class));
+
+ aaiDeleteServiceInstance.execute(execution);
+
+ verify(execution, times(1)).getVariable("serviceInstanceId");
+ verify(aaiResourcesClient, times(1)).delete(isA(AAIResourceUri.class));
+ verify(execution, times(1)).setVariable("GENDS_SuccessIndicator", true);
+ }
+
+ @Test
+ public void executeExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ doReturn("testProcessKey").when(execution).getVariable("testProcessKey");
+ doReturn("serviceInstanceId").when(execution).getVariable("serviceInstanceId");
+ doThrow(RuntimeException.class).when(aaiResourcesClient).delete(isA(AAIResourceUri.class));
+
+ aaiDeleteServiceInstance.execute(execution);
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIServiceInstanceTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIServiceInstanceTest.java
index b68b787904..90576c9566 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIServiceInstanceTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIServiceInstanceTest.java
@@ -26,91 +26,91 @@ import org.junit.Test;
public class AAIServiceInstanceTest {
- AAIServiceInstance test = new AAIServiceInstance.AAIServiceInstanceBuilder()
- .setServiceInstanceName("serviceInstanceName").setServiceType("serviceType").setServiceRole("serviceRole")
- .setOrchestrationStatus("orchestrationStatus").setModelInvariantUuid("modelInvariantUuid")
- .setModelVersionId("modelVersionId").setEnvironmentContext("environmentContext")
- .setWorkloadContext("workloadContext").createAAIServiceInstance();
-
- @Test
- public void getServiceInstanceNameTest() throws Exception {
- test.getServiceInstanceName();
- }
-
- @Test
- public void setServiceInstanceNameTest() throws Exception {
- test.setServiceInstanceName("serviceInstanceName");
- }
-
- @Test
- public void getServiceTypeTest() throws Exception {
- test.getServiceType();
- }
-
- @Test
- public void setServiceTypeTest() throws Exception {
- test.setServiceType("serviceType");
- }
-
- @Test
- public void getServiceRoleTest() throws Exception {
- test.getServiceRole();
- }
-
- @Test
- public void setServiceRoleTest() throws Exception {
- test.setServiceRole("serviceRole");
- }
-
- @Test
- public void getOrchestrationStatusTest() throws Exception {
- test.getOrchestrationStatus();
- }
-
- @Test
- public void setOrchestrationStatusTest() throws Exception {
- test.setOrchestrationStatus("status");
- }
-
- @Test
- public void getModelInvariantUuidTest() throws Exception {
- test.getModelInvariantUuid();
- }
-
- @Test
- public void setModelInvariantUuidTest() throws Exception {
- test.setModelInvariantUuid("uuid");
- }
-
- @Test
- public void getModelVersionIdTest() throws Exception {
- test.getModelVersionId();
- }
-
- @Test
- public void setModelVersionIdTest() throws Exception {
- test.setModelVersionId("versionId");
- }
-
- @Test
- public void getEnvironmentContextTest() throws Exception {
- test.getEnvironmentContext();
- }
-
- @Test
- public void setEnvironmentContextTest() throws Exception {
- test.setEnvironmentContext("context");
- }
-
- @Test
- public void getWorkloadContextTest() throws Exception {
- test.getWorkloadContext();
- }
-
- @Test
- public void setWorkloadContextTest() throws Exception {
- test.setWorkloadContext("context");
- }
+ AAIServiceInstance test = new AAIServiceInstance.AAIServiceInstanceBuilder()
+ .setServiceInstanceName("serviceInstanceName").setServiceType("serviceType").setServiceRole("serviceRole")
+ .setOrchestrationStatus("orchestrationStatus").setModelInvariantUuid("modelInvariantUuid")
+ .setModelVersionId("modelVersionId").setEnvironmentContext("environmentContext")
+ .setWorkloadContext("workloadContext").createAAIServiceInstance();
+
+ @Test
+ public void getServiceInstanceNameTest() throws Exception {
+ test.getServiceInstanceName();
+ }
+
+ @Test
+ public void setServiceInstanceNameTest() throws Exception {
+ test.setServiceInstanceName("serviceInstanceName");
+ }
+
+ @Test
+ public void getServiceTypeTest() throws Exception {
+ test.getServiceType();
+ }
+
+ @Test
+ public void setServiceTypeTest() throws Exception {
+ test.setServiceType("serviceType");
+ }
+
+ @Test
+ public void getServiceRoleTest() throws Exception {
+ test.getServiceRole();
+ }
+
+ @Test
+ public void setServiceRoleTest() throws Exception {
+ test.setServiceRole("serviceRole");
+ }
+
+ @Test
+ public void getOrchestrationStatusTest() throws Exception {
+ test.getOrchestrationStatus();
+ }
+
+ @Test
+ public void setOrchestrationStatusTest() throws Exception {
+ test.setOrchestrationStatus("status");
+ }
+
+ @Test
+ public void getModelInvariantUuidTest() throws Exception {
+ test.getModelInvariantUuid();
+ }
+
+ @Test
+ public void setModelInvariantUuidTest() throws Exception {
+ test.setModelInvariantUuid("uuid");
+ }
+
+ @Test
+ public void getModelVersionIdTest() throws Exception {
+ test.getModelVersionId();
+ }
+
+ @Test
+ public void setModelVersionIdTest() throws Exception {
+ test.setModelVersionId("versionId");
+ }
+
+ @Test
+ public void getEnvironmentContextTest() throws Exception {
+ test.getEnvironmentContext();
+ }
+
+ @Test
+ public void setEnvironmentContextTest() throws Exception {
+ test.setEnvironmentContext("context");
+ }
+
+ @Test
+ public void getWorkloadContextTest() throws Exception {
+ test.getWorkloadContext();
+ }
+
+ @Test
+ public void setWorkloadContextTest() throws Exception {
+ test.setWorkloadContext("context");
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/common/name/generation/AAIObjectInstanceNameGeneratorTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/common/name/generation/AAIObjectInstanceNameGeneratorTest.java
index ebcce191e9..9030fa8328 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/common/name/generation/AAIObjectInstanceNameGeneratorTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/common/name/generation/AAIObjectInstanceNameGeneratorTest.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.common.name.generation;
import static org.junit.Assert.assertEquals;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
@@ -34,25 +33,25 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoInstanceGroup;
public class AAIObjectInstanceNameGeneratorTest {
- @Before
- public void before() {
- }
-
- @Test
- public void generateInstanceGroupNameTest() throws Exception {
-
- ModelInfoInstanceGroup modelVnfc = new ModelInfoInstanceGroup();
- modelVnfc.setFunction("vre");
- modelVnfc.setType("VNFC");
-
- InstanceGroup instanceGroup = new InstanceGroup();
- instanceGroup.setId("test-001");
- instanceGroup.setModelInfoInstanceGroup(modelVnfc);
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnf-123");
- vnf.setVnfName("test-vnf");
-
- assertEquals("test-vnf_vre", new AAIObjectInstanceNameGenerator().generateInstanceGroupName(instanceGroup, vnf));
- }
-
+ @Before
+ public void before() {}
+
+ @Test
+ public void generateInstanceGroupNameTest() throws Exception {
+
+ ModelInfoInstanceGroup modelVnfc = new ModelInfoInstanceGroup();
+ modelVnfc.setFunction("vre");
+ modelVnfc.setType("VNFC");
+
+ InstanceGroup instanceGroup = new InstanceGroup();
+ instanceGroup.setId("test-001");
+ instanceGroup.setModelInfoInstanceGroup(modelVnfc);
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnf-123");
+ vnf.setVnfName("test-vnf");
+
+ assertEquals("test-vnf_vre",
+ new AAIObjectInstanceNameGenerator().generateInstanceGroupName(instanceGroup, vnf));
+ }
+
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java
index b0ff82e3aa..c67b44e44a 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.junit.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -37,7 +36,8 @@ public class CancelDmaapSubscriptionTest {
DmaapClientTestImpl dmaapClientTest = new DmaapClientTestImpl();
delegate.setDmaapClient(dmaapClientTest);
DelegateExecution delegateExecution = mock(DelegateExecution.class);
- when(delegateExecution.getVariable(eq(ExecutionVariableNames.PNF_CORRELATION_ID))).thenReturn("testPnfCorrelationId");
+ when(delegateExecution.getVariable(eq(ExecutionVariableNames.PNF_CORRELATION_ID)))
+ .thenReturn("testPnfCorrelationId");
when(delegateExecution.getProcessBusinessKey()).thenReturn("testBusinessKey");
dmaapClientTest.registerForUpdate("testPnfCorrelationId", () -> {
});
@@ -46,4 +46,4 @@ public class CancelDmaapSubscriptionTest {
// then
assertThat(dmaapClientTest.haveRegisteredConsumer()).isFalse();
}
-} \ No newline at end of file
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForPnfCorrelationIdDelegateTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForPnfCorrelationIdDelegateTest.java
index 6a0aaf776e..4206d796f6 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForPnfCorrelationIdDelegateTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForPnfCorrelationIdDelegateTest.java
@@ -29,7 +29,6 @@ import static org.onap.so.bpmn.infrastructure.pnf.delegate.PnfManagementTestImpl
import static org.onap.so.bpmn.infrastructure.pnf.delegate.PnfManagementTestImpl.ID_WITH_ENTRY;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.AAI_CONTAINS_INFO_ABOUT_PNF;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_CORRELATION_ID;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.junit.Before;
@@ -46,9 +45,9 @@ public class CheckAaiForPnfCorrelationIdDelegateTest {
public static class ConnectionOkTests {
private CheckAaiForPnfCorrelationIdDelegate delegate;
-
+
@Rule
- public ExpectedException expectedException = ExpectedException.none();
+ public ExpectedException expectedException = ExpectedException.none();
@Before
public void setUp() {
@@ -94,9 +93,9 @@ public class CheckAaiForPnfCorrelationIdDelegateTest {
public static class NoConnectionTests {
private CheckAaiForPnfCorrelationIdDelegate delegate;
-
+
@Rule
- public ExpectedException expectedException = ExpectedException.none();
+ public ExpectedException expectedException = ExpectedException.none();
@Before
public void setUp() {
@@ -116,4 +115,4 @@ public class CheckAaiForPnfCorrelationIdDelegateTest {
verify(execution).setVariable(eq("WorkflowException"), any(WorkflowException.class));
}
}
-} \ No newline at end of file
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegateTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegateTest.java
index 571f64335f..5000ca017c 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegateTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegateTest.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.pnf.delegate;
@@ -30,7 +25,6 @@ import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableName
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_INSTANCE_NAME;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.SERVICE_MODEL_INFO;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.SKIP_POST_INSTANTIATION_CONFIGURATION;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -52,7 +46,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {CatalogDbClient.class, ExceptionBuilder.class, ConfigCheckerDelegate.class,
- ProcessEngineConfiguration.class})
+ ProcessEngineConfiguration.class})
public class ConfigCheckerDelegateTest {
private static String TEST_PROCESS_KEY = "processKey1";
@@ -64,14 +58,11 @@ public class ConfigCheckerDelegateTest {
/**
* Service model info json.
*/
- private static String TEST_SERVICE_MODEL_INFO = "{\n"
- + " \"modelType\":\"service\",\n"
- + " \"modelInvariantUuid\":\"539b7a2f-9524-4dbf-9eee-f2e05521df3f\",\n"
- + " \"modelInvariantId\":\"539b7a2f-9524-4dbf-9eee-f2e05521df3f\",\n"
- + " \"modelUuid\":\"f2daaac6-5017-4e1e-96c8-6a27dfbe1421\",\n"
- + " \"modelName\":\"PNF_demo_resource\",\n"
- + " \"modelVersion\":\"1.0\"\n"
- + " }";
+ private static String TEST_SERVICE_MODEL_INFO = "{\n" + " \"modelType\":\"service\",\n"
+ + " \"modelInvariantUuid\":\"539b7a2f-9524-4dbf-9eee-f2e05521df3f\",\n"
+ + " \"modelInvariantId\":\"539b7a2f-9524-4dbf-9eee-f2e05521df3f\",\n"
+ + " \"modelUuid\":\"f2daaac6-5017-4e1e-96c8-6a27dfbe1421\",\n"
+ + " \"modelName\":\"PNF_demo_resource\",\n" + " \"modelVersion\":\"1.0\"\n" + " }";
/**
* Testing model UUID, should be the same as specified in the TEST_SERVICE_MODEL_INFO.
@@ -94,7 +85,7 @@ public class ConfigCheckerDelegateTest {
List<PnfResourceCustomization> pnfResourceCustomizations = new ArrayList<>();
pnfResourceCustomizations.add(buildPnfResourceCustomization());
given(catalogDbClient.getPnfResourceCustomizationByModelUuid(TEST_MODEL_UUID))
- .willReturn(pnfResourceCustomizations);
+ .willReturn(pnfResourceCustomizations);
execution.setVariable("testProcessKey", TEST_PROCESS_KEY);
execution.setVariable(SERVICE_MODEL_INFO, TEST_SERVICE_MODEL_INFO);
}
@@ -128,12 +119,12 @@ public class ConfigCheckerDelegateTest {
@Test
public void testExecution_EmptyPnfResourceCustomization_exceptionThrown() {
given(catalogDbClient.getPnfResourceCustomizationByModelUuid("f2daaac6-5017-4e1e-96c8-6a27dfbe1421"))
- .willReturn(Collections.EMPTY_LIST);
+ .willReturn(Collections.EMPTY_LIST);
assertThatThrownBy(() -> configCheckerDelegate.execute(execution)).isInstanceOf(BpmnError.class);
assertThat(execution.getVariable("WorkflowExceptionErrorMessage")).asString()
- .contains("Unable to find the PNF resource customizations of model service UUID")
- .contains("f2daaac6-5017-4e1e-96c8-6a27dfbe1421");
+ .contains("Unable to find the PNF resource customizations of model service UUID")
+ .contains("f2daaac6-5017-4e1e-96c8-6a27dfbe1421");
assertThat(execution.getVariable("WorkflowException")).isInstanceOf(WorkflowException.class);
}
@@ -142,7 +133,7 @@ public class ConfigCheckerDelegateTest {
execution.removeVariable("serviceModelInfo");
assertThatThrownBy(() -> configCheckerDelegate.execute(execution)).isInstanceOf(BpmnError.class);
assertThat(execution.getVariable("WorkflowExceptionErrorMessage")).asString()
- .contains("Unable to find parameter serviceModelInfo");
+ .contains("Unable to find parameter serviceModelInfo");
assertThat(execution.getVariable("WorkflowException")).isInstanceOf(WorkflowException.class);
}
-} \ No newline at end of file
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegateTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegateTest.java
index 986edfeecf..c90235b103 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegateTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegateTest.java
@@ -27,7 +27,6 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_CORRELATION_ID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID;
-
import java.util.UUID;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.junit.Test;
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateRelationTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateRelationTest.java
index c743ee7018..85a9a5c166 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateRelationTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateRelationTest.java
@@ -23,7 +23,6 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
-
import java.io.IOException;
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegateTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegateTest.java
index 8a1cdfa4c0..597d111e2c 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegateTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegateTest.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
import org.junit.Test;
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java
index eb9f657d4f..446c73dda1 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java
@@ -27,7 +27,6 @@ import org.camunda.bpm.engine.runtime.MessageCorrelationBuilder;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
-
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@@ -74,7 +73,8 @@ public class InformDmaapClientTest {
private DelegateExecution mockDelegateExecution() {
DelegateExecution delegateExecution = mock(DelegateExecution.class);
- when(delegateExecution.getVariable(eq(ExecutionVariableNames.PNF_CORRELATION_ID))).thenReturn("testPnfCorrelationId");
+ when(delegateExecution.getVariable(eq(ExecutionVariableNames.PNF_CORRELATION_ID)))
+ .thenReturn("testPnfCorrelationId");
when(delegateExecution.getProcessBusinessKey()).thenReturn("testBusinessKey");
ProcessEngineServices processEngineServices = mock(ProcessEngineServices.class);
when(delegateExecution.getProcessEngineServices()).thenReturn(processEngineServices);
@@ -85,4 +85,4 @@ public class InformDmaapClientTest {
when(messageCorrelationBuilder.processInstanceBusinessKey(any())).thenReturn(messageCorrelationBuilder);
return delegateExecution;
}
-} \ No newline at end of file
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java
index 001815b206..6c8716cbd7 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java
@@ -24,7 +24,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_CORRELATION_ID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.SERVICE_INSTANCE_ID;
-
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.engine.delegate.BpmnError;
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementTestImpl.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementTestImpl.java
index 3a9d6d0055..8577d9555b 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementTestImpl.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfManagementTestImpl.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate;
import org.onap.aai.domain.yang.Pnf;
import org.onap.so.bpmn.infrastructure.pnf.management.PnfManagement;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@@ -51,8 +50,7 @@ public class PnfManagementTestImpl implements PnfManagement {
}
@Override
- public void createRelation(String serviceInstanceId, String pnfName) {
- }
+ public void createRelation(String serviceInstanceId, String pnfName) {}
public Map<String, Pnf> getCreated() {
return created;
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigAssignDelegateTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigAssignDelegateTest.java
index 8d817e5bca..110ee2146c 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigAssignDelegateTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigAssignDelegateTest.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.pnf.delegate;
@@ -32,7 +27,6 @@ import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableName
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_CUSTOMIZATION_UUID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_INSTANCE_NAME;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.SERVICE_INSTANCE_ID;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
@@ -72,7 +66,7 @@ public class PrepareConfigAssignDelegateTest {
private DelegateExecution execution = new DelegateExecutionFake();
@Before
- public void setUp(){
+ public void setUp() {
execution.setVariable("testProcessKey", TEST_PROCESS_KEY);
execution.setVariable(PNF_CORRELATION_ID, TEST_PNF_CORRELATION_ID);
execution.setVariable(MODEL_UUID, TEST_MODEL_UUID);
@@ -118,8 +112,8 @@ public class PrepareConfigAssignDelegateTest {
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(requestObject);
- ConfigAssignRequestPnf configAssignRequestPnf = mapper
- .treeToValue(tree.at("/config-assign-request"), ConfigAssignRequestPnf.class);
+ ConfigAssignRequestPnf configAssignRequestPnf =
+ mapper.treeToValue(tree.at("/config-assign-request"), ConfigAssignRequestPnf.class);
assertThat(configAssignRequestPnf.getResolutionKey()).matches(TEST_PNF_CORRELATION_ID);
ConfigAssignPropertiesForPnf properties = configAssignRequestPnf.getConfigAssignPropertiesForPnf();
@@ -133,4 +127,4 @@ public class PrepareConfigAssignDelegateTest {
fail("Check request body is json message" + e.getMessage());
}
}
-} \ No newline at end of file
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigDeployDelegateTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigDeployDelegateTest.java
index 0964d2146b..8d19d9e563 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigDeployDelegateTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PrepareConfigDeployDelegateTest.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.pnf.delegate;
@@ -34,7 +29,6 @@ import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableName
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_CUSTOMIZATION_UUID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_INSTANCE_NAME;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.SERVICE_INSTANCE_ID;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
@@ -119,7 +113,7 @@ public class PrepareConfigDeployDelegateTest {
}
@Test
- public void testExecution_failedAaiConnection_exceptionThrown(){
+ public void testExecution_failedAaiConnection_exceptionThrown() {
try {
/**
* Mock the IOException from AAI.
@@ -128,13 +122,14 @@ public class PrepareConfigDeployDelegateTest {
} catch (IOException e) {
e.printStackTrace();
}
- assertThatThrownBy(()->prepareConfigDeployDelegate.execute(execution)).isInstanceOf(BpmnError.class);
- assertThat(execution.getVariable("WorkflowExceptionErrorMessage")).asString().contains("Unable to fetch from AAI");
+ assertThatThrownBy(() -> prepareConfigDeployDelegate.execute(execution)).isInstanceOf(BpmnError.class);
+ assertThat(execution.getVariable("WorkflowExceptionErrorMessage")).asString()
+ .contains("Unable to fetch from AAI");
assertThat(execution.getVariable("WorkflowException")).isInstanceOf(WorkflowException.class);
}
@Test
- public void testExecution_aaiEntryNotExist_exceptionThrown(){
+ public void testExecution_aaiEntryNotExist_exceptionThrown() {
try {
/**
* Mock the AAI without PNF.
@@ -143,8 +138,9 @@ public class PrepareConfigDeployDelegateTest {
} catch (IOException e) {
e.printStackTrace();
}
- assertThatThrownBy(()->prepareConfigDeployDelegate.execute(execution)).isInstanceOf(BpmnError.class);
- assertThat(execution.getVariable("WorkflowExceptionErrorMessage")).asString().contains("AAI entry for PNF: " + TEST_PNF_CORRELATION_ID + " does not exist");
+ assertThatThrownBy(() -> prepareConfigDeployDelegate.execute(execution)).isInstanceOf(BpmnError.class);
+ assertThat(execution.getVariable("WorkflowExceptionErrorMessage")).asString()
+ .contains("AAI entry for PNF: " + TEST_PNF_CORRELATION_ID + " does not exist");
assertThat(execution.getVariable("WorkflowException")).isInstanceOf(WorkflowException.class);
}
@@ -167,12 +163,11 @@ public class PrepareConfigDeployDelegateTest {
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(requestObject);
- ConfigDeployRequestPnf configDeployRequestPnf = mapper
- .treeToValue(tree.at("/config-deploy-request"), ConfigDeployRequestPnf.class);
+ ConfigDeployRequestPnf configDeployRequestPnf =
+ mapper.treeToValue(tree.at("/config-deploy-request"), ConfigDeployRequestPnf.class);
assertThat(configDeployRequestPnf.getResolutionKey()).matches(TEST_PNF_CORRELATION_ID);
- ConfigDeployPropertiesForPnf properties = configDeployRequestPnf
- .getConfigDeployPropertiesForPnf();
+ ConfigDeployPropertiesForPnf properties = configDeployRequestPnf.getConfigDeployPropertiesForPnf();
assertThat(properties.getServiceInstanceId()).matches(TEST_SERVICE_INSTANCE_ID);
assertThat(properties.getPnfName()).matches(TEST_PNF_CORRELATION_ID);
assertThat(properties.getPnfId()).matches(TEST_PNF_UUID);
@@ -185,4 +180,4 @@ public class PrepareConfigDeployDelegateTest {
fail("Check request body is json message" + e.getMessage());
}
}
-} \ No newline at end of file
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationIdTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationIdTest.java
index 17a6ee09d8..8741208d26 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationIdTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationIdTest.java
@@ -23,7 +23,6 @@
package org.onap.so.bpmn.infrastructure.pnf.dmaap;
import static org.assertj.core.api.Assertions.assertThat;
-
import java.util.List;
import org.junit.Test;
@@ -41,12 +40,12 @@ public class JsonUtilForPnfCorrelationIdTest {
@Test
public void parseJsonSuccessful() {
- List<String> expectedResult = JsonUtilForPnfCorrelationId
- .parseJsonToGelAllPnfCorrelationId(JSON_EXAMPLE_WITH_PNF_CORRELATION_ID);
+ List<String> expectedResult =
+ JsonUtilForPnfCorrelationId.parseJsonToGelAllPnfCorrelationId(JSON_EXAMPLE_WITH_PNF_CORRELATION_ID);
assertThat(expectedResult).containsExactly("corrTest1", "corrTest2");
- List<String> expectedResult2 = JsonUtilForPnfCorrelationId
- .parseJsonToGelAllPnfCorrelationId(JSON_WITH_ONE_PNF_CORRELATION_ID);
+ List<String> expectedResult2 =
+ JsonUtilForPnfCorrelationId.parseJsonToGelAllPnfCorrelationId(JSON_WITH_ONE_PNF_CORRELATION_ID);
assertThat(expectedResult2).containsExactly("corrTest3");
}
@@ -59,8 +58,8 @@ public class JsonUtilForPnfCorrelationIdTest {
@Test
public void parseJson_emptyListReturnedWhenNothingFound() {
- List<String> expectedResult = JsonUtilForPnfCorrelationId
- .parseJsonToGelAllPnfCorrelationId(JSON_WITH_NO_PNF_CORRELATION_ID);
+ List<String> expectedResult =
+ JsonUtilForPnfCorrelationId.parseJsonToGelAllPnfCorrelationId(JSON_WITH_NO_PNF_CORRELATION_ID);
assertThat(expectedResult).isEmpty();
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClientTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClientTest.java
index cbfe6c1512..ca3373e8cb 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClientTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClientTest.java
@@ -30,14 +30,12 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
-
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
@@ -53,6 +51,7 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.onap.so.bpmn.infrastructure.pnf.dmaap.PnfEventReadyDmaapClient.DmaapTopicListenerThread;
import org.springframework.core.env.Environment;
+
@RunWith(MockitoJUnitRunner.class)
public class PnfEventReadyDmaapClientTest {
@@ -83,8 +82,8 @@ public class PnfEventReadyDmaapClientTest {
@Before
public void init() throws NoSuchFieldException, IllegalAccessException {
- when(env.getProperty(eq("pnf.dmaap.port"), eq(Integer.class))).thenReturn(PORT);
- when(env.getProperty(eq("pnf.dmaap.host"))).thenReturn(HOST);
+ when(env.getProperty(eq("pnf.dmaap.port"), eq(Integer.class))).thenReturn(PORT);
+ when(env.getProperty(eq("pnf.dmaap.host"))).thenReturn(HOST);
when(env.getProperty(eq("pnf.dmaap.protocol"))).thenReturn(PROTOCOL);
when(env.getProperty(eq("pnf.dmaap.uriPathPrefix"))).thenReturn(URI_PATH_PREFIX);
when(env.getProperty(eq("pnf.dmaap.topicName"))).thenReturn(EVENT_TOPIC_TEST);
@@ -102,56 +101,60 @@ public class PnfEventReadyDmaapClientTest {
/**
* Test run method, where the are following conditions:
- * <p> - DmaapThreadListener is running, flag is set to true
- * <p> - map is filled with one entry with the key that we get from response
- * <p> run method should invoke thread from map to notify camunda process, remove element from the map (map is
- * empty) and shutdown the executor because of empty map
+ * <p>
+ * - DmaapThreadListener is running, flag is set to true
+ * <p>
+ * - map is filled with one entry with the key that we get from response
+ * <p>
+ * run method should invoke thread from map to notify camunda process, remove element from the map (map is empty)
+ * and shutdown the executor because of empty map
*/
@Test
- public void pnfCorrelationIdIsFoundInHttpResponse_notifyAboutPnfReady()
- throws IOException {
- when(httpClientMock.execute(any(HttpGet.class))).
- thenReturn(createResponse(String.format(JSON_EXAMPLE_WITH_PNF_CORRELATION_ID, PNF_CORRELATION_ID)));
+ public void pnfCorrelationIdIsFoundInHttpResponse_notifyAboutPnfReady() throws IOException {
+ when(httpClientMock.execute(any(HttpGet.class)))
+ .thenReturn(createResponse(String.format(JSON_EXAMPLE_WITH_PNF_CORRELATION_ID, PNF_CORRELATION_ID)));
testedObjectInnerClassThread.run();
ArgumentCaptor<HttpGet> captor1 = ArgumentCaptor.forClass(HttpGet.class);
- verify(httpClientMock).execute(captor1.capture());
-
- assertEquals(captor1.getValue().getURI().getHost(),HOST);
- assertEquals(captor1.getValue().getURI().getPort(),PORT);
- assertEquals(captor1.getValue().getURI().getScheme(),PROTOCOL);
- assertEquals(captor1.getValue().getURI().getPath(),"/" + URI_PATH_PREFIX + "/" + EVENT_TOPIC_TEST + "/" + CONSUMER_GROUP + "/" + CONSUMER_ID + "");
-
- //verify(threadMockToNotifyCamundaFlow).run();
+ verify(httpClientMock).execute(captor1.capture());
+
+ assertEquals(captor1.getValue().getURI().getHost(), HOST);
+ assertEquals(captor1.getValue().getURI().getPort(), PORT);
+ assertEquals(captor1.getValue().getURI().getScheme(), PROTOCOL);
+ assertEquals(captor1.getValue().getURI().getPath(),
+ "/" + URI_PATH_PREFIX + "/" + EVENT_TOPIC_TEST + "/" + CONSUMER_GROUP + "/" + CONSUMER_ID + "");
+
+ // verify(threadMockToNotifyCamundaFlow).run();
verify(executorMock).shutdown();
}
/**
* Test run method, where the are following conditions:
- * <p> - DmaapThreadListener is running, flag is set to true
- * <p> - map is filled with one entry with the pnfCorrelationId that does not match to pnfCorrelationId
- * taken from http response. run method should not do anything with the map not run any thread to notify camunda
- * process
+ * <p>
+ * - DmaapThreadListener is running, flag is set to true
+ * <p>
+ * - map is filled with one entry with the pnfCorrelationId that does not match to pnfCorrelationId taken from http
+ * response. run method should not do anything with the map not run any thread to notify camunda process
*/
@Test
- public void pnfCorrelationIdIsFoundInHttpResponse_NotFoundInMap()
- throws IOException {
- when(httpClientMock.execute(any(HttpGet.class))).
- thenReturn(createResponse(
- String.format(JSON_EXAMPLE_WITH_PNF_CORRELATION_ID, PNF_CORRELATION_ID_NOT_FOUND_IN_MAP)));
+ public void pnfCorrelationIdIsFoundInHttpResponse_NotFoundInMap() throws IOException {
+ when(httpClientMock.execute(any(HttpGet.class))).thenReturn(createResponse(
+ String.format(JSON_EXAMPLE_WITH_PNF_CORRELATION_ID, PNF_CORRELATION_ID_NOT_FOUND_IN_MAP)));
testedObjectInnerClassThread.run();
verifyZeroInteractions(threadMockToNotifyCamundaFlow, executorMock);
}
/**
* Test run method, where the are following conditions:
- * <p> - DmaapThreadListener is running, flag is set to true
- * <p> - map is filled with one entry with the pnfCorrelationId but no correlation id is taken from HttpResponse
- * run method should not do anything with the map and not run any thread to notify camunda process
+ * <p>
+ * - DmaapThreadListener is running, flag is set to true
+ * <p>
+ * - map is filled with one entry with the pnfCorrelationId but no correlation id is taken from HttpResponse run
+ * method should not do anything with the map and not run any thread to notify camunda process
*/
@Test
public void pnfCorrelationIdIsNotFoundInHttpResponse() throws IOException {
- when(httpClientMock.execute(any(HttpGet.class))).
- thenReturn(createResponse(JSON_EXAMPLE_WITH_NO_PNF_CORRELATION_ID));
+ when(httpClientMock.execute(any(HttpGet.class)))
+ .thenReturn(createResponse(JSON_EXAMPLE_WITH_NO_PNF_CORRELATION_ID));
testedObjectInnerClassThread.run();
verifyZeroInteractions(threadMockToNotifyCamundaFlow, executorMock);
}
@@ -167,8 +170,7 @@ public class PnfEventReadyDmaapClientTest {
executorField.set(testedObject, executorMock);
executorField.setAccessible(false);
- Field pnfCorrelationToThreadMapField = testedObject.getClass()
- .getDeclaredField("pnfCorrelationIdToThreadMap");
+ Field pnfCorrelationToThreadMapField = testedObject.getClass().getDeclaredField("pnfCorrelationIdToThreadMap");
pnfCorrelationToThreadMapField.setAccessible(true);
Map<String, Runnable> pnfCorrelationToThreadMap = new ConcurrentHashMap<>();
pnfCorrelationToThreadMap.put(PNF_CORRELATION_ID, threadMockToNotifyCamundaFlow);
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/vfcmodel/VfcModelPojoTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/vfcmodel/VfcModelPojoTest.java
index 239361d306..61a4654668 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/vfcmodel/VfcModelPojoTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/vfcmodel/VfcModelPojoTest.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.infrastructure.vfcmodel;
import org.junit.Test;
-
import com.openpojo.validation.Validator;
import com.openpojo.validation.ValidatorBuilder;
import com.openpojo.validation.rule.impl.NoNestedClassRule;
@@ -30,16 +29,12 @@ import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
public class VfcModelPojoTest {
- private String packageName = "org.onap.so.bpmn.infrastructure.vfcmodel";
+ private String packageName = "org.onap.so.bpmn.infrastructure.vfcmodel";
- @Test
- public void validate() {
- Validator validator = ValidatorBuilder.create()
- .with(new NoNestedClassRule())
- .with(new NoPublicFieldsRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
- validator.validate(packageName);
- }
+ @Test
+ public void validate() {
+ Validator validator = ValidatorBuilder.create().with(new NoNestedClassRule()).with(new NoPublicFieldsRule())
+ .with(new SetterTester()).with(new GetterTester()).build();
+ validator.validate(packageName);
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactoryTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactoryTest.java
index 6e22123996..0b4050beec 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactoryTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactoryTest.java
@@ -20,7 +20,6 @@
package org.onap.so.bpmn.infrastructure.workflow.service;
import static org.mockito.Mockito.doReturn;
-
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -38,80 +37,53 @@ public class ServicePluginFactoryTest {
@Spy
ServicePluginFactory servicePluginFactory;
- String uuiRequest = "{"
- + " \"service\":{"
- + " \"name\":\"ONAP_223531\","
- + " \"description\":\"ONAP_1546\","
- + " \"serviceInvariantUuid\":\"4a09419a-c9fd-4a53-b1bd-b49603169ca1\","
- + " \"serviceUuid\":\"1bd0eae6-2dcc-4461-9ae6-56d641f369d6\","
- + " \"globalSubscriberId\":\"test_custormer\","
- + " \"serviceType\":\"example-service-type\","
- + " \"parameters\":{"
- + " \"locationConstraints\":["
- + " ],"
- + " \"resources\":["
- + " {"
- + " \"resourceName\":\"vEPC_ONAP01\","
- + " \"resourceInvariantUuid\":\"36ebe421-283a-4ee8-92f1-d09e7c44b911\","
- + " \"resourceUuid\":\"27a0e235-b67a-4ea4-a0cf-25761afed111\","
- + " \"resourceCustomizationUuid\":\"47a0e235-b67a-4ea4-a0cf-25761afed231\","
- + " \"parameters\":{"
- + " \"locationConstraints\":["
- + " {"
- + " \"vnfProfileId\":\"b244d433-8c9c-49ad-9c70-8e34b8dc8328\","
- + " \"locationConstraints\":{"
- + " \"vimId\":\"vmware_vio\""
- + " }"
- + " },"
- + " {"
- + " \"vnfProfileId\":\"8a9f7c48-21ce-41b7-95b8-a8ac61ccb1ff\","
- + " \"locationConstraints\":{"
- + " \"vimId\":\"core-dc_RegionOne\""
- + " }"
- + " }"
- + " ],"
- + " \"resources\":["
- + " ],"
- + " \"requestInputs\":{"
- + " \"sdncontroller\":\"\""
- + " }"
- + " }"
- + " },"
- + " {"
- + " \"resourceName\":\"VL OVERLAYTUNNEL\","
- + " \"resourceInvariantUuid\":\"184494cf-472f-436f-82e2-d83dddde21cb\","
- + " \"resourceUuid\":\"95bc3e59-c9c5-458f-ad6e-78874ab4b3cc\","
- + " \"resourceCustomizationUuid\":\"27a0e235-b67a-4ea4-a0cf-25761afed232\","
- + " \"parameters\":{"
- + " \"locationConstraints\":["
- + " ],"
- + " \"resources\":["
- + " ],"
- + " \"requestInputs\":{"
- + " }"
- + " }"
- + " }"
- + " ],"
- + " \"requestInputs\":{"
- + " \"vlunderlayvpn0_name\":\"l3connect\","
- + " \"vlunderlayvpn0_site1_id\":\"IP-WAN-Controller-1\","
- + " \"vlunderlayvpn0_site2_id\":\"SPTNController\","
- + " \"vlunderlayvpn0_site1_networkName\":\"network1,network2\","
- + " \"vlunderlayvpn0_site2_networkName\":\"network3,network4\","
- + " \"vlunderlayvpn0_site1_routerId\":\"a8098c1a-f86e-11da-bd1a-00112444be1a\","
- + " \"vlunderlayvpn0_site2_routerId\":\"a8098c1a-f86e-11da-bd1a-00112444be1e\","
- + " \"vlunderlayvpn0_site2_importRT1\":\"200:1,200:2\","
- + " \"vlunderlayvpn0_site1_exportRT1\":\"300:1,300:2\","
- + " \"vlunderlayvpn0_site2_exportRT1\":\"400:1,400:2\","
- + " \"vlunderlayvpn0_site1_vni\":\"2000\","
- + " \"vlunderlayvpn0_site2_vni\":\"3000\","
- + " \"vlunderlayvpn0_tunnelType\":\"L3-DCI\","
- + " \"CallSource\":\"NOT-ExternalAPI\","
- + " \"sotnconnectivity\":\"\""
- + " }"
- + " }"
- + " }"
- + "}";
+ String uuiRequest = "{" + " \"service\":{" + " \"name\":\"ONAP_223531\","
+ + " \"description\":\"ONAP_1546\","
+ + " \"serviceInvariantUuid\":\"4a09419a-c9fd-4a53-b1bd-b49603169ca1\","
+ + " \"serviceUuid\":\"1bd0eae6-2dcc-4461-9ae6-56d641f369d6\","
+ + " \"globalSubscriberId\":\"test_custormer\"," + " \"serviceType\":\"example-service-type\","
+ + " \"parameters\":{" + " \"locationConstraints\":[" + " ],"
+ + " \"resources\":[" + " {"
+ + " \"resourceName\":\"vEPC_ONAP01\","
+ + " \"resourceInvariantUuid\":\"36ebe421-283a-4ee8-92f1-d09e7c44b911\","
+ + " \"resourceUuid\":\"27a0e235-b67a-4ea4-a0cf-25761afed111\","
+ + " \"resourceCustomizationUuid\":\"47a0e235-b67a-4ea4-a0cf-25761afed231\","
+ + " \"parameters\":{" + " \"locationConstraints\":["
+ + " {"
+ + " \"vnfProfileId\":\"b244d433-8c9c-49ad-9c70-8e34b8dc8328\","
+ + " \"locationConstraints\":{"
+ + " \"vimId\":\"vmware_vio\"" + " }"
+ + " }," + " {"
+ + " \"vnfProfileId\":\"8a9f7c48-21ce-41b7-95b8-a8ac61ccb1ff\","
+ + " \"locationConstraints\":{"
+ + " \"vimId\":\"core-dc_RegionOne\""
+ + " }" + " }" + " ],"
+ + " \"resources\":[" + " ],"
+ + " \"requestInputs\":{" + " \"sdncontroller\":\"\""
+ + " }" + " }" + " }," + " {"
+ + " \"resourceName\":\"VL OVERLAYTUNNEL\","
+ + " \"resourceInvariantUuid\":\"184494cf-472f-436f-82e2-d83dddde21cb\","
+ + " \"resourceUuid\":\"95bc3e59-c9c5-458f-ad6e-78874ab4b3cc\","
+ + " \"resourceCustomizationUuid\":\"27a0e235-b67a-4ea4-a0cf-25761afed232\","
+ + " \"parameters\":{" + " \"locationConstraints\":["
+ + " ]," + " \"resources\":[" + " ],"
+ + " \"requestInputs\":{" + " }" + " }"
+ + " }" + " ]," + " \"requestInputs\":{"
+ + " \"vlunderlayvpn0_name\":\"l3connect\","
+ + " \"vlunderlayvpn0_site1_id\":\"IP-WAN-Controller-1\","
+ + " \"vlunderlayvpn0_site2_id\":\"SPTNController\","
+ + " \"vlunderlayvpn0_site1_networkName\":\"network1,network2\","
+ + " \"vlunderlayvpn0_site2_networkName\":\"network3,network4\","
+ + " \"vlunderlayvpn0_site1_routerId\":\"a8098c1a-f86e-11da-bd1a-00112444be1a\","
+ + " \"vlunderlayvpn0_site2_routerId\":\"a8098c1a-f86e-11da-bd1a-00112444be1e\","
+ + " \"vlunderlayvpn0_site2_importRT1\":\"200:1,200:2\","
+ + " \"vlunderlayvpn0_site1_exportRT1\":\"300:1,300:2\","
+ + " \"vlunderlayvpn0_site2_exportRT1\":\"400:1,400:2\","
+ + " \"vlunderlayvpn0_site1_vni\":\"2000\","
+ + " \"vlunderlayvpn0_site2_vni\":\"3000\","
+ + " \"vlunderlayvpn0_tunnelType\":\"L3-DCI\","
+ + " \"CallSource\":\"NOT-ExternalAPI\"," + " \"sotnconnectivity\":\"\""
+ + " }" + " }" + " }" + "}";
@Test
@@ -123,16 +95,14 @@ public class ServicePluginFactoryTest {
@Test
public void doProcessSiteLocation_uuiObjectNull() {
String faultyJsonInput = "site_address,sotncondition_clientsignal";
- String result = servicePluginFactory.doProcessSiteLocation(
- serviceDecomposition, faultyJsonInput);
+ String result = servicePluginFactory.doProcessSiteLocation(serviceDecomposition, faultyJsonInput);
Assert.assertEquals(result, faultyJsonInput);
}
@Test
public void doProcessSiteLocation_isSiteLocationLocal() {
String jsonWithOnlyNeededValues = "{\"site_address\":\"\",\"sotncondition_clientsignal\":\"\"}";
- String result = servicePluginFactory.doProcessSiteLocation(
- serviceDecomposition, jsonWithOnlyNeededValues);
+ String result = servicePluginFactory.doProcessSiteLocation(serviceDecomposition, jsonWithOnlyNeededValues);
Assert.assertEquals(result, jsonWithOnlyNeededValues);
}
@@ -153,7 +123,7 @@ public class ServicePluginFactoryTest {
@Test
public void doTPResourcesAllocation_isNeedAllocateCrossTPResources() {
- //doReturn(null).when(servicePluginFactory).getTPsfromAAI();
+ // doReturn(null).when(servicePluginFactory).getTPsfromAAI();
String jsonWithOnlyNeededValues = "{\"site_address\":\"\",\"sotncondition_clientsignal\":\"\"}";
String result = servicePluginFactory.doTPResourcesAllocation(null, jsonWithOnlyNeededValues);
Assert.assertEquals(result, jsonWithOnlyNeededValues);
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/HeaderUtilTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/HeaderUtilTest.java
index ca8ec22088..f523e7ab1d 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/HeaderUtilTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/HeaderUtilTest.java
@@ -20,15 +20,14 @@
package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
public class HeaderUtilTest {
@Test
public void getAuthorizationTest() throws Exception {
- String authorization = HeaderUtil.getAuthorization(HeaderUtil.USER, HeaderUtil.PASS);
- assertEquals("Basic YWRtaW46S3A4Yko0U1hzek0wV1hsaGFrM2VIbGNzZTJnQXc4NHZhb0dHbUp2VXkyVQ==", authorization);
+ String authorization = HeaderUtil.getAuthorization(HeaderUtil.USER, HeaderUtil.PASS);
+ assertEquals("Basic YWRtaW46S3A4Yko0U1hzek0wV1hsaGFrM2VIbGNzZTJnQXc4NHZhb0dHbUp2VXkyVQ==", authorization);
}
-} \ No newline at end of file
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilderTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilderTest.java
index 4ac131f873..6f884cb126 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilderTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilderTest.java
@@ -20,13 +20,11 @@
package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder;
import static org.junit.Assert.assertEquals;
-
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngineServices;
import org.camunda.bpm.engine.delegate.DelegateExecution;
@@ -52,10 +50,10 @@ public class AbstractBuilderTest {
DelegateExecution delegateExecution = new DelegateExecution() {
private String operType;
- private String resourceType;
- private String requestId;
+ private String resourceType;
+ private String requestId;
- @Override
+ @Override
public String getProcessInstanceId() {
return null;
}
@@ -207,14 +205,14 @@ public class AbstractBuilderTest {
@Override
public Object getVariable(String s) {
- if (AbstractBuilder.OPERATION_TYPE.equals(s)) {
- return operType;
- } else if (AbstractBuilder.RESOURCE_TYPE.equals(s)) {
- return resourceType;
- } else if ("msoRequestId".equals(s)) {
- return requestId;
- }
- return null;
+ if (AbstractBuilder.OPERATION_TYPE.equals(s)) {
+ return operType;
+ } else if (AbstractBuilder.RESOURCE_TYPE.equals(s)) {
+ return resourceType;
+ } else if ("msoRequestId".equals(s)) {
+ return requestId;
+ }
+ return null;
}
@Override
@@ -254,13 +252,13 @@ public class AbstractBuilderTest {
@Override
public void setVariable(String s, Object o) {
- if (AbstractBuilder.OPERATION_TYPE.equals(s)) {
- operType = (String) o;
- } else if (AbstractBuilder.RESOURCE_TYPE.equals(s)) {
- resourceType = (String) o;
- } else if ("msoRequestId".equals(s)) {
- requestId = (String) o;
- }
+ if (AbstractBuilder.OPERATION_TYPE.equals(s)) {
+ operType = (String) o;
+ } else if (AbstractBuilder.RESOURCE_TYPE.equals(s)) {
+ resourceType = (String) o;
+ } else if ("msoRequestId".equals(s)) {
+ requestId = (String) o;
+ }
}
@Override
@@ -328,27 +326,27 @@ public class AbstractBuilderTest {
}
- @Override
- public ProcessEngine getProcessEngine(){
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public ProcessEngine getProcessEngine() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- @Override
- public void setProcessBusinessKey(String arg0){
- // TODO Auto-generated method stub
+ @Override
+ public void setProcessBusinessKey(String arg0) {
+ // TODO Auto-generated method stub
- }
+ }
};
@Test
public void requestActionGetIntValueTest() {
- assertEquals(0, RequestAction.CREATE_NETWORK_INSTANCE.getIntValue());
+ assertEquals(0, RequestAction.CREATE_NETWORK_INSTANCE.getIntValue());
}
@Test
public void svcActionGetIntValueTest() {
- assertEquals(0, SvcAction.RESERVE.getIntValue());
+ assertEquals(0, SvcAction.RESERVE.getIntValue());
}
@Test
@@ -358,81 +356,93 @@ public class AbstractBuilderTest {
@Test
public void getRequestActionBlankOperationTypeTest() throws Exception {
- assertEquals(AbstractBuilder.RequestAction.CREATE_NETWORK_INSTANCE.getName(), abstractBuilder.getRequestAction(delegateExecution));
+ assertEquals(AbstractBuilder.RequestAction.CREATE_NETWORK_INSTANCE.getName(),
+ abstractBuilder.getRequestAction(delegateExecution));
}
@Test
public void getRequestActionDeleteOperationTypeBlankResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "");
- assertEquals(AbstractBuilder.RequestAction.DELETE_SERVICE_INSTANCE.getName(), abstractBuilder.getRequestAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "");
+ assertEquals(AbstractBuilder.RequestAction.DELETE_SERVICE_INSTANCE.getName(),
+ abstractBuilder.getRequestAction(delegateExecution));
}
@Test
public void getRequestActionDeleteOperationTypeBadResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "bad");
- assertEquals(AbstractBuilder.RequestAction.DELETE_SERVICE_INSTANCE.getName(), abstractBuilder.getRequestAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "bad");
+ assertEquals(AbstractBuilder.RequestAction.DELETE_SERVICE_INSTANCE.getName(),
+ abstractBuilder.getRequestAction(delegateExecution));
}
@Test
public void getRequestActionDeleteOperationTypeOverlayResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "overlay");
- assertEquals(AbstractBuilder.RequestAction.DEACTIVATE_DCI_NETWORK_INSTANCE.getName(), abstractBuilder.getRequestAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "overlay");
+ assertEquals(AbstractBuilder.RequestAction.DEACTIVATE_DCI_NETWORK_INSTANCE.getName(),
+ abstractBuilder.getRequestAction(delegateExecution));
}
@Test
public void getRequestActionDeleteOperationTypeUnderlayResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "underlay");
- assertEquals(AbstractBuilder.RequestAction.DELETE_NETWORK_INSTANCE.getName(), abstractBuilder.getRequestAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "underlay");
+ assertEquals(AbstractBuilder.RequestAction.DELETE_NETWORK_INSTANCE.getName(),
+ abstractBuilder.getRequestAction(delegateExecution));
}
@Test
public void getRequestActionDeleteOperationTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
- assertEquals(AbstractBuilder.RequestAction.DELETE_SERVICE_INSTANCE.getName(), abstractBuilder.getRequestAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
+ assertEquals(AbstractBuilder.RequestAction.DELETE_SERVICE_INSTANCE.getName(),
+ abstractBuilder.getRequestAction(delegateExecution));
}
@Test
public void getRequestActionCreateOperationTypeBlankResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "");
- assertEquals(AbstractBuilder.RequestAction.CREATE_SERVICE_INSTANCE.getName(), abstractBuilder.getRequestAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "");
+ assertEquals(AbstractBuilder.RequestAction.CREATE_SERVICE_INSTANCE.getName(),
+ abstractBuilder.getRequestAction(delegateExecution));
}
@Test
public void getRequestActionCreateOperationTypeBadResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "bad");
- assertEquals(AbstractBuilder.RequestAction.CREATE_SERVICE_INSTANCE.getName(), abstractBuilder.getRequestAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "bad");
+ assertEquals(AbstractBuilder.RequestAction.CREATE_SERVICE_INSTANCE.getName(),
+ abstractBuilder.getRequestAction(delegateExecution));
}
@Test
public void getRequestActionCreateOperationTypeOverlayResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "overlay");
- assertEquals(AbstractBuilder.RequestAction.ACTIVATE_DCI_NETWORK_INSTANCE.getName(), abstractBuilder.getRequestAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "overlay");
+ assertEquals(AbstractBuilder.RequestAction.ACTIVATE_DCI_NETWORK_INSTANCE.getName(),
+ abstractBuilder.getRequestAction(delegateExecution));
}
@Test
public void getRequestActionCreateOperationTypeUnderlayResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "underlay");
- assertEquals(AbstractBuilder.RequestAction.CREATE_NETWORK_INSTANCE.getName(), abstractBuilder.getRequestAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "underlay");
+ assertEquals(AbstractBuilder.RequestAction.CREATE_NETWORK_INSTANCE.getName(),
+ abstractBuilder.getRequestAction(delegateExecution));
}
@Test
public void getRequestActionCreateOperationTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
- assertEquals(AbstractBuilder.RequestAction.CREATE_SERVICE_INSTANCE.getName(), abstractBuilder.getRequestAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
+ assertEquals(AbstractBuilder.RequestAction.CREATE_SERVICE_INSTANCE.getName(),
+ abstractBuilder.getRequestAction(delegateExecution));
}
@Test
public void getRequestActionBadOperationType() {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, "bad");
- assertEquals(AbstractBuilder.RequestAction.CREATE_NETWORK_INSTANCE.getName(), abstractBuilder.getRequestAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, "bad");
+ assertEquals(AbstractBuilder.RequestAction.CREATE_NETWORK_INSTANCE.getName(),
+ abstractBuilder.getRequestAction(delegateExecution));
}
@Test
@@ -442,95 +452,95 @@ public class AbstractBuilderTest {
@Test
public void getSvcActionDeleteOperationTypeBlankResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "");
- assertEquals(AbstractBuilder.SvcAction.UNASSIGN.getName(), abstractBuilder.getSvcAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "");
+ assertEquals(AbstractBuilder.SvcAction.UNASSIGN.getName(), abstractBuilder.getSvcAction(delegateExecution));
}
@Test
public void getSvcActionDeleteOperationTypeBadResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "bad");
- assertEquals(AbstractBuilder.SvcAction.UNASSIGN.getName(), abstractBuilder.getSvcAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "bad");
+ assertEquals(AbstractBuilder.SvcAction.UNASSIGN.getName(), abstractBuilder.getSvcAction(delegateExecution));
}
@Test
public void getSvcActionDeleteOperationTypeOverlayResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "overlay");
- assertEquals(AbstractBuilder.SvcAction.DEACTIVATE.getName(), abstractBuilder.getSvcAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "overlay");
+ assertEquals(AbstractBuilder.SvcAction.DEACTIVATE.getName(), abstractBuilder.getSvcAction(delegateExecution));
}
@Test
public void getSvcActionDeleteOperationTypeUnderlayResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "underlay");
- assertEquals(AbstractBuilder.SvcAction.DELETE.getName(), abstractBuilder.getSvcAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "underlay");
+ assertEquals(AbstractBuilder.SvcAction.DELETE.getName(), abstractBuilder.getSvcAction(delegateExecution));
}
@Test
public void getSvcActionDeleteOperationTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
- assertEquals(AbstractBuilder.SvcAction.UNASSIGN.getName(), abstractBuilder.getSvcAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.DELETE);
+ assertEquals(AbstractBuilder.SvcAction.UNASSIGN.getName(), abstractBuilder.getSvcAction(delegateExecution));
}
@Test
public void getSvcActionCreateOperationTypeBlankResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "");
- assertEquals(AbstractBuilder.SvcAction.ASSIGN.getName(), abstractBuilder.getSvcAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "");
+ assertEquals(AbstractBuilder.SvcAction.ASSIGN.getName(), abstractBuilder.getSvcAction(delegateExecution));
}
@Test
public void getSvcActionCreateOperationTypeBadResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "bad");
- assertEquals(AbstractBuilder.SvcAction.ASSIGN.getName(), abstractBuilder.getSvcAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "bad");
+ assertEquals(AbstractBuilder.SvcAction.ASSIGN.getName(), abstractBuilder.getSvcAction(delegateExecution));
}
@Test
public void getSvcActionCreateOperationTypeOverlayResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "overlay");
- assertEquals(AbstractBuilder.SvcAction.ACTIVATE.getName(), abstractBuilder.getSvcAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "overlay");
+ assertEquals(AbstractBuilder.SvcAction.ACTIVATE.getName(), abstractBuilder.getSvcAction(delegateExecution));
}
@Test
public void getSvcActionCreateOperationTypeUnderlayResourceTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
- delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "underlay");
- assertEquals(AbstractBuilder.SvcAction.CREATE.getName(), abstractBuilder.getSvcAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
+ delegateExecution.setVariable(AbstractBuilder.RESOURCE_TYPE, "underlay");
+ assertEquals(AbstractBuilder.SvcAction.CREATE.getName(), abstractBuilder.getSvcAction(delegateExecution));
}
@Test
public void getSvcActionCreateOperationTypeTest() throws Exception {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
- assertEquals(AbstractBuilder.SvcAction.ASSIGN.getName(), abstractBuilder.getSvcAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, RequestsDbConstant.OperationType.CREATE);
+ assertEquals(AbstractBuilder.SvcAction.ASSIGN.getName(), abstractBuilder.getSvcAction(delegateExecution));
}
@Test
public void getSvcActionBadOperationType() {
- delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, "bad");
- assertEquals(AbstractBuilder.SvcAction.CREATE.getName(), abstractBuilder.getSvcAction(delegateExecution));
+ delegateExecution.setVariable(AbstractBuilder.OPERATION_TYPE, "bad");
+ assertEquals(AbstractBuilder.SvcAction.CREATE.getName(), abstractBuilder.getSvcAction(delegateExecution));
}
@Test
public void getRequestIdBlankNotOnExecutionTest() {
- abstractBuilder.getRequestId(delegateExecution);
+ abstractBuilder.getRequestId(delegateExecution);
}
@Test
public void getRequestIdBlankOnExecutionTest() {
- String expected = "requestId";
- delegateExecution.setVariable("msoRequestId", expected);
- assertEquals(expected, abstractBuilder.getRequestId(delegateExecution));
+ String expected = "requestId";
+ delegateExecution.setVariable("msoRequestId", expected);
+ assertEquals(expected, abstractBuilder.getRequestId(delegateExecution));
}
@Test
public void getRequestIdTest() {
- String expected = "requestId";
- abstractBuilder.requestId = expected;
- assertEquals(expected, abstractBuilder.getRequestId(delegateExecution));
+ String expected = "requestId";
+ abstractBuilder.requestId = expected;
+ assertEquals(expected, abstractBuilder.getRequestId(delegateExecution));
}
@Test
@@ -545,8 +555,8 @@ public class AbstractBuilderTest {
@Test
public void getParamEntitiesTest() throws Exception {
- Map<String, String> inputs = new HashMap<>();
- inputs.put("foo", "bar");
+ Map<String, String> inputs = new HashMap<>();
+ inputs.put("foo", "bar");
List<ParamEntity> list = abstractBuilder.getParamEntities(inputs);
assertEquals(1, list.size());
assertEquals("foo", list.get(0).getName());
@@ -555,14 +565,14 @@ public class AbstractBuilderTest {
@Test
public void getParamEntitiesNullInputsTest() {
- List<ParamEntity> list = abstractBuilder.getParamEntities(null);
- assertEquals(0, list.size());
+ List<ParamEntity> list = abstractBuilder.getParamEntities(null);
+ assertEquals(0, list.size());
}
@Test
public void getParamEntitiesEmptyInputsTest() {
- List<ParamEntity> list = abstractBuilder.getParamEntities(new HashMap<>());
- assertEquals(0, list.size());
+ List<ParamEntity> list = abstractBuilder.getParamEntities(new HashMap<>());
+ assertEquals(0, list.size());
}
@Test
@@ -580,4 +590,4 @@ public class AbstractBuilderTest {
abstractBuilder.getServiceInstanceName(delegateExecution);
}
-} \ No newline at end of file
+}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/NetworkRpcInputEntityBuilderTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/NetworkRpcInputEntityBuilderTest.java
index 4e39c7b4e3..ed16f5d197 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/NetworkRpcInputEntityBuilderTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/NetworkRpcInputEntityBuilderTest.java
@@ -23,7 +23,6 @@ package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
-
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngineServices;
import org.camunda.bpm.engine.delegate.DelegateExecution;
@@ -35,14 +34,14 @@ import org.camunda.bpm.model.bpmn.instance.FlowElement;
import org.junit.Test;
public class NetworkRpcInputEntityBuilderTest {
- NetworkRpcInputEntityBuilder networRpcInputEntityBuilder = new NetworkRpcInputEntityBuilder();
+ NetworkRpcInputEntityBuilder networRpcInputEntityBuilder = new NetworkRpcInputEntityBuilder();
- DelegateExecution delegateExecution = new DelegateExecution() {
+ DelegateExecution delegateExecution = new DelegateExecution() {
private String operType;
- private String resourceType;
- private String requestId;
+ private String resourceType;
+ private String requestId;
- @Override
+ @Override
public String getProcessInstanceId() {
return null;
}
@@ -194,14 +193,14 @@ public class NetworkRpcInputEntityBuilderTest {
@Override
public Object getVariable(String s) {
- if (AbstractBuilder.OPERATION_TYPE.equals(s)) {
- return operType;
- } else if (AbstractBuilder.RESOURCE_TYPE.equals(s)) {
- return resourceType;
- } else if ("msoRequestId".equals(s)) {
- return requestId;
- }
- return null;
+ if (AbstractBuilder.OPERATION_TYPE.equals(s)) {
+ return operType;
+ } else if (AbstractBuilder.RESOURCE_TYPE.equals(s)) {
+ return resourceType;
+ } else if ("msoRequestId".equals(s)) {
+ return requestId;
+ }
+ return null;
}
@Override
@@ -241,13 +240,13 @@ public class NetworkRpcInputEntityBuilderTest {
@Override
public void setVariable(String s, Object o) {
- if (AbstractBuilder.OPERATION_TYPE.equals(s)) {
- operType = (String) o;
- } else if (AbstractBuilder.RESOURCE_TYPE.equals(s)) {
- resourceType = (String) o;
- } else if ("msoRequestId".equals(s)) {
- requestId = (String) o;
- }
+ if (AbstractBuilder.OPERATION_TYPE.equals(s)) {
+ operType = (String) o;
+ } else if (AbstractBuilder.RESOURCE_TYPE.equals(s)) {
+ resourceType = (String) o;
+ } else if ("msoRequestId".equals(s)) {
+ requestId = (String) o;
+ }
}
@Override
@@ -315,22 +314,22 @@ public class NetworkRpcInputEntityBuilderTest {
}
- @Override
- public ProcessEngine getProcessEngine(){
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public ProcessEngine getProcessEngine() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- @Override
- public void setProcessBusinessKey(String arg0){
- // TODO Auto-generated method stub
+ @Override
+ public void setProcessBusinessKey(String arg0) {
+ // TODO Auto-generated method stub
- }
+ }
};
- @Test
- public void buildTest() {
- networRpcInputEntityBuilder.build(delegateExecution, null);
- }
+ @Test
+ public void buildTest() {
+ networRpcInputEntityBuilder.build(delegateExecution, null);
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/ServiceRpcInputEntityBuilderTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/ServiceRpcInputEntityBuilderTest.java
index 556ff67fad..3d1b1de8c0 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/ServiceRpcInputEntityBuilderTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/ServiceRpcInputEntityBuilderTest.java
@@ -23,7 +23,6 @@ package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
-
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngineServices;
import org.camunda.bpm.engine.delegate.DelegateExecution;
@@ -35,14 +34,14 @@ import org.camunda.bpm.model.bpmn.instance.FlowElement;
import org.junit.Test;
public class ServiceRpcInputEntityBuilderTest {
- ServiceRpcInputEntityBuilder serviceRpcInputEntityBuilder = new ServiceRpcInputEntityBuilder();
+ ServiceRpcInputEntityBuilder serviceRpcInputEntityBuilder = new ServiceRpcInputEntityBuilder();
- DelegateExecution delegateExecution = new DelegateExecution() {
+ DelegateExecution delegateExecution = new DelegateExecution() {
private String operType;
- private String resourceType;
- private String requestId;
+ private String resourceType;
+ private String requestId;
- @Override
+ @Override
public String getProcessInstanceId() {
return null;
}
@@ -194,14 +193,14 @@ public class ServiceRpcInputEntityBuilderTest {
@Override
public Object getVariable(String s) {
- if (AbstractBuilder.OPERATION_TYPE.equals(s)) {
- return operType;
- } else if (AbstractBuilder.RESOURCE_TYPE.equals(s)) {
- return resourceType;
- } else if ("msoRequestId".equals(s)) {
- return requestId;
- }
- return null;
+ if (AbstractBuilder.OPERATION_TYPE.equals(s)) {
+ return operType;
+ } else if (AbstractBuilder.RESOURCE_TYPE.equals(s)) {
+ return resourceType;
+ } else if ("msoRequestId".equals(s)) {
+ return requestId;
+ }
+ return null;
}
@Override
@@ -241,13 +240,13 @@ public class ServiceRpcInputEntityBuilderTest {
@Override
public void setVariable(String s, Object o) {
- if (AbstractBuilder.OPERATION_TYPE.equals(s)) {
- operType = (String) o;
- } else if (AbstractBuilder.RESOURCE_TYPE.equals(s)) {
- resourceType = (String) o;
- } else if ("msoRequestId".equals(s)) {
- requestId = (String) o;
- }
+ if (AbstractBuilder.OPERATION_TYPE.equals(s)) {
+ operType = (String) o;
+ } else if (AbstractBuilder.RESOURCE_TYPE.equals(s)) {
+ resourceType = (String) o;
+ } else if ("msoRequestId".equals(s)) {
+ requestId = (String) o;
+ }
}
@Override
@@ -315,22 +314,22 @@ public class ServiceRpcInputEntityBuilderTest {
}
- @Override
- public ProcessEngine getProcessEngine(){
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public ProcessEngine getProcessEngine() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- @Override
- public void setProcessBusinessKey(String arg0){
- // TODO Auto-generated method stub
+ @Override
+ public void setProcessBusinessKey(String arg0) {
+ // TODO Auto-generated method stub
- }
+ }
};
- @Test
- public void buildTest() throws Exception {
- serviceRpcInputEntityBuilder.build(delegateExecution, null);
- }
+ @Test
+ public void buildTest() throws Exception {
+ serviceRpcInputEntityBuilder.build(delegateExecution, null);
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/ClientEntityPojoTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/ClientEntityPojoTest.java
index c8949cee0f..70dfd6bd57 100644
--- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/ClientEntityPojoTest.java
+++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/entity/ClientEntityPojoTest.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.entity;
import org.junit.Test;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.impl.PojoClassFactory;
import com.openpojo.validation.Validator;
@@ -36,41 +35,34 @@ import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
public class ClientEntityPojoTest {
- @Test
- public void pojoStructure() {
- test(PojoClassFactory.getPojoClass(NetworkInformationEntity.class));
- test(PojoClassFactory.getPojoClass(NetworkInputParametersEntity.class));
- test(PojoClassFactory.getPojoClass(NetworkRequestInputEntity.class));
- test(PojoClassFactory.getPojoClass(NetworkResponseInformationEntity.class));
- test(PojoClassFactory.getPojoClass(NetworkTopologyOperationInputEntity.class));
- test(PojoClassFactory.getPojoClass(NetworkTopologyOperationOutputEntity.class));
- test(PojoClassFactory.getPojoClass(OnapModelInformationEntity.class));
- test(PojoClassFactory.getPojoClass(ParamEntity.class));
- test(PojoClassFactory.getPojoClass(RequestInformationEntity.class));
- test(PojoClassFactory.getPojoClass(RpcNetworkTopologyOperationInputEntity.class));
- test(PojoClassFactory.getPojoClass(SdncRequestHeaderEntity.class));
- test(PojoClassFactory.getPojoClass(RpcServiceTopologyOperationInputEntity.class));
- test(PojoClassFactory.getPojoClass(RpcServiceTopologyOperationOutputEntity.class));
- test(PojoClassFactory.getPojoClass(ServiceInformationEntity.class));
- test(PojoClassFactory.getPojoClass(ServiceInputParametersEntity.class));
- test(PojoClassFactory.getPojoClass(ServiceRequestInputEntity.class));
- test(PojoClassFactory.getPojoClass(ServiceResponseInformationEntity.class));
- test(PojoClassFactory.getPojoClass(ServiceTopologyOperationInputEntity.class));
- test(PojoClassFactory.getPojoClass(ServiceTopologyOperationOutputEntity.class));
- test(PojoClassFactory.getPojoClass(RpcNetworkTopologyOperationOutputEntity.class));
- }
-
- private void test(PojoClass pojoClass) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterMustExistRule())
- .with(new NoNestedClassRule())
- .with(new NoPrimitivesRule())
- .with(new NoPublicFieldsRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .with(new DefaultValuesNullTester())
- .build();
- validator.validate(pojoClass);
- }
+ @Test
+ public void pojoStructure() {
+ test(PojoClassFactory.getPojoClass(NetworkInformationEntity.class));
+ test(PojoClassFactory.getPojoClass(NetworkInputParametersEntity.class));
+ test(PojoClassFactory.getPojoClass(NetworkRequestInputEntity.class));
+ test(PojoClassFactory.getPojoClass(NetworkResponseInformationEntity.class));
+ test(PojoClassFactory.getPojoClass(NetworkTopologyOperationInputEntity.class));
+ test(PojoClassFactory.getPojoClass(NetworkTopologyOperationOutputEntity.class));
+ test(PojoClassFactory.getPojoClass(OnapModelInformationEntity.class));
+ test(PojoClassFactory.getPojoClass(ParamEntity.class));
+ test(PojoClassFactory.getPojoClass(RequestInformationEntity.class));
+ test(PojoClassFactory.getPojoClass(RpcNetworkTopologyOperationInputEntity.class));
+ test(PojoClassFactory.getPojoClass(SdncRequestHeaderEntity.class));
+ test(PojoClassFactory.getPojoClass(RpcServiceTopologyOperationInputEntity.class));
+ test(PojoClassFactory.getPojoClass(RpcServiceTopologyOperationOutputEntity.class));
+ test(PojoClassFactory.getPojoClass(ServiceInformationEntity.class));
+ test(PojoClassFactory.getPojoClass(ServiceInputParametersEntity.class));
+ test(PojoClassFactory.getPojoClass(ServiceRequestInputEntity.class));
+ test(PojoClassFactory.getPojoClass(ServiceResponseInformationEntity.class));
+ test(PojoClassFactory.getPojoClass(ServiceTopologyOperationInputEntity.class));
+ test(PojoClassFactory.getPojoClass(ServiceTopologyOperationOutputEntity.class));
+ test(PojoClassFactory.getPojoClass(RpcNetworkTopologyOperationOutputEntity.class));
+ }
+
+ private void test(PojoClass pojoClass) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule())
+ .with(new NoNestedClassRule()).with(new NoPrimitivesRule()).with(new NoPublicFieldsRule())
+ .with(new SetterTester()).with(new GetterTester()).with(new DefaultValuesNullTester()).build();
+ validator.validate(pojoClass);
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/AllBPMNTestSuites.java b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/AllBPMNTestSuites.java
index 4f98ee4f1b..b1bf830a7a 100644
--- a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/AllBPMNTestSuites.java
+++ b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/AllBPMNTestSuites.java
@@ -1,21 +1,16 @@
/*
*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so;
@@ -27,6 +22,6 @@ import org.junit.runner.RunWith;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses({"**/service/*Test.class", "**/process/*Test.class", "**/subprocess/*Test.class"})
public class AllBPMNTestSuites {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/BaseBPMNTest.java b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/BaseBPMNTest.java
index 648c9887c2..983fcc2a5c 100644
--- a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/BaseBPMNTest.java
+++ b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/BaseBPMNTest.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so;
@@ -63,7 +58,7 @@ public abstract class BaseBPMNTest {
protected int wireMockPort;
@After
- public void shutDown(){
+ public void shutDown() {
wireMockServer.resetAll();
}
}
diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
index 963d989eb7..3fd39c4953 100644
--- a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
+++ b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
@@ -36,30 +36,25 @@ public class EmbeddedMariaDbConfig {
@Bean
MariaDB4jSpringService mariaDB4jSpringService() {
- MariaDB4jSpringService service = new MariaDB4jSpringService();
-
-
- service.getConfiguration().addArg("--lower_case_table_names=1");
+ MariaDB4jSpringService service = new MariaDB4jSpringService();
+
+
+ service.getConfiguration().addArg("--lower_case_table_names=1");
return service;
}
@Bean
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
}
diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/GrpcNettyServer.java b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/GrpcNettyServer.java
index bf4a015e36..9521e68e16 100644
--- a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/GrpcNettyServer.java
+++ b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/GrpcNettyServer.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so;
@@ -60,50 +55,48 @@ public class GrpcNettyServer extends BluePrintProcessingServiceImplBase {
@PostConstruct
public void start() throws IOException {
- final BluePrintProcessingServiceImplBase blueprintPrcessorImpl =
- new BluePrintProcessingServiceImplBase() {
- @Override
- public StreamObserver<ExecutionServiceInput> process(
+ final BluePrintProcessingServiceImplBase blueprintPrcessorImpl = new BluePrintProcessingServiceImplBase() {
+ @Override
+ public StreamObserver<ExecutionServiceInput> process(
StreamObserver<ExecutionServiceOutput> responseObserver) {
- responseObserverRef.set(responseObserver);
+ responseObserverRef.set(responseObserver);
- StreamObserver<ExecutionServiceInput> requestObserver = new StreamObserver<ExecutionServiceInput>() {
- @Override
- public void onNext(ExecutionServiceInput message) {
- detailedMessages.add(message);
- logger.info("Message received: {}", message);
- ExecutionServiceOutput executionServiceOutput = ExecutionServiceOutput.newBuilder()
+ StreamObserver<ExecutionServiceInput> requestObserver = new StreamObserver<ExecutionServiceInput>() {
+ @Override
+ public void onNext(ExecutionServiceInput message) {
+ detailedMessages.add(message);
+ logger.info("Message received: {}", message);
+ ExecutionServiceOutput executionServiceOutput = ExecutionServiceOutput.newBuilder()
.setActionIdentifiers(message.getActionIdentifiers())
- .setStatus(Status.newBuilder().setEventType(
- EventType.EVENT_COMPONENT_EXECUTED).build()).build();
-
- responseObserverRef.get().onNext(executionServiceOutput);
- logger.info("Message sent: {}", executionServiceOutput);
- }
-
- @Override
- public void onError(Throwable t) {
- responseObserverRef.get().onError(t);
- }
-
- @Override
- public void onCompleted() {
- allRequestsDelivered.countDown();
- responseObserverRef.get().onCompleted();
- }
- };
-
- return requestObserver;
- }
- };
- grpcCleanup.register(
- ServerBuilder.forPort(Integer.valueOf(port)).directExecutor().addService(blueprintPrcessorImpl).build()
- .start());
+ .setStatus(Status.newBuilder().setEventType(EventType.EVENT_COMPONENT_EXECUTED).build())
+ .build();
+
+ responseObserverRef.get().onNext(executionServiceOutput);
+ logger.info("Message sent: {}", executionServiceOutput);
+ }
+
+ @Override
+ public void onError(Throwable t) {
+ responseObserverRef.get().onError(t);
+ }
+
+ @Override
+ public void onCompleted() {
+ allRequestsDelivered.countDown();
+ responseObserverRef.get().onCompleted();
+ }
+ };
+
+ return requestObserver;
+ }
+ };
+ grpcCleanup.register(ServerBuilder.forPort(Integer.valueOf(port)).directExecutor()
+ .addService(blueprintPrcessorImpl).build().start());
}
- public List<ExecutionServiceInput> getDetailedMessages(){
+ public List<ExecutionServiceInput> getDetailedMessages() {
return this.detailedMessages;
}
diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/TestApplication.java b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/TestApplication.java
index 64311d85da..e9855619c9 100644
--- a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/TestApplication.java
+++ b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/TestApplication.java
@@ -30,12 +30,12 @@ import org.springframework.context.annotation.Profile;
@SpringBootApplication
@Profile("test")
-@ComponentScan(basePackages = {"org.onap.so"}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class, excludeFilters = {
- @Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
+@ComponentScan(basePackages = {"org.onap.so"}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class,
+ excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
public class TestApplication {
- public static void main(String... args) {
- SpringApplication.run(TestApplication.class, args);
- System.getProperties().setProperty("mso.db", "MARIADB");
- System.getProperties().setProperty("server.name", "Springboot");
- }
+ public static void main(String... args) {
+ SpringApplication.run(TestApplication.class, args);
+ System.getProperties().setProperty("mso.db", "MARIADB");
+ System.getProperties().setProperty("server.name", "Springboot");
+ }
}
diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/CreateVcpeResCustServiceSimplifiedTest.java b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/CreateVcpeResCustServiceSimplifiedTest.java
index 2b1dc384a1..abab08bdf3 100644
--- a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/CreateVcpeResCustServiceSimplifiedTest.java
+++ b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/CreateVcpeResCustServiceSimplifiedTest.java
@@ -1,21 +1,16 @@
/*
*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.process;
@@ -29,7 +24,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.assertj.core.api.Assertions.fail;
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
-
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import java.io.IOException;
@@ -77,14 +71,13 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest {
variables.put("bpmnRequest", requestObject);
/**
- * This variable indicates that the flow was invoked asynchronously.
- * It's injected by {@link WorkflowProcessor}.
+ * This variable indicates that the flow was invoked asynchronously. It's injected by {@link WorkflowProcessor}.
*/
variables.put("isAsyncProcess", "true");
/**
- * Temporary solution to add pnfCorrelationId to context.
- * this value is getting from the request to SO api handler and then convert to CamudaInput
+ * Temporary solution to add pnfCorrelationId to context. this value is getting from the request to SO api
+ * handler and then convert to CamudaInput
*/
variables.put("pnfCorrelationId", "PNFDemo");
@@ -112,12 +105,12 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest {
mockAai();
mockDmaapForPnf();
- ProcessInstance pi = runtimeService
- .startProcessInstanceByKey(TEST_PROCESSINSTANCE_KEY, testBusinessKey, variables);
+ ProcessInstance pi =
+ runtimeService.startProcessInstanceByKey(TEST_PROCESSINSTANCE_KEY, testBusinessKey, variables);
assertThat(pi).isNotNull();
Execution execution = runtimeService.createExecutionQuery().processDefinitionKey("CreateAndActivatePnfResource")
- .activityId("WaitForDmaapPnfReadyNotification").singleResult();
+ .activityId("WaitForDmaapPnfReadyNotification").singleResult();
if (!execution.isSuspended() && !execution.isEnded()) {
try {
@@ -127,25 +120,11 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest {
}
}
- assertThat(pi).isStarted().hasPassedInOrder(
- "createVCPE_startEvent",
- "preProcessRequest_ScriptTask",
- "sendSyncAckResponse_ScriptTask",
- "ScriptTask_0cdtchu",
- "DecomposeService",
- "ScriptTask_0lpv2da",
- "ScriptTask_1y241p8",
- "CallActivity_1vc4jeh",
- "ScriptTask_1y5lvl7",
- "GeneratePnfUuid",
- "Task_14l19kv",
- "Pnf_Con",
- "setPONR_ScriptTask",
- "postProcessAndCompletionRequest_ScriptTask",
- "callCompleteMsoProcess_CallActivity",
- "ScriptTask_2",
- "CreateVCPE_EndEvent"
- );
+ assertThat(pi).isStarted().hasPassedInOrder("createVCPE_startEvent", "preProcessRequest_ScriptTask",
+ "sendSyncAckResponse_ScriptTask", "ScriptTask_0cdtchu", "DecomposeService", "ScriptTask_0lpv2da",
+ "ScriptTask_1y241p8", "CallActivity_1vc4jeh", "ScriptTask_1y5lvl7", "GeneratePnfUuid", "Task_14l19kv",
+ "Pnf_Con", "setPONR_ScriptTask", "postProcessAndCompletionRequest_ScriptTask",
+ "callCompleteMsoProcess_CallActivity", "ScriptTask_2", "CreateVCPE_EndEvent");
assertThat(pi).isEnded();
@@ -154,7 +133,7 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest {
try {
checkConfigAssign(detailedMessages.get(0));
checkConfigDeploy(detailedMessages.get(1));
- } catch(Exception e){
+ } catch (Exception e) {
e.printStackTrace();
fail("ConfigAssign/deploy request exception", e);
}
@@ -164,7 +143,8 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest {
ActionIdentifiers actionIdentifiers = executionServiceInput.getActionIdentifiers();
/**
- * the fields of actionIdentifiers should match the one in the response/createVcpeResCustServiceSimplifiedTest_catalogdb.json.
+ * the fields of actionIdentifiers should match the one in the
+ * response/createVcpeResCustServiceSimplifiedTest_catalogdb.json.
*/
assertThat(actionIdentifiers.getBlueprintName()).matches("test_configuration_restconf");
assertThat(actionIdentifiers.getBlueprintVersion()).matches("1.0.0");
@@ -182,15 +162,18 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest {
Struct propertiesStruct = requeststruct.getFieldsOrThrow("config-assign-properties").getStructValue();
assertThat(propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue()).matches("PNFDemo");
- assertThat(propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue()).matches("f2daaac6-5017-4e1e-96c8-6a27dfbe1421");
- assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue()).matches("68dc9a92-214c-11e7-93ae-92361f002680");
+ assertThat(propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue())
+ .matches("f2daaac6-5017-4e1e-96c8-6a27dfbe1421");
+ assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue())
+ .matches("68dc9a92-214c-11e7-93ae-92361f002680");
}
private void checkConfigDeploy(ExecutionServiceInput executionServiceInput) {
ActionIdentifiers actionIdentifiers = executionServiceInput.getActionIdentifiers();
/**
- * the fields of actionIdentifiers should match the one in the response/createVcpeResCustServiceSimplifiedTest_catalogdb.json.
+ * the fields of actionIdentifiers should match the one in the
+ * response/createVcpeResCustServiceSimplifiedTest_catalogdb.json.
*/
assertThat(actionIdentifiers.getBlueprintName()).matches("test_configuration_restconf");
assertThat(actionIdentifiers.getBlueprintVersion()).matches("1.0.0");
@@ -208,8 +191,10 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest {
Struct propertiesStruct = requeststruct.getFieldsOrThrow("config-deploy-properties").getStructValue();
assertThat(propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue()).matches("PNFDemo");
- assertThat(propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue()).matches("f2daaac6-5017-4e1e-96c8-6a27dfbe1421");
- assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue()).matches("68dc9a92-214c-11e7-93ae-92361f002680");
+ assertThat(propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue())
+ .matches("f2daaac6-5017-4e1e-96c8-6a27dfbe1421");
+ assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue())
+ .matches("68dc9a92-214c-11e7-93ae-92361f002680");
/**
* IP addresses match the OAM ip addresses from AAI.
@@ -229,51 +214,42 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest {
* Get the events from PNF topic
*/
wireMockServer
- .stubFor(get(urlPathMatching("/events/pnfReady/consumerGroup.*")).willReturn(okJson(pnfResponse)));
+ .stubFor(get(urlPathMatching("/events/pnfReady/consumerGroup.*")).willReturn(okJson(pnfResponse)));
}
private void mockAai() {
- String aaiResponse = "{\n"
- + " \"results\": [\n"
- + " {\n"
- + " \"resource-type\": \"service-instance\",\n"
- + " \"resource-link\": \"https://localhost:8443/aai/v15/business/customers/customer/ADemoCustomerInCiti/service-subscriptions/service-subscription/vCPE/service-instances/service-instance/key3\"\n"
- + " }\n"
- + " ]\n"
- + "}";
-
- String aaiPnfEntry = "{ \n"
- + " \"pnf-name\":\"PNFDemo\",\n"
- + " \"pnf-id\":\"testtest\",\n"
- + " \"in-maint\":true,\n"
- + " \"resource-version\":\"1541720264047\",\n"
- + " \"ipaddress-v4-oam\":\"1.1.1.1\",\n"
- + " \"ipaddress-v6-oam\":\"::/128\"\n"
- + "}";
+ String aaiResponse = "{\n" + " \"results\": [\n" + " {\n"
+ + " \"resource-type\": \"service-instance\",\n"
+ + " \"resource-link\": \"https://localhost:8443/aai/v15/business/customers/customer/ADemoCustomerInCiti/service-subscriptions/service-subscription/vCPE/service-instances/service-instance/key3\"\n"
+ + " }\n" + " ]\n" + "}";
+
+ String aaiPnfEntry = "{ \n" + " \"pnf-name\":\"PNFDemo\",\n" + " \"pnf-id\":\"testtest\",\n"
+ + " \"in-maint\":true,\n" + " \"resource-version\":\"1541720264047\",\n"
+ + " \"ipaddress-v4-oam\":\"1.1.1.1\",\n" + " \"ipaddress-v6-oam\":\"::/128\"\n" + "}";
/**
* Get the AAI entry for globalCustomerId as specified in the request file.
*/
wireMockServer.stubFor(
- get(urlPathMatching("/aai/v15/business/customers/customer/ADemoCustomerInCiti.*")).willReturn(ok()));
+ get(urlPathMatching("/aai/v15/business/customers/customer/ADemoCustomerInCiti.*")).willReturn(ok()));
/**
- * PUT the service to AAI with globalCustomerId, service type as specified in the request file.
- * Service instance id is generated during runtime, REGEX is used to represent the information.
+ * PUT the service to AAI with globalCustomerId, service type as specified in the request file. Service instance
+ * id is generated during runtime, REGEX is used to represent the information.
*/
wireMockServer.stubFor(put(urlPathMatching(
- "/aai/v15/business/customers/customer/ADemoCustomerInCiti/service-subscriptions/service-subscription/vCPE/service-instances/service-instance/.*")));
+ "/aai/v15/business/customers/customer/ADemoCustomerInCiti/service-subscriptions/service-subscription/vCPE/service-instances/service-instance/.*")));
wireMockServer.stubFor(get(urlPathMatching(
- "/aai/v15/business/customers/customer/ADemoCustomerInCiti/service-subscriptions/service-subscription/vCPE/service-instances/service-instance/.*"))
- .willReturn(okJson(aaiResponse)));
+ "/aai/v15/business/customers/customer/ADemoCustomerInCiti/service-subscriptions/service-subscription/vCPE/service-instances/service-instance/.*"))
+ .willReturn(okJson(aaiResponse)));
/**
* Get the service from AAI
*/
wireMockServer.stubFor(get(urlPathMatching("/aai/v15/nodes/service-instances/service-instance/.*"))
- .willReturn(okJson(aaiResponse)));
+ .willReturn(okJson(aaiResponse)));
/**
* Put the project as specified in the request file to AAI.
@@ -283,8 +259,8 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest {
/**
* GET the project as specified in the request file to AAI.
*/
- wireMockServer
- .stubFor(get(urlPathMatching("/aai/v15/business/projects/project/Project-Demonstration")).willReturn(ok()));
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/v15/business/projects/project/Project-Demonstration")).willReturn(ok()));
/**
* PUT the PNF correlation ID to AAI.
@@ -299,8 +275,8 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest {
/**
* Put the PNF relationship
*/
- wireMockServer.stubFor(
- put(urlEqualTo("/aai/v15/business/projects/project/Project-Demonstration/relationship-list/relationship")));
+ wireMockServer.stubFor(put(
+ urlEqualTo("/aai/v15/business/projects/project/Project-Demonstration/relationship-list/relationship")));
}
/**
@@ -308,29 +284,29 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest {
*/
private void mockCatalogDb() {
- String catalogdbClientResponse = FileUtil
- .readResourceFile("response/" + getClass().getSimpleName() + "_catalogdb.json");
+ String catalogdbClientResponse =
+ FileUtil.readResourceFile("response/" + getClass().getSimpleName() + "_catalogdb.json");
/**
* Return valid json for the model UUID in the request file.
*/
wireMockServer
- .stubFor(get(urlEqualTo("/v2/serviceResources?serviceModelUuid=f2daaac6-5017-4e1e-96c8-6a27dfbe1421"))
- .willReturn(okJson(responseObject)));
+ .stubFor(get(urlEqualTo("/v2/serviceResources?serviceModelUuid=f2daaac6-5017-4e1e-96c8-6a27dfbe1421"))
+ .willReturn(okJson(responseObject)));
/**
* Return valid json for the service model InvariantUUID as specified in the request file.
*/
wireMockServer.stubFor(
- get(urlEqualTo("/v2/serviceResources?serviceModelInvariantUuid=539b7a2f-9524-4dbf-9eee-f2e05521df3f"))
- .willReturn(okJson(responseObject)));
+ get(urlEqualTo("/v2/serviceResources?serviceModelInvariantUuid=539b7a2f-9524-4dbf-9eee-f2e05521df3f"))
+ .willReturn(okJson(responseObject)));
/**
* Return valid spring data rest json for the service model UUID as specified in the request file.
*/
wireMockServer.stubFor(get(urlEqualTo(
- "/pnfResourceCustomization/search/findPnfResourceCustomizationByModelUuid?SERVICE_MODEL_UUID=f2daaac6-5017-4e1e-96c8-6a27dfbe1421"))
- .willReturn(okJson(catalogdbClientResponse)));
+ "/pnfResourceCustomization/search/findPnfResourceCustomizationByModelUuid?SERVICE_MODEL_UUID=f2daaac6-5017-4e1e-96c8-6a27dfbe1421"))
+ .willReturn(okJson(catalogdbClientResponse)));
}
private void mockRequestDb() {
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/HomingV2.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/HomingV2.java
index 55f898742c..513ff74180 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/HomingV2.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/HomingV2.java
@@ -54,7 +54,7 @@ public class HomingV2 {
// Default solution is SNIRO. OOF gets called only if specified.
private boolean isOof(BuildingBlockExecution execution) {
for (Map<String, Object> params : execution.getGeneralBuildingBlock().getRequestContext().getRequestParameters()
- .getUserParams()) {
+ .getUserParams()) {
if (params.containsKey(HOMINGSOLUTION) && params.get(HOMINGSOLUTION).equals("oof")) {
return true;
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/OofHomingV2.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/OofHomingV2.java
index f65dde1af5..2524fc7892 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/OofHomingV2.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/OofHomingV2.java
@@ -65,19 +65,16 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;
-
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/**
- * The oof homing building block obtains licensing and homing solutions for a given
- * resource or set of resources.
+ * The oof homing building block obtains licensing and homing solutions for a given resource or set of resources.
*
*/
@Component("OofHoming")
@@ -109,14 +106,13 @@ public class OofHomingV2 {
private static final int INTERNAL = 500;
/**
- * Generates the request payload then sends to Oof to perform homing and
- * licensing for the provided demands
+ * Generates the request payload then sends to Oof to perform homing and licensing for the provided demands
*
* @param execution
*/
- public void callOof(BuildingBlockExecution execution){
+ public void callOof(BuildingBlockExecution execution) {
logger.trace("Started Sniro Homing Call Sniro");
- try{
+ try {
GeneralBuildingBlock bb = execution.getGeneralBuildingBlock();
RequestContext requestContext = bb.getRequestContext();
@@ -127,13 +123,13 @@ public class OofHomingV2 {
Customer customer = bb.getCustomer();
String timeout = execution.getVariable("timeout");
- if(isBlank(timeout)){
+ if (isBlank(timeout)) {
timeout = env.getProperty("oof.timeout", "PT30M");
}
OofRequest request = new OofRequest();
- RequestInfo requestInfo = (RequestInfo)buildRequestInfo(requestId, timeout);
+ RequestInfo requestInfo = (RequestInfo) buildRequestInfo(requestId, timeout);
request.setRequestInformation(requestInfo);
ServiceInfo serviceInfo = buildServiceInfo(serviceInstance);
@@ -151,71 +147,74 @@ public class OofHomingV2 {
licenseInfo.put("licenseDemands", licenseDemands);
request.setLicenseInformation(licenseInfo.toString());
- if(placementDemands.size() > 0 || licenseDemands.length() > 0){
+ if (placementDemands.size() > 0 || licenseDemands.length() > 0) {
client.postDemands(request);
- }else{
+ } else {
logger.debug(SERVICE_MISSING_DATA + " resources eligible for homing or licensing");
- throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + " resources eligible for homing or licensing");
+ throw new BpmnError(UNPROCESSABLE,
+ SERVICE_MISSING_DATA + " resources eligible for homing or licensing");
}
- //Variables for ReceiveWorkflowMessage subflow
+ // Variables for ReceiveWorkflowMessage subflow
execution.setVariable("asyncCorrelator", requestId);
execution.setVariable("asyncMessageType", "OofResponse");
execution.setVariable("asyncTimeout", timeout);
logger.trace("Completed Oof Homing Call Oof");
- }catch(BpmnError e){
+ } catch (BpmnError e) {
exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage());
- }catch(BadResponseException e){
+ } catch (BadResponseException e) {
exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage());
- }catch(Exception e){
- exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL, "Internal Error - occurred while preparing oof request: " + e.getMessage());
+ } catch (Exception e) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL,
+ "Internal Error - occurred while preparing oof request: " + e.getMessage());
}
}
/**
- * Validates, processes, and sets the homing and licensing solutions that are returned by
- * Oof
+ * Validates, processes, and sets the homing and licensing solutions that are returned by Oof
*
* @param execution
* @param asyncResponse
*/
- public void processSolution(BuildingBlockExecution execution, String asyncResponse){
+ public void processSolution(BuildingBlockExecution execution, String asyncResponse) {
logger.trace("Started Oof Homing Process Solution");
- try{
+ try {
oofValidator.validateSolution(asyncResponse);
- ServiceInstance serviceInstance = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
+ ServiceInstance serviceInstance = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription()
+ .getServiceInstances().get(0);
logger.debug("Processing Oof asyncronous response");
JSONObject response = new JSONObject(asyncResponse);
- if(response.has(SOLUTIONS)){
+ if (response.has(SOLUTIONS)) {
JSONObject allSolutions = response.getJSONObject(SOLUTIONS);
- if(allSolutions.has("placementSolutions")){
+ if (allSolutions.has("placementSolutions")) {
JSONArray placementSolutions = allSolutions.getJSONArray("placementSolutions");
- for(int i = 0; i < placementSolutions.length(); i++){
+ for (int i = 0; i < placementSolutions.length(); i++) {
JSONArray placements = placementSolutions.getJSONArray(i);
processPlacementSolution(serviceInstance, placements, i);
}
}
- if(allSolutions.has("licenseSolutions")){
+ if (allSolutions.has("licenseSolutions")) {
JSONArray licenseSolutions = allSolutions.getJSONArray("licenseSolutions");
- if(licenseSolutions.length() > 0){
+ if (licenseSolutions.length() > 0) {
processLicenseSolution(serviceInstance, licenseSolutions);
}
}
- }else{
+ } else {
throw new BpmnError(UNPROCESSABLE, "Oof response does not contain: " + SOLUTIONS);
}
execution.setVariable("generalBuildingBlock", execution.getGeneralBuildingBlock());
logger.trace("Completed Oof Homing Process Solution");
- }catch(BpmnError e){
+ } catch (BpmnError e) {
exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage());
- }catch(BadResponseException e){
+ } catch (BadResponseException e) {
exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage());
- }catch(Exception e){
- exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL, "Internal Error - occurred while processing Oof asynchronous response: " + e.getMessage());
+ } catch (Exception e) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL,
+ "Internal Error - occurred while processing Oof asynchronous response: " + e.getMessage());
}
}
@@ -224,12 +223,13 @@ public class OofHomingV2 {
*
* @throws Exception
*/
- private RequestInfo buildRequestInfo(String requestId, String timeout) throws Exception{
+ private RequestInfo buildRequestInfo(String requestId, String timeout) throws Exception {
logger.trace("Building request information");
RequestInfo requestInfo = new RequestInfo();
- if(requestId != null){
+ if (requestId != null) {
String host = env.getProperty("mso.workflow.message.endpoint");
- String callbackUrl = host + "/" + UriUtils.encodePathSegment("OofResponse", "UTF-8") + "/" + UriUtils.encodePathSegment(requestId, "UTF-8");
+ String callbackUrl = host + "/" + UriUtils.encodePathSegment("OofResponse", "UTF-8") + "/"
+ + UriUtils.encodePathSegment(requestId, "UTF-8");
Duration d = Duration.parse(timeout);
long timeoutSeconds = d.getSeconds();
@@ -240,7 +240,7 @@ public class OofHomingV2 {
requestInfo.setSourceId("mso");
requestInfo.setRequestType("create");
requestInfo.setTimeout(timeoutSeconds);
- } else{
+ } else {
throw new BpmnError(UNPROCESSABLE, "Request Context does not contain: requestId");
}
return requestInfo;
@@ -250,17 +250,17 @@ public class OofHomingV2 {
* Builds the request information section for the homing/licensing request
*
*/
- private ServiceInfo buildServiceInfo(ServiceInstance serviceInstance){
+ private ServiceInfo buildServiceInfo(ServiceInstance serviceInstance) {
logger.trace("Building service information");
ServiceInfo info = new ServiceInfo();
ModelInfoServiceInstance modelInfo = serviceInstance.getModelInfoServiceInstance();
- if(isNotBlank(modelInfo.getModelInvariantUuid()) && isNotBlank(modelInfo.getModelUuid())){
+ if (isNotBlank(modelInfo.getModelInvariantUuid()) && isNotBlank(modelInfo.getModelUuid())) {
info.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- if(modelInfo.getServiceType() != null && modelInfo.getServiceType().length() > 0){ //temp solution
+ if (modelInfo.getServiceType() != null && modelInfo.getServiceType().length() > 0) { // temp solution
info.setServiceName(modelInfo.getServiceType());
}
info.setModelInfo(buildModelInfo(serviceInstance.getModelInfoServiceInstance()));
- }else{
+ } else {
throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + MODEL_VERSION_ID + ", " + MODEL_INVARIANT_ID);
}
return info;
@@ -270,32 +270,32 @@ public class OofHomingV2 {
* Builds initial section of placement info for the homing/licensing request
*
*/
- private PlacementInfo buildPlacementInfo(Customer customer, RequestParameters requestParams){
+ private PlacementInfo buildPlacementInfo(Customer customer, RequestParameters requestParams) {
PlacementInfo placementInfo = new PlacementInfo();
- if(customer != null){
+ if (customer != null) {
logger.debug("Adding subscriber to placement information");
SubscriberInfo subscriberInfo = new SubscriberInfo();
subscriberInfo.setGlobalSubscriberId(customer.getGlobalCustomerId());
subscriberInfo.setSubscriberName(customer.getSubscriberName());
subscriberInfo.setSubscriberCommonSiteId(customer.getSubscriberCommonSiteId());
placementInfo.setSubscriberInfo(subscriberInfo);
- if(requestParams != null){
+ if (requestParams != null) {
logger.debug("Adding request parameters to placement information");
OofRequestParameters oofRequestParams = new OofRequestParameters();
- for (Map requestParam : requestParams.getUserParams()){
- if (requestParam.containsKey("customerLatitude")){
+ for (Map requestParam : requestParams.getUserParams()) {
+ if (requestParam.containsKey("customerLatitude")) {
oofRequestParams.setCustomerLatitude(requestParam.get("customerLatitude").toString());
}
- if (requestParam.containsKey("customerLongitude")){
+ if (requestParam.containsKey("customerLongitude")) {
oofRequestParams.setCustomerLongitude(requestParam.get("customerLongitude").toString());
}
- if (requestParam.containsKey("customerName")){
+ if (requestParam.containsKey("customerName")) {
oofRequestParams.setCustomerName(requestParam.get("customerName").toString());
}
}
placementInfo.setRequestParameters(oofRequestParams);
}
- }else{
+ } else {
throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + "customer");
}
return placementInfo;
@@ -306,33 +306,33 @@ public class OofHomingV2 {
* Builds the placement demand list for the homing/licensing request
*
*/
- private ArrayList<PlacementDemand> buildPlacementDemands(ServiceInstance serviceInstance){
+ private ArrayList<PlacementDemand> buildPlacementDemands(ServiceInstance serviceInstance) {
logger.trace("Building placement information demands");
ArrayList<PlacementDemand> placementDemands = new ArrayList();
List<AllottedResource> allottedResourceList = serviceInstance.getAllottedResources();
- if(!allottedResourceList.isEmpty()){
+ if (!allottedResourceList.isEmpty()) {
logger.debug("Adding allotted resources to placement demands list");
- for(AllottedResource ar : allottedResourceList){
- if(isBlank(ar.getId())){
+ for (AllottedResource ar : allottedResourceList) {
+ if (isBlank(ar.getId())) {
ar.setId(UUID.randomUUID().toString());
}
PlacementDemand demand = buildDemand(ar.getId(), ar.getModelInfoAllottedResource());
- //addCandidates(ar, demand);
+ // addCandidates(ar, demand);
placementDemands.add(demand);
}
}
List<VpnBondingLink> vpnBondingLinkList = serviceInstance.getVpnBondingLinks();
- if(!vpnBondingLinkList.isEmpty()){
+ if (!vpnBondingLinkList.isEmpty()) {
logger.debug("Adding vpn bonding links to placement demands list");
- for(VpnBondingLink vbl:vpnBondingLinkList){
+ for (VpnBondingLink vbl : vpnBondingLinkList) {
List<ServiceProxy> serviceProxyList = vbl.getServiceProxies();
- for(ServiceProxy sp : serviceProxyList){
- if(isBlank(sp.getId())){
+ for (ServiceProxy sp : serviceProxyList) {
+ if (isBlank(sp.getId())) {
sp.setId(UUID.randomUUID().toString());
}
PlacementDemand demand = buildDemand(sp.getId(), sp.getModelInfoServiceProxy());
- //addCandidates(sp, demand);
+ // addCandidates(sp, demand);
placementDemands.add(demand);
}
}
@@ -344,13 +344,13 @@ public class OofHomingV2 {
* Builds the license demand list for the homing/licensing request
*
*/
- private JSONArray buildLicenseDemands(ServiceInstance serviceInstance){
+ private JSONArray buildLicenseDemands(ServiceInstance serviceInstance) {
logger.trace("Building license information");
JSONArray licenseDemands = new JSONArray();
List<GenericVnf> vnfList = serviceInstance.getVnfs();
- if(!vnfList.isEmpty()){
+ if (!vnfList.isEmpty()) {
logger.debug("Adding vnfs to license demands list");
- for(GenericVnf vnf : vnfList){
+ for (GenericVnf vnf : vnfList) {
JSONObject demand = buildLicenseDemand(vnf.getVnfId(), vnf.getModelInfoGenericVnf());
licenseDemands.put(demand);
}
@@ -362,14 +362,14 @@ public class OofHomingV2 {
* Builds a single license demand object
*
*/
- private JSONObject buildLicenseDemand(String id, ModelInfoMetadata metadata){
+ private JSONObject buildLicenseDemand(String id, ModelInfoMetadata metadata) {
logger.debug("Building demand for service or resource: " + id);
JSONObject demand = new JSONObject();
- if(isNotBlank(id) && isNotBlank(metadata.getModelInstanceName())){
+ if (isNotBlank(id) && isNotBlank(metadata.getModelInstanceName())) {
demand.put(SERVICE_RESOURCE_ID, id);
demand.put(RESOURCE_MODULE_NAME, metadata.getModelInstanceName());
demand.put(RESOURCE_MODEL_INFO, buildModelInfo(metadata));
- }else{
+ } else {
throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + "modelInstanceName");
}
return demand;
@@ -379,14 +379,14 @@ public class OofHomingV2 {
* Builds a single demand object
*
*/
- private PlacementDemand buildDemand(String id, ModelInfoMetadata metadata){
+ private PlacementDemand buildDemand(String id, ModelInfoMetadata metadata) {
logger.debug("Building demand for service or resource: " + id);
PlacementDemand placementDemand = new PlacementDemand();
- if(isNotBlank(id) && isNotBlank(metadata.getModelInstanceName())){
+ if (isNotBlank(id) && isNotBlank(metadata.getModelInstanceName())) {
placementDemand.setServiceResourceId(id);
placementDemand.setResourceModuleName(metadata.getModelInstanceName());
placementDemand.setResourceModelInfo((ResourceModelInfo) buildModelInfo(metadata));
- }else{
+ } else {
throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + "modelInstanceName");
}
return placementDemand;
@@ -396,18 +396,18 @@ public class OofHomingV2 {
* Builds the resource model info section
*
*/
- private ModelInfo buildModelInfo(ModelInfoMetadata metadata){
+ private ModelInfo buildModelInfo(ModelInfoMetadata metadata) {
ModelInfo modelInfo = new ModelInfo();
String invariantUuid = metadata.getModelInvariantUuid();
String modelUuid = metadata.getModelUuid();
- if(isNotBlank(invariantUuid) && isNotBlank(modelUuid)){
+ if (isNotBlank(invariantUuid) && isNotBlank(modelUuid)) {
modelInfo.setModelInvariantId(invariantUuid);
modelInfo.setModelVersionId(modelUuid);
modelInfo.setModelName(metadata.getModelName());
modelInfo.setModelVersion(metadata.getModelVersion());
- }else if(isNotBlank(invariantUuid)){
+ } else if (isNotBlank(invariantUuid)) {
throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + MODEL_VERSION_ID);
- }else{
+ } else {
throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + MODEL_INVARIANT_ID);
}
return modelInfo;
@@ -417,30 +417,30 @@ public class OofHomingV2 {
* Adds required, excluded, and existing candidates to a demand
*
*/
- private void addCandidates(SolutionCandidates candidates, JSONObject demand){
+ private void addCandidates(SolutionCandidates candidates, JSONObject demand) {
List<Candidate> required = candidates.getRequiredCandidates();
List<Candidate> excluded = candidates.getExcludedCandidates();
- if(!required.isEmpty()){
+ if (!required.isEmpty()) {
demand.put("requiredCandidates", required);
}
- if(!excluded.isEmpty()){
+ if (!excluded.isEmpty()) {
demand.put("excludedCandidates", excluded);
}
- //TODO support existing candidates
+ // TODO support existing candidates
}
/**
* Processes the license solutions and sets to the corresponding generic vnf
*
*/
- private void processLicenseSolution(ServiceInstance serviceInstance, JSONArray licenseSolutions){
+ private void processLicenseSolution(ServiceInstance serviceInstance, JSONArray licenseSolutions) {
List<GenericVnf> vnfs = serviceInstance.getVnfs();
logger.debug("Processing the license solution");
- for(int i = 0; i < licenseSolutions.length(); i++){
+ for (int i = 0; i < licenseSolutions.length(); i++) {
JSONObject licenseSolution = licenseSolutions.getJSONObject(i);
- for(GenericVnf vnf:vnfs){
- if(licenseSolution.getString(SERVICE_RESOURCE_ID).equals(vnf.getVnfId())){
+ for (GenericVnf vnf : vnfs) {
+ if (licenseSolution.getString(SERVICE_RESOURCE_ID).equals(vnf.getVnfId())) {
License license = new License();
JSONArray entitlementPools = licenseSolution.getJSONArray("entitlementPoolUUID");
List<String> entitlementPoolsList = jsonUtils.StringArrayToList(entitlementPools);
@@ -456,47 +456,48 @@ public class OofHomingV2 {
}
/**
- * Processes a placement solution list then correlates and sets each placement solution
- * to its corresponding resource
+ * Processes a placement solution list then correlates and sets each placement solution to its corresponding
+ * resource
*
*/
- private void processPlacementSolution(ServiceInstance serviceInstance, JSONArray placements, int i){
+ private void processPlacementSolution(ServiceInstance serviceInstance, JSONArray placements, int i) {
List<VpnBondingLink> links = serviceInstance.getVpnBondingLinks();
List<AllottedResource> allottes = serviceInstance.getAllottedResources();
List<GenericVnf> vnfs = serviceInstance.getVnfs();
- logger.debug("Processing placement solution " + i+1);
- for(int p = 0; p < placements.length(); p++){
+ logger.debug("Processing placement solution " + i + 1);
+ for (int p = 0; p < placements.length(); p++) {
JSONObject placement = placements.getJSONObject(p);
SolutionInfo solutionInfo = new SolutionInfo();
solutionInfo.setSolutionId(i + 1);
search: {
- for(VpnBondingLink vbl:links){
+ for (VpnBondingLink vbl : links) {
List<ServiceProxy> proxies = vbl.getServiceProxies();
- for(ServiceProxy sp:proxies){
- if(placement.getString(SERVICE_RESOURCE_ID).equals(sp.getId())){
- if(i > 0){
- if(p % 2 == 0){
+ for (ServiceProxy sp : proxies) {
+ if (placement.getString(SERVICE_RESOURCE_ID).equals(sp.getId())) {
+ if (i > 0) {
+ if (p % 2 == 0) {
VpnBondingLink vblNew = (VpnBondingLink) SerializationUtils.clone(vbl);
vblNew.setVpnBondingLinkId(UUID.randomUUID().toString());
links.add(vblNew);
}
- links.get(links.size() - 1).getServiceProxy(sp.getId()).setServiceInstance(setSolution(solutionInfo, placement));
- }else{
+ links.get(links.size() - 1).getServiceProxy(sp.getId())
+ .setServiceInstance(setSolution(solutionInfo, placement));
+ } else {
sp.setServiceInstance(setSolution(solutionInfo, placement));
}
break search;
}
}
}
- for(AllottedResource ar:allottes){
- if(placement.getString(SERVICE_RESOURCE_ID).equals(ar.getId())){
+ for (AllottedResource ar : allottes) {
+ if (placement.getString(SERVICE_RESOURCE_ID).equals(ar.getId())) {
ar.setParentServiceInstance(setSolution(solutionInfo, placement));
break search;
}
}
- for(GenericVnf vnf:vnfs){
- if(placement.getString(SERVICE_RESOURCE_ID).equals(vnf.getVnfId())){
+ for (GenericVnf vnf : vnfs) {
+ if (placement.getString(SERVICE_RESOURCE_ID).equals(vnf.getVnfId())) {
ServiceInstance si = setSolution(solutionInfo, placement);
serviceInstance.setSolutionInfo(si.getSolutionInfo());
serviceInstance.getVnfs().add(si.getVnfs().get(0));
@@ -512,7 +513,7 @@ public class OofHomingV2 {
* Creates and sets necessary pojos with placement solution data for a given demand
*
*/
- private ServiceInstance setSolution(SolutionInfo solutionInfo, JSONObject placement){
+ private ServiceInstance setSolution(SolutionInfo solutionInfo, JSONObject placement) {
logger.debug("Mapping placement solution");
String invalidMessage = "Oof Response contains invalid: ";
@@ -528,45 +529,45 @@ public class OofHomingV2 {
ServiceInstance si = new ServiceInstance();
CloudRegion cloud = setCloud(assignmentsMap);
- if(type.equals("service")){
- if(identifierType.equals(CandidateType.SERVICE_INSTANCE_ID.toString())){
+ if (type.equals("service")) {
+ if (identifierType.equals(CandidateType.SERVICE_INSTANCE_ID.toString())) {
solutionInfo.setHomed(true);
si.setServiceInstanceId(identifierValue);
si.setOrchestrationStatus(OrchestrationStatus.CREATED);
cloud.setLcpCloudRegionId(assignmentsMap.get("cloudRegionId"));
- if(assignmentsMap.containsKey("vnfHostName")){
+ if (assignmentsMap.containsKey("vnfHostName")) {
logger.debug("Resources has been homed to a vnf");
GenericVnf vnf = setVnf(assignmentsMap);
vnf.setCloudRegion(cloud);
si.getVnfs().add(vnf);
- }else if(assignmentsMap.containsKey("primaryPnfName")){
+ } else if (assignmentsMap.containsKey("primaryPnfName")) {
logger.debug("Resources has been homed to a pnf");
Pnf priPnf = setPnf(assignmentsMap, "primary");
priPnf.setCloudRegion(cloud);
si.getPnfs().add(priPnf);
- if(assignmentsMap.containsKey("secondaryPnfName")){
+ if (assignmentsMap.containsKey("secondaryPnfName")) {
Pnf secPnf = setPnf(assignmentsMap, "secondary");
secPnf.setCloudRegion(cloud);
si.getPnfs().add(secPnf);
}
}
- }else{
+ } else {
logger.debug(invalidMessage + IDENTIFIER_TYPE);
throw new BpmnError(UNPROCESSABLE, invalidMessage + IDENTIFIER_TYPE);
}
- }else if(type.equals("cloud")){
- if(identifierType.equals(CandidateType.CLOUD_REGION_ID.toString())){
+ } else if (type.equals("cloud")) {
+ if (identifierType.equals(CandidateType.CLOUD_REGION_ID.toString())) {
logger.debug("Resources has been homed to a cloud region");
cloud.setLcpCloudRegionId(identifierValue);
solutionInfo.setHomed(false);
solutionInfo.setTargetedCloudRegion(cloud);
si.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- }else{
+ } else {
logger.debug(invalidMessage + IDENTIFIER_TYPE);
throw new BpmnError(UNPROCESSABLE, invalidMessage + IDENTIFIER_TYPE);
}
- }else{
+ } else {
logger.debug(invalidMessage + INVENTORY_TYPE);
throw new BpmnError(UNPROCESSABLE, invalidMessage + INVENTORY_TYPE);
}
@@ -578,7 +579,7 @@ public class OofHomingV2 {
* Sets the cloud data to a cloud region object
*
*/
- private CloudRegion setCloud(Map<String, String> assignmentsMap){
+ private CloudRegion setCloud(Map<String, String> assignmentsMap) {
CloudRegion cloud = new CloudRegion();
cloud.setCloudOwner(assignmentsMap.get("cloudOwner"));
cloud.setCloudRegionVersion(assignmentsMap.get("aicVersion"));
@@ -590,7 +591,7 @@ public class OofHomingV2 {
* Sets the vnf data to a generic vnf object
*
*/
- private GenericVnf setVnf(Map<String, String> assignmentsMap){
+ private GenericVnf setVnf(Map<String, String> assignmentsMap) {
GenericVnf vnf = new GenericVnf();
vnf.setOrchestrationStatus(OrchestrationStatus.CREATED);
vnf.setVnfName(assignmentsMap.get("vnfHostName"));
@@ -602,7 +603,7 @@ public class OofHomingV2 {
* Sets the pnf data to a pnf object
*
*/
- private Pnf setPnf(Map<String, String> assignmentsMap, String role){
+ private Pnf setPnf(Map<String, String> assignmentsMap, String role) {
Pnf pnf = new Pnf();
pnf.setRole(role);
pnf.setOrchestrationStatus(OrchestrationStatus.CREATED);
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java
index 2e7184b9ff..29037980cc 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java
@@ -23,13 +23,11 @@
package org.onap.so.bpmn.buildingblock;
import static org.apache.commons.lang3.StringUtils.*;
-
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import org.apache.commons.lang.SerializationUtils;
import org.camunda.bpm.engine.delegate.BpmnError;
import org.json.JSONArray;
@@ -56,10 +54,8 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoMetadata;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance;
import org.onap.so.client.exception.BadResponseException;
import org.onap.so.client.exception.ExceptionBuilder;
-
import org.onap.so.client.sniro.SniroClient;
import static org.onap.so.client.sniro.SniroValidator.*;
-
import org.onap.so.client.sniro.beans.Demand;
import org.onap.so.client.sniro.beans.LicenseInfo;
import org.onap.so.client.sniro.beans.ModelInfo;
@@ -78,8 +74,7 @@ import org.springframework.web.util.UriUtils;
/**
- * The sniro homing building block obtains licensing and homing solutions for a given
- * resource or set of resources.
+ * The sniro homing building block obtains licensing and homing solutions for a given resource or set of resources.
*
* @author cb645j
*
@@ -87,514 +82,521 @@ import org.springframework.web.util.UriUtils;
@Component("SniroHoming")
public class SniroHomingV2 {
- private static final Logger logger = LoggerFactory.getLogger(SniroHomingV2.class);
- private JsonUtils jsonUtils = new JsonUtils();
- @Autowired
- private Environment env;
- @Autowired
- private SniroClient client;
- @Autowired
- private ExceptionBuilder exceptionUtil;
- private static final String MODEL_NAME = "modelName";
- private static final String MODEL_INVARIANT_ID = "modelInvariantId";
- private static final String MODEL_VERSION_ID = "modelVersionId";
- private static final String MODEL_VERSION = "modelVersion";
- private static final String SERVICE_RESOURCE_ID = "serviceResourceId";
- private static final String RESOURCE_MODULE_NAME = "resourceModuleName";
- private static final String RESOURCE_MODEL_INFO = "resourceModelInfo";
- private static final String IDENTIFIER_TYPE = "identifierType";
- private static final String SOLUTIONS = "solutions";
- private static final String RESOURCE_MISSING_DATA = "Resource does not contain: ";
- private static final String SERVICE_MISSING_DATA = "Service Instance does not contain: ";
- private static final String UNPROCESSABLE = "422";
- private static final int INTERNAL = 500;
-
- /**
- * Generates the request payload then sends to sniro manager to perform homing and
- * licensing for the provided demands
- *
- * @param execution
- */
- public void callSniro(BuildingBlockExecution execution){
- logger.debug("Started Sniro Homing Call Sniro");
- try{
- GeneralBuildingBlock bb = execution.getGeneralBuildingBlock();
-
- RequestContext requestContext = bb.getRequestContext();
- RequestParameters requestParams = requestContext.getRequestParameters();
- String requestId = requestContext.getMsoRequestId();
-
- ServiceInstance serviceInstance = bb.getCustomer().getServiceSubscription().getServiceInstances().get(0);
- Customer customer = bb.getCustomer();
-
- String timeout = execution.getVariable("timeout");
- if(isBlank(timeout)){
- timeout = env.getProperty("sniro.manager.timeout", "PT30M");
- }
-
- SniroManagerRequest request = new SniroManagerRequest();
-
- RequestInfo requestInfo = buildRequestInfo(requestId, timeout);
- request.setRequestInformation(requestInfo);
-
- ServiceInfo serviceInfo = buildServiceInfo(serviceInstance);
- request.setServiceInformation(serviceInfo);
-
- PlacementInfo placementInfo = buildPlacementInfo(customer, requestParams);
-
- List<Demand> placementDemands = buildPlacementDemands(serviceInstance);
- placementInfo.setDemands(placementDemands);
- request.setPlacementInformation(placementInfo);
-
- LicenseInfo licenseInfo = new LicenseInfo();
-
- List<Demand> licenseDemands = buildLicenseDemands(serviceInstance);
- licenseInfo.setDemands(licenseDemands);
- request.setLicenseInformation(licenseInfo);
-
- if(placementDemands.size() > 0 || licenseDemands.size() > 0){
- client.postDemands(request);
- }else{
- logger.debug(SERVICE_MISSING_DATA + "resources eligible for homing or licensing");
- throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + "resources eligible for homing or licensing");
- }
-
- //Variables for ReceiveWorkflowMessage subflow
- execution.setVariable("asyncCorrelator", requestId);
- execution.setVariable("asyncMessageType", "SNIROResponse");
- execution.setVariable("asyncTimeout", timeout);
-
- logger.trace("Completed Sniro Homing Call Sniro");
- }catch(BpmnError e){
- logger.error("Exception occurred", e);
- exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage());
- }catch(BadResponseException e){
- logger.error("Exception occurred", e);
- exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage());
- }catch(Exception e){
- logger.error("Exception occurred", e);
- exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL, "Internal Error - occurred while preparing sniro request: " + e.getMessage());
- }
- }
-
- /**
- * Validates, processes, and sets the homing and licensing solutions that are returned by
- * sniro manager
- *
- * @param execution
- * @param asyncResponse
- */
- public void processSolution(BuildingBlockExecution execution, String asyncResponse){
- logger.trace("Started Sniro Homing Process Solution");
- try{
- //TODO improve handling multiple solutions but is dependent on sniro enhancing api + work with sniro conductor to improve "inventoryType" representation
- validateSolution(asyncResponse);
- ServiceInstance serviceInstance = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
-
- logger.debug("Processing sniro manager asyncronous response");
- JSONObject response = new JSONObject(asyncResponse);
- if(response.has(SOLUTIONS)){
- JSONObject allSolutions = response.getJSONObject(SOLUTIONS);
- if(allSolutions.has("placementSolutions")){
- JSONArray placementSolutions = allSolutions.getJSONArray("placementSolutions");
- for(int i = 0; i < placementSolutions.length(); i++){
- JSONArray placements = placementSolutions.getJSONArray(i);
- processPlacementSolution(serviceInstance, placements, i);
- }
- }
- if(allSolutions.has("licenseSolutions")){
- JSONArray licenseSolutions = allSolutions.getJSONArray("licenseSolutions");
- if(licenseSolutions.length() > 0){
- processLicenseSolution(serviceInstance, licenseSolutions);
- }
- }
- }else{
- throw new BpmnError(UNPROCESSABLE, "Sniro Managers response does not contain: " + SOLUTIONS);
- }
-
- execution.setVariable("generalBuildingBlock", execution.getGeneralBuildingBlock());
-
- logger.trace("Completed Sniro Homing Process Solution");
- }catch(BpmnError e){
- logger.error("Exception occurred", e);
- exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage());
- }catch(BadResponseException e){
- logger.error("Exception occurred", e);
- exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage());
- }catch(Exception e){
- logger.error("Exception occurred", e);
- exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL, "Internal Error - occurred while processing sniro asynchronous response: " + e.getMessage());
- }
- }
-
- /**
- * Builds the request information section for the homing/licensing request
- *
- * @throws Exception
- */
- private RequestInfo buildRequestInfo(String requestId, String timeout) throws Exception{
- logger.trace("Building request information");
- RequestInfo requestInfo = new RequestInfo();
- if(requestId != null){
- String host = env.getProperty("mso.workflow.message.endpoint");
- String callbackUrl = host + "/" + UriUtils.encodePathSegment("SNIROResponse", "UTF-8") + "/" + UriUtils.encodePathSegment(requestId, "UTF-8");
-
- Duration d = Duration.parse(timeout);
-
- requestInfo.setTransactionId(requestId);
- requestInfo.setRequestId(requestId);
- requestInfo.setCallbackUrl(callbackUrl);
- requestInfo.setRequestType("create");
- requestInfo.setTimeout(d.getSeconds());
-
- } else{
- throw new BpmnError(UNPROCESSABLE, "Request Context does not contain: requestId");
- }
- return requestInfo;
- }
-
- /**
- * Builds the request information section for the homing/licensing request
- *
- */
- private ServiceInfo buildServiceInfo(ServiceInstance serviceInstance){
- logger.trace("Building service information");
- ServiceInfo info = new ServiceInfo();
- ModelInfoServiceInstance modelInfo = serviceInstance.getModelInfoServiceInstance();
- if(isNotBlank(modelInfo.getModelInvariantUuid()) && isNotBlank(modelInfo.getModelUuid())){
- info.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- if(modelInfo.getServiceType() != null && modelInfo.getServiceType().length() > 0){ //temp solution
- info.setServiceName(modelInfo.getServiceType());
- }
- if(modelInfo.getServiceRole() != null){
- info.setServiceRole(modelInfo.getServiceRole());
- }
- info.setModelInfo(buildModelInfo(modelInfo));
- }else{
- throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + MODEL_VERSION_ID + ", " + MODEL_INVARIANT_ID);
- }
- return info;
- }
-
- /**
- * Builds initial section of placement info for the homing/licensing request
- *
- */
- private PlacementInfo buildPlacementInfo(Customer customer, RequestParameters requestParams){
- PlacementInfo placementInfo = new PlacementInfo();
- if(customer != null){
- logger.debug("Adding subscriber to placement information");
- SubscriberInfo subscriber = new SubscriberInfo();
- subscriber.setGlobalSubscriberId(customer.getGlobalCustomerId());
- subscriber.setSubscriberName(customer.getSubscriberName());
- subscriber.setSubscriberCommonSiteId(customer.getSubscriberCommonSiteId());
- placementInfo.setSubscriberInfo(subscriber);
- if(requestParams != null){
- logger.debug("Adding request parameters to placement information");
- placementInfo.setRequestParameters(requestParams.toJsonString());
- }
- }else{
- throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + "customer");
- }
- return placementInfo;
-
- }
-
- /**
- * Builds the placement demand list for the homing/licensing request
- *
- */
- private List<Demand> buildPlacementDemands(ServiceInstance serviceInstance){
- logger.trace("Building placement information demands");
- List<Demand> placementDemands = new ArrayList<Demand>();
-
- List<AllottedResource> allottedResourceList = serviceInstance.getAllottedResources();
- if(!allottedResourceList.isEmpty()){
- logger.debug("Adding allotted resources to placement demands list");
- for(AllottedResource ar : allottedResourceList){
- if(isBlank(ar.getId())){
- ar.setId(UUID.randomUUID().toString());
- }
- Demand demand = buildDemand(ar.getId(), ar.getModelInfoAllottedResource());
- addCandidates(ar, demand);
- placementDemands.add(demand);
- }
- }
- List<VpnBondingLink> vpnBondingLinkList = serviceInstance.getVpnBondingLinks();
- if(!vpnBondingLinkList.isEmpty()){
- logger.debug("Adding vpn bonding links to placement demands list");
- for(VpnBondingLink vbl:vpnBondingLinkList){
- List<ServiceProxy> serviceProxyList = vbl.getServiceProxies();
- for(ServiceProxy sp : serviceProxyList){
- if(isBlank(sp.getId())){
- sp.setId(UUID.randomUUID().toString());
- }
- Demand demand = buildDemand(sp.getId(), sp.getModelInfoServiceProxy());
- addCandidates(sp, demand);
- placementDemands.add(demand);
- }
- }
- }
- return placementDemands;
- }
-
- /**
- * Builds the license demand list for the homing/licensing request
- *
- */
- private List<Demand> buildLicenseDemands(ServiceInstance serviceInstance){
- logger.trace("Building license information");
- List<Demand> licenseDemands = new ArrayList<Demand>();
- List<GenericVnf> vnfList = serviceInstance.getVnfs();
- if(!vnfList.isEmpty()){
- logger.debug("Adding vnfs to license demands list");
- for(GenericVnf vnf : vnfList){
- Demand demand = buildDemand(vnf.getVnfId(), vnf.getModelInfoGenericVnf());
- licenseDemands.add(demand);
- }
- }
- return licenseDemands;
- }
-
- /**
- * Builds a single demand object
- *
- */
- private Demand buildDemand(String id, ModelInfoMetadata metadata){
- logger.debug("Building demand for service or resource: " + id);
- Demand demand = new Demand();
- if(isNotBlank(id) && isNotBlank(metadata.getModelInstanceName())){
- demand.setServiceResourceId(id);
- demand.setResourceModuleName(metadata.getModelInstanceName());
- demand.setModelInfo(buildModelInfo(metadata));
- }else{
- throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + "modelInstanceName");
- }
- return demand;
- }
-
- /**
- * Builds the resource model info section
- *
- */
- private ModelInfo buildModelInfo(ModelInfoMetadata metadata){
- ModelInfo object = new ModelInfo();
- String invariantUuid = metadata.getModelInvariantUuid();
- String modelUuid = metadata.getModelUuid();
- if(isNotBlank(invariantUuid) && isNotBlank(modelUuid)){
- object.setModelInvariantId(invariantUuid);
- object.setModelVersionId(modelUuid);
- object.setModelName(metadata.getModelName());
- object.setModelVersion(metadata.getModelVersion());
- }else if(isNotBlank(invariantUuid)){
- throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + MODEL_VERSION_ID);
- }else{
- throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + MODEL_INVARIANT_ID);
- }
- return object;
- }
-
- /**
- * Adds required, excluded, and existing candidates to a demand
- *
- */
- private void addCandidates(SolutionCandidates candidates, Demand demand){
- List<Candidate> required = candidates.getRequiredCandidates();
- List<Candidate> excluded = candidates.getExcludedCandidates();
- if(!required.isEmpty()){
- List<org.onap.so.client.sniro.beans.Candidate> cans = new ArrayList<org.onap.so.client.sniro.beans.Candidate>();
- for(Candidate c:required){
- org.onap.so.client.sniro.beans.Candidate can = new org.onap.so.client.sniro.beans.Candidate();
- can.setIdentifierType(c.getIdentifierType());
- can.setIdentifiers(c.getIdentifiers());
- can.setCloudOwner(c.getCloudOwner());
- cans.add(can);
- }
- demand.setRequiredCandidates(cans);
- }
- if(!excluded.isEmpty()){
- List<org.onap.so.client.sniro.beans.Candidate> cans = new ArrayList<org.onap.so.client.sniro.beans.Candidate>();
- for(Candidate c:excluded){
- org.onap.so.client.sniro.beans.Candidate can = new org.onap.so.client.sniro.beans.Candidate();
- can.setIdentifierType(c.getIdentifierType());
- can.setIdentifiers(c.getIdentifiers());
- can.setCloudOwner(c.getCloudOwner());
- cans.add(can);
- }
- demand.setExcludedCandidates(cans);
- }
- //TODO support existing candidates
- }
-
- /**
- * Processes the license solutions and sets to the corresponding generic vnf
- *
- */
- private void processLicenseSolution(ServiceInstance serviceInstance, JSONArray licenseSolutions){
- List<GenericVnf> vnfs = serviceInstance.getVnfs();
-
- logger.debug("Processing the license solution");
- for(int i = 0; i < licenseSolutions.length(); i++){
- JSONObject licenseSolution = licenseSolutions.getJSONObject(i);
- for(GenericVnf vnf:vnfs){
- if(licenseSolution.getString(SERVICE_RESOURCE_ID).equals(vnf.getVnfId())){
- License license = new License();
- JSONArray entitlementPools = licenseSolution.getJSONArray("entitlementPoolUUID");
- List<String> entitlementPoolsList = jsonUtils.StringArrayToList(entitlementPools);
- license.setEntitlementPoolUuids(entitlementPoolsList);
- JSONArray licenseKeys = licenseSolution.getJSONArray("licenseKeyGroupUUID");
- List<String> licenseKeysList = jsonUtils.StringArrayToList(licenseKeys);
- license.setLicenseKeyGroupUuids(licenseKeysList);
-
- vnf.setLicense(license);
- }
- }
- }
- }
-
- /**
- * Processes a placement solution list then correlates and sets each placement solution
- * to its corresponding resource
- *
- */
- private void processPlacementSolution(ServiceInstance serviceInstance, JSONArray placements, int i){
- List<VpnBondingLink> links = serviceInstance.getVpnBondingLinks();
- List<AllottedResource> allottes = serviceInstance.getAllottedResources();
- List<GenericVnf> vnfs = serviceInstance.getVnfs();
-
- logger.debug("Processing placement solution " + i+1);
- for(int p = 0; p < placements.length(); p++){
- JSONObject placement = placements.getJSONObject(p);
- SolutionInfo solutionInfo = new SolutionInfo();
- solutionInfo.setSolutionId(i + 1);
- search: {
- for(VpnBondingLink vbl:links){
- List<ServiceProxy> proxies = vbl.getServiceProxies();
- for(ServiceProxy sp:proxies){
- if(placement.getString(SERVICE_RESOURCE_ID).equals(sp.getId())){
- if(i > 0){
- if(p % 2 == 0){
- VpnBondingLink vblNew = (VpnBondingLink) SerializationUtils.clone(vbl);
- vblNew.setVpnBondingLinkId(UUID.randomUUID().toString());
- links.add(vblNew);
- }
- links.get(links.size() - 1).getServiceProxy(sp.getId()).setServiceInstance(setSolution(solutionInfo, placement));
- }else{
- sp.setServiceInstance(setSolution(solutionInfo, placement));
- }
- break search;
- }
- }
- }
- for(AllottedResource ar:allottes){
- if(placement.getString(SERVICE_RESOURCE_ID).equals(ar.getId())){
- ar.setParentServiceInstance(setSolution(solutionInfo, placement));
- break search;
- }
- }
- for(GenericVnf vnf:vnfs){
- if(placement.getString(SERVICE_RESOURCE_ID).equals(vnf.getVnfId())){
- ServiceInstance si = setSolution(solutionInfo, placement);
- serviceInstance.setSolutionInfo(si.getSolutionInfo());
- serviceInstance.getVnfs().add(si.getVnfs().get(0));
- break search;
- }
- }
- }
- }
- }
-
-
- /**
- * Creates and sets necessary pojos with placement solution data for a given demand
- *
- */
- private ServiceInstance setSolution(SolutionInfo solutionInfo, JSONObject placement){
- logger.debug("Mapping placement solution");
- String invalidMessage = "Sniro Managers Response contains invalid: ";
-
- JSONObject solution = placement.getJSONObject("solution");
- String identifierType = solution.getString(IDENTIFIER_TYPE);
- List<String> identifiersList = jsonUtils.StringArrayToList(solution.getJSONArray("identifiers").toString());
- String identifierValue = identifiersList.get(0);
-
- JSONArray assignments = placement.getJSONArray("assignmentInfo");
- Map<String, String> assignmentsMap = jsonUtils.entryArrayToMap(assignments.toString(), "key", "value");
- solutionInfo.setRehome(Boolean.parseBoolean(assignmentsMap.get("isRehome")));
-
- ServiceInstance si = new ServiceInstance();
- CloudRegion cloud = setCloud(assignmentsMap);
- if(identifierType.equals(CandidateType.SERVICE_INSTANCE_ID.toString())){
- solutionInfo.setHomed(true);
- si.setServiceInstanceId(identifierValue);
- si.setOrchestrationStatus(OrchestrationStatus.CREATED);
- cloud.setLcpCloudRegionId(assignmentsMap.get("cloudRegionId"));
- if(assignmentsMap.containsKey("vnfHostName")){
- logger.debug("Resources has been homed to a vnf");
- GenericVnf vnf = setVnf(assignmentsMap);
- vnf.setCloudRegion(cloud);
- si.getVnfs().add(vnf);
-
- }else if(assignmentsMap.containsKey("primaryPnfName")){
- logger.debug("Resources has been homed to a pnf");
- Pnf priPnf = setPnf(assignmentsMap, "primary");
- priPnf.setCloudRegion(cloud);
- si.getPnfs().add(priPnf);
- if(assignmentsMap.containsKey("secondaryPnfName")){
- Pnf secPnf = setPnf(assignmentsMap, "secondary");
- secPnf.setCloudRegion(cloud);
- si.getPnfs().add(secPnf);
- }
- }
- }else if(identifierType.equals(CandidateType.CLOUD_REGION_ID.toString())){
- logger.debug("Resources has been homed to a cloud region");
- cloud.setLcpCloudRegionId(identifierValue);
- solutionInfo.setHomed(false);
- solutionInfo.setTargetedCloudRegion(cloud);
- si.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- }else{
- logger.debug(invalidMessage + IDENTIFIER_TYPE);
- throw new BpmnError(UNPROCESSABLE, invalidMessage + IDENTIFIER_TYPE);
- }
- si.setSolutionInfo(solutionInfo);
- return si;
- }
-
- /**
- * Sets the cloud data to a cloud region object
- *
- */
- private CloudRegion setCloud(Map<String, String> assignmentsMap){
- CloudRegion cloud = new CloudRegion();
- cloud.setCloudOwner(assignmentsMap.get("cloudOwner"));
- cloud.setCloudRegionVersion(assignmentsMap.get("aicVersion"));
- cloud.setComplex(assignmentsMap.get("aicClli"));
- return cloud;
- }
-
- /**
- * Sets the vnf data to a generic vnf object
- *
- */
- private GenericVnf setVnf(Map<String, String> assignmentsMap){
- GenericVnf vnf = new GenericVnf();
- vnf.setOrchestrationStatus(OrchestrationStatus.CREATED);
- vnf.setVnfName(assignmentsMap.get("vnfHostName"));
- vnf.setVnfId(assignmentsMap.get("vnfId"));
- return vnf;
- }
-
- /**
- * Sets the pnf data to a pnf object
- *
- */
- private Pnf setPnf(Map<String, String> assignmentsMap, String role){
- Pnf pnf = new Pnf();
- pnf.setRole(role);
- pnf.setOrchestrationStatus(OrchestrationStatus.CREATED);
- pnf.setPnfName(assignmentsMap.get(role + "PnfName"));
- return pnf;
- }
+ private static final Logger logger = LoggerFactory.getLogger(SniroHomingV2.class);
+ private JsonUtils jsonUtils = new JsonUtils();
+ @Autowired
+ private Environment env;
+ @Autowired
+ private SniroClient client;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ private static final String MODEL_NAME = "modelName";
+ private static final String MODEL_INVARIANT_ID = "modelInvariantId";
+ private static final String MODEL_VERSION_ID = "modelVersionId";
+ private static final String MODEL_VERSION = "modelVersion";
+ private static final String SERVICE_RESOURCE_ID = "serviceResourceId";
+ private static final String RESOURCE_MODULE_NAME = "resourceModuleName";
+ private static final String RESOURCE_MODEL_INFO = "resourceModelInfo";
+ private static final String IDENTIFIER_TYPE = "identifierType";
+ private static final String SOLUTIONS = "solutions";
+ private static final String RESOURCE_MISSING_DATA = "Resource does not contain: ";
+ private static final String SERVICE_MISSING_DATA = "Service Instance does not contain: ";
+ private static final String UNPROCESSABLE = "422";
+ private static final int INTERNAL = 500;
+
+ /**
+ * Generates the request payload then sends to sniro manager to perform homing and licensing for the provided
+ * demands
+ *
+ * @param execution
+ */
+ public void callSniro(BuildingBlockExecution execution) {
+ logger.debug("Started Sniro Homing Call Sniro");
+ try {
+ GeneralBuildingBlock bb = execution.getGeneralBuildingBlock();
+
+ RequestContext requestContext = bb.getRequestContext();
+ RequestParameters requestParams = requestContext.getRequestParameters();
+ String requestId = requestContext.getMsoRequestId();
+
+ ServiceInstance serviceInstance = bb.getCustomer().getServiceSubscription().getServiceInstances().get(0);
+ Customer customer = bb.getCustomer();
+
+ String timeout = execution.getVariable("timeout");
+ if (isBlank(timeout)) {
+ timeout = env.getProperty("sniro.manager.timeout", "PT30M");
+ }
+
+ SniroManagerRequest request = new SniroManagerRequest();
+
+ RequestInfo requestInfo = buildRequestInfo(requestId, timeout);
+ request.setRequestInformation(requestInfo);
+
+ ServiceInfo serviceInfo = buildServiceInfo(serviceInstance);
+ request.setServiceInformation(serviceInfo);
+
+ PlacementInfo placementInfo = buildPlacementInfo(customer, requestParams);
+
+ List<Demand> placementDemands = buildPlacementDemands(serviceInstance);
+ placementInfo.setDemands(placementDemands);
+ request.setPlacementInformation(placementInfo);
+
+ LicenseInfo licenseInfo = new LicenseInfo();
+
+ List<Demand> licenseDemands = buildLicenseDemands(serviceInstance);
+ licenseInfo.setDemands(licenseDemands);
+ request.setLicenseInformation(licenseInfo);
+
+ if (placementDemands.size() > 0 || licenseDemands.size() > 0) {
+ client.postDemands(request);
+ } else {
+ logger.debug(SERVICE_MISSING_DATA + "resources eligible for homing or licensing");
+ throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + "resources eligible for homing or licensing");
+ }
+
+ // Variables for ReceiveWorkflowMessage subflow
+ execution.setVariable("asyncCorrelator", requestId);
+ execution.setVariable("asyncMessageType", "SNIROResponse");
+ execution.setVariable("asyncTimeout", timeout);
+
+ logger.trace("Completed Sniro Homing Call Sniro");
+ } catch (BpmnError e) {
+ logger.error("Exception occurred", e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage());
+ } catch (BadResponseException e) {
+ logger.error("Exception occurred", e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage());
+ } catch (Exception e) {
+ logger.error("Exception occurred", e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL,
+ "Internal Error - occurred while preparing sniro request: " + e.getMessage());
+ }
+ }
+
+ /**
+ * Validates, processes, and sets the homing and licensing solutions that are returned by sniro manager
+ *
+ * @param execution
+ * @param asyncResponse
+ */
+ public void processSolution(BuildingBlockExecution execution, String asyncResponse) {
+ logger.trace("Started Sniro Homing Process Solution");
+ try {
+ // TODO improve handling multiple solutions but is dependent on sniro enhancing api + work with sniro
+ // conductor to improve "inventoryType" representation
+ validateSolution(asyncResponse);
+ ServiceInstance serviceInstance = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription()
+ .getServiceInstances().get(0);
+
+ logger.debug("Processing sniro manager asyncronous response");
+ JSONObject response = new JSONObject(asyncResponse);
+ if (response.has(SOLUTIONS)) {
+ JSONObject allSolutions = response.getJSONObject(SOLUTIONS);
+ if (allSolutions.has("placementSolutions")) {
+ JSONArray placementSolutions = allSolutions.getJSONArray("placementSolutions");
+ for (int i = 0; i < placementSolutions.length(); i++) {
+ JSONArray placements = placementSolutions.getJSONArray(i);
+ processPlacementSolution(serviceInstance, placements, i);
+ }
+ }
+ if (allSolutions.has("licenseSolutions")) {
+ JSONArray licenseSolutions = allSolutions.getJSONArray("licenseSolutions");
+ if (licenseSolutions.length() > 0) {
+ processLicenseSolution(serviceInstance, licenseSolutions);
+ }
+ }
+ } else {
+ throw new BpmnError(UNPROCESSABLE, "Sniro Managers response does not contain: " + SOLUTIONS);
+ }
+
+ execution.setVariable("generalBuildingBlock", execution.getGeneralBuildingBlock());
+
+ logger.trace("Completed Sniro Homing Process Solution");
+ } catch (BpmnError e) {
+ logger.error("Exception occurred", e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage());
+ } catch (BadResponseException e) {
+ logger.error("Exception occurred", e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage());
+ } catch (Exception e) {
+ logger.error("Exception occurred", e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL,
+ "Internal Error - occurred while processing sniro asynchronous response: " + e.getMessage());
+ }
+ }
+
+ /**
+ * Builds the request information section for the homing/licensing request
+ *
+ * @throws Exception
+ */
+ private RequestInfo buildRequestInfo(String requestId, String timeout) throws Exception {
+ logger.trace("Building request information");
+ RequestInfo requestInfo = new RequestInfo();
+ if (requestId != null) {
+ String host = env.getProperty("mso.workflow.message.endpoint");
+ String callbackUrl = host + "/" + UriUtils.encodePathSegment("SNIROResponse", "UTF-8") + "/"
+ + UriUtils.encodePathSegment(requestId, "UTF-8");
+
+ Duration d = Duration.parse(timeout);
+
+ requestInfo.setTransactionId(requestId);
+ requestInfo.setRequestId(requestId);
+ requestInfo.setCallbackUrl(callbackUrl);
+ requestInfo.setRequestType("create");
+ requestInfo.setTimeout(d.getSeconds());
+
+ } else {
+ throw new BpmnError(UNPROCESSABLE, "Request Context does not contain: requestId");
+ }
+ return requestInfo;
+ }
+
+ /**
+ * Builds the request information section for the homing/licensing request
+ *
+ */
+ private ServiceInfo buildServiceInfo(ServiceInstance serviceInstance) {
+ logger.trace("Building service information");
+ ServiceInfo info = new ServiceInfo();
+ ModelInfoServiceInstance modelInfo = serviceInstance.getModelInfoServiceInstance();
+ if (isNotBlank(modelInfo.getModelInvariantUuid()) && isNotBlank(modelInfo.getModelUuid())) {
+ info.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ if (modelInfo.getServiceType() != null && modelInfo.getServiceType().length() > 0) { // temp solution
+ info.setServiceName(modelInfo.getServiceType());
+ }
+ if (modelInfo.getServiceRole() != null) {
+ info.setServiceRole(modelInfo.getServiceRole());
+ }
+ info.setModelInfo(buildModelInfo(modelInfo));
+ } else {
+ throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + MODEL_VERSION_ID + ", " + MODEL_INVARIANT_ID);
+ }
+ return info;
+ }
+
+ /**
+ * Builds initial section of placement info for the homing/licensing request
+ *
+ */
+ private PlacementInfo buildPlacementInfo(Customer customer, RequestParameters requestParams) {
+ PlacementInfo placementInfo = new PlacementInfo();
+ if (customer != null) {
+ logger.debug("Adding subscriber to placement information");
+ SubscriberInfo subscriber = new SubscriberInfo();
+ subscriber.setGlobalSubscriberId(customer.getGlobalCustomerId());
+ subscriber.setSubscriberName(customer.getSubscriberName());
+ subscriber.setSubscriberCommonSiteId(customer.getSubscriberCommonSiteId());
+ placementInfo.setSubscriberInfo(subscriber);
+ if (requestParams != null) {
+ logger.debug("Adding request parameters to placement information");
+ placementInfo.setRequestParameters(requestParams.toJsonString());
+ }
+ } else {
+ throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + "customer");
+ }
+ return placementInfo;
+
+ }
+
+ /**
+ * Builds the placement demand list for the homing/licensing request
+ *
+ */
+ private List<Demand> buildPlacementDemands(ServiceInstance serviceInstance) {
+ logger.trace("Building placement information demands");
+ List<Demand> placementDemands = new ArrayList<Demand>();
+
+ List<AllottedResource> allottedResourceList = serviceInstance.getAllottedResources();
+ if (!allottedResourceList.isEmpty()) {
+ logger.debug("Adding allotted resources to placement demands list");
+ for (AllottedResource ar : allottedResourceList) {
+ if (isBlank(ar.getId())) {
+ ar.setId(UUID.randomUUID().toString());
+ }
+ Demand demand = buildDemand(ar.getId(), ar.getModelInfoAllottedResource());
+ addCandidates(ar, demand);
+ placementDemands.add(demand);
+ }
+ }
+ List<VpnBondingLink> vpnBondingLinkList = serviceInstance.getVpnBondingLinks();
+ if (!vpnBondingLinkList.isEmpty()) {
+ logger.debug("Adding vpn bonding links to placement demands list");
+ for (VpnBondingLink vbl : vpnBondingLinkList) {
+ List<ServiceProxy> serviceProxyList = vbl.getServiceProxies();
+ for (ServiceProxy sp : serviceProxyList) {
+ if (isBlank(sp.getId())) {
+ sp.setId(UUID.randomUUID().toString());
+ }
+ Demand demand = buildDemand(sp.getId(), sp.getModelInfoServiceProxy());
+ addCandidates(sp, demand);
+ placementDemands.add(demand);
+ }
+ }
+ }
+ return placementDemands;
+ }
+
+ /**
+ * Builds the license demand list for the homing/licensing request
+ *
+ */
+ private List<Demand> buildLicenseDemands(ServiceInstance serviceInstance) {
+ logger.trace("Building license information");
+ List<Demand> licenseDemands = new ArrayList<Demand>();
+ List<GenericVnf> vnfList = serviceInstance.getVnfs();
+ if (!vnfList.isEmpty()) {
+ logger.debug("Adding vnfs to license demands list");
+ for (GenericVnf vnf : vnfList) {
+ Demand demand = buildDemand(vnf.getVnfId(), vnf.getModelInfoGenericVnf());
+ licenseDemands.add(demand);
+ }
+ }
+ return licenseDemands;
+ }
+
+ /**
+ * Builds a single demand object
+ *
+ */
+ private Demand buildDemand(String id, ModelInfoMetadata metadata) {
+ logger.debug("Building demand for service or resource: " + id);
+ Demand demand = new Demand();
+ if (isNotBlank(id) && isNotBlank(metadata.getModelInstanceName())) {
+ demand.setServiceResourceId(id);
+ demand.setResourceModuleName(metadata.getModelInstanceName());
+ demand.setModelInfo(buildModelInfo(metadata));
+ } else {
+ throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + "modelInstanceName");
+ }
+ return demand;
+ }
+
+ /**
+ * Builds the resource model info section
+ *
+ */
+ private ModelInfo buildModelInfo(ModelInfoMetadata metadata) {
+ ModelInfo object = new ModelInfo();
+ String invariantUuid = metadata.getModelInvariantUuid();
+ String modelUuid = metadata.getModelUuid();
+ if (isNotBlank(invariantUuid) && isNotBlank(modelUuid)) {
+ object.setModelInvariantId(invariantUuid);
+ object.setModelVersionId(modelUuid);
+ object.setModelName(metadata.getModelName());
+ object.setModelVersion(metadata.getModelVersion());
+ } else if (isNotBlank(invariantUuid)) {
+ throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + MODEL_VERSION_ID);
+ } else {
+ throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + MODEL_INVARIANT_ID);
+ }
+ return object;
+ }
+
+ /**
+ * Adds required, excluded, and existing candidates to a demand
+ *
+ */
+ private void addCandidates(SolutionCandidates candidates, Demand demand) {
+ List<Candidate> required = candidates.getRequiredCandidates();
+ List<Candidate> excluded = candidates.getExcludedCandidates();
+ if (!required.isEmpty()) {
+ List<org.onap.so.client.sniro.beans.Candidate> cans =
+ new ArrayList<org.onap.so.client.sniro.beans.Candidate>();
+ for (Candidate c : required) {
+ org.onap.so.client.sniro.beans.Candidate can = new org.onap.so.client.sniro.beans.Candidate();
+ can.setIdentifierType(c.getIdentifierType());
+ can.setIdentifiers(c.getIdentifiers());
+ can.setCloudOwner(c.getCloudOwner());
+ cans.add(can);
+ }
+ demand.setRequiredCandidates(cans);
+ }
+ if (!excluded.isEmpty()) {
+ List<org.onap.so.client.sniro.beans.Candidate> cans =
+ new ArrayList<org.onap.so.client.sniro.beans.Candidate>();
+ for (Candidate c : excluded) {
+ org.onap.so.client.sniro.beans.Candidate can = new org.onap.so.client.sniro.beans.Candidate();
+ can.setIdentifierType(c.getIdentifierType());
+ can.setIdentifiers(c.getIdentifiers());
+ can.setCloudOwner(c.getCloudOwner());
+ cans.add(can);
+ }
+ demand.setExcludedCandidates(cans);
+ }
+ // TODO support existing candidates
+ }
+
+ /**
+ * Processes the license solutions and sets to the corresponding generic vnf
+ *
+ */
+ private void processLicenseSolution(ServiceInstance serviceInstance, JSONArray licenseSolutions) {
+ List<GenericVnf> vnfs = serviceInstance.getVnfs();
+
+ logger.debug("Processing the license solution");
+ for (int i = 0; i < licenseSolutions.length(); i++) {
+ JSONObject licenseSolution = licenseSolutions.getJSONObject(i);
+ for (GenericVnf vnf : vnfs) {
+ if (licenseSolution.getString(SERVICE_RESOURCE_ID).equals(vnf.getVnfId())) {
+ License license = new License();
+ JSONArray entitlementPools = licenseSolution.getJSONArray("entitlementPoolUUID");
+ List<String> entitlementPoolsList = jsonUtils.StringArrayToList(entitlementPools);
+ license.setEntitlementPoolUuids(entitlementPoolsList);
+ JSONArray licenseKeys = licenseSolution.getJSONArray("licenseKeyGroupUUID");
+ List<String> licenseKeysList = jsonUtils.StringArrayToList(licenseKeys);
+ license.setLicenseKeyGroupUuids(licenseKeysList);
+
+ vnf.setLicense(license);
+ }
+ }
+ }
+ }
+
+ /**
+ * Processes a placement solution list then correlates and sets each placement solution to its corresponding
+ * resource
+ *
+ */
+ private void processPlacementSolution(ServiceInstance serviceInstance, JSONArray placements, int i) {
+ List<VpnBondingLink> links = serviceInstance.getVpnBondingLinks();
+ List<AllottedResource> allottes = serviceInstance.getAllottedResources();
+ List<GenericVnf> vnfs = serviceInstance.getVnfs();
+
+ logger.debug("Processing placement solution " + i + 1);
+ for (int p = 0; p < placements.length(); p++) {
+ JSONObject placement = placements.getJSONObject(p);
+ SolutionInfo solutionInfo = new SolutionInfo();
+ solutionInfo.setSolutionId(i + 1);
+ search: {
+ for (VpnBondingLink vbl : links) {
+ List<ServiceProxy> proxies = vbl.getServiceProxies();
+ for (ServiceProxy sp : proxies) {
+ if (placement.getString(SERVICE_RESOURCE_ID).equals(sp.getId())) {
+ if (i > 0) {
+ if (p % 2 == 0) {
+ VpnBondingLink vblNew = (VpnBondingLink) SerializationUtils.clone(vbl);
+ vblNew.setVpnBondingLinkId(UUID.randomUUID().toString());
+ links.add(vblNew);
+ }
+ links.get(links.size() - 1).getServiceProxy(sp.getId())
+ .setServiceInstance(setSolution(solutionInfo, placement));
+ } else {
+ sp.setServiceInstance(setSolution(solutionInfo, placement));
+ }
+ break search;
+ }
+ }
+ }
+ for (AllottedResource ar : allottes) {
+ if (placement.getString(SERVICE_RESOURCE_ID).equals(ar.getId())) {
+ ar.setParentServiceInstance(setSolution(solutionInfo, placement));
+ break search;
+ }
+ }
+ for (GenericVnf vnf : vnfs) {
+ if (placement.getString(SERVICE_RESOURCE_ID).equals(vnf.getVnfId())) {
+ ServiceInstance si = setSolution(solutionInfo, placement);
+ serviceInstance.setSolutionInfo(si.getSolutionInfo());
+ serviceInstance.getVnfs().add(si.getVnfs().get(0));
+ break search;
+ }
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Creates and sets necessary pojos with placement solution data for a given demand
+ *
+ */
+ private ServiceInstance setSolution(SolutionInfo solutionInfo, JSONObject placement) {
+ logger.debug("Mapping placement solution");
+ String invalidMessage = "Sniro Managers Response contains invalid: ";
+
+ JSONObject solution = placement.getJSONObject("solution");
+ String identifierType = solution.getString(IDENTIFIER_TYPE);
+ List<String> identifiersList = jsonUtils.StringArrayToList(solution.getJSONArray("identifiers").toString());
+ String identifierValue = identifiersList.get(0);
+
+ JSONArray assignments = placement.getJSONArray("assignmentInfo");
+ Map<String, String> assignmentsMap = jsonUtils.entryArrayToMap(assignments.toString(), "key", "value");
+ solutionInfo.setRehome(Boolean.parseBoolean(assignmentsMap.get("isRehome")));
+
+ ServiceInstance si = new ServiceInstance();
+ CloudRegion cloud = setCloud(assignmentsMap);
+ if (identifierType.equals(CandidateType.SERVICE_INSTANCE_ID.toString())) {
+ solutionInfo.setHomed(true);
+ si.setServiceInstanceId(identifierValue);
+ si.setOrchestrationStatus(OrchestrationStatus.CREATED);
+ cloud.setLcpCloudRegionId(assignmentsMap.get("cloudRegionId"));
+ if (assignmentsMap.containsKey("vnfHostName")) {
+ logger.debug("Resources has been homed to a vnf");
+ GenericVnf vnf = setVnf(assignmentsMap);
+ vnf.setCloudRegion(cloud);
+ si.getVnfs().add(vnf);
+
+ } else if (assignmentsMap.containsKey("primaryPnfName")) {
+ logger.debug("Resources has been homed to a pnf");
+ Pnf priPnf = setPnf(assignmentsMap, "primary");
+ priPnf.setCloudRegion(cloud);
+ si.getPnfs().add(priPnf);
+ if (assignmentsMap.containsKey("secondaryPnfName")) {
+ Pnf secPnf = setPnf(assignmentsMap, "secondary");
+ secPnf.setCloudRegion(cloud);
+ si.getPnfs().add(secPnf);
+ }
+ }
+ } else if (identifierType.equals(CandidateType.CLOUD_REGION_ID.toString())) {
+ logger.debug("Resources has been homed to a cloud region");
+ cloud.setLcpCloudRegionId(identifierValue);
+ solutionInfo.setHomed(false);
+ solutionInfo.setTargetedCloudRegion(cloud);
+ si.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ } else {
+ logger.debug(invalidMessage + IDENTIFIER_TYPE);
+ throw new BpmnError(UNPROCESSABLE, invalidMessage + IDENTIFIER_TYPE);
+ }
+ si.setSolutionInfo(solutionInfo);
+ return si;
+ }
+
+ /**
+ * Sets the cloud data to a cloud region object
+ *
+ */
+ private CloudRegion setCloud(Map<String, String> assignmentsMap) {
+ CloudRegion cloud = new CloudRegion();
+ cloud.setCloudOwner(assignmentsMap.get("cloudOwner"));
+ cloud.setCloudRegionVersion(assignmentsMap.get("aicVersion"));
+ cloud.setComplex(assignmentsMap.get("aicClli"));
+ return cloud;
+ }
+
+ /**
+ * Sets the vnf data to a generic vnf object
+ *
+ */
+ private GenericVnf setVnf(Map<String, String> assignmentsMap) {
+ GenericVnf vnf = new GenericVnf();
+ vnf.setOrchestrationStatus(OrchestrationStatus.CREATED);
+ vnf.setVnfName(assignmentsMap.get("vnfHostName"));
+ vnf.setVnfId(assignmentsMap.get("vnfId"));
+ return vnf;
+ }
+
+ /**
+ * Sets the pnf data to a pnf object
+ *
+ */
+ private Pnf setPnf(Map<String, String> assignmentsMap, String role) {
+ Pnf pnf = new Pnf();
+ pnf.setRole(role);
+ pnf.setOrchestrationStatus(OrchestrationStatus.CREATED);
+ pnf.setPnfName(assignmentsMap.get(role + "PnfName"));
+ return pnf;
+ }
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICommonTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICommonTasks.java
index bdb46e8d2b..7b518dcc86 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICommonTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICommonTasks.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.infrastructure.aai.tasks;
import java.util.Optional;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance;
import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
@@ -33,24 +32,25 @@ import org.springframework.stereotype.Component;
@Component
public class AAICommonTasks {
-
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
-
- public Optional<String> getServiceType(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- ModelInfoServiceInstance model = serviceInstance.getModelInfoServiceInstance();
- if (model != null) {
- return Optional.of(model.getServiceType());
- }
- } catch(Exception e) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e);
- }
- return Optional.empty();
- }
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+
+ public Optional<String> getServiceType(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+
+ ModelInfoServiceInstance model = serviceInstance.getModelInfoServiceInstance();
+ if (model != null) {
+ return Optional.of(model.getServiceType());
+ }
+ } catch (Exception e) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e);
+ }
+ return Optional.empty();
+ }
-} \ No newline at end of file
+}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java
index 279957ca1e..4d4b7c9ad2 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java
@@ -29,7 +29,6 @@ import java.util.TreeSet;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
@@ -74,493 +73,524 @@ import org.springframework.stereotype.Component;
@Component
public class AAICreateTasks {
- private static final Logger logger = LoggerFactory.getLogger(AAICreateTasks.class);
- private static final String networkTypeProvider = "PROVIDER";
- private static String NETWORK_COLLECTION_NAME = "networkCollectionName";
- private static String CONTRAIL_NETWORK_POLICY_FQDN_LIST = "contrailNetworkPolicyFqdnList";
- private static String HEAT_STACK_ID = "heatStackId";
- private static String NETWORK_POLICY_FQDN_PARAM = "network-policy-fqdn";
- @Autowired
- private AAIServiceInstanceResources aaiSIResources;
- @Autowired
- private AAIVnfResources aaiVnfResources;
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private AAIVolumeGroupResources aaiVolumeGroupResources;
- @Autowired
- private AAIVfModuleResources aaiVfModuleResources;
- @Autowired
- private AAINetworkResources aaiNetworkResources;
- @Autowired
- private AAIVpnBindingResources aaiVpnBindingResources;
- @Autowired
- private AAIConfigurationResources aaiConfigurationResources;
- @Autowired
- private AAIInstanceGroupResources aaiInstanceGroupResources;
- @Autowired
- private Environment env;
-
- public void createServiceInstance(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Customer customer = execution.getGeneralBuildingBlock().getCustomer();
- aaiSIResources.createServiceInstance(serviceInstance, customer);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void createServiceSubscription(BuildingBlockExecution execution){
- try{
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution,
- ResourceKey.SERVICE_INSTANCE_ID);
+ private static final Logger logger = LoggerFactory.getLogger(AAICreateTasks.class);
+ private static final String networkTypeProvider = "PROVIDER";
+ private static String NETWORK_COLLECTION_NAME = "networkCollectionName";
+ private static String CONTRAIL_NETWORK_POLICY_FQDN_LIST = "contrailNetworkPolicyFqdnList";
+ private static String HEAT_STACK_ID = "heatStackId";
+ private static String NETWORK_POLICY_FQDN_PARAM = "network-policy-fqdn";
+ @Autowired
+ private AAIServiceInstanceResources aaiSIResources;
+ @Autowired
+ private AAIVnfResources aaiVnfResources;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private AAIVolumeGroupResources aaiVolumeGroupResources;
+ @Autowired
+ private AAIVfModuleResources aaiVfModuleResources;
+ @Autowired
+ private AAINetworkResources aaiNetworkResources;
+ @Autowired
+ private AAIVpnBindingResources aaiVpnBindingResources;
+ @Autowired
+ private AAIConfigurationResources aaiConfigurationResources;
+ @Autowired
+ private AAIInstanceGroupResources aaiInstanceGroupResources;
+ @Autowired
+ private Environment env;
+
+ public void createServiceInstance(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Customer customer = execution.getGeneralBuildingBlock().getCustomer();
+ aaiSIResources.createServiceInstance(serviceInstance, customer);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void createServiceSubscription(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
Customer customer = execution.getGeneralBuildingBlock().getCustomer();
if (null == customer) {
- String errorMessage = "Exception in creating ServiceSubscription. Customer not present for ServiceInstanceID: "
- + serviceInstance.getServiceInstanceId();
- logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), errorMessage, "BPMN",
- ErrorCode.UnknownError.getValue(), errorMessage);
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, errorMessage);
+ String errorMessage =
+ "Exception in creating ServiceSubscription. Customer not present for ServiceInstanceID: "
+ + serviceInstance.getServiceInstanceId();
+ logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), errorMessage, "BPMN",
+ ErrorCode.UnknownError.getValue(), errorMessage);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, errorMessage);
}
aaiSIResources.createServiceSubscription(customer);
} catch (BpmnError ex) {
throw ex;
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
}
- catch (Exception ex) {
+ }
+
+ public void createProject(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Project project = serviceInstance.getProject();
+ if (project != null) {
+ if (project.getProjectName() == null || "".equals(project.getProjectName())) {
+ logger.info("ProjectName is null in input. Skipping create project...");
+ } else {
+ aaiSIResources.createProjectandConnectServiceInstance(project, serviceInstance);
+ }
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void createOwningEntity(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ OwningEntity owningEntity = serviceInstance.getOwningEntity();
+ String owningEntityId = owningEntity.getOwningEntityId();
+ String owningEntityName = owningEntity.getOwningEntityName();
+ if (owningEntityId == null || "".equals(owningEntityId)) {
+ String msg = "Exception in AAICreateOwningEntity. OwningEntityId is null.";
+ execution.setVariable("ErrorCreateOEAAI", msg);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ } else {
+ if (aaiSIResources.existsOwningEntity(owningEntity)) {
+ aaiSIResources.connectOwningEntityandServiceInstance(owningEntity, serviceInstance);
+ } else {
+ if (owningEntityName == null || "".equals(owningEntityName)) {
+ String msg =
+ "Exception in AAICreateOwningEntity. Can't create an owningEntity with no owningEntityName.";
+ logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
+ ErrorCode.UnknownError.getValue(), msg);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ } else {
+ if (aaiSIResources.existsOwningEntityName(owningEntityName)) {
+ String msg =
+ "Exception in AAICreateOwningEntity. Can't create OwningEntity as name already exists in AAI associated with a different owning-entity-id (name must be unique)";
+ logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg,
+ "BPMN", ErrorCode.UnknownError.getValue(), msg);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ } else {
+ aaiSIResources.createOwningEntityandConnectServiceInstance(owningEntity, serviceInstance);
+ }
+ }
+ }
+ }
+ } catch (Exception ex) {
exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
}
}
- public void createProject(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Project project = serviceInstance.getProject();
- if(project != null) {
- if (project.getProjectName() == null || "".equals(project.getProjectName())) {
- logger.info("ProjectName is null in input. Skipping create project...");
- } else {
- aaiSIResources.createProjectandConnectServiceInstance(project, serviceInstance);
- }
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void createOwningEntity(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- OwningEntity owningEntity = serviceInstance.getOwningEntity();
- String owningEntityId = owningEntity.getOwningEntityId();
- String owningEntityName = owningEntity.getOwningEntityName();
- if (owningEntityId == null || "".equals(owningEntityId)) {
- String msg = "Exception in AAICreateOwningEntity. OwningEntityId is null.";
- execution.setVariable("ErrorCreateOEAAI", msg);
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
- } else {
- if (aaiSIResources.existsOwningEntity(owningEntity)) {
- aaiSIResources.connectOwningEntityandServiceInstance(owningEntity, serviceInstance);
- } else {
- if (owningEntityName == null || "".equals(owningEntityName)) {
- String msg = "Exception in AAICreateOwningEntity. Can't create an owningEntity with no owningEntityName.";
- logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
- ErrorCode.UnknownError.getValue(), msg);
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
- } else {
- if(aaiSIResources.existsOwningEntityName(owningEntityName)){
- String msg = "Exception in AAICreateOwningEntity. Can't create OwningEntity as name already exists in AAI associated with a different owning-entity-id (name must be unique)";
- logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
- ErrorCode.UnknownError.getValue(), msg);
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
- }else{
- aaiSIResources.createOwningEntityandConnectServiceInstance(owningEntity, serviceInstance);
- }
- }
- }
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void createVnf(BuildingBlockExecution execution) {
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- execution.setVariable("callHoming", Boolean.TRUE.equals(vnf.isCallHoming()));
- aaiVnfResources.createVnfandConnectServiceInstance(vnf, serviceInstance);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void createPlatform(BuildingBlockExecution execution) {
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- Platform platform = vnf.getPlatform();
- if(platform != null) {
- if (platform.getPlatformName() == null || "".equals(platform.getPlatformName())) {
- logger.debug("PlatformName is null in input. Skipping create platform...");
- } else {
- List<String> platforms = splitCDL(platform.getPlatformName());
- platforms.stream().forEach(platformName -> aaiVnfResources.createPlatformandConnectVnf(new Platform(platformName),vnf));
- }
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
-
- }
-
- public List<String> splitCDL(String str){
- return Stream.of(str.split(","))
- .map(String::trim)
- .map (elem -> new String(elem))
- .collect(Collectors.toList());
- }
-
- public void createLineOfBusiness(BuildingBlockExecution execution) {
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- LineOfBusiness lineOfBusiness = vnf.getLineOfBusiness();
- if(lineOfBusiness != null) {
- if (lineOfBusiness.getLineOfBusinessName() == null || "".equals(lineOfBusiness.getLineOfBusinessName())) {
- logger.info("lineOfBusiness is null in input. Skipping create lineOfBusiness...");
- } else {
- List<String> lineOfBussinesses = splitCDL(lineOfBusiness.getLineOfBusinessName());
- lineOfBussinesses.stream().forEach(lobName -> aaiVnfResources.createLineOfBusinessandConnectVnf(new LineOfBusiness(lobName),vnf));
- }
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void createVolumeGroup(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
-
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- aaiVolumeGroupResources.createVolumeGroup(volumeGroup, cloudRegion);
- aaiVolumeGroupResources.connectVolumeGroupToVnf(genericVnf, volumeGroup, cloudRegion);
- aaiVolumeGroupResources.connectVolumeGroupToTenant(volumeGroup,cloudRegion);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void createVfModule(BuildingBlockExecution execution) {
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- int moduleIndex = 0;
- if (vfModule.getModelInfoVfModule() != null && !Boolean.TRUE.equals(vfModule.getModelInfoVfModule().getIsBaseBoolean())) {
- moduleIndex = this.getLowestUnusedVfModuleIndexFromAAIVnfResponse(vnf, vfModule);
- }
- vfModule.setModuleIndex(moduleIndex);
- aaiVfModuleResources.createVfModule(vfModule, vnf);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to establish relationships in AAI
- * @param execution
- * @throws Exception
- */
- public void connectVfModuleToVolumeGroup(BuildingBlockExecution execution) {
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- VolumeGroup volumeGroup = null;
- try{
- volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- } catch (BBObjectNotFoundException e){
- logger.info("VolumeGroup not found. Skipping Connect between VfModule and VolumeGroup");
- }
- if (volumeGroup != null) {
- aaiVfModuleResources.connectVfModuleToVolumeGroup(vnf, vfModule, volumeGroup, execution.getGeneralBuildingBlock().getCloudRegion());
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to execute Create L3Network operation (PUT )in AAI
- * @param execution
- * @throws Exception
- */
- public void createNetwork(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- //set default to false. ToBe updated by SDNC
- l3network.setIsBoundToVpn(false);
- //define is bound to vpn flag as true if NEUTRON_NETWORK_TYPE is PROVIDER
- if (l3network.getModelInfoNetwork().getNeutronNetworkType().equalsIgnoreCase(networkTypeProvider))
- l3network.setIsBoundToVpn(true);
- //put network shell in AAI
- aaiNetworkResources.createNetworkConnectToServiceInstance(l3network, serviceInstance);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
- public void createCustomer(BuildingBlockExecution execution) throws Exception {
- try {
- Customer customer = execution.getGeneralBuildingBlock().getCustomer();
-
- aaiVpnBindingResources.createCustomer(customer);
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to execute NetworkCollection operation (PUT) in AAI
- * @param execution
- * @throws Exception
- */
- public void createNetworkCollection(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Collection networkCollection = serviceInstance.getCollection();
- //pass name generated for NetworkCollection/NetworkCollectionInstanceGroup in previous step of the BB flow
- //put shell in AAI
- networkCollection.setName(execution.getVariable(NETWORK_COLLECTION_NAME));
- aaiNetworkResources.createNetworkCollection(networkCollection);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to execute NetworkCollectionInstanceGroup operation (PUT) in AAI
- * @param execution
- * @throws Exception
- */
- public void createNetworkCollectionInstanceGroup(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- InstanceGroup instanceGroup = serviceInstance.getCollection().getInstanceGroup();
- //set name generated for NetworkCollection/NetworkCollectionInstanceGroup in previous step of the BB flow
- instanceGroup.setInstanceGroupName(execution.getVariable(NETWORK_COLLECTION_NAME));
- //put shell in AAI
- aaiNetworkResources.createNetworkInstanceGroup(instanceGroup);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
-
- /**
- * BPMN access method to establish relationships in AAI
- * @param execution
- * @throws Exception
- */
- public void connectNetworkToTenant(BuildingBlockExecution execution) {
- try {
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- aaiNetworkResources.connectNetworkToTenant(l3network, execution.getGeneralBuildingBlock().getCloudRegion());
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to establish relationships in AAI
- * @param execution
- * @throws Exception
- */
- public void connectNetworkToCloudRegion(BuildingBlockExecution execution) {
- try {
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- aaiNetworkResources.connectNetworkToCloudRegion(l3network, execution.getGeneralBuildingBlock().getCloudRegion());
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to establish relationships in AAI
- * @param execution
- * @throws Exception
- */
- public void connectVnfToCloudRegion(BuildingBlockExecution execution) {
- try {
- boolean cloudRegionsToSkip = false;
- String[] cloudRegions = env.getProperty("mso.bpmn.cloudRegionIdsToSkipAddingVnfEdgesTo", String[].class);
- if (cloudRegions != null){
- cloudRegionsToSkip = Arrays.stream(cloudRegions).anyMatch(execution.getGeneralBuildingBlock().getCloudRegion().getLcpCloudRegionId()::equals);
- }
- if(!cloudRegionsToSkip) {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVnfResources.connectVnfToCloudRegion(vnf, execution.getGeneralBuildingBlock().getCloudRegion());
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to establish relationships in AAI
- * @param execution
- * @throws Exception
- */
- public void connectVnfToTenant(BuildingBlockExecution execution) {
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVnfResources.connectVnfToTenant(vnf, execution.getGeneralBuildingBlock().getCloudRegion());
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to establish relationships in AAI
- * @param execution
- * @throws Exception
- */
- public void connectNetworkToNetworkCollectionServiceInstance(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- aaiNetworkResources.connectNetworkToNetworkCollectionServiceInstance(l3network, serviceInstance);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to establish relationships in AAI
- * @param execution
- * @throws Exception
- */
- public void connectNetworkToNetworkCollectionInstanceGroup(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- //connect network only if Instance Group / Collection objects exist
- if (serviceInstance.getCollection() != null && serviceInstance.getCollection().getInstanceGroup() != null)
- aaiNetworkResources.connectNetworkToNetworkCollectionInstanceGroup(l3network, serviceInstance.getCollection().getInstanceGroup());
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void createConfiguration(BuildingBlockExecution execution){
- try{
- Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
- aaiConfigurationResources.createConfiguration(configuration);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void createInstanceGroupVnf(BuildingBlockExecution execution){
- try{
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID);
- aaiInstanceGroupResources.createInstanceGroupandConnectServiceInstance(instanceGroup, serviceInstance);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void createNetworkPolicies(BuildingBlockExecution execution) {
- try{
- String fqdns = execution.getVariable(CONTRAIL_NETWORK_POLICY_FQDN_LIST);
- if (fqdns != null && !fqdns.isEmpty()) {
- String fqdnList[] = fqdns.split(",");
- int fqdnCount = fqdnList.length;
- if (fqdnCount > 0) {
- for (int i=0; i < fqdnCount; i++) {
- String fqdn = fqdnList[i];
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY);
- uri.queryParam(NETWORK_POLICY_FQDN_PARAM, fqdn);
- Optional<org.onap.aai.domain.yang.NetworkPolicy> oNetPolicy = aaiNetworkResources.getNetworkPolicy(uri);
- if(!oNetPolicy.isPresent()) {
- logger.debug("This network policy FQDN is not in AAI yet: {}", fqdn);
- String networkPolicyId = UUID.randomUUID().toString();
- logger.debug("Adding network-policy with network-policy-id {}", networkPolicyId);
- NetworkPolicy networkPolicy = new NetworkPolicy();
- networkPolicy.setNetworkPolicyId(networkPolicyId);
- networkPolicy.setNetworkPolicyFqdn(fqdn);
- networkPolicy.setHeatStackId(execution.getVariable(HEAT_STACK_ID));
-
- aaiNetworkResources.createNetworkPolicy(networkPolicy);
- }
- }
- }
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * Groups existing vf modules by the model uuid of our new vf module and returns the lowest unused index
- *
- * if we have a module type A, and there are 3 instances of those,
- * and then module type B has 2 instances, if we are adding a new module type A,
- * the vf-module-index should be 3 assuming contiguous indices (not 5, or 2)
- *
- */
- protected int getLowestUnusedVfModuleIndexFromAAIVnfResponse(GenericVnf genericVnf, VfModule newVfModule) {
-
- String newVfModuleModelInvariantUUID = null;
- if (newVfModule.getModelInfoVfModule() != null) {
- newVfModuleModelInvariantUUID = newVfModule.getModelInfoVfModule().getModelInvariantUUID();
- }
-
-
- if (genericVnf != null && genericVnf.getVfModules() != null && !genericVnf.getVfModules().isEmpty()) {
- List<VfModule> modules = genericVnf.getVfModules().stream().filter(item -> !item.getVfModuleId().equals(newVfModule.getVfModuleId())).collect(Collectors.toList());
- TreeSet<Integer> moduleIndices = new TreeSet<>();
- int nullIndexFound = 0;
- for (VfModule vfModule : modules) {
- if (vfModule.getModelInfoVfModule() != null) {
- if (vfModule.getModelInfoVfModule().getModelInvariantUUID().equals(newVfModuleModelInvariantUUID)) {
- if (vfModule.getModuleIndex() != null) {
- moduleIndices.add(vfModule.getModuleIndex());
- } else {
- nullIndexFound++;
- logger.warn("Found null index for vf-module-id {} and model-invariant-uuid {}", vfModule.getVfModuleId(), vfModule.getModelInfoVfModule().getModelInvariantUUID());
- }
- }
- }
- }
-
- return calculateUnusedIndex(moduleIndices, nullIndexFound);
- } else {
- return 0;
- }
- }
-
- protected int calculateUnusedIndex(TreeSet<Integer> moduleIndices, int nullIndexFound) {
- //pad array with nulls
- Integer[] temp = new Integer[moduleIndices.size() + nullIndexFound];
- Integer[] array = moduleIndices.toArray(temp);
- int result = 0;
- //when a null is found skip that potential value
- //effectively creates something like, [0,1,3,null,null] -> [0,1,null(2),3,null(4)]
- for (int i=0; i < array.length; i++, result++) {
- if (Integer.valueOf(result) != array[i]) {
- if (nullIndexFound > 0) {
- nullIndexFound--;
- i--;
- } else {
- break;
- }
- }
- }
-
- return result;
- }
+ public void createVnf(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ execution.setVariable("callHoming", Boolean.TRUE.equals(vnf.isCallHoming()));
+ aaiVnfResources.createVnfandConnectServiceInstance(vnf, serviceInstance);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void createPlatform(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ Platform platform = vnf.getPlatform();
+ if (platform != null) {
+ if (platform.getPlatformName() == null || "".equals(platform.getPlatformName())) {
+ logger.debug("PlatformName is null in input. Skipping create platform...");
+ } else {
+ List<String> platforms = splitCDL(platform.getPlatformName());
+ platforms.stream().forEach(platformName -> aaiVnfResources
+ .createPlatformandConnectVnf(new Platform(platformName), vnf));
+ }
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+
+ }
+
+ public List<String> splitCDL(String str) {
+ return Stream.of(str.split(",")).map(String::trim).map(elem -> new String(elem)).collect(Collectors.toList());
+ }
+
+ public void createLineOfBusiness(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ LineOfBusiness lineOfBusiness = vnf.getLineOfBusiness();
+ if (lineOfBusiness != null) {
+ if (lineOfBusiness.getLineOfBusinessName() == null
+ || "".equals(lineOfBusiness.getLineOfBusinessName())) {
+ logger.info("lineOfBusiness is null in input. Skipping create lineOfBusiness...");
+ } else {
+ List<String> lineOfBussinesses = splitCDL(lineOfBusiness.getLineOfBusinessName());
+ lineOfBussinesses.stream().forEach(lobName -> aaiVnfResources
+ .createLineOfBusinessandConnectVnf(new LineOfBusiness(lobName), vnf));
+ }
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void createVolumeGroup(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ aaiVolumeGroupResources.createVolumeGroup(volumeGroup, cloudRegion);
+ aaiVolumeGroupResources.connectVolumeGroupToVnf(genericVnf, volumeGroup, cloudRegion);
+ aaiVolumeGroupResources.connectVolumeGroupToTenant(volumeGroup, cloudRegion);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void createVfModule(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ int moduleIndex = 0;
+ if (vfModule.getModelInfoVfModule() != null
+ && !Boolean.TRUE.equals(vfModule.getModelInfoVfModule().getIsBaseBoolean())) {
+ moduleIndex = this.getLowestUnusedVfModuleIndexFromAAIVnfResponse(vnf, vfModule);
+ }
+ vfModule.setModuleIndex(moduleIndex);
+ aaiVfModuleResources.createVfModule(vfModule, vnf);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to establish relationships in AAI
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void connectVfModuleToVolumeGroup(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ VolumeGroup volumeGroup = null;
+ try {
+ volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ } catch (BBObjectNotFoundException e) {
+ logger.info("VolumeGroup not found. Skipping Connect between VfModule and VolumeGroup");
+ }
+ if (volumeGroup != null) {
+ aaiVfModuleResources.connectVfModuleToVolumeGroup(vnf, vfModule, volumeGroup,
+ execution.getGeneralBuildingBlock().getCloudRegion());
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to execute Create L3Network operation (PUT )in AAI
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void createNetwork(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ // set default to false. ToBe updated by SDNC
+ l3network.setIsBoundToVpn(false);
+ // define is bound to vpn flag as true if NEUTRON_NETWORK_TYPE is PROVIDER
+ if (l3network.getModelInfoNetwork().getNeutronNetworkType().equalsIgnoreCase(networkTypeProvider))
+ l3network.setIsBoundToVpn(true);
+ // put network shell in AAI
+ aaiNetworkResources.createNetworkConnectToServiceInstance(l3network, serviceInstance);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void createCustomer(BuildingBlockExecution execution) throws Exception {
+ try {
+ Customer customer = execution.getGeneralBuildingBlock().getCustomer();
+
+ aaiVpnBindingResources.createCustomer(customer);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to execute NetworkCollection operation (PUT) in AAI
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void createNetworkCollection(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Collection networkCollection = serviceInstance.getCollection();
+ // pass name generated for NetworkCollection/NetworkCollectionInstanceGroup in previous step of the BB flow
+ // put shell in AAI
+ networkCollection.setName(execution.getVariable(NETWORK_COLLECTION_NAME));
+ aaiNetworkResources.createNetworkCollection(networkCollection);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to execute NetworkCollectionInstanceGroup operation (PUT) in AAI
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void createNetworkCollectionInstanceGroup(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ InstanceGroup instanceGroup = serviceInstance.getCollection().getInstanceGroup();
+ // set name generated for NetworkCollection/NetworkCollectionInstanceGroup in previous step of the BB flow
+ instanceGroup.setInstanceGroupName(execution.getVariable(NETWORK_COLLECTION_NAME));
+ // put shell in AAI
+ aaiNetworkResources.createNetworkInstanceGroup(instanceGroup);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+
+ /**
+ * BPMN access method to establish relationships in AAI
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void connectNetworkToTenant(BuildingBlockExecution execution) {
+ try {
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ aaiNetworkResources.connectNetworkToTenant(l3network, execution.getGeneralBuildingBlock().getCloudRegion());
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to establish relationships in AAI
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void connectNetworkToCloudRegion(BuildingBlockExecution execution) {
+ try {
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ aaiNetworkResources.connectNetworkToCloudRegion(l3network,
+ execution.getGeneralBuildingBlock().getCloudRegion());
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to establish relationships in AAI
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void connectVnfToCloudRegion(BuildingBlockExecution execution) {
+ try {
+ boolean cloudRegionsToSkip = false;
+ String[] cloudRegions = env.getProperty("mso.bpmn.cloudRegionIdsToSkipAddingVnfEdgesTo", String[].class);
+ if (cloudRegions != null) {
+ cloudRegionsToSkip = Arrays.stream(cloudRegions)
+ .anyMatch(execution.getGeneralBuildingBlock().getCloudRegion().getLcpCloudRegionId()::equals);
+ }
+ if (!cloudRegionsToSkip) {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVnfResources.connectVnfToCloudRegion(vnf, execution.getGeneralBuildingBlock().getCloudRegion());
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to establish relationships in AAI
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void connectVnfToTenant(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVnfResources.connectVnfToTenant(vnf, execution.getGeneralBuildingBlock().getCloudRegion());
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to establish relationships in AAI
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void connectNetworkToNetworkCollectionServiceInstance(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ aaiNetworkResources.connectNetworkToNetworkCollectionServiceInstance(l3network, serviceInstance);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to establish relationships in AAI
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void connectNetworkToNetworkCollectionInstanceGroup(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ // connect network only if Instance Group / Collection objects exist
+ if (serviceInstance.getCollection() != null && serviceInstance.getCollection().getInstanceGroup() != null)
+ aaiNetworkResources.connectNetworkToNetworkCollectionInstanceGroup(l3network,
+ serviceInstance.getCollection().getInstanceGroup());
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void createConfiguration(BuildingBlockExecution execution) {
+ try {
+ Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
+ aaiConfigurationResources.createConfiguration(configuration);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void createInstanceGroupVnf(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID);
+ aaiInstanceGroupResources.createInstanceGroupandConnectServiceInstance(instanceGroup, serviceInstance);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void createNetworkPolicies(BuildingBlockExecution execution) {
+ try {
+ String fqdns = execution.getVariable(CONTRAIL_NETWORK_POLICY_FQDN_LIST);
+ if (fqdns != null && !fqdns.isEmpty()) {
+ String fqdnList[] = fqdns.split(",");
+ int fqdnCount = fqdnList.length;
+ if (fqdnCount > 0) {
+ for (int i = 0; i < fqdnCount; i++) {
+ String fqdn = fqdnList[i];
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY);
+ uri.queryParam(NETWORK_POLICY_FQDN_PARAM, fqdn);
+ Optional<org.onap.aai.domain.yang.NetworkPolicy> oNetPolicy =
+ aaiNetworkResources.getNetworkPolicy(uri);
+ if (!oNetPolicy.isPresent()) {
+ logger.debug("This network policy FQDN is not in AAI yet: {}", fqdn);
+ String networkPolicyId = UUID.randomUUID().toString();
+ logger.debug("Adding network-policy with network-policy-id {}", networkPolicyId);
+ NetworkPolicy networkPolicy = new NetworkPolicy();
+ networkPolicy.setNetworkPolicyId(networkPolicyId);
+ networkPolicy.setNetworkPolicyFqdn(fqdn);
+ networkPolicy.setHeatStackId(execution.getVariable(HEAT_STACK_ID));
+
+ aaiNetworkResources.createNetworkPolicy(networkPolicy);
+ }
+ }
+ }
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * Groups existing vf modules by the model uuid of our new vf module and returns the lowest unused index
+ *
+ * if we have a module type A, and there are 3 instances of those, and then module type B has 2 instances, if we are
+ * adding a new module type A, the vf-module-index should be 3 assuming contiguous indices (not 5, or 2)
+ *
+ */
+ protected int getLowestUnusedVfModuleIndexFromAAIVnfResponse(GenericVnf genericVnf, VfModule newVfModule) {
+
+ String newVfModuleModelInvariantUUID = null;
+ if (newVfModule.getModelInfoVfModule() != null) {
+ newVfModuleModelInvariantUUID = newVfModule.getModelInfoVfModule().getModelInvariantUUID();
+ }
+
+
+ if (genericVnf != null && genericVnf.getVfModules() != null && !genericVnf.getVfModules().isEmpty()) {
+ List<VfModule> modules = genericVnf.getVfModules().stream()
+ .filter(item -> !item.getVfModuleId().equals(newVfModule.getVfModuleId()))
+ .collect(Collectors.toList());
+ TreeSet<Integer> moduleIndices = new TreeSet<>();
+ int nullIndexFound = 0;
+ for (VfModule vfModule : modules) {
+ if (vfModule.getModelInfoVfModule() != null) {
+ if (vfModule.getModelInfoVfModule().getModelInvariantUUID().equals(newVfModuleModelInvariantUUID)) {
+ if (vfModule.getModuleIndex() != null) {
+ moduleIndices.add(vfModule.getModuleIndex());
+ } else {
+ nullIndexFound++;
+ logger.warn("Found null index for vf-module-id {} and model-invariant-uuid {}",
+ vfModule.getVfModuleId(), vfModule.getModelInfoVfModule().getModelInvariantUUID());
+ }
+ }
+ }
+ }
+
+ return calculateUnusedIndex(moduleIndices, nullIndexFound);
+ } else {
+ return 0;
+ }
+ }
+
+ protected int calculateUnusedIndex(TreeSet<Integer> moduleIndices, int nullIndexFound) {
+ // pad array with nulls
+ Integer[] temp = new Integer[moduleIndices.size() + nullIndexFound];
+ Integer[] array = moduleIndices.toArray(temp);
+ int result = 0;
+ // when a null is found skip that potential value
+ // effectively creates something like, [0,1,3,null,null] -> [0,1,null(2),3,null(4)]
+ for (int i = 0; i < array.length; i++, result++) {
+ if (Integer.valueOf(result) != array[i]) {
+ if (nullIndexFound > 0) {
+ nullIndexFound--;
+ i--;
+ } else {
+ break;
+ }
+ }
+ }
+
+ return result;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasks.java
index 095fd7f86d..28186528e4 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasks.java
@@ -25,7 +25,6 @@ package org.onap.so.bpmn.infrastructure.aai.tasks;
import java.util.List;
import java.util.Optional;
-
import org.onap.aai.domain.yang.NetworkPolicies;
import org.onap.aai.domain.yang.NetworkPolicy;
import org.onap.so.bpmn.common.BuildingBlockExecution;
@@ -57,151 +56,151 @@ import org.springframework.stereotype.Component;
@Component
public class AAIDeleteTasks {
- private static final Logger logger = LoggerFactory.getLogger(AAIDeleteTasks.class);
-
- private static String CONTRAIL_NETWORK_POLICY_FQDN_LIST = "contrailNetworkPolicyFqdnList";
- private static String NETWORK_POLICY_FQDN_PARAM = "network-policy-fqdn";
-
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private AAIServiceInstanceResources aaiSIResources;
- @Autowired
- private AAIVnfResources aaiVnfResources;
- @Autowired
- private AAIVfModuleResources aaiVfModuleResources;
- @Autowired
- private AAINetworkResources aaiNetworkResources;
- @Autowired
- private AAIVolumeGroupResources aaiVolumeGroupResources;
- @Autowired
- private AAIConfigurationResources aaiConfigurationResources;
- @Autowired
- private AAIInstanceGroupResources aaiInstanceGroupResources;
-
- public void deleteVfModule(BuildingBlockExecution execution) throws Exception {
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
-
- execution.setVariable("aaiVfModuleRollback", false);
- try {
- aaiVfModuleResources.deleteVfModule(vfModule, genericVnf);
- execution.setVariable("aaiVfModuleRollback", true);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void deleteVnf(BuildingBlockExecution execution) throws Exception {
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
-
- execution.setVariable("aaiVnfRollback", false);
- try {
- aaiVnfResources.deleteVnf(genericVnf);
- execution.setVariable("aaiVnfRollback", true);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void deleteServiceInstance(BuildingBlockExecution execution) throws Exception {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- aaiSIResources.deleteServiceInstance(serviceInstance);
- }
- catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
-
- }
-
- public void deleteNetwork(BuildingBlockExecution execution) throws Exception {
- try {
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- aaiNetworkResources.deleteNetwork(l3network);
- execution.setVariable("isRollbackNeeded", true);
- }
- catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void deleteCollection(BuildingBlockExecution execution) throws Exception {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- aaiNetworkResources.deleteCollection(serviceInstance.getCollection());
- }
- catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void deleteInstanceGroup(BuildingBlockExecution execution) throws Exception {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- aaiNetworkResources.deleteNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup());
- }
- catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void deleteVolumeGroup(BuildingBlockExecution execution) {
- try {
- VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- CloudRegion cloudRegion = execution.getGeneralBuildingBlock().getCloudRegion();
- aaiVolumeGroupResources.deleteVolumeGroup(volumeGroup, cloudRegion);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
- public void deleteConfiguration(BuildingBlockExecution execution) {
- try {
- Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
- aaiConfigurationResources.deleteConfiguration(configuration);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void deleteInstanceGroupVnf(BuildingBlockExecution execution) {
- try {
- InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID);
- aaiInstanceGroupResources.deleteInstanceGroup(instanceGroup);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void deleteNetworkPolicies(BuildingBlockExecution execution) {
- try{
- String fqdns = execution.getVariable(CONTRAIL_NETWORK_POLICY_FQDN_LIST);
- if (fqdns != null && !fqdns.isEmpty()) {
- String fqdnList[] = fqdns.split(",");
- int fqdnCount = fqdnList.length;
- if (fqdnCount > 0) {
- for (int i=0; i < fqdnCount; i++) {
- String fqdn = fqdnList[i];
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY);
- uri.queryParam(NETWORK_POLICY_FQDN_PARAM, fqdn);
- Optional<NetworkPolicies> oNetPolicies = aaiNetworkResources.getNetworkPolicies(uri);
- if(oNetPolicies.isPresent()) {
- NetworkPolicies networkPolicies = oNetPolicies.get();
- List<NetworkPolicy> networkPolicyList = networkPolicies.getNetworkPolicy();
- if (networkPolicyList != null && !networkPolicyList.isEmpty()) {
- NetworkPolicy networkPolicy = networkPolicyList.get(0);
- String networkPolicyId = networkPolicy.getNetworkPolicyId();
- logger.debug("Deleting network-policy with network-policy-id {}", networkPolicyId);
- aaiNetworkResources.deleteNetworkPolicy(networkPolicyId);
- }
- }
- }
- }
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(AAIDeleteTasks.class);
+
+ private static String CONTRAIL_NETWORK_POLICY_FQDN_LIST = "contrailNetworkPolicyFqdnList";
+ private static String NETWORK_POLICY_FQDN_PARAM = "network-policy-fqdn";
+
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private AAIServiceInstanceResources aaiSIResources;
+ @Autowired
+ private AAIVnfResources aaiVnfResources;
+ @Autowired
+ private AAIVfModuleResources aaiVfModuleResources;
+ @Autowired
+ private AAINetworkResources aaiNetworkResources;
+ @Autowired
+ private AAIVolumeGroupResources aaiVolumeGroupResources;
+ @Autowired
+ private AAIConfigurationResources aaiConfigurationResources;
+ @Autowired
+ private AAIInstanceGroupResources aaiInstanceGroupResources;
+
+ public void deleteVfModule(BuildingBlockExecution execution) throws Exception {
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+
+ execution.setVariable("aaiVfModuleRollback", false);
+ try {
+ aaiVfModuleResources.deleteVfModule(vfModule, genericVnf);
+ execution.setVariable("aaiVfModuleRollback", true);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void deleteVnf(BuildingBlockExecution execution) throws Exception {
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+
+ execution.setVariable("aaiVnfRollback", false);
+ try {
+ aaiVnfResources.deleteVnf(genericVnf);
+ execution.setVariable("aaiVnfRollback", true);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void deleteServiceInstance(BuildingBlockExecution execution) throws Exception {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ aaiSIResources.deleteServiceInstance(serviceInstance);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+
+ }
+
+ public void deleteNetwork(BuildingBlockExecution execution) throws Exception {
+ try {
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ aaiNetworkResources.deleteNetwork(l3network);
+ execution.setVariable("isRollbackNeeded", true);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void deleteCollection(BuildingBlockExecution execution) throws Exception {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ aaiNetworkResources.deleteCollection(serviceInstance.getCollection());
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void deleteInstanceGroup(BuildingBlockExecution execution) throws Exception {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ aaiNetworkResources.deleteNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup());
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void deleteVolumeGroup(BuildingBlockExecution execution) {
+ try {
+ VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ CloudRegion cloudRegion = execution.getGeneralBuildingBlock().getCloudRegion();
+ aaiVolumeGroupResources.deleteVolumeGroup(volumeGroup, cloudRegion);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void deleteConfiguration(BuildingBlockExecution execution) {
+ try {
+ Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
+ aaiConfigurationResources.deleteConfiguration(configuration);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void deleteInstanceGroupVnf(BuildingBlockExecution execution) {
+ try {
+ InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID);
+ aaiInstanceGroupResources.deleteInstanceGroup(instanceGroup);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void deleteNetworkPolicies(BuildingBlockExecution execution) {
+ try {
+ String fqdns = execution.getVariable(CONTRAIL_NETWORK_POLICY_FQDN_LIST);
+ if (fqdns != null && !fqdns.isEmpty()) {
+ String fqdnList[] = fqdns.split(",");
+ int fqdnCount = fqdnList.length;
+ if (fqdnCount > 0) {
+ for (int i = 0; i < fqdnCount; i++) {
+ String fqdn = fqdnList[i];
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY);
+ uri.queryParam(NETWORK_POLICY_FQDN_PARAM, fqdn);
+ Optional<NetworkPolicies> oNetPolicies = aaiNetworkResources.getNetworkPolicies(uri);
+ if (oNetPolicies.isPresent()) {
+ NetworkPolicies networkPolicies = oNetPolicies.get();
+ List<NetworkPolicy> networkPolicyList = networkPolicies.getNetworkPolicy();
+ if (networkPolicyList != null && !networkPolicyList.isEmpty()) {
+ NetworkPolicy networkPolicy = networkPolicyList.get(0);
+ String networkPolicyId = networkPolicy.getNetworkPolicyId();
+ logger.debug("Deleting network-policy with network-policy-id {}", networkPolicyId);
+ aaiNetworkResources.deleteNetworkPolicy(networkPolicyId);
+ }
+ }
+ }
+ }
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIFlagTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIFlagTasks.java
index 177e09d5a1..12aade71bc 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIFlagTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIFlagTasks.java
@@ -35,83 +35,83 @@ import org.springframework.stereotype.Component;
@Component
public class AAIFlagTasks {
- private static final Logger logger = LoggerFactory.getLogger(AAIFlagTasks.class);
-
- @Autowired
- private AAIVnfResources aaiVnfResources;
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
-
- public void checkVnfInMaintFlag(BuildingBlockExecution execution) {
- boolean inMaint = false;
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- String vnfId = vnf.getVnfId();
- inMaint = aaiVnfResources.checkInMaintFlag(vnfId);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- if (inMaint) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "VNF is in maintenance in A&AI");
- }
- }
-
- public void modifyVnfInMaintFlag(BuildingBlockExecution execution, boolean inMaint) {
- try {
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ private static final Logger logger = LoggerFactory.getLogger(AAIFlagTasks.class);
- GenericVnf copiedGenericVnf = genericVnf.shallowCopyId();
+ @Autowired
+ private AAIVnfResources aaiVnfResources;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
- copiedGenericVnf.setInMaint(inMaint);
- genericVnf.setInMaint(inMaint);
+ public void checkVnfInMaintFlag(BuildingBlockExecution execution) {
+ boolean inMaint = false;
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ String vnfId = vnf.getVnfId();
+ inMaint = aaiVnfResources.checkInMaintFlag(vnfId);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ if (inMaint) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "VNF is in maintenance in A&AI");
+ }
+ }
- aaiVnfResources.updateObjectVnf(copiedGenericVnf);
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void checkVnfClosedLoopDisabledFlag(BuildingBlockExecution execution) {
- boolean isClosedLoopDisabled = false;
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- String vnfId = vnf.getVnfId();
- isClosedLoopDisabled = aaiVnfResources.checkVnfClosedLoopDisabledFlag(vnfId);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- if (isClosedLoopDisabled) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "VNF Close Loop Disabled in A&AI");
- }
- }
-
- public void modifyVnfClosedLoopDisabledFlag(BuildingBlockExecution execution, boolean closedLoopDisabled) {
- try {
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ public void modifyVnfInMaintFlag(BuildingBlockExecution execution, boolean inMaint) {
+ try {
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- GenericVnf copiedGenericVnf = genericVnf.shallowCopyId();
- copiedGenericVnf.setClosedLoopDisabled(closedLoopDisabled);
- genericVnf.setClosedLoopDisabled(closedLoopDisabled);
+ GenericVnf copiedGenericVnf = genericVnf.shallowCopyId();
- aaiVnfResources.updateObjectVnf(copiedGenericVnf);
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void checkVnfPserversLockedFlag(BuildingBlockExecution execution) {
- boolean inPserversLocked = false;
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- String vnfId = vnf.getVnfId();
- inPserversLocked = aaiVnfResources.checkVnfPserversLockedFlag(vnfId);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- if (inPserversLocked) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "VNF PServers in Locked in A&AI");
- }
- }
+ copiedGenericVnf.setInMaint(inMaint);
+ genericVnf.setInMaint(inMaint);
+
+ aaiVnfResources.updateObjectVnf(copiedGenericVnf);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void checkVnfClosedLoopDisabledFlag(BuildingBlockExecution execution) {
+ boolean isClosedLoopDisabled = false;
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ String vnfId = vnf.getVnfId();
+ isClosedLoopDisabled = aaiVnfResources.checkVnfClosedLoopDisabledFlag(vnfId);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ if (isClosedLoopDisabled) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "VNF Close Loop Disabled in A&AI");
+ }
+ }
+
+ public void modifyVnfClosedLoopDisabledFlag(BuildingBlockExecution execution, boolean closedLoopDisabled) {
+ try {
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+
+ GenericVnf copiedGenericVnf = genericVnf.shallowCopyId();
+ copiedGenericVnf.setClosedLoopDisabled(closedLoopDisabled);
+ genericVnf.setClosedLoopDisabled(closedLoopDisabled);
+
+ aaiVnfResources.updateObjectVnf(copiedGenericVnf);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void checkVnfPserversLockedFlag(BuildingBlockExecution execution) {
+ boolean inPserversLocked = false;
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ String vnfId = vnf.getVnfId();
+ inPserversLocked = aaiVnfResources.checkVnfPserversLockedFlag(vnfId);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ if (inPserversLocked) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "VNF PServers in Locked in A&AI");
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIQueryTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIQueryTasks.java
index e0e139e290..7668c6b00f 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIQueryTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIQueryTasks.java
@@ -25,7 +25,6 @@ package org.onap.so.bpmn.infrastructure.aai.tasks;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-
import org.modelmapper.ModelMapper;
import org.modelmapper.PropertyMap;
import org.onap.aai.domain.yang.NetworkPolicy;
@@ -52,197 +51,209 @@ import org.springframework.stereotype.Component;
@Component
public class AAIQueryTasks {
- private static final Logger logger = LoggerFactory.getLogger(AAIQueryTasks.class);
- private static final String ERROR_MSG = "No relationships were returned from AAIResultWrapper.getRelationships()";
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private AAINetworkResources aaiNetworkResources;
- private static final ModelMapper modelMapper = new ModelMapper();
-
- /**
- * BPMN access method to query data for VPN bindings from the AAI result wrapper.
- * The resulting VPN bindings are mapped to the corresponding bbobject and placed in the customer bbobject
- *
- * @param execution
- */
-
- public void queryNetworkVpnBinding(BuildingBlockExecution execution) {
- try {
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
- Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships();
- if (!networkRelationships.isPresent()) {
- throw (new Exception(ERROR_MSG));
- }
- List<AAIResourceUri> netBindingsUriList = networkRelationships.get().getRelatedAAIUris(AAIObjectType.VPN_BINDING);
-
- List<org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding> mappedVpnBindings = new ArrayList<>();
- if(netBindingsUriList != null && !netBindingsUriList.isEmpty()) {
- for(AAIResourceUri netBindingUri : netBindingsUriList) {
- Optional<VpnBinding> oVpnBinding = aaiNetworkResources.getVpnBinding(netBindingUri);
- if(oVpnBinding.isPresent()) {
- org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding mappedVpnBinding =
- modelMapper.map(oVpnBinding.get(), org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding.class);
- if (oVpnBinding.get().getRouteTargets() != null){
- mappedVpnBinding.getRouteTargets().addAll(mapRouteTargets(oVpnBinding.get().getRouteTargets().getRouteTarget()));
- mappedVpnBindings.add(mappedVpnBinding);
- }
- }
- }
- }
- execution.getGeneralBuildingBlock().getCustomer().getVpnBindings().addAll(mappedVpnBindings);
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to extract VPN Binding data from AAI result and populate proper fields into CreateNetworkRequest
- */
- public void getNetworkVpnBinding(BuildingBlockExecution execution) {
-
- try {
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
- CreateNetworkRequest createNetworkRequest = execution.getVariable("createNetworkRequest");
-
- Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships();
- if (!networkRelationships.isPresent()) {
- throw (new Exception(ERROR_MSG));
- }
- List<AAIResourceUri> netBindingsUriList = networkRelationships.get()
- .getRelatedAAIUris(AAIObjectType.VPN_BINDING);
- List<org.onap.so.openstack.beans.RouteTarget> routeTargets = new ArrayList<>();
- for (AAIResourceUri netBindingUri : netBindingsUriList) {
- logger.info("Get Route Targests");
- Optional<VpnBinding> oVpnBinding = aaiNetworkResources.getVpnBinding(netBindingUri);
- if (oVpnBinding.isPresent()) {
- VpnBinding vpnBinding = oVpnBinding.get();
- RouteTargets rts = vpnBinding.getRouteTargets();
- if (rts != null) {
- List<org.onap.aai.domain.yang.RouteTarget> rtList = rts.getRouteTarget();
- if (!rtList.isEmpty()) {
- PropertyMap<org.onap.aai.domain.yang.RouteTarget, org.onap.so.openstack.beans.RouteTarget> personMap = new PropertyMap<org.onap.aai.domain.yang.RouteTarget, org.onap.so.openstack.beans.RouteTarget>() {
- @Override
- protected void configure() {
- map().setRouteTarget(source.getGlobalRouteTarget());
- map(source.getRouteTargetRole(), destination.getRouteTargetRole());
- }
- };
- modelMapper.addMappings(personMap);
- for (org.onap.aai.domain.yang.RouteTarget rt : rtList) {
- org.onap.so.openstack.beans.RouteTarget openstackRtBean = modelMapper.map(rt,
- org.onap.so.openstack.beans.RouteTarget.class);
- routeTargets.add(openstackRtBean);
- }
- }
- }
- }
- }
- // store route targets data in execution - to be used as part of
- // Network adapter input
- createNetworkRequest.getContrailNetwork().setRouteTargets(routeTargets);
- execution.setVariable("createNetworkRequest", createNetworkRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to query data for network policies from the AAI result wrapper
- * From the resulting network policy, the network policy fqdn parameter is added to
- * the network bbobject contrail network policy fqdns list
- *
- * @param execution
- */
- public void queryNetworkPolicy(BuildingBlockExecution execution) {
- try {
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
- Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships();
- if (!networkRelationships.isPresent()) {
- throw (new Exception(ERROR_MSG));
- }
- List<AAIResourceUri> netPoliciesUriList = networkRelationships.get().getRelatedAAIUris(AAIObjectType.NETWORK_POLICY);
-
- if(!netPoliciesUriList.isEmpty()) {
- for(AAIResourceUri netPolicyUri : netPoliciesUriList) {
- Optional<NetworkPolicy> oNetPolicy = aaiNetworkResources.getNetworkPolicy(netPolicyUri);
- if(oNetPolicy.isPresent()) {
- l3network.getNetworkPolicies().add(modelMapper.map(oNetPolicy.get(), org.onap.so.bpmn.servicedecomposition.bbobjects.NetworkPolicy.class));
- }
- }
- }
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to query data for network table ref from the AAI result wrapper
- * The resulting route table reference is mapped to the corresponding bbobject and added
- * to the network bbobject contrail network route table references list
- *
- * @param execution
- */
- public void queryNetworkTableRef(BuildingBlockExecution execution) {
- try {
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
- Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships();
- if (!networkRelationships.isPresent()) {
- throw (new Exception(ERROR_MSG));
- }
- List<AAIResourceUri> routeTableUriList = networkRelationships.get().getRelatedAAIUris(AAIObjectType.ROUTE_TABLE_REFERENCE);
-
- if(!routeTableUriList.isEmpty()) {
- for(AAIResourceUri routeTableUri : routeTableUriList) {
- Optional<RouteTableReference> oRouteTableReference = aaiNetworkResources.getRouteTable(routeTableUri);
- if(oRouteTableReference.isPresent()) {
- org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTableReference mappedRouteTableReference = modelMapper.map(oRouteTableReference.get(), org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTableReference.class);
- l3network.getContrailNetworkRouteTableReferences().add(mappedRouteTableReference);
- }
- }
- }
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- private List<org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget> mapRouteTargets(List<org.onap.aai.domain.yang.RouteTarget> routeTargets) {
- List<org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget> mappedRouteTargets = new ArrayList<>();
- if(!routeTargets.isEmpty()) {
- for(org.onap.aai.domain.yang.RouteTarget routeTarget : routeTargets) {
- org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget mappedRouteTarget = modelMapper.map(routeTarget, org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget.class);
- mappedRouteTargets.add(mappedRouteTarget);
- }
- }
- return mappedRouteTargets;
- }
-
- public void querySubnet(BuildingBlockExecution execution) {
- try {
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
- Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships();
- if (!networkRelationships.isPresent()) {
- throw (new Exception(ERROR_MSG));
- }
- List<AAIResourceUri> subnetsUriList = networkRelationships.get().getRelatedAAIUris(AAIObjectType.SUBNET);
-
- if(!subnetsUriList.isEmpty()) {
- for(AAIResourceUri subnetUri : subnetsUriList) {
- Optional<Subnet> oSubnet = aaiNetworkResources.getSubnet(subnetUri);
- if(oSubnet.isPresent()) {
- l3network.getSubnets().add(modelMapper.map(oSubnet.get(), org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet.class));
- }
- }
- }
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(AAIQueryTasks.class);
+ private static final String ERROR_MSG = "No relationships were returned from AAIResultWrapper.getRelationships()";
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private AAINetworkResources aaiNetworkResources;
+ private static final ModelMapper modelMapper = new ModelMapper();
+
+ /**
+ * BPMN access method to query data for VPN bindings from the AAI result wrapper. The resulting VPN bindings are
+ * mapped to the corresponding bbobject and placed in the customer bbobject
+ *
+ * @param execution
+ */
+
+ public void queryNetworkVpnBinding(BuildingBlockExecution execution) {
+ try {
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
+ Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships();
+ if (!networkRelationships.isPresent()) {
+ throw (new Exception(ERROR_MSG));
+ }
+ List<AAIResourceUri> netBindingsUriList =
+ networkRelationships.get().getRelatedAAIUris(AAIObjectType.VPN_BINDING);
+
+ List<org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding> mappedVpnBindings = new ArrayList<>();
+ if (netBindingsUriList != null && !netBindingsUriList.isEmpty()) {
+ for (AAIResourceUri netBindingUri : netBindingsUriList) {
+ Optional<VpnBinding> oVpnBinding = aaiNetworkResources.getVpnBinding(netBindingUri);
+ if (oVpnBinding.isPresent()) {
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding mappedVpnBinding = modelMapper.map(
+ oVpnBinding.get(), org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding.class);
+ if (oVpnBinding.get().getRouteTargets() != null) {
+ mappedVpnBinding.getRouteTargets()
+ .addAll(mapRouteTargets(oVpnBinding.get().getRouteTargets().getRouteTarget()));
+ mappedVpnBindings.add(mappedVpnBinding);
+ }
+ }
+ }
+ }
+ execution.getGeneralBuildingBlock().getCustomer().getVpnBindings().addAll(mappedVpnBindings);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to extract VPN Binding data from AAI result and populate proper fields into
+ * CreateNetworkRequest
+ */
+ public void getNetworkVpnBinding(BuildingBlockExecution execution) {
+
+ try {
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
+ CreateNetworkRequest createNetworkRequest = execution.getVariable("createNetworkRequest");
+
+ Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships();
+ if (!networkRelationships.isPresent()) {
+ throw (new Exception(ERROR_MSG));
+ }
+ List<AAIResourceUri> netBindingsUriList =
+ networkRelationships.get().getRelatedAAIUris(AAIObjectType.VPN_BINDING);
+ List<org.onap.so.openstack.beans.RouteTarget> routeTargets = new ArrayList<>();
+ for (AAIResourceUri netBindingUri : netBindingsUriList) {
+ logger.info("Get Route Targests");
+ Optional<VpnBinding> oVpnBinding = aaiNetworkResources.getVpnBinding(netBindingUri);
+ if (oVpnBinding.isPresent()) {
+ VpnBinding vpnBinding = oVpnBinding.get();
+ RouteTargets rts = vpnBinding.getRouteTargets();
+ if (rts != null) {
+ List<org.onap.aai.domain.yang.RouteTarget> rtList = rts.getRouteTarget();
+ if (!rtList.isEmpty()) {
+ PropertyMap<org.onap.aai.domain.yang.RouteTarget, org.onap.so.openstack.beans.RouteTarget> personMap =
+ new PropertyMap<org.onap.aai.domain.yang.RouteTarget, org.onap.so.openstack.beans.RouteTarget>() {
+ @Override
+ protected void configure() {
+ map().setRouteTarget(source.getGlobalRouteTarget());
+ map(source.getRouteTargetRole(), destination.getRouteTargetRole());
+ }
+ };
+ modelMapper.addMappings(personMap);
+ for (org.onap.aai.domain.yang.RouteTarget rt : rtList) {
+ org.onap.so.openstack.beans.RouteTarget openstackRtBean =
+ modelMapper.map(rt, org.onap.so.openstack.beans.RouteTarget.class);
+ routeTargets.add(openstackRtBean);
+ }
+ }
+ }
+ }
+ }
+ // store route targets data in execution - to be used as part of
+ // Network adapter input
+ createNetworkRequest.getContrailNetwork().setRouteTargets(routeTargets);
+ execution.setVariable("createNetworkRequest", createNetworkRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to query data for network policies from the AAI result wrapper From the resulting network
+ * policy, the network policy fqdn parameter is added to the network bbobject contrail network policy fqdns list
+ *
+ * @param execution
+ */
+ public void queryNetworkPolicy(BuildingBlockExecution execution) {
+ try {
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
+ Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships();
+ if (!networkRelationships.isPresent()) {
+ throw (new Exception(ERROR_MSG));
+ }
+ List<AAIResourceUri> netPoliciesUriList =
+ networkRelationships.get().getRelatedAAIUris(AAIObjectType.NETWORK_POLICY);
+
+ if (!netPoliciesUriList.isEmpty()) {
+ for (AAIResourceUri netPolicyUri : netPoliciesUriList) {
+ Optional<NetworkPolicy> oNetPolicy = aaiNetworkResources.getNetworkPolicy(netPolicyUri);
+ if (oNetPolicy.isPresent()) {
+ l3network.getNetworkPolicies().add(modelMapper.map(oNetPolicy.get(),
+ org.onap.so.bpmn.servicedecomposition.bbobjects.NetworkPolicy.class));
+ }
+ }
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to query data for network table ref from the AAI result wrapper The resulting route table
+ * reference is mapped to the corresponding bbobject and added to the network bbobject contrail network route table
+ * references list
+ *
+ * @param execution
+ */
+ public void queryNetworkTableRef(BuildingBlockExecution execution) {
+ try {
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
+ Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships();
+ if (!networkRelationships.isPresent()) {
+ throw (new Exception(ERROR_MSG));
+ }
+ List<AAIResourceUri> routeTableUriList =
+ networkRelationships.get().getRelatedAAIUris(AAIObjectType.ROUTE_TABLE_REFERENCE);
+
+ if (!routeTableUriList.isEmpty()) {
+ for (AAIResourceUri routeTableUri : routeTableUriList) {
+ Optional<RouteTableReference> oRouteTableReference =
+ aaiNetworkResources.getRouteTable(routeTableUri);
+ if (oRouteTableReference.isPresent()) {
+ org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTableReference mappedRouteTableReference =
+ modelMapper.map(oRouteTableReference.get(),
+ org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTableReference.class);
+ l3network.getContrailNetworkRouteTableReferences().add(mappedRouteTableReference);
+ }
+ }
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ private List<org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget> mapRouteTargets(
+ List<org.onap.aai.domain.yang.RouteTarget> routeTargets) {
+ List<org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget> mappedRouteTargets = new ArrayList<>();
+ if (!routeTargets.isEmpty()) {
+ for (org.onap.aai.domain.yang.RouteTarget routeTarget : routeTargets) {
+ org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget mappedRouteTarget =
+ modelMapper.map(routeTarget, org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget.class);
+ mappedRouteTargets.add(mappedRouteTarget);
+ }
+ }
+ return mappedRouteTargets;
+ }
+
+ public void querySubnet(BuildingBlockExecution execution) {
+ try {
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
+ Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships();
+ if (!networkRelationships.isPresent()) {
+ throw (new Exception(ERROR_MSG));
+ }
+ List<AAIResourceUri> subnetsUriList = networkRelationships.get().getRelatedAAIUris(AAIObjectType.SUBNET);
+
+ if (!subnetsUriList.isEmpty()) {
+ for (AAIResourceUri subnetUri : subnetsUriList) {
+ Optional<Subnet> oSubnet = aaiNetworkResources.getSubnet(subnetUri);
+ if (oSubnet.isPresent()) {
+ l3network.getSubnets().add(modelMapper.map(oSubnet.get(),
+ org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet.class));
+ }
+ }
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java
index 82b61c17b5..3304d1b113 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java
@@ -24,7 +24,6 @@ package org.onap.so.bpmn.infrastructure.aai.tasks;
import java.util.List;
import java.util.Map;
-
import org.onap.so.adapters.nwrest.CreateNetworkResponse;
import org.onap.so.adapters.nwrest.UpdateNetworkResponse;
import org.onap.so.bpmn.common.BuildingBlockExecution;
@@ -57,507 +56,526 @@ import org.springframework.stereotype.Component;
@Component
public class AAIUpdateTasks {
- private static final Logger logger = LoggerFactory.getLogger(AAIUpdateTasks.class);
- private static final String ALACARTE = "aLaCarte";
- private static final String MULTI_STAGE_DESIGN_OFF = "false";
- private static final String MULTI_STAGE_DESIGN_ON = "true";
- @Autowired
- private AAIServiceInstanceResources aaiServiceInstanceResources;
- @Autowired
- private AAIVnfResources aaiVnfResources;
- @Autowired
- private AAIVfModuleResources aaiVfModuleResources;
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private AAIVolumeGroupResources aaiVolumeGroupResources;
- @Autowired
- private AAINetworkResources aaiNetworkResources;
- @Autowired
- private AAICollectionResources aaiCollectionResources;
- @Autowired
- private AAIConfigurationResources aaiConfigurationResources;
-
- public void updateOrchestrationStatusAssignedService(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- aaiServiceInstanceResources.updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ASSIGNED);
- execution.setVariable("aaiServiceInstanceRollback", true);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusActiveService(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- aaiServiceInstanceResources.updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ACTIVE);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusAssignedVnf(BuildingBlockExecution execution) {
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVnfResources.updateOrchestrationStatusVnf(vnf,OrchestrationStatus.ASSIGNED);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusActiveVnf(BuildingBlockExecution execution) {
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVnfResources.updateOrchestrationStatusVnf(vnf,OrchestrationStatus.ACTIVE);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusAssignedVolumeGroup(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
-
- VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- volumeGroup.setHeatStackId("");
- aaiVolumeGroupResources.updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.ASSIGNED);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusActiveVolumeGroup(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
-
- VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
-
- aaiVolumeGroupResources.updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.ACTIVE);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusCreatedVolumeGroup(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
-
- VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
-
- aaiVolumeGroupResources.updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.CREATED);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateHeatStackIdVolumeGroup(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- String heatStackId = execution.getVariable("heatStackId");
- if (heatStackId == null) {
- heatStackId = "";
- }
- VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- volumeGroup.setHeatStackId(heatStackId);
-
- aaiVolumeGroupResources.updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusAssignedVfModule(BuildingBlockExecution execution) {
- try {
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- vfModule.setHeatStackId("");
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule,vnf,OrchestrationStatus.ASSIGNED);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusPendingActivationVfModule(BuildingBlockExecution execution) {
- try {
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule,vnf,OrchestrationStatus.PENDING_ACTIVATION);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusAssignedOrPendingActivationVfModule(BuildingBlockExecution execution) {
- try {
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- vfModule.setHeatStackId("");
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- String multiStageDesign = MULTI_STAGE_DESIGN_OFF;
- if (vnf.getModelInfoGenericVnf() != null) {
- multiStageDesign = vnf.getModelInfoGenericVnf().getMultiStageDesign();
- }
- boolean aLaCarte = (boolean) execution.getVariable(ALACARTE);
- if (aLaCarte && multiStageDesign != null && multiStageDesign.equalsIgnoreCase(MULTI_STAGE_DESIGN_ON)) {
- aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule,vnf,OrchestrationStatus.PENDING_ACTIVATION);
- }
- else {
- aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule,vnf,OrchestrationStatus.ASSIGNED);
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusCreatedVfModule(BuildingBlockExecution execution) {
- try {
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule,vnf,OrchestrationStatus.CREATED);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusDeactivateVfModule(BuildingBlockExecution execution) {
- execution.setVariable("aaiDeactivateVfModuleRollback", false);
- try {
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule,vnf,OrchestrationStatus.CREATED);
- execution.setVariable("aaiDeactivateVfModuleRollback", true);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to update status of L3Network to Assigned in AAI
- * @param execution
- * @throws BBObjectNotFoundException
- */
- public void updateOrchestrationStatusAssignedNetwork(BuildingBlockExecution execution) {
- updateNetwork(execution, OrchestrationStatus.ASSIGNED);
- }
-
- /**
- * BPMN access method to update status of L3Network to Active in AAI
- * @param execution
- * @throws BBObjectNotFoundException
- */
- public void updateOrchestrationStatusActiveNetwork(BuildingBlockExecution execution) {
- updateNetwork(execution, OrchestrationStatus.ACTIVE);
- }
-
- /**
- * BPMN access method to update status of L3Network to Created in AAI
- * @param execution
- * @throws BBObjectNotFoundException
- */
- public void updateOrchestrationStatusCreatedNetwork(BuildingBlockExecution execution) {
- updateNetwork(execution, OrchestrationStatus.CREATED);
- }
-
- protected void updateNetwork(BuildingBlockExecution execution, OrchestrationStatus status) {
- try {
- L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- updateNetworkAAI(l3Network, status);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- protected void updateNetworkAAI(L3Network l3Network, OrchestrationStatus status) {
- L3Network copiedl3Network = l3Network.shallowCopyId();
-
- copiedl3Network.setOrchestrationStatus(status);
- l3Network.setOrchestrationStatus(status);
- aaiNetworkResources.updateNetwork(copiedl3Network);
-
- List<Subnet> subnets = l3Network.getSubnets();
- if (subnets != null){
- for (Subnet subnet : subnets){
- Subnet copiedSubnet = subnet.shallowCopyId();
- copiedSubnet.setOrchestrationStatus(status);
- aaiNetworkResources.updateSubnet(copiedl3Network, copiedSubnet);
- }
- }
- }
-
- /**
- * BPMN access method to update status of L3Network Collection to Active in AAI
- * @param execution
- * @throws BBObjectNotFoundException
- */
- public void updateOrchestrationStatusActiveNetworkCollection(BuildingBlockExecution execution) {
- execution.setVariable("aaiNetworkCollectionActivateRollback", false);
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Collection networkCollection = serviceInstance.getCollection();
- Collection copiedNetworkCollection = networkCollection.shallowCopyId();
-
- networkCollection.setOrchestrationStatus(OrchestrationStatus.ACTIVE);
- copiedNetworkCollection.setOrchestrationStatus(OrchestrationStatus.ACTIVE);
- aaiCollectionResources.updateCollection(copiedNetworkCollection);
- execution.setVariable("aaiNetworkCollectionActivateRollback", true);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusActivateVfModule(BuildingBlockExecution execution) {
- execution.setVariable("aaiActivateVfModuleRollback", false);
- try {
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule, vnf, OrchestrationStatus.ACTIVE);
- execution.setVariable("aaiActivateVfModuleRollback", true);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateHeatStackIdVfModule(BuildingBlockExecution execution) {
- try {
- String heatStackId = execution.getVariable("heatStackId");
- if (heatStackId == null) {
- heatStackId = "";
- }
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- vfModule.setHeatStackId(heatStackId);
- aaiVfModuleResources.updateHeatStackIdVfModule(vfModule, vnf);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to update L3Network after it was created in cloud
- * @param execution
- * @throws Exception
- */
- public void updateNetworkCreated(BuildingBlockExecution execution) throws Exception {
- execution.setVariable("aaiNetworkActivateRollback", false);
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- L3Network copiedl3network = l3network.shallowCopyId();
- CreateNetworkResponse response = execution.getVariable("createNetworkResponse");
- try {
- if(response.getNetworkFqdn()!=null){
- l3network.setContrailNetworkFqdn(response.getNetworkFqdn());
- }
- l3network.setOrchestrationStatus(OrchestrationStatus.CREATED);
- l3network.setHeatStackId(response.getNetworkStackId());
- l3network.setNeutronNetworkId(response.getNeutronNetworkId());
-
- copiedl3network.setContrailNetworkFqdn(response.getNetworkFqdn());
- copiedl3network.setOrchestrationStatus(OrchestrationStatus.CREATED);
- copiedl3network.setHeatStackId(response.getNetworkStackId());
- copiedl3network.setNeutronNetworkId(response.getNeutronNetworkId());
-
- aaiNetworkResources.updateNetwork(copiedl3network);
-
- Map<String, String> subnetMap = response.getSubnetMap();
- List<Subnet> subnets = l3network.getSubnets();
- if (subnets != null && subnetMap != null){
- for (Subnet subnet: subnets){
- Subnet copiedSubnet = subnet.shallowCopyId();
- copiedSubnet.setNeutronSubnetId(subnetMap.get(copiedSubnet.getSubnetId()));
- copiedSubnet.setOrchestrationStatus(OrchestrationStatus.CREATED);
- aaiNetworkResources.updateSubnet(copiedl3network, copiedSubnet);
- }
- }
-
- execution.setVariable("aaiNetworkActivateRollback", true);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to update L3Network after it was updated in cloud
- * @param execution
- * @throws Exception
- */
- public void updateNetworkUpdated(BuildingBlockExecution execution) throws Exception {
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- L3Network copiedl3network = l3network.shallowCopyId();
- UpdateNetworkResponse response = execution.getVariable("updateNetworkResponse");
- try {
- copiedl3network.setNeutronNetworkId(response.getNeutronNetworkId());
- aaiNetworkResources.updateNetwork(copiedl3network);
-
- Map<String, String> subnetMap = response.getSubnetMap();
- List<Subnet> subnets = l3network.getSubnets();
- if (subnets != null && subnetMap != null){
- for (Subnet subnet: subnets){
- Subnet copiedSubnet = subnet.shallowCopyId();
- copiedSubnet.setNeutronSubnetId(subnetMap.get(copiedSubnet.getSubnetId()));
- copiedSubnet.setOrchestrationStatus(OrchestrationStatus.CREATED);
- aaiNetworkResources.updateSubnet(copiedl3network, copiedSubnet);
- }
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateObjectNetwork(BuildingBlockExecution execution) {
- try {
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- aaiNetworkResources.updateNetwork(l3network);
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to update ServiceInstance
- * @param execution
- */
- public void updateServiceInstance(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- aaiServiceInstanceResources.updateServiceInstance(serviceInstance);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateObjectVnf(BuildingBlockExecution execution) {
- try {
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVnfResources.updateObjectVnf(genericVnf);
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusDeleteVfModule(BuildingBlockExecution execution) {
- execution.setVariable("aaiDeleteVfModuleRollback", false);
- try {
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- vfModule.setHeatStackId("");
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
-
- VfModule copiedVfModule = vfModule.shallowCopyId();
- copiedVfModule.setHeatStackId("");
- aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule,vnf,OrchestrationStatus.ASSIGNED);
- execution.setVariable("aaiDeleteVfModuleRollback", true);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateModelVfModule(BuildingBlockExecution execution) {
- try {
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVfModuleResources.changeAssignVfModule(vfModule, vnf);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
- public void updateOrchestrationStatusActivateFabricConfiguration(BuildingBlockExecution execution) {
- try {
- Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
- aaiConfigurationResources.updateOrchestrationStatusConfiguration(configuration, OrchestrationStatus.ACTIVE);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusDeactivateFabricConfiguration(BuildingBlockExecution execution) {
- try {
- Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
- aaiConfigurationResources.updateOrchestrationStatusConfiguration(configuration, OrchestrationStatus.ASSIGNED);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateIpv4OamAddressVnf(BuildingBlockExecution execution) {
- try {
- String ipv4OamAddress = execution.getVariable("oamManagementV4Address");
- if (ipv4OamAddress != null) {
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- GenericVnf copiedGenericVnf = genericVnf.shallowCopyId();
-
- genericVnf.setIpv4OamAddress(ipv4OamAddress);
- copiedGenericVnf.setIpv4OamAddress(ipv4OamAddress);
-
- aaiVnfResources.updateObjectVnf(copiedGenericVnf);
- }
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateManagementV6AddressVnf(BuildingBlockExecution execution) {
- try {
- String managementV6Address = execution.getVariable("oamManagementV6Address");
- if (managementV6Address != null) {
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- GenericVnf copiedGenericVnf = genericVnf.shallowCopyId();
-
- genericVnf.setManagementV6Address(managementV6Address);
- copiedGenericVnf.setManagementV6Address(managementV6Address);
-
- aaiVnfResources.updateObjectVnf(copiedGenericVnf);
- }
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateContrailServiceInstanceFqdnVfModule(BuildingBlockExecution execution) {
- try {
- String contrailServiceInstanceFqdn = execution.getVariable("contrailServiceInstanceFqdn");
- if (contrailServiceInstanceFqdn != null) {
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- vfModule.setContrailServiceInstanceFqdn(contrailServiceInstanceFqdn);
- aaiVfModuleResources.updateContrailServiceInstanceFqdnVfModule(vfModule, vnf);
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStatusConfigAssignedVnf(BuildingBlockExecution execution) {
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVnfResources.updateOrchestrationStatusVnf(vnf, OrchestrationStatus.CONFIGASSIGNED);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void updateOrchestrationStausConfigDeployConfigureVnf(BuildingBlockExecution execution){
- try{
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVnfResources.updateOrchestrationStatusVnf(vnf, OrchestrationStatus.CONFIGURE);
-
- }catch(Exception ex){
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
-
- }
-
- public void updateOrchestrationStausConfigDeployConfiguredVnf(BuildingBlockExecution execution){
- try{
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- aaiVnfResources.updateOrchestrationStatusVnf(vnf, OrchestrationStatus.CONFIGURED);
-
- }catch(Exception ex){
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
-
- }
+ private static final Logger logger = LoggerFactory.getLogger(AAIUpdateTasks.class);
+ private static final String ALACARTE = "aLaCarte";
+ private static final String MULTI_STAGE_DESIGN_OFF = "false";
+ private static final String MULTI_STAGE_DESIGN_ON = "true";
+ @Autowired
+ private AAIServiceInstanceResources aaiServiceInstanceResources;
+ @Autowired
+ private AAIVnfResources aaiVnfResources;
+ @Autowired
+ private AAIVfModuleResources aaiVfModuleResources;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private AAIVolumeGroupResources aaiVolumeGroupResources;
+ @Autowired
+ private AAINetworkResources aaiNetworkResources;
+ @Autowired
+ private AAICollectionResources aaiCollectionResources;
+ @Autowired
+ private AAIConfigurationResources aaiConfigurationResources;
+
+ public void updateOrchestrationStatusAssignedService(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ aaiServiceInstanceResources.updateOrchestrationStatusServiceInstance(serviceInstance,
+ OrchestrationStatus.ASSIGNED);
+ execution.setVariable("aaiServiceInstanceRollback", true);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusActiveService(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ aaiServiceInstanceResources.updateOrchestrationStatusServiceInstance(serviceInstance,
+ OrchestrationStatus.ACTIVE);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusAssignedVnf(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVnfResources.updateOrchestrationStatusVnf(vnf, OrchestrationStatus.ASSIGNED);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusActiveVnf(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVnfResources.updateOrchestrationStatusVnf(vnf, OrchestrationStatus.ACTIVE);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusAssignedVolumeGroup(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ volumeGroup.setHeatStackId("");
+ aaiVolumeGroupResources.updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion,
+ OrchestrationStatus.ASSIGNED);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusActiveVolumeGroup(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+
+ aaiVolumeGroupResources.updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion,
+ OrchestrationStatus.ACTIVE);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusCreatedVolumeGroup(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+
+ aaiVolumeGroupResources.updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion,
+ OrchestrationStatus.CREATED);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateHeatStackIdVolumeGroup(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ String heatStackId = execution.getVariable("heatStackId");
+ if (heatStackId == null) {
+ heatStackId = "";
+ }
+ VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ volumeGroup.setHeatStackId(heatStackId);
+
+ aaiVolumeGroupResources.updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusAssignedVfModule(BuildingBlockExecution execution) {
+ try {
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ vfModule.setHeatStackId("");
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule, vnf, OrchestrationStatus.ASSIGNED);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusPendingActivationVfModule(BuildingBlockExecution execution) {
+ try {
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule, vnf,
+ OrchestrationStatus.PENDING_ACTIVATION);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusAssignedOrPendingActivationVfModule(BuildingBlockExecution execution) {
+ try {
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ vfModule.setHeatStackId("");
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ String multiStageDesign = MULTI_STAGE_DESIGN_OFF;
+ if (vnf.getModelInfoGenericVnf() != null) {
+ multiStageDesign = vnf.getModelInfoGenericVnf().getMultiStageDesign();
+ }
+ boolean aLaCarte = (boolean) execution.getVariable(ALACARTE);
+ if (aLaCarte && multiStageDesign != null && multiStageDesign.equalsIgnoreCase(MULTI_STAGE_DESIGN_ON)) {
+ aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule, vnf,
+ OrchestrationStatus.PENDING_ACTIVATION);
+ } else {
+ aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule, vnf, OrchestrationStatus.ASSIGNED);
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusCreatedVfModule(BuildingBlockExecution execution) {
+ try {
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule, vnf, OrchestrationStatus.CREATED);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusDeactivateVfModule(BuildingBlockExecution execution) {
+ execution.setVariable("aaiDeactivateVfModuleRollback", false);
+ try {
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule, vnf, OrchestrationStatus.CREATED);
+ execution.setVariable("aaiDeactivateVfModuleRollback", true);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to update status of L3Network to Assigned in AAI
+ *
+ * @param execution
+ * @throws BBObjectNotFoundException
+ */
+ public void updateOrchestrationStatusAssignedNetwork(BuildingBlockExecution execution) {
+ updateNetwork(execution, OrchestrationStatus.ASSIGNED);
+ }
+
+ /**
+ * BPMN access method to update status of L3Network to Active in AAI
+ *
+ * @param execution
+ * @throws BBObjectNotFoundException
+ */
+ public void updateOrchestrationStatusActiveNetwork(BuildingBlockExecution execution) {
+ updateNetwork(execution, OrchestrationStatus.ACTIVE);
+ }
+
+ /**
+ * BPMN access method to update status of L3Network to Created in AAI
+ *
+ * @param execution
+ * @throws BBObjectNotFoundException
+ */
+ public void updateOrchestrationStatusCreatedNetwork(BuildingBlockExecution execution) {
+ updateNetwork(execution, OrchestrationStatus.CREATED);
+ }
+
+ protected void updateNetwork(BuildingBlockExecution execution, OrchestrationStatus status) {
+ try {
+ L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ updateNetworkAAI(l3Network, status);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ protected void updateNetworkAAI(L3Network l3Network, OrchestrationStatus status) {
+ L3Network copiedl3Network = l3Network.shallowCopyId();
+
+ copiedl3Network.setOrchestrationStatus(status);
+ l3Network.setOrchestrationStatus(status);
+ aaiNetworkResources.updateNetwork(copiedl3Network);
+
+ List<Subnet> subnets = l3Network.getSubnets();
+ if (subnets != null) {
+ for (Subnet subnet : subnets) {
+ Subnet copiedSubnet = subnet.shallowCopyId();
+ copiedSubnet.setOrchestrationStatus(status);
+ aaiNetworkResources.updateSubnet(copiedl3Network, copiedSubnet);
+ }
+ }
+ }
+
+ /**
+ * BPMN access method to update status of L3Network Collection to Active in AAI
+ *
+ * @param execution
+ * @throws BBObjectNotFoundException
+ */
+ public void updateOrchestrationStatusActiveNetworkCollection(BuildingBlockExecution execution) {
+ execution.setVariable("aaiNetworkCollectionActivateRollback", false);
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Collection networkCollection = serviceInstance.getCollection();
+ Collection copiedNetworkCollection = networkCollection.shallowCopyId();
+
+ networkCollection.setOrchestrationStatus(OrchestrationStatus.ACTIVE);
+ copiedNetworkCollection.setOrchestrationStatus(OrchestrationStatus.ACTIVE);
+ aaiCollectionResources.updateCollection(copiedNetworkCollection);
+ execution.setVariable("aaiNetworkCollectionActivateRollback", true);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusActivateVfModule(BuildingBlockExecution execution) {
+ execution.setVariable("aaiActivateVfModuleRollback", false);
+ try {
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule, vnf, OrchestrationStatus.ACTIVE);
+ execution.setVariable("aaiActivateVfModuleRollback", true);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateHeatStackIdVfModule(BuildingBlockExecution execution) {
+ try {
+ String heatStackId = execution.getVariable("heatStackId");
+ if (heatStackId == null) {
+ heatStackId = "";
+ }
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ vfModule.setHeatStackId(heatStackId);
+ aaiVfModuleResources.updateHeatStackIdVfModule(vfModule, vnf);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to update L3Network after it was created in cloud
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void updateNetworkCreated(BuildingBlockExecution execution) throws Exception {
+ execution.setVariable("aaiNetworkActivateRollback", false);
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ L3Network copiedl3network = l3network.shallowCopyId();
+ CreateNetworkResponse response = execution.getVariable("createNetworkResponse");
+ try {
+ if (response.getNetworkFqdn() != null) {
+ l3network.setContrailNetworkFqdn(response.getNetworkFqdn());
+ }
+ l3network.setOrchestrationStatus(OrchestrationStatus.CREATED);
+ l3network.setHeatStackId(response.getNetworkStackId());
+ l3network.setNeutronNetworkId(response.getNeutronNetworkId());
+
+ copiedl3network.setContrailNetworkFqdn(response.getNetworkFqdn());
+ copiedl3network.setOrchestrationStatus(OrchestrationStatus.CREATED);
+ copiedl3network.setHeatStackId(response.getNetworkStackId());
+ copiedl3network.setNeutronNetworkId(response.getNeutronNetworkId());
+
+ aaiNetworkResources.updateNetwork(copiedl3network);
+
+ Map<String, String> subnetMap = response.getSubnetMap();
+ List<Subnet> subnets = l3network.getSubnets();
+ if (subnets != null && subnetMap != null) {
+ for (Subnet subnet : subnets) {
+ Subnet copiedSubnet = subnet.shallowCopyId();
+ copiedSubnet.setNeutronSubnetId(subnetMap.get(copiedSubnet.getSubnetId()));
+ copiedSubnet.setOrchestrationStatus(OrchestrationStatus.CREATED);
+ aaiNetworkResources.updateSubnet(copiedl3network, copiedSubnet);
+ }
+ }
+
+ execution.setVariable("aaiNetworkActivateRollback", true);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to update L3Network after it was updated in cloud
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void updateNetworkUpdated(BuildingBlockExecution execution) throws Exception {
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ L3Network copiedl3network = l3network.shallowCopyId();
+ UpdateNetworkResponse response = execution.getVariable("updateNetworkResponse");
+ try {
+ copiedl3network.setNeutronNetworkId(response.getNeutronNetworkId());
+ aaiNetworkResources.updateNetwork(copiedl3network);
+
+ Map<String, String> subnetMap = response.getSubnetMap();
+ List<Subnet> subnets = l3network.getSubnets();
+ if (subnets != null && subnetMap != null) {
+ for (Subnet subnet : subnets) {
+ Subnet copiedSubnet = subnet.shallowCopyId();
+ copiedSubnet.setNeutronSubnetId(subnetMap.get(copiedSubnet.getSubnetId()));
+ copiedSubnet.setOrchestrationStatus(OrchestrationStatus.CREATED);
+ aaiNetworkResources.updateSubnet(copiedl3network, copiedSubnet);
+ }
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateObjectNetwork(BuildingBlockExecution execution) {
+ try {
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ aaiNetworkResources.updateNetwork(l3network);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to update ServiceInstance
+ *
+ * @param execution
+ */
+ public void updateServiceInstance(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ aaiServiceInstanceResources.updateServiceInstance(serviceInstance);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateObjectVnf(BuildingBlockExecution execution) {
+ try {
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVnfResources.updateObjectVnf(genericVnf);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusDeleteVfModule(BuildingBlockExecution execution) {
+ execution.setVariable("aaiDeleteVfModuleRollback", false);
+ try {
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ vfModule.setHeatStackId("");
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+
+ VfModule copiedVfModule = vfModule.shallowCopyId();
+ copiedVfModule.setHeatStackId("");
+ aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule, vnf, OrchestrationStatus.ASSIGNED);
+ execution.setVariable("aaiDeleteVfModuleRollback", true);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateModelVfModule(BuildingBlockExecution execution) {
+ try {
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVfModuleResources.changeAssignVfModule(vfModule, vnf);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusActivateFabricConfiguration(BuildingBlockExecution execution) {
+ try {
+ Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
+ aaiConfigurationResources.updateOrchestrationStatusConfiguration(configuration, OrchestrationStatus.ACTIVE);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusDeactivateFabricConfiguration(BuildingBlockExecution execution) {
+ try {
+ Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
+ aaiConfigurationResources.updateOrchestrationStatusConfiguration(configuration,
+ OrchestrationStatus.ASSIGNED);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateIpv4OamAddressVnf(BuildingBlockExecution execution) {
+ try {
+ String ipv4OamAddress = execution.getVariable("oamManagementV4Address");
+ if (ipv4OamAddress != null) {
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ GenericVnf copiedGenericVnf = genericVnf.shallowCopyId();
+
+ genericVnf.setIpv4OamAddress(ipv4OamAddress);
+ copiedGenericVnf.setIpv4OamAddress(ipv4OamAddress);
+
+ aaiVnfResources.updateObjectVnf(copiedGenericVnf);
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateManagementV6AddressVnf(BuildingBlockExecution execution) {
+ try {
+ String managementV6Address = execution.getVariable("oamManagementV6Address");
+ if (managementV6Address != null) {
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ GenericVnf copiedGenericVnf = genericVnf.shallowCopyId();
+
+ genericVnf.setManagementV6Address(managementV6Address);
+ copiedGenericVnf.setManagementV6Address(managementV6Address);
+
+ aaiVnfResources.updateObjectVnf(copiedGenericVnf);
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateContrailServiceInstanceFqdnVfModule(BuildingBlockExecution execution) {
+ try {
+ String contrailServiceInstanceFqdn = execution.getVariable("contrailServiceInstanceFqdn");
+ if (contrailServiceInstanceFqdn != null) {
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ vfModule.setContrailServiceInstanceFqdn(contrailServiceInstanceFqdn);
+ aaiVfModuleResources.updateContrailServiceInstanceFqdnVfModule(vfModule, vnf);
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStatusConfigAssignedVnf(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVnfResources.updateOrchestrationStatusVnf(vnf, OrchestrationStatus.CONFIGASSIGNED);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void updateOrchestrationStausConfigDeployConfigureVnf(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVnfResources.updateOrchestrationStatusVnf(vnf, OrchestrationStatus.CONFIGURE);
+
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+
+ }
+
+ public void updateOrchestrationStausConfigDeployConfiguredVnf(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ aaiVnfResources.updateOrchestrationStatusVnf(vnf, OrchestrationStatus.CONFIGURED);
+
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivity.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivity.java
index 821dfc18b0..05d4f56fdc 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivity.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivity.java
@@ -25,7 +25,6 @@ package org.onap.so.bpmn.infrastructure.activity;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
@@ -44,106 +43,107 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.databind.ObjectMapper;
@Component("ExecuteActivity")
public class ExecuteActivity implements JavaDelegate {
- private static final Logger logger = LoggerFactory.getLogger(ExecuteActivity.class);
- private static final String G_BPMN_REQUEST = "bpmnRequest";
- private static final String VNF_TYPE = "vnfType";
- private static final String G_ACTION = "requestAction";
- private static final String G_REQUEST_ID = "mso-request-id";
- private static final String VNF_ID = "vnfId";
- private static final String SERVICE_INSTANCE_ID = "serviceInstanceId";
-
- private static final String SERVICE_TASK_IMPLEMENTATION_ATTRIBUTE = "implementation";
- private static final String ACTIVITY_PREFIX = "activity:";
-
- private ObjectMapper mapper = new ObjectMapper();
-
- @Autowired
- private RuntimeService runtimeService;
- @Autowired
- private ExceptionBuilder exceptionBuilder;
-
- @Override
- public void execute(DelegateExecution execution) throws Exception {
- final String requestId = (String) execution.getVariable(G_REQUEST_ID);
-
- try {
- final String implementationString = execution.getBpmnModelElementInstance().getAttributeValue(SERVICE_TASK_IMPLEMENTATION_ATTRIBUTE);
- logger.debug("activity implementation String: {}", implementationString);
- if (!implementationString.startsWith(ACTIVITY_PREFIX)) {
- buildAndThrowException(execution, "Implementation attribute has a wrong format");
- }
- String activityName = implementationString.replaceFirst(ACTIVITY_PREFIX, "");
- logger.info("activityName is: {}", activityName);
-
- BuildingBlock buildingBlock = buildBuildingBlock(activityName);
- ExecuteBuildingBlock executeBuildingBlock = buildExecuteBuildingBlock(execution, requestId, buildingBlock);
-
- Map<String, Object> variables = new HashMap<>();
- variables.put("buildingBlock", executeBuildingBlock);
- variables.put("mso-request-id", requestId);
- variables.put("retryCount", 1);
- variables.put("aLaCarte", true);
-
- ProcessInstanceWithVariables buildingBlockResult = runtimeService.createProcessInstanceByKey("ExecuteBuildingBlock").setVariables(variables).executeWithVariablesInReturn();
- VariableMap variableMap = buildingBlockResult.getVariables();
-
- WorkflowException workflowException = (WorkflowException) variableMap.get("WorklfowException");
- if (workflowException != null) {
- logger.error("Workflow exception is: {}", workflowException.getErrorMessage());
- }
- execution.setVariable("WorkflowException", workflowException);
- }
- catch (Exception e) {
- buildAndThrowException(execution, e.getMessage());
- }
- }
-
- protected BuildingBlock buildBuildingBlock(String activityName) {
- BuildingBlock buildingBlock = new BuildingBlock();
- buildingBlock.setBpmnFlowName(activityName);
- buildingBlock.setMsoId(UUID.randomUUID().toString());
- buildingBlock.setKey("");
- buildingBlock.setIsVirtualLink(false);
- buildingBlock.setVirtualLinkKey("");
- return buildingBlock;
- }
-
- protected ExecuteBuildingBlock buildExecuteBuildingBlock(DelegateExecution execution, String requestId,
- BuildingBlock buildingBlock) throws Exception {
- ExecuteBuildingBlock executeBuildingBlock = new ExecuteBuildingBlock();
- String bpmnRequest = (String) execution.getVariable(G_BPMN_REQUEST);
- ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class);
- RequestDetails requestDetails = sIRequest.getRequestDetails();
- executeBuildingBlock.setaLaCarte(true);
- executeBuildingBlock.setRequestAction((String) execution.getVariable(G_ACTION));
- executeBuildingBlock.setResourceId((String) execution.getVariable(VNF_ID));
- executeBuildingBlock.setVnfType((String) execution.getVariable(VNF_TYPE));
- WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
- workflowResourceIds.setServiceInstanceId((String) execution.getVariable(SERVICE_INSTANCE_ID));
- workflowResourceIds.setVnfId((String) execution.getVariable(VNF_ID));
- executeBuildingBlock.setWorkflowResourceIds(workflowResourceIds);
- executeBuildingBlock.setRequestId(requestId);
- executeBuildingBlock.setBuildingBlock(buildingBlock);
- executeBuildingBlock.setRequestDetails(requestDetails);
- return executeBuildingBlock;
- }
-
- protected void buildAndThrowException(DelegateExecution execution, String msg, Exception ex) {
- logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
- ErrorCode.UnknownError.getValue(), msg, ex);
- execution.setVariable("ExecuteActivityErrorMessage", msg);
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
- }
-
- protected void buildAndThrowException(DelegateExecution execution, String msg) {
- logger.error(msg);
- execution.setVariable("ExecuteActuvityErrorMessage", msg);
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
- }
+ private static final Logger logger = LoggerFactory.getLogger(ExecuteActivity.class);
+ private static final String G_BPMN_REQUEST = "bpmnRequest";
+ private static final String VNF_TYPE = "vnfType";
+ private static final String G_ACTION = "requestAction";
+ private static final String G_REQUEST_ID = "mso-request-id";
+ private static final String VNF_ID = "vnfId";
+ private static final String SERVICE_INSTANCE_ID = "serviceInstanceId";
+
+ private static final String SERVICE_TASK_IMPLEMENTATION_ATTRIBUTE = "implementation";
+ private static final String ACTIVITY_PREFIX = "activity:";
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Autowired
+ private RuntimeService runtimeService;
+ @Autowired
+ private ExceptionBuilder exceptionBuilder;
+
+ @Override
+ public void execute(DelegateExecution execution) throws Exception {
+ final String requestId = (String) execution.getVariable(G_REQUEST_ID);
+
+ try {
+ final String implementationString =
+ execution.getBpmnModelElementInstance().getAttributeValue(SERVICE_TASK_IMPLEMENTATION_ATTRIBUTE);
+ logger.debug("activity implementation String: {}", implementationString);
+ if (!implementationString.startsWith(ACTIVITY_PREFIX)) {
+ buildAndThrowException(execution, "Implementation attribute has a wrong format");
+ }
+ String activityName = implementationString.replaceFirst(ACTIVITY_PREFIX, "");
+ logger.info("activityName is: {}", activityName);
+
+ BuildingBlock buildingBlock = buildBuildingBlock(activityName);
+ ExecuteBuildingBlock executeBuildingBlock = buildExecuteBuildingBlock(execution, requestId, buildingBlock);
+
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("buildingBlock", executeBuildingBlock);
+ variables.put("mso-request-id", requestId);
+ variables.put("retryCount", 1);
+ variables.put("aLaCarte", true);
+
+ ProcessInstanceWithVariables buildingBlockResult =
+ runtimeService.createProcessInstanceByKey("ExecuteBuildingBlock").setVariables(variables)
+ .executeWithVariablesInReturn();
+ VariableMap variableMap = buildingBlockResult.getVariables();
+
+ WorkflowException workflowException = (WorkflowException) variableMap.get("WorklfowException");
+ if (workflowException != null) {
+ logger.error("Workflow exception is: {}", workflowException.getErrorMessage());
+ }
+ execution.setVariable("WorkflowException", workflowException);
+ } catch (Exception e) {
+ buildAndThrowException(execution, e.getMessage());
+ }
+ }
+
+ protected BuildingBlock buildBuildingBlock(String activityName) {
+ BuildingBlock buildingBlock = new BuildingBlock();
+ buildingBlock.setBpmnFlowName(activityName);
+ buildingBlock.setMsoId(UUID.randomUUID().toString());
+ buildingBlock.setKey("");
+ buildingBlock.setIsVirtualLink(false);
+ buildingBlock.setVirtualLinkKey("");
+ return buildingBlock;
+ }
+
+ protected ExecuteBuildingBlock buildExecuteBuildingBlock(DelegateExecution execution, String requestId,
+ BuildingBlock buildingBlock) throws Exception {
+ ExecuteBuildingBlock executeBuildingBlock = new ExecuteBuildingBlock();
+ String bpmnRequest = (String) execution.getVariable(G_BPMN_REQUEST);
+ ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class);
+ RequestDetails requestDetails = sIRequest.getRequestDetails();
+ executeBuildingBlock.setaLaCarte(true);
+ executeBuildingBlock.setRequestAction((String) execution.getVariable(G_ACTION));
+ executeBuildingBlock.setResourceId((String) execution.getVariable(VNF_ID));
+ executeBuildingBlock.setVnfType((String) execution.getVariable(VNF_TYPE));
+ WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
+ workflowResourceIds.setServiceInstanceId((String) execution.getVariable(SERVICE_INSTANCE_ID));
+ workflowResourceIds.setVnfId((String) execution.getVariable(VNF_ID));
+ executeBuildingBlock.setWorkflowResourceIds(workflowResourceIds);
+ executeBuildingBlock.setRequestId(requestId);
+ executeBuildingBlock.setBuildingBlock(buildingBlock);
+ executeBuildingBlock.setRequestDetails(requestDetails);
+ return executeBuildingBlock;
+ }
+
+ protected void buildAndThrowException(DelegateExecution execution, String msg, Exception ex) {
+ logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
+ ErrorCode.UnknownError.getValue(), msg, ex);
+ execution.setVariable("ExecuteActivityErrorMessage", msg);
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
+
+ protected void buildAndThrowException(DelegateExecution execution, String msg) {
+ logger.error(msg);
+ execution.setVariable("ExecuteActuvityErrorMessage", msg);
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasks.java
index 67d2864204..0ec28d901c 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasks.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.infrastructure.adapter.network.tasks;
import java.util.Map;
-
import org.onap.so.adapters.nwrest.CreateNetworkRequest;
import org.onap.so.adapters.nwrest.CreateNetworkResponse;
import org.onap.so.bpmn.common.BuildingBlockExecution;
@@ -38,68 +37,74 @@ import org.springframework.stereotype.Component;
@Component
public class NetworkAdapterCreateTasks {
-
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private NetworkAdapterObjectMapper networkAdapterObjectMapper;
- @Autowired
- private NetworkAdapterResources networkAdapterResources;
-
- public void createNetwork(BuildingBlockExecution execution) {
- execution.setVariable("networkAdapterCreateRollback", false);
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
-
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
-
- Map<String, String> userInput = gBBInput.getUserInput();
- String cloudRegionPo = execution.getVariable("cloudRegionPo");
-
- CreateNetworkRequest createNetworkRequest = networkAdapterObjectMapper.createNetworkRequestMapper(gBBInput.getRequestContext(), gBBInput.getCloudRegion(), gBBInput.getOrchContext(), serviceInstance, l3Network, userInput, cloudRegionPo, gBBInput.getCustomer());
-
- execution.setVariable("networkAdapterRequest", createNetworkRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void processResponseFromOpenstack(BuildingBlockExecution execution) {
- try {
- L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
-
- CreateNetworkResponse createNetworkResponse = execution.getVariable("createNetworkResponse");
- if(createNetworkResponse != null) {
- l3Network.setHeatStackId(createNetworkResponse.getNetworkStackId());
- if (createNetworkResponse.getNetworkCreated()){
- //setting rollback TRUE only if network was actually created (not a silent success OP)
- execution.setVariable("networkAdapterCreateRollback", true);
- }
- } else {
- throw new Exception("No response was sent back from NetworkAdapterRestV1 subflow.");
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void rollbackCreateNetwork(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
-
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- CreateNetworkResponse createNetworkResponse = execution.getVariable("createNetworkResponse");
-
- Map<String, String> userInput = gBBInput.getUserInput();
- String cloudRegionPo = execution.getVariable("cloudRegionPo");
- networkAdapterResources.rollbackCreateNetwork(gBBInput.getRequestContext(), gBBInput.getCloudRegion(), gBBInput.getOrchContext(), serviceInstance, l3Network, userInput, cloudRegionPo, createNetworkResponse);
-
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private NetworkAdapterObjectMapper networkAdapterObjectMapper;
+ @Autowired
+ private NetworkAdapterResources networkAdapterResources;
+
+ public void createNetwork(BuildingBlockExecution execution) {
+ execution.setVariable("networkAdapterCreateRollback", false);
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+
+ Map<String, String> userInput = gBBInput.getUserInput();
+ String cloudRegionPo = execution.getVariable("cloudRegionPo");
+
+ CreateNetworkRequest createNetworkRequest = networkAdapterObjectMapper.createNetworkRequestMapper(
+ gBBInput.getRequestContext(), gBBInput.getCloudRegion(), gBBInput.getOrchContext(), serviceInstance,
+ l3Network, userInput, cloudRegionPo, gBBInput.getCustomer());
+
+ execution.setVariable("networkAdapterRequest", createNetworkRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void processResponseFromOpenstack(BuildingBlockExecution execution) {
+ try {
+ L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+
+ CreateNetworkResponse createNetworkResponse = execution.getVariable("createNetworkResponse");
+ if (createNetworkResponse != null) {
+ l3Network.setHeatStackId(createNetworkResponse.getNetworkStackId());
+ if (createNetworkResponse.getNetworkCreated()) {
+ // setting rollback TRUE only if network was actually created (not a silent success OP)
+ execution.setVariable("networkAdapterCreateRollback", true);
+ }
+ } else {
+ throw new Exception("No response was sent back from NetworkAdapterRestV1 subflow.");
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void rollbackCreateNetwork(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ CreateNetworkResponse createNetworkResponse = execution.getVariable("createNetworkResponse");
+
+ Map<String, String> userInput = gBBInput.getUserInput();
+ String cloudRegionPo = execution.getVariable("cloudRegionPo");
+ networkAdapterResources.rollbackCreateNetwork(gBBInput.getRequestContext(), gBBInput.getCloudRegion(),
+ gBBInput.getOrchContext(), serviceInstance, l3Network, userInput, cloudRegionPo,
+ createNetworkResponse);
+
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasks.java
index 7e0c5f6da4..7a7d681762 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasks.java
@@ -34,26 +34,28 @@ import org.springframework.stereotype.Component;
@Component
public class NetworkAdapterDeleteTasks {
-
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private NetworkAdapterObjectMapper networkAdapterObjectMapper;
- @Autowired
- private ExceptionBuilder exceptionUtil;
-
- public void deleteNetwork(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
-
- L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
-
- DeleteNetworkRequest deleteNetworkRequest = networkAdapterObjectMapper.deleteNetworkRequestMapper(gBBInput.getRequestContext(), gBBInput.getCloudRegion(), serviceInstance, l3Network);
-
- execution.setVariable("networkAdapterRequest", deleteNetworkRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private NetworkAdapterObjectMapper networkAdapterObjectMapper;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+
+ public void deleteNetwork(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+
+ DeleteNetworkRequest deleteNetworkRequest = networkAdapterObjectMapper.deleteNetworkRequestMapper(
+ gBBInput.getRequestContext(), gBBInput.getCloudRegion(), serviceInstance, l3Network);
+
+ execution.setVariable("networkAdapterRequest", deleteNetworkRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1.java
index 4861257833..859db11037 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1.java
@@ -22,12 +22,10 @@ package org.onap.so.bpmn.infrastructure.adapter.network.tasks;
import java.io.StringReader;
import java.util.Optional;
-
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.so.adapters.nwrest.CreateNetworkError;
import org.onap.so.adapters.nwrest.CreateNetworkRequest;
@@ -48,111 +46,119 @@ import org.springframework.stereotype.Component;
@Component
public class NetworkAdapterRestV1 {
- private static final Logger logger = LoggerFactory.getLogger(NetworkAdapterRestV1.class);
-
- private static final String NETWORK_REQUEST = "networkAdapterRequest";
- private static final String NETWORK_MESSAGE = "NetworkAResponse_MESSAGE";
- private static final String NETWORK_SYNC_CODE = "NETWORKREST_networkAdapterStatusCode";
- private static final String NETWORK_SYNC_RESPONSE = "NETWORKREST_networkAdapterResponse";
- private static final String NETWORK_CORRELATOR = "NetworkAResponse_CORRELATOR";
-
- @Autowired
- private ExceptionBuilder exceptionBuilder;
+ private static final Logger logger = LoggerFactory.getLogger(NetworkAdapterRestV1.class);
+
+ private static final String NETWORK_REQUEST = "networkAdapterRequest";
+ private static final String NETWORK_MESSAGE = "NetworkAResponse_MESSAGE";
+ private static final String NETWORK_SYNC_CODE = "NETWORKREST_networkAdapterStatusCode";
+ private static final String NETWORK_SYNC_RESPONSE = "NETWORKREST_networkAdapterResponse";
+ private static final String NETWORK_CORRELATOR = "NetworkAResponse_CORRELATOR";
+
+ @Autowired
+ private ExceptionBuilder exceptionBuilder;
+
+ @Autowired
+ private NetworkAdapterResources networkAdapterResources;
+
+ public void callNetworkAdapter(DelegateExecution execution) {
+ try {
+ Object networkAdapterRequest = execution.getVariable(NETWORK_REQUEST);
+ if (networkAdapterRequest != null) {
+ Optional<Response> response = Optional.empty();
+ if (networkAdapterRequest instanceof CreateNetworkRequest) {
+ CreateNetworkRequest createNetworkRequest = (CreateNetworkRequest) networkAdapterRequest;
+ execution.setVariable(NETWORK_CORRELATOR, createNetworkRequest.getMessageId());
+ response = networkAdapterResources.createNetworkAsync(createNetworkRequest);
+ } else if (networkAdapterRequest instanceof DeleteNetworkRequest) {
+ DeleteNetworkRequest deleteNetworkRequest = (DeleteNetworkRequest) networkAdapterRequest;
+ execution.setVariable(NETWORK_CORRELATOR, deleteNetworkRequest.getMessageId());
+ response = networkAdapterResources.deleteNetworkAsync(deleteNetworkRequest);
+ } else if (networkAdapterRequest instanceof UpdateNetworkRequest) {
+ UpdateNetworkRequest updateNetworkRequest = (UpdateNetworkRequest) networkAdapterRequest;
+ execution.setVariable(NETWORK_CORRELATOR, updateNetworkRequest.getMessageId());
+ response = networkAdapterResources.updateNetworkAsync(updateNetworkRequest);
+ }
+ if (response.isPresent()) {
+ String statusCode = Integer.toString(response.get().getStatus());
+ String responseString = "";
+ if (response.get().getEntity() != null) {
+ responseString = (String) response.get().getEntity();
+ }
+ execution.setVariable(NETWORK_SYNC_CODE, statusCode);
+ execution.setVariable(NETWORK_SYNC_RESPONSE, responseString);
+ } else {
+ throw new Exception("No Ack response from Openstack Adapter");
+ }
+ } else {
+ throw new Exception("No Network Request was created. networkAdapterRequest was null.");
+ }
+ } catch (Exception ex) {
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void processCallback(DelegateExecution execution) {
+ try {
+ Object networkAdapterRequest = execution.getVariable(NETWORK_REQUEST);
+ String callback = (String) execution.getVariable(NETWORK_MESSAGE);
+ String logCallbackMessage = "Callback from OpenstackAdapter: " + callback;
+ logger.debug(logCallbackMessage);
+ if (networkAdapterRequest != null) {
+ if (networkAdapterRequest instanceof CreateNetworkRequest) {
+ if (callback.contains("createNetworkError")) {
+ CreateNetworkError createNetworkError =
+ (CreateNetworkError) unmarshalXml(callback, CreateNetworkError.class);
+ throw new Exception(createNetworkError.getMessage());
+ } else {
+ CreateNetworkResponse createNetworkResponse =
+ (CreateNetworkResponse) unmarshalXml(callback, CreateNetworkResponse.class);
+ execution.setVariable("createNetworkResponse", createNetworkResponse);
+ }
+ } else if (networkAdapterRequest instanceof DeleteNetworkRequest) {
+ if (callback.contains("deleteNetworkError")) {
+ DeleteNetworkError deleteNetworkError =
+ (DeleteNetworkError) unmarshalXml(callback, DeleteNetworkError.class);
+ throw new Exception(deleteNetworkError.getMessage());
+ } else {
+ DeleteNetworkResponse deleteNetworkResponse =
+ (DeleteNetworkResponse) unmarshalXml(callback, DeleteNetworkResponse.class);
+ execution.setVariable("deleteNetworkResponse", deleteNetworkResponse);
+ }
+ } else if (networkAdapterRequest instanceof UpdateNetworkRequest) {
+ if (callback.contains("updateNetworkError")) {
+ UpdateNetworkError updateNetworkError =
+ (UpdateNetworkError) unmarshalXml(callback, UpdateNetworkError.class);
+ throw new Exception(updateNetworkError.getMessage());
+ } else {
+ UpdateNetworkResponse updateNetworkResponse =
+ (UpdateNetworkResponse) unmarshalXml(callback, UpdateNetworkResponse.class);
+ execution.setVariable("updateNetworkResponse", updateNetworkResponse);
+ }
+ }
+ }
+ } catch (Exception e) {
+ logger.error("Error in Openstack Adapter callback", e);
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, e.getMessage());
+ }
+ }
+
+ protected <T> Object unmarshalXml(String xmlString, Class<T> resultClass) throws JAXBException {
+ StringReader reader = new StringReader(xmlString);
+ JAXBContext context = JAXBContext.newInstance(resultClass);
+ Unmarshaller unmarshaller = context.createUnmarshaller();
+ return unmarshaller.unmarshal(reader);
+ }
+
+ public void handleTimeOutException(DelegateExecution execution) {
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000,
+ "Error timed out waiting on Openstack Async-Response");
+ }
- @Autowired
- private NetworkAdapterResources networkAdapterResources;
-
- public void callNetworkAdapter (DelegateExecution execution) {
- try {
- Object networkAdapterRequest = execution.getVariable(NETWORK_REQUEST);
- if (networkAdapterRequest != null) {
- Optional<Response> response = Optional.empty();
- if (networkAdapterRequest instanceof CreateNetworkRequest) {
- CreateNetworkRequest createNetworkRequest = (CreateNetworkRequest) networkAdapterRequest;
- execution.setVariable(NETWORK_CORRELATOR, createNetworkRequest.getMessageId());
- response = networkAdapterResources.createNetworkAsync(createNetworkRequest);
- } else if (networkAdapterRequest instanceof DeleteNetworkRequest) {
- DeleteNetworkRequest deleteNetworkRequest = (DeleteNetworkRequest) networkAdapterRequest;
- execution.setVariable(NETWORK_CORRELATOR, deleteNetworkRequest.getMessageId());
- response = networkAdapterResources.deleteNetworkAsync(deleteNetworkRequest);
- } else if (networkAdapterRequest instanceof UpdateNetworkRequest) {
- UpdateNetworkRequest updateNetworkRequest = (UpdateNetworkRequest) networkAdapterRequest;
- execution.setVariable(NETWORK_CORRELATOR, updateNetworkRequest.getMessageId());
- response = networkAdapterResources.updateNetworkAsync(updateNetworkRequest);
- }
- if(response.isPresent()) {
- String statusCode = Integer.toString(response.get().getStatus());
- String responseString = "";
- if(response.get().getEntity() != null) {
- responseString = (String) response.get().getEntity();
- }
- execution.setVariable(NETWORK_SYNC_CODE, statusCode);
- execution.setVariable(NETWORK_SYNC_RESPONSE, responseString);
- } else {
- throw new Exception("No Ack response from Openstack Adapter");
- }
- } else {
- throw new Exception("No Network Request was created. networkAdapterRequest was null.");
- }
- } catch (Exception ex) {
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void processCallback (DelegateExecution execution) {
- try {
- Object networkAdapterRequest = execution.getVariable(NETWORK_REQUEST);
- String callback = (String) execution.getVariable(NETWORK_MESSAGE);
- String logCallbackMessage = "Callback from OpenstackAdapter: " + callback;
- logger.debug(logCallbackMessage);
- if (networkAdapterRequest != null) {
- if (networkAdapterRequest instanceof CreateNetworkRequest) {
- if(callback.contains("createNetworkError")) {
- CreateNetworkError createNetworkError = (CreateNetworkError) unmarshalXml(callback, CreateNetworkError.class);
- throw new Exception(createNetworkError.getMessage());
- } else {
- CreateNetworkResponse createNetworkResponse = (CreateNetworkResponse) unmarshalXml(callback, CreateNetworkResponse.class);
- execution.setVariable("createNetworkResponse", createNetworkResponse);
- }
- } else if (networkAdapterRequest instanceof DeleteNetworkRequest) {
- if(callback.contains("deleteNetworkError")) {
- DeleteNetworkError deleteNetworkError = (DeleteNetworkError) unmarshalXml(callback, DeleteNetworkError.class);
- throw new Exception(deleteNetworkError.getMessage());
- } else {
- DeleteNetworkResponse deleteNetworkResponse = (DeleteNetworkResponse) unmarshalXml(callback, DeleteNetworkResponse.class);
- execution.setVariable("deleteNetworkResponse", deleteNetworkResponse);
- }
- } else if (networkAdapterRequest instanceof UpdateNetworkRequest) {
- if (callback.contains("updateNetworkError")) {
- UpdateNetworkError updateNetworkError = (UpdateNetworkError) unmarshalXml(callback, UpdateNetworkError.class);
- throw new Exception(updateNetworkError.getMessage());
- } else {
- UpdateNetworkResponse updateNetworkResponse = (UpdateNetworkResponse) unmarshalXml(callback, UpdateNetworkResponse.class);
- execution.setVariable("updateNetworkResponse", updateNetworkResponse);
- }
- }
- }
- } catch (Exception e) {
- logger.error("Error in Openstack Adapter callback", e);
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, e.getMessage());
- }
- }
-
- protected <T> Object unmarshalXml(String xmlString, Class<T> resultClass) throws JAXBException {
- StringReader reader = new StringReader(xmlString);
- JAXBContext context = JAXBContext.newInstance(resultClass);
- Unmarshaller unmarshaller = context.createUnmarshaller();
- return unmarshaller.unmarshal(reader);
- }
-
- public void handleTimeOutException (DelegateExecution execution) {
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, "Error timed out waiting on Openstack Async-Response");
- }
-
- public void handleSyncError (DelegateExecution execution) {
- String statusCode = (String) execution.getVariable(NETWORK_SYNC_CODE);
- String responseString = (String) execution.getVariable(NETWORK_SYNC_RESPONSE);
- String errorMessage = "Error with Openstack Adapter Sync Request: StatusCode = " + statusCode + " Response = " + responseString;
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, errorMessage);
- }
+ public void handleSyncError(DelegateExecution execution) {
+ String statusCode = (String) execution.getVariable(NETWORK_SYNC_CODE);
+ String responseString = (String) execution.getVariable(NETWORK_SYNC_RESPONSE);
+ String errorMessage = "Error with Openstack Adapter Sync Request: StatusCode = " + statusCode + " Response = "
+ + responseString;
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, errorMessage);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java
index 9eeba0445b..77898dd5cc 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java
@@ -40,37 +40,40 @@ import org.springframework.stereotype.Component;
@Component
public class NetworkAdapterUpdateTasks {
- private static final Logger logger = LoggerFactory.getLogger(NetworkAdapterUpdateTasks.class);
-
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private NetworkAdapterObjectMapper networkAdapterObjectMapper;
- @Autowired
- private ExceptionBuilder exceptionUtil;
-
- public void updateNetwork(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
-
- UpdateNetworkRequest updateNetworkRequest = networkAdapterObjectMapper.createNetworkUpdateRequestMapper(gBBInput.getRequestContext(), gBBInput.getCloudRegion(), gBBInput.getOrchContext(), serviceInstance, l3Network, gBBInput.getUserInput(), gBBInput.getCustomer());
- execution.setVariable("networkAdapterRequest", updateNetworkRequest);
-
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void processResponseFromOpenstack(BuildingBlockExecution execution) {
- try {
- UpdateNetworkResponse updateNetworkResponse = execution.getVariable("updateNetworkResponse");
- if(updateNetworkResponse == null) {
- throw new Exception("No response was sent back from NetworkAdapterRestV1 subflow.");
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(NetworkAdapterUpdateTasks.class);
+
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private NetworkAdapterObjectMapper networkAdapterObjectMapper;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+
+ public void updateNetwork(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+
+ UpdateNetworkRequest updateNetworkRequest = networkAdapterObjectMapper.createNetworkUpdateRequestMapper(
+ gBBInput.getRequestContext(), gBBInput.getCloudRegion(), gBBInput.getOrchContext(), serviceInstance,
+ l3Network, gBBInput.getUserInput(), gBBInput.getCustomer());
+ execution.setVariable("networkAdapterRequest", updateNetworkRequest);
+
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void processResponseFromOpenstack(BuildingBlockExecution execution) {
+ try {
+ UpdateNetworkResponse updateNetworkResponse = execution.getVariable("updateNetworkResponse");
+ if (updateNetworkResponse == null) {
+ throw new Exception("No response was sent back from NetworkAdapterRestV1 subflow.");
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java
index ae9e6e7488..849465e787 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java
@@ -47,72 +47,79 @@ import static org.apache.commons.lang3.StringUtils.*;
@Component
public class VnfAdapterCreateTasks {
- private static final Logger logger = LoggerFactory.getLogger(VnfAdapterCreateTasks.class);
- private static final String VNFREST_REQUEST = "VNFREST_Request";
+ private static final Logger logger = LoggerFactory.getLogger(VnfAdapterCreateTasks.class);
+ private static final String VNFREST_REQUEST = "VNFREST_Request";
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private VnfAdapterVolumeGroupResources vnfAdapterVolumeGroupResources;
- @Autowired
- private VnfAdapterVfModuleResources vnfAdapterVfModuleResources;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private VnfAdapterVolumeGroupResources vnfAdapterVolumeGroupResources;
+ @Autowired
+ private VnfAdapterVfModuleResources vnfAdapterVfModuleResources;
@Autowired
private ExceptionBuilder exceptionUtil;
- public void createVolumeGroupRequest(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ public void createVolumeGroupRequest(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ ServiceInstance serviceInstance =
+ gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0);
- ServiceInstance serviceInstance = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0);
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ VfModule vfModule;
+ String sdncVfModuleQueryResponse = null;
+ try {
+ vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ if (vfModule.getSelflink() != null && !vfModule.getSelflink().isEmpty()) {
+ sdncVfModuleQueryResponse = execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId());
+ } else {
+ throw new Exception("Vf Module " + vfModule.getVfModuleId()
+ + " exists in gBuildingBlock but does not have a selflink value");
+ }
+ } catch (BBObjectNotFoundException bbException) {
+ // If there is not a vf module in the general building block (in aLaCarte case), we will not retrieve
+ // the SDNCQueryResponse and proceed as normal without throwing an error
+ }
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- VfModule vfModule;
- String sdncVfModuleQueryResponse = null;
- try {
- vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- if(vfModule.getSelflink() != null && !vfModule.getSelflink().isEmpty()) {
- sdncVfModuleQueryResponse = execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId());
- }
- else {
- throw new Exception("Vf Module " + vfModule.getVfModuleId() + " exists in gBuildingBlock but does not have a selflink value");
- }
- } catch(BBObjectNotFoundException bbException) {
- // If there is not a vf module in the general building block (in aLaCarte case), we will not retrieve the SDNCQueryResponse and proceed as normal without throwing an error
- }
+ CreateVolumeGroupRequest createVolumeGroupRequest = vnfAdapterVolumeGroupResources.createVolumeGroupRequest(
+ gBBInput.getRequestContext(), gBBInput.getCloudRegion(), gBBInput.getOrchContext(), serviceInstance,
+ genericVnf, volumeGroup, sdncVfModuleQueryResponse);
+ execution.setVariable(VNFREST_REQUEST, createVolumeGroupRequest.toXmlString());
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
- CreateVolumeGroupRequest createVolumeGroupRequest = vnfAdapterVolumeGroupResources.createVolumeGroupRequest(gBBInput.getRequestContext(), gBBInput.getCloudRegion(), gBBInput.getOrchContext(), serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse);
- execution.setVariable(VNFREST_REQUEST, createVolumeGroupRequest.toXmlString());
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ public void createVfModule(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- public void createVfModule(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ ServiceInstance serviceInstance =
+ gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0);
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ VolumeGroup volumeGroup = null;
+ try {
+ volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ } catch (BBObjectNotFoundException bbException) {
+ }
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ OrchestrationContext orchestrationContext = gBBInput.getOrchContext();
+ String sdncVfModuleQueryResponse = execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId());
+ String sdncVnfQueryResponse = execution.getVariable("SDNCQueryResponse_" + genericVnf.getVnfId());
- ServiceInstance serviceInstance = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0);
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- VolumeGroup volumeGroup = null;
- try {
- volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- } catch(BBObjectNotFoundException bbException) {
- }
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- RequestContext requestContext = gBBInput.getRequestContext();
- OrchestrationContext orchestrationContext = gBBInput.getOrchContext();
- String sdncVfModuleQueryResponse = execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId());
- String sdncVnfQueryResponse = execution.getVariable("SDNCQueryResponse_" + genericVnf.getVnfId());
+ CreateVfModuleRequest createVfModuleRequest = vnfAdapterVfModuleResources.createVfModuleRequest(
+ requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, vfModule,
+ volumeGroup, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+ execution.setVariable(VNFREST_REQUEST, createVfModuleRequest.toXmlString());
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
- CreateVfModuleRequest createVfModuleRequest = vnfAdapterVfModuleResources.createVfModuleRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, vfModule, volumeGroup, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
- execution.setVariable(VNFREST_REQUEST, createVfModuleRequest.toXmlString());
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java
index a96e2702cd..116dc30d63 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java
@@ -42,46 +42,50 @@ import org.springframework.stereotype.Component;
@Component
public class VnfAdapterDeleteTasks {
- private static final Logger logger = LoggerFactory.getLogger(VnfAdapterDeleteTasks.class);
- private static final String VNFREST_REQUEST = "VNFREST_Request";
-
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private VnfAdapterVolumeGroupResources vnfAdapterVolumeGroupResources;
- @Autowired
- private VnfAdapterVfModuleResources vnfAdapterVfModuleResources;
- @Autowired
- private ExceptionBuilder exceptionUtil;
-
- public void deleteVolumeGroup(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
-
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
-
- DeleteVolumeGroupRequest deleteVolumeGroupRequest = vnfAdapterVolumeGroupResources.deleteVolumeGroupRequest(gBBInput.getRequestContext(), gBBInput.getCloudRegion(), serviceInstance, volumeGroup);
- execution.setVariable(VNFREST_REQUEST, deleteVolumeGroupRequest.toXmlString());
- execution.setVariable("deleteVolumeGroupRequest", "true");
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(VnfAdapterDeleteTasks.class);
+ private static final String VNFREST_REQUEST = "VNFREST_Request";
- public void deleteVfModule(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
-
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
-
- DeleteVfModuleRequest deleteVfModuleRequest = vnfAdapterVfModuleResources.deleteVfModuleRequest( gBBInput.getRequestContext(), gBBInput.getCloudRegion(), serviceInstance, genericVnf, vfModule);
- execution.setVariable(VNFREST_REQUEST, deleteVfModuleRequest.toXmlString());
- execution.setVariable("deleteVfModuleRequest", "true");
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private VnfAdapterVolumeGroupResources vnfAdapterVolumeGroupResources;
+ @Autowired
+ private VnfAdapterVfModuleResources vnfAdapterVfModuleResources;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+
+ public void deleteVolumeGroup(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+
+ DeleteVolumeGroupRequest deleteVolumeGroupRequest = vnfAdapterVolumeGroupResources.deleteVolumeGroupRequest(
+ gBBInput.getRequestContext(), gBBInput.getCloudRegion(), serviceInstance, volumeGroup);
+ execution.setVariable(VNFREST_REQUEST, deleteVolumeGroupRequest.toXmlString());
+ execution.setVariable("deleteVolumeGroupRequest", "true");
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void deleteVfModule(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+
+ DeleteVfModuleRequest deleteVfModuleRequest = vnfAdapterVfModuleResources.deleteVfModuleRequest(
+ gBBInput.getRequestContext(), gBBInput.getCloudRegion(), serviceInstance, genericVnf, vfModule);
+ execution.setVariable(VNFREST_REQUEST, deleteVfModuleRequest.toXmlString());
+ execution.setVariable("deleteVfModuleRequest", "true");
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java
index e854efd414..bfa76c5053 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java
@@ -45,7 +45,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
-
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
@@ -59,96 +58,100 @@ import java.util.Map;
@Component
public class VnfAdapterImpl {
- private static final Logger logger = LoggerFactory.getLogger(VnfAdapterImpl.class);
- private static final String CONTRAIL_SERVICE_INSTANCE_FQDN = "contrailServiceInstanceFqdn";
- private static final String OAM_MANAGEMENT_V4_ADDRESS = "oamManagementV4Address";
- private static final String OAM_MANAGEMENT_V6_ADDRESS = "oamManagementV6Address";
- private static final String CONTRAIL_NETWORK_POLICY_FQDN_LIST = "contrailNetworkPolicyFqdnList";
-
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
-
- @Autowired
- private ExceptionBuilder exceptionUtil;
+ private static final Logger logger = LoggerFactory.getLogger(VnfAdapterImpl.class);
+ private static final String CONTRAIL_SERVICE_INSTANCE_FQDN = "contrailServiceInstanceFqdn";
+ private static final String OAM_MANAGEMENT_V4_ADDRESS = "oamManagementV4Address";
+ private static final String OAM_MANAGEMENT_V6_ADDRESS = "oamManagementV6Address";
+ private static final String CONTRAIL_NETWORK_POLICY_FQDN_LIST = "contrailNetworkPolicyFqdnList";
+
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+
+ public void preProcessVnfAdapter(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ execution.setVariable("mso-request-id", gBBInput.getRequestContext().getMsoRequestId());
+ execution.setVariable("mso-service-instance-id", serviceInstance.getServiceInstanceId());
+ execution.setVariable("heatStackId", null);
+ execution.setVariable(CONTRAIL_SERVICE_INSTANCE_FQDN, null);
+ execution.setVariable(OAM_MANAGEMENT_V4_ADDRESS, null);
+ execution.setVariable(OAM_MANAGEMENT_V6_ADDRESS, null);
+ execution.setVariable(CONTRAIL_NETWORK_POLICY_FQDN_LIST, null);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
- public void preProcessVnfAdapter(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- execution.setVariable("mso-request-id", gBBInput.getRequestContext().getMsoRequestId());
- execution.setVariable("mso-service-instance-id", serviceInstance.getServiceInstanceId());
- execution.setVariable("heatStackId", null);
- execution.setVariable(CONTRAIL_SERVICE_INSTANCE_FQDN, null);
- execution.setVariable(OAM_MANAGEMENT_V4_ADDRESS, null);
- execution.setVariable(OAM_MANAGEMENT_V6_ADDRESS, null);
- execution.setVariable(CONTRAIL_NETWORK_POLICY_FQDN_LIST, null);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void postProcessVnfAdapter(BuildingBlockExecution execution) {
- try {
- String vnfAdapterResponse = execution.getVariable("vnfAdapterRestV1Response");
- if (!StringUtils.isEmpty( vnfAdapterResponse)) {
+ public void postProcessVnfAdapter(BuildingBlockExecution execution) {
+ try {
+ String vnfAdapterResponse = execution.getVariable("vnfAdapterRestV1Response");
+ if (!StringUtils.isEmpty(vnfAdapterResponse)) {
Object vnfRestResponse = unMarshal(vnfAdapterResponse);
- if(vnfRestResponse instanceof CreateVfModuleResponse) {
+ if (vnfRestResponse instanceof CreateVfModuleResponse) {
VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
String heatStackId = ((CreateVfModuleResponse) vnfRestResponse).getVfModuleStackId();
- if(!StringUtils.isEmpty(heatStackId)) {
- vfModule.setHeatStackId(heatStackId);
+ if (!StringUtils.isEmpty(heatStackId)) {
+ vfModule.setHeatStackId(heatStackId);
execution.setVariable("heatStackId", heatStackId);
}
- Map<String,String> vfModuleOutputs = ((CreateVfModuleResponse) vnfRestResponse).getVfModuleOutputs();
+ Map<String, String> vfModuleOutputs =
+ ((CreateVfModuleResponse) vnfRestResponse).getVfModuleOutputs();
if (vfModuleOutputs != null) {
- processVfModuleOutputs(execution, vfModuleOutputs);
+ processVfModuleOutputs(execution, vfModuleOutputs);
}
- } else if(vnfRestResponse instanceof DeleteVfModuleResponse) {
+ } else if (vnfRestResponse instanceof DeleteVfModuleResponse) {
VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
Boolean vfModuleDelete = ((DeleteVfModuleResponse) vnfRestResponse).getVfModuleDeleted();
- if(null!= vfModuleDelete && vfModuleDelete) {
+ if (null != vfModuleDelete && vfModuleDelete) {
vfModule.setHeatStackId(null);
execution.setVariable("heatStackId", null);
- Map<String,String> vfModuleOutputs = ((DeleteVfModuleResponse) vnfRestResponse).getVfModuleOutputs();
+ Map<String, String> vfModuleOutputs =
+ ((DeleteVfModuleResponse) vnfRestResponse).getVfModuleOutputs();
if (vfModuleOutputs != null) {
- processVfModuleOutputs(execution, vfModuleOutputs);
- if (execution.getVariable(OAM_MANAGEMENT_V4_ADDRESS) != null) {
- genericVnf.setIpv4OamAddress("");
- execution.setVariable(OAM_MANAGEMENT_V4_ADDRESS, "");
- }
- if (execution.getVariable(OAM_MANAGEMENT_V6_ADDRESS) != null) {
- genericVnf.setManagementV6Address("");
- execution.setVariable(OAM_MANAGEMENT_V6_ADDRESS, "");
- }
- if (execution.getVariable(CONTRAIL_SERVICE_INSTANCE_FQDN) != null) {
- vfModule.setContrailServiceInstanceFqdn("");
- execution.setVariable(CONTRAIL_SERVICE_INSTANCE_FQDN, "");
- }
+ processVfModuleOutputs(execution, vfModuleOutputs);
+ if (execution.getVariable(OAM_MANAGEMENT_V4_ADDRESS) != null) {
+ genericVnf.setIpv4OamAddress("");
+ execution.setVariable(OAM_MANAGEMENT_V4_ADDRESS, "");
+ }
+ if (execution.getVariable(OAM_MANAGEMENT_V6_ADDRESS) != null) {
+ genericVnf.setManagementV6Address("");
+ execution.setVariable(OAM_MANAGEMENT_V6_ADDRESS, "");
+ }
+ if (execution.getVariable(CONTRAIL_SERVICE_INSTANCE_FQDN) != null) {
+ vfModule.setContrailServiceInstanceFqdn("");
+ execution.setVariable(CONTRAIL_SERVICE_INSTANCE_FQDN, "");
+ }
}
}
- } else if(vnfRestResponse instanceof CreateVolumeGroupResponse) {
+ } else if (vnfRestResponse instanceof CreateVolumeGroupResponse) {
VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
String heatStackId = ((CreateVolumeGroupResponse) vnfRestResponse).getVolumeGroupStackId();
- if(!StringUtils.isEmpty(heatStackId)) {
+ if (!StringUtils.isEmpty(heatStackId)) {
volumeGroup.setHeatStackId(heatStackId);
execution.setVariable("heatStackId", heatStackId);
- }else{
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "HeatStackId is missing from create VolumeGroup Vnf Adapter response.");
- }
- } else if(vnfRestResponse instanceof DeleteVolumeGroupResponse) {
- VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- Boolean volumeGroupDelete = ((DeleteVolumeGroupResponse) vnfRestResponse).getVolumeGroupDeleted();
- if(null!= volumeGroupDelete && volumeGroupDelete) {
- volumeGroup.setHeatStackId(null);
- execution.setVariable("heatStackId", null);
- }
+ } else {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000,
+ "HeatStackId is missing from create VolumeGroup Vnf Adapter response.");
+ }
+ } else if (vnfRestResponse instanceof DeleteVolumeGroupResponse) {
+ VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ Boolean volumeGroupDelete = ((DeleteVolumeGroupResponse) vnfRestResponse).getVolumeGroupDeleted();
+ if (null != volumeGroupDelete && volumeGroupDelete) {
+ volumeGroup.setHeatStackId(null);
+ execution.setVariable("heatStackId", null);
+ }
}
}
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
private Object unMarshal(String input) throws MarshallerException {
try {
@@ -160,61 +163,60 @@ public class VnfAdapterImpl {
XMLReader xmlReader = spf.newSAXParser().getXMLReader();
JAXBContext jaxbContext = JAXBContext.newInstance(CreateVfModuleResponse.class,
- CreateVolumeGroupResponse.class,DeleteVfModuleResponse.class,DeleteVolumeGroupResponse.class);
+ CreateVolumeGroupResponse.class, DeleteVfModuleResponse.class, DeleteVolumeGroupResponse.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
InputSource inputSource = new InputSource(new StringReader(input));
SAXSource source = new SAXSource(xmlReader, inputSource);
return jaxbUnmarshaller.unmarshal(source);
} catch (Exception e) {
- logger.error("{} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), ErrorCode.SchemaError.getValue(),
- e.getMessage(), e);
- throw new MarshallerException("Error parsing VNF Adapter response. " + e.getMessage(), ErrorCode.SchemaError.getValue(), e);
+ logger.error("{} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), ErrorCode.SchemaError.getValue(),
+ e.getMessage(), e);
+ throw new MarshallerException("Error parsing VNF Adapter response. " + e.getMessage(),
+ ErrorCode.SchemaError.getValue(), e);
}
}
-
- private void processVfModuleOutputs(BuildingBlockExecution execution, Map<String,String> vfModuleOutputs) {
- if (vfModuleOutputs == null) {
- return;
- }
- try {
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- List<String> contrailNetworkPolicyFqdnList = new ArrayList<String>();
- Iterator<String> keys = vfModuleOutputs.keySet().iterator();
- while (keys.hasNext()) {
- String key = keys.next();
- if (key.equals("contrail-service-instance-fqdn")) {
- String contrailServiceInstanceFqdn = vfModuleOutputs.get(key);
- logger.debug("Obtained contrailServiceInstanceFqdn: {}", contrailServiceInstanceFqdn);
- vfModule.setContrailServiceInstanceFqdn(contrailServiceInstanceFqdn);
- execution.setVariable(CONTRAIL_SERVICE_INSTANCE_FQDN, contrailServiceInstanceFqdn);
- }
- else if (key.endsWith("contrail_network_policy_fqdn")) {
- String contrailNetworkPolicyFqdn = vfModuleOutputs.get(key);
- logger.debug("Obtained contrailNetworkPolicyFqdn: {}", contrailNetworkPolicyFqdn);
- contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn);
- }
- else if (key.equals("oam_management_v4_address")) {
- String oamManagementV4Address = vfModuleOutputs.get(key);
- logger.debug("Obtained oamManagementV4Address: {}", oamManagementV4Address);
- genericVnf.setIpv4OamAddress(oamManagementV4Address);
- execution.setVariable(OAM_MANAGEMENT_V4_ADDRESS, oamManagementV4Address);
- }
- else if (key.equals("oam_management_v6_address")) {
- String oamManagementV6Address = vfModuleOutputs.get(key);
- logger.debug("Obtained oamManagementV6Address: {}", oamManagementV6Address);
- genericVnf.setManagementV6Address(oamManagementV6Address);
- execution.setVariable(OAM_MANAGEMENT_V6_ADDRESS, oamManagementV6Address);
- }
-
- if (!contrailNetworkPolicyFqdnList.isEmpty()) {
- execution.setVariable(CONTRAIL_NETWORK_POLICY_FQDN_LIST, String.join(",", contrailNetworkPolicyFqdnList));
- }
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
-
+
+ private void processVfModuleOutputs(BuildingBlockExecution execution, Map<String, String> vfModuleOutputs) {
+ if (vfModuleOutputs == null) {
+ return;
+ }
+ try {
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ List<String> contrailNetworkPolicyFqdnList = new ArrayList<String>();
+ Iterator<String> keys = vfModuleOutputs.keySet().iterator();
+ while (keys.hasNext()) {
+ String key = keys.next();
+ if (key.equals("contrail-service-instance-fqdn")) {
+ String contrailServiceInstanceFqdn = vfModuleOutputs.get(key);
+ logger.debug("Obtained contrailServiceInstanceFqdn: {}", contrailServiceInstanceFqdn);
+ vfModule.setContrailServiceInstanceFqdn(contrailServiceInstanceFqdn);
+ execution.setVariable(CONTRAIL_SERVICE_INSTANCE_FQDN, contrailServiceInstanceFqdn);
+ } else if (key.endsWith("contrail_network_policy_fqdn")) {
+ String contrailNetworkPolicyFqdn = vfModuleOutputs.get(key);
+ logger.debug("Obtained contrailNetworkPolicyFqdn: {}", contrailNetworkPolicyFqdn);
+ contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn);
+ } else if (key.equals("oam_management_v4_address")) {
+ String oamManagementV4Address = vfModuleOutputs.get(key);
+ logger.debug("Obtained oamManagementV4Address: {}", oamManagementV4Address);
+ genericVnf.setIpv4OamAddress(oamManagementV4Address);
+ execution.setVariable(OAM_MANAGEMENT_V4_ADDRESS, oamManagementV4Address);
+ } else if (key.equals("oam_management_v6_address")) {
+ String oamManagementV6Address = vfModuleOutputs.get(key);
+ logger.debug("Obtained oamManagementV6Address: {}", oamManagementV6Address);
+ genericVnf.setManagementV6Address(oamManagementV6Address);
+ execution.setVariable(OAM_MANAGEMENT_V6_ADDRESS, oamManagementV6Address);
+ }
+
+ if (!contrailNetworkPolicyFqdnList.isEmpty()) {
+ execution.setVariable(CONTRAIL_NETWORK_POLICY_FQDN_LIST,
+ String.join(",", contrailNetworkPolicyFqdnList));
+ }
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+
}
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/Constants.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/Constants.java
index 976b1bc8df..01519fab6e 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/Constants.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/Constants.java
@@ -30,34 +30,34 @@ import org.onap.vnfmadapter.v1.model.OperationStatusRetrievalStatusEnum;
*/
public class Constants {
- public static final String CREATE_VNF_REQUEST_PARAM_NAME = "createVnfRequest";
- public static final String CREATE_VNF_RESPONSE_PARAM_NAME = "createVnfResponse";
- public static final String INPUT_PARAMETER = "inputParameter";
- public static final String DELETE_VNF_RESPONSE_PARAM_NAME = "deleteVnfResponse";
- public static final String DELETE_VNF_NODE_STATUS = "deleteVnfNodeStatus";
- public static final String CREATE_VNF_NODE_STATUS = "createVnfNodeStatus";
- public static final String VNF_ASSIGNED = "Assigned";
- public static final String VNF_CREATED = "Created";
+ public static final String CREATE_VNF_REQUEST_PARAM_NAME = "createVnfRequest";
+ public static final String CREATE_VNF_RESPONSE_PARAM_NAME = "createVnfResponse";
+ public static final String INPUT_PARAMETER = "inputParameter";
+ public static final String DELETE_VNF_RESPONSE_PARAM_NAME = "deleteVnfResponse";
+ public static final String DELETE_VNF_NODE_STATUS = "deleteVnfNodeStatus";
+ public static final String CREATE_VNF_NODE_STATUS = "createVnfNodeStatus";
+ public static final String VNF_ASSIGNED = "Assigned";
+ public static final String VNF_CREATED = "Created";
- public static final String DOT = ".";
- public static final String UNDERSCORE = "_";
- public static final String SPACE = "\\s+";
+ public static final String DOT = ".";
+ public static final String UNDERSCORE = "_";
+ public static final String SPACE = "\\s+";
- public static final String VNFM_ADAPTER_DEFAULT_URL = "http://so-vnfm-adapter.onap:9092/so/vnfm-adapter/v1/";
- public static final String VNFM_ADAPTER_DEFAULT_AUTH = "Basic dm5mbTpwYXNzd29yZDEk";
+ public static final String VNFM_ADAPTER_DEFAULT_URL = "http://so-vnfm-adapter.onap:9092/so/vnfm-adapter/v1/";
+ public static final String VNFM_ADAPTER_DEFAULT_AUTH = "Basic dm5mbTpwYXNzd29yZDEk";
- public static final String FORWARD_SLASH = "/";
- public static final String PRELOAD_VNFS_URL = "/restconf/config/VNF-API:preload-vnfs/vnf-preload-list/";
+ public static final String FORWARD_SLASH = "/";
+ public static final String PRELOAD_VNFS_URL = "/restconf/config/VNF-API:preload-vnfs/vnf-preload-list/";
- public static final Set<OperationStateEnum> OPERATION_FINISHED_STATES =
- newHashSet(OperationStateEnum.COMPLETED, OperationStateEnum.FAILED, OperationStateEnum.ROLLED_BACK);
+ public static final Set<OperationStateEnum> OPERATION_FINISHED_STATES =
+ newHashSet(OperationStateEnum.COMPLETED, OperationStateEnum.FAILED, OperationStateEnum.ROLLED_BACK);
- public static final Set<OperationStatusRetrievalStatusEnum> OPERATION_RETRIEVAL_STATES = newHashSet(
- OperationStatusRetrievalStatusEnum.STATUS_FOUND, OperationStatusRetrievalStatusEnum.WAITING_FOR_STATUS);
+ public static final Set<OperationStatusRetrievalStatusEnum> OPERATION_RETRIEVAL_STATES = newHashSet(
+ OperationStatusRetrievalStatusEnum.STATUS_FOUND, OperationStatusRetrievalStatusEnum.WAITING_FOR_STATUS);
- public static final String OPERATION_STATUS_PARAM_NAME = "operationStatus";
+ public static final String OPERATION_STATUS_PARAM_NAME = "operationStatus";
- private Constants() {}
+ private Constants() {}
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/EtsiVnfDeleteTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/EtsiVnfDeleteTask.java
index 857c5cb6fe..f29f842709 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/EtsiVnfDeleteTask.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/EtsiVnfDeleteTask.java
@@ -39,46 +39,46 @@ import com.google.common.base.Optional;
@Component
public class EtsiVnfDeleteTask {
- private static final Logger LOGGER = LoggerFactory.getLogger(EtsiVnfDeleteTask.class);
- private final ExtractPojosForBB extractPojosForBB;
- private final ExceptionBuilder exceptionUtil;
- private final VnfmAdapterServiceProvider vnfmAdapterServiceProvider;
+ private static final Logger LOGGER = LoggerFactory.getLogger(EtsiVnfDeleteTask.class);
+ private final ExtractPojosForBB extractPojosForBB;
+ private final ExceptionBuilder exceptionUtil;
+ private final VnfmAdapterServiceProvider vnfmAdapterServiceProvider;
- @Autowired
- public EtsiVnfDeleteTask(final ExceptionBuilder exceptionUtil, final ExtractPojosForBB extractPojosForBB,
- final VnfmAdapterServiceProvider vnfmAdapterServiceProvider) {
- this.exceptionUtil = exceptionUtil;
- this.extractPojosForBB = extractPojosForBB;
- this.vnfmAdapterServiceProvider = vnfmAdapterServiceProvider;
- }
+ @Autowired
+ public EtsiVnfDeleteTask(final ExceptionBuilder exceptionUtil, final ExtractPojosForBB extractPojosForBB,
+ final VnfmAdapterServiceProvider vnfmAdapterServiceProvider) {
+ this.exceptionUtil = exceptionUtil;
+ this.extractPojosForBB = extractPojosForBB;
+ this.vnfmAdapterServiceProvider = vnfmAdapterServiceProvider;
+ }
- /**
- * Invoke VNFM adapter to delete the VNF
- *
- * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
- */
- public void invokeVnfmAdapter(final BuildingBlockExecution execution) {
- try {
- LOGGER.debug("Executing invokeVnfmAdapter ...");
- final GenericVnf vnf = extractPojosForBB.extractByKey(execution, GENERIC_VNF_ID);
+ /**
+ * Invoke VNFM adapter to delete the VNF
+ *
+ * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
+ */
+ public void invokeVnfmAdapter(final BuildingBlockExecution execution) {
+ try {
+ LOGGER.debug("Executing invokeVnfmAdapter ...");
+ final GenericVnf vnf = extractPojosForBB.extractByKey(execution, GENERIC_VNF_ID);
- final Optional<DeleteVnfResponse> response = vnfmAdapterServiceProvider.invokeDeleteRequest(vnf.getVnfId());
+ final Optional<DeleteVnfResponse> response = vnfmAdapterServiceProvider.invokeDeleteRequest(vnf.getVnfId());
- if (!response.isPresent()) {
- final String errorMessage = "Unexpected error while processing delete request";
- LOGGER.error(errorMessage);
- exceptionUtil.buildAndThrowWorkflowException(execution, 1211, errorMessage);
- }
+ if (!response.isPresent()) {
+ final String errorMessage = "Unexpected error while processing delete request";
+ LOGGER.error(errorMessage);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1211, errorMessage);
+ }
- final DeleteVnfResponse vnfResponse = response.get();
+ final DeleteVnfResponse vnfResponse = response.get();
- LOGGER.debug("Vnf delete response: {}", vnfResponse);
- execution.setVariable(Constants.DELETE_VNF_RESPONSE_PARAM_NAME, vnfResponse);
+ LOGGER.debug("Vnf delete response: {}", vnfResponse);
+ execution.setVariable(Constants.DELETE_VNF_RESPONSE_PARAM_NAME, vnfResponse);
- LOGGER.debug("Finished executing invokeVnfmAdapter ...");
- } catch (final Exception exception) {
- LOGGER.error("Unable to invoke delete request", exception);
- exceptionUtil.buildAndThrowWorkflowException(execution, 1212, exception);
+ LOGGER.debug("Finished executing invokeVnfmAdapter ...");
+ } catch (final Exception exception) {
+ LOGGER.error("Unable to invoke delete request", exception);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1212, exception);
+ }
}
- }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTask.java
index ebb9d521c3..661fdb258b 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTask.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTask.java
@@ -21,7 +21,6 @@ package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.INPUT_PARAMETER;
import static org.onap.so.bpmn.servicedecomposition.entities.ResourceKey.GENERIC_VNF_ID;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils.InputParameter;
import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils.InputParametersProvider;
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTask.java
index 9e0c26ba20..4645680fc2 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTask.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTask.java
@@ -39,64 +39,65 @@ import com.google.common.base.Optional;
*
*/
@Component
-public class MonitorVnfmCreateJobTask extends MonitorVnfmJobTask{
+public class MonitorVnfmCreateJobTask extends MonitorVnfmJobTask {
- private static final Logger LOGGER = LoggerFactory.getLogger(MonitorVnfmCreateJobTask.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(MonitorVnfmCreateJobTask.class);
- @Autowired
- public MonitorVnfmCreateJobTask(final VnfmAdapterServiceProvider vnfmAdapterServiceProvider,
- final ExceptionBuilder exceptionUtil) {
- super(vnfmAdapterServiceProvider, exceptionUtil);
- }
-
- /**
- * Get the current operation status of instantiation job
- *
- * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
- */
- public void getCurrentOperationStatus(final BuildingBlockExecution execution) {
- LOGGER.debug("Executing getCurrentOperationStatus ...");
- final CreateVnfResponse vnfInstantiateResponse = execution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME);
- execution.setVariable(OPERATION_STATUS_PARAM_NAME, getOperationStatus(execution, vnfInstantiateResponse.getJobId()));
- LOGGER.debug("Finished executing getCurrentOperationStatus ...");
- }
+ @Autowired
+ public MonitorVnfmCreateJobTask(final VnfmAdapterServiceProvider vnfmAdapterServiceProvider,
+ final ExceptionBuilder exceptionUtil) {
+ super(vnfmAdapterServiceProvider, exceptionUtil);
+ }
- /**
- * Log and throw exception on timeout for job status
- *
- * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
- */
- public void timeOutLogFailue(final BuildingBlockExecution execution) {
- final String message = "Instantiation operation time out";
- LOGGER.error(message);
- exceptionUtil.buildAndThrowWorkflowException(execution, 1205, message);
- }
+ /**
+ * Get the current operation status of instantiation job
+ *
+ * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
+ */
+ public void getCurrentOperationStatus(final BuildingBlockExecution execution) {
+ LOGGER.debug("Executing getCurrentOperationStatus ...");
+ final CreateVnfResponse vnfInstantiateResponse = execution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME);
+ execution.setVariable(OPERATION_STATUS_PARAM_NAME,
+ getOperationStatus(execution, vnfInstantiateResponse.getJobId()));
+ LOGGER.debug("Finished executing getCurrentOperationStatus ...");
+ }
- /**
- * Check the final status of instantiation throw exception if not completed successfully
- *
- * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
- */
- public void checkIfOperationWasSuccessful(final BuildingBlockExecution execution) {
- LOGGER.debug("Executing checkIfOperationWasSuccessful ...");
- final Optional<OperationStateEnum> operationStatusOption = execution.getVariable(OPERATION_STATUS_PARAM_NAME);
- final CreateVnfResponse vnfInstantiateResponse = execution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME);
- if (operationStatusOption == null || !operationStatusOption.isPresent()) {
- final String message = "Unable to instantiate jobId: "
- + (vnfInstantiateResponse != null ? vnfInstantiateResponse.getJobId() : "null")
- + "Unable to retrieve OperationStatus";
- LOGGER.error(message);
- exceptionUtil.buildAndThrowWorkflowException(execution, 1206, message);
- } else if (operationStatusOption != null && operationStatusOption.isPresent()) {
- final OperationStateEnum operationStatus = operationStatusOption.get();
- if (operationStatus != OperationStateEnum.COMPLETED) {
- final String message = "Unable to instantiate jobId: "
- + (vnfInstantiateResponse != null ? vnfInstantiateResponse.getJobId() : "null") + " OperationStatus: "
- + operationStatus;
+ /**
+ * Log and throw exception on timeout for job status
+ *
+ * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
+ */
+ public void timeOutLogFailue(final BuildingBlockExecution execution) {
+ final String message = "Instantiation operation time out";
LOGGER.error(message);
- exceptionUtil.buildAndThrowWorkflowException(execution, 1207, message);
- }
- LOGGER.debug("Successfully completed instatiation of job {}", vnfInstantiateResponse);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1205, message);
+ }
+
+ /**
+ * Check the final status of instantiation throw exception if not completed successfully
+ *
+ * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
+ */
+ public void checkIfOperationWasSuccessful(final BuildingBlockExecution execution) {
+ LOGGER.debug("Executing checkIfOperationWasSuccessful ...");
+ final Optional<OperationStateEnum> operationStatusOption = execution.getVariable(OPERATION_STATUS_PARAM_NAME);
+ final CreateVnfResponse vnfInstantiateResponse = execution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME);
+ if (operationStatusOption == null || !operationStatusOption.isPresent()) {
+ final String message = "Unable to instantiate jobId: "
+ + (vnfInstantiateResponse != null ? vnfInstantiateResponse.getJobId() : "null")
+ + "Unable to retrieve OperationStatus";
+ LOGGER.error(message);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1206, message);
+ } else if (operationStatusOption != null && operationStatusOption.isPresent()) {
+ final OperationStateEnum operationStatus = operationStatusOption.get();
+ if (operationStatus != OperationStateEnum.COMPLETED) {
+ final String message = "Unable to instantiate jobId: "
+ + (vnfInstantiateResponse != null ? vnfInstantiateResponse.getJobId() : "null")
+ + " OperationStatus: " + operationStatus;
+ LOGGER.error(message);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1207, message);
+ }
+ LOGGER.debug("Successfully completed instatiation of job {}", vnfInstantiateResponse);
+ }
}
- }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTask.java
index e13d1e4dda..e91f362d53 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTask.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTask.java
@@ -42,61 +42,62 @@ import com.google.common.base.Optional;
@Component
public class MonitorVnfmDeleteJobTask extends MonitorVnfmJobTask {
- private static final Logger LOGGER = LoggerFactory.getLogger(MonitorVnfmDeleteJobTask.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(MonitorVnfmDeleteJobTask.class);
- @Autowired
- public MonitorVnfmDeleteJobTask(final VnfmAdapterServiceProvider vnfmAdapterServiceProvider,
- final ExceptionBuilder exceptionUtil) {
- super(vnfmAdapterServiceProvider, exceptionUtil);
- }
-
- /**
- * Get the current operation status of Delete job
- *
- * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
- */
- public void getCurrentOperationStatus(final BuildingBlockExecution execution) {
- LOGGER.debug("Executing getCurrentOperationStatus ...");
- final DeleteVnfResponse deleteVnfResponse = execution.getVariable(Constants.DELETE_VNF_RESPONSE_PARAM_NAME);
- execution.setVariable(OPERATION_STATUS_PARAM_NAME, getOperationStatus(execution, deleteVnfResponse.getJobId()));
- LOGGER.debug("Finished executing getCurrentOperationStatus ...");
- }
+ @Autowired
+ public MonitorVnfmDeleteJobTask(final VnfmAdapterServiceProvider vnfmAdapterServiceProvider,
+ final ExceptionBuilder exceptionUtil) {
+ super(vnfmAdapterServiceProvider, exceptionUtil);
+ }
- /**
- * Log and throw exception on timeout for job status
- *
- * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
- */
- public void timeOutLogFailue(final BuildingBlockExecution execution) {
- final String message = "Delete operation time out";
- LOGGER.error(message);
- exceptionUtil.buildAndThrowWorkflowException(execution, 1213, message);
- }
+ /**
+ * Get the current operation status of Delete job
+ *
+ * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
+ */
+ public void getCurrentOperationStatus(final BuildingBlockExecution execution) {
+ LOGGER.debug("Executing getCurrentOperationStatus ...");
+ final DeleteVnfResponse deleteVnfResponse = execution.getVariable(Constants.DELETE_VNF_RESPONSE_PARAM_NAME);
+ execution.setVariable(OPERATION_STATUS_PARAM_NAME, getOperationStatus(execution, deleteVnfResponse.getJobId()));
+ LOGGER.debug("Finished executing getCurrentOperationStatus ...");
+ }
- /**
- * Check the final status of delete throw exception if not completed successfully
- *
- * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
- */
- public void checkIfOperationWasSuccessful(final BuildingBlockExecution execution) {
- LOGGER.debug("Executing checkIfOperationWasSuccessful ...");
- final Optional<OperationStateEnum> operationStatusOption = execution.getVariable(OPERATION_STATUS_PARAM_NAME);
- final DeleteVnfResponse deleteVnfResponse = execution.getVariable(DELETE_VNF_RESPONSE_PARAM_NAME);
- if (operationStatusOption == null || !operationStatusOption.isPresent()) {
- final String message = "Unable to delete jobId: "
- + (deleteVnfResponse != null ? deleteVnfResponse.getJobId() : "null") + "Unable to retrieve OperationStatus";
- LOGGER.error(message);
- exceptionUtil.buildAndThrowWorkflowException(execution, 1214, message);
- } else if (operationStatusOption != null && operationStatusOption.isPresent()) {
- final OperationStateEnum operationStatus = operationStatusOption.get();
- if (operationStatus != OperationStateEnum.COMPLETED) {
- final String message =
- "Unable to Delete jobId: " + (deleteVnfResponse != null ? deleteVnfResponse.getJobId() : "null")
- + " OperationStatus: " + operationStatus;
+ /**
+ * Log and throw exception on timeout for job status
+ *
+ * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
+ */
+ public void timeOutLogFailue(final BuildingBlockExecution execution) {
+ final String message = "Delete operation time out";
LOGGER.error(message);
- exceptionUtil.buildAndThrowWorkflowException(execution, 1215, message);
- }
- LOGGER.debug("Successfully completed Deletion of job {}", deleteVnfResponse);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1213, message);
+ }
+
+ /**
+ * Check the final status of delete throw exception if not completed successfully
+ *
+ * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
+ */
+ public void checkIfOperationWasSuccessful(final BuildingBlockExecution execution) {
+ LOGGER.debug("Executing checkIfOperationWasSuccessful ...");
+ final Optional<OperationStateEnum> operationStatusOption = execution.getVariable(OPERATION_STATUS_PARAM_NAME);
+ final DeleteVnfResponse deleteVnfResponse = execution.getVariable(DELETE_VNF_RESPONSE_PARAM_NAME);
+ if (operationStatusOption == null || !operationStatusOption.isPresent()) {
+ final String message =
+ "Unable to delete jobId: " + (deleteVnfResponse != null ? deleteVnfResponse.getJobId() : "null")
+ + "Unable to retrieve OperationStatus";
+ LOGGER.error(message);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1214, message);
+ } else if (operationStatusOption != null && operationStatusOption.isPresent()) {
+ final OperationStateEnum operationStatus = operationStatusOption.get();
+ if (operationStatus != OperationStateEnum.COMPLETED) {
+ final String message =
+ "Unable to Delete jobId: " + (deleteVnfResponse != null ? deleteVnfResponse.getJobId() : "null")
+ + " OperationStatus: " + operationStatus;
+ LOGGER.error(message);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1215, message);
+ }
+ LOGGER.debug("Successfully completed Deletion of job {}", deleteVnfResponse);
+ }
}
- }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmJobTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmJobTask.java
index e3992428cb..395018fb38 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmJobTask.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmJobTask.java
@@ -41,64 +41,65 @@ import com.google.common.base.Optional;
@Component
public class MonitorVnfmJobTask {
- private static final Logger LOGGER = LoggerFactory.getLogger(MonitorVnfmJobTask.class);
- protected final ExceptionBuilder exceptionUtil;
- protected final VnfmAdapterServiceProvider vnfmAdapterServiceProvider;
+ private static final Logger LOGGER = LoggerFactory.getLogger(MonitorVnfmJobTask.class);
+ protected final ExceptionBuilder exceptionUtil;
+ protected final VnfmAdapterServiceProvider vnfmAdapterServiceProvider;
- @Autowired
- public MonitorVnfmJobTask(final VnfmAdapterServiceProvider vnfmAdapterServiceProvider,
- final ExceptionBuilder exceptionUtil) {
- this.vnfmAdapterServiceProvider = vnfmAdapterServiceProvider;
- this.exceptionUtil = exceptionUtil;
- }
+ @Autowired
+ public MonitorVnfmJobTask(final VnfmAdapterServiceProvider vnfmAdapterServiceProvider,
+ final ExceptionBuilder exceptionUtil) {
+ this.vnfmAdapterServiceProvider = vnfmAdapterServiceProvider;
+ this.exceptionUtil = exceptionUtil;
+ }
- /**
- * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
- * @return boolean to indicate whether job has competed or not
- */
- public boolean hasOperationFinished(final BuildingBlockExecution execution) {
- LOGGER.debug("Executing hasOperationFinished ...");
+ /**
+ * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
+ * @return boolean to indicate whether job has competed or not
+ */
+ public boolean hasOperationFinished(final BuildingBlockExecution execution) {
+ LOGGER.debug("Executing hasOperationFinished ...");
- final Optional<OperationStateEnum> operationStatusOption = execution.getVariable(OPERATION_STATUS_PARAM_NAME);
- if (operationStatusOption != null && operationStatusOption.isPresent()) {
- return OPERATION_FINISHED_STATES.contains(operationStatusOption.get());
+ final Optional<OperationStateEnum> operationStatusOption = execution.getVariable(OPERATION_STATUS_PARAM_NAME);
+ if (operationStatusOption != null && operationStatusOption.isPresent()) {
+ return OPERATION_FINISHED_STATES.contains(operationStatusOption.get());
+ }
+ LOGGER.debug("OperationStatus is not present yet... ");
+ LOGGER.debug("Finished executing hasOperationFinished ...");
+ return false;
}
- LOGGER.debug("OperationStatus is not present yet... ");
- LOGGER.debug("Finished executing hasOperationFinished ...");
- return false;
- }
- /**
- * This method calls the Vnfm adapter and gets the Operation status of the job
- * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
- * @param jobId unique job id
- * @return Operation State
- */
- protected Optional<OperationStateEnum> getOperationStatus(final BuildingBlockExecution execution,
- final String jobId) {
+ /**
+ * This method calls the Vnfm adapter and gets the Operation status of the job
+ *
+ * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
+ * @param jobId unique job id
+ * @return Operation State
+ */
+ protected Optional<OperationStateEnum> getOperationStatus(final BuildingBlockExecution execution,
+ final String jobId) {
- final Optional<QueryJobResponse> instantiateOperationJobStatus =
- vnfmAdapterServiceProvider.getInstantiateOperationJobStatus(jobId);
+ final Optional<QueryJobResponse> instantiateOperationJobStatus =
+ vnfmAdapterServiceProvider.getInstantiateOperationJobStatus(jobId);
- if (instantiateOperationJobStatus.isPresent()) {
- final QueryJobResponse queryJobResponse = instantiateOperationJobStatus.get();
+ if (instantiateOperationJobStatus.isPresent()) {
+ final QueryJobResponse queryJobResponse = instantiateOperationJobStatus.get();
- if (!OPERATION_RETRIEVAL_STATES.contains(queryJobResponse.getOperationStatusRetrievalStatus())) {
- final String message =
- "Recevied invalid operation reterivel state: " + queryJobResponse.getOperationStatusRetrievalStatus();
- LOGGER.error(message);
- exceptionUtil.buildAndThrowWorkflowException(execution, 1203, message);
- }
- if (queryJobResponse.getOperationState() != null) {
- final OperationStateEnum operationStatus = queryJobResponse.getOperationState();
- LOGGER.debug("Operation {} with {} and operation retrieval status : {}", queryJobResponse.getId(),
- operationStatus, queryJobResponse.getOperationStatusRetrievalStatus());
- return Optional.of(queryJobResponse.getOperationState());
- }
+ if (!OPERATION_RETRIEVAL_STATES.contains(queryJobResponse.getOperationStatusRetrievalStatus())) {
+ final String message = "Recevied invalid operation reterivel state: "
+ + queryJobResponse.getOperationStatusRetrievalStatus();
+ LOGGER.error(message);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1203, message);
+ }
+ if (queryJobResponse.getOperationState() != null) {
+ final OperationStateEnum operationStatus = queryJobResponse.getOperationState();
+ LOGGER.debug("Operation {} with {} and operation retrieval status : {}", queryJobResponse.getId(),
+ operationStatus, queryJobResponse.getOperationStatusRetrievalStatus());
+ return Optional.of(queryJobResponse.getOperationState());
+ }
- LOGGER.debug("Operation {} without operationStatus and operation retrieval status :{}", queryJobResponse.getId(),
- queryJobResponse.getOperationStatusRetrievalStatus());
+ LOGGER.debug("Operation {} without operationStatus and operation retrieval status :{}",
+ queryJobResponse.getId(), queryJobResponse.getOperationStatusRetrievalStatus());
+ }
+ return Optional.absent();
}
- return Optional.absent();
- }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeTask.java
index 22a5d28e52..65b05e21f5 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeTask.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeTask.java
@@ -42,44 +42,44 @@ import org.springframework.stereotype.Component;
@Component
public class MonitorVnfmNodeTask {
- private static final Logger LOGGER = LoggerFactory.getLogger(MonitorVnfmNodeTask.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(MonitorVnfmNodeTask.class);
- private final ExtractPojosForBB extractPojosForBB;
- private final ExceptionBuilder exceptionUtil;
+ private final ExtractPojosForBB extractPojosForBB;
+ private final ExceptionBuilder exceptionUtil;
- @Autowired
- public MonitorVnfmNodeTask(final ExtractPojosForBB extractPojosForBB, final ExceptionBuilder exceptionUtil) {
- this.exceptionUtil = exceptionUtil;
- this.extractPojosForBB = extractPojosForBB;
- }
+ @Autowired
+ public MonitorVnfmNodeTask(final ExtractPojosForBB extractPojosForBB, final ExceptionBuilder exceptionUtil) {
+ this.exceptionUtil = exceptionUtil;
+ this.extractPojosForBB = extractPojosForBB;
+ }
- /**
- * Check the final status of vnf in A&AI
- *
- * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
- */
- public void getNodeStatus(final BuildingBlockExecution execution) {
- try {
- LOGGER.debug("Executing getNodeStatus ...");
- final GenericVnf vnf = extractPojosForBB.extractByKey(execution, GENERIC_VNF_ID);
- String orchestrationStatus = vnf.getOrchestrationStatus();
- LOGGER.debug("Orchestration Status in AAI {}", orchestrationStatus);
- execution.setVariable(CREATE_VNF_NODE_STATUS, VNF_CREATED.equalsIgnoreCase(orchestrationStatus));
- execution.setVariable(DELETE_VNF_NODE_STATUS, VNF_ASSIGNED.equalsIgnoreCase(orchestrationStatus));
- } catch (final Exception exception) {
- LOGGER.error("Unable to get vnf from AAI", exception);
- exceptionUtil.buildAndThrowWorkflowException(execution, 1220, exception);
+ /**
+ * Check the final status of vnf in A&AI
+ *
+ * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
+ */
+ public void getNodeStatus(final BuildingBlockExecution execution) {
+ try {
+ LOGGER.debug("Executing getNodeStatus ...");
+ final GenericVnf vnf = extractPojosForBB.extractByKey(execution, GENERIC_VNF_ID);
+ String orchestrationStatus = vnf.getOrchestrationStatus();
+ LOGGER.debug("Orchestration Status in AAI {}", orchestrationStatus);
+ execution.setVariable(CREATE_VNF_NODE_STATUS, VNF_CREATED.equalsIgnoreCase(orchestrationStatus));
+ execution.setVariable(DELETE_VNF_NODE_STATUS, VNF_ASSIGNED.equalsIgnoreCase(orchestrationStatus));
+ } catch (final Exception exception) {
+ LOGGER.error("Unable to get vnf from AAI", exception);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1220, exception);
+ }
}
- }
- /**
- * Log and throw exception on timeout for job status
- *
- * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
- */
- public void timeOutLogFailue(final BuildingBlockExecution execution) {
- final String message = "Node operation time out";
- LOGGER.error(message);
- exceptionUtil.buildAndThrowWorkflowException(execution, 1221, message);
- }
+ /**
+ * Log and throw exception on timeout for job status
+ *
+ * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl}
+ */
+ public void timeOutLogFailue(final BuildingBlockExecution execution) {
+ final String message = "Node operation time out";
+ LOGGER.error(message);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1221, message);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTask.java
index 4e15474e46..9ff2835480 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTask.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTask.java
@@ -27,7 +27,6 @@ import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.INPUT
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.SPACE;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.UNDERSCORE;
import static org.onap.so.bpmn.servicedecomposition.entities.ResourceKey.GENERIC_VNF_ID;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils.InputParameter;
import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils.NullInputParameter;
@@ -44,12 +43,10 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.google.common.base.Optional;
/**
- * This class is executed from EtsiVnfInstantiateBB building block and it sends the create request
- * to the VNFM adapter
+ * This class is executed from EtsiVnfInstantiateBB building block and it sends the create request to the VNFM adapter
*
* @author waqas.ikram@est.tech
*/
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfiguration.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfiguration.java
index 1046b6bf26..f5bae2c82a 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfiguration.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfiguration.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks;
import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE;
-
import org.onap.so.configuration.rest.BasicHttpHeadersProvider;
import org.onap.so.configuration.rest.HttpHeadersProvider;
import org.onap.so.rest.service.HttpRestServiceProvider;
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProvider.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProvider.java
index 1e785074f3..d1b270bc1e 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProvider.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProvider.java
@@ -34,10 +34,10 @@ import com.google.common.base.Optional;
*/
public interface VnfmAdapterServiceProvider {
- Optional<CreateVnfResponse> invokeCreateInstantiationRequest(final String vnfId, final CreateVnfRequest request);
+ Optional<CreateVnfResponse> invokeCreateInstantiationRequest(final String vnfId, final CreateVnfRequest request);
- Optional<DeleteVnfResponse> invokeDeleteRequest(final String vnfId);
+ Optional<DeleteVnfResponse> invokeDeleteRequest(final String vnfId);
- Optional<QueryJobResponse> getInstantiateOperationJobStatus(final String jobId);
+ Optional<QueryJobResponse> getInstantiateOperationJobStatus(final String jobId);
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImpl.java
index e8f4c08f38..f193967a32 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImpl.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImpl.java
@@ -41,111 +41,111 @@ import com.google.common.base.Optional;
@Service
public class VnfmAdapterServiceProviderImpl implements VnfmAdapterServiceProvider {
- private static final Logger LOGGER = LoggerFactory.getLogger(VnfmAdapterServiceProviderImpl.class);
-
- private final VnfmAdapterUrlProvider urlProvider;
- private final HttpRestServiceProvider httpServiceProvider;
-
- @Autowired
- public VnfmAdapterServiceProviderImpl(final VnfmAdapterUrlProvider urlProvider,
- final HttpRestServiceProvider httpServiceProvider) {
- this.urlProvider = urlProvider;
- this.httpServiceProvider = httpServiceProvider;
- }
-
- @Override
- public Optional<CreateVnfResponse> invokeCreateInstantiationRequest(final String vnfId,
- final CreateVnfRequest request) {
- try {
- final String url = urlProvider.getCreateInstantiateUrl(vnfId);
-
- final ResponseEntity<CreateVnfResponse> response =
- httpServiceProvider.postHttpRequest(request, url, CreateVnfResponse.class);
-
- final HttpStatus httpStatus = response.getStatusCode();
- if (!(httpStatus.equals(HttpStatus.ACCEPTED)) && !(httpStatus.equals(HttpStatus.OK))) {
- LOGGER.error("Unable to invoke HTTP POST using URL: {}, Response Code: {}", url, httpStatus.value());
- return Optional.absent();
- }
-
- if (!response.hasBody()) {
- LOGGER.error("Received response without body: {}", response);
- return Optional.absent();
- }
-
- final CreateVnfResponse createVnfResponse = response.getBody();
-
- if (createVnfResponse.getJobId() == null || createVnfResponse.getJobId().isEmpty()) {
- LOGGER.error("Received invalid instantiation response: {}", response);
- return Optional.absent();
- }
-
- return Optional.of(createVnfResponse);
- } catch (final RestProcessingException | InvalidRestRequestException httpInvocationException) {
- LOGGER.error("Unexpected error while processing create and instantiation request", httpInvocationException);
- return Optional.absent();
+ private static final Logger LOGGER = LoggerFactory.getLogger(VnfmAdapterServiceProviderImpl.class);
+
+ private final VnfmAdapterUrlProvider urlProvider;
+ private final HttpRestServiceProvider httpServiceProvider;
+
+ @Autowired
+ public VnfmAdapterServiceProviderImpl(final VnfmAdapterUrlProvider urlProvider,
+ final HttpRestServiceProvider httpServiceProvider) {
+ this.urlProvider = urlProvider;
+ this.httpServiceProvider = httpServiceProvider;
}
- }
+ @Override
+ public Optional<CreateVnfResponse> invokeCreateInstantiationRequest(final String vnfId,
+ final CreateVnfRequest request) {
+ try {
+ final String url = urlProvider.getCreateInstantiateUrl(vnfId);
- @Override
- public Optional<DeleteVnfResponse> invokeDeleteRequest(final String vnfId) {
- try {
- final String url = urlProvider.getDeleteUrl(vnfId);
- LOGGER.debug("Will send request to vnfm adapter using url: {}", url);
+ final ResponseEntity<CreateVnfResponse> response =
+ httpServiceProvider.postHttpRequest(request, url, CreateVnfResponse.class);
- final ResponseEntity<DeleteVnfResponse> response =
- httpServiceProvider.deleteHttpRequest(url, DeleteVnfResponse.class);
+ final HttpStatus httpStatus = response.getStatusCode();
+ if (!(httpStatus.equals(HttpStatus.ACCEPTED)) && !(httpStatus.equals(HttpStatus.OK))) {
+ LOGGER.error("Unable to invoke HTTP POST using URL: {}, Response Code: {}", url, httpStatus.value());
+ return Optional.absent();
+ }
- LOGGER.debug("Response received: ", response);
+ if (!response.hasBody()) {
+ LOGGER.error("Received response without body: {}", response);
+ return Optional.absent();
+ }
- final HttpStatus httpStatus = response.getStatusCode();
+ final CreateVnfResponse createVnfResponse = response.getBody();
- if (!(httpStatus.equals(HttpStatus.ACCEPTED)) && !(httpStatus.equals(HttpStatus.OK))) {
- LOGGER.error("Unable to invoke HTTP DELETE using URL: {}, Response Code: {}", url, httpStatus.value());
- return Optional.absent();
- }
+ if (createVnfResponse.getJobId() == null || createVnfResponse.getJobId().isEmpty()) {
+ LOGGER.error("Received invalid instantiation response: {}", response);
+ return Optional.absent();
+ }
- if (!response.hasBody()) {
- LOGGER.error("Received response without body: {}", response);
- return Optional.absent();
- }
- final DeleteVnfResponse deleteVnfResponse = response.getBody();
+ return Optional.of(createVnfResponse);
+ } catch (final RestProcessingException | InvalidRestRequestException httpInvocationException) {
+ LOGGER.error("Unexpected error while processing create and instantiation request", httpInvocationException);
+ return Optional.absent();
+ }
- if (deleteVnfResponse.getJobId() == null || deleteVnfResponse.getJobId().isEmpty()) {
- LOGGER.error("Received invalid delete response: {}", response);
- return Optional.absent();
- }
- return Optional.of(deleteVnfResponse);
- } catch (final RestProcessingException | InvalidRestRequestException httpInvocationException) {
- LOGGER.error("Unexpected error while processing delete request", httpInvocationException);
- return Optional.absent();
}
- }
-
- @Override
- public Optional<QueryJobResponse> getInstantiateOperationJobStatus(final String jobId) {
- try {
- final String url = urlProvider.getJobStatusUrl(jobId);
-
- final ResponseEntity<QueryJobResponse> response =
- httpServiceProvider.getHttpResponse(url, QueryJobResponse.class);
-
- final HttpStatus httpStatus = response.getStatusCode();
-
- if (!(httpStatus.equals(HttpStatus.ACCEPTED)) && !(httpStatus.equals(HttpStatus.OK))) {
- LOGGER.error("Unable to invoke HTTP GET using URL: {}, Response Code: ", url, httpStatus.value());
- return Optional.absent();
- }
-
- if (!response.hasBody()) {
- LOGGER.error("Received response without body: {}", response);
- return Optional.absent();
- }
- return Optional.of(response.getBody());
- } catch (final RestProcessingException | InvalidRestRequestException httpInvocationException) {
- LOGGER.error("Unexpected error while processing job request", httpInvocationException);
- return Optional.absent();
+
+ @Override
+ public Optional<DeleteVnfResponse> invokeDeleteRequest(final String vnfId) {
+ try {
+ final String url = urlProvider.getDeleteUrl(vnfId);
+ LOGGER.debug("Will send request to vnfm adapter using url: {}", url);
+
+ final ResponseEntity<DeleteVnfResponse> response =
+ httpServiceProvider.deleteHttpRequest(url, DeleteVnfResponse.class);
+
+ LOGGER.debug("Response received: ", response);
+
+ final HttpStatus httpStatus = response.getStatusCode();
+
+ if (!(httpStatus.equals(HttpStatus.ACCEPTED)) && !(httpStatus.equals(HttpStatus.OK))) {
+ LOGGER.error("Unable to invoke HTTP DELETE using URL: {}, Response Code: {}", url, httpStatus.value());
+ return Optional.absent();
+ }
+
+ if (!response.hasBody()) {
+ LOGGER.error("Received response without body: {}", response);
+ return Optional.absent();
+ }
+ final DeleteVnfResponse deleteVnfResponse = response.getBody();
+
+ if (deleteVnfResponse.getJobId() == null || deleteVnfResponse.getJobId().isEmpty()) {
+ LOGGER.error("Received invalid delete response: {}", response);
+ return Optional.absent();
+ }
+ return Optional.of(deleteVnfResponse);
+ } catch (final RestProcessingException | InvalidRestRequestException httpInvocationException) {
+ LOGGER.error("Unexpected error while processing delete request", httpInvocationException);
+ return Optional.absent();
+ }
+ }
+
+ @Override
+ public Optional<QueryJobResponse> getInstantiateOperationJobStatus(final String jobId) {
+ try {
+ final String url = urlProvider.getJobStatusUrl(jobId);
+
+ final ResponseEntity<QueryJobResponse> response =
+ httpServiceProvider.getHttpResponse(url, QueryJobResponse.class);
+
+ final HttpStatus httpStatus = response.getStatusCode();
+
+ if (!(httpStatus.equals(HttpStatus.ACCEPTED)) && !(httpStatus.equals(HttpStatus.OK))) {
+ LOGGER.error("Unable to invoke HTTP GET using URL: {}, Response Code: ", url, httpStatus.value());
+ return Optional.absent();
+ }
+
+ if (!response.hasBody()) {
+ LOGGER.error("Received response without body: {}", response);
+ return Optional.absent();
+ }
+ return Optional.of(response.getBody());
+ } catch (final RestProcessingException | InvalidRestRequestException httpInvocationException) {
+ LOGGER.error("Unexpected error while processing job request", httpInvocationException);
+ return Optional.absent();
+ }
}
- }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProvider.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProvider.java
index 97a7197373..cacba5c5fd 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProvider.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProvider.java
@@ -35,34 +35,32 @@ import org.springframework.web.util.UriComponentsBuilder;
@Service
public class VnfmAdapterUrlProvider {
- private final URI baseUri;
+ private final URI baseUri;
- @Autowired
- public VnfmAdapterUrlProvider(final VnfmBasicHttpConfigProvider etsiVnfmAdapter) {
- this.baseUri = UriComponentsBuilder.fromHttpUrl(etsiVnfmAdapter.getUrl()).build().toUri();
- }
+ @Autowired
+ public VnfmAdapterUrlProvider(final VnfmBasicHttpConfigProvider etsiVnfmAdapter) {
+ this.baseUri = UriComponentsBuilder.fromHttpUrl(etsiVnfmAdapter.getUrl()).build().toUri();
+ }
- /**
- * Get VNFM create and instantiate URL
- *
- * @param vnfId The identifier of the VNF. This must be the vnf-id of an existing generic-vnf in
- * AAI.
- * @return VNFM create and instantiate URL
- */
- public String getCreateInstantiateUrl(final String vnfId) {
- return UriComponentsBuilder.fromUri(baseUri).pathSegment("vnfs").pathSegment(vnfId).build().toString();
- }
+ /**
+ * Get VNFM create and instantiate URL
+ *
+ * @param vnfId The identifier of the VNF. This must be the vnf-id of an existing generic-vnf in AAI.
+ * @return VNFM create and instantiate URL
+ */
+ public String getCreateInstantiateUrl(final String vnfId) {
+ return UriComponentsBuilder.fromUri(baseUri).pathSegment("vnfs").pathSegment(vnfId).build().toString();
+ }
- /**
- * Get VNFM delete URL
- *
- * @param vnfId The identifier of the VNF. This must be the vnf-id of an existing generic-vnf in
- * AAI.
- * @return VNFM delete URL
- */
- public String getDeleteUrl(final String vnfId) {
- return UriComponentsBuilder.fromUri(baseUri).pathSegment("vnfs").pathSegment(vnfId).build().toString();
- }
+ /**
+ * Get VNFM delete URL
+ *
+ * @param vnfId The identifier of the VNF. This must be the vnf-id of an existing generic-vnf in AAI.
+ * @return VNFM delete URL
+ */
+ public String getDeleteUrl(final String vnfId) {
+ return UriComponentsBuilder.fromUri(baseUri).pathSegment("vnfs").pathSegment(vnfId).build().toString();
+ }
/**
* Get job status URL
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmBasicHttpConfigProvider.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmBasicHttpConfigProvider.java
index c9b1ad1ce1..8bb5302ce9 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmBasicHttpConfigProvider.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmBasicHttpConfigProvider.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.VNFM_ADAPTER_DEFAULT_AUTH;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.VNFM_ADAPTER_DEFAULT_URL;
-
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameter.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameter.java
index 5ade3240a0..d01d494c58 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameter.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameter.java
@@ -24,7 +24,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.onap.vnfmadapter.v1.model.ExternalVirtualLink;
/**
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImpl.java
index 6027e78d8b..bf4f16b355 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImpl.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImpl.java
@@ -21,14 +21,12 @@ package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.FORWARD_SLASH;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.PRELOAD_VNFS_URL;
-
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf;
import org.onap.so.client.sdnc.SDNCClient;
@@ -37,12 +35,10 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
-
import net.minidev.json.JSONArray;
/**
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/VnfParameter.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/VnfParameter.java
index 11e93e733d..0d45dad6fe 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/VnfParameter.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/VnfParameter.java
@@ -20,7 +20,6 @@
package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils;
import java.util.Objects;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/**
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java
index 75c66345a0..ef882b4694 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java
@@ -46,139 +46,138 @@ import org.springframework.stereotype.Component;
@Component
public class AppcRunTasks {
- private static final Logger logger = LoggerFactory.getLogger(AppcRunTasks.class);
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private CatalogDbClient catalogDbClient;
- @Autowired
- private ApplicationControllerAction appCClient;
-
- public void preProcessActivity(BuildingBlockExecution execution) {
- execution.setVariable("actionSnapshot", Action.Snapshot);
- execution.setVariable("actionLock", Action.Lock);
- execution.setVariable("actionUnlock", Action.Unlock);
- execution.setVariable("actionUpgradePreCheck", Action.UpgradePreCheck);
- execution.setVariable("actionUpgradePostCheck", Action.UpgradePostCheck);
- execution.setVariable("actionQuiesceTraffic", Action.QuiesceTraffic);
- execution.setVariable("actionUpgradeBackup", Action.UpgradeBackup);
- execution.setVariable("actionUpgradeSoftware", Action.UpgradeSoftware);
- execution.setVariable("actionResumeTraffic", Action.ResumeTraffic);
- execution.setVariable("actionStop", Action.Stop);
- execution.setVariable("actionStart", Action.Start);
- execution.setVariable("actionHealthCheck", Action.HealthCheck);
- execution.setVariable("actionDistributeTraffic", Action.DistributeTraffic);
- execution.setVariable("actionDistributeTrafficCheck", Action.DistributeTrafficCheck);
- execution.setVariable("rollbackVnfStop", false);
- execution.setVariable("rollbackVnfLock", false);
- execution.setVariable("rollbackQuiesceTraffic", false);
- }
-
- public void runAppcCommand(BuildingBlockExecution execution, Action action) {
- logger.trace("Start runAppcCommand ");
- String appcCode = "1002";
- String appcMessage = "";
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- GenericVnf vnf = null;
- try {
- vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- } catch (BBObjectNotFoundException e) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "No valid VNF exists");
- }
- String vnfId = null;
- String vnfName = null;
- String vnfType = null;
- String vnfHostIpAddress = null;
+ private static final Logger logger = LoggerFactory.getLogger(AppcRunTasks.class);
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+ @Autowired
+ private ApplicationControllerAction appCClient;
- if (vnf != null) {
- vnfId = vnf.getVnfId();
- vnfName = vnf.getVnfName();
- vnfType = vnf.getVnfType();
- vnfHostIpAddress = vnf.getIpv4OamAddress();
+ public void preProcessActivity(BuildingBlockExecution execution) {
+ execution.setVariable("actionSnapshot", Action.Snapshot);
+ execution.setVariable("actionLock", Action.Lock);
+ execution.setVariable("actionUnlock", Action.Unlock);
+ execution.setVariable("actionUpgradePreCheck", Action.UpgradePreCheck);
+ execution.setVariable("actionUpgradePostCheck", Action.UpgradePostCheck);
+ execution.setVariable("actionQuiesceTraffic", Action.QuiesceTraffic);
+ execution.setVariable("actionUpgradeBackup", Action.UpgradeBackup);
+ execution.setVariable("actionUpgradeSoftware", Action.UpgradeSoftware);
+ execution.setVariable("actionResumeTraffic", Action.ResumeTraffic);
+ execution.setVariable("actionStop", Action.Stop);
+ execution.setVariable("actionStart", Action.Start);
+ execution.setVariable("actionHealthCheck", Action.HealthCheck);
+ execution.setVariable("actionDistributeTraffic", Action.DistributeTraffic);
+ execution.setVariable("actionDistributeTrafficCheck", Action.DistributeTrafficCheck);
+ execution.setVariable("rollbackVnfStop", false);
+ execution.setVariable("rollbackVnfLock", false);
+ execution.setVariable("rollbackQuiesceTraffic", false);
+ }
+
+ public void runAppcCommand(BuildingBlockExecution execution, Action action) {
+ logger.trace("Start runAppcCommand ");
+ String appcCode = "1002";
+ String appcMessage = "";
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ GenericVnf vnf = null;
+ try {
+ vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ } catch (BBObjectNotFoundException e) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "No valid VNF exists");
+ }
+ String vnfId = null;
+ String vnfName = null;
+ String vnfType = null;
+ String vnfHostIpAddress = null;
+
+ if (vnf != null) {
+ vnfId = vnf.getVnfId();
+ vnfName = vnf.getVnfName();
+ vnfType = vnf.getVnfType();
+ vnfHostIpAddress = vnf.getIpv4OamAddress();
+ }
+ String msoRequestId = gBBInput.getRequestContext().getMsoRequestId();
+
+ String aicIdentity = execution.getVariable("aicIdentity");
+ String vmIdList = execution.getVariable("vmIdList");
+ String vserverIdList = execution.getVariable("vserverIdList");
+ String identityUrl = execution.getVariable("identityUrl");
+
+ ControllerSelectionReference controllerSelectionReference = catalogDbClient
+ .getControllerSelectionReferenceByVnfTypeAndActionCategory(vnfType, action.toString());
+ String controllerType = controllerSelectionReference.getControllerName();
+
+ String vfModuleId = null;
+ VfModule vfModule = null;
+ try {
+ vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ } catch (BBObjectNotFoundException e) {
+ }
+ if (vfModule != null) {
+ vfModuleId = vfModule.getVfModuleId();
+ }
+
+ HashMap<String, String> payloadInfo = buildPayloadInfo(vnfName, aicIdentity, vnfHostIpAddress, vmIdList,
+ vserverIdList, identityUrl, vfModuleId);
+ Optional<String> payload = null;
+ RequestParameters requestParameters = gBBInput.getRequestContext().getRequestParameters();
+ if (requestParameters != null) {
+ String pay = requestParameters.getPayload();
+ if (pay != null) {
+ payload = Optional.of(pay);
+ }
+ }
+ logger.debug("Running APP-C action: {}", action.toString());
+ logger.debug("VNFID: {}", vnfId);
+ appCClient.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+ appcCode = appCClient.getErrorCode();
+ appcMessage = appCClient.getErrorMessage();
+ mapRollbackVariables(execution, action, appcCode);
+ } catch (Exception e) {
+ logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(),
+ "Caught exception in runAppcCommand", "BPMN", ErrorCode.UnknownError.getValue(), "APPC Error", e);
+ appcMessage = e.getMessage();
+ }
+
+ logger.error("Error Message: {}", appcMessage);
+ logger.error("ERROR CODE: {}", appcCode);
+ logger.trace("End of runAppCommand ");
+ if (appcCode != null && !appcCode.equals("0")) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage);
+ }
+ }
+
+ protected void mapRollbackVariables(BuildingBlockExecution execution, Action action, String appcCode) {
+ if (appcCode.equals("0") && action != null) {
+ if (action.equals(Action.Lock)) {
+ execution.setVariable("rollbackVnfLock", true);
+ } else if (action.equals(Action.Unlock)) {
+ execution.setVariable("rollbackVnfLock", false);
+ } else if (action.equals(Action.Start)) {
+ execution.setVariable("rollbackVnfStop", false);
+ } else if (action.equals(Action.Stop)) {
+ execution.setVariable("rollbackVnfStop", true);
+ } else if (action.equals(Action.QuiesceTraffic)) {
+ execution.setVariable("rollbackQuiesceTraffic", true);
+ } else if (action.equals(Action.ResumeTraffic)) {
+ execution.setVariable("rollbackQuiesceTraffic", false);
+ }
}
- String msoRequestId = gBBInput.getRequestContext().getMsoRequestId();
+ }
- String aicIdentity = execution.getVariable("aicIdentity");
- String vmIdList = execution.getVariable("vmIdList");
- String vserverIdList = execution.getVariable("vserverIdList");
- String identityUrl = execution.getVariable("identityUrl");
-
- ControllerSelectionReference controllerSelectionReference = catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory(vnfType, action.toString());
- String controllerType = controllerSelectionReference.getControllerName();
-
- String vfModuleId = null;
- VfModule vfModule = null;
- try {
- vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- } catch (BBObjectNotFoundException e) {
- }
- if (vfModule != null) {
- vfModuleId = vfModule.getVfModuleId();
- }
-
- HashMap<String, String> payloadInfo = buildPayloadInfo(vnfName, aicIdentity, vnfHostIpAddress, vmIdList, vserverIdList,
- identityUrl, vfModuleId);
- Optional<String> payload = null;
- RequestParameters requestParameters = gBBInput.getRequestContext().getRequestParameters();
- if(requestParameters != null){
- String pay = requestParameters.getPayload();
- if (pay != null) {
- payload = Optional.of(pay);
- }
- }
- logger.debug("Running APP-C action: {}", action.toString());
- logger.debug("VNFID: {}", vnfId);
- appCClient.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
- appcCode = appCClient.getErrorCode();
- appcMessage = appCClient.getErrorMessage();
- mapRollbackVariables(execution, action, appcCode);
- }
- catch (Exception e) {
- logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(),
- "Caught exception in runAppcCommand", "BPMN",
- ErrorCode.UnknownError.getValue(), "APPC Error", e);
- appcMessage = e.getMessage();
- }
-
- logger.error("Error Message: {}", appcMessage);
- logger.error("ERROR CODE: {}", appcCode);
- logger.trace("End of runAppCommand ");
- if (appcCode != null && !appcCode.equals("0")) {
- exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage);
- }
- }
-
- protected void mapRollbackVariables(BuildingBlockExecution execution, Action action, String appcCode) {
- if (appcCode.equals("0") && action != null) {
- if (action.equals(Action.Lock)) {
- execution.setVariable("rollbackVnfLock", true);
- } else if (action.equals(Action.Unlock)) {
- execution.setVariable("rollbackVnfLock", false);
- } else if (action.equals(Action.Start)) {
- execution.setVariable("rollbackVnfStop", false);
- } else if (action.equals(Action.Stop)) {
- execution.setVariable("rollbackVnfStop", true);
- } else if (action.equals(Action.QuiesceTraffic)) {
- execution.setVariable("rollbackQuiesceTraffic", true);
- } else if (action.equals(Action.ResumeTraffic)) {
- execution.setVariable("rollbackQuiesceTraffic", false);
- }
- }
- }
-
- private HashMap<String,String> buildPayloadInfo(String vnfName, String aicIdentity, String vnfHostIpAddress,
- String vmIdList, String vserverIdList, String identityUrl, String vfModuleId) {
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", vnfName);
- payloadInfo.put("aicIdentity", aicIdentity);
- payloadInfo.put("vnfHostIpAddress", vnfHostIpAddress);
- payloadInfo.put("vmIdList", vmIdList);
- payloadInfo.put("vserverIdList", vserverIdList);
- payloadInfo.put("identityUrl", identityUrl);
- payloadInfo.put("vfModuleId",vfModuleId);
- return payloadInfo;
- }
+ private HashMap<String, String> buildPayloadInfo(String vnfName, String aicIdentity, String vnfHostIpAddress,
+ String vmIdList, String vserverIdList, String identityUrl, String vfModuleId) {
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", vnfName);
+ payloadInfo.put("aicIdentity", aicIdentity);
+ payloadInfo.put("vnfHostIpAddress", vnfHostIpAddress);
+ payloadInfo.put("vmIdList", vmIdList);
+ payloadInfo.put("vserverIdList", vserverIdList);
+ payloadInfo.put("identityUrl", identityUrl);
+ payloadInfo.put("vfModuleId", vfModuleId);
+ return payloadInfo;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java
index f6e07c8303..a223259d4d 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java
@@ -39,45 +39,46 @@ import org.springframework.stereotype.Component;
@Component
public class AuditTasks {
- private static final Logger logger = LoggerFactory.getLogger(AuditTasks.class);
+ private static final Logger logger = LoggerFactory.getLogger(AuditTasks.class);
- @Autowired
- private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private Environment env;
+ @Autowired
+ private Environment env;
- public void isAuditNeeded(BuildingBlockExecution execution) {
- try {
- logger.debug("auditInventoryNeeded Value: {}", env.getProperty("mso.infra.auditInventory"));
- execution.setVariable("auditInventoryNeeded", Boolean.parseBoolean(env.getProperty("mso.infra.auditInventory")));
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ public void isAuditNeeded(BuildingBlockExecution execution) {
+ try {
+ logger.debug("auditInventoryNeeded Value: {}", env.getProperty("mso.infra.auditInventory"));
+ execution.setVariable("auditInventoryNeeded",
+ Boolean.parseBoolean(env.getProperty("mso.infra.auditInventory")));
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
- public void setupAuditVariable(BuildingBlockExecution execution) {
- try {
- execution.setVariable("auditInventory",createAuditInventory(execution));
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ public void setupAuditVariable(BuildingBlockExecution execution) {
+ try {
+ execution.setVariable("auditInventory", createAuditInventory(execution));
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
- private AuditInventory createAuditInventory(BuildingBlockExecution execution) throws BBObjectNotFoundException {
- AuditInventory auditInventory = new AuditInventory();
+ private AuditInventory createAuditInventory(BuildingBlockExecution execution) throws BBObjectNotFoundException {
+ AuditInventory auditInventory = new AuditInventory();
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
- auditInventory.setCloudOwner(cloudRegion.getCloudOwner());
- auditInventory.setCloudRegion(cloudRegion.getLcpCloudRegionId());
- auditInventory.setTenantId(cloudRegion.getTenantId());
- auditInventory.setHeatStackName(vfModule.getVfModuleName());
- return auditInventory;
- }
+ auditInventory.setCloudOwner(cloudRegion.getCloudOwner());
+ auditInventory.setCloudRegion(cloudRegion.getLcpCloudRegionId());
+ auditInventory.setTenantId(cloudRegion.getTenantId());
+ auditInventory.setHeatStackName(vfModule.getVfModuleName());
+ return auditInventory;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ActivateVfModule.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ActivateVfModule.java
index f2fb37e182..9ed77d47ea 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ActivateVfModule.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ActivateVfModule.java
@@ -32,24 +32,24 @@ import org.springframework.stereotype.Component;
public class ActivateVfModule {
private static final Logger logger = LoggerFactory.getLogger(ActivateVfModule.class);
-
- protected static final String VF_MODULE_TIMER_DURATION_PATH = "mso.workflow.vfModuleActivate.timer.duration";
- protected static final String DEFAULT_TIMER_DURATION = "PT180S";
-
- @Autowired
- private ExceptionBuilder exceptionUtil;
-
- @Autowired
+
+ protected static final String VF_MODULE_TIMER_DURATION_PATH = "mso.workflow.vfModuleActivate.timer.duration";
+ protected static final String DEFAULT_TIMER_DURATION = "PT180S";
+
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+
+ @Autowired
private Environment environment;
- public void setTimerDuration(BuildingBlockExecution execution) {
- try {
- String waitDuration = this.environment.getProperty(VF_MODULE_TIMER_DURATION_PATH, DEFAULT_TIMER_DURATION);
- logger.debug("Sleeping before proceeding with SDNC activate. Timer duration: {}", waitDuration);
- execution.setVariable("vfModuleActivateTimerDuration", waitDuration);
- } catch (Exception e) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e);
- }
- }
+ public void setTimerDuration(BuildingBlockExecution execution) {
+ try {
+ String waitDuration = this.environment.getProperty(VF_MODULE_TIMER_DURATION_PATH, DEFAULT_TIMER_DURATION);
+ logger.debug("Sleeping before proceeding with SDNC activate. Timer duration: {}", waitDuration);
+ execution.setVariable("vfModuleActivateTimerDuration", waitDuration);
+ } catch (Exception e) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetwork.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetwork.java
index c3106d6e49..164480d7c7 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetwork.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetwork.java
@@ -34,28 +34,29 @@ import org.springframework.stereotype.Component;
@Component
public class AssignNetwork {
- private static final Logger logger = LoggerFactory.getLogger(AssignNetwork.class);
+ private static final Logger logger = LoggerFactory.getLogger(AssignNetwork.class);
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
-
- /**
- * Check if network was found by name
- * @param execution
- * @return
- */
- public boolean networkFoundByName(BuildingBlockExecution execution) {
- boolean networkFound = false;
- try {
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
- if (!OrchestrationStatus.PRECREATED.equals(l3network.getOrchestrationStatus())){
- networkFound = true;
- logger.debug("network found in NOT PRECREATED status");
- }
- } catch (Exception ex) {
- // return false if no network present
- }
- return networkFound;
- }
+ /**
+ * Check if network was found by name
+ *
+ * @param execution
+ * @return
+ */
+ public boolean networkFoundByName(BuildingBlockExecution execution) {
+ boolean networkFound = false;
+ try {
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+
+ if (!OrchestrationStatus.PRECREATED.equals(l3network.getOrchestrationStatus())) {
+ networkFound = true;
+ logger.debug("network found in NOT PRECREATED status");
+ }
+ } catch (Exception ex) {
+ // return false if no network present
+ }
+ return networkFound;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtils.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtils.java
index df3f5465e6..ab8818f682 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtils.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtils.java
@@ -37,65 +37,69 @@ import org.springframework.stereotype.Component;
@Component
public class AssignNetworkBBUtils {
- private static final Logger logger = LoggerFactory.getLogger(AssignNetworkBBUtils.class);
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private AAINetworkResources aaiNetworkResources;
- @Autowired
- private SDNCNetworkResources sdncNetworkResources;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
+ private static final Logger logger = LoggerFactory.getLogger(AssignNetworkBBUtils.class);
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private AAINetworkResources aaiNetworkResources;
+ @Autowired
+ private SDNCNetworkResources sdncNetworkResources;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
- /**
- * BPMN access method. Verify if network name was provided as input to BB
- * @param execution
- * @return
- */
- public boolean networkFoundByName(BuildingBlockExecution execution) throws Exception {
- boolean found = false;
- //TODO - populate logic after iTrack MSO-2143 implemented
- return found;
- }
-
- /**
- * BPMN access method to extract Cloud Region data
- * @param execution
- * @throws Exception
- */
- public void getCloudRegion(BuildingBlockExecution execution) {
- try{
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- String cloudRegionSdnc;
- String cloudRegionPo = cloudRegion.getLcpCloudRegionId();
- if (cloudRegion.getCloudRegionVersion().equalsIgnoreCase("2.5")){
- cloudRegionSdnc = "AAIAIC25";
- } else {
- cloudRegionSdnc = cloudRegionPo;
- }
- execution.setVariable("cloudRegionPo", cloudRegionPo);
- execution.setVariable("cloudRegionSdnc", cloudRegionSdnc);
- }catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method. Process silent success scenario
- * @param execution
- */
- public void processSilentSuccess(BuildingBlockExecution execution) {
- String msg = "Silent success processing network assign";
- logger.info(msg);
- }
-
- /**
- * BPMN access method. Process silent success scenario
- * @param execution
- */
- public void failOrchestrationStatus(BuildingBlockExecution execution) {
- BpmnError error = new BpmnError("Failed orchestration status verificaiton");
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, error);
- }
+ /**
+ * BPMN access method. Verify if network name was provided as input to BB
+ *
+ * @param execution
+ * @return
+ */
+ public boolean networkFoundByName(BuildingBlockExecution execution) throws Exception {
+ boolean found = false;
+ // TODO - populate logic after iTrack MSO-2143 implemented
+ return found;
+ }
+
+ /**
+ * BPMN access method to extract Cloud Region data
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void getCloudRegion(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ String cloudRegionSdnc;
+ String cloudRegionPo = cloudRegion.getLcpCloudRegionId();
+ if (cloudRegion.getCloudRegionVersion().equalsIgnoreCase("2.5")) {
+ cloudRegionSdnc = "AAIAIC25";
+ } else {
+ cloudRegionSdnc = cloudRegionPo;
+ }
+ execution.setVariable("cloudRegionPo", cloudRegionPo);
+ execution.setVariable("cloudRegionSdnc", cloudRegionSdnc);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method. Process silent success scenario
+ *
+ * @param execution
+ */
+ public void processSilentSuccess(BuildingBlockExecution execution) {
+ String msg = "Silent success processing network assign";
+ logger.info(msg);
+ }
+
+ /**
+ * BPMN access method. Process silent success scenario
+ *
+ * @param execution
+ */
+ public void failOrchestrationStatus(BuildingBlockExecution execution) {
+ BpmnError error = new BpmnError("Failed orchestration status verificaiton");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, error);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnf.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnf.java
index 0aa3142996..1b06fe114f 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnf.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnf.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
import java.util.List;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.infrastructure.common.name.generation.AAIObjectInstanceNameGenerator;
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
@@ -37,35 +36,36 @@ import org.springframework.stereotype.Component;
@Component
public class AssignVnf {
-
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private AAIInstanceGroupResources aaiInstanceGroupResources;
- @Autowired
- private AAIObjectInstanceNameGenerator aaiObjectInstanceNameGenerator;
-
-
- public void createInstanceGroups(BuildingBlockExecution execution) {
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- List<InstanceGroup> instanceGroups = vnf.getInstanceGroups();
- for(InstanceGroup instanceGroup : instanceGroups) {
- if(ModelInfoInstanceGroup.TYPE_VNFC.equalsIgnoreCase(instanceGroup.getModelInfoInstanceGroup().getType())) {
- instanceGroup.setInstanceGroupName(aaiObjectInstanceNameGenerator.generateInstanceGroupName(instanceGroup, vnf));
- aaiInstanceGroupResources.createInstanceGroup(instanceGroup);
- aaiInstanceGroupResources.connectInstanceGroupToVnf(instanceGroup, vnf, AAIEdgeLabel.BELONGS_TO);
- }
- else if(ModelInfoInstanceGroup.TYPE_L3_NETWORK.equalsIgnoreCase(instanceGroup.getModelInfoInstanceGroup().getType())) {
- aaiInstanceGroupResources.connectInstanceGroupToVnf(instanceGroup, vnf, AAIEdgeLabel.USES);
- }
- }
- }
- catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private AAIInstanceGroupResources aaiInstanceGroupResources;
+ @Autowired
+ private AAIObjectInstanceNameGenerator aaiObjectInstanceNameGenerator;
+
+
+ public void createInstanceGroups(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ List<InstanceGroup> instanceGroups = vnf.getInstanceGroups();
+ for (InstanceGroup instanceGroup : instanceGroups) {
+ if (ModelInfoInstanceGroup.TYPE_VNFC
+ .equalsIgnoreCase(instanceGroup.getModelInfoInstanceGroup().getType())) {
+ instanceGroup.setInstanceGroupName(
+ aaiObjectInstanceNameGenerator.generateInstanceGroupName(instanceGroup, vnf));
+ aaiInstanceGroupResources.createInstanceGroup(instanceGroup);
+ aaiInstanceGroupResources.connectInstanceGroupToVnf(instanceGroup, vnf, AAIEdgeLabel.BELONGS_TO);
+ } else if (ModelInfoInstanceGroup.TYPE_L3_NETWORK
+ .equalsIgnoreCase(instanceGroup.getModelInfoInstanceGroup().getType())) {
+ aaiInstanceGroupResources.connectInstanceGroupToVnf(instanceGroup, vnf, AAIEdgeLabel.USES);
+ }
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CloudSiteCatalogUtils.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CloudSiteCatalogUtils.java
index 752c39a0a6..c1482d1463 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CloudSiteCatalogUtils.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CloudSiteCatalogUtils.java
@@ -22,7 +22,6 @@
package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
import java.util.Optional;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.so.client.exception.ExceptionBuilder;
import org.onap.so.db.catalog.client.CatalogDbClient;
@@ -35,45 +34,49 @@ import org.springframework.stereotype.Component;
@Component
public class CloudSiteCatalogUtils {
- private static final Logger logger = LoggerFactory.getLogger(CloudSiteCatalogUtils.class);
- @Autowired
- private ExceptionBuilder exceptionUtil;
-
- @Autowired
- private CatalogDbClient catalogDbClient;
-
-
- public void getIdentityUrlFromCloudSite(DelegateExecution execution) {
- String cloudRegionId = (String) execution.getVariable("lcpCloudRegionId");
-
- if (cloudRegionId != null) {
- Optional<CloudSite> cloudSite = getCloudSite(cloudRegionId);
- if (!cloudSite.isPresent()) {
- logger.debug("Cloud Region with cloudRegionId {} not found in Catalog DB", cloudRegionId);
- exceptionUtil.buildAndThrowWorkflowException(execution, 404, "Cloud Region with cloudRegionId " + cloudRegionId + " not found in Catalog DB");
- }
-
- if (cloudSite.get().getIdentityService() == null) {
- logger.debug("No identityService found for Cloud Region with cloudRegionId {} in Catalog DB", cloudRegionId);
- exceptionUtil.buildAndThrowWorkflowException(execution, 404, "No identityService found for Cloud Region with cloudRegionId " + cloudRegionId + " in Catalog DB");
- }
- String identityUrl = cloudSite.get().getIdentityService().getIdentityUrl();
-
- logger.debug("identityUrl from Catalog DB is: {}", identityUrl);
- execution.setVariable("identityUrl", identityUrl);
- }
- }
-
- protected Optional<CloudSite> getCloudSite(String id) {
- if (id == null) {
- return Optional.empty();
- }
- CloudSite cloudSite = catalogDbClient.getCloudSite(id);
+ private static final Logger logger = LoggerFactory.getLogger(CloudSiteCatalogUtils.class);
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+
+
+ public void getIdentityUrlFromCloudSite(DelegateExecution execution) {
+ String cloudRegionId = (String) execution.getVariable("lcpCloudRegionId");
+
+ if (cloudRegionId != null) {
+ Optional<CloudSite> cloudSite = getCloudSite(cloudRegionId);
+ if (!cloudSite.isPresent()) {
+ logger.debug("Cloud Region with cloudRegionId {} not found in Catalog DB", cloudRegionId);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 404,
+ "Cloud Region with cloudRegionId " + cloudRegionId + " not found in Catalog DB");
+ }
+
+ if (cloudSite.get().getIdentityService() == null) {
+ logger.debug("No identityService found for Cloud Region with cloudRegionId {} in Catalog DB",
+ cloudRegionId);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 404,
+ "No identityService found for Cloud Region with cloudRegionId " + cloudRegionId
+ + " in Catalog DB");
+ }
+ String identityUrl = cloudSite.get().getIdentityService().getIdentityUrl();
+
+ logger.debug("identityUrl from Catalog DB is: {}", identityUrl);
+ execution.setVariable("identityUrl", identityUrl);
+ }
+ }
+
+ protected Optional<CloudSite> getCloudSite(String id) {
+ if (id == null) {
+ return Optional.empty();
+ }
+ CloudSite cloudSite = catalogDbClient.getCloudSite(id);
- if (cloudSite != null) {
- return Optional.of(cloudSite);
- } else {
- return(Optional.of(catalogDbClient.getCloudSiteByClliAndAicVersion(id,"2.5")));
- }
- }
+ if (cloudSite != null) {
+ return Optional.of(cloudSite);
+ } else {
+ return (Optional.of(catalogDbClient.getCloudSiteByClliAndAicVersion(id, "2.5")));
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnf.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnf.java
index 242135adb8..8a24330093 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnf.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnf.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
import java.util.Map;
import java.util.UUID;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance;
@@ -57,8 +56,8 @@ public class ConfigAssignVnf {
private ExtractPojosForBB extractPojosForBB;
/**
- * Getting the vnf data, blueprint name, blueprint version etc and setting them
- * in execution object and calling the subprocess.
+ * Getting the vnf data, blueprint name, blueprint version etc and setting them in execution object and calling the
+ * subprocess.
*
* @param execution
*/
@@ -66,7 +65,8 @@ public class ConfigAssignVnf {
logger.info("Start preProcessAbstractCDSProcessing ");
try {
GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
Map<String, Object> userParams = execution.getGeneralBuildingBlock().getRequestContext().getUserParams();
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnf.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnf.java
index 1bc7c0f574..359f19285f 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnf.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnf.java
@@ -1,27 +1,21 @@
/*
-* ============LICENSE_START=======================================================
-* ONAP : SO
-* ================================================================================
-* Copyright 2019 TechMahindra
-*=================================================================================
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-* ============LICENSE_END=========================================================
-*/
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright 2019 TechMahindra
+ * ================================================================================= Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
import java.util.UUID;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.infrastructure.aai.tasks.AAIUpdateTasks;
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
@@ -45,86 +39,90 @@ import org.springframework.stereotype.Component;
*/
@Component
public class ConfigDeployVnf {
- private static final Logger logger = LoggerFactory.getLogger(ConfigDeployVnf.class);
- private final static String ORIGINATOR_ID = "SO";
- private final static String ACTION_NAME = "config-deploy";
- private final static String MODE = "async";
-
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private AAIUpdateTasks aaiUpdateTask;
-
- /**
- * Update vnf orch status to configure in AAI
- *
- * @param execution
- */
- public void updateAAIConfigure(BuildingBlockExecution execution) {
- aaiUpdateTask.updateOrchestrationStausConfigDeployConfigureVnf(execution);
-
- }
- /**
- * Getting the vnf object and set in execution object
- *
- * @param execution
- *
- *
- */
- public void preProcessAbstractCDSProcessing(BuildingBlockExecution execution) {
-
-
- logger.info("Start preProcessAbstractCDSProcessing");
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
-
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
-
- ConfigDeployPropertiesForVnf configDeployPropertiesForVnf = new ConfigDeployPropertiesForVnf();
- configDeployPropertiesForVnf.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- configDeployPropertiesForVnf.setServiceModelUuid(serviceInstance.getModelInfoServiceInstance().getModelUuid());
- configDeployPropertiesForVnf.setVnfCustomizationUuid(vnf.getModelInfoGenericVnf().getModelCustomizationUuid());
- configDeployPropertiesForVnf.setVnfId(vnf.getVnfId());
- configDeployPropertiesForVnf.setVnfName(vnf.getVnfName());
-
- ConfigDeployRequestVnf configDeployRequestVnf = new ConfigDeployRequestVnf();
-
- configDeployRequestVnf.setResolutionKey(vnf.getVnfName());
- configDeployRequestVnf.setConfigDeployPropertiesForVnf(configDeployPropertiesForVnf);
-
- String blueprintName = vnf.getBlueprintName();
- String blueprintVersion = vnf.getBlueprintVersion();
- AbstractCDSPropertiesBean abstractCDSPropertiesBean = new AbstractCDSPropertiesBean();
-
- abstractCDSPropertiesBean.setBlueprintName(blueprintName);
- abstractCDSPropertiesBean.setBlueprintVersion(blueprintVersion);
- abstractCDSPropertiesBean.setRequestObject(configDeployRequestVnf.toString());
-
-
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
-
- abstractCDSPropertiesBean.setOriginatorId( ORIGINATOR_ID);
- abstractCDSPropertiesBean.setRequestId(gBBInput.getRequestContext().getMsoRequestId());
- abstractCDSPropertiesBean.setSubRequestId(UUID.randomUUID().toString());
- abstractCDSPropertiesBean.setActionName(ACTION_NAME);
- abstractCDSPropertiesBean.setMode(MODE);
-
- execution.setVariable("executionObject", abstractCDSPropertiesBean);
-
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * Update vnf orch status to configured in AAI
- *
- * @param execution
- */
- public void updateAAIConfigured(BuildingBlockExecution execution) {
- aaiUpdateTask.updateOrchestrationStausConfigDeployConfiguredVnf(execution);
-
- }
-} \ No newline at end of file
+ private static final Logger logger = LoggerFactory.getLogger(ConfigDeployVnf.class);
+ private final static String ORIGINATOR_ID = "SO";
+ private final static String ACTION_NAME = "config-deploy";
+ private final static String MODE = "async";
+
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private AAIUpdateTasks aaiUpdateTask;
+
+ /**
+ * Update vnf orch status to configure in AAI
+ *
+ * @param execution
+ */
+ public void updateAAIConfigure(BuildingBlockExecution execution) {
+ aaiUpdateTask.updateOrchestrationStausConfigDeployConfigureVnf(execution);
+
+ }
+
+ /**
+ * Getting the vnf object and set in execution object
+ *
+ * @param execution
+ *
+ *
+ */
+ public void preProcessAbstractCDSProcessing(BuildingBlockExecution execution) {
+
+
+ logger.info("Start preProcessAbstractCDSProcessing");
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+
+ ConfigDeployPropertiesForVnf configDeployPropertiesForVnf = new ConfigDeployPropertiesForVnf();
+ configDeployPropertiesForVnf.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ configDeployPropertiesForVnf
+ .setServiceModelUuid(serviceInstance.getModelInfoServiceInstance().getModelUuid());
+ configDeployPropertiesForVnf
+ .setVnfCustomizationUuid(vnf.getModelInfoGenericVnf().getModelCustomizationUuid());
+ configDeployPropertiesForVnf.setVnfId(vnf.getVnfId());
+ configDeployPropertiesForVnf.setVnfName(vnf.getVnfName());
+
+ ConfigDeployRequestVnf configDeployRequestVnf = new ConfigDeployRequestVnf();
+
+ configDeployRequestVnf.setResolutionKey(vnf.getVnfName());
+ configDeployRequestVnf.setConfigDeployPropertiesForVnf(configDeployPropertiesForVnf);
+
+ String blueprintName = vnf.getBlueprintName();
+ String blueprintVersion = vnf.getBlueprintVersion();
+ AbstractCDSPropertiesBean abstractCDSPropertiesBean = new AbstractCDSPropertiesBean();
+
+ abstractCDSPropertiesBean.setBlueprintName(blueprintName);
+ abstractCDSPropertiesBean.setBlueprintVersion(blueprintVersion);
+ abstractCDSPropertiesBean.setRequestObject(configDeployRequestVnf.toString());
+
+
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ abstractCDSPropertiesBean.setOriginatorId(ORIGINATOR_ID);
+ abstractCDSPropertiesBean.setRequestId(gBBInput.getRequestContext().getMsoRequestId());
+ abstractCDSPropertiesBean.setSubRequestId(UUID.randomUUID().toString());
+ abstractCDSPropertiesBean.setActionName(ACTION_NAME);
+ abstractCDSPropertiesBean.setMode(MODE);
+
+ execution.setVariable("executionObject", abstractCDSPropertiesBean);
+
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * Update vnf orch status to configured in AAI
+ *
+ * @param execution
+ */
+ public void updateAAIConfigured(BuildingBlockExecution execution) {
+ aaiUpdateTask.updateOrchestrationStausConfigDeployConfiguredVnf(execution);
+
+ }
+}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java
index 4cd0321578..1925d8b69f 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java
@@ -25,7 +25,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.onap.appc.client.lcm.model.Action;
import org.onap.so.bpmn.appc.payload.beans.ConfigScaleOutPayload;
import org.onap.so.bpmn.appc.payload.beans.RequestParametersConfigScaleOut;
@@ -45,124 +44,124 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
@Component
public class ConfigurationScaleOut {
- private static final Logger logger = LoggerFactory.getLogger(ConfigurationScaleOut.class);
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private CatalogDbClient catalogDbClient;
- @Autowired
- private ApplicationControllerAction appCClient;
- private static final String ACTION = "action";
- private static final String MSO_REQUEST_ID = "msoRequestId";
- private static final String VNF_ID = "vnfId";
- private static final String VNF_NAME = "vnfName";
- private static final String VFMODULE_ID = "vfModuleId";
- private static final String CONTROLLER_TYPE = "controllerType";
- private static final String PAYLOAD = "payload";
-
- public void setParamsForConfigurationScaleOut(BuildingBlockExecution execution) {
-
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
-
- try {
- List<Map<String, String>> jsonPathForCfgParams = gBBInput.getRequestContext().getConfigurationParameters();
- String key = null;
- String paramValue = null;
- ObjectMapper mapper = new ObjectMapper();
- String configScaleOutPayloadString = null;
- ControllerSelectionReference controllerSelectionReference;
- ConfigScaleOutPayload configPayload = new ConfigScaleOutPayload();
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- String vnfId = vnf.getVnfId();
- String vnfName = vnf.getVnfName();
- String vnfType = vnf.getVnfType();
- String actionCategory = Action.ConfigScaleOut.toString();
- controllerSelectionReference = catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory(vnfType, actionCategory);
- String controllerName = controllerSelectionReference.getControllerName();
-
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- String sdncVfModuleQueryResponse = execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId());
-
- Map<String, String> paramsMap = new HashMap<>();
- RequestParametersConfigScaleOut requestParameters = new RequestParametersConfigScaleOut();
- String configScaleOutParam = null;
- if (jsonPathForCfgParams != null) {
- for (Map<String, String> param : jsonPathForCfgParams) {
- for (Map.Entry<String,String> entry : param.entrySet()) {
- key = entry.getKey();
- paramValue = entry.getValue();
- try{
- configScaleOutParam = JsonPath.parse(sdncVfModuleQueryResponse).read(paramValue);
- }catch(ClassCastException e){
- configScaleOutParam = null;
- logger.warn("Incorrect JSON path. Path points to object rather than value causing: ", e);
- }
- paramsMap.put(key, configScaleOutParam);
- }
- }
- }
- requestParameters.setVfModuleId(vfModule.getVfModuleId());
- requestParameters.setVnfHostIpAddress(vnf.getIpv4OamAddress());
- configPayload.setConfigurationParameters(paramsMap);
- configPayload.setRequestParameters(requestParameters);
- configScaleOutPayloadString = mapper.writeValueAsString(configPayload);
-
- execution.setVariable(ACTION, actionCategory);
- execution.setVariable(MSO_REQUEST_ID, gBBInput.getRequestContext().getMsoRequestId());
- execution.setVariable(VNF_ID, vnfId);
- execution.setVariable(VNF_NAME, vnfName);
- execution.setVariable(VFMODULE_ID, vfModule.getVfModuleId());
- execution.setVariable(CONTROLLER_TYPE, controllerName);
- execution.setVariable(PAYLOAD, configScaleOutPayloadString);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void callAppcClient(BuildingBlockExecution execution) {
- logger.trace("Start runAppcCommand ");
- String appcCode = "1002";
- String appcMessage = "";
- try{
- Action commandAction = Action.valueOf(execution.getVariable(ACTION));
- String msoRequestId = execution.getVariable(MSO_REQUEST_ID);
- String vnfId = execution.getVariable(VNF_ID);
- Optional<String> payloadString = null;
- if(execution.getVariable(PAYLOAD) != null){
- String pay = execution.getVariable(PAYLOAD);
- payloadString = Optional.of(pay);
- }
- String controllerType = execution.getVariable(CONTROLLER_TYPE);
- HashMap<String, String> payloadInfo = new HashMap<>();
- payloadInfo.put(VNF_NAME, execution.getVariable(VNF_NAME));
- payloadInfo.put(VFMODULE_ID,execution.getVariable(VFMODULE_ID));
- logger.debug("Running APP-C action: {}", commandAction.toString());
- logger.debug("VNFID: {}", vnfId);
- //PayloadInfo contains extra information that adds on to payload before making request to appc
- appCClient.runAppCCommand(commandAction, msoRequestId, vnfId, payloadString, payloadInfo, controllerType);
- appcCode = appCClient.getErrorCode();
- appcMessage = appCClient.getErrorMessage();
-
- } catch (Exception e) {
- logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(),
- "Caught exception in runAppcCommand in ConfigurationScaleOut", "BPMN",
- ErrorCode.UnknownError.getValue(), "APPC Error", e);
- appcMessage = e.getMessage();
- }
- logger.error("Error Message: " + appcMessage);
- logger.error("ERROR CODE: " + appcCode);
- logger.trace("End of runAppCommand ");
- if (appcCode != null && !appcCode.equals("0")) {
- exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage);
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(ConfigurationScaleOut.class);
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+ @Autowired
+ private ApplicationControllerAction appCClient;
+ private static final String ACTION = "action";
+ private static final String MSO_REQUEST_ID = "msoRequestId";
+ private static final String VNF_ID = "vnfId";
+ private static final String VNF_NAME = "vnfName";
+ private static final String VFMODULE_ID = "vfModuleId";
+ private static final String CONTROLLER_TYPE = "controllerType";
+ private static final String PAYLOAD = "payload";
+
+ public void setParamsForConfigurationScaleOut(BuildingBlockExecution execution) {
+
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ try {
+ List<Map<String, String>> jsonPathForCfgParams = gBBInput.getRequestContext().getConfigurationParameters();
+ String key = null;
+ String paramValue = null;
+ ObjectMapper mapper = new ObjectMapper();
+ String configScaleOutPayloadString = null;
+ ControllerSelectionReference controllerSelectionReference;
+ ConfigScaleOutPayload configPayload = new ConfigScaleOutPayload();
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ String vnfId = vnf.getVnfId();
+ String vnfName = vnf.getVnfName();
+ String vnfType = vnf.getVnfType();
+ String actionCategory = Action.ConfigScaleOut.toString();
+ controllerSelectionReference =
+ catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory(vnfType, actionCategory);
+ String controllerName = controllerSelectionReference.getControllerName();
+
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ String sdncVfModuleQueryResponse = execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId());
+
+ Map<String, String> paramsMap = new HashMap<>();
+ RequestParametersConfigScaleOut requestParameters = new RequestParametersConfigScaleOut();
+ String configScaleOutParam = null;
+ if (jsonPathForCfgParams != null) {
+ for (Map<String, String> param : jsonPathForCfgParams) {
+ for (Map.Entry<String, String> entry : param.entrySet()) {
+ key = entry.getKey();
+ paramValue = entry.getValue();
+ try {
+ configScaleOutParam = JsonPath.parse(sdncVfModuleQueryResponse).read(paramValue);
+ } catch (ClassCastException e) {
+ configScaleOutParam = null;
+ logger.warn("Incorrect JSON path. Path points to object rather than value causing: ", e);
+ }
+ paramsMap.put(key, configScaleOutParam);
+ }
+ }
+ }
+ requestParameters.setVfModuleId(vfModule.getVfModuleId());
+ requestParameters.setVnfHostIpAddress(vnf.getIpv4OamAddress());
+ configPayload.setConfigurationParameters(paramsMap);
+ configPayload.setRequestParameters(requestParameters);
+ configScaleOutPayloadString = mapper.writeValueAsString(configPayload);
+
+ execution.setVariable(ACTION, actionCategory);
+ execution.setVariable(MSO_REQUEST_ID, gBBInput.getRequestContext().getMsoRequestId());
+ execution.setVariable(VNF_ID, vnfId);
+ execution.setVariable(VNF_NAME, vnfName);
+ execution.setVariable(VFMODULE_ID, vfModule.getVfModuleId());
+ execution.setVariable(CONTROLLER_TYPE, controllerName);
+ execution.setVariable(PAYLOAD, configScaleOutPayloadString);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void callAppcClient(BuildingBlockExecution execution) {
+ logger.trace("Start runAppcCommand ");
+ String appcCode = "1002";
+ String appcMessage = "";
+ try {
+ Action commandAction = Action.valueOf(execution.getVariable(ACTION));
+ String msoRequestId = execution.getVariable(MSO_REQUEST_ID);
+ String vnfId = execution.getVariable(VNF_ID);
+ Optional<String> payloadString = null;
+ if (execution.getVariable(PAYLOAD) != null) {
+ String pay = execution.getVariable(PAYLOAD);
+ payloadString = Optional.of(pay);
+ }
+ String controllerType = execution.getVariable(CONTROLLER_TYPE);
+ HashMap<String, String> payloadInfo = new HashMap<>();
+ payloadInfo.put(VNF_NAME, execution.getVariable(VNF_NAME));
+ payloadInfo.put(VFMODULE_ID, execution.getVariable(VFMODULE_ID));
+ logger.debug("Running APP-C action: {}", commandAction.toString());
+ logger.debug("VNFID: {}", vnfId);
+ // PayloadInfo contains extra information that adds on to payload before making request to appc
+ appCClient.runAppCCommand(commandAction, msoRequestId, vnfId, payloadString, payloadInfo, controllerType);
+ appcCode = appCClient.getErrorCode();
+ appcMessage = appCClient.getErrorMessage();
+
+ } catch (Exception e) {
+ logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(),
+ "Caught exception in runAppcCommand in ConfigurationScaleOut", "BPMN",
+ ErrorCode.UnknownError.getValue(), "APPC Error", e);
+ appcMessage = e.getMessage();
+ }
+ logger.error("Error Message: " + appcMessage);
+ logger.error("ERROR CODE: " + appcCode);
+ logger.trace("End of runAppCommand ");
+ if (appcCode != null && !appcCode.equals("0")) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java
index 8cad8f93ec..c2d9c6e7bb 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java
@@ -22,7 +22,6 @@
package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
import java.util.Map;
-
import org.onap.so.adapters.nwrest.CreateNetworkRequest;
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network;
@@ -40,32 +39,35 @@ import org.springframework.stereotype.Component;
@Component
public class CreateNetwork {
- private static final Logger logger = LoggerFactory.getLogger(CreateNetwork.class);
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private NetworkAdapterObjectMapper networkAdapterObjectMapper;
-
- /**
- * BPMN access method to build CreateNetworkRequest object
- *
- */
- public void buildCreateNetworkRequest(BuildingBlockExecution execution) throws Exception {
- try{
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- Map<String, String> userInput = gBBInput.getUserInput();
- String cloudRegionPo = execution.getVariable("cloudRegionPo");
-
- CreateNetworkRequest createNetworkRequest = networkAdapterObjectMapper.createNetworkRequestMapper(gBBInput.getRequestContext(), gBBInput.getCloudRegion(), gBBInput.getOrchContext(), serviceInstance, l3Network, userInput, cloudRegionPo, gBBInput.getCustomer());
-
- //set CreateNetowrkRequest object on execution to be re-used within current BB
- execution.setVariable("createNetworkRequest", createNetworkRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(CreateNetwork.class);
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private NetworkAdapterObjectMapper networkAdapterObjectMapper;
+
+ /**
+ * BPMN access method to build CreateNetworkRequest object
+ *
+ */
+ public void buildCreateNetworkRequest(BuildingBlockExecution execution) throws Exception {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ Map<String, String> userInput = gBBInput.getUserInput();
+ String cloudRegionPo = execution.getVariable("cloudRegionPo");
+
+ CreateNetworkRequest createNetworkRequest = networkAdapterObjectMapper.createNetworkRequestMapper(
+ gBBInput.getRequestContext(), gBBInput.getCloudRegion(), gBBInput.getOrchContext(), serviceInstance,
+ l3Network, userInput, cloudRegionPo, gBBInput.getCustomer());
+
+ // set CreateNetowrkRequest object on execution to be re-used within current BB
+ execution.setVariable("createNetworkRequest", createNetworkRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java
index 5665302b2a..4eaec381e9 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java
@@ -36,94 +36,107 @@ import org.springframework.stereotype.Component;
@Component
public class CreateNetworkCollection {
- private static final Logger logger = LoggerFactory.getLogger(CreateNetworkCollection.class);
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private AAINetworkResources aaiNetworkResources;
+ private static final Logger logger = LoggerFactory.getLogger(CreateNetworkCollection.class);
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private AAINetworkResources aaiNetworkResources;
- private static final String UNDERSCORE = "_";
- private static final String NETWORK_COLLECTION_NAME = "networkCollectionName";
-
- /**
- * BPMN access method to build Network Collection Name
- * @param execution
- * @throws Exception
- */
- public void buildNetworkCollectionName(BuildingBlockExecution execution) throws Exception {
- try{
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- InstanceGroup instanceGroup = serviceInstance.getCollection().getInstanceGroup();
- if(instanceGroup.getModelInfoInstanceGroup() != null) {
- //Build collection name assembling SI name and IG function
- if(serviceInstance.getServiceInstanceName() != null
- && instanceGroup.getModelInfoInstanceGroup().getFunction() != null) {
- String networkCollectionName = serviceInstance.getServiceInstanceName().concat(UNDERSCORE).concat(instanceGroup.getModelInfoInstanceGroup().getFunction());
- //set networkCollectionName object on execution to be re-used within current BB
- execution.setVariable(NETWORK_COLLECTION_NAME, networkCollectionName);
- } else {
- throw new IllegalArgumentException("Cannot generate collection name because either one or both fields are null: "
- + " Service Instance Name: " + serviceInstance.getServiceInstanceName()
- + ", Instance Group Function: " + instanceGroup.getModelInfoInstanceGroup().getFunction());
- }
- } else {
- throw new IllegalArgumentException("Instance group model info is null");
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to connect Network Collection
- * @param execution
- * @throws Exception
- */
- public void connectCollectionToInstanceGroup(BuildingBlockExecution execution) throws Exception {
- execution.setVariable("connectCollectionToInstanceGroupRollback", false);
- try{
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Collection networkCollection = serviceInstance.getCollection();
- aaiNetworkResources.connectNetworkCollectionInstanceGroupToNetworkCollection(networkCollection.getInstanceGroup(), networkCollection);
- execution.setVariable("connectCollectionToInstanceGroupRollback", true);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to connect Instance Group to Cloud Region
- * @param execution
- * @throws Exception
- */
- public void connectInstanceGroupToCloudRegion(BuildingBlockExecution execution) throws Exception {
- execution.setVariable("connectInstanceGroupToCloudRegionRollback", false);
- try{
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Collection networkCollection = serviceInstance.getCollection();
- aaiNetworkResources.connectInstanceGroupToCloudRegion(networkCollection.getInstanceGroup(), execution.getGeneralBuildingBlock().getCloudRegion());
- execution.setVariable("connectInstanceGroupToCloudRegionRollback", true);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to connect Network Collection
- * @param execution
- * @throws Exception
- */
- public void connectCollectionToServiceInstance(BuildingBlockExecution execution) throws Exception {
- execution.setVariable("connectCollectionToServiceInstanceRollback", false);
- try{
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Collection networkCollection = serviceInstance.getCollection();
- aaiNetworkResources.connectNetworkCollectionToServiceInstance(networkCollection, serviceInstance);
- execution.setVariable("connectCollectionToServiceInstanceRollback", true);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ private static final String UNDERSCORE = "_";
+ private static final String NETWORK_COLLECTION_NAME = "networkCollectionName";
+
+ /**
+ * BPMN access method to build Network Collection Name
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void buildNetworkCollectionName(BuildingBlockExecution execution) throws Exception {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ InstanceGroup instanceGroup = serviceInstance.getCollection().getInstanceGroup();
+ if (instanceGroup.getModelInfoInstanceGroup() != null) {
+ // Build collection name assembling SI name and IG function
+ if (serviceInstance.getServiceInstanceName() != null
+ && instanceGroup.getModelInfoInstanceGroup().getFunction() != null) {
+ String networkCollectionName = serviceInstance.getServiceInstanceName().concat(UNDERSCORE)
+ .concat(instanceGroup.getModelInfoInstanceGroup().getFunction());
+ // set networkCollectionName object on execution to be re-used within current BB
+ execution.setVariable(NETWORK_COLLECTION_NAME, networkCollectionName);
+ } else {
+ throw new IllegalArgumentException(
+ "Cannot generate collection name because either one or both fields are null: "
+ + " Service Instance Name: " + serviceInstance.getServiceInstanceName()
+ + ", Instance Group Function: "
+ + instanceGroup.getModelInfoInstanceGroup().getFunction());
+ }
+ } else {
+ throw new IllegalArgumentException("Instance group model info is null");
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to connect Network Collection
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void connectCollectionToInstanceGroup(BuildingBlockExecution execution) throws Exception {
+ execution.setVariable("connectCollectionToInstanceGroupRollback", false);
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Collection networkCollection = serviceInstance.getCollection();
+ aaiNetworkResources.connectNetworkCollectionInstanceGroupToNetworkCollection(
+ networkCollection.getInstanceGroup(), networkCollection);
+ execution.setVariable("connectCollectionToInstanceGroupRollback", true);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to connect Instance Group to Cloud Region
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void connectInstanceGroupToCloudRegion(BuildingBlockExecution execution) throws Exception {
+ execution.setVariable("connectInstanceGroupToCloudRegionRollback", false);
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Collection networkCollection = serviceInstance.getCollection();
+ aaiNetworkResources.connectInstanceGroupToCloudRegion(networkCollection.getInstanceGroup(),
+ execution.getGeneralBuildingBlock().getCloudRegion());
+ execution.setVariable("connectInstanceGroupToCloudRegionRollback", true);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to connect Network Collection
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void connectCollectionToServiceInstance(BuildingBlockExecution execution) throws Exception {
+ execution.setVariable("connectCollectionToServiceInstanceRollback", false);
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Collection networkCollection = serviceInstance.getCollection();
+ aaiNetworkResources.connectNetworkCollectionToServiceInstance(networkCollection, serviceInstance);
+ execution.setVariable("connectCollectionToServiceInstanceRollback", true);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java
index f0db5eda2e..98b602eca1 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java
@@ -44,98 +44,97 @@ import org.springframework.stereotype.Component;
@Component
public class GenericVnfHealthCheck {
- private static final Logger logger = LoggerFactory.getLogger(GenericVnfHealthCheck.class);
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private CatalogDbClient catalogDbClient;
- @Autowired
- private ApplicationControllerAction appCClient;
-
- public void setParamsForGenericVnfHealthCheck(BuildingBlockExecution execution) {
-
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ private static final Logger logger = LoggerFactory.getLogger(GenericVnfHealthCheck.class);
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+ @Autowired
+ private ApplicationControllerAction appCClient;
- try {
- ControllerSelectionReference controllerSelectionReference;
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- String vnfId = vnf.getVnfId();
- String vnfName = vnf.getVnfName();
- String vnfType = vnf.getVnfType();
- String oamIpAddress = vnf.getIpv4OamAddress();
- String actionCategory = Action.HealthCheck.toString();
- controllerSelectionReference = catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory(vnfType, actionCategory);
- String controllerName = controllerSelectionReference.getControllerName();
-
- execution.setVariable("vnfId", vnfId);
- execution.setVariable("vnfName", vnfName);
- execution.setVariable("oamIpAddress", oamIpAddress);
- execution.setVariable("vnfHostIpAddress", oamIpAddress);
- execution.setVariable("msoRequestId", gBBInput.getRequestContext().getMsoRequestId());
- execution.setVariable("action", actionCategory);
- execution.setVariable("controllerType", controllerName);
-
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void callAppcClient(BuildingBlockExecution execution) {
- logger.trace("Start runAppcCommand ");
- String appcCode = "1002";
- String appcMessage = "";
- try {
- Action action = null;
- action = Action.valueOf(execution.getVariable("action"));
- String msoRequestId = execution.getVariable("msoRequestId");
- String vnfId = execution.getVariable("vnfId");
- Optional<String> payload = null;
- if(execution.getVariable("payload") != null){
- String pay = execution.getVariable("payload");
- payload = Optional.of(pay);
- }
- String controllerType = execution.getVariable("controllerType");
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", execution.getVariable("vnfName"));
- payloadInfo.put("vfModuleId",execution.getVariable("vfModuleId"));
- payloadInfo.put("oamIpAddress",execution.getVariable("oamIpAddress"));
- payloadInfo.put("vnfHostIpAddress",execution.getVariable("vnfHostIpAddress"));
-
- logger.debug("Running APP-C action: {}", action.toString());
- logger.debug("VNFID: {}", vnfId);
- //PayloadInfo contains extra information that adds on to payload before making request to appc
- appCClient.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
- appcCode = appCClient.getErrorCode();
- appcMessage = appCClient.getErrorMessage();
+ public void setParamsForGenericVnfHealthCheck(BuildingBlockExecution execution) {
+
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+
+ try {
+ ControllerSelectionReference controllerSelectionReference;
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ String vnfId = vnf.getVnfId();
+ String vnfName = vnf.getVnfName();
+ String vnfType = vnf.getVnfType();
+ String oamIpAddress = vnf.getIpv4OamAddress();
+ String actionCategory = Action.HealthCheck.toString();
+ controllerSelectionReference =
+ catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory(vnfType, actionCategory);
+ String controllerName = controllerSelectionReference.getControllerName();
+
+ execution.setVariable("vnfId", vnfId);
+ execution.setVariable("vnfName", vnfName);
+ execution.setVariable("oamIpAddress", oamIpAddress);
+ execution.setVariable("vnfHostIpAddress", oamIpAddress);
+ execution.setVariable("msoRequestId", gBBInput.getRequestContext().getMsoRequestId());
+ execution.setVariable("action", actionCategory);
+ execution.setVariable("controllerType", controllerName);
+
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void callAppcClient(BuildingBlockExecution execution) {
+ logger.trace("Start runAppcCommand ");
+ String appcCode = "1002";
+ String appcMessage = "";
+ try {
+ Action action = null;
+ action = Action.valueOf(execution.getVariable("action"));
+ String msoRequestId = execution.getVariable("msoRequestId");
+ String vnfId = execution.getVariable("vnfId");
+ Optional<String> payload = null;
+ if (execution.getVariable("payload") != null) {
+ String pay = execution.getVariable("payload");
+ payload = Optional.of(pay);
+ }
+ String controllerType = execution.getVariable("controllerType");
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", execution.getVariable("vnfName"));
+ payloadInfo.put("vfModuleId", execution.getVariable("vfModuleId"));
+ payloadInfo.put("oamIpAddress", execution.getVariable("oamIpAddress"));
+ payloadInfo.put("vnfHostIpAddress", execution.getVariable("vnfHostIpAddress"));
+
+ logger.debug("Running APP-C action: {}", action.toString());
+ logger.debug("VNFID: {}", vnfId);
+ // PayloadInfo contains extra information that adds on to payload before making request to appc
+ appCClient.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType);
+ appcCode = appCClient.getErrorCode();
+ appcMessage = appCClient.getErrorMessage();
} catch (BpmnError ex) {
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
- "Caught exception in GenericVnfHealthCheck", "BPMN", ErrorCode.UnknownError.getValue(), ex);
- appcMessage = ex.getMessage();
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
+ "Caught exception in GenericVnfHealthCheck", "BPMN", ErrorCode.UnknownError.getValue(), ex);
+ appcMessage = ex.getMessage();
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage);
+ } catch (Exception e) {
+ if (e instanceof java.util.concurrent.TimeoutException) {
+ appcMessage = "Request to APPC timed out. ";
+ logger.error("{} {} {} {} {}", MessageEnum.RA_CONNECTION_EXCEPTION.toString(),
+ "Caught timedOut exception in runAppcCommand in GenericVnfHealthCheck", "BPMN",
+ ErrorCode.UnknownError.getValue(), "APPC Error", e);
+ throw e;
+ } else {
+ logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(),
+ "Caught exception in runAppcCommand in GenericVnfHealthCheck", "BPMN",
+ ErrorCode.UnknownError.getValue(), "APPC Error", e);
+ appcMessage = e.getMessage();
+ exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage);
+ }
+ }
+ logger.error("Error Message: " + appcMessage);
+ logger.error("ERROR CODE: " + appcCode);
+ logger.trace("End of runAppCommand ");
+ if (appcCode != null && !appcCode.equals("0")) {
exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage);
- } catch (Exception e) {
- if (e instanceof java.util.concurrent.TimeoutException )
- {
- appcMessage = "Request to APPC timed out. ";
- logger.error("{} {} {} {} {}", MessageEnum.RA_CONNECTION_EXCEPTION.toString(),
- "Caught timedOut exception in runAppcCommand in GenericVnfHealthCheck", "BPMN",
- ErrorCode.UnknownError.getValue(), "APPC Error", e);
- throw e;
- }
- else {
- logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(),
- "Caught exception in runAppcCommand in GenericVnfHealthCheck", "BPMN",
- ErrorCode.UnknownError.getValue(), "APPC Error", e);
- appcMessage = e.getMessage();
- exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage);
- }
- }
- logger.error("Error Message: " + appcMessage);
- logger.error("ERROR CODE: " + appcCode);
- logger.trace("End of runAppCommand ");
- if (appcCode != null && !appcCode.equals("0")) {
- exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage);
- }
- }
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/NetworkBBUtils.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/NetworkBBUtils.java
index 217a60b60a..7ab53cb506 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/NetworkBBUtils.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/NetworkBBUtils.java
@@ -22,53 +22,56 @@ package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
import java.util.List;
import java.util.Optional;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
import org.springframework.stereotype.Component;
@Component
-public class NetworkBBUtils {
-
- private static final String CLOUD_REGION_VER25 = "2.5";
- private static final String CLOUD_REGION_AAIAIC25 = "AAIAIC25";
-
- /**
- * BPMN access method to check if Relationship's Related-To value exists.
- *
- * @param l3Network - L3Network object
- * @param relatedToValue - String, ex: 'vf-module'
- * @return boolean
- */
- public boolean isRelationshipRelatedToExists(Optional<org.onap.aai.domain.yang.L3Network> l3network, String relatedToValue) {
- boolean isRelatedToExists = false;
- if (l3network.isPresent()) {
- List<org.onap.aai.domain.yang.Relationship> relationshipList = l3network.get().getRelationshipList().getRelationship();
- for (org.onap.aai.domain.yang.Relationship relationship : relationshipList) {
- if (relationship.getRelatedTo().equals(relatedToValue)) {
- isRelatedToExists = true;
- break;
- }
- }
- }
- return isRelatedToExists;
- }
-
- /**
- * BPMN access method to extract Cloud Region data
- * @param execution
- * @param motsValue (ex: SourceSystem.SDNC or SourceSystem.PO)
- */
- public String getCloudRegion(BuildingBlockExecution execution, SourceSystem sourceValue) {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- String cloudRegionId = cloudRegion.getLcpCloudRegionId();
- if (sourceValue.equals(SourceSystem.SDNC) && CLOUD_REGION_VER25.equalsIgnoreCase(cloudRegion.getCloudRegionVersion())) {
- cloudRegionId = CLOUD_REGION_AAIAIC25;
- }
- return cloudRegionId;
- }
-
-
+public class NetworkBBUtils {
+
+ private static final String CLOUD_REGION_VER25 = "2.5";
+ private static final String CLOUD_REGION_AAIAIC25 = "AAIAIC25";
+
+ /**
+ * BPMN access method to check if Relationship's Related-To value exists.
+ *
+ * @param l3Network - L3Network object
+ * @param relatedToValue - String, ex: 'vf-module'
+ * @return boolean
+ */
+ public boolean isRelationshipRelatedToExists(Optional<org.onap.aai.domain.yang.L3Network> l3network,
+ String relatedToValue) {
+ boolean isRelatedToExists = false;
+ if (l3network.isPresent()) {
+ List<org.onap.aai.domain.yang.Relationship> relationshipList =
+ l3network.get().getRelationshipList().getRelationship();
+ for (org.onap.aai.domain.yang.Relationship relationship : relationshipList) {
+ if (relationship.getRelatedTo().equals(relatedToValue)) {
+ isRelatedToExists = true;
+ break;
+ }
+ }
+ }
+ return isRelatedToExists;
+ }
+
+ /**
+ * BPMN access method to extract Cloud Region data
+ *
+ * @param execution
+ * @param motsValue (ex: SourceSystem.SDNC or SourceSystem.PO)
+ */
+ public String getCloudRegion(BuildingBlockExecution execution, SourceSystem sourceValue) {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ String cloudRegionId = cloudRegion.getLcpCloudRegionId();
+ if (sourceValue.equals(SourceSystem.SDNC)
+ && CLOUD_REGION_VER25.equalsIgnoreCase(cloudRegion.getCloudRegionVersion())) {
+ cloudRegionId = CLOUD_REGION_AAIAIC25;
+ }
+ return cloudRegionId;
+ }
+
+
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SourceSystem.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SourceSystem.java
index 596b280916..0f545b9145 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SourceSystem.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SourceSystem.java
@@ -21,6 +21,5 @@
package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
public enum SourceSystem {
- PO,
- SDNC
+ PO, SDNC
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java
index 9a7d695c01..27415190cc 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java
@@ -23,7 +23,6 @@
package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
import java.util.Optional;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network;
import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
@@ -39,80 +38,83 @@ import org.springframework.stereotype.Component;
@Component
public class UnassignNetworkBB {
- private static final Logger logger = LoggerFactory.getLogger(UnassignNetworkBB.class);
-
- private static String MESSAGE_CANNOT_PERFORM_UNASSIGN = "Cannot perform Unassign Network. Network is still related to ";
- private static String MESSAGE_ERROR_ROLLBACK = " Rollback is not possible. Please restore data manually.";
-
- @Autowired
- private ExceptionBuilder exceptionUtil;
-
- @Autowired
- private NetworkBBUtils networkBBUtils;
-
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
-
- @Autowired
- private AAINetworkResources aaiNetworkResources;
-
- /**
- * BPMN access method to prepare overall error messages.
- *
- * @param execution - BuildingBlockExecution
- * @param relatedToValue - String, ex: vf-module
- * @return void - nothing
- * @throws Exception
- */
-
- public void checkRelationshipRelatedTo(BuildingBlockExecution execution, String relatedToValue) throws Exception {
- try {
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
- Optional<org.onap.aai.domain.yang.L3Network> network = aaiResultWrapper.asBean(org.onap.aai.domain.yang.L3Network.class);
- if (networkBBUtils.isRelationshipRelatedToExists(network, relatedToValue)) {
- String msg = MESSAGE_CANNOT_PERFORM_UNASSIGN + relatedToValue;
- execution.setVariable("ErrorUnassignNetworkBB", msg);
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to getCloudRegionId
- *
- * @param execution - BuildingBlockExecution
- * @return void - nothing
- * @throws Exception
- */
-
- public void getCloudSdncRegion(BuildingBlockExecution execution) throws Exception {
- try {
- String cloudRegionSdnc = networkBBUtils.getCloudRegion(execution, SourceSystem.SDNC);
- execution.setVariable("cloudRegionSdnc", cloudRegionSdnc);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to prepare overall error messages.
- *
- * @param execution - BuildingBlockExecution
- * @return void - nothing
- */
- public void errorEncountered(BuildingBlockExecution execution) {
- String msg;
- boolean isRollbackNeeded = execution.getVariable("isRollbackNeeded") != null ? execution.getVariable("isRollbackNeeded") : false;
- if (isRollbackNeeded == true) {
- msg = execution.getVariable("ErrorUnassignNetworkBB") + MESSAGE_ERROR_ROLLBACK;
- } else {
- msg = execution.getVariable("ErrorUnassignNetworkBB");
- }
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
- }
-
-
+ private static final Logger logger = LoggerFactory.getLogger(UnassignNetworkBB.class);
+
+ private static String MESSAGE_CANNOT_PERFORM_UNASSIGN =
+ "Cannot perform Unassign Network. Network is still related to ";
+ private static String MESSAGE_ERROR_ROLLBACK = " Rollback is not possible. Please restore data manually.";
+
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+
+ @Autowired
+ private NetworkBBUtils networkBBUtils;
+
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+
+ @Autowired
+ private AAINetworkResources aaiNetworkResources;
+
+ /**
+ * BPMN access method to prepare overall error messages.
+ *
+ * @param execution - BuildingBlockExecution
+ * @param relatedToValue - String, ex: vf-module
+ * @return void - nothing
+ * @throws Exception
+ */
+
+ public void checkRelationshipRelatedTo(BuildingBlockExecution execution, String relatedToValue) throws Exception {
+ try {
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
+ Optional<org.onap.aai.domain.yang.L3Network> network =
+ aaiResultWrapper.asBean(org.onap.aai.domain.yang.L3Network.class);
+ if (networkBBUtils.isRelationshipRelatedToExists(network, relatedToValue)) {
+ String msg = MESSAGE_CANNOT_PERFORM_UNASSIGN + relatedToValue;
+ execution.setVariable("ErrorUnassignNetworkBB", msg);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to getCloudRegionId
+ *
+ * @param execution - BuildingBlockExecution
+ * @return void - nothing
+ * @throws Exception
+ */
+
+ public void getCloudSdncRegion(BuildingBlockExecution execution) throws Exception {
+ try {
+ String cloudRegionSdnc = networkBBUtils.getCloudRegion(execution, SourceSystem.SDNC);
+ execution.setVariable("cloudRegionSdnc", cloudRegionSdnc);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to prepare overall error messages.
+ *
+ * @param execution - BuildingBlockExecution
+ * @return void - nothing
+ */
+ public void errorEncountered(BuildingBlockExecution execution) {
+ String msg;
+ boolean isRollbackNeeded =
+ execution.getVariable("isRollbackNeeded") != null ? execution.getVariable("isRollbackNeeded") : false;
+ if (isRollbackNeeded == true) {
+ msg = execution.getVariable("ErrorUnassignNetworkBB") + MESSAGE_ERROR_ROLLBACK;
+ } else {
+ msg = execution.getVariable("ErrorUnassignNetworkBB");
+ }
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
+
+
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnf.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnf.java
index afa9b439db..e51774c12c 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnf.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnf.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
import java.util.List;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.infrastructure.common.name.generation.AAIObjectInstanceNameGenerator;
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
@@ -37,27 +36,27 @@ import org.springframework.stereotype.Component;
@Component()
public class UnassignVnf {
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private AAIInstanceGroupResources aaiInstanceGroupResources;
- @Autowired
- private AAIObjectInstanceNameGenerator aaiObjectInstanceNameGenerator;
-
- public void deleteInstanceGroups(BuildingBlockExecution execution) {
- try {
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- List<InstanceGroup> instanceGroups = vnf.getInstanceGroups();
- for(InstanceGroup instanceGroup : instanceGroups) {
- if(ModelInfoInstanceGroup.TYPE_VNFC.equalsIgnoreCase(instanceGroup.getModelInfoInstanceGroup().getType())) {
- aaiInstanceGroupResources.deleteInstanceGroup(instanceGroup);
- }
- }
- }
- catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private AAIInstanceGroupResources aaiInstanceGroupResources;
+ @Autowired
+ private AAIObjectInstanceNameGenerator aaiObjectInstanceNameGenerator;
+
+ public void deleteInstanceGroups(BuildingBlockExecution execution) {
+ try {
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ List<InstanceGroup> instanceGroups = vnf.getInstanceGroups();
+ for (InstanceGroup instanceGroup : instanceGroups) {
+ if (ModelInfoInstanceGroup.TYPE_VNFC
+ .equalsIgnoreCase(instanceGroup.getModelInfoInstanceGroup().getType())) {
+ aaiInstanceGroupResources.deleteInstanceGroup(instanceGroup);
+ }
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasks.java
index 9214635602..b906b8a662 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasks.java
@@ -2,7 +2,6 @@ package org.onap.so.bpmn.infrastructure.manualhandling.tasks;
import java.util.Map;
import java.util.HashMap;
-
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateTask;
@@ -20,185 +19,188 @@ import org.springframework.stereotype.Component;
@Component
public class ManualHandlingTasks {
- private static final Logger logger = LoggerFactory.getLogger(ManualHandlingTasks.class);
-
- private static final String TASK_TYPE_PAUSE = "pause";
- private static final String TASK_TYPE_FALLOUT = "fallout";
-
- @Autowired
- private ExceptionBuilder exceptionUtil;
-
- @Autowired
- private RequestsDbClient requestDbclient;
-
- public void setFalloutTaskVariables (DelegateTask task) {
-
- DelegateExecution execution = task.getExecution();
- try {
- String taskId = task.getId();
- logger.debug("taskId is: " + taskId);
- String type = TASK_TYPE_FALLOUT;
- String nfRole = (String) execution.getVariable("vnfType");
- String subscriptionServiceType = (String) execution.getVariable("serviceType");
- String originalRequestId = (String) execution.getVariable("msoRequestId");
- String originalRequestorId = (String) execution.getVariable("requestorId");
- String description = "";
- String timeout = "";
- String errorSource = (String) execution.getVariable("failedActivity");
- String errorCode = (String) execution.getVariable("errorCode");
- String errorMessage = (String) execution.getVariable("errorText");
- String buildingBlockName = (String) execution.getVariable("currentActivity");
- String buildingBlockStep = (String) execution.getVariable("workStep");
- String validResponses = (String) execution.getVariable("validResponses");
-
- Map<String, String> taskVariables = new HashMap<String, String>();
- taskVariables.put("type", type);
- taskVariables.put("nfRole", nfRole);
- taskVariables.put("subscriptionServiceType", subscriptionServiceType);
- taskVariables.put("originalRequestId", originalRequestId);
- taskVariables.put("originalRequestorId", originalRequestorId);
- taskVariables.put("errorSource", errorSource);
- taskVariables.put("errorCode", errorCode);
- taskVariables.put("errorMessage", errorMessage);
- taskVariables.put("buildingBlockName", buildingBlockName);
- taskVariables.put("buildingBlockStep", buildingBlockStep);
- taskVariables.put("validResponses", validResponses);
- taskVariables.put("tmeout", timeout);
- taskVariables.put("description", description);
- TaskService taskService = execution.getProcessEngineServices().getTaskService();
-
- taskService.setVariables(taskId, taskVariables);
- logger.debug("successfully created fallout task: "+ taskId);
- } catch (BpmnError e) {
- logger.debug("BPMN exception: " + e.getMessage());
- throw e;
- } catch (Exception ex){
- String msg = "Exception in setFalloutTaskVariables " + ex.getMessage();
- logger.debug(msg);
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
- }
- }
-
- public void setPauseTaskVariables (DelegateTask task) {
-
- DelegateExecution execution = task.getExecution();
-
- try {
- String taskId = task.getId();
- logger.debug("taskId is: " + taskId);
- String type = TASK_TYPE_PAUSE;
- String nfRole = (String) execution.getVariable("vnfType");
- String subscriptionServiceType = (String) execution.getVariable("serviceType");
- String originalRequestId = (String) execution.getVariable("msoRequestId");
- String originalRequestorId = (String) execution.getVariable("requestorId");
- String description = (String) execution.getVariable("description");
- String timeout = (String) execution.getVariable("taskTimeout");
- String errorSource = "";
- String errorCode = "";
- String errorMessage = "";
- String buildingBlockName = "";
- String buildingBlockStep = "";
- String validResponses = (String) execution.getVariable("validResponses");
-
- Map<String, String> taskVariables = new HashMap<String, String>();
- taskVariables.put("type", type);
- taskVariables.put("nfRole", nfRole);
- taskVariables.put("description", description);
- taskVariables.put("timeout", timeout);
- taskVariables.put("subscriptionServiceType", subscriptionServiceType);
- taskVariables.put("originalRequestId", originalRequestId);
- taskVariables.put("originalRequestorId", originalRequestorId);
- taskVariables.put("errorSource", errorSource);
- taskVariables.put("errorCode", errorCode);
- taskVariables.put("errorMessage", errorMessage);
- taskVariables.put("buildingBlockName", buildingBlockName);
- taskVariables.put("buildingBlockStep", buildingBlockStep);
- taskVariables.put("validResponses", validResponses);
- TaskService taskService = execution.getProcessEngineServices().getTaskService();
-
- taskService.setVariables(taskId, taskVariables);
- logger.debug("successfully created pause task: "+ taskId);
- } catch (BpmnError e) {
- logger.debug("BPMN exception: " + e.getMessage());
- throw e;
- } catch (Exception ex){
- String msg = "Exception in setPauseTaskVariables " + ex.getMessage();
- logger.debug(msg);
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
- }
-
- }
-
- public void completeTask (DelegateTask task) {
-
- DelegateExecution execution = task.getExecution();
-
- try {
-
- String taskId = task.getId();
- logger.debug("taskId is: " + taskId);
- TaskService taskService = execution.getProcessEngineServices().getTaskService();
-
- Map<String, Object> taskVariables = taskService.getVariables(taskId);
- String responseValue = (String) taskVariables.get("responseValue");
-
- logger.debug("Received responseValue on completion: "+ responseValue);
- // Have to set the first letter of the response to upper case
- String responseValueUppercaseStart = responseValue.substring(0, 1).toUpperCase() + responseValue.substring(1);
- logger.debug("ResponseValue to taskListener: "+ responseValueUppercaseStart);
- execution.setVariable("responseValueTask", responseValueUppercaseStart);
-
- } catch (BpmnError e) {
- logger.debug("BPMN exception: " + e.getMessage());
- throw e;
- } catch (Exception ex){
- String msg = "Exception in completeManualTask " + ex.getMessage();
- logger.debug(msg);
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
- }
-
- }
-
- public void createExternalTicket (DelegateExecution execution) {
-
- try {
- ExternalTicket ticket = new ExternalTicket();
-
- ticket.setRequestId((String) execution.getVariable("msoRequestId"));
- ticket.setCurrentActivity((String) execution.getVariable("currentActivity"));
- ticket.setNfRole((String) execution.getVariable("vnfType"));
- ticket.setDescription((String) execution.getVariable("description"));
- ticket.setSubscriptionServiceType((String) execution.getVariable("serviceType"));
- ticket.setRequestorId((String) execution.getVariable("requestorId"));
- ticket.setTimeout((String) execution.getVariable("taskTimeout"));
- ticket.setErrorSource((String) execution.getVariable("failedActivity"));
- ticket.setErrorCode((String) execution.getVariable("errorCode"));
- ticket.setErrorMessage((String) execution.getVariable("errorText"));
- ticket.setWorkStep((String) execution.getVariable("workStep"));
-
- ticket.createTicket();
- } catch (BpmnError e) {
- String msg = "BPMN error in createAOTSTicket " + e.getMessage();
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", ErrorCode.UnknownError.getValue());
- } catch (Exception ex){
- String msg = "Exception in createExternalTicket " + ex.getMessage();
- logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", ErrorCode.UnknownError.getValue());
- }
-
- }
-
- public void updateRequestDbStatus(DelegateExecution execution, String status) {
- try {
- String requestId = (String) execution.getVariable("msoRequestId");
- InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
-
- request.setRequestStatus(status);
- request.setLastModifiedBy("ManualHandling");
-
- requestDbclient.updateInfraActiveRequests(request);
- } catch (Exception e) {
- logger.error("Unable to save the updated request status to the DB",e);
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(ManualHandlingTasks.class);
+
+ private static final String TASK_TYPE_PAUSE = "pause";
+ private static final String TASK_TYPE_FALLOUT = "fallout";
+
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+
+ @Autowired
+ private RequestsDbClient requestDbclient;
+
+ public void setFalloutTaskVariables(DelegateTask task) {
+
+ DelegateExecution execution = task.getExecution();
+ try {
+ String taskId = task.getId();
+ logger.debug("taskId is: " + taskId);
+ String type = TASK_TYPE_FALLOUT;
+ String nfRole = (String) execution.getVariable("vnfType");
+ String subscriptionServiceType = (String) execution.getVariable("serviceType");
+ String originalRequestId = (String) execution.getVariable("msoRequestId");
+ String originalRequestorId = (String) execution.getVariable("requestorId");
+ String description = "";
+ String timeout = "";
+ String errorSource = (String) execution.getVariable("failedActivity");
+ String errorCode = (String) execution.getVariable("errorCode");
+ String errorMessage = (String) execution.getVariable("errorText");
+ String buildingBlockName = (String) execution.getVariable("currentActivity");
+ String buildingBlockStep = (String) execution.getVariable("workStep");
+ String validResponses = (String) execution.getVariable("validResponses");
+
+ Map<String, String> taskVariables = new HashMap<String, String>();
+ taskVariables.put("type", type);
+ taskVariables.put("nfRole", nfRole);
+ taskVariables.put("subscriptionServiceType", subscriptionServiceType);
+ taskVariables.put("originalRequestId", originalRequestId);
+ taskVariables.put("originalRequestorId", originalRequestorId);
+ taskVariables.put("errorSource", errorSource);
+ taskVariables.put("errorCode", errorCode);
+ taskVariables.put("errorMessage", errorMessage);
+ taskVariables.put("buildingBlockName", buildingBlockName);
+ taskVariables.put("buildingBlockStep", buildingBlockStep);
+ taskVariables.put("validResponses", validResponses);
+ taskVariables.put("tmeout", timeout);
+ taskVariables.put("description", description);
+ TaskService taskService = execution.getProcessEngineServices().getTaskService();
+
+ taskService.setVariables(taskId, taskVariables);
+ logger.debug("successfully created fallout task: " + taskId);
+ } catch (BpmnError e) {
+ logger.debug("BPMN exception: " + e.getMessage());
+ throw e;
+ } catch (Exception ex) {
+ String msg = "Exception in setFalloutTaskVariables " + ex.getMessage();
+ logger.debug(msg);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
+ }
+
+ public void setPauseTaskVariables(DelegateTask task) {
+
+ DelegateExecution execution = task.getExecution();
+
+ try {
+ String taskId = task.getId();
+ logger.debug("taskId is: " + taskId);
+ String type = TASK_TYPE_PAUSE;
+ String nfRole = (String) execution.getVariable("vnfType");
+ String subscriptionServiceType = (String) execution.getVariable("serviceType");
+ String originalRequestId = (String) execution.getVariable("msoRequestId");
+ String originalRequestorId = (String) execution.getVariable("requestorId");
+ String description = (String) execution.getVariable("description");
+ String timeout = (String) execution.getVariable("taskTimeout");
+ String errorSource = "";
+ String errorCode = "";
+ String errorMessage = "";
+ String buildingBlockName = "";
+ String buildingBlockStep = "";
+ String validResponses = (String) execution.getVariable("validResponses");
+
+ Map<String, String> taskVariables = new HashMap<String, String>();
+ taskVariables.put("type", type);
+ taskVariables.put("nfRole", nfRole);
+ taskVariables.put("description", description);
+ taskVariables.put("timeout", timeout);
+ taskVariables.put("subscriptionServiceType", subscriptionServiceType);
+ taskVariables.put("originalRequestId", originalRequestId);
+ taskVariables.put("originalRequestorId", originalRequestorId);
+ taskVariables.put("errorSource", errorSource);
+ taskVariables.put("errorCode", errorCode);
+ taskVariables.put("errorMessage", errorMessage);
+ taskVariables.put("buildingBlockName", buildingBlockName);
+ taskVariables.put("buildingBlockStep", buildingBlockStep);
+ taskVariables.put("validResponses", validResponses);
+ TaskService taskService = execution.getProcessEngineServices().getTaskService();
+
+ taskService.setVariables(taskId, taskVariables);
+ logger.debug("successfully created pause task: " + taskId);
+ } catch (BpmnError e) {
+ logger.debug("BPMN exception: " + e.getMessage());
+ throw e;
+ } catch (Exception ex) {
+ String msg = "Exception in setPauseTaskVariables " + ex.getMessage();
+ logger.debug(msg);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
+
+ }
+
+ public void completeTask(DelegateTask task) {
+
+ DelegateExecution execution = task.getExecution();
+
+ try {
+
+ String taskId = task.getId();
+ logger.debug("taskId is: " + taskId);
+ TaskService taskService = execution.getProcessEngineServices().getTaskService();
+
+ Map<String, Object> taskVariables = taskService.getVariables(taskId);
+ String responseValue = (String) taskVariables.get("responseValue");
+
+ logger.debug("Received responseValue on completion: " + responseValue);
+ // Have to set the first letter of the response to upper case
+ String responseValueUppercaseStart =
+ responseValue.substring(0, 1).toUpperCase() + responseValue.substring(1);
+ logger.debug("ResponseValue to taskListener: " + responseValueUppercaseStart);
+ execution.setVariable("responseValueTask", responseValueUppercaseStart);
+
+ } catch (BpmnError e) {
+ logger.debug("BPMN exception: " + e.getMessage());
+ throw e;
+ } catch (Exception ex) {
+ String msg = "Exception in completeManualTask " + ex.getMessage();
+ logger.debug(msg);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
+
+ }
+
+ public void createExternalTicket(DelegateExecution execution) {
+
+ try {
+ ExternalTicket ticket = new ExternalTicket();
+
+ ticket.setRequestId((String) execution.getVariable("msoRequestId"));
+ ticket.setCurrentActivity((String) execution.getVariable("currentActivity"));
+ ticket.setNfRole((String) execution.getVariable("vnfType"));
+ ticket.setDescription((String) execution.getVariable("description"));
+ ticket.setSubscriptionServiceType((String) execution.getVariable("serviceType"));
+ ticket.setRequestorId((String) execution.getVariable("requestorId"));
+ ticket.setTimeout((String) execution.getVariable("taskTimeout"));
+ ticket.setErrorSource((String) execution.getVariable("failedActivity"));
+ ticket.setErrorCode((String) execution.getVariable("errorCode"));
+ ticket.setErrorMessage((String) execution.getVariable("errorText"));
+ ticket.setWorkStep((String) execution.getVariable("workStep"));
+
+ ticket.createTicket();
+ } catch (BpmnError e) {
+ String msg = "BPMN error in createAOTSTicket " + e.getMessage();
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN",
+ ErrorCode.UnknownError.getValue());
+ } catch (Exception ex) {
+ String msg = "Exception in createExternalTicket " + ex.getMessage();
+ logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN",
+ ErrorCode.UnknownError.getValue());
+ }
+
+ }
+
+ public void updateRequestDbStatus(DelegateExecution execution, String status) {
+ try {
+ String requestId = (String) execution.getVariable("msoRequestId");
+ InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
+
+ request.setRequestStatus(status);
+ request.setLastModifiedBy("ManualHandling");
+
+ requestDbclient.updateInfraActiveRequests(request);
+ } catch (Exception e) {
+ logger.error("Unable to save the updated request status to the DB", e);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java
index 119716a58d..d248ad5443 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java
@@ -32,25 +32,26 @@ import org.springframework.stereotype.Component;
@Component
public class NamingServiceCreateTasks {
-
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
-
- @Autowired
- private NamingServiceResources namingServiceResources;
-
- public void createInstanceGroupName(BuildingBlockExecution execution) throws Exception {
- InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID);
- String policyInstanceName = execution.getVariable("policyInstanceName");
- String nfNamingCode = execution.getVariable("nfNamingCode");
- String generatedInstanceGroupName = "";
- try {
- generatedInstanceGroupName = namingServiceResources.generateInstanceGroupName(instanceGroup, policyInstanceName, nfNamingCode);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- instanceGroup.setInstanceGroupName(generatedInstanceGroupName);
- }
+
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+
+ @Autowired
+ private NamingServiceResources namingServiceResources;
+
+ public void createInstanceGroupName(BuildingBlockExecution execution) throws Exception {
+ InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID);
+ String policyInstanceName = execution.getVariable("policyInstanceName");
+ String nfNamingCode = execution.getVariable("nfNamingCode");
+ String generatedInstanceGroupName = "";
+ try {
+ generatedInstanceGroupName =
+ namingServiceResources.generateInstanceGroupName(instanceGroup, policyInstanceName, nfNamingCode);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ instanceGroup.setInstanceGroupName(generatedInstanceGroupName);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java
index c998e4aa75..9a8c9df8b5 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java
@@ -32,22 +32,22 @@ import org.springframework.stereotype.Component;
@Component
public class NamingServiceDeleteTasks {
-
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
-
- @Autowired
- private NamingServiceResources namingServiceResources;
-
- public void deleteInstanceGroupName(BuildingBlockExecution execution) throws Exception {
- InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID);
-
- try {
- namingServiceResources.deleteInstanceGroupName(instanceGroup);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+
+ @Autowired
+ private NamingServiceResources namingServiceResources;
+
+ public void deleteInstanceGroupName(BuildingBlockExecution execution) throws Exception {
+ InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID);
+
+ try {
+ namingServiceResources.deleteInstanceGroupName(instanceGroup);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/exceptions/SDNCErrorResponseException.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/exceptions/SDNCErrorResponseException.java
index e0f88a20a5..d76d860b3b 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/exceptions/SDNCErrorResponseException.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/exceptions/SDNCErrorResponseException.java
@@ -2,12 +2,12 @@ package org.onap.so.bpmn.infrastructure.sdnc.exceptions;
public class SDNCErrorResponseException extends Exception {
- /**
- *
- */
- private static final long serialVersionUID = 7807799223298140702L;
-
- public SDNCErrorResponseException(String message) {
- super(message);
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = 7807799223298140702L;
+
+ public SDNCErrorResponseException(String message) {
+ super(message);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java
index 31f4b33e0c..7a0008d5a2 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java
@@ -50,80 +50,85 @@ import org.springframework.stereotype.Component;
@Component
public class SDNCActivateTasks {
- private static final Logger logger = LoggerFactory.getLogger(SDNCActivateTasks.class);
- @Autowired
- private SDNCVnfResources sdncVnfResources;
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private SDNCNetworkResources sdncNetworkResources;
- @Autowired
- private SDNCVfModuleResources sdncVfModuleResources;
+ private static final Logger logger = LoggerFactory.getLogger(SDNCActivateTasks.class);
+ @Autowired
+ private SDNCVnfResources sdncVnfResources;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private SDNCNetworkResources sdncNetworkResources;
+ @Autowired
+ private SDNCVfModuleResources sdncVfModuleResources;
- public void activateVnf(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- RequestContext requestContext = gBBInput.getRequestContext();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- Customer customer = gBBInput.getCustomer();
- GenericResourceApiVnfOperationInformation req = sdncVnfResources.activateVnf(vnf, serviceInstance, customer, cloudRegion, requestContext);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.VNF);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- /**
- * BPMN access method to perform Assign action on SDNC for L3Network
- * @param execution
- * @throws BBObjectNotFoundException
- */
- public void activateNetwork(BuildingBlockExecution execution) throws BBObjectNotFoundException {
- try{
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Customer customer = gBBInput.getCustomer();
- RequestContext requestContext = gBBInput.getRequestContext();
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- GenericResourceApiNetworkOperationInformation req = sdncNetworkResources.activateNetwork(l3network, serviceInstance, customer, requestContext, cloudRegion);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.NETWORK);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void activateVfModule(BuildingBlockExecution execution) {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- RequestContext requestContext = gBBInput.getRequestContext();
- ServiceInstance serviceInstance = null;
- GenericVnf vnf = null;
- VfModule vfModule = null;
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- Customer customer = gBBInput.getCustomer();
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.activateVfModule(vfModule, vnf, serviceInstance, customer,
- cloudRegion, requestContext);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.VFMODULE);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ public void activateVnf(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ Customer customer = gBBInput.getCustomer();
+ GenericResourceApiVnfOperationInformation req =
+ sdncVnfResources.activateVnf(vnf, serviceInstance, customer, cloudRegion, requestContext);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.VNF);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ /**
+ * BPMN access method to perform Assign action on SDNC for L3Network
+ *
+ * @param execution
+ * @throws BBObjectNotFoundException
+ */
+ public void activateNetwork(BuildingBlockExecution execution) throws BBObjectNotFoundException {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Customer customer = gBBInput.getCustomer();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ GenericResourceApiNetworkOperationInformation req = sdncNetworkResources.activateNetwork(l3network,
+ serviceInstance, customer, requestContext, cloudRegion);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.NETWORK);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void activateVfModule(BuildingBlockExecution execution) {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ ServiceInstance serviceInstance = null;
+ GenericVnf vnf = null;
+ VfModule vfModule = null;
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ Customer customer = gBBInput.getCustomer();
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.activateVfModule(vfModule, vnf,
+ serviceInstance, customer, cloudRegion, requestContext);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.VFMODULE);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java
index cbb1f34ae5..d3878f06b7 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java
@@ -53,99 +53,108 @@ import org.springframework.stereotype.Component;
@Component
public class SDNCAssignTasks {
- private static final Logger logger = LoggerFactory.getLogger(SDNCAssignTasks.class);
- @Autowired
- private SDNCServiceInstanceResources sdncSIResources;
- @Autowired
- private SDNCVnfResources sdncVnfResources;
- @Autowired
- private SDNCVfModuleResources sdncVfModuleResources;
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private SDNCNetworkResources sdncNetworkResources;
+ private static final Logger logger = LoggerFactory.getLogger(SDNCAssignTasks.class);
+ @Autowired
+ private SDNCServiceInstanceResources sdncSIResources;
+ @Autowired
+ private SDNCVnfResources sdncVnfResources;
+ @Autowired
+ private SDNCVfModuleResources sdncVfModuleResources;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private SDNCNetworkResources sdncNetworkResources;
- public void assignServiceInstance(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- RequestContext requestContext = gBBInput.getRequestContext();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Customer customer = gBBInput.getCustomer();
- GenericResourceApiServiceOperationInformation req = sdncSIResources.assignServiceInstance(serviceInstance, customer, requestContext);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.SERVICE);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ public void assignServiceInstance(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Customer customer = gBBInput.getCustomer();
+ GenericResourceApiServiceOperationInformation req =
+ sdncSIResources.assignServiceInstance(serviceInstance, customer, requestContext);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.SERVICE);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
- public void assignVnf(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- RequestContext requestContext = gBBInput.getRequestContext();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- Customer customer = gBBInput.getCustomer();
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- GenericResourceApiVnfOperationInformation req = sdncVnfResources.assignVnf(vnf, serviceInstance, customer, cloudRegion, requestContext, Boolean.TRUE.equals(vnf.isCallHoming()));
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.VNF);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ public void assignVnf(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ Customer customer = gBBInput.getCustomer();
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ GenericResourceApiVnfOperationInformation req = sdncVnfResources.assignVnf(vnf, serviceInstance, customer,
+ cloudRegion, requestContext, Boolean.TRUE.equals(vnf.isCallHoming()));
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.VNF);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
- public void assignVfModule(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- RequestContext requestContext = gBBInput.getRequestContext();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- VolumeGroup volumeGroup = null;
- try{
- volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- } catch (BBObjectNotFoundException e){
- logger.info("No volume group was found.");
- }
- Customer customer = gBBInput.getCustomer();
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.assignVfModule(vfModule, volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.VFMODULE);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ public void assignVfModule(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ VolumeGroup volumeGroup = null;
+ try {
+ volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ } catch (BBObjectNotFoundException e) {
+ logger.info("No volume group was found.");
+ }
+ Customer customer = gBBInput.getCustomer();
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.assignVfModule(vfModule,
+ volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.VFMODULE);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
- /**
- * BPMN access method to perform Assign action on SDNC for L3Network
- * @param execution
- * @throws Exception
- */
- public void assignNetwork(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Customer customer = gBBInput.getCustomer();
- RequestContext requestContext = gBBInput.getRequestContext();
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- GenericResourceApiNetworkOperationInformation req = sdncNetworkResources.assignNetwork(l3network, serviceInstance, customer, requestContext, cloudRegion);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.NETWORK);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ /**
+ * BPMN access method to perform Assign action on SDNC for L3Network
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void assignNetwork(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Customer customer = gBBInput.getCustomer();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ GenericResourceApiNetworkOperationInformation req = sdncNetworkResources.assignNetwork(l3network,
+ serviceInstance, customer, requestContext, cloudRegion);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.NETWORK);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java
index 59e46e1667..50cf0fb074 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java
@@ -47,79 +47,87 @@ import org.springframework.stereotype.Component;
@Component
public class SDNCChangeAssignTasks {
- @Autowired
- private SDNCNetworkResources sdncNetworkResources;
- @Autowired
- private SDNCServiceInstanceResources sdncServiceInstanceResources;
- @Autowired
- private SDNCVnfResources sdncVnfResources;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private SDNCVfModuleResources sdncVfModuleResources;
-
- public void changeModelServiceInstance(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- GenericResourceApiServiceOperationInformation req = sdncServiceInstanceResources.changeModelServiceInstance(serviceInstance, gBBInput.getCustomer(), gBBInput.getRequestContext());
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.SERVICE);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void changeModelVnf(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- GenericResourceApiVnfOperationInformation req = sdncVnfResources.changeModelVnf(genericVnf, serviceInstance, gBBInput.getCustomer(), gBBInput.getCloudRegion(), gBBInput.getRequestContext());
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.VNF);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void changeAssignNetwork(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- L3Network network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- GenericResourceApiNetworkOperationInformation req = sdncNetworkResources.changeAssignNetwork(network, serviceInstance, gBBInput.getCustomer(), gBBInput.getRequestContext(), gBBInput.getCloudRegion());
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.NETWORK);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void changeAssignModelVfModule(BuildingBlockExecution execution) throws Exception {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- RequestContext requestContext = gBBInput.getRequestContext();
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- Customer customer = gBBInput.getCustomer();
- GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.changeAssignVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion, requestContext);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.VFMODULE);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ @Autowired
+ private SDNCNetworkResources sdncNetworkResources;
+ @Autowired
+ private SDNCServiceInstanceResources sdncServiceInstanceResources;
+ @Autowired
+ private SDNCVnfResources sdncVnfResources;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private SDNCVfModuleResources sdncVfModuleResources;
+
+ public void changeModelServiceInstance(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ GenericResourceApiServiceOperationInformation req = sdncServiceInstanceResources
+ .changeModelServiceInstance(serviceInstance, gBBInput.getCustomer(), gBBInput.getRequestContext());
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.SERVICE);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void changeModelVnf(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ GenericResourceApiVnfOperationInformation req = sdncVnfResources.changeModelVnf(genericVnf, serviceInstance,
+ gBBInput.getCustomer(), gBBInput.getCloudRegion(), gBBInput.getRequestContext());
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.VNF);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void changeAssignNetwork(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ L3Network network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ GenericResourceApiNetworkOperationInformation req = sdncNetworkResources.changeAssignNetwork(network,
+ serviceInstance, gBBInput.getCustomer(), gBBInput.getRequestContext(), gBBInput.getCloudRegion());
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.NETWORK);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void changeAssignModelVfModule(BuildingBlockExecution execution) throws Exception {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ Customer customer = gBBInput.getCustomer();
+ GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.changeAssignVfModule(vfModule,
+ vnf, serviceInstance, customer, cloudRegion, requestContext);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.VFMODULE);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java
index 8202a14fa3..3a1528946d 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java
@@ -51,106 +51,115 @@ import org.springframework.stereotype.Component;
@Component
public class SDNCDeactivateTasks {
- private static final Logger logger = LoggerFactory.getLogger(SDNCDeactivateTasks.class);
- @Autowired
- private SDNCNetworkResources sdncNetworkResources;
- @Autowired
- private SDNCVfModuleResources sdncVfModuleResources;
- @Autowired
- private SDNCServiceInstanceResources sdncSIResources;
- @Autowired
- private SDNCVnfResources sdncVnfResources;
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
+ private static final Logger logger = LoggerFactory.getLogger(SDNCDeactivateTasks.class);
+ @Autowired
+ private SDNCNetworkResources sdncNetworkResources;
+ @Autowired
+ private SDNCVfModuleResources sdncVfModuleResources;
+ @Autowired
+ private SDNCServiceInstanceResources sdncSIResources;
+ @Autowired
+ private SDNCVnfResources sdncVnfResources;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
- public void deactivateVfModule(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- RequestContext requestContext = gBBInput.getRequestContext();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- Customer customer = gBBInput.getCustomer();
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.deactivateVfModule(vfModule, vnf, serviceInstance, customer,
- cloudRegion, requestContext);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.VFMODULE);
- execution.setVariable("SDNCRequest", sdncRequest); } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ public void deactivateVfModule(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ Customer customer = gBBInput.getCustomer();
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.deactivateVfModule(vfModule, vnf,
+ serviceInstance, customer, cloudRegion, requestContext);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.VFMODULE);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
- /**
- * BPMN access method to perform Service Topology Deactivate action on SDNC for Vnf
- * @param execution
- * @throws Exception
- */
- public void deactivateVnf(BuildingBlockExecution execution) throws Exception {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- RequestContext requestContext = gBBInput.getRequestContext();
- ServiceInstance serviceInstance = null;
- GenericVnf vnf = null;
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- Customer customer = gBBInput.getCustomer();
- GenericResourceApiVnfOperationInformation req = sdncVnfResources.deactivateVnf(vnf, serviceInstance, customer, cloudRegion, requestContext);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.VNF);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ /**
+ * BPMN access method to perform Service Topology Deactivate action on SDNC for Vnf
+ *
+ * @param execution
+ * @throws Exception
+ */
+ public void deactivateVnf(BuildingBlockExecution execution) throws Exception {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ ServiceInstance serviceInstance = null;
+ GenericVnf vnf = null;
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ Customer customer = gBBInput.getCustomer();
+ GenericResourceApiVnfOperationInformation req =
+ sdncVnfResources.deactivateVnf(vnf, serviceInstance, customer, cloudRegion, requestContext);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.VNF);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
- /*
- * BPMN access method to perform Service Topology Deactivate action on SDNC for Service Instance
- * @param execution
- * @throws Exception
- */
- public void deactivateServiceInstance(BuildingBlockExecution execution) throws Exception {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- RequestContext requestContext = gBBInput.getRequestContext();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Customer customer = gBBInput.getCustomer();
- GenericResourceApiServiceOperationInformation req = sdncSIResources.deactivateServiceInstance(serviceInstance, customer, requestContext);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.SERVICE);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ /*
+ * BPMN access method to perform Service Topology Deactivate action on SDNC for Service Instance
+ *
+ * @param execution
+ *
+ * @throws Exception
+ */
+ public void deactivateServiceInstance(BuildingBlockExecution execution) throws Exception {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Customer customer = gBBInput.getCustomer();
+ GenericResourceApiServiceOperationInformation req =
+ sdncSIResources.deactivateServiceInstance(serviceInstance, customer, requestContext);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.SERVICE);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
- /**
- * BPMN access method to invoke deactivate on a L3Network object
- *
- * @param execution
- */
- public void deactivateNetwork(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Customer customer = gBBInput.getCustomer();
- RequestContext requestContext = gBBInput.getRequestContext();
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- GenericResourceApiNetworkOperationInformation req = sdncNetworkResources.deactivateNetwork(l3Network, serviceInstance, customer,
- requestContext, cloudRegion);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.NETWORK);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ /**
+ * BPMN access method to invoke deactivate on a L3Network object
+ *
+ * @param execution
+ */
+ public void deactivateNetwork(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Customer customer = gBBInput.getCustomer();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ GenericResourceApiNetworkOperationInformation req = sdncNetworkResources.deactivateNetwork(l3Network,
+ serviceInstance, customer, requestContext, cloudRegion);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.NETWORK);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java
index 941eb7a004..7ae6117c61 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java
@@ -39,77 +39,79 @@ import org.springframework.stereotype.Component;
@Component
public class SDNCQueryTasks {
- private static final Logger logger = LoggerFactory.getLogger(SDNCQueryTasks.class);
- @Autowired
- private SDNCVnfResources sdncVnfResources;
- @Autowired
- private SDNCVfModuleResources sdncVfModuleResources;
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
-
- public void queryVnf(BuildingBlockExecution execution) throws Exception {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
-
- String selfLink = "restconf/config/GENERIC-RESOURCE-API:services/service/"
- + serviceInstance.getServiceInstanceId() + "/service-data/vnfs/vnf/"
- + genericVnf.getVnfId() + "/vnf-data/vnf-topology/";
- try {
- if(genericVnf.getSelflink() == null) {
- genericVnf.setSelflink(selfLink);
- }
- String response = sdncVnfResources.queryVnf(genericVnf);
- execution.setVariable("SDNCQueryResponse_" + genericVnf.getVnfId(), response);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(SDNCQueryTasks.class);
+ @Autowired
+ private SDNCVnfResources sdncVnfResources;
+ @Autowired
+ private SDNCVfModuleResources sdncVfModuleResources;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
-
- public void queryVfModule(BuildingBlockExecution execution) throws Exception {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- String selfLink = "restconf/config/GENERIC-RESOURCE-API:services/service/"
- + serviceInstance.getServiceInstanceId() + "/service-data/vnfs/vnf/"
- + genericVnf.getVnfId() + "/vnf-data/vf-modules/vf-module/"
- + vfModule.getVfModuleId() + "/vf-module-data/vf-module-topology/";
- try {
- if(vfModule.getSelflink() == null || (vfModule.getSelflink() != null && vfModule.getSelflink().isEmpty())) {
- vfModule.setSelflink(selfLink);
- }
- if(vfModule.getSelflink() != null && !vfModule.getSelflink().isEmpty()) {
- String response = sdncVfModuleResources.queryVfModule(vfModule);
- execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), response);
- }
- else {
- throw new Exception("Vf Module " + vfModule.getVfModuleId() + " exists in gBuildingBlock but does not have a selflink value");
- }
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void queryVfModuleForVolumeGroup(BuildingBlockExecution execution) {
- try {
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- if(vfModule.getSelflink() != null && !vfModule.getSelflink().isEmpty()) {
- String response = sdncVfModuleResources.queryVfModule(vfModule);
- execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), response);
- }
- else {
- throw new Exception("Vf Module " + vfModule.getVfModuleId() + " exists in gBuildingBlock but does not have a selflink value");
- }
- } catch(BBObjectNotFoundException bbException) {
- // If there is not a vf module in the general building block, we will not call SDNC and proceed as normal without throwing an error
- // If we see a bb object not found exception for something that is not a vf module id, then we should throw the error as normal
- if(!ResourceKey.VF_MODULE_ID.equals(bbException.getResourceKey())) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, bbException);
- }
- } catch(Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ public void queryVnf(BuildingBlockExecution execution) throws Exception {
+ ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+
+ String selfLink =
+ "restconf/config/GENERIC-RESOURCE-API:services/service/" + serviceInstance.getServiceInstanceId()
+ + "/service-data/vnfs/vnf/" + genericVnf.getVnfId() + "/vnf-data/vnf-topology/";
+ try {
+ if (genericVnf.getSelflink() == null) {
+ genericVnf.setSelflink(selfLink);
+ }
+ String response = sdncVnfResources.queryVnf(genericVnf);
+ execution.setVariable("SDNCQueryResponse_" + genericVnf.getVnfId(), response);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+
+ public void queryVfModule(BuildingBlockExecution execution) throws Exception {
+ ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ String selfLink = "restconf/config/GENERIC-RESOURCE-API:services/service/"
+ + serviceInstance.getServiceInstanceId() + "/service-data/vnfs/vnf/" + genericVnf.getVnfId()
+ + "/vnf-data/vf-modules/vf-module/" + vfModule.getVfModuleId() + "/vf-module-data/vf-module-topology/";
+ try {
+ if (vfModule.getSelflink() == null
+ || (vfModule.getSelflink() != null && vfModule.getSelflink().isEmpty())) {
+ vfModule.setSelflink(selfLink);
+ }
+ if (vfModule.getSelflink() != null && !vfModule.getSelflink().isEmpty()) {
+ String response = sdncVfModuleResources.queryVfModule(vfModule);
+ execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), response);
+ } else {
+ throw new Exception("Vf Module " + vfModule.getVfModuleId()
+ + " exists in gBuildingBlock but does not have a selflink value");
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void queryVfModuleForVolumeGroup(BuildingBlockExecution execution) {
+ try {
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ if (vfModule.getSelflink() != null && !vfModule.getSelflink().isEmpty()) {
+ String response = sdncVfModuleResources.queryVfModule(vfModule);
+ execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), response);
+ } else {
+ throw new Exception("Vf Module " + vfModule.getVfModuleId()
+ + " exists in gBuildingBlock but does not have a selflink value");
+ }
+ } catch (BBObjectNotFoundException bbException) {
+ // If there is not a vf module in the general building block, we will not call SDNC and proceed as normal
+ // without throwing an error
+ // If we see a bb object not found exception for something that is not a vf module id, then we should throw
+ // the error as normal
+ if (!ResourceKey.VF_MODULE_ID.equals(bbException.getResourceKey())) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, bbException);
+ }
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java
index 24f642ae72..f32ffd72c3 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java
@@ -21,12 +21,10 @@
package org.onap.so.bpmn.infrastructure.sdnc.tasks;
import java.io.StringReader;
-
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.so.bpmn.infrastructure.sdnc.exceptions.SDNCErrorResponseException;
import org.onap.so.client.exception.BadResponseException;
@@ -41,93 +39,95 @@ import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
-
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
-
+
@Component
public class SDNCRequestTasks {
-
- private static final Logger logger = LoggerFactory.getLogger(SDNCRequestTasks.class);
-
- private static final String SDNC_REQUEST = "SDNCRequest";
- private static final String MESSAGE = "_MESSAGE";
- private static final String CORRELATOR = "_CORRELATOR";
- protected static final String IS_CALLBACK_COMPLETED = "isCallbackCompleted";
- protected static final String SDNC_SUCCESS = "200";
-
- @Autowired
- private ExceptionBuilder exceptionBuilder;
-
- @Autowired
- private SDNCClient sdncClient;
-
- public void createCorrelationVariables (DelegateExecution execution) {
- SDNCRequest request = (SDNCRequest)execution.getVariable(SDNC_REQUEST);
- execution.setVariable(request.getCorrelationName()+CORRELATOR, request.getCorrelationValue());
- execution.setVariable("sdncTimeout", request.getTimeOut());
- }
-
- public void callSDNC (DelegateExecution execution) {
- SDNCRequest request = (SDNCRequest)execution.getVariable(SDNC_REQUEST);
- try {
- String response = sdncClient.post(request.getSDNCPayload(),request.getTopology());
- String finalMessageIndicator = JsonPath.read(response, "$.output.ack-final-indicator");
- execution.setVariable("isSDNCCompleted", convertIndicatorToBoolean(finalMessageIndicator));
- } catch(PathNotFoundException e) {
- logger.error("Error Parsing SDNC Response. Could not find read final ack indicator from JSON.", e);
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000,"Recieved invalid response from SDNC, unable to read message content.");
- } catch (MapperException e) {
- logger.error("Failed to map SDNC object to JSON prior to POST.", e);
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000,"Failed to map SDNC object to JSON prior to POST.");
- } catch (BadResponseException e) {
- logger.error("Did not receive a successful response from SDNC.", e);
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, e.getLocalizedMessage());
- } catch (HttpClientErrorException e){
- logger.error("HttpClientErrorException: 404 Not Found, Failed to contact SDNC", e);
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, "SDNC cannot be contacted.");
- }
- }
-
- public void processCallback (DelegateExecution execution) {
- try {
- SDNCRequest request = (SDNCRequest)execution.getVariable(SDNC_REQUEST);
- String asyncRequest = (String) execution.getVariable(request.getCorrelationName()+MESSAGE);
-
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = db.parse(new InputSource(new StringReader(asyncRequest)));
-
- String finalMessageIndicator = getXmlElement(doc, "/input/ack-final-indicator");
- boolean isCallbackCompleted = convertIndicatorToBoolean(finalMessageIndicator);
- execution.setVariable(IS_CALLBACK_COMPLETED, isCallbackCompleted);
- if(isCallbackCompleted) {
- String responseCode = getXmlElement(doc, "/input/response-code");
- String responseMessage = getXmlElement(doc, "/input/response-message");
- if(!SDNC_SUCCESS.equalsIgnoreCase(responseCode)) {
- throw new SDNCErrorResponseException(responseMessage);
- }
- }
- } catch (SDNCErrorResponseException e) {
- logger.error("SDNC error response - " + e.getMessage());
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, e.getMessage());
- } catch (Exception e) {
- logger.error("Error procesing SDNC callback", e);
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, "Error procesing SDNC callback");
- }
- }
-
- public void handleTimeOutException (DelegateExecution execution) {
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, "Error timed out waiting on SDNC Async-Response");
- }
-
- protected boolean convertIndicatorToBoolean(String finalMessageIndicator) {
- return "Y".equals(finalMessageIndicator);
- }
-
- protected String getXmlElement(Document doc, String exp) throws Exception {
- XPath xPath = XPathFactory.newInstance().newXPath();
- return xPath.evaluate(exp, doc);
- }
-
+
+ private static final Logger logger = LoggerFactory.getLogger(SDNCRequestTasks.class);
+
+ private static final String SDNC_REQUEST = "SDNCRequest";
+ private static final String MESSAGE = "_MESSAGE";
+ private static final String CORRELATOR = "_CORRELATOR";
+ protected static final String IS_CALLBACK_COMPLETED = "isCallbackCompleted";
+ protected static final String SDNC_SUCCESS = "200";
+
+ @Autowired
+ private ExceptionBuilder exceptionBuilder;
+
+ @Autowired
+ private SDNCClient sdncClient;
+
+ public void createCorrelationVariables(DelegateExecution execution) {
+ SDNCRequest request = (SDNCRequest) execution.getVariable(SDNC_REQUEST);
+ execution.setVariable(request.getCorrelationName() + CORRELATOR, request.getCorrelationValue());
+ execution.setVariable("sdncTimeout", request.getTimeOut());
+ }
+
+ public void callSDNC(DelegateExecution execution) {
+ SDNCRequest request = (SDNCRequest) execution.getVariable(SDNC_REQUEST);
+ try {
+ String response = sdncClient.post(request.getSDNCPayload(), request.getTopology());
+ String finalMessageIndicator = JsonPath.read(response, "$.output.ack-final-indicator");
+ execution.setVariable("isSDNCCompleted", convertIndicatorToBoolean(finalMessageIndicator));
+ } catch (PathNotFoundException e) {
+ logger.error("Error Parsing SDNC Response. Could not find read final ack indicator from JSON.", e);
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000,
+ "Recieved invalid response from SDNC, unable to read message content.");
+ } catch (MapperException e) {
+ logger.error("Failed to map SDNC object to JSON prior to POST.", e);
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000,
+ "Failed to map SDNC object to JSON prior to POST.");
+ } catch (BadResponseException e) {
+ logger.error("Did not receive a successful response from SDNC.", e);
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, e.getLocalizedMessage());
+ } catch (HttpClientErrorException e) {
+ logger.error("HttpClientErrorException: 404 Not Found, Failed to contact SDNC", e);
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, "SDNC cannot be contacted.");
+ }
+ }
+
+ public void processCallback(DelegateExecution execution) {
+ try {
+ SDNCRequest request = (SDNCRequest) execution.getVariable(SDNC_REQUEST);
+ String asyncRequest = (String) execution.getVariable(request.getCorrelationName() + MESSAGE);
+
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ Document doc = db.parse(new InputSource(new StringReader(asyncRequest)));
+
+ String finalMessageIndicator = getXmlElement(doc, "/input/ack-final-indicator");
+ boolean isCallbackCompleted = convertIndicatorToBoolean(finalMessageIndicator);
+ execution.setVariable(IS_CALLBACK_COMPLETED, isCallbackCompleted);
+ if (isCallbackCompleted) {
+ String responseCode = getXmlElement(doc, "/input/response-code");
+ String responseMessage = getXmlElement(doc, "/input/response-message");
+ if (!SDNC_SUCCESS.equalsIgnoreCase(responseCode)) {
+ throw new SDNCErrorResponseException(responseMessage);
+ }
+ }
+ } catch (SDNCErrorResponseException e) {
+ logger.error("SDNC error response - " + e.getMessage());
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, e.getMessage());
+ } catch (Exception e) {
+ logger.error("Error procesing SDNC callback", e);
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, "Error procesing SDNC callback");
+ }
+ }
+
+ public void handleTimeOutException(DelegateExecution execution) {
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000,
+ "Error timed out waiting on SDNC Async-Response");
+ }
+
+ protected boolean convertIndicatorToBoolean(String finalMessageIndicator) {
+ return "Y".equals(finalMessageIndicator);
+ }
+
+ protected String getXmlElement(Document doc, String exp) throws Exception {
+ XPath xPath = XPathFactory.newInstance().newXPath();
+ return xPath.evaluate(exp, doc);
+ }
+
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java
index 340872593f..e9848d1646 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java
@@ -51,85 +51,94 @@ import org.springframework.stereotype.Component;
@Component
public class SDNCUnassignTasks {
- private static final Logger logger = LoggerFactory.getLogger(SDNCUnassignTasks.class);
- @Autowired
- private SDNCServiceInstanceResources sdncSIResources;
- @Autowired
- private SDNCVfModuleResources sdncVfModuleResources;
- @Autowired
- private SDNCVnfResources sdncVnfResources;
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private SDNCNetworkResources sdncNetworkResources;
+ private static final Logger logger = LoggerFactory.getLogger(SDNCUnassignTasks.class);
+ @Autowired
+ private SDNCServiceInstanceResources sdncSIResources;
+ @Autowired
+ private SDNCVfModuleResources sdncVfModuleResources;
+ @Autowired
+ private SDNCVnfResources sdncVnfResources;
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private SDNCNetworkResources sdncNetworkResources;
- public void unassignServiceInstance(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- RequestContext requestContext = gBBInput.getRequestContext();
- Customer customer = gBBInput.getCustomer();
- GenericResourceApiServiceOperationInformation req = sdncSIResources.unassignServiceInstance(serviceInstance, customer, requestContext);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.SERVICE);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void unassignVfModule(BuildingBlockExecution execution) {
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.unassignVfModule(vfModule, vnf, serviceInstance);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.VFMODULE);
- execution.setVariable("SDNCRequest", sdncRequest); } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
-
- public void unassignVnf(BuildingBlockExecution execution) {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- RequestContext requestContext = gBBInput.getRequestContext();
- Customer customer = gBBInput.getCustomer();
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- GenericResourceApiVnfOperationInformation req = sdncVnfResources.unassignVnf(vnf, serviceInstance, customer, cloudRegion, requestContext);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.VNF);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ public void unassignServiceInstance(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ RequestContext requestContext = gBBInput.getRequestContext();
+ Customer customer = gBBInput.getCustomer();
+ GenericResourceApiServiceOperationInformation req =
+ sdncSIResources.unassignServiceInstance(serviceInstance, customer, requestContext);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.SERVICE);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
- public void unassignNetwork(BuildingBlockExecution execution) throws Exception {
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- L3Network network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- Customer customer = gBBInput.getCustomer();
- RequestContext requestContext = gBBInput.getRequestContext();
- CloudRegion cloudRegion = gBBInput.getCloudRegion();
- String cloudRegionSdnc = execution.getVariable("cloudRegionSdnc");
- cloudRegion.setLcpCloudRegionId(cloudRegionSdnc);
- GenericResourceApiNetworkOperationInformation req = sdncNetworkResources.unassignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- SDNCRequest sdncRequest = new SDNCRequest();
- sdncRequest.setSDNCPayload(req);
- sdncRequest.setTopology(SDNCTopology.NETWORK);
- execution.setVariable("SDNCRequest", sdncRequest);
- } catch (Exception ex) {
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }
+ public void unassignVfModule(BuildingBlockExecution execution) {
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ GenericResourceApiVfModuleOperationInformation req =
+ sdncVfModuleResources.unassignVfModule(vfModule, vnf, serviceInstance);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.VFMODULE);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void unassignVnf(BuildingBlockExecution execution) {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ RequestContext requestContext = gBBInput.getRequestContext();
+ Customer customer = gBBInput.getCustomer();
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ GenericResourceApiVnfOperationInformation req =
+ sdncVnfResources.unassignVnf(vnf, serviceInstance, customer, cloudRegion, requestContext);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.VNF);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
+
+ public void unassignNetwork(BuildingBlockExecution execution) throws Exception {
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ L3Network network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ Customer customer = gBBInput.getCustomer();
+ RequestContext requestContext = gBBInput.getRequestContext();
+ CloudRegion cloudRegion = gBBInput.getCloudRegion();
+ String cloudRegionSdnc = execution.getVariable("cloudRegionSdnc");
+ cloudRegion.setLcpCloudRegionId(cloudRegionSdnc);
+ GenericResourceApiNetworkOperationInformation req = sdncNetworkResources.unassignNetwork(network,
+ serviceInstance, customer, requestContext, cloudRegion);
+ SDNCRequest sdncRequest = new SDNCRequest();
+ sdncRequest.setSDNCPayload(req);
+ sdncRequest.setTopology(SDNCTopology.NETWORK);
+ execution.setVariable("SDNCRequest", sdncRequest);
+ } catch (Exception ex) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java
index 3763fca34f..47855eaa6e 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.validations;
import java.util.Optional;
import java.util.regex.Pattern;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.common.validation.PreBuildingBlockValidator;
import org.onap.so.bpmn.common.validation.Skip;
@@ -37,34 +36,35 @@ import org.springframework.stereotype.Component;
@Skip
public class CloudRegionOrchestrationValidator implements PreBuildingBlockValidator {
- private static Logger logger = LoggerFactory.getLogger(CloudRegionOrchestrationValidator.class);
- private final Pattern pattern = Pattern.compile("(?:Activate|Assign|Create|Deactivate|Delete|Unassign|Update)(?:Network|Vnf|VfModule|VolumeGroup|FabricConfiguration)BB");
-
- @Autowired
- private ExceptionBuilder exceptionBuilder;
+ private static Logger logger = LoggerFactory.getLogger(CloudRegionOrchestrationValidator.class);
+ private final Pattern pattern = Pattern.compile(
+ "(?:Activate|Assign|Create|Deactivate|Delete|Unassign|Update)(?:Network|Vnf|VfModule|VolumeGroup|FabricConfiguration)BB");
+
+ @Autowired
+ private ExceptionBuilder exceptionBuilder;
+
+ @Override
+ public boolean shouldRunFor(String bbName) {
+ return pattern.matcher(bbName).find();
+ }
- @Override
- public boolean shouldRunFor(String bbName) {
- return pattern.matcher(bbName).find();
- }
-
- @Override
- public Optional<String> validate(BuildingBlockExecution execution) {
- String msg = null;
- try {
- CloudRegion cloudRegion = execution.getGeneralBuildingBlock().getCloudRegion();
- if (Boolean.TRUE.equals(cloudRegion.getOrchestrationDisabled())) {
- msg = String.format("Error: The request has failed due to orchestration currently disabled for the target cloud region %s for cloud owner %s",
- cloudRegion.getLcpCloudRegionId(), cloudRegion.getCloudOwner());
- logger.error(msg);
- return Optional.ofNullable(msg);
- }
- }
- catch(Exception e) {
- logger.error("failed to validate", e);
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, e);
- }
- return Optional.empty();
- }
+ @Override
+ public Optional<String> validate(BuildingBlockExecution execution) {
+ String msg = null;
+ try {
+ CloudRegion cloudRegion = execution.getGeneralBuildingBlock().getCloudRegion();
+ if (Boolean.TRUE.equals(cloudRegion.getOrchestrationDisabled())) {
+ msg = String.format(
+ "Error: The request has failed due to orchestration currently disabled for the target cloud region %s for cloud owner %s",
+ cloudRegion.getLcpCloudRegionId(), cloudRegion.getCloudOwner());
+ logger.error(msg);
+ return Optional.ofNullable(msg);
+ }
+ } catch (Exception e) {
+ logger.error("failed to validate", e);
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, e);
+ }
+ return Optional.empty();
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/FlowCompletionTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/FlowCompletionTasks.java
index ec2ccdf202..e809ecd0ae 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/FlowCompletionTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/FlowCompletionTasks.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.workflow.tasks;
import java.util.ArrayList;
import java.util.List;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.so.bpmn.common.BuildingBlockExecution;
@@ -40,41 +39,39 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class FlowCompletionTasks {
- private static final Logger logger = LoggerFactory.getLogger(FlowCompletionTasks.class);
+ private static final Logger logger = LoggerFactory.getLogger(FlowCompletionTasks.class);
+
+ @Autowired
+ private RequestsDbClient requestDbclient;
+
+ public void updateRequestDbStatus(BuildingBlockExecution execution) {
+ try {
+ String requestId = execution.getGeneralBuildingBlock().getRequestContext().getMsoRequestId();
+ InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
+
+ WorkflowException workflowException = (WorkflowException) execution.getVariable("WorkflowException");
+ if (workflowException == null) {
+ request.setStatusMessage("RequestCompletedSuccessfully");
+ request.setRequestStatus("COMPLETE");
+
+ } else {
+ request.setStatusMessage(workflowException.getErrorMessage());
+ request.setRequestStatus("FAILED");
+ }
+ request.setProgress(100L);
+ request.setLastModifiedBy("CamundaBPMN");
+
+ requestDbclient.updateInfraActiveRequests(request);
+ } catch (Exception e) {
+ logger.error("Unable to save the updated request status to the DB", e);
+ }
+ }
+
- @Autowired
- private RequestsDbClient requestDbclient;
-
- public void updateRequestDbStatus(BuildingBlockExecution execution) {
- try {
- String requestId = execution.getGeneralBuildingBlock().getRequestContext().getMsoRequestId();
- InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
-
- WorkflowException workflowException = (WorkflowException) execution.getVariable("WorkflowException");
- if (workflowException == null) {
- request.setStatusMessage("RequestCompletedSuccessfully");
- request.setRequestStatus("COMPLETE");
-
- }
- else {
- request.setStatusMessage(workflowException.getErrorMessage());
- request.setRequestStatus("FAILED");
- }
- request.setProgress(100L);
- request.setLastModifiedBy("CamundaBPMN");
-
- requestDbclient.updateInfraActiveRequests(request);
- } catch (Exception e) {
- logger.error("Unable to save the updated request status to the DB",e);
- }
- }
-
-
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java
index bbfc01921c..4fcacb3c42 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java
@@ -42,124 +42,158 @@ import org.springframework.stereotype.Component;
@Component
public class OrchestrationStatusValidator {
- private static final Logger logger = LoggerFactory.getLogger(OrchestrationStatusValidator.class);
-
- private static final String BUILDING_BLOCK_DETAIL_NOT_FOUND = "Building Block (%s) not set up in Orchestration_Status_Validation table in CatalogDB.";
- private static final String UNKNOWN_RESOURCE_TYPE = "Building Block (%s) not set up correctly in Orchestration_Status_Validation table in CatalogDB. ResourceType=(%s), TargetAction=(%s)";
- private static final String ORCHESTRATION_VALIDATION_FAIL = "Orchestration Status Validation failed. ResourceType=(%s), TargetAction=(%s), OrchestrationStatus=(%s)";
- private static final String ORCHESTRATION_STATUS_VALIDATION_RESULT = "orchestrationStatusValidationResult";
- private static final String ALACARTE = "aLaCarte";
- private static final String MULTI_STAGE_DESIGN_OFF = "false";
- private static final String MULTI_STAGE_DESIGN_ON = "true";
-
-
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private ExceptionBuilder exceptionBuilder;
- @Autowired
- private CatalogDbClient catalogDbClient;
-
- public void validateOrchestrationStatus(BuildingBlockExecution execution) {
- try {
- OrchestrationStatusValidationDirective previousOrchestrationStatusValidationResult = execution.getVariable(ORCHESTRATION_STATUS_VALIDATION_RESULT);
-
- execution.setVariable(ORCHESTRATION_STATUS_VALIDATION_RESULT, null);
-
- boolean aLaCarte = (boolean) execution.getVariable(ALACARTE);
-
- String buildingBlockFlowName = execution.getFlowToBeCalled();
-
- BuildingBlockDetail buildingBlockDetail = catalogDbClient.getBuildingBlockDetail(buildingBlockFlowName);
-
- if (buildingBlockDetail == null) {
- throw new OrchestrationStatusValidationException(String.format(BUILDING_BLOCK_DETAIL_NOT_FOUND, buildingBlockFlowName));
- }
-
- OrchestrationStatus orchestrationStatus = null;
-
- switch(buildingBlockDetail.getResourceType()) {
- case SERVICE:
- org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- orchestrationStatus = serviceInstance.getOrchestrationStatus();
- break;
- case VNF:
- org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- orchestrationStatus = genericVnf.getOrchestrationStatus();
- break;
- case VF_MODULE:
- org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
- orchestrationStatus = vfModule.getOrchestrationStatus();
- break;
- case VOLUME_GROUP:
- org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
- orchestrationStatus = volumeGroup.getOrchestrationStatus();
- break;
- case NETWORK:
- org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- orchestrationStatus = network.getOrchestrationStatus();
- break;
- case NETWORK_COLLECTION:
- org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInst = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- org.onap.so.bpmn.servicedecomposition.bbobjects.Collection networkCollection = serviceInst.getCollection();
- orchestrationStatus = networkCollection.getOrchestrationStatus();
- break;
- case CONFIGURATION:
- org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
- orchestrationStatus = configuration.getOrchestrationStatus();
- break;
- case INSTANCE_GROUP:
- org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID);
- orchestrationStatus = instanceGroup.getOrchestrationStatus();
- break;
- case NO_VALIDATE:
- //short circuit and exit method
- execution.setVariable(ORCHESTRATION_STATUS_VALIDATION_RESULT, OrchestrationStatusValidationDirective.VALIDATION_SKIPPED);
- return;
- default:
- // can't currently get here, so not tested. Added in case enum is expanded without a change to this code
- throw new OrchestrationStatusValidationException(String.format(UNKNOWN_RESOURCE_TYPE, buildingBlockFlowName, buildingBlockDetail.getResourceType(), buildingBlockDetail.getTargetAction()));
- }
-
- if(orchestrationStatus==null){
- throw new OrchestrationStatusValidationException("The resource's orchstration status is null. Cannot perform task on a null orchestration status");
- }
- OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = catalogDbClient.getOrchestrationStatusStateTransitionDirective(buildingBlockDetail.getResourceType(), orchestrationStatus, buildingBlockDetail.getTargetAction());
-
- if(aLaCarte && ResourceType.VF_MODULE.equals(buildingBlockDetail.getResourceType()) && OrchestrationAction.CREATE.equals(buildingBlockDetail.getTargetAction()) &&
- OrchestrationStatus.PENDING_ACTIVATION.equals(orchestrationStatus)) {
- org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- orchestrationStatusStateTransitionDirective = processPossibleSecondStageofVfModuleCreate(execution, previousOrchestrationStatusValidationResult,
- genericVnf, orchestrationStatusStateTransitionDirective);
- }
-
- if (orchestrationStatusStateTransitionDirective.getFlowDirective() == OrchestrationStatusValidationDirective.FAIL) {
- throw new OrchestrationStatusValidationException(String.format(ORCHESTRATION_VALIDATION_FAIL, buildingBlockDetail.getResourceType(), buildingBlockDetail.getTargetAction(), orchestrationStatus));
- }
-
- execution.setVariable(ORCHESTRATION_STATUS_VALIDATION_RESULT, orchestrationStatusStateTransitionDirective.getFlowDirective());
- }catch(BBObjectNotFoundException ex){
- if(execution.getFlowToBeCalled().contains("Unassign")){
- execution.setVariable(ORCHESTRATION_STATUS_VALIDATION_RESULT, OrchestrationStatusValidationDirective.SILENT_SUCCESS);
- }else{
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, ex);
- }
- }catch (Exception e) {
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, e);
- }
- }
-
- private OrchestrationStatusStateTransitionDirective processPossibleSecondStageofVfModuleCreate(BuildingBlockExecution execution, OrchestrationStatusValidationDirective previousOrchestrationStatusValidationResult,
- org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf genericVnf, OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective) {
- if (previousOrchestrationStatusValidationResult != null && previousOrchestrationStatusValidationResult.equals(OrchestrationStatusValidationDirective.SILENT_SUCCESS)) {
- String multiStageDesign = MULTI_STAGE_DESIGN_OFF;
- if (genericVnf.getModelInfoGenericVnf() != null) {
- multiStageDesign = genericVnf.getModelInfoGenericVnf().getMultiStageDesign();
- }
- if (multiStageDesign != null && multiStageDesign.equalsIgnoreCase(MULTI_STAGE_DESIGN_ON)) {
- orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.CONTINUE);
- }
- }
- return orchestrationStatusStateTransitionDirective;
- }
+ private static final Logger logger = LoggerFactory.getLogger(OrchestrationStatusValidator.class);
+
+ private static final String BUILDING_BLOCK_DETAIL_NOT_FOUND =
+ "Building Block (%s) not set up in Orchestration_Status_Validation table in CatalogDB.";
+ private static final String UNKNOWN_RESOURCE_TYPE =
+ "Building Block (%s) not set up correctly in Orchestration_Status_Validation table in CatalogDB. ResourceType=(%s), TargetAction=(%s)";
+ private static final String ORCHESTRATION_VALIDATION_FAIL =
+ "Orchestration Status Validation failed. ResourceType=(%s), TargetAction=(%s), OrchestrationStatus=(%s)";
+ private static final String ORCHESTRATION_STATUS_VALIDATION_RESULT = "orchestrationStatusValidationResult";
+ private static final String ALACARTE = "aLaCarte";
+ private static final String MULTI_STAGE_DESIGN_OFF = "false";
+ private static final String MULTI_STAGE_DESIGN_ON = "true";
+
+
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private ExceptionBuilder exceptionBuilder;
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+
+ public void validateOrchestrationStatus(BuildingBlockExecution execution) {
+ try {
+ OrchestrationStatusValidationDirective previousOrchestrationStatusValidationResult =
+ execution.getVariable(ORCHESTRATION_STATUS_VALIDATION_RESULT);
+
+ execution.setVariable(ORCHESTRATION_STATUS_VALIDATION_RESULT, null);
+
+ boolean aLaCarte = (boolean) execution.getVariable(ALACARTE);
+
+ String buildingBlockFlowName = execution.getFlowToBeCalled();
+
+ BuildingBlockDetail buildingBlockDetail = catalogDbClient.getBuildingBlockDetail(buildingBlockFlowName);
+
+ if (buildingBlockDetail == null) {
+ throw new OrchestrationStatusValidationException(
+ String.format(BUILDING_BLOCK_DETAIL_NOT_FOUND, buildingBlockFlowName));
+ }
+
+ OrchestrationStatus orchestrationStatus = null;
+
+ switch (buildingBlockDetail.getResourceType()) {
+ case SERVICE:
+ org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ orchestrationStatus = serviceInstance.getOrchestrationStatus();
+ break;
+ case VNF:
+ org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf genericVnf =
+ extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ orchestrationStatus = genericVnf.getOrchestrationStatus();
+ break;
+ case VF_MODULE:
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule =
+ extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
+ orchestrationStatus = vfModule.getOrchestrationStatus();
+ break;
+ case VOLUME_GROUP:
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup =
+ extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID);
+ orchestrationStatus = volumeGroup.getOrchestrationStatus();
+ break;
+ case NETWORK:
+ org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network =
+ extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ orchestrationStatus = network.getOrchestrationStatus();
+ break;
+ case NETWORK_COLLECTION:
+ org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInst =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ org.onap.so.bpmn.servicedecomposition.bbobjects.Collection networkCollection =
+ serviceInst.getCollection();
+ orchestrationStatus = networkCollection.getOrchestrationStatus();
+ break;
+ case CONFIGURATION:
+ org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration configuration =
+ extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID);
+ orchestrationStatus = configuration.getOrchestrationStatus();
+ break;
+ case INSTANCE_GROUP:
+ org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup instanceGroup =
+ extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID);
+ orchestrationStatus = instanceGroup.getOrchestrationStatus();
+ break;
+ case NO_VALIDATE:
+ // short circuit and exit method
+ execution.setVariable(ORCHESTRATION_STATUS_VALIDATION_RESULT,
+ OrchestrationStatusValidationDirective.VALIDATION_SKIPPED);
+ return;
+ default:
+ // can't currently get here, so not tested. Added in case enum is expanded without a change to this
+ // code
+ throw new OrchestrationStatusValidationException(
+ String.format(UNKNOWN_RESOURCE_TYPE, buildingBlockFlowName,
+ buildingBlockDetail.getResourceType(), buildingBlockDetail.getTargetAction()));
+ }
+
+ if (orchestrationStatus == null) {
+ throw new OrchestrationStatusValidationException(
+ "The resource's orchstration status is null. Cannot perform task on a null orchestration status");
+ }
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = catalogDbClient
+ .getOrchestrationStatusStateTransitionDirective(buildingBlockDetail.getResourceType(),
+ orchestrationStatus, buildingBlockDetail.getTargetAction());
+
+ if (aLaCarte && ResourceType.VF_MODULE.equals(buildingBlockDetail.getResourceType())
+ && OrchestrationAction.CREATE.equals(buildingBlockDetail.getTargetAction())
+ && OrchestrationStatus.PENDING_ACTIVATION.equals(orchestrationStatus)) {
+ org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf genericVnf =
+ extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ orchestrationStatusStateTransitionDirective = processPossibleSecondStageofVfModuleCreate(execution,
+ previousOrchestrationStatusValidationResult, genericVnf,
+ orchestrationStatusStateTransitionDirective);
+ }
+
+ if (orchestrationStatusStateTransitionDirective
+ .getFlowDirective() == OrchestrationStatusValidationDirective.FAIL) {
+ throw new OrchestrationStatusValidationException(
+ String.format(ORCHESTRATION_VALIDATION_FAIL, buildingBlockDetail.getResourceType(),
+ buildingBlockDetail.getTargetAction(), orchestrationStatus));
+ }
+
+ execution.setVariable(ORCHESTRATION_STATUS_VALIDATION_RESULT,
+ orchestrationStatusStateTransitionDirective.getFlowDirective());
+ } catch (BBObjectNotFoundException ex) {
+ if (execution.getFlowToBeCalled().contains("Unassign")) {
+ execution.setVariable(ORCHESTRATION_STATUS_VALIDATION_RESULT,
+ OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+ } else {
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, ex);
+ }
+ } catch (Exception e) {
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, e);
+ }
+ }
+
+ private OrchestrationStatusStateTransitionDirective processPossibleSecondStageofVfModuleCreate(
+ BuildingBlockExecution execution,
+ OrchestrationStatusValidationDirective previousOrchestrationStatusValidationResult,
+ org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf genericVnf,
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective) {
+ if (previousOrchestrationStatusValidationResult != null && previousOrchestrationStatusValidationResult
+ .equals(OrchestrationStatusValidationDirective.SILENT_SUCCESS)) {
+ String multiStageDesign = MULTI_STAGE_DESIGN_OFF;
+ if (genericVnf.getModelInfoGenericVnf() != null) {
+ multiStageDesign = genericVnf.getModelInfoGenericVnf().getMultiStageDesign();
+ }
+ if (multiStageDesign != null && multiStageDesign.equalsIgnoreCase(MULTI_STAGE_DESIGN_ON)) {
+ orchestrationStatusStateTransitionDirective
+ .setFlowDirective(OrchestrationStatusValidationDirective.CONTINUE);
+ }
+ }
+ return orchestrationStatusStateTransitionDirective;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/Resource.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/Resource.java
index 03559afb33..447f8994db 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/Resource.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/Resource.java
@@ -22,67 +22,82 @@ package org.onap.so.bpmn.infrastructure.workflow.tasks;
public class Resource {
- private String resourceId;
- private WorkflowType resourceType;
- private boolean generated;
- private boolean baseVfModule;
- private String virtualLinkKey;
- private String vnfCustomizationId;
- private String vfModuleCustomizationId;
- private String cvnfModuleCustomizationId;
-
- public Resource(WorkflowType resourceType, String resourceId, boolean generated){
- this.resourceId = resourceId;
- this.resourceType = resourceType;
- this.generated = generated;
- }
-
- public String getResourceId() {
- return resourceId;
- }
- public void setResourceId(String resourceId) {
- this.resourceId = resourceId;
- }
- public WorkflowType getResourceType() {
- return resourceType;
- }
- public void setResourceType(WorkflowType resourceType) {
- this.resourceType = resourceType;
- }
- public boolean isGenerated() {
- return generated;
- }
- public void setGenerated(boolean generated) {
- this.generated = generated;
- }
- public boolean isBaseVfModule() {
- return baseVfModule;
- }
- public void setBaseVfModule(boolean baseVfModule) {
- this.baseVfModule = baseVfModule;
- }
- public String getVirtualLinkKey() {
- return virtualLinkKey;
- }
- public void setVirtualLinkKey(String virtualLinkKey) {
- this.virtualLinkKey = virtualLinkKey;
- }
- public String getVnfCustomizationId() {
- return vnfCustomizationId;
- }
- public void setVnfCustomizationId(String vnfCustomizationId) {
- this.vnfCustomizationId = vnfCustomizationId;
- }
- public String getVfModuleCustomizationId() {
- return vfModuleCustomizationId;
- }
- public void setVfModuleCustomizationId(String vfModuleCustomizationId) {
- this.vfModuleCustomizationId = vfModuleCustomizationId;
- }
- public String getCvnfModuleCustomizationId() {
- return cvnfModuleCustomizationId;
- }
- public void setCvnfModuleCustomizationId(String cvnfModuleCustomizationId) {
- this.cvnfModuleCustomizationId = cvnfModuleCustomizationId;
- }
+ private String resourceId;
+ private WorkflowType resourceType;
+ private boolean generated;
+ private boolean baseVfModule;
+ private String virtualLinkKey;
+ private String vnfCustomizationId;
+ private String vfModuleCustomizationId;
+ private String cvnfModuleCustomizationId;
+
+ public Resource(WorkflowType resourceType, String resourceId, boolean generated) {
+ this.resourceId = resourceId;
+ this.resourceType = resourceType;
+ this.generated = generated;
+ }
+
+ public String getResourceId() {
+ return resourceId;
+ }
+
+ public void setResourceId(String resourceId) {
+ this.resourceId = resourceId;
+ }
+
+ public WorkflowType getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(WorkflowType resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public boolean isGenerated() {
+ return generated;
+ }
+
+ public void setGenerated(boolean generated) {
+ this.generated = generated;
+ }
+
+ public boolean isBaseVfModule() {
+ return baseVfModule;
+ }
+
+ public void setBaseVfModule(boolean baseVfModule) {
+ this.baseVfModule = baseVfModule;
+ }
+
+ public String getVirtualLinkKey() {
+ return virtualLinkKey;
+ }
+
+ public void setVirtualLinkKey(String virtualLinkKey) {
+ this.virtualLinkKey = virtualLinkKey;
+ }
+
+ public String getVnfCustomizationId() {
+ return vnfCustomizationId;
+ }
+
+ public void setVnfCustomizationId(String vnfCustomizationId) {
+ this.vnfCustomizationId = vnfCustomizationId;
+ }
+
+ public String getVfModuleCustomizationId() {
+ return vfModuleCustomizationId;
+ }
+
+ public void setVfModuleCustomizationId(String vfModuleCustomizationId) {
+ this.vfModuleCustomizationId = vfModuleCustomizationId;
+ }
+
+ public String getCvnfModuleCustomizationId() {
+ return cvnfModuleCustomizationId;
+ }
+
+ public void setCvnfModuleCustomizationId(String cvnfModuleCustomizationId) {
+ this.cvnfModuleCustomizationId = cvnfModuleCustomizationId;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java
index 7562bd964e..2fc301f9d7 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java
@@ -33,7 +33,6 @@ import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.javatuples.Pair;
import org.slf4j.LoggerFactory;
@@ -82,1184 +81,1306 @@ import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class WorkflowAction {
- private static final String WORKFLOW_ACTION_ERROR_MESSAGE = "WorkflowActionErrorMessage";
- private static final String SERVICE_INSTANCES = "serviceInstances";
- private static final String VF_MODULES = "vfModules";
- private static final String WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI = "WorkflowAction was unable to verify if the instance name already exist in AAI.";
- private static final String G_ORCHESTRATION_FLOW = "gOrchestrationFlow";
- private static final String G_ACTION = "requestAction";
- private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
- private static final String G_REQUEST_ID = "mso-request-id";
- private static final String G_BPMN_REQUEST = "bpmnRequest";
- private static final String G_ALACARTE = "aLaCarte";
- private static final String G_APIVERSION = "apiVersion";
- private static final String G_URI = "requestUri";
- private static final String G_ISTOPLEVELFLOW = "isTopLevelFlow";
- private static final String VNF_TYPE = "vnfType";
- private static final String SERVICE = "Service";
- private static final String VNF = "Vnf";
- private static final String VFMODULE = "VfModule";
- private static final String VOLUMEGROUP = "VolumeGroup";
- private static final String NETWORK = "Network";
- private static final String NETWORKCOLLECTION = "NetworkCollection";
- private static final String CONFIGURATION = "Configuration";
- private static final String ASSIGNINSTANCE = "assignInstance";
- private static final String CREATEINSTANCE = "createInstance";
- private static final String USERPARAMSERVICE = "service";
- private static final String supportedTypes = "vnfs|vfModules|networks|networkCollections|volumeGroups|serviceInstances|instanceGroups";
- private static final String HOMINGSOLUTION = "Homing_Solution";
- private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
- private static final String G_SERVICE_TYPE = "serviceType";
- private static final String SERVICE_TYPE_TRANSPORT = "TRANSPORT";
- private static final Logger logger = LoggerFactory.getLogger(WorkflowAction.class);
-
- @Autowired
- protected BBInputSetup bbInputSetup;
- @Autowired
- protected BBInputSetupUtils bbInputSetupUtils;
- @Autowired
- private ExceptionBuilder exceptionBuilder;
- @Autowired
- private CatalogDbClient catalogDbClient;
- @Autowired
- private AAIConfigurationResources aaiConfigurationResources;
- @Autowired
- private WorkflowActionExtractResourcesAAI workflowActionUtils;
+ private static final String WORKFLOW_ACTION_ERROR_MESSAGE = "WorkflowActionErrorMessage";
+ private static final String SERVICE_INSTANCES = "serviceInstances";
+ private static final String VF_MODULES = "vfModules";
+ private static final String WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI =
+ "WorkflowAction was unable to verify if the instance name already exist in AAI.";
+ private static final String G_ORCHESTRATION_FLOW = "gOrchestrationFlow";
+ private static final String G_ACTION = "requestAction";
+ private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
+ private static final String G_REQUEST_ID = "mso-request-id";
+ private static final String G_BPMN_REQUEST = "bpmnRequest";
+ private static final String G_ALACARTE = "aLaCarte";
+ private static final String G_APIVERSION = "apiVersion";
+ private static final String G_URI = "requestUri";
+ private static final String G_ISTOPLEVELFLOW = "isTopLevelFlow";
+ private static final String VNF_TYPE = "vnfType";
+ private static final String SERVICE = "Service";
+ private static final String VNF = "Vnf";
+ private static final String VFMODULE = "VfModule";
+ private static final String VOLUMEGROUP = "VolumeGroup";
+ private static final String NETWORK = "Network";
+ private static final String NETWORKCOLLECTION = "NetworkCollection";
+ private static final String CONFIGURATION = "Configuration";
+ private static final String ASSIGNINSTANCE = "assignInstance";
+ private static final String CREATEINSTANCE = "createInstance";
+ private static final String USERPARAMSERVICE = "service";
+ private static final String supportedTypes =
+ "vnfs|vfModules|networks|networkCollections|volumeGroups|serviceInstances|instanceGroups";
+ private static final String HOMINGSOLUTION = "Homing_Solution";
+ private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
+ private static final String G_SERVICE_TYPE = "serviceType";
+ private static final String SERVICE_TYPE_TRANSPORT = "TRANSPORT";
+ private static final Logger logger = LoggerFactory.getLogger(WorkflowAction.class);
+
+ @Autowired
+ protected BBInputSetup bbInputSetup;
+ @Autowired
+ protected BBInputSetupUtils bbInputSetupUtils;
+ @Autowired
+ private ExceptionBuilder exceptionBuilder;
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+ @Autowired
+ private AAIConfigurationResources aaiConfigurationResources;
+ @Autowired
+ private WorkflowActionExtractResourcesAAI workflowActionUtils;
+
+ @Autowired
+ private Environment environment;
+ private String defaultCloudOwner = "org.onap.so.cloud-owner";
+
+ public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) {
+ this.bbInputSetupUtils = bbInputSetupUtils;
+ }
+
+ public void setBbInputSetup(BBInputSetup bbInputSetup) {
+ this.bbInputSetup = bbInputSetup;
+ }
+
+ public void selectExecutionList(DelegateExecution execution) throws Exception {
+ final String requestAction = (String) execution.getVariable(G_ACTION);
+ final String requestId = (String) execution.getVariable(G_REQUEST_ID);
+ final String bpmnRequest = (String) execution.getVariable(G_BPMN_REQUEST);
+ final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
+ final String apiVersion = (String) execution.getVariable(G_APIVERSION);
+ final String uri = (String) execution.getVariable(G_URI);
+ final String vnfType = (String) execution.getVariable(VNF_TYPE);
+ String serviceInstanceId = (String) execution.getVariable("serviceInstanceId");
+ final String serviceType = Optional.ofNullable((String) execution.getVariable(G_SERVICE_TYPE)).orElse("");
+
+ List<OrchestrationFlow> orchFlows = (List<OrchestrationFlow>) execution.getVariable(G_ORCHESTRATION_FLOW);
+ List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>();
+ WorkflowResourceIds workflowResourceIds = populateResourceIdsFromApiHandler(execution);
+ List<Pair<WorkflowType, String>> aaiResourceIds = new ArrayList<>();
+ List<Resource> resourceCounter = new ArrayList<>();
+ execution.setVariable("sentSyncResponse", false);
+ execution.setVariable("homing", false);
+ execution.setVariable("calledHoming", false);
+
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ execution.setVariable(G_ISTOPLEVELFLOW, true);
+ ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class);
+ RequestDetails requestDetails = sIRequest.getRequestDetails();
+ String cloudOwner = "";
+ try {
+ cloudOwner = requestDetails.getCloudConfiguration().getCloudOwner();
+ } catch (Exception ex) {
+ cloudOwner = environment.getProperty(defaultCloudOwner);
+ }
+ boolean suppressRollback = false;
+ try {
+ suppressRollback = requestDetails.getRequestInfo().getSuppressRollback();
+ } catch (Exception ex) {
+ suppressRollback = false;
+ }
+ execution.setVariable("suppressRollback", suppressRollback);
+ Resource resource = extractResourceIdAndTypeFromUri(uri);
+ WorkflowType resourceType = resource.getResourceType();
+ execution.setVariable("resourceName", resourceType.toString());
+ String resourceId = "";
+ if (resource.isGenerated()) {
+ resourceId = validateResourceIdInAAI(resource.getResourceId(), resourceType,
+ sIRequest.getRequestDetails().getRequestInfo().getInstanceName(), sIRequest.getRequestDetails(),
+ workflowResourceIds);
+ } else {
+ resourceId = resource.getResourceId();
+ }
+ if ((serviceInstanceId == null || serviceInstanceId.equals("")) && resourceType == WorkflowType.SERVICE) {
+ serviceInstanceId = resourceId;
+ }
+ execution.setVariable("resourceId", resourceId);
+ execution.setVariable("resourceType", resourceType);
+
+ if (aLaCarte) {
+ if (orchFlows == null || orchFlows.isEmpty()) {
+ orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, aLaCarte,
+ cloudOwner, serviceType);
+ }
+ String key = "";
+ ModelInfo modelInfo = sIRequest.getRequestDetails().getModelInfo();
+ if (modelInfo != null) {
+ if (modelInfo.getModelType().equals(ModelType.service)) {
+ key = modelInfo.getModelVersionId();
+ } else {
+ key = modelInfo.getModelCustomizationId();
+ }
+ }
+ boolean isConfiguration = isConfiguration(orchFlows);
+ Resource resourceKey = new Resource(resourceType, key, aLaCarte);
+ if (isConfiguration && !requestAction.equalsIgnoreCase(CREATEINSTANCE)) {
+ List<ExecuteBuildingBlock> configBuildingBlocks = getConfigBuildingBlocks(sIRequest, orchFlows,
+ requestId, resourceKey, apiVersion, resourceId, requestAction, aLaCarte, vnfType,
+ workflowResourceIds, requestDetails, execution);
+ flowsToExecute.addAll(configBuildingBlocks);
+ }
+ orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().contains(FABRIC_CONFIGURATION))
+ .collect(Collectors.toList());
+ for (OrchestrationFlow orchFlow : orchFlows) {
+ ExecuteBuildingBlock ebb = buildExecuteBuildingBlock(orchFlow, requestId, resourceKey, apiVersion,
+ resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false,
+ null, false);
+ flowsToExecute.add(ebb);
+ }
+ } else {
+ boolean foundRelated = false;
+ boolean containsService = false;
+ if (resourceType == WorkflowType.SERVICE && requestAction.equalsIgnoreCase(ASSIGNINSTANCE)) {
+ // SERVICE-MACRO-ASSIGN will always get user params with a
+ // service.
+ if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
+ List<Map<String, Object>> userParams =
+ sIRequest.getRequestDetails().getRequestParameters().getUserParams();
+ for (Map<String, Object> params : userParams) {
+ if (params.containsKey(USERPARAMSERVICE)) {
+ containsService = true;
+ }
+ }
+ if (containsService) {
+ traverseUserParamsService(execution, resourceCounter, sIRequest, requestAction);
+ }
+ } else {
+ buildAndThrowException(execution,
+ "Service-Macro-Assign request details must contain user params with a service");
+ }
+ } else if (resourceType == WorkflowType.SERVICE && requestAction.equalsIgnoreCase(CREATEINSTANCE)) {
+ // SERVICE-MACRO-CREATE will get user params with a service,
+ // a service with a network, a service with a
+ // networkcollection, OR an empty service.
+ // If user params is just a service or null and macro
+ // queries the SI and finds a VNF, macro fails.
+
+ if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
+ List<Map<String, Object>> userParams =
+ sIRequest.getRequestDetails().getRequestParameters().getUserParams();
+ for (Map<String, Object> params : userParams) {
+ if (params.containsKey(USERPARAMSERVICE)) {
+ containsService = true;
+ }
+ }
+ }
+ if (containsService) {
+ foundRelated = traverseUserParamsService(execution, resourceCounter, sIRequest, requestAction);
+ }
+ if (!foundRelated) {
+ traverseCatalogDbService(execution, sIRequest, resourceCounter);
+ }
+ } else if (resourceType == WorkflowType.SERVICE && (requestAction.equalsIgnoreCase("activateInstance")
+ || requestAction.equalsIgnoreCase("unassignInstance")
+ || requestAction.equalsIgnoreCase("deleteInstance")
+ || requestAction.equalsIgnoreCase("activate" + FABRIC_CONFIGURATION))) {
+ // SERVICE-MACRO-ACTIVATE, SERVICE-MACRO-UNASSIGN, and
+ // SERVICE-MACRO-DELETE
+ // Will never get user params with service, macro will have
+ // to query the SI in AAI to find related instances.
+ traverseAAIService(execution, resourceCounter, resourceId, aaiResourceIds);
+ } else if (resourceType == WorkflowType.SERVICE
+ && requestAction.equalsIgnoreCase("deactivateInstance")) {
+ resourceCounter.add(new Resource(WorkflowType.SERVICE, "", false));
+ } else if (resourceType == WorkflowType.VNF && (requestAction.equalsIgnoreCase("replaceInstance")
+ || (requestAction.equalsIgnoreCase("recreateInstance")))) {
+ traverseAAIVnf(execution, resourceCounter, workflowResourceIds.getServiceInstanceId(),
+ workflowResourceIds.getVnfId(), aaiResourceIds);
+ } else {
+ buildAndThrowException(execution, "Current Macro Request is not supported");
+ }
+ String foundObjects = "";
+ for (WorkflowType type : WorkflowType.values()) {
+ foundObjects = foundObjects + type + " - " + resourceCounter.stream()
+ .filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList()).size() + " ";
+ }
+ logger.info("Found {}", foundObjects);
+
+ if (orchFlows == null || orchFlows.isEmpty()) {
+ orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, aLaCarte,
+ cloudOwner, serviceType);
+ }
+ flowsToExecute =
+ buildExecuteBuildingBlockList(orchFlows, resourceCounter, requestId, apiVersion, resourceId,
+ resourceType, requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails);
+ if (!resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType())
+ .collect(Collectors.toList()).isEmpty()) {
+ logger.info("Sorting for Vlan Tagging");
+ flowsToExecute = sortExecutionPathByObjectForVlanTagging(flowsToExecute, requestAction);
+ }
+ // By default, enable homing at VNF level for CREATEINSTANCE and ASSIGNINSTANCE
+ if (resourceType == WorkflowType.SERVICE
+ && (requestAction.equals(CREATEINSTANCE) || requestAction.equals(ASSIGNINSTANCE))
+ && !resourceCounter.stream().filter(x -> WorkflowType.VNF.equals(x.getResourceType()))
+ .collect(Collectors.toList()).isEmpty()) {
+ execution.setVariable("homing", true);
+ execution.setVariable("calledHoming", false);
+ }
+ if (resourceType == WorkflowType.SERVICE && (requestAction.equalsIgnoreCase(ASSIGNINSTANCE)
+ || requestAction.equalsIgnoreCase(CREATEINSTANCE))) {
+ generateResourceIds(flowsToExecute, resourceCounter, serviceInstanceId);
+ } else {
+ updateResourceIdsFromAAITraversal(flowsToExecute, resourceCounter, aaiResourceIds,
+ serviceInstanceId);
+ }
+ }
+
+ // If the user set "Homing_Solution" to "none", disable homing, else if "Homing_Solution" is specified,
+ // enable it.
+ if (sIRequest.getRequestDetails().getRequestParameters() != null
+ && sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
+ List<Map<String, Object>> userParams =
+ sIRequest.getRequestDetails().getRequestParameters().getUserParams();
+ for (Map<String, Object> params : userParams) {
+ if (params.containsKey(HOMINGSOLUTION)) {
+ if (params.get(HOMINGSOLUTION).equals("none")) {
+ execution.setVariable("homing", false);
+ } else {
+ execution.setVariable("homing", true);
+ }
+ }
+ }
+ }
+
+ if (flowsToExecute.isEmpty()) {
+ throw new IllegalStateException("Macro did not come up with a valid execution path.");
+ }
+ List<String> flowNames = new ArrayList<>();
+ logger.info("List of BuildingBlocks to execute:");
+ for (ExecuteBuildingBlock ebb : flowsToExecute) {
+ logger.info(ebb.getBuildingBlock().getBpmnFlowName());
+ flowNames.add(ebb.getBuildingBlock().getBpmnFlowName());
+ }
+ execution.setVariable("flowNames", flowNames);
+ execution.setVariable(G_CURRENT_SEQUENCE, 0);
+ execution.setVariable("retryCount", 0);
+ execution.setVariable("isRollback", false);
+ execution.setVariable("flowsToExecute", flowsToExecute);
+ execution.setVariable("isRollbackComplete", false);
+
+ } catch (Exception ex) {
+ buildAndThrowException(execution, "Exception in create execution list " + ex.getMessage(), ex);
+ }
+ }
+
+ protected <T> List<T> getRelatedResourcesInVfModule(String vnfId, String vfModuleId, Class<T> resultClass,
+ AAIObjectType type) {
+ List<T> vnfcs = new ArrayList<>();
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId);
+ AAIResultWrapper vfModuleResultsWrapper = bbInputSetupUtils.getAAIResourceDepthOne(uri);
+ Optional<Relationships> relationshipsOp = vfModuleResultsWrapper.getRelationships();
+ if (!relationshipsOp.isPresent()) {
+ logger.debug("No relationships were found for vfModule in AAI");
+ } else {
+ Relationships relationships = relationshipsOp.get();
+ List<AAIResultWrapper> vnfcResultWrappers = relationships.getByType(type);
+ for (AAIResultWrapper vnfcResultWrapper : vnfcResultWrappers) {
+ Optional<T> vnfcOp = vnfcResultWrapper.asBean(resultClass);
+ if (vnfcOp.isPresent()) {
+ vnfcs.add(vnfcOp.get());
+ }
+ }
+ }
+ return vnfcs;
+ }
+
+ protected <T> List<T> getRelatedResourcesInVnfc(Vnfc vnfc, Class<T> resultClass, AAIObjectType type) {
+
+ List<T> configurations = new ArrayList<>();
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VNFC, vnfc.getVnfcName());
+ AAIResultWrapper vnfcResultsWrapper = bbInputSetupUtils.getAAIResourceDepthOne(uri);
+ Optional<Relationships> relationshipsOp = vnfcResultsWrapper.getRelationships();
+ if (!relationshipsOp.isPresent()) {
+ logger.debug("No relationships were found for VNFC in AAI");
+ } else {
+ Relationships relationships = relationshipsOp.get();
+ List<AAIResultWrapper> configurationResultWrappers =
+ this.getResultWrappersFromRelationships(relationships, type);
+ for (AAIResultWrapper configurationResultWrapper : configurationResultWrappers) {
+ Optional<T> configurationOp = configurationResultWrapper.asBean(resultClass);
+ if (configurationOp.isPresent()) {
+ configurations.add(configurationOp.get());
+ }
+ }
+ }
+ return configurations;
+ }
+
+ protected List<AAIResultWrapper> getResultWrappersFromRelationships(Relationships relationships,
+ AAIObjectType type) {
+ return relationships.getByType(type);
+ }
- @Autowired
- private Environment environment;
- private String defaultCloudOwner = "org.onap.so.cloud-owner";
+ protected boolean isConfiguration(List<OrchestrationFlow> orchFlows) {
+ for (OrchestrationFlow flow : orchFlows) {
+ if (flow.getFlowName().contains("Configuration")) {
+ return true;
+ }
+ }
+ return false;
+ }
- public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) {
- this.bbInputSetupUtils = bbInputSetupUtils;
- }
+ protected List<ExecuteBuildingBlock> getConfigBuildingBlocks(ServiceInstancesRequest sIRequest,
+ List<OrchestrationFlow> orchFlows, String requestId, Resource resourceKey, String apiVersion,
+ String resourceId, String requestAction, boolean aLaCarte, String vnfType,
+ WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails, DelegateExecution execution) {
- public void setBbInputSetup(BBInputSetup bbInputSetup) {
- this.bbInputSetup = bbInputSetup;
- }
+ List<ExecuteBuildingBlock> flowsToExecuteConfigs = new ArrayList<>();
+ List<OrchestrationFlow> result = new ArrayList<>(orchFlows);
+ result = orchFlows.stream().filter(item -> item.getFlowName().contains(FABRIC_CONFIGURATION))
+ .collect(Collectors.toList());
+ String vnfId = workflowResourceIds.getVnfId();
+ String vfModuleId = workflowResourceIds.getVfModuleId();
- public void selectExecutionList(DelegateExecution execution) throws Exception {
- final String requestAction = (String) execution.getVariable(G_ACTION);
- final String requestId = (String) execution.getVariable(G_REQUEST_ID);
- final String bpmnRequest = (String) execution.getVariable(G_BPMN_REQUEST);
- final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
- final String apiVersion = (String) execution.getVariable(G_APIVERSION);
- final String uri = (String) execution.getVariable(G_URI);
- final String vnfType = (String) execution.getVariable(VNF_TYPE);
- String serviceInstanceId = (String) execution.getVariable("serviceInstanceId");
- final String serviceType = Optional.ofNullable((String) execution.getVariable(G_SERVICE_TYPE)).orElse("");
+ String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
+ String vfModuleCustomizationUUID =
+ bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
- List<OrchestrationFlow> orchFlows = (List<OrchestrationFlow>) execution.getVariable(G_ORCHESTRATION_FLOW);
- List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>();
- WorkflowResourceIds workflowResourceIds = populateResourceIdsFromApiHandler(execution);
- List<Pair<WorkflowType, String>> aaiResourceIds = new ArrayList<>();
- List<Resource> resourceCounter = new ArrayList<>();
- execution.setVariable("sentSyncResponse", false);
- execution.setVariable("homing", false);
- execution.setVariable("calledHoming", false);
+ List<org.onap.aai.domain.yang.Vnfc> vnfcs = getRelatedResourcesInVfModule(vnfId, vfModuleId,
+ org.onap.aai.domain.yang.Vnfc.class, AAIObjectType.VNFC);
+ for (org.onap.aai.domain.yang.Vnfc vnfc : vnfcs) {
+ List<org.onap.aai.domain.yang.Configuration> configurations = getRelatedResourcesInVnfc(vnfc,
+ org.onap.aai.domain.yang.Configuration.class, AAIObjectType.CONFIGURATION);
+ if (configurations.size() > 1) {
+ String multipleRelationshipsError =
+ "Multiple relationships exist from VNFC " + vnfc.getVnfcName() + " to Configurations";
+ buildAndThrowException(execution, multipleRelationshipsError,
+ new Exception(multipleRelationshipsError));
+ }
+ for (org.onap.aai.domain.yang.Configuration configuration : configurations) {
+ workflowResourceIds.setConfigurationId(configuration.getConfigurationId());
+ for (OrchestrationFlow orchFlow : result) {
+ resourceKey.setVfModuleCustomizationId(vfModuleCustomizationUUID);
+ resourceKey.setCvnfModuleCustomizationId(vnfc.getModelCustomizationId());
+ resourceKey.setVnfCustomizationId(vnfCustomizationUUID);
+ ExecuteBuildingBlock ebb = buildExecuteBuildingBlock(orchFlow, requestId, resourceKey, apiVersion,
+ resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false,
+ null, true);
+ String vnfcName = getVnfcNameForConfiguration(configuration);
+ if (vnfcName == null || vnfcName.isEmpty()) {
+ buildAndThrowException(execution, "Exception in create execution list "
+ + ": VnfcName does not exist or is null while there is a configuration for the vfModule",
+ new Exception("Vnfc and Configuration do not match"));
+ }
+ ebb.getConfigurationResourceKeys().setVnfcName(vnfcName);
+ flowsToExecuteConfigs.add(ebb);
+ }
+ }
+ }
+ return flowsToExecuteConfigs;
+ }
- try {
- ObjectMapper mapper = new ObjectMapper();
- execution.setVariable(G_ISTOPLEVELFLOW, true);
- ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class);
- RequestDetails requestDetails = sIRequest.getRequestDetails();
- String cloudOwner = "";
- try{
- cloudOwner = requestDetails.getCloudConfiguration().getCloudOwner();
- } catch (Exception ex) {
- cloudOwner = environment.getProperty(defaultCloudOwner);
- }
- boolean suppressRollback = false;
- try{
- suppressRollback = requestDetails.getRequestInfo().getSuppressRollback();
- } catch (Exception ex) {
- suppressRollback = false;
- }
- execution.setVariable("suppressRollback", suppressRollback);
- Resource resource = extractResourceIdAndTypeFromUri(uri);
- WorkflowType resourceType = resource.getResourceType();
- execution.setVariable("resourceName", resourceType.toString());
- String resourceId = "";
- if (resource.isGenerated()) {
- resourceId = validateResourceIdInAAI(resource.getResourceId(), resourceType,
- sIRequest.getRequestDetails().getRequestInfo().getInstanceName(), sIRequest.getRequestDetails(),
- workflowResourceIds);
- } else {
- resourceId = resource.getResourceId();
- }
- if((serviceInstanceId == null || serviceInstanceId.equals("")) && resourceType == WorkflowType.SERVICE){
- serviceInstanceId = resourceId;
- }
- execution.setVariable("resourceId", resourceId);
- execution.setVariable("resourceType", resourceType);
+ protected String getVnfcNameForConfiguration(org.onap.aai.domain.yang.Configuration configuration) {
+ AAIResultWrapper wrapper = new AAIResultWrapper(configuration);
+ Optional<Relationships> relationshipsOp = wrapper.getRelationships();
+ if (!relationshipsOp.isPresent()) {
+ logger.debug("No relationships were found for Configuration in AAI");
+ return null;
+ } else {
+ Relationships relationships = relationshipsOp.get();
+ List<AAIResultWrapper> vnfcResultWrappers = relationships.getByType(AAIObjectType.VNFC);
+ if (vnfcResultWrappers.size() > 1 || vnfcResultWrappers.isEmpty()) {
+ logger.debug("Too many vnfcs or no vnfc found that are related to configuration");
+ }
+ Optional<Vnfc> vnfcOp = vnfcResultWrappers.get(0).asBean(Vnfc.class);
+ if (vnfcOp.isPresent()) {
+ return vnfcOp.get().getVnfcName();
+ } else {
+ return null;
+ }
+ }
+ }
- if (aLaCarte) {
- if (orchFlows == null || orchFlows.isEmpty()) {
- orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, aLaCarte, cloudOwner, serviceType);
- }
- String key = "";
- ModelInfo modelInfo = sIRequest.getRequestDetails().getModelInfo();
- if(modelInfo != null) {
- if(modelInfo.getModelType().equals(ModelType.service)) {
- key = modelInfo.getModelVersionId();
- } else {
- key = modelInfo.getModelCustomizationId();
- }
- }
- boolean isConfiguration = isConfiguration(orchFlows);
- Resource resourceKey = new Resource(resourceType, key, aLaCarte);
- if(isConfiguration && !requestAction.equalsIgnoreCase(CREATEINSTANCE)) {
- List<ExecuteBuildingBlock> configBuildingBlocks = getConfigBuildingBlocks(sIRequest, orchFlows, requestId, resourceKey, apiVersion, resourceId, requestAction, aLaCarte, vnfType,
- workflowResourceIds, requestDetails, execution);
- flowsToExecute.addAll(configBuildingBlocks);
- }
- orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().contains(FABRIC_CONFIGURATION)).collect(Collectors.toList());
- for (OrchestrationFlow orchFlow : orchFlows) {
- ExecuteBuildingBlock ebb = buildExecuteBuildingBlock(orchFlow, requestId, resourceKey, apiVersion, resourceId,
- requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false);
- flowsToExecute.add(ebb);
- }
- } else {
- boolean foundRelated = false;
- boolean containsService = false;
- if (resourceType == WorkflowType.SERVICE && requestAction.equalsIgnoreCase(ASSIGNINSTANCE)) {
- // SERVICE-MACRO-ASSIGN will always get user params with a
- // service.
- if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
- List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters()
- .getUserParams();
- for (Map<String, Object> params : userParams) {
- if (params.containsKey(USERPARAMSERVICE)) {
- containsService = true;
- }
- }
- if (containsService) {
- traverseUserParamsService(execution, resourceCounter, sIRequest, requestAction);
- }
- } else {
- buildAndThrowException(execution,
- "Service-Macro-Assign request details must contain user params with a service");
- }
- } else if (resourceType == WorkflowType.SERVICE
- && requestAction.equalsIgnoreCase(CREATEINSTANCE)) {
- // SERVICE-MACRO-CREATE will get user params with a service,
- // a service with a network, a service with a
- // networkcollection, OR an empty service.
- // If user params is just a service or null and macro
- // queries the SI and finds a VNF, macro fails.
+ protected List<Resource> sortVfModulesByBaseFirst(List<Resource> vfModuleResources) {
+ int count = 0;
+ for (Resource resource : vfModuleResources) {
+ if (resource.isBaseVfModule()) {
+ Collections.swap(vfModuleResources, 0, count);
+ break;
+ }
+ count++;
+ }
+ return vfModuleResources;
+ }
- if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
- List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters()
- .getUserParams();
- for (Map<String, Object> params : userParams) {
- if (params.containsKey(USERPARAMSERVICE)) {
- containsService = true;
- }
- }
- }
- if (containsService) {
- foundRelated = traverseUserParamsService(execution, resourceCounter, sIRequest, requestAction);
- }
- if (!foundRelated) {
- traverseCatalogDbService(execution, sIRequest, resourceCounter);
- }
- } else if (resourceType == WorkflowType.SERVICE
- && (requestAction.equalsIgnoreCase("activateInstance")
- || requestAction.equalsIgnoreCase("unassignInstance")
- || requestAction.equalsIgnoreCase("deleteInstance")
- || requestAction.equalsIgnoreCase("activate" + FABRIC_CONFIGURATION))) {
- // SERVICE-MACRO-ACTIVATE, SERVICE-MACRO-UNASSIGN, and
- // SERVICE-MACRO-DELETE
- // Will never get user params with service, macro will have
- // to query the SI in AAI to find related instances.
- traverseAAIService(execution, resourceCounter, resourceId, aaiResourceIds);
- } else if (resourceType == WorkflowType.SERVICE
- && requestAction.equalsIgnoreCase("deactivateInstance")) {
- resourceCounter.add(new Resource(WorkflowType.SERVICE,"",false));
- } else if (resourceType == WorkflowType.VNF && (requestAction.equalsIgnoreCase("replaceInstance") || (requestAction.equalsIgnoreCase("recreateInstance")))) {
- traverseAAIVnf(execution, resourceCounter, workflowResourceIds.getServiceInstanceId(), workflowResourceIds.getVnfId(), aaiResourceIds);
- } else {
- buildAndThrowException(execution, "Current Macro Request is not supported");
- }
- String foundObjects = "";
- for(WorkflowType type : WorkflowType.values()){
- foundObjects = foundObjects + type + " - " + resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList()).size() + " ";
- }
- logger.info("Found {}", foundObjects);
+ protected List<Resource> sortVfModulesByBaseLast(List<Resource> vfModuleResources) {
+ int count = 0;
+ for (Resource resource : vfModuleResources) {
+ if (resource.isBaseVfModule()) {
+ Collections.swap(vfModuleResources, vfModuleResources.size() - 1, count);
+ break;
+ }
+ count++;
+ }
+ return vfModuleResources;
+ }
- if (orchFlows == null || orchFlows.isEmpty()) {
- orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, aLaCarte, cloudOwner, serviceType);
- }
- flowsToExecute = buildExecuteBuildingBlockList(orchFlows, resourceCounter, requestId, apiVersion, resourceId,
- resourceType, requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails);
- if (!resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()).collect(Collectors.toList()).isEmpty()) {
- logger.info("Sorting for Vlan Tagging");
- flowsToExecute = sortExecutionPathByObjectForVlanTagging(flowsToExecute, requestAction);
- }
- // By default, enable homing at VNF level for CREATEINSTANCE and ASSIGNINSTANCE
- if (resourceType == WorkflowType.SERVICE
- && (requestAction.equals(CREATEINSTANCE) || requestAction.equals(ASSIGNINSTANCE))
- && !resourceCounter.stream().filter(x -> WorkflowType.VNF.equals(x.getResourceType())).collect(Collectors.toList()).isEmpty()) {
- execution.setVariable("homing", true);
- execution.setVariable("calledHoming", false);
- }
- if (resourceType == WorkflowType.SERVICE && (requestAction.equalsIgnoreCase(ASSIGNINSTANCE) || requestAction.equalsIgnoreCase(CREATEINSTANCE))){
- generateResourceIds(flowsToExecute, resourceCounter, serviceInstanceId);
- }else{
- updateResourceIdsFromAAITraversal(flowsToExecute, resourceCounter, aaiResourceIds, serviceInstanceId);
- }
- }
+ private void updateResourceIdsFromAAITraversal(List<ExecuteBuildingBlock> flowsToExecute,
+ List<Resource> resourceCounter, List<Pair<WorkflowType, String>> aaiResourceIds, String serviceInstanceId) {
+ for (Pair<WorkflowType, String> pair : aaiResourceIds) {
+ logger.debug(pair.getValue0() + ", " + pair.getValue1());
+ }
- // If the user set "Homing_Solution" to "none", disable homing, else if "Homing_Solution" is specified, enable it.
- if (sIRequest.getRequestDetails().getRequestParameters() != null &&
- sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
- List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters().getUserParams();
- for (Map<String, Object> params : userParams) {
- if (params.containsKey(HOMINGSOLUTION)) {
- if (params.get(HOMINGSOLUTION).equals("none")) {
- execution.setVariable("homing", false);
- } else {
- execution.setVariable("homing", true);
- }
- }
- }
- }
+ Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE)).forEach(type -> {
+ List<Resource> resources =
+ resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList());
+ for (int i = 0; i < resources.size(); i++) {
+ updateWorkflowResourceIds(flowsToExecute, type, resources.get(i).getResourceId(),
+ retrieveAAIResourceId(aaiResourceIds, type), null, serviceInstanceId);
+ }
+ });
+ }
- if (flowsToExecute.isEmpty()) {
- throw new IllegalStateException("Macro did not come up with a valid execution path.");
- }
- List<String> flowNames = new ArrayList<>();
- logger.info("List of BuildingBlocks to execute:");
- for (ExecuteBuildingBlock ebb : flowsToExecute) {
- logger.info(ebb.getBuildingBlock().getBpmnFlowName());
- flowNames.add(ebb.getBuildingBlock().getBpmnFlowName());
- }
- execution.setVariable("flowNames", flowNames);
- execution.setVariable(G_CURRENT_SEQUENCE, 0);
- execution.setVariable("retryCount", 0);
- execution.setVariable("isRollback", false);
- execution.setVariable("flowsToExecute", flowsToExecute);
- execution.setVariable("isRollbackComplete", false);
+ private String retrieveAAIResourceId(List<Pair<WorkflowType, String>> aaiResourceIds, WorkflowType resource) {
+ String id = null;
+ for (int i = 0; i < aaiResourceIds.size(); i++) {
+ if (aaiResourceIds.get(i).getValue0() == resource) {
+ id = aaiResourceIds.get(i).getValue1();
+ aaiResourceIds.remove(i);
+ break;
+ }
+ }
+ return id;
+ }
- } catch (Exception ex) {
- buildAndThrowException(execution, "Exception in create execution list " + ex.getMessage(), ex);
- }
- }
-
- protected <T> List<T> getRelatedResourcesInVfModule(String vnfId, String vfModuleId, Class<T> resultClass, AAIObjectType type) {
- List<T> vnfcs = new ArrayList<>();
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId);
- AAIResultWrapper vfModuleResultsWrapper = bbInputSetupUtils.getAAIResourceDepthOne(uri);
- Optional<Relationships> relationshipsOp = vfModuleResultsWrapper.getRelationships();
- if (!relationshipsOp.isPresent()) {
- logger.debug("No relationships were found for vfModule in AAI");
- } else {
- Relationships relationships = relationshipsOp.get();
- List<AAIResultWrapper> vnfcResultWrappers = relationships.getByType(type);
- for(AAIResultWrapper vnfcResultWrapper : vnfcResultWrappers) {
- Optional<T> vnfcOp = vnfcResultWrapper.asBean(resultClass);
- if(vnfcOp.isPresent()) {
- vnfcs.add(vnfcOp.get());
- }
- }
- }
- return vnfcs;
- }
-
- protected <T> List<T> getRelatedResourcesInVnfc(Vnfc vnfc, Class<T> resultClass, AAIObjectType type) {
-
- List<T> configurations = new ArrayList<>();
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VNFC, vnfc.getVnfcName());
- AAIResultWrapper vnfcResultsWrapper = bbInputSetupUtils.getAAIResourceDepthOne(uri);
- Optional<Relationships> relationshipsOp = vnfcResultsWrapper.getRelationships();
- if (!relationshipsOp.isPresent()) {
- logger.debug("No relationships were found for VNFC in AAI");
- } else {
- Relationships relationships = relationshipsOp.get();
- List<AAIResultWrapper> configurationResultWrappers = this.getResultWrappersFromRelationships(relationships, type);
- for(AAIResultWrapper configurationResultWrapper : configurationResultWrappers) {
- Optional<T> configurationOp = configurationResultWrapper.asBean(resultClass);
- if(configurationOp.isPresent()) {
- configurations.add(configurationOp.get());
- }
- }
- }
- return configurations;
- }
-
- protected List<AAIResultWrapper> getResultWrappersFromRelationships(Relationships relationships, AAIObjectType type){
- return relationships.getByType(type);
- }
-
- protected boolean isConfiguration(List<OrchestrationFlow> orchFlows) {
- for(OrchestrationFlow flow : orchFlows) {
- if(flow.getFlowName().contains("Configuration")) {
- return true;
- }
- }
- return false;
- }
+ private void generateResourceIds(List<ExecuteBuildingBlock> flowsToExecute, List<Resource> resourceCounter,
+ String serviceInstanceId) {
+ Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE)).forEach(type -> {
+ List<Resource> resources =
+ resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList());
+ for (int i = 0; i < resources.size(); i++) {
+ Resource resource = resourceCounter.stream().filter(x -> type.equals(x.getResourceType()))
+ .collect(Collectors.toList()).get(i);
+ updateWorkflowResourceIds(flowsToExecute, type, resource.getResourceId(), null,
+ resource.getVirtualLinkKey(), serviceInstanceId);
+ }
+ });
+ }
- protected List<ExecuteBuildingBlock> getConfigBuildingBlocks(ServiceInstancesRequest sIRequest, List<OrchestrationFlow> orchFlows, String requestId, Resource resourceKey,
- String apiVersion, String resourceId, String requestAction, boolean aLaCarte, String vnfType,
- WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails, DelegateExecution execution) {
-
- List<ExecuteBuildingBlock> flowsToExecuteConfigs = new ArrayList<>();
- List<OrchestrationFlow> result = new ArrayList<>(orchFlows);
- result = orchFlows.stream().filter(item -> item.getFlowName().contains(FABRIC_CONFIGURATION)).collect(Collectors.toList());
- String vnfId = workflowResourceIds.getVnfId();
- String vfModuleId = workflowResourceIds.getVfModuleId();
-
- String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
- String vfModuleCustomizationUUID = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
+ protected void updateWorkflowResourceIds(List<ExecuteBuildingBlock> flowsToExecute, WorkflowType resource,
+ String key, String id, String virtualLinkKey, String serviceInstanceId) {
+ String resourceId = id;
+ if (resourceId == null) {
+ resourceId = UUID.randomUUID().toString();
+ }
+ for (ExecuteBuildingBlock ebb : flowsToExecute) {
+ if (key != null && key.equalsIgnoreCase(ebb.getBuildingBlock().getKey())
+ && ebb.getBuildingBlock().getBpmnFlowName().contains(resource.toString())) {
+ WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
+ workflowResourceIds.setServiceInstanceId(serviceInstanceId);
+ if (resource == WorkflowType.VNF) {
+ workflowResourceIds.setVnfId(resourceId);
+ } else if (resource == WorkflowType.VFMODULE) {
+ workflowResourceIds.setVfModuleId(resourceId);
+ } else if (resource == WorkflowType.VOLUMEGROUP) {
+ workflowResourceIds.setVolumeGroupId(resourceId);
+ } else if (resource == WorkflowType.NETWORK) {
+ workflowResourceIds.setNetworkId(resourceId);
+ } else if (resource == WorkflowType.NETWORKCOLLECTION) {
+ workflowResourceIds.setNetworkCollectionId(resourceId);
+ } else if (resource == WorkflowType.CONFIGURATION) {
+ workflowResourceIds.setConfigurationId(resourceId);
+ }
+ ebb.setWorkflowResourceIds(workflowResourceIds);
+ }
+ if (virtualLinkKey != null && ebb.getBuildingBlock().getIsVirtualLink()
+ && virtualLinkKey.equalsIgnoreCase(ebb.getBuildingBlock().getVirtualLinkKey())) {
+ WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
+ workflowResourceIds.setServiceInstanceId(serviceInstanceId);
+ workflowResourceIds.setNetworkId(resourceId);
+ ebb.setWorkflowResourceIds(workflowResourceIds);
+ }
+ }
+ }
- List<org.onap.aai.domain.yang.Vnfc> vnfcs = getRelatedResourcesInVfModule(vnfId, vfModuleId, org.onap.aai.domain.yang.Vnfc.class, AAIObjectType.VNFC);
- for(org.onap.aai.domain.yang.Vnfc vnfc : vnfcs) {
- List<org.onap.aai.domain.yang.Configuration> configurations = getRelatedResourcesInVnfc(vnfc, org.onap.aai.domain.yang.Configuration.class, AAIObjectType.CONFIGURATION);
- if (configurations.size() > 1){
- String multipleRelationshipsError = "Multiple relationships exist from VNFC "+vnfc.getVnfcName()+" to Configurations";
- buildAndThrowException(execution, multipleRelationshipsError, new Exception(multipleRelationshipsError));
- }
- for(org.onap.aai.domain.yang.Configuration configuration : configurations) {
- workflowResourceIds.setConfigurationId(configuration.getConfigurationId());
- for(OrchestrationFlow orchFlow : result) {
- resourceKey.setVfModuleCustomizationId(vfModuleCustomizationUUID);
- resourceKey.setCvnfModuleCustomizationId(vnfc.getModelCustomizationId());
- resourceKey.setVnfCustomizationId(vnfCustomizationUUID);
- ExecuteBuildingBlock ebb = buildExecuteBuildingBlock(orchFlow, requestId, resourceKey, apiVersion, resourceId,
- requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, true);
- String vnfcName = getVnfcNameForConfiguration(configuration);
- if(vnfcName == null || vnfcName.isEmpty()) {
- buildAndThrowException(execution, "Exception in create execution list " + ": VnfcName does not exist or is null while there is a configuration for the vfModule", new Exception("Vnfc and Configuration do not match"));
- }
- ebb.getConfigurationResourceKeys().setVnfcName(vnfcName);
- flowsToExecuteConfigs.add(ebb);
- }
- }
- }
- return flowsToExecuteConfigs;
- }
-
- protected String getVnfcNameForConfiguration(org.onap.aai.domain.yang.Configuration configuration) {
- AAIResultWrapper wrapper = new AAIResultWrapper(configuration);
- Optional<Relationships> relationshipsOp = wrapper.getRelationships();
- if (!relationshipsOp.isPresent()) {
- logger.debug("No relationships were found for Configuration in AAI");
- return null;
- } else {
- Relationships relationships = relationshipsOp.get();
- List<AAIResultWrapper> vnfcResultWrappers = relationships.getByType(AAIObjectType.VNFC);
- if(vnfcResultWrappers.size() > 1 || vnfcResultWrappers.isEmpty()) {
- logger.debug("Too many vnfcs or no vnfc found that are related to configuration");
- }
- Optional<Vnfc> vnfcOp = vnfcResultWrappers.get(0).asBean(Vnfc.class);
- if(vnfcOp.isPresent()) {
- return vnfcOp.get().getVnfcName();
- } else {
- return null;
- }
- }
- }
+ protected CollectionResourceCustomization findCatalogNetworkCollection(DelegateExecution execution,
+ org.onap.so.db.catalog.beans.Service service) {
+ CollectionResourceCustomization networkCollection = null;
+ int count = 0;
+ for (CollectionResourceCustomization collectionCust : service.getCollectionResourceCustomizations()) {
+ if (catalogDbClient.getNetworkCollectionResourceCustomizationByID(
+ collectionCust.getModelCustomizationUUID()) != null) {
+ networkCollection = collectionCust;
+ count++;
+ }
+ }
+ if (count == 0) {
+ return null;
+ } else if (count > 1) {
+ buildAndThrowException(execution,
+ "Found multiple Network Collections in the Service model, only one per Service is supported.");
+ }
+ return networkCollection;
+ }
- protected List<Resource> sortVfModulesByBaseFirst(List<Resource> vfModuleResources) {
- int count = 0;
- for(Resource resource : vfModuleResources){
- if(resource.isBaseVfModule()){
- Collections.swap(vfModuleResources, 0, count);
- break;
- }
- count++;
- }
- return vfModuleResources;
- }
-
- protected List<Resource> sortVfModulesByBaseLast(List<Resource> vfModuleResources) {
- int count = 0;
- for(Resource resource : vfModuleResources){
- if(resource.isBaseVfModule()){
- Collections.swap(vfModuleResources, vfModuleResources.size()-1, count);
- break;
- }
- count++;
- }
- return vfModuleResources;
- }
+ protected void traverseCatalogDbService(DelegateExecution execution, ServiceInstancesRequest sIRequest,
+ List<Resource> resourceCounter) {
+ String modelUUID = sIRequest.getRequestDetails().getModelInfo().getModelVersionId();
+ org.onap.so.db.catalog.beans.Service service = catalogDbClient.getServiceByID(modelUUID);
+ if (service == null) {
+ buildAndThrowException(execution, "Could not find the service model in catalog db.");
+ } else {
+ resourceCounter.add(new Resource(WorkflowType.SERVICE, service.getModelUUID(), false));
+ if (service.getVnfCustomizations() == null || service.getVnfCustomizations().isEmpty()) {
+ List<CollectionResourceCustomization> customizations = service.getCollectionResourceCustomizations();
+ if (customizations.isEmpty()) {
+ logger.debug("No Collections found. CollectionResourceCustomization list is empty.");
+ } else {
+ CollectionResourceCustomization collectionResourceCustomization =
+ findCatalogNetworkCollection(execution, service);
+ if (collectionResourceCustomization != null) {
+ resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION,
+ collectionResourceCustomization.getModelCustomizationUUID(), false));
+ logger.debug("Found a network collection");
+ if (collectionResourceCustomization.getCollectionResource() != null) {
+ if (collectionResourceCustomization.getCollectionResource().getInstanceGroup() != null) {
+ String toscaNodeType = collectionResourceCustomization.getCollectionResource()
+ .getInstanceGroup().getToscaNodeType();
+ if (toscaNodeType != null && toscaNodeType.contains("NetworkCollection")) {
+ int minNetworks = 0;
+ org.onap.so.db.catalog.beans.InstanceGroup instanceGroup =
+ collectionResourceCustomization.getCollectionResource().getInstanceGroup();
+ CollectionResourceInstanceGroupCustomization collectionInstCust = null;
+ if (!instanceGroup.getCollectionInstanceGroupCustomizations().isEmpty()) {
+ for (CollectionResourceInstanceGroupCustomization collectionInstanceGroupTemp : instanceGroup
+ .getCollectionInstanceGroupCustomizations()) {
+ if (collectionInstanceGroupTemp.getModelCustomizationUUID()
+ .equalsIgnoreCase(collectionResourceCustomization
+ .getModelCustomizationUUID())) {
+ collectionInstCust = collectionInstanceGroupTemp;
+ break;
+ }
+ }
+ if (collectionInstCust != null
+ && collectionInstCust.getSubInterfaceNetworkQuantity() != null) {
+ minNetworks = collectionInstCust.getSubInterfaceNetworkQuantity();
+ }
+ }
+ logger.debug("minNetworks: {}", minNetworks);
+ CollectionNetworkResourceCustomization collectionNetworkResourceCust = null;
+ for (CollectionNetworkResourceCustomization collectionNetworkTemp : instanceGroup
+ .getCollectionNetworkResourceCustomizations()) {
+ if (collectionNetworkTemp.getNetworkResourceCustomization()
+ .getModelCustomizationUUID().equalsIgnoreCase(
+ collectionResourceCustomization.getModelCustomizationUUID())) {
+ collectionNetworkResourceCust = collectionNetworkTemp;
+ break;
+ }
+ }
+ for (int i = 0; i < minNetworks; i++) {
+ if (collectionNetworkResourceCust != null && collectionInstCust != null) {
+ Resource resource = new Resource(WorkflowType.VIRTUAL_LINK,
+ collectionNetworkResourceCust.getModelCustomizationUUID(), false);
+ resource.setVirtualLinkKey(Integer.toString(i));
+ resourceCounter.add(resource);
+ }
+ }
+ } else {
+ logger.debug(
+ "Instance Group tosca node type does not contain NetworkCollection: {}",
+ toscaNodeType);
+ }
+ } else {
+ logger.debug("No Instance Group found for network collection.");
+ }
+ } else {
+ logger.debug("No Network Collection found. collectionResource is null");
+ }
+ } else {
+ logger.debug("No Network Collection Customization found");
+ }
+ }
+ if (resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType())
+ .collect(Collectors.toList()).isEmpty()) {
+ if (service.getNetworkCustomizations() == null) {
+ logger.debug("No networks were found on this service model");
+ } else {
+ for (int i = 0; i < service.getNetworkCustomizations().size(); i++) {
+ resourceCounter.add(new Resource(WorkflowType.NETWORK,
+ service.getNetworkCustomizations().get(i).getModelCustomizationUUID(), false));
+ }
+ }
+ }
+ } else {
+ buildAndThrowException(execution,
+ "Cannot orchestrate Service-Macro-Create without user params with a vnf. Please update ASDC model for new macro orchestration support or add service_recipe records to route to old macro flows");
+ }
+ }
+ }
- private void updateResourceIdsFromAAITraversal(List<ExecuteBuildingBlock> flowsToExecute,
- List<Resource> resourceCounter, List<Pair<WorkflowType, String>> aaiResourceIds, String serviceInstanceId) {
- for(Pair<WorkflowType,String> pair : aaiResourceIds){
- logger.debug(pair.getValue0() + ", " + pair.getValue1());
- }
-
- Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE)).forEach(type -> {
- List<Resource> resources = resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList());
- for(int i = 0; i < resources.size(); i++){
- updateWorkflowResourceIds(flowsToExecute, type, resources.get(i).getResourceId(), retrieveAAIResourceId(aaiResourceIds,type), null, serviceInstanceId);
- }
- });
- }
+ protected void traverseAAIService(DelegateExecution execution, List<Resource> resourceCounter, String resourceId,
+ List<Pair<WorkflowType, String>> aaiResourceIds) {
+ try {
+ ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(resourceId);
+ org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO =
+ bbInputSetup.getExistingServiceInstance(serviceInstanceAAI);
+ resourceCounter.add(new Resource(WorkflowType.SERVICE, serviceInstanceMSO.getServiceInstanceId(), false));
+ if (serviceInstanceMSO.getVnfs() != null) {
+ for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO.getVnfs()) {
+ aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VNF, vnf.getVnfId()));
+ resourceCounter.add(new Resource(WorkflowType.VNF, vnf.getVnfId(), false));
+ if (vnf.getVfModules() != null) {
+ for (VfModule vfModule : vnf.getVfModules()) {
+ aaiResourceIds.add(
+ new Pair<WorkflowType, String>(WorkflowType.VFMODULE, vfModule.getVfModuleId()));
+ resourceCounter.add(new Resource(WorkflowType.VFMODULE, vfModule.getVfModuleId(), false));
+ }
+ }
+ if (vnf.getVolumeGroups() != null) {
+ for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf
+ .getVolumeGroups()) {
+ aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VOLUMEGROUP,
+ volumeGroup.getVolumeGroupId()));
+ resourceCounter
+ .add(new Resource(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId(), false));
+ }
+ }
+ }
+ }
+ if (serviceInstanceMSO.getNetworks() != null) {
+ for (org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network : serviceInstanceMSO
+ .getNetworks()) {
+ aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.NETWORK, network.getNetworkId()));
+ resourceCounter.add(new Resource(WorkflowType.NETWORK, network.getNetworkId(), false));
+ }
+ }
+ if (serviceInstanceMSO.getCollection() != null) {
+ logger.debug("found networkcollection");
+ aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.NETWORKCOLLECTION,
+ serviceInstanceMSO.getCollection().getId()));
+ resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION,
+ serviceInstanceMSO.getCollection().getId(), false));
+ }
+ if (serviceInstanceMSO.getConfigurations() != null) {
+ for (Configuration config : serviceInstanceMSO.getConfigurations()) {
+ Optional<org.onap.aai.domain.yang.Configuration> aaiConfig =
+ aaiConfigurationResources.getConfiguration(config.getConfigurationId());
+ if (aaiConfig.isPresent() && aaiConfig.get().getRelationshipList() != null) {
+ for (Relationship relationship : aaiConfig.get().getRelationshipList().getRelationship()) {
+ if (relationship.getRelatedTo().contains("vnfc")) {
+ aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION,
+ config.getConfigurationId()));
+ resourceCounter.add(
+ new Resource(WorkflowType.CONFIGURATION, config.getConfigurationId(), false));
+ break;
+ }
+ }
+ }
+ }
+ }
+ } catch (Exception ex) {
+ buildAndThrowException(execution,
+ "Could not find existing Service Instance or related Instances to execute the request on.");
+ }
+ }
- private String retrieveAAIResourceId(List<Pair<WorkflowType, String>> aaiResourceIds, WorkflowType resource){
- String id = null;
- for(int i = 0; i<aaiResourceIds.size();i++){
- if(aaiResourceIds.get(i).getValue0() == resource){
- id = aaiResourceIds.get(i).getValue1();
- aaiResourceIds.remove(i);
- break;
- }
- }
- return id;
- }
- private void generateResourceIds(List<ExecuteBuildingBlock> flowsToExecute, List<Resource> resourceCounter, String serviceInstanceId) {
- Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE)).forEach(type -> {
- List<Resource> resources = resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList());
- for(int i = 0; i < resources.size(); i++){
- Resource resource = resourceCounter.stream().filter(x -> type.equals(x.getResourceType()))
- .collect(Collectors.toList()).get(i);
- updateWorkflowResourceIds(flowsToExecute, type, resource.getResourceId(), null, resource.getVirtualLinkKey(),serviceInstanceId);
- }
- });
- }
-
- protected void updateWorkflowResourceIds(List<ExecuteBuildingBlock> flowsToExecute, WorkflowType resource, String key, String id, String virtualLinkKey, String serviceInstanceId){
- String resourceId = id;
- if(resourceId==null){
- resourceId = UUID.randomUUID().toString();
- }
- for(ExecuteBuildingBlock ebb : flowsToExecute){
- if(key != null && key.equalsIgnoreCase(ebb.getBuildingBlock().getKey()) && ebb.getBuildingBlock().getBpmnFlowName().contains(resource.toString())){
- WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
- workflowResourceIds.setServiceInstanceId(serviceInstanceId);
- if(resource == WorkflowType.VNF){
- workflowResourceIds.setVnfId(resourceId);
- }else if(resource == WorkflowType.VFMODULE){
- workflowResourceIds.setVfModuleId(resourceId);
- }else if(resource == WorkflowType.VOLUMEGROUP){
- workflowResourceIds.setVolumeGroupId(resourceId);
- }else if(resource == WorkflowType.NETWORK){
- workflowResourceIds.setNetworkId(resourceId);
- }else if(resource == WorkflowType.NETWORKCOLLECTION){
- workflowResourceIds.setNetworkCollectionId(resourceId);
- }else if(resource == WorkflowType.CONFIGURATION){
- workflowResourceIds.setConfigurationId(resourceId);
- }
- ebb.setWorkflowResourceIds(workflowResourceIds);
- }
- if(virtualLinkKey != null && ebb.getBuildingBlock().getIsVirtualLink()
- && virtualLinkKey.equalsIgnoreCase(ebb.getBuildingBlock().getVirtualLinkKey())) {
- WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
- workflowResourceIds.setServiceInstanceId(serviceInstanceId);
- workflowResourceIds.setNetworkId(resourceId);
- ebb.setWorkflowResourceIds(workflowResourceIds);
- }
- }
- }
+ private void traverseAAIVnf(DelegateExecution execution, List<Resource> resourceCounter, String serviceId,
+ String vnfId, List<Pair<WorkflowType, String>> aaiResourceIds) {
+ try {
+ ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceId);
+ org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO =
+ bbInputSetup.getExistingServiceInstance(serviceInstanceAAI);
+ resourceCounter.add(new Resource(WorkflowType.SERVICE, serviceInstanceMSO.getServiceInstanceId(), false));
+ if (serviceInstanceMSO.getVnfs() != null) {
+ for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO.getVnfs()) {
+ if (vnf.getVnfId().equals(vnfId)) {
+ aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VNF, vnf.getVnfId()));
+ resourceCounter.add(new Resource(WorkflowType.VNF, vnf.getVnfId(), false));
+ if (vnf.getVfModules() != null) {
+ for (VfModule vfModule : vnf.getVfModules()) {
+ aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VFMODULE,
+ vfModule.getVfModuleId()));
+ resourceCounter
+ .add(new Resource(WorkflowType.VFMODULE, vfModule.getVfModuleId(), false));
+ findConfigurationsInsideVfModule(execution, vnf.getVnfId(), vfModule.getVfModuleId(),
+ resourceCounter, aaiResourceIds);
+ }
+ }
+ if (vnf.getVolumeGroups() != null) {
+ for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf
+ .getVolumeGroups()) {
+ aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VOLUMEGROUP,
+ volumeGroup.getVolumeGroupId()));
+ resourceCounter.add(
+ new Resource(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId(), false));
+ }
+ }
+ break;
+ }
+ }
+ }
+ } catch (Exception ex) {
+ buildAndThrowException(execution,
+ "Could not find existing Vnf or related Instances to execute the request on.");
+ }
+ }
- protected CollectionResourceCustomization findCatalogNetworkCollection(DelegateExecution execution, org.onap.so.db.catalog.beans.Service service) {
- CollectionResourceCustomization networkCollection = null;
- int count = 0;
- for(CollectionResourceCustomization collectionCust : service.getCollectionResourceCustomizations()){
- if(catalogDbClient.getNetworkCollectionResourceCustomizationByID(collectionCust.getModelCustomizationUUID()) != null) {
- networkCollection = collectionCust;
- count++;
- }
- }
- if(count == 0){
- return null;
- }else if(count > 1) {
- buildAndThrowException(execution, "Found multiple Network Collections in the Service model, only one per Service is supported.");
- }
- return networkCollection;
- }
-
- protected void traverseCatalogDbService(DelegateExecution execution, ServiceInstancesRequest sIRequest,
- List<Resource> resourceCounter) {
- String modelUUID = sIRequest.getRequestDetails().getModelInfo().getModelVersionId();
- org.onap.so.db.catalog.beans.Service service = catalogDbClient.getServiceByID(modelUUID);
- if (service == null) {
- buildAndThrowException(execution, "Could not find the service model in catalog db.");
- } else {
- resourceCounter.add(new Resource(WorkflowType.SERVICE,service.getModelUUID(),false));
- if (service.getVnfCustomizations() == null || service.getVnfCustomizations().isEmpty()) {
- List<CollectionResourceCustomization> customizations = service.getCollectionResourceCustomizations();
- if(customizations.isEmpty()) {
- logger.debug("No Collections found. CollectionResourceCustomization list is empty.");
- }else{
- CollectionResourceCustomization collectionResourceCustomization = findCatalogNetworkCollection(execution, service);
- if(collectionResourceCustomization!=null){
- resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION,collectionResourceCustomization.getModelCustomizationUUID(),false));
- logger.debug("Found a network collection");
- if(collectionResourceCustomization.getCollectionResource()!=null){
- if(collectionResourceCustomization.getCollectionResource().getInstanceGroup() != null){
- String toscaNodeType = collectionResourceCustomization.getCollectionResource().getInstanceGroup().getToscaNodeType();
- if (toscaNodeType != null && toscaNodeType.contains("NetworkCollection")) {
- int minNetworks = 0;
- org.onap.so.db.catalog.beans.InstanceGroup instanceGroup = collectionResourceCustomization.getCollectionResource().getInstanceGroup();
- CollectionResourceInstanceGroupCustomization collectionInstCust = null;
- if(!instanceGroup.getCollectionInstanceGroupCustomizations().isEmpty()) {
- for(CollectionResourceInstanceGroupCustomization collectionInstanceGroupTemp : instanceGroup.getCollectionInstanceGroupCustomizations()) {
- if(collectionInstanceGroupTemp.getModelCustomizationUUID().equalsIgnoreCase(collectionResourceCustomization.getModelCustomizationUUID())) {
- collectionInstCust = collectionInstanceGroupTemp;
- break;
- }
- }
- if(collectionInstCust != null && collectionInstCust.getSubInterfaceNetworkQuantity() != null) {
- minNetworks = collectionInstCust.getSubInterfaceNetworkQuantity();
- }
- }
- logger.debug("minNetworks: {}" , minNetworks);
- CollectionNetworkResourceCustomization collectionNetworkResourceCust = null;
- for(CollectionNetworkResourceCustomization collectionNetworkTemp : instanceGroup.getCollectionNetworkResourceCustomizations()) {
- if(collectionNetworkTemp.getNetworkResourceCustomization().getModelCustomizationUUID().equalsIgnoreCase(collectionResourceCustomization.getModelCustomizationUUID())) {
- collectionNetworkResourceCust = collectionNetworkTemp;
- break;
- }
- }
- for (int i = 0; i < minNetworks; i++) {
- if(collectionNetworkResourceCust != null && collectionInstCust != null) {
- Resource resource = new Resource(WorkflowType.VIRTUAL_LINK,collectionNetworkResourceCust.getModelCustomizationUUID(),false);
- resource.setVirtualLinkKey(Integer.toString(i));
- resourceCounter.add(resource);
- }
- }
- } else {
- logger.debug("Instance Group tosca node type does not contain NetworkCollection: {}" , toscaNodeType);
- }
- }else{
- logger.debug("No Instance Group found for network collection.");
- }
- }else{
- logger.debug("No Network Collection found. collectionResource is null");
- }
- } else {
- logger.debug("No Network Collection Customization found");
- }
- }
- if (resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()).collect(Collectors.toList()).isEmpty()) {
- if (service.getNetworkCustomizations() == null) {
- logger.debug("No networks were found on this service model");
- } else {
- for (int i = 0; i < service.getNetworkCustomizations().size(); i++) {
- resourceCounter.add(new Resource(WorkflowType.NETWORK,service.getNetworkCustomizations().get(i).getModelCustomizationUUID(),false));
- }
- }
- }
- } else {
- buildAndThrowException(execution,
- "Cannot orchestrate Service-Macro-Create without user params with a vnf. Please update ASDC model for new macro orchestration support or add service_recipe records to route to old macro flows");
- }
- }
- }
+ private void findConfigurationsInsideVfModule(DelegateExecution execution, String vnfId, String vfModuleId,
+ List<Resource> resourceCounter, List<Pair<WorkflowType, String>> aaiResourceIds) {
+ try {
+ org.onap.aai.domain.yang.VfModule aaiVfModule = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId);
+ AAIResultWrapper vfModuleWrapper = new AAIResultWrapper(
+ new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiVfModule));
+ Optional<Relationships> relationshipsOp;
+ relationshipsOp = vfModuleWrapper.getRelationships();
+ if (relationshipsOp.isPresent()) {
+ relationshipsOp = workflowActionUtils.extractRelationshipsVnfc(relationshipsOp.get());
+ if (relationshipsOp.isPresent()) {
+ Optional<Configuration> config =
+ workflowActionUtils.extractRelationshipsConfiguration(relationshipsOp.get());
+ if (config.isPresent()) {
+ aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION,
+ config.get().getConfigurationId()));
+ resourceCounter.add(
+ new Resource(WorkflowType.CONFIGURATION, config.get().getConfigurationId(), false));
+ }
+ }
+ }
+ } catch (Exception ex) {
+ buildAndThrowException(execution, "Failed to find Configuration object from the vfModule.");
+ }
+ }
- protected void traverseAAIService(DelegateExecution execution, List<Resource> resourceCounter, String resourceId, List<Pair<WorkflowType, String>> aaiResourceIds) {
- try {
- ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(resourceId);
- org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = bbInputSetup
- .getExistingServiceInstance(serviceInstanceAAI);
- resourceCounter.add(new Resource(WorkflowType.SERVICE,serviceInstanceMSO.getServiceInstanceId(),false));
- if (serviceInstanceMSO.getVnfs() != null) {
- for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO
- .getVnfs()) {
- aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VNF, vnf.getVnfId()));
- resourceCounter.add(new Resource(WorkflowType.VNF,vnf.getVnfId(),false));
- if (vnf.getVfModules() != null) {
- for (VfModule vfModule : vnf.getVfModules()) {
- aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VFMODULE, vfModule.getVfModuleId()));
- resourceCounter.add(new Resource(WorkflowType.VFMODULE,vfModule.getVfModuleId(),false));
- }
- }
- if (vnf.getVolumeGroups() != null) {
- for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf
- .getVolumeGroups()) {
- aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId()));
- resourceCounter.add(new Resource(WorkflowType.VOLUMEGROUP,volumeGroup.getVolumeGroupId(),false));
- }
- }
- }
- }
- if (serviceInstanceMSO.getNetworks() != null) {
- for (org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network : serviceInstanceMSO
- .getNetworks()) {
- aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.NETWORK, network.getNetworkId()));
- resourceCounter.add(new Resource(WorkflowType.NETWORK,network.getNetworkId(),false));
- }
- }
- if (serviceInstanceMSO.getCollection() != null) {
- logger.debug("found networkcollection");
- aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.NETWORKCOLLECTION, serviceInstanceMSO.getCollection().getId()));
- resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION,serviceInstanceMSO.getCollection().getId(),false));
- }
- if (serviceInstanceMSO.getConfigurations() !=null) {
- for(Configuration config : serviceInstanceMSO.getConfigurations()){
- Optional<org.onap.aai.domain.yang.Configuration> aaiConfig = aaiConfigurationResources.getConfiguration(config.getConfigurationId());
- if(aaiConfig.isPresent() && aaiConfig.get().getRelationshipList()!=null){
- for(Relationship relationship : aaiConfig.get().getRelationshipList().getRelationship()){
- if(relationship.getRelatedTo().contains("vnfc")){
- aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, config.getConfigurationId()));
- resourceCounter.add(new Resource(WorkflowType.CONFIGURATION,config.getConfigurationId(),false));
- break;
- }
- }
- }
- }
- }
- } catch (Exception ex) {
- buildAndThrowException(execution,
- "Could not find existing Service Instance or related Instances to execute the request on.");
- }
- }
+ protected boolean traverseUserParamsService(DelegateExecution execution, List<Resource> resourceCounter,
+ ServiceInstancesRequest sIRequest, String requestAction) throws IOException {
+ boolean foundRelated = false;
+ boolean foundVfModuleOrVG = false;
+ String vnfCustomizationUUID = "";
+ String vfModuleCustomizationUUID = "";
+ if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
+ List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters().getUserParams();
+ for (Map<String, Object> params : userParams) {
+ if (params.containsKey(USERPARAMSERVICE)) {
+ ObjectMapper obj = new ObjectMapper();
+ String input = obj.writeValueAsString(params.get(USERPARAMSERVICE));
+ Service validate = obj.readValue(input, Service.class);
+ resourceCounter.add(
+ new Resource(WorkflowType.SERVICE, validate.getModelInfo().getModelVersionId(), false));
+ if (validate.getResources().getVnfs() != null) {
+ for (Vnfs vnf : validate.getResources().getVnfs()) {
+ resourceCounter.add(new Resource(WorkflowType.VNF,
+ vnf.getModelInfo().getModelCustomizationId(), false));
+ foundRelated = true;
+ if (vnf.getModelInfo() != null && vnf.getModelInfo().getModelCustomizationUuid() != null) {
+ vnfCustomizationUUID = vnf.getModelInfo().getModelCustomizationUuid();
+ }
+ if (vnf.getVfModules() != null) {
+ for (VfModules vfModule : vnf.getVfModules()) {
+ VfModuleCustomization vfModuleCustomization =
+ catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID(
+ vfModule.getModelInfo().getModelCustomizationUuid());
+ if (vfModuleCustomization != null) {
- private void traverseAAIVnf(DelegateExecution execution, List<Resource> resourceCounter, String serviceId, String vnfId,
- List<Pair<WorkflowType, String>> aaiResourceIds) {
- try{
- ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceId);
- org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = bbInputSetup
- .getExistingServiceInstance(serviceInstanceAAI);
- resourceCounter.add(new Resource(WorkflowType.SERVICE,serviceInstanceMSO.getServiceInstanceId(),false));
- if (serviceInstanceMSO.getVnfs() != null) {
- for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO
- .getVnfs()) {
- if(vnf.getVnfId().equals(vnfId)){
- aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VNF, vnf.getVnfId()));
- resourceCounter.add(new Resource(WorkflowType.VNF,vnf.getVnfId(),false));
- if (vnf.getVfModules() != null) {
- for (VfModule vfModule : vnf.getVfModules()) {
- aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VFMODULE, vfModule.getVfModuleId()));
- resourceCounter.add(new Resource(WorkflowType.VFMODULE,vfModule.getVfModuleId(),false));
- findConfigurationsInsideVfModule(execution, vnf.getVnfId(), vfModule.getVfModuleId(), resourceCounter, aaiResourceIds);
- }
- }
- if (vnf.getVolumeGroups() != null) {
- for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf
- .getVolumeGroups()) {
- aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId()));
- resourceCounter.add(new Resource(WorkflowType.VOLUMEGROUP,volumeGroup.getVolumeGroupId(),false));
- }
- }
- break;
- }
- }
- }
- } catch (Exception ex) {
- buildAndThrowException(execution,
- "Could not find existing Vnf or related Instances to execute the request on.");
- }
- }
+ if (vfModuleCustomization.getVfModule() != null
+ && vfModuleCustomization.getVfModule().getVolumeHeatTemplate() != null
+ && vfModuleCustomization.getVolumeHeatEnv() != null) {
+ resourceCounter.add(new Resource(WorkflowType.VOLUMEGROUP,
+ vfModuleCustomization.getModelCustomizationUUID(), false));
+ foundRelated = true;
+ foundVfModuleOrVG = true;
+ }
- private void findConfigurationsInsideVfModule(DelegateExecution execution, String vnfId, String vfModuleId, List<Resource> resourceCounter,
- List<Pair<WorkflowType, String>> aaiResourceIds) {
- try{
- org.onap.aai.domain.yang.VfModule aaiVfModule = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId);
- AAIResultWrapper vfModuleWrapper = new AAIResultWrapper(
- new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiVfModule));
- Optional<Relationships> relationshipsOp;
- relationshipsOp = vfModuleWrapper.getRelationships();
- if(relationshipsOp.isPresent()) {
- relationshipsOp = workflowActionUtils.extractRelationshipsVnfc(relationshipsOp.get());
- if(relationshipsOp.isPresent()){
- Optional<Configuration> config = workflowActionUtils.extractRelationshipsConfiguration(relationshipsOp.get());
- if(config.isPresent()){
- aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, config.get().getConfigurationId()));
- resourceCounter.add(new Resource(WorkflowType.CONFIGURATION, config.get().getConfigurationId(), false));
- }
- }
- }
- }catch (Exception ex){
- buildAndThrowException(execution,
- "Failed to find Configuration object from the vfModule.");
- }
- }
-
- protected boolean traverseUserParamsService(DelegateExecution execution, List<Resource> resourceCounter,
- ServiceInstancesRequest sIRequest, String requestAction)
- throws IOException {
- boolean foundRelated = false;
- boolean foundVfModuleOrVG = false;
- String vnfCustomizationUUID = "";
- String vfModuleCustomizationUUID = "";
- if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
- List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters().getUserParams();
- for (Map<String, Object> params : userParams) {
- if (params.containsKey(USERPARAMSERVICE)) {
- ObjectMapper obj = new ObjectMapper();
- String input = obj.writeValueAsString(params.get(USERPARAMSERVICE));
- Service validate = obj.readValue(input, Service.class);
- resourceCounter.add(new Resource(WorkflowType.SERVICE,validate.getModelInfo().getModelVersionId(),false));
- if (validate.getResources().getVnfs() != null) {
- for (Vnfs vnf : validate.getResources().getVnfs()) {
- resourceCounter.add(new Resource(WorkflowType.VNF,vnf.getModelInfo().getModelCustomizationId(),false));
- foundRelated = true;
- if(vnf.getModelInfo()!=null && vnf.getModelInfo().getModelCustomizationUuid()!=null){
- vnfCustomizationUUID = vnf.getModelInfo().getModelCustomizationUuid();
- }
- if (vnf.getVfModules() != null) {
- for (VfModules vfModule : vnf.getVfModules()) {
- VfModuleCustomization vfModuleCustomization = catalogDbClient
- .getVfModuleCustomizationByModelCuztomizationUUID(
- vfModule.getModelInfo().getModelCustomizationUuid());
- if (vfModuleCustomization != null) {
+ if (vfModuleCustomization.getVfModule() != null
+ && vfModuleCustomization.getVfModule().getModuleHeatTemplate() != null
+ && vfModuleCustomization.getHeatEnvironment() != null) {
+ foundRelated = true;
+ foundVfModuleOrVG = true;
+ Resource resource = new Resource(WorkflowType.VFMODULE,
+ vfModuleCustomization.getModelCustomizationUUID(), false);
+ if (vfModuleCustomization.getVfModule().getIsBase() != null
+ && vfModuleCustomization.getVfModule().getIsBase()) {
+ resource.setBaseVfModule(true);
+ } else {
+ resource.setBaseVfModule(false);
+ }
+ resourceCounter.add(resource);
+ if (vfModule.getModelInfo() != null
+ && vfModule.getModelInfo().getModelCustomizationUuid() != null) {
+ vfModuleCustomizationUUID =
+ vfModule.getModelInfo().getModelCustomizationUuid();
+ }
+ if (!vnfCustomizationUUID.equals("")
+ && !vfModuleCustomizationUUID.equals("")) {
+ List<CvnfcConfigurationCustomization> configs =
+ traverseCatalogDbForConfiguration(
+ validate.getModelInfo().getModelVersionId(),
+ vnfCustomizationUUID, vfModuleCustomizationUUID);
+ for (CvnfcConfigurationCustomization config : configs) {
+ Resource configResource = new Resource(WorkflowType.CONFIGURATION,
+ config.getConfigurationResource().getModelUUID(), false);
+ resource.setVnfCustomizationId(
+ vnf.getModelInfo().getModelCustomizationId());
+ resource.setVfModuleCustomizationId(
+ vfModule.getModelInfo().getModelCustomizationId());
+ resourceCounter.add(configResource);
+ }
+ }
+ }
+ if (!foundVfModuleOrVG) {
+ buildAndThrowException(execution,
+ "Could not determine if vfModule was a vfModule or volume group. Heat template and Heat env are null");
+ }
+ }
+ }
+ }
+ }
+ }
+ if (validate.getResources().getNetworks() != null) {
+ for (Networks network : validate.getResources().getNetworks()) {
+ resourceCounter.add(new Resource(WorkflowType.NETWORK,
+ network.getModelInfo().getModelCustomizationId(), false));
+ foundRelated = true;
+ }
+ if (requestAction.equals(CREATEINSTANCE)) {
+ String networkColCustId = queryCatalogDBforNetworkCollection(execution, sIRequest);
+ if (networkColCustId != null) {
+ resourceCounter
+ .add(new Resource(WorkflowType.NETWORKCOLLECTION, networkColCustId, false));
+ foundRelated = true;
+ }
+ }
+ }
+ break;
+ }
+ }
+ }
+ return foundRelated;
+ }
- if(vfModuleCustomization.getVfModule() != null && vfModuleCustomization.getVfModule().getVolumeHeatTemplate() != null && vfModuleCustomization.getVolumeHeatEnv() != null) {
- resourceCounter.add(new Resource(WorkflowType.VOLUMEGROUP,vfModuleCustomization.getModelCustomizationUUID(),false));
- foundRelated = true;
- foundVfModuleOrVG = true;
- }
+ protected List<CvnfcConfigurationCustomization> traverseCatalogDbForConfiguration(String serviceModelUUID,
+ String vnfCustomizationUUID, String vfModuleCustomizationUUID) {
+ List<CvnfcConfigurationCustomization> configurations = new ArrayList<>();
+ try {
+ List<CvnfcCustomization> cvnfcCustomizations = catalogDbClient.getCvnfcCustomization(serviceModelUUID,
+ vnfCustomizationUUID, vfModuleCustomizationUUID);
+ for (CvnfcCustomization cvnfc : cvnfcCustomizations) {
+ for (CvnfcConfigurationCustomization customization : cvnfc.getCvnfcConfigurationCustomization()) {
+ if (customization.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
+ configurations.add(customization);
+ }
+ }
+ }
+ logger.debug("found {} fabric configuration(s)", configurations.size());
+ return configurations;
+ } catch (Exception ex) {
+ logger.error("Error in finding configurations", ex);
+ return configurations;
+ }
+ }
- if(vfModuleCustomization.getVfModule() != null && vfModuleCustomization.getVfModule().getModuleHeatTemplate() != null && vfModuleCustomization.getHeatEnvironment() != null){
- foundRelated = true;
- foundVfModuleOrVG = true;
- Resource resource = new Resource(WorkflowType.VFMODULE,vfModuleCustomization.getModelCustomizationUUID(),false);
- if(vfModuleCustomization.getVfModule().getIsBase()!=null && vfModuleCustomization.getVfModule().getIsBase()){
- resource.setBaseVfModule(true);
- }else{
- resource.setBaseVfModule(false);
- }
- resourceCounter.add(resource);
- if(vfModule.getModelInfo()!=null && vfModule.getModelInfo().getModelCustomizationUuid()!=null){
- vfModuleCustomizationUUID = vfModule.getModelInfo().getModelCustomizationUuid();
- }
- if(!vnfCustomizationUUID.equals("")&&!vfModuleCustomizationUUID.equals("")){
- List<CvnfcConfigurationCustomization> configs = traverseCatalogDbForConfiguration(validate.getModelInfo().getModelVersionId(),vnfCustomizationUUID,vfModuleCustomizationUUID);
- for(CvnfcConfigurationCustomization config : configs){
- Resource configResource = new Resource(WorkflowType.CONFIGURATION,config.getConfigurationResource().getModelUUID(),false);
- resource.setVnfCustomizationId(vnf.getModelInfo().getModelCustomizationId());
- resource.setVfModuleCustomizationId(vfModule.getModelInfo().getModelCustomizationId());
- resourceCounter.add(configResource);
- }
- }
- }
- if(!foundVfModuleOrVG){
- buildAndThrowException(execution, "Could not determine if vfModule was a vfModule or volume group. Heat template and Heat env are null");
- }
- }
- }
- }
- }
- }
- if (validate.getResources().getNetworks() != null) {
- for (Networks network : validate.getResources().getNetworks()) {
- resourceCounter.add(new Resource(WorkflowType.NETWORK,network.getModelInfo().getModelCustomizationId(),false));
- foundRelated = true;
- }
- if (requestAction.equals(CREATEINSTANCE)) {
- String networkColCustId = queryCatalogDBforNetworkCollection(execution, sIRequest);
- if (networkColCustId != null) {
- resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION,networkColCustId,false));
- foundRelated = true;
- }
- }
- }
- break;
- }
- }
- }
- return foundRelated;
- }
+ protected String queryCatalogDBforNetworkCollection(DelegateExecution execution,
+ ServiceInstancesRequest sIRequest) {
+ org.onap.so.db.catalog.beans.Service service =
+ catalogDbClient.getServiceByID(sIRequest.getRequestDetails().getModelInfo().getModelVersionId());
+ if (service != null) {
+ CollectionResourceCustomization networkCollection = this.findCatalogNetworkCollection(execution, service);
+ if (networkCollection != null) {
+ return networkCollection.getModelCustomizationUUID();
+ }
+ }
+ return null;
+ }
- protected List<CvnfcConfigurationCustomization> traverseCatalogDbForConfiguration(String serviceModelUUID, String vnfCustomizationUUID, String vfModuleCustomizationUUID) {
- List<CvnfcConfigurationCustomization> configurations = new ArrayList<>();
- try{
- List<CvnfcCustomization> cvnfcCustomizations = catalogDbClient.getCvnfcCustomization(serviceModelUUID,vnfCustomizationUUID, vfModuleCustomizationUUID);
- for(CvnfcCustomization cvnfc : cvnfcCustomizations){
- for(CvnfcConfigurationCustomization customization : cvnfc.getCvnfcConfigurationCustomization()){
- if(customization.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)){
- configurations.add(customization);
- }
- }
- }
- logger.debug("found {} fabric configuration(s)" , configurations.size() );
- return configurations;
- } catch (Exception ex){
- logger.error("Error in finding configurations", ex);
- return configurations;
- }
- }
+ protected WorkflowResourceIds populateResourceIdsFromApiHandler(DelegateExecution execution) {
+ WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
+ workflowResourceIds.setServiceInstanceId((String) execution.getVariable("serviceInstanceId"));
+ workflowResourceIds.setNetworkId((String) execution.getVariable("networkId"));
+ workflowResourceIds.setVfModuleId((String) execution.getVariable("vfModuleId"));
+ workflowResourceIds.setVnfId((String) execution.getVariable("vnfId"));
+ workflowResourceIds.setVolumeGroupId((String) execution.getVariable("volumeGroupId"));
+ workflowResourceIds.setInstanceGroupId((String) execution.getVariable("instanceGroupId"));
+ return workflowResourceIds;
+ }
- protected String queryCatalogDBforNetworkCollection(DelegateExecution execution, ServiceInstancesRequest sIRequest) {
- org.onap.so.db.catalog.beans.Service service = catalogDbClient
- .getServiceByID(sIRequest.getRequestDetails().getModelInfo().getModelVersionId());
- if (service != null) {
- CollectionResourceCustomization networkCollection = this.findCatalogNetworkCollection(execution, service);
- if(networkCollection != null) {
- return networkCollection.getModelCustomizationUUID();
- }
- }
- return null;
- }
+ protected Resource extractResourceIdAndTypeFromUri(String uri) {
+ Pattern patt = Pattern.compile(
+ "[vV]\\d+.*?(?:(?:/(?<type>" + supportedTypes + ")(?:/(?<id>[^/]+))?)(?:/(?<action>[^/]+))?)?$");
+ Matcher m = patt.matcher(uri);
+ Boolean generated = false;
- protected WorkflowResourceIds populateResourceIdsFromApiHandler(DelegateExecution execution) {
- WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
- workflowResourceIds.setServiceInstanceId((String) execution.getVariable("serviceInstanceId"));
- workflowResourceIds.setNetworkId((String) execution.getVariable("networkId"));
- workflowResourceIds.setVfModuleId((String) execution.getVariable("vfModuleId"));
- workflowResourceIds.setVnfId((String) execution.getVariable("vnfId"));
- workflowResourceIds.setVolumeGroupId((String) execution.getVariable("volumeGroupId"));
- workflowResourceIds.setInstanceGroupId((String) execution.getVariable("instanceGroupId"));
- return workflowResourceIds;
- }
+ if (m.find()) {
+ logger.debug("found match on {} : {} ", uri, m);
+ String type = m.group("type");
+ String id = m.group("id");
+ String action = m.group("action");
+ if (type == null) {
+ throw new IllegalArgumentException("Uri could not be parsed. No type found. " + uri);
+ }
+ if (action == null) {
+ if (type.equals(SERVICE_INSTANCES) && (id == null || id.equals("assign"))) {
+ id = UUID.randomUUID().toString();
+ generated = true;
+ } else if (type.equals(VF_MODULES) && id.equals("scaleOut")) {
+ id = UUID.randomUUID().toString();
+ generated = true;
+ }
+ } else {
+ if (action.matches(supportedTypes)) {
+ id = UUID.randomUUID().toString();
+ generated = true;
+ type = action;
+ }
+ }
+ return new Resource(WorkflowType.fromString(convertTypeFromPlural(type)), id, generated);
+ } else {
+ throw new IllegalArgumentException("Uri could not be parsed: " + uri);
+ }
+ }
- protected Resource extractResourceIdAndTypeFromUri(String uri) {
- Pattern patt = Pattern.compile(
- "[vV]\\d+.*?(?:(?:/(?<type>" + supportedTypes + ")(?:/(?<id>[^/]+))?)(?:/(?<action>[^/]+))?)?$");
- Matcher m = patt.matcher(uri);
- Boolean generated = false;
+ protected String validateResourceIdInAAI(String generatedResourceId, WorkflowType type, String instanceName,
+ RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) throws Exception {
+ try {
+ if ("SERVICE".equalsIgnoreCase(type.toString())) {
+ String globalCustomerId = reqDetails.getSubscriberInfo().getGlobalSubscriberId();
+ String serviceType = reqDetails.getRequestParameters().getSubscriptionServiceType();
+ if (instanceName != null) {
+ Optional<ServiceInstance> serviceInstanceAAI =
+ bbInputSetupUtils.getAAIServiceInstanceByName(globalCustomerId, serviceType, instanceName);
+ if (serviceInstanceAAI.isPresent()) {
+ return serviceInstanceAAI.get().getServiceInstanceId();
+ }
+ }
+ } else if ("NETWORK".equalsIgnoreCase(type.toString())) {
+ Optional<L3Network> network = bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance(
+ workflowResourceIds.getServiceInstanceId(), instanceName);
+ if (network.isPresent()) {
+ return network.get().getNetworkId();
+ }
+ } else if ("VNF".equalsIgnoreCase(type.toString())) {
+ Optional<GenericVnf> vnf = bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance(
+ workflowResourceIds.getServiceInstanceId(), instanceName);
+ if (vnf.isPresent()) {
+ return vnf.get().getVnfId();
+ }
+ } else if ("VFMODULE".equalsIgnoreCase(type.toString())) {
+ GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId());
+ if (vnf != null && vnf.getVfModules() != null) {
+ for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) {
+ if (vfModule.getVfModuleName().equalsIgnoreCase(instanceName)) {
+ return vfModule.getVfModuleId();
+ }
+ }
+ }
+ } else if ("VOLUMEGROUP".equalsIgnoreCase(type.toString())) {
+ Optional<VolumeGroup> volumeGroup = bbInputSetupUtils
+ .getRelatedVolumeGroupByNameFromVnf(workflowResourceIds.getVnfId(), instanceName);
+ if (volumeGroup.isPresent()) {
+ return volumeGroup.get().getVolumeGroupId();
+ }
+ GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId());
+ if (vnf != null && vnf.getVfModules() != null) {
+ for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) {
+ Optional<VolumeGroup> volumeGroupFromVfModule =
+ bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule(vnf.getVnfId(),
+ vfModule.getVfModuleId(), instanceName);
+ if (volumeGroupFromVfModule.isPresent()) {
+ return volumeGroupFromVfModule.get().getVolumeGroupId();
+ }
+ }
+ }
+ }
+ return generatedResourceId;
+ } catch (Exception ex) {
+ logger.error(WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI, ex);
+ throw new IllegalStateException(
+ WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI);
+ }
+ }
- if (m.find()) {
- logger.debug("found match on {} : {} " , uri , m);
- String type = m.group("type");
- String id = m.group("id");
- String action = m.group("action");
- if (type == null) {
- throw new IllegalArgumentException("Uri could not be parsed. No type found. " + uri);
- }
- if (action == null) {
- if (type.equals(SERVICE_INSTANCES) && (id == null || id.equals("assign"))) {
- id = UUID.randomUUID().toString();
- generated = true;
- }else if (type.equals(VF_MODULES) && id.equals("scaleOut")) {
- id = UUID.randomUUID().toString();
- generated = true;
- }
- } else {
- if (action.matches(supportedTypes)) {
- id = UUID.randomUUID().toString();
- generated = true;
- type = action;
- }
- }
- return new Resource(WorkflowType.fromString(convertTypeFromPlural(type)), id, generated);
- } else {
- throw new IllegalArgumentException("Uri could not be parsed: " + uri);
- }
- }
+ protected String convertTypeFromPlural(String type) {
+ if (!type.matches(supportedTypes)) {
+ return type;
+ } else {
+ if (type.equals(SERVICE_INSTANCES)) {
+ return SERVICE;
+ } else {
+ return type.substring(0, 1).toUpperCase() + type.substring(1, type.length() - 1);
+ }
+ }
+ }
- protected String validateResourceIdInAAI(String generatedResourceId, WorkflowType type, String instanceName,
- RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) throws Exception {
- try {
- if ("SERVICE".equalsIgnoreCase(type.toString())) {
- String globalCustomerId = reqDetails.getSubscriberInfo().getGlobalSubscriberId();
- String serviceType = reqDetails.getRequestParameters().getSubscriptionServiceType();
- if (instanceName != null) {
- Optional<ServiceInstance> serviceInstanceAAI = bbInputSetupUtils
- .getAAIServiceInstanceByName(globalCustomerId, serviceType, instanceName);
- if (serviceInstanceAAI.isPresent()) {
- return serviceInstanceAAI.get().getServiceInstanceId();
- }
- }
- } else if ("NETWORK".equalsIgnoreCase(type.toString())) {
- Optional<L3Network> network = bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance(
- workflowResourceIds.getServiceInstanceId(), instanceName);
- if (network.isPresent()) {
- return network.get().getNetworkId();
- }
- } else if ("VNF".equalsIgnoreCase(type.toString())) {
- Optional<GenericVnf> vnf = bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance(
- workflowResourceIds.getServiceInstanceId(), instanceName);
- if (vnf.isPresent()) {
- return vnf.get().getVnfId();
- }
- } else if ("VFMODULE".equalsIgnoreCase(type.toString())) {
- GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId());
- if (vnf != null && vnf.getVfModules() != null) {
- for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) {
- if (vfModule.getVfModuleName().equalsIgnoreCase(instanceName)) {
- return vfModule.getVfModuleId();
- }
- }
- }
- } else if ("VOLUMEGROUP".equalsIgnoreCase(type.toString())) {
- Optional<VolumeGroup> volumeGroup = bbInputSetupUtils
- .getRelatedVolumeGroupByNameFromVnf(workflowResourceIds.getVnfId(), instanceName);
- if (volumeGroup.isPresent()) {
- return volumeGroup.get().getVolumeGroupId();
- }
- GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId());
- if (vnf != null && vnf.getVfModules() != null) {
- for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) {
- Optional<VolumeGroup> volumeGroupFromVfModule = bbInputSetupUtils
- .getRelatedVolumeGroupByNameFromVfModule(vnf.getVnfId(), vfModule.getVfModuleId(), instanceName);
- if (volumeGroupFromVfModule.isPresent()) {
- return volumeGroupFromVfModule.get().getVolumeGroupId();
- }
- }
- }
- }
- return generatedResourceId;
- } catch (Exception ex) {
- logger.error(WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI, ex);
- throw new IllegalStateException(
- WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI);
- }
- }
+ protected List<ExecuteBuildingBlock> sortExecutionPathByObjectForVlanTagging(List<ExecuteBuildingBlock> orchFlows,
+ String requestAction) {
+ List<ExecuteBuildingBlock> sortedOrchFlows = new ArrayList<>();
+ if (requestAction.equals(CREATEINSTANCE)) {
+ for (ExecuteBuildingBlock ebb : orchFlows) {
+ if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignNetworkBB")) {
+ String key = ebb.getBuildingBlock().getKey();
+ boolean isVirtualLink = Boolean.TRUE.equals(ebb.getBuildingBlock().getIsVirtualLink());
+ String virtualLinkKey = ebb.getBuildingBlock().getVirtualLinkKey();
+ sortedOrchFlows.add(ebb);
+ for (ExecuteBuildingBlock ebb2 : orchFlows) {
+ if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
+ && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
+ sortedOrchFlows.add(ebb2);
+ break;
+ }
+ if (isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
+ && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
+ sortedOrchFlows.add(ebb2);
+ break;
+ }
+ }
+ for (ExecuteBuildingBlock ebb2 : orchFlows) {
+ if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")
+ && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
+ sortedOrchFlows.add(ebb2);
+ break;
+ }
+ if (isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")
+ && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
+ sortedOrchFlows.add(ebb2);
+ break;
+ }
+ }
+ } else if (ebb.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
+ || ebb.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")) {
+ continue;
+ } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) {
+ sortedOrchFlows.add(ebb);
+ }
+ }
+ } else if (requestAction.equals("deleteInstance")) {
+ for (ExecuteBuildingBlock ebb : orchFlows) {
+ if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeactivateNetworkBB")) {
+ sortedOrchFlows.add(ebb);
+ String key = ebb.getBuildingBlock().getKey();
+ for (ExecuteBuildingBlock ebb2 : orchFlows) {
+ if (ebb2.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
+ && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
+ sortedOrchFlows.add(ebb2);
+ break;
+ }
+ }
+ for (ExecuteBuildingBlock ebb2 : orchFlows) {
+ if (ebb2.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")
+ && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
+ sortedOrchFlows.add(ebb2);
+ break;
+ }
+ }
+ } else if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
+ || ebb.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")) {
+ continue;
+ } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) {
+ sortedOrchFlows.add(ebb);
+ }
+ }
+ }
+ return sortedOrchFlows;
+ }
- protected String convertTypeFromPlural(String type) {
- if (!type.matches(supportedTypes)) {
- return type;
- } else {
- if (type.equals(SERVICE_INSTANCES)) {
- return SERVICE;
- } else {
- return type.substring(0, 1).toUpperCase() + type.substring(1, type.length() - 1);
- }
- }
- }
+ protected List<ExecuteBuildingBlock> buildExecuteBuildingBlockList(List<OrchestrationFlow> orchFlows,
+ List<Resource> resourceCounter, String requestId, String apiVersion, String resourceId,
+ WorkflowType resourceType, String requestAction, boolean aLaCarte, String vnfType,
+ WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails) {
+ List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>();
+ for (OrchestrationFlow orchFlow : orchFlows) {
+ if (orchFlow.getFlowName().contains(SERVICE)) {
+ for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.SERVICE == x.getResourceType())
+ .collect(Collectors.toList()).size(); i++) {
+ workflowResourceIds.setServiceInstanceId(resourceId);
+ flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId,
+ resourceCounter.stream().filter(x -> WorkflowType.SERVICE == x.getResourceType())
+ .collect(Collectors.toList()).get(i),
+ apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds,
+ requestDetails, false, null, false));
+ }
+ } else if (orchFlow.getFlowName().contains(VNF)) {
+ for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VNF == x.getResourceType())
+ .collect(Collectors.toList()).size(); i++) {
+ flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId,
+ resourceCounter.stream().filter(x -> WorkflowType.VNF == x.getResourceType())
+ .collect(Collectors.toList()).get(i),
+ apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds,
+ requestDetails, false, null, false));
+ }
+ } else if (orchFlow.getFlowName().contains(NETWORK)
+ && !orchFlow.getFlowName().contains(NETWORKCOLLECTION)) {
+ for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.NETWORK == x.getResourceType())
+ .collect(Collectors.toList()).size(); i++) {
+ flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId,
+ resourceCounter.stream().filter(x -> WorkflowType.NETWORK == x.getResourceType())
+ .collect(Collectors.toList()).get(i),
+ apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds,
+ requestDetails, false, null, false));
+ }
+ for (int i = 0; i < resourceCounter.stream()
+ .filter(x -> WorkflowType.VIRTUAL_LINK == x.getResourceType()).collect(Collectors.toList())
+ .size(); i++) {
+ Resource resource =
+ resourceCounter.stream().filter(x -> WorkflowType.VIRTUAL_LINK == x.getResourceType())
+ .collect(Collectors.toList()).get(i);
+ flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resource, apiVersion, resourceId,
+ requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, true,
+ resource.getVirtualLinkKey(), false));
+ }
+ } else if (orchFlow.getFlowName().contains(VFMODULE)) {
+ List<Resource> vfModuleResourcesSorted = null;
+ if (requestAction.equals("createInstance") || requestAction.equals("assignInstance")
+ || requestAction.equals("activateInstance")) {
+ vfModuleResourcesSorted = sortVfModulesByBaseFirst(resourceCounter.stream()
+ .filter(x -> WorkflowType.VFMODULE == x.getResourceType()).collect(Collectors.toList()));
+ } else {
+ vfModuleResourcesSorted = sortVfModulesByBaseLast(resourceCounter.stream()
+ .filter(x -> WorkflowType.VFMODULE == x.getResourceType()).collect(Collectors.toList()));
+ }
+ for (int i = 0; i < vfModuleResourcesSorted.size(); i++) {
+ flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, vfModuleResourcesSorted.get(i),
+ apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds,
+ requestDetails, false, null, false));
+ }
+ } else if (orchFlow.getFlowName().contains(VOLUMEGROUP)) {
+ for (int i = 0; i < resourceCounter.stream()
+ .filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType()).collect(Collectors.toList())
+ .size(); i++) {
+ flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId,
+ resourceCounter.stream().filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType())
+ .collect(Collectors.toList()).get(i),
+ apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds,
+ requestDetails, false, null, false));
+ }
+ } else if (orchFlow.getFlowName().contains(NETWORKCOLLECTION)) {
+ for (int i = 0; i < resourceCounter.stream()
+ .filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()).collect(Collectors.toList())
+ .size(); i++) {
+ flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId,
+ resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType())
+ .collect(Collectors.toList()).get(i),
+ apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds,
+ requestDetails, false, null, false));
+ }
+ } else if (orchFlow.getFlowName().contains(CONFIGURATION)) {
+ for (int i = 0; i < resourceCounter.stream()
+ .filter(x -> WorkflowType.CONFIGURATION == x.getResourceType()).collect(Collectors.toList())
+ .size(); i++) {
+ flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId,
+ resourceCounter.stream().filter(x -> WorkflowType.CONFIGURATION == x.getResourceType())
+ .collect(Collectors.toList()).get(i),
+ apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds,
+ requestDetails, false, null, true));
+ }
+ } else {
+ flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, null, apiVersion, resourceId,
+ requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
+ }
+ }
+ return flowsToExecute;
+ }
- protected List<ExecuteBuildingBlock> sortExecutionPathByObjectForVlanTagging(List<ExecuteBuildingBlock> orchFlows,
- String requestAction) {
- List<ExecuteBuildingBlock> sortedOrchFlows = new ArrayList<>();
- if (requestAction.equals(CREATEINSTANCE)) {
- for (ExecuteBuildingBlock ebb : orchFlows) {
- if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignNetworkBB")) {
- String key = ebb.getBuildingBlock().getKey();
- boolean isVirtualLink = Boolean.TRUE.equals(ebb.getBuildingBlock().getIsVirtualLink());
- String virtualLinkKey = ebb.getBuildingBlock().getVirtualLinkKey();
- sortedOrchFlows.add(ebb);
- for (ExecuteBuildingBlock ebb2 : orchFlows) {
- if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
- && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
- sortedOrchFlows.add(ebb2);
- break;
- }
- if(isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
- && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
- sortedOrchFlows.add(ebb2);
- break;
- }
- }
- for (ExecuteBuildingBlock ebb2 : orchFlows) {
- if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")
- && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
- sortedOrchFlows.add(ebb2);
- break;
- }
- if(isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")
- && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
- sortedOrchFlows.add(ebb2);
- break;
- }
- }
- } else if (ebb.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
- || ebb.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")) {
- continue;
- } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) {
- sortedOrchFlows.add(ebb);
- }
- }
- } else if (requestAction.equals("deleteInstance")) {
- for (ExecuteBuildingBlock ebb : orchFlows) {
- if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeactivateNetworkBB")) {
- sortedOrchFlows.add(ebb);
- String key = ebb.getBuildingBlock().getKey();
- for (ExecuteBuildingBlock ebb2 : orchFlows) {
- if (ebb2.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
- && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
- sortedOrchFlows.add(ebb2);
- break;
- }
- }
- for (ExecuteBuildingBlock ebb2 : orchFlows) {
- if (ebb2.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")
- && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
- sortedOrchFlows.add(ebb2);
- break;
- }
- }
- } else if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
- || ebb.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")) {
- continue;
- } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) {
- sortedOrchFlows.add(ebb);
- }
- }
- }
- return sortedOrchFlows;
- }
+ protected ExecuteBuildingBlock buildExecuteBuildingBlock(OrchestrationFlow orchFlow, String requestId,
+ Resource resource, String apiVersion, String resourceId, String requestAction, boolean aLaCarte,
+ String vnfType, WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails,
+ boolean isVirtualLink, String virtualLinkKey, boolean isConfiguration) {
+ ExecuteBuildingBlock executeBuildingBlock = new ExecuteBuildingBlock();
+ BuildingBlock buildingBlock = new BuildingBlock();
+ buildingBlock.setBpmnFlowName(orchFlow.getFlowName());
+ buildingBlock.setMsoId(UUID.randomUUID().toString());
+ if (resource == null) {
+ buildingBlock.setKey("");
+ } else {
+ buildingBlock.setKey(resource.getResourceId());
+ }
+ buildingBlock.setIsVirtualLink(isVirtualLink);
+ buildingBlock.setVirtualLinkKey(virtualLinkKey);
+ executeBuildingBlock.setApiVersion(apiVersion);
+ executeBuildingBlock.setaLaCarte(aLaCarte);
+ executeBuildingBlock.setRequestAction(requestAction);
+ executeBuildingBlock.setResourceId(resourceId);
+ executeBuildingBlock.setVnfType(vnfType);
+ executeBuildingBlock.setWorkflowResourceIds(workflowResourceIds);
+ executeBuildingBlock.setRequestId(requestId);
+ executeBuildingBlock.setBuildingBlock(buildingBlock);
+ executeBuildingBlock.setRequestDetails(requestDetails);
+ if (resource != null && (isConfiguration || resource.getResourceType().equals(WorkflowType.CONFIGURATION))) {
+ ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
+ if (resource != null) {
+ configurationResourceKeys.setCvnfcCustomizationUUID(resource.getCvnfModuleCustomizationId());
+ configurationResourceKeys.setVfModuleCustomizationUUID(resource.getVfModuleCustomizationId());
+ configurationResourceKeys.setVnfResourceCustomizationUUID(resource.getVnfCustomizationId());
+ }
+ executeBuildingBlock.setConfigurationResourceKeys(configurationResourceKeys);
+ }
+ return executeBuildingBlock;
+ }
- protected List<ExecuteBuildingBlock> buildExecuteBuildingBlockList(List<OrchestrationFlow> orchFlows,
- List<Resource> resourceCounter, String requestId, String apiVersion, String resourceId, WorkflowType resourceType,
- String requestAction, boolean aLaCarte, String vnfType,
- WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails) {
- List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>();
- for (OrchestrationFlow orchFlow : orchFlows) {
- if (orchFlow.getFlowName().contains(SERVICE)) {
- for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.SERVICE == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
- workflowResourceIds.setServiceInstanceId(resourceId);
- flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.SERVICE == x.getResourceType())
- .collect(Collectors.toList()).get(i), apiVersion, resourceId,
- requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
- }
- } else if (orchFlow.getFlowName().contains(VNF)) {
- for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VNF == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
- flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.VNF == x.getResourceType())
- .collect(Collectors.toList()).get(i), apiVersion, resourceId,
- requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
- }
- } else if (orchFlow.getFlowName().contains(NETWORK)
- && !orchFlow.getFlowName().contains(NETWORKCOLLECTION)) {
- for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.NETWORK == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
- flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.NETWORK == x.getResourceType())
- .collect(Collectors.toList()).get(i), apiVersion, resourceId,
- requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
- }
- for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VIRTUAL_LINK == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
- Resource resource = resourceCounter.stream().filter(x -> WorkflowType.VIRTUAL_LINK == x.getResourceType())
- .collect(Collectors.toList()).get(i);
- flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resource, apiVersion, resourceId,
- requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, true, resource.getVirtualLinkKey(), false));
- }
- } else if (orchFlow.getFlowName().contains(VFMODULE)) {
- List<Resource> vfModuleResourcesSorted = null;
- if(requestAction.equals("createInstance")||requestAction.equals("assignInstance")||requestAction.equals("activateInstance")){
- vfModuleResourcesSorted = sortVfModulesByBaseFirst(resourceCounter.stream().filter(x -> WorkflowType.VFMODULE == x.getResourceType())
- .collect(Collectors.toList()));
- }else{
- vfModuleResourcesSorted = sortVfModulesByBaseLast(resourceCounter.stream().filter(x -> WorkflowType.VFMODULE == x.getResourceType())
- .collect(Collectors.toList()));
- }
- for (int i = 0; i < vfModuleResourcesSorted.size(); i++) {
- flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, vfModuleResourcesSorted.get(i), apiVersion, resourceId,
- requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
- }
- } else if (orchFlow.getFlowName().contains(VOLUMEGROUP)) {
- for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
- flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType())
- .collect(Collectors.toList()).get(i), apiVersion, resourceId,
- requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
- }
- } else if (orchFlow.getFlowName().contains(NETWORKCOLLECTION)) {
- for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
- flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType())
- .collect(Collectors.toList()).get(i), apiVersion, resourceId,
- requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
- }
- } else if (orchFlow.getFlowName().contains(CONFIGURATION)) {
- for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.CONFIGURATION == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
- flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.CONFIGURATION == x.getResourceType())
- .collect(Collectors.toList()).get(i), apiVersion, resourceId,
- requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, true));
- }
- }else {
- flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, null, apiVersion, resourceId,
- requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
- }
- }
- return flowsToExecute;
- }
+ protected List<OrchestrationFlow> queryNorthBoundRequestCatalogDb(DelegateExecution execution, String requestAction,
+ WorkflowType resourceName, boolean aLaCarte, String cloudOwner) {
+ return this.queryNorthBoundRequestCatalogDb(execution, requestAction, resourceName, aLaCarte, cloudOwner, "");
+ }
- protected ExecuteBuildingBlock buildExecuteBuildingBlock(OrchestrationFlow orchFlow, String requestId, Resource resource,
- String apiVersion, String resourceId, String requestAction, boolean aLaCarte, String vnfType,
- WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails, boolean isVirtualLink, String virtualLinkKey, boolean isConfiguration) {
- ExecuteBuildingBlock executeBuildingBlock = new ExecuteBuildingBlock();
- BuildingBlock buildingBlock = new BuildingBlock();
- buildingBlock.setBpmnFlowName(orchFlow.getFlowName());
- buildingBlock.setMsoId(UUID.randomUUID().toString());
- if(resource == null){
- buildingBlock.setKey("");
- }else{
- buildingBlock.setKey(resource.getResourceId());
- }
- buildingBlock.setIsVirtualLink(isVirtualLink);
- buildingBlock.setVirtualLinkKey(virtualLinkKey);
- executeBuildingBlock.setApiVersion(apiVersion);
- executeBuildingBlock.setaLaCarte(aLaCarte);
- executeBuildingBlock.setRequestAction(requestAction);
- executeBuildingBlock.setResourceId(resourceId);
- executeBuildingBlock.setVnfType(vnfType);
- executeBuildingBlock.setWorkflowResourceIds(workflowResourceIds);
- executeBuildingBlock.setRequestId(requestId);
- executeBuildingBlock.setBuildingBlock(buildingBlock);
- executeBuildingBlock.setRequestDetails(requestDetails);
- if(resource != null && (isConfiguration || resource.getResourceType().equals(WorkflowType.CONFIGURATION))){
- ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
- if (resource != null){
- configurationResourceKeys.setCvnfcCustomizationUUID(resource.getCvnfModuleCustomizationId());
- configurationResourceKeys.setVfModuleCustomizationUUID(resource.getVfModuleCustomizationId());
- configurationResourceKeys.setVnfResourceCustomizationUUID(resource.getVnfCustomizationId());
- }
- executeBuildingBlock.setConfigurationResourceKeys(configurationResourceKeys);
- }
- return executeBuildingBlock;
- }
+ protected List<OrchestrationFlow> queryNorthBoundRequestCatalogDb(DelegateExecution execution, String requestAction,
+ WorkflowType resourceName, boolean aLaCarte, String cloudOwner, String serviceType) {
+ List<OrchestrationFlow> listToExecute = new ArrayList<>();
+ NorthBoundRequest northBoundRequest = null;
+ if (serviceType.equalsIgnoreCase(SERVICE_TYPE_TRANSPORT)) {
+ northBoundRequest =
+ catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwnerAndServiceType(
+ requestAction, resourceName.toString(), aLaCarte, cloudOwner, serviceType);
+ } else {
+ northBoundRequest = catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(
+ requestAction, resourceName.toString(), aLaCarte, cloudOwner);
+ }
+ if (northBoundRequest == null) {
+ if (aLaCarte) {
+ buildAndThrowException(execution,
+ "The request: ALaCarte " + resourceName + " " + requestAction + " is not supported by GR_API.");
+ } else {
+ buildAndThrowException(execution,
+ "The request: Macro " + resourceName + " " + requestAction + " is not supported by GR_API.");
+ }
+ } else {
+ if (northBoundRequest.getIsToplevelflow() != null) {
+ execution.setVariable(G_ISTOPLEVELFLOW, northBoundRequest.getIsToplevelflow());
+ }
+ List<OrchestrationFlow> flows = northBoundRequest.getOrchestrationFlowList();
+ if (flows == null)
+ flows = new ArrayList<>();
+ for (OrchestrationFlow flow : flows) {
+ if (!flow.getFlowName().contains("BB")) {
+ List<OrchestrationFlow> macroQueryFlows =
+ catalogDbClient.getOrchestrationFlowByAction(flow.getFlowName());
+ for (OrchestrationFlow macroFlow : macroQueryFlows) {
+ listToExecute.add(macroFlow);
+ }
+ } else {
+ listToExecute.add(flow);
+ }
+ }
+ }
+ return listToExecute;
+ }
- protected List<OrchestrationFlow> queryNorthBoundRequestCatalogDb(DelegateExecution execution, String requestAction,
- WorkflowType resourceName, boolean aLaCarte, String cloudOwner) {
- return this.queryNorthBoundRequestCatalogDb(execution, requestAction, resourceName, aLaCarte, cloudOwner, "");
- }
-
- protected List<OrchestrationFlow> queryNorthBoundRequestCatalogDb(DelegateExecution execution, String requestAction,
- WorkflowType resourceName, boolean aLaCarte, String cloudOwner, String serviceType) {
- List<OrchestrationFlow> listToExecute = new ArrayList<>();
- NorthBoundRequest northBoundRequest = null;
- if (serviceType.equalsIgnoreCase(SERVICE_TYPE_TRANSPORT)) {
- northBoundRequest = catalogDbClient
- .getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwnerAndServiceType(requestAction,
- resourceName.toString(), aLaCarte, cloudOwner, serviceType);
- } else {
- northBoundRequest = catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(
- requestAction, resourceName.toString(), aLaCarte, cloudOwner);
- }
- if(northBoundRequest == null){
- if(aLaCarte){
- buildAndThrowException(execution,"The request: ALaCarte " + resourceName + " " + requestAction + " is not supported by GR_API.");
- }else{
- buildAndThrowException(execution,"The request: Macro " + resourceName + " " + requestAction + " is not supported by GR_API.");
- }
- } else {
- if(northBoundRequest.getIsToplevelflow()!=null){
- execution.setVariable(G_ISTOPLEVELFLOW, northBoundRequest.getIsToplevelflow());
- }
- List<OrchestrationFlow> flows = northBoundRequest.getOrchestrationFlowList();
- if (flows == null)
- flows = new ArrayList<>();
- for (OrchestrationFlow flow : flows) {
- if (!flow.getFlowName().contains("BB")) {
- List<OrchestrationFlow> macroQueryFlows = catalogDbClient
- .getOrchestrationFlowByAction(flow.getFlowName());
- for (OrchestrationFlow macroFlow : macroQueryFlows) {
- listToExecute.add(macroFlow);
- }
- } else {
- listToExecute.add(flow);
- }
- }
- }
- return listToExecute;
- }
+ protected void buildAndThrowException(DelegateExecution execution, String msg, Exception ex) {
+ logger.error(msg, ex);
+ execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, msg);
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
- protected void buildAndThrowException(DelegateExecution execution, String msg, Exception ex) {
- logger.error(msg, ex);
- execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, msg);
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
- }
+ protected void buildAndThrowException(DelegateExecution execution, String msg) {
+ logger.error(msg);
+ execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, msg);
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
+ }
- protected void buildAndThrowException(DelegateExecution execution, String msg) {
- logger.error(msg);
- execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, msg);
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
- }
-
- public void handleRuntimeException (DelegateExecution execution){
- StringBuilder wfeExpMsg = new StringBuilder("Runtime error ");
- String runtimeErrorMessage = null;
- try{
- String javaExpMsg = (String) execution.getVariable("BPMN_javaExpMsg");
- if (javaExpMsg != null && !javaExpMsg.isEmpty()) {
- wfeExpMsg = wfeExpMsg.append(": ").append(javaExpMsg);
- }
- runtimeErrorMessage = wfeExpMsg.toString();
- logger.error(runtimeErrorMessage);
- execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, runtimeErrorMessage);
- } catch (Exception e){
- logger.error("Runtime error", e);
- //if runtime message was mulformed
- runtimeErrorMessage = "Runtime error";
- }
- exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, runtimeErrorMessage);
- }
+ public void handleRuntimeException(DelegateExecution execution) {
+ StringBuilder wfeExpMsg = new StringBuilder("Runtime error ");
+ String runtimeErrorMessage = null;
+ try {
+ String javaExpMsg = (String) execution.getVariable("BPMN_javaExpMsg");
+ if (javaExpMsg != null && !javaExpMsg.isEmpty()) {
+ wfeExpMsg = wfeExpMsg.append(": ").append(javaExpMsg);
+ }
+ runtimeErrorMessage = wfeExpMsg.toString();
+ logger.error(runtimeErrorMessage);
+ execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, runtimeErrorMessage);
+ } catch (Exception e) {
+ logger.error("Runtime error", e);
+ // if runtime message was mulformed
+ runtimeErrorMessage = "Runtime error";
+ }
+ exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, runtimeErrorMessage);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailure.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailure.java
index 1812e50328..4fc4d85b97 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailure.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailure.java
@@ -21,7 +21,6 @@
package org.onap.so.bpmn.infrastructure.workflow.tasks;
import java.util.Optional;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.so.bpmn.core.WorkflowException;
@@ -36,113 +35,115 @@ import org.springframework.stereotype.Component;
@Component
public class WorkflowActionBBFailure {
- private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBFailure.class);
- @Autowired
- private RequestsDbClient requestDbclient;
- @Autowired
- private WorkflowAction workflowAction;
-
- protected void updateRequestErrorStatusMessage(DelegateExecution execution) {
- try {
- String requestId = (String) execution.getVariable("mso-request-id");
- InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
- String errorMsg = "";
- Optional<String> errorMsgOp = retrieveErrorMessage(execution);
- if(errorMsgOp.isPresent()){
- errorMsg = errorMsgOp.get();
- }else{
- errorMsg = "Failed to determine error message";
- }
- request.setStatusMessage(errorMsg);
- requestDbclient.updateInfraActiveRequests(request);
- } catch (Exception e) {
- logger.error("Failed to update Request db with the status message after retry or rollback has been initialized.",e);
- }
- }
-
- public void updateRequestStatusToFailed(DelegateExecution execution) {
- try {
- String requestId = (String) execution.getVariable("mso-request-id");
- InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
- String rollbackErrorMsg = "";
- String errorMsg = "";
- Boolean rollbackCompletedSuccessfully = (Boolean) execution.getVariable("isRollbackComplete");
- Boolean isRollbackFailure = (Boolean) execution.getVariable("isRollback");
- ExecuteBuildingBlock ebb = (ExecuteBuildingBlock) execution.getVariable("buildingBlock");
- if(rollbackCompletedSuccessfully==null)
- rollbackCompletedSuccessfully = false;
-
- if(isRollbackFailure==null)
- isRollbackFailure = false;
-
- if(rollbackCompletedSuccessfully){
- rollbackErrorMsg = "Rollback has been completed successfully.";
- request.setRollbackStatusMessage(rollbackErrorMsg);
- execution.setVariable("RollbackErrorMessage", rollbackErrorMsg);
- }else if(isRollbackFailure){
- Optional<String> rollbackErrorMsgOp = retrieveErrorMessage(execution);
- if(rollbackErrorMsgOp.isPresent()){
- rollbackErrorMsg = rollbackErrorMsgOp.get();
- }else{
- rollbackErrorMsg = "Failed to determine rollback error message.";
- }
- request.setRollbackStatusMessage(rollbackErrorMsg);
- execution.setVariable("RollbackErrorMessage", rollbackErrorMsg);
- }else{
- Optional<String> errorMsgOp = retrieveErrorMessage(execution);
- if(errorMsgOp.isPresent()){
- errorMsg = errorMsgOp.get();
- }else{
- errorMsg = "Failed to determine error message";
- }
- request.setStatusMessage(errorMsg);
- execution.setVariable("ErrorMessage", errorMsg);
- }
- if(ebb!=null && ebb.getBuildingBlock()!=null){
- String flowStatus = "";
- if(rollbackCompletedSuccessfully){
- flowStatus = "All Rollback flows have completed successfully";
- }else{
- flowStatus = ebb.getBuildingBlock().getBpmnFlowName() + " has failed.";
- }
- request.setFlowStatus(flowStatus);
- execution.setVariable("flowStatus", flowStatus);
- }
+ private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBFailure.class);
+ @Autowired
+ private RequestsDbClient requestDbclient;
+ @Autowired
+ private WorkflowAction workflowAction;
+
+ protected void updateRequestErrorStatusMessage(DelegateExecution execution) {
+ try {
+ String requestId = (String) execution.getVariable("mso-request-id");
+ InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
+ String errorMsg = "";
+ Optional<String> errorMsgOp = retrieveErrorMessage(execution);
+ if (errorMsgOp.isPresent()) {
+ errorMsg = errorMsgOp.get();
+ } else {
+ errorMsg = "Failed to determine error message";
+ }
+ request.setStatusMessage(errorMsg);
+ requestDbclient.updateInfraActiveRequests(request);
+ } catch (Exception e) {
+ logger.error(
+ "Failed to update Request db with the status message after retry or rollback has been initialized.",
+ e);
+ }
+ }
+
+ public void updateRequestStatusToFailed(DelegateExecution execution) {
+ try {
+ String requestId = (String) execution.getVariable("mso-request-id");
+ InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
+ String rollbackErrorMsg = "";
+ String errorMsg = "";
+ Boolean rollbackCompletedSuccessfully = (Boolean) execution.getVariable("isRollbackComplete");
+ Boolean isRollbackFailure = (Boolean) execution.getVariable("isRollback");
+ ExecuteBuildingBlock ebb = (ExecuteBuildingBlock) execution.getVariable("buildingBlock");
+ if (rollbackCompletedSuccessfully == null)
+ rollbackCompletedSuccessfully = false;
+
+ if (isRollbackFailure == null)
+ isRollbackFailure = false;
+
+ if (rollbackCompletedSuccessfully) {
+ rollbackErrorMsg = "Rollback has been completed successfully.";
+ request.setRollbackStatusMessage(rollbackErrorMsg);
+ execution.setVariable("RollbackErrorMessage", rollbackErrorMsg);
+ } else if (isRollbackFailure) {
+ Optional<String> rollbackErrorMsgOp = retrieveErrorMessage(execution);
+ if (rollbackErrorMsgOp.isPresent()) {
+ rollbackErrorMsg = rollbackErrorMsgOp.get();
+ } else {
+ rollbackErrorMsg = "Failed to determine rollback error message.";
+ }
+ request.setRollbackStatusMessage(rollbackErrorMsg);
+ execution.setVariable("RollbackErrorMessage", rollbackErrorMsg);
+ } else {
+ Optional<String> errorMsgOp = retrieveErrorMessage(execution);
+ if (errorMsgOp.isPresent()) {
+ errorMsg = errorMsgOp.get();
+ } else {
+ errorMsg = "Failed to determine error message";
+ }
+ request.setStatusMessage(errorMsg);
+ execution.setVariable("ErrorMessage", errorMsg);
+ }
+ if (ebb != null && ebb.getBuildingBlock() != null) {
+ String flowStatus = "";
+ if (rollbackCompletedSuccessfully) {
+ flowStatus = "All Rollback flows have completed successfully";
+ } else {
+ flowStatus = ebb.getBuildingBlock().getBpmnFlowName() + " has failed.";
+ }
+ request.setFlowStatus(flowStatus);
+ execution.setVariable("flowStatus", flowStatus);
+ }
+
+ request.setProgress(Long.valueOf(100));
+ request.setRequestStatus("FAILED");
+ request.setLastModifiedBy("CamundaBPMN");
+ requestDbclient.updateInfraActiveRequests(request);
+ } catch (Exception e) {
+ workflowAction.buildAndThrowException(execution, "Error Updating Request Database", e);
+ }
+ }
+
+ private Optional<String> retrieveErrorMessage(DelegateExecution execution) {
+ String errorMsg = "";
+ try {
+ WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
+ if (exception != null && (exception.getErrorMessage() != null || !exception.getErrorMessage().equals(""))) {
+ errorMsg = exception.getErrorMessage();
+ }
+ if (errorMsg == null || errorMsg.equals("")) {
+ errorMsg = (String) execution.getVariable("WorkflowExceptionErrorMessage");
+ }
+ return Optional.of(errorMsg);
+ } catch (Exception ex) {
+ logger.error("Failed to extract workflow exception from execution.", ex);
+ }
+ return Optional.empty();
+ }
- request.setProgress(Long.valueOf(100));
- request.setRequestStatus("FAILED");
- request.setLastModifiedBy("CamundaBPMN");
- requestDbclient.updateInfraActiveRequests(request);
- } catch (Exception e) {
- workflowAction.buildAndThrowException(execution, "Error Updating Request Database", e);
- }
- }
-
- private Optional<String> retrieveErrorMessage (DelegateExecution execution){
- String errorMsg = "";
- try {
- WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
- if(exception != null && (exception.getErrorMessage()!=null || !exception.getErrorMessage().equals(""))){
- errorMsg = exception.getErrorMessage();
- }
- if(errorMsg == null || errorMsg.equals("")){
- errorMsg = (String) execution.getVariable("WorkflowExceptionErrorMessage");
- }
- return Optional.of(errorMsg);
- } catch (Exception ex) {
- logger.error("Failed to extract workflow exception from execution.",ex);
- }
- return Optional.empty();
- }
-
- public void updateRequestStatusToFailedWithRollback(DelegateExecution execution) {
- execution.setVariable("isRollbackComplete", true);
- updateRequestStatusToFailed(execution);
- }
+ public void updateRequestStatusToFailedWithRollback(DelegateExecution execution) {
+ execution.setVariable("isRollbackComplete", true);
+ updateRequestStatusToFailed(execution);
+ }
- public void abortCallErrorHandling(DelegateExecution execution) {
- String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
- logger.error(msg);
- throw new BpmnError(msg);
- }
+ public void abortCallErrorHandling(DelegateExecution execution) {
+ String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
+ logger.error(msg);
+ throw new BpmnError(msg);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java
index a327f0670a..4514d24c54 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java
@@ -24,9 +24,7 @@ import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
-
import javax.persistence.EntityNotFoundException;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.aai.domain.yang.Vnfc;
import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
@@ -49,382 +47,394 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class WorkflowActionBBTasks {
- private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
- private static final String G_REQUEST_ID = "mso-request-id";
- private static final String G_ALACARTE = "aLaCarte";
- private static final String G_ACTION = "requestAction";
- private static final String RETRY_COUNT = "retryCount";
- private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
- private static final String ASSIGN_FABRIC_CONFIGURATION_BB = "AssignFabricConfigurationBB";
- private static final String ACTIVATE_FABRIC_CONFIGURATION_BB = "ActivateFabricConfigurationBB";
- protected String maxRetries = "mso.rainyDay.maxRetries";
- private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
+ private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
+ private static final String G_REQUEST_ID = "mso-request-id";
+ private static final String G_ALACARTE = "aLaCarte";
+ private static final String G_ACTION = "requestAction";
+ private static final String RETRY_COUNT = "retryCount";
+ private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
+ private static final String ASSIGN_FABRIC_CONFIGURATION_BB = "AssignFabricConfigurationBB";
+ private static final String ACTIVATE_FABRIC_CONFIGURATION_BB = "ActivateFabricConfigurationBB";
+ protected String maxRetries = "mso.rainyDay.maxRetries";
+ private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
+
+ @Autowired
+ private RequestsDbClient requestDbclient;
+ @Autowired
+ private WorkflowAction workflowAction;
+ @Autowired
+ private WorkflowActionBBFailure workflowActionBBFailure;
+ @Autowired
+ private Environment environment;
+ @Autowired
+ private BBInputSetupUtils bbInputSetupUtils;
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+
+ public void selectBB(DelegateExecution execution) {
+ List<ExecuteBuildingBlock> flowsToExecute =
+ (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ execution.setVariable("MacroRollback", false);
+ int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
+ ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
+ boolean homing = (boolean) execution.getVariable("homing");
+ boolean calledHoming = (boolean) execution.getVariable("calledHoming");
+ if (homing && !calledHoming) {
+ if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
+ ebb.setHoming(true);
+ execution.setVariable("calledHoming", true);
+ }
+ } else {
+ ebb.setHoming(false);
+ }
+ execution.setVariable("buildingBlock", ebb);
+ currentSequence++;
+ if (currentSequence >= flowsToExecute.size()) {
+ execution.setVariable("completed", true);
+ } else {
+ execution.setVariable("completed", false);
+ }
+ execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
+ }
+
+ public void updateFlowStatistics(DelegateExecution execution) {
+ try {
+ int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
+ if (currentSequence > 1) {
+ InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
+ requestDbclient.updateInfraActiveRequests(request);
+ }
+ } catch (Exception ex) {
+ logger.warn(
+ "Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
+ }
+ }
+
+ protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
+ List<ExecuteBuildingBlock> flowsToExecute =
+ (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ String requestId = (String) execution.getVariable(G_REQUEST_ID);
+ InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
+ ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
+ ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
+ int completedBBs = currentSequence - 1;
+ int totalBBs = flowsToExecute.size();
+ int remainingBBs = totalBBs - completedBBs;
+ String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
+ nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
+ Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
+ request.setFlowStatus(statusMessage);
+ request.setProgress(percentProgress);
+ request.setLastModifiedBy("CamundaBPMN");
+ return request;
+ }
+
+ protected Long getPercentProgress(int completedBBs, int totalBBs) {
+ double ratio = (completedBBs / (totalBBs * 1.0));
+ int percentProgress = (int) (ratio * 95);
+ return new Long(percentProgress + 5);
+ }
+
+ protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
+ return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
+ + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
+ + ").";
+ }
+
+ public void sendSyncAck(DelegateExecution execution) {
+ final String requestId = (String) execution.getVariable(G_REQUEST_ID);
+ final String resourceId = (String) execution.getVariable("resourceId");
+ ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
+ RequestReferences requestRef = new RequestReferences();
+ requestRef.setInstanceId(resourceId);
+ requestRef.setRequestId(requestId);
+ serviceInstancesResponse.setRequestReferences(requestRef);
+ ObjectMapper mapper = new ObjectMapper();
+ String jsonRequest = "";
+ try {
+ jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
+ } catch (JsonProcessingException e) {
+ workflowAction.buildAndThrowException(execution,
+ "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
+ }
+ WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
+ callbackResponse.setStatusCode(200);
+ callbackResponse.setMessage("Success");
+ callbackResponse.setResponse(jsonRequest);
+ String processKey = execution.getProcessEngineServices().getRepositoryService()
+ .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
+ WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
+ callbackResponse);
+ logger.info("Successfully sent sync ack.");
+ updateInstanceId(execution);
+ }
+
+ public void sendErrorSyncAck(DelegateExecution execution) {
+ final String requestId = (String) execution.getVariable(G_REQUEST_ID);
+ try {
+ ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
+ String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
+ if (errorMsg == null) {
+ errorMsg = "WorkflowAction failed unexpectedly.";
+ }
+ String processKey = exceptionBuilder.getProcessKey(execution);
+ String buildworkflowException =
+ "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
+ + errorMsg
+ + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
+ WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
+ callbackResponse.setStatusCode(500);
+ callbackResponse.setMessage("Fail");
+ callbackResponse.setResponse(buildworkflowException);
+ WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
+ callbackResponse);
+ execution.setVariable("sentSyncResponse", true);
+ } catch (Exception ex) {
+ logger.error(" Sending Sync Error Activity Failed. {}", ex.getMessage(), ex);
+ }
+ }
+
+ public void updateRequestStatusToComplete(DelegateExecution execution) {
+ try {
+ final String requestId = (String) execution.getVariable(G_REQUEST_ID);
+ InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
+ final String action = (String) execution.getVariable(G_ACTION);
+ final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
+ final String resourceName = (String) execution.getVariable("resourceName");
+ String macroAction = "";
+ if (aLaCarte) {
+ macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
+ } else {
+ macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
+ }
+ execution.setVariable("finalStatusMessage", macroAction);
+ Timestamp endTime = new Timestamp(System.currentTimeMillis());
+ request.setEndTime(endTime);
+ request.setFlowStatus("Successfully completed all Building Blocks");
+ request.setStatusMessage(macroAction);
+ request.setProgress(Long.valueOf(100));
+ request.setRequestStatus("COMPLETE");
+ request.setLastModifiedBy("CamundaBPMN");
+ requestDbclient.updateInfraActiveRequests(request);
+ } catch (Exception ex) {
+ workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
+ }
+ }
+
+ public void checkRetryStatus(DelegateExecution execution) {
+ String handlingCode = (String) execution.getVariable("handlingCode");
+ String requestId = (String) execution.getVariable(G_REQUEST_ID);
+ String retryDuration = (String) execution.getVariable("RetryDuration");
+ int retryCount = (int) execution.getVariable(RETRY_COUNT);
+ int envMaxRetries;
+ try {
+ envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
+ } catch (Exception ex) {
+ logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
+ envMaxRetries = 5;
+ }
+ int nextCount = retryCount + 1;
+ if (handlingCode.equals("Retry")) {
+ workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
+ try {
+ InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
+ request.setRetryStatusMessage(
+ "Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
+ requestDbclient.updateInfraActiveRequests(request);
+ } catch (Exception ex) {
+ logger.warn("Failed to update Request Db Infra Active Requests with Retry Status", ex);
+ }
+ if (retryCount < envMaxRetries) {
+ int currSequence = (int) execution.getVariable("gCurrentSequence");
+ execution.setVariable("gCurrentSequence", currSequence - 1);
+ execution.setVariable(RETRY_COUNT, nextCount);
+ } else {
+ workflowAction.buildAndThrowException(execution,
+ "Exceeded maximum retries. Ending flow with status Abort");
+ }
+ } else {
+ execution.setVariable(RETRY_COUNT, 0);
+ }
+ }
+
+ /**
+ * Rollback will only handle Create/Activate/Assign Macro flows. Execute layer will rollback the flow its currently
+ * working on.
+ */
+ public void rollbackExecutionPath(DelegateExecution execution) {
+ if (!(boolean) execution.getVariable("isRollback")) {
+ List<ExecuteBuildingBlock> flowsToExecute =
+ (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
+ int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
+ int listSize = flowsToExecute.size();
+ for (int i = listSize - 1; i >= 0; i--) {
+ if (i > currentSequence - 1) {
+ flowsToExecute.remove(i);
+ } else {
+ String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
+ if (flowName.contains("Assign")) {
+ flowName = "Unassign" + flowName.substring(6, flowName.length());
+ } else if (flowName.contains("Create")) {
+ flowName = "Delete" + flowName.substring(6, flowName.length());
+ } else if (flowName.contains("Activate")) {
+ flowName = "Deactivate" + flowName.substring(8, flowName.length());
+ } else {
+ continue;
+ }
+ flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
+ rollbackFlows.add(flowsToExecute.get(i));
+ }
+ }
- @Autowired
- private RequestsDbClient requestDbclient;
- @Autowired
- private WorkflowAction workflowAction;
- @Autowired
- private WorkflowActionBBFailure workflowActionBBFailure;
- @Autowired
- private Environment environment;
- @Autowired
- private BBInputSetupUtils bbInputSetupUtils;
- @Autowired
- private CatalogDbClient catalogDbClient;
-
- public void selectBB(DelegateExecution execution) {
- List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
- .getVariable("flowsToExecute");
- execution.setVariable("MacroRollback", false);
- int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
- ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
- boolean homing = (boolean) execution.getVariable("homing");
- boolean calledHoming = (boolean) execution.getVariable("calledHoming");
- if (homing && !calledHoming) {
- if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
- ebb.setHoming(true);
- execution.setVariable("calledHoming", true);
- }
- } else {
- ebb.setHoming(false);
- }
- execution.setVariable("buildingBlock", ebb);
- currentSequence++;
- if (currentSequence >= flowsToExecute.size()) {
- execution.setVariable("completed", true);
- } else {
- execution.setVariable("completed", false);
- }
- execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
- }
-
- public void updateFlowStatistics(DelegateExecution execution) {
- try{
- int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
- if(currentSequence > 1) {
- InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
- requestDbclient.updateInfraActiveRequests(request);
- }
- }catch (Exception ex){
- logger.warn("Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
- }
- }
+ String handlingCode = (String) execution.getVariable("handlingCode");
+ List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>();
+ rollbackFlowsFiltered.addAll(rollbackFlows);
+ if (handlingCode.equals("RollbackToAssigned") || handlingCode.equals("RollbackToCreated")) {
+ for (int i = 0; i < rollbackFlows.size(); i++) {
+ if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")) {
+ rollbackFlowsFiltered.remove(rollbackFlows.get(i));
+ } else if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete")
+ && handlingCode.equals("RollbackToCreated")) {
+ rollbackFlowsFiltered.remove(rollbackFlows.get(i));
+ }
+ }
+ }
- protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
- List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
- .getVariable("flowsToExecute");
- String requestId = (String) execution.getVariable(G_REQUEST_ID);
- InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
- ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
- ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
- int completedBBs = currentSequence - 1;
- int totalBBs = flowsToExecute.size();
- int remainingBBs = totalBBs - completedBBs;
- String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
- nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
- Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
- request.setFlowStatus(statusMessage);
- request.setProgress(percentProgress);
- request.setLastModifiedBy("CamundaBPMN");
- return request;
- }
-
- protected Long getPercentProgress(int completedBBs, int totalBBs) {
- double ratio = (completedBBs / (totalBBs * 1.0));
- int percentProgress = (int) (ratio * 95);
- return new Long(percentProgress + 5);
- }
-
- protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
- return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
- + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
- + ").";
- }
+ workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
- public void sendSyncAck(DelegateExecution execution) {
- final String requestId = (String) execution.getVariable(G_REQUEST_ID);
- final String resourceId = (String) execution.getVariable("resourceId");
- ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
- RequestReferences requestRef = new RequestReferences();
- requestRef.setInstanceId(resourceId);
- requestRef.setRequestId(requestId);
- serviceInstancesResponse.setRequestReferences(requestRef);
- ObjectMapper mapper = new ObjectMapper();
- String jsonRequest = "";
- try {
- jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
- } catch (JsonProcessingException e) {
- workflowAction.buildAndThrowException(execution,
- "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
- }
- WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
- callbackResponse.setStatusCode(200);
- callbackResponse.setMessage("Success");
- callbackResponse.setResponse(jsonRequest);
- String processKey = execution.getProcessEngineServices().getRepositoryService()
- .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
- WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
- callbackResponse);
- logger.info("Successfully sent sync ack.");
- updateInstanceId(execution);
- }
+ if (rollbackFlows.isEmpty())
+ execution.setVariable("isRollbackNeeded", false);
+ else
+ execution.setVariable("isRollbackNeeded", true);
+ execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
+ execution.setVariable("handlingCode", "PreformingRollback");
+ execution.setVariable("isRollback", true);
+ execution.setVariable("gCurrentSequence", 0);
+ execution.setVariable(RETRY_COUNT, 0);
+ } else {
+ workflowAction.buildAndThrowException(execution,
+ "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
+ }
+ }
- public void sendErrorSyncAck(DelegateExecution execution) {
- final String requestId = (String) execution.getVariable(G_REQUEST_ID);
- try {
- ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
- String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
- if (errorMsg == null) {
- errorMsg = "WorkflowAction failed unexpectedly.";
- }
- String processKey = exceptionBuilder.getProcessKey(execution);
- String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
- + errorMsg
- + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
- WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
- callbackResponse.setStatusCode(500);
- callbackResponse.setMessage("Fail");
- callbackResponse.setResponse(buildworkflowException);
- WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
- callbackResponse);
- execution.setVariable("sentSyncResponse", true);
- } catch (Exception ex) {
- logger.error(" Sending Sync Error Activity Failed. {}" , ex.getMessage(), ex);
- }
- }
+ protected void updateInstanceId(DelegateExecution execution) {
+ try {
+ String requestId = (String) execution.getVariable(G_REQUEST_ID);
+ String resourceId = (String) execution.getVariable("resourceId");
+ WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
+ InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
+ if (resourceType == WorkflowType.SERVICE) {
+ request.setServiceInstanceId(resourceId);
+ } else if (resourceType == WorkflowType.VNF) {
+ request.setVnfId(resourceId);
+ } else if (resourceType == WorkflowType.VFMODULE) {
+ request.setVfModuleId(resourceId);
+ } else if (resourceType == WorkflowType.VOLUMEGROUP) {
+ request.setVolumeGroupId(resourceId);
+ } else if (resourceType == WorkflowType.NETWORK) {
+ request.setNetworkId(resourceId);
+ } else if (resourceType == WorkflowType.CONFIGURATION) {
+ request.setConfigurationId(resourceId);
+ } else if (resourceType == WorkflowType.INSTANCE_GROUP) {
+ request.setInstanceGroupId(resourceId);
+ }
+ requestDbclient.updateInfraActiveRequests(request);
+ } catch (Exception ex) {
+ workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
+ }
+ }
- public void updateRequestStatusToComplete(DelegateExecution execution) {
- try{
- final String requestId = (String) execution.getVariable(G_REQUEST_ID);
- InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
- final String action = (String) execution.getVariable(G_ACTION);
- final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
- final String resourceName = (String) execution.getVariable("resourceName");
- String macroAction = "";
- if (aLaCarte) {
- macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
- } else {
- macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
- }
- execution.setVariable("finalStatusMessage", macroAction);
- Timestamp endTime = new Timestamp(System.currentTimeMillis());
- request.setEndTime(endTime);
- request.setFlowStatus("Successfully completed all Building Blocks");
- request.setStatusMessage(macroAction);
- request.setProgress(Long.valueOf(100));
- request.setRequestStatus("COMPLETE");
- request.setLastModifiedBy("CamundaBPMN");
- requestDbclient.updateInfraActiveRequests(request);
- }catch (Exception ex) {
- workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
- }
- }
+ public void postProcessingExecuteBB(DelegateExecution execution) {
+ List<ExecuteBuildingBlock> flowsToExecute =
+ (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ String handlingCode = (String) execution.getVariable("handlingCode");
+ final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
+ int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
+ ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
+ String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
+ if (bbFlowName.equalsIgnoreCase("ActivateVfModuleBB") && aLaCarte && handlingCode.equalsIgnoreCase("Success")) {
+ postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
+ }
+ }
- public void checkRetryStatus(DelegateExecution execution) {
- String handlingCode = (String) execution.getVariable("handlingCode");
- String requestId = (String) execution.getVariable(G_REQUEST_ID);
- String retryDuration = (String) execution.getVariable("RetryDuration");
- int retryCount = (int) execution.getVariable(RETRY_COUNT);
- int envMaxRetries;
- try{
- envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
- } catch (Exception ex) {
- logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
- envMaxRetries = 5;
- }
- int nextCount = retryCount +1;
- if (handlingCode.equals("Retry")){
- workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
- try{
- InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
- request.setRetryStatusMessage("Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
- requestDbclient.updateInfraActiveRequests(request);
- } catch(Exception ex){
- logger.warn("Failed to update Request Db Infra Active Requests with Retry Status",ex);
- }
- if(retryCount<envMaxRetries){
- int currSequence = (int) execution.getVariable("gCurrentSequence");
- execution.setVariable("gCurrentSequence", currSequence-1);
- execution.setVariable(RETRY_COUNT, nextCount);
- }else{
- workflowAction.buildAndThrowException(execution, "Exceeded maximum retries. Ending flow with status Abort");
- }
- }else{
- execution.setVariable(RETRY_COUNT, 0);
- }
- }
+ protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, ExecuteBuildingBlock ebb,
+ List<ExecuteBuildingBlock> flowsToExecute) {
+ try {
+ String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
+ String vnfId = ebb.getWorkflowResourceIds().getVnfId();
+ String vfModuleId = ebb.getResourceId();
+ ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
+ String serviceModelUUID =
+ bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
+ String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
+ String vfModuleCustomizationUUID =
+ bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
+ List<Vnfc> vnfcs =
+ workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
+ logger.debug("Vnfc Size: {}", vnfcs.size());
+ for (Vnfc vnfc : vnfcs) {
+ String modelCustomizationId = vnfc.getModelCustomizationId();
+ logger.debug("Processing Vnfc: {}", modelCustomizationId);
+ CvnfcConfigurationCustomization fabricConfig = catalogDbClient.getCvnfcCustomization(serviceModelUUID,
+ vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
+ if (fabricConfig != null && fabricConfig.getConfigurationResource() != null
+ && fabricConfig.getConfigurationResource().getToscaNodeType() != null
+ && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
+ String configurationId = UUID.randomUUID().toString();
+ ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
+ configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
+ configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
+ configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
+ configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
+ ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb,
+ configurationId, configurationResourceKeys);
+ ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb,
+ configurationId, configurationResourceKeys);
+ flowsToExecute.add(assignConfigBB);
+ flowsToExecute.add(activateConfigBB);
+ flowsToExecute.stream()
+ .forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
+ executeBB.getBuildingBlock().getBpmnFlowName()));
+ execution.setVariable("flowsToExecute", flowsToExecute);
+ execution.setVariable("completed", false);
+ } else {
+ logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId);
+ }
+ }
+ } catch (EntityNotFoundException e) {
+ logger.debug(e.getMessage() + " Will not be running Fabric Config Building Blocks");
+ } catch (Exception e) {
+ String errorMessage = "Error occurred in post processing of Vf Module create";
+ execution.setVariable("handlingCode", "RollbackToCreated");
+ execution.setVariable("WorkflowActionErrorMessage", errorMessage);
+ logger.error(errorMessage, e);
+ }
+ }
- /**
- * Rollback will only handle Create/Activate/Assign Macro flows. Execute
- * layer will rollback the flow its currently working on.
- */
- public void rollbackExecutionPath(DelegateExecution execution) {
- if(!(boolean)execution.getVariable("isRollback")){
- List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
- .getVariable("flowsToExecute");
- List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
- int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
- int listSize = flowsToExecute.size();
- for (int i = listSize - 1; i >= 0; i--) {
- if (i > currentSequence - 1) {
- flowsToExecute.remove(i);
- } else {
- String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
- if (flowName.contains("Assign")) {
- flowName = "Unassign" + flowName.substring(6, flowName.length());
- } else if (flowName.contains("Create")) {
- flowName = "Delete" + flowName.substring(6, flowName.length());
- } else if (flowName.contains("Activate")) {
- flowName = "Deactivate" + flowName.substring(8, flowName.length());
- }else{
- continue;
- }
- flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
- rollbackFlows.add(flowsToExecute.get(i));
- }
- }
-
- String handlingCode = (String) execution.getVariable("handlingCode");
- List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>();
- rollbackFlowsFiltered.addAll(rollbackFlows);
- if(handlingCode.equals("RollbackToAssigned") || handlingCode.equals("RollbackToCreated")){
- for(int i = 0; i<rollbackFlows.size(); i++){
- if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")){
- rollbackFlowsFiltered.remove(rollbackFlows.get(i));
- } else if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete") && handlingCode.equals("RollbackToCreated")) {
- rollbackFlowsFiltered.remove(rollbackFlows.get(i));
- }
- }
- }
-
- workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
-
- if (rollbackFlows.isEmpty())
- execution.setVariable("isRollbackNeeded", false);
- else
- execution.setVariable("isRollbackNeeded", true);
- execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
- execution.setVariable("handlingCode", "PreformingRollback");
- execution.setVariable("isRollback", true);
- execution.setVariable("gCurrentSequence", 0);
- execution.setVariable(RETRY_COUNT, 0);
- }else{
- workflowAction.buildAndThrowException(execution, "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
- }
- }
-
- protected void updateInstanceId(DelegateExecution execution){
- try{
- String requestId = (String) execution.getVariable(G_REQUEST_ID);
- String resourceId = (String) execution.getVariable("resourceId");
- WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
- InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
- if(resourceType == WorkflowType.SERVICE){
- request.setServiceInstanceId(resourceId);
- }else if(resourceType == WorkflowType.VNF){
- request.setVnfId(resourceId);
- }else if(resourceType == WorkflowType.VFMODULE){
- request.setVfModuleId(resourceId);
- }else if(resourceType == WorkflowType.VOLUMEGROUP){
- request.setVolumeGroupId(resourceId);
- }else if(resourceType == WorkflowType.NETWORK){
- request.setNetworkId(resourceId);
- }else if(resourceType == WorkflowType.CONFIGURATION){
- request.setConfigurationId(resourceId);
- }else if(resourceType == WorkflowType.INSTANCE_GROUP){
- request.setInstanceGroupId(resourceId);
- }
- requestDbclient.updateInfraActiveRequests(request);
- }catch(Exception ex){
- workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
- }
- }
-
- public void postProcessingExecuteBB(DelegateExecution execution) {
- List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
- .getVariable("flowsToExecute");
- String handlingCode = (String) execution.getVariable("handlingCode");
- final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
- int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
- ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
- String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
- if(bbFlowName.equalsIgnoreCase("ActivateVfModuleBB") && aLaCarte && handlingCode.equalsIgnoreCase("Success")) {
- postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
- }
- }
-
- protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution,
- ExecuteBuildingBlock ebb, List<ExecuteBuildingBlock> flowsToExecute) {
- try {
- String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
- String vnfId = ebb.getWorkflowResourceIds().getVnfId();
- String vfModuleId = ebb.getResourceId();
- ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
- String serviceModelUUID = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
- String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
- String vfModuleCustomizationUUID = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
- List<Vnfc> vnfcs = workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
- logger.debug("Vnfc Size: {}", vnfcs.size());
- for(Vnfc vnfc : vnfcs) {
- String modelCustomizationId = vnfc.getModelCustomizationId();
- logger.debug("Processing Vnfc: {}", modelCustomizationId);
- CvnfcConfigurationCustomization fabricConfig =
- catalogDbClient.getCvnfcCustomization(serviceModelUUID,vnfCustomizationUUID,
- vfModuleCustomizationUUID, modelCustomizationId);
- if(fabricConfig != null && fabricConfig.getConfigurationResource() != null
- && fabricConfig.getConfigurationResource().getToscaNodeType() != null
- && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
- String configurationId = UUID.randomUUID().toString();
- ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
- configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
- configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
- configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
- configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
- ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys);
- ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys);
- flowsToExecute.add(assignConfigBB);
- flowsToExecute.add(activateConfigBB);
- flowsToExecute.stream().forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}", executeBB.getBuildingBlock().getBpmnFlowName()));
- execution.setVariable("flowsToExecute", flowsToExecute);
- execution.setVariable("completed", false);
- } else {
- logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId);
- }
- }
- } catch (EntityNotFoundException e) {
- logger.debug(e.getMessage() + " Will not be running Fabric Config Building Blocks");
- } catch (Exception e) {
- String errorMessage = "Error occurred in post processing of Vf Module create";
- execution.setVariable("handlingCode", "RollbackToCreated");
- execution.setVariable("WorkflowActionErrorMessage", errorMessage);
- logger.error(errorMessage, e);
- }
- }
-
- protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb, String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
- ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
- BuildingBlock buildingBlock = new BuildingBlock();
- buildingBlock.setBpmnFlowName(bbName);
- buildingBlock.setMsoId(UUID.randomUUID().toString());
- configBB.setaLaCarte(ebb.isaLaCarte());
- configBB.setApiVersion(ebb.getApiVersion());
- configBB.setRequestAction(ebb.getRequestAction());
- configBB.setVnfType(ebb.getVnfType());
- configBB.setRequestId(ebb.getRequestId());
- configBB.setRequestDetails(ebb.getRequestDetails());
- configBB.setBuildingBlock(buildingBlock);
- WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
- workflowResourceIds.setConfigurationId(configurationId);
- configBB.setWorkflowResourceIds(workflowResourceIds);
- configBB.setConfigurationResourceKeys(configurationResourceKeys);
- return configBB;
- }
+ protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb,
+ String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
+ ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
+ BuildingBlock buildingBlock = new BuildingBlock();
+ buildingBlock.setBpmnFlowName(bbName);
+ buildingBlock.setMsoId(UUID.randomUUID().toString());
+ configBB.setaLaCarte(ebb.isaLaCarte());
+ configBB.setApiVersion(ebb.getApiVersion());
+ configBB.setRequestAction(ebb.getRequestAction());
+ configBB.setVnfType(ebb.getVnfType());
+ configBB.setRequestId(ebb.getRequestId());
+ configBB.setRequestDetails(ebb.getRequestDetails());
+ configBB.setBuildingBlock(buildingBlock);
+ WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
+ workflowResourceIds.setConfigurationId(configurationId);
+ configBB.setWorkflowResourceIds(workflowResourceIds);
+ configBB.setConfigurationResourceKeys(configurationResourceKeys);
+ return configBB;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionExtractResourcesAAI.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionExtractResourcesAAI.java
index 2b0f8bf946..99ae2e7495 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionExtractResourcesAAI.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionExtractResourcesAAI.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.workflow.tasks;
import java.util.List;
import java.util.Optional;
-
import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.entities.AAIResultWrapper;
@@ -33,26 +32,26 @@ import org.springframework.stereotype.Component;
@Component
public class WorkflowActionExtractResourcesAAI {
- private static final Logger logger = LoggerFactory.getLogger(WorkflowActionExtractResourcesAAI.class);
+ private static final Logger logger = LoggerFactory.getLogger(WorkflowActionExtractResourcesAAI.class);
- public Optional<Configuration> extractRelationshipsConfiguration(Relationships relationships) {
- List<AAIResultWrapper> configurations = relationships.getByType(AAIObjectType.CONFIGURATION);
- for(AAIResultWrapper configWrapper : configurations) {
- Optional<Configuration> config = configWrapper.asBean(Configuration.class);
- if(config.isPresent()){
- return config;
- }
- }
- return Optional.empty();
- }
+ public Optional<Configuration> extractRelationshipsConfiguration(Relationships relationships) {
+ List<AAIResultWrapper> configurations = relationships.getByType(AAIObjectType.CONFIGURATION);
+ for (AAIResultWrapper configWrapper : configurations) {
+ Optional<Configuration> config = configWrapper.asBean(Configuration.class);
+ if (config.isPresent()) {
+ return config;
+ }
+ }
+ return Optional.empty();
+ }
- public Optional<Relationships> extractRelationshipsVnfc(Relationships relationships) {
- List<AAIResultWrapper> vnfcs = relationships.getByType(AAIObjectType.VNFC);
- for(AAIResultWrapper vnfcWrapper : vnfcs){
- if(vnfcWrapper.getRelationships().isPresent()){
- return vnfcWrapper.getRelationships();
- }
- }
- return Optional.empty();
- }
+ public Optional<Relationships> extractRelationshipsVnfc(Relationships relationships) {
+ List<AAIResultWrapper> vnfcs = relationships.getByType(AAIObjectType.VNFC);
+ for (AAIResultWrapper vnfcWrapper : vnfcs) {
+ if (vnfcWrapper.getRelationships().isPresent()) {
+ return vnfcWrapper.getRelationships();
+ }
+ }
+ return Optional.empty();
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java
index 304b4000bd..af8f93b92b 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java
@@ -22,33 +22,27 @@ package org.onap.so.bpmn.infrastructure.workflow.tasks;
public enum WorkflowType {
- SERVICE("Service"),
- VNF("Vnf"),
- VFMODULE("VfModule"),
- VOLUMEGROUP("VolumeGroup"),
- NETWORK("Network"),
- VIRTUAL_LINK("VirtualLink"),
- NETWORKCOLLECTION("NetworkCollection"),
- CONFIGURATION("Configuration"),
- INSTANCE_GROUP("InstanceGroup");
-
- private final String type;
-
- private WorkflowType (String type){
- this.type = type;
- }
-
- @Override
- public String toString() {
- return this.type;
- }
-
- public static WorkflowType fromString (String text){
- for (WorkflowType x : WorkflowType.values()) {
- if (x.type.equalsIgnoreCase(text)) {
- return x;
- }
- }
- return null;
- }
+ SERVICE("Service"), VNF("Vnf"), VFMODULE("VfModule"), VOLUMEGROUP("VolumeGroup"), NETWORK("Network"), VIRTUAL_LINK(
+ "VirtualLink"), NETWORKCOLLECTION(
+ "NetworkCollection"), CONFIGURATION("Configuration"), INSTANCE_GROUP("InstanceGroup");
+
+ private final String type;
+
+ private WorkflowType(String type) {
+ this.type = type;
+ }
+
+ @Override
+ public String toString() {
+ return this.type;
+ }
+
+ public static WorkflowType fromString(String text) {
+ for (WorkflowType x : WorkflowType.values()) {
+ if (x.type.equalsIgnoreCase(text)) {
+ return x;
+ }
+ }
+ return null;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasks.java
index c0f7b21a9e..adfeb5ac6a 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasks.java
@@ -23,7 +23,6 @@
package org.onap.so.bpmn.sdno.tasks;
import java.util.Map;
-
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
@@ -39,38 +38,37 @@ import org.springframework.stereotype.Component;
@Component
public class SDNOHealthCheckTasks {
- private static final Logger logger = LoggerFactory.getLogger(SDNOHealthCheckTasks.class);
- @Autowired
- private ExceptionBuilder exceptionUtil;
- @Autowired
- private ExtractPojosForBB extractPojosForBB;
- @Autowired
- private SDNOHealthCheckResources sdnoHealthCheckResources;
-
- public void sdnoHealthCheck(BuildingBlockExecution execution) {
- boolean response = false;
- try {
- GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
- RequestContext requestContext = gBBInput.getRequestContext();
-
- GenericVnf vnf = null;
- Map<ResourceKey, String> lookupMap = execution.getLookupMap();
- for (Map.Entry<ResourceKey, String> entry : lookupMap.entrySet()) {
- if (entry.getKey().equals(ResourceKey.GENERIC_VNF_ID)) {
- vnf = extractPojosForBB.extractByKey(execution, entry.getKey());
- }
- }
-
- response = sdnoHealthCheckResources.healthCheck(vnf, requestContext);
- }
- catch (Exception ex) {
- logger.error("Exception occurred", ex);
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex.getMessage());
- }
-
- if (!response) {
- logger.error("SDNO Health Check failed");
- exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "SDNO Health Check failed");
- }
- }
+ private static final Logger logger = LoggerFactory.getLogger(SDNOHealthCheckTasks.class);
+ @Autowired
+ private ExceptionBuilder exceptionUtil;
+ @Autowired
+ private ExtractPojosForBB extractPojosForBB;
+ @Autowired
+ private SDNOHealthCheckResources sdnoHealthCheckResources;
+
+ public void sdnoHealthCheck(BuildingBlockExecution execution) {
+ boolean response = false;
+ try {
+ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
+ RequestContext requestContext = gBBInput.getRequestContext();
+
+ GenericVnf vnf = null;
+ Map<ResourceKey, String> lookupMap = execution.getLookupMap();
+ for (Map.Entry<ResourceKey, String> entry : lookupMap.entrySet()) {
+ if (entry.getKey().equals(ResourceKey.GENERIC_VNF_ID)) {
+ vnf = extractPojosForBB.extractByKey(execution, entry.getKey());
+ }
+ }
+
+ response = sdnoHealthCheckResources.healthCheck(vnf, requestContext);
+ } catch (Exception ex) {
+ logger.error("Exception occurred", ex);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex.getMessage());
+ }
+
+ if (!response) {
+ logger.error("SDNO Health Check failed");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "SDNO Health Check failed");
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/aai/mapper/AAIObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/aai/mapper/AAIObjectMapper.java
index 518da1fa5f..06f6550d51 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/aai/mapper/AAIObjectMapper.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/aai/mapper/AAIObjectMapper.java
@@ -25,7 +25,6 @@ import org.modelmapper.PropertyMap;
import org.onap.aai.domain.yang.RouteTargets;
import org.onap.so.bpmn.servicedecomposition.bbobjects.*;
import org.springframework.stereotype.Component;
-
import java.util.List;
import org.modelmapper.Converter;
import org.modelmapper.spi.MappingContext;
@@ -36,277 +35,287 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet;
@Component
public class AAIObjectMapper {
- private static final ModelMapper modelMapper = new ModelMapper();
-
- public org.onap.aai.domain.yang.ServiceInstance mapServiceInstance (ServiceInstance serviceInstance){
- if (modelMapper.getTypeMap(ServiceInstance.class, org.onap.aai.domain.yang.ServiceInstance.class) == null) {
- modelMapper.addMappings(new PropertyMap<ServiceInstance, org.onap.aai.domain.yang.ServiceInstance>(){
- @Override
- protected void configure() {
- map().setServiceType(source.getModelInfoServiceInstance().getServiceType());
- map().setServiceRole(source.getModelInfoServiceInstance().getServiceRole());
- map().setModelInvariantId(source.getModelInfoServiceInstance().getModelInvariantUuid());
- map().setModelVersionId(source.getModelInfoServiceInstance().getModelUuid());
- map().setEnvironmentContext(source.getModelInfoServiceInstance().getEnvironmentContext());
- map().setWorkloadContext(source.getModelInfoServiceInstance().getWorkloadContext());
- }
- });
- }
-
- return modelMapper.map(serviceInstance,org.onap.aai.domain.yang.ServiceInstance.class);
- }
-
- public org.onap.aai.domain.yang.Project mapProject (Project project){
- return modelMapper.map(project,org.onap.aai.domain.yang.Project.class);
- }
-
- public org.onap.aai.domain.yang.ServiceSubscription mapServiceSubscription(ServiceSubscription serviceSubscription){
- return modelMapper.map(serviceSubscription,org.onap.aai.domain.yang.ServiceSubscription.class);
+ private static final ModelMapper modelMapper = new ModelMapper();
+
+ public org.onap.aai.domain.yang.ServiceInstance mapServiceInstance(ServiceInstance serviceInstance) {
+ if (modelMapper.getTypeMap(ServiceInstance.class, org.onap.aai.domain.yang.ServiceInstance.class) == null) {
+ modelMapper.addMappings(new PropertyMap<ServiceInstance, org.onap.aai.domain.yang.ServiceInstance>() {
+ @Override
+ protected void configure() {
+ map().setServiceType(source.getModelInfoServiceInstance().getServiceType());
+ map().setServiceRole(source.getModelInfoServiceInstance().getServiceRole());
+ map().setModelInvariantId(source.getModelInfoServiceInstance().getModelInvariantUuid());
+ map().setModelVersionId(source.getModelInfoServiceInstance().getModelUuid());
+ map().setEnvironmentContext(source.getModelInfoServiceInstance().getEnvironmentContext());
+ map().setWorkloadContext(source.getModelInfoServiceInstance().getWorkloadContext());
+ }
+ });
+ }
+
+ return modelMapper.map(serviceInstance, org.onap.aai.domain.yang.ServiceInstance.class);
+ }
+
+ public org.onap.aai.domain.yang.Project mapProject(Project project) {
+ return modelMapper.map(project, org.onap.aai.domain.yang.Project.class);
+ }
+
+ public org.onap.aai.domain.yang.ServiceSubscription mapServiceSubscription(
+ ServiceSubscription serviceSubscription) {
+ return modelMapper.map(serviceSubscription, org.onap.aai.domain.yang.ServiceSubscription.class);
+ }
+
+ public org.onap.aai.domain.yang.OwningEntity mapOwningEntity(OwningEntity owningEntity) {
+ return modelMapper.map(owningEntity, org.onap.aai.domain.yang.OwningEntity.class);
+ }
+
+ public org.onap.aai.domain.yang.GenericVnf mapVnf(GenericVnf vnf) {
+ if (modelMapper.getTypeMap(GenericVnf.class, org.onap.aai.domain.yang.GenericVnf.class) == null) {
+ modelMapper.addMappings(new PropertyMap<GenericVnf, org.onap.aai.domain.yang.GenericVnf>() {
+ @Override
+ protected void configure() {
+ map().setModelCustomizationId(source.getModelInfoGenericVnf().getModelCustomizationUuid());
+ map().setModelInvariantId(source.getModelInfoGenericVnf().getModelInvariantUuid());
+ map().setModelVersionId(source.getModelInfoGenericVnf().getModelUuid());
+ map().setNfRole(source.getModelInfoGenericVnf().getNfRole());
+ map().setNfType(source.getModelInfoGenericVnf().getNfType());
+ map().setNfFunction(source.getModelInfoGenericVnf().getNfFunction());
+ map().setNfNamingCode(source.getModelInfoGenericVnf().getNfNamingCode());
+ }
+ });
+ }
+
+ return modelMapper.map(vnf, org.onap.aai.domain.yang.GenericVnf.class);
}
- public org.onap.aai.domain.yang.OwningEntity mapOwningEntity (OwningEntity owningEntity){
- return modelMapper.map(owningEntity,org.onap.aai.domain.yang.OwningEntity.class);
- }
-
- public org.onap.aai.domain.yang.GenericVnf mapVnf (GenericVnf vnf){
- if (modelMapper.getTypeMap(GenericVnf.class, org.onap.aai.domain.yang.GenericVnf.class) == null) {
- modelMapper.addMappings(new PropertyMap<GenericVnf, org.onap.aai.domain.yang.GenericVnf>(){
- @Override
- protected void configure() {
- map().setModelCustomizationId(source.getModelInfoGenericVnf().getModelCustomizationUuid());
- map().setModelInvariantId(source.getModelInfoGenericVnf().getModelInvariantUuid());
- map().setModelVersionId(source.getModelInfoGenericVnf().getModelUuid());
- map().setNfRole(source.getModelInfoGenericVnf().getNfRole());
- map().setNfType(source.getModelInfoGenericVnf().getNfType());
- map().setNfFunction(source.getModelInfoGenericVnf().getNfFunction());
- map().setNfNamingCode(source.getModelInfoGenericVnf().getNfNamingCode());
- }
- });
- }
-
- return modelMapper.map(vnf, org.onap.aai.domain.yang.GenericVnf.class);
- }
-
- public org.onap.aai.domain.yang.VfModule mapVfModule (VfModule vfModule){
- if (modelMapper.getTypeMap(VfModule.class, org.onap.aai.domain.yang.VfModule.class) == null) {
- modelMapper.addMappings(new PropertyMap<VfModule, org.onap.aai.domain.yang.VfModule>(){
- @Override
- protected void configure() {
- map().setModelCustomizationId(source.getModelInfoVfModule().getModelCustomizationUUID());
- map().setModelInvariantId(source.getModelInfoVfModule().getModelInvariantUUID());
- map().setModelVersionId(source.getModelInfoVfModule().getModelUUID());
- map().setPersonaModelVersion(source.getModelInfoVfModule().getModelInvariantUUID());
- map().setIsBaseVfModule(source.getModelInfoVfModule().getIsBaseBoolean());
-
- }
- });
- }
-
- return modelMapper.map(vfModule, org.onap.aai.domain.yang.VfModule.class);
- }
-
- public org.onap.aai.domain.yang.VolumeGroup mapVolumeGroup(VolumeGroup volumeGroup) {
- if (modelMapper.getTypeMap(VolumeGroup.class, org.onap.aai.domain.yang.VolumeGroup.class) == null) {
- modelMapper.addMappings(new PropertyMap<VolumeGroup, org.onap.aai.domain.yang.VolumeGroup>(){
- @Override
- protected void configure() {
- map().setModelCustomizationId(source.getModelInfoVfModule().getModelCustomizationUUID());
- map().setVfModuleModelCustomizationId(source.getModelInfoVfModule().getModelCustomizationUUID());
- }
- });
- }
- return modelMapper.map(volumeGroup, org.onap.aai.domain.yang.VolumeGroup.class);
- }
-
- public org.onap.aai.domain.yang.L3Network mapNetwork (L3Network l3Network){
- if (modelMapper.getTypeMap(L3Network.class, org.onap.aai.domain.yang.L3Network.class) == null) {
- modelMapper.addMappings(new PropertyMap<L3Network, org.onap.aai.domain.yang.L3Network>(){
- @Override
- protected void configure() {
- map().setModelCustomizationId(source.getModelInfoNetwork().getModelCustomizationUUID());
- map().setModelInvariantId(source.getModelInfoNetwork().getModelInvariantUUID());
- map().setModelVersionId(source.getModelInfoNetwork().getModelUUID());
- map().setNetworkType(source.getModelInfoNetwork().getNetworkType());
- map().setNetworkRole(source.getModelInfoNetwork().getNetworkRole());
- map().setNetworkTechnology(source.getModelInfoNetwork().getNetworkTechnology());
- modelMapper.addConverter(convertSubnets);
- modelMapper.addConverter(convertCtagAssignments);
- modelMapper.addConverter(convertSegmentationAssignments);
- }
- });
- }
- return modelMapper.map(l3Network, org.onap.aai.domain.yang.L3Network.class);
- }
-
- public org.onap.aai.domain.yang.InstanceGroup mapInstanceGroup(InstanceGroup instanceGroup) {
- if (modelMapper.getTypeMap(InstanceGroup.class, org.onap.aai.domain.yang.InstanceGroup.class) == null) {
- modelMapper.addMappings(new PropertyMap<InstanceGroup, org.onap.aai.domain.yang.InstanceGroup>(){
- @Override
- protected void configure() {
- map().setInstanceGroupRole(source.getModelInfoInstanceGroup().getInstanceGroupRole());
- map().setModelInvariantId(source.getModelInfoInstanceGroup().getModelInvariantUUID());
- map().setModelVersionId(source.getModelInfoInstanceGroup().getModelUUID());
- map().setInstanceGroupType(source.getModelInfoInstanceGroup().getType());
- map().setDescription(source.getModelInfoInstanceGroup().getDescription());
- map().setInstanceGroupFunction(source.getModelInfoInstanceGroup().getFunction());
- }
- });
- }
- return modelMapper.map(instanceGroup, org.onap.aai.domain.yang.InstanceGroup.class);
- }
-
- public org.onap.aai.domain.yang.Customer mapCustomer(Customer customer) {
- return modelMapper.map(customer, org.onap.aai.domain.yang.Customer.class);
- }
-
- private Converter<List<Subnet>, org.onap.aai.domain.yang.Subnets> convertSubnets = new Converter<List<Subnet>, org.onap.aai.domain.yang.Subnets>() {
- public org.onap.aai.domain.yang.Subnets convert(MappingContext<List<Subnet>, org.onap.aai.domain.yang.Subnets> context) {
- return mapToAAISubNets(context.getSource());
+ public org.onap.aai.domain.yang.VfModule mapVfModule(VfModule vfModule) {
+ if (modelMapper.getTypeMap(VfModule.class, org.onap.aai.domain.yang.VfModule.class) == null) {
+ modelMapper.addMappings(new PropertyMap<VfModule, org.onap.aai.domain.yang.VfModule>() {
+ @Override
+ protected void configure() {
+ map().setModelCustomizationId(source.getModelInfoVfModule().getModelCustomizationUUID());
+ map().setModelInvariantId(source.getModelInfoVfModule().getModelInvariantUUID());
+ map().setModelVersionId(source.getModelInfoVfModule().getModelUUID());
+ map().setPersonaModelVersion(source.getModelInfoVfModule().getModelInvariantUUID());
+ map().setIsBaseVfModule(source.getModelInfoVfModule().getIsBaseBoolean());
+
+ }
+ });
}
- };
- private Converter<List<CtagAssignment>, org.onap.aai.domain.yang.CtagAssignments> convertCtagAssignments = new Converter<List<CtagAssignment>, org.onap.aai.domain.yang.CtagAssignments>() {
- public org.onap.aai.domain.yang.CtagAssignments convert(MappingContext<List<CtagAssignment>, org.onap.aai.domain.yang.CtagAssignments> context) {
- return mapToAAICtagAssignmentList(context.getSource());
+ return modelMapper.map(vfModule, org.onap.aai.domain.yang.VfModule.class);
+ }
+
+ public org.onap.aai.domain.yang.VolumeGroup mapVolumeGroup(VolumeGroup volumeGroup) {
+ if (modelMapper.getTypeMap(VolumeGroup.class, org.onap.aai.domain.yang.VolumeGroup.class) == null) {
+ modelMapper.addMappings(new PropertyMap<VolumeGroup, org.onap.aai.domain.yang.VolumeGroup>() {
+ @Override
+ protected void configure() {
+ map().setModelCustomizationId(source.getModelInfoVfModule().getModelCustomizationUUID());
+ map().setVfModuleModelCustomizationId(source.getModelInfoVfModule().getModelCustomizationUUID());
+ }
+ });
}
- };
+ return modelMapper.map(volumeGroup, org.onap.aai.domain.yang.VolumeGroup.class);
+ }
+
+ public org.onap.aai.domain.yang.L3Network mapNetwork(L3Network l3Network) {
+ if (modelMapper.getTypeMap(L3Network.class, org.onap.aai.domain.yang.L3Network.class) == null) {
+ modelMapper.addMappings(new PropertyMap<L3Network, org.onap.aai.domain.yang.L3Network>() {
+ @Override
+ protected void configure() {
+ map().setModelCustomizationId(source.getModelInfoNetwork().getModelCustomizationUUID());
+ map().setModelInvariantId(source.getModelInfoNetwork().getModelInvariantUUID());
+ map().setModelVersionId(source.getModelInfoNetwork().getModelUUID());
+ map().setNetworkType(source.getModelInfoNetwork().getNetworkType());
+ map().setNetworkRole(source.getModelInfoNetwork().getNetworkRole());
+ map().setNetworkTechnology(source.getModelInfoNetwork().getNetworkTechnology());
+ modelMapper.addConverter(convertSubnets);
+ modelMapper.addConverter(convertCtagAssignments);
+ modelMapper.addConverter(convertSegmentationAssignments);
+ }
+ });
+ }
+ return modelMapper.map(l3Network, org.onap.aai.domain.yang.L3Network.class);
+ }
- private Converter<List<SegmentationAssignment>, org.onap.aai.domain.yang.SegmentationAssignments> convertSegmentationAssignments = new Converter<List<SegmentationAssignment>, org.onap.aai.domain.yang.SegmentationAssignments>() {
- public org.onap.aai.domain.yang.SegmentationAssignments convert(MappingContext<List<SegmentationAssignment>, org.onap.aai.domain.yang.SegmentationAssignments> context) {
- return mapToAAISegmentationAssignmentList(context.getSource());
+ public org.onap.aai.domain.yang.InstanceGroup mapInstanceGroup(InstanceGroup instanceGroup) {
+ if (modelMapper.getTypeMap(InstanceGroup.class, org.onap.aai.domain.yang.InstanceGroup.class) == null) {
+ modelMapper.addMappings(new PropertyMap<InstanceGroup, org.onap.aai.domain.yang.InstanceGroup>() {
+ @Override
+ protected void configure() {
+ map().setInstanceGroupRole(source.getModelInfoInstanceGroup().getInstanceGroupRole());
+ map().setModelInvariantId(source.getModelInfoInstanceGroup().getModelInvariantUUID());
+ map().setModelVersionId(source.getModelInfoInstanceGroup().getModelUUID());
+ map().setInstanceGroupType(source.getModelInfoInstanceGroup().getType());
+ map().setDescription(source.getModelInfoInstanceGroup().getDescription());
+ map().setInstanceGroupFunction(source.getModelInfoInstanceGroup().getFunction());
+ }
+ });
}
- };
-
- public org.onap.aai.domain.yang.Subnets mapToAAISubNets(List<Subnet> subnetList) {
- org.onap.aai.domain.yang.Subnets subnets = null;
-
- if (!subnetList.isEmpty()) {
- subnets = new org.onap.aai.domain.yang.Subnets();
- org.onap.aai.domain.yang.Subnet subnet = null;
- for (Subnet subnetSource : subnetList) {
- subnet = new org.onap.aai.domain.yang.Subnet();
- subnet.setSubnetId(subnetSource.getSubnetId());
- subnet.setSubnetName(subnetSource.getSubnetName());
- subnet.setNeutronSubnetId(subnetSource.getNeutronSubnetId());
- subnet.setGatewayAddress(subnetSource.getGatewayAddress());
- subnet.setCidrMask(subnetSource.getCidrMask());
- subnet.setIpVersion(subnetSource.getIpVersion());
- subnet.setOrchestrationStatus(subnetSource.getOrchestrationStatus().toString());
- subnet.setCidrMask(subnetSource.getCidrMask());
- subnet.setDhcpEnabled(subnetSource.isDhcpEnabled());
- subnet.setDhcpStart(subnetSource.getDhcpStart());
- subnet.setDhcpEnd(subnetSource.getDhcpEnd());
- subnet.setSubnetRole(subnetSource.getSubnetRole());
- subnet.setIpAssignmentDirection(subnetSource.getIpAssignmentDirection());
- subnet.setSubnetSequence(subnetSource.getSubnetSequence());
-
- org.onap.aai.domain.yang.HostRoutes hostRoutes = new org.onap.aai.domain.yang.HostRoutes();
- org.onap.aai.domain.yang.HostRoute hostRoute = null;
- for (HostRoute hostRouteSource : subnetSource.getHostRoutes()) {
- hostRoute = new org.onap.aai.domain.yang.HostRoute();
- hostRoute.setHostRouteId(hostRouteSource.getHostRouteId());
- hostRoute.setRoutePrefix(hostRouteSource.getRoutePrefix());
- hostRoute.setNextHop(hostRouteSource.getNextHop());
- hostRoute.setNextHopType(hostRouteSource.getNextHopType());
- hostRoutes.getHostRoute().add(hostRoute);
- }
- subnet.setHostRoutes(hostRoutes);
- subnets.getSubnet().add(subnet);
- }
- }
- return subnets;
- }
-
- public org.onap.aai.domain.yang.CtagAssignments mapToAAICtagAssignmentList(List<CtagAssignment> ctagAssignmentsList) {
- org.onap.aai.domain.yang.CtagAssignments ctagAssignments = null;
- if (!ctagAssignmentsList.isEmpty()) {
- ctagAssignments = new org.onap.aai.domain.yang.CtagAssignments();
-
- org.onap.aai.domain.yang.CtagAssignment ctagAssignment = null;
- for (CtagAssignment ctagAssignmentSource : ctagAssignmentsList) {
- ctagAssignment = new org.onap.aai.domain.yang.CtagAssignment();
- ctagAssignment.setVlanIdInner(ctagAssignmentSource.getVlanIdInner());
- ctagAssignments.getCtagAssignment().add(ctagAssignment);
- }
- }
- return ctagAssignments;
- }
-
- public org.onap.aai.domain.yang.SegmentationAssignments mapToAAISegmentationAssignmentList(List<SegmentationAssignment> segmentationAssignmentList) {
- org.onap.aai.domain.yang.SegmentationAssignments segmentationAssignments = null;
- if (!segmentationAssignmentList.isEmpty()) {
- segmentationAssignments = new org.onap.aai.domain.yang.SegmentationAssignments();
- org.onap.aai.domain.yang.SegmentationAssignment segmentationAssignment = null;
- for (SegmentationAssignment segmentationAssignmentSource : segmentationAssignmentList) {
- segmentationAssignment = new org.onap.aai.domain.yang.SegmentationAssignment();
- segmentationAssignment.setSegmentationId(segmentationAssignmentSource.getSegmentationId());
- segmentationAssignments.getSegmentationAssignment().add(segmentationAssignment);
- }
- }
- return segmentationAssignments;
- }
-
- public org.onap.aai.domain.yang.Configuration mapConfiguration(Configuration configuration) {
- if (null == modelMapper.getTypeMap(Configuration.class, org.onap.aai.domain.yang.Configuration.class)) {
- modelMapper.addMappings(new PropertyMap<Configuration, org.onap.aai.domain.yang.Configuration>(){
- @Override
- protected void configure() {
- map().setModelCustomizationId(source.getModelInfoConfiguration().getModelCustomizationId());
- map().setModelVersionId(source.getModelInfoConfiguration().getModelVersionId());
- map().setModelInvariantId(source.getModelInfoConfiguration().getModelInvariantId());
- map().setConfigurationType(source.getModelInfoConfiguration().getConfigurationType());
- map().setConfigurationSubType(source.getModelInfoConfiguration().getConfigurationRole());
- map().setConfigPolicyName(source.getModelInfoConfiguration().getPolicyName());
- }
- });
- }
- return modelMapper.map(configuration, org.onap.aai.domain.yang.Configuration.class);
- }
-
- public org.onap.aai.domain.yang.Collection mapCollection (Collection networkCollection){
- if (modelMapper.getTypeMap(Collection.class, org.onap.aai.domain.yang.Collection.class) == null) {
- modelMapper.addMappings(new PropertyMap<Collection, org.onap.aai.domain.yang.Collection>(){
- @Override
- protected void configure() {
- map().setModelInvariantId(source.getModelInfoCollection().getModelInvariantUUID());
- map().setModelVersionId(source.getModelInfoCollection().getModelVersionId());
- map().setCollectionCustomizationId(source.getModelInfoCollection().getModelCustomizationUUID());
- map().setCollectionFunction(source.getModelInfoCollection().getCollectionFunction());
- map().setCollectionRole(source.getModelInfoCollection().getCollectionRole());
- map().setCollectionType(source.getModelInfoCollection().getCollectionType());
- map().setCollectionName(source.getName());
- }
- });
- }
- return modelMapper.map(networkCollection, org.onap.aai.domain.yang.Collection.class);
- }
+ return modelMapper.map(instanceGroup, org.onap.aai.domain.yang.InstanceGroup.class);
+ }
+
+ public org.onap.aai.domain.yang.Customer mapCustomer(Customer customer) {
+ return modelMapper.map(customer, org.onap.aai.domain.yang.Customer.class);
+ }
+
+ private Converter<List<Subnet>, org.onap.aai.domain.yang.Subnets> convertSubnets =
+ new Converter<List<Subnet>, org.onap.aai.domain.yang.Subnets>() {
+ public org.onap.aai.domain.yang.Subnets convert(
+ MappingContext<List<Subnet>, org.onap.aai.domain.yang.Subnets> context) {
+ return mapToAAISubNets(context.getSource());
+ }
+ };
+
+ private Converter<List<CtagAssignment>, org.onap.aai.domain.yang.CtagAssignments> convertCtagAssignments =
+ new Converter<List<CtagAssignment>, org.onap.aai.domain.yang.CtagAssignments>() {
+ public org.onap.aai.domain.yang.CtagAssignments convert(
+ MappingContext<List<CtagAssignment>, org.onap.aai.domain.yang.CtagAssignments> context) {
+ return mapToAAICtagAssignmentList(context.getSource());
+ }
+ };
+
+ private Converter<List<SegmentationAssignment>, org.onap.aai.domain.yang.SegmentationAssignments> convertSegmentationAssignments =
+ new Converter<List<SegmentationAssignment>, org.onap.aai.domain.yang.SegmentationAssignments>() {
+ public org.onap.aai.domain.yang.SegmentationAssignments convert(
+ MappingContext<List<SegmentationAssignment>, org.onap.aai.domain.yang.SegmentationAssignments> context) {
+ return mapToAAISegmentationAssignmentList(context.getSource());
+ }
+ };
+
+ public org.onap.aai.domain.yang.Subnets mapToAAISubNets(List<Subnet> subnetList) {
+ org.onap.aai.domain.yang.Subnets subnets = null;
+
+ if (!subnetList.isEmpty()) {
+ subnets = new org.onap.aai.domain.yang.Subnets();
+ org.onap.aai.domain.yang.Subnet subnet = null;
+ for (Subnet subnetSource : subnetList) {
+ subnet = new org.onap.aai.domain.yang.Subnet();
+ subnet.setSubnetId(subnetSource.getSubnetId());
+ subnet.setSubnetName(subnetSource.getSubnetName());
+ subnet.setNeutronSubnetId(subnetSource.getNeutronSubnetId());
+ subnet.setGatewayAddress(subnetSource.getGatewayAddress());
+ subnet.setCidrMask(subnetSource.getCidrMask());
+ subnet.setIpVersion(subnetSource.getIpVersion());
+ subnet.setOrchestrationStatus(subnetSource.getOrchestrationStatus().toString());
+ subnet.setCidrMask(subnetSource.getCidrMask());
+ subnet.setDhcpEnabled(subnetSource.isDhcpEnabled());
+ subnet.setDhcpStart(subnetSource.getDhcpStart());
+ subnet.setDhcpEnd(subnetSource.getDhcpEnd());
+ subnet.setSubnetRole(subnetSource.getSubnetRole());
+ subnet.setIpAssignmentDirection(subnetSource.getIpAssignmentDirection());
+ subnet.setSubnetSequence(subnetSource.getSubnetSequence());
+
+ org.onap.aai.domain.yang.HostRoutes hostRoutes = new org.onap.aai.domain.yang.HostRoutes();
+ org.onap.aai.domain.yang.HostRoute hostRoute = null;
+ for (HostRoute hostRouteSource : subnetSource.getHostRoutes()) {
+ hostRoute = new org.onap.aai.domain.yang.HostRoute();
+ hostRoute.setHostRouteId(hostRouteSource.getHostRouteId());
+ hostRoute.setRoutePrefix(hostRouteSource.getRoutePrefix());
+ hostRoute.setNextHop(hostRouteSource.getNextHop());
+ hostRoute.setNextHopType(hostRouteSource.getNextHopType());
+ hostRoutes.getHostRoute().add(hostRoute);
+ }
+ subnet.setHostRoutes(hostRoutes);
+ subnets.getSubnet().add(subnet);
+ }
+ }
+ return subnets;
+ }
+
+ public org.onap.aai.domain.yang.CtagAssignments mapToAAICtagAssignmentList(
+ List<CtagAssignment> ctagAssignmentsList) {
+ org.onap.aai.domain.yang.CtagAssignments ctagAssignments = null;
+ if (!ctagAssignmentsList.isEmpty()) {
+ ctagAssignments = new org.onap.aai.domain.yang.CtagAssignments();
+
+ org.onap.aai.domain.yang.CtagAssignment ctagAssignment = null;
+ for (CtagAssignment ctagAssignmentSource : ctagAssignmentsList) {
+ ctagAssignment = new org.onap.aai.domain.yang.CtagAssignment();
+ ctagAssignment.setVlanIdInner(ctagAssignmentSource.getVlanIdInner());
+ ctagAssignments.getCtagAssignment().add(ctagAssignment);
+ }
+ }
+ return ctagAssignments;
+ }
+
+ public org.onap.aai.domain.yang.SegmentationAssignments mapToAAISegmentationAssignmentList(
+ List<SegmentationAssignment> segmentationAssignmentList) {
+ org.onap.aai.domain.yang.SegmentationAssignments segmentationAssignments = null;
+ if (!segmentationAssignmentList.isEmpty()) {
+ segmentationAssignments = new org.onap.aai.domain.yang.SegmentationAssignments();
+ org.onap.aai.domain.yang.SegmentationAssignment segmentationAssignment = null;
+ for (SegmentationAssignment segmentationAssignmentSource : segmentationAssignmentList) {
+ segmentationAssignment = new org.onap.aai.domain.yang.SegmentationAssignment();
+ segmentationAssignment.setSegmentationId(segmentationAssignmentSource.getSegmentationId());
+ segmentationAssignments.getSegmentationAssignment().add(segmentationAssignment);
+ }
+ }
+ return segmentationAssignments;
+ }
+
+ public org.onap.aai.domain.yang.Configuration mapConfiguration(Configuration configuration) {
+ if (null == modelMapper.getTypeMap(Configuration.class, org.onap.aai.domain.yang.Configuration.class)) {
+ modelMapper.addMappings(new PropertyMap<Configuration, org.onap.aai.domain.yang.Configuration>() {
+ @Override
+ protected void configure() {
+ map().setModelCustomizationId(source.getModelInfoConfiguration().getModelCustomizationId());
+ map().setModelVersionId(source.getModelInfoConfiguration().getModelVersionId());
+ map().setModelInvariantId(source.getModelInfoConfiguration().getModelInvariantId());
+ map().setConfigurationType(source.getModelInfoConfiguration().getConfigurationType());
+ map().setConfigurationSubType(source.getModelInfoConfiguration().getConfigurationRole());
+ map().setConfigPolicyName(source.getModelInfoConfiguration().getPolicyName());
+ }
+ });
+ }
+ return modelMapper.map(configuration, org.onap.aai.domain.yang.Configuration.class);
+ }
+
+ public org.onap.aai.domain.yang.Collection mapCollection(Collection networkCollection) {
+ if (modelMapper.getTypeMap(Collection.class, org.onap.aai.domain.yang.Collection.class) == null) {
+ modelMapper.addMappings(new PropertyMap<Collection, org.onap.aai.domain.yang.Collection>() {
+ @Override
+ protected void configure() {
+ map().setModelInvariantId(source.getModelInfoCollection().getModelInvariantUUID());
+ map().setModelVersionId(source.getModelInfoCollection().getModelVersionId());
+ map().setCollectionCustomizationId(source.getModelInfoCollection().getModelCustomizationUUID());
+ map().setCollectionFunction(source.getModelInfoCollection().getCollectionFunction());
+ map().setCollectionRole(source.getModelInfoCollection().getCollectionRole());
+ map().setCollectionType(source.getModelInfoCollection().getCollectionType());
+ map().setCollectionName(source.getName());
+ }
+ });
+ }
+ return modelMapper.map(networkCollection, org.onap.aai.domain.yang.Collection.class);
+ }
public org.onap.aai.domain.yang.VpnBinding mapVpnBinding(VpnBinding vpnBinding) {
- org.onap.aai.domain.yang.VpnBinding aaiVpnBinding = modelMapper.map(vpnBinding, org.onap.aai.domain.yang.VpnBinding.class);
- mapRouteTargetToVpnBinding(aaiVpnBinding,vpnBinding);
- return aaiVpnBinding;
- }
-
- public org.onap.aai.domain.yang.RouteTarget mapRouteTarget(RouteTarget routeTarget) {
- return modelMapper.map(routeTarget, org.onap.aai.domain.yang.RouteTarget.class);
- }
-
- private void mapRouteTargetToVpnBinding(org.onap.aai.domain.yang.VpnBinding aaiVpnBinding, VpnBinding vpnBinding) {
- if(vpnBinding.getRouteTargets() != null && !vpnBinding.getRouteTargets().isEmpty()) {
- RouteTargets routeTargets = new RouteTargets();
- for (RouteTarget routeTarget : vpnBinding.getRouteTargets()) {
- routeTargets.getRouteTarget().add(mapRouteTarget(routeTarget));
- }
- aaiVpnBinding.setRouteTargets(routeTargets);
- }
- }
-
- public org.onap.aai.domain.yang.Subnet mapSubnet (Subnet subnet){
- return modelMapper.map(subnet,org.onap.aai.domain.yang.Subnet.class);
- }
-
- public org.onap.aai.domain.yang.NetworkPolicy mapNetworkPolicy (NetworkPolicy networkPolicy){
- return modelMapper.map(networkPolicy,org.onap.aai.domain.yang.NetworkPolicy.class);
- }
+ org.onap.aai.domain.yang.VpnBinding aaiVpnBinding =
+ modelMapper.map(vpnBinding, org.onap.aai.domain.yang.VpnBinding.class);
+ mapRouteTargetToVpnBinding(aaiVpnBinding, vpnBinding);
+ return aaiVpnBinding;
+ }
+
+ public org.onap.aai.domain.yang.RouteTarget mapRouteTarget(RouteTarget routeTarget) {
+ return modelMapper.map(routeTarget, org.onap.aai.domain.yang.RouteTarget.class);
+ }
+
+ private void mapRouteTargetToVpnBinding(org.onap.aai.domain.yang.VpnBinding aaiVpnBinding, VpnBinding vpnBinding) {
+ if (vpnBinding.getRouteTargets() != null && !vpnBinding.getRouteTargets().isEmpty()) {
+ RouteTargets routeTargets = new RouteTargets();
+ for (RouteTarget routeTarget : vpnBinding.getRouteTargets()) {
+ routeTargets.getRouteTarget().add(mapRouteTarget(routeTarget));
+ }
+ aaiVpnBinding.setRouteTargets(routeTargets);
+ }
+ }
+
+ public org.onap.aai.domain.yang.Subnet mapSubnet(Subnet subnet) {
+ return modelMapper.map(subnet, org.onap.aai.domain.yang.Subnet.class);
+ }
+
+ public org.onap.aai.domain.yang.NetworkPolicy mapNetworkPolicy(NetworkPolicy networkPolicy) {
+ return modelMapper.map(networkPolicy, org.onap.aai.domain.yang.NetworkPolicy.class);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClient.java
index 350a6ae8d6..62d0c230fb 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClient.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClient.java
@@ -21,7 +21,6 @@
package org.onap.so.client.adapter.network;
import javax.ws.rs.core.Response;
-
import org.onap.so.adapters.nwrest.CreateNetworkRequest;
import org.onap.so.adapters.nwrest.CreateNetworkResponse;
import org.onap.so.adapters.nwrest.DeleteNetworkRequest;
@@ -33,25 +32,25 @@ import org.onap.so.adapters.nwrest.UpdateNetworkRequest;
import org.onap.so.adapters.nwrest.UpdateNetworkResponse;
public interface NetworkAdapterClient {
- CreateNetworkResponse createNetwork(CreateNetworkRequest req) throws NetworkAdapterClientException;
+ CreateNetworkResponse createNetwork(CreateNetworkRequest req) throws NetworkAdapterClientException;
+
+ DeleteNetworkResponse deleteNetwork(String aaiNetworkId, DeleteNetworkRequest req)
+ throws NetworkAdapterClientException;
- DeleteNetworkResponse deleteNetwork(String aaiNetworkId, DeleteNetworkRequest req)
- throws NetworkAdapterClientException;
+ RollbackNetworkResponse rollbackNetwork(String aaiNetworkId, RollbackNetworkRequest req)
+ throws NetworkAdapterClientException;
- RollbackNetworkResponse rollbackNetwork(String aaiNetworkId, RollbackNetworkRequest req)
- throws NetworkAdapterClientException;
+ QueryNetworkResponse queryNetwork(String aaiNetworkId, String cloudSiteId, String tenantId, String networkStackId,
+ boolean skipAAI, String requestId, String serviceInstanceId) throws NetworkAdapterClientException;
- QueryNetworkResponse queryNetwork(String aaiNetworkId, String cloudSiteId, String tenantId, String networkStackId,
- boolean skipAAI, String requestId, String serviceInstanceId) throws NetworkAdapterClientException;
+ UpdateNetworkResponse updateNetwork(String aaiNetworkId, UpdateNetworkRequest req)
+ throws NetworkAdapterClientException;
- UpdateNetworkResponse updateNetwork(String aaiNetworkId, UpdateNetworkRequest req)
- throws NetworkAdapterClientException;
+ Response createNetworkAsync(CreateNetworkRequest req) throws NetworkAdapterClientException;
- Response createNetworkAsync(CreateNetworkRequest req) throws NetworkAdapterClientException;
+ Response deleteNetworkAsync(String aaiNetworkId, DeleteNetworkRequest req) throws NetworkAdapterClientException;
- Response deleteNetworkAsync(String aaiNetworkId, DeleteNetworkRequest req) throws NetworkAdapterClientException;
+ Response rollbackNetworkAsync(String aaiNetworkId, RollbackNetworkRequest req) throws NetworkAdapterClientException;
- Response rollbackNetworkAsync(String aaiNetworkId, RollbackNetworkRequest req) throws NetworkAdapterClientException;
-
- Response updateNetworkAsync(String aaiNetworkId, UpdateNetworkRequest req) throws NetworkAdapterClientException;
+ Response updateNetworkAsync(String aaiNetworkId, UpdateNetworkRequest req) throws NetworkAdapterClientException;
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClientException.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClientException.java
index 0492477cf6..2712f1e6f7 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClientException.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClientException.java
@@ -23,13 +23,13 @@ package org.onap.so.client.adapter.network;
public class NetworkAdapterClientException extends Exception {
- /**
- *
- */
- private static final long serialVersionUID = 8040736661096488110L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 8040736661096488110L;
- public NetworkAdapterClientException(String message) {
- super(message);
- }
+ public NetworkAdapterClientException(String message) {
+ super(message);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClientImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClientImpl.java
index e8a5723e19..8668306f13 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClientImpl.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterClientImpl.java
@@ -24,7 +24,6 @@ import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.adapters.nwrest.CreateNetworkRequest;
import org.onap.so.adapters.nwrest.CreateNetworkResponse;
import org.onap.so.adapters.nwrest.DeleteNetworkRequest;
@@ -40,120 +39,126 @@ import org.springframework.stereotype.Component;
@Component
public class NetworkAdapterClientImpl implements NetworkAdapterClient {
- private final NetworkAdapterRestProperties props;
-
- public NetworkAdapterClientImpl() {
- this.props = new NetworkAdapterRestProperties();
- }
-
- @Override
- public CreateNetworkResponse createNetwork(CreateNetworkRequest req) throws NetworkAdapterClientException{
- try {
- return new AdapterRestClient(this.props, this.getUri("").build()).post(req,
- CreateNetworkResponse.class);
- } catch (InternalServerErrorException e) {
- throw new NetworkAdapterClientException(e.getMessage());
- }
- }
-
- @Override
- public Response createNetworkAsync(CreateNetworkRequest req) throws NetworkAdapterClientException{
- try {
- return new AdapterRestClient(this.props, this.getUri("").build()).post(req);
- } catch (InternalServerErrorException e) {
- throw new NetworkAdapterClientException(e.getMessage());
- }
- }
-
- @Override
- public DeleteNetworkResponse deleteNetwork(String aaiNetworkId, DeleteNetworkRequest req) throws NetworkAdapterClientException {
- try {
- return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).delete(req,
- DeleteNetworkResponse.class);
- } catch (InternalServerErrorException e) {
- throw new NetworkAdapterClientException(e.getMessage());
- }
- }
-
- @Override
- public Response deleteNetworkAsync(String aaiNetworkId, DeleteNetworkRequest req) throws NetworkAdapterClientException {
- try {
- return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).delete(req);
- } catch (InternalServerErrorException e) {
- throw new NetworkAdapterClientException(e.getMessage());
- }
- }
-
- @Override
- public RollbackNetworkResponse rollbackNetwork(String aaiNetworkId, RollbackNetworkRequest req) throws NetworkAdapterClientException {
- try {
- return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).delete(req,
- RollbackNetworkResponse.class);
- } catch (InternalServerErrorException e) {
- throw new NetworkAdapterClientException(e.getMessage());
- }
- }
-
- @Override
- public Response rollbackNetworkAsync(String aaiNetworkId, RollbackNetworkRequest req) throws NetworkAdapterClientException {
- try {
- return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).delete(req);
- } catch (InternalServerErrorException e) {
- throw new NetworkAdapterClientException(e.getMessage());
- }
- }
-
- @Override
- public QueryNetworkResponse queryNetwork(String aaiNetworkId, String cloudSiteId, String tenantId,
- String networkStackId, boolean skipAAI, String requestId, String serviceInstanceId) throws NetworkAdapterClientException {
- UriBuilder builder = this.getUri("/" + aaiNetworkId);
- if (cloudSiteId != null) {
- builder.queryParam("cloudSiteId", cloudSiteId);
- }
- if (tenantId != null) {
- builder.queryParam("tenantId", tenantId);
- }
- if (networkStackId != null) {
- builder.queryParam("networkStackId", networkStackId);
- }
-
- builder.queryParam("skipAAI", skipAAI);
-
- if (requestId != null) {
- builder.queryParam("msoRequest.requestId", requestId);
- }
- if (serviceInstanceId != null) {
- builder.queryParam("msoRequest.serviceInstanceId", serviceInstanceId);
- }
- try {
- return new AdapterRestClient(this.props, builder.build(), MediaType.APPLICATION_XML, MediaType.APPLICATION_XML)
- .get(QueryNetworkResponse.class).get();
- } catch (InternalServerErrorException e) {
- throw new NetworkAdapterClientException(e.getMessage());
- }
- }
-
- @Override
- public UpdateNetworkResponse updateNetwork(String aaiNetworkId, UpdateNetworkRequest req) throws NetworkAdapterClientException {
- try {
- return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).put(req,
- UpdateNetworkResponse.class);
- } catch (InternalServerErrorException e) {
- throw new NetworkAdapterClientException(e.getMessage());
- }
- }
-
- @Override
- public Response updateNetworkAsync(String aaiNetworkId, UpdateNetworkRequest req) throws NetworkAdapterClientException{
- try {
- return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).put(req);
- } catch (InternalServerErrorException e) {
- throw new NetworkAdapterClientException(e.getMessage());
- }
- }
-
- protected UriBuilder getUri(String path) {
- return UriBuilder.fromPath(path);
- }
+ private final NetworkAdapterRestProperties props;
+
+ public NetworkAdapterClientImpl() {
+ this.props = new NetworkAdapterRestProperties();
+ }
+
+ @Override
+ public CreateNetworkResponse createNetwork(CreateNetworkRequest req) throws NetworkAdapterClientException {
+ try {
+ return new AdapterRestClient(this.props, this.getUri("").build()).post(req, CreateNetworkResponse.class);
+ } catch (InternalServerErrorException e) {
+ throw new NetworkAdapterClientException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Response createNetworkAsync(CreateNetworkRequest req) throws NetworkAdapterClientException {
+ try {
+ return new AdapterRestClient(this.props, this.getUri("").build()).post(req);
+ } catch (InternalServerErrorException e) {
+ throw new NetworkAdapterClientException(e.getMessage());
+ }
+ }
+
+ @Override
+ public DeleteNetworkResponse deleteNetwork(String aaiNetworkId, DeleteNetworkRequest req)
+ throws NetworkAdapterClientException {
+ try {
+ return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).delete(req,
+ DeleteNetworkResponse.class);
+ } catch (InternalServerErrorException e) {
+ throw new NetworkAdapterClientException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Response deleteNetworkAsync(String aaiNetworkId, DeleteNetworkRequest req)
+ throws NetworkAdapterClientException {
+ try {
+ return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).delete(req);
+ } catch (InternalServerErrorException e) {
+ throw new NetworkAdapterClientException(e.getMessage());
+ }
+ }
+
+ @Override
+ public RollbackNetworkResponse rollbackNetwork(String aaiNetworkId, RollbackNetworkRequest req)
+ throws NetworkAdapterClientException {
+ try {
+ return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).delete(req,
+ RollbackNetworkResponse.class);
+ } catch (InternalServerErrorException e) {
+ throw new NetworkAdapterClientException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Response rollbackNetworkAsync(String aaiNetworkId, RollbackNetworkRequest req)
+ throws NetworkAdapterClientException {
+ try {
+ return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).delete(req);
+ } catch (InternalServerErrorException e) {
+ throw new NetworkAdapterClientException(e.getMessage());
+ }
+ }
+
+ @Override
+ public QueryNetworkResponse queryNetwork(String aaiNetworkId, String cloudSiteId, String tenantId,
+ String networkStackId, boolean skipAAI, String requestId, String serviceInstanceId)
+ throws NetworkAdapterClientException {
+ UriBuilder builder = this.getUri("/" + aaiNetworkId);
+ if (cloudSiteId != null) {
+ builder.queryParam("cloudSiteId", cloudSiteId);
+ }
+ if (tenantId != null) {
+ builder.queryParam("tenantId", tenantId);
+ }
+ if (networkStackId != null) {
+ builder.queryParam("networkStackId", networkStackId);
+ }
+
+ builder.queryParam("skipAAI", skipAAI);
+
+ if (requestId != null) {
+ builder.queryParam("msoRequest.requestId", requestId);
+ }
+ if (serviceInstanceId != null) {
+ builder.queryParam("msoRequest.serviceInstanceId", serviceInstanceId);
+ }
+ try {
+ return new AdapterRestClient(this.props, builder.build(), MediaType.APPLICATION_XML,
+ MediaType.APPLICATION_XML).get(QueryNetworkResponse.class).get();
+ } catch (InternalServerErrorException e) {
+ throw new NetworkAdapterClientException(e.getMessage());
+ }
+ }
+
+ @Override
+ public UpdateNetworkResponse updateNetwork(String aaiNetworkId, UpdateNetworkRequest req)
+ throws NetworkAdapterClientException {
+ try {
+ return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).put(req,
+ UpdateNetworkResponse.class);
+ } catch (InternalServerErrorException e) {
+ throw new NetworkAdapterClientException(e.getMessage());
+ }
+ }
+
+ @Override
+ public Response updateNetworkAsync(String aaiNetworkId, UpdateNetworkRequest req)
+ throws NetworkAdapterClientException {
+ try {
+ return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).put(req);
+ } catch (InternalServerErrorException e) {
+ throw new NetworkAdapterClientException(e.getMessage());
+ }
+ }
+
+ protected UriBuilder getUri(String path) {
+ return UriBuilder.fromPath(path);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterRestProperties.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterRestProperties.java
index 9888dd3be2..d35f810d2d 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterRestProperties.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/NetworkAdapterRestProperties.java
@@ -22,32 +22,32 @@ package org.onap.so.client.adapter.network;
import java.net.MalformedURLException;
import java.net.URL;
-
import org.onap.so.bpmn.core.UrnPropertiesReader;
import org.onap.so.client.adapter.rest.AdapterRestProperties;
public class NetworkAdapterRestProperties implements AdapterRestProperties {
- public NetworkAdapterRestProperties() {
- }
-
- @Override
- public String getAuth() {
- return UrnPropertiesReader.getVariable("mso.adapters.po.auth");
- }
- @Override
- public String getKey() {
- return UrnPropertiesReader.getVariable("mso.msoKey");
- }
- @Override
- public URL getEndpoint() throws MalformedURLException {
- return new URL(UrnPropertiesReader.getVariable("mso.adapters.network.rest.endpoint"));
- }
-
- @Override
- public String getSystemName() {
- return "MSO";
- }
+ public NetworkAdapterRestProperties() {}
+
+ @Override
+ public String getAuth() {
+ return UrnPropertiesReader.getVariable("mso.adapters.po.auth");
+ }
+
+ @Override
+ public String getKey() {
+ return UrnPropertiesReader.getVariable("mso.msoKey");
+ }
+
+ @Override
+ public URL getEndpoint() throws MalformedURLException {
+ return new URL(UrnPropertiesReader.getVariable("mso.adapters.network.rest.endpoint"));
+ }
+
+ @Override
+ public String getSystemName() {
+ return "MSO";
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java
index 8c774d8677..4fee1f909b 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java
@@ -27,7 +27,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
-
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.modelmapper.PropertyMap;
@@ -61,329 +60,353 @@ import org.springframework.web.util.UriUtils;
@Component
public class NetworkAdapterObjectMapper {
- private static final ModelMapper modelMapper = new ModelMapper();
- private static String FORWARD_SLASH = "/";
- private static final Logger logger = LoggerFactory.getLogger(NetworkAdapterObjectMapper.class);
-
- public CreateNetworkRequest createNetworkRequestMapper(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network, Map<String, String> userInput, String cloudRegionPo, Customer customer) throws UnsupportedEncodingException {
- CreateNetworkRequest createNetworkRequest = new CreateNetworkRequest();
-
- //set cloudSiteId as determined for cloud region PO instead of cloudRegion.getLcpCloudRegionId()
- createNetworkRequest.setCloudSiteId(cloudRegionPo);
- createNetworkRequest.setTenantId(cloudRegion.getTenantId());
- createNetworkRequest.setNetworkId(l3Network.getNetworkId());
- createNetworkRequest.setNetworkName(l3Network.getNetworkName());
- //TODO fields not available
- createNetworkRequest.setNetworkType(l3Network.getNetworkType());
- //createNetworkRequest.setNetworkTypeVersion(serviceInstance.getModelInfoServiceInstance().getModelVersion());
- ModelInfoNetwork modelInfoNetwork = l3Network.getModelInfoNetwork();
- if (modelInfoNetwork != null){
- createNetworkRequest.setModelCustomizationUuid(modelInfoNetwork.getModelCustomizationUUID());
- }
-
- //build and set Subnet list
- createNetworkRequest.setSubnets(buildOpenstackSubnetList(l3Network));
-
- //build and set provider Vlan Network
- ProviderVlanNetwork providerVlanNetwork = buildProviderVlanNetwork(l3Network);
- createNetworkRequest.setProviderVlanNetwork(providerVlanNetwork);
- String networkTechnology = l3Network.getModelInfoNetwork().getNetworkTechnology();
- if(networkTechnology == null) {
- networkTechnology = l3Network.getNetworkTechnology();
- logger.warn("NetworkTechnology was null in CatalogDB. Using field from AAI: " + networkTechnology);
- }
- if (networkTechnology != null) {
- createNetworkRequest.setNetworkTechnology(networkTechnology.toUpperCase());
- if (createNetworkRequest.getNetworkTechnology().contains("CONTRAIL")) {
- createNetworkRequest.setContrailRequest(true);
- }
- }
-
- //build and set Contrail Network
- ContrailNetwork contrailNetwork = buildContrailNetwork(l3Network, customer);
- createNetworkRequest.setContrailNetwork(contrailNetwork);
-
- //set Network Parameters from VID request, add "shared" and "external" to this map
- createNetworkRequest.setNetworkParams(addSharedAndExternal(userInput, l3Network));
-
- createNetworkRequest = setFlowFlags(createNetworkRequest, orchestrationContext);
-
- createNetworkRequest.setMsoRequest(createMsoRequest(requestContext, serviceInstance));
-
- String messageId = getRandomUuid();
- createNetworkRequest.setMessageId(messageId);
- createNetworkRequest.setNotificationUrl(createCallbackUrl("NetworkAResponse", messageId));
-
- return createNetworkRequest;
- }
-
- public DeleteNetworkRequest deleteNetworkRequestMapper(RequestContext requestContext, CloudRegion cloudRegion, ServiceInstance serviceInstance, L3Network l3Network) throws UnsupportedEncodingException {
- DeleteNetworkRequest deleteNetworkRequest = new DeleteNetworkRequest();
-
- deleteNetworkRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
-
- String messageId = getRandomUuid();
- deleteNetworkRequest.setMessageId(messageId);
-
- ModelInfoNetwork modelInfoNetwork = l3Network.getModelInfoNetwork();
- if (modelInfoNetwork != null){
- deleteNetworkRequest.setModelCustomizationUuid(modelInfoNetwork.getModelCustomizationUUID());
- }
-
- deleteNetworkRequest.setMsoRequest(createMsoRequest(requestContext, serviceInstance));
- deleteNetworkRequest.setNetworkId(l3Network.getNetworkId());
- if (!StringUtils.isEmpty(l3Network.getHeatStackId())){
- deleteNetworkRequest.setNetworkStackId(l3Network.getHeatStackId());
- }
- else {
- deleteNetworkRequest.setNetworkStackId(l3Network.getNetworkName());
- }
- deleteNetworkRequest.setNetworkType(l3Network.getNetworkType());
- deleteNetworkRequest.setSkipAAI(true);
- deleteNetworkRequest.setTenantId(cloudRegion.getTenantId());
-
- deleteNetworkRequest.setNotificationUrl(createCallbackUrl("NetworkAResponse", messageId));
-
- return deleteNetworkRequest;
- }
-
- /**
- * Access method to build Rollback Network Request
- * @return
- * @throws UnsupportedEncodingException
- */
- public RollbackNetworkRequest createNetworkRollbackRequestMapper(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network, Map<String, String> userInput, String cloudRegionPo, CreateNetworkResponse createNetworkResponse) throws UnsupportedEncodingException {
- RollbackNetworkRequest rollbackNetworkRequest = new RollbackNetworkRequest();
-
- rollbackNetworkRequest = setCommonRollbackRequestFields(rollbackNetworkRequest, requestContext);
-
- NetworkRollback networkRollback = buildNetworkRollback(l3Network, cloudRegion, cloudRegionPo, createNetworkResponse);
- rollbackNetworkRequest.setNetworkRollback(networkRollback);
-
- return rollbackNetworkRequest;
- }
-
- public UpdateNetworkRequest createNetworkUpdateRequestMapper(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network, Map<String, String> userInput, Customer customer) throws UnsupportedEncodingException {
- UpdateNetworkRequest updateNetworkRequest = new UpdateNetworkRequest();
-
- updateNetworkRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
- updateNetworkRequest.setTenantId(cloudRegion.getTenantId());
- updateNetworkRequest.setNetworkId(l3Network.getNetworkId());
- updateNetworkRequest.setNetworkStackId(l3Network.getHeatStackId());
- updateNetworkRequest.setNetworkName(l3Network.getNetworkName());
- updateNetworkRequest.setNetworkType(l3Network.getModelInfoNetwork().getNetworkType());
- updateNetworkRequest.setNetworkTypeVersion(l3Network.getModelInfoNetwork().getModelVersion());
- updateNetworkRequest.setModelCustomizationUuid(l3Network.getModelInfoNetwork().getModelCustomizationUUID());
- updateNetworkRequest.setSubnets(buildOpenstackSubnetList(l3Network));
- updateNetworkRequest.setProviderVlanNetwork(buildProviderVlanNetwork(l3Network));
- updateNetworkRequest.setContrailNetwork(buildContrailNetwork(l3Network, customer));
- updateNetworkRequest.setNetworkParams(addSharedAndExternal(userInput, l3Network));
- updateNetworkRequest.setMsoRequest(createMsoRequest(requestContext, serviceInstance));
-
- setFlowFlags(updateNetworkRequest, orchestrationContext);
-
- String messageId = getRandomUuid();
- updateNetworkRequest.setMessageId(messageId);
- updateNetworkRequest.setNotificationUrl(createCallbackUrl("NetworkAResponse", messageId));
-
- return updateNetworkRequest;
- }
-
- private RollbackNetworkRequest setCommonRollbackRequestFields(RollbackNetworkRequest request,RequestContext requestContext) throws UnsupportedEncodingException{
- request.setSkipAAI(true);
- String messageId = requestContext.getMsoRequestId();
- request.setMessageId(messageId);
- //request.setNotificationUrl(createCallbackUrl("NetworkAResponse", messageId));
- return request;
- }
-
- private NetworkRollback buildNetworkRollback(L3Network l3Network, CloudRegion cloudRegion, String cloudRegionPo, CreateNetworkResponse createNetworkResponse){
- NetworkRollback networkRollback = new NetworkRollback();
- networkRollback.setNetworkId(l3Network.getNetworkId());
- networkRollback.setNeutronNetworkId(createNetworkResponse.getMessageId());
- networkRollback.setNetworkStackId(createNetworkResponse.getNetworkStackId());
- networkRollback.setTenantId(cloudRegion.getTenantId());
- networkRollback.setCloudId(cloudRegionPo);
- networkRollback.setNetworkType(l3Network.getNetworkType());
- ModelInfoNetwork modelInfoNetwork = l3Network.getModelInfoNetwork();
- if (modelInfoNetwork != null){
- networkRollback.setModelCustomizationUuid(modelInfoNetwork.getModelCustomizationUUID());
- }
- //rollback will only be called when network was actually created
- networkRollback.setNetworkCreated(createNetworkResponse.getNetworkCreated());
- //TODO confirm below not required for create rollback
- //NetworkName
- //PhysicalNetwork
- //Vlans
- //msoRequest
- return networkRollback;
- }
-
- public MsoRequest createMsoRequest(RequestContext requestContext, ServiceInstance serviceInstance) {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId(requestContext.getMsoRequestId());
- msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- return msoRequest;
- }
-
- protected String getRandomUuid() {
- return UUID.randomUUID().toString();
- }
-
- protected String createCallbackUrl(String messageType, String correlator) throws UnsupportedEncodingException {
- String endpoint = this.getEndpoint();
-
- while (endpoint.endsWith("/")) {
- endpoint = endpoint.substring(0, endpoint.length()-1);
- }
- return endpoint + "/" + UriUtils.encodePathSegment(messageType, "UTF-8") + "/" + UriUtils.encodePathSegment(correlator, "UTF-8");
- }
-
- protected String getEndpoint() {
- return UrnPropertiesReader.getVariable("mso.workflow.message.endpoint");
- }
- /**
- * Use BB L3Network object to build subnets list of type org.onap.so.openstack.beans.Subnet
- * @param L3Network
- * @return List<org.onap.so.openstack.beans.Subnet>
- */
- private List<Subnet> buildOpenstackSubnetList(L3Network l3Network){
-
- List<org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet> subnets = l3Network.getSubnets();
- List<org.onap.so.openstack.beans.Subnet> subnetList = new ArrayList<org.onap.so.openstack.beans.Subnet>();
- //create mapper from onap Subnet to openstack bean Subnet
- if(modelMapper.getTypeMap(org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet.class, org.onap.so.openstack.beans.Subnet.class) == null) {
- PropertyMap<org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet, org.onap.so.openstack.beans.Subnet> personMap = new PropertyMap<org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet, org.onap.so.openstack.beans.Subnet>() {
- protected void configure() {
- map().setSubnetName(source.getSubnetName());
- map(source.getSubnetId(), destination.getSubnetId());
- map(source.getNeutronSubnetId(), destination.getNeutronId());
- map(source.getGatewayAddress(), destination.getGatewayIp());
- map(source.getIpVersion(), destination.getIpVersion());
- map(source.isDhcpEnabled(), destination.getEnableDHCP());
- map(source.getSubnetSequence(), destination.getSubnetSequence());
- }
- };
- modelMapper.addMappings(personMap);
- }
-
- for (org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet subnet : subnets) {
- org.onap.so.openstack.beans.Subnet openstackSubnet = modelMapper.map(subnet, org.onap.so.openstack.beans.Subnet.class);
- //update cidr value
- if (subnet.getNetworkStartAddress() != null && subnet.getCidrMask() != null)
- openstackSubnet.setCidr(subnet.getNetworkStartAddress().concat(FORWARD_SLASH).concat(subnet.getCidrMask()));
- List<org.onap.so.bpmn.servicedecomposition.bbobjects.HostRoute> hostRouteList = subnet.getHostRoutes();
- List<org.onap.so.openstack.beans.HostRoute> openstackHostRouteList = new ArrayList<>();
- org.onap.so.openstack.beans.HostRoute openstackHostRoute = new org.onap.so.openstack.beans.HostRoute();
- //TODO only 2 fields available on openstack object. Confirm it is sufficient or add as needed
- for (org.onap.so.bpmn.servicedecomposition.bbobjects.HostRoute hostRoute : hostRouteList) {
- openstackHostRoute.setNextHop(hostRoute.getNextHop());
- openstackHostRoute.setPrefix(hostRoute.getRoutePrefix());
- //add host route to the list
- openstackHostRouteList.add(openstackHostRoute);
- }
- if (subnet.getDhcpStart() != null && !subnet.getDhcpStart().equals("")) {
- org.onap.so.openstack.beans.Pool openstackAllocationPool = new org.onap.so.openstack.beans.Pool();
- openstackAllocationPool.setStart(subnet.getDhcpStart());
- openstackAllocationPool.setEnd(subnet.getDhcpEnd());
- List<org.onap.so.openstack.beans.Pool> allocationPools = new ArrayList<>();
- allocationPools.add(openstackAllocationPool);
- openstackSubnet.setAllocationPools(allocationPools);
- }
- openstackSubnet.setHostRoutes(openstackHostRouteList);
- //add subnet to the list
- subnetList.add(openstackSubnet);
- }
- return subnetList;
- }
-
- private ProviderVlanNetwork buildProviderVlanNetwork(L3Network l3Network){
- ProviderVlanNetwork providerVlanNetwork = new ProviderVlanNetwork();
- providerVlanNetwork.setPhysicalNetworkName(l3Network.getPhysicalNetworkName());
- List<Integer> vlans = new ArrayList<Integer>();
- List<org.onap.so.bpmn.servicedecomposition.bbobjects.SegmentationAssignment> segmentationAssignments = l3Network.getSegmentationAssignments();
- for (org.onap.so.bpmn.servicedecomposition.bbobjects.SegmentationAssignment assignment : segmentationAssignments) {
- vlans.add(Integer.valueOf(assignment.getSegmentationId()));
- }
- providerVlanNetwork.setVlans(vlans);
- return providerVlanNetwork;
- }
-
- private ContrailNetwork buildContrailNetwork(L3Network l3Network, Customer customer){
- ContrailNetwork contrailNetwork = new ContrailNetwork();
- contrailNetwork.setExternal(Optional.ofNullable(l3Network.isIsExternalNetwork()).orElse(false).toString());
- contrailNetwork.setShared(Optional.ofNullable(l3Network.isIsSharedNetwork()).orElse(false).toString());
- contrailNetwork.setPolicyFqdns(buildPolicyFqdns(l3Network.getNetworkPolicies()));
- contrailNetwork.setRouteTableFqdns(buildRouteTableFqdns(l3Network.getContrailNetworkRouteTableReferences()));
- if(customer!= null)
- contrailNetwork.setRouteTargets(buildRouteTargets(customer.getVpnBindings()));
- //PolicyFqdns(policyFqdns); --- is set in getAAINetworkPolicy
- //RouteTableFqdns(routeTableFqdns); --- is set in getAAINetworkTableRef
- //RouteTargets(routeTargets); --- is set in getAAINetworkVpnBinding
- return contrailNetwork;
- }
-
- private List<String> buildPolicyFqdns(List<NetworkPolicy> networkPolicies) {
- List<String> policyFqdns = new ArrayList<>();
- for(NetworkPolicy networkPolicy : networkPolicies) {
- policyFqdns.add(networkPolicy.getNetworkPolicyFqdn());
- }
- return policyFqdns;
- }
-
- private List<String> buildRouteTableFqdns(List<RouteTableReference> contrailNetworkRouteTableReferences) {
- List<String> routeTableFqdns = new ArrayList<>();
- for(RouteTableReference routeTableReference : contrailNetworkRouteTableReferences) {
- routeTableFqdns.add(routeTableReference.getRouteTableReferenceFqdn());
- }
- return routeTableFqdns;
- }
-
- private List<RouteTarget> buildRouteTargets(List<VpnBinding> vpnBindings) {
- if(modelMapper.getTypeMap(org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget.class, RouteTarget.class) == null) {
- modelMapper.addMappings(new PropertyMap<org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget, RouteTarget>() {
- @Override
- protected void configure() {
- map().setRouteTarget(source.getGlobalRouteTarget());
- map().setRouteTargetRole(source.getRouteTargetRole());
- }
- });
- }
-
- List<RouteTarget> routeTargets = new ArrayList<>();
- for(VpnBinding vpnBinding : vpnBindings) {
- for(org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget routeTarget : vpnBinding.getRouteTargets()) {
- routeTargets.add(modelMapper.map(routeTarget, RouteTarget.class));
- }
- }
- return routeTargets;
- }
-
- private CreateNetworkRequest setFlowFlags(CreateNetworkRequest createNetworkRequest, OrchestrationContext orchestrationContext){
- //TODO confirm flag value
- createNetworkRequest.setSkipAAI(true);
- createNetworkRequest.setBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
- //TODO confirm value - false by default
- createNetworkRequest.setFailIfExists(true);
- //NetworkTechnology(NetworkTechnology.NEUTRON); NOOP - default
- return createNetworkRequest;
- }
-
- private void setFlowFlags(UpdateNetworkRequest updateNetworkRequest, OrchestrationContext orchestrationContext){
- updateNetworkRequest.setSkipAAI(true);
- updateNetworkRequest.setBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
- //NetworkTechnology(NetworkTechnology.NEUTRON); NOOP - default
- }
-
- private Map<String, String> addSharedAndExternal(Map<String, String> userInput, L3Network l3Network) {
- if (userInput == null)
- userInput = new HashMap<String, String>();
- if (!userInput.containsKey("shared")) {
- userInput.put("shared", Optional.ofNullable(l3Network.isIsSharedNetwork()).orElse(false).toString());
- }
- if (!userInput.containsKey("external")) {
- userInput.put("external", Optional.ofNullable(l3Network.isIsExternalNetwork()).orElse(false).toString());
- }
- return userInput;
- }
+ private static final ModelMapper modelMapper = new ModelMapper();
+ private static String FORWARD_SLASH = "/";
+ private static final Logger logger = LoggerFactory.getLogger(NetworkAdapterObjectMapper.class);
+
+ public CreateNetworkRequest createNetworkRequestMapper(RequestContext requestContext, CloudRegion cloudRegion,
+ OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network,
+ Map<String, String> userInput, String cloudRegionPo, Customer customer)
+ throws UnsupportedEncodingException {
+ CreateNetworkRequest createNetworkRequest = new CreateNetworkRequest();
+
+ // set cloudSiteId as determined for cloud region PO instead of cloudRegion.getLcpCloudRegionId()
+ createNetworkRequest.setCloudSiteId(cloudRegionPo);
+ createNetworkRequest.setTenantId(cloudRegion.getTenantId());
+ createNetworkRequest.setNetworkId(l3Network.getNetworkId());
+ createNetworkRequest.setNetworkName(l3Network.getNetworkName());
+ // TODO fields not available
+ createNetworkRequest.setNetworkType(l3Network.getNetworkType());
+ // createNetworkRequest.setNetworkTypeVersion(serviceInstance.getModelInfoServiceInstance().getModelVersion());
+ ModelInfoNetwork modelInfoNetwork = l3Network.getModelInfoNetwork();
+ if (modelInfoNetwork != null) {
+ createNetworkRequest.setModelCustomizationUuid(modelInfoNetwork.getModelCustomizationUUID());
+ }
+
+ // build and set Subnet list
+ createNetworkRequest.setSubnets(buildOpenstackSubnetList(l3Network));
+
+ // build and set provider Vlan Network
+ ProviderVlanNetwork providerVlanNetwork = buildProviderVlanNetwork(l3Network);
+ createNetworkRequest.setProviderVlanNetwork(providerVlanNetwork);
+ String networkTechnology = l3Network.getModelInfoNetwork().getNetworkTechnology();
+ if (networkTechnology == null) {
+ networkTechnology = l3Network.getNetworkTechnology();
+ logger.warn("NetworkTechnology was null in CatalogDB. Using field from AAI: " + networkTechnology);
+ }
+ if (networkTechnology != null) {
+ createNetworkRequest.setNetworkTechnology(networkTechnology.toUpperCase());
+ if (createNetworkRequest.getNetworkTechnology().contains("CONTRAIL")) {
+ createNetworkRequest.setContrailRequest(true);
+ }
+ }
+
+ // build and set Contrail Network
+ ContrailNetwork contrailNetwork = buildContrailNetwork(l3Network, customer);
+ createNetworkRequest.setContrailNetwork(contrailNetwork);
+
+ // set Network Parameters from VID request, add "shared" and "external" to this map
+ createNetworkRequest.setNetworkParams(addSharedAndExternal(userInput, l3Network));
+
+ createNetworkRequest = setFlowFlags(createNetworkRequest, orchestrationContext);
+
+ createNetworkRequest.setMsoRequest(createMsoRequest(requestContext, serviceInstance));
+
+ String messageId = getRandomUuid();
+ createNetworkRequest.setMessageId(messageId);
+ createNetworkRequest.setNotificationUrl(createCallbackUrl("NetworkAResponse", messageId));
+
+ return createNetworkRequest;
+ }
+
+ public DeleteNetworkRequest deleteNetworkRequestMapper(RequestContext requestContext, CloudRegion cloudRegion,
+ ServiceInstance serviceInstance, L3Network l3Network) throws UnsupportedEncodingException {
+ DeleteNetworkRequest deleteNetworkRequest = new DeleteNetworkRequest();
+
+ deleteNetworkRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+
+ String messageId = getRandomUuid();
+ deleteNetworkRequest.setMessageId(messageId);
+
+ ModelInfoNetwork modelInfoNetwork = l3Network.getModelInfoNetwork();
+ if (modelInfoNetwork != null) {
+ deleteNetworkRequest.setModelCustomizationUuid(modelInfoNetwork.getModelCustomizationUUID());
+ }
+
+ deleteNetworkRequest.setMsoRequest(createMsoRequest(requestContext, serviceInstance));
+ deleteNetworkRequest.setNetworkId(l3Network.getNetworkId());
+ if (!StringUtils.isEmpty(l3Network.getHeatStackId())) {
+ deleteNetworkRequest.setNetworkStackId(l3Network.getHeatStackId());
+ } else {
+ deleteNetworkRequest.setNetworkStackId(l3Network.getNetworkName());
+ }
+ deleteNetworkRequest.setNetworkType(l3Network.getNetworkType());
+ deleteNetworkRequest.setSkipAAI(true);
+ deleteNetworkRequest.setTenantId(cloudRegion.getTenantId());
+
+ deleteNetworkRequest.setNotificationUrl(createCallbackUrl("NetworkAResponse", messageId));
+
+ return deleteNetworkRequest;
+ }
+
+ /**
+ * Access method to build Rollback Network Request
+ *
+ * @return
+ * @throws UnsupportedEncodingException
+ */
+ public RollbackNetworkRequest createNetworkRollbackRequestMapper(RequestContext requestContext,
+ CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance,
+ L3Network l3Network, Map<String, String> userInput, String cloudRegionPo,
+ CreateNetworkResponse createNetworkResponse) throws UnsupportedEncodingException {
+ RollbackNetworkRequest rollbackNetworkRequest = new RollbackNetworkRequest();
+
+ rollbackNetworkRequest = setCommonRollbackRequestFields(rollbackNetworkRequest, requestContext);
+
+ NetworkRollback networkRollback =
+ buildNetworkRollback(l3Network, cloudRegion, cloudRegionPo, createNetworkResponse);
+ rollbackNetworkRequest.setNetworkRollback(networkRollback);
+
+ return rollbackNetworkRequest;
+ }
+
+ public UpdateNetworkRequest createNetworkUpdateRequestMapper(RequestContext requestContext, CloudRegion cloudRegion,
+ OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network,
+ Map<String, String> userInput, Customer customer) throws UnsupportedEncodingException {
+ UpdateNetworkRequest updateNetworkRequest = new UpdateNetworkRequest();
+
+ updateNetworkRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+ updateNetworkRequest.setTenantId(cloudRegion.getTenantId());
+ updateNetworkRequest.setNetworkId(l3Network.getNetworkId());
+ updateNetworkRequest.setNetworkStackId(l3Network.getHeatStackId());
+ updateNetworkRequest.setNetworkName(l3Network.getNetworkName());
+ updateNetworkRequest.setNetworkType(l3Network.getModelInfoNetwork().getNetworkType());
+ updateNetworkRequest.setNetworkTypeVersion(l3Network.getModelInfoNetwork().getModelVersion());
+ updateNetworkRequest.setModelCustomizationUuid(l3Network.getModelInfoNetwork().getModelCustomizationUUID());
+ updateNetworkRequest.setSubnets(buildOpenstackSubnetList(l3Network));
+ updateNetworkRequest.setProviderVlanNetwork(buildProviderVlanNetwork(l3Network));
+ updateNetworkRequest.setContrailNetwork(buildContrailNetwork(l3Network, customer));
+ updateNetworkRequest.setNetworkParams(addSharedAndExternal(userInput, l3Network));
+ updateNetworkRequest.setMsoRequest(createMsoRequest(requestContext, serviceInstance));
+
+ setFlowFlags(updateNetworkRequest, orchestrationContext);
+
+ String messageId = getRandomUuid();
+ updateNetworkRequest.setMessageId(messageId);
+ updateNetworkRequest.setNotificationUrl(createCallbackUrl("NetworkAResponse", messageId));
+
+ return updateNetworkRequest;
+ }
+
+ private RollbackNetworkRequest setCommonRollbackRequestFields(RollbackNetworkRequest request,
+ RequestContext requestContext) throws UnsupportedEncodingException {
+ request.setSkipAAI(true);
+ String messageId = requestContext.getMsoRequestId();
+ request.setMessageId(messageId);
+ // request.setNotificationUrl(createCallbackUrl("NetworkAResponse", messageId));
+ return request;
+ }
+
+ private NetworkRollback buildNetworkRollback(L3Network l3Network, CloudRegion cloudRegion, String cloudRegionPo,
+ CreateNetworkResponse createNetworkResponse) {
+ NetworkRollback networkRollback = new NetworkRollback();
+ networkRollback.setNetworkId(l3Network.getNetworkId());
+ networkRollback.setNeutronNetworkId(createNetworkResponse.getMessageId());
+ networkRollback.setNetworkStackId(createNetworkResponse.getNetworkStackId());
+ networkRollback.setTenantId(cloudRegion.getTenantId());
+ networkRollback.setCloudId(cloudRegionPo);
+ networkRollback.setNetworkType(l3Network.getNetworkType());
+ ModelInfoNetwork modelInfoNetwork = l3Network.getModelInfoNetwork();
+ if (modelInfoNetwork != null) {
+ networkRollback.setModelCustomizationUuid(modelInfoNetwork.getModelCustomizationUUID());
+ }
+ // rollback will only be called when network was actually created
+ networkRollback.setNetworkCreated(createNetworkResponse.getNetworkCreated());
+ // TODO confirm below not required for create rollback
+ // NetworkName
+ // PhysicalNetwork
+ // Vlans
+ // msoRequest
+ return networkRollback;
+ }
+
+ public MsoRequest createMsoRequest(RequestContext requestContext, ServiceInstance serviceInstance) {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId(requestContext.getMsoRequestId());
+ msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ return msoRequest;
+ }
+
+ protected String getRandomUuid() {
+ return UUID.randomUUID().toString();
+ }
+
+ protected String createCallbackUrl(String messageType, String correlator) throws UnsupportedEncodingException {
+ String endpoint = this.getEndpoint();
+
+ while (endpoint.endsWith("/")) {
+ endpoint = endpoint.substring(0, endpoint.length() - 1);
+ }
+ return endpoint + "/" + UriUtils.encodePathSegment(messageType, "UTF-8") + "/"
+ + UriUtils.encodePathSegment(correlator, "UTF-8");
+ }
+
+ protected String getEndpoint() {
+ return UrnPropertiesReader.getVariable("mso.workflow.message.endpoint");
+ }
+
+ /**
+ * Use BB L3Network object to build subnets list of type org.onap.so.openstack.beans.Subnet
+ *
+ * @param L3Network
+ * @return List<org.onap.so.openstack.beans.Subnet>
+ */
+ private List<Subnet> buildOpenstackSubnetList(L3Network l3Network) {
+
+ List<org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet> subnets = l3Network.getSubnets();
+ List<org.onap.so.openstack.beans.Subnet> subnetList = new ArrayList<org.onap.so.openstack.beans.Subnet>();
+ // create mapper from onap Subnet to openstack bean Subnet
+ if (modelMapper.getTypeMap(org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet.class,
+ org.onap.so.openstack.beans.Subnet.class) == null) {
+ PropertyMap<org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet, org.onap.so.openstack.beans.Subnet> personMap =
+ new PropertyMap<org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet, org.onap.so.openstack.beans.Subnet>() {
+ protected void configure() {
+ map().setSubnetName(source.getSubnetName());
+ map(source.getSubnetId(), destination.getSubnetId());
+ map(source.getNeutronSubnetId(), destination.getNeutronId());
+ map(source.getGatewayAddress(), destination.getGatewayIp());
+ map(source.getIpVersion(), destination.getIpVersion());
+ map(source.isDhcpEnabled(), destination.getEnableDHCP());
+ map(source.getSubnetSequence(), destination.getSubnetSequence());
+ }
+ };
+ modelMapper.addMappings(personMap);
+ }
+
+ for (org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet subnet : subnets) {
+ org.onap.so.openstack.beans.Subnet openstackSubnet =
+ modelMapper.map(subnet, org.onap.so.openstack.beans.Subnet.class);
+ // update cidr value
+ if (subnet.getNetworkStartAddress() != null && subnet.getCidrMask() != null)
+ openstackSubnet
+ .setCidr(subnet.getNetworkStartAddress().concat(FORWARD_SLASH).concat(subnet.getCidrMask()));
+ List<org.onap.so.bpmn.servicedecomposition.bbobjects.HostRoute> hostRouteList = subnet.getHostRoutes();
+ List<org.onap.so.openstack.beans.HostRoute> openstackHostRouteList = new ArrayList<>();
+ org.onap.so.openstack.beans.HostRoute openstackHostRoute = new org.onap.so.openstack.beans.HostRoute();
+ // TODO only 2 fields available on openstack object. Confirm it is sufficient or add as needed
+ for (org.onap.so.bpmn.servicedecomposition.bbobjects.HostRoute hostRoute : hostRouteList) {
+ openstackHostRoute.setNextHop(hostRoute.getNextHop());
+ openstackHostRoute.setPrefix(hostRoute.getRoutePrefix());
+ // add host route to the list
+ openstackHostRouteList.add(openstackHostRoute);
+ }
+ if (subnet.getDhcpStart() != null && !subnet.getDhcpStart().equals("")) {
+ org.onap.so.openstack.beans.Pool openstackAllocationPool = new org.onap.so.openstack.beans.Pool();
+ openstackAllocationPool.setStart(subnet.getDhcpStart());
+ openstackAllocationPool.setEnd(subnet.getDhcpEnd());
+ List<org.onap.so.openstack.beans.Pool> allocationPools = new ArrayList<>();
+ allocationPools.add(openstackAllocationPool);
+ openstackSubnet.setAllocationPools(allocationPools);
+ }
+ openstackSubnet.setHostRoutes(openstackHostRouteList);
+ // add subnet to the list
+ subnetList.add(openstackSubnet);
+ }
+ return subnetList;
+ }
+
+ private ProviderVlanNetwork buildProviderVlanNetwork(L3Network l3Network) {
+ ProviderVlanNetwork providerVlanNetwork = new ProviderVlanNetwork();
+ providerVlanNetwork.setPhysicalNetworkName(l3Network.getPhysicalNetworkName());
+ List<Integer> vlans = new ArrayList<Integer>();
+ List<org.onap.so.bpmn.servicedecomposition.bbobjects.SegmentationAssignment> segmentationAssignments =
+ l3Network.getSegmentationAssignments();
+ for (org.onap.so.bpmn.servicedecomposition.bbobjects.SegmentationAssignment assignment : segmentationAssignments) {
+ vlans.add(Integer.valueOf(assignment.getSegmentationId()));
+ }
+ providerVlanNetwork.setVlans(vlans);
+ return providerVlanNetwork;
+ }
+
+ private ContrailNetwork buildContrailNetwork(L3Network l3Network, Customer customer) {
+ ContrailNetwork contrailNetwork = new ContrailNetwork();
+ contrailNetwork.setExternal(Optional.ofNullable(l3Network.isIsExternalNetwork()).orElse(false).toString());
+ contrailNetwork.setShared(Optional.ofNullable(l3Network.isIsSharedNetwork()).orElse(false).toString());
+ contrailNetwork.setPolicyFqdns(buildPolicyFqdns(l3Network.getNetworkPolicies()));
+ contrailNetwork.setRouteTableFqdns(buildRouteTableFqdns(l3Network.getContrailNetworkRouteTableReferences()));
+ if (customer != null)
+ contrailNetwork.setRouteTargets(buildRouteTargets(customer.getVpnBindings()));
+ // PolicyFqdns(policyFqdns); --- is set in getAAINetworkPolicy
+ // RouteTableFqdns(routeTableFqdns); --- is set in getAAINetworkTableRef
+ // RouteTargets(routeTargets); --- is set in getAAINetworkVpnBinding
+ return contrailNetwork;
+ }
+
+ private List<String> buildPolicyFqdns(List<NetworkPolicy> networkPolicies) {
+ List<String> policyFqdns = new ArrayList<>();
+ for (NetworkPolicy networkPolicy : networkPolicies) {
+ policyFqdns.add(networkPolicy.getNetworkPolicyFqdn());
+ }
+ return policyFqdns;
+ }
+
+ private List<String> buildRouteTableFqdns(List<RouteTableReference> contrailNetworkRouteTableReferences) {
+ List<String> routeTableFqdns = new ArrayList<>();
+ for (RouteTableReference routeTableReference : contrailNetworkRouteTableReferences) {
+ routeTableFqdns.add(routeTableReference.getRouteTableReferenceFqdn());
+ }
+ return routeTableFqdns;
+ }
+
+ private List<RouteTarget> buildRouteTargets(List<VpnBinding> vpnBindings) {
+ if (modelMapper.getTypeMap(org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget.class,
+ RouteTarget.class) == null) {
+ modelMapper.addMappings(
+ new PropertyMap<org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget, RouteTarget>() {
+ @Override
+ protected void configure() {
+ map().setRouteTarget(source.getGlobalRouteTarget());
+ map().setRouteTargetRole(source.getRouteTargetRole());
+ }
+ });
+ }
+
+ List<RouteTarget> routeTargets = new ArrayList<>();
+ for (VpnBinding vpnBinding : vpnBindings) {
+ for (org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget routeTarget : vpnBinding
+ .getRouteTargets()) {
+ routeTargets.add(modelMapper.map(routeTarget, RouteTarget.class));
+ }
+ }
+ return routeTargets;
+ }
+
+ private CreateNetworkRequest setFlowFlags(CreateNetworkRequest createNetworkRequest,
+ OrchestrationContext orchestrationContext) {
+ // TODO confirm flag value
+ createNetworkRequest.setSkipAAI(true);
+ createNetworkRequest.setBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
+ // TODO confirm value - false by default
+ createNetworkRequest.setFailIfExists(true);
+ // NetworkTechnology(NetworkTechnology.NEUTRON); NOOP - default
+ return createNetworkRequest;
+ }
+
+ private void setFlowFlags(UpdateNetworkRequest updateNetworkRequest, OrchestrationContext orchestrationContext) {
+ updateNetworkRequest.setSkipAAI(true);
+ updateNetworkRequest.setBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
+ // NetworkTechnology(NetworkTechnology.NEUTRON); NOOP - default
+ }
+
+ private Map<String, String> addSharedAndExternal(Map<String, String> userInput, L3Network l3Network) {
+ if (userInput == null)
+ userInput = new HashMap<String, String>();
+ if (!userInput.containsKey("shared")) {
+ userInput.put("shared", Optional.ofNullable(l3Network.isIsSharedNetwork()).orElse(false).toString());
+ }
+ if (!userInput.containsKey("external")) {
+ userInput.put("external", Optional.ofNullable(l3Network.isIsExternalNetwork()).orElse(false).toString());
+ }
+ return userInput;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClient.java
index 13739faec2..2ab337037b 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClient.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClient.java
@@ -32,18 +32,18 @@ import org.onap.so.adapters.vnfrest.UpdateVfModuleResponse;
public interface VnfAdapterClient {
- CreateVfModuleResponse createVfModule(String aaiVnfId, CreateVfModuleRequest req) throws VnfAdapterClientException;
+ CreateVfModuleResponse createVfModule(String aaiVnfId, CreateVfModuleRequest req) throws VnfAdapterClientException;
- RollbackVfModuleResponse rollbackVfModule(String aaiVnfId, String aaiVfModuleId, RollbackVfModuleRequest req)
- throws VnfAdapterClientException;
+ RollbackVfModuleResponse rollbackVfModule(String aaiVnfId, String aaiVfModuleId, RollbackVfModuleRequest req)
+ throws VnfAdapterClientException;
- DeleteVfModuleResponse deleteVfModule(String aaiVnfId, String aaiVfModuleId, DeleteVfModuleRequest req)
- throws VnfAdapterClientException;
+ DeleteVfModuleResponse deleteVfModule(String aaiVnfId, String aaiVfModuleId, DeleteVfModuleRequest req)
+ throws VnfAdapterClientException;
- UpdateVfModuleResponse updateVfModule(String aaiVnfId, String aaiVfModuleId, UpdateVfModuleRequest req)
- throws VnfAdapterClientException;
+ UpdateVfModuleResponse updateVfModule(String aaiVnfId, String aaiVfModuleId, UpdateVfModuleRequest req)
+ throws VnfAdapterClientException;
- QueryVfModuleResponse queryVfModule(String aaiVnfId, String aaiVfModuleId, String cloudSiteId, String tenantId,
- String vfModuleName, boolean skipAAI, String requestId, String serviceInstanceId)
- throws VnfAdapterClientException;
+ QueryVfModuleResponse queryVfModule(String aaiVnfId, String aaiVfModuleId, String cloudSiteId, String tenantId,
+ String vfModuleName, boolean skipAAI, String requestId, String serviceInstanceId)
+ throws VnfAdapterClientException;
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClientException.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClientException.java
index b4ad9ef055..9e58fa349b 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClientException.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClientException.java
@@ -22,13 +22,13 @@ package org.onap.so.client.adapter.vnf;
public class VnfAdapterClientException extends Exception {
- /**
- *
- */
- private static final long serialVersionUID = -7154784472485852602L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -7154784472485852602L;
- public VnfAdapterClientException(String message) {
- super(message);
- }
+ public VnfAdapterClientException(String message) {
+ super(message);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClientImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClientImpl.java
index 7b9a8c5312..e24e86285c 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClientImpl.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterClientImpl.java
@@ -23,7 +23,6 @@ package org.onap.so.client.adapter.vnf;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.adapters.vnfrest.CreateVfModuleRequest;
import org.onap.so.adapters.vnfrest.CreateVfModuleResponse;
import org.onap.so.adapters.vnfrest.DeleteVfModuleRequest;
@@ -39,96 +38,96 @@ import org.springframework.stereotype.Component;
@Component
public class VnfAdapterClientImpl implements VnfAdapterClient {
- private static final String VF_MODULES = "/vf-modules/";
-
- private VnfAdapterRestProperties props;
-
- public VnfAdapterClientImpl() {
- this.props = new VnfAdapterRestProperties();
- }
-
- public VnfAdapterClientImpl(VnfAdapterRestProperties props) {
- this.props = props;
- }
-
- @Override
- public CreateVfModuleResponse createVfModule(String aaiVnfId, CreateVfModuleRequest req)
- throws VnfAdapterClientException {
- try {
- return new AdapterRestClient(this.props, this.getUri("/" + aaiVnfId + "/vf-modules").build()).post(req,
- CreateVfModuleResponse.class);
- } catch (InternalServerErrorException e) {
- throw new VnfAdapterClientException(e.getMessage());
- }
- }
-
- @Override
- public RollbackVfModuleResponse rollbackVfModule(String aaiVnfId, String aaiVfModuleId, RollbackVfModuleRequest req)
- throws VnfAdapterClientException {
- try {
- return new AdapterRestClient(this.props,
- this.getUri("/" + aaiVnfId + VF_MODULES + aaiVfModuleId + "/rollback").build()).delete(req,
- RollbackVfModuleResponse.class);
- } catch (InternalServerErrorException e) {
- throw new VnfAdapterClientException(e.getMessage());
- }
- }
-
- @Override
- public DeleteVfModuleResponse deleteVfModule(String aaiVnfId, String aaiVfModuleId, DeleteVfModuleRequest req)
- throws VnfAdapterClientException {
- try {
- return new AdapterRestClient(this.props, this.getUri("/" + aaiVnfId + VF_MODULES + aaiVfModuleId).build())
- .delete(req, DeleteVfModuleResponse.class);
- } catch (InternalServerErrorException e) {
- throw new VnfAdapterClientException(e.getMessage());
- }
- }
-
- @Override
- public UpdateVfModuleResponse updateVfModule(String aaiVnfId, String aaiVfModuleId, UpdateVfModuleRequest req)
- throws VnfAdapterClientException {
- try {
- return new AdapterRestClient(this.props, this.getUri("/" + aaiVnfId + VF_MODULES + aaiVfModuleId).build())
- .put(req, UpdateVfModuleResponse.class);
- } catch (InternalServerErrorException e) {
- throw new VnfAdapterClientException(e.getMessage());
- }
- }
-
- @Override
- public QueryVfModuleResponse queryVfModule(String aaiVnfId, String aaiVfModuleId, String cloudSiteId,
- String tenantId, String vfModuleName, boolean skipAAI, String requestId, String serviceInstanceId)
- throws VnfAdapterClientException {
- UriBuilder builder = this.getUri("/" + aaiVnfId + VF_MODULES + aaiVfModuleId);
- if (cloudSiteId != null) {
- builder.queryParam("cloudSiteId", cloudSiteId);
- }
- if (tenantId != null) {
- builder.queryParam("tenantId", tenantId);
- }
- if (vfModuleName != null) {
- builder.queryParam("vfModuleName", vfModuleName);
- }
-
- builder.queryParam("skipAAI", skipAAI);
-
- if (requestId != null) {
- builder.queryParam("msoRequest.requestId", requestId);
- }
- if (serviceInstanceId != null) {
- builder.queryParam("msoRequest.serviceInstanceId", serviceInstanceId);
- }
- try {
- return new AdapterRestClient(this.props, builder.build(), MediaType.APPLICATION_JSON,
- MediaType.APPLICATION_JSON).get(QueryVfModuleResponse.class).get();
- } catch (InternalServerErrorException e) {
- throw new VnfAdapterClientException(e.getMessage());
- }
- }
-
- public UriBuilder getUri(String path) {
- return UriBuilder.fromPath(path);
- }
+ private static final String VF_MODULES = "/vf-modules/";
+
+ private VnfAdapterRestProperties props;
+
+ public VnfAdapterClientImpl() {
+ this.props = new VnfAdapterRestProperties();
+ }
+
+ public VnfAdapterClientImpl(VnfAdapterRestProperties props) {
+ this.props = props;
+ }
+
+ @Override
+ public CreateVfModuleResponse createVfModule(String aaiVnfId, CreateVfModuleRequest req)
+ throws VnfAdapterClientException {
+ try {
+ return new AdapterRestClient(this.props, this.getUri("/" + aaiVnfId + "/vf-modules").build()).post(req,
+ CreateVfModuleResponse.class);
+ } catch (InternalServerErrorException e) {
+ throw new VnfAdapterClientException(e.getMessage());
+ }
+ }
+
+ @Override
+ public RollbackVfModuleResponse rollbackVfModule(String aaiVnfId, String aaiVfModuleId, RollbackVfModuleRequest req)
+ throws VnfAdapterClientException {
+ try {
+ return new AdapterRestClient(this.props,
+ this.getUri("/" + aaiVnfId + VF_MODULES + aaiVfModuleId + "/rollback").build()).delete(req,
+ RollbackVfModuleResponse.class);
+ } catch (InternalServerErrorException e) {
+ throw new VnfAdapterClientException(e.getMessage());
+ }
+ }
+
+ @Override
+ public DeleteVfModuleResponse deleteVfModule(String aaiVnfId, String aaiVfModuleId, DeleteVfModuleRequest req)
+ throws VnfAdapterClientException {
+ try {
+ return new AdapterRestClient(this.props, this.getUri("/" + aaiVnfId + VF_MODULES + aaiVfModuleId).build())
+ .delete(req, DeleteVfModuleResponse.class);
+ } catch (InternalServerErrorException e) {
+ throw new VnfAdapterClientException(e.getMessage());
+ }
+ }
+
+ @Override
+ public UpdateVfModuleResponse updateVfModule(String aaiVnfId, String aaiVfModuleId, UpdateVfModuleRequest req)
+ throws VnfAdapterClientException {
+ try {
+ return new AdapterRestClient(this.props, this.getUri("/" + aaiVnfId + VF_MODULES + aaiVfModuleId).build())
+ .put(req, UpdateVfModuleResponse.class);
+ } catch (InternalServerErrorException e) {
+ throw new VnfAdapterClientException(e.getMessage());
+ }
+ }
+
+ @Override
+ public QueryVfModuleResponse queryVfModule(String aaiVnfId, String aaiVfModuleId, String cloudSiteId,
+ String tenantId, String vfModuleName, boolean skipAAI, String requestId, String serviceInstanceId)
+ throws VnfAdapterClientException {
+ UriBuilder builder = this.getUri("/" + aaiVnfId + VF_MODULES + aaiVfModuleId);
+ if (cloudSiteId != null) {
+ builder.queryParam("cloudSiteId", cloudSiteId);
+ }
+ if (tenantId != null) {
+ builder.queryParam("tenantId", tenantId);
+ }
+ if (vfModuleName != null) {
+ builder.queryParam("vfModuleName", vfModuleName);
+ }
+
+ builder.queryParam("skipAAI", skipAAI);
+
+ if (requestId != null) {
+ builder.queryParam("msoRequest.requestId", requestId);
+ }
+ if (serviceInstanceId != null) {
+ builder.queryParam("msoRequest.serviceInstanceId", serviceInstanceId);
+ }
+ try {
+ return new AdapterRestClient(this.props, builder.build(), MediaType.APPLICATION_JSON,
+ MediaType.APPLICATION_JSON).get(QueryVfModuleResponse.class).get();
+ } catch (InternalServerErrorException e) {
+ throw new VnfAdapterClientException(e.getMessage());
+ }
+ }
+
+ public UriBuilder getUri(String path) {
+ return UriBuilder.fromPath(path);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterRestProperties.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterRestProperties.java
index 8302375c7e..51b1525a28 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterRestProperties.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfAdapterRestProperties.java
@@ -22,7 +22,6 @@ package org.onap.so.client.adapter.vnf;
import java.net.MalformedURLException;
import java.net.URL;
-
import org.onap.so.bpmn.core.UrnPropertiesReader;
import org.onap.so.client.adapter.rest.AdapterRestProperties;
@@ -30,25 +29,26 @@ import org.onap.so.client.adapter.rest.AdapterRestProperties;
public class VnfAdapterRestProperties implements AdapterRestProperties {
- public VnfAdapterRestProperties() {
- }
-
- @Override
- public String getAuth() {
- return UrnPropertiesReader.getVariable("mso.adapters.po.auth");
- }
- @Override
- public String getKey() {
- return UrnPropertiesReader.getVariable("mso.msoKey");
- }
- @Override
- public URL getEndpoint() throws MalformedURLException {
- return new URL(UrnPropertiesReader.getVariable("mso.adapters.vnf.rest.endpoint"));
- }
-
- @Override
- public String getSystemName() {
- return "MSO";
- }
+ public VnfAdapterRestProperties() {}
+
+ @Override
+ public String getAuth() {
+ return UrnPropertiesReader.getVariable("mso.adapters.po.auth");
+ }
+
+ @Override
+ public String getKey() {
+ return UrnPropertiesReader.getVariable("mso.msoKey");
+ }
+
+ @Override
+ public URL getEndpoint() throws MalformedURLException {
+ return new URL(UrnPropertiesReader.getVariable("mso.adapters.vnf.rest.endpoint"));
+ }
+
+ @Override
+ public String getSystemName() {
+ return "MSO";
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClient.java
index 0626efbd03..f4e4ce8cb1 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClient.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClient.java
@@ -31,18 +31,18 @@ import org.onap.so.adapters.vnfrest.UpdateVolumeGroupRequest;
import org.onap.so.adapters.vnfrest.UpdateVolumeGroupResponse;
public interface VnfVolumeAdapterClient {
- CreateVolumeGroupResponse createVNFVolumes(CreateVolumeGroupRequest req) throws VnfAdapterClientException;
+ CreateVolumeGroupResponse createVNFVolumes(CreateVolumeGroupRequest req) throws VnfAdapterClientException;
- DeleteVolumeGroupResponse deleteVNFVolumes(String aaiVolumeGroupId, DeleteVolumeGroupRequest req)
- throws VnfAdapterClientException;
+ DeleteVolumeGroupResponse deleteVNFVolumes(String aaiVolumeGroupId, DeleteVolumeGroupRequest req)
+ throws VnfAdapterClientException;
- RollbackVolumeGroupResponse rollbackVNFVolumes(String aaiVolumeGroupId, RollbackVolumeGroupRequest req)
- throws VnfAdapterClientException;
+ RollbackVolumeGroupResponse rollbackVNFVolumes(String aaiVolumeGroupId, RollbackVolumeGroupRequest req)
+ throws VnfAdapterClientException;
- UpdateVolumeGroupResponse updateVNFVolumes(String aaiVolumeGroupId, UpdateVolumeGroupRequest req)
- throws VnfAdapterClientException;
+ UpdateVolumeGroupResponse updateVNFVolumes(String aaiVolumeGroupId, UpdateVolumeGroupRequest req)
+ throws VnfAdapterClientException;
- QueryVolumeGroupResponse queryVNFVolumes(String aaiVolumeGroupId, String cloudSiteId, String tenantId,
- String volumeGroupStackId, Boolean skipAAI, String requestId, String serviceInstanceId)
- throws VnfAdapterClientException;
+ QueryVolumeGroupResponse queryVNFVolumes(String aaiVolumeGroupId, String cloudSiteId, String tenantId,
+ String volumeGroupStackId, Boolean skipAAI, String requestId, String serviceInstanceId)
+ throws VnfAdapterClientException;
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientImpl.java
index 0e0fd3bb5d..2af4d5f1fa 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientImpl.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientImpl.java
@@ -23,7 +23,6 @@ package org.onap.so.client.adapter.vnf;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest;
import org.onap.so.adapters.vnfrest.CreateVolumeGroupResponse;
import org.onap.so.adapters.vnfrest.DeleteVolumeGroupRequest;
@@ -40,81 +39,81 @@ import org.springframework.stereotype.Component;
@Component
public class VnfVolumeAdapterClientImpl implements VnfVolumeAdapterClient {
- private final VnfVolumeAdapterRestProperties props;
+ private final VnfVolumeAdapterRestProperties props;
- public VnfVolumeAdapterClientImpl() {
- this.props = new VnfVolumeAdapterRestProperties();
- }
+ public VnfVolumeAdapterClientImpl() {
+ this.props = new VnfVolumeAdapterRestProperties();
+ }
- @Override
- public CreateVolumeGroupResponse createVNFVolumes(CreateVolumeGroupRequest req) throws VnfAdapterClientException {
- try {
- return this.getAdapterRestClient("").post(req, CreateVolumeGroupResponse.class);
- } catch (InternalServerErrorException e) {
- throw new VnfAdapterClientException(e.getMessage());
- }
- }
+ @Override
+ public CreateVolumeGroupResponse createVNFVolumes(CreateVolumeGroupRequest req) throws VnfAdapterClientException {
+ try {
+ return this.getAdapterRestClient("").post(req, CreateVolumeGroupResponse.class);
+ } catch (InternalServerErrorException e) {
+ throw new VnfAdapterClientException(e.getMessage());
+ }
+ }
- @Override
- public DeleteVolumeGroupResponse deleteVNFVolumes(String aaiVolumeGroupId, DeleteVolumeGroupRequest req)
- throws VnfAdapterClientException {
- try {
- return this.getAdapterRestClient("/" + aaiVolumeGroupId).delete(req, DeleteVolumeGroupResponse.class);
- } catch (InternalServerErrorException e) {
- throw new VnfAdapterClientException(e.getMessage());
- }
- }
+ @Override
+ public DeleteVolumeGroupResponse deleteVNFVolumes(String aaiVolumeGroupId, DeleteVolumeGroupRequest req)
+ throws VnfAdapterClientException {
+ try {
+ return this.getAdapterRestClient("/" + aaiVolumeGroupId).delete(req, DeleteVolumeGroupResponse.class);
+ } catch (InternalServerErrorException e) {
+ throw new VnfAdapterClientException(e.getMessage());
+ }
+ }
- @Override
- public RollbackVolumeGroupResponse rollbackVNFVolumes(String aaiVolumeGroupId, RollbackVolumeGroupRequest req)
- throws VnfAdapterClientException {
- try {
- return this.getAdapterRestClient("/" + aaiVolumeGroupId + "/rollback").delete(req,
- RollbackVolumeGroupResponse.class);
- } catch (InternalServerErrorException e) {
- throw new VnfAdapterClientException(e.getMessage());
- }
- }
+ @Override
+ public RollbackVolumeGroupResponse rollbackVNFVolumes(String aaiVolumeGroupId, RollbackVolumeGroupRequest req)
+ throws VnfAdapterClientException {
+ try {
+ return this.getAdapterRestClient("/" + aaiVolumeGroupId + "/rollback").delete(req,
+ RollbackVolumeGroupResponse.class);
+ } catch (InternalServerErrorException e) {
+ throw new VnfAdapterClientException(e.getMessage());
+ }
+ }
- @Override
- public UpdateVolumeGroupResponse updateVNFVolumes(String aaiVolumeGroupId, UpdateVolumeGroupRequest req)
- throws VnfAdapterClientException {
- try {
- return this.getAdapterRestClient("/" + aaiVolumeGroupId).put(req, UpdateVolumeGroupResponse.class);
- } catch (InternalServerErrorException e) {
- throw new VnfAdapterClientException(e.getMessage());
- }
- }
+ @Override
+ public UpdateVolumeGroupResponse updateVNFVolumes(String aaiVolumeGroupId, UpdateVolumeGroupRequest req)
+ throws VnfAdapterClientException {
+ try {
+ return this.getAdapterRestClient("/" + aaiVolumeGroupId).put(req, UpdateVolumeGroupResponse.class);
+ } catch (InternalServerErrorException e) {
+ throw new VnfAdapterClientException(e.getMessage());
+ }
+ }
- @Override
- public QueryVolumeGroupResponse queryVNFVolumes(String aaiVolumeGroupId, String cloudSiteId, String tenantId,
- String volumeGroupStackId, Boolean skipAAI, String requestId, String serviceInstanceId)
- throws VnfAdapterClientException {
- try {
- String path = buildQueryPath(aaiVolumeGroupId, cloudSiteId, tenantId, volumeGroupStackId, skipAAI,
- requestId, serviceInstanceId);
- return this.getAdapterRestClient(path).get(QueryVolumeGroupResponse.class).get();
- } catch (InternalServerErrorException e) {
- throw new VnfAdapterClientException(e.getMessage());
- }
- }
+ @Override
+ public QueryVolumeGroupResponse queryVNFVolumes(String aaiVolumeGroupId, String cloudSiteId, String tenantId,
+ String volumeGroupStackId, Boolean skipAAI, String requestId, String serviceInstanceId)
+ throws VnfAdapterClientException {
+ try {
+ String path = buildQueryPath(aaiVolumeGroupId, cloudSiteId, tenantId, volumeGroupStackId, skipAAI,
+ requestId, serviceInstanceId);
+ return this.getAdapterRestClient(path).get(QueryVolumeGroupResponse.class).get();
+ } catch (InternalServerErrorException e) {
+ throw new VnfAdapterClientException(e.getMessage());
+ }
+ }
- protected String buildQueryPath(String aaiVolumeGroupId, String cloudSiteId, String tenantId,
- String volumeGroupStackId, Boolean skipAAI, String requestId, String serviceInstanceId) {
- javax.ws.rs.core.UriBuilder builder = this.getUri("/" + aaiVolumeGroupId);
- builder.queryParam("cloudSiteId", cloudSiteId).queryParam("tenantId", tenantId)
- .queryParam("volumeGroupStackId", volumeGroupStackId).queryParam("skipAAI", skipAAI)
- .queryParam("msoRequest.requestId", requestId)
- .queryParam("msoRequest.serviceInstanceId", serviceInstanceId);
- return builder.build().toString();
- }
+ protected String buildQueryPath(String aaiVolumeGroupId, String cloudSiteId, String tenantId,
+ String volumeGroupStackId, Boolean skipAAI, String requestId, String serviceInstanceId) {
+ javax.ws.rs.core.UriBuilder builder = this.getUri("/" + aaiVolumeGroupId);
+ builder.queryParam("cloudSiteId", cloudSiteId).queryParam("tenantId", tenantId)
+ .queryParam("volumeGroupStackId", volumeGroupStackId).queryParam("skipAAI", skipAAI)
+ .queryParam("msoRequest.requestId", requestId)
+ .queryParam("msoRequest.serviceInstanceId", serviceInstanceId);
+ return builder.build().toString();
+ }
- protected UriBuilder getUri(String path) {
- return UriBuilder.fromPath(path);
- }
+ protected UriBuilder getUri(String path) {
+ return UriBuilder.fromPath(path);
+ }
- protected RestClient getAdapterRestClient(String path) {
- return new AdapterRestClient(props, this.getUri(path).build(), MediaType.APPLICATION_JSON,
- MediaType.APPLICATION_JSON);
- }
+ protected RestClient getAdapterRestClient(String path) {
+ return new AdapterRestClient(props, this.getUri(path).build(), MediaType.APPLICATION_JSON,
+ MediaType.APPLICATION_JSON);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterRestProperties.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterRestProperties.java
index 80d064249b..1f774f5be7 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterRestProperties.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterRestProperties.java
@@ -22,36 +22,36 @@ package org.onap.so.client.adapter.vnf;
import java.net.MalformedURLException;
import java.net.URL;
-
import org.onap.so.bpmn.core.UrnPropertiesReader;
import org.onap.so.client.adapter.rest.AdapterRestProperties;
public class VnfVolumeAdapterRestProperties implements AdapterRestProperties {
- protected static final String authProp = "mso.adapters.po.auth";
- protected static final String keyProp = "mso.msoKey";
- protected static final String endpointProp = "mso.adapters.volume-groups.rest.endpoint";
-
- public VnfVolumeAdapterRestProperties() {
- }
-
- @Override
- public String getAuth() {
- return UrnPropertiesReader.getVariable(authProp);
- }
- @Override
- public String getKey() {
- return UrnPropertiesReader.getVariable(keyProp);
- }
- @Override
- public URL getEndpoint() throws MalformedURLException {
- return new URL(UrnPropertiesReader.getVariable(endpointProp));
- }
-
- @Override
- public String getSystemName() {
- return "MSO";
- }
+ protected static final String authProp = "mso.adapters.po.auth";
+ protected static final String keyProp = "mso.msoKey";
+ protected static final String endpointProp = "mso.adapters.volume-groups.rest.endpoint";
+
+ public VnfVolumeAdapterRestProperties() {}
+
+ @Override
+ public String getAuth() {
+ return UrnPropertiesReader.getVariable(authProp);
+ }
+
+ @Override
+ public String getKey() {
+ return UrnPropertiesReader.getVariable(keyProp);
+ }
+
+ @Override
+ public URL getEndpoint() throws MalformedURLException {
+ return new URL(UrnPropertiesReader.getVariable(endpointProp));
+ }
+
+ @Override
+ public String getSystemName() {
+ return "MSO";
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/AttributeNameValue.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/AttributeNameValue.java
index e93e216ea3..6daed56675 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/AttributeNameValue.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/AttributeNameValue.java
@@ -51,10 +51,7 @@ public class AttributeNameValue implements Serializable {
@Override
public String toString() {
- return new StringBuilder().append("{\"attribute_name\": \"")
- .append(attributeName.toString())
- .append("\", \"attribute_value\": \"")
- .append(attributeValue.toString())
- .append("\"}").toString();
+ return new StringBuilder().append("{\"attribute_name\": \"").append(attributeName.toString())
+ .append("\", \"attribute_value\": \"").append(attributeValue.toString()).append("\"}").toString();
}
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapper.java
index 2559087619..a78870afc4 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapper.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapper.java
@@ -26,9 +26,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import javax.annotation.PostConstruct;
-
import org.apache.commons.lang3.StringUtils;
import org.onap.sdnc.northbound.client.model.GenericResourceApiParam;
import org.onap.sdnc.northbound.client.model.GenericResourceApiParamParam;
@@ -46,7 +44,6 @@ import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
import org.onap.so.entity.MsoRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -54,129 +51,143 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class VnfAdapterObjectMapper {
- private ObjectMapper mapper = new ObjectMapper();
-
- @PostConstruct
- public void init () {
- mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
- }
-
- public CreateVolumeGroupRequest createVolumeGroupRequestMapper(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, GenericVnf genericVnf, VolumeGroup volumeGroup, String sdncVfModuleQueryResponse) throws JsonParseException, JsonMappingException, IOException {
- CreateVolumeGroupRequest createVolumeGroupRequest = new CreateVolumeGroupRequest();
-
- createVolumeGroupRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
- createVolumeGroupRequest.setTenantId(cloudRegion.getTenantId());
- createVolumeGroupRequest.setVolumeGroupId(volumeGroup.getVolumeGroupId());
- createVolumeGroupRequest.setVolumeGroupName(volumeGroup.getVolumeGroupName());
- createVolumeGroupRequest.setVnfType(genericVnf.getVnfType());
- createVolumeGroupRequest.setVnfVersion(serviceInstance.getModelInfoServiceInstance().getModelVersion());
- createVolumeGroupRequest.setVfModuleType(volumeGroup.getModelInfoVfModule().getModelName());
- createVolumeGroupRequest.setModelCustomizationUuid(volumeGroup.getModelInfoVfModule().getModelCustomizationUUID());
- createVolumeGroupRequest.setVolumeGroupParams(createVolumeGroupParams(requestContext,genericVnf, volumeGroup, sdncVfModuleQueryResponse));
-
- createVolumeGroupRequest.setSkipAAI(true);
- createVolumeGroupRequest.setSuppressBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
- createVolumeGroupRequest.setFailIfExists(true);
-
- createVolumeGroupRequest.setMsoRequest(createMsoRequest(requestContext, serviceInstance));
-
- String messageId = getRandomUuid();
- createVolumeGroupRequest.setMessageId(messageId);
- createVolumeGroupRequest.setNotificationUrl(createCallbackUrl("VNFAResponse", messageId));
-
- return createVolumeGroupRequest;
- }
-
- public DeleteVolumeGroupRequest deleteVolumeGroupRequestMapper(RequestContext requestContext, CloudRegion cloudRegion, ServiceInstance serviceInstance, VolumeGroup volumeGroup) throws IOException {
- DeleteVolumeGroupRequest deleteVolumeGroupRequest = new DeleteVolumeGroupRequest();
-
- deleteVolumeGroupRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
- deleteVolumeGroupRequest.setTenantId(cloudRegion.getTenantId());
- deleteVolumeGroupRequest.setVolumeGroupId(volumeGroup.getVolumeGroupId());
- if (!StringUtils.isEmpty(volumeGroup.getHeatStackId())){
- deleteVolumeGroupRequest.setVolumeGroupStackId(volumeGroup.getHeatStackId());
- } else
- {
- deleteVolumeGroupRequest.setVolumeGroupStackId(volumeGroup.getVolumeGroupName());
- }
-
- deleteVolumeGroupRequest.setSkipAAI(true);
- deleteVolumeGroupRequest.setMsoRequest(createMsoRequest(requestContext, serviceInstance));
-
- String messageId = getRandomUuid();
- deleteVolumeGroupRequest.setMessageId(messageId);
- deleteVolumeGroupRequest.setNotificationUrl(createCallbackUrl("VNFAResponse", messageId));
-
- return deleteVolumeGroupRequest;
- }
-
- public Map<String, Object> createVolumeGroupParams(RequestContext requestContext,GenericVnf genericVnf, VolumeGroup volumeGroup, String sdncVfModuleQueryResponse) throws JsonParseException, JsonMappingException, IOException {
- Map<String, Object> volumeGroupParams = new HashMap<>();
- final String USER_PARAM_NAME_KEY = "name";
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @PostConstruct
+ public void init() {
+ mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ }
+
+ public CreateVolumeGroupRequest createVolumeGroupRequestMapper(RequestContext requestContext,
+ CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance,
+ GenericVnf genericVnf, VolumeGroup volumeGroup, String sdncVfModuleQueryResponse)
+ throws JsonParseException, JsonMappingException, IOException {
+ CreateVolumeGroupRequest createVolumeGroupRequest = new CreateVolumeGroupRequest();
+
+ createVolumeGroupRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+ createVolumeGroupRequest.setTenantId(cloudRegion.getTenantId());
+ createVolumeGroupRequest.setVolumeGroupId(volumeGroup.getVolumeGroupId());
+ createVolumeGroupRequest.setVolumeGroupName(volumeGroup.getVolumeGroupName());
+ createVolumeGroupRequest.setVnfType(genericVnf.getVnfType());
+ createVolumeGroupRequest.setVnfVersion(serviceInstance.getModelInfoServiceInstance().getModelVersion());
+ createVolumeGroupRequest.setVfModuleType(volumeGroup.getModelInfoVfModule().getModelName());
+ createVolumeGroupRequest
+ .setModelCustomizationUuid(volumeGroup.getModelInfoVfModule().getModelCustomizationUUID());
+ createVolumeGroupRequest.setVolumeGroupParams(
+ createVolumeGroupParams(requestContext, genericVnf, volumeGroup, sdncVfModuleQueryResponse));
+
+ createVolumeGroupRequest.setSkipAAI(true);
+ createVolumeGroupRequest.setSuppressBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
+ createVolumeGroupRequest.setFailIfExists(true);
+
+ createVolumeGroupRequest.setMsoRequest(createMsoRequest(requestContext, serviceInstance));
+
+ String messageId = getRandomUuid();
+ createVolumeGroupRequest.setMessageId(messageId);
+ createVolumeGroupRequest.setNotificationUrl(createCallbackUrl("VNFAResponse", messageId));
+
+ return createVolumeGroupRequest;
+ }
+
+ public DeleteVolumeGroupRequest deleteVolumeGroupRequestMapper(RequestContext requestContext,
+ CloudRegion cloudRegion, ServiceInstance serviceInstance, VolumeGroup volumeGroup) throws IOException {
+ DeleteVolumeGroupRequest deleteVolumeGroupRequest = new DeleteVolumeGroupRequest();
+
+ deleteVolumeGroupRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+ deleteVolumeGroupRequest.setTenantId(cloudRegion.getTenantId());
+ deleteVolumeGroupRequest.setVolumeGroupId(volumeGroup.getVolumeGroupId());
+ if (!StringUtils.isEmpty(volumeGroup.getHeatStackId())) {
+ deleteVolumeGroupRequest.setVolumeGroupStackId(volumeGroup.getHeatStackId());
+ } else {
+ deleteVolumeGroupRequest.setVolumeGroupStackId(volumeGroup.getVolumeGroupName());
+ }
+
+ deleteVolumeGroupRequest.setSkipAAI(true);
+ deleteVolumeGroupRequest.setMsoRequest(createMsoRequest(requestContext, serviceInstance));
+
+ String messageId = getRandomUuid();
+ deleteVolumeGroupRequest.setMessageId(messageId);
+ deleteVolumeGroupRequest.setNotificationUrl(createCallbackUrl("VNFAResponse", messageId));
+
+ return deleteVolumeGroupRequest;
+ }
+
+ public Map<String, Object> createVolumeGroupParams(RequestContext requestContext, GenericVnf genericVnf,
+ VolumeGroup volumeGroup, String sdncVfModuleQueryResponse)
+ throws JsonParseException, JsonMappingException, IOException {
+ Map<String, Object> volumeGroupParams = new HashMap<>();
+ final String USER_PARAM_NAME_KEY = "name";
final String USER_PARAM_VALUE_KEY = "value";
- // sdncVfModuleQueryResponse will not be available in aLaCarte case
- if (sdncVfModuleQueryResponse != null) {
- GenericResourceApiVfModuleTopology vfModuleTop = mapper.readValue(sdncVfModuleQueryResponse, GenericResourceApiVfModuleTopology.class);
- GenericResourceApiVfmoduletopologyVfModuleTopology vfModuleTopology = vfModuleTop.getVfModuleTopology();
- buildParamsMapFromSdncParams(volumeGroupParams, vfModuleTopology.getVfModuleParameters());
- }
-
- if(null != requestContext.getRequestParameters() && null != requestContext.getRequestParameters().getUserParams()) {
+ // sdncVfModuleQueryResponse will not be available in aLaCarte case
+ if (sdncVfModuleQueryResponse != null) {
+ GenericResourceApiVfModuleTopology vfModuleTop =
+ mapper.readValue(sdncVfModuleQueryResponse, GenericResourceApiVfModuleTopology.class);
+ GenericResourceApiVfmoduletopologyVfModuleTopology vfModuleTopology = vfModuleTop.getVfModuleTopology();
+ buildParamsMapFromSdncParams(volumeGroupParams, vfModuleTopology.getVfModuleParameters());
+ }
+
+ if (null != requestContext.getRequestParameters()
+ && null != requestContext.getRequestParameters().getUserParams()) {
List<Map<String, Object>> userParams = requestContext.getRequestParameters().getUserParams();
for (Map<String, Object> userParamsMap : userParams) {
- if ( userParamsMap.containsKey(USER_PARAM_NAME_KEY) && (userParamsMap.get(USER_PARAM_NAME_KEY) instanceof String)
- && userParamsMap.containsKey(USER_PARAM_VALUE_KEY) && (userParamsMap.get(USER_PARAM_VALUE_KEY) instanceof String)) {
- volumeGroupParams.put((String) userParamsMap.get(USER_PARAM_NAME_KEY), (String) userParamsMap.get(USER_PARAM_VALUE_KEY));
+ if (userParamsMap.containsKey(USER_PARAM_NAME_KEY)
+ && (userParamsMap.get(USER_PARAM_NAME_KEY) instanceof String)
+ && userParamsMap.containsKey(USER_PARAM_VALUE_KEY)
+ && (userParamsMap.get(USER_PARAM_VALUE_KEY) instanceof String)) {
+ volumeGroupParams.put((String) userParamsMap.get(USER_PARAM_NAME_KEY),
+ (String) userParamsMap.get(USER_PARAM_VALUE_KEY));
}
}
}
- volumeGroupParams.put("vnf_id", genericVnf.getVnfId());
- volumeGroupParams.put("vnf_name", genericVnf.getVnfName());
- volumeGroupParams.put("vf_module_id", volumeGroup.getVolumeGroupId());
- volumeGroupParams.put("vf_module_name", volumeGroup.getVolumeGroupName());
-
- return volumeGroupParams;
- }
-
- public MsoRequest createMsoRequest(RequestContext requestContext, ServiceInstance serviceInstance) {
- MsoRequest msoRequest = new MsoRequest();
-
- msoRequest.setRequestId(requestContext.getMsoRequestId());
- msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
-
- return msoRequest;
- }
-
- private void buildParamsMapFromSdncParams(Map<String,Object> volumeGroupParams, GenericResourceApiParam sdncParameters) {
- if (sdncParameters != null) {
- List<GenericResourceApiParamParam> sdncParametersList = sdncParameters.getParam();
- if (sdncParametersList != null) {
- for (int i = 0; i < sdncParametersList.size(); i++) {
- GenericResourceApiParamParam param = sdncParametersList.get(i);
- String parameterName = param.getName();
- String parameterValue = param.getValue();
- volumeGroupParams.put(parameterName, parameterValue);
- }
- }
- }
- }
-
- protected String getRandomUuid() {
- return UUID.randomUUID().toString();
- }
-
- protected String createCallbackUrl(String messageType, String correlator) throws UnsupportedEncodingException {
- String endpoint = getProperty("mso.workflow.message.endpoint");
-
- while (endpoint.endsWith("/")) {
- endpoint = endpoint.substring(0, endpoint.length()-1);
- }
-
- return endpoint + "/" + UriUtils.encodePathSegment(messageType, "UTF-8") + "/" + UriUtils.encodePathSegment(correlator, "UTF-8");
- }
-
- protected String getProperty(String key) {
- return UrnPropertiesReader.getVariable(key);
- }
-
-} \ No newline at end of file
+ volumeGroupParams.put("vnf_id", genericVnf.getVnfId());
+ volumeGroupParams.put("vnf_name", genericVnf.getVnfName());
+ volumeGroupParams.put("vf_module_id", volumeGroup.getVolumeGroupId());
+ volumeGroupParams.put("vf_module_name", volumeGroup.getVolumeGroupName());
+
+ return volumeGroupParams;
+ }
+
+ public MsoRequest createMsoRequest(RequestContext requestContext, ServiceInstance serviceInstance) {
+ MsoRequest msoRequest = new MsoRequest();
+
+ msoRequest.setRequestId(requestContext.getMsoRequestId());
+ msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+
+ return msoRequest;
+ }
+
+ private void buildParamsMapFromSdncParams(Map<String, Object> volumeGroupParams,
+ GenericResourceApiParam sdncParameters) {
+ if (sdncParameters != null) {
+ List<GenericResourceApiParamParam> sdncParametersList = sdncParameters.getParam();
+ if (sdncParametersList != null) {
+ for (int i = 0; i < sdncParametersList.size(); i++) {
+ GenericResourceApiParamParam param = sdncParametersList.get(i);
+ String parameterName = param.getName();
+ String parameterValue = param.getValue();
+ volumeGroupParams.put(parameterName, parameterValue);
+ }
+ }
+ }
+ }
+
+ protected String getRandomUuid() {
+ return UUID.randomUUID().toString();
+ }
+
+ protected String createCallbackUrl(String messageType, String correlator) throws UnsupportedEncodingException {
+ String endpoint = getProperty("mso.workflow.message.endpoint");
+
+ while (endpoint.endsWith("/")) {
+ endpoint = endpoint.substring(0, endpoint.length() - 1);
+ }
+
+ return endpoint + "/" + UriUtils.encodePathSegment(messageType, "UTF-8") + "/"
+ + UriUtils.encodePathSegment(correlator, "UTF-8");
+ }
+
+ protected String getProperty(String key) {
+ return UrnPropertiesReader.getVariable(key);
+ }
+
+}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperUtils.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperUtils.java
index 6b2d64f170..269484eadf 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperUtils.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperUtils.java
@@ -22,7 +22,6 @@ package org.onap.so.client.adapter.vnf.mapper;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
-
import org.onap.so.bpmn.core.UrnPropertiesReader;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;
@@ -30,25 +29,25 @@ import org.springframework.web.util.UriUtils;
@Component("VnfAdapterObjectMapperUtils")
public class VnfAdapterObjectMapperUtils {
- public String getRandomUuid() {
- return UUID.randomUUID().toString();
- }
+ public String getRandomUuid() {
+ return UUID.randomUUID().toString();
+ }
- public String createCallbackUrl(String messageType, String correlator) throws UnsupportedEncodingException {
- String endpoint = getProperty("mso.workflow.message.endpoint");
- if (endpoint != null) {
- while (endpoint.endsWith("/")) {
- endpoint = endpoint.substring(0, endpoint.length() - 1);
- }
- }
+ public String createCallbackUrl(String messageType, String correlator) throws UnsupportedEncodingException {
+ String endpoint = getProperty("mso.workflow.message.endpoint");
+ if (endpoint != null) {
+ while (endpoint.endsWith("/")) {
+ endpoint = endpoint.substring(0, endpoint.length() - 1);
+ }
+ }
- return endpoint + "/" + UriUtils.encodePathSegment(messageType, "UTF-8") + "/"
- + UriUtils.encodePathSegment(correlator, "UTF-8");
- }
+ return endpoint + "/" + UriUtils.encodePathSegment(messageType, "UTF-8") + "/"
+ + UriUtils.encodePathSegment(correlator, "UTF-8");
+ }
- protected String getProperty(String key) {
+ protected String getProperty(String key) {
- return UrnPropertiesReader.getVariable(key);
- }
+ return UrnPropertiesReader.getVariable(key);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java
index dc113e5abc..94e95687db 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java
@@ -21,7 +21,6 @@
package org.onap.so.client.adapter.vnf.mapper;
import static java.util.Arrays.asList;
-
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
@@ -33,9 +32,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import javax.annotation.PostConstruct;
-
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang3.StringUtils;
import org.onap.sdnc.northbound.client.model.GenericResourceApiParam;
@@ -82,7 +79,6 @@ import org.onap.so.jsonpath.JsonPathUtil;
import org.onap.so.openstack.utils.MsoMulticloudUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -93,120 +89,128 @@ import com.google.common.base.Joiner;
@Component
public class VnfAdapterVfModuleObjectMapper {
- @Autowired
- protected VnfAdapterObjectMapperUtils vnfAdapterObjectMapperUtils;
- private static List<String> sdncResponseParamsToSkip = asList("vnf_id", "vf_module_id", "vnf_name", "vf_module_name");
-
- private ObjectMapper mapper = new ObjectMapper();
- private static final JsonPathUtil jsonPath = JsonPathUtil.getInstance();
- private static final String SUB_INT = "subint";
- private static final String SUBNET_ID = "_subnet_id";
- private static final String V6_SUBNET_ID = "_v6_subnet_id";
- private static final String PORT = "port";
- private static final String SUB_INT_COUNT = "_subintcount";
- private static final String VLAN_IDS = "_vlan_ids";
- private static final String NET_NAMES = "_net_names";
- private static final String NET_IDS = "_net_ids";
- private static final String IP = "_ip";
- private static final String V6_IP = "_v6_ip";
- private static final String FLOATING_IP = "_floating_ip";
- private static final String FLOATING_V6_IP = "_floating_v6_ip";
- private static final String UNDERSCORE = "_";
-
- @PostConstruct
- public void init () {
- mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
- }
-
- public CreateVfModuleRequest createVfModuleRequestMapper(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, GenericVnf genericVnf,
- VfModule vfModule, VolumeGroup volumeGroup, String sdncVnfQueryResponse, String sdncVfModuleQueryResponse) throws JsonParseException, JsonMappingException, IOException {
- CreateVfModuleRequest createVfModuleRequest = new CreateVfModuleRequest();
-
- createVfModuleRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
- createVfModuleRequest.setCloudOwner(cloudRegion.getCloudOwner());
- createVfModuleRequest.setTenantId(cloudRegion.getTenantId());
- createVfModuleRequest.setVfModuleId(vfModule.getVfModuleId());
- createVfModuleRequest.setVfModuleName(vfModule.getVfModuleName());
- createVfModuleRequest.setVnfId(genericVnf.getVnfId());
- createVfModuleRequest.setVnfType(genericVnf.getVnfType());
- createVfModuleRequest.setVnfVersion(serviceInstance.getModelInfoServiceInstance().getModelVersion());
- createVfModuleRequest.setVfModuleType(vfModule.getModelInfoVfModule().getModelName());
- createVfModuleRequest.setModelCustomizationUuid(vfModule.getModelInfoVfModule().getModelCustomizationUUID());
- if (volumeGroup != null) {
- createVfModuleRequest.setVolumeGroupId(volumeGroup.getVolumeGroupId());
- createVfModuleRequest.setVolumeGroupStackId(volumeGroup.getHeatStackId());
- }
- VfModule baseVfModule = getBaseVfModule(genericVnf);
- if (baseVfModule != null) {
- createVfModuleRequest.setBaseVfModuleId(baseVfModule.getVfModuleId());
- createVfModuleRequest.setBaseVfModuleStackId(baseVfModule.getHeatStackId());
- }
- createVfModuleRequest.setVfModuleParams(buildVfModuleParamsMap(requestContext, serviceInstance, genericVnf, vfModule, sdncVnfQueryResponse, sdncVfModuleQueryResponse));
-
- createVfModuleRequest.setSkipAAI(true);
- createVfModuleRequest.setBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
- createVfModuleRequest.setFailIfExists(true);
-
- MsoRequest msoRequest = buildMsoRequest(requestContext, serviceInstance);
- createVfModuleRequest.setMsoRequest(msoRequest);
-
- String messageId = vnfAdapterObjectMapperUtils.getRandomUuid();
- createVfModuleRequest.setMessageId(messageId);
- createVfModuleRequest.setNotificationUrl(vnfAdapterObjectMapperUtils.createCallbackUrl("VNFAResponse", messageId));
-
- return createVfModuleRequest;
- }
-
- private MsoRequest buildMsoRequest(RequestContext requestContext,ServiceInstance serviceInstance) {
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId(requestContext.getMsoRequestId());
- msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- return msoRequest;
- }
-
- private Map<String,Object> buildVfModuleParamsMap(RequestContext requestContext, ServiceInstance serviceInstance, GenericVnf genericVnf,
- VfModule vfModule, String sdncVnfQueryResponse, String sdncVfModuleQueryResponse) throws JsonParseException, JsonMappingException, IOException {
-
-
- GenericResourceApiVnfTopology vnfTop= mapper.readValue(sdncVnfQueryResponse, GenericResourceApiVnfTopology.class);
- GenericResourceApiVfModuleTopology vfModuleTop = mapper.readValue(sdncVfModuleQueryResponse, GenericResourceApiVfModuleTopology.class);
- GenericResourceApiVnftopologyVnfTopology vnfTopology = vnfTop.getVnfTopology();
- GenericResourceApiVfmoduletopologyVfModuleTopology vfModuleTopology = vfModuleTop.getVfModuleTopology();
- Map<String,Object> paramsMap = new HashMap<>();
-
- if( vfModuleTopology.getSdncGeneratedCloudResources()) {
- buildParamsMapFromVfModuleSdncResponse(paramsMap, vfModuleTopology, true);
- buildParamsMapFromVnfSdncResponse(paramsMap, vnfTopology, null, true);
- }
- else {
- Map<String,String> networkRoleMap = buildNetworkRoleMap(vfModuleTopology);
- buildParamsMapFromVfModuleSdncResponse(paramsMap, vfModuleTopology, false);
- buildParamsMapFromVnfSdncResponse(paramsMap, vnfTopology, networkRoleMap, false);
- }
-
- // build the sdnc_directives from paramsMap
- buildDirectivesParamFromMap(paramsMap, MsoMulticloudUtils.SDNC_DIRECTIVES, paramsMap);
- buildDirectivesParamFromMap(paramsMap, MsoMulticloudUtils.USER_DIRECTIVES, requestContext.getUserParams());
-
- buildMandatoryParamsMap(paramsMap, serviceInstance, genericVnf, vfModule);
-
- // Parameters received from the request should overwrite any parameters received from SDNC
- paramsMap.putAll(requestContext.getUserParams());
-
- if (vfModule.getCloudParams() != null) {
- paramsMap.putAll(vfModule.getCloudParams());
- }
- return paramsMap;
- }
-
- private void buildDirectivesParamFromMap(Map<String, Object> paramsMap, String directive, Map<String, Object> srcMap) {
+ @Autowired
+ protected VnfAdapterObjectMapperUtils vnfAdapterObjectMapperUtils;
+ private static List<String> sdncResponseParamsToSkip =
+ asList("vnf_id", "vf_module_id", "vnf_name", "vf_module_name");
+
+ private ObjectMapper mapper = new ObjectMapper();
+ private static final JsonPathUtil jsonPath = JsonPathUtil.getInstance();
+ private static final String SUB_INT = "subint";
+ private static final String SUBNET_ID = "_subnet_id";
+ private static final String V6_SUBNET_ID = "_v6_subnet_id";
+ private static final String PORT = "port";
+ private static final String SUB_INT_COUNT = "_subintcount";
+ private static final String VLAN_IDS = "_vlan_ids";
+ private static final String NET_NAMES = "_net_names";
+ private static final String NET_IDS = "_net_ids";
+ private static final String IP = "_ip";
+ private static final String V6_IP = "_v6_ip";
+ private static final String FLOATING_IP = "_floating_ip";
+ private static final String FLOATING_V6_IP = "_floating_v6_ip";
+ private static final String UNDERSCORE = "_";
+
+ @PostConstruct
+ public void init() {
+ mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ }
+
+ public CreateVfModuleRequest createVfModuleRequestMapper(RequestContext requestContext, CloudRegion cloudRegion,
+ OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, GenericVnf genericVnf,
+ VfModule vfModule, VolumeGroup volumeGroup, String sdncVnfQueryResponse, String sdncVfModuleQueryResponse)
+ throws JsonParseException, JsonMappingException, IOException {
+ CreateVfModuleRequest createVfModuleRequest = new CreateVfModuleRequest();
+
+ createVfModuleRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+ createVfModuleRequest.setCloudOwner(cloudRegion.getCloudOwner());
+ createVfModuleRequest.setTenantId(cloudRegion.getTenantId());
+ createVfModuleRequest.setVfModuleId(vfModule.getVfModuleId());
+ createVfModuleRequest.setVfModuleName(vfModule.getVfModuleName());
+ createVfModuleRequest.setVnfId(genericVnf.getVnfId());
+ createVfModuleRequest.setVnfType(genericVnf.getVnfType());
+ createVfModuleRequest.setVnfVersion(serviceInstance.getModelInfoServiceInstance().getModelVersion());
+ createVfModuleRequest.setVfModuleType(vfModule.getModelInfoVfModule().getModelName());
+ createVfModuleRequest.setModelCustomizationUuid(vfModule.getModelInfoVfModule().getModelCustomizationUUID());
+ if (volumeGroup != null) {
+ createVfModuleRequest.setVolumeGroupId(volumeGroup.getVolumeGroupId());
+ createVfModuleRequest.setVolumeGroupStackId(volumeGroup.getHeatStackId());
+ }
+ VfModule baseVfModule = getBaseVfModule(genericVnf);
+ if (baseVfModule != null) {
+ createVfModuleRequest.setBaseVfModuleId(baseVfModule.getVfModuleId());
+ createVfModuleRequest.setBaseVfModuleStackId(baseVfModule.getHeatStackId());
+ }
+ createVfModuleRequest.setVfModuleParams(buildVfModuleParamsMap(requestContext, serviceInstance, genericVnf,
+ vfModule, sdncVnfQueryResponse, sdncVfModuleQueryResponse));
+
+ createVfModuleRequest.setSkipAAI(true);
+ createVfModuleRequest.setBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
+ createVfModuleRequest.setFailIfExists(true);
+
+ MsoRequest msoRequest = buildMsoRequest(requestContext, serviceInstance);
+ createVfModuleRequest.setMsoRequest(msoRequest);
+
+ String messageId = vnfAdapterObjectMapperUtils.getRandomUuid();
+ createVfModuleRequest.setMessageId(messageId);
+ createVfModuleRequest
+ .setNotificationUrl(vnfAdapterObjectMapperUtils.createCallbackUrl("VNFAResponse", messageId));
+
+ return createVfModuleRequest;
+ }
+
+ private MsoRequest buildMsoRequest(RequestContext requestContext, ServiceInstance serviceInstance) {
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId(requestContext.getMsoRequestId());
+ msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ return msoRequest;
+ }
+
+ private Map<String, Object> buildVfModuleParamsMap(RequestContext requestContext, ServiceInstance serviceInstance,
+ GenericVnf genericVnf, VfModule vfModule, String sdncVnfQueryResponse, String sdncVfModuleQueryResponse)
+ throws JsonParseException, JsonMappingException, IOException {
+
+
+ GenericResourceApiVnfTopology vnfTop =
+ mapper.readValue(sdncVnfQueryResponse, GenericResourceApiVnfTopology.class);
+ GenericResourceApiVfModuleTopology vfModuleTop =
+ mapper.readValue(sdncVfModuleQueryResponse, GenericResourceApiVfModuleTopology.class);
+ GenericResourceApiVnftopologyVnfTopology vnfTopology = vnfTop.getVnfTopology();
+ GenericResourceApiVfmoduletopologyVfModuleTopology vfModuleTopology = vfModuleTop.getVfModuleTopology();
+ Map<String, Object> paramsMap = new HashMap<>();
+
+ if (vfModuleTopology.getSdncGeneratedCloudResources()) {
+ buildParamsMapFromVfModuleSdncResponse(paramsMap, vfModuleTopology, true);
+ buildParamsMapFromVnfSdncResponse(paramsMap, vnfTopology, null, true);
+ } else {
+ Map<String, String> networkRoleMap = buildNetworkRoleMap(vfModuleTopology);
+ buildParamsMapFromVfModuleSdncResponse(paramsMap, vfModuleTopology, false);
+ buildParamsMapFromVnfSdncResponse(paramsMap, vnfTopology, networkRoleMap, false);
+ }
+
+ // build the sdnc_directives from paramsMap
+ buildDirectivesParamFromMap(paramsMap, MsoMulticloudUtils.SDNC_DIRECTIVES, paramsMap);
+ buildDirectivesParamFromMap(paramsMap, MsoMulticloudUtils.USER_DIRECTIVES, requestContext.getUserParams());
+
+ buildMandatoryParamsMap(paramsMap, serviceInstance, genericVnf, vfModule);
+
+ // Parameters received from the request should overwrite any parameters received from SDNC
+ paramsMap.putAll(requestContext.getUserParams());
+
+ if (vfModule.getCloudParams() != null) {
+ paramsMap.putAll(vfModule.getCloudParams());
+ }
+ return paramsMap;
+ }
+
+ private void buildDirectivesParamFromMap(Map<String, Object> paramsMap, String directive,
+ Map<String, Object> srcMap) {
StringBuilder directives = new StringBuilder();
if (srcMap.size() > 0) {
directives.append("{ \"attributes\": [ ");
int i = 0;
for (String attributeName : srcMap.keySet()) {
directives.append(new AttributeNameValue(attributeName, srcMap.get(attributeName).toString()));
- if (i < (srcMap.size()-1))
+ if (i < (srcMap.size() - 1))
directives.append(", ");
i++;
}
@@ -217,636 +221,679 @@ public class VnfAdapterVfModuleObjectMapper {
paramsMap.put(directive, directives.toString());
}
- private void buildMandatoryParamsMap(Map<String,Object> paramsMap, ServiceInstance serviceInstance, GenericVnf genericVnf, VfModule vfModule) {
- paramsMap.put("vnf_id", genericVnf.getVnfId());
- paramsMap.put("vnf_name", genericVnf.getVnfName());
- paramsMap.put("vf_module_id", vfModule.getVfModuleId());
- paramsMap.put("vf_module_name", vfModule.getVfModuleName());
- paramsMap.put("environment_context",serviceInstance.getModelInfoServiceInstance().getEnvironmentContext());
- paramsMap.putIfAbsent("environment_context", "");
- paramsMap.put("workload_context", serviceInstance.getModelInfoServiceInstance().getWorkloadContext());
- paramsMap.putIfAbsent("workload_context", "");
- Integer vfModuleIndex = vfModule.getModuleIndex();
- if (vfModuleIndex != null) {
- paramsMap.put("vf_module_index", vfModuleIndex.toString());
- }
- }
-
- private void buildParamsMapFromVnfSdncResponse(Map<String,Object> paramsMap, GenericResourceApiVnftopologyVnfTopology vnfTopology, Map<String,String> networkRoleMap, boolean skipVnfResourceAssignments) throws JsonParseException, JsonMappingException, IOException {
- // Get VNF parameters from SDNC response
- GenericResourceApiParam vnfParametersData = vnfTopology.getVnfParametersData();
- buildParamsMapFromSdncParams(paramsMap, vnfParametersData);
-
- if(!skipVnfResourceAssignments) {
- GenericResourceApiVnfresourceassignmentsVnfResourceAssignments vnfResourceAssignments = vnfTopology.getVnfResourceAssignments();
- if (vnfResourceAssignments != null) {
- // Availability Zones
- buildAvailabilityZones(paramsMap, vnfResourceAssignments);
- // VNF Networks
- buildVnfNetworks(paramsMap, vnfResourceAssignments, networkRoleMap);
- }
- }
- }
-
- private void buildAvailabilityZones (Map<String,Object> paramsMap, GenericResourceApiVnfresourceassignmentsVnfResourceAssignments vnfResourceAssignments) {
- GenericResourceApiVnfresourceassignmentsVnfresourceassignmentsAvailabilityZones availabilityZones = vnfResourceAssignments.getAvailabilityZones();
- if (availabilityZones != null) {
- List<String> availabilityZonesList = availabilityZones.getAvailabilityZone();
- if (availabilityZonesList != null) {
- for(int i = 0; i < availabilityZonesList.size(); i++) {
- paramsMap.put("availability_zone_" + i, availabilityZonesList.get(i));
- }
- }
- }
- }
-
- private void buildVnfNetworks (Map<String,Object> paramsMap, GenericResourceApiVnfresourceassignmentsVnfResourceAssignments vnfResourceAssignments, Map<String,String> networkRoleMap) {
- GenericResourceApiVnfresourceassignmentsVnfresourceassignmentsVnfNetworks vnfNetworks = vnfResourceAssignments.getVnfNetworks();
- if (vnfNetworks != null) {
- List<GenericResourceApiVnfNetworkData> vnfNetworksList = vnfNetworks.getVnfNetwork();
- if (vnfNetworksList != null) {
- for (int i = 0; i < vnfNetworksList.size(); i++) {
- GenericResourceApiVnfNetworkData vnfNetwork = vnfNetworksList.get(i);
- String networkRole = vnfNetwork.getNetworkRole();
- String vnfNetworkKey = networkRoleMap.get(networkRole);
- if (vnfNetworkKey == null || vnfNetworkKey.isEmpty()) {
- vnfNetworkKey = networkRole;
- }
-
- String vnfNetworkNeutronIdValue = vnfNetwork.getNeutronId();
- paramsMap.put(vnfNetworkKey + "_net_id", vnfNetworkNeutronIdValue);
- String vnfNetworkNetNameValue = vnfNetwork.getNetworkName();
- paramsMap.put(vnfNetworkKey + "_net_name", vnfNetworkNetNameValue);
- String vnfNetworkNetFqdnValue = vnfNetwork.getContrailNetworkFqdn();
- paramsMap.put(vnfNetworkKey + "_net_fqdn", vnfNetworkNetFqdnValue);
-
- buildVnfNetworkSubnets(paramsMap, vnfNetwork, vnfNetworkKey);
-
- }
- }
- }
- }
-
- private void buildVnfNetworkSubnets(Map<String,Object> paramsMap, GenericResourceApiVnfNetworkData vnfNetwork, String vnfNetworkKey) {
- String vnfNetworkString = convertToString(vnfNetwork);
- Optional<String> ipv4Ips = jsonPath.locateResult(vnfNetworkString, "$.subnets-data.subnet-data[*].[?(@.ip-version == 'ipv4' && @.dhcp-enabled == 'Y')].subnet-id");
- if(ipv4Ips.isPresent())
- addPairToMap(paramsMap, vnfNetworkKey, SUBNET_ID, ipv4Ips.get());
-
- Optional<String> ipv6Ips = jsonPath.locateResult(vnfNetworkString, "$.subnets-data.subnet-data[*].[?(@.ip-version == 'ipv6' && @.dhcp-enabled == 'Y')].subnet-id");
- if(ipv6Ips.isPresent())
- addPairToMap(paramsMap, vnfNetworkKey, V6_SUBNET_ID, ipv6Ips.get());
- }
-
- private void buildParamsMapFromVfModuleSdncResponse(Map<String,Object> paramsMap, GenericResourceApiVfmoduletopologyVfModuleTopology vfModuleTopology, boolean skipVfModuleAssignments) throws JsonParseException, JsonMappingException, IOException {
- // Get VF Module parameters from SDNC response
- GenericResourceApiParam vfModuleParametersData = vfModuleTopology.getVfModuleParameters();
- buildParamsMapFromSdncParams(paramsMap, vfModuleParametersData);
-
- if(!skipVfModuleAssignments) {
- GenericResourceApiVfmoduleassignmentsVfModuleAssignments vfModuleAssignments = vfModuleTopology.getVfModuleAssignments();
- if (vfModuleAssignments != null) {
- // VNF-VMS
- GenericResourceApiVfmoduleassignmentsVfmoduleassignmentsVms vms = vfModuleAssignments.getVms();
- if (vms != null) {
- List<GenericResourceApiVmTopologyData> vmsList = vms.getVm();
- if (vmsList != null) {
- for (GenericResourceApiVmTopologyData vm : vmsList){
- String key = vm.getVmType();
- buildVfModuleVmNames(paramsMap, vm, key);
- GenericResourceApiVmtopologydataVmNetworks vmNetworks = vm.getVmNetworks();
- if (vmNetworks != null) {
- List<GenericResourceApiVmNetworkData> vmNetworksList = vmNetworks.getVmNetwork();
- if (vmNetworksList != null) {
- for(int n = 0; n < vmNetworksList.size(); n++){
- GenericResourceApiVmNetworkData network = vmNetworksList.get(n);
- network.getNetworkRoleTag();
- String networkKey = network.getNetworkRole();
- // Floating IPs
- buildVfModuleFloatingIps(paramsMap, network, key, networkKey);
- // Interface Route Prefixes
- buildVfModuleInterfaceRoutePrefixes(paramsMap, network, key, networkKey);
- // SRIOV Parameters
- buildVfModuleSriovParameters(paramsMap, network, networkKey);
- // IPV4 and IPV6 Addresses
- buildVfModuleNetworkInformation(paramsMap, network, key, networkKey);
-
- buildVlanInformation(paramsMap, network, key, networkKey);
-
- }
- }
- }
-
- buildParamsMapFromVfModuleForHeatTemplate(paramsMap, vm);
- }
- }
- }
- }
- }
- }
-
- protected void buildVlanInformation(Map<String, Object> paramsMap,
- GenericResourceApiVmNetworkData network, String key, String networkKey) {
-
- String networkString = convertToString(network);
- String vlanFilterKey = key + UNDERSCORE + networkKey + UNDERSCORE + "vlan_filter";
- String privateVlansKey = key + UNDERSCORE + networkKey + UNDERSCORE + "private_vlans";
- String publicVlansKey = key + UNDERSCORE + networkKey + UNDERSCORE + "public_vlans";
- String guestVlansKey = key + UNDERSCORE + networkKey + UNDERSCORE + "guest_vlans";
-
- if (network.getSegmentationId() != null) {
- paramsMap.put(vlanFilterKey, network.getSegmentationId());
- }
-
- List<String> privateVlans = jsonPath.locateResultList(networkString, "$.related-networks.related-network[?(@.vlan-tags.is-private == true)].vlan-tags.upper-tag-id");
- List<String> publicVlans = jsonPath.locateResultList(networkString, "$.related-networks.related-network[?(@.vlan-tags.is-private == false)].vlan-tags.upper-tag-id");
- List<String> concat = new ArrayList<>(privateVlans);
- concat.addAll(publicVlans);
- Collection<String> guestVlans = new HashSet<>(concat);
-
- if (!privateVlans.isEmpty()) {
- paramsMap.put(privateVlansKey, Joiner.on(",").join(privateVlans));
- }
- if (!publicVlans.isEmpty()) {
- paramsMap.put(publicVlansKey, Joiner.on(",").join(publicVlans));
- }
- if (!guestVlans.isEmpty()) {
- paramsMap.put(guestVlansKey, Joiner.on(",").join(guestVlans));
- }
- }
-
- private void buildVfModuleVmNames(Map<String,Object> paramsMap, GenericResourceApiVmTopologyData vm, String key) {
- String values = "";
- GenericResourceApiVmtopologydataVmNames vmNames = vm.getVmNames();
- if (vmNames != null) {
- List<String> valueList = vmNames.getVmName();
- if (valueList != null) {
- for(int i = 0; i < valueList.size(); i++){
- String value = valueList.get(i);
- if (i != valueList.size() - 1) {
- values += value + ",";
- }
- else {
- values += value;
- }
- paramsMap.put(key + "_name_" + i, value);
- }
- paramsMap.put(key + "_names", values);
- }
- }
- }
-
- private void buildVfModuleFloatingIps(Map<String,Object> paramsMap, GenericResourceApiVmNetworkData network, String key, String networkKey) {
- GenericResourceApiVmnetworkdataFloatingIps floatingIps = network.getFloatingIps();
- if (floatingIps != null) {
- List<String> floatingIpV4List = floatingIps.getFloatingIpV4();
- if (floatingIpV4List != null) {
- // add only one ipv4 floating ip for now
- String floatingIPKey = key + UNDERSCORE + networkKey + FLOATING_IP;
- String floatingIPKeyValue = floatingIpV4List.get(0);
- if (floatingIPKeyValue != null && !floatingIPKeyValue.isEmpty()) {
- paramsMap.put(floatingIPKey, floatingIPKeyValue);
- }
- }
- // add only one ipv6 floating ip for now
- List<String> floatingIpV6List = floatingIps.getFloatingIpV6();
- if (floatingIpV6List != null) {
- String floatingIPV6Key = key + UNDERSCORE + networkKey + FLOATING_V6_IP;
- String floatingIPV6KeyValue = floatingIpV6List.get(0);
- if (floatingIPV6KeyValue != null && !floatingIPV6KeyValue.isEmpty()) {
- paramsMap.put(floatingIPV6Key, floatingIPV6KeyValue);
- }
- }
- }
- }
-
- private void buildVfModuleInterfaceRoutePrefixes(Map<String,Object> paramsMap, GenericResourceApiVmNetworkData network, String key, String networkKey) {
- GenericResourceApiVmnetworkdataInterfaceRoutePrefixes interfaceRoutePrefixes = network.getInterfaceRoutePrefixes();
- if (interfaceRoutePrefixes != null) {
- List<String> interfaceRoutePrefixesList = interfaceRoutePrefixes.getInterfaceRoutePrefix();
- StringBuilder sbInterfaceRoutePrefixes = new StringBuilder();
- sbInterfaceRoutePrefixes.append("[");
- if (interfaceRoutePrefixesList != null) {
- for(int a = 0; a < interfaceRoutePrefixesList.size(); a++){
- String interfaceRoutePrefixValue = interfaceRoutePrefixesList.get(a);
- if (a != interfaceRoutePrefixesList.size() - 1) {
- sbInterfaceRoutePrefixes.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}" + ",");
- }
- else {
- sbInterfaceRoutePrefixes.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}");
- }
- }
- sbInterfaceRoutePrefixes.append("]");
- if (interfaceRoutePrefixesList.size() > 0) {
- paramsMap.put(key + UNDERSCORE + networkKey + "_route_prefixes", sbInterfaceRoutePrefixes.toString());
- }
- }
- }
- }
-
- private void buildVfModuleSriovParameters(Map<String,Object> paramsMap, GenericResourceApiVmNetworkData network, String networkKey) {
- // SRIOV Parameters
- GenericResourceApiVmnetworkdataSriovParameters sriovParameters = network.getSriovParameters();
- if (sriovParameters != null) {
- GenericResourceApiVmnetworkdataSriovparametersHeatVlanFilters heatVlanFilters = sriovParameters.getHeatVlanFilters();
- if (heatVlanFilters != null) {
- List<String> heatVlanFiltersList = heatVlanFilters.getHeatVlanFilter();
- StringBuilder sriovFilterBuf = new StringBuilder();
- if (heatVlanFiltersList != null) {
- for(int a = 0; a < heatVlanFiltersList.size(); a++){
- String heatVlanFilterValue = heatVlanFiltersList.get(a);
- if (a != heatVlanFiltersList.size() - 1) {
- sriovFilterBuf.append(heatVlanFilterValue).append(",");
- }
- else {
- sriovFilterBuf.append(heatVlanFilterValue);
- }
- }
- if (heatVlanFiltersList.size() > 0) {
- paramsMap.put(networkKey + "_ATT_VF_VLAN_FILTER", sriovFilterBuf.toString());
- }
- }
- }
- }
- }
-
- private void buildVfModuleNetworkInformation(Map<String,Object> paramsMap, GenericResourceApiVmNetworkData network, String key, String networkKey) {
-
- GenericResourceApiVmnetworkdataNetworkInformationItems networkInformationItems = network.getNetworkInformationItems();
- StringBuilder sbIpv4Ips = new StringBuilder();
- StringBuilder sbIpv6Ips = new StringBuilder();
-
- if (networkInformationItems != null) {
- List<GenericResourceApiVmnetworkdataNetworkinformationitemsNetworkInformationItem> networkInformationItemList = networkInformationItems.getNetworkInformationItem();
- if (networkInformationItemList != null) {
- for(int a = 0; a < networkInformationItemList.size(); a++){
- GenericResourceApiVmnetworkdataNetworkinformationitemsNetworkInformationItem ipAddress = networkInformationItemList.get(a);
- if (ipAddress != null) {
- GenericResourceApiVmnetworkdataNetworkinformationitemsNetworkinformationitemNetworkIps ips = ipAddress.getNetworkIps();
- if (ips != null) {
- List<String> ipsList = ips.getNetworkIp();
- if (ipsList != null) {
- String ipVersion = ipAddress.getIpVersion();
- for (int b = 0; b < ipsList.size(); b++) {
- String ipAddressValue = ipsList.get(b);
- if (ipVersion.equals("ipv4")) {
- if (b != ipsList.size() - 1) {
- sbIpv4Ips.append(ipAddressValue + ",");
- }
- else {
- sbIpv4Ips.append(ipAddressValue);
- }
- paramsMap.put(key + UNDERSCORE + networkKey + IP + UNDERSCORE + b, ipAddressValue);
- }
- else if (ipVersion.equals("ipv6")) {
- if (b != ipsList.size() - 1) {
- sbIpv6Ips.append(ipAddressValue + ",");
- }
- else {
- sbIpv6Ips.append(ipAddressValue);
- }
- paramsMap.put(key + UNDERSCORE + networkKey + V6_IP + UNDERSCORE + b, ipAddressValue);
- }
- }
- paramsMap.put(key + UNDERSCORE + networkKey + "_ips", sbIpv4Ips.toString());
- paramsMap.put(key + UNDERSCORE + networkKey + "_v6_ips", sbIpv6Ips.toString());
- }
- }
- }
- }
- }
- }
- }
-
- /*
- * Build Mapping from GenericResourceApi SDNC for Heat Template so that AIC - PO gets accurate requests for vf module assignments.
- * Build Count of SubInterfaces, VLAN Tag, network_name, network_id,
- * ip_address (V4 and V6) and Floating IPs Addresses (V4 and V6) for Heat Template
- */
- private void buildParamsMapFromVfModuleForHeatTemplate(Map<String,Object> paramsMap, GenericResourceApiVmTopologyData vm) {
- GenericResourceApiVmtopologydataVmNames vmNames = vm.getVmNames();
-
- if (vmNames != null) {
-
- List<GenericResourceApiVmtopologydataVmnamesVnfcNames> vnfcNamesList = vmNames.getVnfcNames();
- if (vnfcNamesList != null) {
-
- for(int i = 0; i < vnfcNamesList.size(); i++){
-
- GenericResourceApiVmtopologydataVmnamesVnfcNames vnfcNames = vnfcNamesList.get(i);
- parseVnfcNamesData(paramsMap, vnfcNames);
- }
- }
- }
- }
-
- /*
- * Parse vnfcNames data to build Mapping from GenericResourceApi SDNC for Heat Template.
- */
- private void parseVnfcNamesData(Map<String,Object> paramsMap, GenericResourceApiVmtopologydataVmnamesVnfcNames vnfcNames) {
-
- if (vnfcNames != null) {
- GenericResourceApiVnfcNetworkData vnfcNetworks = vnfcNames.getVnfcNetworks();
- if (vnfcNetworks != null) {
- List<GenericResourceApiVnfcnetworkdataVnfcNetworkData> vnfcNetworkdataList = vnfcNetworks.getVnfcNetworkData();
-
- if (vnfcNetworkdataList != null) {
-
- for(int networkDataIdx = 0; networkDataIdx < vnfcNetworkdataList.size(); networkDataIdx++){
-
- GenericResourceApiVnfcnetworkdataVnfcNetworkData vnfcNetworkdata = vnfcNetworkdataList.get(networkDataIdx);
- parseVnfcNetworkData(paramsMap, vnfcNetworkdata, networkDataIdx);
- }
- }
- }
- }
- }
-
- /*
- * Parse VnfcNetworkData to build Mapping from GenericResourceApi SDNC for Heat Template.
- * Build Count of SubInterfaces, VLAN Tag, network_name, network_id,
- * ip_address (V4 and V6) and Floating IPs Addresses (V4 and V6) for Heat Template
- */
- private void parseVnfcNetworkData(Map<String,Object> paramsMap, GenericResourceApiVnfcnetworkdataVnfcNetworkData vnfcNetworkdata, int networkDataIdx) {
-
- String vmTypeKey = vnfcNetworkdata.getVnfcType();
- GenericResourceApiVnfcnetworkdataVnfcnetworkdataVnfcPorts vnfcPorts = vnfcNetworkdata.getVnfcPorts();
- if (vnfcPorts != null) {
- List<GenericResourceApiVnfcnetworkdataVnfcnetworkdataVnfcportsVnfcPort> vnfcPortList = vnfcPorts.getVnfcPort();
- if (vnfcPortList != null) {
- for(int portIdx = 0; portIdx < vnfcPortList.size(); portIdx++){
-
- GenericResourceApiVnfcnetworkdataVnfcnetworkdataVnfcportsVnfcPort vnfcPort = vnfcPortList.get(portIdx);
- GenericResourceApiSubInterfaceNetworkData vnicSubInterfaces = vnfcPort.getVnicSubInterfaces();
-
- String vnicSubInterfacesString = convertToString(vnicSubInterfaces);
- String networkRoleKey = vnfcPort.getCommonSubInterfaceRole();
- String subInterfaceKey = createVnfcSubInterfaceKey(vmTypeKey, networkDataIdx, networkRoleKey, portIdx);
- String globalSubInterfaceKey = createGlobalVnfcSubInterfaceKey(vmTypeKey, networkRoleKey, portIdx);
-
- buildVfModuleSubInterfacesCount(paramsMap, globalSubInterfaceKey, vnicSubInterfaces);
-
- buildVfModuleVlanTag(paramsMap, subInterfaceKey, vnicSubInterfacesString);
-
- buildVfModuleNetworkName(paramsMap, subInterfaceKey, vnicSubInterfacesString);
-
- buildVfModuleNetworkId(paramsMap, subInterfaceKey, vnicSubInterfacesString);
-
- buildVfModuleIpV4AddressHeatTemplate(paramsMap, subInterfaceKey, vnicSubInterfacesString);
-
- buildVfModuleIpV6AddressHeatTemplate(paramsMap, subInterfaceKey, vnicSubInterfacesString);
-
- buildVfModuleFloatingIpV4HeatTemplate(paramsMap, globalSubInterfaceKey, vnicSubInterfacesString);
-
- buildVfModuleFloatingIpV6HeatTemplate(paramsMap, globalSubInterfaceKey, vnicSubInterfacesString);
- }
- }
- }
- }
-
- /*
- * Build "count" (calculating the total number of sub-interfaces) for Heat Template
- * Building Criteria : {vm-type}_subint_{network-role}_port_{index}_subintcount
- * vmTypeKey = vm-type, networkRoleKey = common-sub-interface-role
- * Example: fw_subint_ctrl_port_0_subintcount
- *
- */
- private void buildVfModuleSubInterfacesCount(Map<String,Object> paramsMap, String keyPrefix, GenericResourceApiSubInterfaceNetworkData vnicSubInterfaces) {
+ private void buildMandatoryParamsMap(Map<String, Object> paramsMap, ServiceInstance serviceInstance,
+ GenericVnf genericVnf, VfModule vfModule) {
+ paramsMap.put("vnf_id", genericVnf.getVnfId());
+ paramsMap.put("vnf_name", genericVnf.getVnfName());
+ paramsMap.put("vf_module_id", vfModule.getVfModuleId());
+ paramsMap.put("vf_module_name", vfModule.getVfModuleName());
+ paramsMap.put("environment_context", serviceInstance.getModelInfoServiceInstance().getEnvironmentContext());
+ paramsMap.putIfAbsent("environment_context", "");
+ paramsMap.put("workload_context", serviceInstance.getModelInfoServiceInstance().getWorkloadContext());
+ paramsMap.putIfAbsent("workload_context", "");
+ Integer vfModuleIndex = vfModule.getModuleIndex();
+ if (vfModuleIndex != null) {
+ paramsMap.put("vf_module_index", vfModuleIndex.toString());
+ }
+ }
+
+ private void buildParamsMapFromVnfSdncResponse(Map<String, Object> paramsMap,
+ GenericResourceApiVnftopologyVnfTopology vnfTopology, Map<String, String> networkRoleMap,
+ boolean skipVnfResourceAssignments) throws JsonParseException, JsonMappingException, IOException {
+ // Get VNF parameters from SDNC response
+ GenericResourceApiParam vnfParametersData = vnfTopology.getVnfParametersData();
+ buildParamsMapFromSdncParams(paramsMap, vnfParametersData);
+
+ if (!skipVnfResourceAssignments) {
+ GenericResourceApiVnfresourceassignmentsVnfResourceAssignments vnfResourceAssignments =
+ vnfTopology.getVnfResourceAssignments();
+ if (vnfResourceAssignments != null) {
+ // Availability Zones
+ buildAvailabilityZones(paramsMap, vnfResourceAssignments);
+ // VNF Networks
+ buildVnfNetworks(paramsMap, vnfResourceAssignments, networkRoleMap);
+ }
+ }
+ }
+
+ private void buildAvailabilityZones(Map<String, Object> paramsMap,
+ GenericResourceApiVnfresourceassignmentsVnfResourceAssignments vnfResourceAssignments) {
+ GenericResourceApiVnfresourceassignmentsVnfresourceassignmentsAvailabilityZones availabilityZones =
+ vnfResourceAssignments.getAvailabilityZones();
+ if (availabilityZones != null) {
+ List<String> availabilityZonesList = availabilityZones.getAvailabilityZone();
+ if (availabilityZonesList != null) {
+ for (int i = 0; i < availabilityZonesList.size(); i++) {
+ paramsMap.put("availability_zone_" + i, availabilityZonesList.get(i));
+ }
+ }
+ }
+ }
+
+ private void buildVnfNetworks(Map<String, Object> paramsMap,
+ GenericResourceApiVnfresourceassignmentsVnfResourceAssignments vnfResourceAssignments,
+ Map<String, String> networkRoleMap) {
+ GenericResourceApiVnfresourceassignmentsVnfresourceassignmentsVnfNetworks vnfNetworks =
+ vnfResourceAssignments.getVnfNetworks();
+ if (vnfNetworks != null) {
+ List<GenericResourceApiVnfNetworkData> vnfNetworksList = vnfNetworks.getVnfNetwork();
+ if (vnfNetworksList != null) {
+ for (int i = 0; i < vnfNetworksList.size(); i++) {
+ GenericResourceApiVnfNetworkData vnfNetwork = vnfNetworksList.get(i);
+ String networkRole = vnfNetwork.getNetworkRole();
+ String vnfNetworkKey = networkRoleMap.get(networkRole);
+ if (vnfNetworkKey == null || vnfNetworkKey.isEmpty()) {
+ vnfNetworkKey = networkRole;
+ }
+
+ String vnfNetworkNeutronIdValue = vnfNetwork.getNeutronId();
+ paramsMap.put(vnfNetworkKey + "_net_id", vnfNetworkNeutronIdValue);
+ String vnfNetworkNetNameValue = vnfNetwork.getNetworkName();
+ paramsMap.put(vnfNetworkKey + "_net_name", vnfNetworkNetNameValue);
+ String vnfNetworkNetFqdnValue = vnfNetwork.getContrailNetworkFqdn();
+ paramsMap.put(vnfNetworkKey + "_net_fqdn", vnfNetworkNetFqdnValue);
+
+ buildVnfNetworkSubnets(paramsMap, vnfNetwork, vnfNetworkKey);
+
+ }
+ }
+ }
+ }
+
+ private void buildVnfNetworkSubnets(Map<String, Object> paramsMap, GenericResourceApiVnfNetworkData vnfNetwork,
+ String vnfNetworkKey) {
+ String vnfNetworkString = convertToString(vnfNetwork);
+ Optional<String> ipv4Ips = jsonPath.locateResult(vnfNetworkString,
+ "$.subnets-data.subnet-data[*].[?(@.ip-version == 'ipv4' && @.dhcp-enabled == 'Y')].subnet-id");
+ if (ipv4Ips.isPresent())
+ addPairToMap(paramsMap, vnfNetworkKey, SUBNET_ID, ipv4Ips.get());
+
+ Optional<String> ipv6Ips = jsonPath.locateResult(vnfNetworkString,
+ "$.subnets-data.subnet-data[*].[?(@.ip-version == 'ipv6' && @.dhcp-enabled == 'Y')].subnet-id");
+ if (ipv6Ips.isPresent())
+ addPairToMap(paramsMap, vnfNetworkKey, V6_SUBNET_ID, ipv6Ips.get());
+ }
+
+ private void buildParamsMapFromVfModuleSdncResponse(Map<String, Object> paramsMap,
+ GenericResourceApiVfmoduletopologyVfModuleTopology vfModuleTopology, boolean skipVfModuleAssignments)
+ throws JsonParseException, JsonMappingException, IOException {
+ // Get VF Module parameters from SDNC response
+ GenericResourceApiParam vfModuleParametersData = vfModuleTopology.getVfModuleParameters();
+ buildParamsMapFromSdncParams(paramsMap, vfModuleParametersData);
+
+ if (!skipVfModuleAssignments) {
+ GenericResourceApiVfmoduleassignmentsVfModuleAssignments vfModuleAssignments =
+ vfModuleTopology.getVfModuleAssignments();
+ if (vfModuleAssignments != null) {
+ // VNF-VMS
+ GenericResourceApiVfmoduleassignmentsVfmoduleassignmentsVms vms = vfModuleAssignments.getVms();
+ if (vms != null) {
+ List<GenericResourceApiVmTopologyData> vmsList = vms.getVm();
+ if (vmsList != null) {
+ for (GenericResourceApiVmTopologyData vm : vmsList) {
+ String key = vm.getVmType();
+ buildVfModuleVmNames(paramsMap, vm, key);
+ GenericResourceApiVmtopologydataVmNetworks vmNetworks = vm.getVmNetworks();
+ if (vmNetworks != null) {
+ List<GenericResourceApiVmNetworkData> vmNetworksList = vmNetworks.getVmNetwork();
+ if (vmNetworksList != null) {
+ for (int n = 0; n < vmNetworksList.size(); n++) {
+ GenericResourceApiVmNetworkData network = vmNetworksList.get(n);
+ network.getNetworkRoleTag();
+ String networkKey = network.getNetworkRole();
+ // Floating IPs
+ buildVfModuleFloatingIps(paramsMap, network, key, networkKey);
+ // Interface Route Prefixes
+ buildVfModuleInterfaceRoutePrefixes(paramsMap, network, key, networkKey);
+ // SRIOV Parameters
+ buildVfModuleSriovParameters(paramsMap, network, networkKey);
+ // IPV4 and IPV6 Addresses
+ buildVfModuleNetworkInformation(paramsMap, network, key, networkKey);
+
+ buildVlanInformation(paramsMap, network, key, networkKey);
+
+ }
+ }
+ }
+
+ buildParamsMapFromVfModuleForHeatTemplate(paramsMap, vm);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ protected void buildVlanInformation(Map<String, Object> paramsMap, GenericResourceApiVmNetworkData network,
+ String key, String networkKey) {
+
+ String networkString = convertToString(network);
+ String vlanFilterKey = key + UNDERSCORE + networkKey + UNDERSCORE + "vlan_filter";
+ String privateVlansKey = key + UNDERSCORE + networkKey + UNDERSCORE + "private_vlans";
+ String publicVlansKey = key + UNDERSCORE + networkKey + UNDERSCORE + "public_vlans";
+ String guestVlansKey = key + UNDERSCORE + networkKey + UNDERSCORE + "guest_vlans";
+
+ if (network.getSegmentationId() != null) {
+ paramsMap.put(vlanFilterKey, network.getSegmentationId());
+ }
+
+ List<String> privateVlans = jsonPath.locateResultList(networkString,
+ "$.related-networks.related-network[?(@.vlan-tags.is-private == true)].vlan-tags.upper-tag-id");
+ List<String> publicVlans = jsonPath.locateResultList(networkString,
+ "$.related-networks.related-network[?(@.vlan-tags.is-private == false)].vlan-tags.upper-tag-id");
+ List<String> concat = new ArrayList<>(privateVlans);
+ concat.addAll(publicVlans);
+ Collection<String> guestVlans = new HashSet<>(concat);
+
+ if (!privateVlans.isEmpty()) {
+ paramsMap.put(privateVlansKey, Joiner.on(",").join(privateVlans));
+ }
+ if (!publicVlans.isEmpty()) {
+ paramsMap.put(publicVlansKey, Joiner.on(",").join(publicVlans));
+ }
+ if (!guestVlans.isEmpty()) {
+ paramsMap.put(guestVlansKey, Joiner.on(",").join(guestVlans));
+ }
+ }
+
+ private void buildVfModuleVmNames(Map<String, Object> paramsMap, GenericResourceApiVmTopologyData vm, String key) {
+ String values = "";
+ GenericResourceApiVmtopologydataVmNames vmNames = vm.getVmNames();
+ if (vmNames != null) {
+ List<String> valueList = vmNames.getVmName();
+ if (valueList != null) {
+ for (int i = 0; i < valueList.size(); i++) {
+ String value = valueList.get(i);
+ if (i != valueList.size() - 1) {
+ values += value + ",";
+ } else {
+ values += value;
+ }
+ paramsMap.put(key + "_name_" + i, value);
+ }
+ paramsMap.put(key + "_names", values);
+ }
+ }
+ }
+
+ private void buildVfModuleFloatingIps(Map<String, Object> paramsMap, GenericResourceApiVmNetworkData network,
+ String key, String networkKey) {
+ GenericResourceApiVmnetworkdataFloatingIps floatingIps = network.getFloatingIps();
+ if (floatingIps != null) {
+ List<String> floatingIpV4List = floatingIps.getFloatingIpV4();
+ if (floatingIpV4List != null) {
+ // add only one ipv4 floating ip for now
+ String floatingIPKey = key + UNDERSCORE + networkKey + FLOATING_IP;
+ String floatingIPKeyValue = floatingIpV4List.get(0);
+ if (floatingIPKeyValue != null && !floatingIPKeyValue.isEmpty()) {
+ paramsMap.put(floatingIPKey, floatingIPKeyValue);
+ }
+ }
+ // add only one ipv6 floating ip for now
+ List<String> floatingIpV6List = floatingIps.getFloatingIpV6();
+ if (floatingIpV6List != null) {
+ String floatingIPV6Key = key + UNDERSCORE + networkKey + FLOATING_V6_IP;
+ String floatingIPV6KeyValue = floatingIpV6List.get(0);
+ if (floatingIPV6KeyValue != null && !floatingIPV6KeyValue.isEmpty()) {
+ paramsMap.put(floatingIPV6Key, floatingIPV6KeyValue);
+ }
+ }
+ }
+ }
+
+ private void buildVfModuleInterfaceRoutePrefixes(Map<String, Object> paramsMap,
+ GenericResourceApiVmNetworkData network, String key, String networkKey) {
+ GenericResourceApiVmnetworkdataInterfaceRoutePrefixes interfaceRoutePrefixes =
+ network.getInterfaceRoutePrefixes();
+ if (interfaceRoutePrefixes != null) {
+ List<String> interfaceRoutePrefixesList = interfaceRoutePrefixes.getInterfaceRoutePrefix();
+ StringBuilder sbInterfaceRoutePrefixes = new StringBuilder();
+ sbInterfaceRoutePrefixes.append("[");
+ if (interfaceRoutePrefixesList != null) {
+ for (int a = 0; a < interfaceRoutePrefixesList.size(); a++) {
+ String interfaceRoutePrefixValue = interfaceRoutePrefixesList.get(a);
+ if (a != interfaceRoutePrefixesList.size() - 1) {
+ sbInterfaceRoutePrefixes.append("{\"interface_route_table_routes_route_prefix\": \""
+ + interfaceRoutePrefixValue + "\"}" + ",");
+ } else {
+ sbInterfaceRoutePrefixes.append("{\"interface_route_table_routes_route_prefix\": \""
+ + interfaceRoutePrefixValue + "\"}");
+ }
+ }
+ sbInterfaceRoutePrefixes.append("]");
+ if (interfaceRoutePrefixesList.size() > 0) {
+ paramsMap.put(key + UNDERSCORE + networkKey + "_route_prefixes",
+ sbInterfaceRoutePrefixes.toString());
+ }
+ }
+ }
+ }
+
+ private void buildVfModuleSriovParameters(Map<String, Object> paramsMap, GenericResourceApiVmNetworkData network,
+ String networkKey) {
+ // SRIOV Parameters
+ GenericResourceApiVmnetworkdataSriovParameters sriovParameters = network.getSriovParameters();
+ if (sriovParameters != null) {
+ GenericResourceApiVmnetworkdataSriovparametersHeatVlanFilters heatVlanFilters =
+ sriovParameters.getHeatVlanFilters();
+ if (heatVlanFilters != null) {
+ List<String> heatVlanFiltersList = heatVlanFilters.getHeatVlanFilter();
+ StringBuilder sriovFilterBuf = new StringBuilder();
+ if (heatVlanFiltersList != null) {
+ for (int a = 0; a < heatVlanFiltersList.size(); a++) {
+ String heatVlanFilterValue = heatVlanFiltersList.get(a);
+ if (a != heatVlanFiltersList.size() - 1) {
+ sriovFilterBuf.append(heatVlanFilterValue).append(",");
+ } else {
+ sriovFilterBuf.append(heatVlanFilterValue);
+ }
+ }
+ if (heatVlanFiltersList.size() > 0) {
+ paramsMap.put(networkKey + "_ATT_VF_VLAN_FILTER", sriovFilterBuf.toString());
+ }
+ }
+ }
+ }
+ }
+
+ private void buildVfModuleNetworkInformation(Map<String, Object> paramsMap, GenericResourceApiVmNetworkData network,
+ String key, String networkKey) {
+
+ GenericResourceApiVmnetworkdataNetworkInformationItems networkInformationItems =
+ network.getNetworkInformationItems();
+ StringBuilder sbIpv4Ips = new StringBuilder();
+ StringBuilder sbIpv6Ips = new StringBuilder();
+
+ if (networkInformationItems != null) {
+ List<GenericResourceApiVmnetworkdataNetworkinformationitemsNetworkInformationItem> networkInformationItemList =
+ networkInformationItems.getNetworkInformationItem();
+ if (networkInformationItemList != null) {
+ for (int a = 0; a < networkInformationItemList.size(); a++) {
+ GenericResourceApiVmnetworkdataNetworkinformationitemsNetworkInformationItem ipAddress =
+ networkInformationItemList.get(a);
+ if (ipAddress != null) {
+ GenericResourceApiVmnetworkdataNetworkinformationitemsNetworkinformationitemNetworkIps ips =
+ ipAddress.getNetworkIps();
+ if (ips != null) {
+ List<String> ipsList = ips.getNetworkIp();
+ if (ipsList != null) {
+ String ipVersion = ipAddress.getIpVersion();
+ for (int b = 0; b < ipsList.size(); b++) {
+ String ipAddressValue = ipsList.get(b);
+ if (ipVersion.equals("ipv4")) {
+ if (b != ipsList.size() - 1) {
+ sbIpv4Ips.append(ipAddressValue + ",");
+ } else {
+ sbIpv4Ips.append(ipAddressValue);
+ }
+ paramsMap.put(key + UNDERSCORE + networkKey + IP + UNDERSCORE + b,
+ ipAddressValue);
+ } else if (ipVersion.equals("ipv6")) {
+ if (b != ipsList.size() - 1) {
+ sbIpv6Ips.append(ipAddressValue + ",");
+ } else {
+ sbIpv6Ips.append(ipAddressValue);
+ }
+ paramsMap.put(key + UNDERSCORE + networkKey + V6_IP + UNDERSCORE + b,
+ ipAddressValue);
+ }
+ }
+ paramsMap.put(key + UNDERSCORE + networkKey + "_ips", sbIpv4Ips.toString());
+ paramsMap.put(key + UNDERSCORE + networkKey + "_v6_ips", sbIpv6Ips.toString());
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /*
+ * Build Mapping from GenericResourceApi SDNC for Heat Template so that AIC - PO gets accurate requests for vf
+ * module assignments. Build Count of SubInterfaces, VLAN Tag, network_name, network_id, ip_address (V4 and V6) and
+ * Floating IPs Addresses (V4 and V6) for Heat Template
+ */
+ private void buildParamsMapFromVfModuleForHeatTemplate(Map<String, Object> paramsMap,
+ GenericResourceApiVmTopologyData vm) {
+ GenericResourceApiVmtopologydataVmNames vmNames = vm.getVmNames();
+
+ if (vmNames != null) {
+
+ List<GenericResourceApiVmtopologydataVmnamesVnfcNames> vnfcNamesList = vmNames.getVnfcNames();
+ if (vnfcNamesList != null) {
+
+ for (int i = 0; i < vnfcNamesList.size(); i++) {
+
+ GenericResourceApiVmtopologydataVmnamesVnfcNames vnfcNames = vnfcNamesList.get(i);
+ parseVnfcNamesData(paramsMap, vnfcNames);
+ }
+ }
+ }
+ }
+
+ /*
+ * Parse vnfcNames data to build Mapping from GenericResourceApi SDNC for Heat Template.
+ */
+ private void parseVnfcNamesData(Map<String, Object> paramsMap,
+ GenericResourceApiVmtopologydataVmnamesVnfcNames vnfcNames) {
+
+ if (vnfcNames != null) {
+ GenericResourceApiVnfcNetworkData vnfcNetworks = vnfcNames.getVnfcNetworks();
+ if (vnfcNetworks != null) {
+ List<GenericResourceApiVnfcnetworkdataVnfcNetworkData> vnfcNetworkdataList =
+ vnfcNetworks.getVnfcNetworkData();
+
+ if (vnfcNetworkdataList != null) {
+
+ for (int networkDataIdx = 0; networkDataIdx < vnfcNetworkdataList.size(); networkDataIdx++) {
+
+ GenericResourceApiVnfcnetworkdataVnfcNetworkData vnfcNetworkdata =
+ vnfcNetworkdataList.get(networkDataIdx);
+ parseVnfcNetworkData(paramsMap, vnfcNetworkdata, networkDataIdx);
+ }
+ }
+ }
+ }
+ }
+
+ /*
+ * Parse VnfcNetworkData to build Mapping from GenericResourceApi SDNC for Heat Template. Build Count of
+ * SubInterfaces, VLAN Tag, network_name, network_id, ip_address (V4 and V6) and Floating IPs Addresses (V4 and V6)
+ * for Heat Template
+ */
+ private void parseVnfcNetworkData(Map<String, Object> paramsMap,
+ GenericResourceApiVnfcnetworkdataVnfcNetworkData vnfcNetworkdata, int networkDataIdx) {
+
+ String vmTypeKey = vnfcNetworkdata.getVnfcType();
+ GenericResourceApiVnfcnetworkdataVnfcnetworkdataVnfcPorts vnfcPorts = vnfcNetworkdata.getVnfcPorts();
+ if (vnfcPorts != null) {
+ List<GenericResourceApiVnfcnetworkdataVnfcnetworkdataVnfcportsVnfcPort> vnfcPortList =
+ vnfcPorts.getVnfcPort();
+ if (vnfcPortList != null) {
+ for (int portIdx = 0; portIdx < vnfcPortList.size(); portIdx++) {
+
+ GenericResourceApiVnfcnetworkdataVnfcnetworkdataVnfcportsVnfcPort vnfcPort =
+ vnfcPortList.get(portIdx);
+ GenericResourceApiSubInterfaceNetworkData vnicSubInterfaces = vnfcPort.getVnicSubInterfaces();
+
+ String vnicSubInterfacesString = convertToString(vnicSubInterfaces);
+ String networkRoleKey = vnfcPort.getCommonSubInterfaceRole();
+ String subInterfaceKey =
+ createVnfcSubInterfaceKey(vmTypeKey, networkDataIdx, networkRoleKey, portIdx);
+ String globalSubInterfaceKey = createGlobalVnfcSubInterfaceKey(vmTypeKey, networkRoleKey, portIdx);
+
+ buildVfModuleSubInterfacesCount(paramsMap, globalSubInterfaceKey, vnicSubInterfaces);
+
+ buildVfModuleVlanTag(paramsMap, subInterfaceKey, vnicSubInterfacesString);
+
+ buildVfModuleNetworkName(paramsMap, subInterfaceKey, vnicSubInterfacesString);
+
+ buildVfModuleNetworkId(paramsMap, subInterfaceKey, vnicSubInterfacesString);
+
+ buildVfModuleIpV4AddressHeatTemplate(paramsMap, subInterfaceKey, vnicSubInterfacesString);
+
+ buildVfModuleIpV6AddressHeatTemplate(paramsMap, subInterfaceKey, vnicSubInterfacesString);
+
+ buildVfModuleFloatingIpV4HeatTemplate(paramsMap, globalSubInterfaceKey, vnicSubInterfacesString);
+
+ buildVfModuleFloatingIpV6HeatTemplate(paramsMap, globalSubInterfaceKey, vnicSubInterfacesString);
+ }
+ }
+ }
+ }
+
+ /*
+ * Build "count" (calculating the total number of sub-interfaces) for Heat Template Building Criteria :
+ * {vm-type}_subint_{network-role}_port_{index}_subintcount vmTypeKey = vm-type, networkRoleKey =
+ * common-sub-interface-role Example: fw_subint_ctrl_port_0_subintcount
+ *
+ */
+ private void buildVfModuleSubInterfacesCount(Map<String, Object> paramsMap, String keyPrefix,
+ GenericResourceApiSubInterfaceNetworkData vnicSubInterfaces) {
+
+ List<GenericResourceApiSubinterfacenetworkdataSubInterfaceNetworkData> subInterfaceNetworkDataList =
+ vnicSubInterfaces.getSubInterfaceNetworkData();
+
+ if ((subInterfaceNetworkDataList != null) && !subInterfaceNetworkDataList.isEmpty()) {
+ addPairToMap(paramsMap, keyPrefix, SUB_INT_COUNT, String.valueOf(subInterfaceNetworkDataList.size()));
+ }
+ }
+
+ protected String createVnfcSubInterfaceKey(String vmTypeKey, int networkDataIdx, String networkRoleKey,
+ int portIdx) {
+
+ return Joiner.on(UNDERSCORE)
+ .join(Arrays.asList(vmTypeKey, networkDataIdx, SUB_INT, networkRoleKey, PORT, portIdx));
+ }
+
+ protected String createGlobalVnfcSubInterfaceKey(String vmTypeKey, String networkRoleKey, int portIdx) {
+
+ return Joiner.on(UNDERSCORE).join(Arrays.asList(vmTypeKey, SUB_INT, networkRoleKey, PORT, portIdx));
+ }
+
+ /*
+ * Build VLAN Tag for Heat Template Building Criteria :
+ * {vm-type}_{index}_subint_{network-role}_port_{index}_vlan_ids vmTypeKey = vm-type, networkRoleKey =
+ * common-sub-interface-role Example: fw_0_subint_ctrl_port_0_vlan_ids
+ *
+ */
+ protected void buildVfModuleVlanTag(Map<String, Object> paramsMap, String keyPrefix, String vnicSubInterfaces) {
+
+ List<String> vlanTagIds =
+ jsonPath.locateResultList(vnicSubInterfaces, "$.sub-interface-network-data[*].vlan-tag-id");
+
+ addPairToMap(paramsMap, keyPrefix, VLAN_IDS, vlanTagIds);
+ }
+
+ /*
+ * Build "network_name" for Heat Template Building Criteria :
+ * {vm-type}_{index}_subint_{network-role}_port_{index}_net_names vmTypeKey = vm-type, networkRoleKey =
+ * common-sub-interface-role Example: fw_0_subint_ctrl_port_0_net_names
+ *
+ */
+ protected void buildVfModuleNetworkName(Map<String, Object> paramsMap, String keyPrefix, String vnicSubInterfaces) {
+
+ List<String> neworkNames =
+ jsonPath.locateResultList(vnicSubInterfaces, "$.sub-interface-network-data[*].network-name");
+
+ addPairToMap(paramsMap, keyPrefix, NET_NAMES, neworkNames);
+ }
+
+ /*
+ * Build "network_id" for Heat Template Building Criteria :
+ * {vm-type}_{index}_subint_{network-role}_port_{index}_net_ids vmTypeKey = vm-type, networkRoleKey =
+ * common-sub-interface-role Example: fw_0_subint_ctrl_port_0_net_ids
+ *
+ */
+ protected void buildVfModuleNetworkId(Map<String, Object> paramsMap, String keyPrefix, String vnicSubInterfaces) {
+
+ List<String> neworkIds =
+ jsonPath.locateResultList(vnicSubInterfaces, "$.sub-interface-network-data[*].network-id");
+
+ addPairToMap(paramsMap, keyPrefix, NET_IDS, neworkIds);
+ }
+
+ /*
+ * Build ip_address for V4 for Heat Template Building Criteria :
+ * {vm-type}_{index}_subint_{network-role}_port_{index}_ip_{index} -- for ipV4 key = vm-type, networkRoleKey =
+ * NetWork-Role
+ */
+ protected void buildVfModuleIpV4AddressHeatTemplate(Map<String, Object> paramsMap, String keyPrefix,
+ String vnicSubInterfaces) {
+
+ List<String> ipv4Ips = jsonPath.locateResultList(vnicSubInterfaces,
+ "$.sub-interface-network-data[*].network-information-items.network-information-item[?(@.ip-version == 'ipv4')].network-ips.network-ip[*]");
+
+ addPairToMap(paramsMap, keyPrefix, IP, ipv4Ips);
+
+ for (int i = 0; i < ipv4Ips.size(); i++) {
+ addPairToMap(paramsMap, keyPrefix, IP + UNDERSCORE + i, ipv4Ips.get(i));
+ }
+
+ }
+
+ /*
+ * Build ip_address for Heat Template Building Criteria :
+ * {vm-type}_{index}_subint_{network-role}_port_{index}_v6_ip_{index} -- for ipV6 key = vm-type, networkRoleKey =
+ * NetWork-Role
+ */
+ protected void buildVfModuleIpV6AddressHeatTemplate(Map<String, Object> paramsMap, String keyPrefix,
+ String vnicSubInterfaces) {
+
+ List<String> ipv6Ips = jsonPath.locateResultList(vnicSubInterfaces,
+ "$.sub-interface-network-data[*].network-information-items.network-information-item[?(@.ip-version == 'ipv6')].network-ips.network-ip[*]");
- List<GenericResourceApiSubinterfacenetworkdataSubInterfaceNetworkData> subInterfaceNetworkDataList = vnicSubInterfaces.getSubInterfaceNetworkData();
+ addPairToMap(paramsMap, keyPrefix, V6_IP, ipv6Ips);
- if ( (subInterfaceNetworkDataList != null) && !subInterfaceNetworkDataList.isEmpty() ) {
- addPairToMap(paramsMap, keyPrefix, SUB_INT_COUNT, String.valueOf(subInterfaceNetworkDataList.size()));
- }
+ for (int i = 0; i < ipv6Ips.size(); i++) {
+ addPairToMap(paramsMap, keyPrefix, V6_IP + UNDERSCORE + i, ipv6Ips.get(i));
+ }
}
- protected String createVnfcSubInterfaceKey(String vmTypeKey, int networkDataIdx, String networkRoleKey, int portIdx) {
+ /*
+ * Build floatingip_address for Heat Template Building Criteria :
+ * {vm-type}_subint_{network-role}_port_{index}_floating_ip -- for ipV4
+ */
+ protected void buildVfModuleFloatingIpV4HeatTemplate(Map<String, Object> paramsMap, String keyPrefix,
+ String vnicSubInterfaces) {
- return Joiner.on(UNDERSCORE).join(Arrays.asList(vmTypeKey, networkDataIdx, SUB_INT, networkRoleKey, PORT, portIdx));
- }
+ List<String> floatingV4 = jsonPath.locateResultList(vnicSubInterfaces,
+ "$.sub-interface-network-data[*].floating-ips.floating-ip-v4[*]");
- protected String createGlobalVnfcSubInterfaceKey(String vmTypeKey,String networkRoleKey, int portIdx) {
+ if (!floatingV4.isEmpty()) {
+ floatingV4 = Collections.singletonList(floatingV4.get(0));
+ }
+ addPairToMap(paramsMap, keyPrefix, FLOATING_IP, floatingV4);
- return Joiner.on(UNDERSCORE).join(Arrays.asList(vmTypeKey, SUB_INT, networkRoleKey, PORT, portIdx));
- }
+ }
- /*
- * Build VLAN Tag for Heat Template
- * Building Criteria : {vm-type}_{index}_subint_{network-role}_port_{index}_vlan_ids
- * vmTypeKey = vm-type, networkRoleKey = common-sub-interface-role
- * Example: fw_0_subint_ctrl_port_0_vlan_ids
- *
- */
- protected void buildVfModuleVlanTag(Map<String,Object> paramsMap, String keyPrefix, String vnicSubInterfaces) {
+ /*
+ * Build floatingip_address for Heat Template Building Criteria :
+ * {vm-type}_subint_{network-role}_port_{index}_floating_v6_ip -- for ipV6
+ */
+ protected void buildVfModuleFloatingIpV6HeatTemplate(Map<String, Object> paramsMap, String keyPrefix,
+ String vnicSubInterfaces) {
- List<String> vlanTagIds = jsonPath.locateResultList(vnicSubInterfaces, "$.sub-interface-network-data[*].vlan-tag-id");
+ List<String> floatingV6 = jsonPath.locateResultList(vnicSubInterfaces,
+ "$.sub-interface-network-data[*].floating-ips.floating-ip-v6[*]");
- addPairToMap(paramsMap, keyPrefix, VLAN_IDS, vlanTagIds);
- }
- /*
- * Build "network_name" for Heat Template
- * Building Criteria : {vm-type}_{index}_subint_{network-role}_port_{index}_net_names
- * vmTypeKey = vm-type, networkRoleKey = common-sub-interface-role
- * Example: fw_0_subint_ctrl_port_0_net_names
- *
- */
- protected void buildVfModuleNetworkName(Map<String,Object> paramsMap, String keyPrefix, String vnicSubInterfaces) {
+ if (!floatingV6.isEmpty()) {
+ floatingV6 = Collections.singletonList(floatingV6.get(0));
+ }
+ addPairToMap(paramsMap, keyPrefix, FLOATING_V6_IP, floatingV6);
+ }
- List<String> neworkNames = jsonPath.locateResultList(vnicSubInterfaces, "$.sub-interface-network-data[*].network-name");
+ protected void addPairToMap(Map<String, Object> paramsMap, String keyPrefix, String key, String value) {
- addPairToMap(paramsMap, keyPrefix, NET_NAMES, neworkNames);
- }
+ addPairToMap(paramsMap, keyPrefix, key, Collections.singletonList(value));
+ }
- /*
- * Build "network_id" for Heat Template
- * Building Criteria : {vm-type}_{index}_subint_{network-role}_port_{index}_net_ids
- * vmTypeKey = vm-type, networkRoleKey = common-sub-interface-role
- * Example: fw_0_subint_ctrl_port_0_net_ids
- *
- */
- protected void buildVfModuleNetworkId(Map<String,Object> paramsMap, String keyPrefix, String vnicSubInterfaces) {
+ protected void addPairToMap(Map<String, Object> paramsMap, String keyPrefix, String key, List<String> value) {
- List<String> neworkIds = jsonPath.locateResultList(vnicSubInterfaces, "$.sub-interface-network-data[*].network-id");
+ if (!value.isEmpty()) {
+ paramsMap.put(keyPrefix + key, Joiner.on(",").join(value));
+ }
+ }
- addPairToMap(paramsMap, keyPrefix, NET_IDS, neworkIds);
- }
-
- /*
- * Build ip_address for V4 for Heat Template
- * Building Criteria :
- * {vm-type}_{index}_subint_{network-role}_port_{index}_ip_{index} -- for ipV4
- * key = vm-type, networkRoleKey = NetWork-Role
- */
- protected void buildVfModuleIpV4AddressHeatTemplate(Map<String,Object> paramsMap, String keyPrefix, String vnicSubInterfaces) {
-
- List<String> ipv4Ips = jsonPath.locateResultList(vnicSubInterfaces, "$.sub-interface-network-data[*].network-information-items.network-information-item[?(@.ip-version == 'ipv4')].network-ips.network-ip[*]");
-
- addPairToMap(paramsMap, keyPrefix, IP, ipv4Ips);
-
- for (int i = 0; i < ipv4Ips.size(); i++) {
- addPairToMap(paramsMap, keyPrefix, IP + UNDERSCORE + i, ipv4Ips.get(i));
- }
-
- }
-
- /*
- * Build ip_address for Heat Template
- * Building Criteria :
- * {vm-type}_{index}_subint_{network-role}_port_{index}_v6_ip_{index} -- for ipV6
- * key = vm-type, networkRoleKey = NetWork-Role
- */
- protected void buildVfModuleIpV6AddressHeatTemplate(Map<String,Object> paramsMap, String keyPrefix, String vnicSubInterfaces) {
-
- List<String> ipv6Ips = jsonPath.locateResultList(vnicSubInterfaces, "$.sub-interface-network-data[*].network-information-items.network-information-item[?(@.ip-version == 'ipv6')].network-ips.network-ip[*]");
-
- addPairToMap(paramsMap, keyPrefix, V6_IP, ipv6Ips);
-
- for (int i = 0; i < ipv6Ips.size(); i++) {
- addPairToMap(paramsMap, keyPrefix, V6_IP + UNDERSCORE + i, ipv6Ips.get(i));
- }
- }
-
- /*
- * Build floatingip_address for Heat Template
- * Building Criteria :
- * {vm-type}_subint_{network-role}_port_{index}_floating_ip -- for ipV4
- */
- protected void buildVfModuleFloatingIpV4HeatTemplate(Map<String,Object> paramsMap, String keyPrefix, String vnicSubInterfaces) {
-
- List<String> floatingV4 = jsonPath.locateResultList(vnicSubInterfaces, "$.sub-interface-network-data[*].floating-ips.floating-ip-v4[*]");
-
- if (!floatingV4.isEmpty()) {
- floatingV4 = Collections.singletonList(floatingV4.get(0));
- }
- addPairToMap(paramsMap, keyPrefix, FLOATING_IP, floatingV4);
-
- }
-
- /*
- * Build floatingip_address for Heat Template
- * Building Criteria :
- * {vm-type}_subint_{network-role}_port_{index}_floating_v6_ip -- for ipV6
- */
- protected void buildVfModuleFloatingIpV6HeatTemplate(Map<String,Object> paramsMap, String keyPrefix, String vnicSubInterfaces) {
-
- List<String> floatingV6 = jsonPath.locateResultList(vnicSubInterfaces, "$.sub-interface-network-data[*].floating-ips.floating-ip-v6[*]");
-
- if (!floatingV6.isEmpty()) {
- floatingV6 = Collections.singletonList(floatingV6.get(0));
- }
- addPairToMap(paramsMap, keyPrefix, FLOATING_V6_IP, floatingV6);
- }
-
- protected void addPairToMap(Map<String, Object> paramsMap, String keyPrefix, String key, String value) {
-
- addPairToMap(paramsMap, keyPrefix, key, Collections.singletonList(value));
- }
-
- protected void addPairToMap(Map<String, Object> paramsMap, String keyPrefix, String key, List<String> value) {
-
- if (!value.isEmpty()) {
- paramsMap.put(keyPrefix + key, Joiner.on(",").join(value));
- }
- }
-
- private void buildParamsMapFromSdncParams(Map<String,Object> paramsMap, GenericResourceApiParam parametersData) {
- if (parametersData != null) {
- List<GenericResourceApiParamParam> paramsList = parametersData.getParam();
- if (paramsList != null) {
- for (int i = 0; i < paramsList.size(); i++) {
- GenericResourceApiParamParam param = paramsList.get(i);
- String parameterName = param.getName();
- if (!sdncResponseParamsToSkip.contains(parameterName)) {
- String parameterValue = param.getValue();
- paramsMap.put(parameterName, parameterValue);
- }
- }
- }
- }
- }
-
- private Map<String,String> buildNetworkRoleMap(GenericResourceApiVfmoduletopologyVfModuleTopology vfModuleTopology) throws JsonParseException, JsonMappingException, IOException {
- Map<String, String> networkRoleMap = new HashMap<>();
- GenericResourceApiVfmoduleassignmentsVfModuleAssignments vfModuleAssignments = vfModuleTopology.getVfModuleAssignments();
- if (vfModuleAssignments != null) {
- GenericResourceApiVfmoduleassignmentsVfmoduleassignmentsVms vms = vfModuleAssignments.getVms();
- if (vms != null) {
- List<GenericResourceApiVmTopologyData> vmsList = vms.getVm();
- if (vmsList != null) {
- for (GenericResourceApiVmTopologyData vm : vmsList){
- GenericResourceApiVmtopologydataVmNetworks vmNetworks = vm.getVmNetworks();
- if (vmNetworks != null) {
- List<GenericResourceApiVmNetworkData> vmNetworksList = vmNetworks.getVmNetwork();
- if (vmNetworksList != null) {
- for(int n = 0; n < vmNetworksList.size(); n++){
- GenericResourceApiVmNetworkData network = vmNetworksList.get(n);
- String networkRole = network.getNetworkRole();
- String networkRoleValue = network.getNetworkRoleTag();
- if (networkRoleValue == null || networkRoleValue.isEmpty()) {
- networkRoleValue = networkRole;
- }
- networkRoleMap.put(networkRole, networkRoleValue);
- }
- }
- }
- }
- }
- }
- }
- return networkRoleMap;
- }
-
- public DeleteVfModuleRequest deleteVfModuleRequestMapper(RequestContext requestContext,CloudRegion cloudRegion,
- ServiceInstance serviceInstance, GenericVnf genericVnf,
- VfModule vfModule) throws IOException {
- DeleteVfModuleRequest deleteVfModuleRequest = new DeleteVfModuleRequest();
- deleteVfModuleRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
- deleteVfModuleRequest.setCloudOwner(cloudRegion.getCloudOwner());
- deleteVfModuleRequest.setTenantId(cloudRegion.getTenantId());
- deleteVfModuleRequest.setVnfId(genericVnf.getVnfId());
- deleteVfModuleRequest.setVfModuleId(vfModule.getVfModuleId());
- if (!StringUtils.isEmpty(vfModule.getHeatStackId())){
- deleteVfModuleRequest.setVfModuleStackId(vfModule.getHeatStackId());//DoDVfMod_heatStackId
- } else
- {
- deleteVfModuleRequest.setVfModuleStackId(vfModule.getVfModuleName());
- }
-
- deleteVfModuleRequest.setSkipAAI(true);
- setIdAndUrl(deleteVfModuleRequest);
- MsoRequest msoRequest = buildMsoRequest(requestContext, serviceInstance);
- deleteVfModuleRequest.setMsoRequest(msoRequest);
- return deleteVfModuleRequest;
- }
-
- protected void setIdAndUrl(DeleteVfModuleRequest deleteVfModuleRequest) throws UnsupportedEncodingException{
- String messageId = vnfAdapterObjectMapperUtils.getRandomUuid();
- deleteVfModuleRequest.setMessageId(messageId);
- deleteVfModuleRequest.setNotificationUrl(vnfAdapterObjectMapperUtils.createCallbackUrl("VNFAResponse", messageId));
- }
-
- private String convertToString(Object obj) {
- String json;
- try {
- json = mapper.writeValueAsString(obj);
- } catch (JsonProcessingException e) {
- json = "{}";
- }
-
- return json;
- }
-
- private VfModule getBaseVfModule(GenericVnf genericVnf) {
- List<VfModule> vfModules = genericVnf.getVfModules();
- VfModule baseVfModule = null;
- if (vfModules != null) {
- for(int i = 0; i < vfModules.size(); i++) {
- if (vfModules.get(i).getModelInfoVfModule().getIsBaseBoolean()) {
- baseVfModule = vfModules.get(i);
- break;
- }
- }
- }
- return baseVfModule;
- }
+ private void buildParamsMapFromSdncParams(Map<String, Object> paramsMap, GenericResourceApiParam parametersData) {
+ if (parametersData != null) {
+ List<GenericResourceApiParamParam> paramsList = parametersData.getParam();
+ if (paramsList != null) {
+ for (int i = 0; i < paramsList.size(); i++) {
+ GenericResourceApiParamParam param = paramsList.get(i);
+ String parameterName = param.getName();
+ if (!sdncResponseParamsToSkip.contains(parameterName)) {
+ String parameterValue = param.getValue();
+ paramsMap.put(parameterName, parameterValue);
+ }
+ }
+ }
+ }
+ }
+
+ private Map<String, String> buildNetworkRoleMap(GenericResourceApiVfmoduletopologyVfModuleTopology vfModuleTopology)
+ throws JsonParseException, JsonMappingException, IOException {
+ Map<String, String> networkRoleMap = new HashMap<>();
+ GenericResourceApiVfmoduleassignmentsVfModuleAssignments vfModuleAssignments =
+ vfModuleTopology.getVfModuleAssignments();
+ if (vfModuleAssignments != null) {
+ GenericResourceApiVfmoduleassignmentsVfmoduleassignmentsVms vms = vfModuleAssignments.getVms();
+ if (vms != null) {
+ List<GenericResourceApiVmTopologyData> vmsList = vms.getVm();
+ if (vmsList != null) {
+ for (GenericResourceApiVmTopologyData vm : vmsList) {
+ GenericResourceApiVmtopologydataVmNetworks vmNetworks = vm.getVmNetworks();
+ if (vmNetworks != null) {
+ List<GenericResourceApiVmNetworkData> vmNetworksList = vmNetworks.getVmNetwork();
+ if (vmNetworksList != null) {
+ for (int n = 0; n < vmNetworksList.size(); n++) {
+ GenericResourceApiVmNetworkData network = vmNetworksList.get(n);
+ String networkRole = network.getNetworkRole();
+ String networkRoleValue = network.getNetworkRoleTag();
+ if (networkRoleValue == null || networkRoleValue.isEmpty()) {
+ networkRoleValue = networkRole;
+ }
+ networkRoleMap.put(networkRole, networkRoleValue);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return networkRoleMap;
+ }
+
+ public DeleteVfModuleRequest deleteVfModuleRequestMapper(RequestContext requestContext, CloudRegion cloudRegion,
+ ServiceInstance serviceInstance, GenericVnf genericVnf, VfModule vfModule) throws IOException {
+ DeleteVfModuleRequest deleteVfModuleRequest = new DeleteVfModuleRequest();
+ deleteVfModuleRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+ deleteVfModuleRequest.setCloudOwner(cloudRegion.getCloudOwner());
+ deleteVfModuleRequest.setTenantId(cloudRegion.getTenantId());
+ deleteVfModuleRequest.setVnfId(genericVnf.getVnfId());
+ deleteVfModuleRequest.setVfModuleId(vfModule.getVfModuleId());
+ if (!StringUtils.isEmpty(vfModule.getHeatStackId())) {
+ deleteVfModuleRequest.setVfModuleStackId(vfModule.getHeatStackId());// DoDVfMod_heatStackId
+ } else {
+ deleteVfModuleRequest.setVfModuleStackId(vfModule.getVfModuleName());
+ }
+
+ deleteVfModuleRequest.setSkipAAI(true);
+ setIdAndUrl(deleteVfModuleRequest);
+ MsoRequest msoRequest = buildMsoRequest(requestContext, serviceInstance);
+ deleteVfModuleRequest.setMsoRequest(msoRequest);
+ return deleteVfModuleRequest;
+ }
+
+ protected void setIdAndUrl(DeleteVfModuleRequest deleteVfModuleRequest) throws UnsupportedEncodingException {
+ String messageId = vnfAdapterObjectMapperUtils.getRandomUuid();
+ deleteVfModuleRequest.setMessageId(messageId);
+ deleteVfModuleRequest
+ .setNotificationUrl(vnfAdapterObjectMapperUtils.createCallbackUrl("VNFAResponse", messageId));
+ }
+
+ private String convertToString(Object obj) {
+ String json;
+ try {
+ json = mapper.writeValueAsString(obj);
+ } catch (JsonProcessingException e) {
+ json = "{}";
+ }
+
+ return json;
+ }
+
+ private VfModule getBaseVfModule(GenericVnf genericVnf) {
+ List<VfModule> vfModules = genericVnf.getVfModules();
+ VfModule baseVfModule = null;
+ if (vfModules != null) {
+ for (int i = 0; i < vfModules.size(); i++) {
+ if (vfModules.get(i).getModelInfoVfModule().getIsBaseBoolean()) {
+ baseVfModule = vfModules.get(i);
+ break;
+ }
+ }
+ }
+ return baseVfModule;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClient.java
index 9613fbdcf1..593426a85f 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClient.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClient.java
@@ -25,7 +25,6 @@ package org.onap.so.client.namingservice;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-
import org.onap.namingservice.model.NameGenDeleteRequest;
import org.onap.namingservice.model.NameGenDeleteResponse;
import org.onap.namingservice.model.NameGenRequest;
@@ -47,53 +46,53 @@ import org.springframework.web.client.RestTemplate;
@Component
-public class NamingClient{
- private static final Logger logger = LoggerFactory.getLogger(NamingClient.class);
- private static final String ENDPOINT = "mso.naming.endpoint";
- private static final String AUTH = "mso.naming.auth";
-
- @Autowired
- private RestTemplate restTemplate;
- @Autowired
+public class NamingClient {
+ private static final Logger logger = LoggerFactory.getLogger(NamingClient.class);
+ private static final String ENDPOINT = "mso.naming.endpoint";
+ private static final String AUTH = "mso.naming.auth";
+
+ @Autowired
+ private RestTemplate restTemplate;
+ @Autowired
private Environment env;
- @Autowired
- private NamingClientResponseValidator namingClientResponseValidator;
-
- public String postNameGenRequest(NameGenRequest request) throws BadResponseException, IOException {
- String targetUrl = env.getProperty(ENDPOINT);
- HttpHeaders headers = setHeaders(env.getProperty(AUTH));
- logger.info("Sending postNameGenRequest to url: {}", targetUrl);
- HttpEntity<NameGenRequest> requestEntity = new HttpEntity<>(request, headers);
- ResponseEntity<NameGenResponse> response;
- try{
- response = restTemplate.postForEntity(targetUrl, requestEntity, NameGenResponse.class);
- }catch(HttpStatusCodeException e){
- throw new BadResponseException(namingClientResponseValidator.formatError(e));
- }
- return namingClientResponseValidator.validateNameGenResponse(response);
- }
+ @Autowired
+ private NamingClientResponseValidator namingClientResponseValidator;
+
+ public String postNameGenRequest(NameGenRequest request) throws BadResponseException, IOException {
+ String targetUrl = env.getProperty(ENDPOINT);
+ HttpHeaders headers = setHeaders(env.getProperty(AUTH));
+ logger.info("Sending postNameGenRequest to url: {}", targetUrl);
+ HttpEntity<NameGenRequest> requestEntity = new HttpEntity<>(request, headers);
+ ResponseEntity<NameGenResponse> response;
+ try {
+ response = restTemplate.postForEntity(targetUrl, requestEntity, NameGenResponse.class);
+ } catch (HttpStatusCodeException e) {
+ throw new BadResponseException(namingClientResponseValidator.formatError(e));
+ }
+ return namingClientResponseValidator.validateNameGenResponse(response);
+ }
- public String deleteNameGenRequest(NameGenDeleteRequest request) throws BadResponseException, IOException {
- String targetUrl = env.getProperty(ENDPOINT);
- HttpHeaders headers = setHeaders(env.getProperty(AUTH));
- logger.info("Sending deleteNameGenRequest to url: {}", targetUrl);
- HttpEntity<NameGenDeleteRequest> requestEntity = new HttpEntity<>(request, headers);
- ResponseEntity<NameGenDeleteResponse> response;
- try{
- response = restTemplate.exchange(targetUrl, HttpMethod.DELETE, requestEntity, NameGenDeleteResponse.class);
- }catch(HttpStatusCodeException e){
- throw new BadResponseException(namingClientResponseValidator.formatError(e));
- }
- return namingClientResponseValidator.validateNameGenDeleteResponse(response);
- }
+ public String deleteNameGenRequest(NameGenDeleteRequest request) throws BadResponseException, IOException {
+ String targetUrl = env.getProperty(ENDPOINT);
+ HttpHeaders headers = setHeaders(env.getProperty(AUTH));
+ logger.info("Sending deleteNameGenRequest to url: {}", targetUrl);
+ HttpEntity<NameGenDeleteRequest> requestEntity = new HttpEntity<>(request, headers);
+ ResponseEntity<NameGenDeleteResponse> response;
+ try {
+ response = restTemplate.exchange(targetUrl, HttpMethod.DELETE, requestEntity, NameGenDeleteResponse.class);
+ } catch (HttpStatusCodeException e) {
+ throw new BadResponseException(namingClientResponseValidator.formatError(e));
+ }
+ return namingClientResponseValidator.validateNameGenDeleteResponse(response);
+ }
- private HttpHeaders setHeaders(String auth) {
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_JSON);
- List<MediaType> acceptableMediaTypes = new ArrayList<>();
- acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
- headers.setAccept(acceptableMediaTypes);
- headers.add(HttpHeaders.AUTHORIZATION, auth);
- return headers;
- }
+ private HttpHeaders setHeaders(String auth) {
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.APPLICATION_JSON);
+ List<MediaType> acceptableMediaTypes = new ArrayList<>();
+ acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
+ headers.setAccept(acceptableMediaTypes);
+ headers.add(HttpHeaders.AUTHORIZATION, auth);
+ return headers;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClientResponseValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClientResponseValidator.java
index 8456f26239..717bb04099 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClientResponseValidator.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClientResponseValidator.java
@@ -24,7 +24,6 @@ package org.onap.so.client.namingservice;
import java.io.IOException;
import java.util.List;
-
import org.apache.http.HttpStatus;
import org.onap.namingservice.model.NameGenDeleteResponse;
import org.onap.namingservice.model.NameGenResponse;
@@ -38,113 +37,113 @@ import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpStatusCodeException;
-
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class NamingClientResponseValidator {
- private static final Logger logger = LoggerFactory.getLogger(NamingClientResponseValidator.class);
- private static final String INSTANCE_GROUP_NAME = "instance-group-name";
- private static final String NO_RESPONSE_FROM_NAMING_SERVICE = "Error did not receive a response from Naming Service.";
- private static final String NULL_RESPONSE_FROM_NAMING_SERVICE = "Error received a null response from Naming Service.";
- private static final String NAMING_SERVICE_ERROR = "Error from Naming Service: %s";
-
- public String validateNameGenResponse(ResponseEntity<NameGenResponse> response) throws BadResponseException {
- if (response == null) {
- logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), NO_RESPONSE_FROM_NAMING_SERVICE,
- "BPMN", ErrorCode.UnknownError.getValue(),
- NO_RESPONSE_FROM_NAMING_SERVICE);
- throw new BadResponseException(NO_RESPONSE_FROM_NAMING_SERVICE);
- }
-
+ private static final Logger logger = LoggerFactory.getLogger(NamingClientResponseValidator.class);
+ private static final String INSTANCE_GROUP_NAME = "instance-group-name";
+ private static final String NO_RESPONSE_FROM_NAMING_SERVICE =
+ "Error did not receive a response from Naming Service.";
+ private static final String NULL_RESPONSE_FROM_NAMING_SERVICE =
+ "Error received a null response from Naming Service.";
+ private static final String NAMING_SERVICE_ERROR = "Error from Naming Service: %s";
+
+ public String validateNameGenResponse(ResponseEntity<NameGenResponse> response) throws BadResponseException {
+ if (response == null) {
+ logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), NO_RESPONSE_FROM_NAMING_SERVICE,
+ "BPMN", ErrorCode.UnknownError.getValue(), NO_RESPONSE_FROM_NAMING_SERVICE);
+ throw new BadResponseException(NO_RESPONSE_FROM_NAMING_SERVICE);
+ }
+
int responseCode = response.getStatusCodeValue();
String generatedName = "";
NameGenResponse responseBody = response.getBody();
if (responseBody == null) {
- logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), NULL_RESPONSE_FROM_NAMING_SERVICE,
- "BPMN", ErrorCode.UnknownError.getValue(),
- NULL_RESPONSE_FROM_NAMING_SERVICE);
- throw new BadResponseException(NULL_RESPONSE_FROM_NAMING_SERVICE);
- }
-
- if (isHttpCodeSuccess(responseCode)) {
- logger.info("Successful Response from Naming Service");
- List<Respelement> respList = responseBody.getElements();
-
- if (respList != null) {
- for (int i=0; i < respList.size(); i++) {
- Respelement respElement = respList.get(i);
- if (respElement != null) {
- String resourceName = respElement.getResourceName();
- if (INSTANCE_GROUP_NAME.equals(resourceName)) {
- generatedName = respElement.getResourceValue();
- break;
- }
- }
- }
- }
- return generatedName;
- } else {
- NameGenResponseError error = responseBody.getError();
- String errorMessageString = NAMING_SERVICE_ERROR;
- if (error != null) {
- errorMessageString = error.getMessage();
- }
- String errorMessage = String.format(NAMING_SERVICE_ERROR, errorMessageString);
- logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), errorMessage, "BPMN",
- ErrorCode.DataError.getValue(), errorMessage);
- throw new BadResponseException(errorMessage);
- }
- }
-
- public String validateNameGenDeleteResponse(ResponseEntity<NameGenDeleteResponse> response) throws BadResponseException {
- if (response == null) {
- logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), NO_RESPONSE_FROM_NAMING_SERVICE,
- "BPMN", ErrorCode.UnknownError.getValue(),
- NO_RESPONSE_FROM_NAMING_SERVICE);
- throw new BadResponseException(NO_RESPONSE_FROM_NAMING_SERVICE);
- }
-
+ logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(),
+ NULL_RESPONSE_FROM_NAMING_SERVICE, "BPMN", ErrorCode.UnknownError.getValue(),
+ NULL_RESPONSE_FROM_NAMING_SERVICE);
+ throw new BadResponseException(NULL_RESPONSE_FROM_NAMING_SERVICE);
+ }
+
+ if (isHttpCodeSuccess(responseCode)) {
+ logger.info("Successful Response from Naming Service");
+ List<Respelement> respList = responseBody.getElements();
+
+ if (respList != null) {
+ for (int i = 0; i < respList.size(); i++) {
+ Respelement respElement = respList.get(i);
+ if (respElement != null) {
+ String resourceName = respElement.getResourceName();
+ if (INSTANCE_GROUP_NAME.equals(resourceName)) {
+ generatedName = respElement.getResourceValue();
+ break;
+ }
+ }
+ }
+ }
+ return generatedName;
+ } else {
+ NameGenResponseError error = responseBody.getError();
+ String errorMessageString = NAMING_SERVICE_ERROR;
+ if (error != null) {
+ errorMessageString = error.getMessage();
+ }
+ String errorMessage = String.format(NAMING_SERVICE_ERROR, errorMessageString);
+ logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), errorMessage, "BPMN",
+ ErrorCode.DataError.getValue(), errorMessage);
+ throw new BadResponseException(errorMessage);
+ }
+ }
+
+ public String validateNameGenDeleteResponse(ResponseEntity<NameGenDeleteResponse> response)
+ throws BadResponseException {
+ if (response == null) {
+ logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), NO_RESPONSE_FROM_NAMING_SERVICE,
+ "BPMN", ErrorCode.UnknownError.getValue(), NO_RESPONSE_FROM_NAMING_SERVICE);
+ throw new BadResponseException(NO_RESPONSE_FROM_NAMING_SERVICE);
+ }
+
int responseCode = response.getStatusCodeValue();
String responseMessage = "";
NameGenDeleteResponse responseBody = response.getBody();
if (responseBody == null) {
- logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), NULL_RESPONSE_FROM_NAMING_SERVICE,
- "BPMN", ErrorCode.UnknownError.getValue(),
- NULL_RESPONSE_FROM_NAMING_SERVICE);
- throw new BadResponseException(NULL_RESPONSE_FROM_NAMING_SERVICE);
- }
-
- if (isHttpCodeSuccess(responseCode)) {
- logger.info("Successful Response from Naming Service");
- return responseMessage;
- } else {
- String errorMessageString = NAMING_SERVICE_ERROR;
-
- String errorMessage = String.format(NAMING_SERVICE_ERROR, errorMessageString);
- logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), errorMessage, "BPMN",
- ErrorCode.DataError.getValue(), errorMessage);
- throw new BadResponseException(errorMessage);
- }
- }
-
- private boolean isHttpCodeSuccess(int code) {
+ logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(),
+ NULL_RESPONSE_FROM_NAMING_SERVICE, "BPMN", ErrorCode.UnknownError.getValue(),
+ NULL_RESPONSE_FROM_NAMING_SERVICE);
+ throw new BadResponseException(NULL_RESPONSE_FROM_NAMING_SERVICE);
+ }
+
+ if (isHttpCodeSuccess(responseCode)) {
+ logger.info("Successful Response from Naming Service");
+ return responseMessage;
+ } else {
+ String errorMessageString = NAMING_SERVICE_ERROR;
+
+ String errorMessage = String.format(NAMING_SERVICE_ERROR, errorMessageString);
+ logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), errorMessage, "BPMN",
+ ErrorCode.DataError.getValue(), errorMessage);
+ throw new BadResponseException(errorMessage);
+ }
+ }
+
+ private boolean isHttpCodeSuccess(int code) {
return code >= HttpStatus.SC_OK && code < HttpStatus.SC_MULTIPLE_CHOICES || code == 0;
}
-
- protected String formatError(HttpStatusCodeException e) throws IOException {
- ObjectMapper mapper = new ObjectMapper();
- NameGenResponse errorResponse = mapper.readValue(e.getResponseBodyAsString(), NameGenResponse.class);
- NameGenResponseError error = errorResponse.getError();
-
- String errorMessageString = null;
- if (error != null) {
- errorMessageString = error.getMessage();
- }
- String errorMessage = String.format(NAMING_SERVICE_ERROR, errorMessageString);
- logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), errorMessage, "BPMN",
- ErrorCode.DataError.getValue(), errorMessage);
- return errorMessage;
- }
+
+ protected String formatError(HttpStatusCodeException e) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ NameGenResponse errorResponse = mapper.readValue(e.getResponseBodyAsString(), NameGenResponse.class);
+ NameGenResponseError error = errorResponse.getError();
+
+ String errorMessageString = null;
+ if (error != null) {
+ errorMessageString = error.getMessage();
+ }
+ String errorMessage = String.format(NAMING_SERVICE_ERROR, errorMessageString);
+ logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), errorMessage, "BPMN",
+ ErrorCode.DataError.getValue(), errorMessage);
+ return errorMessage;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingRequestObjectBuilder.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingRequestObjectBuilder.java
index ba9f170d71..a4e68f8100 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingRequestObjectBuilder.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingRequestObjectBuilder.java
@@ -21,7 +21,6 @@
package org.onap.so.client.namingservice;
import java.util.List;
-
import org.onap.namingservice.model.Deleteelement;
import org.onap.namingservice.model.Element;
import org.onap.namingservice.model.NameGenDeleteRequest;
@@ -29,30 +28,34 @@ import org.onap.namingservice.model.NameGenRequest;
import org.springframework.stereotype.Component;
@Component
-public class NamingRequestObjectBuilder{
-
- public Element elementMapper(String instanceGroupId, String policyInstanceName, String namingType, String nfNamingCode, String instanceGroupName){
- Element element = new Element();
- element.put("external-key", instanceGroupId);
- element.put("policy-instance-name", policyInstanceName);
- element.put("naming-type", namingType);
- element.put("resource-name", instanceGroupName);
- element.put("nf-naming-code", nfNamingCode);
- return element;
- }
- public Deleteelement deleteElementMapper(String instanceGroupId){
- Deleteelement deleteElement = new Deleteelement();
- deleteElement.setExternalKey(instanceGroupId);
- return deleteElement;
- }
- public NameGenRequest nameGenRequestMapper(List<Element> elements){
- NameGenRequest nameGenRequest = new NameGenRequest();
- nameGenRequest.setElements(elements);
- return nameGenRequest;
- }
- public NameGenDeleteRequest nameGenDeleteRequestMapper(List<Deleteelement> deleteElements){
- NameGenDeleteRequest nameGenDeleteRequest = new NameGenDeleteRequest();
- nameGenDeleteRequest.setElements(deleteElements);
- return nameGenDeleteRequest;
- }
+public class NamingRequestObjectBuilder {
+
+ public Element elementMapper(String instanceGroupId, String policyInstanceName, String namingType,
+ String nfNamingCode, String instanceGroupName) {
+ Element element = new Element();
+ element.put("external-key", instanceGroupId);
+ element.put("policy-instance-name", policyInstanceName);
+ element.put("naming-type", namingType);
+ element.put("resource-name", instanceGroupName);
+ element.put("nf-naming-code", nfNamingCode);
+ return element;
+ }
+
+ public Deleteelement deleteElementMapper(String instanceGroupId) {
+ Deleteelement deleteElement = new Deleteelement();
+ deleteElement.setExternalKey(instanceGroupId);
+ return deleteElement;
+ }
+
+ public NameGenRequest nameGenRequestMapper(List<Element> elements) {
+ NameGenRequest nameGenRequest = new NameGenRequest();
+ nameGenRequest.setElements(elements);
+ return nameGenRequest;
+ }
+
+ public NameGenDeleteRequest nameGenDeleteRequestMapper(List<Deleteelement> deleteElements) {
+ NameGenDeleteRequest nameGenDeleteRequest = new NameGenDeleteRequest();
+ nameGenDeleteRequest.setElements(deleteElements);
+ return nameGenDeleteRequest;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofClient.java
index fa039c235c..e31285f044 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofClient.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofClient.java
@@ -34,7 +34,6 @@ import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.LinkedHashMap;
@@ -54,15 +53,14 @@ public class OofClient {
/**
- * Makes a rest call to oof to perform homing and licensing for a
- * list of demands
+ * Makes a rest call to oof to perform homing and licensing for a list of demands
*
* @param homingRequest
* @return
* @throws JsonProcessingException
* @throws BpmnError
*/
- public void postDemands(OofRequest homingRequest) throws BadResponseException, JsonProcessingException{
+ public void postDemands(OofRequest homingRequest) throws BadResponseException, JsonProcessingException {
logger.trace("Started oof Client Post Demands");
String url = oofProperties.getHost() + oofProperties.getUri();
logger.debug("Post demands url: " + url);
@@ -79,7 +77,8 @@ public class OofClient {
baseClient.setTargetUrl(url);
baseClient.setHttpHeader(header);
- LinkedHashMap<?, ?> response = baseClient.post(homingRequest.toJsonString(), new ParameterizedTypeReference<LinkedHashMap<? ,?>>() {});
+ LinkedHashMap<?, ?> response =
+ baseClient.post(homingRequest.toJsonString(), new ParameterizedTypeReference<LinkedHashMap<?, ?>>() {});
validator.validateDemandsResponse(response);
logger.trace("Completed OOF Client Post Demands");
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofValidator.java
index 252ff0d6a6..abbf52e38c 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofValidator.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofValidator.java
@@ -26,9 +26,7 @@ import org.onap.so.client.exception.BadResponseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-
import java.util.LinkedHashMap;
-
import static org.apache.commons.lang.StringUtils.isNotBlank;
@@ -44,55 +42,54 @@ public class OofValidator {
*/
public void validateDemandsResponse(LinkedHashMap<?, ?> response) throws BadResponseException {
logger.debug("Validating oofs synchronous response");
- if(!response.isEmpty()){
+ if (!response.isEmpty()) {
JSONObject jsonResponse = new JSONObject(response);
- if(jsonResponse.has("requestStatus")){
+ if (jsonResponse.has("requestStatus")) {
String status = jsonResponse.getString("requestStatus");
- if(status.equals("accepted")){
+ if (status.equals("accepted")) {
logger.debug("oofs synchronous response indicates accepted");
- }else{
+ } else {
String message = jsonResponse.getString("statusMessage");
- if(isNotBlank(message)){
+ if (isNotBlank(message)) {
logger.debug("oofs response indicates failed: " + message);
- }else{
+ } else {
logger.debug("oofs response indicates failed: no status message provided");
message = "error message not provided";
}
throw new BadResponseException("oofs synchronous response indicates failed: " + message);
}
- }else{
+ } else {
logger.debug("oofs synchronous response does not contain: request status");
throw new BadResponseException("oofs synchronous response does not contain: request status");
}
- }else{
+ } else {
logger.debug("oofs synchronous response is empty");
throw new BadResponseException("oofs synchronous response i is empty");
}
}
/**
- * Validates the asynchronous/callback response from oof which
- * contains the homing and licensing solutions
+ * Validates the asynchronous/callback response from oof which contains the homing and licensing solutions
*
* @throws BadResponseException
*/
- public void validateSolution(String response) throws BadResponseException{
+ public void validateSolution(String response) throws BadResponseException {
logger.debug("Validating oofs asynchronous callback response");
- if(isNotBlank(response)) {
+ if (isNotBlank(response)) {
JSONObject jsonResponse = new JSONObject(response);
- if(!jsonResponse.has("serviceException")){
+ if (!jsonResponse.has("serviceException")) {
logger.debug("oofs asynchronous response is valid");
- }else{
+ } else {
String message = jsonResponse.getJSONObject("serviceException").getString("text");
- if(isNotBlank(message)){
+ if (isNotBlank(message)) {
logger.debug("oofs response contains a service exception: " + message);
- }else{
+ } else {
logger.debug("oofs response contains a service exception: no service exception text provided");
message = "error message not provided";
}
throw new BadResponseException("oofs asynchronous response contains a service exception: " + message);
}
- }else{
+ } else {
logger.debug("oofs asynchronous response is empty");
throw new BadResponseException("oofs asynchronous response is empty");
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ModelInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ModelInfo.java
index f5fb87503a..433de22aba 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ModelInfo.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ModelInfo.java
@@ -24,18 +24,11 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
-
import java.io.Serializable;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "modelType",
- "modelInvariantId",
- "modelVersionId",
- "modelName",
- "modelVersion",
- "modelCustomizationName"
-})
+@JsonPropertyOrder({"modelType", "modelInvariantId", "modelVersionId", "modelName", "modelVersion",
+ "modelCustomizationName"})
@JsonRootName("modelInfo")
public class ModelInfo implements Serializable {
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofProperties.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofProperties.java
index 507eaeaf5e..84e29b6f2d 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofProperties.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofProperties.java
@@ -22,7 +22,6 @@ package org.onap.so.client.oof.beans;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
-
import java.util.Map;
@Configuration
@@ -38,25 +37,27 @@ public class OofProperties {
public String getHost() {
return host;
}
+
public void setHost(String host) {
this.host = host;
}
+
public String getUri() {
return uri;
}
+
public void setUri(String uri) {
this.uri = uri;
}
+
public Map<String, String> getHeaders() {
return headers;
}
+
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
-
-
-
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofRequest.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofRequest.java
index 58f0bfc9cc..e3c29fe04d 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofRequest.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofRequest.java
@@ -27,11 +27,10 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
import java.io.Serializable;
-public class OofRequest implements Serializable{
+public class OofRequest implements Serializable {
private static final long serialVersionUID = -1541132882892163132L;
private static final Logger logger = LoggerFactory.getLogger(OofRequest.class);
@@ -53,38 +52,45 @@ public class OofRequest implements Serializable{
public RequestInfo getRequestInformation() {
return requestInformation;
}
+
public void setRequestInformation(RequestInfo requestInformation) {
this.requestInformation = requestInformation;
}
+
public ServiceInfo getServiceInformation() {
return serviceInformation;
}
+
public void setServiceInformation(ServiceInfo serviceInformation) {
this.serviceInformation = serviceInformation;
}
+
public PlacementInfo getPlacementInformation() {
return placementInformation;
}
+
public void setPlacementInformation(PlacementInfo placementInformation) {
this.placementInformation = placementInformation;
}
+
public String getLicenseInformation() {
return licenseInformation;
}
+
public void setLicenseInformation(String licenseInformation) {
this.licenseInformation = licenseInformation;
}
@JsonInclude(Include.NON_NULL)
- public String toJsonString(){
+ public String toJsonString() {
String json = "";
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
- try{
+ try {
json = ow.writeValueAsString(this);
- }catch (Exception e){
+ } catch (Exception e) {
logger.error("Unable to convert oofRequest to string", e);
}
return json.replaceAll("\\\\", "");
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofRequestParameters.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofRequestParameters.java
index 621f5652a3..6c9e45c787 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofRequestParameters.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/OofRequestParameters.java
@@ -24,15 +24,10 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
-
import java.io.Serializable;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "customerLatitude",
- "customerLongitude",
- "customerName"
-})
+@JsonPropertyOrder({"customerLatitude", "customerLongitude", "customerName"})
@JsonRootName("requestParameters")
public class OofRequestParameters implements Serializable {
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/PlacementDemand.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/PlacementDemand.java
index 38728efcfb..73c100df6d 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/PlacementDemand.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/PlacementDemand.java
@@ -24,16 +24,10 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
-
import java.io.Serializable;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "resourceModuleName",
- "serviceResourceId",
- "tenantId",
- "resourceModelInfo"
-})
+@JsonPropertyOrder({"resourceModuleName", "serviceResourceId", "tenantId", "resourceModelInfo"})
@JsonRootName("placementDemand")
public class PlacementDemand implements Serializable {
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/PlacementInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/PlacementInfo.java
index 2a7dc9decb..0eb14d991a 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/PlacementInfo.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/PlacementInfo.java
@@ -28,11 +28,7 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "requestParameters",
- "subscriberInfo",
- "placementDemands"
-})
+@JsonPropertyOrder({"requestParameters", "subscriberInfo", "placementDemands"})
@JsonRootName("placementInfo")
public class PlacementInfo implements Serializable {
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/RequestInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/RequestInfo.java
index 6831fe54e9..0132ed56e9 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/RequestInfo.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/RequestInfo.java
@@ -28,16 +28,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "transactionId",
- "requestId",
- "callbackUrl",
- "sourceId",
- "requestType",
- "numSolutions",
- "optimizers",
- "timeout"
-})
+@JsonPropertyOrder({"transactionId", "requestId", "callbackUrl", "sourceId", "requestType", "numSolutions",
+ "optimizers", "timeout"})
@JsonRootName("requestInfo")
public class RequestInfo implements Serializable {
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/Resource.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/Resource.java
index fea7437a93..8d44c63571 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/Resource.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/Resource.java
@@ -21,10 +21,9 @@
package org.onap.so.client.oof.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import java.io.Serializable;
-public class Resource implements Serializable{
+public class Resource implements Serializable {
private static final long serialVersionUID = 5949861520571440421L;
@@ -34,19 +33,19 @@ public class Resource implements Serializable{
private String status;
- public String getServiceResourceId(){
+ public String getServiceResourceId() {
return serviceResourceId;
}
- public void setServiceResourceId(String serviceResourceId){
+ public void setServiceResourceId(String serviceResourceId) {
this.serviceResourceId = serviceResourceId;
}
- public String getStatus(){
+ public String getStatus() {
return status;
}
- public void setStatus(String status){
+ public void setStatus(String status) {
this.status = status;
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ResourceModelInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ResourceModelInfo.java
index e9257bcb0c..9d0352525d 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ResourceModelInfo.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ResourceModelInfo.java
@@ -23,7 +23,6 @@ package org.onap.so.client.oof.beans;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
-
import java.io.Serializable;
@JsonInclude(JsonInclude.Include.NON_NULL)
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ServiceInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ServiceInfo.java
index 0cfffbbff6..db0e2acd60 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ServiceInfo.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/ServiceInfo.java
@@ -24,15 +24,10 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
-
import java.io.Serializable;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "serviceInstanceId",
- "serviceName",
- "modelInfo"
-})
+@JsonPropertyOrder({"serviceInstanceId", "serviceName", "modelInfo"})
@JsonRootName("serviceInfo")
public class ServiceInfo implements Serializable {
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/SubscriberInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/SubscriberInfo.java
index 3218975095..8fef4c45e7 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/SubscriberInfo.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/beans/SubscriberInfo.java
@@ -24,15 +24,10 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
-
import java.io.Serializable;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "globalSubscriberId",
- "subscriberName",
- "subscriberCommonSiteId"
-})
+@JsonPropertyOrder({"globalSubscriberId", "subscriberName", "subscriberCommonSiteId"})
@JsonRootName("subscriberInfo")
public class SubscriberInfo implements Serializable {
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAICollectionResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAICollectionResources.java
index 4a9f01fa53..5df7518698 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAICollectionResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAICollectionResources.java
@@ -32,27 +32,29 @@ import org.springframework.stereotype.Component;
@Component
public class AAICollectionResources {
- @Autowired
- private InjectionHelper injectionHelper;
-
- @Autowired
- private AAIObjectMapper aaiObjectMapper;
-
- public void createCollection(Collection collection) {
- AAIResourceUri networkCollectionURI = AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, collection.getId());
- collection.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
- org.onap.aai.domain.yang.Collection aaiCollection = aaiObjectMapper.mapCollection(collection);
- injectionHelper.getAaiClient().create(networkCollectionURI, aaiCollection);
- }
-
- public void updateCollection(Collection collection) {
- AAIResourceUri networkCollectionURI = AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, collection.getId());
- org.onap.aai.domain.yang.Collection aaiCollection = aaiObjectMapper.mapCollection(collection);
- injectionHelper.getAaiClient().update(networkCollectionURI, aaiCollection);
- }
-
- public void deleteCollection(Collection collection) {
- AAIResourceUri instanceGroupUri = AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, collection.getId());
- injectionHelper.getAaiClient().delete(instanceGroupUri);
- }
+ @Autowired
+ private InjectionHelper injectionHelper;
+
+ @Autowired
+ private AAIObjectMapper aaiObjectMapper;
+
+ public void createCollection(Collection collection) {
+ AAIResourceUri networkCollectionURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, collection.getId());
+ collection.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
+ org.onap.aai.domain.yang.Collection aaiCollection = aaiObjectMapper.mapCollection(collection);
+ injectionHelper.getAaiClient().create(networkCollectionURI, aaiCollection);
+ }
+
+ public void updateCollection(Collection collection) {
+ AAIResourceUri networkCollectionURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, collection.getId());
+ org.onap.aai.domain.yang.Collection aaiCollection = aaiObjectMapper.mapCollection(collection);
+ injectionHelper.getAaiClient().update(networkCollectionURI, aaiCollection);
+ }
+
+ public void deleteCollection(Collection collection) {
+ AAIResourceUri instanceGroupUri = AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, collection.getId());
+ injectionHelper.getAaiClient().delete(instanceGroupUri);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java
index f412720af7..746f136e96 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java
@@ -21,9 +21,7 @@
package org.onap.so.client.orchestration;
import java.util.Optional;
-
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.bpmn.common.InjectionHelper;
import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration;
import org.onap.so.client.aai.AAIObjectType;
@@ -37,11 +35,11 @@ import org.springframework.stereotype.Component;
@Component
public class AAIConfigurationResources {
- @Autowired
- private InjectionHelper injectionHelper;
+ @Autowired
+ private InjectionHelper injectionHelper;
- @Autowired
- private AAIObjectMapper aaiObjectMapper;
+ @Autowired
+ private AAIObjectMapper aaiObjectMapper;
/**
* A&AI call to create configuration
@@ -49,14 +47,15 @@ public class AAIConfigurationResources {
* @param configuration
*/
public void createConfiguration(Configuration configuration) {
- AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configuration.getConfigurationId());
+ AAIResourceUri configurationURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configuration.getConfigurationId());
configuration.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
org.onap.aai.domain.yang.Configuration aaiConfiguration = aaiObjectMapper.mapConfiguration(configuration);
injectionHelper.getAaiClient().create(configurationURI, aaiConfiguration);
}
/**
- * method to get Configuration details from A&AI
+ * method to get Configuration details from A&AI
*
* @param configurationId
* @return
@@ -72,21 +71,24 @@ public class AAIConfigurationResources {
* @param configuration
*/
public void updateConfiguration(Configuration configuration) {
- AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configuration.getConfigurationId());
+ AAIResourceUri configurationURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configuration.getConfigurationId());
org.onap.aai.domain.yang.Configuration aaiConfiguration = aaiObjectMapper.mapConfiguration(configuration);
injectionHelper.getAaiClient().update(configurationURI, aaiConfiguration);
}
+
/**
* A&AI call to disconnect configuration relation with service instance
+ *
* @param configurationId
* @param serviceInstanceId
*/
- public void disconnectConfigurationToServiceInstance(String configurationId, String serviceInstanceId){
+ public void disconnectConfigurationToServiceInstance(String configurationId, String serviceInstanceId) {
AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId);
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstanceId);
- injectionHelper.getAaiClient().disconnect(configurationURI,serviceInstanceURI);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId);
+ injectionHelper.getAaiClient().disconnect(configurationURI, serviceInstanceURI);
}
/**
@@ -96,8 +98,10 @@ public class AAIConfigurationResources {
* @param vnrConfigurationId
*/
public void connectVrfConfigurationToVnrConfiguration(String vrfConfigurationId, String vnrConfigurationId) {
- AAIResourceUri vnrConfigurationUri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, vnrConfigurationId);
- AAIResourceUri vrfConfigurationUri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, vrfConfigurationId);
+ AAIResourceUri vnrConfigurationUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, vnrConfigurationId);
+ AAIResourceUri vrfConfigurationUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, vrfConfigurationId);
injectionHelper.getAaiClient().connect(vrfConfigurationUri, vnrConfigurationUri);
}
@@ -121,11 +125,11 @@ public class AAIConfigurationResources {
*/
public void connectConfigurationToServiceInstance(String configurationId, String serviceInstanceId) {
AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId);
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstanceId);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId);
injectionHelper.getAaiClient().connect(configurationURI, serviceInstanceURI);
}
-
+
/**
* A&AI call to add configuration relationship with service instance
*
@@ -133,10 +137,11 @@ public class AAIConfigurationResources {
* @param serviceInstanceId
* @param aaiLabel
*/
- public void connectConfigurationToServiceInstance(String configurationId, String serviceInstanceId, AAIEdgeLabel aaiLabel) {
+ public void connectConfigurationToServiceInstance(String configurationId, String serviceInstanceId,
+ AAIEdgeLabel aaiLabel) {
AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId);
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstanceId);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId);
injectionHelper.getAaiClient().connect(configurationURI, serviceInstanceURI, aaiLabel);
}
@@ -165,22 +170,22 @@ public class AAIConfigurationResources {
injectionHelper.getAaiClient().connect(configurationURI, vpnBindingURI);
}
- public void connectConfigurationToVfModule(String configurationId, String vnfId, String vfModuleId){
- AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId);
- AAIResourceUri vfModuleURI = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId);
- injectionHelper.getAaiClient().connect(configurationURI, vfModuleURI);
+ public void connectConfigurationToVfModule(String configurationId, String vnfId, String vfModuleId) {
+ AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId);
+ AAIResourceUri vfModuleURI = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId);
+ injectionHelper.getAaiClient().connect(configurationURI, vfModuleURI);
}
- public void connectConfigurationToVnfc(String configurationId, String vnfcName){
- AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId);
- AAIResourceUri vnfcURI = AAIUriFactory.createResourceUri(AAIObjectType.VNFC, vnfcName);
- injectionHelper.getAaiClient().connect(configurationURI, vnfcURI);
+ public void connectConfigurationToVnfc(String configurationId, String vnfcName) {
+ AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId);
+ AAIResourceUri vnfcURI = AAIUriFactory.createResourceUri(AAIObjectType.VNFC, vnfcName);
+ injectionHelper.getAaiClient().connect(configurationURI, vnfcURI);
}
- public void connectConfigurationToL3Network(String configurationId, String networkId){
- AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId);
- AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId);
- injectionHelper.getAaiClient().connect(configurationURI, networkURI);
+ public void connectConfigurationToL3Network(String configurationId, String networkId) {
+ AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId);
+ AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId);
+ injectionHelper.getAaiClient().connect(configurationURI, networkURI);
}
/**
@@ -192,30 +197,35 @@ public class AAIConfigurationResources {
AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId);
injectionHelper.getAaiClient().delete(aaiResourceUri);
}
+
/**
* method to delete Configuration details in A&AI
*
* @param configuration
*/
public void deleteConfiguration(Configuration configuration) {
- AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configuration.getConfigurationId());
+ AAIResourceUri aaiResourceUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configuration.getConfigurationId());
injectionHelper.getAaiClient().delete(aaiResourceUri);
}
/**
* Get Configuration from AAI using related Link
+ *
* @param relatedLink related link - URI
* @return AAI Configuration object
*/
- public Optional<org.onap.aai.domain.yang.Configuration> getConfigurationFromRelatedLink(String relatedLink){
- return injectionHelper.getAaiClient()
- .get(org.onap.aai.domain.yang.Configuration.class, AAIUriFactory.createResourceFromExistingURI(AAIObjectType.CONFIGURATION, UriBuilder.fromPath(relatedLink).build()));
+ public Optional<org.onap.aai.domain.yang.Configuration> getConfigurationFromRelatedLink(String relatedLink) {
+ return injectionHelper.getAaiClient().get(org.onap.aai.domain.yang.Configuration.class, AAIUriFactory
+ .createResourceFromExistingURI(AAIObjectType.CONFIGURATION, UriBuilder.fromPath(relatedLink).build()));
}
- public void updateOrchestrationStatusConfiguration(Configuration configuration, OrchestrationStatus orchestrationStatus) {
- AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configuration.getConfigurationId());
- configuration.setOrchestrationStatus(orchestrationStatus);
- org.onap.aai.domain.yang.Configuration aaiConfiguration = aaiObjectMapper.mapConfiguration(configuration);
- injectionHelper.getAaiClient().update(aaiResourceUri, aaiConfiguration);
- }
+ public void updateOrchestrationStatusConfiguration(Configuration configuration,
+ OrchestrationStatus orchestrationStatus) {
+ AAIResourceUri aaiResourceUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configuration.getConfigurationId());
+ configuration.setOrchestrationStatus(orchestrationStatus);
+ org.onap.aai.domain.yang.Configuration aaiConfiguration = aaiObjectMapper.mapConfiguration(configuration);
+ injectionHelper.getAaiClient().update(aaiResourceUri, aaiConfiguration);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIInstanceGroupResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIInstanceGroupResources.java
index c325dd75ee..c48593037a 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIInstanceGroupResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIInstanceGroupResources.java
@@ -21,7 +21,6 @@
package org.onap.so.client.orchestration;
import java.util.Optional;
-
import org.onap.so.bpmn.common.InjectionHelper;
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup;
@@ -36,45 +35,53 @@ import org.springframework.stereotype.Component;
@Component
public class AAIInstanceGroupResources {
- @Autowired
- private InjectionHelper injectionHelper;
-
- @Autowired
- private AAIObjectMapper aaiObjectMapper;
+ @Autowired
+ private InjectionHelper injectionHelper;
+
+ @Autowired
+ private AAIObjectMapper aaiObjectMapper;
+
+ public void createInstanceGroup(InstanceGroup instanceGroup) {
+ AAIResourceUri instanceGroupUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
+ org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = aaiObjectMapper.mapInstanceGroup(instanceGroup);
+ injectionHelper.getAaiClient().createIfNotExists(instanceGroupUri, Optional.of(aaiInstanceGroup));
+ }
+
+ public void deleteInstanceGroup(InstanceGroup instanceGroup) {
+ AAIResourceUri instanceGroupUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
+ injectionHelper.getAaiClient().delete(instanceGroupUri);
+ }
+
+ public void connectInstanceGroupToVnf(InstanceGroup instanceGroup, GenericVnf vnf) {
+ AAIResourceUri instanceGroupUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
+ AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
+ injectionHelper.getAaiClient().connect(instanceGroupUri, vnfURI);
+ }
+
+ public void connectInstanceGroupToVnf(InstanceGroup instanceGroup, GenericVnf vnf, AAIEdgeLabel aaiLabel) {
+ AAIResourceUri instanceGroupUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
+ AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
+ injectionHelper.getAaiClient().connect(instanceGroupUri, vnfURI, aaiLabel);
+ }
- public void createInstanceGroup(InstanceGroup instanceGroup) {
- AAIResourceUri instanceGroupUri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
- org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = aaiObjectMapper.mapInstanceGroup(instanceGroup);
- injectionHelper.getAaiClient().createIfNotExists(instanceGroupUri, Optional.of(aaiInstanceGroup));
- }
-
- public void deleteInstanceGroup(InstanceGroup instanceGroup) {
- AAIResourceUri instanceGroupUri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
- injectionHelper.getAaiClient().delete(instanceGroupUri);
- }
+ public boolean exists(InstanceGroup instanceGroup) {
+ AAIResourceUri instanceGroupUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
+ return injectionHelper.getAaiClient().exists(instanceGroupUri);
+ }
- public void connectInstanceGroupToVnf(InstanceGroup instanceGroup, GenericVnf vnf) {
- AAIResourceUri instanceGroupUri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
- AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
- injectionHelper.getAaiClient().connect(instanceGroupUri, vnfURI);
- }
-
- public void connectInstanceGroupToVnf(InstanceGroup instanceGroup, GenericVnf vnf, AAIEdgeLabel aaiLabel) {
- AAIResourceUri instanceGroupUri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
- AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
- injectionHelper.getAaiClient().connect(instanceGroupUri, vnfURI, aaiLabel);
- }
-
- public boolean exists(InstanceGroup instanceGroup) {
- AAIResourceUri instanceGroupUri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
- return injectionHelper.getAaiClient().exists(instanceGroupUri);
- }
-
- public void createInstanceGroupandConnectServiceInstance(InstanceGroup instanceGroup, ServiceInstance serviceInstance) {
- AAIResourceUri instanceGroupUri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
- org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = aaiObjectMapper.mapInstanceGroup(instanceGroup);
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstance.getServiceInstanceId());
- injectionHelper.getAaiClient().createIfNotExists(instanceGroupUri, Optional.of(aaiInstanceGroup)).connect(instanceGroupUri, serviceInstanceURI);
- }
+ public void createInstanceGroupandConnectServiceInstance(InstanceGroup instanceGroup,
+ ServiceInstance serviceInstance) {
+ AAIResourceUri instanceGroupUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
+ org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = aaiObjectMapper.mapInstanceGroup(instanceGroup);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId());
+ injectionHelper.getAaiClient().createIfNotExists(instanceGroupUri, Optional.of(aaiInstanceGroup))
+ .connect(instanceGroupUri, serviceInstanceURI);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAINetworkResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAINetworkResources.java
index 7283c9967c..b936551549 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAINetworkResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAINetworkResources.java
@@ -21,7 +21,6 @@
package org.onap.so.client.orchestration;
import java.util.Optional;
-
import org.onap.aai.domain.yang.NetworkPolicies;
import org.onap.aai.domain.yang.NetworkPolicy;
import org.onap.aai.domain.yang.RouteTableReference;
@@ -46,147 +45,165 @@ import org.springframework.stereotype.Component;
@Component
public class AAINetworkResources {
-
- @Autowired
- private InjectionHelper injectionHelper;
-
- @Autowired
- private AAIObjectMapper aaiObjectMapper;
-
- public void updateNetwork(L3Network network) {
- AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId());
- org.onap.aai.domain.yang.L3Network aaiL3Network = aaiObjectMapper.mapNetwork(network);
- injectionHelper.getAaiClient().update(networkURI, aaiL3Network);
- }
-
- public void updateSubnet(L3Network network, Subnet subnet) {
- AAIResourceUri subnetURI = AAIUriFactory.createResourceUri(AAIObjectType.SUBNET, network.getNetworkId(), subnet.getSubnetId());
- org.onap.aai.domain.yang.Subnet aaiSubnet = aaiObjectMapper.mapSubnet(subnet);
- injectionHelper.getAaiClient().update(subnetURI, aaiSubnet);
- }
-
- public void createNetworkConnectToServiceInstance(L3Network network, ServiceInstance serviceInstance) {
- AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId());
- network.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstance.getServiceInstanceId());
- org.onap.aai.domain.yang.L3Network aaiL3Network = aaiObjectMapper.mapNetwork(network);
- injectionHelper.getAaiClient().createIfNotExists(networkURI, Optional.of(aaiL3Network)).connect(networkURI, serviceInstanceURI);
- }
-
- public void deleteNetwork(L3Network network) {
- AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId());
- injectionHelper.getAaiClient().delete(networkURI);
- }
-
- public Optional<VpnBinding> getVpnBinding(AAIResourceUri netBindingUri) {
- return injectionHelper.getAaiClient().get(netBindingUri.depth(Depth.TWO)).asBean(VpnBinding.class);
- }
-
- public Optional<NetworkPolicy> getNetworkPolicy(AAIResourceUri netPolicyUri) {
- return injectionHelper.getAaiClient().get(netPolicyUri).asBean(NetworkPolicy.class);
- }
-
- public Optional<NetworkPolicies> getNetworkPolicies(AAIResourceUri netPoliciesUri) {
- return injectionHelper.getAaiClient().get(netPoliciesUri).asBean(NetworkPolicies.class);
- }
-
- public Optional<org.onap.aai.domain.yang.Subnet> getSubnet(AAIResourceUri subnetUri) {
- return injectionHelper.getAaiClient().get(subnetUri).asBean(org.onap.aai.domain.yang.Subnet.class);
- }
-
- public Optional<RouteTableReference> getRouteTable(AAIResourceUri rTableUri) {
- return injectionHelper.getAaiClient().get(rTableUri).asBean(RouteTableReference.class);
- }
-
- public Optional<org.onap.aai.domain.yang.L3Network> queryNetworkById(L3Network l3network) {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK,l3network.getNetworkId()).depth(Depth.ALL);
- AAIResultWrapper aaiWrapper = injectionHelper.getAaiClient().get(uri);
- return aaiWrapper.asBean(org.onap.aai.domain.yang.L3Network.class);
- }
-
- public AAIResultWrapper queryNetworkWrapperById(L3Network l3network) {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK,l3network.getNetworkId()).depth(Depth.ALL);
- return injectionHelper.getAaiClient().get(uri);
- }
-
- public void createNetworkInstanceGroup(InstanceGroup instanceGroup) {
- AAIResourceUri instanceGroupURI = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
- org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = aaiObjectMapper.mapInstanceGroup(instanceGroup);
- injectionHelper.getAaiClient().create(instanceGroupURI, aaiInstanceGroup);
- }
-
- public void createNetworkCollection(Collection networkCollection) {
- AAIResourceUri networkCollectionURI = AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, networkCollection.getId());
- networkCollection.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
- org.onap.aai.domain.yang.Collection aaiCollection = aaiObjectMapper.mapCollection(networkCollection);
- injectionHelper.getAaiClient().create(networkCollectionURI, aaiCollection);
- }
-
- public void connectNetworkToTenant(L3Network l3network, CloudRegion cloudRegion) {
- AAIResourceUri tenantURI = AAIUriFactory.createResourceUri(AAIObjectType.TENANT,
- cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), cloudRegion.getTenantId());
- AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, l3network.getNetworkId());
- injectionHelper.getAaiClient().connect(tenantURI, networkURI);
- }
-
- public void connectNetworkToCloudRegion(L3Network l3network, CloudRegion cloudRegion) {
- AAIResourceUri cloudRegionURI = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION,
- cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId());
- AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, l3network.getNetworkId());
- injectionHelper.getAaiClient().connect(networkURI,cloudRegionURI);
- }
-
- public void connectNetworkToNetworkCollectionInstanceGroup(L3Network l3network, InstanceGroup instanceGroup) {
- AAIResourceUri netwrokCollectionInstanceGroupURI = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
- AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, l3network.getNetworkId());
- injectionHelper.getAaiClient().connect(netwrokCollectionInstanceGroupURI, networkURI);
- }
-
- public void connectNetworkToNetworkCollectionServiceInstance(L3Network l3network, ServiceInstance networkCollectionServiceInstance) {
- AAIResourceUri networkCollectionServiceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, networkCollectionServiceInstance.getServiceInstanceId());
- AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, l3network.getNetworkId());
- injectionHelper.getAaiClient().connect(networkCollectionServiceInstanceUri, networkURI);
- }
-
- public void connectNetworkCollectionInstanceGroupToNetworkCollection(InstanceGroup instanceGroup, Collection networkCollection) {
- AAIResourceUri networkCollectionUri = AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, networkCollection.getId());
- AAIResourceUri netwrokCollectionInstanceGroupURI = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
- injectionHelper.getAaiClient().connect(networkCollectionUri, netwrokCollectionInstanceGroupURI);
- }
-
- public void connectInstanceGroupToCloudRegion(InstanceGroup instanceGroup, CloudRegion cloudRegion) {
- AAIResourceUri cloudRegionURI = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION,
- cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId());
- AAIResourceUri instanceGroupURI = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
- injectionHelper.getAaiClient().connect(instanceGroupURI, cloudRegionURI, AAIEdgeLabel.USES);
- }
-
- public void connectNetworkCollectionToServiceInstance(Collection networkCollection, ServiceInstance networkCollectionServiceInstance) {
- AAIResourceUri networkCollectionUri = AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, networkCollection.getId());
- AAIResourceUri networkCollectionServiceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, networkCollectionServiceInstance.getServiceInstanceId());
- injectionHelper.getAaiClient().connect(networkCollectionUri, networkCollectionServiceInstanceUri);
- }
-
- public void deleteCollection(Collection collection) {
- AAIResourceUri collectionURI = AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, collection.getId());
- injectionHelper.getAaiClient().delete(collectionURI);
- }
-
- public void deleteNetworkInstanceGroup(InstanceGroup instanceGroup) {
- AAIResourceUri instanceGroupURI = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
- injectionHelper.getAaiClient().delete(instanceGroupURI);
- }
-
- public void createNetworkPolicy(org.onap.so.bpmn.servicedecomposition.bbobjects.NetworkPolicy networkPolicy) {
- NetworkPolicy aaiNetworkPolicy = aaiObjectMapper.mapNetworkPolicy(networkPolicy);
- String networkPolicyId = networkPolicy.getNetworkPolicyId();
- AAIResourceUri netUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId);
- injectionHelper.getAaiClient().create(netUri, aaiNetworkPolicy);
- }
-
- public void deleteNetworkPolicy(String networkPolicyId) {
- AAIResourceUri networkPolicyURI = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId);
- injectionHelper.getAaiClient().delete(networkPolicyURI);
- }
+
+ @Autowired
+ private InjectionHelper injectionHelper;
+
+ @Autowired
+ private AAIObjectMapper aaiObjectMapper;
+
+ public void updateNetwork(L3Network network) {
+ AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId());
+ org.onap.aai.domain.yang.L3Network aaiL3Network = aaiObjectMapper.mapNetwork(network);
+ injectionHelper.getAaiClient().update(networkURI, aaiL3Network);
+ }
+
+ public void updateSubnet(L3Network network, Subnet subnet) {
+ AAIResourceUri subnetURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SUBNET, network.getNetworkId(), subnet.getSubnetId());
+ org.onap.aai.domain.yang.Subnet aaiSubnet = aaiObjectMapper.mapSubnet(subnet);
+ injectionHelper.getAaiClient().update(subnetURI, aaiSubnet);
+ }
+
+ public void createNetworkConnectToServiceInstance(L3Network network, ServiceInstance serviceInstance) {
+ AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId());
+ network.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId());
+ org.onap.aai.domain.yang.L3Network aaiL3Network = aaiObjectMapper.mapNetwork(network);
+ injectionHelper.getAaiClient().createIfNotExists(networkURI, Optional.of(aaiL3Network)).connect(networkURI,
+ serviceInstanceURI);
+ }
+
+ public void deleteNetwork(L3Network network) {
+ AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId());
+ injectionHelper.getAaiClient().delete(networkURI);
+ }
+
+ public Optional<VpnBinding> getVpnBinding(AAIResourceUri netBindingUri) {
+ return injectionHelper.getAaiClient().get(netBindingUri.depth(Depth.TWO)).asBean(VpnBinding.class);
+ }
+
+ public Optional<NetworkPolicy> getNetworkPolicy(AAIResourceUri netPolicyUri) {
+ return injectionHelper.getAaiClient().get(netPolicyUri).asBean(NetworkPolicy.class);
+ }
+
+ public Optional<NetworkPolicies> getNetworkPolicies(AAIResourceUri netPoliciesUri) {
+ return injectionHelper.getAaiClient().get(netPoliciesUri).asBean(NetworkPolicies.class);
+ }
+
+ public Optional<org.onap.aai.domain.yang.Subnet> getSubnet(AAIResourceUri subnetUri) {
+ return injectionHelper.getAaiClient().get(subnetUri).asBean(org.onap.aai.domain.yang.Subnet.class);
+ }
+
+ public Optional<RouteTableReference> getRouteTable(AAIResourceUri rTableUri) {
+ return injectionHelper.getAaiClient().get(rTableUri).asBean(RouteTableReference.class);
+ }
+
+ public Optional<org.onap.aai.domain.yang.L3Network> queryNetworkById(L3Network l3network) {
+ AAIResourceUri uri =
+ AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, l3network.getNetworkId()).depth(Depth.ALL);
+ AAIResultWrapper aaiWrapper = injectionHelper.getAaiClient().get(uri);
+ return aaiWrapper.asBean(org.onap.aai.domain.yang.L3Network.class);
+ }
+
+ public AAIResultWrapper queryNetworkWrapperById(L3Network l3network) {
+ AAIResourceUri uri =
+ AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, l3network.getNetworkId()).depth(Depth.ALL);
+ return injectionHelper.getAaiClient().get(uri);
+ }
+
+ public void createNetworkInstanceGroup(InstanceGroup instanceGroup) {
+ AAIResourceUri instanceGroupURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
+ org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = aaiObjectMapper.mapInstanceGroup(instanceGroup);
+ injectionHelper.getAaiClient().create(instanceGroupURI, aaiInstanceGroup);
+ }
+
+ public void createNetworkCollection(Collection networkCollection) {
+ AAIResourceUri networkCollectionURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, networkCollection.getId());
+ networkCollection.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
+ org.onap.aai.domain.yang.Collection aaiCollection = aaiObjectMapper.mapCollection(networkCollection);
+ injectionHelper.getAaiClient().create(networkCollectionURI, aaiCollection);
+ }
+
+ public void connectNetworkToTenant(L3Network l3network, CloudRegion cloudRegion) {
+ AAIResourceUri tenantURI = AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId(), cloudRegion.getTenantId());
+ AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, l3network.getNetworkId());
+ injectionHelper.getAaiClient().connect(tenantURI, networkURI);
+ }
+
+ public void connectNetworkToCloudRegion(L3Network l3network, CloudRegion cloudRegion) {
+ AAIResourceUri cloudRegionURI = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION,
+ cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId());
+ AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, l3network.getNetworkId());
+ injectionHelper.getAaiClient().connect(networkURI, cloudRegionURI);
+ }
+
+ public void connectNetworkToNetworkCollectionInstanceGroup(L3Network l3network, InstanceGroup instanceGroup) {
+ AAIResourceUri netwrokCollectionInstanceGroupURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
+ AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, l3network.getNetworkId());
+ injectionHelper.getAaiClient().connect(netwrokCollectionInstanceGroupURI, networkURI);
+ }
+
+ public void connectNetworkToNetworkCollectionServiceInstance(L3Network l3network,
+ ServiceInstance networkCollectionServiceInstance) {
+ AAIResourceUri networkCollectionServiceInstanceUri = AAIUriFactory.createResourceUri(
+ AAIObjectType.SERVICE_INSTANCE, networkCollectionServiceInstance.getServiceInstanceId());
+ AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, l3network.getNetworkId());
+ injectionHelper.getAaiClient().connect(networkCollectionServiceInstanceUri, networkURI);
+ }
+
+ public void connectNetworkCollectionInstanceGroupToNetworkCollection(InstanceGroup instanceGroup,
+ Collection networkCollection) {
+ AAIResourceUri networkCollectionUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, networkCollection.getId());
+ AAIResourceUri netwrokCollectionInstanceGroupURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
+ injectionHelper.getAaiClient().connect(networkCollectionUri, netwrokCollectionInstanceGroupURI);
+ }
+
+ public void connectInstanceGroupToCloudRegion(InstanceGroup instanceGroup, CloudRegion cloudRegion) {
+ AAIResourceUri cloudRegionURI = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION,
+ cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId());
+ AAIResourceUri instanceGroupURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
+ injectionHelper.getAaiClient().connect(instanceGroupURI, cloudRegionURI, AAIEdgeLabel.USES);
+ }
+
+ public void connectNetworkCollectionToServiceInstance(Collection networkCollection,
+ ServiceInstance networkCollectionServiceInstance) {
+ AAIResourceUri networkCollectionUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, networkCollection.getId());
+ AAIResourceUri networkCollectionServiceInstanceUri = AAIUriFactory.createResourceUri(
+ AAIObjectType.SERVICE_INSTANCE, networkCollectionServiceInstance.getServiceInstanceId());
+ injectionHelper.getAaiClient().connect(networkCollectionUri, networkCollectionServiceInstanceUri);
+ }
+
+ public void deleteCollection(Collection collection) {
+ AAIResourceUri collectionURI = AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, collection.getId());
+ injectionHelper.getAaiClient().delete(collectionURI);
+ }
+
+ public void deleteNetworkInstanceGroup(InstanceGroup instanceGroup) {
+ AAIResourceUri instanceGroupURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId());
+ injectionHelper.getAaiClient().delete(instanceGroupURI);
+ }
+
+ public void createNetworkPolicy(org.onap.so.bpmn.servicedecomposition.bbobjects.NetworkPolicy networkPolicy) {
+ NetworkPolicy aaiNetworkPolicy = aaiObjectMapper.mapNetworkPolicy(networkPolicy);
+ String networkPolicyId = networkPolicy.getNetworkPolicyId();
+ AAIResourceUri netUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId);
+ injectionHelper.getAaiClient().create(netUri, aaiNetworkPolicy);
+ }
+
+ public void deleteNetworkPolicy(String networkPolicyId) {
+ AAIResourceUri networkPolicyURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId);
+ injectionHelper.getAaiClient().delete(networkPolicyURI);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java
index 3032b66e6d..e391349d2c 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java
@@ -23,7 +23,6 @@
package org.onap.so.client.orchestration;
import java.util.Optional;
-
import org.onap.so.bpmn.common.InjectionHelper;
import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer;
import org.onap.so.bpmn.servicedecomposition.bbobjects.OwningEntity;
@@ -43,112 +42,120 @@ import org.springframework.stereotype.Component;
@Component
public class AAIServiceInstanceResources {
- private static final Logger logger = LoggerFactory.getLogger(AAIServiceInstanceResources
- .class);
-
- @Autowired
- private InjectionHelper injectionHelper;
-
- @Autowired
- private AAIObjectMapper aaiObjectMapper;
-
- public boolean existsServiceInstance(ServiceInstance serviceInstance) {
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstance.getServiceInstanceId());
- return injectionHelper.getAaiClient().exists(serviceInstanceURI);
- }
-
- public void createServiceInstance(ServiceInstance serviceInstance, Customer customer) {
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- customer.getGlobalCustomerId(), customer.getServiceSubscription().getServiceType(), serviceInstance.getServiceInstanceId());
- serviceInstance.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
- org.onap.aai.domain.yang.ServiceInstance AAIServiceInstance = aaiObjectMapper.mapServiceInstance(serviceInstance);
- injectionHelper.getAaiClient().createIfNotExists(serviceInstanceURI, Optional.of(AAIServiceInstance));
- }
+ private static final Logger logger = LoggerFactory.getLogger(AAIServiceInstanceResources.class);
+
+ @Autowired
+ private InjectionHelper injectionHelper;
+
+ @Autowired
+ private AAIObjectMapper aaiObjectMapper;
+
+ public boolean existsServiceInstance(ServiceInstance serviceInstance) {
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId());
+ return injectionHelper.getAaiClient().exists(serviceInstanceURI);
+ }
+
+ public void createServiceInstance(ServiceInstance serviceInstance, Customer customer) {
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, customer.getGlobalCustomerId(),
+ customer.getServiceSubscription().getServiceType(), serviceInstance.getServiceInstanceId());
+ serviceInstance.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
+ org.onap.aai.domain.yang.ServiceInstance AAIServiceInstance =
+ aaiObjectMapper.mapServiceInstance(serviceInstance);
+ injectionHelper.getAaiClient().createIfNotExists(serviceInstanceURI, Optional.of(AAIServiceInstance));
+ }
/**
* Create ServiceSubscription in A&AI
+ *
* @param customer
*/
- public void createServiceSubscription(Customer customer) {
+ public void createServiceSubscription(Customer customer) {
AAIResourceUri serviceSubscriptionURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_SUBSCRIPTION,
- customer.getGlobalCustomerId(),customer.getServiceSubscription().getServiceType());
- org.onap.aai.domain.yang.ServiceSubscription serviceSubscription = aaiObjectMapper.mapServiceSubscription(customer.getServiceSubscription());
- injectionHelper.getAaiClient().createIfNotExists(serviceSubscriptionURI , Optional.of(serviceSubscription));
+ customer.getGlobalCustomerId(), customer.getServiceSubscription().getServiceType());
+ org.onap.aai.domain.yang.ServiceSubscription serviceSubscription =
+ aaiObjectMapper.mapServiceSubscription(customer.getServiceSubscription());
+ injectionHelper.getAaiClient().createIfNotExists(serviceSubscriptionURI, Optional.of(serviceSubscription));
+ }
+
+ public void deleteServiceInstance(ServiceInstance serviceInstance) {
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId());
+ injectionHelper.getAaiClient().delete(serviceInstanceURI);
+ }
+
+ public void createProject(Project project) {
+ AAIResourceUri projectURI = AAIUriFactory.createResourceUri(AAIObjectType.PROJECT, project.getProjectName());
+ org.onap.aai.domain.yang.Project AAIProject = aaiObjectMapper.mapProject(project);
+ injectionHelper.getAaiClient().createIfNotExists(projectURI, Optional.of(AAIProject));
+ }
+
+ public void createProjectandConnectServiceInstance(Project project, ServiceInstance serviceInstance) {
+ AAIResourceUri projectURI = AAIUriFactory.createResourceUri(AAIObjectType.PROJECT, project.getProjectName());
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId());
+ org.onap.aai.domain.yang.Project AAIProject = aaiObjectMapper.mapProject(project);
+ injectionHelper.getAaiClient().createIfNotExists(projectURI, Optional.of(AAIProject)).connect(projectURI,
+ serviceInstanceURI);
+ }
+
+ public void createOwningEntity(OwningEntity owningEntity) {
+ AAIResourceUri owningEntityURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntity.getOwningEntityId());
+ org.onap.aai.domain.yang.OwningEntity AAIOwningEntity = aaiObjectMapper.mapOwningEntity(owningEntity);
+ injectionHelper.getAaiClient().createIfNotExists(owningEntityURI, Optional.of(AAIOwningEntity));
+ }
+
+ public boolean existsOwningEntity(OwningEntity owningEntity) {
+ AAIResourceUri owningEntityUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntity.getOwningEntityId());
+ return injectionHelper.getAaiClient().exists(owningEntityUri);
+ }
+
+ public boolean existsOwningEntityName(String owningEntityName) {
+ AAIResourceUri owningEntityUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.OWNING_ENTITY)
+ .queryParam("owning-entity-name", owningEntityName);
+ AAIResourcesClient aaiRC = injectionHelper.getAaiClient();
+ return aaiRC.exists(owningEntityUri);
+ }
+
+ public void connectOwningEntityandServiceInstance(OwningEntity owningEntity, ServiceInstance serviceInstance) {
+ AAIResourceUri owningEntityURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntity.getOwningEntityId());
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId());
+ injectionHelper.getAaiClient().connect(owningEntityURI, serviceInstanceURI);
+ }
+
+ public void createOwningEntityandConnectServiceInstance(OwningEntity owningEntity,
+ ServiceInstance serviceInstance) {
+ AAIResourceUri owningEntityURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntity.getOwningEntityId());
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId());
+ org.onap.aai.domain.yang.OwningEntity AAIOwningEntity = aaiObjectMapper.mapOwningEntity(owningEntity);
+ injectionHelper.getAaiClient().createIfNotExists(owningEntityURI, Optional.of(AAIOwningEntity))
+ .connect(owningEntityURI, serviceInstanceURI);
+ }
+
+ public void updateOrchestrationStatusServiceInstance(ServiceInstance serviceInstance,
+ OrchestrationStatus orchestrationStatus) {
+ ServiceInstance copiedServiceInstance = serviceInstance.shallowCopyId();
+
+ copiedServiceInstance.setOrchestrationStatus(orchestrationStatus);
+ copiedServiceInstance.setServiceInstanceName(serviceInstance.getServiceInstanceName());
+ serviceInstance.setOrchestrationStatus(orchestrationStatus);
+ updateServiceInstance(copiedServiceInstance);
+ }
+
+ public void updateServiceInstance(ServiceInstance serviceInstance) {
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId());
+ org.onap.aai.domain.yang.ServiceInstance AAIServiceInstance =
+ aaiObjectMapper.mapServiceInstance(serviceInstance);
+ injectionHelper.getAaiClient().update(serviceInstanceURI, AAIServiceInstance);
}
- public void deleteServiceInstance(ServiceInstance serviceInstance) {
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstance.getServiceInstanceId());
- injectionHelper.getAaiClient().delete(serviceInstanceURI);
- }
-
- public void createProject(Project project) {
- AAIResourceUri projectURI = AAIUriFactory.createResourceUri(AAIObjectType.PROJECT, project.getProjectName());
- org.onap.aai.domain.yang.Project AAIProject = aaiObjectMapper.mapProject(project);
- injectionHelper.getAaiClient().createIfNotExists(projectURI, Optional.of(AAIProject));
- }
-
- public void createProjectandConnectServiceInstance(Project project, ServiceInstance serviceInstance) {
- AAIResourceUri projectURI = AAIUriFactory.createResourceUri(AAIObjectType.PROJECT, project.getProjectName());
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstance.getServiceInstanceId());
- org.onap.aai.domain.yang.Project AAIProject = aaiObjectMapper.mapProject(project);
- injectionHelper.getAaiClient().createIfNotExists(projectURI, Optional.of(AAIProject)).connect(projectURI, serviceInstanceURI);
- }
-
- public void createOwningEntity(OwningEntity owningEntity) {
- AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY,
- owningEntity.getOwningEntityId());
- org.onap.aai.domain.yang.OwningEntity AAIOwningEntity = aaiObjectMapper.mapOwningEntity(owningEntity);
- injectionHelper.getAaiClient().createIfNotExists(owningEntityURI, Optional.of(AAIOwningEntity));
- }
-
- public boolean existsOwningEntity(OwningEntity owningEntity) {
- AAIResourceUri owningEntityUri = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY,
- owningEntity.getOwningEntityId());
- return injectionHelper.getAaiClient().exists(owningEntityUri);
- }
-
- public boolean existsOwningEntityName(String owningEntityName) {
- AAIResourceUri owningEntityUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.OWNING_ENTITY).queryParam("owning-entity-name", owningEntityName);
- AAIResourcesClient aaiRC = injectionHelper.getAaiClient();
- return aaiRC.exists(owningEntityUri);
- }
-
- public void connectOwningEntityandServiceInstance(OwningEntity owningEntity, ServiceInstance serviceInstance) {
- AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY,
- owningEntity.getOwningEntityId());
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstance.getServiceInstanceId());
- injectionHelper.getAaiClient().connect(owningEntityURI, serviceInstanceURI);
- }
-
- public void createOwningEntityandConnectServiceInstance(OwningEntity owningEntity,
- ServiceInstance serviceInstance) {
- AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY,
- owningEntity.getOwningEntityId());
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstance.getServiceInstanceId());
- org.onap.aai.domain.yang.OwningEntity AAIOwningEntity = aaiObjectMapper.mapOwningEntity(owningEntity);
- injectionHelper.getAaiClient().createIfNotExists(owningEntityURI, Optional.of(AAIOwningEntity)).connect(owningEntityURI,
- serviceInstanceURI);
- }
-
- public void updateOrchestrationStatusServiceInstance(ServiceInstance serviceInstance, OrchestrationStatus orchestrationStatus){
- ServiceInstance copiedServiceInstance = serviceInstance.shallowCopyId();
-
- copiedServiceInstance.setOrchestrationStatus(orchestrationStatus);
- copiedServiceInstance.setServiceInstanceName(serviceInstance.getServiceInstanceName());
- serviceInstance.setOrchestrationStatus(orchestrationStatus);
- updateServiceInstance(copiedServiceInstance);
- }
-
- public void updateServiceInstance(ServiceInstance serviceInstance) {
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId());
- org.onap.aai.domain.yang.ServiceInstance AAIServiceInstance = aaiObjectMapper.mapServiceInstance(serviceInstance);
- injectionHelper.getAaiClient().update(serviceInstanceURI, AAIServiceInstance);
- }
-
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVfModuleResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVfModuleResources.java
index 5fa73c85ff..83fe31a116 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVfModuleResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVfModuleResources.java
@@ -23,7 +23,6 @@
package org.onap.so.client.orchestration;
import java.util.Optional;
-
import org.onap.so.bpmn.common.InjectionHelper;
import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
@@ -41,62 +40,73 @@ import org.springframework.stereotype.Component;
@Component
public class AAIVfModuleResources {
- private static final Logger logger = LoggerFactory.getLogger(AAIVfModuleResources.class);
-
- @Autowired
- private InjectionHelper injectionHelper;
-
- @Autowired
- private AAIObjectMapper aaiObjectMapper;
+ private static final Logger logger = LoggerFactory.getLogger(AAIVfModuleResources.class);
+
+ @Autowired
+ private InjectionHelper injectionHelper;
+
+ @Autowired
+ private AAIObjectMapper aaiObjectMapper;
+
+ public void createVfModule(VfModule vfModule, GenericVnf vnf) {
+ AAIResourceUri vfModuleURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
+ vfModule.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
+ injectionHelper.getAaiClient().createIfNotExists(vfModuleURI,
+ Optional.of(aaiObjectMapper.mapVfModule(vfModule)));
+ }
+
+ public void deleteVfModule(VfModule vfModule, GenericVnf vnf) {
+ AAIResourceUri vfModuleURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
+ injectionHelper.getAaiClient().delete(vfModuleURI);
+ }
+
+ public void updateOrchestrationStatusVfModule(VfModule vfModule, GenericVnf vnf,
+ OrchestrationStatus orchestrationStatus) {
+ AAIResourceUri vfModuleURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
+ VfModule copiedVfModule = vfModule.shallowCopyId();
+
+ vfModule.setOrchestrationStatus(orchestrationStatus);
+ copiedVfModule.setOrchestrationStatus(orchestrationStatus);
+ org.onap.aai.domain.yang.VfModule aaiVfModule = aaiObjectMapper.mapVfModule(copiedVfModule);
+ injectionHelper.getAaiClient().update(vfModuleURI, aaiVfModule);
+ }
+
+ public void updateHeatStackIdVfModule(VfModule vfModule, GenericVnf vnf) {
+ AAIResourceUri vfModuleURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
+ VfModule copiedVfModule = vfModule.shallowCopyId();
+
+ copiedVfModule.setHeatStackId(vfModule.getHeatStackId());
+ org.onap.aai.domain.yang.VfModule aaiVfModule = aaiObjectMapper.mapVfModule(copiedVfModule);
+ injectionHelper.getAaiClient().update(vfModuleURI, aaiVfModule);
+ }
- public void createVfModule(VfModule vfModule, GenericVnf vnf) {
- AAIResourceUri vfModuleURI = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
- vfModule.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
- injectionHelper.getAaiClient().createIfNotExists(vfModuleURI, Optional.of(aaiObjectMapper.mapVfModule(vfModule)));
- }
-
- public void deleteVfModule(VfModule vfModule, GenericVnf vnf) {
- AAIResourceUri vfModuleURI = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
- injectionHelper.getAaiClient().delete(vfModuleURI);
- }
+ public void updateContrailServiceInstanceFqdnVfModule(VfModule vfModule, GenericVnf vnf) {
+ AAIResourceUri vfModuleURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
+ VfModule copiedVfModule = vfModule.shallowCopyId();
- public void updateOrchestrationStatusVfModule(VfModule vfModule, GenericVnf vnf, OrchestrationStatus orchestrationStatus) {
- AAIResourceUri vfModuleURI = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
- VfModule copiedVfModule = vfModule.shallowCopyId();
+ copiedVfModule.setContrailServiceInstanceFqdn(vfModule.getContrailServiceInstanceFqdn());
+ org.onap.aai.domain.yang.VfModule aaiVfModule = aaiObjectMapper.mapVfModule(copiedVfModule);
+ injectionHelper.getAaiClient().update(vfModuleURI, aaiVfModule);
+ }
- vfModule.setOrchestrationStatus(orchestrationStatus);
- copiedVfModule.setOrchestrationStatus(orchestrationStatus);
- org.onap.aai.domain.yang.VfModule aaiVfModule = aaiObjectMapper.mapVfModule(copiedVfModule);
- injectionHelper.getAaiClient().update(vfModuleURI, aaiVfModule);
- }
-
- public void updateHeatStackIdVfModule(VfModule vfModule, GenericVnf vnf) {
- AAIResourceUri vfModuleURI = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
- VfModule copiedVfModule = vfModule.shallowCopyId();
+ public void changeAssignVfModule(VfModule vfModule, GenericVnf vnf) {
+ AAIResourceUri vfModuleURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
+ org.onap.aai.domain.yang.VfModule AAIVfModule = aaiObjectMapper.mapVfModule(vfModule);
+ injectionHelper.getAaiClient().update(vfModuleURI, AAIVfModule);
+ }
- copiedVfModule.setHeatStackId(vfModule.getHeatStackId());
- org.onap.aai.domain.yang.VfModule aaiVfModule = aaiObjectMapper.mapVfModule(copiedVfModule);
- injectionHelper.getAaiClient().update(vfModuleURI, aaiVfModule);
- }
-
- public void updateContrailServiceInstanceFqdnVfModule(VfModule vfModule, GenericVnf vnf) {
- AAIResourceUri vfModuleURI = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
- VfModule copiedVfModule = vfModule.shallowCopyId();
-
- copiedVfModule.setContrailServiceInstanceFqdn(vfModule.getContrailServiceInstanceFqdn());
- org.onap.aai.domain.yang.VfModule aaiVfModule = aaiObjectMapper.mapVfModule(copiedVfModule);
- injectionHelper.getAaiClient().update(vfModuleURI, aaiVfModule);
- }
-
- public void changeAssignVfModule(VfModule vfModule, GenericVnf vnf) {
- AAIResourceUri vfModuleURI = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
- org.onap.aai.domain.yang.VfModule AAIVfModule = aaiObjectMapper.mapVfModule(vfModule);
- injectionHelper.getAaiClient().update(vfModuleURI, AAIVfModule);
- }
-
- public void connectVfModuleToVolumeGroup(GenericVnf vnf, VfModule vfModule, VolumeGroup volumeGroup, CloudRegion cloudRegion) {
- AAIResourceUri vfModuleURI = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
- AAIResourceUri volumeGroupURI = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
- injectionHelper.getAaiClient().connect(vfModuleURI, volumeGroupURI);
- }
+ public void connectVfModuleToVolumeGroup(GenericVnf vnf, VfModule vfModule, VolumeGroup volumeGroup,
+ CloudRegion cloudRegion) {
+ AAIResourceUri vfModuleURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId());
+ AAIResourceUri volumeGroupURI = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,
+ cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
+ injectionHelper.getAaiClient().connect(vfModuleURI, volumeGroupURI);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java
index 48a1c1e558..fc61d862aa 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java
@@ -24,7 +24,6 @@ package org.onap.so.client.orchestration;
import java.io.IOException;
import java.util.Optional;
-
import org.onap.so.bpmn.common.InjectionHelper;
import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
@@ -44,104 +43,114 @@ import org.springframework.stereotype.Component;
@Component
public class AAIVnfResources {
- private static final Logger logger = LoggerFactory.getLogger(AAIVnfResources.class);
-
- @Autowired
- private InjectionHelper injectionHelper;
-
- @Autowired
- private AAIObjectMapper aaiObjectMapper;
-
- private AAIValidatorImpl aaiValidatorImpl= new AAIValidatorImpl();
-
- public void createVnfandConnectServiceInstance(GenericVnf vnf, ServiceInstance serviceInstance) {
- AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
- vnf.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
- AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
- serviceInstance.getServiceInstanceId());
- injectionHelper.getAaiClient().createIfNotExists(vnfURI, Optional.of(aaiObjectMapper.mapVnf(vnf))).connect(vnfURI, serviceInstanceURI);
- }
-
- public void createPlatformandConnectVnf(Platform platform, GenericVnf vnf) {
- AAIResourceUri platformURI = AAIUriFactory.createResourceUri(AAIObjectType.PLATFORM, platform.getPlatformName());
- AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
- injectionHelper.getAaiClient().createIfNotExists(platformURI, Optional.of(platform)).connect(vnfURI, platformURI);
- }
-
- public void createLineOfBusinessandConnectVnf(LineOfBusiness lineOfBusiness, GenericVnf vnf) {
- AAIResourceUri lineOfBusinessURI = AAIUriFactory.createResourceUri(AAIObjectType.LINE_OF_BUSINESS, lineOfBusiness.getLineOfBusinessName());
- AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
- injectionHelper.getAaiClient().createIfNotExists(lineOfBusinessURI, Optional.of(lineOfBusiness)).connect(vnfURI, lineOfBusinessURI);
- }
-
- public void deleteVnf(GenericVnf vnf) {
- AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
- injectionHelper.getAaiClient().delete(vnfURI);
- }
-
- public void updateOrchestrationStatusVnf(GenericVnf vnf, OrchestrationStatus orchestrationStatus) {
- AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
-
- GenericVnf copiedVnf = vnf.shallowCopyId();
-
- vnf.setOrchestrationStatus(orchestrationStatus);
- copiedVnf.setOrchestrationStatus(orchestrationStatus);
- injectionHelper.getAaiClient().update(vnfURI, aaiObjectMapper.mapVnf(copiedVnf));
- }
-
- public void updateObjectVnf(GenericVnf vnf) {
- AAIResourceUri vnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
- injectionHelper.getAaiClient().update(vnfUri, aaiObjectMapper.mapVnf(vnf));
- }
-
- /**
- * Retrieve Generic VNF from AAI using vnf Id
- * @param vnfId - vnf-id required vnf
- * @return AAI Generic Vnf
- */
- public Optional<org.onap.aai.domain.yang.GenericVnf> getGenericVnf( String vnfId) {
- return injectionHelper.getAaiClient()
- .get(org.onap.aai.domain.yang.GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId));
- }
-
- /**
- * Check inMaint flag value of Generic VNF from AAI using vnf Id
- * @param vnfId - vnf-id required vnf
- * @return inMaint flag value
- */
- public boolean checkInMaintFlag(String vnfId) {
- org.onap.aai.domain.yang.GenericVnf vnf = injectionHelper.getAaiClient()
- .get(org.onap.aai.domain.yang.GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId))
- .orElse(new org.onap.aai.domain.yang.GenericVnf());
- return vnf.isInMaint();
- }
-
- public void connectVnfToCloudRegion(GenericVnf vnf, CloudRegion cloudRegion) {
- AAIResourceUri cloudRegionURI = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION,
- cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId());
- AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
- injectionHelper.getAaiClient().connect(vnfURI,cloudRegionURI);
- }
-
- public void connectVnfToTenant(GenericVnf vnf, CloudRegion cloudRegion) {
- AAIResourceUri tenantURI = AAIUriFactory.createResourceUri(AAIObjectType.TENANT,
- cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), cloudRegion.getTenantId());
- AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
- injectionHelper.getAaiClient().connect(tenantURI, vnfURI);
- }
-
- public boolean checkVnfClosedLoopDisabledFlag(String vnfId) {
- org.onap.aai.domain.yang.GenericVnf vnf = injectionHelper.getAaiClient()
- .get(org.onap.aai.domain.yang.GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId))
- .orElse(new org.onap.aai.domain.yang.GenericVnf());
- return vnf.isIsClosedLoopDisabled();
- }
-
- public boolean checkVnfPserversLockedFlag (String vnfId) throws IOException {
- org.onap.aai.domain.yang.GenericVnf vnf = injectionHelper.getAaiClient()
- .get(org.onap.aai.domain.yang.GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId))
- .orElse(new org.onap.aai.domain.yang.GenericVnf());
- return aaiValidatorImpl.isPhysicalServerLocked(vnf.getVnfId());
-
- }
+ private static final Logger logger = LoggerFactory.getLogger(AAIVnfResources.class);
+
+ @Autowired
+ private InjectionHelper injectionHelper;
+
+ @Autowired
+ private AAIObjectMapper aaiObjectMapper;
+
+ private AAIValidatorImpl aaiValidatorImpl = new AAIValidatorImpl();
+
+ public void createVnfandConnectServiceInstance(GenericVnf vnf, ServiceInstance serviceInstance) {
+ AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
+ vnf.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
+ AAIResourceUri serviceInstanceURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId());
+ injectionHelper.getAaiClient().createIfNotExists(vnfURI, Optional.of(aaiObjectMapper.mapVnf(vnf)))
+ .connect(vnfURI, serviceInstanceURI);
+ }
+
+ public void createPlatformandConnectVnf(Platform platform, GenericVnf vnf) {
+ AAIResourceUri platformURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.PLATFORM, platform.getPlatformName());
+ AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
+ injectionHelper.getAaiClient().createIfNotExists(platformURI, Optional.of(platform)).connect(vnfURI,
+ platformURI);
+ }
+
+ public void createLineOfBusinessandConnectVnf(LineOfBusiness lineOfBusiness, GenericVnf vnf) {
+ AAIResourceUri lineOfBusinessURI =
+ AAIUriFactory.createResourceUri(AAIObjectType.LINE_OF_BUSINESS, lineOfBusiness.getLineOfBusinessName());
+ AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
+ injectionHelper.getAaiClient().createIfNotExists(lineOfBusinessURI, Optional.of(lineOfBusiness)).connect(vnfURI,
+ lineOfBusinessURI);
+ }
+
+ public void deleteVnf(GenericVnf vnf) {
+ AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
+ injectionHelper.getAaiClient().delete(vnfURI);
+ }
+
+ public void updateOrchestrationStatusVnf(GenericVnf vnf, OrchestrationStatus orchestrationStatus) {
+ AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
+
+ GenericVnf copiedVnf = vnf.shallowCopyId();
+
+ vnf.setOrchestrationStatus(orchestrationStatus);
+ copiedVnf.setOrchestrationStatus(orchestrationStatus);
+ injectionHelper.getAaiClient().update(vnfURI, aaiObjectMapper.mapVnf(copiedVnf));
+ }
+
+ public void updateObjectVnf(GenericVnf vnf) {
+ AAIResourceUri vnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
+ injectionHelper.getAaiClient().update(vnfUri, aaiObjectMapper.mapVnf(vnf));
+ }
+
+ /**
+ * Retrieve Generic VNF from AAI using vnf Id
+ *
+ * @param vnfId - vnf-id required vnf
+ * @return AAI Generic Vnf
+ */
+ public Optional<org.onap.aai.domain.yang.GenericVnf> getGenericVnf(String vnfId) {
+ return injectionHelper.getAaiClient().get(org.onap.aai.domain.yang.GenericVnf.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId));
+ }
+
+ /**
+ * Check inMaint flag value of Generic VNF from AAI using vnf Id
+ *
+ * @param vnfId - vnf-id required vnf
+ * @return inMaint flag value
+ */
+ public boolean checkInMaintFlag(String vnfId) {
+ org.onap.aai.domain.yang.GenericVnf vnf = injectionHelper.getAaiClient()
+ .get(org.onap.aai.domain.yang.GenericVnf.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId))
+ .orElse(new org.onap.aai.domain.yang.GenericVnf());
+ return vnf.isInMaint();
+ }
+
+ public void connectVnfToCloudRegion(GenericVnf vnf, CloudRegion cloudRegion) {
+ AAIResourceUri cloudRegionURI = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION,
+ cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId());
+ AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
+ injectionHelper.getAaiClient().connect(vnfURI, cloudRegionURI);
+ }
+
+ public void connectVnfToTenant(GenericVnf vnf, CloudRegion cloudRegion) {
+ AAIResourceUri tenantURI = AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId(), cloudRegion.getTenantId());
+ AAIResourceUri vnfURI = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId());
+ injectionHelper.getAaiClient().connect(tenantURI, vnfURI);
+ }
+
+ public boolean checkVnfClosedLoopDisabledFlag(String vnfId) {
+ org.onap.aai.domain.yang.GenericVnf vnf = injectionHelper.getAaiClient()
+ .get(org.onap.aai.domain.yang.GenericVnf.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId))
+ .orElse(new org.onap.aai.domain.yang.GenericVnf());
+ return vnf.isIsClosedLoopDisabled();
+ }
+
+ public boolean checkVnfPserversLockedFlag(String vnfId) throws IOException {
+ org.onap.aai.domain.yang.GenericVnf vnf = injectionHelper.getAaiClient()
+ .get(org.onap.aai.domain.yang.GenericVnf.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId))
+ .orElse(new org.onap.aai.domain.yang.GenericVnf());
+ return aaiValidatorImpl.isPhysicalServerLocked(vnf.getVnfId());
+
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVolumeGroupResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVolumeGroupResources.java
index 7bb96ec2ed..c24d1483e2 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVolumeGroupResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVolumeGroupResources.java
@@ -38,51 +38,60 @@ import org.springframework.stereotype.Component;
@Component
public class AAIVolumeGroupResources {
- private static final Logger logger = LoggerFactory.getLogger(AAIVolumeGroupResources.class);
-
- @Autowired
- private InjectionHelper injectionHelper;
-
- @Autowired
- private AAIObjectMapper aaiObjectMapper;
+ private static final Logger logger = LoggerFactory.getLogger(AAIVolumeGroupResources.class);
- public void createVolumeGroup(VolumeGroup volumeGroup, CloudRegion cloudRegion) {
- AAIResourceUri uriVolumeGroup = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
- injectionHelper.getAaiClient().create(uriVolumeGroup, aaiObjectMapper.mapVolumeGroup(volumeGroup));
- }
-
- public void updateOrchestrationStatusVolumeGroup(VolumeGroup volumeGroup, CloudRegion cloudRegion, OrchestrationStatus orchestrationStatus) {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
- VolumeGroup copiedVolumeGroup = volumeGroup.shallowCopyId();
+ @Autowired
+ private InjectionHelper injectionHelper;
- volumeGroup.setOrchestrationStatus(orchestrationStatus);
- copiedVolumeGroup.setOrchestrationStatus(orchestrationStatus);
- injectionHelper.getAaiClient().update(uri, aaiObjectMapper.mapVolumeGroup(copiedVolumeGroup));
- }
-
- public void connectVolumeGroupToVnf(GenericVnf genericVnf, VolumeGroup volumeGroup, CloudRegion cloudRegion) {
- AAIResourceUri uriGenericVnf = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, genericVnf.getVnfId());
- AAIResourceUri uriVolumeGroup = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
- injectionHelper.getAaiClient().connect(uriGenericVnf, uriVolumeGroup);
- }
-
- public void connectVolumeGroupToTenant(VolumeGroup volumeGroup , CloudRegion cloudRegion) {
- AAIResourceUri uriTenant = AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(),cloudRegion.getTenantId());
- AAIResourceUri uriVolumeGroup = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
- injectionHelper.getAaiClient().connect(uriTenant, uriVolumeGroup);
- }
-
- public void deleteVolumeGroup(VolumeGroup volumeGroup, CloudRegion cloudRegion) {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
- injectionHelper.getAaiClient().delete(uri);
- }
-
- public void updateHeatStackIdVolumeGroup(VolumeGroup volumeGroup, CloudRegion cloudRegion) {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
- VolumeGroup copiedVolumeGroup = volumeGroup.shallowCopyId();
-
- copiedVolumeGroup.setHeatStackId(volumeGroup.getHeatStackId());
- injectionHelper.getAaiClient().update(uri, aaiObjectMapper.mapVolumeGroup(copiedVolumeGroup));
- }
+ @Autowired
+ private AAIObjectMapper aaiObjectMapper;
+
+ public void createVolumeGroup(VolumeGroup volumeGroup, CloudRegion cloudRegion) {
+ AAIResourceUri uriVolumeGroup = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,
+ cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+ injectionHelper.getAaiClient().create(uriVolumeGroup, aaiObjectMapper.mapVolumeGroup(volumeGroup));
+ }
+
+ public void updateOrchestrationStatusVolumeGroup(VolumeGroup volumeGroup, CloudRegion cloudRegion,
+ OrchestrationStatus orchestrationStatus) {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
+ VolumeGroup copiedVolumeGroup = volumeGroup.shallowCopyId();
+
+ volumeGroup.setOrchestrationStatus(orchestrationStatus);
+ copiedVolumeGroup.setOrchestrationStatus(orchestrationStatus);
+ injectionHelper.getAaiClient().update(uri, aaiObjectMapper.mapVolumeGroup(copiedVolumeGroup));
+ }
+
+ public void connectVolumeGroupToVnf(GenericVnf genericVnf, VolumeGroup volumeGroup, CloudRegion cloudRegion) {
+ AAIResourceUri uriGenericVnf =
+ AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, genericVnf.getVnfId());
+ AAIResourceUri uriVolumeGroup = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,
+ cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
+ injectionHelper.getAaiClient().connect(uriGenericVnf, uriVolumeGroup);
+ }
+
+ public void connectVolumeGroupToTenant(VolumeGroup volumeGroup, CloudRegion cloudRegion) {
+ AAIResourceUri uriTenant = AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId(), cloudRegion.getTenantId());
+ AAIResourceUri uriVolumeGroup = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,
+ cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
+ injectionHelper.getAaiClient().connect(uriTenant, uriVolumeGroup);
+ }
+
+ public void deleteVolumeGroup(VolumeGroup volumeGroup, CloudRegion cloudRegion) {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
+ injectionHelper.getAaiClient().delete(uri);
+ }
+
+ public void updateHeatStackIdVolumeGroup(VolumeGroup volumeGroup, CloudRegion cloudRegion) {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId());
+ VolumeGroup copiedVolumeGroup = volumeGroup.shallowCopyId();
+
+ copiedVolumeGroup.setHeatStackId(volumeGroup.getHeatStackId());
+ injectionHelper.getAaiClient().update(uri, aaiObjectMapper.mapVolumeGroup(copiedVolumeGroup));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVpnBindingResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVpnBindingResources.java
index 092af30558..3ac61dff60 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVpnBindingResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVpnBindingResources.java
@@ -21,9 +21,7 @@
package org.onap.so.client.orchestration;
import java.util.Optional;
-
import javax.ws.rs.NotFoundException;
-
import org.onap.aai.domain.yang.VpnBindings;
import org.onap.so.bpmn.common.InjectionHelper;
import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer;
@@ -38,65 +36,69 @@ import org.springframework.stereotype.Component;
@Component
public class AAIVpnBindingResources {
- @Autowired
- private InjectionHelper injectionHelper;
+ @Autowired
+ private InjectionHelper injectionHelper;
- @Autowired
- private AAIObjectMapper aaiObjectMapper;
+ @Autowired
+ private AAIObjectMapper aaiObjectMapper;
- /**
- * @param customer
- */
- public boolean existsCustomer(Customer customer) {
- AAIResourceUri uriCustomer = AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, customer.getGlobalCustomerId());
- return injectionHelper.getAaiClient().exists(uriCustomer);
- }
+ /**
+ * @param customer
+ */
+ public boolean existsCustomer(Customer customer) {
+ AAIResourceUri uriCustomer =
+ AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, customer.getGlobalCustomerId());
+ return injectionHelper.getAaiClient().exists(uriCustomer);
+ }
- /**
- * @param customerVpnId
- * @return
- */
- public Optional<VpnBindings> getVpnBindingByCustomerVpnId (String customerVpnId) {
- AAIResourceUri aaiVpnBindingsResourceUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VPN_BINDING)
- .queryParam("customer-vpn-id",customerVpnId);
- return injectionHelper.getAaiClient().get(VpnBindings.class,aaiVpnBindingsResourceUri);
+ /**
+ * @param customerVpnId
+ * @return
+ */
+ public Optional<VpnBindings> getVpnBindingByCustomerVpnId(String customerVpnId) {
+ AAIResourceUri aaiVpnBindingsResourceUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VPN_BINDING)
+ .queryParam("customer-vpn-id", customerVpnId);
+ return injectionHelper.getAaiClient().get(VpnBindings.class, aaiVpnBindingsResourceUri);
- }
+ }
- /**
- * @param vpnBinding
- */
- public void createVpnBinding(VpnBinding vpnBinding) {
- AAIResourceUri aaiVpnBindingResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING,vpnBinding.getVpnId());
- injectionHelper.getAaiClient().create(aaiVpnBindingResourceUri, aaiObjectMapper.mapVpnBinding(vpnBinding));
- }
+ /**
+ * @param vpnBinding
+ */
+ public void createVpnBinding(VpnBinding vpnBinding) {
+ AAIResourceUri aaiVpnBindingResourceUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, vpnBinding.getVpnId());
+ injectionHelper.getAaiClient().create(aaiVpnBindingResourceUri, aaiObjectMapper.mapVpnBinding(vpnBinding));
+ }
- /**
- * @param customer
- */
- public void createCustomer(Customer customer) {
- AAIResourceUri uriCustomer = AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, customer.getGlobalCustomerId());
- injectionHelper.getAaiClient().create(uriCustomer, aaiObjectMapper.mapCustomer(customer));
- }
+ /**
+ * @param customer
+ */
+ public void createCustomer(Customer customer) {
+ AAIResourceUri uriCustomer =
+ AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, customer.getGlobalCustomerId());
+ injectionHelper.getAaiClient().create(uriCustomer, aaiObjectMapper.mapCustomer(customer));
+ }
- /**
- * Retrieve VPN Binding from AAI using vpn-id
- * @param vpnId - vpn-id required VPN Binding
- * @return AAI VPN Binding
- */
- public Optional<org.onap.aai.domain.yang.VpnBinding> getVpnBinding(String vpnId){
- return injectionHelper.getAaiClient()
- .get(org.onap.aai.domain.yang.VpnBinding.class, AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, vpnId));
- }
+ /**
+ * Retrieve VPN Binding from AAI using vpn-id
+ *
+ * @param vpnId - vpn-id required VPN Binding
+ * @return AAI VPN Binding
+ */
+ public Optional<org.onap.aai.domain.yang.VpnBinding> getVpnBinding(String vpnId) {
+ return injectionHelper.getAaiClient().get(org.onap.aai.domain.yang.VpnBinding.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, vpnId));
+ }
- /**
- * @param globalSubscriberId
- * @param vpnId
- */
- public void connectCustomerToVpnBinding(String globalSubscriberId, String vpnId) {
- AAIResourceUri customerURI = AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId);
- AAIResourceUri vpnBindingURI = AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING,vpnId);
- injectionHelper.getAaiClient().connect(customerURI, vpnBindingURI);
- }
+ /**
+ * @param globalSubscriberId
+ * @param vpnId
+ */
+ public void connectCustomerToVpnBinding(String globalSubscriberId, String vpnId) {
+ AAIResourceUri customerURI = AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId);
+ AAIResourceUri vpnBindingURI = AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, vpnId);
+ injectionHelper.getAaiClient().connect(customerURI, vpnBindingURI);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java
index 2a25ec5ba1..06535bb765 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java
@@ -25,7 +25,6 @@ package org.onap.so.client.orchestration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-
import org.onap.namingservice.model.Element;
import org.onap.namingservice.model.Deleteelement;
import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup;
@@ -39,26 +38,29 @@ import org.springframework.stereotype.Component;
@Component
public class NamingServiceResources {
- private static final Logger logger = LoggerFactory.getLogger(NamingServiceResources.class);
- private static final String NAMING_TYPE = "instanceGroup";
-
- @Autowired
- private NamingClient namingClient;
-
- @Autowired
- private NamingRequestObjectBuilder namingRequestObjectBuilder;
-
- public String generateInstanceGroupName(InstanceGroup instanceGroup, String policyInstanceName, String nfNamingCode) throws BadResponseException, IOException {
- Element element = namingRequestObjectBuilder.elementMapper(instanceGroup.getId(), policyInstanceName, NAMING_TYPE, nfNamingCode, instanceGroup.getInstanceGroupName());
- List<Element> elements = new ArrayList<Element>();
- elements.add(element);
- return(namingClient.postNameGenRequest(namingRequestObjectBuilder.nameGenRequestMapper(elements)));
- }
-
- public String deleteInstanceGroupName(InstanceGroup instanceGroup) throws BadResponseException, IOException {
- Deleteelement deleteElement = namingRequestObjectBuilder.deleteElementMapper(instanceGroup.getId());
- List<Deleteelement> deleteElements = new ArrayList<Deleteelement>();
- deleteElements.add(deleteElement);
- return(namingClient.deleteNameGenRequest(namingRequestObjectBuilder.nameGenDeleteRequestMapper(deleteElements)));
- }
+ private static final Logger logger = LoggerFactory.getLogger(NamingServiceResources.class);
+ private static final String NAMING_TYPE = "instanceGroup";
+
+ @Autowired
+ private NamingClient namingClient;
+
+ @Autowired
+ private NamingRequestObjectBuilder namingRequestObjectBuilder;
+
+ public String generateInstanceGroupName(InstanceGroup instanceGroup, String policyInstanceName, String nfNamingCode)
+ throws BadResponseException, IOException {
+ Element element = namingRequestObjectBuilder.elementMapper(instanceGroup.getId(), policyInstanceName,
+ NAMING_TYPE, nfNamingCode, instanceGroup.getInstanceGroupName());
+ List<Element> elements = new ArrayList<Element>();
+ elements.add(element);
+ return (namingClient.postNameGenRequest(namingRequestObjectBuilder.nameGenRequestMapper(elements)));
+ }
+
+ public String deleteInstanceGroupName(InstanceGroup instanceGroup) throws BadResponseException, IOException {
+ Deleteelement deleteElement = namingRequestObjectBuilder.deleteElementMapper(instanceGroup.getId());
+ List<Deleteelement> deleteElements = new ArrayList<Deleteelement>();
+ deleteElements.add(deleteElement);
+ return (namingClient
+ .deleteNameGenRequest(namingRequestObjectBuilder.nameGenDeleteRequestMapper(deleteElements)));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NetworkAdapterResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NetworkAdapterResources.java
index 8f3445529e..b3efa71969 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NetworkAdapterResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NetworkAdapterResources.java
@@ -23,9 +23,7 @@ package org.onap.so.client.orchestration;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Optional;
-
import javax.ws.rs.core.Response;
-
import org.onap.so.adapters.nwrest.CreateNetworkRequest;
import org.onap.so.adapters.nwrest.CreateNetworkResponse;
import org.onap.so.adapters.nwrest.DeleteNetworkRequest;
@@ -48,66 +46,95 @@ import org.springframework.stereotype.Component;
@Component
public class NetworkAdapterResources {
-
- @Autowired
- private NetworkAdapterClientImpl networkAdapterClient;
-
- @Autowired
- private NetworkAdapterObjectMapper networkAdapterObjectMapper;
-
- public Optional<CreateNetworkResponse> createNetwork(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network, Map<String, String> userInput, String cloudRegionPo, Customer customer) throws UnsupportedEncodingException, NetworkAdapterClientException {
-
- CreateNetworkRequest createNetworkRequest = networkAdapterObjectMapper.createNetworkRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, customer);
- return Optional.of(networkAdapterClient.createNetwork(createNetworkRequest));
- }
-
- public Optional<RollbackNetworkResponse> rollbackCreateNetwork(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network, Map<String, String> userInput, String cloudRegionPo, CreateNetworkResponse createNetworkResponse) throws UnsupportedEncodingException, NetworkAdapterClientException {
-
- RollbackNetworkRequest rollbackNetworkRequest = null;
- rollbackNetworkRequest = networkAdapterObjectMapper.createNetworkRollbackRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, createNetworkResponse);
-
- return Optional.of(networkAdapterClient.rollbackNetwork(l3Network.getNetworkId(), rollbackNetworkRequest));
- }
-
- public Optional<UpdateNetworkResponse> updateNetwork(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network, Map<String, String> userInput, Customer customer) throws UnsupportedEncodingException, NetworkAdapterClientException {
- UpdateNetworkRequest updateNetworkRequest = networkAdapterObjectMapper.createNetworkUpdateRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, customer);
-
- return Optional.of(networkAdapterClient.updateNetwork(l3Network.getNetworkId(), updateNetworkRequest));
- }
-
- public Optional<DeleteNetworkResponse> deleteNetwork(RequestContext requestContext, CloudRegion cloudRegion, ServiceInstance serviceInstance, L3Network l3Network) throws UnsupportedEncodingException, NetworkAdapterClientException {
-
- DeleteNetworkRequest deleteNetworkRequest = networkAdapterObjectMapper.deleteNetworkRequestMapper(requestContext, cloudRegion, serviceInstance, l3Network);
- return Optional.of(networkAdapterClient.deleteNetwork(l3Network.getNetworkId(), deleteNetworkRequest));
- }
-
- public Optional<Response> createNetworkAsync(CreateNetworkRequest createNetworkRequest) throws UnsupportedEncodingException, NetworkAdapterClientException {
-
- return Optional.of(networkAdapterClient.createNetworkAsync(createNetworkRequest));
- }
-
- public Optional<Response> deleteNetworkAsync(DeleteNetworkRequest deleteNetworkRequest) throws UnsupportedEncodingException, NetworkAdapterClientException {
-
- return Optional.of(networkAdapterClient.deleteNetworkAsync(deleteNetworkRequest.getNetworkId(), deleteNetworkRequest));
- }
-
- public Optional<Response> updateNetworkAsync(UpdateNetworkRequest updateNetworkRequest) throws UnsupportedEncodingException, NetworkAdapterClientException {
-
- return Optional.of(networkAdapterClient.updateNetworkAsync(updateNetworkRequest.getNetworkId(), updateNetworkRequest));
- }
-
- public Optional<RollbackNetworkResponse> rollbackCreateNetwork(String networkId, RollbackNetworkRequest rollbackNetworkRequest) throws UnsupportedEncodingException, NetworkAdapterClientException {
-
- return Optional.of(networkAdapterClient.rollbackNetwork(networkId, rollbackNetworkRequest));
- }
-
- public Optional<UpdateNetworkResponse> updateNetwork(UpdateNetworkRequest updateNetworkRequest) throws UnsupportedEncodingException, NetworkAdapterClientException {
-
- return Optional.of(networkAdapterClient.updateNetwork(updateNetworkRequest.getNetworkId(), updateNetworkRequest));
- }
-
- public Optional<DeleteNetworkResponse> deleteNetwork(DeleteNetworkRequest deleteNetworkRequest) throws UnsupportedEncodingException, NetworkAdapterClientException {
-
- return Optional.of(networkAdapterClient.deleteNetwork(deleteNetworkRequest.getNetworkId(), deleteNetworkRequest));
- }
+
+ @Autowired
+ private NetworkAdapterClientImpl networkAdapterClient;
+
+ @Autowired
+ private NetworkAdapterObjectMapper networkAdapterObjectMapper;
+
+ public Optional<CreateNetworkResponse> createNetwork(RequestContext requestContext, CloudRegion cloudRegion,
+ OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network,
+ Map<String, String> userInput, String cloudRegionPo, Customer customer)
+ throws UnsupportedEncodingException, NetworkAdapterClientException {
+
+ CreateNetworkRequest createNetworkRequest =
+ networkAdapterObjectMapper.createNetworkRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, l3Network, userInput, cloudRegionPo, customer);
+ return Optional.of(networkAdapterClient.createNetwork(createNetworkRequest));
+ }
+
+ public Optional<RollbackNetworkResponse> rollbackCreateNetwork(RequestContext requestContext,
+ CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance,
+ L3Network l3Network, Map<String, String> userInput, String cloudRegionPo,
+ CreateNetworkResponse createNetworkResponse)
+ throws UnsupportedEncodingException, NetworkAdapterClientException {
+
+ RollbackNetworkRequest rollbackNetworkRequest = null;
+ rollbackNetworkRequest = networkAdapterObjectMapper.createNetworkRollbackRequestMapper(requestContext,
+ cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo,
+ createNetworkResponse);
+
+ return Optional.of(networkAdapterClient.rollbackNetwork(l3Network.getNetworkId(), rollbackNetworkRequest));
+ }
+
+ public Optional<UpdateNetworkResponse> updateNetwork(RequestContext requestContext, CloudRegion cloudRegion,
+ OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network,
+ Map<String, String> userInput, Customer customer)
+ throws UnsupportedEncodingException, NetworkAdapterClientException {
+ UpdateNetworkRequest updateNetworkRequest = networkAdapterObjectMapper.createNetworkUpdateRequestMapper(
+ requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, customer);
+
+ return Optional.of(networkAdapterClient.updateNetwork(l3Network.getNetworkId(), updateNetworkRequest));
+ }
+
+ public Optional<DeleteNetworkResponse> deleteNetwork(RequestContext requestContext, CloudRegion cloudRegion,
+ ServiceInstance serviceInstance, L3Network l3Network)
+ throws UnsupportedEncodingException, NetworkAdapterClientException {
+
+ DeleteNetworkRequest deleteNetworkRequest = networkAdapterObjectMapper
+ .deleteNetworkRequestMapper(requestContext, cloudRegion, serviceInstance, l3Network);
+ return Optional.of(networkAdapterClient.deleteNetwork(l3Network.getNetworkId(), deleteNetworkRequest));
+ }
+
+ public Optional<Response> createNetworkAsync(CreateNetworkRequest createNetworkRequest)
+ throws UnsupportedEncodingException, NetworkAdapterClientException {
+
+ return Optional.of(networkAdapterClient.createNetworkAsync(createNetworkRequest));
+ }
+
+ public Optional<Response> deleteNetworkAsync(DeleteNetworkRequest deleteNetworkRequest)
+ throws UnsupportedEncodingException, NetworkAdapterClientException {
+
+ return Optional
+ .of(networkAdapterClient.deleteNetworkAsync(deleteNetworkRequest.getNetworkId(), deleteNetworkRequest));
+ }
+
+ public Optional<Response> updateNetworkAsync(UpdateNetworkRequest updateNetworkRequest)
+ throws UnsupportedEncodingException, NetworkAdapterClientException {
+
+ return Optional
+ .of(networkAdapterClient.updateNetworkAsync(updateNetworkRequest.getNetworkId(), updateNetworkRequest));
+ }
+
+ public Optional<RollbackNetworkResponse> rollbackCreateNetwork(String networkId,
+ RollbackNetworkRequest rollbackNetworkRequest)
+ throws UnsupportedEncodingException, NetworkAdapterClientException {
+
+ return Optional.of(networkAdapterClient.rollbackNetwork(networkId, rollbackNetworkRequest));
+ }
+
+ public Optional<UpdateNetworkResponse> updateNetwork(UpdateNetworkRequest updateNetworkRequest)
+ throws UnsupportedEncodingException, NetworkAdapterClientException {
+
+ return Optional
+ .of(networkAdapterClient.updateNetwork(updateNetworkRequest.getNetworkId(), updateNetworkRequest));
+ }
+
+ public Optional<DeleteNetworkResponse> deleteNetwork(DeleteNetworkRequest deleteNetworkRequest)
+ throws UnsupportedEncodingException, NetworkAdapterClientException {
+
+ return Optional
+ .of(networkAdapterClient.deleteNetwork(deleteNetworkRequest.getNetworkId(), deleteNetworkRequest));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCConfigurationResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCConfigurationResources.java
index 9dc03ecb88..ca32130c23 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCConfigurationResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCConfigurationResources.java
@@ -34,90 +34,83 @@ import org.onap.so.client.sdnc.endpoint.SDNCTopology;
import org.onap.so.client.sdnc.mapper.GCTopologyOperationRequestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import java.net.URI;
-
import org.onap.sdnc.northbound.client.model.GenericResourceApiGcTopologyOperationInformation;
import org.onap.sdnc.northbound.client.model.GenericResourceApiRequestActionEnumeration;
@Component
public class SDNCConfigurationResources {
- @Autowired
- private GCTopologyOperationRequestMapper sdncRM;
+ @Autowired
+ private GCTopologyOperationRequestMapper sdncRM;
- /**
- * SDN-C call to assign configuration after it was created in A&AI
- *
- * @param serviceInstance
- * @param requestContext
- * @param vnrConfiguration
- * @param voiceVnf
- * @return
- * @throws MapperException
- * @throws BadResponseException
- */
- public GenericResourceApiGcTopologyOperationInformation assignVnrConfiguration(ServiceInstance serviceInstance,
- RequestContext requestContext,
- Customer customer,
- Configuration vnrConfiguration,
- GenericVnf voiceVnf, String sdncRequestId, URI callbackUri)
- throws MapperException, BadResponseException {
- return sdncRM.assignOrActivateVnrReqMapper(
- SDNCSvcAction.ASSIGN,
- GenericResourceApiRequestActionEnumeration.CREATEGENERICCONFIGURATIONINSTANCE ,
- serviceInstance , requestContext, customer, vnrConfiguration,voiceVnf,sdncRequestId,callbackUri);
- }
+ /**
+ * SDN-C call to assign configuration after it was created in A&AI
+ *
+ * @param serviceInstance
+ * @param requestContext
+ * @param vnrConfiguration
+ * @param voiceVnf
+ * @return
+ * @throws MapperException
+ * @throws BadResponseException
+ */
+ public GenericResourceApiGcTopologyOperationInformation assignVnrConfiguration(ServiceInstance serviceInstance,
+ RequestContext requestContext, Customer customer, Configuration vnrConfiguration, GenericVnf voiceVnf,
+ String sdncRequestId, URI callbackUri) throws MapperException, BadResponseException {
+ return sdncRM.assignOrActivateVnrReqMapper(SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATEGENERICCONFIGURATIONINSTANCE, serviceInstance,
+ requestContext, customer, vnrConfiguration, voiceVnf, sdncRequestId, callbackUri);
+ }
- /**
- * SDNC Call to Activate VNR Configuration
- *
- * @param serviceInstance
- * @param requestContext
- * @param vnrConfiguration
- * @param voiceVnf
- * @return
- * @throws MapperException
- * @throws BadResponseException
- */
- public GenericResourceApiGcTopologyOperationInformation activateVnrConfiguration(ServiceInstance serviceInstance,
- RequestContext requestContext,
- Customer customer,
- Configuration vnrConfiguration,
- GenericVnf voiceVnf, String sdncRequestId, URI callbackUri)
- throws MapperException, BadResponseException {
- return sdncRM.assignOrActivateVnrReqMapper(
- SDNCSvcAction.ACTIVATE,
- GenericResourceApiRequestActionEnumeration.CREATEGENERICCONFIGURATIONINSTANCE,
- serviceInstance , requestContext, customer, vnrConfiguration, voiceVnf,sdncRequestId,callbackUri);
- }
+ /**
+ * SDNC Call to Activate VNR Configuration
+ *
+ * @param serviceInstance
+ * @param requestContext
+ * @param vnrConfiguration
+ * @param voiceVnf
+ * @return
+ * @throws MapperException
+ * @throws BadResponseException
+ */
+ public GenericResourceApiGcTopologyOperationInformation activateVnrConfiguration(ServiceInstance serviceInstance,
+ RequestContext requestContext, Customer customer, Configuration vnrConfiguration, GenericVnf voiceVnf,
+ String sdncRequestId, URI callbackUri) throws MapperException, BadResponseException {
+ return sdncRM.assignOrActivateVnrReqMapper(SDNCSvcAction.ACTIVATE,
+ GenericResourceApiRequestActionEnumeration.CREATEGENERICCONFIGURATIONINSTANCE, serviceInstance,
+ requestContext, customer, vnrConfiguration, voiceVnf, sdncRequestId, callbackUri);
+ }
- /**
- * method to unAssign Vnr Configuration in SDNC
- *
- * @param serviceInstance
- * @param requestContext
- * @param vnrConfiguration
- * @return
- * @throws BadResponseException
- * @throws MapperException
- */
- public GenericResourceApiGcTopologyOperationInformation unAssignVnrConfiguration(ServiceInstance serviceInstance, RequestContext requestContext,
- Configuration vnrConfiguration, String sdncRequestId, URI callbackUri) throws BadResponseException, MapperException {
- return sdncRM.deactivateOrUnassignVnrReqMapper
- (SDNCSvcAction.UNASSIGN,serviceInstance, requestContext, vnrConfiguration,sdncRequestId,callbackUri);
- }
+ /**
+ * method to unAssign Vnr Configuration in SDNC
+ *
+ * @param serviceInstance
+ * @param requestContext
+ * @param vnrConfiguration
+ * @return
+ * @throws BadResponseException
+ * @throws MapperException
+ */
+ public GenericResourceApiGcTopologyOperationInformation unAssignVnrConfiguration(ServiceInstance serviceInstance,
+ RequestContext requestContext, Configuration vnrConfiguration, String sdncRequestId, URI callbackUri)
+ throws BadResponseException, MapperException {
+ return sdncRM.deactivateOrUnassignVnrReqMapper(SDNCSvcAction.UNASSIGN, serviceInstance, requestContext,
+ vnrConfiguration, sdncRequestId, callbackUri);
+ }
- /***
- * Deactivate VNR SDNC Call
- * @param serviceInstance
- * @param requestContext
- * @param vnrConfiguration
- * @throws BadResponseException
- * @throws MapperException
- */
- public GenericResourceApiGcTopologyOperationInformation deactivateVnrConfiguration(ServiceInstance serviceInstance, RequestContext requestContext, Configuration vnrConfiguration, String sdncRequestId, URI callbackUri) throws BadResponseException, MapperException {
- return sdncRM.deactivateOrUnassignVnrReqMapper(
- SDNCSvcAction.DEACTIVATE,
- serviceInstance , requestContext, vnrConfiguration,sdncRequestId,callbackUri);
- }
+ /***
+ * Deactivate VNR SDNC Call
+ *
+ * @param serviceInstance
+ * @param requestContext
+ * @param vnrConfiguration
+ * @throws BadResponseException
+ * @throws MapperException
+ */
+ public GenericResourceApiGcTopologyOperationInformation deactivateVnrConfiguration(ServiceInstance serviceInstance,
+ RequestContext requestContext, Configuration vnrConfiguration, String sdncRequestId, URI callbackUri)
+ throws BadResponseException, MapperException {
+ return sdncRM.deactivateOrUnassignVnrReqMapper(SDNCSvcAction.DEACTIVATE, serviceInstance, requestContext,
+ vnrConfiguration, sdncRequestId, callbackUri);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCNetworkResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCNetworkResources.java
index fb828c1981..54a9cabb57 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCNetworkResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCNetworkResources.java
@@ -39,64 +39,64 @@ import org.springframework.stereotype.Component;
@Component
public class SDNCNetworkResources {
- private static final Logger logger = LoggerFactory.getLogger(SDNCNetworkResources.class);
+ private static final Logger logger = LoggerFactory.getLogger(SDNCNetworkResources.class);
- @Autowired
- private NetworkTopologyOperationRequestMapper sdncRM;
+ @Autowired
+ private NetworkTopologyOperationRequestMapper sdncRM;
- public GenericResourceApiNetworkOperationInformation assignNetwork(L3Network network,
- ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
- CloudRegion cloudRegion) {
- return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
- GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
+ public GenericResourceApiNetworkOperationInformation assignNetwork(L3Network network,
+ ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
+ CloudRegion cloudRegion) {
+ return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
- public GenericResourceApiNetworkOperationInformation rollbackAssignNetwork(L3Network network,
- ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
- CloudRegion cloudRegion) {
- return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
- GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
+ public GenericResourceApiNetworkOperationInformation rollbackAssignNetwork(L3Network network,
+ ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
+ CloudRegion cloudRegion) {
+ return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
- public GenericResourceApiNetworkOperationInformation activateNetwork(L3Network network,
- ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
- CloudRegion cloudRegion) {
- return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE,
- GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
+ public GenericResourceApiNetworkOperationInformation activateNetwork(L3Network network,
+ ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
+ CloudRegion cloudRegion) {
+ return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
- public GenericResourceApiNetworkOperationInformation deactivateNetwork(L3Network network,
- ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
- CloudRegion cloudRegion) {
- return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE,
- GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
+ public GenericResourceApiNetworkOperationInformation deactivateNetwork(L3Network network,
+ ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
+ CloudRegion cloudRegion) {
+ return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
- public GenericResourceApiNetworkOperationInformation deleteNetwork(L3Network network,
- ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
- CloudRegion cloudRegion) {
- return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.DELETE,
- GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
+ public GenericResourceApiNetworkOperationInformation deleteNetwork(L3Network network,
+ ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
+ CloudRegion cloudRegion) {
+ return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.DELETE,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
- public GenericResourceApiNetworkOperationInformation changeAssignNetwork(L3Network network,
- ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
- CloudRegion cloudRegion) {
- return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN,
- GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
+ public GenericResourceApiNetworkOperationInformation changeAssignNetwork(L3Network network,
+ ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
+ CloudRegion cloudRegion) {
+ return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
- public GenericResourceApiNetworkOperationInformation unassignNetwork(L3Network network,
- ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
- CloudRegion cloudRegion) {
- return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
- GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
+ public GenericResourceApiNetworkOperationInformation unassignNetwork(L3Network network,
+ ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
+ CloudRegion cloudRegion) {
+ return sdncRM.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCServiceInstanceResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCServiceInstanceResources.java
index a4c9b8fe05..960efea2f0 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCServiceInstanceResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCServiceInstanceResources.java
@@ -36,82 +36,81 @@ import org.springframework.stereotype.Component;
@Component
public class SDNCServiceInstanceResources {
- @Autowired
- private ServiceTopologyOperationMapper sdncRM;
+ @Autowired
+ private ServiceTopologyOperationMapper sdncRM;
- /**
- * SDNC call to perform Service Topology Assign for ServiceInsatnce
- *
- * @param serviceInstance
- * @param customer
- * @param requestContext
- * @throws MapperException
- * @throws BadResponseException
- * @return the response as a String
- */
- public GenericResourceApiServiceOperationInformation assignServiceInstance(ServiceInstance serviceInstance,
- Customer customer, RequestContext requestContext) {
- return sdncRM.reqMapper(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
- GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE, serviceInstance, customer,
- requestContext);
- }
+ /**
+ * SDNC call to perform Service Topology Assign for ServiceInsatnce
+ *
+ * @param serviceInstance
+ * @param customer
+ * @param requestContext
+ * @throws MapperException
+ * @throws BadResponseException
+ * @return the response as a String
+ */
+ public GenericResourceApiServiceOperationInformation assignServiceInstance(ServiceInstance serviceInstance,
+ Customer customer, RequestContext requestContext) {
+ return sdncRM.reqMapper(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE, serviceInstance, customer,
+ requestContext);
+ }
- /**
- * SDNC call to perform Service Topology Delete for ServiceInsatnce
- *
- * @param serviceInstance
- * @param customer
- * @param requestContext
- * @throws MapperException
- * @throws BadResponseException
- * @return the response as a String
- */
- public GenericResourceApiServiceOperationInformation deleteServiceInstance(ServiceInstance serviceInstance,
- Customer customer, RequestContext requestContext) {
- return sdncRM.reqMapper(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.DELETE,
- GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE, serviceInstance, customer,
- requestContext);
- }
+ /**
+ * SDNC call to perform Service Topology Delete for ServiceInsatnce
+ *
+ * @param serviceInstance
+ * @param customer
+ * @param requestContext
+ * @throws MapperException
+ * @throws BadResponseException
+ * @return the response as a String
+ */
+ public GenericResourceApiServiceOperationInformation deleteServiceInstance(ServiceInstance serviceInstance,
+ Customer customer, RequestContext requestContext) {
+ return sdncRM.reqMapper(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.DELETE,
+ GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE, serviceInstance, customer,
+ requestContext);
+ }
- public GenericResourceApiServiceOperationInformation unassignServiceInstance(ServiceInstance serviceInstance,
- Customer customer, RequestContext requestContext) {
- return sdncRM.reqMapper(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.DELETE,
- GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE, serviceInstance, customer,
- requestContext);
- }
+ public GenericResourceApiServiceOperationInformation unassignServiceInstance(ServiceInstance serviceInstance,
+ Customer customer, RequestContext requestContext) {
+ return sdncRM.reqMapper(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.DELETE,
+ GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE, serviceInstance, customer,
+ requestContext);
+ }
- /**
- * SDNC call to perform Service Topology Deactivate for ServiceInstance
- *
- * @param serviceInstance
- * @param customer
- * @param requestContext
- * @throws MapperException
- * @throws BadResponseException
- * @return the response as a String
- */
- public GenericResourceApiServiceOperationInformation deactivateServiceInstance(ServiceInstance serviceInstance,
- Customer customer, RequestContext requestContext) {
- return sdncRM.reqMapper(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE,
- GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE, serviceInstance, customer,
- requestContext);
- }
+ /**
+ * SDNC call to perform Service Topology Deactivate for ServiceInstance
+ *
+ * @param serviceInstance
+ * @param customer
+ * @param requestContext
+ * @throws MapperException
+ * @throws BadResponseException
+ * @return the response as a String
+ */
+ public GenericResourceApiServiceOperationInformation deactivateServiceInstance(ServiceInstance serviceInstance,
+ Customer customer, RequestContext requestContext) {
+ return sdncRM.reqMapper(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE,
+ GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE, serviceInstance, customer,
+ requestContext);
+ }
- /**
- * SDNC call to perform Service Topology Change Assign for the
- * ServiceInstance
- *
- * @param serviceInstance
- * @param customer
- * @param requestContext
- * @throws MapperException
- * @throws BadResponseException
- * @return the response as a String
- */
- public GenericResourceApiServiceOperationInformation changeModelServiceInstance(ServiceInstance serviceInstance,
- Customer customer, RequestContext requestContext) {
- return sdncRM.reqMapper(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN,
- GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE, serviceInstance, customer,
- requestContext);
- }
+ /**
+ * SDNC call to perform Service Topology Change Assign for the ServiceInstance
+ *
+ * @param serviceInstance
+ * @param customer
+ * @param requestContext
+ * @throws MapperException
+ * @throws BadResponseException
+ * @return the response as a String
+ */
+ public GenericResourceApiServiceOperationInformation changeModelServiceInstance(ServiceInstance serviceInstance,
+ Customer customer, RequestContext requestContext) {
+ return sdncRM.reqMapper(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE, serviceInstance, customer,
+ requestContext);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVfModuleResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVfModuleResources.java
index 1e3d655298..60cad78f5d 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVfModuleResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVfModuleResources.java
@@ -43,50 +43,50 @@ import org.springframework.stereotype.Component;
@Component
public class SDNCVfModuleResources {
- private static final Logger logger = LoggerFactory.getLogger(SDNCVfModuleResources.class);
+ private static final Logger logger = LoggerFactory.getLogger(SDNCVfModuleResources.class);
- @Autowired
- private VfModuleTopologyOperationRequestMapper sdncRM;
+ @Autowired
+ private VfModuleTopologyOperationRequestMapper sdncRM;
- @Autowired
- private SDNCClient sdncClient;
+ @Autowired
+ private SDNCClient sdncClient;
- public GenericResourceApiVfModuleOperationInformation assignVfModule(VfModule vfModule, VolumeGroup volumeGroup,
- GenericVnf vnf, ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion,
- RequestContext requestContext) throws MapperException {
- return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule,
- volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext, null);
- }
+ public GenericResourceApiVfModuleOperationInformation assignVfModule(VfModule vfModule, VolumeGroup volumeGroup,
+ GenericVnf vnf, ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion,
+ RequestContext requestContext) throws MapperException {
+ return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule,
+ volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext, null);
+ }
- public GenericResourceApiVfModuleOperationInformation unassignVfModule(VfModule vfModule, GenericVnf vnf,
- ServiceInstance serviceInstance) throws MapperException {
- return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null,
- vnf, serviceInstance, null, null, null, null);
- }
+ public GenericResourceApiVfModuleOperationInformation unassignVfModule(VfModule vfModule, GenericVnf vnf,
+ ServiceInstance serviceInstance) throws MapperException {
+ return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null,
+ vnf, serviceInstance, null, null, null, null);
+ }
- public GenericResourceApiVfModuleOperationInformation deactivateVfModule(VfModule vfModule, GenericVnf vnf,
- ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext)
- throws MapperException {
- return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE, vfModule, null,
- vnf, serviceInstance, customer, cloudRegion, requestContext, null);
- }
+ public GenericResourceApiVfModuleOperationInformation deactivateVfModule(VfModule vfModule, GenericVnf vnf,
+ ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext)
+ throws MapperException {
+ return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE, vfModule, null,
+ vnf, serviceInstance, customer, cloudRegion, requestContext, null);
+ }
- public String queryVfModule(VfModule vfModule) throws MapperException, BadResponseException {
- String objectPath = vfModule.getSelflink();
- return sdncClient.get(objectPath);
- }
+ public String queryVfModule(VfModule vfModule) throws MapperException, BadResponseException {
+ String objectPath = vfModule.getSelflink();
+ return sdncClient.get(objectPath);
+ }
- public GenericResourceApiVfModuleOperationInformation activateVfModule(VfModule vfModule, GenericVnf vnf,
- ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext)
- throws MapperException {
- return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE, vfModule, null,
- vnf, serviceInstance, customer, cloudRegion, requestContext, null);
- }
+ public GenericResourceApiVfModuleOperationInformation activateVfModule(VfModule vfModule, GenericVnf vnf,
+ ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext)
+ throws MapperException {
+ return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE, vfModule, null,
+ vnf, serviceInstance, customer, cloudRegion, requestContext, null);
+ }
- public GenericResourceApiVfModuleOperationInformation changeAssignVfModule(VfModule vfModule, GenericVnf vnf,
- ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext)
- throws MapperException {
- return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN, vfModule,
- null, vnf, serviceInstance, customer, cloudRegion, requestContext, null);
- }
+ public GenericResourceApiVfModuleOperationInformation changeAssignVfModule(VfModule vfModule, GenericVnf vnf,
+ ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext)
+ throws MapperException {
+ return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN, vfModule,
+ null, vnf, serviceInstance, customer, cloudRegion, requestContext, null);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVnfResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVnfResources.java
index d8f2e47224..954cbc1b1d 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVnfResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVnfResources.java
@@ -42,54 +42,60 @@ import org.springframework.stereotype.Component;
@Component
public class SDNCVnfResources {
- private static final Logger logger = LoggerFactory.getLogger(SDNCVnfResources.class);
+ private static final Logger logger = LoggerFactory.getLogger(SDNCVnfResources.class);
- @Autowired
- private VnfTopologyOperationRequestMapper sdncRM;
-
- @Autowired
- private SDNCClient sdncClient;
-
- public GenericResourceApiVnfOperationInformation assignVnf(GenericVnf vnf, ServiceInstance serviceInstance, Customer customer,
- CloudRegion cloudRegion, RequestContext requestContext, boolean homing) {
- return sdncRM.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION,
- SDNCSvcAction.ASSIGN,GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, vnf, serviceInstance, customer, cloudRegion, requestContext, homing);
- }
+ @Autowired
+ private VnfTopologyOperationRequestMapper sdncRM;
- public GenericResourceApiVnfOperationInformation activateVnf(GenericVnf vnf, ServiceInstance serviceInstance, Customer customer,
- CloudRegion cloudRegion, RequestContext requestContext) {
- return sdncRM.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION,
- SDNCSvcAction.ACTIVATE,GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, vnf, serviceInstance, customer,cloudRegion, requestContext, false);
- }
+ @Autowired
+ private SDNCClient sdncClient;
-
- public GenericResourceApiVnfOperationInformation deactivateVnf(GenericVnf vnf, ServiceInstance serviceInstance, Customer customer,
- CloudRegion cloudRegion, RequestContext requestContext) {
- return sdncRM.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION,
- SDNCSvcAction.DEACTIVATE,GenericResourceApiRequestActionEnumeration.DELETEVNFINSTANCE, vnf, serviceInstance, customer,cloudRegion, requestContext, false);
- }
+ public GenericResourceApiVnfOperationInformation assignVnf(GenericVnf vnf, ServiceInstance serviceInstance,
+ Customer customer, CloudRegion cloudRegion, RequestContext requestContext, boolean homing) {
+ return sdncRM.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, vnf, serviceInstance, customer,
+ cloudRegion, requestContext, homing);
+ }
-
- public GenericResourceApiVnfOperationInformation unassignVnf(GenericVnf vnf, ServiceInstance serviceInstance, Customer customer,
- CloudRegion cloudRegion, RequestContext requestContext) {
- return sdncRM.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION,
- SDNCSvcAction.UNASSIGN,GenericResourceApiRequestActionEnumeration.DELETEVNFINSTANCE, vnf, serviceInstance, customer, cloudRegion, requestContext, false);
- }
-
- public GenericResourceApiVnfOperationInformation deleteVnf(GenericVnf vnf, ServiceInstance serviceInstance, Customer customer,
- CloudRegion cloudRegion, RequestContext requestContext) {
- return sdncRM.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION,
- SDNCSvcAction.DEACTIVATE, GenericResourceApiRequestActionEnumeration.DELETEVNFINSTANCE,vnf, serviceInstance, customer, cloudRegion, requestContext, false);
- }
-
- public GenericResourceApiVnfOperationInformation changeModelVnf(GenericVnf vnf, ServiceInstance serviceInstance, Customer customer,
- CloudRegion cloudRegion, RequestContext requestContext) {
- return sdncRM.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION,
- SDNCSvcAction.CHANGE_ASSIGN,GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, vnf, serviceInstance, customer, cloudRegion, requestContext, false);
- }
-
- public String queryVnf(GenericVnf vnf) throws MapperException, BadResponseException {
- String queryPath = vnf.getSelflink();
- return sdncClient.get(queryPath);
- }
+ public GenericResourceApiVnfOperationInformation activateVnf(GenericVnf vnf, ServiceInstance serviceInstance,
+ Customer customer, CloudRegion cloudRegion, RequestContext requestContext) {
+ return sdncRM.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE,
+ GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, vnf, serviceInstance, customer,
+ cloudRegion, requestContext, false);
+ }
+
+
+ public GenericResourceApiVnfOperationInformation deactivateVnf(GenericVnf vnf, ServiceInstance serviceInstance,
+ Customer customer, CloudRegion cloudRegion, RequestContext requestContext) {
+ return sdncRM.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE,
+ GenericResourceApiRequestActionEnumeration.DELETEVNFINSTANCE, vnf, serviceInstance, customer,
+ cloudRegion, requestContext, false);
+ }
+
+
+ public GenericResourceApiVnfOperationInformation unassignVnf(GenericVnf vnf, ServiceInstance serviceInstance,
+ Customer customer, CloudRegion cloudRegion, RequestContext requestContext) {
+ return sdncRM.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
+ GenericResourceApiRequestActionEnumeration.DELETEVNFINSTANCE, vnf, serviceInstance, customer,
+ cloudRegion, requestContext, false);
+ }
+
+ public GenericResourceApiVnfOperationInformation deleteVnf(GenericVnf vnf, ServiceInstance serviceInstance,
+ Customer customer, CloudRegion cloudRegion, RequestContext requestContext) {
+ return sdncRM.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE,
+ GenericResourceApiRequestActionEnumeration.DELETEVNFINSTANCE, vnf, serviceInstance, customer,
+ cloudRegion, requestContext, false);
+ }
+
+ public GenericResourceApiVnfOperationInformation changeModelVnf(GenericVnf vnf, ServiceInstance serviceInstance,
+ Customer customer, CloudRegion cloudRegion, RequestContext requestContext) {
+ return sdncRM.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, vnf, serviceInstance, customer,
+ cloudRegion, requestContext, false);
+ }
+
+ public String queryVnf(GenericVnf vnf) throws MapperException, BadResponseException {
+ String queryPath = vnf.getSelflink();
+ return sdncClient.get(queryPath);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNOHealthCheckResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNOHealthCheckResources.java
index dac89a495d..e93b80c562 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNOHealthCheckResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNOHealthCheckResources.java
@@ -21,7 +21,6 @@
package org.onap.so.client.orchestration;
import java.util.UUID;
-
import org.onap.so.bpmn.common.InjectionHelper;
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
@@ -30,24 +29,23 @@ import org.springframework.stereotype.Component;
@Component
public class SDNOHealthCheckResources {
- @Autowired
- private InjectionHelper injectionHelper;
-
+ @Autowired
+ private InjectionHelper injectionHelper;
+
/**
* SDNO Call to Check Health Status
*
* @param vnf
- * @param requestContext *
+ * @param requestContext *
* @return healthCheckResult
- * @throws
- * @throws Exception
+ * @throws @throws Exception
*/
public boolean healthCheck(GenericVnf vnf, RequestContext requestContext) throws Exception {
- String requestId = requestContext.getMsoRequestId();
- String requestorId = requestContext.getRequestorId();
- String vnfId = vnf.getVnfId();
- UUID uuid = UUID.fromString(requestId);
+ String requestId = requestContext.getMsoRequestId();
+ String requestorId = requestContext.getRequestorId();
+ String vnfId = vnf.getVnfId();
+ UUID uuid = UUID.fromString(requestId);
- return injectionHelper.getSdnoValidator().healthDiagnostic(vnfId, uuid, requestorId);
- }
+ return injectionHelper.getSdnoValidator().healthDiagnostic(vnfId, uuid, requestorId);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResources.java
index de59e6835e..939f53727d 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResources.java
@@ -23,7 +23,6 @@
package org.onap.so.client.orchestration;
import java.io.IOException;
-
import org.onap.so.adapters.vnfrest.CreateVfModuleRequest;
import org.onap.so.adapters.vnfrest.DeleteVfModuleRequest;
import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
@@ -41,19 +40,23 @@ import org.springframework.stereotype.Component;
@Component
public class VnfAdapterVfModuleResources {
- private static final Logger logger = LoggerFactory.getLogger(VnfAdapterVfModuleResources.class);
-
- @Autowired
- private VnfAdapterVfModuleObjectMapper vnfAdapterVfModuleObjectMapper;
-
- public CreateVfModuleRequest createVfModuleRequest(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, GenericVnf genericVnf,
- VfModule vfModule, VolumeGroup volumeGroup, String sdncVnfQueryResponse, String sdncVfModuleQueryResponse) throws IOException {
- return vnfAdapterVfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, vfModule, volumeGroup, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
- }
-
- public DeleteVfModuleRequest deleteVfModuleRequest(RequestContext requestContext, CloudRegion cloudRegion,
- ServiceInstance serviceInstance, GenericVnf genericVnf,
- VfModule vfModule) throws IOException {
- return vnfAdapterVfModuleObjectMapper.deleteVfModuleRequestMapper(requestContext, cloudRegion, serviceInstance, genericVnf, vfModule);
- }
+ private static final Logger logger = LoggerFactory.getLogger(VnfAdapterVfModuleResources.class);
+
+ @Autowired
+ private VnfAdapterVfModuleObjectMapper vnfAdapterVfModuleObjectMapper;
+
+ public CreateVfModuleRequest createVfModuleRequest(RequestContext requestContext, CloudRegion cloudRegion,
+ OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, GenericVnf genericVnf,
+ VfModule vfModule, VolumeGroup volumeGroup, String sdncVnfQueryResponse, String sdncVfModuleQueryResponse)
+ throws IOException {
+ return vnfAdapterVfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, genericVnf, vfModule, volumeGroup, sdncVnfQueryResponse,
+ sdncVfModuleQueryResponse);
+ }
+
+ public DeleteVfModuleRequest deleteVfModuleRequest(RequestContext requestContext, CloudRegion cloudRegion,
+ ServiceInstance serviceInstance, GenericVnf genericVnf, VfModule vfModule) throws IOException {
+ return vnfAdapterVfModuleObjectMapper.deleteVfModuleRequestMapper(requestContext, cloudRegion, serviceInstance,
+ genericVnf, vfModule);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResources.java
index 737e9eeb37..c97ca8e0ea 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResources.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResources.java
@@ -39,19 +39,24 @@ import org.springframework.stereotype.Component;
@Component
public class VnfAdapterVolumeGroupResources {
- private static final Logger logger = LoggerFactory.getLogger(VnfAdapterVolumeGroupResources.class);
+ private static final Logger logger = LoggerFactory.getLogger(VnfAdapterVolumeGroupResources.class);
- @Autowired
- private VnfAdapterObjectMapper vnfAdapterObjectMapper;
-
- @Autowired
- private VnfVolumeAdapterClientImpl vnfVolumeAdapterClient;
-
- public CreateVolumeGroupRequest createVolumeGroupRequest(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, GenericVnf genericVnf, VolumeGroup volumeGroup, String sdncVfModuleQueryResponse) throws Exception {
- return vnfAdapterObjectMapper.createVolumeGroupRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse);
- }
-
- public DeleteVolumeGroupRequest deleteVolumeGroupRequest(RequestContext requestContext, CloudRegion cloudRegion, ServiceInstance serviceInstance, VolumeGroup volumeGroup) throws Exception {
- return vnfAdapterObjectMapper.deleteVolumeGroupRequestMapper(requestContext, cloudRegion, serviceInstance, volumeGroup);
- }
+ @Autowired
+ private VnfAdapterObjectMapper vnfAdapterObjectMapper;
+
+ @Autowired
+ private VnfVolumeAdapterClientImpl vnfVolumeAdapterClient;
+
+ public CreateVolumeGroupRequest createVolumeGroupRequest(RequestContext requestContext, CloudRegion cloudRegion,
+ OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, GenericVnf genericVnf,
+ VolumeGroup volumeGroup, String sdncVfModuleQueryResponse) throws Exception {
+ return vnfAdapterObjectMapper.createVolumeGroupRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse);
+ }
+
+ public DeleteVolumeGroupRequest deleteVolumeGroupRequest(RequestContext requestContext, CloudRegion cloudRegion,
+ ServiceInstance serviceInstance, VolumeGroup volumeGroup) throws Exception {
+ return vnfAdapterObjectMapper.deleteVolumeGroupRequestMapper(requestContext, cloudRegion, serviceInstance,
+ volumeGroup);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java
index cae4a19f20..732bba8489 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java
@@ -23,9 +23,7 @@
package org.onap.so.client.sdnc;
import java.util.LinkedHashMap;
-
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.bpmn.common.baseclient.BaseClient;
import org.onap.so.client.exception.BadResponseException;
import org.onap.so.client.exception.MapperException;
@@ -41,65 +39,63 @@ import org.springframework.stereotype.Component;
@Component
public class SDNCClient {
- private static final Logger logger = LoggerFactory.getLogger(SDNCClient.class);
+ private static final Logger logger = LoggerFactory.getLogger(SDNCClient.class);
+
+ @Autowired
+ private SDNCProperties properties;
+ @Autowired
+ private SdnCommonTasks sdnCommonTasks;
+
+ /**
+ *
+ * @param request - takes in a generated object from sdnc client - creates a json request string and sends it to
+ * sdnc - receives and validates the linkedhashmap sent back from sdnc
+ * @throws MapperException
+ * @throws BadResponseException
+ */
+ public String post(Object request, SDNCTopology topology) throws MapperException, BadResponseException {
+ String jsonRequest = sdnCommonTasks.buildJsonRequest(request);
+ String targetUrl = properties.getHost() + properties.getPath() + ":" + topology.toString() + "/";
+ BaseClient<String, LinkedHashMap<String, Object>> STOClient = new BaseClient<>();
+
+ STOClient.setTargetUrl(targetUrl);
+ HttpHeaders httpHeader = sdnCommonTasks.getHttpHeaders(properties.getAuth());
+ STOClient.setHttpHeader(httpHeader);
+ LinkedHashMap<String, Object> output =
+ STOClient.post(jsonRequest, new ParameterizedTypeReference<LinkedHashMap<String, Object>>() {});
+ return sdnCommonTasks.validateSDNResponse(output);
+ }
+
- @Autowired
- private SDNCProperties properties;
- @Autowired
- private SdnCommonTasks sdnCommonTasks;
-
- /**
- *
- * @param request
- * - takes in a generated object from sdnc client
- * - creates a json request string and sends it to sdnc
- * - receives and validates the linkedhashmap sent back from sdnc
- * @throws MapperException
- * @throws BadResponseException
- */
- public String post(Object request, SDNCTopology topology) throws MapperException, BadResponseException {
- String jsonRequest = sdnCommonTasks.buildJsonRequest(request);
- String targetUrl = properties.getHost() + properties.getPath() + ":" + topology.toString() + "/";
- BaseClient<String, LinkedHashMap<String, Object>> STOClient = new BaseClient<>();
+ public String post(Object request, String url) throws MapperException, BadResponseException {
+ String jsonRequest = sdnCommonTasks.buildJsonRequest(request);
+ BaseClient<String, LinkedHashMap<String, Object>> STOClient = new BaseClient<>();
+ STOClient.setTargetUrl(url);
+ HttpHeaders httpHeader = sdnCommonTasks.getHttpHeaders(properties.getAuth());
+ STOClient.setHttpHeader(httpHeader);
+ LinkedHashMap<String, Object> output =
+ STOClient.post(jsonRequest, new ParameterizedTypeReference<LinkedHashMap<String, Object>>() {});
+ return sdnCommonTasks.validateSDNResponse(output);
+ }
- STOClient.setTargetUrl(targetUrl);
- HttpHeaders httpHeader = sdnCommonTasks.getHttpHeaders(properties.getAuth());
- STOClient.setHttpHeader(httpHeader);
- LinkedHashMap<String, Object> output = STOClient.post(jsonRequest, new ParameterizedTypeReference<LinkedHashMap<String, Object>>() {});
- return sdnCommonTasks.validateSDNResponse(output);
- }
-
-
- public String post(Object request, String url) throws MapperException, BadResponseException {
- String jsonRequest = sdnCommonTasks.buildJsonRequest(request);
- BaseClient<String, LinkedHashMap<String, Object>> STOClient = new BaseClient<>();
- STOClient.setTargetUrl(url);
- HttpHeaders httpHeader = sdnCommonTasks.getHttpHeaders(properties.getAuth());
- STOClient.setHttpHeader(httpHeader);
- LinkedHashMap<String, Object> output = STOClient.post(jsonRequest, new ParameterizedTypeReference<LinkedHashMap<String, Object>>() {});
- return sdnCommonTasks.validateSDNResponse(output);
- }
-
- /**
- *
- * @param queryLink
- * - takes in a link to topology that needs to be queried
- * - creates a json request string and sends it to sdnc
- * - receives and validates the linkedhashmap sent back from sdnc
- * *
- * @throws MapperException
- * @throws BadResponseException
- */
- public String get(String queryLink) throws MapperException, BadResponseException {
- String request = "";
- String jsonRequest = sdnCommonTasks.buildJsonRequest(request);
- String targetUrl = UriBuilder.fromUri(properties.getHost()).path(queryLink).build().toString();
- BaseClient<String, LinkedHashMap<String, Object>> STOClient = new BaseClient<>();
- STOClient.setTargetUrl(targetUrl);
- HttpHeaders httpHeader = sdnCommonTasks.getHttpHeaders(properties.getAuth());
- STOClient.setHttpHeader(httpHeader);
- LinkedHashMap<String, Object> output = STOClient.get(jsonRequest, new ParameterizedTypeReference<LinkedHashMap<String, Object>>() {});
- return sdnCommonTasks.validateSDNGetResponse(output);
- }
+ /**
+ *
+ * @param queryLink - takes in a link to topology that needs to be queried - creates a json request string and sends
+ * it to sdnc - receives and validates the linkedhashmap sent back from sdnc *
+ * @throws MapperException
+ * @throws BadResponseException
+ */
+ public String get(String queryLink) throws MapperException, BadResponseException {
+ String request = "";
+ String jsonRequest = sdnCommonTasks.buildJsonRequest(request);
+ String targetUrl = UriBuilder.fromUri(properties.getHost()).path(queryLink).build().toString();
+ BaseClient<String, LinkedHashMap<String, Object>> STOClient = new BaseClient<>();
+ STOClient.setTargetUrl(targetUrl);
+ HttpHeaders httpHeader = sdnCommonTasks.getHttpHeaders(properties.getAuth());
+ STOClient.setHttpHeader(httpHeader);
+ LinkedHashMap<String, Object> output =
+ STOClient.get(jsonRequest, new ParameterizedTypeReference<LinkedHashMap<String, Object>>() {});
+ return sdnCommonTasks.validateSDNGetResponse(output);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java
index 418e70a09e..e21f64accd 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java
@@ -25,7 +25,6 @@ package org.onap.so.client.sdnc;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
-
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.onap.so.client.exception.BadResponseException;
@@ -38,7 +37,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -52,7 +50,8 @@ public class SdnCommonTasks {
private static final String NO_RESPONSE_FROM_SDNC = "Error did not receive a response from SDNC.";
private static final String BAD_RESPONSE_FROM_SDNC = "Error received a bad response from SDNC.";
private static final String SDNC_CODE_NOT_0_OR_IN_200_299 = "Error from SDNC: %s";
- private static final String COULD_NOT_CONVERT_SDNC_POJO_TO_JSON = "ERROR: Could not convert SDNC pojo to json string.";
+ private static final String COULD_NOT_CONVERT_SDNC_POJO_TO_JSON =
+ "ERROR: Could not convert SDNC pojo to json string.";
/***
*
@@ -67,8 +66,7 @@ public class SdnCommonTasks {
try {
jsonRequest = objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(request);
} catch (JsonProcessingException e) {
- logger.error("{} {} {} {} {}", MessageEnum.JAXB_EXCEPTION.toString(),
- COULD_NOT_CONVERT_SDNC_POJO_TO_JSON,
+ logger.error("{} {} {} {} {}", MessageEnum.JAXB_EXCEPTION.toString(), COULD_NOT_CONVERT_SDNC_POJO_TO_JSON,
"BPMN", ErrorCode.DataError.getValue(), e.getMessage());
throw new MapperException(COULD_NOT_CONVERT_SDNC_POJO_TO_JSON);
}
@@ -98,41 +96,41 @@ public class SdnCommonTasks {
* @return
* @throws BadResponseException
*/
- public String validateSDNResponse(LinkedHashMap<String, Object> output) throws BadResponseException {
- if (CollectionUtils.isEmpty(output)) {
- logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), NO_RESPONSE_FROM_SDNC, "BPMN",
- ErrorCode.UnknownError.getValue(), NO_RESPONSE_FROM_SDNC);
- throw new BadResponseException(NO_RESPONSE_FROM_SDNC);
- }
- LinkedHashMap<String, Object> embeddedResponse =(LinkedHashMap<String, Object>) output.get("output");
+ public String validateSDNResponse(LinkedHashMap<String, Object> output) throws BadResponseException {
+ if (CollectionUtils.isEmpty(output)) {
+ logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), NO_RESPONSE_FROM_SDNC, "BPMN",
+ ErrorCode.UnknownError.getValue(), NO_RESPONSE_FROM_SDNC);
+ throw new BadResponseException(NO_RESPONSE_FROM_SDNC);
+ }
+ LinkedHashMap<String, Object> embeddedResponse = (LinkedHashMap<String, Object>) output.get("output");
String responseCode = "";
String responseMessage = "";
if (embeddedResponse != null) {
- responseCode = (String) embeddedResponse.get(RESPONSE_CODE);
+ responseCode = (String) embeddedResponse.get(RESPONSE_CODE);
responseMessage = (String) embeddedResponse.get(RESPONSE_MESSAGE);
}
ObjectMapper objMapper = new ObjectMapper();
String jsonResponse;
- try {
- jsonResponse = objMapper.writeValueAsString(output);
- logger.debug(jsonResponse);
- } catch (JsonProcessingException e) {
- logger.warn("Could not convert SDNC Response to String", e);
- jsonResponse = "";
- }
- logger.info("ResponseCode: {} ResponseMessage: {}", responseCode, responseMessage);
- int code = StringUtils.isNotEmpty(responseCode) ? Integer.parseInt(responseCode) : 0;
- if (isHttpCodeSuccess(code)) {
- logger.info("Successful Response from SDNC");
- return jsonResponse;
- } else {
- String errorMessage = String.format(SDNC_CODE_NOT_0_OR_IN_200_299, responseMessage);
- logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), errorMessage, "BPMN",
- ErrorCode.DataError.getValue(), errorMessage);
- throw new BadResponseException(errorMessage);
- }
- }
-
+ try {
+ jsonResponse = objMapper.writeValueAsString(output);
+ logger.debug(jsonResponse);
+ } catch (JsonProcessingException e) {
+ logger.warn("Could not convert SDNC Response to String", e);
+ jsonResponse = "";
+ }
+ logger.info("ResponseCode: {} ResponseMessage: {}", responseCode, responseMessage);
+ int code = StringUtils.isNotEmpty(responseCode) ? Integer.parseInt(responseCode) : 0;
+ if (isHttpCodeSuccess(code)) {
+ logger.info("Successful Response from SDNC");
+ return jsonResponse;
+ } else {
+ String errorMessage = String.format(SDNC_CODE_NOT_0_OR_IN_200_299, responseMessage);
+ logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), errorMessage, "BPMN",
+ ErrorCode.DataError.getValue(), errorMessage);
+ throw new BadResponseException(errorMessage);
+ }
+ }
+
/***
*
* @param output
@@ -149,18 +147,16 @@ public class SdnCommonTasks {
logger.debug("Using object mapper");
String stringOutput = "";
try {
- stringOutput = objMapper.writeValueAsString(output);
- }
- catch (Exception e) {
- logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), BAD_RESPONSE_FROM_SDNC,
- "BPMN", ErrorCode.UnknownError.getValue(),
- BAD_RESPONSE_FROM_SDNC);
+ stringOutput = objMapper.writeValueAsString(output);
+ } catch (Exception e) {
+ logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), BAD_RESPONSE_FROM_SDNC, "BPMN",
+ ErrorCode.UnknownError.getValue(), BAD_RESPONSE_FROM_SDNC);
throw new BadResponseException(BAD_RESPONSE_FROM_SDNC);
}
logger.debug("Received from GET request: {}", stringOutput);
return stringOutput;
}
-
+
private boolean isHttpCodeSuccess(int code) {
return code >= HttpStatus.SC_OK && code < HttpStatus.SC_MULTIPLE_CHOICES || code == 0;
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCProperties.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCProperties.java
index 08be73e3fd..15076fa45a 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCProperties.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCProperties.java
@@ -24,29 +24,34 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
-@ConfigurationProperties(prefix="sdnc")
+@ConfigurationProperties(prefix = "sdnc")
public class SDNCProperties {
- private String host;
- private String path;
- private String auth;
-
- public String getHost() {
- return host;
- }
- public void setHost(String host) {
- this.host = host;
- }
- public String getPath() {
- return path;
- }
- public void setPath(String path) {
- this.path = path;
- }
- public String getAuth() {
- return auth;
- }
- public void setAuth(String auth) {
- this.auth = auth;
- }
+ private String host;
+ private String path;
+ private String auth;
+
+ public String getHost() {
+ return host;
+ }
+
+ public void setHost(String host) {
+ this.host = host;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ public String getAuth() {
+ return auth;
+ }
+
+ public void setAuth(String auth) {
+ this.auth = auth;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java
index 3ee560f4f4..5910975051 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java
@@ -23,72 +23,76 @@ package org.onap.so.client.sdnc.beans;
import java.io.Serializable;
import java.time.Duration;
import java.util.UUID;
-
import org.onap.so.client.sdnc.endpoint.SDNCTopology;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
-public class SDNCRequest implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = 4679678988657593282L;
- private String timeOut = "PT1H";
- private SDNCTopology topology;
- private String CorrelationValue = UUID.randomUUID().toString();
- private String CorrelationName = "SDNCCallback";
- private Object SDNCPayload;
-
-
- public String getTimeOut() {
- return timeOut;
- }
-
- public void setTimeOut(String timeOut) {
- this.timeOut = timeOut;
- }
-
- public SDNCTopology getTopology() {
- return topology;
- }
-
- public void setTopology(SDNCTopology topology) {
- this.topology = topology;
- }
-
- public String getCorrelationValue() {
- return CorrelationValue;
- }
- public void setCorrelationValue(String correlationValue) {
- CorrelationValue = correlationValue;
- }
- public String getCorrelationName() {
- return CorrelationName;
- }
- public void setCorrelationName(String correlationName) {
- CorrelationName = correlationName;
- }
- public Object getSDNCPayload() {
- return SDNCPayload;
- }
- public void setSDNCPayload(Object sDNCPayload) {
- SDNCPayload = sDNCPayload;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof SDNCRequest)) {
- return false;
- }
- SDNCRequest castOther = (SDNCRequest) other;
- return new EqualsBuilder().append(CorrelationValue, castOther.CorrelationValue)
- .append(CorrelationName, castOther.CorrelationName).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(CorrelationValue).append(CorrelationName).toHashCode();
- }
+public class SDNCRequest implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 4679678988657593282L;
+ private String timeOut = "PT1H";
+ private SDNCTopology topology;
+ private String CorrelationValue = UUID.randomUUID().toString();
+ private String CorrelationName = "SDNCCallback";
+ private Object SDNCPayload;
+
+
+ public String getTimeOut() {
+ return timeOut;
+ }
+
+ public void setTimeOut(String timeOut) {
+ this.timeOut = timeOut;
+ }
+
+ public SDNCTopology getTopology() {
+ return topology;
+ }
+
+ public void setTopology(SDNCTopology topology) {
+ this.topology = topology;
+ }
+
+ public String getCorrelationValue() {
+ return CorrelationValue;
+ }
+
+ public void setCorrelationValue(String correlationValue) {
+ CorrelationValue = correlationValue;
+ }
+
+ public String getCorrelationName() {
+ return CorrelationName;
+ }
+
+ public void setCorrelationName(String correlationName) {
+ CorrelationName = correlationName;
+ }
+
+ public Object getSDNCPayload() {
+ return SDNCPayload;
+ }
+
+ public void setSDNCPayload(Object sDNCPayload) {
+ SDNCPayload = sDNCPayload;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof SDNCRequest)) {
+ return false;
+ }
+ SDNCRequest castOther = (SDNCRequest) other;
+ return new EqualsBuilder().append(CorrelationValue, castOther.CorrelationValue)
+ .append(CorrelationName, castOther.CorrelationName).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(CorrelationValue).append(CorrelationName).toHashCode();
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcAction.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcAction.java
index 876c7e002f..1718de9fe0 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcAction.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcAction.java
@@ -23,33 +23,38 @@ package org.onap.so.client.sdnc.beans;
import org.onap.sdnc.northbound.client.model.GenericResourceApiSvcActionEnumeration;
public enum SDNCSvcAction {
- ACTIVATE("activate",GenericResourceApiSvcActionEnumeration.ACTIVATE),
- DELETE("delete",GenericResourceApiSvcActionEnumeration.DELETE),
- ASSIGN("assign",GenericResourceApiSvcActionEnumeration.ASSIGN),
- ROLLBACK("rollback",GenericResourceApiSvcActionEnumeration.ROLLBACK),
- UNASSIGN("unassign",GenericResourceApiSvcActionEnumeration.UNASSIGN),
- DEACTIVATE("deactivate",GenericResourceApiSvcActionEnumeration.DEACTIVATE),
- CHANGE_DELETE("changedelete",GenericResourceApiSvcActionEnumeration.CHANGEDELETE),
- CHANGE_ASSIGN("changeassign",GenericResourceApiSvcActionEnumeration.CHANGEASSIGN),
- CREATE("create",GenericResourceApiSvcActionEnumeration.CREATE),
- ENABLE("enable",GenericResourceApiSvcActionEnumeration.ENABLE),
- DISABLE("disable",GenericResourceApiSvcActionEnumeration.DISABLE);
-
- private final String name;
-
- private GenericResourceApiSvcActionEnumeration sdncApiAction ;
-
- private SDNCSvcAction(String name , GenericResourceApiSvcActionEnumeration sdncApiAction) {
- this.name = name;
- this.sdncApiAction = sdncApiAction;
- }
-
- public GenericResourceApiSvcActionEnumeration getSdncApiAction(){
- return this.sdncApiAction;
- }
-
- @Override
- public String toString() {
- return name;
- }
+ ACTIVATE("activate", GenericResourceApiSvcActionEnumeration.ACTIVATE), DELETE("delete",
+ GenericResourceApiSvcActionEnumeration.DELETE), ASSIGN("assign",
+ GenericResourceApiSvcActionEnumeration.ASSIGN), ROLLBACK("rollback",
+ GenericResourceApiSvcActionEnumeration.ROLLBACK), UNASSIGN("unassign",
+ GenericResourceApiSvcActionEnumeration.UNASSIGN), DEACTIVATE("deactivate",
+ GenericResourceApiSvcActionEnumeration.DEACTIVATE), CHANGE_DELETE(
+ "changedelete",
+ GenericResourceApiSvcActionEnumeration.CHANGEDELETE), CHANGE_ASSIGN(
+ "changeassign",
+ GenericResourceApiSvcActionEnumeration.CHANGEASSIGN), CREATE(
+ "create",
+ GenericResourceApiSvcActionEnumeration.CREATE), ENABLE(
+ "enable",
+ GenericResourceApiSvcActionEnumeration.ENABLE), DISABLE(
+ "disable",
+ GenericResourceApiSvcActionEnumeration.DISABLE);
+
+ private final String name;
+
+ private GenericResourceApiSvcActionEnumeration sdncApiAction;
+
+ private SDNCSvcAction(String name, GenericResourceApiSvcActionEnumeration sdncApiAction) {
+ this.name = name;
+ this.sdncApiAction = sdncApiAction;
+ }
+
+ public GenericResourceApiSvcActionEnumeration getSdncApiAction() {
+ return this.sdncApiAction;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcOperation.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcOperation.java
index ba9fedccac..b9b04bc7b7 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcOperation.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcOperation.java
@@ -22,23 +22,23 @@ package org.onap.so.client.sdnc.beans;
public enum SDNCSvcOperation {
- VF_MODULE_TOPOLOGY_OPERATION("vf-module-topology-operation"),
- NETWORK_TOPOLOGY_OPERATION("network-topology-operation"),
- VNF_TOPOLOGY_OPERATION("vnf-topology-operation"),
- CONTRAIL_ROUTE_TOPOLOGY_OPERATION("contrail-route-topology-operation"),
- SECURITY_ZONE_TOPOLOGY_OPERATION("security-zone-topology-operation"),
- PORT_MIRROR_TOPOLOGY_OPERATION("port-mirror-topology-operation"),
- SERVICE_TOPOLOGY_OPERATION("service-topology-operation"),
- GENERIC_CONFIGURATION_TOPOLOGY_OPERATION("generic-configuration-topology-operation");
-
- private final String name;
-
- private SDNCSvcOperation(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return name;
- }
+ VF_MODULE_TOPOLOGY_OPERATION("vf-module-topology-operation"), NETWORK_TOPOLOGY_OPERATION(
+ "network-topology-operation"), VNF_TOPOLOGY_OPERATION(
+ "vnf-topology-operation"), CONTRAIL_ROUTE_TOPOLOGY_OPERATION(
+ "contrail-route-topology-operation"), SECURITY_ZONE_TOPOLOGY_OPERATION(
+ "security-zone-topology-operation"), PORT_MIRROR_TOPOLOGY_OPERATION(
+ "port-mirror-topology-operation"), SERVICE_TOPOLOGY_OPERATION(
+ "service-topology-operation"), GENERIC_CONFIGURATION_TOPOLOGY_OPERATION(
+ "generic-configuration-topology-operation");
+
+ private final String name;
+
+ private SDNCSvcOperation(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/endpoint/SDNCTopology.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/endpoint/SDNCTopology.java
index a709e80220..fb5f24694b 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/endpoint/SDNCTopology.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/endpoint/SDNCTopology.java
@@ -21,24 +21,21 @@
package org.onap.so.client.sdnc.endpoint;
public enum SDNCTopology {
-
- SERVICE("service-topology-operation"),
- VNF("vnf-topology-operation"),
- VFMODULE("vf-module-topology-operation"),
- CONTRAILROUTE("contrail-route-topology-operation"),
- PORTMIRROR("port-mirror-topology-operation"),
- NETWORK("network-topology-operation"),
- SECURITYZONE("security-zone-topology-operation"),
- CONFIGURATION("generic-configuration-topology-operation");
-
- private final String topology;
-
- private SDNCTopology(String topology) {
- this.topology = topology;
- }
-
- @Override
- public String toString(){
- return this.topology;
- }
+
+ SERVICE("service-topology-operation"), VNF("vnf-topology-operation"), VFMODULE(
+ "vf-module-topology-operation"), CONTRAILROUTE("contrail-route-topology-operation"), PORTMIRROR(
+ "port-mirror-topology-operation"), NETWORK("network-topology-operation"), SECURITYZONE(
+ "security-zone-topology-operation"), CONFIGURATION(
+ "generic-configuration-topology-operation");
+
+ private final String topology;
+
+ private SDNCTopology(String topology) {
+ this.topology = topology;
+ }
+
+ @Override
+ public String toString() {
+ return this.topology;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java
index 7b86756afa..6af8c2f9c5 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java
@@ -22,7 +22,6 @@ package org.onap.so.client.sdnc.mapper;
import java.net.URI;
import java.util.UUID;
-
import org.onap.sdnc.northbound.client.model.GenericResourceApiConfigurationinformationConfigurationInformation;
import org.onap.sdnc.northbound.client.model.GenericResourceApiGcTopologyOperationInformation;
import org.onap.sdnc.northbound.client.model.GenericResourceApiGcrequestinputGcRequestInput;
@@ -42,27 +41,29 @@ import org.springframework.stereotype.Component;
@Component(value = "sdncGCTopologyOperationRequestMapper")
public class GCTopologyOperationRequestMapper {
- @Autowired
+ @Autowired
private GeneralTopologyObjectMapper generalTopologyObjectMapper;
public GenericResourceApiGcTopologyOperationInformation assignOrActivateVnrReqMapper(SDNCSvcAction svcAction,
- GenericResourceApiRequestActionEnumeration reqAction,
- ServiceInstance serviceInstance,
- RequestContext requestContext,
- Customer customer,
- Configuration vnrConfiguration,
- GenericVnf voiceVnf, String sdncReqId,URI callbackUri) {
+ GenericResourceApiRequestActionEnumeration reqAction, ServiceInstance serviceInstance,
+ RequestContext requestContext, Customer customer, Configuration vnrConfiguration, GenericVnf voiceVnf,
+ String sdncReqId, URI callbackUri) {
- String msoRequestId = UUID.randomUUID().toString();
- if (requestContext != null && requestContext.getMsoRequestId() != null) {
- msoRequestId = requestContext.getMsoRequestId();
- }
+ String msoRequestId = UUID.randomUUID().toString();
+ if (requestContext != null && requestContext.getMsoRequestId() != null) {
+ msoRequestId = requestContext.getMsoRequestId();
+ }
GenericResourceApiGcTopologyOperationInformation req = new GenericResourceApiGcTopologyOperationInformation();
- GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId,callbackUri.toString());
- GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, reqAction);
- GenericResourceApiServiceinformationServiceInformation serviceInformation = generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, false);
- GenericResourceApiConfigurationinformationConfigurationInformation configurationInformation = generalTopologyObjectMapper.buildConfigurationInformation(vnrConfiguration,true);
- GenericResourceApiGcrequestinputGcRequestInput gcRequestInput = generalTopologyObjectMapper.buildGcRequestInformation(voiceVnf,null);
+ GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader =
+ generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId, callbackUri.toString());
+ GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper
+ .buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, reqAction);
+ GenericResourceApiServiceinformationServiceInformation serviceInformation =
+ generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, false);
+ GenericResourceApiConfigurationinformationConfigurationInformation configurationInformation =
+ generalTopologyObjectMapper.buildConfigurationInformation(vnrConfiguration, true);
+ GenericResourceApiGcrequestinputGcRequestInput gcRequestInput =
+ generalTopologyObjectMapper.buildGcRequestInformation(voiceVnf, null);
req.setRequestInformation(requestInformation);
req.setSdncRequestHeader(sdncRequestHeader);
req.setServiceInformation(serviceInformation);
@@ -75,21 +76,21 @@ public class GCTopologyOperationRequestMapper {
public GenericResourceApiGcTopologyOperationInformation deactivateOrUnassignVnrReqMapper(SDNCSvcAction svcAction,
- ServiceInstance serviceInstance,
- RequestContext requestContext,
- Configuration vnrConfiguration, String sdncReqId, URI callbackUri) {
+ ServiceInstance serviceInstance, RequestContext requestContext, Configuration vnrConfiguration,
+ String sdncReqId, URI callbackUri) {
- String msoRequestId = null;
- if (requestContext != null) {
- msoRequestId = requestContext.getMsoRequestId();
- }
- GenericResourceApiGcTopologyOperationInformation req = new GenericResourceApiGcTopologyOperationInformation();
+ String msoRequestId = null;
+ if (requestContext != null) {
+ msoRequestId = requestContext.getMsoRequestId();
+ }
+ GenericResourceApiGcTopologyOperationInformation req = new GenericResourceApiGcTopologyOperationInformation();
GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader =
- generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId,callbackUri.toString());
- GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper
- .buildGenericResourceApiRequestinformationRequestInformation(msoRequestId,
+ generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId, callbackUri.toString());
+ GenericResourceApiRequestinformationRequestInformation requestInformation =
+ generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(msoRequestId,
GenericResourceApiRequestActionEnumeration.DELETEGENERICCONFIGURATIONINSTANCE);
- GenericResourceApiServiceinformationServiceInformation serviceInformation = new GenericResourceApiServiceinformationServiceInformation();
+ GenericResourceApiServiceinformationServiceInformation serviceInformation =
+ new GenericResourceApiServiceinformationServiceInformation();
serviceInformation.setServiceInstanceId(serviceInstance.getServiceInstanceId());
GenericResourceApiConfigurationinformationConfigurationInformation configurationInformation =
new GenericResourceApiConfigurationinformationConfigurationInformation();
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java
index 756e5b068e..a9611cbde5 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java
@@ -23,7 +23,6 @@ package org.onap.so.client.sdnc.mapper;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import org.onap.sdnc.northbound.client.model.GenericResourceApiConfigurationinformationConfigurationInformation;
import org.onap.sdnc.northbound.client.model.GenericResourceApiGcrequestinputGcRequestInput;
import org.onap.sdnc.northbound.client.model.GenericResourceApiNetworkinformationNetworkInformation;
@@ -47,157 +46,183 @@ import org.onap.so.client.sdnc.beans.SDNCSvcAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class GeneralTopologyObjectMapper {
-
- private static final Logger logger = LoggerFactory.getLogger(GeneralTopologyObjectMapper.class);
- private ObjectMapper mapper = new ObjectMapper();
-
- /*
- * Build GenericResourceApiRequestinformationRequestInformation
- */
- public GenericResourceApiRequestinformationRequestInformation buildGenericResourceApiRequestinformationRequestInformation(String msoReqId, GenericResourceApiRequestActionEnumeration requestAction){
-
- GenericResourceApiRequestinformationRequestInformation requestInformation = new GenericResourceApiRequestinformationRequestInformation();
- requestInformation.setRequestId(msoReqId);
- requestInformation.setRequestAction(requestAction);
- requestInformation.setSource("MSO");
- return requestInformation;
- }
- /*
- * Build GenericResourceApiServiceinformationServiceInformation
- */
- public GenericResourceApiServiceinformationServiceInformation buildServiceInformation(ServiceInstance serviceInstance, RequestContext requestContext, Customer customer, boolean includeModelInformation){
- GenericResourceApiServiceinformationServiceInformation serviceInformation = new GenericResourceApiServiceinformationServiceInformation();
- serviceInformation.serviceId(serviceInstance.getServiceInstanceId());
- if (requestContext != null) {
- serviceInformation.setSubscriptionServiceType(requestContext.getProductFamilyId());
- }
- if (includeModelInformation) {
- GenericResourceApiOnapmodelinformationOnapModelInformation onapModelInformation = new GenericResourceApiOnapmodelinformationOnapModelInformation();
- onapModelInformation.setModelInvariantUuid(serviceInstance.getModelInfoServiceInstance().getModelInvariantUuid());
- onapModelInformation.setModelVersion(serviceInstance.getModelInfoServiceInstance().getModelVersion());
- onapModelInformation.setModelName(serviceInstance.getModelInfoServiceInstance().getModelName());
- onapModelInformation.setModelUuid(serviceInstance.getModelInfoServiceInstance().getModelUuid());
- serviceInformation.setOnapModelInformation(onapModelInformation );
- }
- serviceInformation.setServiceInstanceId(serviceInstance.getServiceInstanceId());
-
- if (customer != null) {
- serviceInformation.setGlobalCustomerId(customer.getGlobalCustomerId());
- if(customer.getServiceSubscription() != null){
- serviceInformation.setSubscriptionServiceType(customer.getServiceSubscription().getServiceType());
- }
-
- }
- return serviceInformation;
- }
- /*
- * Build GenericResourceApiNetworkinformationNetworkInformation
- */
- public GenericResourceApiNetworkinformationNetworkInformation buildNetworkInformation(L3Network network){
- GenericResourceApiNetworkinformationNetworkInformation networkInformation = new GenericResourceApiNetworkinformationNetworkInformation();
- GenericResourceApiOnapmodelinformationOnapModelInformation onapModelInformation = new GenericResourceApiOnapmodelinformationOnapModelInformation();
- if (network.getModelInfoNetwork() != null) {
- onapModelInformation.setModelInvariantUuid(network.getModelInfoNetwork().getModelInvariantUUID());
- onapModelInformation.setModelName(network.getModelInfoNetwork().getModelName());
- onapModelInformation.setModelVersion(network.getModelInfoNetwork().getModelVersion());
- onapModelInformation.setModelUuid(network.getModelInfoNetwork().getModelUUID());
- onapModelInformation.setModelCustomizationUuid(network.getModelInfoNetwork().getModelCustomizationUUID());
- networkInformation.setOnapModelInformation(onapModelInformation);
- }
-
- networkInformation.setFromPreload(null);
- networkInformation.setNetworkId(network.getNetworkId());
- networkInformation.setNetworkType(network.getNetworkType());
- networkInformation.setNetworkTechnology(network.getNetworkTechnology());
- return networkInformation;
- }
- /*
- * Build GenericResourceApiVnfinformationVnfInformation
- */
- public GenericResourceApiVnfinformationVnfInformation buildVnfInformation(GenericVnf vnf, ServiceInstance serviceInstance, boolean includeModelInformation){
- GenericResourceApiVnfinformationVnfInformation vnfInformation = new GenericResourceApiVnfinformationVnfInformation();
- if (includeModelInformation && vnf.getModelInfoGenericVnf() != null) {
- GenericResourceApiOnapmodelinformationOnapModelInformation onapModelInformation = new GenericResourceApiOnapmodelinformationOnapModelInformation();
- onapModelInformation.setModelInvariantUuid(vnf.getModelInfoGenericVnf().getModelInvariantUuid());
- onapModelInformation.setModelName(vnf.getModelInfoGenericVnf().getModelName());
- onapModelInformation.setModelVersion(vnf.getModelInfoGenericVnf().getModelVersion());
- onapModelInformation.setModelUuid(vnf.getModelInfoGenericVnf().getModelUuid());
- onapModelInformation.setModelCustomizationUuid(vnf.getModelInfoGenericVnf().getModelCustomizationUuid());
- vnfInformation.setOnapModelInformation(onapModelInformation);
- }
- vnfInformation.setVnfId(vnf.getVnfId());
- vnfInformation.setVnfType(vnf.getVnfType());
- vnfInformation.setVnfName(vnf.getVnfName());
- return vnfInformation;
- }
- /*
- * Build GenericResourceApiVfModuleinformationVfModuleInformation
- */
- public GenericResourceApiVfmoduleinformationVfModuleInformation buildVfModuleInformation(VfModule vfModule, GenericVnf vnf, ServiceInstance serviceInstance, RequestContext requestContext, boolean includeModelInformation) throws MapperException {
- GenericResourceApiVfmoduleinformationVfModuleInformation vfModuleInformation = new GenericResourceApiVfmoduleinformationVfModuleInformation();
- if (includeModelInformation) {
- if (vfModule.getModelInfoVfModule() == null) {
- throw new MapperException("VF Module model info is null for " + vfModule.getVfModuleId());
- }
- else {
- GenericResourceApiOnapmodelinformationOnapModelInformation onapModelInformation = new GenericResourceApiOnapmodelinformationOnapModelInformation();
- onapModelInformation.setModelInvariantUuid(vfModule.getModelInfoVfModule().getModelInvariantUUID());
- onapModelInformation.setModelName(vfModule.getModelInfoVfModule().getModelName());
- onapModelInformation.setModelVersion(vfModule.getModelInfoVfModule().getModelVersion());
- onapModelInformation.setModelUuid(vfModule.getModelInfoVfModule().getModelUUID());
- onapModelInformation.setModelCustomizationUuid(vfModule.getModelInfoVfModule().getModelCustomizationUUID());
- vfModuleInformation.setOnapModelInformation(onapModelInformation);
- }
- }
- if (vfModule.getModelInfoVfModule() != null) {
- vfModuleInformation.setVfModuleType(vfModule.getModelInfoVfModule().getModelName());
- }
- vfModuleInformation.setVfModuleId(vfModule.getVfModuleId());
- if (requestContext != null && requestContext.getRequestParameters() != null) {
- vfModuleInformation.setFromPreload(requestContext.getRequestParameters().getUsePreload());
- }
- else {
- vfModuleInformation.setFromPreload(true);
- }
-
- return vfModuleInformation;
- }
-
-
- public GenericResourceApiSdncrequestheaderSdncRequestHeader buildSdncRequestHeader(SDNCSvcAction svcAction, String sdncReqId){
- return buildSdncRequestHeader(svcAction, sdncReqId, null);
- }
-
- public GenericResourceApiSdncrequestheaderSdncRequestHeader buildSdncRequestHeader(SDNCSvcAction svcAction, String sdncReqId, String callbackUrl){
- GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = new GenericResourceApiSdncrequestheaderSdncRequestHeader();
- sdncRequestHeader.setSvcAction(svcAction.getSdncApiAction());
- sdncRequestHeader.setSvcRequestId(sdncReqId);
- sdncRequestHeader.setSvcNotificationUrl(callbackUrl);
- return sdncRequestHeader;
- }
+
+ private static final Logger logger = LoggerFactory.getLogger(GeneralTopologyObjectMapper.class);
+ private ObjectMapper mapper = new ObjectMapper();
+
+ /*
+ * Build GenericResourceApiRequestinformationRequestInformation
+ */
+ public GenericResourceApiRequestinformationRequestInformation buildGenericResourceApiRequestinformationRequestInformation(
+ String msoReqId, GenericResourceApiRequestActionEnumeration requestAction) {
+
+ GenericResourceApiRequestinformationRequestInformation requestInformation =
+ new GenericResourceApiRequestinformationRequestInformation();
+ requestInformation.setRequestId(msoReqId);
+ requestInformation.setRequestAction(requestAction);
+ requestInformation.setSource("MSO");
+ return requestInformation;
+ }
+
+ /*
+ * Build GenericResourceApiServiceinformationServiceInformation
+ */
+ public GenericResourceApiServiceinformationServiceInformation buildServiceInformation(
+ ServiceInstance serviceInstance, RequestContext requestContext, Customer customer,
+ boolean includeModelInformation) {
+ GenericResourceApiServiceinformationServiceInformation serviceInformation =
+ new GenericResourceApiServiceinformationServiceInformation();
+ serviceInformation.serviceId(serviceInstance.getServiceInstanceId());
+ if (requestContext != null) {
+ serviceInformation.setSubscriptionServiceType(requestContext.getProductFamilyId());
+ }
+ if (includeModelInformation) {
+ GenericResourceApiOnapmodelinformationOnapModelInformation onapModelInformation =
+ new GenericResourceApiOnapmodelinformationOnapModelInformation();
+ onapModelInformation
+ .setModelInvariantUuid(serviceInstance.getModelInfoServiceInstance().getModelInvariantUuid());
+ onapModelInformation.setModelVersion(serviceInstance.getModelInfoServiceInstance().getModelVersion());
+ onapModelInformation.setModelName(serviceInstance.getModelInfoServiceInstance().getModelName());
+ onapModelInformation.setModelUuid(serviceInstance.getModelInfoServiceInstance().getModelUuid());
+ serviceInformation.setOnapModelInformation(onapModelInformation);
+ }
+ serviceInformation.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+
+ if (customer != null) {
+ serviceInformation.setGlobalCustomerId(customer.getGlobalCustomerId());
+ if (customer.getServiceSubscription() != null) {
+ serviceInformation.setSubscriptionServiceType(customer.getServiceSubscription().getServiceType());
+ }
+
+ }
+ return serviceInformation;
+ }
+
+ /*
+ * Build GenericResourceApiNetworkinformationNetworkInformation
+ */
+ public GenericResourceApiNetworkinformationNetworkInformation buildNetworkInformation(L3Network network) {
+ GenericResourceApiNetworkinformationNetworkInformation networkInformation =
+ new GenericResourceApiNetworkinformationNetworkInformation();
+ GenericResourceApiOnapmodelinformationOnapModelInformation onapModelInformation =
+ new GenericResourceApiOnapmodelinformationOnapModelInformation();
+ if (network.getModelInfoNetwork() != null) {
+ onapModelInformation.setModelInvariantUuid(network.getModelInfoNetwork().getModelInvariantUUID());
+ onapModelInformation.setModelName(network.getModelInfoNetwork().getModelName());
+ onapModelInformation.setModelVersion(network.getModelInfoNetwork().getModelVersion());
+ onapModelInformation.setModelUuid(network.getModelInfoNetwork().getModelUUID());
+ onapModelInformation.setModelCustomizationUuid(network.getModelInfoNetwork().getModelCustomizationUUID());
+ networkInformation.setOnapModelInformation(onapModelInformation);
+ }
+
+ networkInformation.setFromPreload(null);
+ networkInformation.setNetworkId(network.getNetworkId());
+ networkInformation.setNetworkType(network.getNetworkType());
+ networkInformation.setNetworkTechnology(network.getNetworkTechnology());
+ return networkInformation;
+ }
+
+ /*
+ * Build GenericResourceApiVnfinformationVnfInformation
+ */
+ public GenericResourceApiVnfinformationVnfInformation buildVnfInformation(GenericVnf vnf,
+ ServiceInstance serviceInstance, boolean includeModelInformation) {
+ GenericResourceApiVnfinformationVnfInformation vnfInformation =
+ new GenericResourceApiVnfinformationVnfInformation();
+ if (includeModelInformation && vnf.getModelInfoGenericVnf() != null) {
+ GenericResourceApiOnapmodelinformationOnapModelInformation onapModelInformation =
+ new GenericResourceApiOnapmodelinformationOnapModelInformation();
+ onapModelInformation.setModelInvariantUuid(vnf.getModelInfoGenericVnf().getModelInvariantUuid());
+ onapModelInformation.setModelName(vnf.getModelInfoGenericVnf().getModelName());
+ onapModelInformation.setModelVersion(vnf.getModelInfoGenericVnf().getModelVersion());
+ onapModelInformation.setModelUuid(vnf.getModelInfoGenericVnf().getModelUuid());
+ onapModelInformation.setModelCustomizationUuid(vnf.getModelInfoGenericVnf().getModelCustomizationUuid());
+ vnfInformation.setOnapModelInformation(onapModelInformation);
+ }
+ vnfInformation.setVnfId(vnf.getVnfId());
+ vnfInformation.setVnfType(vnf.getVnfType());
+ vnfInformation.setVnfName(vnf.getVnfName());
+ return vnfInformation;
+ }
+
+ /*
+ * Build GenericResourceApiVfModuleinformationVfModuleInformation
+ */
+ public GenericResourceApiVfmoduleinformationVfModuleInformation buildVfModuleInformation(VfModule vfModule,
+ GenericVnf vnf, ServiceInstance serviceInstance, RequestContext requestContext,
+ boolean includeModelInformation) throws MapperException {
+ GenericResourceApiVfmoduleinformationVfModuleInformation vfModuleInformation =
+ new GenericResourceApiVfmoduleinformationVfModuleInformation();
+ if (includeModelInformation) {
+ if (vfModule.getModelInfoVfModule() == null) {
+ throw new MapperException("VF Module model info is null for " + vfModule.getVfModuleId());
+ } else {
+ GenericResourceApiOnapmodelinformationOnapModelInformation onapModelInformation =
+ new GenericResourceApiOnapmodelinformationOnapModelInformation();
+ onapModelInformation.setModelInvariantUuid(vfModule.getModelInfoVfModule().getModelInvariantUUID());
+ onapModelInformation.setModelName(vfModule.getModelInfoVfModule().getModelName());
+ onapModelInformation.setModelVersion(vfModule.getModelInfoVfModule().getModelVersion());
+ onapModelInformation.setModelUuid(vfModule.getModelInfoVfModule().getModelUUID());
+ onapModelInformation
+ .setModelCustomizationUuid(vfModule.getModelInfoVfModule().getModelCustomizationUUID());
+ vfModuleInformation.setOnapModelInformation(onapModelInformation);
+ }
+ }
+ if (vfModule.getModelInfoVfModule() != null) {
+ vfModuleInformation.setVfModuleType(vfModule.getModelInfoVfModule().getModelName());
+ }
+ vfModuleInformation.setVfModuleId(vfModule.getVfModuleId());
+ if (requestContext != null && requestContext.getRequestParameters() != null) {
+ vfModuleInformation.setFromPreload(requestContext.getRequestParameters().getUsePreload());
+ } else {
+ vfModuleInformation.setFromPreload(true);
+ }
+
+ return vfModuleInformation;
+ }
+
+
+ public GenericResourceApiSdncrequestheaderSdncRequestHeader buildSdncRequestHeader(SDNCSvcAction svcAction,
+ String sdncReqId) {
+ return buildSdncRequestHeader(svcAction, sdncReqId, null);
+ }
+
+ public GenericResourceApiSdncrequestheaderSdncRequestHeader buildSdncRequestHeader(SDNCSvcAction svcAction,
+ String sdncReqId, String callbackUrl) {
+ GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader =
+ new GenericResourceApiSdncrequestheaderSdncRequestHeader();
+ sdncRequestHeader.setSvcAction(svcAction.getSdncApiAction());
+ sdncRequestHeader.setSvcRequestId(sdncReqId);
+ sdncRequestHeader.setSvcNotificationUrl(callbackUrl);
+ return sdncRequestHeader;
+ }
/**
- * Build ConfigurationInformation
+ * Build ConfigurationInformation
+ *
* @param configuration
* @param includeModelInformation
* @return
*/
- public GenericResourceApiConfigurationinformationConfigurationInformation buildConfigurationInformation(Configuration configuration, boolean includeModelInformation) {
- GenericResourceApiConfigurationinformationConfigurationInformation configurationInformation = new GenericResourceApiConfigurationinformationConfigurationInformation();
+ public GenericResourceApiConfigurationinformationConfigurationInformation buildConfigurationInformation(
+ Configuration configuration, boolean includeModelInformation) {
+ GenericResourceApiConfigurationinformationConfigurationInformation configurationInformation =
+ new GenericResourceApiConfigurationinformationConfigurationInformation();
configurationInformation.setConfigurationId(configuration.getConfigurationId());
configurationInformation.setConfigurationName(configuration.getConfigurationName());
configurationInformation.setConfigurationType(configuration.getConfigurationType());
- if(includeModelInformation) {
- GenericResourceApiOnapmodelinformationOnapModelInformation onapModelInformation = new GenericResourceApiOnapmodelinformationOnapModelInformation();
+ if (includeModelInformation) {
+ GenericResourceApiOnapmodelinformationOnapModelInformation onapModelInformation =
+ new GenericResourceApiOnapmodelinformationOnapModelInformation();
onapModelInformation.setModelInvariantUuid(configuration.getModelInfoConfiguration().getModelInvariantId());
onapModelInformation.setModelUuid(configuration.getModelInfoConfiguration().getModelVersionId());
- onapModelInformation.setModelCustomizationUuid(configuration.getModelInfoConfiguration().getModelCustomizationId());
+ onapModelInformation
+ .setModelCustomizationUuid(configuration.getModelInfoConfiguration().getModelCustomizationId());
configurationInformation.setOnapModelInformation(onapModelInformation);
}
return configurationInformation;
@@ -205,35 +230,38 @@ public class GeneralTopologyObjectMapper {
/**
- * Build GcRequestInformation
+ * Build GcRequestInformation
+ *
* @param vnf
* @param genericResourceApiParam
* @return
*/
- public GenericResourceApiGcrequestinputGcRequestInput buildGcRequestInformation(GenericVnf vnf,GenericResourceApiParam genericResourceApiParam) {
- GenericResourceApiGcrequestinputGcRequestInput gcRequestInput = new GenericResourceApiGcrequestinputGcRequestInput();
+ public GenericResourceApiGcrequestinputGcRequestInput buildGcRequestInformation(GenericVnf vnf,
+ GenericResourceApiParam genericResourceApiParam) {
+ GenericResourceApiGcrequestinputGcRequestInput gcRequestInput =
+ new GenericResourceApiGcrequestinputGcRequestInput();
gcRequestInput.setVnfId(vnf.getVnfId());
- if(genericResourceApiParam != null) {
+ if (genericResourceApiParam != null) {
gcRequestInput.setInputParameters(genericResourceApiParam);
}
- return gcRequestInput;
- }
-
-
+ return gcRequestInput;
+ }
+
+
public String mapUserParamValue(Object value) {
- if (value == null) {
- return null;
- } else {
- if (value instanceof Map || value instanceof Set || value instanceof List) {
- try {
- return mapper.writeValueAsString(value);
- } catch (JsonProcessingException e) {
- logger.error("could not map value to string", e);
- throw new IllegalArgumentException(e);
- }
- } else {
- return value.toString();
- }
- }
+ if (value == null) {
+ return null;
+ } else {
+ if (value instanceof Map || value instanceof Set || value instanceof List) {
+ try {
+ return mapper.writeValueAsString(value);
+ } catch (JsonProcessingException e) {
+ logger.error("could not map value to string", e);
+ throw new IllegalArgumentException(e);
+ }
+ } else {
+ return value.toString();
+ }
+ }
}
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapper.java
index aef7e9e044..b1c95154c6 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapper.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapper.java
@@ -22,7 +22,6 @@ package org.onap.so.client.sdnc.mapper;
import java.util.Map;
import java.util.UUID;
-
import org.onap.sdnc.northbound.client.model.GenericResourceApiNetworkOperationInformation;
import org.onap.sdnc.northbound.client.model.GenericResourceApiNetworkinformationNetworkInformation;
import org.onap.sdnc.northbound.client.model.GenericResourceApiNetworkrequestinputNetworkRequestInput;
@@ -48,59 +47,68 @@ import org.springframework.stereotype.Component;
*/
@Component
public class NetworkTopologyOperationRequestMapper {
-
- @Autowired
- private GeneralTopologyObjectMapper generalTopologyObjectMapper;
- public GenericResourceApiNetworkOperationInformation reqMapper(SDNCSvcOperation svcOperation,
- SDNCSvcAction svcAction, GenericResourceApiRequestActionEnumeration reqAction, L3Network network, ServiceInstance serviceInstance,
- Customer customer, RequestContext requestContext, CloudRegion cloudRegion) {
- GenericResourceApiNetworkOperationInformation req = new GenericResourceApiNetworkOperationInformation();
- String sdncReqId = UUID.randomUUID().toString();
- String msoRequestId = UUID.randomUUID().toString();
- if (requestContext != null && requestContext.getMsoRequestId() != null) {
- msoRequestId = requestContext.getMsoRequestId();
- }
- GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId);
- GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, reqAction);
- GenericResourceApiServiceinformationServiceInformation serviceInformation = generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, true);
- GenericResourceApiNetworkinformationNetworkInformation networkInformation = generalTopologyObjectMapper.buildNetworkInformation(network);
- GenericResourceApiNetworkrequestinputNetworkRequestInput networkRequestInput = buildNetworkRequestInput(network, serviceInstance, cloudRegion);
+ @Autowired
+ private GeneralTopologyObjectMapper generalTopologyObjectMapper;
+
+ public GenericResourceApiNetworkOperationInformation reqMapper(SDNCSvcOperation svcOperation,
+ SDNCSvcAction svcAction, GenericResourceApiRequestActionEnumeration reqAction, L3Network network,
+ ServiceInstance serviceInstance, Customer customer, RequestContext requestContext,
+ CloudRegion cloudRegion) {
+ GenericResourceApiNetworkOperationInformation req = new GenericResourceApiNetworkOperationInformation();
+ String sdncReqId = UUID.randomUUID().toString();
+ String msoRequestId = UUID.randomUUID().toString();
+ if (requestContext != null && requestContext.getMsoRequestId() != null) {
+ msoRequestId = requestContext.getMsoRequestId();
+ }
+ GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader =
+ generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId);
+ GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper
+ .buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, reqAction);
+ GenericResourceApiServiceinformationServiceInformation serviceInformation =
+ generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, true);
+ GenericResourceApiNetworkinformationNetworkInformation networkInformation =
+ generalTopologyObjectMapper.buildNetworkInformation(network);
+ GenericResourceApiNetworkrequestinputNetworkRequestInput networkRequestInput =
+ buildNetworkRequestInput(network, serviceInstance, cloudRegion);
+
+ req.setRequestInformation(requestInformation);
+ req.setSdncRequestHeader(sdncRequestHeader);
+ req.setServiceInformation(serviceInformation);
+ req.setNetworkInformation(networkInformation);
- req.setRequestInformation(requestInformation);
- req.setSdncRequestHeader(sdncRequestHeader);
- req.setServiceInformation(serviceInformation);
- req.setNetworkInformation(networkInformation);
+ if (requestContext != null && requestContext.getUserParams() != null) {
+ for (Map.Entry<String, Object> entry : requestContext.getUserParams().entrySet()) {
+ GenericResourceApiParam networkInputParameters = new GenericResourceApiParam();
+ GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
+ paramItem.setName(entry.getKey());
+ paramItem.setValue(generalTopologyObjectMapper.mapUserParamValue(entry.getValue()));
+ networkInputParameters.addParamItem(paramItem);
+ networkRequestInput.setNetworkInputParameters(networkInputParameters);
+ }
+ }
- if (requestContext != null && requestContext.getUserParams() != null) {
- for (Map.Entry<String, Object> entry : requestContext.getUserParams().entrySet()) {
- GenericResourceApiParam networkInputParameters = new GenericResourceApiParam();
- GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
- paramItem.setName(entry.getKey());
- paramItem.setValue(generalTopologyObjectMapper.mapUserParamValue(entry.getValue()));
- networkInputParameters.addParamItem(paramItem);
- networkRequestInput.setNetworkInputParameters(networkInputParameters);
- }
- }
+ req.setNetworkRequestInput(networkRequestInput);
+ return req;
+ }
- req.setNetworkRequestInput(networkRequestInput);
- return req;
- }
- /*
- * Private helper to build GenericResourceApiNetworkrequestinputNetworkRequestInput
- */
- private GenericResourceApiNetworkrequestinputNetworkRequestInput buildNetworkRequestInput(L3Network network, ServiceInstance serviceInstance, CloudRegion cloudRegion){
- GenericResourceApiNetworkrequestinputNetworkRequestInput networkRequestInput = new GenericResourceApiNetworkrequestinputNetworkRequestInput();
- networkRequestInput.setTenant(cloudRegion.getTenantId());
- networkRequestInput.setCloudOwner(cloudRegion.getCloudOwner());
- networkRequestInput.setAicCloudRegion(cloudRegion.getLcpCloudRegionId());
- if (network.getNetworkName() != null && !network.getNetworkName().equals("")) {
- networkRequestInput.setNetworkName(network.getNetworkName());
- }
- if (serviceInstance.getCollection() != null && serviceInstance.getCollection().getInstanceGroup() != null){
- //set only for network created as part of the collection/instance since 1806
- networkRequestInput.setNetworkInstanceGroupId(serviceInstance.getCollection().getInstanceGroup().getId());
- }
- return networkRequestInput;
- }
+ /*
+ * Private helper to build GenericResourceApiNetworkrequestinputNetworkRequestInput
+ */
+ private GenericResourceApiNetworkrequestinputNetworkRequestInput buildNetworkRequestInput(L3Network network,
+ ServiceInstance serviceInstance, CloudRegion cloudRegion) {
+ GenericResourceApiNetworkrequestinputNetworkRequestInput networkRequestInput =
+ new GenericResourceApiNetworkrequestinputNetworkRequestInput();
+ networkRequestInput.setTenant(cloudRegion.getTenantId());
+ networkRequestInput.setCloudOwner(cloudRegion.getCloudOwner());
+ networkRequestInput.setAicCloudRegion(cloudRegion.getLcpCloudRegionId());
+ if (network.getNetworkName() != null && !network.getNetworkName().equals("")) {
+ networkRequestInput.setNetworkName(network.getNetworkName());
+ }
+ if (serviceInstance.getCollection() != null && serviceInstance.getCollection().getInstanceGroup() != null) {
+ // set only for network created as part of the collection/instance since 1806
+ networkRequestInput.setNetworkInstanceGroupId(serviceInstance.getCollection().getInstanceGroup().getId());
+ }
+ return networkRequestInput;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapper.java
index cdb4ab96aa..b5957b3009 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapper.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapper.java
@@ -22,7 +22,6 @@ package org.onap.so.client.sdnc.mapper;
import java.util.Map;
import java.util.UUID;
-
import org.onap.sdnc.northbound.client.model.GenericResourceApiParam;
import org.onap.sdnc.northbound.client.model.GenericResourceApiParamParam;
import org.onap.sdnc.northbound.client.model.GenericResourceApiRequestActionEnumeration;
@@ -40,45 +39,51 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
-public class ServiceTopologyOperationMapper{
+public class ServiceTopologyOperationMapper {
+
+ @Autowired
+ public GeneralTopologyObjectMapper generalTopologyObjectMapper;
+
+ public GenericResourceApiServiceOperationInformation reqMapper(SDNCSvcOperation svcOperation,
+ SDNCSvcAction svcAction, GenericResourceApiRequestActionEnumeration resourceAction,
+ ServiceInstance serviceInstance, Customer customer, RequestContext requestContext) {
+
+ String sdncReqId = UUID.randomUUID().toString();
+ String msoRequestId = UUID.randomUUID().toString();
+ if (requestContext != null && requestContext.getMsoRequestId() != null) {
+ msoRequestId = requestContext.getMsoRequestId();
+ }
+ GenericResourceApiServiceOperationInformation servOpInput = new GenericResourceApiServiceOperationInformation();
+ GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader =
+ generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId);
+ GenericResourceApiRequestinformationRequestInformation reqInfo = generalTopologyObjectMapper
+ .buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, resourceAction);
+ GenericResourceApiServiceinformationServiceInformation servInfo =
+ generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, true);
+ GenericResourceApiServicerequestinputServiceRequestInput servReqInfo =
+ new GenericResourceApiServicerequestinputServiceRequestInput();
+
+ servReqInfo.setServiceInstanceName(serviceInstance.getServiceInstanceName());
- @Autowired
- public GeneralTopologyObjectMapper generalTopologyObjectMapper;
-
- public GenericResourceApiServiceOperationInformation reqMapper (SDNCSvcOperation svcOperation,
- SDNCSvcAction svcAction, GenericResourceApiRequestActionEnumeration resourceAction,ServiceInstance serviceInstance, Customer customer, RequestContext requestContext) {
+ servOpInput.setSdncRequestHeader(sdncRequestHeader);
+ servOpInput.setRequestInformation(reqInfo);
+ servOpInput.setServiceInformation(servInfo);
+ servOpInput.setServiceRequestInput(servReqInfo);
- String sdncReqId = UUID.randomUUID().toString();
- String msoRequestId = UUID.randomUUID().toString();
- if (requestContext != null && requestContext.getMsoRequestId() != null) {
- msoRequestId = requestContext.getMsoRequestId();
- }
- GenericResourceApiServiceOperationInformation servOpInput = new GenericResourceApiServiceOperationInformation();
- GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId);
- GenericResourceApiRequestinformationRequestInformation reqInfo = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, resourceAction);
- GenericResourceApiServiceinformationServiceInformation servInfo = generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, true);
- GenericResourceApiServicerequestinputServiceRequestInput servReqInfo = new GenericResourceApiServicerequestinputServiceRequestInput();
-
- servReqInfo.setServiceInstanceName(serviceInstance.getServiceInstanceName());
-
- servOpInput.setSdncRequestHeader(sdncRequestHeader);
- servOpInput.setRequestInformation(reqInfo);
- servOpInput.setServiceInformation(servInfo);
- servOpInput.setServiceRequestInput(servReqInfo);
-
- if(requestContext != null && requestContext.getUserParams()!=null){
- for (Map.Entry<String, Object> entry : requestContext.getUserParams().entrySet()) {
- GenericResourceApiServicerequestinputServiceRequestInput serviceRequestInput = new GenericResourceApiServicerequestinputServiceRequestInput();
- serviceRequestInput.setServiceInstanceName(serviceInstance.getServiceInstanceName());
- GenericResourceApiParam serviceInputParameters = new GenericResourceApiParam();
- GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
- paramItem.setName(entry.getKey());
- paramItem.setValue(generalTopologyObjectMapper.mapUserParamValue(entry.getValue()));
- serviceInputParameters.addParamItem(paramItem );
- serviceRequestInput.serviceInputParameters(serviceInputParameters);
- servOpInput.setServiceRequestInput(serviceRequestInput );
- }
- }
- return servOpInput;
- }
+ if (requestContext != null && requestContext.getUserParams() != null) {
+ for (Map.Entry<String, Object> entry : requestContext.getUserParams().entrySet()) {
+ GenericResourceApiServicerequestinputServiceRequestInput serviceRequestInput =
+ new GenericResourceApiServicerequestinputServiceRequestInput();
+ serviceRequestInput.setServiceInstanceName(serviceInstance.getServiceInstanceName());
+ GenericResourceApiParam serviceInputParameters = new GenericResourceApiParam();
+ GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
+ paramItem.setName(entry.getKey());
+ paramItem.setValue(generalTopologyObjectMapper.mapUserParamValue(entry.getValue()));
+ serviceInputParameters.addParamItem(paramItem);
+ serviceRequestInput.serviceInputParameters(serviceInputParameters);
+ servOpInput.setServiceRequestInput(serviceRequestInput);
+ }
+ }
+ return servOpInput;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java
index 86c718d165..6627625d62 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java
@@ -24,7 +24,6 @@ package org.onap.so.client.sdnc.mapper;
import java.util.Map;
import java.util.UUID;
-
import org.onap.sdnc.northbound.client.model.GenericResourceApiParam;
import org.onap.sdnc.northbound.client.model.GenericResourceApiParamParam;
import org.onap.sdnc.northbound.client.model.GenericResourceApiRequestActionEnumeration;
@@ -53,134 +52,146 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class VfModuleTopologyOperationRequestMapper {
- private static final Logger logger = LoggerFactory.getLogger(VfModuleTopologyOperationRequestMapper.class);
-
- @Autowired
- private GeneralTopologyObjectMapper generalTopologyObjectMapper;
-
- public GenericResourceApiVfModuleOperationInformation reqMapper(SDNCSvcOperation svcOperation,
- SDNCSvcAction svcAction, VfModule vfModule, VolumeGroup volumeGroup, GenericVnf vnf, ServiceInstance serviceInstance,
- Customer customer, CloudRegion cloudRegion, RequestContext requestContext, String sdncAssignResponse) throws MapperException {
- GenericResourceApiVfModuleOperationInformation req = new GenericResourceApiVfModuleOperationInformation();
-
- boolean includeModelInformation = false;
-
- GenericResourceApiRequestActionEnumeration requestAction = GenericResourceApiRequestActionEnumeration.CREATEVFMODULEINSTANCE;
- GenericResourceApiSvcActionEnumeration genericResourceApiSvcAction = GenericResourceApiSvcActionEnumeration.ASSIGN;
-
- if (svcAction.equals(SDNCSvcAction.ACTIVATE)) {
- genericResourceApiSvcAction = GenericResourceApiSvcActionEnumeration.ACTIVATE;
- requestAction = GenericResourceApiRequestActionEnumeration.CREATEVFMODULEINSTANCE;
- includeModelInformation = true;
- } else if (svcAction.equals(SDNCSvcAction.ASSIGN)) {
- genericResourceApiSvcAction = GenericResourceApiSvcActionEnumeration.ASSIGN;
- requestAction = GenericResourceApiRequestActionEnumeration.CREATEVFMODULEINSTANCE;
- includeModelInformation = true;
- } else if (svcAction.equals(SDNCSvcAction.DEACTIVATE)) {
- genericResourceApiSvcAction = GenericResourceApiSvcActionEnumeration.DEACTIVATE;
- requestAction = GenericResourceApiRequestActionEnumeration.DELETEVFMODULEINSTANCE;
- includeModelInformation = false;
- } else if (svcAction.equals(SDNCSvcAction.DELETE)) {
- genericResourceApiSvcAction = GenericResourceApiSvcActionEnumeration.DELETE;
- requestAction = GenericResourceApiRequestActionEnumeration.DELETEVFMODULEINSTANCE;
- includeModelInformation = false;
- } else if (svcAction.equals(SDNCSvcAction.UNASSIGN)) {
- genericResourceApiSvcAction = GenericResourceApiSvcActionEnumeration.UNASSIGN;
- requestAction = GenericResourceApiRequestActionEnumeration.DELETEVFMODULEINSTANCE;
- includeModelInformation = false;
- }
-
- String sdncReqId = UUID.randomUUID().toString();
- String msoRequestId = UUID.randomUUID().toString();
- if (requestContext != null && requestContext.getMsoRequestId() != null) {
- msoRequestId = requestContext.getMsoRequestId();
- }
-
- GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(msoRequestId,
- requestAction);
- GenericResourceApiServiceinformationServiceInformation serviceInformation = generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, includeModelInformation);
- GenericResourceApiVnfinformationVnfInformation vnfInformation = generalTopologyObjectMapper.buildVnfInformation(vnf, serviceInstance, includeModelInformation);
- GenericResourceApiVfmoduleinformationVfModuleInformation vfModuleInformation = generalTopologyObjectMapper.buildVfModuleInformation(vfModule, vnf, serviceInstance, requestContext, includeModelInformation);
- GenericResourceApiVfmodulerequestinputVfModuleRequestInput vfModuleRequestInput = buildVfModuleRequestInput(vfModule, volumeGroup, cloudRegion, requestContext);
- GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = buildVfModuleSdncRequestHeader(sdncReqId, genericResourceApiSvcAction);
-
- req.setRequestInformation(requestInformation);
- req.setSdncRequestHeader(sdncRequestHeader);
- req.setServiceInformation(serviceInformation);
- req.setVnfInformation(vnfInformation);
- req.setVfModuleInformation(vfModuleInformation);
- req.setVfModuleRequestInput(vfModuleRequestInput);
-
- return req;
- }
-
- private GenericResourceApiVfmodulerequestinputVfModuleRequestInput buildVfModuleRequestInput(VfModule vfModule, VolumeGroup volumeGroup, CloudRegion cloudRegion, RequestContext requestContext) {
- GenericResourceApiVfmodulerequestinputVfModuleRequestInput vfModuleRequestInput = new GenericResourceApiVfmodulerequestinputVfModuleRequestInput();
- if (cloudRegion != null) {
- vfModuleRequestInput.setTenant(cloudRegion.getTenantId());
- vfModuleRequestInput.setAicCloudRegion(cloudRegion.getLcpCloudRegionId());
- vfModuleRequestInput.setCloudOwner(cloudRegion.getCloudOwner());
- }
- if (vfModule.getVfModuleName() != null && !vfModule.getVfModuleName().equals("")) {
- vfModuleRequestInput.setVfModuleName(vfModule.getVfModuleName());
- }
- GenericResourceApiParam vfModuleInputParameters = new GenericResourceApiParam();
-
- if (requestContext != null && requestContext.getUserParams() != null) {
- for (Map.Entry<String, Object> entry : requestContext.getUserParams().entrySet()) {
- GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
- paramItem.setName(entry.getKey());
- paramItem.setValue(generalTopologyObjectMapper.mapUserParamValue(entry.getValue()));
- vfModuleInputParameters.addParamItem(paramItem);
- }
- }
-
- if (vfModule.getCloudParams() != null) {
- for (Map.Entry<String, String> entry : vfModule.getCloudParams().entrySet()) {
- GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
- paramItem.setName(entry.getKey());
- paramItem.setValue(entry.getValue());
- vfModuleInputParameters.addParamItem(paramItem);
- }
- }
-
- if (volumeGroup != null) {
- GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
- paramItem.setName("volume-group-id");
- paramItem.setValue(volumeGroup.getVolumeGroupId());
- vfModuleInputParameters.addParamItem(paramItem);
- }
- vfModuleRequestInput.setVfModuleInputParameters(vfModuleInputParameters);
-
- return vfModuleRequestInput;
- }
-
- private GenericResourceApiSdncrequestheaderSdncRequestHeader buildVfModuleSdncRequestHeader(String sdncReqId, GenericResourceApiSvcActionEnumeration svcAction) {
- GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = new GenericResourceApiSdncrequestheaderSdncRequestHeader();
-
- sdncRequestHeader.setSvcRequestId(sdncReqId);
- sdncRequestHeader.setSvcAction(svcAction);
-
- return sdncRequestHeader;
- }
-
- public String buildObjectPath(String sdncAssignResponse) {
- String objectPath = null;
- if (sdncAssignResponse != null) {
- ObjectMapper mapper = new ObjectMapper();
- try {
- GenericResourceApiVfModuleResponseInformation assignResponseInfo = mapper.readValue(sdncAssignResponse, GenericResourceApiVfModuleResponseInformation.class);
- objectPath = assignResponseInfo.getVfModuleResponseInformation().getObjectPath();
- } catch (Exception e) {
- logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), e.getMessage(), "BPMN",
- ErrorCode.UnknownError.getValue(), e.getMessage());
- }
- }
- return objectPath;
- }
+ private static final Logger logger = LoggerFactory.getLogger(VfModuleTopologyOperationRequestMapper.class);
+
+ @Autowired
+ private GeneralTopologyObjectMapper generalTopologyObjectMapper;
+
+ public GenericResourceApiVfModuleOperationInformation reqMapper(SDNCSvcOperation svcOperation,
+ SDNCSvcAction svcAction, VfModule vfModule, VolumeGroup volumeGroup, GenericVnf vnf,
+ ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext,
+ String sdncAssignResponse) throws MapperException {
+ GenericResourceApiVfModuleOperationInformation req = new GenericResourceApiVfModuleOperationInformation();
+
+ boolean includeModelInformation = false;
+
+ GenericResourceApiRequestActionEnumeration requestAction =
+ GenericResourceApiRequestActionEnumeration.CREATEVFMODULEINSTANCE;
+ GenericResourceApiSvcActionEnumeration genericResourceApiSvcAction =
+ GenericResourceApiSvcActionEnumeration.ASSIGN;
+
+ if (svcAction.equals(SDNCSvcAction.ACTIVATE)) {
+ genericResourceApiSvcAction = GenericResourceApiSvcActionEnumeration.ACTIVATE;
+ requestAction = GenericResourceApiRequestActionEnumeration.CREATEVFMODULEINSTANCE;
+ includeModelInformation = true;
+ } else if (svcAction.equals(SDNCSvcAction.ASSIGN)) {
+ genericResourceApiSvcAction = GenericResourceApiSvcActionEnumeration.ASSIGN;
+ requestAction = GenericResourceApiRequestActionEnumeration.CREATEVFMODULEINSTANCE;
+ includeModelInformation = true;
+ } else if (svcAction.equals(SDNCSvcAction.DEACTIVATE)) {
+ genericResourceApiSvcAction = GenericResourceApiSvcActionEnumeration.DEACTIVATE;
+ requestAction = GenericResourceApiRequestActionEnumeration.DELETEVFMODULEINSTANCE;
+ includeModelInformation = false;
+ } else if (svcAction.equals(SDNCSvcAction.DELETE)) {
+ genericResourceApiSvcAction = GenericResourceApiSvcActionEnumeration.DELETE;
+ requestAction = GenericResourceApiRequestActionEnumeration.DELETEVFMODULEINSTANCE;
+ includeModelInformation = false;
+ } else if (svcAction.equals(SDNCSvcAction.UNASSIGN)) {
+ genericResourceApiSvcAction = GenericResourceApiSvcActionEnumeration.UNASSIGN;
+ requestAction = GenericResourceApiRequestActionEnumeration.DELETEVFMODULEINSTANCE;
+ includeModelInformation = false;
+ }
+
+ String sdncReqId = UUID.randomUUID().toString();
+ String msoRequestId = UUID.randomUUID().toString();
+ if (requestContext != null && requestContext.getMsoRequestId() != null) {
+ msoRequestId = requestContext.getMsoRequestId();
+ }
+
+ GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper
+ .buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, requestAction);
+ GenericResourceApiServiceinformationServiceInformation serviceInformation = generalTopologyObjectMapper
+ .buildServiceInformation(serviceInstance, requestContext, customer, includeModelInformation);
+ GenericResourceApiVnfinformationVnfInformation vnfInformation =
+ generalTopologyObjectMapper.buildVnfInformation(vnf, serviceInstance, includeModelInformation);
+ GenericResourceApiVfmoduleinformationVfModuleInformation vfModuleInformation = generalTopologyObjectMapper
+ .buildVfModuleInformation(vfModule, vnf, serviceInstance, requestContext, includeModelInformation);
+ GenericResourceApiVfmodulerequestinputVfModuleRequestInput vfModuleRequestInput =
+ buildVfModuleRequestInput(vfModule, volumeGroup, cloudRegion, requestContext);
+ GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader =
+ buildVfModuleSdncRequestHeader(sdncReqId, genericResourceApiSvcAction);
+
+ req.setRequestInformation(requestInformation);
+ req.setSdncRequestHeader(sdncRequestHeader);
+ req.setServiceInformation(serviceInformation);
+ req.setVnfInformation(vnfInformation);
+ req.setVfModuleInformation(vfModuleInformation);
+ req.setVfModuleRequestInput(vfModuleRequestInput);
+
+ return req;
+ }
+
+ private GenericResourceApiVfmodulerequestinputVfModuleRequestInput buildVfModuleRequestInput(VfModule vfModule,
+ VolumeGroup volumeGroup, CloudRegion cloudRegion, RequestContext requestContext) {
+ GenericResourceApiVfmodulerequestinputVfModuleRequestInput vfModuleRequestInput =
+ new GenericResourceApiVfmodulerequestinputVfModuleRequestInput();
+ if (cloudRegion != null) {
+ vfModuleRequestInput.setTenant(cloudRegion.getTenantId());
+ vfModuleRequestInput.setAicCloudRegion(cloudRegion.getLcpCloudRegionId());
+ vfModuleRequestInput.setCloudOwner(cloudRegion.getCloudOwner());
+ }
+ if (vfModule.getVfModuleName() != null && !vfModule.getVfModuleName().equals("")) {
+ vfModuleRequestInput.setVfModuleName(vfModule.getVfModuleName());
+ }
+ GenericResourceApiParam vfModuleInputParameters = new GenericResourceApiParam();
+
+ if (requestContext != null && requestContext.getUserParams() != null) {
+ for (Map.Entry<String, Object> entry : requestContext.getUserParams().entrySet()) {
+ GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
+ paramItem.setName(entry.getKey());
+ paramItem.setValue(generalTopologyObjectMapper.mapUserParamValue(entry.getValue()));
+ vfModuleInputParameters.addParamItem(paramItem);
+ }
+ }
+
+ if (vfModule.getCloudParams() != null) {
+ for (Map.Entry<String, String> entry : vfModule.getCloudParams().entrySet()) {
+ GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
+ paramItem.setName(entry.getKey());
+ paramItem.setValue(entry.getValue());
+ vfModuleInputParameters.addParamItem(paramItem);
+ }
+ }
+
+ if (volumeGroup != null) {
+ GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
+ paramItem.setName("volume-group-id");
+ paramItem.setValue(volumeGroup.getVolumeGroupId());
+ vfModuleInputParameters.addParamItem(paramItem);
+ }
+ vfModuleRequestInput.setVfModuleInputParameters(vfModuleInputParameters);
+
+ return vfModuleRequestInput;
+ }
+
+ private GenericResourceApiSdncrequestheaderSdncRequestHeader buildVfModuleSdncRequestHeader(String sdncReqId,
+ GenericResourceApiSvcActionEnumeration svcAction) {
+ GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader =
+ new GenericResourceApiSdncrequestheaderSdncRequestHeader();
+
+ sdncRequestHeader.setSvcRequestId(sdncReqId);
+ sdncRequestHeader.setSvcAction(svcAction);
+
+ return sdncRequestHeader;
+ }
+
+ public String buildObjectPath(String sdncAssignResponse) {
+ String objectPath = null;
+ if (sdncAssignResponse != null) {
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ GenericResourceApiVfModuleResponseInformation assignResponseInfo =
+ mapper.readValue(sdncAssignResponse, GenericResourceApiVfModuleResponseInformation.class);
+ objectPath = assignResponseInfo.getVfModuleResponseInformation().getObjectPath();
+ } catch (Exception e) {
+ logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), e.getMessage(), "BPMN",
+ ErrorCode.UnknownError.getValue(), e.getMessage());
+ }
+ }
+ return objectPath;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapper.java
index 85e5b85529..f31bff988a 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapper.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapper.java
@@ -24,7 +24,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import org.apache.commons.lang.StringUtils;
import org.onap.sdnc.northbound.client.model.GenericResourceApiParam;
import org.onap.sdnc.northbound.client.model.GenericResourceApiParamParam;
@@ -52,93 +51,96 @@ import org.springframework.stereotype.Component;
@Component
public class VnfTopologyOperationRequestMapper {
- @Autowired
- private GeneralTopologyObjectMapper generalTopologyObjectMapper;
+ @Autowired
+ private GeneralTopologyObjectMapper generalTopologyObjectMapper;
+
+ public GenericResourceApiVnfOperationInformation reqMapper(SDNCSvcOperation svcOperation, SDNCSvcAction svcAction,
+ GenericResourceApiRequestActionEnumeration requestAction, GenericVnf vnf, ServiceInstance serviceInstance,
+ Customer customer, CloudRegion cloudRegion, RequestContext requestContext, boolean homing) {
+ String sdncReqId = UUID.randomUUID().toString();
+ String msoRequestId = UUID.randomUUID().toString();
+ if (requestContext != null && requestContext.getMsoRequestId() != null) {
+ msoRequestId = requestContext.getMsoRequestId();
+ }
+ GenericResourceApiVnfOperationInformation req = new GenericResourceApiVnfOperationInformation();
+ GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader =
+ generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId);
+ GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper
+ .buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, requestAction);
+ GenericResourceApiServiceinformationServiceInformation serviceInformation =
+ generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, true);
+ GenericResourceApiVnfinformationVnfInformation vnfInformation =
+ generalTopologyObjectMapper.buildVnfInformation(vnf, serviceInstance, true);
+ GenericResourceApiVnfrequestinputVnfRequestInput vnfRequestInput =
+ new GenericResourceApiVnfrequestinputVnfRequestInput();
- public GenericResourceApiVnfOperationInformation reqMapper(SDNCSvcOperation svcOperation, SDNCSvcAction svcAction,
- GenericResourceApiRequestActionEnumeration requestAction, GenericVnf vnf, ServiceInstance serviceInstance,
- Customer customer, CloudRegion cloudRegion, RequestContext requestContext, boolean homing) {
- String sdncReqId = UUID.randomUUID().toString();
- String msoRequestId = UUID.randomUUID().toString();
- if (requestContext != null && requestContext.getMsoRequestId() != null) {
- msoRequestId = requestContext.getMsoRequestId();
- }
- GenericResourceApiVnfOperationInformation req = new GenericResourceApiVnfOperationInformation();
- GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = generalTopologyObjectMapper
- .buildSdncRequestHeader(svcAction, sdncReqId);
- GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper
- .buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, requestAction);
- GenericResourceApiServiceinformationServiceInformation serviceInformation = generalTopologyObjectMapper
- .buildServiceInformation(serviceInstance, requestContext, customer, true);
- GenericResourceApiVnfinformationVnfInformation vnfInformation = generalTopologyObjectMapper
- .buildVnfInformation(vnf, serviceInstance, true);
- GenericResourceApiVnfrequestinputVnfRequestInput vnfRequestInput = new GenericResourceApiVnfrequestinputVnfRequestInput();
+ vnfRequestInput.setTenant(cloudRegion.getTenantId());
+ vnfRequestInput.setAicCloudRegion(cloudRegion.getLcpCloudRegionId());
+ vnfRequestInput.setCloudOwner(cloudRegion.getCloudOwner());
- vnfRequestInput.setTenant(cloudRegion.getTenantId());
- vnfRequestInput.setAicCloudRegion(cloudRegion.getLcpCloudRegionId());
- vnfRequestInput.setCloudOwner(cloudRegion.getCloudOwner());
-
- if (StringUtils.isNotBlank(vnf.getVnfName())) {
- vnfRequestInput.setVnfName(vnf.getVnfName());
- }
+ if (StringUtils.isNotBlank(vnf.getVnfName())) {
+ vnfRequestInput.setVnfName(vnf.getVnfName());
+ }
- req.setRequestInformation(requestInformation);
- req.setSdncRequestHeader(sdncRequestHeader);
- req.setServiceInformation(serviceInformation);
- req.setVnfInformation(vnfInformation);
+ req.setRequestInformation(requestInformation);
+ req.setSdncRequestHeader(sdncRequestHeader);
+ req.setServiceInformation(serviceInformation);
+ req.setVnfInformation(vnfInformation);
- GenericResourceApiParam vnfInputParameters = new GenericResourceApiParam();
- if (requestContext != null && requestContext.getUserParams() != null) {
- for (Map.Entry<String, Object> entry : requestContext.getUserParams().entrySet()) {
- GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
- paramItem.setName(entry.getKey());
- paramItem.setValue(generalTopologyObjectMapper.mapUserParamValue(entry.getValue()));
- vnfInputParameters.addParamItem(paramItem);
- vnfRequestInput.setVnfInputParameters(vnfInputParameters);
- }
- }
- if (vnf.getCloudParams() != null) {
- for (Map.Entry<String, String> entry : vnf.getCloudParams().entrySet()) {
- GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
- paramItem.setName(entry.getKey());
- paramItem.setValue(entry.getValue());
- vnfInputParameters.addParamItem(paramItem);
- }
- }
- if (homing) {
- License license = vnf.getLicense();
- if (license != null) {
- if(license.getEntitlementPoolUuids() != null && !license.getEntitlementPoolUuids().isEmpty()) {
- String entitlementPoolUuid = license.getEntitlementPoolUuids().get(0);
- GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
- paramItem.setName("entitlement_assignment_group_uuid");
- paramItem.setValue(entitlementPoolUuid);
- vnfInputParameters.addParamItem(paramItem);
- }
- if (license.getLicenseKeyGroupUuids() != null && !license.getLicenseKeyGroupUuids().isEmpty()) {
- String licenseKeyGroupUuid = license.getLicenseKeyGroupUuids().get(0);
- GenericResourceApiParamParam paramItem2 = new GenericResourceApiParamParam();
- paramItem2.setName("license_assignment_group_uuid");
- paramItem2.setValue(licenseKeyGroupUuid);
- vnfInputParameters.addParamItem(paramItem2);
- }
- }
- }
- List<InstanceGroup> instanceGroups = vnf.getInstanceGroups();
- List<GenericResourceApiVnfrequestinputVnfrequestinputVnfNetworkInstanceGroupIds> networkInstanceGroupIdList = new ArrayList<GenericResourceApiVnfrequestinputVnfrequestinputVnfNetworkInstanceGroupIds>();
+ GenericResourceApiParam vnfInputParameters = new GenericResourceApiParam();
+ if (requestContext != null && requestContext.getUserParams() != null) {
+ for (Map.Entry<String, Object> entry : requestContext.getUserParams().entrySet()) {
+ GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
+ paramItem.setName(entry.getKey());
+ paramItem.setValue(generalTopologyObjectMapper.mapUserParamValue(entry.getValue()));
+ vnfInputParameters.addParamItem(paramItem);
+ vnfRequestInput.setVnfInputParameters(vnfInputParameters);
+ }
+ }
+ if (vnf.getCloudParams() != null) {
+ for (Map.Entry<String, String> entry : vnf.getCloudParams().entrySet()) {
+ GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
+ paramItem.setName(entry.getKey());
+ paramItem.setValue(entry.getValue());
+ vnfInputParameters.addParamItem(paramItem);
+ }
+ }
+ if (homing) {
+ License license = vnf.getLicense();
+ if (license != null) {
+ if (license.getEntitlementPoolUuids() != null && !license.getEntitlementPoolUuids().isEmpty()) {
+ String entitlementPoolUuid = license.getEntitlementPoolUuids().get(0);
+ GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam();
+ paramItem.setName("entitlement_assignment_group_uuid");
+ paramItem.setValue(entitlementPoolUuid);
+ vnfInputParameters.addParamItem(paramItem);
+ }
+ if (license.getLicenseKeyGroupUuids() != null && !license.getLicenseKeyGroupUuids().isEmpty()) {
+ String licenseKeyGroupUuid = license.getLicenseKeyGroupUuids().get(0);
+ GenericResourceApiParamParam paramItem2 = new GenericResourceApiParamParam();
+ paramItem2.setName("license_assignment_group_uuid");
+ paramItem2.setValue(licenseKeyGroupUuid);
+ vnfInputParameters.addParamItem(paramItem2);
+ }
+ }
+ }
+ List<InstanceGroup> instanceGroups = vnf.getInstanceGroups();
+ List<GenericResourceApiVnfrequestinputVnfrequestinputVnfNetworkInstanceGroupIds> networkInstanceGroupIdList =
+ new ArrayList<GenericResourceApiVnfrequestinputVnfrequestinputVnfNetworkInstanceGroupIds>();
- for (InstanceGroup instanceGroup : instanceGroups) {
- if (ModelInfoInstanceGroup.TYPE_L3_NETWORK
- .equalsIgnoreCase(instanceGroup.getModelInfoInstanceGroup().getType())) {
- GenericResourceApiVnfrequestinputVnfrequestinputVnfNetworkInstanceGroupIds instanceGroupId = new GenericResourceApiVnfrequestinputVnfrequestinputVnfNetworkInstanceGroupIds();
- instanceGroupId.setVnfNetworkInstanceGroupId(instanceGroup.getId());
- networkInstanceGroupIdList.add(instanceGroupId);
- }
- }
+ for (InstanceGroup instanceGroup : instanceGroups) {
+ if (ModelInfoInstanceGroup.TYPE_L3_NETWORK
+ .equalsIgnoreCase(instanceGroup.getModelInfoInstanceGroup().getType())) {
+ GenericResourceApiVnfrequestinputVnfrequestinputVnfNetworkInstanceGroupIds instanceGroupId =
+ new GenericResourceApiVnfrequestinputVnfrequestinputVnfNetworkInstanceGroupIds();
+ instanceGroupId.setVnfNetworkInstanceGroupId(instanceGroup.getId());
+ networkInstanceGroupIdList.add(instanceGroupId);
+ }
+ }
- vnfRequestInput.setVnfNetworkInstanceGroupIds(networkInstanceGroupIdList);
- vnfRequestInput.setVnfInputParameters(vnfInputParameters);
- req.setVnfRequestInput(vnfRequestInput);
- return req;
- }
+ vnfRequestInput.setVnfNetworkInstanceGroupIds(networkInstanceGroupIdList);
+ vnfRequestInput.setVnfInputParameters(vnfInputParameters);
+ req.setVnfRequestInput(vnfRequestInput);
+ return req;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java
index 5a48a757bc..f7aad558b2 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java
@@ -23,7 +23,6 @@
package org.onap.so.client.sniro;
import java.util.LinkedHashMap;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.onap.so.bpmn.common.baseclient.BaseClient;
import org.onap.so.bpmn.core.UrnPropertiesReader;
@@ -38,82 +37,83 @@ import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
@Component
public class SniroClient {
- private static final Logger logger = LoggerFactory.getLogger(SniroClient.class);
-
- @Autowired
- private ManagerProperties managerProperties;
-
- @Autowired
- private SniroValidator validator;
-
-
- /**
- * Makes a rest call to sniro manager to perform homing and licensing for a
- * list of demands
- *
- * @param homingRequest
- * @return
- * @throws JsonProcessingException
- * @throws BpmnError
- */
- public void postDemands(SniroManagerRequest homingRequest) throws BadResponseException, JsonProcessingException{
- logger.trace("Started Sniro Client Post Demands");
- String url = managerProperties.getHost() + managerProperties.getUri().get("v2");
- logger.debug("Post demands url: {}", url);
- logger.debug("Post demands payload: {}", homingRequest.toJsonString());
-
- HttpHeaders header = new HttpHeaders();
- header.setContentType(MediaType.APPLICATION_JSON);
- header.set("Authorization", managerProperties.getHeaders().get("auth"));
- header.set("X-patchVersion", managerProperties.getHeaders().get("patchVersion"));
- header.set("X-minorVersion", managerProperties.getHeaders().get("minorVersion"));
- header.set("X-latestVersion", managerProperties.getHeaders().get("latestVersion"));
- BaseClient<String, LinkedHashMap<String, Object>> baseClient = new BaseClient<>();
-
- baseClient.setTargetUrl(url);
- baseClient.setHttpHeader(header);
-
- LinkedHashMap<String, Object> response = baseClient.post(homingRequest.toJsonString(), new ParameterizedTypeReference<LinkedHashMap<String, Object>>() {});
- validator.validateDemandsResponse(response);
- logger.trace("Completed Sniro Client Post Demands");
- }
-
- /**
- * Makes a rest call to sniro conductor to notify them of successful or unsuccessful vnf
- * creation for previously homed resources
- *
- * TODO Temporarily being used in groovy therefore can not utilize autowire. Once java "release"
- * subflow is developed it will be refactored to use autowire.
- *
- * @param releaseRequest
- * @return
- * @throws BadResponseException
- */
- public void postRelease(SniroConductorRequest releaseRequest) throws BadResponseException {
- logger.trace("Started Sniro Client Post Release");
- String url = UrnPropertiesReader.getVariable("sniro.conductor.host") + UrnPropertiesReader.getVariable("sniro.conductor.uri");
- logger.debug("Post release url: {}", url);
- logger.debug("Post release payload: {}", releaseRequest.toJsonString());
-
- HttpHeaders header = new HttpHeaders();
- header.setContentType(MediaType.APPLICATION_JSON);
- header.set("Authorization", UrnPropertiesReader.getVariable("sniro.conductor.headers.auth"));
- BaseClient<String, LinkedHashMap<String, Object>> baseClient = new BaseClient<>();
-
- baseClient.setTargetUrl(url);
- baseClient.setHttpHeader(header);
-
- LinkedHashMap<String, Object> response = baseClient.post(releaseRequest.toJsonString(), new ParameterizedTypeReference<LinkedHashMap<String, Object>>() {});
- SniroValidator v = new SniroValidator();
- v.validateReleaseResponse(response);
- logger.trace("Completed Sniro Client Post Release");
- }
+ private static final Logger logger = LoggerFactory.getLogger(SniroClient.class);
+
+ @Autowired
+ private ManagerProperties managerProperties;
+
+ @Autowired
+ private SniroValidator validator;
+
+
+ /**
+ * Makes a rest call to sniro manager to perform homing and licensing for a list of demands
+ *
+ * @param homingRequest
+ * @return
+ * @throws JsonProcessingException
+ * @throws BpmnError
+ */
+ public void postDemands(SniroManagerRequest homingRequest) throws BadResponseException, JsonProcessingException {
+ logger.trace("Started Sniro Client Post Demands");
+ String url = managerProperties.getHost() + managerProperties.getUri().get("v2");
+ logger.debug("Post demands url: {}", url);
+ logger.debug("Post demands payload: {}", homingRequest.toJsonString());
+
+ HttpHeaders header = new HttpHeaders();
+ header.setContentType(MediaType.APPLICATION_JSON);
+ header.set("Authorization", managerProperties.getHeaders().get("auth"));
+ header.set("X-patchVersion", managerProperties.getHeaders().get("patchVersion"));
+ header.set("X-minorVersion", managerProperties.getHeaders().get("minorVersion"));
+ header.set("X-latestVersion", managerProperties.getHeaders().get("latestVersion"));
+ BaseClient<String, LinkedHashMap<String, Object>> baseClient = new BaseClient<>();
+
+ baseClient.setTargetUrl(url);
+ baseClient.setHttpHeader(header);
+
+ LinkedHashMap<String, Object> response = baseClient.post(homingRequest.toJsonString(),
+ new ParameterizedTypeReference<LinkedHashMap<String, Object>>() {});
+ validator.validateDemandsResponse(response);
+ logger.trace("Completed Sniro Client Post Demands");
+ }
+
+ /**
+ * Makes a rest call to sniro conductor to notify them of successful or unsuccessful vnf creation for previously
+ * homed resources
+ *
+ * TODO Temporarily being used in groovy therefore can not utilize autowire. Once java "release" subflow is
+ * developed it will be refactored to use autowire.
+ *
+ * @param releaseRequest
+ * @return
+ * @throws BadResponseException
+ */
+ public void postRelease(SniroConductorRequest releaseRequest) throws BadResponseException {
+ logger.trace("Started Sniro Client Post Release");
+ String url = UrnPropertiesReader.getVariable("sniro.conductor.host")
+ + UrnPropertiesReader.getVariable("sniro.conductor.uri");
+ logger.debug("Post release url: {}", url);
+ logger.debug("Post release payload: {}", releaseRequest.toJsonString());
+
+ HttpHeaders header = new HttpHeaders();
+ header.setContentType(MediaType.APPLICATION_JSON);
+ header.set("Authorization", UrnPropertiesReader.getVariable("sniro.conductor.headers.auth"));
+ BaseClient<String, LinkedHashMap<String, Object>> baseClient = new BaseClient<>();
+
+ baseClient.setTargetUrl(url);
+ baseClient.setHttpHeader(header);
+
+ LinkedHashMap<String, Object> response = baseClient.post(releaseRequest.toJsonString(),
+ new ParameterizedTypeReference<LinkedHashMap<String, Object>>() {});
+ SniroValidator v = new SniroValidator();
+ v.validateReleaseResponse(response);
+ logger.trace("Completed Sniro Client Post Release");
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java
index dcccd319c6..a448082cfe 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java
@@ -24,12 +24,9 @@ package org.onap.so.client.sniro;
import static org.apache.commons.lang.StringUtils.*;
-
import java.util.LinkedHashMap;
-
import org.json.JSONObject;
import org.onap.so.client.exception.BadResponseException;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@@ -39,101 +36,103 @@ import org.springframework.stereotype.Component;
@Component
public class SniroValidator {
- private static final Logger logger = LoggerFactory.getLogger(SniroValidator.class);
-
- /**
- * Validates the synchronous homing response from sniro manager
- *
- * @throws BadResponseException
- */
- public void validateDemandsResponse(LinkedHashMap<String, Object> response) throws BadResponseException {
- logger.debug("Validating Sniro Managers synchronous response");
- if(!response.isEmpty()){
- JSONObject jsonResponse = new JSONObject(response);
- if(jsonResponse.has("requestStatus")){
- String status = jsonResponse.getString("requestStatus");
- if(status.equals("accepted")){
- logger.debug("Sniro Managers synchronous response indicates accepted");
- }else{
- String message = jsonResponse.getString("statusMessage");
- if(isNotBlank(message)){
- logger.debug("Sniro Managers response indicates failed: " + message);
- }else{
- logger.debug("Sniro Managers response indicates failed: no status message provided");
- message = "error message not provided";
- }
- throw new BadResponseException("Sniro Managers synchronous response indicates failed: " + message);
- }
- }else{
- logger.debug("Sniro Managers synchronous response does not contain: request status");
- throw new BadResponseException("Sniro Managers synchronous response does not contain: request status");
- }
- }else{
- logger.debug("Sniro Managers synchronous response is empty");
- throw new BadResponseException("Sniro Managers synchronous response i is empty");
- }
- }
-
- /**
- * Validates the asynchronous/callback response from sniro manager which
- * contains the homing and licensing solutions
- *
- * @throws BadResponseException
- */
- public static void validateSolution(String response) throws BadResponseException{
- logger.debug("Validating Sniro Managers asynchronous callback response");
- if(isNotBlank(response)) {
- JSONObject jsonResponse = new JSONObject(response);
- if(!jsonResponse.has("serviceException")){
- logger.debug("Sniro Managers asynchronous response is valid");
- }else{
- String message = jsonResponse.getJSONObject("serviceException").getString("text");
- if(isNotBlank(message)){
- logger.debug("Sniro Managers response contains a service exception: " + message);
- }else{
- logger.debug("Sniro Managers response contains a service exception: no service exception text provided");
- message = "error message not provided";
- }
- throw new BadResponseException("Sniro Managers asynchronous response contains a service exception: " + message);
- }
- }else{
- logger.debug("Sniro Managers asynchronous response is empty");
- throw new BadResponseException("Sniro Managers asynchronous response is empty");
- }
- }
-
-
- /**
- * Validates the release response from sniro conductor
- *
- * @throws BadResponseException
- */
- public void validateReleaseResponse(LinkedHashMap<String, Object> response) throws BadResponseException {
- logger.debug("Validating Sniro Conductors response");
- if(!response.isEmpty()){
- String status = (String) response.get("status");
- if(isNotBlank(status)){
- if(status.equals("success")){
- logger.debug("Sniro Conductors synchronous response indicates success");
- }else{
- String message = (String) response.get("message");
- if(isNotBlank(message)){
- logger.debug("Sniro Conductors response indicates failed: " + message);
- }else{
- logger.debug("Sniro Conductors response indicates failed: error message not provided");
- message = "error message not provided";
- }
- throw new BadResponseException("Sniro Conductors synchronous response indicates failed: " + message);
- }
- }else{
- logger.debug("Sniro Managers Conductors response does not contain: status");
- throw new BadResponseException("Sniro Conductors synchronous response does not contain: status");
- }
- }else{
- logger.debug("Sniro Conductors response is empty");
- throw new BadResponseException("Sniro Conductors response is empty");
- }
-
- }
+ private static final Logger logger = LoggerFactory.getLogger(SniroValidator.class);
+
+ /**
+ * Validates the synchronous homing response from sniro manager
+ *
+ * @throws BadResponseException
+ */
+ public void validateDemandsResponse(LinkedHashMap<String, Object> response) throws BadResponseException {
+ logger.debug("Validating Sniro Managers synchronous response");
+ if (!response.isEmpty()) {
+ JSONObject jsonResponse = new JSONObject(response);
+ if (jsonResponse.has("requestStatus")) {
+ String status = jsonResponse.getString("requestStatus");
+ if (status.equals("accepted")) {
+ logger.debug("Sniro Managers synchronous response indicates accepted");
+ } else {
+ String message = jsonResponse.getString("statusMessage");
+ if (isNotBlank(message)) {
+ logger.debug("Sniro Managers response indicates failed: " + message);
+ } else {
+ logger.debug("Sniro Managers response indicates failed: no status message provided");
+ message = "error message not provided";
+ }
+ throw new BadResponseException("Sniro Managers synchronous response indicates failed: " + message);
+ }
+ } else {
+ logger.debug("Sniro Managers synchronous response does not contain: request status");
+ throw new BadResponseException("Sniro Managers synchronous response does not contain: request status");
+ }
+ } else {
+ logger.debug("Sniro Managers synchronous response is empty");
+ throw new BadResponseException("Sniro Managers synchronous response i is empty");
+ }
+ }
+
+ /**
+ * Validates the asynchronous/callback response from sniro manager which contains the homing and licensing solutions
+ *
+ * @throws BadResponseException
+ */
+ public static void validateSolution(String response) throws BadResponseException {
+ logger.debug("Validating Sniro Managers asynchronous callback response");
+ if (isNotBlank(response)) {
+ JSONObject jsonResponse = new JSONObject(response);
+ if (!jsonResponse.has("serviceException")) {
+ logger.debug("Sniro Managers asynchronous response is valid");
+ } else {
+ String message = jsonResponse.getJSONObject("serviceException").getString("text");
+ if (isNotBlank(message)) {
+ logger.debug("Sniro Managers response contains a service exception: " + message);
+ } else {
+ logger.debug(
+ "Sniro Managers response contains a service exception: no service exception text provided");
+ message = "error message not provided";
+ }
+ throw new BadResponseException(
+ "Sniro Managers asynchronous response contains a service exception: " + message);
+ }
+ } else {
+ logger.debug("Sniro Managers asynchronous response is empty");
+ throw new BadResponseException("Sniro Managers asynchronous response is empty");
+ }
+ }
+
+
+ /**
+ * Validates the release response from sniro conductor
+ *
+ * @throws BadResponseException
+ */
+ public void validateReleaseResponse(LinkedHashMap<String, Object> response) throws BadResponseException {
+ logger.debug("Validating Sniro Conductors response");
+ if (!response.isEmpty()) {
+ String status = (String) response.get("status");
+ if (isNotBlank(status)) {
+ if (status.equals("success")) {
+ logger.debug("Sniro Conductors synchronous response indicates success");
+ } else {
+ String message = (String) response.get("message");
+ if (isNotBlank(message)) {
+ logger.debug("Sniro Conductors response indicates failed: " + message);
+ } else {
+ logger.debug("Sniro Conductors response indicates failed: error message not provided");
+ message = "error message not provided";
+ }
+ throw new BadResponseException(
+ "Sniro Conductors synchronous response indicates failed: " + message);
+ }
+ } else {
+ logger.debug("Sniro Managers Conductors response does not contain: status");
+ throw new BadResponseException("Sniro Conductors synchronous response does not contain: status");
+ }
+ } else {
+ logger.debug("Sniro Conductors response is empty");
+ throw new BadResponseException("Sniro Conductors response is empty");
+ }
+
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Candidate.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Candidate.java
index 3b7e509752..cded23aad2 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Candidate.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Candidate.java
@@ -22,45 +22,43 @@ package org.onap.so.client.sniro.beans;
import java.io.Serializable;
import java.util.List;
-
import org.onap.so.bpmn.servicedecomposition.homingobjects.CandidateType;
-
import com.fasterxml.jackson.annotation.JsonProperty;
-public class Candidate implements Serializable{
+public class Candidate implements Serializable {
- private static final long serialVersionUID = -5474502255533410907L;
+ private static final long serialVersionUID = -5474502255533410907L;
- @JsonProperty("identifierType")
- private CandidateType identifierType;
- @JsonProperty("identifiers")
- private List<String> identifiers;
- @JsonProperty("cloudOwner")
- private String cloudOwner;
+ @JsonProperty("identifierType")
+ private CandidateType identifierType;
+ @JsonProperty("identifiers")
+ private List<String> identifiers;
+ @JsonProperty("cloudOwner")
+ private String cloudOwner;
- public CandidateType getIdentifierType(){
- return identifierType;
- }
+ public CandidateType getIdentifierType() {
+ return identifierType;
+ }
- public void setIdentifierType(CandidateType identifierType){
- this.identifierType = identifierType;
- }
+ public void setIdentifierType(CandidateType identifierType) {
+ this.identifierType = identifierType;
+ }
- public List<String> getIdentifiers(){
- return identifiers;
- }
+ public List<String> getIdentifiers() {
+ return identifiers;
+ }
- public void setIdentifiers(List<String> identifiers){
- this.identifiers = identifiers;
- }
+ public void setIdentifiers(List<String> identifiers) {
+ this.identifiers = identifiers;
+ }
- public String getCloudOwner(){
- return cloudOwner;
- }
+ public String getCloudOwner() {
+ return cloudOwner;
+ }
- public void setCloudOwner(String cloudOwner){
- this.cloudOwner = cloudOwner;
- }
+ public void setCloudOwner(String cloudOwner) {
+ this.cloudOwner = cloudOwner;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ConductorProperties.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ConductorProperties.java
index 6e60bfa293..9ac8727a0f 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ConductorProperties.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ConductorProperties.java
@@ -21,7 +21,6 @@
package org.onap.so.client.sniro.beans;
import java.util.Map;
-
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@@ -29,33 +28,35 @@ import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "sniro.conductor")
public class ConductorProperties {
- private String host;
- private String uri;
-
- private Map<String, String> headers;
-
-
- public String getHost() {
- return host;
- }
- public void setHost(String host) {
- this.host = host;
- }
- public String getUri() {
- return uri;
- }
- public void setUri(String uri) {
- this.uri = uri;
- }
- public Map<String, String> getHeaders() {
- return headers;
- }
- public void setHeaders(Map<String, String> headers) {
- this.headers = headers;
- }
+ private String host;
+ private String uri;
+
+ private Map<String, String> headers;
+
+
+ public String getHost() {
+ return host;
+ }
+
+ public void setHost(String host) {
+ this.host = host;
+ }
+
+ public String getUri() {
+ return uri;
+ }
+ public void setUri(String uri) {
+ this.uri = uri;
+ }
+ public Map<String, String> getHeaders() {
+ return headers;
+ }
+ public void setHeaders(Map<String, String> headers) {
+ this.headers = headers;
+ }
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Demand.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Demand.java
index ed7875f286..19378cdbfa 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Demand.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Demand.java
@@ -22,63 +22,62 @@ package org.onap.so.client.sniro.beans;
import java.io.Serializable;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
-public class Demand implements Serializable{
+public class Demand implements Serializable {
- private static final long serialVersionUID = 5676094538091859816L;
+ private static final long serialVersionUID = 5676094538091859816L;
- @JsonProperty("serviceResourceId")
- private String serviceResourceId;
- @JsonProperty("resourceModuleName")
- private String resourceModuleName;
- @JsonProperty("resourceModelInfo")
- private ModelInfo modelInfo;
- @JsonProperty("requiredCandidates")
- private List<Candidate> requiredCandidates;
- @JsonProperty("excludedCandidates")
- private List<Candidate> excludedCandidates;
+ @JsonProperty("serviceResourceId")
+ private String serviceResourceId;
+ @JsonProperty("resourceModuleName")
+ private String resourceModuleName;
+ @JsonProperty("resourceModelInfo")
+ private ModelInfo modelInfo;
+ @JsonProperty("requiredCandidates")
+ private List<Candidate> requiredCandidates;
+ @JsonProperty("excludedCandidates")
+ private List<Candidate> excludedCandidates;
- public List<Candidate> getRequiredCandidates(){
- return requiredCandidates;
- }
+ public List<Candidate> getRequiredCandidates() {
+ return requiredCandidates;
+ }
- public void setRequiredCandidates(List<Candidate> requiredCandidates){
- this.requiredCandidates = requiredCandidates;
- }
+ public void setRequiredCandidates(List<Candidate> requiredCandidates) {
+ this.requiredCandidates = requiredCandidates;
+ }
- public List<Candidate> getExcludedCandidates(){
- return excludedCandidates;
- }
+ public List<Candidate> getExcludedCandidates() {
+ return excludedCandidates;
+ }
- public void setExcludedCandidates(List<Candidate> excludedCandidates){
- this.excludedCandidates = excludedCandidates;
- }
+ public void setExcludedCandidates(List<Candidate> excludedCandidates) {
+ this.excludedCandidates = excludedCandidates;
+ }
- public String getServiceResourceId(){
- return serviceResourceId;
- }
+ public String getServiceResourceId() {
+ return serviceResourceId;
+ }
- public void setServiceResourceId(String serviceResourceId){
- this.serviceResourceId = serviceResourceId;
- }
+ public void setServiceResourceId(String serviceResourceId) {
+ this.serviceResourceId = serviceResourceId;
+ }
- public String getResourceModuleName(){
- return resourceModuleName;
- }
+ public String getResourceModuleName() {
+ return resourceModuleName;
+ }
- public void setResourceModuleName(String resourceModuleName){
- this.resourceModuleName = resourceModuleName;
- }
+ public void setResourceModuleName(String resourceModuleName) {
+ this.resourceModuleName = resourceModuleName;
+ }
- public ModelInfo getModelInfo(){
- return modelInfo;
- }
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
- public void setModelInfo(ModelInfo modelInfo){
- this.modelInfo = modelInfo;
- }
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/LicenseInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/LicenseInfo.java
index 209792b4d7..d71b4ec5fc 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/LicenseInfo.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/LicenseInfo.java
@@ -23,23 +23,22 @@ package org.onap.so.client.sniro.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
-public class LicenseInfo implements Serializable{
+public class LicenseInfo implements Serializable {
- private static final long serialVersionUID = 6878164369491185856L;
+ private static final long serialVersionUID = 6878164369491185856L;
- @JsonProperty("licenseDemands")
- private List<Demand> demands = new ArrayList<Demand>();
+ @JsonProperty("licenseDemands")
+ private List<Demand> demands = new ArrayList<Demand>();
- public List<Demand> getDemands(){
- return demands;
- }
+ public List<Demand> getDemands() {
+ return demands;
+ }
- public void setDemands(List<Demand> demands){
- this.demands = demands;
- }
+ public void setDemands(List<Demand> demands) {
+ this.demands = demands;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ManagerProperties.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ManagerProperties.java
index 0070f2fe04..70b1a37b5e 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ManagerProperties.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ManagerProperties.java
@@ -21,7 +21,6 @@
package org.onap.so.client.sniro.beans;
import java.util.Map;
-
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@@ -29,30 +28,34 @@ import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "sniro.manager")
public class ManagerProperties {
- private String host;
- private Map<String, String> uri;
- private Map<String, String> headers;
-
-
- public String getHost() {
- return host;
- }
- public void setHost(String host) {
- this.host = host;
- }
- public Map<String, String> getUri() {
- return uri;
- }
- public void setUri(Map<String, String> uri) {
- this.uri = uri;
- }
- public Map<String, String> getHeaders() {
- return headers;
- }
- public void setHeaders(Map<String, String> headers) {
- this.headers = headers;
- }
+ private String host;
+ private Map<String, String> uri;
+ private Map<String, String> headers;
+
+
+ public String getHost() {
+ return host;
+ }
+
+ public void setHost(String host) {
+ this.host = host;
+ }
+
+ public Map<String, String> getUri() {
+ return uri;
+ }
+
+ public void setUri(Map<String, String> uri) {
+ this.uri = uri;
+ }
+
+ public Map<String, String> getHeaders() {
+ return headers;
+ }
+ public void setHeaders(Map<String, String> headers) {
+ this.headers = headers;
+ }
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ModelInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ModelInfo.java
index 34d746b8d2..6c1932e344 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ModelInfo.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ModelInfo.java
@@ -21,62 +21,56 @@
package org.onap.so.client.sniro.beans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
-@JsonPropertyOrder({
- "modelName",
- "modelVersionId",
- "modelVersion",
- "modelInvariantId"
-})
+@JsonPropertyOrder({"modelName", "modelVersionId", "modelVersion", "modelInvariantId"})
@JsonRootName("modelInfo")
-public class ModelInfo implements Serializable{
+public class ModelInfo implements Serializable {
- private static final long serialVersionUID = 1488642558601651075L;
+ private static final long serialVersionUID = 1488642558601651075L;
- @JsonProperty("modelInvariantId")
- private String modelInvariantId;
- @JsonProperty("modelVersionId")
- private String modelVersionId;
- @JsonProperty("modelName")
- private String modelName;
- @JsonProperty("modelVersion")
- private String modelVersion;
+ @JsonProperty("modelInvariantId")
+ private String modelInvariantId;
+ @JsonProperty("modelVersionId")
+ private String modelVersionId;
+ @JsonProperty("modelName")
+ private String modelName;
+ @JsonProperty("modelVersion")
+ private String modelVersion;
- public String getModelInvariantId(){
- return modelInvariantId;
- }
+ public String getModelInvariantId() {
+ return modelInvariantId;
+ }
- public void setModelInvariantId(String modelInvariantId){
- this.modelInvariantId = modelInvariantId;
- }
+ public void setModelInvariantId(String modelInvariantId) {
+ this.modelInvariantId = modelInvariantId;
+ }
- public String getModelVersionId(){
- return modelVersionId;
- }
+ public String getModelVersionId() {
+ return modelVersionId;
+ }
- public void setModelVersionId(String modelVersionId){
- this.modelVersionId = modelVersionId;
- }
+ public void setModelVersionId(String modelVersionId) {
+ this.modelVersionId = modelVersionId;
+ }
- public String getModelName(){
- return modelName;
- }
+ public String getModelName() {
+ return modelName;
+ }
- public void setModelName(String modelName){
- this.modelName = modelName;
- }
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
- public String getModelVersion(){
- return modelVersion;
- }
+ public String getModelVersion() {
+ return modelVersion;
+ }
- public void setModelVersion(String modelVersion){
- this.modelVersion = modelVersion;
- }
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/PlacementInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/PlacementInfo.java
index 9ae2c72798..ae13903a22 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/PlacementInfo.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/PlacementInfo.java
@@ -23,53 +23,48 @@ package org.onap.so.client.sniro.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.annotation.JsonRootName;
-@JsonPropertyOrder({
- "subscriberInfo",
- "placementDemands",
- "requestParameters"
-})
+@JsonPropertyOrder({"subscriberInfo", "placementDemands", "requestParameters"})
@JsonRootName("placementInfo")
-public class PlacementInfo implements Serializable{
+public class PlacementInfo implements Serializable {
- private static final long serialVersionUID = -964488472247386556L;
+ private static final long serialVersionUID = -964488472247386556L;
- @JsonProperty("subscriberInfo")
- private SubscriberInfo subscriberInfo;
- @JsonProperty("placementDemands")
- private List<Demand> demands = new ArrayList<Demand>();
- @JsonRawValue
- @JsonProperty("requestParameters")
- private String requestParameters;
+ @JsonProperty("subscriberInfo")
+ private SubscriberInfo subscriberInfo;
+ @JsonProperty("placementDemands")
+ private List<Demand> demands = new ArrayList<Demand>();
+ @JsonRawValue
+ @JsonProperty("requestParameters")
+ private String requestParameters;
- public SubscriberInfo getSubscriberInfo(){
- return subscriberInfo;
- }
+ public SubscriberInfo getSubscriberInfo() {
+ return subscriberInfo;
+ }
- public void setSubscriberInfo(SubscriberInfo subscriberInfo){
- this.subscriberInfo = subscriberInfo;
- }
+ public void setSubscriberInfo(SubscriberInfo subscriberInfo) {
+ this.subscriberInfo = subscriberInfo;
+ }
- public List<Demand> getDemands(){
- return demands;
- }
+ public List<Demand> getDemands() {
+ return demands;
+ }
- public void setDemands(List<Demand> demands){
- this.demands = demands;
- }
+ public void setDemands(List<Demand> demands) {
+ this.demands = demands;
+ }
- public String getRequestParameters(){
- return requestParameters;
- }
+ public String getRequestParameters() {
+ return requestParameters;
+ }
- public void setRequestParameters(String requestParameters){
- this.requestParameters = requestParameters;
- }
+ public void setRequestParameters(String requestParameters) {
+ this.requestParameters = requestParameters;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/RequestInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/RequestInfo.java
index e92b5d1ca3..fc6aec7d14 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/RequestInfo.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/RequestInfo.java
@@ -21,77 +21,75 @@
package org.onap.so.client.sniro.beans;
import java.io.Serializable;
-
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("requestInfo")
-public class RequestInfo implements Serializable{
-
- private static final long serialVersionUID = -759180997599143791L;
-
- @JsonProperty("transactionId")
- String transactionId;
- @JsonProperty("requestId")
- String requestId;
- @JsonProperty("callbackUrl")
- String callbackUrl;
- @JsonProperty("sourceId")
- String sourceId = "mso";
- @JsonProperty("requestType")
- String requestType;
- @JsonProperty("timeout")
- long timeout;
-
- public String getTransactionId(){
- return transactionId;
- }
-
- public void setTransactionId(String transactionId){
- this.transactionId = transactionId;
- }
-
- public String getRequestId(){
- return requestId;
- }
-
- public void setRequestId(String requestId){
- this.requestId = requestId;
- }
-
- public String getCallbackUrl(){
- return callbackUrl;
- }
-
- public void setCallbackUrl(String callbackUrl){
- this.callbackUrl = callbackUrl;
- }
-
- public String getSourceId(){
- return sourceId;
- }
-
- public void setSourceId(String sourceId){
- this.sourceId = sourceId;
- }
-
- public String getRequestType(){
- return requestType;
- }
-
- public void setRequestType(String requestType){
- this.requestType = requestType;
- }
-
- public long getTimeout(){
- return timeout;
- }
-
- public void setTimeout(long timeout){
- this.timeout = timeout;
- }
+public class RequestInfo implements Serializable {
+
+ private static final long serialVersionUID = -759180997599143791L;
+
+ @JsonProperty("transactionId")
+ String transactionId;
+ @JsonProperty("requestId")
+ String requestId;
+ @JsonProperty("callbackUrl")
+ String callbackUrl;
+ @JsonProperty("sourceId")
+ String sourceId = "mso";
+ @JsonProperty("requestType")
+ String requestType;
+ @JsonProperty("timeout")
+ long timeout;
+
+ public String getTransactionId() {
+ return transactionId;
+ }
+
+ public void setTransactionId(String transactionId) {
+ this.transactionId = transactionId;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getCallbackUrl() {
+ return callbackUrl;
+ }
+
+ public void setCallbackUrl(String callbackUrl) {
+ this.callbackUrl = callbackUrl;
+ }
+
+ public String getSourceId() {
+ return sourceId;
+ }
+
+ public void setSourceId(String sourceId) {
+ this.sourceId = sourceId;
+ }
+
+ public String getRequestType() {
+ return requestType;
+ }
+
+ public void setRequestType(String requestType) {
+ this.requestType = requestType;
+ }
+
+ public long getTimeout() {
+ return timeout;
+ }
+
+ public void setTimeout(long timeout) {
+ this.timeout = timeout;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Resource.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Resource.java
index 8441a01072..b5d40a8e80 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Resource.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Resource.java
@@ -21,34 +21,33 @@
package org.onap.so.client.sniro.beans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
-public class Resource implements Serializable{
+public class Resource implements Serializable {
- private static final long serialVersionUID = 5949861520571440421L;
+ private static final long serialVersionUID = 5949861520571440421L;
- @JsonProperty("service-resource-id")
- private String serviceResourceId;
- @JsonProperty("status")
- private String status;
+ @JsonProperty("service-resource-id")
+ private String serviceResourceId;
+ @JsonProperty("status")
+ private String status;
- public String getServiceResourceId(){
- return serviceResourceId;
- }
+ public String getServiceResourceId() {
+ return serviceResourceId;
+ }
- public void setServiceResourceId(String serviceResourceId){
- this.serviceResourceId = serviceResourceId;
- }
+ public void setServiceResourceId(String serviceResourceId) {
+ this.serviceResourceId = serviceResourceId;
+ }
- public String getStatus(){
- return status;
- }
+ public String getStatus() {
+ return status;
+ }
- public void setStatus(String status){
- this.status = status;
- }
+ public void setStatus(String status) {
+ this.status = status;
+ }
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ServiceInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ServiceInfo.java
index f035013cd5..8b6f234c1e 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ServiceInfo.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/ServiceInfo.java
@@ -21,62 +21,56 @@
package org.onap.so.client.sniro.beans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
-@JsonPropertyOrder({
- "modelInfo",
- "serviceRole",
- "serviceInstanceId",
- "serviceName"
-})
+@JsonPropertyOrder({"modelInfo", "serviceRole", "serviceInstanceId", "serviceName"})
@JsonRootName("serviceInfo")
-public class ServiceInfo implements Serializable{
+public class ServiceInfo implements Serializable {
- private static final long serialVersionUID = -6866022419398548585L;
+ private static final long serialVersionUID = -6866022419398548585L;
- @JsonProperty("serviceInstanceId")
- private String serviceInstanceId;
- @JsonProperty("serviceName")
- private String serviceName;
- @JsonProperty("serviceRole")
- private String serviceRole;
- @JsonProperty("modelInfo")
- private ModelInfo modelInfo;
+ @JsonProperty("serviceInstanceId")
+ private String serviceInstanceId;
+ @JsonProperty("serviceName")
+ private String serviceName;
+ @JsonProperty("serviceRole")
+ private String serviceRole;
+ @JsonProperty("modelInfo")
+ private ModelInfo modelInfo;
- public String getServiceInstanceId(){
- return serviceInstanceId;
- }
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
- public void setServiceInstanceId(String serviceInstanceId){
- this.serviceInstanceId = serviceInstanceId;
- }
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
- public String getServiceName(){
- return serviceName;
- }
+ public String getServiceName() {
+ return serviceName;
+ }
- public void setServiceName(String serviceName){
- this.serviceName = serviceName;
- }
+ public void setServiceName(String serviceName) {
+ this.serviceName = serviceName;
+ }
- public String getServiceRole(){
- return serviceRole;
- }
+ public String getServiceRole() {
+ return serviceRole;
+ }
- public void setServiceRole(String serviceRole){
- this.serviceRole = serviceRole;
- }
+ public void setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ }
- public ModelInfo getModelInfo(){
- return modelInfo;
- }
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
- public void setModelInfo(ModelInfo modelInfo){
- this.modelInfo = modelInfo;
- }
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroConductorRequest.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroConductorRequest.java
index 11417d646c..f632424c26 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroConductorRequest.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroConductorRequest.java
@@ -25,7 +25,6 @@ package org.onap.so.client.sniro.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@@ -35,32 +34,32 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class SniroConductorRequest implements Serializable{
+public class SniroConductorRequest implements Serializable {
- private static final long serialVersionUID = 1906052095861777655L;
- private static final Logger logger = LoggerFactory.getLogger(SniroConductorRequest.class);
+ private static final long serialVersionUID = 1906052095861777655L;
+ private static final Logger logger = LoggerFactory.getLogger(SniroConductorRequest.class);
- @JsonProperty("release-locks")
- private List<Resource> resources = new ArrayList<Resource>();
+ @JsonProperty("release-locks")
+ private List<Resource> resources = new ArrayList<Resource>();
- public List<Resource> getResources(){
- return resources;
- }
+ public List<Resource> getResources() {
+ return resources;
+ }
- @JsonInclude(Include.NON_NULL)
- public String toJsonString(){
- String json = "";
- ObjectMapper mapper = new ObjectMapper();
- mapper.setSerializationInclusion(Include.NON_NULL);
- ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
- try{
- json = ow.writeValueAsString(this);
- }catch (Exception e){
- logger.error("Unable to convert SniroConductorRequest to string", e);
- }
- return json;
- }
+ @JsonInclude(Include.NON_NULL)
+ public String toJsonString() {
+ String json = "";
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(Include.NON_NULL);
+ ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
+ try {
+ json = ow.writeValueAsString(this);
+ } catch (Exception e) {
+ logger.error("Unable to convert SniroConductorRequest to string", e);
+ }
+ return json;
+ }
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroManagerRequest.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroManagerRequest.java
index c1e376814f..4babbe5c39 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroManagerRequest.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroManagerRequest.java
@@ -23,7 +23,6 @@
package org.onap.so.client.sniro.beans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@@ -33,60 +32,67 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class SniroManagerRequest implements Serializable{
-
- private static final long serialVersionUID = -1541132882892163132L;
- private static final Logger logger = LoggerFactory.getLogger(SniroManagerRequest.class);
-
- @JsonProperty("requestInfo")
- private RequestInfo requestInformation;
- @JsonProperty("serviceInfo")
- private ServiceInfo serviceInformation;
- @JsonProperty("placementInfo")
- private PlacementInfo placementInformation;
- @JsonProperty("licenseInfo")
- private LicenseInfo licenseInformation;
-
-
- public RequestInfo getRequestInformation() {
- return requestInformation;
- }
- public void setRequestInformation(RequestInfo requestInformation) {
- this.requestInformation = requestInformation;
- }
- public ServiceInfo getServiceInformation() {
- return serviceInformation;
- }
- public void setServiceInformation(ServiceInfo serviceInformation) {
- this.serviceInformation = serviceInformation;
- }
- public PlacementInfo getPlacementInformation() {
- return placementInformation;
- }
- public void setPlacementInformation(PlacementInfo placementInformation) {
- this.placementInformation = placementInformation;
- }
- public LicenseInfo getLicenseInformation() {
- return licenseInformation;
- }
- public void setLicenseInformation(LicenseInfo licenseInformation) {
- this.licenseInformation = licenseInformation;
- }
-
-
- @JsonInclude(Include.NON_NULL)
- public String toJsonString(){
- String json = "";
- ObjectMapper mapper = new ObjectMapper();
- mapper.setSerializationInclusion(Include.NON_NULL);
- ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
- try{
- json = ow.writeValueAsString(this);
- }catch (Exception e){
- logger.error("Unable to convert SniroManagerRequest to string", e);
- }
- return json.replaceAll("\\\\", "");
- }
+public class SniroManagerRequest implements Serializable {
+
+ private static final long serialVersionUID = -1541132882892163132L;
+ private static final Logger logger = LoggerFactory.getLogger(SniroManagerRequest.class);
+
+ @JsonProperty("requestInfo")
+ private RequestInfo requestInformation;
+ @JsonProperty("serviceInfo")
+ private ServiceInfo serviceInformation;
+ @JsonProperty("placementInfo")
+ private PlacementInfo placementInformation;
+ @JsonProperty("licenseInfo")
+ private LicenseInfo licenseInformation;
+
+
+ public RequestInfo getRequestInformation() {
+ return requestInformation;
+ }
+
+ public void setRequestInformation(RequestInfo requestInformation) {
+ this.requestInformation = requestInformation;
+ }
+
+ public ServiceInfo getServiceInformation() {
+ return serviceInformation;
+ }
+
+ public void setServiceInformation(ServiceInfo serviceInformation) {
+ this.serviceInformation = serviceInformation;
+ }
+
+ public PlacementInfo getPlacementInformation() {
+ return placementInformation;
+ }
+
+ public void setPlacementInformation(PlacementInfo placementInformation) {
+ this.placementInformation = placementInformation;
+ }
+
+ public LicenseInfo getLicenseInformation() {
+ return licenseInformation;
+ }
+
+ public void setLicenseInformation(LicenseInfo licenseInformation) {
+ this.licenseInformation = licenseInformation;
+ }
+
+
+ @JsonInclude(Include.NON_NULL)
+ public String toJsonString() {
+ String json = "";
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(Include.NON_NULL);
+ ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
+ try {
+ json = ow.writeValueAsString(this);
+ } catch (Exception e) {
+ logger.error("Unable to convert SniroManagerRequest to string", e);
+ }
+ return json.replaceAll("\\\\", "");
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SubscriberInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SubscriberInfo.java
index b6b09cbf80..eaf8b6e379 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SubscriberInfo.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SubscriberInfo.java
@@ -21,46 +21,45 @@
package org.onap.so.client.sniro.beans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("subscriberInfo")
-public class SubscriberInfo implements Serializable{
+public class SubscriberInfo implements Serializable {
- private static final long serialVersionUID = -6350949051379748872L;
+ private static final long serialVersionUID = -6350949051379748872L;
- @JsonProperty("globalSubscriberId")
- private String globalSubscriberId;
- @JsonProperty("subscriberName")
- private String subscriberName;
- @JsonProperty("subscriberCommonSiteId")
- private String subscriberCommonSiteId;
+ @JsonProperty("globalSubscriberId")
+ private String globalSubscriberId;
+ @JsonProperty("subscriberName")
+ private String subscriberName;
+ @JsonProperty("subscriberCommonSiteId")
+ private String subscriberCommonSiteId;
- public String getGlobalSubscriberId(){
- return globalSubscriberId;
- }
+ public String getGlobalSubscriberId() {
+ return globalSubscriberId;
+ }
- public void setGlobalSubscriberId(String globalSubscriberId){
- this.globalSubscriberId = globalSubscriberId;
- }
+ public void setGlobalSubscriberId(String globalSubscriberId) {
+ this.globalSubscriberId = globalSubscriberId;
+ }
- public String getSubscriberName(){
- return subscriberName;
- }
+ public String getSubscriberName() {
+ return subscriberName;
+ }
- public void setSubscriberName(String subscriberName){
- this.subscriberName = subscriberName;
- }
+ public void setSubscriberName(String subscriberName) {
+ this.subscriberName = subscriberName;
+ }
- public String getSubscriberCommonSiteId(){
- return subscriberCommonSiteId;
- }
+ public String getSubscriberCommonSiteId() {
+ return subscriberCommonSiteId;
+ }
- public void setSubscriberCommonSiteId(String subscriberCommonSiteId){
- this.subscriberCommonSiteId = subscriberCommonSiteId;
- }
+ public void setSubscriberCommonSiteId(String subscriberCommonSiteId) {
+ this.subscriberCommonSiteId = subscriberCommonSiteId;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/ticket/ExternalTicket.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/ticket/ExternalTicket.java
index 519afe6f2d..a78dffb4e0 100644
--- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/ticket/ExternalTicket.java
+++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/ticket/ExternalTicket.java
@@ -1,155 +1,154 @@
package org.onap.so.client.ticket;
public class ExternalTicket {
- private String requestId;
- private String nfRole;
- private String currentActivity;
- private String description;
- private String subscriptionServiceType;
- private String requestorId;
- private String timeout;
- private String errorSource;
- private String errorCode;
- private String errorMessage;
- private String workStep;
+ private String requestId;
+ private String nfRole;
+ private String currentActivity;
+ private String description;
+ private String subscriptionServiceType;
+ private String requestorId;
+ private String timeout;
+ private String errorSource;
+ private String errorCode;
+ private String errorMessage;
+ private String workStep;
- public String getRequestId() {
- return requestId;
- }
+ public String getRequestId() {
+ return requestId;
+ }
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
- public String getNfRole() {
- return nfRole;
- }
+ public String getNfRole() {
+ return nfRole;
+ }
- public void setNfRole(String nfRole) {
- this.nfRole = nfRole;
- }
+ public void setNfRole(String nfRole) {
+ this.nfRole = nfRole;
+ }
- public String getCurrentActivity() {
- return currentActivity;
- }
+ public String getCurrentActivity() {
+ return currentActivity;
+ }
- public void setCurrentActivity(String currentActivity) {
- this.currentActivity = currentActivity;
- }
+ public void setCurrentActivity(String currentActivity) {
+ this.currentActivity = currentActivity;
+ }
- public String getDescription() {
- return description;
- }
+ public String getDescription() {
+ return description;
+ }
- public void setDescription(String description) {
- this.description = description;
- }
+ public void setDescription(String description) {
+ this.description = description;
+ }
- public String getSubscriptionServiceType() {
- return subscriptionServiceType;
- }
+ public String getSubscriptionServiceType() {
+ return subscriptionServiceType;
+ }
- public void setSubscriptionServiceType(String subscriptionServiceType) {
- this.subscriptionServiceType = subscriptionServiceType;
- }
+ public void setSubscriptionServiceType(String subscriptionServiceType) {
+ this.subscriptionServiceType = subscriptionServiceType;
+ }
- public String getRequestorId() {
- return requestorId;
- }
+ public String getRequestorId() {
+ return requestorId;
+ }
- public void setRequestorId(String requestorId) {
- this.requestorId = requestorId;
- }
+ public void setRequestorId(String requestorId) {
+ this.requestorId = requestorId;
+ }
- public String getTimeout() {
- return timeout;
- }
+ public String getTimeout() {
+ return timeout;
+ }
- public void setTimeout(String timeout) {
- this.timeout = timeout;
- }
+ public void setTimeout(String timeout) {
+ this.timeout = timeout;
+ }
- public String getErrorSource() {
- return errorSource;
- }
+ public String getErrorSource() {
+ return errorSource;
+ }
- public void setErrorSource(String errorSource) {
- this.errorSource = errorSource;
- }
+ public void setErrorSource(String errorSource) {
+ this.errorSource = errorSource;
+ }
- public String getErrorCode() {
- return errorCode;
- }
+ public String getErrorCode() {
+ return errorCode;
+ }
- public void setErrorCode(String errorCode) {
- this.errorCode = errorCode;
- }
+ public void setErrorCode(String errorCode) {
+ this.errorCode = errorCode;
+ }
- public String getErrorMessage() {
- return errorMessage;
- }
+ public String getErrorMessage() {
+ return errorMessage;
+ }
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
- public String getWorkStep() {
- return workStep;
- }
+ public String getWorkStep() {
+ return workStep;
+ }
- public void setWorkStep(String workStep) {
- this.workStep = workStep;
- }
+ public void setWorkStep(String workStep) {
+ this.workStep = workStep;
+ }
- public void createTicket() throws Exception {
- //Replace with your ticket creation mechanism if any
- }
-
-
-
+ public void createTicket() throws Exception {
+ // Replace with your ticket creation mechanism if any
+ }
+
+
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/AllIntegrationTestSuites.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/AllIntegrationTestSuites.java
index 23fcddfe8a..c5cdae4425 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/AllIntegrationTestSuites.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/AllIntegrationTestSuites.java
@@ -21,12 +21,11 @@
package org.onap.so;
import org.junit.runner.RunWith;
-
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses({"**/SniroHomingV2IT.class"})
-public class AllIntegrationTestSuites{
+public class AllIntegrationTestSuites {
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/BaseIntegrationTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/BaseIntegrationTest.java
index aefe4c64bf..3bb8fb70f2 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/BaseIntegrationTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/BaseIntegrationTest.java
@@ -21,7 +21,6 @@ package org.onap.so;
import java.io.IOException;
import java.io.InputStream;
-
import org.junit.Before;
import org.junit.runner.RunWith;
import org.onap.so.bpmn.buildingblock.SniroHomingV2;
@@ -40,7 +39,6 @@ import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
-
import com.github.tomakehurst.wiremock.WireMockServer;
@RunWith(SpringRunner.class)
@@ -50,60 +48,60 @@ import com.github.tomakehurst.wiremock.WireMockServer;
@AutoConfigureWireMock(port = 0)
public abstract class BaseIntegrationTest extends TestDataSetup {
- @Value("${wiremock.server.port}")
- protected String wireMockPort;
+ @Value("${wiremock.server.port}")
+ protected String wireMockPort;
+
+ @SpyBean
+ protected SDNCClient SPY_sdncClient;
+
+ @SpyBean
+ protected SDNOHealthCheckResources MOCK_sdnoHealthCheckResources;
- @SpyBean
- protected SDNCClient SPY_sdncClient;
+ @SpyBean
+ protected SniroHomingV2 sniroHoming;
- @SpyBean
- protected SDNOHealthCheckResources MOCK_sdnoHealthCheckResources;
+ @SpyBean
+ protected SniroClient sniroClient;
- @SpyBean
- protected SniroHomingV2 sniroHoming;
+ @MockBean
+ protected ApplicationControllerAction appCClient;
- @SpyBean
- protected SniroClient sniroClient;
+ @MockBean
+ protected CatalogDbClient catalogDbClient;
- @MockBean
- protected ApplicationControllerAction appCClient;
+ @Autowired
+ protected WireMockServer wireMockServer;
- @MockBean
- protected CatalogDbClient catalogDbClient;
-
- @Autowired
- protected WireMockServer wireMockServer;
+ @Before
+ public void baseTestBefore() {
+ wireMockServer.resetAll();
+ }
- @Before
- public void baseTestBefore() {
- wireMockServer.resetAll();
- }
- public String readResourceFile(String fileName) {
- InputStream stream;
- try {
- stream = getResourceAsStream(fileName);
- byte[] bytes;
- bytes = new byte[stream.available()];
- if(stream.read(bytes) > 0) {
- stream.close();
- return new String(bytes);
- } else {
- stream.close();
- return "";
- }
- } catch (IOException e) {
- return "";
- }
- }
+ public String readResourceFile(String fileName) {
+ InputStream stream;
+ try {
+ stream = getResourceAsStream(fileName);
+ byte[] bytes;
+ bytes = new byte[stream.available()];
+ if (stream.read(bytes) > 0) {
+ stream.close();
+ return new String(bytes);
+ } else {
+ stream.close();
+ return "";
+ }
+ } catch (IOException e) {
+ return "";
+ }
+ }
- private InputStream getResourceAsStream(String resourceName) throws IOException {
- InputStream stream =
- FileUtil.class.getClassLoader().getResourceAsStream(resourceName);
- if (stream == null) {
- throw new IOException("Can't access resource '" + resourceName + "'");
- }
- return stream;
- }
+ private InputStream getResourceAsStream(String resourceName) throws IOException {
+ InputStream stream = FileUtil.class.getClassLoader().getResourceAsStream(resourceName);
+ if (stream == null) {
+ throw new IOException("Can't access resource '" + resourceName + "'");
+ }
+ return stream;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
index fb08e5e830..62d9ecee44 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java
@@ -19,6 +19,7 @@
*/
package org.onap.so;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
@@ -35,30 +36,25 @@ public class EmbeddedMariaDbConfig {
@Bean
MariaDB4jSpringService mariaDB4jSpringService() {
- MariaDB4jSpringService service = new MariaDB4jSpringService();
-
-
- service.getConfiguration().addArg("--lower_case_table_names=1");
+ MariaDB4jSpringService service = new MariaDB4jSpringService();
+
+
+ service.getConfiguration().addArg("--lower_case_table_names=1");
return service;
}
@Bean
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/FileUtil.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/FileUtil.java
index 366c9c11a9..24927b0d1c 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/FileUtil.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/FileUtil.java
@@ -34,51 +34,50 @@ import org.slf4j.LoggerFactory;
* </p>
*
* @author
- * @version ONAP Sep 15, 2017
+ * @version ONAP Sep 15, 2017
*/
public class FileUtil {
private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
-
- /**
- * Read the specified resource file and return the contents as a String.
- *
- * @param fileName Name of the resource file
- * @return the contents of the resource file as a String
- * @throws IOException if there is a problem reading the file
- */
- public static String readResourceFile(String fileName) {
- InputStream stream;
- try {
- stream = getResourceAsStream(fileName);
- byte[] bytes;
- bytes = new byte[stream.available()];
- if(stream.read(bytes) > 0) {
- stream.close();
- return new String(bytes);
- } else {
- stream.close();
- return "";
- }
- } catch (IOException e) {
- logger.debug("Exception:", e);
- return "";
- }
- }
-
- /**
- * Get an InputStream for the resource specified.
- *
- * @param resourceName Name of resource for which to get InputStream.
- * @return an InputStream for the resource specified.
- * @throws IOException If we can't get the InputStream for whatever reason.
- */
- private static InputStream getResourceAsStream(String resourceName) throws IOException {
- InputStream stream =
- FileUtil.class.getClassLoader().getResourceAsStream(resourceName);
- if (stream == null) {
- throw new IOException("Can't access resource '" + resourceName + "'");
- }
- return stream;
- }
+
+ /**
+ * Read the specified resource file and return the contents as a String.
+ *
+ * @param fileName Name of the resource file
+ * @return the contents of the resource file as a String
+ * @throws IOException if there is a problem reading the file
+ */
+ public static String readResourceFile(String fileName) {
+ InputStream stream;
+ try {
+ stream = getResourceAsStream(fileName);
+ byte[] bytes;
+ bytes = new byte[stream.available()];
+ if (stream.read(bytes) > 0) {
+ stream.close();
+ return new String(bytes);
+ } else {
+ stream.close();
+ return "";
+ }
+ } catch (IOException e) {
+ logger.debug("Exception:", e);
+ return "";
+ }
+ }
+
+ /**
+ * Get an InputStream for the resource specified.
+ *
+ * @param resourceName Name of resource for which to get InputStream.
+ * @return an InputStream for the resource specified.
+ * @throws IOException If we can't get the InputStream for whatever reason.
+ */
+ private static InputStream getResourceAsStream(String resourceName) throws IOException {
+ InputStream stream = FileUtil.class.getClassLoader().getResourceAsStream(resourceName);
+ if (stream == null) {
+ throw new IOException("Can't access resource '" + resourceName + "'");
+ }
+ return stream;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/IntegrationTestSuite.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/IntegrationTestSuite.java
index 0eddeb1649..50bbc1845f 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/IntegrationTestSuite.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/IntegrationTestSuite.java
@@ -21,7 +21,6 @@
package org.onap.so;
import org.junit.runner.RunWith;
-
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/TestApplication.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/TestApplication.java
index 87153144c8..2e27b346ea 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/TestApplication.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/TestApplication.java
@@ -31,14 +31,14 @@ import org.springframework.context.annotation.Profile;
@SpringBootApplication
@Profile("test")
-@ComponentScan(basePackages = {"org.onap.so"}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class, excludeFilters = {
- @Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
+@ComponentScan(basePackages = {"org.onap.so"}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class,
+ excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
public class TestApplication {
- public static void main(String... args) {
- SpringApplication.run(TestApplication.class, args);
- System.getProperties().setProperty("mso.db", "MARIADB");
- System.getProperties().setProperty("server.name", "Springboot");
-
-
- }
+ public static void main(String... args) {
+ SpringApplication.run(TestApplication.class, args);
+ System.getProperties().setProperty("mso.db", "MARIADB");
+ System.getProperties().setProperty("server.name", "Springboot");
+
+
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/UnitTestSuite.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/UnitTestSuite.java
index 82ad6582c5..890c81daeb 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/UnitTestSuite.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/UnitTestSuite.java
@@ -22,7 +22,6 @@ package org.onap.so;
import org.junit.runner.RunWith;
-
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java
index 6dc0b1861d..b40e43b959 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java
@@ -58,96 +58,96 @@ import org.springframework.core.env.Environment;
@RunWith(MockitoJUnitRunner.Silent.class)
public abstract class BaseTaskTest extends TestDataSetup {
- @Mock
- protected AAIVolumeGroupResources aaiVolumeGroupResources;
+ @Mock
+ protected AAIVolumeGroupResources aaiVolumeGroupResources;
- @Mock
- protected AAIServiceInstanceResources aaiServiceInstanceResources;
+ @Mock
+ protected AAIServiceInstanceResources aaiServiceInstanceResources;
- @Mock
- protected AAIVnfResources aaiVnfResources;
+ @Mock
+ protected AAIVnfResources aaiVnfResources;
- @Mock
- protected AAIVfModuleResources aaiVfModuleResources;
+ @Mock
+ protected AAIVfModuleResources aaiVfModuleResources;
- @Mock
- protected AAIVpnBindingResources aaiVpnBindingResources;
+ @Mock
+ protected AAIVpnBindingResources aaiVpnBindingResources;
- @Mock
- protected AAINetworkResources aaiNetworkResources;
+ @Mock
+ protected AAINetworkResources aaiNetworkResources;
- @Mock
- protected AAICollectionResources aaiCollectionResources;
+ @Mock
+ protected AAICollectionResources aaiCollectionResources;
- @Mock
- protected NetworkAdapterResources networkAdapterResources;
+ @Mock
+ protected NetworkAdapterResources networkAdapterResources;
- @Mock
- protected VnfAdapterVolumeGroupResources vnfAdapterVolumeGroupResources;
+ @Mock
+ protected VnfAdapterVolumeGroupResources vnfAdapterVolumeGroupResources;
- @Mock
- protected VnfAdapterVfModuleResources vnfAdapterVfModuleResources;
+ @Mock
+ protected VnfAdapterVfModuleResources vnfAdapterVfModuleResources;
- @Mock
- protected SDNCVnfResources sdncVnfResources;
+ @Mock
+ protected SDNCVnfResources sdncVnfResources;
- @Mock
- protected SDNCNetworkResources sdncNetworkResources;
+ @Mock
+ protected SDNCNetworkResources sdncNetworkResources;
- @Mock
- protected SDNCVfModuleResources sdncVfModuleResources;
+ @Mock
+ protected SDNCVfModuleResources sdncVfModuleResources;
- @Mock
- protected SDNCServiceInstanceResources sdncServiceInstanceResources;
+ @Mock
+ protected SDNCServiceInstanceResources sdncServiceInstanceResources;
- @Mock
- protected AssignNetworkBBUtils assignNetworkBBUtils;
+ @Mock
+ protected AssignNetworkBBUtils assignNetworkBBUtils;
- @Mock
- protected NetworkAdapterObjectMapper networkAdapterObjectMapper;
+ @Mock
+ protected NetworkAdapterObjectMapper networkAdapterObjectMapper;
- @Mock
- protected AAIInstanceGroupResources aaiInstanceGroupResources;
-
- @Mock
- protected NamingServiceResources namingServiceResources;
+ @Mock
+ protected AAIInstanceGroupResources aaiInstanceGroupResources;
- @Mock
- protected ApplicationControllerAction appCClient;
+ @Mock
+ protected NamingServiceResources namingServiceResources;
- @Mock
- protected CatalogDbClient catalogDbClient;
+ @Mock
+ protected ApplicationControllerAction appCClient;
- @Mock
- protected RequestsDbClient requestsDbClient;
+ @Mock
+ protected CatalogDbClient catalogDbClient;
- @Mock
- protected BBInputSetupUtils bbSetupUtils;
+ @Mock
+ protected RequestsDbClient requestsDbClient;
- @Mock
- protected BBInputSetup bbInputSetup;
+ @Mock
+ protected BBInputSetupUtils bbSetupUtils;
- @Mock
- protected AAIConfigurationResources aaiConfigurationResources;
+ @Mock
+ protected BBInputSetup bbInputSetup;
- @Mock
- protected AAIObjectMapper MOCK_aaiObjectMapper;
+ @Mock
+ protected AAIConfigurationResources aaiConfigurationResources;
- @Mock
- protected InjectionHelper MOCK_injectionHelper;
+ @Mock
+ protected AAIObjectMapper MOCK_aaiObjectMapper;
- @Mock
- protected AAIResourcesClient MOCK_aaiResourcesClient;
+ @Mock
+ protected InjectionHelper MOCK_injectionHelper;
- @Mock
- protected ExtractPojosForBB extractPojosForBB;
+ @Mock
+ protected AAIResourcesClient MOCK_aaiResourcesClient;
- @Mock
- protected ExceptionBuilder exceptionUtil;
+ @Mock
+ protected ExtractPojosForBB extractPojosForBB;
- @Mock
- protected WorkflowActionExtractResourcesAAI workflowActionUtils;
-
- @Mock
- protected Environment env;
+ @Mock
+ protected ExceptionBuilder exceptionUtil;
+
+ @Mock
+ protected WorkflowActionExtractResourcesAAI workflowActionUtils;
+
+ @Mock
+ protected Environment env;
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/aai/tasks/AAIFlagTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/aai/tasks/AAIFlagTasksTest.java
index a91ef66a29..95689e49cd 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/aai/tasks/AAIFlagTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/aai/tasks/AAIFlagTasksTest.java
@@ -28,9 +28,7 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -56,154 +54,173 @@ import org.springframework.beans.factory.annotation.Autowired;
public class AAIFlagTasksTest extends BaseTaskTest {
- @InjectMocks
- private AAIFlagTasks aaiFlagTasks = new AAIFlagTasks();
-
- private GenericVnf genericVnf;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- genericVnf = setGenericVnf();
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- when(extractPojosForBB.extractByKey(any(),any())).thenReturn(genericVnf);
- }
-
- @Test
- public void checkVnfInMaintTestTrue() throws Exception {
- doThrow(new BpmnError("VNF is in maintenance in A&AI")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- doReturn(false).when(aaiVnfResources).checkInMaintFlag(isA(String.class));
- doReturn(true).when(aaiVnfResources).checkInMaintFlag(isA(String.class));
- try {
- aaiFlagTasks.checkVnfInMaintFlag(execution);
- } catch (Exception e) {
- verify(aaiVnfResources, times(1)).checkInMaintFlag(any(String.class));
- verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), eq("VNF is in maintenance in A&AI"));
- }
- }
-
- @Test
- public void checkVnfInMaintTestFalse() throws Exception {
- doReturn(false).when(aaiVnfResources).checkInMaintFlag(isA(String.class));
- aaiFlagTasks.checkVnfInMaintFlag(execution);
- verify(exceptionUtil, times(0)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), any(int.class), any(String.class));
- }
-
- @Test
- public void checkVnfInMaintFlagExceptionTest() {
-
- doThrow(new BpmnError("Unknown Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- doThrow(RuntimeException.class).when(aaiVnfResources).checkInMaintFlag(isA(String.class));
- try {
- aaiFlagTasks.checkVnfInMaintFlag(execution);
- } catch (Exception e) {
- verify(aaiVnfResources, times(1)).checkInMaintFlag(any(String.class));
- verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- }
-
- }
-
- @Test
- public void modifyVnfInMaintFlagTest() throws Exception {
- doNothing().when(aaiVnfResources).updateObjectVnf(ArgumentMatchers.any(GenericVnf.class));
- aaiFlagTasks.modifyVnfInMaintFlag(execution, true);
- verify(aaiVnfResources, times(1)).updateObjectVnf(ArgumentMatchers.any(GenericVnf.class));
- }
-
- @Test
- public void modifyVnfInMaintFlagExceptionTest() {
-
- doThrow(new BpmnError("Unknown Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- doThrow(RuntimeException.class).when(aaiVnfResources).updateObjectVnf(isA(GenericVnf.class));
- try {
- aaiFlagTasks.modifyVnfInMaintFlag(execution, true);
- } catch (Exception e) {
- verify(aaiVnfResources, times(1)).checkInMaintFlag(any(String.class));
- verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- }
- }
-
- @Test
- public void checkVnfClosedLoopDisabledTestTrue() throws Exception {
- doThrow(new BpmnError("VNF Closed Loop Disabled in A&AI")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- doReturn(false).when(aaiVnfResources).checkVnfClosedLoopDisabledFlag(isA(String.class));
- try {
- aaiFlagTasks.checkVnfClosedLoopDisabledFlag(execution);
- } catch (Exception e) {
- verify(aaiVnfResources, times(1)).checkVnfClosedLoopDisabledFlag(any(String.class));
- verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), eq("VNF Closed Loop Disabled in A&AI"));
- }
- }
-
- @Test
- public void checkVnfClosedLoopDisabledTestFalse() throws Exception {
- doReturn(false).when(aaiVnfResources).checkVnfClosedLoopDisabledFlag(isA(String.class));
- aaiFlagTasks.checkVnfClosedLoopDisabledFlag(execution);
- verify(exceptionUtil, times(0)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), any(int.class), any(String.class));
- }
-
- @Test
- public void checkVnfClosedLoopDisabledFlagExceptionTest() {
-
- doThrow(new BpmnError("Unknown Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- doThrow(RuntimeException.class).when(aaiVnfResources).checkVnfClosedLoopDisabledFlag(isA(String.class));
- try {
- aaiFlagTasks.checkVnfClosedLoopDisabledFlag(execution);
- } catch (Exception e) {
- verify(aaiVnfResources, times(1)).checkVnfClosedLoopDisabledFlag(any(String.class));
- verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- }
- }
-
- @Test
- public void modifyVnfClosedLoopDisabledFlagTest() throws Exception {
- doNothing().when(aaiVnfResources).updateObjectVnf(ArgumentMatchers.any(GenericVnf.class));
- aaiFlagTasks.modifyVnfClosedLoopDisabledFlag(execution, true);
- verify(aaiVnfResources, times(1)).updateObjectVnf(ArgumentMatchers.any(GenericVnf.class));
- }
-
- @Test
- public void modifyVnfClosedLoopDisabledFlagExceptionTest() {
-
- doThrow(new BpmnError("Unknown Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- doThrow(RuntimeException.class).when(aaiVnfResources).updateObjectVnf(isA(GenericVnf.class));
- try {
- aaiFlagTasks.modifyVnfClosedLoopDisabledFlag(execution, true);
- } catch (Exception e) {
- verify(aaiVnfResources, times(1)).checkVnfClosedLoopDisabledFlag(any(String.class));
- verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- }
- }
-
-
- @Test
- public void checkVnfPserversLockedFlagTestTrue() throws Exception {
- doThrow(new BpmnError("VNF PServers in Locked in A&AI")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- doReturn(true).when(aaiVnfResources).checkVnfPserversLockedFlag(isA(String.class));
- try {
- aaiFlagTasks.checkVnfClosedLoopDisabledFlag(execution);
- } catch (Exception e) {
- verify(aaiVnfResources, times(1)).checkVnfPserversLockedFlag(any(String.class));
- verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), eq("VNF PServers in Locked in A&AI"));
- }
- }
-
- @Test
- public void checkVnfPserversLockedFlagTestFalse() throws Exception {
- doReturn(false).when(aaiVnfResources).checkVnfPserversLockedFlag(isA(String.class));
- aaiFlagTasks.checkVnfPserversLockedFlag(execution);
- verify(exceptionUtil, times(0)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), any(int.class), any(String.class));
- }
-
- @Test
- public void checkVnfPserversLockedFlagExceptionTest() throws IOException {
-
- doThrow(new BpmnError("Unknown Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- doThrow(RuntimeException.class).when(aaiVnfResources).checkVnfClosedLoopDisabledFlag(isA(String.class));
- try {
- aaiFlagTasks.checkVnfPserversLockedFlag(execution);
- } catch (Exception e) {
- verify(aaiVnfResources, times(1)).checkVnfPserversLockedFlag(any(String.class));
- verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- }
- }
+ @InjectMocks
+ private AAIFlagTasks aaiFlagTasks = new AAIFlagTasks();
+
+ private GenericVnf genericVnf;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ genericVnf = setGenericVnf();
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ when(extractPojosForBB.extractByKey(any(), any())).thenReturn(genericVnf);
+ }
+
+ @Test
+ public void checkVnfInMaintTestTrue() throws Exception {
+ doThrow(new BpmnError("VNF is in maintenance in A&AI")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ doReturn(false).when(aaiVnfResources).checkInMaintFlag(isA(String.class));
+ doReturn(true).when(aaiVnfResources).checkInMaintFlag(isA(String.class));
+ try {
+ aaiFlagTasks.checkVnfInMaintFlag(execution);
+ } catch (Exception e) {
+ verify(aaiVnfResources, times(1)).checkInMaintFlag(any(String.class));
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000),
+ eq("VNF is in maintenance in A&AI"));
+ }
+ }
+
+ @Test
+ public void checkVnfInMaintTestFalse() throws Exception {
+ doReturn(false).when(aaiVnfResources).checkInMaintFlag(isA(String.class));
+ aaiFlagTasks.checkVnfInMaintFlag(execution);
+ verify(exceptionUtil, times(0)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class),
+ any(int.class), any(String.class));
+ }
+
+ @Test
+ public void checkVnfInMaintFlagExceptionTest() {
+
+ doThrow(new BpmnError("Unknown Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ doThrow(RuntimeException.class).when(aaiVnfResources).checkInMaintFlag(isA(String.class));
+ try {
+ aaiFlagTasks.checkVnfInMaintFlag(execution);
+ } catch (Exception e) {
+ verify(aaiVnfResources, times(1)).checkInMaintFlag(any(String.class));
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000),
+ any(String.class));
+ }
+
+ }
+
+ @Test
+ public void modifyVnfInMaintFlagTest() throws Exception {
+ doNothing().when(aaiVnfResources).updateObjectVnf(ArgumentMatchers.any(GenericVnf.class));
+ aaiFlagTasks.modifyVnfInMaintFlag(execution, true);
+ verify(aaiVnfResources, times(1)).updateObjectVnf(ArgumentMatchers.any(GenericVnf.class));
+ }
+
+ @Test
+ public void modifyVnfInMaintFlagExceptionTest() {
+
+ doThrow(new BpmnError("Unknown Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ doThrow(RuntimeException.class).when(aaiVnfResources).updateObjectVnf(isA(GenericVnf.class));
+ try {
+ aaiFlagTasks.modifyVnfInMaintFlag(execution, true);
+ } catch (Exception e) {
+ verify(aaiVnfResources, times(1)).checkInMaintFlag(any(String.class));
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000),
+ any(String.class));
+ }
+ }
+
+ @Test
+ public void checkVnfClosedLoopDisabledTestTrue() throws Exception {
+ doThrow(new BpmnError("VNF Closed Loop Disabled in A&AI")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ doReturn(false).when(aaiVnfResources).checkVnfClosedLoopDisabledFlag(isA(String.class));
+ try {
+ aaiFlagTasks.checkVnfClosedLoopDisabledFlag(execution);
+ } catch (Exception e) {
+ verify(aaiVnfResources, times(1)).checkVnfClosedLoopDisabledFlag(any(String.class));
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000),
+ eq("VNF Closed Loop Disabled in A&AI"));
+ }
+ }
+
+ @Test
+ public void checkVnfClosedLoopDisabledTestFalse() throws Exception {
+ doReturn(false).when(aaiVnfResources).checkVnfClosedLoopDisabledFlag(isA(String.class));
+ aaiFlagTasks.checkVnfClosedLoopDisabledFlag(execution);
+ verify(exceptionUtil, times(0)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class),
+ any(int.class), any(String.class));
+ }
+
+ @Test
+ public void checkVnfClosedLoopDisabledFlagExceptionTest() {
+
+ doThrow(new BpmnError("Unknown Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ doThrow(RuntimeException.class).when(aaiVnfResources).checkVnfClosedLoopDisabledFlag(isA(String.class));
+ try {
+ aaiFlagTasks.checkVnfClosedLoopDisabledFlag(execution);
+ } catch (Exception e) {
+ verify(aaiVnfResources, times(1)).checkVnfClosedLoopDisabledFlag(any(String.class));
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000),
+ any(String.class));
+ }
+ }
+
+ @Test
+ public void modifyVnfClosedLoopDisabledFlagTest() throws Exception {
+ doNothing().when(aaiVnfResources).updateObjectVnf(ArgumentMatchers.any(GenericVnf.class));
+ aaiFlagTasks.modifyVnfClosedLoopDisabledFlag(execution, true);
+ verify(aaiVnfResources, times(1)).updateObjectVnf(ArgumentMatchers.any(GenericVnf.class));
+ }
+
+ @Test
+ public void modifyVnfClosedLoopDisabledFlagExceptionTest() {
+
+ doThrow(new BpmnError("Unknown Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ doThrow(RuntimeException.class).when(aaiVnfResources).updateObjectVnf(isA(GenericVnf.class));
+ try {
+ aaiFlagTasks.modifyVnfClosedLoopDisabledFlag(execution, true);
+ } catch (Exception e) {
+ verify(aaiVnfResources, times(1)).checkVnfClosedLoopDisabledFlag(any(String.class));
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000),
+ any(String.class));
+ }
+ }
+
+
+ @Test
+ public void checkVnfPserversLockedFlagTestTrue() throws Exception {
+ doThrow(new BpmnError("VNF PServers in Locked in A&AI")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ doReturn(true).when(aaiVnfResources).checkVnfPserversLockedFlag(isA(String.class));
+ try {
+ aaiFlagTasks.checkVnfClosedLoopDisabledFlag(execution);
+ } catch (Exception e) {
+ verify(aaiVnfResources, times(1)).checkVnfPserversLockedFlag(any(String.class));
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000),
+ eq("VNF PServers in Locked in A&AI"));
+ }
+ }
+
+ @Test
+ public void checkVnfPserversLockedFlagTestFalse() throws Exception {
+ doReturn(false).when(aaiVnfResources).checkVnfPserversLockedFlag(isA(String.class));
+ aaiFlagTasks.checkVnfPserversLockedFlag(execution);
+ verify(exceptionUtil, times(0)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class),
+ any(int.class), any(String.class));
+ }
+
+ @Test
+ public void checkVnfPserversLockedFlagExceptionTest() throws IOException {
+
+ doThrow(new BpmnError("Unknown Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ doThrow(RuntimeException.class).when(aaiVnfResources).checkVnfClosedLoopDisabledFlag(isA(String.class));
+ try {
+ aaiFlagTasks.checkVnfPserversLockedFlag(execution);
+ } catch (Exception e) {
+ verify(aaiVnfResources, times(1)).checkVnfPserversLockedFlag(any(String.class));
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000),
+ any(String.class));
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/data/TestDataSetup.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/data/TestDataSetup.java
index 8bbb6c7f46..ff6426d351 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/data/TestDataSetup.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/data/TestDataSetup.java
@@ -21,14 +21,12 @@ package org.onap.so.bpmn.common.data;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.impl.pvm.runtime.ExecutionImpl;
import org.junit.Before;
@@ -75,540 +73,543 @@ import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB;
import org.onap.so.client.exception.BBObjectNotFoundException;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-public class TestDataSetup{
- private int collectionCounter;
- private int configurationCounter;
- private int customerCounter;
- private int genericVnfCounter;
- private int instanceGroupCounter;
- private int l3NetworkCounter;
- private int owningEntityCounter;
- private int pnfCounter;
- private int projectCounter;
- private int serviceInstanceCounter;
- private int serviceProxyCounter;
- private int serviceSubscriptionCounter;
- private int vfModuleCounter;
- private int volumeGroupCounter;
- private int vpnBindingCounter;
- private int vpnBondingLinkCounter;
-
- protected BuildingBlockExecution execution;
-
- protected GeneralBuildingBlock gBBInput;
-
- protected HashMap<ResourceKey, String> lookupKeyMap;
-
- protected ExtractPojosForBB extractPojosForBB = new ExtractPojosForBB();
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- protected DelegateExecution delegateExecution;
-
- @Before
- public void buildingBlockTestDataSetupBefore() {
- collectionCounter = 0;
- configurationCounter = 0;
- customerCounter = 0;
- genericVnfCounter = 0;
- instanceGroupCounter = 0;
- l3NetworkCounter = 0;
- owningEntityCounter = 0;
- pnfCounter = 0;
- projectCounter = 0;
- serviceInstanceCounter = 0;
- serviceProxyCounter = 0;
- serviceSubscriptionCounter = 0;
- vfModuleCounter = 0;
- volumeGroupCounter = 0;
- vpnBindingCounter = 0;
- vpnBondingLinkCounter = 0;
-
- execution = new DelegateExecutionImpl(new ExecutionImpl());
- execution.setVariable("testProcessKey", "testProcessKeyValue");
-
- gBBInput = new GeneralBuildingBlock();
- execution.setVariable("gBBInput", gBBInput);
-
- lookupKeyMap = new HashMap<ResourceKey, String>();
- execution.setVariable("lookupKeyMap", lookupKeyMap);
-
- ExecutionImpl mockExecutionImpl = mock(ExecutionImpl.class);
- doReturn("test").when(mockExecutionImpl).getProcessInstanceId();
-
- ExecutionImpl executionImpl = new ExecutionImpl();
- executionImpl.setProcessInstance(mockExecutionImpl);
-
- delegateExecution = (DelegateExecution) executionImpl;
- delegateExecution.setVariable("testProcessKey", "testProcessKeyValue");
- }
-
- public Map<String, String> buildUserInput() {
- Map<String, String> userInput = new HashMap<>();
- userInput.put("testUserInputKey", "testUserInputValue");
-
- return userInput;
- }
-
- public Map<String, String> setUserInput() {
- Map<String, String> userInput = buildUserInput();
-
- gBBInput.setUserInput(userInput);
-
- return userInput;
- }
-
- public RequestContext buildRequestContext() {
- RequestContext requestContext = new RequestContext();
- requestContext.setMsoRequestId(UUID.randomUUID().toString());
- requestContext.setProductFamilyId("testProductFamilyId");
- requestContext.setRequestorId("testRequestorId");
-
- requestContext.setUserParams(new HashMap<>());
-
- Map<String,Object> dataMap = new HashMap<>();
- dataMap.put("vpnId","testVpnId");
- dataMap.put("vpnRegion","testVpnRegion");
- dataMap.put("vpnRt","testVpnRt");
- dataMap.put("vpnName","vpnName");
+public class TestDataSetup {
+ private int collectionCounter;
+ private int configurationCounter;
+ private int customerCounter;
+ private int genericVnfCounter;
+ private int instanceGroupCounter;
+ private int l3NetworkCounter;
+ private int owningEntityCounter;
+ private int pnfCounter;
+ private int projectCounter;
+ private int serviceInstanceCounter;
+ private int serviceProxyCounter;
+ private int serviceSubscriptionCounter;
+ private int vfModuleCounter;
+ private int volumeGroupCounter;
+ private int vpnBindingCounter;
+ private int vpnBondingLinkCounter;
+
+ protected BuildingBlockExecution execution;
+
+ protected GeneralBuildingBlock gBBInput;
+
+ protected HashMap<ResourceKey, String> lookupKeyMap;
+
+ protected ExtractPojosForBB extractPojosForBB = new ExtractPojosForBB();
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ protected DelegateExecution delegateExecution;
+
+ @Before
+ public void buildingBlockTestDataSetupBefore() {
+ collectionCounter = 0;
+ configurationCounter = 0;
+ customerCounter = 0;
+ genericVnfCounter = 0;
+ instanceGroupCounter = 0;
+ l3NetworkCounter = 0;
+ owningEntityCounter = 0;
+ pnfCounter = 0;
+ projectCounter = 0;
+ serviceInstanceCounter = 0;
+ serviceProxyCounter = 0;
+ serviceSubscriptionCounter = 0;
+ vfModuleCounter = 0;
+ volumeGroupCounter = 0;
+ vpnBindingCounter = 0;
+ vpnBondingLinkCounter = 0;
+
+ execution = new DelegateExecutionImpl(new ExecutionImpl());
+ execution.setVariable("testProcessKey", "testProcessKeyValue");
+
+ gBBInput = new GeneralBuildingBlock();
+ execution.setVariable("gBBInput", gBBInput);
+
+ lookupKeyMap = new HashMap<ResourceKey, String>();
+ execution.setVariable("lookupKeyMap", lookupKeyMap);
+
+ ExecutionImpl mockExecutionImpl = mock(ExecutionImpl.class);
+ doReturn("test").when(mockExecutionImpl).getProcessInstanceId();
+
+ ExecutionImpl executionImpl = new ExecutionImpl();
+ executionImpl.setProcessInstance(mockExecutionImpl);
+
+ delegateExecution = (DelegateExecution) executionImpl;
+ delegateExecution.setVariable("testProcessKey", "testProcessKeyValue");
+ }
+
+ public Map<String, String> buildUserInput() {
+ Map<String, String> userInput = new HashMap<>();
+ userInput.put("testUserInputKey", "testUserInputValue");
+
+ return userInput;
+ }
+
+ public Map<String, String> setUserInput() {
+ Map<String, String> userInput = buildUserInput();
+
+ gBBInput.setUserInput(userInput);
+
+ return userInput;
+ }
+
+ public RequestContext buildRequestContext() {
+ RequestContext requestContext = new RequestContext();
+ requestContext.setMsoRequestId(UUID.randomUUID().toString());
+ requestContext.setProductFamilyId("testProductFamilyId");
+ requestContext.setRequestorId("testRequestorId");
+
+ requestContext.setUserParams(new HashMap<>());
+
+ Map<String, Object> dataMap = new HashMap<>();
+ dataMap.put("vpnId", "testVpnId");
+ dataMap.put("vpnRegion", "testVpnRegion");
+ dataMap.put("vpnRt", "testVpnRt");
+ dataMap.put("vpnName", "vpnName");
dataMap.put("vpnRegion", Arrays.asList(new String[] {"USA", "EMEA", "APAC"}));
- HashMap<String,Object> userParams = new HashMap<>();
- userParams.put("vpnData",dataMap);
+ HashMap<String, Object> userParams = new HashMap<>();
+ userParams.put("vpnData", dataMap);
+
+ List<Map<String, Object>> userParamsList = new ArrayList<>();
+ userParamsList.add(userParams);
- List<Map<String,Object>> userParamsList = new ArrayList<>();
- userParamsList.add(userParams);
+ RequestParameters requestParameters = new RequestParameters();
+ requestParameters.setUserParams(userParamsList);
+ requestContext.setRequestParameters(requestParameters);
- RequestParameters requestParameters = new RequestParameters();
- requestParameters.setUserParams(userParamsList);
- requestContext.setRequestParameters(requestParameters);
+ return requestContext;
+ }
- return requestContext;
- }
+ public RequestContext setRequestContext() {
+ RequestContext requestContext = buildRequestContext();
- public RequestContext setRequestContext() {
- RequestContext requestContext = buildRequestContext();
+ gBBInput.setRequestContext(requestContext);
- gBBInput.setRequestContext(requestContext);
+ return requestContext;
+ }
- return requestContext;
- }
+ public CloudRegion buildCloudRegion() {
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("testLcpCloudRegionId");
+ cloudRegion.setTenantId("testTenantId");
+ cloudRegion.setCloudOwner("testCloudOwner");
- public CloudRegion buildCloudRegion() {
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("testLcpCloudRegionId");
- cloudRegion.setTenantId("testTenantId");
- cloudRegion.setCloudOwner("testCloudOwner");
+ return cloudRegion;
+ }
- return cloudRegion;
- }
+ public CloudRegion setCloudRegion() {
+ CloudRegion cloudRegion = buildCloudRegion();
- public CloudRegion setCloudRegion() {
- CloudRegion cloudRegion = buildCloudRegion();
+ gBBInput.setCloudRegion(cloudRegion);
- gBBInput.setCloudRegion(cloudRegion);
+ return cloudRegion;
+ }
- return cloudRegion;
- }
+ public OrchestrationContext buildOrchestrationContext() {
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
- public OrchestrationContext buildOrchestrationContext() {
- OrchestrationContext orchestrationContext = new OrchestrationContext();
+ return orchestrationContext;
+ }
- return orchestrationContext;
- }
+ public OrchestrationContext setOrchestrationContext() {
+ OrchestrationContext orchestrationContext = buildOrchestrationContext();
- public OrchestrationContext setOrchestrationContext() {
- OrchestrationContext orchestrationContext = buildOrchestrationContext();
+ gBBInput.setOrchContext(orchestrationContext);
- gBBInput.setOrchContext(orchestrationContext);
+ return orchestrationContext;
+ }
- return orchestrationContext;
- }
+ public Collection buildCollection() {
+ collectionCounter++;
- public Collection buildCollection() {
- collectionCounter++;
+ Collection collection = new Collection();
+ collection.setId("testId" + collectionCounter);
+ collection.setInstanceGroup(buildInstanceGroup());
- Collection collection = new Collection();
- collection.setId("testId" + collectionCounter);
- collection.setInstanceGroup(buildInstanceGroup());
+ return collection;
+ }
- return collection;
- }
+ public Configuration buildConfiguration() {
+ configurationCounter++;
- public Configuration buildConfiguration() {
- configurationCounter++;
+ Configuration configuration = new Configuration();
+ configuration.setConfigurationId("testConfigurationId" + configurationCounter);
+ configuration.setConfigurationName("testConfigurationName" + configurationCounter);
- Configuration configuration = new Configuration();
- configuration.setConfigurationId("testConfigurationId" + configurationCounter);
- configuration.setConfigurationName("testConfigurationName" + configurationCounter);
+ ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
+ modelInfoConfiguration.setModelVersionId("testModelVersionId" + configurationCounter);
+ modelInfoConfiguration.setModelInvariantId("testModelInvariantId" + configurationCounter);
+ modelInfoConfiguration.setModelCustomizationId("testModelCustomizationId" + configurationCounter);
- ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
- modelInfoConfiguration.setModelVersionId("testModelVersionId" + configurationCounter);
- modelInfoConfiguration.setModelInvariantId("testModelInvariantId" + configurationCounter);
- modelInfoConfiguration.setModelCustomizationId("testModelCustomizationId" + configurationCounter);
+ configuration.setModelInfoConfiguration(modelInfoConfiguration);
- configuration.setModelInfoConfiguration(modelInfoConfiguration);
+ return configuration;
+ }
- return configuration;
- }
+ public OwningEntity buildOwningEntity() {
+ owningEntityCounter++;
- public OwningEntity buildOwningEntity() {
- owningEntityCounter++;
+ OwningEntity owningEntity = new OwningEntity();
+ owningEntity.setOwningEntityId("testOwningEntityId" + owningEntityCounter);
+ owningEntity.setOwningEntityName("testOwningEntityName" + owningEntityCounter);
- OwningEntity owningEntity = new OwningEntity();
- owningEntity.setOwningEntityId("testOwningEntityId" + owningEntityCounter);
- owningEntity.setOwningEntityName("testOwningEntityName" + owningEntityCounter);
+ return owningEntity;
+ }
- return owningEntity;
- }
+ public Project buildProject() {
+ projectCounter++;
- public Project buildProject() {
- projectCounter++;
+ Project project = new Project();
+ project.setProjectName("testProjectName1 , testProjectName2 , testProjectName3" + projectCounter);
- Project project = new Project();
- project.setProjectName("testProjectName1 , testProjectName2 , testProjectName3" + projectCounter);
+ return project;
+ }
- return project;
- }
+ public ServiceSubscription buildServiceSubscription() {
+ serviceSubscriptionCounter++;
- public ServiceSubscription buildServiceSubscription() {
- serviceSubscriptionCounter++;
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ serviceSubscription.setTempUbSubAccountId("testTempUbSubAccountId" + serviceSubscriptionCounter);
+ serviceSubscription.setServiceType("testServiceType" + serviceSubscriptionCounter);
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- serviceSubscription.setTempUbSubAccountId("testTempUbSubAccountId" + serviceSubscriptionCounter);
- serviceSubscription.setServiceType("testServiceType" + serviceSubscriptionCounter);
+ return serviceSubscription;
+ }
- return serviceSubscription;
- }
+ public Customer buildCustomer() {
+ customerCounter++;
- public Customer buildCustomer() {
- customerCounter++;
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("testGlobalCustomerId" + customerCounter);
+ customer.setSubscriberType("testSubscriberType" + customerCounter);
- Customer customer = new Customer();
- customer.setGlobalCustomerId("testGlobalCustomerId" + customerCounter);
- customer.setSubscriberType("testSubscriberType" + customerCounter);
+ customer.setServiceSubscription(buildServiceSubscription());
- customer.setServiceSubscription(buildServiceSubscription());
+ return customer;
+ }
- return customer;
- }
+ public ServiceInstance buildServiceInstance() {
+ serviceInstanceCounter++;
- public ServiceInstance buildServiceInstance() {
- serviceInstanceCounter++;
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("testServiceInstanceId" + serviceInstanceCounter);
+ serviceInstance.setServiceInstanceName("testServiceInstanceName" + serviceInstanceCounter);
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("testServiceInstanceId" + serviceInstanceCounter);
- serviceInstance.setServiceInstanceName("testServiceInstanceName" + serviceInstanceCounter);
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("testModelInvariantUUID" + serviceInstanceCounter);
+ modelInfoServiceInstance.setModelUuid("testModelUUID" + serviceInstanceCounter);
+ modelInfoServiceInstance.setModelVersion("testModelVersion" + serviceInstanceCounter);
+ modelInfoServiceInstance.setModelName("testModelName" + serviceInstanceCounter);
+ modelInfoServiceInstance.setServiceType("testServiceType" + serviceInstanceCounter);
+ modelInfoServiceInstance.setServiceRole("testServiceRole" + serviceInstanceCounter);
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("testModelInvariantUUID" + serviceInstanceCounter);
- modelInfoServiceInstance.setModelUuid("testModelUUID" + serviceInstanceCounter);
- modelInfoServiceInstance.setModelVersion("testModelVersion" + serviceInstanceCounter);
- modelInfoServiceInstance.setModelName("testModelName" + serviceInstanceCounter);
- modelInfoServiceInstance.setServiceType("testServiceType" + serviceInstanceCounter);
- modelInfoServiceInstance.setServiceRole("testServiceRole" + serviceInstanceCounter);
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+ serviceInstance.setProject(buildProject());
- serviceInstance.setProject(buildProject());
+ serviceInstance.setOwningEntity(buildOwningEntity());
- serviceInstance.setOwningEntity(buildOwningEntity());
+ serviceInstance.setCollection(buildCollection());
- serviceInstance.setCollection(buildCollection());
+ serviceInstance.getConfigurations().add(buildConfiguration());
- serviceInstance.getConfigurations().add(buildConfiguration());
+ return serviceInstance;
+ }
- return serviceInstance;
- }
+ public ServiceInstance setServiceInstance() {
+ ServiceInstance serviceInstance = buildServiceInstance();
- public ServiceInstance setServiceInstance() {
- ServiceInstance serviceInstance = buildServiceInstance();
+ if (gBBInput.getCustomer() == null) {
+ gBBInput.setCustomer(buildCustomer());
+ }
+ gBBInput.getCustomer().getServiceSubscription().getServiceInstances().add(serviceInstance);
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstance.getServiceInstanceId());
- if(gBBInput.getCustomer() == null) {
- gBBInput.setCustomer(buildCustomer());
- }
- gBBInput.getCustomer().getServiceSubscription().getServiceInstances().add(serviceInstance);
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstance.getServiceInstanceId());
+ return serviceInstance;
+ }
- return serviceInstance;
- }
+ public Customer setCustomer() {
+ if (gBBInput.getCustomer() != null)
+ return gBBInput.getCustomer();
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("testGlobalCustomerId");
+ customer.setSubscriberType("testSubscriberType");
- public Customer setCustomer() {
- if(gBBInput.getCustomer() != null) return gBBInput.getCustomer();
- Customer customer = new Customer();
- customer.setGlobalCustomerId("testGlobalCustomerId");
- customer.setSubscriberType("testSubscriberType");
+ customer.setServiceSubscription(buildServiceSubscription());
- customer.setServiceSubscription(buildServiceSubscription());
+ gBBInput.setCustomer(customer);
- gBBInput.setCustomer(customer);
+ return customer;
+ }
- return customer;
- }
+ public Collection setCollection() {
+ Collection collection = new Collection();
+ collection.setId("testId");
- public Collection setCollection() {
- Collection collection = new Collection();
- collection.setId("testId");
+ ServiceInstance serviceInstance = null;
- ServiceInstance serviceInstance = null;
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
+ serviceInstance.setCollection(collection);
- serviceInstance.setCollection(collection);
+ return collection;
+ }
- return collection;
- }
+ public InstanceGroup setInstanceGroup() {
+ InstanceGroup instanceGroup = new InstanceGroup();
+ instanceGroup.setId("testId");
+ instanceGroup.setInstanceGroupFunction("testInstanceGroupFunction");
- public InstanceGroup setInstanceGroup() {
- InstanceGroup instanceGroup = new InstanceGroup();
- instanceGroup.setId("testId");
- instanceGroup.setInstanceGroupFunction("testInstanceGroupFunction");
+ Collection collection = null;
- Collection collection = null;
+ try {
+ ServiceInstance serviceInstance =
+ extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ collection = serviceInstance.getCollection();
- try {
- ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- collection = serviceInstance.getCollection();
+ if (collection == null) {
+ collection = setCollection();
+ }
+ } catch (BBObjectNotFoundException e) {
+ collection = setCollection();
+ }
- if (collection == null) {
- collection = setCollection();
- }
- } catch(BBObjectNotFoundException e) {
- collection = setCollection();
- }
+ collection.setInstanceGroup(instanceGroup);
- collection.setInstanceGroup(instanceGroup);
-
- return instanceGroup;
- }
+ return instanceGroup;
+ }
- public InstanceGroup setInstanceGroupVnf() {
- InstanceGroup instanceGroup = buildInstanceGroup();
+ public InstanceGroup setInstanceGroupVnf() {
+ InstanceGroup instanceGroup = buildInstanceGroup();
- ServiceInstance serviceInstance = null;
+ ServiceInstance serviceInstance = null;
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
- serviceInstance.getInstanceGroups().add(instanceGroup);
- lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, instanceGroup.getId());
+ serviceInstance.getInstanceGroups().add(instanceGroup);
+ lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, instanceGroup.getId());
- return instanceGroup;
- }
+ return instanceGroup;
+ }
- public VpnBinding buildVpnBinding() {
- vpnBindingCounter++;
+ public VpnBinding buildVpnBinding() {
+ vpnBindingCounter++;
- VpnBinding vpnBinding = new VpnBinding();
- vpnBinding.setVpnId("testVpnId" + vpnBindingCounter);
- vpnBinding.setVpnName("testVpnName" + vpnBindingCounter);
- vpnBinding.setCustomerVpnId("testCustomerVpnId" + vpnBindingCounter);
+ VpnBinding vpnBinding = new VpnBinding();
+ vpnBinding.setVpnId("testVpnId" + vpnBindingCounter);
+ vpnBinding.setVpnName("testVpnName" + vpnBindingCounter);
+ vpnBinding.setCustomerVpnId("testCustomerVpnId" + vpnBindingCounter);
- return vpnBinding;
- }
+ return vpnBinding;
+ }
- public VpnBinding setVpnBinding() {
- VpnBinding vpnBinding = buildVpnBinding();
+ public VpnBinding setVpnBinding() {
+ VpnBinding vpnBinding = buildVpnBinding();
- Customer customer = gBBInput.getCustomer();
+ Customer customer = gBBInput.getCustomer();
- if(customer == null){
- customer = buildCustomer();
- }
+ if (customer == null) {
+ customer = buildCustomer();
+ }
- customer.getVpnBindings().add(vpnBinding);
- lookupKeyMap.put(ResourceKey.VPN_ID, vpnBinding.getVpnId());
+ customer.getVpnBindings().add(vpnBinding);
+ lookupKeyMap.put(ResourceKey.VPN_ID, vpnBinding.getVpnId());
- return vpnBinding;
- }
+ return vpnBinding;
+ }
- public InstanceGroup buildInstanceGroup() {
- instanceGroupCounter++;
+ public InstanceGroup buildInstanceGroup() {
+ instanceGroupCounter++;
- InstanceGroup instanceGroup = new InstanceGroup();
- instanceGroup.setId("testId" + instanceGroupCounter);
- instanceGroup.setInstanceGroupFunction("testInstanceGroupFunction" + instanceGroupCounter);
+ InstanceGroup instanceGroup = new InstanceGroup();
+ instanceGroup.setId("testId" + instanceGroupCounter);
+ instanceGroup.setInstanceGroupFunction("testInstanceGroupFunction" + instanceGroupCounter);
- return instanceGroup;
- }
+ return instanceGroup;
+ }
- public L3Network buildL3Network() {
- l3NetworkCounter++;
+ public L3Network buildL3Network() {
+ l3NetworkCounter++;
- L3Network network = new L3Network();
- network.setNetworkId("testNetworkId" + l3NetworkCounter);
- network.setNetworkName("testNetworkName" + l3NetworkCounter);
- network.setNetworkType("testNetworkType" + l3NetworkCounter);
+ L3Network network = new L3Network();
+ network.setNetworkId("testNetworkId" + l3NetworkCounter);
+ network.setNetworkName("testNetworkName" + l3NetworkCounter);
+ network.setNetworkType("testNetworkType" + l3NetworkCounter);
- ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
- modelInfoNetwork.setModelInvariantUUID("testModelInvariantUUID" + l3NetworkCounter);
- modelInfoNetwork.setModelName("testModelName" + l3NetworkCounter);
- modelInfoNetwork.setModelVersion("testModelVersion" + l3NetworkCounter);
- modelInfoNetwork.setModelUUID("testModelUUID" + l3NetworkCounter);
- network.setModelInfoNetwork(modelInfoNetwork);
+ ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
+ modelInfoNetwork.setModelInvariantUUID("testModelInvariantUUID" + l3NetworkCounter);
+ modelInfoNetwork.setModelName("testModelName" + l3NetworkCounter);
+ modelInfoNetwork.setModelVersion("testModelVersion" + l3NetworkCounter);
+ modelInfoNetwork.setModelUUID("testModelUUID" + l3NetworkCounter);
+ network.setModelInfoNetwork(modelInfoNetwork);
- return network;
- }
+ return network;
+ }
- public L3Network setL3Network() {
- L3Network network = buildL3Network();
+ public L3Network setL3Network() {
+ L3Network network = buildL3Network();
- ServiceInstance serviceInstance = null;
+ ServiceInstance serviceInstance = null;
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
- serviceInstance.getNetworks().add(network);
- lookupKeyMap.put(ResourceKey.NETWORK_ID, network.getNetworkId());
+ serviceInstance.getNetworks().add(network);
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, network.getNetworkId());
- return network;
- }
+ return network;
+ }
- public GenericVnf buildGenericVnf() {
- genericVnfCounter++;
+ public GenericVnf buildGenericVnf() {
+ genericVnfCounter++;
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId("testVnfId" + genericVnfCounter);
- genericVnf.setVnfName("testVnfName" + genericVnfCounter);
- genericVnf.setVnfType("testVnfType" + genericVnfCounter);
- genericVnf.setIpv4OamAddress("10.222.22.2");
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId("testVnfId" + genericVnfCounter);
+ genericVnf.setVnfName("testVnfName" + genericVnfCounter);
+ genericVnf.setVnfType("testVnfType" + genericVnfCounter);
+ genericVnf.setIpv4OamAddress("10.222.22.2");
- Platform platform = new Platform();
- platform.setPlatformName(" testPlatformName, testPlatformName2 , testPlatformName3 , testPlatformName4");
- genericVnf.setPlatform(platform);
+ Platform platform = new Platform();
+ platform.setPlatformName(" testPlatformName, testPlatformName2 , testPlatformName3 , testPlatformName4");
+ genericVnf.setPlatform(platform);
- LineOfBusiness lob = new LineOfBusiness();
- lob.setLineOfBusinessName(" testLineOfBusinessName , testLineOfBusinessName2, testLineOfBusinessName3, testLineOfBusinessName4");
- genericVnf.setLineOfBusiness(lob);
+ LineOfBusiness lob = new LineOfBusiness();
+ lob.setLineOfBusinessName(
+ " testLineOfBusinessName , testLineOfBusinessName2, testLineOfBusinessName3, testLineOfBusinessName4");
+ genericVnf.setLineOfBusiness(lob);
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelName("testModelName" + genericVnfCounter);
- modelInfoGenericVnf.setModelCustomizationUuid("testModelCustomizationUUID" + genericVnfCounter);
- modelInfoGenericVnf.setModelInvariantUuid("testModelInvariantUUID" + genericVnfCounter);
- modelInfoGenericVnf.setModelVersion("testModelVersion" + genericVnfCounter);
- modelInfoGenericVnf.setModelUuid("testModelUUID" + genericVnfCounter);
- modelInfoGenericVnf.setModelInstanceName("testInstanceName" + genericVnfCounter);
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelName("testModelName" + genericVnfCounter);
+ modelInfoGenericVnf.setModelCustomizationUuid("testModelCustomizationUUID" + genericVnfCounter);
+ modelInfoGenericVnf.setModelInvariantUuid("testModelInvariantUUID" + genericVnfCounter);
+ modelInfoGenericVnf.setModelVersion("testModelVersion" + genericVnfCounter);
+ modelInfoGenericVnf.setModelUuid("testModelUUID" + genericVnfCounter);
+ modelInfoGenericVnf.setModelInstanceName("testInstanceName" + genericVnfCounter);
- genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+ genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf);
- License license = new License();
- List<String> array = new ArrayList<String>();
- array.add("testPoolUuid");
- license.setEntitlementPoolUuids(array);
- genericVnf.setLicense(license);
+ License license = new License();
+ List<String> array = new ArrayList<String>();
+ array.add("testPoolUuid");
+ license.setEntitlementPoolUuids(array);
+ genericVnf.setLicense(license);
- return genericVnf;
- }
+ return genericVnf;
+ }
- public GenericVnf setGenericVnf() {
- GenericVnf genericVnf = buildGenericVnf();
+ public GenericVnf setGenericVnf() {
+ GenericVnf genericVnf = buildGenericVnf();
- ServiceInstance serviceInstance = null;
+ ServiceInstance serviceInstance = null;
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
- serviceInstance.getVnfs().add(genericVnf);
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, genericVnf.getVnfId());
+ serviceInstance.getVnfs().add(genericVnf);
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, genericVnf.getVnfId());
- return genericVnf;
- }
+ return genericVnf;
+ }
- public VfModule buildVfModule() {
- vfModuleCounter++;
+ public VfModule buildVfModule() {
+ vfModuleCounter++;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("testVfModuleId" + vfModuleCounter);
- vfModule.setVfModuleName("testVfModuleName" + vfModuleCounter);
- vfModule.setModuleIndex(0);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("testModelInvariantUUID" + vfModuleCounter);
- modelInfoVfModule.setModelVersion("testModelVersion" + vfModuleCounter);
- modelInfoVfModule.setModelUUID("testModelUUID" + vfModuleCounter);
- modelInfoVfModule.setModelName("testModelName" + vfModuleCounter);
- modelInfoVfModule.setModelCustomizationUUID("testModelCustomizationUUID" + vfModuleCounter);
- vfModule.setModelInfoVfModule(modelInfoVfModule);
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("testVfModuleId" + vfModuleCounter);
+ vfModule.setVfModuleName("testVfModuleName" + vfModuleCounter);
+ vfModule.setModuleIndex(0);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("testModelInvariantUUID" + vfModuleCounter);
+ modelInfoVfModule.setModelVersion("testModelVersion" + vfModuleCounter);
+ modelInfoVfModule.setModelUUID("testModelUUID" + vfModuleCounter);
+ modelInfoVfModule.setModelName("testModelName" + vfModuleCounter);
+ modelInfoVfModule.setModelCustomizationUUID("testModelCustomizationUUID" + vfModuleCounter);
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
- return vfModule;
- }
+ return vfModule;
+ }
- public VfModule setVfModule() {
- return setVfModule(true);
- }
-
- public VfModule setVfModule(boolean addToGenericVnf) {
- VfModule vfModule = buildVfModule();
+ public VfModule setVfModule() {
+ return setVfModule(true);
+ }
- GenericVnf genericVnf = null;
+ public VfModule setVfModule(boolean addToGenericVnf) {
+ VfModule vfModule = buildVfModule();
- try {
- genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- } catch(BBObjectNotFoundException e) {
- genericVnf = setGenericVnf();
- }
+ GenericVnf genericVnf = null;
- if (addToGenericVnf) {
- genericVnf.getVfModules().add(vfModule);
- }
- lookupKeyMap.put(ResourceKey.VF_MODULE_ID, vfModule.getVfModuleId());
+ try {
+ genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ } catch (BBObjectNotFoundException e) {
+ genericVnf = setGenericVnf();
+ }
- return vfModule;
- }
+ if (addToGenericVnf) {
+ genericVnf.getVfModules().add(vfModule);
+ }
+ lookupKeyMap.put(ResourceKey.VF_MODULE_ID, vfModule.getVfModuleId());
- public VolumeGroup buildVolumeGroup() {
- volumeGroupCounter++;
+ return vfModule;
+ }
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("testVolumeGroupId" + volumeGroupCounter);
- volumeGroup.setVolumeGroupName("testVolumeGroupName" + volumeGroupCounter);
- volumeGroup.setHeatStackId("testHeatStackId" + volumeGroupCounter);
+ public VolumeGroup buildVolumeGroup() {
+ volumeGroupCounter++;
- return volumeGroup;
- }
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("testVolumeGroupId" + volumeGroupCounter);
+ volumeGroup.setVolumeGroupName("testVolumeGroupName" + volumeGroupCounter);
+ volumeGroup.setHeatStackId("testHeatStackId" + volumeGroupCounter);
- public VolumeGroup setVolumeGroup() {
- VolumeGroup volumeGroup = buildVolumeGroup();
+ return volumeGroup;
+ }
- GenericVnf genericVnf = null;
+ public VolumeGroup setVolumeGroup() {
+ VolumeGroup volumeGroup = buildVolumeGroup();
- try {
- genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
- } catch(BBObjectNotFoundException e) {
- genericVnf = setGenericVnf();
- }
+ GenericVnf genericVnf = null;
- genericVnf.getVolumeGroups().add(volumeGroup);
- lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroup.getVolumeGroupId());
+ try {
+ genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+ } catch (BBObjectNotFoundException e) {
+ genericVnf = setGenericVnf();
+ }
- return volumeGroup;
- }
+ genericVnf.getVolumeGroups().add(volumeGroup);
+ lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroup.getVolumeGroupId());
- public Pnf buildPnf() {
- pnfCounter++;
+ return volumeGroup;
+ }
- Pnf pnf = new Pnf();
- pnf.setPnfId("testPnfId" + pnfCounter);
- pnf.setPnfName("testPnfName" + pnfCounter);
+ public Pnf buildPnf() {
+ pnfCounter++;
- return pnf;
- }
+ Pnf pnf = new Pnf();
+ pnf.setPnfId("testPnfId" + pnfCounter);
+ pnf.setPnfName("testPnfName" + pnfCounter);
- public ServiceProxy buildServiceProxy() {
- serviceProxyCounter++;
+ return pnf;
+ }
+
+ public ServiceProxy buildServiceProxy() {
+ serviceProxyCounter++;
ServiceProxy serviceProxy = new ServiceProxy();
serviceProxy.setServiceInstance(buildServiceInstance());
@@ -623,115 +624,115 @@ public class TestDataSetup{
serviceProxy.getServiceInstance().getPnfs().add(secondaryPnf);
return serviceProxy;
- }
+ }
- public VpnBondingLink buildVpnBondingLink() {
- vpnBondingLinkCounter++;
+ public VpnBondingLink buildVpnBondingLink() {
+ vpnBondingLinkCounter++;
- VpnBondingLink vpnBondingLink = new VpnBondingLink();
- vpnBondingLink.setVpnBondingLinkId("testVpnBondingLinkId" + vpnBondingLinkCounter);
+ VpnBondingLink vpnBondingLink = new VpnBondingLink();
+ vpnBondingLink.setVpnBondingLinkId("testVpnBondingLinkId" + vpnBondingLinkCounter);
- Configuration vnrConfiguration = buildConfiguration();
- vnrConfiguration.setNetwork(buildL3Network());
- vpnBondingLink.setVnrConfiguration(vnrConfiguration);
+ Configuration vnrConfiguration = buildConfiguration();
+ vnrConfiguration.setNetwork(buildL3Network());
+ vpnBondingLink.setVnrConfiguration(vnrConfiguration);
- vpnBondingLink.setVrfConfiguration(buildConfiguration());
+ vpnBondingLink.setVrfConfiguration(buildConfiguration());
vpnBondingLink.setInfrastructureServiceProxy(buildServiceProxy());
vpnBondingLink.setTransportServiceProxy(buildServiceProxy());
- return vpnBondingLink;
- }
-
- public VpnBondingLink setVpnBondingLink() {
- VpnBondingLink vpnBondingLink = buildVpnBondingLink();
-
- ServiceInstance serviceInstance = null;
+ return vpnBondingLink;
+ }
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
+ public VpnBondingLink setVpnBondingLink() {
+ VpnBondingLink vpnBondingLink = buildVpnBondingLink();
- serviceInstance.getVpnBondingLinks().add(vpnBondingLink);
- lookupKeyMap.put(ResourceKey.VPN_BONDING_LINK_ID, vpnBondingLink.getVpnBondingLinkId());
+ ServiceInstance serviceInstance = null;
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
- return vpnBondingLink;
- }
+ serviceInstance.getVpnBondingLinks().add(vpnBondingLink);
+ lookupKeyMap.put(ResourceKey.VPN_BONDING_LINK_ID, vpnBondingLink.getVpnBondingLinkId());
- public Customer setAvpnCustomer() {
- Customer customer = buildCustomer();
- gBBInput.setCustomer(customer);
+ return vpnBondingLink;
+ }
- return customer;
- }
+ public Customer setAvpnCustomer() {
+ Customer customer = buildCustomer();
- public ServiceProxy setServiceProxy(String uniqueIdentifier, String type) {
- ServiceProxy serviceProxy = new ServiceProxy();
- serviceProxy.setId("testProxyId" + uniqueIdentifier);
- serviceProxy.setType(type);
+ gBBInput.setCustomer(customer);
- ModelInfoServiceProxy modelInfo = new ModelInfoServiceProxy();
- modelInfo.setModelInvariantUuid("testProxyModelInvariantUuid" + uniqueIdentifier);
- modelInfo.setModelName("testProxyModelName" + uniqueIdentifier);
- modelInfo.setModelUuid("testProxyModelUuid" + uniqueIdentifier);
- modelInfo.setModelVersion("testProxyModelVersion" + uniqueIdentifier);
- modelInfo.setModelInstanceName("testProxyInstanceName" + uniqueIdentifier);
+ return customer;
+ }
- serviceProxy.setModelInfoServiceProxy(modelInfo);
-
- return serviceProxy;
- }
-
- public AllottedResource setAllottedResource(String uniqueIdentifier) {
- AllottedResource ar = new AllottedResource();
- ar.setId("testAllottedResourceId" + uniqueIdentifier);
-
- ModelInfoAllottedResource modelInfo = new ModelInfoAllottedResource();
- modelInfo.setModelInvariantUuid("testAllottedModelInvariantUuid" + uniqueIdentifier);
- modelInfo.setModelName("testAllottedModelName" + uniqueIdentifier);
- modelInfo.setModelUuid("testAllottedModelUuid" + uniqueIdentifier);
- modelInfo.setModelVersion("testAllottedModelVersion" + uniqueIdentifier);
- modelInfo.setModelInstanceName("testAllottedModelInstanceName" + uniqueIdentifier);
-
- ar.setModelInfoAllottedResource(modelInfo);
+ public ServiceProxy setServiceProxy(String uniqueIdentifier, String type) {
+ ServiceProxy serviceProxy = new ServiceProxy();
+ serviceProxy.setId("testProxyId" + uniqueIdentifier);
+ serviceProxy.setType(type);
- return ar;
- }
+ ModelInfoServiceProxy modelInfo = new ModelInfoServiceProxy();
+ modelInfo.setModelInvariantUuid("testProxyModelInvariantUuid" + uniqueIdentifier);
+ modelInfo.setModelName("testProxyModelName" + uniqueIdentifier);
+ modelInfo.setModelUuid("testProxyModelUuid" + uniqueIdentifier);
+ modelInfo.setModelVersion("testProxyModelVersion" + uniqueIdentifier);
+ modelInfo.setModelInstanceName("testProxyInstanceName" + uniqueIdentifier);
- public Configuration setConfiguration () {
- Configuration config = new Configuration();
- config.setConfigurationId("testConfigurationId");
- List<Configuration> configurations = new ArrayList<>();
- configurations.add(config);
- ServiceInstance serviceInstance = new ServiceInstance();
- try {
- serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
- } catch(BBObjectNotFoundException e) {
- serviceInstance = setServiceInstance();
- }
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "testConfigurationId");
- serviceInstance.setConfigurations(configurations);
- return config;
- }
+ serviceProxy.setModelInfoServiceProxy(modelInfo);
- public Subnet buildSubnet() {
+ return serviceProxy;
+ }
+
+ public AllottedResource setAllottedResource(String uniqueIdentifier) {
+ AllottedResource ar = new AllottedResource();
+ ar.setId("testAllottedResourceId" + uniqueIdentifier);
+
+ ModelInfoAllottedResource modelInfo = new ModelInfoAllottedResource();
+ modelInfo.setModelInvariantUuid("testAllottedModelInvariantUuid" + uniqueIdentifier);
+ modelInfo.setModelName("testAllottedModelName" + uniqueIdentifier);
+ modelInfo.setModelUuid("testAllottedModelUuid" + uniqueIdentifier);
+ modelInfo.setModelVersion("testAllottedModelVersion" + uniqueIdentifier);
+ modelInfo.setModelInstanceName("testAllottedModelInstanceName" + uniqueIdentifier);
+
+ ar.setModelInfoAllottedResource(modelInfo);
+
+ return ar;
+ }
+
+ public Configuration setConfiguration() {
+ Configuration config = new Configuration();
+ config.setConfigurationId("testConfigurationId");
+ List<Configuration> configurations = new ArrayList<>();
+ configurations.add(config);
+ ServiceInstance serviceInstance = new ServiceInstance();
+ try {
+ serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
+ } catch (BBObjectNotFoundException e) {
+ serviceInstance = setServiceInstance();
+ }
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "testConfigurationId");
+ serviceInstance.setConfigurations(configurations);
+ return config;
+ }
+
+ public Subnet buildSubnet() {
Subnet subnet = new Subnet();
subnet.setSubnetId("testSubnetId");
subnet.setOrchestrationStatus(OrchestrationStatus.PENDING);
subnet.setNeutronSubnetId("testNeutronSubnetId");
- return subnet;
- }
-
- public NetworkPolicy buildNetworkPolicy() {
- NetworkPolicy networkPolicy = new NetworkPolicy();
- networkPolicy.setNetworkPolicyId("testNetworkPolicyId");
- networkPolicy.setNetworkPolicyFqdn("testNetworkPolicyFqdn");
- networkPolicy.setHeatStackId("testHeatStackId");
- return networkPolicy;
- }
+ return subnet;
+ }
+
+ public NetworkPolicy buildNetworkPolicy() {
+ NetworkPolicy networkPolicy = new NetworkPolicy();
+ networkPolicy.setNetworkPolicyId("testNetworkPolicyId");
+ networkPolicy.setNetworkPolicyFqdn("testNetworkPolicyFqdn");
+ networkPolicy.setHeatStackId("testHeatStackId");
+ return networkPolicy;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java
index 5c1caccc2d..b054cc17bb 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java
@@ -30,12 +30,10 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.TreeSet;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Rule;
@@ -67,589 +65,631 @@ import org.onap.so.db.catalog.beans.OrchestrationStatus;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform;
-public class AAICreateTasksTest extends BaseTaskTest{
-
- @InjectMocks
- private AAICreateTasks aaiCreateTasks = new AAICreateTasks();
-
-
- private ServiceInstance serviceInstance;
- private L3Network network;
- private GenericVnf genericVnf;
- private VolumeGroup volumeGroup;
- private CloudRegion cloudRegion;
- private VfModule vfModule;
- private Customer customer;
- private Configuration configuration;
- private InstanceGroup instanceGroup;
-
- @Captor
- ArgumentCaptor<NetworkPolicy> networkPolicyCaptor;
-
- @Rule
- public final ExpectedException exception = ExpectedException.none();
-
- @Before
- public void before() throws BBObjectNotFoundException {
- customer = setCustomer();
- serviceInstance = setServiceInstance();
- network = setL3Network();
- genericVnf = setGenericVnf();
- volumeGroup = setVolumeGroup();
- cloudRegion = setCloudRegion();
- vfModule = setVfModule();
- configuration = setConfiguration();
- instanceGroup = setInstanceGroupVnf();
-
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.CONFIGURATION_ID))).thenReturn(configuration);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID))).thenReturn(instanceGroup);
-
-
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
-
- }
-
- @Test
- public void createServiceInstanceTest() throws Exception {
- doNothing().when(aaiServiceInstanceResources).createServiceInstance(serviceInstance, customer);
- aaiCreateTasks.createServiceInstance(execution);
- verify(aaiServiceInstanceResources, times(1)).createServiceInstance(serviceInstance, customer);
- }
-
- @Test
- public void createServiceInstanceExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "notfound");
- doThrow(RuntimeException.class).when(aaiServiceInstanceResources).createServiceInstance(serviceInstance, customer);
- aaiCreateTasks.createServiceInstance(execution);
- }
-
- @Test
- public void createVolumeGroupTest() throws Exception {
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
-
- doNothing().when(aaiVolumeGroupResources).createVolumeGroup(volumeGroup, cloudRegion);
- doNothing().when(aaiVolumeGroupResources).connectVolumeGroupToVnf(genericVnf, volumeGroup, cloudRegion);
-
- aaiCreateTasks.createVolumeGroup(execution);
-
- verify(aaiVolumeGroupResources, times(1)).createVolumeGroup(volumeGroup, cloudRegion);
- verify(aaiVolumeGroupResources, times(1)).connectVolumeGroupToVnf(genericVnf, volumeGroup, cloudRegion);
- verify(aaiVolumeGroupResources, times(1)).connectVolumeGroupToTenant(volumeGroup, cloudRegion);
- }
-
- @Test
- public void createVolumeGroupExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
-
- doThrow(RuntimeException.class).when(aaiVolumeGroupResources).createVolumeGroup(volumeGroup, cloudRegion);
-
- aaiCreateTasks.createVolumeGroup(execution);
- }
-
- @Test
- public void createProjectTest() throws Exception {
- doNothing().when(aaiServiceInstanceResources).createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
- aaiCreateTasks.createProject(execution);
- verify(aaiServiceInstanceResources, times(1)).createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
- }
-
- @Test
- public void createPlatformTest() throws Exception {
- doNothing().when(aaiVnfResources).createPlatformandConnectVnf(genericVnf.getPlatform(), genericVnf);
- aaiCreateTasks.createPlatform(execution);
- ArgumentCaptor<Platform> platformCaptor = ArgumentCaptor.forClass(Platform.class);
- ArgumentCaptor<GenericVnf> genericVnf = ArgumentCaptor.forClass(GenericVnf.class);
- Mockito.verify(aaiVnfResources,times(4)).createPlatformandConnectVnf(platformCaptor.capture(),genericVnf.capture());
-
- List<Platform> capturedPlatforms = platformCaptor.getAllValues();
- assertTrue(capturedPlatforms.stream().anyMatch(item -> "testPlatformName".equals(item.getPlatformName())));
- assertTrue(capturedPlatforms.stream().anyMatch(item -> "testPlatformName2".equals(item.getPlatformName())));
- assertTrue(capturedPlatforms.stream().anyMatch(item -> "testPlatformName3".equals(item.getPlatformName())));
- assertTrue(capturedPlatforms.stream().anyMatch(item -> "testPlatformName4".equals(item.getPlatformName())));
- }
-
- @Test
- public void createLineOfBusinessTest() throws Exception {
- doNothing().when(aaiVnfResources).createLineOfBusinessandConnectVnf(genericVnf.getLineOfBusiness(), genericVnf);
- aaiCreateTasks.createLineOfBusiness(execution);
-
- ArgumentCaptor<LineOfBusiness> lobCaptor = ArgumentCaptor.forClass(LineOfBusiness.class);
- ArgumentCaptor<GenericVnf> genericVnf = ArgumentCaptor.forClass(GenericVnf.class);
- Mockito.verify(aaiVnfResources,times(4)).createLineOfBusinessandConnectVnf(lobCaptor.capture(),genericVnf.capture());
-
- List<LineOfBusiness> capturedLOB = lobCaptor.getAllValues();
- assertTrue(capturedLOB.stream().anyMatch(item -> "testLineOfBusinessName".equals(item.getLineOfBusinessName())));
- assertTrue(capturedLOB.stream().anyMatch(item -> "testLineOfBusinessName2".equals(item.getLineOfBusinessName())));
- assertTrue(capturedLOB.stream().anyMatch(item -> "testLineOfBusinessName3".equals(item.getLineOfBusinessName())));
- assertTrue(capturedLOB.stream().anyMatch(item -> "testLineOfBusinessName4".equals(item.getLineOfBusinessName())));
-
- }
-
- @Test
- public void splitCDL_Test() throws Exception {
- List<String> strings = aaiCreateTasks.splitCDL("Test");
- assertEquals(strings.get(0),"Test");
-
- List<String> strings2 = aaiCreateTasks.splitCDL("");
- assertEquals(strings2.get(0),"");
- }
-
- @Test
- public void createProjectExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "notfound");
- doThrow(RuntimeException.class).when(aaiServiceInstanceResources).createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
- aaiCreateTasks.createProject(execution);
- }
-
- @Test
- public void createProjectNullProjectNameTest() throws Exception {
- serviceInstance.getProject().setProjectName(null);
- doNothing().when(aaiServiceInstanceResources).createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
- aaiCreateTasks.createProject(execution);
- verify(aaiServiceInstanceResources, times(0)).createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
- }
-
- @Test
- public void createProjectEmptyProjectNameTest() throws Exception {
- serviceInstance.getProject().setProjectName("");
- doNothing().when(aaiServiceInstanceResources).createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
- aaiCreateTasks.createProject(execution);
- verify(aaiServiceInstanceResources, times(0)).createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
- }
-
- @Test
- public void createOwningEntityTest() throws Exception {
- doReturn(true).when(aaiServiceInstanceResources).existsOwningEntity(serviceInstance.getOwningEntity());
- doNothing().when(aaiServiceInstanceResources).connectOwningEntityandServiceInstance(serviceInstance.getOwningEntity(),serviceInstance);
- aaiCreateTasks.createOwningEntity(execution);
- verify(aaiServiceInstanceResources, times(1)).existsOwningEntity(serviceInstance.getOwningEntity());
- verify(aaiServiceInstanceResources, times(1)).connectOwningEntityandServiceInstance(serviceInstance.getOwningEntity(), serviceInstance);
- }
-
- @Test
- public void createOwningEntityNotExistsOwningEntityTest() throws Exception {
- doReturn(false).when(aaiServiceInstanceResources).existsOwningEntity(serviceInstance.getOwningEntity());
- doNothing().when(aaiServiceInstanceResources).createOwningEntityandConnectServiceInstance(serviceInstance.getOwningEntity(),serviceInstance);
- aaiCreateTasks.createOwningEntity(execution);
- verify(aaiServiceInstanceResources, times(1)).existsOwningEntity(serviceInstance.getOwningEntity());
- verify(aaiServiceInstanceResources, times(1)).createOwningEntityandConnectServiceInstance(serviceInstance.getOwningEntity(), serviceInstance);
- }
-
- @Test
- public void createOwningEntityNullOwningEntityIdTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- serviceInstance.getOwningEntity().setOwningEntityId(null);
-
- aaiCreateTasks.createOwningEntity(execution);
- }
-
- @Test
- public void createOwningEntityEmptyOwningEntityIdTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- serviceInstance.getOwningEntity().setOwningEntityId("");
-
- aaiCreateTasks.createOwningEntity(execution);
- }
-
- @Test
- public void createOwningEntityNullOwningEntityNameTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- serviceInstance.getOwningEntity().setOwningEntityName(null);
-
- doReturn(false).when(aaiServiceInstanceResources).existsOwningEntity(serviceInstance.getOwningEntity());
-
- aaiCreateTasks.createOwningEntity(execution);
- }
-
- @Test
- public void createOwningEntityEmptyOwningEntityNameTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- serviceInstance.getOwningEntity().setOwningEntityName("");
-
- doReturn(false).when(aaiServiceInstanceResources).existsOwningEntity(serviceInstance.getOwningEntity());
-
- aaiCreateTasks.createOwningEntity(execution);
- }
-
- @Test
- public void createOwningEntityExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- doReturn(true).when(aaiServiceInstanceResources).existsOwningEntity(serviceInstance.getOwningEntity());
-
- doThrow(RuntimeException.class).when(aaiServiceInstanceResources).connectOwningEntityandServiceInstance(serviceInstance.getOwningEntity(), serviceInstance);
-
- aaiCreateTasks.createOwningEntity(execution);
- }
-
- @Test
- public void createVnfTest() throws Exception {
- doNothing().when(aaiVnfResources).createVnfandConnectServiceInstance(genericVnf, serviceInstance);
- aaiCreateTasks.createVnf(execution);
- verify(aaiVnfResources, times(1)).createVnfandConnectServiceInstance(genericVnf, serviceInstance);
- }
-
- @Test
- public void createVnfExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "notfound");
- doThrow(BBObjectNotFoundException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID));
- doNothing().when(aaiVnfResources).createVnfandConnectServiceInstance(genericVnf, serviceInstance);
- aaiCreateTasks.createVnf(execution);
- verify(aaiVnfResources, times(1)).createVnfandConnectServiceInstance(genericVnf, serviceInstance);
- }
-
-
- @Test
- public void createVfModuleTest() throws Exception {
-
- VfModule newVfModule = setVfModule(false);
- newVfModule.setModuleIndex(null);
- newVfModule.getModelInfoVfModule().setModelInvariantUUID("testModelInvariantUUID1");
- doNothing().when(aaiVfModuleResources).createVfModule(newVfModule, genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(newVfModule);
-
- assertEquals(null, newVfModule.getModuleIndex());
- aaiCreateTasks.createVfModule(execution);
- assertEquals(1, newVfModule.getModuleIndex().intValue());
- verify(aaiVfModuleResources, times(1)).createVfModule(newVfModule, genericVnf);
- }
-
- @Test
- public void createServiceSubscriptionTest(){
- doNothing().when(aaiServiceInstanceResources).createServiceSubscription(customer);
- aaiCreateTasks.createServiceSubscription(execution);
- verify(aaiServiceInstanceResources, times(1)).createServiceSubscription(customer);
- }
-
- @Test
- public void createServiceSubscriptionTestExceptionHandling(){
+public class AAICreateTasksTest extends BaseTaskTest {
+
+ @InjectMocks
+ private AAICreateTasks aaiCreateTasks = new AAICreateTasks();
+
+
+ private ServiceInstance serviceInstance;
+ private L3Network network;
+ private GenericVnf genericVnf;
+ private VolumeGroup volumeGroup;
+ private CloudRegion cloudRegion;
+ private VfModule vfModule;
+ private Customer customer;
+ private Configuration configuration;
+ private InstanceGroup instanceGroup;
+
+ @Captor
+ ArgumentCaptor<NetworkPolicy> networkPolicyCaptor;
+
+ @Rule
+ public final ExpectedException exception = ExpectedException.none();
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ customer = setCustomer();
+ serviceInstance = setServiceInstance();
+ network = setL3Network();
+ genericVnf = setGenericVnf();
+ volumeGroup = setVolumeGroup();
+ cloudRegion = setCloudRegion();
+ vfModule = setVfModule();
+ configuration = setConfiguration();
+ instanceGroup = setInstanceGroupVnf();
+
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID)))
+ .thenReturn(volumeGroup);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.CONFIGURATION_ID)))
+ .thenReturn(configuration);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID)))
+ .thenReturn(instanceGroup);
+
+
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+
+ }
+
+ @Test
+ public void createServiceInstanceTest() throws Exception {
+ doNothing().when(aaiServiceInstanceResources).createServiceInstance(serviceInstance, customer);
+ aaiCreateTasks.createServiceInstance(execution);
+ verify(aaiServiceInstanceResources, times(1)).createServiceInstance(serviceInstance, customer);
+ }
+
+ @Test
+ public void createServiceInstanceExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "notfound");
+ doThrow(RuntimeException.class).when(aaiServiceInstanceResources).createServiceInstance(serviceInstance,
+ customer);
+ aaiCreateTasks.createServiceInstance(execution);
+ }
+
+ @Test
+ public void createVolumeGroupTest() throws Exception {
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+
+ doNothing().when(aaiVolumeGroupResources).createVolumeGroup(volumeGroup, cloudRegion);
+ doNothing().when(aaiVolumeGroupResources).connectVolumeGroupToVnf(genericVnf, volumeGroup, cloudRegion);
+
+ aaiCreateTasks.createVolumeGroup(execution);
+
+ verify(aaiVolumeGroupResources, times(1)).createVolumeGroup(volumeGroup, cloudRegion);
+ verify(aaiVolumeGroupResources, times(1)).connectVolumeGroupToVnf(genericVnf, volumeGroup, cloudRegion);
+ verify(aaiVolumeGroupResources, times(1)).connectVolumeGroupToTenant(volumeGroup, cloudRegion);
+ }
+
+ @Test
+ public void createVolumeGroupExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+
+ doThrow(RuntimeException.class).when(aaiVolumeGroupResources).createVolumeGroup(volumeGroup, cloudRegion);
+
+ aaiCreateTasks.createVolumeGroup(execution);
+ }
+
+ @Test
+ public void createProjectTest() throws Exception {
+ doNothing().when(aaiServiceInstanceResources)
+ .createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
+ aaiCreateTasks.createProject(execution);
+ verify(aaiServiceInstanceResources, times(1))
+ .createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
+ }
+
+ @Test
+ public void createPlatformTest() throws Exception {
+ doNothing().when(aaiVnfResources).createPlatformandConnectVnf(genericVnf.getPlatform(), genericVnf);
+ aaiCreateTasks.createPlatform(execution);
+ ArgumentCaptor<Platform> platformCaptor = ArgumentCaptor.forClass(Platform.class);
+ ArgumentCaptor<GenericVnf> genericVnf = ArgumentCaptor.forClass(GenericVnf.class);
+ Mockito.verify(aaiVnfResources, times(4)).createPlatformandConnectVnf(platformCaptor.capture(),
+ genericVnf.capture());
+
+ List<Platform> capturedPlatforms = platformCaptor.getAllValues();
+ assertTrue(capturedPlatforms.stream().anyMatch(item -> "testPlatformName".equals(item.getPlatformName())));
+ assertTrue(capturedPlatforms.stream().anyMatch(item -> "testPlatformName2".equals(item.getPlatformName())));
+ assertTrue(capturedPlatforms.stream().anyMatch(item -> "testPlatformName3".equals(item.getPlatformName())));
+ assertTrue(capturedPlatforms.stream().anyMatch(item -> "testPlatformName4".equals(item.getPlatformName())));
+ }
+
+ @Test
+ public void createLineOfBusinessTest() throws Exception {
+ doNothing().when(aaiVnfResources).createLineOfBusinessandConnectVnf(genericVnf.getLineOfBusiness(), genericVnf);
+ aaiCreateTasks.createLineOfBusiness(execution);
+
+ ArgumentCaptor<LineOfBusiness> lobCaptor = ArgumentCaptor.forClass(LineOfBusiness.class);
+ ArgumentCaptor<GenericVnf> genericVnf = ArgumentCaptor.forClass(GenericVnf.class);
+ Mockito.verify(aaiVnfResources, times(4)).createLineOfBusinessandConnectVnf(lobCaptor.capture(),
+ genericVnf.capture());
+
+ List<LineOfBusiness> capturedLOB = lobCaptor.getAllValues();
+ assertTrue(
+ capturedLOB.stream().anyMatch(item -> "testLineOfBusinessName".equals(item.getLineOfBusinessName())));
+ assertTrue(
+ capturedLOB.stream().anyMatch(item -> "testLineOfBusinessName2".equals(item.getLineOfBusinessName())));
+ assertTrue(
+ capturedLOB.stream().anyMatch(item -> "testLineOfBusinessName3".equals(item.getLineOfBusinessName())));
+ assertTrue(
+ capturedLOB.stream().anyMatch(item -> "testLineOfBusinessName4".equals(item.getLineOfBusinessName())));
+
+ }
+
+ @Test
+ public void splitCDL_Test() throws Exception {
+ List<String> strings = aaiCreateTasks.splitCDL("Test");
+ assertEquals(strings.get(0), "Test");
+
+ List<String> strings2 = aaiCreateTasks.splitCDL("");
+ assertEquals(strings2.get(0), "");
+ }
+
+ @Test
+ public void createProjectExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "notfound");
+ doThrow(RuntimeException.class).when(aaiServiceInstanceResources)
+ .createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
+ aaiCreateTasks.createProject(execution);
+ }
+
+ @Test
+ public void createProjectNullProjectNameTest() throws Exception {
+ serviceInstance.getProject().setProjectName(null);
+ doNothing().when(aaiServiceInstanceResources)
+ .createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
+ aaiCreateTasks.createProject(execution);
+ verify(aaiServiceInstanceResources, times(0))
+ .createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
+ }
+
+ @Test
+ public void createProjectEmptyProjectNameTest() throws Exception {
+ serviceInstance.getProject().setProjectName("");
+ doNothing().when(aaiServiceInstanceResources)
+ .createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
+ aaiCreateTasks.createProject(execution);
+ verify(aaiServiceInstanceResources, times(0))
+ .createProjectandConnectServiceInstance(serviceInstance.getProject(), serviceInstance);
+ }
+
+ @Test
+ public void createOwningEntityTest() throws Exception {
+ doReturn(true).when(aaiServiceInstanceResources).existsOwningEntity(serviceInstance.getOwningEntity());
+ doNothing().when(aaiServiceInstanceResources)
+ .connectOwningEntityandServiceInstance(serviceInstance.getOwningEntity(), serviceInstance);
+ aaiCreateTasks.createOwningEntity(execution);
+ verify(aaiServiceInstanceResources, times(1)).existsOwningEntity(serviceInstance.getOwningEntity());
+ verify(aaiServiceInstanceResources, times(1))
+ .connectOwningEntityandServiceInstance(serviceInstance.getOwningEntity(), serviceInstance);
+ }
+
+ @Test
+ public void createOwningEntityNotExistsOwningEntityTest() throws Exception {
+ doReturn(false).when(aaiServiceInstanceResources).existsOwningEntity(serviceInstance.getOwningEntity());
+ doNothing().when(aaiServiceInstanceResources)
+ .createOwningEntityandConnectServiceInstance(serviceInstance.getOwningEntity(), serviceInstance);
+ aaiCreateTasks.createOwningEntity(execution);
+ verify(aaiServiceInstanceResources, times(1)).existsOwningEntity(serviceInstance.getOwningEntity());
+ verify(aaiServiceInstanceResources, times(1))
+ .createOwningEntityandConnectServiceInstance(serviceInstance.getOwningEntity(), serviceInstance);
+ }
+
+ @Test
+ public void createOwningEntityNullOwningEntityIdTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ serviceInstance.getOwningEntity().setOwningEntityId(null);
+
+ aaiCreateTasks.createOwningEntity(execution);
+ }
+
+ @Test
+ public void createOwningEntityEmptyOwningEntityIdTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ serviceInstance.getOwningEntity().setOwningEntityId("");
+
+ aaiCreateTasks.createOwningEntity(execution);
+ }
+
+ @Test
+ public void createOwningEntityNullOwningEntityNameTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ serviceInstance.getOwningEntity().setOwningEntityName(null);
+
+ doReturn(false).when(aaiServiceInstanceResources).existsOwningEntity(serviceInstance.getOwningEntity());
+
+ aaiCreateTasks.createOwningEntity(execution);
+ }
+
+ @Test
+ public void createOwningEntityEmptyOwningEntityNameTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ serviceInstance.getOwningEntity().setOwningEntityName("");
+
+ doReturn(false).when(aaiServiceInstanceResources).existsOwningEntity(serviceInstance.getOwningEntity());
+
+ aaiCreateTasks.createOwningEntity(execution);
+ }
+
+ @Test
+ public void createOwningEntityExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ doReturn(true).when(aaiServiceInstanceResources).existsOwningEntity(serviceInstance.getOwningEntity());
+
+ doThrow(RuntimeException.class).when(aaiServiceInstanceResources)
+ .connectOwningEntityandServiceInstance(serviceInstance.getOwningEntity(), serviceInstance);
+
+ aaiCreateTasks.createOwningEntity(execution);
+ }
+
+ @Test
+ public void createVnfTest() throws Exception {
+ doNothing().when(aaiVnfResources).createVnfandConnectServiceInstance(genericVnf, serviceInstance);
+ aaiCreateTasks.createVnf(execution);
+ verify(aaiVnfResources, times(1)).createVnfandConnectServiceInstance(genericVnf, serviceInstance);
+ }
+
+ @Test
+ public void createVnfExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "notfound");
+ doThrow(BBObjectNotFoundException.class).when(extractPojosForBB).extractByKey(any(),
+ ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID));
+ doNothing().when(aaiVnfResources).createVnfandConnectServiceInstance(genericVnf, serviceInstance);
+ aaiCreateTasks.createVnf(execution);
+ verify(aaiVnfResources, times(1)).createVnfandConnectServiceInstance(genericVnf, serviceInstance);
+ }
+
+
+ @Test
+ public void createVfModuleTest() throws Exception {
+
+ VfModule newVfModule = setVfModule(false);
+ newVfModule.setModuleIndex(null);
+ newVfModule.getModelInfoVfModule().setModelInvariantUUID("testModelInvariantUUID1");
+ doNothing().when(aaiVfModuleResources).createVfModule(newVfModule, genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID)))
+ .thenReturn(newVfModule);
+
+ assertEquals(null, newVfModule.getModuleIndex());
+ aaiCreateTasks.createVfModule(execution);
+ assertEquals(1, newVfModule.getModuleIndex().intValue());
+ verify(aaiVfModuleResources, times(1)).createVfModule(newVfModule, genericVnf);
+ }
+
+ @Test
+ public void createServiceSubscriptionTest() {
+ doNothing().when(aaiServiceInstanceResources).createServiceSubscription(customer);
+ aaiCreateTasks.createServiceSubscription(execution);
+ verify(aaiServiceInstanceResources, times(1)).createServiceSubscription(customer);
+ }
+
+ @Test
+ public void createServiceSubscriptionTestExceptionHandling() {
expectedException.expect(BpmnError.class);
doThrow(RuntimeException.class).when(aaiServiceInstanceResources).createServiceSubscription(customer);
aaiCreateTasks.createServiceSubscription(execution);
}
@Test
- public void createServiceSubscriptionTestCustomerIsNull(){
+ public void createServiceSubscriptionTestCustomerIsNull() {
expectedException.expect(BpmnError.class);
gBBInput.setCustomer(null);
aaiCreateTasks.createServiceSubscription(execution);
}
- @Test
- public void createVfModuleExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- doThrow(RuntimeException.class).when(aaiVfModuleResources).createVfModule(vfModule, genericVnf);
- aaiCreateTasks.createVfModule(execution);
- }
-
- @Test
- public void connectVfModuleToVolumeGroupTest() throws Exception {
- doNothing().when(aaiVfModuleResources).connectVfModuleToVolumeGroup(genericVnf, vfModule, volumeGroup, cloudRegion);
- aaiCreateTasks.connectVfModuleToVolumeGroup(execution);
- verify(aaiVfModuleResources, times(1)).connectVfModuleToVolumeGroup(genericVnf, vfModule, volumeGroup, cloudRegion);
- }
-
- @Test
- public void createNetworkTest() throws Exception {
- network.getModelInfoNetwork().setNeutronNetworkType("PROVIDER");
-
- doNothing().when(aaiNetworkResources).createNetworkConnectToServiceInstance(network,serviceInstance);
- aaiCreateTasks.createNetwork(execution);
- verify(aaiNetworkResources, times(1)).createNetworkConnectToServiceInstance(network, serviceInstance);
- }
-
- @Test
- public void createNetworkExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- lookupKeyMap.put(ResourceKey.NETWORK_ID, "notfound");
- doThrow(RuntimeException.class).when(aaiNetworkResources).createNetworkConnectToServiceInstance(network,serviceInstance);
- aaiCreateTasks.createNetwork(execution);
- }
-
- @Test
- public void createCustomerTest() throws Exception {
- doNothing().when(aaiVpnBindingResources).createCustomer(customer);
-
- aaiCreateTasks.createCustomer(execution);
-
- verify(aaiVpnBindingResources, times(1)).createCustomer(customer);
- }
-
- @Test
- public void createCustomerExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- doThrow(RuntimeException.class).when(aaiVpnBindingResources).createCustomer(customer);
-
- aaiCreateTasks.createCustomer(execution);
- }
-
- @Test
- public void createNetworkCollectionTest() throws Exception {
- doNothing().when(aaiNetworkResources).createNetworkCollection(serviceInstance.getCollection());
- execution.setVariable("networkCollectionName", "testNetworkCollectionName");
- aaiCreateTasks.createNetworkCollection(execution);
- verify(aaiNetworkResources, times(1)).createNetworkCollection(serviceInstance.getCollection());
- }
-
- @Test
- public void createNetworkCollectionInstanceGroupTest() throws Exception {
- doNothing().when(aaiNetworkResources).createNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup());
- aaiCreateTasks.createNetworkCollectionInstanceGroup(execution);
- verify(aaiNetworkResources, times(1)).createNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup());
- }
-
- @Test
- public void connectNetworkToNetworkCollectionServiceInstanceTest() throws Exception {
- doNothing().when(aaiNetworkResources).connectNetworkToNetworkCollectionServiceInstance(network, serviceInstance);
- aaiCreateTasks.connectNetworkToNetworkCollectionServiceInstance(execution);
- verify(aaiNetworkResources, times(1)).connectNetworkToNetworkCollectionServiceInstance(network, serviceInstance);
- }
-
- @Test
- public void connectNetworkToNetworkCollectionInstanceGroupTest() throws Exception {
- doNothing().when(aaiNetworkResources).connectNetworkToNetworkCollectionInstanceGroup(network, serviceInstance.getCollection().getInstanceGroup());
- aaiCreateTasks.connectNetworkToNetworkCollectionInstanceGroup(execution);
- verify(aaiNetworkResources, times(1)).connectNetworkToNetworkCollectionInstanceGroup(network, serviceInstance.getCollection().getInstanceGroup());
- }
-
- @Test
- public void connectNetworkToNullNetworkCollectionInstanceGroupTest() throws Exception {
- //reset test data to have no network collection instance group
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("testServiceInstanceId");
- L3Network network = new L3Network();
- network.setNetworkId("testNetworkId");
- serviceInstance.getNetworks().add(network);
- lookupKeyMap.put(ResourceKey.NETWORK_ID, network.getNetworkId());
- gBBInput.setServiceInstance(serviceInstance);
- lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstance.getServiceInstanceId());
-
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(serviceInstance);
- //verify connection call was not executednetwork
- exception.expect(BpmnError.class);
- aaiCreateTasks.connectNetworkToNetworkCollectionInstanceGroup(execution);
- verify(aaiNetworkResources, never()).connectNetworkToNetworkCollectionInstanceGroup(network, null);
- }
-
- @Test
- public void connectNetworkToCloudRegionTest() throws Exception {
- gBBInput = execution.getGeneralBuildingBlock();
- doNothing().when(aaiNetworkResources).connectNetworkToCloudRegion(network, gBBInput.getCloudRegion());
- aaiCreateTasks.connectNetworkToCloudRegion(execution);
- verify(aaiNetworkResources, times(1)).connectNetworkToCloudRegion(network, gBBInput.getCloudRegion());
- }
-
- @Test
- public void connectNetworkToTenantTest() throws Exception {
- gBBInput = execution.getGeneralBuildingBlock();
- doNothing().when(aaiNetworkResources).connectNetworkToTenant(network, gBBInput.getCloudRegion());
- aaiCreateTasks.connectNetworkToTenant(execution);
- verify(aaiNetworkResources, times(1)).connectNetworkToTenant(network, gBBInput.getCloudRegion());
- }
-
- @Test
- public void createConfigurationTest() throws Exception {
- gBBInput = execution.getGeneralBuildingBlock();
- doNothing().when(aaiConfigurationResources).createConfiguration(configuration);
- aaiCreateTasks.createConfiguration(execution);
- verify(aaiConfigurationResources, times(1)).createConfiguration(configuration);
- }
-
- @Test
- public void connectVnfToCloudRegionTest() throws Exception {
- gBBInput = execution.getGeneralBuildingBlock();
- doNothing().when(aaiVnfResources).connectVnfToCloudRegion(genericVnf, gBBInput.getCloudRegion());
- aaiCreateTasks.connectVnfToCloudRegion(execution);
- verify(aaiVnfResources, times(1)).connectVnfToCloudRegion(genericVnf, gBBInput.getCloudRegion());
- }
-
- @Test
- public void connectNoneToVnfToCloudRegionTest() throws Exception {
- String[] arr = new String[1];
- arr[0] = "test25Region2";
- doReturn(arr).when(env).getProperty("mso.bpmn.cloudRegionIdsToSkipAddingVnfEdgesTo", String[].class);
- gBBInput = execution.getGeneralBuildingBlock();
- gBBInput.getCloudRegion().setLcpCloudRegionId("test25Region2");
- doNothing().when(aaiVnfResources).connectVnfToCloudRegion(genericVnf, gBBInput.getCloudRegion());
- aaiCreateTasks.connectVnfToCloudRegion(execution);
- verify(aaiVnfResources, times(0)).connectVnfToCloudRegion(genericVnf, gBBInput.getCloudRegion());
- }
-
- @Test
- public void connectVnfTenantTest() throws Exception {
- gBBInput = execution.getGeneralBuildingBlock();
- doNothing().when(aaiVnfResources).connectVnfToTenant(genericVnf, gBBInput.getCloudRegion());
- aaiCreateTasks.connectVnfToTenant(execution);
- verify(aaiVnfResources, times(1)).connectVnfToTenant(genericVnf, gBBInput.getCloudRegion());
- }
-
- @Test
- public void createInstanceGroupVnfTest() throws Exception {
- doNothing().when(aaiInstanceGroupResources).createInstanceGroupandConnectServiceInstance(instanceGroup, serviceInstance);
- aaiCreateTasks.createInstanceGroupVnf(execution);
- verify(aaiInstanceGroupResources, times(1)).createInstanceGroupandConnectServiceInstance(instanceGroup, serviceInstance);
- }
-
- @Test
- public void createInstanceGroupVnfExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(aaiInstanceGroupResources).createInstanceGroupandConnectServiceInstance(instanceGroup, serviceInstance);
- aaiCreateTasks.createInstanceGroupVnf(execution);
- }
-
- @Test
- public void createNetworkPolicyNeedToCreateAllTest() throws Exception {
- execution.setVariable("heatStackId", "testHeatStackId");
- execution.setVariable("contrailNetworkPolicyFqdnList", "ABC123,ED456");
- Optional<NetworkPolicy> networkPolicy = Optional.empty();
- doReturn(networkPolicy).when(aaiNetworkResources).getNetworkPolicy(any(AAIResourceUri.class));
- doNothing().when(aaiNetworkResources).createNetworkPolicy(any(NetworkPolicy.class));
- aaiCreateTasks.createNetworkPolicies(execution);
- verify(aaiNetworkResources, times(2)).createNetworkPolicy(networkPolicyCaptor.capture());
- assertEquals("ABC123", networkPolicyCaptor.getAllValues().get(0).getNetworkPolicyFqdn());
- assertEquals("ED456", networkPolicyCaptor.getAllValues().get(1).getNetworkPolicyFqdn());
- assertEquals("testHeatStackId", networkPolicyCaptor.getAllValues().get(0).getHeatStackId());
- assertEquals("testHeatStackId", networkPolicyCaptor.getAllValues().get(1).getHeatStackId());
- }
-
- @Test
- public void createNetworkPolicyNeedToCreateNoneTest() throws Exception {
- execution.setVariable("heatStackId", "testHeatStackId");
- execution.setVariable("contrailNetworkPolicyFqdnList", "ABC123");
- NetworkPolicy networkPolicy = new NetworkPolicy();
- doReturn(Optional.of(networkPolicy)).when(aaiNetworkResources).getNetworkPolicy(any(AAIResourceUri.class));
- doNothing().when(aaiNetworkResources).createNetworkPolicy(any(NetworkPolicy.class));
- aaiCreateTasks.createNetworkPolicies(execution);
- verify(aaiNetworkResources, times(0)).createNetworkPolicy(any(NetworkPolicy.class));
- }
-
- @Test
- public void createNetworkPolicyNoNetworkPoliciesTest() throws Exception {
- execution.setVariable("heatStackId", "testHeatStackId");
- aaiCreateTasks.createNetworkPolicies(execution);
- verify(aaiNetworkResources, times(0)).createNetworkPolicy(any(NetworkPolicy.class));
- }
-
- @Test
- public void createVfModuleGetLowestIndexTest() throws Exception {
- GenericVnf vnf = new GenericVnf();
- ModelInfoGenericVnf vnfInfo = new ModelInfoGenericVnf();
- vnf.setModelInfoGenericVnf(vnfInfo);
- vnfInfo.setModelInvariantUuid("my-uuid");
-
- ModelInfoVfModule infoA = new ModelInfoVfModule();
- infoA.setIsBaseBoolean(false);
- infoA.setModelInvariantUUID("A");
-
- ModelInfoVfModule infoB = new ModelInfoVfModule();
- infoB.setIsBaseBoolean(false);
- infoB.setModelInvariantUUID("B");
-
- ModelInfoVfModule infoC = new ModelInfoVfModule();
- infoC.setIsBaseBoolean(false);
- infoC.setModelInvariantUUID("C");
-
- VfModule newVfModuleA = new VfModule();
- newVfModuleA.setVfModuleId("a");
- VfModule newVfModuleB = new VfModule();
- newVfModuleB.setVfModuleId("b");
- VfModule newVfModuleC = new VfModule();
- newVfModuleC.setVfModuleId("c");
-
- VfModule vfModule = new VfModule();
- vnf.getVfModules().add(vfModule);
- vfModule.setVfModuleId("1");
-
- VfModule vfModule2 = new VfModule();
- vnf.getVfModules().add(vfModule2);
- vfModule2.setVfModuleId("2");
-
- VfModule vfModule3 = new VfModule();
- vnf.getVfModules().add(vfModule3);
- vfModule3.setVfModuleId("3");
-
- VfModule vfModule4 = new VfModule();
- vnf.getVfModules().add(vfModule4);
- vfModule4.setVfModuleId("4");
-
- VfModule vfModule5 = new VfModule();
- vnf.getVfModules().add(vfModule5);
- vfModule5.setVfModuleId("5");
-
- //modules are included in the vnf already
- vnf.getVfModules().add(newVfModuleA);
- vnf.getVfModules().add(newVfModuleB);
- vnf.getVfModules().add(newVfModuleC);
-
- //A
- newVfModuleA.setModelInfoVfModule(infoA);
- vfModule.setModelInfoVfModule(infoA);
- vfModule2.setModelInfoVfModule(infoA);
- vfModule3.setModelInfoVfModule(infoA);
-
- //B
-
- newVfModuleB.setModelInfoVfModule(infoB);
- vfModule4.setModelInfoVfModule(infoB);
- vfModule5.setModelInfoVfModule(infoB);
-
- //C
- newVfModuleC.setModelInfoVfModule(infoC);
-
-
- //A
- vfModule.setModuleIndex(2);
- vfModule2.setModuleIndex(0);
- vfModule3.setModuleIndex(3);
-
- //B
- vfModule4.setModuleIndex(null);
- vfModule5.setModuleIndex(1);
-
- assertEquals(1, aaiCreateTasks.getLowestUnusedVfModuleIndexFromAAIVnfResponse(vnf, newVfModuleA));
-
- assertEquals(2, aaiCreateTasks.getLowestUnusedVfModuleIndexFromAAIVnfResponse(vnf, newVfModuleB));
-
- assertEquals(0, aaiCreateTasks.getLowestUnusedVfModuleIndexFromAAIVnfResponse(vnf, newVfModuleC));
-
- }
-
- @Test
- public void calculateUnusedIndexTest() {
-
- TreeSet<Integer> a = new TreeSet<>(Arrays.asList(0,1,3));
- TreeSet<Integer> b = new TreeSet<>(Arrays.asList(0,1,8));
- TreeSet<Integer> c = new TreeSet<>(Arrays.asList(0,2,4));
- assertEquals(2, aaiCreateTasks.calculateUnusedIndex(a, 0));
- assertEquals(5, aaiCreateTasks.calculateUnusedIndex(a, 2));
-
- assertEquals(4, aaiCreateTasks.calculateUnusedIndex(b, 2));
- assertEquals(3, aaiCreateTasks.calculateUnusedIndex(b, 1));
-
- assertEquals(5, aaiCreateTasks.calculateUnusedIndex(c, 2));
- assertEquals(9, aaiCreateTasks.calculateUnusedIndex(c, 6));
- assertEquals(1, aaiCreateTasks.calculateUnusedIndex(c, 0));
-
- }
+ @Test
+ public void createVfModuleExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ doThrow(RuntimeException.class).when(aaiVfModuleResources).createVfModule(vfModule, genericVnf);
+ aaiCreateTasks.createVfModule(execution);
+ }
+
+ @Test
+ public void connectVfModuleToVolumeGroupTest() throws Exception {
+ doNothing().when(aaiVfModuleResources).connectVfModuleToVolumeGroup(genericVnf, vfModule, volumeGroup,
+ cloudRegion);
+ aaiCreateTasks.connectVfModuleToVolumeGroup(execution);
+ verify(aaiVfModuleResources, times(1)).connectVfModuleToVolumeGroup(genericVnf, vfModule, volumeGroup,
+ cloudRegion);
+ }
+
+ @Test
+ public void createNetworkTest() throws Exception {
+ network.getModelInfoNetwork().setNeutronNetworkType("PROVIDER");
+
+ doNothing().when(aaiNetworkResources).createNetworkConnectToServiceInstance(network, serviceInstance);
+ aaiCreateTasks.createNetwork(execution);
+ verify(aaiNetworkResources, times(1)).createNetworkConnectToServiceInstance(network, serviceInstance);
+ }
+
+ @Test
+ public void createNetworkExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, "notfound");
+ doThrow(RuntimeException.class).when(aaiNetworkResources).createNetworkConnectToServiceInstance(network,
+ serviceInstance);
+ aaiCreateTasks.createNetwork(execution);
+ }
+
+ @Test
+ public void createCustomerTest() throws Exception {
+ doNothing().when(aaiVpnBindingResources).createCustomer(customer);
+
+ aaiCreateTasks.createCustomer(execution);
+
+ verify(aaiVpnBindingResources, times(1)).createCustomer(customer);
+ }
+
+ @Test
+ public void createCustomerExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ doThrow(RuntimeException.class).when(aaiVpnBindingResources).createCustomer(customer);
+
+ aaiCreateTasks.createCustomer(execution);
+ }
+
+ @Test
+ public void createNetworkCollectionTest() throws Exception {
+ doNothing().when(aaiNetworkResources).createNetworkCollection(serviceInstance.getCollection());
+ execution.setVariable("networkCollectionName", "testNetworkCollectionName");
+ aaiCreateTasks.createNetworkCollection(execution);
+ verify(aaiNetworkResources, times(1)).createNetworkCollection(serviceInstance.getCollection());
+ }
+
+ @Test
+ public void createNetworkCollectionInstanceGroupTest() throws Exception {
+ doNothing().when(aaiNetworkResources)
+ .createNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup());
+ aaiCreateTasks.createNetworkCollectionInstanceGroup(execution);
+ verify(aaiNetworkResources, times(1))
+ .createNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup());
+ }
+
+ @Test
+ public void connectNetworkToNetworkCollectionServiceInstanceTest() throws Exception {
+ doNothing().when(aaiNetworkResources).connectNetworkToNetworkCollectionServiceInstance(network,
+ serviceInstance);
+ aaiCreateTasks.connectNetworkToNetworkCollectionServiceInstance(execution);
+ verify(aaiNetworkResources, times(1)).connectNetworkToNetworkCollectionServiceInstance(network,
+ serviceInstance);
+ }
+
+ @Test
+ public void connectNetworkToNetworkCollectionInstanceGroupTest() throws Exception {
+ doNothing().when(aaiNetworkResources).connectNetworkToNetworkCollectionInstanceGroup(network,
+ serviceInstance.getCollection().getInstanceGroup());
+ aaiCreateTasks.connectNetworkToNetworkCollectionInstanceGroup(execution);
+ verify(aaiNetworkResources, times(1)).connectNetworkToNetworkCollectionInstanceGroup(network,
+ serviceInstance.getCollection().getInstanceGroup());
+ }
+
+ @Test
+ public void connectNetworkToNullNetworkCollectionInstanceGroupTest() throws Exception {
+ // reset test data to have no network collection instance group
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("testServiceInstanceId");
+ L3Network network = new L3Network();
+ network.setNetworkId("testNetworkId");
+ serviceInstance.getNetworks().add(network);
+ lookupKeyMap.put(ResourceKey.NETWORK_ID, network.getNetworkId());
+ gBBInput.setServiceInstance(serviceInstance);
+ lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstance.getServiceInstanceId());
+
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID)))
+ .thenReturn(serviceInstance);
+ // verify connection call was not executednetwork
+ exception.expect(BpmnError.class);
+ aaiCreateTasks.connectNetworkToNetworkCollectionInstanceGroup(execution);
+ verify(aaiNetworkResources, never()).connectNetworkToNetworkCollectionInstanceGroup(network, null);
+ }
+
+ @Test
+ public void connectNetworkToCloudRegionTest() throws Exception {
+ gBBInput = execution.getGeneralBuildingBlock();
+ doNothing().when(aaiNetworkResources).connectNetworkToCloudRegion(network, gBBInput.getCloudRegion());
+ aaiCreateTasks.connectNetworkToCloudRegion(execution);
+ verify(aaiNetworkResources, times(1)).connectNetworkToCloudRegion(network, gBBInput.getCloudRegion());
+ }
+
+ @Test
+ public void connectNetworkToTenantTest() throws Exception {
+ gBBInput = execution.getGeneralBuildingBlock();
+ doNothing().when(aaiNetworkResources).connectNetworkToTenant(network, gBBInput.getCloudRegion());
+ aaiCreateTasks.connectNetworkToTenant(execution);
+ verify(aaiNetworkResources, times(1)).connectNetworkToTenant(network, gBBInput.getCloudRegion());
+ }
+
+ @Test
+ public void createConfigurationTest() throws Exception {
+ gBBInput = execution.getGeneralBuildingBlock();
+ doNothing().when(aaiConfigurationResources).createConfiguration(configuration);
+ aaiCreateTasks.createConfiguration(execution);
+ verify(aaiConfigurationResources, times(1)).createConfiguration(configuration);
+ }
+
+ @Test
+ public void connectVnfToCloudRegionTest() throws Exception {
+ gBBInput = execution.getGeneralBuildingBlock();
+ doNothing().when(aaiVnfResources).connectVnfToCloudRegion(genericVnf, gBBInput.getCloudRegion());
+ aaiCreateTasks.connectVnfToCloudRegion(execution);
+ verify(aaiVnfResources, times(1)).connectVnfToCloudRegion(genericVnf, gBBInput.getCloudRegion());
+ }
+
+ @Test
+ public void connectNoneToVnfToCloudRegionTest() throws Exception {
+ String[] arr = new String[1];
+ arr[0] = "test25Region2";
+ doReturn(arr).when(env).getProperty("mso.bpmn.cloudRegionIdsToSkipAddingVnfEdgesTo", String[].class);
+ gBBInput = execution.getGeneralBuildingBlock();
+ gBBInput.getCloudRegion().setLcpCloudRegionId("test25Region2");
+ doNothing().when(aaiVnfResources).connectVnfToCloudRegion(genericVnf, gBBInput.getCloudRegion());
+ aaiCreateTasks.connectVnfToCloudRegion(execution);
+ verify(aaiVnfResources, times(0)).connectVnfToCloudRegion(genericVnf, gBBInput.getCloudRegion());
+ }
+
+ @Test
+ public void connectVnfTenantTest() throws Exception {
+ gBBInput = execution.getGeneralBuildingBlock();
+ doNothing().when(aaiVnfResources).connectVnfToTenant(genericVnf, gBBInput.getCloudRegion());
+ aaiCreateTasks.connectVnfToTenant(execution);
+ verify(aaiVnfResources, times(1)).connectVnfToTenant(genericVnf, gBBInput.getCloudRegion());
+ }
+
+ @Test
+ public void createInstanceGroupVnfTest() throws Exception {
+ doNothing().when(aaiInstanceGroupResources).createInstanceGroupandConnectServiceInstance(instanceGroup,
+ serviceInstance);
+ aaiCreateTasks.createInstanceGroupVnf(execution);
+ verify(aaiInstanceGroupResources, times(1)).createInstanceGroupandConnectServiceInstance(instanceGroup,
+ serviceInstance);
+ }
+
+ @Test
+ public void createInstanceGroupVnfExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(aaiInstanceGroupResources)
+ .createInstanceGroupandConnectServiceInstance(instanceGroup, serviceInstance);
+ aaiCreateTasks.createInstanceGroupVnf(execution);
+ }
+
+ @Test
+ public void createNetworkPolicyNeedToCreateAllTest() throws Exception {
+ execution.setVariable("heatStackId", "testHeatStackId");
+ execution.setVariable("contrailNetworkPolicyFqdnList", "ABC123,ED456");
+ Optional<NetworkPolicy> networkPolicy = Optional.empty();
+ doReturn(networkPolicy).when(aaiNetworkResources).getNetworkPolicy(any(AAIResourceUri.class));
+ doNothing().when(aaiNetworkResources).createNetworkPolicy(any(NetworkPolicy.class));
+ aaiCreateTasks.createNetworkPolicies(execution);
+ verify(aaiNetworkResources, times(2)).createNetworkPolicy(networkPolicyCaptor.capture());
+ assertEquals("ABC123", networkPolicyCaptor.getAllValues().get(0).getNetworkPolicyFqdn());
+ assertEquals("ED456", networkPolicyCaptor.getAllValues().get(1).getNetworkPolicyFqdn());
+ assertEquals("testHeatStackId", networkPolicyCaptor.getAllValues().get(0).getHeatStackId());
+ assertEquals("testHeatStackId", networkPolicyCaptor.getAllValues().get(1).getHeatStackId());
+ }
+
+ @Test
+ public void createNetworkPolicyNeedToCreateNoneTest() throws Exception {
+ execution.setVariable("heatStackId", "testHeatStackId");
+ execution.setVariable("contrailNetworkPolicyFqdnList", "ABC123");
+ NetworkPolicy networkPolicy = new NetworkPolicy();
+ doReturn(Optional.of(networkPolicy)).when(aaiNetworkResources).getNetworkPolicy(any(AAIResourceUri.class));
+ doNothing().when(aaiNetworkResources).createNetworkPolicy(any(NetworkPolicy.class));
+ aaiCreateTasks.createNetworkPolicies(execution);
+ verify(aaiNetworkResources, times(0)).createNetworkPolicy(any(NetworkPolicy.class));
+ }
+
+ @Test
+ public void createNetworkPolicyNoNetworkPoliciesTest() throws Exception {
+ execution.setVariable("heatStackId", "testHeatStackId");
+ aaiCreateTasks.createNetworkPolicies(execution);
+ verify(aaiNetworkResources, times(0)).createNetworkPolicy(any(NetworkPolicy.class));
+ }
+
+ @Test
+ public void createVfModuleGetLowestIndexTest() throws Exception {
+ GenericVnf vnf = new GenericVnf();
+ ModelInfoGenericVnf vnfInfo = new ModelInfoGenericVnf();
+ vnf.setModelInfoGenericVnf(vnfInfo);
+ vnfInfo.setModelInvariantUuid("my-uuid");
+
+ ModelInfoVfModule infoA = new ModelInfoVfModule();
+ infoA.setIsBaseBoolean(false);
+ infoA.setModelInvariantUUID("A");
+
+ ModelInfoVfModule infoB = new ModelInfoVfModule();
+ infoB.setIsBaseBoolean(false);
+ infoB.setModelInvariantUUID("B");
+
+ ModelInfoVfModule infoC = new ModelInfoVfModule();
+ infoC.setIsBaseBoolean(false);
+ infoC.setModelInvariantUUID("C");
+
+ VfModule newVfModuleA = new VfModule();
+ newVfModuleA.setVfModuleId("a");
+ VfModule newVfModuleB = new VfModule();
+ newVfModuleB.setVfModuleId("b");
+ VfModule newVfModuleC = new VfModule();
+ newVfModuleC.setVfModuleId("c");
+
+ VfModule vfModule = new VfModule();
+ vnf.getVfModules().add(vfModule);
+ vfModule.setVfModuleId("1");
+
+ VfModule vfModule2 = new VfModule();
+ vnf.getVfModules().add(vfModule2);
+ vfModule2.setVfModuleId("2");
+
+ VfModule vfModule3 = new VfModule();
+ vnf.getVfModules().add(vfModule3);
+ vfModule3.setVfModuleId("3");
+
+ VfModule vfModule4 = new VfModule();
+ vnf.getVfModules().add(vfModule4);
+ vfModule4.setVfModuleId("4");
+
+ VfModule vfModule5 = new VfModule();
+ vnf.getVfModules().add(vfModule5);
+ vfModule5.setVfModuleId("5");
+
+ // modules are included in the vnf already
+ vnf.getVfModules().add(newVfModuleA);
+ vnf.getVfModules().add(newVfModuleB);
+ vnf.getVfModules().add(newVfModuleC);
+
+ // A
+ newVfModuleA.setModelInfoVfModule(infoA);
+ vfModule.setModelInfoVfModule(infoA);
+ vfModule2.setModelInfoVfModule(infoA);
+ vfModule3.setModelInfoVfModule(infoA);
+
+ // B
+
+ newVfModuleB.setModelInfoVfModule(infoB);
+ vfModule4.setModelInfoVfModule(infoB);
+ vfModule5.setModelInfoVfModule(infoB);
+
+ // C
+ newVfModuleC.setModelInfoVfModule(infoC);
+
+
+ // A
+ vfModule.setModuleIndex(2);
+ vfModule2.setModuleIndex(0);
+ vfModule3.setModuleIndex(3);
+
+ // B
+ vfModule4.setModuleIndex(null);
+ vfModule5.setModuleIndex(1);
+
+ assertEquals(1, aaiCreateTasks.getLowestUnusedVfModuleIndexFromAAIVnfResponse(vnf, newVfModuleA));
+
+ assertEquals(2, aaiCreateTasks.getLowestUnusedVfModuleIndexFromAAIVnfResponse(vnf, newVfModuleB));
+
+ assertEquals(0, aaiCreateTasks.getLowestUnusedVfModuleIndexFromAAIVnfResponse(vnf, newVfModuleC));
+
+ }
+
+ @Test
+ public void calculateUnusedIndexTest() {
+
+ TreeSet<Integer> a = new TreeSet<>(Arrays.asList(0, 1, 3));
+ TreeSet<Integer> b = new TreeSet<>(Arrays.asList(0, 1, 8));
+ TreeSet<Integer> c = new TreeSet<>(Arrays.asList(0, 2, 4));
+ assertEquals(2, aaiCreateTasks.calculateUnusedIndex(a, 0));
+ assertEquals(5, aaiCreateTasks.calculateUnusedIndex(a, 2));
+
+ assertEquals(4, aaiCreateTasks.calculateUnusedIndex(b, 2));
+ assertEquals(3, aaiCreateTasks.calculateUnusedIndex(b, 1));
+
+ assertEquals(5, aaiCreateTasks.calculateUnusedIndex(c, 2));
+ assertEquals(9, aaiCreateTasks.calculateUnusedIndex(c, 6));
+ assertEquals(1, aaiCreateTasks.calculateUnusedIndex(c, 0));
+
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasksTest.java
index 826f888818..855d935ae1 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasksTest.java
@@ -29,11 +29,9 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -60,180 +58,191 @@ import org.onap.so.client.exception.BBObjectNotFoundException;
public class AAIDeleteTasksTest extends BaseTaskTest {
- private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
-
- @InjectMocks
- private AAIDeleteTasks aaiDeleteTasks = new AAIDeleteTasks();
-
- private L3Network network;
- private ServiceInstance serviceInstance;
- private GenericVnf genericVnf;
- private VfModule vfModule;
- private VolumeGroup volumeGroup;
- private CloudRegion cloudRegion;
- private Configuration configuration;
- private InstanceGroup instanceGroup;
-
- @Captor
- ArgumentCaptor<String> stringCaptor;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- serviceInstance = setServiceInstance();
- genericVnf = setGenericVnf();
- vfModule = setVfModule();
- network = setL3Network();
- volumeGroup = setVolumeGroup();
- cloudRegion = setCloudRegion();
- configuration = setConfiguration();
- instanceGroup = setInstanceGroupVnf();
-
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.CONFIGURATION_ID))).thenReturn(configuration);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID))).thenReturn(instanceGroup);
-
-
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- }
-
- @Test
- public void deleteVfModuleTest() throws Exception {
-
- doNothing().when(aaiVfModuleResources).deleteVfModule(vfModule, genericVnf);
-
- aaiDeleteTasks.deleteVfModule(execution);
- verify(aaiVfModuleResources, times(1)).deleteVfModule(vfModule, genericVnf);
- }
-
- @Test
- public void deleteVfModuleExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(aaiVfModuleResources).deleteVfModule(vfModule, genericVnf);
- aaiDeleteTasks.deleteVfModule(execution);
- }
-
- @Test
- public void deleteServiceInstanceTest() throws Exception {
- doNothing().when(aaiServiceInstanceResources).deleteServiceInstance(serviceInstance);
-
- aaiDeleteTasks.deleteServiceInstance(execution);
-
- verify(aaiServiceInstanceResources, times(1)).deleteServiceInstance(serviceInstance);
- }
-
- @Test
- public void deleteServiceInstanceExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- doThrow(RuntimeException.class).when(aaiServiceInstanceResources).deleteServiceInstance(serviceInstance);
-
- aaiDeleteTasks.deleteServiceInstance(execution);
- }
-
- @Test
- public void deleteVnfTest() throws Exception {
- doNothing().when(aaiVnfResources).deleteVnf(genericVnf);
- aaiDeleteTasks.deleteVnf(execution);
- verify(aaiVnfResources, times(1)).deleteVnf(genericVnf);
- }
-
- @Test
- public void deleteVnfTestException() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(aaiVnfResources).deleteVnf(genericVnf);
-
- aaiDeleteTasks.deleteVnf(execution);
- verify(aaiVnfResources, times(1)).deleteVnf(genericVnf);
- }
-
- @Test
- public void deleteNetworkTest() throws Exception {
- doNothing().when(aaiNetworkResources).deleteNetwork(network);
- aaiDeleteTasks.deleteNetwork(execution);
- verify(aaiNetworkResources, times(1)).deleteNetwork(network);
- }
-
- @Test
- public void deleteCollectionTest() throws Exception {
- doNothing().when(aaiNetworkResources).deleteCollection(serviceInstance.getCollection());
- aaiDeleteTasks.deleteCollection(execution);
- verify(aaiNetworkResources, times(1)).deleteCollection(serviceInstance.getCollection());
- }
-
- @Test
- public void deleteInstanceGroupTest() throws Exception {
- doNothing().when(aaiNetworkResources).deleteNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup());
- aaiDeleteTasks.deleteInstanceGroup(execution);
- verify(aaiNetworkResources, times(1)).deleteNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup());
- }
-
- @Test
- public void deleteVolumeGroupTest() {
- doNothing().when(aaiVolumeGroupResources).deleteVolumeGroup(volumeGroup, cloudRegion);
-
- aaiDeleteTasks.deleteVolumeGroup(execution);
-
- verify(aaiVolumeGroupResources, times(1)).deleteVolumeGroup(volumeGroup, cloudRegion);
- }
-
- @Test
- public void deleteVolumeGroupExceptionTest() {
- expectedException.expect(BpmnError.class);
-
- doThrow(RuntimeException.class).when(aaiVolumeGroupResources).deleteVolumeGroup(volumeGroup, cloudRegion);
-
- aaiDeleteTasks.deleteVolumeGroup(execution);
- }
-
- @Test
- public void deleteConfigurationTest() throws Exception {
- gBBInput = execution.getGeneralBuildingBlock();
- doNothing().when(aaiConfigurationResources).deleteConfiguration(configuration);
- aaiDeleteTasks.deleteConfiguration(execution);
- verify(aaiConfigurationResources, times(1)).deleteConfiguration(configuration);
- }
-
- @Test
- public void deleteInstanceGroupVnfTest() throws Exception {
- doNothing().when(aaiInstanceGroupResources).deleteInstanceGroup(instanceGroup);
- aaiDeleteTasks.deleteInstanceGroupVnf(execution);
- verify(aaiInstanceGroupResources, times(1)).deleteInstanceGroup(instanceGroup);
- }
-
- @Test
- public void deleteNetworkPolicyNeedToDeleteAllTest() throws Exception {
- execution.setVariable("contrailNetworkPolicyFqdnList", "ABC123,DEF456");
- final String content0 = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAaiNetworkPoliciesForDelete0.json")));
- AAIResultWrapper aaiResultWrapper0 = new AAIResultWrapper(content0);
- NetworkPolicies networkPolicies0 = aaiResultWrapper0.asBean(NetworkPolicies.class).get();
- final String content1 = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAaiNetworkPoliciesForDelete1.json")));
- AAIResultWrapper aaiResultWrapper1 = new AAIResultWrapper(content1);
- NetworkPolicies networkPolicies1 = aaiResultWrapper1.asBean(NetworkPolicies.class).get();
-
- doReturn(Optional.of(networkPolicies0),Optional.of(networkPolicies1)).when(aaiNetworkResources).getNetworkPolicies(any(AAIResourceUri.class));
- doNothing().when(aaiNetworkResources).deleteNetworkPolicy(any(String.class));
- aaiDeleteTasks.deleteNetworkPolicies(execution);
- verify(aaiNetworkResources, times(2)).deleteNetworkPolicy(stringCaptor.capture());
- assertEquals("testNetworkPolicyId0", stringCaptor.getAllValues().get(0));
- assertEquals("testNetworkPolicyId1", stringCaptor.getAllValues().get(1));
- }
-
- @Test
- public void deleteNetworkPolicyNeedToDeleteNoneTest() throws Exception {
- execution.setVariable("contrailNetworkPolicyFqdnList", "ABC123");
- Optional<NetworkPolicies> networkPolicies = Optional.empty();
- doReturn(networkPolicies).when(aaiNetworkResources).getNetworkPolicies(any(AAIResourceUri.class));
- aaiDeleteTasks.deleteNetworkPolicies(execution);
- verify(aaiNetworkResources, times(0)).deleteNetworkPolicy(any(String.class));
- }
-
- @Test
- public void deleteNetworkPolicyNoNetworkPoliciesTest() throws Exception {
- aaiDeleteTasks.deleteNetworkPolicies(execution);
- verify(aaiNetworkResources, times(0)).deleteNetworkPolicy(any(String.class));
- }
+ private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
+
+ @InjectMocks
+ private AAIDeleteTasks aaiDeleteTasks = new AAIDeleteTasks();
+
+ private L3Network network;
+ private ServiceInstance serviceInstance;
+ private GenericVnf genericVnf;
+ private VfModule vfModule;
+ private VolumeGroup volumeGroup;
+ private CloudRegion cloudRegion;
+ private Configuration configuration;
+ private InstanceGroup instanceGroup;
+
+ @Captor
+ ArgumentCaptor<String> stringCaptor;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ serviceInstance = setServiceInstance();
+ genericVnf = setGenericVnf();
+ vfModule = setVfModule();
+ network = setL3Network();
+ volumeGroup = setVolumeGroup();
+ cloudRegion = setCloudRegion();
+ configuration = setConfiguration();
+ instanceGroup = setInstanceGroupVnf();
+
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID)))
+ .thenReturn(volumeGroup);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.CONFIGURATION_ID)))
+ .thenReturn(configuration);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID)))
+ .thenReturn(instanceGroup);
+
+
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ }
+
+ @Test
+ public void deleteVfModuleTest() throws Exception {
+
+ doNothing().when(aaiVfModuleResources).deleteVfModule(vfModule, genericVnf);
+
+ aaiDeleteTasks.deleteVfModule(execution);
+ verify(aaiVfModuleResources, times(1)).deleteVfModule(vfModule, genericVnf);
+ }
+
+ @Test
+ public void deleteVfModuleExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(aaiVfModuleResources).deleteVfModule(vfModule, genericVnf);
+ aaiDeleteTasks.deleteVfModule(execution);
+ }
+
+ @Test
+ public void deleteServiceInstanceTest() throws Exception {
+ doNothing().when(aaiServiceInstanceResources).deleteServiceInstance(serviceInstance);
+
+ aaiDeleteTasks.deleteServiceInstance(execution);
+
+ verify(aaiServiceInstanceResources, times(1)).deleteServiceInstance(serviceInstance);
+ }
+
+ @Test
+ public void deleteServiceInstanceExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ doThrow(RuntimeException.class).when(aaiServiceInstanceResources).deleteServiceInstance(serviceInstance);
+
+ aaiDeleteTasks.deleteServiceInstance(execution);
+ }
+
+ @Test
+ public void deleteVnfTest() throws Exception {
+ doNothing().when(aaiVnfResources).deleteVnf(genericVnf);
+ aaiDeleteTasks.deleteVnf(execution);
+ verify(aaiVnfResources, times(1)).deleteVnf(genericVnf);
+ }
+
+ @Test
+ public void deleteVnfTestException() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(aaiVnfResources).deleteVnf(genericVnf);
+
+ aaiDeleteTasks.deleteVnf(execution);
+ verify(aaiVnfResources, times(1)).deleteVnf(genericVnf);
+ }
+
+ @Test
+ public void deleteNetworkTest() throws Exception {
+ doNothing().when(aaiNetworkResources).deleteNetwork(network);
+ aaiDeleteTasks.deleteNetwork(execution);
+ verify(aaiNetworkResources, times(1)).deleteNetwork(network);
+ }
+
+ @Test
+ public void deleteCollectionTest() throws Exception {
+ doNothing().when(aaiNetworkResources).deleteCollection(serviceInstance.getCollection());
+ aaiDeleteTasks.deleteCollection(execution);
+ verify(aaiNetworkResources, times(1)).deleteCollection(serviceInstance.getCollection());
+ }
+
+ @Test
+ public void deleteInstanceGroupTest() throws Exception {
+ doNothing().when(aaiNetworkResources)
+ .deleteNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup());
+ aaiDeleteTasks.deleteInstanceGroup(execution);
+ verify(aaiNetworkResources, times(1))
+ .deleteNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup());
+ }
+
+ @Test
+ public void deleteVolumeGroupTest() {
+ doNothing().when(aaiVolumeGroupResources).deleteVolumeGroup(volumeGroup, cloudRegion);
+
+ aaiDeleteTasks.deleteVolumeGroup(execution);
+
+ verify(aaiVolumeGroupResources, times(1)).deleteVolumeGroup(volumeGroup, cloudRegion);
+ }
+
+ @Test
+ public void deleteVolumeGroupExceptionTest() {
+ expectedException.expect(BpmnError.class);
+
+ doThrow(RuntimeException.class).when(aaiVolumeGroupResources).deleteVolumeGroup(volumeGroup, cloudRegion);
+
+ aaiDeleteTasks.deleteVolumeGroup(execution);
+ }
+
+ @Test
+ public void deleteConfigurationTest() throws Exception {
+ gBBInput = execution.getGeneralBuildingBlock();
+ doNothing().when(aaiConfigurationResources).deleteConfiguration(configuration);
+ aaiDeleteTasks.deleteConfiguration(execution);
+ verify(aaiConfigurationResources, times(1)).deleteConfiguration(configuration);
+ }
+
+ @Test
+ public void deleteInstanceGroupVnfTest() throws Exception {
+ doNothing().when(aaiInstanceGroupResources).deleteInstanceGroup(instanceGroup);
+ aaiDeleteTasks.deleteInstanceGroupVnf(execution);
+ verify(aaiInstanceGroupResources, times(1)).deleteInstanceGroup(instanceGroup);
+ }
+
+ @Test
+ public void deleteNetworkPolicyNeedToDeleteAllTest() throws Exception {
+ execution.setVariable("contrailNetworkPolicyFqdnList", "ABC123,DEF456");
+ final String content0 = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAaiNetworkPoliciesForDelete0.json")));
+ AAIResultWrapper aaiResultWrapper0 = new AAIResultWrapper(content0);
+ NetworkPolicies networkPolicies0 = aaiResultWrapper0.asBean(NetworkPolicies.class).get();
+ final String content1 = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAaiNetworkPoliciesForDelete1.json")));
+ AAIResultWrapper aaiResultWrapper1 = new AAIResultWrapper(content1);
+ NetworkPolicies networkPolicies1 = aaiResultWrapper1.asBean(NetworkPolicies.class).get();
+
+ doReturn(Optional.of(networkPolicies0), Optional.of(networkPolicies1)).when(aaiNetworkResources)
+ .getNetworkPolicies(any(AAIResourceUri.class));
+ doNothing().when(aaiNetworkResources).deleteNetworkPolicy(any(String.class));
+ aaiDeleteTasks.deleteNetworkPolicies(execution);
+ verify(aaiNetworkResources, times(2)).deleteNetworkPolicy(stringCaptor.capture());
+ assertEquals("testNetworkPolicyId0", stringCaptor.getAllValues().get(0));
+ assertEquals("testNetworkPolicyId1", stringCaptor.getAllValues().get(1));
+ }
+
+ @Test
+ public void deleteNetworkPolicyNeedToDeleteNoneTest() throws Exception {
+ execution.setVariable("contrailNetworkPolicyFqdnList", "ABC123");
+ Optional<NetworkPolicies> networkPolicies = Optional.empty();
+ doReturn(networkPolicies).when(aaiNetworkResources).getNetworkPolicies(any(AAIResourceUri.class));
+ aaiDeleteTasks.deleteNetworkPolicies(execution);
+ verify(aaiNetworkResources, times(0)).deleteNetworkPolicy(any(String.class));
+ }
+
+ @Test
+ public void deleteNetworkPolicyNoNetworkPoliciesTest() throws Exception {
+ aaiDeleteTasks.deleteNetworkPolicies(execution);
+ verify(aaiNetworkResources, times(0)).deleteNetworkPolicy(any(String.class));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java
index 05af58040a..7109ac8826 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java
@@ -32,9 +32,7 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.util.HashMap;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.hamcrest.Matchers;
import org.junit.Before;
@@ -59,613 +57,678 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf;
import org.onap.so.client.exception.BBObjectNotFoundException;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-public class AAIUpdateTasksTest extends BaseTaskTest{
-
- @InjectMocks
- private AAIUpdateTasks aaiUpdateTasks = new AAIUpdateTasks();
-
- private L3Network network;
- private ServiceInstance serviceInstance;
- private VfModule vfModule;
- private GenericVnf genericVnf;
- private VolumeGroup volumeGroup;
- private CloudRegion cloudRegion;
- private Configuration configuration;
- private Subnet subnet;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- serviceInstance = setServiceInstance();
- genericVnf = setGenericVnf();
- vfModule = setVfModule();
- volumeGroup = setVolumeGroup();
- cloudRegion = setCloudRegion();
- network = setL3Network();
- configuration = setConfiguration();
- subnet = buildSubnet();
-
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.CONFIGURATION_ID))).thenReturn(configuration);
-
-
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- }
-
- @Test
- public void updateOrchestrationStatusAssignedServiceTest() throws Exception {
- doNothing().when(aaiServiceInstanceResources).updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ASSIGNED);
-
- aaiUpdateTasks.updateOrchestrationStatusAssignedService(execution);
-
- verify(aaiServiceInstanceResources, times(1)).updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ASSIGNED);
- }
-
- @Test
- public void updateOrchestrationStatusAssignedServiceExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- doThrow(RuntimeException.class).when(aaiServiceInstanceResources).updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ASSIGNED);
-
- aaiUpdateTasks.updateOrchestrationStatusAssignedService(execution);
- }
-
- @Test
- public void updateOrchestrationStatusActiveServiceTest() throws Exception {
- doNothing().when(aaiServiceInstanceResources).updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ACTIVE);
-
- aaiUpdateTasks.updateOrchestrationStatusActiveService(execution);
-
- verify(aaiServiceInstanceResources, times(1)).updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ACTIVE);
- }
-
- @Test
- public void updateOrchestrationStatusActiveServiceExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- doThrow(RuntimeException.class).when(aaiServiceInstanceResources).updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ACTIVE);
-
- aaiUpdateTasks.updateOrchestrationStatusActiveService(execution);
- }
-
- @Test
- public void updateOrchestrationStatusAssignedVnfTest() throws Exception {
- doNothing().when(aaiVnfResources).updateOrchestrationStatusVnf(genericVnf, OrchestrationStatus.ASSIGNED);
-
- aaiUpdateTasks.updateOrchestrationStatusAssignedVnf(execution);
-
- verify(aaiVnfResources, times(1)).updateOrchestrationStatusVnf(genericVnf, OrchestrationStatus.ASSIGNED);
- }
-
- @Test
- public void updateOrchestrationStatusAssignedVnfExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- doThrow(RuntimeException.class).when(aaiVnfResources).updateOrchestrationStatusVnf(genericVnf, OrchestrationStatus.ASSIGNED);
-
- aaiUpdateTasks.updateOrchestrationStatusAssignedVnf(execution);
- }
-
- @Test
- public void updateOrchestrationStatusActiveVnfTest() throws Exception {
- doNothing().when(aaiVnfResources).updateOrchestrationStatusVnf(genericVnf, OrchestrationStatus.ACTIVE);
-
- aaiUpdateTasks.updateOrchestrationStatusActiveVnf(execution);
-
- verify(aaiVnfResources, times(1)).updateOrchestrationStatusVnf(genericVnf, OrchestrationStatus.ACTIVE);
- }
-
- @Test
- public void updateOrchestrationStatusActiveVnfExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- doThrow(RuntimeException.class).when(aaiVnfResources).updateOrchestrationStatusVnf(genericVnf, OrchestrationStatus.ACTIVE);
-
- aaiUpdateTasks.updateOrchestrationStatusActiveVnf(execution);
- }
-
- @Test
- public void updateOrchestrationStatusAssignVfModuleTest() throws Exception {
- doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ASSIGNED);
- aaiUpdateTasks.updateOrchestrationStatusAssignedVfModule(execution);
- verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ASSIGNED);
- assertEquals("", vfModule.getHeatStackId());
- }
-
- @Test
- public void updateOrchestrationStatusAssignVfModuleExceptionTest() throws Exception {
- doThrow(RuntimeException.class).when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ASSIGNED);
-
- expectedException.expect(BpmnError.class);
-
- aaiUpdateTasks.updateOrchestrationStatusAssignedVfModule(execution);
- }
-
- @Test
- public void updateOrchestrationStatusAssignedOrPendingActivationVfModuleNoMultiStageTest() throws Exception {
- execution.setVariable("aLaCarte", true);
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setMultiStageDesign("false");
- genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf);
- doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ASSIGNED);
- aaiUpdateTasks.updateOrchestrationStatusAssignedOrPendingActivationVfModule(execution);
- verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ASSIGNED);
- assertEquals("", vfModule.getHeatStackId());
- }
-
- @Test
- public void updateOrchestrationStatusAssignedOrPendingActivationVfModuleMultiStageButNotAlacarteTest() throws Exception {
- execution.setVariable("aLaCarte", false);
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setMultiStageDesign("true");
- genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf);
- doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ASSIGNED);
- aaiUpdateTasks.updateOrchestrationStatusAssignedOrPendingActivationVfModule(execution);
- verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ASSIGNED);
- assertEquals("", vfModule.getHeatStackId());
- }
-
- @Test
- public void updateOrchestrationStatusAssignedOrPendingActivationVfModuleWithMultiStageTest() throws Exception {
- execution.setVariable("aLaCarte", true);
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setMultiStageDesign("true");
- genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf);
- doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.PENDING_ACTIVATION);
- aaiUpdateTasks.updateOrchestrationStatusAssignedOrPendingActivationVfModule(execution);
- verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.PENDING_ACTIVATION);
- assertEquals("", vfModule.getHeatStackId());
- }
-
- @Test
- public void updateOrchestrationStatusAssignedOrPendingActivationVfModuleExceptionTest() throws Exception {
- execution.setVariable("aLaCarte", true);
- doThrow(RuntimeException.class).when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ASSIGNED);
-
- expectedException.expect(BpmnError.class);
-
- aaiUpdateTasks.updateOrchestrationStatusAssignedOrPendingActivationVfModule(execution);
- }
-
- @Test
- public void updateOrchestrationStatusCreatedVfModuleTest() throws Exception {
- doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.CREATED);
- aaiUpdateTasks.updateOrchestrationStatusCreatedVfModule(execution);
- verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.CREATED);
- }
-
- @Test
- public void updateOrchestrationStatusCreatedVfModuleExceptionTest() throws Exception {
- doThrow(RuntimeException.class).when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.CREATED);
-
- expectedException.expect(BpmnError.class);
-
- aaiUpdateTasks.updateOrchestrationStatusCreatedVfModule(execution);
- }
-
- @Test
- public void updateOrchestrationStatusPendingActivatefModuleTest() throws Exception {
- doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.PENDING_ACTIVATION);
-
- aaiUpdateTasks.updateOrchestrationStatusPendingActivationVfModule(execution);
-
- verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.PENDING_ACTIVATION);
- }
-
- @Test
- public void updateOrchestrationStatusPendingActivatefModuleExceptionTest() throws Exception {
- doThrow(RuntimeException.class).when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.PENDING_ACTIVATION);
-
- expectedException.expect(BpmnError.class);
-
- aaiUpdateTasks.updateOrchestrationStatusPendingActivationVfModule(execution);
- }
-
- @Test
- public void updateOrchestrationStatusDectivateVfModuleTest() throws Exception {
- doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.CREATED);
-
- aaiUpdateTasks.updateOrchestrationStatusDeactivateVfModule(execution);
-
- verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.CREATED);
- }
-
- @Test
- public void updateOrchestrationStatusDectivateVfModuleExceptionTest() throws Exception {
- doThrow(RuntimeException.class).when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.CREATED);
-
- expectedException.expect(BpmnError.class);
-
- aaiUpdateTasks.updateOrchestrationStatusDeactivateVfModule(execution);
- }
-
- @Test
- public void updateHeatStackIdVfModuleTest() throws Exception {
- execution.setVariable("heatStackId", "newHeatStackId");
- doNothing().when(aaiVfModuleResources).updateHeatStackIdVfModule(vfModule, genericVnf);
-
- aaiUpdateTasks.updateHeatStackIdVfModule(execution);
-
- verify(aaiVfModuleResources, times(1)).updateHeatStackIdVfModule(vfModule, genericVnf);
- assertEquals("newHeatStackId", vfModule.getHeatStackId());
- }
-
- @Test
- public void updateHeatStackIdVfModuleToNullTest() throws Exception {
- execution.setVariable("heatStackId", null);
- doNothing().when(aaiVfModuleResources).updateHeatStackIdVfModule(vfModule, genericVnf);
-
- aaiUpdateTasks.updateHeatStackIdVfModule(execution);
-
- verify(aaiVfModuleResources, times(1)).updateHeatStackIdVfModule(vfModule, genericVnf);
- assertEquals(vfModule.getHeatStackId(), "");
- }
-
- @Test
- public void updateHeatStackIdVfModuleExceptionTest() throws Exception {
- doThrow(RuntimeException.class).when(aaiVfModuleResources).updateHeatStackIdVfModule(vfModule, genericVnf);
-
- expectedException.expect(BpmnError.class);
-
- aaiUpdateTasks.updateHeatStackIdVfModule(execution);
- }
-
- @Test
- public void updateOrchestrationStatusActiveVolumeGroupTest() throws Exception {
- doNothing().when(aaiVolumeGroupResources).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.ACTIVE);
-
- aaiUpdateTasks.updateOrchestrationStatusActiveVolumeGroup(execution);
-
- verify(aaiVolumeGroupResources, times(1)).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.ACTIVE);
- }
-
- @Test
- public void updateOrchestrationStatusActiveVolumeGroupExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(aaiVolumeGroupResources).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.ACTIVE);
- aaiUpdateTasks.updateOrchestrationStatusActiveVolumeGroup(execution);
- }
-
- @Test
- public void updateOrchestrationStatusCreatedVolumeGroupTest() throws Exception {
- doNothing().when(aaiVolumeGroupResources).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.CREATED);
-
- aaiUpdateTasks.updateOrchestrationStatusCreatedVolumeGroup(execution);
-
- verify(aaiVolumeGroupResources, times(1)).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.CREATED);
- }
-
- @Test
- public void updateOrchestrationStatusCreatedVolumeGroupExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(aaiVolumeGroupResources).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.CREATED);
- aaiUpdateTasks.updateOrchestrationStatusCreatedVolumeGroup(execution);
- }
-
- @Test
- public void test_updateOrchestrationStatusAssignedVolumeGroup() throws Exception {
- doNothing().when(aaiVolumeGroupResources).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.ASSIGNED);
-
- aaiUpdateTasks.updateOrchestrationStatusAssignedVolumeGroup(execution);
-
- verify(aaiVolumeGroupResources, times(1)).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.ASSIGNED);
- assertEquals("", volumeGroup.getHeatStackId());
- }
-
- @Test
- public void test_updateOrchestrationStatusAssignedVolumeGroup_exception() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(aaiVolumeGroupResources).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.ASSIGNED);
- aaiUpdateTasks.updateOrchestrationStatusAssignedVolumeGroup(execution);
- }
- @Test
- public void updateHeatStackIdVolumeGroupTest() throws Exception {
- execution.setVariable("heatStackId", "newHeatStackId");
- doNothing().when(aaiVolumeGroupResources).updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
-
- aaiUpdateTasks.updateHeatStackIdVolumeGroup(execution);
-
- verify(aaiVolumeGroupResources, times(1)).updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
- assertEquals("newHeatStackId", volumeGroup.getHeatStackId());
- }
- @Test
- public void updateHeatStackIdVolumeGroupToNullTest() throws Exception {
- execution.setVariable("heatStackId", null);
- doNothing().when(aaiVolumeGroupResources).updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
-
- aaiUpdateTasks.updateHeatStackIdVolumeGroup(execution);
-
- verify(aaiVolumeGroupResources, times(1)).updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
- assertEquals(volumeGroup.getHeatStackId(), "");
- }
-
- @Test
- public void updateHeatStackIdVolumeGroupExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(aaiVolumeGroupResources).updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
- aaiUpdateTasks.updateHeatStackIdVolumeGroup(execution);
- }
-
- @Test
- public void updateNetworkExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- doThrow(RuntimeException.class).when(aaiNetworkResources).updateNetwork(network);
-
- aaiUpdateTasks.updateNetwork(execution, OrchestrationStatus.ACTIVE);
- }
-
- @Test
- public void updateOstatusActivedNetworkCollectionTest() throws Exception {
- doNothing().when(aaiCollectionResources).updateCollection(serviceInstance.getCollection());
- aaiUpdateTasks.updateOrchestrationStatusActiveNetworkCollection(execution);
- verify(aaiCollectionResources, times(1)).updateCollection(serviceInstance.getCollection());
- }
-
- @Test
- public void updateOstatusActiveNetworkColectionExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(aaiCollectionResources).updateCollection(serviceInstance.getCollection());
- aaiUpdateTasks.updateOrchestrationStatusActiveNetworkCollection(execution);
- }
-
- @Test
- public void updateOrchestrationStatusActivateVfModuleTest() throws Exception {
- doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ACTIVE);
-
- aaiUpdateTasks.updateOrchestrationStatusActivateVfModule(execution);
-
- verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ACTIVE);
- }
-
- @Test
- public void updateOrchestrationStatusActivateVfModuleExceptionTest() throws Exception {
- doThrow(RuntimeException.class).when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ACTIVE);
-
- expectedException.expect(BpmnError.class);
-
- aaiUpdateTasks.updateOrchestrationStatusActivateVfModule(execution);
- }
-
- @Test
- public void updateNetworkCreatedTest() throws Exception {
- CreateNetworkResponse createNetworkResponse = new CreateNetworkResponse();
- createNetworkResponse.setNetworkFqdn("testNetworkFqdn");
- createNetworkResponse.setNetworkStackId("testNetworkStackId");
- HashMap<String, String> subnetMap = new HashMap<>();
- subnetMap.put("testSubnetId", "testNeutronSubnetId");
- createNetworkResponse.setSubnetMap(subnetMap);
-
- network.getSubnets().add(subnet);
-
- execution.setVariable("createNetworkResponse", createNetworkResponse);
-
- doNothing().when(aaiNetworkResources).updateNetwork(network);
- doNothing().when(aaiNetworkResources).updateSubnet(network, subnet);
-
- aaiUpdateTasks.updateNetworkCreated(execution);
- verify(aaiNetworkResources, times(1)).updateNetwork(network);
- verify(aaiNetworkResources, times(1)).updateSubnet(network, subnet);
-
- assertEquals(createNetworkResponse.getNetworkFqdn(), network.getContrailNetworkFqdn());
- assertEquals(OrchestrationStatus.CREATED, network.getOrchestrationStatus());
- assertEquals(createNetworkResponse.getNetworkStackId(), network.getHeatStackId());
- assertEquals(createNetworkResponse.getNeutronNetworkId(), network.getNeutronNetworkId());
- String neutronSubnetId = createNetworkResponse.getSubnetMap().entrySet().iterator().next().getValue();
- assertEquals(neutronSubnetId, network.getSubnets().get(0).getNeutronSubnetId());
- }
-
- @Test
- public void updateNetworkUpdatedTest() throws Exception {
- UpdateNetworkResponse updateNetworkResponse = new UpdateNetworkResponse();
- updateNetworkResponse.setNeutronNetworkId("testNeutronNetworkId");
- HashMap<String, String> subnetMap = new HashMap<>();
- subnetMap.put("testSubnetId", "testNeutronSubnetId");
- updateNetworkResponse.setSubnetMap(subnetMap);
-
- network.getSubnets().add(subnet);
-
- execution.setVariable("updateNetworkResponse", updateNetworkResponse);
-
- doNothing().when(aaiNetworkResources).updateNetwork(network);
- doNothing().when(aaiNetworkResources).updateSubnet(network, subnet);
-
- aaiUpdateTasks.updateNetworkUpdated(execution);
- verify(aaiNetworkResources, times(1)).updateNetwork(network);
- verify(aaiNetworkResources, times(1)).updateSubnet(network, subnet);
-
- String neutronSubnetId = updateNetworkResponse.getSubnetMap().entrySet().iterator().next().getValue();
- assertEquals(neutronSubnetId, network.getSubnets().get(0).getNeutronSubnetId());
- }
-
- @Test
- public void updateOrchestrationStatusNetworkTest() {
- AAIUpdateTasks spy = Mockito.spy(new AAIUpdateTasks());
- doNothing().when(spy).updateNetwork(eq(execution), any());
- spy.updateOrchestrationStatusActiveNetwork(execution);
- verify(spy, times(1)).updateNetwork(execution, OrchestrationStatus.ACTIVE);
- spy.updateOrchestrationStatusAssignedNetwork(execution);
- verify(spy, times(1)).updateNetwork(execution, OrchestrationStatus.ASSIGNED);
- spy.updateOrchestrationStatusCreatedNetwork(execution);
- verify(spy, times(1)).updateNetwork(execution, OrchestrationStatus.CREATED);
- }
-
- @Test
- public void updateNetworkAAITest() {
-
- L3Network spy = spy(new L3Network());
- L3Network shallowCopy = mock(L3Network.class);
- Subnet mockSubnet = mock(Subnet.class);
- Subnet shallowCopySubnet = mock(Subnet.class);
- when(mockSubnet.shallowCopyId()).thenReturn(shallowCopySubnet);
- doReturn(shallowCopy).when(spy).shallowCopyId();
-
- doNothing().when(aaiNetworkResources).updateNetwork(network);
- doNothing().when(aaiNetworkResources).updateSubnet(network, subnet);
-
- spy.getSubnets().add(mockSubnet);
- aaiUpdateTasks.updateNetworkAAI(spy, OrchestrationStatus.CREATED);
-
- verify(shallowCopy, times(1)).setOrchestrationStatus(OrchestrationStatus.CREATED);
- verify(spy, times(1)).setOrchestrationStatus(OrchestrationStatus.CREATED);
- verify(shallowCopySubnet, times(1)).setOrchestrationStatus(OrchestrationStatus.CREATED);
- }
- @Test
- public void updateNetworkCreatedkExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(aaiNetworkResources).updateNetwork(network);
- aaiUpdateTasks.updateNetworkCreated(execution);
- }
-
- @Test
- public void updateObjectNetworkTest() {
- doNothing().when(aaiNetworkResources).updateNetwork(network);
-
- aaiUpdateTasks.updateObjectNetwork(execution);
-
- verify(aaiNetworkResources, times(1)).updateNetwork(network);
- }
-
- @Test
- public void updateObjectNetworkExceptionText() {
- expectedException.expect(BpmnError.class);
-
- doThrow(RuntimeException.class).when(aaiNetworkResources).updateNetwork(network);
-
- aaiUpdateTasks.updateObjectNetwork(execution);
- }
-
- @Test
- public void test_updateServiceInstance() {
- doNothing().when(aaiServiceInstanceResources).updateServiceInstance(serviceInstance);
- aaiUpdateTasks.updateServiceInstance(execution);
- verify(aaiServiceInstanceResources, times(1)).updateServiceInstance(serviceInstance);
- }
-
- @Test
- public void test_updateServiceInstance_exception() {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(aaiServiceInstanceResources).updateServiceInstance(serviceInstance);
- aaiUpdateTasks.updateServiceInstance(execution);
- }
-
- @Test
- public void updateObjectVnfTest() {
- doNothing().when(aaiVnfResources).updateObjectVnf(genericVnf);
-
- aaiUpdateTasks.updateObjectVnf(execution);
-
- verify(aaiVnfResources, times(1)).updateObjectVnf(genericVnf);
- }
-
- @Test
- public void updateObjectVnfExceptionTest() {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(aaiVnfResources).updateObjectVnf(genericVnf);
- aaiUpdateTasks.updateObjectVnf(execution);
- }
-
- @Test
- public void updateOrchestrationStatusDeleteVfModuleTest() throws Exception {
- doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ASSIGNED);
-
- aaiUpdateTasks.updateOrchestrationStatusDeleteVfModule(execution);
-
- verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.ASSIGNED);
- assertEquals("", vfModule.getHeatStackId());
- }
-
- @Test
- public void updateModelVfModuleTest() {
- doNothing().when(aaiVfModuleResources).changeAssignVfModule(vfModule, genericVnf);
- aaiUpdateTasks.updateModelVfModule(execution);
- verify(aaiVfModuleResources, times(1)).changeAssignVfModule(vfModule, genericVnf);
- }
-
- @Test
- public void updateModelVfModuleExceptionTest() {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(aaiVfModuleResources).changeAssignVfModule(vfModule, genericVnf);
- aaiUpdateTasks.updateModelVfModule(execution);
- }
-
- @Test
- public void updateOrchestrationStatusDeactivateFabricConfigurationTest() throws Exception {
- gBBInput = execution.getGeneralBuildingBlock();
- doNothing().when(aaiConfigurationResources).updateOrchestrationStatusConfiguration(configuration, OrchestrationStatus.ASSIGNED);
-
- aaiUpdateTasks.updateOrchestrationStatusDeactivateFabricConfiguration(execution);
-
- verify(aaiConfigurationResources, times(1)).updateOrchestrationStatusConfiguration(configuration, OrchestrationStatus.ASSIGNED);
- }
- @Test
- public void updateOrchestrationStatusActivateFabricConfigurationTest() throws Exception {
- gBBInput = execution.getGeneralBuildingBlock();
- doNothing().when(aaiConfigurationResources).updateOrchestrationStatusConfiguration(configuration, OrchestrationStatus.ACTIVE);
-
- aaiUpdateTasks.updateOrchestrationStatusActivateFabricConfiguration(execution);
-
- verify(aaiConfigurationResources, times(1)).updateOrchestrationStatusConfiguration(configuration, OrchestrationStatus.ACTIVE);
- }
- @Test
- public void updateContrailServiceInstanceFqdnVfModuleTest() throws Exception {
- execution.setVariable("contrailServiceInstanceFqdn", "newContrailServiceInstanceFqdn");
- doNothing().when(aaiVfModuleResources).updateContrailServiceInstanceFqdnVfModule(vfModule, genericVnf);
-
- aaiUpdateTasks.updateContrailServiceInstanceFqdnVfModule(execution);
-
- verify(aaiVfModuleResources, times(1)).updateContrailServiceInstanceFqdnVfModule(vfModule, genericVnf);
- assertEquals("newContrailServiceInstanceFqdn", vfModule.getContrailServiceInstanceFqdn());
- }
- @Test
- public void updateContrailServiceInstanceFqdnVfModuleNoUpdateTest() throws Exception {
- aaiUpdateTasks.updateContrailServiceInstanceFqdnVfModule(execution);
- verify(aaiVfModuleResources, times(0)).updateContrailServiceInstanceFqdnVfModule(vfModule, genericVnf);
- }
- @Test
- public void updateIpv4OamAddressVnfTest() throws Exception {
- execution.setVariable("oamManagementV4Address", "newIpv4OamAddress");
- doNothing().when(aaiVnfResources).updateObjectVnf(genericVnf);
-
- aaiUpdateTasks.updateIpv4OamAddressVnf(execution);
-
- verify(aaiVnfResources, times(1)).updateObjectVnf(genericVnf);
- assertEquals("newIpv4OamAddress", genericVnf.getIpv4OamAddress());
- }
- @Test
- public void updateIpv4OamAddressVnfNoUpdateTest() throws Exception {
- aaiUpdateTasks.updateIpv4OamAddressVnf(execution);
- verify(aaiVnfResources, times(0)).updateObjectVnf(genericVnf);
- }
- @Test
- public void updateManagementV6AddressVnfTest() throws Exception {
- execution.setVariable("oamManagementV6Address", "newManagementV6Address");
- doNothing().when(aaiVnfResources).updateObjectVnf(genericVnf);
-
- aaiUpdateTasks.updateManagementV6AddressVnf(execution);
-
- verify(aaiVnfResources, times(1)).updateObjectVnf(genericVnf);
- assertEquals("newManagementV6Address", genericVnf.getManagementV6Address());
- }
- @Test
- public void updateManagementV6AddressVnfNoUpdateTest() throws Exception {
- aaiUpdateTasks.updateManagementV6AddressVnf(execution);
- verify(aaiVnfResources, times(0)).updateObjectVnf(genericVnf);
- }
-
- @Test
- public void updateOrchestrationStatusVnfConfigureTest() throws Exception {
- doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.CONFIGURE);
-
- aaiUpdateTasks.updateOrchestrationStausConfigDeployConfigureVnf(execution);
- }
- @Test
- public void updateOrchestrationStatusVnfConfiguredTest() throws Exception {
- doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf, OrchestrationStatus.CONFIGURED);
-
- aaiUpdateTasks.updateOrchestrationStausConfigDeployConfiguredVnf(execution);
- }
+public class AAIUpdateTasksTest extends BaseTaskTest {
+
+ @InjectMocks
+ private AAIUpdateTasks aaiUpdateTasks = new AAIUpdateTasks();
+
+ private L3Network network;
+ private ServiceInstance serviceInstance;
+ private VfModule vfModule;
+ private GenericVnf genericVnf;
+ private VolumeGroup volumeGroup;
+ private CloudRegion cloudRegion;
+ private Configuration configuration;
+ private Subnet subnet;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ serviceInstance = setServiceInstance();
+ genericVnf = setGenericVnf();
+ vfModule = setVfModule();
+ volumeGroup = setVolumeGroup();
+ cloudRegion = setCloudRegion();
+ network = setL3Network();
+ configuration = setConfiguration();
+ subnet = buildSubnet();
+
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID)))
+ .thenReturn(volumeGroup);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.CONFIGURATION_ID)))
+ .thenReturn(configuration);
+
+
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ }
+
+ @Test
+ public void updateOrchestrationStatusAssignedServiceTest() throws Exception {
+ doNothing().when(aaiServiceInstanceResources).updateOrchestrationStatusServiceInstance(serviceInstance,
+ OrchestrationStatus.ASSIGNED);
+
+ aaiUpdateTasks.updateOrchestrationStatusAssignedService(execution);
+
+ verify(aaiServiceInstanceResources, times(1)).updateOrchestrationStatusServiceInstance(serviceInstance,
+ OrchestrationStatus.ASSIGNED);
+ }
+
+ @Test
+ public void updateOrchestrationStatusAssignedServiceExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ doThrow(RuntimeException.class).when(aaiServiceInstanceResources)
+ .updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ASSIGNED);
+
+ aaiUpdateTasks.updateOrchestrationStatusAssignedService(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusActiveServiceTest() throws Exception {
+ doNothing().when(aaiServiceInstanceResources).updateOrchestrationStatusServiceInstance(serviceInstance,
+ OrchestrationStatus.ACTIVE);
+
+ aaiUpdateTasks.updateOrchestrationStatusActiveService(execution);
+
+ verify(aaiServiceInstanceResources, times(1)).updateOrchestrationStatusServiceInstance(serviceInstance,
+ OrchestrationStatus.ACTIVE);
+ }
+
+ @Test
+ public void updateOrchestrationStatusActiveServiceExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ doThrow(RuntimeException.class).when(aaiServiceInstanceResources)
+ .updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ACTIVE);
+
+ aaiUpdateTasks.updateOrchestrationStatusActiveService(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusAssignedVnfTest() throws Exception {
+ doNothing().when(aaiVnfResources).updateOrchestrationStatusVnf(genericVnf, OrchestrationStatus.ASSIGNED);
+
+ aaiUpdateTasks.updateOrchestrationStatusAssignedVnf(execution);
+
+ verify(aaiVnfResources, times(1)).updateOrchestrationStatusVnf(genericVnf, OrchestrationStatus.ASSIGNED);
+ }
+
+ @Test
+ public void updateOrchestrationStatusAssignedVnfExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ doThrow(RuntimeException.class).when(aaiVnfResources).updateOrchestrationStatusVnf(genericVnf,
+ OrchestrationStatus.ASSIGNED);
+
+ aaiUpdateTasks.updateOrchestrationStatusAssignedVnf(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusActiveVnfTest() throws Exception {
+ doNothing().when(aaiVnfResources).updateOrchestrationStatusVnf(genericVnf, OrchestrationStatus.ACTIVE);
+
+ aaiUpdateTasks.updateOrchestrationStatusActiveVnf(execution);
+
+ verify(aaiVnfResources, times(1)).updateOrchestrationStatusVnf(genericVnf, OrchestrationStatus.ACTIVE);
+ }
+
+ @Test
+ public void updateOrchestrationStatusActiveVnfExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ doThrow(RuntimeException.class).when(aaiVnfResources).updateOrchestrationStatusVnf(genericVnf,
+ OrchestrationStatus.ACTIVE);
+
+ aaiUpdateTasks.updateOrchestrationStatusActiveVnf(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusAssignVfModuleTest() throws Exception {
+ doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.ASSIGNED);
+ aaiUpdateTasks.updateOrchestrationStatusAssignedVfModule(execution);
+ verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.ASSIGNED);
+ assertEquals("", vfModule.getHeatStackId());
+ }
+
+ @Test
+ public void updateOrchestrationStatusAssignVfModuleExceptionTest() throws Exception {
+ doThrow(RuntimeException.class).when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule,
+ genericVnf, OrchestrationStatus.ASSIGNED);
+
+ expectedException.expect(BpmnError.class);
+
+ aaiUpdateTasks.updateOrchestrationStatusAssignedVfModule(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusAssignedOrPendingActivationVfModuleNoMultiStageTest() throws Exception {
+ execution.setVariable("aLaCarte", true);
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setMultiStageDesign("false");
+ genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+ doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.ASSIGNED);
+ aaiUpdateTasks.updateOrchestrationStatusAssignedOrPendingActivationVfModule(execution);
+ verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.ASSIGNED);
+ assertEquals("", vfModule.getHeatStackId());
+ }
+
+ @Test
+ public void updateOrchestrationStatusAssignedOrPendingActivationVfModuleMultiStageButNotAlacarteTest()
+ throws Exception {
+ execution.setVariable("aLaCarte", false);
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setMultiStageDesign("true");
+ genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+ doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.ASSIGNED);
+ aaiUpdateTasks.updateOrchestrationStatusAssignedOrPendingActivationVfModule(execution);
+ verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.ASSIGNED);
+ assertEquals("", vfModule.getHeatStackId());
+ }
+
+ @Test
+ public void updateOrchestrationStatusAssignedOrPendingActivationVfModuleWithMultiStageTest() throws Exception {
+ execution.setVariable("aLaCarte", true);
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setMultiStageDesign("true");
+ genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+ doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.PENDING_ACTIVATION);
+ aaiUpdateTasks.updateOrchestrationStatusAssignedOrPendingActivationVfModule(execution);
+ verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.PENDING_ACTIVATION);
+ assertEquals("", vfModule.getHeatStackId());
+ }
+
+ @Test
+ public void updateOrchestrationStatusAssignedOrPendingActivationVfModuleExceptionTest() throws Exception {
+ execution.setVariable("aLaCarte", true);
+ doThrow(RuntimeException.class).when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule,
+ genericVnf, OrchestrationStatus.ASSIGNED);
+
+ expectedException.expect(BpmnError.class);
+
+ aaiUpdateTasks.updateOrchestrationStatusAssignedOrPendingActivationVfModule(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusCreatedVfModuleTest() throws Exception {
+ doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.CREATED);
+ aaiUpdateTasks.updateOrchestrationStatusCreatedVfModule(execution);
+ verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.CREATED);
+ }
+
+ @Test
+ public void updateOrchestrationStatusCreatedVfModuleExceptionTest() throws Exception {
+ doThrow(RuntimeException.class).when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule,
+ genericVnf, OrchestrationStatus.CREATED);
+
+ expectedException.expect(BpmnError.class);
+
+ aaiUpdateTasks.updateOrchestrationStatusCreatedVfModule(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusPendingActivatefModuleTest() throws Exception {
+ doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.PENDING_ACTIVATION);
+
+ aaiUpdateTasks.updateOrchestrationStatusPendingActivationVfModule(execution);
+
+ verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.PENDING_ACTIVATION);
+ }
+
+ @Test
+ public void updateOrchestrationStatusPendingActivatefModuleExceptionTest() throws Exception {
+ doThrow(RuntimeException.class).when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule,
+ genericVnf, OrchestrationStatus.PENDING_ACTIVATION);
+
+ expectedException.expect(BpmnError.class);
+
+ aaiUpdateTasks.updateOrchestrationStatusPendingActivationVfModule(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusDectivateVfModuleTest() throws Exception {
+ doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.CREATED);
+
+ aaiUpdateTasks.updateOrchestrationStatusDeactivateVfModule(execution);
+
+ verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.CREATED);
+ }
+
+ @Test
+ public void updateOrchestrationStatusDectivateVfModuleExceptionTest() throws Exception {
+ doThrow(RuntimeException.class).when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule,
+ genericVnf, OrchestrationStatus.CREATED);
+
+ expectedException.expect(BpmnError.class);
+
+ aaiUpdateTasks.updateOrchestrationStatusDeactivateVfModule(execution);
+ }
+
+ @Test
+ public void updateHeatStackIdVfModuleTest() throws Exception {
+ execution.setVariable("heatStackId", "newHeatStackId");
+ doNothing().when(aaiVfModuleResources).updateHeatStackIdVfModule(vfModule, genericVnf);
+
+ aaiUpdateTasks.updateHeatStackIdVfModule(execution);
+
+ verify(aaiVfModuleResources, times(1)).updateHeatStackIdVfModule(vfModule, genericVnf);
+ assertEquals("newHeatStackId", vfModule.getHeatStackId());
+ }
+
+ @Test
+ public void updateHeatStackIdVfModuleToNullTest() throws Exception {
+ execution.setVariable("heatStackId", null);
+ doNothing().when(aaiVfModuleResources).updateHeatStackIdVfModule(vfModule, genericVnf);
+
+ aaiUpdateTasks.updateHeatStackIdVfModule(execution);
+
+ verify(aaiVfModuleResources, times(1)).updateHeatStackIdVfModule(vfModule, genericVnf);
+ assertEquals(vfModule.getHeatStackId(), "");
+ }
+
+ @Test
+ public void updateHeatStackIdVfModuleExceptionTest() throws Exception {
+ doThrow(RuntimeException.class).when(aaiVfModuleResources).updateHeatStackIdVfModule(vfModule, genericVnf);
+
+ expectedException.expect(BpmnError.class);
+
+ aaiUpdateTasks.updateHeatStackIdVfModule(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusActiveVolumeGroupTest() throws Exception {
+ doNothing().when(aaiVolumeGroupResources).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion,
+ OrchestrationStatus.ACTIVE);
+
+ aaiUpdateTasks.updateOrchestrationStatusActiveVolumeGroup(execution);
+
+ verify(aaiVolumeGroupResources, times(1)).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion,
+ OrchestrationStatus.ACTIVE);
+ }
+
+ @Test
+ public void updateOrchestrationStatusActiveVolumeGroupExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(aaiVolumeGroupResources).updateOrchestrationStatusVolumeGroup(volumeGroup,
+ cloudRegion, OrchestrationStatus.ACTIVE);
+ aaiUpdateTasks.updateOrchestrationStatusActiveVolumeGroup(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusCreatedVolumeGroupTest() throws Exception {
+ doNothing().when(aaiVolumeGroupResources).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion,
+ OrchestrationStatus.CREATED);
+
+ aaiUpdateTasks.updateOrchestrationStatusCreatedVolumeGroup(execution);
+
+ verify(aaiVolumeGroupResources, times(1)).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion,
+ OrchestrationStatus.CREATED);
+ }
+
+ @Test
+ public void updateOrchestrationStatusCreatedVolumeGroupExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(aaiVolumeGroupResources).updateOrchestrationStatusVolumeGroup(volumeGroup,
+ cloudRegion, OrchestrationStatus.CREATED);
+ aaiUpdateTasks.updateOrchestrationStatusCreatedVolumeGroup(execution);
+ }
+
+ @Test
+ public void test_updateOrchestrationStatusAssignedVolumeGroup() throws Exception {
+ doNothing().when(aaiVolumeGroupResources).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion,
+ OrchestrationStatus.ASSIGNED);
+
+ aaiUpdateTasks.updateOrchestrationStatusAssignedVolumeGroup(execution);
+
+ verify(aaiVolumeGroupResources, times(1)).updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion,
+ OrchestrationStatus.ASSIGNED);
+ assertEquals("", volumeGroup.getHeatStackId());
+ }
+
+ @Test
+ public void test_updateOrchestrationStatusAssignedVolumeGroup_exception() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(aaiVolumeGroupResources).updateOrchestrationStatusVolumeGroup(volumeGroup,
+ cloudRegion, OrchestrationStatus.ASSIGNED);
+ aaiUpdateTasks.updateOrchestrationStatusAssignedVolumeGroup(execution);
+ }
+
+ @Test
+ public void updateHeatStackIdVolumeGroupTest() throws Exception {
+ execution.setVariable("heatStackId", "newHeatStackId");
+ doNothing().when(aaiVolumeGroupResources).updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
+
+ aaiUpdateTasks.updateHeatStackIdVolumeGroup(execution);
+
+ verify(aaiVolumeGroupResources, times(1)).updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
+ assertEquals("newHeatStackId", volumeGroup.getHeatStackId());
+ }
+
+ @Test
+ public void updateHeatStackIdVolumeGroupToNullTest() throws Exception {
+ execution.setVariable("heatStackId", null);
+ doNothing().when(aaiVolumeGroupResources).updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
+
+ aaiUpdateTasks.updateHeatStackIdVolumeGroup(execution);
+
+ verify(aaiVolumeGroupResources, times(1)).updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
+ assertEquals(volumeGroup.getHeatStackId(), "");
+ }
+
+ @Test
+ public void updateHeatStackIdVolumeGroupExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(aaiVolumeGroupResources).updateHeatStackIdVolumeGroup(volumeGroup,
+ cloudRegion);
+ aaiUpdateTasks.updateHeatStackIdVolumeGroup(execution);
+ }
+
+ @Test
+ public void updateNetworkExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ doThrow(RuntimeException.class).when(aaiNetworkResources).updateNetwork(network);
+
+ aaiUpdateTasks.updateNetwork(execution, OrchestrationStatus.ACTIVE);
+ }
+
+ @Test
+ public void updateOstatusActivedNetworkCollectionTest() throws Exception {
+ doNothing().when(aaiCollectionResources).updateCollection(serviceInstance.getCollection());
+ aaiUpdateTasks.updateOrchestrationStatusActiveNetworkCollection(execution);
+ verify(aaiCollectionResources, times(1)).updateCollection(serviceInstance.getCollection());
+ }
+
+ @Test
+ public void updateOstatusActiveNetworkColectionExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(aaiCollectionResources).updateCollection(serviceInstance.getCollection());
+ aaiUpdateTasks.updateOrchestrationStatusActiveNetworkCollection(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusActivateVfModuleTest() throws Exception {
+ doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.ACTIVE);
+
+ aaiUpdateTasks.updateOrchestrationStatusActivateVfModule(execution);
+
+ verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.ACTIVE);
+ }
+
+ @Test
+ public void updateOrchestrationStatusActivateVfModuleExceptionTest() throws Exception {
+ doThrow(RuntimeException.class).when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule,
+ genericVnf, OrchestrationStatus.ACTIVE);
+
+ expectedException.expect(BpmnError.class);
+
+ aaiUpdateTasks.updateOrchestrationStatusActivateVfModule(execution);
+ }
+
+ @Test
+ public void updateNetworkCreatedTest() throws Exception {
+ CreateNetworkResponse createNetworkResponse = new CreateNetworkResponse();
+ createNetworkResponse.setNetworkFqdn("testNetworkFqdn");
+ createNetworkResponse.setNetworkStackId("testNetworkStackId");
+ HashMap<String, String> subnetMap = new HashMap<>();
+ subnetMap.put("testSubnetId", "testNeutronSubnetId");
+ createNetworkResponse.setSubnetMap(subnetMap);
+
+ network.getSubnets().add(subnet);
+
+ execution.setVariable("createNetworkResponse", createNetworkResponse);
+
+ doNothing().when(aaiNetworkResources).updateNetwork(network);
+ doNothing().when(aaiNetworkResources).updateSubnet(network, subnet);
+
+ aaiUpdateTasks.updateNetworkCreated(execution);
+ verify(aaiNetworkResources, times(1)).updateNetwork(network);
+ verify(aaiNetworkResources, times(1)).updateSubnet(network, subnet);
+
+ assertEquals(createNetworkResponse.getNetworkFqdn(), network.getContrailNetworkFqdn());
+ assertEquals(OrchestrationStatus.CREATED, network.getOrchestrationStatus());
+ assertEquals(createNetworkResponse.getNetworkStackId(), network.getHeatStackId());
+ assertEquals(createNetworkResponse.getNeutronNetworkId(), network.getNeutronNetworkId());
+ String neutronSubnetId = createNetworkResponse.getSubnetMap().entrySet().iterator().next().getValue();
+ assertEquals(neutronSubnetId, network.getSubnets().get(0).getNeutronSubnetId());
+ }
+
+ @Test
+ public void updateNetworkUpdatedTest() throws Exception {
+ UpdateNetworkResponse updateNetworkResponse = new UpdateNetworkResponse();
+ updateNetworkResponse.setNeutronNetworkId("testNeutronNetworkId");
+ HashMap<String, String> subnetMap = new HashMap<>();
+ subnetMap.put("testSubnetId", "testNeutronSubnetId");
+ updateNetworkResponse.setSubnetMap(subnetMap);
+
+ network.getSubnets().add(subnet);
+
+ execution.setVariable("updateNetworkResponse", updateNetworkResponse);
+
+ doNothing().when(aaiNetworkResources).updateNetwork(network);
+ doNothing().when(aaiNetworkResources).updateSubnet(network, subnet);
+
+ aaiUpdateTasks.updateNetworkUpdated(execution);
+ verify(aaiNetworkResources, times(1)).updateNetwork(network);
+ verify(aaiNetworkResources, times(1)).updateSubnet(network, subnet);
+
+ String neutronSubnetId = updateNetworkResponse.getSubnetMap().entrySet().iterator().next().getValue();
+ assertEquals(neutronSubnetId, network.getSubnets().get(0).getNeutronSubnetId());
+ }
+
+ @Test
+ public void updateOrchestrationStatusNetworkTest() {
+ AAIUpdateTasks spy = Mockito.spy(new AAIUpdateTasks());
+ doNothing().when(spy).updateNetwork(eq(execution), any());
+ spy.updateOrchestrationStatusActiveNetwork(execution);
+ verify(spy, times(1)).updateNetwork(execution, OrchestrationStatus.ACTIVE);
+ spy.updateOrchestrationStatusAssignedNetwork(execution);
+ verify(spy, times(1)).updateNetwork(execution, OrchestrationStatus.ASSIGNED);
+ spy.updateOrchestrationStatusCreatedNetwork(execution);
+ verify(spy, times(1)).updateNetwork(execution, OrchestrationStatus.CREATED);
+ }
+
+ @Test
+ public void updateNetworkAAITest() {
+
+ L3Network spy = spy(new L3Network());
+ L3Network shallowCopy = mock(L3Network.class);
+ Subnet mockSubnet = mock(Subnet.class);
+ Subnet shallowCopySubnet = mock(Subnet.class);
+ when(mockSubnet.shallowCopyId()).thenReturn(shallowCopySubnet);
+ doReturn(shallowCopy).when(spy).shallowCopyId();
+
+ doNothing().when(aaiNetworkResources).updateNetwork(network);
+ doNothing().when(aaiNetworkResources).updateSubnet(network, subnet);
+
+ spy.getSubnets().add(mockSubnet);
+ aaiUpdateTasks.updateNetworkAAI(spy, OrchestrationStatus.CREATED);
+
+ verify(shallowCopy, times(1)).setOrchestrationStatus(OrchestrationStatus.CREATED);
+ verify(spy, times(1)).setOrchestrationStatus(OrchestrationStatus.CREATED);
+ verify(shallowCopySubnet, times(1)).setOrchestrationStatus(OrchestrationStatus.CREATED);
+ }
+
+ @Test
+ public void updateNetworkCreatedkExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(aaiNetworkResources).updateNetwork(network);
+ aaiUpdateTasks.updateNetworkCreated(execution);
+ }
+
+ @Test
+ public void updateObjectNetworkTest() {
+ doNothing().when(aaiNetworkResources).updateNetwork(network);
+
+ aaiUpdateTasks.updateObjectNetwork(execution);
+
+ verify(aaiNetworkResources, times(1)).updateNetwork(network);
+ }
+
+ @Test
+ public void updateObjectNetworkExceptionText() {
+ expectedException.expect(BpmnError.class);
+
+ doThrow(RuntimeException.class).when(aaiNetworkResources).updateNetwork(network);
+
+ aaiUpdateTasks.updateObjectNetwork(execution);
+ }
+
+ @Test
+ public void test_updateServiceInstance() {
+ doNothing().when(aaiServiceInstanceResources).updateServiceInstance(serviceInstance);
+ aaiUpdateTasks.updateServiceInstance(execution);
+ verify(aaiServiceInstanceResources, times(1)).updateServiceInstance(serviceInstance);
+ }
+
+ @Test
+ public void test_updateServiceInstance_exception() {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(aaiServiceInstanceResources).updateServiceInstance(serviceInstance);
+ aaiUpdateTasks.updateServiceInstance(execution);
+ }
+
+ @Test
+ public void updateObjectVnfTest() {
+ doNothing().when(aaiVnfResources).updateObjectVnf(genericVnf);
+
+ aaiUpdateTasks.updateObjectVnf(execution);
+
+ verify(aaiVnfResources, times(1)).updateObjectVnf(genericVnf);
+ }
+
+ @Test
+ public void updateObjectVnfExceptionTest() {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(aaiVnfResources).updateObjectVnf(genericVnf);
+ aaiUpdateTasks.updateObjectVnf(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusDeleteVfModuleTest() throws Exception {
+ doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.ASSIGNED);
+
+ aaiUpdateTasks.updateOrchestrationStatusDeleteVfModule(execution);
+
+ verify(aaiVfModuleResources, times(1)).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.ASSIGNED);
+ assertEquals("", vfModule.getHeatStackId());
+ }
+
+ @Test
+ public void updateModelVfModuleTest() {
+ doNothing().when(aaiVfModuleResources).changeAssignVfModule(vfModule, genericVnf);
+ aaiUpdateTasks.updateModelVfModule(execution);
+ verify(aaiVfModuleResources, times(1)).changeAssignVfModule(vfModule, genericVnf);
+ }
+
+ @Test
+ public void updateModelVfModuleExceptionTest() {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(aaiVfModuleResources).changeAssignVfModule(vfModule, genericVnf);
+ aaiUpdateTasks.updateModelVfModule(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusDeactivateFabricConfigurationTest() throws Exception {
+ gBBInput = execution.getGeneralBuildingBlock();
+ doNothing().when(aaiConfigurationResources).updateOrchestrationStatusConfiguration(configuration,
+ OrchestrationStatus.ASSIGNED);
+
+ aaiUpdateTasks.updateOrchestrationStatusDeactivateFabricConfiguration(execution);
+
+ verify(aaiConfigurationResources, times(1)).updateOrchestrationStatusConfiguration(configuration,
+ OrchestrationStatus.ASSIGNED);
+ }
+
+ @Test
+ public void updateOrchestrationStatusActivateFabricConfigurationTest() throws Exception {
+ gBBInput = execution.getGeneralBuildingBlock();
+ doNothing().when(aaiConfigurationResources).updateOrchestrationStatusConfiguration(configuration,
+ OrchestrationStatus.ACTIVE);
+
+ aaiUpdateTasks.updateOrchestrationStatusActivateFabricConfiguration(execution);
+
+ verify(aaiConfigurationResources, times(1)).updateOrchestrationStatusConfiguration(configuration,
+ OrchestrationStatus.ACTIVE);
+ }
+
+ @Test
+ public void updateContrailServiceInstanceFqdnVfModuleTest() throws Exception {
+ execution.setVariable("contrailServiceInstanceFqdn", "newContrailServiceInstanceFqdn");
+ doNothing().when(aaiVfModuleResources).updateContrailServiceInstanceFqdnVfModule(vfModule, genericVnf);
+
+ aaiUpdateTasks.updateContrailServiceInstanceFqdnVfModule(execution);
+
+ verify(aaiVfModuleResources, times(1)).updateContrailServiceInstanceFqdnVfModule(vfModule, genericVnf);
+ assertEquals("newContrailServiceInstanceFqdn", vfModule.getContrailServiceInstanceFqdn());
+ }
+
+ @Test
+ public void updateContrailServiceInstanceFqdnVfModuleNoUpdateTest() throws Exception {
+ aaiUpdateTasks.updateContrailServiceInstanceFqdnVfModule(execution);
+ verify(aaiVfModuleResources, times(0)).updateContrailServiceInstanceFqdnVfModule(vfModule, genericVnf);
+ }
+
+ @Test
+ public void updateIpv4OamAddressVnfTest() throws Exception {
+ execution.setVariable("oamManagementV4Address", "newIpv4OamAddress");
+ doNothing().when(aaiVnfResources).updateObjectVnf(genericVnf);
+
+ aaiUpdateTasks.updateIpv4OamAddressVnf(execution);
+
+ verify(aaiVnfResources, times(1)).updateObjectVnf(genericVnf);
+ assertEquals("newIpv4OamAddress", genericVnf.getIpv4OamAddress());
+ }
+
+ @Test
+ public void updateIpv4OamAddressVnfNoUpdateTest() throws Exception {
+ aaiUpdateTasks.updateIpv4OamAddressVnf(execution);
+ verify(aaiVnfResources, times(0)).updateObjectVnf(genericVnf);
+ }
+
+ @Test
+ public void updateManagementV6AddressVnfTest() throws Exception {
+ execution.setVariable("oamManagementV6Address", "newManagementV6Address");
+ doNothing().when(aaiVnfResources).updateObjectVnf(genericVnf);
+
+ aaiUpdateTasks.updateManagementV6AddressVnf(execution);
+
+ verify(aaiVnfResources, times(1)).updateObjectVnf(genericVnf);
+ assertEquals("newManagementV6Address", genericVnf.getManagementV6Address());
+ }
+
+ @Test
+ public void updateManagementV6AddressVnfNoUpdateTest() throws Exception {
+ aaiUpdateTasks.updateManagementV6AddressVnf(execution);
+ verify(aaiVnfResources, times(0)).updateObjectVnf(genericVnf);
+ }
+
+ @Test
+ public void updateOrchestrationStatusVnfConfigureTest() throws Exception {
+ doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.CONFIGURE);
+
+ aaiUpdateTasks.updateOrchestrationStausConfigDeployConfigureVnf(execution);
+ }
+
+ @Test
+ public void updateOrchestrationStatusVnfConfiguredTest() throws Exception {
+ doNothing().when(aaiVfModuleResources).updateOrchestrationStatusVfModule(vfModule, genericVnf,
+ OrchestrationStatus.CONFIGURED);
+
+ aaiUpdateTasks.updateOrchestrationStausConfigDeployConfiguredVnf(execution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivityTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivityTest.java
index ee7a9ad952..56ff813e73 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivityTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivityTest.java
@@ -22,14 +22,11 @@ package org.onap.so.bpmn.infrastructure.activity;
import static org.junit.Assert.assertEquals;
-
import java.nio.file.Files;
import java.nio.file.Paths;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
import org.junit.Before;
-
import org.junit.Test;
import org.mockito.InjectMocks;
import org.onap.so.bpmn.BaseTaskTest;
@@ -38,40 +35,41 @@ import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
import org.springframework.beans.factory.annotation.Autowired;
public class ExecuteActivityTest extends BaseTaskTest {
- @InjectMocks
- protected ExecuteActivity executeActivity = new ExecuteActivity();
-
- private DelegateExecution execution;
-
- @Before
- public void before() throws Exception {
- execution = new DelegateExecutionFake();
- execution.setVariable("vnfType", "testVnfType");
- execution.setVariable("requestAction", "testRequestAction");
- execution.setVariable("mso-request-id", "testMsoRequestId");
- execution.setVariable("vnfId", "testVnfId");
- execution.setVariable("serviceInstanceId", "testServiceInstanceId");
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- }
-
- @Test
- public void buildBuildingBlock_Test(){
- BuildingBlock bb = executeActivity.buildBuildingBlock("testActivityName");
- assertEquals(bb.getBpmnFlowName(), "testActivityName");
- assertEquals(bb.getKey(), "");
- }
-
- @Test
- public void executeBuildingBlock_Test() throws Exception {
- BuildingBlock bb = executeActivity.buildBuildingBlock("testActivityName");
- ExecuteBuildingBlock ebb = executeActivity.buildExecuteBuildingBlock(execution, "testMsoRequestId", bb);
- assertEquals(ebb.getVnfType(), "testVnfType");
- assertEquals(ebb.getRequestAction(), "testRequestAction");
- assertEquals(ebb.getRequestId(), "testMsoRequestId");
- assertEquals(ebb.getWorkflowResourceIds().getVnfId(), "testVnfId");
- assertEquals(ebb.getWorkflowResourceIds().getServiceInstanceId(), "testServiceInstanceId");
- assertEquals(ebb.getBuildingBlock(), bb);
- }
-
+ @InjectMocks
+ protected ExecuteActivity executeActivity = new ExecuteActivity();
+
+ private DelegateExecution execution;
+
+ @Before
+ public void before() throws Exception {
+ execution = new DelegateExecutionFake();
+ execution.setVariable("vnfType", "testVnfType");
+ execution.setVariable("requestAction", "testRequestAction");
+ execution.setVariable("mso-request-id", "testMsoRequestId");
+ execution.setVariable("vnfId", "testVnfId");
+ execution.setVariable("serviceInstanceId", "testServiceInstanceId");
+ String bpmnRequest =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ }
+
+ @Test
+ public void buildBuildingBlock_Test() {
+ BuildingBlock bb = executeActivity.buildBuildingBlock("testActivityName");
+ assertEquals(bb.getBpmnFlowName(), "testActivityName");
+ assertEquals(bb.getKey(), "");
+ }
+
+ @Test
+ public void executeBuildingBlock_Test() throws Exception {
+ BuildingBlock bb = executeActivity.buildBuildingBlock("testActivityName");
+ ExecuteBuildingBlock ebb = executeActivity.buildExecuteBuildingBlock(execution, "testMsoRequestId", bb);
+ assertEquals(ebb.getVnfType(), "testVnfType");
+ assertEquals(ebb.getRequestAction(), "testRequestAction");
+ assertEquals(ebb.getRequestId(), "testMsoRequestId");
+ assertEquals(ebb.getWorkflowResourceIds().getVnfId(), "testVnfId");
+ assertEquals(ebb.getWorkflowResourceIds().getServiceInstanceId(), "testServiceInstanceId");
+ assertEquals(ebb.getBuildingBlock(), bb);
+ }
+
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasksTest.java
index 72f6a08ee7..00dfd4e236 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasksTest.java
@@ -27,10 +27,8 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.util.Map;
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
@@ -47,61 +45,69 @@ import org.onap.so.bpmn.servicedecomposition.generalobjects.OrchestrationContext
import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
import org.onap.so.client.exception.BBObjectNotFoundException;
-public class NetworkAdapterCreateTasksTest extends BaseTaskTest{
- @InjectMocks
- private NetworkAdapterCreateTasks networkAdapterCreateTasks = new NetworkAdapterCreateTasks();
+public class NetworkAdapterCreateTasksTest extends BaseTaskTest {
+ @InjectMocks
+ private NetworkAdapterCreateTasks networkAdapterCreateTasks = new NetworkAdapterCreateTasks();
+
+ private ServiceInstance serviceInstance;
+ private RequestContext requestContext;
+ private CloudRegion cloudRegion;
+ private OrchestrationContext orchestrationContext;
+ private L3Network l3Network;
+ private Map<String, String> userInput;
+ private Customer customer;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ customer = setCustomer();
+ serviceInstance = setServiceInstance();
+ l3Network = setL3Network();
+ userInput = setUserInput();
+ userInput.put("userInputKey1", "userInputValue1");
+ requestContext = setRequestContext();
+ cloudRegion = setCloudRegion();
+ orchestrationContext = setOrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+
+
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(l3Network);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
- private ServiceInstance serviceInstance;
- private RequestContext requestContext;
- private CloudRegion cloudRegion;
- private OrchestrationContext orchestrationContext;
- private L3Network l3Network;
- private Map<String, String> userInput;
- private Customer customer;
+ }
- @Before
- public void before() throws BBObjectNotFoundException {
- customer = setCustomer();
- serviceInstance = setServiceInstance();
- l3Network = setL3Network();
- userInput = setUserInput();
- userInput.put("userInputKey1", "userInputValue1");
- requestContext = setRequestContext();
- cloudRegion = setCloudRegion();
- orchestrationContext = setOrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
-
+ @Test
+ public void createNetworkTest() throws Exception {
+ String cloudRegionPo = "cloudRegionPo";
+ CreateNetworkRequest createNetworkRequest = new CreateNetworkRequest();
+ execution.setVariable("cloudRegionPo", cloudRegionPo);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(l3Network);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
-
- }
-
- @Test
- public void createNetworkTest() throws Exception {
- String cloudRegionPo = "cloudRegionPo";
- CreateNetworkRequest createNetworkRequest = new CreateNetworkRequest();
- execution.setVariable("cloudRegionPo", cloudRegionPo);
+ doReturn(createNetworkRequest).when(networkAdapterObjectMapper).createNetworkRequestMapper(
+ isA(RequestContext.class), isA(CloudRegion.class), isA(OrchestrationContext.class),
+ isA(ServiceInstance.class), isA(L3Network.class), isA(Map.class), isA(String.class),
+ isA(Customer.class));
+ networkAdapterCreateTasks.createNetwork(execution);
+ verify(networkAdapterObjectMapper, times(1)).createNetworkRequestMapper(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, customer);
+ assertEquals(createNetworkRequest, execution.getVariable("networkAdapterRequest"));
+ }
- doReturn(createNetworkRequest).when(networkAdapterObjectMapper).createNetworkRequestMapper(isA(RequestContext.class), isA(CloudRegion.class), isA(OrchestrationContext.class), isA(ServiceInstance.class), isA(L3Network.class), isA(Map.class), isA(String.class), isA(Customer.class));
- networkAdapterCreateTasks.createNetwork(execution);
- verify(networkAdapterObjectMapper, times(1)).createNetworkRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, customer);
- assertEquals(createNetworkRequest, execution.getVariable("networkAdapterRequest"));
- }
-
- @Test
- public void rollbackCreateNetworkTest() throws Exception {
- CreateNetworkResponse createNetworkResponse = new CreateNetworkResponse();
- createNetworkResponse.setNetworkStackId("networkStackId");
- createNetworkResponse.setNetworkCreated(true);
- execution.setVariable("createNetworkResponse", createNetworkResponse);
- Optional<CreateNetworkResponse> oCreateNetworkResponse = Optional.of(createNetworkResponse);
+ @Test
+ public void rollbackCreateNetworkTest() throws Exception {
+ CreateNetworkResponse createNetworkResponse = new CreateNetworkResponse();
+ createNetworkResponse.setNetworkStackId("networkStackId");
+ createNetworkResponse.setNetworkCreated(true);
+ execution.setVariable("createNetworkResponse", createNetworkResponse);
+ Optional<CreateNetworkResponse> oCreateNetworkResponse = Optional.of(createNetworkResponse);
- String cloudRegionPo = "cloudRegionPo";
- execution.setVariable("cloudRegionPo", cloudRegionPo);
+ String cloudRegionPo = "cloudRegionPo";
+ execution.setVariable("cloudRegionPo", cloudRegionPo);
- doReturn(oCreateNetworkResponse).when(networkAdapterResources).rollbackCreateNetwork(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, createNetworkResponse);
- networkAdapterCreateTasks.rollbackCreateNetwork(execution);
- verify(networkAdapterResources, times(1)).rollbackCreateNetwork(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, createNetworkResponse);
- }
+ doReturn(oCreateNetworkResponse).when(networkAdapterResources).rollbackCreateNetwork(requestContext,
+ cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo,
+ createNetworkResponse);
+ networkAdapterCreateTasks.rollbackCreateNetwork(execution);
+ verify(networkAdapterResources, times(1)).rollbackCreateNetwork(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, createNetworkResponse);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasksTest.java
index ceb4796443..eb481651f0 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasksTest.java
@@ -27,9 +27,7 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.io.UnsupportedEncodingException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -48,44 +46,48 @@ import org.onap.so.client.adapter.network.NetworkAdapterClientException;
import org.onap.so.client.exception.BBObjectNotFoundException;
-public class NetworkAdapterDeleteTasksTest extends BaseTaskTest{
-
- @InjectMocks
- private NetworkAdapterDeleteTasks networkAdapterDeleteTasks = new NetworkAdapterDeleteTasks();
+public class NetworkAdapterDeleteTasksTest extends BaseTaskTest {
+
+ @InjectMocks
+ private NetworkAdapterDeleteTasks networkAdapterDeleteTasks = new NetworkAdapterDeleteTasks();
- private ServiceInstance serviceInstance;
- private L3Network l3Network;
- private RequestContext requestContext;
- private CloudRegion cloudRegion;
+ private ServiceInstance serviceInstance;
+ private L3Network l3Network;
+ private RequestContext requestContext;
+ private CloudRegion cloudRegion;
- @Before
- public void before() throws BBObjectNotFoundException {
- serviceInstance = setServiceInstance();
- l3Network = setL3Network();
- requestContext = setRequestContext();
- cloudRegion = setCloudRegion();
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ serviceInstance = setServiceInstance();
+ l3Network = setL3Network();
+ requestContext = setRequestContext();
+ cloudRegion = setCloudRegion();
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(l3Network);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- }
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(l3Network);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ }
- @Test
- public void test_deleteNetwork() throws UnsupportedEncodingException, NetworkAdapterClientException {
- DeleteNetworkRequest deleteNetworkRequest = new DeleteNetworkRequest();
- doReturn(deleteNetworkRequest).when(networkAdapterObjectMapper).deleteNetworkRequestMapper(requestContext, cloudRegion, serviceInstance, l3Network);
+ @Test
+ public void test_deleteNetwork() throws UnsupportedEncodingException, NetworkAdapterClientException {
+ DeleteNetworkRequest deleteNetworkRequest = new DeleteNetworkRequest();
+ doReturn(deleteNetworkRequest).when(networkAdapterObjectMapper).deleteNetworkRequestMapper(requestContext,
+ cloudRegion, serviceInstance, l3Network);
- networkAdapterDeleteTasks.deleteNetwork(execution);
- verify(networkAdapterObjectMapper, times(1)).deleteNetworkRequestMapper(requestContext, cloudRegion, serviceInstance, l3Network);
- }
+ networkAdapterDeleteTasks.deleteNetwork(execution);
+ verify(networkAdapterObjectMapper, times(1)).deleteNetworkRequestMapper(requestContext, cloudRegion,
+ serviceInstance, l3Network);
+ }
- @Test
- public void test_deleteNetwork_exception() throws UnsupportedEncodingException, NetworkAdapterClientException {
- expectedException.expect(BpmnError.class);
+ @Test
+ public void test_deleteNetwork_exception() throws UnsupportedEncodingException, NetworkAdapterClientException {
+ expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(networkAdapterObjectMapper).
- deleteNetworkRequestMapper(any(RequestContext.class), any(CloudRegion.class), any(ServiceInstance.class), eq(l3Network));
- networkAdapterDeleteTasks.deleteNetwork(execution);
- }
+ doThrow(RuntimeException.class).when(networkAdapterObjectMapper).deleteNetworkRequestMapper(
+ any(RequestContext.class), any(CloudRegion.class), any(ServiceInstance.class), eq(l3Network));
+ networkAdapterDeleteTasks.deleteNetwork(execution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1Test.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1Test.java
index c11dc822b4..d0cee42178 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1Test.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1Test.java
@@ -23,15 +23,12 @@ package org.onap.so.bpmn.infrastructure.adapter.network.tasks;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
-
import javax.xml.bind.JAXBException;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
import org.junit.Before;
import org.junit.Test;
-
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.onap.so.adapters.nwrest.CreateNetworkResponse;
@@ -42,7 +39,6 @@ import org.onap.so.bpmn.BaseTaskTest;
import org.onap.so.client.exception.BadResponseException;
import org.onap.so.client.exception.ExceptionBuilder;
import org.onap.so.client.exception.MapperException;
-
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
@@ -55,69 +51,74 @@ import static org.mockito.Mockito.verify;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
public class NetworkAdapterRestV1Test extends BaseTaskTest {
-
- @InjectMocks
- NetworkAdapterRestV1 networkAdapterRestV1Tasks = new NetworkAdapterRestV1();
- @Mock
- ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
- @Before
- public void setup(){
- delegateExecution = new DelegateExecutionFake();
- }
-
- @Test
- public void testUnmarshalXml() throws IOException, JAXBException {
- String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><createNetworkResponse><messageId>ec37c121-e3ec-4697-8adf-2d7dca7044fc</messageId><networkCreated>true</networkCreated><networkFqdn>someNetworkFqdn</networkFqdn><networkId>991ec7bf-c9c4-4ac1-bb9c-4b61645bddb3</networkId><networkStackId>someStackId</networkStackId><neutronNetworkId>9c47521a-2916-4018-b2bc-71ab767497e3</neutronNetworkId><rollback><cloudId>someCloudId</cloudId><modelCustomizationUuid>b7171cdd-8b05-459b-80ef-2093150e8983</modelCustomizationUuid><msoRequest><requestId>90b32315-176e-4dab-bcf1-80eb97a1c4f4</requestId><serviceInstanceId>71e7db22-7907-4d78-8fcc-8d89d28e90be</serviceInstanceId></msoRequest><networkCreated>true</networkCreated><networkStackId>someStackId</networkStackId><networkType>SomeNetworkType</networkType><neutronNetworkId>9c47521a-2916-4018-b2bc-71ab767497e3</neutronNetworkId><tenantId>b60da4f71c1d4b35b8113d4eca6deaa1</tenantId></rollback><subnetMap><entry><key>6b381fa9-48ce-4e16-9978-d75309565bb6</key><value>bc1d5537-860b-4894-8eba-6faff41e648c</value></entry></subnetMap></createNetworkResponse>";
- CreateNetworkResponse response = (CreateNetworkResponse) new NetworkAdapterRestV1().unmarshalXml(xml, CreateNetworkResponse.class);
- String returnedXml = response.toXmlString();
- System.out.println(returnedXml);
- }
-
- @Test
- public void testUnmarshalXmlUpdate() throws IOException, JAXBException {
- UpdateNetworkResponse expectedResponse = new UpdateNetworkResponse();
- expectedResponse.setMessageId("ec100bcc-2659-4aa4-b4d8-3255715c2a51");
- expectedResponse.setNetworkId("80de31e3-cc78-4111-a9d3-5b92bf0a39eb");
- Map<String,String>subnetMap = new HashMap<String,String>();
- subnetMap.put("95cd8437-25f1-4238-8720-cbfe7fa81476", "d8d16606-5d01-4822-b160-9a0d257303e0");
- expectedResponse.setSubnetMap(subnetMap);
- String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><updateNetworkResponse><messageId>ec100bcc-2659-4aa4-b4d8-3255715c2a51</messageId><networkId>80de31e3-cc78-4111-a9d3-5b92bf0a39eb</networkId><subnetMap><entry><key>95cd8437-25f1-4238-8720-cbfe7fa81476</key><value>d8d16606-5d01-4822-b160-9a0d257303e0</value></entry></subnetMap></updateNetworkResponse>";
- UpdateNetworkResponse response = (UpdateNetworkResponse) new NetworkAdapterRestV1().unmarshalXml(xml, UpdateNetworkResponse.class);
- assertThat(expectedResponse, sameBeanAs(response));
- }
-
- @Test
- public void processCallbackTest() throws MapperException, BadResponseException, IOException{
- UpdateNetworkRequest updateNetworkRequest = new UpdateNetworkRequest();
- UpdateNetworkResponse updateNetworkResponse = new UpdateNetworkResponse();
- updateNetworkResponse.setMessageId("messageId");
- updateNetworkResponse.setNetworkId("networkId");
- delegateExecution.setVariable("networkAdapterRequest", updateNetworkRequest);
- delegateExecution.setVariable("NetworkAResponse_MESSAGE", updateNetworkResponse.toXmlString());
-
- networkAdapterRestV1Tasks.processCallback(delegateExecution);
-
- assertThat(updateNetworkResponse,sameBeanAs(delegateExecution.getVariable("updateNetworkResponse")));
- }
-
- @Test
- public void processCallbackErrorTest() throws MapperException, BadResponseException, IOException{
- UpdateNetworkRequest updateNetworkRequest = new UpdateNetworkRequest();
- UpdateNetworkError updateNetworkResponse = new UpdateNetworkError();
- updateNetworkResponse.setMessageId("messageId");
- updateNetworkResponse.setMessage("test error message");
- delegateExecution.setVariable("networkAdapterRequest", updateNetworkRequest);
- delegateExecution.setVariable("NetworkAResponse_MESSAGE", updateNetworkResponse.toXmlString());
-
- doThrow(new BpmnError("MSOWorkflowException")).when(exceptionBuilder).buildAndThrowWorkflowException(any(DelegateExecution.class), anyInt(), any(String.class));
- try {
- networkAdapterRestV1Tasks.processCallback(delegateExecution);
- }
- catch (BpmnError be){
- assertEquals("MSOWorkflowException",be.getErrorCode());
- }
- assertNull(delegateExecution.getVariable("updateNetworkResponse"));
- verify(exceptionBuilder, times(1)).buildAndThrowWorkflowException(any(DelegateExecution.class), eq(7000), eq("test error message"));
- }
+ @InjectMocks
+ NetworkAdapterRestV1 networkAdapterRestV1Tasks = new NetworkAdapterRestV1();
+ @Mock
+ ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
+
+ @Before
+ public void setup() {
+ delegateExecution = new DelegateExecutionFake();
+ }
+
+ @Test
+ public void testUnmarshalXml() throws IOException, JAXBException {
+ String xml =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><createNetworkResponse><messageId>ec37c121-e3ec-4697-8adf-2d7dca7044fc</messageId><networkCreated>true</networkCreated><networkFqdn>someNetworkFqdn</networkFqdn><networkId>991ec7bf-c9c4-4ac1-bb9c-4b61645bddb3</networkId><networkStackId>someStackId</networkStackId><neutronNetworkId>9c47521a-2916-4018-b2bc-71ab767497e3</neutronNetworkId><rollback><cloudId>someCloudId</cloudId><modelCustomizationUuid>b7171cdd-8b05-459b-80ef-2093150e8983</modelCustomizationUuid><msoRequest><requestId>90b32315-176e-4dab-bcf1-80eb97a1c4f4</requestId><serviceInstanceId>71e7db22-7907-4d78-8fcc-8d89d28e90be</serviceInstanceId></msoRequest><networkCreated>true</networkCreated><networkStackId>someStackId</networkStackId><networkType>SomeNetworkType</networkType><neutronNetworkId>9c47521a-2916-4018-b2bc-71ab767497e3</neutronNetworkId><tenantId>b60da4f71c1d4b35b8113d4eca6deaa1</tenantId></rollback><subnetMap><entry><key>6b381fa9-48ce-4e16-9978-d75309565bb6</key><value>bc1d5537-860b-4894-8eba-6faff41e648c</value></entry></subnetMap></createNetworkResponse>";
+ CreateNetworkResponse response =
+ (CreateNetworkResponse) new NetworkAdapterRestV1().unmarshalXml(xml, CreateNetworkResponse.class);
+ String returnedXml = response.toXmlString();
+ System.out.println(returnedXml);
+ }
+
+ @Test
+ public void testUnmarshalXmlUpdate() throws IOException, JAXBException {
+ UpdateNetworkResponse expectedResponse = new UpdateNetworkResponse();
+ expectedResponse.setMessageId("ec100bcc-2659-4aa4-b4d8-3255715c2a51");
+ expectedResponse.setNetworkId("80de31e3-cc78-4111-a9d3-5b92bf0a39eb");
+ Map<String, String> subnetMap = new HashMap<String, String>();
+ subnetMap.put("95cd8437-25f1-4238-8720-cbfe7fa81476", "d8d16606-5d01-4822-b160-9a0d257303e0");
+ expectedResponse.setSubnetMap(subnetMap);
+ String xml =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><updateNetworkResponse><messageId>ec100bcc-2659-4aa4-b4d8-3255715c2a51</messageId><networkId>80de31e3-cc78-4111-a9d3-5b92bf0a39eb</networkId><subnetMap><entry><key>95cd8437-25f1-4238-8720-cbfe7fa81476</key><value>d8d16606-5d01-4822-b160-9a0d257303e0</value></entry></subnetMap></updateNetworkResponse>";
+ UpdateNetworkResponse response =
+ (UpdateNetworkResponse) new NetworkAdapterRestV1().unmarshalXml(xml, UpdateNetworkResponse.class);
+ assertThat(expectedResponse, sameBeanAs(response));
+ }
+
+ @Test
+ public void processCallbackTest() throws MapperException, BadResponseException, IOException {
+ UpdateNetworkRequest updateNetworkRequest = new UpdateNetworkRequest();
+ UpdateNetworkResponse updateNetworkResponse = new UpdateNetworkResponse();
+ updateNetworkResponse.setMessageId("messageId");
+ updateNetworkResponse.setNetworkId("networkId");
+ delegateExecution.setVariable("networkAdapterRequest", updateNetworkRequest);
+ delegateExecution.setVariable("NetworkAResponse_MESSAGE", updateNetworkResponse.toXmlString());
+
+ networkAdapterRestV1Tasks.processCallback(delegateExecution);
+
+ assertThat(updateNetworkResponse, sameBeanAs(delegateExecution.getVariable("updateNetworkResponse")));
+ }
+
+ @Test
+ public void processCallbackErrorTest() throws MapperException, BadResponseException, IOException {
+ UpdateNetworkRequest updateNetworkRequest = new UpdateNetworkRequest();
+ UpdateNetworkError updateNetworkResponse = new UpdateNetworkError();
+ updateNetworkResponse.setMessageId("messageId");
+ updateNetworkResponse.setMessage("test error message");
+ delegateExecution.setVariable("networkAdapterRequest", updateNetworkRequest);
+ delegateExecution.setVariable("NetworkAResponse_MESSAGE", updateNetworkResponse.toXmlString());
+
+ doThrow(new BpmnError("MSOWorkflowException")).when(exceptionBuilder)
+ .buildAndThrowWorkflowException(any(DelegateExecution.class), anyInt(), any(String.class));
+ try {
+ networkAdapterRestV1Tasks.processCallback(delegateExecution);
+ } catch (BpmnError be) {
+ assertEquals("MSOWorkflowException", be.getErrorCode());
+ }
+ assertNull(delegateExecution.getVariable("updateNetworkResponse"));
+ verify(exceptionBuilder, times(1)).buildAndThrowWorkflowException(any(DelegateExecution.class), eq(7000),
+ eq("test error message"));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasksTest.java
index 0406ce09a3..af97c3d038 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasksTest.java
@@ -30,11 +30,9 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Optional;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -56,45 +54,49 @@ import org.onap.so.client.adapter.network.NetworkAdapterClientException;
import org.onap.so.client.exception.BBObjectNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
-public class NetworkAdapterUpdateTasksTest extends BaseTaskTest{
- @InjectMocks
- private NetworkAdapterUpdateTasks networkAdapterUpdateTasks = new NetworkAdapterUpdateTasks();
-
- private ServiceInstance serviceInstance;
- private L3Network network;
- private RequestContext requestContext;
- private CloudRegion cloudRegion;
- private OrchestrationContext orchestrationContext;
- private Map<String, String> userInput;
- private Customer customer;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- customer = setCustomer();
- serviceInstance = setServiceInstance();
- network = setL3Network();
- requestContext = setRequestContext();
- cloudRegion = setCloudRegion();
- orchestrationContext = setOrchestrationContext();
- userInput = setUserInput();
- userInput.put("userInputKey1", "userInputValue1");
-
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
-
- }
-
- @Test
- public void updateNetworkTest() throws Exception {
- String cloudRegionPo = "cloudRegionPo";
- UpdateNetworkRequest updateNetworkRequest = new UpdateNetworkRequest();
- execution.setVariable("cloudRegionPo", cloudRegionPo);
+public class NetworkAdapterUpdateTasksTest extends BaseTaskTest {
+ @InjectMocks
+ private NetworkAdapterUpdateTasks networkAdapterUpdateTasks = new NetworkAdapterUpdateTasks();
+
+ private ServiceInstance serviceInstance;
+ private L3Network network;
+ private RequestContext requestContext;
+ private CloudRegion cloudRegion;
+ private OrchestrationContext orchestrationContext;
+ private Map<String, String> userInput;
+ private Customer customer;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ customer = setCustomer();
+ serviceInstance = setServiceInstance();
+ network = setL3Network();
+ requestContext = setRequestContext();
+ cloudRegion = setCloudRegion();
+ orchestrationContext = setOrchestrationContext();
+ userInput = setUserInput();
+ userInput.put("userInputKey1", "userInputValue1");
+
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+
+ }
+
+ @Test
+ public void updateNetworkTest() throws Exception {
+ String cloudRegionPo = "cloudRegionPo";
+ UpdateNetworkRequest updateNetworkRequest = new UpdateNetworkRequest();
+ execution.setVariable("cloudRegionPo", cloudRegionPo);
+
+ doReturn(updateNetworkRequest).when(networkAdapterObjectMapper).createNetworkUpdateRequestMapper(
+ isA(RequestContext.class), isA(CloudRegion.class), isA(OrchestrationContext.class),
+ isA(ServiceInstance.class), isA(L3Network.class), isA(Map.class), isA(Customer.class));
+ networkAdapterUpdateTasks.updateNetwork(execution);
+ verify(networkAdapterObjectMapper, times(1)).createNetworkUpdateRequestMapper(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, network, userInput, customer);
+ assertEquals(updateNetworkRequest, execution.getVariable("networkAdapterRequest"));
+ }
- doReturn(updateNetworkRequest).when(networkAdapterObjectMapper).createNetworkUpdateRequestMapper(isA(RequestContext.class), isA(CloudRegion.class), isA(OrchestrationContext.class), isA(ServiceInstance.class), isA(L3Network.class), isA(Map.class), isA(Customer.class));
- networkAdapterUpdateTasks.updateNetwork(execution);
- verify(networkAdapterObjectMapper, times(1)).createNetworkUpdateRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, network, userInput, customer);
- assertEquals(updateNetworkRequest, execution.getVariable("networkAdapterRequest"));
- }
-
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasksTest.java
index 32b3201d11..13f2b81fd9 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasksTest.java
@@ -28,7 +28,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
@@ -47,178 +46,197 @@ import org.onap.so.bpmn.servicedecomposition.generalobjects.OrchestrationContext
import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-public class VnfAdapterCreateTasksTest extends BaseTaskTest{
- @InjectMocks
- private VnfAdapterCreateTasks vnfAdapterCreateTasks = new VnfAdapterCreateTasks();
-
-
- @Test
- public void test_createVolumeGroupRequest() throws Exception {
- RequestContext requestContext = setRequestContext();
-
- ServiceInstance serviceInstance = setServiceInstance();
-
- GenericVnf genericVnf = setGenericVnf();
-
- VfModule vfModule = setVfModule();
- vfModule.setSelflink("vfModuleSelfLink");
- VolumeGroup volumeGroup = setVolumeGroup();
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
-
- CloudRegion cloudRegion = setCloudRegion();
-
- OrchestrationContext orchestrationContext = setOrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
-
- String sdncVnfQueryResponse = "SDNCVnfQueryResponse";
+public class VnfAdapterCreateTasksTest extends BaseTaskTest {
+ @InjectMocks
+ private VnfAdapterCreateTasks vnfAdapterCreateTasks = new VnfAdapterCreateTasks();
+
+
+ @Test
+ public void test_createVolumeGroupRequest() throws Exception {
+ RequestContext requestContext = setRequestContext();
+
+ ServiceInstance serviceInstance = setServiceInstance();
+
+ GenericVnf genericVnf = setGenericVnf();
+
+ VfModule vfModule = setVfModule();
+ vfModule.setSelflink("vfModuleSelfLink");
+ VolumeGroup volumeGroup = setVolumeGroup();
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+
+ CloudRegion cloudRegion = setCloudRegion();
+
+ OrchestrationContext orchestrationContext = setOrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+
+ String sdncVnfQueryResponse = "SDNCVnfQueryResponse";
execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), sdncVnfQueryResponse);
CreateVolumeGroupRequest request = new CreateVolumeGroupRequest();
request.setVolumeGroupId("volumeGroupStackId");
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- doReturn(request).when(vnfAdapterVolumeGroupResources).createVolumeGroupRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVnfQueryResponse);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID)))
+ .thenReturn(volumeGroup);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ doReturn(request).when(vnfAdapterVolumeGroupResources).createVolumeGroupRequest(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVnfQueryResponse);
vnfAdapterCreateTasks.createVolumeGroupRequest(execution);
-
- verify(vnfAdapterVolumeGroupResources, times(1)).createVolumeGroupRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVnfQueryResponse);
-
- assertEquals(request.toXmlString(), execution.getVariable("VNFREST_Request"));
- }
-
- @Test
- public void test_createVolumeGroupRequest_for_alaCarte_flow() throws Exception {
- RequestContext requestContext = setRequestContext();
- ServiceInstance serviceInstance = setServiceInstance();
- GenericVnf genericVnf = setGenericVnf();
- VolumeGroup volumeGroup = setVolumeGroup();
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
-
- VfModule vfModule = setVfModule();
- vfModule.setSelflink("vfModuleSelfLink");
-
- CloudRegion cloudRegion = setCloudRegion();
-
- OrchestrationContext orchestrationContext = setOrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
+
+ verify(vnfAdapterVolumeGroupResources, times(1)).createVolumeGroupRequest(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVnfQueryResponse);
+
+ assertEquals(request.toXmlString(), execution.getVariable("VNFREST_Request"));
+ }
+
+ @Test
+ public void test_createVolumeGroupRequest_for_alaCarte_flow() throws Exception {
+ RequestContext requestContext = setRequestContext();
+ ServiceInstance serviceInstance = setServiceInstance();
+ GenericVnf genericVnf = setGenericVnf();
+ VolumeGroup volumeGroup = setVolumeGroup();
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+
+ VfModule vfModule = setVfModule();
+ vfModule.setSelflink("vfModuleSelfLink");
+
+ CloudRegion cloudRegion = setCloudRegion();
+
+ OrchestrationContext orchestrationContext = setOrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
CreateVolumeGroupRequest request = new CreateVolumeGroupRequest();
request.setVolumeGroupId("volumeGroupStackId");
-
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- doReturn(request).when(vnfAdapterVolumeGroupResources).createVolumeGroupRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, null);
-
- vnfAdapterCreateTasks.createVolumeGroupRequest(execution);
-
- verify(vnfAdapterVolumeGroupResources, times(1)).createVolumeGroupRequest(any(RequestContext.class),
- any(CloudRegion.class), any(OrchestrationContext.class), eq(serviceInstance), eq(genericVnf), eq(volumeGroup), ArgumentMatchers.isNull());
-
- assertEquals(request.toXmlString(), execution.getVariable("VNFREST_Request"));
- }
-
- @Test
- public void test_createVolumeGroupRequest_exception() throws Exception {
- doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID));
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- expectedException.expect(BpmnError.class);
-
- vnfAdapterCreateTasks.createVolumeGroupRequest(execution);
- }
-
- @Test
- public void test_createVfModule() throws Exception {
- RequestContext requestContext = setRequestContext();
-
- ServiceInstance serviceInstance = setServiceInstance();
-
- GenericVnf genericVnf = setGenericVnf();
-
- VfModule vfModule = setVfModule();
-
- CloudRegion cloudRegion = setCloudRegion();
-
- OrchestrationContext orchestrationContext = setOrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
-
- CreateVfModuleRequest modRequest = new CreateVfModuleRequest();
- modRequest.setVfModuleId(vfModule.getVfModuleId());
- modRequest.setBaseVfModuleStackId("baseVfModuleStackId");
- modRequest.setVfModuleName(vfModule.getVfModuleName());
- CreateVfModuleRequest createVfModuleRequest = modRequest;
-
- String sdncVfModuleQueryResponse = "{someJson}";
- execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), sdncVfModuleQueryResponse);
-
- String sdncVnfQueryResponse = "{someJson}";
- execution.setVariable("SDNCQueryResponse_" + genericVnf.getVnfId(), sdncVnfQueryResponse);
-
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
-
- doReturn(createVfModuleRequest).when(vnfAdapterVfModuleResources).createVfModuleRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance,
- genericVnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
- vnfAdapterCreateTasks.createVfModule(execution);
-
- verify(vnfAdapterVfModuleResources, times(1)).createVfModuleRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance,
- genericVnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
- assertEquals(execution.getVariable("VNFREST_Request"), createVfModuleRequest.toXmlString());
- }
-
- @Test
- public void test_createVfModuleWithVolumeGroup() throws Exception {
- RequestContext requestContext = setRequestContext();
-
- ServiceInstance serviceInstance = setServiceInstance();
-
- GenericVnf genericVnf = setGenericVnf();
-
- VfModule vfModule = setVfModule();
-
- VolumeGroup volumeGroup = setVolumeGroup();
-
- CloudRegion cloudRegion = setCloudRegion();
-
- OrchestrationContext orchestrationContext = setOrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
-
- CreateVfModuleRequest modRequest = new CreateVfModuleRequest();
- modRequest.setVfModuleId(vfModule.getVfModuleId());
- modRequest.setBaseVfModuleStackId("baseVfModuleStackId");
- modRequest.setVfModuleName(vfModule.getVfModuleName());
- CreateVfModuleRequest createVfModuleRequest = modRequest;
-
- String sdncVfModuleQueryResponse = "{someJson}";
- execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), sdncVfModuleQueryResponse);
-
- String sdncVnfQueryResponse = "{someJson}";
- execution.setVariable("SDNCQueryResponse_" + genericVnf.getVnfId(), sdncVnfQueryResponse);
-
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- doReturn(createVfModuleRequest).when(vnfAdapterVfModuleResources).createVfModuleRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance,
- genericVnf, vfModule, volumeGroup, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
- vnfAdapterCreateTasks.createVfModule(execution);
-
- verify(vnfAdapterVfModuleResources, times(1)).createVfModuleRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance,
- genericVnf, vfModule, volumeGroup, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
- assertEquals(execution.getVariable("VNFREST_Request"), createVfModuleRequest.toXmlString());
- }
-
- @Test
- public void createVfModuleExceptionTest() throws Exception {
- // run with no data setup, and it will throw a BBObjectNotFoundException
- doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID));
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- expectedException.expect(BpmnError.class);
- vnfAdapterCreateTasks.createVolumeGroupRequest(execution);
- }
+
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID)))
+ .thenReturn(volumeGroup);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ doReturn(request).when(vnfAdapterVolumeGroupResources).createVolumeGroupRequest(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, genericVnf, volumeGroup, null);
+
+ vnfAdapterCreateTasks.createVolumeGroupRequest(execution);
+
+ verify(vnfAdapterVolumeGroupResources, times(1)).createVolumeGroupRequest(any(RequestContext.class),
+ any(CloudRegion.class), any(OrchestrationContext.class), eq(serviceInstance), eq(genericVnf),
+ eq(volumeGroup), ArgumentMatchers.isNull());
+
+ assertEquals(request.toXmlString(), execution.getVariable("VNFREST_Request"));
+ }
+
+ @Test
+ public void test_createVolumeGroupRequest_exception() throws Exception {
+ doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),
+ ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID));
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ expectedException.expect(BpmnError.class);
+
+ vnfAdapterCreateTasks.createVolumeGroupRequest(execution);
+ }
+
+ @Test
+ public void test_createVfModule() throws Exception {
+ RequestContext requestContext = setRequestContext();
+
+ ServiceInstance serviceInstance = setServiceInstance();
+
+ GenericVnf genericVnf = setGenericVnf();
+
+ VfModule vfModule = setVfModule();
+
+ CloudRegion cloudRegion = setCloudRegion();
+
+ OrchestrationContext orchestrationContext = setOrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+
+ CreateVfModuleRequest modRequest = new CreateVfModuleRequest();
+ modRequest.setVfModuleId(vfModule.getVfModuleId());
+ modRequest.setBaseVfModuleStackId("baseVfModuleStackId");
+ modRequest.setVfModuleName(vfModule.getVfModuleName());
+ CreateVfModuleRequest createVfModuleRequest = modRequest;
+
+ String sdncVfModuleQueryResponse = "{someJson}";
+ execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), sdncVfModuleQueryResponse);
+
+ String sdncVnfQueryResponse = "{someJson}";
+ execution.setVariable("SDNCQueryResponse_" + genericVnf.getVnfId(), sdncVnfQueryResponse);
+
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+
+ doReturn(createVfModuleRequest).when(vnfAdapterVfModuleResources).createVfModuleRequest(requestContext,
+ cloudRegion, orchestrationContext, serviceInstance, genericVnf, vfModule, null, sdncVnfQueryResponse,
+ sdncVfModuleQueryResponse);
+
+ vnfAdapterCreateTasks.createVfModule(execution);
+
+ verify(vnfAdapterVfModuleResources, times(1)).createVfModuleRequest(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, genericVnf, vfModule, null, sdncVnfQueryResponse,
+ sdncVfModuleQueryResponse);
+
+ assertEquals(execution.getVariable("VNFREST_Request"), createVfModuleRequest.toXmlString());
+ }
+
+ @Test
+ public void test_createVfModuleWithVolumeGroup() throws Exception {
+ RequestContext requestContext = setRequestContext();
+
+ ServiceInstance serviceInstance = setServiceInstance();
+
+ GenericVnf genericVnf = setGenericVnf();
+
+ VfModule vfModule = setVfModule();
+
+ VolumeGroup volumeGroup = setVolumeGroup();
+
+ CloudRegion cloudRegion = setCloudRegion();
+
+ OrchestrationContext orchestrationContext = setOrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+
+ CreateVfModuleRequest modRequest = new CreateVfModuleRequest();
+ modRequest.setVfModuleId(vfModule.getVfModuleId());
+ modRequest.setBaseVfModuleStackId("baseVfModuleStackId");
+ modRequest.setVfModuleName(vfModule.getVfModuleName());
+ CreateVfModuleRequest createVfModuleRequest = modRequest;
+
+ String sdncVfModuleQueryResponse = "{someJson}";
+ execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), sdncVfModuleQueryResponse);
+
+ String sdncVnfQueryResponse = "{someJson}";
+ execution.setVariable("SDNCQueryResponse_" + genericVnf.getVnfId(), sdncVnfQueryResponse);
+
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID)))
+ .thenReturn(volumeGroup);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ doReturn(createVfModuleRequest).when(vnfAdapterVfModuleResources).createVfModuleRequest(requestContext,
+ cloudRegion, orchestrationContext, serviceInstance, genericVnf, vfModule, volumeGroup,
+ sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+ vnfAdapterCreateTasks.createVfModule(execution);
+
+ verify(vnfAdapterVfModuleResources, times(1)).createVfModuleRequest(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, genericVnf, vfModule, volumeGroup, sdncVnfQueryResponse,
+ sdncVfModuleQueryResponse);
+
+ assertEquals(execution.getVariable("VNFREST_Request"), createVfModuleRequest.toXmlString());
+ }
+
+ @Test
+ public void createVfModuleExceptionTest() throws Exception {
+ // run with no data setup, and it will throw a BBObjectNotFoundException
+ doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),
+ ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID));
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ expectedException.expect(BpmnError.class);
+ vnfAdapterCreateTasks.createVolumeGroupRequest(execution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasksTest.java
index efd2e7d849..c680978953 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasksTest.java
@@ -28,7 +28,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -47,84 +46,97 @@ import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
import org.onap.so.bpmn.servicedecomposition.generalobjects.OrchestrationContext;
import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
-public class VnfAdapterDeleteTasksTest extends BaseTaskTest{
- @InjectMocks
- private VnfAdapterDeleteTasks vnfAdapterDeleteTasks = new VnfAdapterDeleteTasks();
-
- private VolumeGroup volumeGroup;
- private VfModule vfModule;
- private GenericVnf genericVnf;
- private RequestContext requestContext;
- private CloudRegion cloudRegion;
- private ServiceInstance serviceInstance;
- private OrchestrationContext orchestrationContext;
-
- @Before
- public void before() throws Exception {
- requestContext = setRequestContext();
-
- serviceInstance = setServiceInstance();
-
- cloudRegion = setCloudRegion();
-
- genericVnf = setGenericVnf();
-
- vfModule = setVfModule();
-
- volumeGroup = setVolumeGroup();
-
- orchestrationContext = setOrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
-
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- }
-
- @Test
- public void test_deleteVfModule() throws Exception {
- DeleteVfModuleRequest deleteVfModuleRequest = new DeleteVfModuleRequest();
- deleteVfModuleRequest.setVfModuleId("vfModuleId");
-
- doReturn(deleteVfModuleRequest).when(vnfAdapterVfModuleResources).deleteVfModuleRequest(requestContext, cloudRegion, serviceInstance, genericVnf, vfModule);
-
- vnfAdapterDeleteTasks.deleteVfModule(execution);
-
- verify(vnfAdapterVfModuleResources, times(1)).deleteVfModuleRequest(ArgumentMatchers.eq(requestContext), ArgumentMatchers.eq(cloudRegion), ArgumentMatchers.eq(serviceInstance), ArgumentMatchers.eq(genericVnf),ArgumentMatchers.eq(vfModule));
- assertEquals(execution.getVariable("VNFREST_Request"), deleteVfModuleRequest.toXmlString());
- }
-
- @Test
- public void deleteVfModuleExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- doThrow(RuntimeException.class).when(vnfAdapterVfModuleResources).deleteVfModuleRequest(requestContext, cloudRegion, serviceInstance, genericVnf, vfModule);
-
- vnfAdapterDeleteTasks.deleteVfModule(execution);
- }
-
- @Test
- public void test_deleteVolumeGroup() throws Exception {
- DeleteVolumeGroupRequest deleteVolumeGroupRequest = new DeleteVolumeGroupRequest();
- deleteVolumeGroupRequest.setVolumeGroupId("volumeGroupId");
-
- doReturn(deleteVolumeGroupRequest).when(vnfAdapterVolumeGroupResources).deleteVolumeGroupRequest(requestContext, cloudRegion, serviceInstance, volumeGroup);
-
- vnfAdapterDeleteTasks.deleteVolumeGroup(execution);
-
- verify(vnfAdapterVolumeGroupResources, times(1)).deleteVolumeGroupRequest(ArgumentMatchers.eq(requestContext), ArgumentMatchers.eq(cloudRegion), ArgumentMatchers.eq(serviceInstance), ArgumentMatchers.eq(volumeGroup));
- assertEquals(execution.getVariable("VNFREST_Request"), deleteVolumeGroupRequest.toXmlString());
- }
-
- @Test
- public void deleteVolumeGroupExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- doThrow(RuntimeException.class).when(vnfAdapterVolumeGroupResources).deleteVolumeGroupRequest(requestContext, cloudRegion, serviceInstance, volumeGroup);
-
- vnfAdapterDeleteTasks.deleteVolumeGroup(execution);
- }
+public class VnfAdapterDeleteTasksTest extends BaseTaskTest {
+ @InjectMocks
+ private VnfAdapterDeleteTasks vnfAdapterDeleteTasks = new VnfAdapterDeleteTasks();
+
+ private VolumeGroup volumeGroup;
+ private VfModule vfModule;
+ private GenericVnf genericVnf;
+ private RequestContext requestContext;
+ private CloudRegion cloudRegion;
+ private ServiceInstance serviceInstance;
+ private OrchestrationContext orchestrationContext;
+
+ @Before
+ public void before() throws Exception {
+ requestContext = setRequestContext();
+
+ serviceInstance = setServiceInstance();
+
+ cloudRegion = setCloudRegion();
+
+ genericVnf = setGenericVnf();
+
+ vfModule = setVfModule();
+
+ volumeGroup = setVolumeGroup();
+
+ orchestrationContext = setOrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID)))
+ .thenReturn(volumeGroup);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ }
+
+ @Test
+ public void test_deleteVfModule() throws Exception {
+ DeleteVfModuleRequest deleteVfModuleRequest = new DeleteVfModuleRequest();
+ deleteVfModuleRequest.setVfModuleId("vfModuleId");
+
+ doReturn(deleteVfModuleRequest).when(vnfAdapterVfModuleResources).deleteVfModuleRequest(requestContext,
+ cloudRegion, serviceInstance, genericVnf, vfModule);
+
+ vnfAdapterDeleteTasks.deleteVfModule(execution);
+
+ verify(vnfAdapterVfModuleResources, times(1)).deleteVfModuleRequest(ArgumentMatchers.eq(requestContext),
+ ArgumentMatchers.eq(cloudRegion), ArgumentMatchers.eq(serviceInstance), ArgumentMatchers.eq(genericVnf),
+ ArgumentMatchers.eq(vfModule));
+ assertEquals(execution.getVariable("VNFREST_Request"), deleteVfModuleRequest.toXmlString());
+ }
+
+ @Test
+ public void deleteVfModuleExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ doThrow(RuntimeException.class).when(vnfAdapterVfModuleResources).deleteVfModuleRequest(requestContext,
+ cloudRegion, serviceInstance, genericVnf, vfModule);
+
+ vnfAdapterDeleteTasks.deleteVfModule(execution);
+ }
+
+ @Test
+ public void test_deleteVolumeGroup() throws Exception {
+ DeleteVolumeGroupRequest deleteVolumeGroupRequest = new DeleteVolumeGroupRequest();
+ deleteVolumeGroupRequest.setVolumeGroupId("volumeGroupId");
+
+ doReturn(deleteVolumeGroupRequest).when(vnfAdapterVolumeGroupResources).deleteVolumeGroupRequest(requestContext,
+ cloudRegion, serviceInstance, volumeGroup);
+
+ vnfAdapterDeleteTasks.deleteVolumeGroup(execution);
+
+ verify(vnfAdapterVolumeGroupResources, times(1)).deleteVolumeGroupRequest(ArgumentMatchers.eq(requestContext),
+ ArgumentMatchers.eq(cloudRegion), ArgumentMatchers.eq(serviceInstance),
+ ArgumentMatchers.eq(volumeGroup));
+ assertEquals(execution.getVariable("VNFREST_Request"), deleteVolumeGroupRequest.toXmlString());
+ }
+
+ @Test
+ public void deleteVolumeGroupExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ doThrow(RuntimeException.class).when(vnfAdapterVolumeGroupResources).deleteVolumeGroupRequest(requestContext,
+ cloudRegion, serviceInstance, volumeGroup);
+
+ vnfAdapterDeleteTasks.deleteVolumeGroup(execution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java
index b515835f19..97a9388f8d 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java
@@ -27,7 +27,6 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -46,173 +45,188 @@ import org.onap.so.client.exception.BBObjectNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
public class VnfAdapterImplTest extends BaseTaskTest {
-
- @InjectMocks
- private VnfAdapterImpl vnfAdapterImpl = new VnfAdapterImpl();
-
- private RequestContext requestContext;
- private ServiceInstance serviceInstance;
- private GenericVnf genericVnf;
- private VfModule vfModule;
+
+ @InjectMocks
+ private VnfAdapterImpl vnfAdapterImpl = new VnfAdapterImpl();
+
+ private RequestContext requestContext;
+ private ServiceInstance serviceInstance;
+ private GenericVnf genericVnf;
+ private VfModule vfModule;
private VolumeGroup volumeGroup;
-
- private static final String VNF_ADAPTER_REST_DELETE_RESPONSE = FileUtil.readResourceFile("__files/VfModularity/VNFAdapterRestDeleteResponse.xml");
- private static final String VNF_ADAPTER_REST_CREATE_RESPONSE = FileUtil.readResourceFile("__files/VfModularity/VNFAdapterRestCreateCallback.xml");
- private static final String VNF_ADAPTER_VOLUME_CREATE_RESPONSE = FileUtil.readResourceFile("__files/VfModularity/CreateVfModuleVolumeCallbackResponse.xml");
- private static final String VNF_ADAPTER_VOLUME_DELETE_RESPONSE = FileUtil.readResourceFile("__files/VfModularity/DeleteVfModuleVolumeCallbackResponse.xml");
- private static final String TEST_VFMODULE_HEATSTACK_ID = "slowburn";
+
+ private static final String VNF_ADAPTER_REST_DELETE_RESPONSE =
+ FileUtil.readResourceFile("__files/VfModularity/VNFAdapterRestDeleteResponse.xml");
+ private static final String VNF_ADAPTER_REST_CREATE_RESPONSE =
+ FileUtil.readResourceFile("__files/VfModularity/VNFAdapterRestCreateCallback.xml");
+ private static final String VNF_ADAPTER_VOLUME_CREATE_RESPONSE =
+ FileUtil.readResourceFile("__files/VfModularity/CreateVfModuleVolumeCallbackResponse.xml");
+ private static final String VNF_ADAPTER_VOLUME_DELETE_RESPONSE =
+ FileUtil.readResourceFile("__files/VfModularity/DeleteVfModuleVolumeCallbackResponse.xml");
+ private static final String TEST_VFMODULE_HEATSTACK_ID = "slowburn";
private static final String TEST_VOLUME_HEATSTACK_ID = "testHeatStackId1";
private static final String TEST_CONTRAIL_SERVICE_INSTANCE_FQDN = "default-domain:MSOTest:MsoNW-RA";
private static final String TEST_OAM_MANAGEMENT_V4_ADDRESS = "127.0.0.1";
private static final String TEST_OAM_MANAGEMENT_V6_ADDRESS = "2000:abc:bce:1111";
- private static final String TEST_CONTRAIL_NETWORK_POLICY_FQDNS = "MSOTest:DefaultPolicyFQDN2,MSOTest:DefaultPolicyFQDN1";
-
- @Before
- public void before() throws BBObjectNotFoundException {
- requestContext = setRequestContext();
- serviceInstance = setServiceInstance();
- genericVnf = setGenericVnf();
- vfModule = setVfModule();
+ private static final String TEST_CONTRAIL_NETWORK_POLICY_FQDNS =
+ "MSOTest:DefaultPolicyFQDN2,MSOTest:DefaultPolicyFQDN1";
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ requestContext = setRequestContext();
+ serviceInstance = setServiceInstance();
+ genericVnf = setGenericVnf();
+ vfModule = setVfModule();
volumeGroup = setVolumeGroup();
- vfModule.setHeatStackId(null);
- volumeGroup.setHeatStackId(null);
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- }
-
- @Test
- public void preProcessVnfAdapterTest() {
- vnfAdapterImpl.preProcessVnfAdapter(execution);
-
- assertEquals(requestContext.getMsoRequestId(), execution.getVariable("mso-request-id"));
- assertEquals(serviceInstance.getServiceInstanceId(), execution.getVariable("mso-service-instance-id"));
- }
-
- @Test
- public void postProcessVnfAdapter_CreateResponseTest() {
- execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_REST_CREATE_RESPONSE);
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- assertEquals(TEST_VFMODULE_HEATSTACK_ID, vfModule.getHeatStackId());
- assertEquals(TEST_CONTRAIL_SERVICE_INSTANCE_FQDN, vfModule.getContrailServiceInstanceFqdn());
- assertEquals(TEST_CONTRAIL_SERVICE_INSTANCE_FQDN, execution.getVariable("contrailServiceInstanceFqdn"));
- assertEquals(TEST_OAM_MANAGEMENT_V4_ADDRESS, genericVnf.getIpv4OamAddress());
- assertEquals(TEST_OAM_MANAGEMENT_V4_ADDRESS, execution.getVariable("oamManagementV4Address"));
- assertEquals(TEST_OAM_MANAGEMENT_V6_ADDRESS, genericVnf.getManagementV6Address());
- assertEquals(TEST_OAM_MANAGEMENT_V6_ADDRESS, execution.getVariable("oamManagementV6Address"));
- assertEquals(TEST_CONTRAIL_NETWORK_POLICY_FQDNS, execution.getVariable("contrailNetworkPolicyFqdnList"));
- }
-
-
- @Test
- public void postProcessVnfAdapter_CreateResponseTest_EmptyCreateVfModuleResponseTag() {
+ vfModule.setHeatStackId(null);
+ volumeGroup.setHeatStackId(null);
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID)))
+ .thenReturn(volumeGroup);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ }
+
+ @Test
+ public void preProcessVnfAdapterTest() {
+ vnfAdapterImpl.preProcessVnfAdapter(execution);
+
+ assertEquals(requestContext.getMsoRequestId(), execution.getVariable("mso-request-id"));
+ assertEquals(serviceInstance.getServiceInstanceId(), execution.getVariable("mso-service-instance-id"));
+ }
+
+ @Test
+ public void postProcessVnfAdapter_CreateResponseTest() {
+ execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_REST_CREATE_RESPONSE);
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ assertEquals(TEST_VFMODULE_HEATSTACK_ID, vfModule.getHeatStackId());
+ assertEquals(TEST_CONTRAIL_SERVICE_INSTANCE_FQDN, vfModule.getContrailServiceInstanceFqdn());
+ assertEquals(TEST_CONTRAIL_SERVICE_INSTANCE_FQDN, execution.getVariable("contrailServiceInstanceFqdn"));
+ assertEquals(TEST_OAM_MANAGEMENT_V4_ADDRESS, genericVnf.getIpv4OamAddress());
+ assertEquals(TEST_OAM_MANAGEMENT_V4_ADDRESS, execution.getVariable("oamManagementV4Address"));
+ assertEquals(TEST_OAM_MANAGEMENT_V6_ADDRESS, genericVnf.getManagementV6Address());
+ assertEquals(TEST_OAM_MANAGEMENT_V6_ADDRESS, execution.getVariable("oamManagementV6Address"));
+ assertEquals(TEST_CONTRAIL_NETWORK_POLICY_FQDNS, execution.getVariable("contrailNetworkPolicyFqdnList"));
+ }
+
+
+ @Test
+ public void postProcessVnfAdapter_CreateResponseTest_EmptyCreateVfModuleResponseTag() {
expectedException.expect(BpmnError.class);
- execution.setVariable("vnfAdapterRestV1Response", "<vfModuleStackId></vfModuleStackId>");
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- }
-
- @Test
- public void postProcessVnfAdapter_CreateResponseTest_EmptyVfModuleStackIdTag() {
- execution.setVariable("vnfAdapterRestV1Response", "<createVfModuleResponse></createVfModuleResponse>");
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- assertNull(vfModule.getHeatStackId());
- }
-
- @Test
- public void postProcessVnfAdapter_CreateResponseTest_EmptyHeatStackId() {
- execution.setVariable("vnfAdapterRestV1Response", "<createVfModuleResponse><vfModuleStackId></vfModuleStackId></createVfModuleResponse>");
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- assertNull(vfModule.getHeatStackId());
- }
-
- @Test
- public void postProcessVnfAdapter_CreateResponseTest_EmptyVfModuleOutputs() {
- execution.setVariable("vnfAdapterRestV1Response", "<createVfModuleResponse><vfModuleOutputs></vfModuleOutputs></createVfModuleResponse>");
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- assertNull(vfModule.getHeatStackId());
- assertNull(vfModule.getContrailServiceInstanceFqdn());
- assertNull(execution.getVariable("contrailServiceInstanceFqdn"));
- assertNotEquals(TEST_OAM_MANAGEMENT_V4_ADDRESS, genericVnf.getIpv4OamAddress());
- assertNull(execution.getVariable("oamManagementV4Address"));
- assertNull(genericVnf.getManagementV6Address());
- assertNull(execution.getVariable("oamManagementV6Address"));
- assertNull(execution.getVariable("contrailNetworkPolicyFqdnList"));
- }
-
- @Test
- public void postProcessVnfAdapter_DeleteResponseTest() {
- vfModule.setHeatStackId(TEST_VFMODULE_HEATSTACK_ID);
- execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_REST_DELETE_RESPONSE);
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- assertNull(vfModule.getHeatStackId());
- assertEquals(vfModule.getContrailServiceInstanceFqdn(), "");
- assertEquals(execution.getVariable("contrailServiceInstanceFqdn"), "");
- assertEquals(genericVnf.getIpv4OamAddress(), "");
- assertEquals(execution.getVariable("oamManagementV4Address"), "");
- assertEquals(genericVnf.getManagementV6Address(), "");
- assertEquals(execution.getVariable("oamManagementV6Address"), "");
- assertEquals(TEST_CONTRAIL_NETWORK_POLICY_FQDNS, execution.getVariable("contrailNetworkPolicyFqdnList"));
- }
-
- @Test
- public void postProcessVnfAdapter_DeleteResponseTest_EmptyVfModuleOutputs() {
- execution.setVariable("vnfAdapterRestV1Response", "<createVfModuleResponse><vfModuleOutputs></vfModuleOutputs></createVfModuleResponse>");
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- assertNull(vfModule.getHeatStackId());
- assertNull(vfModule.getContrailServiceInstanceFqdn());
- assertNull(execution.getVariable("contrailServiceInstanceFqdn"));
- assertNull(execution.getVariable("oamManagementV4Address"));
- assertNull(execution.getVariable("oamManagementV6Address"));
- assertNull(execution.getVariable("contrailNetworkPolicyFqdnList"));
- }
-
- @Test
- public void postProcessVnfAdapter_ResponseNullTest() {
- execution.setVariable("vnfAdapterRestV1Response", null);
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- assertNull(vfModule.getHeatStackId());
- }
-
- @Test
- public void postProcessVnfAdapter_ResponseEmptyTest() {
+ execution.setVariable("vnfAdapterRestV1Response", "<vfModuleStackId></vfModuleStackId>");
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ }
+
+ @Test
+ public void postProcessVnfAdapter_CreateResponseTest_EmptyVfModuleStackIdTag() {
+ execution.setVariable("vnfAdapterRestV1Response", "<createVfModuleResponse></createVfModuleResponse>");
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ assertNull(vfModule.getHeatStackId());
+ }
+
+ @Test
+ public void postProcessVnfAdapter_CreateResponseTest_EmptyHeatStackId() {
+ execution.setVariable("vnfAdapterRestV1Response",
+ "<createVfModuleResponse><vfModuleStackId></vfModuleStackId></createVfModuleResponse>");
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ assertNull(vfModule.getHeatStackId());
+ }
+
+ @Test
+ public void postProcessVnfAdapter_CreateResponseTest_EmptyVfModuleOutputs() {
+ execution.setVariable("vnfAdapterRestV1Response",
+ "<createVfModuleResponse><vfModuleOutputs></vfModuleOutputs></createVfModuleResponse>");
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ assertNull(vfModule.getHeatStackId());
+ assertNull(vfModule.getContrailServiceInstanceFqdn());
+ assertNull(execution.getVariable("contrailServiceInstanceFqdn"));
+ assertNotEquals(TEST_OAM_MANAGEMENT_V4_ADDRESS, genericVnf.getIpv4OamAddress());
+ assertNull(execution.getVariable("oamManagementV4Address"));
+ assertNull(genericVnf.getManagementV6Address());
+ assertNull(execution.getVariable("oamManagementV6Address"));
+ assertNull(execution.getVariable("contrailNetworkPolicyFqdnList"));
+ }
+
+ @Test
+ public void postProcessVnfAdapter_DeleteResponseTest() {
+ vfModule.setHeatStackId(TEST_VFMODULE_HEATSTACK_ID);
+ execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_REST_DELETE_RESPONSE);
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ assertNull(vfModule.getHeatStackId());
+ assertEquals(vfModule.getContrailServiceInstanceFqdn(), "");
+ assertEquals(execution.getVariable("contrailServiceInstanceFqdn"), "");
+ assertEquals(genericVnf.getIpv4OamAddress(), "");
+ assertEquals(execution.getVariable("oamManagementV4Address"), "");
+ assertEquals(genericVnf.getManagementV6Address(), "");
+ assertEquals(execution.getVariable("oamManagementV6Address"), "");
+ assertEquals(TEST_CONTRAIL_NETWORK_POLICY_FQDNS, execution.getVariable("contrailNetworkPolicyFqdnList"));
+ }
+
+ @Test
+ public void postProcessVnfAdapter_DeleteResponseTest_EmptyVfModuleOutputs() {
+ execution.setVariable("vnfAdapterRestV1Response",
+ "<createVfModuleResponse><vfModuleOutputs></vfModuleOutputs></createVfModuleResponse>");
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ assertNull(vfModule.getHeatStackId());
+ assertNull(vfModule.getContrailServiceInstanceFqdn());
+ assertNull(execution.getVariable("contrailServiceInstanceFqdn"));
+ assertNull(execution.getVariable("oamManagementV4Address"));
+ assertNull(execution.getVariable("oamManagementV6Address"));
+ assertNull(execution.getVariable("contrailNetworkPolicyFqdnList"));
+ }
+
+ @Test
+ public void postProcessVnfAdapter_ResponseNullTest() {
+ execution.setVariable("vnfAdapterRestV1Response", null);
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ assertNull(vfModule.getHeatStackId());
+ }
+
+ @Test
+ public void postProcessVnfAdapter_ResponseEmptyTest() {
execution.setVariable("vnfAdapterRestV1Response", "");
- vnfAdapterImpl.postProcessVnfAdapter(execution);
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
assertNull(vfModule.getHeatStackId());
- }
-
- @Test
- public void postProcessVnfAdapter_DeleteResponseTest_VfModuleDeletedFalse() {
- vfModule.setHeatStackId(TEST_VFMODULE_HEATSTACK_ID);
- execution.setVariable("vnfAdapterRestV1Response", "<deleteVfModuleResponse><vfModuleDeleted>false</vfModuleDeleted></deleteVfModuleResponse>");
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- assertEquals(TEST_VFMODULE_HEATSTACK_ID, vfModule.getHeatStackId());
- }
-
- @Test
- public void postProcessVnfAdapter_DeleteResponseTest_EmptyDeleteVfModuleResponseTag() {
+ }
+
+ @Test
+ public void postProcessVnfAdapter_DeleteResponseTest_VfModuleDeletedFalse() {
+ vfModule.setHeatStackId(TEST_VFMODULE_HEATSTACK_ID);
+ execution.setVariable("vnfAdapterRestV1Response",
+ "<deleteVfModuleResponse><vfModuleDeleted>false</vfModuleDeleted></deleteVfModuleResponse>");
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ assertEquals(TEST_VFMODULE_HEATSTACK_ID, vfModule.getHeatStackId());
+ }
+
+ @Test
+ public void postProcessVnfAdapter_DeleteResponseTest_EmptyDeleteVfModuleResponseTag() {
+ expectedException.expect(BpmnError.class);
+ execution.setVariable("vnfAdapterRestV1Response", "<vfModuleDeleted></vfModuleDeleted>");
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ }
+
+ @Test
+ public void postProcessVnfAdapter_DeleteResponseTest_EmptyVfModuleDeletedTag() {
+ vfModule.setHeatStackId(TEST_VFMODULE_HEATSTACK_ID);
+ execution.setVariable("vnfAdapterRestV1Response", "<deleteVfModuleResponse></deleteVfModuleResponse>");
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ assertEquals(TEST_VFMODULE_HEATSTACK_ID, vfModule.getHeatStackId());
+ }
+
+ @Test
+ public void preProcessVnfAdapterExceptionTest() throws BBObjectNotFoundException {
expectedException.expect(BpmnError.class);
- execution.setVariable("vnfAdapterRestV1Response", "<vfModuleDeleted></vfModuleDeleted>");
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- }
-
- @Test
- public void postProcessVnfAdapter_DeleteResponseTest_EmptyVfModuleDeletedTag() {
- vfModule.setHeatStackId(TEST_VFMODULE_HEATSTACK_ID);
- execution.setVariable("vnfAdapterRestV1Response", "<deleteVfModuleResponse></deleteVfModuleResponse>");
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- assertEquals(TEST_VFMODULE_HEATSTACK_ID, vfModule.getHeatStackId());
- }
-
- @Test
- public void preProcessVnfAdapterExceptionTest() throws BBObjectNotFoundException {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID));
-
- vnfAdapterImpl.preProcessVnfAdapter(execution);
- }
+ doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),
+ ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID));
+
+ vnfAdapterImpl.preProcessVnfAdapter(execution);
+ }
@Test
public void postProcessVnfAdapter_CreateVolumeResponseTest() {
@@ -222,52 +236,54 @@ public class VnfAdapterImplTest extends BaseTaskTest {
}
@Test
- public void postProcessVnfAdapter_CreateVolumeEmptyResponseTest() {
+ public void postProcessVnfAdapter_CreateVolumeEmptyResponseTest() {
expectedException.expect(BpmnError.class);
execution.setVariable("vnfAdapterRestV1Response", "<createVolumeGroupResponse></createVolumeGroupResponse>");
vnfAdapterImpl.postProcessVnfAdapter(execution);
assertNull(volumeGroup.getHeatStackId());
}
-
+
@Test
- public void postProcessVnfAdapter_DeleteResponseTest_DeleteVolumeGroup() {
- volumeGroup.setHeatStackId(TEST_VOLUME_HEATSTACK_ID);
- execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_VOLUME_DELETE_RESPONSE);
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- assertNull(volumeGroup.getHeatStackId());
- }
-
-
+ public void postProcessVnfAdapter_DeleteResponseTest_DeleteVolumeGroup() {
+ volumeGroup.setHeatStackId(TEST_VOLUME_HEATSTACK_ID);
+ execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_VOLUME_DELETE_RESPONSE);
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ assertNull(volumeGroup.getHeatStackId());
+ }
+
+
+ @Test
+ public void postProcessVnfAdapter_DeleteResponseTest_VolumeGroupDeletedFalse() {
+ volumeGroup.setHeatStackId(TEST_VOLUME_HEATSTACK_ID);
+ execution.setVariable("vnfAdapterRestV1Response",
+ "<deleteVolumeGroupResponse><volumeGroupDeleted>false</volumeGroupDeleted></deleteVolumeGroupResponse>");
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ assertEquals(TEST_VOLUME_HEATSTACK_ID, volumeGroup.getHeatStackId());
+ }
+
@Test
- public void postProcessVnfAdapter_DeleteResponseTest_VolumeGroupDeletedFalse() {
- volumeGroup.setHeatStackId(TEST_VOLUME_HEATSTACK_ID);
- execution.setVariable("vnfAdapterRestV1Response", "<deleteVolumeGroupResponse><volumeGroupDeleted>false</volumeGroupDeleted></deleteVolumeGroupResponse>");
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- assertEquals(TEST_VOLUME_HEATSTACK_ID, volumeGroup.getHeatStackId());
- }
-
- @Test
- public void postProcessVnfAdapter_DeleteResponseTest_EmptyDeleteVolumeGroupResponseTag() {
+ public void postProcessVnfAdapter_DeleteResponseTest_EmptyDeleteVolumeGroupResponseTag() {
expectedException.expect(BpmnError.class);
- execution.setVariable("vnfAdapterRestV1Response", "<volumeGroupDeleted></volumeGroupDeleted>");
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- }
-
- @Test
- public void postProcessVnfAdapter_DeleteResponseTest_EmptyVolumeGroupDeletedTag() {
- volumeGroup.setHeatStackId(TEST_VOLUME_HEATSTACK_ID);
- execution.setVariable("vnfAdapterRestV1Response", "<deleteVolumeGroupResponse></deleteVolumeGroupResponse>");
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- assertEquals(TEST_VOLUME_HEATSTACK_ID, volumeGroup.getHeatStackId());
- }
-
- @Test
- public void postProcessVnfAdapterExceptionTest() throws BBObjectNotFoundException {
- doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID));
-
- execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_REST_CREATE_RESPONSE);
- expectedException.expect(BpmnError.class);
-
- vnfAdapterImpl.postProcessVnfAdapter(execution);
- }
+ execution.setVariable("vnfAdapterRestV1Response", "<volumeGroupDeleted></volumeGroupDeleted>");
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ }
+
+ @Test
+ public void postProcessVnfAdapter_DeleteResponseTest_EmptyVolumeGroupDeletedTag() {
+ volumeGroup.setHeatStackId(TEST_VOLUME_HEATSTACK_ID);
+ execution.setVariable("vnfAdapterRestV1Response", "<deleteVolumeGroupResponse></deleteVolumeGroupResponse>");
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ assertEquals(TEST_VOLUME_HEATSTACK_ID, volumeGroup.getHeatStackId());
+ }
+
+ @Test
+ public void postProcessVnfAdapterExceptionTest() throws BBObjectNotFoundException {
+ doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),
+ ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID));
+
+ execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_REST_CREATE_RESPONSE);
+ expectedException.expect(BpmnError.class);
+
+ vnfAdapterImpl.postProcessVnfAdapter(execution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/EtsiVnfDeleteTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/EtsiVnfDeleteTaskTest.java
index 5c76018ced..5233203c05 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/EtsiVnfDeleteTaskTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/EtsiVnfDeleteTaskTest.java
@@ -46,66 +46,66 @@ import com.google.common.base.Optional;
*/
public class EtsiVnfDeleteTaskTest extends BaseTaskTest {
- private static final String MODEL_INSTANCE_NAME = "MODEL_INSTANCE_NAME";
-
- private static final String VNF_ID = UUID.randomUUID().toString();
-
- private static final String VNF_NAME = "VNF_NAME";
-
- private static final String JOB_ID = UUID.randomUUID().toString();
-
- @Mock
- private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider;
-
- @Mock
- private GeneralBuildingBlock buildingBlock;
-
- @Mock
- private RequestContext requestContext;
-
- private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution();
-
- @Test
- public void testInvokeVnfmAdapter() throws Exception {
- final EtsiVnfDeleteTask objUnderTest = getEtsiVnfDeleteTask();
- when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf());
- when(mockedVnfmAdapterServiceProvider.invokeDeleteRequest(eq(VNF_ID))).thenReturn(getDeleteVnfResponse());
- objUnderTest.invokeVnfmAdapter(stubbedxecution);
- assertNotNull(stubbedxecution.getVariable(Constants.DELETE_VNF_RESPONSE_PARAM_NAME));
- }
-
- @Test
- public void testInvokeVnfmAdapterException() throws Exception {
- final EtsiVnfDeleteTask objUnderTest = getEtsiVnfDeleteTask();
- when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf());
- when(mockedVnfmAdapterServiceProvider.invokeDeleteRequest(eq(VNF_ID))).thenReturn(Optional.absent());
- objUnderTest.invokeVnfmAdapter(stubbedxecution);
- assertNull(stubbedxecution.getVariable(Constants.DELETE_VNF_RESPONSE_PARAM_NAME));
- verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1212),
- any(Exception.class));
- }
-
- private Optional<DeleteVnfResponse> getDeleteVnfResponse() {
- final DeleteVnfResponse response = new DeleteVnfResponse();
- response.setJobId(JOB_ID);
- return Optional.of(response);
- }
-
- private GenericVnf getGenericVnf() {
- final GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId(VNF_ID);
- genericVnf.setModelInfoGenericVnf(getModelInfoGenericVnf());
- genericVnf.setVnfName(VNF_NAME);
- return genericVnf;
- }
-
- private ModelInfoGenericVnf getModelInfoGenericVnf() {
- final ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInstanceName(MODEL_INSTANCE_NAME);
- return modelInfoGenericVnf;
- }
-
- private EtsiVnfDeleteTask getEtsiVnfDeleteTask() {
- return new EtsiVnfDeleteTask(exceptionUtil, extractPojosForBB, mockedVnfmAdapterServiceProvider);
- }
+ private static final String MODEL_INSTANCE_NAME = "MODEL_INSTANCE_NAME";
+
+ private static final String VNF_ID = UUID.randomUUID().toString();
+
+ private static final String VNF_NAME = "VNF_NAME";
+
+ private static final String JOB_ID = UUID.randomUUID().toString();
+
+ @Mock
+ private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider;
+
+ @Mock
+ private GeneralBuildingBlock buildingBlock;
+
+ @Mock
+ private RequestContext requestContext;
+
+ private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution();
+
+ @Test
+ public void testInvokeVnfmAdapter() throws Exception {
+ final EtsiVnfDeleteTask objUnderTest = getEtsiVnfDeleteTask();
+ when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf());
+ when(mockedVnfmAdapterServiceProvider.invokeDeleteRequest(eq(VNF_ID))).thenReturn(getDeleteVnfResponse());
+ objUnderTest.invokeVnfmAdapter(stubbedxecution);
+ assertNotNull(stubbedxecution.getVariable(Constants.DELETE_VNF_RESPONSE_PARAM_NAME));
+ }
+
+ @Test
+ public void testInvokeVnfmAdapterException() throws Exception {
+ final EtsiVnfDeleteTask objUnderTest = getEtsiVnfDeleteTask();
+ when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf());
+ when(mockedVnfmAdapterServiceProvider.invokeDeleteRequest(eq(VNF_ID))).thenReturn(Optional.absent());
+ objUnderTest.invokeVnfmAdapter(stubbedxecution);
+ assertNull(stubbedxecution.getVariable(Constants.DELETE_VNF_RESPONSE_PARAM_NAME));
+ verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1212),
+ any(Exception.class));
+ }
+
+ private Optional<DeleteVnfResponse> getDeleteVnfResponse() {
+ final DeleteVnfResponse response = new DeleteVnfResponse();
+ response.setJobId(JOB_ID);
+ return Optional.of(response);
+ }
+
+ private GenericVnf getGenericVnf() {
+ final GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId(VNF_ID);
+ genericVnf.setModelInfoGenericVnf(getModelInfoGenericVnf());
+ genericVnf.setVnfName(VNF_NAME);
+ return genericVnf;
+ }
+
+ private ModelInfoGenericVnf getModelInfoGenericVnf() {
+ final ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInstanceName(MODEL_INSTANCE_NAME);
+ return modelInfoGenericVnf;
+ }
+
+ private EtsiVnfDeleteTask getEtsiVnfDeleteTask() {
+ return new EtsiVnfDeleteTask(exceptionUtil, extractPojosForBB, mockedVnfmAdapterServiceProvider);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTaskTest.java
index 803b58b4b8..5805ea5ec1 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTaskTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTaskTest.java
@@ -24,12 +24,10 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
-
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTaskTest.java
index ed5fa94100..718418eae0 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTaskTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTaskTest.java
@@ -49,130 +49,131 @@ import com.google.common.base.Optional;
*/
public class MonitorVnfmCreateJobTaskTest extends BaseTaskTest {
- private static final String JOB_ID = UUID.randomUUID().toString();
-
- @Mock
- private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider;
-
- private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution();
-
- @Test
- public void testGetCurrentOperationStatus() throws Exception {
- final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
- stubbedxecution.setVariable(Constants.CREATE_VNF_RESPONSE_PARAM_NAME, getCreateVnfResponse());
- Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
- queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND);
- queryJobResponse.get().setOperationState(OperationStateEnum.COMPLETED);
- when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
- objUnderTest.getCurrentOperationStatus(stubbedxecution);
- final Optional<OperationStateEnum> operationState =
- stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
- assertNotNull(operationState);
- assertEquals(OperationStateEnum.COMPLETED, operationState.get());
- }
-
- @Test
- public void testGetCurrentOperationStatusFailed() throws Exception {
- final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
- stubbedxecution.setVariable(Constants.CREATE_VNF_RESPONSE_PARAM_NAME, getCreateVnfResponse());
- Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
- queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.CANNOT_RETRIEVE_STATUS);
- queryJobResponse.get().setOperationState(OperationStateEnum.FAILED);
- when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
- objUnderTest.getCurrentOperationStatus(stubbedxecution);
- final Optional<OperationStateEnum> operationState =
- stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
- assertNotNull(operationState);
- assertEquals(OperationStateEnum.FAILED, operationState.get());
- }
-
- @Test
- public void testGetCurrentOperationStatusEmpty() throws Exception {
- final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
- stubbedxecution.setVariable(Constants.CREATE_VNF_RESPONSE_PARAM_NAME, getCreateVnfResponse());
- Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
- queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND);
- when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
- objUnderTest.getCurrentOperationStatus(stubbedxecution);
- final Optional<OperationStateEnum> operationState =
- stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
- assertFalse(operationState.isPresent());
- }
-
- @Test
- public void testGetCurrentOperationStatusException() throws Exception {
- final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
- stubbedxecution.setVariable(Constants.CREATE_VNF_RESPONSE_PARAM_NAME, getCreateVnfResponse());
- Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
- queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND);
- when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
- objUnderTest.getCurrentOperationStatus(stubbedxecution);
- final Optional<OperationStateEnum> operationState =
- stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
- assertFalse(operationState.isPresent());
- }
-
- @Test
- public void testHasOperationFinished() throws Exception {
- final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
- stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.of(OperationStateEnum.COMPLETED));
- assertTrue(objUnderTest.hasOperationFinished(stubbedxecution));
- }
-
- @Test
- public void testHasOperationPending() throws Exception {
- final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
- stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.absent());
- assertFalse(objUnderTest.hasOperationFinished(stubbedxecution));
- }
-
- @Test
- public void testTimeOutLogFailue() throws Exception {
- final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
- objUnderTest.timeOutLogFailue(stubbedxecution);
- verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1205),
- eq("Instantiation operation time out"));
- }
-
- @Test
- public void testCheckIfOperationWasSuccessful() throws Exception {
- stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.of(OperationStateEnum.COMPLETED));
- MonitorVnfmCreateJobTask objUnderTest = Mockito.spy(getEtsiVnfMonitorJobTask());
- objUnderTest.checkIfOperationWasSuccessful(stubbedxecution);
- verify(objUnderTest, times(1)).checkIfOperationWasSuccessful(stubbedxecution);
- }
-
- @Test
- public void testCheckIfOperationWasSuccessfulWithPending() throws Exception {
- final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
- stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.of(OperationStateEnum.PROCESSING));
- objUnderTest.checkIfOperationWasSuccessful(stubbedxecution);
- verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1207), anyString());
- }
-
- @Test
- public void testCheckIfOperationWasSuccessfulEmpty() throws Exception {
- MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
- stubbedxecution.setVariable(Constants.CREATE_VNF_RESPONSE_PARAM_NAME, getCreateVnfResponse());
- stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.absent());
- objUnderTest.checkIfOperationWasSuccessful(stubbedxecution);
- verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1206), anyString());
- }
-
- private CreateVnfResponse getCreateVnfResponse() {
- final CreateVnfResponse response = new CreateVnfResponse();
- response.setJobId(JOB_ID);
- return response;
- }
-
- private Optional<QueryJobResponse> getQueryJobResponse() {
- final QueryJobResponse queryJobResponse = new QueryJobResponse();
- queryJobResponse.setId(JOB_ID);
- return Optional.of(queryJobResponse);
- }
-
- private MonitorVnfmCreateJobTask getEtsiVnfMonitorJobTask() {
- return new MonitorVnfmCreateJobTask(mockedVnfmAdapterServiceProvider, exceptionUtil);
- }
+ private static final String JOB_ID = UUID.randomUUID().toString();
+
+ @Mock
+ private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider;
+
+ private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution();
+
+ @Test
+ public void testGetCurrentOperationStatus() throws Exception {
+ final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
+ stubbedxecution.setVariable(Constants.CREATE_VNF_RESPONSE_PARAM_NAME, getCreateVnfResponse());
+ Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
+ queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND);
+ queryJobResponse.get().setOperationState(OperationStateEnum.COMPLETED);
+ when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
+ objUnderTest.getCurrentOperationStatus(stubbedxecution);
+ final Optional<OperationStateEnum> operationState =
+ stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
+ assertNotNull(operationState);
+ assertEquals(OperationStateEnum.COMPLETED, operationState.get());
+ }
+
+ @Test
+ public void testGetCurrentOperationStatusFailed() throws Exception {
+ final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
+ stubbedxecution.setVariable(Constants.CREATE_VNF_RESPONSE_PARAM_NAME, getCreateVnfResponse());
+ Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
+ queryJobResponse.get()
+ .setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.CANNOT_RETRIEVE_STATUS);
+ queryJobResponse.get().setOperationState(OperationStateEnum.FAILED);
+ when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
+ objUnderTest.getCurrentOperationStatus(stubbedxecution);
+ final Optional<OperationStateEnum> operationState =
+ stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
+ assertNotNull(operationState);
+ assertEquals(OperationStateEnum.FAILED, operationState.get());
+ }
+
+ @Test
+ public void testGetCurrentOperationStatusEmpty() throws Exception {
+ final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
+ stubbedxecution.setVariable(Constants.CREATE_VNF_RESPONSE_PARAM_NAME, getCreateVnfResponse());
+ Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
+ queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND);
+ when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
+ objUnderTest.getCurrentOperationStatus(stubbedxecution);
+ final Optional<OperationStateEnum> operationState =
+ stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
+ assertFalse(operationState.isPresent());
+ }
+
+ @Test
+ public void testGetCurrentOperationStatusException() throws Exception {
+ final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
+ stubbedxecution.setVariable(Constants.CREATE_VNF_RESPONSE_PARAM_NAME, getCreateVnfResponse());
+ Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
+ queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND);
+ when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
+ objUnderTest.getCurrentOperationStatus(stubbedxecution);
+ final Optional<OperationStateEnum> operationState =
+ stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
+ assertFalse(operationState.isPresent());
+ }
+
+ @Test
+ public void testHasOperationFinished() throws Exception {
+ final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
+ stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.of(OperationStateEnum.COMPLETED));
+ assertTrue(objUnderTest.hasOperationFinished(stubbedxecution));
+ }
+
+ @Test
+ public void testHasOperationPending() throws Exception {
+ final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
+ stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.absent());
+ assertFalse(objUnderTest.hasOperationFinished(stubbedxecution));
+ }
+
+ @Test
+ public void testTimeOutLogFailue() throws Exception {
+ final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
+ objUnderTest.timeOutLogFailue(stubbedxecution);
+ verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1205),
+ eq("Instantiation operation time out"));
+ }
+
+ @Test
+ public void testCheckIfOperationWasSuccessful() throws Exception {
+ stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.of(OperationStateEnum.COMPLETED));
+ MonitorVnfmCreateJobTask objUnderTest = Mockito.spy(getEtsiVnfMonitorJobTask());
+ objUnderTest.checkIfOperationWasSuccessful(stubbedxecution);
+ verify(objUnderTest, times(1)).checkIfOperationWasSuccessful(stubbedxecution);
+ }
+
+ @Test
+ public void testCheckIfOperationWasSuccessfulWithPending() throws Exception {
+ final MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
+ stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.of(OperationStateEnum.PROCESSING));
+ objUnderTest.checkIfOperationWasSuccessful(stubbedxecution);
+ verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1207), anyString());
+ }
+
+ @Test
+ public void testCheckIfOperationWasSuccessfulEmpty() throws Exception {
+ MonitorVnfmCreateJobTask objUnderTest = getEtsiVnfMonitorJobTask();
+ stubbedxecution.setVariable(Constants.CREATE_VNF_RESPONSE_PARAM_NAME, getCreateVnfResponse());
+ stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.absent());
+ objUnderTest.checkIfOperationWasSuccessful(stubbedxecution);
+ verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1206), anyString());
+ }
+
+ private CreateVnfResponse getCreateVnfResponse() {
+ final CreateVnfResponse response = new CreateVnfResponse();
+ response.setJobId(JOB_ID);
+ return response;
+ }
+
+ private Optional<QueryJobResponse> getQueryJobResponse() {
+ final QueryJobResponse queryJobResponse = new QueryJobResponse();
+ queryJobResponse.setId(JOB_ID);
+ return Optional.of(queryJobResponse);
+ }
+
+ private MonitorVnfmCreateJobTask getEtsiVnfMonitorJobTask() {
+ return new MonitorVnfmCreateJobTask(mockedVnfmAdapterServiceProvider, exceptionUtil);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTaskTest.java
index e41c571765..a821de1cd1 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTaskTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTaskTest.java
@@ -50,124 +50,125 @@ import com.google.common.base.Optional;
*/
public class MonitorVnfmDeleteJobTaskTest extends BaseTaskTest {
- private static final String JOB_ID = UUID.randomUUID().toString();
-
- private MonitorVnfmDeleteJobTask objUnderTest;
-
- @Mock
- private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider;
-
- private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution();
-
- @Before
- public void setUp() {
- objUnderTest = getEtsiVnfMonitorJobTask();
- stubbedxecution.setVariable(Constants.DELETE_VNF_RESPONSE_PARAM_NAME, getDeleteVnfResponse());
- }
-
- @Test
- public void testGetCurrentOperationStatus() throws Exception {
- Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
- queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND);
- queryJobResponse.get().setOperationState(OperationStateEnum.COMPLETED);
- when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
- objUnderTest.getCurrentOperationStatus(stubbedxecution);
- final Optional<OperationStateEnum> operationState =
- stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
- assertNotNull(operationState);
- assertEquals(OperationStateEnum.COMPLETED, operationState.get());
- }
-
- @Test
- public void testGetCurrentOperationStatusFailed() throws Exception {
- Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
- queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.CANNOT_RETRIEVE_STATUS);
- queryJobResponse.get().setOperationState(OperationStateEnum.FAILED);
- when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
- objUnderTest.getCurrentOperationStatus(stubbedxecution);
- final Optional<OperationStateEnum> operationState =
- stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
- assertNotNull(operationState);
- assertEquals(OperationStateEnum.FAILED, operationState.get());
- }
-
- @Test
- public void testGetCurrentOperationStatusEmpty() throws Exception {
- Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
- queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND);
- when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
- objUnderTest.getCurrentOperationStatus(stubbedxecution);
- final Optional<OperationStateEnum> operationState =
- stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
- assertFalse(operationState.isPresent());
- }
-
- @Test
- public void testGetCurrentOperationStatusException() throws Exception {
- Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
- queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND);
- when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
- objUnderTest.getCurrentOperationStatus(stubbedxecution);
- final Optional<OperationStateEnum> operationState =
- stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
- assertFalse(operationState.isPresent());
- }
-
- @Test
- public void testHasOperationFinished() throws Exception {
- stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.of(OperationStateEnum.COMPLETED));
- assertTrue(objUnderTest.hasOperationFinished(stubbedxecution));
- }
-
- @Test
- public void testHasOperationPending() throws Exception {
- stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.absent());
- assertFalse(objUnderTest.hasOperationFinished(stubbedxecution));
- }
-
- @Test
- public void testTimeOutLogFailue() throws Exception {
- objUnderTest.timeOutLogFailue(stubbedxecution);
- verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1213),
- eq("Delete operation time out"));
- }
-
- @Test
- public void testCheckIfOperationWasSuccessful() throws Exception {
- stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.of(OperationStateEnum.COMPLETED));
- MonitorVnfmDeleteJobTask spyObject = Mockito.spy(objUnderTest);
- spyObject.checkIfOperationWasSuccessful(stubbedxecution);
- verify(spyObject, times(1)).checkIfOperationWasSuccessful(stubbedxecution);
- }
-
- @Test
- public void testCheckIfOperationWasSuccessfulWithPending() throws Exception {
- stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.of(OperationStateEnum.PROCESSING));
- objUnderTest.checkIfOperationWasSuccessful(stubbedxecution);
- verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1215), anyString());
- }
-
- @Test
- public void testCheckIfOperationWasSuccessfulEmpty() throws Exception {
- stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.absent());
- objUnderTest.checkIfOperationWasSuccessful(stubbedxecution);
- verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1214), anyString());
- }
-
- private DeleteVnfResponse getDeleteVnfResponse() {
- final DeleteVnfResponse response = new DeleteVnfResponse();
- response.setJobId(JOB_ID);
- return response;
- }
-
- private Optional<QueryJobResponse> getQueryJobResponse() {
- final QueryJobResponse queryJobResponse = new QueryJobResponse();
- queryJobResponse.setId(JOB_ID);
- return Optional.of(queryJobResponse);
- }
-
- private MonitorVnfmDeleteJobTask getEtsiVnfMonitorJobTask() {
- return new MonitorVnfmDeleteJobTask(mockedVnfmAdapterServiceProvider, exceptionUtil);
- }
+ private static final String JOB_ID = UUID.randomUUID().toString();
+
+ private MonitorVnfmDeleteJobTask objUnderTest;
+
+ @Mock
+ private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider;
+
+ private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution();
+
+ @Before
+ public void setUp() {
+ objUnderTest = getEtsiVnfMonitorJobTask();
+ stubbedxecution.setVariable(Constants.DELETE_VNF_RESPONSE_PARAM_NAME, getDeleteVnfResponse());
+ }
+
+ @Test
+ public void testGetCurrentOperationStatus() throws Exception {
+ Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
+ queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND);
+ queryJobResponse.get().setOperationState(OperationStateEnum.COMPLETED);
+ when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
+ objUnderTest.getCurrentOperationStatus(stubbedxecution);
+ final Optional<OperationStateEnum> operationState =
+ stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
+ assertNotNull(operationState);
+ assertEquals(OperationStateEnum.COMPLETED, operationState.get());
+ }
+
+ @Test
+ public void testGetCurrentOperationStatusFailed() throws Exception {
+ Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
+ queryJobResponse.get()
+ .setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.CANNOT_RETRIEVE_STATUS);
+ queryJobResponse.get().setOperationState(OperationStateEnum.FAILED);
+ when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
+ objUnderTest.getCurrentOperationStatus(stubbedxecution);
+ final Optional<OperationStateEnum> operationState =
+ stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
+ assertNotNull(operationState);
+ assertEquals(OperationStateEnum.FAILED, operationState.get());
+ }
+
+ @Test
+ public void testGetCurrentOperationStatusEmpty() throws Exception {
+ Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
+ queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND);
+ when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
+ objUnderTest.getCurrentOperationStatus(stubbedxecution);
+ final Optional<OperationStateEnum> operationState =
+ stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
+ assertFalse(operationState.isPresent());
+ }
+
+ @Test
+ public void testGetCurrentOperationStatusException() throws Exception {
+ Optional<QueryJobResponse> queryJobResponse = getQueryJobResponse();
+ queryJobResponse.get().setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND);
+ when(mockedVnfmAdapterServiceProvider.getInstantiateOperationJobStatus(JOB_ID)).thenReturn(queryJobResponse);
+ objUnderTest.getCurrentOperationStatus(stubbedxecution);
+ final Optional<OperationStateEnum> operationState =
+ stubbedxecution.getVariable(Constants.OPERATION_STATUS_PARAM_NAME);
+ assertFalse(operationState.isPresent());
+ }
+
+ @Test
+ public void testHasOperationFinished() throws Exception {
+ stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.of(OperationStateEnum.COMPLETED));
+ assertTrue(objUnderTest.hasOperationFinished(stubbedxecution));
+ }
+
+ @Test
+ public void testHasOperationPending() throws Exception {
+ stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.absent());
+ assertFalse(objUnderTest.hasOperationFinished(stubbedxecution));
+ }
+
+ @Test
+ public void testTimeOutLogFailue() throws Exception {
+ objUnderTest.timeOutLogFailue(stubbedxecution);
+ verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1213),
+ eq("Delete operation time out"));
+ }
+
+ @Test
+ public void testCheckIfOperationWasSuccessful() throws Exception {
+ stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.of(OperationStateEnum.COMPLETED));
+ MonitorVnfmDeleteJobTask spyObject = Mockito.spy(objUnderTest);
+ spyObject.checkIfOperationWasSuccessful(stubbedxecution);
+ verify(spyObject, times(1)).checkIfOperationWasSuccessful(stubbedxecution);
+ }
+
+ @Test
+ public void testCheckIfOperationWasSuccessfulWithPending() throws Exception {
+ stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.of(OperationStateEnum.PROCESSING));
+ objUnderTest.checkIfOperationWasSuccessful(stubbedxecution);
+ verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1215), anyString());
+ }
+
+ @Test
+ public void testCheckIfOperationWasSuccessfulEmpty() throws Exception {
+ stubbedxecution.setVariable(Constants.OPERATION_STATUS_PARAM_NAME, Optional.absent());
+ objUnderTest.checkIfOperationWasSuccessful(stubbedxecution);
+ verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1214), anyString());
+ }
+
+ private DeleteVnfResponse getDeleteVnfResponse() {
+ final DeleteVnfResponse response = new DeleteVnfResponse();
+ response.setJobId(JOB_ID);
+ return response;
+ }
+
+ private Optional<QueryJobResponse> getQueryJobResponse() {
+ final QueryJobResponse queryJobResponse = new QueryJobResponse();
+ queryJobResponse.setId(JOB_ID);
+ return Optional.of(queryJobResponse);
+ }
+
+ private MonitorVnfmDeleteJobTask getEtsiVnfMonitorJobTask() {
+ return new MonitorVnfmDeleteJobTask(mockedVnfmAdapterServiceProvider, exceptionUtil);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeJobTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeJobTest.java
index aa3ab113a0..6b84f6a918 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeJobTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeJobTest.java
@@ -46,66 +46,66 @@ import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
*/
public class MonitorVnfmNodeJobTest extends BaseTaskTest {
- private static final String VNF_ID = UUID.randomUUID().toString();
-
- private static final String VNF_NAME = "VNF_NAME";
-
- private MonitorVnfmNodeTask objUnderTest;
-
- @Mock
- private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider;
-
- private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution();
-
- @Before
- public void setUp() {
- objUnderTest = getEtsiVnfMonitorNodeJobTask();
- }
-
- @Test
- public void testGetNodeStatusCreate() throws Exception {
- GenericVnf vnf = getGenericVnf();
- vnf.setOrchestrationStatus(VNF_CREATED);
- when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(vnf);
- objUnderTest.getNodeStatus(stubbedxecution);
- assertTrue(stubbedxecution.getVariable(CREATE_VNF_NODE_STATUS));
- }
-
- @Test
- public void testGetNodeStatusDelete() throws Exception {
- GenericVnf vnf = getGenericVnf();
- vnf.setOrchestrationStatus(VNF_ASSIGNED);
- when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(vnf);
- objUnderTest.getNodeStatus(stubbedxecution);
- assertTrue(stubbedxecution.getVariable(DELETE_VNF_NODE_STATUS));
- }
-
- @Test
- public void testGetNodeStatusException() throws Exception {
- when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenThrow(RuntimeException.class);
- objUnderTest.getNodeStatus(stubbedxecution);
- assertNull(stubbedxecution.getVariable(CREATE_VNF_NODE_STATUS));
- assertNull(stubbedxecution.getVariable(DELETE_VNF_NODE_STATUS));
- verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1220),
- any(Exception.class));
- }
-
- @Test
- public void testTimeOutLogFailue() throws Exception {
- objUnderTest.timeOutLogFailue(stubbedxecution);
- verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1221),
- eq("Node operation time out"));
- }
-
- private GenericVnf getGenericVnf() {
- final GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId(VNF_ID);
- genericVnf.setVnfName(VNF_NAME);
- return genericVnf;
- }
-
- private MonitorVnfmNodeTask getEtsiVnfMonitorNodeJobTask() {
- return new MonitorVnfmNodeTask(extractPojosForBB, exceptionUtil);
- }
+ private static final String VNF_ID = UUID.randomUUID().toString();
+
+ private static final String VNF_NAME = "VNF_NAME";
+
+ private MonitorVnfmNodeTask objUnderTest;
+
+ @Mock
+ private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider;
+
+ private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution();
+
+ @Before
+ public void setUp() {
+ objUnderTest = getEtsiVnfMonitorNodeJobTask();
+ }
+
+ @Test
+ public void testGetNodeStatusCreate() throws Exception {
+ GenericVnf vnf = getGenericVnf();
+ vnf.setOrchestrationStatus(VNF_CREATED);
+ when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(vnf);
+ objUnderTest.getNodeStatus(stubbedxecution);
+ assertTrue(stubbedxecution.getVariable(CREATE_VNF_NODE_STATUS));
+ }
+
+ @Test
+ public void testGetNodeStatusDelete() throws Exception {
+ GenericVnf vnf = getGenericVnf();
+ vnf.setOrchestrationStatus(VNF_ASSIGNED);
+ when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(vnf);
+ objUnderTest.getNodeStatus(stubbedxecution);
+ assertTrue(stubbedxecution.getVariable(DELETE_VNF_NODE_STATUS));
+ }
+
+ @Test
+ public void testGetNodeStatusException() throws Exception {
+ when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenThrow(RuntimeException.class);
+ objUnderTest.getNodeStatus(stubbedxecution);
+ assertNull(stubbedxecution.getVariable(CREATE_VNF_NODE_STATUS));
+ assertNull(stubbedxecution.getVariable(DELETE_VNF_NODE_STATUS));
+ verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1220),
+ any(Exception.class));
+ }
+
+ @Test
+ public void testTimeOutLogFailue() throws Exception {
+ objUnderTest.timeOutLogFailue(stubbedxecution);
+ verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1221),
+ eq("Node operation time out"));
+ }
+
+ private GenericVnf getGenericVnf() {
+ final GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId(VNF_ID);
+ genericVnf.setVnfName(VNF_NAME);
+ return genericVnf;
+ }
+
+ private MonitorVnfmNodeTask getEtsiVnfMonitorNodeJobTask() {
+ return new MonitorVnfmNodeTask(extractPojosForBB, exceptionUtil);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/StubbedBuildingBlockExecution.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/StubbedBuildingBlockExecution.java
index 260585d208..84012e8b8d 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/StubbedBuildingBlockExecution.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/StubbedBuildingBlockExecution.java
@@ -38,63 +38,63 @@ import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
*/
public class StubbedBuildingBlockExecution implements BuildingBlockExecution {
- private static final String CLOUD_OWNER = "CLOUD_OWNER";
- private static final String LCP_CLOUD_REGIONID = "RegionOnce";
- private static final String TENANT_ID = UUID.randomUUID().toString();
- private final Map<String, Serializable> execution = new HashMap<>();
- private final GeneralBuildingBlock generalBuildingBlock;
+ private static final String CLOUD_OWNER = "CLOUD_OWNER";
+ private static final String LCP_CLOUD_REGIONID = "RegionOnce";
+ private static final String TENANT_ID = UUID.randomUUID().toString();
+ private final Map<String, Serializable> execution = new HashMap<>();
+ private final GeneralBuildingBlock generalBuildingBlock;
- StubbedBuildingBlockExecution() {
- generalBuildingBlock = getGeneralBuildingBlockValue();
- }
+ StubbedBuildingBlockExecution() {
+ generalBuildingBlock = getGeneralBuildingBlockValue();
+ }
- @Override
- public GeneralBuildingBlock getGeneralBuildingBlock() {
- return generalBuildingBlock;
- }
+ @Override
+ public GeneralBuildingBlock getGeneralBuildingBlock() {
+ return generalBuildingBlock;
+ }
- @SuppressWarnings("unchecked")
- @Override
- public <T> T getVariable(final String key) {
- return (T) execution.get(key);
- }
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T getVariable(final String key) {
+ return (T) execution.get(key);
+ }
- @Override
- public <T> T getRequiredVariable(final String key) throws RequiredExecutionVariableExeception {
- return null;
- }
+ @Override
+ public <T> T getRequiredVariable(final String key) throws RequiredExecutionVariableExeception {
+ return null;
+ }
- @Override
- public void setVariable(final String key, final Serializable value) {
- execution.put(key, value);
- }
+ @Override
+ public void setVariable(final String key, final Serializable value) {
+ execution.put(key, value);
+ }
- @Override
- public Map<ResourceKey, String> getLookupMap() {
- return Collections.emptyMap();
- }
+ @Override
+ public Map<ResourceKey, String> getLookupMap() {
+ return Collections.emptyMap();
+ }
- @Override
- public String getFlowToBeCalled() {
- return null;
- }
+ @Override
+ public String getFlowToBeCalled() {
+ return null;
+ }
- public static String getTenantId() {
- return TENANT_ID;
- }
+ public static String getTenantId() {
+ return TENANT_ID;
+ }
- private GeneralBuildingBlock getGeneralBuildingBlockValue() {
- final GeneralBuildingBlock buildingBlock = new GeneralBuildingBlock();
- buildingBlock.setCloudRegion(getCloudRegion());
- return buildingBlock;
- }
+ private GeneralBuildingBlock getGeneralBuildingBlockValue() {
+ final GeneralBuildingBlock buildingBlock = new GeneralBuildingBlock();
+ buildingBlock.setCloudRegion(getCloudRegion());
+ return buildingBlock;
+ }
- private CloudRegion getCloudRegion() {
- final CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setCloudOwner(CLOUD_OWNER);
- cloudRegion.setLcpCloudRegionId(LCP_CLOUD_REGIONID);
- cloudRegion.setTenantId(TENANT_ID);
- return cloudRegion;
- }
+ private CloudRegion getCloudRegion() {
+ final CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setCloudOwner(CLOUD_OWNER);
+ cloudRegion.setLcpCloudRegionId(LCP_CLOUD_REGIONID);
+ cloudRegion.setTenantId(TENANT_ID);
+ return cloudRegion;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/TestConstants.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/TestConstants.java
index c4f19d6d1a..7b63e5f811 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/TestConstants.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/TestConstants.java
@@ -21,9 +21,7 @@
package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.DUMMY_URL;
-
import java.util.UUID;
-
import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.VnfmBasicHttpConfigProvider;
/**
@@ -36,7 +34,7 @@ public class TestConstants {
public static final String DUMMY_BASIC_AUTH = "Basic 123abc";
public static final String DUMMY_URL = "http://localhost:30406/so/vnfm-adapter/v1/";
public static final String EXPECTED_URL = DUMMY_URL + "vnfs/" + DUMMY_GENERIC_VND_ID;
-
+
public static final String DUMMY_JOB_ID = UUID.randomUUID().toString();
public static final String JOB_STATUS_EXPECTED_URL = DUMMY_URL + "jobs/" + DUMMY_JOB_ID;
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfigurationTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfigurationTest.java
index 5aaebea76e..75151d9c6a 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfigurationTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfigurationTest.java
@@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks;
import static org.junit.Assert.assertNotNull;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.getVnfmBasicHttpConfigProvider;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskTest.java
index 22c4c15079..cfa5aaa4b8 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskTest.java
@@ -51,131 +51,132 @@ import com.google.common.base.Optional;
*/
public class VnfmAdapterCreateVnfTaskTest extends BaseTaskTest {
- private static final String MODEL_INSTANCE_NAME = "MODEL_INSTANCE_NAME";
+ private static final String MODEL_INSTANCE_NAME = "MODEL_INSTANCE_NAME";
- private static final String CLOUD_OWNER = "CLOUD_OWNER";
+ private static final String CLOUD_OWNER = "CLOUD_OWNER";
- private static final String LCP_CLOUD_REGIONID = "RegionOnce";
+ private static final String LCP_CLOUD_REGIONID = "RegionOnce";
- private static final String VNF_ID = UUID.randomUUID().toString();
+ private static final String VNF_ID = UUID.randomUUID().toString();
- private static final String VNF_NAME = "VNF_NAME";
+ private static final String VNF_NAME = "VNF_NAME";
- private static final String JOB_ID = UUID.randomUUID().toString();
+ private static final String JOB_ID = UUID.randomUUID().toString();
- @Mock
- private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider;
+ @Mock
+ private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider;
- private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution();
+ private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution();
- @Test
- public void testBuildCreateVnfRequest_withValidValues_storesRequestInExecution() throws Exception {
+ @Test
+ public void testBuildCreateVnfRequest_withValidValues_storesRequestInExecution() throws Exception {
- final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask();
- stubbedxecution.setVariable(INPUT_PARAMETER, new InputParameter(Collections.emptyMap(), Collections.emptyList()));
+ final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask();
+ stubbedxecution.setVariable(INPUT_PARAMETER,
+ new InputParameter(Collections.emptyMap(), Collections.emptyList()));
- when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf());
- objUnderTest.buildCreateVnfRequest(stubbedxecution);
+ when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf());
+ objUnderTest.buildCreateVnfRequest(stubbedxecution);
- final CreateVnfRequest actual = stubbedxecution.getVariable(CREATE_VNF_REQUEST_PARAM_NAME);
- assertNotNull(actual);
- assertEquals(VNF_NAME + "." + MODEL_INSTANCE_NAME, actual.getName());
+ final CreateVnfRequest actual = stubbedxecution.getVariable(CREATE_VNF_REQUEST_PARAM_NAME);
+ assertNotNull(actual);
+ assertEquals(VNF_NAME + "." + MODEL_INSTANCE_NAME, actual.getName());
- final Tenant actualTenant = actual.getTenant();
- assertEquals(CLOUD_OWNER, actualTenant.getCloudOwner());
- assertEquals(LCP_CLOUD_REGIONID, actualTenant.getRegionName());
- assertEquals(StubbedBuildingBlockExecution.getTenantId(), actualTenant.getTenantId());
+ final Tenant actualTenant = actual.getTenant();
+ assertEquals(CLOUD_OWNER, actualTenant.getCloudOwner());
+ assertEquals(LCP_CLOUD_REGIONID, actualTenant.getRegionName());
+ assertEquals(StubbedBuildingBlockExecution.getTenantId(), actualTenant.getTenantId());
- }
+ }
- @Test
- public void testBuildCreateVnfRequest_extractPojosForBBThrowsException_exceptionBuilderCalled() throws Exception {
+ @Test
+ public void testBuildCreateVnfRequest_extractPojosForBBThrowsException_exceptionBuilderCalled() throws Exception {
- final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask();
+ final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask();
- when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenThrow(RuntimeException.class);
+ when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenThrow(RuntimeException.class);
- objUnderTest.buildCreateVnfRequest(stubbedxecution);
+ objUnderTest.buildCreateVnfRequest(stubbedxecution);
- final CreateVnfRequest actual = stubbedxecution.getVariable(CREATE_VNF_REQUEST_PARAM_NAME);
+ final CreateVnfRequest actual = stubbedxecution.getVariable(CREATE_VNF_REQUEST_PARAM_NAME);
- assertNull(actual);
- verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1200),
- any(Exception.class));
+ assertNull(actual);
+ verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1200),
+ any(Exception.class));
- }
+ }
- @Test
- public void testInvokeVnfmAdapter_validValues_storesResponseInExecution() throws Exception {
+ @Test
+ public void testInvokeVnfmAdapter_validValues_storesResponseInExecution() throws Exception {
- final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask();
+ final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask();
- stubbedxecution.setVariable(CREATE_VNF_REQUEST_PARAM_NAME, new CreateVnfRequest());
+ stubbedxecution.setVariable(CREATE_VNF_REQUEST_PARAM_NAME, new CreateVnfRequest());
- when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf());
- when(mockedVnfmAdapterServiceProvider.invokeCreateInstantiationRequest(eq(VNF_ID), any(CreateVnfRequest.class)))
- .thenReturn(getCreateVnfResponse());
+ when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf());
+ when(mockedVnfmAdapterServiceProvider.invokeCreateInstantiationRequest(eq(VNF_ID), any(CreateVnfRequest.class)))
+ .thenReturn(getCreateVnfResponse());
- objUnderTest.invokeVnfmAdapter(stubbedxecution);
+ objUnderTest.invokeVnfmAdapter(stubbedxecution);
- assertNotNull(stubbedxecution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME));
- }
+ assertNotNull(stubbedxecution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME));
+ }
- @Test
- public void testInvokeVnfmAdapter_invalidValues_storesResponseInExecution() throws Exception {
+ @Test
+ public void testInvokeVnfmAdapter_invalidValues_storesResponseInExecution() throws Exception {
- final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask();
+ final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask();
- stubbedxecution.setVariable(CREATE_VNF_REQUEST_PARAM_NAME, new CreateVnfRequest());
+ stubbedxecution.setVariable(CREATE_VNF_REQUEST_PARAM_NAME, new CreateVnfRequest());
- when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf());
- when(mockedVnfmAdapterServiceProvider.invokeCreateInstantiationRequest(eq(VNF_ID), any(CreateVnfRequest.class)))
- .thenReturn(Optional.absent());
+ when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf());
+ when(mockedVnfmAdapterServiceProvider.invokeCreateInstantiationRequest(eq(VNF_ID), any(CreateVnfRequest.class)))
+ .thenReturn(Optional.absent());
- objUnderTest.invokeVnfmAdapter(stubbedxecution);
+ objUnderTest.invokeVnfmAdapter(stubbedxecution);
- assertNull(stubbedxecution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME));
- verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1202),
- any(Exception.class));
- }
+ assertNull(stubbedxecution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME));
+ verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1202),
+ any(Exception.class));
+ }
- @Test
- public void testInvokeVnfmAdapter_extractPojosForBBThrowsException_exceptionBuilderCalled() throws Exception {
+ @Test
+ public void testInvokeVnfmAdapter_extractPojosForBBThrowsException_exceptionBuilderCalled() throws Exception {
- final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask();
+ final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask();
- when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenThrow(RuntimeException.class);
+ when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenThrow(RuntimeException.class);
- objUnderTest.invokeVnfmAdapter(stubbedxecution);
+ objUnderTest.invokeVnfmAdapter(stubbedxecution);
- assertNull(stubbedxecution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME));
- verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1202),
- any(Exception.class));
+ assertNull(stubbedxecution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME));
+ verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1202),
+ any(Exception.class));
- }
+ }
- private Optional<CreateVnfResponse> getCreateVnfResponse() {
- final CreateVnfResponse response = new CreateVnfResponse();
- response.setJobId(JOB_ID);
- return Optional.of(response);
- }
+ private Optional<CreateVnfResponse> getCreateVnfResponse() {
+ final CreateVnfResponse response = new CreateVnfResponse();
+ response.setJobId(JOB_ID);
+ return Optional.of(response);
+ }
- private GenericVnf getGenericVnf() {
- final GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId(VNF_ID);
- genericVnf.setModelInfoGenericVnf(getModelInfoGenericVnf());
- genericVnf.setVnfName(VNF_NAME);
- return genericVnf;
- }
+ private GenericVnf getGenericVnf() {
+ final GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId(VNF_ID);
+ genericVnf.setModelInfoGenericVnf(getModelInfoGenericVnf());
+ genericVnf.setVnfName(VNF_NAME);
+ return genericVnf;
+ }
- private ModelInfoGenericVnf getModelInfoGenericVnf() {
- final ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInstanceName(MODEL_INSTANCE_NAME);
- return modelInfoGenericVnf;
- }
+ private ModelInfoGenericVnf getModelInfoGenericVnf() {
+ final ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInstanceName(MODEL_INSTANCE_NAME);
+ return modelInfoGenericVnf;
+ }
- private VnfmAdapterCreateVnfTask getEtsiVnfInstantiateTask() {
- return new VnfmAdapterCreateVnfTask(exceptionUtil, extractPojosForBB, mockedVnfmAdapterServiceProvider);
- }
+ private VnfmAdapterCreateVnfTask getEtsiVnfInstantiateTask() {
+ return new VnfmAdapterCreateVnfTask(exceptionUtil, extractPojosForBB, mockedVnfmAdapterServiceProvider);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImplTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImplTest.java
index 6f1b6f0bd2..7bd6435b60 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImplTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImplTest.java
@@ -52,242 +52,242 @@ import com.google.common.base.Optional;
@RunWith(MockitoJUnitRunner.class)
public class VnfmAdapterServiceProviderImplTest {
- private static final String EMPTY_JOB_ID = "";
-
- private static final CreateVnfRequest CREATE_VNF_REQUEST = new CreateVnfRequest();
-
- @Mock
- private HttpRestServiceProvider mockedHttpServiceProvider;
-
- @Mock
- private ResponseEntity<CreateVnfResponse> mockedResponseEntity;
-
- @Mock
- private ResponseEntity<DeleteVnfResponse> deleteVnfResponse;
- @Mock
- private ResponseEntity<QueryJobResponse> mockedQueryJobResponseResponseEntity;
-
- @Test
- public void testInvokeCreateInstantiationRequest_httpServiceProviderReturnsStatusAcceptedWithBody_validResponse() {
-
- when(mockedHttpServiceProvider.postHttpRequest(eq(CREATE_VNF_REQUEST), anyString(), eq(CreateVnfResponse.class)))
- .thenReturn(mockedResponseEntity);
- when(mockedResponseEntity.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
- when(mockedResponseEntity.hasBody()).thenReturn(true);
- final CreateVnfResponse response = getCreateVnfResponse(DUMMY_JOB_ID);
- when(mockedResponseEntity.getBody()).thenReturn(response);
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
- final Optional<CreateVnfResponse> actual =
- objUnderTest.invokeCreateInstantiationRequest(DUMMY_GENERIC_VND_ID, CREATE_VNF_REQUEST);
- assertTrue(actual.isPresent());
- assertEquals(actual.get(), response);
- }
-
- @Test
- public void testInvokeCreateInstantiationRequest_httpServiceProviderReturnsStatusAcceptedWithNoBody_noResponse() {
- assertWithStatuCode(HttpStatus.ACCEPTED);
- }
-
- @Test
- public void testInvokeCreateInstantiationRequest_httpServiceProviderReturnsStatusNotOkWithNoBody_noResponse() {
- assertWithStatuCode(HttpStatus.UNAUTHORIZED);
- }
-
-
- @Test
- public void testInvokeCreateInstantiationRequest_httpServiceProviderReturnsStatusAcceptedWithBodyWithInvalidJobId_noResponse() {
- assertWithJobId(null);
- assertWithJobId(EMPTY_JOB_ID);
- }
-
- @Test
- public void testInvokeCreateInstantiationRequest_httpServiceProviderThrowException_httpRestServiceProviderNotNull() {
-
- when(mockedHttpServiceProvider.postHttpRequest(eq(CREATE_VNF_REQUEST), anyString(), eq(CreateVnfResponse.class)))
- .thenThrow(RestProcessingException.class);
-
-
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
-
- final Optional<CreateVnfResponse> actual =
- objUnderTest.invokeCreateInstantiationRequest(DUMMY_GENERIC_VND_ID, CREATE_VNF_REQUEST);
- assertFalse(actual.isPresent());
-
- }
-
- @Test
- public void testInvokeDeleteRequest() {
- when(mockedHttpServiceProvider.deleteHttpRequest(anyString(), eq(DeleteVnfResponse.class)))
- .thenReturn(deleteVnfResponse);
- when(deleteVnfResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
- when(deleteVnfResponse.hasBody()).thenReturn(true);
- final DeleteVnfResponse response = getDeleteVnfResponse(DUMMY_JOB_ID);
- when(deleteVnfResponse.getBody()).thenReturn(response);
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
- final Optional<DeleteVnfResponse> actual = objUnderTest.invokeDeleteRequest(DUMMY_GENERIC_VND_ID);
- assertTrue(actual.isPresent());
- }
-
- @Test
- public void testInvokeDeleteRequestNotAccepted() {
- when(mockedHttpServiceProvider.deleteHttpRequest(anyString(), eq(DeleteVnfResponse.class)))
- .thenReturn(deleteVnfResponse);
- when(deleteVnfResponse.getStatusCode()).thenReturn(HttpStatus.BAD_GATEWAY);
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
- final Optional<DeleteVnfResponse> actual = objUnderTest.invokeDeleteRequest(DUMMY_GENERIC_VND_ID);
- assertFalse(actual.isPresent());
- }
-
- @Test
- public void testInvokeDeleteRequestNoBody() {
- when(mockedHttpServiceProvider.deleteHttpRequest(anyString(), eq(DeleteVnfResponse.class)))
- .thenReturn(deleteVnfResponse);
- when(deleteVnfResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
- when(deleteVnfResponse.hasBody()).thenReturn(false);
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
- final Optional<DeleteVnfResponse> actual = objUnderTest.invokeDeleteRequest(DUMMY_GENERIC_VND_ID);
- assertFalse(actual.isPresent());
- }
-
- @Test
- public void testInvokeDeleteRequestNoJobId() {
- when(mockedHttpServiceProvider.deleteHttpRequest(anyString(), eq(DeleteVnfResponse.class)))
- .thenReturn(deleteVnfResponse);
- when(deleteVnfResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
- when(deleteVnfResponse.hasBody()).thenReturn(true);
- final DeleteVnfResponse response = getDeleteVnfResponse("");
- when(deleteVnfResponse.getBody()).thenReturn(response);
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
- final Optional<DeleteVnfResponse> actual = objUnderTest.invokeDeleteRequest(DUMMY_GENERIC_VND_ID);
- assertFalse(actual.isPresent());
- }
-
- @Test
- public void testInvokeDeleteRequestException() {
- when(mockedHttpServiceProvider.deleteHttpRequest(anyString(), eq(DeleteVnfResponse.class)))
- .thenThrow(RestProcessingException.class);
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
- final Optional<DeleteVnfResponse> actual = objUnderTest.invokeDeleteRequest(DUMMY_GENERIC_VND_ID);
- assertFalse(actual.isPresent());
- }
-
- @Test
- public void testGetInstantiateOperationJobStatus_httpServiceProviderReturnsStatusOkWithBody_validResponse() {
-
- when(mockedQueryJobResponseResponseEntity.getStatusCode()).thenReturn(HttpStatus.OK);
- when(mockedQueryJobResponseResponseEntity.hasBody()).thenReturn(true);
- when(mockedQueryJobResponseResponseEntity.getBody()).thenReturn(getQueryJobResponse());
-
- when(mockedHttpServiceProvider.getHttpResponse(eq(TestConstants.JOB_STATUS_EXPECTED_URL),
- eq(QueryJobResponse.class))).thenReturn(mockedQueryJobResponseResponseEntity);
-
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
-
- final Optional<QueryJobResponse> actual = objUnderTest.getInstantiateOperationJobStatus(DUMMY_JOB_ID);
- assertTrue(actual.isPresent());
- final QueryJobResponse actualQueryJobResponse = actual.get();
- assertNotNull(actualQueryJobResponse);
- }
-
- @Test
- public void testGetInstantiateOperationJobStatus_httpServiceProviderReturnsStatusOkWithOutBody_invalidResponse() {
-
- when(mockedQueryJobResponseResponseEntity.getStatusCode()).thenReturn(HttpStatus.OK);
- when(mockedQueryJobResponseResponseEntity.hasBody()).thenReturn(false);
-
- when(mockedHttpServiceProvider.getHttpResponse(eq(TestConstants.JOB_STATUS_EXPECTED_URL),
- eq(QueryJobResponse.class))).thenReturn(mockedQueryJobResponseResponseEntity);
-
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
-
- final Optional<QueryJobResponse> actual = objUnderTest.getInstantiateOperationJobStatus(DUMMY_JOB_ID);
- assertFalse(actual.isPresent());
- }
-
- @Test
- public void testGetInstantiateOperationJobStatus_httpServiceProviderReturnsStatusNotOkWithOutBody_invalidResponse() {
-
- when(mockedQueryJobResponseResponseEntity.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
-
- when(mockedHttpServiceProvider.getHttpResponse(eq(TestConstants.JOB_STATUS_EXPECTED_URL),
- eq(QueryJobResponse.class))).thenReturn(mockedQueryJobResponseResponseEntity);
-
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
-
- final Optional<QueryJobResponse> actual = objUnderTest.getInstantiateOperationJobStatus(DUMMY_JOB_ID);
- assertFalse(actual.isPresent());
- }
-
- @Test
- public void testGetInstantiateOperationJobStatus_Exception() {
-
- when(mockedHttpServiceProvider.getHttpResponse(eq(TestConstants.JOB_STATUS_EXPECTED_URL),
- eq(QueryJobResponse.class))).thenThrow(RestProcessingException.class);
-
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
-
- final Optional<QueryJobResponse> actual = objUnderTest.getInstantiateOperationJobStatus(DUMMY_JOB_ID);
- assertFalse(actual.isPresent());
- }
-
- private QueryJobResponse getQueryJobResponse() {
- return new QueryJobResponse().id(DUMMY_JOB_ID).operationState(OperationStateEnum.COMPLETED);
-
- }
-
- private void assertWithJobId(final String jobId) {
- when(mockedHttpServiceProvider.postHttpRequest(eq(CREATE_VNF_REQUEST), anyString(), eq(CreateVnfResponse.class)))
- .thenReturn(mockedResponseEntity);
- when(mockedResponseEntity.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
- when(mockedResponseEntity.hasBody()).thenReturn(true);
- final CreateVnfResponse response = getCreateVnfResponse(jobId);
- when(mockedResponseEntity.getBody()).thenReturn(response);
-
-
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
-
- final Optional<CreateVnfResponse> actual =
- objUnderTest.invokeCreateInstantiationRequest(DUMMY_GENERIC_VND_ID, CREATE_VNF_REQUEST);
- assertFalse(actual.isPresent());
- }
-
- private void assertWithStatuCode(final HttpStatus status) {
- when(mockedHttpServiceProvider.postHttpRequest(eq(CREATE_VNF_REQUEST), anyString(), eq(CreateVnfResponse.class)))
- .thenReturn(mockedResponseEntity);
- when(mockedResponseEntity.getStatusCode()).thenReturn(status);
- when(mockedResponseEntity.hasBody()).thenReturn(false);
+ private static final String EMPTY_JOB_ID = "";
+
+ private static final CreateVnfRequest CREATE_VNF_REQUEST = new CreateVnfRequest();
+
+ @Mock
+ private HttpRestServiceProvider mockedHttpServiceProvider;
+
+ @Mock
+ private ResponseEntity<CreateVnfResponse> mockedResponseEntity;
+
+ @Mock
+ private ResponseEntity<DeleteVnfResponse> deleteVnfResponse;
+ @Mock
+ private ResponseEntity<QueryJobResponse> mockedQueryJobResponseResponseEntity;
+
+ @Test
+ public void testInvokeCreateInstantiationRequest_httpServiceProviderReturnsStatusAcceptedWithBody_validResponse() {
+
+ when(mockedHttpServiceProvider.postHttpRequest(eq(CREATE_VNF_REQUEST), anyString(),
+ eq(CreateVnfResponse.class))).thenReturn(mockedResponseEntity);
+ when(mockedResponseEntity.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
+ when(mockedResponseEntity.hasBody()).thenReturn(true);
+ final CreateVnfResponse response = getCreateVnfResponse(DUMMY_JOB_ID);
+ when(mockedResponseEntity.getBody()).thenReturn(response);
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+ final Optional<CreateVnfResponse> actual =
+ objUnderTest.invokeCreateInstantiationRequest(DUMMY_GENERIC_VND_ID, CREATE_VNF_REQUEST);
+ assertTrue(actual.isPresent());
+ assertEquals(actual.get(), response);
+ }
+
+ @Test
+ public void testInvokeCreateInstantiationRequest_httpServiceProviderReturnsStatusAcceptedWithNoBody_noResponse() {
+ assertWithStatuCode(HttpStatus.ACCEPTED);
+ }
+
+ @Test
+ public void testInvokeCreateInstantiationRequest_httpServiceProviderReturnsStatusNotOkWithNoBody_noResponse() {
+ assertWithStatuCode(HttpStatus.UNAUTHORIZED);
+ }
+
+
+ @Test
+ public void testInvokeCreateInstantiationRequest_httpServiceProviderReturnsStatusAcceptedWithBodyWithInvalidJobId_noResponse() {
+ assertWithJobId(null);
+ assertWithJobId(EMPTY_JOB_ID);
+ }
+
+ @Test
+ public void testInvokeCreateInstantiationRequest_httpServiceProviderThrowException_httpRestServiceProviderNotNull() {
+
+ when(mockedHttpServiceProvider.postHttpRequest(eq(CREATE_VNF_REQUEST), anyString(),
+ eq(CreateVnfResponse.class))).thenThrow(RestProcessingException.class);
+
+
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+
+ final Optional<CreateVnfResponse> actual =
+ objUnderTest.invokeCreateInstantiationRequest(DUMMY_GENERIC_VND_ID, CREATE_VNF_REQUEST);
+ assertFalse(actual.isPresent());
+
+ }
+
+ @Test
+ public void testInvokeDeleteRequest() {
+ when(mockedHttpServiceProvider.deleteHttpRequest(anyString(), eq(DeleteVnfResponse.class)))
+ .thenReturn(deleteVnfResponse);
+ when(deleteVnfResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
+ when(deleteVnfResponse.hasBody()).thenReturn(true);
+ final DeleteVnfResponse response = getDeleteVnfResponse(DUMMY_JOB_ID);
+ when(deleteVnfResponse.getBody()).thenReturn(response);
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+ final Optional<DeleteVnfResponse> actual = objUnderTest.invokeDeleteRequest(DUMMY_GENERIC_VND_ID);
+ assertTrue(actual.isPresent());
+ }
+
+ @Test
+ public void testInvokeDeleteRequestNotAccepted() {
+ when(mockedHttpServiceProvider.deleteHttpRequest(anyString(), eq(DeleteVnfResponse.class)))
+ .thenReturn(deleteVnfResponse);
+ when(deleteVnfResponse.getStatusCode()).thenReturn(HttpStatus.BAD_GATEWAY);
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+ final Optional<DeleteVnfResponse> actual = objUnderTest.invokeDeleteRequest(DUMMY_GENERIC_VND_ID);
+ assertFalse(actual.isPresent());
+ }
+
+ @Test
+ public void testInvokeDeleteRequestNoBody() {
+ when(mockedHttpServiceProvider.deleteHttpRequest(anyString(), eq(DeleteVnfResponse.class)))
+ .thenReturn(deleteVnfResponse);
+ when(deleteVnfResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
+ when(deleteVnfResponse.hasBody()).thenReturn(false);
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+ final Optional<DeleteVnfResponse> actual = objUnderTest.invokeDeleteRequest(DUMMY_GENERIC_VND_ID);
+ assertFalse(actual.isPresent());
+ }
+
+ @Test
+ public void testInvokeDeleteRequestNoJobId() {
+ when(mockedHttpServiceProvider.deleteHttpRequest(anyString(), eq(DeleteVnfResponse.class)))
+ .thenReturn(deleteVnfResponse);
+ when(deleteVnfResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
+ when(deleteVnfResponse.hasBody()).thenReturn(true);
+ final DeleteVnfResponse response = getDeleteVnfResponse("");
+ when(deleteVnfResponse.getBody()).thenReturn(response);
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+ final Optional<DeleteVnfResponse> actual = objUnderTest.invokeDeleteRequest(DUMMY_GENERIC_VND_ID);
+ assertFalse(actual.isPresent());
+ }
+
+ @Test
+ public void testInvokeDeleteRequestException() {
+ when(mockedHttpServiceProvider.deleteHttpRequest(anyString(), eq(DeleteVnfResponse.class)))
+ .thenThrow(RestProcessingException.class);
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+ final Optional<DeleteVnfResponse> actual = objUnderTest.invokeDeleteRequest(DUMMY_GENERIC_VND_ID);
+ assertFalse(actual.isPresent());
+ }
+
+ @Test
+ public void testGetInstantiateOperationJobStatus_httpServiceProviderReturnsStatusOkWithBody_validResponse() {
+
+ when(mockedQueryJobResponseResponseEntity.getStatusCode()).thenReturn(HttpStatus.OK);
+ when(mockedQueryJobResponseResponseEntity.hasBody()).thenReturn(true);
+ when(mockedQueryJobResponseResponseEntity.getBody()).thenReturn(getQueryJobResponse());
+
+ when(mockedHttpServiceProvider.getHttpResponse(eq(TestConstants.JOB_STATUS_EXPECTED_URL),
+ eq(QueryJobResponse.class))).thenReturn(mockedQueryJobResponseResponseEntity);
+
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+
+ final Optional<QueryJobResponse> actual = objUnderTest.getInstantiateOperationJobStatus(DUMMY_JOB_ID);
+ assertTrue(actual.isPresent());
+ final QueryJobResponse actualQueryJobResponse = actual.get();
+ assertNotNull(actualQueryJobResponse);
+ }
+
+ @Test
+ public void testGetInstantiateOperationJobStatus_httpServiceProviderReturnsStatusOkWithOutBody_invalidResponse() {
+
+ when(mockedQueryJobResponseResponseEntity.getStatusCode()).thenReturn(HttpStatus.OK);
+ when(mockedQueryJobResponseResponseEntity.hasBody()).thenReturn(false);
+
+ when(mockedHttpServiceProvider.getHttpResponse(eq(TestConstants.JOB_STATUS_EXPECTED_URL),
+ eq(QueryJobResponse.class))).thenReturn(mockedQueryJobResponseResponseEntity);
+
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+
+ final Optional<QueryJobResponse> actual = objUnderTest.getInstantiateOperationJobStatus(DUMMY_JOB_ID);
+ assertFalse(actual.isPresent());
+ }
+
+ @Test
+ public void testGetInstantiateOperationJobStatus_httpServiceProviderReturnsStatusNotOkWithOutBody_invalidResponse() {
+
+ when(mockedQueryJobResponseResponseEntity.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
+
+ when(mockedHttpServiceProvider.getHttpResponse(eq(TestConstants.JOB_STATUS_EXPECTED_URL),
+ eq(QueryJobResponse.class))).thenReturn(mockedQueryJobResponseResponseEntity);
+
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+
+ final Optional<QueryJobResponse> actual = objUnderTest.getInstantiateOperationJobStatus(DUMMY_JOB_ID);
+ assertFalse(actual.isPresent());
+ }
+
+ @Test
+ public void testGetInstantiateOperationJobStatus_Exception() {
+
+ when(mockedHttpServiceProvider.getHttpResponse(eq(TestConstants.JOB_STATUS_EXPECTED_URL),
+ eq(QueryJobResponse.class))).thenThrow(RestProcessingException.class);
+
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+
+ final Optional<QueryJobResponse> actual = objUnderTest.getInstantiateOperationJobStatus(DUMMY_JOB_ID);
+ assertFalse(actual.isPresent());
+ }
+
+ private QueryJobResponse getQueryJobResponse() {
+ return new QueryJobResponse().id(DUMMY_JOB_ID).operationState(OperationStateEnum.COMPLETED);
+
+ }
+
+ private void assertWithJobId(final String jobId) {
+ when(mockedHttpServiceProvider.postHttpRequest(eq(CREATE_VNF_REQUEST), anyString(),
+ eq(CreateVnfResponse.class))).thenReturn(mockedResponseEntity);
+ when(mockedResponseEntity.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
+ when(mockedResponseEntity.hasBody()).thenReturn(true);
+ final CreateVnfResponse response = getCreateVnfResponse(jobId);
+ when(mockedResponseEntity.getBody()).thenReturn(response);
+
+
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+
+ final Optional<CreateVnfResponse> actual =
+ objUnderTest.invokeCreateInstantiationRequest(DUMMY_GENERIC_VND_ID, CREATE_VNF_REQUEST);
+ assertFalse(actual.isPresent());
+ }
- final VnfmAdapterServiceProvider objUnderTest =
- new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
+ private void assertWithStatuCode(final HttpStatus status) {
+ when(mockedHttpServiceProvider.postHttpRequest(eq(CREATE_VNF_REQUEST), anyString(),
+ eq(CreateVnfResponse.class))).thenReturn(mockedResponseEntity);
+ when(mockedResponseEntity.getStatusCode()).thenReturn(status);
+ when(mockedResponseEntity.hasBody()).thenReturn(false);
- final Optional<CreateVnfResponse> actual =
- objUnderTest.invokeCreateInstantiationRequest(DUMMY_GENERIC_VND_ID, CREATE_VNF_REQUEST);
- assertFalse(actual.isPresent());
- }
+ final VnfmAdapterServiceProvider objUnderTest =
+ new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider);
- private CreateVnfResponse getCreateVnfResponse(final String jobId) {
- return new CreateVnfResponse().jobId(jobId);
- }
+ final Optional<CreateVnfResponse> actual =
+ objUnderTest.invokeCreateInstantiationRequest(DUMMY_GENERIC_VND_ID, CREATE_VNF_REQUEST);
+ assertFalse(actual.isPresent());
+ }
- private DeleteVnfResponse getDeleteVnfResponse(final String jobId) {
- final DeleteVnfResponse response = new DeleteVnfResponse();
- response.setJobId(jobId);
- return response;
- }
+ private CreateVnfResponse getCreateVnfResponse(final String jobId) {
+ return new CreateVnfResponse().jobId(jobId);
+ }
- private VnfmAdapterUrlProvider getVnfmAdapterUrlProvider() {
- return new VnfmAdapterUrlProvider(getVnfmBasicHttpConfigProvider());
- }
+ private DeleteVnfResponse getDeleteVnfResponse(final String jobId) {
+ final DeleteVnfResponse response = new DeleteVnfResponse();
+ response.setJobId(jobId);
+ return response;
+ }
+
+ private VnfmAdapterUrlProvider getVnfmAdapterUrlProvider() {
+ return new VnfmAdapterUrlProvider(getVnfmBasicHttpConfigProvider());
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProviderTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProviderTest.java
index 133f24bbe1..4bffb845f4 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProviderTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProviderTest.java
@@ -26,7 +26,6 @@ import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.D
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.EXPECTED_URL;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.JOB_STATUS_EXPECTED_URL;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.getVnfmBasicHttpConfigProvider;
-
import org.junit.Test;
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImplTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImplTest.java
index d21942d08f..51e86c1fea 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImplTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImplTest.java
@@ -26,14 +26,12 @@ import static org.mockito.Mockito.when;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.FORWARD_SLASH;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.PRELOAD_VNFS_URL;
import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.DUMMY_GENERIC_VND_ID;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/VnfParameterTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/VnfParameterTest.java
index 46018b8f39..c7c61f9a1d 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/VnfParameterTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/VnfParameterTest.java
@@ -20,7 +20,6 @@
package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils;
import org.junit.Test;
-
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java
index 9cf1a1cdc9..e7a8b35db8 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java
@@ -24,11 +24,9 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.HashMap;
import java.util.Optional;
import java.util.UUID;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.appc.client.lcm.model.Action;
@@ -40,62 +38,66 @@ import org.onap.so.db.catalog.beans.ControllerSelectionReference;
import org.springframework.beans.factory.annotation.Autowired;
public class AppcRunTasksIT extends BaseIntegrationTest {
-
- @Autowired
- private AppcRunTasks appcRunTasks;
-
- private GenericVnf genericVnf;
- private RequestContext requestContext;
- private String msoRequestId;
- @Before
- public void before() {
- genericVnf = setGenericVnf();
- msoRequestId = UUID.randomUUID().toString();
- requestContext = setRequestContext();
- requestContext.setMsoRequestId(msoRequestId);
- gBBInput.setRequestContext(requestContext);
- }
-
- @Test
- public void preProcessActivityTest() throws Exception {
- appcRunTasks.preProcessActivity(execution);
- assertEquals(execution.getVariable("actionQuiesceTraffic"), Action.QuiesceTraffic);
- assertEquals(execution.getVariable("rollbackQuiesceTraffic"), false);
- }
-
- @Test
- public void runAppcCommandTest() throws Exception {
- Action action = Action.QuiesceTraffic;
- ControllerSelectionReference controllerSelectionReference = new ControllerSelectionReference();
- controllerSelectionReference.setControllerName("testName");
- controllerSelectionReference.setActionCategory(action.toString());
- controllerSelectionReference.setVnfType("testVnfType");
-
- doReturn(controllerSelectionReference).when(catalogDbClient).getControllerSelectionReferenceByVnfTypeAndActionCategory(genericVnf.getVnfType(), Action.QuiesceTraffic.toString());
-
- execution.setVariable("aicIdentity", "testAicIdentity");
-
- String vnfId = genericVnf.getVnfId();
- genericVnf.setIpv4OamAddress("testOamIpAddress");
- String payload = "{\"testName\":\"testValue\",}";
- RequestParameters requestParameters = new RequestParameters();
- requestParameters.setPayload(payload);
- gBBInput.getRequestContext().setRequestParameters(requestParameters);
-
- String controllerType = "testName";
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName1");
- payloadInfo.put("aicIdentity", "testAicIdentity");
- payloadInfo.put("vnfHostIpAddress", "testOamIpAddress");
- payloadInfo.put("vserverIdList", null);
- payloadInfo.put("vfModuleId", null);
- payloadInfo.put("identityUrl", null);
- payloadInfo.put("vmIdList", null);
-
- doNothing().when(appCClient).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType);
-
- appcRunTasks.runAppcCommand(execution, action);
- verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType);
- }
+ @Autowired
+ private AppcRunTasks appcRunTasks;
+
+ private GenericVnf genericVnf;
+ private RequestContext requestContext;
+ private String msoRequestId;
+
+ @Before
+ public void before() {
+ genericVnf = setGenericVnf();
+ msoRequestId = UUID.randomUUID().toString();
+ requestContext = setRequestContext();
+ requestContext.setMsoRequestId(msoRequestId);
+ gBBInput.setRequestContext(requestContext);
+ }
+
+ @Test
+ public void preProcessActivityTest() throws Exception {
+ appcRunTasks.preProcessActivity(execution);
+ assertEquals(execution.getVariable("actionQuiesceTraffic"), Action.QuiesceTraffic);
+ assertEquals(execution.getVariable("rollbackQuiesceTraffic"), false);
+ }
+
+ @Test
+ public void runAppcCommandTest() throws Exception {
+ Action action = Action.QuiesceTraffic;
+ ControllerSelectionReference controllerSelectionReference = new ControllerSelectionReference();
+ controllerSelectionReference.setControllerName("testName");
+ controllerSelectionReference.setActionCategory(action.toString());
+ controllerSelectionReference.setVnfType("testVnfType");
+
+ doReturn(controllerSelectionReference).when(catalogDbClient)
+ .getControllerSelectionReferenceByVnfTypeAndActionCategory(genericVnf.getVnfType(),
+ Action.QuiesceTraffic.toString());
+
+ execution.setVariable("aicIdentity", "testAicIdentity");
+
+ String vnfId = genericVnf.getVnfId();
+ genericVnf.setIpv4OamAddress("testOamIpAddress");
+ String payload = "{\"testName\":\"testValue\",}";
+ RequestParameters requestParameters = new RequestParameters();
+ requestParameters.setPayload(payload);
+ gBBInput.getRequestContext().setRequestParameters(requestParameters);
+
+ String controllerType = "testName";
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName1");
+ payloadInfo.put("aicIdentity", "testAicIdentity");
+ payloadInfo.put("vnfHostIpAddress", "testOamIpAddress");
+ payloadInfo.put("vserverIdList", null);
+ payloadInfo.put("vfModuleId", null);
+ payloadInfo.put("identityUrl", null);
+ payloadInfo.put("vmIdList", null);
+
+ doNothing().when(appCClient).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo,
+ controllerType);
+
+ appcRunTasks.runAppcCommand(execution, action);
+ verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo,
+ controllerType);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java
index a8518d9016..cf673c5eb5 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java
@@ -30,7 +30,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.junit.Test;
import org.mockito.InjectMocks;
import org.onap.appc.client.lcm.model.Action;
@@ -45,47 +44,45 @@ import org.onap.so.db.catalog.beans.ControllerSelectionReference;
public class AppcRunTasksTest extends BaseTaskTest {
- @InjectMocks
- private AppcRunTasks appcRunTasks = new AppcRunTasks();
-
- @Test
- public void mapRollbackVariablesTest() {
-
- BuildingBlockExecution mock = mock(BuildingBlockExecution.class);
-
- appcRunTasks.mapRollbackVariables(mock, Action.Lock, "1");
- verify(mock, times(0)).setVariable(any(String.class), any());
- appcRunTasks.mapRollbackVariables(mock, Action.Lock, "0");
- verify(mock, times(1)).setVariable("rollbackVnfLock", true);
- appcRunTasks.mapRollbackVariables(mock, Action.Unlock, "0");
- verify(mock, times(1)).setVariable("rollbackVnfLock", false);
- appcRunTasks.mapRollbackVariables(mock, Action.Start, "0");
- verify(mock, times(1)).setVariable("rollbackVnfStop", false);
- appcRunTasks.mapRollbackVariables(mock, Action.Stop, "0");
- verify(mock, times(1)).setVariable("rollbackVnfStop", true);
- appcRunTasks.mapRollbackVariables(mock, Action.QuiesceTraffic, "0");
- verify(mock, times(1)).setVariable("rollbackQuiesceTraffic", true);
- appcRunTasks.mapRollbackVariables(mock, Action.ResumeTraffic, "0");
- verify(mock, times(1)).setVariable("rollbackQuiesceTraffic", false);
- }
+ @InjectMocks
+ private AppcRunTasks appcRunTasks = new AppcRunTasks();
+
+ @Test
+ public void mapRollbackVariablesTest() {
+
+ BuildingBlockExecution mock = mock(BuildingBlockExecution.class);
+
+ appcRunTasks.mapRollbackVariables(mock, Action.Lock, "1");
+ verify(mock, times(0)).setVariable(any(String.class), any());
+ appcRunTasks.mapRollbackVariables(mock, Action.Lock, "0");
+ verify(mock, times(1)).setVariable("rollbackVnfLock", true);
+ appcRunTasks.mapRollbackVariables(mock, Action.Unlock, "0");
+ verify(mock, times(1)).setVariable("rollbackVnfLock", false);
+ appcRunTasks.mapRollbackVariables(mock, Action.Start, "0");
+ verify(mock, times(1)).setVariable("rollbackVnfStop", false);
+ appcRunTasks.mapRollbackVariables(mock, Action.Stop, "0");
+ verify(mock, times(1)).setVariable("rollbackVnfStop", true);
+ appcRunTasks.mapRollbackVariables(mock, Action.QuiesceTraffic, "0");
+ verify(mock, times(1)).setVariable("rollbackQuiesceTraffic", true);
+ appcRunTasks.mapRollbackVariables(mock, Action.ResumeTraffic, "0");
+ verify(mock, times(1)).setVariable("rollbackQuiesceTraffic", false);
+ }
@Test
public void runAppcCommandVnfNull() throws BBObjectNotFoundException {
execution.getLookupMap().put(ResourceKey.GENERIC_VNF_ID, "NULL-TEST");
fillRequiredAppcExecutionFields();
- when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID)))
- .thenReturn(null);
- when(catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory(
- isNull(), eq(Action.Lock.toString()))).
- thenThrow(new IllegalArgumentException("name or values is null"));
+ when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(null);
+ when(catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory(isNull(),
+ eq(Action.Lock.toString()))).thenThrow(new IllegalArgumentException("name or values is null"));
appcRunTasks.runAppcCommand(execution, Action.Lock);
// if vnf = null -> vnfType = null ->
- // IllegalArgumentException will be thrown in catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory
- verify(exceptionUtil, times(1)).
- buildAndThrowWorkflowException(
- any(BuildingBlockExecution.class), eq(1002), eq("name or values is null"));
+ // IllegalArgumentException will be thrown in
+ // catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1002),
+ eq("name or values is null"));
}
@Test
@@ -93,13 +90,12 @@ public class AppcRunTasksTest extends BaseTaskTest {
execution.getLookupMap().put(ResourceKey.GENERIC_VNF_ID, "EXCEPTION-TEST");
fillRequiredAppcExecutionFields();
when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID)))
- .thenThrow(new BBObjectNotFoundException());
+ .thenThrow(new BBObjectNotFoundException());
appcRunTasks.runAppcCommand(execution, Action.Lock);
- verify(exceptionUtil, times(1)).
- buildAndThrowWorkflowException(
- any(BuildingBlockExecution.class), eq(7000), eq("No valid VNF exists"));
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000),
+ eq("No valid VNF exists"));
}
@Test
@@ -107,12 +103,10 @@ public class AppcRunTasksTest extends BaseTaskTest {
execution.getLookupMap().put(ResourceKey.GENERIC_VNF_ID, "SUCCESS-TEST");
fillRequiredAppcExecutionFields();
GenericVnf genericVnf = getTestGenericVnf();
- when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID)))
- .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
mockReferenceResponse();
execution.getLookupMap().put(ResourceKey.VF_MODULE_ID, "VF-MODULE-ID-TEST");
- when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.VF_MODULE_ID)))
- .thenReturn(null);
+ when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.VF_MODULE_ID))).thenReturn(null);
when(appCClient.getErrorCode()).thenReturn("0");
appcRunTasks.runAppcCommand(execution, Action.Lock);
@@ -125,14 +119,12 @@ public class AppcRunTasksTest extends BaseTaskTest {
execution.getLookupMap().put(ResourceKey.GENERIC_VNF_ID, "SUCCESS-TEST");
fillRequiredAppcExecutionFields();
GenericVnf genericVnf = getTestGenericVnf();
- when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID)))
- .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
mockReferenceResponse();
execution.getLookupMap().put(ResourceKey.VF_MODULE_ID, "VF-MODULE-ID-TEST");
VfModule vfModule = new VfModule();
vfModule.setVfModuleId("VF-MODULE-ID");
- when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.VF_MODULE_ID)))
- .thenReturn(vfModule);
+ when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
when(appCClient.getErrorCode()).thenReturn("0");
appcRunTasks.runAppcCommand(execution, Action.Lock);
@@ -143,8 +135,8 @@ public class AppcRunTasksTest extends BaseTaskTest {
private void mockReferenceResponse() {
ControllerSelectionReference reference = new ControllerSelectionReference();
reference.setControllerName("TEST-CONTROLLER-NAME");
- when(catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory(
- eq("TEST-VNF-TYPE"), eq(Action.Lock.toString()))).thenReturn(reference);
+ when(catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory(eq("TEST-VNF-TYPE"),
+ eq(Action.Lock.toString()))).thenReturn(reference);
}
private void fillRequiredAppcExecutionFields() {
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/audit/AuditTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/audit/AuditTasksTest.java
index 3542d7fdb3..3bf24291ea 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/audit/AuditTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/audit/AuditTasksTest.java
@@ -23,7 +23,6 @@ import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
-
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -38,37 +37,39 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule;
import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
import org.onap.so.client.exception.BBObjectNotFoundException;
-public class AuditTasksTest extends BaseTaskTest{
-
- @InjectMocks
- private AuditTasks auditTasks = new AuditTasks();
- private ServiceInstance serviceInstance;
- private GenericVnf genericVnf;
- private VfModule vfModule;
+public class AuditTasksTest extends BaseTaskTest {
+
+ @InjectMocks
+ private AuditTasks auditTasks = new AuditTasks();
+ private ServiceInstance serviceInstance;
+ private GenericVnf genericVnf;
+ private VfModule vfModule;
+
+
+ @Rule
+ public final ExpectedException exception = ExpectedException.none();
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ serviceInstance = setServiceInstance();
+ genericVnf = setGenericVnf();
+ vfModule = setVfModule();
+ setCloudRegion();
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ }
-
- @Rule
- public final ExpectedException exception = ExpectedException.none();
-
- @Before
- public void before() throws BBObjectNotFoundException {
- serviceInstance = setServiceInstance();
- genericVnf = setGenericVnf();
- vfModule = setVfModule();
- setCloudRegion();
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- }
-
- @Test
- public void setupAuditVariableTest() throws Exception {
- AuditInventory expectedAuditInventory = new AuditInventory();
- expectedAuditInventory.setCloudOwner("testCloudOwner");
- expectedAuditInventory.setCloudRegion("testLcpCloudRegionId");
- expectedAuditInventory.setHeatStackName("testVfModuleName1");
- expectedAuditInventory.setTenantId("testTenantId");
- auditTasks.setupAuditVariable(execution);
- assertThat((AuditInventory)execution.getVariable("auditInventory"), sameBeanAs(expectedAuditInventory));
- }
+ @Test
+ public void setupAuditVariableTest() throws Exception {
+ AuditInventory expectedAuditInventory = new AuditInventory();
+ expectedAuditInventory.setCloudOwner("testCloudOwner");
+ expectedAuditInventory.setCloudRegion("testLcpCloudRegionId");
+ expectedAuditInventory.setHeatStackName("testVfModuleName1");
+ expectedAuditInventory.setTenantId("testTenantId");
+ auditTasks.setupAuditVariable(execution);
+ assertThat((AuditInventory) execution.getVariable("auditInventory"), sameBeanAs(expectedAuditInventory));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ActivateVfModuleTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ActivateVfModuleTest.java
index d1d167e561..0a880ad0e5 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ActivateVfModuleTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ActivateVfModuleTest.java
@@ -29,16 +29,18 @@ import org.mockito.InjectMocks;
import org.onap.so.bpmn.BaseTaskTest;
public class ActivateVfModuleTest extends BaseTaskTest {
-
- @InjectMocks
- private ActivateVfModule activateVfModule = new ActivateVfModule();
-
- @Test
- public void setWaitBeforeDurationTest() throws Exception {
- when(env.getProperty(ActivateVfModule.VF_MODULE_TIMER_DURATION_PATH, ActivateVfModule.DEFAULT_TIMER_DURATION)).thenReturn("PT300S");
- activateVfModule.setTimerDuration(execution);
- verify(env, times(1)).getProperty(ActivateVfModule.VF_MODULE_TIMER_DURATION_PATH, ActivateVfModule.DEFAULT_TIMER_DURATION);
- assertEquals("PT300S", (String) execution.getVariable("vfModuleActivateTimerDuration"));
- }
+
+ @InjectMocks
+ private ActivateVfModule activateVfModule = new ActivateVfModule();
+
+ @Test
+ public void setWaitBeforeDurationTest() throws Exception {
+ when(env.getProperty(ActivateVfModule.VF_MODULE_TIMER_DURATION_PATH, ActivateVfModule.DEFAULT_TIMER_DURATION))
+ .thenReturn("PT300S");
+ activateVfModule.setTimerDuration(execution);
+ verify(env, times(1)).getProperty(ActivateVfModule.VF_MODULE_TIMER_DURATION_PATH,
+ ActivateVfModule.DEFAULT_TIMER_DURATION);
+ assertEquals("PT300S", (String) execution.getVariable("vfModuleActivateTimerDuration"));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtilsTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtilsTest.java
index e7f841fa47..8ca0e79c6e 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtilsTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtilsTest.java
@@ -20,7 +20,6 @@
package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
import static org.junit.Assert.assertEquals;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -28,34 +27,34 @@ import org.onap.so.bpmn.BaseTaskTest;
import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
public class AssignNetworkBBUtilsTest extends BaseTaskTest {
-
- @InjectMocks
- private AssignNetworkBBUtils nonMockAssignNetworkBBUtils = new AssignNetworkBBUtils();
-
- private CloudRegion cloudRegion;
-
- @Before
- public void before() {
- cloudRegion = setCloudRegion();
- }
-
- @Test
- public void getCloudRegionTest25() throws Exception {
- cloudRegion.setCloudRegionVersion("2.5");
-
- nonMockAssignNetworkBBUtils.getCloudRegion(execution);
-
- assertEquals(cloudRegion.getLcpCloudRegionId(), execution.getVariable("cloudRegionPo"));
- assertEquals("AAIAIC25", execution.getVariable("cloudRegionSdnc"));
- }
-
- @Test
- public void getCloudRegionTest30() throws Exception {
- cloudRegion.setCloudRegionVersion("3.0");
-
- nonMockAssignNetworkBBUtils.getCloudRegion(execution);
-
- assertEquals(cloudRegion.getLcpCloudRegionId(), execution.getVariable("cloudRegionPo"));
- assertEquals(cloudRegion.getLcpCloudRegionId(), execution.getVariable("cloudRegionSdnc"));
- }
+
+ @InjectMocks
+ private AssignNetworkBBUtils nonMockAssignNetworkBBUtils = new AssignNetworkBBUtils();
+
+ private CloudRegion cloudRegion;
+
+ @Before
+ public void before() {
+ cloudRegion = setCloudRegion();
+ }
+
+ @Test
+ public void getCloudRegionTest25() throws Exception {
+ cloudRegion.setCloudRegionVersion("2.5");
+
+ nonMockAssignNetworkBBUtils.getCloudRegion(execution);
+
+ assertEquals(cloudRegion.getLcpCloudRegionId(), execution.getVariable("cloudRegionPo"));
+ assertEquals("AAIAIC25", execution.getVariable("cloudRegionSdnc"));
+ }
+
+ @Test
+ public void getCloudRegionTest30() throws Exception {
+ cloudRegion.setCloudRegionVersion("3.0");
+
+ nonMockAssignNetworkBBUtils.getCloudRegion(execution);
+
+ assertEquals(cloudRegion.getLcpCloudRegionId(), execution.getVariable("cloudRegionPo"));
+ assertEquals(cloudRegion.getLcpCloudRegionId(), execution.getVariable("cloudRegionSdnc"));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkTest.java
index 19981bc45a..d7a5dbd8f0 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkTest.java
@@ -24,7 +24,6 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -38,39 +37,40 @@ import org.onap.so.client.exception.BBObjectNotFoundException;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
public class AssignNetworkTest extends BaseTaskTest {
-
- @InjectMocks
- private AssignNetwork assignNetwork = new AssignNetwork();
-
- private L3Network network;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- network = setL3Network();
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
- }
-
- @Test
- public void networkNotFoundTest() throws Exception {
- //network status to PRECREATED - when it was NOT found by name
- try {
- network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- } catch(BBObjectNotFoundException e) {
- }
-
- network.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- boolean networkFound = assignNetwork.networkFoundByName(execution);
- assertEquals(false, networkFound);
- }
- @Test
- public void networkFoundTest() throws Exception {
- try {
- network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
- } catch(BBObjectNotFoundException e) {
- }
- boolean networkFound = assignNetwork.networkFoundByName(execution);
- assertEquals(true, networkFound);
- }
+ @InjectMocks
+ private AssignNetwork assignNetwork = new AssignNetwork();
+
+ private L3Network network;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ network = setL3Network();
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
+ }
+
+ @Test
+ public void networkNotFoundTest() throws Exception {
+ // network status to PRECREATED - when it was NOT found by name
+ try {
+ network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ } catch (BBObjectNotFoundException e) {
+ }
+
+ network.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ boolean networkFound = assignNetwork.networkFoundByName(execution);
+ assertEquals(false, networkFound);
+ }
+
+ @Test
+ public void networkFoundTest() throws Exception {
+ try {
+ network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
+ } catch (BBObjectNotFoundException e) {
+ }
+ boolean networkFound = assignNetwork.networkFoundByName(execution);
+ assertEquals(true, networkFound);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnfTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnfTest.java
index 834990db5a..06ad66e855 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnfTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnfTest.java
@@ -28,9 +28,7 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.util.List;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -48,94 +46,103 @@ import org.onap.so.client.aai.entities.AAIEdgeLabel;
import org.onap.so.client.exception.BBObjectNotFoundException;
public class AssignVnfTest extends BaseTaskTest {
- @InjectMocks
- private AssignVnf assignVnf = new AssignVnf();
-
- @Mock
- private AAIObjectInstanceNameGenerator aaiObjectInstanceNameGenerator = new AAIObjectInstanceNameGenerator();
-
- private InstanceGroup instanceGroup1;
- private InstanceGroup instanceGroup2;
- private InstanceGroup instanceGroup3;
- private InstanceGroup instanceGroup4;
- private GenericVnf genericVnf;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- ModelInfoInstanceGroup modelVnfc = new ModelInfoInstanceGroup();
- modelVnfc.setType("VNFC");
- modelVnfc.setFunction("function");
-
- ModelInfoInstanceGroup modelNetworkInstanceGroup = new ModelInfoInstanceGroup();
- modelNetworkInstanceGroup.setType("L3-NETWORK");
- modelNetworkInstanceGroup.setFunction("function");
-
- instanceGroup1 = new InstanceGroup();
- instanceGroup1.setId("test-001");
- instanceGroup1.setModelInfoInstanceGroup(modelVnfc);
-
- instanceGroup2 = new InstanceGroup();
- instanceGroup2.setId("test-002");
- instanceGroup2.setModelInfoInstanceGroup(modelVnfc);
-
- instanceGroup3 = new InstanceGroup();
- instanceGroup3.setId("test-003");
- instanceGroup3.setModelInfoInstanceGroup(modelNetworkInstanceGroup);
-
- instanceGroup4 = new InstanceGroup();
- instanceGroup4.setId("test-004");
- instanceGroup4.setModelInfoInstanceGroup(modelNetworkInstanceGroup);
-
- genericVnf = setGenericVnf();
- genericVnf.setVnfName("vnfName");
-
-
- doNothing().when(aaiInstanceGroupResources).createInstanceGroup(isA(InstanceGroup.class));
- doNothing().when(aaiInstanceGroupResources).connectInstanceGroupToVnf(isA(InstanceGroup.class), isA(GenericVnf.class));
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- }
-
- @Test
- public void createInstanceGroupsSunnyDayTest() throws Exception {
-
- List<InstanceGroup> instanceGroupList = genericVnf.getInstanceGroups();
- instanceGroupList.add(instanceGroup1);
- instanceGroupList.add(instanceGroup2);
- instanceGroupList.add(instanceGroup3);
- instanceGroupList.add(instanceGroup4);
-
-
- assignVnf.createInstanceGroups(execution);
- verify(aaiInstanceGroupResources, times(1)).createInstanceGroup(instanceGroup1);
- verify(aaiInstanceGroupResources, times(1)).createInstanceGroup(instanceGroup2);
- verify(aaiInstanceGroupResources, times(1)).connectInstanceGroupToVnf(instanceGroup1, genericVnf, AAIEdgeLabel.BELONGS_TO);
- verify(aaiInstanceGroupResources, times(1)).connectInstanceGroupToVnf(instanceGroup2, genericVnf, AAIEdgeLabel.BELONGS_TO);
- verify(aaiInstanceGroupResources, times(1)).connectInstanceGroupToVnf(instanceGroup3, genericVnf, AAIEdgeLabel.USES);
- verify(aaiInstanceGroupResources, times(1)).connectInstanceGroupToVnf(instanceGroup4, genericVnf, AAIEdgeLabel.USES);
- }
-
- @Test
- public void createVnfcInstanceGroupNoneTest() throws Exception {
- assignVnf.createInstanceGroups(execution);
-
-
- verify(aaiInstanceGroupResources, times(0)).createInstanceGroup(any(InstanceGroup.class));
- verify(aaiInstanceGroupResources, times(0)).connectInstanceGroupToVnf(any(InstanceGroup.class), any(GenericVnf.class));
- }
-
- @Test
- public void createVnfcInstanceGroupExceptionTest() throws Exception {
- List<InstanceGroup> instanceGroupList = genericVnf.getInstanceGroups();
- instanceGroupList.add(instanceGroup1);
- instanceGroupList.add(instanceGroup2);
- instanceGroupList.add(instanceGroup3);
- instanceGroupList.add(instanceGroup4);
- doThrow(RuntimeException.class).when(aaiInstanceGroupResources).createInstanceGroup(isA(InstanceGroup.class));
- expectedException.expect(BpmnError.class);
-
- genericVnf.setVnfId("test-999");
- assignVnf.createInstanceGroups(execution);
- }
+ @InjectMocks
+ private AssignVnf assignVnf = new AssignVnf();
+
+ @Mock
+ private AAIObjectInstanceNameGenerator aaiObjectInstanceNameGenerator = new AAIObjectInstanceNameGenerator();
+
+ private InstanceGroup instanceGroup1;
+ private InstanceGroup instanceGroup2;
+ private InstanceGroup instanceGroup3;
+ private InstanceGroup instanceGroup4;
+ private GenericVnf genericVnf;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ ModelInfoInstanceGroup modelVnfc = new ModelInfoInstanceGroup();
+ modelVnfc.setType("VNFC");
+ modelVnfc.setFunction("function");
+
+ ModelInfoInstanceGroup modelNetworkInstanceGroup = new ModelInfoInstanceGroup();
+ modelNetworkInstanceGroup.setType("L3-NETWORK");
+ modelNetworkInstanceGroup.setFunction("function");
+
+ instanceGroup1 = new InstanceGroup();
+ instanceGroup1.setId("test-001");
+ instanceGroup1.setModelInfoInstanceGroup(modelVnfc);
+
+ instanceGroup2 = new InstanceGroup();
+ instanceGroup2.setId("test-002");
+ instanceGroup2.setModelInfoInstanceGroup(modelVnfc);
+
+ instanceGroup3 = new InstanceGroup();
+ instanceGroup3.setId("test-003");
+ instanceGroup3.setModelInfoInstanceGroup(modelNetworkInstanceGroup);
+
+ instanceGroup4 = new InstanceGroup();
+ instanceGroup4.setId("test-004");
+ instanceGroup4.setModelInfoInstanceGroup(modelNetworkInstanceGroup);
+
+ genericVnf = setGenericVnf();
+ genericVnf.setVnfName("vnfName");
+
+
+ doNothing().when(aaiInstanceGroupResources).createInstanceGroup(isA(InstanceGroup.class));
+ doNothing().when(aaiInstanceGroupResources).connectInstanceGroupToVnf(isA(InstanceGroup.class),
+ isA(GenericVnf.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ }
+
+ @Test
+ public void createInstanceGroupsSunnyDayTest() throws Exception {
+
+ List<InstanceGroup> instanceGroupList = genericVnf.getInstanceGroups();
+ instanceGroupList.add(instanceGroup1);
+ instanceGroupList.add(instanceGroup2);
+ instanceGroupList.add(instanceGroup3);
+ instanceGroupList.add(instanceGroup4);
+
+
+ assignVnf.createInstanceGroups(execution);
+ verify(aaiInstanceGroupResources, times(1)).createInstanceGroup(instanceGroup1);
+ verify(aaiInstanceGroupResources, times(1)).createInstanceGroup(instanceGroup2);
+ verify(aaiInstanceGroupResources, times(1)).connectInstanceGroupToVnf(instanceGroup1, genericVnf,
+ AAIEdgeLabel.BELONGS_TO);
+ verify(aaiInstanceGroupResources, times(1)).connectInstanceGroupToVnf(instanceGroup2, genericVnf,
+ AAIEdgeLabel.BELONGS_TO);
+ verify(aaiInstanceGroupResources, times(1)).connectInstanceGroupToVnf(instanceGroup3, genericVnf,
+ AAIEdgeLabel.USES);
+ verify(aaiInstanceGroupResources, times(1)).connectInstanceGroupToVnf(instanceGroup4, genericVnf,
+ AAIEdgeLabel.USES);
+ }
+
+ @Test
+ public void createVnfcInstanceGroupNoneTest() throws Exception {
+ assignVnf.createInstanceGroups(execution);
+
+
+ verify(aaiInstanceGroupResources, times(0)).createInstanceGroup(any(InstanceGroup.class));
+ verify(aaiInstanceGroupResources, times(0)).connectInstanceGroupToVnf(any(InstanceGroup.class),
+ any(GenericVnf.class));
+ }
+
+ @Test
+ public void createVnfcInstanceGroupExceptionTest() throws Exception {
+ List<InstanceGroup> instanceGroupList = genericVnf.getInstanceGroups();
+ instanceGroupList.add(instanceGroup1);
+ instanceGroupList.add(instanceGroup2);
+ instanceGroupList.add(instanceGroup3);
+ instanceGroupList.add(instanceGroup4);
+ doThrow(RuntimeException.class).when(aaiInstanceGroupResources).createInstanceGroup(isA(InstanceGroup.class));
+ expectedException.expect(BpmnError.class);
+
+ genericVnf.setVnfId("test-999");
+ assignVnf.createInstanceGroups(execution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CloudSiteCatalogUtilsTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CloudSiteCatalogUtilsTest.java
index 125c97109c..99516e69e3 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CloudSiteCatalogUtilsTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CloudSiteCatalogUtilsTest.java
@@ -25,64 +25,63 @@ import java.util.Optional;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.onap.so.bpmn.BaseTaskTest;
-
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.db.catalog.beans.CloudSite;
public class CloudSiteCatalogUtilsTest extends BaseTaskTest {
-
- @InjectMocks
- private CloudSiteCatalogUtils cloudSiteCatalogUtils = new CloudSiteCatalogUtils();
-
- @Test
- public void testGetCloudSiteGetVersion30Test() throws Exception {
- CloudSite cloudSite = new CloudSite();
- String testCloudSiteId = "testCloudSiteId";
- cloudSite.setClli(testCloudSiteId);
- doReturn(cloudSite).when(catalogDbClient).getCloudSite(testCloudSiteId);
- Optional<CloudSite> actualCloudSite = cloudSiteCatalogUtils.getCloudSite(testCloudSiteId);
- assertEquals(actualCloudSite.get().getClli(), testCloudSiteId);
- }
-
- @Test
- public void testGetCloudSiteGetVersion25Test() throws Exception {
- CloudSite cloudSite = new CloudSite();
- String testCloudSiteId = "testCloudSiteId";
- cloudSite.setClli(testCloudSiteId);
- doReturn(null).when(catalogDbClient).getCloudSite(testCloudSiteId);
- doReturn(cloudSite).when(catalogDbClient).getCloudSiteByClliAndAicVersion(testCloudSiteId, "2.5");
- Optional<CloudSite> actualCloudSite = cloudSiteCatalogUtils.getCloudSite(testCloudSiteId);
- assertEquals(actualCloudSite.get().getClli(), testCloudSiteId);
- }
-
- @Test
- public void testGetIdentityUrlFromCloudSiteSuccessTest() throws Exception {
- CloudSite cloudSite = new CloudSite();
- String testCloudSiteId = "testCloudSiteId";
- String testIdentityUrl = "testIdentityUrl";
- delegateExecution.setVariable("lcpCloudRegionId", testCloudSiteId);
- cloudSite.setClli(testCloudSiteId);
- CloudIdentity cloudIdentity = new CloudIdentity();
- cloudIdentity.setIdentityUrl(testIdentityUrl);
- cloudSite.setIdentityService(cloudIdentity);
- doReturn(cloudSite).when(catalogDbClient).getCloudSite(testCloudSiteId);
- cloudSiteCatalogUtils.getIdentityUrlFromCloudSite(delegateExecution);
- String actualIdentityUrl = (String) delegateExecution.getVariable("identityUrl");
- assertEquals(testIdentityUrl, actualIdentityUrl);
- }
-
- @Test
- public void testGetIdentityUrlFromCloudSiteNoCloudIdProvidedTest() throws Exception {
- CloudSite cloudSite = new CloudSite();
- String testCloudSiteId = "testCloudSiteId";
- String testIdentityUrl = "testIdentityUrl";
- cloudSite.setClli(testCloudSiteId);
- CloudIdentity cloudIdentity = new CloudIdentity();
- cloudIdentity.setIdentityUrl(testIdentityUrl);
- cloudSite.setIdentityService(cloudIdentity);
- doReturn(cloudSite).when(catalogDbClient).getCloudSite(testCloudSiteId);
- cloudSiteCatalogUtils.getIdentityUrlFromCloudSite(delegateExecution);
- String actualIdentityUrl = (String) delegateExecution.getVariable("identityUrl");
- assertEquals(null, actualIdentityUrl);
- }
+
+ @InjectMocks
+ private CloudSiteCatalogUtils cloudSiteCatalogUtils = new CloudSiteCatalogUtils();
+
+ @Test
+ public void testGetCloudSiteGetVersion30Test() throws Exception {
+ CloudSite cloudSite = new CloudSite();
+ String testCloudSiteId = "testCloudSiteId";
+ cloudSite.setClli(testCloudSiteId);
+ doReturn(cloudSite).when(catalogDbClient).getCloudSite(testCloudSiteId);
+ Optional<CloudSite> actualCloudSite = cloudSiteCatalogUtils.getCloudSite(testCloudSiteId);
+ assertEquals(actualCloudSite.get().getClli(), testCloudSiteId);
+ }
+
+ @Test
+ public void testGetCloudSiteGetVersion25Test() throws Exception {
+ CloudSite cloudSite = new CloudSite();
+ String testCloudSiteId = "testCloudSiteId";
+ cloudSite.setClli(testCloudSiteId);
+ doReturn(null).when(catalogDbClient).getCloudSite(testCloudSiteId);
+ doReturn(cloudSite).when(catalogDbClient).getCloudSiteByClliAndAicVersion(testCloudSiteId, "2.5");
+ Optional<CloudSite> actualCloudSite = cloudSiteCatalogUtils.getCloudSite(testCloudSiteId);
+ assertEquals(actualCloudSite.get().getClli(), testCloudSiteId);
+ }
+
+ @Test
+ public void testGetIdentityUrlFromCloudSiteSuccessTest() throws Exception {
+ CloudSite cloudSite = new CloudSite();
+ String testCloudSiteId = "testCloudSiteId";
+ String testIdentityUrl = "testIdentityUrl";
+ delegateExecution.setVariable("lcpCloudRegionId", testCloudSiteId);
+ cloudSite.setClli(testCloudSiteId);
+ CloudIdentity cloudIdentity = new CloudIdentity();
+ cloudIdentity.setIdentityUrl(testIdentityUrl);
+ cloudSite.setIdentityService(cloudIdentity);
+ doReturn(cloudSite).when(catalogDbClient).getCloudSite(testCloudSiteId);
+ cloudSiteCatalogUtils.getIdentityUrlFromCloudSite(delegateExecution);
+ String actualIdentityUrl = (String) delegateExecution.getVariable("identityUrl");
+ assertEquals(testIdentityUrl, actualIdentityUrl);
+ }
+
+ @Test
+ public void testGetIdentityUrlFromCloudSiteNoCloudIdProvidedTest() throws Exception {
+ CloudSite cloudSite = new CloudSite();
+ String testCloudSiteId = "testCloudSiteId";
+ String testIdentityUrl = "testIdentityUrl";
+ cloudSite.setClli(testCloudSiteId);
+ CloudIdentity cloudIdentity = new CloudIdentity();
+ cloudIdentity.setIdentityUrl(testIdentityUrl);
+ cloudSite.setIdentityService(cloudIdentity);
+ doReturn(cloudSite).when(catalogDbClient).getCloudSite(testCloudSiteId);
+ cloudSiteCatalogUtils.getIdentityUrlFromCloudSite(delegateExecution);
+ String actualIdentityUrl = (String) delegateExecution.getVariable("identityUrl");
+ assertEquals(null, actualIdentityUrl);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnfTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnfTest.java
index 07983ccd50..7d96a18305 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnfTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnfTest.java
@@ -25,9 +25,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
-
import java.util.UUID;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnfTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnfTest.java
index e5aa702dad..6f76c83c6f 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnfTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnfTest.java
@@ -1,23 +1,18 @@
/*
-* ============LICENSE_START=======================================================
-* ONAP : SO
-* ================================================================================
-* Copyright 2019 TechMahindra
-*=================================================================================
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-* ============LICENSE_END=========================================================
-*/
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright 2019 TechMahindra
+ * ================================================================================= Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
@@ -26,9 +21,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
-
import java.util.UUID;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -46,52 +39,55 @@ import org.onap.so.client.exception.BBObjectNotFoundException;
public class ConfigDeployVnfTest extends BaseTaskTest {
- @InjectMocks
- private ConfigDeployVnf configDeployVnf = new ConfigDeployVnf();
- @Mock
- AAIUpdateTasks aAIUpdateTasks = new AAIUpdateTasks();
-
-
- private GenericVnf genericVnf;
- private ServiceInstance serviceInstance;
- private RequestContext requestContext;
- private String msoRequestId;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- genericVnf = setGenericVnf();
- serviceInstance = setServiceInstance();
- msoRequestId = UUID.randomUUID().toString();
- requestContext = setRequestContext();
- requestContext.setMsoRequestId(msoRequestId);
- gBBInput.setRequestContext(requestContext);
-
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- }
-
-
-
- @Test
- public void preProcessAbstractCDSProcessingTest() throws Exception {
-
- configDeployVnf.preProcessAbstractCDSProcessing(execution);
-
- assertTrue(true);
- }
-
- @Test
- public void updateAAIConfigureTaskTest() throws Exception {
-
- configDeployVnf.updateAAIConfigure(execution);
- assertTrue(true);
- }
-
- @Test
- public void updateAAIConfiguredTaskTest() throws Exception {
- configDeployVnf.updateAAIConfigured(execution);
- assertTrue(true);
- }
+ @InjectMocks
+ private ConfigDeployVnf configDeployVnf = new ConfigDeployVnf();
+ @Mock
+ AAIUpdateTasks aAIUpdateTasks = new AAIUpdateTasks();
+
+
+ private GenericVnf genericVnf;
+ private ServiceInstance serviceInstance;
+ private RequestContext requestContext;
+ private String msoRequestId;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ genericVnf = setGenericVnf();
+ serviceInstance = setServiceInstance();
+ msoRequestId = UUID.randomUUID().toString();
+ requestContext = setRequestContext();
+ requestContext.setMsoRequestId(msoRequestId);
+ gBBInput.setRequestContext(requestContext);
+
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ }
+
+
+
+ @Test
+ public void preProcessAbstractCDSProcessingTest() throws Exception {
+
+ configDeployVnf.preProcessAbstractCDSProcessing(execution);
+
+ assertTrue(true);
+ }
+
+ @Test
+ public void updateAAIConfigureTaskTest() throws Exception {
+
+ configDeployVnf.updateAAIConfigure(execution);
+ assertTrue(true);
+ }
+
+ @Test
+ public void updateAAIConfiguredTaskTest() throws Exception {
+ configDeployVnf.updateAAIConfigured(execution);
+ assertTrue(true);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOutTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOutTest.java
index 6390268a0c..4d43bbbce7 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOutTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOutTest.java
@@ -28,7 +28,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
@@ -37,7 +36,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -54,137 +52,153 @@ import org.onap.so.client.exception.BBObjectNotFoundException;
import org.onap.so.db.catalog.beans.ControllerSelectionReference;
public class ConfigurationScaleOutTest extends BaseTaskTest {
-
- @InjectMocks
- private ConfigurationScaleOut configurationScaleOut = new ConfigurationScaleOut();
-
- private GenericVnf genericVnf;
- private VfModule vfModule;
- private RequestContext requestContext;
- private String msoRequestId;
- private List<Map<String, String>> configurationParameters = new ArrayList<>();
- private Map<String, String> configParamsMap = new HashMap<>();
-
-
-
- @Before
- public void before() throws BBObjectNotFoundException {
- genericVnf = setGenericVnf();
- vfModule = setVfModule();
- msoRequestId = UUID.randomUUID().toString();
- requestContext = setRequestContext();
- requestContext.setMsoRequestId(msoRequestId);
- configParamsMap.put("availability-zone", "$.vnf-topology.vnf-resource-assignments.availability-zones.availability-zone[0]");
- configParamsMap.put("vnf-id", "$.vnf-topology.vnf-topology-identifier-structure.vnf-id");
- configurationParameters.add(configParamsMap);
- requestContext.setConfigurationParameters(configurationParameters);
- gBBInput.setRequestContext(requestContext);
-
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
-
- }
-
- @Test
- public void setParamsForConfigurationScaleOutTest() throws Exception {
- ControllerSelectionReference controllerSelectionReference = new ControllerSelectionReference();
- controllerSelectionReference.setControllerName("testName");
- controllerSelectionReference.setActionCategory("testAction");
- controllerSelectionReference.setVnfType("testVnfType");
- String sdncResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNCClientGetResponse.json")));
- String expectedPayload = "{\"request-parameters\":{\"vnf-host-ip-address\":\"10.222.22.2\","
- + "\"vf-module-id\":\"testVfModuleId1\"},\"configuration-parameters\""
- + ":{\"vnf-id\":\"66dac89b-2a5b-4cb9-b22e-a7e4488fb3db\",\"availability-zone\":\"AZ-MN02\"}}";
- execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), sdncResponse);
-
- doReturn(controllerSelectionReference).when(catalogDbClient).getControllerSelectionReferenceByVnfTypeAndActionCategory(genericVnf.getVnfType(), Action.ConfigScaleOut.toString());
-
- configurationScaleOut.setParamsForConfigurationScaleOut(execution);
-
- assertEquals(genericVnf.getVnfId(), execution.getVariable("vnfId"));
- assertEquals(genericVnf.getVnfName(), execution.getVariable("vnfName"));
- assertEquals("ConfigScaleOut", execution.getVariable("action"));
- assertEquals(requestContext.getMsoRequestId(), execution.getVariable("msoRequestId"));
- assertEquals(controllerSelectionReference.getControllerName(), execution.getVariable("controllerType"));
- assertEquals(vfModule.getVfModuleId(), execution.getVariable("vfModuleId"));
- assertEquals(expectedPayload, execution.getVariable("payload"));
- }
- @Test
- public void callAppcClientTest() throws Exception {
- Action action = Action.ConfigScaleOut;
- String vnfId = genericVnf.getVnfId();
- String controllerType = "testType";
- String payload = "{\"request-parameters\":{\"vnf-host-ip-address\":\"10.222.22.2\","
- + "\"vf-module-id\":\"testVfModuleId1\"},\"configuration-parameters\""
- + ":{\"vnf-id\":\"66dac89b-2a5b-4cb9-b22e-a7e4488fb3db\",\"availability-zone\":\"AZ-MN02\"}}";
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName");
- payloadInfo.put("vfModuleId", "testVfModuleId");
-
- execution.setVariable("action", Action.ConfigScaleOut.toString());
- execution.setVariable("msoRequestId", msoRequestId);
- execution.setVariable("controllerType", controllerType);
- execution.setVariable("vnfId", "testVnfId1");
- execution.setVariable("vnfName", "testVnfName");
- execution.setVariable("vfModuleId", "testVfModuleId");
- execution.setVariable("payload", payload);
-
- doNothing().when(appCClient).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType);
-
- configurationScaleOut.callAppcClient(execution);
- verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType);
- }
- @Test
- public void setParamsForConfigurationScaleOutBadPathTest() throws Exception {
- ControllerSelectionReference controllerSelectionReference = new ControllerSelectionReference();
- controllerSelectionReference.setControllerName("testName");
- controllerSelectionReference.setActionCategory("testAction");
- controllerSelectionReference.setVnfType("testVnfType");
- String sdncResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNCClientResponseIncorrectPath.json")));
- String expectedPayload = "{\"request-parameters\":{\"vnf-host-ip-address\":\"10.222.22.2\","
- + "\"vf-module-id\":\"testVfModuleId1\"},\"configuration-parameters\""
- + ":{\"vnf-id\":\"66dac89b-2a5b-4cb9-b22e-a7e4488fb3db\",\"availability-zone\":null}}";
- execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), sdncResponse);
-
- doReturn(controllerSelectionReference).when(catalogDbClient).getControllerSelectionReferenceByVnfTypeAndActionCategory(genericVnf.getVnfType(), Action.ConfigScaleOut.toString());
-
- configurationScaleOut.setParamsForConfigurationScaleOut(execution);
-
- assertEquals(genericVnf.getVnfId(), execution.getVariable("vnfId"));
- assertEquals(genericVnf.getVnfName(), execution.getVariable("vnfName"));
- assertEquals("ConfigScaleOut", execution.getVariable("action"));
- assertEquals(requestContext.getMsoRequestId(), execution.getVariable("msoRequestId"));
- assertEquals(controllerSelectionReference.getControllerName(), execution.getVariable("controllerType"));
- assertEquals(vfModule.getVfModuleId(), execution.getVariable("vfModuleId"));
- assertEquals(expectedPayload, execution.getVariable("payload"));
- }
-
- @Test
- public void callAppcClientExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- Action action = Action.ConfigScaleOut;
- String vnfId = genericVnf.getVnfId();
- String controllerType = "testType";
- String payload = "{\"request-parameters\":{\"vnf-host-ip-address\":\"10.222.22.2\","
- + "\"vf-module-id\":\"testVfModuleId1\"},\"configuration-parameters\""
- + ":{\"vnf-id\":\"66dac89b-2a5b-4cb9-b22e-a7e4488fb3db\",\"availability-zone\":\"AZ-MN02\"}}";
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName");
- payloadInfo.put("vfModuleId", "testVfModuleId");
-
- execution.setVariable("action", Action.ConfigScaleOut.toString());
- execution.setVariable("msoRequestId", msoRequestId);
- execution.setVariable("controllerType", controllerType);
- execution.setVariable("vnfId", "testVnfId1");
- execution.setVariable("vnfName", "testVnfName");
- execution.setVariable("vfModuleId", "testVfModuleId");
- execution.setVariable("payload", payload);
-
-
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1002), eq("APPC Client Failed"));
- doThrow(new RuntimeException("APPC Client Failed")).when(appCClient).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType);
- configurationScaleOut.callAppcClient(execution);
- verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType);
- }
+
+ @InjectMocks
+ private ConfigurationScaleOut configurationScaleOut = new ConfigurationScaleOut();
+
+ private GenericVnf genericVnf;
+ private VfModule vfModule;
+ private RequestContext requestContext;
+ private String msoRequestId;
+ private List<Map<String, String>> configurationParameters = new ArrayList<>();
+ private Map<String, String> configParamsMap = new HashMap<>();
+
+
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ genericVnf = setGenericVnf();
+ vfModule = setVfModule();
+ msoRequestId = UUID.randomUUID().toString();
+ requestContext = setRequestContext();
+ requestContext.setMsoRequestId(msoRequestId);
+ configParamsMap.put("availability-zone",
+ "$.vnf-topology.vnf-resource-assignments.availability-zones.availability-zone[0]");
+ configParamsMap.put("vnf-id", "$.vnf-topology.vnf-topology-identifier-structure.vnf-id");
+ configurationParameters.add(configParamsMap);
+ requestContext.setConfigurationParameters(configurationParameters);
+ gBBInput.setRequestContext(requestContext);
+
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+
+ }
+
+ @Test
+ public void setParamsForConfigurationScaleOutTest() throws Exception {
+ ControllerSelectionReference controllerSelectionReference = new ControllerSelectionReference();
+ controllerSelectionReference.setControllerName("testName");
+ controllerSelectionReference.setActionCategory("testAction");
+ controllerSelectionReference.setVnfType("testVnfType");
+ String sdncResponse =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNCClientGetResponse.json")));
+ String expectedPayload = "{\"request-parameters\":{\"vnf-host-ip-address\":\"10.222.22.2\","
+ + "\"vf-module-id\":\"testVfModuleId1\"},\"configuration-parameters\""
+ + ":{\"vnf-id\":\"66dac89b-2a5b-4cb9-b22e-a7e4488fb3db\",\"availability-zone\":\"AZ-MN02\"}}";
+ execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), sdncResponse);
+
+ doReturn(controllerSelectionReference).when(catalogDbClient)
+ .getControllerSelectionReferenceByVnfTypeAndActionCategory(genericVnf.getVnfType(),
+ Action.ConfigScaleOut.toString());
+
+ configurationScaleOut.setParamsForConfigurationScaleOut(execution);
+
+ assertEquals(genericVnf.getVnfId(), execution.getVariable("vnfId"));
+ assertEquals(genericVnf.getVnfName(), execution.getVariable("vnfName"));
+ assertEquals("ConfigScaleOut", execution.getVariable("action"));
+ assertEquals(requestContext.getMsoRequestId(), execution.getVariable("msoRequestId"));
+ assertEquals(controllerSelectionReference.getControllerName(), execution.getVariable("controllerType"));
+ assertEquals(vfModule.getVfModuleId(), execution.getVariable("vfModuleId"));
+ assertEquals(expectedPayload, execution.getVariable("payload"));
+ }
+
+ @Test
+ public void callAppcClientTest() throws Exception {
+ Action action = Action.ConfigScaleOut;
+ String vnfId = genericVnf.getVnfId();
+ String controllerType = "testType";
+ String payload = "{\"request-parameters\":{\"vnf-host-ip-address\":\"10.222.22.2\","
+ + "\"vf-module-id\":\"testVfModuleId1\"},\"configuration-parameters\""
+ + ":{\"vnf-id\":\"66dac89b-2a5b-4cb9-b22e-a7e4488fb3db\",\"availability-zone\":\"AZ-MN02\"}}";
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName");
+ payloadInfo.put("vfModuleId", "testVfModuleId");
+
+ execution.setVariable("action", Action.ConfigScaleOut.toString());
+ execution.setVariable("msoRequestId", msoRequestId);
+ execution.setVariable("controllerType", controllerType);
+ execution.setVariable("vnfId", "testVnfId1");
+ execution.setVariable("vnfName", "testVnfName");
+ execution.setVariable("vfModuleId", "testVfModuleId");
+ execution.setVariable("payload", payload);
+
+ doNothing().when(appCClient).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo,
+ controllerType);
+
+ configurationScaleOut.callAppcClient(execution);
+ verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo,
+ controllerType);
+ }
+
+ @Test
+ public void setParamsForConfigurationScaleOutBadPathTest() throws Exception {
+ ControllerSelectionReference controllerSelectionReference = new ControllerSelectionReference();
+ controllerSelectionReference.setControllerName("testName");
+ controllerSelectionReference.setActionCategory("testAction");
+ controllerSelectionReference.setVnfType("testVnfType");
+ String sdncResponse = new String(
+ Files.readAllBytes(Paths.get("src/test/resources/__files/SDNCClientResponseIncorrectPath.json")));
+ String expectedPayload = "{\"request-parameters\":{\"vnf-host-ip-address\":\"10.222.22.2\","
+ + "\"vf-module-id\":\"testVfModuleId1\"},\"configuration-parameters\""
+ + ":{\"vnf-id\":\"66dac89b-2a5b-4cb9-b22e-a7e4488fb3db\",\"availability-zone\":null}}";
+ execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), sdncResponse);
+
+ doReturn(controllerSelectionReference).when(catalogDbClient)
+ .getControllerSelectionReferenceByVnfTypeAndActionCategory(genericVnf.getVnfType(),
+ Action.ConfigScaleOut.toString());
+
+ configurationScaleOut.setParamsForConfigurationScaleOut(execution);
+
+ assertEquals(genericVnf.getVnfId(), execution.getVariable("vnfId"));
+ assertEquals(genericVnf.getVnfName(), execution.getVariable("vnfName"));
+ assertEquals("ConfigScaleOut", execution.getVariable("action"));
+ assertEquals(requestContext.getMsoRequestId(), execution.getVariable("msoRequestId"));
+ assertEquals(controllerSelectionReference.getControllerName(), execution.getVariable("controllerType"));
+ assertEquals(vfModule.getVfModuleId(), execution.getVariable("vfModuleId"));
+ assertEquals(expectedPayload, execution.getVariable("payload"));
+ }
+
+ @Test
+ public void callAppcClientExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ Action action = Action.ConfigScaleOut;
+ String vnfId = genericVnf.getVnfId();
+ String controllerType = "testType";
+ String payload = "{\"request-parameters\":{\"vnf-host-ip-address\":\"10.222.22.2\","
+ + "\"vf-module-id\":\"testVfModuleId1\"},\"configuration-parameters\""
+ + ":{\"vnf-id\":\"66dac89b-2a5b-4cb9-b22e-a7e4488fb3db\",\"availability-zone\":\"AZ-MN02\"}}";
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName");
+ payloadInfo.put("vfModuleId", "testVfModuleId");
+
+ execution.setVariable("action", Action.ConfigScaleOut.toString());
+ execution.setVariable("msoRequestId", msoRequestId);
+ execution.setVariable("controllerType", controllerType);
+ execution.setVariable("vnfId", "testVnfId1");
+ execution.setVariable("vnfName", "testVnfName");
+ execution.setVariable("vfModuleId", "testVfModuleId");
+ execution.setVariable("payload", payload);
+
+
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1002), eq("APPC Client Failed"));
+ doThrow(new RuntimeException("APPC Client Failed")).when(appCClient).runAppCCommand(action, msoRequestId, vnfId,
+ Optional.of(payload), payloadInfo, controllerType);
+ configurationScaleOut.callAppcClient(execution);
+ verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo,
+ controllerType);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollectionTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollectionTest.java
index 423029c59b..f0889f62c0 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollectionTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollectionTest.java
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
+
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@@ -26,10 +27,8 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.util.ArrayList;
import java.util.List;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -45,73 +44,84 @@ import org.onap.so.bpmn.servicedecomposition.generalobjects.OrchestrationContext
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoInstanceGroup;
import org.onap.so.client.exception.BBObjectNotFoundException;
-public class CreateNetworkCollectionTest extends BaseTaskTest{
- @InjectMocks
- private CreateNetworkCollection createNetworkCollection = new CreateNetworkCollection();
-
- private L3Network network;
- private ServiceInstance serviceInstance;
- private OrchestrationContext orchestrationContext;
- private CloudRegion cloudRegion;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- serviceInstance = setServiceInstance();
- network = setL3Network();
- cloudRegion = setCloudRegion();
-
- List<L3Network> l3NetworkList = new ArrayList<L3Network>();
- l3NetworkList.add(network);
- ModelInfoInstanceGroup modelInfoInstanceGroup = new ModelInfoInstanceGroup();
- modelInfoInstanceGroup.setFunction("function");
- serviceInstance.getCollection().getInstanceGroup().setModelInfoInstanceGroup(modelInfoInstanceGroup);
-
- orchestrationContext = setOrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
-
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- }
-
- @Test
- public void buildCreateNetworkRequestTest() throws Exception {
- createNetworkCollection.buildNetworkCollectionName(execution);
-
- assertEquals(serviceInstance.getServiceInstanceName() + "_" + serviceInstance.getCollection().getInstanceGroup().getModelInfoInstanceGroup().getFunction(), execution.getVariable("networkCollectionName"));
- }
-
- @Test(expected = BpmnError.class)
- public void buildCreateNetworkRequestInstanceGroupModelInfoFunctionNullExceptionTest() throws Exception {
- ModelInfoInstanceGroup modelInfoInstanceGroup = new ModelInfoInstanceGroup();
- serviceInstance.getCollection().getInstanceGroup().setModelInfoInstanceGroup(modelInfoInstanceGroup);
- createNetworkCollection.buildNetworkCollectionName(execution);
- }
-
- @Test(expected = BpmnError.class)
- public void buildCreateNetworkRequestInstanceGroupModelInfoNullTest() throws Exception {
- serviceInstance.getCollection().getInstanceGroup().setModelInfoInstanceGroup(null);
- createNetworkCollection.buildNetworkCollectionName(execution);
- }
-
- @Test
- public void connectCollectionToInstanceGroupTest() throws Exception {
- doNothing().when(aaiNetworkResources).connectNetworkCollectionInstanceGroupToNetworkCollection(serviceInstance.getCollection().getInstanceGroup(), serviceInstance.getCollection());
- createNetworkCollection.connectCollectionToInstanceGroup(execution);
- verify(aaiNetworkResources, times(1)).connectNetworkCollectionInstanceGroupToNetworkCollection(serviceInstance.getCollection().getInstanceGroup(), serviceInstance.getCollection());
- }
-
- @Test
- public void connectCollectionToServiceInstanceTest() throws Exception {
- doNothing().when(aaiNetworkResources).connectNetworkCollectionToServiceInstance(serviceInstance.getCollection(), serviceInstance);
- createNetworkCollection.connectCollectionToServiceInstance(execution);
- verify(aaiNetworkResources, times(1)).connectNetworkCollectionToServiceInstance(serviceInstance.getCollection(), serviceInstance);
- }
-
- @Test
- public void connectInstanceGroupToCloudRegionTest() throws Exception {
- doNothing().when(aaiNetworkResources).connectInstanceGroupToCloudRegion(serviceInstance.getCollection().getInstanceGroup(), cloudRegion);
- createNetworkCollection.connectInstanceGroupToCloudRegion(execution);
- verify(aaiNetworkResources, times(1)).connectInstanceGroupToCloudRegion(serviceInstance.getCollection().getInstanceGroup(), cloudRegion);
- }
+public class CreateNetworkCollectionTest extends BaseTaskTest {
+ @InjectMocks
+ private CreateNetworkCollection createNetworkCollection = new CreateNetworkCollection();
+
+ private L3Network network;
+ private ServiceInstance serviceInstance;
+ private OrchestrationContext orchestrationContext;
+ private CloudRegion cloudRegion;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ serviceInstance = setServiceInstance();
+ network = setL3Network();
+ cloudRegion = setCloudRegion();
+
+ List<L3Network> l3NetworkList = new ArrayList<L3Network>();
+ l3NetworkList.add(network);
+ ModelInfoInstanceGroup modelInfoInstanceGroup = new ModelInfoInstanceGroup();
+ modelInfoInstanceGroup.setFunction("function");
+ serviceInstance.getCollection().getInstanceGroup().setModelInfoInstanceGroup(modelInfoInstanceGroup);
+
+ orchestrationContext = setOrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ }
+
+ @Test
+ public void buildCreateNetworkRequestTest() throws Exception {
+ createNetworkCollection.buildNetworkCollectionName(execution);
+
+ assertEquals(
+ serviceInstance.getServiceInstanceName() + "_"
+ + serviceInstance.getCollection().getInstanceGroup().getModelInfoInstanceGroup().getFunction(),
+ execution.getVariable("networkCollectionName"));
+ }
+
+ @Test(expected = BpmnError.class)
+ public void buildCreateNetworkRequestInstanceGroupModelInfoFunctionNullExceptionTest() throws Exception {
+ ModelInfoInstanceGroup modelInfoInstanceGroup = new ModelInfoInstanceGroup();
+ serviceInstance.getCollection().getInstanceGroup().setModelInfoInstanceGroup(modelInfoInstanceGroup);
+ createNetworkCollection.buildNetworkCollectionName(execution);
+ }
+
+ @Test(expected = BpmnError.class)
+ public void buildCreateNetworkRequestInstanceGroupModelInfoNullTest() throws Exception {
+ serviceInstance.getCollection().getInstanceGroup().setModelInfoInstanceGroup(null);
+ createNetworkCollection.buildNetworkCollectionName(execution);
+ }
+
+ @Test
+ public void connectCollectionToInstanceGroupTest() throws Exception {
+ doNothing().when(aaiNetworkResources).connectNetworkCollectionInstanceGroupToNetworkCollection(
+ serviceInstance.getCollection().getInstanceGroup(), serviceInstance.getCollection());
+ createNetworkCollection.connectCollectionToInstanceGroup(execution);
+ verify(aaiNetworkResources, times(1)).connectNetworkCollectionInstanceGroupToNetworkCollection(
+ serviceInstance.getCollection().getInstanceGroup(), serviceInstance.getCollection());
+ }
+
+ @Test
+ public void connectCollectionToServiceInstanceTest() throws Exception {
+ doNothing().when(aaiNetworkResources).connectNetworkCollectionToServiceInstance(serviceInstance.getCollection(),
+ serviceInstance);
+ createNetworkCollection.connectCollectionToServiceInstance(execution);
+ verify(aaiNetworkResources, times(1)).connectNetworkCollectionToServiceInstance(serviceInstance.getCollection(),
+ serviceInstance);
+ }
+
+ @Test
+ public void connectInstanceGroupToCloudRegionTest() throws Exception {
+ doNothing().when(aaiNetworkResources)
+ .connectInstanceGroupToCloudRegion(serviceInstance.getCollection().getInstanceGroup(), cloudRegion);
+ createNetworkCollection.connectInstanceGroupToCloudRegion(execution);
+ verify(aaiNetworkResources, times(1))
+ .connectInstanceGroupToCloudRegion(serviceInstance.getCollection().getInstanceGroup(), cloudRegion);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkTest.java
index de1aa63f55..1e0ab20d97 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkTest.java
@@ -26,9 +26,7 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.util.Map;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
@@ -45,47 +43,51 @@ import org.onap.so.client.exception.BBObjectNotFoundException;
import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer;
import org.springframework.beans.factory.annotation.Autowired;
-public class CreateNetworkTest extends BaseTaskTest{
- @InjectMocks
- private CreateNetwork createNetwork = new CreateNetwork();
-
- private L3Network network;
- private ServiceInstance serviceInstance;
- private CloudRegion cloudRegion;
- private OrchestrationContext orchestrationContext;
- private Map<String, String> userInput;
- private RequestContext requestContext;
- private String cloudRegionPo = "testCloudRegionPo";
- private Customer customer;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- customer = setCustomer();
- serviceInstance = setServiceInstance();
- network = setL3Network();
- cloudRegion = setCloudRegion();
- orchestrationContext = setOrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
- requestContext = setRequestContext();
- userInput = setUserInput();
+public class CreateNetworkTest extends BaseTaskTest {
+ @InjectMocks
+ private CreateNetwork createNetwork = new CreateNetwork();
+
+ private L3Network network;
+ private ServiceInstance serviceInstance;
+ private CloudRegion cloudRegion;
+ private OrchestrationContext orchestrationContext;
+ private Map<String, String> userInput;
+ private RequestContext requestContext;
+ private String cloudRegionPo = "testCloudRegionPo";
+ private Customer customer;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ customer = setCustomer();
+ serviceInstance = setServiceInstance();
+ network = setL3Network();
+ cloudRegion = setCloudRegion();
+ orchestrationContext = setOrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+ requestContext = setRequestContext();
+ userInput = setUserInput();
+
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ }
+
+ @Test
+ public void buildCreateNetworkRequestTest() throws Exception {
+ execution.setVariable("cloudRegionPo", cloudRegionPo);
+
+ CreateNetworkRequest expectedCreateNetworkRequest = new CreateNetworkRequest();
+
+ doReturn(expectedCreateNetworkRequest).when(networkAdapterObjectMapper).createNetworkRequestMapper(
+ requestContext, cloudRegion, orchestrationContext, serviceInstance, network, userInput, cloudRegionPo,
+ customer);
+
+ createNetwork.buildCreateNetworkRequest(execution);
+
+ verify(networkAdapterObjectMapper, times(1)).createNetworkRequestMapper(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, network, userInput, cloudRegionPo, customer);
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- }
-
- @Test
- public void buildCreateNetworkRequestTest() throws Exception {
- execution.setVariable("cloudRegionPo", cloudRegionPo);
-
- CreateNetworkRequest expectedCreateNetworkRequest = new CreateNetworkRequest();
-
- doReturn(expectedCreateNetworkRequest).when(networkAdapterObjectMapper).createNetworkRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, network, userInput, cloudRegionPo, customer);
-
- createNetwork.buildCreateNetworkRequest(execution);
-
- verify(networkAdapterObjectMapper, times(1)).createNetworkRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, network, userInput, cloudRegionPo, customer);
-
- assertThat(expectedCreateNetworkRequest, sameBeanAs(execution.getVariable("createNetworkRequest")));
- }
+ assertThat(expectedCreateNetworkRequest, sameBeanAs(execution.getVariable("createNetworkRequest")));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheckTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheckTest.java
index 2386da743b..f23bbd8c91 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheckTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheckTest.java
@@ -28,11 +28,9 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.util.HashMap;
import java.util.Optional;
import java.util.UUID;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Ignore;
@@ -49,128 +47,140 @@ import org.onap.so.client.exception.BBObjectNotFoundException;
import org.onap.so.db.catalog.beans.ControllerSelectionReference;
public class GenericVnfHealthCheckTest extends BaseTaskTest {
-
- @InjectMocks
- private GenericVnfHealthCheck genericVnfHealthCheck = new GenericVnfHealthCheck();
-
- private GenericVnf genericVnf;
- private RequestContext requestContext;
- private String msoRequestId;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- genericVnf = setGenericVnf();
- msoRequestId = UUID.randomUUID().toString();
- requestContext = setRequestContext();
- requestContext.setMsoRequestId(msoRequestId);
- gBBInput.setRequestContext(requestContext);
-
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- }
-
- @Test
- public void setParamsForGenericVnfHealthCheckTest() throws Exception {
- ControllerSelectionReference controllerSelectionReference = new ControllerSelectionReference();
- controllerSelectionReference.setControllerName("testName");
- controllerSelectionReference.setActionCategory("testAction");
- controllerSelectionReference.setVnfType("testVnfType");
-
- doReturn(controllerSelectionReference).when(catalogDbClient).getControllerSelectionReferenceByVnfTypeAndActionCategory(genericVnf.getVnfType(), Action.HealthCheck.toString());
-
- genericVnfHealthCheck.setParamsForGenericVnfHealthCheck(execution);
-
- assertEquals(genericVnf.getVnfId(), execution.getVariable("vnfId"));
- assertEquals(genericVnf.getVnfName(), execution.getVariable("vnfName"));
- assertEquals(genericVnf.getIpv4OamAddress(), execution.getVariable("oamIpAddress"));
- assertEquals("HealthCheck", execution.getVariable("action"));
- assertEquals(requestContext.getMsoRequestId(), execution.getVariable("msoRequestId"));
- assertEquals(controllerSelectionReference.getControllerName(), execution.getVariable("controllerType"));
- }
- @Test
- public void callAppcClientTest() throws Exception {
- Action action = Action.HealthCheck;
- String vnfId = genericVnf.getVnfId();
- String payload = "{\"testName\":\"testValue\",}";
- String controllerType = "testType";
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName");
- payloadInfo.put("vfModuleId", "testVfModuleId");
- payloadInfo.put("oamIpAddress", "testOamIpAddress");
- payloadInfo.put("vnfHostIpAddress", "testOamIpAddress");
- execution.setVariable("action", Action.HealthCheck.toString());
- execution.setVariable("msoRequestId", msoRequestId);
- execution.setVariable("controllerType", controllerType);
- execution.setVariable("vnfId", "testVnfId1");
- execution.setVariable("vnfName", "testVnfName");
- execution.setVariable("vfModuleId", "testVfModuleId");
- execution.setVariable("oamIpAddress", "testOamIpAddress");
- execution.setVariable("vnfHostIpAddress", "testOamIpAddress");
- execution.setVariable("payload", payload);
-
- doNothing().when(appCClient).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType);
-
- genericVnfHealthCheck.callAppcClient(execution);
- verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType);
- }
-
- @Test
- public void callAppcClientExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- Action action = Action.HealthCheck;
- String vnfId = genericVnf.getVnfId();
- String payload = "{\"testName\":\"testValue\",}";
- String controllerType = "testType";
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName");
- payloadInfo.put("vfModuleId", "testVfModuleId");
- payloadInfo.put("oamIpAddress", "testOamIpAddress");
- payloadInfo.put("vnfHostIpAddress", "testOamIpAddress");
- execution.setVariable("action", Action.HealthCheck.toString());
- execution.setVariable("msoRequestId", msoRequestId);
- execution.setVariable("controllerType", controllerType);
- execution.setVariable("vnfId", "testVnfId1");
- execution.setVariable("vnfName", "testVnfName");
- execution.setVariable("vfModuleId", "testVfModuleId");
- execution.setVariable("oamIpAddress", "testOamIpAddress");
- execution.setVariable("vnfHostIpAddress", "testOamIpAddress");
- execution.setVariable("payload", payload);
-
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1002), eq("APPC Client Failed"));
- doThrow(new RuntimeException("APPC Client Failed")).when(appCClient).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType);
-
-
- genericVnfHealthCheck.callAppcClient(execution);
- verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType);
- }
-
- @Test
- @Ignore //The runAppCCommand method in not capable of throwing this exception
- public void callAppcClientTimeOutExceptionTest() {
- expectedException.expect(java.util.concurrent.TimeoutException.class);
- Action action = Action.HealthCheck;
- String vnfId = genericVnf.getVnfId();
- String payload = "{\"testName\":\"testValue\",}";
- String controllerType = "testType";
- HashMap<String, String> payloadInfo = new HashMap<String, String>();
- payloadInfo.put("vnfName", "testVnfName");
- payloadInfo.put("vfModuleId", "testVfModuleId");
- payloadInfo.put("oamIpAddress", "testOamIpAddress");
- payloadInfo.put("vnfHostIpAddress", "testOamIpAddress");
- execution.setVariable("action", Action.HealthCheck.toString());
- execution.setVariable("msoRequestId", msoRequestId);
- execution.setVariable("controllerType", controllerType);
- execution.setVariable("vnfId", "testVnfId1");
- execution.setVariable("vnfName", "testVnfName");
- execution.setVariable("vfModuleId", "testVfModuleId");
- execution.setVariable("oamIpAddress", "testOamIpAddress");
- execution.setVariable("vnfHostIpAddress", "testOamIpAddress");
- execution.setVariable("payload", payload);
-
- doThrow(java.util.concurrent.TimeoutException.class).when(appCClient).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType);
-
-
- genericVnfHealthCheck.callAppcClient(execution);
- verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType);
- }
+
+ @InjectMocks
+ private GenericVnfHealthCheck genericVnfHealthCheck = new GenericVnfHealthCheck();
+
+ private GenericVnf genericVnf;
+ private RequestContext requestContext;
+ private String msoRequestId;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ genericVnf = setGenericVnf();
+ msoRequestId = UUID.randomUUID().toString();
+ requestContext = setRequestContext();
+ requestContext.setMsoRequestId(msoRequestId);
+ gBBInput.setRequestContext(requestContext);
+
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ }
+
+ @Test
+ public void setParamsForGenericVnfHealthCheckTest() throws Exception {
+ ControllerSelectionReference controllerSelectionReference = new ControllerSelectionReference();
+ controllerSelectionReference.setControllerName("testName");
+ controllerSelectionReference.setActionCategory("testAction");
+ controllerSelectionReference.setVnfType("testVnfType");
+
+ doReturn(controllerSelectionReference).when(catalogDbClient)
+ .getControllerSelectionReferenceByVnfTypeAndActionCategory(genericVnf.getVnfType(),
+ Action.HealthCheck.toString());
+
+ genericVnfHealthCheck.setParamsForGenericVnfHealthCheck(execution);
+
+ assertEquals(genericVnf.getVnfId(), execution.getVariable("vnfId"));
+ assertEquals(genericVnf.getVnfName(), execution.getVariable("vnfName"));
+ assertEquals(genericVnf.getIpv4OamAddress(), execution.getVariable("oamIpAddress"));
+ assertEquals("HealthCheck", execution.getVariable("action"));
+ assertEquals(requestContext.getMsoRequestId(), execution.getVariable("msoRequestId"));
+ assertEquals(controllerSelectionReference.getControllerName(), execution.getVariable("controllerType"));
+ }
+
+ @Test
+ public void callAppcClientTest() throws Exception {
+ Action action = Action.HealthCheck;
+ String vnfId = genericVnf.getVnfId();
+ String payload = "{\"testName\":\"testValue\",}";
+ String controllerType = "testType";
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName");
+ payloadInfo.put("vfModuleId", "testVfModuleId");
+ payloadInfo.put("oamIpAddress", "testOamIpAddress");
+ payloadInfo.put("vnfHostIpAddress", "testOamIpAddress");
+ execution.setVariable("action", Action.HealthCheck.toString());
+ execution.setVariable("msoRequestId", msoRequestId);
+ execution.setVariable("controllerType", controllerType);
+ execution.setVariable("vnfId", "testVnfId1");
+ execution.setVariable("vnfName", "testVnfName");
+ execution.setVariable("vfModuleId", "testVfModuleId");
+ execution.setVariable("oamIpAddress", "testOamIpAddress");
+ execution.setVariable("vnfHostIpAddress", "testOamIpAddress");
+ execution.setVariable("payload", payload);
+
+ doNothing().when(appCClient).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo,
+ controllerType);
+
+ genericVnfHealthCheck.callAppcClient(execution);
+ verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo,
+ controllerType);
+ }
+
+ @Test
+ public void callAppcClientExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ Action action = Action.HealthCheck;
+ String vnfId = genericVnf.getVnfId();
+ String payload = "{\"testName\":\"testValue\",}";
+ String controllerType = "testType";
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName");
+ payloadInfo.put("vfModuleId", "testVfModuleId");
+ payloadInfo.put("oamIpAddress", "testOamIpAddress");
+ payloadInfo.put("vnfHostIpAddress", "testOamIpAddress");
+ execution.setVariable("action", Action.HealthCheck.toString());
+ execution.setVariable("msoRequestId", msoRequestId);
+ execution.setVariable("controllerType", controllerType);
+ execution.setVariable("vnfId", "testVnfId1");
+ execution.setVariable("vnfName", "testVnfName");
+ execution.setVariable("vfModuleId", "testVfModuleId");
+ execution.setVariable("oamIpAddress", "testOamIpAddress");
+ execution.setVariable("vnfHostIpAddress", "testOamIpAddress");
+ execution.setVariable("payload", payload);
+
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1002), eq("APPC Client Failed"));
+ doThrow(new RuntimeException("APPC Client Failed")).when(appCClient).runAppCCommand(action, msoRequestId, vnfId,
+ Optional.of(payload), payloadInfo, controllerType);
+
+
+ genericVnfHealthCheck.callAppcClient(execution);
+ verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo,
+ controllerType);
+ }
+
+ @Test
+ @Ignore // The runAppCCommand method in not capable of throwing this exception
+ public void callAppcClientTimeOutExceptionTest() {
+ expectedException.expect(java.util.concurrent.TimeoutException.class);
+ Action action = Action.HealthCheck;
+ String vnfId = genericVnf.getVnfId();
+ String payload = "{\"testName\":\"testValue\",}";
+ String controllerType = "testType";
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", "testVnfName");
+ payloadInfo.put("vfModuleId", "testVfModuleId");
+ payloadInfo.put("oamIpAddress", "testOamIpAddress");
+ payloadInfo.put("vnfHostIpAddress", "testOamIpAddress");
+ execution.setVariable("action", Action.HealthCheck.toString());
+ execution.setVariable("msoRequestId", msoRequestId);
+ execution.setVariable("controllerType", controllerType);
+ execution.setVariable("vnfId", "testVnfId1");
+ execution.setVariable("vnfName", "testVnfName");
+ execution.setVariable("vfModuleId", "testVfModuleId");
+ execution.setVariable("oamIpAddress", "testOamIpAddress");
+ execution.setVariable("vnfHostIpAddress", "testOamIpAddress");
+ execution.setVariable("payload", payload);
+
+ doThrow(java.util.concurrent.TimeoutException.class).when(appCClient).runAppCCommand(action, msoRequestId,
+ vnfId, Optional.of(payload), payloadInfo, controllerType);
+
+
+ genericVnfHealthCheck.callAppcClient(execution);
+ verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo,
+ controllerType);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/NetworkBBUtilsTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/NetworkBBUtilsTest.java
index bf9be282d4..5eafb982e6 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/NetworkBBUtilsTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/NetworkBBUtilsTest.java
@@ -23,11 +23,9 @@ package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -38,82 +36,84 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
import org.onap.so.client.aai.entities.AAIResultWrapper;
import org.springframework.beans.factory.annotation.Autowired;
-public class NetworkBBUtilsTest extends BaseTaskTest{
- @InjectMocks
- private NetworkBBUtils networkBBUtils = new NetworkBBUtils();
-
- private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/Network/";
-
- private CloudRegion cloudRegion;
-
- @Before
- public void before() {
- cloudRegion = setCloudRegion();
- }
-
- @Test
- public void isRelationshipRelatedToExistsTrueTest() throws Exception {
- final String aaiResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "unassignNetworkBB_queryAAIResponse_.json")));
- AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiResponse);
- Optional<L3Network> l3network = aaiResultWrapper.asBean(L3Network.class);
-
- boolean isVfModule = networkBBUtils.isRelationshipRelatedToExists(l3network, "vf-module");
- assertTrue(isVfModule);
-
- }
-
- @Test
- public void isRelationshipRelatedToExistsFalseTest() throws Exception {
- final String aaiResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAAIResponse.json")));
- AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiResponse);
- Optional<L3Network> l3network = aaiResultWrapper.asBean(L3Network.class);
-
- boolean isVfModule = networkBBUtils.isRelationshipRelatedToExists(l3network, "vf-module");
- assertFalse(isVfModule);
-
- }
-
- @Test
- public void getCloudRegionSDNC25Test() throws Exception {
- cloudRegion.setCloudRegionVersion("2.5");
-
- NetworkBBUtils spyAssign = Mockito.spy(NetworkBBUtils.class);
- String cloudRegionId = spyAssign.getCloudRegion(execution, SourceSystem.SDNC);
- Mockito.verify(spyAssign).getCloudRegion(execution, SourceSystem.SDNC);
-
- assertEquals("AAIAIC25", cloudRegionId);
- }
-
- @Test
- public void getCloudRegionSDNC30Test() throws Exception {
- cloudRegion.setCloudRegionVersion("3.0");
-
- NetworkBBUtils spyAssign = Mockito.spy(NetworkBBUtils.class);
- String cloudRegionId = spyAssign.getCloudRegion(execution, SourceSystem.SDNC);
- Mockito.verify(spyAssign).getCloudRegion(execution, SourceSystem.SDNC);
-
- assertEquals(cloudRegion.getLcpCloudRegionId(), cloudRegionId);
- }
-
- @Test
- public void getCloudRegionPO25Test() throws Exception {
- cloudRegion.setCloudRegionVersion("2.5");
-
- NetworkBBUtils spyAssign = Mockito.spy(NetworkBBUtils.class);
- String cloudRegionId = spyAssign.getCloudRegion(execution, SourceSystem.PO);
- Mockito.verify(spyAssign).getCloudRegion(execution, SourceSystem.PO);
-
- assertEquals(cloudRegion.getLcpCloudRegionId(), cloudRegionId);
- }
-
- @Test
- public void getCloudRegionPO30Test() throws Exception {
- cloudRegion.setCloudRegionVersion("3.0");
-
- NetworkBBUtils spyAssignPO = Mockito.spy(NetworkBBUtils.class);
- String cloudRegionIdPO = spyAssignPO.getCloudRegion(execution, SourceSystem.PO);
- Mockito.verify(spyAssignPO).getCloudRegion(execution, SourceSystem.PO);
-
- assertEquals(cloudRegion.getLcpCloudRegionId(), cloudRegionIdPO);
- }
+public class NetworkBBUtilsTest extends BaseTaskTest {
+ @InjectMocks
+ private NetworkBBUtils networkBBUtils = new NetworkBBUtils();
+
+ private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/Network/";
+
+ private CloudRegion cloudRegion;
+
+ @Before
+ public void before() {
+ cloudRegion = setCloudRegion();
+ }
+
+ @Test
+ public void isRelationshipRelatedToExistsTrueTest() throws Exception {
+ final String aaiResponse = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "unassignNetworkBB_queryAAIResponse_.json")));
+ AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiResponse);
+ Optional<L3Network> l3network = aaiResultWrapper.asBean(L3Network.class);
+
+ boolean isVfModule = networkBBUtils.isRelationshipRelatedToExists(l3network, "vf-module");
+ assertTrue(isVfModule);
+
+ }
+
+ @Test
+ public void isRelationshipRelatedToExistsFalseTest() throws Exception {
+ final String aaiResponse =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAAIResponse.json")));
+ AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiResponse);
+ Optional<L3Network> l3network = aaiResultWrapper.asBean(L3Network.class);
+
+ boolean isVfModule = networkBBUtils.isRelationshipRelatedToExists(l3network, "vf-module");
+ assertFalse(isVfModule);
+
+ }
+
+ @Test
+ public void getCloudRegionSDNC25Test() throws Exception {
+ cloudRegion.setCloudRegionVersion("2.5");
+
+ NetworkBBUtils spyAssign = Mockito.spy(NetworkBBUtils.class);
+ String cloudRegionId = spyAssign.getCloudRegion(execution, SourceSystem.SDNC);
+ Mockito.verify(spyAssign).getCloudRegion(execution, SourceSystem.SDNC);
+
+ assertEquals("AAIAIC25", cloudRegionId);
+ }
+
+ @Test
+ public void getCloudRegionSDNC30Test() throws Exception {
+ cloudRegion.setCloudRegionVersion("3.0");
+
+ NetworkBBUtils spyAssign = Mockito.spy(NetworkBBUtils.class);
+ String cloudRegionId = spyAssign.getCloudRegion(execution, SourceSystem.SDNC);
+ Mockito.verify(spyAssign).getCloudRegion(execution, SourceSystem.SDNC);
+
+ assertEquals(cloudRegion.getLcpCloudRegionId(), cloudRegionId);
+ }
+
+ @Test
+ public void getCloudRegionPO25Test() throws Exception {
+ cloudRegion.setCloudRegionVersion("2.5");
+
+ NetworkBBUtils spyAssign = Mockito.spy(NetworkBBUtils.class);
+ String cloudRegionId = spyAssign.getCloudRegion(execution, SourceSystem.PO);
+ Mockito.verify(spyAssign).getCloudRegion(execution, SourceSystem.PO);
+
+ assertEquals(cloudRegion.getLcpCloudRegionId(), cloudRegionId);
+ }
+
+ @Test
+ public void getCloudRegionPO30Test() throws Exception {
+ cloudRegion.setCloudRegionVersion("3.0");
+
+ NetworkBBUtils spyAssignPO = Mockito.spy(NetworkBBUtils.class);
+ String cloudRegionIdPO = spyAssignPO.getCloudRegion(execution, SourceSystem.PO);
+ Mockito.verify(spyAssignPO).getCloudRegion(execution, SourceSystem.PO);
+
+ assertEquals(cloudRegion.getLcpCloudRegionId(), cloudRegionIdPO);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java
index b50cd69f73..8d51ceb65f 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java
@@ -29,11 +29,9 @@ import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.json.JSONArray;
import org.json.JSONObject;
@@ -53,443 +51,542 @@ import org.onap.so.bpmn.servicedecomposition.homingobjects.Candidate;
import org.onap.so.bpmn.servicedecomposition.homingobjects.CandidateType;
import org.onap.so.client.exception.BadResponseException;
import org.onap.so.client.sniro.beans.SniroManagerRequest;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class SniroHomingV2IT extends BaseIntegrationTest{
+public class SniroHomingV2IT extends BaseIntegrationTest {
+
+ private ServiceInstance serviceInstance;
+
+ private RequestContext requestContext;
+
+ private Customer customer;
+ ObjectMapper mapper = new ObjectMapper();
+
+ private static final String RESOURCE_PATH = "__files/BuildingBlocks/SniroHoming/";
+
+
+ String mockResponse =
+ "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"corys cool\", \"requestStatus\": \"accepted\"}";
+
+ @Before
+ public void before() {
+ serviceInstance = setServiceInstance();
+ customer = setCustomer();
+ customer.setGlobalCustomerId("testCustomerId");
+ customer.setSubscriberName("testCustomerName");
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+
+ requestContext = setRequestContext();
+ requestContext.setMsoRequestId("testRequestId");
+ RequestParameters params = new RequestParameters();
+ params.setaLaCarte(false);
+ params.setSubscriptionServiceType("testSubscriptionServiceType");
+ requestContext.setRequestParameters(params);
+ }
+
+ public void beforeVpnBondingLink(String id) {
+ VpnBondingLink bondingLink = new VpnBondingLink();
+ bondingLink.setVpnBondingLinkId("testVpnBondingId" + id);
+ bondingLink.getServiceProxies().add(setServiceProxy("1", "transport"));
+ ServiceProxy sp2 = setServiceProxy("2", "infrastructure");
+ Candidate requiredCandidate = new Candidate();
+ requiredCandidate.setIdentifierType(CandidateType.VNF_ID);
+ List<String> c = new ArrayList<String>();
+ c.add("testVnfId");
+ requiredCandidate.setIdentifiers(c);
+ sp2.addRequiredCandidates(requiredCandidate);
+ bondingLink.getServiceProxies().add(sp2);
+ serviceInstance.getVpnBondingLinks().add(bondingLink);
+
+ }
+
+ public void beforeAllottedResource() {
+ serviceInstance.getAllottedResources().add(setAllottedResource("1"));
+ serviceInstance.getAllottedResources().add(setAllottedResource("2"));
+ serviceInstance.getAllottedResources().add(setAllottedResource("3"));
+ }
+
+ public void beforeVnf() {
+ setGenericVnf();
+ }
+
+ @Test(expected = Test.None.class)
+ public void testCallSniro_success_1VpnLink() throws BadResponseException, IOException {
+ beforeVpnBondingLink("1");
+
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
+
+ sniroHoming.callSniro(execution);
+
+ String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest1Vpn.json");
+ request = request.replace("28080", wireMockPort);
+
+ ArgumentCaptor<SniroManagerRequest> argument = ArgumentCaptor.forClass(SniroManagerRequest.class);
+ verify(sniroClient, times(1)).postDemands(argument.capture());
+ assertEquals(request, argument.getValue().toJsonString());
+ }
+
+ @Test
+ public void testCallSniro_success_3VpnLink() throws JsonProcessingException, BadResponseException {
+ beforeVpnBondingLink("1");
+ beforeVpnBondingLink("2");
+ beforeVpnBondingLink("3");
+
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
+
+ sniroHoming.callSniro(execution);
+
+ String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest3Vpn.json");
+ request = request.replace("28080", wireMockPort);
+
+ ArgumentCaptor<SniroManagerRequest> argument = ArgumentCaptor.forClass(SniroManagerRequest.class);
+ verify(sniroClient, times(1)).postDemands(argument.capture());
+ assertEquals(request, argument.getValue().toJsonString());
+ }
+
+ @Test
+ public void testCallSniro_success_3Allotteds() throws BadResponseException, JsonProcessingException {
+ beforeAllottedResource();
- private ServiceInstance serviceInstance;
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- private RequestContext requestContext;
+ sniroHoming.callSniro(execution);
- private Customer customer;
- ObjectMapper mapper = new ObjectMapper();
+ String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest3AR.json");
+ request = request.replace("28080", wireMockPort);
- private static final String RESOURCE_PATH = "__files/BuildingBlocks/SniroHoming/";
+ ArgumentCaptor<SniroManagerRequest> argument = ArgumentCaptor.forClass(SniroManagerRequest.class);
+ verify(sniroClient, times(1)).postDemands(argument.capture());
+ assertEquals(request, argument.getValue().toJsonString());
+ }
+ @Test
+ public void testCallSniro_success_1Vnf() throws JsonProcessingException, BadResponseException {
+ beforeVnf();
- String mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"corys cool\", \"requestStatus\": \"accepted\"}";
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- @Before
- public void before() {
- serviceInstance = setServiceInstance();
- customer = setCustomer();
- customer.setGlobalCustomerId("testCustomerId");
- customer.setSubscriberName("testCustomerName");
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ sniroHoming.callSniro(execution);
- requestContext = setRequestContext();
- requestContext.setMsoRequestId("testRequestId");
- RequestParameters params = new RequestParameters();
- params.setaLaCarte(false);
- params.setSubscriptionServiceType("testSubscriptionServiceType");
- requestContext.setRequestParameters(params);
- }
+ ArgumentCaptor<SniroManagerRequest> argument = ArgumentCaptor.forClass(SniroManagerRequest.class);
+ verify(sniroClient, times(1)).postDemands(argument.capture());
+ // TODO assertEquals(request, argument.getValue().toJsonString());
+ }
- public void beforeVpnBondingLink(String id){
- VpnBondingLink bondingLink = new VpnBondingLink();
- bondingLink.setVpnBondingLinkId("testVpnBondingId" + id);
- bondingLink.getServiceProxies().add(setServiceProxy("1", "transport"));
- ServiceProxy sp2 = setServiceProxy("2", "infrastructure");
- Candidate requiredCandidate = new Candidate();
- requiredCandidate.setIdentifierType(CandidateType.VNF_ID);
- List<String> c = new ArrayList<String>();
- c.add("testVnfId");
- requiredCandidate.setIdentifiers(c);
- sp2.addRequiredCandidates(requiredCandidate);
- bondingLink.getServiceProxies().add(sp2);
- serviceInstance.getVpnBondingLinks().add(bondingLink);
+ @Test
+ public void testCallSniro_success_3Allotteds1Vnf() throws JsonProcessingException, BadResponseException {
+ beforeAllottedResource();
+ beforeVnf();
- }
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- public void beforeAllottedResource(){
- serviceInstance.getAllottedResources().add(setAllottedResource("1"));
- serviceInstance.getAllottedResources().add(setAllottedResource("2"));
- serviceInstance.getAllottedResources().add(setAllottedResource("3"));
- }
+ sniroHoming.callSniro(execution);
- public void beforeVnf(){
- setGenericVnf();
- }
+ verify(sniroClient, times(1)).postDemands(isA(SniroManagerRequest.class));
+ }
@Test(expected = Test.None.class)
- public void testCallSniro_success_1VpnLink() throws BadResponseException, IOException{
- beforeVpnBondingLink("1");
-
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
-
- sniroHoming.callSniro(execution);
-
- String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest1Vpn.json");
- request = request.replace("28080", wireMockPort);
-
- ArgumentCaptor<SniroManagerRequest> argument = ArgumentCaptor.forClass(SniroManagerRequest.class);
- verify(sniroClient, times(1)).postDemands(argument.capture());
- assertEquals(request, argument.getValue().toJsonString());
- }
-
- @Test
- public void testCallSniro_success_3VpnLink() throws JsonProcessingException, BadResponseException{
- beforeVpnBondingLink("1");
- beforeVpnBondingLink("2");
- beforeVpnBondingLink("3");
-
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
-
- sniroHoming.callSniro(execution);
-
- String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest3Vpn.json");
- request = request.replace("28080", wireMockPort);
-
- ArgumentCaptor<SniroManagerRequest> argument = ArgumentCaptor.forClass(SniroManagerRequest.class);
- verify(sniroClient, times(1)).postDemands(argument.capture());
- assertEquals(request, argument.getValue().toJsonString());
- }
-
- @Test
- public void testCallSniro_success_3Allotteds() throws BadResponseException, JsonProcessingException{
- beforeAllottedResource();
-
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
-
- sniroHoming.callSniro(execution);
-
- String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest3AR.json");
- request = request.replace("28080", wireMockPort);
-
- ArgumentCaptor<SniroManagerRequest> argument = ArgumentCaptor.forClass(SniroManagerRequest.class);
- verify(sniroClient, times(1)).postDemands(argument.capture());
- assertEquals(request, argument.getValue().toJsonString());
- }
-
- @Test
- public void testCallSniro_success_1Vnf() throws JsonProcessingException, BadResponseException{
- beforeVnf();
-
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
-
- sniroHoming.callSniro(execution);
-
- ArgumentCaptor<SniroManagerRequest> argument = ArgumentCaptor.forClass(SniroManagerRequest.class);
- verify(sniroClient, times(1)).postDemands(argument.capture());
- //TODO assertEquals(request, argument.getValue().toJsonString());
- }
-
- @Test
- public void testCallSniro_success_3Allotteds1Vnf() throws JsonProcessingException, BadResponseException{
- beforeAllottedResource();
- beforeVnf();
-
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
-
- sniroHoming.callSniro(execution);
-
- verify(sniroClient, times(1)).postDemands(isA(SniroManagerRequest.class));
- }
-
- @Test(expected = Test.None.class)
- public void testProcessSolution_success_1VpnLink_1Solution(){
- beforeVpnBondingLink("1");
-
- JSONObject asyncResponse = new JSONObject();
- asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed");
- JSONArray solution1 = new JSONArray();
- solution1.put(new JSONObject().put("serviceResourceId", "testProxyId1").put("solution", new JSONObject()
- .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId1")))
- .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False"))
- .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1"))
- .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")).put(new JSONObject().put("key", "aicVersion").put("value", "3"))
- .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId1"))));
- solution1.put(new JSONObject().put("serviceResourceId", "testProxyId2").put("solution", new JSONObject()
- .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId2")))
- .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False"))
- .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "primaryPnfName").put("value", "testPrimaryPnfName2"))
- .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3"))
- .put(new JSONObject().put("key", "secondaryPnfName").put("value", "testSecondaryPnfName2")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId2"))));
-
- asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1)).put("licenseSolutions", new JSONArray()));
-
- sniroHoming.processSolution(execution, asyncResponse.toString());
-
- ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
-
- assertFalse(si.getVpnBondingLinks().isEmpty());
- VpnBondingLink link = si.getVpnBondingLinks().get(0);
- assertNotNull(link);
- assertFalse(link.getServiceProxies().isEmpty());
-
- assertEquals("testServiceInstanceId1", link.getServiceProxy("testProxyId1").getServiceInstance().getServiceInstanceId());
- assertNotNull(link.getServiceProxy("testProxyId1").getServiceInstance().getSolutionInfo());
- assertEquals("testVnfHostName1", link.getServiceProxy("testProxyId1").getServiceInstance().getVnfs().get(0).getVnfName());
-
- assertEquals("testServiceInstanceId2", link.getServiceProxy("testProxyId2").getServiceInstance().getServiceInstanceId());
- assertNotNull(link.getServiceProxy("testProxyId2").getServiceInstance().getSolutionInfo());
- assertFalse(link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().isEmpty());
- assertEquals("testPrimaryPnfName2", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getPnfName());
- assertEquals("primary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getRole());
- assertEquals("testSecondaryPnfName2", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getPnfName());
- assertEquals("secondary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getRole());
- }
-
- @Test
- public void testProcessSolution_success_1VpnLink_2Solutions(){
- beforeVpnBondingLink("1");
-
- JSONObject asyncResponse = new JSONObject();
- asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed");
- JSONArray solution1 = new JSONArray();
- solution1.put(new JSONObject().put("serviceResourceId", "testProxyId1").put("solution", new JSONObject()
- .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId1")))
- .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False"))
- .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1"))
- .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")).put(new JSONObject().put("key", "aicVersion").put("value", "3"))
- .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId1"))));
- solution1.put(new JSONObject().put("serviceResourceId", "testProxyId2").put("solution", new JSONObject()
- .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId2")))
- .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False"))
- .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "primaryPnfName").put("value", "testPrimaryPnfName2"))
- .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3"))
- .put(new JSONObject().put("key", "secondaryPnfName").put("value", "testSecondaryPnfName2")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId2"))));
-
- JSONArray solution2 = new JSONArray();
- solution2.put(new JSONObject().put("serviceResourceId", "testProxyId1").put("solution", new JSONObject()
- .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId3")))
- .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False"))
- .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName3"))
- .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli3")).put(new JSONObject().put("key", "aicVersion").put("value", "3"))
- .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId3")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId3"))));
- solution2.put(new JSONObject().put("serviceResourceId", "testProxyId2").put("solution", new JSONObject()
- .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId4")))
- .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False"))
- .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "primaryPnfName").put("value", "testPrimaryPnfName4"))
- .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli4")).put(new JSONObject().put("key", "aicVersion").put("value", "3"))
- .put(new JSONObject().put("key", "secondaryPnfName").put("value", "testSecondaryPnfName4")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId4"))));
-
- asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1).put(solution2)).put("licenseSolutions", new JSONArray()));
-
- sniroHoming.processSolution(execution, asyncResponse.toString());
-
- ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
-
- assertFalse(si.getVpnBondingLinks().isEmpty());
- VpnBondingLink link = si.getVpnBondingLinks().get(0);
- VpnBondingLink link2 = si.getVpnBondingLinks().get(1);
- assertNotNull(link);
- assertFalse(link.getServiceProxies().isEmpty());
-
- assertEquals("testServiceInstanceId1", link.getServiceProxy("testProxyId1").getServiceInstance().getServiceInstanceId());
- assertNotNull(link.getServiceProxy("testProxyId1").getServiceInstance().getSolutionInfo());
- assertEquals("testVnfHostName1", link.getServiceProxy("testProxyId1").getServiceInstance().getVnfs().get(0).getVnfName());
-
- assertEquals("testServiceInstanceId2", link.getServiceProxy("testProxyId2").getServiceInstance().getServiceInstanceId());
- assertNotNull(link.getServiceProxy("testProxyId2").getServiceInstance().getSolutionInfo());
- assertFalse(link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().isEmpty());
- assertEquals("testPrimaryPnfName2", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getPnfName());
- assertEquals("primary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getRole());
- assertEquals("testSecondaryPnfName2", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getPnfName());
- assertEquals("secondary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getRole());
-
- assertNotNull(link2);
- assertFalse(link2.getServiceProxies().isEmpty());
-
- assertEquals("testServiceInstanceId3", link2.getServiceProxy("testProxyId1").getServiceInstance().getServiceInstanceId());
- assertNotNull(link2.getServiceProxy("testProxyId1").getServiceInstance().getSolutionInfo());
- assertEquals("testVnfHostName3", link2.getServiceProxy("testProxyId1").getServiceInstance().getVnfs().get(0).getVnfName());
-
- assertEquals("testServiceInstanceId4", link2.getServiceProxy("testProxyId2").getServiceInstance().getServiceInstanceId());
- assertNotNull(link2.getServiceProxy("testProxyId2").getServiceInstance().getSolutionInfo());
- assertFalse(link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().isEmpty());
- assertEquals("testPrimaryPnfName4", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getPnfName());
- assertEquals("primary", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getRole());
- assertEquals("testSecondaryPnfName4", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getPnfName());
- assertEquals("secondary", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getRole());
-
- }
-
- @Test
- public void testProcessSolution_success_3VpnLink_2Solutions(){
- //TODO
- }
-
- @Test
- public void testProcessSolution_success_3Allotteds_1Solution(){
- beforeAllottedResource();
-
- JSONObject asyncResponse = new JSONObject();
- asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed");
- JSONArray solution1 = new JSONArray();
- solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId1").put("solution", new JSONObject()
- .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId1")))
- .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True"))
- .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1"))
- .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")).put(new JSONObject().put("key", "aicVersion").put("value", "3"))
- .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId1"))));
- solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId2").put("solution", new JSONObject()
- .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId2")))
- .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True"))
- .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName2"))
- .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3"))
- .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId2"))));
- solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId3").put("solution", new JSONObject()
- .put("identifierType", "cloudRegionId").put("identifiers", new JSONArray().put("testCloudRegionId3")))
- .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True"))
- .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
- .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3"))));
-
- asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1)).put("licenseSolutions", new JSONArray()));
-
- sniroHoming.processSolution(execution, asyncResponse.toString());
-
- ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
-
- assertFalse(si.getAllottedResources().isEmpty());
- AllottedResource ar = si.getAllottedResources().get(0);
- assertNotNull(ar);
- assertEquals("testServiceInstanceId1", ar.getParentServiceInstance().getServiceInstanceId());
- assertNotNull(ar.getParentServiceInstance().getSolutionInfo());
- assertEquals("testVnfHostName1", ar.getParentServiceInstance().getVnfs().get(0).getVnfName());
-
- AllottedResource ar2 = si.getAllottedResources().get(1);
- assertNotNull(ar2);
- assertEquals("testServiceInstanceId2", ar2.getParentServiceInstance().getServiceInstanceId());
- assertNotNull(ar2.getParentServiceInstance().getSolutionInfo());
- assertEquals("testVnfHostName2", ar2.getParentServiceInstance().getVnfs().get(0).getVnfName());
-
- AllottedResource ar3 = si.getAllottedResources().get(2);
- assertNotNull(ar3);
- assertNotNull(ar3.getParentServiceInstance().getSolutionInfo());
- assertEquals("testCloudRegionId3", ar3.getParentServiceInstance().getSolutionInfo().getTargetedCloudRegion().getLcpCloudRegionId());
- }
-
- @Test
- public void testProcessSolution_success_3Allotteds1Vnf_1Solution(){
- beforeVnf();
- beforeAllottedResource();
-
- JSONObject asyncResponse = new JSONObject();
- asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed");
- JSONArray solution1 = new JSONArray();
- JSONArray licenseSolution = new JSONArray();
- solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId1").put("solution", new JSONObject()
- .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId1")))
- .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True"))
- .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1"))
- .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")).put(new JSONObject().put("key", "aicVersion").put("value", "3"))
- .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId1"))));
- solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId2").put("solution", new JSONObject()
- .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId2")))
- .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True"))
- .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName2"))
- .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3"))
- .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId2"))));
- solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId3").put("solution", new JSONObject()
- .put("identifierType", "cloudRegionId").put("identifiers", new JSONArray().put("testCloudRegionId3")))
- .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True"))
- .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2"))
- .put(new JSONObject().put("key", "aicVersion").put("value", "3"))));
-
- licenseSolution.put(
- new JSONObject().put("serviceResourceId", "testVnfId1").put("entitlementPoolUUID", new JSONArray().put("f1d563e8-e714-4393-8f99-cc480144a05e").put("j1d563e8-e714-4393-8f99-cc480144a05e"))
- .put("licenseKeyGroupUUID", new JSONArray().put("s1d563e8-e714-4393-8f99-cc480144a05e").put("b1d563e8-e714-4393-8f99-cc480144a05e")));
-
- asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1)).put("licenseSolutions", licenseSolution));
-
- sniroHoming.processSolution(execution, asyncResponse.toString());
-
- ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
-
- assertFalse(si.getAllottedResources().isEmpty());
- AllottedResource ar = si.getAllottedResources().get(0);
- assertNotNull(ar);
- assertEquals("testServiceInstanceId1", ar.getParentServiceInstance().getServiceInstanceId());
- assertNotNull(ar.getParentServiceInstance().getSolutionInfo());
- assertEquals("testVnfHostName1", ar.getParentServiceInstance().getVnfs().get(0).getVnfName());
-
- AllottedResource ar2 = si.getAllottedResources().get(1);
- assertNotNull(ar2);
- assertEquals("testServiceInstanceId2", ar2.getParentServiceInstance().getServiceInstanceId());
- assertNotNull(ar2.getParentServiceInstance().getSolutionInfo());
- assertEquals("testVnfHostName2", ar2.getParentServiceInstance().getVnfs().get(0).getVnfName());
-
- AllottedResource ar3 = si.getAllottedResources().get(2);
- assertNotNull(ar3);
- assertNotNull(ar3.getParentServiceInstance().getSolutionInfo());
- assertEquals("testCloudRegionId3", ar3.getParentServiceInstance().getSolutionInfo().getTargetedCloudRegion().getLcpCloudRegionId());
-
- GenericVnf vnf = si.getVnfs().get(0);
- assertNotNull(vnf);
- assertNotNull(vnf.getLicense());
- assertEquals(2, vnf.getLicense().getEntitlementPoolUuids().size());
- assertEquals("s1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getLicenseKeyGroupUuids().get(0));
-
- }
-
- @Test
- public void testProcessSolution_success_1Vnf_1Solution(){
- beforeVnf();
-
- JSONObject asyncResponse = new JSONObject();
- asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed");
- JSONArray licenseSolution = new JSONArray();
-
- licenseSolution.put(
- new JSONObject().put("serviceResourceId", "testVnfId1").put("entitlementPoolUUID", new JSONArray().put("f1d563e8-e714-4393-8f99-cc480144a05e").put("j1d563e8-e714-4393-8f99-cc480144a05e"))
- .put("licenseKeyGroupUUID", new JSONArray().put("s1d563e8-e714-4393-8f99-cc480144a05e").put("b1d563e8-e714-4393-8f99-cc480144a05e")));
-
- asyncResponse.put("solutions", new JSONObject().put("licenseSolutions", licenseSolution));
-
- sniroHoming.processSolution(execution, asyncResponse.toString());
-
- ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
-
- GenericVnf vnf = si.getVnfs().get(0);
- assertNotNull(vnf);
- assertNotNull(vnf.getLicense());
- assertEquals(2, vnf.getLicense().getEntitlementPoolUuids().size());
- assertEquals(2, vnf.getLicense().getLicenseKeyGroupUuids().size());
- assertEquals("f1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getEntitlementPoolUuids().get(0));
- assertEquals("s1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getLicenseKeyGroupUuids().get(0));
-
-
- }
-
- @Test(expected = BpmnError.class)
- public void testCallSniro_error_0Resources() throws BadResponseException, JsonProcessingException{
-
- sniroHoming.callSniro(execution);
-
- verify(sniroClient, times(0)).postDemands(isA(SniroManagerRequest.class));
- }
-
- @Test(expected = BpmnError.class)
- public void testCallSniro_error_badResponse() throws BadResponseException, JsonProcessingException{
- beforeAllottedResource();
-
- mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"\", \"requestStatus\": \"failed\"}";
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
-
- sniroHoming.callSniro(execution);
+ public void testProcessSolution_success_1VpnLink_1Solution() {
+ beforeVpnBondingLink("1");
+
+ JSONObject asyncResponse = new JSONObject();
+ asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState",
+ "completed");
+ JSONArray solution1 = new JSONArray();
+ solution1.put(new JSONObject().put("serviceResourceId", "testProxyId1")
+ .put("solution",
+ new JSONObject().put("identifierType", "serviceInstanceId").put("identifiers",
+ new JSONArray().put("testServiceInstanceId1")))
+ .put("assignmentInfo",
+ new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False"))
+ .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
+ .put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1"))
+ .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1"))
+ .put(new JSONObject().put("key", "aicVersion").put("value", "3"))
+ .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1"))
+ .put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId1"))));
+ solution1.put(new JSONObject().put("serviceResourceId", "testProxyId2")
+ .put("solution",
+ new JSONObject().put("identifierType", "serviceInstanceId").put("identifiers",
+ new JSONArray().put("testServiceInstanceId2")))
+ .put("assignmentInfo",
+ new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False"))
+ .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
+ .put(new JSONObject().put("key", "primaryPnfName").put("value", "testPrimaryPnfName2"))
+ .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2"))
+ .put(new JSONObject().put("key", "aicVersion").put("value", "3"))
+ .put(new JSONObject().put("key", "secondaryPnfName").put("value",
+ "testSecondaryPnfName2"))
+ .put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId2"))));
+
+ asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1))
+ .put("licenseSolutions", new JSONArray()));
+
+ sniroHoming.processSolution(execution, asyncResponse.toString());
+
+ ServiceInstance si =
+ execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
+
+ assertFalse(si.getVpnBondingLinks().isEmpty());
+ VpnBondingLink link = si.getVpnBondingLinks().get(0);
+ assertNotNull(link);
+ assertFalse(link.getServiceProxies().isEmpty());
+
+ assertEquals("testServiceInstanceId1",
+ link.getServiceProxy("testProxyId1").getServiceInstance().getServiceInstanceId());
+ assertNotNull(link.getServiceProxy("testProxyId1").getServiceInstance().getSolutionInfo());
+ assertEquals("testVnfHostName1",
+ link.getServiceProxy("testProxyId1").getServiceInstance().getVnfs().get(0).getVnfName());
+
+ assertEquals("testServiceInstanceId2",
+ link.getServiceProxy("testProxyId2").getServiceInstance().getServiceInstanceId());
+ assertNotNull(link.getServiceProxy("testProxyId2").getServiceInstance().getSolutionInfo());
+ assertFalse(link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().isEmpty());
+ assertEquals("testPrimaryPnfName2",
+ link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getPnfName());
+ assertEquals("primary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getRole());
+ assertEquals("testSecondaryPnfName2",
+ link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getPnfName());
+ assertEquals("secondary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getRole());
+ }
+
+ @Test
+ public void testProcessSolution_success_1VpnLink_2Solutions() {
+ beforeVpnBondingLink("1");
+
+ JSONObject asyncResponse = new JSONObject();
+ asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState",
+ "completed");
+ JSONArray solution1 = new JSONArray();
+ solution1.put(new JSONObject().put("serviceResourceId", "testProxyId1")
+ .put("solution",
+ new JSONObject().put("identifierType", "serviceInstanceId").put("identifiers",
+ new JSONArray().put("testServiceInstanceId1")))
+ .put("assignmentInfo",
+ new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False"))
+ .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
+ .put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1"))
+ .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1"))
+ .put(new JSONObject().put("key", "aicVersion").put("value", "3"))
+ .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1"))
+ .put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId1"))));
+ solution1.put(new JSONObject().put("serviceResourceId", "testProxyId2")
+ .put("solution",
+ new JSONObject().put("identifierType", "serviceInstanceId").put("identifiers",
+ new JSONArray().put("testServiceInstanceId2")))
+ .put("assignmentInfo",
+ new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False"))
+ .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
+ .put(new JSONObject().put("key", "primaryPnfName").put("value", "testPrimaryPnfName2"))
+ .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2"))
+ .put(new JSONObject().put("key", "aicVersion").put("value", "3"))
+ .put(new JSONObject().put("key", "secondaryPnfName").put("value",
+ "testSecondaryPnfName2"))
+ .put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId2"))));
+
+ JSONArray solution2 = new JSONArray();
+ solution2.put(new JSONObject().put("serviceResourceId", "testProxyId1")
+ .put("solution",
+ new JSONObject().put("identifierType", "serviceInstanceId").put("identifiers",
+ new JSONArray().put("testServiceInstanceId3")))
+ .put("assignmentInfo",
+ new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False"))
+ .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
+ .put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName3"))
+ .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli3"))
+ .put(new JSONObject().put("key", "aicVersion").put("value", "3"))
+ .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId3"))
+ .put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId3"))));
+ solution2.put(new JSONObject().put("serviceResourceId", "testProxyId2")
+ .put("solution",
+ new JSONObject().put("identifierType", "serviceInstanceId").put("identifiers",
+ new JSONArray().put("testServiceInstanceId4")))
+ .put("assignmentInfo",
+ new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False"))
+ .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
+ .put(new JSONObject().put("key", "primaryPnfName").put("value", "testPrimaryPnfName4"))
+ .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli4"))
+ .put(new JSONObject().put("key", "aicVersion").put("value", "3"))
+ .put(new JSONObject().put("key", "secondaryPnfName").put("value",
+ "testSecondaryPnfName4"))
+ .put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId4"))));
+
+ asyncResponse.put("solutions",
+ new JSONObject().put("placementSolutions", new JSONArray().put(solution1).put(solution2))
+ .put("licenseSolutions", new JSONArray()));
+
+ sniroHoming.processSolution(execution, asyncResponse.toString());
+
+ ServiceInstance si =
+ execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
+
+ assertFalse(si.getVpnBondingLinks().isEmpty());
+ VpnBondingLink link = si.getVpnBondingLinks().get(0);
+ VpnBondingLink link2 = si.getVpnBondingLinks().get(1);
+ assertNotNull(link);
+ assertFalse(link.getServiceProxies().isEmpty());
+
+ assertEquals("testServiceInstanceId1",
+ link.getServiceProxy("testProxyId1").getServiceInstance().getServiceInstanceId());
+ assertNotNull(link.getServiceProxy("testProxyId1").getServiceInstance().getSolutionInfo());
+ assertEquals("testVnfHostName1",
+ link.getServiceProxy("testProxyId1").getServiceInstance().getVnfs().get(0).getVnfName());
+
+ assertEquals("testServiceInstanceId2",
+ link.getServiceProxy("testProxyId2").getServiceInstance().getServiceInstanceId());
+ assertNotNull(link.getServiceProxy("testProxyId2").getServiceInstance().getSolutionInfo());
+ assertFalse(link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().isEmpty());
+ assertEquals("testPrimaryPnfName2",
+ link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getPnfName());
+ assertEquals("primary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getRole());
+ assertEquals("testSecondaryPnfName2",
+ link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getPnfName());
+ assertEquals("secondary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getRole());
+
+ assertNotNull(link2);
+ assertFalse(link2.getServiceProxies().isEmpty());
+
+ assertEquals("testServiceInstanceId3",
+ link2.getServiceProxy("testProxyId1").getServiceInstance().getServiceInstanceId());
+ assertNotNull(link2.getServiceProxy("testProxyId1").getServiceInstance().getSolutionInfo());
+ assertEquals("testVnfHostName3",
+ link2.getServiceProxy("testProxyId1").getServiceInstance().getVnfs().get(0).getVnfName());
+
+ assertEquals("testServiceInstanceId4",
+ link2.getServiceProxy("testProxyId2").getServiceInstance().getServiceInstanceId());
+ assertNotNull(link2.getServiceProxy("testProxyId2").getServiceInstance().getSolutionInfo());
+ assertFalse(link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().isEmpty());
+ assertEquals("testPrimaryPnfName4",
+ link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getPnfName());
+ assertEquals("primary", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getRole());
+ assertEquals("testSecondaryPnfName4",
+ link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getPnfName());
+ assertEquals("secondary",
+ link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getRole());
+
+ }
+
+ @Test
+ public void testProcessSolution_success_3VpnLink_2Solutions() {
+ // TODO
+ }
+
+ @Test
+ public void testProcessSolution_success_3Allotteds_1Solution() {
+ beforeAllottedResource();
+
+ JSONObject asyncResponse = new JSONObject();
+ asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState",
+ "completed");
+ JSONArray solution1 = new JSONArray();
+ solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId1")
+ .put("solution",
+ new JSONObject().put("identifierType", "serviceInstanceId").put("identifiers",
+ new JSONArray().put("testServiceInstanceId1")))
+ .put("assignmentInfo",
+ new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True"))
+ .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
+ .put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1"))
+ .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1"))
+ .put(new JSONObject().put("key", "aicVersion").put("value", "3"))
+ .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1"))
+ .put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId1"))));
+ solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId2")
+ .put("solution",
+ new JSONObject().put("identifierType", "serviceInstanceId").put("identifiers",
+ new JSONArray().put("testServiceInstanceId2")))
+ .put("assignmentInfo",
+ new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True"))
+ .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
+ .put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName2"))
+ .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2"))
+ .put(new JSONObject().put("key", "aicVersion").put("value", "3"))
+ .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1"))
+ .put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId2"))));
+ solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId3")
+ .put("solution",
+ new JSONObject().put("identifierType", "cloudRegionId").put("identifiers",
+ new JSONArray().put("testCloudRegionId3")))
+ .put("assignmentInfo",
+ new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True"))
+ .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
+ .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2"))
+ .put(new JSONObject().put("key", "aicVersion").put("value", "3"))));
+
+ asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1))
+ .put("licenseSolutions", new JSONArray()));
+
+ sniroHoming.processSolution(execution, asyncResponse.toString());
+
+ ServiceInstance si =
+ execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
+
+ assertFalse(si.getAllottedResources().isEmpty());
+ AllottedResource ar = si.getAllottedResources().get(0);
+ assertNotNull(ar);
+ assertEquals("testServiceInstanceId1", ar.getParentServiceInstance().getServiceInstanceId());
+ assertNotNull(ar.getParentServiceInstance().getSolutionInfo());
+ assertEquals("testVnfHostName1", ar.getParentServiceInstance().getVnfs().get(0).getVnfName());
+
+ AllottedResource ar2 = si.getAllottedResources().get(1);
+ assertNotNull(ar2);
+ assertEquals("testServiceInstanceId2", ar2.getParentServiceInstance().getServiceInstanceId());
+ assertNotNull(ar2.getParentServiceInstance().getSolutionInfo());
+ assertEquals("testVnfHostName2", ar2.getParentServiceInstance().getVnfs().get(0).getVnfName());
+
+ AllottedResource ar3 = si.getAllottedResources().get(2);
+ assertNotNull(ar3);
+ assertNotNull(ar3.getParentServiceInstance().getSolutionInfo());
+ assertEquals("testCloudRegionId3",
+ ar3.getParentServiceInstance().getSolutionInfo().getTargetedCloudRegion().getLcpCloudRegionId());
+ }
+
+ @Test
+ public void testProcessSolution_success_3Allotteds1Vnf_1Solution() {
+ beforeVnf();
+ beforeAllottedResource();
+
+ JSONObject asyncResponse = new JSONObject();
+ asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState",
+ "completed");
+ JSONArray solution1 = new JSONArray();
+ JSONArray licenseSolution = new JSONArray();
+ solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId1")
+ .put("solution",
+ new JSONObject().put("identifierType", "serviceInstanceId").put("identifiers",
+ new JSONArray().put("testServiceInstanceId1")))
+ .put("assignmentInfo",
+ new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True"))
+ .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
+ .put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1"))
+ .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1"))
+ .put(new JSONObject().put("key", "aicVersion").put("value", "3"))
+ .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1"))
+ .put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId1"))));
+ solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId2")
+ .put("solution",
+ new JSONObject().put("identifierType", "serviceInstanceId").put("identifiers",
+ new JSONArray().put("testServiceInstanceId2")))
+ .put("assignmentInfo",
+ new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True"))
+ .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
+ .put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName2"))
+ .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2"))
+ .put(new JSONObject().put("key", "aicVersion").put("value", "3"))
+ .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1"))
+ .put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId2"))));
+ solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId3")
+ .put("solution",
+ new JSONObject().put("identifierType", "cloudRegionId").put("identifiers",
+ new JSONArray().put("testCloudRegionId3")))
+ .put("assignmentInfo",
+ new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True"))
+ .put(new JSONObject().put("key", "cloudOwner").put("value", "aic"))
+ .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2"))
+ .put(new JSONObject().put("key", "aicVersion").put("value", "3"))));
+
+ licenseSolution.put(new JSONObject().put("serviceResourceId", "testVnfId1")
+ .put("entitlementPoolUUID",
+ new JSONArray().put("f1d563e8-e714-4393-8f99-cc480144a05e")
+ .put("j1d563e8-e714-4393-8f99-cc480144a05e"))
+ .put("licenseKeyGroupUUID", new JSONArray().put("s1d563e8-e714-4393-8f99-cc480144a05e")
+ .put("b1d563e8-e714-4393-8f99-cc480144a05e")));
+
+ asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1))
+ .put("licenseSolutions", licenseSolution));
+
+ sniroHoming.processSolution(execution, asyncResponse.toString());
+
+ ServiceInstance si =
+ execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
+
+ assertFalse(si.getAllottedResources().isEmpty());
+ AllottedResource ar = si.getAllottedResources().get(0);
+ assertNotNull(ar);
+ assertEquals("testServiceInstanceId1", ar.getParentServiceInstance().getServiceInstanceId());
+ assertNotNull(ar.getParentServiceInstance().getSolutionInfo());
+ assertEquals("testVnfHostName1", ar.getParentServiceInstance().getVnfs().get(0).getVnfName());
+
+ AllottedResource ar2 = si.getAllottedResources().get(1);
+ assertNotNull(ar2);
+ assertEquals("testServiceInstanceId2", ar2.getParentServiceInstance().getServiceInstanceId());
+ assertNotNull(ar2.getParentServiceInstance().getSolutionInfo());
+ assertEquals("testVnfHostName2", ar2.getParentServiceInstance().getVnfs().get(0).getVnfName());
+
+ AllottedResource ar3 = si.getAllottedResources().get(2);
+ assertNotNull(ar3);
+ assertNotNull(ar3.getParentServiceInstance().getSolutionInfo());
+ assertEquals("testCloudRegionId3",
+ ar3.getParentServiceInstance().getSolutionInfo().getTargetedCloudRegion().getLcpCloudRegionId());
+
+ GenericVnf vnf = si.getVnfs().get(0);
+ assertNotNull(vnf);
+ assertNotNull(vnf.getLicense());
+ assertEquals(2, vnf.getLicense().getEntitlementPoolUuids().size());
+ assertEquals("s1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getLicenseKeyGroupUuids().get(0));
+
+ }
+
+ @Test
+ public void testProcessSolution_success_1Vnf_1Solution() {
+ beforeVnf();
+
+ JSONObject asyncResponse = new JSONObject();
+ asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState",
+ "completed");
+ JSONArray licenseSolution = new JSONArray();
+
+ licenseSolution.put(new JSONObject().put("serviceResourceId", "testVnfId1")
+ .put("entitlementPoolUUID",
+ new JSONArray().put("f1d563e8-e714-4393-8f99-cc480144a05e")
+ .put("j1d563e8-e714-4393-8f99-cc480144a05e"))
+ .put("licenseKeyGroupUUID", new JSONArray().put("s1d563e8-e714-4393-8f99-cc480144a05e")
+ .put("b1d563e8-e714-4393-8f99-cc480144a05e")));
+
+ asyncResponse.put("solutions", new JSONObject().put("licenseSolutions", licenseSolution));
+
+ sniroHoming.processSolution(execution, asyncResponse.toString());
+
+ ServiceInstance si =
+ execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
+
+ GenericVnf vnf = si.getVnfs().get(0);
+ assertNotNull(vnf);
+ assertNotNull(vnf.getLicense());
+ assertEquals(2, vnf.getLicense().getEntitlementPoolUuids().size());
+ assertEquals(2, vnf.getLicense().getLicenseKeyGroupUuids().size());
+ assertEquals("f1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getEntitlementPoolUuids().get(0));
+ assertEquals("s1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getLicenseKeyGroupUuids().get(0));
+
+
+ }
+
+ @Test(expected = BpmnError.class)
+ public void testCallSniro_error_0Resources() throws BadResponseException, JsonProcessingException {
+
+ sniroHoming.callSniro(execution);
+
+ verify(sniroClient, times(0)).postDemands(isA(SniroManagerRequest.class));
+ }
+
+ @Test(expected = BpmnError.class)
+ public void testCallSniro_error_badResponse() throws BadResponseException, JsonProcessingException {
+ beforeAllottedResource();
+
+ mockResponse =
+ "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"\", \"requestStatus\": \"failed\"}";
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
+
+ sniroHoming.callSniro(execution);
- verify(sniroClient, times(1)).postDemands(isA(SniroManagerRequest.class));
- }
+ verify(sniroClient, times(1)).postDemands(isA(SniroManagerRequest.class));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBBTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBBTest.java
index ecdf11bd05..bacc57758b 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBBTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBBTest.java
@@ -27,11 +27,9 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
-
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -47,71 +45,77 @@ import org.onap.so.client.aai.entities.AAIResultWrapper;
import org.springframework.beans.factory.annotation.Autowired;
public class UnassignNetworkBBTest extends BaseTaskTest {
-
- @Mock
- private NetworkBBUtils networkBBUtils;
- @InjectMocks
- private UnassignNetworkBB unassignNetworkBB = new UnassignNetworkBB();
-
- private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/Network/";
- private L3Network network;
-
- @Before
- public void setup(){
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- }
-
- @Test
- public void checkRelationshipRelatedToTrueTest() throws Exception {
- expectedException.expect(BpmnError.class);
- network = setL3Network();
- network.setNetworkId("testNetworkId1");
- final String aaiResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "unassignNetworkBB_queryAAIResponse_.json")));
- AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiResponse);
- Optional<org.onap.aai.domain.yang.L3Network> l3network = aaiResultWrapper.asBean(org.onap.aai.domain.yang.L3Network.class);
-
- doReturn(network).when(extractPojosForBB).extractByKey(execution, ResourceKey.NETWORK_ID);
- doReturn(aaiResultWrapper).when(aaiNetworkResources).queryNetworkWrapperById(network);
-
- doReturn(true).when(networkBBUtils).isRelationshipRelatedToExists(any(Optional.class), eq("vf-module"));
-
- unassignNetworkBB.checkRelationshipRelatedTo(execution, "vf-module");
- assertThat(execution.getVariable("ErrorUnassignNetworkBB"), notNullValue());
- }
-
- @Test
- public void getCloudSdncRegion25Test() throws Exception {
- CloudRegion cloudRegion = setCloudRegion();
- cloudRegion.setCloudRegionVersion("2.5");
- doReturn("AAIAIC25").when(networkBBUtils).getCloudRegion(execution, SourceSystem.SDNC);
- unassignNetworkBB.getCloudSdncRegion(execution);
- assertEquals("AAIAIC25", execution.getVariable("cloudRegionSdnc"));
- }
-
- @Test
- public void getCloudSdncRegion30Test() throws Exception {
- CloudRegion cloudRegion = setCloudRegion();
- cloudRegion.setCloudRegionVersion("3.0");
- gBBInput.setCloudRegion(cloudRegion);
- doReturn(cloudRegion.getLcpCloudRegionId()).when(networkBBUtils).getCloudRegion(execution, SourceSystem.SDNC);
- unassignNetworkBB.getCloudSdncRegion(execution);
- assertEquals(cloudRegion.getLcpCloudRegionId(), execution.getVariable("cloudRegionSdnc"));
- }
-
- @Test
- public void errorEncounteredTest_rollback() throws Exception {
- expectedException.expect(BpmnError.class);
- execution.setVariable("ErrorUnassignNetworkBB", "Relationship's RelatedTo still exists in AAI, remove the relationship vf-module first.");
- execution.setVariable("isRollbackNeeded", true);
- unassignNetworkBB.errorEncountered(execution);
- }
-
- @Test
- public void errorEncounteredTest_noRollback() throws Exception {
- expectedException.expect(BpmnError.class);
- execution.setVariable("ErrorUnassignNetworkBB", "Relationship's RelatedTo still exists in AAI, remove the relationship vf-module first.");
- unassignNetworkBB.errorEncountered(execution);
- }
+ @Mock
+ private NetworkBBUtils networkBBUtils;
+
+ @InjectMocks
+ private UnassignNetworkBB unassignNetworkBB = new UnassignNetworkBB();
+
+ private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/Network/";
+ private L3Network network;
+
+ @Before
+ public void setup() {
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ }
+
+ @Test
+ public void checkRelationshipRelatedToTrueTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ network = setL3Network();
+ network.setNetworkId("testNetworkId1");
+ final String aaiResponse = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "unassignNetworkBB_queryAAIResponse_.json")));
+ AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiResponse);
+ Optional<org.onap.aai.domain.yang.L3Network> l3network =
+ aaiResultWrapper.asBean(org.onap.aai.domain.yang.L3Network.class);
+
+ doReturn(network).when(extractPojosForBB).extractByKey(execution, ResourceKey.NETWORK_ID);
+ doReturn(aaiResultWrapper).when(aaiNetworkResources).queryNetworkWrapperById(network);
+
+ doReturn(true).when(networkBBUtils).isRelationshipRelatedToExists(any(Optional.class), eq("vf-module"));
+
+ unassignNetworkBB.checkRelationshipRelatedTo(execution, "vf-module");
+ assertThat(execution.getVariable("ErrorUnassignNetworkBB"), notNullValue());
+ }
+
+ @Test
+ public void getCloudSdncRegion25Test() throws Exception {
+ CloudRegion cloudRegion = setCloudRegion();
+ cloudRegion.setCloudRegionVersion("2.5");
+ doReturn("AAIAIC25").when(networkBBUtils).getCloudRegion(execution, SourceSystem.SDNC);
+ unassignNetworkBB.getCloudSdncRegion(execution);
+ assertEquals("AAIAIC25", execution.getVariable("cloudRegionSdnc"));
+ }
+
+ @Test
+ public void getCloudSdncRegion30Test() throws Exception {
+ CloudRegion cloudRegion = setCloudRegion();
+ cloudRegion.setCloudRegionVersion("3.0");
+ gBBInput.setCloudRegion(cloudRegion);
+ doReturn(cloudRegion.getLcpCloudRegionId()).when(networkBBUtils).getCloudRegion(execution, SourceSystem.SDNC);
+ unassignNetworkBB.getCloudSdncRegion(execution);
+ assertEquals(cloudRegion.getLcpCloudRegionId(), execution.getVariable("cloudRegionSdnc"));
+ }
+
+ @Test
+ public void errorEncounteredTest_rollback() throws Exception {
+ expectedException.expect(BpmnError.class);
+ execution.setVariable("ErrorUnassignNetworkBB",
+ "Relationship's RelatedTo still exists in AAI, remove the relationship vf-module first.");
+ execution.setVariable("isRollbackNeeded", true);
+ unassignNetworkBB.errorEncountered(execution);
+ }
+
+ @Test
+ public void errorEncounteredTest_noRollback() throws Exception {
+ expectedException.expect(BpmnError.class);
+ execution.setVariable("ErrorUnassignNetworkBB",
+ "Relationship's RelatedTo still exists in AAI, remove the relationship vf-module first.");
+ unassignNetworkBB.errorEncountered(execution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnfTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnfTest.java
index 394ffcf0ac..b4cb214483 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnfTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnfTest.java
@@ -28,7 +28,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -41,43 +40,46 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup;
import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoInstanceGroup;
-public class UnassignVnfTest extends BaseTaskTest{
- @InjectMocks
- private UnassignVnf unassignVnf = new UnassignVnf();
-
- @Before
- public void setup(){
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
-
- }
+public class UnassignVnfTest extends BaseTaskTest {
+ @InjectMocks
+ private UnassignVnf unassignVnf = new UnassignVnf();
+
+ @Before
+ public void setup() {
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+
+ }
+
+ @Test
+ public void deleteInstanceGroupsSunnyDayTest() throws Exception {
+ GenericVnf genericVnf = setGenericVnf();
+
+ ModelInfoInstanceGroup modelVnfc = new ModelInfoInstanceGroup();
+ modelVnfc.setType("VNFC");
+
+ InstanceGroup instanceGroup1 = new InstanceGroup();
+ instanceGroup1.setId("test-001");
+ instanceGroup1.setModelInfoInstanceGroup(modelVnfc);
+ genericVnf.getInstanceGroups().add(instanceGroup1);
+
+ InstanceGroup instanceGroup2 = new InstanceGroup();
+ instanceGroup2.setId("test-002");
+ instanceGroup2.setModelInfoInstanceGroup(modelVnfc);
+ genericVnf.getInstanceGroups().add(instanceGroup2);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ unassignVnf.deleteInstanceGroups(execution);
+ verify(aaiInstanceGroupResources, times(1)).deleteInstanceGroup(eq(instanceGroup1));
+ verify(aaiInstanceGroupResources, times(1)).deleteInstanceGroup(eq(instanceGroup2));
+ }
+
+ @Test
+ public void deletecreateVnfcInstanceGroupExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
- @Test
- public void deleteInstanceGroupsSunnyDayTest() throws Exception {
- GenericVnf genericVnf = setGenericVnf();
-
- ModelInfoInstanceGroup modelVnfc = new ModelInfoInstanceGroup();
- modelVnfc.setType("VNFC");
-
- InstanceGroup instanceGroup1 = new InstanceGroup();
- instanceGroup1.setId("test-001");
- instanceGroup1.setModelInfoInstanceGroup(modelVnfc);
- genericVnf.getInstanceGroups().add(instanceGroup1);
-
- InstanceGroup instanceGroup2 = new InstanceGroup();
- instanceGroup2.setId("test-002");
- instanceGroup2.setModelInfoInstanceGroup(modelVnfc);
- genericVnf.getInstanceGroups().add(instanceGroup2);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- unassignVnf.deleteInstanceGroups(execution);
- verify(aaiInstanceGroupResources, times(1)).deleteInstanceGroup(eq(instanceGroup1));
- verify(aaiInstanceGroupResources, times(1)).deleteInstanceGroup(eq(instanceGroup2));
- }
-
- @Test
- public void deletecreateVnfcInstanceGroupExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- unassignVnf.deleteInstanceGroups(execution);
- }
+ unassignVnf.deleteInstanceGroups(execution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasksTest.java
index 5e9565446f..f9ad473e5a 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasksTest.java
@@ -6,10 +6,8 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.util.HashMap;
import java.util.Map;
-
import org.camunda.bpm.engine.ProcessEngineServices;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.delegate.DelegateExecution;
@@ -23,76 +21,76 @@ import org.onap.so.bpmn.BaseTaskTest;
import org.onap.so.db.request.beans.InfraActiveRequests;
public class ManualHandlingTasksTest extends BaseTaskTest {
- @InjectMocks
- protected ManualHandlingTasks manualHandlingTasks = new ManualHandlingTasks();
-
- @Mock
- TaskService taskService;
-
- @Mock
- private DelegateExecution mockExecution;
-
- @Mock
- ProcessEngineServices processEngineServices;
-
- @Mock
- private DelegateTask task;
-
- private DelegateExecution delegateExecution;
-
- @Before
- public void before() throws Exception {
- delegateExecution = new DelegateExecutionFake();
- }
-
- @Test
- public void setFalloutTaskVariables_Test () {
- when(task.getId()).thenReturn("taskId");
- when(task.getExecution()).thenReturn(mockExecution);
- when(mockExecution.getProcessEngineServices()).thenReturn(processEngineServices);
- when(processEngineServices.getTaskService()).thenReturn(taskService);
- manualHandlingTasks.setFalloutTaskVariables(task);
- verify(taskService, times(1)).setVariables(any(String.class), any(Map.class));
- }
-
- @Test
- public void setPauseTaskVariables_Test () {
- when(task.getId()).thenReturn("taskId");
- when(task.getExecution()).thenReturn(mockExecution);
- when(mockExecution.getProcessEngineServices()).thenReturn(processEngineServices);
- when(processEngineServices.getTaskService()).thenReturn(taskService);
- manualHandlingTasks.setPauseTaskVariables(task);
- verify(taskService, times(1)).setVariables(any(String.class), any(Map.class));
- }
-
- @Test
- public void completeTask_Test() throws Exception{
- when(task.getId()).thenReturn("taskId");
- when(task.getExecution()).thenReturn(mockExecution);
- Map<String, Object> taskVariables = new HashMap<String, Object>();
- taskVariables.put("responseValue", "resume");
- when(mockExecution.getProcessEngineServices()).thenReturn(processEngineServices);
- when(processEngineServices.getTaskService()).thenReturn(taskService);
- when(taskService.getVariables(any(String.class))).thenReturn(taskVariables);
- manualHandlingTasks.completeTask(task);
- verify(mockExecution, times(1)).setVariable("responseValueTask", "Resume");
- }
-
- @Test
- public void updateRequestDbStatus_Test() throws Exception{
- InfraActiveRequests mockedRequest = new InfraActiveRequests();
- delegateExecution.setVariable("msoRequestId", "testMsoRequestId");
- when(requestsDbClient.getInfraActiveRequestbyRequestId(any(String.class))).thenReturn(mockedRequest);
- doNothing().when(requestsDbClient).updateInfraActiveRequests(any(InfraActiveRequests.class));
- manualHandlingTasks.updateRequestDbStatus(delegateExecution, "IN_PROGRESS");
- verify(requestsDbClient, times(1)).updateInfraActiveRequests(any(InfraActiveRequests.class));
- assertEquals(mockedRequest.getRequestStatus(), "IN_PROGRESS");
- }
-
- @Test
- public void createExternalTicket_Test() throws Exception{
- delegateExecution.setVariable("msoRequestId", ("testMsoRequestId"));
- delegateExecution.setVariable("vnfType", "testVnfType");
- manualHandlingTasks.createExternalTicket(delegateExecution);
- }
+ @InjectMocks
+ protected ManualHandlingTasks manualHandlingTasks = new ManualHandlingTasks();
+
+ @Mock
+ TaskService taskService;
+
+ @Mock
+ private DelegateExecution mockExecution;
+
+ @Mock
+ ProcessEngineServices processEngineServices;
+
+ @Mock
+ private DelegateTask task;
+
+ private DelegateExecution delegateExecution;
+
+ @Before
+ public void before() throws Exception {
+ delegateExecution = new DelegateExecutionFake();
+ }
+
+ @Test
+ public void setFalloutTaskVariables_Test() {
+ when(task.getId()).thenReturn("taskId");
+ when(task.getExecution()).thenReturn(mockExecution);
+ when(mockExecution.getProcessEngineServices()).thenReturn(processEngineServices);
+ when(processEngineServices.getTaskService()).thenReturn(taskService);
+ manualHandlingTasks.setFalloutTaskVariables(task);
+ verify(taskService, times(1)).setVariables(any(String.class), any(Map.class));
+ }
+
+ @Test
+ public void setPauseTaskVariables_Test() {
+ when(task.getId()).thenReturn("taskId");
+ when(task.getExecution()).thenReturn(mockExecution);
+ when(mockExecution.getProcessEngineServices()).thenReturn(processEngineServices);
+ when(processEngineServices.getTaskService()).thenReturn(taskService);
+ manualHandlingTasks.setPauseTaskVariables(task);
+ verify(taskService, times(1)).setVariables(any(String.class), any(Map.class));
+ }
+
+ @Test
+ public void completeTask_Test() throws Exception {
+ when(task.getId()).thenReturn("taskId");
+ when(task.getExecution()).thenReturn(mockExecution);
+ Map<String, Object> taskVariables = new HashMap<String, Object>();
+ taskVariables.put("responseValue", "resume");
+ when(mockExecution.getProcessEngineServices()).thenReturn(processEngineServices);
+ when(processEngineServices.getTaskService()).thenReturn(taskService);
+ when(taskService.getVariables(any(String.class))).thenReturn(taskVariables);
+ manualHandlingTasks.completeTask(task);
+ verify(mockExecution, times(1)).setVariable("responseValueTask", "Resume");
+ }
+
+ @Test
+ public void updateRequestDbStatus_Test() throws Exception {
+ InfraActiveRequests mockedRequest = new InfraActiveRequests();
+ delegateExecution.setVariable("msoRequestId", "testMsoRequestId");
+ when(requestsDbClient.getInfraActiveRequestbyRequestId(any(String.class))).thenReturn(mockedRequest);
+ doNothing().when(requestsDbClient).updateInfraActiveRequests(any(InfraActiveRequests.class));
+ manualHandlingTasks.updateRequestDbStatus(delegateExecution, "IN_PROGRESS");
+ verify(requestsDbClient, times(1)).updateInfraActiveRequests(any(InfraActiveRequests.class));
+ assertEquals(mockedRequest.getRequestStatus(), "IN_PROGRESS");
+ }
+
+ @Test
+ public void createExternalTicket_Test() throws Exception {
+ delegateExecution.setVariable("msoRequestId", ("testMsoRequestId"));
+ delegateExecution.setVariable("vnfType", "testVnfType");
+ manualHandlingTasks.createExternalTicket(delegateExecution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java
index 67c48d1e91..f5785f94fd 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java
@@ -27,7 +27,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
@@ -38,44 +37,50 @@ import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
import org.onap.so.client.exception.BBObjectNotFoundException;
public class NamingServiceCreateTasksTest extends BaseTaskTest {
- @InjectMocks
- private NamingServiceCreateTasks namingServiceCreateTasks = new NamingServiceCreateTasks();
-
- private InstanceGroup instanceGroup;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- instanceGroup = setInstanceGroup();
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID))).thenReturn(instanceGroup);
- }
-
- @Test
- public void createInstanceGroupTest() throws Exception {
- String policyInstanceName = "policyInstanceName";
- String nfNamingCode = "nfNamingCode";
- String generatedName = "generatedInstanceGroupName";
- execution.setVariable(policyInstanceName, policyInstanceName);
- execution.setVariable(nfNamingCode, nfNamingCode);
- doReturn(generatedName).when(namingServiceResources).generateInstanceGroupName(instanceGroup, policyInstanceName, nfNamingCode);
-
- namingServiceCreateTasks.createInstanceGroupName(execution);
- verify(namingServiceResources, times(1)).generateInstanceGroupName(instanceGroup, policyInstanceName, nfNamingCode);
- assertEquals(instanceGroup.getInstanceGroupName(), generatedName);
- }
-
- @Test
- public void createInstanceGroupExceptionTest() throws Exception {
- expectedException.expect(BBObjectNotFoundException.class);
- lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, "notfound");
- doThrow(BBObjectNotFoundException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID));
- String policyInstanceName = "policyInstanceName";
- String nfNamingCode = "nfNamingCode";
- execution.setVariable(policyInstanceName, policyInstanceName);
- execution.setVariable(nfNamingCode, nfNamingCode);
- doReturn("").when(namingServiceResources).generateInstanceGroupName(instanceGroup, policyInstanceName, nfNamingCode);
- namingServiceCreateTasks.createInstanceGroupName(execution);
- verify(namingServiceResources, times(1)).generateInstanceGroupName(instanceGroup, policyInstanceName, nfNamingCode);
-
- }
-
+ @InjectMocks
+ private NamingServiceCreateTasks namingServiceCreateTasks = new NamingServiceCreateTasks();
+
+ private InstanceGroup instanceGroup;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ instanceGroup = setInstanceGroup();
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID)))
+ .thenReturn(instanceGroup);
+ }
+
+ @Test
+ public void createInstanceGroupTest() throws Exception {
+ String policyInstanceName = "policyInstanceName";
+ String nfNamingCode = "nfNamingCode";
+ String generatedName = "generatedInstanceGroupName";
+ execution.setVariable(policyInstanceName, policyInstanceName);
+ execution.setVariable(nfNamingCode, nfNamingCode);
+ doReturn(generatedName).when(namingServiceResources).generateInstanceGroupName(instanceGroup,
+ policyInstanceName, nfNamingCode);
+
+ namingServiceCreateTasks.createInstanceGroupName(execution);
+ verify(namingServiceResources, times(1)).generateInstanceGroupName(instanceGroup, policyInstanceName,
+ nfNamingCode);
+ assertEquals(instanceGroup.getInstanceGroupName(), generatedName);
+ }
+
+ @Test
+ public void createInstanceGroupExceptionTest() throws Exception {
+ expectedException.expect(BBObjectNotFoundException.class);
+ lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, "notfound");
+ doThrow(BBObjectNotFoundException.class).when(extractPojosForBB).extractByKey(any(),
+ ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID));
+ String policyInstanceName = "policyInstanceName";
+ String nfNamingCode = "nfNamingCode";
+ execution.setVariable(policyInstanceName, policyInstanceName);
+ execution.setVariable(nfNamingCode, nfNamingCode);
+ doReturn("").when(namingServiceResources).generateInstanceGroupName(instanceGroup, policyInstanceName,
+ nfNamingCode);
+ namingServiceCreateTasks.createInstanceGroupName(execution);
+ verify(namingServiceResources, times(1)).generateInstanceGroupName(instanceGroup, policyInstanceName,
+ nfNamingCode);
+
+ }
+
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java
index 56226dfa96..758b8f4ffd 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java
@@ -26,7 +26,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
@@ -37,34 +36,36 @@ import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
import org.onap.so.client.exception.BBObjectNotFoundException;
public class NamingServiceDeleteTasksTest extends BaseTaskTest {
- @InjectMocks
- private NamingServiceDeleteTasks namingServiceDeleteTasks = new NamingServiceDeleteTasks();
-
- private InstanceGroup instanceGroup;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- instanceGroup = setInstanceGroup();
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID))).thenReturn(instanceGroup);
- }
-
- @Test
- public void deleteInstanceGroupTest() throws Exception {
-
- doReturn("").when(namingServiceResources).deleteInstanceGroupName(instanceGroup);
-
- namingServiceDeleteTasks.deleteInstanceGroupName(execution);
- verify(namingServiceResources, times(1)).deleteInstanceGroupName(instanceGroup);
- }
-
- @Test
- public void deleteInstanceGroupExceptionTest() throws Exception {
- expectedException.expect(BBObjectNotFoundException.class);
- lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, "notfound");
- doThrow(BBObjectNotFoundException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID));
- doReturn("").when(namingServiceResources).deleteInstanceGroupName(instanceGroup);
- namingServiceDeleteTasks.deleteInstanceGroupName(execution);
- verify(namingServiceResources, times(1)).deleteInstanceGroupName(instanceGroup);
- }
-
+ @InjectMocks
+ private NamingServiceDeleteTasks namingServiceDeleteTasks = new NamingServiceDeleteTasks();
+
+ private InstanceGroup instanceGroup;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ instanceGroup = setInstanceGroup();
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID)))
+ .thenReturn(instanceGroup);
+ }
+
+ @Test
+ public void deleteInstanceGroupTest() throws Exception {
+
+ doReturn("").when(namingServiceResources).deleteInstanceGroupName(instanceGroup);
+
+ namingServiceDeleteTasks.deleteInstanceGroupName(execution);
+ verify(namingServiceResources, times(1)).deleteInstanceGroupName(instanceGroup);
+ }
+
+ @Test
+ public void deleteInstanceGroupExceptionTest() throws Exception {
+ expectedException.expect(BBObjectNotFoundException.class);
+ lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, "notfound");
+ doThrow(BBObjectNotFoundException.class).when(extractPojosForBB).extractByKey(any(),
+ ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID));
+ doReturn("").when(namingServiceResources).deleteInstanceGroupName(instanceGroup);
+ namingServiceDeleteTasks.deleteInstanceGroupName(execution);
+ verify(namingServiceResources, times(1)).deleteInstanceGroupName(instanceGroup);
+ }
+
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java
index cbd7605aa4..4eb1432bbf 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java
@@ -29,7 +29,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -52,84 +51,98 @@ import org.onap.so.client.exception.BBObjectNotFoundException;
import org.onap.so.client.sdnc.beans.SDNCRequest;
import org.onap.so.client.sdnc.endpoint.SDNCTopology;
-public class SDNCActivateTaskTest extends BaseTaskTest{
-
- @InjectMocks
- private SDNCActivateTasks sdncActivateTasks = new SDNCActivateTasks();
-
- private L3Network network;
- private ServiceInstance serviceInstance;
- private RequestContext requestContext;
- private CloudRegion cloudRegion;
- private GenericVnf genericVnf;
- private VfModule vfModule;
- private Customer customer;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- serviceInstance = setServiceInstance();
- network = setL3Network();
- genericVnf = setGenericVnf();
- vfModule = setVfModule();
- cloudRegion = setCloudRegion();
- requestContext = setRequestContext();
- customer = setCustomer();
+public class SDNCActivateTaskTest extends BaseTaskTest {
+
+ @InjectMocks
+ private SDNCActivateTasks sdncActivateTasks = new SDNCActivateTasks();
+
+ private L3Network network;
+ private ServiceInstance serviceInstance;
+ private RequestContext requestContext;
+ private CloudRegion cloudRegion;
+ private GenericVnf genericVnf;
+ private VfModule vfModule;
+ private Customer customer;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ serviceInstance = setServiceInstance();
+ network = setL3Network();
+ genericVnf = setGenericVnf();
+ vfModule = setVfModule();
+ cloudRegion = setCloudRegion();
+ requestContext = setRequestContext();
+ customer = setCustomer();
+
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+
+ }
+
+ @Test
+ public void activateVnfTest() throws Exception {
+ doReturn(new GenericResourceApiVnfOperationInformation()).when(sdncVnfResources).activateVnf(genericVnf,
+ serviceInstance, customer, cloudRegion, requestContext);
+ sdncActivateTasks.activateVnf(execution);
+ verify(sdncVnfResources, times(1)).activateVnf(genericVnf, serviceInstance, customer, cloudRegion,
+ requestContext);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.VNF, sdncRequest.getTopology());
+ }
+
+ @Test
+ public void activateVnfTestException() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncVnfResources).activateVnf(genericVnf, serviceInstance, customer,
+ cloudRegion, requestContext);
+ sdncActivateTasks.activateVnf(execution);
+ }
+
+ @Test
+ public void activateNetworkTest() throws Exception {
+ doReturn(new GenericResourceApiNetworkOperationInformation()).when(sdncNetworkResources).activateNetwork(
+ isA(L3Network.class), isA(ServiceInstance.class), isA(Customer.class), isA(RequestContext.class),
+ isA(CloudRegion.class));
+ sdncActivateTasks.activateNetwork(execution);
+ verify(sdncNetworkResources, times(1)).activateNetwork(network, serviceInstance, customer, requestContext,
+ cloudRegion);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.NETWORK, sdncRequest.getTopology());
+ }
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
+ @Test
+ public void activateNetworkExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncNetworkResources).activateNetwork(isA(L3Network.class),
+ isA(ServiceInstance.class), isA(Customer.class), isA(RequestContext.class), isA(CloudRegion.class));
+ sdncActivateTasks.activateNetwork(execution);
+ }
- }
+ @Test
+ public void activateVfModuleTest() throws Exception {
+ doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources)
+ .activateVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
+ sdncActivateTasks.activateVfModule(execution);
+ verify(sdncVfModuleResources, times(1)).activateVfModule(vfModule, genericVnf, serviceInstance, customer,
+ cloudRegion, requestContext);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.VFMODULE, sdncRequest.getTopology());
+ }
- @Test
- public void activateVnfTest() throws Exception {
- doReturn(new GenericResourceApiVnfOperationInformation()).when(sdncVnfResources).activateVnf(genericVnf,serviceInstance, customer, cloudRegion,requestContext);
- sdncActivateTasks.activateVnf(execution);
- verify(sdncVnfResources, times(1)).activateVnf(genericVnf,serviceInstance, customer,cloudRegion,requestContext);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.VNF,sdncRequest.getTopology());
- }
-
- @Test
- public void activateVnfTestException() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncVnfResources).activateVnf(genericVnf,serviceInstance, customer,cloudRegion,requestContext);
- sdncActivateTasks.activateVnf(execution);
- }
-
- @Test
- public void activateNetworkTest() throws Exception {
- doReturn(new GenericResourceApiNetworkOperationInformation()).when(sdncNetworkResources).activateNetwork(isA(L3Network.class), isA(ServiceInstance.class), isA(Customer.class), isA(RequestContext.class), isA(CloudRegion.class));
- sdncActivateTasks.activateNetwork(execution);
- verify(sdncNetworkResources, times(1)).activateNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.NETWORK,sdncRequest.getTopology());
- }
-
- @Test
- public void activateNetworkExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncNetworkResources).activateNetwork(isA(L3Network.class), isA(ServiceInstance.class), isA(Customer.class), isA(RequestContext.class), isA(CloudRegion.class));
- sdncActivateTasks.activateNetwork(execution);
- }
-
- @Test
- public void activateVfModuleTest() throws Exception {
- doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources).activateVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncActivateTasks.activateVfModule(execution);
- verify(sdncVfModuleResources, times(1)).activateVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.VFMODULE,sdncRequest.getTopology());
- }
-
- @Test
- public void activateVfModuleTestException() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncVfModuleResources).activateVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncActivateTasks.activateVfModule(execution);
- }
+ @Test
+ public void activateVfModuleTestException() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncVfModuleResources).activateVfModule(vfModule, genericVnf,
+ serviceInstance, customer, cloudRegion, requestContext);
+ sdncActivateTasks.activateVfModule(execution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java
index b5509b1e12..7d8e94d1e9 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java
@@ -28,7 +28,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -54,101 +53,117 @@ import org.onap.so.client.sdnc.beans.SDNCRequest;
import org.onap.so.client.sdnc.endpoint.SDNCTopology;
-public class SDNCAssignTasksTest extends BaseTaskTest{
- @InjectMocks
- private SDNCAssignTasks sdncAssignTasks = new SDNCAssignTasks();
+public class SDNCAssignTasksTest extends BaseTaskTest {
+ @InjectMocks
+ private SDNCAssignTasks sdncAssignTasks = new SDNCAssignTasks();
+
+ private L3Network network;
+ private ServiceInstance serviceInstance;
+ private RequestContext requestContext;
+ private CloudRegion cloudRegion;
+ private GenericVnf genericVnf;
+ private VfModule vfModule;
+ private VolumeGroup volumeGroup;
+ private Customer customer;
- private L3Network network;
- private ServiceInstance serviceInstance;
- private RequestContext requestContext;
- private CloudRegion cloudRegion;
- private GenericVnf genericVnf;
- private VfModule vfModule;
- private VolumeGroup volumeGroup;
- private Customer customer;
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ customer = setCustomer();
+ serviceInstance = setServiceInstance();
+ network = setL3Network();
+ cloudRegion = setCloudRegion();
+ requestContext = setRequestContext();
+ genericVnf = setGenericVnf();
+ vfModule = setVfModule();
+ volumeGroup = setVolumeGroup();
- @Before
- public void before() throws BBObjectNotFoundException {
- customer = setCustomer();
- serviceInstance = setServiceInstance();
- network = setL3Network();
- cloudRegion = setCloudRegion();
- requestContext = setRequestContext();
- genericVnf = setGenericVnf();
- vfModule = setVfModule();
- volumeGroup = setVolumeGroup();
-
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup);
- }
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID)))
+ .thenReturn(volumeGroup);
+ }
- @Test
- public void assignServiceInstanceTest() throws Exception {
- doReturn(new GenericResourceApiServiceOperationInformation()).when(sdncServiceInstanceResources).assignServiceInstance(serviceInstance, customer, requestContext);
- sdncAssignTasks.assignServiceInstance(execution);
- verify(sdncServiceInstanceResources, times(1)).assignServiceInstance(serviceInstance, customer, requestContext);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.SERVICE,sdncRequest.getTopology());
- }
+ @Test
+ public void assignServiceInstanceTest() throws Exception {
+ doReturn(new GenericResourceApiServiceOperationInformation()).when(sdncServiceInstanceResources)
+ .assignServiceInstance(serviceInstance, customer, requestContext);
+ sdncAssignTasks.assignServiceInstance(execution);
+ verify(sdncServiceInstanceResources, times(1)).assignServiceInstance(serviceInstance, customer, requestContext);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.SERVICE, sdncRequest.getTopology());
+ }
- @Test
- public void assignServiceInstanceExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncServiceInstanceResources).assignServiceInstance(serviceInstance, customer, requestContext);
- sdncAssignTasks.assignServiceInstance(execution);
- }
+ @Test
+ public void assignServiceInstanceExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncServiceInstanceResources).assignServiceInstance(serviceInstance,
+ customer, requestContext);
+ sdncAssignTasks.assignServiceInstance(execution);
+ }
- @Test
- public void assignVnfTest() throws Exception {
- doReturn(new GenericResourceApiVnfOperationInformation()).when(sdncVnfResources).assignVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext, false);
- execution.setVariable("generalBuildingBlock", gBBInput);
- sdncAssignTasks.assignVnf(execution);
- verify(sdncVnfResources, times(1)).assignVnf(genericVnf, serviceInstance,customer, cloudRegion, requestContext, false);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.VNF,sdncRequest.getTopology());
- }
+ @Test
+ public void assignVnfTest() throws Exception {
+ doReturn(new GenericResourceApiVnfOperationInformation()).when(sdncVnfResources).assignVnf(genericVnf,
+ serviceInstance, customer, cloudRegion, requestContext, false);
+ execution.setVariable("generalBuildingBlock", gBBInput);
+ sdncAssignTasks.assignVnf(execution);
+ verify(sdncVnfResources, times(1)).assignVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext,
+ false);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.VNF, sdncRequest.getTopology());
+ }
- @Test
- public void assignVnfExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncVnfResources).assignVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext, false);
- sdncAssignTasks.assignVnf(execution);
- }
+ @Test
+ public void assignVnfExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncVnfResources).assignVnf(genericVnf, serviceInstance, customer,
+ cloudRegion, requestContext, false);
+ sdncAssignTasks.assignVnf(execution);
+ }
- @Test
- public void assignVfModuleTest() throws Exception {
- doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources).assignVfModule(vfModule, volumeGroup, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncAssignTasks.assignVfModule(execution);
- verify(sdncVfModuleResources, times(1)).assignVfModule(vfModule, volumeGroup, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.VFMODULE,sdncRequest.getTopology());
- }
+ @Test
+ public void assignVfModuleTest() throws Exception {
+ doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources).assignVfModule(
+ vfModule, volumeGroup, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
+ sdncAssignTasks.assignVfModule(execution);
+ verify(sdncVfModuleResources, times(1)).assignVfModule(vfModule, volumeGroup, genericVnf, serviceInstance,
+ customer, cloudRegion, requestContext);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.VFMODULE, sdncRequest.getTopology());
+ }
- @Test
- public void assignVfModuleExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncVfModuleResources).assignVfModule(vfModule, volumeGroup, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncAssignTasks.assignVfModule(execution);
- }
+ @Test
+ public void assignVfModuleExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncVfModuleResources).assignVfModule(vfModule, volumeGroup, genericVnf,
+ serviceInstance, customer, cloudRegion, requestContext);
+ sdncAssignTasks.assignVfModule(execution);
+ }
- @Test
- public void assignNetworkTest() throws Exception {
- doReturn(new GenericResourceApiNetworkOperationInformation()).when(sdncNetworkResources).assignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- sdncAssignTasks.assignNetwork(execution);
- verify(sdncNetworkResources, times(1)).assignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.NETWORK,sdncRequest.getTopology());
- }
+ @Test
+ public void assignNetworkTest() throws Exception {
+ doReturn(new GenericResourceApiNetworkOperationInformation()).when(sdncNetworkResources).assignNetwork(network,
+ serviceInstance, customer, requestContext, cloudRegion);
+ sdncAssignTasks.assignNetwork(execution);
+ verify(sdncNetworkResources, times(1)).assignNetwork(network, serviceInstance, customer, requestContext,
+ cloudRegion);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.NETWORK, sdncRequest.getTopology());
+ }
- @Test
- public void assignNetworkExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncNetworkResources).assignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- sdncAssignTasks.assignNetwork(execution);
- }
+ @Test
+ public void assignNetworkExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncNetworkResources).assignNetwork(network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ sdncAssignTasks.assignNetwork(execution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java
index be792115c9..1c1616a472 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java
@@ -27,7 +27,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -48,61 +47,70 @@ import org.onap.so.client.exception.BBObjectNotFoundException;
import org.onap.so.client.sdnc.beans.SDNCRequest;
import org.onap.so.client.sdnc.endpoint.SDNCTopology;
-public class SDNCChangeAssignTasksTest extends BaseTaskTest{
- @InjectMocks
- private SDNCChangeAssignTasks sdncChangeAssignTasks = new SDNCChangeAssignTasks();
-
- private ServiceInstance serviceInstance;
- private RequestContext requestContext;
- private CloudRegion cloudRegion;
- private VfModule vfModule;
- private GenericVnf genericVnf;
- private Customer customer;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- customer = setCustomer();
- serviceInstance = setServiceInstance();
- genericVnf = setGenericVnf();
- vfModule = setVfModule();
- cloudRegion = setCloudRegion();
- requestContext = setRequestContext();
+public class SDNCChangeAssignTasksTest extends BaseTaskTest {
+ @InjectMocks
+ private SDNCChangeAssignTasks sdncChangeAssignTasks = new SDNCChangeAssignTasks();
+
+ private ServiceInstance serviceInstance;
+ private RequestContext requestContext;
+ private CloudRegion cloudRegion;
+ private VfModule vfModule;
+ private GenericVnf genericVnf;
+ private Customer customer;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ customer = setCustomer();
+ serviceInstance = setServiceInstance();
+ genericVnf = setGenericVnf();
+ vfModule = setVfModule();
+ cloudRegion = setCloudRegion();
+ requestContext = setRequestContext();
+
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ }
+
+ @Test
+ public void changeModelVnfTest() throws Exception {
+ doReturn(new GenericResourceApiVnfOperationInformation()).when(sdncVnfResources).changeModelVnf(genericVnf,
+ serviceInstance, customer, cloudRegion, requestContext);
+ sdncChangeAssignTasks.changeModelVnf(execution);
+ verify(sdncVnfResources, times(1)).changeModelVnf(genericVnf, serviceInstance, customer, cloudRegion,
+ requestContext);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.VNF, sdncRequest.getTopology());
+ }
+
+ @Test
+ public void changeModelVnfExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncVnfResources).changeModelVnf(genericVnf, serviceInstance, customer,
+ cloudRegion, requestContext);
+ sdncChangeAssignTasks.changeModelVnf(execution);
+ }
+
+ @Test
+ public void changeAssignModelVfModuleTest() throws Exception {
+ doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources)
+ .changeAssignVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
+ sdncChangeAssignTasks.changeAssignModelVfModule(execution);
+ verify(sdncVfModuleResources, times(1)).changeAssignVfModule(vfModule, genericVnf, serviceInstance, customer,
+ cloudRegion, requestContext);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.VFMODULE, sdncRequest.getTopology());
+ }
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- }
-
- @Test
- public void changeModelVnfTest() throws Exception {
- doReturn(new GenericResourceApiVnfOperationInformation()).when(sdncVnfResources).changeModelVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncChangeAssignTasks.changeModelVnf(execution);
- verify(sdncVnfResources, times(1)).changeModelVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.VNF,sdncRequest.getTopology());
- }
-
- @Test
- public void changeModelVnfExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncVnfResources).changeModelVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncChangeAssignTasks.changeModelVnf(execution);
- }
-
- @Test
- public void changeAssignModelVfModuleTest() throws Exception {
- doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources).changeAssignVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncChangeAssignTasks.changeAssignModelVfModule(execution);
- verify(sdncVfModuleResources, times(1)).changeAssignVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.VFMODULE,sdncRequest.getTopology());
- }
-
- @Test
- public void changeAssignModelVfModuleExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncVfModuleResources).changeAssignVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncChangeAssignTasks.changeAssignModelVfModule(execution);
- }
+ @Test
+ public void changeAssignModelVfModuleExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncVfModuleResources).changeAssignVfModule(vfModule, genericVnf,
+ serviceInstance, customer, cloudRegion, requestContext);
+ sdncChangeAssignTasks.changeAssignModelVfModule(execution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java
index 18048da50d..08d4d196da 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java
@@ -28,7 +28,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -53,97 +52,113 @@ import org.onap.so.client.sdnc.beans.SDNCRequest;
import org.onap.so.client.sdnc.endpoint.SDNCTopology;
public class SDNCDeactivateTaskTest extends BaseTaskTest {
- @InjectMocks
- private SDNCDeactivateTasks sdncDeactivateTasks = new SDNCDeactivateTasks();
-
- private ServiceInstance serviceInstance;
- private CloudRegion cloudRegion;
- private RequestContext requestContext;
- private GenericVnf genericVnf;
- private VfModule vfModule;
- private L3Network network;
- private Customer customer;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- customer = setCustomer();
- serviceInstance = setServiceInstance();
- cloudRegion = setCloudRegion();
- requestContext = setRequestContext();
- genericVnf = setGenericVnf();
- vfModule = setVfModule();
- network = setL3Network();
-
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
+ @InjectMocks
+ private SDNCDeactivateTasks sdncDeactivateTasks = new SDNCDeactivateTasks();
+
+ private ServiceInstance serviceInstance;
+ private CloudRegion cloudRegion;
+ private RequestContext requestContext;
+ private GenericVnf genericVnf;
+ private VfModule vfModule;
+ private L3Network network;
+ private Customer customer;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ customer = setCustomer();
+ serviceInstance = setServiceInstance();
+ cloudRegion = setCloudRegion();
+ requestContext = setRequestContext();
+ genericVnf = setGenericVnf();
+ vfModule = setVfModule();
+ network = setL3Network();
+
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+
+ }
+
+ @Test
+ public void deactivateVfModuleTest() throws Exception {
+ doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources)
+ .deactivateVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
+ sdncDeactivateTasks.deactivateVfModule(execution);
+ verify(sdncVfModuleResources, times(1)).deactivateVfModule(vfModule, genericVnf, serviceInstance, customer,
+ cloudRegion, requestContext);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.VFMODULE, sdncRequest.getTopology());
+ }
+
+ @Test
+ public void deactivateVfModuleExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncVfModuleResources).deactivateVfModule(vfModule, genericVnf,
+ serviceInstance, customer, cloudRegion, requestContext);
+ sdncDeactivateTasks.deactivateVfModule(execution);
+ }
+
+ @Test
+ public void deactivateVnfTest() throws Exception {
+ doReturn(new GenericResourceApiVnfOperationInformation()).when(sdncVnfResources).deactivateVnf(genericVnf,
+ serviceInstance, customer, cloudRegion, requestContext);
+ sdncDeactivateTasks.deactivateVnf(execution);
+ verify(sdncVnfResources, times(1)).deactivateVnf(genericVnf, serviceInstance, customer, cloudRegion,
+ requestContext);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.VNF, sdncRequest.getTopology());
+ }
+
+ @Test
+ public void deactivateVnfExceptionTest() throws Exception {
+ doThrow(RuntimeException.class).when(sdncVnfResources).deactivateVnf(genericVnf, serviceInstance, customer,
+ cloudRegion, requestContext);
+ expectedException.expect(BpmnError.class);
+ sdncDeactivateTasks.deactivateVnf(execution);
+ }
+
+ @Test
+ public void deactivateServiceInstanceTest() throws Exception {
+ doReturn(new GenericResourceApiServiceOperationInformation()).when(sdncServiceInstanceResources)
+ .deactivateServiceInstance(serviceInstance, customer, requestContext);
+ sdncDeactivateTasks.deactivateServiceInstance(execution);
+ verify(sdncServiceInstanceResources, times(1)).deactivateServiceInstance(serviceInstance, customer,
+ requestContext);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.SERVICE, sdncRequest.getTopology());
+ }
+
+ @Test
+ public void deactivateServiceInstanceExceptionTest() throws Exception {
+ doThrow(RuntimeException.class).when(sdncServiceInstanceResources).deactivateServiceInstance(serviceInstance,
+ customer, requestContext);
+ expectedException.expect(BpmnError.class);
+ sdncDeactivateTasks.deactivateServiceInstance(execution);
+ }
+
+ @Test
+ public void test_deactivateNetwork() throws Exception {
+ doReturn(new GenericResourceApiNetworkOperationInformation()).when(sdncNetworkResources)
+ .deactivateNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
+ sdncDeactivateTasks.deactivateNetwork(execution);
+ verify(sdncNetworkResources, times(1)).deactivateNetwork(network, serviceInstance, customer, requestContext,
+ cloudRegion);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.NETWORK, sdncRequest.getTopology());
+ }
- }
-
- @Test
- public void deactivateVfModuleTest() throws Exception {
- doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources).deactivateVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncDeactivateTasks.deactivateVfModule(execution);
- verify(sdncVfModuleResources, times(1)).deactivateVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.VFMODULE,sdncRequest.getTopology());
- }
-
- @Test
- public void deactivateVfModuleExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncVfModuleResources).deactivateVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncDeactivateTasks.deactivateVfModule(execution);
- }
-
- @Test
- public void deactivateVnfTest() throws Exception {
- doReturn(new GenericResourceApiVnfOperationInformation()).when(sdncVnfResources).deactivateVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncDeactivateTasks.deactivateVnf(execution);
- verify(sdncVnfResources, times(1)).deactivateVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.VNF,sdncRequest.getTopology());
- }
-
- @Test
- public void deactivateVnfExceptionTest() throws Exception {
- doThrow(RuntimeException.class).when(sdncVnfResources).deactivateVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- expectedException.expect(BpmnError.class);
- sdncDeactivateTasks.deactivateVnf(execution);
- }
-
- @Test
- public void deactivateServiceInstanceTest() throws Exception {
- doReturn(new GenericResourceApiServiceOperationInformation()).when(sdncServiceInstanceResources).deactivateServiceInstance(serviceInstance, customer, requestContext);
- sdncDeactivateTasks.deactivateServiceInstance(execution);
- verify(sdncServiceInstanceResources, times(1)).deactivateServiceInstance(serviceInstance, customer, requestContext);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.SERVICE,sdncRequest.getTopology());
- }
-
- @Test
- public void deactivateServiceInstanceExceptionTest() throws Exception {
- doThrow(RuntimeException.class).when(sdncServiceInstanceResources).deactivateServiceInstance(serviceInstance, customer, requestContext);
- expectedException.expect(BpmnError.class);
- sdncDeactivateTasks.deactivateServiceInstance(execution);
- }
-
- @Test
- public void test_deactivateNetwork() throws Exception {
- doReturn(new GenericResourceApiNetworkOperationInformation()).when(sdncNetworkResources).deactivateNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- sdncDeactivateTasks.deactivateNetwork(execution);
- verify(sdncNetworkResources, times(1)).deactivateNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.NETWORK,sdncRequest.getTopology());
- }
-
- @Test
- public void test_deactivateNetwork_exception() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID));
- sdncDeactivateTasks.deactivateNetwork(execution);
- verify(sdncNetworkResources, times(0)).deactivateNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- }
+ @Test
+ public void test_deactivateNetwork_exception() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),
+ ArgumentMatchers.eq(ResourceKey.NETWORK_ID));
+ sdncDeactivateTasks.deactivateNetwork(execution);
+ verify(sdncNetworkResources, times(0)).deactivateNetwork(network, serviceInstance, customer, requestContext,
+ cloudRegion);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasksTest.java
index 28551baa7a..3ea8474b24 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasksTest.java
@@ -29,7 +29,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Rule;
@@ -45,95 +44,99 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule;
import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
import org.onap.so.client.exception.BBObjectNotFoundException;
-public class SDNCQueryTasksTest extends BaseTaskTest{
- @InjectMocks
- private SDNCQueryTasks sdncQueryTasks = new SDNCQueryTasks();
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- private ServiceInstance serviceInstance;
- private GenericVnf genericVnf;
- private VfModule vfModule;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- serviceInstance = setServiceInstance();
- genericVnf = setGenericVnf();
- vfModule = setVfModule();
-
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
-
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
-
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
-
- }
-
- @Test
- public void queryVfModuleTest() throws Exception {
- String sdncQueryResponse = "response";
- vfModule.setSelflink("vfModuleSelfLink");
-
- doReturn(sdncQueryResponse).when(sdncVfModuleResources).queryVfModule(vfModule);
-
- assertNotEquals(sdncQueryResponse, execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId()));
- sdncQueryTasks.queryVfModule(execution);
- assertEquals(sdncQueryResponse, execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId()));
-
- verify(sdncVfModuleResources, times(1)).queryVfModule(vfModule);
- }
-
- @Test
- public void queryVnfTest() throws Exception {
- String sdncQueryResponse = "response";
-
- doReturn(sdncQueryResponse).when(sdncVnfResources).queryVnf(genericVnf);
-
- assertNotEquals(sdncQueryResponse, execution.getVariable("SDNCQueryResponse_" + genericVnf.getVnfId()));
- sdncQueryTasks.queryVnf(execution);
- assertEquals(sdncQueryResponse, execution.getVariable("SDNCQueryResponse_" + genericVnf.getVnfId()));
-
- verify(sdncVnfResources, times(1)).queryVnf(genericVnf);
- }
-
- @Test
- public void queryVfModuleForVolumeGroupTest() throws Exception {
- String sdncQueryResponse = "response";
- vfModule.setSelflink("vfModuleSelfLink");
-
- doReturn(sdncQueryResponse).when(sdncVfModuleResources).queryVfModule(vfModule);
-
- assertNotEquals(sdncQueryResponse, execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId()));
- sdncQueryTasks.queryVfModuleForVolumeGroup(execution);
- assertEquals(sdncQueryResponse, execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId()));
-
- verify(sdncVfModuleResources, times(1)).queryVfModule(vfModule);
- }
-
- @Test
- public void queryVfModuleForVolumeGroupNoSelfLinkExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- vfModule.setSelflink("");
-
- sdncQueryTasks.queryVfModuleForVolumeGroup(execution);
- }
-
- @Test
- public void queryVfModuleForVolumeGroupVfObjectExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID));
- sdncQueryTasks.queryVfModuleForVolumeGroup(execution);
-
- verify(sdncVfModuleResources, times(0)).queryVfModule(any(VfModule.class));
- }
-
- @Test
- public void queryVfModuleForVolumeGroupNonVfObjectExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
-
- sdncQueryTasks.queryVfModuleForVolumeGroup(execution);
- }
+public class SDNCQueryTasksTest extends BaseTaskTest {
+ @InjectMocks
+ private SDNCQueryTasks sdncQueryTasks = new SDNCQueryTasks();
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ private ServiceInstance serviceInstance;
+ private GenericVnf genericVnf;
+ private VfModule vfModule;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ serviceInstance = setServiceInstance();
+ genericVnf = setGenericVnf();
+ vfModule = setVfModule();
+
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+
+ }
+
+ @Test
+ public void queryVfModuleTest() throws Exception {
+ String sdncQueryResponse = "response";
+ vfModule.setSelflink("vfModuleSelfLink");
+
+ doReturn(sdncQueryResponse).when(sdncVfModuleResources).queryVfModule(vfModule);
+
+ assertNotEquals(sdncQueryResponse, execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId()));
+ sdncQueryTasks.queryVfModule(execution);
+ assertEquals(sdncQueryResponse, execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId()));
+
+ verify(sdncVfModuleResources, times(1)).queryVfModule(vfModule);
+ }
+
+ @Test
+ public void queryVnfTest() throws Exception {
+ String sdncQueryResponse = "response";
+
+ doReturn(sdncQueryResponse).when(sdncVnfResources).queryVnf(genericVnf);
+
+ assertNotEquals(sdncQueryResponse, execution.getVariable("SDNCQueryResponse_" + genericVnf.getVnfId()));
+ sdncQueryTasks.queryVnf(execution);
+ assertEquals(sdncQueryResponse, execution.getVariable("SDNCQueryResponse_" + genericVnf.getVnfId()));
+
+ verify(sdncVnfResources, times(1)).queryVnf(genericVnf);
+ }
+
+ @Test
+ public void queryVfModuleForVolumeGroupTest() throws Exception {
+ String sdncQueryResponse = "response";
+ vfModule.setSelflink("vfModuleSelfLink");
+
+ doReturn(sdncQueryResponse).when(sdncVfModuleResources).queryVfModule(vfModule);
+
+ assertNotEquals(sdncQueryResponse, execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId()));
+ sdncQueryTasks.queryVfModuleForVolumeGroup(execution);
+ assertEquals(sdncQueryResponse, execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId()));
+
+ verify(sdncVfModuleResources, times(1)).queryVfModule(vfModule);
+ }
+
+ @Test
+ public void queryVfModuleForVolumeGroupNoSelfLinkExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ vfModule.setSelflink("");
+
+ sdncQueryTasks.queryVfModuleForVolumeGroup(execution);
+ }
+
+ @Test
+ public void queryVfModuleForVolumeGroupVfObjectExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),
+ ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID));
+ sdncQueryTasks.queryVfModuleForVolumeGroup(execution);
+
+ verify(sdncVfModuleResources, times(0)).queryVfModule(any(VfModule.class));
+ }
+
+ @Test
+ public void queryVfModuleForVolumeGroupNonVfObjectExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ sdncQueryTasks.queryVfModuleForVolumeGroup(execution);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java
index 043aad43b1..b5d34ea4c9 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java
@@ -25,18 +25,14 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
-
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
import org.junit.Before;
import org.junit.Rule;
@@ -57,128 +53,133 @@ import org.onap.so.client.sdnc.beans.SDNCRequest;
import org.onap.so.client.sdnc.endpoint.SDNCTopology;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(MockitoJUnitRunner.class)
-public class SDNCRequestTasksTest extends SDNCRequestTasks{
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @InjectMocks
- SDNCRequestTasks sndcRequestTasks = new SDNCRequestTasks();
-
- @Mock
- SDNCClient sdncClient;
-
- @Spy
- private ExceptionBuilder exceptionBuilder;
-
- protected DelegateExecution delegateExecution;
-
-
- @Before
- public void setup(){
- delegateExecution = new DelegateExecutionFake();
- delegateExecution.setVariable("SDNCRequest", createSDNCRequest());
- }
-
- @Test
- public void createCorrelationVariables_Test(){
- sndcRequestTasks.createCorrelationVariables(delegateExecution);
- assertEquals("correlationValue",delegateExecution.getVariable("correlationName_CORRELATOR"));
- }
-
- @Test
- public void callSDNC_Final_Test() throws MapperException, BadResponseException, IOException{
- final String sdncResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNCClientPut200Response.json")));
- doReturn(sdncResponse).when(sdncClient).post(createSDNCRequest().getSDNCPayload(),SDNCTopology.CONFIGURATION);
- sndcRequestTasks.callSDNC(delegateExecution);
- assertEquals(true,delegateExecution.getVariable("isSDNCCompleted"));
- }
-
- @Test
- public void callSDNC_Not_Final_Test() throws MapperException, BadResponseException, IOException{
- final String sdncResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNCClientPut200ResponseNotFinal.json")));
- doReturn(sdncResponse).when(sdncClient).post(createSDNCRequest().getSDNCPayload(),SDNCTopology.CONFIGURATION);
- sndcRequestTasks.callSDNC(delegateExecution);
- assertEquals(false,delegateExecution.getVariable("isSDNCCompleted"));
- }
-
- @Test
- public void callSDNC_Error_Test() throws MapperException, BadResponseException{
- doThrow(MapperException.class).when(sdncClient).post(createSDNCRequest().getSDNCPayload(),SDNCTopology.CONFIGURATION);
- doReturn("processKey").when(exceptionBuilder).getProcessKey(delegateExecution);
- expectedException.expect(BpmnError.class);
- sndcRequestTasks.callSDNC(delegateExecution);
- }
-
- @Test
- public void convertIndicatorToBoolean_True_Test() throws MapperException, BadResponseException{
- boolean testValue = sndcRequestTasks.convertIndicatorToBoolean("Y");
- assertEquals(true,testValue);
- }
-
- @Test
- public void convertIndicatorToBoolean_False_Test() throws MapperException, BadResponseException{
- boolean testValue = sndcRequestTasks.convertIndicatorToBoolean("N");
- assertEquals(false,testValue);
- }
-
- @Test
- public void HandleTimeout_Test() throws MapperException, BadResponseException{
- doReturn("processKey").when(exceptionBuilder).getProcessKey(delegateExecution);
- expectedException.expect(BpmnError.class);
- sndcRequestTasks.handleTimeOutException(delegateExecution);
- }
-
- @Test
- public void processCallBack_Final_Test() throws MapperException, BadResponseException, IOException{
- final String sdncResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNC_Async_Request2.xml")));
- delegateExecution.setVariable("correlationName_MESSAGE", sdncResponse);
- sndcRequestTasks.processCallback(delegateExecution);
- assertEquals(true,delegateExecution.getVariable(IS_CALLBACK_COMPLETED));
- }
-
- @Test
- public void getXmlElementTest() throws Exception {
- final String sdncResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNC_Async_Request2.xml")));
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();
+public class SDNCRequestTasksTest extends SDNCRequestTasks {
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @InjectMocks
+ SDNCRequestTasks sndcRequestTasks = new SDNCRequestTasks();
+
+ @Mock
+ SDNCClient sdncClient;
+
+ @Spy
+ private ExceptionBuilder exceptionBuilder;
+
+ protected DelegateExecution delegateExecution;
+
+
+ @Before
+ public void setup() {
+ delegateExecution = new DelegateExecutionFake();
+ delegateExecution.setVariable("SDNCRequest", createSDNCRequest());
+ }
+
+ @Test
+ public void createCorrelationVariables_Test() {
+ sndcRequestTasks.createCorrelationVariables(delegateExecution);
+ assertEquals("correlationValue", delegateExecution.getVariable("correlationName_CORRELATOR"));
+ }
+
+ @Test
+ public void callSDNC_Final_Test() throws MapperException, BadResponseException, IOException {
+ final String sdncResponse =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNCClientPut200Response.json")));
+ doReturn(sdncResponse).when(sdncClient).post(createSDNCRequest().getSDNCPayload(), SDNCTopology.CONFIGURATION);
+ sndcRequestTasks.callSDNC(delegateExecution);
+ assertEquals(true, delegateExecution.getVariable("isSDNCCompleted"));
+ }
+
+ @Test
+ public void callSDNC_Not_Final_Test() throws MapperException, BadResponseException, IOException {
+ final String sdncResponse = new String(
+ Files.readAllBytes(Paths.get("src/test/resources/__files/SDNCClientPut200ResponseNotFinal.json")));
+ doReturn(sdncResponse).when(sdncClient).post(createSDNCRequest().getSDNCPayload(), SDNCTopology.CONFIGURATION);
+ sndcRequestTasks.callSDNC(delegateExecution);
+ assertEquals(false, delegateExecution.getVariable("isSDNCCompleted"));
+ }
+
+ @Test
+ public void callSDNC_Error_Test() throws MapperException, BadResponseException {
+ doThrow(MapperException.class).when(sdncClient).post(createSDNCRequest().getSDNCPayload(),
+ SDNCTopology.CONFIGURATION);
+ doReturn("processKey").when(exceptionBuilder).getProcessKey(delegateExecution);
+ expectedException.expect(BpmnError.class);
+ sndcRequestTasks.callSDNC(delegateExecution);
+ }
+
+ @Test
+ public void convertIndicatorToBoolean_True_Test() throws MapperException, BadResponseException {
+ boolean testValue = sndcRequestTasks.convertIndicatorToBoolean("Y");
+ assertEquals(true, testValue);
+ }
+
+ @Test
+ public void convertIndicatorToBoolean_False_Test() throws MapperException, BadResponseException {
+ boolean testValue = sndcRequestTasks.convertIndicatorToBoolean("N");
+ assertEquals(false, testValue);
+ }
+
+ @Test
+ public void HandleTimeout_Test() throws MapperException, BadResponseException {
+ doReturn("processKey").when(exceptionBuilder).getProcessKey(delegateExecution);
+ expectedException.expect(BpmnError.class);
+ sndcRequestTasks.handleTimeOutException(delegateExecution);
+ }
+
+ @Test
+ public void processCallBack_Final_Test() throws MapperException, BadResponseException, IOException {
+ final String sdncResponse =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNC_Async_Request2.xml")));
+ delegateExecution.setVariable("correlationName_MESSAGE", sdncResponse);
+ sndcRequestTasks.processCallback(delegateExecution);
+ assertEquals(true, delegateExecution.getVariable(IS_CALLBACK_COMPLETED));
+ }
+
+ @Test
+ public void getXmlElementTest() throws Exception {
+ final String sdncResponse =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNC_Async_Request2.xml")));
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
- db = dbf.newDocumentBuilder ();
- Document doc = db.parse (new InputSource(new StringReader(sdncResponse)));
-
+ db = dbf.newDocumentBuilder();
+ Document doc = db.parse(new InputSource(new StringReader(sdncResponse)));
+
String finalMessageIndicator = getXmlElement(doc, "/input/ack-final-indicator");
String responseCode = getXmlElement(doc, "/input/response-code");
- String responseMessage = getXmlElement(doc, "/input/response-message");
-
- assertEquals("Y", finalMessageIndicator);
- assertEquals("200", responseCode);
- assertEquals("Success", responseMessage);
- }
-
- public SDNCRequest createSDNCRequest(){
- SDNCRequest request = new SDNCRequest();
- request.setCorrelationName("correlationName");
- request.setCorrelationValue("correlationValue");
- request.setTopology(SDNCTopology.CONFIGURATION);
- ObjectMapper mapper = new ObjectMapper();
- try {
- GenericResourceApiServiceOperationInformation sdncReq =
- mapper.readValue(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNC_Client_Request.json")), GenericResourceApiServiceOperationInformation.class);
- request.setSDNCPayload(sdncReq);
- } catch (JsonParseException e) {
-
- } catch (JsonMappingException e) {
-
- } catch (IOException e) {
-
- }
-
- return request;
- }
-
+ String responseMessage = getXmlElement(doc, "/input/response-message");
+
+ assertEquals("Y", finalMessageIndicator);
+ assertEquals("200", responseCode);
+ assertEquals("Success", responseMessage);
+ }
+
+ public SDNCRequest createSDNCRequest() {
+ SDNCRequest request = new SDNCRequest();
+ request.setCorrelationName("correlationName");
+ request.setCorrelationValue("correlationValue");
+ request.setTopology(SDNCTopology.CONFIGURATION);
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ GenericResourceApiServiceOperationInformation sdncReq = mapper.readValue(
+ Files.readAllBytes(Paths.get("src/test/resources/__files/SDNC_Client_Request.json")),
+ GenericResourceApiServiceOperationInformation.class);
+ request.setSDNCPayload(sdncReq);
+ } catch (JsonParseException e) {
+
+ } catch (JsonMappingException e) {
+
+ } catch (IOException e) {
+
+ }
+
+ return request;
+ }
+
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java
index 527fe0d916..c6ed1cca7a 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java
@@ -30,7 +30,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -54,99 +53,111 @@ import org.onap.so.client.exception.BBObjectNotFoundException;
import org.onap.so.client.sdnc.beans.SDNCRequest;
import org.onap.so.client.sdnc.endpoint.SDNCTopology;
-public class SDNCUnassignTasksTest extends BaseTaskTest{
- @InjectMocks
- private SDNCUnassignTasks sdncUnassignTasks = new SDNCUnassignTasks();
-
- private ServiceInstance serviceInstance;
- private RequestContext requestContext;
- private GenericVnf genericVnf;
- private VfModule vfModule;
- private CloudRegion cloudRegion;
- private L3Network network;
- private Customer customer;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- customer = setCustomer();
- serviceInstance = setServiceInstance();
- requestContext = setRequestContext();
- genericVnf = setGenericVnf();
- vfModule = setVfModule();
- cloudRegion = setCloudRegion();
- network = setL3Network();
- doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
- when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance);
- }
-
- @Test
- public void unassignServiceInstanceTest() throws Exception {
- doReturn(new GenericResourceApiServiceOperationInformation()).when(sdncServiceInstanceResources).unassignServiceInstance(serviceInstance, customer, requestContext);
- sdncUnassignTasks.unassignServiceInstance(execution);
- verify(sdncServiceInstanceResources, times(1)).unassignServiceInstance(serviceInstance, customer, requestContext);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.SERVICE,sdncRequest.getTopology());
- }
-
-
-
- @Test
- public void unassignServiceInstanceExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncServiceInstanceResources).unassignServiceInstance(serviceInstance, customer, requestContext);
- sdncUnassignTasks.unassignServiceInstance(execution);
- }
-
- @Test
- public void unassignVfModuleTest() throws Exception {
- doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources).unassignVfModule(vfModule, genericVnf, serviceInstance);
- sdncUnassignTasks.unassignVfModule(execution);
- verify(sdncVfModuleResources, times(1)).unassignVfModule(vfModule, genericVnf, serviceInstance);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.VFMODULE,sdncRequest.getTopology());
- }
-
-
-
-
- @Test
- public void unassignVfModuleExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncVfModuleResources).unassignVfModule(vfModule, genericVnf, serviceInstance);
- sdncUnassignTasks.unassignVfModule(execution);
- }
-
- @Test
- public void unassignVnfTest() throws Exception {
- doReturn(new GenericResourceApiVnfOperationInformation()).when(sdncVnfResources).unassignVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncUnassignTasks.unassignVnf(execution);
- verify(sdncVnfResources, times(1)).unassignVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.VNF,sdncRequest.getTopology());
- }
-
-
- @Test
- public void unassignVnfExceptionTest() throws Exception {
- expectedException.expect(BpmnError.class);
- doThrow(RuntimeException.class).when(sdncVnfResources).unassignVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- sdncUnassignTasks.unassignVnf(execution);
- }
-
- @Test
- public void unassignNetworkTest() throws Exception {
- String cloudRegionSdnc = "AAIAIC25";
- cloudRegion.setCloudRegionVersion("2.5");
- execution.setVariable("cloudRegionSdnc", cloudRegionSdnc);
- doReturn(new GenericResourceApiNetworkOperationInformation()).when(sdncNetworkResources).unassignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- assertNotEquals(cloudRegionSdnc, cloudRegion.getLcpCloudRegionId());
- sdncUnassignTasks.unassignNetwork(execution);
- verify(sdncNetworkResources, times(1)).unassignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- assertEquals(cloudRegionSdnc, cloudRegion.getLcpCloudRegionId());
- SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
- assertEquals(SDNCTopology.NETWORK,sdncRequest.getTopology());
- }
+public class SDNCUnassignTasksTest extends BaseTaskTest {
+ @InjectMocks
+ private SDNCUnassignTasks sdncUnassignTasks = new SDNCUnassignTasks();
+
+ private ServiceInstance serviceInstance;
+ private RequestContext requestContext;
+ private GenericVnf genericVnf;
+ private VfModule vfModule;
+ private CloudRegion cloudRegion;
+ private L3Network network;
+ private Customer customer;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ customer = setCustomer();
+ serviceInstance = setServiceInstance();
+ requestContext = setRequestContext();
+ genericVnf = setGenericVnf();
+ vfModule = setVfModule();
+ cloudRegion = setCloudRegion();
+ network = setL3Network();
+ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class));
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)))
+ .thenReturn(genericVnf);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule);
+ when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)))
+ .thenReturn(serviceInstance);
+ }
+
+ @Test
+ public void unassignServiceInstanceTest() throws Exception {
+ doReturn(new GenericResourceApiServiceOperationInformation()).when(sdncServiceInstanceResources)
+ .unassignServiceInstance(serviceInstance, customer, requestContext);
+ sdncUnassignTasks.unassignServiceInstance(execution);
+ verify(sdncServiceInstanceResources, times(1)).unassignServiceInstance(serviceInstance, customer,
+ requestContext);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.SERVICE, sdncRequest.getTopology());
+ }
+
+
+
+ @Test
+ public void unassignServiceInstanceExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncServiceInstanceResources).unassignServiceInstance(serviceInstance,
+ customer, requestContext);
+ sdncUnassignTasks.unassignServiceInstance(execution);
+ }
+
+ @Test
+ public void unassignVfModuleTest() throws Exception {
+ doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources)
+ .unassignVfModule(vfModule, genericVnf, serviceInstance);
+ sdncUnassignTasks.unassignVfModule(execution);
+ verify(sdncVfModuleResources, times(1)).unassignVfModule(vfModule, genericVnf, serviceInstance);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.VFMODULE, sdncRequest.getTopology());
+ }
+
+
+
+ @Test
+ public void unassignVfModuleExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncVfModuleResources).unassignVfModule(vfModule, genericVnf,
+ serviceInstance);
+ sdncUnassignTasks.unassignVfModule(execution);
+ }
+
+ @Test
+ public void unassignVnfTest() throws Exception {
+ doReturn(new GenericResourceApiVnfOperationInformation()).when(sdncVnfResources).unassignVnf(genericVnf,
+ serviceInstance, customer, cloudRegion, requestContext);
+ sdncUnassignTasks.unassignVnf(execution);
+ verify(sdncVnfResources, times(1)).unassignVnf(genericVnf, serviceInstance, customer, cloudRegion,
+ requestContext);
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.VNF, sdncRequest.getTopology());
+ }
+
+
+ @Test
+ public void unassignVnfExceptionTest() throws Exception {
+ expectedException.expect(BpmnError.class);
+ doThrow(RuntimeException.class).when(sdncVnfResources).unassignVnf(genericVnf, serviceInstance, customer,
+ cloudRegion, requestContext);
+ sdncUnassignTasks.unassignVnf(execution);
+ }
+
+ @Test
+ public void unassignNetworkTest() throws Exception {
+ String cloudRegionSdnc = "AAIAIC25";
+ cloudRegion.setCloudRegionVersion("2.5");
+ execution.setVariable("cloudRegionSdnc", cloudRegionSdnc);
+ doReturn(new GenericResourceApiNetworkOperationInformation()).when(sdncNetworkResources)
+ .unassignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
+ assertNotEquals(cloudRegionSdnc, cloudRegion.getLcpCloudRegionId());
+ sdncUnassignTasks.unassignNetwork(execution);
+ verify(sdncNetworkResources, times(1)).unassignNetwork(network, serviceInstance, customer, requestContext,
+ cloudRegion);
+ assertEquals(cloudRegionSdnc, cloudRegion.getLcpCloudRegionId());
+ SDNCRequest sdncRequest = execution.getVariable("SDNCRequest");
+ assertEquals(SDNCTopology.NETWORK, sdncRequest.getTopology());
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidatorTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidatorTest.java
index 81ec388649..2fc3cf639c 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidatorTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidatorTest.java
@@ -27,7 +27,6 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import java.util.Optional;
import java.util.Set;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.so.bpmn.common.BuildingBlockExecution;
@@ -35,83 +34,84 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
public class CloudRegionOrchestrationValidatorTest {
-
- private BuildingBlockExecution mockExecution;
- private CloudRegion cloudRegion;
-
- @Before
- public void setUp() {
- cloudRegion = new CloudRegion();
- cloudRegion.setCloudOwner("CloudOwner");
- cloudRegion.setLcpCloudRegionId("my-region-id");
- GeneralBuildingBlock gbb = new GeneralBuildingBlock();
- gbb.setCloudRegion(cloudRegion);
- mockExecution = mock(BuildingBlockExecution.class);
- doReturn(gbb).when(mockExecution).getGeneralBuildingBlock();
- }
-
- @Test
- public void validateDisabledTest() {
- cloudRegion.setOrchestrationDisabled(true);
- CloudRegionOrchestrationValidator validation = new CloudRegionOrchestrationValidator();
- Optional<String> result = validation.validate(mockExecution);
- assertEquals("Error: The request has failed due to orchestration currently disabled for the target cloud region my-region-id for cloud owner CloudOwner",
- result.get());
- }
-
- @Test
- public void validateNotDisabledTest() {
- cloudRegion.setOrchestrationDisabled(false);
- CloudRegionOrchestrationValidator validation = new CloudRegionOrchestrationValidator();
- Optional<String> result = validation.validate(mockExecution);
- assertFalse(result.isPresent());
- }
-
- @Test
- public void validateDisabledIsNullTest() {
- CloudRegionOrchestrationValidator validation = new CloudRegionOrchestrationValidator();
- Optional<String> result = validation.validate(mockExecution);
- assertFalse(result.isPresent());
- }
- @Test
- public void shouldRunForTest() {
- CloudRegionOrchestrationValidator validator = new CloudRegionOrchestrationValidator();
- assertTrue(validator.shouldRunFor("ActivateNetworkBB"));
- assertTrue(validator.shouldRunFor("AssignNetworkBB"));
- assertTrue(validator.shouldRunFor("CreateNetworkBB"));
- assertTrue(validator.shouldRunFor("DeactivateNetworkBB"));
- assertTrue(validator.shouldRunFor("DeleteNetworkBB"));
- assertTrue(validator.shouldRunFor("UnassignNetworkBB"));
- assertTrue(validator.shouldRunFor("UpdateNetworkBB"));
-
- assertTrue(validator.shouldRunFor("ActivateVnfBB"));
- assertTrue(validator.shouldRunFor("AssignVnfBB"));
- assertTrue(validator.shouldRunFor("UnassignVnfBB"));
- assertTrue(validator.shouldRunFor("DeactivateVnfBB"));
+ private BuildingBlockExecution mockExecution;
+ private CloudRegion cloudRegion;
+
+ @Before
+ public void setUp() {
+ cloudRegion = new CloudRegion();
+ cloudRegion.setCloudOwner("CloudOwner");
+ cloudRegion.setLcpCloudRegionId("my-region-id");
+ GeneralBuildingBlock gbb = new GeneralBuildingBlock();
+ gbb.setCloudRegion(cloudRegion);
+ mockExecution = mock(BuildingBlockExecution.class);
+ doReturn(gbb).when(mockExecution).getGeneralBuildingBlock();
+ }
+
+ @Test
+ public void validateDisabledTest() {
+ cloudRegion.setOrchestrationDisabled(true);
+ CloudRegionOrchestrationValidator validation = new CloudRegionOrchestrationValidator();
+ Optional<String> result = validation.validate(mockExecution);
+ assertEquals(
+ "Error: The request has failed due to orchestration currently disabled for the target cloud region my-region-id for cloud owner CloudOwner",
+ result.get());
+ }
+
+ @Test
+ public void validateNotDisabledTest() {
+ cloudRegion.setOrchestrationDisabled(false);
+ CloudRegionOrchestrationValidator validation = new CloudRegionOrchestrationValidator();
+ Optional<String> result = validation.validate(mockExecution);
+ assertFalse(result.isPresent());
+ }
+
+ @Test
+ public void validateDisabledIsNullTest() {
+ CloudRegionOrchestrationValidator validation = new CloudRegionOrchestrationValidator();
+ Optional<String> result = validation.validate(mockExecution);
+ assertFalse(result.isPresent());
+ }
+
+ @Test
+ public void shouldRunForTest() {
+ CloudRegionOrchestrationValidator validator = new CloudRegionOrchestrationValidator();
+ assertTrue(validator.shouldRunFor("ActivateNetworkBB"));
+ assertTrue(validator.shouldRunFor("AssignNetworkBB"));
+ assertTrue(validator.shouldRunFor("CreateNetworkBB"));
+ assertTrue(validator.shouldRunFor("DeactivateNetworkBB"));
+ assertTrue(validator.shouldRunFor("DeleteNetworkBB"));
+ assertTrue(validator.shouldRunFor("UnassignNetworkBB"));
+ assertTrue(validator.shouldRunFor("UpdateNetworkBB"));
+
+ assertTrue(validator.shouldRunFor("ActivateVnfBB"));
+ assertTrue(validator.shouldRunFor("AssignVnfBB"));
+ assertTrue(validator.shouldRunFor("UnassignVnfBB"));
+ assertTrue(validator.shouldRunFor("DeactivateVnfBB"));
+
+ assertTrue(validator.shouldRunFor("ActivateVfModuleBB"));
+ assertTrue(validator.shouldRunFor("AssignVfModuleBB"));
+ assertTrue(validator.shouldRunFor("CreateVfModuleBB"));
+ assertTrue(validator.shouldRunFor("DeactivateVfModuleBB"));
+ assertTrue(validator.shouldRunFor("DeleteVfModuleBB"));
+ assertTrue(validator.shouldRunFor("UnassignVfModuleBB"));
+
+ assertTrue(validator.shouldRunFor("ActivateVolumeGroupBB"));
+ assertTrue(validator.shouldRunFor("AssignVolumeGroupBB"));
+ assertTrue(validator.shouldRunFor("CreateVolumeGroupBB"));
+ assertTrue(validator.shouldRunFor("DeactivateVolumeGroupBB"));
+ assertTrue(validator.shouldRunFor("DeleteVolumeGroupBB"));
+ assertTrue(validator.shouldRunFor("UnassignVolumeGroupBB"));
+
+ assertTrue(validator.shouldRunFor("ActivateFabricConfigurationBB"));
+ assertTrue(validator.shouldRunFor("AssignFabricConfigurationBB"));
+ assertTrue(validator.shouldRunFor("UnassignFabricConfigurationBB"));
+ assertTrue(validator.shouldRunFor("DeactivateFabricConfigurationBB"));
- assertTrue(validator.shouldRunFor("ActivateVfModuleBB"));
- assertTrue(validator.shouldRunFor("AssignVfModuleBB"));
- assertTrue(validator.shouldRunFor("CreateVfModuleBB"));
- assertTrue(validator.shouldRunFor("DeactivateVfModuleBB"));
- assertTrue(validator.shouldRunFor("DeleteVfModuleBB"));
- assertTrue(validator.shouldRunFor("UnassignVfModuleBB"));
-
- assertTrue(validator.shouldRunFor("ActivateVolumeGroupBB"));
- assertTrue(validator.shouldRunFor("AssignVolumeGroupBB"));
- assertTrue(validator.shouldRunFor("CreateVolumeGroupBB"));
- assertTrue(validator.shouldRunFor("DeactivateVolumeGroupBB"));
- assertTrue(validator.shouldRunFor("DeleteVolumeGroupBB"));
- assertTrue(validator.shouldRunFor("UnassignVolumeGroupBB"));
-
- assertTrue(validator.shouldRunFor("ActivateFabricConfigurationBB"));
- assertTrue(validator.shouldRunFor("AssignFabricConfigurationBB"));
- assertTrue(validator.shouldRunFor("UnassignFabricConfigurationBB"));
- assertTrue(validator.shouldRunFor("DeactivateFabricConfigurationBB"));
-
- assertFalse(validator.shouldRunFor("AssignServiceInstanceBB"));
- assertFalse(validator.shouldRunFor("AAICheckVnfInMaintBB"));
- assertFalse(validator.shouldRunFor("ChangeModelVfModuleBB"));
- assertFalse(validator.shouldRunFor("CreateNetworkCollectionBB"));
- }
+ assertFalse(validator.shouldRunFor("AssignServiceInstanceBB"));
+ assertFalse(validator.shouldRunFor("AAICheckVnfInMaintBB"));
+ assertFalse(validator.shouldRunFor("ChangeModelVfModuleBB"));
+ assertFalse(validator.shouldRunFor("CreateNetworkCollectionBB"));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/FlowCompletionTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/FlowCompletionTasksTest.java
index 3cf003d1ad..1bdde8f904 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/FlowCompletionTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/FlowCompletionTasksTest.java
@@ -26,7 +26,6 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -37,33 +36,33 @@ import org.springframework.beans.factory.annotation.Autowired;
public class FlowCompletionTasksTest extends BaseTaskTest {
- @InjectMocks
- protected FlowCompletionTasks flowCompletionTasks = new FlowCompletionTasks();
+ @InjectMocks
+ protected FlowCompletionTasks flowCompletionTasks = new FlowCompletionTasks();
+
+ @Before
+ public void before() {
+ setRequestContext();
+ }
+
+ @Test
+ public void updateRequestDbStatusComplete_Test() throws Exception {
+ InfraActiveRequests mockedRequest = new InfraActiveRequests();
+ when(requestsDbClient.getInfraActiveRequestbyRequestId(any(String.class))).thenReturn(mockedRequest);
+ doNothing().when(requestsDbClient).updateInfraActiveRequests(any(InfraActiveRequests.class));
+ flowCompletionTasks.updateRequestDbStatus(execution);
+ verify(requestsDbClient, times(1)).updateInfraActiveRequests(any(InfraActiveRequests.class));
+ assertEquals(mockedRequest.getRequestStatus(), "COMPLETE");
+ }
- @Before
- public void before() {
- setRequestContext();
- }
-
- @Test
- public void updateRequestDbStatusComplete_Test() throws Exception{
- InfraActiveRequests mockedRequest = new InfraActiveRequests();
- when(requestsDbClient.getInfraActiveRequestbyRequestId(any(String.class))).thenReturn(mockedRequest);
- doNothing().when(requestsDbClient).updateInfraActiveRequests(any(InfraActiveRequests.class));
- flowCompletionTasks.updateRequestDbStatus(execution);
- verify(requestsDbClient, times(1)).updateInfraActiveRequests(any(InfraActiveRequests.class));
- assertEquals(mockedRequest.getRequestStatus(), "COMPLETE");
- }
-
- @Test
- public void updateRequestDbStatusFailed_Test() throws Exception{
- WorkflowException workflowException = new WorkflowException("testProcessKey", 7000, "Error");
- execution.setVariable("WorkflowException", workflowException);
- InfraActiveRequests mockedRequest = new InfraActiveRequests();
- when(requestsDbClient.getInfraActiveRequestbyRequestId(any(String.class))).thenReturn(mockedRequest);
- doNothing().when(requestsDbClient).updateInfraActiveRequests(any(InfraActiveRequests.class));
- flowCompletionTasks.updateRequestDbStatus(execution);
- verify(requestsDbClient, times(1)).updateInfraActiveRequests(any(InfraActiveRequests.class));
- assertEquals(mockedRequest.getRequestStatus(), "FAILED");
- }
+ @Test
+ public void updateRequestDbStatusFailed_Test() throws Exception {
+ WorkflowException workflowException = new WorkflowException("testProcessKey", 7000, "Error");
+ execution.setVariable("WorkflowException", workflowException);
+ InfraActiveRequests mockedRequest = new InfraActiveRequests();
+ when(requestsDbClient.getInfraActiveRequestbyRequestId(any(String.class))).thenReturn(mockedRequest);
+ doNothing().when(requestsDbClient).updateInfraActiveRequests(any(InfraActiveRequests.class));
+ flowCompletionTasks.updateRequestDbStatus(execution);
+ verify(requestsDbClient, times(1)).updateInfraActiveRequests(any(InfraActiveRequests.class));
+ assertEquals(mockedRequest.getRequestStatus(), "FAILED");
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidatorTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidatorTest.java
index 60d456e2b5..b371e3a48a 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidatorTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidatorTest.java
@@ -26,11 +26,9 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Ignore;
@@ -54,384 +52,434 @@ import org.springframework.beans.factory.annotation.Autowired;
@Ignore
public class OrchestrationStatusValidatorTest extends BaseTaskTest {
- @InjectMocks
- protected OrchestrationStatusValidator orchestrationStatusValidator = new OrchestrationStatusValidator();
-
-
-
- @Test
- public void test_validateOrchestrationStatus() throws Exception {
- String flowToBeCalled = "AssignServiceInstanceBB";
- setServiceInstance().setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("flowToBeCalled", flowToBeCalled);
-
- BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
- buildingBlockDetail.setBuildingBlockName("AssignServiceInstanceBB");
- buildingBlockDetail.setId(1);
- buildingBlockDetail.setResourceType(ResourceType.SERVICE);
- buildingBlockDetail.setTargetAction(OrchestrationAction.ASSIGN);
-
- doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
-
- OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = new OrchestrationStatusStateTransitionDirective();
- orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.CONTINUE);
- orchestrationStatusStateTransitionDirective.setId(1);
- orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.SERVICE);
- orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.ASSIGN);
-
- doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient).getOrchestrationStatusStateTransitionDirective(ResourceType.SERVICE, OrchestrationStatus.PRECREATED, OrchestrationAction.ASSIGN);
-
- orchestrationStatusValidator.validateOrchestrationStatus(execution);
-
- assertEquals(OrchestrationStatusValidationDirective.CONTINUE, execution.getVariable("orchestrationStatusValidationResult"));
- }
-
- @Test
- public void test_validateOrchestrationStatusConfiguration() throws Exception {
- lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId");
- String flowToBeCalled = "UnassignFabricConfigurationBB";
- ServiceInstance si = setServiceInstance();
- List<Configuration> configurations = new ArrayList<>();
- Configuration config = new Configuration();
-
- si.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- config.setConfigurationId("configurationId");
- config.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- configurations.add(config);
- si.setConfigurations(configurations);
-
- execution.setVariable("flowToBeCalled", flowToBeCalled);
- execution.setVariable("aLaCarte", true);
-
- BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
- buildingBlockDetail.setBuildingBlockName("UnassignFabricConfigurationBB");
- buildingBlockDetail.setId(1);
- buildingBlockDetail.setResourceType(ResourceType.CONFIGURATION);
- buildingBlockDetail.setTargetAction(OrchestrationAction.UNASSIGN);
-
- doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
-
- OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = new OrchestrationStatusStateTransitionDirective();
- orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.SILENT_SUCCESS);
- orchestrationStatusStateTransitionDirective.setId(1);
- orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.CONFIGURATION);
- orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.UNASSIGN);
-
- doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient).getOrchestrationStatusStateTransitionDirective(ResourceType.CONFIGURATION, OrchestrationStatus.PRECREATED, OrchestrationAction.UNASSIGN);
-
- orchestrationStatusValidator.validateOrchestrationStatus(execution);
-
- assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS, execution.getVariable("orchestrationStatusValidationResult"));
- }
-
- @Test
- public void test_validateOrchestrationStatus_buildingBlockDetailNotFound() throws Exception {
- expectedException.expect(BpmnError.class);
-
- String flowToBeCalled = "AssignServiceInstanceBB";
-
- execution.setVariable("flowToBeCalled", flowToBeCalled);
-
- doReturn(null).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
-
- orchestrationStatusValidator.validateOrchestrationStatus(execution);
- }
-
- @Test
- public void test_validateOrchestrationStatus_orchestrationValidationFail() throws Exception {
- expectedException.expect(BpmnError.class);
-
- String flowToBeCalled = "AssignServiceInstanceBB";
-
- execution.setVariable("flowToBeCalled", flowToBeCalled);
-
- BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
- buildingBlockDetail.setBuildingBlockName("AssignServiceInstanceBB");
- buildingBlockDetail.setId(1);
- buildingBlockDetail.setResourceType(ResourceType.SERVICE);
- buildingBlockDetail.setTargetAction(OrchestrationAction.ASSIGN);
-
- doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
-
- OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = new OrchestrationStatusStateTransitionDirective();
- orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.FAIL);
- orchestrationStatusStateTransitionDirective.setId(1);
- orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.SERVICE);
- orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.ASSIGN);
-
- doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient).getOrchestrationStatusStateTransitionDirective(ResourceType.SERVICE, OrchestrationStatus.PRECREATED, OrchestrationAction.ASSIGN);
-
- orchestrationStatusValidator.validateOrchestrationStatus(execution);
- }
-
- @Test
- public void test_validateOrchestrationStatus_orchestrationValidationNotFound() throws Exception {
- expectedException.expect(BpmnError.class);
-
- String flowToBeCalled = "AssignServiceInstanceBB";
-
- execution.setVariable("flowToBeCalled", flowToBeCalled);
-
- BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
- buildingBlockDetail.setBuildingBlockName("AssignServiceInstanceBB");
- buildingBlockDetail.setId(1);
- buildingBlockDetail.setResourceType(ResourceType.SERVICE);
- buildingBlockDetail.setTargetAction(OrchestrationAction.ASSIGN);
-
- doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
-
- OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = new OrchestrationStatusStateTransitionDirective();
- orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.FAIL);
- orchestrationStatusStateTransitionDirective.setId(1);
- orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.SERVICE);
- orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.ASSIGN);
-
- doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient).getOrchestrationStatusStateTransitionDirective(ResourceType.NETWORK, OrchestrationStatus.PRECREATED, OrchestrationAction.ASSIGN);
-
- orchestrationStatusValidator.validateOrchestrationStatus(execution);
- }
-
- @Test
- public void test_validateOrchestrationStatus_unassignNotFound() throws Exception{
- String flowToBeCalled = "UnassignServiceInstanceBB";
-
- execution.setVariable("flowToBeCalled", flowToBeCalled);
- execution.setVariable("aLaCarte", true);
-
- BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
- buildingBlockDetail.setBuildingBlockName("UnassignServiceInstanceBB");
- buildingBlockDetail.setId(1);
- buildingBlockDetail.setResourceType(ResourceType.SERVICE);
- buildingBlockDetail.setTargetAction(OrchestrationAction.UNASSIGN);
-
- doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
-
- lookupKeyMap = new HashMap<ResourceKey, String>();
-
- orchestrationStatusValidator.validateOrchestrationStatus(execution);
-
- assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS,execution.getVariable("orchestrationStatusValidationResult"));
- }
-
- @Test
- public void test_validateOrchestrationStatusSecondStageOfMultiStageEnabledVfModule() throws Exception {
- String flowToBeCalled = "CreateVfModuleBB";
-
- execution.setVariable("orchestrationStatusValidationResult", OrchestrationStatusValidationDirective.SILENT_SUCCESS);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("flowToBeCalled", flowToBeCalled);
-
- GenericVnf genericVnf = buildGenericVnf();
- ModelInfoGenericVnf modelInfoGenericVnf = genericVnf.getModelInfoGenericVnf();
- modelInfoGenericVnf.setMultiStageDesign("true");
- setGenericVnf().setModelInfoGenericVnf(modelInfoGenericVnf);
- setVfModule().setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
-
- BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
- buildingBlockDetail.setBuildingBlockName("CreateVfModuleBB");
- buildingBlockDetail.setId(1);
- buildingBlockDetail.setResourceType(ResourceType.VF_MODULE);
- buildingBlockDetail.setTargetAction(OrchestrationAction.CREATE);
-
- doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
-
- OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = new OrchestrationStatusStateTransitionDirective();
- orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.FAIL);
- orchestrationStatusStateTransitionDirective.setId(1);
- orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
- orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.VF_MODULE);
- orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.CREATE);
-
- doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient).getOrchestrationStatusStateTransitionDirective(ResourceType.VF_MODULE, OrchestrationStatus.PENDING_ACTIVATION, OrchestrationAction.CREATE);
-
- orchestrationStatusValidator.validateOrchestrationStatus(execution);
-
- assertEquals(OrchestrationStatusValidationDirective.CONTINUE, execution.getVariable("orchestrationStatusValidationResult"));
- }
-
-
- @Test
- public void test_validateOrchestrationStatusSecondStageOfMultiStageWrongPrevStatusVfModule() throws Exception {
- String flowToBeCalled = "CreateVfModuleBB";
-
- execution.setVariable("orchestrationStatusValidationResult", OrchestrationStatusValidationDirective.CONTINUE);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("flowToBeCalled", flowToBeCalled);
-
- GenericVnf genericVnf = buildGenericVnf();
- ModelInfoGenericVnf modelInfoGenericVnf = genericVnf.getModelInfoGenericVnf();
- modelInfoGenericVnf.setMultiStageDesign("true");
- setGenericVnf().setModelInfoGenericVnf(modelInfoGenericVnf);
- setVfModule().setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
-
- BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
- buildingBlockDetail.setBuildingBlockName("CreateVfModuleBB");
- buildingBlockDetail.setId(1);
- buildingBlockDetail.setResourceType(ResourceType.VF_MODULE);
- buildingBlockDetail.setTargetAction(OrchestrationAction.CREATE);
-
- doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
-
- OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = new OrchestrationStatusStateTransitionDirective();
- orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.SILENT_SUCCESS);
- orchestrationStatusStateTransitionDirective.setId(1);
- orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
- orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.VF_MODULE);
- orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.CREATE);
-
- doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient).getOrchestrationStatusStateTransitionDirective(ResourceType.VF_MODULE, OrchestrationStatus.PENDING_ACTIVATION, OrchestrationAction.CREATE);
-
- orchestrationStatusValidator.validateOrchestrationStatus(execution);
-
- assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS, execution.getVariable("orchestrationStatusValidationResult"));
- }
-
- @Test
- public void test_validateOrchestrationStatusSecondStageOfMultiStageDisabledVfModule() throws Exception {
- String flowToBeCalled = "CreateVfModuleBB";
-
- execution.setVariable("orchestrationStatusValidationResult", OrchestrationStatusValidationDirective.SILENT_SUCCESS);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("flowToBeCalled", flowToBeCalled);
-
- GenericVnf genericVnf = buildGenericVnf();
- ModelInfoGenericVnf modelInfoGenericVnf = genericVnf.getModelInfoGenericVnf();
- modelInfoGenericVnf.setMultiStageDesign("false");
- setGenericVnf().setModelInfoGenericVnf(modelInfoGenericVnf);
- setVfModule().setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
-
- BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
- buildingBlockDetail.setBuildingBlockName("CreateVfModuleBB");
- buildingBlockDetail.setId(1);
- buildingBlockDetail.setResourceType(ResourceType.VF_MODULE);
- buildingBlockDetail.setTargetAction(OrchestrationAction.CREATE);
-
- doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
-
- OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = new OrchestrationStatusStateTransitionDirective();
- orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.SILENT_SUCCESS);
- orchestrationStatusStateTransitionDirective.setId(1);
- orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
- orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.VF_MODULE);
- orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.CREATE);
-
- doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient).getOrchestrationStatusStateTransitionDirective(ResourceType.VF_MODULE, OrchestrationStatus.PENDING_ACTIVATION, OrchestrationAction.CREATE);
-
- orchestrationStatusValidator.validateOrchestrationStatus(execution);
-
- assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS, execution.getVariable("orchestrationStatusValidationResult"));
- }
-
- @Test
- public void test_validateOrchestrationStatusSecondStageOfMultiStageWrongOrchStatusVfModule() throws Exception {
- String flowToBeCalled = "CreateVfModuleBB";
-
- execution.setVariable("orchestrationStatusValidationResult", OrchestrationStatusValidationDirective.SILENT_SUCCESS);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("flowToBeCalled", flowToBeCalled);
-
- GenericVnf genericVnf = buildGenericVnf();
- ModelInfoGenericVnf modelInfoGenericVnf = genericVnf.getModelInfoGenericVnf();
- modelInfoGenericVnf.setMultiStageDesign("true");
- setGenericVnf().setModelInfoGenericVnf(modelInfoGenericVnf);
- setVfModule().setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
-
- BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
- buildingBlockDetail.setBuildingBlockName("CreateVfModuleBB");
- buildingBlockDetail.setId(1);
- buildingBlockDetail.setResourceType(ResourceType.VF_MODULE);
- buildingBlockDetail.setTargetAction(OrchestrationAction.CREATE);
-
- doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
-
- OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = new OrchestrationStatusStateTransitionDirective();
- orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.SILENT_SUCCESS);
- orchestrationStatusStateTransitionDirective.setId(1);
- orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
- orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.VF_MODULE);
- orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.CREATE);
-
- doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient).getOrchestrationStatusStateTransitionDirective(ResourceType.VF_MODULE, OrchestrationStatus.ASSIGNED, OrchestrationAction.CREATE);
-
- orchestrationStatusValidator.validateOrchestrationStatus(execution);
-
- assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS, execution.getVariable("orchestrationStatusValidationResult"));
- }
-
- @Test
- public void test_validateOrchestrationStatusSecondStageOfMultiStageWrongTargetActionVfModule() throws Exception {
- String flowToBeCalled = "CreateVfModuleBB";
-
- execution.setVariable("orchestrationStatusValidationResult", OrchestrationStatusValidationDirective.SILENT_SUCCESS);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("flowToBeCalled", flowToBeCalled);
-
- GenericVnf genericVnf = buildGenericVnf();
- ModelInfoGenericVnf modelInfoGenericVnf = genericVnf.getModelInfoGenericVnf();
- modelInfoGenericVnf.setMultiStageDesign("true");
- setGenericVnf().setModelInfoGenericVnf(modelInfoGenericVnf);
- setVfModule().setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
-
- BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
- buildingBlockDetail.setBuildingBlockName("CreateVfModuleBB");
- buildingBlockDetail.setId(1);
- buildingBlockDetail.setResourceType(ResourceType.VF_MODULE);
- buildingBlockDetail.setTargetAction(OrchestrationAction.ACTIVATE);
-
- doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
-
- OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = new OrchestrationStatusStateTransitionDirective();
- orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.SILENT_SUCCESS);
- orchestrationStatusStateTransitionDirective.setId(1);
- orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
- orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.VF_MODULE);
- orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.ACTIVATE);
-
- doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient).getOrchestrationStatusStateTransitionDirective(ResourceType.VF_MODULE, OrchestrationStatus.PENDING_ACTIVATION, OrchestrationAction.ACTIVATE);
-
- orchestrationStatusValidator.validateOrchestrationStatus(execution);
-
- assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS, execution.getVariable("orchestrationStatusValidationResult"));
- }
-
- @Test
- public void test_validateOrchestrationStatusSecondStageOfMultiStageWrongAlacarteValueVfModule() throws Exception {
- String flowToBeCalled = "CreateVfModuleBB";
-
- execution.setVariable("orchestrationStatusValidationResult", OrchestrationStatusValidationDirective.SILENT_SUCCESS);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("flowToBeCalled", flowToBeCalled);
-
- GenericVnf genericVnf = buildGenericVnf();
- ModelInfoGenericVnf modelInfoGenericVnf = genericVnf.getModelInfoGenericVnf();
- modelInfoGenericVnf.setMultiStageDesign("true");
- setGenericVnf().setModelInfoGenericVnf(modelInfoGenericVnf);
- setVfModule().setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
-
- BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
- buildingBlockDetail.setBuildingBlockName("CreateVfModuleBB");
- buildingBlockDetail.setId(1);
- buildingBlockDetail.setResourceType(ResourceType.VF_MODULE);
- buildingBlockDetail.setTargetAction(OrchestrationAction.CREATE);
-
- doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
-
- OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = new OrchestrationStatusStateTransitionDirective();
- orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.SILENT_SUCCESS);
- orchestrationStatusStateTransitionDirective.setId(1);
- orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
- orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.VF_MODULE);
- orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.ACTIVATE);
-
- doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient).getOrchestrationStatusStateTransitionDirective(ResourceType.VF_MODULE, OrchestrationStatus.PENDING_ACTIVATION, OrchestrationAction.CREATE);
-
- orchestrationStatusValidator.validateOrchestrationStatus(execution);
-
- assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS, execution.getVariable("orchestrationStatusValidationResult"));
- }
+ @InjectMocks
+ protected OrchestrationStatusValidator orchestrationStatusValidator = new OrchestrationStatusValidator();
+
+
+
+ @Test
+ public void test_validateOrchestrationStatus() throws Exception {
+ String flowToBeCalled = "AssignServiceInstanceBB";
+ setServiceInstance().setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("flowToBeCalled", flowToBeCalled);
+
+ BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
+ buildingBlockDetail.setBuildingBlockName("AssignServiceInstanceBB");
+ buildingBlockDetail.setId(1);
+ buildingBlockDetail.setResourceType(ResourceType.SERVICE);
+ buildingBlockDetail.setTargetAction(OrchestrationAction.ASSIGN);
+
+ doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
+
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective =
+ new OrchestrationStatusStateTransitionDirective();
+ orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.CONTINUE);
+ orchestrationStatusStateTransitionDirective.setId(1);
+ orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.SERVICE);
+ orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.ASSIGN);
+
+ doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient)
+ .getOrchestrationStatusStateTransitionDirective(ResourceType.SERVICE, OrchestrationStatus.PRECREATED,
+ OrchestrationAction.ASSIGN);
+
+ orchestrationStatusValidator.validateOrchestrationStatus(execution);
+
+ assertEquals(OrchestrationStatusValidationDirective.CONTINUE,
+ execution.getVariable("orchestrationStatusValidationResult"));
+ }
+
+ @Test
+ public void test_validateOrchestrationStatusConfiguration() throws Exception {
+ lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId");
+ String flowToBeCalled = "UnassignFabricConfigurationBB";
+ ServiceInstance si = setServiceInstance();
+ List<Configuration> configurations = new ArrayList<>();
+ Configuration config = new Configuration();
+
+ si.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ config.setConfigurationId("configurationId");
+ config.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ configurations.add(config);
+ si.setConfigurations(configurations);
+
+ execution.setVariable("flowToBeCalled", flowToBeCalled);
+ execution.setVariable("aLaCarte", true);
+
+ BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
+ buildingBlockDetail.setBuildingBlockName("UnassignFabricConfigurationBB");
+ buildingBlockDetail.setId(1);
+ buildingBlockDetail.setResourceType(ResourceType.CONFIGURATION);
+ buildingBlockDetail.setTargetAction(OrchestrationAction.UNASSIGN);
+
+ doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
+
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective =
+ new OrchestrationStatusStateTransitionDirective();
+ orchestrationStatusStateTransitionDirective
+ .setFlowDirective(OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+ orchestrationStatusStateTransitionDirective.setId(1);
+ orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.CONFIGURATION);
+ orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.UNASSIGN);
+
+ doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient)
+ .getOrchestrationStatusStateTransitionDirective(ResourceType.CONFIGURATION,
+ OrchestrationStatus.PRECREATED, OrchestrationAction.UNASSIGN);
+
+ orchestrationStatusValidator.validateOrchestrationStatus(execution);
+
+ assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS,
+ execution.getVariable("orchestrationStatusValidationResult"));
+ }
+
+ @Test
+ public void test_validateOrchestrationStatus_buildingBlockDetailNotFound() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ String flowToBeCalled = "AssignServiceInstanceBB";
+
+ execution.setVariable("flowToBeCalled", flowToBeCalled);
+
+ doReturn(null).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
+
+ orchestrationStatusValidator.validateOrchestrationStatus(execution);
+ }
+
+ @Test
+ public void test_validateOrchestrationStatus_orchestrationValidationFail() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ String flowToBeCalled = "AssignServiceInstanceBB";
+
+ execution.setVariable("flowToBeCalled", flowToBeCalled);
+
+ BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
+ buildingBlockDetail.setBuildingBlockName("AssignServiceInstanceBB");
+ buildingBlockDetail.setId(1);
+ buildingBlockDetail.setResourceType(ResourceType.SERVICE);
+ buildingBlockDetail.setTargetAction(OrchestrationAction.ASSIGN);
+
+ doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
+
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective =
+ new OrchestrationStatusStateTransitionDirective();
+ orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.FAIL);
+ orchestrationStatusStateTransitionDirective.setId(1);
+ orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.SERVICE);
+ orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.ASSIGN);
+
+ doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient)
+ .getOrchestrationStatusStateTransitionDirective(ResourceType.SERVICE, OrchestrationStatus.PRECREATED,
+ OrchestrationAction.ASSIGN);
+
+ orchestrationStatusValidator.validateOrchestrationStatus(execution);
+ }
+
+ @Test
+ public void test_validateOrchestrationStatus_orchestrationValidationNotFound() throws Exception {
+ expectedException.expect(BpmnError.class);
+
+ String flowToBeCalled = "AssignServiceInstanceBB";
+
+ execution.setVariable("flowToBeCalled", flowToBeCalled);
+
+ BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
+ buildingBlockDetail.setBuildingBlockName("AssignServiceInstanceBB");
+ buildingBlockDetail.setId(1);
+ buildingBlockDetail.setResourceType(ResourceType.SERVICE);
+ buildingBlockDetail.setTargetAction(OrchestrationAction.ASSIGN);
+
+ doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
+
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective =
+ new OrchestrationStatusStateTransitionDirective();
+ orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.FAIL);
+ orchestrationStatusStateTransitionDirective.setId(1);
+ orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.SERVICE);
+ orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.ASSIGN);
+
+ doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient)
+ .getOrchestrationStatusStateTransitionDirective(ResourceType.NETWORK, OrchestrationStatus.PRECREATED,
+ OrchestrationAction.ASSIGN);
+
+ orchestrationStatusValidator.validateOrchestrationStatus(execution);
+ }
+
+ @Test
+ public void test_validateOrchestrationStatus_unassignNotFound() throws Exception {
+ String flowToBeCalled = "UnassignServiceInstanceBB";
+
+ execution.setVariable("flowToBeCalled", flowToBeCalled);
+ execution.setVariable("aLaCarte", true);
+
+ BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
+ buildingBlockDetail.setBuildingBlockName("UnassignServiceInstanceBB");
+ buildingBlockDetail.setId(1);
+ buildingBlockDetail.setResourceType(ResourceType.SERVICE);
+ buildingBlockDetail.setTargetAction(OrchestrationAction.UNASSIGN);
+
+ doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
+
+ lookupKeyMap = new HashMap<ResourceKey, String>();
+
+ orchestrationStatusValidator.validateOrchestrationStatus(execution);
+
+ assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS,
+ execution.getVariable("orchestrationStatusValidationResult"));
+ }
+
+ @Test
+ public void test_validateOrchestrationStatusSecondStageOfMultiStageEnabledVfModule() throws Exception {
+ String flowToBeCalled = "CreateVfModuleBB";
+
+ execution.setVariable("orchestrationStatusValidationResult",
+ OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("flowToBeCalled", flowToBeCalled);
+
+ GenericVnf genericVnf = buildGenericVnf();
+ ModelInfoGenericVnf modelInfoGenericVnf = genericVnf.getModelInfoGenericVnf();
+ modelInfoGenericVnf.setMultiStageDesign("true");
+ setGenericVnf().setModelInfoGenericVnf(modelInfoGenericVnf);
+ setVfModule().setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
+
+ BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
+ buildingBlockDetail.setBuildingBlockName("CreateVfModuleBB");
+ buildingBlockDetail.setId(1);
+ buildingBlockDetail.setResourceType(ResourceType.VF_MODULE);
+ buildingBlockDetail.setTargetAction(OrchestrationAction.CREATE);
+
+ doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
+
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective =
+ new OrchestrationStatusStateTransitionDirective();
+ orchestrationStatusStateTransitionDirective.setFlowDirective(OrchestrationStatusValidationDirective.FAIL);
+ orchestrationStatusStateTransitionDirective.setId(1);
+ orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
+ orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.VF_MODULE);
+ orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.CREATE);
+
+ doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient)
+ .getOrchestrationStatusStateTransitionDirective(ResourceType.VF_MODULE,
+ OrchestrationStatus.PENDING_ACTIVATION, OrchestrationAction.CREATE);
+
+ orchestrationStatusValidator.validateOrchestrationStatus(execution);
+
+ assertEquals(OrchestrationStatusValidationDirective.CONTINUE,
+ execution.getVariable("orchestrationStatusValidationResult"));
+ }
+
+
+ @Test
+ public void test_validateOrchestrationStatusSecondStageOfMultiStageWrongPrevStatusVfModule() throws Exception {
+ String flowToBeCalled = "CreateVfModuleBB";
+
+ execution.setVariable("orchestrationStatusValidationResult", OrchestrationStatusValidationDirective.CONTINUE);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("flowToBeCalled", flowToBeCalled);
+
+ GenericVnf genericVnf = buildGenericVnf();
+ ModelInfoGenericVnf modelInfoGenericVnf = genericVnf.getModelInfoGenericVnf();
+ modelInfoGenericVnf.setMultiStageDesign("true");
+ setGenericVnf().setModelInfoGenericVnf(modelInfoGenericVnf);
+ setVfModule().setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
+
+ BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
+ buildingBlockDetail.setBuildingBlockName("CreateVfModuleBB");
+ buildingBlockDetail.setId(1);
+ buildingBlockDetail.setResourceType(ResourceType.VF_MODULE);
+ buildingBlockDetail.setTargetAction(OrchestrationAction.CREATE);
+
+ doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
+
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective =
+ new OrchestrationStatusStateTransitionDirective();
+ orchestrationStatusStateTransitionDirective
+ .setFlowDirective(OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+ orchestrationStatusStateTransitionDirective.setId(1);
+ orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
+ orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.VF_MODULE);
+ orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.CREATE);
+
+ doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient)
+ .getOrchestrationStatusStateTransitionDirective(ResourceType.VF_MODULE,
+ OrchestrationStatus.PENDING_ACTIVATION, OrchestrationAction.CREATE);
+
+ orchestrationStatusValidator.validateOrchestrationStatus(execution);
+
+ assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS,
+ execution.getVariable("orchestrationStatusValidationResult"));
+ }
+
+ @Test
+ public void test_validateOrchestrationStatusSecondStageOfMultiStageDisabledVfModule() throws Exception {
+ String flowToBeCalled = "CreateVfModuleBB";
+
+ execution.setVariable("orchestrationStatusValidationResult",
+ OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("flowToBeCalled", flowToBeCalled);
+
+ GenericVnf genericVnf = buildGenericVnf();
+ ModelInfoGenericVnf modelInfoGenericVnf = genericVnf.getModelInfoGenericVnf();
+ modelInfoGenericVnf.setMultiStageDesign("false");
+ setGenericVnf().setModelInfoGenericVnf(modelInfoGenericVnf);
+ setVfModule().setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
+
+ BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
+ buildingBlockDetail.setBuildingBlockName("CreateVfModuleBB");
+ buildingBlockDetail.setId(1);
+ buildingBlockDetail.setResourceType(ResourceType.VF_MODULE);
+ buildingBlockDetail.setTargetAction(OrchestrationAction.CREATE);
+
+ doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
+
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective =
+ new OrchestrationStatusStateTransitionDirective();
+ orchestrationStatusStateTransitionDirective
+ .setFlowDirective(OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+ orchestrationStatusStateTransitionDirective.setId(1);
+ orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
+ orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.VF_MODULE);
+ orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.CREATE);
+
+ doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient)
+ .getOrchestrationStatusStateTransitionDirective(ResourceType.VF_MODULE,
+ OrchestrationStatus.PENDING_ACTIVATION, OrchestrationAction.CREATE);
+
+ orchestrationStatusValidator.validateOrchestrationStatus(execution);
+
+ assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS,
+ execution.getVariable("orchestrationStatusValidationResult"));
+ }
+
+ @Test
+ public void test_validateOrchestrationStatusSecondStageOfMultiStageWrongOrchStatusVfModule() throws Exception {
+ String flowToBeCalled = "CreateVfModuleBB";
+
+ execution.setVariable("orchestrationStatusValidationResult",
+ OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("flowToBeCalled", flowToBeCalled);
+
+ GenericVnf genericVnf = buildGenericVnf();
+ ModelInfoGenericVnf modelInfoGenericVnf = genericVnf.getModelInfoGenericVnf();
+ modelInfoGenericVnf.setMultiStageDesign("true");
+ setGenericVnf().setModelInfoGenericVnf(modelInfoGenericVnf);
+ setVfModule().setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+
+ BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
+ buildingBlockDetail.setBuildingBlockName("CreateVfModuleBB");
+ buildingBlockDetail.setId(1);
+ buildingBlockDetail.setResourceType(ResourceType.VF_MODULE);
+ buildingBlockDetail.setTargetAction(OrchestrationAction.CREATE);
+
+ doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
+
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective =
+ new OrchestrationStatusStateTransitionDirective();
+ orchestrationStatusStateTransitionDirective
+ .setFlowDirective(OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+ orchestrationStatusStateTransitionDirective.setId(1);
+ orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
+ orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.VF_MODULE);
+ orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.CREATE);
+
+ doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient)
+ .getOrchestrationStatusStateTransitionDirective(ResourceType.VF_MODULE, OrchestrationStatus.ASSIGNED,
+ OrchestrationAction.CREATE);
+
+ orchestrationStatusValidator.validateOrchestrationStatus(execution);
+
+ assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS,
+ execution.getVariable("orchestrationStatusValidationResult"));
+ }
+
+ @Test
+ public void test_validateOrchestrationStatusSecondStageOfMultiStageWrongTargetActionVfModule() throws Exception {
+ String flowToBeCalled = "CreateVfModuleBB";
+
+ execution.setVariable("orchestrationStatusValidationResult",
+ OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("flowToBeCalled", flowToBeCalled);
+
+ GenericVnf genericVnf = buildGenericVnf();
+ ModelInfoGenericVnf modelInfoGenericVnf = genericVnf.getModelInfoGenericVnf();
+ modelInfoGenericVnf.setMultiStageDesign("true");
+ setGenericVnf().setModelInfoGenericVnf(modelInfoGenericVnf);
+ setVfModule().setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
+
+ BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
+ buildingBlockDetail.setBuildingBlockName("CreateVfModuleBB");
+ buildingBlockDetail.setId(1);
+ buildingBlockDetail.setResourceType(ResourceType.VF_MODULE);
+ buildingBlockDetail.setTargetAction(OrchestrationAction.ACTIVATE);
+
+ doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
+
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective =
+ new OrchestrationStatusStateTransitionDirective();
+ orchestrationStatusStateTransitionDirective
+ .setFlowDirective(OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+ orchestrationStatusStateTransitionDirective.setId(1);
+ orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
+ orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.VF_MODULE);
+ orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.ACTIVATE);
+
+ doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient)
+ .getOrchestrationStatusStateTransitionDirective(ResourceType.VF_MODULE,
+ OrchestrationStatus.PENDING_ACTIVATION, OrchestrationAction.ACTIVATE);
+
+ orchestrationStatusValidator.validateOrchestrationStatus(execution);
+
+ assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS,
+ execution.getVariable("orchestrationStatusValidationResult"));
+ }
+
+ @Test
+ public void test_validateOrchestrationStatusSecondStageOfMultiStageWrongAlacarteValueVfModule() throws Exception {
+ String flowToBeCalled = "CreateVfModuleBB";
+
+ execution.setVariable("orchestrationStatusValidationResult",
+ OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("flowToBeCalled", flowToBeCalled);
+
+ GenericVnf genericVnf = buildGenericVnf();
+ ModelInfoGenericVnf modelInfoGenericVnf = genericVnf.getModelInfoGenericVnf();
+ modelInfoGenericVnf.setMultiStageDesign("true");
+ setGenericVnf().setModelInfoGenericVnf(modelInfoGenericVnf);
+ setVfModule().setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
+
+ BuildingBlockDetail buildingBlockDetail = new BuildingBlockDetail();
+ buildingBlockDetail.setBuildingBlockName("CreateVfModuleBB");
+ buildingBlockDetail.setId(1);
+ buildingBlockDetail.setResourceType(ResourceType.VF_MODULE);
+ buildingBlockDetail.setTargetAction(OrchestrationAction.CREATE);
+
+ doReturn(buildingBlockDetail).when(catalogDbClient).getBuildingBlockDetail(flowToBeCalled);
+
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective =
+ new OrchestrationStatusStateTransitionDirective();
+ orchestrationStatusStateTransitionDirective
+ .setFlowDirective(OrchestrationStatusValidationDirective.SILENT_SUCCESS);
+ orchestrationStatusStateTransitionDirective.setId(1);
+ orchestrationStatusStateTransitionDirective.setOrchestrationStatus(OrchestrationStatus.PENDING_ACTIVATION);
+ orchestrationStatusStateTransitionDirective.setResourceType(ResourceType.VF_MODULE);
+ orchestrationStatusStateTransitionDirective.setTargetAction(OrchestrationAction.ACTIVATE);
+
+ doReturn(orchestrationStatusStateTransitionDirective).when(catalogDbClient)
+ .getOrchestrationStatusStateTransitionDirective(ResourceType.VF_MODULE,
+ OrchestrationStatus.PENDING_ACTIVATION, OrchestrationAction.CREATE);
+
+ orchestrationStatusValidator.validateOrchestrationStatus(execution);
+
+ assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS,
+ execution.getVariable("orchestrationStatusValidationResult"));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidatorUnitTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidatorUnitTest.java
index 03b39f57e5..0da683de62 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidatorUnitTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidatorUnitTest.java
@@ -23,7 +23,6 @@ package org.onap.so.bpmn.infrastructure.workflow.tasks;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -41,25 +40,27 @@ import org.onap.so.db.catalog.client.CatalogDbClient;
@RunWith(MockitoJUnitRunner.class)
public class OrchestrationStatusValidatorUnitTest {
- @Mock
- private CatalogDbClient catalogDbClient;
-
- @InjectMocks
- private OrchestrationStatusValidator validator;
- @Test
- public void skipValidationTest() {
- BuildingBlockDetail bbDetail = new BuildingBlockDetail();
- bbDetail.setBuildingBlockName("customBB");
- bbDetail.setResourceType(ResourceType.NO_VALIDATE);
- bbDetail.setTargetAction(OrchestrationAction.CUSTOM);
- when(catalogDbClient.getBuildingBlockDetail("customBB")).thenReturn(bbDetail);
- BuildingBlockExecution execution = new DelegateExecutionImpl(new DelegateExecutionFake());
- execution.setVariable("flowToBeCalled", "customBB");
- execution.setVariable("aLaCarte", false);
- validator.validateOrchestrationStatus(execution);
-
-
- assertThat(execution.getVariable("orchestrationStatusValidationResult"), equalTo(OrchestrationStatusValidationDirective.VALIDATION_SKIPPED));
- }
-
+ @Mock
+ private CatalogDbClient catalogDbClient;
+
+ @InjectMocks
+ private OrchestrationStatusValidator validator;
+
+ @Test
+ public void skipValidationTest() {
+ BuildingBlockDetail bbDetail = new BuildingBlockDetail();
+ bbDetail.setBuildingBlockName("customBB");
+ bbDetail.setResourceType(ResourceType.NO_VALIDATE);
+ bbDetail.setTargetAction(OrchestrationAction.CUSTOM);
+ when(catalogDbClient.getBuildingBlockDetail("customBB")).thenReturn(bbDetail);
+ BuildingBlockExecution execution = new DelegateExecutionImpl(new DelegateExecutionFake());
+ execution.setVariable("flowToBeCalled", "customBB");
+ execution.setVariable("aLaCarte", false);
+ validator.validateOrchestrationStatus(execution);
+
+
+ assertThat(execution.getVariable("orchestrationStatusValidationResult"),
+ equalTo(OrchestrationStatusValidationDirective.VALIDATION_SKIPPED));
+ }
+
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailureTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailureTest.java
index 14261e876d..a6ce88f164 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailureTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailureTest.java
@@ -26,7 +26,6 @@ import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
import org.junit.Before;
@@ -42,105 +41,105 @@ import org.onap.so.bpmn.core.WorkflowException;
import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer;
import org.onap.so.db.request.beans.InfraActiveRequests;
-public class WorkflowActionBBFailureTest extends BaseTaskTest {
+public class WorkflowActionBBFailureTest extends BaseTaskTest {
+
+ @Mock
+ protected WorkflowAction workflowAction;
+
+ @InjectMocks
+ @Spy
+ protected WorkflowActionBBFailure workflowActionBBFailure;
+
+ @Mock
+ InfraActiveRequests reqMock;
+
+ private DelegateExecution execution;
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Before
+ public void before() throws Exception {
+ execution = new DelegateExecutionFake();
+ org.onap.aai.domain.yang.ServiceInstance servInstance = new org.onap.aai.domain.yang.ServiceInstance();
+ servInstance.setServiceInstanceId("TEST");
+ when(bbSetupUtils.getAAIServiceInstanceByName(anyString(), isA(Customer.class))).thenReturn(servInstance);
+ workflowAction.setBbInputSetupUtils(bbSetupUtils);
+ workflowAction.setBbInputSetup(bbInputSetup);
+ }
+
+ @Test
+ public void updateRequestStatusToFailed_Null_Rollback() {
+ String reqId = "reqId123";
+ execution.setVariable("mso-request-id", reqId);
+ execution.setVariable("retryCount", 3);
+ execution.setVariable("handlingCode", "Success");
+ execution.setVariable("gCurrentSequence", 1);
+ WorkflowException we = new WorkflowException("WorkflowAction", 1231, "Error Case");
+ execution.setVariable("WorkflowException", we);
+
+ doReturn(reqMock).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId);
+ workflowActionBBFailure.updateRequestStatusToFailed(execution);
+ Mockito.verify(reqMock, Mockito.times(1)).setStatusMessage("Error Case");
+ Mockito.verify(reqMock, Mockito.times(1)).setRequestStatus("FAILED");
+ Mockito.verify(reqMock, Mockito.times(1)).setProgress(Long.valueOf(100));
+ Mockito.verify(reqMock, Mockito.times(1)).setLastModifiedBy("CamundaBPMN");
+ }
+
+ @Test
+ public void updateRequestStatusToFailed() {
+ execution.setVariable("mso-request-id", "123");
+ execution.setVariable("isRollbackComplete", false);
+ execution.setVariable("isRollback", false);
+ InfraActiveRequests req = new InfraActiveRequests();
+ WorkflowException wfe = new WorkflowException("processKey123", 1, "error in test case");
+ execution.setVariable("WorkflowException", wfe);
+ doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId("123");
+ doNothing().when(requestsDbClient).updateInfraActiveRequests(isA(InfraActiveRequests.class));
+ workflowActionBBFailure.updateRequestStatusToFailed(execution);
+ String errorMsg = (String) execution.getVariable("ErrorMessage");
+ assertEquals("error in test case", errorMsg);
+ }
+
+ @Test
+ public void updateRequestStatusToFailedRollback() {
+ execution.setVariable("mso-request-id", "123");
+ execution.setVariable("isRollbackComplete", false);
+ execution.setVariable("isRollback", true);
+ InfraActiveRequests req = new InfraActiveRequests();
+ WorkflowException wfe = new WorkflowException("processKey123", 1, "error in rollback");
+ execution.setVariable("WorkflowException", wfe);
+ doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId("123");
+ doNothing().when(requestsDbClient).updateInfraActiveRequests(isA(InfraActiveRequests.class));
+ workflowActionBBFailure.updateRequestStatusToFailed(execution);
+ String errorMsg = (String) execution.getVariable("RollbackErrorMessage");
+ assertEquals("error in rollback", errorMsg);
+ }
+
+ @Test
+ public void updateRequestStatusToFailedRollbackCompleted() {
+ execution.setVariable("mso-request-id", "123");
+ execution.setVariable("isRollbackComplete", true);
+ execution.setVariable("isRollback", true);
+ InfraActiveRequests req = new InfraActiveRequests();
+ doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId("123");
+ doNothing().when(requestsDbClient).updateInfraActiveRequests(isA(InfraActiveRequests.class));
+ workflowActionBBFailure.updateRequestStatusToFailed(execution);
+ String errorMsg = (String) execution.getVariable("RollbackErrorMessage");
+ assertEquals("Rollback has been completed successfully.", errorMsg);
+ }
- @Mock
- protected WorkflowAction workflowAction;
-
- @InjectMocks
- @Spy
- protected WorkflowActionBBFailure workflowActionBBFailure;
-
- @Mock
- InfraActiveRequests reqMock;
-
- private DelegateExecution execution;
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Before
- public void before() throws Exception {
- execution = new DelegateExecutionFake();
- org.onap.aai.domain.yang.ServiceInstance servInstance = new org.onap.aai.domain.yang.ServiceInstance();
- servInstance.setServiceInstanceId("TEST");
- when(bbSetupUtils.getAAIServiceInstanceByName(anyString(), isA(Customer.class))).thenReturn(servInstance);
- workflowAction.setBbInputSetupUtils(bbSetupUtils);
- workflowAction.setBbInputSetup(bbInputSetup);
- }
-
- @Test
- public void updateRequestStatusToFailed_Null_Rollback(){
- String reqId = "reqId123";
- execution.setVariable("mso-request-id", reqId);
- execution.setVariable("retryCount", 3);
- execution.setVariable("handlingCode","Success");
- execution.setVariable("gCurrentSequence",1);
- WorkflowException we = new WorkflowException("WorkflowAction",1231,"Error Case");
- execution.setVariable("WorkflowException",we);
-
- doReturn(reqMock).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId);
- workflowActionBBFailure.updateRequestStatusToFailed(execution);
- Mockito.verify( reqMock, Mockito.times(1)).setStatusMessage("Error Case");
- Mockito.verify( reqMock, Mockito.times(1)).setRequestStatus("FAILED");
- Mockito.verify( reqMock, Mockito.times(1)).setProgress(Long.valueOf(100));
- Mockito.verify( reqMock, Mockito.times(1)).setLastModifiedBy("CamundaBPMN");
- }
-
- @Test
- public void updateRequestStatusToFailed(){
- execution.setVariable("mso-request-id", "123");
- execution.setVariable("isRollbackComplete", false);
- execution.setVariable("isRollback", false);
- InfraActiveRequests req = new InfraActiveRequests();
- WorkflowException wfe = new WorkflowException("processKey123", 1, "error in test case");
- execution.setVariable("WorkflowException", wfe);
- doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId("123");
- doNothing().when(requestsDbClient).updateInfraActiveRequests(isA(InfraActiveRequests.class));
- workflowActionBBFailure.updateRequestStatusToFailed(execution);
- String errorMsg = (String) execution.getVariable("ErrorMessage");
- assertEquals("error in test case", errorMsg);
- }
-
- @Test
- public void updateRequestStatusToFailedRollback(){
- execution.setVariable("mso-request-id", "123");
- execution.setVariable("isRollbackComplete", false);
- execution.setVariable("isRollback", true);
- InfraActiveRequests req = new InfraActiveRequests();
- WorkflowException wfe = new WorkflowException("processKey123", 1, "error in rollback");
- execution.setVariable("WorkflowException", wfe);
- doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId("123");
- doNothing().when(requestsDbClient).updateInfraActiveRequests(isA(InfraActiveRequests.class));
- workflowActionBBFailure.updateRequestStatusToFailed(execution);
- String errorMsg = (String) execution.getVariable("RollbackErrorMessage");
- assertEquals("error in rollback", errorMsg);
- }
-
- @Test
- public void updateRequestStatusToFailedRollbackCompleted(){
- execution.setVariable("mso-request-id", "123");
- execution.setVariable("isRollbackComplete", true);
- execution.setVariable("isRollback", true);
- InfraActiveRequests req = new InfraActiveRequests();
- doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId("123");
- doNothing().when(requestsDbClient).updateInfraActiveRequests(isA(InfraActiveRequests.class));
- workflowActionBBFailure.updateRequestStatusToFailed(execution);
- String errorMsg = (String) execution.getVariable("RollbackErrorMessage");
- assertEquals("Rollback has been completed successfully.", errorMsg);
- }
-
- @Test
- public void updateRequestStatusToFailedNoWorkflowException(){
- execution.setVariable("mso-request-id", "123");
- execution.setVariable("isRollbackComplete", false);
- execution.setVariable("isRollback", false);
- execution.setVariable("WorkflowExceptionErrorMessage", "error in test case");
- InfraActiveRequests req = new InfraActiveRequests();
- doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId("123");
- doNothing().when(requestsDbClient).updateInfraActiveRequests(isA(InfraActiveRequests.class));
- workflowActionBBFailure.updateRequestStatusToFailed(execution);
- String errorMsg = (String) execution.getVariable("ErrorMessage");
- assertEquals("error in test case", errorMsg);
- }
+ @Test
+ public void updateRequestStatusToFailedNoWorkflowException() {
+ execution.setVariable("mso-request-id", "123");
+ execution.setVariable("isRollbackComplete", false);
+ execution.setVariable("isRollback", false);
+ execution.setVariable("WorkflowExceptionErrorMessage", "error in test case");
+ InfraActiveRequests req = new InfraActiveRequests();
+ doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId("123");
+ doNothing().when(requestsDbClient).updateInfraActiveRequests(isA(InfraActiveRequests.class));
+ workflowActionBBFailure.updateRequestStatusToFailed(execution);
+ String errorMsg = (String) execution.getVariable("ErrorMessage");
+ assertEquals("error in test case", errorMsg);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java
index c5b4a482b7..029562a6e9 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java
@@ -27,10 +27,8 @@ import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
-
import java.util.ArrayList;
import java.util.List;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
@@ -51,314 +49,315 @@ import org.springframework.core.env.Environment;
public class WorkflowActionBBTasksTest extends BaseTaskTest {
- @Mock
- protected WorkflowAction workflowAction;
-
- @Mock
- protected WorkflowActionBBFailure workflowActionBBFailure;
-
- @InjectMocks
- @Spy
- protected WorkflowActionBBTasks workflowActionBBTasks;
-
- @Mock
- InfraActiveRequests reqMock;
-
- private DelegateExecution execution;
-
- @Mock
- protected Environment environment;
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Before
- public void before() throws Exception {
- execution = new DelegateExecutionFake();
- org.onap.aai.domain.yang.ServiceInstance servInstance = new org.onap.aai.domain.yang.ServiceInstance();
- servInstance.setServiceInstanceId("TEST");
- when(bbSetupUtils.getAAIServiceInstanceByName(anyString(), anyObject())).thenReturn(servInstance);
- workflowAction.setBbInputSetupUtils(bbSetupUtils);
- workflowAction.setBbInputSetup(bbInputSetup);
- }
-
- @Test
- public void selectBBTest() throws Exception{
- String gAction = "Delete-Network-Collection";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- execution.setVariable("gCurrentSequence", 0);
- execution.setVariable("homing", false);
- execution.setVariable("calledHoming", false);
- List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
- ExecuteBuildingBlock ebb = new ExecuteBuildingBlock();
- flowsToExecute.add(ebb);
- execution.setVariable("flowsToExecute", flowsToExecute);
- workflowActionBBTasks.selectBB(execution);
- boolean success = (boolean) execution.getVariable("completed");
- int currentSequence = (int) execution.getVariable("gCurrentSequence");
- assertEquals(true,success);
- assertEquals(1,currentSequence);
- }
-
- @Test
- public void select2BBTest() throws Exception{
- String gAction = "Delete-Network-Collection";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- execution.setVariable("gCurrentSequence", 0);
- execution.setVariable("homing", false);
- execution.setVariable("calledHoming", false);
- List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
- ExecuteBuildingBlock ebb = new ExecuteBuildingBlock();
- ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
- flowsToExecute.add(ebb);
- flowsToExecute.add(ebb2);
- execution.setVariable("flowsToExecute", flowsToExecute);
- workflowActionBBTasks.selectBB(execution);
- boolean success = (boolean) execution.getVariable("completed");
- int currentSequence = (int) execution.getVariable("gCurrentSequence");
- assertEquals(false,success);
- assertEquals(1,currentSequence);
- }
-
- @Test
- public void updateRequestStatusToCompleteTest() throws Exception{
- String reqId = "reqId123";
- execution.setVariable("mso-request-id", reqId);
- execution.setVariable("requestAction", "createInstance");
- execution.setVariable("resourceName", "Service");
- execution.setVariable("aLaCarte", true);
- InfraActiveRequests req = new InfraActiveRequests();
- doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId);
- doNothing().when(requestsDbClient).updateInfraActiveRequests(isA(InfraActiveRequests.class));
- workflowActionBBTasks.updateRequestStatusToComplete(execution);
- assertEquals("ALaCarte-Service-createInstance request was executed correctly.",execution.getVariable("finalStatusMessage"));
- }
-
- @Test
- public void rollbackExecutionPathTest(){
- execution.setVariable("handlingCode", "Rollback");
- execution.setVariable("isRollback", false);
- List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
- ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock();
- BuildingBlock bb1 = new BuildingBlock();
- bb1.setBpmnFlowName("AssignVfModuleBB");
- ebb1.setBuildingBlock(bb1);
- flowsToExecute.add(ebb1);
- ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
- BuildingBlock bb2 = new BuildingBlock();
- bb2.setBpmnFlowName("CreateVfModuleBB");
- ebb2.setBuildingBlock(bb2);
- flowsToExecute.add(ebb2);
- ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
- BuildingBlock bb3 = new BuildingBlock();
- bb3.setBpmnFlowName("ActivateVfModuleBB");
- ebb3.setBuildingBlock(bb3);
- flowsToExecute.add(ebb3);
-
- execution.setVariable("flowsToExecute", flowsToExecute);
- execution.setVariable("gCurrentSequence", 3);
- doNothing().when(workflowActionBBFailure).updateRequestErrorStatusMessage(isA(DelegateExecution.class));
-
- workflowActionBBTasks.rollbackExecutionPath(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEquals(ebbs.get(0).getBuildingBlock().getBpmnFlowName(),"DeactivateVfModuleBB");
- assertEquals(ebbs.get(1).getBuildingBlock().getBpmnFlowName(),"DeleteVfModuleBB");
- assertEquals(ebbs.get(2).getBuildingBlock().getBpmnFlowName(),"UnassignVfModuleBB");
- assertEquals(0,execution.getVariable("gCurrentSequence"));
- }
-
- @Test
- public void rollbackExecutionPathUnfinishedFlowTest(){
- execution.setVariable("handlingCode", "Rollback");
- execution.setVariable("isRollback", false);
- List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
- ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock();
- BuildingBlock bb1 = new BuildingBlock();
- bb1.setBpmnFlowName("AssignVfModuleBB");
- ebb1.setBuildingBlock(bb1);
- flowsToExecute.add(ebb1);
- ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
- BuildingBlock bb2 = new BuildingBlock();
- bb2.setBpmnFlowName("CreateVfModuleBB");
- ebb2.setBuildingBlock(bb2);
- flowsToExecute.add(ebb2);
- ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
- BuildingBlock bb3 = new BuildingBlock();
- bb3.setBpmnFlowName("ActivateVfModuleBB");
- ebb3.setBuildingBlock(bb3);
- flowsToExecute.add(ebb3);
-
- execution.setVariable("flowsToExecute", flowsToExecute);
- execution.setVariable("gCurrentSequence", 2);
- doNothing().when(workflowActionBBFailure).updateRequestErrorStatusMessage(isA(DelegateExecution.class));
-
- workflowActionBBTasks.rollbackExecutionPath(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEquals(ebbs.get(0).getBuildingBlock().getBpmnFlowName(),"DeleteVfModuleBB");
- assertEquals(ebbs.get(1).getBuildingBlock().getBpmnFlowName(),"UnassignVfModuleBB");
- assertEquals(0,execution.getVariable("gCurrentSequence"));
- assertEquals(0,execution.getVariable("retryCount"));
- }
-
- @Test
- public void rollbackExecutionTest(){
- execution.setVariable("handlingCode", "Rollback");
- execution.setVariable("isRollback", false);
- List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
- ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock();
- BuildingBlock bb1 = new BuildingBlock();
- bb1.setBpmnFlowName("AssignServiceInstanceBB");
- ebb1.setBuildingBlock(bb1);
- flowsToExecute.add(ebb1);
- ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
- BuildingBlock bb2 = new BuildingBlock();
- bb2.setBpmnFlowName("CreateNetworkCollectionBB");
- ebb2.setBuildingBlock(bb2);
- flowsToExecute.add(ebb2);
- ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
- BuildingBlock bb3 = new BuildingBlock();
- bb3.setBpmnFlowName("AssignNetworkBB");
- ebb3.setBuildingBlock(bb3);
- flowsToExecute.add(ebb3);
- ExecuteBuildingBlock ebb4 = new ExecuteBuildingBlock();
- BuildingBlock bb4 = new BuildingBlock();
- bb4.setBpmnFlowName("CreateNetworkBB");
- ebb4.setBuildingBlock(bb4);
- flowsToExecute.add(ebb4);
-
- execution.setVariable("flowsToExecute", flowsToExecute);
- execution.setVariable("gCurrentSequence", 3);
- doNothing().when(workflowActionBBFailure).updateRequestErrorStatusMessage(isA(DelegateExecution.class));
-
- workflowActionBBTasks.rollbackExecutionPath(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEquals(ebbs.get(0).getBuildingBlock().getBpmnFlowName(),"UnassignNetworkBB");
- assertEquals(ebbs.get(1).getBuildingBlock().getBpmnFlowName(),"DeleteNetworkCollectionBB");
- assertEquals(ebbs.get(2).getBuildingBlock().getBpmnFlowName(),"UnassignServiceInstanceBB");
- assertEquals(0,execution.getVariable("gCurrentSequence"));
- }
-
- @Test
- public void rollbackExecutionRollbackToAssignedTest(){
- execution.setVariable("isRollback", false);
- execution.setVariable("handlingCode", "RollbackToAssigned");
- List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
- ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock();
- BuildingBlock bb1 = new BuildingBlock();
- bb1.setBpmnFlowName("AssignVfModuleBB");
- ebb1.setBuildingBlock(bb1);
- flowsToExecute.add(ebb1);
- ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
- BuildingBlock bb2 = new BuildingBlock();
- bb2.setBpmnFlowName("CreateVfModuleBB");
- ebb2.setBuildingBlock(bb2);
- flowsToExecute.add(ebb2);
- ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
- BuildingBlock bb3 = new BuildingBlock();
- bb3.setBpmnFlowName("ActivateVfModuleBB");
- ebb3.setBuildingBlock(bb3);
- flowsToExecute.add(ebb3);
-
- execution.setVariable("flowsToExecute", flowsToExecute);
- execution.setVariable("gCurrentSequence", 2);
-
- workflowActionBBTasks.rollbackExecutionPath(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEquals("DeleteVfModuleBB",ebbs.get(0).getBuildingBlock().getBpmnFlowName());
- assertEquals(0,execution.getVariable("gCurrentSequence"));
- assertEquals(1,ebbs.size());
- }
-
- @Test
- public void rollbackExecutionRollbackToCreatedTest(){
- execution.setVariable("isRollback", false);
- execution.setVariable("handlingCode", "RollbackToCreated");
- List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
- ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock();
- BuildingBlock bb1 = new BuildingBlock();
- bb1.setBpmnFlowName("AssignVfModuleBB");
- ebb1.setBuildingBlock(bb1);
- flowsToExecute.add(ebb1);
- ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
- BuildingBlock bb2 = new BuildingBlock();
- bb2.setBpmnFlowName("CreateVfModuleBB");
- ebb2.setBuildingBlock(bb2);
- flowsToExecute.add(ebb2);
- ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
- BuildingBlock bb3 = new BuildingBlock();
- bb3.setBpmnFlowName("ActivateVfModuleBB");
- ebb3.setBuildingBlock(bb3);
- flowsToExecute.add(ebb3);
-
- execution.setVariable("flowsToExecute", flowsToExecute);
- execution.setVariable("gCurrentSequence", 3);
-
- workflowActionBBTasks.rollbackExecutionPath(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEquals("DeactivateVfModuleBB",ebbs.get(0).getBuildingBlock().getBpmnFlowName());
- assertEquals(0,execution.getVariable("gCurrentSequence"));
- assertEquals(1,ebbs.size());
- }
-
- @Test
- public void checkRetryStatusTest(){
- String reqId = "reqId123";
- execution.setVariable("mso-request-id", reqId);
- doNothing().when(workflowActionBBFailure).updateRequestErrorStatusMessage(isA(DelegateExecution.class));
- doReturn("6").when(environment).getProperty("mso.rainyDay.maxRetries");
- execution.setVariable("handlingCode","Retry");
- execution.setVariable("retryCount", 1);
- execution.setVariable("gCurrentSequence",1);
- InfraActiveRequests req = new InfraActiveRequests();
- doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId);
- workflowActionBBTasks.checkRetryStatus(execution);
- assertEquals(0,execution.getVariable("gCurrentSequence"));
- }
-
- @Test
- public void checkRetryStatusTestExceededMaxRetries(){
- String reqId = "reqId123";
- execution.setVariable("mso-request-id", reqId);
- doNothing().when(workflowActionBBFailure).updateRequestErrorStatusMessage(isA(DelegateExecution.class));
- doReturn("6").when(environment).getProperty("mso.rainyDay.maxRetries");
- execution.setVariable("handlingCode","Retry");
- execution.setVariable("retryCount", 6);
- execution.setVariable("gCurrentSequence",1);
- InfraActiveRequests req = new InfraActiveRequests();
- doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId);
- try{
- workflowActionBBTasks.checkRetryStatus(execution);
- } catch (BpmnError e) {
- WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
- assertEquals("Exceeded maximum retries. Ending flow with status Abort",exception.getErrorMessage());
- }
- }
-
- @Test
- public void checkRetryStatusNoRetryTest(){
- String reqId = "reqId123";
- execution.setVariable("mso-request-id", reqId);
- execution.setVariable("retryCount", 3);
- execution.setVariable("handlingCode","Success");
- execution.setVariable("gCurrentSequence",1);
- InfraActiveRequests req = new InfraActiveRequests();
- doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId);
- workflowActionBBTasks.checkRetryStatus(execution);
- assertEquals(0,execution.getVariable("retryCount"));
- }
-
- @Test
- public void updateInstanceId(){
- String reqId = "req123";
- String instanceId = "123123123";
- execution.setVariable("mso-request-id", reqId);
- execution.setVariable("resourceId", instanceId);
- execution.setVariable("resourceType", WorkflowType.SERVICE);
- doReturn(reqMock).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId);
- doNothing().when(requestsDbClient).updateInfraActiveRequests(isA(InfraActiveRequests.class));
- workflowActionBBTasks.updateInstanceId(execution);
- Mockito.verify( reqMock, Mockito.times(1)).setServiceInstanceId(instanceId);
- }
+ @Mock
+ protected WorkflowAction workflowAction;
+
+ @Mock
+ protected WorkflowActionBBFailure workflowActionBBFailure;
+
+ @InjectMocks
+ @Spy
+ protected WorkflowActionBBTasks workflowActionBBTasks;
+
+ @Mock
+ InfraActiveRequests reqMock;
+
+ private DelegateExecution execution;
+
+ @Mock
+ protected Environment environment;
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Before
+ public void before() throws Exception {
+ execution = new DelegateExecutionFake();
+ org.onap.aai.domain.yang.ServiceInstance servInstance = new org.onap.aai.domain.yang.ServiceInstance();
+ servInstance.setServiceInstanceId("TEST");
+ when(bbSetupUtils.getAAIServiceInstanceByName(anyString(), anyObject())).thenReturn(servInstance);
+ workflowAction.setBbInputSetupUtils(bbSetupUtils);
+ workflowAction.setBbInputSetup(bbInputSetup);
+ }
+
+ @Test
+ public void selectBBTest() throws Exception {
+ String gAction = "Delete-Network-Collection";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ execution.setVariable("gCurrentSequence", 0);
+ execution.setVariable("homing", false);
+ execution.setVariable("calledHoming", false);
+ List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
+ ExecuteBuildingBlock ebb = new ExecuteBuildingBlock();
+ flowsToExecute.add(ebb);
+ execution.setVariable("flowsToExecute", flowsToExecute);
+ workflowActionBBTasks.selectBB(execution);
+ boolean success = (boolean) execution.getVariable("completed");
+ int currentSequence = (int) execution.getVariable("gCurrentSequence");
+ assertEquals(true, success);
+ assertEquals(1, currentSequence);
+ }
+
+ @Test
+ public void select2BBTest() throws Exception {
+ String gAction = "Delete-Network-Collection";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ execution.setVariable("gCurrentSequence", 0);
+ execution.setVariable("homing", false);
+ execution.setVariable("calledHoming", false);
+ List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
+ ExecuteBuildingBlock ebb = new ExecuteBuildingBlock();
+ ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
+ flowsToExecute.add(ebb);
+ flowsToExecute.add(ebb2);
+ execution.setVariable("flowsToExecute", flowsToExecute);
+ workflowActionBBTasks.selectBB(execution);
+ boolean success = (boolean) execution.getVariable("completed");
+ int currentSequence = (int) execution.getVariable("gCurrentSequence");
+ assertEquals(false, success);
+ assertEquals(1, currentSequence);
+ }
+
+ @Test
+ public void updateRequestStatusToCompleteTest() throws Exception {
+ String reqId = "reqId123";
+ execution.setVariable("mso-request-id", reqId);
+ execution.setVariable("requestAction", "createInstance");
+ execution.setVariable("resourceName", "Service");
+ execution.setVariable("aLaCarte", true);
+ InfraActiveRequests req = new InfraActiveRequests();
+ doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId);
+ doNothing().when(requestsDbClient).updateInfraActiveRequests(isA(InfraActiveRequests.class));
+ workflowActionBBTasks.updateRequestStatusToComplete(execution);
+ assertEquals("ALaCarte-Service-createInstance request was executed correctly.",
+ execution.getVariable("finalStatusMessage"));
+ }
+
+ @Test
+ public void rollbackExecutionPathTest() {
+ execution.setVariable("handlingCode", "Rollback");
+ execution.setVariable("isRollback", false);
+ List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
+ ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock();
+ BuildingBlock bb1 = new BuildingBlock();
+ bb1.setBpmnFlowName("AssignVfModuleBB");
+ ebb1.setBuildingBlock(bb1);
+ flowsToExecute.add(ebb1);
+ ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
+ BuildingBlock bb2 = new BuildingBlock();
+ bb2.setBpmnFlowName("CreateVfModuleBB");
+ ebb2.setBuildingBlock(bb2);
+ flowsToExecute.add(ebb2);
+ ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
+ BuildingBlock bb3 = new BuildingBlock();
+ bb3.setBpmnFlowName("ActivateVfModuleBB");
+ ebb3.setBuildingBlock(bb3);
+ flowsToExecute.add(ebb3);
+
+ execution.setVariable("flowsToExecute", flowsToExecute);
+ execution.setVariable("gCurrentSequence", 3);
+ doNothing().when(workflowActionBBFailure).updateRequestErrorStatusMessage(isA(DelegateExecution.class));
+
+ workflowActionBBTasks.rollbackExecutionPath(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEquals(ebbs.get(0).getBuildingBlock().getBpmnFlowName(), "DeactivateVfModuleBB");
+ assertEquals(ebbs.get(1).getBuildingBlock().getBpmnFlowName(), "DeleteVfModuleBB");
+ assertEquals(ebbs.get(2).getBuildingBlock().getBpmnFlowName(), "UnassignVfModuleBB");
+ assertEquals(0, execution.getVariable("gCurrentSequence"));
+ }
+
+ @Test
+ public void rollbackExecutionPathUnfinishedFlowTest() {
+ execution.setVariable("handlingCode", "Rollback");
+ execution.setVariable("isRollback", false);
+ List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
+ ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock();
+ BuildingBlock bb1 = new BuildingBlock();
+ bb1.setBpmnFlowName("AssignVfModuleBB");
+ ebb1.setBuildingBlock(bb1);
+ flowsToExecute.add(ebb1);
+ ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
+ BuildingBlock bb2 = new BuildingBlock();
+ bb2.setBpmnFlowName("CreateVfModuleBB");
+ ebb2.setBuildingBlock(bb2);
+ flowsToExecute.add(ebb2);
+ ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
+ BuildingBlock bb3 = new BuildingBlock();
+ bb3.setBpmnFlowName("ActivateVfModuleBB");
+ ebb3.setBuildingBlock(bb3);
+ flowsToExecute.add(ebb3);
+
+ execution.setVariable("flowsToExecute", flowsToExecute);
+ execution.setVariable("gCurrentSequence", 2);
+ doNothing().when(workflowActionBBFailure).updateRequestErrorStatusMessage(isA(DelegateExecution.class));
+
+ workflowActionBBTasks.rollbackExecutionPath(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEquals(ebbs.get(0).getBuildingBlock().getBpmnFlowName(), "DeleteVfModuleBB");
+ assertEquals(ebbs.get(1).getBuildingBlock().getBpmnFlowName(), "UnassignVfModuleBB");
+ assertEquals(0, execution.getVariable("gCurrentSequence"));
+ assertEquals(0, execution.getVariable("retryCount"));
+ }
+
+ @Test
+ public void rollbackExecutionTest() {
+ execution.setVariable("handlingCode", "Rollback");
+ execution.setVariable("isRollback", false);
+ List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
+ ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock();
+ BuildingBlock bb1 = new BuildingBlock();
+ bb1.setBpmnFlowName("AssignServiceInstanceBB");
+ ebb1.setBuildingBlock(bb1);
+ flowsToExecute.add(ebb1);
+ ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
+ BuildingBlock bb2 = new BuildingBlock();
+ bb2.setBpmnFlowName("CreateNetworkCollectionBB");
+ ebb2.setBuildingBlock(bb2);
+ flowsToExecute.add(ebb2);
+ ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
+ BuildingBlock bb3 = new BuildingBlock();
+ bb3.setBpmnFlowName("AssignNetworkBB");
+ ebb3.setBuildingBlock(bb3);
+ flowsToExecute.add(ebb3);
+ ExecuteBuildingBlock ebb4 = new ExecuteBuildingBlock();
+ BuildingBlock bb4 = new BuildingBlock();
+ bb4.setBpmnFlowName("CreateNetworkBB");
+ ebb4.setBuildingBlock(bb4);
+ flowsToExecute.add(ebb4);
+
+ execution.setVariable("flowsToExecute", flowsToExecute);
+ execution.setVariable("gCurrentSequence", 3);
+ doNothing().when(workflowActionBBFailure).updateRequestErrorStatusMessage(isA(DelegateExecution.class));
+
+ workflowActionBBTasks.rollbackExecutionPath(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEquals(ebbs.get(0).getBuildingBlock().getBpmnFlowName(), "UnassignNetworkBB");
+ assertEquals(ebbs.get(1).getBuildingBlock().getBpmnFlowName(), "DeleteNetworkCollectionBB");
+ assertEquals(ebbs.get(2).getBuildingBlock().getBpmnFlowName(), "UnassignServiceInstanceBB");
+ assertEquals(0, execution.getVariable("gCurrentSequence"));
+ }
+
+ @Test
+ public void rollbackExecutionRollbackToAssignedTest() {
+ execution.setVariable("isRollback", false);
+ execution.setVariable("handlingCode", "RollbackToAssigned");
+ List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
+ ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock();
+ BuildingBlock bb1 = new BuildingBlock();
+ bb1.setBpmnFlowName("AssignVfModuleBB");
+ ebb1.setBuildingBlock(bb1);
+ flowsToExecute.add(ebb1);
+ ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
+ BuildingBlock bb2 = new BuildingBlock();
+ bb2.setBpmnFlowName("CreateVfModuleBB");
+ ebb2.setBuildingBlock(bb2);
+ flowsToExecute.add(ebb2);
+ ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
+ BuildingBlock bb3 = new BuildingBlock();
+ bb3.setBpmnFlowName("ActivateVfModuleBB");
+ ebb3.setBuildingBlock(bb3);
+ flowsToExecute.add(ebb3);
+
+ execution.setVariable("flowsToExecute", flowsToExecute);
+ execution.setVariable("gCurrentSequence", 2);
+
+ workflowActionBBTasks.rollbackExecutionPath(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEquals("DeleteVfModuleBB", ebbs.get(0).getBuildingBlock().getBpmnFlowName());
+ assertEquals(0, execution.getVariable("gCurrentSequence"));
+ assertEquals(1, ebbs.size());
+ }
+
+ @Test
+ public void rollbackExecutionRollbackToCreatedTest() {
+ execution.setVariable("isRollback", false);
+ execution.setVariable("handlingCode", "RollbackToCreated");
+ List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
+ ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock();
+ BuildingBlock bb1 = new BuildingBlock();
+ bb1.setBpmnFlowName("AssignVfModuleBB");
+ ebb1.setBuildingBlock(bb1);
+ flowsToExecute.add(ebb1);
+ ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
+ BuildingBlock bb2 = new BuildingBlock();
+ bb2.setBpmnFlowName("CreateVfModuleBB");
+ ebb2.setBuildingBlock(bb2);
+ flowsToExecute.add(ebb2);
+ ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
+ BuildingBlock bb3 = new BuildingBlock();
+ bb3.setBpmnFlowName("ActivateVfModuleBB");
+ ebb3.setBuildingBlock(bb3);
+ flowsToExecute.add(ebb3);
+
+ execution.setVariable("flowsToExecute", flowsToExecute);
+ execution.setVariable("gCurrentSequence", 3);
+
+ workflowActionBBTasks.rollbackExecutionPath(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEquals("DeactivateVfModuleBB", ebbs.get(0).getBuildingBlock().getBpmnFlowName());
+ assertEquals(0, execution.getVariable("gCurrentSequence"));
+ assertEquals(1, ebbs.size());
+ }
+
+ @Test
+ public void checkRetryStatusTest() {
+ String reqId = "reqId123";
+ execution.setVariable("mso-request-id", reqId);
+ doNothing().when(workflowActionBBFailure).updateRequestErrorStatusMessage(isA(DelegateExecution.class));
+ doReturn("6").when(environment).getProperty("mso.rainyDay.maxRetries");
+ execution.setVariable("handlingCode", "Retry");
+ execution.setVariable("retryCount", 1);
+ execution.setVariable("gCurrentSequence", 1);
+ InfraActiveRequests req = new InfraActiveRequests();
+ doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId);
+ workflowActionBBTasks.checkRetryStatus(execution);
+ assertEquals(0, execution.getVariable("gCurrentSequence"));
+ }
+
+ @Test
+ public void checkRetryStatusTestExceededMaxRetries() {
+ String reqId = "reqId123";
+ execution.setVariable("mso-request-id", reqId);
+ doNothing().when(workflowActionBBFailure).updateRequestErrorStatusMessage(isA(DelegateExecution.class));
+ doReturn("6").when(environment).getProperty("mso.rainyDay.maxRetries");
+ execution.setVariable("handlingCode", "Retry");
+ execution.setVariable("retryCount", 6);
+ execution.setVariable("gCurrentSequence", 1);
+ InfraActiveRequests req = new InfraActiveRequests();
+ doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId);
+ try {
+ workflowActionBBTasks.checkRetryStatus(execution);
+ } catch (BpmnError e) {
+ WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
+ assertEquals("Exceeded maximum retries. Ending flow with status Abort", exception.getErrorMessage());
+ }
+ }
+
+ @Test
+ public void checkRetryStatusNoRetryTest() {
+ String reqId = "reqId123";
+ execution.setVariable("mso-request-id", reqId);
+ execution.setVariable("retryCount", 3);
+ execution.setVariable("handlingCode", "Success");
+ execution.setVariable("gCurrentSequence", 1);
+ InfraActiveRequests req = new InfraActiveRequests();
+ doReturn(req).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId);
+ workflowActionBBTasks.checkRetryStatus(execution);
+ assertEquals(0, execution.getVariable("retryCount"));
+ }
+
+ @Test
+ public void updateInstanceId() {
+ String reqId = "req123";
+ String instanceId = "123123123";
+ execution.setVariable("mso-request-id", reqId);
+ execution.setVariable("resourceId", instanceId);
+ execution.setVariable("resourceType", WorkflowType.SERVICE);
+ doReturn(reqMock).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId);
+ doNothing().when(requestsDbClient).updateInfraActiveRequests(isA(InfraActiveRequests.class));
+ workflowActionBBTasks.updateInstanceId(execution);
+ Mockito.verify(reqMock, Mockito.times(1)).setServiceInstanceId(instanceId);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksUpdateReqDbTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksUpdateReqDbTest.java
index 0f106ad913..9c3f0c6f0b 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksUpdateReqDbTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksUpdateReqDbTest.java
@@ -26,10 +26,8 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
-
import java.util.ArrayList;
import java.util.List;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
import org.junit.Before;
@@ -43,52 +41,53 @@ import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
import org.onap.so.db.request.beans.InfraActiveRequests;
-public class WorkflowActionBBTasksUpdateReqDbTest extends BaseTaskTest{
+public class WorkflowActionBBTasksUpdateReqDbTest extends BaseTaskTest {
+
+ protected WorkflowAction workflowAction = new WorkflowAction();
+
+ @Spy
+ @InjectMocks
+ protected WorkflowActionBBTasks workflowActionBBTasks;
+
+ private DelegateExecution execution;
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Before
+ public void before() throws Exception {
+ execution = new DelegateExecutionFake();
+ org.onap.aai.domain.yang.ServiceInstance servInstance = new org.onap.aai.domain.yang.ServiceInstance();
+ servInstance.setServiceInstanceId("TEST");
+ when(bbSetupUtils.getAAIServiceInstanceByName(anyString(), any())).thenReturn(servInstance);
+ workflowAction.setBbInputSetupUtils(bbSetupUtils);
+ workflowAction.setBbInputSetup(bbInputSetup);
+ }
- protected WorkflowAction workflowAction = new WorkflowAction();
-
- @Spy
- @InjectMocks
- protected WorkflowActionBBTasks workflowActionBBTasks;
-
- private DelegateExecution execution;
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Before
- public void before() throws Exception {
- execution = new DelegateExecutionFake();
- org.onap.aai.domain.yang.ServiceInstance servInstance = new org.onap.aai.domain.yang.ServiceInstance();
- servInstance.setServiceInstanceId("TEST");
- when(bbSetupUtils.getAAIServiceInstanceByName(anyString(), any())).thenReturn(servInstance);
- workflowAction.setBbInputSetupUtils(bbSetupUtils);
- workflowAction.setBbInputSetup(bbInputSetup);
- }
-
- @Test
- public void getUpdatedRequestTest() throws Exception{
- List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
- ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock();
- BuildingBlock bb1 = new BuildingBlock();
- bb1.setBpmnFlowName("CreateNetworkBB");
- flowsToExecute.add(ebb1);
- ebb1.setBuildingBlock(bb1);
- ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
- BuildingBlock bb2 = new BuildingBlock();
- bb2.setBpmnFlowName("ActivateNetworkBB");
- flowsToExecute.add(ebb2);
- ebb2.setBuildingBlock(bb2);
- String requestId = "requestId";
- execution.setVariable("mso-request-id", requestId);
- execution.setVariable("flowsToExecute", flowsToExecute);
- int currentSequence = 2;
- String expectedStatusMessage = "Execution of CreateNetworkBB has completed successfully, next invoking ActivateNetworkBB (Execution Path progress: BBs completed = 1; BBs remaining = 1).";
- Long expectedLong = new Long(52);
- InfraActiveRequests mockedRequest = new InfraActiveRequests();
- doReturn(mockedRequest).when(requestsDbClient).getInfraActiveRequestbyRequestId(isA(String.class));
- InfraActiveRequests actual = workflowActionBBTasks.getUpdatedRequest(execution, currentSequence);
- assertEquals(expectedStatusMessage, actual.getFlowStatus());
- assertEquals(expectedLong, actual.getProgress());
- }
+ @Test
+ public void getUpdatedRequestTest() throws Exception {
+ List<ExecuteBuildingBlock> flowsToExecute = new ArrayList();
+ ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock();
+ BuildingBlock bb1 = new BuildingBlock();
+ bb1.setBpmnFlowName("CreateNetworkBB");
+ flowsToExecute.add(ebb1);
+ ebb1.setBuildingBlock(bb1);
+ ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
+ BuildingBlock bb2 = new BuildingBlock();
+ bb2.setBpmnFlowName("ActivateNetworkBB");
+ flowsToExecute.add(ebb2);
+ ebb2.setBuildingBlock(bb2);
+ String requestId = "requestId";
+ execution.setVariable("mso-request-id", requestId);
+ execution.setVariable("flowsToExecute", flowsToExecute);
+ int currentSequence = 2;
+ String expectedStatusMessage =
+ "Execution of CreateNetworkBB has completed successfully, next invoking ActivateNetworkBB (Execution Path progress: BBs completed = 1; BBs remaining = 1).";
+ Long expectedLong = new Long(52);
+ InfraActiveRequests mockedRequest = new InfraActiveRequests();
+ doReturn(mockedRequest).when(requestsDbClient).getInfraActiveRequestbyRequestId(isA(String.class));
+ InfraActiveRequests actual = workflowActionBBTasks.getUpdatedRequest(execution, currentSequence);
+ assertEquals(expectedStatusMessage, actual.getFlowStatus());
+ assertEquals(expectedLong, actual.getProgress());
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java
index 87e6daa58a..ad1238b86f 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java
@@ -30,7 +30,6 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.MalformedURLException;
@@ -97,687 +96,808 @@ import org.onap.so.serviceinstancebeans.SubscriberInfo;
import org.springframework.core.env.Environment;
public class WorkflowActionTest extends BaseTaskTest {
-
-
- @Mock
- protected Environment environment;
- @InjectMocks
- protected WorkflowAction workflowAction;
- private DelegateExecution execution;
-
-
- @InjectMocks
- @Spy
- protected WorkflowAction SPY_workflowAction;
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- private String RESOURCE_PATH = "src/test/resources/__files/";
-
- @Before
- public void before() throws Exception {
- execution = new DelegateExecutionFake();
- org.onap.aai.domain.yang.ServiceInstance servInstance = new org.onap.aai.domain.yang.ServiceInstance();
- servInstance.setServiceInstanceId("TEST");
- when(bbSetupUtils.getAAIServiceInstanceByName(anyString(), anyObject())).thenReturn(servInstance);
- workflowAction.setBbInputSetupUtils(bbSetupUtils);
- workflowAction.setBbInputSetup(bbInputSetup);
- }
- /**
- * ALACARTE TESTS
- */
- @Test
- public void selectExecutionListALaCarteNetworkCreateTest() throws Exception{
- String gAction = "createInstance";
- String resource = "Network";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/networks/123");
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("AssignNetwork1802BB","CreateNetworkBB","ActivateNetworkBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,true, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"AssignNetwork1802BB","CreateNetworkBB","ActivateNetworkBB");
- }
-
- @Test
- public void selectExecutionListALaCarteNetworkDeleteTest() throws Exception{
- String gAction = "deleteInstance";
- String resource = "Network";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/networks/123");
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("DeactivateNetworkBB","DeleteNetworkBB","UnassignNetwork1802BB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,true,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"DeactivateNetworkBB","DeleteNetworkBB","UnassignNetwork1802BB");
- }
-
- @Test
- public void selectExecutionListALaCarteServiceCreateTest() throws Exception{
- String gAction = "createInstance";
- String resource = "Service";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB","ActivateServiceInstanceBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,true,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"AssignServiceInstanceBB","ActivateServiceInstanceBB");
- }
-
- /**
- * SERVICE MACRO TESTS
- */
- @Test
- public void selectExecutionListServiceMacroAssignTest() throws Exception{
- String gAction = "assignInstance";
- String resource = "Service";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB","AssignNetworkBB","AssignVnfBB","AssignVolumeGroupBB","AssignVfModuleBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
- vfModuleCustomization.setModelCustomizationUUID("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
- HeatEnvironment volumeHeatEnv = new HeatEnvironment();
- vfModuleCustomization.setVolumeHeatEnv(volumeHeatEnv);
- org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule();
- HeatTemplate volumeHeatTemplate = new HeatTemplate();
- vfModule.setVolumeHeatTemplate(volumeHeatTemplate);
- vfModuleCustomization.setVfModule(vfModule);
-
- VfModuleCustomization vfModuleCustomization2 = new VfModuleCustomization();
- vfModuleCustomization2.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
- HeatEnvironment heatEnvironment = new HeatEnvironment();
- vfModuleCustomization2.setHeatEnvironment(heatEnvironment);
- org.onap.so.db.catalog.beans.VfModule vfModule2 = new org.onap.so.db.catalog.beans.VfModule();
- HeatTemplate moduleHeatTemplate = new HeatTemplate();
- vfModule2.setModuleHeatTemplate(moduleHeatTemplate);
- vfModuleCustomization2.setVfModule(vfModule2);
-
- VfModuleCustomization vfModuleCustomization3 = vfModuleCustomization2;
- vfModuleCustomization3.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f")).thenReturn(vfModuleCustomization);
- when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8")).thenReturn(vfModuleCustomization2);
- when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("da4d4327-fb7d-4311-ac7a-be7ba60cf969")).thenReturn(vfModuleCustomization3);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"AssignServiceInstanceBB","AssignVnfBB","AssignVolumeGroupBB","AssignVfModuleBB","AssignVfModuleBB","AssignVfModuleBB");
- }
-
- @Test
- public void selectExecutionListServiceMacroAssignNoCloudTest() throws Exception{
- String gAction = "assignInstance";
- String resource = "Service";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssignNoCloud.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB","AssignNetworkBB","AssignVnfBB","AssignVolumeGroupBB","AssignVfModuleBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
- vfModuleCustomization.setModelCustomizationUUID("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
- HeatEnvironment volumeHeatEnv = new HeatEnvironment();
- vfModuleCustomization.setVolumeHeatEnv(volumeHeatEnv);
- org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule();
- HeatTemplate volumeHeatTemplate = new HeatTemplate();
- vfModule.setVolumeHeatTemplate(volumeHeatTemplate);
- vfModuleCustomization.setVfModule(vfModule);
-
- VfModuleCustomization vfModuleCustomization2 = new VfModuleCustomization();
- vfModuleCustomization2.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
- HeatEnvironment heatEnvironment = new HeatEnvironment();
- vfModuleCustomization2.setHeatEnvironment(heatEnvironment);
- org.onap.so.db.catalog.beans.VfModule vfModule2 = new org.onap.so.db.catalog.beans.VfModule();
- HeatTemplate moduleHeatTemplate = new HeatTemplate();
- vfModule2.setModuleHeatTemplate(moduleHeatTemplate);
- vfModuleCustomization2.setVfModule(vfModule2);
-
- VfModuleCustomization vfModuleCustomization3 = vfModuleCustomization2;
- vfModuleCustomization3.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
-
- when(environment.getProperty("org.onap.so.cloud-owner")).thenReturn("att-aic");
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"att-aic")).thenReturn(northBoundRequest);
- when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f")).thenReturn(vfModuleCustomization);
- when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8")).thenReturn(vfModuleCustomization2);
- when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("da4d4327-fb7d-4311-ac7a-be7ba60cf969")).thenReturn(vfModuleCustomization3);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"AssignServiceInstanceBB","AssignVnfBB","AssignVolumeGroupBB","AssignVfModuleBB","AssignVfModuleBB","AssignVfModuleBB");
- }
-
- @Test
- public void selectExecutionListServiceMacroActivateTest() throws Exception{
- String gAction = "activateInstance";
- String resource = "Service";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/si0");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("CreateNetworkBB","ActivateNetworkBB","CreateVolumeGroupBB","ActivateVolumeGroupBB","CreateVfModuleBB","ActivateVfModuleBB"
- ,"ActivateVnfBB","ActivateServiceInstanceBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- ServiceInstance serviceInstanceAAI = new ServiceInstance();
- serviceInstanceAAI.setServiceInstanceId("si0");
- org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = new org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance();
- org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf = new org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf();
- vnf.setVnfId("vnf0");
-
- org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule = new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
- vfModule.setVfModuleId("vfModule0");
- vnf.getVfModules().add(vfModule);
- org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule2 = new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
- vfModule2.setVfModuleId("vfModule1");
- vnf.getVfModules().add(vfModule2);
-
- org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup = new org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup();
- volumeGroup.setVolumeGroupId("volumeGroup0");
- vnf.getVolumeGroups().add(volumeGroup);
-
- serviceInstanceMSO.getVnfs().add(vnf);
-
- doReturn(serviceInstanceAAI).when(bbSetupUtils).getAAIServiceInstanceById("si0");
- doReturn(serviceInstanceMSO).when(bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"CreateVolumeGroupBB","ActivateVolumeGroupBB","CreateVfModuleBB","CreateVfModuleBB","ActivateVfModuleBB","ActivateVfModuleBB","ActivateVnfBB","ActivateServiceInstanceBB");
- assertEquals("volumeGroup0", ebbs.get(0).getWorkflowResourceIds().getVolumeGroupId());
- assertEquals("volumeGroup0", ebbs.get(1).getWorkflowResourceIds().getVolumeGroupId());
- assertEquals("vfModule0", ebbs.get(2).getWorkflowResourceIds().getVfModuleId());
- assertEquals("vfModule1", ebbs.get(3).getWorkflowResourceIds().getVfModuleId());
- assertEquals("vfModule0", ebbs.get(4).getWorkflowResourceIds().getVfModuleId());
- assertEquals("vfModule1", ebbs.get(5).getWorkflowResourceIds().getVfModuleId());
- assertEquals("vnf0", ebbs.get(6).getWorkflowResourceIds().getVnfId());
- assertEquals("si0", ebbs.get(7).getWorkflowResourceIds().getServiceInstanceId());
-
- }
-
- @Test
- public void selectExecutionListServiceMacroDeactivateTest() throws Exception{
- String gAction = "deactivateInstance";
- String resource = "Service";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("DeactivateServiceInstanceBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEquals(ebbs.get(0).getBuildingBlock().getBpmnFlowName(),"DeactivateServiceInstanceBB");
- }
-
- @Test
- public void selectExecutionListServiceMacroEmptyServiceTest() throws Exception{
- String gAction = "createInstance";
- String resource = "Service";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- northBoundRequest.setIsToplevelflow(true);
- List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB","CreateNetworkCollectionBB","AssignNetworkBB","AssignVnfBB","AssignVolumeGroupBB","AssignVfModuleBB"
- ,"CreateNetworkBB","ActivateNetworkBB","CreateVolumeGroupBB","ActivateVolumeGroupBB","CreateVfModuleBB","ActivateVfModuleBB","AssignFabricConfigurationBB","ActivateFabricConfigurationBB"
- ,"ActivateVnfBB","ActivateNetworkCollectionBB","ActivateServiceInstanceBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- Service service = new Service();
- doReturn(service).when(catalogDbClient).getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a");
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"AssignServiceInstanceBB","ActivateServiceInstanceBB");
- }
-
- @Test
- public void selectExecutionListServiceMacroCreateJustNetworkTest() throws Exception{
- String gAction = "createInstance";
- String resource = "Service";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- northBoundRequest.setIsToplevelflow(true);
- List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB","CreateNetworkCollectionBB","AssignNetworkBB","AssignVnfBB","AssignVolumeGroupBB","AssignVfModuleBB"
- ,"CreateNetworkBB","ActivateNetworkBB","CreateVolumeGroupBB","ActivateVolumeGroupBB","CreateVfModuleBB","ActivateVfModuleBB","AssignFabricConfigurationBB","ActivateFabricConfigurationBB"
- ,"ActivateVnfBB","ActivateNetworkCollectionBB","ActivateServiceInstanceBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- Service service = new Service();
- NetworkResourceCustomization networkCustomization = new NetworkResourceCustomization();
- networkCustomization.setModelCustomizationUUID("1234");
- service.getNetworkCustomizations().add(networkCustomization);
- doReturn(service).when(catalogDbClient).getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a");
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"AssignServiceInstanceBB","AssignNetworkBB","CreateNetworkBB","ActivateNetworkBB","ActivateServiceInstanceBB");
- }
-
- @Test
- public void selectExecutionListServiceMacroCreateWithNetworkCollectionTest() throws Exception{
- String gAction = "createInstance";
- String resource = "Service";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- northBoundRequest.setIsToplevelflow(true);
- List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB","CreateNetworkCollectionBB","AssignNetworkBB","AssignVnfBB","AssignVolumeGroupBB","AssignVfModuleBB"
- ,"CreateNetworkBB","ActivateNetworkBB","CreateVolumeGroupBB","ActivateVolumeGroupBB","CreateVfModuleBB","ActivateVfModuleBB","AssignFabricConfigurationBB","ActivateFabricConfigurationBB"
- ,"ActivateVnfBB","ActivateNetworkCollectionBB","ActivateServiceInstanceBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- Service service = new Service();
- List<NetworkResourceCustomization> networkCustomizations = new ArrayList<>();
- NetworkResourceCustomization networkCust = new NetworkResourceCustomization();
- networkCust.setModelCustomizationUUID("123");
- networkCustomizations.add(networkCust);
- service.setNetworkCustomizations(networkCustomizations);
- NetworkCollectionResourceCustomization collectionResourceCustomization = new NetworkCollectionResourceCustomization();
- collectionResourceCustomization.setModelCustomizationUUID("123");
-
- CollectionResource collectionResource = new CollectionResource();
- collectionResource.setToscaNodeType("NetworkCollection");
- InstanceGroup instanceGroup = new InstanceGroup();
- instanceGroup.setToscaNodeType("NetworkCollectionResource");
- instanceGroup.setCollectionNetworkResourceCustomizations(new ArrayList<>());
- CollectionNetworkResourceCustomization collectionNetworkResourceCust = new CollectionNetworkResourceCustomization();
- collectionNetworkResourceCust.setModelCustomizationUUID("123");
- collectionNetworkResourceCust.setNetworkResourceCustomization(collectionResourceCustomization);
- instanceGroup.getCollectionNetworkResourceCustomizations().add(collectionNetworkResourceCust );
- List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupCustomizations = new ArrayList<>();
- CollectionResourceInstanceGroupCustomization collectionInstanceGroupCustomization = new CollectionResourceInstanceGroupCustomization();
- collectionInstanceGroupCustomization.setModelCustomizationUUID("123");
- collectionInstanceGroupCustomization.setSubInterfaceNetworkQuantity(3);
- collectionInstanceGroupCustomizations.add(collectionInstanceGroupCustomization);
- collectionInstanceGroupCustomization.setInstanceGroup(instanceGroup);
- collectionInstanceGroupCustomization.setCollectionResourceCust(collectionResourceCustomization);
- instanceGroup.setCollectionInstanceGroupCustomizations(collectionInstanceGroupCustomizations);
- collectionResource.setInstanceGroup(instanceGroup);
- collectionResourceCustomization.setCollectionResource(collectionResource);;
- service.getCollectionResourceCustomizations().add(collectionResourceCustomization);
- doReturn(service).when(catalogDbClient).getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a");
- doReturn(collectionResourceCustomization).when(catalogDbClient).getNetworkCollectionResourceCustomizationByID("123");
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"AssignServiceInstanceBB","CreateNetworkCollectionBB","AssignNetworkBB","CreateNetworkBB","ActivateNetworkBB","AssignNetworkBB","CreateNetworkBB","ActivateNetworkBB"
- ,"AssignNetworkBB","CreateNetworkBB","ActivateNetworkBB","ActivateNetworkCollectionBB","ActivateServiceInstanceBB");
- assertEquals("Network id not empty", !ebbs.get(2).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
- assertEquals("Network id not empty", !ebbs.get(3).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
- assertEquals("Network id not empty", !ebbs.get(4).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
- assertEquals("Network id same for AssignNetworkBB CreateNetworkBB ActivateNetworkBB",
- ebbs.get(2).getWorkflowResourceIds().getNetworkId() == ebbs.get(3).getWorkflowResourceIds().getNetworkId()
- && ebbs.get(3).getWorkflowResourceIds().getNetworkId() == ebbs.get(4).getWorkflowResourceIds().getNetworkId(), true);
- assertEquals("Network id not empty", !ebbs.get(5).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
- assertEquals("Network id not empty", !ebbs.get(6).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
- assertEquals("Network id not empty", !ebbs.get(7).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
- assertEquals("Network id same for AssignNetworkBB CreateNetworkBB ActivateNetworkBB",
- ebbs.get(5).getWorkflowResourceIds().getNetworkId() == ebbs.get(6).getWorkflowResourceIds().getNetworkId()
- && ebbs.get(6).getWorkflowResourceIds().getNetworkId() == ebbs.get(7).getWorkflowResourceIds().getNetworkId(), true);
- assertEquals("Network id not empty", !ebbs.get(8).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
- assertEquals("Network id not empty", !ebbs.get(9).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
- assertEquals("Network id not empty", !ebbs.get(10).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
- assertEquals("Network id same for AssignNetworkBB CreateNetworkBB ActivateNetworkBB",
- ebbs.get(8).getWorkflowResourceIds().getNetworkId() == ebbs.get(9).getWorkflowResourceIds().getNetworkId()
- && ebbs.get(9).getWorkflowResourceIds().getNetworkId() == ebbs.get(10).getWorkflowResourceIds().getNetworkId(), true);
- }
-
- @Test
- public void selectExecutionListServiceMacroCreateWithUserParams() throws Exception{
- String gAction = "createInstance";
- String resource = "Service";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB","CreateNetworkCollectionBB","AssignNetworkBB","AssignVnfBB","AssignVolumeGroupBB","AssignVfModuleBB"
- ,"CreateNetworkBB","ActivateNetworkBB","CreateVolumeGroupBB","ActivateVolumeGroupBB","CreateVfModuleBB","ActivateVfModuleBB","AssignFabricConfigurationBB","ActivateFabricConfigurationBB"
- ,"ActivateVnfBB","ActivateNetworkCollectionBB","ActivateServiceInstanceBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- Service service = new Service();
- service.setModelUUID("3c40d244-808e-42ca-b09a-256d83d19d0a");
-
- VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
- vfModuleCustomization.setModelCustomizationUUID("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
- HeatEnvironment volumeHeatEnv = new HeatEnvironment();
- vfModuleCustomization.setVolumeHeatEnv(volumeHeatEnv);
- org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule();
- HeatTemplate volumeHeatTemplate = new HeatTemplate();
- vfModule.setVolumeHeatTemplate(volumeHeatTemplate);
- vfModuleCustomization.setVfModule(vfModule);
-
- VfModuleCustomization vfModuleCustomization2 = new VfModuleCustomization();
- vfModuleCustomization2.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
- HeatEnvironment heatEnvironment = new HeatEnvironment();
- vfModuleCustomization2.setHeatEnvironment(heatEnvironment);
- org.onap.so.db.catalog.beans.VfModule vfModule2 = new org.onap.so.db.catalog.beans.VfModule();
- HeatTemplate moduleHeatTemplate = new HeatTemplate();
- vfModule2.setModuleHeatTemplate(moduleHeatTemplate);
- vfModuleCustomization2.setVfModule(vfModule2);
-
- VfModuleCustomization vfModuleCustomization3 = vfModuleCustomization2;
- vfModuleCustomization3.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f")).thenReturn(vfModuleCustomization);
- when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8")).thenReturn(vfModuleCustomization2);
- when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("da4d4327-fb7d-4311-ac7a-be7ba60cf969")).thenReturn(vfModuleCustomization3);
- when(catalogDbClient.getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a")).thenReturn(service);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"AssignServiceInstanceBB","AssignVnfBB","AssignVolumeGroupBB","AssignVfModuleBB","AssignVfModuleBB","AssignVfModuleBB","CreateVolumeGroupBB"
- ,"ActivateVolumeGroupBB","CreateVfModuleBB","CreateVfModuleBB","CreateVfModuleBB","ActivateVfModuleBB","ActivateVfModuleBB","ActivateVfModuleBB","ActivateVnfBB","ActivateServiceInstanceBB");
- assertEquals(3,ebbs.get(0).getWorkflowResourceIds().getServiceInstanceId().length());
- int randomUUIDLength = UUID.randomUUID().toString().length();
- assertEquals(randomUUIDLength,ebbs.get(1).getWorkflowResourceIds().getVnfId().length());
- assertEquals(randomUUIDLength,ebbs.get(2).getWorkflowResourceIds().getVolumeGroupId().length());
- assertEquals(randomUUIDLength,ebbs.get(3).getWorkflowResourceIds().getVfModuleId().length());
- assertEquals(randomUUIDLength,ebbs.get(4).getWorkflowResourceIds().getVfModuleId().length());
- assertEquals(randomUUIDLength,ebbs.get(5).getWorkflowResourceIds().getVfModuleId().length());
- assertEquals(randomUUIDLength,ebbs.get(6).getWorkflowResourceIds().getVolumeGroupId().length());
- assertEquals(randomUUIDLength,ebbs.get(7).getWorkflowResourceIds().getVolumeGroupId().length());
- assertEquals(randomUUIDLength,ebbs.get(8).getWorkflowResourceIds().getVfModuleId().length());
- assertEquals(randomUUIDLength,ebbs.get(9).getWorkflowResourceIds().getVfModuleId().length());
- assertEquals(randomUUIDLength,ebbs.get(10).getWorkflowResourceIds().getVfModuleId().length());
- assertEquals(randomUUIDLength,ebbs.get(11).getWorkflowResourceIds().getVfModuleId().length());
- assertEquals(randomUUIDLength,ebbs.get(12).getWorkflowResourceIds().getVfModuleId().length());
- assertEquals(randomUUIDLength,ebbs.get(13).getWorkflowResourceIds().getVfModuleId().length());
- assertEquals(randomUUIDLength,ebbs.get(14).getWorkflowResourceIds().getVnfId().length());
- assertEquals(3,ebbs.get(0).getWorkflowResourceIds().getServiceInstanceId().length());
- assertEquals(true, execution.getVariable("homing"));
- }
-
- @Test
- public void selectExecutionListServiceMacroDeleteTest() throws Exception{
- String gAction = "deleteInstance";
- String resource = "Service";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("DeactivateVfModuleBB","DeleteVfModuleBB","DeactivateVolumeGroupBB","DeleteVolumeGroupBB","DeactivateVnfBB","DeactivateNetworkBB"
- ,"DeleteNetworkBB","DeleteNetworkCollectionBB","DeactivateServiceInstanceBB","UnassignVfModuleBB","UnassignVolumeGroupBB","UnassignVnfBB","UnassignNetworkBB","UnassignServiceInstanceBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- ServiceInstance serviceInstanceAAI = new ServiceInstance();
- serviceInstanceAAI.setServiceInstanceId("aaisi123");
- org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = new org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance();
- org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf = new org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf();
- vnf.setVnfId("vnfId123");
-
- org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule = new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
- vfModule.setVfModuleId("vfModule1");
- vnf.getVfModules().add(vfModule);
- org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule2 = new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
- vfModule2.setVfModuleId("vfModule2");
- vnf.getVfModules().add(vfModule2);
-
- org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup = new org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup();
- volumeGroup.setVolumeGroupId("vg123");
- vnf.getVolumeGroups().add(volumeGroup);
-
- serviceInstanceMSO.getVnfs().add(vnf);
-
- doReturn(serviceInstanceAAI).when(bbSetupUtils).getAAIServiceInstanceById("123");
- doReturn(serviceInstanceMSO).when(bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"DeactivateVfModuleBB","DeactivateVfModuleBB","DeleteVfModuleBB","DeleteVfModuleBB","DeactivateVolumeGroupBB","DeleteVolumeGroupBB","DeactivateVnfBB"
- ,"DeactivateServiceInstanceBB","UnassignVfModuleBB","UnassignVfModuleBB","UnassignVolumeGroupBB","UnassignVnfBB","UnassignServiceInstanceBB");
- }
-
- @Test
- public void selectExecutionListServiceMacroUnassignTest() throws Exception{
- String gAction = "unassignInstance";
- String resource = "Service";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("UnassignVfModuleBB","UnassignVolumeGroupBB","UnassignVnfBB","UnassignNetworkBB","UnassignServiceInstanceBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- ServiceInstance serviceInstanceAAI = new ServiceInstance();
- serviceInstanceAAI.setServiceInstanceId("aaisi123");
- org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = new org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance();
- org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf = new org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf();
- vnf.setVnfId("vnfId123");
-
- org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule = new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
- vfModule.setVfModuleId("vfModule1");
- vnf.getVfModules().add(vfModule);
- org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule2 = new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
- vfModule2.setVfModuleId("vfModule2");
- vnf.getVfModules().add(vfModule2);
-
- org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup = new org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup();
- volumeGroup.setVolumeGroupId("vg123");
- vnf.getVolumeGroups().add(volumeGroup);
-
- serviceInstanceMSO.getVnfs().add(vnf);
-
- doReturn(serviceInstanceAAI).when(bbSetupUtils).getAAIServiceInstanceById("123");
- doReturn(serviceInstanceMSO).when(bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"UnassignVfModuleBB","UnassignVfModuleBB","UnassignVolumeGroupBB","UnassignVnfBB","UnassignServiceInstanceBB");
- }
-
- @Test
- public void selectExecutionListServiceMacroDeleteNetworkCollectionTest() throws Exception{
- String gAction = "deleteInstance";
- String resource = "Service";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("DeactivateVfModuleBB","DeleteVfModuleBB","DeactivateVolumeGroupBB","DeleteVolumeGroupBB","DeactivateVnfBB","DeactivateNetworkBB"
- ,"DeleteNetworkBB","DeleteNetworkCollectionBB","DeactivateServiceInstanceBB","UnassignVfModuleBB","UnassignVolumeGroupBB","UnassignVnfBB","UnassignNetworkBB","UnassignServiceInstanceBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- ServiceInstance serviceInstanceAAI = new ServiceInstance();
- serviceInstanceAAI.setServiceInstanceId("aaisi123");
- org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = new org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance();
-
- org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network = new org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network();
- network.setNetworkId("123");
- serviceInstanceMSO.getNetworks().add(network);
- org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network2 = new org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network();
- network2.setNetworkId("321");
- serviceInstanceMSO.getNetworks().add(network2);
-
- Collection collection = new Collection();
- serviceInstanceMSO.setCollection(collection);
-
- doReturn(serviceInstanceAAI).when(bbSetupUtils).getAAIServiceInstanceById("123");
- doReturn(serviceInstanceMSO).when(bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"DeactivateNetworkBB","DeleteNetworkBB","UnassignNetworkBB","DeactivateNetworkBB","DeleteNetworkBB","UnassignNetworkBB","DeleteNetworkCollectionBB"
- ,"DeactivateServiceInstanceBB","UnassignServiceInstanceBB");
- }
-
+
+
+ @Mock
+ protected Environment environment;
+ @InjectMocks
+ protected WorkflowAction workflowAction;
+ private DelegateExecution execution;
+
+
+ @InjectMocks
+ @Spy
+ protected WorkflowAction SPY_workflowAction;
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ private String RESOURCE_PATH = "src/test/resources/__files/";
+
+ @Before
+ public void before() throws Exception {
+ execution = new DelegateExecutionFake();
+ org.onap.aai.domain.yang.ServiceInstance servInstance = new org.onap.aai.domain.yang.ServiceInstance();
+ servInstance.setServiceInstanceId("TEST");
+ when(bbSetupUtils.getAAIServiceInstanceByName(anyString(), anyObject())).thenReturn(servInstance);
+ workflowAction.setBbInputSetupUtils(bbSetupUtils);
+ workflowAction.setBbInputSetup(bbInputSetup);
+ }
+
+ /**
+ * ALACARTE TESTS
+ */
+ @Test
+ public void selectExecutionListALaCarteNetworkCreateTest() throws Exception {
+ String gAction = "createInstance";
+ String resource = "Network";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/networks/123");
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows =
+ createFlowList("AssignNetwork1802BB", "CreateNetworkBB", "ActivateNetworkBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ true, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "AssignNetwork1802BB", "CreateNetworkBB", "ActivateNetworkBB");
+ }
+
+ @Test
+ public void selectExecutionListALaCarteNetworkDeleteTest() throws Exception {
+ String gAction = "deleteInstance";
+ String resource = "Network";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/networks/123");
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows =
+ createFlowList("DeactivateNetworkBB", "DeleteNetworkBB", "UnassignNetwork1802BB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ true, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "DeactivateNetworkBB", "DeleteNetworkBB", "UnassignNetwork1802BB");
+ }
+
+ @Test
+ public void selectExecutionListALaCarteServiceCreateTest() throws Exception {
+ String gAction = "createInstance";
+ String resource = "Service";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB", "ActivateServiceInstanceBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ true, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "AssignServiceInstanceBB", "ActivateServiceInstanceBB");
+ }
+
+ /**
+ * SERVICE MACRO TESTS
+ */
+ @Test
+ public void selectExecutionListServiceMacroAssignTest() throws Exception {
+ String gAction = "assignInstance";
+ String resource = "Service";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB", "AssignNetworkBB", "AssignVnfBB",
+ "AssignVolumeGroupBB", "AssignVfModuleBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
+ vfModuleCustomization.setModelCustomizationUUID("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
+ HeatEnvironment volumeHeatEnv = new HeatEnvironment();
+ vfModuleCustomization.setVolumeHeatEnv(volumeHeatEnv);
+ org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule();
+ HeatTemplate volumeHeatTemplate = new HeatTemplate();
+ vfModule.setVolumeHeatTemplate(volumeHeatTemplate);
+ vfModuleCustomization.setVfModule(vfModule);
+
+ VfModuleCustomization vfModuleCustomization2 = new VfModuleCustomization();
+ vfModuleCustomization2.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
+ HeatEnvironment heatEnvironment = new HeatEnvironment();
+ vfModuleCustomization2.setHeatEnvironment(heatEnvironment);
+ org.onap.so.db.catalog.beans.VfModule vfModule2 = new org.onap.so.db.catalog.beans.VfModule();
+ HeatTemplate moduleHeatTemplate = new HeatTemplate();
+ vfModule2.setModuleHeatTemplate(moduleHeatTemplate);
+ vfModuleCustomization2.setVfModule(vfModule2);
+
+ VfModuleCustomization vfModuleCustomization3 = vfModuleCustomization2;
+ vfModuleCustomization3.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f"))
+ .thenReturn(vfModuleCustomization);
+ when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8"))
+ .thenReturn(vfModuleCustomization2);
+ when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("da4d4327-fb7d-4311-ac7a-be7ba60cf969"))
+ .thenReturn(vfModuleCustomization3);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "AssignServiceInstanceBB", "AssignVnfBB", "AssignVolumeGroupBB",
+ "AssignVfModuleBB", "AssignVfModuleBB", "AssignVfModuleBB");
+ }
+
+ @Test
+ public void selectExecutionListServiceMacroAssignNoCloudTest() throws Exception {
+ String gAction = "assignInstance";
+ String resource = "Service";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest = new String(
+ Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssignNoCloud.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB", "AssignNetworkBB", "AssignVnfBB",
+ "AssignVolumeGroupBB", "AssignVfModuleBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
+ vfModuleCustomization.setModelCustomizationUUID("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
+ HeatEnvironment volumeHeatEnv = new HeatEnvironment();
+ vfModuleCustomization.setVolumeHeatEnv(volumeHeatEnv);
+ org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule();
+ HeatTemplate volumeHeatTemplate = new HeatTemplate();
+ vfModule.setVolumeHeatTemplate(volumeHeatTemplate);
+ vfModuleCustomization.setVfModule(vfModule);
+
+ VfModuleCustomization vfModuleCustomization2 = new VfModuleCustomization();
+ vfModuleCustomization2.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
+ HeatEnvironment heatEnvironment = new HeatEnvironment();
+ vfModuleCustomization2.setHeatEnvironment(heatEnvironment);
+ org.onap.so.db.catalog.beans.VfModule vfModule2 = new org.onap.so.db.catalog.beans.VfModule();
+ HeatTemplate moduleHeatTemplate = new HeatTemplate();
+ vfModule2.setModuleHeatTemplate(moduleHeatTemplate);
+ vfModuleCustomization2.setVfModule(vfModule2);
+
+ VfModuleCustomization vfModuleCustomization3 = vfModuleCustomization2;
+ vfModuleCustomization3.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
+
+ when(environment.getProperty("org.onap.so.cloud-owner")).thenReturn("att-aic");
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "att-aic")).thenReturn(northBoundRequest);
+ when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f"))
+ .thenReturn(vfModuleCustomization);
+ when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8"))
+ .thenReturn(vfModuleCustomization2);
+ when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("da4d4327-fb7d-4311-ac7a-be7ba60cf969"))
+ .thenReturn(vfModuleCustomization3);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "AssignServiceInstanceBB", "AssignVnfBB", "AssignVolumeGroupBB",
+ "AssignVfModuleBB", "AssignVfModuleBB", "AssignVfModuleBB");
+ }
+
+ @Test
+ public void selectExecutionListServiceMacroActivateTest() throws Exception {
+ String gAction = "activateInstance";
+ String resource = "Service";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/si0");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows =
+ createFlowList("CreateNetworkBB", "ActivateNetworkBB", "CreateVolumeGroupBB", "ActivateVolumeGroupBB",
+ "CreateVfModuleBB", "ActivateVfModuleBB", "ActivateVnfBB", "ActivateServiceInstanceBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ ServiceInstance serviceInstanceAAI = new ServiceInstance();
+ serviceInstanceAAI.setServiceInstanceId("si0");
+ org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance();
+ org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf();
+ vnf.setVnfId("vnf0");
+
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
+ vfModule.setVfModuleId("vfModule0");
+ vnf.getVfModules().add(vfModule);
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule2 =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
+ vfModule2.setVfModuleId("vfModule1");
+ vnf.getVfModules().add(vfModule2);
+
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup();
+ volumeGroup.setVolumeGroupId("volumeGroup0");
+ vnf.getVolumeGroups().add(volumeGroup);
+
+ serviceInstanceMSO.getVnfs().add(vnf);
+
+ doReturn(serviceInstanceAAI).when(bbSetupUtils).getAAIServiceInstanceById("si0");
+ doReturn(serviceInstanceMSO).when(bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "CreateVolumeGroupBB", "ActivateVolumeGroupBB", "CreateVfModuleBB",
+ "CreateVfModuleBB", "ActivateVfModuleBB", "ActivateVfModuleBB", "ActivateVnfBB",
+ "ActivateServiceInstanceBB");
+ assertEquals("volumeGroup0", ebbs.get(0).getWorkflowResourceIds().getVolumeGroupId());
+ assertEquals("volumeGroup0", ebbs.get(1).getWorkflowResourceIds().getVolumeGroupId());
+ assertEquals("vfModule0", ebbs.get(2).getWorkflowResourceIds().getVfModuleId());
+ assertEquals("vfModule1", ebbs.get(3).getWorkflowResourceIds().getVfModuleId());
+ assertEquals("vfModule0", ebbs.get(4).getWorkflowResourceIds().getVfModuleId());
+ assertEquals("vfModule1", ebbs.get(5).getWorkflowResourceIds().getVfModuleId());
+ assertEquals("vnf0", ebbs.get(6).getWorkflowResourceIds().getVnfId());
+ assertEquals("si0", ebbs.get(7).getWorkflowResourceIds().getServiceInstanceId());
+
+ }
+
+ @Test
+ public void selectExecutionListServiceMacroDeactivateTest() throws Exception {
+ String gAction = "deactivateInstance";
+ String resource = "Service";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("DeactivateServiceInstanceBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEquals(ebbs.get(0).getBuildingBlock().getBpmnFlowName(), "DeactivateServiceInstanceBB");
+ }
+
+ @Test
+ public void selectExecutionListServiceMacroEmptyServiceTest() throws Exception {
+ String gAction = "createInstance";
+ String resource = "Service";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ northBoundRequest.setIsToplevelflow(true);
+ List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB", "CreateNetworkCollectionBB",
+ "AssignNetworkBB", "AssignVnfBB", "AssignVolumeGroupBB", "AssignVfModuleBB", "CreateNetworkBB",
+ "ActivateNetworkBB", "CreateVolumeGroupBB", "ActivateVolumeGroupBB", "CreateVfModuleBB",
+ "ActivateVfModuleBB", "AssignFabricConfigurationBB", "ActivateFabricConfigurationBB", "ActivateVnfBB",
+ "ActivateNetworkCollectionBB", "ActivateServiceInstanceBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ Service service = new Service();
+ doReturn(service).when(catalogDbClient).getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a");
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "AssignServiceInstanceBB", "ActivateServiceInstanceBB");
+ }
+
+ @Test
+ public void selectExecutionListServiceMacroCreateJustNetworkTest() throws Exception {
+ String gAction = "createInstance";
+ String resource = "Service";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ northBoundRequest.setIsToplevelflow(true);
+ List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB", "CreateNetworkCollectionBB",
+ "AssignNetworkBB", "AssignVnfBB", "AssignVolumeGroupBB", "AssignVfModuleBB", "CreateNetworkBB",
+ "ActivateNetworkBB", "CreateVolumeGroupBB", "ActivateVolumeGroupBB", "CreateVfModuleBB",
+ "ActivateVfModuleBB", "AssignFabricConfigurationBB", "ActivateFabricConfigurationBB", "ActivateVnfBB",
+ "ActivateNetworkCollectionBB", "ActivateServiceInstanceBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ Service service = new Service();
+ NetworkResourceCustomization networkCustomization = new NetworkResourceCustomization();
+ networkCustomization.setModelCustomizationUUID("1234");
+ service.getNetworkCustomizations().add(networkCustomization);
+ doReturn(service).when(catalogDbClient).getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a");
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "AssignServiceInstanceBB", "AssignNetworkBB", "CreateNetworkBB",
+ "ActivateNetworkBB", "ActivateServiceInstanceBB");
+ }
+
+ @Test
+ public void selectExecutionListServiceMacroCreateWithNetworkCollectionTest() throws Exception {
+ String gAction = "createInstance";
+ String resource = "Service";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ northBoundRequest.setIsToplevelflow(true);
+ List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB", "CreateNetworkCollectionBB",
+ "AssignNetworkBB", "AssignVnfBB", "AssignVolumeGroupBB", "AssignVfModuleBB", "CreateNetworkBB",
+ "ActivateNetworkBB", "CreateVolumeGroupBB", "ActivateVolumeGroupBB", "CreateVfModuleBB",
+ "ActivateVfModuleBB", "AssignFabricConfigurationBB", "ActivateFabricConfigurationBB", "ActivateVnfBB",
+ "ActivateNetworkCollectionBB", "ActivateServiceInstanceBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ Service service = new Service();
+ List<NetworkResourceCustomization> networkCustomizations = new ArrayList<>();
+ NetworkResourceCustomization networkCust = new NetworkResourceCustomization();
+ networkCust.setModelCustomizationUUID("123");
+ networkCustomizations.add(networkCust);
+ service.setNetworkCustomizations(networkCustomizations);
+ NetworkCollectionResourceCustomization collectionResourceCustomization =
+ new NetworkCollectionResourceCustomization();
+ collectionResourceCustomization.setModelCustomizationUUID("123");
+
+ CollectionResource collectionResource = new CollectionResource();
+ collectionResource.setToscaNodeType("NetworkCollection");
+ InstanceGroup instanceGroup = new InstanceGroup();
+ instanceGroup.setToscaNodeType("NetworkCollectionResource");
+ instanceGroup.setCollectionNetworkResourceCustomizations(new ArrayList<>());
+ CollectionNetworkResourceCustomization collectionNetworkResourceCust =
+ new CollectionNetworkResourceCustomization();
+ collectionNetworkResourceCust.setModelCustomizationUUID("123");
+ collectionNetworkResourceCust.setNetworkResourceCustomization(collectionResourceCustomization);
+ instanceGroup.getCollectionNetworkResourceCustomizations().add(collectionNetworkResourceCust);
+ List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupCustomizations = new ArrayList<>();
+ CollectionResourceInstanceGroupCustomization collectionInstanceGroupCustomization =
+ new CollectionResourceInstanceGroupCustomization();
+ collectionInstanceGroupCustomization.setModelCustomizationUUID("123");
+ collectionInstanceGroupCustomization.setSubInterfaceNetworkQuantity(3);
+ collectionInstanceGroupCustomizations.add(collectionInstanceGroupCustomization);
+ collectionInstanceGroupCustomization.setInstanceGroup(instanceGroup);
+ collectionInstanceGroupCustomization.setCollectionResourceCust(collectionResourceCustomization);
+ instanceGroup.setCollectionInstanceGroupCustomizations(collectionInstanceGroupCustomizations);
+ collectionResource.setInstanceGroup(instanceGroup);
+ collectionResourceCustomization.setCollectionResource(collectionResource);;
+ service.getCollectionResourceCustomizations().add(collectionResourceCustomization);
+ doReturn(service).when(catalogDbClient).getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a");
+ doReturn(collectionResourceCustomization).when(catalogDbClient)
+ .getNetworkCollectionResourceCustomizationByID("123");
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "AssignServiceInstanceBB", "CreateNetworkCollectionBB", "AssignNetworkBB",
+ "CreateNetworkBB", "ActivateNetworkBB", "AssignNetworkBB", "CreateNetworkBB", "ActivateNetworkBB",
+ "AssignNetworkBB", "CreateNetworkBB", "ActivateNetworkBB", "ActivateNetworkCollectionBB",
+ "ActivateServiceInstanceBB");
+ assertEquals("Network id not empty", !ebbs.get(2).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
+ assertEquals("Network id not empty", !ebbs.get(3).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
+ assertEquals("Network id not empty", !ebbs.get(4).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
+ assertEquals("Network id same for AssignNetworkBB CreateNetworkBB ActivateNetworkBB",
+ ebbs.get(2).getWorkflowResourceIds().getNetworkId() == ebbs.get(3).getWorkflowResourceIds()
+ .getNetworkId()
+ && ebbs.get(3).getWorkflowResourceIds().getNetworkId() == ebbs.get(4).getWorkflowResourceIds()
+ .getNetworkId(),
+ true);
+ assertEquals("Network id not empty", !ebbs.get(5).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
+ assertEquals("Network id not empty", !ebbs.get(6).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
+ assertEquals("Network id not empty", !ebbs.get(7).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
+ assertEquals("Network id same for AssignNetworkBB CreateNetworkBB ActivateNetworkBB",
+ ebbs.get(5).getWorkflowResourceIds().getNetworkId() == ebbs.get(6).getWorkflowResourceIds()
+ .getNetworkId()
+ && ebbs.get(6).getWorkflowResourceIds().getNetworkId() == ebbs.get(7).getWorkflowResourceIds()
+ .getNetworkId(),
+ true);
+ assertEquals("Network id not empty", !ebbs.get(8).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
+ assertEquals("Network id not empty", !ebbs.get(9).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
+ assertEquals("Network id not empty", !ebbs.get(10).getWorkflowResourceIds().getNetworkId().isEmpty(), true);
+ assertEquals("Network id same for AssignNetworkBB CreateNetworkBB ActivateNetworkBB",
+ ebbs.get(8).getWorkflowResourceIds().getNetworkId() == ebbs.get(9).getWorkflowResourceIds()
+ .getNetworkId()
+ && ebbs.get(9).getWorkflowResourceIds().getNetworkId() == ebbs.get(10).getWorkflowResourceIds()
+ .getNetworkId(),
+ true);
+ }
+
+ @Test
+ public void selectExecutionListServiceMacroCreateWithUserParams() throws Exception {
+ String gAction = "createInstance";
+ String resource = "Service";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroAssign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB", "CreateNetworkCollectionBB",
+ "AssignNetworkBB", "AssignVnfBB", "AssignVolumeGroupBB", "AssignVfModuleBB", "CreateNetworkBB",
+ "ActivateNetworkBB", "CreateVolumeGroupBB", "ActivateVolumeGroupBB", "CreateVfModuleBB",
+ "ActivateVfModuleBB", "AssignFabricConfigurationBB", "ActivateFabricConfigurationBB", "ActivateVnfBB",
+ "ActivateNetworkCollectionBB", "ActivateServiceInstanceBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ Service service = new Service();
+ service.setModelUUID("3c40d244-808e-42ca-b09a-256d83d19d0a");
+
+ VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
+ vfModuleCustomization.setModelCustomizationUUID("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f");
+ HeatEnvironment volumeHeatEnv = new HeatEnvironment();
+ vfModuleCustomization.setVolumeHeatEnv(volumeHeatEnv);
+ org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule();
+ HeatTemplate volumeHeatTemplate = new HeatTemplate();
+ vfModule.setVolumeHeatTemplate(volumeHeatTemplate);
+ vfModuleCustomization.setVfModule(vfModule);
+
+ VfModuleCustomization vfModuleCustomization2 = new VfModuleCustomization();
+ vfModuleCustomization2.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
+ HeatEnvironment heatEnvironment = new HeatEnvironment();
+ vfModuleCustomization2.setHeatEnvironment(heatEnvironment);
+ org.onap.so.db.catalog.beans.VfModule vfModule2 = new org.onap.so.db.catalog.beans.VfModule();
+ HeatTemplate moduleHeatTemplate = new HeatTemplate();
+ vfModule2.setModuleHeatTemplate(moduleHeatTemplate);
+ vfModuleCustomization2.setVfModule(vfModule2);
+
+ VfModuleCustomization vfModuleCustomization3 = vfModuleCustomization2;
+ vfModuleCustomization3.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8");
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f"))
+ .thenReturn(vfModuleCustomization);
+ when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa8"))
+ .thenReturn(vfModuleCustomization2);
+ when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("da4d4327-fb7d-4311-ac7a-be7ba60cf969"))
+ .thenReturn(vfModuleCustomization3);
+ when(catalogDbClient.getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a")).thenReturn(service);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "AssignServiceInstanceBB", "AssignVnfBB", "AssignVolumeGroupBB",
+ "AssignVfModuleBB", "AssignVfModuleBB", "AssignVfModuleBB", "CreateVolumeGroupBB",
+ "ActivateVolumeGroupBB", "CreateVfModuleBB", "CreateVfModuleBB", "CreateVfModuleBB",
+ "ActivateVfModuleBB", "ActivateVfModuleBB", "ActivateVfModuleBB", "ActivateVnfBB",
+ "ActivateServiceInstanceBB");
+ assertEquals(3, ebbs.get(0).getWorkflowResourceIds().getServiceInstanceId().length());
+ int randomUUIDLength = UUID.randomUUID().toString().length();
+ assertEquals(randomUUIDLength, ebbs.get(1).getWorkflowResourceIds().getVnfId().length());
+ assertEquals(randomUUIDLength, ebbs.get(2).getWorkflowResourceIds().getVolumeGroupId().length());
+ assertEquals(randomUUIDLength, ebbs.get(3).getWorkflowResourceIds().getVfModuleId().length());
+ assertEquals(randomUUIDLength, ebbs.get(4).getWorkflowResourceIds().getVfModuleId().length());
+ assertEquals(randomUUIDLength, ebbs.get(5).getWorkflowResourceIds().getVfModuleId().length());
+ assertEquals(randomUUIDLength, ebbs.get(6).getWorkflowResourceIds().getVolumeGroupId().length());
+ assertEquals(randomUUIDLength, ebbs.get(7).getWorkflowResourceIds().getVolumeGroupId().length());
+ assertEquals(randomUUIDLength, ebbs.get(8).getWorkflowResourceIds().getVfModuleId().length());
+ assertEquals(randomUUIDLength, ebbs.get(9).getWorkflowResourceIds().getVfModuleId().length());
+ assertEquals(randomUUIDLength, ebbs.get(10).getWorkflowResourceIds().getVfModuleId().length());
+ assertEquals(randomUUIDLength, ebbs.get(11).getWorkflowResourceIds().getVfModuleId().length());
+ assertEquals(randomUUIDLength, ebbs.get(12).getWorkflowResourceIds().getVfModuleId().length());
+ assertEquals(randomUUIDLength, ebbs.get(13).getWorkflowResourceIds().getVfModuleId().length());
+ assertEquals(randomUUIDLength, ebbs.get(14).getWorkflowResourceIds().getVnfId().length());
+ assertEquals(3, ebbs.get(0).getWorkflowResourceIds().getServiceInstanceId().length());
+ assertEquals(true, execution.getVariable("homing"));
+ }
+
+ @Test
+ public void selectExecutionListServiceMacroDeleteTest() throws Exception {
+ String gAction = "deleteInstance";
+ String resource = "Service";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("DeactivateVfModuleBB", "DeleteVfModuleBB",
+ "DeactivateVolumeGroupBB", "DeleteVolumeGroupBB", "DeactivateVnfBB", "DeactivateNetworkBB",
+ "DeleteNetworkBB", "DeleteNetworkCollectionBB", "DeactivateServiceInstanceBB", "UnassignVfModuleBB",
+ "UnassignVolumeGroupBB", "UnassignVnfBB", "UnassignNetworkBB", "UnassignServiceInstanceBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ ServiceInstance serviceInstanceAAI = new ServiceInstance();
+ serviceInstanceAAI.setServiceInstanceId("aaisi123");
+ org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance();
+ org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf();
+ vnf.setVnfId("vnfId123");
+
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
+ vfModule.setVfModuleId("vfModule1");
+ vnf.getVfModules().add(vfModule);
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule2 =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
+ vfModule2.setVfModuleId("vfModule2");
+ vnf.getVfModules().add(vfModule2);
+
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup();
+ volumeGroup.setVolumeGroupId("vg123");
+ vnf.getVolumeGroups().add(volumeGroup);
+
+ serviceInstanceMSO.getVnfs().add(vnf);
+
+ doReturn(serviceInstanceAAI).when(bbSetupUtils).getAAIServiceInstanceById("123");
+ doReturn(serviceInstanceMSO).when(bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeactivateVfModuleBB", "DeleteVfModuleBB",
+ "DeleteVfModuleBB", "DeactivateVolumeGroupBB", "DeleteVolumeGroupBB", "DeactivateVnfBB",
+ "DeactivateServiceInstanceBB", "UnassignVfModuleBB", "UnassignVfModuleBB", "UnassignVolumeGroupBB",
+ "UnassignVnfBB", "UnassignServiceInstanceBB");
+ }
+
+ @Test
+ public void selectExecutionListServiceMacroUnassignTest() throws Exception {
+ String gAction = "unassignInstance";
+ String resource = "Service";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("UnassignVfModuleBB", "UnassignVolumeGroupBB",
+ "UnassignVnfBB", "UnassignNetworkBB", "UnassignServiceInstanceBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ ServiceInstance serviceInstanceAAI = new ServiceInstance();
+ serviceInstanceAAI.setServiceInstanceId("aaisi123");
+ org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance();
+ org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf();
+ vnf.setVnfId("vnfId123");
+
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
+ vfModule.setVfModuleId("vfModule1");
+ vnf.getVfModules().add(vfModule);
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule2 =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
+ vfModule2.setVfModuleId("vfModule2");
+ vnf.getVfModules().add(vfModule2);
+
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup();
+ volumeGroup.setVolumeGroupId("vg123");
+ vnf.getVolumeGroups().add(volumeGroup);
+
+ serviceInstanceMSO.getVnfs().add(vnf);
+
+ doReturn(serviceInstanceAAI).when(bbSetupUtils).getAAIServiceInstanceById("123");
+ doReturn(serviceInstanceMSO).when(bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "UnassignVfModuleBB", "UnassignVfModuleBB", "UnassignVolumeGroupBB",
+ "UnassignVnfBB", "UnassignServiceInstanceBB");
+ }
+
@Test
- public void selectExecutionListVnfMacroRecreateTest() throws Exception{
+ public void selectExecutionListServiceMacroDeleteNetworkCollectionTest() throws Exception {
+ String gAction = "deleteInstance";
+ String resource = "Service";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("DeactivateVfModuleBB", "DeleteVfModuleBB",
+ "DeactivateVolumeGroupBB", "DeleteVolumeGroupBB", "DeactivateVnfBB", "DeactivateNetworkBB",
+ "DeleteNetworkBB", "DeleteNetworkCollectionBB", "DeactivateServiceInstanceBB", "UnassignVfModuleBB",
+ "UnassignVolumeGroupBB", "UnassignVnfBB", "UnassignNetworkBB", "UnassignServiceInstanceBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ ServiceInstance serviceInstanceAAI = new ServiceInstance();
+ serviceInstanceAAI.setServiceInstanceId("aaisi123");
+ org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance();
+
+ org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network();
+ network.setNetworkId("123");
+ serviceInstanceMSO.getNetworks().add(network);
+ org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network2 =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network();
+ network2.setNetworkId("321");
+ serviceInstanceMSO.getNetworks().add(network2);
+
+ Collection collection = new Collection();
+ serviceInstanceMSO.setCollection(collection);
+
+ doReturn(serviceInstanceAAI).when(bbSetupUtils).getAAIServiceInstanceById("123");
+ doReturn(serviceInstanceMSO).when(bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "DeactivateNetworkBB", "DeleteNetworkBB", "UnassignNetworkBB",
+ "DeactivateNetworkBB", "DeleteNetworkBB", "UnassignNetworkBB", "DeleteNetworkCollectionBB",
+ "DeactivateServiceInstanceBB", "UnassignServiceInstanceBB");
+ }
+
+ @Test
+ public void selectExecutionListVnfMacroRecreateTest() throws Exception {
String gAction = "recreateInstance";
String resource = "Vnf";
execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/VnfMacroReplace.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
+ String bpmnRequest =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/VnfMacroReplace.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
execution.setVariable("aLaCarte", false);
execution.setVariable("apiVersion", "7");
execution.setVariable("requestUri", "v7/serviceInstances/123/vnfs/1234/recreate");
execution.setVariable("serviceInstanceId", "123");
execution.setVariable("vnfId", "1234");
-
+
NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("AAICheckVnfInMaintBB","AAISetVnfInMaintBB","DeactivateFabricConfigurationBB", "UnassignFabricConfigurationBB", "DeactivateVfModuleBB","DeleteVfModuleBB","DeactivateVnfBB","CreateVfModuleBB"
- ,"ActivateVfModuleBB","AssignFabricConfigurationBB","ActivateFabricConfigurationBB","ActivateVnfBB","SDNOVnfHealthCheckBB","AAIUnsetVnfInMaintBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
+ List<OrchestrationFlow> orchFlows = createFlowList("AAICheckVnfInMaintBB", "AAISetVnfInMaintBB",
+ "DeactivateFabricConfigurationBB", "UnassignFabricConfigurationBB", "DeactivateVfModuleBB",
+ "DeleteVfModuleBB", "DeactivateVnfBB", "CreateVfModuleBB", "ActivateVfModuleBB",
+ "AssignFabricConfigurationBB", "ActivateFabricConfigurationBB", "ActivateVnfBB", "SDNOVnfHealthCheckBB",
+ "AAIUnsetVnfInMaintBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
ServiceInstance serviceInstanceAAI = new ServiceInstance();
serviceInstanceAAI.setServiceInstanceId("123");
- org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = new org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance();
- org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf = new org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf();
+ org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance();
+ org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf();
vnf.setVnfId("1234");
-
- org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule = new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
+
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
vfModule.setVfModuleId("vfModule1");
vnf.getVfModules().add(vfModule);
- org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule2 = new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule2 =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
vfModule2.setVfModuleId("vfModule2");
vnf.getVfModules().add(vfModule2);
-
+
serviceInstanceMSO.getVnfs().add(vnf);
-
+
doReturn(serviceInstanceAAI).when(bbSetupUtils).getAAIServiceInstanceById("123");
doReturn(serviceInstanceMSO).when(bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"cloud-owner")).thenReturn(northBoundRequest);
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "cloud-owner")).thenReturn(northBoundRequest);
workflowAction.selectExecutionList(execution);
List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"AAICheckVnfInMaintBB","AAISetVnfInMaintBB","DeactivateVfModuleBB","DeactivateVfModuleBB","DeleteVfModuleBB","DeleteVfModuleBB","DeactivateVnfBB"
- ,"CreateVfModuleBB","CreateVfModuleBB","ActivateVfModuleBB","ActivateVfModuleBB","ActivateVnfBB","SDNOVnfHealthCheckBB","AAIUnsetVnfInMaintBB");
+ assertEqualsBulkFlowName(ebbs, "AAICheckVnfInMaintBB", "AAISetVnfInMaintBB", "DeactivateVfModuleBB",
+ "DeactivateVfModuleBB", "DeleteVfModuleBB", "DeleteVfModuleBB", "DeactivateVnfBB", "CreateVfModuleBB",
+ "CreateVfModuleBB", "ActivateVfModuleBB", "ActivateVfModuleBB", "ActivateVnfBB", "SDNOVnfHealthCheckBB",
+ "AAIUnsetVnfInMaintBB");
}
-
+
@Test
- public void selectExecutionListVnfMacroReplaceTest() throws Exception{
+ public void selectExecutionListVnfMacroReplaceTest() throws Exception {
String gAction = "replaceInstance";
String resource = "Vnf";
execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/VnfMacroReplace.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
+ String bpmnRequest =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/VnfMacroReplace.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
execution.setVariable("aLaCarte", false);
execution.setVariable("apiVersion", "7");
execution.setVariable("requestUri", "v7/serviceInstances/123/vnfs/1234/replace");
execution.setVariable("serviceInstanceId", "123");
execution.setVariable("vnfId", "1234");
-
+
NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("AAICheckVnfInMaintBB","AAISetVnfInMaintBB","DeactivateFabricConfigurationBB","UnassignFabricConfigurationBB","DeactivateVfModuleBB","DeleteVfModuleBB"
- ,"DeactivateVnfBB","ChangeModelVfModuleBB","CreateVfModuleBB","ActivateVfModuleBB","AssignFabricConfigurationBB","ActivateFabricConfigurationBB","ChangeModelVnfBB","ActivateVnfBB","ChangeModelServiceInstanceBB","SDNOVnfHealthCheckBB","AAIUnsetVnfInMaintBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
+ List<OrchestrationFlow> orchFlows = createFlowList("AAICheckVnfInMaintBB", "AAISetVnfInMaintBB",
+ "DeactivateFabricConfigurationBB", "UnassignFabricConfigurationBB", "DeactivateVfModuleBB",
+ "DeleteVfModuleBB", "DeactivateVnfBB", "ChangeModelVfModuleBB", "CreateVfModuleBB",
+ "ActivateVfModuleBB", "AssignFabricConfigurationBB", "ActivateFabricConfigurationBB",
+ "ChangeModelVnfBB", "ActivateVnfBB", "ChangeModelServiceInstanceBB", "SDNOVnfHealthCheckBB",
+ "AAIUnsetVnfInMaintBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
ServiceInstance serviceInstanceAAI = new ServiceInstance();
serviceInstanceAAI.setServiceInstanceId("123");
- org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = new org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance();
- org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf = new org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf();
+ org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance();
+ org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf();
vnf.setVnfId("1234");
- org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule = new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
vfModule.setVfModuleId("vfModule1");
vnf.getVfModules().add(vfModule);
- org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule2 = new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
+ org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule2 =
+ new org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule();
vfModule2.setVfModuleId("vfModule2");
vnf.getVfModules().add(vfModule2);
serviceInstanceMSO.getVnfs().add(vnf);
@@ -792,647 +912,716 @@ public class WorkflowActionTest extends BaseTaskTest {
config.setConfigurationId("configId");
Optional<Configuration> configOp = Optional.of(config);
Optional<Relationships> relationshipsOp = Optional.of(relationships);
-
+
doReturn(relationshipsOp).when(workflowActionUtils).extractRelationshipsVnfc(isA(Relationships.class));
doReturn(configOp).when(workflowActionUtils).extractRelationshipsConfiguration(isA(Relationships.class));
doReturn(vfModuleAAI).when(bbSetupUtils).getAAIVfModule("1234", "vfModule2");
doReturn(serviceInstanceAAI).when(bbSetupUtils).getAAIServiceInstanceById("123");
doReturn(serviceInstanceMSO).when(bbInputSetup).getExistingServiceInstance(serviceInstanceAAI);
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"cloud-owner")).thenReturn(northBoundRequest);
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "AAICheckVnfInMaintBB", "AAISetVnfInMaintBB", "DeactivateFabricConfigurationBB",
+ "UnassignFabricConfigurationBB", "DeactivateVfModuleBB", "DeactivateVfModuleBB", "DeleteVfModuleBB",
+ "DeleteVfModuleBB", "DeactivateVnfBB", "ChangeModelVfModuleBB", "ChangeModelVfModuleBB",
+ "CreateVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB", "ActivateVfModuleBB",
+ "AssignFabricConfigurationBB", "ActivateFabricConfigurationBB", "ChangeModelVnfBB", "ActivateVnfBB",
+ "ChangeModelServiceInstanceBB", "SDNOVnfHealthCheckBB", "AAIUnsetVnfInMaintBB");
+ }
+
+ @Ignore
+ @Test
+ public void selectExecutionListNetworkCollectionMacroCreate() throws Exception {
+ String gAction = "createInstance";
+ String resource = "NetworkCollection";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest = new String(
+ Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/CreateNetworkCollection.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123/networkCollections/123");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("CreateNetworkCollectionBB", "AssignNetworkBB",
+ "CreateNetworkBB", "ActivateNetworkBB", "ActivateNetworkCollectionBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ Service service = new Service();
+ CollectionResourceCustomization collectionResourceCustomization = new CollectionResourceCustomization();
+ CollectionResource collectionResource = new CollectionResource();
+ collectionResource.setToscaNodeType("Data NetworkCollection Data");
+ collectionResourceCustomization.setCollectionResource(collectionResource);
+ service.getCollectionResourceCustomizations().add(collectionResourceCustomization);
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ when(catalogDbClient.getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a")).thenReturn(service);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "CreateNetworkCollectionBB", "AssignNetworkBB", "CreateNetworkBB",
+ "ActivateNetworkBB", "AssignNetworkBB", "CreateNetworkBB", "ActivateNetworkBB",
+ "ActivateNetworkCollectionBB");
+ }
+
+ @Ignore
+ @Test
+ public void selectExecutionListNetworkCollectionMacroDelete() throws Exception {
+ String gAction = "deleteInstance";
+ String resource = "NetworkCollection";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest = new String(
+ Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/CreateNetworkCollection.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", false);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri", "v6/serviceInstances/123/networkCollections/123");
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("DeactivateNetworkBB", "DeleteNetworkBB",
+ "UnassignNetworkBB", "DeactivateNetworkCollectionBB", "DeleteNetworkCollectionBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ Service service = new Service();
+ CollectionResourceCustomization collectionResourceCustomization = new CollectionResourceCustomization();
+ CollectionResource collectionResource = new CollectionResource();
+ collectionResource.setToscaNodeType("Data NetworkCollection Data");
+ collectionResourceCustomization.setCollectionResource(collectionResource);
+ service.getCollectionResourceCustomizations().add(collectionResourceCustomization);
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ when(catalogDbClient.getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a")).thenReturn(service);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "DeactivateNetworkBB", "DeleteNetworkBB", "UnassignNetworkBB",
+ "DeactivateNetworkBB", "DeleteNetworkBB", "UnassignNetworkBB", "DeactivateNetworkCollectionBB",
+ "DeleteNetworkCollectionBB");
+ }
+
+ @Test
+ public void selectExecutionListALaCarteVfModuleNoFabricCreateTest() throws Exception {
+ String gAction = "createInstance";
+ String resource = "VfModule";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri",
+ "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules");
+
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB",
+ "AssignFabricConfigurationBB", "ActivateFabricConfigurationBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ true, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB");
+ }
+
+ @Test
+ public void selectExecutionListALaCarteVfModuleFabricCreateTest() throws Exception {
+ String gAction = "createInstance";
+ String resource = "VfModule";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri",
+ "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules");
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB",
+ "AssignFabricConfigurationBB", "ActivateFabricConfigurationBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ List<CvnfcCustomization> cvnfcCustomizations = new ArrayList<CvnfcCustomization>();
+ CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
+ CvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization =
+ new CvnfcConfigurationCustomization();
+ ConfigurationResource configurationResource = new ConfigurationResource();
+ configurationResource.setToscaNodeType("FabricConfiguration");
+ vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationResource(configurationResource);
+ vnfVfmoduleCvnfcConfigurationCustomization.setModelInstanceName("modelInstanceName1");
+ vnfVfmoduleCvnfcConfigurationCustomization.setCvnfcCustomization(cvnfcCustomization);
+ Set<CvnfcConfigurationCustomization> custSet = new HashSet<CvnfcConfigurationCustomization>();
+ custSet.add(vnfVfmoduleCvnfcConfigurationCustomization);
+ cvnfcCustomization.setCvnfcConfigurationCustomization(custSet);
+ cvnfcCustomization.setDescription("description");
+ cvnfcCustomizations.add(cvnfcCustomization);
+
+ CvnfcCustomization cvnfcCustomization2 = new CvnfcCustomization();
+ CvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization2 =
+ new CvnfcConfigurationCustomization();
+ ConfigurationResource configurationResource2 = new ConfigurationResource();
+ configurationResource2.setToscaNodeType("FabricConfiguration");
+ vnfVfmoduleCvnfcConfigurationCustomization2.setConfigurationResource(configurationResource2);
+ vnfVfmoduleCvnfcConfigurationCustomization2.setModelInstanceName("modelInstanceName2");
+ vnfVfmoduleCvnfcConfigurationCustomization2.setCvnfcCustomization(cvnfcCustomization2);
+ Set<CvnfcConfigurationCustomization> custSet2 = new HashSet<CvnfcConfigurationCustomization>();
+ custSet2.add(vnfVfmoduleCvnfcConfigurationCustomization2);
+ cvnfcCustomization2.setCvnfcConfigurationCustomization(custSet2);
+ cvnfcCustomization2.setDescription("description2");
+ cvnfcCustomizations.add(cvnfcCustomization2);
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ true, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ // when(catalogDbClient.getCvnfcCustomizationByVnfCustomizationUUIDAndVfModuleCustomizationUUID("fc25201d-36d6-43a3-8d39-fdae88e526ae",
+ // "9a6d01fd-19a7-490a-9800-460830a12e0b")).thenReturn(cvnfcCustomizations);
workflowAction.selectExecutionList(execution);
List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"AAICheckVnfInMaintBB","AAISetVnfInMaintBB", "DeactivateFabricConfigurationBB", "UnassignFabricConfigurationBB", "DeactivateVfModuleBB","DeactivateVfModuleBB","DeleteVfModuleBB","DeleteVfModuleBB","DeactivateVnfBB"
- ,"ChangeModelVfModuleBB" ,"ChangeModelVfModuleBB" , "CreateVfModuleBB","CreateVfModuleBB", "ActivateVfModuleBB","ActivateVfModuleBB", "AssignFabricConfigurationBB", "ActivateFabricConfigurationBB", "ChangeModelVnfBB", "ActivateVnfBB","ChangeModelServiceInstanceBB","SDNOVnfHealthCheckBB","AAIUnsetVnfInMaintBB");
+ assertEqualsBulkFlowName(ebbs, "AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB",
+ "AssignFabricConfigurationBB", "ActivateFabricConfigurationBB", "AssignFabricConfigurationBB",
+ "ActivateFabricConfigurationBB");
+ }
+
+ @Test
+ public void selectExecutionListALaCarteVfModuleFabricDeleteTest() throws Exception {
+ String gAction = "deleteInstance";
+ String resource = "VfModule";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri",
+ "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules");
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("DeactivateVfModuleBB", "DeleteVfModuleBB",
+ "UnassignVfModuleBB", "DeactivateFabricConfigurationBB", "UnassignFabricConfigurationBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ true, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+
+ org.onap.aai.domain.yang.GenericVnf vnf = new org.onap.aai.domain.yang.GenericVnf();
+ vnf.setVnfId("vnf0");
+ vnf.setModelCustomizationId("modelCustomizationId");
+ when(bbSetupUtils.getAAIGenericVnf(anyObject())).thenReturn(vnf);
+
+ org.onap.aai.domain.yang.VfModule vfModule = new org.onap.aai.domain.yang.VfModule();
+ vfModule.setModelCustomizationId("modelCustomizationId");
+ when(bbSetupUtils.getAAIVfModule(anyObject(), anyObject())).thenReturn(vfModule);
+
+ List<org.onap.aai.domain.yang.Vnfc> vnfcs = new ArrayList<org.onap.aai.domain.yang.Vnfc>();
+ org.onap.aai.domain.yang.Vnfc vnfc = new org.onap.aai.domain.yang.Vnfc();
+ vnfc.setModelInvariantId("modelInvariantId");
+ vnfc.setVnfcName("testVnfcName");
+ vnfcs.add(vnfc);
+ doReturn(vnfcs).when(SPY_workflowAction).getRelatedResourcesInVfModule(anyObject(), anyObject(), anyObject(),
+ anyObject());
+
+ List<org.onap.aai.domain.yang.Configuration> configurations =
+ new ArrayList<org.onap.aai.domain.yang.Configuration>();
+ org.onap.aai.domain.yang.Configuration configuration = new org.onap.aai.domain.yang.Configuration();
+ configuration.setConfigurationId("configurationId");
+ configuration.setModelCustomizationId("modelCustimizationId");
+ configuration.setConfigurationName("testConfigurationName");
+ configurations.add(configuration);
+ doReturn(configurations).when(SPY_workflowAction).getRelatedResourcesInVnfc(anyObject(), anyObject(),
+ anyObject());
+
+ doReturn("testName").when(SPY_workflowAction).getVnfcNameForConfiguration(anyObject());
+
+ SPY_workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "DeactivateFabricConfigurationBB", "UnassignFabricConfigurationBB",
+ "DeactivateVfModuleBB", "DeleteVfModuleBB", "UnassignVfModuleBB");
}
-
- @Ignore
- @Test
- public void selectExecutionListNetworkCollectionMacroCreate() throws Exception{
- String gAction = "createInstance";
- String resource = "NetworkCollection";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/CreateNetworkCollection.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123/networkCollections/123");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("CreateNetworkCollectionBB","AssignNetworkBB","CreateNetworkBB","ActivateNetworkBB","ActivateNetworkCollectionBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- Service service = new Service();
- CollectionResourceCustomization collectionResourceCustomization = new CollectionResourceCustomization();
- CollectionResource collectionResource = new CollectionResource();
- collectionResource.setToscaNodeType("Data NetworkCollection Data");
- collectionResourceCustomization.setCollectionResource(collectionResource);
- service.getCollectionResourceCustomizations().add(collectionResourceCustomization);
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- when(catalogDbClient.getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a")).thenReturn(service);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"CreateNetworkCollectionBB","AssignNetworkBB","CreateNetworkBB","ActivateNetworkBB","AssignNetworkBB","CreateNetworkBB","ActivateNetworkBB","ActivateNetworkCollectionBB");
- }
-
- @Ignore
- @Test
- public void selectExecutionListNetworkCollectionMacroDelete() throws Exception{
- String gAction = "deleteInstance";
- String resource = "NetworkCollection";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/CreateNetworkCollection.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", false);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v6/serviceInstances/123/networkCollections/123");
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("DeactivateNetworkBB","DeleteNetworkBB","UnassignNetworkBB","DeactivateNetworkCollectionBB","DeleteNetworkCollectionBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- Service service = new Service();
- CollectionResourceCustomization collectionResourceCustomization = new CollectionResourceCustomization();
- CollectionResource collectionResource = new CollectionResource();
- collectionResource.setToscaNodeType("Data NetworkCollection Data");
- collectionResourceCustomization.setCollectionResource(collectionResource);
- service.getCollectionResourceCustomizations().add(collectionResourceCustomization);
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- when(catalogDbClient.getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a")).thenReturn(service);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"DeactivateNetworkBB","DeleteNetworkBB","UnassignNetworkBB","DeactivateNetworkBB","DeleteNetworkBB","UnassignNetworkBB","DeactivateNetworkCollectionBB"
- ,"DeleteNetworkCollectionBB");
- }
-
- @Test
- public void selectExecutionListALaCarteVfModuleNoFabricCreateTest() throws Exception{
- String gAction = "createInstance";
- String resource = "VfModule";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules");
-
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("AssignVfModuleBB","CreateVfModuleBB","ActivateVfModuleBB","AssignFabricConfigurationBB","ActivateFabricConfigurationBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,true,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"AssignVfModuleBB","CreateVfModuleBB","ActivateVfModuleBB");
- }
-
- @Test
- public void selectExecutionListALaCarteVfModuleFabricCreateTest() throws Exception{
- String gAction = "createInstance";
- String resource = "VfModule";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules");
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("AssignVfModuleBB","CreateVfModuleBB","ActivateVfModuleBB","AssignFabricConfigurationBB","ActivateFabricConfigurationBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- List<CvnfcCustomization> cvnfcCustomizations = new ArrayList<CvnfcCustomization>();
- CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
- CvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization = new CvnfcConfigurationCustomization();
- ConfigurationResource configurationResource = new ConfigurationResource();
- configurationResource.setToscaNodeType("FabricConfiguration");
- vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationResource(configurationResource);
- vnfVfmoduleCvnfcConfigurationCustomization.setModelInstanceName("modelInstanceName1");
- vnfVfmoduleCvnfcConfigurationCustomization.setCvnfcCustomization(cvnfcCustomization);
- Set<CvnfcConfigurationCustomization> custSet = new HashSet<CvnfcConfigurationCustomization>();
- custSet.add(vnfVfmoduleCvnfcConfigurationCustomization);
- cvnfcCustomization.setCvnfcConfigurationCustomization(custSet);
- cvnfcCustomization.setDescription("description");
- cvnfcCustomizations.add(cvnfcCustomization);
-
- CvnfcCustomization cvnfcCustomization2 = new CvnfcCustomization();
- CvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization2 = new CvnfcConfigurationCustomization();
- ConfigurationResource configurationResource2 = new ConfigurationResource();
- configurationResource2.setToscaNodeType("FabricConfiguration");
- vnfVfmoduleCvnfcConfigurationCustomization2.setConfigurationResource(configurationResource2);
- vnfVfmoduleCvnfcConfigurationCustomization2.setModelInstanceName("modelInstanceName2");
- vnfVfmoduleCvnfcConfigurationCustomization2.setCvnfcCustomization(cvnfcCustomization2);
- Set<CvnfcConfigurationCustomization> custSet2 = new HashSet<CvnfcConfigurationCustomization>();
- custSet2.add(vnfVfmoduleCvnfcConfigurationCustomization2);
- cvnfcCustomization2.setCvnfcConfigurationCustomization(custSet2);
- cvnfcCustomization2.setDescription("description2");
- cvnfcCustomizations.add(cvnfcCustomization2);
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,true,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- //when(catalogDbClient.getCvnfcCustomizationByVnfCustomizationUUIDAndVfModuleCustomizationUUID("fc25201d-36d6-43a3-8d39-fdae88e526ae", "9a6d01fd-19a7-490a-9800-460830a12e0b")).thenReturn(cvnfcCustomizations);
- workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"AssignVfModuleBB","CreateVfModuleBB","ActivateVfModuleBB","AssignFabricConfigurationBB","ActivateFabricConfigurationBB", "AssignFabricConfigurationBB","ActivateFabricConfigurationBB");
- }
-
- @Test
- public void selectExecutionListALaCarteVfModuleFabricDeleteTest() throws Exception{
- String gAction = "deleteInstance";
- String resource = "VfModule";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules");
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("DeactivateVfModuleBB","DeleteVfModuleBB","UnassignVfModuleBB","DeactivateFabricConfigurationBB","UnassignFabricConfigurationBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,true,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
-
- org.onap.aai.domain.yang.GenericVnf vnf = new org.onap.aai.domain.yang.GenericVnf();
- vnf.setVnfId("vnf0");
- vnf.setModelCustomizationId("modelCustomizationId");
- when(bbSetupUtils.getAAIGenericVnf(anyObject())).thenReturn(vnf);
-
- org.onap.aai.domain.yang.VfModule vfModule = new org.onap.aai.domain.yang.VfModule();
- vfModule.setModelCustomizationId("modelCustomizationId");
- when(bbSetupUtils.getAAIVfModule(anyObject(), anyObject())).thenReturn(vfModule);
-
- List<org.onap.aai.domain.yang.Vnfc> vnfcs = new ArrayList<org.onap.aai.domain.yang.Vnfc>();
- org.onap.aai.domain.yang.Vnfc vnfc = new org.onap.aai.domain.yang.Vnfc();
- vnfc.setModelInvariantId("modelInvariantId");
- vnfc.setVnfcName("testVnfcName");
- vnfcs.add(vnfc);
- doReturn(vnfcs).when(SPY_workflowAction).getRelatedResourcesInVfModule(anyObject(), anyObject(), anyObject(), anyObject());
-
- List<org.onap.aai.domain.yang.Configuration> configurations = new ArrayList<org.onap.aai.domain.yang.Configuration>();
- org.onap.aai.domain.yang.Configuration configuration = new org.onap.aai.domain.yang.Configuration();
- configuration.setConfigurationId("configurationId");
- configuration.setModelCustomizationId("modelCustimizationId");
- configuration.setConfigurationName("testConfigurationName");
- configurations.add(configuration);
- doReturn(configurations).when(SPY_workflowAction).getRelatedResourcesInVnfc(anyObject(), anyObject(), anyObject());
-
- doReturn("testName").when(SPY_workflowAction).getVnfcNameForConfiguration(anyObject());
-
- SPY_workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"DeactivateFabricConfigurationBB","UnassignFabricConfigurationBB","DeactivateVfModuleBB","DeleteVfModuleBB","UnassignVfModuleBB");
- }
-
- @Test
- public void selectExecutionListALaCarteVfModuleNoFabricDeleteTest() throws Exception{
- String gAction = "deleteInstance";
- String resource = "VfModule";
- execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
- execution.setVariable("requestAction", gAction);
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json")));
- execution.setVariable("bpmnRequest", bpmnRequest);
- execution.setVariable("aLaCarte", true);
- execution.setVariable("apiVersion", "7");
- execution.setVariable("requestUri", "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules");
-
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("DeactivateVfModuleBB","DeleteVfModuleBB","UnassignVfModuleBB","DeactivateFabricConfigurationBB","UnassignFabricConfigurationBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction,resource,true,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
-
- org.onap.aai.domain.yang.GenericVnf vnf = new org.onap.aai.domain.yang.GenericVnf();
- vnf.setVnfId("vnf0");
- vnf.setModelCustomizationId("modelCustomizationId");
- when(bbSetupUtils.getAAIGenericVnf(anyObject())).thenReturn(vnf);
-
- org.onap.aai.domain.yang.VfModule vfModule = new org.onap.aai.domain.yang.VfModule();
- vfModule.setModelCustomizationId("modelCustomizationId");
- when(bbSetupUtils.getAAIVfModule(anyObject(), anyObject())).thenReturn(vfModule);
-
- List<org.onap.aai.domain.yang.Vnfc> vnfcs = new ArrayList<org.onap.aai.domain.yang.Vnfc>();
- org.onap.aai.domain.yang.Vnfc vnfc = new org.onap.aai.domain.yang.Vnfc();
- vnfc.setModelInvariantId("modelInvariantId");
- vnfc.setVnfcName("testVnfcName");
- vnfcs.add(vnfc);
- doReturn(vnfcs).when(SPY_workflowAction).getRelatedResourcesInVfModule(anyObject(), anyObject(), anyObject(), anyObject());
-
- List<org.onap.aai.domain.yang.Configuration> configurations = new ArrayList<org.onap.aai.domain.yang.Configuration>();
- org.onap.aai.domain.yang.Configuration configuration = new org.onap.aai.domain.yang.Configuration();
- doReturn(configurations).when(SPY_workflowAction).getRelatedResourcesInVnfc(anyObject(), anyObject(), anyObject());
-
- doReturn("testName").when(SPY_workflowAction).getVnfcNameForConfiguration(anyObject());
-
- SPY_workflowAction.selectExecutionList(execution);
- List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
- assertEqualsBulkFlowName(ebbs,"DeactivateVfModuleBB","DeleteVfModuleBB","UnassignVfModuleBB");
- }
-
- @Test
- public void getRelatedResourcesInVfModuleTest() throws Exception{
- org.onap.aai.domain.yang.Vnfc vnfc = new org.onap.aai.domain.yang.Vnfc();
- vnfc.setModelInvariantId("modelInvariantId");
- vnfc.setVnfcName("testVnfcName");
-
- String vfncPayload = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/BuildingBlocks/vnfcResponse.json")));
- AAIResultWrapper vfncWrapper = new AAIResultWrapper(vfncPayload);
-
- String configurationPayload = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/BuildingBlocks/configurationResponse.json")));
- AAIResultWrapper configurationWrapper = new AAIResultWrapper(configurationPayload);
- List<AAIResultWrapper> configurationResultWrappers = new ArrayList<AAIResultWrapper>();
- configurationResultWrappers.add(configurationWrapper);
-
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VNFC, vnfc.getVnfcName());
- when(bbSetupUtils.getAAIResourceDepthOne(uri)).thenReturn(vfncWrapper);
-
- doReturn(configurationResultWrappers).when(SPY_workflowAction).getResultWrappersFromRelationships(anyObject(),anyObject());
- List<org.onap.aai.domain.yang.Configuration> configurationsList = SPY_workflowAction.getRelatedResourcesInVnfc(vnfc, org.onap.aai.domain.yang.Configuration.class, AAIObjectType.CONFIGURATION);
- assertEquals(1,configurationsList.size());
- assertEquals("testConfigurationId",configurationsList.get(0).getConfigurationId());
- }
-
- /**
- * WorkflowActionBB Tests
- */
-
- @Test
- public void pluralTest() {
- List<String> items = Arrays.asList(
- "serviceInstances, Service",
- "vnfs, Vnf",
- "vfModules, VfModule",
- "networks, Network",
- "invalidNames, invalidNames");
- items.forEach(item -> {
- String[] split = item.split(",");
- String type = split[0].trim();
- String expected = split[1].trim();
- assertThat(workflowAction.convertTypeFromPlural(type), equalTo(expected));
- });
- }
-
- @Test
- public void sortExecutionPathByObjectForVlanTaggingCreateTest() throws Exception{
- List<ExecuteBuildingBlock> executeFlows = new ArrayList<>();
- ExecuteBuildingBlock ebb = new ExecuteBuildingBlock();
- BuildingBlock bb = new BuildingBlock();
- bb.setBpmnFlowName("AssignNetworkBB");
- bb.setKey("0");
- ebb.setBuildingBlock(bb);
- executeFlows.add(ebb);
- ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
- BuildingBlock bb2 = new BuildingBlock();
- bb2.setBpmnFlowName("AssignNetworkBB");
- bb2.setKey("1");
- ebb2.setBuildingBlock(bb2);
- executeFlows.add(ebb2);
- ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
- BuildingBlock bb3 = new BuildingBlock();
- bb3.setBpmnFlowName("CreateNetworkBB");
- bb3.setKey("0");
- ebb3.setBuildingBlock(bb3);
- executeFlows.add(ebb3);
- ExecuteBuildingBlock ebb4 = new ExecuteBuildingBlock();
- BuildingBlock bb4 = new BuildingBlock();
- bb4.setBpmnFlowName("CreateNetworkBB");
- bb4.setKey("1");
- ebb4.setBuildingBlock(bb4);
- executeFlows.add(ebb4);
- ExecuteBuildingBlock ebb5 = new ExecuteBuildingBlock();
- BuildingBlock bb5 = new BuildingBlock();
- bb5.setBpmnFlowName("ActivateNetworkBB");
- bb5.setKey("0");
- ebb5.setBuildingBlock(bb5);
- executeFlows.add(ebb5);
- ExecuteBuildingBlock ebb6 = new ExecuteBuildingBlock();
- BuildingBlock bb6 = new BuildingBlock();
- bb6.setBpmnFlowName("ActivateNetworkBB");
- bb6.setKey("1");
- ebb6.setBuildingBlock(bb6);
- executeFlows.add(ebb6);
-
- List<ExecuteBuildingBlock> sorted = workflowAction.sortExecutionPathByObjectForVlanTagging(executeFlows,"createInstance");
- assertEqualsBulkFlowName(sorted,"AssignNetworkBB","CreateNetworkBB","ActivateNetworkBB","AssignNetworkBB","CreateNetworkBB","ActivateNetworkBB");
- }
-
- @Test
- public void sortExecutionPathByObjectForVlanTaggingDeleteTest() throws Exception{
- List<ExecuteBuildingBlock> executeFlows = new ArrayList<>();
- ExecuteBuildingBlock ebb = new ExecuteBuildingBlock();
- BuildingBlock bb = new BuildingBlock();
- bb.setBpmnFlowName("DeactivateNetworkBB");
- bb.setKey("0");
- ebb.setBuildingBlock(bb);
- executeFlows.add(ebb);
- ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
- BuildingBlock bb2 = new BuildingBlock();
- bb2.setBpmnFlowName("DeactivateNetworkBB");
- bb2.setKey("1");
- ebb2.setBuildingBlock(bb2);
- executeFlows.add(ebb2);
- ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
- BuildingBlock bb3 = new BuildingBlock();
- bb3.setBpmnFlowName("DeleteNetworkBB");
- bb3.setKey("0");
- ebb3.setBuildingBlock(bb3);
- executeFlows.add(ebb3);
- ExecuteBuildingBlock ebb4 = new ExecuteBuildingBlock();
- BuildingBlock bb4 = new BuildingBlock();
- bb4.setBpmnFlowName("DeleteNetworkBB");
- bb4.setKey("1");
- ebb4.setBuildingBlock(bb4);
- executeFlows.add(ebb4);
- ExecuteBuildingBlock ebb5 = new ExecuteBuildingBlock();
- BuildingBlock bb5 = new BuildingBlock();
- bb5.setBpmnFlowName("UnassignNetworkBB");
- bb5.setKey("0");
- ebb5.setBuildingBlock(bb5);
- executeFlows.add(ebb5);
- ExecuteBuildingBlock ebb6 = new ExecuteBuildingBlock();
- BuildingBlock bb6 = new BuildingBlock();
- bb6.setBpmnFlowName("UnassignNetworkBB");
- bb6.setKey("1");
- ebb6.setBuildingBlock(bb6);
- executeFlows.add(ebb6);
-
- List<ExecuteBuildingBlock> sorted = workflowAction.sortExecutionPathByObjectForVlanTagging(executeFlows,"deleteInstance");
- assertEqualsBulkFlowName(sorted,"DeactivateNetworkBB","DeleteNetworkBB","UnassignNetworkBB","DeactivateNetworkBB","DeleteNetworkBB","UnassignNetworkBB");
- }
- @Test
- public void queryNorthBoundRequestCatalogDbNestedTest() throws MalformedURLException {
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("AAICheckVnfInMaintBB","AAISetVnfInMaintBB","VNF-Macro-Replace","SDNOVnfHealthCheckBB","AAIUnsetVnfInMaintBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
- List<OrchestrationFlow> macroFlows = createFlowList("DeactivateVfModuleBB","DeleteVfModuleBB","DeactivateVnfBB","CreateVfModuleBB","ActivateVfModuleBB","ActivateVnfBB");
-
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner("replaceInstance","Vnf",false,"my-custom-cloud-owner")).thenReturn(northBoundRequest);
- when(catalogDbClient.getOrchestrationFlowByAction("VNF-Macro-Replace")).thenReturn(macroFlows);
- List<OrchestrationFlow> flows = workflowAction.queryNorthBoundRequestCatalogDb(execution, "replaceInstance", WorkflowType.VNF, false,"my-custom-cloud-owner");
- assertEquals(flows.get(0).getFlowName(),"AAICheckVnfInMaintBB");
- assertEquals(flows.get(1).getFlowName(),"AAISetVnfInMaintBB");
- assertEquals(flows.get(2).getFlowName(),"DeactivateVfModuleBB");
- assertEquals(flows.get(3).getFlowName(),"DeleteVfModuleBB");
- assertEquals(flows.get(4).getFlowName(),"DeactivateVnfBB");
- assertEquals(flows.get(5).getFlowName(),"CreateVfModuleBB");
- assertEquals(flows.get(6).getFlowName(),"ActivateVfModuleBB");
- assertEquals(flows.get(7).getFlowName(),"ActivateVnfBB");
- assertEquals(flows.get(8).getFlowName(),"SDNOVnfHealthCheckBB");
- assertEquals(flows.get(9).getFlowName(),"AAIUnsetVnfInMaintBB");
- }
-
- @Test
- public void queryNorthBoundRequestCatalogDbTransportTest() throws MalformedURLException {
- NorthBoundRequest northBoundRequest = new NorthBoundRequest();
- List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB");
- northBoundRequest.setOrchestrationFlowList(orchFlows);
- when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwnerAndServiceType("createInstance","Service",true,"my-custom-cloud-owner","TRANSPORT")).thenReturn(northBoundRequest);
-
- List<OrchestrationFlow> flows = workflowAction.queryNorthBoundRequestCatalogDb(execution, "createInstance", WorkflowType.SERVICE, true,"my-custom-cloud-owner","TRANSPORT");
- assertEquals(flows.get(0).getFlowName(),"AssignServiceInstanceBB");
- }
-
- @Test
- public void extractResourceIdAndTypeFromUriTest(){
- String uri = "/v6/serviceInstances/123";
- String uri2 = "/v6/serviceInstances/123/vnfs/1234";
- String uri3 = "/v6/serviceInstances";
- String uri4 = "/v6/serviceInstances/assign";
- String uri5 = "'/v6/serviceInstances/123/vnfs";
- String uri6 = "/v6/serviceInstances/123/vnfs/1234/someAction";
- String uri7 = "/v6/serviceInstances/123/vnfs/1234/vfModules/5678/replace";
- String uri8 = "/v6/serviceInstances/123/vnfs/1234/vfModules/scaleOut";
- Resource expected1 = new Resource(WorkflowType.SERVICE, "123", true);
- Resource expected2 = new Resource(WorkflowType.VNF, "1234", false);
- Resource expected3 = new Resource(WorkflowType.VNF, "1234", false);
- Resource expected4 = new Resource(WorkflowType.VFMODULE, "5678", false);
- Resource result = workflowAction.extractResourceIdAndTypeFromUri(uri);
- assertEquals(expected1.getResourceId(),result.getResourceId());
- assertEquals(expected1.getResourceType(),result.getResourceType());
- result = workflowAction.extractResourceIdAndTypeFromUri(uri2);
- assertEquals(expected2.getResourceId(),result.getResourceId());
- assertEquals(expected2.getResourceType(),result.getResourceType());
- result = workflowAction.extractResourceIdAndTypeFromUri(uri3);
- assertEquals("Service", result.getResourceType().toString());
- assertEquals(UUID.randomUUID().toString().length(),result.getResourceId().length());
- result = workflowAction.extractResourceIdAndTypeFromUri(uri4);
- assertEquals("Service", result.getResourceType().toString());
- assertEquals(UUID.randomUUID().toString().length(),result.getResourceId().length());
- result = workflowAction.extractResourceIdAndTypeFromUri(uri5);
- assertEquals("Vnf", result.getResourceType().toString());
- assertEquals(UUID.randomUUID().toString().length(),result.getResourceId().length());
- result = workflowAction.extractResourceIdAndTypeFromUri(uri6);
- assertEquals(expected3.getResourceId(),result.getResourceId());
- assertEquals(expected3.getResourceType(),result.getResourceType());
- result = workflowAction.extractResourceIdAndTypeFromUri(uri7);
- assertEquals(expected4.getResourceId(),result.getResourceId());
- assertEquals(expected4.getResourceType(),result.getResourceType());
- result = workflowAction.extractResourceIdAndTypeFromUri(uri8);
- assertEquals(UUID.randomUUID().toString().length(),result.getResourceId().length());
+
+ @Test
+ public void selectExecutionListALaCarteVfModuleNoFabricDeleteTest() throws Exception {
+ String gAction = "deleteInstance";
+ String resource = "VfModule";
+ execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688");
+ execution.setVariable("requestAction", gAction);
+ String bpmnRequest =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json")));
+ execution.setVariable("bpmnRequest", bpmnRequest);
+ execution.setVariable("aLaCarte", true);
+ execution.setVariable("apiVersion", "7");
+ execution.setVariable("requestUri",
+ "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules");
+
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("DeactivateVfModuleBB", "DeleteVfModuleBB",
+ "UnassignVfModuleBB", "DeactivateFabricConfigurationBB", "UnassignFabricConfigurationBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource,
+ true, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+
+ org.onap.aai.domain.yang.GenericVnf vnf = new org.onap.aai.domain.yang.GenericVnf();
+ vnf.setVnfId("vnf0");
+ vnf.setModelCustomizationId("modelCustomizationId");
+ when(bbSetupUtils.getAAIGenericVnf(anyObject())).thenReturn(vnf);
+
+ org.onap.aai.domain.yang.VfModule vfModule = new org.onap.aai.domain.yang.VfModule();
+ vfModule.setModelCustomizationId("modelCustomizationId");
+ when(bbSetupUtils.getAAIVfModule(anyObject(), anyObject())).thenReturn(vfModule);
+
+ List<org.onap.aai.domain.yang.Vnfc> vnfcs = new ArrayList<org.onap.aai.domain.yang.Vnfc>();
+ org.onap.aai.domain.yang.Vnfc vnfc = new org.onap.aai.domain.yang.Vnfc();
+ vnfc.setModelInvariantId("modelInvariantId");
+ vnfc.setVnfcName("testVnfcName");
+ vnfcs.add(vnfc);
+ doReturn(vnfcs).when(SPY_workflowAction).getRelatedResourcesInVfModule(anyObject(), anyObject(), anyObject(),
+ anyObject());
+
+ List<org.onap.aai.domain.yang.Configuration> configurations =
+ new ArrayList<org.onap.aai.domain.yang.Configuration>();
+ org.onap.aai.domain.yang.Configuration configuration = new org.onap.aai.domain.yang.Configuration();
+ doReturn(configurations).when(SPY_workflowAction).getRelatedResourcesInVnfc(anyObject(), anyObject(),
+ anyObject());
+
+ doReturn("testName").when(SPY_workflowAction).getVnfcNameForConfiguration(anyObject());
+
+ SPY_workflowAction.selectExecutionList(execution);
+ List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
+ assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleBB", "UnassignVfModuleBB");
+ }
+
+ @Test
+ public void getRelatedResourcesInVfModuleTest() throws Exception {
+ org.onap.aai.domain.yang.Vnfc vnfc = new org.onap.aai.domain.yang.Vnfc();
+ vnfc.setModelInvariantId("modelInvariantId");
+ vnfc.setVnfcName("testVnfcName");
+
+ String vfncPayload =
+ new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/BuildingBlocks/vnfcResponse.json")));
+ AAIResultWrapper vfncWrapper = new AAIResultWrapper(vfncPayload);
+
+ String configurationPayload =
+ new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/BuildingBlocks/configurationResponse.json")));
+ AAIResultWrapper configurationWrapper = new AAIResultWrapper(configurationPayload);
+ List<AAIResultWrapper> configurationResultWrappers = new ArrayList<AAIResultWrapper>();
+ configurationResultWrappers.add(configurationWrapper);
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VNFC, vnfc.getVnfcName());
+ when(bbSetupUtils.getAAIResourceDepthOne(uri)).thenReturn(vfncWrapper);
+
+ doReturn(configurationResultWrappers).when(SPY_workflowAction).getResultWrappersFromRelationships(anyObject(),
+ anyObject());
+ List<org.onap.aai.domain.yang.Configuration> configurationsList = SPY_workflowAction.getRelatedResourcesInVnfc(
+ vnfc, org.onap.aai.domain.yang.Configuration.class, AAIObjectType.CONFIGURATION);
+ assertEquals(1, configurationsList.size());
+ assertEquals("testConfigurationId", configurationsList.get(0).getConfigurationId());
+ }
+
+ /**
+ * WorkflowActionBB Tests
+ */
+
+ @Test
+ public void pluralTest() {
+ List<String> items = Arrays.asList("serviceInstances, Service", "vnfs, Vnf", "vfModules, VfModule",
+ "networks, Network", "invalidNames, invalidNames");
+ items.forEach(item -> {
+ String[] split = item.split(",");
+ String type = split[0].trim();
+ String expected = split[1].trim();
+ assertThat(workflowAction.convertTypeFromPlural(type), equalTo(expected));
+ });
+ }
+
+ @Test
+ public void sortExecutionPathByObjectForVlanTaggingCreateTest() throws Exception {
+ List<ExecuteBuildingBlock> executeFlows = new ArrayList<>();
+ ExecuteBuildingBlock ebb = new ExecuteBuildingBlock();
+ BuildingBlock bb = new BuildingBlock();
+ bb.setBpmnFlowName("AssignNetworkBB");
+ bb.setKey("0");
+ ebb.setBuildingBlock(bb);
+ executeFlows.add(ebb);
+ ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
+ BuildingBlock bb2 = new BuildingBlock();
+ bb2.setBpmnFlowName("AssignNetworkBB");
+ bb2.setKey("1");
+ ebb2.setBuildingBlock(bb2);
+ executeFlows.add(ebb2);
+ ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
+ BuildingBlock bb3 = new BuildingBlock();
+ bb3.setBpmnFlowName("CreateNetworkBB");
+ bb3.setKey("0");
+ ebb3.setBuildingBlock(bb3);
+ executeFlows.add(ebb3);
+ ExecuteBuildingBlock ebb4 = new ExecuteBuildingBlock();
+ BuildingBlock bb4 = new BuildingBlock();
+ bb4.setBpmnFlowName("CreateNetworkBB");
+ bb4.setKey("1");
+ ebb4.setBuildingBlock(bb4);
+ executeFlows.add(ebb4);
+ ExecuteBuildingBlock ebb5 = new ExecuteBuildingBlock();
+ BuildingBlock bb5 = new BuildingBlock();
+ bb5.setBpmnFlowName("ActivateNetworkBB");
+ bb5.setKey("0");
+ ebb5.setBuildingBlock(bb5);
+ executeFlows.add(ebb5);
+ ExecuteBuildingBlock ebb6 = new ExecuteBuildingBlock();
+ BuildingBlock bb6 = new BuildingBlock();
+ bb6.setBpmnFlowName("ActivateNetworkBB");
+ bb6.setKey("1");
+ ebb6.setBuildingBlock(bb6);
+ executeFlows.add(ebb6);
+
+ List<ExecuteBuildingBlock> sorted =
+ workflowAction.sortExecutionPathByObjectForVlanTagging(executeFlows, "createInstance");
+ assertEqualsBulkFlowName(sorted, "AssignNetworkBB", "CreateNetworkBB", "ActivateNetworkBB", "AssignNetworkBB",
+ "CreateNetworkBB", "ActivateNetworkBB");
+ }
+
+ @Test
+ public void sortExecutionPathByObjectForVlanTaggingDeleteTest() throws Exception {
+ List<ExecuteBuildingBlock> executeFlows = new ArrayList<>();
+ ExecuteBuildingBlock ebb = new ExecuteBuildingBlock();
+ BuildingBlock bb = new BuildingBlock();
+ bb.setBpmnFlowName("DeactivateNetworkBB");
+ bb.setKey("0");
+ ebb.setBuildingBlock(bb);
+ executeFlows.add(ebb);
+ ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock();
+ BuildingBlock bb2 = new BuildingBlock();
+ bb2.setBpmnFlowName("DeactivateNetworkBB");
+ bb2.setKey("1");
+ ebb2.setBuildingBlock(bb2);
+ executeFlows.add(ebb2);
+ ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock();
+ BuildingBlock bb3 = new BuildingBlock();
+ bb3.setBpmnFlowName("DeleteNetworkBB");
+ bb3.setKey("0");
+ ebb3.setBuildingBlock(bb3);
+ executeFlows.add(ebb3);
+ ExecuteBuildingBlock ebb4 = new ExecuteBuildingBlock();
+ BuildingBlock bb4 = new BuildingBlock();
+ bb4.setBpmnFlowName("DeleteNetworkBB");
+ bb4.setKey("1");
+ ebb4.setBuildingBlock(bb4);
+ executeFlows.add(ebb4);
+ ExecuteBuildingBlock ebb5 = new ExecuteBuildingBlock();
+ BuildingBlock bb5 = new BuildingBlock();
+ bb5.setBpmnFlowName("UnassignNetworkBB");
+ bb5.setKey("0");
+ ebb5.setBuildingBlock(bb5);
+ executeFlows.add(ebb5);
+ ExecuteBuildingBlock ebb6 = new ExecuteBuildingBlock();
+ BuildingBlock bb6 = new BuildingBlock();
+ bb6.setBpmnFlowName("UnassignNetworkBB");
+ bb6.setKey("1");
+ ebb6.setBuildingBlock(bb6);
+ executeFlows.add(ebb6);
+
+ List<ExecuteBuildingBlock> sorted =
+ workflowAction.sortExecutionPathByObjectForVlanTagging(executeFlows, "deleteInstance");
+ assertEqualsBulkFlowName(sorted, "DeactivateNetworkBB", "DeleteNetworkBB", "UnassignNetworkBB",
+ "DeactivateNetworkBB", "DeleteNetworkBB", "UnassignNetworkBB");
+ }
+
+ @Test
+ public void queryNorthBoundRequestCatalogDbNestedTest() throws MalformedURLException {
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("AAICheckVnfInMaintBB", "AAISetVnfInMaintBB",
+ "VNF-Macro-Replace", "SDNOVnfHealthCheckBB", "AAIUnsetVnfInMaintBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+ List<OrchestrationFlow> macroFlows = createFlowList("DeactivateVfModuleBB", "DeleteVfModuleBB",
+ "DeactivateVnfBB", "CreateVfModuleBB", "ActivateVfModuleBB", "ActivateVnfBB");
+
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner("replaceInstance",
+ "Vnf", false, "my-custom-cloud-owner")).thenReturn(northBoundRequest);
+ when(catalogDbClient.getOrchestrationFlowByAction("VNF-Macro-Replace")).thenReturn(macroFlows);
+ List<OrchestrationFlow> flows = workflowAction.queryNorthBoundRequestCatalogDb(execution, "replaceInstance",
+ WorkflowType.VNF, false, "my-custom-cloud-owner");
+ assertEquals(flows.get(0).getFlowName(), "AAICheckVnfInMaintBB");
+ assertEquals(flows.get(1).getFlowName(), "AAISetVnfInMaintBB");
+ assertEquals(flows.get(2).getFlowName(), "DeactivateVfModuleBB");
+ assertEquals(flows.get(3).getFlowName(), "DeleteVfModuleBB");
+ assertEquals(flows.get(4).getFlowName(), "DeactivateVnfBB");
+ assertEquals(flows.get(5).getFlowName(), "CreateVfModuleBB");
+ assertEquals(flows.get(6).getFlowName(), "ActivateVfModuleBB");
+ assertEquals(flows.get(7).getFlowName(), "ActivateVnfBB");
+ assertEquals(flows.get(8).getFlowName(), "SDNOVnfHealthCheckBB");
+ assertEquals(flows.get(9).getFlowName(), "AAIUnsetVnfInMaintBB");
+ }
+
+ @Test
+ public void queryNorthBoundRequestCatalogDbTransportTest() throws MalformedURLException {
+ NorthBoundRequest northBoundRequest = new NorthBoundRequest();
+ List<OrchestrationFlow> orchFlows = createFlowList("AssignServiceInstanceBB");
+ northBoundRequest.setOrchestrationFlowList(orchFlows);
+ when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwnerAndServiceType(
+ "createInstance", "Service", true, "my-custom-cloud-owner", "TRANSPORT")).thenReturn(northBoundRequest);
+
+ List<OrchestrationFlow> flows = workflowAction.queryNorthBoundRequestCatalogDb(execution, "createInstance",
+ WorkflowType.SERVICE, true, "my-custom-cloud-owner", "TRANSPORT");
+ assertEquals(flows.get(0).getFlowName(), "AssignServiceInstanceBB");
+ }
+
+ @Test
+ public void extractResourceIdAndTypeFromUriTest() {
+ String uri = "/v6/serviceInstances/123";
+ String uri2 = "/v6/serviceInstances/123/vnfs/1234";
+ String uri3 = "/v6/serviceInstances";
+ String uri4 = "/v6/serviceInstances/assign";
+ String uri5 = "'/v6/serviceInstances/123/vnfs";
+ String uri6 = "/v6/serviceInstances/123/vnfs/1234/someAction";
+ String uri7 = "/v6/serviceInstances/123/vnfs/1234/vfModules/5678/replace";
+ String uri8 = "/v6/serviceInstances/123/vnfs/1234/vfModules/scaleOut";
+ Resource expected1 = new Resource(WorkflowType.SERVICE, "123", true);
+ Resource expected2 = new Resource(WorkflowType.VNF, "1234", false);
+ Resource expected3 = new Resource(WorkflowType.VNF, "1234", false);
+ Resource expected4 = new Resource(WorkflowType.VFMODULE, "5678", false);
+ Resource result = workflowAction.extractResourceIdAndTypeFromUri(uri);
+ assertEquals(expected1.getResourceId(), result.getResourceId());
+ assertEquals(expected1.getResourceType(), result.getResourceType());
+ result = workflowAction.extractResourceIdAndTypeFromUri(uri2);
+ assertEquals(expected2.getResourceId(), result.getResourceId());
+ assertEquals(expected2.getResourceType(), result.getResourceType());
+ result = workflowAction.extractResourceIdAndTypeFromUri(uri3);
+ assertEquals("Service", result.getResourceType().toString());
+ assertEquals(UUID.randomUUID().toString().length(), result.getResourceId().length());
+ result = workflowAction.extractResourceIdAndTypeFromUri(uri4);
+ assertEquals("Service", result.getResourceType().toString());
+ assertEquals(UUID.randomUUID().toString().length(), result.getResourceId().length());
+ result = workflowAction.extractResourceIdAndTypeFromUri(uri5);
+ assertEquals("Vnf", result.getResourceType().toString());
+ assertEquals(UUID.randomUUID().toString().length(), result.getResourceId().length());
+ result = workflowAction.extractResourceIdAndTypeFromUri(uri6);
+ assertEquals(expected3.getResourceId(), result.getResourceId());
+ assertEquals(expected3.getResourceType(), result.getResourceType());
+ result = workflowAction.extractResourceIdAndTypeFromUri(uri7);
+ assertEquals(expected4.getResourceId(), result.getResourceId());
+ assertEquals(expected4.getResourceType(), result.getResourceType());
+ result = workflowAction.extractResourceIdAndTypeFromUri(uri8);
+ assertEquals(UUID.randomUUID().toString().length(), result.getResourceId().length());
assertEquals("VfModule", result.getResourceType().toString());
-
- }
-
- @Test
- public void extractResourceIdAndTypeFromUriInvalidTypeTest() {
- this.expectedException.expect(IllegalArgumentException.class);
- this.expectedException.expectMessage(containsString("Uri could not be parsed. No type found."));
- workflowAction.extractResourceIdAndTypeFromUri("/v6/serviceInstances/123/vnfs/1234/vfmodules/5678/replace");
- }
-
- @Test
- public void extractResourceIdAndTypeFromUriInvalidUriTest() {
- this.expectedException.expect(IllegalArgumentException.class);
- this.expectedException.expectMessage(containsString("Uri could not be parsed:"));
- workflowAction.extractResourceIdAndTypeFromUri("something that doesn't match anything");
- }
-
- @Test
- public void populateResourceIdsFromApiHandlerTest(){
- execution.setVariable("serviceInstanceId", "123");
- execution.setVariable("vnfId", "888");
- WorkflowResourceIds x = workflowAction.populateResourceIdsFromApiHandler(execution);
- assertEquals("123",x.getServiceInstanceId());
- assertEquals("888",x.getVnfId());
- assertNull(x.getVolumeGroupId());
- }
-
- @Test
- public void validateResourceIdInAAITest() throws Exception{
- //SI
- RequestDetails reqDetails = new RequestDetails();
- SubscriberInfo subInfo = new SubscriberInfo();
- subInfo.setGlobalSubscriberId("id123");
- reqDetails.setSubscriberInfo(subInfo);
- RequestParameters reqParams = new RequestParameters();
- reqParams.setSubscriptionServiceType("subServiceType123");
- reqDetails.setRequestParameters(reqParams );
- WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
- ServiceInstance si = new ServiceInstance();
- si.setServiceInstanceId("siId123");
- Optional<ServiceInstance> siOp = Optional.of(si);
- when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "siName123")).thenReturn(siOp);
- when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "111111")).thenReturn(Optional.empty());
- String id = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.SERVICE, "siName123", reqDetails, workflowResourceIds);
- assertEquals("siId123",id);
- String id2 = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.SERVICE, "111111", reqDetails, workflowResourceIds);
- assertEquals("generatedId123",id2);
-
- //Network
- L3Network network = new L3Network();
- network.setNetworkId("id123");
- network.setNetworkName("name123");
- workflowResourceIds.setServiceInstanceId("siId123");
- Optional<L3Network> opNetwork = Optional.of(network);
- when(bbSetupUtils.getRelatedNetworkByNameFromServiceInstance("siId123","name123")).thenReturn(opNetwork);
- when(bbSetupUtils.getRelatedNetworkByNameFromServiceInstance("siId123","111111")).thenReturn(Optional.empty());
- id = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.NETWORK, "name123", reqDetails, workflowResourceIds);
- assertEquals("id123",id);
- id2 = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.NETWORK, "111111", reqDetails, workflowResourceIds);
- assertEquals("generatedId123",id2);
-
- //Vnf
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("id123");
- vnf.setVnfName("vnfName123");
- Optional<GenericVnf> opVnf = Optional.of(vnf);
- when(bbSetupUtils.getRelatedVnfByNameFromServiceInstance("siId123","name123")).thenReturn(opVnf);
- when(bbSetupUtils.getRelatedVnfByNameFromServiceInstance("siId123","111111")).thenReturn(Optional.empty());
- id = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VNF, "name123", reqDetails, workflowResourceIds);
- assertEquals("id123",id);
- id2 = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VNF, "111111", reqDetails, workflowResourceIds);
- assertEquals("generatedId123",id2);
-
- //VfModule
- VfModules vfModules = new VfModules();
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("id123");
- vfModule.setVfModuleName("name123");
- vfModules.getVfModule().add(vfModule);
- vnf.setVfModules(vfModules);
- workflowResourceIds.setVnfId("id123");
- when(bbSetupUtils.getAAIGenericVnf("id123")).thenReturn(vnf);
- id = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VFMODULE, "name123", reqDetails, workflowResourceIds);
- assertEquals("id123",id);
-
- GenericVnf vnf2 = new GenericVnf();
- VfModules vfModules2 = new VfModules();
- VfModule vfModule2 = new VfModule();
- vfModule2.setVfModuleId("id123");
- vfModule2.setVfModuleName("name123");
- vfModules2.getVfModule().add(vfModule2);
- vnf2.setVfModules(vfModules2);
- workflowResourceIds.setVnfId("id111");
- when(bbSetupUtils.getAAIGenericVnf("id111")).thenReturn(vnf2);
- id2 = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VFMODULE, "111111", reqDetails, workflowResourceIds);
- assertEquals("generatedId123",id2);
-
- //VolumeGroup
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("id123");
- volumeGroup.setVolumeGroupName("name123");
- workflowResourceIds.setVnfId("id123");
- Optional<VolumeGroup> opVolumeGroup = Optional.of(volumeGroup);
- when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("id123","name123")).thenReturn(opVolumeGroup);
- id = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VOLUMEGROUP, "name123", reqDetails, workflowResourceIds);
- assertEquals("id123",id);
-
- workflowResourceIds.setVnfId("id444");
- when(bbSetupUtils.getAAIGenericVnf("id444")).thenReturn(vnf);
- when(bbSetupUtils.getRelatedVolumeGroupByNameFromVfModule("id123", "id123","111111")).thenReturn(opVolumeGroup);
- when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("id444","111111")).thenReturn(Optional.empty());
- id2 = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VOLUMEGROUP, "111111", reqDetails, workflowResourceIds);
- assertEquals("id123",id2);
- }
-
- @Test
- public void handleRuntimeExceptionTest(){
- execution.setVariable("BPMN_javaExpMsg", "test runtime error message");
- execution.setVariable("testProcessKey", "testProcessKeyValue");
- try{
- workflowAction.handleRuntimeException(execution);
- } catch (BpmnError wfe) {
- assertEquals("MSOWorkflowException",wfe.getErrorCode());
- }
- }
-
- @Ignore
- @Test
- public void traverseCatalogDbServiceMultipleNetworkTest() throws IOException{
- execution.setVariable("testProcessKey", "testProcessKeyValue");
- Service service = new Service();
- List<NetworkResourceCustomization> networkCustomizations = new ArrayList<>();
- NetworkResourceCustomization networkCust = new NetworkResourceCustomization();
- networkCust.setModelCustomizationUUID("123");
- networkCustomizations.add(networkCust);
- service.setNetworkCustomizations(networkCustomizations);
- NetworkCollectionResourceCustomization collectionResourceCustomization = new NetworkCollectionResourceCustomization();
- collectionResourceCustomization.setModelCustomizationUUID("123");
- CollectionResource collectionResource = new CollectionResource();
- collectionResource.setToscaNodeType("NetworkCollection");
- InstanceGroup instanceGroup = new InstanceGroup();
- List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupCustomizations = new ArrayList<>();
- CollectionResourceInstanceGroupCustomization collectionInstanceGroupCustomization = new CollectionResourceInstanceGroupCustomization();
- collectionInstanceGroupCustomization.setSubInterfaceNetworkQuantity(3);
- collectionInstanceGroupCustomizations.add(collectionInstanceGroupCustomization);
- instanceGroup.setCollectionInstanceGroupCustomizations(collectionInstanceGroupCustomizations);
- collectionResource.setInstanceGroup(instanceGroup);
- collectionResourceCustomization.setCollectionResource(collectionResource);;
- service.setModelUUID("abc");
- service.getCollectionResourceCustomizations().add(collectionResourceCustomization);
- service.getCollectionResourceCustomizations().add(collectionResourceCustomization);
- doReturn(service).when(catalogDbClient).getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a");
- doReturn(collectionResourceCustomization).when(catalogDbClient).getNetworkCollectionResourceCustomizationByID("123");
- String bpmnRequest = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
- ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class);
- List<Resource> resourceCounter = new ArrayList<>();
- thrown.expect(BpmnError.class);
- workflowAction.traverseCatalogDbService(execution, sIRequest, resourceCounter);
- }
-
- @Test
- public void sortVfModulesByBaseFirstTest(){
- List<Resource> resources = new ArrayList<>();
- Resource resource1 = new Resource(WorkflowType.VFMODULE,"111",false);
- resource1.setBaseVfModule(false);
- resources.add(resource1);
- Resource resource2 = new Resource(WorkflowType.VFMODULE,"222",false);
- resource2.setBaseVfModule(false);
- resources.add(resource2);
- Resource resource3 = new Resource(WorkflowType.VFMODULE,"333",false);
- resource3.setBaseVfModule(true);
- resources.add(resource3);
- List<Resource> result = workflowAction.sortVfModulesByBaseFirst(resources);
- assertEquals("333",result.get(0).getResourceId());
- assertEquals("222",result.get(1).getResourceId());
- assertEquals("111",result.get(2).getResourceId());
- }
-
- @Test
- public void sortVfModulesByBaseLastTest(){
- List<Resource> resources = new ArrayList<>();
- Resource resource1 = new Resource(WorkflowType.VFMODULE,"111",false);
- resource1.setBaseVfModule(true);
- resources.add(resource1);
- Resource resource2 = new Resource(WorkflowType.VFMODULE,"222",false);
- resource2.setBaseVfModule(false);
- resources.add(resource2);
- Resource resource3 = new Resource(WorkflowType.VFMODULE,"333",false);
- resource3.setBaseVfModule(false);
- resources.add(resource3);
- List<Resource> result = workflowAction.sortVfModulesByBaseLast(resources);
- assertEquals("333",result.get(0).getResourceId());
- assertEquals("222",result.get(1).getResourceId());
- assertEquals("111",result.get(2).getResourceId());
- }
+
+ }
+
+ @Test
+ public void extractResourceIdAndTypeFromUriInvalidTypeTest() {
+ this.expectedException.expect(IllegalArgumentException.class);
+ this.expectedException.expectMessage(containsString("Uri could not be parsed. No type found."));
+ workflowAction.extractResourceIdAndTypeFromUri("/v6/serviceInstances/123/vnfs/1234/vfmodules/5678/replace");
+ }
+
+ @Test
+ public void extractResourceIdAndTypeFromUriInvalidUriTest() {
+ this.expectedException.expect(IllegalArgumentException.class);
+ this.expectedException.expectMessage(containsString("Uri could not be parsed:"));
+ workflowAction.extractResourceIdAndTypeFromUri("something that doesn't match anything");
+ }
+
+ @Test
+ public void populateResourceIdsFromApiHandlerTest() {
+ execution.setVariable("serviceInstanceId", "123");
+ execution.setVariable("vnfId", "888");
+ WorkflowResourceIds x = workflowAction.populateResourceIdsFromApiHandler(execution);
+ assertEquals("123", x.getServiceInstanceId());
+ assertEquals("888", x.getVnfId());
+ assertNull(x.getVolumeGroupId());
+ }
+
+ @Test
+ public void validateResourceIdInAAITest() throws Exception {
+ // SI
+ RequestDetails reqDetails = new RequestDetails();
+ SubscriberInfo subInfo = new SubscriberInfo();
+ subInfo.setGlobalSubscriberId("id123");
+ reqDetails.setSubscriberInfo(subInfo);
+ RequestParameters reqParams = new RequestParameters();
+ reqParams.setSubscriptionServiceType("subServiceType123");
+ reqDetails.setRequestParameters(reqParams);
+ WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
+ ServiceInstance si = new ServiceInstance();
+ si.setServiceInstanceId("siId123");
+ Optional<ServiceInstance> siOp = Optional.of(si);
+ when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "siName123")).thenReturn(siOp);
+ when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "111111"))
+ .thenReturn(Optional.empty());
+ String id = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.SERVICE, "siName123",
+ reqDetails, workflowResourceIds);
+ assertEquals("siId123", id);
+ String id2 = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.SERVICE, "111111",
+ reqDetails, workflowResourceIds);
+ assertEquals("generatedId123", id2);
+
+ // Network
+ L3Network network = new L3Network();
+ network.setNetworkId("id123");
+ network.setNetworkName("name123");
+ workflowResourceIds.setServiceInstanceId("siId123");
+ Optional<L3Network> opNetwork = Optional.of(network);
+ when(bbSetupUtils.getRelatedNetworkByNameFromServiceInstance("siId123", "name123")).thenReturn(opNetwork);
+ when(bbSetupUtils.getRelatedNetworkByNameFromServiceInstance("siId123", "111111")).thenReturn(Optional.empty());
+ id = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.NETWORK, "name123", reqDetails,
+ workflowResourceIds);
+ assertEquals("id123", id);
+ id2 = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.NETWORK, "111111", reqDetails,
+ workflowResourceIds);
+ assertEquals("generatedId123", id2);
+
+ // Vnf
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("id123");
+ vnf.setVnfName("vnfName123");
+ Optional<GenericVnf> opVnf = Optional.of(vnf);
+ when(bbSetupUtils.getRelatedVnfByNameFromServiceInstance("siId123", "name123")).thenReturn(opVnf);
+ when(bbSetupUtils.getRelatedVnfByNameFromServiceInstance("siId123", "111111")).thenReturn(Optional.empty());
+ id = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VNF, "name123", reqDetails,
+ workflowResourceIds);
+ assertEquals("id123", id);
+ id2 = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VNF, "111111", reqDetails,
+ workflowResourceIds);
+ assertEquals("generatedId123", id2);
+
+ // VfModule
+ VfModules vfModules = new VfModules();
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("id123");
+ vfModule.setVfModuleName("name123");
+ vfModules.getVfModule().add(vfModule);
+ vnf.setVfModules(vfModules);
+ workflowResourceIds.setVnfId("id123");
+ when(bbSetupUtils.getAAIGenericVnf("id123")).thenReturn(vnf);
+ id = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VFMODULE, "name123", reqDetails,
+ workflowResourceIds);
+ assertEquals("id123", id);
+
+ GenericVnf vnf2 = new GenericVnf();
+ VfModules vfModules2 = new VfModules();
+ VfModule vfModule2 = new VfModule();
+ vfModule2.setVfModuleId("id123");
+ vfModule2.setVfModuleName("name123");
+ vfModules2.getVfModule().add(vfModule2);
+ vnf2.setVfModules(vfModules2);
+ workflowResourceIds.setVnfId("id111");
+ when(bbSetupUtils.getAAIGenericVnf("id111")).thenReturn(vnf2);
+ id2 = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VFMODULE, "111111", reqDetails,
+ workflowResourceIds);
+ assertEquals("generatedId123", id2);
+
+ // VolumeGroup
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("id123");
+ volumeGroup.setVolumeGroupName("name123");
+ workflowResourceIds.setVnfId("id123");
+ Optional<VolumeGroup> opVolumeGroup = Optional.of(volumeGroup);
+ when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("id123", "name123")).thenReturn(opVolumeGroup);
+ id = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VOLUMEGROUP, "name123", reqDetails,
+ workflowResourceIds);
+ assertEquals("id123", id);
+
+ workflowResourceIds.setVnfId("id444");
+ when(bbSetupUtils.getAAIGenericVnf("id444")).thenReturn(vnf);
+ when(bbSetupUtils.getRelatedVolumeGroupByNameFromVfModule("id123", "id123", "111111"))
+ .thenReturn(opVolumeGroup);
+ when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("id444", "111111")).thenReturn(Optional.empty());
+ id2 = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VOLUMEGROUP, "111111", reqDetails,
+ workflowResourceIds);
+ assertEquals("id123", id2);
+ }
+
+ @Test
+ public void handleRuntimeExceptionTest() {
+ execution.setVariable("BPMN_javaExpMsg", "test runtime error message");
+ execution.setVariable("testProcessKey", "testProcessKeyValue");
+ try {
+ workflowAction.handleRuntimeException(execution);
+ } catch (BpmnError wfe) {
+ assertEquals("MSOWorkflowException", wfe.getErrorCode());
+ }
+ }
+
+ @Ignore
+ @Test
+ public void traverseCatalogDbServiceMultipleNetworkTest() throws IOException {
+ execution.setVariable("testProcessKey", "testProcessKeyValue");
+ Service service = new Service();
+ List<NetworkResourceCustomization> networkCustomizations = new ArrayList<>();
+ NetworkResourceCustomization networkCust = new NetworkResourceCustomization();
+ networkCust.setModelCustomizationUUID("123");
+ networkCustomizations.add(networkCust);
+ service.setNetworkCustomizations(networkCustomizations);
+ NetworkCollectionResourceCustomization collectionResourceCustomization =
+ new NetworkCollectionResourceCustomization();
+ collectionResourceCustomization.setModelCustomizationUUID("123");
+ CollectionResource collectionResource = new CollectionResource();
+ collectionResource.setToscaNodeType("NetworkCollection");
+ InstanceGroup instanceGroup = new InstanceGroup();
+ List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupCustomizations = new ArrayList<>();
+ CollectionResourceInstanceGroupCustomization collectionInstanceGroupCustomization =
+ new CollectionResourceInstanceGroupCustomization();
+ collectionInstanceGroupCustomization.setSubInterfaceNetworkQuantity(3);
+ collectionInstanceGroupCustomizations.add(collectionInstanceGroupCustomization);
+ instanceGroup.setCollectionInstanceGroupCustomizations(collectionInstanceGroupCustomizations);
+ collectionResource.setInstanceGroup(instanceGroup);
+ collectionResourceCustomization.setCollectionResource(collectionResource);;
+ service.setModelUUID("abc");
+ service.getCollectionResourceCustomizations().add(collectionResourceCustomization);
+ service.getCollectionResourceCustomizations().add(collectionResourceCustomization);
+ doReturn(service).when(catalogDbClient).getServiceByID("3c40d244-808e-42ca-b09a-256d83d19d0a");
+ doReturn(collectionResourceCustomization).when(catalogDbClient)
+ .getNetworkCollectionResourceCustomizationByID("123");
+ String bpmnRequest = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class);
+ List<Resource> resourceCounter = new ArrayList<>();
+ thrown.expect(BpmnError.class);
+ workflowAction.traverseCatalogDbService(execution, sIRequest, resourceCounter);
+ }
+
+ @Test
+ public void sortVfModulesByBaseFirstTest() {
+ List<Resource> resources = new ArrayList<>();
+ Resource resource1 = new Resource(WorkflowType.VFMODULE, "111", false);
+ resource1.setBaseVfModule(false);
+ resources.add(resource1);
+ Resource resource2 = new Resource(WorkflowType.VFMODULE, "222", false);
+ resource2.setBaseVfModule(false);
+ resources.add(resource2);
+ Resource resource3 = new Resource(WorkflowType.VFMODULE, "333", false);
+ resource3.setBaseVfModule(true);
+ resources.add(resource3);
+ List<Resource> result = workflowAction.sortVfModulesByBaseFirst(resources);
+ assertEquals("333", result.get(0).getResourceId());
+ assertEquals("222", result.get(1).getResourceId());
+ assertEquals("111", result.get(2).getResourceId());
+ }
+
+ @Test
+ public void sortVfModulesByBaseLastTest() {
+ List<Resource> resources = new ArrayList<>();
+ Resource resource1 = new Resource(WorkflowType.VFMODULE, "111", false);
+ resource1.setBaseVfModule(true);
+ resources.add(resource1);
+ Resource resource2 = new Resource(WorkflowType.VFMODULE, "222", false);
+ resource2.setBaseVfModule(false);
+ resources.add(resource2);
+ Resource resource3 = new Resource(WorkflowType.VFMODULE, "333", false);
+ resource3.setBaseVfModule(false);
+ resources.add(resource3);
+ List<Resource> result = workflowAction.sortVfModulesByBaseLast(resources);
+ assertEquals("333", result.get(0).getResourceId());
+ assertEquals("222", result.get(1).getResourceId());
+ assertEquals("111", result.get(2).getResourceId());
+ }
@Test
public void findCatalogNetworkCollectionTest() {
@@ -1468,35 +1657,34 @@ public class WorkflowActionTest extends BaseTaskTest {
doReturn(networkCustomization2).when(catalogDbClient).getNetworkCollectionResourceCustomizationByID("321");
workflowAction.findCatalogNetworkCollection(execution, service);
assertEquals("Found multiple Network Collections in the Service model, only one per Service is supported.",
- execution.getVariable("WorkflowActionErrorMessage"));
+ execution.getVariable("WorkflowActionErrorMessage"));
}
@Test
- public void verifyLackOfNullPointerExceptionForNullResource(){
- ExecuteBuildingBlock result = null;
- try {
- result = workflowAction
- .buildExecuteBuildingBlock(new OrchestrationFlow(), null, null, null, null, null, false,
- null, null, null, false, null, true);
- }catch (NullPointerException e){
- fail("NullPointerException should not be thrown when 'resource' is null");
- }
- assertNotNull(result);
+ public void verifyLackOfNullPointerExceptionForNullResource() {
+ ExecuteBuildingBlock result = null;
+ try {
+ result = workflowAction.buildExecuteBuildingBlock(new OrchestrationFlow(), null, null, null, null, null,
+ false, null, null, null, false, null, true);
+ } catch (NullPointerException e) {
+ fail("NullPointerException should not be thrown when 'resource' is null");
+ }
+ assertNotNull(result);
}
- private List<OrchestrationFlow> createFlowList (String... flowNames){
- List<OrchestrationFlow> result = new ArrayList<>();
- for(String flowName : flowNames){
- OrchestrationFlow orchFlow = new OrchestrationFlow();
- orchFlow.setFlowName(flowName);
- result.add(orchFlow);
- }
- return result;
- }
-
- private void assertEqualsBulkFlowName (List<ExecuteBuildingBlock> ebbs, String... flowNames){
- for(int i = 0; i<ebbs.size(); i++){
- assertEquals(ebbs.get(i).getBuildingBlock().getBpmnFlowName(),flowNames[i]);
- }
- }
+ private List<OrchestrationFlow> createFlowList(String... flowNames) {
+ List<OrchestrationFlow> result = new ArrayList<>();
+ for (String flowName : flowNames) {
+ OrchestrationFlow orchFlow = new OrchestrationFlow();
+ orchFlow.setFlowName(flowName);
+ result.add(orchFlow);
+ }
+ return result;
+ }
+
+ private void assertEqualsBulkFlowName(List<ExecuteBuildingBlock> ebbs, String... flowNames) {
+ for (int i = 0; i < ebbs.size(); i++) {
+ assertEquals(ebbs.get(i).getBuildingBlock().getBpmnFlowName(), flowNames[i]);
+ }
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionUnitTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionUnitTest.java
index ada8a237e7..34ad1b0fd4 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionUnitTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionUnitTest.java
@@ -31,7 +31,6 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
@@ -39,7 +38,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -65,57 +63,59 @@ import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
@RunWith(MockitoJUnitRunner.class)
public class WorkflowActionUnitTest {
- private final static String JSON_FILE_LOCATION = "src/test/resources/__files/Macro/";
-
- @Mock
- private CatalogDbClient catalogDbClient;
- @Mock
- private BBInputSetup bbInputSetup;
- @Mock
- private BBInputSetupUtils bbInputSetupUtils;
- @Mock
- private ExceptionBuilder exceptionBuilder;
- @Mock
- private AAIConfigurationResources aaiConfigurationResources;
-
- @InjectMocks
- @Spy
- private WorkflowAction workflowAction;
-
- @Test
- public void traverseCatalogDbForConfigurationTest() {
-
- CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
- CvnfcConfigurationCustomization vfModuleCustomization = new CvnfcConfigurationCustomization();
- ConfigurationResource configuration = new ConfigurationResource();
- configuration.setToscaNodeType("FabricConfiguration");
- configuration.setModelUUID("my-uuid");
- vfModuleCustomization.setConfigurationResource(configuration);
- cvnfcCustomization.setCvnfcConfigurationCustomization(Collections.singleton(vfModuleCustomization));
- List<CvnfcCustomization> cvnfcCustomizations = Arrays.asList(cvnfcCustomization);
- // when(catalogDbClient.getCvnfcCustomizationByVnfCustomizationUUIDAndVfModuleCustomizationUUID(any(String.class), any(String.class)))
- // .thenReturn(cvnfcCustomizations);
-
- // List<CvnfcConfigurationCustomization> results = workflowAction.traverseCatalogDbForConfiguration("myVnfCustomizationId", "myVfModuleCustomizationId");
-
- //assertThat(results, is(Arrays.asList(vfModuleCustomization)));
-
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + filename)));
- }
-
- private List<OrchestrationFlow> createFlowList(String... myList) {
-
- List<OrchestrationFlow> result = new ArrayList<>();
- for (String name : myList) {
- OrchestrationFlow flow = new OrchestrationFlow();
- flow.setFlowName(name);
- result.add(flow);
- }
-
- return result;
-
- }
+ private final static String JSON_FILE_LOCATION = "src/test/resources/__files/Macro/";
+
+ @Mock
+ private CatalogDbClient catalogDbClient;
+ @Mock
+ private BBInputSetup bbInputSetup;
+ @Mock
+ private BBInputSetupUtils bbInputSetupUtils;
+ @Mock
+ private ExceptionBuilder exceptionBuilder;
+ @Mock
+ private AAIConfigurationResources aaiConfigurationResources;
+
+ @InjectMocks
+ @Spy
+ private WorkflowAction workflowAction;
+
+ @Test
+ public void traverseCatalogDbForConfigurationTest() {
+
+ CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
+ CvnfcConfigurationCustomization vfModuleCustomization = new CvnfcConfigurationCustomization();
+ ConfigurationResource configuration = new ConfigurationResource();
+ configuration.setToscaNodeType("FabricConfiguration");
+ configuration.setModelUUID("my-uuid");
+ vfModuleCustomization.setConfigurationResource(configuration);
+ cvnfcCustomization.setCvnfcConfigurationCustomization(Collections.singleton(vfModuleCustomization));
+ List<CvnfcCustomization> cvnfcCustomizations = Arrays.asList(cvnfcCustomization);
+ // when(catalogDbClient.getCvnfcCustomizationByVnfCustomizationUUIDAndVfModuleCustomizationUUID(any(String.class),
+ // any(String.class)))
+ // .thenReturn(cvnfcCustomizations);
+
+ // List<CvnfcConfigurationCustomization> results =
+ // workflowAction.traverseCatalogDbForConfiguration("myVnfCustomizationId", "myVfModuleCustomizationId");
+
+ // assertThat(results, is(Arrays.asList(vfModuleCustomization)));
+
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + filename)));
+ }
+
+ private List<OrchestrationFlow> createFlowList(String... myList) {
+
+ List<OrchestrationFlow> result = new ArrayList<>();
+ for (String name : myList) {
+ OrchestrationFlow flow = new OrchestrationFlow();
+ flow.setFlowName(name);
+ result.add(flow);
+ }
+
+ return result;
+
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasksTest.java
index 329f2cf8c1..c235902561 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasksTest.java
@@ -27,7 +27,6 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import org.camunda.bpm.engine.delegate.BpmnError;
import org.junit.Before;
import org.junit.Test;
@@ -47,62 +46,66 @@ import org.onap.so.client.orchestration.SDNOHealthCheckResources;
@RunWith(MockitoJUnitRunner.Silent.class)
public class SDNOHealthCheckTasksTest extends TestDataSetup {
-
- @InjectMocks
- protected SDNOHealthCheckTasks sdnoHealthCheckTasks = new SDNOHealthCheckTasks();
-
- @Mock
- SDNOHealthCheckResources MOCK_sdnoHealthCheckResources;
-
-
- @Mock
- private ExceptionBuilder exceptionUtil;
-
- @Mock
- private ExtractPojosForBB extractPojosForBB;
-
-
- private RequestContext requestContext;
- private GenericVnf genericVnf;
-
- @Before
- public void before() throws BBObjectNotFoundException {
- genericVnf = setGenericVnf();
- requestContext = setRequestContext();
- when(extractPojosForBB.extractByKey(any(),any())).thenReturn(genericVnf);
-
- }
-
- @Test
- public void sdnoHealthCheckTest() throws Exception {
- doReturn(true).when(MOCK_sdnoHealthCheckResources).healthCheck(genericVnf, requestContext);
- sdnoHealthCheckTasks.sdnoHealthCheck(execution);
- verify(MOCK_sdnoHealthCheckResources, times(1)).healthCheck(genericVnf, requestContext);
- }
-
- @Test
- public void sdnoHealthCheckNoResponseTest() throws Exception {
-
- doReturn(false).when(MOCK_sdnoHealthCheckResources).healthCheck(genericVnf, requestContext);
- try {
- sdnoHealthCheckTasks.sdnoHealthCheck(execution);
- } catch (Exception e) {
- verify(MOCK_sdnoHealthCheckResources, times(1)).healthCheck(genericVnf, requestContext);
- verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- }
-
- }
-
- @Test
- public void sdnoHealthCheckExceptionTest() throws Exception {
- doThrow(new Exception("Unknown Error")).when(MOCK_sdnoHealthCheckResources).healthCheck(genericVnf, requestContext);
- doThrow(new BpmnError("Unknown Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- try {
- sdnoHealthCheckTasks.sdnoHealthCheck(execution);
- } catch (Exception e) {
- verify(MOCK_sdnoHealthCheckResources, times(1)).healthCheck(genericVnf, requestContext);
- verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
- }
-
- }
+
+ @InjectMocks
+ protected SDNOHealthCheckTasks sdnoHealthCheckTasks = new SDNOHealthCheckTasks();
+
+ @Mock
+ SDNOHealthCheckResources MOCK_sdnoHealthCheckResources;
+
+
+ @Mock
+ private ExceptionBuilder exceptionUtil;
+
+ @Mock
+ private ExtractPojosForBB extractPojosForBB;
+
+
+ private RequestContext requestContext;
+ private GenericVnf genericVnf;
+
+ @Before
+ public void before() throws BBObjectNotFoundException {
+ genericVnf = setGenericVnf();
+ requestContext = setRequestContext();
+ when(extractPojosForBB.extractByKey(any(), any())).thenReturn(genericVnf);
+
+ }
+
+ @Test
+ public void sdnoHealthCheckTest() throws Exception {
+ doReturn(true).when(MOCK_sdnoHealthCheckResources).healthCheck(genericVnf, requestContext);
+ sdnoHealthCheckTasks.sdnoHealthCheck(execution);
+ verify(MOCK_sdnoHealthCheckResources, times(1)).healthCheck(genericVnf, requestContext);
+ }
+
+ @Test
+ public void sdnoHealthCheckNoResponseTest() throws Exception {
+
+ doReturn(false).when(MOCK_sdnoHealthCheckResources).healthCheck(genericVnf, requestContext);
+ try {
+ sdnoHealthCheckTasks.sdnoHealthCheck(execution);
+ } catch (Exception e) {
+ verify(MOCK_sdnoHealthCheckResources, times(1)).healthCheck(genericVnf, requestContext);
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000),
+ any(String.class));
+ }
+
+ }
+
+ @Test
+ public void sdnoHealthCheckExceptionTest() throws Exception {
+ doThrow(new Exception("Unknown Error")).when(MOCK_sdnoHealthCheckResources).healthCheck(genericVnf,
+ requestContext);
+ doThrow(new BpmnError("Unknown Error")).when(exceptionUtil)
+ .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class));
+ try {
+ sdnoHealthCheckTasks.sdnoHealthCheck(execution);
+ } catch (Exception e) {
+ verify(MOCK_sdnoHealthCheckResources, times(1)).healthCheck(genericVnf, requestContext);
+ verify(exceptionUtil, times(1)).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000),
+ any(String.class));
+ }
+
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/aai/mapper/AAIObjectMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/aai/mapper/AAIObjectMapperTest.java
index d5b529288f..821e70a8c8 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/aai/mapper/AAIObjectMapperTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/aai/mapper/AAIObjectMapperTest.java
@@ -24,13 +24,11 @@ import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
import org.onap.aai.domain.yang.RouteTargets;
import org.onap.so.bpmn.servicedecomposition.bbobjects.Collection;
@@ -60,562 +58,581 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoNetwork;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
public class AAIObjectMapperTest {
- private AAIObjectMapper aaiObjectMapper = new AAIObjectMapper();
- private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
-
-
- @Test
- public void mapConfigurationTest() {
- Configuration configuration = new Configuration();
- configuration.setConfigurationId("configId");
- configuration.setConfigurationName("VNR");
- configuration.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
- configuration.setManagementOption("managementOption");
- ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
- modelInfoConfiguration.setModelCustomizationId("modelCustId");
- modelInfoConfiguration.setModelInvariantId("modelInvariantId");
- modelInfoConfiguration.setModelVersionId("modelVersionId");
- modelInfoConfiguration.setConfigurationType("5G");
- modelInfoConfiguration.setConfigurationRole("ConfigurationRole");
- configuration.setModelInfoConfiguration(modelInfoConfiguration);
-
- org.onap.aai.domain.yang.Configuration expectedConfiguration = new org.onap.aai.domain.yang.Configuration();
- expectedConfiguration.setConfigurationId(configuration.getConfigurationId());
- expectedConfiguration.setConfigurationName(configuration.getConfigurationName());
- expectedConfiguration.setConfigurationType(configuration.getModelInfoConfiguration().getConfigurationType());
- expectedConfiguration.setOrchestrationStatus(configuration.getOrchestrationStatus().toString());
- expectedConfiguration.setManagementOption(configuration.getManagementOption());
- expectedConfiguration.setModelInvariantId(configuration.getModelInfoConfiguration().getModelInvariantId());
- expectedConfiguration.setModelVersionId(configuration.getModelInfoConfiguration().getModelVersionId());
- expectedConfiguration.setModelCustomizationId(configuration.getModelInfoConfiguration().getModelCustomizationId());
- expectedConfiguration.setConfigurationSubType(configuration.getModelInfoConfiguration().getConfigurationRole());
- expectedConfiguration.setConfigPolicyName(configuration.getModelInfoConfiguration().getPolicyName());
-
- org.onap.aai.domain.yang.Configuration actualConfiguration = aaiObjectMapper.mapConfiguration(configuration);
-
- assertThat(actualConfiguration, sameBeanAs(expectedConfiguration));
- }
-
- @Test
- public void mapVolumeGroupTest() throws Exception {
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setHeatStackId("heatStackId");
- volumeGroup.setModelInfoVfModule(new ModelInfoVfModule());
- volumeGroup.getModelInfoVfModule().setModelCustomizationUUID("modelCustomizationId");
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.ACTIVE);
- volumeGroup.setVnfType("vnfType");
- volumeGroup.setVolumeGroupId("volumeGroupId");
- volumeGroup.setVolumeGroupName("volumeGroupName");
-
- org.onap.aai.domain.yang.VolumeGroup expectedVolumeGroup = new org.onap.aai.domain.yang.VolumeGroup();
- expectedVolumeGroup.setHeatStackId(volumeGroup.getHeatStackId());
- expectedVolumeGroup.setModelCustomizationId(volumeGroup.getModelInfoVfModule().getModelCustomizationUUID());
- expectedVolumeGroup.setOrchestrationStatus(volumeGroup.getOrchestrationStatus().toString());
- expectedVolumeGroup.setVfModuleModelCustomizationId(volumeGroup.getModelInfoVfModule().getModelCustomizationUUID());
- expectedVolumeGroup.setVnfType(volumeGroup.getVnfType());
- expectedVolumeGroup.setVolumeGroupId(volumeGroup.getVolumeGroupId());
- expectedVolumeGroup.setVolumeGroupName(volumeGroup.getVolumeGroupName());
-
- org.onap.aai.domain.yang.VolumeGroup actualVolumeGroup = aaiObjectMapper.mapVolumeGroup(volumeGroup);
-
- assertThat(actualVolumeGroup, sameBeanAs(expectedVolumeGroup));
- }
-
- @Test
- public void serviceInstanceMap() {
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("SIID");
- serviceInstance.setServiceInstanceName("SINAME");
- serviceInstance.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setServiceType("SITYPE");
- modelInfoServiceInstance.setServiceRole("SIROLE");
- modelInfoServiceInstance.setModelInvariantUuid("MIUUID");
- modelInfoServiceInstance.setModelUuid("MUUID");
- modelInfoServiceInstance.setEnvironmentContext("EC");
- modelInfoServiceInstance.setWorkloadContext("WC");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- org.onap.aai.domain.yang.ServiceInstance AAIServiceInstance = aaiObjectMapper.mapServiceInstance(serviceInstance);
-
- assertEquals(AAIServiceInstance.getServiceInstanceId(),serviceInstance.getServiceInstanceId());
- assertEquals(AAIServiceInstance.getServiceInstanceName(),serviceInstance.getServiceInstanceName());
- assertEquals(AAIServiceInstance.getOrchestrationStatus().toString(),serviceInstance.getOrchestrationStatus().toString());
- assertEquals(AAIServiceInstance.getServiceType(),serviceInstance.getModelInfoServiceInstance().getServiceType());
- assertEquals(AAIServiceInstance.getServiceRole(),serviceInstance.getModelInfoServiceInstance().getServiceRole());
- assertEquals(AAIServiceInstance.getModelInvariantId(),serviceInstance.getModelInfoServiceInstance().getModelInvariantUuid());
- assertEquals(AAIServiceInstance.getModelVersionId(),serviceInstance.getModelInfoServiceInstance().getModelUuid());
- assertEquals(AAIServiceInstance.getEnvironmentContext(),serviceInstance.getModelInfoServiceInstance().getEnvironmentContext());
- assertEquals(AAIServiceInstance.getWorkloadContext(),serviceInstance.getModelInfoServiceInstance().getWorkloadContext());
- }
-
- @Test
- public void projectMap(){
- Project project = new Project();
- project.setProjectName("abc");
-
- org.onap.aai.domain.yang.Project AAIProject = aaiObjectMapper.mapProject(project);
-
- assertEquals(AAIProject.getProjectName(),project.getProjectName());
- }
-
- @Test
- public void serviceSubscriptionMap(){
+ private AAIObjectMapper aaiObjectMapper = new AAIObjectMapper();
+ private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
+
+
+ @Test
+ public void mapConfigurationTest() {
+ Configuration configuration = new Configuration();
+ configuration.setConfigurationId("configId");
+ configuration.setConfigurationName("VNR");
+ configuration.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+ configuration.setManagementOption("managementOption");
+ ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
+ modelInfoConfiguration.setModelCustomizationId("modelCustId");
+ modelInfoConfiguration.setModelInvariantId("modelInvariantId");
+ modelInfoConfiguration.setModelVersionId("modelVersionId");
+ modelInfoConfiguration.setConfigurationType("5G");
+ modelInfoConfiguration.setConfigurationRole("ConfigurationRole");
+ configuration.setModelInfoConfiguration(modelInfoConfiguration);
+
+ org.onap.aai.domain.yang.Configuration expectedConfiguration = new org.onap.aai.domain.yang.Configuration();
+ expectedConfiguration.setConfigurationId(configuration.getConfigurationId());
+ expectedConfiguration.setConfigurationName(configuration.getConfigurationName());
+ expectedConfiguration.setConfigurationType(configuration.getModelInfoConfiguration().getConfigurationType());
+ expectedConfiguration.setOrchestrationStatus(configuration.getOrchestrationStatus().toString());
+ expectedConfiguration.setManagementOption(configuration.getManagementOption());
+ expectedConfiguration.setModelInvariantId(configuration.getModelInfoConfiguration().getModelInvariantId());
+ expectedConfiguration.setModelVersionId(configuration.getModelInfoConfiguration().getModelVersionId());
+ expectedConfiguration
+ .setModelCustomizationId(configuration.getModelInfoConfiguration().getModelCustomizationId());
+ expectedConfiguration.setConfigurationSubType(configuration.getModelInfoConfiguration().getConfigurationRole());
+ expectedConfiguration.setConfigPolicyName(configuration.getModelInfoConfiguration().getPolicyName());
+
+ org.onap.aai.domain.yang.Configuration actualConfiguration = aaiObjectMapper.mapConfiguration(configuration);
+
+ assertThat(actualConfiguration, sameBeanAs(expectedConfiguration));
+ }
+
+ @Test
+ public void mapVolumeGroupTest() throws Exception {
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setHeatStackId("heatStackId");
+ volumeGroup.setModelInfoVfModule(new ModelInfoVfModule());
+ volumeGroup.getModelInfoVfModule().setModelCustomizationUUID("modelCustomizationId");
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.ACTIVE);
+ volumeGroup.setVnfType("vnfType");
+ volumeGroup.setVolumeGroupId("volumeGroupId");
+ volumeGroup.setVolumeGroupName("volumeGroupName");
+
+ org.onap.aai.domain.yang.VolumeGroup expectedVolumeGroup = new org.onap.aai.domain.yang.VolumeGroup();
+ expectedVolumeGroup.setHeatStackId(volumeGroup.getHeatStackId());
+ expectedVolumeGroup.setModelCustomizationId(volumeGroup.getModelInfoVfModule().getModelCustomizationUUID());
+ expectedVolumeGroup.setOrchestrationStatus(volumeGroup.getOrchestrationStatus().toString());
+ expectedVolumeGroup
+ .setVfModuleModelCustomizationId(volumeGroup.getModelInfoVfModule().getModelCustomizationUUID());
+ expectedVolumeGroup.setVnfType(volumeGroup.getVnfType());
+ expectedVolumeGroup.setVolumeGroupId(volumeGroup.getVolumeGroupId());
+ expectedVolumeGroup.setVolumeGroupName(volumeGroup.getVolumeGroupName());
+
+ org.onap.aai.domain.yang.VolumeGroup actualVolumeGroup = aaiObjectMapper.mapVolumeGroup(volumeGroup);
+
+ assertThat(actualVolumeGroup, sameBeanAs(expectedVolumeGroup));
+ }
+
+ @Test
+ public void serviceInstanceMap() {
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("SIID");
+ serviceInstance.setServiceInstanceName("SINAME");
+ serviceInstance.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setServiceType("SITYPE");
+ modelInfoServiceInstance.setServiceRole("SIROLE");
+ modelInfoServiceInstance.setModelInvariantUuid("MIUUID");
+ modelInfoServiceInstance.setModelUuid("MUUID");
+ modelInfoServiceInstance.setEnvironmentContext("EC");
+ modelInfoServiceInstance.setWorkloadContext("WC");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ org.onap.aai.domain.yang.ServiceInstance AAIServiceInstance =
+ aaiObjectMapper.mapServiceInstance(serviceInstance);
+
+ assertEquals(AAIServiceInstance.getServiceInstanceId(), serviceInstance.getServiceInstanceId());
+ assertEquals(AAIServiceInstance.getServiceInstanceName(), serviceInstance.getServiceInstanceName());
+ assertEquals(AAIServiceInstance.getOrchestrationStatus().toString(),
+ serviceInstance.getOrchestrationStatus().toString());
+ assertEquals(AAIServiceInstance.getServiceType(),
+ serviceInstance.getModelInfoServiceInstance().getServiceType());
+ assertEquals(AAIServiceInstance.getServiceRole(),
+ serviceInstance.getModelInfoServiceInstance().getServiceRole());
+ assertEquals(AAIServiceInstance.getModelInvariantId(),
+ serviceInstance.getModelInfoServiceInstance().getModelInvariantUuid());
+ assertEquals(AAIServiceInstance.getModelVersionId(),
+ serviceInstance.getModelInfoServiceInstance().getModelUuid());
+ assertEquals(AAIServiceInstance.getEnvironmentContext(),
+ serviceInstance.getModelInfoServiceInstance().getEnvironmentContext());
+ assertEquals(AAIServiceInstance.getWorkloadContext(),
+ serviceInstance.getModelInfoServiceInstance().getWorkloadContext());
+ }
+
+ @Test
+ public void projectMap() {
+ Project project = new Project();
+ project.setProjectName("abc");
+
+ org.onap.aai.domain.yang.Project AAIProject = aaiObjectMapper.mapProject(project);
+
+ assertEquals(AAIProject.getProjectName(), project.getProjectName());
+ }
+
+ @Test
+ public void serviceSubscriptionMap() {
ServiceSubscription serviceSubscription = new ServiceSubscription();
serviceSubscription.setServiceType("IP-FLEX");
serviceSubscription.setTempUbSubAccountId("Account-ID");
- org.onap.aai.domain.yang.ServiceSubscription serviceSubscriptionMapped = aaiObjectMapper.mapServiceSubscription(serviceSubscription);
+ org.onap.aai.domain.yang.ServiceSubscription serviceSubscriptionMapped =
+ aaiObjectMapper.mapServiceSubscription(serviceSubscription);
assertNotNull(serviceSubscriptionMapped);
- assertEquals(serviceSubscription.getTempUbSubAccountId(),serviceSubscriptionMapped.getTempUbSubAccountId());
- assertEquals(serviceSubscription.getServiceType(),serviceSubscriptionMapped.getServiceType());
+ assertEquals(serviceSubscription.getTempUbSubAccountId(), serviceSubscriptionMapped.getTempUbSubAccountId());
+ assertEquals(serviceSubscription.getServiceType(), serviceSubscriptionMapped.getServiceType());
+ }
+
+ @Test
+ public void owningEntityMap() {
+ OwningEntity oe = new OwningEntity();
+ oe.setOwningEntityId("abc");
+ oe.setOwningEntityName("bbb");
+
+ org.onap.aai.domain.yang.OwningEntity AAIOwningEntity = aaiObjectMapper.mapOwningEntity(oe);
+
+ assertEquals(AAIOwningEntity.getOwningEntityId(), oe.getOwningEntityId());
+ assertEquals(AAIOwningEntity.getOwningEntityName(), oe.getOwningEntityName());
+
+ }
+
+ @Test
+ public void vnfMap() {
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("a");
+ vnf.setVnfName("b");
+ vnf.setServiceId("c");
+ vnf.setVnfType("d");
+ vnf.setProvStatus("e");
+ vnf.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelCustomizationUuid("f");
+ modelInfoGenericVnf.setModelInvariantUuid("g");
+ modelInfoGenericVnf.setModelUuid("h");
+ modelInfoGenericVnf.setNfRole("i");
+ modelInfoGenericVnf.setNfType("j");
+ modelInfoGenericVnf.setNfFunction("k");
+ modelInfoGenericVnf.setNfNamingCode("l");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ org.onap.aai.domain.yang.GenericVnf AAIVnf = aaiObjectMapper.mapVnf(vnf);
+
+ assertEquals(AAIVnf.getVnfId(), vnf.getVnfId());
+ assertEquals(AAIVnf.getVnfName(), vnf.getVnfName());
+ assertEquals(AAIVnf.getServiceId(), vnf.getServiceId());
+ assertEquals(AAIVnf.getVnfType(), vnf.getVnfType());
+ assertEquals(AAIVnf.getProvStatus(), vnf.getProvStatus());
+ assertEquals(AAIVnf.getOrchestrationStatus().toString(), vnf.getOrchestrationStatus().toString());
+ assertEquals(AAIVnf.getModelCustomizationId(), vnf.getModelInfoGenericVnf().getModelCustomizationUuid());
+ assertEquals(AAIVnf.getModelInvariantId(), vnf.getModelInfoGenericVnf().getModelInvariantUuid());
+ assertEquals(AAIVnf.getModelVersionId(), vnf.getModelInfoGenericVnf().getModelUuid());
+ assertEquals(AAIVnf.getModelVersionId(), vnf.getModelInfoGenericVnf().getModelUuid());
+ assertEquals(AAIVnf.getNfType(), vnf.getModelInfoGenericVnf().getNfType());
+ assertEquals(AAIVnf.getNfFunction(), vnf.getModelInfoGenericVnf().getNfFunction());
+ assertEquals(AAIVnf.getNfNamingCode(), vnf.getModelInfoGenericVnf().getNfNamingCode());
+ }
+
+ @Test
+ public void vfModuleMap() throws Exception {
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("a");
+ vfModule.setVfModuleName("b");
+ vfModule.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelCustomizationUUID("f");
+ modelInfoVfModule.setModelInvariantUUID("g");
+ modelInfoVfModule.setModelUUID("h");
+ modelInfoVfModule.setIsBaseBoolean(false);
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+
+ org.onap.aai.domain.yang.VfModule AAIVfModule = aaiObjectMapper.mapVfModule(vfModule);
+
+ String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiVfModuleMap.json")));
+
+ ObjectMapper omapper = new ObjectMapper();
+ org.onap.aai.domain.yang.VfModule reqMapper1 =
+ omapper.readValue(jsonToCompare, org.onap.aai.domain.yang.VfModule.class);
+
+ assertThat(reqMapper1, sameBeanAs(AAIVfModule));
+
+ }
+
+ @Test
+ public void vfModuleBaseMap() throws Exception {
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("a");
+ vfModule.setVfModuleName("b");
+ vfModule.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelCustomizationUUID("f");
+ modelInfoVfModule.setModelInvariantUUID("g");
+ modelInfoVfModule.setModelUUID("h");
+ modelInfoVfModule.setIsBaseBoolean(true);
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+
+ org.onap.aai.domain.yang.VfModule AAIVfModule = aaiObjectMapper.mapVfModule(vfModule);
+
+ String jsonToCompare =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiVfModuleBaseMap.json")));
+
+ ObjectMapper omapper = new ObjectMapper();
+ org.onap.aai.domain.yang.VfModule reqMapper1 =
+ omapper.readValue(jsonToCompare, org.onap.aai.domain.yang.VfModule.class);
+
+ assertThat(reqMapper1, sameBeanAs(AAIVfModule));
+
+ }
+
+ @Test
+ public void testMapInstanceGroup() {
+ InstanceGroup instanceGroup = new InstanceGroup();
+ instanceGroup.setId("test-id");
+ instanceGroup.setDescription("test-description");
+ instanceGroup.setInstanceGroupName("test-instanceGroupName");
+ instanceGroup.setResourceVersion("test-resourceVersion");
+
+ ModelInfoInstanceGroup model = new ModelInfoInstanceGroup();
+ model.setFunction("test-function");
+ model.setInstanceGroupRole("SUB-INTERFACE");
+ model.setType("VNFC");
+ model.setModelInvariantUUID("modelInvariantUUID-000");
+ model.setModelUUID("modelUUID-000");
+ model.setDescription("test-description");
+ model.setInstanceGroupRole("SUB-INTERFACE");
+
+ instanceGroup.setModelInfoInstanceGroup(model);
+
+
+ org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = aaiObjectMapper.mapInstanceGroup(instanceGroup);
+
+ try {
+ com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
+ String json = mapper.writeValueAsString(aaiInstanceGroup);
+ System.out.println("GGG - json:\n" + json);
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ assertEquals(aaiInstanceGroup.getId(), instanceGroup.getId());
+ assertEquals(aaiInstanceGroup.getDescription(), instanceGroup.getDescription());
+ assertEquals(aaiInstanceGroup.getInstanceGroupRole(),
+ instanceGroup.getModelInfoInstanceGroup().getInstanceGroupRole());
+ assertEquals(aaiInstanceGroup.getModelInvariantId(),
+ instanceGroup.getModelInfoInstanceGroup().getModelInvariantUUID());
+ assertEquals(aaiInstanceGroup.getModelVersionId(), instanceGroup.getModelInfoInstanceGroup().getModelUUID());
+ assertEquals(aaiInstanceGroup.getResourceVersion(), instanceGroup.getResourceVersion());
+ assertEquals(aaiInstanceGroup.getInstanceGroupType(), instanceGroup.getModelInfoInstanceGroup().getType());
+ assertEquals(aaiInstanceGroup.getInstanceGroupRole(),
+ instanceGroup.getModelInfoInstanceGroup().getInstanceGroupRole());
+ }
+
+ @Test
+ public void mapCustomerTest() {
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("globalCustomerId");
+ customer.setSubscriberName("subscriberName");
+ customer.setSubscriberType("subscriberType");
+
+ org.onap.aai.domain.yang.Customer expectedCustomer = new org.onap.aai.domain.yang.Customer();
+ expectedCustomer.setGlobalCustomerId("globalCustomerId");
+ expectedCustomer.setSubscriberName("subscriberName");
+ expectedCustomer.setSubscriberType("subscriberType");
+
+ org.onap.aai.domain.yang.Customer actualCustomer = aaiObjectMapper.mapCustomer(customer);
+
+ assertThat(actualCustomer, sameBeanAs(expectedCustomer));
+ }
+
+ @Test
+ public void networkMap() throws Exception {
+ L3Network l3Network = new L3Network();
+ l3Network.setNetworkId("networkId");
+ l3Network.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+ l3Network.setNetworkName("networkName");
+ l3Network.setNetworkRole("networkRole");
+ l3Network.setNetworkTechnology("networkTechnology");
+ l3Network.setNeutronNetworkId("neutronNetworkId");
+ l3Network.setNetworkRoleInstance(0L);
+ l3Network.setContrailNetworkFqdn("contrailNetworkFqdn");
+ l3Network.setIsBoundToVpn(false);
+ l3Network.setIsCascaded(false);
+ l3Network.setIsSharedNetwork(false);
+ l3Network.setHeatStackId("heatStackId");
+ l3Network.setOperationalStatus("operationalStatus");
+ l3Network.setPhysicalNetworkName("physicalNetworkName");
+ l3Network.setIsProviderNetwork(false);
+ l3Network.setSelflink("selflink");
+ l3Network.setServiceId("serviceId");
+
+ ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
+ modelInfoNetwork.setModelCustomizationUUID("modelCustomizationUUID");
+ modelInfoNetwork.setModelInvariantUUID("modelInvariantUUID");
+ modelInfoNetwork.setModelUUID("modelUUID");
+
+ l3Network.setModelInfoNetwork(modelInfoNetwork);
+
+ org.onap.aai.domain.yang.L3Network aaiL3Network = aaiObjectMapper.mapNetwork(l3Network);
+
+ ObjectMapper omapper = new ObjectMapper();
+ org.onap.aai.domain.yang.L3Network network =
+ omapper.readValue(getJson("aaiL3NetworkMapped.json"), org.onap.aai.domain.yang.L3Network.class);
+
+ com.shazam.shazamcrest.MatcherAssert.assertThat(aaiL3Network, sameBeanAs(network));
+
+ }
+
+ @Test
+ public void mapCollectionTest() {
+ Collection networkCollection = new Collection();
+ networkCollection.setId("networkCollectionId");
+ ModelInfoCollection modelInfoCollection = new ModelInfoCollection();
+ modelInfoCollection.setCollectionFunction("networkCollectionFunction");
+ modelInfoCollection.setCollectionRole("networkCollectionRole");
+ modelInfoCollection.setCollectionType("networkCollectionType");
+ modelInfoCollection.setModelCustomizationUUID("modelCustomizationUUID");
+ modelInfoCollection.setModelVersionId("modelVersionId");
+ modelInfoCollection.setModelInvariantUUID("modelInvariantUUID");
+ networkCollection.setModelInfoCollection(modelInfoCollection);
+ networkCollection.setName("networkCollectionName");
+
+ org.onap.aai.domain.yang.Collection expectedCollection = new org.onap.aai.domain.yang.Collection();
+ expectedCollection.setCollectionId("networkCollectionId");
+ expectedCollection.setCollectionType("networkCollectionType");
+ expectedCollection.setCollectionCustomizationId("modelCustomizationUUID");
+ expectedCollection.setModelVersionId("modelVersionId");
+ expectedCollection.setModelInvariantId("modelInvariantUUID");
+ expectedCollection.setCollectionFunction("networkCollectionFunction");
+ expectedCollection.setCollectionRole("networkCollectionRole");
+ expectedCollection.setCollectionName("networkCollectionName");
+
+ org.onap.aai.domain.yang.Collection actualCollection = aaiObjectMapper.mapCollection(networkCollection);
+
+ assertThat(actualCollection, sameBeanAs(expectedCollection));
+ }
+
+ /*
+ * Helper method to load JSON data
+ */
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + filename)));
+ }
+
+ @Test
+ public void mapNetworkTest() throws Exception {
+ L3Network l3Network = new L3Network();
+ ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
+ modelInfoNetwork.setModelCustomizationUUID("modelCustomization_id");
+ modelInfoNetwork.setModelInvariantUUID("modelInvariant_id");
+ modelInfoNetwork.setModelUUID("modelCustomization_id");
+ modelInfoNetwork.setNetworkType("CONTRAIL_EXTERNAL");
+ modelInfoNetwork.setNetworkRole("dmz_direct");
+ modelInfoNetwork.setNetworkTechnology("contrail");
+ l3Network.setModelInfoNetwork(modelInfoNetwork);
+ l3Network.setNetworkId("TESTING_ID");
+ l3Network.setNetworkName("TESTING_NAME");
+ l3Network.setIsBoundToVpn(true);
+ l3Network.setServiceId("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb");
+ l3Network.setNetworkRoleInstance(1L);
+ l3Network.setOrchestrationStatus(OrchestrationStatus.CREATED);
+ l3Network.setHeatStackId("heatStack_id");
+ l3Network.setContrailNetworkFqdn("contrailNetwork_fqdn");
+ l3Network.setWidgetModelId("widgetModel_id");
+ l3Network.setWidgetModelVersion("widgetModel_version");
+ l3Network.setPhysicalNetworkName("physicalNetwork_name");
+ l3Network.setIsProviderNetwork(true);
+ l3Network.setIsSharedNetwork(false);
+ l3Network.setIsExternalNetwork(true);
+ l3Network.setSelflink("self_link");
+ l3Network.setOperationalStatus("operationalStatus");
+
+ List<Subnet> subnets = new ArrayList<Subnet>();
+ Subnet subnet1 = new Subnet();
+ subnet1.setSubnetId("57e9a1ff-d14f-4071-a828-b19ae98eb2fc");
+ subnet1.setSubnetName("subnetName");
+ subnet1.setGatewayAddress("192.168.52.1");
+ subnet1.setNetworkStartAddress("192.168.52.0");
+ subnet1.setCidrMask("24");
+ subnet1.setIpVersion("4");
+ subnet1.setOrchestrationStatus(OrchestrationStatus.CREATED);
+ subnet1.setIpAssignmentDirection("true");
+ subnet1.setDhcpEnabled(true);
+ subnet1.setDhcpStart("dhcpStart");
+ subnet1.setDhcpEnd("dhcpEnd");
+ subnet1.setSubnetRole("subnetRole");
+ subnet1.setIpAssignmentDirection("true");
+ subnet1.setSubnetSequence(new Integer(3));
+
+ List<HostRoute> hostRoutes = new ArrayList<HostRoute>();
+ HostRoute hostRoute1 = new HostRoute();
+ hostRoute1.setHostRouteId("string");
+ hostRoute1.setRoutePrefix("192.10.16.0/24");
+ hostRoute1.setNextHop("192.10.16.100/24");
+ hostRoute1.setNextHopType("ip-address");
+ HostRoute hostRoute2 = new HostRoute();
+ hostRoute2.setHostRouteId("string");
+ hostRoute2.setRoutePrefix("192.110.17.0/24");
+ hostRoute2.setNextHop("192.110.17.110/24");
+ hostRoute2.setNextHopType("ip-address");
+ hostRoutes.add(hostRoute1);
+ hostRoutes.add(hostRoute2);
+ subnet1.getHostRoutes().addAll(hostRoutes);
+
+ subnets.add(subnet1);
+ subnets.add(subnet1);
+ l3Network.getSubnets().addAll(subnets);
+
+ List<CtagAssignment> ctagAssignments = new ArrayList<CtagAssignment>();
+ CtagAssignment ctagAssignment1 = new CtagAssignment();
+ ctagAssignment1.setVlanIdInner(1L);
+ ctagAssignments.add(ctagAssignment1);
+ l3Network.getCtagAssignments().addAll(ctagAssignments);
+
+ List<SegmentationAssignment> segmentationAssignments = new ArrayList<SegmentationAssignment>();
+ SegmentationAssignment segmentationAssignment1 = new SegmentationAssignment();
+ segmentationAssignment1.setSegmentationId("segmentationId1");
+ SegmentationAssignment segmentationAssignment2 = new SegmentationAssignment();
+ segmentationAssignment2.setSegmentationId("segmentationId2");
+ segmentationAssignments.add(segmentationAssignment1);
+ segmentationAssignments.add(segmentationAssignment2);
+ l3Network.getSegmentationAssignments().addAll(segmentationAssignments);
+
+ AAIObjectMapper l3NetworkMapper = new AAIObjectMapper();
+ org.onap.aai.domain.yang.L3Network v12L3Network = l3NetworkMapper.mapNetwork(l3Network);
+
+ String jsonToCompare =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiL3NetworkMapped_to_aai.json")));
+ ObjectMapper omapper = new ObjectMapper();
+ org.onap.aai.domain.yang.L3Network network =
+ omapper.readValue(jsonToCompare, org.onap.aai.domain.yang.L3Network.class);
+
+ ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
+ String jsonGenerated = ow.writeValueAsString(v12L3Network);
+ String jsonExpected = ow.writeValueAsString(network);
+ assertEquals(jsonExpected, jsonGenerated);
+
+ }
+
+ @Test
+ public void mapToAAISubNetsTest() throws Exception {
+ List<Subnet> subnets = new ArrayList<Subnet>();
+ Subnet subnet1 = new Subnet();
+ subnet1.setSubnetId("57e9a1ff-d14f-4071-a828-b19ae98eb2fc");
+ subnet1.setSubnetName("subnetName");
+ subnet1.setGatewayAddress("192.168.52.1");
+ subnet1.setNetworkStartAddress("192.168.52.0");
+ subnet1.setCidrMask("24");
+ subnet1.setIpVersion("4");
+ subnet1.setOrchestrationStatus(OrchestrationStatus.CREATED);
+ subnet1.setIpAssignmentDirection("true");
+ subnet1.setDhcpEnabled(true);
+ subnet1.setDhcpStart("dhcpStart");
+ subnet1.setDhcpEnd("dhcpEnd");
+ subnet1.setSubnetRole("subnetRole");
+ subnet1.setIpAssignmentDirection("true");
+ subnet1.setSubnetSequence(new Integer(3));
+
+ List<HostRoute> hostRoutes = new ArrayList<HostRoute>();
+ HostRoute hostRoute1 = new HostRoute();
+ hostRoute1.setHostRouteId("string");
+ hostRoute1.setRoutePrefix("192.10.16.0/24");
+ hostRoute1.setNextHop("192.10.16.100/24");
+ hostRoute1.setNextHopType("ip-address");
+ HostRoute hostRoute2 = new HostRoute();
+ hostRoute2.setHostRouteId("string");
+ hostRoute2.setRoutePrefix("192.110.17.0/24");
+ hostRoute2.setNextHop("192.110.17.110/24");
+ hostRoute2.setNextHopType("ip-address");
+ hostRoutes.add(hostRoute1);
+ hostRoutes.add(hostRoute2);
+ subnet1.getHostRoutes().addAll(hostRoutes);
+
+ subnets.add(subnet1);
+ subnets.add(subnet1);
+
+ AAIObjectMapper aaiObjectMapper = new AAIObjectMapper();
+ org.onap.aai.domain.yang.Subnets v12Subnets = aaiObjectMapper.mapToAAISubNets(subnets);
+
+ assertEquals(subnets.get(0).getDhcpEnd(), v12Subnets.getSubnet().get(0).getDhcpEnd());
+ assertEquals(subnets.get(0).getCidrMask(), v12Subnets.getSubnet().get(0).getCidrMask());
+
+ String jsonToCompare =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiSubnetsMapped_to_aai.json")));
+ ObjectMapper omapper = new ObjectMapper();
+ org.onap.aai.domain.yang.Subnets subnet =
+ omapper.readValue(jsonToCompare, org.onap.aai.domain.yang.Subnets.class);
+ ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
+ String jsonGenerated = ow.writeValueAsString(v12Subnets);
+ String jsonExpected = ow.writeValueAsString(subnet);
+ assertEquals(jsonExpected, jsonGenerated);
}
- @Test
- public void owningEntityMap(){
- OwningEntity oe = new OwningEntity();
- oe.setOwningEntityId("abc");
- oe.setOwningEntityName("bbb");
-
- org.onap.aai.domain.yang.OwningEntity AAIOwningEntity = aaiObjectMapper.mapOwningEntity(oe);
-
- assertEquals(AAIOwningEntity.getOwningEntityId(),oe.getOwningEntityId());
- assertEquals(AAIOwningEntity.getOwningEntityName(),oe.getOwningEntityName());
-
- }
-
- @Test
- public void vnfMap(){
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("a");
- vnf.setVnfName("b");
- vnf.setServiceId("c");
- vnf.setVnfType("d");
- vnf.setProvStatus("e");
- vnf.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelCustomizationUuid("f");
- modelInfoGenericVnf.setModelInvariantUuid("g");
- modelInfoGenericVnf.setModelUuid("h");
- modelInfoGenericVnf.setNfRole("i");
- modelInfoGenericVnf.setNfType("j");
- modelInfoGenericVnf.setNfFunction("k");
- modelInfoGenericVnf.setNfNamingCode("l");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- org.onap.aai.domain.yang.GenericVnf AAIVnf = aaiObjectMapper.mapVnf(vnf);
-
- assertEquals(AAIVnf.getVnfId(),vnf.getVnfId());
- assertEquals(AAIVnf.getVnfName(),vnf.getVnfName());
- assertEquals(AAIVnf.getServiceId(),vnf.getServiceId());
- assertEquals(AAIVnf.getVnfType(),vnf.getVnfType());
- assertEquals(AAIVnf.getProvStatus(),vnf.getProvStatus());
- assertEquals(AAIVnf.getOrchestrationStatus().toString(),vnf.getOrchestrationStatus().toString());
- assertEquals(AAIVnf.getModelCustomizationId(),vnf.getModelInfoGenericVnf().getModelCustomizationUuid());
- assertEquals(AAIVnf.getModelInvariantId(),vnf.getModelInfoGenericVnf().getModelInvariantUuid());
- assertEquals(AAIVnf.getModelVersionId(),vnf.getModelInfoGenericVnf().getModelUuid());
- assertEquals(AAIVnf.getModelVersionId(),vnf.getModelInfoGenericVnf().getModelUuid());
- assertEquals(AAIVnf.getNfType(),vnf.getModelInfoGenericVnf().getNfType());
- assertEquals(AAIVnf.getNfFunction(),vnf.getModelInfoGenericVnf().getNfFunction());
- assertEquals(AAIVnf.getNfNamingCode(),vnf.getModelInfoGenericVnf().getNfNamingCode());
- }
-
- @Test
- public void vfModuleMap() throws Exception {
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("a");
- vfModule.setVfModuleName("b");
- vfModule.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelCustomizationUUID("f");
- modelInfoVfModule.setModelInvariantUUID("g");
- modelInfoVfModule.setModelUUID("h");
- modelInfoVfModule.setIsBaseBoolean(false);
- vfModule.setModelInfoVfModule(modelInfoVfModule);
-
- org.onap.aai.domain.yang.VfModule AAIVfModule = aaiObjectMapper.mapVfModule(vfModule);
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiVfModuleMap.json")));
-
- ObjectMapper omapper = new ObjectMapper();
- org.onap.aai.domain.yang.VfModule reqMapper1 = omapper.readValue(
- jsonToCompare,
- org.onap.aai.domain.yang.VfModule.class);
-
- assertThat(reqMapper1, sameBeanAs(AAIVfModule));
-
- }
-
- @Test
- public void vfModuleBaseMap() throws Exception {
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("a");
- vfModule.setVfModuleName("b");
- vfModule.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelCustomizationUUID("f");
- modelInfoVfModule.setModelInvariantUUID("g");
- modelInfoVfModule.setModelUUID("h");
- modelInfoVfModule.setIsBaseBoolean(true);
- vfModule.setModelInfoVfModule(modelInfoVfModule);
-
- org.onap.aai.domain.yang.VfModule AAIVfModule = aaiObjectMapper.mapVfModule(vfModule);
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiVfModuleBaseMap.json")));
-
- ObjectMapper omapper = new ObjectMapper();
- org.onap.aai.domain.yang.VfModule reqMapper1 = omapper.readValue(
- jsonToCompare,
- org.onap.aai.domain.yang.VfModule.class);
-
- assertThat(reqMapper1, sameBeanAs(AAIVfModule));
-
- }
-
- @Test
- public void testMapInstanceGroup() {
- InstanceGroup instanceGroup = new InstanceGroup();
- instanceGroup.setId("test-id");
- instanceGroup.setDescription("test-description");
- instanceGroup.setInstanceGroupName("test-instanceGroupName");
- instanceGroup.setResourceVersion("test-resourceVersion");
-
- ModelInfoInstanceGroup model = new ModelInfoInstanceGroup();
- model.setFunction("test-function");
- model.setInstanceGroupRole("SUB-INTERFACE");
- model.setType("VNFC");
- model.setModelInvariantUUID("modelInvariantUUID-000");
- model.setModelUUID("modelUUID-000");
- model.setDescription("test-description");
- model.setInstanceGroupRole("SUB-INTERFACE");
-
- instanceGroup.setModelInfoInstanceGroup(model);
-
-
- org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = aaiObjectMapper.mapInstanceGroup(instanceGroup);
-
- try {
- com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
- String json = mapper.writeValueAsString(aaiInstanceGroup);
- System.out.println("GGG - json:\n" + json);
-
- }
- catch(Exception e) {
- e.printStackTrace();
- }
-
- assertEquals(aaiInstanceGroup.getId(), instanceGroup.getId());
- assertEquals(aaiInstanceGroup.getDescription(), instanceGroup.getDescription());
- assertEquals(aaiInstanceGroup.getInstanceGroupRole(), instanceGroup.getModelInfoInstanceGroup().getInstanceGroupRole());
- assertEquals(aaiInstanceGroup.getModelInvariantId(), instanceGroup.getModelInfoInstanceGroup().getModelInvariantUUID());
- assertEquals(aaiInstanceGroup.getModelVersionId(), instanceGroup.getModelInfoInstanceGroup().getModelUUID());
- assertEquals(aaiInstanceGroup.getResourceVersion(), instanceGroup.getResourceVersion());
- assertEquals(aaiInstanceGroup.getInstanceGroupType(), instanceGroup.getModelInfoInstanceGroup().getType());
- assertEquals(aaiInstanceGroup.getInstanceGroupRole(), instanceGroup.getModelInfoInstanceGroup().getInstanceGroupRole());
- }
-
- @Test
- public void mapCustomerTest() {
- Customer customer = new Customer();
- customer.setGlobalCustomerId("globalCustomerId");
- customer.setSubscriberName("subscriberName");
- customer.setSubscriberType("subscriberType");
-
- org.onap.aai.domain.yang.Customer expectedCustomer = new org.onap.aai.domain.yang.Customer();
- expectedCustomer.setGlobalCustomerId("globalCustomerId");
- expectedCustomer.setSubscriberName("subscriberName");
- expectedCustomer.setSubscriberType("subscriberType");
-
- org.onap.aai.domain.yang.Customer actualCustomer = aaiObjectMapper.mapCustomer(customer);
-
- assertThat(actualCustomer, sameBeanAs(expectedCustomer));
- }
-
- @Test
- public void networkMap() throws Exception {
- L3Network l3Network = new L3Network();
- l3Network.setNetworkId("networkId");
- l3Network.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
- l3Network.setNetworkName("networkName");
- l3Network.setNetworkRole("networkRole");
- l3Network.setNetworkTechnology("networkTechnology");
- l3Network.setNeutronNetworkId("neutronNetworkId");
- l3Network.setNetworkRoleInstance(0L);
- l3Network.setContrailNetworkFqdn("contrailNetworkFqdn");
- l3Network.setIsBoundToVpn(false);
- l3Network.setIsCascaded(false);
- l3Network.setIsSharedNetwork(false);
- l3Network.setHeatStackId("heatStackId");
- l3Network.setOperationalStatus("operationalStatus");
- l3Network.setPhysicalNetworkName("physicalNetworkName");
- l3Network.setIsProviderNetwork(false);
- l3Network.setSelflink("selflink");
- l3Network.setServiceId("serviceId");
-
- ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
- modelInfoNetwork.setModelCustomizationUUID("modelCustomizationUUID");
- modelInfoNetwork.setModelInvariantUUID("modelInvariantUUID");
- modelInfoNetwork.setModelUUID("modelUUID");
-
- l3Network.setModelInfoNetwork(modelInfoNetwork);
-
- org.onap.aai.domain.yang.L3Network aaiL3Network = aaiObjectMapper.mapNetwork(l3Network);
-
- ObjectMapper omapper = new ObjectMapper();
- org.onap.aai.domain.yang.L3Network network = omapper.readValue(
- getJson("aaiL3NetworkMapped.json"),
- org.onap.aai.domain.yang.L3Network.class);
-
- com.shazam.shazamcrest.MatcherAssert.assertThat(aaiL3Network, sameBeanAs(network));
-
- }
-
- @Test
- public void mapCollectionTest() {
- Collection networkCollection = new Collection();
- networkCollection.setId("networkCollectionId");
- ModelInfoCollection modelInfoCollection = new ModelInfoCollection();
- modelInfoCollection.setCollectionFunction("networkCollectionFunction");
- modelInfoCollection.setCollectionRole("networkCollectionRole");
- modelInfoCollection.setCollectionType("networkCollectionType");
- modelInfoCollection.setModelCustomizationUUID("modelCustomizationUUID");
- modelInfoCollection.setModelVersionId("modelVersionId");
- modelInfoCollection.setModelInvariantUUID("modelInvariantUUID");
- networkCollection.setModelInfoCollection(modelInfoCollection);
- networkCollection.setName("networkCollectionName");
-
- org.onap.aai.domain.yang.Collection expectedCollection = new org.onap.aai.domain.yang.Collection();
- expectedCollection.setCollectionId("networkCollectionId");
- expectedCollection.setCollectionType("networkCollectionType");
- expectedCollection.setCollectionCustomizationId("modelCustomizationUUID");
- expectedCollection.setModelVersionId("modelVersionId");
- expectedCollection.setModelInvariantId("modelInvariantUUID");
- expectedCollection.setCollectionFunction("networkCollectionFunction");
- expectedCollection.setCollectionRole("networkCollectionRole");
- expectedCollection.setCollectionName("networkCollectionName");
-
- org.onap.aai.domain.yang.Collection actualCollection = aaiObjectMapper.mapCollection(networkCollection);
-
- assertThat(actualCollection, sameBeanAs(expectedCollection));
- }
-
- /*
- * Helper method to load JSON data
- */
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + filename)));
- }
-
- @Test
- public void mapNetworkTest() throws Exception {
- L3Network l3Network = new L3Network();
- ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
- modelInfoNetwork.setModelCustomizationUUID("modelCustomization_id");
- modelInfoNetwork.setModelInvariantUUID("modelInvariant_id");
- modelInfoNetwork.setModelUUID("modelCustomization_id");
- modelInfoNetwork.setNetworkType("CONTRAIL_EXTERNAL");
- modelInfoNetwork.setNetworkRole("dmz_direct");
- modelInfoNetwork.setNetworkTechnology("contrail");
- l3Network.setModelInfoNetwork(modelInfoNetwork);
- l3Network.setNetworkId("TESTING_ID");
- l3Network.setNetworkName("TESTING_NAME");
- l3Network.setIsBoundToVpn(true);
- l3Network.setServiceId("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb");
- l3Network.setNetworkRoleInstance(1L);
- l3Network.setOrchestrationStatus(OrchestrationStatus.CREATED);
- l3Network.setHeatStackId("heatStack_id");
- l3Network.setContrailNetworkFqdn("contrailNetwork_fqdn");
- l3Network.setWidgetModelId("widgetModel_id");
- l3Network.setWidgetModelVersion("widgetModel_version");
- l3Network.setPhysicalNetworkName("physicalNetwork_name");
- l3Network.setIsProviderNetwork(true);
- l3Network.setIsSharedNetwork(false);
- l3Network.setIsExternalNetwork(true);
- l3Network.setSelflink("self_link");
- l3Network.setOperationalStatus("operationalStatus");
-
- List<Subnet> subnets = new ArrayList<Subnet>();
- Subnet subnet1 = new Subnet();
- subnet1.setSubnetId("57e9a1ff-d14f-4071-a828-b19ae98eb2fc");
- subnet1.setSubnetName("subnetName");
- subnet1.setGatewayAddress("192.168.52.1");
- subnet1.setNetworkStartAddress("192.168.52.0");
- subnet1.setCidrMask("24");
- subnet1.setIpVersion("4");
- subnet1.setOrchestrationStatus(OrchestrationStatus.CREATED);
- subnet1.setIpAssignmentDirection("true");
- subnet1.setDhcpEnabled(true);
- subnet1.setDhcpStart("dhcpStart");
- subnet1.setDhcpEnd("dhcpEnd");
- subnet1.setSubnetRole("subnetRole");
- subnet1.setIpAssignmentDirection("true");
- subnet1.setSubnetSequence(new Integer(3));
-
- List<HostRoute> hostRoutes = new ArrayList<HostRoute>();
- HostRoute hostRoute1 = new HostRoute();
- hostRoute1.setHostRouteId("string");
- hostRoute1.setRoutePrefix("192.10.16.0/24");
- hostRoute1.setNextHop("192.10.16.100/24");
- hostRoute1.setNextHopType("ip-address");
- HostRoute hostRoute2 = new HostRoute();
- hostRoute2.setHostRouteId("string");
- hostRoute2.setRoutePrefix("192.110.17.0/24");
- hostRoute2.setNextHop("192.110.17.110/24");
- hostRoute2.setNextHopType("ip-address");
- hostRoutes.add(hostRoute1);
- hostRoutes.add(hostRoute2);
- subnet1.getHostRoutes().addAll(hostRoutes);
-
- subnets.add(subnet1);
- subnets.add(subnet1);
- l3Network.getSubnets().addAll(subnets);
-
- List<CtagAssignment> ctagAssignments = new ArrayList<CtagAssignment>();
- CtagAssignment ctagAssignment1 = new CtagAssignment();
- ctagAssignment1.setVlanIdInner(1L);
- ctagAssignments.add(ctagAssignment1);
- l3Network.getCtagAssignments().addAll(ctagAssignments);
-
- List<SegmentationAssignment> segmentationAssignments = new ArrayList<SegmentationAssignment>();
- SegmentationAssignment segmentationAssignment1 = new SegmentationAssignment();
- segmentationAssignment1.setSegmentationId("segmentationId1");
- SegmentationAssignment segmentationAssignment2 = new SegmentationAssignment();
- segmentationAssignment2.setSegmentationId("segmentationId2");
- segmentationAssignments.add(segmentationAssignment1);
- segmentationAssignments.add(segmentationAssignment2);
- l3Network.getSegmentationAssignments().addAll(segmentationAssignments);
-
- AAIObjectMapper l3NetworkMapper = new AAIObjectMapper();
- org.onap.aai.domain.yang.L3Network v12L3Network = l3NetworkMapper.mapNetwork(l3Network);
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiL3NetworkMapped_to_aai.json")));
- ObjectMapper omapper = new ObjectMapper();
- org.onap.aai.domain.yang.L3Network network = omapper.readValue(jsonToCompare,
- org.onap.aai.domain.yang.L3Network.class);
-
- ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
- String jsonGenerated = ow.writeValueAsString(v12L3Network);
- String jsonExpected = ow.writeValueAsString(network);
- assertEquals(jsonExpected, jsonGenerated);
-
- }
-
- @Test
- public void mapToAAISubNetsTest() throws Exception {
- List<Subnet> subnets = new ArrayList<Subnet>();
- Subnet subnet1 = new Subnet();
- subnet1.setSubnetId("57e9a1ff-d14f-4071-a828-b19ae98eb2fc");
- subnet1.setSubnetName("subnetName");
- subnet1.setGatewayAddress("192.168.52.1");
- subnet1.setNetworkStartAddress("192.168.52.0");
- subnet1.setCidrMask("24");
- subnet1.setIpVersion("4");
- subnet1.setOrchestrationStatus(OrchestrationStatus.CREATED);
- subnet1.setIpAssignmentDirection("true");
- subnet1.setDhcpEnabled(true);
- subnet1.setDhcpStart("dhcpStart");
- subnet1.setDhcpEnd("dhcpEnd");
- subnet1.setSubnetRole("subnetRole");
- subnet1.setIpAssignmentDirection("true");
- subnet1.setSubnetSequence(new Integer(3));
-
- List<HostRoute> hostRoutes = new ArrayList<HostRoute>();
- HostRoute hostRoute1 = new HostRoute();
- hostRoute1.setHostRouteId("string");
- hostRoute1.setRoutePrefix("192.10.16.0/24");
- hostRoute1.setNextHop("192.10.16.100/24");
- hostRoute1.setNextHopType("ip-address");
- HostRoute hostRoute2 = new HostRoute();
- hostRoute2.setHostRouteId("string");
- hostRoute2.setRoutePrefix("192.110.17.0/24");
- hostRoute2.setNextHop("192.110.17.110/24");
- hostRoute2.setNextHopType("ip-address");
- hostRoutes.add(hostRoute1);
- hostRoutes.add(hostRoute2);
- subnet1.getHostRoutes().addAll(hostRoutes);
-
- subnets.add(subnet1);
- subnets.add(subnet1);
-
- AAIObjectMapper aaiObjectMapper = new AAIObjectMapper();
- org.onap.aai.domain.yang.Subnets v12Subnets = aaiObjectMapper.mapToAAISubNets(subnets);
-
- assertEquals(subnets.get(0).getDhcpEnd(), v12Subnets.getSubnet().get(0).getDhcpEnd());
- assertEquals(subnets.get(0).getCidrMask(), v12Subnets.getSubnet().get(0).getCidrMask());
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiSubnetsMapped_to_aai.json")));
- ObjectMapper omapper = new ObjectMapper();
- org.onap.aai.domain.yang.Subnets subnet = omapper.readValue(jsonToCompare,
- org.onap.aai.domain.yang.Subnets.class);
- ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
- String jsonGenerated = ow.writeValueAsString(v12Subnets);
- String jsonExpected = ow.writeValueAsString(subnet);
- assertEquals(jsonExpected, jsonGenerated);
- }
-
- @Test
- public void mapToAAICtagAssignmentListTest() throws Exception {
- List<CtagAssignment> ctagAssignments = new ArrayList<CtagAssignment>();
- CtagAssignment ctagAssignment1 = new CtagAssignment();
- ctagAssignment1.setVlanIdInner(1L);
- ctagAssignments.add(ctagAssignment1);
-
- AAIObjectMapper aaiObjectMapper = new AAIObjectMapper();
- org.onap.aai.domain.yang.CtagAssignments v12CtagAssingments = aaiObjectMapper.mapToAAICtagAssignmentList(ctagAssignments);
-
- assertEquals(new Long(ctagAssignments.get(0).getVlanIdInner().longValue()), new Long(v12CtagAssingments.getCtagAssignment().get(0).getVlanIdInner()));
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiCtagAssingmentsMapped_to_aai.json")));
- ObjectMapper omapper = new ObjectMapper();
- org.onap.aai.domain.yang.CtagAssignments ctagAssignment = omapper.readValue(jsonToCompare,
- org.onap.aai.domain.yang.CtagAssignments.class);
- ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
- String jsonGenerated = ow.writeValueAsString(v12CtagAssingments);
- String jsonExpected = ow.writeValueAsString(ctagAssignment);
- assertEquals(jsonExpected, jsonGenerated);
- }
-
- @Test
- public void mapToAAISegmentationAssignmentListTest() throws Exception {
- List<SegmentationAssignment> segmentationAssignments = new ArrayList<SegmentationAssignment>();
- SegmentationAssignment segmentationAssignment1 = new SegmentationAssignment();
- segmentationAssignment1.setSegmentationId("segmentationId1");
- SegmentationAssignment segmentationAssignment2 = new SegmentationAssignment();
- segmentationAssignment2.setSegmentationId("segmentationId2");
- segmentationAssignments.add(segmentationAssignment1);
- segmentationAssignments.add(segmentationAssignment2);
-
- AAIObjectMapper aaiObjectMapper = new AAIObjectMapper();
- org.onap.aai.domain.yang.SegmentationAssignments v12SegmentationAssignments = aaiObjectMapper.mapToAAISegmentationAssignmentList(segmentationAssignments);
-
- assertEquals(segmentationAssignments.get(0).getSegmentationId(), v12SegmentationAssignments.getSegmentationAssignment().get(0).getSegmentationId());
- assertEquals(segmentationAssignments.get(1).getSegmentationId(), v12SegmentationAssignments.getSegmentationAssignment().get(1).getSegmentationId());
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiSegmentationAssignmentsMapped_to_aai.json")));
- ObjectMapper omapper = new ObjectMapper();
- org.onap.aai.domain.yang.SegmentationAssignments segmentationAssignment = omapper.readValue(jsonToCompare,
- org.onap.aai.domain.yang.SegmentationAssignments.class);
- ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
- String jsonGenerated = ow.writeValueAsString(v12SegmentationAssignments);
- String jsonExpected = ow.writeValueAsString(segmentationAssignment);
- assertEquals(jsonExpected, jsonGenerated);
-
- }
+ @Test
+ public void mapToAAICtagAssignmentListTest() throws Exception {
+ List<CtagAssignment> ctagAssignments = new ArrayList<CtagAssignment>();
+ CtagAssignment ctagAssignment1 = new CtagAssignment();
+ ctagAssignment1.setVlanIdInner(1L);
+ ctagAssignments.add(ctagAssignment1);
+
+ AAIObjectMapper aaiObjectMapper = new AAIObjectMapper();
+ org.onap.aai.domain.yang.CtagAssignments v12CtagAssingments =
+ aaiObjectMapper.mapToAAICtagAssignmentList(ctagAssignments);
+
+ assertEquals(new Long(ctagAssignments.get(0).getVlanIdInner().longValue()),
+ new Long(v12CtagAssingments.getCtagAssignment().get(0).getVlanIdInner()));
+
+ String jsonToCompare =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiCtagAssingmentsMapped_to_aai.json")));
+ ObjectMapper omapper = new ObjectMapper();
+ org.onap.aai.domain.yang.CtagAssignments ctagAssignment =
+ omapper.readValue(jsonToCompare, org.onap.aai.domain.yang.CtagAssignments.class);
+ ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
+ String jsonGenerated = ow.writeValueAsString(v12CtagAssingments);
+ String jsonExpected = ow.writeValueAsString(ctagAssignment);
+ assertEquals(jsonExpected, jsonGenerated);
+ }
+
+ @Test
+ public void mapToAAISegmentationAssignmentListTest() throws Exception {
+ List<SegmentationAssignment> segmentationAssignments = new ArrayList<SegmentationAssignment>();
+ SegmentationAssignment segmentationAssignment1 = new SegmentationAssignment();
+ segmentationAssignment1.setSegmentationId("segmentationId1");
+ SegmentationAssignment segmentationAssignment2 = new SegmentationAssignment();
+ segmentationAssignment2.setSegmentationId("segmentationId2");
+ segmentationAssignments.add(segmentationAssignment1);
+ segmentationAssignments.add(segmentationAssignment2);
+
+ AAIObjectMapper aaiObjectMapper = new AAIObjectMapper();
+ org.onap.aai.domain.yang.SegmentationAssignments v12SegmentationAssignments =
+ aaiObjectMapper.mapToAAISegmentationAssignmentList(segmentationAssignments);
+
+ assertEquals(segmentationAssignments.get(0).getSegmentationId(),
+ v12SegmentationAssignments.getSegmentationAssignment().get(0).getSegmentationId());
+ assertEquals(segmentationAssignments.get(1).getSegmentationId(),
+ v12SegmentationAssignments.getSegmentationAssignment().get(1).getSegmentationId());
+
+ String jsonToCompare = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiSegmentationAssignmentsMapped_to_aai.json")));
+ ObjectMapper omapper = new ObjectMapper();
+ org.onap.aai.domain.yang.SegmentationAssignments segmentationAssignment =
+ omapper.readValue(jsonToCompare, org.onap.aai.domain.yang.SegmentationAssignments.class);
+ ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
+ String jsonGenerated = ow.writeValueAsString(v12SegmentationAssignments);
+ String jsonExpected = ow.writeValueAsString(segmentationAssignment);
+ assertEquals(jsonExpected, jsonGenerated);
+
+ }
@Test
public void mapVpnBindingTest() {
- VpnBinding vpnBinding = new VpnBinding();
- vpnBinding.setVpnId("testVpnId");
- vpnBinding.setVpnName("testVpn");
- vpnBinding.setVpnPlatform("AVPN");
- vpnBinding.setCustomerVpnId("testCustomerVpnId");
- vpnBinding.setVpnType("testVpnType");
- vpnBinding.setVpnRegion("testVpnRegion");
- vpnBinding.setRouteDistinguisher("testRD");
+ VpnBinding vpnBinding = new VpnBinding();
+ vpnBinding.setVpnId("testVpnId");
+ vpnBinding.setVpnName("testVpn");
+ vpnBinding.setVpnPlatform("AVPN");
+ vpnBinding.setCustomerVpnId("testCustomerVpnId");
+ vpnBinding.setVpnType("testVpnType");
+ vpnBinding.setVpnRegion("testVpnRegion");
+ vpnBinding.setRouteDistinguisher("testRD");
RouteTarget routeTarget = new RouteTarget();
routeTarget.setRouteTargetRole("testRtRole");
routeTarget.setGlobalRouteTarget("testGrt");
@@ -659,7 +676,7 @@ public class AAIObjectMapperTest {
assertThat(actualRouteTarget, sameBeanAs(expectedRouteTarget));
}
-
+
@Test
public void mapSubnetTest() {
Subnet subnet = new Subnet();
@@ -671,24 +688,24 @@ public class AAIObjectMapperTest {
expectedSubnet.setSubnetId("testSubnetId");
expectedSubnet.setOrchestrationStatus("Pending");
expectedSubnet.setNeutronSubnetId("testNeutronSubnetId");
-
+
org.onap.aai.domain.yang.Subnet actualSubnet = aaiObjectMapper.mapSubnet(subnet);
assertThat(actualSubnet, sameBeanAs(expectedSubnet));
}
-
+
@Test
public void mapNetworkPolicyTest() {
NetworkPolicy networkPolicy = new NetworkPolicy();
networkPolicy.setNetworkPolicyId("testNetworkPolicyId");
networkPolicy.setNetworkPolicyFqdn("testNetworkPolicyFqdn");
- networkPolicy.setHeatStackId("testHeatStackId");
+ networkPolicy.setHeatStackId("testHeatStackId");
org.onap.aai.domain.yang.NetworkPolicy expectedNetworkPolicy = new org.onap.aai.domain.yang.NetworkPolicy();
expectedNetworkPolicy.setNetworkPolicyId("testNetworkPolicyId");
expectedNetworkPolicy.setNetworkPolicyFqdn("testNetworkPolicyFqdn");
- expectedNetworkPolicy.setHeatStackId("testHeatStackId");
-
+ expectedNetworkPolicy.setHeatStackId("testHeatStackId");
+
org.onap.aai.domain.yang.NetworkPolicy actualNetworkPolicy = aaiObjectMapper.mapNetworkPolicy(networkPolicy);
assertThat(actualNetworkPolicy, sameBeanAs(expectedNetworkPolicy));
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java
index fe9e1c1608..251ab2cb74 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java
@@ -29,9 +29,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import javax.ws.rs.core.Response;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
@@ -51,197 +49,196 @@ import org.onap.so.adapters.nwrest.UpdateNetworkRequest;
import org.onap.so.adapters.nwrest.UpdateNetworkResponse;
import org.onap.so.client.policy.JettisonStyleMapperProvider;
import org.onap.so.openstack.beans.NetworkRollback;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class NetworkAdapterClientIT extends BaseIntegrationTest{
-
- private static final String TESTING_ID = "___TESTING___";
- private static final String AAI_NETWORK_ID = "test";
- private static final String REST_ENDPOINT = "/networks/rest/v1/networks";
-
- private NetworkAdapterClientImpl client = new NetworkAdapterClientImpl();
- private ObjectMapper mapper = new JettisonStyleMapperProvider().getMapper();
-
- @BeforeClass
- public static void setUp() {
- System.setProperty("mso.config.path", "src/test/resources");
- }
-
- @Test
- public void createNetworkTest() throws NetworkAdapterClientException, JsonProcessingException {
- CreateNetworkRequest request = new CreateNetworkRequest();
- request.setCloudSiteId(TESTING_ID);
-
- CreateNetworkResponse mockResponse = new CreateNetworkResponse();
- mockResponse.setNetworkCreated(true);
- wireMockServer.stubFor(post(urlPathEqualTo(REST_ENDPOINT))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
-
- CreateNetworkResponse response = client.createNetwork(request);
- assertEquals("Testing CreateVfModule response", true, response.getNetworkCreated());
- }
-
- @Test(expected = NetworkAdapterClientException.class)
- public void createNetworkTestThrowException() throws NetworkAdapterClientException, JsonProcessingException {
- CreateNetworkRequest request = new CreateNetworkRequest();
- request.setCloudSiteId(TESTING_ID);
-
- CreateNetworkError mockResponse = new CreateNetworkError();
- mockResponse.setMessage("Error in create network");
- wireMockServer.stubFor(post(urlPathEqualTo(REST_ENDPOINT))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
-
- client.createNetwork(request);
- }
-
- @Test
- public void deleteNetworkTest() throws NetworkAdapterClientException, JsonProcessingException {
- DeleteNetworkRequest request = new DeleteNetworkRequest();
- request.setCloudSiteId(TESTING_ID);
-
- DeleteNetworkResponse mockResponse = new DeleteNetworkResponse();
- mockResponse.setNetworkDeleted(true);
-
- wireMockServer.stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
-
- DeleteNetworkResponse response = client.deleteNetwork(AAI_NETWORK_ID, request);
- assertEquals("Testing DeleteVfModule response", true, response.getNetworkDeleted());
- }
-
- @Test(expected = NetworkAdapterClientException.class)
- public void deleteNetworkTestThrowException() throws NetworkAdapterClientException, JsonProcessingException {
- DeleteNetworkRequest request = new DeleteNetworkRequest();
- request.setCloudSiteId(TESTING_ID);
-
- DeleteNetworkError mockResponse = new DeleteNetworkError();
- mockResponse.setMessage("Error in delete network");
- wireMockServer.stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
-
- client.deleteNetwork(AAI_NETWORK_ID, request);
- }
-
- @Test
- public void rollbackNetworkTest() throws NetworkAdapterClientException, JsonProcessingException {
- RollbackNetworkRequest request = new RollbackNetworkRequest();
- NetworkRollback rollback = new NetworkRollback();
- rollback.setCloudId(TESTING_ID);
- request.setNetworkRollback(rollback);
-
- RollbackNetworkResponse mockResponse = new RollbackNetworkResponse();
- mockResponse.setNetworkRolledBack(true);
-
- wireMockServer.stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
-
- RollbackNetworkResponse response = client.rollbackNetwork(AAI_NETWORK_ID, request);
- assertEquals("Testing DeleteVfModule response", true, response.getNetworkRolledBack());
- }
-
- @Test(expected = NetworkAdapterClientException.class)
- public void rollbackNetworkTestThrowException() throws NetworkAdapterClientException, JsonProcessingException {
- RollbackNetworkRequest request = new RollbackNetworkRequest();
- NetworkRollback rollback = new NetworkRollback();
- rollback.setCloudId(TESTING_ID);
- request.setNetworkRollback(rollback);
-
- RollbackNetworkError mockResponse = new RollbackNetworkError();
- mockResponse.setMessage("Error in rollback network");
-
- wireMockServer.stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
-
- client.rollbackNetwork(AAI_NETWORK_ID, request);
- }
-
- @Test
- public void queryNetworkTest() throws NetworkAdapterClientException, JsonProcessingException {
- QueryNetworkResponse mockResponse = new QueryNetworkResponse();
- mockResponse.setNetworkExists(true);
-
- wireMockServer.stubFor(get(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID)).withQueryParam("cloudSiteId", equalTo(TESTING_ID))
- .withQueryParam("tenantId", equalTo(TESTING_ID))
- .withQueryParam("networkStackId", equalTo("networkStackId")).withQueryParam("skipAAI", equalTo("true"))
- .withQueryParam("msoRequest.requestId", equalTo("testRequestId"))
- .withQueryParam("msoRequest.serviceInstanceId", equalTo("serviceInstanceId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
-
- QueryNetworkResponse response = client.queryNetwork(AAI_NETWORK_ID, TESTING_ID, TESTING_ID, "networkStackId",
- true, "testRequestId", "serviceInstanceId");
- assertEquals("Testing QueryVfModule response", true, response.getNetworkExists());
- }
-
- @Test(expected = NetworkAdapterClientException.class)
- public void queryNetworkTestThrowException() throws NetworkAdapterClientException, JsonProcessingException {
- QueryNetworkError mockResponse = new QueryNetworkError();
- mockResponse.setMessage("Error in query network");
-
- wireMockServer.stubFor(get(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID)).withQueryParam("cloudSiteId", equalTo(TESTING_ID))
- .withQueryParam("tenantId", equalTo(TESTING_ID))
- .withQueryParam("networkStackId", equalTo("networkStackId")).withQueryParam("skipAAI", equalTo("true"))
- .withQueryParam("msoRequest.requestId", equalTo("testRequestId"))
- .withQueryParam("msoRequest.serviceInstanceId", equalTo("serviceInstanceId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
-
- client.queryNetwork(AAI_NETWORK_ID, TESTING_ID, TESTING_ID, "networkStackId",
- true, "testRequestId", "serviceInstanceId");
- }
-
- @Test
- public void updateNetworkTest() throws NetworkAdapterClientException, JsonProcessingException {
- UpdateNetworkRequest request = new UpdateNetworkRequest();
- request.setCloudSiteId(TESTING_ID);
- request.setNetworkId("test1");
-
- UpdateNetworkResponse mockResponse = new UpdateNetworkResponse();
- mockResponse.setNetworkId("test1");
- wireMockServer.stubFor(put(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
-
- UpdateNetworkResponse response = client.updateNetwork(AAI_NETWORK_ID, request);
- assertEquals("Testing UpdateVfModule response", "test1", response.getNetworkId());
- }
-
- @Test
- public void updateNetworkTestAsync() throws NetworkAdapterClientException, JsonProcessingException {
- UpdateNetworkRequest request = new UpdateNetworkRequest();
- request.setCloudSiteId(TESTING_ID);
- request.setNetworkId("test1");
-
- UpdateNetworkResponse mockResponse = new UpdateNetworkResponse();
- mockResponse.setNetworkId("test1");
- wireMockServer.stubFor(put(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
-
- Response response = client.updateNetworkAsync(AAI_NETWORK_ID, request);
- assertNotNull(response.getEntity());
- }
-
- @Test(expected = NetworkAdapterClientException.class)
- public void updateNetworkTestThrowException() throws NetworkAdapterClientException, JsonProcessingException {
- UpdateNetworkRequest request = new UpdateNetworkRequest();
- request.setCloudSiteId(TESTING_ID);
- request.setNetworkId("test1");
-
- UpdateNetworkError mockResponse = new UpdateNetworkError();
- mockResponse.setMessage("Error in update network");
- wireMockServer.stubFor(put(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
-
- client.updateNetwork(AAI_NETWORK_ID, request);
- }
+public class NetworkAdapterClientIT extends BaseIntegrationTest {
+
+ private static final String TESTING_ID = "___TESTING___";
+ private static final String AAI_NETWORK_ID = "test";
+ private static final String REST_ENDPOINT = "/networks/rest/v1/networks";
+
+ private NetworkAdapterClientImpl client = new NetworkAdapterClientImpl();
+ private ObjectMapper mapper = new JettisonStyleMapperProvider().getMapper();
+
+ @BeforeClass
+ public static void setUp() {
+ System.setProperty("mso.config.path", "src/test/resources");
+ }
+
+ @Test
+ public void createNetworkTest() throws NetworkAdapterClientException, JsonProcessingException {
+ CreateNetworkRequest request = new CreateNetworkRequest();
+ request.setCloudSiteId(TESTING_ID);
+
+ CreateNetworkResponse mockResponse = new CreateNetworkResponse();
+ mockResponse.setNetworkCreated(true);
+ wireMockServer.stubFor(post(urlPathEqualTo(REST_ENDPOINT))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
+
+ CreateNetworkResponse response = client.createNetwork(request);
+ assertEquals("Testing CreateVfModule response", true, response.getNetworkCreated());
+ }
+
+ @Test(expected = NetworkAdapterClientException.class)
+ public void createNetworkTestThrowException() throws NetworkAdapterClientException, JsonProcessingException {
+ CreateNetworkRequest request = new CreateNetworkRequest();
+ request.setCloudSiteId(TESTING_ID);
+
+ CreateNetworkError mockResponse = new CreateNetworkError();
+ mockResponse.setMessage("Error in create network");
+ wireMockServer.stubFor(post(urlPathEqualTo(REST_ENDPOINT))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
+
+ client.createNetwork(request);
+ }
+
+ @Test
+ public void deleteNetworkTest() throws NetworkAdapterClientException, JsonProcessingException {
+ DeleteNetworkRequest request = new DeleteNetworkRequest();
+ request.setCloudSiteId(TESTING_ID);
+
+ DeleteNetworkResponse mockResponse = new DeleteNetworkResponse();
+ mockResponse.setNetworkDeleted(true);
+
+ wireMockServer.stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
+
+ DeleteNetworkResponse response = client.deleteNetwork(AAI_NETWORK_ID, request);
+ assertEquals("Testing DeleteVfModule response", true, response.getNetworkDeleted());
+ }
+
+ @Test(expected = NetworkAdapterClientException.class)
+ public void deleteNetworkTestThrowException() throws NetworkAdapterClientException, JsonProcessingException {
+ DeleteNetworkRequest request = new DeleteNetworkRequest();
+ request.setCloudSiteId(TESTING_ID);
+
+ DeleteNetworkError mockResponse = new DeleteNetworkError();
+ mockResponse.setMessage("Error in delete network");
+ wireMockServer.stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
+
+ client.deleteNetwork(AAI_NETWORK_ID, request);
+ }
+
+ @Test
+ public void rollbackNetworkTest() throws NetworkAdapterClientException, JsonProcessingException {
+ RollbackNetworkRequest request = new RollbackNetworkRequest();
+ NetworkRollback rollback = new NetworkRollback();
+ rollback.setCloudId(TESTING_ID);
+ request.setNetworkRollback(rollback);
+
+ RollbackNetworkResponse mockResponse = new RollbackNetworkResponse();
+ mockResponse.setNetworkRolledBack(true);
+
+ wireMockServer.stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
+
+ RollbackNetworkResponse response = client.rollbackNetwork(AAI_NETWORK_ID, request);
+ assertEquals("Testing DeleteVfModule response", true, response.getNetworkRolledBack());
+ }
+
+ @Test(expected = NetworkAdapterClientException.class)
+ public void rollbackNetworkTestThrowException() throws NetworkAdapterClientException, JsonProcessingException {
+ RollbackNetworkRequest request = new RollbackNetworkRequest();
+ NetworkRollback rollback = new NetworkRollback();
+ rollback.setCloudId(TESTING_ID);
+ request.setNetworkRollback(rollback);
+
+ RollbackNetworkError mockResponse = new RollbackNetworkError();
+ mockResponse.setMessage("Error in rollback network");
+
+ wireMockServer.stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
+
+ client.rollbackNetwork(AAI_NETWORK_ID, request);
+ }
+
+ @Test
+ public void queryNetworkTest() throws NetworkAdapterClientException, JsonProcessingException {
+ QueryNetworkResponse mockResponse = new QueryNetworkResponse();
+ mockResponse.setNetworkExists(true);
+
+ wireMockServer.stubFor(get(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
+ .withQueryParam("cloudSiteId", equalTo(TESTING_ID)).withQueryParam("tenantId", equalTo(TESTING_ID))
+ .withQueryParam("networkStackId", equalTo("networkStackId")).withQueryParam("skipAAI", equalTo("true"))
+ .withQueryParam("msoRequest.requestId", equalTo("testRequestId"))
+ .withQueryParam("msoRequest.serviceInstanceId", equalTo("serviceInstanceId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
+
+ QueryNetworkResponse response = client.queryNetwork(AAI_NETWORK_ID, TESTING_ID, TESTING_ID, "networkStackId",
+ true, "testRequestId", "serviceInstanceId");
+ assertEquals("Testing QueryVfModule response", true, response.getNetworkExists());
+ }
+
+ @Test(expected = NetworkAdapterClientException.class)
+ public void queryNetworkTestThrowException() throws NetworkAdapterClientException, JsonProcessingException {
+ QueryNetworkError mockResponse = new QueryNetworkError();
+ mockResponse.setMessage("Error in query network");
+
+ wireMockServer.stubFor(get(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
+ .withQueryParam("cloudSiteId", equalTo(TESTING_ID)).withQueryParam("tenantId", equalTo(TESTING_ID))
+ .withQueryParam("networkStackId", equalTo("networkStackId")).withQueryParam("skipAAI", equalTo("true"))
+ .withQueryParam("msoRequest.requestId", equalTo("testRequestId"))
+ .withQueryParam("msoRequest.serviceInstanceId", equalTo("serviceInstanceId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
+
+ client.queryNetwork(AAI_NETWORK_ID, TESTING_ID, TESTING_ID, "networkStackId", true, "testRequestId",
+ "serviceInstanceId");
+ }
+
+ @Test
+ public void updateNetworkTest() throws NetworkAdapterClientException, JsonProcessingException {
+ UpdateNetworkRequest request = new UpdateNetworkRequest();
+ request.setCloudSiteId(TESTING_ID);
+ request.setNetworkId("test1");
+
+ UpdateNetworkResponse mockResponse = new UpdateNetworkResponse();
+ mockResponse.setNetworkId("test1");
+ wireMockServer.stubFor(put(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
+
+ UpdateNetworkResponse response = client.updateNetwork(AAI_NETWORK_ID, request);
+ assertEquals("Testing UpdateVfModule response", "test1", response.getNetworkId());
+ }
+
+ @Test
+ public void updateNetworkTestAsync() throws NetworkAdapterClientException, JsonProcessingException {
+ UpdateNetworkRequest request = new UpdateNetworkRequest();
+ request.setCloudSiteId(TESTING_ID);
+ request.setNetworkId("test1");
+
+ UpdateNetworkResponse mockResponse = new UpdateNetworkResponse();
+ mockResponse.setNetworkId("test1");
+ wireMockServer.stubFor(put(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
+
+ Response response = client.updateNetworkAsync(AAI_NETWORK_ID, request);
+ assertNotNull(response.getEntity());
+ }
+
+ @Test(expected = NetworkAdapterClientException.class)
+ public void updateNetworkTestThrowException() throws NetworkAdapterClientException, JsonProcessingException {
+ UpdateNetworkRequest request = new UpdateNetworkRequest();
+ request.setCloudSiteId(TESTING_ID);
+ request.setNetworkId("test1");
+
+ UpdateNetworkError mockResponse = new UpdateNetworkError();
+ mockResponse.setMessage("Error in update network");
+ wireMockServer.stubFor(put(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
+
+ client.updateNetwork(AAI_NETWORK_ID, request);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java
index 4bdbd1a846..ccd677c80e 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java
@@ -24,7 +24,6 @@ import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
-
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
@@ -33,7 +32,6 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -62,314 +60,329 @@ import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoNetwork;
import org.onap.so.entity.MsoRequest;
import org.onap.so.openstack.beans.NetworkRollback;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-public class NetworkAdapterObjectMapperTest extends TestDataSetup{
-
- private NetworkAdapterObjectMapper SPY_networkAdapterObjectMapper = Mockito.spy(NetworkAdapterObjectMapper.class);
-
- private L3Network l3Network;
- private RequestContext requestContext;
- private ServiceInstance serviceInstance;
- private CloudRegion cloudRegion;
- private OrchestrationContext orchestrationContext;
- private Customer customer;
- Map<String, String> userInput;
-
- private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/NetworkMapper/";
-
- @Before
- public void before() {
- requestContext = setRequestContext();
-
- customer = buildCustomer();
-
- serviceInstance = setServiceInstance();
-
- cloudRegion = setCloudRegion();
-
- orchestrationContext = setOrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(false);
-
- userInput = setUserInput();
-
- l3Network = setL3Network();
-
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- }
-
- @Test
- public void buildCreateNetworkRequestFromBbobjectTest() throws Exception {
-
- String cloudRegionPo = "cloudRegionPo";
- CreateNetworkRequest expectedCreateNetworkRequest = new CreateNetworkRequest();
-
- expectedCreateNetworkRequest.setCloudSiteId(cloudRegionPo);
- expectedCreateNetworkRequest.setTenantId(cloudRegion.getTenantId());
- expectedCreateNetworkRequest.setNetworkId(l3Network.getNetworkId());
- expectedCreateNetworkRequest.setNetworkName(l3Network.getNetworkName());
- expectedCreateNetworkRequest.setNetworkType(l3Network.getNetworkType());
- expectedCreateNetworkRequest.setBackout(false);
- expectedCreateNetworkRequest.setFailIfExists(true);
- expectedCreateNetworkRequest.setNetworkTechnology("CONTRAIL");
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId(requestContext.getMsoRequestId());
- msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- expectedCreateNetworkRequest.setMsoRequest(msoRequest);
- expectedCreateNetworkRequest.setSkipAAI(true);
- HashMap<String, String> networkParams = new HashMap<String, String>();
- networkParams.put("shared", "true");
- networkParams.put("external", "false");
- networkParams.put("testUserInputKey", "testUserInputValue");
- expectedCreateNetworkRequest.setNetworkParams(networkParams);
-
- expectedCreateNetworkRequest.setNotificationUrl("endpoint/NetworkAResponse/messageId");
-
- Subnet openstackSubnet = new Subnet();
- HostRoute hostRoute = new HostRoute();
- hostRoute.setHostRouteId("hostRouteId");
- hostRoute.setNextHop("nextHop");
- hostRoute.setRoutePrefix("routePrefix");
- openstackSubnet.getHostRoutes().add(hostRoute);
- List<Subnet> subnetList = new ArrayList<Subnet>();
- subnetList.add(openstackSubnet);
- l3Network.getSubnets().add(openstackSubnet);
- l3Network.setNetworkTechnology("Contrail");
- l3Network.setIsSharedNetwork(true);
- l3Network.setIsExternalNetwork(false);
-
- doReturn("endpoint/").when(SPY_networkAdapterObjectMapper).getEndpoint();
- doReturn("messageId").when(SPY_networkAdapterObjectMapper).getRandomUuid();
-
- CreateNetworkRequest createNetworkRequest = SPY_networkAdapterObjectMapper.createNetworkRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, customer);
-
- assertThat(createNetworkRequest, sameBeanAs(expectedCreateNetworkRequest).ignoring("contrailRequest").ignoring("contrailNetwork").ignoring("providerVlanNetwork").ignoring("subnets").ignoring("messageId"));
- }
-
- @Test
- public void createNetworkRollbackRequestMapperTest() throws Exception {
-
- String cloudRegionPo = "cloudRegionPo";
- RollbackNetworkRequest expectedRollbackNetworkRequest = new RollbackNetworkRequest();
-
- expectedRollbackNetworkRequest.setMessageId(requestContext.getMsoRequestId());
- NetworkRollback networkRollback = new NetworkRollback();
- networkRollback.setCloudId(cloudRegionPo);
- networkRollback.setNetworkCreated(true);
- networkRollback.setNetworkId(l3Network.getNetworkId());
- networkRollback.setNetworkType(l3Network.getNetworkType());
- networkRollback.setTenantId(cloudRegion.getTenantId());
- expectedRollbackNetworkRequest.setNetworkRollback(networkRollback);
- expectedRollbackNetworkRequest.setSkipAAI(true);
-
- CreateNetworkResponse createNetworkResponse = new CreateNetworkResponse();
- createNetworkResponse.setNetworkCreated(true);
-
- RollbackNetworkRequest rollbackNetworkRequest = SPY_networkAdapterObjectMapper.createNetworkRollbackRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, createNetworkResponse);
-
- assertThat(rollbackNetworkRequest, sameBeanAs(expectedRollbackNetworkRequest).ignoring("contrailNetwork").ignoring("providerVlanNetwork").ignoring("subnets").ignoring("networkParams").ignoring("messageId"));
- }
-
- @Test
- public void updateNetworkRequestMapperTest() throws UnsupportedEncodingException {
- org.onap.so.openstack.beans.Subnet subnet = new org.onap.so.openstack.beans.Subnet();
- subnet.setSubnetId("subnetId");
- subnet.setHostRoutes(new ArrayList<org.onap.so.openstack.beans.HostRoute>());
-
- List<org.onap.so.openstack.beans.Subnet> subnets = new ArrayList<>();
- subnets.add(subnet);
-
- ProviderVlanNetwork providerVlanNetwork = new ProviderVlanNetwork("physicalNetworkName", new ArrayList<Integer>());
-
- List<String> policyFqdns = Arrays.asList("networkPolicyFqdn");
-
- org.onap.so.openstack.beans.RouteTarget expectedRouteTarget = new org.onap.so.openstack.beans.RouteTarget();
- expectedRouteTarget.setRouteTarget("globalRouteTarget");
-
- ContrailNetwork contrailNetwork = new ContrailNetwork();
- contrailNetwork.setPolicyFqdns(policyFqdns);
- contrailNetwork.setRouteTableFqdns(new ArrayList<String>());
- contrailNetwork.setRouteTargets(new ArrayList<org.onap.so.openstack.beans.RouteTarget>());
- contrailNetwork.getRouteTargets().add(expectedRouteTarget);
- contrailNetwork.getRouteTableFqdns().add("routeTableReferenceFqdn");
-
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setServiceInstanceId("testServiceInstanceId1");
-
- ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
- modelInfoNetwork.setNetworkType("networkType");
- modelInfoNetwork.setModelCustomizationUUID("modelCustomizationUuid");
- modelInfoNetwork.setModelVersion("modelVersion");
-
- Subnet actualSubnet = new Subnet();
- actualSubnet.setSubnetId("subnetId");
- actualSubnet.setDhcpEnabled(false);
- actualSubnet.setIpVersion("4");
-
- RouteTarget routeTarget = new RouteTarget();
- routeTarget.setGlobalRouteTarget("globalRouteTarget");
-
- VpnBinding vpnBinding = new VpnBinding();
- vpnBinding.setVpnId("vpnId");
- vpnBinding.getRouteTargets().add(routeTarget);
-
- Customer customer = new Customer();
- customer.getVpnBindings().add(vpnBinding);
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- customer.setServiceSubscription(serviceSubscription);
- // set Customer on service instance
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
-
- NetworkPolicy networkPolicy = new NetworkPolicy();
- networkPolicy.setNetworkPolicyId("networkPolicyId");
- networkPolicy.setNetworkPolicyFqdn("networkPolicyFqdn");
-
- RouteTableReference routeTableReference = new RouteTableReference();
- routeTableReference.setRouteTableReferenceFqdn("routeTableReferenceFqdn");
-
- l3Network.setModelInfoNetwork(modelInfoNetwork);
- l3Network.setPhysicalNetworkName("physicalNetworkName");
- l3Network.getSubnets().add(actualSubnet);
- l3Network.getNetworkPolicies().add(networkPolicy);
- l3Network.getContrailNetworkRouteTableReferences().add(routeTableReference);
- l3Network.setIsSharedNetwork(false);
- l3Network.setIsExternalNetwork(false);
- HashMap<String, String> networkParams = new HashMap<String, String>();
- networkParams.put("shared", "false");
- networkParams.put("external", "false");
- networkParams.put("testUserInputKey", "testUserInputValue");
-
- UpdateNetworkRequest expectedUpdateNetworkRequest = new UpdateNetworkRequest();
- expectedUpdateNetworkRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
- expectedUpdateNetworkRequest.setTenantId(cloudRegion.getTenantId());
- expectedUpdateNetworkRequest.setNetworkId(l3Network.getNetworkId());
- expectedUpdateNetworkRequest.setNetworkStackId(l3Network.getHeatStackId());
- expectedUpdateNetworkRequest.setNetworkName(l3Network.getNetworkName());
- expectedUpdateNetworkRequest.setNetworkType(l3Network.getModelInfoNetwork().getNetworkType());
- expectedUpdateNetworkRequest.setNetworkTypeVersion(l3Network.getModelInfoNetwork().getModelVersion());
- expectedUpdateNetworkRequest.setModelCustomizationUuid(l3Network.getModelInfoNetwork().getModelCustomizationUUID());
- expectedUpdateNetworkRequest.setSubnets(subnets);
- expectedUpdateNetworkRequest.setProviderVlanNetwork(providerVlanNetwork);
- expectedUpdateNetworkRequest.setContrailNetwork(contrailNetwork);
- expectedUpdateNetworkRequest.setNetworkParams(networkParams);
- expectedUpdateNetworkRequest.setMsoRequest(msoRequest);
- expectedUpdateNetworkRequest.setSkipAAI(true);
- expectedUpdateNetworkRequest.setBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
- expectedUpdateNetworkRequest.setMessageId("messageId");
- expectedUpdateNetworkRequest.setNotificationUrl("http://localhost:28080/mso/WorkflowMesssage/NetworkAResponse/messageId");
-
- doReturn("messageId").when(SPY_networkAdapterObjectMapper).getRandomUuid();
- doReturn("http://localhost:28080/mso/WorkflowMesssage").when(SPY_networkAdapterObjectMapper).getEndpoint();
- UpdateNetworkRequest actualUpdateNetworkRequest = SPY_networkAdapterObjectMapper.createNetworkUpdateRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, customer);
-
- assertThat(actualUpdateNetworkRequest, sameBeanAs(expectedUpdateNetworkRequest).ignoring("msoRequest.requestId"));
- }
-
- @Test
- public void deleteNetworkRequestMapperTest() throws Exception {
- DeleteNetworkRequest expectedDeleteNetworkRequest = new DeleteNetworkRequest();
-
- String messageId = "messageId";
- expectedDeleteNetworkRequest.setMessageId(messageId);
- doReturn(messageId).when(SPY_networkAdapterObjectMapper).getRandomUuid();
-
- ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
- l3Network.setModelInfoNetwork(modelInfoNetwork);
- modelInfoNetwork.setModelCustomizationUUID("modelCustomizationUuid");
- expectedDeleteNetworkRequest.setModelCustomizationUuid(modelInfoNetwork.getModelCustomizationUUID());
-
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId(requestContext.getMsoRequestId());
- msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- expectedDeleteNetworkRequest.setMsoRequest(msoRequest);
-
- expectedDeleteNetworkRequest.setNetworkId(l3Network.getNetworkId());
-
- l3Network.setHeatStackId("heatStackId");
- expectedDeleteNetworkRequest.setNetworkStackId(l3Network.getHeatStackId());
-
- expectedDeleteNetworkRequest.setNetworkType(l3Network.getNetworkType());
-
- expectedDeleteNetworkRequest.setSkipAAI(true);
-
- expectedDeleteNetworkRequest.setTenantId(cloudRegion.getTenantId());
-
- expectedDeleteNetworkRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
-
- expectedDeleteNetworkRequest.setNotificationUrl("endpoint/NetworkAResponse/messageId");
-
- doReturn("endpoint/").when(SPY_networkAdapterObjectMapper).getEndpoint();
- doReturn("messageId").when(SPY_networkAdapterObjectMapper).getRandomUuid();
-
- DeleteNetworkRequest deleteNetworkRequest = SPY_networkAdapterObjectMapper.deleteNetworkRequestMapper(requestContext, cloudRegion, serviceInstance, l3Network);
-
- assertThat(expectedDeleteNetworkRequest, sameBeanAs(deleteNetworkRequest));
- }
-
- @Test
- public void deleteNetworkRequestNoHeatIdMapperTest() throws Exception {
- DeleteNetworkRequest expectedDeleteNetworkRequest = new DeleteNetworkRequest();
-
- String messageId = "messageId";
- expectedDeleteNetworkRequest.setMessageId(messageId);
- doReturn(messageId).when(SPY_networkAdapterObjectMapper).getRandomUuid();
-
- ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
- l3Network.setModelInfoNetwork(modelInfoNetwork);
- modelInfoNetwork.setModelCustomizationUUID("modelCustomizationUuid");
- expectedDeleteNetworkRequest.setModelCustomizationUuid(modelInfoNetwork.getModelCustomizationUUID());
-
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId(requestContext.getMsoRequestId());
- msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- expectedDeleteNetworkRequest.setMsoRequest(msoRequest);
-
- expectedDeleteNetworkRequest.setNetworkId(l3Network.getNetworkId());
-
- l3Network.setNetworkName("heatStackId");
- expectedDeleteNetworkRequest.setNetworkStackId("heatStackId");
-
- expectedDeleteNetworkRequest.setNetworkType(l3Network.getNetworkType());
-
- expectedDeleteNetworkRequest.setSkipAAI(true);
-
- expectedDeleteNetworkRequest.setTenantId(cloudRegion.getTenantId());
-
- expectedDeleteNetworkRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
-
- expectedDeleteNetworkRequest.setNotificationUrl("endpoint/NetworkAResponse/messageId");
-
- doReturn("endpoint/").when(SPY_networkAdapterObjectMapper).getEndpoint();
- doReturn("messageId").when(SPY_networkAdapterObjectMapper).getRandomUuid();
- DeleteNetworkRequest deleteNetworkRequest = SPY_networkAdapterObjectMapper.deleteNetworkRequestMapper(requestContext, cloudRegion, serviceInstance, l3Network);
-
- assertThat(expectedDeleteNetworkRequest, sameBeanAs(deleteNetworkRequest));
- }
-
- @Test
- public void buildOpenstackSubnetListTest() throws Exception {
-
- ObjectMapper omapper = new ObjectMapper();
- String bbJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "generalBB.json")));
- org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock gbb = omapper.readValue(
- bbJson,
- org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock.class);
- L3Network myNetwork = gbb.getServiceInstance().getNetworks().get(0);
-
- String expectedCreateNetworkRequestJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "createNetworkRequest.json")));
- org.onap.so.adapters.nwrest.CreateNetworkRequest expectedCreateNetworkRequest = omapper.readValue(
- expectedCreateNetworkRequestJson,
- org.onap.so.adapters.nwrest.CreateNetworkRequest.class);
-
- String cloudRegionPo = "cloudRegionPo";
-
- expectedCreateNetworkRequest.setNotificationUrl("endpoint/NetworkAResponse/messageId");
-
- doReturn("endpoint/").when(SPY_networkAdapterObjectMapper).getEndpoint();
- doReturn("messageId").when(SPY_networkAdapterObjectMapper).getRandomUuid();
- CreateNetworkRequest createNetworkRequest = SPY_networkAdapterObjectMapper.createNetworkRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, myNetwork, userInput, cloudRegionPo, customer);
- //ignoring dynamic fields and networkParams that throws parsing exception on json file load
- assertThat(createNetworkRequest, sameBeanAs(expectedCreateNetworkRequest).ignoring("messageId").ignoring("msoRequest.requestId").ignoring("networkParams"));
- }
+public class NetworkAdapterObjectMapperTest extends TestDataSetup {
+
+ private NetworkAdapterObjectMapper SPY_networkAdapterObjectMapper = Mockito.spy(NetworkAdapterObjectMapper.class);
+
+ private L3Network l3Network;
+ private RequestContext requestContext;
+ private ServiceInstance serviceInstance;
+ private CloudRegion cloudRegion;
+ private OrchestrationContext orchestrationContext;
+ private Customer customer;
+ Map<String, String> userInput;
+
+ private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/NetworkMapper/";
+
+ @Before
+ public void before() {
+ requestContext = setRequestContext();
+
+ customer = buildCustomer();
+
+ serviceInstance = setServiceInstance();
+
+ cloudRegion = setCloudRegion();
+
+ orchestrationContext = setOrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(false);
+
+ userInput = setUserInput();
+
+ l3Network = setL3Network();
+
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ }
+
+ @Test
+ public void buildCreateNetworkRequestFromBbobjectTest() throws Exception {
+
+ String cloudRegionPo = "cloudRegionPo";
+ CreateNetworkRequest expectedCreateNetworkRequest = new CreateNetworkRequest();
+
+ expectedCreateNetworkRequest.setCloudSiteId(cloudRegionPo);
+ expectedCreateNetworkRequest.setTenantId(cloudRegion.getTenantId());
+ expectedCreateNetworkRequest.setNetworkId(l3Network.getNetworkId());
+ expectedCreateNetworkRequest.setNetworkName(l3Network.getNetworkName());
+ expectedCreateNetworkRequest.setNetworkType(l3Network.getNetworkType());
+ expectedCreateNetworkRequest.setBackout(false);
+ expectedCreateNetworkRequest.setFailIfExists(true);
+ expectedCreateNetworkRequest.setNetworkTechnology("CONTRAIL");
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId(requestContext.getMsoRequestId());
+ msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ expectedCreateNetworkRequest.setMsoRequest(msoRequest);
+ expectedCreateNetworkRequest.setSkipAAI(true);
+ HashMap<String, String> networkParams = new HashMap<String, String>();
+ networkParams.put("shared", "true");
+ networkParams.put("external", "false");
+ networkParams.put("testUserInputKey", "testUserInputValue");
+ expectedCreateNetworkRequest.setNetworkParams(networkParams);
+
+ expectedCreateNetworkRequest.setNotificationUrl("endpoint/NetworkAResponse/messageId");
+
+ Subnet openstackSubnet = new Subnet();
+ HostRoute hostRoute = new HostRoute();
+ hostRoute.setHostRouteId("hostRouteId");
+ hostRoute.setNextHop("nextHop");
+ hostRoute.setRoutePrefix("routePrefix");
+ openstackSubnet.getHostRoutes().add(hostRoute);
+ List<Subnet> subnetList = new ArrayList<Subnet>();
+ subnetList.add(openstackSubnet);
+ l3Network.getSubnets().add(openstackSubnet);
+ l3Network.setNetworkTechnology("Contrail");
+ l3Network.setIsSharedNetwork(true);
+ l3Network.setIsExternalNetwork(false);
+
+ doReturn("endpoint/").when(SPY_networkAdapterObjectMapper).getEndpoint();
+ doReturn("messageId").when(SPY_networkAdapterObjectMapper).getRandomUuid();
+
+ CreateNetworkRequest createNetworkRequest =
+ SPY_networkAdapterObjectMapper.createNetworkRequestMapper(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, customer);
+
+ assertThat(createNetworkRequest, sameBeanAs(expectedCreateNetworkRequest).ignoring("contrailRequest")
+ .ignoring("contrailNetwork").ignoring("providerVlanNetwork").ignoring("subnets").ignoring("messageId"));
+ }
+
+ @Test
+ public void createNetworkRollbackRequestMapperTest() throws Exception {
+
+ String cloudRegionPo = "cloudRegionPo";
+ RollbackNetworkRequest expectedRollbackNetworkRequest = new RollbackNetworkRequest();
+
+ expectedRollbackNetworkRequest.setMessageId(requestContext.getMsoRequestId());
+ NetworkRollback networkRollback = new NetworkRollback();
+ networkRollback.setCloudId(cloudRegionPo);
+ networkRollback.setNetworkCreated(true);
+ networkRollback.setNetworkId(l3Network.getNetworkId());
+ networkRollback.setNetworkType(l3Network.getNetworkType());
+ networkRollback.setTenantId(cloudRegion.getTenantId());
+ expectedRollbackNetworkRequest.setNetworkRollback(networkRollback);
+ expectedRollbackNetworkRequest.setSkipAAI(true);
+
+ CreateNetworkResponse createNetworkResponse = new CreateNetworkResponse();
+ createNetworkResponse.setNetworkCreated(true);
+
+ RollbackNetworkRequest rollbackNetworkRequest = SPY_networkAdapterObjectMapper
+ .createNetworkRollbackRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance,
+ l3Network, userInput, cloudRegionPo, createNetworkResponse);
+
+ assertThat(rollbackNetworkRequest, sameBeanAs(expectedRollbackNetworkRequest).ignoring("contrailNetwork")
+ .ignoring("providerVlanNetwork").ignoring("subnets").ignoring("networkParams").ignoring("messageId"));
+ }
+
+ @Test
+ public void updateNetworkRequestMapperTest() throws UnsupportedEncodingException {
+ org.onap.so.openstack.beans.Subnet subnet = new org.onap.so.openstack.beans.Subnet();
+ subnet.setSubnetId("subnetId");
+ subnet.setHostRoutes(new ArrayList<org.onap.so.openstack.beans.HostRoute>());
+
+ List<org.onap.so.openstack.beans.Subnet> subnets = new ArrayList<>();
+ subnets.add(subnet);
+
+ ProviderVlanNetwork providerVlanNetwork =
+ new ProviderVlanNetwork("physicalNetworkName", new ArrayList<Integer>());
+
+ List<String> policyFqdns = Arrays.asList("networkPolicyFqdn");
+
+ org.onap.so.openstack.beans.RouteTarget expectedRouteTarget = new org.onap.so.openstack.beans.RouteTarget();
+ expectedRouteTarget.setRouteTarget("globalRouteTarget");
+
+ ContrailNetwork contrailNetwork = new ContrailNetwork();
+ contrailNetwork.setPolicyFqdns(policyFqdns);
+ contrailNetwork.setRouteTableFqdns(new ArrayList<String>());
+ contrailNetwork.setRouteTargets(new ArrayList<org.onap.so.openstack.beans.RouteTarget>());
+ contrailNetwork.getRouteTargets().add(expectedRouteTarget);
+ contrailNetwork.getRouteTableFqdns().add("routeTableReferenceFqdn");
+
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setServiceInstanceId("testServiceInstanceId1");
+
+ ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
+ modelInfoNetwork.setNetworkType("networkType");
+ modelInfoNetwork.setModelCustomizationUUID("modelCustomizationUuid");
+ modelInfoNetwork.setModelVersion("modelVersion");
+
+ Subnet actualSubnet = new Subnet();
+ actualSubnet.setSubnetId("subnetId");
+ actualSubnet.setDhcpEnabled(false);
+ actualSubnet.setIpVersion("4");
+
+ RouteTarget routeTarget = new RouteTarget();
+ routeTarget.setGlobalRouteTarget("globalRouteTarget");
+
+ VpnBinding vpnBinding = new VpnBinding();
+ vpnBinding.setVpnId("vpnId");
+ vpnBinding.getRouteTargets().add(routeTarget);
+
+ Customer customer = new Customer();
+ customer.getVpnBindings().add(vpnBinding);
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ customer.setServiceSubscription(serviceSubscription);
+ // set Customer on service instance
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+
+ NetworkPolicy networkPolicy = new NetworkPolicy();
+ networkPolicy.setNetworkPolicyId("networkPolicyId");
+ networkPolicy.setNetworkPolicyFqdn("networkPolicyFqdn");
+
+ RouteTableReference routeTableReference = new RouteTableReference();
+ routeTableReference.setRouteTableReferenceFqdn("routeTableReferenceFqdn");
+
+ l3Network.setModelInfoNetwork(modelInfoNetwork);
+ l3Network.setPhysicalNetworkName("physicalNetworkName");
+ l3Network.getSubnets().add(actualSubnet);
+ l3Network.getNetworkPolicies().add(networkPolicy);
+ l3Network.getContrailNetworkRouteTableReferences().add(routeTableReference);
+ l3Network.setIsSharedNetwork(false);
+ l3Network.setIsExternalNetwork(false);
+ HashMap<String, String> networkParams = new HashMap<String, String>();
+ networkParams.put("shared", "false");
+ networkParams.put("external", "false");
+ networkParams.put("testUserInputKey", "testUserInputValue");
+
+ UpdateNetworkRequest expectedUpdateNetworkRequest = new UpdateNetworkRequest();
+ expectedUpdateNetworkRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+ expectedUpdateNetworkRequest.setTenantId(cloudRegion.getTenantId());
+ expectedUpdateNetworkRequest.setNetworkId(l3Network.getNetworkId());
+ expectedUpdateNetworkRequest.setNetworkStackId(l3Network.getHeatStackId());
+ expectedUpdateNetworkRequest.setNetworkName(l3Network.getNetworkName());
+ expectedUpdateNetworkRequest.setNetworkType(l3Network.getModelInfoNetwork().getNetworkType());
+ expectedUpdateNetworkRequest.setNetworkTypeVersion(l3Network.getModelInfoNetwork().getModelVersion());
+ expectedUpdateNetworkRequest
+ .setModelCustomizationUuid(l3Network.getModelInfoNetwork().getModelCustomizationUUID());
+ expectedUpdateNetworkRequest.setSubnets(subnets);
+ expectedUpdateNetworkRequest.setProviderVlanNetwork(providerVlanNetwork);
+ expectedUpdateNetworkRequest.setContrailNetwork(contrailNetwork);
+ expectedUpdateNetworkRequest.setNetworkParams(networkParams);
+ expectedUpdateNetworkRequest.setMsoRequest(msoRequest);
+ expectedUpdateNetworkRequest.setSkipAAI(true);
+ expectedUpdateNetworkRequest.setBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
+ expectedUpdateNetworkRequest.setMessageId("messageId");
+ expectedUpdateNetworkRequest
+ .setNotificationUrl("http://localhost:28080/mso/WorkflowMesssage/NetworkAResponse/messageId");
+
+ doReturn("messageId").when(SPY_networkAdapterObjectMapper).getRandomUuid();
+ doReturn("http://localhost:28080/mso/WorkflowMesssage").when(SPY_networkAdapterObjectMapper).getEndpoint();
+ UpdateNetworkRequest actualUpdateNetworkRequest =
+ SPY_networkAdapterObjectMapper.createNetworkUpdateRequestMapper(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, l3Network, userInput, customer);
+
+ assertThat(actualUpdateNetworkRequest,
+ sameBeanAs(expectedUpdateNetworkRequest).ignoring("msoRequest.requestId"));
+ }
+
+ @Test
+ public void deleteNetworkRequestMapperTest() throws Exception {
+ DeleteNetworkRequest expectedDeleteNetworkRequest = new DeleteNetworkRequest();
+
+ String messageId = "messageId";
+ expectedDeleteNetworkRequest.setMessageId(messageId);
+ doReturn(messageId).when(SPY_networkAdapterObjectMapper).getRandomUuid();
+
+ ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
+ l3Network.setModelInfoNetwork(modelInfoNetwork);
+ modelInfoNetwork.setModelCustomizationUUID("modelCustomizationUuid");
+ expectedDeleteNetworkRequest.setModelCustomizationUuid(modelInfoNetwork.getModelCustomizationUUID());
+
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId(requestContext.getMsoRequestId());
+ msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ expectedDeleteNetworkRequest.setMsoRequest(msoRequest);
+
+ expectedDeleteNetworkRequest.setNetworkId(l3Network.getNetworkId());
+
+ l3Network.setHeatStackId("heatStackId");
+ expectedDeleteNetworkRequest.setNetworkStackId(l3Network.getHeatStackId());
+
+ expectedDeleteNetworkRequest.setNetworkType(l3Network.getNetworkType());
+
+ expectedDeleteNetworkRequest.setSkipAAI(true);
+
+ expectedDeleteNetworkRequest.setTenantId(cloudRegion.getTenantId());
+
+ expectedDeleteNetworkRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+
+ expectedDeleteNetworkRequest.setNotificationUrl("endpoint/NetworkAResponse/messageId");
+
+ doReturn("endpoint/").when(SPY_networkAdapterObjectMapper).getEndpoint();
+ doReturn("messageId").when(SPY_networkAdapterObjectMapper).getRandomUuid();
+
+ DeleteNetworkRequest deleteNetworkRequest = SPY_networkAdapterObjectMapper
+ .deleteNetworkRequestMapper(requestContext, cloudRegion, serviceInstance, l3Network);
+
+ assertThat(expectedDeleteNetworkRequest, sameBeanAs(deleteNetworkRequest));
+ }
+
+ @Test
+ public void deleteNetworkRequestNoHeatIdMapperTest() throws Exception {
+ DeleteNetworkRequest expectedDeleteNetworkRequest = new DeleteNetworkRequest();
+
+ String messageId = "messageId";
+ expectedDeleteNetworkRequest.setMessageId(messageId);
+ doReturn(messageId).when(SPY_networkAdapterObjectMapper).getRandomUuid();
+
+ ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
+ l3Network.setModelInfoNetwork(modelInfoNetwork);
+ modelInfoNetwork.setModelCustomizationUUID("modelCustomizationUuid");
+ expectedDeleteNetworkRequest.setModelCustomizationUuid(modelInfoNetwork.getModelCustomizationUUID());
+
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId(requestContext.getMsoRequestId());
+ msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ expectedDeleteNetworkRequest.setMsoRequest(msoRequest);
+
+ expectedDeleteNetworkRequest.setNetworkId(l3Network.getNetworkId());
+
+ l3Network.setNetworkName("heatStackId");
+ expectedDeleteNetworkRequest.setNetworkStackId("heatStackId");
+
+ expectedDeleteNetworkRequest.setNetworkType(l3Network.getNetworkType());
+
+ expectedDeleteNetworkRequest.setSkipAAI(true);
+
+ expectedDeleteNetworkRequest.setTenantId(cloudRegion.getTenantId());
+
+ expectedDeleteNetworkRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+
+ expectedDeleteNetworkRequest.setNotificationUrl("endpoint/NetworkAResponse/messageId");
+
+ doReturn("endpoint/").when(SPY_networkAdapterObjectMapper).getEndpoint();
+ doReturn("messageId").when(SPY_networkAdapterObjectMapper).getRandomUuid();
+ DeleteNetworkRequest deleteNetworkRequest = SPY_networkAdapterObjectMapper
+ .deleteNetworkRequestMapper(requestContext, cloudRegion, serviceInstance, l3Network);
+
+ assertThat(expectedDeleteNetworkRequest, sameBeanAs(deleteNetworkRequest));
+ }
+
+ @Test
+ public void buildOpenstackSubnetListTest() throws Exception {
+
+ ObjectMapper omapper = new ObjectMapper();
+ String bbJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "generalBB.json")));
+ org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock gbb =
+ omapper.readValue(bbJson, org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock.class);
+ L3Network myNetwork = gbb.getServiceInstance().getNetworks().get(0);
+
+ String expectedCreateNetworkRequestJson =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "createNetworkRequest.json")));
+ org.onap.so.adapters.nwrest.CreateNetworkRequest expectedCreateNetworkRequest = omapper
+ .readValue(expectedCreateNetworkRequestJson, org.onap.so.adapters.nwrest.CreateNetworkRequest.class);
+
+ String cloudRegionPo = "cloudRegionPo";
+
+ expectedCreateNetworkRequest.setNotificationUrl("endpoint/NetworkAResponse/messageId");
+
+ doReturn("endpoint/").when(SPY_networkAdapterObjectMapper).getEndpoint();
+ doReturn("messageId").when(SPY_networkAdapterObjectMapper).getRandomUuid();
+ CreateNetworkRequest createNetworkRequest =
+ SPY_networkAdapterObjectMapper.createNetworkRequestMapper(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, myNetwork, userInput, cloudRegionPo, customer);
+ // ignoring dynamic fields and networkParams that throws parsing exception on json file load
+ assertThat(createNetworkRequest, sameBeanAs(expectedCreateNetworkRequest).ignoring("messageId")
+ .ignoring("msoRequest.requestId").ignoring("networkParams"));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java
index 90e99eb0ad..7fb1db9d98 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java
@@ -28,7 +28,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.junit.Assert.assertEquals;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
@@ -44,182 +43,179 @@ import org.onap.so.adapters.vnfrest.UpdateVfModuleResponse;
import org.onap.so.adapters.vnfrest.VfModuleExceptionResponse;
import org.onap.so.adapters.vnfrest.VfModuleRollback;
import org.onap.so.client.policy.JettisonStyleMapperProvider;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class VnfAdapterClientIT extends BaseIntegrationTest{
-
- private static final String TESTING_ID = "___TESTING___";
- private static final String AAI_VNF_ID = "test";
- private static final String AAI_VF_MODULE_ID = "test";
- private static final String REST_ENDPOINT = "/services/rest/v1/vnfs";
-
- private VnfAdapterClientImpl client = new VnfAdapterClientImpl();
- private ObjectMapper mapper = new JettisonStyleMapperProvider().getMapper();
-
- @BeforeClass
- public static void setUp() {
- System.setProperty("mso.config.path", "src/test/resources");
- }
-
- @Test
- public void createVfModuleTest() throws JsonProcessingException, VnfAdapterClientException {
- CreateVfModuleRequest request = new CreateVfModuleRequest();
- request.setCloudSiteId(TESTING_ID);
-
- CreateVfModuleResponse mockResponse = new CreateVfModuleResponse();
- mockResponse.setVfModuleCreated(true);
- wireMockServer.stubFor(post(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
-
- CreateVfModuleResponse response = client.createVfModule(AAI_VNF_ID, request);
- assertEquals("Testing CreateVfModule response", true, response.getVfModuleCreated());
- }
-
- @Test(expected = VnfAdapterClientException.class)
- public void createVfModuleTestThrowException() throws JsonProcessingException, VnfAdapterClientException {
- CreateVfModuleRequest request = new CreateVfModuleRequest();
- request.setCloudSiteId(TESTING_ID);
-
- VfModuleExceptionResponse mockResponse = new VfModuleExceptionResponse();
- mockResponse.setMessage("Error in create Vf module");
- wireMockServer.stubFor(post(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
-
- client.createVfModule(AAI_VNF_ID, request);
- }
-
- @Test
- public void rollbackVfModuleTest() throws JsonProcessingException, VnfAdapterClientException {
- RollbackVfModuleRequest request = new RollbackVfModuleRequest();
- VfModuleRollback rollback = new VfModuleRollback();
- rollback.setCloudSiteId(TESTING_ID);
- request.setVfModuleRollback(rollback);
-
- RollbackVfModuleResponse mockResponse = new RollbackVfModuleResponse();
- mockResponse.setVfModuleRolledback(true);
- wireMockServer.stubFor(
- delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID + "/rollback"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
-
- RollbackVfModuleResponse response = client.rollbackVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, request);
- assertEquals("Testing RollbackVfModule response", true, response.getVfModuleRolledback());
- }
-
- @Test(expected = VnfAdapterClientException.class)
- public void rollbackVfModuleTestThrowException() throws JsonProcessingException, VnfAdapterClientException {
- RollbackVfModuleRequest request = new RollbackVfModuleRequest();
- VfModuleRollback rollback = new VfModuleRollback();
- rollback.setCloudSiteId(TESTING_ID);
- request.setVfModuleRollback(rollback);
-
- VfModuleExceptionResponse mockResponse = new VfModuleExceptionResponse();
- mockResponse.setMessage("Error in rollback Vf module");
- wireMockServer.stubFor(
- delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID + "/rollback"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
-
- client.rollbackVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, request);
- }
-
- @Test
- public void deleteVfModuleTest() throws JsonProcessingException, VnfAdapterClientException {
- DeleteVfModuleRequest request = new DeleteVfModuleRequest();
- request.setCloudSiteId(TESTING_ID);
-
- DeleteVfModuleResponse mockResponse = new DeleteVfModuleResponse();
- mockResponse.setVfModuleDeleted(true);
- wireMockServer.stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
-
- DeleteVfModuleResponse response = client.deleteVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, request);
- assertEquals("Testing DeleteVfModule response", true, response.getVfModuleDeleted());
- }
-
- @Test(expected = VnfAdapterClientException.class)
- public void deleteVfModuleTestThrowException() throws JsonProcessingException, VnfAdapterClientException {
- DeleteVfModuleRequest request = new DeleteVfModuleRequest();
- request.setCloudSiteId(TESTING_ID);
-
- VfModuleExceptionResponse mockResponse = new VfModuleExceptionResponse();
- mockResponse.setMessage("Error in delete Vf module");
- wireMockServer.stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
-
- client.deleteVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, request);
- }
-
- @Test
- public void updateVfModuleTest() throws JsonProcessingException, VnfAdapterClientException {
- UpdateVfModuleRequest request = new UpdateVfModuleRequest();
- request.setCloudSiteId(TESTING_ID);
- request.setVfModuleId("test1");
-
- UpdateVfModuleResponse mockResponse = new UpdateVfModuleResponse();
- mockResponse.setVfModuleId("test1");
- wireMockServer.stubFor(put(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
-
- UpdateVfModuleResponse response = client.updateVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, request);
- assertEquals("Testing UpdateVfModule response", "test1", response.getVfModuleId());
- }
-
- @Test(expected = VnfAdapterClientException.class)
- public void updateVfModuleTestThrowException() throws JsonProcessingException, VnfAdapterClientException {
- UpdateVfModuleRequest request = new UpdateVfModuleRequest();
- request.setCloudSiteId(TESTING_ID);
- request.setVfModuleId("test1");
-
- VfModuleExceptionResponse mockResponse = new VfModuleExceptionResponse();
- mockResponse.setMessage("Error in update Vf module");
- wireMockServer.stubFor(put(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
-
- client.updateVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, request);
- }
-
- @Test
- public void queryVfModuleTest() throws JsonProcessingException, VnfAdapterClientException {
- QueryVfModuleResponse mockResponse = new QueryVfModuleResponse();
- mockResponse.setVnfId(AAI_VNF_ID);
- mockResponse.setVfModuleId(AAI_VF_MODULE_ID);
- wireMockServer.stubFor(get(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID))
- .withQueryParam("cloudSiteId", equalTo(TESTING_ID))
- .withQueryParam("tenantId", equalTo(TESTING_ID))
- .withQueryParam("vfModuleName", equalTo("someName"))
- .withQueryParam("skipAAI", equalTo("true"))
- .withQueryParam("msoRequest.requestId", equalTo("testRequestId"))
- .withQueryParam("msoRequest.serviceInstanceId", equalTo("serviceInstanceId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
- QueryVfModuleResponse response = client.queryVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, TESTING_ID, TESTING_ID,
- "someName", true, "testRequestId", "serviceInstanceId");
- assertEquals("Testing QueryVfModule response", AAI_VF_MODULE_ID, response.getVfModuleId());
- }
-
- @Test(expected = VnfAdapterClientException.class)
- public void queryVfModuleTestThrowException() throws JsonProcessingException, VnfAdapterClientException {
- VfModuleExceptionResponse mockResponse = new VfModuleExceptionResponse();
- mockResponse.setMessage("Error in update Vf module");
- wireMockServer.stubFor(get(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID))
- .withQueryParam("cloudSiteId", equalTo(TESTING_ID))
- .withQueryParam("tenantId", equalTo(TESTING_ID))
- .withQueryParam("vfModuleName", equalTo("someName"))
- .withQueryParam("skipAAI", equalTo("true"))
- .withQueryParam("msoRequest.requestId", equalTo("testRequestId"))
- .withQueryParam("msoRequest.serviceInstanceId", equalTo("serviceInstanceId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
- client.queryVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, TESTING_ID, TESTING_ID,
- "someName", true, "testRequestId", "serviceInstanceId");
- }
+public class VnfAdapterClientIT extends BaseIntegrationTest {
+
+ private static final String TESTING_ID = "___TESTING___";
+ private static final String AAI_VNF_ID = "test";
+ private static final String AAI_VF_MODULE_ID = "test";
+ private static final String REST_ENDPOINT = "/services/rest/v1/vnfs";
+
+ private VnfAdapterClientImpl client = new VnfAdapterClientImpl();
+ private ObjectMapper mapper = new JettisonStyleMapperProvider().getMapper();
+
+ @BeforeClass
+ public static void setUp() {
+ System.setProperty("mso.config.path", "src/test/resources");
+ }
+
+ @Test
+ public void createVfModuleTest() throws JsonProcessingException, VnfAdapterClientException {
+ CreateVfModuleRequest request = new CreateVfModuleRequest();
+ request.setCloudSiteId(TESTING_ID);
+
+ CreateVfModuleResponse mockResponse = new CreateVfModuleResponse();
+ mockResponse.setVfModuleCreated(true);
+ wireMockServer.stubFor(post(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
+
+ CreateVfModuleResponse response = client.createVfModule(AAI_VNF_ID, request);
+ assertEquals("Testing CreateVfModule response", true, response.getVfModuleCreated());
+ }
+
+ @Test(expected = VnfAdapterClientException.class)
+ public void createVfModuleTestThrowException() throws JsonProcessingException, VnfAdapterClientException {
+ CreateVfModuleRequest request = new CreateVfModuleRequest();
+ request.setCloudSiteId(TESTING_ID);
+
+ VfModuleExceptionResponse mockResponse = new VfModuleExceptionResponse();
+ mockResponse.setMessage("Error in create Vf module");
+ wireMockServer.stubFor(post(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
+
+ client.createVfModule(AAI_VNF_ID, request);
+ }
+
+ @Test
+ public void rollbackVfModuleTest() throws JsonProcessingException, VnfAdapterClientException {
+ RollbackVfModuleRequest request = new RollbackVfModuleRequest();
+ VfModuleRollback rollback = new VfModuleRollback();
+ rollback.setCloudSiteId(TESTING_ID);
+ request.setVfModuleRollback(rollback);
+
+ RollbackVfModuleResponse mockResponse = new RollbackVfModuleResponse();
+ mockResponse.setVfModuleRolledback(true);
+ wireMockServer.stubFor(delete(
+ urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID + "/rollback"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
+
+ RollbackVfModuleResponse response = client.rollbackVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, request);
+ assertEquals("Testing RollbackVfModule response", true, response.getVfModuleRolledback());
+ }
+
+ @Test(expected = VnfAdapterClientException.class)
+ public void rollbackVfModuleTestThrowException() throws JsonProcessingException, VnfAdapterClientException {
+ RollbackVfModuleRequest request = new RollbackVfModuleRequest();
+ VfModuleRollback rollback = new VfModuleRollback();
+ rollback.setCloudSiteId(TESTING_ID);
+ request.setVfModuleRollback(rollback);
+
+ VfModuleExceptionResponse mockResponse = new VfModuleExceptionResponse();
+ mockResponse.setMessage("Error in rollback Vf module");
+ wireMockServer.stubFor(delete(
+ urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID + "/rollback"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
+
+ client.rollbackVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, request);
+ }
+
+ @Test
+ public void deleteVfModuleTest() throws JsonProcessingException, VnfAdapterClientException {
+ DeleteVfModuleRequest request = new DeleteVfModuleRequest();
+ request.setCloudSiteId(TESTING_ID);
+
+ DeleteVfModuleResponse mockResponse = new DeleteVfModuleResponse();
+ mockResponse.setVfModuleDeleted(true);
+ wireMockServer
+ .stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
+
+ DeleteVfModuleResponse response = client.deleteVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, request);
+ assertEquals("Testing DeleteVfModule response", true, response.getVfModuleDeleted());
+ }
+
+ @Test(expected = VnfAdapterClientException.class)
+ public void deleteVfModuleTestThrowException() throws JsonProcessingException, VnfAdapterClientException {
+ DeleteVfModuleRequest request = new DeleteVfModuleRequest();
+ request.setCloudSiteId(TESTING_ID);
+
+ VfModuleExceptionResponse mockResponse = new VfModuleExceptionResponse();
+ mockResponse.setMessage("Error in delete Vf module");
+ wireMockServer
+ .stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
+
+ client.deleteVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, request);
+ }
+
+ @Test
+ public void updateVfModuleTest() throws JsonProcessingException, VnfAdapterClientException {
+ UpdateVfModuleRequest request = new UpdateVfModuleRequest();
+ request.setCloudSiteId(TESTING_ID);
+ request.setVfModuleId("test1");
+
+ UpdateVfModuleResponse mockResponse = new UpdateVfModuleResponse();
+ mockResponse.setVfModuleId("test1");
+ wireMockServer.stubFor(put(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
+
+ UpdateVfModuleResponse response = client.updateVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, request);
+ assertEquals("Testing UpdateVfModule response", "test1", response.getVfModuleId());
+ }
+
+ @Test(expected = VnfAdapterClientException.class)
+ public void updateVfModuleTestThrowException() throws JsonProcessingException, VnfAdapterClientException {
+ UpdateVfModuleRequest request = new UpdateVfModuleRequest();
+ request.setCloudSiteId(TESTING_ID);
+ request.setVfModuleId("test1");
+
+ VfModuleExceptionResponse mockResponse = new VfModuleExceptionResponse();
+ mockResponse.setMessage("Error in update Vf module");
+ wireMockServer.stubFor(put(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
+
+ client.updateVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, request);
+ }
+
+ @Test
+ public void queryVfModuleTest() throws JsonProcessingException, VnfAdapterClientException {
+ QueryVfModuleResponse mockResponse = new QueryVfModuleResponse();
+ mockResponse.setVnfId(AAI_VNF_ID);
+ mockResponse.setVfModuleId(AAI_VF_MODULE_ID);
+ wireMockServer.stubFor(get(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID))
+ .withQueryParam("cloudSiteId", equalTo(TESTING_ID)).withQueryParam("tenantId", equalTo(TESTING_ID))
+ .withQueryParam("vfModuleName", equalTo("someName")).withQueryParam("skipAAI", equalTo("true"))
+ .withQueryParam("msoRequest.requestId", equalTo("testRequestId"))
+ .withQueryParam("msoRequest.serviceInstanceId", equalTo("serviceInstanceId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200)));
+ QueryVfModuleResponse response = client.queryVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, TESTING_ID, TESTING_ID,
+ "someName", true, "testRequestId", "serviceInstanceId");
+ assertEquals("Testing QueryVfModule response", AAI_VF_MODULE_ID, response.getVfModuleId());
+ }
+
+ @Test(expected = VnfAdapterClientException.class)
+ public void queryVfModuleTestThrowException() throws JsonProcessingException, VnfAdapterClientException {
+ VfModuleExceptionResponse mockResponse = new VfModuleExceptionResponse();
+ mockResponse.setMessage("Error in update Vf module");
+ wireMockServer.stubFor(get(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID))
+ .withQueryParam("cloudSiteId", equalTo(TESTING_ID)).withQueryParam("tenantId", equalTo(TESTING_ID))
+ .withQueryParam("vfModuleName", equalTo("someName")).withQueryParam("skipAAI", equalTo("true"))
+ .withQueryParam("msoRequest.requestId", equalTo("testRequestId"))
+ .withQueryParam("msoRequest.serviceInstanceId", equalTo("serviceInstanceId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500)));
+ client.queryVfModule(AAI_VNF_ID, AAI_VF_MODULE_ID, TESTING_ID, TESTING_ID, "someName", true, "testRequestId",
+ "serviceInstanceId");
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientIT.java
index 4a006f8b66..282d7a04f9 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientIT.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientIT.java
@@ -25,10 +25,8 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.core.UriBuilder;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
@@ -44,169 +42,170 @@ import org.onap.so.adapters.vnfrest.UpdateVolumeGroupResponse;
import org.onap.so.client.adapter.rest.AdapterRestClient;
import org.onap.so.BaseIntegrationTest;
-public class VnfVolumeAdapterClientIT extends BaseIntegrationTest{
-
- private static final String TESTING_ID = "___TESTING___";
- private static final String AAI_VOLUME_GROUP_ID = "test";
- private static final String CLOUD_SITE_ID = "test";
- private static final String TENANT_ID = "test";
- private static final String VOLUME_GROUP_STACK_ID = "test";
- private static final boolean SKIP_AAI = true;
- private static final String REQUEST_ID = "test";
- private static final String SERVICE_INSTANCE_ID = "test";
-
- @Test
- public void createVolumeGroupTest() throws VnfAdapterClientException {
- CreateVolumeGroupRequest request = new CreateVolumeGroupRequest();
- request.setCloudSiteId(TESTING_ID);
-
- CreateVolumeGroupResponse mockResponse = new CreateVolumeGroupResponse();
- mockResponse.setVolumeGroupCreated(true);
-
- VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
- AdapterRestClient mockClient = mock(AdapterRestClient.class);
-
- doReturn(mockClient).when(client).getAdapterRestClient("");
- when(mockClient.post(request, CreateVolumeGroupResponse.class)).thenReturn(mockResponse);
-
- CreateVolumeGroupResponse response = client.createVNFVolumes(request);
- assertEquals("Testing CreateVolumeGroup response", mockResponse.getVolumeGroupCreated(),
- response.getVolumeGroupCreated());
- }
-
- @Test(expected = VnfAdapterClientException.class)
- public void createVolumeGroupTestThrowException() throws VnfAdapterClientException {
- CreateVolumeGroupRequest request = new CreateVolumeGroupRequest();
- request.setCloudSiteId(TESTING_ID);
-
- CreateVolumeGroupResponse mockResponse = new CreateVolumeGroupResponse();
- mockResponse.setVolumeGroupCreated(true);
-
- VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
- AdapterRestClient mockClient = mock(AdapterRestClient.class);
-
- doReturn(mockClient).when(client).getAdapterRestClient("");
- when(mockClient.post(request, CreateVolumeGroupResponse.class)).thenThrow(new InternalServerErrorException("Error in create volume group"));
-
- client.createVNFVolumes(request);
- }
-
- @Test
- public void deleteVolumeGroupTest() throws VnfAdapterClientException {
- DeleteVolumeGroupRequest request = new DeleteVolumeGroupRequest();
- request.setCloudSiteId(TESTING_ID);
-
- DeleteVolumeGroupResponse mockResponse = new DeleteVolumeGroupResponse();
- mockResponse.setVolumeGroupDeleted(true);
-
- VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
- AdapterRestClient mockClient = mock(AdapterRestClient.class);
- doReturn(mockClient).when(client).getAdapterRestClient("/" + AAI_VOLUME_GROUP_ID);
- when(mockClient.delete(request, DeleteVolumeGroupResponse.class)).thenReturn(mockResponse);
- MockitoAnnotations.initMocks(this);
-
- DeleteVolumeGroupResponse response = client.deleteVNFVolumes(AAI_VOLUME_GROUP_ID, request);
- assertEquals("Testing DeleteVolumeGroup response", mockResponse.getVolumeGroupDeleted(),
- response.getVolumeGroupDeleted());
- }
-
- @Test(expected = VnfAdapterClientException.class)
- public void deleteVolumeGroupTestThrowException() throws VnfAdapterClientException {
- DeleteVolumeGroupRequest request = new DeleteVolumeGroupRequest();
- request.setCloudSiteId(TESTING_ID);
-
- DeleteVolumeGroupResponse mockResponse = new DeleteVolumeGroupResponse();
- mockResponse.setVolumeGroupDeleted(true);
-
- VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
- AdapterRestClient mockClient = mock(AdapterRestClient.class);
- doReturn(mockClient).when(client).getAdapterRestClient("/" + AAI_VOLUME_GROUP_ID);
- when(mockClient.delete(request, DeleteVolumeGroupResponse.class))
- .thenThrow(new InternalServerErrorException("Error in delete volume group"));
- MockitoAnnotations.initMocks(this);
-
- client.deleteVNFVolumes(AAI_VOLUME_GROUP_ID, request);
- }
-
- @Test
- public void rollbackVolumeGroupTest() throws VnfAdapterClientException {
- RollbackVolumeGroupRequest request = new RollbackVolumeGroupRequest();
-
- RollbackVolumeGroupResponse mockResponse = new RollbackVolumeGroupResponse();
- mockResponse.setVolumeGroupRolledBack(true);
-
- VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
- AdapterRestClient mockClient = mock(AdapterRestClient.class);
- doReturn(mockClient).when(client).getAdapterRestClient("/" + AAI_VOLUME_GROUP_ID + "/rollback");
- when(mockClient.delete(request, RollbackVolumeGroupResponse.class)).thenReturn(mockResponse);
- MockitoAnnotations.initMocks(this);
-
- RollbackVolumeGroupResponse response = client.rollbackVNFVolumes(AAI_VOLUME_GROUP_ID, request);
- assertEquals("Testing RollbackVolumeGroup response", mockResponse.getVolumeGroupRolledBack(),
- response.getVolumeGroupRolledBack());
- }
-
- @Test(expected = VnfAdapterClientException.class)
- public void rollbackVolumeGroupTestThrowException() throws VnfAdapterClientException {
- RollbackVolumeGroupRequest request = new RollbackVolumeGroupRequest();
-
- RollbackVolumeGroupResponse mockResponse = new RollbackVolumeGroupResponse();
- mockResponse.setVolumeGroupRolledBack(true);
-
- VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
- AdapterRestClient mockClient = mock(AdapterRestClient.class);
- doReturn(mockClient).when(client).getAdapterRestClient("/" + AAI_VOLUME_GROUP_ID + "/rollback");
- when(mockClient.delete(request, RollbackVolumeGroupResponse.class))
- .thenThrow(new InternalServerErrorException("Error in rollback volume group"));
- MockitoAnnotations.initMocks(this);
-
- client.rollbackVNFVolumes(AAI_VOLUME_GROUP_ID, request);
- }
-
- @Test
- public void updateVolumeGroupTest() throws VnfAdapterClientException {
- UpdateVolumeGroupRequest request = new UpdateVolumeGroupRequest();
-
- UpdateVolumeGroupResponse mockResponse = new UpdateVolumeGroupResponse();
- mockResponse.setVolumeGroupId(AAI_VOLUME_GROUP_ID);
-
- VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
- AdapterRestClient mockClient = mock(AdapterRestClient.class);
- doReturn(mockClient).when(client).getAdapterRestClient("/" + AAI_VOLUME_GROUP_ID);
- when(mockClient.put(request, UpdateVolumeGroupResponse.class)).thenReturn(mockResponse);
- MockitoAnnotations.initMocks(this);
-
- UpdateVolumeGroupResponse response = client.updateVNFVolumes(AAI_VOLUME_GROUP_ID, request);
- assertEquals("Testing DeleteVfModule response", mockResponse.getVolumeGroupId(), response.getVolumeGroupId());
- }
-
- @Test(expected = VnfAdapterClientException.class)
- public void updateVolumeGroupTestThrowException() throws VnfAdapterClientException {
- UpdateVolumeGroupRequest request = new UpdateVolumeGroupRequest();
-
- UpdateVolumeGroupResponse mockResponse = new UpdateVolumeGroupResponse();
- mockResponse.setVolumeGroupId(AAI_VOLUME_GROUP_ID);
-
- VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
- AdapterRestClient mockClient = mock(AdapterRestClient.class);
- doReturn(mockClient).when(client).getAdapterRestClient("/" + AAI_VOLUME_GROUP_ID);
- when(mockClient.put(request, UpdateVolumeGroupResponse.class))
- .thenThrow(new InternalServerErrorException("Error in update volume group"));
- MockitoAnnotations.initMocks(this);
-
- client.updateVNFVolumes(AAI_VOLUME_GROUP_ID, request);
- }
-
- public void buildQueryPathTest() {
- String expectedOutput = "/" + AAI_VOLUME_GROUP_ID + "?cloudSiteId=" + CLOUD_SITE_ID + "&tenantId=" + TENANT_ID
- + "&volumeGroupStackId=" + VOLUME_GROUP_STACK_ID + "&skipAAI=" + SKIP_AAI + "&msoRequest.requestId="
- + REQUEST_ID + "&msoRequest.serviceInstanceId=" + SERVICE_INSTANCE_ID;
- VnfVolumeAdapterClientImpl client = new VnfVolumeAdapterClientImpl();
- assertEquals("Test build query path", expectedOutput, client.buildQueryPath(AAI_VOLUME_GROUP_ID, CLOUD_SITE_ID,
- TENANT_ID, VOLUME_GROUP_STACK_ID, SKIP_AAI, REQUEST_ID, SERVICE_INSTANCE_ID));
- }
-
- protected UriBuilder getUri(String path) {
- return UriBuilder.fromPath(path);
- }
+public class VnfVolumeAdapterClientIT extends BaseIntegrationTest {
+
+ private static final String TESTING_ID = "___TESTING___";
+ private static final String AAI_VOLUME_GROUP_ID = "test";
+ private static final String CLOUD_SITE_ID = "test";
+ private static final String TENANT_ID = "test";
+ private static final String VOLUME_GROUP_STACK_ID = "test";
+ private static final boolean SKIP_AAI = true;
+ private static final String REQUEST_ID = "test";
+ private static final String SERVICE_INSTANCE_ID = "test";
+
+ @Test
+ public void createVolumeGroupTest() throws VnfAdapterClientException {
+ CreateVolumeGroupRequest request = new CreateVolumeGroupRequest();
+ request.setCloudSiteId(TESTING_ID);
+
+ CreateVolumeGroupResponse mockResponse = new CreateVolumeGroupResponse();
+ mockResponse.setVolumeGroupCreated(true);
+
+ VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
+ AdapterRestClient mockClient = mock(AdapterRestClient.class);
+
+ doReturn(mockClient).when(client).getAdapterRestClient("");
+ when(mockClient.post(request, CreateVolumeGroupResponse.class)).thenReturn(mockResponse);
+
+ CreateVolumeGroupResponse response = client.createVNFVolumes(request);
+ assertEquals("Testing CreateVolumeGroup response", mockResponse.getVolumeGroupCreated(),
+ response.getVolumeGroupCreated());
+ }
+
+ @Test(expected = VnfAdapterClientException.class)
+ public void createVolumeGroupTestThrowException() throws VnfAdapterClientException {
+ CreateVolumeGroupRequest request = new CreateVolumeGroupRequest();
+ request.setCloudSiteId(TESTING_ID);
+
+ CreateVolumeGroupResponse mockResponse = new CreateVolumeGroupResponse();
+ mockResponse.setVolumeGroupCreated(true);
+
+ VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
+ AdapterRestClient mockClient = mock(AdapterRestClient.class);
+
+ doReturn(mockClient).when(client).getAdapterRestClient("");
+ when(mockClient.post(request, CreateVolumeGroupResponse.class))
+ .thenThrow(new InternalServerErrorException("Error in create volume group"));
+
+ client.createVNFVolumes(request);
+ }
+
+ @Test
+ public void deleteVolumeGroupTest() throws VnfAdapterClientException {
+ DeleteVolumeGroupRequest request = new DeleteVolumeGroupRequest();
+ request.setCloudSiteId(TESTING_ID);
+
+ DeleteVolumeGroupResponse mockResponse = new DeleteVolumeGroupResponse();
+ mockResponse.setVolumeGroupDeleted(true);
+
+ VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
+ AdapterRestClient mockClient = mock(AdapterRestClient.class);
+ doReturn(mockClient).when(client).getAdapterRestClient("/" + AAI_VOLUME_GROUP_ID);
+ when(mockClient.delete(request, DeleteVolumeGroupResponse.class)).thenReturn(mockResponse);
+ MockitoAnnotations.initMocks(this);
+
+ DeleteVolumeGroupResponse response = client.deleteVNFVolumes(AAI_VOLUME_GROUP_ID, request);
+ assertEquals("Testing DeleteVolumeGroup response", mockResponse.getVolumeGroupDeleted(),
+ response.getVolumeGroupDeleted());
+ }
+
+ @Test(expected = VnfAdapterClientException.class)
+ public void deleteVolumeGroupTestThrowException() throws VnfAdapterClientException {
+ DeleteVolumeGroupRequest request = new DeleteVolumeGroupRequest();
+ request.setCloudSiteId(TESTING_ID);
+
+ DeleteVolumeGroupResponse mockResponse = new DeleteVolumeGroupResponse();
+ mockResponse.setVolumeGroupDeleted(true);
+
+ VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
+ AdapterRestClient mockClient = mock(AdapterRestClient.class);
+ doReturn(mockClient).when(client).getAdapterRestClient("/" + AAI_VOLUME_GROUP_ID);
+ when(mockClient.delete(request, DeleteVolumeGroupResponse.class))
+ .thenThrow(new InternalServerErrorException("Error in delete volume group"));
+ MockitoAnnotations.initMocks(this);
+
+ client.deleteVNFVolumes(AAI_VOLUME_GROUP_ID, request);
+ }
+
+ @Test
+ public void rollbackVolumeGroupTest() throws VnfAdapterClientException {
+ RollbackVolumeGroupRequest request = new RollbackVolumeGroupRequest();
+
+ RollbackVolumeGroupResponse mockResponse = new RollbackVolumeGroupResponse();
+ mockResponse.setVolumeGroupRolledBack(true);
+
+ VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
+ AdapterRestClient mockClient = mock(AdapterRestClient.class);
+ doReturn(mockClient).when(client).getAdapterRestClient("/" + AAI_VOLUME_GROUP_ID + "/rollback");
+ when(mockClient.delete(request, RollbackVolumeGroupResponse.class)).thenReturn(mockResponse);
+ MockitoAnnotations.initMocks(this);
+
+ RollbackVolumeGroupResponse response = client.rollbackVNFVolumes(AAI_VOLUME_GROUP_ID, request);
+ assertEquals("Testing RollbackVolumeGroup response", mockResponse.getVolumeGroupRolledBack(),
+ response.getVolumeGroupRolledBack());
+ }
+
+ @Test(expected = VnfAdapterClientException.class)
+ public void rollbackVolumeGroupTestThrowException() throws VnfAdapterClientException {
+ RollbackVolumeGroupRequest request = new RollbackVolumeGroupRequest();
+
+ RollbackVolumeGroupResponse mockResponse = new RollbackVolumeGroupResponse();
+ mockResponse.setVolumeGroupRolledBack(true);
+
+ VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
+ AdapterRestClient mockClient = mock(AdapterRestClient.class);
+ doReturn(mockClient).when(client).getAdapterRestClient("/" + AAI_VOLUME_GROUP_ID + "/rollback");
+ when(mockClient.delete(request, RollbackVolumeGroupResponse.class))
+ .thenThrow(new InternalServerErrorException("Error in rollback volume group"));
+ MockitoAnnotations.initMocks(this);
+
+ client.rollbackVNFVolumes(AAI_VOLUME_GROUP_ID, request);
+ }
+
+ @Test
+ public void updateVolumeGroupTest() throws VnfAdapterClientException {
+ UpdateVolumeGroupRequest request = new UpdateVolumeGroupRequest();
+
+ UpdateVolumeGroupResponse mockResponse = new UpdateVolumeGroupResponse();
+ mockResponse.setVolumeGroupId(AAI_VOLUME_GROUP_ID);
+
+ VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
+ AdapterRestClient mockClient = mock(AdapterRestClient.class);
+ doReturn(mockClient).when(client).getAdapterRestClient("/" + AAI_VOLUME_GROUP_ID);
+ when(mockClient.put(request, UpdateVolumeGroupResponse.class)).thenReturn(mockResponse);
+ MockitoAnnotations.initMocks(this);
+
+ UpdateVolumeGroupResponse response = client.updateVNFVolumes(AAI_VOLUME_GROUP_ID, request);
+ assertEquals("Testing DeleteVfModule response", mockResponse.getVolumeGroupId(), response.getVolumeGroupId());
+ }
+
+ @Test(expected = VnfAdapterClientException.class)
+ public void updateVolumeGroupTestThrowException() throws VnfAdapterClientException {
+ UpdateVolumeGroupRequest request = new UpdateVolumeGroupRequest();
+
+ UpdateVolumeGroupResponse mockResponse = new UpdateVolumeGroupResponse();
+ mockResponse.setVolumeGroupId(AAI_VOLUME_GROUP_ID);
+
+ VnfVolumeAdapterClientImpl client = spy(VnfVolumeAdapterClientImpl.class);
+ AdapterRestClient mockClient = mock(AdapterRestClient.class);
+ doReturn(mockClient).when(client).getAdapterRestClient("/" + AAI_VOLUME_GROUP_ID);
+ when(mockClient.put(request, UpdateVolumeGroupResponse.class))
+ .thenThrow(new InternalServerErrorException("Error in update volume group"));
+ MockitoAnnotations.initMocks(this);
+
+ client.updateVNFVolumes(AAI_VOLUME_GROUP_ID, request);
+ }
+
+ public void buildQueryPathTest() {
+ String expectedOutput = "/" + AAI_VOLUME_GROUP_ID + "?cloudSiteId=" + CLOUD_SITE_ID + "&tenantId=" + TENANT_ID
+ + "&volumeGroupStackId=" + VOLUME_GROUP_STACK_ID + "&skipAAI=" + SKIP_AAI + "&msoRequest.requestId="
+ + REQUEST_ID + "&msoRequest.serviceInstanceId=" + SERVICE_INSTANCE_ID;
+ VnfVolumeAdapterClientImpl client = new VnfVolumeAdapterClientImpl();
+ assertEquals("Test build query path", expectedOutput, client.buildQueryPath(AAI_VOLUME_GROUP_ID, CLOUD_SITE_ID,
+ TENANT_ID, VOLUME_GROUP_STACK_ID, SKIP_AAI, REQUEST_ID, SERVICE_INSTANCE_ID));
+ }
+
+ protected UriBuilder getUri(String path) {
+ return UriBuilder.fromPath(path);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterRestPropertiesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterRestPropertiesTest.java
index df48596893..63c73322a5 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterRestPropertiesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterRestPropertiesTest.java
@@ -21,26 +21,24 @@
package org.onap.so.client.adapter.vnf;
import static org.junit.Assert.assertEquals;
-
import java.net.MalformedURLException;
-
import org.junit.Test;
-public class VnfVolumeAdapterRestPropertiesTest{
- private VnfVolumeAdapterRestProperties props = new VnfVolumeAdapterRestProperties();
-
- @Test
- public void testGetAuth(){
- assertEquals("mso.adapters.po.auth", VnfVolumeAdapterRestProperties.authProp);
- }
-
- @Test
- public void testGetKey(){
- assertEquals("mso.msoKey", VnfVolumeAdapterRestProperties.keyProp);
- }
-
- @Test
- public void testGetUrl() throws MalformedURLException{
- assertEquals("mso.adapters.volume-groups.rest.endpoint", VnfVolumeAdapterRestProperties.endpointProp);
- }
+public class VnfVolumeAdapterRestPropertiesTest {
+ private VnfVolumeAdapterRestProperties props = new VnfVolumeAdapterRestProperties();
+
+ @Test
+ public void testGetAuth() {
+ assertEquals("mso.adapters.po.auth", VnfVolumeAdapterRestProperties.authProp);
+ }
+
+ @Test
+ public void testGetKey() {
+ assertEquals("mso.msoKey", VnfVolumeAdapterRestProperties.keyProp);
+ }
+
+ @Test
+ public void testGetUrl() throws MalformedURLException {
+ assertEquals("mso.adapters.volume-groups.rest.endpoint", VnfVolumeAdapterRestProperties.endpointProp);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java
index 5169663add..4450e4a9f4 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java
@@ -26,14 +26,12 @@ import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.reset;
-
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
@@ -55,282 +53,294 @@ import org.onap.so.db.catalog.beans.OrchestrationStatus;
import org.onap.so.entity.MsoRequest;
public class VnfAdapterObjectMapperTest {
- private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/";
-
- @Spy
- private VnfAdapterObjectMapper vnfAdapterObjectMapper = new VnfAdapterObjectMapper();
-
- @Before
- public void before() {
- MockitoAnnotations.initMocks(this);
-
- }
-
- @After
- public void after() {
- reset(vnfAdapterObjectMapper);
- }
-
- @Test
- public void test_createVolumeGroupRequestMapper() throws Exception {
- RequestContext requestContext = new RequestContext();
- requestContext.setMsoRequestId("msoRequestId");
-
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
-
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelVersion("modelVersion");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId("vnfId");
- genericVnf.setVnfName("vnfName");
- genericVnf.setVnfType("vnfType");
- serviceInstance.getVnfs().add(genericVnf);
-
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelName("modelName");
- modelInfoVfModule.setModelCustomizationUUID("modelCustomizationUUID");
-
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("volumeGroupId");
- volumeGroup.setVolumeGroupName("volumeGroupName");
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
- volumeGroup.setModelInfoVfModule(modelInfoVfModule);
-
- serviceInstance.getVnfs().get(0).getVolumeGroups().add(volumeGroup);
-
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("lcpCloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
-
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
-
- CreateVolumeGroupRequest expectedCreateVolumeGroupRequest = new CreateVolumeGroupRequest();
-
- expectedCreateVolumeGroupRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
- expectedCreateVolumeGroupRequest.setTenantId(cloudRegion.getTenantId());
- expectedCreateVolumeGroupRequest.setVolumeGroupId(volumeGroup.getVolumeGroupId());
- expectedCreateVolumeGroupRequest.setVolumeGroupName(volumeGroup.getVolumeGroupName());
- expectedCreateVolumeGroupRequest.setVnfType(genericVnf.getVnfType());
- expectedCreateVolumeGroupRequest.setVnfVersion(serviceInstance.getModelInfoServiceInstance().getModelVersion());
- expectedCreateVolumeGroupRequest.setVfModuleType(volumeGroup.getModelInfoVfModule().getModelName());
- expectedCreateVolumeGroupRequest.setModelCustomizationUuid(volumeGroup.getModelInfoVfModule().getModelCustomizationUUID());
-
- Map<String, Object> volumeGroupParams = new HashMap<>();
- volumeGroupParams.put("vnf_id", genericVnf.getVnfId());
- volumeGroupParams.put("vnf_name", genericVnf.getVnfName());
- volumeGroupParams.put("vf_module_id", volumeGroup.getVolumeGroupId());
- volumeGroupParams.put("vf_module_name", volumeGroup.getVolumeGroupName());
- volumeGroupParams.put("paramOne", "paramOneValue");
- volumeGroupParams.put("paramTwo", "paramTwoValue");
- volumeGroupParams.put("paramThree", "paramThreeValue");
- expectedCreateVolumeGroupRequest.setVolumeGroupParams(volumeGroupParams);
-
- expectedCreateVolumeGroupRequest.setSkipAAI(true);
- expectedCreateVolumeGroupRequest.setSuppressBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
- expectedCreateVolumeGroupRequest.setFailIfExists(true);
-
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId(requestContext.getMsoRequestId());
- msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- expectedCreateVolumeGroupRequest.setMsoRequest(msoRequest);
-
- expectedCreateVolumeGroupRequest.setMessageId("messageId");
- expectedCreateVolumeGroupRequest.setNotificationUrl("endpoint/VNFAResponse/messageId");
-
- doReturn("endpoint/").when(vnfAdapterObjectMapper).getProperty(isA(String.class));
- doReturn("messageId").when(vnfAdapterObjectMapper).getRandomUuid();
-
- CreateVolumeGroupRequest actualCreateVolumeGroupRequest = vnfAdapterObjectMapper.createVolumeGroupRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse);
-
- assertThat(actualCreateVolumeGroupRequest, sameBeanAs(expectedCreateVolumeGroupRequest));
- }
-
- @Test
- public void test_createVolumeGroupRequestMapper_for_alaCarte_flow() throws Exception {
- RequestContext requestContext = new RequestContext();
- requestContext.setMsoRequestId("msoRequestId");
-
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
-
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelVersion("modelVersion");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId("vnfId");
- genericVnf.setVnfName("vnfName");
- genericVnf.setVnfType("vnfType");
- serviceInstance.getVnfs().add(genericVnf);
-
-
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelName("modelName");
- modelInfoVfModule.setModelCustomizationUUID("modelCustomizationUUID");
-
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("volumeGroupId");
- volumeGroup.setVolumeGroupName("volumeGroupName");
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
- volumeGroup.setModelInfoVfModule(modelInfoVfModule);
- serviceInstance.getVnfs().get(0).getVolumeGroups().add(volumeGroup);
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("lcpCloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
-
- CreateVolumeGroupRequest expectedCreateVolumeGroupRequest = new CreateVolumeGroupRequest();
-
- expectedCreateVolumeGroupRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
- expectedCreateVolumeGroupRequest.setTenantId(cloudRegion.getTenantId());
- expectedCreateVolumeGroupRequest.setVolumeGroupId(volumeGroup.getVolumeGroupId());
- expectedCreateVolumeGroupRequest.setVolumeGroupName(volumeGroup.getVolumeGroupName());
- expectedCreateVolumeGroupRequest.setVnfType(genericVnf.getVnfType());
- expectedCreateVolumeGroupRequest.setVnfVersion(serviceInstance.getModelInfoServiceInstance().getModelVersion());
- expectedCreateVolumeGroupRequest.setVfModuleType(volumeGroup.getModelInfoVfModule().getModelName());
- expectedCreateVolumeGroupRequest.setModelCustomizationUuid(volumeGroup.getModelInfoVfModule().getModelCustomizationUUID());
-
- Map<String, Object> volumeGroupParams = new HashMap<>();
- volumeGroupParams.put("vnf_id", genericVnf.getVnfId());
- volumeGroupParams.put("vnf_name", genericVnf.getVnfName());
- volumeGroupParams.put("vf_module_id", volumeGroup.getVolumeGroupId());
- volumeGroupParams.put("vf_module_name", volumeGroup.getVolumeGroupName());
-
- expectedCreateVolumeGroupRequest.setVolumeGroupParams(volumeGroupParams);
-
- expectedCreateVolumeGroupRequest.setSkipAAI(true);
- expectedCreateVolumeGroupRequest.setSuppressBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
- expectedCreateVolumeGroupRequest.setFailIfExists(true);
-
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId(requestContext.getMsoRequestId());
- msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- expectedCreateVolumeGroupRequest.setMsoRequest(msoRequest);
-
- expectedCreateVolumeGroupRequest.setMessageId("messageId");
- expectedCreateVolumeGroupRequest.setNotificationUrl("endpoint/VNFAResponse/messageId");
-
- doReturn("endpoint/").when(vnfAdapterObjectMapper).getProperty(isA(String.class));
- doReturn("messageId").when(vnfAdapterObjectMapper).getRandomUuid();
-
- CreateVolumeGroupRequest actualCreateVolumeGroupRequest = vnfAdapterObjectMapper.createVolumeGroupRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, null);
-
- assertThat(actualCreateVolumeGroupRequest, sameBeanAs(expectedCreateVolumeGroupRequest));
- }
-
- @Test
- public void test_deleteVolumeGroupHeatIdRequestMapper() throws Exception{
- this.test_deleteVolumeGroupRequestMapper("heatStackId");
- }
-
- @Test
- public void test_deleteVolumeGroupNoHeatIdRequestMapper() throws Exception{
- this.test_deleteVolumeGroupRequestMapper(null);
- }
-
- private void test_deleteVolumeGroupRequestMapper(String heatStackId) throws Exception {
- DeleteVolumeGroupRequest expectedDeleteVolumeGroupRequest = new DeleteVolumeGroupRequest();
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("lcpCloudRegionId");
- expectedDeleteVolumeGroupRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
-
- cloudRegion.setTenantId("tenantId");
- expectedDeleteVolumeGroupRequest.setTenantId(cloudRegion.getTenantId());
-
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("volumeGroupId");
- expectedDeleteVolumeGroupRequest.setVolumeGroupId(volumeGroup.getVolumeGroupId());
-
- if (heatStackId != null){
- volumeGroup.setHeatStackId("heatStackId");
- expectedDeleteVolumeGroupRequest.setVolumeGroupStackId(volumeGroup.getHeatStackId());
- } else {
- volumeGroup.setVolumeGroupName("volumeGroupName");
- expectedDeleteVolumeGroupRequest.setVolumeGroupStackId(volumeGroup.getVolumeGroupName());
- }
-
- expectedDeleteVolumeGroupRequest.setSkipAAI(true);
-
- MsoRequest msoRequest = new MsoRequest();
- RequestContext requestContext = new RequestContext();
- requestContext.setMsoRequestId("msoRequestId");
- msoRequest.setRequestId(requestContext.getMsoRequestId());
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- expectedDeleteVolumeGroupRequest.setMsoRequest(msoRequest);
-
- String messageId = "messageId";
- String endpoint = "endpoint";
- doReturn(messageId).when(vnfAdapterObjectMapper).getRandomUuid();
- doReturn(endpoint).when(vnfAdapterObjectMapper).getProperty(isA(String.class));
- expectedDeleteVolumeGroupRequest.setMessageId(messageId);
- expectedDeleteVolumeGroupRequest.setNotificationUrl(endpoint + "/VNFAResponse/" + messageId);
-
- DeleteVolumeGroupRequest actualDeleteVolumeGroupRequest = vnfAdapterObjectMapper.deleteVolumeGroupRequestMapper(requestContext, cloudRegion, serviceInstance, volumeGroup);
-
- assertThat(actualDeleteVolumeGroupRequest, sameBeanAs(expectedDeleteVolumeGroupRequest));
- }
-
- @Test
- public void test_createVolumeGroupParams() throws Exception {
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId("vnfId");
- genericVnf.setVnfName("vnfName");
-
- RequestContext requestContext = new RequestContext();
-
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("volumeGroupId");
- volumeGroup.setVolumeGroupName("volumeGroupName");
-
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
-
- Map<String, String> expectedVolumeGroupParams = new HashMap<>();
- expectedVolumeGroupParams.put("vnf_id", genericVnf.getVnfId());
- expectedVolumeGroupParams.put("vnf_name", genericVnf.getVnfName());
- expectedVolumeGroupParams.put("vf_module_id", volumeGroup.getVolumeGroupId());
- expectedVolumeGroupParams.put("vf_module_name", volumeGroup.getVolumeGroupName());
- expectedVolumeGroupParams.put("paramOne", "paramOneValue");
- expectedVolumeGroupParams.put("paramTwo", "paramTwoValue");
- expectedVolumeGroupParams.put("paramThree", "paramThreeValue");
-
- Map<String, Object> actualVolumeGroupParams = vnfAdapterObjectMapper.createVolumeGroupParams(requestContext,genericVnf, volumeGroup, sdncVfModuleQueryResponse);
-
- assertEquals(expectedVolumeGroupParams, actualVolumeGroupParams);
- }
-
- @Test
- public void test_createVolumeGroupParams_without_sdncResponse() throws Exception {
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId("vnfId");
- genericVnf.setVnfName("vnfName");
-
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("volumeGroupId");
- volumeGroup.setVolumeGroupName("volumeGroupName");
-
- Map<String, String> expectedVolumeGroupParams = new HashMap<>();
- expectedVolumeGroupParams.put("vnf_id", genericVnf.getVnfId());
- expectedVolumeGroupParams.put("vnf_name", genericVnf.getVnfName());
- expectedVolumeGroupParams.put("vf_module_id", volumeGroup.getVolumeGroupId());
- expectedVolumeGroupParams.put("vf_module_name", volumeGroup.getVolumeGroupName());
- RequestContext requestContext = new RequestContext();
- Map<String, Object> actualVolumeGroupParams = vnfAdapterObjectMapper.createVolumeGroupParams(requestContext,genericVnf, volumeGroup, null);
-
- assertEquals(expectedVolumeGroupParams, actualVolumeGroupParams);
- }
+ private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/";
+
+ @Spy
+ private VnfAdapterObjectMapper vnfAdapterObjectMapper = new VnfAdapterObjectMapper();
+
+ @Before
+ public void before() {
+ MockitoAnnotations.initMocks(this);
+
+ }
+
+ @After
+ public void after() {
+ reset(vnfAdapterObjectMapper);
+ }
+
+ @Test
+ public void test_createVolumeGroupRequestMapper() throws Exception {
+ RequestContext requestContext = new RequestContext();
+ requestContext.setMsoRequestId("msoRequestId");
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelVersion("modelVersion");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId("vnfId");
+ genericVnf.setVnfName("vnfName");
+ genericVnf.setVnfType("vnfType");
+ serviceInstance.getVnfs().add(genericVnf);
+
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelName("modelName");
+ modelInfoVfModule.setModelCustomizationUUID("modelCustomizationUUID");
+
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("volumeGroupId");
+ volumeGroup.setVolumeGroupName("volumeGroupName");
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+ volumeGroup.setModelInfoVfModule(modelInfoVfModule);
+
+ serviceInstance.getVnfs().get(0).getVolumeGroups().add(volumeGroup);
+
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("lcpCloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+
+ String sdncVfModuleQueryResponse = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
+
+ CreateVolumeGroupRequest expectedCreateVolumeGroupRequest = new CreateVolumeGroupRequest();
+
+ expectedCreateVolumeGroupRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+ expectedCreateVolumeGroupRequest.setTenantId(cloudRegion.getTenantId());
+ expectedCreateVolumeGroupRequest.setVolumeGroupId(volumeGroup.getVolumeGroupId());
+ expectedCreateVolumeGroupRequest.setVolumeGroupName(volumeGroup.getVolumeGroupName());
+ expectedCreateVolumeGroupRequest.setVnfType(genericVnf.getVnfType());
+ expectedCreateVolumeGroupRequest.setVnfVersion(serviceInstance.getModelInfoServiceInstance().getModelVersion());
+ expectedCreateVolumeGroupRequest.setVfModuleType(volumeGroup.getModelInfoVfModule().getModelName());
+ expectedCreateVolumeGroupRequest
+ .setModelCustomizationUuid(volumeGroup.getModelInfoVfModule().getModelCustomizationUUID());
+
+ Map<String, Object> volumeGroupParams = new HashMap<>();
+ volumeGroupParams.put("vnf_id", genericVnf.getVnfId());
+ volumeGroupParams.put("vnf_name", genericVnf.getVnfName());
+ volumeGroupParams.put("vf_module_id", volumeGroup.getVolumeGroupId());
+ volumeGroupParams.put("vf_module_name", volumeGroup.getVolumeGroupName());
+ volumeGroupParams.put("paramOne", "paramOneValue");
+ volumeGroupParams.put("paramTwo", "paramTwoValue");
+ volumeGroupParams.put("paramThree", "paramThreeValue");
+ expectedCreateVolumeGroupRequest.setVolumeGroupParams(volumeGroupParams);
+
+ expectedCreateVolumeGroupRequest.setSkipAAI(true);
+ expectedCreateVolumeGroupRequest
+ .setSuppressBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
+ expectedCreateVolumeGroupRequest.setFailIfExists(true);
+
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId(requestContext.getMsoRequestId());
+ msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ expectedCreateVolumeGroupRequest.setMsoRequest(msoRequest);
+
+ expectedCreateVolumeGroupRequest.setMessageId("messageId");
+ expectedCreateVolumeGroupRequest.setNotificationUrl("endpoint/VNFAResponse/messageId");
+
+ doReturn("endpoint/").when(vnfAdapterObjectMapper).getProperty(isA(String.class));
+ doReturn("messageId").when(vnfAdapterObjectMapper).getRandomUuid();
+
+ CreateVolumeGroupRequest actualCreateVolumeGroupRequest =
+ vnfAdapterObjectMapper.createVolumeGroupRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse);
+
+ assertThat(actualCreateVolumeGroupRequest, sameBeanAs(expectedCreateVolumeGroupRequest));
+ }
+
+ @Test
+ public void test_createVolumeGroupRequestMapper_for_alaCarte_flow() throws Exception {
+ RequestContext requestContext = new RequestContext();
+ requestContext.setMsoRequestId("msoRequestId");
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelVersion("modelVersion");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId("vnfId");
+ genericVnf.setVnfName("vnfName");
+ genericVnf.setVnfType("vnfType");
+ serviceInstance.getVnfs().add(genericVnf);
+
+
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelName("modelName");
+ modelInfoVfModule.setModelCustomizationUUID("modelCustomizationUUID");
+
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("volumeGroupId");
+ volumeGroup.setVolumeGroupName("volumeGroupName");
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+ volumeGroup.setModelInfoVfModule(modelInfoVfModule);
+ serviceInstance.getVnfs().get(0).getVolumeGroups().add(volumeGroup);
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("lcpCloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+
+ CreateVolumeGroupRequest expectedCreateVolumeGroupRequest = new CreateVolumeGroupRequest();
+
+ expectedCreateVolumeGroupRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+ expectedCreateVolumeGroupRequest.setTenantId(cloudRegion.getTenantId());
+ expectedCreateVolumeGroupRequest.setVolumeGroupId(volumeGroup.getVolumeGroupId());
+ expectedCreateVolumeGroupRequest.setVolumeGroupName(volumeGroup.getVolumeGroupName());
+ expectedCreateVolumeGroupRequest.setVnfType(genericVnf.getVnfType());
+ expectedCreateVolumeGroupRequest.setVnfVersion(serviceInstance.getModelInfoServiceInstance().getModelVersion());
+ expectedCreateVolumeGroupRequest.setVfModuleType(volumeGroup.getModelInfoVfModule().getModelName());
+ expectedCreateVolumeGroupRequest
+ .setModelCustomizationUuid(volumeGroup.getModelInfoVfModule().getModelCustomizationUUID());
+
+ Map<String, Object> volumeGroupParams = new HashMap<>();
+ volumeGroupParams.put("vnf_id", genericVnf.getVnfId());
+ volumeGroupParams.put("vnf_name", genericVnf.getVnfName());
+ volumeGroupParams.put("vf_module_id", volumeGroup.getVolumeGroupId());
+ volumeGroupParams.put("vf_module_name", volumeGroup.getVolumeGroupName());
+
+ expectedCreateVolumeGroupRequest.setVolumeGroupParams(volumeGroupParams);
+
+ expectedCreateVolumeGroupRequest.setSkipAAI(true);
+ expectedCreateVolumeGroupRequest
+ .setSuppressBackout(Boolean.TRUE.equals(orchestrationContext.getIsRollbackEnabled()));
+ expectedCreateVolumeGroupRequest.setFailIfExists(true);
+
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId(requestContext.getMsoRequestId());
+ msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ expectedCreateVolumeGroupRequest.setMsoRequest(msoRequest);
+
+ expectedCreateVolumeGroupRequest.setMessageId("messageId");
+ expectedCreateVolumeGroupRequest.setNotificationUrl("endpoint/VNFAResponse/messageId");
+
+ doReturn("endpoint/").when(vnfAdapterObjectMapper).getProperty(isA(String.class));
+ doReturn("messageId").when(vnfAdapterObjectMapper).getRandomUuid();
+
+ CreateVolumeGroupRequest actualCreateVolumeGroupRequest = vnfAdapterObjectMapper.createVolumeGroupRequestMapper(
+ requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, null);
+
+ assertThat(actualCreateVolumeGroupRequest, sameBeanAs(expectedCreateVolumeGroupRequest));
+ }
+
+ @Test
+ public void test_deleteVolumeGroupHeatIdRequestMapper() throws Exception {
+ this.test_deleteVolumeGroupRequestMapper("heatStackId");
+ }
+
+ @Test
+ public void test_deleteVolumeGroupNoHeatIdRequestMapper() throws Exception {
+ this.test_deleteVolumeGroupRequestMapper(null);
+ }
+
+ private void test_deleteVolumeGroupRequestMapper(String heatStackId) throws Exception {
+ DeleteVolumeGroupRequest expectedDeleteVolumeGroupRequest = new DeleteVolumeGroupRequest();
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("lcpCloudRegionId");
+ expectedDeleteVolumeGroupRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+
+ cloudRegion.setTenantId("tenantId");
+ expectedDeleteVolumeGroupRequest.setTenantId(cloudRegion.getTenantId());
+
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("volumeGroupId");
+ expectedDeleteVolumeGroupRequest.setVolumeGroupId(volumeGroup.getVolumeGroupId());
+
+ if (heatStackId != null) {
+ volumeGroup.setHeatStackId("heatStackId");
+ expectedDeleteVolumeGroupRequest.setVolumeGroupStackId(volumeGroup.getHeatStackId());
+ } else {
+ volumeGroup.setVolumeGroupName("volumeGroupName");
+ expectedDeleteVolumeGroupRequest.setVolumeGroupStackId(volumeGroup.getVolumeGroupName());
+ }
+
+ expectedDeleteVolumeGroupRequest.setSkipAAI(true);
+
+ MsoRequest msoRequest = new MsoRequest();
+ RequestContext requestContext = new RequestContext();
+ requestContext.setMsoRequestId("msoRequestId");
+ msoRequest.setRequestId(requestContext.getMsoRequestId());
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ expectedDeleteVolumeGroupRequest.setMsoRequest(msoRequest);
+
+ String messageId = "messageId";
+ String endpoint = "endpoint";
+ doReturn(messageId).when(vnfAdapterObjectMapper).getRandomUuid();
+ doReturn(endpoint).when(vnfAdapterObjectMapper).getProperty(isA(String.class));
+ expectedDeleteVolumeGroupRequest.setMessageId(messageId);
+ expectedDeleteVolumeGroupRequest.setNotificationUrl(endpoint + "/VNFAResponse/" + messageId);
+
+ DeleteVolumeGroupRequest actualDeleteVolumeGroupRequest = vnfAdapterObjectMapper
+ .deleteVolumeGroupRequestMapper(requestContext, cloudRegion, serviceInstance, volumeGroup);
+
+ assertThat(actualDeleteVolumeGroupRequest, sameBeanAs(expectedDeleteVolumeGroupRequest));
+ }
+
+ @Test
+ public void test_createVolumeGroupParams() throws Exception {
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId("vnfId");
+ genericVnf.setVnfName("vnfName");
+
+ RequestContext requestContext = new RequestContext();
+
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("volumeGroupId");
+ volumeGroup.setVolumeGroupName("volumeGroupName");
+
+ String sdncVfModuleQueryResponse = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
+
+ Map<String, String> expectedVolumeGroupParams = new HashMap<>();
+ expectedVolumeGroupParams.put("vnf_id", genericVnf.getVnfId());
+ expectedVolumeGroupParams.put("vnf_name", genericVnf.getVnfName());
+ expectedVolumeGroupParams.put("vf_module_id", volumeGroup.getVolumeGroupId());
+ expectedVolumeGroupParams.put("vf_module_name", volumeGroup.getVolumeGroupName());
+ expectedVolumeGroupParams.put("paramOne", "paramOneValue");
+ expectedVolumeGroupParams.put("paramTwo", "paramTwoValue");
+ expectedVolumeGroupParams.put("paramThree", "paramThreeValue");
+
+ Map<String, Object> actualVolumeGroupParams = vnfAdapterObjectMapper.createVolumeGroupParams(requestContext,
+ genericVnf, volumeGroup, sdncVfModuleQueryResponse);
+
+ assertEquals(expectedVolumeGroupParams, actualVolumeGroupParams);
+ }
+
+ @Test
+ public void test_createVolumeGroupParams_without_sdncResponse() throws Exception {
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId("vnfId");
+ genericVnf.setVnfName("vnfName");
+
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("volumeGroupId");
+ volumeGroup.setVolumeGroupName("volumeGroupName");
+
+ Map<String, String> expectedVolumeGroupParams = new HashMap<>();
+ expectedVolumeGroupParams.put("vnf_id", genericVnf.getVnfId());
+ expectedVolumeGroupParams.put("vnf_name", genericVnf.getVnfName());
+ expectedVolumeGroupParams.put("vf_module_id", volumeGroup.getVolumeGroupId());
+ expectedVolumeGroupParams.put("vf_module_name", volumeGroup.getVolumeGroupName());
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> actualVolumeGroupParams =
+ vnfAdapterObjectMapper.createVolumeGroupParams(requestContext, genericVnf, volumeGroup, null);
+
+ assertEquals(expectedVolumeGroupParams, actualVolumeGroupParams);
+ }
@Test
public void test_createVolumeGroupParams_with_user_params() throws Exception {
@@ -351,7 +361,8 @@ public class VnfAdapterObjectMapperTest {
volumeGroup.setVolumeGroupId("volumeGroupId");
volumeGroup.setVolumeGroupName("volumeGroupName");
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
+ String sdncVfModuleQueryResponse = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
Map<String, String> expectedVolumeGroupParams = new HashMap<>();
expectedVolumeGroupParams.put("vnf_id", genericVnf.getVnfId());
@@ -363,25 +374,26 @@ public class VnfAdapterObjectMapperTest {
expectedVolumeGroupParams.put("paramThree", "paramThreeValue");
expectedVolumeGroupParams.put("userParamKey", "userParamValue");
- Map<String, Object> actualVolumeGroupParams = vnfAdapterObjectMapper.createVolumeGroupParams(requestContext,genericVnf, volumeGroup, sdncVfModuleQueryResponse);
+ Map<String, Object> actualVolumeGroupParams = vnfAdapterObjectMapper.createVolumeGroupParams(requestContext,
+ genericVnf, volumeGroup, sdncVfModuleQueryResponse);
assertEquals(expectedVolumeGroupParams, actualVolumeGroupParams);
}
- @Test
- public void test_createMsoRequest() {
- RequestContext requestContext = new RequestContext();
- requestContext.setMsoRequestId("msoRequestId");
-
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
-
- MsoRequest expectedMsoRequest = new MsoRequest();
- expectedMsoRequest.setRequestId(requestContext.getMsoRequestId());
- expectedMsoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
-
- MsoRequest actualMsoRequest = vnfAdapterObjectMapper.createMsoRequest(requestContext, serviceInstance);
-
- assertThat(expectedMsoRequest, sameBeanAs(actualMsoRequest));
- }
+ @Test
+ public void test_createMsoRequest() {
+ RequestContext requestContext = new RequestContext();
+ requestContext.setMsoRequestId("msoRequestId");
+
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+
+ MsoRequest expectedMsoRequest = new MsoRequest();
+ expectedMsoRequest.setRequestId(requestContext.getMsoRequestId());
+ expectedMsoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+
+ MsoRequest actualMsoRequest = vnfAdapterObjectMapper.createMsoRequest(requestContext, serviceInstance);
+
+ assertThat(expectedMsoRequest, sameBeanAs(actualMsoRequest));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperPayloadTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperPayloadTest.java
index 00e5c10f73..5a8e57135a 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperPayloadTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperPayloadTest.java
@@ -23,13 +23,11 @@ package org.onap.so.client.adapter.vnf.mapper;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.sdnc.northbound.client.model.GenericResourceApiVmNetworkData;
@@ -45,820 +43,831 @@ import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule;
-
import com.fasterxml.jackson.databind.ObjectMapper;
public class VnfAdapterVfModuleObjectMapperPayloadTest {
- private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/";
-
- private VnfAdapterVfModuleObjectMapper vfModuleObjectMapper = new VnfAdapterVfModuleObjectMapper();
- private ObjectMapper omapper = new ObjectMapper();
- @Before
- public void setUp() {
- vfModuleObjectMapper.vnfAdapterObjectMapperUtils = new VnfAdapterObjectMapperUtils();
- vfModuleObjectMapper.init();
-
- }
- @Test
- public void createVfModuleRequestMapperTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
- modelInfoServiceInstance.setEnvironmentContext("environmentContext");
- modelInfoServiceInstance.setWorkloadContext("workloadContext");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value2");
- requestContext.setMsoRequestId("requestId");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnfId");
- vnf.setVnfType("vnfType");
- vnf.setVnfName("vnfName");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- Integer vfModuleIndex = 1;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("vfModuleId");
- vfModule.setVfModuleName("vfModuleName");
- vfModule.setModuleIndex(vfModuleIndex);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
- HashMap<String, String> cloudParams = new HashMap<String, String>();
- cloudParams.put("key3", "value3");
- vfModule.setCloudParams(cloudParams);
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("cloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(false);
-
- String sdncVnfQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopology.json")));
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
-
- CreateVfModuleRequest vfModuleVNFAdapterRequest = vfModuleObjectMapper.createVfModuleRequestMapper(
- requestContext, cloudRegion, orchestrationContext, serviceInstance,
- vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequest.json")));
-
- CreateVfModuleRequest reqMapper1 = omapper.readValue(
- jsonToCompare,
- CreateVfModuleRequest.class);
-
- assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
- }
-
- @Test
- public void createVfModuleWithFalseRollbackRequestMapperTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
- modelInfoServiceInstance.setEnvironmentContext("environmentContext");
- modelInfoServiceInstance.setWorkloadContext("workloadContext");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value2");
- requestContext.setMsoRequestId("requestId");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnfId");
- vnf.setVnfType("vnfType");
- vnf.setVnfName("vnfName");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- Integer vfModuleIndex = 1;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("vfModuleId");
- vfModule.setVfModuleName("vfModuleName");
- vfModule.setModuleIndex(vfModuleIndex);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
- HashMap<String, String> cloudParams = new HashMap<String, String>();
- cloudParams.put("key3", "value3");
- vfModule.setCloudParams(cloudParams);
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("cloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
-
- String sdncVnfQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopology.json")));
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
-
- CreateVfModuleRequest vfModuleVNFAdapterRequest = vfModuleObjectMapper.createVfModuleRequestMapper(
- requestContext, cloudRegion, orchestrationContext, serviceInstance,
- vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestTrueBackout.json")));
-
- CreateVfModuleRequest reqMapper1 = omapper.readValue(
- jsonToCompare,
- CreateVfModuleRequest.class);
-
- assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
- }
-
- @Test
- public void createVfModuleRequestWithNoEnvironmentAndWorkloadContextMapperTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
- modelInfoServiceInstance.setEnvironmentContext(null);
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value2");
- requestContext.setMsoRequestId("requestId");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnfId");
- vnf.setVnfType("vnfType");
- vnf.setVnfName("vnfName");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- Integer vfModuleIndex = 1;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("vfModuleId");
- vfModule.setVfModuleName("vfModuleName");
- vfModule.setModuleIndex(vfModuleIndex);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("cloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(false);
-
- String sdncVnfQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopology.json")));
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
-
- CreateVfModuleRequest vfModuleVNFAdapterRequest = vfModuleObjectMapper.createVfModuleRequestMapper(
- requestContext, cloudRegion, orchestrationContext, serviceInstance,
- vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleWithNoEnvironmentAndWorkloadContextRequest.json")));
-
- CreateVfModuleRequest reqMapper1 = omapper.readValue(
- jsonToCompare,
- CreateVfModuleRequest.class);
-
- assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
- }
-
- @Test
- public void createVfModuleAddonRequestMapperTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
- modelInfoServiceInstance.setEnvironmentContext("environmentContext");
- modelInfoServiceInstance.setWorkloadContext("workloadContext");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- //
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value2");
- requestContext.setMsoRequestId("requestId");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnfId");
- vnf.setVnfType("vnfType");
- vnf.setVnfName("vnfName");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- Integer vfModuleIndex = 1;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("vfModuleId");
- vfModule.setVfModuleName("vfModuleName");
- vfModule.setModuleIndex(vfModuleIndex);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
-
- VfModule baseVfModule = new VfModule();
- baseVfModule.setVfModuleId("baseVfModuleId");
- baseVfModule.setHeatStackId("baseVfModuleStackId");
- ModelInfoVfModule baseModelInfoVfModule = new ModelInfoVfModule();
- baseModelInfoVfModule.setIsBaseBoolean(true);
- baseVfModule.setModelInfoVfModule(baseModelInfoVfModule);
- vnf.getVfModules().add(baseVfModule);
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("cloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(false);
-
- String sdncVnfQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopology.json")));
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
-
- CreateVfModuleRequest vfModuleVNFAdapterRequest = vfModuleObjectMapper.createVfModuleRequestMapper(
- requestContext, cloudRegion, orchestrationContext, serviceInstance,
- vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleAddonRequest.json")));
-
- CreateVfModuleRequest reqMapper1 = omapper.readValue(
- jsonToCompare,
- CreateVfModuleRequest.class);
-
- assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
- }
-
- @Test
- public void createVfModuleWithVolumeGroupRequestMapperTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
- modelInfoServiceInstance.setEnvironmentContext("environmentContext");
- modelInfoServiceInstance.setWorkloadContext("workloadContext");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- //
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value2");
- requestContext.setMsoRequestId("requestId");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnfId");
- vnf.setVnfType("vnfType");
- vnf.setVnfName("vnfName");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- Integer vfModuleIndex = 1;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("vfModuleId");
- vfModule.setVfModuleName("vfModuleName");
- vfModule.setModuleIndex(vfModuleIndex);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
-
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("volumeGroupId");
- volumeGroup.setHeatStackId("volumeGroupStackId");
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("cloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(false);
-
- String sdncVnfQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopology.json")));
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
-
- CreateVfModuleRequest vfModuleVNFAdapterRequest = vfModuleObjectMapper.createVfModuleRequestMapper(
- requestContext, cloudRegion, orchestrationContext, serviceInstance,
- vnf, vfModule, volumeGroup, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleWithVolumeGroupRequest.json")));
-
- CreateVfModuleRequest reqMapper1 = omapper.readValue(
- jsonToCompare,
- CreateVfModuleRequest.class);
-
- assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
- }
-
- @Test
- public void createVfModuleWithSingleAvailabilityZoneRequestMapperTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
- modelInfoServiceInstance.setEnvironmentContext("environmentContext");
- modelInfoServiceInstance.setWorkloadContext("workloadContext");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value2");
- requestContext.setMsoRequestId("requestId");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnfId");
- vnf.setVnfType("vnfType");
- vnf.setVnfName("vnfName");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- Integer vfModuleIndex = 1;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("vfModuleId");
- vfModule.setVfModuleName("vfModuleName");
- vfModule.setModuleIndex(vfModuleIndex);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("cloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(false);
-
- String sdncVnfQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopologyWithSingletonArray.json")));
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
-
- CreateVfModuleRequest vfModuleVNFAdapterRequest = vfModuleObjectMapper.createVfModuleRequestMapper(
- requestContext, cloudRegion, orchestrationContext, serviceInstance,
- vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestWithSingleAvailabilityZone.json")));
-
- CreateVfModuleRequest reqMapper1 = omapper.readValue(
- jsonToCompare,
- CreateVfModuleRequest.class);
-
- assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
- }
-
- @Test
- public void createVfModuleRequestMapperWithCloudResourcesTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
- modelInfoServiceInstance.setEnvironmentContext("environmentContext");
- modelInfoServiceInstance.setWorkloadContext("workloadContext");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value1");
- requestContext.setMsoRequestId("requestId");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnfId");
- vnf.setVnfType("vnfType");
- vnf.setVnfName("vnfName");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- Integer vfModuleIndex = 1;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("vfModuleId");
- vfModule.setVfModuleName("vfModuleName");
- vfModule.setModuleIndex(vfModuleIndex);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("cloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(false);
-
- String sdncVnfQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopologyWithCloudResources.json")));
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopologyWithCloudResources.json")));
-
- CreateVfModuleRequest vfModuleVNFAdapterRequest = vfModuleObjectMapper.createVfModuleRequestMapper(
- requestContext, cloudRegion, orchestrationContext, serviceInstance,
- vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestWithCloudResources.json")));
-
- CreateVfModuleRequest reqMapper1 = omapper.readValue(
- jsonToCompare,
- CreateVfModuleRequest.class);
-
- assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
- }
-
- @Test
- public void createVfModuleRequestMapperDhcpDisabledTest() throws Exception {
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
- modelInfoServiceInstance.setEnvironmentContext("environmentContext");
- modelInfoServiceInstance.setWorkloadContext("workloadContext");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value1");
- requestContext.setMsoRequestId("requestId");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnfId");
- vnf.setVnfType("vnfType");
- vnf.setVnfName("vnfName");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- Integer vfModuleIndex = 1;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("vfModuleId");
- vfModule.setVfModuleName("vfModuleName");
- vfModule.setModuleIndex(vfModuleIndex);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("cloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(false);
-
- String sdncVnfQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopologySubnetDhcpDisabled.json")));
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
-
- CreateVfModuleRequest vfModuleVNFAdapterRequest = vfModuleObjectMapper.createVfModuleRequestMapper(
- requestContext, cloudRegion, orchestrationContext, serviceInstance,
- vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestDhcpDisabled.json")));
-
- CreateVfModuleRequest reqMapper1 = omapper.readValue(
- jsonToCompare,
- CreateVfModuleRequest.class);
-
- assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
- }
-
- @Test
- public void createVfModuleRequestMapperMultipleDhcpTest() throws Exception {
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
- modelInfoServiceInstance.setEnvironmentContext("environmentContext");
- modelInfoServiceInstance.setWorkloadContext("workloadContext");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value1");
- requestContext.setMsoRequestId("requestId");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnfId");
- vnf.setVnfType("vnfType");
- vnf.setVnfName("vnfName");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- Integer vfModuleIndex = 1;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("vfModuleId");
- vfModule.setVfModuleName("vfModuleName");
- vfModule.setModuleIndex(vfModuleIndex);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("cloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(false);
-
- String sdncVnfQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopologySubnetMultipleDhcp.json")));
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
-
- CreateVfModuleRequest vfModuleVNFAdapterRequest = vfModuleObjectMapper.createVfModuleRequestMapper(
- requestContext, cloudRegion, orchestrationContext, serviceInstance,
- vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestMultipleDhcp.json")));
-
- CreateVfModuleRequest reqMapper1 = omapper.readValue(
- jsonToCompare,
- CreateVfModuleRequest.class);
-
- assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
- }
-
- @Test
- public void createVfModuleRequestMapperWithNullUserParamsTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
- modelInfoServiceInstance.setEnvironmentContext("environmentContext");
- modelInfoServiceInstance.setWorkloadContext("workloadContext");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- RequestContext requestContext = new RequestContext();
- requestContext.setMsoRequestId("requestId");
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnfId");
- vnf.setVnfType("vnfType");
- vnf.setVnfName("vnfName");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- Integer vfModuleIndex = 1;
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("vfModuleId");
- vfModule.setVfModuleName("vfModuleName");
- vfModule.setModuleIndex(vfModuleIndex);
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("cloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(false);
-
- String sdncVnfQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopology.json")));
- String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
-
- CreateVfModuleRequest vfModuleVNFAdapterRequest = vfModuleObjectMapper.createVfModuleRequestMapper(
- requestContext, cloudRegion, orchestrationContext, serviceInstance,
- vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestNoUserParams.json")));
-
- CreateVfModuleRequest reqMapper1 = omapper.readValue(
- jsonToCompare,
- CreateVfModuleRequest.class);
-
- assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
- }
-
- @Test
- public void DeleteVfModuleRequestMapperTest() throws Exception {
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
- modelInfoServiceInstance.setEnvironmentContext("environmentContext");
- modelInfoServiceInstance.setWorkloadContext("workloadContext");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value1");
- requestContext.setMsoRequestId("requestId");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("vnfId");
- vnf.setVnfType("vnfType");
- vnf.setVnfName("vnfName");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("vfModuleId");
- vfModule.setVfModuleName("vfModuleName");
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("cloudRegionId");
- cloudRegion.setTenantId("tenantId");
-
- OrchestrationContext orchestrationContext = new OrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(false);
-
- DeleteVfModuleRequest vfModuleVNFAdapterRequest = vfModuleObjectMapper.deleteVfModuleRequestMapper(
- requestContext, cloudRegion, serviceInstance,
- vnf, vfModule);
-
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterDeleteVfModuleRequest.json")));
-
- DeleteVfModuleRequest reqMapper1 = omapper.readValue(
- jsonToCompare,
- DeleteVfModuleRequest.class);
-
- assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl").ignoring("vfModuleStackId"));
- }
-
- @Test
- public void networkCloudParamsTest() throws IOException {
-
- String json = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "grApiVmNetworkSubSectionWith5GParams.json")));
- GenericResourceApiVmNetworkData network = omapper.readValue(json, GenericResourceApiVmNetworkData.class);
- Map<String, Object> paramsMap = new HashMap<>();
- vfModuleObjectMapper.buildVlanInformation(paramsMap, network, "testKey", "testType");
-
- assertEquals("1,3", paramsMap.get("testKey_testType_private_vlans"));
- assertEquals("2,3", paramsMap.get("testKey_testType_public_vlans"));
- assertEquals("1,2,3", paramsMap.get("testKey_testType_guest_vlans"));
- assertEquals("my-segemntation-id", paramsMap.get("testKey_testType_vlan_filter"));
- }
+ private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/";
+
+ private VnfAdapterVfModuleObjectMapper vfModuleObjectMapper = new VnfAdapterVfModuleObjectMapper();
+ private ObjectMapper omapper = new ObjectMapper();
+
+ @Before
+ public void setUp() {
+ vfModuleObjectMapper.vnfAdapterObjectMapperUtils = new VnfAdapterObjectMapperUtils();
+ vfModuleObjectMapper.init();
+
+ }
+
+ @Test
+ public void createVfModuleRequestMapperTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+ modelInfoServiceInstance.setEnvironmentContext("environmentContext");
+ modelInfoServiceInstance.setWorkloadContext("workloadContext");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value2");
+ requestContext.setMsoRequestId("requestId");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnfId");
+ vnf.setVnfType("vnfType");
+ vnf.setVnfName("vnfName");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ Integer vfModuleIndex = 1;
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("vfModuleId");
+ vfModule.setVfModuleName("vfModuleName");
+ vfModule.setModuleIndex(vfModuleIndex);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+ HashMap<String, String> cloudParams = new HashMap<String, String>();
+ cloudParams.put("key3", "value3");
+ vfModule.setCloudParams(cloudParams);
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("cloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(false);
+
+ String sdncVnfQueryResponse = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopology.json")));
+ String sdncVfModuleQueryResponse = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
+
+ CreateVfModuleRequest vfModuleVNFAdapterRequest =
+ vfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+
+ String jsonToCompare =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequest.json")));
+
+ CreateVfModuleRequest reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class);
+
+ assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
+ }
+
+ @Test
+ public void createVfModuleWithFalseRollbackRequestMapperTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+ modelInfoServiceInstance.setEnvironmentContext("environmentContext");
+ modelInfoServiceInstance.setWorkloadContext("workloadContext");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value2");
+ requestContext.setMsoRequestId("requestId");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnfId");
+ vnf.setVnfType("vnfType");
+ vnf.setVnfName("vnfName");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ Integer vfModuleIndex = 1;
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("vfModuleId");
+ vfModule.setVfModuleName("vfModuleName");
+ vfModule.setModuleIndex(vfModuleIndex);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+ HashMap<String, String> cloudParams = new HashMap<String, String>();
+ cloudParams.put("key3", "value3");
+ vfModule.setCloudParams(cloudParams);
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("cloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+
+ String sdncVnfQueryResponse = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopology.json")));
+ String sdncVfModuleQueryResponse = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
+
+ CreateVfModuleRequest vfModuleVNFAdapterRequest =
+ vfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+
+ String jsonToCompare = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestTrueBackout.json")));
+
+ CreateVfModuleRequest reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class);
+
+ assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
+ }
+
+ @Test
+ public void createVfModuleRequestWithNoEnvironmentAndWorkloadContextMapperTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+ modelInfoServiceInstance.setEnvironmentContext(null);
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value2");
+ requestContext.setMsoRequestId("requestId");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnfId");
+ vnf.setVnfType("vnfType");
+ vnf.setVnfName("vnfName");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ Integer vfModuleIndex = 1;
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("vfModuleId");
+ vfModule.setVfModuleName("vfModuleName");
+ vfModule.setModuleIndex(vfModuleIndex);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("cloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(false);
+
+ String sdncVnfQueryResponse = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopology.json")));
+ String sdncVfModuleQueryResponse = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
+
+ CreateVfModuleRequest vfModuleVNFAdapterRequest =
+ vfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+
+ String jsonToCompare = new String(Files.readAllBytes(Paths
+ .get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleWithNoEnvironmentAndWorkloadContextRequest.json")));
+
+ CreateVfModuleRequest reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class);
+
+ assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
+ }
+
+ @Test
+ public void createVfModuleAddonRequestMapperTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+ modelInfoServiceInstance.setEnvironmentContext("environmentContext");
+ modelInfoServiceInstance.setWorkloadContext("workloadContext");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ //
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value2");
+ requestContext.setMsoRequestId("requestId");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnfId");
+ vnf.setVnfType("vnfType");
+ vnf.setVnfName("vnfName");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ Integer vfModuleIndex = 1;
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("vfModuleId");
+ vfModule.setVfModuleName("vfModuleName");
+ vfModule.setModuleIndex(vfModuleIndex);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+
+ VfModule baseVfModule = new VfModule();
+ baseVfModule.setVfModuleId("baseVfModuleId");
+ baseVfModule.setHeatStackId("baseVfModuleStackId");
+ ModelInfoVfModule baseModelInfoVfModule = new ModelInfoVfModule();
+ baseModelInfoVfModule.setIsBaseBoolean(true);
+ baseVfModule.setModelInfoVfModule(baseModelInfoVfModule);
+ vnf.getVfModules().add(baseVfModule);
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("cloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(false);
+
+ String sdncVnfQueryResponse = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopology.json")));
+ String sdncVfModuleQueryResponse = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
+
+ CreateVfModuleRequest vfModuleVNFAdapterRequest =
+ vfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+
+ String jsonToCompare = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleAddonRequest.json")));
+
+ CreateVfModuleRequest reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class);
+
+ assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
+ }
+
+ @Test
+ public void createVfModuleWithVolumeGroupRequestMapperTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+ modelInfoServiceInstance.setEnvironmentContext("environmentContext");
+ modelInfoServiceInstance.setWorkloadContext("workloadContext");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ //
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value2");
+ requestContext.setMsoRequestId("requestId");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnfId");
+ vnf.setVnfType("vnfType");
+ vnf.setVnfName("vnfName");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ Integer vfModuleIndex = 1;
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("vfModuleId");
+ vfModule.setVfModuleName("vfModuleName");
+ vfModule.setModuleIndex(vfModuleIndex);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("volumeGroupId");
+ volumeGroup.setHeatStackId("volumeGroupStackId");
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("cloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(false);
+
+ String sdncVnfQueryResponse = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopology.json")));
+ String sdncVfModuleQueryResponse = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
+
+ CreateVfModuleRequest vfModuleVNFAdapterRequest =
+ vfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, vnf, vfModule, volumeGroup, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+
+ String jsonToCompare = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleWithVolumeGroupRequest.json")));
+
+ CreateVfModuleRequest reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class);
+
+ assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
+ }
+
+ @Test
+ public void createVfModuleWithSingleAvailabilityZoneRequestMapperTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+ modelInfoServiceInstance.setEnvironmentContext("environmentContext");
+ modelInfoServiceInstance.setWorkloadContext("workloadContext");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value2");
+ requestContext.setMsoRequestId("requestId");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnfId");
+ vnf.setVnfType("vnfType");
+ vnf.setVnfName("vnfName");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ Integer vfModuleIndex = 1;
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("vfModuleId");
+ vfModule.setVfModuleName("vfModuleName");
+ vfModule.setModuleIndex(vfModuleIndex);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("cloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(false);
+
+ String sdncVnfQueryResponse = new String(Files.readAllBytes(
+ Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopologyWithSingletonArray.json")));
+ String sdncVfModuleQueryResponse = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
+
+ CreateVfModuleRequest vfModuleVNFAdapterRequest =
+ vfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+
+ String jsonToCompare = new String(Files.readAllBytes(
+ Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestWithSingleAvailabilityZone.json")));
+
+ CreateVfModuleRequest reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class);
+
+ assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
+ }
+
+ @Test
+ public void createVfModuleRequestMapperWithCloudResourcesTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+ modelInfoServiceInstance.setEnvironmentContext("environmentContext");
+ modelInfoServiceInstance.setWorkloadContext("workloadContext");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value1");
+ requestContext.setMsoRequestId("requestId");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnfId");
+ vnf.setVnfType("vnfType");
+ vnf.setVnfName("vnfName");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ Integer vfModuleIndex = 1;
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("vfModuleId");
+ vfModule.setVfModuleName("vfModuleName");
+ vfModule.setModuleIndex(vfModuleIndex);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("cloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(false);
+
+ String sdncVnfQueryResponse = new String(Files.readAllBytes(
+ Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopologyWithCloudResources.json")));
+ String sdncVfModuleQueryResponse = new String(Files.readAllBytes(Paths
+ .get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopologyWithCloudResources.json")));
+
+ CreateVfModuleRequest vfModuleVNFAdapterRequest =
+ vfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+
+ String jsonToCompare = new String(Files.readAllBytes(
+ Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestWithCloudResources.json")));
+
+ CreateVfModuleRequest reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class);
+
+ assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
+ }
+
+ @Test
+ public void createVfModuleRequestMapperDhcpDisabledTest() throws Exception {
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+ modelInfoServiceInstance.setEnvironmentContext("environmentContext");
+ modelInfoServiceInstance.setWorkloadContext("workloadContext");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value1");
+ requestContext.setMsoRequestId("requestId");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnfId");
+ vnf.setVnfType("vnfType");
+ vnf.setVnfName("vnfName");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ Integer vfModuleIndex = 1;
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("vfModuleId");
+ vfModule.setVfModuleName("vfModuleName");
+ vfModule.setModuleIndex(vfModuleIndex);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("cloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(false);
+
+ String sdncVnfQueryResponse = new String(Files.readAllBytes(
+ Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopologySubnetDhcpDisabled.json")));
+ String sdncVfModuleQueryResponse = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
+
+ CreateVfModuleRequest vfModuleVNFAdapterRequest =
+ vfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+
+ String jsonToCompare = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestDhcpDisabled.json")));
+
+ CreateVfModuleRequest reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class);
+
+ assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
+ }
+
+ @Test
+ public void createVfModuleRequestMapperMultipleDhcpTest() throws Exception {
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+ modelInfoServiceInstance.setEnvironmentContext("environmentContext");
+ modelInfoServiceInstance.setWorkloadContext("workloadContext");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value1");
+ requestContext.setMsoRequestId("requestId");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnfId");
+ vnf.setVnfType("vnfType");
+ vnf.setVnfName("vnfName");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ Integer vfModuleIndex = 1;
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("vfModuleId");
+ vfModule.setVfModuleName("vfModuleName");
+ vfModule.setModuleIndex(vfModuleIndex);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("cloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(false);
+
+ String sdncVnfQueryResponse = new String(Files.readAllBytes(
+ Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopologySubnetMultipleDhcp.json")));
+ String sdncVfModuleQueryResponse = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
+
+ CreateVfModuleRequest vfModuleVNFAdapterRequest =
+ vfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+
+ String jsonToCompare = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestMultipleDhcp.json")));
+
+ CreateVfModuleRequest reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class);
+
+ assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
+ }
+
+ @Test
+ public void createVfModuleRequestMapperWithNullUserParamsTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+ modelInfoServiceInstance.setEnvironmentContext("environmentContext");
+ modelInfoServiceInstance.setWorkloadContext("workloadContext");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ RequestContext requestContext = new RequestContext();
+ requestContext.setMsoRequestId("requestId");
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnfId");
+ vnf.setVnfType("vnfType");
+ vnf.setVnfName("vnfName");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ Integer vfModuleIndex = 1;
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("vfModuleId");
+ vfModule.setVfModuleName("vfModuleName");
+ vfModule.setModuleIndex(vfModuleIndex);
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("cloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(false);
+
+ String sdncVnfQueryResponse = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVnfTopology.json")));
+ String sdncVfModuleQueryResponse = new String(Files
+ .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json")));
+
+ CreateVfModuleRequest vfModuleVNFAdapterRequest =
+ vfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+
+ String jsonToCompare = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestNoUserParams.json")));
+
+ CreateVfModuleRequest reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class);
+
+ assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl"));
+ }
+
+ @Test
+ public void DeleteVfModuleRequestMapperTest() throws Exception {
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+ modelInfoServiceInstance.setEnvironmentContext("environmentContext");
+ modelInfoServiceInstance.setWorkloadContext("workloadContext");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value1");
+ requestContext.setMsoRequestId("requestId");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("vnfId");
+ vnf.setVnfType("vnfType");
+ vnf.setVnfName("vnfName");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("vfModuleId");
+ vfModule.setVfModuleName("vfModuleName");
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("cloudRegionId");
+ cloudRegion.setTenantId("tenantId");
+
+ OrchestrationContext orchestrationContext = new OrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(false);
+
+ DeleteVfModuleRequest vfModuleVNFAdapterRequest = vfModuleObjectMapper
+ .deleteVfModuleRequestMapper(requestContext, cloudRegion, serviceInstance, vnf, vfModule);
+
+
+ String jsonToCompare =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterDeleteVfModuleRequest.json")));
+
+ DeleteVfModuleRequest reqMapper1 = omapper.readValue(jsonToCompare, DeleteVfModuleRequest.class);
+
+ assertThat(vfModuleVNFAdapterRequest,
+ sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl").ignoring("vfModuleStackId"));
+ }
+
+ @Test
+ public void networkCloudParamsTest() throws IOException {
+
+ String json = new String(
+ Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "grApiVmNetworkSubSectionWith5GParams.json")));
+ GenericResourceApiVmNetworkData network = omapper.readValue(json, GenericResourceApiVmNetworkData.class);
+ Map<String, Object> paramsMap = new HashMap<>();
+ vfModuleObjectMapper.buildVlanInformation(paramsMap, network, "testKey", "testType");
+
+ assertEquals("1,3", paramsMap.get("testKey_testType_private_vlans"));
+ assertEquals("2,3", paramsMap.get("testKey_testType_public_vlans"));
+ assertEquals("1,2,3", paramsMap.get("testKey_testType_guest_vlans"));
+ assertEquals("my-segemntation-id", paramsMap.get("testKey_testType_vlan_filter"));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperTest.java
index 81d30e33c5..d6ab3db094 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperTest.java
@@ -26,11 +26,9 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
-
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
@@ -45,80 +43,81 @@ import org.onap.so.entity.MsoRequest;
public class VnfAdapterVfModuleObjectMapperTest {
- @Spy
- private VnfAdapterVfModuleObjectMapper mapper = new VnfAdapterVfModuleObjectMapper();
-
- @Before
- public void before() {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void createVnfcSubInterfaceKeyTest() {
-
- assertEquals("type_0_subint_role_port_0", mapper.createVnfcSubInterfaceKey("type", 0, "role", 0));
- }
-
- @Test
- public void createGlobalVnfcSubInterfaceKeyTest() {
-
- assertEquals("type_subint_role_port_0", mapper.createGlobalVnfcSubInterfaceKey("type", "role", 0));
- }
-
- @Test
- public void addPairToMapTest() {
- Map<String, Object> map = new HashMap<>();
-
- mapper.addPairToMap(map, "test", "_key", Arrays.asList("a", "b"));
-
- assertEquals("a,b", map.get("test_key"));
-
- mapper.addPairToMap(map, "test", "_key2", Arrays.asList());
-
- assertThat(map.containsKey("test_key2"), equalTo(false));
-
- mapper.addPairToMap(map, "test", "_key3", "myVal");
-
- assertEquals("myVal", map.get("test_key3"));
-
- }
-
- @Test
- public void test_deleteVfModuleNoHeatIdRequestMapper() throws Exception {
- DeleteVfModuleRequest expectedDeleteVfModuleRequest = new DeleteVfModuleRequest();
-
- CloudRegion cloudRegion = new CloudRegion();
- cloudRegion.setLcpCloudRegionId("lcpCloudRegionId");
- expectedDeleteVfModuleRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
-
- cloudRegion.setTenantId("tenantId");
- expectedDeleteVfModuleRequest.setTenantId(cloudRegion.getTenantId());
-
- GenericVnf genericVnf = new GenericVnf();
- VfModule vfModule = new VfModule();
- vfModule.setHeatStackId("heatStackId");
- expectedDeleteVfModuleRequest.setVfModuleStackId("heatStackId");
- expectedDeleteVfModuleRequest.setSkipAAI(true);
-
- MsoRequest msoRequest = new MsoRequest();
- RequestContext requestContext = new RequestContext();
- requestContext.setMsoRequestId("msoRequestId");
- msoRequest.setRequestId(requestContext.getMsoRequestId());
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- expectedDeleteVfModuleRequest.setMsoRequest(msoRequest);
-
- String messageId = "messageId";
- String endpoint = "endpoint";
- doNothing().when(mapper).setIdAndUrl(any());
- expectedDeleteVfModuleRequest.setMessageId(messageId);
- expectedDeleteVfModuleRequest.setNotificationUrl(endpoint + "/VNFAResponse/" + messageId);
-
- DeleteVfModuleRequest actualDeleteVfModuleRequest = mapper.deleteVfModuleRequestMapper(requestContext, cloudRegion,
- serviceInstance, genericVnf, vfModule);
-
- assertThat(actualDeleteVfModuleRequest, sameBeanAs(expectedDeleteVfModuleRequest).ignoring("messageId").ignoring("notificationUrl"));
- }
-
+ @Spy
+ private VnfAdapterVfModuleObjectMapper mapper = new VnfAdapterVfModuleObjectMapper();
+
+ @Before
+ public void before() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void createVnfcSubInterfaceKeyTest() {
+
+ assertEquals("type_0_subint_role_port_0", mapper.createVnfcSubInterfaceKey("type", 0, "role", 0));
+ }
+
+ @Test
+ public void createGlobalVnfcSubInterfaceKeyTest() {
+
+ assertEquals("type_subint_role_port_0", mapper.createGlobalVnfcSubInterfaceKey("type", "role", 0));
+ }
+
+ @Test
+ public void addPairToMapTest() {
+ Map<String, Object> map = new HashMap<>();
+
+ mapper.addPairToMap(map, "test", "_key", Arrays.asList("a", "b"));
+
+ assertEquals("a,b", map.get("test_key"));
+
+ mapper.addPairToMap(map, "test", "_key2", Arrays.asList());
+
+ assertThat(map.containsKey("test_key2"), equalTo(false));
+
+ mapper.addPairToMap(map, "test", "_key3", "myVal");
+
+ assertEquals("myVal", map.get("test_key3"));
+
+ }
+
+ @Test
+ public void test_deleteVfModuleNoHeatIdRequestMapper() throws Exception {
+ DeleteVfModuleRequest expectedDeleteVfModuleRequest = new DeleteVfModuleRequest();
+
+ CloudRegion cloudRegion = new CloudRegion();
+ cloudRegion.setLcpCloudRegionId("lcpCloudRegionId");
+ expectedDeleteVfModuleRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId());
+
+ cloudRegion.setTenantId("tenantId");
+ expectedDeleteVfModuleRequest.setTenantId(cloudRegion.getTenantId());
+
+ GenericVnf genericVnf = new GenericVnf();
+ VfModule vfModule = new VfModule();
+ vfModule.setHeatStackId("heatStackId");
+ expectedDeleteVfModuleRequest.setVfModuleStackId("heatStackId");
+ expectedDeleteVfModuleRequest.setSkipAAI(true);
+
+ MsoRequest msoRequest = new MsoRequest();
+ RequestContext requestContext = new RequestContext();
+ requestContext.setMsoRequestId("msoRequestId");
+ msoRequest.setRequestId(requestContext.getMsoRequestId());
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ expectedDeleteVfModuleRequest.setMsoRequest(msoRequest);
+
+ String messageId = "messageId";
+ String endpoint = "endpoint";
+ doNothing().when(mapper).setIdAndUrl(any());
+ expectedDeleteVfModuleRequest.setMessageId(messageId);
+ expectedDeleteVfModuleRequest.setNotificationUrl(endpoint + "/VNFAResponse/" + messageId);
+
+ DeleteVfModuleRequest actualDeleteVfModuleRequest =
+ mapper.deleteVfModuleRequestMapper(requestContext, cloudRegion, serviceInstance, genericVnf, vfModule);
+
+ assertThat(actualDeleteVfModuleRequest,
+ sameBeanAs(expectedDeleteVfModuleRequest).ignoring("messageId").ignoring("notificationUrl"));
+ }
+
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientResponseValidatorTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientResponseValidatorTest.java
index 7c58038f65..f50916c0be 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientResponseValidatorTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientResponseValidatorTest.java
@@ -21,10 +21,8 @@
package org.onap.so.client.namingservice;
import static org.junit.Assert.assertEquals;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
import org.onap.namingservice.model.NameGenDeleteResponse;
import org.onap.namingservice.model.NameGenResponse;
@@ -35,70 +33,70 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class NamingClientResponseValidatorTest extends TestDataSetup {
-
- private NamingClientResponseValidator responseValidator = new NamingClientResponseValidator();
- private String instanceGroupName = "generatedInstanceGroupName";
-
- @Test
- public void validateNameGenResponseSuccessTest() throws BadResponseException {
- NameGenResponse name = new NameGenResponse();
- Respelement respElement = new Respelement();
- respElement.setResourceName("instance-group-name");
- respElement.setResourceValue(instanceGroupName);
- List<Respelement> respList = new ArrayList<Respelement>();
- respList.add(respElement);
- name.setElements(respList);
- ResponseEntity<NameGenResponse> resp = new ResponseEntity<>(name, null, HttpStatus.OK);
-
- String actual = responseValidator.validateNameGenResponse(resp);
-
- assertEquals(actual, "generatedInstanceGroupName");
- }
-
- @Test
- public void validateNameGenResponseNoNameGeneratedTest() throws BadResponseException {
- NameGenResponse name = new NameGenResponse();
- Respelement respElement = new Respelement();
- respElement.setResourceName("instance-group");
- respElement.setResourceValue(instanceGroupName);
- List<Respelement> respList = new ArrayList<Respelement>();
- respList.add(respElement);
- name.setElements(respList);
- ResponseEntity<NameGenResponse> resp = new ResponseEntity<>(name, null, HttpStatus.OK);
-
- String actual = responseValidator.validateNameGenResponse(resp);
-
- assertEquals(actual, "");
- }
-
- @Test
- public void validateNameGenResponseBadStatusTest() throws BadResponseException {
- NameGenResponse name = new NameGenResponse();
-
- ResponseEntity<NameGenResponse> resp = new ResponseEntity<>(name, null, HttpStatus.NOT_FOUND);
-
- expectedException.expect(BadResponseException.class);
- responseValidator.validateNameGenResponse(resp);
- }
-
- @Test
- public void validateNameGenDeleteResponseSuccessTest() throws BadResponseException {
- NameGenDeleteResponse name = new NameGenDeleteResponse();
- ResponseEntity<NameGenDeleteResponse> resp = new ResponseEntity<>(name, null, HttpStatus.OK);
-
- String actual = responseValidator.validateNameGenDeleteResponse(resp);
-
- assertEquals(actual, "");
- }
-
- @Test
- public void validateNameGenDeleteResponseBadStatusTest() throws BadResponseException {
- NameGenDeleteResponse name = new NameGenDeleteResponse();
-
- ResponseEntity<NameGenDeleteResponse> resp = new ResponseEntity<>(name, null, HttpStatus.NOT_FOUND);
-
- expectedException.expect(BadResponseException.class);
- responseValidator.validateNameGenDeleteResponse(resp);
- }
-
+
+ private NamingClientResponseValidator responseValidator = new NamingClientResponseValidator();
+ private String instanceGroupName = "generatedInstanceGroupName";
+
+ @Test
+ public void validateNameGenResponseSuccessTest() throws BadResponseException {
+ NameGenResponse name = new NameGenResponse();
+ Respelement respElement = new Respelement();
+ respElement.setResourceName("instance-group-name");
+ respElement.setResourceValue(instanceGroupName);
+ List<Respelement> respList = new ArrayList<Respelement>();
+ respList.add(respElement);
+ name.setElements(respList);
+ ResponseEntity<NameGenResponse> resp = new ResponseEntity<>(name, null, HttpStatus.OK);
+
+ String actual = responseValidator.validateNameGenResponse(resp);
+
+ assertEquals(actual, "generatedInstanceGroupName");
+ }
+
+ @Test
+ public void validateNameGenResponseNoNameGeneratedTest() throws BadResponseException {
+ NameGenResponse name = new NameGenResponse();
+ Respelement respElement = new Respelement();
+ respElement.setResourceName("instance-group");
+ respElement.setResourceValue(instanceGroupName);
+ List<Respelement> respList = new ArrayList<Respelement>();
+ respList.add(respElement);
+ name.setElements(respList);
+ ResponseEntity<NameGenResponse> resp = new ResponseEntity<>(name, null, HttpStatus.OK);
+
+ String actual = responseValidator.validateNameGenResponse(resp);
+
+ assertEquals(actual, "");
+ }
+
+ @Test
+ public void validateNameGenResponseBadStatusTest() throws BadResponseException {
+ NameGenResponse name = new NameGenResponse();
+
+ ResponseEntity<NameGenResponse> resp = new ResponseEntity<>(name, null, HttpStatus.NOT_FOUND);
+
+ expectedException.expect(BadResponseException.class);
+ responseValidator.validateNameGenResponse(resp);
+ }
+
+ @Test
+ public void validateNameGenDeleteResponseSuccessTest() throws BadResponseException {
+ NameGenDeleteResponse name = new NameGenDeleteResponse();
+ ResponseEntity<NameGenDeleteResponse> resp = new ResponseEntity<>(name, null, HttpStatus.OK);
+
+ String actual = responseValidator.validateNameGenDeleteResponse(resp);
+
+ assertEquals(actual, "");
+ }
+
+ @Test
+ public void validateNameGenDeleteResponseBadStatusTest() throws BadResponseException {
+ NameGenDeleteResponse name = new NameGenDeleteResponse();
+
+ ResponseEntity<NameGenDeleteResponse> resp = new ResponseEntity<>(name, null, HttpStatus.NOT_FOUND);
+
+ expectedException.expect(BadResponseException.class);
+ responseValidator.validateNameGenDeleteResponse(resp);
+ }
+
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientTest.java
index 4bae5b40e4..8a387a88a4 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientTest.java
@@ -25,11 +25,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.delete;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
@@ -41,78 +39,78 @@ import org.onap.namingservice.model.NameGenRequest;
import org.onap.so.BaseIntegrationTest;
import org.onap.so.client.exception.BadResponseException;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.core.JsonProcessingException;
-public class NamingClientTest extends BaseIntegrationTest{
- @Autowired
- NamingClient client;
- @Autowired
- NamingRequestObjectBuilder requestBuilder;
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Test
- public void assignNameGenRequest() throws BadResponseException, IOException{
- wireMockServer.stubFor(post(urlPathEqualTo("/web/service/v1/genNetworkElementName"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("NamingClient/AssignResponse.json")
- .withStatus(HttpStatus.SC_ACCEPTED)));
-
- NameGenRequest request = assignSetup();
- String response = client.postNameGenRequest(request);
- assertTrue(response.equals("$vnf-name"));
- }
- @Test
- public void assignNameGenRequestError() throws BadResponseException, IOException{
- wireMockServer.stubFor(post(urlPathEqualTo("/web/service/v1/genNetworkElementName"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("NamingClient/ErrorResponse.json")
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
-
- thrown.expect(BadResponseException.class);
- thrown.expectMessage("Error from Naming Service: External Key is required and must be unique");
- NameGenRequest request = assignSetup();
- client.postNameGenRequest(request);
- }
- @Test
- public void unassignNameGenRequest() throws BadResponseException, IOException{
- wireMockServer.stubFor(delete(urlPathEqualTo("/web/service/v1/genNetworkElementName"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("NamingClient/UnassignResponse.json")
- .withStatus(HttpStatus.SC_ACCEPTED)));
-
- String response = client.deleteNameGenRequest(unassignSetup());
- assertTrue(response.equals(""));
- }
- @Test
- public void unassignNameGenRequestError() throws BadResponseException, IOException{
- wireMockServer.stubFor(delete(urlPathEqualTo("/web/service/v1/genNetworkElementName"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("NamingClient/ErrorResponse.json")
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
-
- thrown.expect(BadResponseException.class);
- thrown.expectMessage("Error from Naming Service: External Key is required and must be unique");
- client.deleteNameGenRequest(unassignSetup());
- }
-
- public NameGenRequest assignSetup() throws JsonProcessingException{
- NameGenRequest request = new NameGenRequest();
- List<Element> elements = new ArrayList<>();
- Element testElement = new Element();
- testElement = requestBuilder.elementMapper("SomeUniqueValue", "SDNC_Policy.Config_MS_1806SRIOV_VNATJson.4.xml", "VNF", "nfNamingCode", "vnf_name");
- elements.add(testElement);
- request = requestBuilder.nameGenRequestMapper(elements);
- return request;
- }
- public NameGenDeleteRequest unassignSetup() throws JsonProcessingException{
- NameGenDeleteRequest request = new NameGenDeleteRequest();
- List<Deleteelement> deleteElements = new ArrayList<>();
- Deleteelement testElement = new Deleteelement();
- testElement = requestBuilder.deleteElementMapper("instanceGroupId");
- deleteElements.add(testElement);
- request = requestBuilder.nameGenDeleteRequestMapper(deleteElements);
- return request;
- }
+public class NamingClientTest extends BaseIntegrationTest {
+ @Autowired
+ NamingClient client;
+ @Autowired
+ NamingRequestObjectBuilder requestBuilder;
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void assignNameGenRequest() throws BadResponseException, IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/web/service/v1/genNetworkElementName"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("NamingClient/AssignResponse.json").withStatus(HttpStatus.SC_ACCEPTED)));
+
+ NameGenRequest request = assignSetup();
+ String response = client.postNameGenRequest(request);
+ assertTrue(response.equals("$vnf-name"));
+ }
+
+ @Test
+ public void assignNameGenRequestError() throws BadResponseException, IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/web/service/v1/genNetworkElementName")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile("NamingClient/ErrorResponse.json")
+ .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+
+ thrown.expect(BadResponseException.class);
+ thrown.expectMessage("Error from Naming Service: External Key is required and must be unique");
+ NameGenRequest request = assignSetup();
+ client.postNameGenRequest(request);
+ }
+
+ @Test
+ public void unassignNameGenRequest() throws BadResponseException, IOException {
+ wireMockServer.stubFor(delete(urlPathEqualTo("/web/service/v1/genNetworkElementName"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("NamingClient/UnassignResponse.json").withStatus(HttpStatus.SC_ACCEPTED)));
+
+ String response = client.deleteNameGenRequest(unassignSetup());
+ assertTrue(response.equals(""));
+ }
+
+ @Test
+ public void unassignNameGenRequestError() throws BadResponseException, IOException {
+ wireMockServer.stubFor(delete(urlPathEqualTo("/web/service/v1/genNetworkElementName")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile("NamingClient/ErrorResponse.json")
+ .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+
+ thrown.expect(BadResponseException.class);
+ thrown.expectMessage("Error from Naming Service: External Key is required and must be unique");
+ client.deleteNameGenRequest(unassignSetup());
+ }
+
+ public NameGenRequest assignSetup() throws JsonProcessingException {
+ NameGenRequest request = new NameGenRequest();
+ List<Element> elements = new ArrayList<>();
+ Element testElement = new Element();
+ testElement = requestBuilder.elementMapper("SomeUniqueValue", "SDNC_Policy.Config_MS_1806SRIOV_VNATJson.4.xml",
+ "VNF", "nfNamingCode", "vnf_name");
+ elements.add(testElement);
+ request = requestBuilder.nameGenRequestMapper(elements);
+ return request;
+ }
+
+ public NameGenDeleteRequest unassignSetup() throws JsonProcessingException {
+ NameGenDeleteRequest request = new NameGenDeleteRequest();
+ List<Deleteelement> deleteElements = new ArrayList<>();
+ Deleteelement testElement = new Deleteelement();
+ testElement = requestBuilder.deleteElementMapper("instanceGroupId");
+ deleteElements.add(testElement);
+ request = requestBuilder.nameGenDeleteRequestMapper(deleteElements);
+ return request;
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingRequestObjectBuilderTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingRequestObjectBuilderTest.java
index 6cb4987bee..bec588b6d3 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingRequestObjectBuilderTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingRequestObjectBuilderTest.java
@@ -22,10 +22,8 @@ package org.onap.so.client.namingservice;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertThat;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
import org.onap.namingservice.model.Deleteelement;
import org.onap.namingservice.model.Element;
@@ -34,72 +32,76 @@ import org.onap.namingservice.model.NameGenRequest;
import org.onap.so.client.namingservice.NamingRequestObjectBuilder;
public class NamingRequestObjectBuilderTest {
-
- private NamingRequestObjectBuilder mapper = new NamingRequestObjectBuilder();
- private String instanceGroupId = "95cbbe59-1017-4c13-b4e8-d824e54def3e";
- private String policyInstanceName = "MSO_Policy.Config_MS_VNFInstanceGroup";
- private String namingType = "InstanceGroup";
- private String nfNamingCode = "NamingCode";
- private String instanceGroupName = "InstanceGroupName";
-
- @Test
- public void elementMapperTest(){
- // Expected element
- Element expected = new Element();
- expected.put("external-key", instanceGroupId);
- expected.put("policy-instance-name", policyInstanceName);
- expected.put("naming-type", namingType);
- expected.put("resource-name", instanceGroupName);
- expected.put("nf-naming-code", nfNamingCode);
-
- // Actual element
- Element actual = mapper.elementMapper(instanceGroupId, policyInstanceName, namingType, nfNamingCode, instanceGroupName);
-
- assertThat(actual, sameBeanAs(expected));
- }
- @Test
- public void deleteElementMapperTest(){
- // Expected Deleteelement
- Deleteelement expected = new Deleteelement();
- expected.setExternalKey(instanceGroupId);
-
- // Actual Deleteelement
- Deleteelement actual = mapper.deleteElementMapper(instanceGroupId);
-
- assertThat(actual, sameBeanAs(expected));
- }
- @Test
- public void nameGenRequestMapper(){
- // Expected NameGenRequest
- NameGenRequest expected = new NameGenRequest();
- List<Element> elements = new ArrayList<>();
- Element element = new Element();
- element.setExternalKey(instanceGroupId);
- element.setPolicyInstanceName(policyInstanceName);
- element.setNamingType(namingType);
- element.setResourceName(instanceGroupName);
- element.setNamingIngredientsZeroOrMore(nfNamingCode);
- elements.add(element);
- expected.setElements(elements);
-
- //Actual NameGenRequest
- NameGenRequest actual = mapper.nameGenRequestMapper(elements);
-
- assertThat(actual, sameBeanAs(expected));
- }
- @Test
- public void nameGenDeleteRequestMapper(){
- // Expected NameGenDeleteRequest
- NameGenDeleteRequest expected = new NameGenDeleteRequest();
- List<Deleteelement> deleteElements = new ArrayList<>();
- Deleteelement deleteElement = new Deleteelement();
- deleteElement.setExternalKey(instanceGroupId);
- deleteElements.add(deleteElement);
- expected.setElements(deleteElements);
-
- // Actual NameGenDeleteRequest
- NameGenDeleteRequest actual = mapper.nameGenDeleteRequestMapper(deleteElements);
-
- assertThat(actual, sameBeanAs(expected));
- }
+
+ private NamingRequestObjectBuilder mapper = new NamingRequestObjectBuilder();
+ private String instanceGroupId = "95cbbe59-1017-4c13-b4e8-d824e54def3e";
+ private String policyInstanceName = "MSO_Policy.Config_MS_VNFInstanceGroup";
+ private String namingType = "InstanceGroup";
+ private String nfNamingCode = "NamingCode";
+ private String instanceGroupName = "InstanceGroupName";
+
+ @Test
+ public void elementMapperTest() {
+ // Expected element
+ Element expected = new Element();
+ expected.put("external-key", instanceGroupId);
+ expected.put("policy-instance-name", policyInstanceName);
+ expected.put("naming-type", namingType);
+ expected.put("resource-name", instanceGroupName);
+ expected.put("nf-naming-code", nfNamingCode);
+
+ // Actual element
+ Element actual =
+ mapper.elementMapper(instanceGroupId, policyInstanceName, namingType, nfNamingCode, instanceGroupName);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void deleteElementMapperTest() {
+ // Expected Deleteelement
+ Deleteelement expected = new Deleteelement();
+ expected.setExternalKey(instanceGroupId);
+
+ // Actual Deleteelement
+ Deleteelement actual = mapper.deleteElementMapper(instanceGroupId);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void nameGenRequestMapper() {
+ // Expected NameGenRequest
+ NameGenRequest expected = new NameGenRequest();
+ List<Element> elements = new ArrayList<>();
+ Element element = new Element();
+ element.setExternalKey(instanceGroupId);
+ element.setPolicyInstanceName(policyInstanceName);
+ element.setNamingType(namingType);
+ element.setResourceName(instanceGroupName);
+ element.setNamingIngredientsZeroOrMore(nfNamingCode);
+ elements.add(element);
+ expected.setElements(elements);
+
+ // Actual NameGenRequest
+ NameGenRequest actual = mapper.nameGenRequestMapper(elements);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void nameGenDeleteRequestMapper() {
+ // Expected NameGenDeleteRequest
+ NameGenDeleteRequest expected = new NameGenDeleteRequest();
+ List<Deleteelement> deleteElements = new ArrayList<>();
+ Deleteelement deleteElement = new Deleteelement();
+ deleteElement.setExternalKey(instanceGroupId);
+ deleteElements.add(deleteElement);
+ expected.setElements(deleteElements);
+
+ // Actual NameGenDeleteRequest
+ NameGenDeleteRequest actual = mapper.nameGenDeleteRequestMapper(deleteElements);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/oof/OofClientTestIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/oof/OofClientTestIT.java
index c4e50412a9..ce7d557254 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/oof/OofClientTestIT.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/oof/OofClientTestIT.java
@@ -24,7 +24,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
import org.onap.so.client.exception.BadResponseException;
@@ -38,9 +37,7 @@ import org.onap.so.client.oof.beans.ResourceModelInfo;
import org.onap.so.client.oof.beans.ServiceInfo;
import org.onap.so.client.oof.beans.SubscriberInfo;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.core.JsonProcessingException;
-
import java.util.ArrayList;
import java.util.List;
@@ -52,7 +49,8 @@ public class OofClientTestIT extends BaseIntegrationTest {
@Test
public void testPostDemands_success() throws BadResponseException, JsonProcessingException {
- String mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"status\", \"requestStatus\": \"accepted\"}";
+ String mockResponse =
+ "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"status\", \"requestStatus\": \"accepted\"}";
ModelInfo modelInfo = new ModelInfo();
modelInfo.setModelCustomizationName("modelCustomizationName-Service");
@@ -118,102 +116,73 @@ public class OofClientTestIT extends BaseIntegrationTest {
oofRequest.setServiceInformation(serviceInfo);
oofRequest.setLicenseInformation("");
- wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
client.postDemands(oofRequest);
String oofRequestOutput = oofRequest.toJsonString();
- assertEquals("{\n" +
- " \"requestInfo\" : {\n" +
- " \"transactionId\" : \"transactionId\",\n" +
- " \"requestId\" : \"requestId\",\n" +
- " \"callbackUrl\" : \"callBackUrl\",\n" +
- " \"sourceId\" : \"sourceId\",\n" +
- " \"requestType\" : \"requestType\",\n" +
- " \"numSolutions\" : 1,\n" +
- " \"optimizers\" : [ \"optimizer1\", \"optimizer2\" ],\n" +
- " \"timeout\" : 30\n" +
- " },\n" +
- " \"serviceInfo\" : {\n" +
- " \"serviceInstanceId\" : \"serviceInstanceId\",\n" +
- " \"serviceName\" : \"serviceName\",\n" +
- " \"modelInfo\" : {\n" +
- " \"modelType\" : \"modelType-Service\",\n" +
- " \"modelInvariantId\" : \"modelInvariantId-Service\",\n" +
- " \"modelVersionId\" : \"modelVersionId-Service\",\n" +
- " \"modelName\" : \"modelName-Service\",\n" +
- " \"modelVersion\" : \"modelVersion-Service\",\n" +
- " \"modelCustomizationName\" : \"modelCustomizationName-Service\"\n" +
- " }\n" +
- " },\n" +
- " \"placementInfo\" : {\n" +
- " \"requestParameters\" : {\n" +
- " \"customerLatitude\" : \"customerLatitude\",\n" +
- " \"customerLongitude\" : \"customerLongitude\",\n" +
- " \"customerName\" : \"customerName\"\n" +
- " },\n" +
- " \"subscriberInfo\" : {\n" +
- " \"globalSubscriberId\" : \"globalSubscriberId\",\n" +
- " \"subscriberName\" : \"subscriberName\",\n" +
- " \"subscriberCommonSiteId\" : \"subscriberCommonSiteId\"\n" +
- " },\n" +
- " \"placementDemands\" : [ {\n" +
- " \"resourceModuleName\" : \"resourceModuleName\",\n" +
- " \"serviceResourceId\" : \"serviceResourceId\",\n" +
- " \"tenantId\" : \"tenantId\",\n" +
- " \"resourceModelInfo\" : {\n" +
- " \"modelType\" : \"modelType\",\n" +
- " \"modelInvariantId\" : \"invarianteId\",\n" +
- " \"modelVersionId\" : \"versionId\",\n" +
- " \"modelName\" : \"modelName\",\n" +
- " \"modelVersion\" : \"version\",\n" +
- " \"modelCustomizationName\" : \"modelCustomizationName\"\n" +
- " }\n" +
- " } ]\n" +
- " },\n" +
- " \"licenseInfo\" : \"\"\n" +
- "}", oofRequestOutput);
+ assertEquals("{\n" + " \"requestInfo\" : {\n" + " \"transactionId\" : \"transactionId\",\n"
+ + " \"requestId\" : \"requestId\",\n" + " \"callbackUrl\" : \"callBackUrl\",\n"
+ + " \"sourceId\" : \"sourceId\",\n" + " \"requestType\" : \"requestType\",\n"
+ + " \"numSolutions\" : 1,\n" + " \"optimizers\" : [ \"optimizer1\", \"optimizer2\" ],\n"
+ + " \"timeout\" : 30\n" + " },\n" + " \"serviceInfo\" : {\n"
+ + " \"serviceInstanceId\" : \"serviceInstanceId\",\n" + " \"serviceName\" : \"serviceName\",\n"
+ + " \"modelInfo\" : {\n" + " \"modelType\" : \"modelType-Service\",\n"
+ + " \"modelInvariantId\" : \"modelInvariantId-Service\",\n"
+ + " \"modelVersionId\" : \"modelVersionId-Service\",\n"
+ + " \"modelName\" : \"modelName-Service\",\n"
+ + " \"modelVersion\" : \"modelVersion-Service\",\n"
+ + " \"modelCustomizationName\" : \"modelCustomizationName-Service\"\n" + " }\n" + " },\n"
+ + " \"placementInfo\" : {\n" + " \"requestParameters\" : {\n"
+ + " \"customerLatitude\" : \"customerLatitude\",\n"
+ + " \"customerLongitude\" : \"customerLongitude\",\n"
+ + " \"customerName\" : \"customerName\"\n" + " },\n" + " \"subscriberInfo\" : {\n"
+ + " \"globalSubscriberId\" : \"globalSubscriberId\",\n"
+ + " \"subscriberName\" : \"subscriberName\",\n"
+ + " \"subscriberCommonSiteId\" : \"subscriberCommonSiteId\"\n" + " },\n"
+ + " \"placementDemands\" : [ {\n" + " \"resourceModuleName\" : \"resourceModuleName\",\n"
+ + " \"serviceResourceId\" : \"serviceResourceId\",\n" + " \"tenantId\" : \"tenantId\",\n"
+ + " \"resourceModelInfo\" : {\n" + " \"modelType\" : \"modelType\",\n"
+ + " \"modelInvariantId\" : \"invarianteId\",\n" + " \"modelVersionId\" : \"versionId\",\n"
+ + " \"modelName\" : \"modelName\",\n" + " \"modelVersion\" : \"version\",\n"
+ + " \"modelCustomizationName\" : \"modelCustomizationName\"\n" + " }\n" + " } ]\n"
+ + " },\n" + " \"licenseInfo\" : \"\"\n" + "}", oofRequestOutput);
}
@Test
public void testAsyncResponse_success() throws BadResponseException, JsonProcessingException {
- String mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"status\", \"requestStatus\": \"accepted\"}";
+ String mockResponse =
+ "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"status\", \"requestStatus\": \"accepted\"}";
- wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
client.postDemands(new OofRequest());
}
@Test(expected = BadResponseException.class)
public void testPostDemands_error_failed() throws JsonProcessingException, BadResponseException {
- String mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"missing data\", \"requestStatus\": \"failed\"}";
+ String mockResponse =
+ "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"missing data\", \"requestStatus\": \"failed\"}";
- wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
client.postDemands(new OofRequest());
- //TODO assertEquals("missing data", );
+ // TODO assertEquals("missing data", );
}
@Test(expected = BadResponseException.class)
public void testPostDemands_error_noMessage() throws JsonProcessingException, BadResponseException {
- String mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"\", \"requestStatus\": \"failed\"}";
+ String mockResponse =
+ "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"\", \"requestStatus\": \"failed\"}";
- wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
client.postDemands(new OofRequest());
@@ -222,12 +191,11 @@ public class OofClientTestIT extends BaseIntegrationTest {
@Test(expected = BadResponseException.class)
public void testPostDemands_error_noStatus() throws JsonProcessingException, BadResponseException {
- String mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"missing data\", \"requestStatus\": null}";
+ String mockResponse =
+ "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"missing data\", \"requestStatus\": null}";
- wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
client.postDemands(new OofRequest());
@@ -238,10 +206,8 @@ public class OofClientTestIT extends BaseIntegrationTest {
public void testPostDemands_error_empty() throws JsonProcessingException, BadResponseException {
String mockResponse = "{ }";
- wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/api/oof/v1/placement")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
client.postDemands(new OofRequest());
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAICollectionResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAICollectionResourcesTest.java
index 8bf3de5c4e..7c40995d48 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAICollectionResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAICollectionResourcesTest.java
@@ -26,7 +26,6 @@ import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -43,42 +42,47 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.onap.so.client.aai.mapper.AAIObjectMapper;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-public class AAICollectionResourcesTest extends BaseTaskTest{
-
- @InjectMocks
- private AAICollectionResources aaiCollectionResources = new AAICollectionResources();
-
-
- private Collection networkCollection;
-
- @Before
- public void before() {
- networkCollection = buildCollection();
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- }
-
- @Test
- public void createCollectionTest() throws Exception {
- networkCollection.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
- doReturn(new org.onap.aai.domain.yang.Collection()).when(MOCK_aaiObjectMapper).mapCollection(networkCollection);
-
- aaiCollectionResources.createCollection(networkCollection);
-
- assertEquals(OrchestrationStatus.INVENTORIED, networkCollection.getOrchestrationStatus());
- verify(MOCK_aaiResourcesClient, times(1)).create(eq(AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, networkCollection.getId())), isA(org.onap.aai.domain.yang.Collection.class));
- }
-
- @Test
- public void updateCollectionTest() throws Exception {
- doReturn(new org.onap.aai.domain.yang.Collection()).when(MOCK_aaiObjectMapper).mapCollection(networkCollection);
- aaiCollectionResources.updateCollection(networkCollection);
- verify(MOCK_aaiResourcesClient, times(1)).update(eq(AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, networkCollection.getId())), isA(org.onap.aai.domain.yang.Collection.class));
- }
-
- @Test
- public void deleteCollectionTest() throws Exception {
- aaiCollectionResources.deleteCollection(networkCollection);
- verify(MOCK_aaiResourcesClient, times(1)).delete(eq(AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, networkCollection.getId())));
- }
-
+public class AAICollectionResourcesTest extends BaseTaskTest {
+
+ @InjectMocks
+ private AAICollectionResources aaiCollectionResources = new AAICollectionResources();
+
+
+ private Collection networkCollection;
+
+ @Before
+ public void before() {
+ networkCollection = buildCollection();
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ }
+
+ @Test
+ public void createCollectionTest() throws Exception {
+ networkCollection.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ doReturn(new org.onap.aai.domain.yang.Collection()).when(MOCK_aaiObjectMapper).mapCollection(networkCollection);
+
+ aaiCollectionResources.createCollection(networkCollection);
+
+ assertEquals(OrchestrationStatus.INVENTORIED, networkCollection.getOrchestrationStatus());
+ verify(MOCK_aaiResourcesClient, times(1)).create(
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, networkCollection.getId())),
+ isA(org.onap.aai.domain.yang.Collection.class));
+ }
+
+ @Test
+ public void updateCollectionTest() throws Exception {
+ doReturn(new org.onap.aai.domain.yang.Collection()).when(MOCK_aaiObjectMapper).mapCollection(networkCollection);
+ aaiCollectionResources.updateCollection(networkCollection);
+ verify(MOCK_aaiResourcesClient, times(1)).update(
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, networkCollection.getId())),
+ isA(org.onap.aai.domain.yang.Collection.class));
+ }
+
+ @Test
+ public void deleteCollectionTest() throws Exception {
+ aaiCollectionResources.deleteCollection(networkCollection);
+ verify(MOCK_aaiResourcesClient, times(1))
+ .delete(eq(AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, networkCollection.getId())));
+ }
+
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java
index 4bf445949a..2e1a40dd22 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java
@@ -27,9 +27,7 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -57,32 +55,32 @@ import org.onap.so.bpmn.common.data.TestDataSetup;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class AAIConfigurationResourcesTest extends TestDataSetup{
-
-
-
- private Configuration configuration;
+public class AAIConfigurationResourcesTest extends TestDataSetup {
+
+
+
+ private Configuration configuration;
private ServiceProxy serviceProxy;
private ServiceInstance serviceInstance;
private GenericVnf genericVnf;
private VpnBinding vpnBinding;
private VfModule vfModule;
-
- @Mock
- protected AAIResourcesClient MOCK_aaiResourcesClient;
-
+
+ @Mock
+ protected AAIResourcesClient MOCK_aaiResourcesClient;
+
@Mock
protected AAIObjectMapper MOCK_aaiObjectMapper;
-
+
@Mock
protected InjectionHelper MOCK_injectionHelper;
-
+
@InjectMocks
- private AAIConfigurationResources aaiConfigurationResources = new AAIConfigurationResources();
-
+ private AAIConfigurationResources aaiConfigurationResources = new AAIConfigurationResources();
+
@Before
public void before() {
- configuration = buildConfiguration();
+ configuration = buildConfiguration();
serviceProxy = buildServiceProxy();
serviceInstance = buildServiceInstance();
genericVnf = buildGenericVnf();
@@ -90,62 +88,73 @@ public class AAIConfigurationResourcesTest extends TestDataSetup{
vpnBinding = buildVpnBinding();
doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
}
-
+
@Test
public void createConfigurationTest() {
- doReturn(new org.onap.aai.domain.yang.Configuration()).when(MOCK_aaiObjectMapper).mapConfiguration(configuration);
- doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Configuration.class));
-
+ doReturn(new org.onap.aai.domain.yang.Configuration()).when(MOCK_aaiObjectMapper)
+ .mapConfiguration(configuration);
+ doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.Configuration.class));
+
aaiConfigurationResources.createConfiguration(configuration);
-
+
assertEquals(OrchestrationStatus.ASSIGNED, configuration.getOrchestrationStatus());
- verify(MOCK_aaiResourcesClient, times(1)).create(any(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Configuration.class));
+ verify(MOCK_aaiResourcesClient, times(1)).create(any(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.Configuration.class));
}
@Test
- public void updateConfigurationTest() {
- doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Configuration.class));
+ public void updateConfigurationTest() {
+ doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.Configuration.class));
configuration.setConfigurationType("VNR");
configuration.setOrchestrationStatus(OrchestrationStatus.ACTIVE);
aaiConfigurationResources.updateConfiguration(configuration);
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class),ArgumentMatchers.isNull());
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
}
@Test
public void connectConfigurationToServiceInstanceTest() {
doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- aaiConfigurationResources.connectConfigurationToServiceInstance(configuration.getConfigurationId(), serviceInstance.getServiceInstanceId());
+ aaiConfigurationResources.connectConfigurationToServiceInstance(configuration.getConfigurationId(),
+ serviceInstance.getServiceInstanceId());
verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
}
-
+
@Test
public void connectConfigurationToServiceInstanceWithEdgeTest() {
- doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class), any(AAIEdgeLabel.class));
- aaiConfigurationResources.connectConfigurationToServiceInstance(configuration.getConfigurationId(), serviceInstance.getServiceInstanceId(), AAIEdgeLabel.USES);
- verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class), any(AAIEdgeLabel.class));
+ doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class),
+ any(AAIEdgeLabel.class));
+ aaiConfigurationResources.connectConfigurationToServiceInstance(configuration.getConfigurationId(),
+ serviceInstance.getServiceInstanceId(), AAIEdgeLabel.USES);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class),
+ any(AAIEdgeLabel.class));
}
-
+
@Test
- public void disconnectConfigurationToServiceInstanceTest(){
+ public void disconnectConfigurationToServiceInstanceTest() {
doNothing().when(MOCK_aaiResourcesClient).disconnect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- aaiConfigurationResources.disconnectConfigurationToServiceInstance("TEST_CONFIGURATION_ID", "TEST_SERVICE_INSTANCE_ID");
+ aaiConfigurationResources.disconnectConfigurationToServiceInstance("TEST_CONFIGURATION_ID",
+ "TEST_SERVICE_INSTANCE_ID");
verify(MOCK_aaiResourcesClient, times(1)).disconnect(any(AAIResourceUri.class), any(AAIResourceUri.class));
}
@Test
public void connectConfigurationToGenericVnfTest() {
doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- aaiConfigurationResources.connectConfigurationToGenericVnf(configuration.getConfigurationId(), genericVnf.getVnfId());
+ aaiConfigurationResources.connectConfigurationToGenericVnf(configuration.getConfigurationId(),
+ genericVnf.getVnfId());
verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
}
-
+
@Test
public void connectConfigurationToVfModuleTest() {
doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- aaiConfigurationResources.connectConfigurationToVfModule(configuration.getConfigurationId(), vfModule.getVfModuleId(),genericVnf.getVnfId());
+ aaiConfigurationResources.connectConfigurationToVfModule(configuration.getConfigurationId(),
+ vfModule.getVfModuleId(), genericVnf.getVnfId());
verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
}
-
+
@Test
public void connectConfigurationToVnfcTest() {
doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
@@ -156,17 +165,22 @@ public class AAIConfigurationResourcesTest extends TestDataSetup{
@Test
public void connectConfigurationToVpnBindingTest() {
doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- aaiConfigurationResources.connectConfigurationToVpnBinding(configuration.getConfigurationId(), vpnBinding.getVpnId());
+ aaiConfigurationResources.connectConfigurationToVpnBinding(configuration.getConfigurationId(),
+ vpnBinding.getVpnId());
verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
}
@Test
- public void getConfigurationFromRelatedLinkTest () {
- Optional<org.onap.aai.domain.yang.Configuration> configuration = Optional.of(new org.onap.aai.domain.yang.Configuration());
+ public void getConfigurationFromRelatedLinkTest() {
+ Optional<org.onap.aai.domain.yang.Configuration> configuration =
+ Optional.of(new org.onap.aai.domain.yang.Configuration());
configuration.get().setConfigurationId("config1");
- doReturn(configuration).when(MOCK_aaiResourcesClient).get(eq(org.onap.aai.domain.yang.Configuration.class),isA(AAIResourceUri.class));
- aaiConfigurationResources.getConfigurationFromRelatedLink("http://localhost:8090/aai/v12/network/configurations/configuration/config1");
- verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.Configuration.class),isA(AAIResourceUri.class));
+ doReturn(configuration).when(MOCK_aaiResourcesClient).get(eq(org.onap.aai.domain.yang.Configuration.class),
+ isA(AAIResourceUri.class));
+ aaiConfigurationResources.getConfigurationFromRelatedLink(
+ "http://localhost:8090/aai/v12/network/configurations/configuration/config1");
+ verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.Configuration.class),
+ isA(AAIResourceUri.class));
}
@Test
@@ -174,24 +188,28 @@ public class AAIConfigurationResourcesTest extends TestDataSetup{
Configuration vrfConfiguration = buildConfiguration();
Configuration vnrConfiguration = buildConfiguration();
doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- aaiConfigurationResources.connectVrfConfigurationToVnrConfiguration(vrfConfiguration.getConfigurationId(),vnrConfiguration.getConfigurationId());
+ aaiConfigurationResources.connectVrfConfigurationToVnrConfiguration(vrfConfiguration.getConfigurationId(),
+ vnrConfiguration.getConfigurationId());
verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
}
@Test
public void connectConfigurationToPnfObjectTest() throws Exception {
doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
-
- Pnf primaryPnf = serviceProxy.getServiceInstance().getPnfs().stream().filter(o -> o.getRole().equals("Primary")).findFirst().get();
-
- aaiConfigurationResources.connectConfigurationToPnfObject(primaryPnf.getPnfId(), configuration.getConfigurationId());
+
+ Pnf primaryPnf = serviceProxy.getServiceInstance().getPnfs().stream().filter(o -> o.getRole().equals("Primary"))
+ .findFirst().get();
+
+ aaiConfigurationResources.connectConfigurationToPnfObject(primaryPnf.getPnfId(),
+ configuration.getConfigurationId());
verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
}
@Test
public void getConfigurationTest() {
AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, "configurationId");
- doReturn(Optional.of(new org.onap.aai.domain.yang.Configuration())).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.Configuration.class, aaiResourceUri);
+ doReturn(Optional.of(new org.onap.aai.domain.yang.Configuration())).when(MOCK_aaiResourcesClient)
+ .get(org.onap.aai.domain.yang.Configuration.class, aaiResourceUri);
aaiConfigurationResources.getConfiguration("configurationId");
verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.Configuration.class, aaiResourceUri);
}
@@ -203,13 +221,14 @@ public class AAIConfigurationResourcesTest extends TestDataSetup{
aaiConfigurationResources.deleteConfiguration("configurationId");
verify(MOCK_aaiResourcesClient, times(1)).delete(aaiResourceUri);
}
-
+
@Test
- public void updateOrchestrationStatusConfigurationTest() throws Exception {
- configuration.setOrchestrationStatus(OrchestrationStatus.ACTIVE);
- doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Configuration.class));
- aaiConfigurationResources.updateOrchestrationStatusConfiguration(configuration,OrchestrationStatus.ACTIVE);
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
- assertEquals(OrchestrationStatus.ACTIVE, configuration.getOrchestrationStatus());
- }
-} \ No newline at end of file
+ public void updateOrchestrationStatusConfigurationTest() throws Exception {
+ configuration.setOrchestrationStatus(OrchestrationStatus.ACTIVE);
+ doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.Configuration.class));
+ aaiConfigurationResources.updateOrchestrationStatusConfiguration(configuration, OrchestrationStatus.ACTIVE);
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
+ assertEquals(OrchestrationStatus.ACTIVE, configuration.getOrchestrationStatus());
+ }
+}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIInstanceGroupResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIInstanceGroupResourcesTest.java
index 58bcc8b1aa..8c0d27f799 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIInstanceGroupResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIInstanceGroupResourcesTest.java
@@ -28,9 +28,7 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -49,75 +47,88 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.onap.so.client.aai.mapper.AAIObjectMapper;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
+
@RunWith(MockitoJUnitRunner.Silent.class)
-public class AAIInstanceGroupResourcesTest extends TestDataSetup{
-
- @InjectMocks
- private AAIInstanceGroupResources aaiInstanceGroupResources = new AAIInstanceGroupResources();
-
- private InstanceGroup instanceGroup;
- private GenericVnf vnf;
- private ServiceInstance serviceInstance;
-
- @Mock
- protected AAIResourcesClient MOCK_aaiResourcesClient;
-
+public class AAIInstanceGroupResourcesTest extends TestDataSetup {
+
+ @InjectMocks
+ private AAIInstanceGroupResources aaiInstanceGroupResources = new AAIInstanceGroupResources();
+
+ private InstanceGroup instanceGroup;
+ private GenericVnf vnf;
+ private ServiceInstance serviceInstance;
+
+ @Mock
+ protected AAIResourcesClient MOCK_aaiResourcesClient;
+
@Mock
protected AAIObjectMapper MOCK_aaiObjectMapper;
-
+
@Mock
protected InjectionHelper MOCK_injectionHelper;
-
- @Before
- public void before() {
- instanceGroup = buildInstanceGroup();
- vnf = buildGenericVnf();
- serviceInstance = buildServiceInstance();
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- }
-
- @Test
- public void createInstanceGroupTest() throws Exception {
- doReturn(new org.onap.aai.domain.yang.InstanceGroup()).when(MOCK_aaiObjectMapper).mapInstanceGroup(instanceGroup);
- aaiInstanceGroupResources.createInstanceGroup(instanceGroup);
- verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())), isA(Optional.class));
- }
-
- @Test
- public void deleteInstanceGroupTest() throws Exception {
- aaiInstanceGroupResources.deleteInstanceGroup(instanceGroup);
- verify(MOCK_aaiResourcesClient, times(1)).delete(eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())));
- }
-
- @Test
- public void connectInstanceGroupTest() throws Exception {
- aaiInstanceGroupResources.connectInstanceGroupToVnf(instanceGroup, vnf);
- verify(MOCK_aaiResourcesClient, times(1)).connect(eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())), eq(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId())));
- }
-
- @Test
- public void connectInstanceGroupWithEdgeTest() throws Exception {
- aaiInstanceGroupResources.connectInstanceGroupToVnf(instanceGroup, vnf, AAIEdgeLabel.BELONGS_TO);
- verify(MOCK_aaiResourcesClient, times(1)).connect(eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())), eq(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId())), eq(AAIEdgeLabel.BELONGS_TO));
- }
-
- @Test
- public void existsTest() throws Exception {
- aaiInstanceGroupResources.exists(instanceGroup);
- verify(MOCK_aaiResourcesClient, times(1)).exists(eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())));
- }
-
- @Test
- public void createInstanceGroupandConnectServiceInstanceTest() {
- doReturn(new org.onap.aai.domain.yang.InstanceGroup()).when(MOCK_aaiObjectMapper).mapInstanceGroup(instanceGroup);
- doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class), any(Optional.class));
- doNothing().when(MOCK_aaiResourcesClient).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
-
- aaiInstanceGroupResources.createInstanceGroupandConnectServiceInstance(instanceGroup, serviceInstance);
-
- verify(MOCK_aaiObjectMapper, times(1)).mapInstanceGroup(instanceGroup);
- verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
- verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
- }
-
+
+ @Before
+ public void before() {
+ instanceGroup = buildInstanceGroup();
+ vnf = buildGenericVnf();
+ serviceInstance = buildServiceInstance();
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ }
+
+ @Test
+ public void createInstanceGroupTest() throws Exception {
+ doReturn(new org.onap.aai.domain.yang.InstanceGroup()).when(MOCK_aaiObjectMapper)
+ .mapInstanceGroup(instanceGroup);
+ aaiInstanceGroupResources.createInstanceGroup(instanceGroup);
+ verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())),
+ isA(Optional.class));
+ }
+
+ @Test
+ public void deleteInstanceGroupTest() throws Exception {
+ aaiInstanceGroupResources.deleteInstanceGroup(instanceGroup);
+ verify(MOCK_aaiResourcesClient, times(1))
+ .delete(eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())));
+ }
+
+ @Test
+ public void connectInstanceGroupTest() throws Exception {
+ aaiInstanceGroupResources.connectInstanceGroupToVnf(instanceGroup, vnf);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())),
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId())));
+ }
+
+ @Test
+ public void connectInstanceGroupWithEdgeTest() throws Exception {
+ aaiInstanceGroupResources.connectInstanceGroupToVnf(instanceGroup, vnf, AAIEdgeLabel.BELONGS_TO);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())),
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId())),
+ eq(AAIEdgeLabel.BELONGS_TO));
+ }
+
+ @Test
+ public void existsTest() throws Exception {
+ aaiInstanceGroupResources.exists(instanceGroup);
+ verify(MOCK_aaiResourcesClient, times(1))
+ .exists(eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())));
+ }
+
+ @Test
+ public void createInstanceGroupandConnectServiceInstanceTest() {
+ doReturn(new org.onap.aai.domain.yang.InstanceGroup()).when(MOCK_aaiObjectMapper)
+ .mapInstanceGroup(instanceGroup);
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class),
+ any(Optional.class));
+ doNothing().when(MOCK_aaiResourcesClient).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
+
+ aaiInstanceGroupResources.createInstanceGroupandConnectServiceInstance(instanceGroup, serviceInstance);
+
+ verify(MOCK_aaiObjectMapper, times(1)).mapInstanceGroup(instanceGroup);
+ verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
+ verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
+ }
+
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAINetworkResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAINetworkResourcesTest.java
index 8632a6afdd..d41148d784 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAINetworkResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAINetworkResourcesTest.java
@@ -32,13 +32,11 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -68,328 +66,363 @@ import org.onap.so.client.aai.mapper.AAIObjectMapper;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class AAINetworkResourcesTest extends TestDataSetup{
-
- private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
-
- private L3Network network;
- private Collection collection;
- private InstanceGroup instanceGroup;
- private ServiceInstance serviceInstance;
- private CloudRegion cloudRegion;
- private Subnet subnet;
- private NetworkPolicy networkPolicy;
-
- @Mock
- protected AAIResourcesClient MOCK_aaiResourcesClient;
-
+public class AAINetworkResourcesTest extends TestDataSetup {
+
+ private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
+
+ private L3Network network;
+ private Collection collection;
+ private InstanceGroup instanceGroup;
+ private ServiceInstance serviceInstance;
+ private CloudRegion cloudRegion;
+ private Subnet subnet;
+ private NetworkPolicy networkPolicy;
+
+ @Mock
+ protected AAIResourcesClient MOCK_aaiResourcesClient;
+
@Mock
protected AAIObjectMapper MOCK_aaiObjectMapper;
-
+
@Mock
protected InjectionHelper MOCK_injectionHelper;
-
- @InjectMocks
- private AAINetworkResources aaiNetworkResources = new AAINetworkResources();
-
- @Before
- public void before() {
- network = buildL3Network();
-
- collection = buildCollection();
-
- List<L3Network> l3NetworkList = new ArrayList<L3Network>();
- l3NetworkList.add(network);
-
- instanceGroup = buildInstanceGroup();
-
- serviceInstance = buildServiceInstance();
-
- cloudRegion = buildCloudRegion();
-
- subnet = buildSubnet();
-
- networkPolicy = buildNetworkPolicy();
-
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- }
-
-
- @Test
- public void updateNetworkTest() throws Exception {
-
- network.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
-
- doReturn(new org.onap.aai.domain.yang.L3Network()).when(MOCK_aaiObjectMapper).mapNetwork(network);
- doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.L3Network.class));
-
- aaiNetworkResources.updateNetwork(network);
-
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), isA(org.onap.aai.domain.yang.L3Network.class));
- assertEquals(OrchestrationStatus.ASSIGNED, network.getOrchestrationStatus());
- }
-
- @Test
- public void createNetworkConnectToServiceInstanceTest() throws Exception {
-
- network.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
-
- doReturn(new org.onap.aai.domain.yang.L3Network()).when(MOCK_aaiObjectMapper).mapNetwork(network);
- doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
- doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), any(AAIResourceUri.class));
-
- aaiNetworkResources.createNetworkConnectToServiceInstance(network, serviceInstance);
-
- assertEquals(OrchestrationStatus.INVENTORIED, network.getOrchestrationStatus());
+
+ @InjectMocks
+ private AAINetworkResources aaiNetworkResources = new AAINetworkResources();
+
+ @Before
+ public void before() {
+ network = buildL3Network();
+
+ collection = buildCollection();
+
+ List<L3Network> l3NetworkList = new ArrayList<L3Network>();
+ l3NetworkList.add(network);
+
+ instanceGroup = buildInstanceGroup();
+
+ serviceInstance = buildServiceInstance();
+
+ cloudRegion = buildCloudRegion();
+
+ subnet = buildSubnet();
+
+ networkPolicy = buildNetworkPolicy();
+
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ }
+
+
+ @Test
+ public void updateNetworkTest() throws Exception {
+
+ network.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+
+ doReturn(new org.onap.aai.domain.yang.L3Network()).when(MOCK_aaiObjectMapper).mapNetwork(network);
+ doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.L3Network.class));
+
+ aaiNetworkResources.updateNetwork(network);
+
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.L3Network.class));
+ assertEquals(OrchestrationStatus.ASSIGNED, network.getOrchestrationStatus());
+ }
+
+ @Test
+ public void createNetworkConnectToServiceInstanceTest() throws Exception {
+
+ network.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+
+ doReturn(new org.onap.aai.domain.yang.L3Network()).when(MOCK_aaiObjectMapper).mapNetwork(network);
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(any(AAIResourceUri.class),
+ any(Optional.class));
+ doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), any(AAIResourceUri.class));
+
+ aaiNetworkResources.createNetworkConnectToServiceInstance(network, serviceInstance);
+
+ assertEquals(OrchestrationStatus.INVENTORIED, network.getOrchestrationStatus());
verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
- }
-
- @Test
- public void deleteNetworkTest() throws Exception {
-
- network.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
-
- doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
-
- aaiNetworkResources.deleteNetwork(network);
-
- verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
- }
-
- @Test
- public void getVpnBindingTest() throws Exception {
- final String content = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAaiVpnBinding.json")));
- AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
- Optional<VpnBinding> oVpnBinding = Optional.empty();
- AAIResourceUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, "ModelInvariantUUID");
-
- doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
- oVpnBinding = aaiNetworkResources.getVpnBinding(aaiUri);
- verify(MOCK_aaiResourcesClient, times(1)).get(any(AAIResourceUri.class));
-
- if (oVpnBinding.isPresent()) {
- VpnBinding vpnBinding = oVpnBinding.get();
- assertThat(aaiResultWrapper.asBean(VpnBinding.class).get(), sameBeanAs(vpnBinding));
- }
- }
-
- @Test
- public void getNetworkPolicyTest() throws Exception {
- final String content = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAaiNetworkPolicy.json")));
- AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
- Optional<org.onap.aai.domain.yang.NetworkPolicy> oNetPolicy = Optional.empty();
- AAIResourceUri netPolicyUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, "ModelInvariantUUID");
-
- doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
- oNetPolicy = aaiNetworkResources.getNetworkPolicy(netPolicyUri);
- verify(MOCK_aaiResourcesClient, times(1)).get(any(AAIResourceUri.class));
- if (oNetPolicy.isPresent()) {
- org.onap.aai.domain.yang.NetworkPolicy networkPolicy = oNetPolicy.get();
- assertThat(aaiResultWrapper.asBean(org.onap.aai.domain.yang.NetworkPolicy.class).get(), sameBeanAs(networkPolicy));
- }
- }
-
- @Test
- public void getNetworkPoliciesTest() throws Exception {
- final String content = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAaiNetworkPolicies.json")));
- AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
- Optional<org.onap.aai.domain.yang.NetworkPolicies> oNetPolicies = Optional.empty();
- AAIResourceUri netPoliciesUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY);
-
- doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
- oNetPolicies = aaiNetworkResources.getNetworkPolicies(netPoliciesUri);
- verify(MOCK_aaiResourcesClient, times(1)).get(any(AAIResourceUri.class));
- if (oNetPolicies.isPresent()) {
- org.onap.aai.domain.yang.NetworkPolicies networkPolicies = oNetPolicies.get();
- assertThat(aaiResultWrapper.asBean(org.onap.aai.domain.yang.NetworkPolicies.class).get(), sameBeanAs(networkPolicies));
- }
- }
-
- @Test
- public void getRouteTableTest() throws Exception {
- final String content = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAaiNetworkTableRefs.json")));
- AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
- Optional<RouteTableReference> oRtref = Optional.empty();
- AAIResourceUri rTRefUri = AAIUriFactory.createResourceUri(AAIObjectType.ROUTE_TABLE_REFERENCE, "ModelInvariantUUID");
-
- doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
- oRtref = aaiNetworkResources.getRouteTable(rTRefUri);
- verify(MOCK_aaiResourcesClient, times(1)).get(any(AAIResourceUri.class));
-
- if (oRtref.isPresent()) {
- RouteTableReference rTref = oRtref.get();
- assertThat(aaiResultWrapper.asBean(RouteTableReference.class).get(), sameBeanAs(rTref));
- }
- }
-
- @Test
- public void queryNetworkByIdTest() throws Exception {
- final String content = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiQueryAAIResponse-Wrapper.json")));
- AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
- L3Network network = new L3Network();
- network.setNetworkId("0384d743-f69b-4cc8-9aa8-c3ae66662c44");
- network.setNetworkName("Dev_Bindings_1802_020118");
- network.setOrchestrationStatus(OrchestrationStatus.CREATED);
-
- doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
- Optional<org.onap.aai.domain.yang.L3Network> l3NetworkOpt = aaiNetworkResources.queryNetworkById(network);
- org.onap.aai.domain.yang.L3Network l3Network = l3NetworkOpt.isPresent() ? l3NetworkOpt.get() : null;
-
- verify(MOCK_aaiResourcesClient, times(1)).get(isA(AAIResourceUri.class));
- assertNotNull(l3Network);
- assertEquals("0384d743-f69b-4cc8-9aa8-c3ae66662c44", l3Network.getNetworkId());
- assertEquals("Dev_Bindings_1802_020118", l3Network.getNetworkName());
- }
-
- @Test
- public void queryNetworkWrapperByIdTest() throws Exception {
- final String content = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiQueryAAIResponse-Wrapper.json")));
- AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
- L3Network network = new L3Network();
- network.setNetworkId("0384d743-f69b-4cc8-9aa8-c3ae66662c44");
- network.setNetworkName("Dev_Bindings_1802_020118");
- network.setOrchestrationStatus(OrchestrationStatus.CREATED);
-
- doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
- AAIResultWrapper result = aaiNetworkResources.queryNetworkWrapperById(network);
-
- verify(MOCK_aaiResourcesClient, times(1)).get(isA(AAIResourceUri.class));
- assertEquals(aaiResultWrapper.getJson(), result.getJson());
- assertNotNull(result);
- Optional<Relationships> resultNetworkRelationships = result.getRelationships();
- assertTrue(resultNetworkRelationships.isPresent());
- Optional<org.onap.aai.domain.yang.L3Network> aaiL3Network = result.asBean(org.onap.aai.domain.yang.L3Network.class);
- assertEquals(network.getNetworkId(),aaiL3Network.get().getNetworkId());
- assertEquals(network.getNetworkName(),aaiL3Network.get().getNetworkName());
-
-
- }
-
- @Test
- public void createNetworkCollectionTest() throws Exception {
-
- doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Collection.class));
- doReturn(new org.onap.aai.domain.yang.Collection()).when(MOCK_aaiObjectMapper).mapCollection(collection);
- collection.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
-
- aaiNetworkResources.createNetworkCollection(collection);
- assertEquals(OrchestrationStatus.INVENTORIED, collection.getOrchestrationStatus());
- verify(MOCK_aaiResourcesClient, times(1)).create(any(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Collection.class));
- }
-
- @Test
- public void createNetworkInstanceGroupTest() throws Exception {
- doReturn(new org.onap.aai.domain.yang.InstanceGroup()).when(MOCK_aaiObjectMapper).mapInstanceGroup(instanceGroup);
- doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.InstanceGroup.class));
- aaiNetworkResources.createNetworkInstanceGroup(instanceGroup);
- verify(MOCK_aaiResourcesClient, times(1)).create(any(AAIResourceUri.class), isA(org.onap.aai.domain.yang.InstanceGroup.class));
- }
-
- @Test
- public void connectNetworkToNetworkCollectionInstanceGroupTest() throws Exception {
- aaiNetworkResources.connectNetworkToNetworkCollectionInstanceGroup(network, instanceGroup);
- verify(MOCK_aaiResourcesClient, times(1)).connect(eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())), eq(AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId())));
- }
-
- @Test
- public void connectNetworkToNetworkCollectionServiceInstanceTest() throws Exception {
- aaiNetworkResources.connectNetworkToNetworkCollectionServiceInstance(network, serviceInstance);
- verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), eq(AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId())));
- }
-
- @Test
- public void connectNetworkToCloudRegionTest() throws Exception {
- aaiNetworkResources.connectNetworkToCloudRegion(network, cloudRegion);
- verify(MOCK_aaiResourcesClient, times(1)).connect(eq(AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId())),eq(AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION,
- cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId())));
- }
-
- @Test
- public void connectNetworkToTenantTest() throws Exception {
- aaiNetworkResources.connectNetworkToTenant(network, cloudRegion);
- verify(MOCK_aaiResourcesClient, times(1)).connect(eq(AAIUriFactory.createResourceUri(AAIObjectType.TENANT,
- cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), cloudRegion.getTenantId())),
- eq(AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId())));
- }
-
- @Test
- public void connectNetworkCollectionInstanceGroupToNetworkCollectionTest() throws Exception {
- aaiNetworkResources.connectNetworkCollectionInstanceGroupToNetworkCollection(instanceGroup, collection);
- verify(MOCK_aaiResourcesClient, times(1)).connect(eq(AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, collection.getId())), eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())));
- }
-
- @Test
- public void connectNetworkCollectionToServiceInstanceTest() throws Exception {
- aaiNetworkResources.connectNetworkCollectionToServiceInstance(collection, serviceInstance);
- verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
- }
-
- @Test
- public void deleteCollectionTest() throws Exception {
- doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
- aaiNetworkResources.deleteCollection(collection);
- verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
- }
-
- @Test
- public void deleteInstanceGroupTest() throws Exception {
- doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
- aaiNetworkResources.deleteNetworkInstanceGroup(instanceGroup);
- verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
- }
-
- @Test
- public void updateSubnetTest() throws Exception {
-
- doReturn(new org.onap.aai.domain.yang.Subnet()).when(MOCK_aaiObjectMapper).mapSubnet(subnet);
- doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Subnet.class));
-
- aaiNetworkResources.updateSubnet(network, subnet);
-
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Subnet.class));
- }
-
- @Test
- public void connectInstanceGroupToCloudRegionTest() throws Exception {
- aaiNetworkResources.connectInstanceGroupToCloudRegion(instanceGroup, cloudRegion);
- verify(MOCK_aaiResourcesClient, times(1)).connect(
- eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())),
- eq(AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId())),
- eq(AAIEdgeLabel.USES));
- }
-
- @Test
- public void getSubnetTest() throws Exception {
- final String content = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiSubnetsMapped_to_aai.json")));
- AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
- Optional<org.onap.aai.domain.yang.Subnet> oSubnet = Optional.empty();
- AAIResourceUri subnetUri = AAIUriFactory.createResourceUri(AAIObjectType.SUBNET, "ModelInvariantUUID", "serviceModelVersionId");
-
- doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
- oSubnet = aaiNetworkResources.getSubnet(subnetUri);
- verify(MOCK_aaiResourcesClient, times(1)).get(any(AAIResourceUri.class));
-
- if (oSubnet.isPresent()) {
- org.onap.aai.domain.yang.Subnet subnet = oSubnet.get();
- assertThat(aaiResultWrapper.asBean(org.onap.aai.domain.yang.Subnet.class).get(), sameBeanAs(subnet));
- }
- }
-
- @Test
- public void createNetworkPolicyTest() throws Exception {
- doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.NetworkPolicy.class));
- doReturn(new org.onap.aai.domain.yang.NetworkPolicy()).when(MOCK_aaiObjectMapper).mapNetworkPolicy(networkPolicy);
- aaiNetworkResources.createNetworkPolicy(networkPolicy);
- verify(MOCK_aaiResourcesClient, times(1)).create(any(AAIResourceUri.class), isA(org.onap.aai.domain.yang.NetworkPolicy.class));
- }
-
- @Test
- public void deleteNetworkPolicyTest() throws Exception {
- doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
- aaiNetworkResources.deleteNetworkPolicy(networkPolicy.getNetworkPolicyId());
- verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
- }
-
+ }
+
+ @Test
+ public void deleteNetworkTest() throws Exception {
+
+ network.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
+
+ doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
+
+ aaiNetworkResources.deleteNetwork(network);
+
+ verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
+ }
+
+ @Test
+ public void getVpnBindingTest() throws Exception {
+ final String content =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAaiVpnBinding.json")));
+ AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
+ Optional<VpnBinding> oVpnBinding = Optional.empty();
+ AAIResourceUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, "ModelInvariantUUID");
+
+ doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
+ oVpnBinding = aaiNetworkResources.getVpnBinding(aaiUri);
+ verify(MOCK_aaiResourcesClient, times(1)).get(any(AAIResourceUri.class));
+
+ if (oVpnBinding.isPresent()) {
+ VpnBinding vpnBinding = oVpnBinding.get();
+ assertThat(aaiResultWrapper.asBean(VpnBinding.class).get(), sameBeanAs(vpnBinding));
+ }
+ }
+
+ @Test
+ public void getNetworkPolicyTest() throws Exception {
+ final String content =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAaiNetworkPolicy.json")));
+ AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
+ Optional<org.onap.aai.domain.yang.NetworkPolicy> oNetPolicy = Optional.empty();
+ AAIResourceUri netPolicyUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, "ModelInvariantUUID");
+
+ doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
+ oNetPolicy = aaiNetworkResources.getNetworkPolicy(netPolicyUri);
+ verify(MOCK_aaiResourcesClient, times(1)).get(any(AAIResourceUri.class));
+ if (oNetPolicy.isPresent()) {
+ org.onap.aai.domain.yang.NetworkPolicy networkPolicy = oNetPolicy.get();
+ assertThat(aaiResultWrapper.asBean(org.onap.aai.domain.yang.NetworkPolicy.class).get(),
+ sameBeanAs(networkPolicy));
+ }
+ }
+
+ @Test
+ public void getNetworkPoliciesTest() throws Exception {
+ final String content =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAaiNetworkPolicies.json")));
+ AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
+ Optional<org.onap.aai.domain.yang.NetworkPolicies> oNetPolicies = Optional.empty();
+ AAIResourceUri netPoliciesUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY);
+
+ doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
+ oNetPolicies = aaiNetworkResources.getNetworkPolicies(netPoliciesUri);
+ verify(MOCK_aaiResourcesClient, times(1)).get(any(AAIResourceUri.class));
+ if (oNetPolicies.isPresent()) {
+ org.onap.aai.domain.yang.NetworkPolicies networkPolicies = oNetPolicies.get();
+ assertThat(aaiResultWrapper.asBean(org.onap.aai.domain.yang.NetworkPolicies.class).get(),
+ sameBeanAs(networkPolicies));
+ }
+ }
+
+ @Test
+ public void getRouteTableTest() throws Exception {
+ final String content =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "queryAaiNetworkTableRefs.json")));
+ AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
+ Optional<RouteTableReference> oRtref = Optional.empty();
+ AAIResourceUri rTRefUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.ROUTE_TABLE_REFERENCE, "ModelInvariantUUID");
+
+ doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
+ oRtref = aaiNetworkResources.getRouteTable(rTRefUri);
+ verify(MOCK_aaiResourcesClient, times(1)).get(any(AAIResourceUri.class));
+
+ if (oRtref.isPresent()) {
+ RouteTableReference rTref = oRtref.get();
+ assertThat(aaiResultWrapper.asBean(RouteTableReference.class).get(), sameBeanAs(rTref));
+ }
+ }
+
+ @Test
+ public void queryNetworkByIdTest() throws Exception {
+ final String content =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiQueryAAIResponse-Wrapper.json")));
+ AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
+ L3Network network = new L3Network();
+ network.setNetworkId("0384d743-f69b-4cc8-9aa8-c3ae66662c44");
+ network.setNetworkName("Dev_Bindings_1802_020118");
+ network.setOrchestrationStatus(OrchestrationStatus.CREATED);
+
+ doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
+ Optional<org.onap.aai.domain.yang.L3Network> l3NetworkOpt = aaiNetworkResources.queryNetworkById(network);
+ org.onap.aai.domain.yang.L3Network l3Network = l3NetworkOpt.isPresent() ? l3NetworkOpt.get() : null;
+
+ verify(MOCK_aaiResourcesClient, times(1)).get(isA(AAIResourceUri.class));
+ assertNotNull(l3Network);
+ assertEquals("0384d743-f69b-4cc8-9aa8-c3ae66662c44", l3Network.getNetworkId());
+ assertEquals("Dev_Bindings_1802_020118", l3Network.getNetworkName());
+ }
+
+ @Test
+ public void queryNetworkWrapperByIdTest() throws Exception {
+ final String content =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiQueryAAIResponse-Wrapper.json")));
+ AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
+ L3Network network = new L3Network();
+ network.setNetworkId("0384d743-f69b-4cc8-9aa8-c3ae66662c44");
+ network.setNetworkName("Dev_Bindings_1802_020118");
+ network.setOrchestrationStatus(OrchestrationStatus.CREATED);
+
+ doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
+ AAIResultWrapper result = aaiNetworkResources.queryNetworkWrapperById(network);
+
+ verify(MOCK_aaiResourcesClient, times(1)).get(isA(AAIResourceUri.class));
+ assertEquals(aaiResultWrapper.getJson(), result.getJson());
+ assertNotNull(result);
+ Optional<Relationships> resultNetworkRelationships = result.getRelationships();
+ assertTrue(resultNetworkRelationships.isPresent());
+ Optional<org.onap.aai.domain.yang.L3Network> aaiL3Network =
+ result.asBean(org.onap.aai.domain.yang.L3Network.class);
+ assertEquals(network.getNetworkId(), aaiL3Network.get().getNetworkId());
+ assertEquals(network.getNetworkName(), aaiL3Network.get().getNetworkName());
+
+
+ }
+
+ @Test
+ public void createNetworkCollectionTest() throws Exception {
+
+ doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.Collection.class));
+ doReturn(new org.onap.aai.domain.yang.Collection()).when(MOCK_aaiObjectMapper).mapCollection(collection);
+ collection.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+
+ aaiNetworkResources.createNetworkCollection(collection);
+ assertEquals(OrchestrationStatus.INVENTORIED, collection.getOrchestrationStatus());
+ verify(MOCK_aaiResourcesClient, times(1)).create(any(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.Collection.class));
+ }
+
+ @Test
+ public void createNetworkInstanceGroupTest() throws Exception {
+ doReturn(new org.onap.aai.domain.yang.InstanceGroup()).when(MOCK_aaiObjectMapper)
+ .mapInstanceGroup(instanceGroup);
+ doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.InstanceGroup.class));
+ aaiNetworkResources.createNetworkInstanceGroup(instanceGroup);
+ verify(MOCK_aaiResourcesClient, times(1)).create(any(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.InstanceGroup.class));
+ }
+
+ @Test
+ public void connectNetworkToNetworkCollectionInstanceGroupTest() throws Exception {
+ aaiNetworkResources.connectNetworkToNetworkCollectionInstanceGroup(network, instanceGroup);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())),
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId())));
+ }
+
+ @Test
+ public void connectNetworkToNetworkCollectionServiceInstanceTest() throws Exception {
+ aaiNetworkResources.connectNetworkToNetworkCollectionServiceInstance(network, serviceInstance);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class),
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId())));
+ }
+
+ @Test
+ public void connectNetworkToCloudRegionTest() throws Exception {
+ aaiNetworkResources.connectNetworkToCloudRegion(network, cloudRegion);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId())),
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId())));
+ }
+
+ @Test
+ public void connectNetworkToTenantTest() throws Exception {
+ aaiNetworkResources.connectNetworkToTenant(network, cloudRegion);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId(), cloudRegion.getTenantId())),
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, network.getNetworkId())));
+ }
+
+ @Test
+ public void connectNetworkCollectionInstanceGroupToNetworkCollectionTest() throws Exception {
+ aaiNetworkResources.connectNetworkCollectionInstanceGroupToNetworkCollection(instanceGroup, collection);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, collection.getId())),
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())));
+ }
+
+ @Test
+ public void connectNetworkCollectionToServiceInstanceTest() throws Exception {
+ aaiNetworkResources.connectNetworkCollectionToServiceInstance(collection, serviceInstance);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
+ }
+
+ @Test
+ public void deleteCollectionTest() throws Exception {
+ doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
+ aaiNetworkResources.deleteCollection(collection);
+ verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
+ }
+
+ @Test
+ public void deleteInstanceGroupTest() throws Exception {
+ doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
+ aaiNetworkResources.deleteNetworkInstanceGroup(instanceGroup);
+ verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
+ }
+
+ @Test
+ public void updateSubnetTest() throws Exception {
+
+ doReturn(new org.onap.aai.domain.yang.Subnet()).when(MOCK_aaiObjectMapper).mapSubnet(subnet);
+ doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.Subnet.class));
+
+ aaiNetworkResources.updateSubnet(network, subnet);
+
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.Subnet.class));
+ }
+
+ @Test
+ public void connectInstanceGroupToCloudRegionTest() throws Exception {
+ aaiNetworkResources.connectInstanceGroupToCloudRegion(instanceGroup, cloudRegion);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroup.getId())),
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId())),
+ eq(AAIEdgeLabel.USES));
+ }
+
+ @Test
+ public void getSubnetTest() throws Exception {
+ final String content =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiSubnetsMapped_to_aai.json")));
+ AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
+ Optional<org.onap.aai.domain.yang.Subnet> oSubnet = Optional.empty();
+ AAIResourceUri subnetUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.SUBNET, "ModelInvariantUUID", "serviceModelVersionId");
+
+ doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
+ oSubnet = aaiNetworkResources.getSubnet(subnetUri);
+ verify(MOCK_aaiResourcesClient, times(1)).get(any(AAIResourceUri.class));
+
+ if (oSubnet.isPresent()) {
+ org.onap.aai.domain.yang.Subnet subnet = oSubnet.get();
+ assertThat(aaiResultWrapper.asBean(org.onap.aai.domain.yang.Subnet.class).get(), sameBeanAs(subnet));
+ }
+ }
+
+ @Test
+ public void createNetworkPolicyTest() throws Exception {
+ doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.NetworkPolicy.class));
+ doReturn(new org.onap.aai.domain.yang.NetworkPolicy()).when(MOCK_aaiObjectMapper)
+ .mapNetworkPolicy(networkPolicy);
+ aaiNetworkResources.createNetworkPolicy(networkPolicy);
+ verify(MOCK_aaiResourcesClient, times(1)).create(any(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.NetworkPolicy.class));
+ }
+
+ @Test
+ public void deleteNetworkPolicyTest() throws Exception {
+ doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
+ aaiNetworkResources.deleteNetworkPolicy(networkPolicy.getNetworkPolicyId());
+ verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
+ }
+
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIServiceInstanceResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIServiceInstanceResourcesTest.java
index a4b59f1f81..14df832754 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIServiceInstanceResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIServiceInstanceResourcesTest.java
@@ -28,9 +28,7 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -51,36 +49,36 @@ import org.onap.so.client.aai.mapper.AAIObjectMapper;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class AAIServiceInstanceResourcesTest extends TestDataSetup{
-
+public class AAIServiceInstanceResourcesTest extends TestDataSetup {
+
@InjectMocks
private AAIServiceInstanceResources aaiServiceInstanceResources = new AAIServiceInstanceResources();
-
+
@Mock
- protected AAIResourcesClient MOCK_aaiResourcesClient;
-
+ protected AAIResourcesClient MOCK_aaiResourcesClient;
+
@Mock
protected AAIObjectMapper MOCK_aaiObjectMapper;
-
+
@Mock
protected InjectionHelper MOCK_injectionHelper;
-
+
private ServiceInstance serviceInstance;
private ServiceSubscription serviceSubscription;
private Customer customer;
private Project project;
private OwningEntity owningEntity;
-
+
@Before
public void before() {
- serviceInstance = buildServiceInstance();
- serviceSubscription = buildServiceSubscription();
- customer = buildCustomer();
- project = buildProject();
- owningEntity = buildOwningEntity();
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ serviceInstance = buildServiceInstance();
+ serviceSubscription = buildServiceSubscription();
+ customer = buildCustomer();
+ project = buildProject();
+ owningEntity = buildOwningEntity();
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
}
-
+
@Test
public void deleteServiceInstanceSuccessTest() throws Exception {
aaiServiceInstanceResources.deleteServiceInstance(serviceInstance);
@@ -104,34 +102,37 @@ public class AAIServiceInstanceResourcesTest extends TestDataSetup{
public void createServiceSubscriptionTest() {
serviceSubscription.setServiceType("IP-FLEX");
customer.setServiceSubscription(serviceSubscription);
- doReturn(new org.onap.aai.domain.yang.ServiceSubscription()).when(MOCK_aaiObjectMapper).mapServiceSubscription(customer.getServiceSubscription());
+ doReturn(new org.onap.aai.domain.yang.ServiceSubscription()).when(MOCK_aaiObjectMapper)
+ .mapServiceSubscription(customer.getServiceSubscription());
aaiServiceInstanceResources.createServiceSubscription(customer);
verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
}
@Test
public void createServiceInstanceTest() {
- serviceSubscription.setServiceType("testSubscriberType");
+ serviceSubscription.setServiceType("testSubscriberType");
customer.setServiceSubscription(serviceSubscription);
- doReturn(new org.onap.aai.domain.yang.ServiceInstance()).when(MOCK_aaiObjectMapper).mapServiceInstance(serviceInstance);
+ doReturn(new org.onap.aai.domain.yang.ServiceInstance()).when(MOCK_aaiObjectMapper)
+ .mapServiceInstance(serviceInstance);
serviceInstance.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
-
+
aaiServiceInstanceResources.createServiceInstance(serviceInstance, customer);
-
+
assertEquals(OrchestrationStatus.INVENTORIED, serviceInstance.getOrchestrationStatus());
verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
}
@Test
public void createProjectTest() {
- doReturn(new org.onap.aai.domain.yang.Project()).when(MOCK_aaiObjectMapper).mapProject(project);
+ doReturn(new org.onap.aai.domain.yang.Project()).when(MOCK_aaiObjectMapper).mapProject(project);
aaiServiceInstanceResources.createProject(project);
verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
}
@Test
public void createProjectandConnectServiceInstanceTest() {
- doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(any(AAIResourceUri.class),
+ any(Optional.class));
doNothing().when(MOCK_aaiResourcesClient).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
doReturn(new org.onap.aai.domain.yang.Project()).when(MOCK_aaiObjectMapper).mapProject(project);
aaiServiceInstanceResources.createProjectandConnectServiceInstance(project, serviceInstance);
@@ -141,7 +142,7 @@ public class AAIServiceInstanceResourcesTest extends TestDataSetup{
@Test
public void createOwningEntityTest() {
- doReturn(new org.onap.aai.domain.yang.OwningEntity()).when(MOCK_aaiObjectMapper).mapOwningEntity(owningEntity);
+ doReturn(new org.onap.aai.domain.yang.OwningEntity()).when(MOCK_aaiObjectMapper).mapOwningEntity(owningEntity);
aaiServiceInstanceResources.createOwningEntity(owningEntity);
verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
}
@@ -160,7 +161,8 @@ public class AAIServiceInstanceResourcesTest extends TestDataSetup{
@Test
public void createOwningEntityandConnectServiceInstanceTest() {
- doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(any(AAIResourceUri.class),
+ any(Optional.class));
doNothing().when(MOCK_aaiResourcesClient).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
doReturn(new org.onap.aai.domain.yang.OwningEntity()).when(MOCK_aaiObjectMapper).mapOwningEntity(owningEntity);
aaiServiceInstanceResources.createOwningEntityandConnectServiceInstance(owningEntity, serviceInstance);
@@ -171,14 +173,17 @@ public class AAIServiceInstanceResourcesTest extends TestDataSetup{
@Test
@Ignore
public void updateOrchestrationStatusServiceInstanceTest() {
- aaiServiceInstanceResources.updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ACTIVE);
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), any(org.onap.aai.domain.yang.ServiceInstance.class));
+ aaiServiceInstanceResources.updateOrchestrationStatusServiceInstance(serviceInstance,
+ OrchestrationStatus.ACTIVE);
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class),
+ any(org.onap.aai.domain.yang.ServiceInstance.class));
}
@Test
@Ignore
public void test_updateServiceInstance() {
aaiServiceInstanceResources.updateServiceInstance(serviceInstance);
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), any(org.onap.aai.domain.yang.ServiceInstance.class));
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class),
+ any(org.onap.aai.domain.yang.ServiceInstance.class));
}
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVfModuleResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVfModuleResourcesTest.java
index a8200caf79..ae3ebeddbd 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVfModuleResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVfModuleResourcesTest.java
@@ -27,9 +27,7 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -49,106 +47,111 @@ import org.onap.so.client.aai.mapper.AAIObjectMapper;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class AAIVfModuleResourcesTest extends TestDataSetup{
- @InjectMocks
- private AAIVfModuleResources aaiVfModuleResources = new AAIVfModuleResources();
-
- private VfModule vfModule;
- private GenericVnf vnf;
-
- @Mock
- protected AAIResourcesClient MOCK_aaiResourcesClient;
-
- @Mock
- protected AAIObjectMapper MOCK_aaiObjectMapper;
-
- @Mock
- protected InjectionHelper MOCK_injectionHelper;
-
- @Before
- public void before() {
- vfModule = buildVfModule();
- vnf = buildGenericVnf();
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- }
-
- @Test
- public void updateOrchestrationStatusVfModuleTest() throws Exception {
- vfModule.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
-
- doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.VfModule.class));
-
- aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule, vnf, OrchestrationStatus.ACTIVE);
-
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class),ArgumentMatchers.isNull());
-
- assertEquals(OrchestrationStatus.ACTIVE, vfModule.getOrchestrationStatus());
- }
-
- @Test
- public void createVfModuleTest() throws Exception {
- vfModule.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
-
- doReturn(new org.onap.aai.domain.yang.VfModule()).when(MOCK_aaiObjectMapper).mapVfModule(vfModule);
- doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class), any(Optional.class));
- aaiVfModuleResources.createVfModule(vfModule, vnf);
-
- verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
- assertEquals(OrchestrationStatus.INVENTORIED, vfModule.getOrchestrationStatus());
- }
-
- @Test
- public void deleteVfModuleTest() throws Exception {
- doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
-
- aaiVfModuleResources.deleteVfModule(vfModule, vnf);
-
- verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
- }
-
- @Test
- public void changeAssignVfModuleTest() throws Exception {
- doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.VfModule.class));
-
- aaiVfModuleResources.changeAssignVfModule(vfModule, vnf);
-
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
- }
-
- @Test
- public void connectVfModuleToVolumeGroupTest() throws Exception {
- VolumeGroup volumeGroup = buildVolumeGroup();
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
-
- CloudRegion cloudRegion = buildCloudRegion();
-
- aaiVfModuleResources.connectVfModuleToVolumeGroup(vnf, vfModule, volumeGroup, cloudRegion);
- verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
- }
-
- @Test
- public void updateHeatStackIdVfModuleTest() throws Exception {
- vfModule.setHeatStackId("testHeatStackId");
-
- doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.VfModule.class));
-
- aaiVfModuleResources.updateHeatStackIdVfModule(vfModule, vnf);
-
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class),ArgumentMatchers.isNull());
-
- assertEquals("testHeatStackId", vfModule.getHeatStackId());
- }
-
- @Test
- public void updateContrailServiceInstanceFqdnVfModuleTest() throws Exception {
- vfModule.setContrailServiceInstanceFqdn("testContrailServiceInstanceFqdn");
-
- doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.VfModule.class));
-
- aaiVfModuleResources.updateContrailServiceInstanceFqdnVfModule(vfModule, vnf);
-
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class),ArgumentMatchers.isNull());
-
- assertEquals("testContrailServiceInstanceFqdn", vfModule.getContrailServiceInstanceFqdn());
- }
+public class AAIVfModuleResourcesTest extends TestDataSetup {
+ @InjectMocks
+ private AAIVfModuleResources aaiVfModuleResources = new AAIVfModuleResources();
+
+ private VfModule vfModule;
+ private GenericVnf vnf;
+
+ @Mock
+ protected AAIResourcesClient MOCK_aaiResourcesClient;
+
+ @Mock
+ protected AAIObjectMapper MOCK_aaiObjectMapper;
+
+ @Mock
+ protected InjectionHelper MOCK_injectionHelper;
+
+ @Before
+ public void before() {
+ vfModule = buildVfModule();
+ vnf = buildGenericVnf();
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ }
+
+ @Test
+ public void updateOrchestrationStatusVfModuleTest() throws Exception {
+ vfModule.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+
+ doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.VfModule.class));
+
+ aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule, vnf, OrchestrationStatus.ACTIVE);
+
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
+
+ assertEquals(OrchestrationStatus.ACTIVE, vfModule.getOrchestrationStatus());
+ }
+
+ @Test
+ public void createVfModuleTest() throws Exception {
+ vfModule.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+
+ doReturn(new org.onap.aai.domain.yang.VfModule()).when(MOCK_aaiObjectMapper).mapVfModule(vfModule);
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class),
+ any(Optional.class));
+ aaiVfModuleResources.createVfModule(vfModule, vnf);
+
+ verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
+ assertEquals(OrchestrationStatus.INVENTORIED, vfModule.getOrchestrationStatus());
+ }
+
+ @Test
+ public void deleteVfModuleTest() throws Exception {
+ doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
+
+ aaiVfModuleResources.deleteVfModule(vfModule, vnf);
+
+ verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
+ }
+
+ @Test
+ public void changeAssignVfModuleTest() throws Exception {
+ doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.VfModule.class));
+
+ aaiVfModuleResources.changeAssignVfModule(vfModule, vnf);
+
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
+ }
+
+ @Test
+ public void connectVfModuleToVolumeGroupTest() throws Exception {
+ VolumeGroup volumeGroup = buildVolumeGroup();
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+
+ CloudRegion cloudRegion = buildCloudRegion();
+
+ aaiVfModuleResources.connectVfModuleToVolumeGroup(vnf, vfModule, volumeGroup, cloudRegion);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
+ }
+
+ @Test
+ public void updateHeatStackIdVfModuleTest() throws Exception {
+ vfModule.setHeatStackId("testHeatStackId");
+
+ doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.VfModule.class));
+
+ aaiVfModuleResources.updateHeatStackIdVfModule(vfModule, vnf);
+
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
+
+ assertEquals("testHeatStackId", vfModule.getHeatStackId());
+ }
+
+ @Test
+ public void updateContrailServiceInstanceFqdnVfModuleTest() throws Exception {
+ vfModule.setContrailServiceInstanceFqdn("testContrailServiceInstanceFqdn");
+
+ doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.VfModule.class));
+
+ aaiVfModuleResources.updateContrailServiceInstanceFqdnVfModule(vfModule, vnf);
+
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
+
+ assertEquals("testContrailServiceInstanceFqdn", vfModule.getContrailServiceInstanceFqdn());
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java
index d499bcd36e..cdc601c1e4 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java
@@ -29,10 +29,8 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.io.IOException;
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -58,159 +56,175 @@ import org.onap.so.db.catalog.beans.OrchestrationStatus;
@RunWith(MockitoJUnitRunner.Silent.class)
public class AAIVnfResourcesTest extends TestDataSetup {
- private GenericVnf genericVnf;
-
- private ServiceInstance serviceInstance;
-
- private CloudRegion cloudRegion;
-
- @Mock
- protected AAIResourcesClient MOCK_aaiResourcesClient;
-
- @Mock
- protected AAIObjectMapper MOCK_aaiObjectMapper;
-
- @Mock
- protected InjectionHelper MOCK_injectionHelper;
-
- @Mock
- protected AAIValidatorImpl MOCK_aaiValidatorImpl;
-
- @InjectMocks
- AAIVnfResources aaiVnfResources = new AAIVnfResources();
-
- @Before
- public void before() {
- serviceInstance = buildServiceInstance();
- genericVnf = buildGenericVnf();
- cloudRegion = buildCloudRegion();
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- }
-
- @Test
- public void createVnfandConnectServiceInstanceTest() {
- doReturn(new org.onap.aai.domain.yang.GenericVnf()).when(MOCK_aaiObjectMapper).mapVnf(genericVnf);
- doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class), any(Optional.class));
- doNothing().when(MOCK_aaiResourcesClient).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
- genericVnf.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
-
- aaiVnfResources.createVnfandConnectServiceInstance(genericVnf, serviceInstance);
-
- assertEquals(OrchestrationStatus.INVENTORIED, genericVnf.getOrchestrationStatus());
- verify(MOCK_aaiObjectMapper, times(1)).mapVnf(genericVnf);
- verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
- verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
- }
-
- @Test
- public void createPlatformandConnectVnfTest() {
- Platform platform = new Platform();
- platform.setPlatformName("a123");
- doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class),isA(AAIResourceUri.class));
- doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class), any(Optional.class));
- aaiVnfResources.createPlatformandConnectVnf(platform, genericVnf);
- verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class),isA(AAIResourceUri.class));
- }
-
- @Test
- public void createLineOfBusinessandConnectVnfTest() {
- LineOfBusiness lob = new LineOfBusiness();
- lob.setLineOfBusinessName("a123");
- doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class),isA(AAIResourceUri.class));
- doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class), any(Optional.class));
- aaiVnfResources.createLineOfBusinessandConnectVnf(lob, genericVnf);
- verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class),isA(AAIResourceUri.class));
- }
-
- @Test
- public void deleteVnfTest() {
- doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
-
- aaiVnfResources.deleteVnf(genericVnf);
-
- verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
- }
-
- @Test
- public void updateOrchestrationStatusVnfTest() {
- doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Vnf.class));
-
- aaiVnfResources.updateOrchestrationStatusVnf(genericVnf, OrchestrationStatus.ACTIVE);
-
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
-
- assertEquals(OrchestrationStatus.ACTIVE, genericVnf.getOrchestrationStatus());
- }
-
- @Test
- public void updateObjectVnfTest() {
- doReturn(new org.onap.aai.domain.yang.GenericVnf()).when(MOCK_aaiObjectMapper).mapVnf(genericVnf);
- doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.GenericVnf.class));
-
- aaiVnfResources.updateObjectVnf(genericVnf);
-
- verify(MOCK_aaiObjectMapper, times(1)).mapVnf(genericVnf);
- verify(MOCK_aaiResourcesClient, times(1)).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.GenericVnf.class));
- }
-
- @Test
- public void getGenericVnfTest () {
- Optional<org.onap.aai.domain.yang.GenericVnf> vnf = Optional.of(new org.onap.aai.domain.yang.GenericVnf());
- vnf.get().setVnfId("vnfId");
- doReturn(vnf).when(MOCK_aaiResourcesClient).get(eq(org.onap.aai.domain.yang.GenericVnf.class),isA(AAIResourceUri.class));
- aaiVnfResources.getGenericVnf("vnfId");
- verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.GenericVnf.class),isA(AAIResourceUri.class));
- }
-
- @Test
- public void checkInMaintFlagTest () {
- Optional<org.onap.aai.domain.yang.GenericVnf> vnf = Optional.of(new org.onap.aai.domain.yang.GenericVnf());
- vnf.get().setVnfId("vnfId");
- vnf.get().setInMaint(true);
- doReturn(vnf).when(MOCK_aaiResourcesClient).get(eq(org.onap.aai.domain.yang.GenericVnf.class),isA(AAIResourceUri.class));
- boolean inMaintFlag = aaiVnfResources.checkInMaintFlag("vnfId");
- verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.GenericVnf.class),isA(AAIResourceUri.class));
- assertEquals(inMaintFlag, true);
- }
-
- @Test
- public void connectVnfToTenantTest() throws Exception {
- aaiVnfResources.connectVnfToTenant(genericVnf, cloudRegion);
- verify(MOCK_aaiResourcesClient, times(1)).connect(eq(AAIUriFactory.createResourceUri(AAIObjectType.TENANT,
- cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), cloudRegion.getTenantId())),
- eq(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, genericVnf.getVnfId())));
- }
-
- @Test
- public void connectVnfToCloudRegionTest() throws Exception {
- aaiVnfResources.connectVnfToCloudRegion(genericVnf, cloudRegion);
- verify(MOCK_aaiResourcesClient, times(1)).connect(eq(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, genericVnf.getVnfId())),
- eq(AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION,
- cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId())));
- }
-
-
- @Test
- public void checkVnfClosedLoopDisabledFlagTest () {
- Optional<org.onap.aai.domain.yang.GenericVnf> vnf = Optional.of(new org.onap.aai.domain.yang.GenericVnf());
- vnf.get().setVnfId("vnfId");
- vnf.get().setIsClosedLoopDisabled(true);
- doReturn(vnf).when(MOCK_aaiResourcesClient).get(eq(org.onap.aai.domain.yang.GenericVnf.class),isA(AAIResourceUri.class));
- boolean isCheckVnfClosedLoopDisabledFlag = aaiVnfResources.checkVnfClosedLoopDisabledFlag("vnfId");
- verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.GenericVnf.class),isA(AAIResourceUri.class));
- assertEquals(isCheckVnfClosedLoopDisabledFlag, true);
- }
-
- @Test
- public void checkVnfPserversLockedFlagTest () throws IOException {
-
- Optional<org.onap.aai.domain.yang.GenericVnf> vnf = Optional.of(new org.onap.aai.domain.yang.GenericVnf());
- vnf.get().setVnfId("vnfId");
- doReturn(vnf).when(MOCK_aaiResourcesClient).get(eq(org.onap.aai.domain.yang.GenericVnf.class),isA(AAIResourceUri.class));
- doReturn(true).when(MOCK_aaiValidatorImpl).isPhysicalServerLocked("vnfId");
- boolean isVnfPserversLockedFlag = aaiVnfResources.checkVnfPserversLockedFlag("vnfId");
- verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.GenericVnf.class),isA(AAIResourceUri.class));
- verify(MOCK_aaiValidatorImpl, times(1)).isPhysicalServerLocked(isA(String.class));
- assertTrue(isVnfPserversLockedFlag);
- }
+ private GenericVnf genericVnf;
+
+ private ServiceInstance serviceInstance;
+
+ private CloudRegion cloudRegion;
+
+ @Mock
+ protected AAIResourcesClient MOCK_aaiResourcesClient;
+
+ @Mock
+ protected AAIObjectMapper MOCK_aaiObjectMapper;
+
+ @Mock
+ protected InjectionHelper MOCK_injectionHelper;
+
+ @Mock
+ protected AAIValidatorImpl MOCK_aaiValidatorImpl;
+
+ @InjectMocks
+ AAIVnfResources aaiVnfResources = new AAIVnfResources();
+
+ @Before
+ public void before() {
+ serviceInstance = buildServiceInstance();
+ genericVnf = buildGenericVnf();
+ cloudRegion = buildCloudRegion();
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ }
+
+ @Test
+ public void createVnfandConnectServiceInstanceTest() {
+ doReturn(new org.onap.aai.domain.yang.GenericVnf()).when(MOCK_aaiObjectMapper).mapVnf(genericVnf);
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class),
+ any(Optional.class));
+ doNothing().when(MOCK_aaiResourcesClient).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
+ genericVnf.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+
+ aaiVnfResources.createVnfandConnectServiceInstance(genericVnf, serviceInstance);
+
+ assertEquals(OrchestrationStatus.INVENTORIED, genericVnf.getOrchestrationStatus());
+ verify(MOCK_aaiObjectMapper, times(1)).mapVnf(genericVnf);
+ verify(MOCK_aaiResourcesClient, times(1)).createIfNotExists(any(AAIResourceUri.class), any(Optional.class));
+ verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
+ }
+
+ @Test
+ public void createPlatformandConnectVnfTest() {
+ Platform platform = new Platform();
+ platform.setPlatformName("a123");
+ doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class),
+ any(Optional.class));
+ aaiVnfResources.createPlatformandConnectVnf(platform, genericVnf);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), isA(AAIResourceUri.class));
+ }
+
+ @Test
+ public void createLineOfBusinessandConnectVnfTest() {
+ LineOfBusiness lob = new LineOfBusiness();
+ lob.setLineOfBusinessName("a123");
+ doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class),
+ any(Optional.class));
+ aaiVnfResources.createLineOfBusinessandConnectVnf(lob, genericVnf);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), isA(AAIResourceUri.class));
+ }
+
+ @Test
+ public void deleteVnfTest() {
+ doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
+
+ aaiVnfResources.deleteVnf(genericVnf);
+
+ verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
+ }
+
+ @Test
+ public void updateOrchestrationStatusVnfTest() {
+ doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.Vnf.class));
+
+ aaiVnfResources.updateOrchestrationStatusVnf(genericVnf, OrchestrationStatus.ACTIVE);
+
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
+
+ assertEquals(OrchestrationStatus.ACTIVE, genericVnf.getOrchestrationStatus());
+ }
+
+ @Test
+ public void updateObjectVnfTest() {
+ doReturn(new org.onap.aai.domain.yang.GenericVnf()).when(MOCK_aaiObjectMapper).mapVnf(genericVnf);
+ doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.GenericVnf.class));
+
+ aaiVnfResources.updateObjectVnf(genericVnf);
+
+ verify(MOCK_aaiObjectMapper, times(1)).mapVnf(genericVnf);
+ verify(MOCK_aaiResourcesClient, times(1)).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.GenericVnf.class));
+ }
+
+ @Test
+ public void getGenericVnfTest() {
+ Optional<org.onap.aai.domain.yang.GenericVnf> vnf = Optional.of(new org.onap.aai.domain.yang.GenericVnf());
+ vnf.get().setVnfId("vnfId");
+ doReturn(vnf).when(MOCK_aaiResourcesClient).get(eq(org.onap.aai.domain.yang.GenericVnf.class),
+ isA(AAIResourceUri.class));
+ aaiVnfResources.getGenericVnf("vnfId");
+ verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.GenericVnf.class),
+ isA(AAIResourceUri.class));
+ }
+
+ @Test
+ public void checkInMaintFlagTest() {
+ Optional<org.onap.aai.domain.yang.GenericVnf> vnf = Optional.of(new org.onap.aai.domain.yang.GenericVnf());
+ vnf.get().setVnfId("vnfId");
+ vnf.get().setInMaint(true);
+ doReturn(vnf).when(MOCK_aaiResourcesClient).get(eq(org.onap.aai.domain.yang.GenericVnf.class),
+ isA(AAIResourceUri.class));
+ boolean inMaintFlag = aaiVnfResources.checkInMaintFlag("vnfId");
+ verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.GenericVnf.class),
+ isA(AAIResourceUri.class));
+ assertEquals(inMaintFlag, true);
+ }
+
+ @Test
+ public void connectVnfToTenantTest() throws Exception {
+ aaiVnfResources.connectVnfToTenant(genericVnf, cloudRegion);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId(), cloudRegion.getTenantId())),
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, genericVnf.getVnfId())));
+ }
+
+ @Test
+ public void connectVnfToCloudRegionTest() throws Exception {
+ aaiVnfResources.connectVnfToCloudRegion(genericVnf, cloudRegion);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, genericVnf.getVnfId())),
+ eq(AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudRegion.getCloudOwner(),
+ cloudRegion.getLcpCloudRegionId())));
+ }
+
+
+ @Test
+ public void checkVnfClosedLoopDisabledFlagTest() {
+ Optional<org.onap.aai.domain.yang.GenericVnf> vnf = Optional.of(new org.onap.aai.domain.yang.GenericVnf());
+ vnf.get().setVnfId("vnfId");
+ vnf.get().setIsClosedLoopDisabled(true);
+ doReturn(vnf).when(MOCK_aaiResourcesClient).get(eq(org.onap.aai.domain.yang.GenericVnf.class),
+ isA(AAIResourceUri.class));
+ boolean isCheckVnfClosedLoopDisabledFlag = aaiVnfResources.checkVnfClosedLoopDisabledFlag("vnfId");
+ verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.GenericVnf.class),
+ isA(AAIResourceUri.class));
+ assertEquals(isCheckVnfClosedLoopDisabledFlag, true);
+ }
+
+ @Test
+ public void checkVnfPserversLockedFlagTest() throws IOException {
+
+ Optional<org.onap.aai.domain.yang.GenericVnf> vnf = Optional.of(new org.onap.aai.domain.yang.GenericVnf());
+ vnf.get().setVnfId("vnfId");
+ doReturn(vnf).when(MOCK_aaiResourcesClient).get(eq(org.onap.aai.domain.yang.GenericVnf.class),
+ isA(AAIResourceUri.class));
+ doReturn(true).when(MOCK_aaiValidatorImpl).isPhysicalServerLocked("vnfId");
+ boolean isVnfPserversLockedFlag = aaiVnfResources.checkVnfPserversLockedFlag("vnfId");
+ verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.GenericVnf.class),
+ isA(AAIResourceUri.class));
+ verify(MOCK_aaiValidatorImpl, times(1)).isPhysicalServerLocked(isA(String.class));
+ assertTrue(isVnfPserversLockedFlag);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVolumeGroupResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVolumeGroupResourcesTest.java
index 6a44ed649e..2bdcf30a4c 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVolumeGroupResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVolumeGroupResourcesTest.java
@@ -27,7 +27,6 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -46,101 +45,105 @@ import org.onap.so.client.aai.mapper.AAIObjectMapper;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class AAIVolumeGroupResourcesTest extends TestDataSetup{
- @InjectMocks
- private AAIVolumeGroupResources aaiVolumeGroupResources = new AAIVolumeGroupResources();
+public class AAIVolumeGroupResourcesTest extends TestDataSetup {
+ @InjectMocks
+ private AAIVolumeGroupResources aaiVolumeGroupResources = new AAIVolumeGroupResources();
+
+ private CloudRegion cloudRegion;
+ private VolumeGroup volumeGroup;
+
+ @Mock
+ protected AAIResourcesClient MOCK_aaiResourcesClient;
+
+ @Mock
+ protected AAIObjectMapper MOCK_aaiObjectMapper;
+
+ @Mock
+ protected InjectionHelper MOCK_injectionHelper;
+
+ @Before
+ public void before() {
+ cloudRegion = buildCloudRegion();
+ volumeGroup = buildVolumeGroup();
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ }
+
+
- private CloudRegion cloudRegion;
- private VolumeGroup volumeGroup;
+ @Test
+ public void updateOrchestrationStatusVolumeGroupTest() throws Exception {
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
- @Mock
- protected AAIResourcesClient MOCK_aaiResourcesClient;
+ doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.VolumeGroup.class));
- @Mock
- protected AAIObjectMapper MOCK_aaiObjectMapper;
+ aaiVolumeGroupResources.updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion,
+ OrchestrationStatus.ACTIVE);
- @Mock
- protected InjectionHelper MOCK_injectionHelper;
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
- @Before
- public void before() {
- cloudRegion = buildCloudRegion();
- volumeGroup = buildVolumeGroup();
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- }
+ assertEquals(OrchestrationStatus.ACTIVE, volumeGroup.getOrchestrationStatus());
+ }
+ @Test
+ public void createVolumeGroupTest() throws Exception {
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.VolumeGroup.class));
- @Test
- public void updateOrchestrationStatusVolumeGroupTest() throws Exception {
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+ aaiVolumeGroupResources.createVolumeGroup(volumeGroup, cloudRegion);
- doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.VolumeGroup.class));
+ verify(MOCK_aaiResourcesClient, times(1)).create(any(AAIResourceUri.class), ArgumentMatchers.isNull());
- aaiVolumeGroupResources.updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.ACTIVE);
+ assertEquals(OrchestrationStatus.ASSIGNED, volumeGroup.getOrchestrationStatus());
+ }
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
+ @Test
+ public void connectVolumeGroupToVnfTest() throws Exception {
- assertEquals(OrchestrationStatus.ACTIVE, volumeGroup.getOrchestrationStatus());
- }
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
- @Test
- public void createVolumeGroupTest() throws Exception {
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
+ doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.VolumeGroup.class));
+ aaiVolumeGroupResources.connectVolumeGroupToTenant(volumeGroup, cloudRegion);
- aaiVolumeGroupResources.createVolumeGroup(volumeGroup, cloudRegion);
+ verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
+ }
- verify(MOCK_aaiResourcesClient, times(1)).create(any(AAIResourceUri.class), ArgumentMatchers.isNull());
+ @Test
+ public void connectVolumeGroupToTenantTest() throws Exception {
+ GenericVnf genericVnf = buildGenericVnf();
- assertEquals(OrchestrationStatus.ASSIGNED, volumeGroup.getOrchestrationStatus());
- }
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
- @Test
- public void connectVolumeGroupToVnfTest() throws Exception {
-
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
-
- doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+ doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- aaiVolumeGroupResources.connectVolumeGroupToTenant(volumeGroup, cloudRegion);
+ aaiVolumeGroupResources.connectVolumeGroupToVnf(genericVnf, volumeGroup, cloudRegion);
- verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
- }
-
- @Test
- public void connectVolumeGroupToTenantTest() throws Exception {
- GenericVnf genericVnf = buildGenericVnf();
+ verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
+ }
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+ @Test
+ public void deleteVolumeGroupTest() {
+ doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
- doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+ aaiVolumeGroupResources.deleteVolumeGroup(volumeGroup, cloudRegion);
- aaiVolumeGroupResources.connectVolumeGroupToVnf(genericVnf, volumeGroup, cloudRegion);
+ verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
+ }
- verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class));
- }
+ @Test
+ public void updateHeatStackIdVolumeGroupTest() throws Exception {
+ volumeGroup.setHeatStackId("testVolumeHeatStackId");
- @Test
- public void deleteVolumeGroupTest() {
- doNothing().when(MOCK_aaiResourcesClient).delete(isA(AAIResourceUri.class));
+ doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.VolumeGroup.class));
- aaiVolumeGroupResources.deleteVolumeGroup(volumeGroup, cloudRegion);
+ aaiVolumeGroupResources.updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
- verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class));
- }
-
- @Test
- public void updateHeatStackIdVolumeGroupTest() throws Exception {
- volumeGroup.setHeatStackId("testVolumeHeatStackId");
-
- doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.VolumeGroup.class));
-
- aaiVolumeGroupResources.updateHeatStackIdVolumeGroup(volumeGroup, cloudRegion);
+ verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
- verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull());
-
- assertEquals("testVolumeHeatStackId", volumeGroup.getHeatStackId());
- }
+ assertEquals("testVolumeHeatStackId", volumeGroup.getHeatStackId());
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVpnBindingResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVpnBindingResourcesTest.java
index c50b084df2..0cbdee396f 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVpnBindingResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVpnBindingResourcesTest.java
@@ -29,9 +29,7 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -42,76 +40,84 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
-public class AAIVpnBindingResourcesTest extends BaseTaskTest{
-
- @InjectMocks
- private AAIVpnBindingResources aaiVpnBindingResources = new AAIVpnBindingResources();
-
- private Customer customer;
-
- @Before
- public void before() {
- customer = buildCustomer();
- doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
- }
-
- @Test
- public void createCustomerTest() {
- org.onap.aai.domain.yang.Customer mappedCustomer = new org.onap.aai.domain.yang.Customer();
- mappedCustomer.setGlobalCustomerId(customer.getGlobalCustomerId());
-
- doReturn(mappedCustomer).when(MOCK_aaiObjectMapper).mapCustomer(customer);
- doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Customer.class));
-
- aaiVpnBindingResources.createCustomer(customer);
-
- verify(MOCK_aaiResourcesClient, times(1)).create(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Customer.class));
- verify(MOCK_aaiObjectMapper, times(1)).mapCustomer(customer);
- }
-
- @Test
- public void getVpnBindingTest () {
- org.onap.aai.domain.yang.VpnBinding vpnBinding = new org.onap.aai.domain.yang.VpnBinding();
- vpnBinding.setVpnId("vnfId");
- when(MOCK_aaiResourcesClient.get(eq(org.onap.aai.domain.yang.VpnBinding.class),isA(AAIResourceUri.class))).thenReturn(Optional.of(vpnBinding));
- aaiVpnBindingResources.getVpnBinding("vpnId");
- verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.VpnBinding.class),isA(AAIResourceUri.class));
- }
+public class AAIVpnBindingResourcesTest extends BaseTaskTest {
+
+ @InjectMocks
+ private AAIVpnBindingResources aaiVpnBindingResources = new AAIVpnBindingResources();
+
+ private Customer customer;
+
+ @Before
+ public void before() {
+ customer = buildCustomer();
+ doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
+ }
+
+ @Test
+ public void createCustomerTest() {
+ org.onap.aai.domain.yang.Customer mappedCustomer = new org.onap.aai.domain.yang.Customer();
+ mappedCustomer.setGlobalCustomerId(customer.getGlobalCustomerId());
+
+ doReturn(mappedCustomer).when(MOCK_aaiObjectMapper).mapCustomer(customer);
+ doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.Customer.class));
+
+ aaiVpnBindingResources.createCustomer(customer);
+
+ verify(MOCK_aaiResourcesClient, times(1)).create(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.Customer.class));
+ verify(MOCK_aaiObjectMapper, times(1)).mapCustomer(customer);
+ }
+
+ @Test
+ public void getVpnBindingTest() {
+ org.onap.aai.domain.yang.VpnBinding vpnBinding = new org.onap.aai.domain.yang.VpnBinding();
+ vpnBinding.setVpnId("vnfId");
+ when(MOCK_aaiResourcesClient.get(eq(org.onap.aai.domain.yang.VpnBinding.class), isA(AAIResourceUri.class)))
+ .thenReturn(Optional.of(vpnBinding));
+ aaiVpnBindingResources.getVpnBinding("vpnId");
+ verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.VpnBinding.class),
+ isA(AAIResourceUri.class));
+ }
@Test
public void existsCustomerTest() {
- when(MOCK_aaiResourcesClient.exists(isA(AAIResourceUri.class))).thenReturn(true);
- boolean isCustomerExist = aaiVpnBindingResources.existsCustomer(customer);
- verify(MOCK_aaiResourcesClient, times(1)).exists(isA(AAIResourceUri.class));
- assertEquals(true,isCustomerExist);
- }
+ when(MOCK_aaiResourcesClient.exists(isA(AAIResourceUri.class))).thenReturn(true);
+ boolean isCustomerExist = aaiVpnBindingResources.existsCustomer(customer);
+ verify(MOCK_aaiResourcesClient, times(1)).exists(isA(AAIResourceUri.class));
+ assertEquals(true, isCustomerExist);
+ }
@Test
public void getVpnBindingByCustomerVpnIdTest() {
- when(MOCK_aaiResourcesClient.get(eq(VpnBindings.class),isA(AAIResourceUri.class))).thenReturn(Optional.of(new VpnBindings()));
- Optional<VpnBindings> vpnBindings = aaiVpnBindingResources.getVpnBindingByCustomerVpnId("testCustomerVpnId");
- assertNotNull(vpnBindings.get());
- verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.VpnBindings.class),isA(AAIResourceUri.class));
- }
-
- @Test
- public void createVpnBindingTest() {
- doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.VpnBinding.class));
- org.onap.aai.domain.yang.VpnBinding mappedVpnBinding = new org.onap.aai.domain.yang.VpnBinding();
- mappedVpnBinding.setVpnName("test");
-
- doReturn(mappedVpnBinding).when(MOCK_aaiObjectMapper).mapVpnBinding(isA(VpnBinding.class));
- VpnBinding vpnBinding = buildVpnBinding();
- aaiVpnBindingResources.createVpnBinding(vpnBinding);
-
- verify(MOCK_aaiResourcesClient, times(1)).create(isA(AAIResourceUri.class), isA(org.onap.aai.domain.yang.VpnBinding.class));
- verify(MOCK_aaiObjectMapper, times(1)).mapVpnBinding(isA(VpnBinding.class));
- }
-
- @Test
- public void connectCustomerToVpnBinding() {
- doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- aaiVpnBindingResources.connectCustomerToVpnBinding("testCustId","testVpnId");
- verify(MOCK_aaiResourcesClient,times(1)).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
- }
+ when(MOCK_aaiResourcesClient.get(eq(VpnBindings.class), isA(AAIResourceUri.class)))
+ .thenReturn(Optional.of(new VpnBindings()));
+ Optional<VpnBindings> vpnBindings = aaiVpnBindingResources.getVpnBindingByCustomerVpnId("testCustomerVpnId");
+ assertNotNull(vpnBindings.get());
+ verify(MOCK_aaiResourcesClient, times(1)).get(eq(org.onap.aai.domain.yang.VpnBindings.class),
+ isA(AAIResourceUri.class));
+ }
+
+ @Test
+ public void createVpnBindingTest() {
+ doNothing().when(MOCK_aaiResourcesClient).create(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.VpnBinding.class));
+ org.onap.aai.domain.yang.VpnBinding mappedVpnBinding = new org.onap.aai.domain.yang.VpnBinding();
+ mappedVpnBinding.setVpnName("test");
+
+ doReturn(mappedVpnBinding).when(MOCK_aaiObjectMapper).mapVpnBinding(isA(VpnBinding.class));
+ VpnBinding vpnBinding = buildVpnBinding();
+ aaiVpnBindingResources.createVpnBinding(vpnBinding);
+
+ verify(MOCK_aaiResourcesClient, times(1)).create(isA(AAIResourceUri.class),
+ isA(org.onap.aai.domain.yang.VpnBinding.class));
+ verify(MOCK_aaiObjectMapper, times(1)).mapVpnBinding(isA(VpnBinding.class));
+ }
+
+ @Test
+ public void connectCustomerToVpnBinding() {
+ doNothing().when(MOCK_aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+ aaiVpnBindingResources.connectCustomerToVpnBinding("testCustId", "testVpnId");
+ verify(MOCK_aaiResourcesClient, times(1)).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NamingServiceResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NamingServiceResourcesTest.java
index 629e98abb2..195c89a651 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NamingServiceResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NamingServiceResourcesTest.java
@@ -26,9 +26,7 @@ import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.List;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -49,57 +47,58 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class NamingServiceResourcesTest extends TestDataSetup{
- @InjectMocks
- private NamingServiceResources namingServiceResources = new NamingServiceResources();
-
- private InstanceGroup instanceGroup;
-
- @Mock
- protected NamingRequestObjectBuilder MOCK_namingRequestObjectBuilder;
-
- @Mock
- protected NamingClient MOCK_namingClient;
-
- @Before
- public void before() {
- instanceGroup = buildInstanceGroup();
- }
-
- @Test
- public void generateInstanceGroupNameTest() throws Exception {
- NameGenResponse name = new NameGenResponse();
- ResponseEntity<NameGenResponse> resp = new ResponseEntity<>(name, null, HttpStatus.OK);
- Element element = new Element();
-
- NameGenRequest req = new NameGenRequest();
- doReturn(element).when(MOCK_namingRequestObjectBuilder).elementMapper(isA(String.class), isA(String.class),
- isA(String.class), isA(String.class), isA(String.class));
- doReturn("generatedInstanceGroupName").when(MOCK_namingClient).postNameGenRequest(isA(NameGenRequest.class));
- doReturn(req).when(MOCK_namingRequestObjectBuilder).nameGenRequestMapper(isA(List.class));
-
- String generatedName = namingServiceResources.generateInstanceGroupName(instanceGroup, "policyInstanceName", "nfNamingCode");
-
- verify(MOCK_namingClient, times(1)).postNameGenRequest(any(NameGenRequest.class));
- assertEquals(generatedName, "generatedInstanceGroupName");
- }
-
- @Test
- public void deleteInstanceGroupNameTest() throws Exception {
- NameGenDeleteResponse name = new NameGenDeleteResponse();
- ResponseEntity<NameGenDeleteResponse> resp = new ResponseEntity<>(name, null, HttpStatus.OK);
- Deleteelement deleteElement = new Deleteelement();
- deleteElement.setExternalKey(instanceGroup.getId());
- NameGenDeleteRequest req = new NameGenDeleteRequest();
- doReturn(deleteElement).when(MOCK_namingRequestObjectBuilder).deleteElementMapper(isA(String.class));
- doReturn("").when(MOCK_namingClient).deleteNameGenRequest(isA(NameGenDeleteRequest.class));
- doReturn(req).when(MOCK_namingRequestObjectBuilder).nameGenDeleteRequestMapper(isA(List.class));
-
- namingServiceResources.deleteInstanceGroupName(instanceGroup);
-
- verify(MOCK_namingClient, times(1)).deleteNameGenRequest(any(NameGenDeleteRequest.class));
-
- }
-
-
+public class NamingServiceResourcesTest extends TestDataSetup {
+ @InjectMocks
+ private NamingServiceResources namingServiceResources = new NamingServiceResources();
+
+ private InstanceGroup instanceGroup;
+
+ @Mock
+ protected NamingRequestObjectBuilder MOCK_namingRequestObjectBuilder;
+
+ @Mock
+ protected NamingClient MOCK_namingClient;
+
+ @Before
+ public void before() {
+ instanceGroup = buildInstanceGroup();
+ }
+
+ @Test
+ public void generateInstanceGroupNameTest() throws Exception {
+ NameGenResponse name = new NameGenResponse();
+ ResponseEntity<NameGenResponse> resp = new ResponseEntity<>(name, null, HttpStatus.OK);
+ Element element = new Element();
+
+ NameGenRequest req = new NameGenRequest();
+ doReturn(element).when(MOCK_namingRequestObjectBuilder).elementMapper(isA(String.class), isA(String.class),
+ isA(String.class), isA(String.class), isA(String.class));
+ doReturn("generatedInstanceGroupName").when(MOCK_namingClient).postNameGenRequest(isA(NameGenRequest.class));
+ doReturn(req).when(MOCK_namingRequestObjectBuilder).nameGenRequestMapper(isA(List.class));
+
+ String generatedName =
+ namingServiceResources.generateInstanceGroupName(instanceGroup, "policyInstanceName", "nfNamingCode");
+
+ verify(MOCK_namingClient, times(1)).postNameGenRequest(any(NameGenRequest.class));
+ assertEquals(generatedName, "generatedInstanceGroupName");
+ }
+
+ @Test
+ public void deleteInstanceGroupNameTest() throws Exception {
+ NameGenDeleteResponse name = new NameGenDeleteResponse();
+ ResponseEntity<NameGenDeleteResponse> resp = new ResponseEntity<>(name, null, HttpStatus.OK);
+ Deleteelement deleteElement = new Deleteelement();
+ deleteElement.setExternalKey(instanceGroup.getId());
+ NameGenDeleteRequest req = new NameGenDeleteRequest();
+ doReturn(deleteElement).when(MOCK_namingRequestObjectBuilder).deleteElementMapper(isA(String.class));
+ doReturn("").when(MOCK_namingClient).deleteNameGenRequest(isA(NameGenDeleteRequest.class));
+ doReturn(req).when(MOCK_namingRequestObjectBuilder).nameGenDeleteRequestMapper(isA(List.class));
+
+ namingServiceResources.deleteInstanceGroupName(instanceGroup);
+
+ verify(MOCK_namingClient, times(1)).deleteNameGenRequest(any(NameGenDeleteRequest.class));
+
+ }
+
+
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NetworkAdapterResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NetworkAdapterResourcesTest.java
index 1ff9d2af2d..96e2a74297 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NetworkAdapterResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NetworkAdapterResourcesTest.java
@@ -26,13 +26,11 @@ import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -61,159 +59,182 @@ import org.onap.so.client.adapter.network.NetworkAdapterClientImpl;
import org.onap.so.client.adapter.network.mapper.NetworkAdapterObjectMapper;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
import org.onap.so.entity.MsoRequest;
-
import com.shazam.shazamcrest.matcher.Matchers;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class NetworkAdapterResourcesTest extends TestDataSetup{
-
- @InjectMocks
- private NetworkAdapterResources networkAdapterResources = new NetworkAdapterResources();
-
- @Mock
- protected NetworkAdapterClientImpl MOCK_networkAdapterClient;
-
- @Mock
- protected NetworkAdapterObjectMapper MOCK_networkAdapterObjectMapper;
-
- private L3Network l3Network;
- private RequestContext requestContext;
- private ServiceInstance serviceInstance;
- private CloudRegion cloudRegion;
- private OrchestrationContext orchestrationContext;
- private Customer customer;
- Map<String, String> userInput;
-
- @Before
- public void before() {
- requestContext = buildRequestContext();
-
- customer = buildCustomer();
-
- serviceInstance = buildServiceInstance();
-
- cloudRegion = buildCloudRegion();
-
- orchestrationContext = buildOrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
-
- userInput = buildUserInput();
-
- l3Network = buildL3Network();
- }
-
- @Test
- public void createNetworTest() throws Exception {
- String cloudRegionPo = "cloudRegionPo";
- CreateNetworkRequest expectedCreateNetworkRequest = new CreateNetworkRequest();
-
- expectedCreateNetworkRequest.setCloudSiteId(cloudRegionPo);
- expectedCreateNetworkRequest.setTenantId(cloudRegion.getTenantId());
- expectedCreateNetworkRequest.setNetworkId(l3Network.getNetworkId());
- expectedCreateNetworkRequest.setNetworkName(l3Network.getNetworkName());
- expectedCreateNetworkRequest.setBackout(false);
- expectedCreateNetworkRequest.setFailIfExists(true);
-
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId(requestContext.getMsoRequestId());
- msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
- expectedCreateNetworkRequest.setMsoRequest(msoRequest);
- expectedCreateNetworkRequest.setSkipAAI(true);
-
- Subnet openstackSubnet = new Subnet();
- HostRoute hostRoute = new HostRoute();
- hostRoute.setHostRouteId("hostRouteId");
- hostRoute.setNextHop("nextHop");
- hostRoute.setRoutePrefix("routePrefix");
- openstackSubnet.getHostRoutes().add(hostRoute);
- List<Subnet> subnetList = new ArrayList<Subnet>();
- subnetList.add(openstackSubnet);
- l3Network.getSubnets().add(openstackSubnet);
-
- l3Network.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
-
- CreateNetworkRequest createNetworkRequest = new CreateNetworkRequest();
- createNetworkRequest.setCloudSiteId("cloudSiteId");
-
- CreateNetworkResponse expectedCreateNetworkResponse = new CreateNetworkResponse();
- expectedCreateNetworkResponse.setNetworkStackId("networkStackId");
- expectedCreateNetworkResponse.setNetworkCreated(true);
-
-
- doReturn(expectedCreateNetworkResponse).when(MOCK_networkAdapterClient).createNetwork(isA(CreateNetworkRequest.class));
-
- doReturn(createNetworkRequest).when(MOCK_networkAdapterObjectMapper).createNetworkRequestMapper(isA(RequestContext.class), isA(CloudRegion.class), isA(OrchestrationContext.class), isA(ServiceInstance.class), isA(L3Network.class), isA(Map.class), isA(String.class), isA(Customer.class));
-
- CreateNetworkResponse actualCreateNetwrokResponse = (networkAdapterResources.createNetwork(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, customer)).get();
-
- verify(MOCK_networkAdapterClient, times(1)).createNetwork(createNetworkRequest);
-
- verify(MOCK_networkAdapterObjectMapper, times(1)).createNetworkRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, customer);
-
- assertThat(expectedCreateNetworkResponse, Matchers.sameBeanAs(actualCreateNetwrokResponse));
- }
-
- @Test
- public void rollbackCreateNetworkTest() throws Exception {
- String cloudRegionPo = "cloudRegionPo";
- RollbackNetworkResponse expectedRollbackNetworkResponse = new RollbackNetworkResponse();
- expectedRollbackNetworkResponse.setMessageId("messageId");
- expectedRollbackNetworkResponse.setNetworkRolledBack(true);
-
- RollbackNetworkRequest rollbackNetworkRequest = new RollbackNetworkRequest();
- rollbackNetworkRequest.setMessageId("messageId");
-
- RollbackNetworkResponse rollbackNetworkResponse = new RollbackNetworkResponse();
- rollbackNetworkResponse.setMessageId("messageId");
- rollbackNetworkResponse.setNetworkRolledBack(true);
-
- CreateNetworkResponse createNetworkResponse = new CreateNetworkResponse();
- createNetworkResponse.setMessageId("messageId");
-
- doReturn(rollbackNetworkResponse).when(MOCK_networkAdapterClient).rollbackNetwork(isA(String.class), isA(RollbackNetworkRequest.class));
-
- doReturn(rollbackNetworkRequest).when(MOCK_networkAdapterObjectMapper).createNetworkRollbackRequestMapper(isA(RequestContext.class), isA(CloudRegion.class), isA(OrchestrationContext.class), isA(ServiceInstance.class), isA(L3Network.class), isA(Map.class), isA(String.class), isA(CreateNetworkResponse.class));
-
- RollbackNetworkResponse actualRollbackCreateNetwrokResponse = (networkAdapterResources.rollbackCreateNetwork(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, createNetworkResponse)).get();
-
- verify(MOCK_networkAdapterClient, times(1)).rollbackNetwork(l3Network.getNetworkId(), rollbackNetworkRequest);
-
- verify(MOCK_networkAdapterObjectMapper, times(1)).createNetworkRollbackRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, createNetworkResponse);
-
- assertThat(expectedRollbackNetworkResponse, Matchers.sameBeanAs(actualRollbackCreateNetwrokResponse));
- }
-
- @Test
- public void updateNetworkTest() throws UnsupportedEncodingException, NetworkAdapterClientException {
-
- doReturn(new UpdateNetworkRequest()).when(MOCK_networkAdapterObjectMapper).createNetworkUpdateRequestMapper(isA(RequestContext.class), isA(CloudRegion.class), isA(OrchestrationContext.class), isA(ServiceInstance.class), isA(L3Network.class), isA(Map.class), isA(Customer.class));
-
- doReturn(new UpdateNetworkResponse()).when(MOCK_networkAdapterClient).updateNetwork(isA(String.class), isA(UpdateNetworkRequest.class));
-
- Optional<UpdateNetworkResponse> actualUpdateNetworkResponse = networkAdapterResources.updateNetwork(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, customer);
-
-
- verify(MOCK_networkAdapterObjectMapper, times(1)).createNetworkUpdateRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, customer);
- verify(MOCK_networkAdapterClient, times(1)).updateNetwork(isA(String.class), isA(UpdateNetworkRequest.class));
- assertNotNull(actualUpdateNetworkResponse);
- }
-
- @Test
- public void deleteNetwork_DeleteAction_Test() throws UnsupportedEncodingException, NetworkAdapterClientException {
-
- DeleteNetworkRequest deleteNetworkRequest = new DeleteNetworkRequest();
- doReturn(deleteNetworkRequest).when(MOCK_networkAdapterObjectMapper).deleteNetworkRequestMapper(requestContext, cloudRegion, serviceInstance, l3Network);
-
- DeleteNetworkResponse expectedDeleteNetworkResponse = new DeleteNetworkResponse();
-
- doReturn(expectedDeleteNetworkResponse).when(MOCK_networkAdapterClient).deleteNetwork(l3Network.getNetworkId(), deleteNetworkRequest);
-
- Optional<DeleteNetworkResponse> actualODeleteNetworkResponse = networkAdapterResources.deleteNetwork(requestContext, cloudRegion, serviceInstance, l3Network);
- DeleteNetworkResponse actualDeleteNetworkResponse = actualODeleteNetworkResponse.get();
-
- verify(MOCK_networkAdapterObjectMapper, times(1)).deleteNetworkRequestMapper(requestContext, cloudRegion, serviceInstance, l3Network);
- verify(MOCK_networkAdapterClient, times(1)).deleteNetwork(l3Network.getNetworkId(), deleteNetworkRequest);
- assertThat(expectedDeleteNetworkResponse, Matchers.sameBeanAs(actualDeleteNetworkResponse));
- }
+public class NetworkAdapterResourcesTest extends TestDataSetup {
+
+ @InjectMocks
+ private NetworkAdapterResources networkAdapterResources = new NetworkAdapterResources();
+
+ @Mock
+ protected NetworkAdapterClientImpl MOCK_networkAdapterClient;
+
+ @Mock
+ protected NetworkAdapterObjectMapper MOCK_networkAdapterObjectMapper;
+
+ private L3Network l3Network;
+ private RequestContext requestContext;
+ private ServiceInstance serviceInstance;
+ private CloudRegion cloudRegion;
+ private OrchestrationContext orchestrationContext;
+ private Customer customer;
+ Map<String, String> userInput;
+
+ @Before
+ public void before() {
+ requestContext = buildRequestContext();
+
+ customer = buildCustomer();
+
+ serviceInstance = buildServiceInstance();
+
+ cloudRegion = buildCloudRegion();
+
+ orchestrationContext = buildOrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+
+ userInput = buildUserInput();
+
+ l3Network = buildL3Network();
+ }
+
+ @Test
+ public void createNetworTest() throws Exception {
+ String cloudRegionPo = "cloudRegionPo";
+ CreateNetworkRequest expectedCreateNetworkRequest = new CreateNetworkRequest();
+
+ expectedCreateNetworkRequest.setCloudSiteId(cloudRegionPo);
+ expectedCreateNetworkRequest.setTenantId(cloudRegion.getTenantId());
+ expectedCreateNetworkRequest.setNetworkId(l3Network.getNetworkId());
+ expectedCreateNetworkRequest.setNetworkName(l3Network.getNetworkName());
+ expectedCreateNetworkRequest.setBackout(false);
+ expectedCreateNetworkRequest.setFailIfExists(true);
+
+ MsoRequest msoRequest = new MsoRequest();
+ msoRequest.setRequestId(requestContext.getMsoRequestId());
+ msoRequest.setServiceInstanceId(serviceInstance.getServiceInstanceId());
+ expectedCreateNetworkRequest.setMsoRequest(msoRequest);
+ expectedCreateNetworkRequest.setSkipAAI(true);
+
+ Subnet openstackSubnet = new Subnet();
+ HostRoute hostRoute = new HostRoute();
+ hostRoute.setHostRouteId("hostRouteId");
+ hostRoute.setNextHop("nextHop");
+ hostRoute.setRoutePrefix("routePrefix");
+ openstackSubnet.getHostRoutes().add(hostRoute);
+ List<Subnet> subnetList = new ArrayList<Subnet>();
+ subnetList.add(openstackSubnet);
+ l3Network.getSubnets().add(openstackSubnet);
+
+ l3Network.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+
+ CreateNetworkRequest createNetworkRequest = new CreateNetworkRequest();
+ createNetworkRequest.setCloudSiteId("cloudSiteId");
+
+ CreateNetworkResponse expectedCreateNetworkResponse = new CreateNetworkResponse();
+ expectedCreateNetworkResponse.setNetworkStackId("networkStackId");
+ expectedCreateNetworkResponse.setNetworkCreated(true);
+
+
+ doReturn(expectedCreateNetworkResponse).when(MOCK_networkAdapterClient)
+ .createNetwork(isA(CreateNetworkRequest.class));
+
+ doReturn(createNetworkRequest).when(MOCK_networkAdapterObjectMapper).createNetworkRequestMapper(
+ isA(RequestContext.class), isA(CloudRegion.class), isA(OrchestrationContext.class),
+ isA(ServiceInstance.class), isA(L3Network.class), isA(Map.class), isA(String.class),
+ isA(Customer.class));
+
+ CreateNetworkResponse actualCreateNetwrokResponse =
+ (networkAdapterResources.createNetwork(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, l3Network, userInput, cloudRegionPo, customer)).get();
+
+ verify(MOCK_networkAdapterClient, times(1)).createNetwork(createNetworkRequest);
+
+ verify(MOCK_networkAdapterObjectMapper, times(1)).createNetworkRequestMapper(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo, customer);
+
+ assertThat(expectedCreateNetworkResponse, Matchers.sameBeanAs(actualCreateNetwrokResponse));
+ }
+
+ @Test
+ public void rollbackCreateNetworkTest() throws Exception {
+ String cloudRegionPo = "cloudRegionPo";
+ RollbackNetworkResponse expectedRollbackNetworkResponse = new RollbackNetworkResponse();
+ expectedRollbackNetworkResponse.setMessageId("messageId");
+ expectedRollbackNetworkResponse.setNetworkRolledBack(true);
+
+ RollbackNetworkRequest rollbackNetworkRequest = new RollbackNetworkRequest();
+ rollbackNetworkRequest.setMessageId("messageId");
+
+ RollbackNetworkResponse rollbackNetworkResponse = new RollbackNetworkResponse();
+ rollbackNetworkResponse.setMessageId("messageId");
+ rollbackNetworkResponse.setNetworkRolledBack(true);
+
+ CreateNetworkResponse createNetworkResponse = new CreateNetworkResponse();
+ createNetworkResponse.setMessageId("messageId");
+
+ doReturn(rollbackNetworkResponse).when(MOCK_networkAdapterClient).rollbackNetwork(isA(String.class),
+ isA(RollbackNetworkRequest.class));
+
+ doReturn(rollbackNetworkRequest).when(MOCK_networkAdapterObjectMapper).createNetworkRollbackRequestMapper(
+ isA(RequestContext.class), isA(CloudRegion.class), isA(OrchestrationContext.class),
+ isA(ServiceInstance.class), isA(L3Network.class), isA(Map.class), isA(String.class),
+ isA(CreateNetworkResponse.class));
+
+ RollbackNetworkResponse actualRollbackCreateNetwrokResponse =
+ (networkAdapterResources.rollbackCreateNetwork(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, l3Network, userInput, cloudRegionPo, createNetworkResponse)).get();
+
+ verify(MOCK_networkAdapterClient, times(1)).rollbackNetwork(l3Network.getNetworkId(), rollbackNetworkRequest);
+
+ verify(MOCK_networkAdapterObjectMapper, times(1)).createNetworkRollbackRequestMapper(requestContext,
+ cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, cloudRegionPo,
+ createNetworkResponse);
+
+ assertThat(expectedRollbackNetworkResponse, Matchers.sameBeanAs(actualRollbackCreateNetwrokResponse));
+ }
+
+ @Test
+ public void updateNetworkTest() throws UnsupportedEncodingException, NetworkAdapterClientException {
+
+ doReturn(new UpdateNetworkRequest()).when(MOCK_networkAdapterObjectMapper).createNetworkUpdateRequestMapper(
+ isA(RequestContext.class), isA(CloudRegion.class), isA(OrchestrationContext.class),
+ isA(ServiceInstance.class), isA(L3Network.class), isA(Map.class), isA(Customer.class));
+
+ doReturn(new UpdateNetworkResponse()).when(MOCK_networkAdapterClient).updateNetwork(isA(String.class),
+ isA(UpdateNetworkRequest.class));
+
+ Optional<UpdateNetworkResponse> actualUpdateNetworkResponse = networkAdapterResources.updateNetwork(
+ requestContext, cloudRegion, orchestrationContext, serviceInstance, l3Network, userInput, customer);
+
+
+ verify(MOCK_networkAdapterObjectMapper, times(1)).createNetworkUpdateRequestMapper(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, l3Network, userInput, customer);
+ verify(MOCK_networkAdapterClient, times(1)).updateNetwork(isA(String.class), isA(UpdateNetworkRequest.class));
+ assertNotNull(actualUpdateNetworkResponse);
+ }
+
+ @Test
+ public void deleteNetwork_DeleteAction_Test() throws UnsupportedEncodingException, NetworkAdapterClientException {
+
+ DeleteNetworkRequest deleteNetworkRequest = new DeleteNetworkRequest();
+ doReturn(deleteNetworkRequest).when(MOCK_networkAdapterObjectMapper).deleteNetworkRequestMapper(requestContext,
+ cloudRegion, serviceInstance, l3Network);
+
+ DeleteNetworkResponse expectedDeleteNetworkResponse = new DeleteNetworkResponse();
+
+ doReturn(expectedDeleteNetworkResponse).when(MOCK_networkAdapterClient).deleteNetwork(l3Network.getNetworkId(),
+ deleteNetworkRequest);
+
+ Optional<DeleteNetworkResponse> actualODeleteNetworkResponse =
+ networkAdapterResources.deleteNetwork(requestContext, cloudRegion, serviceInstance, l3Network);
+ DeleteNetworkResponse actualDeleteNetworkResponse = actualODeleteNetworkResponse.get();
+
+ verify(MOCK_networkAdapterObjectMapper, times(1)).deleteNetworkRequestMapper(requestContext, cloudRegion,
+ serviceInstance, l3Network);
+ verify(MOCK_networkAdapterClient, times(1)).deleteNetwork(l3Network.getNetworkId(), deleteNetworkRequest);
+ assertThat(expectedDeleteNetworkResponse, Matchers.sameBeanAs(actualDeleteNetworkResponse));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCConfigurationResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCConfigurationResourcesTest.java
index 0023066949..9049fe1965 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCConfigurationResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCConfigurationResourcesTest.java
@@ -24,10 +24,8 @@ import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
-
import java.net.URI;
import java.net.URISyntaxException;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -50,17 +48,17 @@ import org.onap.so.client.sdnc.beans.SDNCSvcAction;
import org.onap.so.client.sdnc.mapper.GCTopologyOperationRequestMapper;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class SDNCConfigurationResourcesTest extends TestDataSetup{
-
- @InjectMocks
+public class SDNCConfigurationResourcesTest extends TestDataSetup {
+
+ @InjectMocks
private SDNCConfigurationResources sdncConfigurationResources = new SDNCConfigurationResources();
-
- @Mock
- private GCTopologyOperationRequestMapper MOCK_gcTopologyMapper ;
-
- @Mock
- protected SDNCClient MOCK_sdncClient;
-
+
+ @Mock
+ private GCTopologyOperationRequestMapper MOCK_gcTopologyMapper;
+
+ @Mock
+ protected SDNCClient MOCK_sdncClient;
+
private RequestContext requestContext;
private ServiceInstance serviceInstance;
private VpnBondingLink vpnBondingLink;
@@ -68,45 +66,55 @@ public class SDNCConfigurationResourcesTest extends TestDataSetup{
private Customer customer;
@Before
- public void setUp(){
- customer = buildCustomer();
+ public void setUp() {
+ customer = buildCustomer();
requestContext = buildRequestContext();
serviceInstance = buildServiceInstance();
- vpnBondingLink = buildVpnBondingLink();
+ vpnBondingLink = buildVpnBondingLink();
vnf = vpnBondingLink.getInfrastructureServiceProxy().getServiceInstance().getVnfs().get(0);
}
@Test
public void activateVnrConfigurationTest() throws BadResponseException, MapperException, URISyntaxException {
- GenericResourceApiGcTopologyOperationInformation response = sdncConfigurationResources.activateVnrConfiguration(serviceInstance,requestContext,customer,vpnBondingLink.getVnrConfiguration(),vnf,"uuid",new URI("http://localhost"));
- verify(MOCK_gcTopologyMapper).assignOrActivateVnrReqMapper(
- eq(SDNCSvcAction.ACTIVATE), eq(GenericResourceApiRequestActionEnumeration.CREATEGENERICCONFIGURATIONINSTANCE),
- eq(serviceInstance), eq(requestContext), eq(customer), any(Configuration.class), any(GenericVnf.class), any(String.class), any(URI.class));
+ GenericResourceApiGcTopologyOperationInformation response =
+ sdncConfigurationResources.activateVnrConfiguration(serviceInstance, requestContext, customer,
+ vpnBondingLink.getVnrConfiguration(), vnf, "uuid", new URI("http://localhost"));
+ verify(MOCK_gcTopologyMapper).assignOrActivateVnrReqMapper(eq(SDNCSvcAction.ACTIVATE),
+ eq(GenericResourceApiRequestActionEnumeration.CREATEGENERICCONFIGURATIONINSTANCE), eq(serviceInstance),
+ eq(requestContext), eq(customer), any(Configuration.class), any(GenericVnf.class), any(String.class),
+ any(URI.class));
}
@Test
public void assignVnrConfigurationTest() throws BadResponseException, MapperException, URISyntaxException {
- GenericResourceApiGcTopologyOperationInformation response = sdncConfigurationResources.assignVnrConfiguration(serviceInstance,requestContext,customer,vpnBondingLink.getVnrConfiguration(),vnf,"uuid",new URI("http://localhost"));
- verify(MOCK_gcTopologyMapper).assignOrActivateVnrReqMapper(
- eq(SDNCSvcAction.ASSIGN), eq(GenericResourceApiRequestActionEnumeration.CREATEGENERICCONFIGURATIONINSTANCE),
- eq(serviceInstance), eq(requestContext), eq(customer), any(Configuration.class), any(GenericVnf.class), any(String.class), any(URI.class));
+ GenericResourceApiGcTopologyOperationInformation response =
+ sdncConfigurationResources.assignVnrConfiguration(serviceInstance, requestContext, customer,
+ vpnBondingLink.getVnrConfiguration(), vnf, "uuid", new URI("http://localhost"));
+ verify(MOCK_gcTopologyMapper).assignOrActivateVnrReqMapper(eq(SDNCSvcAction.ASSIGN),
+ eq(GenericResourceApiRequestActionEnumeration.CREATEGENERICCONFIGURATIONINSTANCE), eq(serviceInstance),
+ eq(requestContext), eq(customer), any(Configuration.class), any(GenericVnf.class), any(String.class),
+ any(URI.class));
}
@Test
- public void unAssignVnrConfigurationTest() throws BadResponseException, MapperException , URISyntaxException{
- GenericResourceApiGcTopologyOperationInformation response = sdncConfigurationResources.unAssignVnrConfiguration(serviceInstance,requestContext,vpnBondingLink.getVnrConfiguration(),"uuid",new URI("http://localhost"));
- verify(MOCK_gcTopologyMapper).deactivateOrUnassignVnrReqMapper(
- eq(SDNCSvcAction.UNASSIGN), eq(serviceInstance), eq(requestContext), any(Configuration.class), any(String.class), any(URI.class));
+ public void unAssignVnrConfigurationTest() throws BadResponseException, MapperException, URISyntaxException {
+ GenericResourceApiGcTopologyOperationInformation response =
+ sdncConfigurationResources.unAssignVnrConfiguration(serviceInstance, requestContext,
+ vpnBondingLink.getVnrConfiguration(), "uuid", new URI("http://localhost"));
+ verify(MOCK_gcTopologyMapper).deactivateOrUnassignVnrReqMapper(eq(SDNCSvcAction.UNASSIGN), eq(serviceInstance),
+ eq(requestContext), any(Configuration.class), any(String.class), any(URI.class));
}
@Test
- public void deactivateVnrConfigurationTest() throws BadResponseException, MapperException , URISyntaxException{
- GenericResourceApiGcTopologyOperationInformation response = sdncConfigurationResources.deactivateVnrConfiguration(serviceInstance,requestContext,vpnBondingLink.getVnrConfiguration(),"uuid",new URI("http://localhost"));
- verify(MOCK_gcTopologyMapper).deactivateOrUnassignVnrReqMapper(
- eq(SDNCSvcAction.DEACTIVATE), eq(serviceInstance), eq(requestContext), any(Configuration.class), any(String.class), any(URI.class));
+ public void deactivateVnrConfigurationTest() throws BadResponseException, MapperException, URISyntaxException {
+ GenericResourceApiGcTopologyOperationInformation response =
+ sdncConfigurationResources.deactivateVnrConfiguration(serviceInstance, requestContext,
+ vpnBondingLink.getVnrConfiguration(), "uuid", new URI("http://localhost"));
+ verify(MOCK_gcTopologyMapper).deactivateOrUnassignVnrReqMapper(eq(SDNCSvcAction.DEACTIVATE),
+ eq(serviceInstance), eq(requestContext), any(Configuration.class), any(String.class), any(URI.class));
}
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCNetworkResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCNetworkResourcesTest.java
index f275f3c484..327bae5749 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCNetworkResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCNetworkResourcesTest.java
@@ -23,7 +23,6 @@ package org.onap.so.client.orchestration;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -48,122 +47,122 @@ import org.onap.so.client.sdnc.mapper.NetworkTopologyOperationRequestMapper;
@RunWith(MockitoJUnitRunner.Silent.class)
public class SDNCNetworkResourcesTest extends TestDataSetup {
- @InjectMocks
- private SDNCNetworkResources sdncNetworkResources;
-
- @Mock
- protected SDNCClient MOCK_sdncClient;
-
- @Mock
- protected NetworkTopologyOperationRequestMapper MOCK_networkTopologyOperationRequestMapper;
-
- private L3Network network;
- private ServiceInstance serviceInstance;
- private Customer customer;
- private RequestContext requestContext;
- private CloudRegion cloudRegion;
-
- @Before
- public void before() {
- network = buildL3Network();
-
- customer = buildCustomer();
-
- serviceInstance = buildServiceInstance();
-
- requestContext = buildRequestContext();
-
- cloudRegion = new CloudRegion();
- }
-
- @Test
- public void assignNetworkTest() throws Exception {
- doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
- .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
- GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance,
- customer, requestContext, cloudRegion);
- sdncNetworkResources.assignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
- GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
-
- @Test
- public void rollbackAssignNetworkTest() throws Exception {
- doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
- .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
- GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance,
- customer, requestContext, cloudRegion);
- sdncNetworkResources.rollbackAssignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
- GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
-
- @Test
- public void activateNetworkTest() throws Exception {
- doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
- .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE,
- GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance,
- customer, requestContext, cloudRegion);
- sdncNetworkResources.activateNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE,
- GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
-
- @Test
- public void deleteNetworkTest() throws Exception {
- doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
- .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.DELETE,
- GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance,
- customer, requestContext, cloudRegion);
- sdncNetworkResources.deleteNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.DELETE,
- GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
-
- @Test
- public void test_deactivateNetwork() throws MapperException, BadResponseException {
- doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
- .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE,
- GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance,
- customer, requestContext, cloudRegion);
- sdncNetworkResources.deactivateNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE,
- GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
-
- @Test
- public void changeAssignNetworkTest() throws MapperException, BadResponseException {
- doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
- .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN,
- GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance,
- customer, requestContext, cloudRegion);
- sdncNetworkResources.changeAssignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN,
- GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
-
- @Test
- public void unassignNetwork_Test() throws Exception {
- doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
- .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
- GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance,
- customer, requestContext, cloudRegion);
- sdncNetworkResources.unassignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
- verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
- GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
- }
-} \ No newline at end of file
+ @InjectMocks
+ private SDNCNetworkResources sdncNetworkResources;
+
+ @Mock
+ protected SDNCClient MOCK_sdncClient;
+
+ @Mock
+ protected NetworkTopologyOperationRequestMapper MOCK_networkTopologyOperationRequestMapper;
+
+ private L3Network network;
+ private ServiceInstance serviceInstance;
+ private Customer customer;
+ private RequestContext requestContext;
+ private CloudRegion cloudRegion;
+
+ @Before
+ public void before() {
+ network = buildL3Network();
+
+ customer = buildCustomer();
+
+ serviceInstance = buildServiceInstance();
+
+ requestContext = buildRequestContext();
+
+ cloudRegion = new CloudRegion();
+ }
+
+ @Test
+ public void assignNetworkTest() throws Exception {
+ doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
+ .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance,
+ customer, requestContext, cloudRegion);
+ sdncNetworkResources.assignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
+ verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
+ SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
+
+ @Test
+ public void rollbackAssignNetworkTest() throws Exception {
+ doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
+ .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance,
+ customer, requestContext, cloudRegion);
+ sdncNetworkResources.rollbackAssignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
+ verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
+ SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
+
+ @Test
+ public void activateNetworkTest() throws Exception {
+ doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
+ .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance,
+ customer, requestContext, cloudRegion);
+ sdncNetworkResources.activateNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
+ verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
+ SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
+
+ @Test
+ public void deleteNetworkTest() throws Exception {
+ doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
+ .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.DELETE,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance,
+ customer, requestContext, cloudRegion);
+ sdncNetworkResources.deleteNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
+ verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
+ SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.DELETE,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
+
+ @Test
+ public void test_deactivateNetwork() throws MapperException, BadResponseException {
+ doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
+ .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance,
+ customer, requestContext, cloudRegion);
+ sdncNetworkResources.deactivateNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
+ verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
+ SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
+
+ @Test
+ public void changeAssignNetworkTest() throws MapperException, BadResponseException {
+ doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
+ .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance,
+ customer, requestContext, cloudRegion);
+ sdncNetworkResources.changeAssignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
+ verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
+ SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
+
+ @Test
+ public void unassignNetwork_Test() throws Exception {
+ doReturn(new GenericResourceApiNetworkOperationInformation()).when(MOCK_networkTopologyOperationRequestMapper)
+ .reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance,
+ customer, requestContext, cloudRegion);
+ sdncNetworkResources.unassignNetwork(network, serviceInstance, customer, requestContext, cloudRegion);
+ verify(MOCK_networkTopologyOperationRequestMapper, times(1)).reqMapper(
+ SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
+ requestContext, cloudRegion);
+ }
+}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCServiceInstanceResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCServiceInstanceResourcesTest.java
index 509dc1de0d..ad05ac0072 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCServiceInstanceResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCServiceInstanceResourcesTest.java
@@ -26,7 +26,6 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -46,84 +45,121 @@ import org.onap.so.client.sdnc.beans.SDNCSvcOperation;
import org.onap.so.client.sdnc.mapper.ServiceTopologyOperationMapper;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class SDNCServiceInstanceResourcesTest extends TestDataSetup{
-
- @InjectMocks
+public class SDNCServiceInstanceResourcesTest extends TestDataSetup {
+
+ @InjectMocks
private SDNCServiceInstanceResources sdncServiceInstanceResources;
- @Mock
- protected ServiceTopologyOperationMapper MOCK_serviceTopologyOperationMapper;
- private RequestContext requestContext;
- private ServiceInstance serviceInstance;
- private Customer customer;
-
- @Before
- public void before() {
- requestContext = buildRequestContext();
- serviceInstance = buildServiceInstance();
- customer = buildCustomer();
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- }
-
- @Test
- public void assignServiceInstanceSuccessTest() throws Exception {
- doReturn(new GenericResourceApiServiceOperationInformation()).when(MOCK_serviceTopologyOperationMapper).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.ASSIGN), eq(GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- sdncServiceInstanceResources.assignServiceInstance(serviceInstance, customer, requestContext);
- verify(MOCK_serviceTopologyOperationMapper, times(1)).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.ASSIGN), eq(GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- }
-
- @Test
- public void assignServiceInstanceExceptionTest() throws Exception {
- expectedException.expect(Exception.class);
- doThrow(Exception.class).when(MOCK_serviceTopologyOperationMapper).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.ASSIGN), eq(GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- sdncServiceInstanceResources.assignServiceInstance(serviceInstance, customer, requestContext);
- }
-
- @Test
- public void deleteServiceInstanceSuccessTest() throws Exception {
- doReturn(new GenericResourceApiServiceOperationInformation()).when(MOCK_serviceTopologyOperationMapper).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DELETE), eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- sdncServiceInstanceResources.deleteServiceInstance(serviceInstance, customer, requestContext);
- verify(MOCK_serviceTopologyOperationMapper, times(1)).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DELETE), eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- }
-
- @Test
- public void deleteServiceInstanceExceptionTest() throws Exception {
- expectedException.expect(Exception.class);
- doThrow(Exception.class).when(MOCK_serviceTopologyOperationMapper).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DELETE), eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- sdncServiceInstanceResources.deleteServiceInstance(serviceInstance, customer, requestContext);
- }
-
- @Test
- public void unassignServiceInstanceSuccessTest() throws Exception {
- doReturn(new GenericResourceApiServiceOperationInformation()).when(MOCK_serviceTopologyOperationMapper).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DELETE), eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- sdncServiceInstanceResources.unassignServiceInstance(serviceInstance, customer, requestContext);
- verify(MOCK_serviceTopologyOperationMapper, times(1)).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DELETE), eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- }
-
- @Test
- public void unassignServiceInstanceExceptionTest() throws Exception {
- expectedException.expect(Exception.class);
- doThrow(Exception.class).when(MOCK_serviceTopologyOperationMapper).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DELETE), eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- sdncServiceInstanceResources.unassignServiceInstance(serviceInstance,customer, requestContext);
- }
+ @Mock
+ protected ServiceTopologyOperationMapper MOCK_serviceTopologyOperationMapper;
+ private RequestContext requestContext;
+ private ServiceInstance serviceInstance;
+ private Customer customer;
+
+ @Before
+ public void before() {
+ requestContext = buildRequestContext();
+ serviceInstance = buildServiceInstance();
+ customer = buildCustomer();
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ }
+
+ @Test
+ public void assignServiceInstanceSuccessTest() throws Exception {
+ doReturn(new GenericResourceApiServiceOperationInformation()).when(MOCK_serviceTopologyOperationMapper)
+ .reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.ASSIGN),
+ eq(GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE),
+ any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
+ sdncServiceInstanceResources.assignServiceInstance(serviceInstance, customer, requestContext);
+ verify(MOCK_serviceTopologyOperationMapper, times(1)).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION),
+ eq(SDNCSvcAction.ASSIGN), eq(GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE),
+ any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
+ }
+
+ @Test
+ public void assignServiceInstanceExceptionTest() throws Exception {
+ expectedException.expect(Exception.class);
+ doThrow(Exception.class).when(MOCK_serviceTopologyOperationMapper).reqMapper(
+ eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.ASSIGN),
+ eq(GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE), any(ServiceInstance.class),
+ any(Customer.class), any(RequestContext.class));
+ sdncServiceInstanceResources.assignServiceInstance(serviceInstance, customer, requestContext);
+ }
+
+ @Test
+ public void deleteServiceInstanceSuccessTest() throws Exception {
+ doReturn(new GenericResourceApiServiceOperationInformation()).when(MOCK_serviceTopologyOperationMapper)
+ .reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DELETE),
+ eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE),
+ any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
+ sdncServiceInstanceResources.deleteServiceInstance(serviceInstance, customer, requestContext);
+ verify(MOCK_serviceTopologyOperationMapper, times(1)).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION),
+ eq(SDNCSvcAction.DELETE), eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE),
+ any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
+ }
+
+ @Test
+ public void deleteServiceInstanceExceptionTest() throws Exception {
+ expectedException.expect(Exception.class);
+ doThrow(Exception.class).when(MOCK_serviceTopologyOperationMapper).reqMapper(
+ eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DELETE),
+ eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE), any(ServiceInstance.class),
+ any(Customer.class), any(RequestContext.class));
+ sdncServiceInstanceResources.deleteServiceInstance(serviceInstance, customer, requestContext);
+ }
+
+ @Test
+ public void unassignServiceInstanceSuccessTest() throws Exception {
+ doReturn(new GenericResourceApiServiceOperationInformation()).when(MOCK_serviceTopologyOperationMapper)
+ .reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DELETE),
+ eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE),
+ any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
+ sdncServiceInstanceResources.unassignServiceInstance(serviceInstance, customer, requestContext);
+ verify(MOCK_serviceTopologyOperationMapper, times(1)).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION),
+ eq(SDNCSvcAction.DELETE), eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE),
+ any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
+ }
+
+ @Test
+ public void unassignServiceInstanceExceptionTest() throws Exception {
+ expectedException.expect(Exception.class);
+ doThrow(Exception.class).when(MOCK_serviceTopologyOperationMapper).reqMapper(
+ eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DELETE),
+ eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE), any(ServiceInstance.class),
+ any(Customer.class), any(RequestContext.class));
+ sdncServiceInstanceResources.unassignServiceInstance(serviceInstance, customer, requestContext);
+ }
+
+ @Test
+ public void deactivateServiceInstanceSuccessTest() throws Exception {
+ doReturn(new GenericResourceApiServiceOperationInformation()).when(MOCK_serviceTopologyOperationMapper)
+ .reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DEACTIVATE),
+ eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE),
+ any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
+ sdncServiceInstanceResources.deactivateServiceInstance(serviceInstance, customer, requestContext);
+ verify(MOCK_serviceTopologyOperationMapper, times(1)).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION),
+ eq(SDNCSvcAction.DEACTIVATE), eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE),
+ any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
+ }
- @Test
- public void deactivateServiceInstanceSuccessTest() throws Exception {
- doReturn(new GenericResourceApiServiceOperationInformation()).when(MOCK_serviceTopologyOperationMapper).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DEACTIVATE), eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- sdncServiceInstanceResources.deactivateServiceInstance(serviceInstance, customer, requestContext);
- verify(MOCK_serviceTopologyOperationMapper, times(1)).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DEACTIVATE), eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- }
-
- @Test
- public void deactivateServiceInstanceExceptionTest() throws Exception {
- expectedException.expect(Exception.class);
- doThrow(Exception.class).when(MOCK_serviceTopologyOperationMapper).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DEACTIVATE), eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- sdncServiceInstanceResources.deactivateServiceInstance(serviceInstance, customer, requestContext);
- }
+ @Test
+ public void deactivateServiceInstanceExceptionTest() throws Exception {
+ expectedException.expect(Exception.class);
+ doThrow(Exception.class).when(MOCK_serviceTopologyOperationMapper).reqMapper(
+ eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DEACTIVATE),
+ eq(GenericResourceApiRequestActionEnumeration.DELETESERVICEINSTANCE), any(ServiceInstance.class),
+ any(Customer.class), any(RequestContext.class));
+ sdncServiceInstanceResources.deactivateServiceInstance(serviceInstance, customer, requestContext);
+ }
- @Test
- public void test_changeModelServiceInstance() throws MapperException, BadResponseException {
- doReturn(new GenericResourceApiServiceOperationInformation()).when(MOCK_serviceTopologyOperationMapper).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.CHANGE_ASSIGN), eq(GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- sdncServiceInstanceResources.changeModelServiceInstance(serviceInstance, customer, requestContext);
- verify(MOCK_serviceTopologyOperationMapper, times(1)).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.CHANGE_ASSIGN), eq(GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE), any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
- }
+ @Test
+ public void test_changeModelServiceInstance() throws MapperException, BadResponseException {
+ doReturn(new GenericResourceApiServiceOperationInformation()).when(MOCK_serviceTopologyOperationMapper)
+ .reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION), eq(SDNCSvcAction.CHANGE_ASSIGN),
+ eq(GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE),
+ any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
+ sdncServiceInstanceResources.changeModelServiceInstance(serviceInstance, customer, requestContext);
+ verify(MOCK_serviceTopologyOperationMapper, times(1)).reqMapper(eq(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION),
+ eq(SDNCSvcAction.CHANGE_ASSIGN), eq(GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE),
+ any(ServiceInstance.class), any(Customer.class), any(RequestContext.class));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVfModuleResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVfModuleResourcesTest.java
index 7d05758129..2b45a3302c 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVfModuleResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVfModuleResourcesTest.java
@@ -23,7 +23,6 @@ package org.onap.so.client.orchestration;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -46,77 +45,87 @@ import org.onap.so.client.sdnc.beans.SDNCSvcOperation;
import org.onap.so.client.sdnc.mapper.VfModuleTopologyOperationRequestMapper;;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class SDNCVfModuleResourcesTest extends TestDataSetup{
+public class SDNCVfModuleResourcesTest extends TestDataSetup {
+
+ @InjectMocks
+ private SDNCVfModuleResources sdncVfModuleResources;
+
+ @Mock
+ protected VfModuleTopologyOperationRequestMapper vfModuleTopologyMapper;
+
+ private VfModule vfModule;
+ private GenericVnf vnf;
+ private ServiceInstance serviceInstance;
+ private VolumeGroup volumeGroup;
+ private Customer customer;
+ private CloudRegion cloudRegion;
+ private RequestContext requestContext;
+ private GenericResourceApiVfModuleOperationInformation sdncReq;
+
+ @Before
+ public void before() {
+ vfModule = buildVfModule();
+ vnf = buildGenericVnf();
+ serviceInstance = buildServiceInstance();
+ volumeGroup = buildVolumeGroup();
+ customer = buildCustomer();
+ cloudRegion = buildCloudRegion();
+ requestContext = buildRequestContext();
+ sdncReq = new GenericResourceApiVfModuleOperationInformation();
+ }
+
+ @Test
+ public void assignVfModuleTest() throws MapperException {
+ doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION,
+ SDNCSvcAction.ASSIGN, vfModule, volumeGroup, vnf, serviceInstance, customer, cloudRegion,
+ requestContext, null);
+ sdncVfModuleResources.assignVfModule(vfModule, volumeGroup, vnf, serviceInstance, customer, cloudRegion,
+ requestContext);
+ verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION,
+ SDNCSvcAction.ASSIGN, vfModule, volumeGroup, vnf, serviceInstance, customer, cloudRegion,
+ requestContext, null);
+ }
+
+ @Test
+ public void unassignVfModuleTest() throws MapperException {
+ doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION,
+ SDNCSvcAction.UNASSIGN, vfModule, null, vnf, serviceInstance, null, null, null, null);
+ sdncVfModuleResources.unassignVfModule(vfModule, vnf, serviceInstance);
+ verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION,
+ SDNCSvcAction.UNASSIGN, vfModule, null, vnf, serviceInstance, null, null, null, null);
+ }
+
+ @Test
+ public void activateVfModuleTest() throws MapperException {
+ doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION,
+ SDNCSvcAction.ACTIVATE, vfModule, null, vnf, serviceInstance, customer, cloudRegion, requestContext,
+ null);
+ sdncVfModuleResources.activateVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion, requestContext);
+ verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION,
+ SDNCSvcAction.ACTIVATE, vfModule, null, vnf, serviceInstance, customer, cloudRegion, requestContext,
+ null);
+ }
+
+ @Test
+ public void deactivateVfModuleTest() throws MapperException {
+ doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION,
+ SDNCSvcAction.DEACTIVATE, vfModule, null, vnf, serviceInstance, customer, cloudRegion, requestContext,
+ null);
+ sdncVfModuleResources.deactivateVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion, requestContext);
+ verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION,
+ SDNCSvcAction.DEACTIVATE, vfModule, null, vnf, serviceInstance, customer, cloudRegion, requestContext,
+ null);
+ }
- @InjectMocks
- private SDNCVfModuleResources sdncVfModuleResources;
-
- @Mock
- protected VfModuleTopologyOperationRequestMapper vfModuleTopologyMapper;
-
- private VfModule vfModule;
- private GenericVnf vnf;
- private ServiceInstance serviceInstance;
- private VolumeGroup volumeGroup;
- private Customer customer;
- private CloudRegion cloudRegion;
- private RequestContext requestContext;
- private GenericResourceApiVfModuleOperationInformation sdncReq;
-
- @Before
- public void before() {
- vfModule = buildVfModule();
- vnf = buildGenericVnf();
- serviceInstance = buildServiceInstance();
- volumeGroup = buildVolumeGroup();
- customer = buildCustomer();
- cloudRegion = buildCloudRegion();
- requestContext = buildRequestContext();
- sdncReq = new GenericResourceApiVfModuleOperationInformation();
- }
-
- @Test
- public void assignVfModuleTest() throws MapperException {
- doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule,
- volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext, null);
- sdncVfModuleResources.assignVfModule(vfModule, volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext);
- verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule,
- volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext, null);
- }
-
- @Test
- public void unassignVfModuleTest() throws MapperException {
- doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null,
- vnf, serviceInstance, null, null, null, null);
- sdncVfModuleResources.unassignVfModule(vfModule, vnf, serviceInstance);
- verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null,
- vnf, serviceInstance, null, null, null, null);
- }
-
- @Test
- public void activateVfModuleTest() throws MapperException {
- doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE, vfModule, null,
- vnf, serviceInstance, customer, cloudRegion, requestContext, null);
- sdncVfModuleResources.activateVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion, requestContext);
- verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE, vfModule, null,
- vnf, serviceInstance, customer, cloudRegion, requestContext, null);
- }
-
- @Test
- public void deactivateVfModuleTest() throws MapperException {
- doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE, vfModule, null,
- vnf, serviceInstance, customer, cloudRegion, requestContext, null);
- sdncVfModuleResources.deactivateVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion, requestContext);
- verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE, vfModule, null,
- vnf, serviceInstance, customer, cloudRegion, requestContext, null);
- }
-
- @Test
- public void changeAssignVfModuleTest() throws MapperException, BadResponseException {
- doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN, vfModule,
- null, vnf, serviceInstance, customer, cloudRegion, requestContext, null);
- sdncVfModuleResources.changeAssignVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion, requestContext);
- verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN, vfModule,
- null, vnf, serviceInstance, customer, cloudRegion, requestContext, null);
- }
+ @Test
+ public void changeAssignVfModuleTest() throws MapperException, BadResponseException {
+ doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION,
+ SDNCSvcAction.CHANGE_ASSIGN, vfModule, null, vnf, serviceInstance, customer, cloudRegion,
+ requestContext, null);
+ sdncVfModuleResources.changeAssignVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion,
+ requestContext);
+ verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION,
+ SDNCSvcAction.CHANGE_ASSIGN, vfModule, null, vnf, serviceInstance, customer, cloudRegion,
+ requestContext, null);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVnfResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVnfResourcesTest.java
index 9bbf790ecb..4c0e2b873f 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVnfResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVnfResourcesTest.java
@@ -28,7 +28,6 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -51,103 +50,148 @@ import org.onap.so.client.sdnc.beans.SDNCSvcOperation;
import org.onap.so.client.sdnc.mapper.VnfTopologyOperationRequestMapper;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class SDNCVnfResourcesTest extends TestDataSetup{
- @InjectMocks
- private SDNCVnfResources sdncVnfResources;
-
- @Mock
- protected VnfTopologyOperationRequestMapper MOCK_vnfTopologyOperationRequestMapper;
-
- @Mock
- protected SDNCClient MOCK_sdncClient;
-
- private GenericVnf genericVnf;
- private ServiceInstance serviceInstance;
- private Customer customer;
- private CloudRegion cloudRegion;
- private RequestContext requestContext;
- private GenericResourceApiVnfOperationInformation sdncReq;
-
- @Before
- public void before() {
- serviceInstance = buildServiceInstance();
- genericVnf = buildGenericVnf();
- customer = buildCustomer();
- cloudRegion = buildCloudRegion();
- requestContext = buildRequestContext();
- sdncReq = new GenericResourceApiVnfOperationInformation();
- }
-
- @Test
- public void assignVnfTest() {
- doReturn(sdncReq).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(isA(SDNCSvcOperation.class), isA(SDNCSvcAction.class),isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class), isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class), anyBoolean());
- sdncVnfResources.assignVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext, false);
- verify(MOCK_vnfTopologyOperationRequestMapper, times(1)).reqMapper(isA(SDNCSvcOperation.class), isA(SDNCSvcAction.class),isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class), isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class), anyBoolean());
- }
-
- @Test
- public void activateVnfTest() {
- doReturn(sdncReq).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(isA(SDNCSvcOperation.class), isA(SDNCSvcAction.class),isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class), isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class), anyBoolean());
- sdncVnfResources.activateVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- verify(MOCK_vnfTopologyOperationRequestMapper, times(1)).reqMapper(isA(SDNCSvcOperation.class), isA(SDNCSvcAction.class),isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class), isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class), anyBoolean());
- }
-
- @Test
- public void deleteVnfTest() {
- doReturn(sdncReq).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(isA(SDNCSvcOperation.class), isA(SDNCSvcAction.class),isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class), isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class), anyBoolean());
- sdncVnfResources.deleteVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- verify(MOCK_vnfTopologyOperationRequestMapper, times(1)).reqMapper(isA(SDNCSvcOperation.class), isA(SDNCSvcAction.class),isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class), isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class), anyBoolean());
- }
-
- @Test
- public void queryVnfTest() throws MapperException, BadResponseException {
- doReturn("test").when(MOCK_sdncClient).get(isA(String.class));
- genericVnf.setSelflink("testSelflink");
- sdncVnfResources.queryVnf(genericVnf);
- verify(MOCK_sdncClient, times(1)).get(isA(String.class));
- }
-
- @Test
- public void queryVnfWithResourcePrefixTest() throws MapperException, BadResponseException {
- doReturn("test").when(MOCK_sdncClient).get(isA(String.class));
- genericVnf.setSelflink("restconf/test:testSelflink");
- sdncVnfResources.queryVnf(genericVnf);
- verify(MOCK_sdncClient, times(1)).get(isA(String.class));
- }
-
- @Test
- public void changeModelVnfTest() {
- doReturn(sdncReq).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(isA(SDNCSvcOperation.class), isA(SDNCSvcAction.class),isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class), isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class), anyBoolean());
- sdncVnfResources.changeModelVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- verify(MOCK_vnfTopologyOperationRequestMapper, times(1)).reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN,GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, genericVnf, serviceInstance, customer, cloudRegion, requestContext, false);
- }
-
- @Test
- public void deactivateVnfSuccessTest() {
- doReturn(sdncReq).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(eq(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DEACTIVATE),isA(GenericResourceApiRequestActionEnumeration.class), any(GenericVnf.class),any(ServiceInstance.class), any(Customer.class), any(CloudRegion.class),any(RequestContext.class), anyBoolean());
- sdncVnfResources.deactivateVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- verify(MOCK_vnfTopologyOperationRequestMapper, times(1)).reqMapper(eq(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DEACTIVATE),isA(GenericResourceApiRequestActionEnumeration.class), any(GenericVnf.class),any(ServiceInstance.class), any(Customer.class), any(CloudRegion.class),any(RequestContext.class), anyBoolean());
-
- }
-
- @Test
- public void deactivateVnfExceptionTest() {
- expectedException.expect(Exception.class);
- doThrow(Exception.class).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(eq(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DEACTIVATE),isA(GenericResourceApiRequestActionEnumeration.class), any(GenericVnf.class),any(ServiceInstance.class), any(Customer.class), any(CloudRegion.class),any(RequestContext.class), anyBoolean());
- sdncVnfResources.deactivateVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- }
-
- @Test
- public void unassignVnfSuccessTest() throws Exception {
- doReturn(sdncReq).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(eq(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION), eq(SDNCSvcAction.UNASSIGN),isA(GenericResourceApiRequestActionEnumeration.class), any(GenericVnf.class),any(ServiceInstance.class), any(Customer.class), any(CloudRegion.class),any(RequestContext.class), anyBoolean());
- sdncVnfResources.unassignVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- verify(MOCK_vnfTopologyOperationRequestMapper, times(1)).reqMapper(eq(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION), eq(SDNCSvcAction.UNASSIGN),isA(GenericResourceApiRequestActionEnumeration.class), any(GenericVnf.class),any(ServiceInstance.class), any(Customer.class), any(CloudRegion.class),any(RequestContext.class), anyBoolean());
- }
-
- @Test
- public void unassignVnfExceptionTest() throws Exception {
- expectedException.expect(Exception.class);
- doThrow(Exception.class).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(eq(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION), eq(SDNCSvcAction.UNASSIGN),isA(GenericResourceApiRequestActionEnumeration.class), any(GenericVnf.class),any(ServiceInstance.class), any(Customer.class), any(CloudRegion.class),any(RequestContext.class), anyBoolean());
- sdncVnfResources.unassignVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
- }
+public class SDNCVnfResourcesTest extends TestDataSetup {
+ @InjectMocks
+ private SDNCVnfResources sdncVnfResources;
+
+ @Mock
+ protected VnfTopologyOperationRequestMapper MOCK_vnfTopologyOperationRequestMapper;
+
+ @Mock
+ protected SDNCClient MOCK_sdncClient;
+
+ private GenericVnf genericVnf;
+ private ServiceInstance serviceInstance;
+ private Customer customer;
+ private CloudRegion cloudRegion;
+ private RequestContext requestContext;
+ private GenericResourceApiVnfOperationInformation sdncReq;
+
+ @Before
+ public void before() {
+ serviceInstance = buildServiceInstance();
+ genericVnf = buildGenericVnf();
+ customer = buildCustomer();
+ cloudRegion = buildCloudRegion();
+ requestContext = buildRequestContext();
+ sdncReq = new GenericResourceApiVnfOperationInformation();
+ }
+
+ @Test
+ public void assignVnfTest() {
+ doReturn(sdncReq).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(isA(SDNCSvcOperation.class),
+ isA(SDNCSvcAction.class), isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class),
+ isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class),
+ anyBoolean());
+ sdncVnfResources.assignVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext, false);
+ verify(MOCK_vnfTopologyOperationRequestMapper, times(1)).reqMapper(isA(SDNCSvcOperation.class),
+ isA(SDNCSvcAction.class), isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class),
+ isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class),
+ anyBoolean());
+ }
+
+ @Test
+ public void activateVnfTest() {
+ doReturn(sdncReq).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(isA(SDNCSvcOperation.class),
+ isA(SDNCSvcAction.class), isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class),
+ isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class),
+ anyBoolean());
+ sdncVnfResources.activateVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
+ verify(MOCK_vnfTopologyOperationRequestMapper, times(1)).reqMapper(isA(SDNCSvcOperation.class),
+ isA(SDNCSvcAction.class), isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class),
+ isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class),
+ anyBoolean());
+ }
+
+ @Test
+ public void deleteVnfTest() {
+ doReturn(sdncReq).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(isA(SDNCSvcOperation.class),
+ isA(SDNCSvcAction.class), isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class),
+ isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class),
+ anyBoolean());
+ sdncVnfResources.deleteVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
+ verify(MOCK_vnfTopologyOperationRequestMapper, times(1)).reqMapper(isA(SDNCSvcOperation.class),
+ isA(SDNCSvcAction.class), isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class),
+ isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class),
+ anyBoolean());
+ }
+
+ @Test
+ public void queryVnfTest() throws MapperException, BadResponseException {
+ doReturn("test").when(MOCK_sdncClient).get(isA(String.class));
+ genericVnf.setSelflink("testSelflink");
+ sdncVnfResources.queryVnf(genericVnf);
+ verify(MOCK_sdncClient, times(1)).get(isA(String.class));
+ }
+
+ @Test
+ public void queryVnfWithResourcePrefixTest() throws MapperException, BadResponseException {
+ doReturn("test").when(MOCK_sdncClient).get(isA(String.class));
+ genericVnf.setSelflink("restconf/test:testSelflink");
+ sdncVnfResources.queryVnf(genericVnf);
+ verify(MOCK_sdncClient, times(1)).get(isA(String.class));
+ }
+
+ @Test
+ public void changeModelVnfTest() {
+ doReturn(sdncReq).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(isA(SDNCSvcOperation.class),
+ isA(SDNCSvcAction.class), isA(GenericResourceApiRequestActionEnumeration.class), isA(GenericVnf.class),
+ isA(ServiceInstance.class), isA(Customer.class), isA(CloudRegion.class), isA(RequestContext.class),
+ anyBoolean());
+ sdncVnfResources.changeModelVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
+ verify(MOCK_vnfTopologyOperationRequestMapper, times(1)).reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION,
+ SDNCSvcAction.CHANGE_ASSIGN, GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, genericVnf,
+ serviceInstance, customer, cloudRegion, requestContext, false);
+ }
+
+ @Test
+ public void deactivateVnfSuccessTest() {
+ doReturn(sdncReq).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(
+ eq(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DEACTIVATE),
+ isA(GenericResourceApiRequestActionEnumeration.class), any(GenericVnf.class),
+ any(ServiceInstance.class), any(Customer.class), any(CloudRegion.class), any(RequestContext.class),
+ anyBoolean());
+ sdncVnfResources.deactivateVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
+ verify(MOCK_vnfTopologyOperationRequestMapper, times(1)).reqMapper(eq(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION),
+ eq(SDNCSvcAction.DEACTIVATE), isA(GenericResourceApiRequestActionEnumeration.class),
+ any(GenericVnf.class), any(ServiceInstance.class), any(Customer.class), any(CloudRegion.class),
+ any(RequestContext.class), anyBoolean());
+
+ }
+
+ @Test
+ public void deactivateVnfExceptionTest() {
+ expectedException.expect(Exception.class);
+ doThrow(Exception.class).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(
+ eq(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION), eq(SDNCSvcAction.DEACTIVATE),
+ isA(GenericResourceApiRequestActionEnumeration.class), any(GenericVnf.class),
+ any(ServiceInstance.class), any(Customer.class), any(CloudRegion.class), any(RequestContext.class),
+ anyBoolean());
+ sdncVnfResources.deactivateVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
+ }
+
+ @Test
+ public void unassignVnfSuccessTest() throws Exception {
+ doReturn(sdncReq).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(
+ eq(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION), eq(SDNCSvcAction.UNASSIGN),
+ isA(GenericResourceApiRequestActionEnumeration.class), any(GenericVnf.class),
+ any(ServiceInstance.class), any(Customer.class), any(CloudRegion.class), any(RequestContext.class),
+ anyBoolean());
+ sdncVnfResources.unassignVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
+ verify(MOCK_vnfTopologyOperationRequestMapper, times(1)).reqMapper(eq(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION),
+ eq(SDNCSvcAction.UNASSIGN), isA(GenericResourceApiRequestActionEnumeration.class),
+ any(GenericVnf.class), any(ServiceInstance.class), any(Customer.class), any(CloudRegion.class),
+ any(RequestContext.class), anyBoolean());
+ }
+
+ @Test
+ public void unassignVnfExceptionTest() throws Exception {
+ expectedException.expect(Exception.class);
+ doThrow(Exception.class).when(MOCK_vnfTopologyOperationRequestMapper).reqMapper(
+ eq(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION), eq(SDNCSvcAction.UNASSIGN),
+ isA(GenericResourceApiRequestActionEnumeration.class), any(GenericVnf.class),
+ any(ServiceInstance.class), any(Customer.class), any(CloudRegion.class), any(RequestContext.class),
+ anyBoolean());
+ sdncVnfResources.unassignVnf(genericVnf, serviceInstance, customer, cloudRegion, requestContext);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNOHealthCheckResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNOHealthCheckResourcesTest.java
index 46d87c7ca3..265bb5d3b5 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNOHealthCheckResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNOHealthCheckResourcesTest.java
@@ -24,9 +24,7 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.ArgumentMatchers.any;
-
import java.util.UUID;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -40,29 +38,29 @@ import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
import org.onap.so.client.sdno.SDNOValidator;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class SDNOHealthCheckResourcesTest extends TestDataSetup{
- @InjectMocks
- private SDNOHealthCheckResources sdnoHealthCheckResources = new SDNOHealthCheckResources();
-
- private GenericVnf genericVnf;
- private RequestContext requestContext;
-
- @Mock
- protected SDNOValidator MOCK_sdnoValidator;
-
- @Mock
- protected InjectionHelper MOCK_injectionHelper;
-
- @Before
- public void before() {
- genericVnf = buildGenericVnf();
- requestContext = buildRequestContext();
- doReturn(MOCK_sdnoValidator).when(MOCK_injectionHelper).getSdnoValidator();
- }
-
- @Test
- public void healthCheckTest() throws Exception {
- doReturn(true).when(MOCK_sdnoValidator).healthDiagnostic(any(String.class), any(UUID.class), any(String.class));
- assertTrue(sdnoHealthCheckResources.healthCheck(genericVnf, requestContext));
- }
+public class SDNOHealthCheckResourcesTest extends TestDataSetup {
+ @InjectMocks
+ private SDNOHealthCheckResources sdnoHealthCheckResources = new SDNOHealthCheckResources();
+
+ private GenericVnf genericVnf;
+ private RequestContext requestContext;
+
+ @Mock
+ protected SDNOValidator MOCK_sdnoValidator;
+
+ @Mock
+ protected InjectionHelper MOCK_injectionHelper;
+
+ @Before
+ public void before() {
+ genericVnf = buildGenericVnf();
+ requestContext = buildRequestContext();
+ doReturn(MOCK_sdnoValidator).when(MOCK_injectionHelper).getSdnoValidator();
+ }
+
+ @Test
+ public void healthCheckTest() throws Exception {
+ doReturn(true).when(MOCK_sdnoValidator).healthDiagnostic(any(String.class), any(UUID.class), any(String.class));
+ assertTrue(sdnoHealthCheckResources.healthCheck(genericVnf, requestContext));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResourcesTest.java
index 2de4f11801..4cebd2cde5 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResourcesTest.java
@@ -26,7 +26,6 @@ import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -48,94 +47,102 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule;
import org.onap.so.client.adapter.vnf.mapper.VnfAdapterVfModuleObjectMapper;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class VnfAdapterVfModuleResourcesTest extends TestDataSetup{
- @InjectMocks
- private VnfAdapterVfModuleResources vnfAdapterVfModuleResources = new VnfAdapterVfModuleResources();
-
- @Mock
- protected VnfAdapterVfModuleObjectMapper MOCK_vnfAdapterVfModuleObjectMapper;
-
- private RequestContext requestContext;
- private ServiceInstance serviceInstance;
- private ModelInfoServiceInstance modelInfoServiceInstance;
- private GenericVnf genericVnf;
- private VfModule vfModule;
- private VolumeGroup volumeGroup;
- private ModelInfoVfModule modelInfoVfModule;
- private CloudRegion cloudRegion;
- private OrchestrationContext orchestrationContext;
- private CreateVfModuleRequest createVfModuleRequest;
- private String sdncVnfQueryResponse;
- private String sdncVfModuleQueryResponse;
- private DeleteVfModuleRequest deleteVfModuleRequest;
-
- @Before
- public void before() {
- requestContext = buildRequestContext();
-
- serviceInstance = buildServiceInstance();
-
- genericVnf = buildGenericVnf();
-
- vfModule = buildVfModule();
-
- cloudRegion = buildCloudRegion();
-
- orchestrationContext = buildOrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
-
- sdncVnfQueryResponse = new String();
- sdncVfModuleQueryResponse = new String();
-
- createVfModuleRequest = new CreateVfModuleRequest();
- createVfModuleRequest.setCloudSiteId("cloudSiteId");
-
- deleteVfModuleRequest = new DeleteVfModuleRequest();
- deleteVfModuleRequest.setCloudSiteId("cloudSiteId");
- }
-
- @Test
- public void test_createVfModule() throws Exception {
- doReturn(createVfModuleRequest).when(MOCK_vnfAdapterVfModuleObjectMapper).createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance,
- genericVnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
- CreateVfModuleRequest actualCreateVfModuleRequest = vnfAdapterVfModuleResources.createVfModuleRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance,
- genericVnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
- verify(MOCK_vnfAdapterVfModuleObjectMapper, times(1)).createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance,
- genericVnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
- assertNotNull(createVfModuleRequest);
- assertNotNull(actualCreateVfModuleRequest);
- assertEquals(createVfModuleRequest, actualCreateVfModuleRequest);
- }
-
- @Test
- public void test_createVfModuleWithVolumeGroup() throws Exception {
- volumeGroup = buildVolumeGroup();
- doReturn(createVfModuleRequest).when(MOCK_vnfAdapterVfModuleObjectMapper).createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance,
- genericVnf, vfModule, volumeGroup, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
- CreateVfModuleRequest actualCreateVfModuleRequest = vnfAdapterVfModuleResources.createVfModuleRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance,
- genericVnf, vfModule, volumeGroup, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
- verify(MOCK_vnfAdapterVfModuleObjectMapper, times(1)).createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance,
- genericVnf, vfModule, volumeGroup, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
-
- assertNotNull(createVfModuleRequest);
- assertNotNull(actualCreateVfModuleRequest);
- assertEquals(createVfModuleRequest, actualCreateVfModuleRequest);
- }
-
- @Test
- public void test_deleteVfModule() throws Exception {
- doReturn(deleteVfModuleRequest).when(MOCK_vnfAdapterVfModuleObjectMapper).deleteVfModuleRequestMapper(isA(RequestContext.class), isA(CloudRegion.class), isA(ServiceInstance.class),
- isA(GenericVnf.class), isA(VfModule.class));
-
- DeleteVfModuleRequest actualDeleteVfModuleRequest = vnfAdapterVfModuleResources.deleteVfModuleRequest(requestContext, cloudRegion, serviceInstance,
- genericVnf, vfModule);
-
- verify(MOCK_vnfAdapterVfModuleObjectMapper, times(1)).deleteVfModuleRequestMapper(requestContext, cloudRegion, serviceInstance, genericVnf, vfModule);
- assertEquals(deleteVfModuleRequest, actualDeleteVfModuleRequest);
- }
+public class VnfAdapterVfModuleResourcesTest extends TestDataSetup {
+ @InjectMocks
+ private VnfAdapterVfModuleResources vnfAdapterVfModuleResources = new VnfAdapterVfModuleResources();
+
+ @Mock
+ protected VnfAdapterVfModuleObjectMapper MOCK_vnfAdapterVfModuleObjectMapper;
+
+ private RequestContext requestContext;
+ private ServiceInstance serviceInstance;
+ private ModelInfoServiceInstance modelInfoServiceInstance;
+ private GenericVnf genericVnf;
+ private VfModule vfModule;
+ private VolumeGroup volumeGroup;
+ private ModelInfoVfModule modelInfoVfModule;
+ private CloudRegion cloudRegion;
+ private OrchestrationContext orchestrationContext;
+ private CreateVfModuleRequest createVfModuleRequest;
+ private String sdncVnfQueryResponse;
+ private String sdncVfModuleQueryResponse;
+ private DeleteVfModuleRequest deleteVfModuleRequest;
+
+ @Before
+ public void before() {
+ requestContext = buildRequestContext();
+
+ serviceInstance = buildServiceInstance();
+
+ genericVnf = buildGenericVnf();
+
+ vfModule = buildVfModule();
+
+ cloudRegion = buildCloudRegion();
+
+ orchestrationContext = buildOrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+
+ sdncVnfQueryResponse = new String();
+ sdncVfModuleQueryResponse = new String();
+
+ createVfModuleRequest = new CreateVfModuleRequest();
+ createVfModuleRequest.setCloudSiteId("cloudSiteId");
+
+ deleteVfModuleRequest = new DeleteVfModuleRequest();
+ deleteVfModuleRequest.setCloudSiteId("cloudSiteId");
+ }
+
+ @Test
+ public void test_createVfModule() throws Exception {
+ doReturn(createVfModuleRequest).when(MOCK_vnfAdapterVfModuleObjectMapper).createVfModuleRequestMapper(
+ requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, vfModule, null,
+ sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+ CreateVfModuleRequest actualCreateVfModuleRequest =
+ vnfAdapterVfModuleResources.createVfModuleRequest(requestContext, cloudRegion, orchestrationContext,
+ serviceInstance, genericVnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+ verify(MOCK_vnfAdapterVfModuleObjectMapper, times(1)).createVfModuleRequestMapper(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, genericVnf, vfModule, null, sdncVnfQueryResponse,
+ sdncVfModuleQueryResponse);
+
+ assertNotNull(createVfModuleRequest);
+ assertNotNull(actualCreateVfModuleRequest);
+ assertEquals(createVfModuleRequest, actualCreateVfModuleRequest);
+ }
+
+ @Test
+ public void test_createVfModuleWithVolumeGroup() throws Exception {
+ volumeGroup = buildVolumeGroup();
+ doReturn(createVfModuleRequest).when(MOCK_vnfAdapterVfModuleObjectMapper).createVfModuleRequestMapper(
+ requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, vfModule, volumeGroup,
+ sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+ CreateVfModuleRequest actualCreateVfModuleRequest = vnfAdapterVfModuleResources.createVfModuleRequest(
+ requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, vfModule, volumeGroup,
+ sdncVnfQueryResponse, sdncVfModuleQueryResponse);
+
+ verify(MOCK_vnfAdapterVfModuleObjectMapper, times(1)).createVfModuleRequestMapper(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, genericVnf, vfModule, volumeGroup, sdncVnfQueryResponse,
+ sdncVfModuleQueryResponse);
+
+ assertNotNull(createVfModuleRequest);
+ assertNotNull(actualCreateVfModuleRequest);
+ assertEquals(createVfModuleRequest, actualCreateVfModuleRequest);
+ }
+
+ @Test
+ public void test_deleteVfModule() throws Exception {
+ doReturn(deleteVfModuleRequest).when(MOCK_vnfAdapterVfModuleObjectMapper).deleteVfModuleRequestMapper(
+ isA(RequestContext.class), isA(CloudRegion.class), isA(ServiceInstance.class), isA(GenericVnf.class),
+ isA(VfModule.class));
+
+ DeleteVfModuleRequest actualDeleteVfModuleRequest = vnfAdapterVfModuleResources
+ .deleteVfModuleRequest(requestContext, cloudRegion, serviceInstance, genericVnf, vfModule);
+
+ verify(MOCK_vnfAdapterVfModuleObjectMapper, times(1)).deleteVfModuleRequestMapper(requestContext, cloudRegion,
+ serviceInstance, genericVnf, vfModule);
+ assertEquals(deleteVfModuleRequest, actualDeleteVfModuleRequest);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResourcesTest.java
index b1812a3da9..b23c5bca87 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResourcesTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResourcesTest.java
@@ -24,7 +24,6 @@ import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -46,74 +45,81 @@ import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
import org.onap.so.client.adapter.vnf.VnfVolumeAdapterClientImpl;
import org.onap.so.client.adapter.vnf.mapper.VnfAdapterObjectMapper;
import org.onap.so.db.catalog.beans.OrchestrationStatus;
-
import com.shazam.shazamcrest.matcher.Matchers;
@RunWith(MockitoJUnitRunner.Silent.class)
-public class VnfAdapterVolumeGroupResourcesTest extends TestDataSetup {
- @InjectMocks
- private VnfAdapterVolumeGroupResources vnfAdapterVolumeGroupResources;
-
- @Mock
- protected VnfAdapterObjectMapper MOCK_vnfAdapterObjectMapper;
-
- @Mock
- protected VnfVolumeAdapterClientImpl MOCK_vnfVolumeAdapterClient;
-
- private RequestContext requestContext;
- private ServiceInstance serviceInstance;
- private GenericVnf genericVnf;
- private VfModule vfModule;
- private VolumeGroup volumeGroup;
- private CloudRegion cloudRegion;
- private OrchestrationContext orchestrationContext;
-
- @Before
- public void before() {
- requestContext = buildRequestContext();
- serviceInstance = buildServiceInstance();
- genericVnf = buildGenericVnf();
- serviceInstance.getVnfs().add(genericVnf);
- vfModule = buildVfModule();
- genericVnf.getVfModules().add(vfModule);
- volumeGroup = buildVolumeGroup();
- serviceInstance.getVnfs().get(0).getVolumeGroups().add(volumeGroup);
- cloudRegion = buildCloudRegion();
- orchestrationContext = buildOrchestrationContext();
- orchestrationContext.setIsRollbackEnabled(true);
- }
-
- @Test
- public void test_createVolumeGroup() throws Exception {
- volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
-
- CreateVolumeGroupRequest createVolumeGroupRequest = new CreateVolumeGroupRequest();
- createVolumeGroupRequest.setCloudSiteId("cloudSiteId");
-
- CreateVolumeGroupResponse expectedCreateVolumeGroupResponse = new CreateVolumeGroupResponse();
- expectedCreateVolumeGroupResponse.setVolumeGroupStackId("volumeGroupStackId");
- expectedCreateVolumeGroupResponse.setVolumeGroupCreated(true);
-
- String sdncVfModuleQueryResponse = "sdncVfModuleQueryResponse";
-
- doReturn(createVolumeGroupRequest).when(MOCK_vnfAdapterObjectMapper).createVolumeGroupRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse);
-
- CreateVolumeGroupRequest actualCreateVolumeGroupResponse = vnfAdapterVolumeGroupResources.createVolumeGroupRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse);
-
- verify(MOCK_vnfAdapterObjectMapper, times(1)).createVolumeGroupRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse);
-
- assertThat(createVolumeGroupRequest, Matchers.sameBeanAs(actualCreateVolumeGroupResponse));
- }
-
- @Test
- public void test_deleteVolumeGroup() throws Exception {
- DeleteVolumeGroupRequest deleteVolumeGroupRequest = new DeleteVolumeGroupRequest();
- doReturn(deleteVolumeGroupRequest).when(MOCK_vnfAdapterObjectMapper).deleteVolumeGroupRequestMapper(requestContext, cloudRegion, serviceInstance, volumeGroup);
-
- DeleteVolumeGroupRequest expectedDeleteVolumeGroupRequest = new DeleteVolumeGroupRequest();
- DeleteVolumeGroupRequest actualDeleteVolumeGroupRequest = vnfAdapterVolumeGroupResources.deleteVolumeGroupRequest(requestContext, cloudRegion, serviceInstance, volumeGroup);
-
- verify(MOCK_vnfAdapterObjectMapper, times(1)).deleteVolumeGroupRequestMapper(requestContext, cloudRegion, serviceInstance, volumeGroup);
- assertThat(expectedDeleteVolumeGroupRequest, Matchers.sameBeanAs(actualDeleteVolumeGroupRequest));
- }
+public class VnfAdapterVolumeGroupResourcesTest extends TestDataSetup {
+ @InjectMocks
+ private VnfAdapterVolumeGroupResources vnfAdapterVolumeGroupResources;
+
+ @Mock
+ protected VnfAdapterObjectMapper MOCK_vnfAdapterObjectMapper;
+
+ @Mock
+ protected VnfVolumeAdapterClientImpl MOCK_vnfVolumeAdapterClient;
+
+ private RequestContext requestContext;
+ private ServiceInstance serviceInstance;
+ private GenericVnf genericVnf;
+ private VfModule vfModule;
+ private VolumeGroup volumeGroup;
+ private CloudRegion cloudRegion;
+ private OrchestrationContext orchestrationContext;
+
+ @Before
+ public void before() {
+ requestContext = buildRequestContext();
+ serviceInstance = buildServiceInstance();
+ genericVnf = buildGenericVnf();
+ serviceInstance.getVnfs().add(genericVnf);
+ vfModule = buildVfModule();
+ genericVnf.getVfModules().add(vfModule);
+ volumeGroup = buildVolumeGroup();
+ serviceInstance.getVnfs().get(0).getVolumeGroups().add(volumeGroup);
+ cloudRegion = buildCloudRegion();
+ orchestrationContext = buildOrchestrationContext();
+ orchestrationContext.setIsRollbackEnabled(true);
+ }
+
+ @Test
+ public void test_createVolumeGroup() throws Exception {
+ volumeGroup.setOrchestrationStatus(OrchestrationStatus.ASSIGNED);
+
+ CreateVolumeGroupRequest createVolumeGroupRequest = new CreateVolumeGroupRequest();
+ createVolumeGroupRequest.setCloudSiteId("cloudSiteId");
+
+ CreateVolumeGroupResponse expectedCreateVolumeGroupResponse = new CreateVolumeGroupResponse();
+ expectedCreateVolumeGroupResponse.setVolumeGroupStackId("volumeGroupStackId");
+ expectedCreateVolumeGroupResponse.setVolumeGroupCreated(true);
+
+ String sdncVfModuleQueryResponse = "sdncVfModuleQueryResponse";
+
+ doReturn(createVolumeGroupRequest).when(MOCK_vnfAdapterObjectMapper).createVolumeGroupRequestMapper(
+ requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup,
+ sdncVfModuleQueryResponse);
+
+ CreateVolumeGroupRequest actualCreateVolumeGroupResponse =
+ vnfAdapterVolumeGroupResources.createVolumeGroupRequest(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse);
+
+ verify(MOCK_vnfAdapterObjectMapper, times(1)).createVolumeGroupRequestMapper(requestContext, cloudRegion,
+ orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse);
+
+ assertThat(createVolumeGroupRequest, Matchers.sameBeanAs(actualCreateVolumeGroupResponse));
+ }
+
+ @Test
+ public void test_deleteVolumeGroup() throws Exception {
+ DeleteVolumeGroupRequest deleteVolumeGroupRequest = new DeleteVolumeGroupRequest();
+ doReturn(deleteVolumeGroupRequest).when(MOCK_vnfAdapterObjectMapper)
+ .deleteVolumeGroupRequestMapper(requestContext, cloudRegion, serviceInstance, volumeGroup);
+
+ DeleteVolumeGroupRequest expectedDeleteVolumeGroupRequest = new DeleteVolumeGroupRequest();
+ DeleteVolumeGroupRequest actualDeleteVolumeGroupRequest = vnfAdapterVolumeGroupResources
+ .deleteVolumeGroupRequest(requestContext, cloudRegion, serviceInstance, volumeGroup);
+
+ verify(MOCK_vnfAdapterObjectMapper, times(1)).deleteVolumeGroupRequestMapper(requestContext, cloudRegion,
+ serviceInstance, volumeGroup);
+ assertThat(expectedDeleteVolumeGroupRequest, Matchers.sameBeanAs(actualDeleteVolumeGroupRequest));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/policy/CommonObjectMapperProviderTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/policy/CommonObjectMapperProviderTest.java
index e3f6a1829e..2ff0d1d281 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/policy/CommonObjectMapperProviderTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/policy/CommonObjectMapperProviderTest.java
@@ -22,9 +22,7 @@ package org.onap.so.client.policy;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
import org.junit.Test;
-
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -43,4 +41,4 @@ public class CommonObjectMapperProviderTest {
assertFalse(context.isEnabled(SerializationFeature.WRAP_ROOT_VALUE));
assertFalse(context.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE));
}
-} \ No newline at end of file
+}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdn/common/SdnCommonTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdn/common/SdnCommonTasksTest.java
index 2636aec4a7..9c736b7634 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdn/common/SdnCommonTasksTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdn/common/SdnCommonTasksTest.java
@@ -21,9 +21,7 @@
package org.onap.so.client.sdn.common;
import static org.junit.Assert.assertEquals;
-
import java.util.LinkedHashMap;
-
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
@@ -33,9 +31,9 @@ import org.onap.so.client.exception.MapperException;
import org.onap.so.client.sdnc.SdnCommonTasks;
-public class SdnCommonTasksTest{
+public class SdnCommonTasksTest {
+
-
SdnCommonTasks sdnCommonTasks = new SdnCommonTasks();
@Rule
@@ -60,7 +58,7 @@ public class SdnCommonTasksTest{
@Test
public void validateSDNResponseTest() throws BadResponseException {
- String jsonResponse = "{\"output\":{\"response-code\":\"0\",\"response-message\":\"success\"}}";
+ String jsonResponse = "{\"output\":{\"response-code\":\"0\",\"response-message\":\"success\"}}";
LinkedHashMap<String, Object> responseMap = new LinkedHashMap<>();
LinkedHashMap<String, Object> output = new LinkedHashMap<>();
output.put("response-code", "0");
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientIT.java
index 70f196db8c..0b338bde1d 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientIT.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientIT.java
@@ -25,11 +25,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
import org.onap.so.client.exception.BadResponseException;
@@ -38,43 +36,43 @@ import org.onap.so.client.sdnc.endpoint.SDNCTopology;
import org.skyscreamer.jsonassert.JSONAssert;
public class SDNCClientIT extends BaseIntegrationTest {
- private final static String JSON_FILE_LOCATION = "src/test/resources/__files/";
-
+ private final static String JSON_FILE_LOCATION = "src/test/resources/__files/";
+
@Test
public void getTest() throws BadResponseException, MapperException, IOException {
- String responseJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "SDNCClientGetResponse.json")));
- String queryLink = "/topologyQuery";
-
- wireMockServer.stubFor(get(urlEqualTo(queryLink))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json").withBody(responseJson)));
+ String responseJson =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "SDNCClientGetResponse.json")));
+ String queryLink = "/topologyQuery";
+
+ wireMockServer.stubFor(get(urlEqualTo(queryLink)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(responseJson)));
String response = SPY_sdncClient.get(queryLink);
JSONAssert.assertEquals(responseJson, response, false);
}
-
+
@Test(expected = BadResponseException.class)
public void post404Test() throws BadResponseException, MapperException, IOException {
- String responseJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "SDNCClientPut404Response.json")));
-
- String queryLink = "/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation/";
-
- wireMockServer.stubFor(post(urlMatching(queryLink))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json").withBody(responseJson)));
-
+ String responseJson =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "SDNCClientPut404Response.json")));
+
+ String queryLink = "/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation/";
+
+ wireMockServer.stubFor(post(urlMatching(queryLink)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(responseJson)));
+
SPY_sdncClient.post("", SDNCTopology.NETWORK);
}
-
+
@Test
public void post200Test() throws BadResponseException, MapperException, IOException {
- String responseJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "SDNCClientPut200Response.json")));
-
- String queryLink = "/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation/";
-
- wireMockServer.stubFor(post(urlMatching(queryLink))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json").withBody(responseJson)));
-
+ String responseJson =
+ new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "SDNCClientPut200Response.json")));
+
+ String queryLink = "/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation/";
+
+ wireMockServer.stubFor(post(urlMatching(queryLink)).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(responseJson)));
+
String response = SPY_sdncClient.post("", SDNCTopology.NETWORK);
JSONAssert.assertEquals(responseJson, response, true);
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java
index 302bb551c3..0eb0304cdf 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java
@@ -25,7 +25,6 @@ import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -47,11 +46,11 @@ import org.onap.so.client.sdnc.beans.SDNCSvcAction;
@RunWith(MockitoJUnitRunner.Silent.class)
public class GCTopologyOperationRequestMapperTest extends TestDataSetup {
-
- @Spy
- private GeneralTopologyObjectMapper generalTopologyObjectMapper;
-
- @InjectMocks
+
+ @Spy
+ private GeneralTopologyObjectMapper generalTopologyObjectMapper;
+
+ @InjectMocks
private GCTopologyOperationRequestMapper genObjMapper = new GCTopologyOperationRequestMapper();
@Test
@@ -63,8 +62,9 @@ public class GCTopologyOperationRequestMapperTest extends TestDataSetup {
Configuration Configuration = new Configuration();
Configuration.setConfigurationId("ConfigurationId");
Configuration.setConfigurationType("VLAN-NETWORK-RECEPTOR");
- GenericResourceApiGcTopologyOperationInformation genericInfo = genObjMapper.deactivateOrUnassignVnrReqMapper
- (SDNCSvcAction.UNASSIGN, serviceInstance, requestContext, Configuration,"uuid",new URI("http://localhost"));
+ GenericResourceApiGcTopologyOperationInformation genericInfo =
+ genObjMapper.deactivateOrUnassignVnrReqMapper(SDNCSvcAction.UNASSIGN, serviceInstance, requestContext,
+ Configuration, "uuid", new URI("http://localhost"));
Assert.assertNotNull(genericInfo);
Assert.assertNotNull(genericInfo.getRequestInformation());
@@ -73,9 +73,9 @@ public class GCTopologyOperationRequestMapperTest extends TestDataSetup {
Assert.assertNotNull(genericInfo.getServiceInformation());
Assert.assertEquals("ConfigurationId", genericInfo.getConfigurationInformation().getConfigurationId());
Assert.assertEquals("VLAN-NETWORK-RECEPTOR", genericInfo.getConfigurationInformation().getConfigurationType());
- Assert.assertEquals("uuid",genericInfo.getSdncRequestHeader().getSvcRequestId());
- Assert.assertEquals("http://localhost",genericInfo.getSdncRequestHeader().getSvcNotificationUrl());
- Assert.assertEquals("MsoRequestId",genericInfo.getRequestInformation().getRequestId());
+ Assert.assertEquals("uuid", genericInfo.getSdncRequestHeader().getSvcRequestId());
+ Assert.assertEquals("http://localhost", genericInfo.getSdncRequestHeader().getSvcNotificationUrl());
+ Assert.assertEquals("MsoRequestId", genericInfo.getRequestInformation().getRequestId());
}
@@ -99,8 +99,8 @@ public class GCTopologyOperationRequestMapperTest extends TestDataSetup {
}
private Map<String, Object> getUserParams() {
- Map<String,Object> userParams = new HashMap<>();
- userParams.put("lppCustomerId","lppCustomerId");
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("lppCustomerId", "lppCustomerId");
return userParams;
}
@@ -148,7 +148,7 @@ public class GCTopologyOperationRequestMapperTest extends TestDataSetup {
return ipv4subnet;
}
- private ServiceInstance buildServiceInstance(GenericVnf vnf) {
+ private ServiceInstance buildServiceInstance(GenericVnf vnf) {
ServiceInstance serviceInstance = new ServiceInstance();
serviceInstance.setServiceInstanceId("ServiceInstanceId");
List<GenericVnf> vnfs = serviceInstance.getVnfs();
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapperTest.java
index 630bccee9d..88a291e68b 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapperTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapperTest.java
@@ -27,10 +27,8 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
-
import java.util.HashMap;
import java.util.Map;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
@@ -66,365 +64,383 @@ import org.onap.so.client.exception.MapperException;
import org.onap.so.client.sdnc.beans.SDNCSvcAction;
-public class GeneralTopologyObjectMapperTest extends TestDataSetup {
- @InjectMocks
- private GeneralTopologyObjectMapper genObjMapper = new GeneralTopologyObjectMapper();
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Before
- public void before() {
-
- }
-
- @After
- public void after() {
-
- }
-
- @Test
- public void testBuildServiceInformation() {
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
-
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
- // prepare Customer object
- Customer customer = new Customer();
- customer.setGlobalCustomerId("globalCustomerId");
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- serviceSubscription.setServiceType("productFamilyId");
- customer.setServiceSubscription(serviceSubscription);
- // set Customer on service instance
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- //
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value1");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericResourceApiServiceinformationServiceInformation serviceInfo = genObjMapper.buildServiceInformation(serviceInstance, requestContext, customer, true);
-
- assertEquals("serviceModelInvariantUuid", serviceInfo.getOnapModelInformation().getModelInvariantUuid());
- assertEquals("serviceModelName", serviceInfo.getOnapModelInformation().getModelName());
- assertEquals("serviceModelUuid", serviceInfo.getOnapModelInformation().getModelUuid());
- assertEquals("serviceModelVersion", serviceInfo.getOnapModelInformation().getModelVersion());
- assertNull(serviceInfo.getOnapModelInformation().getModelCustomizationUuid());
- assertEquals("serviceInstanceId", serviceInfo.getServiceInstanceId());
- assertEquals("serviceInstanceId", serviceInfo.getServiceId());
- assertEquals("globalCustomerId", serviceInfo.getGlobalCustomerId());
- assertEquals("productFamilyId", serviceInfo.getSubscriptionServiceType());
- }
-
- @Test
- public void buildSdncRequestHeaderActivateTest() {
- GenericResourceApiSdncrequestheaderSdncRequestHeader requestHeader = genObjMapper.buildSdncRequestHeader(SDNCSvcAction.ACTIVATE, "sdncReqId");
-
- assertEquals(GenericResourceApiSvcActionEnumeration.ACTIVATE, requestHeader.getSvcAction());
- assertEquals("sdncReqId", requestHeader.getSvcRequestId());
- }
-
- @Test
- public void buildSdncRequestHeaderAssignTest() {
- GenericResourceApiSdncrequestheaderSdncRequestHeader requestHeader = genObjMapper.buildSdncRequestHeader(SDNCSvcAction.ASSIGN, "sdncReqId");
-
- assertEquals(GenericResourceApiSvcActionEnumeration.ASSIGN, requestHeader.getSvcAction());
- assertEquals("sdncReqId", requestHeader.getSvcRequestId());
- }
-
- @Test
- public void buildSdncRequestHeaderDeactivateTest() {
- GenericResourceApiSdncrequestheaderSdncRequestHeader requestHeader = genObjMapper.buildSdncRequestHeader(SDNCSvcAction.DEACTIVATE, "sdncReqId");
-
- assertEquals(GenericResourceApiSvcActionEnumeration.DEACTIVATE, requestHeader.getSvcAction());
- assertEquals("sdncReqId", requestHeader.getSvcRequestId());
- }
-
- @Test
- public void buildSdncRequestHeaderDeleteTest() {
- GenericResourceApiSdncrequestheaderSdncRequestHeader requestHeader = genObjMapper.buildSdncRequestHeader(SDNCSvcAction.DELETE, "sdncReqId");
-
- assertEquals(GenericResourceApiSvcActionEnumeration.DELETE, requestHeader.getSvcAction());
- assertEquals("sdncReqId", requestHeader.getSvcRequestId());
- }
-
- @Test
- public void buildSdncRequestHeaderChangeAssignTest() {
- GenericResourceApiSdncrequestheaderSdncRequestHeader requestHeader = genObjMapper.buildSdncRequestHeader(SDNCSvcAction.CHANGE_ASSIGN, "sdncReqId");
-
- assertEquals(GenericResourceApiSvcActionEnumeration.CHANGEASSIGN, requestHeader.getSvcAction());
- assertEquals("sdncReqId", requestHeader.getSvcRequestId());
- }
-
- @Test
- public void buildConfigurationInformationTest_excludesOnapModelInfo() {
- Configuration configuration = new Configuration();
- configuration.setConfigurationId("testConfigurationId");
- configuration.setConfigurationType("VNR");
- configuration.setConfigurationName("VNRCONF");
- GenericResourceApiConfigurationinformationConfigurationInformation configurationInformation =genObjMapper.buildConfigurationInformation(configuration,false);
- assertEquals(configuration.getConfigurationId(),configurationInformation.getConfigurationId());
- assertEquals(configuration.getConfigurationType(),configurationInformation.getConfigurationType());
- assertEquals(configuration.getConfigurationName(),configurationInformation.getConfigurationName());
- assertNull(configurationInformation.getOnapModelInformation());
- }
-
- @Test
- public void buildConfigurationInformationTest_includesOnapModelInfo() {
- Configuration configuration = new Configuration();
- configuration.setConfigurationId("testConfigurationId");
- configuration.setConfigurationType("VNR");
- configuration.setConfigurationName("VNRCONF");
- ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
- modelInfoConfiguration.setModelVersionId("modelVersionId");
- modelInfoConfiguration.setModelInvariantId("modelInvariantId");
- modelInfoConfiguration.setModelCustomizationId("modelCustomizationId");
- configuration.setModelInfoConfiguration(modelInfoConfiguration);
-
- GenericResourceApiConfigurationinformationConfigurationInformation configurationInformation = genObjMapper.buildConfigurationInformation(configuration,true);
-
- assertEquals(configuration.getConfigurationId(),configurationInformation.getConfigurationId());
- assertEquals(configuration.getConfigurationType(),configurationInformation.getConfigurationType());
- assertEquals(configuration.getConfigurationName(),configurationInformation.getConfigurationName());
- assertNotNull(configurationInformation.getOnapModelInformation());
- assertEquals(configuration.getModelInfoConfiguration().getModelVersionId(),configurationInformation.getOnapModelInformation().getModelUuid());
- assertEquals(configuration.getModelInfoConfiguration().getModelInvariantId(),configurationInformation.getOnapModelInformation().getModelInvariantUuid());
- assertEquals(configuration.getModelInfoConfiguration().getModelCustomizationId(),configurationInformation.getOnapModelInformation().getModelCustomizationUuid());
-
- }
-
- @Test
- public void buildGcRequestInformationTest() {
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("TestVnfId");
- GenericResourceApiGcrequestinputGcRequestInput gcRequestInput = genObjMapper.buildGcRequestInformation(vnf,null);
- assertNotNull(gcRequestInput);
- assertEquals(vnf.getVnfId(),gcRequestInput.getVnfId());
- assertNull(gcRequestInput.getInputParameters());
- }
-
- @Test
- public void buildGcRequestInformationTest_withInputParams() {
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("TestVnfId");
- GenericResourceApiParam genericResourceApiParam =new GenericResourceApiParam();
- genericResourceApiParam.addParamItem(new GenericResourceApiParamParam());
- GenericResourceApiGcrequestinputGcRequestInput gcRequestInput = genObjMapper.buildGcRequestInformation(vnf,genericResourceApiParam);
- assertNotNull(gcRequestInput);
- assertEquals(vnf.getVnfId(),gcRequestInput.getVnfId());
- assertNotNull(gcRequestInput.getInputParameters());
- }
-
- @Test
- public void buildVnfInformationTest_withNullData() {
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("TestVnfId");
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- GenericResourceApiVnfinformationVnfInformation gcRequestInput = genObjMapper.buildVnfInformation(vnf,serviceInstance,true);
- assertNotNull(gcRequestInput);
- assertNull(vnf.getModelInfoGenericVnf());
- assertNull(gcRequestInput.getOnapModelInformation());
- assertEquals(vnf.getVnfId(),gcRequestInput.getVnfId());
- assertNotNull(gcRequestInput.getVnfId());
- }
-
- @Test
- public void buildNetworkInformationTest() {
-
- L3Network network = new L3Network();
- ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
- modelInfoNetwork.setModelInvariantUUID("my-uuid");
- modelInfoNetwork.setModelName("my-model-name");
- modelInfoNetwork.setModelVersion("my-model-version");
- modelInfoNetwork.setModelUUID("my-model-uuid");
- modelInfoNetwork.setModelCustomizationUUID("my-customization-uuid");
- network.setModelInfoNetwork(modelInfoNetwork);
- network.setNetworkId("my-network-id");
- network.setNetworkType("my-network-type");
- network.setNetworkTechnology("my-network-technology");
-
- GenericResourceApiNetworkinformationNetworkInformation networkInformation = new GenericResourceApiNetworkinformationNetworkInformation();
- GenericResourceApiOnapmodelinformationOnapModelInformation onapModelInformation = new GenericResourceApiOnapmodelinformationOnapModelInformation();
- networkInformation.setNetworkId("my-network-id");
- networkInformation.setNetworkType("my-network-type");
- networkInformation.networkTechnology("my-network-technology");
- networkInformation.setFromPreload(null);
- onapModelInformation.setModelInvariantUuid("my-uuid");
- onapModelInformation.setModelName("my-model-name");
- onapModelInformation.setModelVersion("my-model-version");
- onapModelInformation.setModelUuid("my-model-uuid");
- onapModelInformation.setModelCustomizationUuid("my-customization-uuid");
- networkInformation.setOnapModelInformation(onapModelInformation);
-
- assertThat(networkInformation, sameBeanAs(genObjMapper.buildNetworkInformation(network)));
-
- }
-
- @Test
- public void buildNetworkInformationNoModelTest() {
-
- L3Network network = new L3Network();
- network.setNetworkId("my-network-id");
- network.setNetworkType("my-network-type");
- network.setNetworkTechnology("my-network-technology");
-
- GenericResourceApiNetworkinformationNetworkInformation networkInformation = new GenericResourceApiNetworkinformationNetworkInformation();
- networkInformation.setNetworkId("my-network-id");
- networkInformation.setNetworkType("my-network-type");
- networkInformation.networkTechnology("my-network-technology");
- networkInformation.setFromPreload(null);
-
-
- assertThat(networkInformation, sameBeanAs(genObjMapper.buildNetworkInformation(network)));
-
- }
-
-
- @Test
- public void buildVfModuleInformationTest_withNoModelIsFromPreload() {
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("TestVfModuleId");
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId("TestVnfId");
- RequestContext requestContext = new RequestContext();
- RequestParameters requestParameters = new RequestParameters();
- requestParameters.setUsePreload(true);
- requestContext.setRequestParameters(requestParameters);
- GenericResourceApiVfmoduleinformationVfModuleInformation gcRequestInput = null;
- try {
- gcRequestInput = genObjMapper.buildVfModuleInformation(vfModule, genericVnf, serviceInstance, requestContext, false);
- }
- catch (MapperException ex) {
-
- }
- assertNotNull(gcRequestInput);
- assertNull(vfModule.getModelInfoVfModule());
- assertNull(gcRequestInput.getOnapModelInformation());
- assertEquals(vfModule.getVfModuleId(),gcRequestInput.getVfModuleId());
- assertNotNull(gcRequestInput.getVfModuleId());
- assertTrue(gcRequestInput.getFromPreload());
- }
-
- @Test
- public void buildVfModuleInformationTest_withNoModelIsNotFromPreload() {
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("TestVfModuleId");
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId("TestVnfId");
- RequestContext requestContext = new RequestContext();
- RequestParameters requestParameters = new RequestParameters();
- requestParameters.setUsePreload(false);
- requestContext.setRequestParameters(requestParameters);
- GenericResourceApiVfmoduleinformationVfModuleInformation gcRequestInput = null;
- try {
- gcRequestInput = genObjMapper.buildVfModuleInformation(vfModule, genericVnf, serviceInstance, requestContext, false);
- }
- catch (MapperException ex) {
-
- }
- assertNotNull(gcRequestInput);
- assertNull(vfModule.getModelInfoVfModule());
- assertNull(gcRequestInput.getOnapModelInformation());
- assertEquals(vfModule.getVfModuleId(),gcRequestInput.getVfModuleId());
- assertNotNull(gcRequestInput.getVfModuleId());
- assertFalse(gcRequestInput.getFromPreload());
- }
-
- @Test
- public void buildVfModuleInformationTest_withNoModelNoRequestContext() {
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("TestVfModuleId");
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId("TestVnfId");
- GenericResourceApiVfmoduleinformationVfModuleInformation gcRequestInput = null;
- try {
- gcRequestInput = genObjMapper.buildVfModuleInformation(vfModule, genericVnf, serviceInstance, null, false);
- }
- catch (MapperException ex) {
-
- }
- assertNotNull(gcRequestInput);
- assertNull(vfModule.getModelInfoVfModule());
- assertNull(gcRequestInput.getOnapModelInformation());
- assertEquals(vfModule.getVfModuleId(),gcRequestInput.getVfModuleId());
- assertNotNull(gcRequestInput.getVfModuleId());
- assertTrue(gcRequestInput.getFromPreload());
- }
-
- @Test
- public void buildVfModuleInformationTest_withNoModelNoRequestParameters() {
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("TestVfModuleId");
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId("TestVnfId");
- RequestContext requestContext = new RequestContext();
- GenericResourceApiVfmoduleinformationVfModuleInformation gcRequestInput = null;
- try {
- gcRequestInput = genObjMapper.buildVfModuleInformation(vfModule, genericVnf, serviceInstance, requestContext, false);
- }
- catch (MapperException ex) {
-
- }
- assertNotNull(gcRequestInput);
- assertNull(vfModule.getModelInfoVfModule());
- assertNull(gcRequestInput.getOnapModelInformation());
- assertEquals(vfModule.getVfModuleId(),gcRequestInput.getVfModuleId());
- assertNotNull(gcRequestInput.getVfModuleId());
- assertTrue(gcRequestInput.getFromPreload());
- }
-
- @Test
- public void buildVfModuleInformationTest_withModel() {
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("TestVfModuleId");
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("testModelInvariantUUID");
- modelInfoVfModule.setModelName("testModelName");
- modelInfoVfModule.setModelVersion("testModelVersion");
- modelInfoVfModule.setModelUUID("testModelUUID");
- modelInfoVfModule.setModelCustomizationUUID("testModelCustomizationUUID");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setVnfId("TestVnfId");
- RequestContext requestContext = new RequestContext();
- RequestParameters requestParameters = new RequestParameters();
- requestParameters.setUsePreload(true);
- requestContext.setRequestParameters(requestParameters);
- GenericResourceApiVfmoduleinformationVfModuleInformation gcRequestInput = null;
- try {
- gcRequestInput = genObjMapper.buildVfModuleInformation(vfModule, genericVnf, serviceInstance, requestContext, true);
- }
- catch (MapperException ex) {
-
- }
- assertNotNull(gcRequestInput);
- assertNotNull(vfModule.getModelInfoVfModule());
- assertNotNull(gcRequestInput.getOnapModelInformation());
- assertEquals(modelInfoVfModule.getModelInvariantUUID(), gcRequestInput.getOnapModelInformation().getModelInvariantUuid());
- assertEquals(modelInfoVfModule.getModelName(), gcRequestInput.getOnapModelInformation().getModelName());
- assertEquals(modelInfoVfModule.getModelVersion(), gcRequestInput.getOnapModelInformation().getModelVersion());
- assertEquals(modelInfoVfModule.getModelUUID(), gcRequestInput.getOnapModelInformation().getModelUuid());
- assertEquals(modelInfoVfModule.getModelCustomizationUUID(), gcRequestInput.getOnapModelInformation().getModelCustomizationUuid());
- assertEquals(vfModule.getVfModuleId(),gcRequestInput.getVfModuleId());
- assertNotNull(gcRequestInput.getVfModuleId());
- assertTrue(gcRequestInput.getFromPreload());
- }
+public class GeneralTopologyObjectMapperTest extends TestDataSetup {
+ @InjectMocks
+ private GeneralTopologyObjectMapper genObjMapper = new GeneralTopologyObjectMapper();
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Before
+ public void before() {
+
+ }
+
+ @After
+ public void after() {
+
+ }
+
+ @Test
+ public void testBuildServiceInformation() {
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+ // prepare Customer object
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("globalCustomerId");
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ serviceSubscription.setServiceType("productFamilyId");
+ customer.setServiceSubscription(serviceSubscription);
+ // set Customer on service instance
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ //
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value1");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericResourceApiServiceinformationServiceInformation serviceInfo =
+ genObjMapper.buildServiceInformation(serviceInstance, requestContext, customer, true);
+
+ assertEquals("serviceModelInvariantUuid", serviceInfo.getOnapModelInformation().getModelInvariantUuid());
+ assertEquals("serviceModelName", serviceInfo.getOnapModelInformation().getModelName());
+ assertEquals("serviceModelUuid", serviceInfo.getOnapModelInformation().getModelUuid());
+ assertEquals("serviceModelVersion", serviceInfo.getOnapModelInformation().getModelVersion());
+ assertNull(serviceInfo.getOnapModelInformation().getModelCustomizationUuid());
+ assertEquals("serviceInstanceId", serviceInfo.getServiceInstanceId());
+ assertEquals("serviceInstanceId", serviceInfo.getServiceId());
+ assertEquals("globalCustomerId", serviceInfo.getGlobalCustomerId());
+ assertEquals("productFamilyId", serviceInfo.getSubscriptionServiceType());
+ }
+
+ @Test
+ public void buildSdncRequestHeaderActivateTest() {
+ GenericResourceApiSdncrequestheaderSdncRequestHeader requestHeader =
+ genObjMapper.buildSdncRequestHeader(SDNCSvcAction.ACTIVATE, "sdncReqId");
+
+ assertEquals(GenericResourceApiSvcActionEnumeration.ACTIVATE, requestHeader.getSvcAction());
+ assertEquals("sdncReqId", requestHeader.getSvcRequestId());
+ }
+
+ @Test
+ public void buildSdncRequestHeaderAssignTest() {
+ GenericResourceApiSdncrequestheaderSdncRequestHeader requestHeader =
+ genObjMapper.buildSdncRequestHeader(SDNCSvcAction.ASSIGN, "sdncReqId");
+
+ assertEquals(GenericResourceApiSvcActionEnumeration.ASSIGN, requestHeader.getSvcAction());
+ assertEquals("sdncReqId", requestHeader.getSvcRequestId());
+ }
+
+ @Test
+ public void buildSdncRequestHeaderDeactivateTest() {
+ GenericResourceApiSdncrequestheaderSdncRequestHeader requestHeader =
+ genObjMapper.buildSdncRequestHeader(SDNCSvcAction.DEACTIVATE, "sdncReqId");
+
+ assertEquals(GenericResourceApiSvcActionEnumeration.DEACTIVATE, requestHeader.getSvcAction());
+ assertEquals("sdncReqId", requestHeader.getSvcRequestId());
+ }
+
+ @Test
+ public void buildSdncRequestHeaderDeleteTest() {
+ GenericResourceApiSdncrequestheaderSdncRequestHeader requestHeader =
+ genObjMapper.buildSdncRequestHeader(SDNCSvcAction.DELETE, "sdncReqId");
+
+ assertEquals(GenericResourceApiSvcActionEnumeration.DELETE, requestHeader.getSvcAction());
+ assertEquals("sdncReqId", requestHeader.getSvcRequestId());
+ }
+
+ @Test
+ public void buildSdncRequestHeaderChangeAssignTest() {
+ GenericResourceApiSdncrequestheaderSdncRequestHeader requestHeader =
+ genObjMapper.buildSdncRequestHeader(SDNCSvcAction.CHANGE_ASSIGN, "sdncReqId");
+
+ assertEquals(GenericResourceApiSvcActionEnumeration.CHANGEASSIGN, requestHeader.getSvcAction());
+ assertEquals("sdncReqId", requestHeader.getSvcRequestId());
+ }
+
+ @Test
+ public void buildConfigurationInformationTest_excludesOnapModelInfo() {
+ Configuration configuration = new Configuration();
+ configuration.setConfigurationId("testConfigurationId");
+ configuration.setConfigurationType("VNR");
+ configuration.setConfigurationName("VNRCONF");
+ GenericResourceApiConfigurationinformationConfigurationInformation configurationInformation =
+ genObjMapper.buildConfigurationInformation(configuration, false);
+ assertEquals(configuration.getConfigurationId(), configurationInformation.getConfigurationId());
+ assertEquals(configuration.getConfigurationType(), configurationInformation.getConfigurationType());
+ assertEquals(configuration.getConfigurationName(), configurationInformation.getConfigurationName());
+ assertNull(configurationInformation.getOnapModelInformation());
+ }
+
+ @Test
+ public void buildConfigurationInformationTest_includesOnapModelInfo() {
+ Configuration configuration = new Configuration();
+ configuration.setConfigurationId("testConfigurationId");
+ configuration.setConfigurationType("VNR");
+ configuration.setConfigurationName("VNRCONF");
+ ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration();
+ modelInfoConfiguration.setModelVersionId("modelVersionId");
+ modelInfoConfiguration.setModelInvariantId("modelInvariantId");
+ modelInfoConfiguration.setModelCustomizationId("modelCustomizationId");
+ configuration.setModelInfoConfiguration(modelInfoConfiguration);
+
+ GenericResourceApiConfigurationinformationConfigurationInformation configurationInformation =
+ genObjMapper.buildConfigurationInformation(configuration, true);
+
+ assertEquals(configuration.getConfigurationId(), configurationInformation.getConfigurationId());
+ assertEquals(configuration.getConfigurationType(), configurationInformation.getConfigurationType());
+ assertEquals(configuration.getConfigurationName(), configurationInformation.getConfigurationName());
+ assertNotNull(configurationInformation.getOnapModelInformation());
+ assertEquals(configuration.getModelInfoConfiguration().getModelVersionId(),
+ configurationInformation.getOnapModelInformation().getModelUuid());
+ assertEquals(configuration.getModelInfoConfiguration().getModelInvariantId(),
+ configurationInformation.getOnapModelInformation().getModelInvariantUuid());
+ assertEquals(configuration.getModelInfoConfiguration().getModelCustomizationId(),
+ configurationInformation.getOnapModelInformation().getModelCustomizationUuid());
+
+ }
+
+ @Test
+ public void buildGcRequestInformationTest() {
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("TestVnfId");
+ GenericResourceApiGcrequestinputGcRequestInput gcRequestInput =
+ genObjMapper.buildGcRequestInformation(vnf, null);
+ assertNotNull(gcRequestInput);
+ assertEquals(vnf.getVnfId(), gcRequestInput.getVnfId());
+ assertNull(gcRequestInput.getInputParameters());
+ }
+
+ @Test
+ public void buildGcRequestInformationTest_withInputParams() {
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("TestVnfId");
+ GenericResourceApiParam genericResourceApiParam = new GenericResourceApiParam();
+ genericResourceApiParam.addParamItem(new GenericResourceApiParamParam());
+ GenericResourceApiGcrequestinputGcRequestInput gcRequestInput =
+ genObjMapper.buildGcRequestInformation(vnf, genericResourceApiParam);
+ assertNotNull(gcRequestInput);
+ assertEquals(vnf.getVnfId(), gcRequestInput.getVnfId());
+ assertNotNull(gcRequestInput.getInputParameters());
+ }
+
+ @Test
+ public void buildVnfInformationTest_withNullData() {
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("TestVnfId");
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ GenericResourceApiVnfinformationVnfInformation gcRequestInput =
+ genObjMapper.buildVnfInformation(vnf, serviceInstance, true);
+ assertNotNull(gcRequestInput);
+ assertNull(vnf.getModelInfoGenericVnf());
+ assertNull(gcRequestInput.getOnapModelInformation());
+ assertEquals(vnf.getVnfId(), gcRequestInput.getVnfId());
+ assertNotNull(gcRequestInput.getVnfId());
+ }
+
+ @Test
+ public void buildNetworkInformationTest() {
+
+ L3Network network = new L3Network();
+ ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
+ modelInfoNetwork.setModelInvariantUUID("my-uuid");
+ modelInfoNetwork.setModelName("my-model-name");
+ modelInfoNetwork.setModelVersion("my-model-version");
+ modelInfoNetwork.setModelUUID("my-model-uuid");
+ modelInfoNetwork.setModelCustomizationUUID("my-customization-uuid");
+ network.setModelInfoNetwork(modelInfoNetwork);
+ network.setNetworkId("my-network-id");
+ network.setNetworkType("my-network-type");
+ network.setNetworkTechnology("my-network-technology");
+
+ GenericResourceApiNetworkinformationNetworkInformation networkInformation =
+ new GenericResourceApiNetworkinformationNetworkInformation();
+ GenericResourceApiOnapmodelinformationOnapModelInformation onapModelInformation =
+ new GenericResourceApiOnapmodelinformationOnapModelInformation();
+ networkInformation.setNetworkId("my-network-id");
+ networkInformation.setNetworkType("my-network-type");
+ networkInformation.networkTechnology("my-network-technology");
+ networkInformation.setFromPreload(null);
+ onapModelInformation.setModelInvariantUuid("my-uuid");
+ onapModelInformation.setModelName("my-model-name");
+ onapModelInformation.setModelVersion("my-model-version");
+ onapModelInformation.setModelUuid("my-model-uuid");
+ onapModelInformation.setModelCustomizationUuid("my-customization-uuid");
+ networkInformation.setOnapModelInformation(onapModelInformation);
+
+ assertThat(networkInformation, sameBeanAs(genObjMapper.buildNetworkInformation(network)));
+
+ }
+
+ @Test
+ public void buildNetworkInformationNoModelTest() {
+
+ L3Network network = new L3Network();
+ network.setNetworkId("my-network-id");
+ network.setNetworkType("my-network-type");
+ network.setNetworkTechnology("my-network-technology");
+
+ GenericResourceApiNetworkinformationNetworkInformation networkInformation =
+ new GenericResourceApiNetworkinformationNetworkInformation();
+ networkInformation.setNetworkId("my-network-id");
+ networkInformation.setNetworkType("my-network-type");
+ networkInformation.networkTechnology("my-network-technology");
+ networkInformation.setFromPreload(null);
+
+
+ assertThat(networkInformation, sameBeanAs(genObjMapper.buildNetworkInformation(network)));
+
+ }
+
+
+ @Test
+ public void buildVfModuleInformationTest_withNoModelIsFromPreload() {
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("TestVfModuleId");
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId("TestVnfId");
+ RequestContext requestContext = new RequestContext();
+ RequestParameters requestParameters = new RequestParameters();
+ requestParameters.setUsePreload(true);
+ requestContext.setRequestParameters(requestParameters);
+ GenericResourceApiVfmoduleinformationVfModuleInformation gcRequestInput = null;
+ try {
+ gcRequestInput =
+ genObjMapper.buildVfModuleInformation(vfModule, genericVnf, serviceInstance, requestContext, false);
+ } catch (MapperException ex) {
+
+ }
+ assertNotNull(gcRequestInput);
+ assertNull(vfModule.getModelInfoVfModule());
+ assertNull(gcRequestInput.getOnapModelInformation());
+ assertEquals(vfModule.getVfModuleId(), gcRequestInput.getVfModuleId());
+ assertNotNull(gcRequestInput.getVfModuleId());
+ assertTrue(gcRequestInput.getFromPreload());
+ }
+
+ @Test
+ public void buildVfModuleInformationTest_withNoModelIsNotFromPreload() {
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("TestVfModuleId");
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId("TestVnfId");
+ RequestContext requestContext = new RequestContext();
+ RequestParameters requestParameters = new RequestParameters();
+ requestParameters.setUsePreload(false);
+ requestContext.setRequestParameters(requestParameters);
+ GenericResourceApiVfmoduleinformationVfModuleInformation gcRequestInput = null;
+ try {
+ gcRequestInput =
+ genObjMapper.buildVfModuleInformation(vfModule, genericVnf, serviceInstance, requestContext, false);
+ } catch (MapperException ex) {
+
+ }
+ assertNotNull(gcRequestInput);
+ assertNull(vfModule.getModelInfoVfModule());
+ assertNull(gcRequestInput.getOnapModelInformation());
+ assertEquals(vfModule.getVfModuleId(), gcRequestInput.getVfModuleId());
+ assertNotNull(gcRequestInput.getVfModuleId());
+ assertFalse(gcRequestInput.getFromPreload());
+ }
+
+ @Test
+ public void buildVfModuleInformationTest_withNoModelNoRequestContext() {
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("TestVfModuleId");
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId("TestVnfId");
+ GenericResourceApiVfmoduleinformationVfModuleInformation gcRequestInput = null;
+ try {
+ gcRequestInput = genObjMapper.buildVfModuleInformation(vfModule, genericVnf, serviceInstance, null, false);
+ } catch (MapperException ex) {
+
+ }
+ assertNotNull(gcRequestInput);
+ assertNull(vfModule.getModelInfoVfModule());
+ assertNull(gcRequestInput.getOnapModelInformation());
+ assertEquals(vfModule.getVfModuleId(), gcRequestInput.getVfModuleId());
+ assertNotNull(gcRequestInput.getVfModuleId());
+ assertTrue(gcRequestInput.getFromPreload());
+ }
+
+ @Test
+ public void buildVfModuleInformationTest_withNoModelNoRequestParameters() {
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("TestVfModuleId");
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId("TestVnfId");
+ RequestContext requestContext = new RequestContext();
+ GenericResourceApiVfmoduleinformationVfModuleInformation gcRequestInput = null;
+ try {
+ gcRequestInput =
+ genObjMapper.buildVfModuleInformation(vfModule, genericVnf, serviceInstance, requestContext, false);
+ } catch (MapperException ex) {
+
+ }
+ assertNotNull(gcRequestInput);
+ assertNull(vfModule.getModelInfoVfModule());
+ assertNull(gcRequestInput.getOnapModelInformation());
+ assertEquals(vfModule.getVfModuleId(), gcRequestInput.getVfModuleId());
+ assertNotNull(gcRequestInput.getVfModuleId());
+ assertTrue(gcRequestInput.getFromPreload());
+ }
+
+ @Test
+ public void buildVfModuleInformationTest_withModel() {
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("TestVfModuleId");
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("testModelInvariantUUID");
+ modelInfoVfModule.setModelName("testModelName");
+ modelInfoVfModule.setModelVersion("testModelVersion");
+ modelInfoVfModule.setModelUUID("testModelUUID");
+ modelInfoVfModule.setModelCustomizationUUID("testModelCustomizationUUID");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setVnfId("TestVnfId");
+ RequestContext requestContext = new RequestContext();
+ RequestParameters requestParameters = new RequestParameters();
+ requestParameters.setUsePreload(true);
+ requestContext.setRequestParameters(requestParameters);
+ GenericResourceApiVfmoduleinformationVfModuleInformation gcRequestInput = null;
+ try {
+ gcRequestInput =
+ genObjMapper.buildVfModuleInformation(vfModule, genericVnf, serviceInstance, requestContext, true);
+ } catch (MapperException ex) {
+
+ }
+ assertNotNull(gcRequestInput);
+ assertNotNull(vfModule.getModelInfoVfModule());
+ assertNotNull(gcRequestInput.getOnapModelInformation());
+ assertEquals(modelInfoVfModule.getModelInvariantUUID(),
+ gcRequestInput.getOnapModelInformation().getModelInvariantUuid());
+ assertEquals(modelInfoVfModule.getModelName(), gcRequestInput.getOnapModelInformation().getModelName());
+ assertEquals(modelInfoVfModule.getModelVersion(), gcRequestInput.getOnapModelInformation().getModelVersion());
+ assertEquals(modelInfoVfModule.getModelUUID(), gcRequestInput.getOnapModelInformation().getModelUuid());
+ assertEquals(modelInfoVfModule.getModelCustomizationUUID(),
+ gcRequestInput.getOnapModelInformation().getModelCustomizationUuid());
+ assertEquals(vfModule.getVfModuleId(), gcRequestInput.getVfModuleId());
+ assertNotNull(gcRequestInput.getVfModuleId());
+ assertTrue(gcRequestInput.getFromPreload());
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapperTest.java
index 1bfa78ad6d..76e915781f 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapperTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapperTest.java
@@ -25,13 +25,11 @@ import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -52,174 +50,183 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoNetwork;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance;
import org.onap.so.client.sdnc.beans.SDNCSvcAction;
import org.onap.so.client.sdnc.beans.SDNCSvcOperation;
-
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(MockitoJUnitRunner.class)
public class NetworkTopologyOperationRequestMapperTest {
- private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
-
- private ServiceInstance serviceInstance;
- private ServiceInstance serviceInstanceNoCollection;
- private Customer customer;
- private RequestContext requestContext;
- private L3Network network;
- private CloudRegion cloudRegion;
-
- @Spy
- private GeneralTopologyObjectMapper generalTopologyObjectMapper;
-
- @InjectMocks
- private NetworkTopologyOperationRequestMapper mapper = new NetworkTopologyOperationRequestMapper();
-
- @Before
- public void before() {
- // prepare and set service instance
- serviceInstance = new ServiceInstance();
- serviceInstanceNoCollection = new ServiceInstance();
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("modelInvariantUuid");
- modelInfoServiceInstance.setModelName("modelName");
- modelInfoServiceInstance.setModelUuid("modelUuid");
- modelInfoServiceInstance.setModelVersion("modelVersion");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
- serviceInstanceNoCollection.setModelInfoServiceInstance(modelInfoServiceInstance);
- // prepare Customer object
- customer = new Customer();
- customer.setGlobalCustomerId("globalCustomerId");
- //serviceInstance.setCustomer(customer);
- // set Customer on service instance
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- serviceSubscription.setServiceType("productFamilyId");
- customer.setServiceSubscription(serviceSubscription);
-
- // set Customer on service instance
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- customer.getServiceSubscription().getServiceInstances().add(serviceInstanceNoCollection);
- //
- InstanceGroup networkInstanceGroup = new InstanceGroup();
- networkInstanceGroup.setId("networkInstanceGroupId");
- networkInstanceGroup.setInstanceGroupFunction("instanceGroupFunction");
- Collection networkCollection = new Collection();
- networkCollection.setInstanceGroup(networkInstanceGroup);
- serviceInstance.setCollection(networkCollection);
- //
- requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value1");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
- requestContext.setMsoRequestId("MsoRequestId");
-
- network = new L3Network();
- network.setNetworkId("TEST_NETWORK_ID");
- network.setNetworkName("TEST_NETWORK_NAME");
- ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
- modelInfoNetwork.setModelInvariantUUID("modelInvariantUuid");
- modelInfoNetwork.setModelName("modelName");
- modelInfoNetwork.setModelVersion("modelVersion");
- modelInfoNetwork.setModelUUID("modelUuid");
- modelInfoNetwork.setModelCustomizationUUID("modelCustomizationUUID");
- network.setModelInfoNetwork(modelInfoNetwork);
-
- cloudRegion = new CloudRegion();
- }
-
- @Test
- public void createGenericResourceApiNetworkOperationInformationTest() throws Exception {
-
- GenericResourceApiNetworkOperationInformation networkSDNCrequest = mapper.reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
-
- ObjectMapper omapper = new ObjectMapper();
- GenericResourceApiNetworkOperationInformation reqMapper1 = omapper.readValue(
- getJson("genericResourceApiNetworkOperationInformation.json"),
- GenericResourceApiNetworkOperationInformation.class);
-
- assertThat(networkSDNCrequest, sameBeanAs(reqMapper1).ignoring("sdncRequestHeader.svcRequestId")
- .ignoring("requestInformation.requestId"));
- assertEquals("MsoRequestId", networkSDNCrequest.getRequestInformation().getRequestId());
- }
-
- @Test
- public void createGenericResourceApiNetworkOperationInformationReqContextNullTest() throws Exception {
-
- RequestContext rc = new RequestContext();
- rc.setMsoRequestId(null);
- GenericResourceApiNetworkOperationInformation networkSDNCrequest = mapper.reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
- rc, cloudRegion);
- assertNotNull(networkSDNCrequest.getRequestInformation().getRequestId());
- GenericResourceApiNetworkOperationInformation networkSDNCrequest2 = mapper.reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
- null, cloudRegion);
- assertNotNull(networkSDNCrequest2.getRequestInformation().getRequestId());
- }
-
- @Test
- public void reqMapperTest() throws Exception {
-
- GenericResourceApiNetworkOperationInformation networkSDNCrequest = mapper.reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
-
- assertNull(networkSDNCrequest.getServiceInformation().getOnapModelInformation().getModelCustomizationUuid());
- assertEquals("modelCustomizationUUID", networkSDNCrequest.getNetworkInformation().getOnapModelInformation().getModelCustomizationUuid());
- }
-
- @Test
- public void reqMapperNoCollectionTest() throws Exception {
- GenericResourceApiNetworkOperationInformation networkSDNCrequest = mapper.reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstanceNoCollection, customer,
- requestContext, cloudRegion);
-
- assertNull(networkSDNCrequest.getServiceInformation().getOnapModelInformation().getModelCustomizationUuid());
- assertEquals("modelCustomizationUUID", networkSDNCrequest.getNetworkInformation().getOnapModelInformation().getModelCustomizationUuid());
- }
- @Test
- public void createGenericResourceApiNetworkOperationInformation_UnassignTest() throws Exception {
-
- NetworkTopologyOperationRequestMapper mapperUnassign = mapper;
- GenericResourceApiNetworkOperationInformation networkSDNCrequestUnassign = mapperUnassign.reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
-
- ObjectMapper omapperUnassign = new ObjectMapper();
- GenericResourceApiNetworkOperationInformation reqMapperUnassign = omapperUnassign.readValue(
- getJson("genericResourceApiNetworkOperationInformationUnAssign.json"),
- GenericResourceApiNetworkOperationInformation.class);
-
- assertThat(reqMapperUnassign, sameBeanAs(networkSDNCrequestUnassign).ignoring("sdncRequestHeader.svcRequestId")
- .ignoring("requestInformation.requestId"));
- assertEquals("MsoRequestId", networkSDNCrequestUnassign.getRequestInformation().getRequestId());
-
- }
-
- @Test
- public void createGenericResourceApiNetworkOperationInformationNoNetworkNameTest() throws Exception {
-
- //set network name NULL
- network.setNetworkName(null);
- GenericResourceApiNetworkOperationInformation networkSDNCrequest = mapper.reqMapper(
- SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer,
- requestContext, cloudRegion);
-
- ObjectMapper omapper = new ObjectMapper();
- GenericResourceApiNetworkOperationInformation reqMapper1 = omapper.readValue(
- getJson("genericResourceApiNetworkOperationInformationNoNetworkName.json"),
- GenericResourceApiNetworkOperationInformation.class);
-
- assertThat(reqMapper1, sameBeanAs(networkSDNCrequest).ignoring("sdncRequestHeader.svcRequestId")
- .ignoring("requestInformation.requestId"));
- }
-
- /*
- * Helper method to load JSON data
- */
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + filename)));
- }
+ private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
+
+ private ServiceInstance serviceInstance;
+ private ServiceInstance serviceInstanceNoCollection;
+ private Customer customer;
+ private RequestContext requestContext;
+ private L3Network network;
+ private CloudRegion cloudRegion;
+
+ @Spy
+ private GeneralTopologyObjectMapper generalTopologyObjectMapper;
+
+ @InjectMocks
+ private NetworkTopologyOperationRequestMapper mapper = new NetworkTopologyOperationRequestMapper();
+
+ @Before
+ public void before() {
+ // prepare and set service instance
+ serviceInstance = new ServiceInstance();
+ serviceInstanceNoCollection = new ServiceInstance();
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("modelInvariantUuid");
+ modelInfoServiceInstance.setModelName("modelName");
+ modelInfoServiceInstance.setModelUuid("modelUuid");
+ modelInfoServiceInstance.setModelVersion("modelVersion");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+ serviceInstanceNoCollection.setModelInfoServiceInstance(modelInfoServiceInstance);
+ // prepare Customer object
+ customer = new Customer();
+ customer.setGlobalCustomerId("globalCustomerId");
+ // serviceInstance.setCustomer(customer);
+ // set Customer on service instance
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ serviceSubscription.setServiceType("productFamilyId");
+ customer.setServiceSubscription(serviceSubscription);
+
+ // set Customer on service instance
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstanceNoCollection);
+ //
+ InstanceGroup networkInstanceGroup = new InstanceGroup();
+ networkInstanceGroup.setId("networkInstanceGroupId");
+ networkInstanceGroup.setInstanceGroupFunction("instanceGroupFunction");
+ Collection networkCollection = new Collection();
+ networkCollection.setInstanceGroup(networkInstanceGroup);
+ serviceInstance.setCollection(networkCollection);
+ //
+ requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value1");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+ requestContext.setMsoRequestId("MsoRequestId");
+
+ network = new L3Network();
+ network.setNetworkId("TEST_NETWORK_ID");
+ network.setNetworkName("TEST_NETWORK_NAME");
+ ModelInfoNetwork modelInfoNetwork = new ModelInfoNetwork();
+ modelInfoNetwork.setModelInvariantUUID("modelInvariantUuid");
+ modelInfoNetwork.setModelName("modelName");
+ modelInfoNetwork.setModelVersion("modelVersion");
+ modelInfoNetwork.setModelUUID("modelUuid");
+ modelInfoNetwork.setModelCustomizationUUID("modelCustomizationUUID");
+ network.setModelInfoNetwork(modelInfoNetwork);
+
+ cloudRegion = new CloudRegion();
+ }
+
+ @Test
+ public void createGenericResourceApiNetworkOperationInformationTest() throws Exception {
+
+ GenericResourceApiNetworkOperationInformation networkSDNCrequest =
+ mapper.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance,
+ customer, requestContext, cloudRegion);
+
+ ObjectMapper omapper = new ObjectMapper();
+ GenericResourceApiNetworkOperationInformation reqMapper1 =
+ omapper.readValue(getJson("genericResourceApiNetworkOperationInformation.json"),
+ GenericResourceApiNetworkOperationInformation.class);
+
+ assertThat(networkSDNCrequest, sameBeanAs(reqMapper1).ignoring("sdncRequestHeader.svcRequestId")
+ .ignoring("requestInformation.requestId"));
+ assertEquals("MsoRequestId", networkSDNCrequest.getRequestInformation().getRequestId());
+ }
+
+ @Test
+ public void createGenericResourceApiNetworkOperationInformationReqContextNullTest() throws Exception {
+
+ RequestContext rc = new RequestContext();
+ rc.setMsoRequestId(null);
+ GenericResourceApiNetworkOperationInformation networkSDNCrequest =
+ mapper.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance,
+ customer, rc, cloudRegion);
+ assertNotNull(networkSDNCrequest.getRequestInformation().getRequestId());
+ GenericResourceApiNetworkOperationInformation networkSDNCrequest2 =
+ mapper.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance,
+ customer, null, cloudRegion);
+ assertNotNull(networkSDNCrequest2.getRequestInformation().getRequestId());
+ }
+
+ @Test
+ public void reqMapperTest() throws Exception {
+
+ GenericResourceApiNetworkOperationInformation networkSDNCrequest =
+ mapper.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance,
+ customer, requestContext, cloudRegion);
+
+ assertNull(networkSDNCrequest.getServiceInformation().getOnapModelInformation().getModelCustomizationUuid());
+ assertEquals("modelCustomizationUUID",
+ networkSDNCrequest.getNetworkInformation().getOnapModelInformation().getModelCustomizationUuid());
+ }
+
+ @Test
+ public void reqMapperNoCollectionTest() throws Exception {
+ GenericResourceApiNetworkOperationInformation networkSDNCrequest =
+ mapper.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network,
+ serviceInstanceNoCollection, customer, requestContext, cloudRegion);
+
+ assertNull(networkSDNCrequest.getServiceInformation().getOnapModelInformation().getModelCustomizationUuid());
+ assertEquals("modelCustomizationUUID",
+ networkSDNCrequest.getNetworkInformation().getOnapModelInformation().getModelCustomizationUuid());
+ }
+
+ @Test
+ public void createGenericResourceApiNetworkOperationInformation_UnassignTest() throws Exception {
+
+ NetworkTopologyOperationRequestMapper mapperUnassign = mapper;
+ GenericResourceApiNetworkOperationInformation networkSDNCrequestUnassign =
+ mapperUnassign.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN,
+ GenericResourceApiRequestActionEnumeration.DELETENETWORKINSTANCE, network, serviceInstance,
+ customer, requestContext, cloudRegion);
+
+ ObjectMapper omapperUnassign = new ObjectMapper();
+ GenericResourceApiNetworkOperationInformation reqMapperUnassign =
+ omapperUnassign.readValue(getJson("genericResourceApiNetworkOperationInformationUnAssign.json"),
+ GenericResourceApiNetworkOperationInformation.class);
+
+ assertThat(reqMapperUnassign, sameBeanAs(networkSDNCrequestUnassign).ignoring("sdncRequestHeader.svcRequestId")
+ .ignoring("requestInformation.requestId"));
+ assertEquals("MsoRequestId", networkSDNCrequestUnassign.getRequestInformation().getRequestId());
+
+ }
+
+ @Test
+ public void createGenericResourceApiNetworkOperationInformationNoNetworkNameTest() throws Exception {
+
+ // set network name NULL
+ network.setNetworkName(null);
+ GenericResourceApiNetworkOperationInformation networkSDNCrequest =
+ mapper.reqMapper(SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance,
+ customer, requestContext, cloudRegion);
+
+ ObjectMapper omapper = new ObjectMapper();
+ GenericResourceApiNetworkOperationInformation reqMapper1 =
+ omapper.readValue(getJson("genericResourceApiNetworkOperationInformationNoNetworkName.json"),
+ GenericResourceApiNetworkOperationInformation.class);
+
+ assertThat(reqMapper1, sameBeanAs(networkSDNCrequest).ignoring("sdncRequestHeader.svcRequestId")
+ .ignoring("requestInformation.requestId"));
+ }
+
+ /*
+ * Helper method to load JSON data
+ */
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + filename)));
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapperTest.java
index 1919ef437b..f4006ab5d5 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapperTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapperTest.java
@@ -24,12 +24,10 @@ import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
@@ -42,7 +40,6 @@ import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance;
import org.onap.so.client.sdnc.beans.SDNCSvcAction;
import org.onap.so.client.sdnc.beans.SDNCSvcOperation;
-
import org.onap.sdnc.northbound.client.model.GenericResourceApiOnapmodelinformationOnapModelInformation;
import org.onap.sdnc.northbound.client.model.GenericResourceApiRequestActionEnumeration;
import org.onap.sdnc.northbound.client.model.GenericResourceApiServiceOperationInformation;
@@ -51,54 +48,56 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(MockitoJUnitRunner.class)
public class ServiceTopologyOperationMapperTest {
- @Spy
- private GeneralTopologyObjectMapper generalTopologyObjectMapper;
-
- @InjectMocks
- private ServiceTopologyOperationMapper mapper = new ServiceTopologyOperationMapper();
+ @Spy
+ private GeneralTopologyObjectMapper generalTopologyObjectMapper;
+
+ @InjectMocks
+ private ServiceTopologyOperationMapper mapper = new ServiceTopologyOperationMapper();
- @Test
- public void reqMapperTest() throws Exception {
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("modelInvariantUuid");
- modelInfoServiceInstance.setModelName("modelName");
- modelInfoServiceInstance.setModelUuid("modelUuid");
- modelInfoServiceInstance.setModelVersion("modelVersion");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+ @Test
+ public void reqMapperTest() throws Exception {
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("modelInvariantUuid");
+ modelInfoServiceInstance.setModelName("modelName");
+ modelInfoServiceInstance.setModelUuid("modelUuid");
+ modelInfoServiceInstance.setModelVersion("modelVersion");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
- // prepare Customer object
- Customer customer = new Customer();
- customer.setGlobalCustomerId("globalCustomerId");
+ // prepare Customer object
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("globalCustomerId");
- customer.setServiceSubscription(new ServiceSubscription());
- // set Customer on service instance
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ customer.setServiceSubscription(new ServiceSubscription());
+ // set Customer on service instance
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- //prepare RequestContext
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value1");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
- requestContext.setMsoRequestId("MsoRequestId");
+ // prepare RequestContext
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value1");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+ requestContext.setMsoRequestId("MsoRequestId");
- GenericResourceApiServiceOperationInformation serviceOpInformation = mapper.reqMapper(
- SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE, serviceInstance, customer,
- requestContext);
- GenericResourceApiServiceOperationInformation serviceOpInformationNullReqContext = mapper.reqMapper(
- SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE, serviceInstance, customer,
- null);
+ GenericResourceApiServiceOperationInformation serviceOpInformation =
+ mapper.reqMapper(SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE, serviceInstance, customer,
+ requestContext);
+ GenericResourceApiServiceOperationInformation serviceOpInformationNullReqContext = mapper.reqMapper(
+ SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE, serviceInstance, customer, null);
- String jsonToCompare = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/BuildingBlocks/genericResourceApiEcompModelInformation.json")));
+ String jsonToCompare = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/__files/BuildingBlocks/genericResourceApiEcompModelInformation.json")));
- ObjectMapper omapper = new ObjectMapper();
- GenericResourceApiOnapmodelinformationOnapModelInformation reqMapper1 = omapper.readValue(jsonToCompare,
- GenericResourceApiOnapmodelinformationOnapModelInformation.class);
+ ObjectMapper omapper = new ObjectMapper();
+ GenericResourceApiOnapmodelinformationOnapModelInformation reqMapper1 =
+ omapper.readValue(jsonToCompare, GenericResourceApiOnapmodelinformationOnapModelInformation.class);
- assertThat(reqMapper1, sameBeanAs(serviceOpInformation.getServiceInformation().getOnapModelInformation()));
- assertEquals("MsoRequestId", serviceOpInformation.getRequestInformation().getRequestId());
- assertNotNull(serviceOpInformationNullReqContext.getRequestInformation().getRequestId());
- }
+ assertThat(reqMapper1, sameBeanAs(serviceOpInformation.getServiceInformation().getOnapModelInformation()));
+ assertEquals("MsoRequestId", serviceOpInformation.getRequestInformation().getRequestId());
+ assertNotNull(serviceOpInformationNullReqContext.getRequestInformation().getRequestId());
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java
index 7fce8c48c8..275e9f7dbb 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java
@@ -25,14 +25,12 @@ import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -55,283 +53,284 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule;
import org.onap.so.client.exception.MapperException;
import org.onap.so.client.sdnc.beans.SDNCSvcAction;
import org.onap.so.client.sdnc.beans.SDNCSvcOperation;
-
import org.onap.sdnc.northbound.client.model.GenericResourceApiVfModuleOperationInformation;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(MockitoJUnitRunner.class)
public class VfModuleTopologyOperationRequestMapperTest {
- private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
- private final static String ERRORMESSAGE = "VF Module model info is null for testVfModuleId";
-
- @Spy
- private GeneralTopologyObjectMapper generalTopologyObjectMapper;
-
- @InjectMocks
- private VfModuleTopologyOperationRequestMapper mapper = new VfModuleTopologyOperationRequestMapper();
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Test
- public void assignGenericResourceApiVfModuleInformationTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
- // prepare Customer object
- Customer customer = new Customer();
- customer.setGlobalCustomerId("globalCustomerId");
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- serviceSubscription.setServiceType("productFamilyId");
- customer.setServiceSubscription(serviceSubscription);
-
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- //
- RequestContext requestContext = new RequestContext();
- Map<String,Object> userParams = new HashMap<>();
- userParams.put("key1", "value1");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
- RequestParameters requestParameters = new RequestParameters();
- requestParameters.setUsePreload(true);
- requestContext.setRequestParameters(requestParameters);
- requestContext.setMsoRequestId("MsoRequestId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("testVnfId");
- vnf.setVnfType("testVnfType");
- vnf.setVnfName("testVnfName");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("testVfModuleId");
- vfModule.setVfModuleName("testVfModuleName");
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
- HashMap<String, String> cloudParams = new HashMap<String, String>();
- cloudParams.put("key2", "value2");
- vfModule.setCloudParams(cloudParams);
-
- VolumeGroup volumeGroup = new VolumeGroup();
- volumeGroup.setVolumeGroupId("volumeGroupId");
- volumeGroup.setVolumeGroupName("volumeGroupName");
-
- CloudRegion cloudRegion = new CloudRegion();
-
- GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest = mapper.reqMapper(
- SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, volumeGroup, vnf, serviceInstance, customer,
- cloudRegion, requestContext, null);
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleOperationInformationAssign.json")));
-
- ObjectMapper omapper = new ObjectMapper();
- GenericResourceApiVfModuleOperationInformation reqMapper1 = omapper.readValue(
- jsonToCompare,
- GenericResourceApiVfModuleOperationInformation.class);
-
- assertThat(reqMapper1, sameBeanAs(vfModuleSDNCrequest).ignoring("sdncRequestHeader.svcRequestId")
- .ignoring("requestInformation.requestId"));
- assertEquals("MsoRequestId", vfModuleSDNCrequest.getRequestInformation().getRequestId());
- }
-
- @Test
- public void unassignGenericResourceApiVfModuleInformationTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
-
- // prepare and set vnf instance
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("testVnfId");
- vnf.setVnfType("testVnfType");
-
- // prepare and set vf module instance
-
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("testVfModuleId");
- vfModule.setVfModuleName("testVfModuleName");
-
- RequestContext requestContext = new RequestContext();
- requestContext.setMsoRequestId("MsoRequestId");
-
- GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest = mapper.reqMapper(
- SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null, vnf, serviceInstance, null,
- null, requestContext, null);
-
- String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleOperationInformationUnassign.json")));
-
- ObjectMapper omapper = new ObjectMapper();
- GenericResourceApiVfModuleOperationInformation reqMapper1 = omapper.readValue(
- jsonToCompare,
- GenericResourceApiVfModuleOperationInformation.class);
-
- assertThat(reqMapper1, sameBeanAs(vfModuleSDNCrequest).ignoring("sdncRequestHeader.svcRequestId")
- .ignoring("requestInformation.requestId"));
- assertEquals("MsoRequestId", vfModuleSDNCrequest.getRequestInformation().getRequestId());
- }
-
- @Test
- public void unassignGenericResourceApiVfModuleInformationNullMsoReqIdTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
-
- // prepare and set vnf instance
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("testVnfId");
- vnf.setVnfType("testVnfType");
-
- // prepare and set vf module instance
-
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("testVfModuleId");
- vfModule.setVfModuleName("testVfModuleName");
-
- RequestContext requestContext = new RequestContext();
-
- GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest = mapper.reqMapper(
- SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null, vnf, serviceInstance, null,
- null, requestContext, null);
-
- assertNotNull(vfModuleSDNCrequest.getRequestInformation().getRequestId());
- }
-
- @Test
- public void reqMapperTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
-
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
- // prepare Customer object
- Customer customer = new Customer();
- customer.setGlobalCustomerId("globalCustomerId");
- customer.setServiceSubscription(new ServiceSubscription());
- // set Customer on service instance
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- //
- RequestContext requestContext = new RequestContext();
- RequestParameters requestParameters = new RequestParameters();
- HashMap<String,Object> userParams1 = new HashMap<>();
- userParams1.put("key1", "value1");
- List<Map<String,Object>> userParams = new ArrayList<>();
- userParams.add(userParams1);
-
- requestParameters.setUserParams(userParams);
- requestContext.setRequestParameters(requestParameters);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("testVnfId");
- vnf.setVnfType("testVnfType");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("testVfModuleId");
- vfModule.setVfModuleName("testVfModuleName");
- ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
- modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
- modelInfoVfModule.setModelName("vfModuleModelName");
- modelInfoVfModule.setModelVersion("vfModuleModelVersion");
- modelInfoVfModule.setModelUUID("vfModuleModelUuid");
- modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
- vfModule.setModelInfoVfModule(modelInfoVfModule);
-
- CloudRegion cloudRegion = new CloudRegion();
-
- GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest = mapper.reqMapper(
- SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, null, vnf, serviceInstance, customer,
- cloudRegion, requestContext, null);
-
- assertNull(vfModuleSDNCrequest.getServiceInformation().getOnapModelInformation().getModelCustomizationUuid());
- assertEquals("vnfModelCustomizationUuid", vfModuleSDNCrequest.getVnfInformation().getOnapModelInformation().getModelCustomizationUuid());
- assertEquals("vfModuleModelCustomizationUuid", vfModuleSDNCrequest.getVfModuleInformation().getOnapModelInformation().getModelCustomizationUuid());
- }
-
- @Test
- public void reqMapperNoModelInfoTest() throws Exception {
-
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- serviceInstance.setServiceInstanceId("serviceInstanceId");
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
- modelInfoServiceInstance.setModelName("serviceModelName");
- modelInfoServiceInstance.setModelUuid("serviceModelUuid");
- modelInfoServiceInstance.setModelVersion("serviceModelVersion");
-
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
- // prepare Customer object
- Customer customer = new Customer();
- customer.setGlobalCustomerId("globalCustomerId");
- customer.setServiceSubscription(new ServiceSubscription());
- // set Customer on service instance
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
- //
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<String, Object>();
- userParams.put("key1", "value1");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
-
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("testVnfId");
- vnf.setVnfType("testVnfType");
- ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
- modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
- modelInfoGenericVnf.setModelName("vnfModelName");
- modelInfoGenericVnf.setModelVersion("vnfModelVersion");
- modelInfoGenericVnf.setModelUuid("vnfModelUuid");
- modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
- vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
-
- VfModule vfModule = new VfModule();
- vfModule.setVfModuleId("testVfModuleId");
- vfModule.setVfModuleName("testVfModuleName");
- vfModule.setModelInfoVfModule(null);
-
- CloudRegion cloudRegion = new CloudRegion();
-
- expectedException.expect(MapperException.class);
- expectedException.expectMessage(ERRORMESSAGE);
-
- mapper.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, null, vnf, serviceInstance, customer,
- cloudRegion, requestContext, null);
- }
+ private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
+ private final static String ERRORMESSAGE = "VF Module model info is null for testVfModuleId";
+
+ @Spy
+ private GeneralTopologyObjectMapper generalTopologyObjectMapper;
+
+ @InjectMocks
+ private VfModuleTopologyOperationRequestMapper mapper = new VfModuleTopologyOperationRequestMapper();
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Test
+ public void assignGenericResourceApiVfModuleInformationTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+ // prepare Customer object
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("globalCustomerId");
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ serviceSubscription.setServiceType("productFamilyId");
+ customer.setServiceSubscription(serviceSubscription);
+
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ //
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value1");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+ RequestParameters requestParameters = new RequestParameters();
+ requestParameters.setUsePreload(true);
+ requestContext.setRequestParameters(requestParameters);
+ requestContext.setMsoRequestId("MsoRequestId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("testVnfId");
+ vnf.setVnfType("testVnfType");
+ vnf.setVnfName("testVnfName");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("testVfModuleId");
+ vfModule.setVfModuleName("testVfModuleName");
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+ HashMap<String, String> cloudParams = new HashMap<String, String>();
+ cloudParams.put("key2", "value2");
+ vfModule.setCloudParams(cloudParams);
+
+ VolumeGroup volumeGroup = new VolumeGroup();
+ volumeGroup.setVolumeGroupId("volumeGroupId");
+ volumeGroup.setVolumeGroupName("volumeGroupName");
+
+ CloudRegion cloudRegion = new CloudRegion();
+
+ GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest =
+ mapper.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule,
+ volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext, null);
+
+ String jsonToCompare = new String(Files.readAllBytes(
+ Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleOperationInformationAssign.json")));
+
+ ObjectMapper omapper = new ObjectMapper();
+ GenericResourceApiVfModuleOperationInformation reqMapper1 =
+ omapper.readValue(jsonToCompare, GenericResourceApiVfModuleOperationInformation.class);
+
+ assertThat(reqMapper1, sameBeanAs(vfModuleSDNCrequest).ignoring("sdncRequestHeader.svcRequestId")
+ .ignoring("requestInformation.requestId"));
+ assertEquals("MsoRequestId", vfModuleSDNCrequest.getRequestInformation().getRequestId());
+ }
+
+ @Test
+ public void unassignGenericResourceApiVfModuleInformationTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+
+ // prepare and set vnf instance
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("testVnfId");
+ vnf.setVnfType("testVnfType");
+
+ // prepare and set vf module instance
+
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("testVfModuleId");
+ vfModule.setVfModuleName("testVfModuleName");
+
+ RequestContext requestContext = new RequestContext();
+ requestContext.setMsoRequestId("MsoRequestId");
+
+ GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest =
+ mapper.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null,
+ vnf, serviceInstance, null, null, requestContext, null);
+
+ String jsonToCompare = new String(Files.readAllBytes(
+ Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleOperationInformationUnassign.json")));
+
+ ObjectMapper omapper = new ObjectMapper();
+ GenericResourceApiVfModuleOperationInformation reqMapper1 =
+ omapper.readValue(jsonToCompare, GenericResourceApiVfModuleOperationInformation.class);
+
+ assertThat(reqMapper1, sameBeanAs(vfModuleSDNCrequest).ignoring("sdncRequestHeader.svcRequestId")
+ .ignoring("requestInformation.requestId"));
+ assertEquals("MsoRequestId", vfModuleSDNCrequest.getRequestInformation().getRequestId());
+ }
+
+ @Test
+ public void unassignGenericResourceApiVfModuleInformationNullMsoReqIdTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+
+ // prepare and set vnf instance
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("testVnfId");
+ vnf.setVnfType("testVnfType");
+
+ // prepare and set vf module instance
+
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("testVfModuleId");
+ vfModule.setVfModuleName("testVfModuleName");
+
+ RequestContext requestContext = new RequestContext();
+
+ GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest =
+ mapper.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null,
+ vnf, serviceInstance, null, null, requestContext, null);
+
+ assertNotNull(vfModuleSDNCrequest.getRequestInformation().getRequestId());
+ }
+
+ @Test
+ public void reqMapperTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+ // prepare Customer object
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("globalCustomerId");
+ customer.setServiceSubscription(new ServiceSubscription());
+ // set Customer on service instance
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ //
+ RequestContext requestContext = new RequestContext();
+ RequestParameters requestParameters = new RequestParameters();
+ HashMap<String, Object> userParams1 = new HashMap<>();
+ userParams1.put("key1", "value1");
+ List<Map<String, Object>> userParams = new ArrayList<>();
+ userParams.add(userParams1);
+
+ requestParameters.setUserParams(userParams);
+ requestContext.setRequestParameters(requestParameters);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("testVnfId");
+ vnf.setVnfType("testVnfType");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("testVfModuleId");
+ vfModule.setVfModuleName("testVfModuleName");
+ ModelInfoVfModule modelInfoVfModule = new ModelInfoVfModule();
+ modelInfoVfModule.setModelInvariantUUID("vfModuleModelInvariantUuid");
+ modelInfoVfModule.setModelName("vfModuleModelName");
+ modelInfoVfModule.setModelVersion("vfModuleModelVersion");
+ modelInfoVfModule.setModelUUID("vfModuleModelUuid");
+ modelInfoVfModule.setModelCustomizationUUID("vfModuleModelCustomizationUuid");
+ vfModule.setModelInfoVfModule(modelInfoVfModule);
+
+ CloudRegion cloudRegion = new CloudRegion();
+
+ GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest =
+ mapper.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, null,
+ vnf, serviceInstance, customer, cloudRegion, requestContext, null);
+
+ assertNull(vfModuleSDNCrequest.getServiceInformation().getOnapModelInformation().getModelCustomizationUuid());
+ assertEquals("vnfModelCustomizationUuid",
+ vfModuleSDNCrequest.getVnfInformation().getOnapModelInformation().getModelCustomizationUuid());
+ assertEquals("vfModuleModelCustomizationUuid",
+ vfModuleSDNCrequest.getVfModuleInformation().getOnapModelInformation().getModelCustomizationUuid());
+ }
+
+ @Test
+ public void reqMapperNoModelInfoTest() throws Exception {
+
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setServiceInstanceId("serviceInstanceId");
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("serviceModelInvariantUuid");
+ modelInfoServiceInstance.setModelName("serviceModelName");
+ modelInfoServiceInstance.setModelUuid("serviceModelUuid");
+ modelInfoServiceInstance.setModelVersion("serviceModelVersion");
+
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+ // prepare Customer object
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("globalCustomerId");
+ customer.setServiceSubscription(new ServiceSubscription());
+ // set Customer on service instance
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+ //
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<String, Object>();
+ userParams.put("key1", "value1");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("testVnfId");
+ vnf.setVnfType("testVnfType");
+ ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf();
+ modelInfoGenericVnf.setModelInvariantUuid("vnfModelInvariantUuid");
+ modelInfoGenericVnf.setModelName("vnfModelName");
+ modelInfoGenericVnf.setModelVersion("vnfModelVersion");
+ modelInfoGenericVnf.setModelUuid("vnfModelUuid");
+ modelInfoGenericVnf.setModelCustomizationUuid("vnfModelCustomizationUuid");
+ vnf.setModelInfoGenericVnf(modelInfoGenericVnf);
+
+ VfModule vfModule = new VfModule();
+ vfModule.setVfModuleId("testVfModuleId");
+ vfModule.setVfModuleName("testVfModuleName");
+ vfModule.setModelInfoVfModule(null);
+
+ CloudRegion cloudRegion = new CloudRegion();
+
+ expectedException.expect(MapperException.class);
+ expectedException.expectMessage(ERRORMESSAGE);
+
+ mapper.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, null, vnf,
+ serviceInstance, customer, cloudRegion, requestContext, null);
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapperTest.java
index 64b532fd07..cecf34ea10 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapperTest.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapperTest.java
@@ -23,12 +23,10 @@ package org.onap.so.client.sdnc.mapper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
@@ -47,101 +45,107 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoInstanceGroup;
import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance;
import org.onap.so.client.sdnc.beans.SDNCSvcAction;
import org.onap.so.client.sdnc.beans.SDNCSvcOperation;
-
import org.onap.sdnc.northbound.client.model.GenericResourceApiRequestActionEnumeration;
import org.onap.sdnc.northbound.client.model.GenericResourceApiVnfOperationInformation;
@RunWith(MockitoJUnitRunner.class)
public class VnfTopologyOperationRequestMapperTest {
- @Spy
- private GeneralTopologyObjectMapper generalTopologyObjectMapper;
-
- @InjectMocks
- private VnfTopologyOperationRequestMapper mapper = new VnfTopologyOperationRequestMapper();
-
- @Test
- public void reqMapperTest() throws Exception {
- // prepare and set service instance
- ServiceInstance serviceInstance = new ServiceInstance();
- ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
- modelInfoServiceInstance.setModelInvariantUuid("modelInvariantUuid");
- modelInfoServiceInstance.setModelName("modelName");
- modelInfoServiceInstance.setModelUuid("modelUuid");
- modelInfoServiceInstance.setModelVersion("modelVersion");
- serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
-
- //prepare VNF
- ModelInfoGenericVnf genericVnf = new ModelInfoGenericVnf();
- genericVnf.setModelInvariantUuid("vnfModelInvariantUUID");
- genericVnf.setModelVersion("vnfModelVersion");
- genericVnf.setModelName("vnfModelName");
- genericVnf.setModelUuid("vnfModelUUID");
- genericVnf.setModelCustomizationUuid("vnfModelCustomizationUUID");
-
- ModelInfoInstanceGroup modelL3Network = new ModelInfoInstanceGroup();
- modelL3Network.setType("L3-NETWORK");
-
- InstanceGroup instanceGroup1 = new InstanceGroup();
- instanceGroup1.setId("l3-network-ig-111");
- instanceGroup1.setModelInfoInstanceGroup(modelL3Network);
-
- InstanceGroup instanceGroup2 = new InstanceGroup();
- instanceGroup2.setId("l3-network-ig-222");
- instanceGroup2.setModelInfoInstanceGroup(modelL3Network);
-
- GenericVnf vnf = new GenericVnf();
- vnf.setModelInfoGenericVnf(genericVnf);
- vnf.setVnfId("vnfId");
- vnf.setVnfType("vnfType");
- vnf.getInstanceGroups().add(instanceGroup1);
- vnf.getInstanceGroups().add(instanceGroup2);
- License license = new License();
- List<String> entitlementPoolUuids = new ArrayList<>();
- entitlementPoolUuids.add("entitlementPoolUuid");
- List<String> licenseKeyGroupUuids = new ArrayList<>();
- licenseKeyGroupUuids.add("licenseKeyGroupUuid");
- license.setEntitlementPoolUuids(entitlementPoolUuids);
- license.setLicenseKeyGroupUuids(licenseKeyGroupUuids);
- vnf.setLicense(license);
-
- // prepare Customer object
- Customer customer = new Customer();
- customer.setGlobalCustomerId("globalCustomerId");
-
- ServiceSubscription serviceSubscription = new ServiceSubscription();
- serviceSubscription.setServiceType("productFamilyId");
- customer.setServiceSubscription(serviceSubscription);
-
- // set Customer on service instance
- customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
-
-
- //prepare RequestContext
- RequestContext requestContext = new RequestContext();
- Map<String, Object> userParams = new HashMap<>();
- userParams.put("key1", "value1");
- requestContext.setUserParams(userParams);
- requestContext.setProductFamilyId("productFamilyId");
- requestContext.setMsoRequestId("MsoRequestId");
-
- CloudRegion cloudRegion = new CloudRegion();
-
- GenericResourceApiVnfOperationInformation vnfOpInformation = mapper.reqMapper(
- SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, vnf, serviceInstance, customer,
- cloudRegion, requestContext,true);
- GenericResourceApiVnfOperationInformation vnfOpInformationNullReqContext = mapper.reqMapper(
- SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, vnf, serviceInstance, customer,
- cloudRegion, null,true);
-
- assertNull(vnfOpInformation.getServiceInformation().getOnapModelInformation().getModelCustomizationUuid());
- assertEquals("vnfModelCustomizationUUID", vnfOpInformation.getVnfInformation().getOnapModelInformation().getModelCustomizationUuid());
- assertEquals(2, vnfOpInformation.getVnfRequestInput().getVnfNetworkInstanceGroupIds().size());
- assertEquals("l3-network-ig-111", vnfOpInformation.getVnfRequestInput().getVnfNetworkInstanceGroupIds().get(0).getVnfNetworkInstanceGroupId());
- assertEquals("l3-network-ig-222", vnfOpInformation.getVnfRequestInput().getVnfNetworkInstanceGroupIds().get(1).getVnfNetworkInstanceGroupId());
- assertEquals("entitlementPoolUuid", vnfOpInformation.getVnfRequestInput().getVnfInputParameters().getParam().get(1).getValue());
- assertEquals("licenseKeyGroupUuid", vnfOpInformation.getVnfRequestInput().getVnfInputParameters().getParam().get(2).getValue());
- assertEquals("MsoRequestId", vnfOpInformation.getRequestInformation().getRequestId());
- assertNotNull(vnfOpInformationNullReqContext.getRequestInformation().getRequestId());
- }
+ @Spy
+ private GeneralTopologyObjectMapper generalTopologyObjectMapper;
+
+ @InjectMocks
+ private VnfTopologyOperationRequestMapper mapper = new VnfTopologyOperationRequestMapper();
+
+ @Test
+ public void reqMapperTest() throws Exception {
+ // prepare and set service instance
+ ServiceInstance serviceInstance = new ServiceInstance();
+ ModelInfoServiceInstance modelInfoServiceInstance = new ModelInfoServiceInstance();
+ modelInfoServiceInstance.setModelInvariantUuid("modelInvariantUuid");
+ modelInfoServiceInstance.setModelName("modelName");
+ modelInfoServiceInstance.setModelUuid("modelUuid");
+ modelInfoServiceInstance.setModelVersion("modelVersion");
+ serviceInstance.setModelInfoServiceInstance(modelInfoServiceInstance);
+
+ // prepare VNF
+ ModelInfoGenericVnf genericVnf = new ModelInfoGenericVnf();
+ genericVnf.setModelInvariantUuid("vnfModelInvariantUUID");
+ genericVnf.setModelVersion("vnfModelVersion");
+ genericVnf.setModelName("vnfModelName");
+ genericVnf.setModelUuid("vnfModelUUID");
+ genericVnf.setModelCustomizationUuid("vnfModelCustomizationUUID");
+
+ ModelInfoInstanceGroup modelL3Network = new ModelInfoInstanceGroup();
+ modelL3Network.setType("L3-NETWORK");
+
+ InstanceGroup instanceGroup1 = new InstanceGroup();
+ instanceGroup1.setId("l3-network-ig-111");
+ instanceGroup1.setModelInfoInstanceGroup(modelL3Network);
+
+ InstanceGroup instanceGroup2 = new InstanceGroup();
+ instanceGroup2.setId("l3-network-ig-222");
+ instanceGroup2.setModelInfoInstanceGroup(modelL3Network);
+
+ GenericVnf vnf = new GenericVnf();
+ vnf.setModelInfoGenericVnf(genericVnf);
+ vnf.setVnfId("vnfId");
+ vnf.setVnfType("vnfType");
+ vnf.getInstanceGroups().add(instanceGroup1);
+ vnf.getInstanceGroups().add(instanceGroup2);
+ License license = new License();
+ List<String> entitlementPoolUuids = new ArrayList<>();
+ entitlementPoolUuids.add("entitlementPoolUuid");
+ List<String> licenseKeyGroupUuids = new ArrayList<>();
+ licenseKeyGroupUuids.add("licenseKeyGroupUuid");
+ license.setEntitlementPoolUuids(entitlementPoolUuids);
+ license.setLicenseKeyGroupUuids(licenseKeyGroupUuids);
+ vnf.setLicense(license);
+
+ // prepare Customer object
+ Customer customer = new Customer();
+ customer.setGlobalCustomerId("globalCustomerId");
+
+ ServiceSubscription serviceSubscription = new ServiceSubscription();
+ serviceSubscription.setServiceType("productFamilyId");
+ customer.setServiceSubscription(serviceSubscription);
+
+ // set Customer on service instance
+ customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+
+
+ // prepare RequestContext
+ RequestContext requestContext = new RequestContext();
+ Map<String, Object> userParams = new HashMap<>();
+ userParams.put("key1", "value1");
+ requestContext.setUserParams(userParams);
+ requestContext.setProductFamilyId("productFamilyId");
+ requestContext.setMsoRequestId("MsoRequestId");
+
+ CloudRegion cloudRegion = new CloudRegion();
+
+ GenericResourceApiVnfOperationInformation vnfOpInformation =
+ mapper.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, vnf, serviceInstance, customer,
+ cloudRegion, requestContext, true);
+ GenericResourceApiVnfOperationInformation vnfOpInformationNullReqContext =
+ mapper.reqMapper(SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,
+ GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, vnf, serviceInstance, customer,
+ cloudRegion, null, true);
+
+ assertNull(vnfOpInformation.getServiceInformation().getOnapModelInformation().getModelCustomizationUuid());
+ assertEquals("vnfModelCustomizationUUID",
+ vnfOpInformation.getVnfInformation().getOnapModelInformation().getModelCustomizationUuid());
+ assertEquals(2, vnfOpInformation.getVnfRequestInput().getVnfNetworkInstanceGroupIds().size());
+ assertEquals("l3-network-ig-111", vnfOpInformation.getVnfRequestInput().getVnfNetworkInstanceGroupIds().get(0)
+ .getVnfNetworkInstanceGroupId());
+ assertEquals("l3-network-ig-222", vnfOpInformation.getVnfRequestInput().getVnfNetworkInstanceGroupIds().get(1)
+ .getVnfNetworkInstanceGroupId());
+ assertEquals("entitlementPoolUuid",
+ vnfOpInformation.getVnfRequestInput().getVnfInputParameters().getParam().get(1).getValue());
+ assertEquals("licenseKeyGroupUuid",
+ vnfOpInformation.getVnfRequestInput().getVnfInputParameters().getParam().get(2).getValue());
+ assertEquals("MsoRequestId", vnfOpInformation.getRequestInformation().getRequestId());
+ assertNotNull(vnfOpInformationNullReqContext.getRequestInformation().getRequestId());
+ }
}
diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sniro/SniroClientTestIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sniro/SniroClientTestIT.java
index 722180f54b..56c52388f8 100644
--- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sniro/SniroClientTestIT.java
+++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sniro/SniroClientTestIT.java
@@ -23,14 +23,12 @@ package org.onap.so.client.sniro;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
-
import org.junit.Test;
import org.onap.so.BaseIntegrationTest;
import org.onap.so.client.exception.BadResponseException;
import org.onap.so.client.sniro.beans.SniroConductorRequest;
import org.onap.so.client.sniro.beans.SniroManagerRequest;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -42,108 +40,96 @@ public class SniroClientTestIT extends BaseIntegrationTest {
@Test(expected = Test.None.class)
public void testPostDemands_success() throws BadResponseException, JsonProcessingException {
- String mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"corys cool\", \"requestStatus\": \"accepted\"}";
+ String mockResponse =
+ "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"corys cool\", \"requestStatus\": \"accepted\"}";
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- client.postDemands(new SniroManagerRequest());
+ client.postDemands(new SniroManagerRequest());
}
@Test(expected = BadResponseException.class)
public void testPostDemands_error_failed() throws JsonProcessingException, BadResponseException {
- String mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"missing data\", \"requestStatus\": \"failed\"}";
+ String mockResponse =
+ "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"missing data\", \"requestStatus\": \"failed\"}";
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- client.postDemands(new SniroManagerRequest());
+ client.postDemands(new SniroManagerRequest());
- //TODO assertEquals("missing data", );
+ // TODO assertEquals("missing data", );
}
@Test(expected = BadResponseException.class)
public void testPostDemands_error_noMessage() throws JsonProcessingException, BadResponseException {
- String mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"\", \"requestStatus\": \"failed\"}";
+ String mockResponse =
+ "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"\", \"requestStatus\": \"failed\"}";
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- client.postDemands(new SniroManagerRequest());
+ client.postDemands(new SniroManagerRequest());
}
@Test(expected = BadResponseException.class)
public void testPostDemands_error_noStatus() throws JsonProcessingException, BadResponseException {
- String mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"missing data\", \"requestStatus\": null}";
+ String mockResponse =
+ "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"missing data\", \"requestStatus\": null}";
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- client.postDemands(new SniroManagerRequest());
+ client.postDemands(new SniroManagerRequest());
}
@Test(expected = BadResponseException.class)
public void testPostDemands_error_empty() throws JsonProcessingException, BadResponseException {
- String mockResponse = "{ }";
+ String mockResponse = "{ }";
- wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- client.postDemands(new SniroManagerRequest());
+ client.postDemands(new SniroManagerRequest());
}
@Test(expected = Test.None.class)
public void testPostRelease_success() throws BadResponseException, JsonProcessingException {
String mockResponse = "{\"status\": \"success\", \"message\": \"corys cool\"}";
- wireMockServer.stubFor(post(urlEqualTo("/v1/release-orders"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/v1/release-orders")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- client.postRelease(new SniroConductorRequest());
+ client.postRelease(new SniroConductorRequest());
}
@Test(expected = BadResponseException.class)
public void testPostRelease_error_failed() throws BadResponseException, JsonProcessingException {
String mockResponse = "{\"status\": \"failure\", \"message\": \"corys cool\"}";
- wireMockServer.stubFor(post(urlEqualTo("/v1/release-orders"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/v1/release-orders")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- client.postRelease(new SniroConductorRequest());
+ client.postRelease(new SniroConductorRequest());
}
@Test(expected = BadResponseException.class)
public void testPostRelease_error_noStatus() throws BadResponseException, JsonProcessingException {
String mockResponse = "{\"status\": \"\", \"message\": \"corys cool\"}";
- wireMockServer.stubFor(post(urlEqualTo("/v1/release-orders"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/v1/release-orders")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- client.postRelease(new SniroConductorRequest());
+ client.postRelease(new SniroConductorRequest());
}
@@ -151,12 +137,10 @@ public class SniroClientTestIT extends BaseIntegrationTest {
public void testPostRelease_error_noMessage() throws BadResponseException, JsonProcessingException {
String mockResponse = "{\"status\": \"failure\", \"message\": null}";
- wireMockServer.stubFor(post(urlEqualTo("/v1/release-orders"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/v1/release-orders")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- client.postRelease(new SniroConductorRequest());
+ client.postRelease(new SniroConductorRequest());
}
@@ -164,12 +148,10 @@ public class SniroClientTestIT extends BaseIntegrationTest {
public void testPostRelease_error_empty() throws BadResponseException, JsonProcessingException {
String mockResponse = "{ }";
- wireMockServer.stubFor(post(urlEqualTo("/v1/release-orders"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody(mockResponse)));
+ wireMockServer.stubFor(post(urlEqualTo("/v1/release-orders")).willReturn(
+ aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse)));
- client.postRelease(new SniroConductorRequest());
+ client.postRelease(new SniroConductorRequest());
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyBaseException.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyBaseException.java
index a6e0cc3680..b8006cb45f 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyBaseException.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyBaseException.java
@@ -21,23 +21,22 @@
package org.onap.so.cloudify.base.client;
/**
- * A common abstract parent of all Openstack Exception types, allowing
- * calling classes the choice to catch all error exceptions together.
+ * A common abstract parent of all Openstack Exception types, allowing calling classes the choice to catch all error
+ * exceptions together.
*/
-public abstract class CloudifyBaseException extends RuntimeException
-{
- private static final long serialVersionUID = 1L;
+public abstract class CloudifyBaseException extends RuntimeException {
+ private static final long serialVersionUID = 1L;
- /*
- * Implement only the basic constructors
- */
- public CloudifyBaseException () {}
-
- public CloudifyBaseException(String message) {
- super(message);
- }
+ /*
+ * Implement only the basic constructors
+ */
+ public CloudifyBaseException() {}
- public CloudifyBaseException(String message, Throwable cause) {
- super(message, cause);
- }
+ public CloudifyBaseException(String message) {
+ super(message);
+ }
+
+ public CloudifyBaseException(String message, Throwable cause) {
+ super(message, cause);
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClient.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClient.java
index 8387557c24..1893590106 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClient.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClient.java
@@ -21,114 +21,116 @@
package org.onap.so.cloudify.base.client;
import java.util.Properties;
-
import org.onap.so.cloudify.connector.http.HttpClientConnector;
public class CloudifyClient {
-
- protected String managerEndpoint;
- protected String tenant = "default_tenant"; // Note - only default_tenant supported in community edition
-
- protected CloudifyTokenProvider tokenProvider;
-
- protected static int AUTHENTICATION_RETRIES = 1;
-
- protected CloudifyClientConnector connector;
-
- protected Properties properties = new Properties();
-
- public CloudifyClient(String managerEndpoint) {
- this.managerEndpoint = managerEndpoint;
- this.connector = new HttpClientConnector();
- }
-
- public CloudifyClient(String managerEndpoint, String tenant) {
- this.managerEndpoint = managerEndpoint;
- this.tenant = tenant;
- this.connector = new HttpClientConnector();
- }
-
- public CloudifyClient(String managerEndpoint, CloudifyClientConnector connector) {
- this.managerEndpoint = managerEndpoint;
- this.connector = connector;
- }
-
- /**
- * Execute a Cloudify request by making the REST API call. Return the
- * complete CloudifyResponse structure, which includes the complete
- * HTTP response.
- * @param request a CloudifyRequest object
- * @return a CloudifyResponse object
- */
- public <T> CloudifyResponse request(CloudifyRequest<T> request) {
- CloudifyResponseException authException = null;
-
- for (int i = 0; i <= AUTHENTICATION_RETRIES; i++) {
- request.endpoint(managerEndpoint);
- request.header("Tenant", tenant);
- if (tokenProvider != null)
- request.header("Authentication-Token", tokenProvider.getToken());
-
- try {
- return connector.request(request);
- } catch (CloudifyResponseException e) {
- if (e.getStatus() != CloudifyResponseStatus.NOT_AUTHORIZED
- || tokenProvider == null) {
- throw e;
- }
- authException = e;
- tokenProvider.expireToken();
- }
- }
-
- if (authException != null) {
- throw authException;
- }
-
- return null;
- }
-
- /**
- * Execute a CloudifyRequest by sending the REST API call to the Cloudify
- * Manager endpoint. The return type is a JSON POJO object containing the
- * response body entity.
- * @param request
- * @return a JSON POJO object specific to the request type
- */
- public <T> T execute(CloudifyRequest<T> request) {
- CloudifyResponse response = request(request);
- return (request.returnType() != null && request.returnType() != Void.class) ? response.getEntity(request.returnType()) : null;
- }
-
- public void property(String property, String value) {
- properties.put(property, value);
- }
-
- /**
- * Set a Token Provider. This class should be able to produce an
- * authentication token on-demand.
- * @param tokenProvider
- */
- public void setTokenProvider(CloudifyTokenProvider tokenProvider) {
- this.tokenProvider = tokenProvider;
- }
-
- /**
- * Manually set the authentication token to use for this client.
- * @param token
- */
- public void setToken(String token) {
- setTokenProvider(new CloudifySimpleTokenProvider(token));
- }
-
- /**
- * Perform a simple GET request with no request message body
- * @param path
- * @param returnType
- * @return An object of Class <R>
- */
- public <R> CloudifyRequest<R> get(String path, Class<R> returnType) {
- return new CloudifyRequest<R>(this, HttpMethod.GET, path, null, returnType);
- }
-
+
+ protected String managerEndpoint;
+ protected String tenant = "default_tenant"; // Note - only default_tenant supported in community edition
+
+ protected CloudifyTokenProvider tokenProvider;
+
+ protected static int AUTHENTICATION_RETRIES = 1;
+
+ protected CloudifyClientConnector connector;
+
+ protected Properties properties = new Properties();
+
+ public CloudifyClient(String managerEndpoint) {
+ this.managerEndpoint = managerEndpoint;
+ this.connector = new HttpClientConnector();
+ }
+
+ public CloudifyClient(String managerEndpoint, String tenant) {
+ this.managerEndpoint = managerEndpoint;
+ this.tenant = tenant;
+ this.connector = new HttpClientConnector();
+ }
+
+ public CloudifyClient(String managerEndpoint, CloudifyClientConnector connector) {
+ this.managerEndpoint = managerEndpoint;
+ this.connector = connector;
+ }
+
+ /**
+ * Execute a Cloudify request by making the REST API call. Return the complete CloudifyResponse structure, which
+ * includes the complete HTTP response.
+ *
+ * @param request a CloudifyRequest object
+ * @return a CloudifyResponse object
+ */
+ public <T> CloudifyResponse request(CloudifyRequest<T> request) {
+ CloudifyResponseException authException = null;
+
+ for (int i = 0; i <= AUTHENTICATION_RETRIES; i++) {
+ request.endpoint(managerEndpoint);
+ request.header("Tenant", tenant);
+ if (tokenProvider != null)
+ request.header("Authentication-Token", tokenProvider.getToken());
+
+ try {
+ return connector.request(request);
+ } catch (CloudifyResponseException e) {
+ if (e.getStatus() != CloudifyResponseStatus.NOT_AUTHORIZED || tokenProvider == null) {
+ throw e;
+ }
+ authException = e;
+ tokenProvider.expireToken();
+ }
+ }
+
+ if (authException != null) {
+ throw authException;
+ }
+
+ return null;
+ }
+
+ /**
+ * Execute a CloudifyRequest by sending the REST API call to the Cloudify Manager endpoint. The return type is a
+ * JSON POJO object containing the response body entity.
+ *
+ * @param request
+ * @return a JSON POJO object specific to the request type
+ */
+ public <T> T execute(CloudifyRequest<T> request) {
+ CloudifyResponse response = request(request);
+ return (request.returnType() != null && request.returnType() != Void.class)
+ ? response.getEntity(request.returnType())
+ : null;
+ }
+
+ public void property(String property, String value) {
+ properties.put(property, value);
+ }
+
+ /**
+ * Set a Token Provider. This class should be able to produce an authentication token on-demand.
+ *
+ * @param tokenProvider
+ */
+ public void setTokenProvider(CloudifyTokenProvider tokenProvider) {
+ this.tokenProvider = tokenProvider;
+ }
+
+ /**
+ * Manually set the authentication token to use for this client.
+ *
+ * @param token
+ */
+ public void setToken(String token) {
+ setTokenProvider(new CloudifySimpleTokenProvider(token));
+ }
+
+ /**
+ * Perform a simple GET request with no request message body
+ *
+ * @param path
+ * @param returnType
+ * @return An object of Class <R>
+ */
+ public <R> CloudifyRequest<R> get(String path, Class<R> returnType) {
+ return new CloudifyRequest<R>(this, HttpMethod.GET, path, null, returnType);
+ }
+
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClientConnector.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClientConnector.java
index 2e00c4c396..f031f10bb5 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClientConnector.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClientConnector.java
@@ -23,6 +23,6 @@ package org.onap.so.cloudify.base.client;
public interface CloudifyClientConnector {
- public <T> CloudifyResponse request(CloudifyRequest<T> request);
+ public <T> CloudifyResponse request(CloudifyRequest<T> request);
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClientTokenProvider.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClientTokenProvider.java
index 7676afa6c7..2478557afc 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClientTokenProvider.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClientTokenProvider.java
@@ -21,9 +21,7 @@
package org.onap.so.cloudify.base.client;
import java.util.Date;
-
import org.apache.commons.lang.time.DateUtils;
-
import org.onap.so.cloudify.v3.client.Cloudify;
import org.onap.so.cloudify.v3.client.TokensResource.GetToken;
import org.onap.so.cloudify.v3.model.Token;
@@ -36,50 +34,49 @@ import org.onap.so.cloudify.v3.model.Token;
*/
public class CloudifyClientTokenProvider implements CloudifyTokenProvider {
- String user;
- String password;
- String token;
- Date expiration;
- Cloudify cloudify = null;
+ String user;
+ String password;
+ String token;
+ Date expiration;
+ Cloudify cloudify = null;
+
+ public CloudifyClientTokenProvider(String cloudifyEndpoint, String user, String password) {
+ this.user = user;
+ this.password = password;
+
+ cloudify = new Cloudify(cloudifyEndpoint);
+ }
+
+ @Override
+ public String getToken() {
+ Date now = new Date();
+ if (token != null && expiration != null && expiration.after(now)) {
+ return token;
+ }
+
+ // Create a "Get Token" request. Force basic authentication to acquire the token itself.
+ GetToken tokenRequest = cloudify.tokens().token();
+ tokenRequest.setBasicAuthentication(user, password);
+ Token newToken = tokenRequest.execute();
- public CloudifyClientTokenProvider(String cloudifyEndpoint, String user, String password) {
- this.user = user;
- this.password = password;
-
- cloudify = new Cloudify (cloudifyEndpoint);
- }
+ token = newToken.getValue();
- @Override
- public String getToken() {
- Date now = new Date();
- if (token != null && expiration != null && expiration.after(now)) {
- return token;
- }
+ if (expiration == null) {
+ expiration = new Date();
+ }
+ // TODO: Make this property driven (or see if it comes back somehow in response)
+ expiration = DateUtils.addMinutes(expiration, 10);
- // Create a "Get Token" request. Force basic authentication to acquire the token itself.
- GetToken tokenRequest = cloudify.tokens().token();
- tokenRequest.setBasicAuthentication(user, password);
- Token newToken = tokenRequest.execute();
-
- token = newToken.getValue();
-
- if (expiration == null) {
- expiration = new Date();
- }
- // TODO: Make this property driven (or see if it comes back somehow in response)
- expiration = DateUtils.addMinutes(expiration, 10);
-
- return token;
- }
+ return token;
+ }
- @Override
- /**
- * This doesn't actually expire the token in Cloudify. It just prevents this token provider
- * from using it.
- */
- public void expireToken() {
- expiration = null;
- token = null;
- }
+ @Override
+ /**
+ * This doesn't actually expire the token in Cloudify. It just prevents this token provider from using it.
+ */
+ public void expireToken() {
+ expiration = null;
+ token = null;
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyConnectException.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyConnectException.java
index 3f378fd10f..5bcc27bafc 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyConnectException.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyConnectException.java
@@ -21,19 +21,18 @@
package org.onap.so.cloudify.base.client;
/**
- * Custom RuntimeException to report connection errors to Openstack endpoints.
- * Must be a RuntimeException to conform with OpenstackClient interface, which
- * does not declare specific Exceptions.
+ * Custom RuntimeException to report connection errors to Openstack endpoints. Must be a RuntimeException to conform
+ * with OpenstackClient interface, which does not declare specific Exceptions.
*/
public class CloudifyConnectException extends CloudifyBaseException {
- private static final long serialVersionUID = 7294957362769575271L;
+ private static final long serialVersionUID = 7294957362769575271L;
- public CloudifyConnectException(String message) {
- super(message);
- }
+ public CloudifyConnectException(String message) {
+ super(message);
+ }
- public CloudifyConnectException(String message, Throwable cause) {
- super(message, cause);
- }
+ public CloudifyConnectException(String message, Throwable cause) {
+ super(message, cause);
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyRequest.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyRequest.java
index ffa89fe4a3..0f9ad2da39 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyRequest.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyRequest.java
@@ -28,161 +28,163 @@ import java.util.ArrayList;
import java.util.Map;
public class CloudifyRequest<R> {
-
- private CloudifyClient client;
-
- public CloudifyRequest() {
-
- }
-
- public CloudifyRequest(CloudifyClient client, HttpMethod method, CharSequence path, Entity<?> entity, Class<R> returnType) {
- this.client = client;
- this.method = method;
- this.path = new StringBuilder(path);
- this.entity = entity;
- this.returnType = returnType;
- header("Accept", "application/json");
- }
-
- private String endpoint;
-
- private HttpMethod method;
-
- private StringBuilder path = new StringBuilder();
-
- private Map<String, List<Object>> headers = new HashMap<String, List<Object>>();
-
- private Entity<?> entity;
-
- private Class<R> returnType;
-
- private boolean basicAuth = false;
- private String user = null;
- private String password = null;
-
- public CloudifyRequest<R> endpoint(String endpoint) {
- this.endpoint = endpoint;
- return this;
- }
-
- public String endpoint() {
- return endpoint;
- }
-
- public CloudifyRequest<R> method(HttpMethod method) {
- this.method = method;
- return this;
- }
-
- public HttpMethod method() {
- return method;
- }
-
- public CloudifyRequest<R> path(String path) {
- this.path.append(path);
- return this;
- }
-
- public String path() {
- return path.toString();
- }
-
- public CloudifyRequest<R> header(String name, Object value) {
- if(value != null) {
- headers.put(name, Arrays.asList(value));
- }
- return this;
- }
-
- public Map<String, List<Object>> headers() {
- return headers;
- }
-
- public <T> Entity<T> entity(T entity, String contentType) {
- return new Entity<T>(entity, contentType);
- }
-
- public Entity<?> entity() {
- return entity;
- }
-
- public <T> Entity<T> json(T entity) {
- return entity(entity, "application/json");
- }
-
- public void returnType(Class<R> returnType) {
- this.returnType = returnType;
- }
-
- public Class<R> returnType() {
- return returnType;
- }
-
- /*
- * Use Basic Authentication for this request. If not set, the client will use Token authentication
- * if a token provider is defined. Otherwise, no authentication will be applied.
- */
- public void setBasicAuthentication (String user, String password) {
- this.basicAuth = true;
- this.user = user;
- this.password= password;
- }
-
- public boolean isBasicAuth () {
- return this.basicAuth;
- }
-
- public String getUser() {
- return user;
- }
-
- public String getPassword() {
- return password;
- }
-
- public R execute() {
- return client.execute(this);
- }
-
- public CloudifyResponse request() {
- return client.request(this);
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return "CloudifyRequest [endpoint=" + endpoint + ", method=" + method
- + ", path=" + path + ", headers=" + headers + ", entity="
- + entity + ", returnType=" + returnType + "]";
- }
-
- private Map<String, List<Object> > queryParams = new LinkedHashMap<String, List<Object> >();
-
- public Map<String, List<Object> > queryParams() {
- return queryParams;
- }
-
- public CloudifyRequest<R> queryParam(String key, Object value) {
- if (queryParams.containsKey(key)) {
- List<Object> values = queryParams.get(key);
- values.add(value);
- } else {
- List<Object> values = new ArrayList<Object>();
- values.add(value);
- queryParams.put(key, values);
- }
-
- return this;
- }
-
- protected static String buildPath(String ... elements) {
- StringBuilder stringBuilder = new StringBuilder();
- for (String element : elements) {
+
+ private CloudifyClient client;
+
+ public CloudifyRequest() {
+
+ }
+
+ public CloudifyRequest(CloudifyClient client, HttpMethod method, CharSequence path, Entity<?> entity,
+ Class<R> returnType) {
+ this.client = client;
+ this.method = method;
+ this.path = new StringBuilder(path);
+ this.entity = entity;
+ this.returnType = returnType;
+ header("Accept", "application/json");
+ }
+
+ private String endpoint;
+
+ private HttpMethod method;
+
+ private StringBuilder path = new StringBuilder();
+
+ private Map<String, List<Object>> headers = new HashMap<String, List<Object>>();
+
+ private Entity<?> entity;
+
+ private Class<R> returnType;
+
+ private boolean basicAuth = false;
+ private String user = null;
+ private String password = null;
+
+ public CloudifyRequest<R> endpoint(String endpoint) {
+ this.endpoint = endpoint;
+ return this;
+ }
+
+ public String endpoint() {
+ return endpoint;
+ }
+
+ public CloudifyRequest<R> method(HttpMethod method) {
+ this.method = method;
+ return this;
+ }
+
+ public HttpMethod method() {
+ return method;
+ }
+
+ public CloudifyRequest<R> path(String path) {
+ this.path.append(path);
+ return this;
+ }
+
+ public String path() {
+ return path.toString();
+ }
+
+ public CloudifyRequest<R> header(String name, Object value) {
+ if (value != null) {
+ headers.put(name, Arrays.asList(value));
+ }
+ return this;
+ }
+
+ public Map<String, List<Object>> headers() {
+ return headers;
+ }
+
+ public <T> Entity<T> entity(T entity, String contentType) {
+ return new Entity<T>(entity, contentType);
+ }
+
+ public Entity<?> entity() {
+ return entity;
+ }
+
+ public <T> Entity<T> json(T entity) {
+ return entity(entity, "application/json");
+ }
+
+ public void returnType(Class<R> returnType) {
+ this.returnType = returnType;
+ }
+
+ public Class<R> returnType() {
+ return returnType;
+ }
+
+ /*
+ * Use Basic Authentication for this request. If not set, the client will use Token authentication if a token
+ * provider is defined. Otherwise, no authentication will be applied.
+ */
+ public void setBasicAuthentication(String user, String password) {
+ this.basicAuth = true;
+ this.user = user;
+ this.password = password;
+ }
+
+ public boolean isBasicAuth() {
+ return this.basicAuth;
+ }
+
+ public String getUser() {
+ return user;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public R execute() {
+ return client.execute(this);
+ }
+
+ public CloudifyResponse request() {
+ return client.request(this);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return "CloudifyRequest [endpoint=" + endpoint + ", method=" + method + ", path=" + path + ", headers="
+ + headers + ", entity=" + entity + ", returnType=" + returnType + "]";
+ }
+
+ private Map<String, List<Object>> queryParams = new LinkedHashMap<String, List<Object>>();
+
+ public Map<String, List<Object>> queryParams() {
+ return queryParams;
+ }
+
+ public CloudifyRequest<R> queryParam(String key, Object value) {
+ if (queryParams.containsKey(key)) {
+ List<Object> values = queryParams.get(key);
+ values.add(value);
+ } else {
+ List<Object> values = new ArrayList<Object>();
+ values.add(value);
+ queryParams.put(key, values);
+ }
+
+ return this;
+ }
+
+ protected static String buildPath(String... elements) {
+ StringBuilder stringBuilder = new StringBuilder();
+ for (String element : elements) {
stringBuilder.append(element);
}
- return stringBuilder.toString();
- }
+ return stringBuilder.toString();
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponse.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponse.java
index 2d920734b5..6b70e5fa95 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponse.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponse.java
@@ -24,16 +24,16 @@ import java.io.InputStream;
import java.io.Serializable;
import java.util.Map;
-public interface CloudifyResponse extends Serializable{
+public interface CloudifyResponse extends Serializable {
- public <T> T getEntity(Class<T> returnType);
+ public <T> T getEntity(Class<T> returnType);
- public <T> T getErrorEntity(Class<T> returnType);
+ public <T> T getErrorEntity(Class<T> returnType);
- public InputStream getInputStream();
+ public InputStream getInputStream();
+
+ public String getHeader(String name);
+
+ public Map<String, String> headers();
- public String getHeader(String name);
-
- public Map<String, String> headers();
-
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponseException.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponseException.java
index f7c42d3957..966cc8f144 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponseException.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponseException.java
@@ -24,38 +24,38 @@ import org.onap.so.cloudify.v3.model.CloudifyError;
public class CloudifyResponseException extends CloudifyBaseException {
- private static final long serialVersionUID = 7294957362769575271L;
-
- protected String message;
- protected int status;
-
- // Make the response available for exception handling (includes body)
- protected CloudifyResponse response;
-
- public CloudifyResponseException(String message, int status) {
- this.message = message;
- this.status = status;
- this.response = null;
- }
-
- // Include the response message itself. The body is a CloudifyError JSON structure.
- public CloudifyResponseException(String message, int status, CloudifyResponse response) {
- CloudifyError error = response.getErrorEntity(CloudifyError.class);
- this.message = message + ": " + error.getErrorCode();
- this.status = status;
- this.response = response;
- }
-
- public String getMessage() {
- return message;
- }
-
- public int getStatus() {
- return status;
- }
-
- public CloudifyResponse getResponse() {
- return response;
- }
+ private static final long serialVersionUID = 7294957362769575271L;
+
+ protected String message;
+ protected int status;
+
+ // Make the response available for exception handling (includes body)
+ protected CloudifyResponse response;
+
+ public CloudifyResponseException(String message, int status) {
+ this.message = message;
+ this.status = status;
+ this.response = null;
+ }
+
+ // Include the response message itself. The body is a CloudifyError JSON structure.
+ public CloudifyResponseException(String message, int status, CloudifyResponse response) {
+ CloudifyError error = response.getErrorEntity(CloudifyError.class);
+ this.message = message + ": " + error.getErrorCode();
+ this.status = status;
+ this.response = response;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public int getStatus() {
+ return status;
+ }
+
+ public CloudifyResponse getResponse() {
+ return response;
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponseStatus.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponseStatus.java
index af6940c041..ccdd7a4168 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponseStatus.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyResponseStatus.java
@@ -22,16 +22,16 @@ package org.onap.so.cloudify.base.client;
public class CloudifyResponseStatus {
- public static final int OK = 200;
+ public static final int OK = 200;
- public static final int ACCEPTED = 201;
+ public static final int ACCEPTED = 201;
- public static final int BAD_REQUEST = 400;
+ public static final int BAD_REQUEST = 400;
- public static final int NOT_AUTHORIZED = 401;
+ public static final int NOT_AUTHORIZED = 401;
- public static final int NOT_FOUND = 404;
+ public static final int NOT_FOUND = 404;
- public static final int CONFLICT = 409;
+ public static final int CONFLICT = 409;
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifySimpleTokenProvider.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifySimpleTokenProvider.java
index 074d164b48..0c1e42d0e8 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifySimpleTokenProvider.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifySimpleTokenProvider.java
@@ -22,19 +22,18 @@ package org.onap.so.cloudify.base.client;
public class CloudifySimpleTokenProvider implements CloudifyTokenProvider {
- String token;
+ String token;
- public CloudifySimpleTokenProvider(String token) {
- this.token = token;
- }
+ public CloudifySimpleTokenProvider(String token) {
+ this.token = token;
+ }
- @Override
- public String getToken() {
- return this.token;
- }
+ @Override
+ public String getToken() {
+ return this.token;
+ }
- @Override
- public void expireToken() {
- }
+ @Override
+ public void expireToken() {}
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyTokenProvider.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyTokenProvider.java
index 8915a0393b..7c31d9288f 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyTokenProvider.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyTokenProvider.java
@@ -22,8 +22,8 @@ package org.onap.so.cloudify.base.client;
public interface CloudifyTokenProvider {
- String getToken();
+ String getToken();
- void expireToken();
+ void expireToken();
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/Entity.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/Entity.java
index 15a913a4c4..095582fa51 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/Entity.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/Entity.java
@@ -21,51 +21,51 @@
package org.onap.so.cloudify.base.client;
public class Entity<T> {
-
- private T entity;
-
- private String contentType;
-
- public static <T> Entity<T> json(T entity) {
- return new Entity<T>(entity, "application/json");
- }
-
- public static <T> Entity<T> stream(T entity) {
- return new Entity<T>(entity, "application/octet-stream");
- }
- public Entity(T entity, String contentType) {
- super();
- this.entity = entity;
- this.contentType = contentType;
- }
+ private T entity;
- /**
- * @return the entity
- */
- public T getEntity() {
- return entity;
- }
+ private String contentType;
- /**
- * @param entity the entity to set
- */
- public void setEntity(T entity) {
- this.entity = entity;
- }
+ public static <T> Entity<T> json(T entity) {
+ return new Entity<T>(entity, "application/json");
+ }
- /**
- * @return the contentType
- */
- public String getContentType() {
- return contentType;
- }
+ public static <T> Entity<T> stream(T entity) {
+ return new Entity<T>(entity, "application/octet-stream");
+ }
+
+ public Entity(T entity, String contentType) {
+ super();
+ this.entity = entity;
+ this.contentType = contentType;
+ }
+
+ /**
+ * @return the entity
+ */
+ public T getEntity() {
+ return entity;
+ }
+
+ /**
+ * @param entity the entity to set
+ */
+ public void setEntity(T entity) {
+ this.entity = entity;
+ }
+
+ /**
+ * @return the contentType
+ */
+ public String getContentType() {
+ return contentType;
+ }
+
+ /**
+ * @param contentType the contentType to set
+ */
+ public void setContentType(String contentType) {
+ this.contentType = contentType;
+ }
- /**
- * @param contentType the contentType to set
- */
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
-
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/HttpMethod.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/HttpMethod.java
index aa991dfcf8..2c5097f1ad 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/HttpMethod.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/HttpMethod.java
@@ -21,5 +21,5 @@
package org.onap.so.cloudify.base.client;
public enum HttpMethod {
- HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
+ HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientConnector.java b/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientConnector.java
index 247afb3124..e1992d98ca 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientConnector.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientConnector.java
@@ -30,7 +30,6 @@ import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
@@ -55,7 +54,6 @@ import org.onap.so.cloudify.base.client.CloudifyConnectException;
import org.onap.so.cloudify.base.client.CloudifyRequest;
import org.onap.so.cloudify.base.client.CloudifyResponse;
import org.onap.so.cloudify.base.client.CloudifyResponseException;
-
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -67,183 +65,175 @@ import org.slf4j.LoggerFactory;
public class HttpClientConnector implements CloudifyClientConnector {
- private static ObjectMapper DEFAULT_MAPPER;
- private static ObjectMapper WRAPPED_MAPPER;
-
+ private static ObjectMapper DEFAULT_MAPPER;
+ private static ObjectMapper WRAPPED_MAPPER;
+
private static Logger logger = LoggerFactory.getLogger(HttpClientConnector.class);
- static {
- DEFAULT_MAPPER = new ObjectMapper();
-
- DEFAULT_MAPPER.setSerializationInclusion(Include.NON_NULL);
- DEFAULT_MAPPER.disable(SerializationFeature.INDENT_OUTPUT);
- DEFAULT_MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
- DEFAULT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
-
- WRAPPED_MAPPER = new ObjectMapper();
-
- WRAPPED_MAPPER.setSerializationInclusion(Include.NON_NULL);
- WRAPPED_MAPPER.disable(SerializationFeature.INDENT_OUTPUT);
- WRAPPED_MAPPER.enable(SerializationFeature.WRAP_ROOT_VALUE);
- WRAPPED_MAPPER.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
- WRAPPED_MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
- WRAPPED_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
- }
-
- protected static <T> ObjectMapper getObjectMapper (Class<T> type) {
- return type.getAnnotation(JsonRootName.class) == null ? DEFAULT_MAPPER : WRAPPED_MAPPER;
- }
-
- public <T> CloudifyResponse request(CloudifyRequest<T> request) {
-
- CloseableHttpClient httpClient = null; //HttpClients.createDefault();
-
- if (request.isBasicAuth()) {
- // Use Basic Auth for this request.
- CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
- credentialsProvider.setCredentials(AuthScope.ANY,
- new UsernamePasswordCredentials (request.getUser(), request.getPassword()));
-
- httpClient = HttpClients.custom().setRedirectStrategy(new HttpClientRedirectStrategy()).setDefaultCredentialsProvider(credentialsProvider).build();
- }
- else {
- // Don't use basic authentication. The Client will attempt Token-based authentication
- httpClient = HttpClients.custom().setRedirectStrategy(new HttpClientRedirectStrategy()).build();
- }
-
- URI uri = null;
-
- // Build the URI with query params
- try {
- URIBuilder uriBuilder = new URIBuilder(request.endpoint() + request.path());
-
- for(Map.Entry<String, List<Object> > entry : request.queryParams().entrySet()) {
- for (Object o : entry.getValue()) {
- uriBuilder.setParameter(entry.getKey(), String.valueOf(o));
- }
- }
-
- uri = uriBuilder.build();
- } catch (URISyntaxException e) {
- throw new HttpClientException (e);
- }
-
- HttpEntity entity = null;
- if (request.entity() != null) {
- // Special handling for streaming input
- if (request.entity().getEntity() instanceof InputStream) {
- // Entity is an InputStream
- entity = new InputStreamEntity ((InputStream) request.entity().getEntity());
- }
- else {
- // Assume to be JSON. Flatten the entity to a Json string
- try {
- // Get appropriate mapper, based on existence of a root element in Entity class
- ObjectMapper mapper = getObjectMapper (request.entity().getEntity().getClass());
-
- String entityJson = mapper.writeValueAsString (request.entity().getEntity());
- entity = new StringEntity(entityJson, ContentType.create(request.entity().getContentType()));
-
- logger.debug ("Request JSON Body: {}", entityJson.replaceAll("\"password\":\"[^\"]*\"",
- "\"password\":\"***\""));
-
- } catch (JsonProcessingException e) {
- throw new HttpClientException ("Json processing error on request entity", e);
- } catch (IOException e) {
- throw new HttpClientException ("Json IO error on request entity", e);
- }
- }
- }
-
- // Determine the HttpRequest class based on the method
- HttpUriRequest httpRequest;
-
- switch (request.method()) {
- case POST:
- HttpPost post = new HttpPost(uri);
- post.setEntity (entity);
- httpRequest = post;
- break;
-
- case GET:
- httpRequest = new HttpGet(uri);
- break;
-
- case PUT:
- HttpPut put = new HttpPut(uri);
- put.setEntity (entity);
- httpRequest = put;
- break;
-
- case DELETE:
- httpRequest = new HttpDelete(uri);
- break;
-
- default:
- throw new HttpClientException ("Unrecognized HTTP Method: " + request.method());
- }
-
- for (Entry<String, List<Object>> h : request.headers().entrySet()) {
- StringBuilder sb = new StringBuilder();
- for (Object v : h.getValue()) {
- sb.append(String.valueOf(v));
- }
- httpRequest.addHeader(h.getKey(), sb.toString());
- }
-
- // Get the Response. But don't get the body entity yet, as this response
- // will be wrapped in an HttpClientResponse. The HttpClientResponse
- // buffers the body in constructor, so can close the response here.
- HttpClientResponse httpClientResponse = null;
- CloseableHttpResponse httpResponse = null;
-
- // Catch known HttpClient exceptions, and wrap them in OpenStack Client Exceptions
- // so calling functions can distinguish. Only RuntimeExceptions are allowed.
- try {
- httpResponse = httpClient.execute(httpRequest);
-
- logger.debug ("Response status: {}", httpResponse.getStatusLine().getStatusCode());
-
- httpClientResponse = new HttpClientResponse (httpResponse);
-
- int status = httpResponse.getStatusLine().getStatusCode();
- if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED ||
- status == HttpStatus.SC_NO_CONTENT || status == HttpStatus.SC_ACCEPTED)
- {
- return httpClientResponse;
- }
- }
- catch (HttpResponseException e) {
- // What exactly does this mean? It does not appear to get thrown for
- // non-2XX responses as documented.
- throw new CloudifyResponseException(e.getMessage(), e.getStatusCode());
- }
- catch (UnknownHostException e) {
- throw new CloudifyConnectException("Unknown Host: " + e.getMessage());
- }
- catch (IOException e) {
- // Catch all other IOExceptions and throw as OpenStackConnectException
- throw new CloudifyConnectException(e.getMessage());
- }
- catch (Exception e) {
- // Catchall for anything else, must throw as a RuntimeException
- logger.error("Client exception", e);
- throw new RuntimeException("Unexpected client exception", e);
- }
- finally {
- // Have the body. Close the stream
- if (httpResponse != null)
- try {
- httpResponse.close();
- } catch (IOException e) {
- logger.debug("Unable to close HTTP Response: " + e);
- }
- }
-
- // Get here on an error response (4XX-5XX)
- throw new CloudifyResponseException(httpResponse.getStatusLine().getReasonPhrase(),
- httpResponse.getStatusLine().getStatusCode(),
- httpClientResponse);
- }
+ static {
+ DEFAULT_MAPPER = new ObjectMapper();
+
+ DEFAULT_MAPPER.setSerializationInclusion(Include.NON_NULL);
+ DEFAULT_MAPPER.disable(SerializationFeature.INDENT_OUTPUT);
+ DEFAULT_MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ DEFAULT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
+
+ WRAPPED_MAPPER = new ObjectMapper();
+
+ WRAPPED_MAPPER.setSerializationInclusion(Include.NON_NULL);
+ WRAPPED_MAPPER.disable(SerializationFeature.INDENT_OUTPUT);
+ WRAPPED_MAPPER.enable(SerializationFeature.WRAP_ROOT_VALUE);
+ WRAPPED_MAPPER.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
+ WRAPPED_MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ WRAPPED_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
+ }
+
+ protected static <T> ObjectMapper getObjectMapper(Class<T> type) {
+ return type.getAnnotation(JsonRootName.class) == null ? DEFAULT_MAPPER : WRAPPED_MAPPER;
+ }
+
+ public <T> CloudifyResponse request(CloudifyRequest<T> request) {
+
+ CloseableHttpClient httpClient = null; // HttpClients.createDefault();
+
+ if (request.isBasicAuth()) {
+ // Use Basic Auth for this request.
+ CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(AuthScope.ANY,
+ new UsernamePasswordCredentials(request.getUser(), request.getPassword()));
+
+ httpClient = HttpClients.custom().setRedirectStrategy(new HttpClientRedirectStrategy())
+ .setDefaultCredentialsProvider(credentialsProvider).build();
+ } else {
+ // Don't use basic authentication. The Client will attempt Token-based authentication
+ httpClient = HttpClients.custom().setRedirectStrategy(new HttpClientRedirectStrategy()).build();
+ }
+
+ URI uri = null;
+
+ // Build the URI with query params
+ try {
+ URIBuilder uriBuilder = new URIBuilder(request.endpoint() + request.path());
+
+ for (Map.Entry<String, List<Object>> entry : request.queryParams().entrySet()) {
+ for (Object o : entry.getValue()) {
+ uriBuilder.setParameter(entry.getKey(), String.valueOf(o));
+ }
+ }
+
+ uri = uriBuilder.build();
+ } catch (URISyntaxException e) {
+ throw new HttpClientException(e);
+ }
+
+ HttpEntity entity = null;
+ if (request.entity() != null) {
+ // Special handling for streaming input
+ if (request.entity().getEntity() instanceof InputStream) {
+ // Entity is an InputStream
+ entity = new InputStreamEntity((InputStream) request.entity().getEntity());
+ } else {
+ // Assume to be JSON. Flatten the entity to a Json string
+ try {
+ // Get appropriate mapper, based on existence of a root element in Entity class
+ ObjectMapper mapper = getObjectMapper(request.entity().getEntity().getClass());
+
+ String entityJson = mapper.writeValueAsString(request.entity().getEntity());
+ entity = new StringEntity(entityJson, ContentType.create(request.entity().getContentType()));
+
+ logger.debug("Request JSON Body: {}",
+ entityJson.replaceAll("\"password\":\"[^\"]*\"", "\"password\":\"***\""));
+
+ } catch (JsonProcessingException e) {
+ throw new HttpClientException("Json processing error on request entity", e);
+ } catch (IOException e) {
+ throw new HttpClientException("Json IO error on request entity", e);
+ }
+ }
+ }
+
+ // Determine the HttpRequest class based on the method
+ HttpUriRequest httpRequest;
+
+ switch (request.method()) {
+ case POST:
+ HttpPost post = new HttpPost(uri);
+ post.setEntity(entity);
+ httpRequest = post;
+ break;
+
+ case GET:
+ httpRequest = new HttpGet(uri);
+ break;
+
+ case PUT:
+ HttpPut put = new HttpPut(uri);
+ put.setEntity(entity);
+ httpRequest = put;
+ break;
+
+ case DELETE:
+ httpRequest = new HttpDelete(uri);
+ break;
+
+ default:
+ throw new HttpClientException("Unrecognized HTTP Method: " + request.method());
+ }
+
+ for (Entry<String, List<Object>> h : request.headers().entrySet()) {
+ StringBuilder sb = new StringBuilder();
+ for (Object v : h.getValue()) {
+ sb.append(String.valueOf(v));
+ }
+ httpRequest.addHeader(h.getKey(), sb.toString());
+ }
+
+ // Get the Response. But don't get the body entity yet, as this response
+ // will be wrapped in an HttpClientResponse. The HttpClientResponse
+ // buffers the body in constructor, so can close the response here.
+ HttpClientResponse httpClientResponse = null;
+ CloseableHttpResponse httpResponse = null;
+
+ // Catch known HttpClient exceptions, and wrap them in OpenStack Client Exceptions
+ // so calling functions can distinguish. Only RuntimeExceptions are allowed.
+ try {
+ httpResponse = httpClient.execute(httpRequest);
+
+ logger.debug("Response status: {}", httpResponse.getStatusLine().getStatusCode());
+
+ httpClientResponse = new HttpClientResponse(httpResponse);
+
+ int status = httpResponse.getStatusLine().getStatusCode();
+ if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT
+ || status == HttpStatus.SC_ACCEPTED) {
+ return httpClientResponse;
+ }
+ } catch (HttpResponseException e) {
+ // What exactly does this mean? It does not appear to get thrown for
+ // non-2XX responses as documented.
+ throw new CloudifyResponseException(e.getMessage(), e.getStatusCode());
+ } catch (UnknownHostException e) {
+ throw new CloudifyConnectException("Unknown Host: " + e.getMessage());
+ } catch (IOException e) {
+ // Catch all other IOExceptions and throw as OpenStackConnectException
+ throw new CloudifyConnectException(e.getMessage());
+ } catch (Exception e) {
+ // Catchall for anything else, must throw as a RuntimeException
+ logger.error("Client exception", e);
+ throw new RuntimeException("Unexpected client exception", e);
+ } finally {
+ // Have the body. Close the stream
+ if (httpResponse != null)
+ try {
+ httpResponse.close();
+ } catch (IOException e) {
+ logger.debug("Unable to close HTTP Response: " + e);
+ }
+ }
+
+ // Get here on an error response (4XX-5XX)
+ throw new CloudifyResponseException(httpResponse.getStatusLine().getReasonPhrase(),
+ httpResponse.getStatusLine().getStatusCode(), httpClientResponse);
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientException.java b/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientException.java
index eb967af996..6f170baef5 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientException.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientException.java
@@ -21,22 +21,22 @@
package org.onap.so.cloudify.connector.http;
/*
- * Declare a RuntimeException since the Interface does not declare any
- * throwables. Any caught exception will be wrapped in HttpClientException
+ * Declare a RuntimeException since the Interface does not declare any throwables. Any caught exception will be wrapped
+ * in HttpClientException
*/
public class HttpClientException extends RuntimeException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- public HttpClientException (String s) {
- super (s);
- }
-
- public HttpClientException (Exception e) {
- super ("Caught nested exception in HttpClient", e);
- }
-
- public HttpClientException (String s, Exception e) {
- super (s, e);
- }
+ public HttpClientException(String s) {
+ super(s);
+ }
+
+ public HttpClientException(Exception e) {
+ super("Caught nested exception in HttpClient", e);
+ }
+
+ public HttpClientException(String s, Exception e) {
+ super(s, e);
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientRedirectStrategy.java b/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientRedirectStrategy.java
index a7575ff499..b8b4a5b018 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientRedirectStrategy.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientRedirectStrategy.java
@@ -21,7 +21,6 @@
package org.onap.so.cloudify.connector.http;
import java.net.URI;
-
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
@@ -36,15 +35,12 @@ import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.protocol.HttpContext;
/**
- * Custom {@link org.apache.http.client.RedirectStrategy} implementation
- * that automatically redirects all HEAD, GET and DELETE requests.
- * The {@link org.apache.http.client.DefaultRedirectStrategy} only
- * redirects GET and HEAD automatically, per the HTTP specification
- * (POST and PUT typically have bodies and thus cannot be redirected).
+ * Custom {@link org.apache.http.client.RedirectStrategy} implementation that automatically redirects all HEAD, GET and
+ * DELETE requests. The {@link org.apache.http.client.DefaultRedirectStrategy} only redirects GET and HEAD
+ * automatically, per the HTTP specification (POST and PUT typically have bodies and thus cannot be redirected).
*
- * A custom strategy is needed for the Openstack API, which can also send
- * 302 on a DELETE (by name) request, expecting the client to follow the
- * redirect to perform the actual deletion.
+ * A custom strategy is needed for the Openstack API, which can also send 302 on a DELETE (by name) request, expecting
+ * the client to follow the redirect to perform the actual deletion.
*/
@Immutable
public class HttpClientRedirectStrategy extends DefaultRedirectStrategy {
@@ -52,20 +48,16 @@ public class HttpClientRedirectStrategy extends DefaultRedirectStrategy {
/**
* Redirectable methods.
*/
- private static final String[] REDIRECT_METHODS = new String[] {
- HttpGet.METHOD_NAME,
- HttpDelete.METHOD_NAME,
- HttpHead.METHOD_NAME
- };
+ private static final String[] REDIRECT_METHODS =
+ new String[] {HttpGet.METHOD_NAME, HttpDelete.METHOD_NAME, HttpHead.METHOD_NAME};
/**
- * Determine if the request should be redirected.
- * This may not actually be needed, since the REDIRECT_METHODS
- * array has been updated with the DELETE.
+ * Determine if the request should be redirected. This may not actually be needed, since the REDIRECT_METHODS array
+ * has been updated with the DELETE.
*/
@Override
protected boolean isRedirectable(final String method) {
- for (final String m: REDIRECT_METHODS) {
+ for (final String m : REDIRECT_METHODS) {
if (m.equalsIgnoreCase(method)) {
return true;
}
@@ -74,16 +66,13 @@ public class HttpClientRedirectStrategy extends DefaultRedirectStrategy {
}
/**
- * Override the default redirect handling method. As implemented
- * in HttpClient, it does not preserve the method on 301 or 302
- * responses, always redirecting to a GET.
+ * Override the default redirect handling method. As implemented in HttpClient, it does not preserve the method on
+ * 301 or 302 responses, always redirecting to a GET.
*/
@Override
- public HttpUriRequest getRedirect(
- final HttpRequest request,
- final HttpResponse response,
- final HttpContext context) throws ProtocolException {
-
+ public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context)
+ throws ProtocolException {
+
final URI uri = getLocationURI(request, response, context);
final String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
@@ -93,14 +82,14 @@ public class HttpClientRedirectStrategy extends DefaultRedirectStrategy {
} else {
final int status = response.getStatusLine().getStatusCode();
-
- HttpUriRequest newRequest = null;
- if (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_TEMPORARILY) {
+
+ HttpUriRequest newRequest = null;
+ if (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_TEMPORARILY) {
newRequest = RequestBuilder.copy(request).setUri(uri).build();
} else {
- newRequest = new HttpGet(uri);
+ newRequest = new HttpGet(uri);
}
- return newRequest;
+ return newRequest;
}
}
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientResponse.java b/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientResponse.java
index b9e7851c98..a96fdb6b50 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientResponse.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/connector/http/HttpClientResponse.java
@@ -25,11 +25,9 @@ package org.onap.so.cloudify.connector.http;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
-
import org.onap.so.cloudify.base.client.CloudifyResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -40,44 +38,43 @@ import java.util.Map;
public class HttpClientResponse implements CloudifyResponse {
private static Logger logger = LoggerFactory.getLogger(HttpClientResponse.class);
-
+
private HttpResponse response = null;
private String entityBody = null;
- public HttpClientResponse(HttpResponse response)
- {
+ public HttpClientResponse(HttpResponse response) {
this.response = response;
-
+
// Read the body so InputStream can be closed
if (response.getEntity() == null) {
// No body
logger.debug("No Response Body");
return;
}
-
- ByteArrayOutputStream responseBody = new ByteArrayOutputStream();
- try {
- response.getEntity().writeTo(responseBody);
- } catch (IOException e) {
- throw new HttpClientException ("Error Reading Response Body", e);
- }
- entityBody = responseBody.toString();
+
+ ByteArrayOutputStream responseBody = new ByteArrayOutputStream();
+ try {
+ response.getEntity().writeTo(responseBody);
+ } catch (IOException e) {
+ throw new HttpClientException("Error Reading Response Body", e);
+ }
+ entityBody = responseBody.toString();
logger.debug(entityBody);
}
-
+
@Override
- public <T> T getEntity (Class<T> returnType) {
- // Get appropriate mapper, based on existence of a root element
- ObjectMapper mapper = HttpClientConnector.getObjectMapper (returnType);
-
- T resp = null;
- try {
- resp = mapper.readValue(entityBody, returnType);
- } catch (Exception e) {
- throw new HttpClientException ("Caught exception in getEntity", e);
- }
- return resp;
+ public <T> T getEntity(Class<T> returnType) {
+ // Get appropriate mapper, based on existence of a root element
+ ObjectMapper mapper = HttpClientConnector.getObjectMapper(returnType);
+
+ T resp = null;
+ try {
+ resp = mapper.readValue(entityBody, returnType);
+ } catch (Exception e) {
+ throw new HttpClientException("Caught exception in getEntity", e);
+ }
+ return resp;
}
@Override
@@ -87,7 +84,7 @@ public class HttpClientResponse implements CloudifyResponse {
@Override
public InputStream getInputStream() {
- return new ByteArrayInputStream (entityBody.getBytes());
+ return new ByteArrayInputStream(entityBody.getBytes());
}
@Override
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/BlueprintsResource.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/BlueprintsResource.java
index 03c130e4c5..3eae02bcee 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/BlueprintsResource.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/BlueprintsResource.java
@@ -21,7 +21,6 @@
package org.onap.so.cloudify.v3.client;
import java.io.InputStream;
-
import org.onap.so.cloudify.v3.model.Blueprint;
import org.onap.so.cloudify.v3.model.Blueprints;
import org.onap.so.cloudify.base.client.Entity;
@@ -38,15 +37,15 @@ public class BlueprintsResource {
}
/*
- * Upload a blueprint package directly. The blueprint must be a ZIP archive.
- * However, this method will not validate this.
+ * Upload a blueprint package directly. The blueprint must be a ZIP archive. However, this method will not validate
+ * this.
*/
- public UploadBlueprint uploadFromStream (String blueprintId, String mainFileName, InputStream blueprint) {
- return new UploadBlueprint (blueprintId, mainFileName, blueprint, null);
+ public UploadBlueprint uploadFromStream(String blueprintId, String mainFileName, InputStream blueprint) {
+ return new UploadBlueprint(blueprintId, mainFileName, blueprint, null);
}
- public UploadBlueprint uploadFromUrl (String blueprintId, String mainFileName, String blueprintUrl) {
- return new UploadBlueprint (blueprintId, mainFileName, null, blueprintUrl);
+ public UploadBlueprint uploadFromUrl(String blueprintId, String mainFileName, String blueprintUrl) {
+ return new UploadBlueprint(blueprintId, mainFileName, null, blueprintUrl);
}
public ListBlueprints list() {
@@ -68,14 +67,14 @@ public class BlueprintsResource {
public class UploadBlueprint extends CloudifyRequest<Blueprint> {
public UploadBlueprint(String blueprintId, String mainFileName, InputStream blueprint, String blueprintUrl) {
- // Initialize the request elements dynamically.
- // Either a blueprint input stream or a URL will be provided.
- // If a URL is provided, add it to the query string
- // If a Stream is provided, set it as the Entity body
- super(client, HttpMethod.PUT,
- "/api/v3/blueprints/" + blueprintId + "?application_file_name=" + mainFileName + ((blueprintUrl != null) ? "&blueprint_archive=" + blueprintUrl : ""),
- ((blueprint != null) ? Entity.stream(blueprint) : null),
- Blueprint.class);
+ // Initialize the request elements dynamically.
+ // Either a blueprint input stream or a URL will be provided.
+ // If a URL is provided, add it to the query string
+ // If a Stream is provided, set it as the Entity body
+ super(client, HttpMethod.PUT,
+ "/api/v3/blueprints/" + blueprintId + "?application_file_name=" + mainFileName
+ + ((blueprintUrl != null) ? "&blueprint_archive=" + blueprintUrl : ""),
+ ((blueprint != null) ? Entity.stream(blueprint) : null), Blueprint.class);
}
}
@@ -94,10 +93,10 @@ public class BlueprintsResource {
public class ListBlueprints extends CloudifyRequest<Blueprints> {
public ListBlueprints() {
super(client, HttpMethod.GET, "/api/v3/blueprints", null, Blueprints.class);
- }
+ }
}
- // TODO: DownloadBlueprint is not supported, as it needs to return an input stream
- // containing the full blueprint ZIP.
- // For a full client library, this will require returning an open stream as the entity...
+ // TODO: DownloadBlueprint is not supported, as it needs to return an input stream
+ // containing the full blueprint ZIP.
+ // For a full client library, this will require returning an open stream as the entity...
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/Cloudify.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/Cloudify.java
index cd47e1937a..2fdd61ce48 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/Cloudify.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/Cloudify.java
@@ -34,15 +34,11 @@ public class Cloudify extends CloudifyClient {
private final NodeInstancesResource nodeInstances;
private final ExecutionsResource executions;
-/* Not supporting dynamic connectors
- public Cloudify(String endpoint, CloudifyClientConnector connector) {
- super(endpoint, connector);
- deployments = new DeploymentsResource(this);
- blueprints = new BlueprintsResource(this);
- nodeInstances = new NodeInstancesResource(this);
- tokens = new TokensResource(this);
- }
-*/
+ /*
+ * Not supporting dynamic connectors public Cloudify(String endpoint, CloudifyClientConnector connector) {
+ * super(endpoint, connector); deployments = new DeploymentsResource(this); blueprints = new
+ * BlueprintsResource(this); nodeInstances = new NodeInstancesResource(this); tokens = new TokensResource(this); }
+ */
public Cloudify(String endpoint, String tenant) {
super(endpoint, tenant);
deployments = new DeploymentsResource(this);
@@ -53,7 +49,7 @@ public class Cloudify extends CloudifyClient {
}
public Cloudify(String endpoint) {
- super(endpoint);
+ super(endpoint);
deployments = new DeploymentsResource(this);
blueprints = new BlueprintsResource(this);
nodeInstances = new NodeInstancesResource(this);
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/DeploymentsResource.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/DeploymentsResource.java
index 1160bee420..262045a367 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/DeploymentsResource.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/DeploymentsResource.java
@@ -84,7 +84,7 @@ public class DeploymentsResource {
public class ListDeployments extends CloudifyRequest<Deployments> {
public ListDeployments() {
super(client, HttpMethod.GET, "/api/v3/deployments", null, Deployments.class);
- }
+ }
}
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/ExecutionsResource.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/ExecutionsResource.java
index 6057fbba97..51aaea94bb 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/ExecutionsResource.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/ExecutionsResource.java
@@ -42,18 +42,19 @@ public class ExecutionsResource {
return new ListExecutions(null);
}
- public ListExecutions listSorted (String sortBy) {
+ public ListExecutions listSorted(String sortBy) {
return new ListExecutions("?_sort=" + sortBy);
}
-
+
// Return a filtered list.
// The filter parameter should be a query string of filter criteria (without leading "?")
- public ListExecutions listFiltered (String filter, String sortBy) {
- String listParams = "?" + filter;
- if (sortBy != null) listParams += "&_sort=" + sortBy;
+ public ListExecutions listFiltered(String filter, String sortBy) {
+ String listParams = "?" + filter;
+ if (sortBy != null)
+ listParams += "&_sort=" + sortBy;
return new ListExecutions(listParams);
}
-
+
public GetExecution byId(String id) {
return new GetExecution(id);
}
@@ -61,28 +62,29 @@ public class ExecutionsResource {
public StartExecution start(StartExecutionParams params) {
return new StartExecution(params);
}
-
+
public UpdateExecution updateStatus(String id, String status) {
- UpdateExecutionParams params = new UpdateExecutionParams();
- params.setStatus(status);
+ UpdateExecutionParams params = new UpdateExecutionParams();
+ params.setStatus(status);
return new UpdateExecution(id, params);
}
public CancelExecution cancel(String executionId, CancelExecutionParams params) {
return new CancelExecution(executionId, params);
}
-
+
public class GetExecution extends CloudifyRequest<Execution> {
- public GetExecution (String id) {
+ public GetExecution(String id) {
super(client, HttpMethod.GET, "/api/v3/executions/" + id, null, Execution.class);
}
}
public class ListExecutions extends CloudifyRequest<Executions> {
public ListExecutions(String listParams) {
- super(client, HttpMethod.GET, "/api/v3/executions" + ((listParams!=null) ? listParams : ""), null, Executions.class);
- }
+ super(client, HttpMethod.GET, "/api/v3/executions" + ((listParams != null) ? listParams : ""), null,
+ Executions.class);
+ }
}
public class StartExecution extends CloudifyRequest<Execution> {
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/NodeInstancesResource.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/NodeInstancesResource.java
index 801ced6ef7..bc82c77026 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/NodeInstancesResource.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/NodeInstancesResource.java
@@ -50,7 +50,7 @@ public class NodeInstancesResource {
public class GetNodeInstance extends CloudifyRequest<NodeInstance> {
- public GetNodeInstance (String id) {
+ public GetNodeInstance(String id) {
super(client, HttpMethod.GET, "/api/v3/node-instances/" + id, null, NodeInstance.class);
}
}
@@ -58,12 +58,13 @@ public class NodeInstancesResource {
public class ListNodeInstances extends CloudifyRequest<NodeInstances> {
public ListNodeInstances() {
super(client, HttpMethod.GET, "/api/v3/node-instances", null, NodeInstances.class);
- }
+ }
}
public class UpdateNodeInstance extends CloudifyRequest<NodeInstance> {
public UpdateNodeInstance(String nodeInstanceId, UpdateNodeInstanceParams body) {
- super(client, HttpMethod.PATCH, "/api/v3/node-instances/" + nodeInstanceId, Entity.json(body), NodeInstance.class);
+ super(client, HttpMethod.PATCH, "/api/v3/node-instances/" + nodeInstanceId, Entity.json(body),
+ NodeInstance.class);
}
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/TokensResource.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/TokensResource.java
index 3ef2ef2bb9..417d7c6eda 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/TokensResource.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/TokensResource.java
@@ -34,9 +34,8 @@ public class TokensResource {
}
/*
- * Get a new token for a user
- * TODO: User ID/Password logic need to be in the Client.
- * Results of a token query should also be able to add to the Client
+ * Get a new token for a user TODO: User ID/Password logic need to be in the Client. Results of a token query should
+ * also be able to add to the Client
*/
public GetToken token() {
return new GetToken();
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/AzureConfig.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/AzureConfig.java
index 29f2d1a8ce..8fd6b7c9c0 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/AzureConfig.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/AzureConfig.java
@@ -21,55 +21,54 @@
package org.onap.so.cloudify.v3.model;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class AzureConfig implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @JsonProperty("subscription_id")
- String subscriptionId;
+ private static final long serialVersionUID = 1L;
+
+ @JsonProperty("subscription_id")
+ String subscriptionId;
+
+ @JsonProperty("tenant_id")
+ String tenantId;
- @JsonProperty("tenant_id")
- String tenantId;
+ @JsonProperty("client_id")
+ String clientId;
- @JsonProperty("client_id")
- String clientId;
+ @JsonProperty("client_secret")
+ String clientSecret;
- @JsonProperty("client_secret")
- String clientSecret;
+ public String getSubscriptionId() {
+ return subscriptionId;
+ }
- public String getSubscriptionId() {
- return subscriptionId;
- }
+ public void setSubscriptionId(String subscriptionId) {
+ this.subscriptionId = subscriptionId;
+ }
- public void setSubscriptionId(String subscriptionId) {
- this.subscriptionId = subscriptionId;
- }
+ public String getTenantId() {
+ return tenantId;
+ }
- public String getTenantId() {
- return tenantId;
- }
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
- public void setTenantId(String tenantId) {
- this.tenantId = tenantId;
- }
+ public String getClientId() {
+ return clientId;
+ }
- public String getClientId() {
- return clientId;
- }
+ public void setClientId(String clientId) {
+ this.clientId = clientId;
+ }
- public void setClientId(String clientId) {
- this.clientId = clientId;
- }
+ public String getClientSecret() {
+ return clientSecret;
+ }
- public String getClientSecret() {
- return clientSecret;
- }
+ public void setClientSecret(String clientSecret) {
+ this.clientSecret = clientSecret;
+ }
- public void setClientSecret(String clientSecret) {
- this.clientSecret = clientSecret;
- }
-
-} \ No newline at end of file
+}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Blueprint.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Blueprint.java
index ef2a258b9e..873816d121 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Blueprint.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Blueprint.java
@@ -24,23 +24,22 @@ import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
@JsonIgnoreProperties(ignoreUnknown = true)
-//@JsonRootName("blueprint")
+// @JsonRootName("blueprint")
public class Blueprint implements Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = 938604986548763151L;
- @JsonProperty("created_at")
+ /**
+ *
+ */
+ private static final long serialVersionUID = 938604986548763151L;
+
+ @JsonProperty("created_at")
private Date createdAt;
@JsonProperty("description")
@@ -48,19 +47,19 @@ public class Blueprint implements Serializable {
@JsonProperty("id")
private String id;
-
+
@JsonProperty("main_file_name")
private String mainFileName;
-
+
@JsonProperty("plan")
private Map<String, Object> plan = null;
-
+
@JsonProperty("tenant_name")
private String tenantName;
-
+
@JsonProperty("updated_at")
private Date updatedAt;
-
+
public Date getCreatedAt() {
return createdAt;
}
@@ -76,7 +75,7 @@ public class Blueprint implements Serializable {
public void setDescription(String description) {
this.description = description;
}
-
+
public String getId() {
return id;
}
@@ -92,24 +91,24 @@ public class Blueprint implements Serializable {
public void setMainFileName(String mainFileName) {
this.mainFileName = mainFileName;
}
-
+
public Map<String, Object> getPlan() {
- return this.plan;
+ return this.plan;
}
-
+
public void setPlan(Map<String, Object> plan) {
- this.plan = plan;
+ this.plan = plan;
}
public String getTenantName() {
- return tenantName;
- }
+ return tenantName;
+ }
- public void setTenantName(String tenantName) {
- this.tenantName = tenantName;
- }
+ public void setTenantName(String tenantName) {
+ this.tenantName = tenantName;
+ }
- public Date getUpdatedAt() {
+ public Date getUpdatedAt() {
return updatedAt;
}
@@ -118,46 +117,37 @@ public class Blueprint implements Serializable {
}
- /*
- * Return an output as a Json-mapped Object of the provided type.
- * This is useful for json-object outputs.
- */
- public <T> T getMapValue (Map<String,Object> map, String key, Class<T> type)
- {
+ /*
+ * Return an output as a Json-mapped Object of the provided type. This is useful for json-object outputs.
+ */
+ public <T> T getMapValue(Map<String, Object> map, String key, Class<T> type) {
- ObjectMapper mapper = new ObjectMapper();
+ ObjectMapper mapper = new ObjectMapper();
- if (map.containsKey(key)) {
- try {
- String s = mapper.writeValueAsString(map.get(key));
- return (mapper.readValue(s, type));
- }
- catch (IOException e) {
- return null;
- }
- }
- return null;
- }
+ if (map.containsKey(key)) {
+ try {
+ String s = mapper.writeValueAsString(map.get(key));
+ return (mapper.readValue(s, type));
+ } catch (IOException e) {
+ return null;
+ }
+ }
+ return null;
+ }
- @Override
+ @Override
public String toString() {
- return "Deployment{" +
- "id='" + id + '\'' +
- ", description='" + description + '\'' +
- ", createdAt=" + createdAt +
- ", updatedAt=" + updatedAt +
- ", mainFileName='" + mainFileName + '\'' +
- ", tenantName='" + tenantName + '\'' +
- '}';
- }
-
- /* Add a definition of the Cloudify "plan" attribute once we know what it is.
-
- @JsonIgnoreProperties(ignoreUnknown=true)
- public static final class Plan {
- }
-
-*/
-
+ return "Deployment{" + "id='" + id + '\'' + ", description='" + description + '\'' + ", createdAt=" + createdAt
+ + ", updatedAt=" + updatedAt + ", mainFileName='" + mainFileName + '\'' + ", tenantName='" + tenantName
+ + '\'' + '}';
+ }
+
+ /*
+ * Add a definition of the Cloudify "plan" attribute once we know what it is.
+ *
+ * @JsonIgnoreProperties(ignoreUnknown=true) public static final class Plan { }
+ *
+ */
+
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Blueprints.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Blueprints.java
index aa8e2fc28f..aebf1e5daa 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Blueprints.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Blueprints.java
@@ -22,33 +22,32 @@ package org.onap.so.cloudify.v3.model;
import java.io.Serializable;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
-public class Blueprints implements Serializable{
+public class Blueprints implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @JsonProperty("items")
+ private List<Blueprint> items;
- private static final long serialVersionUID = 1L;
+ @JsonProperty("metadata")
+ private Metadata metadata;
- @JsonProperty("items")
- private List<Blueprint> items;
-
- @JsonProperty("metadata")
- private Metadata metadata;
-
- public List<Blueprint> getItems() {
- return items;
- }
+ public List<Blueprint> getItems() {
+ return items;
+ }
- public void setItems(List<Blueprint> items) {
- this.items = items;
- }
+ public void setItems(List<Blueprint> items) {
+ this.items = items;
+ }
- public Metadata getMetadata() {
- return metadata;
- }
+ public Metadata getMetadata() {
+ return metadata;
+ }
- public void setMetadata(Metadata metadata) {
- this.metadata = metadata;
- }
+ public void setMetadata(Metadata metadata) {
+ this.metadata = metadata;
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CancelExecutionParams.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CancelExecutionParams.java
index 4e90d699c7..0fbe1fc33d 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CancelExecutionParams.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CancelExecutionParams.java
@@ -21,33 +21,30 @@
package org.onap.so.cloudify.v3.model;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class CancelExecutionParams implements Serializable {
- private static final long serialVersionUID = 1L;
-
+ private static final long serialVersionUID = 1L;
+
@JsonProperty("action")
private String action;
-
+
public final static String CANCEL_ACTION = "cancel";
public final static String FORCE_CANCEL_ACTION = "force-cancel";
-
+
public String getAction() {
- return action;
- }
+ return action;
+ }
- public void setAction(String action) {
- this.action = action;
- }
+ public void setAction(String action) {
+ this.action = action;
+ }
- @Override
+ @Override
public String toString() {
- return "CancelExecutionParams{" +
- "action='" + action + '\'' +
- '}';
+ return "CancelExecutionParams{" + "action='" + action + '\'' + '}';
}
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CloudifyError.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CloudifyError.java
index 546ae086d8..1638199ce9 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CloudifyError.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CloudifyError.java
@@ -21,54 +21,48 @@
package org.onap.so.cloudify.v3.model;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/**
- * This class represents a generic Cloudify error response body.
- * These responses have a common format:
- * {
- * "message": "<error message>",
- * "error_code": "<cloudify error id string>".
- * "server_traceback": "<Python traceback>"
- * }
+ * This class represents a generic Cloudify error response body. These responses have a common format: { "message":
+ * "<error message>", "error_code": "<cloudify error id string>". "server_traceback": "<Python traceback>" }
*
* @author jc1348
*/
public class CloudifyError implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @JsonProperty("message")
- private String message;
-
- @JsonProperty("error_code")
- private String errorCode;
-
- @JsonProperty("server_traceback")
- private String serverTraceback;
-
- public String getMessage() {
- return message;
- }
+ private static final long serialVersionUID = 1L;
+
+ @JsonProperty("message")
+ private String message;
+
+ @JsonProperty("error_code")
+ private String errorCode;
+
+ @JsonProperty("server_traceback")
+ private String serverTraceback;
+
+ public String getMessage() {
+ return message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public String getErrorCode() {
- return errorCode;
- }
+ public String getErrorCode() {
+ return errorCode;
+ }
- public void setErrorCode(String errorCode) {
- this.errorCode = errorCode;
- }
+ public void setErrorCode(String errorCode) {
+ this.errorCode = errorCode;
+ }
- public String getServerTraceback() {
- return serverTraceback;
- }
+ public String getServerTraceback() {
+ return serverTraceback;
+ }
- public void setServerTraceback(String serverTraceback) {
- this.serverTraceback = serverTraceback;
- }
+ public void setServerTraceback(String serverTraceback) {
+ this.serverTraceback = serverTraceback;
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CreateDeploymentParams.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CreateDeploymentParams.java
index 10b1854d81..66e9b61d27 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CreateDeploymentParams.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CreateDeploymentParams.java
@@ -21,42 +21,38 @@
package org.onap.so.cloudify.v3.model;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import java.io.Serializable;
import java.util.Map;
public class CreateDeploymentParams implements Serializable {
- private static final long serialVersionUID = 1L;
-
+ private static final long serialVersionUID = 1L;
+
@JsonProperty("blueprint_id")
private String blueprintId;
@JsonProperty("inputs")
private Map<String, Object> inputs;
- public String getBlueprintId() {
- return blueprintId;
- }
+ public String getBlueprintId() {
+ return blueprintId;
+ }
- public void setBlueprintId(String blueprintId) {
- this.blueprintId = blueprintId;
- }
+ public void setBlueprintId(String blueprintId) {
+ this.blueprintId = blueprintId;
+ }
- public Map<String, Object> getInputs() {
- return inputs;
- }
+ public Map<String, Object> getInputs() {
+ return inputs;
+ }
- public void setInputs(Map<String, Object> inputs) {
- this.inputs = inputs;
- }
+ public void setInputs(Map<String, Object> inputs) {
+ this.inputs = inputs;
+ }
@Override
public String toString() {
- return "CreateDeploymentBody{" +
- "blueprintId='" + blueprintId + '\'' +
- ", inputs=" + inputs +
- '}';
+ return "CreateDeploymentBody{" + "blueprintId='" + blueprintId + '\'' + ", inputs=" + inputs + '}';
}
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Deployment.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Deployment.java
index 9bb3107798..811cdc7333 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Deployment.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Deployment.java
@@ -25,18 +25,17 @@ import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
@JsonIgnoreProperties(ignoreUnknown = true)
-//@JsonRootName("deployment")
+// @JsonRootName("deployment")
public class Deployment implements Serializable {
- private static final long serialVersionUID = 1L;
-
+ private static final long serialVersionUID = 1L;
+
@JsonProperty("blueprint_id")
private String blueprintId;
@@ -51,13 +50,13 @@ public class Deployment implements Serializable {
@JsonProperty("groups")
private Map<String, Group> groups = null;
-
+
@JsonProperty("id")
private String id;
-
+
@JsonProperty("inputs")
private Map<String, Object> inputs = null;
-
+
// TODO: Expand the definition of a PolicyTrigger
@JsonProperty("policy_triggers")
private List<Object> policyTriggers;
@@ -68,7 +67,7 @@ public class Deployment implements Serializable {
@JsonProperty("scaling_groups")
private Map<String, ScalingGroup> scalingGroups = null;
-
+
@JsonProperty("tenant_name")
private String tenantName;
@@ -77,31 +76,31 @@ public class Deployment implements Serializable {
@JsonProperty("workflows")
private List<Workflow> workflows;
-
+
public List<Object> getPolicyTriggers() {
- return policyTriggers;
- }
+ return policyTriggers;
+ }
- public void setPolicyTriggers(List<Object> policyTriggers) {
- this.policyTriggers = policyTriggers;
- }
+ public void setPolicyTriggers(List<Object> policyTriggers) {
+ this.policyTriggers = policyTriggers;
+ }
- public List<Object> getPolicyTypes() {
- return policyTypes;
- }
+ public List<Object> getPolicyTypes() {
+ return policyTypes;
+ }
- public void setPolicyTypes(List<Object> policyTypes) {
- this.policyTypes = policyTypes;
- }
+ public void setPolicyTypes(List<Object> policyTypes) {
+ this.policyTypes = policyTypes;
+ }
- public String getBlueprintId() {
+ public String getBlueprintId() {
return blueprintId;
}
public void setBlueprintId(String blueprintId) {
this.blueprintId = blueprintId;
}
-
+
public Date getCreatedAt() {
return createdAt;
}
@@ -125,13 +124,13 @@ public class Deployment implements Serializable {
public void setDescription(String description) {
this.description = description;
}
-
+
public Map<String, Group> getGroups() {
- return this.groups;
+ return this.groups;
}
-
+
public void setGroups(Map<String, Group> groups) {
- this.groups = groups;
+ this.groups = groups;
}
public String getId() {
@@ -143,10 +142,11 @@ public class Deployment implements Serializable {
}
public Map<String, Object> getInputs() {
- return this.inputs;
+ return this.inputs;
}
+
public void setInputs(Map<String, Object> inputs) {
- this.inputs = inputs;
+ this.inputs = inputs;
}
public String getTenantName() {
@@ -158,14 +158,14 @@ public class Deployment implements Serializable {
}
public Map<String, ScalingGroup> getScalingGroups() {
- return scalingGroups;
- }
+ return scalingGroups;
+ }
- public void setScalingGroups(Map<String, ScalingGroup> scalingGroups) {
- this.scalingGroups = scalingGroups;
- }
+ public void setScalingGroups(Map<String, ScalingGroup> scalingGroups) {
+ this.scalingGroups = scalingGroups;
+ }
- public Date getUpdatedAt() {
+ public Date getUpdatedAt() {
return updatedAt;
}
@@ -185,181 +185,175 @@ public class Deployment implements Serializable {
* Nested subclasses for Group definitions
*/
public static final class Group {
- @JsonProperty ("policies")
- Object policies;
-
- @JsonProperty("members")
- List<String> members;
+ @JsonProperty("policies")
+ Object policies;
+
+ @JsonProperty("members")
+ List<String> members;
- public Object getPolicies() {
- return policies;
- }
+ public Object getPolicies() {
+ return policies;
+ }
- public void setPolicies(Object policies) {
- this.policies = policies;
- }
+ public void setPolicies(Object policies) {
+ this.policies = policies;
+ }
- public List<String> getMembers() {
- return members;
- }
+ public List<String> getMembers() {
+ return members;
+ }
- public void setMembers(List<String> members) {
- this.members = members;
- }
+ public void setMembers(List<String> members) {
+ this.members = members;
+ }
}
/*
* Nested subclasses for Scaling Group definitions
*/
public static final class ScalingGroup {
- @JsonProperty ("properties")
- ScalingGroupProperties properties;
-
- @JsonProperty("members")
- List<String> members;
+ @JsonProperty("properties")
+ ScalingGroupProperties properties;
+
+ @JsonProperty("members")
+ List<String> members;
- public ScalingGroupProperties getProperties() {
- return properties;
- }
+ public ScalingGroupProperties getProperties() {
+ return properties;
+ }
- public void setProperties(ScalingGroupProperties properties) {
- this.properties = properties;
- }
+ public void setProperties(ScalingGroupProperties properties) {
+ this.properties = properties;
+ }
- public List<String> getMembers() {
- return members;
- }
+ public List<String> getMembers() {
+ return members;
+ }
- public void setMembers(List<String> members) {
- this.members = members;
- }
+ public void setMembers(List<String> members) {
+ this.members = members;
+ }
}
public static final class ScalingGroupProperties {
- @JsonProperty("current_instances")
- int currentInstances;
-
- @JsonProperty("default_instances")
- int defaultInstances;
-
- @JsonProperty("max_instances")
- int maxInstances;
-
- @JsonProperty("min_instances")
- int minInstances;
-
- @JsonProperty("planned_instances")
- int plannedInstances;
-
- public int getCurrentInstances() {
- return currentInstances;
- }
-
- public void setCurrentInstances(int currentInstances) {
- this.currentInstances = currentInstances;
- }
-
- public int getDefaultInstances() {
- return defaultInstances;
- }
-
- public void setDefaultInstances(int defaultInstances) {
- this.defaultInstances = defaultInstances;
- }
-
- public int getMaxInstances() {
- return maxInstances;
- }
-
- public void setMaxInstances(int maxInstances) {
- this.maxInstances = maxInstances;
- }
-
- public int getMinInstances() {
- return minInstances;
- }
-
- public void setMinInstances(int minInstances) {
- this.minInstances = minInstances;
- }
-
- public int getPlannedInstances() {
- return plannedInstances;
- }
-
- public void setPlannedInstances(int plannedInstances) {
- this.plannedInstances = plannedInstances;
- }
- }
-
+ @JsonProperty("current_instances")
+ int currentInstances;
+
+ @JsonProperty("default_instances")
+ int defaultInstances;
+
+ @JsonProperty("max_instances")
+ int maxInstances;
+
+ @JsonProperty("min_instances")
+ int minInstances;
+
+ @JsonProperty("planned_instances")
+ int plannedInstances;
+
+ public int getCurrentInstances() {
+ return currentInstances;
+ }
+
+ public void setCurrentInstances(int currentInstances) {
+ this.currentInstances = currentInstances;
+ }
+
+ public int getDefaultInstances() {
+ return defaultInstances;
+ }
+
+ public void setDefaultInstances(int defaultInstances) {
+ this.defaultInstances = defaultInstances;
+ }
+
+ public int getMaxInstances() {
+ return maxInstances;
+ }
+
+ public void setMaxInstances(int maxInstances) {
+ this.maxInstances = maxInstances;
+ }
+
+ public int getMinInstances() {
+ return minInstances;
+ }
+
+ public void setMinInstances(int minInstances) {
+ this.minInstances = minInstances;
+ }
+
+ public int getPlannedInstances() {
+ return plannedInstances;
+ }
+
+ public void setPlannedInstances(int plannedInstances) {
+ this.plannedInstances = plannedInstances;
+ }
+ }
+
/*
- * Nested subclass for Deployment Workflow entities.
- * Note that Blueprint class also contains a slightly different Workflow structure.
+ * Nested subclass for Deployment Workflow entities. Note that Blueprint class also contains a slightly different
+ * Workflow structure.
*/
public static final class Workflow {
- @JsonProperty("name")
- private String name;
- @JsonProperty("created_at")
- private Date createdAt;
- @JsonProperty("parameters")
- private Map<String,ParameterDefinition> parameters;
-
- public Workflow() {}
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Date getCreatedAt() {
- return createdAt;
- }
- public void setCreatedAt(Date createdAt) {
- this.createdAt = createdAt;
- }
- public Map<String, ParameterDefinition> getParameters() {
- return parameters;
- }
- public void setParameters(Map<String, ParameterDefinition> parameters) {
- this.parameters = parameters;
- }
- }
-
- /*
- * Return an output as a Json-mapped Object of the provided type.
- * This is useful for json-object outputs.
- */
- public <T> T getMapValue (Map<String,Object> map, String key, Class<T> type)
- {
-
- ObjectMapper mapper = new ObjectMapper();
- if (map.containsKey(key)) {
- try {
- String s = mapper.writeValueAsString(map.get(key));
- return (mapper.readValue(s, type));
- }
- catch (IOException e) {
- return null;
- }
- }
- return null;
- }
-
- @Override
+ @JsonProperty("name")
+ private String name;
+ @JsonProperty("created_at")
+ private Date createdAt;
+ @JsonProperty("parameters")
+ private Map<String, ParameterDefinition> parameters;
+
+ public Workflow() {}
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Date getCreatedAt() {
+ return createdAt;
+ }
+
+ public void setCreatedAt(Date createdAt) {
+ this.createdAt = createdAt;
+ }
+
+ public Map<String, ParameterDefinition> getParameters() {
+ return parameters;
+ }
+
+ public void setParameters(Map<String, ParameterDefinition> parameters) {
+ this.parameters = parameters;
+ }
+ }
+
+ /*
+ * Return an output as a Json-mapped Object of the provided type. This is useful for json-object outputs.
+ */
+ public <T> T getMapValue(Map<String, Object> map, String key, Class<T> type) {
+
+ ObjectMapper mapper = new ObjectMapper();
+ if (map.containsKey(key)) {
+ try {
+ String s = mapper.writeValueAsString(map.get(key));
+ return (mapper.readValue(s, type));
+ } catch (IOException e) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ @Override
public String toString() {
- return "Deployment{" +
- "id='" + id + '\'' +
- ", description='" + description + '\'' +
- ", blueprintId='" + blueprintId + '\'' +
- ", createdBy='" + createdBy + '\'' +
- ", tenantName='" + tenantName + '\'' +
- ", createdAt=" + createdAt +
- ", updatedAt=" + updatedAt +
- ", inputs='" + inputs + '\'' +
- ", workflows=" + workflows +
- ", groups=" + groups +
- '}';
+ return "Deployment{" + "id='" + id + '\'' + ", description='" + description + '\'' + ", blueprintId='"
+ + blueprintId + '\'' + ", createdBy='" + createdBy + '\'' + ", tenantName='" + tenantName + '\''
+ + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + ", inputs='" + inputs + '\''
+ + ", workflows=" + workflows + ", groups=" + groups + '}';
}
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/DeploymentOutputs.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/DeploymentOutputs.java
index d34195cfd7..5d828720b0 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/DeploymentOutputs.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/DeploymentOutputs.java
@@ -23,65 +23,60 @@ package org.onap.so.cloudify.v3.model;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
@JsonIgnoreProperties(ignoreUnknown = true)
-//@JsonRootName("outputs")
+// @JsonRootName("outputs")
public class DeploymentOutputs implements Serializable {
- private static final long serialVersionUID = 1L;
-
+ private static final long serialVersionUID = 1L;
+
@JsonProperty("deployment_id")
private String deploymentId;
-
+
@JsonProperty("outputs")
private Map<String, Object> outputs = null;
-
+
public Map<String, Object> getOutputs() {
- return this.outputs;
+ return this.outputs;
}
+
public void setOutputs(Map<String, Object> outputs) {
- this.outputs = outputs;
+ this.outputs = outputs;
+ }
+
+ public String getDeploymentId() {
+ return deploymentId;
+ }
+
+ public void setDeploymentId(String deploymentId) {
+ this.deploymentId = deploymentId;
}
-
- public String getDeploymentId() {
- return deploymentId;
- }
- public void setDeploymentId(String deploymentId) {
- this.deploymentId = deploymentId;
- }
-
- /*
- * Return an output as a Json-mapped Object of the provided type.
- * This is useful for json-object outputs.
- */
- public <T> T getMapValue (Map<String,Object> map, String key, Class<T> type)
- {
-
- ObjectMapper mapper = new ObjectMapper();
- if (map.containsKey(key)) {
- try {
- String s = mapper.writeValueAsString(map.get(key));
- return (mapper.readValue(s, type));
- }
- catch (IOException e) {
- return null;
- }
- }
- return null;
- }
+ /*
+ * Return an output as a Json-mapped Object of the provided type. This is useful for json-object outputs.
+ */
+ public <T> T getMapValue(Map<String, Object> map, String key, Class<T> type) {
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ if (map.containsKey(key)) {
+ try {
+ String s = mapper.writeValueAsString(map.get(key));
+ return (mapper.readValue(s, type));
+ } catch (IOException e) {
+ return null;
+ }
+ }
+ return null;
+ }
- @Override
+ @Override
public String toString() {
- return "DeploymentOutputs{" +
- "deploymentId='" + deploymentId + '\'' +
- ", outputs='" + outputs + '\'' +
- '}';
+ return "DeploymentOutputs{" + "deploymentId='" + deploymentId + '\'' + ", outputs='" + outputs + '\'' + '}';
}
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Deployments.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Deployments.java
index f5019a74e9..b97164f528 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Deployments.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Deployments.java
@@ -21,34 +21,33 @@
package org.onap.so.cloudify.v3.model;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import java.io.Serializable;
import java.util.List;
public class Deployments implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @JsonProperty("items")
- private List<Deployment> items;
-
- @JsonProperty("metadata")
- private Metadata metadata;
-
- public List<Deployment> getItems() {
- return items;
- }
-
- public void setItems(List<Deployment> items) {
- this.items = items;
- }
-
- public Metadata getMetadata() {
- return metadata;
- }
-
- public void setMetadata(Metadata metadata) {
- this.metadata = metadata;
- }
+ private static final long serialVersionUID = 1L;
+
+ @JsonProperty("items")
+ private List<Deployment> items;
+
+ @JsonProperty("metadata")
+ private Metadata metadata;
+
+ public List<Deployment> getItems() {
+ return items;
+ }
+
+ public void setItems(List<Deployment> items) {
+ this.items = items;
+ }
+
+ public Metadata getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(Metadata metadata) {
+ this.metadata = metadata;
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Execution.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Execution.java
index 73510ceeb0..258d8e525a 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Execution.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Execution.java
@@ -23,7 +23,6 @@ package org.onap.so.cloudify.v3.model;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,8 +30,8 @@ import com.fasterxml.jackson.annotation.JsonProperty;
// @JsonRootName("execution")
public class Execution implements Serializable {
- private static final long serialVersionUID = 1L;
-
+ private static final long serialVersionUID = 1L;
+
@JsonProperty("blueprint_id")
private String blueprintId;
@@ -47,127 +46,119 @@ public class Execution implements Serializable {
@JsonProperty("error")
private String error;
-
+
@JsonProperty("id")
private String id;
-
+
@JsonProperty("is_system_workflow")
private boolean isSystemWorkflow;
-
+
@JsonProperty("parameters")
private Map<String, Object> parameters;
-
+
@JsonProperty("status")
private String status;
-
+
@JsonProperty("tenant_name")
private String tenantName;
-
+
@JsonProperty("workflow_id")
private String workflowId;
- public String getBlueprintId() {
- return blueprintId;
- }
+ public String getBlueprintId() {
+ return blueprintId;
+ }
- public void setBlueprintId(String blueprintId) {
- this.blueprintId = blueprintId;
- }
+ public void setBlueprintId(String blueprintId) {
+ this.blueprintId = blueprintId;
+ }
- public Date getCreatedAt() {
- return createdAt;
- }
+ public Date getCreatedAt() {
+ return createdAt;
+ }
- public void setCreatedAt(Date createdAt) {
- this.createdAt = createdAt;
- }
+ public void setCreatedAt(Date createdAt) {
+ this.createdAt = createdAt;
+ }
- public String getCreatedBy() {
- return createdBy;
- }
+ public String getCreatedBy() {
+ return createdBy;
+ }
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
+ public void setCreatedBy(String createdBy) {
+ this.createdBy = createdBy;
+ }
- public String getDeploymentId() {
- return deploymentId;
- }
+ public String getDeploymentId() {
+ return deploymentId;
+ }
- public void setDeploymentId(String deploymentId) {
- this.deploymentId = deploymentId;
- }
+ public void setDeploymentId(String deploymentId) {
+ this.deploymentId = deploymentId;
+ }
- public String getError() {
- return error;
- }
+ public String getError() {
+ return error;
+ }
- public void setError(String error) {
- this.error = error;
- }
+ public void setError(String error) {
+ this.error = error;
+ }
- public String getId() {
- return id;
- }
+ public String getId() {
+ return id;
+ }
- public void setId(String id) {
- this.id = id;
- }
+ public void setId(String id) {
+ this.id = id;
+ }
- public boolean isSystemWorkflow() {
- return isSystemWorkflow;
- }
+ public boolean isSystemWorkflow() {
+ return isSystemWorkflow;
+ }
- public void setSystemWorkflow(boolean isSystemWorkflow) {
- this.isSystemWorkflow = isSystemWorkflow;
- }
+ public void setSystemWorkflow(boolean isSystemWorkflow) {
+ this.isSystemWorkflow = isSystemWorkflow;
+ }
- public Map<String, Object> getParameters() {
- return parameters;
- }
+ public Map<String, Object> getParameters() {
+ return parameters;
+ }
- public void setParameters(Map<String, Object> parameters) {
- this.parameters = parameters;
- }
+ public void setParameters(Map<String, Object> parameters) {
+ this.parameters = parameters;
+ }
- public String getStatus() {
- return status;
- }
+ public String getStatus() {
+ return status;
+ }
- public void setStatus(String status) {
- this.status = status;
- }
+ public void setStatus(String status) {
+ this.status = status;
+ }
- public String getTenantName() {
- return tenantName;
- }
+ public String getTenantName() {
+ return tenantName;
+ }
- public void setTenantName(String tenantName) {
- this.tenantName = tenantName;
- }
+ public void setTenantName(String tenantName) {
+ this.tenantName = tenantName;
+ }
- public String getWorkflowId() {
- return workflowId;
- }
+ public String getWorkflowId() {
+ return workflowId;
+ }
- public void setWorkflowId(String workflowId) {
- this.workflowId = workflowId;
- }
+ public void setWorkflowId(String workflowId) {
+ this.workflowId = workflowId;
+ }
- @Override
+ @Override
public String toString() {
- return "Execution{" +
- "id='" + id + '\'' +
- ", blueprintId='" + blueprintId + '\'' +
- ", createdBy='" + createdBy + '\'' +
- ", createdAt=" + createdAt +
- ", deploymentId='" + deploymentId + '\'' +
- ", error=" + error +
- ", isSystemWorkflow=" + isSystemWorkflow +
- ", status=" + status +
- ", tenantName='" + tenantName + '\'' +
- ", parameters=" + parameters +
- '}';
+ return "Execution{" + "id='" + id + '\'' + ", blueprintId='" + blueprintId + '\'' + ", createdBy='" + createdBy
+ + '\'' + ", createdAt=" + createdAt + ", deploymentId='" + deploymentId + '\'' + ", error=" + error
+ + ", isSystemWorkflow=" + isSystemWorkflow + ", status=" + status + ", tenantName='" + tenantName + '\''
+ + ", parameters=" + parameters + '}';
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Executions.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Executions.java
index 2095f8acd9..e238bc7fee 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Executions.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Executions.java
@@ -21,34 +21,33 @@
package org.onap.so.cloudify.v3.model;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import java.io.Serializable;
import java.util.List;
public class Executions implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @JsonProperty("items")
- private List<Execution> items;
-
- @JsonProperty("metadata")
- private Metadata metadata;
-
- public List<Execution> getItems() {
- return items;
- }
-
- public void setItems(List<Execution> items) {
- this.items = items;
- }
-
- public Metadata getMetadata() {
- return metadata;
- }
-
- public void setMetadata(Metadata metadata) {
- this.metadata = metadata;
- }
+ private static final long serialVersionUID = 1L;
+
+ @JsonProperty("items")
+ private List<Execution> items;
+
+ @JsonProperty("metadata")
+ private Metadata metadata;
+
+ public List<Execution> getItems() {
+ return items;
+ }
+
+ public void setItems(List<Execution> items) {
+ this.items = items;
+ }
+
+ public Metadata getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(Metadata metadata) {
+ this.metadata = metadata;
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Metadata.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Metadata.java
index 6ae895b30d..269ed9db8a 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Metadata.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Metadata.java
@@ -21,37 +21,29 @@
package org.onap.so.cloudify.v3.model;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import java.io.Serializable;
/**
- * This class represents a generic Cloudify response to a GET command.
- * These responses have a common format:
- * {
- * "items": [
- * List of objects of the requested type
- * ],
- * "metadata": {
- * }
- * }
+ * This class represents a generic Cloudify response to a GET command. These responses have a common format: { "items":
+ * [ List of objects of the requested type ], "metadata": { } }
*
* @author jc1348
*
*/
public class Metadata implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @JsonProperty("pagination")
- private Pagination pagination;
-
+ private static final long serialVersionUID = 1L;
+
+ @JsonProperty("pagination")
+ private Pagination pagination;
+
- public Pagination getPagination() {
- return pagination;
- }
+ public Pagination getPagination() {
+ return pagination;
+ }
- public void setPagination(Pagination pagination) {
- this.pagination = pagination;
- }
+ public void setPagination(Pagination pagination) {
+ this.pagination = pagination;
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/NodeInstance.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/NodeInstance.java
index ec597b77a4..4d7f8fb749 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/NodeInstance.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/NodeInstance.java
@@ -23,7 +23,6 @@ package org.onap.so.cloudify.v3.model;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -32,9 +31,9 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("node_instance")
public class NodeInstance implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @JsonProperty("created_by")
+ private static final long serialVersionUID = 1L;
+
+ @JsonProperty("created_by")
private String createdBy;
@JsonProperty("deployment_id")
@@ -45,19 +44,19 @@ public class NodeInstance implements Serializable {
@JsonProperty("id")
private String id;
-
+
@JsonProperty("node_id")
private String nodeId;
-
+
@JsonProperty("relationships")
private List<Object> relationships = null;
-
+
@JsonProperty("runtime_properties")
private Map<String, Object> runtimeProperties = null;
-
+
@JsonProperty("scaling_groups")
private List<ScalingGroupIdentifier> scalingGroups;
-
+
@JsonProperty("state")
private String state;
@@ -67,139 +66,132 @@ public class NodeInstance implements Serializable {
@JsonProperty("version")
private String version;
- public String getCreatedBy() {
- return createdBy;
- }
-
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
-
- public String getDeploymentId() {
- return deploymentId;
- }
-
- public void setDeploymentId(String deploymentId) {
- this.deploymentId = deploymentId;
- }
-
- public String getHostId() {
- return hostId;
- }
-
- public void setHostId(String hostId) {
- this.hostId = hostId;
- }
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- public String getNodeId() {
- return nodeId;
- }
-
- public void setNodeId(String nodeId) {
- this.nodeId = nodeId;
- }
-
- public List<Object> getRelationships() {
- return relationships;
- }
-
- public void setRelationships(List<Object> relationships) {
- this.relationships = relationships;
- }
-
- public Map<String, Object> getRuntimeProperties() {
- return runtimeProperties;
- }
-
- public void setRuntimeProperties(Map<String, Object> runtimeProperties) {
- this.runtimeProperties = runtimeProperties;
- }
-
- public List<ScalingGroupIdentifier> getScalingGroups() {
- return scalingGroups;
- }
-
- public void setScalingGroups(List<ScalingGroupIdentifier> scalingGroups) {
- this.scalingGroups = scalingGroups;
- }
-
- public String getState() {
- return state;
- }
-
- public void setState(String state) {
- this.state = state;
- }
-
- public String getTenantName() {
- return tenantName;
- }
-
- public void setTenantName(String tenantName) {
- this.tenantName = tenantName;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
- /*
- * Nested structure representing scaling groups in which this node is a member
- */
- public static final class ScalingGroupIdentifier
- {
- @JsonProperty("name")
- private String name;
-
- @JsonProperty("id")
- private String id;
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
-
- public String toString() {
- return "Scaling Group{ name=" + name + ", id=" + id + "}";
- }
- }
-
- @Override
+ public String getCreatedBy() {
+ return createdBy;
+ }
+
+ public void setCreatedBy(String createdBy) {
+ this.createdBy = createdBy;
+ }
+
+ public String getDeploymentId() {
+ return deploymentId;
+ }
+
+ public void setDeploymentId(String deploymentId) {
+ this.deploymentId = deploymentId;
+ }
+
+ public String getHostId() {
+ return hostId;
+ }
+
+ public void setHostId(String hostId) {
+ this.hostId = hostId;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getNodeId() {
+ return nodeId;
+ }
+
+ public void setNodeId(String nodeId) {
+ this.nodeId = nodeId;
+ }
+
+ public List<Object> getRelationships() {
+ return relationships;
+ }
+
+ public void setRelationships(List<Object> relationships) {
+ this.relationships = relationships;
+ }
+
+ public Map<String, Object> getRuntimeProperties() {
+ return runtimeProperties;
+ }
+
+ public void setRuntimeProperties(Map<String, Object> runtimeProperties) {
+ this.runtimeProperties = runtimeProperties;
+ }
+
+ public List<ScalingGroupIdentifier> getScalingGroups() {
+ return scalingGroups;
+ }
+
+ public void setScalingGroups(List<ScalingGroupIdentifier> scalingGroups) {
+ this.scalingGroups = scalingGroups;
+ }
+
+ public String getState() {
+ return state;
+ }
+
+ public void setState(String state) {
+ this.state = state;
+ }
+
+ public String getTenantName() {
+ return tenantName;
+ }
+
+ public void setTenantName(String tenantName) {
+ this.tenantName = tenantName;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ /*
+ * Nested structure representing scaling groups in which this node is a member
+ */
+ public static final class ScalingGroupIdentifier {
+ @JsonProperty("name")
+ private String name;
+
+ @JsonProperty("id")
+ private String id;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String toString() {
+ return "Scaling Group{ name=" + name + ", id=" + id + "}";
+ }
+ }
+
+ @Override
public String toString() {
- return "Deployment{" +
- "id='" + id + '\'' +
- "nodeId='" + nodeId + '\'' +
- ", createdBy='" + createdBy + '\'' +
- ", tenantName='" + tenantName + '\'' +
- ", state=" + state +
- ", deploymentId=" + deploymentId +
- ", hostId='" + hostId + '\'' +
- ", version='" + version + '\'' +
- ", relationships=" + relationships +
- ", runtimeProperties=" + runtimeProperties +
- ", scalingGroups=" + scalingGroups +
- '}';
- }
-
- // TODO: Need an object structure for Relationships
+ return "Deployment{" + "id='" + id + '\'' + "nodeId='" + nodeId + '\'' + ", createdBy='" + createdBy + '\''
+ + ", tenantName='" + tenantName + '\'' + ", state=" + state + ", deploymentId=" + deploymentId
+ + ", hostId='" + hostId + '\'' + ", version='" + version + '\'' + ", relationships=" + relationships
+ + ", runtimeProperties=" + runtimeProperties + ", scalingGroups=" + scalingGroups + '}';
+ }
+
+ // TODO: Need an object structure for Relationships
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/NodeInstances.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/NodeInstances.java
index ddaa209b75..8dd30d9696 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/NodeInstances.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/NodeInstances.java
@@ -21,34 +21,33 @@
package org.onap.so.cloudify.v3.model;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import java.io.Serializable;
import java.util.List;
-public class NodeInstances implements Serializable{
+public class NodeInstances implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @JsonProperty("items")
+ private List<NodeInstance> items;
- private static final long serialVersionUID = 1L;
+ @JsonProperty("metadata")
+ private Metadata metadata;
- @JsonProperty("items")
- private List<NodeInstance> items;
-
- @JsonProperty("metadata")
- private Metadata metadata;
-
- public List<NodeInstance> getItems() {
- return items;
- }
+ public List<NodeInstance> getItems() {
+ return items;
+ }
- public void setItems(List<NodeInstance> items) {
- this.items = items;
- }
+ public void setItems(List<NodeInstance> items) {
+ this.items = items;
+ }
- public Metadata getMetadata() {
- return metadata;
- }
+ public Metadata getMetadata() {
+ return metadata;
+ }
- public void setMetadata(Metadata metadata) {
- this.metadata = metadata;
- }
+ public void setMetadata(Metadata metadata) {
+ this.metadata = metadata;
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/OpenstackConfig.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/OpenstackConfig.java
index 03ab1f194c..8914a83a55 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/OpenstackConfig.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/OpenstackConfig.java
@@ -21,69 +21,68 @@
package org.onap.so.cloudify.v3.model;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class OpenstackConfig implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @JsonProperty("username")
- String username;
+ private static final long serialVersionUID = 1L;
+
+ @JsonProperty("username")
+ String username;
+
+ @JsonProperty("password")
+ String password;
- @JsonProperty("password")
- String password;
+ @JsonProperty("tenant_name")
+ String tenantName;
- @JsonProperty("tenant_name")
- String tenantName;
+ @JsonProperty("auth_url")
+ String authUrl;
- @JsonProperty("auth_url")
- String authUrl;
+ @JsonProperty("region")
+ String region;
- @JsonProperty("region")
- String region;
+ // NOTE: Not supporting "custom_configuration"
- // NOTE: Not supporting "custom_configuration"
+ public String getUsername() {
+ return username;
+ }
- public String getUsername() {
- return username;
- }
+ public void setUsername(String username) {
+ this.username = username;
+ }
- public void setUsername(String username) {
- this.username = username;
- }
+ public String getPassword() {
+ return password;
+ }
- public String getPassword() {
- return password;
- }
+ public void setPassword(String password) {
+ this.password = password;
+ }
- public void setPassword(String password) {
- this.password = password;
- }
+ public String getTenantName() {
+ return tenantName;
+ }
- public String getTenantName() {
- return tenantName;
- }
+ public void setTenantName(String tenantName) {
+ this.tenantName = tenantName;
+ }
- public void setTenantName(String tenantName) {
- this.tenantName = tenantName;
- }
+ public String getAuthUrl() {
+ return authUrl;
+ }
- public String getAuthUrl() {
- return authUrl;
- }
+ public void setAuthUrl(String authUrl) {
+ this.authUrl = authUrl;
+ }
- public void setAuthUrl(String authUrl) {
- this.authUrl = authUrl;
- }
+ public String getRegion() {
+ return region;
+ }
- public String getRegion() {
- return region;
- }
+ public void setRegion(String region) {
+ this.region = region;
+ }
- public void setRegion(String region) {
- this.region = region;
- }
-
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Pagination.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Pagination.java
index 547c437b75..a292b13881 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Pagination.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Pagination.java
@@ -23,29 +23,34 @@ package org.onap.so.cloudify.v3.model;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Pagination {
- @JsonProperty("total")
- private int total;
- @JsonProperty("offset")
- private int offset;
- @JsonProperty("size")
- private int size;
-
- public int getTotal() {
- return total;
- }
- public void setTotal(int total) {
- this.total = total;
- }
- public int getOffset() {
- return offset;
- }
- public void setOffset(int offset) {
- this.offset = offset;
- }
- public int getSize() {
- return size;
- }
- public void setSize(int size) {
- this.size = size;
- }
+ @JsonProperty("total")
+ private int total;
+ @JsonProperty("offset")
+ private int offset;
+ @JsonProperty("size")
+ private int size;
+
+ public int getTotal() {
+ return total;
+ }
+
+ public void setTotal(int total) {
+ this.total = total;
+ }
+
+ public int getOffset() {
+ return offset;
+ }
+
+ public void setOffset(int offset) {
+ this.offset = offset;
+ }
+
+ public int getSize() {
+ return size;
+ }
+
+ public void setSize(int size) {
+ this.size = size;
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/ParameterDefinition.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/ParameterDefinition.java
index ae79880cca..1ff70b68d6 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/ParameterDefinition.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/ParameterDefinition.java
@@ -21,38 +21,42 @@
package org.onap.so.cloudify.v3.model;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ParameterDefinition implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @JsonProperty("type")
- private String type;
- @JsonProperty("description")
- private String description;
- @JsonProperty("default")
- private Object defaultValue;
-
- public String getType() {
- return type;
- }
- public void setType(String type) {
- this.type = type;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- public Object getDefaultValue() {
- return defaultValue;
- }
- public void setDefaultValue(Object defaultValue) {
- this.defaultValue = defaultValue;
- }
+ private static final long serialVersionUID = 1L;
+
+ @JsonProperty("type")
+ private String type;
+ @JsonProperty("description")
+ private String description;
+ @JsonProperty("default")
+ private Object defaultValue;
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Object getDefaultValue() {
+ return defaultValue;
+ }
+
+ public void setDefaultValue(Object defaultValue) {
+ this.defaultValue = defaultValue;
+ }
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/StartExecutionParams.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/StartExecutionParams.java
index f9d1cecb30..e12b7d094c 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/StartExecutionParams.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/StartExecutionParams.java
@@ -22,16 +22,15 @@ package org.onap.so.cloudify.v3.model;
import java.io.Serializable;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class StartExecutionParams implements Serializable {
- private static final long serialVersionUID = 1L;
-
+ private static final long serialVersionUID = 1L;
+
@JsonProperty("workflow_id")
private String workflowId;
-
+
@JsonProperty("deployment_id")
private String deploymentId;
@@ -43,56 +42,52 @@ public class StartExecutionParams implements Serializable {
@JsonProperty("parameters")
private Map<String, Object> parameters;
-
- public String getWorkflowId() {
- return workflowId;
- }
- public void setWorkflowId(String workflowId) {
- this.workflowId = workflowId;
- }
+ public String getWorkflowId() {
+ return workflowId;
+ }
- public String getDeploymentId() {
- return deploymentId;
- }
+ public void setWorkflowId(String workflowId) {
+ this.workflowId = workflowId;
+ }
+
+ public String getDeploymentId() {
+ return deploymentId;
+ }
- public void setDeploymentId(String deploymentId) {
- this.deploymentId = deploymentId;
- }
+ public void setDeploymentId(String deploymentId) {
+ this.deploymentId = deploymentId;
+ }
- public boolean isAllowCustomParameters() {
- return allowCustomParameters;
- }
+ public boolean isAllowCustomParameters() {
+ return allowCustomParameters;
+ }
- public void setAllowCustomParameters(boolean allowCustomParameters) {
- this.allowCustomParameters = allowCustomParameters;
- }
+ public void setAllowCustomParameters(boolean allowCustomParameters) {
+ this.allowCustomParameters = allowCustomParameters;
+ }
- public boolean isForce() {
- return force;
- }
+ public boolean isForce() {
+ return force;
+ }
- public void setForce(boolean force) {
- this.force = force;
- }
+ public void setForce(boolean force) {
+ this.force = force;
+ }
- public Map<String, Object> getParameters() {
- return parameters;
- }
+ public Map<String, Object> getParameters() {
+ return parameters;
+ }
- public void setParameters(Map<String, Object> parameters) {
- this.parameters = parameters;
- }
+ public void setParameters(Map<String, Object> parameters) {
+ this.parameters = parameters;
+ }
- @Override
+ @Override
public String toString() {
- return "UpdateExecutionParams{" +
- "workflowId='" + workflowId + '\'' +
- "deploymentId='" + deploymentId + '\'' +
- "allowCustomParameters='" + allowCustomParameters + '\'' +
- "force='" + force + '\'' +
- "parameters='" + parameters + '\'' +
- '}';
+ return "UpdateExecutionParams{" + "workflowId='" + workflowId + '\'' + "deploymentId='" + deploymentId + '\''
+ + "allowCustomParameters='" + allowCustomParameters + '\'' + "force='" + force + '\'' + "parameters='"
+ + parameters + '\'' + '}';
}
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Token.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Token.java
index ebb968acbf..c5809d4a32 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Token.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/Token.java
@@ -21,47 +21,43 @@
package org.onap.so.cloudify.v3.model;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
-//@JsonRootName("token")
+// @JsonRootName("token")
// The Token object is returned without a root element
public class Token implements Serializable {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- @JsonProperty("role")
+ @JsonProperty("role")
private String role;
@JsonProperty("value")
private String value;
-
- // Any expiration? Maybe something in the Headers?
-
- public String getRole() {
- return role;
- }
- public void setRole(String role) {
- this.role = role;
- }
+ // Any expiration? Maybe something in the Headers?
+
+ public String getRole() {
+ return role;
+ }
- public String getValue() {
- return value;
- }
+ public void setRole(String role) {
+ this.role = role;
+ }
- public void setValue(String value) {
- this.value = value;
- }
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
- @Override
+ @Override
public String toString() {
- return "Token{" +
- "role='" + role + '\'' +
- ", value='" + value + '\'' +
- '}';
+ return "Token{" + "role='" + role + '\'' + ", value='" + value + '\'' + '}';
}
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/UpdateExecutionParams.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/UpdateExecutionParams.java
index abd809b5d6..3f49b90626 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/UpdateExecutionParams.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/UpdateExecutionParams.java
@@ -21,30 +21,27 @@
package org.onap.so.cloudify.v3.model;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class UpdateExecutionParams implements Serializable {
- private static final long serialVersionUID = 1L;
-
+ private static final long serialVersionUID = 1L;
+
@JsonProperty("status")
private String status;
-
+
public String getStatus() {
- return status;
- }
+ return status;
+ }
- public void setStatus(String status) {
- this.status = status;
- }
+ public void setStatus(String status) {
+ this.status = status;
+ }
- @Override
+ @Override
public String toString() {
- return "UpdateExecutionParams{" +
- "status='" + status + '\'' +
- '}';
+ return "UpdateExecutionParams{" + "status='" + status + '\'' + '}';
}
}
diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/UpdateNodeInstanceParams.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/UpdateNodeInstanceParams.java
index 946bb2165c..fabb70a49a 100644
--- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/UpdateNodeInstanceParams.java
+++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/UpdateNodeInstanceParams.java
@@ -21,14 +21,13 @@
package org.onap.so.cloudify.v3.model;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import java.io.Serializable;
import java.util.Map;
public class UpdateNodeInstanceParams implements Serializable {
- private static final long serialVersionUID = 1L;
-
+ private static final long serialVersionUID = 1L;
+
@JsonProperty("state")
private String state;
@@ -40,37 +39,34 @@ public class UpdateNodeInstanceParams implements Serializable {
public String getState() {
- return state;
- }
+ return state;
+ }
- public void setState(String state) {
- this.state = state;
- }
+ public void setState(String state) {
+ this.state = state;
+ }
- public String getVersion() {
- return version;
- }
+ public String getVersion() {
+ return version;
+ }
- public void setVersion(String version) {
- this.version = version;
- }
+ public void setVersion(String version) {
+ this.version = version;
+ }
- public Map<String, Object> getRuntimeProperties() {
- return runtimeProperties;
- }
+ public Map<String, Object> getRuntimeProperties() {
+ return runtimeProperties;
+ }
- public void setRuntimeProperties(Map<String, Object> runtimeProperties) {
- this.runtimeProperties = runtimeProperties;
- }
+ public void setRuntimeProperties(Map<String, Object> runtimeProperties) {
+ this.runtimeProperties = runtimeProperties;
+ }
- @Override
+ @Override
public String toString() {
- return "UpdateNodeInstanceParams{" +
- "state='" + state + '\'' +
- "version='" + version + '\'' +
- ", runtimeProperties=" + runtimeProperties +
- '}';
+ return "UpdateNodeInstanceParams{" + "state='" + state + '\'' + "version='" + version + '\''
+ + ", runtimeProperties=" + runtimeProperties + '}';
}
}
diff --git a/cloudify-client/src/test/java/org/onap/so/cloudify/BeanMultiTest.java b/cloudify-client/src/test/java/org/onap/so/cloudify/BeanMultiTest.java
index d38c7468db..4028b71109 100644
--- a/cloudify-client/src/test/java/org/onap/so/cloudify/BeanMultiTest.java
+++ b/cloudify-client/src/test/java/org/onap/so/cloudify/BeanMultiTest.java
@@ -19,9 +19,9 @@
*/
package org.onap.so.cloudify;
+
import org.junit.Before;
import org.junit.Test;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterEnum;
@@ -35,29 +35,26 @@ import com.openpojo.validation.test.impl.SetterTester;
public class BeanMultiTest {
- Validator validator;
- PojoClassFilter enumFilter;
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
-
- @Before
- public void setup(){
- enumFilter = new FilterEnum();
- validator = ValidatorBuilder.create()
- .with(new SetterMustExistRule(),
- new GetterMustExistRule())
- .with(new SetterTester(),
- new GetterTester())
- .build();
- }
- @Test
- public void validateBeansMsoApihandlerBeans() {
-
- validator.validate("org.onap.so.cloudify.v3.model",enumFilter);
- }
-
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/src/test/java");
- }
- }
+ Validator validator;
+ PojoClassFilter enumFilter;
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ @Before
+ public void setup() {
+ enumFilter = new FilterEnum();
+ validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule())
+ .with(new SetterTester(), new GetterTester()).build();
+ }
+
+ @Test
+ public void validateBeansMsoApihandlerBeans() {
+
+ validator.validate("org.onap.so.cloudify.v3.model", enumFilter);
+ }
+
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/src/test/java");
+ }
+ }
}
diff --git a/cloudify-client/src/test/java/org/onap/so/cloudify/base/client/CloudifyClientTest.java b/cloudify-client/src/test/java/org/onap/so/cloudify/base/client/CloudifyClientTest.java
index fc55eaf19c..88974acb11 100644
--- a/cloudify-client/src/test/java/org/onap/so/cloudify/base/client/CloudifyClientTest.java
+++ b/cloudify-client/src/test/java/org/onap/so/cloudify/base/client/CloudifyClientTest.java
@@ -25,79 +25,83 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.Assert.assertEquals;
-
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onap.so.cloudify.v3.model.Execution;
-
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class CloudifyClientTest {
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
- @Test
- public void clientCreate(){
- wireMockRule.stubFor(get(urlPathEqualTo("/testUrl")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("{\"id\": \"123\"}").withStatus(HttpStatus.SC_OK)));
- int port = wireMockRule.port();
- CloudifyClient cc = new CloudifyClient("http://localhost:"+port);
- cc.setToken("token");
- CloudifyRequest<Execution> crx = cc.get("/testUrl", Execution.class);
- Execution x = crx.execute();
- assertEquals("123", x.getId());
- }
+ @Test
+ public void clientCreate() {
+ wireMockRule.stubFor(
+ get(urlPathEqualTo("/testUrl")).willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody("{\"id\": \"123\"}").withStatus(HttpStatus.SC_OK)));
+ int port = wireMockRule.port();
+ CloudifyClient cc = new CloudifyClient("http://localhost:" + port);
+ cc.setToken("token");
+ CloudifyRequest<Execution> crx = cc.get("/testUrl", Execution.class);
+ Execution x = crx.execute();
+ assertEquals("123", x.getId());
+ }
- @Test
- public void clientCreateWithBadConnector(){
- thrown.expect(CloudifyResponseException.class);
- wireMockRule.stubFor(get(urlPathEqualTo("/testUrl")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("{\"id\": \"123\"}").withStatus(HttpStatus.SC_OK)));
- int port = wireMockRule.port();
- CloudifyClientConnector ccc = new CloudifyClientConnector(){
- @Override
- public <T> CloudifyResponse request(CloudifyRequest<T> request) {
- throw new CloudifyResponseException("test case", 401);
- }};
- CloudifyClient cc = new CloudifyClient("http://localhost:"+port, ccc);
-// cc.setToken("token");
- CloudifyRequest<Execution> crx = cc.get("/testUrl", Execution.class);
- Execution x = crx.execute();
- }
+ @Test
+ public void clientCreateWithBadConnector() {
+ thrown.expect(CloudifyResponseException.class);
+ wireMockRule.stubFor(
+ get(urlPathEqualTo("/testUrl")).willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody("{\"id\": \"123\"}").withStatus(HttpStatus.SC_OK)));
+ int port = wireMockRule.port();
+ CloudifyClientConnector ccc = new CloudifyClientConnector() {
+ @Override
+ public <T> CloudifyResponse request(CloudifyRequest<T> request) {
+ throw new CloudifyResponseException("test case", 401);
+ }
+ };
+ CloudifyClient cc = new CloudifyClient("http://localhost:" + port, ccc);
+ // cc.setToken("token");
+ CloudifyRequest<Execution> crx = cc.get("/testUrl", Execution.class);
+ Execution x = crx.execute();
+ }
- @Test
- public void clientCreateWithBadConnectorAndToken(){
- thrown.expect(CloudifyResponseException.class);
- wireMockRule.stubFor(get(urlPathEqualTo("/testUrl")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("{\"id\": \"123\"}").withStatus(HttpStatus.SC_OK)));
- int port = wireMockRule.port();
- CloudifyClientConnector ccc = new CloudifyClientConnector(){
- @Override
- public <T> CloudifyResponse request(CloudifyRequest<T> request) {
- throw new CloudifyResponseException("test case", 401);
- }};
- CloudifyClient cc = new CloudifyClient("http://localhost:"+port, ccc);
- cc.setToken("token");
- CloudifyRequest<Execution> crx = cc.get("/testUrl", Execution.class);
- Execution x = crx.execute();
- }
+ @Test
+ public void clientCreateWithBadConnectorAndToken() {
+ thrown.expect(CloudifyResponseException.class);
+ wireMockRule.stubFor(
+ get(urlPathEqualTo("/testUrl")).willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody("{\"id\": \"123\"}").withStatus(HttpStatus.SC_OK)));
+ int port = wireMockRule.port();
+ CloudifyClientConnector ccc = new CloudifyClientConnector() {
+ @Override
+ public <T> CloudifyResponse request(CloudifyRequest<T> request) {
+ throw new CloudifyResponseException("test case", 401);
+ }
+ };
+ CloudifyClient cc = new CloudifyClient("http://localhost:" + port, ccc);
+ cc.setToken("token");
+ CloudifyRequest<Execution> crx = cc.get("/testUrl", Execution.class);
+ Execution x = crx.execute();
+ }
- @Test
- public void clientCreateWithTenant(){
- wireMockRule.stubFor(get(urlPathEqualTo("/testUrl")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("{\"id\": \"123\"}").withStatus(HttpStatus.SC_OK)));
- int port = wireMockRule.port();
- CloudifyClient cc = new CloudifyClient("http://localhost:"+port, "other_tenant");
- cc.setToken("token");
- cc.property("property", "value");
- CloudifyRequest<Execution> crx = cc.get("/testUrl", Execution.class);
- Execution x = crx.execute();
- assertEquals("123", x.getId());
- }
+ @Test
+ public void clientCreateWithTenant() {
+ wireMockRule.stubFor(
+ get(urlPathEqualTo("/testUrl")).willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody("{\"id\": \"123\"}").withStatus(HttpStatus.SC_OK)));
+ int port = wireMockRule.port();
+ CloudifyClient cc = new CloudifyClient("http://localhost:" + port, "other_tenant");
+ cc.setToken("token");
+ cc.property("property", "value");
+ CloudifyRequest<Execution> crx = cc.get("/testUrl", Execution.class);
+ Execution x = crx.execute();
+ assertEquals("123", x.getId());
+ }
}
diff --git a/cloudify-client/src/test/java/org/onap/so/cloudify/base/client/CloudifyClientTokenProviderTest.java b/cloudify-client/src/test/java/org/onap/so/cloudify/base/client/CloudifyClientTokenProviderTest.java
index ba43dc9e78..77152a2dd0 100644
--- a/cloudify-client/src/test/java/org/onap/so/cloudify/base/client/CloudifyClientTokenProviderTest.java
+++ b/cloudify-client/src/test/java/org/onap/so/cloudify/base/client/CloudifyClientTokenProviderTest.java
@@ -25,32 +25,32 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.Assert.assertEquals;
-
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class CloudifyClientTokenProviderTest {
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
- @Test
- public void createTokenProvider() {
- wireMockRule.stubFor(get(urlPathEqualTo("/testUrl/api/v3/tokens")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("{\"role\": \"user\", \"value\": \"tokenVal\"}").withStatus(HttpStatus.SC_OK)));
- int port = wireMockRule.port();
+ @Test
+ public void createTokenProvider() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/testUrl/api/v3/tokens"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody("{\"role\": \"user\", \"value\": \"tokenVal\"}").withStatus(HttpStatus.SC_OK)));
+ int port = wireMockRule.port();
- CloudifyClientTokenProvider cctp = new CloudifyClientTokenProvider("http://localhost:"+port+"/testUrl", "user", "pswd");
- String token = cctp.getToken();
- assertEquals("tokenVal", token);
- token = cctp.getToken();
- assertEquals("tokenVal", token);
- cctp.expireToken();
- }
+ CloudifyClientTokenProvider cctp =
+ new CloudifyClientTokenProvider("http://localhost:" + port + "/testUrl", "user", "pswd");
+ String token = cctp.getToken();
+ assertEquals("tokenVal", token);
+ token = cctp.getToken();
+ assertEquals("tokenVal", token);
+ cctp.expireToken();
+ }
}
diff --git a/cloudify-client/src/test/java/org/onap/so/cloudify/connector/http/HttpClientConnectorTest.java b/cloudify-client/src/test/java/org/onap/so/cloudify/connector/http/HttpClientConnectorTest.java
index 4475fff093..c85b88f7f3 100644
--- a/cloudify-client/src/test/java/org/onap/so/cloudify/connector/http/HttpClientConnectorTest.java
+++ b/cloudify-client/src/test/java/org/onap/so/cloudify/connector/http/HttpClientConnectorTest.java
@@ -24,7 +24,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
-
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
@@ -43,11 +42,9 @@ import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertEquals;
-
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
-
import org.onap.so.cloudify.base.client.CloudifyConnectException;
import org.onap.so.cloudify.base.client.CloudifyRequest;
import org.onap.so.cloudify.base.client.CloudifyResponseException;
@@ -56,199 +53,203 @@ import org.onap.so.cloudify.base.client.HttpMethod;
import org.onap.so.cloudify.v3.model.Deployment;
public class HttpClientConnectorTest {
-
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Test
- public void sunnyDay_POST(){
- wireMockRule.stubFor(post(urlPathEqualTo("/testUrl")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
- int port = wireMockRule.port();
- HttpClientConnector conector = new HttpClientConnector();
- CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
- Deployment deployment = new Deployment();
- deployment.setId("id");
- request.entity(deployment, "application/json");
- request.endpoint("http://localhost:"+port+"/testUrl");
- request.setBasicAuthentication("USER","PASSWORD");
- request.header("Content-Type","application/json");
- request.method(HttpMethod.POST);
- conector.request(request);
- verify(postRequestedFor(urlEqualTo("/testUrl")));
- }
-
-
- @Test
- public void sunnyDay_GET(){
- wireMockRule.stubFor(get(urlPathEqualTo("/testUrl")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
- int port = wireMockRule.port();
- HttpClientConnector conector = new HttpClientConnector();
- CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
- request.endpoint("http://localhost:"+port+"/testUrl");
- request.setBasicAuthentication("USER","PASSWORD");
- request.method(HttpMethod.GET);
- conector.request(request);
- verify(getRequestedFor(urlEqualTo("/testUrl")));
- }
-
- @Test
- public void sunnyDay_PUT(){
- wireMockRule.stubFor(put(urlPathEqualTo("/testUrl")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
- int port = wireMockRule.port();
- HttpClientConnector conector = new HttpClientConnector();
- CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
- request.endpoint("http://localhost:"+port+"/testUrl");
- request.setBasicAuthentication("USER","PASSWORD");
- request.method(HttpMethod.PUT);
- conector.request(request);
- verify(putRequestedFor(urlEqualTo("/testUrl")));
- }
-
-
- @Test
- public void sunnyDay_DELETE(){
- wireMockRule.stubFor(delete(urlPathEqualTo("/testUrl")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
- int port = wireMockRule.port();
- HttpClientConnector conector = new HttpClientConnector();
- CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
- request.endpoint("http://localhost:"+port+"/testUrl");
- request.setBasicAuthentication("USER","PASSWORD");
- request.method(HttpMethod.DELETE);
- conector.request(request);
- verify(deleteRequestedFor(urlEqualTo("/testUrl")));
- }
-
-
- @Test
- public void rainyDay_PATCH(){
- thrown.expect(HttpClientException.class);
- thrown.expectMessage("Unrecognized HTTP Method: PATCH");
- HttpClientConnector conector = new HttpClientConnector();
- CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
- request.endpoint("http://localhost:123123/testUrl");
- request.setBasicAuthentication("USER","PASSWORD");
- request.method(HttpMethod.PATCH);
- conector.request(request);
-
- }
-
- @Test
- public void rainyDayRunTimeException(){
- wireMockRule.stubFor(post(urlEqualTo("/503")).willReturn(
- aResponse().withStatus(503).withHeader("Content-Type", "text/plain").withBody("failure")));
- thrown.expect(RuntimeException.class);
- thrown.expectMessage("Unexpected client exception");
- HttpClientConnector conector = new HttpClientConnector();
- CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
- request.endpoint("http://localhost:123123/503");
- request.setBasicAuthentication("USER","PASSWORD");
- request.method(HttpMethod.POST);
- conector.request(request);
-
- }
-
- @Test
- public void rainyDayBadUri() {
- wireMockRule.stubFor(post(urlPathEqualTo("/testUrl")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
- thrown.expect(HttpClientException.class);
- int port = wireMockRule.port();
- HttpClientConnector conector = new HttpClientConnector();
- CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
- Deployment deployment = new Deployment();
- deployment.setId("id");
- request.entity(deployment, "application/json");
- request.endpoint("(@#$@(#*$&asfasdf");
- request.setBasicAuthentication("USER","PASSWORD");
- request.header("Content-Type","application/json");
- request.method(HttpMethod.POST);
- conector.request(request);
- }
-
- @Test
- public void sunnyDayWithJsonEntity_POST(){
- wireMockRule.stubFor(post(urlPathEqualTo("/testUrl")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
- int port = wireMockRule.port();
- HttpClientConnector conector = new HttpClientConnector();
-
- Deployment deployment = new Deployment();
- deployment.setId("id");
-
- CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>(null, HttpMethod.POST, "/", Entity.json(deployment), null);
-
- request.endpoint("http://localhost:"+port);
- request.path("testUrl");
- request.header("Content-Type","application/json");
- request.header("Content-Type", null);
-
- request.returnType(Deployment.class);
- assertEquals(Deployment.class, request.returnType());
-
- Entity<Deployment> t = request.json(deployment);
- assertEquals(t.getEntity().getId(), "id");
-
- request.queryParam("test", "one").queryParam("test", "two");
-
- conector.request(request);
-
- verify(postRequestedFor(urlEqualTo("/testUrl?test=two")));
- }
-
- @Test
- public void sunnyDayWithStreamEntity_POST() {
- wireMockRule.stubFor(post(urlPathEqualTo("/testUrl")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
- int port = wireMockRule.port();
- HttpClientConnector conector = new HttpClientConnector();
-
- InputStream is = new ByteArrayInputStream("{}".getBytes(StandardCharsets.UTF_8));
-
- CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>(null, HttpMethod.POST, "/testUrl", Entity.stream(is), null);
-
- request.endpoint("http://localhost:"+port);
- request.setBasicAuthentication("USER","PASSWORD");
- request.header("Content-Type","application/json");
-
- conector.request(request);
- verify(postRequestedFor(urlEqualTo("/testUrl")));
- }
-
- @Test
- public void rainyDayGarbageData(){
- wireMockRule.stubFor(get(urlPathEqualTo("/testUrl")).willReturn(
- aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE)));
- thrown.expect(CloudifyConnectException.class);
- int port = wireMockRule.port();
- HttpClientConnector conector = new HttpClientConnector();
- CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
- request.endpoint("http://localhost:"+port+"/testUrl");
- request.setBasicAuthentication("USER","PASSWORD");
- request.method(HttpMethod.GET);
- conector.request(request);
- }
-
- @Test
- public void rainyDayEmptyResponse(){
- wireMockRule.stubFor(get(urlPathEqualTo("/testUrl")).willReturn(aResponse()
- .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_NOT_FOUND)));
-
- thrown.expect(HttpClientException.class);
- int port = wireMockRule.port();
- HttpClientConnector conector = new HttpClientConnector();
- CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
- request.endpoint("http://localhost:"+port+"/testUrl");
- request.setBasicAuthentication("USER","PASSWORD");
- request.method(HttpMethod.GET);
- conector.request(request); // gets down to "Get here on an error response (4XX-5XX)", then tries to throw a CloudifyResponseException, which calls getEntity, which tries to parse an HTML error page as a JSON, which causes the HttpClientException.
- }
-
-
-} \ No newline at end of file
+
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void sunnyDay_POST() {
+ wireMockRule.stubFor(post(urlPathEqualTo("/testUrl")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
+ int port = wireMockRule.port();
+ HttpClientConnector conector = new HttpClientConnector();
+ CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
+ Deployment deployment = new Deployment();
+ deployment.setId("id");
+ request.entity(deployment, "application/json");
+ request.endpoint("http://localhost:" + port + "/testUrl");
+ request.setBasicAuthentication("USER", "PASSWORD");
+ request.header("Content-Type", "application/json");
+ request.method(HttpMethod.POST);
+ conector.request(request);
+ verify(postRequestedFor(urlEqualTo("/testUrl")));
+ }
+
+
+ @Test
+ public void sunnyDay_GET() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/testUrl")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
+ int port = wireMockRule.port();
+ HttpClientConnector conector = new HttpClientConnector();
+ CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
+ request.endpoint("http://localhost:" + port + "/testUrl");
+ request.setBasicAuthentication("USER", "PASSWORD");
+ request.method(HttpMethod.GET);
+ conector.request(request);
+ verify(getRequestedFor(urlEqualTo("/testUrl")));
+ }
+
+ @Test
+ public void sunnyDay_PUT() {
+ wireMockRule.stubFor(put(urlPathEqualTo("/testUrl")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
+ int port = wireMockRule.port();
+ HttpClientConnector conector = new HttpClientConnector();
+ CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
+ request.endpoint("http://localhost:" + port + "/testUrl");
+ request.setBasicAuthentication("USER", "PASSWORD");
+ request.method(HttpMethod.PUT);
+ conector.request(request);
+ verify(putRequestedFor(urlEqualTo("/testUrl")));
+ }
+
+
+ @Test
+ public void sunnyDay_DELETE() {
+ wireMockRule.stubFor(delete(urlPathEqualTo("/testUrl")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
+ int port = wireMockRule.port();
+ HttpClientConnector conector = new HttpClientConnector();
+ CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
+ request.endpoint("http://localhost:" + port + "/testUrl");
+ request.setBasicAuthentication("USER", "PASSWORD");
+ request.method(HttpMethod.DELETE);
+ conector.request(request);
+ verify(deleteRequestedFor(urlEqualTo("/testUrl")));
+ }
+
+
+ @Test
+ public void rainyDay_PATCH() {
+ thrown.expect(HttpClientException.class);
+ thrown.expectMessage("Unrecognized HTTP Method: PATCH");
+ HttpClientConnector conector = new HttpClientConnector();
+ CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
+ request.endpoint("http://localhost:123123/testUrl");
+ request.setBasicAuthentication("USER", "PASSWORD");
+ request.method(HttpMethod.PATCH);
+ conector.request(request);
+
+ }
+
+ @Test
+ public void rainyDayRunTimeException() {
+ wireMockRule.stubFor(post(urlEqualTo("/503"))
+ .willReturn(aResponse().withStatus(503).withHeader("Content-Type", "text/plain").withBody("failure")));
+ thrown.expect(RuntimeException.class);
+ thrown.expectMessage("Unexpected client exception");
+ HttpClientConnector conector = new HttpClientConnector();
+ CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
+ request.endpoint("http://localhost:123123/503");
+ request.setBasicAuthentication("USER", "PASSWORD");
+ request.method(HttpMethod.POST);
+ conector.request(request);
+
+ }
+
+ @Test
+ public void rainyDayBadUri() {
+ wireMockRule.stubFor(post(urlPathEqualTo("/testUrl")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
+ thrown.expect(HttpClientException.class);
+ int port = wireMockRule.port();
+ HttpClientConnector conector = new HttpClientConnector();
+ CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
+ Deployment deployment = new Deployment();
+ deployment.setId("id");
+ request.entity(deployment, "application/json");
+ request.endpoint("(@#$@(#*$&asfasdf");
+ request.setBasicAuthentication("USER", "PASSWORD");
+ request.header("Content-Type", "application/json");
+ request.method(HttpMethod.POST);
+ conector.request(request);
+ }
+
+ @Test
+ public void sunnyDayWithJsonEntity_POST() {
+ wireMockRule.stubFor(post(urlPathEqualTo("/testUrl")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
+ int port = wireMockRule.port();
+ HttpClientConnector conector = new HttpClientConnector();
+
+ Deployment deployment = new Deployment();
+ deployment.setId("id");
+
+ CloudifyRequest<Deployment> request =
+ new CloudifyRequest<Deployment>(null, HttpMethod.POST, "/", Entity.json(deployment), null);
+
+ request.endpoint("http://localhost:" + port);
+ request.path("testUrl");
+ request.header("Content-Type", "application/json");
+ request.header("Content-Type", null);
+
+ request.returnType(Deployment.class);
+ assertEquals(Deployment.class, request.returnType());
+
+ Entity<Deployment> t = request.json(deployment);
+ assertEquals(t.getEntity().getId(), "id");
+
+ request.queryParam("test", "one").queryParam("test", "two");
+
+ conector.request(request);
+
+ verify(postRequestedFor(urlEqualTo("/testUrl?test=two")));
+ }
+
+ @Test
+ public void sunnyDayWithStreamEntity_POST() {
+ wireMockRule.stubFor(post(urlPathEqualTo("/testUrl")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_OK)));
+ int port = wireMockRule.port();
+ HttpClientConnector conector = new HttpClientConnector();
+
+ InputStream is = new ByteArrayInputStream("{}".getBytes(StandardCharsets.UTF_8));
+
+ CloudifyRequest<Deployment> request =
+ new CloudifyRequest<Deployment>(null, HttpMethod.POST, "/testUrl", Entity.stream(is), null);
+
+ request.endpoint("http://localhost:" + port);
+ request.setBasicAuthentication("USER", "PASSWORD");
+ request.header("Content-Type", "application/json");
+
+ conector.request(request);
+ verify(postRequestedFor(urlEqualTo("/testUrl")));
+ }
+
+ @Test
+ public void rainyDayGarbageData() {
+ wireMockRule.stubFor(
+ get(urlPathEqualTo("/testUrl")).willReturn(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE)));
+ thrown.expect(CloudifyConnectException.class);
+ int port = wireMockRule.port();
+ HttpClientConnector conector = new HttpClientConnector();
+ CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
+ request.endpoint("http://localhost:" + port + "/testUrl");
+ request.setBasicAuthentication("USER", "PASSWORD");
+ request.method(HttpMethod.GET);
+ conector.request(request);
+ }
+
+ @Test
+ public void rainyDayEmptyResponse() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/testUrl")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBody("TEST").withStatus(HttpStatus.SC_NOT_FOUND)));
+
+ thrown.expect(HttpClientException.class);
+ int port = wireMockRule.port();
+ HttpClientConnector conector = new HttpClientConnector();
+ CloudifyRequest<Deployment> request = new CloudifyRequest<Deployment>();
+ request.endpoint("http://localhost:" + port + "/testUrl");
+ request.setBasicAuthentication("USER", "PASSWORD");
+ request.method(HttpMethod.GET);
+ conector.request(request); // gets down to "Get here on an error response (4XX-5XX)", then tries to throw a
+ // CloudifyResponseException, which calls getEntity, which tries to parse an HTML
+ // error page as a JSON, which causes the HttpClientException.
+ }
+
+
+}
diff --git a/cloudify-client/src/test/java/org/onap/so/cloudify/connector/http/HttpClientRedirectStrategyTest.java b/cloudify-client/src/test/java/org/onap/so/cloudify/connector/http/HttpClientRedirectStrategyTest.java
index 87b51e9357..6010726669 100644
--- a/cloudify-client/src/test/java/org/onap/so/cloudify/connector/http/HttpClientRedirectStrategyTest.java
+++ b/cloudify-client/src/test/java/org/onap/so/cloudify/connector/http/HttpClientRedirectStrategyTest.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP : SO
- * ================================================================================
- * Copyright (C) 2018 Nokia.
- * =============================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP : SO
+ * ================================================================================ Copyright (C) 2018 Nokia.
+ * ============================================================================= Licensed under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
+ * of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.so.cloudify.connector.http;
@@ -23,7 +18,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
-
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpRequest;
@@ -73,7 +67,7 @@ public class HttpClientRedirectStrategyTest {
}
private void assertHttpUriRequestFor(String methodName, Class<? extends HttpUriRequest> expectedHttpMethodClass)
- throws URISyntaxException, ProtocolException {
+ throws URISyntaxException, ProtocolException {
// GIVEN
HttpRequest request = mock(HttpRequest.class, RETURNS_DEEP_STUBS);
given(request.getRequestLine().getMethod()).willReturn(methodName);
@@ -81,8 +75,8 @@ public class HttpClientRedirectStrategyTest {
HttpContext context = null;
URI expectedUri = new URI("http://localhost/host");
// WHEN
- HttpUriRequest httpUriRequest = new TestableHttpClientRedirectStrategy(expectedUri)
- .getRedirect(request, response, context);
+ HttpUriRequest httpUriRequest =
+ new TestableHttpClientRedirectStrategy(expectedUri).getRedirect(request, response, context);
// THEN
assertThat(httpUriRequest).isInstanceOf(expectedHttpMethodClass);
assertThat(httpUriRequest.getURI()).isEqualTo(expectedUri);
@@ -98,20 +92,22 @@ public class HttpClientRedirectStrategyTest {
URI expectedUri = new URI("http://localhost/host");
HttpContext context = null;
// WHEN
- HttpUriRequest httpUriRequest = new TestableHttpClientRedirectStrategy(expectedUri)
- .getRedirect(request, response, context);
+ HttpUriRequest httpUriRequest =
+ new TestableHttpClientRedirectStrategy(expectedUri).getRedirect(request, response, context);
// THEN
assertThat(httpUriRequest).isInstanceOf(HttpGet.class);
assertThat(httpUriRequest.getURI()).isEqualTo(expectedUri);
}
@Test
- public void getRedirect_shouldCopyHttpRequestAndSetNewUri_forMovedTemporarilyStatus() throws URISyntaxException, ProtocolException {
+ public void getRedirect_shouldCopyHttpRequestAndSetNewUri_forMovedTemporarilyStatus()
+ throws URISyntaxException, ProtocolException {
assertHttpRequestIsCopied(HttpStatus.SC_MOVED_TEMPORARILY);
}
@Test
- public void getRedirect_shouldCopyHttpRequestAndSetNewUri_forTemporaryRedirectStatus() throws URISyntaxException, ProtocolException {
+ public void getRedirect_shouldCopyHttpRequestAndSetNewUri_forTemporaryRedirectStatus()
+ throws URISyntaxException, ProtocolException {
assertHttpRequestIsCopied(HttpStatus.SC_TEMPORARY_REDIRECT);
}
@@ -125,8 +121,8 @@ public class HttpClientRedirectStrategyTest {
URI expectedUri = new URI("http://localhost/host");
HttpContext context = null;
// WHEN
- HttpUriRequest httpUriRequest = new TestableHttpClientRedirectStrategy(expectedUri)
- .getRedirect(request, response, context);
+ HttpUriRequest httpUriRequest =
+ new TestableHttpClientRedirectStrategy(expectedUri).getRedirect(request, response, context);
// THEN
assertThat(httpUriRequest).isInstanceOf(HttpGet.class);
assertThat(httpUriRequest.getURI()).isEqualTo(expectedUri);
@@ -139,9 +135,10 @@ public class HttpClientRedirectStrategyTest {
public TestableHttpClientRedirectStrategy(URI expectedUri) {
this.expectedUri = expectedUri;
}
+
@Override
public URI getLocationURI(HttpRequest request, HttpResponse response, HttpContext context) {
return expectedUri;
}
}
-} \ No newline at end of file
+}
diff --git a/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/BlueprintsResourceTest.java b/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/BlueprintsResourceTest.java
index 6155cf287c..cba3bf8fdc 100644
--- a/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/BlueprintsResourceTest.java
+++ b/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/BlueprintsResourceTest.java
@@ -27,11 +27,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.Assert.assertEquals;
-
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
-
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
@@ -42,106 +40,105 @@ import org.onap.so.cloudify.v3.client.BlueprintsResource.ListBlueprints;
import org.onap.so.cloudify.v3.client.BlueprintsResource.UploadBlueprint;
import org.onap.so.cloudify.v3.model.Blueprint;
import org.onap.so.cloudify.v3.model.Blueprints;
-
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class BlueprintsResourceTest {
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Test
- public void cloudifyClientBlueprintFromStream() {
- wireMockRule.stubFor(put(urlPathEqualTo("/api/v3/blueprints/123")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{\"id\": \"123\"}")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- BlueprintsResource br = c.blueprints();
- InputStream is = new ByteArrayInputStream("{}".getBytes(StandardCharsets.UTF_8));
- UploadBlueprint ub = br.uploadFromStream("123", "blueprint.json", is);
- Blueprint b = ub.execute();
- assertEquals("123", b.getId());
- }
-
- @Test
- public void cloudifyClientBlueprintFromUrl() {
- wireMockRule.stubFor(put(urlPathEqualTo("/api/v3/blueprints/123")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{\"id\": \"123\"}")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- BlueprintsResource br = c.blueprints();
- UploadBlueprint ub = br.uploadFromUrl("123", "blueprint.json", "http://localhost:"+port+"/blueprint");
- Blueprint b = ub.execute();
- assertEquals("123", b.getId());
- }
-
- @Test
- public void cloudifyClientBlueprintDelete() {
- wireMockRule.stubFor(delete(urlPathEqualTo("/api/v3/blueprints/123")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{\"id\": \"123\"}")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- BlueprintsResource br = c.blueprints();
- DeleteBlueprint db = br.deleteById("123");
- Blueprint b = db.execute();
- assertEquals("123", b.getId());
- }
-
- @Test
- public void cloudifyClientBlueprintList() {
- wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/blueprints")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{\"items\": [{\"id\": \"123\"}]}")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- BlueprintsResource br = c.blueprints();
- ListBlueprints lb = br.list();
- Blueprints b = lb.execute();
- assertEquals("123", b.getItems().get(0).getId());
- }
-
- @Test
- public void cloudifyClientBlueprintGetById() {
- wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/blueprints/123")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{\"id\": \"123\"}")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- BlueprintsResource br = c.blueprints();
- GetBlueprint gb = br.getById("123");
- Blueprint b = gb.execute();
- assertEquals("123", b.getId());
- }
-
- @Test
- public void cloudifyClientBlueprintGetMetadataById() {
- wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/blueprints/123")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{\"id\": \"123\"}")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- BlueprintsResource br = c.blueprints();
- GetBlueprint gb = br.getMetadataById("123");
- Blueprint b = gb.execute();
- assertEquals("123", b.getId());
- }
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void cloudifyClientBlueprintFromStream() {
+ wireMockRule.stubFor(put(urlPathEqualTo("/api/v3/blueprints/123"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{\"id\": \"123\"}")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ BlueprintsResource br = c.blueprints();
+ InputStream is = new ByteArrayInputStream("{}".getBytes(StandardCharsets.UTF_8));
+ UploadBlueprint ub = br.uploadFromStream("123", "blueprint.json", is);
+ Blueprint b = ub.execute();
+ assertEquals("123", b.getId());
+ }
+
+ @Test
+ public void cloudifyClientBlueprintFromUrl() {
+ wireMockRule.stubFor(put(urlPathEqualTo("/api/v3/blueprints/123"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{\"id\": \"123\"}")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ BlueprintsResource br = c.blueprints();
+ UploadBlueprint ub = br.uploadFromUrl("123", "blueprint.json", "http://localhost:" + port + "/blueprint");
+ Blueprint b = ub.execute();
+ assertEquals("123", b.getId());
+ }
+
+ @Test
+ public void cloudifyClientBlueprintDelete() {
+ wireMockRule.stubFor(delete(urlPathEqualTo("/api/v3/blueprints/123"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{\"id\": \"123\"}")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ BlueprintsResource br = c.blueprints();
+ DeleteBlueprint db = br.deleteById("123");
+ Blueprint b = db.execute();
+ assertEquals("123", b.getId());
+ }
+
+ @Test
+ public void cloudifyClientBlueprintList() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/blueprints"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody("{\"items\": [{\"id\": \"123\"}]}").withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ BlueprintsResource br = c.blueprints();
+ ListBlueprints lb = br.list();
+ Blueprints b = lb.execute();
+ assertEquals("123", b.getItems().get(0).getId());
+ }
+
+ @Test
+ public void cloudifyClientBlueprintGetById() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/blueprints/123"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{\"id\": \"123\"}")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ BlueprintsResource br = c.blueprints();
+ GetBlueprint gb = br.getById("123");
+ Blueprint b = gb.execute();
+ assertEquals("123", b.getId());
+ }
+
+ @Test
+ public void cloudifyClientBlueprintGetMetadataById() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/blueprints/123"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{\"id\": \"123\"}")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ BlueprintsResource br = c.blueprints();
+ GetBlueprint gb = br.getMetadataById("123");
+ Blueprint b = gb.execute();
+ assertEquals("123", b.getId());
+ }
}
diff --git a/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/DeploymentsResourceTest.java b/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/DeploymentsResourceTest.java
index 071b7638e6..2acd4ba5a3 100644
--- a/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/DeploymentsResourceTest.java
+++ b/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/DeploymentsResourceTest.java
@@ -28,10 +28,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
-
import java.util.HashMap;
import java.util.Map;
-
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
@@ -45,104 +43,103 @@ import org.onap.so.cloudify.v3.model.CreateDeploymentParams;
import org.onap.so.cloudify.v3.model.Deployment;
import org.onap.so.cloudify.v3.model.Deployments;
import org.onap.so.cloudify.v3.model.DeploymentOutputs;
-
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class DeploymentsResourceTest {
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Test
- public void cloudifyDeploymentsCreate() {
- wireMockRule.stubFor(put(urlPathEqualTo("/api/v3/deployments/123")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{ \"id\": \"123\" }")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- DeploymentsResource br = c.deployments();
-
- CreateDeploymentParams cdp = new CreateDeploymentParams();
- cdp.setBlueprintId("123");
- Map<String, Object> inputs = new HashMap<String, Object>();
- cdp.setInputs(inputs);
- CreateDeployment cd = br.create("123", cdp);
- Deployment d = cd.execute();
- assertEquals("123", d.getId());
- }
-
- @Test
- public void cloudifyDeploymentsList() {
- wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/deployments")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{ \"items\": {\"id\": \"123\" } } ")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- DeploymentsResource br = c.deployments();
- ListDeployments ld = br.list();
- Deployments d = ld.execute();
- assertEquals("123", d.getItems().get(0).getId());
- }
-
- @Test
- public void cloudifyDeploymentsGet() {
- wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/deployments/123")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{ \"id\": \"123\" }")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- DeploymentsResource br = c.deployments();
- GetDeployment gd = br.byId("123");
- Deployment d = gd.execute();
- assertEquals("123", d.getId());
- }
-
- @Test
- public void cloudifyDeploymentsGetOutputs() {
- wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/deployments/123/outputs")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{ \"deployment_id\": \"123\" }")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- DeploymentsResource br = c.deployments();
- GetDeploymentOutputs gdo = br.outputsById("123");
- DeploymentOutputs d = gdo.execute();
- assertEquals("123", d.getDeploymentId());
-
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("test", "answer");
- assertEquals("answer", d.getMapValue(map, "test", String.class));
-
- Integer i = d.getMapValue(map, "nil", Integer.class);
- assertNull( i );
-
- i = d.getMapValue(map, "test", Integer.class);
- assertNull( i );
- }
-
- @Test
- public void cloudifyDeploymentsDelete() {
- wireMockRule.stubFor(delete(urlPathEqualTo("/api/v3/deployments/name")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{ \"id\": \"123\" }")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- DeploymentsResource br = c.deployments();
- DeleteDeployment cd = br.deleteByName("name");
- Deployment d = cd.execute();
- assertEquals("123", d.getId());
- }
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void cloudifyDeploymentsCreate() {
+ wireMockRule.stubFor(put(urlPathEqualTo("/api/v3/deployments/123"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{ \"id\": \"123\" }")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ DeploymentsResource br = c.deployments();
+
+ CreateDeploymentParams cdp = new CreateDeploymentParams();
+ cdp.setBlueprintId("123");
+ Map<String, Object> inputs = new HashMap<String, Object>();
+ cdp.setInputs(inputs);
+ CreateDeployment cd = br.create("123", cdp);
+ Deployment d = cd.execute();
+ assertEquals("123", d.getId());
+ }
+
+ @Test
+ public void cloudifyDeploymentsList() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/deployments"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody("{ \"items\": {\"id\": \"123\" } } ").withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ DeploymentsResource br = c.deployments();
+ ListDeployments ld = br.list();
+ Deployments d = ld.execute();
+ assertEquals("123", d.getItems().get(0).getId());
+ }
+
+ @Test
+ public void cloudifyDeploymentsGet() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/deployments/123"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{ \"id\": \"123\" }")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ DeploymentsResource br = c.deployments();
+ GetDeployment gd = br.byId("123");
+ Deployment d = gd.execute();
+ assertEquals("123", d.getId());
+ }
+
+ @Test
+ public void cloudifyDeploymentsGetOutputs() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/deployments/123/outputs"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody("{ \"deployment_id\": \"123\" }").withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ DeploymentsResource br = c.deployments();
+ GetDeploymentOutputs gdo = br.outputsById("123");
+ DeploymentOutputs d = gdo.execute();
+ assertEquals("123", d.getDeploymentId());
+
+ Map<String, Object> map = new HashMap<String, Object>();
+ map.put("test", "answer");
+ assertEquals("answer", d.getMapValue(map, "test", String.class));
+
+ Integer i = d.getMapValue(map, "nil", Integer.class);
+ assertNull(i);
+
+ i = d.getMapValue(map, "test", Integer.class);
+ assertNull(i);
+ }
+
+ @Test
+ public void cloudifyDeploymentsDelete() {
+ wireMockRule.stubFor(delete(urlPathEqualTo("/api/v3/deployments/name"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{ \"id\": \"123\" }")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ DeploymentsResource br = c.deployments();
+ DeleteDeployment cd = br.deleteByName("name");
+ Deployment d = cd.execute();
+ assertEquals("123", d.getId());
+ }
}
diff --git a/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/ExecutionsResourceTest.java b/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/ExecutionsResourceTest.java
index 098b5cf387..7b63c6eecb 100644
--- a/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/ExecutionsResourceTest.java
+++ b/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/ExecutionsResourceTest.java
@@ -27,7 +27,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.Assert.assertEquals;
-
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
@@ -42,129 +41,134 @@ import org.onap.so.cloudify.v3.model.CancelExecutionParams;
import org.onap.so.cloudify.v3.model.Execution;
import org.onap.so.cloudify.v3.model.Executions;
import org.onap.so.cloudify.v3.model.StartExecutionParams;
-
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class ExecutionsResourceTest {
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Test
- public void cloudifyClientExecutions() {
- wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/executions")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{\"items\": [{ \"id\": \"345\" }, { \"id\": \"123\" }], \"metadata\": {\"pagination\": {\"total\": 100, \"offset\": 0, \"size\": 25}}}")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- ExecutionsResource xr = c.executions();
- ListExecutions lx = xr.list();
- Executions x = lx.execute();
- assertEquals("123", x.getItems().get(1).getId());
- }
-
- @Test
- public void cloudifyClientExecutionsSorted() {
- wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/executions")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{\"items\": [{ \"id\": \"123\" }, { \"id\": \"345\" }], \"metadata\": {\"pagination\": {\"total\": 100, \"offset\": 0, \"size\": 25}}}")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- ExecutionsResource xr = c.executions();
- ListExecutions lx = xr.listSorted("id");
- Executions x = lx.execute();
- assertEquals("345", x.getItems().get(1).getId());
- }
-
- @Test
- public void cloudifyClientExecutionsFilter() {
- wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/executions")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{\"items\": [{ \"id\": \"121\" }, { \"id\": \"123\" }], \"metadata\": {\"pagination\": {\"total\": 100, \"offset\": 0, \"size\": 25}}}")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- ExecutionsResource xr = c.executions();
- ListExecutions lx = xr.listFiltered("a=b", "id");
- Executions x = lx.execute();
- assertEquals("123", x.getItems().get(1).getId());
- }
-
- @Test
- public void cloudifyClientExecutionById() {
- wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/executions/123")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{ \"id\": \"123\" }")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- ExecutionsResource xr = c.executions();
- GetExecution gx = xr.byId("123");
- Execution x = gx.execute();
- assertEquals("123", x.getId());
- }
-
- @Test
- public void cloudifyClientStartExecution() {
- wireMockRule.stubFor(post(urlPathEqualTo("/api/v3/executions")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{ \"id\": \"123\" }")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- ExecutionsResource xr = c.executions();
-
- StartExecutionParams params = new StartExecutionParams();
- StartExecution sx = xr.start(params);
- Execution x = sx.execute();
- assertEquals("123", x.getId());
- }
-
- @Test
- public void cloudifyClientUpdateExecution() {
- thrown.expect(HttpClientException.class);
- thrown.expectMessage("Unrecognized HTTP Method: PATCH");
-
- wireMockRule.stubFor(patch(urlPathEqualTo("/api/v3/executions")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{ \"id\": \"123\" }")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- ExecutionsResource xr = c.executions();
-
- UpdateExecution ux = xr.updateStatus("123", "good");
- Execution x = ux.execute();
- assertEquals("123", x.getId());
- }
-
- @Test
- public void cloudifyClientCancelExecution() {
- wireMockRule.stubFor(post(urlPathEqualTo("/api/v3/executions/123")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{ \"id\": \"123\" }")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
-
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- ExecutionsResource xr = c.executions();
-
- CancelExecutionParams params = new CancelExecutionParams();
- CancelExecution cx = xr.cancel("123", params);
- Execution x = cx.execute();
- assertEquals("123", x.getId());
- }
-
-
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void cloudifyClientExecutions() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/executions")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json")
+ .withBody(
+ "{\"items\": [{ \"id\": \"345\" }, { \"id\": \"123\" }], \"metadata\": {\"pagination\": {\"total\": 100, \"offset\": 0, \"size\": 25}}}")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ ExecutionsResource xr = c.executions();
+ ListExecutions lx = xr.list();
+ Executions x = lx.execute();
+ assertEquals("123", x.getItems().get(1).getId());
+ }
+
+ @Test
+ public void cloudifyClientExecutionsSorted() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/executions")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json")
+ .withBody(
+ "{\"items\": [{ \"id\": \"123\" }, { \"id\": \"345\" }], \"metadata\": {\"pagination\": {\"total\": 100, \"offset\": 0, \"size\": 25}}}")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ ExecutionsResource xr = c.executions();
+ ListExecutions lx = xr.listSorted("id");
+ Executions x = lx.execute();
+ assertEquals("345", x.getItems().get(1).getId());
+ }
+
+ @Test
+ public void cloudifyClientExecutionsFilter() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/executions")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json")
+ .withBody(
+ "{\"items\": [{ \"id\": \"121\" }, { \"id\": \"123\" }], \"metadata\": {\"pagination\": {\"total\": 100, \"offset\": 0, \"size\": 25}}}")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ ExecutionsResource xr = c.executions();
+ ListExecutions lx = xr.listFiltered("a=b", "id");
+ Executions x = lx.execute();
+ assertEquals("123", x.getItems().get(1).getId());
+ }
+
+ @Test
+ public void cloudifyClientExecutionById() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/executions/123"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{ \"id\": \"123\" }")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ ExecutionsResource xr = c.executions();
+ GetExecution gx = xr.byId("123");
+ Execution x = gx.execute();
+ assertEquals("123", x.getId());
+ }
+
+ @Test
+ public void cloudifyClientStartExecution() {
+ wireMockRule.stubFor(post(urlPathEqualTo("/api/v3/executions"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{ \"id\": \"123\" }")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ ExecutionsResource xr = c.executions();
+
+ StartExecutionParams params = new StartExecutionParams();
+ StartExecution sx = xr.start(params);
+ Execution x = sx.execute();
+ assertEquals("123", x.getId());
+ }
+
+ @Test
+ public void cloudifyClientUpdateExecution() {
+ thrown.expect(HttpClientException.class);
+ thrown.expectMessage("Unrecognized HTTP Method: PATCH");
+
+ wireMockRule.stubFor(patch(urlPathEqualTo("/api/v3/executions"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{ \"id\": \"123\" }")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ ExecutionsResource xr = c.executions();
+
+ UpdateExecution ux = xr.updateStatus("123", "good");
+ Execution x = ux.execute();
+ assertEquals("123", x.getId());
+ }
+
+ @Test
+ public void cloudifyClientCancelExecution() {
+ wireMockRule.stubFor(post(urlPathEqualTo("/api/v3/executions/123"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{ \"id\": \"123\" }")
+ .withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ ExecutionsResource xr = c.executions();
+
+ CancelExecutionParams params = new CancelExecutionParams();
+ CancelExecution cx = xr.cancel("123", params);
+ Execution x = cx.execute();
+ assertEquals("123", x.getId());
+ }
+
+
}
diff --git a/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/NodeInstancesResourceTest.java b/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/NodeInstancesResourceTest.java
index c5f3be4ce2..d38d0401c3 100644
--- a/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/NodeInstancesResourceTest.java
+++ b/cloudify-client/src/test/java/org/onap/so/cloudify/v3/client/NodeInstancesResourceTest.java
@@ -26,7 +26,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.patch;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.Assert.assertEquals;
-
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
@@ -38,61 +37,60 @@ import org.onap.so.cloudify.v3.client.NodeInstancesResource.UpdateNodeInstance;
import org.onap.so.cloudify.v3.model.NodeInstance;
import org.onap.so.cloudify.v3.model.NodeInstances;
import org.onap.so.cloudify.v3.model.UpdateNodeInstanceParams;
-
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class NodeInstancesResourceTest {
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void nodeInstanceGet() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/node-instances/123"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody("{ \"node_instance\": { \"id\": \"123\" } }").withStatus(HttpStatus.SC_OK)));
+
+ int port = wireMockRule.port();
+
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ NodeInstancesResource nir = c.nodeInstances();
+ GetNodeInstance gni = nir.byId("123");
+ NodeInstance ni = gni.execute();
+ assertEquals("123", ni.getId());
+ }
+
+ @Test
+ public void nodeInstanceList() {
+ wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/node-instances"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ // .withBody(" { \"items\": [ { \"node_instance\": { \"id\": \"123\" } } ] } ")
+ .withBody(" { \"items\": [ { \"id\": \"123\" } ] } ").withStatus(HttpStatus.SC_OK)));
- @Test
- public void nodeInstanceGet() {
- wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/node-instances/123")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{ \"node_instance\": { \"id\": \"123\" } }")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
+ int port = wireMockRule.port();
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- NodeInstancesResource nir = c.nodeInstances();
- GetNodeInstance gni = nir.byId("123");
- NodeInstance ni = gni.execute();
- assertEquals("123", ni.getId());
- }
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ NodeInstancesResource nir = c.nodeInstances();
+ ListNodeInstances lni = nir.list();
+ NodeInstances ni = lni.execute();
+ assertEquals("123", ni.getItems().get(0).getId());
+ }
- @Test
- public void nodeInstanceList() {
- wireMockRule.stubFor(get(urlPathEqualTo("/api/v3/node-instances")).willReturn(aResponse().withHeader("Content-Type", "application/json")
-// .withBody(" { \"items\": [ { \"node_instance\": { \"id\": \"123\" } } ] } ")
- .withBody(" { \"items\": [ { \"id\": \"123\" } ] } ")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
+ @Test
+ public void nodeInstanceUpdate() {
+ wireMockRule.stubFor(patch(urlPathEqualTo("/api/v3/node-instances/"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody("{ \"node_instance\": { \"id\": \"123\" } }").withStatus(HttpStatus.SC_OK)));
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- NodeInstancesResource nir = c.nodeInstances();
- ListNodeInstances lni = nir.list();
- NodeInstances ni = lni.execute();
- assertEquals("123", ni.getItems().get(0).getId());
- }
-
- @Test
- public void nodeInstanceUpdate() {
- wireMockRule.stubFor(patch(urlPathEqualTo("/api/v3/node-instances/")).willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{ \"node_instance\": { \"id\": \"123\" } }")
- .withStatus(HttpStatus.SC_OK)));
-
- int port = wireMockRule.port();
+ int port = wireMockRule.port();
- Cloudify c = new Cloudify("http://localhost:"+port, "tenant");
- NodeInstancesResource nir = c.nodeInstances();
- UpdateNodeInstanceParams params = new UpdateNodeInstanceParams();
+ Cloudify c = new Cloudify("http://localhost:" + port, "tenant");
+ NodeInstancesResource nir = c.nodeInstances();
+ UpdateNodeInstanceParams params = new UpdateNodeInstanceParams();
- UpdateNodeInstance uni = nir.update("123", params);
- thrown.expect(HttpClientException.class); /// ???????
- NodeInstance ni = uni.execute();
- }
+ UpdateNodeInstance uni = nir.update("123", params);
+ thrown.expect(HttpClientException.class); /// ???????
+ NodeInstance ni = uni.execute();
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/DefaultProperties.java b/common/src/main/java/org/onap/so/client/DefaultProperties.java
index 84509ead05..7d70cff50f 100644
--- a/common/src/main/java/org/onap/so/client/DefaultProperties.java
+++ b/common/src/main/java/org/onap/so/client/DefaultProperties.java
@@ -25,18 +25,20 @@ import java.net.URL;
public class DefaultProperties implements RestProperties {
- private final URL url;
- public DefaultProperties(URL url) {
- this.url = url;
- }
- @Override
- public URL getEndpoint() throws MalformedURLException {
- return this.url;
- }
-
- @Override
- public String getSystemName() {
- return RestClient.ECOMP_COMPONENT_NAME;
- }
+ private final URL url;
+
+ public DefaultProperties(URL url) {
+ this.url = url;
+ }
+
+ @Override
+ public URL getEndpoint() throws MalformedURLException {
+ return this.url;
+ }
+
+ @Override
+ public String getSystemName() {
+ return RestClient.ECOMP_COMPONENT_NAME;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/HttpClient.java b/common/src/main/java/org/onap/so/client/HttpClient.java
index 6f13a86237..3fb09433e1 100644
--- a/common/src/main/java/org/onap/so/client/HttpClient.java
+++ b/common/src/main/java/org/onap/so/client/HttpClient.java
@@ -23,65 +23,64 @@ package org.onap.so.client;
import java.net.URL;
import java.util.Map;
import java.util.Optional;
-
import static org.apache.commons.lang3.StringUtils.*;
-
import org.onap.so.utils.TargetEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClient extends RestClient {
- protected final Logger log = LoggerFactory.getLogger(HttpClient.class);
+ protected final Logger log = LoggerFactory.getLogger(HttpClient.class);
private TargetEntity targetEntity;
HttpClient(URL host, String contentType, TargetEntity targetEntity) {
- super(host, contentType);
- this.targetEntity = targetEntity;
- }
+ super(host, contentType);
+ this.targetEntity = targetEntity;
+ }
@Override
- public TargetEntity getTargetEntity(){
+ public TargetEntity getTargetEntity() {
return targetEntity;
}
- @Override
- protected void initializeHeaderMap(Map<String, String> headerMap) {
- }
+ @Override
+ protected void initializeHeaderMap(Map<String, String> headerMap) {}
- @Override
- protected Optional<ResponseExceptionMapper> addResponseExceptionMapper() {
- return Optional.empty();
- }
+ @Override
+ protected Optional<ResponseExceptionMapper> addResponseExceptionMapper() {
+ return Optional.empty();
+ }
- /**
- * Adds a basic authentication header to the request.
- * @param auth the encrypted credentials
- * @param key the key for decrypting the credentials
- */
- @Override
- public void addBasicAuthHeader(String auth, String key) {
- if(isNotBlank(auth) && isNotBlank(key)){
- super.addBasicAuthHeader(auth, key);
- }else{
- log.warn("Not adding basic auth to headers.");
- }
- }
+ /**
+ * Adds a basic authentication header to the request.
+ *
+ * @param auth the encrypted credentials
+ * @param key the key for decrypting the credentials
+ */
+ @Override
+ public void addBasicAuthHeader(String auth, String key) {
+ if (isNotBlank(auth) && isNotBlank(key)) {
+ super.addBasicAuthHeader(auth, key);
+ } else {
+ log.warn("Not adding basic auth to headers.");
+ }
+ }
- /**
- * Adds an additional header to the header map
- * @param encoded basic auth value
- */
- public void addAdditionalHeader(String name, String value) {
- try {
- if(isNotBlank(name) && isNotBlank(value)){
- headerMap.put(name, value);
- }else{
- log.warn("Not adding " + name + " to headers.");
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
- }
+ /**
+ * Adds an additional header to the header map
+ *
+ * @param encoded basic auth value
+ */
+ public void addAdditionalHeader(String name, String value) {
+ try {
+ if (isNotBlank(name) && isNotBlank(value)) {
+ headerMap.put(name, value);
+ } else {
+ log.warn("Not adding " + name + " to headers.");
+ }
+ } catch (Exception e) {
+ logger.error(e.getMessage(), e);
+ }
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/PreconditionFailedException.java b/common/src/main/java/org/onap/so/client/PreconditionFailedException.java
index 4ff07a616d..29f4c4d9b9 100644
--- a/common/src/main/java/org/onap/so/client/PreconditionFailedException.java
+++ b/common/src/main/java/org/onap/so/client/PreconditionFailedException.java
@@ -24,12 +24,12 @@ import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
public class PreconditionFailedException extends WebApplicationException {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
- public PreconditionFailedException(String message) {
+ public PreconditionFailedException(String message) {
super(message, Response.Status.PRECONDITION_FAILED);
}
}
diff --git a/common/src/main/java/org/onap/so/client/ResponseExceptionMapper.java b/common/src/main/java/org/onap/so/client/ResponseExceptionMapper.java
index bcc60b6915..2517ebe2d5 100644
--- a/common/src/main/java/org/onap/so/client/ResponseExceptionMapper.java
+++ b/common/src/main/java/org/onap/so/client/ResponseExceptionMapper.java
@@ -21,7 +21,6 @@
package org.onap.so.client;
import java.util.Optional;
-
import javax.ws.rs.BadRequestException;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.InternalServerErrorException;
@@ -33,71 +32,71 @@ import javax.ws.rs.NotSupportedException;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class ResponseExceptionMapper {
- private static final Logger logger = LoggerFactory.getLogger(ResponseExceptionMapper.class);
- public void map(Response response) {
- if (response.getStatus() >= 300) {
- String body = "";
- String message = "empty message";
- try {
- response.bufferEntity();
- if (response.hasEntity()) {
- body = response.readEntity(String.class);
- }
- } catch (IllegalStateException e) {
- body = "failed to read entity stream";
- logger.error(body, e);
- } catch (ProcessingException e) {
- body = "could not buffer stream";
- logger.error(body, e);
- }
- Optional<String> result = this.extractMessage(body);
- if (result.isPresent()) {
- message = result.get();
- }
- Response.Status status = Response.Status.fromStatusCode(response.getStatus());
- WebApplicationException webAppException;
- switch (status) {
- case BAD_REQUEST:
- webAppException = new BadRequestException(message);
- break;
- case UNAUTHORIZED:
- webAppException = new NotAuthorizedException(message);
- break;
- case FORBIDDEN:
- webAppException = new ForbiddenException(message);
- break;
- case NOT_FOUND:
- webAppException = new NotFoundException(message);
- break;
- case METHOD_NOT_ALLOWED:
- webAppException = new NotAllowedException(message);
- break;
- case NOT_ACCEPTABLE:
- webAppException = new NotAcceptableException(message);
- break;
- case PRECONDITION_FAILED:
- webAppException = new PreconditionFailedException(message);
- break;
- case UNSUPPORTED_MEDIA_TYPE:
- webAppException = new NotSupportedException(message);
- break;
- case INTERNAL_SERVER_ERROR:
- webAppException = new InternalServerErrorException(message);
- break;
- case SERVICE_UNAVAILABLE:
- webAppException = new WebApplicationException(message);
- break;
- default:
- webAppException = new WebApplicationException(message);
- }
- throw webAppException;
- }
- }
-
- public abstract Optional<String> extractMessage(String entity);
+ private static final Logger logger = LoggerFactory.getLogger(ResponseExceptionMapper.class);
+
+ public void map(Response response) {
+ if (response.getStatus() >= 300) {
+ String body = "";
+ String message = "empty message";
+ try {
+ response.bufferEntity();
+ if (response.hasEntity()) {
+ body = response.readEntity(String.class);
+ }
+ } catch (IllegalStateException e) {
+ body = "failed to read entity stream";
+ logger.error(body, e);
+ } catch (ProcessingException e) {
+ body = "could not buffer stream";
+ logger.error(body, e);
+ }
+ Optional<String> result = this.extractMessage(body);
+ if (result.isPresent()) {
+ message = result.get();
+ }
+ Response.Status status = Response.Status.fromStatusCode(response.getStatus());
+ WebApplicationException webAppException;
+ switch (status) {
+ case BAD_REQUEST:
+ webAppException = new BadRequestException(message);
+ break;
+ case UNAUTHORIZED:
+ webAppException = new NotAuthorizedException(message);
+ break;
+ case FORBIDDEN:
+ webAppException = new ForbiddenException(message);
+ break;
+ case NOT_FOUND:
+ webAppException = new NotFoundException(message);
+ break;
+ case METHOD_NOT_ALLOWED:
+ webAppException = new NotAllowedException(message);
+ break;
+ case NOT_ACCEPTABLE:
+ webAppException = new NotAcceptableException(message);
+ break;
+ case PRECONDITION_FAILED:
+ webAppException = new PreconditionFailedException(message);
+ break;
+ case UNSUPPORTED_MEDIA_TYPE:
+ webAppException = new NotSupportedException(message);
+ break;
+ case INTERNAL_SERVER_ERROR:
+ webAppException = new InternalServerErrorException(message);
+ break;
+ case SERVICE_UNAVAILABLE:
+ webAppException = new WebApplicationException(message);
+ break;
+ default:
+ webAppException = new WebApplicationException(message);
+ }
+ throw webAppException;
+ }
+ }
+
+ public abstract Optional<String> extractMessage(String entity);
}
diff --git a/common/src/main/java/org/onap/so/client/ResponseExceptionMapperImpl.java b/common/src/main/java/org/onap/so/client/ResponseExceptionMapperImpl.java
index 0392b49629..5927d4d99d 100644
--- a/common/src/main/java/org/onap/so/client/ResponseExceptionMapperImpl.java
+++ b/common/src/main/java/org/onap/so/client/ResponseExceptionMapperImpl.java
@@ -17,11 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.client;
import java.util.Optional;
-
import javax.annotation.Priority;
import javax.ws.rs.ext.Provider;
@@ -29,10 +28,10 @@ import javax.ws.rs.ext.Provider;
@Priority(Integer.MIN_VALUE)
public class ResponseExceptionMapperImpl extends ResponseExceptionMapper {
- @Override
- public Optional<String> extractMessage(String entity) {
- return Optional.of(entity);
- }
-
+ @Override
+ public Optional<String> extractMessage(String entity) {
+ return Optional.of(entity);
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/client/RestClient.java b/common/src/main/java/org/onap/so/client/RestClient.java
index 4284cea847..0b10d85bbf 100644
--- a/common/src/main/java/org/onap/so/client/RestClient.java
+++ b/common/src/main/java/org/onap/so/client/RestClient.java
@@ -58,252 +58,253 @@ import net.jodah.failsafe.RetryPolicy;
public abstract class RestClient {
- private static final String APPLICATION_MERGE_PATCH_JSON = "application/merge-patch+json";
+ private static final String APPLICATION_MERGE_PATCH_JSON = "application/merge-patch+json";
public static final String ECOMP_COMPONENT_NAME = "MSO";
- private static final int MAX_PAYLOAD_SIZE = 1024 * 1024;
- private WebTarget webTarget;
+ private static final int MAX_PAYLOAD_SIZE = 1024 * 1024;
+ private WebTarget webTarget;
- protected final Map<String, String> headerMap;
- protected final Logger logger = LoggerFactory.getLogger(RestClient.class);
- protected URL host;
- protected Optional<URI> path;
- protected String accept;
- protected String contentType;
- protected String requestId = "";
+ protected final Map<String, String> headerMap;
+ protected final Logger logger = LoggerFactory.getLogger(RestClient.class);
+ protected URL host;
+ protected Optional<URI> path;
+ protected String accept;
+ protected String contentType;
+ protected String requestId = "";
protected JaxRsClientLogging jaxRsClientLogging;
protected RestProperties props;
protected RestClient(RestProperties props, Optional<URI> path) {
- headerMap = new HashMap<>();
- try {
- host = props.getEndpoint();
- } catch (MalformedURLException e) {
-
- throw new RuntimeException(e);
- }
- this.props = props;
- this.path = path;
- }
-
- protected RestClient(RestProperties props, Optional<URI> path, String accept, String contentType) {
- this(props, path);
- this.accept = accept;
- this.contentType = contentType;
- this.props = props;
- }
-
- protected RestClient(URL host, String contentType) {
- headerMap = new HashMap<>();
- this.path = Optional.empty();
- this.host = host;
- this.contentType = contentType;
- this.props = new DefaultProperties(host);
- }
-
- /**
- * Override method to return false to disable logging.
- *
- * @return true - to enable logging, false otherwise
- */
- protected boolean enableLogging() {
- return true;
- }
-
- /**
- * Override method to return custom value for max payload size.
- *
- * @return Default value for MAX_PAYLOAD_SIZE = 1024 * 1024
- */
- protected int getMaxPayloadSize()
- {
- return MAX_PAYLOAD_SIZE;
- }
-
- protected Builder getBuilder() {
-
- if (webTarget == null) {
- initializeClient(getClient());
- }
- Builder builder = webTarget.request();
- initializeHeaderMap(headerMap);
- for (Entry<String, String> entry : headerMap.entrySet()) {
- builder.header(entry.getKey(), entry.getValue());
- }
- return builder;
- }
-
- protected WebTarget getWebTarget() {
- return this.webTarget;
- }
-
- protected abstract void initializeHeaderMap(Map<String, String> headerMap);
-
- protected Optional<ResponseExceptionMapper> addResponseExceptionMapper() {
- return Optional.of(new ResponseExceptionMapperImpl());
- }
-
- protected CommonObjectMapperProvider getCommonObjectMapperProvider() {
- return new CommonObjectMapperProvider();
- }
-
- /**
- * Adds a basic authentication header to the request.
- * @param auth the encrypted credentials
- * @param key the key for decrypting the credentials
- */
- protected void addBasicAuthHeader(String auth, String key) {
- try {
- byte[] decryptedAuth = CryptoUtils.decrypt(auth, key).getBytes();
- String authHeaderValue = "Basic " + Base64.getEncoder().encodeToString(decryptedAuth);
- headerMap.put("Authorization", authHeaderValue);
- } catch (GeneralSecurityException e) {
- logger.error(e.getMessage(), e);
- }
- }
-
- protected String getAccept() {
- return accept;
- }
-
- protected String getContentType() {
- return contentType;
- }
-
- protected String getMergeContentType() {
- return APPLICATION_MERGE_PATCH_JSON;
- }
-
- protected Client getClient() {
- return ClientBuilder.newBuilder().build();
- }
-
- protected abstract TargetEntity getTargetEntity();
-
- protected void initializeClient(Client client) {
- if (this.enableLogging()) {
- client.register(new PayloadLoggingFilter(this.getMaxPayloadSize()));
- }
- CommonObjectMapperProvider provider = this.getCommonObjectMapperProvider();
- client.register(new JacksonJsonProvider(provider.getMapper()));
+ headerMap = new HashMap<>();
+ try {
+ host = props.getEndpoint();
+ } catch (MalformedURLException e) {
+
+ throw new RuntimeException(e);
+ }
+ this.props = props;
+ this.path = path;
+ }
+
+ protected RestClient(RestProperties props, Optional<URI> path, String accept, String contentType) {
+ this(props, path);
+ this.accept = accept;
+ this.contentType = contentType;
+ this.props = props;
+ }
+
+ protected RestClient(URL host, String contentType) {
+ headerMap = new HashMap<>();
+ this.path = Optional.empty();
+ this.host = host;
+ this.contentType = contentType;
+ this.props = new DefaultProperties(host);
+ }
+
+ /**
+ * Override method to return false to disable logging.
+ *
+ * @return true - to enable logging, false otherwise
+ */
+ protected boolean enableLogging() {
+ return true;
+ }
+
+ /**
+ * Override method to return custom value for max payload size.
+ *
+ * @return Default value for MAX_PAYLOAD_SIZE = 1024 * 1024
+ */
+ protected int getMaxPayloadSize() {
+ return MAX_PAYLOAD_SIZE;
+ }
+
+ protected Builder getBuilder() {
+
+ if (webTarget == null) {
+ initializeClient(getClient());
+ }
+ Builder builder = webTarget.request();
+ initializeHeaderMap(headerMap);
+ for (Entry<String, String> entry : headerMap.entrySet()) {
+ builder.header(entry.getKey(), entry.getValue());
+ }
+ return builder;
+ }
+
+ protected WebTarget getWebTarget() {
+ return this.webTarget;
+ }
+
+ protected abstract void initializeHeaderMap(Map<String, String> headerMap);
+
+ protected Optional<ResponseExceptionMapper> addResponseExceptionMapper() {
+ return Optional.of(new ResponseExceptionMapperImpl());
+ }
+
+ protected CommonObjectMapperProvider getCommonObjectMapperProvider() {
+ return new CommonObjectMapperProvider();
+ }
+
+ /**
+ * Adds a basic authentication header to the request.
+ *
+ * @param auth the encrypted credentials
+ * @param key the key for decrypting the credentials
+ */
+ protected void addBasicAuthHeader(String auth, String key) {
+ try {
+ byte[] decryptedAuth = CryptoUtils.decrypt(auth, key).getBytes();
+ String authHeaderValue = "Basic " + Base64.getEncoder().encodeToString(decryptedAuth);
+ headerMap.put("Authorization", authHeaderValue);
+ } catch (GeneralSecurityException e) {
+ logger.error(e.getMessage(), e);
+ }
+ }
+
+ protected String getAccept() {
+ return accept;
+ }
+
+ protected String getContentType() {
+ return contentType;
+ }
+
+ protected String getMergeContentType() {
+ return APPLICATION_MERGE_PATCH_JSON;
+ }
+
+ protected Client getClient() {
+ return ClientBuilder.newBuilder().build();
+ }
+
+ protected abstract TargetEntity getTargetEntity();
+
+ protected void initializeClient(Client client) {
+ if (this.enableLogging()) {
+ client.register(new PayloadLoggingFilter(this.getMaxPayloadSize()));
+ }
+ CommonObjectMapperProvider provider = this.getCommonObjectMapperProvider();
+ client.register(new JacksonJsonProvider(provider.getMapper()));
jaxRsClientLogging = new JaxRsClientLogging();
jaxRsClientLogging.setTargetService(getTargetEntity());
client.register(jaxRsClientLogging);
if (!path.isPresent()) {
- webTarget = client.target(host.toString());
- } else {
- webTarget = client.target(UriBuilder.fromUri(host + path.get().toString()));
- }
- if (getAccept() == null || getAccept().isEmpty()) {
- this.accept = MediaType.APPLICATION_JSON;
- }
- if (getContentType() == null || getContentType().isEmpty()) {
- this.contentType = MediaType.APPLICATION_JSON;
- }
- }
-
- protected List<Predicate<Throwable>> retryOn() {
-
- List<Predicate<Throwable>> result = new ArrayList<>();
-
- result.add(e -> {
- return e.getCause() instanceof SocketTimeoutException;
- });
- result.add(e -> {
- return e.getCause() instanceof ConnectException;
- });
- return result;
- }
-
- public Response get() {
- return method("GET", null);
- }
-
- public Response post(Object obj) {
- return method("POST", obj);
- }
-
- public Response patch(Object obj) {
- return method("PATCH", obj);
- }
-
- public Response put(Object obj) {
- return method("PUT", obj);
- }
-
- public Response delete() {
- return method("DELETE", null);
- }
-
- public Response delete(Object obj) {
- return method("DELETE", obj);
- }
-
- public <T> Optional<T> get(Class<T> resultClass) {
- return format(method("GET", null), resultClass);
- }
-
- public <T> Optional<T> get(GenericType<T> resultClass) {
- return format(method("GET", null), resultClass);
- }
-
- public <T> T post(Object obj, Class<T> resultClass) {
- return format(method("POST", obj), resultClass).orElse(null);
- }
-
- public <T> T patch(Object obj, Class<T> resultClass) {
- return format(method("PATCH", obj), resultClass).orElse(null);
- }
-
- public <T> T put(Object obj, Class<T> resultClass) {
- return format(method("PUT", obj), resultClass).orElse(null);
- }
-
- public <T> T put(Object obj, GenericType<T> resultClass) {
- return format(method("PUT", obj), resultClass).orElse(null);
- }
-
- public <T> T delete(Class<T> resultClass) {
- return format(method("DELETE", null), resultClass).orElse(null);
- }
-
- public <T> T delete(Object obj, Class<T> resultClass) {
- return format(method("DELETE", obj), resultClass).orElse(null);
- }
-
- public Response method(String method, Object entity) {
- RetryPolicy policy = new RetryPolicy();
-
- List<Predicate<Throwable>> items = retryOn();
-
- Predicate<Throwable> pred = items.stream().reduce(Predicate::or).orElse(x -> false);
-
- policy.retryOn(error -> pred.test(error));
-
- policy.withDelay(this.props.getDelayBetweenRetries(), TimeUnit.MILLISECONDS)
- .withMaxRetries(this.props.getRetries());
-
- return Failsafe.with(policy).get(buildRequest(method, entity));
- }
-
- protected RestRequest buildRequest(String method, Object entity) {
- return new RestRequest(this, method, entity);
- }
- private <T> Optional<T> format(Response response, Class<T> resultClass) {
- if (this.props.mapNotFoundToEmpty() && response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
- return Optional.empty();
- }
- return Optional.of(response.readEntity(resultClass));
- }
-
- private <T> Optional<T> format(Response response, GenericType<T> resultClass) {
- if (this.props.mapNotFoundToEmpty() && response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
- return Optional.empty();
- }
- return Optional.of(response.readEntity(resultClass));
- }
+ webTarget = client.target(host.toString());
+ } else {
+ webTarget = client.target(UriBuilder.fromUri(host + path.get().toString()));
+ }
+ if (getAccept() == null || getAccept().isEmpty()) {
+ this.accept = MediaType.APPLICATION_JSON;
+ }
+ if (getContentType() == null || getContentType().isEmpty()) {
+ this.contentType = MediaType.APPLICATION_JSON;
+ }
+ }
+
+ protected List<Predicate<Throwable>> retryOn() {
+
+ List<Predicate<Throwable>> result = new ArrayList<>();
+
+ result.add(e -> {
+ return e.getCause() instanceof SocketTimeoutException;
+ });
+ result.add(e -> {
+ return e.getCause() instanceof ConnectException;
+ });
+ return result;
+ }
+
+ public Response get() {
+ return method("GET", null);
+ }
+
+ public Response post(Object obj) {
+ return method("POST", obj);
+ }
+
+ public Response patch(Object obj) {
+ return method("PATCH", obj);
+ }
+
+ public Response put(Object obj) {
+ return method("PUT", obj);
+ }
+
+ public Response delete() {
+ return method("DELETE", null);
+ }
+
+ public Response delete(Object obj) {
+ return method("DELETE", obj);
+ }
+
+ public <T> Optional<T> get(Class<T> resultClass) {
+ return format(method("GET", null), resultClass);
+ }
+
+ public <T> Optional<T> get(GenericType<T> resultClass) {
+ return format(method("GET", null), resultClass);
+ }
+
+ public <T> T post(Object obj, Class<T> resultClass) {
+ return format(method("POST", obj), resultClass).orElse(null);
+ }
+
+ public <T> T patch(Object obj, Class<T> resultClass) {
+ return format(method("PATCH", obj), resultClass).orElse(null);
+ }
+
+ public <T> T put(Object obj, Class<T> resultClass) {
+ return format(method("PUT", obj), resultClass).orElse(null);
+ }
+
+ public <T> T put(Object obj, GenericType<T> resultClass) {
+ return format(method("PUT", obj), resultClass).orElse(null);
+ }
+
+ public <T> T delete(Class<T> resultClass) {
+ return format(method("DELETE", null), resultClass).orElse(null);
+ }
+
+ public <T> T delete(Object obj, Class<T> resultClass) {
+ return format(method("DELETE", obj), resultClass).orElse(null);
+ }
+
+ public Response method(String method, Object entity) {
+ RetryPolicy policy = new RetryPolicy();
+
+ List<Predicate<Throwable>> items = retryOn();
+
+ Predicate<Throwable> pred = items.stream().reduce(Predicate::or).orElse(x -> false);
+
+ policy.retryOn(error -> pred.test(error));
+
+ policy.withDelay(this.props.getDelayBetweenRetries(), TimeUnit.MILLISECONDS)
+ .withMaxRetries(this.props.getRetries());
+
+ return Failsafe.with(policy).get(buildRequest(method, entity));
+ }
+
+ protected RestRequest buildRequest(String method, Object entity) {
+ return new RestRequest(this, method, entity);
+ }
+
+ private <T> Optional<T> format(Response response, Class<T> resultClass) {
+ if (this.props.mapNotFoundToEmpty() && response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
+ return Optional.empty();
+ }
+ return Optional.of(response.readEntity(resultClass));
+ }
+
+ private <T> Optional<T> format(Response response, GenericType<T> resultClass) {
+ if (this.props.mapNotFoundToEmpty() && response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
+ return Optional.empty();
+ }
+ return Optional.of(response.readEntity(resultClass));
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/RestClientSSL.java b/common/src/main/java/org/onap/so/client/RestClientSSL.java
index 8369eba859..abef417325 100644
--- a/common/src/main/java/org/onap/so/client/RestClientSSL.java
+++ b/common/src/main/java/org/onap/so/client/RestClientSSL.java
@@ -26,62 +26,62 @@ import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
-
import javax.net.ssl.SSLContext;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
public abstract class RestClientSSL extends RestClient {
-
- private static final String TRUE = "true";
+
+ private static final String TRUE = "true";
public static final String SSL_KEY_STORE_KEY = "javax.net.ssl.keyStore";
- public static final String SSL_KEY_STORE_PASSWORD_KEY = "javax.net.ssl.keyStorePassword";
- public static final String MSO_LOAD_SSL_CLIENT_KEYSTORE_KEY = "mso.load.ssl.client.keystore";
-
+ public static final String SSL_KEY_STORE_PASSWORD_KEY = "javax.net.ssl.keyStorePassword";
+ public static final String MSO_LOAD_SSL_CLIENT_KEYSTORE_KEY = "mso.load.ssl.client.keystore";
+
+
+ protected RestClientSSL(RestProperties props, Optional<URI> path) {
+ super(props, path);
+ }
+
+ protected RestClientSSL(RestProperties props, Optional<URI> path, String accept, String contentType) {
+ super(props, path, accept, contentType);
+ }
+
+ @Override
+ protected Client getClient() {
+
+ Client client = null;
+ try {
+ String loadSSLKeyStore = System.getProperty(RestClientSSL.MSO_LOAD_SSL_CLIENT_KEYSTORE_KEY);
+ if (loadSSLKeyStore != null && loadSSLKeyStore.equalsIgnoreCase(TRUE)) {
+ KeyStore ks = getKeyStore();
+ if (ks != null) {
+ client = ClientBuilder.newBuilder()
+ .keyStore(ks, System.getProperty(RestClientSSL.SSL_KEY_STORE_PASSWORD_KEY)).build();
+ logger.info("RestClientSSL not using default SSL context - setting keystore here.");
+ return client;
+ }
+ }
+ // Use default SSL context
+ client = ClientBuilder.newBuilder().sslContext(SSLContext.getDefault()).build();
+ logger.info("RestClientSSL using default SSL context!");
+ } catch (NoSuchAlgorithmException e) {
+ throw new RuntimeException(e);
+ }
+ return client;
+ }
- protected RestClientSSL(RestProperties props, Optional<URI> path) {
- super(props, path);
- }
+ private KeyStore getKeyStore() {
+ KeyStore ks = null;
+ char[] password = System.getProperty(RestClientSSL.SSL_KEY_STORE_PASSWORD_KEY).toCharArray();
+ try (FileInputStream fis = new FileInputStream(
+ Paths.get(System.getProperty(RestClientSSL.SSL_KEY_STORE_KEY)).normalize().toString())) {
+ ks = KeyStore.getInstance(KeyStore.getDefaultType());
- protected RestClientSSL(RestProperties props, Optional<URI> path, String accept, String contentType) {
- super(props, path, accept, contentType);
- }
+ ks.load(fis, password);
+ } catch (Exception e) {
+ return null;
+ }
- @Override
- protected Client getClient() {
-
- Client client = null;
- try {
- String loadSSLKeyStore = System.getProperty(RestClientSSL.MSO_LOAD_SSL_CLIENT_KEYSTORE_KEY);
- if(loadSSLKeyStore != null && loadSSLKeyStore.equalsIgnoreCase(TRUE)) {
- KeyStore ks = getKeyStore();
- if(ks != null) {
- client = ClientBuilder.newBuilder().keyStore(ks, System.getProperty(RestClientSSL.SSL_KEY_STORE_PASSWORD_KEY)).build();
- logger.info("RestClientSSL not using default SSL context - setting keystore here.");
- return client;
- }
- }
- //Use default SSL context
- client = ClientBuilder.newBuilder().sslContext(SSLContext.getDefault()).build();
- logger.info("RestClientSSL using default SSL context!");
- } catch (NoSuchAlgorithmException e) {
- throw new RuntimeException(e);
- }
- return client;
- }
-
- private KeyStore getKeyStore() {
- KeyStore ks = null;
- char[] password = System.getProperty(RestClientSSL.SSL_KEY_STORE_PASSWORD_KEY).toCharArray();
- try(FileInputStream fis = new FileInputStream(Paths.get(System.getProperty(RestClientSSL.SSL_KEY_STORE_KEY)).normalize().toString())) {
- ks = KeyStore.getInstance(KeyStore.getDefaultType());
-
- ks.load(fis, password);
- }
- catch(Exception e) {
- return null;
- }
-
- return ks;
- }
+ return ks;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/RestProperties.java b/common/src/main/java/org/onap/so/client/RestProperties.java
index 7043e89b1e..9e4e99cb4e 100644
--- a/common/src/main/java/org/onap/so/client/RestProperties.java
+++ b/common/src/main/java/org/onap/so/client/RestProperties.java
@@ -25,15 +25,19 @@ import java.net.URL;
public interface RestProperties {
- public URL getEndpoint() throws MalformedURLException;
- public String getSystemName();
- public default Integer getRetries() {
- return Integer.valueOf(2);
- }
- public default Long getDelayBetweenRetries() {
- return Long.valueOf(500);
- }
- public default boolean mapNotFoundToEmpty() {
- return false;
- }
+ public URL getEndpoint() throws MalformedURLException;
+
+ public String getSystemName();
+
+ public default Integer getRetries() {
+ return Integer.valueOf(2);
+ }
+
+ public default Long getDelayBetweenRetries() {
+ return Long.valueOf(500);
+ }
+
+ public default boolean mapNotFoundToEmpty() {
+ return false;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/RestPropertiesLoader.java b/common/src/main/java/org/onap/so/client/RestPropertiesLoader.java
index 570b48ecb8..efb50cf04b 100644
--- a/common/src/main/java/org/onap/so/client/RestPropertiesLoader.java
+++ b/common/src/main/java/org/onap/so/client/RestPropertiesLoader.java
@@ -25,55 +25,57 @@ import java.util.ServiceLoader;
public class RestPropertiesLoader {
- /* required to make ServiceLoader thread safe */
- private static final ThreadLocal<ServiceLoader<RestProperties>> services = new ThreadLocal<ServiceLoader<RestProperties>>() {
- @Override
- protected ServiceLoader<RestProperties> initialValue() {
- return ServiceLoader.load(RestProperties.class);
- }
- };
- private RestPropertiesLoader() {
- }
-
- private static class Helper {
- private static final RestPropertiesLoader INSTANCE = new RestPropertiesLoader();
- }
-
- public static RestPropertiesLoader getInstance() {
- return Helper.INSTANCE;
- }
-
- public <T> T getNewImpl(Class<? extends RestProperties> clazz) {
- return this.getImpl(clazz, true);
- }
- public <T> T getImpl(Class<? extends RestProperties> clazz) {
- return this.getImpl(clazz, false);
- }
-
- private <T> T getImpl(Class<? extends RestProperties> clazz, boolean forceNewInstance) {
- T result = null;
- ServiceLoader<RestProperties> loader = this.services.get();
- Iterator<RestProperties> propertyImpls = loader.iterator();
- RestProperties item;
- while (propertyImpls.hasNext()) {
- item = propertyImpls.next();
- if (clazz.isAssignableFrom(item.getClass())) {
- try {
- if (forceNewInstance) {
- result = (T)item.getClass().newInstance();
- } else {
- result = (T)item;
- }
- } catch (InstantiationException | IllegalAccessException e) {
- /* all spi implementations must provide a public
- * no argument constructor
- */
-
- }
- //break;
- }
- }
-
- return result;
- }
+ /* required to make ServiceLoader thread safe */
+ private static final ThreadLocal<ServiceLoader<RestProperties>> services =
+ new ThreadLocal<ServiceLoader<RestProperties>>() {
+ @Override
+ protected ServiceLoader<RestProperties> initialValue() {
+ return ServiceLoader.load(RestProperties.class);
+ }
+ };
+
+ private RestPropertiesLoader() {}
+
+ private static class Helper {
+ private static final RestPropertiesLoader INSTANCE = new RestPropertiesLoader();
+ }
+
+ public static RestPropertiesLoader getInstance() {
+ return Helper.INSTANCE;
+ }
+
+ public <T> T getNewImpl(Class<? extends RestProperties> clazz) {
+ return this.getImpl(clazz, true);
+ }
+
+ public <T> T getImpl(Class<? extends RestProperties> clazz) {
+ return this.getImpl(clazz, false);
+ }
+
+ private <T> T getImpl(Class<? extends RestProperties> clazz, boolean forceNewInstance) {
+ T result = null;
+ ServiceLoader<RestProperties> loader = this.services.get();
+ Iterator<RestProperties> propertyImpls = loader.iterator();
+ RestProperties item;
+ while (propertyImpls.hasNext()) {
+ item = propertyImpls.next();
+ if (clazz.isAssignableFrom(item.getClass())) {
+ try {
+ if (forceNewInstance) {
+ result = (T) item.getClass().newInstance();
+ } else {
+ result = (T) item;
+ }
+ } catch (InstantiationException | IllegalAccessException e) {
+ /*
+ * all spi implementations must provide a public no argument constructor
+ */
+
+ }
+ // break;
+ }
+ }
+
+ return result;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/RestRequest.java b/common/src/main/java/org/onap/so/client/RestRequest.java
index 3864f2e5cc..9d2fa42d00 100644
--- a/common/src/main/java/org/onap/so/client/RestRequest.java
+++ b/common/src/main/java/org/onap/so/client/RestRequest.java
@@ -24,67 +24,68 @@ package org.onap.so.client;
import java.util.Optional;
import java.util.concurrent.Callable;
-
import javax.ws.rs.HttpMethod;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RestRequest implements Callable<Response> {
- private static final Logger logger = LoggerFactory.getLogger(RestRequest.class);
+ private static final Logger logger = LoggerFactory.getLogger(RestRequest.class);
+
+ private final RestClient client;
+ private final String method;
+ private final Object entity;
+
+ public RestRequest(RestClient client, String method, Object entity) {
+ this.client = client;
+ this.method = method;
+ this.entity = entity;
+ }
+
+ @Override
+ public Response call() throws Exception {
+ final Response response;
+ if ("GET".equals(method)) {
+ response = this.client.getBuilder().accept(this.client.getAccept()).get();
+ } else if ("POST".equals(method)) {
+ response = this.client.getBuilder().accept(this.client.getAccept())
+ .post(Entity.entity(entity, this.client.getContentType()));
+ } else if ("PATCH".equals(method)) {
+ response = this.client.getBuilder().header("X-HTTP-Method-Override", "PATCH")
+ .accept(this.client.getAccept()).post(Entity.entity(entity, this.client.getMergeContentType()));
+ } else if ("DELETE".equals(method)) {
+ if (entity == null) {
+ response = this.client.getBuilder().accept(this.client.getAccept()).delete();
- private final RestClient client;
- private final String method;
- private final Object entity;
-
- public RestRequest(RestClient client, String method, Object entity) {
- this.client = client;
- this.method = method;
- this.entity = entity;
- }
- @Override
- public Response call() throws Exception {
- final Response response;
- if ("GET".equals(method)) {
- response = this.client.getBuilder().accept(this.client.getAccept()).get();
- } else if ("POST".equals(method)) {
- response = this.client.getBuilder().accept(this.client.getAccept()).post(Entity.entity(entity, this.client.getContentType()));
- } else if ("PATCH".equals(method)) {
- response = this.client.getBuilder().header("X-HTTP-Method-Override", "PATCH").accept(this.client.getAccept())
- .post(Entity.entity(entity, this.client.getMergeContentType()));
- } else if ("DELETE".equals(method)) {
- if (entity == null) {
- response = this.client.getBuilder().accept(this.client.getAccept()).delete();
+ } else {
+ response = this.client.getBuilder().accept(this.client.getAccept())
+ .build(HttpMethod.DELETE, Entity.entity(entity, this.client.getContentType())).invoke();
+ }
+ } else if ("PUT".equals(method)) {
+ response = this.client.getBuilder().accept(this.client.getAccept())
+ .put(Entity.entity(entity, this.client.getContentType()));
+ } else {
+ response = Response.serverError().entity(method + " not valid").build();
+ }
- } else {
- response = this.client.getBuilder().accept(this.client.getAccept())
- .build(HttpMethod.DELETE, Entity.entity(entity, this.client.getContentType())).invoke();
- }
- } else if ("PUT".equals(method)) {
- response = this.client.getBuilder().accept(this.client.getAccept()).put(Entity.entity(entity, this.client.getContentType()));
- } else {
- response = Response.serverError().entity(method + " not valid").build();
- }
-
- Optional<ResponseExceptionMapper> mapper = this.client.addResponseExceptionMapper();
- if (mapper.isPresent()) {
- try {
- mapper.get().map(response);
- } catch (NotFoundException e) {
- if (this.client.props.mapNotFoundToEmpty() && "GET".equals(method)) {
- logger.debug("RestClient recieved not found on URL: {}", this.client.getWebTarget().getUri());
- return response;
- } else {
- throw e;
- }
- }
- }
+ Optional<ResponseExceptionMapper> mapper = this.client.addResponseExceptionMapper();
+ if (mapper.isPresent()) {
+ try {
+ mapper.get().map(response);
+ } catch (NotFoundException e) {
+ if (this.client.props.mapNotFoundToEmpty() && "GET".equals(method)) {
+ logger.debug("RestClient recieved not found on URL: {}", this.client.getWebTarget().getUri());
+ return response;
+ } else {
+ throw e;
+ }
+ }
+ }
- return response;
- }
+ return response;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIClient.java b/common/src/main/java/org/onap/so/client/aai/AAIClient.java
index 72a381a048..131bc27783 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIClient.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIClient.java
@@ -21,10 +21,8 @@
package org.onap.so.client.aai;
import java.net.URI;
-
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.client.RestClient;
import org.onap.so.client.graphinventory.GraphInventoryClient;
import org.onap.so.client.graphinventory.GraphInventoryVersion;
@@ -35,45 +33,47 @@ import org.slf4j.LoggerFactory;
public class AAIClient extends GraphInventoryClient {
- private static final String AAI_ROOT = "/aai";
- protected static Logger logger = LoggerFactory.getLogger(AAIClient.class);
- protected AAIVersion version;
- protected AAIClient() {
- super(AAIProperties.class);
- }
-
- protected AAIClient(AAIVersion version) {
- super(AAIProperties.class);
- this.version = version;
- }
- @Override
- protected URI constructPath(GraphInventoryUri uri) {
-
- return UriBuilder.fromUri(AAI_ROOT + "/" + this.getVersion().toString() + uri.build().toString()).build();
- }
+ private static final String AAI_ROOT = "/aai";
+ protected static Logger logger = LoggerFactory.getLogger(AAIClient.class);
+ protected AAIVersion version;
+
+ protected AAIClient() {
+ super(AAIProperties.class);
+ }
+
+ protected AAIClient(AAIVersion version) {
+ super(AAIProperties.class);
+ this.version = version;
+ }
+
+ @Override
+ protected URI constructPath(GraphInventoryUri uri) {
+
+ return UriBuilder.fromUri(AAI_ROOT + "/" + this.getVersion().toString() + uri.build().toString()).build();
+ }
+
+ @Override
+ public RestClient createClient(GraphInventoryUri uri) {
+ try {
+ return new AAIRestClient(getRestProperties(), constructPath(uri));
+ } catch (GraphInventoryUriComputationException | NotFoundException e) {
+ logger.debug("failed to construct A&AI uri", e);
+ throw e;
+ }
+ }
+
+ @Override
+ public AAIVersion getVersion() {
+ if (version == null) {
+ return this.<AAIProperties>getRestProperties().getDefaultVersion();
+ } else {
+ return this.version;
+ }
+ }
- @Override
- public RestClient createClient(GraphInventoryUri uri) {
- try {
- return new AAIRestClient(getRestProperties(), constructPath(uri));
- } catch (GraphInventoryUriComputationException | NotFoundException e) {
- logger.debug("failed to construct A&AI uri", e);
- throw e;
- }
- }
-
- @Override
- public AAIVersion getVersion() {
- if (version == null) {
- return this.<AAIProperties>getRestProperties().getDefaultVersion();
- } else {
- return this.version;
- }
- }
-
- @Override
- public String getGraphDBName() {
- return "A&AI";
- }
+ @Override
+ public String getGraphDBName() {
+ return "A&AI";
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java b/common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java
index 6c6cf9024d..7029ffe5e4 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java
@@ -22,42 +22,40 @@ package org.onap.so.client.aai;
import java.io.IOException;
import java.util.Optional;
-
import javax.annotation.Priority;
import javax.ws.rs.ext.Provider;
-
import javax.annotation.Priority;
import javax.ws.rs.ext.Provider;
-
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.onap.so.client.ResponseExceptionMapper;
import org.onap.so.client.aai.entities.AAIError;
import org.slf4j.MDC;
-
import com.fasterxml.jackson.databind.ObjectMapper;
@Provider
@Priority(Integer.MIN_VALUE)
public class AAIClientResponseExceptionMapper extends ResponseExceptionMapper {
- private final String requestId;
- public AAIClientResponseExceptionMapper() {
- this.requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
- }
- @Override
- public Optional<String> extractMessage(String entity) {
-
- String errorString = "Error calling A&AI. Request-Id=" + this.getRequestId() + " ";
- try {
- AAIError error = new ObjectMapper().readValue(entity, AAIError.class);
- AAIErrorFormatter formatter = new AAIErrorFormatter(error);
- return Optional.of(errorString + formatter.getMessage());
- } catch (IOException e) {
- return Optional.of(errorString + entity);
- }
- }
-
- protected String getRequestId() {
- return this.requestId;
- }
+ private final String requestId;
+
+ public AAIClientResponseExceptionMapper() {
+ this.requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
+ }
+
+ @Override
+ public Optional<String> extractMessage(String entity) {
+
+ String errorString = "Error calling A&AI. Request-Id=" + this.getRequestId() + " ";
+ try {
+ AAIError error = new ObjectMapper().readValue(entity, AAIError.class);
+ AAIErrorFormatter formatter = new AAIErrorFormatter(error);
+ return Optional.of(errorString + formatter.getMessage());
+ } catch (IOException e) {
+ return Optional.of(errorString + entity);
+ }
+ }
+
+ protected String getRequestId() {
+ return this.requestId;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperPatchProvider.java b/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperPatchProvider.java
index 9c8345d4b6..bb2b2eca19 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperPatchProvider.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperPatchProvider.java
@@ -24,8 +24,8 @@ import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperPatchPr
public class AAICommonObjectMapperPatchProvider extends GraphInventoryCommonObjectMapperPatchProvider {
-
- public AAICommonObjectMapperPatchProvider() {
- super();
- }
+
+ public AAICommonObjectMapperPatchProvider() {
+ super();
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperProvider.java b/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperProvider.java
index 15bc2ea8ef..b75f40eb39 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperProvider.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAICommonObjectMapperProvider.java
@@ -24,8 +24,8 @@ import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvide
public class AAICommonObjectMapperProvider extends GraphInventoryCommonObjectMapperProvider {
- public AAICommonObjectMapperProvider() {
- super();
- }
+ public AAICommonObjectMapperProvider() {
+ super();
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIConfigurationClient.java b/common/src/main/java/org/onap/so/client/aai/AAIConfigurationClient.java
index b29c8070c8..135341a2f4 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIConfigurationClient.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIConfigurationClient.java
@@ -27,57 +27,58 @@ import org.onap.so.serviceinstancebeans.RequestDetails;
public class AAIConfigurationClient {
- private AAIResourcesClient aaiClient;
-
- private static final String ORCHESTRATION_STATUS = "PreCreated";
-
- public AAIConfigurationClient() {
- aaiClient = new AAIResourcesClient();
- }
-
- public void createConfiguration(RequestDetails requestDetails, String configurationId, String configurationType,
- String configurationSubType) {
-
- AAIResourceUri uri = getConfigurationURI(configurationId);
- Configuration payload = configurePayload(requestDetails, configurationId, configurationType, configurationSubType);
-
- aaiClient.create(uri, payload);
- }
-
- public Configuration configurePayload(RequestDetails requestDetails, String configurationId, String configurationType,
- String configurationSubType) {
-
- Configuration payload = new Configuration();
- payload.setConfigurationId(configurationId);
- payload.setConfigurationType(configurationType);
- payload.setConfigurationSubType(configurationSubType);
- payload.setModelInvariantId(requestDetails.getModelInfo().getModelInvariantId());
- payload.setModelVersionId(requestDetails.getModelInfo().getModelVersionId());
- payload.setOrchestrationStatus(ORCHESTRATION_STATUS);
- payload.setOperationalStatus("");
- payload.setConfigurationSelflink(getConfigurationURI(configurationId).build().getPath());
- payload.setModelCustomizationId(requestDetails.getModelInfo().getModelCustomizationId());
-
- return payload;
- }
-
- public void deleteConfiguration(String uuid) {
- aaiClient.delete(getConfigurationURI(uuid));
- }
-
- public void updateOrchestrationStatus(String uuid, String payload) {
- aaiClient.update(getConfigurationURI(uuid), payload);
- }
-
- public Configuration getConfiguration(String uuid) {
- return aaiClient.get(Configuration.class, getConfigurationURI(uuid)).orElse(null);
- }
-
- public boolean configurationExists(String uuid) {
- return aaiClient.exists(getConfigurationURI(uuid));
- }
-
- public AAIResourceUri getConfigurationURI(String uuid) {
- return AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, uuid);
- }
+ private AAIResourcesClient aaiClient;
+
+ private static final String ORCHESTRATION_STATUS = "PreCreated";
+
+ public AAIConfigurationClient() {
+ aaiClient = new AAIResourcesClient();
+ }
+
+ public void createConfiguration(RequestDetails requestDetails, String configurationId, String configurationType,
+ String configurationSubType) {
+
+ AAIResourceUri uri = getConfigurationURI(configurationId);
+ Configuration payload =
+ configurePayload(requestDetails, configurationId, configurationType, configurationSubType);
+
+ aaiClient.create(uri, payload);
+ }
+
+ public Configuration configurePayload(RequestDetails requestDetails, String configurationId,
+ String configurationType, String configurationSubType) {
+
+ Configuration payload = new Configuration();
+ payload.setConfigurationId(configurationId);
+ payload.setConfigurationType(configurationType);
+ payload.setConfigurationSubType(configurationSubType);
+ payload.setModelInvariantId(requestDetails.getModelInfo().getModelInvariantId());
+ payload.setModelVersionId(requestDetails.getModelInfo().getModelVersionId());
+ payload.setOrchestrationStatus(ORCHESTRATION_STATUS);
+ payload.setOperationalStatus("");
+ payload.setConfigurationSelflink(getConfigurationURI(configurationId).build().getPath());
+ payload.setModelCustomizationId(requestDetails.getModelInfo().getModelCustomizationId());
+
+ return payload;
+ }
+
+ public void deleteConfiguration(String uuid) {
+ aaiClient.delete(getConfigurationURI(uuid));
+ }
+
+ public void updateOrchestrationStatus(String uuid, String payload) {
+ aaiClient.update(getConfigurationURI(uuid), payload);
+ }
+
+ public Configuration getConfiguration(String uuid) {
+ return aaiClient.get(Configuration.class, getConfigurationURI(uuid)).orElse(null);
+ }
+
+ public boolean configurationExists(String uuid) {
+ return aaiClient.exists(getConfigurationURI(uuid));
+ }
+
+ public AAIResourceUri getConfigurationURI(String uuid) {
+ return AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, uuid);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIDSLQueryClient.java b/common/src/main/java/org/onap/so/client/aai/AAIDSLQueryClient.java
index 5f2c623d57..1747d97633 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIDSLQueryClient.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIDSLQueryClient.java
@@ -26,30 +26,31 @@ import org.onap.so.client.graphinventory.GraphInventoryQueryClient;
import org.onap.so.client.graphinventory.entities.DSLQuery;
import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri;
-public class AAIDSLQueryClient extends GraphInventoryQueryClient<AAIDSLQueryClient, DSLQuery, AAIResultWrapper, AAIObjectType> {
-
- public AAIDSLQueryClient() {
- super(new AAIClient());
- }
-
- public AAIDSLQueryClient(AAIVersion version) {
- super(new AAIClient(version));
- }
-
- @Override
- protected GraphInventoryUri getQueryUri() {
- return AAIUriFactory.createResourceUri(AAIObjectType.DSL);
- }
-
-
- @Override
- public AAIResultWrapper createWrapper(String json) {
- return new AAIResultWrapper(json);
- }
-
- @Override
- public AAIObjectType createType(String name) {
- return AAIObjectType.fromTypeName(name);
- }
-
+public class AAIDSLQueryClient
+ extends GraphInventoryQueryClient<AAIDSLQueryClient, DSLQuery, AAIResultWrapper, AAIObjectType> {
+
+ public AAIDSLQueryClient() {
+ super(new AAIClient());
+ }
+
+ public AAIDSLQueryClient(AAIVersion version) {
+ super(new AAIClient(version));
+ }
+
+ @Override
+ protected GraphInventoryUri getQueryUri() {
+ return AAIUriFactory.createResourceUri(AAIObjectType.DSL);
+ }
+
+
+ @Override
+ public AAIResultWrapper createWrapper(String json) {
+ return new AAIResultWrapper(json);
+ }
+
+ @Override
+ public AAIObjectType createType(String name) {
+ return AAIObjectType.fromTypeName(name);
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIErrorFormatter.java b/common/src/main/java/org/onap/so/client/aai/AAIErrorFormatter.java
index 6b3bb545de..2fe3910486 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIErrorFormatter.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIErrorFormatter.java
@@ -21,36 +21,35 @@
package org.onap.so.client.aai;
import java.util.List;
-
import org.onap.so.client.aai.entities.AAIError;
import org.onap.so.client.aai.entities.ServiceException;
public class AAIErrorFormatter {
- private final AAIError error;
- public AAIErrorFormatter(AAIError error) {
- this.error = error;
- }
-
- public String getMessage() {
- if (error.getRequestError() != null &&
- error.getRequestError().getServiceException() != null) {
- ServiceException serviceException = error.getRequestError().getServiceException();
- return this.fillInTemplate(serviceException.getText(), serviceException.getVariables());
- }
-
- return "no parsable error message found";
- }
-
- protected String fillInTemplate(String text, List<String> variables) {
- for (int i = 0; i < variables.size(); i++) {
- variables.set(i, this.format(variables.get(i), variables));
- }
-
- return format(text, variables);
- }
-
- protected String format(String s, List<String> variables) {
- return String.format(s.replaceAll("%(\\d+)", "%$1\\$s"), variables.toArray());
- }
+ private final AAIError error;
+
+ public AAIErrorFormatter(AAIError error) {
+ this.error = error;
+ }
+
+ public String getMessage() {
+ if (error.getRequestError() != null && error.getRequestError().getServiceException() != null) {
+ ServiceException serviceException = error.getRequestError().getServiceException();
+ return this.fillInTemplate(serviceException.getText(), serviceException.getVariables());
+ }
+
+ return "no parsable error message found";
+ }
+
+ protected String fillInTemplate(String text, List<String> variables) {
+ for (int i = 0; i < variables.size(); i++) {
+ variables.set(i, this.format(variables.get(i), variables));
+ }
+
+ return format(text, variables);
+ }
+
+ protected String format(String s, List<String> variables) {
+ return String.format(s.replaceAll("%(\\d+)", "%$1\\$s"), variables.toArray());
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java b/common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java
index 7eadea00ff..923a6805aa 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java
@@ -21,67 +21,88 @@
package org.onap.so.client.aai;
import java.io.Serializable;
-
import org.onap.so.client.graphinventory.GraphInventoryObjectPlurals;
import org.onap.so.constants.Defaults;
-
import com.google.common.base.CaseFormat;
public class AAIObjectPlurals implements GraphInventoryObjectPlurals, Serializable {
- private static final long serialVersionUID = 5312713297525740746L;
-
- public static final AAIObjectPlurals CUSTOMER = new AAIObjectPlurals(AAINamespaceConstants.BUSINESS, "/customers", "customer");
- public static final AAIObjectPlurals GENERIC_VNF = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/generic-vnfs", "generic-vnf");
- public static final AAIObjectPlurals PORT_GROUP = new AAIObjectPlurals(AAIObjectType.VCE.uriTemplate(), "/port-groups", "port-group");
- public static final AAIObjectPlurals PSERVER = new AAIObjectPlurals(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/pservers", "pserver");
- public static final AAIObjectPlurals P_INTERFACE = new AAIObjectPlurals(AAIObjectType.PSERVER.uriTemplate(), "/p-interfaces", "p-interface");
- public static final AAIObjectPlurals L3_NETWORK = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/l3-networks", "l3-network");
- public static final AAIObjectPlurals NETWORK_POLICY = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/network-policies", "network-policy");
- public static final AAIObjectPlurals VPN_BINDING = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/vpn-bindings", "vpn-binding");
- public static final AAIObjectPlurals SERVICE_SUBSCRIPTION = new AAIObjectPlurals(AAIObjectType.CUSTOMER.uriTemplate(), "/service-subscriptions", "service-subscription");
- public static final AAIObjectPlurals SERVICE_INSTANCE = new AAIObjectPlurals(AAIObjectType.SERVICE_SUBSCRIPTION.uriTemplate(), "/service-instances", "service-instance");
- public static final AAIObjectPlurals OWNING_ENTITY = new AAIObjectPlurals(AAINamespaceConstants.BUSINESS, "/owning-entities", "owning-entity");
- public static final AAIObjectPlurals VOLUME_GROUP = new AAIObjectPlurals(AAIObjectType.CLOUD_REGION.uriTemplate(), "/volume-groups", "volume-group");
- public static final AAIObjectPlurals AVAILIBILITY_ZONE = new AAIObjectPlurals(AAIObjectType.CLOUD_REGION.uriTemplate(), "/availability-zones", "availability-zone");
- public static final AAIObjectPlurals VF_MODULE = new AAIObjectPlurals(AAIObjectType.GENERIC_VNF.uriTemplate(), "/vf-modules", "vf-module");
- public static final AAIObjectPlurals CONFIGURATION = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/configurations", "configuration");
- public static final AAIObjectPlurals DEFAULT_TENANT = new AAIObjectPlurals(AAINamespaceConstants.CLOUD_INFRASTRUCTURE + "/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER + "/AAIAIC25", "/tenants", "default-tenant");
- public static final AAIObjectPlurals NETWORK_TECHNOLOGY = new AAIObjectPlurals(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/network-technologies", "network-technology");
- public static final AAIObjectPlurals LOGICAL_LINK = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/logical-links", "logical-link");
- public static final AAIObjectPlurals L_INTERFACE = new AAIObjectPlurals(AAIObjectType.VSERVER.uriTemplate(), "/l-interfaces", "l-interface");
- public static final AAIObjectPlurals SUB_L_INTERFACE = new AAIObjectPlurals(AAIObjectType.L_INTERFACE.uriTemplate(), "/l-interfaces", "l-interface");
+ private static final long serialVersionUID = 5312713297525740746L;
+
+ public static final AAIObjectPlurals CUSTOMER =
+ new AAIObjectPlurals(AAINamespaceConstants.BUSINESS, "/customers", "customer");
+ public static final AAIObjectPlurals GENERIC_VNF =
+ new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/generic-vnfs", "generic-vnf");
+ public static final AAIObjectPlurals PORT_GROUP =
+ new AAIObjectPlurals(AAIObjectType.VCE.uriTemplate(), "/port-groups", "port-group");
+ public static final AAIObjectPlurals PSERVER =
+ new AAIObjectPlurals(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/pservers", "pserver");
+ public static final AAIObjectPlurals P_INTERFACE =
+ new AAIObjectPlurals(AAIObjectType.PSERVER.uriTemplate(), "/p-interfaces", "p-interface");
+ public static final AAIObjectPlurals L3_NETWORK =
+ new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/l3-networks", "l3-network");
+ public static final AAIObjectPlurals NETWORK_POLICY =
+ new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/network-policies", "network-policy");
+ public static final AAIObjectPlurals VPN_BINDING =
+ new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/vpn-bindings", "vpn-binding");
+ public static final AAIObjectPlurals SERVICE_SUBSCRIPTION = new AAIObjectPlurals(
+ AAIObjectType.CUSTOMER.uriTemplate(), "/service-subscriptions", "service-subscription");
+ public static final AAIObjectPlurals SERVICE_INSTANCE = new AAIObjectPlurals(
+ AAIObjectType.SERVICE_SUBSCRIPTION.uriTemplate(), "/service-instances", "service-instance");
+ public static final AAIObjectPlurals OWNING_ENTITY =
+ new AAIObjectPlurals(AAINamespaceConstants.BUSINESS, "/owning-entities", "owning-entity");
+ public static final AAIObjectPlurals VOLUME_GROUP =
+ new AAIObjectPlurals(AAIObjectType.CLOUD_REGION.uriTemplate(), "/volume-groups", "volume-group");
+ public static final AAIObjectPlurals AVAILIBILITY_ZONE =
+ new AAIObjectPlurals(AAIObjectType.CLOUD_REGION.uriTemplate(), "/availability-zones", "availability-zone");
+ public static final AAIObjectPlurals VF_MODULE =
+ new AAIObjectPlurals(AAIObjectType.GENERIC_VNF.uriTemplate(), "/vf-modules", "vf-module");
+ public static final AAIObjectPlurals CONFIGURATION =
+ new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/configurations", "configuration");
+ public static final AAIObjectPlurals DEFAULT_TENANT =
+ new AAIObjectPlurals(AAINamespaceConstants.CLOUD_INFRASTRUCTURE + "/cloud-regions/cloud-region/"
+ + Defaults.CLOUD_OWNER + "/AAIAIC25", "/tenants", "default-tenant");
+ public static final AAIObjectPlurals NETWORK_TECHNOLOGY = new AAIObjectPlurals(
+ AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/network-technologies", "network-technology");
+ public static final AAIObjectPlurals LOGICAL_LINK =
+ new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/logical-links", "logical-link");
+ public static final AAIObjectPlurals L_INTERFACE =
+ new AAIObjectPlurals(AAIObjectType.VSERVER.uriTemplate(), "/l-interfaces", "l-interface");
+ public static final AAIObjectPlurals SUB_L_INTERFACE =
+ new AAIObjectPlurals(AAIObjectType.L_INTERFACE.uriTemplate(), "/l-interfaces", "l-interface");
+
+ private final String uriTemplate;
+ private final String partialUri;
+ private final String name;
+
+ protected AAIObjectPlurals(String parentUri, String partialUri, String name) {
+ this.uriTemplate = parentUri + partialUri;
+ this.partialUri = partialUri;
+ this.name = name;
+ }
- private final String uriTemplate;
- private final String partialUri;
- private final String name;
- protected AAIObjectPlurals(String parentUri, String partialUri, String name) {
- this.uriTemplate = parentUri + partialUri;
- this.partialUri = partialUri;
- this.name = name;
- }
+ @Override
+ public String toString() {
+ return this.uriTemplate();
+ }
- @Override
- public String toString() {
- return this.uriTemplate();
- }
+ @Override
+ public String uriTemplate() {
+ return this.uriTemplate;
+ }
- @Override
- public String uriTemplate() {
- return this.uriTemplate;
- }
+ @Override
+ public String partialUri() {
+ return this.partialUri;
+ }
- @Override
- public String partialUri() {
- return this.partialUri;
- }
+ @Override
+ public String typeName() {
+ return this.typeName(CaseFormat.LOWER_HYPHEN);
+ }
- @Override
- public String typeName() {
- return this.typeName(CaseFormat.LOWER_HYPHEN);
- }
- @Override
- public String typeName(CaseFormat format) {
- return CaseFormat.LOWER_HYPHEN.to(format, this.name);
- }
+ @Override
+ public String typeName(CaseFormat format) {
+ return CaseFormat.LOWER_HYPHEN.to(format, this.name);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java
index 29485f2de8..2ce4d8c6bf 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java
@@ -26,7 +26,6 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
-
import org.onap.aai.annotations.Metadata;
import org.onap.aai.domain.yang.AggregateRoute;
import org.onap.aai.domain.yang.AllottedResource;
@@ -81,157 +80,198 @@ import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
-
import com.google.common.base.CaseFormat;
public class AAIObjectType implements GraphInventoryObjectType, Serializable {
- private static final long serialVersionUID = -2877184776691514600L;
- private static Map<String, AAIObjectType> map = new HashMap<>();
-
- public static final AAIObjectType DEFAULT_CLOUD_REGION = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER + "/{cloud-region-id}", "default-cloud-region");
- public static final AAIObjectType CUSTOMER = new AAIObjectType(AAINamespaceConstants.BUSINESS, Customer.class);
- public static final AAIObjectType GENERIC_QUERY = new AAIObjectType("/search", "/generic-query", "generic-query");
- public static final AAIObjectType BULK_PROCESS = new AAIObjectType("/bulkprocess", "", "bulkprocess");
- public static final AAIObjectType SINGLE_TRANSACTION = new AAIObjectType("/bulk/single-transaction", "", "single-transaction");
- public static final AAIObjectType GENERIC_VNF = new AAIObjectType(AAINamespaceConstants.NETWORK, GenericVnf.class);
- public static final AAIObjectType GENERIC_VNFS = new AAIObjectType(AAINamespaceConstants.NETWORK, "/generic-vnfs", "generic-vnfs");
- public static final AAIObjectType VF_MODULE = new AAIObjectType(AAIObjectType.GENERIC_VNF.uriTemplate(), VfModule.class);
- public static final AAIObjectType L3_NETWORK = new AAIObjectType(AAINamespaceConstants.NETWORK, L3Network.class);
- public static final AAIObjectType NETWORK_POLICY = new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkPolicy.class);
- public static final AAIObjectType NODES_QUERY = new AAIObjectType("/search", "/nodes-query", "nodes-query");
- public static final AAIObjectType CUSTOM_QUERY = new AAIObjectType("/query", "", "query");
- public static final AAIObjectType ROUTE_TABLE_REFERENCE = new AAIObjectType(AAINamespaceConstants.NETWORK, RouteTableReference.class);
- public static final AAIObjectType DEFAULT_TENANT = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE + "/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER + "/AAIAIC25", "/tenants/tenant/{tenant-id}", "default-tenant");
- public static final AAIObjectType VCE = new AAIObjectType(AAINamespaceConstants.NETWORK, Vce.class);
- public static final AAIObjectType PORT_GROUP = new AAIObjectType(AAIObjectType.VCE.uriTemplate(), PortGroup.class);
- public static final AAIObjectType VPN_BINDING = new AAIObjectType(AAINamespaceConstants.NETWORK, VpnBinding.class);
- public static final AAIObjectType CONFIGURATION = new AAIObjectType(AAINamespaceConstants.NETWORK, Configuration.class);
- public static final AAIObjectType PSERVER = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, Pserver.class);
- public static final AAIObjectType SERVICE_SUBSCRIPTION = new AAIObjectType(AAIObjectType.CUSTOMER.uriTemplate(), ServiceSubscription.class);
- public static final AAIObjectType SERVICE_INSTANCE = new AAIObjectType(AAIObjectType.SERVICE_SUBSCRIPTION.uriTemplate(), ServiceInstance.class);
- public static final AAIObjectType PROJECT = new AAIObjectType(AAINamespaceConstants.BUSINESS, Project.class);
- public static final AAIObjectType LINE_OF_BUSINESS = new AAIObjectType(AAINamespaceConstants.BUSINESS, LineOfBusiness.class);
- public static final AAIObjectType PLATFORM = new AAIObjectType(AAINamespaceConstants.BUSINESS, Platform.class);
- public static final AAIObjectType OWNING_ENTITY = new AAIObjectType(AAINamespaceConstants.BUSINESS, OwningEntity.class);
- public static final AAIObjectType ALLOTTED_RESOURCE = new AAIObjectType(AAIObjectType.SERVICE_INSTANCE.uriTemplate(), AllottedResource.class);
- public static final AAIObjectType PNF = new AAIObjectType(AAINamespaceConstants.NETWORK, Pnf.class);
- public static final AAIObjectType OPERATIONAL_ENVIRONMENT = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, OperationalEnvironment.class);
- public static final AAIObjectType CLOUD_REGION = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, CloudRegion.class);
- public static final AAIObjectType TENANT = new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), Tenant.class);
- public static final AAIObjectType VOLUME_GROUP = new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), VolumeGroup.class);
- public static final AAIObjectType VSERVER = new AAIObjectType(AAIObjectType.TENANT.uriTemplate(), Vserver.class);
- public static final AAIObjectType MODEL_VER = new AAIObjectType(AAINamespaceConstants.SERVICE_DESIGN_AND_CREATION + "/models/model/{model-invariant-id}", ModelVer.class);
- public static final AAIObjectType TUNNEL_XCONNECT = new AAIObjectType(AAIObjectType.ALLOTTED_RESOURCE.uriTemplate(), TunnelXconnect.class);
- public static final AAIObjectType P_INTERFACE = new AAIObjectType(AAIObjectType.PSERVER.uriTemplate(), PInterface.class);
- public static final AAIObjectType SRIOV_PF = new AAIObjectType(AAIObjectType.P_INTERFACE.uriTemplate(), SriovPf.class);
- public static final AAIObjectType PHYSICAL_LINK = new AAIObjectType(AAINamespaceConstants.NETWORK, PhysicalLink.class);
- public static final AAIObjectType INSTANCE_GROUP = new AAIObjectType(AAINamespaceConstants.NETWORK, InstanceGroup.class);
- public static final AAIObjectType COLLECTION = new AAIObjectType(AAINamespaceConstants.NETWORK, Collection.class);
- public static final AAIObjectType VNFC = new AAIObjectType(AAINamespaceConstants.NETWORK, Vnfc.class);
- public static final AAIObjectType VLAN_TAG = new AAIObjectType(AAINamespaceConstants.NETWORK, VlanTag.class);
- public static final AAIObjectType COMPLEX = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, Complex.class);
- public static final AAIObjectType CONNECTOR = new AAIObjectType(AAINamespaceConstants.BUSINESS, Connector.class);
- public static final AAIObjectType NETWORK_TECHNOLOGY = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, NetworkTechnology.class);
- public static final AAIObjectType SUBNET = new AAIObjectType(AAIObjectType.L3_NETWORK.uriTemplate(), Subnet.class);
- public static final AAIObjectType SP_PARTNER = new AAIObjectType(AAINamespaceConstants.BUSINESS, SpPartner.class);
- public static final AAIObjectType DEVICE = new AAIObjectType(AAINamespaceConstants.NETWORK, Device.class);
- public static final AAIObjectType EXT_AAI_NETWORK = new AAIObjectType(AAINamespaceConstants.NETWORK, ExtAaiNetwork.class);
- public static final AAIObjectType AGGREGATE_ROUTE = new AAIObjectType(AAINamespaceConstants.NETWORK, AggregateRoute.class);
- public static final AAIObjectType L_INTERFACE = new AAIObjectType(AAIObjectType.VSERVER.uriTemplate(), LInterface.class);
- public static final AAIObjectType SUB_L_INTERFACE = new AAIObjectType(AAIObjectType.L_INTERFACE.uriTemplate(), "/l-interfaces/l-interface/{sub-interface-name}", "sub-l-interface");
- public static final AAIObjectType IMAGE = new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), Image.class);
- public static final AAIObjectType FLAVOR = new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), Flavor.class);
- public static final AAIObjectType UNKNOWN = new AAIObjectType("", "", "unknown");
- public static final AAIObjectType DSL = new AAIObjectType("/dsl", "", "dsl");
- public static final AAIObjectType VNFM = new AAIObjectType(AAINamespaceConstants.EXTERNAL_SYSTEM + "/esr-vnfm-list/esr-vnfm/{vnfm-id}", EsrVnfm.class);
- public static final AAIObjectType VNFM_LIST = new AAIObjectType(AAINamespaceConstants.EXTERNAL_SYSTEM, "/esr-vnfm-list", "vnfm-list");
- public static final AAIObjectType VNFM_ESR_SYSTEM_INFO_LIST = new AAIObjectType(AAINamespaceConstants.EXTERNAL_SYSTEM + "/esr-vnfm-list", "/esr-vnfm/{vnfm-id}/esr-system-info-list", "vnfm-esr-system-info-list");
- public static final AAIObjectType CLOUD_ESR_SYSTEM_INFO_LIST = new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), "/esr-system-info-list", "cloud-esr-system-info-list");
-
-
- private final String uriTemplate;
- private final String parentUri;
- private final String partialUri;
- private final Class<?> aaiObjectClass;
- private final String name;
-
- static {
- /* Locate any AAIObjectTypes on the classpath and add them to our map */
- java.util.Collection<URL> packages = ClasspathHelper.forPackage("");
- Reflections r = new Reflections(new ConfigurationBuilder().setUrls(packages).setScanners(new SubTypesScanner()));
-
- Set<Class<? extends AAIObjectType>> resources =
- r.getSubTypesOf(AAIObjectType.class);
- try {
- for (Class<? extends AAIObjectType> customTypeClass : resources) {
- AAIObjectType customType;
- customType = customTypeClass.newInstance();
- }
- } catch (InstantiationException | IllegalAccessException e) {
- }
- }
- protected AAIObjectType() {
- this.parentUri = null;
- this.partialUri = null;
- this.uriTemplate = null;
- this.aaiObjectClass = null;
- this.name = null;
- }
- protected AAIObjectType(String parentUri, String partialUri, String name) {
- this.parentUri = parentUri;
- this.partialUri = partialUri;
- this.uriTemplate = parentUri + partialUri;
- this.aaiObjectClass = null;
- this.name = name;
- if (!AAIObjectType.map.containsKey(name)) {
- AAIObjectType.map.put(name, this);
- }
- }
-
- protected AAIObjectType(String parentUri, Class<?> aaiObjectClass) {
- this.parentUri = parentUri;
- this.partialUri = removeParentUri(aaiObjectClass, parentUri);
- this.uriTemplate = parentUri + partialUri;
- this.aaiObjectClass = aaiObjectClass;
- this.name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, aaiObjectClass.getSimpleName());
- if (!AAIObjectType.map.containsKey(name)) {
- AAIObjectType.map.put(name, this);
- }
- }
-
- @Override
- public String toString() {
- return this.uriTemplate();
- }
-
- public static AAIObjectType fromTypeName(String name) {
- if (map.containsKey(name)) {
- return map.get(name);
- } else {
- return AAIObjectType.UNKNOWN;
- }
- }
- @Override
- public String typeName() {
- return this.typeName(CaseFormat.LOWER_HYPHEN);
- }
- @Override
- public String typeName(CaseFormat format) {
- return CaseFormat.LOWER_HYPHEN.to(format, this.name.replace("default-", ""));
- }
-
- @Override
- public String uriTemplate() {
- return this.uriTemplate;
- }
-
- @Override
- public String partialUri() {
- return this.partialUri;
- }
-
- protected String removeParentUri(Class<?> aaiObjectClass, String parentUri) {
- return aaiObjectClass.getAnnotation(Metadata.class).uriTemplate().replaceFirst(Pattern.quote(parentUri), "");
- }
+ private static final long serialVersionUID = -2877184776691514600L;
+ private static Map<String, AAIObjectType> map = new HashMap<>();
+
+ public static final AAIObjectType DEFAULT_CLOUD_REGION = new AAIObjectType(
+ AAINamespaceConstants.CLOUD_INFRASTRUCTURE,
+ "/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER + "/{cloud-region-id}", "default-cloud-region");
+ public static final AAIObjectType CUSTOMER = new AAIObjectType(AAINamespaceConstants.BUSINESS, Customer.class);
+ public static final AAIObjectType GENERIC_QUERY = new AAIObjectType("/search", "/generic-query", "generic-query");
+ public static final AAIObjectType BULK_PROCESS = new AAIObjectType("/bulkprocess", "", "bulkprocess");
+ public static final AAIObjectType SINGLE_TRANSACTION =
+ new AAIObjectType("/bulk/single-transaction", "", "single-transaction");
+ public static final AAIObjectType GENERIC_VNF = new AAIObjectType(AAINamespaceConstants.NETWORK, GenericVnf.class);
+ public static final AAIObjectType GENERIC_VNFS =
+ new AAIObjectType(AAINamespaceConstants.NETWORK, "/generic-vnfs", "generic-vnfs");
+ public static final AAIObjectType VF_MODULE =
+ new AAIObjectType(AAIObjectType.GENERIC_VNF.uriTemplate(), VfModule.class);
+ public static final AAIObjectType L3_NETWORK = new AAIObjectType(AAINamespaceConstants.NETWORK, L3Network.class);
+ public static final AAIObjectType NETWORK_POLICY =
+ new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkPolicy.class);
+ public static final AAIObjectType NODES_QUERY = new AAIObjectType("/search", "/nodes-query", "nodes-query");
+ public static final AAIObjectType CUSTOM_QUERY = new AAIObjectType("/query", "", "query");
+ public static final AAIObjectType ROUTE_TABLE_REFERENCE =
+ new AAIObjectType(AAINamespaceConstants.NETWORK, RouteTableReference.class);
+ public static final AAIObjectType DEFAULT_TENANT =
+ new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE + "/cloud-regions/cloud-region/"
+ + Defaults.CLOUD_OWNER + "/AAIAIC25", "/tenants/tenant/{tenant-id}", "default-tenant");
+ public static final AAIObjectType VCE = new AAIObjectType(AAINamespaceConstants.NETWORK, Vce.class);
+ public static final AAIObjectType PORT_GROUP = new AAIObjectType(AAIObjectType.VCE.uriTemplate(), PortGroup.class);
+ public static final AAIObjectType VPN_BINDING = new AAIObjectType(AAINamespaceConstants.NETWORK, VpnBinding.class);
+ public static final AAIObjectType CONFIGURATION =
+ new AAIObjectType(AAINamespaceConstants.NETWORK, Configuration.class);
+ public static final AAIObjectType PSERVER =
+ new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, Pserver.class);
+ public static final AAIObjectType SERVICE_SUBSCRIPTION =
+ new AAIObjectType(AAIObjectType.CUSTOMER.uriTemplate(), ServiceSubscription.class);
+ public static final AAIObjectType SERVICE_INSTANCE =
+ new AAIObjectType(AAIObjectType.SERVICE_SUBSCRIPTION.uriTemplate(), ServiceInstance.class);
+ public static final AAIObjectType PROJECT = new AAIObjectType(AAINamespaceConstants.BUSINESS, Project.class);
+ public static final AAIObjectType LINE_OF_BUSINESS =
+ new AAIObjectType(AAINamespaceConstants.BUSINESS, LineOfBusiness.class);
+ public static final AAIObjectType PLATFORM = new AAIObjectType(AAINamespaceConstants.BUSINESS, Platform.class);
+ public static final AAIObjectType OWNING_ENTITY =
+ new AAIObjectType(AAINamespaceConstants.BUSINESS, OwningEntity.class);
+ public static final AAIObjectType ALLOTTED_RESOURCE =
+ new AAIObjectType(AAIObjectType.SERVICE_INSTANCE.uriTemplate(), AllottedResource.class);
+ public static final AAIObjectType PNF = new AAIObjectType(AAINamespaceConstants.NETWORK, Pnf.class);
+ public static final AAIObjectType OPERATIONAL_ENVIRONMENT =
+ new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, OperationalEnvironment.class);
+ public static final AAIObjectType CLOUD_REGION =
+ new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, CloudRegion.class);
+ public static final AAIObjectType TENANT =
+ new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), Tenant.class);
+ public static final AAIObjectType VOLUME_GROUP =
+ new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), VolumeGroup.class);
+ public static final AAIObjectType VSERVER = new AAIObjectType(AAIObjectType.TENANT.uriTemplate(), Vserver.class);
+ public static final AAIObjectType MODEL_VER = new AAIObjectType(
+ AAINamespaceConstants.SERVICE_DESIGN_AND_CREATION + "/models/model/{model-invariant-id}", ModelVer.class);
+ public static final AAIObjectType TUNNEL_XCONNECT =
+ new AAIObjectType(AAIObjectType.ALLOTTED_RESOURCE.uriTemplate(), TunnelXconnect.class);
+ public static final AAIObjectType P_INTERFACE =
+ new AAIObjectType(AAIObjectType.PSERVER.uriTemplate(), PInterface.class);
+ public static final AAIObjectType SRIOV_PF =
+ new AAIObjectType(AAIObjectType.P_INTERFACE.uriTemplate(), SriovPf.class);
+ public static final AAIObjectType PHYSICAL_LINK =
+ new AAIObjectType(AAINamespaceConstants.NETWORK, PhysicalLink.class);
+ public static final AAIObjectType INSTANCE_GROUP =
+ new AAIObjectType(AAINamespaceConstants.NETWORK, InstanceGroup.class);
+ public static final AAIObjectType COLLECTION = new AAIObjectType(AAINamespaceConstants.NETWORK, Collection.class);
+ public static final AAIObjectType VNFC = new AAIObjectType(AAINamespaceConstants.NETWORK, Vnfc.class);
+ public static final AAIObjectType VLAN_TAG = new AAIObjectType(AAINamespaceConstants.NETWORK, VlanTag.class);
+ public static final AAIObjectType COMPLEX =
+ new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, Complex.class);
+ public static final AAIObjectType CONNECTOR = new AAIObjectType(AAINamespaceConstants.BUSINESS, Connector.class);
+ public static final AAIObjectType NETWORK_TECHNOLOGY =
+ new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, NetworkTechnology.class);
+ public static final AAIObjectType SUBNET = new AAIObjectType(AAIObjectType.L3_NETWORK.uriTemplate(), Subnet.class);
+ public static final AAIObjectType SP_PARTNER = new AAIObjectType(AAINamespaceConstants.BUSINESS, SpPartner.class);
+ public static final AAIObjectType DEVICE = new AAIObjectType(AAINamespaceConstants.NETWORK, Device.class);
+ public static final AAIObjectType EXT_AAI_NETWORK =
+ new AAIObjectType(AAINamespaceConstants.NETWORK, ExtAaiNetwork.class);
+ public static final AAIObjectType AGGREGATE_ROUTE =
+ new AAIObjectType(AAINamespaceConstants.NETWORK, AggregateRoute.class);
+ public static final AAIObjectType L_INTERFACE =
+ new AAIObjectType(AAIObjectType.VSERVER.uriTemplate(), LInterface.class);
+ public static final AAIObjectType SUB_L_INTERFACE = new AAIObjectType(AAIObjectType.L_INTERFACE.uriTemplate(),
+ "/l-interfaces/l-interface/{sub-interface-name}", "sub-l-interface");
+ public static final AAIObjectType IMAGE = new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), Image.class);
+ public static final AAIObjectType FLAVOR =
+ new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), Flavor.class);
+ public static final AAIObjectType UNKNOWN = new AAIObjectType("", "", "unknown");
+ public static final AAIObjectType DSL = new AAIObjectType("/dsl", "", "dsl");
+ public static final AAIObjectType VNFM = new AAIObjectType(
+ AAINamespaceConstants.EXTERNAL_SYSTEM + "/esr-vnfm-list/esr-vnfm/{vnfm-id}", EsrVnfm.class);
+ public static final AAIObjectType VNFM_LIST =
+ new AAIObjectType(AAINamespaceConstants.EXTERNAL_SYSTEM, "/esr-vnfm-list", "vnfm-list");
+ public static final AAIObjectType VNFM_ESR_SYSTEM_INFO_LIST =
+ new AAIObjectType(AAINamespaceConstants.EXTERNAL_SYSTEM + "/esr-vnfm-list",
+ "/esr-vnfm/{vnfm-id}/esr-system-info-list", "vnfm-esr-system-info-list");
+ public static final AAIObjectType CLOUD_ESR_SYSTEM_INFO_LIST = new AAIObjectType(
+ AAIObjectType.CLOUD_REGION.uriTemplate(), "/esr-system-info-list", "cloud-esr-system-info-list");
+
+
+ private final String uriTemplate;
+ private final String parentUri;
+ private final String partialUri;
+ private final Class<?> aaiObjectClass;
+ private final String name;
+
+ static {
+ /* Locate any AAIObjectTypes on the classpath and add them to our map */
+ java.util.Collection<URL> packages = ClasspathHelper.forPackage("");
+ Reflections r =
+ new Reflections(new ConfigurationBuilder().setUrls(packages).setScanners(new SubTypesScanner()));
+
+ Set<Class<? extends AAIObjectType>> resources = r.getSubTypesOf(AAIObjectType.class);
+ try {
+ for (Class<? extends AAIObjectType> customTypeClass : resources) {
+ AAIObjectType customType;
+ customType = customTypeClass.newInstance();
+ }
+ } catch (InstantiationException | IllegalAccessException e) {
+ }
+ }
+
+ protected AAIObjectType() {
+ this.parentUri = null;
+ this.partialUri = null;
+ this.uriTemplate = null;
+ this.aaiObjectClass = null;
+ this.name = null;
+ }
+
+ protected AAIObjectType(String parentUri, String partialUri, String name) {
+ this.parentUri = parentUri;
+ this.partialUri = partialUri;
+ this.uriTemplate = parentUri + partialUri;
+ this.aaiObjectClass = null;
+ this.name = name;
+ if (!AAIObjectType.map.containsKey(name)) {
+ AAIObjectType.map.put(name, this);
+ }
+ }
+
+ protected AAIObjectType(String parentUri, Class<?> aaiObjectClass) {
+ this.parentUri = parentUri;
+ this.partialUri = removeParentUri(aaiObjectClass, parentUri);
+ this.uriTemplate = parentUri + partialUri;
+ this.aaiObjectClass = aaiObjectClass;
+ this.name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, aaiObjectClass.getSimpleName());
+ if (!AAIObjectType.map.containsKey(name)) {
+ AAIObjectType.map.put(name, this);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return this.uriTemplate();
+ }
+
+ public static AAIObjectType fromTypeName(String name) {
+ if (map.containsKey(name)) {
+ return map.get(name);
+ } else {
+ return AAIObjectType.UNKNOWN;
+ }
+ }
+
+ @Override
+ public String typeName() {
+ return this.typeName(CaseFormat.LOWER_HYPHEN);
+ }
+
+ @Override
+ public String typeName(CaseFormat format) {
+ return CaseFormat.LOWER_HYPHEN.to(format, this.name.replace("default-", ""));
+ }
+
+ @Override
+ public String uriTemplate() {
+ return this.uriTemplate;
+ }
+
+ @Override
+ public String partialUri() {
+ return this.partialUri;
+ }
+
+ protected String removeParentUri(Class<?> aaiObjectClass, String parentUri) {
+ return aaiObjectClass.getAnnotation(Metadata.class).uriTemplate().replaceFirst(Pattern.quote(parentUri), "");
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIProperties.java b/common/src/main/java/org/onap/so/client/aai/AAIProperties.java
index 9f6708200c..6505818758 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIProperties.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIProperties.java
@@ -24,11 +24,14 @@ import org.onap.so.client.RestProperties;
public interface AAIProperties extends RestProperties {
- public AAIVersion getDefaultVersion();
- public String getAuth();
- public String getKey();
- @Override
- public default boolean mapNotFoundToEmpty() {
- return true;
- }
+ public AAIVersion getDefaultVersion();
+
+ public String getAuth();
+
+ public String getKey();
+
+ @Override
+ public default boolean mapNotFoundToEmpty() {
+ return true;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIQueryClient.java b/common/src/main/java/org/onap/so/client/aai/AAIQueryClient.java
index cc855e444a..634a65831f 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIQueryClient.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIQueryClient.java
@@ -26,34 +26,35 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.onap.so.client.graphinventory.GraphInventoryQueryClient;
import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri;
-public class AAIQueryClient extends GraphInventoryQueryClient<AAIQueryClient, CustomQuery, AAIResultWrapper, AAIObjectType> {
-
- public AAIQueryClient() {
- super(new AAIClient());
- }
-
- public AAIQueryClient(AAIVersion version) {
- super(new AAIClient(version));
- }
-
- @Override
- protected GraphInventoryUri getQueryUri() {
- return AAIUriFactory.createResourceUri(AAIObjectType.CUSTOM_QUERY);
- }
-
- @Override
- protected GraphInventoryUri setupQueryParams(GraphInventoryUri uri) {
- return super.setupQueryParams(uri);
- }
-
- @Override
- public AAIResultWrapper createWrapper(String json) {
- return new AAIResultWrapper(json);
- }
-
- @Override
- public AAIObjectType createType(String name) {
- return AAIObjectType.fromTypeName(name);
- }
-
+public class AAIQueryClient
+ extends GraphInventoryQueryClient<AAIQueryClient, CustomQuery, AAIResultWrapper, AAIObjectType> {
+
+ public AAIQueryClient() {
+ super(new AAIClient());
+ }
+
+ public AAIQueryClient(AAIVersion version) {
+ super(new AAIClient(version));
+ }
+
+ @Override
+ protected GraphInventoryUri getQueryUri() {
+ return AAIUriFactory.createResourceUri(AAIObjectType.CUSTOM_QUERY);
+ }
+
+ @Override
+ protected GraphInventoryUri setupQueryParams(GraphInventoryUri uri) {
+ return super.setupQueryParams(uri);
+ }
+
+ @Override
+ public AAIResultWrapper createWrapper(String json) {
+ return new AAIResultWrapper(json);
+ }
+
+ @Override
+ public AAIObjectType createType(String name) {
+ return AAIObjectType.fromTypeName(name);
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIQueryObjectMapperProvider.java b/common/src/main/java/org/onap/so/client/aai/AAIQueryObjectMapperProvider.java
index d5eeb83041..8f16d815b6 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIQueryObjectMapperProvider.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIQueryObjectMapperProvider.java
@@ -27,13 +27,13 @@ import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
public class AAIQueryObjectMapperProvider extends AAICommonObjectMapperProvider {
- public AAIQueryObjectMapperProvider() {
- super();
- AnnotationIntrospector aiJaxb = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
+ public AAIQueryObjectMapperProvider() {
+ super();
+ AnnotationIntrospector aiJaxb = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
AnnotationIntrospector aiJackson = new JacksonAnnotationIntrospector();
// first Jaxb, second Jackson annotations
mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(aiJaxb, aiJackson));
- }
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java b/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java
index ee1736feeb..5b302f663e 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java
@@ -21,7 +21,6 @@
package org.onap.so.client.aai;
import java.util.Optional;
-
import org.onap.aai.domain.yang.Relationship;
import org.onap.so.client.aai.entities.AAIEdgeLabel;
import org.onap.so.client.aai.entities.AAIResultWrapper;
@@ -30,48 +29,49 @@ import org.onap.so.client.graphinventory.GraphInventoryResourcesClient;
import org.onap.so.client.graphinventory.entities.GraphInventoryEdgeLabel;
import org.onap.so.client.graphinventory.entities.uri.GraphInventoryResourceUri;
-public class AAIResourcesClient extends GraphInventoryResourcesClient<AAIResourcesClient, AAIResourceUri, AAIEdgeLabel, AAIResultWrapper, AAITransactionalClient, AAISingleTransactionClient> {
-
- private AAIClient aaiClient;
-
- public AAIResourcesClient() {
- super(new AAIClient());
- aaiClient = (AAIClient) super.client;
- }
-
- public AAIResourcesClient(AAIVersion version) {
- super(new AAIClient(version));
- aaiClient = (AAIClient) super.client;
- }
+public class AAIResourcesClient extends
+ GraphInventoryResourcesClient<AAIResourcesClient, AAIResourceUri, AAIEdgeLabel, AAIResultWrapper, AAITransactionalClient, AAISingleTransactionClient> {
+
+ private AAIClient aaiClient;
+
+ public AAIResourcesClient() {
+ super(new AAIClient());
+ aaiClient = (AAIClient) super.client;
+ }
+
+ public AAIResourcesClient(AAIVersion version) {
+ super(new AAIClient(version));
+ aaiClient = (AAIClient) super.client;
+ }
+
+ @Override
+ public AAIResultWrapper createWrapper(String json) {
+ return new AAIResultWrapper(json);
+ }
+
+ @Override
+ public AAITransactionalClient beginTransaction() {
+ return new AAITransactionalClient(this, aaiClient);
+ }
+
+ @Override
+ public AAISingleTransactionClient beginSingleTransaction() {
+ return new AAISingleTransactionClient(this, aaiClient);
+ }
+
+ @Override
+ protected Relationship buildRelationship(GraphInventoryResourceUri uri) {
+ return super.buildRelationship(uri, Optional.empty());
+ }
- @Override
- public AAIResultWrapper createWrapper(String json) {
- return new AAIResultWrapper(json);
- }
+ @Override
+ protected Relationship buildRelationship(GraphInventoryResourceUri uri, GraphInventoryEdgeLabel label) {
+ return super.buildRelationship(uri, Optional.of(label));
+ }
- @Override
- public AAITransactionalClient beginTransaction() {
- return new AAITransactionalClient(this, aaiClient);
- }
+ @Override
+ protected Relationship buildRelationship(GraphInventoryResourceUri uri, Optional<GraphInventoryEdgeLabel> label) {
+ return super.buildRelationship(uri, label);
+ }
- @Override
- public AAISingleTransactionClient beginSingleTransaction() {
- return new AAISingleTransactionClient(this, aaiClient);
- }
-
- @Override
- protected Relationship buildRelationship(GraphInventoryResourceUri uri) {
- return super.buildRelationship(uri, Optional.empty());
- }
-
- @Override
- protected Relationship buildRelationship(GraphInventoryResourceUri uri, GraphInventoryEdgeLabel label) {
- return super.buildRelationship(uri, Optional.of(label));
- }
-
- @Override
- protected Relationship buildRelationship(GraphInventoryResourceUri uri, Optional<GraphInventoryEdgeLabel> label) {
- return super.buildRelationship(uri, label);
- }
-
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIResourcesObjectMapperProvider.java b/common/src/main/java/org/onap/so/client/aai/AAIResourcesObjectMapperProvider.java
index 15f2ed2fa2..875571d71e 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIResourcesObjectMapperProvider.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIResourcesObjectMapperProvider.java
@@ -22,8 +22,8 @@ package org.onap.so.client.aai;
public class AAIResourcesObjectMapperProvider extends AAICommonObjectMapperProvider {
- public AAIResourcesObjectMapperProvider() {
- super();
- }
+ public AAIResourcesObjectMapperProvider() {
+ super();
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIRestClient.java b/common/src/main/java/org/onap/so/client/aai/AAIRestClient.java
index 30d1b040e2..6eafb965a2 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIRestClient.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIRestClient.java
@@ -23,9 +23,7 @@ package org.onap.so.client.aai;
import java.net.URI;
import java.util.Map;
import java.util.Optional;
-
import javax.ws.rs.core.Response;
-
import org.onap.so.client.ResponseExceptionMapper;
import org.onap.so.client.graphinventory.GraphInventoryPatchConverter;
import org.onap.so.client.graphinventory.GraphInventoryRestClient;
@@ -34,38 +32,38 @@ import org.onap.so.utils.TargetEntity;
public class AAIRestClient extends GraphInventoryRestClient {
- private final AAIProperties aaiProperties;
+ private final AAIProperties aaiProperties;
- protected AAIRestClient(AAIProperties props, URI uri) {
- super(props, uri);
- this.aaiProperties = props;
- }
+ protected AAIRestClient(AAIProperties props, URI uri) {
+ super(props, uri);
+ this.aaiProperties = props;
+ }
- @Override
- public TargetEntity getTargetEntity(){
- return TargetEntity.AAI;
+ @Override
+ public TargetEntity getTargetEntity() {
+ return TargetEntity.AAI;
}
- @Override
- protected void initializeHeaderMap(Map<String, String> headerMap) {
- headerMap.put("X-FromAppId", aaiProperties.getSystemName());
- headerMap.put("X-TransactionId", requestId);
- String auth = aaiProperties.getAuth();
- String key = aaiProperties.getKey();
+ @Override
+ protected void initializeHeaderMap(Map<String, String> headerMap) {
+ headerMap.put("X-FromAppId", aaiProperties.getSystemName());
+ headerMap.put("X-TransactionId", requestId);
+ String auth = aaiProperties.getAuth();
+ String key = aaiProperties.getKey();
- if (auth != null && !auth.isEmpty() && key != null && !key.isEmpty()) {
- addBasicAuthHeader(auth, key);
- }
- }
+ if (auth != null && !auth.isEmpty() && key != null && !key.isEmpty()) {
+ addBasicAuthHeader(auth, key);
+ }
+ }
- @Override
- protected Optional<ResponseExceptionMapper> addResponseExceptionMapper() {
+ @Override
+ protected Optional<ResponseExceptionMapper> addResponseExceptionMapper() {
- return Optional.of(new AAIClientResponseExceptionMapper());
- }
-
- protected GraphInventoryPatchConverter getPatchConverter() {
- return this.patchConverter;
- }
+ return Optional.of(new AAIClientResponseExceptionMapper());
+ }
+
+ protected GraphInventoryPatchConverter getPatchConverter() {
+ return this.patchConverter;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIRestClientI.java b/common/src/main/java/org/onap/so/client/aai/AAIRestClientI.java
index 62d7d565ac..8bc709b276 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIRestClientI.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIRestClientI.java
@@ -29,13 +29,13 @@ import org.onap.aai.domain.yang.Pserver;
public interface AAIRestClientI {
- List<Pserver> getPhysicalServerByVnfId(String vnfId) throws IOException;
-
- void updateMaintenceFlagVnfId(String vnfId, boolean inMaint);
-
- GenericVnf getVnfByName(String vnfId);
+ List<Pserver> getPhysicalServerByVnfId(String vnfId) throws IOException;
- Optional<Pnf> getPnfByName(String pnfId);
+ void updateMaintenceFlagVnfId(String vnfId, boolean inMaint);
- void createPnf(String pnfId, Pnf pnf);
+ GenericVnf getVnfByName(String vnfId);
+
+ Optional<Pnf> getPnfByName(String pnfId);
+
+ void createPnf(String pnfId, Pnf pnf);
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIRestClientImpl.java b/common/src/main/java/org/onap/so/client/aai/AAIRestClientImpl.java
index b2c7fcc062..03e2eaea1f 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIRestClientImpl.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIRestClientImpl.java
@@ -45,8 +45,7 @@ public class AAIRestClientImpl implements AAIRestClientI {
public List<Pserver> getPhysicalServerByVnfId(String vnfId) throws IOException {
List<AAIResourceUri> startNodes = new ArrayList<>();
startNodes.add(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId));
- String jsonInput = new AAIQueryClient()
- .query(Format.RESOURCE, new CustomQuery(startNodes, PSERVER_VNF_QUERY));
+ String jsonInput = new AAIQueryClient().query(Format.RESOURCE, new CustomQuery(startNodes, PSERVER_VNF_QUERY));
return this.getListOfPservers(jsonInput);
@@ -54,9 +53,8 @@ public class AAIRestClientImpl implements AAIRestClientI {
protected List<Pserver> getListOfPservers(String jsonInput) throws IOException {
ObjectMapper mapper = new AAICommonObjectMapperProvider().getMapper();
- Results<Map<String, Pserver>> resultsFromJson = mapper.readValue(jsonInput,
- new TypeReference<Results<Map<String, Pserver>>>() {
- });
+ Results<Map<String, Pserver>> resultsFromJson =
+ mapper.readValue(jsonInput, new TypeReference<Results<Map<String, Pserver>>>() {});
List<Pserver> results = new ArrayList<>();
for (Map<String, Pserver> m : resultsFromJson.getResult()) {
results.add(m.get("pserver"));
@@ -68,8 +66,7 @@ public class AAIRestClientImpl implements AAIRestClientI {
public void updateMaintenceFlagVnfId(String vnfId, boolean inMaint) {
GenericVnf genericVnf = new GenericVnf();
genericVnf.setInMaint(inMaint);
- new AAIResourcesClient()
- .update(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId), genericVnf);
+ new AAIResourcesClient().update(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId), genericVnf);
}
@@ -81,8 +78,8 @@ public class AAIRestClientImpl implements AAIRestClientI {
@Override
public Optional<Pnf> getPnfByName(String pnfId) {
- Response response = new AAIResourcesClient()
- .getFullResponse(AAIUriFactory.createResourceUri(AAIObjectType.PNF, pnfId));
+ Response response =
+ new AAIResourcesClient().getFullResponse(AAIUriFactory.createResourceUri(AAIObjectType.PNF, pnfId));
if (response.getStatus() != 200) {
return Optional.empty();
} else {
@@ -92,7 +89,7 @@ public class AAIRestClientImpl implements AAIRestClientI {
@Override
public void createPnf(String pnfId, Pnf pnf) {
- new AAIResourcesClient()
- .createIfNotExists(AAIUriFactory.createResourceUri(AAIObjectType.PNF, pnfId), Optional.of(pnf));
+ new AAIResourcesClient().createIfNotExists(AAIUriFactory.createResourceUri(AAIObjectType.PNF, pnfId),
+ Optional.of(pnf));
}
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java b/common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java
index fecbf59c36..1370bb3fa3 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java
@@ -24,9 +24,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-
import javax.ws.rs.core.GenericType;
-
import org.onap.so.client.RestClient;
import org.onap.so.client.aai.entities.AAIEdgeLabel;
import org.onap.so.client.aai.entities.AAIError;
@@ -39,109 +37,116 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.onap.so.client.graphinventory.GraphInventoryPatchConverter;
import org.onap.so.client.graphinventory.GraphInventoryTransactionClient;
import org.onap.so.client.graphinventory.exceptions.BulkProcessFailed;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
-public class AAISingleTransactionClient extends GraphInventoryTransactionClient<AAISingleTransactionClient, AAIResourceUri, AAIEdgeLabel> {
-
- private final SingleTransactionRequest request;
- private AAIResourcesClient resourcesClient;
- private AAIClient aaiClient;
- protected AAISingleTransactionClient(AAIResourcesClient resourcesClient, AAIClient aaiClient) {
- super();
- this.resourcesClient = resourcesClient;
- this.aaiClient = aaiClient;
- this.request = new SingleTransactionRequest();
- }
-
- /* (non-Javadoc)
- * @see org.onap.so.client.aai.GraphInventoryTransactionClient#execute()
- */
- @Override
- public void execute() throws BulkProcessFailed {
- try {
- if (!this.request.getOperations().isEmpty()) {
- RestClient client = aaiClient.createClient(AAIUriFactory.createResourceUri(AAIObjectType.SINGLE_TRANSACTION));
- SingleTransactionResponse response = client.post(this.request, SingleTransactionResponse.class);
- if (response != null) {
- final Optional<String> errorMessage = this.locateErrorMessages(response);
- if (errorMessage.isPresent()) {
- throw new BulkProcessFailed("One or more transactions failed in A&AI. Check logs for payloads.\nMessages:\n" + errorMessage.get());
- }
- } else {
- throw new BulkProcessFailed("Transactions acccepted by A&AI, but there was no response. Unsure of result.");
- }
- }
- } finally {
- this.request.getOperations().clear();
- this.actionCount = 0;
- }
- }
-
- protected Optional<String> locateErrorMessages(SingleTransactionResponse response) {
- final List<String> errorMessages = new ArrayList<>();
- final ObjectMapper mapper = new ObjectMapper();
-
- for (OperationBodyResponse body : response.getOperationResponses()) {
- if (Optional.ofNullable(body.getResponseStatusCode()).orElse(400) > 300) {
- AAIError error;
- try {
- error = mapper.readValue(mapper.writeValueAsString(body.getResponseBody()), AAIError.class);
- } catch (IOException e) {
- logger.error("could not parse error object from A&AI", e);
- error = new AAIError();
- }
- AAIErrorFormatter formatter = new AAIErrorFormatter(error);
- String outputMessage = formatter.getMessage();
- errorMessages.add(outputMessage);
- }
- }
-
- if (!errorMessages.isEmpty()) {
- return Optional.of(Joiner.on("\n").join(errorMessages));
- } else {
- return Optional.empty();
- }
- }
-
-
- protected SingleTransactionRequest getRequest() {
- return this.request;
- }
-
- @Override
- public void put(String uri, Object body) {
- request.getOperations().add(new OperationBodyRequest().withAction("put").withUri(uri).withBody(body));
- }
-
- @Override
- public void delete(String uri, Object body) {
- request.getOperations().add(new OperationBodyRequest().withAction("delete").withUri(uri).withBody(body));
- }
-
- @Override
- public void patch(String uri, Object body) {
- request.getOperations().add(new OperationBodyRequest().withAction("patch").withUri(uri).withBody(body));
- }
-
- @Override
- protected <T> Optional<T> get(GenericType<T> genericType, AAIResourceUri clone) {
- return resourcesClient.get(genericType, clone);
- }
-
- @Override
- protected boolean exists(AAIResourceUri uri) {
- return resourcesClient.exists(uri);
- }
-
- @Override
- protected String getGraphDBName() {
- return aaiClient.getGraphDBName();
- }
-
- @Override
- protected GraphInventoryPatchConverter getPatchConverter() {
- return this.patchConverter;
- }
+public class AAISingleTransactionClient
+ extends GraphInventoryTransactionClient<AAISingleTransactionClient, AAIResourceUri, AAIEdgeLabel> {
+
+ private final SingleTransactionRequest request;
+ private AAIResourcesClient resourcesClient;
+ private AAIClient aaiClient;
+
+ protected AAISingleTransactionClient(AAIResourcesClient resourcesClient, AAIClient aaiClient) {
+ super();
+ this.resourcesClient = resourcesClient;
+ this.aaiClient = aaiClient;
+ this.request = new SingleTransactionRequest();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.so.client.aai.GraphInventoryTransactionClient#execute()
+ */
+ @Override
+ public void execute() throws BulkProcessFailed {
+ try {
+ if (!this.request.getOperations().isEmpty()) {
+ RestClient client =
+ aaiClient.createClient(AAIUriFactory.createResourceUri(AAIObjectType.SINGLE_TRANSACTION));
+ SingleTransactionResponse response = client.post(this.request, SingleTransactionResponse.class);
+ if (response != null) {
+ final Optional<String> errorMessage = this.locateErrorMessages(response);
+ if (errorMessage.isPresent()) {
+ throw new BulkProcessFailed(
+ "One or more transactions failed in A&AI. Check logs for payloads.\nMessages:\n"
+ + errorMessage.get());
+ }
+ } else {
+ throw new BulkProcessFailed(
+ "Transactions acccepted by A&AI, but there was no response. Unsure of result.");
+ }
+ }
+ } finally {
+ this.request.getOperations().clear();
+ this.actionCount = 0;
+ }
+ }
+
+ protected Optional<String> locateErrorMessages(SingleTransactionResponse response) {
+ final List<String> errorMessages = new ArrayList<>();
+ final ObjectMapper mapper = new ObjectMapper();
+
+ for (OperationBodyResponse body : response.getOperationResponses()) {
+ if (Optional.ofNullable(body.getResponseStatusCode()).orElse(400) > 300) {
+ AAIError error;
+ try {
+ error = mapper.readValue(mapper.writeValueAsString(body.getResponseBody()), AAIError.class);
+ } catch (IOException e) {
+ logger.error("could not parse error object from A&AI", e);
+ error = new AAIError();
+ }
+ AAIErrorFormatter formatter = new AAIErrorFormatter(error);
+ String outputMessage = formatter.getMessage();
+ errorMessages.add(outputMessage);
+ }
+ }
+
+ if (!errorMessages.isEmpty()) {
+ return Optional.of(Joiner.on("\n").join(errorMessages));
+ } else {
+ return Optional.empty();
+ }
+ }
+
+
+ protected SingleTransactionRequest getRequest() {
+ return this.request;
+ }
+
+ @Override
+ public void put(String uri, Object body) {
+ request.getOperations().add(new OperationBodyRequest().withAction("put").withUri(uri).withBody(body));
+ }
+
+ @Override
+ public void delete(String uri, Object body) {
+ request.getOperations().add(new OperationBodyRequest().withAction("delete").withUri(uri).withBody(body));
+ }
+
+ @Override
+ public void patch(String uri, Object body) {
+ request.getOperations().add(new OperationBodyRequest().withAction("patch").withUri(uri).withBody(body));
+ }
+
+ @Override
+ protected <T> Optional<T> get(GenericType<T> genericType, AAIResourceUri clone) {
+ return resourcesClient.get(genericType, clone);
+ }
+
+ @Override
+ protected boolean exists(AAIResourceUri uri) {
+ return resourcesClient.exists(uri);
+ }
+
+ @Override
+ protected String getGraphDBName() {
+ return aaiClient.getGraphDBName();
+ }
+
+ @Override
+ protected GraphInventoryPatchConverter getPatchConverter() {
+ return this.patchConverter;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java b/common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java
index 9fb6cd7706..11e458a3da 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java
@@ -26,10 +26,8 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
-
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
-
import org.onap.aai.domain.yang.Relationship;
import org.onap.so.client.RestClient;
import org.onap.so.client.aai.entities.AAIEdgeLabel;
@@ -43,156 +41,166 @@ import org.onap.so.client.graphinventory.GraphInventoryPatchConverter;
import org.onap.so.client.graphinventory.GraphInventoryTransactionClient;
import org.onap.so.client.graphinventory.exceptions.BulkProcessFailed;
import org.onap.so.jsonpath.JsonPathUtil;
-
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
-public class AAITransactionalClient extends GraphInventoryTransactionClient<AAITransactionalClient, AAIResourceUri, AAIEdgeLabel> {
-
- private final Transactions transactions;
- private Transaction currentTransaction;
-
- private AAIResourcesClient resourcesClient;
- private AAIClient aaiClient;
- protected AAITransactionalClient(AAIResourcesClient resourcesClient, AAIClient aaiClient) {
- super();
- this.resourcesClient = resourcesClient;
- this.aaiClient = aaiClient;
- this.transactions = new Transactions();
- startTransaction();
- }
-
- private void startTransaction() {
- Transaction transaction = new Transaction();
- transactions.getTransactions().add(transaction);
- currentTransaction = transaction;
- }
-
- /* (non-Javadoc)
- * @see org.onap.so.client.aai.GraphInventoryTransactionalClient#beginNewTransaction()
- */
- public AAITransactionalClient beginNewTransaction() {
- startTransaction();
- return this;
- }
-
- /* (non-Javadoc)
- * @see org.onap.so.client.aai.GraphInventoryTransactionalClient#execute()
- */
- @Override
- public void execute() throws BulkProcessFailed {
- try {
- if (!this.transactions.getTransactions().isEmpty()) {
- RestClient client = aaiClient.createClient(AAIUriFactory.createResourceUri(AAIObjectType.BULK_PROCESS));
- Response response = client.put(this.transactions);
- if (response.hasEntity()) {
- final Optional<String> errorMessage = this.locateErrorMessages(response.readEntity(String.class));
- if (errorMessage.isPresent()) {
- throw new BulkProcessFailed("One or more transactions failed in A&AI. Check logs for payloads.\nMessages:\n" + errorMessage.get());
- }
- } else {
- throw new BulkProcessFailed("Transactions acccepted by A&AI, but there was no response. Unsure of result.");
- }
- }
- } finally {
- this.transactions.getTransactions().clear();
- this.currentTransaction = null;
- this.actionCount = 0;
- }
- }
-
- protected Optional<String> locateErrorMessages(String response) {
- final List<String> errorMessages = new ArrayList<>();
- final List<String> results = JsonPathUtil.getInstance().locateResultList(response, "$..body");
- final ObjectMapper mapper = new ObjectMapper();
- if (!results.isEmpty()) {
- List<Map<String, Object>> parsed = new ArrayList<>();
- try {
- for (String result : results) {
- parsed.add(mapper.readValue(result, new TypeReference<Map<String, Object>>(){}));
- }
- } catch (IOException e) {
- logger.error("could not map json", e);
- }
- for (Map<String, Object> map : parsed) {
- for (Entry<String, Object> entry : map.entrySet()) {
- if (!entry.getKey().matches("2\\d\\d")) {
- AAIError error;
- try {
- error = mapper.readValue(entry.getValue().toString(), AAIError.class);
- } catch (IOException e) {
- logger.error("could not parse error object from A&AI", e);
- error = new AAIError();
- }
- AAIErrorFormatter formatter = new AAIErrorFormatter(error);
- String outputMessage = formatter.getMessage();
- logger.error("part of a bulk action failed in A&AI: " + entry.getValue());
- errorMessages.add(outputMessage);
- }
- }
- }
- }
-
- if (!errorMessages.isEmpty()) {
- return Optional.of(Joiner.on("\n").join(errorMessages));
- } else {
- return Optional.empty();
- }
- }
- private Relationship buildRelationship(AAIResourceUri uri) {
- return buildRelationship(uri, Optional.empty());
- }
-
- private Relationship buildRelationship(AAIResourceUri uri, AAIEdgeLabel label) {
- return buildRelationship(uri, Optional.of(label));
- }
- private Relationship buildRelationship(AAIResourceUri uri, Optional<AAIEdgeLabel> label) {
- final Relationship result = new Relationship();
- result.setRelatedLink(uri.build().toString());
- if (label.isPresent()) {
- result.setRelationshipLabel(label.toString());
- }
- return result;
- }
-
- protected Transactions getTransactions() {
- return this.transactions;
- }
-
- @Override
- public void put(String uri, Object body) {
- currentTransaction.getPut().add(new OperationBody().withUri(uri).withBody(body));
- }
-
- @Override
- public void delete(String uri, Object body) {
- currentTransaction.getDelete().add(new OperationBody().withUri(uri).withBody(body));
-
- }
-
- @Override
- public void patch(String uri, Object body) {
- currentTransaction.getPatch().add(new OperationBody().withUri(uri).withBody(body));
- }
-
- @Override
- protected <T> Optional<T> get(GenericType<T> genericType, AAIResourceUri clone) {
- return resourcesClient.get(genericType, clone);
- }
-
- @Override
- protected boolean exists(AAIResourceUri uri) {
- return resourcesClient.exists(uri);
- }
-
- @Override
- protected String getGraphDBName() {
- return aaiClient.getGraphDBName();
- }
-
- @Override
- protected GraphInventoryPatchConverter getPatchConverter() {
- return this.patchConverter;
- }
+public class AAITransactionalClient
+ extends GraphInventoryTransactionClient<AAITransactionalClient, AAIResourceUri, AAIEdgeLabel> {
+
+ private final Transactions transactions;
+ private Transaction currentTransaction;
+
+ private AAIResourcesClient resourcesClient;
+ private AAIClient aaiClient;
+
+ protected AAITransactionalClient(AAIResourcesClient resourcesClient, AAIClient aaiClient) {
+ super();
+ this.resourcesClient = resourcesClient;
+ this.aaiClient = aaiClient;
+ this.transactions = new Transactions();
+ startTransaction();
+ }
+
+ private void startTransaction() {
+ Transaction transaction = new Transaction();
+ transactions.getTransactions().add(transaction);
+ currentTransaction = transaction;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.so.client.aai.GraphInventoryTransactionalClient#beginNewTransaction()
+ */
+ public AAITransactionalClient beginNewTransaction() {
+ startTransaction();
+ return this;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.so.client.aai.GraphInventoryTransactionalClient#execute()
+ */
+ @Override
+ public void execute() throws BulkProcessFailed {
+ try {
+ if (!this.transactions.getTransactions().isEmpty()) {
+ RestClient client = aaiClient.createClient(AAIUriFactory.createResourceUri(AAIObjectType.BULK_PROCESS));
+ Response response = client.put(this.transactions);
+ if (response.hasEntity()) {
+ final Optional<String> errorMessage = this.locateErrorMessages(response.readEntity(String.class));
+ if (errorMessage.isPresent()) {
+ throw new BulkProcessFailed(
+ "One or more transactions failed in A&AI. Check logs for payloads.\nMessages:\n"
+ + errorMessage.get());
+ }
+ } else {
+ throw new BulkProcessFailed(
+ "Transactions acccepted by A&AI, but there was no response. Unsure of result.");
+ }
+ }
+ } finally {
+ this.transactions.getTransactions().clear();
+ this.currentTransaction = null;
+ this.actionCount = 0;
+ }
+ }
+
+ protected Optional<String> locateErrorMessages(String response) {
+ final List<String> errorMessages = new ArrayList<>();
+ final List<String> results = JsonPathUtil.getInstance().locateResultList(response, "$..body");
+ final ObjectMapper mapper = new ObjectMapper();
+ if (!results.isEmpty()) {
+ List<Map<String, Object>> parsed = new ArrayList<>();
+ try {
+ for (String result : results) {
+ parsed.add(mapper.readValue(result, new TypeReference<Map<String, Object>>() {}));
+ }
+ } catch (IOException e) {
+ logger.error("could not map json", e);
+ }
+ for (Map<String, Object> map : parsed) {
+ for (Entry<String, Object> entry : map.entrySet()) {
+ if (!entry.getKey().matches("2\\d\\d")) {
+ AAIError error;
+ try {
+ error = mapper.readValue(entry.getValue().toString(), AAIError.class);
+ } catch (IOException e) {
+ logger.error("could not parse error object from A&AI", e);
+ error = new AAIError();
+ }
+ AAIErrorFormatter formatter = new AAIErrorFormatter(error);
+ String outputMessage = formatter.getMessage();
+ logger.error("part of a bulk action failed in A&AI: " + entry.getValue());
+ errorMessages.add(outputMessage);
+ }
+ }
+ }
+ }
+
+ if (!errorMessages.isEmpty()) {
+ return Optional.of(Joiner.on("\n").join(errorMessages));
+ } else {
+ return Optional.empty();
+ }
+ }
+
+ private Relationship buildRelationship(AAIResourceUri uri) {
+ return buildRelationship(uri, Optional.empty());
+ }
+
+ private Relationship buildRelationship(AAIResourceUri uri, AAIEdgeLabel label) {
+ return buildRelationship(uri, Optional.of(label));
+ }
+
+ private Relationship buildRelationship(AAIResourceUri uri, Optional<AAIEdgeLabel> label) {
+ final Relationship result = new Relationship();
+ result.setRelatedLink(uri.build().toString());
+ if (label.isPresent()) {
+ result.setRelationshipLabel(label.toString());
+ }
+ return result;
+ }
+
+ protected Transactions getTransactions() {
+ return this.transactions;
+ }
+
+ @Override
+ public void put(String uri, Object body) {
+ currentTransaction.getPut().add(new OperationBody().withUri(uri).withBody(body));
+ }
+
+ @Override
+ public void delete(String uri, Object body) {
+ currentTransaction.getDelete().add(new OperationBody().withUri(uri).withBody(body));
+
+ }
+
+ @Override
+ public void patch(String uri, Object body) {
+ currentTransaction.getPatch().add(new OperationBody().withUri(uri).withBody(body));
+ }
+
+ @Override
+ protected <T> Optional<T> get(GenericType<T> genericType, AAIResourceUri clone) {
+ return resourcesClient.get(genericType, clone);
+ }
+
+ @Override
+ protected boolean exists(AAIResourceUri uri) {
+ return resourcesClient.exists(uri);
+ }
+
+ @Override
+ protected String getGraphDBName() {
+ return aaiClient.getGraphDBName();
+ }
+
+ @Override
+ protected GraphInventoryPatchConverter getPatchConverter() {
+ return this.patchConverter;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIUpdator.java b/common/src/main/java/org/onap/so/client/aai/AAIUpdator.java
index f7c9fe8362..e8a2bc6c9c 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIUpdator.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIUpdator.java
@@ -21,9 +21,9 @@
package org.onap.so.client.aai;
public interface AAIUpdator {
-
- void updateVnfToLocked(String vnfName) throws Exception;
-
- void updateVnfToUnLocked(String vnfName) throws Exception;
+
+ void updateVnfToLocked(String vnfName) throws Exception;
+
+ void updateVnfToUnLocked(String vnfName) throws Exception;
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIUpdatorImpl.java b/common/src/main/java/org/onap/so/client/aai/AAIUpdatorImpl.java
index 2697e4a9e8..0d400339f9 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIUpdatorImpl.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIUpdatorImpl.java
@@ -24,27 +24,27 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
public class AAIUpdatorImpl implements AAIUpdator {
-
- @Autowired
- protected AAIRestClientI client;
-
- public AAIRestClientI getClient() {
- return client;
- }
-
-
- public void setClient(AAIRestClientI client) {
- this.client = client;
- }
-
- @Override
- public void updateVnfToLocked(String vnfId) throws Exception {
- client.updateMaintenceFlagVnfId(vnfId, true);
- }
-
- @Override
- public void updateVnfToUnLocked(String vnfId) throws Exception {
- client.updateMaintenceFlagVnfId(vnfId, false);
- }
+
+ @Autowired
+ protected AAIRestClientI client;
+
+ public AAIRestClientI getClient() {
+ return client;
+ }
+
+
+ public void setClient(AAIRestClientI client) {
+ this.client = client;
+ }
+
+ @Override
+ public void updateVnfToLocked(String vnfId) throws Exception {
+ client.updateMaintenceFlagVnfId(vnfId, true);
+ }
+
+ @Override
+ public void updateVnfToUnLocked(String vnfId) throws Exception {
+ client.updateMaintenceFlagVnfId(vnfId, false);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIValidator.java b/common/src/main/java/org/onap/so/client/aai/AAIValidator.java
index 18252d548b..f191311b2a 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIValidator.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIValidator.java
@@ -23,10 +23,10 @@ package org.onap.so.client.aai;
import java.io.IOException;
public interface AAIValidator {
-
- boolean isPhysicalServerLocked(String hostName) throws IOException;
-
- boolean isVNFLocked(String vnfId);
-
-} \ No newline at end of file
+ boolean isPhysicalServerLocked(String hostName) throws IOException;
+
+ boolean isVNFLocked(String vnfId);
+
+
+}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java b/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java
index 1bd7720e55..3987d7375a 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java
@@ -22,7 +22,6 @@ package org.onap.so.client.aai;
import java.io.IOException;
import java.util.List;
-
import org.onap.aai.domain.yang.GenericVnf;
import org.onap.aai.domain.yang.Pserver;
import org.springframework.beans.factory.annotation.Autowired;
@@ -32,40 +31,40 @@ import org.springframework.stereotype.Component;
public class AAIValidatorImpl implements AAIValidator {
- @Autowired
- protected AAIRestClientI client;
-
- public AAIRestClientI getClient() {
- return client;
- }
+ @Autowired
+ protected AAIRestClientI client;
+
+ public AAIRestClientI getClient() {
+ return client;
+ }
- public void setClient(AAIRestClientI client) {
- this.client = client;
- }
+ public void setClient(AAIRestClientI client) {
+ this.client = client;
+ }
- @Override
- public boolean isPhysicalServerLocked(String vnfId) throws IOException {
- List<Pserver> pservers;
- boolean isLocked = false;
- pservers = client.getPhysicalServerByVnfId(vnfId);
- for (Pserver pserver : pservers) {
- if (pserver.isInMaint()) {
- isLocked = true;
- return isLocked;
- }
- }
- return isLocked;
- }
+ @Override
+ public boolean isPhysicalServerLocked(String vnfId) throws IOException {
+ List<Pserver> pservers;
+ boolean isLocked = false;
+ pservers = client.getPhysicalServerByVnfId(vnfId);
+ for (Pserver pserver : pservers) {
+ if (pserver.isInMaint()) {
+ isLocked = true;
+ return isLocked;
+ }
+ }
+ return isLocked;
+ }
- @Override
- public boolean isVNFLocked(String vnfId) {
- boolean isLocked = false;
- GenericVnf genericVnf = client.getVnfByName(vnfId);
- if (genericVnf.isInMaint())
- isLocked = true;
+ @Override
+ public boolean isVNFLocked(String vnfId) {
+ boolean isLocked = false;
+ GenericVnf genericVnf = client.getVnfByName(vnfId);
+ if (genericVnf.isInMaint())
+ isLocked = true;
- return isLocked;
- }
+ return isLocked;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIVersion.java b/common/src/main/java/org/onap/so/client/aai/AAIVersion.java
index d93d656403..499246d7d1 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIVersion.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIVersion.java
@@ -23,19 +23,19 @@ package org.onap.so.client.aai;
import org.onap.so.client.graphinventory.GraphInventoryVersion;
public enum AAIVersion implements GraphInventoryVersion {
- V13("v13"),
- V14("v14"),
- V15("v15");
-
- public final static AAIVersion LATEST = AAIVersion.values()[AAIVersion.values().length - 1];
- private final String value;
- private AAIVersion(String value){
- this.value = value;
- }
- @Override
- public String toString(){
- return this.value;
- }
+ V13("v13"), V14("v14"), V15("v15");
+
+ public final static AAIVersion LATEST = AAIVersion.values()[AAIVersion.values().length - 1];
+ private final String value;
+
+ private AAIVersion(String value) {
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return this.value;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java b/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java
index eb6d0d0b43..2e70c4925a 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java
@@ -24,18 +24,18 @@ import org.onap.so.client.graphinventory.entities.GraphInventoryEdgeLabel;
public enum AAIEdgeLabel implements GraphInventoryEdgeLabel {
- BELONGS_TO("org.onap.relationships.inventory.BelongsTo"),
- USES("org.onap.relationships.inventory.Uses"),
- COMPOSED_OF("org.onap.relationships.inventory.ComposedOf");
-
- private final String label;
- private AAIEdgeLabel(String label) {
- this.label = label;
- }
-
-
- @Override
- public String toString() {
- return this.label;
- }
+ BELONGS_TO("org.onap.relationships.inventory.BelongsTo"), USES(
+ "org.onap.relationships.inventory.Uses"), COMPOSED_OF("org.onap.relationships.inventory.ComposedOf");
+
+ private final String label;
+
+ private AAIEdgeLabel(String label) {
+ this.label = label;
+ }
+
+
+ @Override
+ public String toString() {
+ return this.label;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/AAIEntity.java b/common/src/main/java/org/onap/so/client/aai/entities/AAIEntity.java
index c2aceeeeba..ee3ffd9bbf 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/AAIEntity.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/AAIEntity.java
@@ -20,6 +20,6 @@
package org.onap.so.client.aai.entities;
-public class AAIEntity{
-
+public class AAIEntity {
+
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/AAIEntityObject.java b/common/src/main/java/org/onap/so/client/aai/entities/AAIEntityObject.java
index dc91c8a034..5989a6579d 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/AAIEntityObject.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/AAIEntityObject.java
@@ -23,7 +23,7 @@ package org.onap.so.client.aai.entities;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
public interface AAIEntityObject {
-
- public AAIResourceUri getUri();
+
+ public AAIResourceUri getUri();
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/AAIError.java b/common/src/main/java/org/onap/so/client/aai/entities/AAIError.java
index 4261f4f3c0..10828acd96 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/AAIError.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/AAIError.java
@@ -25,9 +25,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "requestError"
-})
+@JsonPropertyOrder({"requestError"})
public class AAIError {
@JsonProperty("requestError")
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java b/common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java
index 5ce81ce879..ab3284dd8f 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java
@@ -21,26 +21,25 @@
package org.onap.so.client.aai.entities;
import java.io.Serializable;
-
import org.onap.so.client.graphinventory.entities.GraphInventoryResultWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AAIResultWrapper extends GraphInventoryResultWrapper<Relationships> implements Serializable {
- private static final long serialVersionUID = 5895841925807816737L;
- private final static transient Logger logger = LoggerFactory.getLogger(AAIResultWrapper.class);
-
- public AAIResultWrapper(String json) {
- super(json, logger);
- }
-
- public AAIResultWrapper(Object aaiObject) {
- super(aaiObject, logger);
- }
+ private static final long serialVersionUID = 5895841925807816737L;
+ private final static transient Logger logger = LoggerFactory.getLogger(AAIResultWrapper.class);
+
+ public AAIResultWrapper(String json) {
+ super(json, logger);
+ }
+
+ public AAIResultWrapper(Object aaiObject) {
+ super(aaiObject, logger);
+ }
- @Override
- protected Relationships createRelationships(String json) {
- return new Relationships(json);
- }
+ @Override
+ protected Relationships createRelationships(String json) {
+ return new Relationships(json);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/Configuration.java b/common/src/main/java/org/onap/so/client/aai/entities/Configuration.java
index e1ce3a8adc..81c07b2cf4 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/Configuration.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/Configuration.java
@@ -25,24 +25,16 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "configuration-id",
- "configuration-type",
- "configuration-sub-type",
- "model-invariant-id",
- "model-version-id",
- "orchestration-status",
- "operational-status",
- "configuration-selflink",
- "model-customization-id"
-})
+@JsonPropertyOrder({"configuration-id", "configuration-type", "configuration-sub-type", "model-invariant-id",
+ "model-version-id", "orchestration-status", "operational-status", "configuration-selflink",
+ "model-customization-id"})
public class Configuration {
@JsonProperty("configuration-id")
private String configurationId;
@JsonProperty("configuration-name")
private String configurationName;
- @JsonProperty("configuration-type")
+ @JsonProperty("configuration-type")
private String configurationType;
@JsonProperty("configuration-sub-type")
private String configurationSubType;
@@ -52,13 +44,13 @@ public class Configuration {
private String modelVersionId;
@JsonProperty("orchestration-status")
private String orchestrationStatus;
- @JsonProperty("operational-status")
+ @JsonProperty("operational-status")
private String operationalStatus;
- @JsonProperty("configuration-selflink")
+ @JsonProperty("configuration-selflink")
private String configurationSelflink;
@JsonProperty("model-customization-id")
private String modelCustomizationId;
-
+
@JsonProperty("configuration-id")
public String getConfigurationId() {
return configurationId;
@@ -68,16 +60,16 @@ public class Configuration {
public void setConfigurationId(String configurationId) {
this.configurationId = configurationId;
}
-
+
@JsonProperty("configuration-name")
public String getConfigurationName() {
- return configurationName;
- }
+ return configurationName;
+ }
@JsonProperty("configuration-name")
- public void setConfigurationName(String configurationName) {
- this.configurationName = configurationName;
- }
+ public void setConfigurationName(String configurationName) {
+ this.configurationName = configurationName;
+ }
@JsonProperty("configuration-type")
public String getConfigurationType() {
@@ -118,36 +110,36 @@ public class Configuration {
public void setModelVersionId(String modelVersionId) {
this.modelVersionId = modelVersionId;
}
-
+
@JsonProperty("orchestration-status")
public String getOrchestrationStatus() {
- return orchestrationStatus;
- }
+ return orchestrationStatus;
+ }
@JsonProperty("orchestration-status")
- public void setOrchestrationStatus(String orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
+ public void setOrchestrationStatus(String orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
@JsonProperty("operational-status")
- public String getOperationalStatus() {
- return operationalStatus;
- }
+ public String getOperationalStatus() {
+ return operationalStatus;
+ }
@JsonProperty("operational-status")
- public void setOperationalStatus(String operationalStatus) {
- this.operationalStatus = operationalStatus;
- }
-
+ public void setOperationalStatus(String operationalStatus) {
+ this.operationalStatus = operationalStatus;
+ }
+
@JsonProperty("model-customization-id")
public String getModelCustomizationId() {
- return modelCustomizationId;
- }
+ return modelCustomizationId;
+ }
@JsonProperty("model-customization-id")
- public void setModelCustomizationId(String modelCustomizationId) {
- this.modelCustomizationId = modelCustomizationId;
- }
+ public void setModelCustomizationId(String modelCustomizationId) {
+ this.modelCustomizationId = modelCustomizationId;
+ }
@JsonProperty("configuration-selflink")
public String getConfigurationSelflink() {
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/CustomQuery.java b/common/src/main/java/org/onap/so/client/aai/entities/CustomQuery.java
index 8203476c82..af7ccf661e 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/CustomQuery.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/CustomQuery.java
@@ -23,60 +23,58 @@ package org.onap.so.client.aai.entities;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
-
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
-
import com.fasterxml.jackson.annotation.JsonInclude;
-@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonInclude(JsonInclude.Include.NON_NULL)
public class CustomQuery {
-
- private List<String> start;
- private String query;
- private String gremlin;
-
- public String getGremlin() {
- return gremlin;
- }
-
- public void setGremlin(String gremlin) {
- this.gremlin = gremlin;
- }
-
-
- public CustomQuery(List<AAIResourceUri> start){
- this.setStart(start);
- }
-
- public CustomQuery(List<AAIResourceUri> start, String query){
- this.setStart(start);
- this.query= "query/" + query;
- }
-
- public CustomQuery(String gremlin) throws UnsupportedEncodingException{
- this.gremlin=gremlin;
- }
-
- public List<String> getStart() {
- return start;
- }
-
- public void setStart(List<AAIResourceUri> start) {
- this.start = this.mapUris(start);
- }
-
- public String getQuery() {
- return query;
- }
-
- public void setQuery(String query) {
- this.query = query;
- }
-
- private List<String> mapUris(List<AAIResourceUri> uris) {
- final List<String> result = new ArrayList<>();
- uris.stream().map(item -> item.build().toString()).forEach(result::add);
- return result;
- }
+
+ private List<String> start;
+ private String query;
+ private String gremlin;
+
+ public String getGremlin() {
+ return gremlin;
+ }
+
+ public void setGremlin(String gremlin) {
+ this.gremlin = gremlin;
+ }
+
+
+ public CustomQuery(List<AAIResourceUri> start) {
+ this.setStart(start);
+ }
+
+ public CustomQuery(List<AAIResourceUri> start, String query) {
+ this.setStart(start);
+ this.query = "query/" + query;
+ }
+
+ public CustomQuery(String gremlin) throws UnsupportedEncodingException {
+ this.gremlin = gremlin;
+ }
+
+ public List<String> getStart() {
+ return start;
+ }
+
+ public void setStart(List<AAIResourceUri> start) {
+ this.start = this.mapUris(start);
+ }
+
+ public String getQuery() {
+ return query;
+ }
+
+ public void setQuery(String query) {
+ this.query = query;
+ }
+
+ private List<String> mapUris(List<AAIResourceUri> uris) {
+ final List<String> result = new ArrayList<>();
+ uris.stream().map(item -> item.build().toString()).forEach(result::add);
+ return result;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/QueryStep.java b/common/src/main/java/org/onap/so/client/aai/entities/QueryStep.java
index b056fd0e40..c662b4e465 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/QueryStep.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/QueryStep.java
@@ -23,6 +23,6 @@ package org.onap.so.client.aai.entities;
@FunctionalInterface
public interface QueryStep {
-
- public String build();
+
+ public String build();
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/Relationships.java b/common/src/main/java/org/onap/so/client/aai/entities/Relationships.java
index 61a2f4b8fa..91f2ee121e 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/Relationships.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/Relationships.java
@@ -21,9 +21,7 @@
package org.onap.so.client.aai.entities;
import java.util.List;
-
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.AAIResourcesClient;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
@@ -31,44 +29,46 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.onap.so.client.graphinventory.GraphInventoryObjectName;
import org.onap.so.client.graphinventory.entities.GraphInventoryRelationships;
-public class Relationships extends GraphInventoryRelationships<AAIResultWrapper, AAIResourceUri, AAIObjectType>{
+public class Relationships extends GraphInventoryRelationships<AAIResultWrapper, AAIResourceUri, AAIObjectType> {
+
+ public Relationships(String json) {
+ super(json);
+ }
+
+ @Deprecated
+ /**
+ * Use getRelatedUris instead
+ *
+ * @return
+ */
+ public List<AAIResourceUri> getRelatedAAIUris() {
+ return this.getRelatedUris();
+ }
+
+ @Deprecated
+ /**
+ * Use getRelatedUris instead
+ *
+ * @return
+ */
+ public List<AAIResourceUri> getRelatedAAIUris(GraphInventoryObjectName type) {
+ return this.getRelatedUris(type);
+ }
+
+
+ protected AAIResultWrapper get(AAIResourceUri uri) {
+ return new AAIResourcesClient().get(uri);
+
+ }
- public Relationships(String json) {
- super(json);
- }
-
- @Deprecated
- /**
- * Use getRelatedUris instead
- * @return
- */
- public List<AAIResourceUri> getRelatedAAIUris() {
- return this.getRelatedUris();
- }
-
- @Deprecated
- /**
- * Use getRelatedUris instead
- * @return
- */
- public List<AAIResourceUri> getRelatedAAIUris(GraphInventoryObjectName type) {
- return this.getRelatedUris(type);
- }
-
-
- protected AAIResultWrapper get(AAIResourceUri uri) {
- return new AAIResourcesClient().get(uri);
-
- }
+ @Override
+ protected AAIResourceUri createUri(AAIObjectType type, String relatedLink) {
- @Override
- protected AAIResourceUri createUri(AAIObjectType type, String relatedLink) {
-
- return AAIUriFactory.createResourceFromExistingURI(type, UriBuilder.fromPath(relatedLink).build());
- }
+ return AAIUriFactory.createResourceFromExistingURI(type, UriBuilder.fromPath(relatedLink).build());
+ }
- @Override
- protected AAIObjectType fromTypeName(String name) {
- return AAIObjectType.fromTypeName(name);
- }
+ @Override
+ protected AAIObjectType fromTypeName(String name) {
+ return AAIObjectType.fromTypeName(name);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/RequestError.java b/common/src/main/java/org/onap/so/client/aai/entities/RequestError.java
index bc8c283e34..1a9001df11 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/RequestError.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/RequestError.java
@@ -25,9 +25,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "serviceException"
-})
+@JsonPropertyOrder({"serviceException"})
public class RequestError {
@JsonProperty("serviceException")
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/Results.java b/common/src/main/java/org/onap/so/client/aai/entities/Results.java
index c3f0ad1fa1..a62c6adec1 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/Results.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/Results.java
@@ -22,7 +22,6 @@ package org.onap.so.client.aai.entities;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@@ -30,22 +29,21 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"results"
-})
+@JsonPropertyOrder({"results"})
public class Results<T> {
- @JsonProperty("results")
- protected List<T> results;
-
- @JsonProperty("results")
+ @JsonProperty("results")
+ protected List<T> results;
+
+ @JsonProperty("results")
public List<T> getResult() {
if (results == null) {
- results = new ArrayList<>();
+ results = new ArrayList<>();
}
return this.results;
}
- @JsonProperty("results")
- public void setResult(List<T> results) {
- this.results=results;
- }
+
+ @JsonProperty("results")
+ public void setResult(List<T> results) {
+ this.results = results;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/ServiceException.java b/common/src/main/java/org/onap/so/client/aai/entities/ServiceException.java
index 9d9723c514..de08dd9a81 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/ServiceException.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/ServiceException.java
@@ -22,17 +22,12 @@ package org.onap.so.client.aai.entities;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "messageId",
- "text",
- "variables"
-})
+@JsonPropertyOrder({"messageId", "text", "variables"})
public class ServiceException {
@JsonProperty("messageId")
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBody.java b/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBody.java
index 4b2aac1364..16a4c178e5 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBody.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBody.java
@@ -27,46 +27,43 @@ import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"uri",
-"body"
-})
+@JsonPropertyOrder({"uri", "body"})
public class OperationBody {
-@JsonProperty("uri")
-private String uri;
-@JsonProperty("body")
-@JsonSerialize(using = OperationBodySerializer.class)
-private Object body;
+ @JsonProperty("uri")
+ private String uri;
+ @JsonProperty("body")
+ @JsonSerialize(using = OperationBodySerializer.class)
+ private Object body;
-@JsonProperty("uri")
-public String getUri() {
-return uri;
-}
+ @JsonProperty("uri")
+ public String getUri() {
+ return uri;
+ }
-@JsonProperty("uri")
-public void setUri(String uri) {
-this.uri = uri;
-}
+ @JsonProperty("uri")
+ public void setUri(String uri) {
+ this.uri = uri;
+ }
-public OperationBody withUri(String uri) {
-this.uri = uri;
-return this;
-}
+ public OperationBody withUri(String uri) {
+ this.uri = uri;
+ return this;
+ }
-@JsonProperty("body")
-public Object getBody() {
-return body;
-}
+ @JsonProperty("body")
+ public Object getBody() {
+ return body;
+ }
-@JsonProperty("body")
-public void setBody(Object body) {
-this.body = body;
-}
+ @JsonProperty("body")
+ public void setBody(Object body) {
+ this.body = body;
+ }
-public OperationBody withBody(Object body) {
-this.body = body;
-return this;
-}
+ public OperationBody withBody(Object body) {
+ this.body = body;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBodySerializer.java b/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBodySerializer.java
index 2981e0deef..7181e96aa4 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBodySerializer.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBodySerializer.java
@@ -21,7 +21,6 @@
package org.onap.so.client.aai.entities.bulkprocess;
import java.io.IOException;
-
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
@@ -29,26 +28,27 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class OperationBodySerializer extends StdSerializer<Object> {
- private static final long serialVersionUID = 5367385969270400106L;
-
- public OperationBodySerializer() {
- this(null);
- }
- public OperationBodySerializer(Class<Object> t) {
- super(t);
- }
-
- @Override
- public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
- throws IOException, JsonProcessingException {
-
- if (value instanceof String) {
- gen.writeRawValue((String)value);
- } else {
- gen.writeObject(value);
- }
-
- }
+ private static final long serialVersionUID = 5367385969270400106L;
+
+ public OperationBodySerializer() {
+ this(null);
+ }
+
+ public OperationBodySerializer(Class<Object> t) {
+ super(t);
+ }
+
+ @Override
+ public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
+ throws IOException, JsonProcessingException {
+
+ if (value instanceof String) {
+ gen.writeRawValue((String) value);
+ } else {
+ gen.writeObject(value);
+ }
+
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/Transaction.java b/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/Transaction.java
index 1c405753c3..3b4351d768 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/Transaction.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/Transaction.java
@@ -22,74 +22,69 @@ package org.onap.so.client.aai.entities.bulkprocess;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"patch",
-"patch",
-"delete"
-})
+@JsonPropertyOrder({"patch", "patch", "delete"})
public class Transaction {
-@JsonInclude(JsonInclude.Include.NON_EMPTY)
-@JsonProperty("put")
-private List<OperationBody> put = new ArrayList<>();
-
-@JsonInclude(JsonInclude.Include.NON_EMPTY)
-@JsonProperty("patch")
-private List<OperationBody> patch = new ArrayList<>();
-
-@JsonInclude(JsonInclude.Include.NON_EMPTY)
-@JsonProperty("delete")
-private List<OperationBody> delete = new ArrayList<>();
-
-@JsonProperty("put")
-public List<OperationBody> getPut() {
-return put;
-}
-
-@JsonProperty("put")
-public void setPut(List<OperationBody> put) {
-this.put = put;
-}
-
-public Transaction withPut(List<OperationBody> put) {
-this.put = put;
-return this;
-}
-
-@JsonProperty("patch")
-public List<OperationBody> getPatch() {
-return patch;
-}
-
-@JsonProperty("patch")
-public void setPatch(List<OperationBody> patch) {
-this.patch = patch;
-}
-
-public Transaction withPatch(List<OperationBody> patch) {
-this.patch = patch;
-return this;
-}
-
-@JsonProperty("delete")
-public List<OperationBody> getDelete() {
-return delete;
-}
-
-@JsonProperty("delete")
-public void setDelete(List<OperationBody> delete) {
-this.delete = delete;
-}
-
-public Transaction withDelete(List<OperationBody> delete) {
-this.delete = delete;
-return this;
-}
+ @JsonInclude(JsonInclude.Include.NON_EMPTY)
+ @JsonProperty("put")
+ private List<OperationBody> put = new ArrayList<>();
+
+ @JsonInclude(JsonInclude.Include.NON_EMPTY)
+ @JsonProperty("patch")
+ private List<OperationBody> patch = new ArrayList<>();
+
+ @JsonInclude(JsonInclude.Include.NON_EMPTY)
+ @JsonProperty("delete")
+ private List<OperationBody> delete = new ArrayList<>();
+
+ @JsonProperty("put")
+ public List<OperationBody> getPut() {
+ return put;
+ }
+
+ @JsonProperty("put")
+ public void setPut(List<OperationBody> put) {
+ this.put = put;
+ }
+
+ public Transaction withPut(List<OperationBody> put) {
+ this.put = put;
+ return this;
+ }
+
+ @JsonProperty("patch")
+ public List<OperationBody> getPatch() {
+ return patch;
+ }
+
+ @JsonProperty("patch")
+ public void setPatch(List<OperationBody> patch) {
+ this.patch = patch;
+ }
+
+ public Transaction withPatch(List<OperationBody> patch) {
+ this.patch = patch;
+ return this;
+ }
+
+ @JsonProperty("delete")
+ public List<OperationBody> getDelete() {
+ return delete;
+ }
+
+ @JsonProperty("delete")
+ public void setDelete(List<OperationBody> delete) {
+ this.delete = delete;
+ }
+
+ public Transaction withDelete(List<OperationBody> delete) {
+ this.delete = delete;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/Transactions.java b/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/Transactions.java
index 51d56d371a..69e8a18a3e 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/Transactions.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/Transactions.java
@@ -22,33 +22,30 @@ package org.onap.so.client.aai.entities.bulkprocess;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"transactions"
-})
+@JsonPropertyOrder({"transactions"})
public class Transactions {
-@JsonProperty("transactions")
-private List<Transaction> transactions = new ArrayList<>();
+ @JsonProperty("transactions")
+ private List<Transaction> transactions = new ArrayList<>();
-@JsonProperty("transactions")
-public List<Transaction> getTransactions() {
-return transactions;
-}
+ @JsonProperty("transactions")
+ public List<Transaction> getTransactions() {
+ return transactions;
+ }
-@JsonProperty("transactions")
-public void setTransactions(List<Transaction> transactions) {
-this.transactions = transactions;
-}
+ @JsonProperty("transactions")
+ public void setTransactions(List<Transaction> transactions) {
+ this.transactions = transactions;
+ }
-public Transactions withTransactions(List<Transaction> transactions) {
-this.transactions = transactions;
-return this;
-}
+ public Transactions withTransactions(List<Transaction> transactions) {
+ this.transactions = transactions;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequest.java b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequest.java
index f2626e9e43..5d28013c85 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequest.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequest.java
@@ -27,62 +27,59 @@ import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"action",
-"uri",
-"body"
-})
+@JsonPropertyOrder({"action", "uri", "body"})
public class OperationBodyRequest {
-@JsonProperty("action")
-private String action;
-@JsonProperty("uri")
-private String uri;
-@JsonProperty("body")
-@JsonSerialize(using = OperationBodyRequestSerializer.class)
-private Object body;
+ @JsonProperty("action")
+ private String action;
+ @JsonProperty("uri")
+ private String uri;
+ @JsonProperty("body")
+ @JsonSerialize(using = OperationBodyRequestSerializer.class)
+ private Object body;
-public String getAction() {
- return action;
-}
+ public String getAction() {
+ return action;
+ }
-public void setAction(String action) {
- this.action = action;
-}
+ public void setAction(String action) {
+ this.action = action;
+ }
-public OperationBodyRequest withAction(String action) {
- this.action = action;
- return this;
-}
-@JsonProperty("uri")
-public String getUri() {
-return uri;
-}
+ public OperationBodyRequest withAction(String action) {
+ this.action = action;
+ return this;
+ }
-@JsonProperty("uri")
-public void setUri(String uri) {
-this.uri = uri;
-}
+ @JsonProperty("uri")
+ public String getUri() {
+ return uri;
+ }
-public OperationBodyRequest withUri(String uri) {
-this.uri = uri;
-return this;
-}
+ @JsonProperty("uri")
+ public void setUri(String uri) {
+ this.uri = uri;
+ }
-@JsonProperty("body")
-public Object getBody() {
-return body;
-}
+ public OperationBodyRequest withUri(String uri) {
+ this.uri = uri;
+ return this;
+ }
-@JsonProperty("body")
-public void setBody(Object body) {
-this.body = body;
-}
+ @JsonProperty("body")
+ public Object getBody() {
+ return body;
+ }
-public OperationBodyRequest withBody(Object body) {
-this.body = body;
-return this;
-}
+ @JsonProperty("body")
+ public void setBody(Object body) {
+ this.body = body;
+ }
+
+ public OperationBodyRequest withBody(Object body) {
+ this.body = body;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequestSerializer.java b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequestSerializer.java
index 170719962e..addc3f1364 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequestSerializer.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequestSerializer.java
@@ -21,7 +21,6 @@
package org.onap.so.client.aai.entities.singletransaction;
import java.io.IOException;
-
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
@@ -29,26 +28,27 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class OperationBodyRequestSerializer extends StdSerializer<Object> {
- private static final long serialVersionUID = 5367385969270400106L;
-
- public OperationBodyRequestSerializer() {
- this(null);
- }
- public OperationBodyRequestSerializer(Class<Object> t) {
- super(t);
- }
-
- @Override
- public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
- throws IOException, JsonProcessingException {
-
- if (value instanceof String) {
- gen.writeRawValue((String)value);
- } else {
- gen.writeObject(value);
- }
-
- }
+ private static final long serialVersionUID = 5367385969270400106L;
+
+ public OperationBodyRequestSerializer() {
+ this(null);
+ }
+
+ public OperationBodyRequestSerializer(Class<Object> t) {
+ super(t);
+ }
+
+ @Override
+ public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
+ throws IOException, JsonProcessingException {
+
+ if (value instanceof String) {
+ gen.writeRawValue((String) value);
+ } else {
+ gen.writeObject(value);
+ }
+
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyResponse.java b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyResponse.java
index 71f65b50db..c5b11fe1f7 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyResponse.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyResponse.java
@@ -23,49 +23,51 @@ package org.onap.so.client.aai.entities.singletransaction;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
-@JsonPropertyOrder({
-"action",
-"uri",
-"response-status-code",
-"response-body"
-})
+@JsonPropertyOrder({"action", "uri", "response-status-code", "response-body"})
public class OperationBodyResponse {
- @JsonProperty("action")
- public String action;
- @JsonProperty("uri")
- public String uri;
- @JsonProperty("response-status-code")
- public Integer responseStatusCode;
- @JsonProperty("response-body")
- public Object responseBody;
-
- public String getAction() {
- return action;
- }
- public void setAction(String action) {
- this.action = action;
- }
- public String getUri() {
- return uri;
- }
- public void setUri(String uri) {
- this.uri = uri;
- }
- @JsonProperty("response-status-code")
- public Integer getResponseStatusCode() {
- return responseStatusCode;
- }
- @JsonProperty("response-status-code")
- public void setResponseStatusCode(Integer responseStatusCode) {
- this.responseStatusCode = responseStatusCode;
- }
- @JsonProperty("response-body")
- public Object getResponseBody() {
- return responseBody;
- }
- @JsonProperty("response-body")
- public void getResponseBody(Object responseBody) {
- this.responseBody = responseBody;
- }
+ @JsonProperty("action")
+ public String action;
+ @JsonProperty("uri")
+ public String uri;
+ @JsonProperty("response-status-code")
+ public Integer responseStatusCode;
+ @JsonProperty("response-body")
+ public Object responseBody;
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getUri() {
+ return uri;
+ }
+
+ public void setUri(String uri) {
+ this.uri = uri;
+ }
+
+ @JsonProperty("response-status-code")
+ public Integer getResponseStatusCode() {
+ return responseStatusCode;
+ }
+
+ @JsonProperty("response-status-code")
+ public void setResponseStatusCode(Integer responseStatusCode) {
+ this.responseStatusCode = responseStatusCode;
+ }
+
+ @JsonProperty("response-body")
+ public Object getResponseBody() {
+ return responseBody;
+ }
+
+ @JsonProperty("response-body")
+ public void getResponseBody(Object responseBody) {
+ this.responseBody = responseBody;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionRequest.java b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionRequest.java
index 0d392c453f..af32ca9498 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionRequest.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionRequest.java
@@ -22,24 +22,23 @@ package org.onap.so.client.aai.entities.singletransaction;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class SingleTransactionRequest {
- @JsonProperty("operations")
- public List<OperationBodyRequest> operations;
-
- public List<OperationBodyRequest> getOperations() {
-
- if (operations == null) {
- operations = new ArrayList<>();
- }
-
- return operations;
- }
-
- public void setOperations(List<OperationBodyRequest> operations) {
- this.operations = operations;
- }
+ @JsonProperty("operations")
+ public List<OperationBodyRequest> operations;
+
+ public List<OperationBodyRequest> getOperations() {
+
+ if (operations == null) {
+ operations = new ArrayList<>();
+ }
+
+ return operations;
+ }
+
+ public void setOperations(List<OperationBodyRequest> operations) {
+ this.operations = operations;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionResponse.java b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionResponse.java
index db251b5b3b..525956c5a9 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionResponse.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionResponse.java
@@ -22,26 +22,25 @@ package org.onap.so.client.aai.entities.singletransaction;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class SingleTransactionResponse {
- @JsonProperty("operation-responses")
- public List<OperationBodyResponse> operationResponses;
-
- @JsonProperty("operation-responses")
- public List<OperationBodyResponse> getOperationResponses() {
- if (operationResponses == null) {
- operationResponses = new ArrayList<>();
- }
- return operationResponses;
- }
-
- @JsonProperty("operation-responses")
- public void setOperationResponses(List<OperationBodyResponse> operationResponses) {
- this.operationResponses = operationResponses;
- }
-
-
+ @JsonProperty("operation-responses")
+ public List<OperationBodyResponse> operationResponses;
+
+ @JsonProperty("operation-responses")
+ public List<OperationBodyResponse> getOperationResponses() {
+ if (operationResponses == null) {
+ operationResponses = new ArrayList<>();
+ }
+ return operationResponses;
+ }
+
+ @JsonProperty("operation-responses")
+ public void setOperationResponses(List<OperationBodyResponse> operationResponses) {
+ this.operationResponses = operationResponses;
+ }
+
+
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIResourceUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIResourceUri.java
index 8775a6a687..70dfd581e8 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIResourceUri.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIResourceUri.java
@@ -28,25 +28,37 @@ import org.onap.so.client.graphinventory.entities.uri.GraphInventoryResourceUri;
public interface AAIResourceUri extends AAIUri, GraphInventoryResourceUri {
- public AAIResourceUri relationshipAPI();
- public AAIResourceUri relatedTo(AAIObjectPlurals plural);
- public AAIResourceUri relatedTo(AAIObjectType type, String... values);
- public AAIResourceUri resourceVersion(String version);
- public AAIResourceUri format(Format format);
- @Override
- public AAIResourceUri depth(Depth depth);
- @Override
- public AAIResourceUri nodesOnly(boolean nodesOnly);
- @Override
- public AAIResourceUri queryParam(String name, String... values);
- @Override
- public AAIResourceUri replaceQueryParam(String name, String... values);
- @Override
- public AAIResourceUri resultIndex(int index);
- @Override
- public AAIResourceUri resultSize(int size);
- @Override
- public AAIResourceUri limit(int size);
- @Override
- public AAIResourceUri clone();
+ public AAIResourceUri relationshipAPI();
+
+ public AAIResourceUri relatedTo(AAIObjectPlurals plural);
+
+ public AAIResourceUri relatedTo(AAIObjectType type, String... values);
+
+ public AAIResourceUri resourceVersion(String version);
+
+ public AAIResourceUri format(Format format);
+
+ @Override
+ public AAIResourceUri depth(Depth depth);
+
+ @Override
+ public AAIResourceUri nodesOnly(boolean nodesOnly);
+
+ @Override
+ public AAIResourceUri queryParam(String name, String... values);
+
+ @Override
+ public AAIResourceUri replaceQueryParam(String name, String... values);
+
+ @Override
+ public AAIResourceUri resultIndex(int index);
+
+ @Override
+ public AAIResourceUri resultSize(int size);
+
+ @Override
+ public AAIResourceUri limit(int size);
+
+ @Override
+ public AAIResourceUri clone();
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java
index 7cb37d9c3a..7572541206 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java
@@ -21,9 +21,7 @@
package org.onap.so.client.aai.entities.uri;
import java.net.URI;
-
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.client.aai.AAIObjectPlurals;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.graphinventory.Format;
@@ -33,105 +31,113 @@ import org.onap.so.client.graphinventory.entities.uri.GraphInventoryResourceUri;
import org.onap.so.client.graphinventory.entities.uri.SimpleUri;
public class AAISimpleUri extends SimpleUri implements AAIResourceUri {
-
- private static final long serialVersionUID = -6397024057188453229L;
-
- protected AAISimpleUri(AAIObjectType type, Object... values) {
- super(type, values);
-
- }
- protected AAISimpleUri(AAIObjectType type, URI uri) {
- super(type, uri);
- }
- protected AAISimpleUri(AAIObjectType type, UriBuilder builder, Object... values) {
- super(type, builder, values);
- }
- protected AAISimpleUri(AAIObjectPlurals type, UriBuilder builder, Object... values) {
- super(type, builder, values);
- }
- protected AAISimpleUri(AAIObjectPlurals type) {
- super(type);
- }
- protected AAISimpleUri(AAIObjectPlurals type, Object... values) {
- super(type, values);
- }
- protected AAISimpleUri(AAIResourceUri parentUri, AAIObjectType childType, Object... childValues) {
- super(parentUri, childType, childValues);
- }
-
- protected AAISimpleUri(AAIResourceUri parentUri, AAIObjectPlurals childType) {
- super(parentUri, childType);
- }
-
- @Override
- public AAISimpleUri relationshipAPI() {
- return (AAISimpleUri) super.relationshipAPI();
- }
-
- @Override
- public AAISimpleUri relatedTo(AAIObjectPlurals plural) {
- return (AAISimpleUri) super.relatedTo(plural);
- }
- @Override
- public AAISimpleUri relatedTo(AAIObjectType type, String... values) {
- return (AAISimpleUri) super.relatedTo(type, values);
- }
-
- @Override
- public AAISimpleUri resourceVersion(String version) {
- return (AAISimpleUri) super.resourceVersion(version);
- }
-
- @Override
- public AAISimpleUri queryParam(String name, String... values) {
- return (AAISimpleUri) super.queryParam(name, values);
- }
-
- @Override
- public AAISimpleUri replaceQueryParam(String name, String... values) {
- return (AAISimpleUri) super.replaceQueryParam(name, values);
- }
-
- @Override
- public AAISimpleUri resultIndex(int index) {
- return (AAISimpleUri) super.resultIndex(index);
- }
-
- @Override
- public AAISimpleUri resultSize(int size) {
- return (AAISimpleUri) super.resultSize(size);
- }
-
- @Override
- public AAISimpleUri limit(int size) {
- return (AAISimpleUri) super.limit(size);
- }
-
- @Override
- public AAISimpleUri clone() {
- if (this.type != null) {
- return new AAISimpleUri((AAIObjectType)this.type, this.internalURI.clone(), values);
- } else {
- return new AAISimpleUri((AAIObjectPlurals)this.pluralType, this.internalURI.clone(), values);
- }
- }
-
- @Override
- public AAIObjectType getObjectType() {
- return (AAIObjectType)this.type;
- }
-
- @Override
- public AAISimpleUri depth(Depth depth) {
- return (AAISimpleUri) super.depth(depth);
- }
- @Override
- public AAISimpleUri nodesOnly(boolean nodesOnly) {
- return (AAISimpleUri)super.nodesOnly(nodesOnly);
- }
-
- @Override
- public AAISimpleUri format(Format format) {
- return (AAISimpleUri)super.format(format);
- }
+
+ private static final long serialVersionUID = -6397024057188453229L;
+
+ protected AAISimpleUri(AAIObjectType type, Object... values) {
+ super(type, values);
+
+ }
+
+ protected AAISimpleUri(AAIObjectType type, URI uri) {
+ super(type, uri);
+ }
+
+ protected AAISimpleUri(AAIObjectType type, UriBuilder builder, Object... values) {
+ super(type, builder, values);
+ }
+
+ protected AAISimpleUri(AAIObjectPlurals type, UriBuilder builder, Object... values) {
+ super(type, builder, values);
+ }
+
+ protected AAISimpleUri(AAIObjectPlurals type) {
+ super(type);
+ }
+
+ protected AAISimpleUri(AAIObjectPlurals type, Object... values) {
+ super(type, values);
+ }
+
+ protected AAISimpleUri(AAIResourceUri parentUri, AAIObjectType childType, Object... childValues) {
+ super(parentUri, childType, childValues);
+ }
+
+ protected AAISimpleUri(AAIResourceUri parentUri, AAIObjectPlurals childType) {
+ super(parentUri, childType);
+ }
+
+ @Override
+ public AAISimpleUri relationshipAPI() {
+ return (AAISimpleUri) super.relationshipAPI();
+ }
+
+ @Override
+ public AAISimpleUri relatedTo(AAIObjectPlurals plural) {
+ return (AAISimpleUri) super.relatedTo(plural);
+ }
+
+ @Override
+ public AAISimpleUri relatedTo(AAIObjectType type, String... values) {
+ return (AAISimpleUri) super.relatedTo(type, values);
+ }
+
+ @Override
+ public AAISimpleUri resourceVersion(String version) {
+ return (AAISimpleUri) super.resourceVersion(version);
+ }
+
+ @Override
+ public AAISimpleUri queryParam(String name, String... values) {
+ return (AAISimpleUri) super.queryParam(name, values);
+ }
+
+ @Override
+ public AAISimpleUri replaceQueryParam(String name, String... values) {
+ return (AAISimpleUri) super.replaceQueryParam(name, values);
+ }
+
+ @Override
+ public AAISimpleUri resultIndex(int index) {
+ return (AAISimpleUri) super.resultIndex(index);
+ }
+
+ @Override
+ public AAISimpleUri resultSize(int size) {
+ return (AAISimpleUri) super.resultSize(size);
+ }
+
+ @Override
+ public AAISimpleUri limit(int size) {
+ return (AAISimpleUri) super.limit(size);
+ }
+
+ @Override
+ public AAISimpleUri clone() {
+ if (this.type != null) {
+ return new AAISimpleUri((AAIObjectType) this.type, this.internalURI.clone(), values);
+ } else {
+ return new AAISimpleUri((AAIObjectPlurals) this.pluralType, this.internalURI.clone(), values);
+ }
+ }
+
+ @Override
+ public AAIObjectType getObjectType() {
+ return (AAIObjectType) this.type;
+ }
+
+ @Override
+ public AAISimpleUri depth(Depth depth) {
+ return (AAISimpleUri) super.depth(depth);
+ }
+
+ @Override
+ public AAISimpleUri nodesOnly(boolean nodesOnly) {
+ return (AAISimpleUri) super.nodesOnly(nodesOnly);
+ }
+
+ @Override
+ public AAISimpleUri format(Format format) {
+ return (AAISimpleUri) super.format(format);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUri.java
index fb43cda7a4..6a4c90a6ee 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUri.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUri.java
@@ -26,37 +26,46 @@ import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri;
public interface AAIUri extends GraphInventoryUri {
- /**
- * By default A&AI enforces a depth of 1. Some objects can be told to retrieve objects
- * nested beneath them by increasing this number.
- *
- * You can use 0 to restrict the returned information to only the object you requested
- * You can use all to retrieve all nested objects (this should only be used if you really need a massive amount of information and are caching the retrieval)
- * @param depth
- * @return
- */
- @Override
- public AAIUri depth(Depth depth);
- /**
- * Makes client only return object fields, no relationships
- *
- * @return
- */
- @Override
- public AAIUri nodesOnly(boolean nodesOnly);
- @Override
- public AAIUri queryParam(String name, String... values);
- @Override
- public AAIUri replaceQueryParam(String name, String... values);
- @Override
- public AAIUri resultIndex(int index);
- @Override
- public AAIUri resultSize(int size);
- @Override
- public AAIUri limit(int size);
- @Override
- public AAIUri clone();
-
- @Override
- public AAIObjectType getObjectType();
+ /**
+ * By default A&AI enforces a depth of 1. Some objects can be told to retrieve objects nested beneath them by
+ * increasing this number.
+ *
+ * You can use 0 to restrict the returned information to only the object you requested You can use all to retrieve
+ * all nested objects (this should only be used if you really need a massive amount of information and are caching
+ * the retrieval)
+ *
+ * @param depth
+ * @return
+ */
+ @Override
+ public AAIUri depth(Depth depth);
+
+ /**
+ * Makes client only return object fields, no relationships
+ *
+ * @return
+ */
+ @Override
+ public AAIUri nodesOnly(boolean nodesOnly);
+
+ @Override
+ public AAIUri queryParam(String name, String... values);
+
+ @Override
+ public AAIUri replaceQueryParam(String name, String... values);
+
+ @Override
+ public AAIUri resultIndex(int index);
+
+ @Override
+ public AAIUri resultSize(int size);
+
+ @Override
+ public AAIUri limit(int size);
+
+ @Override
+ public AAIUri clone();
+
+ @Override
+ public AAIObjectType getObjectType();
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java
index ac0aba3c36..406ff09952 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java
@@ -21,96 +21,94 @@
package org.onap.so.client.aai.entities.uri;
import java.net.URI;
-
import org.onap.so.client.aai.AAIObjectPlurals;
import org.onap.so.client.aai.AAIObjectType;
public class AAIUriFactory {
-
- /**
- * values are filled into the URI template specified in {@link AAIObjectType} in order
- * <br>
- * There are two special lookups performed on certain types when a single value is specified:
- * <br>
- * Service Instance and AllottedResources
- * <br>
- * These can be retrieved without all their required keys but an HTTP call is required to do so
- * @param type
- * @param values
- * @return
- */
- public static AAIResourceUri createResourceUri(AAIObjectType type, Object... values) {
- if (AAIObjectType.SERVICE_INSTANCE.equals(type)) {
- return new ServiceInstanceUri(values);
- } else if (AAIObjectType.ALLOTTED_RESOURCE.equals(type)) {
- return new AllottedResourceLookupUri(values);
- } else {
- return new AAISimpleUri(type, values);
- }
- }
-
- public static AAIResourceUri createNodesUri(AAIObjectType type, Object... values) {
- return new NodesUri(type, values);
-
- }
-
- public static AAIResourceUri createNodesUri(AAIObjectPlurals type) {
- return new NodesUri(type);
-
- }
-
- /**
- * This method should only be used to wrap a URI retrieved from A&AI contained within an object response
- *
- * @param type
- * @param uri
- * @return
- */
- public static AAIResourceUri createResourceFromExistingURI(AAIObjectType type, URI uri) {
- return new AAISimpleUri(type, uri);
- }
-
-
- /**
- * creates an AAIResourceUri from a parentUri
- *
- * @param parentUri
- * @param childType
- * @param childValues
- * @return
- */
- public static AAIResourceUri createResourceFromParentURI(AAIResourceUri parentUri, AAIObjectType childType, Object... childValues) {
-
- return new AAISimpleUri(parentUri, childType, childValues);
- }
-
- public static AAIResourceUri createResourceFromParentURI(AAIResourceUri parentUri, AAIObjectPlurals childType) {
-
- return new AAISimpleUri(parentUri, childType);
- }
-
- /**
- * Creates a uri for a plural type e.g. /cloud-infrastructure/pservers
- *
- * @param type
- * @return
- */
- public static AAIResourceUri createResourceUri(AAIObjectPlurals type) {
-
- return new AAISimpleUri(type);
-
- }
-
- /**
- * Creates a uri for a plural type with values e.g. /cloud-infrastructure/pservers
- *
- * @param type
- * @return
- */
- public static AAIResourceUri createResourceUri(AAIObjectPlurals type, Object... values) {
-
- return new AAISimpleUri(type, values);
-
- }
-} \ No newline at end of file
+
+ /**
+ * values are filled into the URI template specified in {@link AAIObjectType} in order <br>
+ * There are two special lookups performed on certain types when a single value is specified: <br>
+ * Service Instance and AllottedResources <br>
+ * These can be retrieved without all their required keys but an HTTP call is required to do so
+ *
+ * @param type
+ * @param values
+ * @return
+ */
+ public static AAIResourceUri createResourceUri(AAIObjectType type, Object... values) {
+ if (AAIObjectType.SERVICE_INSTANCE.equals(type)) {
+ return new ServiceInstanceUri(values);
+ } else if (AAIObjectType.ALLOTTED_RESOURCE.equals(type)) {
+ return new AllottedResourceLookupUri(values);
+ } else {
+ return new AAISimpleUri(type, values);
+ }
+ }
+
+ public static AAIResourceUri createNodesUri(AAIObjectType type, Object... values) {
+ return new NodesUri(type, values);
+
+ }
+
+ public static AAIResourceUri createNodesUri(AAIObjectPlurals type) {
+ return new NodesUri(type);
+
+ }
+
+ /**
+ * This method should only be used to wrap a URI retrieved from A&AI contained within an object response
+ *
+ * @param type
+ * @param uri
+ * @return
+ */
+ public static AAIResourceUri createResourceFromExistingURI(AAIObjectType type, URI uri) {
+ return new AAISimpleUri(type, uri);
+ }
+
+
+ /**
+ * creates an AAIResourceUri from a parentUri
+ *
+ * @param parentUri
+ * @param childType
+ * @param childValues
+ * @return
+ */
+ public static AAIResourceUri createResourceFromParentURI(AAIResourceUri parentUri, AAIObjectType childType,
+ Object... childValues) {
+
+ return new AAISimpleUri(parentUri, childType, childValues);
+ }
+
+ public static AAIResourceUri createResourceFromParentURI(AAIResourceUri parentUri, AAIObjectPlurals childType) {
+
+ return new AAISimpleUri(parentUri, childType);
+ }
+
+ /**
+ * Creates a uri for a plural type e.g. /cloud-infrastructure/pservers
+ *
+ * @param type
+ * @return
+ */
+ public static AAIResourceUri createResourceUri(AAIObjectPlurals type) {
+
+ return new AAISimpleUri(type);
+
+ }
+
+ /**
+ * Creates a uri for a plural type with values e.g. /cloud-infrastructure/pservers
+ *
+ * @param type
+ * @return
+ */
+ public static AAIResourceUri createResourceUri(AAIObjectPlurals type, Object... values) {
+
+ return new AAISimpleUri(type, values);
+
+ }
+}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUri.java
index 329471243b..30e60cdff2 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUri.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUri.java
@@ -22,32 +22,33 @@ package org.onap.so.client.aai.entities.uri;
import java.net.URI;
import java.util.Optional;
-
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.AAIResourcesClient;
public class AllottedResourceLookupUri extends HttpLookupUri {
- private static final long serialVersionUID = -9212594383876793188L;
- protected AllottedResourceLookupUri(Object... values) {
- super(AAIObjectType.ALLOTTED_RESOURCE, values);
- }
- protected AllottedResourceLookupUri(UriBuilder builder, Optional<String> cachedValue, Object... values) {
- super(AAIObjectType.ALLOTTED_RESOURCE, builder, cachedValue, values);
- }
-
- @Override
- public AllottedResourceLookupUri clone() {
- return new AllottedResourceLookupUri(this.internalURI.clone(), this.getCachedValue(), values);
- }
-
- public AAIResourcesClient getResourcesClient() {
- return new AAIResourcesClient();
- }
- @Override
- public URI buildNoNetwork() {
- return super.build(new String[]{"NONE", "NONE", "NONE", (String)this.values[0]});
- }
+ private static final long serialVersionUID = -9212594383876793188L;
+
+ protected AllottedResourceLookupUri(Object... values) {
+ super(AAIObjectType.ALLOTTED_RESOURCE, values);
+ }
+
+ protected AllottedResourceLookupUri(UriBuilder builder, Optional<String> cachedValue, Object... values) {
+ super(AAIObjectType.ALLOTTED_RESOURCE, builder, cachedValue, values);
+ }
+
+ @Override
+ public AllottedResourceLookupUri clone() {
+ return new AllottedResourceLookupUri(this.internalURI.clone(), this.getCachedValue(), values);
+ }
+
+ public AAIResourcesClient getResourcesClient() {
+ return new AAIResourcesClient();
+ }
+
+ @Override
+ public URI buildNoNetwork() {
+ return super.build(new String[] {"NONE", "NONE", "NONE", (String) this.values[0]});
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java
index a627480d5d..f086a6abcf 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java
@@ -24,11 +24,9 @@ import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Optional;
-
import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.AAIResourcesClient;
import org.onap.so.client.aai.entities.Results;
@@ -39,101 +37,108 @@ import org.onap.so.client.graphinventory.exceptions.GraphInventoryPayloadExcepti
import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriComputationException;
import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriNotFoundException;
import org.onap.so.client.graphinventory.exceptions.IncorrectNumberOfUriKeys;
-
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class HttpLookupUri extends AAISimpleUri implements HttpAwareUri {
- private Optional<String> cachedValue = Optional.empty();
- private final AAIObjectType aaiType;
- protected HttpLookupUri(AAIObjectType type, Object... values) {
- super(type, values);
- this.aaiType = type;
- }
- protected HttpLookupUri(AAIObjectType type, UriBuilder builder, Optional<String> cachedValue, Object... values) {
- super(type, builder, values);
- this.cachedValue = cachedValue;
- this.aaiType = type;
- }
- protected String getObjectById(Object id) throws GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
- if (!this.getCachedValue().isPresent()) {
- AAIResourceUri serviceInstanceUri = AAIUriFactory.createNodesUri(aaiType, id).format(Format.PATHED);
- String resultJson;
- try {
- resultJson = this.getResourcesClient().get(serviceInstanceUri, NotFoundException.class).getJson();
- } catch (BadRequestException e) {
- throw new GraphInventoryUriNotFoundException(aaiType.typeName() + " " + id + " not found at: " + serviceInstanceUri.build());
-
- }
- try {
- cachedValue = extractRelatedLink(resultJson);
- if (!cachedValue.isPresent()) {
- throw new GraphInventoryUriNotFoundException(aaiType.typeName() + " " + id + " not found at: " + serviceInstanceUri.build());
- }
- } catch (IOException e) {
- throw new GraphInventoryPayloadException("could not map payload: " + resultJson, e);
- }
- }
- Optional<String> cachedValueOpt = this.getCachedValue();
- return cachedValueOpt.isPresent() ? cachedValueOpt.get() : "";
- }
-
- protected Optional<String> extractRelatedLink(String jsonString) throws IOException {
- Optional<String> result;
- ObjectMapper mapper = new ObjectMapper();
-
- Results<Pathed> results = mapper.readValue(jsonString, new TypeReference<Results<Pathed>>(){});
- if (results.getResult().size() == 1) {
- String uriString = results.getResult().get(0).getResourceLink();
- URI uri = UriBuilder.fromUri(uriString).build();
- String rawPath = uri.getRawPath();
- result = Optional.of(rawPath.replaceAll("/aai/v\\d+", ""));
- } else if (results.getResult().isEmpty()) {
- result = Optional.empty();
- } else {
- throw new IllegalStateException("more than one result returned");
- }
-
- return result;
- }
-
- protected Optional<String> getCachedValue() {
- return this.cachedValue;
- }
-
- @Override
- public URI build() {
- try {
- if (this.values.length == 1) {
- String uri = getObjectById(this.values[0]);
- Map<String, String> map = getURIKeys(uri);
- return super.build(map.values().toArray(values));
- }
- } catch (GraphInventoryUriNotFoundException | GraphInventoryPayloadException e) {
- throw new GraphInventoryUriComputationException(e);
- }
- return super.build();
- }
-
- @Override
- public abstract HttpLookupUri clone();
-
- @Override
- public void validateValuesSize(String template, Object... values) {
- try {
- super.validateValuesSize(template, values);
- } catch (IncorrectNumberOfUriKeys e) {
- if (values.length == 1) {
- //Special case where we perform an http look up
- } else {
- throw e;
- }
- }
- }
- public AAIResourcesClient getResourcesClient() {
- return new AAIResourcesClient();
- }
- @Override
- public abstract URI buildNoNetwork();
+ private Optional<String> cachedValue = Optional.empty();
+ private final AAIObjectType aaiType;
+
+ protected HttpLookupUri(AAIObjectType type, Object... values) {
+ super(type, values);
+ this.aaiType = type;
+ }
+
+ protected HttpLookupUri(AAIObjectType type, UriBuilder builder, Optional<String> cachedValue, Object... values) {
+ super(type, builder, values);
+ this.cachedValue = cachedValue;
+ this.aaiType = type;
+ }
+
+ protected String getObjectById(Object id)
+ throws GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
+ if (!this.getCachedValue().isPresent()) {
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createNodesUri(aaiType, id).format(Format.PATHED);
+ String resultJson;
+ try {
+ resultJson = this.getResourcesClient().get(serviceInstanceUri, NotFoundException.class).getJson();
+ } catch (BadRequestException e) {
+ throw new GraphInventoryUriNotFoundException(
+ aaiType.typeName() + " " + id + " not found at: " + serviceInstanceUri.build());
+
+ }
+ try {
+ cachedValue = extractRelatedLink(resultJson);
+ if (!cachedValue.isPresent()) {
+ throw new GraphInventoryUriNotFoundException(
+ aaiType.typeName() + " " + id + " not found at: " + serviceInstanceUri.build());
+ }
+ } catch (IOException e) {
+ throw new GraphInventoryPayloadException("could not map payload: " + resultJson, e);
+ }
+ }
+ Optional<String> cachedValueOpt = this.getCachedValue();
+ return cachedValueOpt.isPresent() ? cachedValueOpt.get() : "";
+ }
+
+ protected Optional<String> extractRelatedLink(String jsonString) throws IOException {
+ Optional<String> result;
+ ObjectMapper mapper = new ObjectMapper();
+
+ Results<Pathed> results = mapper.readValue(jsonString, new TypeReference<Results<Pathed>>() {});
+ if (results.getResult().size() == 1) {
+ String uriString = results.getResult().get(0).getResourceLink();
+ URI uri = UriBuilder.fromUri(uriString).build();
+ String rawPath = uri.getRawPath();
+ result = Optional.of(rawPath.replaceAll("/aai/v\\d+", ""));
+ } else if (results.getResult().isEmpty()) {
+ result = Optional.empty();
+ } else {
+ throw new IllegalStateException("more than one result returned");
+ }
+
+ return result;
+ }
+
+ protected Optional<String> getCachedValue() {
+ return this.cachedValue;
+ }
+
+ @Override
+ public URI build() {
+ try {
+ if (this.values.length == 1) {
+ String uri = getObjectById(this.values[0]);
+ Map<String, String> map = getURIKeys(uri);
+ return super.build(map.values().toArray(values));
+ }
+ } catch (GraphInventoryUriNotFoundException | GraphInventoryPayloadException e) {
+ throw new GraphInventoryUriComputationException(e);
+ }
+ return super.build();
+ }
+
+ @Override
+ public abstract HttpLookupUri clone();
+
+ @Override
+ public void validateValuesSize(String template, Object... values) {
+ try {
+ super.validateValuesSize(template, values);
+ } catch (IncorrectNumberOfUriKeys e) {
+ if (values.length == 1) {
+ // Special case where we perform an http look up
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ public AAIResourcesClient getResourcesClient() {
+ return new AAIResourcesClient();
+ }
+
+ @Override
+ public abstract URI buildNoNetwork();
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/NodesUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/NodesUri.java
index 6ffc6ecd9b..4b4b5d92a2 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/uri/NodesUri.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/NodesUri.java
@@ -21,7 +21,6 @@
package org.onap.so.client.aai.entities.uri;
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.client.aai.AAIObjectPlurals;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.graphinventory.GraphInventoryObjectPlurals;
@@ -29,24 +28,24 @@ import org.onap.so.client.graphinventory.GraphInventoryObjectType;
public class NodesUri extends AAISimpleUri {
- private static final long serialVersionUID = 8818689895730182042L;
-
- protected NodesUri(AAIObjectType type, Object... values) {
- super(type, values);
- }
-
- protected NodesUri(AAIObjectPlurals type) {
- super(type);
- }
-
-
- @Override
- protected String getTemplate(GraphInventoryObjectType type) {
- return UriBuilder.fromUri("/nodes").path(type.partialUri()).toTemplate();
- }
-
- @Override
- protected String getTemplate(GraphInventoryObjectPlurals type) {
- return UriBuilder.fromUri("/nodes").path(type.partialUri()).toTemplate();
- }
+ private static final long serialVersionUID = 8818689895730182042L;
+
+ protected NodesUri(AAIObjectType type, Object... values) {
+ super(type, values);
+ }
+
+ protected NodesUri(AAIObjectPlurals type) {
+ super(type);
+ }
+
+
+ @Override
+ protected String getTemplate(GraphInventoryObjectType type) {
+ return UriBuilder.fromUri("/nodes").path(type.partialUri()).toTemplate();
+ }
+
+ @Override
+ protected String getTemplate(GraphInventoryObjectPlurals type) {
+ return UriBuilder.fromUri("/nodes").path(type.partialUri()).toTemplate();
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java
index 324193dc84..0b62d05c67 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java
@@ -22,32 +22,33 @@ package org.onap.so.client.aai.entities.uri;
import java.net.URI;
import java.util.Optional;
-
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.AAIResourcesClient;
public class ServiceInstanceUri extends HttpLookupUri {
- private static final long serialVersionUID = 2248914170527514548L;
- protected ServiceInstanceUri(Object... values) {
- super(AAIObjectType.SERVICE_INSTANCE, values);
- }
- protected ServiceInstanceUri(UriBuilder builder, Optional<String> cachedValue, Object... values) {
- super(AAIObjectType.SERVICE_INSTANCE, builder, cachedValue, values);
- }
-
- @Override
- public ServiceInstanceUri clone() {
- return new ServiceInstanceUri(this.internalURI.clone(), this.getCachedValue(), values);
- }
-
- public AAIResourcesClient getResourcesClient() {
- return new AAIResourcesClient();
- }
- @Override
- public URI buildNoNetwork() {
- return super.build(new String[]{"NONE", "NONE", (String)this.values[0]});
- }
+ private static final long serialVersionUID = 2248914170527514548L;
+
+ protected ServiceInstanceUri(Object... values) {
+ super(AAIObjectType.SERVICE_INSTANCE, values);
+ }
+
+ protected ServiceInstanceUri(UriBuilder builder, Optional<String> cachedValue, Object... values) {
+ super(AAIObjectType.SERVICE_INSTANCE, builder, cachedValue, values);
+ }
+
+ @Override
+ public ServiceInstanceUri clone() {
+ return new ServiceInstanceUri(this.internalURI.clone(), this.getCachedValue(), values);
+ }
+
+ public AAIResourcesClient getResourcesClient() {
+ return new AAIResourcesClient();
+ }
+
+ @Override
+ public URI buildNoNetwork() {
+ return super.build(new String[] {"NONE", "NONE", (String) this.values[0]});
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestClient.java b/common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestClient.java
index 9d72fdf85b..d6c7072c14 100644
--- a/common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestClient.java
+++ b/common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestClient.java
@@ -24,7 +24,6 @@ import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Map;
import java.util.Optional;
-
import org.apache.commons.codec.binary.Base64;
import org.onap.so.client.RestClient;
import org.onap.so.client.policy.CommonObjectMapperProvider;
@@ -34,46 +33,47 @@ import org.onap.so.utils.TargetEntity;
public class AdapterRestClient extends RestClient {
- private final AdapterRestProperties adapterRestProperties;
- public AdapterRestClient(AdapterRestProperties props, URI uri) {
- super(props, Optional.of(uri));
- this.adapterRestProperties = props;
- }
+ private final AdapterRestProperties adapterRestProperties;
- public AdapterRestClient(AdapterRestProperties props, URI uri, String accept, String contentType) {
- super(props, Optional.of(uri), accept, contentType);
- this.adapterRestProperties = props;
- }
+ public AdapterRestClient(AdapterRestProperties props, URI uri) {
+ super(props, Optional.of(uri));
+ this.adapterRestProperties = props;
+ }
+
+ public AdapterRestClient(AdapterRestProperties props, URI uri, String accept, String contentType) {
+ super(props, Optional.of(uri), accept, contentType);
+ this.adapterRestProperties = props;
+ }
@Override
- public TargetEntity getTargetEntity(){
+ public TargetEntity getTargetEntity() {
return TargetEntity.OPENSTACK_ADAPTER;
}
- @Override
- protected void initializeHeaderMap(Map<String, String> headerMap) {
- headerMap.put("Authorization",
- this.getBasicAuth(adapterRestProperties.getAuth(), adapterRestProperties.getKey()));
- }
+ @Override
+ protected void initializeHeaderMap(Map<String, String> headerMap) {
+ headerMap.put("Authorization",
+ this.getBasicAuth(adapterRestProperties.getAuth(), adapterRestProperties.getKey()));
+ }
+
+ @Override
+ protected CommonObjectMapperProvider getCommonObjectMapperProvider() {
+ return new JettisonStyleMapperProvider();
+ }
- @Override
- protected CommonObjectMapperProvider getCommonObjectMapperProvider() {
- return new JettisonStyleMapperProvider();
- }
-
- private String getBasicAuth(String encryptedAuth, String msoKey) {
- if ((encryptedAuth == null || encryptedAuth.isEmpty()) || (msoKey == null || msoKey.isEmpty())) {
- return null;
- }
- try {
- String auth = CryptoUtils.decrypt(encryptedAuth, msoKey);
- byte[] encoded = Base64.encodeBase64(auth.getBytes());
- String encodedString = new String(encoded);
- encodedString = "Basic " + encodedString;
- return encodedString;
- } catch (GeneralSecurityException e) {
- logger.error(e.getMessage(),e);
- return null;
- }
- }
+ private String getBasicAuth(String encryptedAuth, String msoKey) {
+ if ((encryptedAuth == null || encryptedAuth.isEmpty()) || (msoKey == null || msoKey.isEmpty())) {
+ return null;
+ }
+ try {
+ String auth = CryptoUtils.decrypt(encryptedAuth, msoKey);
+ byte[] encoded = Base64.encodeBase64(auth.getBytes());
+ String encodedString = new String(encoded);
+ encodedString = "Basic " + encodedString;
+ return encodedString;
+ } catch (GeneralSecurityException e) {
+ logger.error(e.getMessage(), e);
+ return null;
+ }
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestProperties.java b/common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestProperties.java
index 18e0bd8996..5dcc6d52d7 100644
--- a/common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestProperties.java
+++ b/common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestProperties.java
@@ -24,6 +24,7 @@ import org.onap.so.client.RestProperties;
public interface AdapterRestProperties extends RestProperties {
- public String getAuth();
- public String getKey();
+ public String getAuth();
+
+ public String getKey();
}
diff --git a/common/src/main/java/org/onap/so/client/cds/BasicAuthClientInterceptor.java b/common/src/main/java/org/onap/so/client/cds/BasicAuthClientInterceptor.java
index edd4e6dfa4..66beec0d48 100644
--- a/common/src/main/java/org/onap/so/client/cds/BasicAuthClientInterceptor.java
+++ b/common/src/main/java/org/onap/so/client/cds/BasicAuthClientInterceptor.java
@@ -39,15 +39,12 @@ public class BasicAuthClientInterceptor implements ClientInterceptor {
}
@Override
- public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
- MethodDescriptor<ReqT, RespT> method,
- CallOptions callOptions,
- Channel channel) {
+ public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method,
+ CallOptions callOptions, Channel channel) {
Key<String> authHeader = Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER);
- return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(
- channel.newCall(method, callOptions)) {
+ return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(channel.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
headers.put(authHeader, props.getBasicAuth());
diff --git a/common/src/main/java/org/onap/so/client/cds/CDSProcessingClient.java b/common/src/main/java/org/onap/so/client/cds/CDSProcessingClient.java
index 9b2fd3fdb0..7ef158996d 100644
--- a/common/src/main/java/org/onap/so/client/cds/CDSProcessingClient.java
+++ b/common/src/main/java/org/onap/so/client/cds/CDSProcessingClient.java
@@ -33,18 +33,17 @@ import org.slf4j.LoggerFactory;
/**
* <p>
- * The CDS processing client is using gRPC for communication between SO and CDS.
- * That communication is configured to use a streaming approach, meaning that
- * client can send an event to which server can reply will multiple sub-responses,
+ * The CDS processing client is using gRPC for communication between SO and CDS. That communication is configured to use
+ * a streaming approach, meaning that client can send an event to which server can reply will multiple sub-responses,
* until full completion of the processing.
* </p>
* <p>
- * In order for the caller to manage the callback, it is the responsibility of the
- * caller to implement and provide a {@link CDSProcessingListener} so received messages
- * can be handled appropriately.
+ * In order for the caller to manage the callback, it is the responsibility of the caller to implement and provide a
+ * {@link CDSProcessingListener} so received messages can be handled appropriately.
* </p>
*
* Here is an example of implementation of such listener:
+ *
* <pre>
* new CDSProcessingListener {
*
@@ -72,15 +71,12 @@ public class CDSProcessingClient implements AutoCloseable {
CDSProperties props = RestPropertiesLoader.getInstance().getNewImpl(CDSProperties.class);
if (props == null) {
throw new PreconditionFailedException(
- "No RestProperty.CDSProperties implementation found on classpath, can't create client.");
+ "No RestProperty.CDSProperties implementation found on classpath, can't create client.");
}
- this.channel = NettyChannelBuilder
- .forAddress(props.getHost(), props.getPort())
- .nameResolverFactory(new DnsNameResolverProvider())
- .loadBalancerFactory(new PickFirstLoadBalancerProvider())
- .intercept(new BasicAuthClientInterceptor(props))
- .usePlaintext()
- .build();
+ this.channel = NettyChannelBuilder.forAddress(props.getHost(), props.getPort())
+ .nameResolverFactory(new DnsNameResolverProvider())
+ .loadBalancerFactory(new PickFirstLoadBalancerProvider())
+ .intercept(new BasicAuthClientInterceptor(props)).usePlaintext().build();
this.handler = new CDSProcessingHandler(listener);
log.info("CDSProcessingClient started");
}
@@ -93,16 +89,14 @@ public class CDSProcessingClient implements AutoCloseable {
/**
* Sends a request to the CDS backend micro-service.
*
- * The caller will be returned a CountDownLatch that can be used
- * to define how long the processing can wait. The CountDownLatch is
- * initiated with just 1 count. When the client receives an #onCompleted callback,
- * the counter will decrement.
+ * The caller will be returned a CountDownLatch that can be used to define how long the processing can wait. The
+ * CountDownLatch is initiated with just 1 count. When the client receives an #onCompleted callback, the counter
+ * will decrement.
*
* It is the user responsibility to close the client.
*
* @param input request to send
- * @return CountDownLatch instance that can be use to #await for
- * completeness of processing
+ * @return CountDownLatch instance that can be use to #await for completeness of processing
*/
public CountDownLatch sendRequest(ExecutionServiceInput input) {
return handler.process(input, channel);
diff --git a/common/src/main/java/org/onap/so/client/cds/CDSProcessingHandler.java b/common/src/main/java/org/onap/so/client/cds/CDSProcessingHandler.java
index 4b86493f79..9fdcb8e13e 100644
--- a/common/src/main/java/org/onap/so/client/cds/CDSProcessingHandler.java
+++ b/common/src/main/java/org/onap/so/client/cds/CDSProcessingHandler.java
@@ -46,7 +46,7 @@ class CDSProcessingHandler {
ActionIdentifiers header = request.getActionIdentifiers();
log.info("Processing blueprint({}:{}) for action({})", header.getBlueprintVersion(), header.getBlueprintName(),
- header.getBlueprintVersion());
+ header.getBlueprintVersion());
final CountDownLatch finishLatch = new CountDownLatch(1);
@@ -67,7 +67,7 @@ class CDSProcessingHandler {
@Override
public void onCompleted() {
log.info("Completed blueprint({}:{}) for action({})", header.getBlueprintVersion(),
- header.getBlueprintName(), header.getBlueprintVersion());
+ header.getBlueprintName(), header.getBlueprintVersion());
finishLatch.countDown();
}
};
diff --git a/common/src/main/java/org/onap/so/client/cds/CDSProperties.java b/common/src/main/java/org/onap/so/client/cds/CDSProperties.java
index 59c64e0459..a1e58c6a08 100644
--- a/common/src/main/java/org/onap/so/client/cds/CDSProperties.java
+++ b/common/src/main/java/org/onap/so/client/cds/CDSProperties.java
@@ -1,17 +1,14 @@
/*
* Copyright (C) 2019 Bell Canada.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
*/
package org.onap.so.client.cds;
@@ -25,6 +22,6 @@ public interface CDSProperties extends RestProperties {
int getPort();
String getBasicAuth();
-
+
int getTimeout();
}
diff --git a/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java b/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java
index ffebe77620..4ca5690188 100644
--- a/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java
+++ b/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.client.defaultproperties;
import java.io.File;
@@ -27,23 +27,24 @@ import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
-
import org.onap.so.client.dmaap.DmaapProperties;
public class DefaultDmaapPropertiesImpl implements DmaapProperties {
- private final Map<String, String> properties;
- public DefaultDmaapPropertiesImpl() throws IOException {
- File initialFile = new File("src/test/resources/dmaap.properties");
- InputStream targetStream = new FileInputStream(initialFile);
- Properties properties = new Properties();
- properties.load(targetStream);
- this.properties = new HashMap<>();
- properties.forEach((key, value) -> this.properties.put((String)key, (String)value));
- }
- @Override
- public Map<String, String> getProperties() {
- return this.properties;
- }
+ private final Map<String, String> properties;
+
+ public DefaultDmaapPropertiesImpl() throws IOException {
+ File initialFile = new File("src/test/resources/dmaap.properties");
+ InputStream targetStream = new FileInputStream(initialFile);
+ Properties properties = new Properties();
+ properties.load(targetStream);
+ this.properties = new HashMap<>();
+ properties.forEach((key, value) -> this.properties.put((String) key, (String) value));
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return this.properties;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/defaultproperties/PolicyRestPropertiesImpl.java b/common/src/main/java/org/onap/so/client/defaultproperties/PolicyRestPropertiesImpl.java
index 9e4574df4c..06aaf6de3c 100644
--- a/common/src/main/java/org/onap/so/client/defaultproperties/PolicyRestPropertiesImpl.java
+++ b/common/src/main/java/org/onap/so/client/defaultproperties/PolicyRestPropertiesImpl.java
@@ -29,53 +29,54 @@ import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
-
import org.onap.so.client.policy.PolicyRestProperties;
public class PolicyRestPropertiesImpl implements PolicyRestProperties {
-
- final Map<Object, Object> props;
- public PolicyRestPropertiesImpl() {
- File initialFile = new File("src/test/resources/policy.properties");
- Map<Object, Object> temp;
- try (InputStream targetStream = new FileInputStream(initialFile)) {
- Properties properties = new Properties();
- properties.load(targetStream);
- temp = properties;
- } catch (IOException e) {
- temp = new HashMap<>();
- }
- this.props = temp;
-
- }
- @Override
- public URL getEndpoint() {
- try {
- return new URL((String)props.getOrDefault("policy.endpoint", ""));
- } catch (MalformedURLException e) {
- return null;
- }
- }
- @Override
- public String getSystemName() {
- return "MSO";
- }
-
- @Override
- public String getClientAuth() {
- return (String)props.get("policy.client.auth");
- }
-
- @Override
- public String getAuth() {
- return (String)props.get("policy.auth");
- }
-
- @Override
- public String getEnvironment() {
- return (String)props.get("policy.environment");
- }
+ final Map<Object, Object> props;
+
+ public PolicyRestPropertiesImpl() {
+ File initialFile = new File("src/test/resources/policy.properties");
+ Map<Object, Object> temp;
+ try (InputStream targetStream = new FileInputStream(initialFile)) {
+ Properties properties = new Properties();
+ properties.load(targetStream);
+ temp = properties;
+ } catch (IOException e) {
+ temp = new HashMap<>();
+ }
+ this.props = temp;
+
+ }
+
+ @Override
+ public URL getEndpoint() {
+ try {
+ return new URL((String) props.getOrDefault("policy.endpoint", ""));
+ } catch (MalformedURLException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public String getSystemName() {
+ return "MSO";
+ }
+
+ @Override
+ public String getClientAuth() {
+ return (String) props.get("policy.client.auth");
+ }
+
+ @Override
+ public String getAuth() {
+ return (String) props.get("policy.auth");
+ }
+
+ @Override
+ public String getEnvironment() {
+ return (String) props.get("policy.environment");
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/dmaap/Consumer.java b/common/src/main/java/org/onap/so/client/dmaap/Consumer.java
index 7b1310f252..1985f6478a 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/Consumer.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/Consumer.java
@@ -22,5 +22,5 @@ package org.onap.so.client.dmaap;
public interface Consumer {
- public Iterable<String> fetch();
+ public Iterable<String> fetch();
}
diff --git a/common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java b/common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java
index dea00dd08f..86d4aa7413 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java
@@ -26,7 +26,6 @@ import java.util.Base64;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
-
import org.onap.so.client.defaultproperties.DefaultDmaapPropertiesImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -36,48 +35,48 @@ import org.onap.so.utils.CryptoUtils;
public abstract class DmaapClient {
- protected static Logger logger = LoggerFactory.getLogger(DmaapClient.class);
- protected final Map<String, String> msoProperties;
- protected final Properties properties;
+ protected static Logger logger = LoggerFactory.getLogger(DmaapClient.class);
+ protected final Map<String, String> msoProperties;
+ protected final Properties properties;
- public DmaapClient(String filepath) throws IOException {
- Resource resource = new ClassPathResource(filepath);
- DmaapProperties dmaapProperties = DmaapPropertiesLoader.getInstance().getNewImpl();
- if (dmaapProperties == null) {
- logger.error("No RestProperty implementation found on classpath, loading default");
- dmaapProperties = new DefaultDmaapPropertiesImpl();
- }
- this.msoProperties = dmaapProperties.getProperties();
- this.properties = new Properties();
- this.properties.load(resource.getInputStream());
- try {
- this.properties.put("auth", CryptoUtils.decrypt(this.getAuth(), this.getKey()).getBytes());
- } catch (GeneralSecurityException e) {
- logger.error(e.getMessage(), e);
- }
- this.properties.put("key", this.getKey());
- this.properties.put("topic", this.getTopic());
- Optional<String> host = this.getHost();
- if (host.isPresent()) {
- this.properties.put("host", host.get());
- }
- }
+ public DmaapClient(String filepath) throws IOException {
+ Resource resource = new ClassPathResource(filepath);
+ DmaapProperties dmaapProperties = DmaapPropertiesLoader.getInstance().getNewImpl();
+ if (dmaapProperties == null) {
+ logger.error("No RestProperty implementation found on classpath, loading default");
+ dmaapProperties = new DefaultDmaapPropertiesImpl();
+ }
+ this.msoProperties = dmaapProperties.getProperties();
+ this.properties = new Properties();
+ this.properties.load(resource.getInputStream());
+ try {
+ this.properties.put("auth", CryptoUtils.decrypt(this.getAuth(), this.getKey()).getBytes());
+ } catch (GeneralSecurityException e) {
+ logger.error(e.getMessage(), e);
+ }
+ this.properties.put("key", this.getKey());
+ this.properties.put("topic", this.getTopic());
+ Optional<String> host = this.getHost();
+ if (host.isPresent()) {
+ this.properties.put("host", host.get());
+ }
+ }
- protected String deobfuscatePassword(String decrypted_key) {
+ protected String deobfuscatePassword(String decrypted_key) {
- try {
- return new String(Base64.getDecoder().decode(decrypted_key.getBytes()));
- } catch (IllegalArgumentException iae) {
- logger.error("llegal Arguments", iae);
- return decrypted_key;
- }
- }
+ try {
+ return new String(Base64.getDecoder().decode(decrypted_key.getBytes()));
+ } catch (IllegalArgumentException iae) {
+ logger.error("llegal Arguments", iae);
+ return decrypted_key;
+ }
+ }
- public abstract String getKey();
+ public abstract String getKey();
- public abstract String getAuth();
+ public abstract String getAuth();
- public abstract String getTopic();
+ public abstract String getTopic();
- public abstract Optional<String> getHost();
+ public abstract Optional<String> getHost();
}
diff --git a/common/src/main/java/org/onap/so/client/dmaap/DmaapConsumer.java b/common/src/main/java/org/onap/so/client/dmaap/DmaapConsumer.java
index c9acdd7e89..3dd0c751e3 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/DmaapConsumer.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/DmaapConsumer.java
@@ -29,97 +29,104 @@ import org.onap.so.client.dmaap.rest.RestConsumer;
public abstract class DmaapConsumer extends DmaapClient {
- public DmaapConsumer() throws IOException {
- super("dmaap/default-consumer.properties");
- }
-
- public Consumer getConsumer() {
- return new RestConsumer(this.properties);
- }
-
- public boolean consume() throws Exception {
- Consumer mrConsumer = this.getConsumer();
- boolean accepted = false;
- Stopwatch stopwatch = Stopwatch.createUnstarted();
- try {
- while (this.continuePolling()) {
- if (stopwatch.elapsed(TimeUnit.MILLISECONDS) >= this.getMaximumElapsedTime()) {
- final String message = "exceeded maximum retries on " + this.getRequestId() + " on " + this.getTopic();
- logger.error(message);
- throw new ExceededMaximumPollingTime(message);
- }
- stopwatch.start();
- Iterable<String> itr = mrConsumer.fetch();
- stopwatch.stop();
- for (String message : itr) {
- if (!accepted && this.isAccepted(message)) {
- logger.info("accepted message found for " + this.getRequestId() + " on " + this.getTopic());
- accepted = true;
- }
- if (accepted) {
- logger.info("received dmaap message: " + message);
- if (this.isFailure(message)) {
- this.stopProcessingMessages();
- final String errorMsg = "failure received from dmaap topic " + this.getTopic();
- logger.error(errorMsg);
- throw new DMaaPConsumerFailure(errorMsg);
- } else {
- this.processMessage(message);
- }
- }
- }
- }
- return true;
- } finally {
- if (stopwatch.isRunning()) {
- stopwatch.stop();
- }
- }
- }
-
- /**
- * Should this consumer continue to consume messages from the topic?
- * @return
- */
- public abstract boolean continuePolling();
- /**
- * Process a message from a DMaaP topic
- *
- * @param message
- * @throws Exception
- */
- public abstract void processMessage(String message) throws Exception;
- /**
- * Has the request been accepted by the receiving system?
- * Should the consumer move to processing messages?
- *
- * @param message
- * @return
- */
- public abstract boolean isAccepted(String message);
- /**
- * has the request failed?
- *
- * @param message
- * @return
- */
- public abstract boolean isFailure(String message);
- /**
- * The request id to filter messages on
- * @return
- */
- public abstract String getRequestId();
- /**
- * Logic that defines when the consumer should stop processing messages
- */
- public abstract void stopProcessingMessages();
-
- /**
- * time in milliseconds
- */
- public int getMaximumElapsedTime() {
- return 180000;
- }
+ public DmaapConsumer() throws IOException {
+ super("dmaap/default-consumer.properties");
+ }
+
+ public Consumer getConsumer() {
+ return new RestConsumer(this.properties);
+ }
+
+ public boolean consume() throws Exception {
+ Consumer mrConsumer = this.getConsumer();
+ boolean accepted = false;
+ Stopwatch stopwatch = Stopwatch.createUnstarted();
+ try {
+ while (this.continuePolling()) {
+ if (stopwatch.elapsed(TimeUnit.MILLISECONDS) >= this.getMaximumElapsedTime()) {
+ final String message =
+ "exceeded maximum retries on " + this.getRequestId() + " on " + this.getTopic();
+ logger.error(message);
+ throw new ExceededMaximumPollingTime(message);
+ }
+ stopwatch.start();
+ Iterable<String> itr = mrConsumer.fetch();
+ stopwatch.stop();
+ for (String message : itr) {
+ if (!accepted && this.isAccepted(message)) {
+ logger.info("accepted message found for " + this.getRequestId() + " on " + this.getTopic());
+ accepted = true;
+ }
+ if (accepted) {
+ logger.info("received dmaap message: " + message);
+ if (this.isFailure(message)) {
+ this.stopProcessingMessages();
+ final String errorMsg = "failure received from dmaap topic " + this.getTopic();
+ logger.error(errorMsg);
+ throw new DMaaPConsumerFailure(errorMsg);
+ } else {
+ this.processMessage(message);
+ }
+ }
+ }
+ }
+ return true;
+ } finally {
+ if (stopwatch.isRunning()) {
+ stopwatch.stop();
+ }
+ }
+ }
+
+ /**
+ * Should this consumer continue to consume messages from the topic?
+ *
+ * @return
+ */
+ public abstract boolean continuePolling();
+
+ /**
+ * Process a message from a DMaaP topic
+ *
+ * @param message
+ * @throws Exception
+ */
+ public abstract void processMessage(String message) throws Exception;
+
+ /**
+ * Has the request been accepted by the receiving system? Should the consumer move to processing messages?
+ *
+ * @param message
+ * @return
+ */
+ public abstract boolean isAccepted(String message);
+
+ /**
+ * has the request failed?
+ *
+ * @param message
+ * @return
+ */
+ public abstract boolean isFailure(String message);
+
+ /**
+ * The request id to filter messages on
+ *
+ * @return
+ */
+ public abstract String getRequestId();
+
+ /**
+ * Logic that defines when the consumer should stop processing messages
+ */
+ public abstract void stopProcessingMessages();
+
+ /**
+ * time in milliseconds
+ */
+ public int getMaximumElapsedTime() {
+ return 180000;
+ }
diff --git a/common/src/main/java/org/onap/so/client/dmaap/DmaapProperties.java b/common/src/main/java/org/onap/so/client/dmaap/DmaapProperties.java
index 161608dc77..604f2b3e89 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/DmaapProperties.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/DmaapProperties.java
@@ -24,9 +24,10 @@ import java.util.Map;
public interface DmaapProperties {
- /**
- * A map of strings which contains the properties for a dmaap client
- * @return
- */
- public Map<String, String> getProperties();
+ /**
+ * A map of strings which contains the properties for a dmaap client
+ *
+ * @return
+ */
+ public Map<String, String> getProperties();
}
diff --git a/common/src/main/java/org/onap/so/client/dmaap/DmaapPropertiesLoader.java b/common/src/main/java/org/onap/so/client/dmaap/DmaapPropertiesLoader.java
index 3064f6142f..f2b3d5d643 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/DmaapPropertiesLoader.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/DmaapPropertiesLoader.java
@@ -23,47 +23,50 @@ package org.onap.so.client.dmaap;
import java.util.ServiceLoader;
public class DmaapPropertiesLoader {
- /* required to make ServiceLoader thread safe */
- private static final ThreadLocal<ServiceLoader<DmaapProperties>> services = new ThreadLocal<ServiceLoader<DmaapProperties>>() {
- @Override
- protected ServiceLoader<DmaapProperties> initialValue() {
- return ServiceLoader.load(DmaapProperties.class);
- }
- };
+ /* required to make ServiceLoader thread safe */
+ private static final ThreadLocal<ServiceLoader<DmaapProperties>> services =
+ new ThreadLocal<ServiceLoader<DmaapProperties>>() {
+ @Override
+ protected ServiceLoader<DmaapProperties> initialValue() {
+ return ServiceLoader.load(DmaapProperties.class);
+ }
+ };
- private DmaapPropertiesLoader() {
- }
-
- private static class Helper {
- private static final DmaapPropertiesLoader INSTANCE = new DmaapPropertiesLoader();
- }
-
- public static DmaapPropertiesLoader getInstance() {
- return Helper.INSTANCE;
- }
- public DmaapProperties getImpl() {
- return this.getImpl(false);
- }
- public DmaapProperties getNewImpl() {
- return this.getImpl(true);
- }
- private DmaapProperties getImpl(boolean forceNewInstance) {
-
- ServiceLoader<DmaapProperties> loader = this.services.get();
- for (DmaapProperties service : loader) {
- if (forceNewInstance) {
- try {
- return service.getClass().newInstance();
- } catch (InstantiationException | IllegalAccessException e) {
- /* all spi implementations must provide a public
- * no argument constructor
- */
- }
- } else {
- return service;
- }
- }
-
- return null;
- }
+ private DmaapPropertiesLoader() {}
+
+ private static class Helper {
+ private static final DmaapPropertiesLoader INSTANCE = new DmaapPropertiesLoader();
+ }
+
+ public static DmaapPropertiesLoader getInstance() {
+ return Helper.INSTANCE;
+ }
+
+ public DmaapProperties getImpl() {
+ return this.getImpl(false);
+ }
+
+ public DmaapProperties getNewImpl() {
+ return this.getImpl(true);
+ }
+
+ private DmaapProperties getImpl(boolean forceNewInstance) {
+
+ ServiceLoader<DmaapProperties> loader = this.services.get();
+ for (DmaapProperties service : loader) {
+ if (forceNewInstance) {
+ try {
+ return service.getClass().newInstance();
+ } catch (InstantiationException | IllegalAccessException e) {
+ /*
+ * all spi implementations must provide a public no argument constructor
+ */
+ }
+ } else {
+ return service;
+ }
+ }
+
+ return null;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/dmaap/DmaapPublisher.java b/common/src/main/java/org/onap/so/client/dmaap/DmaapPublisher.java
index 48691dcd84..158bc6e264 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/DmaapPublisher.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/DmaapPublisher.java
@@ -22,30 +22,30 @@ package org.onap.so.client.dmaap;
import java.io.FileNotFoundException;
import java.io.IOException;
-
import org.onap.so.client.dmaap.rest.RestPublisher;
public abstract class DmaapPublisher extends DmaapClient {
-
- private long seconds;
- private final Publisher publisher;
- public DmaapPublisher() throws FileNotFoundException, IOException {
- super("dmaap/default-consumer.properties");
- this.publisher = new RestPublisher(properties);
- this.seconds = 20;
-
- }
-
- public DmaapPublisher(long seconds) throws FileNotFoundException, IOException {
- this();
- this.seconds = seconds;
- }
-
- public void send(String json){
- logger.info("publishing message to dmaap topic " + this.getTopic() + ": " + json);
- publisher.send(json);
- //publisher.close(seconds, TimeUnit.SECONDS);
- }
+
+ private long seconds;
+ private final Publisher publisher;
+
+ public DmaapPublisher() throws FileNotFoundException, IOException {
+ super("dmaap/default-consumer.properties");
+ this.publisher = new RestPublisher(properties);
+ this.seconds = 20;
+
+ }
+
+ public DmaapPublisher(long seconds) throws FileNotFoundException, IOException {
+ this();
+ this.seconds = seconds;
+ }
+
+ public void send(String json) {
+ logger.info("publishing message to dmaap topic " + this.getTopic() + ": " + json);
+ publisher.send(json);
+ // publisher.close(seconds, TimeUnit.SECONDS);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/dmaap/Publisher.java b/common/src/main/java/org/onap/so/client/dmaap/Publisher.java
index ba6ce16418..8d5974cdfc 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/Publisher.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/Publisher.java
@@ -17,10 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.client.dmaap;
public interface Publisher {
- public void send(String json);
+ public void send(String json);
}
diff --git a/common/src/main/java/org/onap/so/client/dmaap/exceptions/DMaaPConsumerFailure.java b/common/src/main/java/org/onap/so/client/dmaap/exceptions/DMaaPConsumerFailure.java
index f845f7e6ef..70c27532b6 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/exceptions/DMaaPConsumerFailure.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/exceptions/DMaaPConsumerFailure.java
@@ -17,18 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.client.dmaap.exceptions;
public class DMaaPConsumerFailure extends Exception {
- private static final long serialVersionUID = 2499229901897110362L;
+ private static final long serialVersionUID = 2499229901897110362L;
+
+ public DMaaPConsumerFailure() {
+ super();
+ }
- public DMaaPConsumerFailure() {
- super();
- }
-
- public DMaaPConsumerFailure(String message) {
- super(message);
- }
+ public DMaaPConsumerFailure(String message) {
+ super(message);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/dmaap/exceptions/ExceededMaximumPollingTime.java b/common/src/main/java/org/onap/so/client/dmaap/exceptions/ExceededMaximumPollingTime.java
index 0002f878d8..e6d27aac80 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/exceptions/ExceededMaximumPollingTime.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/exceptions/ExceededMaximumPollingTime.java
@@ -17,18 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.client.dmaap.exceptions;
-public class ExceededMaximumPollingTime extends RuntimeException {
+public class ExceededMaximumPollingTime extends RuntimeException {
+
+ private static final long serialVersionUID = 2331207691092906423L;
- private static final long serialVersionUID = 2331207691092906423L;
+ public ExceededMaximumPollingTime() {
+ super();
+ }
- public ExceededMaximumPollingTime() {
- super();
- }
-
- public ExceededMaximumPollingTime(String message) {
- super(message);
- }
+ public ExceededMaximumPollingTime(String message) {
+ super(message);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java b/common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java
index 9fd8c05cb5..1d85dac7dc 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java
@@ -22,32 +22,31 @@ package org.onap.so.client.dmaap.rest;
import java.net.URL;
import java.util.Map;
-
import org.onap.so.client.RestClient;
import org.onap.so.utils.CryptoUtils;
import org.onap.so.utils.TargetEntity;
public class DMaaPRestClient extends RestClient {
- private final String auth;
- private final String key;
-
- public DMaaPRestClient(URL url, String contentType, String auth, String key) {
- super(url, contentType);
- this.auth = auth;
- this.key = key;
- }
-
- @Override
- public TargetEntity getTargetEntity() {
- return TargetEntity.DMAAP;
- }
-
- @Override
- protected void initializeHeaderMap(Map<String, String> headerMap) {
- if (auth != null && !auth.isEmpty() && key != null && !key.isEmpty()) {
- addBasicAuthHeader(auth, key);
- }
- }
+ private final String auth;
+ private final String key;
+
+ public DMaaPRestClient(URL url, String contentType, String auth, String key) {
+ super(url, contentType);
+ this.auth = auth;
+ this.key = key;
+ }
+
+ @Override
+ public TargetEntity getTargetEntity() {
+ return TargetEntity.DMAAP;
+ }
+
+ @Override
+ protected void initializeHeaderMap(Map<String, String> headerMap) {
+ if (auth != null && !auth.isEmpty() && key != null && !key.isEmpty()) {
+ addBasicAuthHeader(auth, key);
+ }
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/dmaap/rest/PropertiesBean.java b/common/src/main/java/org/onap/so/client/dmaap/rest/PropertiesBean.java
index 18849217f8..52ea452e07 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/rest/PropertiesBean.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/rest/PropertiesBean.java
@@ -17,115 +17,135 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.client.dmaap.rest;
import java.util.Properties;
public class PropertiesBean {
- private String auth;
- private String key;
- private String environment;
- private String partition;
- private String contentType;
- private String host;
- private String topic;
- private String timeout;
-
-
- public PropertiesBean(Properties properties) {
- this.withAuth(properties.getProperty("auth"))
- .withKey(properties.getProperty("key"))
- .withTopic(properties.getProperty("topic"))
- .withEnvironment(properties.getProperty("environment"))
- .withHost(properties.getProperty("host"))
- .withTimeout(properties.getProperty("timeout", "20000"))
- .withPartition(properties.getProperty("partition"))
- .withContentType(properties.getProperty("contentType", "application/json"));
- }
- public String getAuth() {
- return auth;
- }
- public void setAuth(String auth) {
- this.auth = auth;
- }
- public PropertiesBean withAuth(String auth) {
- this.auth = auth;
- return this;
- }
- public String getKey() {
- return key;
- }
- public void setKey(String key) {
- this.key = key;
- }
- public PropertiesBean withKey(String key) {
- this.key = key;
- return this;
- }
- public String getEnvironment() {
- return environment;
- }
- public void setEnvironment(String environment) {
- this.environment = environment;
- }
- public PropertiesBean withEnvironment(String environment) {
- this.environment = environment;
- return this;
- }
- public String getPartition() {
- return partition;
- }
- public void setPartition(String partition) {
- this.partition = partition;
- }
- public PropertiesBean withPartition(String partition) {
- this.partition = partition;
- return this;
- }
- public String getContentType() {
- return contentType;
- }
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
- public PropertiesBean withContentType(String contentType) {
- this.contentType = contentType;
- return this;
- }
- public String getHost() {
- return host;
- }
- public void setHost(String host) {
- this.host = host;
- }
- public PropertiesBean withHost(String host) {
- this.host = host;
- return this;
- }
- public String getTopic() {
- return topic;
- }
- public void setTopic(String topic) {
- this.topic = topic;
- }
- public PropertiesBean withTopic(String topic) {
- this.topic = topic;
- return this;
- }
- public String getTimeout() {
- return timeout;
- }
- public void setTimeout(String timeout) {
- this.timeout = timeout;
- }
- public PropertiesBean withTimeout(String timeout) {
- this.timeout = timeout;
- return this;
- }
-
-
-
-
+ private String auth;
+ private String key;
+ private String environment;
+ private String partition;
+ private String contentType;
+ private String host;
+ private String topic;
+ private String timeout;
+
+
+ public PropertiesBean(Properties properties) {
+ this.withAuth(properties.getProperty("auth")).withKey(properties.getProperty("key"))
+ .withTopic(properties.getProperty("topic")).withEnvironment(properties.getProperty("environment"))
+ .withHost(properties.getProperty("host")).withTimeout(properties.getProperty("timeout", "20000"))
+ .withPartition(properties.getProperty("partition"))
+ .withContentType(properties.getProperty("contentType", "application/json"));
+ }
+
+ public String getAuth() {
+ return auth;
+ }
+
+ public void setAuth(String auth) {
+ this.auth = auth;
+ }
+
+ public PropertiesBean withAuth(String auth) {
+ this.auth = auth;
+ return this;
+ }
+
+ public String getKey() {
+ return key;
+ }
+
+ public void setKey(String key) {
+ this.key = key;
+ }
+
+ public PropertiesBean withKey(String key) {
+ this.key = key;
+ return this;
+ }
+
+ public String getEnvironment() {
+ return environment;
+ }
+
+ public void setEnvironment(String environment) {
+ this.environment = environment;
+ }
+
+ public PropertiesBean withEnvironment(String environment) {
+ this.environment = environment;
+ return this;
+ }
+
+ public String getPartition() {
+ return partition;
+ }
+
+ public void setPartition(String partition) {
+ this.partition = partition;
+ }
+
+ public PropertiesBean withPartition(String partition) {
+ this.partition = partition;
+ return this;
+ }
+
+ public String getContentType() {
+ return contentType;
+ }
+
+ public void setContentType(String contentType) {
+ this.contentType = contentType;
+ }
+
+ public PropertiesBean withContentType(String contentType) {
+ this.contentType = contentType;
+ return this;
+ }
+
+ public String getHost() {
+ return host;
+ }
+
+ public void setHost(String host) {
+ this.host = host;
+ }
+
+ public PropertiesBean withHost(String host) {
+ this.host = host;
+ return this;
+ }
+
+ public String getTopic() {
+ return topic;
+ }
+
+ public void setTopic(String topic) {
+ this.topic = topic;
+ }
+
+ public PropertiesBean withTopic(String topic) {
+ this.topic = topic;
+ return this;
+ }
+
+ public String getTimeout() {
+ return timeout;
+ }
+
+ public void setTimeout(String timeout) {
+ this.timeout = timeout;
+ }
+
+ public PropertiesBean withTimeout(String timeout) {
+ this.timeout = timeout;
+ return this;
+ }
+
+
+
}
diff --git a/common/src/main/java/org/onap/so/client/dmaap/rest/RestConsumer.java b/common/src/main/java/org/onap/so/client/dmaap/rest/RestConsumer.java
index bee5a0c2ca..a3ebf3c56c 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/rest/RestConsumer.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/rest/RestConsumer.java
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.client.dmaap.rest;
import java.net.MalformedURLException;
@@ -25,37 +25,34 @@ import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
-
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.client.RestClient;
import org.onap.so.client.dmaap.Consumer;
public class RestConsumer implements Consumer {
- private final RestClient client;
- public RestConsumer(Properties properties) {
- PropertiesBean bean = new PropertiesBean(properties);
- client = new DMaaPRestClient(this.createURL(bean), bean.getContentType(), bean.getAuth(), bean.getKey());
- }
-
- private URL createURL(PropertiesBean properties) {
- try {
- return UriBuilder.fromUri(properties.getHost())
- .path("events").path(properties.getTopic())
- .path(properties.getPartition())
- .path("consumer1")
- .queryParam("timeout", properties.getTimeout()).build().toURL();
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public Iterable<String> fetch() {
-
- return client.get(new GenericType<List<String>>() {}).orElse(new ArrayList<>());
- }
+ private final RestClient client;
+
+ public RestConsumer(Properties properties) {
+ PropertiesBean bean = new PropertiesBean(properties);
+ client = new DMaaPRestClient(this.createURL(bean), bean.getContentType(), bean.getAuth(), bean.getKey());
+ }
+
+ private URL createURL(PropertiesBean properties) {
+ try {
+ return UriBuilder.fromUri(properties.getHost()).path("events").path(properties.getTopic())
+ .path(properties.getPartition()).path("consumer1").queryParam("timeout", properties.getTimeout())
+ .build().toURL();
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public Iterable<String> fetch() {
+
+ return client.get(new GenericType<List<String>>() {}).orElse(new ArrayList<>());
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/dmaap/rest/RestPublisher.java b/common/src/main/java/org/onap/so/client/dmaap/rest/RestPublisher.java
index af660c2aa4..7926141f3b 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/rest/RestPublisher.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/rest/RestPublisher.java
@@ -23,33 +23,30 @@ package org.onap.so.client.dmaap.rest;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
-
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.client.RestClient;
import org.onap.so.client.dmaap.Publisher;
public class RestPublisher implements Publisher {
- private final RestClient client;
+ private final RestClient client;
+
+ public RestPublisher(Properties properties) {
+ PropertiesBean bean = new PropertiesBean(properties);
+ client = new DMaaPRestClient(this.createURL(bean), bean.getContentType(), bean.getAuth(), bean.getKey());
+ }
+
+ private URL createURL(PropertiesBean properties) {
+ try {
+ return UriBuilder.fromUri(properties.getHost()).path("events").path(properties.getTopic())
+ .queryParam("timeout", properties.getTimeout()).build().toURL();
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
+ }
- public RestPublisher(Properties properties) {
- PropertiesBean bean = new PropertiesBean(properties);
- client = new DMaaPRestClient(this.createURL(bean), bean.getContentType(), bean.getAuth(), bean.getKey());
- }
-
- private URL createURL(PropertiesBean properties) {
- try {
- return UriBuilder.fromUri(properties.getHost())
- .path("events").path(properties.getTopic())
- .queryParam("timeout", properties.getTimeout()).build().toURL();
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public void send(String json) {
- client.post(json);
- }
+ @Override
+ public void send(String json) {
+ client.post(json);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/exceptions/SDNOException.java b/common/src/main/java/org/onap/so/client/exceptions/SDNOException.java
index 1e14308ad5..a83657ad8c 100644
--- a/common/src/main/java/org/onap/so/client/exceptions/SDNOException.java
+++ b/common/src/main/java/org/onap/so/client/exceptions/SDNOException.java
@@ -23,17 +23,17 @@ package org.onap.so.client.exceptions;
public class SDNOException extends Exception {
- private static final long serialVersionUID = 6189163383568887383L;
+ private static final long serialVersionUID = 6189163383568887383L;
- public SDNOException() {
- super();
- }
-
- public SDNOException(String string) {
- super("SDN-O exception: " + string);
- }
+ public SDNOException() {
+ super();
+ }
- public SDNOException(Exception e) {
- super(e);
- }
+ public SDNOException(String string) {
+ super("SDN-O exception: " + string);
+ }
+
+ public SDNOException(Exception e) {
+ super(e);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/EmptyStringToNullSerializer.java b/common/src/main/java/org/onap/so/client/graphinventory/EmptyStringToNullSerializer.java
index e21386f809..c483bd2caf 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/EmptyStringToNullSerializer.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/EmptyStringToNullSerializer.java
@@ -21,7 +21,6 @@
package org.onap.so.client.graphinventory;
import java.io.IOException;
-
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
@@ -29,24 +28,25 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class EmptyStringToNullSerializer extends StdSerializer<String> {
- private static final long serialVersionUID = 5367385969270400106L;
-
- public EmptyStringToNullSerializer() {
- this(null);
- }
- public EmptyStringToNullSerializer(Class<String> t) {
- super(t);
- }
-
- @Override
- public void serialize(String value, JsonGenerator gen, SerializerProvider serializers)
- throws IOException, JsonProcessingException {
-
- if("".equals(value)) {
- gen.writeNull();
- } else {
- gen.writeString(value);
- }
- }
+ private static final long serialVersionUID = 5367385969270400106L;
+
+ public EmptyStringToNullSerializer() {
+ this(null);
+ }
+
+ public EmptyStringToNullSerializer(Class<String> t) {
+ super(t);
+ }
+
+ @Override
+ public void serialize(String value, JsonGenerator gen, SerializerProvider serializers)
+ throws IOException, JsonProcessingException {
+
+ if ("".equals(value)) {
+ gen.writeNull();
+ } else {
+ gen.writeString(value);
+ }
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/Format.java b/common/src/main/java/org/onap/so/client/graphinventory/Format.java
index 0a3e0b498c..b422516e63 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/Format.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/Format.java
@@ -22,23 +22,17 @@ package org.onap.so.client.graphinventory;
public enum Format {
- RESOURCE("resource"),
- RESOURCE_AND_URL("resource_and_url"),
- SIMPLE("simple"),
- RAW("raw"),
- CONSOLE("console"),
- PATHED("pathed"),
- GRAPHSON("graphson"),
- ID("id");
+ RESOURCE("resource"), RESOURCE_AND_URL("resource_and_url"), SIMPLE("simple"), RAW("raw"), CONSOLE(
+ "console"), PATHED("pathed"), GRAPHSON("graphson"), ID("id");
- private final String name;
-
- private Format(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return name;
- }
+ private final String name;
+
+ private Format(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryClient.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryClient.java
index 30e91dce03..98d48ec3a8 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryClient.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryClient.java
@@ -21,7 +21,6 @@
package org.onap.so.client.graphinventory;
import java.net.URI;
-
import org.onap.so.client.RestClient;
import org.onap.so.client.RestProperties;
import org.onap.so.client.RestPropertiesLoader;
@@ -29,24 +28,26 @@ import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri;
public abstract class GraphInventoryClient {
- private RestProperties props;
- protected GraphInventoryClient(Class<? extends RestProperties> propertiesClass) {
-
- RestProperties props = RestPropertiesLoader.getInstance().getNewImpl(propertiesClass);
- this.props = props;
- }
- protected abstract URI constructPath(GraphInventoryUri uri);
-
- public abstract RestClient createClient(GraphInventoryUri uri);
-
- public <T extends RestProperties> T getRestProperties() {
- if (props == null) {
- throw new IllegalStateException("No RestProperty implementation found on classpath");
- }
- return (T)props;
- }
-
- public abstract GraphInventoryVersion getVersion();
-
- public abstract String getGraphDBName();
+ private RestProperties props;
+
+ protected GraphInventoryClient(Class<? extends RestProperties> propertiesClass) {
+
+ RestProperties props = RestPropertiesLoader.getInstance().getNewImpl(propertiesClass);
+ this.props = props;
+ }
+
+ protected abstract URI constructPath(GraphInventoryUri uri);
+
+ public abstract RestClient createClient(GraphInventoryUri uri);
+
+ public <T extends RestProperties> T getRestProperties() {
+ if (props == null) {
+ throw new IllegalStateException("No RestProperty implementation found on classpath");
+ }
+ return (T) props;
+ }
+
+ public abstract GraphInventoryVersion getVersion();
+
+ public abstract String getGraphDBName();
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperPatchProvider.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperPatchProvider.java
index 47c9e77b84..2facdaa64e 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperPatchProvider.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperPatchProvider.java
@@ -24,12 +24,12 @@ import com.fasterxml.jackson.databind.module.SimpleModule;
public class GraphInventoryCommonObjectMapperPatchProvider extends GraphInventoryCommonObjectMapperProvider {
-
- public GraphInventoryCommonObjectMapperPatchProvider() {
- super();
- EmptyStringToNullSerializer sp = new EmptyStringToNullSerializer();
- SimpleModule emptyStringModule = new SimpleModule();
- emptyStringModule.addSerializer(String.class, sp);
- mapper.registerModule(emptyStringModule);
- }
+
+ public GraphInventoryCommonObjectMapperPatchProvider() {
+ super();
+ EmptyStringToNullSerializer sp = new EmptyStringToNullSerializer();
+ SimpleModule emptyStringModule = new SimpleModule();
+ emptyStringModule.addSerializer(String.class, sp);
+ mapper.registerModule(emptyStringModule);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperProvider.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperProvider.java
index f9857424a2..72b01c268e 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperProvider.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryCommonObjectMapperProvider.java
@@ -21,7 +21,6 @@
package org.onap.so.client.graphinventory;
import org.onap.so.client.policy.CommonObjectMapperProvider;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
@@ -35,18 +34,18 @@ import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
public class GraphInventoryCommonObjectMapperProvider extends CommonObjectMapperProvider {
- public GraphInventoryCommonObjectMapperProvider() {
- mapper = new ObjectMapper();
- mapper.setSerializationInclusion(Include.NON_NULL);
- mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
- mapper.enable(MapperFeature.USE_ANNOTATIONS);
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
- mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- AnnotationIntrospector aiJaxb = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
+ public GraphInventoryCommonObjectMapperProvider() {
+ mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(Include.NON_NULL);
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
+ mapper.enable(MapperFeature.USE_ANNOTATIONS);
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
+ mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ AnnotationIntrospector aiJaxb = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
AnnotationIntrospector aiJackson = new JacksonAnnotationIntrospector();
// first Jaxb, second Jackson annotations
mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(aiJaxb, aiJackson));
- }
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectName.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectName.java
index 4543d8523b..bb547e30e8 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectName.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectName.java
@@ -24,6 +24,7 @@ import com.google.common.base.CaseFormat;
public interface GraphInventoryObjectName {
- public String typeName();
- public String typeName(CaseFormat format);
+ public String typeName();
+
+ public String typeName(CaseFormat format);
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectPlurals.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectPlurals.java
index ba48eb279f..42f4733e47 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectPlurals.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectPlurals.java
@@ -20,6 +20,7 @@
package org.onap.so.client.graphinventory;
-public interface GraphInventoryObjectPlurals extends GraphInventoryObjectName, GraphInventoryObjectUriTemplate, GraphInventoryObjectUriPartial {
+public interface GraphInventoryObjectPlurals
+ extends GraphInventoryObjectName, GraphInventoryObjectUriTemplate, GraphInventoryObjectUriPartial {
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectType.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectType.java
index 453becb75a..c11a08e867 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectType.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectType.java
@@ -20,6 +20,7 @@
package org.onap.so.client.graphinventory;
-public interface GraphInventoryObjectType extends GraphInventoryObjectName, GraphInventoryObjectUriTemplate, GraphInventoryObjectUriPartial {
+public interface GraphInventoryObjectType
+ extends GraphInventoryObjectName, GraphInventoryObjectUriTemplate, GraphInventoryObjectUriPartial {
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectUriPartial.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectUriPartial.java
index 0987221b0d..0207595f7f 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectUriPartial.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectUriPartial.java
@@ -22,5 +22,5 @@ package org.onap.so.client.graphinventory;
public interface GraphInventoryObjectUriPartial {
- public String partialUri();
+ public String partialUri();
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectUriTemplate.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectUriTemplate.java
index e231ddb811..bcc26535ff 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectUriTemplate.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryObjectUriTemplate.java
@@ -22,5 +22,5 @@ package org.onap.so.client.graphinventory;
public interface GraphInventoryObjectUriTemplate {
- public String uriTemplate();
+ public String uriTemplate();
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverter.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverter.java
index 00e597b189..d1bc6bc61e 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverter.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverter.java
@@ -23,61 +23,61 @@ package org.onap.so.client.graphinventory;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
-
import org.onap.so.client.aai.AAICommonObjectMapperPatchProvider;
import org.onap.so.client.aai.AAICommonObjectMapperProvider;
import org.onap.so.client.graphinventory.exceptions.GraphInventoryPatchDepthExceededException;
import org.onap.so.jsonpath.JsonPathUtil;
-
import com.fasterxml.jackson.core.JsonProcessingException;
public class GraphInventoryPatchConverter {
- private static final AAICommonObjectMapperProvider standardProvider = new AAICommonObjectMapperProvider();
- private static final AAICommonObjectMapperPatchProvider patchProvider = new AAICommonObjectMapperPatchProvider();
- private static final Pattern LOCATE_COMPLEX_OBJECT = Pattern.compile("^((?!relationship-list).)+?\\['[^\\[\\]]+?'\\]$");
+ private static final AAICommonObjectMapperProvider standardProvider = new AAICommonObjectMapperProvider();
+ private static final AAICommonObjectMapperPatchProvider patchProvider = new AAICommonObjectMapperPatchProvider();
+ private static final Pattern LOCATE_COMPLEX_OBJECT =
+ Pattern.compile("^((?!relationship-list).)+?\\['[^\\[\\]]+?'\\]$");
+
+
+ public String convertPatchFormat(Object obj) {
+ return validatePatchObject(marshallObjectToPatchFormat(obj));
+ }
+
+ public String validatePatchObject(String payload) {
+ if (hasComplexObject(payload)) {
+ throw new GraphInventoryPatchDepthExceededException(payload);
+ }
+
+ return payload;
+ }
+
+ /**
+ * validates client side that json does not include any complex objects relationship-list is omitted from this
+ * validation
+ */
+ protected boolean hasComplexObject(String json) {
+ if (json.isEmpty()) {
+ return false;
+ }
+ String complex = "$.*.*";
+ String array = "$.*.*.*";
+ List<String> result = JsonPathUtil.getInstance().getPathList(json, complex);
+ List<String> result2 = JsonPathUtil.getInstance().getPathList(json, array);
+
+ result.addAll(result2);
+ return result.stream().anyMatch(item -> LOCATE_COMPLEX_OBJECT.matcher(item).find());
+ }
+
+ protected String marshallObjectToPatchFormat(Object obj) {
+ Object value = obj;
+ try {
+ if (!(obj instanceof Map || obj instanceof String)) {
+ value = patchProvider.getMapper().writeValueAsString(obj);
+ } else if (obj instanceof Map) {
+ value = standardProvider.getMapper().writeValueAsString(obj);
+ }
+ } catch (JsonProcessingException e) {
+ value = "{}";
+ }
-
- public String convertPatchFormat(Object obj) {
- return validatePatchObject(marshallObjectToPatchFormat(obj));
- }
-
- public String validatePatchObject(String payload) {
- if (hasComplexObject(payload)) {
- throw new GraphInventoryPatchDepthExceededException(payload);
- }
-
- return payload;
- }
-
- /** validates client side that json does not include any complex objects
- * relationship-list is omitted from this validation
- */
- protected boolean hasComplexObject(String json) {
- if (json.isEmpty()) {
- return false;
- }
- String complex = "$.*.*";
- String array = "$.*.*.*";
- List<String> result = JsonPathUtil.getInstance().getPathList(json, complex);
- List<String> result2 = JsonPathUtil.getInstance().getPathList(json, array);
-
- result.addAll(result2);
- return result.stream().anyMatch(item -> LOCATE_COMPLEX_OBJECT.matcher(item).find());
- }
-
- protected String marshallObjectToPatchFormat(Object obj) {
- Object value = obj;
- try {
- if (!(obj instanceof Map || obj instanceof String)) {
- value = patchProvider.getMapper().writeValueAsString(obj);
- } else if (obj instanceof Map) {
- value = standardProvider.getMapper().writeValueAsString(obj);
- }
- } catch (JsonProcessingException e) {
- value = "{}";
- }
-
- return (String)value;
- }
+ return (String) value;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryQueryClient.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryQueryClient.java
index 152e9d7a36..3ff564fcb2 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryQueryClient.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryQueryClient.java
@@ -27,115 +27,115 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
-
import javax.ws.rs.core.GenericType;
-
import org.onap.so.client.aai.entities.Results;
import org.onap.so.client.graphinventory.entities.GraphInventoryResultWrapper;
import org.onap.so.client.graphinventory.entities.Pathed;
import org.onap.so.client.graphinventory.entities.ResourceAndUrl;
import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri;
-
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class GraphInventoryQueryClient<S, I, Wrapper extends GraphInventoryResultWrapper<?>, Type extends GraphInventoryObjectType> {
- private Optional<String> depth = Optional.empty();
- private boolean nodesOnly = false;
- private Optional<GraphInventorySubgraphType> subgraph = Optional.empty();
- private GraphInventoryClient client;
- private GraphInventoryCommonObjectMapperProvider mapperProvider = new GraphInventoryCommonObjectMapperProvider();
-
- public GraphInventoryQueryClient(GraphInventoryClient client) {
- this.client = client;
- }
-
- protected abstract GraphInventoryUri getQueryUri();
-
- public String query(Format format, I query) {
- return client.createClient(setupQueryParams(getQueryUri().queryParam("format", format.toString()))).put(query, String.class);
- }
-
- protected <R> List<R> querySingleType(Format format, I query, Class<R> clazz) {
- return client.createClient(
- setupQueryParams(getQueryUri().queryParam("format", format.toString()))).put(
- query, new GenericType<Results<Object>>(){}).getResult()
- .stream().map(item -> {
- try {
- return mapperProvider.getMapper().readValue(mapperProvider.getMapper().writeValueAsString(item), clazz);
- } catch (IOException e) {
- throw new IllegalArgumentException("could not map values from json", e);
- }
- }).collect(Collectors.toList());
- }
-
- public List<Pathed> queryPathed(I query) {
- return querySingleType(Format.PATHED, query, Pathed.class);
- }
-
- public List<Id> queryId(I query) {
- return querySingleType(Format.ID, query, Id.class);
- }
-
- public <R> List<R> querySingleResource(I query, Class<R> clazz) {
- try {
- return getResourceAndUrl(query).stream().map(item -> item.getWrapper().asBean(clazz).get()).collect(Collectors.toList());
- } catch (IOException e) {
- throw new IllegalArgumentException("could not map values from json", e);
- }
- }
-
- public List<ResourceAndUrl<Wrapper>> getResourceAndUrl(I query) throws IOException {
- List<ResourceAndUrl<Wrapper>> result = new ArrayList<>();
- ObjectMapper mapper = mapperProvider.getMapper();
- Results<Map<String, Object>> resultsFromJson = mapper.readValue(query(Format.RESOURCE_AND_URL, query),
- new TypeReference<Results<Map<String, Object>>>() {
- });
- for (Map<String, Object> m : resultsFromJson.getResult()) {
- for(Entry<String, Object> entrySet : m.entrySet()) {
- if (!entrySet.getKey().equals("url")) {
- String url = (String)m.get("url");
- String stringJson = mapper.writeValueAsString(entrySet.getValue());
- result.add(new ResourceAndUrl<Wrapper>(url, createType(entrySet.getKey()), createWrapper(stringJson)));
- }
- }
- }
-
- return result;
- }
-
- public abstract Wrapper createWrapper(String json);
-
- public abstract Type createType(String name);
-
- public S depth (String depth) {
- this.depth = Optional.of(depth);
- return (S) this;
- }
- public S nodesOnly() {
- this.nodesOnly = true;
- return (S) this;
- }
- public S subgraph(GraphInventorySubgraphType type){
-
- subgraph = Optional.of(type);
-
- return (S) this;
- }
-
- protected GraphInventoryUri setupQueryParams(GraphInventoryUri uri) {
- GraphInventoryUri clone = uri.clone();
- if (this.depth.isPresent()) {
- clone.queryParam("depth", depth.get());
- }
- if (this.nodesOnly) {
- clone.queryParam("nodesOnly", "");
- }
- if (this.subgraph.isPresent()) {
- clone.queryParam("subgraph", this.subgraph.get().toString());
- }
- return clone;
- }
+ private Optional<String> depth = Optional.empty();
+ private boolean nodesOnly = false;
+ private Optional<GraphInventorySubgraphType> subgraph = Optional.empty();
+ private GraphInventoryClient client;
+ private GraphInventoryCommonObjectMapperProvider mapperProvider = new GraphInventoryCommonObjectMapperProvider();
+
+ public GraphInventoryQueryClient(GraphInventoryClient client) {
+ this.client = client;
+ }
+
+ protected abstract GraphInventoryUri getQueryUri();
+
+ public String query(Format format, I query) {
+ return client.createClient(setupQueryParams(getQueryUri().queryParam("format", format.toString()))).put(query,
+ String.class);
+ }
+
+ protected <R> List<R> querySingleType(Format format, I query, Class<R> clazz) {
+ return client.createClient(setupQueryParams(getQueryUri().queryParam("format", format.toString())))
+ .put(query, new GenericType<Results<Object>>() {}).getResult().stream().map(item -> {
+ try {
+ return mapperProvider.getMapper().readValue(mapperProvider.getMapper().writeValueAsString(item),
+ clazz);
+ } catch (IOException e) {
+ throw new IllegalArgumentException("could not map values from json", e);
+ }
+ }).collect(Collectors.toList());
+ }
+
+ public List<Pathed> queryPathed(I query) {
+ return querySingleType(Format.PATHED, query, Pathed.class);
+ }
+
+ public List<Id> queryId(I query) {
+ return querySingleType(Format.ID, query, Id.class);
+ }
+
+ public <R> List<R> querySingleResource(I query, Class<R> clazz) {
+ try {
+ return getResourceAndUrl(query).stream().map(item -> item.getWrapper().asBean(clazz).get())
+ .collect(Collectors.toList());
+ } catch (IOException e) {
+ throw new IllegalArgumentException("could not map values from json", e);
+ }
+ }
+
+ public List<ResourceAndUrl<Wrapper>> getResourceAndUrl(I query) throws IOException {
+ List<ResourceAndUrl<Wrapper>> result = new ArrayList<>();
+ ObjectMapper mapper = mapperProvider.getMapper();
+ Results<Map<String, Object>> resultsFromJson = mapper.readValue(query(Format.RESOURCE_AND_URL, query),
+ new TypeReference<Results<Map<String, Object>>>() {});
+ for (Map<String, Object> m : resultsFromJson.getResult()) {
+ for (Entry<String, Object> entrySet : m.entrySet()) {
+ if (!entrySet.getKey().equals("url")) {
+ String url = (String) m.get("url");
+ String stringJson = mapper.writeValueAsString(entrySet.getValue());
+ result.add(
+ new ResourceAndUrl<Wrapper>(url, createType(entrySet.getKey()), createWrapper(stringJson)));
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public abstract Wrapper createWrapper(String json);
+
+ public abstract Type createType(String name);
+
+ public S depth(String depth) {
+ this.depth = Optional.of(depth);
+ return (S) this;
+ }
+
+ public S nodesOnly() {
+ this.nodesOnly = true;
+ return (S) this;
+ }
+
+ public S subgraph(GraphInventorySubgraphType type) {
+
+ subgraph = Optional.of(type);
+
+ return (S) this;
+ }
+
+ protected GraphInventoryUri setupQueryParams(GraphInventoryUri uri) {
+ GraphInventoryUri clone = uri.clone();
+ if (this.depth.isPresent()) {
+ clone.queryParam("depth", depth.get());
+ }
+ if (this.nodesOnly) {
+ clone.queryParam("nodesOnly", "");
+ }
+ if (this.subgraph.isPresent()) {
+ clone.queryParam("subgraph", this.subgraph.get().toString());
+ }
+ return clone;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryResourcesClient.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryResourcesClient.java
index e1519d61a2..2a76dab107 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryResourcesClient.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryResourcesClient.java
@@ -23,12 +23,10 @@ package org.onap.so.client.graphinventory;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Optional;
-
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-
import org.onap.aai.domain.yang.Relationship;
import org.onap.so.client.RestClient;
import org.onap.so.client.RestProperties;
@@ -40,287 +38,296 @@ import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri;
public abstract class GraphInventoryResourcesClient<Self, Uri extends GraphInventoryResourceUri, EdgeLabel extends GraphInventoryEdgeLabel, Wrapper extends GraphInventoryResultWrapper, TransactionalClient, SingleTransactionClient> {
- protected GraphInventoryClient client;
-
- protected GraphInventoryResourcesClient(GraphInventoryClient client) {
- this.client = client;
- }
- /**
- * creates a new object in GraphInventory
- *
- * @param obj - can be any object which will marshal into a valid GraphInventory payload
- * @param uri
- * @return
- */
- public void create(Uri uri, Object obj) {
- RestClient giRC = client.createClient(uri);
- giRC.put(obj);
- }
-
- /**
- * creates a new object in GraphInventory with no payload body
- *
- * @param uri
- * @return
- */
- public void createEmpty(Uri uri) {
- RestClient giRC = client.createClient(uri);
- giRC.put("");
- }
-
- /**
- * returns false if the object does not exist in GraphInventory
- *
- * @param uri
- * @return
- */
- public boolean exists(Uri uri) {
- GraphInventoryUri forceMinimal = this.addParams(Optional.of(Depth.ZERO), true, uri);
- try {
- RestClient giRC = client.createClient(forceMinimal);
-
- return giRC.get().getStatus() == Status.OK.getStatusCode();
- } catch (NotFoundException e) {
- return false;
- }
- }
-
- /**
- * Adds a relationship between two objects in GraphInventory
- * @param uriA
- * @param uriB
- * @return
- */
- public void connect(Uri uriA, Uri uriB) {
- GraphInventoryResourceUri uriAClone = uriA.clone();
- RestClient giRC = client.createClient(uriAClone.relationshipAPI());
- giRC.put(this.buildRelationship(uriB));
- }
-
- /**
- * Adds a relationship between two objects in GraphInventory
- * with a given edge label
- * @param uriA
- * @param uriB
- * @param edge label
- * @return
- */
- public void connect(Uri uriA, Uri uriB, EdgeLabel label) {
- GraphInventoryResourceUri uriAClone = uriA.clone();
- RestClient giRC = client.createClient(uriAClone.relationshipAPI());
- giRC.put(this.buildRelationship(uriB, label));
- }
-
- /**
- * Removes relationship from two objects in GraphInventory
- *
- * @param uriA
- * @param uriB
- * @return
- */
- public void disconnect(Uri uriA, Uri uriB) {
- GraphInventoryResourceUri uriAClone = uriA.clone();
- RestClient giRC = client.createClient(uriAClone.relationshipAPI());
- giRC.delete(this.buildRelationship(uriB));
- }
-
- /**
- * Deletes object from GraphInventory. Automatically handles resource-version.
- *
- * @param uri
- * @return
- */
- public void delete(Uri uri) {
- GraphInventoryResourceUri clone = uri.clone();
- RestClient giRC = client.createClient(clone);
- Map<String, Object> result = giRC.get(new GenericType<Map<String, Object>>(){})
- .orElseThrow(() -> new NotFoundException(clone.build() + " does not exist in " + client.getGraphDBName()));
- String resourceVersion = (String) result.get("resource-version");
- giRC = client.createClient(clone.resourceVersion(resourceVersion));
- giRC.delete();
- }
-
- /**
- * @param obj - can be any object which will marshal into a valid GraphInventory payload
- * @param uri
- * @return
- */
- public void update(Uri uri, Object obj) {
- RestClient giRC = client.createClient(uri);
- giRC.patch(obj);
- }
-
- /**
- * Retrieves an object from GraphInventory and unmarshalls it into the Class specified
- * @param clazz
- * @param uri
- * @return
- */
- public <T> Optional<T> get(Class<T> clazz, Uri uri) {
- try {
- return client.createClient(uri).get(clazz);
- } catch (NotFoundException e) {
- if (this.getRestProperties().mapNotFoundToEmpty()) {
- return Optional.empty();
- } else {
- throw e;
- }
- }
- }
-
- /**
- * Retrieves an object from GraphInventory and returns complete response
- * @param uri
- * @return
- */
- public Response getFullResponse(Uri uri) {
- try {
- return client.createClient(uri).get();
- } catch (NotFoundException e) {
- if (this.getRestProperties().mapNotFoundToEmpty()) {
- return e.getResponse();
- } else {
- throw e;
- }
- }
- }
-
- /**
- * Retrieves an object from GraphInventory and automatically unmarshalls it into a Map or List
- * @param resultClass
- * @param uri
- * @return
- */
- public <T> Optional<T> get(GenericType<T> resultClass, Uri uri) {
- try {
- return client.createClient(uri).get(resultClass);
- } catch (NotFoundException e) {
- if (this.getRestProperties().mapNotFoundToEmpty()) {
- return Optional.empty();
- } else {
- throw e;
- }
- }
- }
- /**
- * Retrieves an object from GraphInventory wrapped in a helper class which offer additional features
- *
- * @param uri
- * @return
- */
- public Wrapper get(Uri uri) {
- String json;
- try {
- json = client.createClient(uri).get(String.class).orElse(null);
- } catch (NotFoundException e) {
- if (this.getRestProperties().mapNotFoundToEmpty()) {
- json = null;
- } else {
- throw e;
- }
- }
- return this.createWrapper(json);
- }
-
- /**
- * Retrieves an object from GraphInventory wrapped in a helper class which offer additional features
- * If the object cannot be found in GraphInventory the method will throw the runtime exception
- * included as an argument
- * @param uri
- * @return
- */
- public Wrapper get(Uri uri, Class<? extends RuntimeException> c) {
- String json;
- try {
- json = client.createClient(uri).get(String.class)
- .orElseThrow(() -> createException(c, uri.build() + " not found in " + client.getGraphDBName(), Optional.empty()));
- } catch (NotFoundException e) {
- throw createException(c, "could not construct uri for use with " + client.getGraphDBName(), Optional.of(e));
- }
-
- return this.createWrapper(json);
- }
-
- private RuntimeException createException(Class<? extends RuntimeException> c, String message, Optional<Throwable> t) {
- RuntimeException e;
- try {
- if (t.isPresent()) {
- e = c.getConstructor(String.class, Throwable.class).newInstance(message, t.get());
- } else {
- e = c.getConstructor(String.class).newInstance(message);
- }
- } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
- | NoSuchMethodException | SecurityException e1) {
- throw new IllegalArgumentException("could not create instance for " + c.getName());
- }
-
- return e;
- }
-
- /**
- * Will automatically create the object if it does not exist
- *
- * @param obj - Optional object which serializes to a valid GraphInventory payload
- * @param uri
- * @return
- */
- public Self createIfNotExists(Uri uri, Optional<Object> obj) {
- if(!this.exists(uri)){
- if (obj.isPresent()) {
- this.create(uri, obj.get());
- } else {
- this.createEmpty(uri);
- }
-
- }
- return (Self)this;
- }
- protected Relationship buildRelationship(GraphInventoryResourceUri uri) {
- return buildRelationship(uri, Optional.empty());
- }
-
- protected Relationship buildRelationship(GraphInventoryResourceUri uri, GraphInventoryEdgeLabel label) {
- return buildRelationship(uri, Optional.of(label));
- }
- protected Relationship buildRelationship(GraphInventoryResourceUri uri, Optional<GraphInventoryEdgeLabel> label) {
- final Relationship result = new Relationship();
- result.setRelatedLink(uri.build().toString());
- if (label.isPresent()) {
- result.setRelationshipLabel(label.get().toString());
- }
- return result;
- }
-
- public abstract Wrapper createWrapper(String json);
-
- /**
- * Starts a transaction which encloses multiple GraphInventory mutations
- *
- * @return
- */
- public abstract TransactionalClient beginTransaction();
-
- /**
- * Starts a transaction groups multiple GraphInventory mutations
- *
- * @return
- */
- public abstract SingleTransactionClient beginSingleTransaction();
-
- private GraphInventoryUri addParams(Optional<Depth> depth, boolean nodesOnly, GraphInventoryUri uri) {
- GraphInventoryUri clone = uri.clone();
- if (depth.isPresent()) {
- clone.depth(depth.get());
- }
- if (nodesOnly) {
- clone.nodesOnly(nodesOnly);
- }
-
- return clone;
- }
-
- public <T extends RestProperties> T getRestProperties() {
- return client.getRestProperties();
- }
+ protected GraphInventoryClient client;
+
+ protected GraphInventoryResourcesClient(GraphInventoryClient client) {
+ this.client = client;
+ }
+
+ /**
+ * creates a new object in GraphInventory
+ *
+ * @param obj - can be any object which will marshal into a valid GraphInventory payload
+ * @param uri
+ * @return
+ */
+ public void create(Uri uri, Object obj) {
+ RestClient giRC = client.createClient(uri);
+ giRC.put(obj);
+ }
+
+ /**
+ * creates a new object in GraphInventory with no payload body
+ *
+ * @param uri
+ * @return
+ */
+ public void createEmpty(Uri uri) {
+ RestClient giRC = client.createClient(uri);
+ giRC.put("");
+ }
+
+ /**
+ * returns false if the object does not exist in GraphInventory
+ *
+ * @param uri
+ * @return
+ */
+ public boolean exists(Uri uri) {
+ GraphInventoryUri forceMinimal = this.addParams(Optional.of(Depth.ZERO), true, uri);
+ try {
+ RestClient giRC = client.createClient(forceMinimal);
+
+ return giRC.get().getStatus() == Status.OK.getStatusCode();
+ } catch (NotFoundException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Adds a relationship between two objects in GraphInventory
+ *
+ * @param uriA
+ * @param uriB
+ * @return
+ */
+ public void connect(Uri uriA, Uri uriB) {
+ GraphInventoryResourceUri uriAClone = uriA.clone();
+ RestClient giRC = client.createClient(uriAClone.relationshipAPI());
+ giRC.put(this.buildRelationship(uriB));
+ }
+
+ /**
+ * Adds a relationship between two objects in GraphInventory with a given edge label
+ *
+ * @param uriA
+ * @param uriB
+ * @param edge label
+ * @return
+ */
+ public void connect(Uri uriA, Uri uriB, EdgeLabel label) {
+ GraphInventoryResourceUri uriAClone = uriA.clone();
+ RestClient giRC = client.createClient(uriAClone.relationshipAPI());
+ giRC.put(this.buildRelationship(uriB, label));
+ }
+
+ /**
+ * Removes relationship from two objects in GraphInventory
+ *
+ * @param uriA
+ * @param uriB
+ * @return
+ */
+ public void disconnect(Uri uriA, Uri uriB) {
+ GraphInventoryResourceUri uriAClone = uriA.clone();
+ RestClient giRC = client.createClient(uriAClone.relationshipAPI());
+ giRC.delete(this.buildRelationship(uriB));
+ }
+
+ /**
+ * Deletes object from GraphInventory. Automatically handles resource-version.
+ *
+ * @param uri
+ * @return
+ */
+ public void delete(Uri uri) {
+ GraphInventoryResourceUri clone = uri.clone();
+ RestClient giRC = client.createClient(clone);
+ Map<String, Object> result = giRC.get(new GenericType<Map<String, Object>>() {}).orElseThrow(
+ () -> new NotFoundException(clone.build() + " does not exist in " + client.getGraphDBName()));
+ String resourceVersion = (String) result.get("resource-version");
+ giRC = client.createClient(clone.resourceVersion(resourceVersion));
+ giRC.delete();
+ }
+
+ /**
+ * @param obj - can be any object which will marshal into a valid GraphInventory payload
+ * @param uri
+ * @return
+ */
+ public void update(Uri uri, Object obj) {
+ RestClient giRC = client.createClient(uri);
+ giRC.patch(obj);
+ }
+
+ /**
+ * Retrieves an object from GraphInventory and unmarshalls it into the Class specified
+ *
+ * @param clazz
+ * @param uri
+ * @return
+ */
+ public <T> Optional<T> get(Class<T> clazz, Uri uri) {
+ try {
+ return client.createClient(uri).get(clazz);
+ } catch (NotFoundException e) {
+ if (this.getRestProperties().mapNotFoundToEmpty()) {
+ return Optional.empty();
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ /**
+ * Retrieves an object from GraphInventory and returns complete response
+ *
+ * @param uri
+ * @return
+ */
+ public Response getFullResponse(Uri uri) {
+ try {
+ return client.createClient(uri).get();
+ } catch (NotFoundException e) {
+ if (this.getRestProperties().mapNotFoundToEmpty()) {
+ return e.getResponse();
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ /**
+ * Retrieves an object from GraphInventory and automatically unmarshalls it into a Map or List
+ *
+ * @param resultClass
+ * @param uri
+ * @return
+ */
+ public <T> Optional<T> get(GenericType<T> resultClass, Uri uri) {
+ try {
+ return client.createClient(uri).get(resultClass);
+ } catch (NotFoundException e) {
+ if (this.getRestProperties().mapNotFoundToEmpty()) {
+ return Optional.empty();
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ /**
+ * Retrieves an object from GraphInventory wrapped in a helper class which offer additional features
+ *
+ * @param uri
+ * @return
+ */
+ public Wrapper get(Uri uri) {
+ String json;
+ try {
+ json = client.createClient(uri).get(String.class).orElse(null);
+ } catch (NotFoundException e) {
+ if (this.getRestProperties().mapNotFoundToEmpty()) {
+ json = null;
+ } else {
+ throw e;
+ }
+ }
+ return this.createWrapper(json);
+ }
+
+ /**
+ * Retrieves an object from GraphInventory wrapped in a helper class which offer additional features If the object
+ * cannot be found in GraphInventory the method will throw the runtime exception included as an argument
+ *
+ * @param uri
+ * @return
+ */
+ public Wrapper get(Uri uri, Class<? extends RuntimeException> c) {
+ String json;
+ try {
+ json = client.createClient(uri).get(String.class).orElseThrow(() -> createException(c,
+ uri.build() + " not found in " + client.getGraphDBName(), Optional.empty()));
+ } catch (NotFoundException e) {
+ throw createException(c, "could not construct uri for use with " + client.getGraphDBName(), Optional.of(e));
+ }
+
+ return this.createWrapper(json);
+ }
+
+ private RuntimeException createException(Class<? extends RuntimeException> c, String message,
+ Optional<Throwable> t) {
+ RuntimeException e;
+ try {
+ if (t.isPresent()) {
+ e = c.getConstructor(String.class, Throwable.class).newInstance(message, t.get());
+ } else {
+ e = c.getConstructor(String.class).newInstance(message);
+ }
+ } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
+ | NoSuchMethodException | SecurityException e1) {
+ throw new IllegalArgumentException("could not create instance for " + c.getName());
+ }
+
+ return e;
+ }
+
+ /**
+ * Will automatically create the object if it does not exist
+ *
+ * @param obj - Optional object which serializes to a valid GraphInventory payload
+ * @param uri
+ * @return
+ */
+ public Self createIfNotExists(Uri uri, Optional<Object> obj) {
+ if (!this.exists(uri)) {
+ if (obj.isPresent()) {
+ this.create(uri, obj.get());
+ } else {
+ this.createEmpty(uri);
+ }
+
+ }
+ return (Self) this;
+ }
+
+ protected Relationship buildRelationship(GraphInventoryResourceUri uri) {
+ return buildRelationship(uri, Optional.empty());
+ }
+
+ protected Relationship buildRelationship(GraphInventoryResourceUri uri, GraphInventoryEdgeLabel label) {
+ return buildRelationship(uri, Optional.of(label));
+ }
+
+ protected Relationship buildRelationship(GraphInventoryResourceUri uri, Optional<GraphInventoryEdgeLabel> label) {
+ final Relationship result = new Relationship();
+ result.setRelatedLink(uri.build().toString());
+ if (label.isPresent()) {
+ result.setRelationshipLabel(label.get().toString());
+ }
+ return result;
+ }
+
+ public abstract Wrapper createWrapper(String json);
+
+ /**
+ * Starts a transaction which encloses multiple GraphInventory mutations
+ *
+ * @return
+ */
+ public abstract TransactionalClient beginTransaction();
+
+ /**
+ * Starts a transaction groups multiple GraphInventory mutations
+ *
+ * @return
+ */
+ public abstract SingleTransactionClient beginSingleTransaction();
+
+ private GraphInventoryUri addParams(Optional<Depth> depth, boolean nodesOnly, GraphInventoryUri uri) {
+ GraphInventoryUri clone = uri.clone();
+ if (depth.isPresent()) {
+ clone.depth(depth.get());
+ }
+ if (nodesOnly) {
+ clone.nodesOnly(nodesOnly);
+ }
+
+ return clone;
+ }
+
+ public <T extends RestProperties> T getRestProperties() {
+ return client.getRestProperties();
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryRestClient.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryRestClient.java
index 10c06634dc..434c65da46 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryRestClient.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryRestClient.java
@@ -23,9 +23,7 @@ package org.onap.so.client.graphinventory;
import java.net.URI;
import java.util.Map;
import java.util.Optional;
-
import javax.ws.rs.core.Response;
-
import org.onap.so.client.ResponseExceptionMapper;
import org.onap.so.client.RestClientSSL;
import org.onap.so.client.RestProperties;
@@ -34,44 +32,45 @@ import org.onap.so.utils.TargetEntity;
public abstract class GraphInventoryRestClient extends RestClientSSL {
- protected static final GraphInventoryCommonObjectMapperProvider standardProvider = new GraphInventoryCommonObjectMapperProvider();
+ protected static final GraphInventoryCommonObjectMapperProvider standardProvider =
+ new GraphInventoryCommonObjectMapperProvider();
+
+ protected final GraphInventoryPatchConverter patchConverter = new GraphInventoryPatchConverter();
- protected final GraphInventoryPatchConverter patchConverter = new GraphInventoryPatchConverter();
-
- protected GraphInventoryRestClient(RestProperties props, URI uri) {
- super(props, Optional.of(uri));
- }
+ protected GraphInventoryRestClient(RestProperties props, URI uri) {
+ super(props, Optional.of(uri));
+ }
- @Override
+ @Override
public abstract TargetEntity getTargetEntity();
- @Override
- protected abstract void initializeHeaderMap(Map<String, String> headerMap);
+ @Override
+ protected abstract void initializeHeaderMap(Map<String, String> headerMap);
+
+ @Override
+ protected abstract Optional<ResponseExceptionMapper> addResponseExceptionMapper();
+
+ @Override
+ protected CommonObjectMapperProvider getCommonObjectMapperProvider() {
+ return standardProvider;
+ }
+
+ @Override
+ public Response patch(Object obj) {
+ return super.patch(convertToPatchFormat(obj));
+ }
- @Override
- protected abstract Optional<ResponseExceptionMapper> addResponseExceptionMapper();
-
- @Override
- protected CommonObjectMapperProvider getCommonObjectMapperProvider() {
- return standardProvider;
- }
+ @Override
+ public <T> T patch(Object obj, Class<T> resultClass) {
+ return super.patch(convertToPatchFormat(obj), resultClass);
+ }
- @Override
- public Response patch(Object obj) {
- return super.patch(convertToPatchFormat(obj));
- }
+ protected GraphInventoryPatchConverter getPatchConverter() {
+ return this.patchConverter;
+ }
- @Override
- public <T> T patch(Object obj, Class<T> resultClass) {
- return super.patch(convertToPatchFormat(obj), resultClass);
- }
-
- protected GraphInventoryPatchConverter getPatchConverter() {
- return this.patchConverter;
- }
-
- protected String convertToPatchFormat(Object obj) {
- return getPatchConverter().convertPatchFormat(obj);
- }
+ protected String convertToPatchFormat(Object obj) {
+ return getPatchConverter().convertPatchFormat(obj);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventorySubgraphType.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventorySubgraphType.java
index 4bbbe202cc..d30f481ac8 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventorySubgraphType.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventorySubgraphType.java
@@ -22,17 +22,16 @@ package org.onap.so.client.graphinventory;
public enum GraphInventorySubgraphType {
- STAR("star"),
- PRUNE("prune");
+ STAR("star"), PRUNE("prune");
- private final String name;
+ private final String name;
- private GraphInventorySubgraphType(String name) {
- this.name = name;
- }
+ private GraphInventorySubgraphType(String name) {
+ this.name = name;
+ }
- @Override
- public String toString() {
- return name;
- }
+ @Override
+ public String toString() {
+ return name;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryTransactionClient.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryTransactionClient.java
index 4c228b2ea3..992d1f017b 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryTransactionClient.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryTransactionClient.java
@@ -24,10 +24,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.GenericType;
-
import org.onap.aai.domain.yang.Relationship;
import org.onap.so.client.aai.AAIVersion;
import org.onap.so.client.aai.entities.singletransaction.SingleTransactionRequest;
@@ -37,202 +35,208 @@ import org.onap.so.client.graphinventory.exceptions.BulkProcessFailed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public abstract class GraphInventoryTransactionClient<Self, Uri extends GraphInventoryResourceUri, EdgeLabel extends GraphInventoryEdgeLabel> implements TransactionBuilder {
-
- protected static Logger logger = LoggerFactory.getLogger(GraphInventoryTransactionClient.class);
-
- protected int actionCount = 0;
-
- protected final GraphInventoryPatchConverter patchConverter = new GraphInventoryPatchConverter();
-
- protected GraphInventoryTransactionClient() {
- }
-
- /**
- * creates a new object in A&AI
- *
- * @param obj - can be any object which will marshal into a valid A&AI payload
- * @param uri
- * @return
- */
- public Self create(Uri uri, Object obj) {
- this.put(uri.build().toString(), obj);
- incrementActionAmount();
- return (Self)this;
- }
-
- /**
- * creates a new object in A&AI with no payload body
- *
- * @param uri
- * @return
- */
- public Self createEmpty(Uri uri) {
- this.put(uri.build().toString(), new HashMap<String, String>());
- incrementActionAmount();
- return (Self)this;
- }
-
- /**
- * Will automatically create the object if it does not exist
- *
- * @param obj - Optional object which serializes to a valid GraphInventory payload
- * @param uri
- * @return
- */
- public Self createIfNotExists(Uri uri, Optional<Object> obj) {
- if(!this.exists(uri)){
- if (obj.isPresent()) {
- this.create(uri, obj.get());
- } else {
- this.createEmpty(uri);
- }
-
- }
- return (Self)this;
- }
-
- /**
- * Adds a relationship between two objects in A&AI
- * @param uriA
- * @param uriB
- * @return
- */
- public Self connect(Uri uriA, Uri uriB) {
- GraphInventoryResourceUri uriAClone = uriA.clone();
- this.put(uriAClone.relationshipAPI().build().toString(), this.buildRelationship(uriB));
- incrementActionAmount();
- return (Self)this;
- }
-
- /**
- * relationship between multiple objects in A&AI - connects A to all objects specified in list
- *
- * @param uriA
- * @param uris
- * @return
- */
- public Self connect(Uri uriA, List<Uri> uris) {
- for (Uri uri : uris) {
- this.connect(uriA, uri);
- }
- return (Self)this;
- }
-
- /**
- * relationship between multiple objects in A&AI - connects A to all objects specified in list
- *
- * @param uriA
- * @param uris
- * @return
- */
- public Self connect(Uri uriA, Uri uriB, EdgeLabel label) {
- GraphInventoryResourceUri uriAClone = uriA.clone();
- this.put(uriAClone.relationshipAPI().build().toString(), this.buildRelationship(uriB, label));
- return (Self)this;
- }
-
- /**
- * relationship between multiple objects in A&AI - connects A to all objects specified in list
- *
- * @param uriA
- * @param uris
- * @return
- */
- public Self connect(Uri uriA, List<Uri> uris, EdgeLabel label) {
- for (Uri uri : uris) {
- this.connect(uriA, uri, label);
- }
- return (Self)this;
- }
-
- /**
- * Removes relationship from two objects in A&AI
- *
- * @param uriA
- * @param uriB
- * @return
- */
- public Self disconnect(Uri uriA, Uri uriB) {
- GraphInventoryResourceUri uriAClone = uriA.clone();
- this.delete(uriAClone.relationshipAPI().build().toString(), this.buildRelationship(uriB));
- incrementActionAmount();
- return (Self)this;
- }
-
- /**
- * Removes relationship from multiple objects - disconnects A from all objects specified in list
- * @param uriA
- * @param uris
- * @return
- */
- public Self disconnect(Uri uriA, List<Uri> uris) {
- for (Uri uri : uris) {
- this.disconnect(uriA, uri);
- }
- return (Self)this;
- }
- /**
- * Deletes object from A&AI. Automatically handles resource-version.
- *
- * @param uri
- * @return
- */
- public Self delete(Uri uri) {
- Map<String, Object> result = this.get(new GenericType<Map<String, Object>>(){}, (Uri)uri.clone())
- .orElseThrow(() -> new NotFoundException(uri.build() + " does not exist in " + this.getGraphDBName()));
- String resourceVersion = (String) result.get("resource-version");
- this.delete(uri.resourceVersion(resourceVersion).build().toString(), "");
- incrementActionAmount();
- return (Self)this;
- }
-
- protected abstract <T> Optional<T> get(GenericType<T> genericType, Uri clone);
-
- protected abstract boolean exists(Uri uri);
-
- protected abstract String getGraphDBName();
-
- /**
- * @param obj - can be any object which will marshal into a valid A&AI payload
- * @param uri
- * @return
- */
- public Self update(Uri uri, Object obj) {
-
- final String payload = getPatchConverter().convertPatchFormat(obj);
- this.patch(uri.build().toString(), payload);
- incrementActionAmount();
- return (Self)this;
- }
-
- private void incrementActionAmount() {
- actionCount++;
- }
- /**
- * Executes all created transactions in A&AI
- * @throws BulkProcessFailed
- */
- public abstract void execute() throws BulkProcessFailed;
-
- private Relationship buildRelationship(Uri uri) {
- return buildRelationship(uri, Optional.empty());
- }
-
- private Relationship buildRelationship(Uri uri, EdgeLabel label) {
- return buildRelationship(uri, Optional.of(label));
- }
- private Relationship buildRelationship(Uri uri, Optional<EdgeLabel> label) {
- final Relationship result = new Relationship();
- result.setRelatedLink(uri.build().toString());
- if (label.isPresent()) {
- result.setRelationshipLabel(label.toString());
- }
- return result;
- }
-
- protected GraphInventoryPatchConverter getPatchConverter() {
- return this.patchConverter;
- }
-
+public abstract class GraphInventoryTransactionClient<Self, Uri extends GraphInventoryResourceUri, EdgeLabel extends GraphInventoryEdgeLabel>
+ implements TransactionBuilder {
+
+ protected static Logger logger = LoggerFactory.getLogger(GraphInventoryTransactionClient.class);
+
+ protected int actionCount = 0;
+
+ protected final GraphInventoryPatchConverter patchConverter = new GraphInventoryPatchConverter();
+
+ protected GraphInventoryTransactionClient() {}
+
+ /**
+ * creates a new object in A&AI
+ *
+ * @param obj - can be any object which will marshal into a valid A&AI payload
+ * @param uri
+ * @return
+ */
+ public Self create(Uri uri, Object obj) {
+ this.put(uri.build().toString(), obj);
+ incrementActionAmount();
+ return (Self) this;
+ }
+
+ /**
+ * creates a new object in A&AI with no payload body
+ *
+ * @param uri
+ * @return
+ */
+ public Self createEmpty(Uri uri) {
+ this.put(uri.build().toString(), new HashMap<String, String>());
+ incrementActionAmount();
+ return (Self) this;
+ }
+
+ /**
+ * Will automatically create the object if it does not exist
+ *
+ * @param obj - Optional object which serializes to a valid GraphInventory payload
+ * @param uri
+ * @return
+ */
+ public Self createIfNotExists(Uri uri, Optional<Object> obj) {
+ if (!this.exists(uri)) {
+ if (obj.isPresent()) {
+ this.create(uri, obj.get());
+ } else {
+ this.createEmpty(uri);
+ }
+
+ }
+ return (Self) this;
+ }
+
+ /**
+ * Adds a relationship between two objects in A&AI
+ *
+ * @param uriA
+ * @param uriB
+ * @return
+ */
+ public Self connect(Uri uriA, Uri uriB) {
+ GraphInventoryResourceUri uriAClone = uriA.clone();
+ this.put(uriAClone.relationshipAPI().build().toString(), this.buildRelationship(uriB));
+ incrementActionAmount();
+ return (Self) this;
+ }
+
+ /**
+ * relationship between multiple objects in A&AI - connects A to all objects specified in list
+ *
+ * @param uriA
+ * @param uris
+ * @return
+ */
+ public Self connect(Uri uriA, List<Uri> uris) {
+ for (Uri uri : uris) {
+ this.connect(uriA, uri);
+ }
+ return (Self) this;
+ }
+
+ /**
+ * relationship between multiple objects in A&AI - connects A to all objects specified in list
+ *
+ * @param uriA
+ * @param uris
+ * @return
+ */
+ public Self connect(Uri uriA, Uri uriB, EdgeLabel label) {
+ GraphInventoryResourceUri uriAClone = uriA.clone();
+ this.put(uriAClone.relationshipAPI().build().toString(), this.buildRelationship(uriB, label));
+ return (Self) this;
+ }
+
+ /**
+ * relationship between multiple objects in A&AI - connects A to all objects specified in list
+ *
+ * @param uriA
+ * @param uris
+ * @return
+ */
+ public Self connect(Uri uriA, List<Uri> uris, EdgeLabel label) {
+ for (Uri uri : uris) {
+ this.connect(uriA, uri, label);
+ }
+ return (Self) this;
+ }
+
+ /**
+ * Removes relationship from two objects in A&AI
+ *
+ * @param uriA
+ * @param uriB
+ * @return
+ */
+ public Self disconnect(Uri uriA, Uri uriB) {
+ GraphInventoryResourceUri uriAClone = uriA.clone();
+ this.delete(uriAClone.relationshipAPI().build().toString(), this.buildRelationship(uriB));
+ incrementActionAmount();
+ return (Self) this;
+ }
+
+ /**
+ * Removes relationship from multiple objects - disconnects A from all objects specified in list
+ *
+ * @param uriA
+ * @param uris
+ * @return
+ */
+ public Self disconnect(Uri uriA, List<Uri> uris) {
+ for (Uri uri : uris) {
+ this.disconnect(uriA, uri);
+ }
+ return (Self) this;
+ }
+
+ /**
+ * Deletes object from A&AI. Automatically handles resource-version.
+ *
+ * @param uri
+ * @return
+ */
+ public Self delete(Uri uri) {
+ Map<String, Object> result = this.get(new GenericType<Map<String, Object>>() {}, (Uri) uri.clone())
+ .orElseThrow(() -> new NotFoundException(uri.build() + " does not exist in " + this.getGraphDBName()));
+ String resourceVersion = (String) result.get("resource-version");
+ this.delete(uri.resourceVersion(resourceVersion).build().toString(), "");
+ incrementActionAmount();
+ return (Self) this;
+ }
+
+ protected abstract <T> Optional<T> get(GenericType<T> genericType, Uri clone);
+
+ protected abstract boolean exists(Uri uri);
+
+ protected abstract String getGraphDBName();
+
+ /**
+ * @param obj - can be any object which will marshal into a valid A&AI payload
+ * @param uri
+ * @return
+ */
+ public Self update(Uri uri, Object obj) {
+
+ final String payload = getPatchConverter().convertPatchFormat(obj);
+ this.patch(uri.build().toString(), payload);
+ incrementActionAmount();
+ return (Self) this;
+ }
+
+ private void incrementActionAmount() {
+ actionCount++;
+ }
+
+ /**
+ * Executes all created transactions in A&AI
+ *
+ * @throws BulkProcessFailed
+ */
+ public abstract void execute() throws BulkProcessFailed;
+
+ private Relationship buildRelationship(Uri uri) {
+ return buildRelationship(uri, Optional.empty());
+ }
+
+ private Relationship buildRelationship(Uri uri, EdgeLabel label) {
+ return buildRelationship(uri, Optional.of(label));
+ }
+
+ private Relationship buildRelationship(Uri uri, Optional<EdgeLabel> label) {
+ final Relationship result = new Relationship();
+ result.setRelatedLink(uri.build().toString());
+ if (label.isPresent()) {
+ result.setRelationshipLabel(label.toString());
+ }
+ return result;
+ }
+
+ protected GraphInventoryPatchConverter getPatchConverter() {
+ return this.patchConverter;
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/TransactionBuilder.java b/common/src/main/java/org/onap/so/client/graphinventory/TransactionBuilder.java
index 88a6228d2b..3c69f70b11 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/TransactionBuilder.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/TransactionBuilder.java
@@ -22,9 +22,11 @@ package org.onap.so.client.graphinventory;
public interface TransactionBuilder {
-
- void put(String uri, Object body);
- void delete(String uri, Object body);
- void patch(String uri,Object body);
-
+
+ void put(String uri, Object body);
+
+ void delete(String uri, Object body);
+
+ void patch(String uri, Object body);
+
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNode.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNode.java
index 1e4750d2cf..7ee5bd328e 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNode.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNode.java
@@ -23,55 +23,56 @@ package org.onap.so.client.graphinventory.entities;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-
import org.onap.so.client.aai.entities.QueryStep;
import org.onap.so.client.graphinventory.GraphInventoryObjectName;
public class DSLNode implements QueryStep {
- private final String nodeName;
- private final List<DSLNodeKey> nodeKeys;
- private final StringBuilder query = new StringBuilder();
- private boolean output = false;
-
- public DSLNode() {
- this.nodeName = "";
- this.nodeKeys = new ArrayList<>();
-
- }
- public DSLNode(GraphInventoryObjectName name) {
- this.nodeName = name.typeName();
- this.nodeKeys = new ArrayList<>();
- query.append(nodeName);
- }
- public DSLNode(GraphInventoryObjectName name, DSLNodeKey... key) {
- this.nodeName = name.typeName();
- this.nodeKeys = Arrays.asList(key);
- query.append(nodeName);
- }
-
- public DSLNode output() {
- this.output = true;
-
- return this;
- }
+ private final String nodeName;
+ private final List<DSLNodeKey> nodeKeys;
+ private final StringBuilder query = new StringBuilder();
+ private boolean output = false;
+
+ public DSLNode() {
+ this.nodeName = "";
+ this.nodeKeys = new ArrayList<>();
+
+ }
+
+ public DSLNode(GraphInventoryObjectName name) {
+ this.nodeName = name.typeName();
+ this.nodeKeys = new ArrayList<>();
+ query.append(nodeName);
+ }
+
+ public DSLNode(GraphInventoryObjectName name, DSLNodeKey... key) {
+ this.nodeName = name.typeName();
+ this.nodeKeys = Arrays.asList(key);
+ query.append(nodeName);
+ }
+
+ public DSLNode output() {
+ this.output = true;
+
+ return this;
+ }
+
+ public DSLNode and(DSLNodeKey... key) {
+ this.nodeKeys.addAll(Arrays.asList(key));
+
+ return this;
+ }
+
+ @Override
+ public String build() {
+ StringBuilder result = new StringBuilder(query);
+ if (output) {
+ result.append("*");
+ }
+ for (DSLNodeKey key : nodeKeys) {
+ result.append(key.build());
+ }
- public DSLNode and(DSLNodeKey... key) {
- this.nodeKeys.addAll(Arrays.asList(key));
-
- return this;
- }
-
- @Override
- public String build() {
- StringBuilder result = new StringBuilder(query);
- if (output) {
- result.append("*");
- }
- for (DSLNodeKey key : nodeKeys) {
- result.append(key.build());
- }
-
- return result.toString();
- }
+ return result.toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java
index c40a3e6f96..bf33e8f8d3 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java
@@ -23,50 +23,49 @@ package org.onap.so.client.graphinventory.entities;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-
import org.onap.so.client.aai.entities.QueryStep;
-
import com.google.common.base.Joiner;
public class DSLNodeKey implements QueryStep {
- private boolean not = false;
- private final StringBuilder query = new StringBuilder();
- private final String keyName;
- private final List<String> values;
- public DSLNodeKey(String keyName, String... value) {
+ private boolean not = false;
+ private final StringBuilder query = new StringBuilder();
+ private final String keyName;
+ private final List<String> values;
+
+ public DSLNodeKey(String keyName, String... value) {
+
+ this.keyName = keyName;
+ this.values = Arrays.asList(value);
+ }
+
+ public DSLNodeKey not() {
+
+ this.not = true;
+ return this;
+ }
+
+ @Override
+ public String build() {
+ StringBuilder result = new StringBuilder(query);
- this.keyName = keyName;
- this.values = Arrays.asList(value);
- }
-
- public DSLNodeKey not() {
-
- this.not = true;
- return this;
- }
-
- @Override
- public String build() {
- StringBuilder result = new StringBuilder(query);
+ if (not) {
+ result.append(" !");
+ }
+ result.append("('").append(keyName).append("', ");
+ List<String> temp = new ArrayList<>();
+ for (String item : values) {
+ if (item.equals("null")) {
+ temp.add(String.format("' %s '", item));
+ } else if (item.equals("")) {
+ temp.add("' '");
+ } else {
+ temp.add(String.format("'%s'", item));
+ }
+ }
+ result.append(Joiner.on(", ").join(temp)).append(")");
- if (not) {
- result.append(" !");
- }
- result.append("('").append(keyName).append("', ");
- List<String> temp = new ArrayList<>();
- for (String item : values) {
- if (item.equals("null")) {
- temp.add(String.format("' %s '", item));
- } else if (item.equals("")){
- temp.add("' '");
- } else {
- temp.add(String.format("'%s'", item));
- }
- }
- result.append(Joiner.on(", ").join(temp)).append(")");
-
- return result.toString();
- }
+ return result.toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQuery.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQuery.java
index c8ab015b26..3056c9ca80 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQuery.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQuery.java
@@ -25,23 +25,23 @@ import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DSLQuery {
- private String dsl;
-
- public DSLQuery() {
-
- }
-
- public DSLQuery(String dsl) {
- this.dsl = dsl;
- }
-
- public String getDsl() {
- return dsl;
- }
-
- public void setDsl(String dsl) {
- this.dsl = dsl;
- }
-
-
+ private String dsl;
+
+ public DSLQuery() {
+
+ }
+
+ public DSLQuery(String dsl) {
+ this.dsl = dsl;
+ }
+
+ public String getDsl() {
+ return dsl;
+ }
+
+ public void setDsl(String dsl) {
+ this.dsl = dsl;
+ }
+
+
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java
index 3a47c38444..ffbb86f023 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java
@@ -24,123 +24,122 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
-
import org.onap.so.client.aai.entities.QueryStep;
import org.onap.so.client.graphinventory.GraphInventoryObjectName;
-
import com.google.common.base.Joiner;
public class DSLQueryBuilder<S, E> implements QueryStep {
- private List<QueryStep> steps = new ArrayList<>();
- private String suffix = "";
-
- public DSLQueryBuilder() {
-
- }
- public DSLQueryBuilder(DSLNode node) {
- steps.add(node);
- }
-
- public DSLQueryBuilder<S, DSLNode> node(DSLNode node) {
- steps.add(node);
-
- return (DSLQueryBuilder<S, DSLNode>) this;
- }
- public DSLQueryBuilder<S, E> output() {
- if (steps.get(steps.size() -1) instanceof DSLNode) {
- ((DSLNode)steps.get(steps.size() -1)).output();
- }
- return this;
- }
-
- public <E2> DSLQueryBuilder<S, E2> union(final DSLQueryBuilder<?, E2>... union) {
-
- List<DSLQueryBuilder<?, ?>> unions = Arrays.asList(union);
- steps.add(() -> {
- StringBuilder query = new StringBuilder();
-
- query.append("> [ ").append(
- Joiner.on(", ").join(
- unions.stream().map(item -> item.build()).collect(Collectors.toList())))
- .append(" ]");
- return query.toString();
- });
-
- return (DSLQueryBuilder<S, E2>) this;
- }
-
- public DSLQueryBuilder<S, E> where(DSLQueryBuilder<?, ?> where) {
-
- steps.add(() -> {
- StringBuilder query = new StringBuilder();
- query.append(where.build()).append(")");
- String result = query.toString();
- if (!result.startsWith(">")) {
- result = "> " + result;
- }
- return "(" + result;
- });
- return this;
- }
-
- public DSLQueryBuilder<S, E> to(DSLQueryBuilder<?, ?> to) {
- steps.add(() -> {
- StringBuilder query = new StringBuilder();
-
- query.append("> ").append(to.build());
- return query.toString();
- });
- return this;
- }
-
- public DSLQueryBuilder<S, E> to(GraphInventoryObjectName name) {
- return to(__.node(name));
- }
-
- public DSLQueryBuilder<S, E> to(GraphInventoryObjectName name, DSLNodeKey... key) {
- return to(__.node(name, key));
- }
-
- public DSLQueryBuilder<S, E> limit(int limit) {
- suffix = " LIMIT " + limit;
- return this;
- }
-
- @Override
- public String build() {
- return compile();
- }
-
- @Override
- public String toString() {
- return build();
- }
-
- @Override
- public boolean equals(Object o) {
- if (o != null) {
- if (o instanceof QueryStep) {
- return ((QueryStep)o).build().equals(this.build());
- } else if (o instanceof String) {
- return o.equals(this.build());
- }
- }
- return false;
- }
-
- @Override
- public int hashCode() {
-
- return build().hashCode();
- }
-
- private String compile() {
- return Joiner.on(" ").join(steps.stream().map(item -> item.build()).collect(Collectors.toList())) + suffix;
- }
-
- protected QueryStep getFirst() {
- return steps.get(0);
- }
+ private List<QueryStep> steps = new ArrayList<>();
+ private String suffix = "";
+
+ public DSLQueryBuilder() {
+
+ }
+
+ public DSLQueryBuilder(DSLNode node) {
+ steps.add(node);
+ }
+
+ public DSLQueryBuilder<S, DSLNode> node(DSLNode node) {
+ steps.add(node);
+
+ return (DSLQueryBuilder<S, DSLNode>) this;
+ }
+
+ public DSLQueryBuilder<S, E> output() {
+ if (steps.get(steps.size() - 1) instanceof DSLNode) {
+ ((DSLNode) steps.get(steps.size() - 1)).output();
+ }
+ return this;
+ }
+
+ public <E2> DSLQueryBuilder<S, E2> union(final DSLQueryBuilder<?, E2>... union) {
+
+ List<DSLQueryBuilder<?, ?>> unions = Arrays.asList(union);
+ steps.add(() -> {
+ StringBuilder query = new StringBuilder();
+
+ query.append("> [ ").append(
+ Joiner.on(", ").join(unions.stream().map(item -> item.build()).collect(Collectors.toList())))
+ .append(" ]");
+ return query.toString();
+ });
+
+ return (DSLQueryBuilder<S, E2>) this;
+ }
+
+ public DSLQueryBuilder<S, E> where(DSLQueryBuilder<?, ?> where) {
+
+ steps.add(() -> {
+ StringBuilder query = new StringBuilder();
+ query.append(where.build()).append(")");
+ String result = query.toString();
+ if (!result.startsWith(">")) {
+ result = "> " + result;
+ }
+ return "(" + result;
+ });
+ return this;
+ }
+
+ public DSLQueryBuilder<S, E> to(DSLQueryBuilder<?, ?> to) {
+ steps.add(() -> {
+ StringBuilder query = new StringBuilder();
+
+ query.append("> ").append(to.build());
+ return query.toString();
+ });
+ return this;
+ }
+
+ public DSLQueryBuilder<S, E> to(GraphInventoryObjectName name) {
+ return to(__.node(name));
+ }
+
+ public DSLQueryBuilder<S, E> to(GraphInventoryObjectName name, DSLNodeKey... key) {
+ return to(__.node(name, key));
+ }
+
+ public DSLQueryBuilder<S, E> limit(int limit) {
+ suffix = " LIMIT " + limit;
+ return this;
+ }
+
+ @Override
+ public String build() {
+ return compile();
+ }
+
+ @Override
+ public String toString() {
+ return build();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o != null) {
+ if (o instanceof QueryStep) {
+ return ((QueryStep) o).build().equals(this.build());
+ } else if (o instanceof String) {
+ return o.equals(this.build());
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+
+ return build().hashCode();
+ }
+
+ private String compile() {
+ return Joiner.on(" ").join(steps.stream().map(item -> item.build()).collect(Collectors.toList())) + suffix;
+ }
+
+ protected QueryStep getFirst() {
+ return steps.get(0);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java
index 461920fe7f..e3542e863a 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java
@@ -22,7 +22,7 @@ package org.onap.so.client.graphinventory.entities;
public interface GraphInventoryEdgeLabel {
-
- @Override
- public String toString();
+
+ @Override
+ public String toString();
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryRelationships.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryRelationships.java
index 752a743247..892951f950 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryRelationships.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryRelationships.java
@@ -27,7 +27,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
-
import org.onap.so.client.aai.AAICommonObjectMapperProvider;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.entities.AAIResultWrapper;
@@ -37,101 +36,102 @@ import org.onap.so.client.graphinventory.GraphInventoryObjectName;
import org.onap.so.client.graphinventory.GraphInventoryObjectType;
import org.onap.so.client.graphinventory.entities.uri.GraphInventoryResourceUri;
import org.onap.so.jsonpath.JsonPathUtil;
-
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class GraphInventoryRelationships<Wrapper extends GraphInventoryResultWrapper, Uri extends GraphInventoryResourceUri, Type extends GraphInventoryObjectType> {
- protected final ObjectMapper mapper;
- protected Map<String, Object> map;
- protected final String jsonBody;
-
- public GraphInventoryRelationships(String json) {
- this.jsonBody = json;
- this.mapper = new GraphInventoryCommonObjectMapperProvider().getMapper();
- try {
- this.map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {});
- } catch (IOException e) {
- this.map = new HashMap<>();
- }
- }
-
- public List<Wrapper> getByType(GraphInventoryObjectName type) {
-
- return this.getAll(Optional.of(type));
- }
-
- public List<Wrapper> getAll() {
-
- return this.getAll(Optional.empty());
- }
-
-
- public List<String> getRelatedLinks() {
- return this.getRelatedLinks(Optional.empty());
- }
-
- public List<String> getRelatedLinks(GraphInventoryObjectName type) {
- return this.getRelatedLinks(Optional.of(type));
- }
-
- public List<Uri> getRelatedUris() {
- return this.getRelatedUris(x -> true);
- }
-
- public List<Uri> getRelatedUris(GraphInventoryObjectName type) {
- return this.getRelatedUris(x -> type.typeName().equals(x));
- }
- protected List<Uri> getRelatedUris(Predicate<String> p) {
- List<Uri> result = new ArrayList<>();
- if (map.containsKey("relationship")) {
- List<Map<String, Object>> relationships = (List<Map<String, Object>>)map.get("relationship");
- for (Map<String, Object> relationship : relationships) {
- final String relatedTo = (String)relationship.get("related-to");
- if (p.test(relatedTo)) {
- Type type;
- type = fromTypeName(relatedTo);
- final String relatedLink = (String)relationship.get("related-link");
-
- result.add(createUri(type, relatedLink));
- }
- }
- }
- return result;
- }
-
-
-
- protected List<Wrapper> getAll(final Optional<GraphInventoryObjectName> type) {
- List<Uri> relatedLinks;
- if (type.isPresent()) {
- relatedLinks = this.getRelatedUris(type.get());
- } else {
- relatedLinks = this.getRelatedUris();
- }
- ArrayList<Wrapper> result = new ArrayList<>();
- for (Uri link : relatedLinks) {
- result.add(this.get(link));
- }
- return result;
- }
-
- protected abstract Wrapper get(Uri uri);
-
- protected abstract Uri createUri(Type type, String relatedLink);
-
- protected abstract Type fromTypeName(String name);
-
- protected List<String> getRelatedLinks(Optional<GraphInventoryObjectName> type) {
- String matcher = "";
- if (type.isPresent()) {
- matcher = "[?(@.related-to=='" + type.get().typeName() + "')]";
- }
- return JsonPathUtil.getInstance().locateResultList(this.jsonBody, String.format("$.relationship%s.related-link", matcher));
- }
-
- public String getJson() {
- return this.jsonBody;
- }
+ protected final ObjectMapper mapper;
+ protected Map<String, Object> map;
+ protected final String jsonBody;
+
+ public GraphInventoryRelationships(String json) {
+ this.jsonBody = json;
+ this.mapper = new GraphInventoryCommonObjectMapperProvider().getMapper();
+ try {
+ this.map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {});
+ } catch (IOException e) {
+ this.map = new HashMap<>();
+ }
+ }
+
+ public List<Wrapper> getByType(GraphInventoryObjectName type) {
+
+ return this.getAll(Optional.of(type));
+ }
+
+ public List<Wrapper> getAll() {
+
+ return this.getAll(Optional.empty());
+ }
+
+
+ public List<String> getRelatedLinks() {
+ return this.getRelatedLinks(Optional.empty());
+ }
+
+ public List<String> getRelatedLinks(GraphInventoryObjectName type) {
+ return this.getRelatedLinks(Optional.of(type));
+ }
+
+ public List<Uri> getRelatedUris() {
+ return this.getRelatedUris(x -> true);
+ }
+
+ public List<Uri> getRelatedUris(GraphInventoryObjectName type) {
+ return this.getRelatedUris(x -> type.typeName().equals(x));
+ }
+
+ protected List<Uri> getRelatedUris(Predicate<String> p) {
+ List<Uri> result = new ArrayList<>();
+ if (map.containsKey("relationship")) {
+ List<Map<String, Object>> relationships = (List<Map<String, Object>>) map.get("relationship");
+ for (Map<String, Object> relationship : relationships) {
+ final String relatedTo = (String) relationship.get("related-to");
+ if (p.test(relatedTo)) {
+ Type type;
+ type = fromTypeName(relatedTo);
+ final String relatedLink = (String) relationship.get("related-link");
+
+ result.add(createUri(type, relatedLink));
+ }
+ }
+ }
+ return result;
+ }
+
+
+
+ protected List<Wrapper> getAll(final Optional<GraphInventoryObjectName> type) {
+ List<Uri> relatedLinks;
+ if (type.isPresent()) {
+ relatedLinks = this.getRelatedUris(type.get());
+ } else {
+ relatedLinks = this.getRelatedUris();
+ }
+ ArrayList<Wrapper> result = new ArrayList<>();
+ for (Uri link : relatedLinks) {
+ result.add(this.get(link));
+ }
+ return result;
+ }
+
+ protected abstract Wrapper get(Uri uri);
+
+ protected abstract Uri createUri(Type type, String relatedLink);
+
+ protected abstract Type fromTypeName(String name);
+
+ protected List<String> getRelatedLinks(Optional<GraphInventoryObjectName> type) {
+ String matcher = "";
+ if (type.isPresent()) {
+ matcher = "[?(@.related-to=='" + type.get().typeName() + "')]";
+ }
+ return JsonPathUtil.getInstance().locateResultList(this.jsonBody,
+ String.format("$.relationship%s.related-link", matcher));
+ }
+
+ public String getJson() {
+ return this.jsonBody;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryResultWrapper.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryResultWrapper.java
index c0b29e46c2..6a571038ee 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryResultWrapper.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryResultWrapper.java
@@ -27,97 +27,99 @@ import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-
import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider;
import org.onap.so.jsonpath.JsonPathUtil;
import org.slf4j.Logger;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
-public abstract class GraphInventoryResultWrapper<R extends GraphInventoryRelationships<?, ?, ?>> implements Serializable {
-
- private static final long serialVersionUID = 5895841925807816727L;
- protected final String jsonBody;
- protected final ObjectMapper mapper;
- private final transient Logger logger;
-
- protected GraphInventoryResultWrapper(String json, Logger logger) {
- this.jsonBody = json;
- this.mapper = new GraphInventoryCommonObjectMapperProvider().getMapper();
- this.logger = logger;
- }
-
- protected GraphInventoryResultWrapper(Object aaiObject, Logger logger) {
- this.mapper = new GraphInventoryCommonObjectMapperProvider().getMapper();
- this.jsonBody = mapObjectToString(aaiObject);
- this.logger = logger;
- }
-
- protected String mapObjectToString(Object aaiObject) {
- try {
- return mapper.writeValueAsString(aaiObject);
- } catch (JsonProcessingException e) {
- logger.warn("could not parse object into json - defaulting to empty object");
- return "{}";
- }
- }
- public Optional<R> getRelationships() {
- final String path = "$.relationship-list";
- if (isEmpty()) {
- return Optional.empty();
- }
- Optional<String> result = JsonPathUtil.getInstance().locateResult(jsonBody, path);
- if (result.isPresent()) {
- return Optional.of(createRelationships(result.get()));
- } else {
- return Optional.empty();
- }
- }
- protected abstract R createRelationships(String json);
-
- public String getJson() {
- if(jsonBody == null) {
- return "{}";
- } else {
- return jsonBody;
- }
- }
-
- public Map<String, Object> asMap() {
-
- return asBean(new TypeReference<Map<String, Object>>(){}).orElse(new HashMap<>());
- }
-
- public <T> Optional<T> asBean(Class<T> clazz) {
- if (isEmpty()) {
- return Optional.empty();
- }
- try {
- return Optional.of(mapper.readValue(this.jsonBody, clazz));
- } catch (IOException e) {
- return Optional.empty();
- }
- }
-
- public <T> Optional<T> asBean(TypeReference<T> reference) {
- if (isEmpty()) {
- return Optional.empty();
- }
- try {
- return Optional.of(mapper.readValue(this.jsonBody, reference));
- } catch (IOException e) {
- return Optional.empty();
- }
- }
-
- public boolean isEmpty() {
- return jsonBody == null;
- }
- @Override
- public String toString() {
- return this.getJson();
- }
+public abstract class GraphInventoryResultWrapper<R extends GraphInventoryRelationships<?, ?, ?>>
+ implements Serializable {
+
+ private static final long serialVersionUID = 5895841925807816727L;
+ protected final String jsonBody;
+ protected final ObjectMapper mapper;
+ private final transient Logger logger;
+
+ protected GraphInventoryResultWrapper(String json, Logger logger) {
+ this.jsonBody = json;
+ this.mapper = new GraphInventoryCommonObjectMapperProvider().getMapper();
+ this.logger = logger;
+ }
+
+ protected GraphInventoryResultWrapper(Object aaiObject, Logger logger) {
+ this.mapper = new GraphInventoryCommonObjectMapperProvider().getMapper();
+ this.jsonBody = mapObjectToString(aaiObject);
+ this.logger = logger;
+ }
+
+ protected String mapObjectToString(Object aaiObject) {
+ try {
+ return mapper.writeValueAsString(aaiObject);
+ } catch (JsonProcessingException e) {
+ logger.warn("could not parse object into json - defaulting to empty object");
+ return "{}";
+ }
+ }
+
+ public Optional<R> getRelationships() {
+ final String path = "$.relationship-list";
+ if (isEmpty()) {
+ return Optional.empty();
+ }
+ Optional<String> result = JsonPathUtil.getInstance().locateResult(jsonBody, path);
+ if (result.isPresent()) {
+ return Optional.of(createRelationships(result.get()));
+ } else {
+ return Optional.empty();
+ }
+ }
+
+ protected abstract R createRelationships(String json);
+
+ public String getJson() {
+ if (jsonBody == null) {
+ return "{}";
+ } else {
+ return jsonBody;
+ }
+ }
+
+ public Map<String, Object> asMap() {
+
+ return asBean(new TypeReference<Map<String, Object>>() {}).orElse(new HashMap<>());
+ }
+
+ public <T> Optional<T> asBean(Class<T> clazz) {
+ if (isEmpty()) {
+ return Optional.empty();
+ }
+ try {
+ return Optional.of(mapper.readValue(this.jsonBody, clazz));
+ } catch (IOException e) {
+ return Optional.empty();
+ }
+ }
+
+ public <T> Optional<T> asBean(TypeReference<T> reference) {
+ if (isEmpty()) {
+ return Optional.empty();
+ }
+ try {
+ return Optional.of(mapper.readValue(this.jsonBody, reference));
+ } catch (IOException e) {
+ return Optional.empty();
+ }
+ }
+
+ public boolean isEmpty() {
+ return jsonBody == null;
+ }
+
+ @Override
+ public String toString() {
+ return this.getJson();
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/Resource.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/Resource.java
index 8d49fb5640..1e7169d092 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/Resource.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/Resource.java
@@ -25,36 +25,33 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "resource-type",
- "resource-link"
-})
+@JsonPropertyOrder({"resource-type", "resource-link"})
public class Resource {
- @JsonProperty("resource-type")
- private String resourceType;
- @JsonProperty("resource-link")
- private String resourceLink;
-
- @JsonProperty("resource-type")
- public String getResourceType() {
- return resourceType;
- }
-
- @JsonProperty("resource-type")
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- @JsonProperty("resource-link")
- public String getResourceLink() {
- return resourceLink;
- }
-
- @JsonProperty("resource-link")
- public void setResourceLink(String resourceLink) {
- this.resourceLink = resourceLink;
- }
+ @JsonProperty("resource-type")
+ private String resourceType;
+ @JsonProperty("resource-link")
+ private String resourceLink;
+
+ @JsonProperty("resource-type")
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ @JsonProperty("resource-type")
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ @JsonProperty("resource-link")
+ public String getResourceLink() {
+ return resourceLink;
+ }
+
+ @JsonProperty("resource-link")
+ public void setResourceLink(String resourceLink) {
+ this.resourceLink = resourceLink;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/ResourceAndUrl.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/ResourceAndUrl.java
index 6e7312c1f3..326bd06dfb 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/ResourceAndUrl.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/ResourceAndUrl.java
@@ -24,33 +24,38 @@ import org.onap.so.client.graphinventory.GraphInventoryObjectType;
public class ResourceAndUrl<Wrapper extends GraphInventoryResultWrapper> {
- private String url;
- private GraphInventoryObjectType type;
- private Wrapper wrapper;
-
- public ResourceAndUrl(String url, GraphInventoryObjectType type, Wrapper wrapper) {
- this.url = url;
- this.type = type;
- this.wrapper = wrapper;
- }
- public String getUrl() {
- return url;
- }
- public void setUrl(String url) {
- this.url = url;
- }
- public Wrapper getWrapper() {
- return wrapper;
- }
- public void setWrapper(Wrapper wrapper) {
- this.wrapper = wrapper;
- }
- public GraphInventoryObjectType getType() {
- return type;
- }
-
- public void setType(GraphInventoryObjectType type) {
- this.type = type;
- }
-
+ private String url;
+ private GraphInventoryObjectType type;
+ private Wrapper wrapper;
+
+ public ResourceAndUrl(String url, GraphInventoryObjectType type, Wrapper wrapper) {
+ this.url = url;
+ this.type = type;
+ this.wrapper = wrapper;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public Wrapper getWrapper() {
+ return wrapper;
+ }
+
+ public void setWrapper(Wrapper wrapper) {
+ this.wrapper = wrapper;
+ }
+
+ public GraphInventoryObjectType getType() {
+ return type;
+ }
+
+ public void setType(GraphInventoryObjectType type) {
+ this.type = type;
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java
index 184f412adb..2fdd6574e5 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java
@@ -24,36 +24,38 @@ import org.onap.so.client.graphinventory.GraphInventoryObjectName;
public class __ {
- protected __() {
-
- }
-
- public static <A> DSLQueryBuilder<A, A> identity() {
- return new DSLQueryBuilder<>();
- }
- public static <A> DSLQueryBuilder<A, A> start(DSLNode node) {
- return new DSLQueryBuilder<>(node);
- }
- public static DSLQueryBuilder<DSLNode, DSLNode> node(GraphInventoryObjectName name) {
-
- return __.<DSLNode>start(new DSLNode(name));
- }
-
- public static DSLQueryBuilder<DSLNode, DSLNode> node(GraphInventoryObjectName name, DSLNodeKey... key) {
- return __.<DSLNode>start(new DSLNode(name, key));
- }
-
- public static DSLNodeKey key(String keyName, String... value) {
- return new DSLNodeKey(keyName, value);
- }
-
- public static <A, B> DSLQueryBuilder<A, B> union(final DSLQueryBuilder<?, B>... traversal) {
-
- return __.<A>identity().union(traversal);
- }
-
-public static <A> DSLQueryBuilder<A, A> where(DSLQueryBuilder<A, A> traversal) {
-
- return __.<A>identity().where(traversal);
- }
+ protected __() {
+
+ }
+
+ public static <A> DSLQueryBuilder<A, A> identity() {
+ return new DSLQueryBuilder<>();
+ }
+
+ public static <A> DSLQueryBuilder<A, A> start(DSLNode node) {
+ return new DSLQueryBuilder<>(node);
+ }
+
+ public static DSLQueryBuilder<DSLNode, DSLNode> node(GraphInventoryObjectName name) {
+
+ return __.<DSLNode>start(new DSLNode(name));
+ }
+
+ public static DSLQueryBuilder<DSLNode, DSLNode> node(GraphInventoryObjectName name, DSLNodeKey... key) {
+ return __.<DSLNode>start(new DSLNode(name, key));
+ }
+
+ public static DSLNodeKey key(String keyName, String... value) {
+ return new DSLNodeKey(keyName, value);
+ }
+
+ public static <A, B> DSLQueryBuilder<A, B> union(final DSLQueryBuilder<?, B>... traversal) {
+
+ return __.<A>identity().union(traversal);
+ }
+
+ public static <A> DSLQueryBuilder<A, A> where(DSLQueryBuilder<A, A> traversal) {
+
+ return __.<A>identity().where(traversal);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/Depth.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/Depth.java
index 1205511d11..d91f36c0c7 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/Depth.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/Depth.java
@@ -21,24 +21,18 @@
package org.onap.so.client.graphinventory.entities.uri;
public enum Depth {
- ZERO("0"),
- ONE("1"),
- TWO("2"),
- THREE("3"),
- FOUR("4"),
- FIVE("5"),
- SIX("6"),
- ALL("all");
-
- private final String depth;
- private Depth(String s) {
-
- this.depth = s;
- }
-
-
- @Override
- public String toString() {
- return this.depth;
- }
+ ZERO("0"), ONE("1"), TWO("2"), THREE("3"), FOUR("4"), FIVE("5"), SIX("6"), ALL("all");
+
+ private final String depth;
+
+ private Depth(String s) {
+
+ this.depth = s;
+ }
+
+
+ @Override
+ public String toString() {
+ return this.depth;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryResourceUri.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryResourceUri.java
index 2357d07fd4..c579a285d2 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryResourceUri.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryResourceUri.java
@@ -26,25 +26,37 @@ import org.onap.so.client.graphinventory.GraphInventoryObjectPlurals;
import org.onap.so.client.graphinventory.GraphInventoryObjectType;
public interface GraphInventoryResourceUri extends GraphInventoryUri {
- public GraphInventoryResourceUri relationshipAPI();
- public GraphInventoryResourceUri relatedTo(GraphInventoryObjectPlurals plural);
- public GraphInventoryResourceUri relatedTo(GraphInventoryObjectType type, String... values);
- public GraphInventoryResourceUri resourceVersion(String version);
- public GraphInventoryResourceUri format(Format format);
- @Override
- public GraphInventoryResourceUri depth(Depth depth);
- @Override
- public GraphInventoryResourceUri nodesOnly(boolean nodesOnly);
- @Override
- public GraphInventoryResourceUri queryParam(String name, String... values);
- @Override
- public GraphInventoryResourceUri replaceQueryParam(String name, String... values);
- @Override
- public GraphInventoryResourceUri resultIndex(int index);
- @Override
- public GraphInventoryResourceUri resultSize(int size);
- @Override
- public GraphInventoryResourceUri limit(int size);
- @Override
- public GraphInventoryResourceUri clone();
+ public GraphInventoryResourceUri relationshipAPI();
+
+ public GraphInventoryResourceUri relatedTo(GraphInventoryObjectPlurals plural);
+
+ public GraphInventoryResourceUri relatedTo(GraphInventoryObjectType type, String... values);
+
+ public GraphInventoryResourceUri resourceVersion(String version);
+
+ public GraphInventoryResourceUri format(Format format);
+
+ @Override
+ public GraphInventoryResourceUri depth(Depth depth);
+
+ @Override
+ public GraphInventoryResourceUri nodesOnly(boolean nodesOnly);
+
+ @Override
+ public GraphInventoryResourceUri queryParam(String name, String... values);
+
+ @Override
+ public GraphInventoryResourceUri replaceQueryParam(String name, String... values);
+
+ @Override
+ public GraphInventoryResourceUri resultIndex(int index);
+
+ @Override
+ public GraphInventoryResourceUri resultSize(int size);
+
+ @Override
+ public GraphInventoryResourceUri limit(int size);
+
+ @Override
+ public GraphInventoryResourceUri clone();
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryUri.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryUri.java
index 42c478eff7..d6d3e5eaa2 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryUri.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryUri.java
@@ -22,42 +22,55 @@ package org.onap.so.client.graphinventory.entities.uri;
import java.net.URI;
import java.util.Map;
-
import org.onap.so.client.graphinventory.entities.uri.Depth;
import org.onap.so.client.graphinventory.GraphInventoryObjectType;
public interface GraphInventoryUri {
-
- public URI build();
- /**
- * By default GraphInventory enforces a depth of 1. Some objects can be told to retrieve objects
- * nested beneath them by increasing this number.
- *
- * You can use 0 to restrict the returned information to only the object you requested
- * You can use all to retrieve all nested objects (this should only be used if you really need a massive amount of information and are caching the retrieval)
- * @param depth
- * @return
- */
- public GraphInventoryUri depth(Depth depth);
- /**
- * Makes client only return object fields, no relationships
- *
- * @return
- */
- public GraphInventoryUri nodesOnly(boolean nodesOnly);
- public GraphInventoryUri queryParam(String name, String... values);
- public GraphInventoryUri replaceQueryParam(String name, String... values);
- public GraphInventoryUri resultIndex(int index);
- public GraphInventoryUri resultSize(int size);
- public GraphInventoryUri limit(int size);
- public GraphInventoryUri clone();
-
- /**
- * returns all key values of the URI as a map. Key names can be found in {@link GraphInventoryObjectType}
- * @return
- */
- public Map<String, String> getURIKeys();
- public GraphInventoryObjectType getObjectType();
- public boolean equals(Object o);
- public int hashCode();
+
+ public URI build();
+
+ /**
+ * By default GraphInventory enforces a depth of 1. Some objects can be told to retrieve objects nested beneath them
+ * by increasing this number.
+ *
+ * You can use 0 to restrict the returned information to only the object you requested You can use all to retrieve
+ * all nested objects (this should only be used if you really need a massive amount of information and are caching
+ * the retrieval)
+ *
+ * @param depth
+ * @return
+ */
+ public GraphInventoryUri depth(Depth depth);
+
+ /**
+ * Makes client only return object fields, no relationships
+ *
+ * @return
+ */
+ public GraphInventoryUri nodesOnly(boolean nodesOnly);
+
+ public GraphInventoryUri queryParam(String name, String... values);
+
+ public GraphInventoryUri replaceQueryParam(String name, String... values);
+
+ public GraphInventoryUri resultIndex(int index);
+
+ public GraphInventoryUri resultSize(int size);
+
+ public GraphInventoryUri limit(int size);
+
+ public GraphInventoryUri clone();
+
+ /**
+ * returns all key values of the URI as a map. Key names can be found in {@link GraphInventoryObjectType}
+ *
+ * @return
+ */
+ public Map<String, String> getURIKeys();
+
+ public GraphInventoryObjectType getObjectType();
+
+ public boolean equals(Object o);
+
+ public int hashCode();
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java
index 3d08c8d40c..fcfde74b33 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java
@@ -24,6 +24,6 @@ import java.net.URI;
public interface HttpAwareUri {
-
- public URI buildNoNetwork();
+
+ public URI buildNoNetwork();
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java
index 1b8844116a..5d0a33909a 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java
@@ -29,9 +29,7 @@ import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
-
import javax.ws.rs.core.UriBuilder;
-
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.client.graphinventory.Format;
import org.onap.so.client.graphinventory.GraphInventoryObjectPlurals;
@@ -43,229 +41,241 @@ import org.springframework.web.util.UriUtils;
public class SimpleUri implements GraphInventoryResourceUri, Serializable {
- private static final long serialVersionUID = -337701171277616439L;
-
- protected transient UriBuilder internalURI;
- protected final static String relationshipAPI = "/relationship-list/relationship";
- protected final static String relatedTo = "/related-to";
- protected final Object[] values;
- protected final GraphInventoryObjectType type;
- protected final GraphInventoryObjectPlurals pluralType;
- protected SimpleUri(GraphInventoryObjectType type, Object... values) {
- this.type = type;
- this.pluralType = null;
- this.internalURI = UriBuilder.fromPath(this.getTemplate(type));
- this.values = values;
- validateValuesSize(this.getTemplate(type), values);
- }
- protected SimpleUri(GraphInventoryObjectType type, URI uri) {
- this.type = type;
- this.pluralType = null;
- this.internalURI = UriBuilder.fromPath(uri.getRawPath().replaceAll("/aai/v\\d+", ""));
- this.values = new Object[0];
- }
- protected SimpleUri(GraphInventoryObjectType type, UriBuilder builder, Object... values) {
- this.internalURI = builder;
- this.values = values;
- this.type = type;
- this.pluralType = null;
- }
- protected SimpleUri(GraphInventoryObjectPlurals type, UriBuilder builder, Object... values) {
- this.internalURI = builder;
- this.values = values;
- this.type = null;
- this.pluralType = type;
- }
- protected SimpleUri(GraphInventoryObjectPlurals type) {
- this.type = null;
- this.pluralType = type;
- this.internalURI = UriBuilder.fromPath(this.getTemplate(type));
- this.values = new Object[0];
- }
- protected SimpleUri(GraphInventoryObjectPlurals type, Object... values) {
- this.type = null;
- this.pluralType = type;
- this.internalURI = UriBuilder.fromPath(this.getTemplate(type));
- this.values = values;
- validateValuesSize(this.getTemplate(type), values);
- }
- protected SimpleUri(GraphInventoryResourceUri parentUri, GraphInventoryObjectType childType, Object... childValues) {
- this.type = childType;
- this.pluralType = null;
- this.internalURI = UriBuilder.fromUri(parentUri.build()).path(childType.partialUri());
- this.values = childValues;
- validateValuesSize(childType.partialUri(), values);
- }
-
- protected SimpleUri(GraphInventoryResourceUri parentUri, GraphInventoryObjectPlurals childType) {
- this.type = null;
- this.pluralType = childType;
- this.internalURI = UriBuilder.fromUri(parentUri.build()).path(childType.partialUri());
- this.values = new Object[0];
- }
-
- protected void setInternalURI(UriBuilder builder) {
- this.internalURI = builder;
- }
- @Override
- public SimpleUri relationshipAPI() {
- this.internalURI = internalURI.path(relationshipAPI);
- return this;
- }
-
- @Override
- public SimpleUri relatedTo(GraphInventoryObjectPlurals plural) {
-
- this.internalURI = internalURI.path(relatedTo).path(plural.partialUri());
- return this;
- }
- @Override
- public SimpleUri relatedTo(GraphInventoryObjectType type, String... values) {
- this.internalURI = internalURI.path(relatedTo).path(UriBuilder.fromPath(type.partialUri()).build(values).toString());
- return this;
- }
-
- @Override
- public SimpleUri resourceVersion(String version) {
- this.internalURI = internalURI.replaceQueryParam("resource-version", version);
- return this;
- }
-
- @Override
- public SimpleUri queryParam(String name, String... values) {
- this.internalURI = internalURI.queryParam(name, values);
- return this;
- }
-
- @Override
- public SimpleUri replaceQueryParam(String name, String... values) {
- this.internalURI = internalURI.replaceQueryParam(name, values);
- return this;
- }
-
- @Override
- public SimpleUri resultIndex(int index) {
- this.internalURI = internalURI.replaceQueryParam("resultIndex", index);
- return this;
- }
-
- @Override
- public SimpleUri resultSize(int size) {
- this.internalURI = internalURI.replaceQueryParam("resultSize", size);
- return this;
- }
-
- @Override
- public SimpleUri limit(int size) {
- return this.resultIndex(0).resultSize(size);
- }
-
- @Override
- public URI build() {
- return build(this.values);
- }
-
- protected URI build(Object... values) {
- //This is a workaround because resteasy does not encode URIs correctly
- final String[] encoded = new String[values.length];
- for (int i = 0; i < values.length; i++) {
- encoded[i] = UriUtils.encode(values[i].toString(), StandardCharsets.UTF_8.toString());
- }
- return internalURI.buildFromEncoded(encoded);
- }
-
- @Override
- public Map<String, String> getURIKeys() {
- return this.getURIKeys(this.build().toString());
- }
-
- protected Map<String, String> getURIKeys(String uri) {
- UriParser parser;
- if (this.type != null) {
- if (!("".equals(this.getTemplate(type)))) {
- parser = new UriParserSpringImpl(this.getTemplate(type));
- } else {
- return new HashMap<>();
- }
- } else {
- parser = new UriParserSpringImpl(this.getTemplate(pluralType));
- }
-
-
- return parser.parse(uri);
- }
-
- @Override
- public SimpleUri clone() {
- if (this.type != null) {
- return new SimpleUri(this.type, this.internalURI.clone(), values);
- } else {
- return new SimpleUri(this.pluralType, this.internalURI.clone(), values);
- }
- }
-
- @Override
- public GraphInventoryObjectType getObjectType() {
- return this.type;
- }
-
- @Override
- public boolean equals(Object o) {
- if (o instanceof GraphInventoryUri) {
- return this.build().equals(((GraphInventoryUri)o).build());
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(this.build()).toHashCode();
- }
-
-
- @Override
- public SimpleUri depth(Depth depth) {
- this.internalURI.replaceQueryParam("depth", depth.toString());
- return this;
- }
- @Override
- public SimpleUri nodesOnly(boolean nodesOnly) {
- if (nodesOnly) {
- this.internalURI.replaceQueryParam("nodes-only", "");
- }
- return this;
- }
-
- @Override
- public SimpleUri format(Format format) {
- this.internalURI.replaceQueryParam("format", format);
- return this;
- }
-
- public void validateValuesSize(String template, Object... values) {
- UriParser parser = new UriParserSpringImpl(template);
- Set<String> variables = parser.getVariables();
- if (variables.size() != values.length) {
- throw new IncorrectNumberOfUriKeys(String.format("Expected %s variables: %s", variables.size(), variables));
- }
- }
-
- protected String getTemplate(GraphInventoryObjectType type) {
- return type.uriTemplate();
- }
-
- protected String getTemplate(GraphInventoryObjectPlurals type) {
- return type.uriTemplate();
- }
-
- private void writeObject(ObjectOutputStream oos) throws IOException {
- oos.defaultWriteObject();
- oos.writeUTF(this.internalURI.toTemplate());
- }
-
- private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
- ois.defaultReadObject();
- String uri = ois.readUTF();
- this.setInternalURI(UriBuilder.fromUri(uri));
- }
+ private static final long serialVersionUID = -337701171277616439L;
+
+ protected transient UriBuilder internalURI;
+ protected final static String relationshipAPI = "/relationship-list/relationship";
+ protected final static String relatedTo = "/related-to";
+ protected final Object[] values;
+ protected final GraphInventoryObjectType type;
+ protected final GraphInventoryObjectPlurals pluralType;
+
+ protected SimpleUri(GraphInventoryObjectType type, Object... values) {
+ this.type = type;
+ this.pluralType = null;
+ this.internalURI = UriBuilder.fromPath(this.getTemplate(type));
+ this.values = values;
+ validateValuesSize(this.getTemplate(type), values);
+ }
+
+ protected SimpleUri(GraphInventoryObjectType type, URI uri) {
+ this.type = type;
+ this.pluralType = null;
+ this.internalURI = UriBuilder.fromPath(uri.getRawPath().replaceAll("/aai/v\\d+", ""));
+ this.values = new Object[0];
+ }
+
+ protected SimpleUri(GraphInventoryObjectType type, UriBuilder builder, Object... values) {
+ this.internalURI = builder;
+ this.values = values;
+ this.type = type;
+ this.pluralType = null;
+ }
+
+ protected SimpleUri(GraphInventoryObjectPlurals type, UriBuilder builder, Object... values) {
+ this.internalURI = builder;
+ this.values = values;
+ this.type = null;
+ this.pluralType = type;
+ }
+
+ protected SimpleUri(GraphInventoryObjectPlurals type) {
+ this.type = null;
+ this.pluralType = type;
+ this.internalURI = UriBuilder.fromPath(this.getTemplate(type));
+ this.values = new Object[0];
+ }
+
+ protected SimpleUri(GraphInventoryObjectPlurals type, Object... values) {
+ this.type = null;
+ this.pluralType = type;
+ this.internalURI = UriBuilder.fromPath(this.getTemplate(type));
+ this.values = values;
+ validateValuesSize(this.getTemplate(type), values);
+ }
+
+ protected SimpleUri(GraphInventoryResourceUri parentUri, GraphInventoryObjectType childType,
+ Object... childValues) {
+ this.type = childType;
+ this.pluralType = null;
+ this.internalURI = UriBuilder.fromUri(parentUri.build()).path(childType.partialUri());
+ this.values = childValues;
+ validateValuesSize(childType.partialUri(), values);
+ }
+
+ protected SimpleUri(GraphInventoryResourceUri parentUri, GraphInventoryObjectPlurals childType) {
+ this.type = null;
+ this.pluralType = childType;
+ this.internalURI = UriBuilder.fromUri(parentUri.build()).path(childType.partialUri());
+ this.values = new Object[0];
+ }
+
+ protected void setInternalURI(UriBuilder builder) {
+ this.internalURI = builder;
+ }
+
+ @Override
+ public SimpleUri relationshipAPI() {
+ this.internalURI = internalURI.path(relationshipAPI);
+ return this;
+ }
+
+ @Override
+ public SimpleUri relatedTo(GraphInventoryObjectPlurals plural) {
+
+ this.internalURI = internalURI.path(relatedTo).path(plural.partialUri());
+ return this;
+ }
+
+ @Override
+ public SimpleUri relatedTo(GraphInventoryObjectType type, String... values) {
+ this.internalURI =
+ internalURI.path(relatedTo).path(UriBuilder.fromPath(type.partialUri()).build(values).toString());
+ return this;
+ }
+
+ @Override
+ public SimpleUri resourceVersion(String version) {
+ this.internalURI = internalURI.replaceQueryParam("resource-version", version);
+ return this;
+ }
+
+ @Override
+ public SimpleUri queryParam(String name, String... values) {
+ this.internalURI = internalURI.queryParam(name, values);
+ return this;
+ }
+
+ @Override
+ public SimpleUri replaceQueryParam(String name, String... values) {
+ this.internalURI = internalURI.replaceQueryParam(name, values);
+ return this;
+ }
+
+ @Override
+ public SimpleUri resultIndex(int index) {
+ this.internalURI = internalURI.replaceQueryParam("resultIndex", index);
+ return this;
+ }
+
+ @Override
+ public SimpleUri resultSize(int size) {
+ this.internalURI = internalURI.replaceQueryParam("resultSize", size);
+ return this;
+ }
+
+ @Override
+ public SimpleUri limit(int size) {
+ return this.resultIndex(0).resultSize(size);
+ }
+
+ @Override
+ public URI build() {
+ return build(this.values);
+ }
+
+ protected URI build(Object... values) {
+ // This is a workaround because resteasy does not encode URIs correctly
+ final String[] encoded = new String[values.length];
+ for (int i = 0; i < values.length; i++) {
+ encoded[i] = UriUtils.encode(values[i].toString(), StandardCharsets.UTF_8.toString());
+ }
+ return internalURI.buildFromEncoded(encoded);
+ }
+
+ @Override
+ public Map<String, String> getURIKeys() {
+ return this.getURIKeys(this.build().toString());
+ }
+
+ protected Map<String, String> getURIKeys(String uri) {
+ UriParser parser;
+ if (this.type != null) {
+ if (!("".equals(this.getTemplate(type)))) {
+ parser = new UriParserSpringImpl(this.getTemplate(type));
+ } else {
+ return new HashMap<>();
+ }
+ } else {
+ parser = new UriParserSpringImpl(this.getTemplate(pluralType));
+ }
+
+
+ return parser.parse(uri);
+ }
+
+ @Override
+ public SimpleUri clone() {
+ if (this.type != null) {
+ return new SimpleUri(this.type, this.internalURI.clone(), values);
+ } else {
+ return new SimpleUri(this.pluralType, this.internalURI.clone(), values);
+ }
+ }
+
+ @Override
+ public GraphInventoryObjectType getObjectType() {
+ return this.type;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof GraphInventoryUri) {
+ return this.build().equals(((GraphInventoryUri) o).build());
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(this.build()).toHashCode();
+ }
+
+
+ @Override
+ public SimpleUri depth(Depth depth) {
+ this.internalURI.replaceQueryParam("depth", depth.toString());
+ return this;
+ }
+
+ @Override
+ public SimpleUri nodesOnly(boolean nodesOnly) {
+ if (nodesOnly) {
+ this.internalURI.replaceQueryParam("nodes-only", "");
+ }
+ return this;
+ }
+
+ @Override
+ public SimpleUri format(Format format) {
+ this.internalURI.replaceQueryParam("format", format);
+ return this;
+ }
+
+ public void validateValuesSize(String template, Object... values) {
+ UriParser parser = new UriParserSpringImpl(template);
+ Set<String> variables = parser.getVariables();
+ if (variables.size() != values.length) {
+ throw new IncorrectNumberOfUriKeys(String.format("Expected %s variables: %s", variables.size(), variables));
+ }
+ }
+
+ protected String getTemplate(GraphInventoryObjectType type) {
+ return type.uriTemplate();
+ }
+
+ protected String getTemplate(GraphInventoryObjectPlurals type) {
+ return type.uriTemplate();
+ }
+
+ private void writeObject(ObjectOutputStream oos) throws IOException {
+ oos.defaultWriteObject();
+ oos.writeUTF(this.internalURI.toTemplate());
+ }
+
+ private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
+ ois.defaultReadObject();
+ String uri = ois.readUTF();
+ this.setInternalURI(UriBuilder.fromUri(uri));
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParser.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParser.java
index 03d83ebfb6..00000268a7 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParser.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParser.java
@@ -24,6 +24,7 @@ import java.util.Map;
import java.util.Set;
public interface UriParser {
- public Set<String> getVariables();
- public Map<String, String> parse(final String uri);
+ public Set<String> getVariables();
+
+ public Map<String, String> parse(final String uri);
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java
index b4cf8eb949..14a46c243b 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java
@@ -19,6 +19,7 @@
*/
package org.onap.so.client.graphinventory.entities.uri.parsers;
+
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.LinkedHashMap;
@@ -26,39 +27,38 @@ import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-
import org.springframework.web.util.UriTemplate;
import org.springframework.web.util.UriUtils;
public class UriParserSpringImpl implements UriParser {
- private final UriTemplate uriTemplate;
+ private final UriTemplate uriTemplate;
+
+ public UriParserSpringImpl(final String template) {
+ this.uriTemplate = new UriTemplate(template);
+ }
- public UriParserSpringImpl(final String template) {
- this.uriTemplate = new UriTemplate(template);
- }
+ @Override
+ public Map<String, String> parse(final String uri) {
+ final boolean match = this.uriTemplate.matches(uri);
+ if (!match) {
+ return new LinkedHashMap<>();
+ }
+ return Collections.unmodifiableMap(decodeParams(this.uriTemplate.match(uri)));
+ }
- @Override
- public Map<String, String> parse(final String uri) {
- final boolean match = this.uriTemplate.matches(uri);
- if (!match) {
- return new LinkedHashMap<>();
+ @Override
+ public Set<String> getVariables() {
+ return Collections.unmodifiableSet(new LinkedHashSet<String>(this.uriTemplate.getVariableNames()));
}
- return Collections.unmodifiableMap(decodeParams(this.uriTemplate.match(uri)));
- }
- @Override
- public Set<String> getVariables() {
- return Collections.unmodifiableSet(new LinkedHashSet<String>(this.uriTemplate.getVariableNames()));
- }
-
- protected Map<String, String> decodeParams(Map<String, String> map) {
- final Map<String, String> result = new LinkedHashMap<>();
-
- for (Entry<String, String> entry : map.entrySet()) {
- result.put(entry.getKey(), UriUtils.decode(entry.getValue(), "UTF-8"));
- }
-
- return result;
- }
+ protected Map<String, String> decodeParams(Map<String, String> map) {
+ final Map<String, String> result = new LinkedHashMap<>();
+
+ for (Entry<String, String> entry : map.entrySet()) {
+ result.put(entry.getKey(), UriUtils.decode(entry.getValue(), "UTF-8"));
+ }
+
+ return result;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/BulkProcessFailed.java b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/BulkProcessFailed.java
index 0c973a8457..d69e83435b 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/BulkProcessFailed.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/BulkProcessFailed.java
@@ -22,7 +22,7 @@ package org.onap.so.client.graphinventory.exceptions;
public class BulkProcessFailed extends Exception {
- public BulkProcessFailed(String message) {
- super(message);
- }
+ public BulkProcessFailed(String message) {
+ super(message);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryPatchDepthExceededException.java b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryPatchDepthExceededException.java
index 07af13049c..fe5f159291 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryPatchDepthExceededException.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryPatchDepthExceededException.java
@@ -22,10 +22,10 @@ package org.onap.so.client.graphinventory.exceptions;
public class GraphInventoryPatchDepthExceededException extends RuntimeException {
- private static final long serialVersionUID = -3740429832086738907L;
-
-
- public GraphInventoryPatchDepthExceededException(String payload) {
- super("Object exceeds allowed depth for update action: " + payload);
- }
+ private static final long serialVersionUID = -3740429832086738907L;
+
+
+ public GraphInventoryPatchDepthExceededException(String payload) {
+ super("Object exceeds allowed depth for update action: " + payload);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryPayloadException.java b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryPayloadException.java
index 24a6e5ccf9..45ebf9ee46 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryPayloadException.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryPayloadException.java
@@ -22,19 +22,19 @@ package org.onap.so.client.graphinventory.exceptions;
public class GraphInventoryPayloadException extends Exception {
- private static final long serialVersionUID = -5712783905947711065L;
-
- public GraphInventoryPayloadException(Throwable t) {
- super(t);
- }
-
- public GraphInventoryPayloadException(String s, Throwable t) {
- super(s, t);
- }
-
- public GraphInventoryPayloadException(String s) {
- super(s);
- }
-
+ private static final long serialVersionUID = -5712783905947711065L;
+
+ public GraphInventoryPayloadException(Throwable t) {
+ super(t);
+ }
+
+ public GraphInventoryPayloadException(String s, Throwable t) {
+ super(s, t);
+ }
+
+ public GraphInventoryPayloadException(String s) {
+ super(s);
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryUriComputationException.java b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryUriComputationException.java
index 51747d495a..380bce7165 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryUriComputationException.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryUriComputationException.java
@@ -22,13 +22,13 @@ package org.onap.so.client.graphinventory.exceptions;
public class GraphInventoryUriComputationException extends RuntimeException {
- private static final long serialVersionUID = 5187931752227522034L;
+ private static final long serialVersionUID = 5187931752227522034L;
- public GraphInventoryUriComputationException(String s) {
- super(s);
- }
-
- public GraphInventoryUriComputationException(Throwable t) {
- super(t);
- }
+ public GraphInventoryUriComputationException(String s) {
+ super(s);
+ }
+
+ public GraphInventoryUriComputationException(Throwable t) {
+ super(t);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryUriNotFoundException.java b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryUriNotFoundException.java
index d2f47a5b00..6637c89402 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryUriNotFoundException.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/GraphInventoryUriNotFoundException.java
@@ -21,9 +21,9 @@
package org.onap.so.client.graphinventory.exceptions;
public class GraphInventoryUriNotFoundException extends Exception {
- private static final long serialVersionUID = 2789643165122257833L;
+ private static final long serialVersionUID = 2789643165122257833L;
- public GraphInventoryUriNotFoundException(String message) {
- super(message);
- }
+ public GraphInventoryUriNotFoundException(String message) {
+ super(message);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/IncorrectNumberOfUriKeys.java b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/IncorrectNumberOfUriKeys.java
index 121708fc46..ede8e481b2 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/IncorrectNumberOfUriKeys.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/IncorrectNumberOfUriKeys.java
@@ -22,10 +22,10 @@ package org.onap.so.client.graphinventory.exceptions;
public class IncorrectNumberOfUriKeys extends RuntimeException {
- private static final long serialVersionUID = 2189285428827817518L;
-
- public IncorrectNumberOfUriKeys(String message) {
- super(message);
- }
+ private static final long serialVersionUID = 2189285428827817518L;
+
+ public IncorrectNumberOfUriKeys(String message) {
+ super(message);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/GRMAction.java b/common/src/main/java/org/onap/so/client/grm/GRMAction.java
index 376c736037..4236c04741 100644
--- a/common/src/main/java/org/onap/so/client/grm/GRMAction.java
+++ b/common/src/main/java/org/onap/so/client/grm/GRMAction.java
@@ -21,17 +21,16 @@
package org.onap.so.client.grm;
public enum GRMAction {
-
- FIND_RUNNING("findRunning"),
- ADD("add");
- private final String action;
+ FIND_RUNNING("findRunning"), ADD("add");
- GRMAction(String action) {
- this.action = action;
- }
+ private final String action;
- public String getAction() {
- return action;
- }
+ GRMAction(String action) {
+ this.action = action;
+ }
+
+ public String getAction() {
+ return action;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/GRMClient.java b/common/src/main/java/org/onap/so/client/grm/GRMClient.java
index 653e1cc7b3..4c221d1a8e 100644
--- a/common/src/main/java/org/onap/so/client/grm/GRMClient.java
+++ b/common/src/main/java/org/onap/so/client/grm/GRMClient.java
@@ -29,55 +29,52 @@ import org.onap.so.client.grm.exceptions.GRMClientCallFailed;
public class GRMClient {
- public String findRunningServicesAsString(String name, int majorVersion, String env) throws Exception {
-
- ServiceEndPointLookupRequest request = buildServiceEndPointlookupRequest(name, majorVersion, env);
- try {
- GRMRestInvoker invoker = this.getInvoker(GRMAction.FIND_RUNNING);
- return invoker.post(request, String.class);
- }
- catch(Exception e) {
- throw new GRMClientCallFailed("Call to GRM findRunning failed: " + e.getMessage(), e);
- }
- }
-
- public ServiceEndPointList findRunningServices(String name, int majorVersion, String env) throws Exception {
-
- ServiceEndPointLookupRequest request = buildServiceEndPointlookupRequest(name, majorVersion, env);
- try {
- GRMRestInvoker invoker = this.getInvoker(GRMAction.FIND_RUNNING);
- return invoker.post(request, ServiceEndPointList.class);
- }
- catch(Exception e) {
- throw new GRMClientCallFailed("Call to GRM findRunning failed: " + e.getMessage(), e);
- }
- }
-
- public ServiceEndPointLookupRequest buildServiceEndPointlookupRequest(String name, int majorVersion, String env) {
- VersionLookup version = new VersionLookup();
- version.setMajor(majorVersion);
-
- ServiceEndPointLookup endpoint = new ServiceEndPointLookup();
- endpoint.setName(name);
- endpoint.setVersion(version);
-
- ServiceEndPointLookupRequest request = new ServiceEndPointLookupRequest();
- request.setServiceEndPoint(endpoint);
- request.setEnv(env);
- return request;
- }
-
- public void addServiceEndPoint(ServiceEndPointRequest request) throws Exception {
- try {
- GRMRestInvoker invoker = this.getInvoker(GRMAction.ADD);
- invoker.post(request);
- }
- catch(Exception e) {
- throw new GRMClientCallFailed("Call to GRM addServiceEndPoint failed: " + e.getMessage(), e);
- }
- }
-
- protected GRMRestInvoker getInvoker(GRMAction action) {
- return new GRMRestInvoker(action);
- }
+ public String findRunningServicesAsString(String name, int majorVersion, String env) throws Exception {
+
+ ServiceEndPointLookupRequest request = buildServiceEndPointlookupRequest(name, majorVersion, env);
+ try {
+ GRMRestInvoker invoker = this.getInvoker(GRMAction.FIND_RUNNING);
+ return invoker.post(request, String.class);
+ } catch (Exception e) {
+ throw new GRMClientCallFailed("Call to GRM findRunning failed: " + e.getMessage(), e);
+ }
+ }
+
+ public ServiceEndPointList findRunningServices(String name, int majorVersion, String env) throws Exception {
+
+ ServiceEndPointLookupRequest request = buildServiceEndPointlookupRequest(name, majorVersion, env);
+ try {
+ GRMRestInvoker invoker = this.getInvoker(GRMAction.FIND_RUNNING);
+ return invoker.post(request, ServiceEndPointList.class);
+ } catch (Exception e) {
+ throw new GRMClientCallFailed("Call to GRM findRunning failed: " + e.getMessage(), e);
+ }
+ }
+
+ public ServiceEndPointLookupRequest buildServiceEndPointlookupRequest(String name, int majorVersion, String env) {
+ VersionLookup version = new VersionLookup();
+ version.setMajor(majorVersion);
+
+ ServiceEndPointLookup endpoint = new ServiceEndPointLookup();
+ endpoint.setName(name);
+ endpoint.setVersion(version);
+
+ ServiceEndPointLookupRequest request = new ServiceEndPointLookupRequest();
+ request.setServiceEndPoint(endpoint);
+ request.setEnv(env);
+ return request;
+ }
+
+ public void addServiceEndPoint(ServiceEndPointRequest request) throws Exception {
+ try {
+ GRMRestInvoker invoker = this.getInvoker(GRMAction.ADD);
+ invoker.post(request);
+ } catch (Exception e) {
+ throw new GRMClientCallFailed("Call to GRM addServiceEndPoint failed: " + e.getMessage(), e);
+ }
+ }
+
+ protected GRMRestInvoker getInvoker(GRMAction action) {
+ return new GRMRestInvoker(action);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/GRMProperties.java b/common/src/main/java/org/onap/so/client/grm/GRMProperties.java
index 1206896bf9..615f93f921 100644
--- a/common/src/main/java/org/onap/so/client/grm/GRMProperties.java
+++ b/common/src/main/java/org/onap/so/client/grm/GRMProperties.java
@@ -23,8 +23,11 @@ package org.onap.so.client.grm;
import org.onap.so.client.RestProperties;
public interface GRMProperties extends RestProperties {
- public String getDefaultVersion();
- public String getAuth();
- public String getKey();
- public String getContentType();
+ public String getDefaultVersion();
+
+ public String getAuth();
+
+ public String getKey();
+
+ public String getContentType();
}
diff --git a/common/src/main/java/org/onap/so/client/grm/GRMPropertiesLoader.java b/common/src/main/java/org/onap/so/client/grm/GRMPropertiesLoader.java
index 485b9b0d15..2e8a6492ec 100644
--- a/common/src/main/java/org/onap/so/client/grm/GRMPropertiesLoader.java
+++ b/common/src/main/java/org/onap/so/client/grm/GRMPropertiesLoader.java
@@ -25,24 +25,25 @@ import java.util.ServiceLoader;
public class GRMPropertiesLoader {
- private final ServiceLoader<GRMProperties> services;
- private GRMPropertiesLoader() {
- services = ServiceLoader.load(GRMProperties.class);
- }
-
- private static class Helper {
- private static final GRMPropertiesLoader INSTANCE = new GRMPropertiesLoader();
- }
-
- public static GRMPropertiesLoader getInstance() {
- return Helper.INSTANCE;
- }
-
- public GRMProperties getImpl() {
- Iterator<GRMProperties> propertyImpls = services.iterator();
- while (propertyImpls.hasNext()) {
- return propertyImpls.next();
- }
- return null;
- }
+ private final ServiceLoader<GRMProperties> services;
+
+ private GRMPropertiesLoader() {
+ services = ServiceLoader.load(GRMProperties.class);
+ }
+
+ private static class Helper {
+ private static final GRMPropertiesLoader INSTANCE = new GRMPropertiesLoader();
+ }
+
+ public static GRMPropertiesLoader getInstance() {
+ return Helper.INSTANCE;
+ }
+
+ public GRMProperties getImpl() {
+ Iterator<GRMProperties> propertyImpls = services.iterator();
+ while (propertyImpls.hasNext()) {
+ return propertyImpls.next();
+ }
+ return null;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/GRMRestClient.java b/common/src/main/java/org/onap/so/client/grm/GRMRestClient.java
index 0bb55e627a..fa155de6a2 100644
--- a/common/src/main/java/org/onap/so/client/grm/GRMRestClient.java
+++ b/common/src/main/java/org/onap/so/client/grm/GRMRestClient.java
@@ -25,33 +25,32 @@ import java.net.URI;
import java.util.Base64;
import java.util.Map;
import java.util.Optional;
-
import org.onap.so.client.RestClient;
import org.onap.so.client.RestProperties;
import org.onap.so.utils.TargetEntity;
public class GRMRestClient extends RestClient {
- private final GRMProperties properties;
-
- public GRMRestClient(GRMProperties props, URI path) {
- super(props, Optional.of(path));
- this.properties = props;
- }
+ private final GRMProperties properties;
+
+ public GRMRestClient(GRMProperties props, URI path) {
+ super(props, Optional.of(path));
+ this.properties = props;
+ }
@Override
- public TargetEntity getTargetEntity(){
+ public TargetEntity getTargetEntity() {
return TargetEntity.GRM;
}
- @Override
- protected void initializeHeaderMap(Map<String, String> headerMap) {
- String auth = properties.getAuth();
- String key = properties.getKey();
+ @Override
+ protected void initializeHeaderMap(Map<String, String> headerMap) {
+ String auth = properties.getAuth();
+ String key = properties.getKey();
- if (auth != null && !auth.isEmpty() && key != null && !key.isEmpty()) {
- addBasicAuthHeader(auth, key);
- }
- }
+ if (auth != null && !auth.isEmpty() && key != null && !key.isEmpty()) {
+ addBasicAuthHeader(auth, key);
+ }
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/GRMRestInvoker.java b/common/src/main/java/org/onap/so/client/grm/GRMRestInvoker.java
index 0c95a66979..609a206341 100644
--- a/common/src/main/java/org/onap/so/client/grm/GRMRestInvoker.java
+++ b/common/src/main/java/org/onap/so/client/grm/GRMRestInvoker.java
@@ -21,40 +21,35 @@
package org.onap.so.client.grm;
import java.net.URI;
-
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.client.RestClient;
public class GRMRestInvoker {
-
- private final RestClient client;
- private final GRMProperties properties;
-
- public GRMRestInvoker(GRMAction action) {
- GRMProperties props = GRMPropertiesLoader.getInstance().getImpl();
- this.properties = props;
- this.client = new GRMRestClient(properties, this.createURI(action));
- }
-
- private URI createURI(GRMAction action) {
- return UriBuilder.fromUri("/GRMLWPService")
- .path(this.properties.getDefaultVersion())
- .path("serviceEndPoint")
- .path(action.getAction())
- .build();
- }
-
- private RestClient getClient() {
- return this.client;
- }
-
- public void post(Object obj) {
- getClient().post(obj);
- }
-
- public <T> T post(Object obj, Class<T> resultClass) {
- return getClient().post(obj, resultClass);
- }
-
+
+ private final RestClient client;
+ private final GRMProperties properties;
+
+ public GRMRestInvoker(GRMAction action) {
+ GRMProperties props = GRMPropertiesLoader.getInstance().getImpl();
+ this.properties = props;
+ this.client = new GRMRestClient(properties, this.createURI(action));
+ }
+
+ private URI createURI(GRMAction action) {
+ return UriBuilder.fromUri("/GRMLWPService").path(this.properties.getDefaultVersion()).path("serviceEndPoint")
+ .path(action.getAction()).build();
+ }
+
+ private RestClient getClient() {
+ return this.client;
+ }
+
+ public void post(Object obj) {
+ getClient().post(obj);
+ }
+
+ public <T> T post(Object obj, Class<T> resultClass) {
+ return getClient().post(obj, resultClass);
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/client/grm/beans/OperationalInfo.java b/common/src/main/java/org/onap/so/client/grm/beans/OperationalInfo.java
index 85e15f597c..a1f4d6e639 100644
--- a/common/src/main/java/org/onap/so/client/grm/beans/OperationalInfo.java
+++ b/common/src/main/java/org/onap/so/client/grm/beans/OperationalInfo.java
@@ -21,7 +21,6 @@
package org.onap.so.client.grm.beans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -29,60 +28,60 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
-@JsonPropertyOrder({ "createdBy", "updatedBy", "createdTimestamp", "updatedTimestamp" })
-public class OperationalInfo implements Serializable{
+@JsonPropertyOrder({"createdBy", "updatedBy", "createdTimestamp", "updatedTimestamp"})
+public class OperationalInfo implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -7213334079745439793L;
- @JsonProperty("createdBy")
- private String createdBy;
- @JsonProperty("updatedBy")
- private String updatedBy;
- @JsonProperty("createdTimestamp")
- private String createdTimestamp;
- @JsonProperty("updatedTimestamp")
- private String updatedTimestamp;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -7213334079745439793L;
+ @JsonProperty("createdBy")
+ private String createdBy;
+ @JsonProperty("updatedBy")
+ private String updatedBy;
+ @JsonProperty("createdTimestamp")
+ private String createdTimestamp;
+ @JsonProperty("updatedTimestamp")
+ private String updatedTimestamp;
- @JsonProperty("createdBy")
- public String getCreatedBy() {
- return createdBy;
- }
+ @JsonProperty("createdBy")
+ public String getCreatedBy() {
+ return createdBy;
+ }
- @JsonProperty("createdBy")
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
+ @JsonProperty("createdBy")
+ public void setCreatedBy(String createdBy) {
+ this.createdBy = createdBy;
+ }
- @JsonProperty("updatedBy")
- public String getUpdatedBy() {
- return updatedBy;
- }
+ @JsonProperty("updatedBy")
+ public String getUpdatedBy() {
+ return updatedBy;
+ }
- @JsonProperty("updatedBy")
- public void setUpdatedBy(String updatedBy) {
- this.updatedBy = updatedBy;
- }
+ @JsonProperty("updatedBy")
+ public void setUpdatedBy(String updatedBy) {
+ this.updatedBy = updatedBy;
+ }
- @JsonProperty("createdTimestamp")
- public String getCreatedTimestamp() {
- return createdTimestamp;
- }
+ @JsonProperty("createdTimestamp")
+ public String getCreatedTimestamp() {
+ return createdTimestamp;
+ }
- @JsonProperty("createdTimestamp")
- public void setCreatedTimestamp(String createdTimestamp) {
- this.createdTimestamp = createdTimestamp;
- }
+ @JsonProperty("createdTimestamp")
+ public void setCreatedTimestamp(String createdTimestamp) {
+ this.createdTimestamp = createdTimestamp;
+ }
- @JsonProperty("updatedTimestamp")
- public String getUpdatedTimestamp() {
- return updatedTimestamp;
- }
+ @JsonProperty("updatedTimestamp")
+ public String getUpdatedTimestamp() {
+ return updatedTimestamp;
+ }
- @JsonProperty("updatedTimestamp")
- public void setUpdatedTimestamp(String updatedTimestamp) {
- this.updatedTimestamp = updatedTimestamp;
- }
+ @JsonProperty("updatedTimestamp")
+ public void setUpdatedTimestamp(String updatedTimestamp) {
+ this.updatedTimestamp = updatedTimestamp;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/beans/Property.java b/common/src/main/java/org/onap/so/client/grm/beans/Property.java
index 705db95222..dcba6ba10b 100644
--- a/common/src/main/java/org/onap/so/client/grm/beans/Property.java
+++ b/common/src/main/java/org/onap/so/client/grm/beans/Property.java
@@ -21,7 +21,6 @@
package org.onap.so.client.grm.beans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -29,36 +28,36 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
-@JsonPropertyOrder({ "name", "value" })
-public class Property implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = -6060749559638446881L;
- @JsonProperty("name")
- private String name;
- @JsonProperty("value")
- private String value;
-
- @JsonProperty("name")
- public String getName() {
- return name;
- }
-
- @JsonProperty("name")
- public void setName(String name) {
- this.name = name;
- }
-
- @JsonProperty("value")
- public String getValue() {
- return value;
- }
-
- @JsonProperty("value")
- public void setValue(String value) {
- this.value = value;
- }
+@JsonPropertyOrder({"name", "value"})
+public class Property implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -6060749559638446881L;
+ @JsonProperty("name")
+ private String name;
+ @JsonProperty("value")
+ private String value;
+
+ @JsonProperty("name")
+ public String getName() {
+ return name;
+ }
+
+ @JsonProperty("name")
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @JsonProperty("value")
+ public String getValue() {
+ return value;
+ }
+
+ @JsonProperty("value")
+ public void setValue(String value) {
+ this.value = value;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPoint.java b/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPoint.java
index e739f00c9a..a7260943ee 100644
--- a/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPoint.java
+++ b/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPoint.java
@@ -22,7 +22,6 @@ package org.onap.so.client.grm.beans;
import java.io.Serializable;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -32,216 +31,216 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "serviceEndPoint")
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
-@JsonPropertyOrder({ "name", "version", "hostAddress", "listenPort", "latitude", "longitude", "registrationTime",
- "expirationTime", "contextPath", "routeOffer", "statusInfo", "eventStatusInfo", "validatorStatusInfo",
- "operationalInfo", "protocol", "properties", "disableType" })
+@JsonPropertyOrder({"name", "version", "hostAddress", "listenPort", "latitude", "longitude", "registrationTime",
+ "expirationTime", "contextPath", "routeOffer", "statusInfo", "eventStatusInfo", "validatorStatusInfo",
+ "operationalInfo", "protocol", "properties", "disableType"})
public class ServiceEndPoint implements Serializable {
- private static final long serialVersionUID = -1594441352549128491L;
-
- @JsonProperty("name")
- private String name;
- @JsonProperty("version")
- private Version version;
- @JsonProperty("hostAddress")
- private String hostAddress;
- @JsonProperty("listenPort")
- private String listenPort;
- @JsonProperty("latitude")
- private String latitude;
- @JsonProperty("longitude")
- private String longitude;
- @JsonProperty("registrationTime")
- private String registrationTime;
- @JsonProperty("expirationTime")
- private String expirationTime;
- @JsonProperty("contextPath")
- private String contextPath;
- @JsonProperty("routeOffer")
- private String routeOffer;
- @JsonProperty("statusInfo")
- private Status statusInfo;
- @JsonProperty("eventStatusInfo")
- private Status eventStatusInfo;
- @JsonProperty("validatorStatusInfo")
- private Status validatorStatusInfo;
- @JsonProperty("operationalInfo")
- private OperationalInfo operationalInfo;
- @JsonProperty("protocol")
- private String protocol;
- @JsonProperty("properties")
- private List<Property> properties = null;
- @JsonProperty("disableType")
- private List<Object> disableType = null;
-
- @JsonProperty("name")
- public String getName() {
- return name;
- }
-
- @JsonProperty("name")
- public void setName(String name) {
- this.name = name;
- }
-
- @JsonProperty("version")
- public Version getVersion() {
- return version;
- }
-
- @JsonProperty("version")
- public void setVersion(Version version) {
- this.version = version;
- }
-
- @JsonProperty("hostAddress")
- public String getHostAddress() {
- return hostAddress;
- }
-
- @JsonProperty("hostAddress")
- public void setHostAddress(String hostAddress) {
- this.hostAddress = hostAddress;
- }
-
- @JsonProperty("listenPort")
- public String getListenPort() {
- return listenPort;
- }
-
- @JsonProperty("listenPort")
- public void setListenPort(String listenPort) {
- this.listenPort = listenPort;
- }
-
- @JsonProperty("latitude")
- public String getLatitude() {
- return latitude;
- }
-
- @JsonProperty("latitude")
- public void setLatitude(String latitude) {
- this.latitude = latitude;
- }
-
- @JsonProperty("longitude")
- public String getLongitude() {
- return longitude;
- }
-
- @JsonProperty("longitude")
- public void setLongitude(String longitude) {
- this.longitude = longitude;
- }
-
- @JsonProperty("registrationTime")
- public String getRegistrationTime() {
- return registrationTime;
- }
-
- @JsonProperty("registrationTime")
- public void setRegistrationTime(String registrationTime) {
- this.registrationTime = registrationTime;
- }
-
- @JsonProperty("expirationTime")
- public String getExpirationTime() {
- return expirationTime;
- }
-
- @JsonProperty("expirationTime")
- public void setExpirationTime(String expirationTime) {
- this.expirationTime = expirationTime;
- }
-
- @JsonProperty("contextPath")
- public String getContextPath() {
- return contextPath;
- }
-
- @JsonProperty("contextPath")
- public void setContextPath(String contextPath) {
- this.contextPath = contextPath;
- }
-
- @JsonProperty("routeOffer")
- public String getRouteOffer() {
- return routeOffer;
- }
-
- @JsonProperty("routeOffer")
- public void setRouteOffer(String routeOffer) {
- this.routeOffer = routeOffer;
- }
-
- @JsonProperty("statusInfo")
- public Status getStatusInfo() {
- return statusInfo;
- }
-
- @JsonProperty("statusInfo")
- public void setStatusInfo(Status statusInfo) {
- this.statusInfo = statusInfo;
- }
-
- @JsonProperty("eventStatusInfo")
- public Status getEventStatusInfo() {
- return eventStatusInfo;
- }
-
- @JsonProperty("eventStatusInfo")
- public void setEventStatusInfo(Status eventStatusInfo) {
- this.eventStatusInfo = eventStatusInfo;
- }
-
- @JsonProperty("validatorStatusInfo")
- public Status getValidatorStatusInfo() {
- return validatorStatusInfo;
- }
-
- @JsonProperty("validatorStatusInfo")
- public void setValidatorStatusInfo(Status validatorStatusInfo) {
- this.validatorStatusInfo = validatorStatusInfo;
- }
-
- @JsonProperty("operationalInfo")
- public OperationalInfo getOperationalInfo() {
- return operationalInfo;
- }
-
- @JsonProperty("operationalInfo")
- public void setOperationalInfo(OperationalInfo operationalInfo) {
- this.operationalInfo = operationalInfo;
- }
-
- @JsonProperty("protocol")
- public String getProtocol() {
- return protocol;
- }
-
- @JsonProperty("protocol")
- public void setProtocol(String protocol) {
- this.protocol = protocol;
- }
-
- @JsonProperty("properties")
- public List<Property> getProperties() {
- return properties;
- }
-
- @JsonProperty("properties")
- public void setProperties(List<Property> properties) {
- this.properties = properties;
- }
-
- @JsonProperty("disableType")
- public List<Object> getDisableType() {
- return disableType;
- }
-
- @JsonProperty("disableType")
- public void setDisableType(List<Object> disableType) {
- this.disableType = disableType;
- }
+ private static final long serialVersionUID = -1594441352549128491L;
+
+ @JsonProperty("name")
+ private String name;
+ @JsonProperty("version")
+ private Version version;
+ @JsonProperty("hostAddress")
+ private String hostAddress;
+ @JsonProperty("listenPort")
+ private String listenPort;
+ @JsonProperty("latitude")
+ private String latitude;
+ @JsonProperty("longitude")
+ private String longitude;
+ @JsonProperty("registrationTime")
+ private String registrationTime;
+ @JsonProperty("expirationTime")
+ private String expirationTime;
+ @JsonProperty("contextPath")
+ private String contextPath;
+ @JsonProperty("routeOffer")
+ private String routeOffer;
+ @JsonProperty("statusInfo")
+ private Status statusInfo;
+ @JsonProperty("eventStatusInfo")
+ private Status eventStatusInfo;
+ @JsonProperty("validatorStatusInfo")
+ private Status validatorStatusInfo;
+ @JsonProperty("operationalInfo")
+ private OperationalInfo operationalInfo;
+ @JsonProperty("protocol")
+ private String protocol;
+ @JsonProperty("properties")
+ private List<Property> properties = null;
+ @JsonProperty("disableType")
+ private List<Object> disableType = null;
+
+ @JsonProperty("name")
+ public String getName() {
+ return name;
+ }
+
+ @JsonProperty("name")
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @JsonProperty("version")
+ public Version getVersion() {
+ return version;
+ }
+
+ @JsonProperty("version")
+ public void setVersion(Version version) {
+ this.version = version;
+ }
+
+ @JsonProperty("hostAddress")
+ public String getHostAddress() {
+ return hostAddress;
+ }
+
+ @JsonProperty("hostAddress")
+ public void setHostAddress(String hostAddress) {
+ this.hostAddress = hostAddress;
+ }
+
+ @JsonProperty("listenPort")
+ public String getListenPort() {
+ return listenPort;
+ }
+
+ @JsonProperty("listenPort")
+ public void setListenPort(String listenPort) {
+ this.listenPort = listenPort;
+ }
+
+ @JsonProperty("latitude")
+ public String getLatitude() {
+ return latitude;
+ }
+
+ @JsonProperty("latitude")
+ public void setLatitude(String latitude) {
+ this.latitude = latitude;
+ }
+
+ @JsonProperty("longitude")
+ public String getLongitude() {
+ return longitude;
+ }
+
+ @JsonProperty("longitude")
+ public void setLongitude(String longitude) {
+ this.longitude = longitude;
+ }
+
+ @JsonProperty("registrationTime")
+ public String getRegistrationTime() {
+ return registrationTime;
+ }
+
+ @JsonProperty("registrationTime")
+ public void setRegistrationTime(String registrationTime) {
+ this.registrationTime = registrationTime;
+ }
+
+ @JsonProperty("expirationTime")
+ public String getExpirationTime() {
+ return expirationTime;
+ }
+
+ @JsonProperty("expirationTime")
+ public void setExpirationTime(String expirationTime) {
+ this.expirationTime = expirationTime;
+ }
+
+ @JsonProperty("contextPath")
+ public String getContextPath() {
+ return contextPath;
+ }
+
+ @JsonProperty("contextPath")
+ public void setContextPath(String contextPath) {
+ this.contextPath = contextPath;
+ }
+
+ @JsonProperty("routeOffer")
+ public String getRouteOffer() {
+ return routeOffer;
+ }
+
+ @JsonProperty("routeOffer")
+ public void setRouteOffer(String routeOffer) {
+ this.routeOffer = routeOffer;
+ }
+
+ @JsonProperty("statusInfo")
+ public Status getStatusInfo() {
+ return statusInfo;
+ }
+
+ @JsonProperty("statusInfo")
+ public void setStatusInfo(Status statusInfo) {
+ this.statusInfo = statusInfo;
+ }
+
+ @JsonProperty("eventStatusInfo")
+ public Status getEventStatusInfo() {
+ return eventStatusInfo;
+ }
+
+ @JsonProperty("eventStatusInfo")
+ public void setEventStatusInfo(Status eventStatusInfo) {
+ this.eventStatusInfo = eventStatusInfo;
+ }
+
+ @JsonProperty("validatorStatusInfo")
+ public Status getValidatorStatusInfo() {
+ return validatorStatusInfo;
+ }
+
+ @JsonProperty("validatorStatusInfo")
+ public void setValidatorStatusInfo(Status validatorStatusInfo) {
+ this.validatorStatusInfo = validatorStatusInfo;
+ }
+
+ @JsonProperty("operationalInfo")
+ public OperationalInfo getOperationalInfo() {
+ return operationalInfo;
+ }
+
+ @JsonProperty("operationalInfo")
+ public void setOperationalInfo(OperationalInfo operationalInfo) {
+ this.operationalInfo = operationalInfo;
+ }
+
+ @JsonProperty("protocol")
+ public String getProtocol() {
+ return protocol;
+ }
+
+ @JsonProperty("protocol")
+ public void setProtocol(String protocol) {
+ this.protocol = protocol;
+ }
+
+ @JsonProperty("properties")
+ public List<Property> getProperties() {
+ return properties;
+ }
+
+ @JsonProperty("properties")
+ public void setProperties(List<Property> properties) {
+ this.properties = properties;
+ }
+
+ @JsonProperty("disableType")
+ public List<Object> getDisableType() {
+ return disableType;
+ }
+
+ @JsonProperty("disableType")
+ public void setDisableType(List<Object> disableType) {
+ this.disableType = disableType;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointList.java b/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointList.java
index 2b7a81d590..b87819d528 100644
--- a/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointList.java
+++ b/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointList.java
@@ -21,22 +21,21 @@
package org.onap.so.client.grm.beans;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
-//@JsonIgnoreProperties(ignoreUnknown = true)
+// @JsonIgnoreProperties(ignoreUnknown = true)
public class ServiceEndPointList {
- @JsonAlias("ServiceEndPointList")
- private List<ServiceEndPoint> serviceEndPointList = null;
+ @JsonAlias("ServiceEndPointList")
+ private List<ServiceEndPoint> serviceEndPointList = null;
- public List<ServiceEndPoint> getServiceEndPointList() {
- return serviceEndPointList;
- }
+ public List<ServiceEndPoint> getServiceEndPointList() {
+ return serviceEndPointList;
+ }
- public void setServiceEndPointList(List<ServiceEndPoint> serviceEndPointList) {
- this.serviceEndPointList = serviceEndPointList;
- }
+ public void setServiceEndPointList(List<ServiceEndPoint> serviceEndPointList) {
+ this.serviceEndPointList = serviceEndPointList;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointLookup.java b/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointLookup.java
index cab10e64f4..200a2fce64 100644
--- a/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointLookup.java
+++ b/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointLookup.java
@@ -21,7 +21,6 @@
package org.onap.so.client.grm.beans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@@ -29,33 +28,33 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "serviceEndPoint")
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({ "name", "version"})
+@JsonPropertyOrder({"name", "version"})
public class ServiceEndPointLookup implements Serializable {
- private static final long serialVersionUID = 8867758152519088615L;
+ private static final long serialVersionUID = 8867758152519088615L;
- @JsonProperty("name")
- private String name;
- @JsonProperty("version")
- private VersionLookup version;
+ @JsonProperty("name")
+ private String name;
+ @JsonProperty("version")
+ private VersionLookup version;
- @JsonProperty("name")
- public String getName() {
- return name;
- }
+ @JsonProperty("name")
+ public String getName() {
+ return name;
+ }
- @JsonProperty("name")
- public void setName(String name) {
- this.name = name;
- }
+ @JsonProperty("name")
+ public void setName(String name) {
+ this.name = name;
+ }
- @JsonProperty("version")
- public VersionLookup getVersion() {
- return version;
- }
+ @JsonProperty("version")
+ public VersionLookup getVersion() {
+ return version;
+ }
- @JsonProperty("version")
- public void setVersion(VersionLookup version) {
- this.version = version;
- }
+ @JsonProperty("version")
+ public void setVersion(VersionLookup version) {
+ this.version = version;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointLookupRequest.java b/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointLookupRequest.java
index 5e886300dd..be537e4ff9 100644
--- a/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointLookupRequest.java
+++ b/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointLookupRequest.java
@@ -27,32 +27,32 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
-@JsonPropertyOrder({ "serviceEndPoint", "env" })
+@JsonPropertyOrder({"serviceEndPoint", "env"})
public class ServiceEndPointLookupRequest {
- @JsonProperty("serviceEndPoint")
- private ServiceEndPointLookup serviceEndPoint;
- @JsonProperty("env")
- private String env;
-
- @JsonProperty("serviceEndPoint")
- public ServiceEndPointLookup getServiceEndPoint() {
- return serviceEndPoint;
- }
-
- @JsonProperty("serviceEndPoint")
- public void setServiceEndPoint(ServiceEndPointLookup serviceEndPoint) {
- this.serviceEndPoint = serviceEndPoint;
- }
-
- @JsonProperty("env")
- public String getEnv() {
- return env;
- }
-
- @JsonProperty("env")
- public void setEnv(String env) {
- this.env = env;
- }
+ @JsonProperty("serviceEndPoint")
+ private ServiceEndPointLookup serviceEndPoint;
+ @JsonProperty("env")
+ private String env;
+
+ @JsonProperty("serviceEndPoint")
+ public ServiceEndPointLookup getServiceEndPoint() {
+ return serviceEndPoint;
+ }
+
+ @JsonProperty("serviceEndPoint")
+ public void setServiceEndPoint(ServiceEndPointLookup serviceEndPoint) {
+ this.serviceEndPoint = serviceEndPoint;
+ }
+
+ @JsonProperty("env")
+ public String getEnv() {
+ return env;
+ }
+
+ @JsonProperty("env")
+ public void setEnv(String env) {
+ this.env = env;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointRequest.java b/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointRequest.java
index f7ea352f21..6c64be33bd 100644
--- a/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointRequest.java
+++ b/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointRequest.java
@@ -27,32 +27,32 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
-@JsonPropertyOrder({ "serviceEndPoint", "env" })
+@JsonPropertyOrder({"serviceEndPoint", "env"})
public class ServiceEndPointRequest {
- @JsonProperty("serviceEndPoint")
- private ServiceEndPoint serviceEndPoint;
- @JsonProperty("env")
- private String env;
-
- @JsonProperty("serviceEndPoint")
- public ServiceEndPoint getServiceEndPoint() {
- return serviceEndPoint;
- }
-
- @JsonProperty("serviceEndPoint")
- public void setServiceEndPoint(ServiceEndPoint serviceEndPoint) {
- this.serviceEndPoint = serviceEndPoint;
- }
-
- @JsonProperty("env")
- public String getEnv() {
- return env;
- }
-
- @JsonProperty("env")
- public void setEnv(String env) {
- this.env = env;
- }
+ @JsonProperty("serviceEndPoint")
+ private ServiceEndPoint serviceEndPoint;
+ @JsonProperty("env")
+ private String env;
+
+ @JsonProperty("serviceEndPoint")
+ public ServiceEndPoint getServiceEndPoint() {
+ return serviceEndPoint;
+ }
+
+ @JsonProperty("serviceEndPoint")
+ public void setServiceEndPoint(ServiceEndPoint serviceEndPoint) {
+ this.serviceEndPoint = serviceEndPoint;
+ }
+
+ @JsonProperty("env")
+ public String getEnv() {
+ return env;
+ }
+
+ @JsonProperty("env")
+ public void setEnv(String env) {
+ this.env = env;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/beans/Status.java b/common/src/main/java/org/onap/so/client/grm/beans/Status.java
index 8794139b67..f4b0ff583e 100644
--- a/common/src/main/java/org/onap/so/client/grm/beans/Status.java
+++ b/common/src/main/java/org/onap/so/client/grm/beans/Status.java
@@ -21,7 +21,6 @@
package org.onap.so.client.grm.beans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -29,60 +28,60 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
-@JsonPropertyOrder({ "status", "statusReasonCode", "statusReasonDescription", "statusCheckTime" })
+@JsonPropertyOrder({"status", "statusReasonCode", "statusReasonDescription", "statusCheckTime"})
public class Status implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -3555636617671062648L;
- @JsonProperty("status")
- private String status;
- @JsonProperty("statusReasonCode")
- private String statusReasonCode;
- @JsonProperty("statusReasonDescription")
- private String statusReasonDescription;
- @JsonProperty("statusCheckTime")
- private String statusCheckTime;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -3555636617671062648L;
+ @JsonProperty("status")
+ private String status;
+ @JsonProperty("statusReasonCode")
+ private String statusReasonCode;
+ @JsonProperty("statusReasonDescription")
+ private String statusReasonDescription;
+ @JsonProperty("statusCheckTime")
+ private String statusCheckTime;
- @JsonProperty("status")
- public String getStatus() {
- return status;
- }
+ @JsonProperty("status")
+ public String getStatus() {
+ return status;
+ }
- @JsonProperty("status")
- public void setStatus(String status) {
- this.status = status;
- }
+ @JsonProperty("status")
+ public void setStatus(String status) {
+ this.status = status;
+ }
- @JsonProperty("statusReasonCode")
- public String getStatusReasonCode() {
- return statusReasonCode;
- }
+ @JsonProperty("statusReasonCode")
+ public String getStatusReasonCode() {
+ return statusReasonCode;
+ }
- @JsonProperty("statusReasonCode")
- public void setStatusReasonCode(String statusReasonCode) {
- this.statusReasonCode = statusReasonCode;
- }
+ @JsonProperty("statusReasonCode")
+ public void setStatusReasonCode(String statusReasonCode) {
+ this.statusReasonCode = statusReasonCode;
+ }
- @JsonProperty("statusReasonDescription")
- public String getStatusReasonDescription() {
- return statusReasonDescription;
- }
+ @JsonProperty("statusReasonDescription")
+ public String getStatusReasonDescription() {
+ return statusReasonDescription;
+ }
- @JsonProperty("statusReasonDescription")
- public void setStatusReasonDescription(String statusReasonDescription) {
- this.statusReasonDescription = statusReasonDescription;
- }
+ @JsonProperty("statusReasonDescription")
+ public void setStatusReasonDescription(String statusReasonDescription) {
+ this.statusReasonDescription = statusReasonDescription;
+ }
- @JsonProperty("statusCheckTime")
- public String getStatusCheckTime() {
- return statusCheckTime;
- }
+ @JsonProperty("statusCheckTime")
+ public String getStatusCheckTime() {
+ return statusCheckTime;
+ }
- @JsonProperty("statusCheckTime")
- public void setStatusCheckTime(String statusCheckTime) {
- this.statusCheckTime = statusCheckTime;
- }
+ @JsonProperty("statusCheckTime")
+ public void setStatusCheckTime(String statusCheckTime) {
+ this.statusCheckTime = statusCheckTime;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/beans/Version.java b/common/src/main/java/org/onap/so/client/grm/beans/Version.java
index fd1e5803ab..fd2cceec01 100644
--- a/common/src/main/java/org/onap/so/client/grm/beans/Version.java
+++ b/common/src/main/java/org/onap/so/client/grm/beans/Version.java
@@ -21,7 +21,6 @@
package org.onap.so.client.grm.beans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -29,47 +28,47 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
-@JsonPropertyOrder({ "major", "minor", "patch" })
-public class Version implements Serializable{
+@JsonPropertyOrder({"major", "minor", "patch"})
+public class Version implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 7509573030831487410L;
- @JsonProperty("major")
- private Integer major;
- @JsonProperty("minor")
- private Integer minor;
- @JsonProperty("patch")
- private String patch;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 7509573030831487410L;
+ @JsonProperty("major")
+ private Integer major;
+ @JsonProperty("minor")
+ private Integer minor;
+ @JsonProperty("patch")
+ private String patch;
- @JsonProperty("major")
- public Integer getMajor() {
- return major;
- }
+ @JsonProperty("major")
+ public Integer getMajor() {
+ return major;
+ }
- @JsonProperty("major")
- public void setMajor(Integer major) {
- this.major = major;
- }
+ @JsonProperty("major")
+ public void setMajor(Integer major) {
+ this.major = major;
+ }
- @JsonProperty("minor")
- public Integer getMinor() {
- return minor;
- }
+ @JsonProperty("minor")
+ public Integer getMinor() {
+ return minor;
+ }
- @JsonProperty("minor")
- public void setMinor(Integer minor) {
- this.minor = minor;
- }
+ @JsonProperty("minor")
+ public void setMinor(Integer minor) {
+ this.minor = minor;
+ }
- @JsonProperty("patch")
- public String getPatch() {
- return patch;
- }
+ @JsonProperty("patch")
+ public String getPatch() {
+ return patch;
+ }
- @JsonProperty("patch")
- public void setPatch(String patch) {
- this.patch = patch;
- }
+ @JsonProperty("patch")
+ public void setPatch(String patch) {
+ this.patch = patch;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/beans/VersionLookup.java b/common/src/main/java/org/onap/so/client/grm/beans/VersionLookup.java
index 0dc86b04d6..661b91829c 100644
--- a/common/src/main/java/org/onap/so/client/grm/beans/VersionLookup.java
+++ b/common/src/main/java/org/onap/so/client/grm/beans/VersionLookup.java
@@ -21,7 +21,6 @@
package org.onap.so.client.grm.beans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -29,21 +28,21 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
-@JsonPropertyOrder({ "major" })
+@JsonPropertyOrder({"major"})
public class VersionLookup implements Serializable {
- private static final long serialVersionUID = 3802602253627725770L;
+ private static final long serialVersionUID = 3802602253627725770L;
+
+ @JsonProperty("major")
+ private Integer major;
- @JsonProperty("major")
- private Integer major;
-
- @JsonProperty("major")
- public Integer getMajor() {
- return major;
- }
+ @JsonProperty("major")
+ public Integer getMajor() {
+ return major;
+ }
- @JsonProperty("major")
- public void setMajor(Integer major) {
- this.major = major;
- }
+ @JsonProperty("major")
+ public void setMajor(Integer major) {
+ this.major = major;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/grm/exceptions/GRMClientCallFailed.java b/common/src/main/java/org/onap/so/client/grm/exceptions/GRMClientCallFailed.java
index 7107d4027f..458cfa2a72 100644
--- a/common/src/main/java/org/onap/so/client/grm/exceptions/GRMClientCallFailed.java
+++ b/common/src/main/java/org/onap/so/client/grm/exceptions/GRMClientCallFailed.java
@@ -22,11 +22,11 @@ package org.onap.so.client.grm.exceptions;
public class GRMClientCallFailed extends Exception {
- private static final long serialVersionUID = -8714110346844078779L;
+ private static final long serialVersionUID = -8714110346844078779L;
+
+ public GRMClientCallFailed(String message, Throwable cause) {
+ super(message, cause);
+ }
- public GRMClientCallFailed(String message, Throwable cause) {
- super(message, cause);
- }
-
}
diff --git a/common/src/main/java/org/onap/so/client/policy/CommonObjectMapperProvider.java b/common/src/main/java/org/onap/so/client/policy/CommonObjectMapperProvider.java
index f2f6f0362f..c55370f7dc 100644
--- a/common/src/main/java/org/onap/so/client/policy/CommonObjectMapperProvider.java
+++ b/common/src/main/java/org/onap/so/client/policy/CommonObjectMapperProvider.java
@@ -28,19 +28,19 @@ import com.fasterxml.jackson.databind.SerializationFeature;
public class CommonObjectMapperProvider {
- protected ObjectMapper mapper;
+ protected ObjectMapper mapper;
- public CommonObjectMapperProvider() {
-
- mapper = new ObjectMapper();
- mapper.setSerializationInclusion(Include.NON_NULL);
+ public CommonObjectMapperProvider() {
+
+ mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(Include.NON_NULL);
mapper.enable(MapperFeature.USE_ANNOTATIONS);
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
- mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- }
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
+ mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ }
- public ObjectMapper getMapper() {
- return mapper;
- }
-} \ No newline at end of file
+ public ObjectMapper getMapper() {
+ return mapper;
+ }
+}
diff --git a/common/src/main/java/org/onap/so/client/policy/DecisionAttributes.java b/common/src/main/java/org/onap/so/client/policy/DecisionAttributes.java
index 951372db42..cf41dea7a2 100644
--- a/common/src/main/java/org/onap/so/client/policy/DecisionAttributes.java
+++ b/common/src/main/java/org/onap/so/client/policy/DecisionAttributes.java
@@ -27,67 +27,67 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({ "ServiceType", "VNFType", "BB_ID", "WorkStep", "ErrorCode" })
+@JsonPropertyOrder({"ServiceType", "VNFType", "BB_ID", "WorkStep", "ErrorCode"})
public class DecisionAttributes {
- @JsonProperty("ServiceType")
- private String serviceType;
- @JsonProperty("VNFType")
- private String vNFType;
- @JsonProperty("BB_ID")
- private String bbID;
- @JsonProperty("WorkStep")
- private String workStep;
- @JsonProperty("ErrorCode")
- private String errorCode;
-
- @JsonProperty("ServiceType")
- public String getServiceType() {
- return serviceType;
- }
-
- @JsonProperty("ServiceType")
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
-
- @JsonProperty("VNFType")
- public String getVNFType() {
- return vNFType;
- }
-
- @JsonProperty("VNFType")
- public void setVNFType(String vNFType) {
- this.vNFType = vNFType;
- }
-
- @JsonProperty("BB_ID")
- public String getBBID() {
- return bbID;
- }
-
- @JsonProperty("BB_ID")
- public void setBBID(String bBID) {
- this.bbID = bBID;
- }
-
- @JsonProperty("WorkStep")
- public String getWorkStep() {
- return workStep;
- }
-
- @JsonProperty("WorkStep")
- public void setWorkStep(String workStep) {
- this.workStep = workStep;
- }
-
- @JsonProperty("ErrorCode")
- public String getErrorCode() {
- return errorCode;
- }
-
- @JsonProperty("ErrorCode")
- public void setErrorCode(String errorCode) {
- this.errorCode = errorCode;
- }
+ @JsonProperty("ServiceType")
+ private String serviceType;
+ @JsonProperty("VNFType")
+ private String vNFType;
+ @JsonProperty("BB_ID")
+ private String bbID;
+ @JsonProperty("WorkStep")
+ private String workStep;
+ @JsonProperty("ErrorCode")
+ private String errorCode;
+
+ @JsonProperty("ServiceType")
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ @JsonProperty("ServiceType")
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ @JsonProperty("VNFType")
+ public String getVNFType() {
+ return vNFType;
+ }
+
+ @JsonProperty("VNFType")
+ public void setVNFType(String vNFType) {
+ this.vNFType = vNFType;
+ }
+
+ @JsonProperty("BB_ID")
+ public String getBBID() {
+ return bbID;
+ }
+
+ @JsonProperty("BB_ID")
+ public void setBBID(String bBID) {
+ this.bbID = bBID;
+ }
+
+ @JsonProperty("WorkStep")
+ public String getWorkStep() {
+ return workStep;
+ }
+
+ @JsonProperty("WorkStep")
+ public void setWorkStep(String workStep) {
+ this.workStep = workStep;
+ }
+
+ @JsonProperty("ErrorCode")
+ public String getErrorCode() {
+ return errorCode;
+ }
+
+ @JsonProperty("ErrorCode")
+ public void setErrorCode(String errorCode) {
+ this.errorCode = errorCode;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/JettisonStyleMapperProvider.java b/common/src/main/java/org/onap/so/client/policy/JettisonStyleMapperProvider.java
index 23b984a3d0..34b121366b 100644
--- a/common/src/main/java/org/onap/so/client/policy/JettisonStyleMapperProvider.java
+++ b/common/src/main/java/org/onap/so/client/policy/JettisonStyleMapperProvider.java
@@ -21,7 +21,6 @@
package org.onap.so.client.policy;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -30,16 +29,16 @@ import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
@Component
public class JettisonStyleMapperProvider extends CommonObjectMapperProvider {
-
- public JettisonStyleMapperProvider() {
-
- mapper = new ObjectMapper();
- JaxbAnnotationModule jaxbModule = new JaxbAnnotationModule();
- mapper.setSerializationInclusion(Include.NON_NULL);
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
- mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- mapper.registerModule(jaxbModule);
- }
+
+ public JettisonStyleMapperProvider() {
+
+ mapper = new ObjectMapper();
+ JaxbAnnotationModule jaxbModule = new JaxbAnnotationModule();
+ mapper.setSerializationInclusion(Include.NON_NULL);
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
+ mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.registerModule(jaxbModule);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/PolicyClient.java b/common/src/main/java/org/onap/so/client/policy/PolicyClient.java
index 6743bc2c34..d1349260c5 100644
--- a/common/src/main/java/org/onap/so/client/policy/PolicyClient.java
+++ b/common/src/main/java/org/onap/so/client/policy/PolicyClient.java
@@ -26,10 +26,10 @@ import org.onap.so.client.policy.entities.PolicyDecision;
public interface PolicyClient {
- public PolicyDecision getDecision(String serviceType, String vnfType, String bbID, String workStep,
- String errorCode);
-
- public DictionaryData getAllowedTreatments(String bbID, String workStep);
-
- public Config getConfigWithPolicyName(String policyName);
+ public PolicyDecision getDecision(String serviceType, String vnfType, String bbID, String workStep,
+ String errorCode);
+
+ public DictionaryData getAllowedTreatments(String bbID, String workStep);
+
+ public Config getConfigWithPolicyName(String policyName);
}
diff --git a/common/src/main/java/org/onap/so/client/policy/PolicyClientImpl.java b/common/src/main/java/org/onap/so/client/policy/PolicyClientImpl.java
index 71a3227c56..72c5a7dd5b 100644
--- a/common/src/main/java/org/onap/so/client/policy/PolicyClientImpl.java
+++ b/common/src/main/java/org/onap/so/client/policy/PolicyClientImpl.java
@@ -22,7 +22,6 @@ package org.onap.so.client.policy;
import java.io.IOException;
import java.util.List;
-
import org.onap.so.client.RestClient;
import org.onap.so.client.RestPropertiesLoader;
import org.onap.so.client.defaultproperties.PolicyRestPropertiesImpl;
@@ -41,7 +40,6 @@ import org.onap.so.client.policy.entities.PolicyServiceType;
import org.onap.so.client.policy.entities.Workstep;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -51,88 +49,89 @@ import com.fasterxml.jackson.databind.SerializationFeature;
public class PolicyClientImpl implements PolicyClient {
- private static Logger logger = LoggerFactory.getLogger(PolicyClientImpl.class);
- private PolicyRestProperties props;
- private ObjectMapper mapper = new ObjectMapper();
-
- public PolicyClientImpl() {
- props = RestPropertiesLoader.getInstance().getNewImpl(PolicyRestProperties.class);
- if (props == null) {
- logger.error("No RestProperty.PolicyRestProperties implementation found on classpath");
- props = new PolicyRestPropertiesImpl();
- }
- }
- public PolicyDecision getDecision(String serviceType, String vnfType, String bbID, String workStep,
- String errorCode) {
- DecisionAttributes decisionAttributes = new DecisionAttributes();
- decisionAttributes.setServiceType(serviceType);
- decisionAttributes.setvNFType(vnfType);
- decisionAttributes.setBbID(bbID);
- decisionAttributes.setWorkStep(workStep);
- decisionAttributes.setErrorCode(errorCode);
+ private static Logger logger = LoggerFactory.getLogger(PolicyClientImpl.class);
+ private PolicyRestProperties props;
+ private ObjectMapper mapper = new ObjectMapper();
+
+ public PolicyClientImpl() {
+ props = RestPropertiesLoader.getInstance().getNewImpl(PolicyRestProperties.class);
+ if (props == null) {
+ logger.error("No RestProperty.PolicyRestProperties implementation found on classpath");
+ props = new PolicyRestPropertiesImpl();
+ }
+ }
+
+ public PolicyDecision getDecision(String serviceType, String vnfType, String bbID, String workStep,
+ String errorCode) {
+ DecisionAttributes decisionAttributes = new DecisionAttributes();
+ decisionAttributes.setServiceType(serviceType);
+ decisionAttributes.setvNFType(vnfType);
+ decisionAttributes.setBbID(bbID);
+ decisionAttributes.setWorkStep(workStep);
+ decisionAttributes.setErrorCode(errorCode);
+
+ return this.getDecision(decisionAttributes);
+ }
+
+ protected PolicyDecision getDecision(DecisionAttributes decisionAttributes) {
+ PolicyRestClient client = this.getPolicyRestClient(PolicyServiceType.GET_DECISION);
+ PolicyDecisionRequest decisionRequest = new PolicyDecisionRequest();
+ decisionRequest.setDecisionAttributes(decisionAttributes);
+ decisionRequest.setEcompcomponentName(RestClient.ECOMP_COMPONENT_NAME);
+
+ return client.post(decisionRequest, PolicyDecision.class);
+ }
+
+ public DictionaryData getAllowedTreatments(String bbID, String workStep) {
+ PolicyRestClient client = this.getPolicyRestClient(PolicyServiceType.GET_DICTIONARY_ITEMS);
+ DictionaryItemsRequest dictionaryItemsRequest = new DictionaryItemsRequest();
+ dictionaryItemsRequest.setDictionaryType("Decision");
+ dictionaryItemsRequest.setDictionary("RainyDayTreatments");
+ final AllowedTreatments response = client.post(dictionaryItemsRequest, AllowedTreatments.class);
+ final DictionaryJson dictionaryJson = response.getDictionaryJson();
+ final List<DictionaryData> dictionaryDataList = dictionaryJson.getDictionaryDatas();
+ for (DictionaryData dictData : dictionaryDataList) {
+ Bbid bBid = dictData.getBbid();
+ Workstep workstep = dictData.getWorkstep();
+ String bBidString = bBid.getString();
+ String workstepString = workstep.getString();
+ if (bbID.equals(bBidString) && workStep.equals(workstepString)) {
+ return dictData;
+ }
+ }
+ logger.error("There is no AllowedTreatments with that specified parameter set");
+ return null;
+ }
+
+ @Override
+ public Config getConfigWithPolicyName(String policyName) {
+ PolicyRestClient client = this.getPolicyRestClient(PolicyServiceType.GET_CONFIG);
+ ConfigRequestParameters configReqParameters = new ConfigRequestParameters();
+ configReqParameters.setPolicyName(policyName);
+ PolicyConfig[] policyConfigList = client.post(configReqParameters, PolicyConfig[].class);
+ PolicyConfig policyConfig = null;
+ if (policyConfigList.length > 1) {
+ logger.debug("Too many configs for policyName: " + policyName);
+ return null;
+ }
+ try {
+ policyConfig = policyConfigList[0];
+ return this.getConfigFromStringJson(policyConfig.getConfig());
+ } catch (IOException e) {
+ logger.error(e.getMessage());
+ return null;
+ }
+ }
- return this.getDecision(decisionAttributes);
- }
+ protected Config getConfigFromStringJson(String configJson)
+ throws JsonParseException, JsonMappingException, IOException {
+ String unescapedJson = configJson.replaceAll("\\\\", "");
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
+ mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
+ return mapper.readValue(unescapedJson, Config.class);
+ }
- protected PolicyDecision getDecision(DecisionAttributes decisionAttributes) {
- PolicyRestClient client = this.getPolicyRestClient(PolicyServiceType.GET_DECISION);
- PolicyDecisionRequest decisionRequest = new PolicyDecisionRequest();
- decisionRequest.setDecisionAttributes(decisionAttributes);
- decisionRequest.setEcompcomponentName(RestClient.ECOMP_COMPONENT_NAME);
-
- return client.post(decisionRequest, PolicyDecision.class);
- }
-
- public DictionaryData getAllowedTreatments(String bbID, String workStep)
- {
- PolicyRestClient client = this.getPolicyRestClient(PolicyServiceType.GET_DICTIONARY_ITEMS);
- DictionaryItemsRequest dictionaryItemsRequest = new DictionaryItemsRequest();
- dictionaryItemsRequest.setDictionaryType("Decision");
- dictionaryItemsRequest.setDictionary("RainyDayTreatments");
- final AllowedTreatments response = client.post(dictionaryItemsRequest, AllowedTreatments.class);
- final DictionaryJson dictionaryJson = response.getDictionaryJson();
- final List<DictionaryData> dictionaryDataList = dictionaryJson.getDictionaryDatas();
- for(DictionaryData dictData : dictionaryDataList){
- Bbid bBid = dictData.getBbid();
- Workstep workstep = dictData.getWorkstep();
- String bBidString = bBid.getString();
- String workstepString = workstep.getString();
- if(bbID.equals(bBidString) && workStep.equals(workstepString)){
- return dictData;
- }
- }
- logger.error("There is no AllowedTreatments with that specified parameter set");
- return null;
- }
-
- @Override
- public Config getConfigWithPolicyName(String policyName) {
- PolicyRestClient client = this.getPolicyRestClient(PolicyServiceType.GET_CONFIG);
- ConfigRequestParameters configReqParameters = new ConfigRequestParameters();
- configReqParameters.setPolicyName(policyName);
- PolicyConfig[] policyConfigList = client.post(configReqParameters, PolicyConfig[].class);
- PolicyConfig policyConfig = null;
- if(policyConfigList.length > 1) {
- logger.debug("Too many configs for policyName: " + policyName);
- return null;
- }
- try {
- policyConfig = policyConfigList[0];
- return this.getConfigFromStringJson(policyConfig.getConfig());
- } catch (IOException e) {
- logger.error(e.getMessage());
- return null;
- }
- }
-
- protected Config getConfigFromStringJson(String configJson) throws JsonParseException, JsonMappingException, IOException {
- String unescapedJson = configJson.replaceAll("\\\\", "");
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
- mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
- return mapper.readValue(unescapedJson, Config.class);
- }
-
- protected PolicyRestClient getPolicyRestClient(PolicyServiceType policyServiceType) {
- return new PolicyRestClient(this.props, policyServiceType);
- }
+ protected PolicyRestClient getPolicyRestClient(PolicyServiceType policyServiceType) {
+ return new PolicyRestClient(this.props, policyServiceType);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/PolicyRestClient.java b/common/src/main/java/org/onap/so/client/policy/PolicyRestClient.java
index 9427fa7eb9..95bc4282ae 100644
--- a/common/src/main/java/org/onap/so/client/policy/PolicyRestClient.java
+++ b/common/src/main/java/org/onap/so/client/policy/PolicyRestClient.java
@@ -23,32 +23,30 @@ package org.onap.so.client.policy;
import java.util.Map;
import java.util.Optional;
-
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.client.RestClient;
import org.onap.so.client.policy.entities.PolicyServiceType;
import org.onap.so.utils.TargetEntity;
public class PolicyRestClient extends RestClient {
- private final PolicyRestProperties properties;
+ private final PolicyRestProperties properties;
- public PolicyRestClient(PolicyRestProperties props, PolicyServiceType serviceType) {
- super(props, Optional.of(UriBuilder.fromPath(serviceType.toString()).build()));
- this.properties = props;
- }
+ public PolicyRestClient(PolicyRestProperties props, PolicyServiceType serviceType) {
+ super(props, Optional.of(UriBuilder.fromPath(serviceType.toString()).build()));
+ this.properties = props;
+ }
@Override
- public TargetEntity getTargetEntity(){
+ public TargetEntity getTargetEntity() {
return TargetEntity.POLICY;
}
- @Override
- protected void initializeHeaderMap(Map<String, String> headerMap) {
- headerMap.put("ClientAuth", properties.getClientAuth());
- headerMap.put("Authorization", properties.getAuth());
- headerMap.put("Environment", properties.getEnvironment());
- }
+ @Override
+ protected void initializeHeaderMap(Map<String, String> headerMap) {
+ headerMap.put("ClientAuth", properties.getClientAuth());
+ headerMap.put("Authorization", properties.getAuth());
+ headerMap.put("Environment", properties.getEnvironment());
+ }
-} \ No newline at end of file
+}
diff --git a/common/src/main/java/org/onap/so/client/policy/PolicyRestProperties.java b/common/src/main/java/org/onap/so/client/policy/PolicyRestProperties.java
index 1de6e8cd97..2b6947104c 100644
--- a/common/src/main/java/org/onap/so/client/policy/PolicyRestProperties.java
+++ b/common/src/main/java/org/onap/so/client/policy/PolicyRestProperties.java
@@ -23,9 +23,11 @@ package org.onap.so.client.policy;
import org.onap.so.client.RestProperties;
public interface PolicyRestProperties extends RestProperties {
-
- public String getClientAuth();
- public String getAuth();
- public String getEnvironment();
+
+ public String getClientAuth();
+
+ public String getAuth();
+
+ public String getEnvironment();
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/AllowedTreatments.java b/common/src/main/java/org/onap/so/client/policy/entities/AllowedTreatments.java
index e82eca56b8..6c03b60ffb 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/AllowedTreatments.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/AllowedTreatments.java
@@ -25,81 +25,76 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"dictionaryJson",
-"dictionaryData",
-"responseCode",
-"responseMessage"
-})
-public class AllowedTreatments{
-
-@JsonProperty("dictionaryJson")
-private DictionaryJson dictionaryJson;
-@JsonProperty("dictionaryData")
-private Object dictionaryData;
-@JsonProperty("responseCode")
-private Integer responseCode;
-@JsonProperty("responseMessage")
-private String responseMessage;
-
-@JsonProperty("dictionaryJson")
-public DictionaryJson getDictionaryJson() {
-return dictionaryJson;
- }
-
-@JsonProperty("dictionaryJson")
-public void setDictionaryJson(DictionaryJson dictionaryJson) {
-this.dictionaryJson = dictionaryJson;
- }
-
-public AllowedTreatments withDictionaryJson(DictionaryJson dictionaryJson) {
-this.dictionaryJson = dictionaryJson;
-return this;
- }
-
-@JsonProperty("dictionaryData")
-public Object getDictionaryData() {
-return dictionaryData;
- }
-
-@JsonProperty("dictionaryData")
-public void setDictionaryData(Object dictionaryData) {
-this.dictionaryData = dictionaryData;
- }
-
-public AllowedTreatments withDictionaryData(Object dictionaryData) {
-this.dictionaryData = dictionaryData;
-return this;
- }
-
-@JsonProperty("responseCode")
-public Integer getResponseCode() {
-return responseCode;
- }
-
-@JsonProperty("responseCode")
-public void setResponseCode(Integer responseCode) {
-this.responseCode = responseCode;
- }
-
-public AllowedTreatments withResponseCode(Integer responseCode) {
-this.responseCode = responseCode;
-return this;
- }
-
-@JsonProperty("responseMessage")
-public String getResponseMessage() {
-return responseMessage;
- }
-
-@JsonProperty("responseMessage")
-public void setResponseMessage(String responseMessage) {
-this.responseMessage = responseMessage;
- }
-
-public AllowedTreatments withResponseMessage(String responseMessage) {
-this.responseMessage = responseMessage;
-return this;
- }
+@JsonPropertyOrder({"dictionaryJson", "dictionaryData", "responseCode", "responseMessage"})
+public class AllowedTreatments {
+
+ @JsonProperty("dictionaryJson")
+ private DictionaryJson dictionaryJson;
+ @JsonProperty("dictionaryData")
+ private Object dictionaryData;
+ @JsonProperty("responseCode")
+ private Integer responseCode;
+ @JsonProperty("responseMessage")
+ private String responseMessage;
+
+ @JsonProperty("dictionaryJson")
+ public DictionaryJson getDictionaryJson() {
+ return dictionaryJson;
+ }
+
+ @JsonProperty("dictionaryJson")
+ public void setDictionaryJson(DictionaryJson dictionaryJson) {
+ this.dictionaryJson = dictionaryJson;
+ }
+
+ public AllowedTreatments withDictionaryJson(DictionaryJson dictionaryJson) {
+ this.dictionaryJson = dictionaryJson;
+ return this;
+ }
+
+ @JsonProperty("dictionaryData")
+ public Object getDictionaryData() {
+ return dictionaryData;
+ }
+
+ @JsonProperty("dictionaryData")
+ public void setDictionaryData(Object dictionaryData) {
+ this.dictionaryData = dictionaryData;
+ }
+
+ public AllowedTreatments withDictionaryData(Object dictionaryData) {
+ this.dictionaryData = dictionaryData;
+ return this;
+ }
+
+ @JsonProperty("responseCode")
+ public Integer getResponseCode() {
+ return responseCode;
+ }
+
+ @JsonProperty("responseCode")
+ public void setResponseCode(Integer responseCode) {
+ this.responseCode = responseCode;
+ }
+
+ public AllowedTreatments withResponseCode(Integer responseCode) {
+ this.responseCode = responseCode;
+ return this;
+ }
+
+ @JsonProperty("responseMessage")
+ public String getResponseMessage() {
+ return responseMessage;
+ }
+
+ @JsonProperty("responseMessage")
+ public void setResponseMessage(String responseMessage) {
+ this.responseMessage = responseMessage;
+ }
+
+ public AllowedTreatments withResponseMessage(String responseMessage) {
+ this.responseMessage = responseMessage;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/Bbid.java b/common/src/main/java/org/onap/so/client/policy/entities/Bbid.java
index 34faa7df09..90ebd603bc 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/Bbid.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/Bbid.java
@@ -25,63 +25,59 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"valueType",
-"string",
-"chars"
-})
+@JsonPropertyOrder({"valueType", "string", "chars"})
public class Bbid {
-@JsonProperty("valueType")
-private String valueType;
-@JsonProperty("string")
-private String string;
-@JsonProperty("chars")
-private String chars;
+ @JsonProperty("valueType")
+ private String valueType;
+ @JsonProperty("string")
+ private String string;
+ @JsonProperty("chars")
+ private String chars;
-@JsonProperty("valueType")
-public String getValueType() {
-return valueType;
- }
+ @JsonProperty("valueType")
+ public String getValueType() {
+ return valueType;
+ }
-@JsonProperty("valueType")
-public void setValueType(String valueType) {
-this.valueType = valueType;
- }
+ @JsonProperty("valueType")
+ public void setValueType(String valueType) {
+ this.valueType = valueType;
+ }
-public Bbid withValueType(String valueType) {
-this.valueType = valueType;
-return this;
- }
+ public Bbid withValueType(String valueType) {
+ this.valueType = valueType;
+ return this;
+ }
-@JsonProperty("string")
-public String getString() {
-return string;
- }
+ @JsonProperty("string")
+ public String getString() {
+ return string;
+ }
-@JsonProperty("string")
-public void setString(String string) {
-this.string = string;
- }
+ @JsonProperty("string")
+ public void setString(String string) {
+ this.string = string;
+ }
-public Bbid withString(String string) {
-this.string = string;
-return this;
- }
+ public Bbid withString(String string) {
+ this.string = string;
+ return this;
+ }
-@JsonProperty("chars")
-public String getChars() {
-return chars;
- }
+ @JsonProperty("chars")
+ public String getChars() {
+ return chars;
+ }
-@JsonProperty("chars")
-public void setChars(String chars) {
-this.chars = chars;
- }
+ @JsonProperty("chars")
+ public void setChars(String chars) {
+ this.chars = chars;
+ }
-public Bbid withChars(String chars) {
-this.chars = chars;
-return this;
- }
+ public Bbid withChars(String chars) {
+ this.chars = chars;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/Config.java b/common/src/main/java/org/onap/so/client/policy/entities/Config.java
index 6c9c0759d6..440c31916f 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/Config.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/Config.java
@@ -26,22 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "configName",
- "riskLevel",
- "policyName",
- "policyScope",
- "guard",
- "description",
- "priority",
- "uuid",
- "version",
- "content",
- "riskType",
- "service",
- "location",
- "templateVersion"
-})
+@JsonPropertyOrder({"configName", "riskLevel", "policyName", "policyScope", "guard", "description", "priority", "uuid",
+ "version", "content", "riskType", "service", "location", "templateVersion"})
@JsonRootName(value = "config")
public class Config {
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/ConfigRequestParameters.java b/common/src/main/java/org/onap/so/client/policy/entities/ConfigRequestParameters.java
index 8cd5b93a36..177a1c0ca3 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/ConfigRequestParameters.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/ConfigRequestParameters.java
@@ -22,21 +22,12 @@ package org.onap.so.client.policy.entities;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "configAttributes",
- "configName",
- "ecompName",
- "onapName",
- "policyName",
- "requestID",
- "unique"
-})
+@JsonPropertyOrder({"configAttributes", "configName", "ecompName", "onapName", "policyName", "requestID", "unique"})
public class ConfigRequestParameters {
@JsonProperty("configAttributes")
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/Content.java b/common/src/main/java/org/onap/so/client/policy/entities/Content.java
index a473f6c566..009774dbe6 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/Content.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/Content.java
@@ -26,9 +26,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "fabric-config-models"
-})
+@JsonPropertyOrder({"fabric-config-models"})
public class Content {
@JsonProperty("fabric-config-models")
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/DecisionAttributes.java b/common/src/main/java/org/onap/so/client/policy/entities/DecisionAttributes.java
index 07db7d8568..08489f4a08 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/DecisionAttributes.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/DecisionAttributes.java
@@ -27,68 +27,68 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({ "ServiceType", "VNFType", "BB_ID", "WorkStep", "ErrorCode" })
+@JsonPropertyOrder({"ServiceType", "VNFType", "BB_ID", "WorkStep", "ErrorCode"})
public class DecisionAttributes {
- @JsonProperty("ServiceType")
- private String serviceType;
- @JsonProperty("VNFType")
- private String vNFType;
- @JsonProperty("BB_ID")
- private String bbID;
- @JsonProperty("WorkStep")
- private String workStep;
- @JsonProperty("ErrorCode")
- private String errorCode;
-
- @JsonProperty("ServiceType")
- public String getServiceType() {
- return serviceType;
- }
-
- @JsonProperty("ServiceType")
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
-
- @JsonProperty("WorkStep")
- public String getWorkStep() {
- return workStep;
- }
-
- @JsonProperty("WorkStep")
- public void setWorkStep(String workStep) {
- this.workStep = workStep;
- }
-
- @JsonProperty("ErrorCode")
- public String getErrorCode() {
- return errorCode;
- }
-
- @JsonProperty("ErrorCode")
- public void setErrorCode(String errorCode) {
- this.errorCode = errorCode;
- }
-
- @JsonProperty("VNFType")
- public String getvNFType() {
- return vNFType;
- }
-
- @JsonProperty("VNFType")
- public void setvNFType(String vNFType) {
- this.vNFType = vNFType;
- }
-
- @JsonProperty("BB_ID")
- public String getBbID() {
- return bbID;
- }
-
- @JsonProperty("BB_ID")
- public void setBbID(String bbID) {
- this.bbID = bbID;
- }
-
+ @JsonProperty("ServiceType")
+ private String serviceType;
+ @JsonProperty("VNFType")
+ private String vNFType;
+ @JsonProperty("BB_ID")
+ private String bbID;
+ @JsonProperty("WorkStep")
+ private String workStep;
+ @JsonProperty("ErrorCode")
+ private String errorCode;
+
+ @JsonProperty("ServiceType")
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ @JsonProperty("ServiceType")
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ @JsonProperty("WorkStep")
+ public String getWorkStep() {
+ return workStep;
+ }
+
+ @JsonProperty("WorkStep")
+ public void setWorkStep(String workStep) {
+ this.workStep = workStep;
+ }
+
+ @JsonProperty("ErrorCode")
+ public String getErrorCode() {
+ return errorCode;
+ }
+
+ @JsonProperty("ErrorCode")
+ public void setErrorCode(String errorCode) {
+ this.errorCode = errorCode;
+ }
+
+ @JsonProperty("VNFType")
+ public String getvNFType() {
+ return vNFType;
+ }
+
+ @JsonProperty("VNFType")
+ public void setvNFType(String vNFType) {
+ this.vNFType = vNFType;
+ }
+
+ @JsonProperty("BB_ID")
+ public String getBbID() {
+ return bbID;
+ }
+
+ @JsonProperty("BB_ID")
+ public void setBbID(String bbID) {
+ this.bbID = bbID;
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/DictionaryData.java b/common/src/main/java/org/onap/so/client/policy/entities/DictionaryData.java
index 8207999a80..d509d78df7 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/DictionaryData.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/DictionaryData.java
@@ -25,81 +25,76 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"id",
-"bbid",
-"workstep",
-"treatments"
-})
+@JsonPropertyOrder({"id", "bbid", "workstep", "treatments"})
public class DictionaryData {
-@JsonProperty("id")
-private Id id;
-@JsonProperty("bbid")
-private Bbid bbid;
-@JsonProperty("workstep")
-private Workstep workstep;
-@JsonProperty("treatments")
-private Treatments treatments;
-
-@JsonProperty("id")
-public Id getId() {
-return id;
- }
-
-@JsonProperty("id")
-public void setId(Id id) {
-this.id = id;
- }
-
-public DictionaryData withId(Id id) {
-this.id = id;
-return this;
- }
-
-@JsonProperty("bbid")
-public Bbid getBbid() {
-return bbid;
- }
-
-@JsonProperty("bbid")
-public void setBbid(Bbid bbid) {
-this.bbid = bbid;
- }
-
-public DictionaryData withBbid(Bbid bbid) {
-this.bbid = bbid;
-return this;
- }
-
-@JsonProperty("workstep")
-public Workstep getWorkstep() {
-return workstep;
- }
-
-@JsonProperty("workstep")
-public void setWorkstep(Workstep workstep) {
-this.workstep = workstep;
- }
-
-public DictionaryData withWorkstep(Workstep workstep) {
-this.workstep = workstep;
-return this;
- }
-
-@JsonProperty("treatments")
-public Treatments getTreatments() {
-return treatments;
- }
-
-@JsonProperty("treatments")
-public void setTreatments(Treatments treatments) {
-this.treatments = treatments;
- }
-
-public DictionaryData withTreatments(Treatments treatments) {
-this.treatments = treatments;
-return this;
- }
+ @JsonProperty("id")
+ private Id id;
+ @JsonProperty("bbid")
+ private Bbid bbid;
+ @JsonProperty("workstep")
+ private Workstep workstep;
+ @JsonProperty("treatments")
+ private Treatments treatments;
+
+ @JsonProperty("id")
+ public Id getId() {
+ return id;
+ }
+
+ @JsonProperty("id")
+ public void setId(Id id) {
+ this.id = id;
+ }
+
+ public DictionaryData withId(Id id) {
+ this.id = id;
+ return this;
+ }
+
+ @JsonProperty("bbid")
+ public Bbid getBbid() {
+ return bbid;
+ }
+
+ @JsonProperty("bbid")
+ public void setBbid(Bbid bbid) {
+ this.bbid = bbid;
+ }
+
+ public DictionaryData withBbid(Bbid bbid) {
+ this.bbid = bbid;
+ return this;
+ }
+
+ @JsonProperty("workstep")
+ public Workstep getWorkstep() {
+ return workstep;
+ }
+
+ @JsonProperty("workstep")
+ public void setWorkstep(Workstep workstep) {
+ this.workstep = workstep;
+ }
+
+ public DictionaryData withWorkstep(Workstep workstep) {
+ this.workstep = workstep;
+ return this;
+ }
+
+ @JsonProperty("treatments")
+ public Treatments getTreatments() {
+ return treatments;
+ }
+
+ @JsonProperty("treatments")
+ public void setTreatments(Treatments treatments) {
+ this.treatments = treatments;
+ }
+
+ public DictionaryData withTreatments(Treatments treatments) {
+ this.treatments = treatments;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/DictionaryItemsRequest.java b/common/src/main/java/org/onap/so/client/policy/entities/DictionaryItemsRequest.java
index 8b063e83c7..9fa2e4d0b9 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/DictionaryItemsRequest.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/DictionaryItemsRequest.java
@@ -25,31 +25,31 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({ "dictionaryType", "dictionary" })
+@JsonPropertyOrder({"dictionaryType", "dictionary"})
public class DictionaryItemsRequest {
- @JsonProperty("dictionary")
- private String dictionary;
- @JsonProperty("dictionaryType")
- private String dictionaryType;
-
- @JsonProperty("dictionary")
- public String getDictionary() {
- return dictionary;
- }
-
- @JsonProperty("dictionary")
- public void setDictionary(String dictionary) {
- this.dictionary = dictionary;
- }
-
- @JsonProperty("dictionaryType")
- public String getDictionaryType() {
- return dictionaryType;
- }
-
- @JsonProperty("dictionaryType")
- public void setDictionaryType(String dictionaryType) {
- this.dictionaryType = dictionaryType;
- }
+ @JsonProperty("dictionary")
+ private String dictionary;
+ @JsonProperty("dictionaryType")
+ private String dictionaryType;
+
+ @JsonProperty("dictionary")
+ public String getDictionary() {
+ return dictionary;
+ }
+
+ @JsonProperty("dictionary")
+ public void setDictionary(String dictionary) {
+ this.dictionary = dictionary;
+ }
+
+ @JsonProperty("dictionaryType")
+ public String getDictionaryType() {
+ return dictionaryType;
+ }
+
+ @JsonProperty("dictionaryType")
+ public void setDictionaryType(String dictionaryType) {
+ this.dictionaryType = dictionaryType;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/DictionaryJson.java b/common/src/main/java/org/onap/so/client/policy/entities/DictionaryJson.java
index 097c9a5cb9..5b99fe1a05 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/DictionaryJson.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/DictionaryJson.java
@@ -22,33 +22,30 @@ package org.onap.so.client.policy.entities;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"DictionaryDatas"
-})
+@JsonPropertyOrder({"DictionaryDatas"})
public class DictionaryJson {
-@JsonProperty("DictionaryDatas")
-private List<DictionaryData> dictionaryDatas = new ArrayList<DictionaryData>();
+ @JsonProperty("DictionaryDatas")
+ private List<DictionaryData> dictionaryDatas = new ArrayList<DictionaryData>();
-@JsonProperty("DictionaryDatas")
-public List<DictionaryData> getDictionaryDatas() {
-return dictionaryDatas;
- }
+ @JsonProperty("DictionaryDatas")
+ public List<DictionaryData> getDictionaryDatas() {
+ return dictionaryDatas;
+ }
-@JsonProperty("DictionaryDatas")
-public void setDictionaryDatas(List<DictionaryData> dictionaryDatas) {
-this.dictionaryDatas = dictionaryDatas;
- }
+ @JsonProperty("DictionaryDatas")
+ public void setDictionaryDatas(List<DictionaryData> dictionaryDatas) {
+ this.dictionaryDatas = dictionaryDatas;
+ }
-public DictionaryJson withDictionaryDatas(List<DictionaryData> dictionaryDatas) {
-this.dictionaryDatas = dictionaryDatas;
-return this;
- }
+ public DictionaryJson withDictionaryDatas(List<DictionaryData> dictionaryDatas) {
+ this.dictionaryDatas = dictionaryDatas;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/FabricConfigModel.java b/common/src/main/java/org/onap/so/client/policy/entities/FabricConfigModel.java
index d1a924cb7d..684311f997 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/FabricConfigModel.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/FabricConfigModel.java
@@ -25,10 +25,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "vnfProfile",
- "lagProfile"
-})
+@JsonPropertyOrder({"vnfProfile", "lagProfile"})
public class FabricConfigModel {
@JsonProperty("vnfProfile")
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/Id.java b/common/src/main/java/org/onap/so/client/policy/entities/Id.java
index af164d6866..0b957711fe 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/Id.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/Id.java
@@ -25,45 +25,42 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"integral",
-"valueType"
-})
+@JsonPropertyOrder({"integral", "valueType"})
public class Id {
-@JsonProperty("integral")
-private Boolean integral;
-@JsonProperty("valueType")
-private String valueType;
+ @JsonProperty("integral")
+ private Boolean integral;
+ @JsonProperty("valueType")
+ private String valueType;
-@JsonProperty("integral")
-public Boolean getIntegral() {
-return integral;
- }
+ @JsonProperty("integral")
+ public Boolean getIntegral() {
+ return integral;
+ }
-@JsonProperty("integral")
-public void setIntegral(Boolean integral) {
-this.integral = integral;
- }
+ @JsonProperty("integral")
+ public void setIntegral(Boolean integral) {
+ this.integral = integral;
+ }
-public Id withIntegral(Boolean integral) {
-this.integral = integral;
-return this;
- }
+ public Id withIntegral(Boolean integral) {
+ this.integral = integral;
+ return this;
+ }
-@JsonProperty("valueType")
-public String getValueType() {
-return valueType;
- }
+ @JsonProperty("valueType")
+ public String getValueType() {
+ return valueType;
+ }
-@JsonProperty("valueType")
-public void setValueType(String valueType) {
-this.valueType = valueType;
- }
+ @JsonProperty("valueType")
+ public void setValueType(String valueType) {
+ this.valueType = valueType;
+ }
-public Id withValueType(String valueType) {
-this.valueType = valueType;
-return this;
- }
+ public Id withValueType(String valueType) {
+ this.valueType = valueType;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/PolicyConfig.java b/common/src/main/java/org/onap/so/client/policy/entities/PolicyConfig.java
index 807829e323..716462f534 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/PolicyConfig.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/PolicyConfig.java
@@ -22,24 +22,13 @@ package org.onap.so.client.policy.entities;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "policyConfigMessage",
- "policyConfigStatus",
- "type",
- "config",
- "policyName",
- "policyType",
- "policyVersion",
- "matchingConditions",
- "responseAttributes",
- "property"
-})
+@JsonPropertyOrder({"policyConfigMessage", "policyConfigStatus", "type", "config", "policyName", "policyType",
+ "policyVersion", "matchingConditions", "responseAttributes", "property"})
public class PolicyConfig {
@JsonProperty("policyConfigMessage")
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/PolicyDecision.java b/common/src/main/java/org/onap/so/client/policy/entities/PolicyDecision.java
index 57c93927cb..f907b041fa 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/PolicyDecision.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/PolicyDecision.java
@@ -27,31 +27,31 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({ "decision", "details" })
+@JsonPropertyOrder({"decision", "details"})
public class PolicyDecision {
- @JsonProperty("decision")
- private String decision;
- @JsonProperty("details")
- private String details;
-
- @JsonProperty("decision")
- public String getDecision() {
- return decision;
- }
-
- @JsonProperty("decision")
- public void setDecision(String decision) {
- this.decision = decision;
- }
-
- @JsonProperty("details")
- public String getDetails() {
- return details;
- }
-
- @JsonProperty("details")
- public void setDetails(String details) {
- this.details = details;
- }
+ @JsonProperty("decision")
+ private String decision;
+ @JsonProperty("details")
+ private String details;
+
+ @JsonProperty("decision")
+ public String getDecision() {
+ return decision;
+ }
+
+ @JsonProperty("decision")
+ public void setDecision(String decision) {
+ this.decision = decision;
+ }
+
+ @JsonProperty("details")
+ public String getDetails() {
+ return details;
+ }
+
+ @JsonProperty("details")
+ public void setDetails(String details) {
+ this.details = details;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/PolicyDecisionRequest.java b/common/src/main/java/org/onap/so/client/policy/entities/PolicyDecisionRequest.java
index b402e85e32..be58b567bc 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/PolicyDecisionRequest.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/PolicyDecisionRequest.java
@@ -26,32 +26,32 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({ "decisionAttributes", "ecompcomponentName" })
+@JsonPropertyOrder({"decisionAttributes", "ecompcomponentName"})
public class PolicyDecisionRequest {
- @JsonProperty("decisionAttributes")
- private DecisionAttributes decisionAttributes;
- @JsonProperty("ecompcomponentName")
- private String ecompcomponentName;
-
- @JsonProperty("decisionAttributes")
- public DecisionAttributes getDecisionAttributes() {
- return decisionAttributes;
- }
-
- @JsonProperty("decisionAttributes")
- public void setDecisionAttributes(DecisionAttributes decisionAttributes) {
- this.decisionAttributes = decisionAttributes;
- }
-
- @JsonProperty("ecompcomponentName")
- public String getEcompcomponentName() {
- return ecompcomponentName;
- }
-
- @JsonProperty("ecompcomponentName")
- public void setEcompcomponentName(String ecompcomponentName) {
- this.ecompcomponentName = ecompcomponentName;
- }
+ @JsonProperty("decisionAttributes")
+ private DecisionAttributes decisionAttributes;
+ @JsonProperty("ecompcomponentName")
+ private String ecompcomponentName;
+
+ @JsonProperty("decisionAttributes")
+ public DecisionAttributes getDecisionAttributes() {
+ return decisionAttributes;
+ }
+
+ @JsonProperty("decisionAttributes")
+ public void setDecisionAttributes(DecisionAttributes decisionAttributes) {
+ this.decisionAttributes = decisionAttributes;
+ }
+
+ @JsonProperty("ecompcomponentName")
+ public String getEcompcomponentName() {
+ return ecompcomponentName;
+ }
+
+ @JsonProperty("ecompcomponentName")
+ public void setEcompcomponentName(String ecompcomponentName) {
+ this.ecompcomponentName = ecompcomponentName;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/PolicyServiceType.java b/common/src/main/java/org/onap/so/client/policy/entities/PolicyServiceType.java
index 83dc6b7862..b00d22dbad 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/PolicyServiceType.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/PolicyServiceType.java
@@ -21,28 +21,21 @@
package org.onap.so.client.policy.entities;
public enum PolicyServiceType {
- GET_CONFIG("getConfig"),
- SEND_EVENT("sendEvent"),
- PUSH_POLICY("pushPolicy"),
- CREATE_POLICY("createPolicy"),
- UPDATE_POLICY("updatePolicy"),
- GET_DECISION("getDecision"),
- GET_METRICS("getMetrics"),
- DELETE_POLICY("deletePolicy"),
- LIST_CONFIG("listConfig"),
- CREATE_DICTIONARY_ITEM("createDictionaryItem"),
- UPDATE_DICTIONARY_ITEM("updateDictionaryItem"),
- GET_DICTIONARY_ITEMS("getDictionaryItems");
-
- private final String name;
-
- PolicyServiceType(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return name;
- }
-
+ GET_CONFIG("getConfig"), SEND_EVENT("sendEvent"), PUSH_POLICY("pushPolicy"), CREATE_POLICY(
+ "createPolicy"), UPDATE_POLICY("updatePolicy"), GET_DECISION("getDecision"), GET_METRICS(
+ "getMetrics"), DELETE_POLICY("deletePolicy"), LIST_CONFIG("listConfig"), CREATE_DICTIONARY_ITEM(
+ "createDictionaryItem"), UPDATE_DICTIONARY_ITEM(
+ "updateDictionaryItem"), GET_DICTIONARY_ITEMS("getDictionaryItems");
+
+ private final String name;
+
+ PolicyServiceType(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/Treatments.java b/common/src/main/java/org/onap/so/client/policy/entities/Treatments.java
index 433d32756c..fd8a3c5e2a 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/Treatments.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/Treatments.java
@@ -25,63 +25,59 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"valueType",
-"string",
-"chars"
-})
+@JsonPropertyOrder({"valueType", "string", "chars"})
public class Treatments {
-@JsonProperty("valueType")
-private String valueType;
-@JsonProperty("string")
-private String string;
-@JsonProperty("chars")
-private String chars;
+ @JsonProperty("valueType")
+ private String valueType;
+ @JsonProperty("string")
+ private String string;
+ @JsonProperty("chars")
+ private String chars;
-@JsonProperty("valueType")
-public String getValueType() {
-return valueType;
- }
+ @JsonProperty("valueType")
+ public String getValueType() {
+ return valueType;
+ }
-@JsonProperty("valueType")
-public void setValueType(String valueType) {
-this.valueType = valueType;
- }
+ @JsonProperty("valueType")
+ public void setValueType(String valueType) {
+ this.valueType = valueType;
+ }
-public Treatments withValueType(String valueType) {
-this.valueType = valueType;
-return this;
- }
+ public Treatments withValueType(String valueType) {
+ this.valueType = valueType;
+ return this;
+ }
-@JsonProperty("string")
-public String getString() {
-return string;
- }
+ @JsonProperty("string")
+ public String getString() {
+ return string;
+ }
-@JsonProperty("string")
-public void setString(String string) {
-this.string = string;
- }
+ @JsonProperty("string")
+ public void setString(String string) {
+ this.string = string;
+ }
-public Treatments withString(String string) {
-this.string = string;
-return this;
- }
+ public Treatments withString(String string) {
+ this.string = string;
+ return this;
+ }
-@JsonProperty("chars")
-public String getChars() {
-return chars;
- }
+ @JsonProperty("chars")
+ public String getChars() {
+ return chars;
+ }
-@JsonProperty("chars")
-public void setChars(String chars) {
-this.chars = chars;
- }
+ @JsonProperty("chars")
+ public void setChars(String chars) {
+ this.chars = chars;
+ }
-public Treatments withChars(String chars) {
-this.chars = chars;
-return this;
- }
+ public Treatments withChars(String chars) {
+ this.chars = chars;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/Workstep.java b/common/src/main/java/org/onap/so/client/policy/entities/Workstep.java
index 4fbd6e2f8a..1bf3ce001d 100644
--- a/common/src/main/java/org/onap/so/client/policy/entities/Workstep.java
+++ b/common/src/main/java/org/onap/so/client/policy/entities/Workstep.java
@@ -25,63 +25,59 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"valueType",
-"string",
-"chars"
-})
+@JsonPropertyOrder({"valueType", "string", "chars"})
public class Workstep {
-@JsonProperty("valueType")
-private String valueType;
-@JsonProperty("string")
-private String string;
-@JsonProperty("chars")
-private String chars;
+ @JsonProperty("valueType")
+ private String valueType;
+ @JsonProperty("string")
+ private String string;
+ @JsonProperty("chars")
+ private String chars;
-@JsonProperty("valueType")
-public String getValueType() {
-return valueType;
- }
+ @JsonProperty("valueType")
+ public String getValueType() {
+ return valueType;
+ }
-@JsonProperty("valueType")
-public void setValueType(String valueType) {
-this.valueType = valueType;
- }
+ @JsonProperty("valueType")
+ public void setValueType(String valueType) {
+ this.valueType = valueType;
+ }
-public Workstep withValueType(String valueType) {
-this.valueType = valueType;
-return this;
- }
+ public Workstep withValueType(String valueType) {
+ this.valueType = valueType;
+ return this;
+ }
-@JsonProperty("string")
-public String getString() {
-return string;
- }
+ @JsonProperty("string")
+ public String getString() {
+ return string;
+ }
-@JsonProperty("string")
-public void setString(String string) {
-this.string = string;
- }
+ @JsonProperty("string")
+ public void setString(String string) {
+ this.string = string;
+ }
-public Workstep withString(String string) {
-this.string = string;
-return this;
- }
+ public Workstep withString(String string) {
+ this.string = string;
+ return this;
+ }
-@JsonProperty("chars")
-public String getChars() {
-return chars;
- }
+ @JsonProperty("chars")
+ public String getChars() {
+ return chars;
+ }
-@JsonProperty("chars")
-public void setChars(String chars) {
-this.chars = chars;
- }
+ @JsonProperty("chars")
+ public void setChars(String chars) {
+ this.chars = chars;
+ }
-public Workstep withChars(String chars) {
-this.chars = chars;
-return this;
- }
+ public Workstep withChars(String chars) {
+ this.chars = chars;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/ruby/RubyClient.java b/common/src/main/java/org/onap/so/client/ruby/RubyClient.java
index 15b232475b..6c8f48884d 100644
--- a/common/src/main/java/org/onap/so/client/ruby/RubyClient.java
+++ b/common/src/main/java/org/onap/so/client/ruby/RubyClient.java
@@ -24,67 +24,64 @@ import java.io.IOException;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
-
import org.onap.so.client.dmaap.DmaapPublisher;
import org.onap.so.client.ruby.beans.Event;
import org.onap.so.client.ruby.beans.MsoRequest;
import org.onap.so.client.ruby.beans.Ruby;
import org.onap.so.client.ruby.dmaap.RubyCreateTicketRequestPublisher;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-
+
public class RubyClient {
-
- private static final String REQUEST_CLIENT_NAME = "MSO";
- private static final String ACTION = "Create Ticket";
-
- protected String buildRequest(String requestId, String sourceName, String reason, String workflowId, String notification) throws JsonProcessingException {
- final MsoRequest request = new MsoRequest();
- request.withRequestClientName(REQUEST_CLIENT_NAME)
- .withRequestId(requestId)
- .withSourceName(sourceName)
- .withWorkflowId(workflowId)
- .withAction(ACTION);
-
- request.withRequestTime(this.getTime());
-
- if(reason.length() <= 255){
- request.withReason(reason);
- } else {
- throw new IllegalArgumentException("reason exceeds 255 characters");
- }
- if(notification.length() <= 1024){
- request.withNotification(notification);
- } else {
- throw new IllegalArgumentException("notification exceeds 1024 characters");
- }
- final Event event = new Event();
- event.setMsoRequest(request);
- final Ruby ruby = new Ruby();
- ruby.setEvent(event);
- return this.getJson(ruby);
- }
-
- protected String getJson(Ruby obj) throws JsonProcessingException {
- final ObjectMapper mapper = new ObjectMapper();
- return mapper.writeValueAsString(obj);
- }
-
- protected DmaapPublisher getPublisher() throws IOException {
- return new RubyCreateTicketRequestPublisher();
- }
-
- protected String getTime() {
- final ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneOffset.UTC);
- final DateTimeFormatter format = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z");
- return currentDateTime.format(format);
- }
-
- public void rubyCreateTicketCheckRequest(String requestId, String sourceName, String reason, String workflowId, String notification) throws Exception {
- String request = this.buildRequest(requestId, sourceName, reason, workflowId, notification);
- final DmaapPublisher publisher = this.getPublisher();
- publisher.send(request);
- }
+
+ private static final String REQUEST_CLIENT_NAME = "MSO";
+ private static final String ACTION = "Create Ticket";
+
+ protected String buildRequest(String requestId, String sourceName, String reason, String workflowId,
+ String notification) throws JsonProcessingException {
+ final MsoRequest request = new MsoRequest();
+ request.withRequestClientName(REQUEST_CLIENT_NAME).withRequestId(requestId).withSourceName(sourceName)
+ .withWorkflowId(workflowId).withAction(ACTION);
+
+ request.withRequestTime(this.getTime());
+
+ if (reason.length() <= 255) {
+ request.withReason(reason);
+ } else {
+ throw new IllegalArgumentException("reason exceeds 255 characters");
+ }
+ if (notification.length() <= 1024) {
+ request.withNotification(notification);
+ } else {
+ throw new IllegalArgumentException("notification exceeds 1024 characters");
+ }
+ final Event event = new Event();
+ event.setMsoRequest(request);
+ final Ruby ruby = new Ruby();
+ ruby.setEvent(event);
+ return this.getJson(ruby);
+ }
+
+ protected String getJson(Ruby obj) throws JsonProcessingException {
+ final ObjectMapper mapper = new ObjectMapper();
+ return mapper.writeValueAsString(obj);
+ }
+
+ protected DmaapPublisher getPublisher() throws IOException {
+ return new RubyCreateTicketRequestPublisher();
+ }
+
+ protected String getTime() {
+ final ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneOffset.UTC);
+ final DateTimeFormatter format = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z");
+ return currentDateTime.format(format);
+ }
+
+ public void rubyCreateTicketCheckRequest(String requestId, String sourceName, String reason, String workflowId,
+ String notification) throws Exception {
+ String request = this.buildRequest(requestId, sourceName, reason, workflowId, notification);
+ final DmaapPublisher publisher = this.getPublisher();
+ publisher.send(request);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/ruby/beans/Event.java b/common/src/main/java/org/onap/so/client/ruby/beans/Event.java
index 93745ff55e..2737342adc 100644
--- a/common/src/main/java/org/onap/so/client/ruby/beans/Event.java
+++ b/common/src/main/java/org/onap/so/client/ruby/beans/Event.java
@@ -25,43 +25,40 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"msoRequest"
-})
+@JsonPropertyOrder({"msoRequest"})
public class Event {
-@JsonProperty("msoRequest")
-private MsoRequest msoRequest;
+ @JsonProperty("msoRequest")
+ private MsoRequest msoRequest;
-/**
-* No args constructor for use in serialization
-*
-*/
-public Event() {
- }
+ /**
+ * No args constructor for use in serialization
+ *
+ */
+ public Event() {}
-/**
-*
-* @param msoRequest
-*/
-public Event(MsoRequest msoRequest) {
-super();
-this.msoRequest = msoRequest;
- }
+ /**
+ *
+ * @param msoRequest
+ */
+ public Event(MsoRequest msoRequest) {
+ super();
+ this.msoRequest = msoRequest;
+ }
-@JsonProperty("msoRequest")
-public MsoRequest getMsoRequest() {
-return msoRequest;
- }
+ @JsonProperty("msoRequest")
+ public MsoRequest getMsoRequest() {
+ return msoRequest;
+ }
-@JsonProperty("msoRequest")
-public void setMsoRequest(MsoRequest msoRequest) {
-this.msoRequest = msoRequest;
- }
+ @JsonProperty("msoRequest")
+ public void setMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ }
-public Event withMsoRequest(MsoRequest msoRequest) {
-this.msoRequest = msoRequest;
-return this;
- }
+ public Event withMsoRequest(MsoRequest msoRequest) {
+ this.msoRequest = msoRequest;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/ruby/beans/MsoRequest.java b/common/src/main/java/org/onap/so/client/ruby/beans/MsoRequest.java
index f2c004ea6e..15cfc9222f 100644
--- a/common/src/main/java/org/onap/so/client/ruby/beans/MsoRequest.java
+++ b/common/src/main/java/org/onap/so/client/ruby/beans/MsoRequest.java
@@ -25,183 +25,175 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"requestClientName",
-"requestId",
-"requestTime",
-"sourceName",
-"reason",
-"action",
-"workflowId",
-"notification"
-})
+@JsonPropertyOrder({"requestClientName", "requestId", "requestTime", "sourceName", "reason", "action", "workflowId",
+ "notification"})
public class MsoRequest {
-@JsonProperty("requestClientName")
-private String requestClientName;
-@JsonProperty("requestId")
-private String requestId;
-@JsonProperty("requestTime")
-private String requestTime;
-@JsonProperty("sourceName")
-private String sourceName;
-@JsonProperty("reason")
-private String reason;
-@JsonProperty("action")
-private String action;
-@JsonProperty("workflowId")
-private String workflowId;
-@JsonProperty("notification")
-private String notification;
-
-/**
-* No args constructor for use in serialization
-*
-*/
-public MsoRequest() {
- }
-
-/**
-*
-* @param requestClientName
-* @param requestTime
-* @param reason
-* @param requestId
-* @param workflowId
-* @param sourceName
-* @param action
-* @param notification
-*/
-public MsoRequest(String requestClientName, String requestId, String requestTime, String sourceName, String reason, String action, String workflowId, String notification) {
-super();
-this.requestClientName = requestClientName;
-this.requestId = requestId;
-this.requestTime = requestTime;
-this.sourceName = sourceName;
-this.reason = reason;
-this.action = action;
-this.workflowId = workflowId;
-this.notification = notification;
- }
-
-@JsonProperty("requestClientName")
-public String getRequestClientName() {
-return requestClientName;
- }
-
-@JsonProperty("requestClientName")
-public void setRequestClientName(String requestClientName) {
-this.requestClientName = requestClientName;
- }
-
-public MsoRequest withRequestClientName(String requestClientName) {
-this.requestClientName = requestClientName;
-return this;
- }
-
-@JsonProperty("requestId")
-public String getRequestId() {
-return requestId;
- }
-
-@JsonProperty("requestId")
-public void setRequestId(String requestId) {
-this.requestId = requestId;
- }
-
-public MsoRequest withRequestId(String requestId) {
-this.requestId = requestId;
-return this;
- }
-
-@JsonProperty("requestTime")
-public String getRequestTime() {
-return requestTime;
- }
-
-@JsonProperty("requestTime")
-public void setRequestTime(String requestTime) {
-this.requestTime = requestTime;
- }
-
-public MsoRequest withRequestTime(String requestTime) {
-this.requestTime = requestTime;
-return this;
- }
-
-@JsonProperty("sourceName")
-public String getSourceName() {
-return sourceName;
- }
-
-@JsonProperty("sourceName")
-public void setSourceName(String sourceName) {
-this.sourceName = sourceName;
- }
-
-public MsoRequest withSourceName(String sourceName) {
-this.sourceName = sourceName;
-return this;
- }
-
-@JsonProperty("reason")
-public String getReason() {
-return reason;
- }
-
-@JsonProperty("reason")
-public void setReason(String reason) {
-this.reason = reason;
- }
-
-public MsoRequest withReason(String reason) {
-this.reason = reason;
-return this;
- }
-
-@JsonProperty("action")
-public String getAction() {
-return action;
- }
-
-@JsonProperty("action")
-public void setAction(String action) {
-this.action = action;
- }
-
-public MsoRequest withAction(String action) {
-this.action = action;
-return this;
- }
-
-@JsonProperty("workflowId")
-public String getWorkflowId() {
-return workflowId;
- }
-
-@JsonProperty("workflowId")
-public void setWorkflowId(String workflowId) {
-this.workflowId = workflowId;
- }
-
-public MsoRequest withWorkflowId(String workflowId) {
-this.workflowId = workflowId;
-return this;
- }
-
-@JsonProperty("notification")
-public String getNotification() {
-return notification;
- }
-
-@JsonProperty("notification")
-public void setNotification(String notification) {
-this.notification = notification;
- }
-
-public MsoRequest withNotification(String notification) {
-this.notification = notification;
-return this;
- }
+ @JsonProperty("requestClientName")
+ private String requestClientName;
+ @JsonProperty("requestId")
+ private String requestId;
+ @JsonProperty("requestTime")
+ private String requestTime;
+ @JsonProperty("sourceName")
+ private String sourceName;
+ @JsonProperty("reason")
+ private String reason;
+ @JsonProperty("action")
+ private String action;
+ @JsonProperty("workflowId")
+ private String workflowId;
+ @JsonProperty("notification")
+ private String notification;
+
+ /**
+ * No args constructor for use in serialization
+ *
+ */
+ public MsoRequest() {}
+
+ /**
+ *
+ * @param requestClientName
+ * @param requestTime
+ * @param reason
+ * @param requestId
+ * @param workflowId
+ * @param sourceName
+ * @param action
+ * @param notification
+ */
+ public MsoRequest(String requestClientName, String requestId, String requestTime, String sourceName, String reason,
+ String action, String workflowId, String notification) {
+ super();
+ this.requestClientName = requestClientName;
+ this.requestId = requestId;
+ this.requestTime = requestTime;
+ this.sourceName = sourceName;
+ this.reason = reason;
+ this.action = action;
+ this.workflowId = workflowId;
+ this.notification = notification;
+ }
+
+ @JsonProperty("requestClientName")
+ public String getRequestClientName() {
+ return requestClientName;
+ }
+
+ @JsonProperty("requestClientName")
+ public void setRequestClientName(String requestClientName) {
+ this.requestClientName = requestClientName;
+ }
+
+ public MsoRequest withRequestClientName(String requestClientName) {
+ this.requestClientName = requestClientName;
+ return this;
+ }
+
+ @JsonProperty("requestId")
+ public String getRequestId() {
+ return requestId;
+ }
+
+ @JsonProperty("requestId")
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public MsoRequest withRequestId(String requestId) {
+ this.requestId = requestId;
+ return this;
+ }
+
+ @JsonProperty("requestTime")
+ public String getRequestTime() {
+ return requestTime;
+ }
+
+ @JsonProperty("requestTime")
+ public void setRequestTime(String requestTime) {
+ this.requestTime = requestTime;
+ }
+
+ public MsoRequest withRequestTime(String requestTime) {
+ this.requestTime = requestTime;
+ return this;
+ }
+
+ @JsonProperty("sourceName")
+ public String getSourceName() {
+ return sourceName;
+ }
+
+ @JsonProperty("sourceName")
+ public void setSourceName(String sourceName) {
+ this.sourceName = sourceName;
+ }
+
+ public MsoRequest withSourceName(String sourceName) {
+ this.sourceName = sourceName;
+ return this;
+ }
+
+ @JsonProperty("reason")
+ public String getReason() {
+ return reason;
+ }
+
+ @JsonProperty("reason")
+ public void setReason(String reason) {
+ this.reason = reason;
+ }
+
+ public MsoRequest withReason(String reason) {
+ this.reason = reason;
+ return this;
+ }
+
+ @JsonProperty("action")
+ public String getAction() {
+ return action;
+ }
+
+ @JsonProperty("action")
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public MsoRequest withAction(String action) {
+ this.action = action;
+ return this;
+ }
+
+ @JsonProperty("workflowId")
+ public String getWorkflowId() {
+ return workflowId;
+ }
+
+ @JsonProperty("workflowId")
+ public void setWorkflowId(String workflowId) {
+ this.workflowId = workflowId;
+ }
+
+ public MsoRequest withWorkflowId(String workflowId) {
+ this.workflowId = workflowId;
+ return this;
+ }
+
+ @JsonProperty("notification")
+ public String getNotification() {
+ return notification;
+ }
+
+ @JsonProperty("notification")
+ public void setNotification(String notification) {
+ this.notification = notification;
+ }
+
+ public MsoRequest withNotification(String notification) {
+ this.notification = notification;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/ruby/beans/Ruby.java b/common/src/main/java/org/onap/so/client/ruby/beans/Ruby.java
index 725e6a3a94..708b91638b 100644
--- a/common/src/main/java/org/onap/so/client/ruby/beans/Ruby.java
+++ b/common/src/main/java/org/onap/so/client/ruby/beans/Ruby.java
@@ -25,43 +25,40 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"event"
-})
+@JsonPropertyOrder({"event"})
public class Ruby {
-@JsonProperty("event")
-private Event event;
+ @JsonProperty("event")
+ private Event event;
-/**
-* No args constructor for use in serialization
-*
-*/
-public Ruby() {
- }
+ /**
+ * No args constructor for use in serialization
+ *
+ */
+ public Ruby() {}
-/**
-*
-* @param event
-*/
-public Ruby(Event event) {
-super();
-this.event = event;
- }
+ /**
+ *
+ * @param event
+ */
+ public Ruby(Event event) {
+ super();
+ this.event = event;
+ }
-@JsonProperty("event")
-public Event getEvent() {
-return event;
- }
+ @JsonProperty("event")
+ public Event getEvent() {
+ return event;
+ }
-@JsonProperty("event")
-public void setEvent(Event event) {
-this.event = event;
- }
+ @JsonProperty("event")
+ public void setEvent(Event event) {
+ this.event = event;
+ }
-public Ruby withEvent(Event event) {
-this.event = event;
-return this;
- }
+ public Ruby withEvent(Event event) {
+ this.event = event;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/ruby/dmaap/RubyCreateTicketRequestPublisher.java b/common/src/main/java/org/onap/so/client/ruby/dmaap/RubyCreateTicketRequestPublisher.java
index 93a2d96c5e..10402d9921 100644
--- a/common/src/main/java/org/onap/so/client/ruby/dmaap/RubyCreateTicketRequestPublisher.java
+++ b/common/src/main/java/org/onap/so/client/ruby/dmaap/RubyCreateTicketRequestPublisher.java
@@ -23,34 +23,33 @@ package org.onap.so.client.ruby.dmaap;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Optional;
-
import org.onap.so.client.dmaap.DmaapPublisher;
-public class RubyCreateTicketRequestPublisher extends DmaapPublisher{
- public RubyCreateTicketRequestPublisher() throws FileNotFoundException, IOException {
- super();
- }
-
- @Override
- public String getAuth() {
- return msoProperties.get("ruby.create-ticket-request.dmaap.auth");
- }
-
- @Override
- public String getKey() {
- return msoProperties.get("mso.msoKey");
- }
-
- @Override
- public String getTopic() {
- return msoProperties.get("ruby.create-ticket-request.publisher.topic");
- }
-
- @Override
- public Optional<String> getHost() {
- return Optional.ofNullable(msoProperties.get("ruby.create-ticket-request.publisher.host"));
- }
-
+public class RubyCreateTicketRequestPublisher extends DmaapPublisher {
+ public RubyCreateTicketRequestPublisher() throws FileNotFoundException, IOException {
+ super();
+ }
+
+ @Override
+ public String getAuth() {
+ return msoProperties.get("ruby.create-ticket-request.dmaap.auth");
+ }
+
+ @Override
+ public String getKey() {
+ return msoProperties.get("mso.msoKey");
+ }
+
+ @Override
+ public String getTopic() {
+ return msoProperties.get("ruby.create-ticket-request.publisher.topic");
+ }
+
+ @Override
+ public Optional<String> getHost() {
+ return Optional.ofNullable(msoProperties.get("ruby.create-ticket-request.publisher.host"));
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/client/sdno/SDNOHealthCheckClient.java b/common/src/main/java/org/onap/so/client/sdno/SDNOHealthCheckClient.java
index 93a35f34b0..9b857dc08c 100644
--- a/common/src/main/java/org/onap/so/client/sdno/SDNOHealthCheckClient.java
+++ b/common/src/main/java/org/onap/so/client/sdno/SDNOHealthCheckClient.java
@@ -26,7 +26,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
-
import org.onap.so.client.dmaap.DmaapConsumer;
import org.onap.so.client.dmaap.DmaapPublisher;
import org.onap.so.client.sdno.beans.AAIParamList;
@@ -36,123 +35,133 @@ import org.onap.so.client.sdno.beans.RequestHdCustom;
import org.onap.so.client.sdno.beans.SDNO;
import org.onap.so.client.sdno.dmaap.SDNOHealthCheckDmaapConsumer;
import org.onap.so.client.sdno.dmaap.SDNOHealthCheckDmaapPublisher;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class SDNOHealthCheckClient {
- private static final String NODE_TYPE = "VROUTER";
- private static final String API_OPERATION_TYPE = "health-diagnostic-custom";
- private static final String MIRRORING_CHECK = "mirroring_check";
- private static final String CLIENT_NAME = "MSO";
- private static final String PRE_CHECK_CODE = "VROUTER000003";
- private static final String POST_CHECK_CODE = "VROUTER000004";
- private static final String LPORT_MIRRORING_CHECK = "lport_mirroring_check";
- private static final String CONFIGURATION_ID = "configuration-id";
-
-
- public boolean lPortMirrorHealthPreCheck(String userId, String requestId, Optional<String>clliCode, String configurationId, String interfaceId) throws Exception{
- String request = buildLPortMirrorCheckPreRequest(userId, requestId, clliCode, configurationId, interfaceId);
- return this.execute(requestId, request);
- }
-
- public boolean lPortMirrorHealthPostCheck(String userId, String requestId, Optional<String>clliCode, String configurationId, String interfaceId) throws Exception{
- String request = buildLPortMirrorCheckPostRequest(userId, requestId, clliCode, configurationId, interfaceId);
- return this.execute(requestId, request);
- }
-
- public boolean portMirrorHealthPreCheck(String userId, String requestId, Optional<String> clliCode, String configurationId) throws Exception {
- final String request = this.buildPortMirrorPreCheckRequest(userId, requestId, clliCode, configurationId);
- return this.execute(requestId, request);
- }
-
- public boolean portMirrorHealthPostCheck(String userId, String requestId, Optional<String> clliCode, String configurationId) throws Exception {
- final String request = this.buildPortMirrorPostCheckRequest(userId, requestId, clliCode, configurationId);
- return this.execute(requestId, request);
- }
-
- protected String buildLPortMirrorCheckPreRequest(String userId, String requestId, Optional<String> clliCode, String configurationId, String interfaceId) throws JsonProcessingException{
- return this.buildLPortMirrorCheckRequest(userId, requestId, clliCode, configurationId, interfaceId, PRE_CHECK_CODE);
- }
-
- protected String buildLPortMirrorCheckPostRequest(String userId, String requestId, Optional<String> clliCode, String configurationId, String interfaceId) throws JsonProcessingException{
- return this.buildLPortMirrorCheckRequest(userId, requestId, clliCode, configurationId, interfaceId, POST_CHECK_CODE);
- }
-
- protected String buildPortMirrorPreCheckRequest(String userId, String requestId, Optional<String> clliCode, String configurationId) throws JsonProcessingException {
- return this.buildPortMirrorCheckRequest(userId, requestId, clliCode, configurationId, PRE_CHECK_CODE);
- }
-
- protected String buildPortMirrorPostCheckRequest(String userId, String requestId, Optional<String> clliCode, String configurationId) throws JsonProcessingException {
- return this.buildPortMirrorCheckRequest(userId, requestId, clliCode, configurationId, POST_CHECK_CODE);
- }
-
- protected String buildPortMirrorCheckRequest(String userId, String requestId, Optional<String> clliCode, String configurationId, String diagnosticCode) throws JsonProcessingException {
- final AAIParamList list = new AAIParamList();
- list.setKey(CONFIGURATION_ID);
- list.setValue(configurationId);
-
- return this.buildRequest(userId, requestId, clliCode, diagnosticCode, MIRRORING_CHECK, Collections.singletonList(list));
- }
-
- protected String buildLPortMirrorCheckRequest(String userId, String requestId, Optional<String> clliCode, String configurationId, String interfaceId, String diagnosticCode) throws JsonProcessingException {
-
- final AAIParamList configurationIdParam = new AAIParamList();
- configurationIdParam.setKey(CONFIGURATION_ID);
- configurationIdParam.setValue(configurationId);
- final AAIParamList interfaceIdParam = new AAIParamList();
- interfaceIdParam.setKey("interface-id");
- interfaceIdParam.setValue(interfaceId);
- final List<AAIParamList> list = new ArrayList<>();
- list.add(configurationIdParam);
- list.add(interfaceIdParam);
- return this.buildRequest(userId, requestId, clliCode, diagnosticCode, LPORT_MIRRORING_CHECK, list);
- }
-
-
- protected String buildRequest(String userId, String requestId, Optional<String> clliCode, String diagnosticCode, String operationType, List<AAIParamList> paramList) throws JsonProcessingException {
-
- final RequestHdCustom hdCustom = new RequestHdCustom();
- hdCustom.withRequestUserId(userId)
- .withRequestId(requestId)
- .withRequestClientName(CLIENT_NAME)
- .withHealthDiagnosticCode(diagnosticCode)
- .withOperationType(operationType)
- .withAaiParamList(paramList);
-
- final Input input = new Input();
- input.setRequestHdCustom(hdCustom);
- final Body body = new Body();
- body.setInput(input);
- final SDNO request = new SDNO();
- request.withBody(body).withOperation(API_OPERATION_TYPE).withNodeType(NODE_TYPE);
- if (clliCode.isPresent()) {
- request.setNodeLoc(clliCode.get());
- }
- return this.getJson(request);
-
- }
- protected String getJson(SDNO obj) throws JsonProcessingException {
- final ObjectMapper mapper = new ObjectMapper();
- return mapper.writeValueAsString(obj);
- }
-
- protected DmaapPublisher getPublisher() throws FileNotFoundException, IOException {
- return new SDNOHealthCheckDmaapPublisher();
- }
-
- protected DmaapConsumer getConsumer(String requestId) throws FileNotFoundException, IOException {
- return new SDNOHealthCheckDmaapConsumer(requestId);
- }
-
- protected boolean execute(String requestId, String request) throws Exception {
- final DmaapPublisher publisher = this.getPublisher();
- publisher.send(request);
-
- final DmaapConsumer consumer = this.getConsumer(requestId);
-
- return consumer.consume();
- }
-
+ private static final String NODE_TYPE = "VROUTER";
+ private static final String API_OPERATION_TYPE = "health-diagnostic-custom";
+ private static final String MIRRORING_CHECK = "mirroring_check";
+ private static final String CLIENT_NAME = "MSO";
+ private static final String PRE_CHECK_CODE = "VROUTER000003";
+ private static final String POST_CHECK_CODE = "VROUTER000004";
+ private static final String LPORT_MIRRORING_CHECK = "lport_mirroring_check";
+ private static final String CONFIGURATION_ID = "configuration-id";
+
+
+ public boolean lPortMirrorHealthPreCheck(String userId, String requestId, Optional<String> clliCode,
+ String configurationId, String interfaceId) throws Exception {
+ String request = buildLPortMirrorCheckPreRequest(userId, requestId, clliCode, configurationId, interfaceId);
+ return this.execute(requestId, request);
+ }
+
+ public boolean lPortMirrorHealthPostCheck(String userId, String requestId, Optional<String> clliCode,
+ String configurationId, String interfaceId) throws Exception {
+ String request = buildLPortMirrorCheckPostRequest(userId, requestId, clliCode, configurationId, interfaceId);
+ return this.execute(requestId, request);
+ }
+
+ public boolean portMirrorHealthPreCheck(String userId, String requestId, Optional<String> clliCode,
+ String configurationId) throws Exception {
+ final String request = this.buildPortMirrorPreCheckRequest(userId, requestId, clliCode, configurationId);
+ return this.execute(requestId, request);
+ }
+
+ public boolean portMirrorHealthPostCheck(String userId, String requestId, Optional<String> clliCode,
+ String configurationId) throws Exception {
+ final String request = this.buildPortMirrorPostCheckRequest(userId, requestId, clliCode, configurationId);
+ return this.execute(requestId, request);
+ }
+
+ protected String buildLPortMirrorCheckPreRequest(String userId, String requestId, Optional<String> clliCode,
+ String configurationId, String interfaceId) throws JsonProcessingException {
+ return this.buildLPortMirrorCheckRequest(userId, requestId, clliCode, configurationId, interfaceId,
+ PRE_CHECK_CODE);
+ }
+
+ protected String buildLPortMirrorCheckPostRequest(String userId, String requestId, Optional<String> clliCode,
+ String configurationId, String interfaceId) throws JsonProcessingException {
+ return this.buildLPortMirrorCheckRequest(userId, requestId, clliCode, configurationId, interfaceId,
+ POST_CHECK_CODE);
+ }
+
+ protected String buildPortMirrorPreCheckRequest(String userId, String requestId, Optional<String> clliCode,
+ String configurationId) throws JsonProcessingException {
+ return this.buildPortMirrorCheckRequest(userId, requestId, clliCode, configurationId, PRE_CHECK_CODE);
+ }
+
+ protected String buildPortMirrorPostCheckRequest(String userId, String requestId, Optional<String> clliCode,
+ String configurationId) throws JsonProcessingException {
+ return this.buildPortMirrorCheckRequest(userId, requestId, clliCode, configurationId, POST_CHECK_CODE);
+ }
+
+ protected String buildPortMirrorCheckRequest(String userId, String requestId, Optional<String> clliCode,
+ String configurationId, String diagnosticCode) throws JsonProcessingException {
+ final AAIParamList list = new AAIParamList();
+ list.setKey(CONFIGURATION_ID);
+ list.setValue(configurationId);
+
+ return this.buildRequest(userId, requestId, clliCode, diagnosticCode, MIRRORING_CHECK,
+ Collections.singletonList(list));
+ }
+
+ protected String buildLPortMirrorCheckRequest(String userId, String requestId, Optional<String> clliCode,
+ String configurationId, String interfaceId, String diagnosticCode) throws JsonProcessingException {
+
+ final AAIParamList configurationIdParam = new AAIParamList();
+ configurationIdParam.setKey(CONFIGURATION_ID);
+ configurationIdParam.setValue(configurationId);
+ final AAIParamList interfaceIdParam = new AAIParamList();
+ interfaceIdParam.setKey("interface-id");
+ interfaceIdParam.setValue(interfaceId);
+ final List<AAIParamList> list = new ArrayList<>();
+ list.add(configurationIdParam);
+ list.add(interfaceIdParam);
+ return this.buildRequest(userId, requestId, clliCode, diagnosticCode, LPORT_MIRRORING_CHECK, list);
+ }
+
+
+ protected String buildRequest(String userId, String requestId, Optional<String> clliCode, String diagnosticCode,
+ String operationType, List<AAIParamList> paramList) throws JsonProcessingException {
+
+ final RequestHdCustom hdCustom = new RequestHdCustom();
+ hdCustom.withRequestUserId(userId).withRequestId(requestId).withRequestClientName(CLIENT_NAME)
+ .withHealthDiagnosticCode(diagnosticCode).withOperationType(operationType).withAaiParamList(paramList);
+
+ final Input input = new Input();
+ input.setRequestHdCustom(hdCustom);
+ final Body body = new Body();
+ body.setInput(input);
+ final SDNO request = new SDNO();
+ request.withBody(body).withOperation(API_OPERATION_TYPE).withNodeType(NODE_TYPE);
+ if (clliCode.isPresent()) {
+ request.setNodeLoc(clliCode.get());
+ }
+ return this.getJson(request);
+
+ }
+
+ protected String getJson(SDNO obj) throws JsonProcessingException {
+ final ObjectMapper mapper = new ObjectMapper();
+ return mapper.writeValueAsString(obj);
+ }
+
+ protected DmaapPublisher getPublisher() throws FileNotFoundException, IOException {
+ return new SDNOHealthCheckDmaapPublisher();
+ }
+
+ protected DmaapConsumer getConsumer(String requestId) throws FileNotFoundException, IOException {
+ return new SDNOHealthCheckDmaapConsumer(requestId);
+ }
+
+ protected boolean execute(String requestId, String request) throws Exception {
+ final DmaapPublisher publisher = this.getPublisher();
+ publisher.send(request);
+
+ final DmaapConsumer consumer = this.getConsumer(requestId);
+
+ return consumer.consume();
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/client/sdno/SDNOValidator.java b/common/src/main/java/org/onap/so/client/sdno/SDNOValidator.java
index f3cab1e3e8..83624dec63 100644
--- a/common/src/main/java/org/onap/so/client/sdno/SDNOValidator.java
+++ b/common/src/main/java/org/onap/so/client/sdno/SDNOValidator.java
@@ -22,34 +22,34 @@ package org.onap.so.client.sdno;
import java.io.IOException;
import java.util.UUID;
-
import org.onap.aai.domain.yang.GenericVnf;
public interface SDNOValidator {
- /**
- * Issues a health diagnostic request for a given vnf to SDN-O
- *
- * @param vnfId
- * @param uuid
- * @param requestingUserId
- * @return diagnostic result
- * @throws IOException
- * @throws Exception
- */
- public boolean healthDiagnostic(String vnfId, UUID uuid, String requestingUserId) throws IOException, Exception;
-
+ /**
+ * Issues a health diagnostic request for a given vnf to SDN-O
+ *
+ * @param vnfId
+ * @param uuid
+ * @param requestingUserId
+ * @return diagnostic result
+ * @throws IOException
+ * @throws Exception
+ */
+ public boolean healthDiagnostic(String vnfId, UUID uuid, String requestingUserId) throws IOException, Exception;
+
- /**
- * Issues a health diagnostic request for a given GenericVnf to SDN-O
- *
- * @param genericVnf
- * @param uuid
- * @param requestingUserId
- * @return diagnostic result
- * @throws IOException
- * @throws Exception
- */
- public boolean healthDiagnostic(GenericVnf genericVnf, UUID uuid, String requestingUserId) throws IOException, Exception;
+ /**
+ * Issues a health diagnostic request for a given GenericVnf to SDN-O
+ *
+ * @param genericVnf
+ * @param uuid
+ * @param requestingUserId
+ * @return diagnostic result
+ * @throws IOException
+ * @throws Exception
+ */
+ public boolean healthDiagnostic(GenericVnf genericVnf, UUID uuid, String requestingUserId)
+ throws IOException, Exception;
}
diff --git a/common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java b/common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java
index 882a390c7b..4aafd145b7 100644
--- a/common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java
+++ b/common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java
@@ -24,9 +24,7 @@ import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;
-
import javax.ws.rs.NotFoundException;
-
import org.onap.aai.domain.yang.GenericVnf;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.AAIResourcesClient;
@@ -41,88 +39,91 @@ import org.onap.so.client.sdno.beans.RequestHealthDiagnostic;
import org.onap.so.client.sdno.beans.SDNO;
import org.onap.so.client.sdno.dmaap.SDNOHealthCheckDmaapConsumer;
import org.onap.so.client.sdno.dmaap.SDNOHealthCheckDmaapPublisher;
-
import com.fasterxml.jackson.databind.ObjectMapper;
public class SDNOValidatorImpl implements SDNOValidator {
- private final static String clientName = "MSO";
- private final static String HEALTH_DIAGNOSTIC_CODE_DEFAULT = "default";
-
- @Override
- public boolean healthDiagnostic(String vnfId, UUID uuid, String requestingUserId) throws IOException, Exception {
-
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
- AAIResourcesClient client = new AAIResourcesClient();
- GenericVnf vnf = client.get(GenericVnf.class, uri).orElseThrow(() -> new NotFoundException(vnfId + " not found in A&AI"));
-
- SDNO requestDiagnostic = buildRequestDiagnostic(vnf, uuid, requestingUserId);
- ObjectMapper mapper = new ObjectMapper();
- String json = mapper.writeValueAsString(requestDiagnostic);
- this.submitRequest(json);
- boolean status = this.pollForResponse(uuid.toString());
- return status;
- }
-
- @Override
- public boolean healthDiagnostic(GenericVnf genericVnf, UUID uuid, String requestingUserId) throws IOException, Exception {
-
- SDNO requestDiagnostic = buildRequestDiagnostic(genericVnf, uuid, requestingUserId);
- ObjectMapper mapper = new ObjectMapper();
- String json = mapper.writeValueAsString(requestDiagnostic);
- this.submitRequest(json);
- boolean status = this.pollForResponse(uuid.toString());
- return status;
- }
-
- protected SDNO buildRequestDiagnostic(GenericVnf vnf, UUID uuid, String requestingUserId) {
-
- Optional<String> nfRole;
- if (vnf.getNfRole() == null) {
- nfRole = Optional.empty();
- } else {
- nfRole = Optional.of(vnf.getNfRole());
- }
- Input input = new Input();
- SDNO parentRequest = new SDNO();
- Body body = new Body();
- parentRequest.setBody(body);
- parentRequest.setNodeType(nfRole.orElse("NONE").toUpperCase());
- parentRequest.setOperation("health-diagnostic");
-
- body.setInput(input);
-
- RequestHealthDiagnostic request = new RequestHealthDiagnostic();
-
- request.setRequestClientName(clientName);
- request.setRequestNodeName(vnf.getVnfName());
- request.setRequestNodeUuid(vnf.getVnfId());
- request.setRequestNodeType(nfRole.orElse("NONE").toUpperCase());
- request.setRequestNodeIp(vnf.getIpv4OamAddress()); //generic-vnf oam ip
- request.setRequestUserId(requestingUserId); //mech id?
- request.setRequestId(uuid.toString()); //something to identify this request by for polling
- request.setHealthDiagnosticCode(HEALTH_DIAGNOSTIC_CODE_DEFAULT);
-
- input.setRequestHealthDiagnostic(request);
-
- return parentRequest;
- }
- protected void submitRequest(String json) throws FileNotFoundException, IOException, InterruptedException {
-
- DmaapPublisher publisher = new SDNOHealthCheckDmaapPublisher();
- publisher.send(json);
- }
- protected boolean pollForResponse(String uuid) throws Exception {
- DmaapConsumer consumer = this.getConsumer(uuid);
- return consumer.consume();
- }
-
-
-
- protected DmaapConsumer getConsumer(String uuid) throws FileNotFoundException, IOException {
- return new SDNOHealthCheckDmaapConsumer(uuid);
- }
-
-
-
+ private final static String clientName = "MSO";
+ private final static String HEALTH_DIAGNOSTIC_CODE_DEFAULT = "default";
+
+ @Override
+ public boolean healthDiagnostic(String vnfId, UUID uuid, String requestingUserId) throws IOException, Exception {
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
+ AAIResourcesClient client = new AAIResourcesClient();
+ GenericVnf vnf = client.get(GenericVnf.class, uri)
+ .orElseThrow(() -> new NotFoundException(vnfId + " not found in A&AI"));
+
+ SDNO requestDiagnostic = buildRequestDiagnostic(vnf, uuid, requestingUserId);
+ ObjectMapper mapper = new ObjectMapper();
+ String json = mapper.writeValueAsString(requestDiagnostic);
+ this.submitRequest(json);
+ boolean status = this.pollForResponse(uuid.toString());
+ return status;
+ }
+
+ @Override
+ public boolean healthDiagnostic(GenericVnf genericVnf, UUID uuid, String requestingUserId)
+ throws IOException, Exception {
+
+ SDNO requestDiagnostic = buildRequestDiagnostic(genericVnf, uuid, requestingUserId);
+ ObjectMapper mapper = new ObjectMapper();
+ String json = mapper.writeValueAsString(requestDiagnostic);
+ this.submitRequest(json);
+ boolean status = this.pollForResponse(uuid.toString());
+ return status;
+ }
+
+ protected SDNO buildRequestDiagnostic(GenericVnf vnf, UUID uuid, String requestingUserId) {
+
+ Optional<String> nfRole;
+ if (vnf.getNfRole() == null) {
+ nfRole = Optional.empty();
+ } else {
+ nfRole = Optional.of(vnf.getNfRole());
+ }
+ Input input = new Input();
+ SDNO parentRequest = new SDNO();
+ Body body = new Body();
+ parentRequest.setBody(body);
+ parentRequest.setNodeType(nfRole.orElse("NONE").toUpperCase());
+ parentRequest.setOperation("health-diagnostic");
+
+ body.setInput(input);
+
+ RequestHealthDiagnostic request = new RequestHealthDiagnostic();
+
+ request.setRequestClientName(clientName);
+ request.setRequestNodeName(vnf.getVnfName());
+ request.setRequestNodeUuid(vnf.getVnfId());
+ request.setRequestNodeType(nfRole.orElse("NONE").toUpperCase());
+ request.setRequestNodeIp(vnf.getIpv4OamAddress()); // generic-vnf oam ip
+ request.setRequestUserId(requestingUserId); // mech id?
+ request.setRequestId(uuid.toString()); // something to identify this request by for polling
+ request.setHealthDiagnosticCode(HEALTH_DIAGNOSTIC_CODE_DEFAULT);
+
+ input.setRequestHealthDiagnostic(request);
+
+ return parentRequest;
+ }
+
+ protected void submitRequest(String json) throws FileNotFoundException, IOException, InterruptedException {
+
+ DmaapPublisher publisher = new SDNOHealthCheckDmaapPublisher();
+ publisher.send(json);
+ }
+
+ protected boolean pollForResponse(String uuid) throws Exception {
+ DmaapConsumer consumer = this.getConsumer(uuid);
+ return consumer.consume();
+ }
+
+
+
+ protected DmaapConsumer getConsumer(String uuid) throws FileNotFoundException, IOException {
+ return new SDNOHealthCheckDmaapConsumer(uuid);
+ }
+
+
+
}
diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/AAIParamList.java b/common/src/main/java/org/onap/so/client/sdno/beans/AAIParamList.java
index 0de9b90d66..7e98355b4d 100644
--- a/common/src/main/java/org/onap/so/client/sdno/beans/AAIParamList.java
+++ b/common/src/main/java/org/onap/so/client/sdno/beans/AAIParamList.java
@@ -25,63 +25,59 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"key",
-"value"
-})
+@JsonPropertyOrder({"key", "value"})
public class AAIParamList {
-@JsonProperty("key")
-private String key;
-@JsonProperty("value")
-private String value;
+ @JsonProperty("key")
+ private String key;
+ @JsonProperty("value")
+ private String value;
-/**
-* No args constructor for use in serialization
-*
-*/
-public AAIParamList() {
- }
+ /**
+ * No args constructor for use in serialization
+ *
+ */
+ public AAIParamList() {}
-/**
-*
-* @param value
-* @param key
-*/
-public AAIParamList(String key, String value) {
-super();
-this.key = key;
-this.value = value;
- }
+ /**
+ *
+ * @param value
+ * @param key
+ */
+ public AAIParamList(String key, String value) {
+ super();
+ this.key = key;
+ this.value = value;
+ }
-@JsonProperty("key")
-public String getKey() {
-return key;
- }
+ @JsonProperty("key")
+ public String getKey() {
+ return key;
+ }
-@JsonProperty("key")
-public void setKey(String key) {
-this.key = key;
- }
+ @JsonProperty("key")
+ public void setKey(String key) {
+ this.key = key;
+ }
-public AAIParamList withKey(String key) {
-this.key = key;
-return this;
- }
+ public AAIParamList withKey(String key) {
+ this.key = key;
+ return this;
+ }
-@JsonProperty("value")
-public String getValue() {
-return value;
- }
+ @JsonProperty("value")
+ public String getValue() {
+ return value;
+ }
-@JsonProperty("value")
-public void setValue(String value) {
-this.value = value;
- }
+ @JsonProperty("value")
+ public void setValue(String value) {
+ this.value = value;
+ }
-public AAIParamList withValue(String value) {
-this.value = value;
-return this;
- }
+ public AAIParamList withValue(String value) {
+ this.value = value;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/Body.java b/common/src/main/java/org/onap/so/client/sdno/beans/Body.java
index dfca9ec124..84dd83ea6f 100644
--- a/common/src/main/java/org/onap/so/client/sdno/beans/Body.java
+++ b/common/src/main/java/org/onap/so/client/sdno/beans/Body.java
@@ -23,7 +23,6 @@ package org.onap.so.client.sdno.beans;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -32,11 +31,8 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "input"
-})
-public class Body implements Serializable
-{
+@JsonPropertyOrder({"input"})
+public class Body implements Serializable {
@JsonProperty("input")
private Input input;
@@ -68,8 +64,9 @@ public class Body implements Serializable
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
+
public void setAdditionalProperties(Map<String, Object> map) {
- this.additionalProperties = map;
+ this.additionalProperties = map;
}
public Body withAdditionalProperty(String name, Object value) {
diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/Input.java b/common/src/main/java/org/onap/so/client/sdno/beans/Input.java
index e565f71445..ea537bba09 100644
--- a/common/src/main/java/org/onap/so/client/sdno/beans/Input.java
+++ b/common/src/main/java/org/onap/so/client/sdno/beans/Input.java
@@ -23,7 +23,6 @@ package org.onap.so.client.sdno.beans;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -32,18 +31,14 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "request-healthdiagnostic",
- "request-hd-custom"
-})
-public class Input implements Serializable
-{
+@JsonPropertyOrder({"request-healthdiagnostic", "request-hd-custom"})
+public class Input implements Serializable {
@JsonProperty("request-healthdiagnostic")
private RequestHealthDiagnostic RequestHealthDiagnostic;
@JsonProperty("request-hd-custom")
private RequestHdCustom requestHdCustom;
-
+
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
private final static long serialVersionUID = 7155546785389227528L;
@@ -57,15 +52,15 @@ public class Input implements Serializable
public void setRequestHealthDiagnostic(RequestHealthDiagnostic RequestHealthDiagnostic) {
this.RequestHealthDiagnostic = RequestHealthDiagnostic;
}
-
+
@JsonProperty("request-hd-custom")
public RequestHdCustom getRequestHdCustom() {
- return requestHdCustom;
- }
+ return requestHdCustom;
+ }
@JsonProperty("request-hd-custom")
public void setRequestHdCustom(RequestHdCustom requestHdCustom) {
- this.requestHdCustom = requestHdCustom;
+ this.requestHdCustom = requestHdCustom;
}
public Input withRequestHealthDiagnostic(RequestHealthDiagnostic RequestHealthDiagnostic) {
@@ -82,9 +77,9 @@ public class Input implements Serializable
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
-
+
public void setAdditionalProperties(Map<String, Object> map) {
- this.additionalProperties = map;
+ this.additionalProperties = map;
}
public Input withAdditionalProperty(String name, Object value) {
diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/RequestHdCustom.java b/common/src/main/java/org/onap/so/client/sdno/beans/RequestHdCustom.java
index b3a6a4815e..c08d1ef386 100644
--- a/common/src/main/java/org/onap/so/client/sdno/beans/RequestHdCustom.java
+++ b/common/src/main/java/org/onap/so/client/sdno/beans/RequestHdCustom.java
@@ -23,169 +23,161 @@ package org.onap.so.client.sdno.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"request-client-name",
-"request-user-id",
-"request-id",
-"health-diagnostic-code",
-"operation-type",
-"send-detailed-cmd-response",
-"aai-param-list"
-})
+@JsonPropertyOrder({"request-client-name", "request-user-id", "request-id", "health-diagnostic-code", "operation-type",
+ "send-detailed-cmd-response", "aai-param-list"})
public class RequestHdCustom implements Serializable {
-/**
- *
- */
- private static final long serialVersionUID = -206110458275127710L;
-@JsonProperty("request-client-name")
-private String requestClientName;
-@JsonProperty("request-user-id")
-private String requestUserId;
-@JsonProperty("request-id")
-private String requestId;
-@JsonProperty("health-diagnostic-code")
-private String healthDiagnosticCode;
-@JsonProperty("operation-type")
-private String operationType;
-@JsonProperty("send-detailed-cmd-response")
-private String sendDetailedCmdResponse = "false";
-@JsonProperty("aai-param-list")
-private List<AAIParamList> aaiParamList = new ArrayList<AAIParamList>();
-
-/**
-* No args constructor for use in serialization
-*
-*/
-public RequestHdCustom() {
- }
-
-/**
-*
-* @param requestClientName
-* @param operationType
-* @param requestId
-* @param healthDiagnosticCode
-* @param aaiParamList
-* @param requestUserId
-*/
-public RequestHdCustom(String requestClientName, String requestUserId, String requestId, String healthDiagnosticCode, String operationType, List<AAIParamList> aaiParamList) {
-super();
-this.requestClientName = requestClientName;
-this.requestUserId = requestUserId;
-this.requestId = requestId;
-this.healthDiagnosticCode = healthDiagnosticCode;
-this.operationType = operationType;
-this.aaiParamList = aaiParamList;
- }
-
-@JsonProperty("request-client-name")
-public String getRequestClientName() {
-return requestClientName;
- }
-
-@JsonProperty("request-client-name")
-public void setRequestClientName(String requestClientName) {
-this.requestClientName = requestClientName;
- }
-
-public RequestHdCustom withRequestClientName(String requestClientName) {
-this.requestClientName = requestClientName;
-return this;
- }
-
-@JsonProperty("request-user-id")
-public String getRequestUserId() {
-return requestUserId;
- }
-
-@JsonProperty("request-user-id")
-public void setRequestUserId(String requestUserId) {
-this.requestUserId = requestUserId;
- }
-
-public RequestHdCustom withRequestUserId(String requestUserId) {
-this.requestUserId = requestUserId;
-return this;
- }
-
-@JsonProperty("request-id")
-public String getRequestId() {
-return requestId;
- }
-
-@JsonProperty("request-id")
-public void setRequestId(String requestId) {
-this.requestId = requestId;
- }
-
-public RequestHdCustom withRequestId(String requestId) {
-this.requestId = requestId;
-return this;
- }
-
-@JsonProperty("health-diagnostic-code")
-public String getHealthDiagnosticCode() {
-return healthDiagnosticCode;
- }
-
-@JsonProperty("health-diagnostic-code")
-public void setHealthDiagnosticCode(String healthDiagnosticCode) {
-this.healthDiagnosticCode = healthDiagnosticCode;
- }
-
-public RequestHdCustom withHealthDiagnosticCode(String healthDiagnosticCode) {
-this.healthDiagnosticCode = healthDiagnosticCode;
-return this;
- }
-
-@JsonProperty("operation-type")
-public String getOperationType() {
-return operationType;
- }
-
-@JsonProperty("operation-type")
-public void setOperationType(String operationType) {
-this.operationType = operationType;
- }
-
-public RequestHdCustom withOperationType(String operationType) {
-this.operationType = operationType;
-return this;
- }
-
-public void setSendDetailedCmdResponse(String sendDetailedCmdResponse) {
- this.sendDetailedCmdResponse = sendDetailedCmdResponse;
-}
-
-public String getSendDetailedCmdResponse() {
- return sendDetailedCmdResponse;
-}
-
-public RequestHdCustom withSendDetailedCmdResponse(String sendDetailedCmdResponse) {
- this.sendDetailedCmdResponse = sendDetailedCmdResponse;
- return this;
-}
-
-@JsonProperty("aai-param-list")
-public List<AAIParamList> getAaiParamList() {
-return aaiParamList;
- }
-
-@JsonProperty("aai-param-list")
-public void setAaiParamList(List<AAIParamList> aaiParamList) {
-this.aaiParamList = aaiParamList;
- }
-
-public RequestHdCustom withAaiParamList(List<AAIParamList> aaiParamList) {
-this.aaiParamList = aaiParamList;
-return this;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -206110458275127710L;
+ @JsonProperty("request-client-name")
+ private String requestClientName;
+ @JsonProperty("request-user-id")
+ private String requestUserId;
+ @JsonProperty("request-id")
+ private String requestId;
+ @JsonProperty("health-diagnostic-code")
+ private String healthDiagnosticCode;
+ @JsonProperty("operation-type")
+ private String operationType;
+ @JsonProperty("send-detailed-cmd-response")
+ private String sendDetailedCmdResponse = "false";
+ @JsonProperty("aai-param-list")
+ private List<AAIParamList> aaiParamList = new ArrayList<AAIParamList>();
+
+ /**
+ * No args constructor for use in serialization
+ *
+ */
+ public RequestHdCustom() {}
+
+ /**
+ *
+ * @param requestClientName
+ * @param operationType
+ * @param requestId
+ * @param healthDiagnosticCode
+ * @param aaiParamList
+ * @param requestUserId
+ */
+ public RequestHdCustom(String requestClientName, String requestUserId, String requestId,
+ String healthDiagnosticCode, String operationType, List<AAIParamList> aaiParamList) {
+ super();
+ this.requestClientName = requestClientName;
+ this.requestUserId = requestUserId;
+ this.requestId = requestId;
+ this.healthDiagnosticCode = healthDiagnosticCode;
+ this.operationType = operationType;
+ this.aaiParamList = aaiParamList;
+ }
+
+ @JsonProperty("request-client-name")
+ public String getRequestClientName() {
+ return requestClientName;
+ }
+
+ @JsonProperty("request-client-name")
+ public void setRequestClientName(String requestClientName) {
+ this.requestClientName = requestClientName;
+ }
+
+ public RequestHdCustom withRequestClientName(String requestClientName) {
+ this.requestClientName = requestClientName;
+ return this;
+ }
+
+ @JsonProperty("request-user-id")
+ public String getRequestUserId() {
+ return requestUserId;
+ }
+
+ @JsonProperty("request-user-id")
+ public void setRequestUserId(String requestUserId) {
+ this.requestUserId = requestUserId;
+ }
+
+ public RequestHdCustom withRequestUserId(String requestUserId) {
+ this.requestUserId = requestUserId;
+ return this;
+ }
+
+ @JsonProperty("request-id")
+ public String getRequestId() {
+ return requestId;
+ }
+
+ @JsonProperty("request-id")
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public RequestHdCustom withRequestId(String requestId) {
+ this.requestId = requestId;
+ return this;
+ }
+
+ @JsonProperty("health-diagnostic-code")
+ public String getHealthDiagnosticCode() {
+ return healthDiagnosticCode;
+ }
+
+ @JsonProperty("health-diagnostic-code")
+ public void setHealthDiagnosticCode(String healthDiagnosticCode) {
+ this.healthDiagnosticCode = healthDiagnosticCode;
+ }
+
+ public RequestHdCustom withHealthDiagnosticCode(String healthDiagnosticCode) {
+ this.healthDiagnosticCode = healthDiagnosticCode;
+ return this;
+ }
+
+ @JsonProperty("operation-type")
+ public String getOperationType() {
+ return operationType;
+ }
+
+ @JsonProperty("operation-type")
+ public void setOperationType(String operationType) {
+ this.operationType = operationType;
+ }
+
+ public RequestHdCustom withOperationType(String operationType) {
+ this.operationType = operationType;
+ return this;
+ }
+
+ public void setSendDetailedCmdResponse(String sendDetailedCmdResponse) {
+ this.sendDetailedCmdResponse = sendDetailedCmdResponse;
+ }
+
+ public String getSendDetailedCmdResponse() {
+ return sendDetailedCmdResponse;
+ }
+
+ public RequestHdCustom withSendDetailedCmdResponse(String sendDetailedCmdResponse) {
+ this.sendDetailedCmdResponse = sendDetailedCmdResponse;
+ return this;
+ }
+
+ @JsonProperty("aai-param-list")
+ public List<AAIParamList> getAaiParamList() {
+ return aaiParamList;
+ }
+
+ @JsonProperty("aai-param-list")
+ public void setAaiParamList(List<AAIParamList> aaiParamList) {
+ this.aaiParamList = aaiParamList;
+ }
+
+ public RequestHdCustom withAaiParamList(List<AAIParamList> aaiParamList) {
+ this.aaiParamList = aaiParamList;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/RequestHealthDiagnostic.java b/common/src/main/java/org/onap/so/client/sdno/beans/RequestHealthDiagnostic.java
index 69745d6bfb..c05b470b0e 100644
--- a/common/src/main/java/org/onap/so/client/sdno/beans/RequestHealthDiagnostic.java
+++ b/common/src/main/java/org/onap/so/client/sdno/beans/RequestHealthDiagnostic.java
@@ -23,7 +23,6 @@ package org.onap.so.client.sdno.beans;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -32,18 +31,9 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "request-client-name",
- "request-node-name",
- "request-node-uuid",
- "request-node-ip",
- "request-id",
- "request-user-id",
- "request-node-type",
- "health-diagnostic-code"
-})
-public class RequestHealthDiagnostic implements Serializable
-{
+@JsonPropertyOrder({"request-client-name", "request-node-name", "request-node-uuid", "request-node-ip", "request-id",
+ "request-user-id", "request-node-type", "health-diagnostic-code"})
+public class RequestHealthDiagnostic implements Serializable {
@JsonProperty("request-client-name")
private String requestClientName;
@@ -94,7 +84,7 @@ public class RequestHealthDiagnostic implements Serializable
this.requestNodeName = requestNodeName;
return this;
}
-
+
@JsonProperty("request-node-uuid")
public String getRequestNodeUuid() {
return requestNodeUuid;
@@ -194,9 +184,9 @@ public class RequestHealthDiagnostic implements Serializable
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
-
+
public void setAdditionalProperties(Map<String, Object> map) {
- this.additionalProperties = map;
+ this.additionalProperties = map;
}
public RequestHealthDiagnostic withAdditionalProperty(String name, Object value) {
diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/ResultInfo.java b/common/src/main/java/org/onap/so/client/sdno/beans/ResultInfo.java
index 7cf9c7cb06..93826c752f 100644
--- a/common/src/main/java/org/onap/so/client/sdno/beans/ResultInfo.java
+++ b/common/src/main/java/org/onap/so/client/sdno/beans/ResultInfo.java
@@ -22,7 +22,6 @@ package org.onap.so.client.sdno.beans;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -31,89 +30,83 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
-"client-name",
-"code",
-"processing-host",
-"request-id",
-"status"
-})
+@JsonPropertyOrder({"client-name", "code", "processing-host", "request-id", "status"})
public class ResultInfo {
-@JsonProperty("client-name")
-private String clientName;
-@JsonProperty("code")
-private String code;
-@JsonProperty("processing-host")
-private String processingHost;
-@JsonProperty("request-id")
-private String requestId;
-@JsonProperty("status")
-private String status;
-@JsonIgnore
-private Map<String, Object> additionalProperties = new HashMap<String, Object>();
-
-@JsonProperty("client-name")
-public String getClientName() {
-return clientName;
-}
-
-@JsonProperty("client-name")
-public void setClientName(String clientName) {
-this.clientName = clientName;
-}
-
-@JsonProperty("code")
-public String getCode() {
-return code;
-}
-
-@JsonProperty("code")
-public void setCode(String code) {
-this.code = code;
-}
-
-@JsonProperty("processing-host")
-public String getProcessingHost() {
-return processingHost;
-}
-
-@JsonProperty("processing-host")
-public void setProcessingHost(String processingHost) {
-this.processingHost = processingHost;
-}
-
-@JsonProperty("request-id")
-public String getRequestId() {
-return requestId;
-}
-
-@JsonProperty("request-id")
-public void setRequestId(String requestId) {
-this.requestId = requestId;
-}
-
-@JsonProperty("status")
-public String getStatus() {
-return status;
-}
-
-@JsonProperty("status")
-public void setStatus(String status) {
-this.status = status;
-}
-
-@JsonAnyGetter
-public Map<String, Object> getAdditionalProperties() {
-return this.additionalProperties;
-}
-
-@JsonAnySetter
-public void setAdditionalProperty(String name, Object value) {
-this.additionalProperties.put(name, value);
-}
-
-public void setAdditionalProperties(Map<String, Object> map) {
-this.additionalProperties = map;
-}
+ @JsonProperty("client-name")
+ private String clientName;
+ @JsonProperty("code")
+ private String code;
+ @JsonProperty("processing-host")
+ private String processingHost;
+ @JsonProperty("request-id")
+ private String requestId;
+ @JsonProperty("status")
+ private String status;
+ @JsonIgnore
+ private Map<String, Object> additionalProperties = new HashMap<String, Object>();
+
+ @JsonProperty("client-name")
+ public String getClientName() {
+ return clientName;
+ }
+
+ @JsonProperty("client-name")
+ public void setClientName(String clientName) {
+ this.clientName = clientName;
+ }
+
+ @JsonProperty("code")
+ public String getCode() {
+ return code;
+ }
+
+ @JsonProperty("code")
+ public void setCode(String code) {
+ this.code = code;
+ }
+
+ @JsonProperty("processing-host")
+ public String getProcessingHost() {
+ return processingHost;
+ }
+
+ @JsonProperty("processing-host")
+ public void setProcessingHost(String processingHost) {
+ this.processingHost = processingHost;
+ }
+
+ @JsonProperty("request-id")
+ public String getRequestId() {
+ return requestId;
+ }
+
+ @JsonProperty("request-id")
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ @JsonProperty("status")
+ public String getStatus() {
+ return status;
+ }
+
+ @JsonProperty("status")
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ @JsonAnyGetter
+ public Map<String, Object> getAdditionalProperties() {
+ return this.additionalProperties;
+ }
+
+ @JsonAnySetter
+ public void setAdditionalProperty(String name, Object value) {
+ this.additionalProperties.put(name, value);
+ }
+
+ public void setAdditionalProperties(Map<String, Object> map) {
+ this.additionalProperties = map;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/SDNO.java b/common/src/main/java/org/onap/so/client/sdno/beans/SDNO.java
index 7c728a7bab..09f408c967 100644
--- a/common/src/main/java/org/onap/so/client/sdno/beans/SDNO.java
+++ b/common/src/main/java/org/onap/so/client/sdno/beans/SDNO.java
@@ -23,7 +23,6 @@ package org.onap.so.client.sdno.beans;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -32,14 +31,8 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "operation",
- "nodeLoc",
- "nodeType",
- "body"
-})
-public class SDNO implements Serializable
-{
+@JsonPropertyOrder({"operation", "nodeLoc", "nodeType", "body"})
+public class SDNO implements Serializable {
@JsonProperty("operation")
private String operation;
@@ -62,23 +55,23 @@ public class SDNO implements Serializable
public void setOperation(String operation) {
this.operation = operation;
}
-
+
@JsonProperty("nodeLoc")
public String getNodeLoc() {
- return nodeLoc;
- }
-
+ return nodeLoc;
+ }
+
@JsonProperty("nodeLoc")
- public void setNodeLoc(String nodeLoc) {
- this.nodeLoc = nodeLoc;
- }
-
+ public void setNodeLoc(String nodeLoc) {
+ this.nodeLoc = nodeLoc;
+ }
+
public SDNO withNodeLoc(String nodeLoc) {
- this.nodeLoc = nodeLoc;
- return this;
+ this.nodeLoc = nodeLoc;
+ return this;
}
- public SDNO withOperation(String operation) {
+ public SDNO withOperation(String operation) {
this.operation = operation;
return this;
}
@@ -124,10 +117,10 @@ public class SDNO implements Serializable
}
public void setAdditionalProperties(Map<String, Object> map) {
- this.additionalProperties = map;
+ this.additionalProperties = map;
}
-
- public SDNO SDNO (String name, Object value) {
+
+ public SDNO SDNO(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
diff --git a/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java b/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java
index a76c47c805..3589900273 100644
--- a/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java
+++ b/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java
@@ -28,132 +28,137 @@ import org.onap.so.jsonpath.JsonPathUtil;
public class SDNOHealthCheckDmaapConsumer extends DmaapConsumer {
- private final String uuid;
- private boolean continuePolling = true;
- private final static String healthDiagnosticPath = "body.output.*";
-
- public SDNOHealthCheckDmaapConsumer() throws IOException {
- this("none");
- }
-
- public SDNOHealthCheckDmaapConsumer(String uuid) throws IOException {
- super();
- this.uuid = uuid;
- }
-
- @Override
- public String getAuth() {
- return msoProperties.get("sdno.health-check.dmaap.auth");
- }
-
- @Override
- public String getKey() {
- return msoProperties.get("mso.msoKey");
- }
-
- @Override
- public String getTopic() {
- return msoProperties.get("sdno.health-check.dmaap.subscriber.topic");
- }
-
- @Override
- public Optional<String> getHost() {
- return Optional.ofNullable(msoProperties.get("sdno.health-check.dmaap.subscriber.host"));
- }
-
- @Override
- public boolean continuePolling() {
- return continuePolling;
- }
-
- @Override
- public void stopProcessingMessages() {
- continuePolling = false;
- }
- @Override
- public void processMessage(String message) throws Exception {
- if (isHealthDiagnostic(message, this.getRequestId())) {
- if (!healthDiagnosticSuccessful(message)) {
- Optional<String> statusMessage = this.getStatusMessage(message);
- if (statusMessage.isPresent()) {
- throw new SDNOException("failed with message " + statusMessage.get());
- } else {
- throw new SDNOException("failed with no status message");
- }
- } else {
- logger.info("successful health diagnostic found for request: {}" ,getRequestId());
- stopProcessingMessages();
- }
- }
- }
-
- @Override
- public boolean isAccepted(String message) {
- if (isResultInfo(message)) {
- Optional<String> code = isAccepted(message, this.getRequestId());
- if (code.isPresent()) {
- if ("202".equals(code.get())) {
- return true;
- } else {
- //TODO check other statuses 400 and 500
- }
- } else {
- //TODO throw error
- }
- }
-
- return false;
- }
-
- @Override
- public boolean isFailure(String message) {
- if (isResultInfo(message)) {
- Optional<String> code = isFailure(message, this.getRequestId());
- if (code.isPresent()) {
- if ("500".equals(code.get())) {
- return true;
- } else {
- //TODO check other statuses 400 and 500
- }
- } else {
- //TODO throw error
- }
- }
-
- return false;
- }
-
- @Override
- public String getRequestId() {
- return uuid;
- }
-
- protected Optional<String> isAccepted(String json, String uuid) {
- return JsonPathUtil.getInstance().locateResult(json, String.format("$.result-info[?(@.status=='ACCEPTED' && @.request-id=='%s')].code", uuid));
- }
-
- protected Optional<String> isFailure(String json, String uuid) {
- return JsonPathUtil.getInstance().locateResult(json, String.format("$.result-info[?(@.status=='FAILURE' && @.request-id=='%s')].code", uuid));
- }
-
- protected boolean isResultInfo(String json) {
- return JsonPathUtil.getInstance().pathExists(json, "$[?(@.result-info)]");
- }
-
- protected boolean isHealthDiagnostic(String json, String uuid) {
- return JsonPathUtil.getInstance().pathExists(json, String.format("$[?(@.result-info.request-id=='%s')].%s", uuid, healthDiagnosticPath));
- }
-
- protected boolean healthDiagnosticSuccessful(String json) {
- return JsonPathUtil.getInstance().pathExists(json, "$." + healthDiagnosticPath + "[?(@.response-status=='Success')]");
- }
-
- protected Optional<String> getStatusMessage(String json) {
- return JsonPathUtil.getInstance().locateResult(json, "$." + healthDiagnosticPath + ".error-message");
- }
-
- @Override
- public int getMaximumElapsedTime() {
- return 600000;
- }
+ private final String uuid;
+ private boolean continuePolling = true;
+ private final static String healthDiagnosticPath = "body.output.*";
+
+ public SDNOHealthCheckDmaapConsumer() throws IOException {
+ this("none");
+ }
+
+ public SDNOHealthCheckDmaapConsumer(String uuid) throws IOException {
+ super();
+ this.uuid = uuid;
+ }
+
+ @Override
+ public String getAuth() {
+ return msoProperties.get("sdno.health-check.dmaap.auth");
+ }
+
+ @Override
+ public String getKey() {
+ return msoProperties.get("mso.msoKey");
+ }
+
+ @Override
+ public String getTopic() {
+ return msoProperties.get("sdno.health-check.dmaap.subscriber.topic");
+ }
+
+ @Override
+ public Optional<String> getHost() {
+ return Optional.ofNullable(msoProperties.get("sdno.health-check.dmaap.subscriber.host"));
+ }
+
+ @Override
+ public boolean continuePolling() {
+ return continuePolling;
+ }
+
+ @Override
+ public void stopProcessingMessages() {
+ continuePolling = false;
+ }
+
+ @Override
+ public void processMessage(String message) throws Exception {
+ if (isHealthDiagnostic(message, this.getRequestId())) {
+ if (!healthDiagnosticSuccessful(message)) {
+ Optional<String> statusMessage = this.getStatusMessage(message);
+ if (statusMessage.isPresent()) {
+ throw new SDNOException("failed with message " + statusMessage.get());
+ } else {
+ throw new SDNOException("failed with no status message");
+ }
+ } else {
+ logger.info("successful health diagnostic found for request: {}", getRequestId());
+ stopProcessingMessages();
+ }
+ }
+ }
+
+ @Override
+ public boolean isAccepted(String message) {
+ if (isResultInfo(message)) {
+ Optional<String> code = isAccepted(message, this.getRequestId());
+ if (code.isPresent()) {
+ if ("202".equals(code.get())) {
+ return true;
+ } else {
+ // TODO check other statuses 400 and 500
+ }
+ } else {
+ // TODO throw error
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean isFailure(String message) {
+ if (isResultInfo(message)) {
+ Optional<String> code = isFailure(message, this.getRequestId());
+ if (code.isPresent()) {
+ if ("500".equals(code.get())) {
+ return true;
+ } else {
+ // TODO check other statuses 400 and 500
+ }
+ } else {
+ // TODO throw error
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ public String getRequestId() {
+ return uuid;
+ }
+
+ protected Optional<String> isAccepted(String json, String uuid) {
+ return JsonPathUtil.getInstance().locateResult(json,
+ String.format("$.result-info[?(@.status=='ACCEPTED' && @.request-id=='%s')].code", uuid));
+ }
+
+ protected Optional<String> isFailure(String json, String uuid) {
+ return JsonPathUtil.getInstance().locateResult(json,
+ String.format("$.result-info[?(@.status=='FAILURE' && @.request-id=='%s')].code", uuid));
+ }
+
+ protected boolean isResultInfo(String json) {
+ return JsonPathUtil.getInstance().pathExists(json, "$[?(@.result-info)]");
+ }
+
+ protected boolean isHealthDiagnostic(String json, String uuid) {
+ return JsonPathUtil.getInstance().pathExists(json,
+ String.format("$[?(@.result-info.request-id=='%s')].%s", uuid, healthDiagnosticPath));
+ }
+
+ protected boolean healthDiagnosticSuccessful(String json) {
+ return JsonPathUtil.getInstance().pathExists(json,
+ "$." + healthDiagnosticPath + "[?(@.response-status=='Success')]");
+ }
+
+ protected Optional<String> getStatusMessage(String json) {
+ return JsonPathUtil.getInstance().locateResult(json, "$." + healthDiagnosticPath + ".error-message");
+ }
+
+ @Override
+ public int getMaximumElapsedTime() {
+ return 600000;
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java b/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java
index f4af2052ac..b1adc53f3a 100644
--- a/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java
+++ b/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java
@@ -23,33 +23,32 @@ package org.onap.so.client.sdno.dmaap;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Optional;
-
import org.onap.so.client.dmaap.DmaapPublisher;
public class SDNOHealthCheckDmaapPublisher extends DmaapPublisher {
-
- public SDNOHealthCheckDmaapPublisher() throws FileNotFoundException, IOException {
- super();
- }
-
- @Override
- public String getAuth() {
- return msoProperties.get("sdno.health-check.dmaap.auth");
- }
-
- @Override
- public String getKey() {
- return msoProperties.get("sdno.health-check.dmaap.msoKey");
- }
-
- @Override
- public String getTopic() {
- return msoProperties.get("sdno.health-check.dmaap.publisher.topic");
- }
-
- @Override
- public Optional<String> getHost() {
- return Optional.ofNullable(msoProperties.get("sdno.health-check.dmaap.publisher.host"));
- }
+
+ public SDNOHealthCheckDmaapPublisher() throws FileNotFoundException, IOException {
+ super();
+ }
+
+ @Override
+ public String getAuth() {
+ return msoProperties.get("sdno.health-check.dmaap.auth");
+ }
+
+ @Override
+ public String getKey() {
+ return msoProperties.get("sdno.health-check.dmaap.msoKey");
+ }
+
+ @Override
+ public String getTopic() {
+ return msoProperties.get("sdno.health-check.dmaap.publisher.topic");
+ }
+
+ @Override
+ public Optional<String> getHost() {
+ return Optional.ofNullable(msoProperties.get("sdno.health-check.dmaap.publisher.host"));
+ }
}
diff --git a/common/src/main/java/org/onap/so/configuration/rest/HttpClientConnectionConfiguration.java b/common/src/main/java/org/onap/so/configuration/rest/HttpClientConnectionConfiguration.java
index a5a4cb7d53..6c2c76e87c 100644
--- a/common/src/main/java/org/onap/so/configuration/rest/HttpClientConnectionConfiguration.java
+++ b/common/src/main/java/org/onap/so/configuration/rest/HttpClientConnectionConfiguration.java
@@ -21,13 +21,11 @@
package org.onap.so.configuration.rest;
import java.util.concurrent.TimeUnit;
-
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
- * This class is used configure the parameters needed for
- * {@link org.apache.http.impl.client.CloseableHttpClient}
+ * This class is used configure the parameters needed for {@link org.apache.http.impl.client.CloseableHttpClient}
*
* @author waqas.ikram@est.tech
*/
diff --git a/common/src/main/java/org/onap/so/configuration/rest/HttpComponentsClientConfiguration.java b/common/src/main/java/org/onap/so/configuration/rest/HttpComponentsClientConfiguration.java
index e943aef159..882ed95cfc 100644
--- a/common/src/main/java/org/onap/so/configuration/rest/HttpComponentsClientConfiguration.java
+++ b/common/src/main/java/org/onap/so/configuration/rest/HttpComponentsClientConfiguration.java
@@ -21,7 +21,6 @@
package org.onap.so.configuration.rest;
import java.util.concurrent.TimeUnit;
-
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
diff --git a/common/src/main/java/org/onap/so/constants/Defaults.java b/common/src/main/java/org/onap/so/constants/Defaults.java
index 5117f4de95..5b30537056 100644
--- a/common/src/main/java/org/onap/so/constants/Defaults.java
+++ b/common/src/main/java/org/onap/so/constants/Defaults.java
@@ -21,34 +21,33 @@
package org.onap.so.constants;
import java.util.Optional;
-
import org.onap.so.spring.SpringContextHelper;
import org.springframework.context.ApplicationContext;
public enum Defaults {
- CLOUD_OWNER("org.onap.so.cloud-owner", "CloudOwner");
-
- private final String propName;
- private final String defaultValue;
-
- private Defaults(String propName, String defaultValue) {
- this.defaultValue = defaultValue;
- this.propName = propName;
- }
-
- @Override
- public String toString() {
- Optional<ApplicationContext> context = getAppContext();
- if (context.isPresent()) {
- return context.get().getEnvironment().getProperty(this.propName, this.defaultValue);
- } else {
- return this.defaultValue;
- }
-
- }
-
- protected Optional<ApplicationContext> getAppContext() {
- return Optional.ofNullable(SpringContextHelper.getAppContext());
- }
+ CLOUD_OWNER("org.onap.so.cloud-owner", "CloudOwner");
+
+ private final String propName;
+ private final String defaultValue;
+
+ private Defaults(String propName, String defaultValue) {
+ this.defaultValue = defaultValue;
+ this.propName = propName;
+ }
+
+ @Override
+ public String toString() {
+ Optional<ApplicationContext> context = getAppContext();
+ if (context.isPresent()) {
+ return context.get().getEnvironment().getProperty(this.propName, this.defaultValue);
+ } else {
+ return this.defaultValue;
+ }
+
+ }
+
+ protected Optional<ApplicationContext> getAppContext() {
+ return Optional.ofNullable(SpringContextHelper.getAppContext());
+ }
}
diff --git a/common/src/main/java/org/onap/so/entity/MsoRequest.java b/common/src/main/java/org/onap/so/entity/MsoRequest.java
index c61684bec7..c45b2f68f1 100644
--- a/common/src/main/java/org/onap/so/entity/MsoRequest.java
+++ b/common/src/main/java/org/onap/so/entity/MsoRequest.java
@@ -24,41 +24,39 @@ package org.onap.so.entity;
import java.io.Serializable;
/**
- * This simple bean holds tracking information for MSO requests within
- * the adapters. This tracking information should be added to logs,
- * metrics, alarms as appropriate.
+ * This simple bean holds tracking information for MSO requests within the adapters. This tracking information should be
+ * added to logs, metrics, alarms as appropriate.
*
*
*/
-public class MsoRequest implements Serializable
-{
- private static final long serialVersionUID = 1797142528913733469L;
- private String requestId;
- private String serviceInstanceId;
-
- public MsoRequest() {
- this.requestId = null;
- this.serviceInstanceId = null;
- }
-
- public MsoRequest(String r, String s) {
- this.requestId = r;
- this.serviceInstanceId = s;
- }
-
- public String getRequestId() {
- return requestId;
- }
-
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
+public class MsoRequest implements Serializable {
+ private static final long serialVersionUID = 1797142528913733469L;
+ private String requestId;
+ private String serviceInstanceId;
+
+ public MsoRequest() {
+ this.requestId = null;
+ this.serviceInstanceId = null;
+ }
+
+ public MsoRequest(String r, String s) {
+ this.requestId = r;
+ this.serviceInstanceId = s;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
}
diff --git a/common/src/main/java/org/onap/so/exceptions/MSOException.java b/common/src/main/java/org/onap/so/exceptions/MSOException.java
index f49cd8d8f8..99ae92e34b 100644
--- a/common/src/main/java/org/onap/so/exceptions/MSOException.java
+++ b/common/src/main/java/org/onap/so/exceptions/MSOException.java
@@ -21,36 +21,36 @@
package org.onap.so.exceptions;
-public class MSOException extends Exception{
+public class MSOException extends Exception {
/**
*
*/
private static final long serialVersionUID = 4563920496855255206L;
private Integer errorCode;
- public MSOException(String msg){
+ public MSOException(String msg) {
super(msg);
}
-
- public MSOException (Throwable e) {
+
+ public MSOException(Throwable e) {
super(e);
}
-
- public MSOException (String msg, Throwable e) {
- super (msg, e);
+
+ public MSOException(String msg, Throwable e) {
+ super(msg, e);
}
-
- public MSOException(String msg, int errorCode){
+
+ public MSOException(String msg, int errorCode) {
super(msg);
- this.errorCode=errorCode;
+ this.errorCode = errorCode;
}
-
- public MSOException(String msg, int errorCode, Throwable t){
- super(msg,t);
- this.errorCode=errorCode;
+
+ public MSOException(String msg, int errorCode, Throwable t) {
+ super(msg, t);
+ this.errorCode = errorCode;
}
-
- public Integer getErrorCode(){
+
+ public Integer getErrorCode() {
return errorCode;
}
}
diff --git a/common/src/main/java/org/onap/so/exceptions/MarshallerException.java b/common/src/main/java/org/onap/so/exceptions/MarshallerException.java
index 8b06a8519f..a763260aa3 100644
--- a/common/src/main/java/org/onap/so/exceptions/MarshallerException.java
+++ b/common/src/main/java/org/onap/so/exceptions/MarshallerException.java
@@ -32,7 +32,7 @@ public class MarshallerException extends Exception {
}
public MarshallerException(String message, int errorCode, Exception e) {
- super (e);
+ super(e);
this.message = message;
this.errorCode = errorCode;
diff --git a/common/src/main/java/org/onap/so/exceptions/ValidationException.java b/common/src/main/java/org/onap/so/exceptions/ValidationException.java
index b91c30c598..fbc2d9ae99 100644
--- a/common/src/main/java/org/onap/so/exceptions/ValidationException.java
+++ b/common/src/main/java/org/onap/so/exceptions/ValidationException.java
@@ -24,8 +24,8 @@ package org.onap.so.exceptions;
public class ValidationException extends Exception {
/**
- * This class simply extends Exception (without addition additional functionality)
- * to provide an identifier for RequestsDB related exceptions on create, delete, query.
+ * This class simply extends Exception (without addition additional functionality) to provide an identifier for
+ * RequestsDB related exceptions on create, delete, query.
*
*
**/
@@ -37,18 +37,20 @@ public class ValidationException extends Exception {
private static final String REPLACE_SECOND_ELEMENT_KEY = "\\$SECOND_ELEMENT";
@Deprecated
- public ValidationException (String msg) {
- super (VALIDATION_FAIL.replaceAll (REPLACE_ELEMENT_KEY, msg));
+ public ValidationException(String msg) {
+ super(VALIDATION_FAIL.replaceAll(REPLACE_ELEMENT_KEY, msg));
}
public ValidationException(String msg, boolean overrideExistingMessage) {
super(overrideExistingMessage ? VALIDATION_FAIL.replaceAll(REPLACE_ELEMENT_KEY, msg) : msg);
}
- public ValidationException (String msg, Exception cause) {
- super (VALIDATION_FAIL.replaceAll (REPLACE_ELEMENT_KEY, msg), cause);
+ public ValidationException(String msg, Exception cause) {
+ super(VALIDATION_FAIL.replaceAll(REPLACE_ELEMENT_KEY, msg), cause);
}
+
public ValidationException(String firstElement, String secondElement) {
- super(UNMATCHED_ELEMENTS.replaceAll(REPLACE_ELEMENT_KEY, firstElement).replaceAll(REPLACE_SECOND_ELEMENT_KEY, secondElement));
+ super(UNMATCHED_ELEMENTS.replaceAll(REPLACE_ELEMENT_KEY, firstElement).replaceAll(REPLACE_SECOND_ELEMENT_KEY,
+ secondElement));
}
-} \ No newline at end of file
+}
diff --git a/common/src/main/java/org/onap/so/jsonpath/JsonPathUtil.java b/common/src/main/java/org/onap/so/jsonpath/JsonPathUtil.java
index cb0de998ba..ca822617c8 100644
--- a/common/src/main/java/org/onap/so/jsonpath/JsonPathUtil.java
+++ b/common/src/main/java/org/onap/so/jsonpath/JsonPathUtil.java
@@ -23,7 +23,6 @@ package org.onap.so.jsonpath;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.jayway.jsonpath.Configuration;
@@ -33,55 +32,59 @@ import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
public class JsonPathUtil {
-
- private final Configuration conf;
- private final Configuration pathListConf;
- private JsonPathUtil() {
- conf = Configuration.defaultConfiguration().jsonProvider(new JacksonJsonNodeJsonProvider()).addOptions(Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS);
- pathListConf = Configuration.defaultConfiguration().addOptions(Option.AS_PATH_LIST, Option.SUPPRESS_EXCEPTIONS,Option.ALWAYS_RETURN_LIST);
- }
-
- private static class Helper {
- private static final JsonPathUtil INSTANCE = new JsonPathUtil();
- }
-
- public static JsonPathUtil getInstance() {
- return Helper.INSTANCE;
- }
- public boolean pathExists(String json, String jsonPath) {
- return JsonPath.using(conf).parse(json).<ArrayNode>read(jsonPath).size() != 0;
- }
-
- public Optional<String> locateResult(String json, String jsonPath) {
- final ArrayNode result = JsonPath.using(conf).parse(json).read(jsonPath);
- if (result.size() == 0) {
- return Optional.empty();
- } else {
- if (result.get(0).isValueNode()) {
- return Optional.of(result.get(0).asText());
- } else {
- return Optional.of(result.get(0).toString());
- }
-
- }
- }
-
- public List<String> locateResultList(String json, String jsonPath) {
- final ArrayNode resultNodes = JsonPath.using(conf).parse(json).read(jsonPath);
- final ArrayList<String> result = new ArrayList<>();
-
- for (JsonNode node : resultNodes) {
- if (node.isValueNode()) {
- result.add(node.asText());
- } else {
- result.add(node.toString());
- }
-
- }
- return result;
- }
-
- public List<String> getPathList(String json, String jsonPath) {
- return JsonPath.using(pathListConf).parse(json).read(jsonPath);
- }
+
+ private final Configuration conf;
+ private final Configuration pathListConf;
+
+ private JsonPathUtil() {
+ conf = Configuration.defaultConfiguration().jsonProvider(new JacksonJsonNodeJsonProvider())
+ .addOptions(Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS);
+ pathListConf = Configuration.defaultConfiguration().addOptions(Option.AS_PATH_LIST, Option.SUPPRESS_EXCEPTIONS,
+ Option.ALWAYS_RETURN_LIST);
+ }
+
+ private static class Helper {
+ private static final JsonPathUtil INSTANCE = new JsonPathUtil();
+ }
+
+ public static JsonPathUtil getInstance() {
+ return Helper.INSTANCE;
+ }
+
+ public boolean pathExists(String json, String jsonPath) {
+ return JsonPath.using(conf).parse(json).<ArrayNode>read(jsonPath).size() != 0;
+ }
+
+ public Optional<String> locateResult(String json, String jsonPath) {
+ final ArrayNode result = JsonPath.using(conf).parse(json).read(jsonPath);
+ if (result.size() == 0) {
+ return Optional.empty();
+ } else {
+ if (result.get(0).isValueNode()) {
+ return Optional.of(result.get(0).asText());
+ } else {
+ return Optional.of(result.get(0).toString());
+ }
+
+ }
+ }
+
+ public List<String> locateResultList(String json, String jsonPath) {
+ final ArrayNode resultNodes = JsonPath.using(conf).parse(json).read(jsonPath);
+ final ArrayList<String> result = new ArrayList<>();
+
+ for (JsonNode node : resultNodes) {
+ if (node.isValueNode()) {
+ result.add(node.asText());
+ } else {
+ result.add(node.toString());
+ }
+
+ }
+ return result;
+ }
+
+ public List<String> getPathList(String json, String jsonPath) {
+ return JsonPath.using(pathListConf).parse(json).read(jsonPath);
+ }
}
diff --git a/common/src/main/java/org/onap/so/logger/ErrorCode.java b/common/src/main/java/org/onap/so/logger/ErrorCode.java
index b58189efda..2d6fb791d5 100644
--- a/common/src/main/java/org/onap/so/logger/ErrorCode.java
+++ b/common/src/main/java/org/onap/so/logger/ErrorCode.java
@@ -2,7 +2,7 @@ package org.onap.so.logger;
public enum ErrorCode {
PermissionError(100), AvailabilityError(200), DataError(300), SchemaError(400), BusinessProcesssError(
- 500), UnknownError(900);
+ 500), UnknownError(900);
private int value;
diff --git a/common/src/main/java/org/onap/so/logger/LogConstants.java b/common/src/main/java/org/onap/so/logger/LogConstants.java
index 3c8b7f7d56..30915c6171 100644
--- a/common/src/main/java/org/onap/so/logger/LogConstants.java
+++ b/common/src/main/java/org/onap/so/logger/LogConstants.java
@@ -21,8 +21,8 @@
package org.onap.so.logger;
public class LogConstants {
- public static final String TARGET_ENTITY_HEADER="X-Target-Entity";
- public static final String UNKNOWN_TARGET_ENTITY="Unknown-Target-Entity";
- public static final String HTTP_URL="Http-Url";
- public static final String URI_BASE="Uri-Base";
+ public static final String TARGET_ENTITY_HEADER = "X-Target-Entity";
+ public static final String UNKNOWN_TARGET_ENTITY = "Unknown-Target-Entity";
+ public static final String HTTP_URL = "Http-Url";
+ public static final String URI_BASE = "Uri-Base";
}
diff --git a/common/src/main/java/org/onap/so/logger/LoggerStartupListener.java b/common/src/main/java/org/onap/so/logger/LoggerStartupListener.java
index cd7859a170..fe7558693c 100644
--- a/common/src/main/java/org/onap/so/logger/LoggerStartupListener.java
+++ b/common/src/main/java/org/onap/so/logger/LoggerStartupListener.java
@@ -24,11 +24,9 @@ package org.onap.so.logger;
import java.net.InetAddress;
import java.net.UnknownHostException;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggerContextListener;
@@ -39,54 +37,49 @@ import ch.qos.logback.core.spi.LifeCycle;
@Component
public class LoggerStartupListener extends ContextAwareBase implements LoggerContextListener, LifeCycle {
- private boolean started = false;
- private static final Logger logger = LoggerFactory.getLogger(LoggerStartupListener.class);
+ private boolean started = false;
+ private static final Logger logger = LoggerFactory.getLogger(LoggerStartupListener.class);
@Override
public void start() {
- if (started)
- return;
- InetAddress addr= null;
- try {
- addr = InetAddress.getLocalHost();
- } catch (UnknownHostException e) {
- logger.error("UnknownHostException",e);
-
- }
+ if (started)
+ return;
+ InetAddress addr = null;
+ try {
+ addr = InetAddress.getLocalHost();
+ } catch (UnknownHostException e) {
+ logger.error("UnknownHostException", e);
+
+ }
Context context = getContext();
if (addr != null) {
- context.putProperty("server.name", addr.getHostName());
+ context.putProperty("server.name", addr.getHostName());
}
started = true;
}
@Override
- public void stop() {
- }
+ public void stop() {}
- @Override
- public boolean isStarted() {
- return started;
- }
+ @Override
+ public boolean isStarted() {
+ return started;
+ }
- @Override
- public boolean isResetResistant() {
- return true;
- }
+ @Override
+ public boolean isResetResistant() {
+ return true;
+ }
- @Override
- public void onReset(LoggerContext arg0) {
- }
+ @Override
+ public void onReset(LoggerContext arg0) {}
- @Override
- public void onStart(LoggerContext arg0) {
- }
+ @Override
+ public void onStart(LoggerContext arg0) {}
- @Override
- public void onStop(LoggerContext arg0) {
- }
+ @Override
+ public void onStop(LoggerContext arg0) {}
- @Override
- public void onLevelChange(ch.qos.logback.classic.Logger logger, Level level) {
- }
+ @Override
+ public void onLevelChange(ch.qos.logback.classic.Logger logger, Level level) {}
}
diff --git a/common/src/main/java/org/onap/so/logger/MessageEnum.java b/common/src/main/java/org/onap/so/logger/MessageEnum.java
index fcaa52024b..e92d50a685 100644
--- a/common/src/main/java/org/onap/so/logger/MessageEnum.java
+++ b/common/src/main/java/org/onap/so/logger/MessageEnum.java
@@ -22,202 +22,15 @@ package org.onap.so.logger;
-public enum MessageEnum{
- // Api Handler Messages
- APIH_REQUEST_NULL,
- APIH_QUERY_FOUND,
- APIH_QUERY_NOT_FOUND,
- APIH_QUERY_PARAM_WRONG,
- APIH_DB_ACCESS_EXC,
- APIH_DB_ACCESS_EXC_REASON,
- APIH_VALIDATION_ERROR,
- APIH_REQUEST_VALIDATION_ERROR,
- APIH_SERVICE_VALIDATION_ERROR,
- APIH_GENERAL_EXCEPTION_ARG,
- APIH_GENERAL_EXCEPTION,
- APIH_GENERAL_WARNING,
- APIH_AUDIT_EXEC,
- APIH_GENERAL_METRICS,
- APIH_DUPLICATE_CHECK_EXC,
- APIH_DUPLICATE_FOUND,
- APIH_BAD_ORDER,
- APIH_DB_ATTRIBUTE_NOT_FOUND,
- APIH_BPEL_COMMUNICATE_ERROR,
- APIH_BPEL_RESPONSE_ERROR,
- APIH_WARP_REQUEST,
- APIH_ERROR_FROM_BPEL_SERVER,
- APIH_DB_INSERT_EXC,
- APIH_DB_UPDATE_EXC,
- APIH_NO_PROPERTIES,
- APIH_PROPERTY_LOAD_SUC,
- APIH_LOAD_PROPERTIES_FAIL,
- APIH_SDNC_COMMUNICATE_ERROR,
- APIH_SDNC_RESPONSE_ERROR,
- APIH_CANNOT_READ_SCHEMA,
- APIH_HEALTH_CHECK_EXCEPTION,
- APIH_REQUEST_VALIDATION_ERROR_REASON,
- APIH_JAXB_MARSH_ERROR,
- APIH_JAXB_UNMARSH_ERROR,
- APIH_VNFREQUEST_VALIDATION_ERROR,
- APIH_DOM2STR_ERROR,
- APIH_READ_VNFOUTPUT_CLOB_EXCEPTION,
- APIH_DUPLICATE_CHECK_EXC_ATT,
- APIH_GENERATED_REQUEST_ID,
- APIH_GENERATED_SERVICE_INSTANCE_ID,
- APIH_REPLACE_REQUEST_ID,
- // Resource Adapter Messages
- RA_GENERAL_EXCEPTION_ARG,
- RA_GENERAL_EXCEPTION,
- RA_GENERAL_WARNING,
- RA_MISSING_PARAM,
- RA_AUDIT_EXEC,
- RA_GENERAL_METRICS,
- RA_CREATE_STACK_TIMEOUT,
- RA_DELETE_STACK_TIMEOUT,
- RA_UPDATE_STACK_TIMEOUT,
- RA_CONNECTION_EXCEPTION,
- RA_PARSING_ERROR,
- RA_PROPERTIES_NOT_FOUND,
- RA_LOAD_PROPERTIES_SUC,
- RA_NETWORK_ALREADY_EXIST,
- RA_UPDATE_NETWORK_ERR,
- RA_CREATE_STACK_ERR,
- RA_UPDATE_STACK_ERR,
- RA_CREATE_TENANT_ERR,
- RA_NETWORK_NOT_FOUND,
- RA_NETWORK_ORCHE_MODE_NOT_SUPPORT,
- RA_CREATE_NETWORK_EXC,
- RA_NS_EXC,
- RA_PARAM_NOT_FOUND,
- RA_CONFIG_EXC,
- RA_UNKOWN_PARAM,
- RA_VLAN_PARSE,
- RA_DELETE_NETWORK_EXC,
- RA_ROLLBACK_NULL,
- RA_TENANT_NOT_FOUND,
- RA_QUERY_NETWORK_EXC,
- RA_CREATE_NETWORK_NOTIF_EXC,
- RA_ASYNC_ROLLBACK,
- RA_WSDL_NOT_FOUND,
- RA_WSDL_URL_CONVENTION_EXC,
- RA_INIT_NOTIF_EXC,
- RA_SET_CALLBACK_AUTH_EXC,
- RA_FAULT_INFO_EXC,
- RA_MARSHING_ERROR,
- RA_PARSING_REQUEST_ERROR,
- RA_SEND_REQUEST_SDNC,
- RA_RESPONSE_FROM_SDNC,
- RA_EXCEPTION_COMMUNICATE_SDNC,
- RA_EVALUATE_XPATH_ERROR,
- RA_ANALYZE_ERROR_EXC,
- RA_ERROR_GET_RESPONSE_SDNC,
- RA_CALLBACK_BPEL,
- RA_INIT_CALLBACK_WSDL_ERR,
- RA_CALLBACK_BPEL_EXC,
- RA_CALLBACK_BPEL_COMPLETE,
- RA_SDNC_MISS_CONFIG_PARAM,
- RA_SDNC_INVALID_CONFIG,
- RA_PRINT_URL,
- RA_ERROR_CREATE_SDNC_REQUEST,
- RA_ERROR_CREATE_SDNC_RESPONSE,
- RA_ERROR_CONVERT_XML2STR,
- RA_RECEIVE_SDNC_NOTIF,
- RA_INIT_SDNC_ADAPTER,
- RA_SEND_REQUEST_APPC_ERR,
- RA_SEND_REQUEST_SDNC_ERR,
- RA_RECEIVE_BPEL_REQUEST,
- RA_TENANT_ALREADY_EXIST,
- RA_UPDATE_TENANT_ERR,
- RA_DELETE_TEMAMT_ERR,
- RA_ROLLBACK_TENANT_ERR,
- RA_QUERY_VNF_ERR,
- RA_VNF_ALREADY_EXIST,
- RA_VNF_UNKNOWN_PARAM,
- RA_VNF_EXTRA_PARAM,
- RA_CREATE_VNF_ERR,
- RA_VNF_NOT_EXIST,
- RA_UPDATE_VNF_ERR,
- RA_DELETE_VNF_ERR,
- RA_ASYNC_CREATE_VNF,
- RA_SEND_VNF_NOTIF_ERR,
- RA_ASYNC_CREATE_VNF_COMPLETE,
- RA_ASYNC_UPDATE_VNF,
- RA_ASYNC_UPDATE_VNF_COMPLETE,
- RA_ASYNC_QUERY_VNF,
- RA_ASYNC_QUERY_VNF_COMPLETE,
- RA_ASYNC_DELETE_VNF,
- RA_ASYNC_DELETE_VNF_COMPLETE,
- RA_ASYNC_ROLLBACK_VNF,
- RA_ASYNC_ROLLBACK_VNF_COMPLETE,
- RA_ROLLBACK_VNF_ERR,
- RA_DB_INVALID_STATUS,
- RA_CANT_UPDATE_REQUEST,
- RA_DB_REQUEST_NOT_EXIST,
- RA_CONFIG_NOT_FOUND,
- RA_CONFIG_LOAD,
- RA_RECEIVE_WORKFLOW_MESSAGE,
- // BPEL engine Messages
- BPMN_GENERAL_INFO,
- BPMN_GENERAL_EXCEPTION_ARG,
- BPMN_GENERAL_EXCEPTION,
- BPMN_GENERAL_WARNING,
- BPMN_AUDIT_EXEC,
- BPMN_GENERAL_METRICS,
- BPMN_URN_MAPPING_FAIL,
- BPMN_VARIABLE_NULL,
- BPMN_CALLBACK_EXCEPTION,
- // ASDC Messages
- ASDC_GENERAL_EXCEPTION_ARG,
- ASDC_GENERAL_EXCEPTION,
- ASDC_GENERAL_WARNING,
- ASDC_GENERAL_INFO,
- ASDC_AUDIT_EXEC,
- ASDC_GENERAL_METRICS,
- ASDC_CREATE_SERVICE,
- ASDC_ARTIFACT_ALREADY_DEPLOYED,
- ASDC_CREATE_ARTIFACT,
- ASDC_ARTIFACT_INSTALL_EXC,
- ASDC_ARTIFACT_ALREADY_DEPLOYED_DETAIL,
- ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL,
- ASDC_ARTIFACT_CHECK_EXC,
- ASDC_INIT_ASDC_CLIENT_EXC,
- ASDC_INIT_ASDC_CLIENT_SUC,
- ASDC_LOAD_ASDC_CLIENT_EXC,
- ASDC_SINGLETON_CHECKT_EXC,
- ASDC_SHUTDOWN_ASDC_CLIENT_EXC,
- ASDC_CHECK_HEAT_TEMPLATE,
- ASDC_START_INSTALL_ARTIFACT,
- ASDC_ARTIFACT_TYPE_NOT_SUPPORT,
- ASDC_ARTIFACT_ALREADY_EXIST,
- ASDC_ARTIFACT_DOWNLOAD_SUC,
- ASDC_ARTIFACT_DOWNLOAD_FAIL,
- ASDC_START_DEPLOY_ARTIFACT,
- ASDC_SEND_NOTIF_ASDC,
- ASDC_SEND_NOTIF_ASDC_EXEC,
- ASDC_RECEIVE_CALLBACK_NOTIF,
- ASDC_RECEIVE_SERVICE_NOTIF,
- ASDC_ARTIFACT_NULL,
- ASDC_SERVICE_NOT_SUPPORT,
- ASDC_ARTIFACT_DEPLOY_SUC,
- ASDC_PROPERTIES_NOT_FOUND,
- ASDC_PROPERTIES_LOAD_SUCCESS,
- // Default Messages, in case Log catalog is not defined
- GENERAL_EXCEPTION_ARG,
- GENERAL_EXCEPTION,
- GENERAL_WARNING,
- AUDIT_EXEC,
- GENERAL_METRICS,
- LOGGER_SETUP,
- LOGGER_NOT_FOUND,
- LOGGER_UPDATE_SUC,
- LOGGER_UPDATE_DEBUG,
- LOGGER_UPDATE_DEBUG_SUC,
- LOAD_PROPERTIES_SUC,
- NO_PROPERTIES,
- MADATORY_PARAM_MISSING,
- LOAD_PROPERTIES_FAIL,
- INIT_LOGGER,
- INIT_LOGGER_FAIL,
- JAXB_EXCEPTION,
- IDENTITY_SERVICE_NOT_FOUND;
+public enum MessageEnum {
+ // Api Handler Messages
+ APIH_REQUEST_NULL, APIH_QUERY_FOUND, APIH_QUERY_NOT_FOUND, APIH_QUERY_PARAM_WRONG, APIH_DB_ACCESS_EXC, APIH_DB_ACCESS_EXC_REASON, APIH_VALIDATION_ERROR, APIH_REQUEST_VALIDATION_ERROR, APIH_SERVICE_VALIDATION_ERROR, APIH_GENERAL_EXCEPTION_ARG, APIH_GENERAL_EXCEPTION, APIH_GENERAL_WARNING, APIH_AUDIT_EXEC, APIH_GENERAL_METRICS, APIH_DUPLICATE_CHECK_EXC, APIH_DUPLICATE_FOUND, APIH_BAD_ORDER, APIH_DB_ATTRIBUTE_NOT_FOUND, APIH_BPEL_COMMUNICATE_ERROR, APIH_BPEL_RESPONSE_ERROR, APIH_WARP_REQUEST, APIH_ERROR_FROM_BPEL_SERVER, APIH_DB_INSERT_EXC, APIH_DB_UPDATE_EXC, APIH_NO_PROPERTIES, APIH_PROPERTY_LOAD_SUC, APIH_LOAD_PROPERTIES_FAIL, APIH_SDNC_COMMUNICATE_ERROR, APIH_SDNC_RESPONSE_ERROR, APIH_CANNOT_READ_SCHEMA, APIH_HEALTH_CHECK_EXCEPTION, APIH_REQUEST_VALIDATION_ERROR_REASON, APIH_JAXB_MARSH_ERROR, APIH_JAXB_UNMARSH_ERROR, APIH_VNFREQUEST_VALIDATION_ERROR, APIH_DOM2STR_ERROR, APIH_READ_VNFOUTPUT_CLOB_EXCEPTION, APIH_DUPLICATE_CHECK_EXC_ATT, APIH_GENERATED_REQUEST_ID, APIH_GENERATED_SERVICE_INSTANCE_ID, APIH_REPLACE_REQUEST_ID,
+ // Resource Adapter Messages
+ RA_GENERAL_EXCEPTION_ARG, RA_GENERAL_EXCEPTION, RA_GENERAL_WARNING, RA_MISSING_PARAM, RA_AUDIT_EXEC, RA_GENERAL_METRICS, RA_CREATE_STACK_TIMEOUT, RA_DELETE_STACK_TIMEOUT, RA_UPDATE_STACK_TIMEOUT, RA_CONNECTION_EXCEPTION, RA_PARSING_ERROR, RA_PROPERTIES_NOT_FOUND, RA_LOAD_PROPERTIES_SUC, RA_NETWORK_ALREADY_EXIST, RA_UPDATE_NETWORK_ERR, RA_CREATE_STACK_ERR, RA_UPDATE_STACK_ERR, RA_CREATE_TENANT_ERR, RA_NETWORK_NOT_FOUND, RA_NETWORK_ORCHE_MODE_NOT_SUPPORT, RA_CREATE_NETWORK_EXC, RA_NS_EXC, RA_PARAM_NOT_FOUND, RA_CONFIG_EXC, RA_UNKOWN_PARAM, RA_VLAN_PARSE, RA_DELETE_NETWORK_EXC, RA_ROLLBACK_NULL, RA_TENANT_NOT_FOUND, RA_QUERY_NETWORK_EXC, RA_CREATE_NETWORK_NOTIF_EXC, RA_ASYNC_ROLLBACK, RA_WSDL_NOT_FOUND, RA_WSDL_URL_CONVENTION_EXC, RA_INIT_NOTIF_EXC, RA_SET_CALLBACK_AUTH_EXC, RA_FAULT_INFO_EXC, RA_MARSHING_ERROR, RA_PARSING_REQUEST_ERROR, RA_SEND_REQUEST_SDNC, RA_RESPONSE_FROM_SDNC, RA_EXCEPTION_COMMUNICATE_SDNC, RA_EVALUATE_XPATH_ERROR, RA_ANALYZE_ERROR_EXC, RA_ERROR_GET_RESPONSE_SDNC, RA_CALLBACK_BPEL, RA_INIT_CALLBACK_WSDL_ERR, RA_CALLBACK_BPEL_EXC, RA_CALLBACK_BPEL_COMPLETE, RA_SDNC_MISS_CONFIG_PARAM, RA_SDNC_INVALID_CONFIG, RA_PRINT_URL, RA_ERROR_CREATE_SDNC_REQUEST, RA_ERROR_CREATE_SDNC_RESPONSE, RA_ERROR_CONVERT_XML2STR, RA_RECEIVE_SDNC_NOTIF, RA_INIT_SDNC_ADAPTER, RA_SEND_REQUEST_APPC_ERR, RA_SEND_REQUEST_SDNC_ERR, RA_RECEIVE_BPEL_REQUEST, RA_TENANT_ALREADY_EXIST, RA_UPDATE_TENANT_ERR, RA_DELETE_TEMAMT_ERR, RA_ROLLBACK_TENANT_ERR, RA_QUERY_VNF_ERR, RA_VNF_ALREADY_EXIST, RA_VNF_UNKNOWN_PARAM, RA_VNF_EXTRA_PARAM, RA_CREATE_VNF_ERR, RA_VNF_NOT_EXIST, RA_UPDATE_VNF_ERR, RA_DELETE_VNF_ERR, RA_ASYNC_CREATE_VNF, RA_SEND_VNF_NOTIF_ERR, RA_ASYNC_CREATE_VNF_COMPLETE, RA_ASYNC_UPDATE_VNF, RA_ASYNC_UPDATE_VNF_COMPLETE, RA_ASYNC_QUERY_VNF, RA_ASYNC_QUERY_VNF_COMPLETE, RA_ASYNC_DELETE_VNF, RA_ASYNC_DELETE_VNF_COMPLETE, RA_ASYNC_ROLLBACK_VNF, RA_ASYNC_ROLLBACK_VNF_COMPLETE, RA_ROLLBACK_VNF_ERR, RA_DB_INVALID_STATUS, RA_CANT_UPDATE_REQUEST, RA_DB_REQUEST_NOT_EXIST, RA_CONFIG_NOT_FOUND, RA_CONFIG_LOAD, RA_RECEIVE_WORKFLOW_MESSAGE,
+ // BPEL engine Messages
+ BPMN_GENERAL_INFO, BPMN_GENERAL_EXCEPTION_ARG, BPMN_GENERAL_EXCEPTION, BPMN_GENERAL_WARNING, BPMN_AUDIT_EXEC, BPMN_GENERAL_METRICS, BPMN_URN_MAPPING_FAIL, BPMN_VARIABLE_NULL, BPMN_CALLBACK_EXCEPTION,
+ // ASDC Messages
+ ASDC_GENERAL_EXCEPTION_ARG, ASDC_GENERAL_EXCEPTION, ASDC_GENERAL_WARNING, ASDC_GENERAL_INFO, ASDC_AUDIT_EXEC, ASDC_GENERAL_METRICS, ASDC_CREATE_SERVICE, ASDC_ARTIFACT_ALREADY_DEPLOYED, ASDC_CREATE_ARTIFACT, ASDC_ARTIFACT_INSTALL_EXC, ASDC_ARTIFACT_ALREADY_DEPLOYED_DETAIL, ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL, ASDC_ARTIFACT_CHECK_EXC, ASDC_INIT_ASDC_CLIENT_EXC, ASDC_INIT_ASDC_CLIENT_SUC, ASDC_LOAD_ASDC_CLIENT_EXC, ASDC_SINGLETON_CHECKT_EXC, ASDC_SHUTDOWN_ASDC_CLIENT_EXC, ASDC_CHECK_HEAT_TEMPLATE, ASDC_START_INSTALL_ARTIFACT, ASDC_ARTIFACT_TYPE_NOT_SUPPORT, ASDC_ARTIFACT_ALREADY_EXIST, ASDC_ARTIFACT_DOWNLOAD_SUC, ASDC_ARTIFACT_DOWNLOAD_FAIL, ASDC_START_DEPLOY_ARTIFACT, ASDC_SEND_NOTIF_ASDC, ASDC_SEND_NOTIF_ASDC_EXEC, ASDC_RECEIVE_CALLBACK_NOTIF, ASDC_RECEIVE_SERVICE_NOTIF, ASDC_ARTIFACT_NULL, ASDC_SERVICE_NOT_SUPPORT, ASDC_ARTIFACT_DEPLOY_SUC, ASDC_PROPERTIES_NOT_FOUND, ASDC_PROPERTIES_LOAD_SUCCESS,
+ // Default Messages, in case Log catalog is not defined
+ GENERAL_EXCEPTION_ARG, GENERAL_EXCEPTION, GENERAL_WARNING, AUDIT_EXEC, GENERAL_METRICS, LOGGER_SETUP, LOGGER_NOT_FOUND, LOGGER_UPDATE_SUC, LOGGER_UPDATE_DEBUG, LOGGER_UPDATE_DEBUG_SUC, LOAD_PROPERTIES_SUC, NO_PROPERTIES, MADATORY_PARAM_MISSING, LOAD_PROPERTIES_FAIL, INIT_LOGGER, INIT_LOGGER_FAIL, JAXB_EXCEPTION, IDENTITY_SERVICE_NOT_FOUND;
}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java
index 436faef27f..975f6bb9d8 100644
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java
@@ -54,22 +54,22 @@ import java.util.UUID;
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Component
@Priority(0)
-public class JaxRsClientLogging implements ClientRequestFilter,ClientResponseFilter {
-
- @Context
+public class JaxRsClientLogging implements ClientRequestFilter, ClientResponseFilter {
+
+ @Context
private Providers providers;
private static final String TRACE = "trace-#";
private static final String SO = "SO";
private static Logger logger = LoggerFactory.getLogger(JaxRsClientLogging.class);
- public void setTargetService(TargetEntity targetEntity){
+ public void setTargetService(TargetEntity targetEntity) {
MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity.toString());
}
@Override
public void filter(ClientRequestContext clientRequest) {
- try{
+ try {
setupMDC(clientRequest);
setupHeaders(clientRequest);
logger.info(ONAPLogConstants.Markers.INVOKE, "Invoke");
@@ -86,26 +86,27 @@ public class JaxRsClientLogging implements ClientRequestFilter,ClientResponseFil
}
private void setupMDC(ClientRequestContext clientRequest) {
- MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
+ MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP,
+ ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, clientRequest.getUri().toString());
MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
setInvocationId();
- MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY,MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY));
+ MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY));
}
private String extractRequestID(ClientRequestContext clientRequest) {
String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
- if(requestId == null || requestId.isEmpty() || requestId.equals(TRACE)){
+ if (requestId == null || requestId.isEmpty() || requestId.equals(TRACE)) {
requestId = UUID.randomUUID().toString();
- logger.warn("Could not Find Request ID Generating New One: {}",clientRequest.getUri().getPath());
+ logger.warn("Could not Find Request ID Generating New One: {}", clientRequest.getUri().getPath());
}
return requestId;
- }
+ }
private void setInvocationId() {
String invocationId = MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID);
- if(invocationId == null || invocationId.isEmpty())
- invocationId =UUID.randomUUID().toString();
+ if (invocationId == null || invocationId.isEmpty())
+ invocationId = UUID.randomUUID().toString();
MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
}
@@ -115,16 +116,17 @@ public class JaxRsClientLogging implements ClientRequestFilter,ClientResponseFil
try {
String statusCode;
- if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){
- statusCode=ONAPLogConstants.ResponseStatus.COMPLETED.toString();
- }else{
- statusCode=ONAPLogConstants.ResponseStatus.ERROR.toString();
+ if (Response.Status.Family.familyOf(responseContext.getStatus())
+ .equals(Response.Status.Family.SUCCESSFUL)) {
+ statusCode = ONAPLogConstants.ResponseStatus.COMPLETED.toString();
+ } else {
+ statusCode = ONAPLogConstants.ResponseStatus.ERROR.toString();
}
MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(responseContext.getStatus()));
MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
logger.info(ONAPLogConstants.Markers.INVOKE_RETURN, "InvokeReturn");
clearClientMDCs();
- } catch ( Exception e) {
+ } catch (Exception e) {
logger.warn("Error in outgoing JAX-RS Inteceptor", e);
}
}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java
index 7a99594d19..635d95be2e 100644
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java
@@ -51,16 +51,16 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@Priority(1)
@Provider
@Component
-public class JaxRsFilterLogging implements ContainerRequestFilter,ContainerResponseFilter {
-
+public class JaxRsFilterLogging implements ContainerRequestFilter, ContainerResponseFilter {
+
protected static Logger logger = LoggerFactory.getLogger(JaxRsFilterLogging.class);
@Context
private HttpServletRequest httpServletRequest;
- @Context
+ @Context
private Providers providers;
-
+
@Autowired
private MDCSetup mdcSetup;
@@ -78,7 +78,7 @@ public class JaxRsFilterLogging implements ContainerRequestFilter,ContainerRespo
mdcSetup.setInstanceUUID();
mdcSetup.setEntryTimeStamp();
MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
- MDC.put(LogConstants.URI_BASE, containerRequest.getUriInfo().getBaseUri().toString());
+ MDC.put(LogConstants.URI_BASE, containerRequest.getUriInfo().getBaseUri().toString());
logger.info(ONAPLogConstants.Markers.ENTRY, "Entering");
} catch (Exception e) {
logger.warn("Error in incoming JAX-RS Inteceptor", e);
@@ -90,78 +90,71 @@ public class JaxRsFilterLogging implements ContainerRequestFilter,ContainerRespo
throws IOException {
try {
setResponseStatusCode(responseContext);
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION,payloadMessage(responseContext));
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE,String.valueOf(responseContext.getStatus()));
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, payloadMessage(responseContext));
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(responseContext.getStatus()));
logger.info(ONAPLogConstants.Markers.EXIT, "Exiting.");
MDC.clear();
- } catch ( Exception e) {
+ } catch (Exception e) {
MDC.clear();
logger.warn("Error in outgoing JAX-RS Inteceptor", e);
- }
+ }
}
private void setResponseStatusCode(ContainerResponseContext responseContext) {
String statusCode;
- if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){
- statusCode=ONAPLogConstants.ResponseStatus.COMPLETED.toString();
- }else{
- statusCode= ONAPLogConstants.ResponseStatus.ERROR.toString();
- }
+ if (Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)) {
+ statusCode = ONAPLogConstants.ResponseStatus.COMPLETED.toString();
+ } else {
+ statusCode = ONAPLogConstants.ResponseStatus.ERROR.toString();
+ }
MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
- }
+ }
private String payloadMessage(ContainerResponseContext responseContext) throws IOException {
String message = "";
if (responseContext.hasEntity()) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
Class<?> entityClass = responseContext.getEntityClass();
Type entityType = responseContext.getEntityType();
Annotation[] entityAnnotations = responseContext.getEntityAnnotations();
MediaType mediaType = responseContext.getMediaType();
@SuppressWarnings("unchecked")
- MessageBodyWriter<Object> bodyWriter = (MessageBodyWriter<Object>) providers.getMessageBodyWriter(entityClass,
- entityType,
- entityAnnotations,
- mediaType);
- bodyWriter.writeTo(responseContext.getEntity(),
- entityClass,
- entityType,
- entityAnnotations,
- mediaType,
- responseContext.getHeaders(),
- baos);
+ MessageBodyWriter<Object> bodyWriter = (MessageBodyWriter<Object>) providers
+ .getMessageBodyWriter(entityClass, entityType, entityAnnotations, mediaType);
+ bodyWriter.writeTo(responseContext.getEntity(), entityClass, entityType, entityAnnotations, mediaType,
+ responseContext.getHeaders(), baos);
message = message.concat(new String(baos.toByteArray()));
}
return message;
}
- private void setRequestId(MultivaluedMap<String, String> headers){
- String requestId=headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID);
- if(requestId == null || requestId.isEmpty())
+ private void setRequestId(MultivaluedMap<String, String> headers) {
+ String requestId = headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID);
+ if (requestId == null || requestId.isEmpty())
requestId = UUID.randomUUID().toString();
- MDC.put(ONAPLogConstants.MDCs.REQUEST_ID,requestId);
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
}
- private void setInvocationId(MultivaluedMap<String, String> headers){
+ private void setInvocationId(MultivaluedMap<String, String> headers) {
MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, findInvocationId(headers));
}
- private void setMDCPartnerName(MultivaluedMap<String, String> headers){
- String partnerName=headers.getFirst(ONAPLogConstants.Headers.PARTNER_NAME);
- if(partnerName == null || partnerName.isEmpty())
+ private void setMDCPartnerName(MultivaluedMap<String, String> headers) {
+ String partnerName = headers.getFirst(ONAPLogConstants.Headers.PARTNER_NAME);
+ if (partnerName == null || partnerName.isEmpty())
partnerName = "";
- MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME,partnerName);
+ MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName);
}
-
+
private String findInvocationId(MultivaluedMap<String, String> headers) {
String invocationId = headers.getFirst(ONAPLogConstants.Headers.INVOCATION_ID);
- if(invocationId == null || invocationId.isEmpty())
- invocationId =UUID.randomUUID().toString();
+ if (invocationId == null || invocationId.isEmpty())
+ invocationId = UUID.randomUUID().toString();
return invocationId;
}
- private void setServiceName(ContainerRequestContext containerRequest){
+ private void setServiceName(ContainerRequestContext containerRequest) {
MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, containerRequest.getUriInfo().getPath());
}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java
index f0a16561aa..607f067ec4 100644
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java
@@ -38,18 +38,18 @@ import org.springframework.stereotype.Component;
@Component
public class MDCSetup {
-
- protected static Logger logger = LoggerFactory.getLogger(MDCSetup.class);
-
+
+ protected static Logger logger = LoggerFactory.getLogger(MDCSetup.class);
+
private static final String INSTANCE_UUID = UUID.randomUUID().toString();
-
- public void setInstanceUUID(){
+
+ public void setInstanceUUID() {
MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, INSTANCE_UUID);
}
- public void setServerFQDN(){
+ public void setServerFQDN() {
String serverFQDN = "";
- InetAddress addr= null;
+ InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
serverFQDN = addr.toString();
@@ -60,51 +60,52 @@ public class MDCSetup {
MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, serverFQDN);
}
- public void setClientIPAddress(HttpServletRequest httpServletRequest){
+ public void setClientIPAddress(HttpServletRequest httpServletRequest) {
String remoteIpAddress = "";
if (httpServletRequest != null) {
remoteIpAddress = httpServletRequest.getRemoteAddr();
- }
+ }
MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, remoteIpAddress);
}
public void setEntryTimeStamp() {
- MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
+ MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,
+ ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
}
-
+
public void setServiceName(HttpServletRequest request) {
MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI());
}
public void setRequestId(Map<String, String> headers) {
- String requestId=headers.get(ONAPLogConstants.Headers.REQUEST_ID);
- if(requestId == null || requestId.isEmpty())
+ String requestId = headers.get(ONAPLogConstants.Headers.REQUEST_ID);
+ if (requestId == null || requestId.isEmpty())
requestId = UUID.randomUUID().toString();
- MDC.put(ONAPLogConstants.MDCs.REQUEST_ID,requestId);
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
}
public void setInvocationId(Map<String, String> headers) {
String invocationId = headers.get(ONAPLogConstants.Headers.INVOCATION_ID);
- if(invocationId == null || invocationId.isEmpty())
- invocationId =UUID.randomUUID().toString();
+ if (invocationId == null || invocationId.isEmpty())
+ invocationId = UUID.randomUUID().toString();
MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
}
public void setMDCPartnerName(Map<String, String> headers) {
- String partnerName=headers.get(ONAPLogConstants.Headers.PARTNER_NAME);
- if(partnerName == null || partnerName.isEmpty())
+ String partnerName = headers.get(ONAPLogConstants.Headers.PARTNER_NAME);
+ if (partnerName == null || partnerName.isEmpty())
partnerName = "";
- MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME,partnerName);
+ MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName);
}
-
+
public void setResponseStatusCode(HttpServletResponse response) {
String statusCode;
- if(Response.Status.Family.familyOf(response.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){
- statusCode=ONAPLogConstants.ResponseStatus.COMPLETED.toString();
- }else{
- statusCode= ONAPLogConstants.ResponseStatus.ERROR.toString();
- }
+ if (Response.Status.Family.familyOf(response.getStatus()).equals(Response.Status.Family.SUCCESSFUL)) {
+ statusCode = ONAPLogConstants.ResponseStatus.COMPLETED.toString();
+ } else {
+ statusCode = ONAPLogConstants.ResponseStatus.ERROR.toString();
+ }
MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
}
}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCTaskDecorator.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCTaskDecorator.java
index 9624dcd578..e644f9e030 100644
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCTaskDecorator.java
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCTaskDecorator.java
@@ -21,24 +21,23 @@
package org.onap.so.logging.jaxrs.filter;
import java.util.Map;
-
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;
public class MDCTaskDecorator implements TaskDecorator {
-
- @Override
- public Runnable decorate(Runnable runnable) {
- Map<String, String> contextMap = MDC.getCopyOfContextMap();
- return () -> {
- try {
- if(contextMap!=null){
- MDC.setContextMap(contextMap);
- runnable.run();
- }
- } finally {
- MDC.clear();
- }
- };
- }
-} \ No newline at end of file
+
+ @Override
+ public Runnable decorate(Runnable runnable) {
+ Map<String, String> contextMap = MDC.getCopyOfContextMap();
+ return () -> {
+ try {
+ if (contextMap != null) {
+ MDC.setContextMap(contextMap);
+ runnable.run();
+ }
+ } finally {
+ MDC.clear();
+ }
+ };
+ }
+}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java
index 7f88f22b79..21c0b52a91 100644
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java
@@ -28,7 +28,6 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
-
import javax.annotation.Priority;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.ClientRequestContext;
@@ -38,7 +37,6 @@ import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -47,112 +45,114 @@ import org.slf4j.LoggerFactory;
@Priority(1)
public class PayloadLoggingFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor {
- private static final Logger logger = LoggerFactory.getLogger(PayloadLoggingFilter.class);
- private static final String ENTITY_STREAM_PROPERTY = "LoggingFilter.entityStream";
- private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
- private final int maxEntitySize;
-
- public PayloadLoggingFilter() {
- maxEntitySize = 1024 * 1024;
- }
-
- public PayloadLoggingFilter(int maxPayloadSize) {
- this.maxEntitySize = Integer.min(maxPayloadSize, 1024 * 1024);
- }
-
- private void log(StringBuilder sb) {
- logger.debug(sb.toString());
- }
-
- protected InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset)
- throws IOException {
- if (!stream.markSupported()) {
- stream = new BufferedInputStream(stream);
- }
- stream.mark(maxEntitySize + 1);
- final byte[] entity = new byte[maxEntitySize + 1];
- final int entitySize = stream.read(entity);
- if (entitySize != -1) {
- b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset));
- }
- if (entitySize > maxEntitySize) {
- b.append("...more...");
- }
- b.append('\n');
- stream.reset();
- return stream;
- }
-
- @Override
- public void filter(ClientRequestContext requestContext) throws IOException {
- if (requestContext.hasEntity()) {
- final OutputStream stream = new LoggingStream(requestContext.getEntityStream());
- requestContext.setEntityStream(stream);
- requestContext.setProperty(ENTITY_STREAM_PROPERTY, stream);
- }
- String method = formatMethod(requestContext);
- log(new StringBuilder("Making " + method + " request to: " + requestContext.getUri() + "\nRequest Headers: " + requestContext.getHeaders().toString()));
-
- }
-
- @Override
- public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
- final StringBuilder sb = new StringBuilder();
- if (responseContext.hasEntity()) {
- responseContext.setEntityStream(logInboundEntity(sb, responseContext.getEntityStream(), DEFAULT_CHARSET));
- String method = formatMethod(requestContext);
- log(sb.insert(0, "Response from " + method + ": " + requestContext.getUri() + "\nResponse Headers: " + responseContext.getHeaders().toString()));
- }
- }
-
- @Override
- public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
- final LoggingStream stream = (LoggingStream) context.getProperty(ENTITY_STREAM_PROPERTY);
- context.proceed();
- if (stream != null) {
- log(stream.getStringBuilder(DEFAULT_CHARSET));
- }
- }
-
- private class LoggingStream extends FilterOutputStream {
-
- private final StringBuilder sb = new StringBuilder();
- private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- LoggingStream(OutputStream out) {
- super(out);
- }
-
- StringBuilder getStringBuilder(Charset charset) {
- // write entity to the builder
- final byte[] entity = baos.toByteArray();
-
- sb.append(new String(entity, 0, entity.length, charset));
- if (entity.length > maxEntitySize) {
- sb.append("...more...");
- }
- sb.append('\n');
-
- return sb;
- }
-
- @Override
- public void write(final int i) throws IOException {
- if (baos.size() <= maxEntitySize) {
- baos.write(i);
- }
- out.write(i);
- }
- }
-
- private String formatMethod(ClientRequestContext requestContext) {
- String method = requestContext.getHeaderString("X-HTTP-Method-Override");
- if (method == null) {
- method = requestContext.getMethod();
- } else {
- method = requestContext.getMethod() + " (overridden to " + method + ")";
- }
-
- return method;
- }
+ private static final Logger logger = LoggerFactory.getLogger(PayloadLoggingFilter.class);
+ private static final String ENTITY_STREAM_PROPERTY = "LoggingFilter.entityStream";
+ private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
+ private final int maxEntitySize;
+
+ public PayloadLoggingFilter() {
+ maxEntitySize = 1024 * 1024;
+ }
+
+ public PayloadLoggingFilter(int maxPayloadSize) {
+ this.maxEntitySize = Integer.min(maxPayloadSize, 1024 * 1024);
+ }
+
+ private void log(StringBuilder sb) {
+ logger.debug(sb.toString());
+ }
+
+ protected InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset)
+ throws IOException {
+ if (!stream.markSupported()) {
+ stream = new BufferedInputStream(stream);
+ }
+ stream.mark(maxEntitySize + 1);
+ final byte[] entity = new byte[maxEntitySize + 1];
+ final int entitySize = stream.read(entity);
+ if (entitySize != -1) {
+ b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset));
+ }
+ if (entitySize > maxEntitySize) {
+ b.append("...more...");
+ }
+ b.append('\n');
+ stream.reset();
+ return stream;
+ }
+
+ @Override
+ public void filter(ClientRequestContext requestContext) throws IOException {
+ if (requestContext.hasEntity()) {
+ final OutputStream stream = new LoggingStream(requestContext.getEntityStream());
+ requestContext.setEntityStream(stream);
+ requestContext.setProperty(ENTITY_STREAM_PROPERTY, stream);
+ }
+ String method = formatMethod(requestContext);
+ log(new StringBuilder("Making " + method + " request to: " + requestContext.getUri() + "\nRequest Headers: "
+ + requestContext.getHeaders().toString()));
+
+ }
+
+ @Override
+ public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
+ final StringBuilder sb = new StringBuilder();
+ if (responseContext.hasEntity()) {
+ responseContext.setEntityStream(logInboundEntity(sb, responseContext.getEntityStream(), DEFAULT_CHARSET));
+ String method = formatMethod(requestContext);
+ log(sb.insert(0, "Response from " + method + ": " + requestContext.getUri() + "\nResponse Headers: "
+ + responseContext.getHeaders().toString()));
+ }
+ }
+
+ @Override
+ public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
+ final LoggingStream stream = (LoggingStream) context.getProperty(ENTITY_STREAM_PROPERTY);
+ context.proceed();
+ if (stream != null) {
+ log(stream.getStringBuilder(DEFAULT_CHARSET));
+ }
+ }
+
+ private class LoggingStream extends FilterOutputStream {
+
+ private final StringBuilder sb = new StringBuilder();
+ private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ LoggingStream(OutputStream out) {
+ super(out);
+ }
+
+ StringBuilder getStringBuilder(Charset charset) {
+ // write entity to the builder
+ final byte[] entity = baos.toByteArray();
+
+ sb.append(new String(entity, 0, entity.length, charset));
+ if (entity.length > maxEntitySize) {
+ sb.append("...more...");
+ }
+ sb.append('\n');
+
+ return sb;
+ }
+
+ @Override
+ public void write(final int i) throws IOException {
+ if (baos.size() <= maxEntitySize) {
+ baos.write(i);
+ }
+ out.write(i);
+ }
+ }
+
+ private String formatMethod(ClientRequestContext requestContext) {
+ String method = requestContext.getHeaderString("X-HTTP-Method-Override");
+ if (method == null) {
+ method = requestContext.getMethod();
+ } else {
+ method = requestContext.getMethod() + " (overridden to " + method + ")";
+ }
+
+ return method;
+ }
}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java
index ed63a706a2..c763dd4374 100644
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java
@@ -31,7 +31,6 @@ import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;
-
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.ZoneOffset;
@@ -40,26 +39,27 @@ import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
import javax.ws.rs.core.Response;
-
+
public class SpringClientFilter implements ClientHttpRequestInterceptor {
-
+
private final Logger log = LoggerFactory.getLogger(this.getClass());
-
+
private static final String TRACE = "trace-#";
private static final String SO = "SO";
-
+
@Override
- public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
- processRequest(request, body);
+ public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
+ throws IOException {
+ processRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
processResponse(response);
return response;
}
-
+
private void processRequest(HttpRequest request, byte[] body) throws IOException {
- setInvocationId();
- setupHeaders(request);
- setupMDC(request);
+ setInvocationId();
+ setupHeaders(request);
+ setupMDC(request);
if (log.isDebugEnabled()) {
log.debug("===========================request begin================================================");
log.debug("URI : {}", request.getURI());
@@ -69,58 +69,57 @@ public class SpringClientFilter implements ClientHttpRequestInterceptor {
log.debug("==========================request end================================================");
}
}
-
+
private void setupHeaders(HttpRequest clientRequest) {
HttpHeaders headers = clientRequest.getHeaders();
headers.add(ONAPLogConstants.Headers.REQUEST_ID, extractRequestID(clientRequest));
headers.add(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID));
headers.add(ONAPLogConstants.Headers.PARTNER_NAME, SO);
}
-
+
private String extractRequestID(HttpRequest clientRequest) {
String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
- if(requestId == null || requestId.isEmpty() || requestId.equals(TRACE)){
+ if (requestId == null || requestId.isEmpty() || requestId.equals(TRACE)) {
requestId = UUID.randomUUID().toString();
- log.warn("Could not Find Request ID Generating New One: {}",clientRequest.getURI());
+ log.warn("Could not Find Request ID Generating New One: {}", clientRequest.getURI());
}
return requestId;
- }
+ }
private void setupMDC(HttpRequest clientRequest) {
- MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
- MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, clientRequest.getURI().toString());
+ MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP,
+ ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
+ MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, clientRequest.getURI().toString());
MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
- MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY,extractTargetEntity(clientRequest));
+ MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, extractTargetEntity(clientRequest));
}
-
+
private String extractTargetEntity(HttpRequest clientRequest) {
- HttpHeaders headers = clientRequest.getHeaders();
- String headerTargetEntity = null;
- List<String> headerTargetEntityList = headers.get(LogConstants.TARGET_ENTITY_HEADER);
- if(headerTargetEntityList!= null && !headerTargetEntityList.isEmpty())
- headerTargetEntity = headerTargetEntityList.get(0);
+ HttpHeaders headers = clientRequest.getHeaders();
+ String headerTargetEntity = null;
+ List<String> headerTargetEntityList = headers.get(LogConstants.TARGET_ENTITY_HEADER);
+ if (headerTargetEntityList != null && !headerTargetEntityList.isEmpty())
+ headerTargetEntity = headerTargetEntityList.get(0);
String targetEntity = MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY);
- if(targetEntity != null &&
- !targetEntity.isEmpty() ){
- return targetEntity;
- }else if(headerTargetEntity != null &&
- !headerTargetEntity.isEmpty()){
- targetEntity = headerTargetEntity;
- }else{
- targetEntity = LogConstants.UNKNOWN_TARGET_ENTITY;
- log.warn("Could not Target Entity: {}",clientRequest.getURI());
+ if (targetEntity != null && !targetEntity.isEmpty()) {
+ return targetEntity;
+ } else if (headerTargetEntity != null && !headerTargetEntity.isEmpty()) {
+ targetEntity = headerTargetEntity;
+ } else {
+ targetEntity = LogConstants.UNKNOWN_TARGET_ENTITY;
+ log.warn("Could not Target Entity: {}", clientRequest.getURI());
}
return targetEntity;
- }
-
+ }
+
private void setInvocationId() {
String invocationId = MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID);
- if(invocationId == null || invocationId.isEmpty())
- invocationId =UUID.randomUUID().toString();
+ if (invocationId == null || invocationId.isEmpty())
+ invocationId = UUID.randomUUID().toString();
MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
}
-
+
private void processResponse(ClientHttpResponse response) throws IOException {
if (log.isDebugEnabled()) {
log.debug("============================response begin==========================================");
@@ -131,18 +130,18 @@ public class SpringClientFilter implements ClientHttpRequestInterceptor {
log.debug("=======================response end=================================================");
}
String statusCode;
- if(Response.Status.Family.familyOf(response.getRawStatusCode()).equals(Response.Status.Family.SUCCESSFUL)){
- statusCode=ONAPLogConstants.ResponseStatus.COMPLETED.toString();
- }else{
- statusCode=ONAPLogConstants.ResponseStatus.ERROR.toString();
+ if (Response.Status.Family.familyOf(response.getRawStatusCode()).equals(Response.Status.Family.SUCCESSFUL)) {
+ statusCode = ONAPLogConstants.ResponseStatus.COMPLETED.toString();
+ } else {
+ statusCode = ONAPLogConstants.ResponseStatus.ERROR.toString();
}
MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(response.getRawStatusCode()));
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION,"");
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, "");
MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
log.info(ONAPLogConstants.Markers.INVOKE_RETURN, "InvokeReturn");
clearClientMDCs();
}
-
+
private void clearClientMDCs() {
MDC.remove(ONAPLogConstants.MDCs.INVOCATION_ID);
MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION);
diff --git a/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java b/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java
index 9aa4e4c9b5..8e7a95b581 100644
--- a/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java
+++ b/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java
@@ -47,16 +47,15 @@ public class LoggingInterceptor extends HandlerInterceptorAdapter {
@Autowired
private MDCSetup mdcSetup;
-
- @Context
+
+ @Context
private Providers providers;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
-
- Map<String, String> headers = Collections.list((request).getHeaderNames())
- .stream()
+
+ Map<String, String> headers = Collections.list((request).getHeaderNames()).stream()
.collect(Collectors.toMap(h -> h, request::getHeader));
setRequestId(headers);
setInvocationId(headers);
@@ -68,69 +67,67 @@ public class LoggingInterceptor extends HandlerInterceptorAdapter {
mdcSetup.setServerFQDN();
MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
logger.info(ONAPLogConstants.Markers.ENTRY, "Entering");
- if (logger.isDebugEnabled())
- logRequestInformation(request);
+ if (logger.isDebugEnabled())
+ logRequestInformation(request);
return true;
}
-
+
protected void logRequestInformation(HttpServletRequest request) {
- Map<String, String> headers = Collections.list((request).getHeaderNames())
- .stream()
- .collect(Collectors.toMap(h -> h, request::getHeader));
-
- logger.debug("===========================request begin================================================");
- logger.debug("URI : {}", request.getRequestURI());
- logger.debug("Method : {}", request.getMethod());
- logger.debug("Headers : {}", headers);
- logger.debug("==========================request end================================================");
-
- }
-
- @Override
- public void postHandle(
- HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
- throws Exception {
+ Map<String, String> headers = Collections.list((request).getHeaderNames()).stream()
+ .collect(Collectors.toMap(h -> h, request::getHeader));
+
+ logger.debug("===========================request begin================================================");
+ logger.debug("URI : {}", request.getRequestURI());
+ logger.debug("Method : {}", request.getMethod());
+ logger.debug("Headers : {}", headers);
+ logger.debug("==========================request end================================================");
+
+ }
+
+ @Override
+ public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
+ ModelAndView modelAndView) throws Exception {
setResponseStatusCode(response);
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION,"");
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE,String.valueOf(response.getStatus()));
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, "");
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(response.getStatus()));
logger.info(ONAPLogConstants.Markers.EXIT, "Exiting.");
MDC.clear();
}
- protected void setResponseStatusCode(HttpServletResponse response) {
+ protected void setResponseStatusCode(HttpServletResponse response) {
String statusCode;
- if(Response.Status.Family.familyOf(response.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){
- statusCode=ONAPLogConstants.ResponseStatus.COMPLETED.toString();
- }else{
- statusCode= ONAPLogConstants.ResponseStatus.ERROR.toString();
- }
+ if (Response.Status.Family.familyOf(response.getStatus()).equals(Response.Status.Family.SUCCESSFUL)) {
+ statusCode = ONAPLogConstants.ResponseStatus.COMPLETED.toString();
+ } else {
+ statusCode = ONAPLogConstants.ResponseStatus.ERROR.toString();
+ }
MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
}
- protected void setServiceName(HttpServletRequest request) {
+ protected void setServiceName(HttpServletRequest request) {
MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI());
}
-
- protected void setRequestId(Map<String, String> headers) {
- String requestId=headers.get(ONAPLogConstants.Headers.REQUEST_ID.toLowerCase());
- if(requestId == null || requestId.isEmpty())
- requestId = UUID.randomUUID().toString();
- MDC.put(ONAPLogConstants.MDCs.REQUEST_ID,requestId);
+
+ protected void setRequestId(Map<String, String> headers) {
+ String requestId = headers.get(ONAPLogConstants.Headers.REQUEST_ID.toLowerCase());
+ if (requestId == null || requestId.isEmpty())
+ requestId = UUID.randomUUID().toString();
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
}
- protected void setInvocationId(Map<String, String> headers) {
+ protected void setInvocationId(Map<String, String> headers) {
String invocationId = headers.get(ONAPLogConstants.Headers.INVOCATION_ID.toLowerCase());
- if(invocationId == null || invocationId.isEmpty())
- invocationId =UUID.randomUUID().toString();
+ if (invocationId == null || invocationId.isEmpty())
+ invocationId = UUID.randomUUID().toString();
MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
}
- protected void setMDCPartnerName(Map<String, String> headers) {
- String partnerName=headers.get(ONAPLogConstants.Headers.PARTNER_NAME.toLowerCase());
- if(partnerName == null || partnerName.isEmpty())
+ protected void setMDCPartnerName(Map<String, String> headers) {
+ String partnerName = headers.get(ONAPLogConstants.Headers.PARTNER_NAME.toLowerCase());
+ if (partnerName == null || partnerName.isEmpty())
partnerName = "";
- MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME,partnerName);
+ MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName);
}
-
+
}
diff --git a/common/src/main/java/org/onap/so/openpojo/rules/CustomSetterMustExistRule.java b/common/src/main/java/org/onap/so/openpojo/rules/CustomSetterMustExistRule.java
index 2c6590afb3..204e98a031 100644
--- a/common/src/main/java/org/onap/so/openpojo/rules/CustomSetterMustExistRule.java
+++ b/common/src/main/java/org/onap/so/openpojo/rules/CustomSetterMustExistRule.java
@@ -23,9 +23,7 @@ package org.onap.so.openpojo.rules;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.anything;
import static org.hamcrest.CoreMatchers.not;
-
import org.hamcrest.Matcher;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoField;
import com.openpojo.validation.affirm.Affirm;
@@ -33,26 +31,29 @@ import com.openpojo.validation.rule.Rule;
public class CustomSetterMustExistRule implements Rule {
- private Matcher[] excludeMatchers = new Matcher[]{not(anything())};
- private Matcher<PojoField>[] includeMatchers = new Matcher[]{anything()};
- public CustomSetterMustExistRule() {
- }
- @Override
- public void evaluate(final PojoClass pojoClass) {
- for (PojoField fieldEntry : pojoClass.getPojoFields()) {
- if (!anyOf(excludeMatchers).matches(fieldEntry) && anyOf(includeMatchers).matches(fieldEntry) && !fieldEntry.isFinal() && !fieldEntry.hasSetter()) {
- Affirm.fail(String.format("[%s] is missing a setter", fieldEntry));
- }
- }
- }
- public CustomSetterMustExistRule exclude(Matcher... excludeMatchers) {
- this.excludeMatchers = excludeMatchers;
- return this;
- }
-
- public CustomSetterMustExistRule include(Matcher<PojoField>... includeMatchers) {
- this.includeMatchers = includeMatchers;
- return this;
- }
+ private Matcher[] excludeMatchers = new Matcher[] {not(anything())};
+ private Matcher<PojoField>[] includeMatchers = new Matcher[] {anything()};
+
+ public CustomSetterMustExistRule() {}
+
+ @Override
+ public void evaluate(final PojoClass pojoClass) {
+ for (PojoField fieldEntry : pojoClass.getPojoFields()) {
+ if (!anyOf(excludeMatchers).matches(fieldEntry) && anyOf(includeMatchers).matches(fieldEntry)
+ && !fieldEntry.isFinal() && !fieldEntry.hasSetter()) {
+ Affirm.fail(String.format("[%s] is missing a setter", fieldEntry));
+ }
+ }
+ }
+
+ public CustomSetterMustExistRule exclude(Matcher... excludeMatchers) {
+ this.excludeMatchers = excludeMatchers;
+ return this;
+ }
+
+ public CustomSetterMustExistRule include(Matcher<PojoField>... includeMatchers) {
+ this.includeMatchers = includeMatchers;
+ return this;
+ }
}
diff --git a/common/src/main/java/org/onap/so/openpojo/rules/EqualsAndHashCodeTester.java b/common/src/main/java/org/onap/so/openpojo/rules/EqualsAndHashCodeTester.java
index 05f69caacd..e63e226457 100644
--- a/common/src/main/java/org/onap/so/openpojo/rules/EqualsAndHashCodeTester.java
+++ b/common/src/main/java/org/onap/so/openpojo/rules/EqualsAndHashCodeTester.java
@@ -24,18 +24,14 @@ package org.onap.so.openpojo.rules;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.anything;
-
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
-
import org.hamcrest.Matcher;
-
import com.openpojo.business.annotation.BusinessKey;
import com.openpojo.random.RandomFactory;
import com.openpojo.reflection.PojoClass;
@@ -46,90 +42,93 @@ import com.openpojo.validation.utils.ValidationHelper;
public class EqualsAndHashCodeTester implements Tester {
-
- private final Matcher m;
- private boolean onlyDeclaredMethods = false;
- public EqualsAndHashCodeTester() {
- m = anything();
- }
-
- public EqualsAndHashCodeTester(Matcher m) {
- this.m = m;
- }
-
- public EqualsAndHashCodeTester onlyDeclaredMethods() {
- this.onlyDeclaredMethods = true;
- return this;
- }
-
- // Marks sonar warnings about object being compared to itself as false positive
- // https://sonar.onap.org/coding_rules#rule_key=squid%3AS1764
- @SuppressWarnings("squid:S1764")
- @Override
- public void run(PojoClass pojoClass) {
- Class<?> clazz = pojoClass.getClazz();
- if (anyOf(m).matches(clazz)) {
- final Object classInstanceOne = ValidationHelper.getBasicInstance(pojoClass);
- final Object classInstanceTwo = ValidationHelper.getBasicInstance(pojoClass);
- if (onlyDeclaredMethods) {
- Method[] methods = classInstanceOne.getClass().getDeclaredMethods();
- boolean hasEquals = false;
- boolean hasHashcode = false;
- for (Method method : methods) {
- if (method.getName().equals("equals")) {
- hasEquals = true;
- } else if (method.getName().equals("hashCode")) {
- hasHashcode = true;
- }
- }
-
- if (!(hasEquals && hasHashcode)) {
- return;
- }
- }
- Set<PojoField> identityFields = hasIdOrBusinessKey(pojoClass);
- List<PojoField> otherFields = new ArrayList<>(pojoClass.getPojoFields());
- otherFields.removeAll(identityFields);
-
- for (PojoField field : identityFields) {
- final Object value = RandomFactory.getRandomValue(field);
-
- field.invokeSetter(classInstanceOne, value);
- field.invokeSetter(classInstanceTwo, value);
- }
-
- for (PojoField field : otherFields) {
- if (field.hasSetter()) {
- final Object valueOne = RandomFactory.getRandomValue(field);
- final Object valueTwo = RandomFactory.getRandomValue(field);
-
- field.invokeSetter(classInstanceOne, valueOne);
- field.invokeSetter(classInstanceTwo, valueTwo);
- }
- }
-
- Affirm.affirmTrue("Equals test failed for [" + classInstanceOne.getClass().getName() + "]", classInstanceOne.equals(classInstanceTwo));
-
- Affirm.affirmTrue("Expected true for comparison of the same references [" + classInstanceOne.getClass().getName() + "]",
- classInstanceOne.equals(classInstanceOne));
-
- Affirm.affirmTrue("HashCode test failed for [" + classInstanceOne.getClass().getName() + "]", classInstanceOne.hashCode() == classInstanceTwo.hashCode());
-
- Affirm.affirmFalse("Expected false for comparison of two unlike objects", classInstanceOne.equals("test"));
- }
- }
-
-
- private Set<PojoField> hasIdOrBusinessKey(PojoClass pojoClass) {
- final Set<PojoField> fields = new HashSet<>();
-
- fields.addAll(pojoClass.getPojoFieldsAnnotatedWith(BusinessKey.class));
- final Set<PojoField> temp = new HashSet<>();
- temp.addAll(pojoClass.getPojoFieldsAnnotatedWith(Id.class));
- temp.removeAll(pojoClass.getPojoFieldsAnnotatedWith(GeneratedValue.class));
- fields.addAll(temp);
- return fields;
-
- }
+
+ private final Matcher m;
+ private boolean onlyDeclaredMethods = false;
+
+ public EqualsAndHashCodeTester() {
+ m = anything();
+ }
+
+ public EqualsAndHashCodeTester(Matcher m) {
+ this.m = m;
+ }
+
+ public EqualsAndHashCodeTester onlyDeclaredMethods() {
+ this.onlyDeclaredMethods = true;
+ return this;
+ }
+
+ // Marks sonar warnings about object being compared to itself as false positive
+ // https://sonar.onap.org/coding_rules#rule_key=squid%3AS1764
+ @SuppressWarnings("squid:S1764")
+ @Override
+ public void run(PojoClass pojoClass) {
+ Class<?> clazz = pojoClass.getClazz();
+ if (anyOf(m).matches(clazz)) {
+ final Object classInstanceOne = ValidationHelper.getBasicInstance(pojoClass);
+ final Object classInstanceTwo = ValidationHelper.getBasicInstance(pojoClass);
+ if (onlyDeclaredMethods) {
+ Method[] methods = classInstanceOne.getClass().getDeclaredMethods();
+ boolean hasEquals = false;
+ boolean hasHashcode = false;
+ for (Method method : methods) {
+ if (method.getName().equals("equals")) {
+ hasEquals = true;
+ } else if (method.getName().equals("hashCode")) {
+ hasHashcode = true;
+ }
+ }
+
+ if (!(hasEquals && hasHashcode)) {
+ return;
+ }
+ }
+ Set<PojoField> identityFields = hasIdOrBusinessKey(pojoClass);
+ List<PojoField> otherFields = new ArrayList<>(pojoClass.getPojoFields());
+ otherFields.removeAll(identityFields);
+
+ for (PojoField field : identityFields) {
+ final Object value = RandomFactory.getRandomValue(field);
+
+ field.invokeSetter(classInstanceOne, value);
+ field.invokeSetter(classInstanceTwo, value);
+ }
+
+ for (PojoField field : otherFields) {
+ if (field.hasSetter()) {
+ final Object valueOne = RandomFactory.getRandomValue(field);
+ final Object valueTwo = RandomFactory.getRandomValue(field);
+
+ field.invokeSetter(classInstanceOne, valueOne);
+ field.invokeSetter(classInstanceTwo, valueTwo);
+ }
+ }
+
+ Affirm.affirmTrue("Equals test failed for [" + classInstanceOne.getClass().getName() + "]",
+ classInstanceOne.equals(classInstanceTwo));
+
+ Affirm.affirmTrue("Expected true for comparison of the same references ["
+ + classInstanceOne.getClass().getName() + "]", classInstanceOne.equals(classInstanceOne));
+
+ Affirm.affirmTrue("HashCode test failed for [" + classInstanceOne.getClass().getName() + "]",
+ classInstanceOne.hashCode() == classInstanceTwo.hashCode());
+
+ Affirm.affirmFalse("Expected false for comparison of two unlike objects", classInstanceOne.equals("test"));
+ }
+ }
+
+
+ private Set<PojoField> hasIdOrBusinessKey(PojoClass pojoClass) {
+ final Set<PojoField> fields = new HashSet<>();
+
+ fields.addAll(pojoClass.getPojoFieldsAnnotatedWith(BusinessKey.class));
+ final Set<PojoField> temp = new HashSet<>();
+ temp.addAll(pojoClass.getPojoFieldsAnnotatedWith(Id.class));
+ temp.removeAll(pojoClass.getPojoFieldsAnnotatedWith(GeneratedValue.class));
+ fields.addAll(temp);
+ return fields;
+
+ }
}
diff --git a/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationMatcher.java b/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationMatcher.java
index 6a06834d87..fc9bb388f4 100644
--- a/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationMatcher.java
+++ b/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationMatcher.java
@@ -21,51 +21,50 @@
package org.onap.so.openpojo.rules;
import static org.hamcrest.CoreMatchers.anything;
-
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
-
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
-
import com.openpojo.reflection.PojoField;
public class HasAnnotationMatcher<T extends PojoField> extends TypeSafeDiagnosingMatcher<T> {
- private final Class<? extends Annotation> annotationType;
- private final Matcher<? super T> annotationMatcher;
+ private final Class<? extends Annotation> annotationType;
+ private final Matcher<? super T> annotationMatcher;
- public HasAnnotationMatcher(final Class<? extends Annotation> annotationType, final Matcher<? super T> annotationMatcher) {
- this.annotationType = annotationType;
- this.annotationMatcher = annotationMatcher;
- }
+ public HasAnnotationMatcher(final Class<? extends Annotation> annotationType,
+ final Matcher<? super T> annotationMatcher) {
+ this.annotationType = annotationType;
+ this.annotationMatcher = annotationMatcher;
+ }
- @Override
- protected boolean matchesSafely(final PojoField item, final Description mismatchDescription) {
- final Annotation annotation = item.getAnnotation(this.annotationType);
- if (annotation == null) {
- mismatchDescription.appendText("does not have annotation ").appendText(this.annotationType.getName());
- return false;
- }
+ @Override
+ protected boolean matchesSafely(final PojoField item, final Description mismatchDescription) {
+ final Annotation annotation = item.getAnnotation(this.annotationType);
+ if (annotation == null) {
+ mismatchDescription.appendText("does not have annotation ").appendText(this.annotationType.getName());
+ return false;
+ }
- if (!this.annotationMatcher.matches(annotation)) {
- this.annotationMatcher.describeMismatch(annotation, mismatchDescription);
- return false;
- }
+ if (!this.annotationMatcher.matches(annotation)) {
+ this.annotationMatcher.describeMismatch(annotation, mismatchDescription);
+ return false;
+ }
- return true;
- }
+ return true;
+ }
- @Override
- public void describeTo(final Description description) {
- // Intentionally left blank.
- }
+ @Override
+ public void describeTo(final Description description) {
+ // Intentionally left blank.
+ }
- public static <T extends PojoField> Matcher<T> hasAnnotation(final Class<? extends Annotation> annotationType) {
- return hasAnnotation(annotationType, anything(""));
- }
+ public static <T extends PojoField> Matcher<T> hasAnnotation(final Class<? extends Annotation> annotationType) {
+ return hasAnnotation(annotationType, anything(""));
+ }
- public static <T extends PojoField> Matcher<T> hasAnnotation(final Class<? extends Annotation> annotationType, final Matcher<? super T> annotationMatcher) {
- return new HasAnnotationMatcher<T>(annotationType, annotationMatcher);
- }
+ public static <T extends PojoField> Matcher<T> hasAnnotation(final Class<? extends Annotation> annotationType,
+ final Matcher<? super T> annotationMatcher) {
+ return new HasAnnotationMatcher<T>(annotationType, annotationMatcher);
+ }
}
diff --git a/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationPropertyWithValueMatcher.java b/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationPropertyWithValueMatcher.java
index f76a27cce2..8a47299c73 100644
--- a/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationPropertyWithValueMatcher.java
+++ b/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationPropertyWithValueMatcher.java
@@ -25,56 +25,59 @@ package org.onap.so.openpojo.rules;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
-
import com.openpojo.reflection.PojoField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HasAnnotationPropertyWithValueMatcher<T extends PojoField> extends TypeSafeDiagnosingMatcher<T> {
- private Logger logger = LoggerFactory.getLogger(HasAnnotationPropertyWithValueMatcher.class);
- private final String attribute;
- private final Matcher<?> annotationMatcher;
- private final Class<? extends Annotation> annotationClass;
- public HasAnnotationPropertyWithValueMatcher(Class<? extends Annotation> clazz, String attribute, final Matcher<?> annotationMatcher) {
- this.attribute = attribute;
- this.annotationMatcher = annotationMatcher;
- this.annotationClass = clazz;
- }
+ private Logger logger = LoggerFactory.getLogger(HasAnnotationPropertyWithValueMatcher.class);
+ private final String attribute;
+ private final Matcher<?> annotationMatcher;
+ private final Class<? extends Annotation> annotationClass;
+
+ public HasAnnotationPropertyWithValueMatcher(Class<? extends Annotation> clazz, String attribute,
+ final Matcher<?> annotationMatcher) {
+ this.attribute = attribute;
+ this.annotationMatcher = annotationMatcher;
+ this.annotationClass = clazz;
+ }
- @Override
- protected boolean matchesSafely(T obj, final Description mismatchDescription) {
- final PojoField temp = (PojoField)obj;
- final Method method;
- try {
- Annotation a = temp.getAnnotation(this.annotationClass);
- if (a == null) {
- mismatchDescription.appendText("does not have annotation ").appendText(this.annotationClass.getSimpleName());
- return false;
- }
- method = a.getClass().getMethod(attribute);
- final Object result = method.invoke(a);
- if (!this.annotationMatcher.matches(result)) {
- this.annotationMatcher.describeMismatch(result, mismatchDescription);
- return false;
- }
- } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- mismatchDescription.appendText("does not have property ").appendText(attribute);
- logger.debug("Error occured", e);
- return false;
- }
- return true;
- }
+ @Override
+ protected boolean matchesSafely(T obj, final Description mismatchDescription) {
+ final PojoField temp = (PojoField) obj;
+ final Method method;
+ try {
+ Annotation a = temp.getAnnotation(this.annotationClass);
+ if (a == null) {
+ mismatchDescription.appendText("does not have annotation ")
+ .appendText(this.annotationClass.getSimpleName());
+ return false;
+ }
+ method = a.getClass().getMethod(attribute);
+ final Object result = method.invoke(a);
+ if (!this.annotationMatcher.matches(result)) {
+ this.annotationMatcher.describeMismatch(result, mismatchDescription);
+ return false;
+ }
+ } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
+ | InvocationTargetException e) {
+ mismatchDescription.appendText("does not have property ").appendText(attribute);
+ logger.debug("Error occured", e);
+ return false;
+ }
+ return true;
+ }
- @Override
- public void describeTo(final Description description) {
- // Intentionally left blank.
- }
+ @Override
+ public void describeTo(final Description description) {
+ // Intentionally left blank.
+ }
- public static <T extends PojoField> Matcher<T> hasAnnotationPropertyWithValue(Class<? extends Annotation> clazz, String attribute, final Matcher<?> annotationMatcher) {
- return new HasAnnotationPropertyWithValueMatcher<T>(clazz, attribute, annotationMatcher);
- }
+ public static <T extends PojoField> Matcher<T> hasAnnotationPropertyWithValue(Class<? extends Annotation> clazz,
+ String attribute, final Matcher<?> annotationMatcher) {
+ return new HasAnnotationPropertyWithValueMatcher<T>(clazz, attribute, annotationMatcher);
+ }
}
diff --git a/common/src/main/java/org/onap/so/openpojo/rules/HasEqualsAndHashCodeRule.java b/common/src/main/java/org/onap/so/openpojo/rules/HasEqualsAndHashCodeRule.java
index 0c7d6add73..351c5b0977 100644
--- a/common/src/main/java/org/onap/so/openpojo/rules/HasEqualsAndHashCodeRule.java
+++ b/common/src/main/java/org/onap/so/openpojo/rules/HasEqualsAndHashCodeRule.java
@@ -22,12 +22,9 @@ package org.onap.so.openpojo.rules;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.anything;
-
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
-
import org.hamcrest.Matcher;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.validation.affirm.Affirm;
import com.openpojo.validation.rule.Rule;
@@ -37,45 +34,46 @@ import com.openpojo.validation.rule.Rule;
*/
public class HasEqualsAndHashCodeRule implements Rule {
- private final Matcher m;
- public HasEqualsAndHashCodeRule() {
- m = anything();
- }
-
- public HasEqualsAndHashCodeRule(Matcher m) {
- this.m = m;
- }
- @Override
- public void evaluate(PojoClass pojoClass) {
- Class<?> clazz = pojoClass.getClazz();
- if (anyOf(m).matches(clazz)) {
- boolean hasEquals = false;
- boolean hasHashCode = false;
- final String name = clazz.getSimpleName();
- final Method[] methods;
- if (clazz.getSuperclass().equals(Object.class)) {
- methods = clazz.getDeclaredMethods();
- } else {
- methods = clazz.getMethods();
- }
- for (Method method : methods) {
- Parameter[] parameters = method.getParameters();
- if ("equals".equals(method.getName()) && boolean.class.equals(method.getReturnType()) && parameters.length == 1 && Object.class.equals(parameters[0].getType())) {
- hasEquals = true;
- } else if ("hashCode".equals(method.getName()) && int.class.equals(method.getReturnType())) {
- hasHashCode = true;
- }
- }
-
- if (!hasEquals) {
- Affirm.fail(String.format(
- "[%s] does not override equals", name));
- }
- if (!hasHashCode) {
- Affirm.fail(String.format(
- "[%s] does not override hashCode", name));
- }
- }
- }
+ private final Matcher m;
+
+ public HasEqualsAndHashCodeRule() {
+ m = anything();
+ }
+
+ public HasEqualsAndHashCodeRule(Matcher m) {
+ this.m = m;
+ }
+
+ @Override
+ public void evaluate(PojoClass pojoClass) {
+ Class<?> clazz = pojoClass.getClazz();
+ if (anyOf(m).matches(clazz)) {
+ boolean hasEquals = false;
+ boolean hasHashCode = false;
+ final String name = clazz.getSimpleName();
+ final Method[] methods;
+ if (clazz.getSuperclass().equals(Object.class)) {
+ methods = clazz.getDeclaredMethods();
+ } else {
+ methods = clazz.getMethods();
+ }
+ for (Method method : methods) {
+ Parameter[] parameters = method.getParameters();
+ if ("equals".equals(method.getName()) && boolean.class.equals(method.getReturnType())
+ && parameters.length == 1 && Object.class.equals(parameters[0].getType())) {
+ hasEquals = true;
+ } else if ("hashCode".equals(method.getName()) && int.class.equals(method.getReturnType())) {
+ hasHashCode = true;
+ }
+ }
+
+ if (!hasEquals) {
+ Affirm.fail(String.format("[%s] does not override equals", name));
+ }
+ if (!hasHashCode) {
+ Affirm.fail(String.format("[%s] does not override hashCode", name));
+ }
+ }
+ }
}
diff --git a/common/src/main/java/org/onap/so/openpojo/rules/HasToStringRule.java b/common/src/main/java/org/onap/so/openpojo/rules/HasToStringRule.java
index 8a4333e0e2..a55863122e 100644
--- a/common/src/main/java/org/onap/so/openpojo/rules/HasToStringRule.java
+++ b/common/src/main/java/org/onap/so/openpojo/rules/HasToStringRule.java
@@ -22,51 +22,50 @@ package org.onap.so.openpojo.rules;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.anything;
-
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
-
import org.hamcrest.Matcher;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.validation.affirm.Affirm;
import com.openpojo.validation.rule.Rule;
public class HasToStringRule implements Rule {
-
- private final Matcher m;
- public HasToStringRule() {
- m = anything();
- }
-
- public HasToStringRule(Matcher m) {
- this.m = m;
- }
- @Override
- public void evaluate(PojoClass pojoClass) {
- Class<?> clazz = pojoClass.getClazz();
- if (anyOf(m).matches(clazz)) {
- boolean hasToString = false;
- final String name = clazz.getSimpleName();
- final Method[] methods;
- if (clazz.getSuperclass().equals(Object.class)) {
- methods = clazz.getDeclaredMethods();
- } else {
- methods = clazz.getMethods();
- }
- for (Method method : methods) {
- Parameter[] parameters = method.getParameters();
- if ("toString".equals(method.getName()) && String.class.equals(method.getReturnType()) && parameters.length == 0) {
- hasToString = true;
- break;
- }
- }
-
- if (!hasToString) {
- Affirm.fail(String.format(
- "[%s] does not override toString", name));
- }
- }
- }
+
+ private final Matcher m;
+
+ public HasToStringRule() {
+ m = anything();
+ }
+
+ public HasToStringRule(Matcher m) {
+ this.m = m;
+ }
+
+ @Override
+ public void evaluate(PojoClass pojoClass) {
+ Class<?> clazz = pojoClass.getClazz();
+ if (anyOf(m).matches(clazz)) {
+ boolean hasToString = false;
+ final String name = clazz.getSimpleName();
+ final Method[] methods;
+ if (clazz.getSuperclass().equals(Object.class)) {
+ methods = clazz.getDeclaredMethods();
+ } else {
+ methods = clazz.getMethods();
+ }
+ for (Method method : methods) {
+ Parameter[] parameters = method.getParameters();
+ if ("toString".equals(method.getName()) && String.class.equals(method.getReturnType())
+ && parameters.length == 0) {
+ hasToString = true;
+ break;
+ }
+ }
+
+ if (!hasToString) {
+ Affirm.fail(String.format("[%s] does not override toString", name));
+ }
+ }
+ }
}
diff --git a/common/src/main/java/org/onap/so/openpojo/rules/ToStringTester.java b/common/src/main/java/org/onap/so/openpojo/rules/ToStringTester.java
index ff1a139768..5f1b5b61ba 100644
--- a/common/src/main/java/org/onap/so/openpojo/rules/ToStringTester.java
+++ b/common/src/main/java/org/onap/so/openpojo/rules/ToStringTester.java
@@ -22,9 +22,7 @@ package org.onap.so.openpojo.rules;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.anything;
-
import org.hamcrest.Matcher;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.validation.affirm.Affirm;
import com.openpojo.validation.test.Tester;
@@ -32,24 +30,26 @@ import com.openpojo.validation.utils.ValidationHelper;
public class ToStringTester implements Tester {
- private final Matcher m;
- public ToStringTester() {
- m = anything();
- }
-
- public ToStringTester(Matcher m) {
- this.m = m;
- }
-
- @Override
- public void run(PojoClass pojoClass) {
- Class<?> clazz = pojoClass.getClazz();
- if (anyOf(m).matches(clazz)) {
- final Object classInstance = ValidationHelper.getBasicInstance(pojoClass);
-
- Affirm.affirmFalse("Found default toString output", classInstance.toString().matches(Object.class.getName() + "@" + "\\w+"));
- }
-
- }
+ private final Matcher m;
+
+ public ToStringTester() {
+ m = anything();
+ }
+
+ public ToStringTester(Matcher m) {
+ this.m = m;
+ }
+
+ @Override
+ public void run(PojoClass pojoClass) {
+ Class<?> clazz = pojoClass.getClazz();
+ if (anyOf(m).matches(clazz)) {
+ final Object classInstance = ValidationHelper.getBasicInstance(pojoClass);
+
+ Affirm.affirmFalse("Found default toString output",
+ classInstance.toString().matches(Object.class.getName() + "@" + "\\w+"));
+ }
+
+ }
}
diff --git a/common/src/main/java/org/onap/so/properties/MsoDatabaseException.java b/common/src/main/java/org/onap/so/properties/MsoDatabaseException.java
index 84216af6e8..a7594789bc 100644
--- a/common/src/main/java/org/onap/so/properties/MsoDatabaseException.java
+++ b/common/src/main/java/org/onap/so/properties/MsoDatabaseException.java
@@ -35,17 +35,17 @@ public class MsoDatabaseException extends RuntimeException {
* @param message The message to dump
* @param cause The Throwable cause object
*/
- public MsoDatabaseException (final String message) {
- super (message);
-
+ public MsoDatabaseException(final String message) {
+ super(message);
+
}
-
+
/**
* @param message The message to dump
* @param cause The Throwable cause object
*/
- public MsoDatabaseException (final String message, final Throwable cause) {
- super (message, cause);
-
+ public MsoDatabaseException(final String message, final Throwable cause) {
+ super(message, cause);
+
}
}
diff --git a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java
index a3d16175bc..69046a2eba 100644
--- a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java
+++ b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java
@@ -87,14 +87,14 @@ public interface HttpRestServiceProvider {
*/
<T> ResponseEntity<T> putHttpRequest(final Object object, final String url, final Class<T> clazz);
- /**
- * Execute the HTTP DELETE to the given URI template
- *
- * @param url the URL
- * @param clazz the type of the return value
- * @return Returns the {@link ResponseEntity}.
- */
- public <T> ResponseEntity<T> deleteHttpRequest(final String url, final Class<T> clazz);
+ /**
+ * Execute the HTTP DELETE to the given URI template
+ *
+ * @param url the URL
+ * @param clazz the type of the return value
+ * @return Returns the {@link ResponseEntity}.
+ */
+ public <T> ResponseEntity<T> deleteHttpRequest(final String url, final Class<T> clazz);
}
diff --git a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java
index 029431c86e..8e6ebab43a 100644
--- a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java
+++ b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java
@@ -133,17 +133,18 @@ public class HttpRestServiceProviderImpl implements HttpRestServiceProvider {
}
}
- @Override
- public <T> ResponseEntity<T> deleteHttpRequest(final String url, final Class<T> clazz) {
- try {
- final HttpEntity<?> request = new HttpEntity<>(getHttpHeaders());
- return restTemplate.exchange(url, HttpMethod.DELETE, request, clazz);
-
- } catch (final RestClientException restClientException) {
- LOGGER.error("Unable to invoke HTTP DELETE using url: " + url, restClientException);
- throw new InvalidRestRequestException("Unable to invoke HTTP DELETE using URL: " + url, restClientException);
+ @Override
+ public <T> ResponseEntity<T> deleteHttpRequest(final String url, final Class<T> clazz) {
+ try {
+ final HttpEntity<?> request = new HttpEntity<>(getHttpHeaders());
+ return restTemplate.exchange(url, HttpMethod.DELETE, request, clazz);
+
+ } catch (final RestClientException restClientException) {
+ LOGGER.error("Unable to invoke HTTP DELETE using url: " + url, restClientException);
+ throw new InvalidRestRequestException("Unable to invoke HTTP DELETE using URL: " + url,
+ restClientException);
+ }
}
- }
private HttpHeaders getHttpHeaders() {
return httpHeadersProvider.getHttpHeaders();
diff --git a/common/src/main/java/org/onap/so/security/MSOSpringFirewall.java b/common/src/main/java/org/onap/so/security/MSOSpringFirewall.java
index 82a30f05be..441623a233 100644
--- a/common/src/main/java/org/onap/so/security/MSOSpringFirewall.java
+++ b/common/src/main/java/org/onap/so/security/MSOSpringFirewall.java
@@ -24,11 +24,11 @@ import org.springframework.security.web.firewall.StrictHttpFirewall;
public class MSOSpringFirewall extends StrictHttpFirewall {
-
- public MSOSpringFirewall() {
- super();
- this.setAllowUrlEncodedSlash(true);
- this.setAllowSemicolon(true);
- this.setAllowUrlEncodedPercent(true);
- }
+
+ public MSOSpringFirewall() {
+ super();
+ this.setAllowUrlEncodedSlash(true);
+ this.setAllowSemicolon(true);
+ this.setAllowUrlEncodedPercent(true);
+ }
}
diff --git a/common/src/main/java/org/onap/so/security/UserCredentials.java b/common/src/main/java/org/onap/so/security/UserCredentials.java
index f411789e00..d446af36d9 100644
--- a/common/src/main/java/org/onap/so/security/UserCredentials.java
+++ b/common/src/main/java/org/onap/so/security/UserCredentials.java
@@ -22,32 +22,32 @@ package org.onap.so.security;
public class UserCredentials {
- private String username;
- private String password;
- private String role;
+ private String username;
+ private String password;
+ private String role;
- public String getUsername() {
- return username;
- }
+ public String getUsername() {
+ return username;
+ }
- public void setUsername(String username) {
- this.username = username;
- }
+ public void setUsername(String username) {
+ this.username = username;
+ }
- public String getPassword() {
- return password;
- }
+ public String getPassword() {
+ return password;
+ }
- public void setPassword(String password) {
- this.password = password;
- }
+ public void setPassword(String password) {
+ this.password = password;
+ }
- public String getRole() {
- return role;
- }
+ public String getRole() {
+ return role;
+ }
- public void setRole(String role) {
- this.role = role;
- }
+ public void setRole(String role) {
+ this.role = role;
+ }
}
diff --git a/common/src/main/java/org/onap/so/security/UserDetailsServiceImpl.java b/common/src/main/java/org/onap/so/security/UserDetailsServiceImpl.java
index 90d484ebf4..91d5d7e612 100644
--- a/common/src/main/java/org/onap/so/security/UserDetailsServiceImpl.java
+++ b/common/src/main/java/org/onap/so/security/UserDetailsServiceImpl.java
@@ -30,27 +30,27 @@ import java.util.List;
@ConfigurationProperties(prefix = "spring.security")
public class UserDetailsServiceImpl implements UserDetailsService {
- private List<UserCredentials> usercredentials;
+ private List<UserCredentials> usercredentials;
- public List<UserCredentials> getUsercredentials() {
- return usercredentials;
- }
+ public List<UserCredentials> getUsercredentials() {
+ return usercredentials;
+ }
- public void setUsercredentials(List<UserCredentials> usercredentials) {
- this.usercredentials = usercredentials;
- }
+ public void setUsercredentials(List<UserCredentials> usercredentials) {
+ this.usercredentials = usercredentials;
+ }
- @Override
- public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
+ @Override
+ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
- for (int i = 0; usercredentials != null && i < usercredentials.size(); i++) {
- if (usercredentials.get(i).getUsername().equals(username)) {
- return User.withUsername(username).password(usercredentials.get(i).getPassword())
- .roles(usercredentials.get(i).getRole()).build();
- }
- }
+ for (int i = 0; usercredentials != null && i < usercredentials.size(); i++) {
+ if (usercredentials.get(i).getUsername().equals(username)) {
+ return User.withUsername(username).password(usercredentials.get(i).getPassword())
+ .roles(usercredentials.get(i).getRole()).build();
+ }
+ }
- throw new UsernameNotFoundException("User not found, username: " + username);
- }
+ throw new UsernameNotFoundException("User not found, username: " + username);
+ }
}
diff --git a/common/src/main/java/org/onap/so/security/WebSecurityConfig.java b/common/src/main/java/org/onap/so/security/WebSecurityConfig.java
index 11eec46f41..635784c642 100644
--- a/common/src/main/java/org/onap/so/security/WebSecurityConfig.java
+++ b/common/src/main/java/org/onap/so/security/WebSecurityConfig.java
@@ -22,9 +22,7 @@ package org.onap.so.security;
import java.util.ArrayList;
import java.util.List;
-
import javax.annotation.PostConstruct;
-
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
@@ -35,42 +33,42 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@ConfigurationProperties(prefix = "spring.security")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
-
- private List<UserCredentials> credentials;
- private List<String> roles = new ArrayList<>();
- public List<String> getRoles() {
- return roles;
- }
+ private List<UserCredentials> credentials;
+ private List<String> roles = new ArrayList<>();
+
+ public List<String> getRoles() {
+ return roles;
+ }
+
+ @PostConstruct
+ private void addRoles() {
+ for (int i = 0; i < credentials.size(); i++) {
+ roles.add(credentials.get(i).getRole());
+ }
+ }
- @PostConstruct
- private void addRoles() {
- for(int i=0; i <credentials.size(); i++) {
- roles.add(credentials.get(i).getRole());
- }
- }
-
- public List<UserCredentials> getUsercredentials() {
- return credentials;
- }
+ public List<UserCredentials> getUsercredentials() {
+ return credentials;
+ }
- public void setUsercredentials(List<UserCredentials> usercredentials) {
- this.credentials = usercredentials;
- }
+ public void setUsercredentials(List<UserCredentials> usercredentials) {
+ this.credentials = usercredentials;
+ }
- @Bean
- public UserDetailsService userDetailsService() {
- return new UserDetailsServiceImpl();
- }
+ @Bean
+ public UserDetailsService userDetailsService() {
+ return new UserDetailsServiceImpl();
+ }
- @Bean
- public BCryptPasswordEncoder passwordEncoder() {
- return new BCryptPasswordEncoder();
- }
+ @Bean
+ public BCryptPasswordEncoder passwordEncoder() {
+ return new BCryptPasswordEncoder();
+ }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/CloudConfiguration.java b/common/src/main/java/org/onap/so/serviceinstancebeans/CloudConfiguration.java
index 67d852eff8..4a284b55ec 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/CloudConfiguration.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/CloudConfiguration.java
@@ -21,9 +21,7 @@
package org.onap.so.serviceinstancebeans;
import java.io.Serializable;
-
import org.onap.so.constants.Defaults;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -34,22 +32,20 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
@JsonInclude(Include.NON_EMPTY)
public class CloudConfiguration implements Serializable {
- private static final long serialVersionUID = 6260165690180745471L;
- @JsonProperty("aicNodeClli")
+ private static final long serialVersionUID = 6260165690180745471L;
+ @JsonProperty("aicNodeClli")
protected String aicNodeClli;
- @JsonProperty("tenantId")
+ @JsonProperty("tenantId")
protected String tenantId;
- @JsonProperty("cloudOwner")
- protected String cloudOwner = Defaults.CLOUD_OWNER.toString();
- @JsonProperty("lcpCloudRegionId")
+ @JsonProperty("cloudOwner")
+ protected String cloudOwner = Defaults.CLOUD_OWNER.toString();
+ @JsonProperty("lcpCloudRegionId")
protected String lcpCloudRegionId;
/**
* Gets the value of the aicNodeClli property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getAicNodeClli() {
@@ -59,9 +55,7 @@ public class CloudConfiguration implements Serializable {
/**
* Sets the value of the aicNodeClli property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setAicNodeClli(String value) {
@@ -71,9 +65,7 @@ public class CloudConfiguration implements Serializable {
/**
* Gets the value of the tenantId property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getTenantId() {
@@ -83,9 +75,7 @@ public class CloudConfiguration implements Serializable {
/**
* Sets the value of the tenantId property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setTenantId(String value) {
@@ -93,27 +83,27 @@ public class CloudConfiguration implements Serializable {
}
- public String getLcpCloudRegionId() {
- return lcpCloudRegionId;
- }
+ public String getLcpCloudRegionId() {
+ return lcpCloudRegionId;
+ }
- public void setLcpCloudRegionId(String lcpCloudRegionId) {
- this.lcpCloudRegionId = lcpCloudRegionId;
- }
+ public void setLcpCloudRegionId(String lcpCloudRegionId) {
+ this.lcpCloudRegionId = lcpCloudRegionId;
+ }
- public String getCloudOwner() {
- return cloudOwner;
- }
+ public String getCloudOwner() {
+ return cloudOwner;
+ }
+
+ public void setCloudOwner(String cloudOwner) {
+ this.cloudOwner = cloudOwner;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("aicNodeClli", getAicNodeClli()).append("tenantId", getTenantId())
+ .append("cloudOwner", getCloudOwner()).append("lcpCloudRegionId", getLcpCloudRegionId()).toString();
+ }
- public void setCloudOwner(String cloudOwner) {
- this.cloudOwner = cloudOwner;
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("aicNodeClli", getAicNodeClli()).append("tenantId", getTenantId())
- .append("cloudOwner", getCloudOwner()).append("lcpCloudRegionId", getLcpCloudRegionId()).toString();
- }
-
-
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ExceptionType.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ExceptionType.java
index e5d586f165..b85e80a670 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/ExceptionType.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ExceptionType.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.05.03 at 03:56:30 PM CDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.05.03 at 03:56:30 PM CDT
//
@@ -30,20 +30,20 @@ package org.onap.so.serviceinstancebeans;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
-
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
- * <p>Java class for exceptionType complex type.
+ * <p>
+ * Java class for exceptionType complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="exceptionType">
@@ -62,15 +62,8 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "exceptionType", propOrder = {
- "messageId",
- "text",
- "variables"
-})
-@XmlSeeAlso({
- ServiceException.class,
- PolicyException.class
-})
+@XmlType(name = "exceptionType", propOrder = {"messageId", "text", "variables"})
+@XmlSeeAlso({ServiceException.class, PolicyException.class})
public class ExceptionType {
@XmlElement(required = true)
@@ -82,10 +75,8 @@ public class ExceptionType {
/**
* Gets the value of the messageId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -94,10 +85,8 @@ public class ExceptionType {
/**
* Sets the value of the messageId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -106,10 +95,8 @@ public class ExceptionType {
/**
* Gets the value of the text property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getText() {
return text;
@@ -118,10 +105,8 @@ public class ExceptionType {
/**
* Sets the value of the text property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setText(String value) {
this.text = value;
@@ -131,21 +116,20 @@ public class ExceptionType {
* Gets the value of the variables property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the variables property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to
+ * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for
+ * the variables property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getVariables().add(newItem);
+ * getVariables().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link String }
+ * Objects of the following type(s) are allowed in the list {@link String }
*
*
*/
@@ -156,13 +140,13 @@ public class ExceptionType {
return this.variables;
}
- public void setVariables(List<String> variables) {
- this.variables = variables;
- }
+ public void setVariables(List<String> variables) {
+ this.variables = variables;
+ }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("messageId", messageId).append("text", text)
- .append("variables", variables).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("messageId", messageId).append("text", text)
+ .append("variables", variables).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/GetOrchestrationListResponse.java b/common/src/main/java/org/onap/so/serviceinstancebeans/GetOrchestrationListResponse.java
index 7be03e635f..b1087b6e8e 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/GetOrchestrationListResponse.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/GetOrchestrationListResponse.java
@@ -21,27 +21,26 @@
package org.onap.so.serviceinstancebeans;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import org.apache.commons.lang3.builder.ToStringBuilder;
@JsonInclude(Include.NON_DEFAULT)
public class GetOrchestrationListResponse {
-
- protected List<RequestList> requestList;
- public List<RequestList> getRequestList() {
- return requestList;
- }
+ protected List<RequestList> requestList;
+
+ public List<RequestList> getRequestList() {
+ return requestList;
+ }
- public void setRequestList(List<RequestList> requestList) {
- this.requestList = requestList;
- }
+ public void setRequestList(List<RequestList> requestList) {
+ this.requestList = requestList;
+ }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("requestList", requestList).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("requestList", requestList).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/GetOrchestrationResponse.java b/common/src/main/java/org/onap/so/serviceinstancebeans/GetOrchestrationResponse.java
index 788cdd973d..53ce3884e9 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/GetOrchestrationResponse.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/GetOrchestrationResponse.java
@@ -27,21 +27,21 @@ import org.apache.commons.lang3.builder.ToStringStyle;
@JsonInclude(Include.NON_DEFAULT)
public class GetOrchestrationResponse {
-
- protected Request request;
- public Request getRequest() {
- return request;
- }
+ protected Request request;
- public void setRequest(Request request) {
- this.request = request;
- }
+ public Request getRequest() {
+ return request;
+ }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("request", request).toString();
- }
+ public void setRequest(Request request) {
+ this.request = request;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("request", request).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/InstanceDirection.java b/common/src/main/java/org/onap/so/serviceinstancebeans/InstanceDirection.java
index ad796b21f9..2e65919d3b 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/InstanceDirection.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/InstanceDirection.java
@@ -22,8 +22,7 @@ package org.onap.so.serviceinstancebeans;
public enum InstanceDirection {
- source,
- destination;
+ source, destination;
public String value() {
return name();
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/InstanceReferences.java b/common/src/main/java/org/onap/so/serviceinstancebeans/InstanceReferences.java
index 72374e0580..5bff780c4c 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/InstanceReferences.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/InstanceReferences.java
@@ -21,118 +21,141 @@
package org.onap.so.serviceinstancebeans;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_DEFAULT)
public class InstanceReferences {
- protected String serviceInstanceId;
- protected String serviceInstanceName;
- protected String vnfInstanceId;
- protected String vnfInstanceName;
- protected String vfModuleInstanceId;
- protected String vfModuleInstanceName;
- protected String volumeGroupInstanceId;
- protected String volumeGroupInstanceName;
- protected String networkInstanceId;
- protected String networkInstanceName;
- protected String requestorId;
- protected String instanceGroupId;
- protected String instanceGroupName;
-
-
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
- public String getServiceInstanceName() {
- return serviceInstanceName;
- }
- public void setServiceInstanceName(String serviceInstanceName) {
- this.serviceInstanceName = serviceInstanceName;
- }
- public String getVnfInstanceId() {
- return vnfInstanceId;
- }
- public void setVnfInstanceId(String vnfInstanceId) {
- this.vnfInstanceId = vnfInstanceId;
- }
- public String getVnfInstanceName() {
- return vnfInstanceName;
- }
- public void setVnfInstanceName(String vnfInstanceName) {
- this.vnfInstanceName = vnfInstanceName;
- }
- public String getVfModuleInstanceId() {
- return vfModuleInstanceId;
- }
- public void setVfModuleInstanceId(String vfModuleInstanceId) {
- this.vfModuleInstanceId = vfModuleInstanceId;
- }
- public String getVfModuleInstanceName() {
- return vfModuleInstanceName;
- }
- public void setVfModuleInstanceName(String vfModuleInstanceName) {
- this.vfModuleInstanceName = vfModuleInstanceName;
- }
- public String getVolumeGroupInstanceId() {
- return volumeGroupInstanceId;
- }
- public void setVolumeGroupInstanceId(String volumeGroupInstanceId) {
- this.volumeGroupInstanceId = volumeGroupInstanceId;
- }
- public String getVolumeGroupInstanceName() {
- return volumeGroupInstanceName;
- }
- public void setVolumeGroupInstanceName(String volumeGroupInstanceName) {
- this.volumeGroupInstanceName = volumeGroupInstanceName;
- }
- public String getNetworkInstanceId() {
- return networkInstanceId;
- }
- public void setNetworkInstanceId(String networkInstanceId) {
- this.networkInstanceId = networkInstanceId;
- }
- public String getNetworkInstanceName() {
- return networkInstanceName;
- }
- public void setNetworkInstanceName(String networkInstanceName) {
- this.networkInstanceName = networkInstanceName;
- }
-
- public String getRequestorId() {
- return requestorId;
- }
-
- public void setRequestorId(String requestorId) {
- this.requestorId = requestorId;
- }
- public String getInstanceGroupId() {
- return instanceGroupId;
- }
- public void setInstanceGroupId(String instanceGroupId) {
- this.instanceGroupId = instanceGroupId;
- }
- public String getInstanceGroupName() {
- return instanceGroupName;
- }
- public void setInstanceGroupName(String instanceGroupName) {
- this.instanceGroupName = instanceGroupName;
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("serviceInstanceId", serviceInstanceId)
- .append("serviceInstanceName", serviceInstanceName).append("vnfInstanceId", vnfInstanceId)
- .append("vnfInstanceName", vnfInstanceName).append("vfModuleInstanceId", vfModuleInstanceId)
- .append("vfModuleInstanceName", vfModuleInstanceName)
- .append("volumeGroupInstanceId", volumeGroupInstanceId)
- .append("volumeGroupInstanceName", volumeGroupInstanceName)
- .append("networkInstanceId", networkInstanceId).append("networkInstanceName", networkInstanceName)
- .append("requestorId", requestorId).append("instanceGroupId", instanceGroupId)
- .append("instanceGroupName", instanceGroupName).toString();
- }
+ protected String serviceInstanceId;
+ protected String serviceInstanceName;
+ protected String vnfInstanceId;
+ protected String vnfInstanceName;
+ protected String vfModuleInstanceId;
+ protected String vfModuleInstanceName;
+ protected String volumeGroupInstanceId;
+ protected String volumeGroupInstanceName;
+ protected String networkInstanceId;
+ protected String networkInstanceName;
+ protected String requestorId;
+ protected String instanceGroupId;
+ protected String instanceGroupName;
+
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getServiceInstanceName() {
+ return serviceInstanceName;
+ }
+
+ public void setServiceInstanceName(String serviceInstanceName) {
+ this.serviceInstanceName = serviceInstanceName;
+ }
+
+ public String getVnfInstanceId() {
+ return vnfInstanceId;
+ }
+
+ public void setVnfInstanceId(String vnfInstanceId) {
+ this.vnfInstanceId = vnfInstanceId;
+ }
+
+ public String getVnfInstanceName() {
+ return vnfInstanceName;
+ }
+
+ public void setVnfInstanceName(String vnfInstanceName) {
+ this.vnfInstanceName = vnfInstanceName;
+ }
+
+ public String getVfModuleInstanceId() {
+ return vfModuleInstanceId;
+ }
+
+ public void setVfModuleInstanceId(String vfModuleInstanceId) {
+ this.vfModuleInstanceId = vfModuleInstanceId;
+ }
+
+ public String getVfModuleInstanceName() {
+ return vfModuleInstanceName;
+ }
+
+ public void setVfModuleInstanceName(String vfModuleInstanceName) {
+ this.vfModuleInstanceName = vfModuleInstanceName;
+ }
+
+ public String getVolumeGroupInstanceId() {
+ return volumeGroupInstanceId;
+ }
+
+ public void setVolumeGroupInstanceId(String volumeGroupInstanceId) {
+ this.volumeGroupInstanceId = volumeGroupInstanceId;
+ }
+
+ public String getVolumeGroupInstanceName() {
+ return volumeGroupInstanceName;
+ }
+
+ public void setVolumeGroupInstanceName(String volumeGroupInstanceName) {
+ this.volumeGroupInstanceName = volumeGroupInstanceName;
+ }
+
+ public String getNetworkInstanceId() {
+ return networkInstanceId;
+ }
+
+ public void setNetworkInstanceId(String networkInstanceId) {
+ this.networkInstanceId = networkInstanceId;
+ }
+
+ public String getNetworkInstanceName() {
+ return networkInstanceName;
+ }
+
+ public void setNetworkInstanceName(String networkInstanceName) {
+ this.networkInstanceName = networkInstanceName;
+ }
+
+ public String getRequestorId() {
+ return requestorId;
+ }
+
+ public void setRequestorId(String requestorId) {
+ this.requestorId = requestorId;
+ }
+
+ public String getInstanceGroupId() {
+ return instanceGroupId;
+ }
+
+ public void setInstanceGroupId(String instanceGroupId) {
+ this.instanceGroupId = instanceGroupId;
+ }
+
+ public String getInstanceGroupName() {
+ return instanceGroupName;
+ }
+
+ public void setInstanceGroupName(String instanceGroupName) {
+ this.instanceGroupName = instanceGroupName;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("serviceInstanceId", serviceInstanceId)
+ .append("serviceInstanceName", serviceInstanceName).append("vnfInstanceId", vnfInstanceId)
+ .append("vnfInstanceName", vnfInstanceName).append("vfModuleInstanceId", vfModuleInstanceId)
+ .append("vfModuleInstanceName", vfModuleInstanceName)
+ .append("volumeGroupInstanceId", volumeGroupInstanceId)
+ .append("volumeGroupInstanceName", volumeGroupInstanceName)
+ .append("networkInstanceId", networkInstanceId).append("networkInstanceName", networkInstanceName)
+ .append("requestorId", requestorId).append("instanceGroupId", instanceGroupId)
+ .append("instanceGroupName", instanceGroupName).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/LineOfBusiness.java b/common/src/main/java/org/onap/so/serviceinstancebeans/LineOfBusiness.java
index 27bc0e84a4..35428106b8 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/LineOfBusiness.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/LineOfBusiness.java
@@ -21,7 +21,6 @@
package org.onap.so.serviceinstancebeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,19 +30,21 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
@JsonRootName(value = "lineOfBusiness")
@JsonInclude(Include.NON_DEFAULT)
public class LineOfBusiness implements Serializable {
-
- private static final long serialVersionUID = -8574860788160041209L;
- @JsonProperty("lineOfBusinessName")
- private String lineOfBusinessName;
-
- public String getLineOfBusinessName(){
- return lineOfBusinessName;
- }
- public void setLineOfBusinessName(String value){
- this.lineOfBusinessName = value;
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("lineOfBusinessName", lineOfBusinessName).toString();
- }
+
+ private static final long serialVersionUID = -8574860788160041209L;
+ @JsonProperty("lineOfBusinessName")
+ private String lineOfBusinessName;
+
+ public String getLineOfBusinessName() {
+ return lineOfBusinessName;
+ }
+
+ public void setLineOfBusinessName(String value) {
+ this.lineOfBusinessName = value;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("lineOfBusinessName", lineOfBusinessName).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ModelInfo.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ModelInfo.java
index 6976fb6791..946deefee7 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/ModelInfo.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ModelInfo.java
@@ -29,7 +29,6 @@
package org.onap.so.serviceinstancebeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -39,131 +38,157 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class ModelInfo implements Serializable {
- private static final long serialVersionUID = 5281763573935476852L;
- @JsonProperty("modelCustomizationName")
+ private static final long serialVersionUID = 5281763573935476852L;
+ @JsonProperty("modelCustomizationName")
protected String modelCustomizationName;
- @JsonProperty("modelInvariantId")
+ @JsonProperty("modelInvariantId")
protected String modelInvariantId;
- @JsonProperty("modelType")
- protected ModelType modelType;
- @JsonProperty("modelId")
- protected String modelId;
- //v2
- @JsonProperty("modelNameVersionId")
+ @JsonProperty("modelType")
+ protected ModelType modelType;
+ @JsonProperty("modelId")
+ protected String modelId;
+ // v2
+ @JsonProperty("modelNameVersionId")
protected String modelNameVersionId;
- @JsonProperty("modelName")
+ @JsonProperty("modelName")
protected String modelName;
- @JsonProperty("modelVersion")
+ @JsonProperty("modelVersion")
protected String modelVersion;
- @JsonProperty("modelCustomizationUuid")
+ @JsonProperty("modelCustomizationUuid")
protected String modelCustomizationUuid;
- //v3
- @JsonProperty("modelVersionId")
+ // v3
+ @JsonProperty("modelVersionId")
protected String modelVersionId;
- @JsonProperty("modelCustomizationId")
+ @JsonProperty("modelCustomizationId")
protected String modelCustomizationId;
-
- //Decomposition fields
- @JsonProperty("modelUuid")
+
+ // Decomposition fields
+ @JsonProperty("modelUuid")
protected String modelUuid;
- @JsonProperty("modelInvariantUuid")
- protected String modelInvariantUuid;
- @JsonProperty("modelInstanceName")
+ @JsonProperty("modelInvariantUuid")
+ protected String modelInvariantUuid;
+ @JsonProperty("modelInstanceName")
protected String modelInstanceName;
- public String getModelCustomizationName() {
- return modelCustomizationName;
- }
- public void setModelCustomizationName(String modelCustomizationName) {
- modelInstanceName = modelCustomizationName;
- this.modelCustomizationName = modelCustomizationName;
- }
- public String getModelNameVersionId() {
- return modelNameVersionId;
- }
- public void setModelNameVersionId(String modelNameVersionId) {
- this.modelNameVersionId = modelNameVersionId;
- }
- public String getModelName() {
- return modelName;
- }
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
- public String getModelVersion() {
- return modelVersion;
- }
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
- public ModelType getModelType() {
- return modelType;
- }
- public void setModelType(ModelType modelType) {
- this.modelType = modelType;
- }
- public String getModelInvariantId() {
- return modelInvariantId;
- }
- public void setModelInvariantId(String modelInvariantId) {
- this.modelInvariantUuid = modelInvariantId;
- this.modelInvariantId = modelInvariantId;
- }
- public String getModelCustomizationUuid() {
- return modelCustomizationUuid;
- }
- public void setModelCustomizationUuid(String modelCustomizationUuid) {
- this.modelCustomizationUuid = modelCustomizationUuid;
- }
- public String getModelVersionId() {
- return modelVersionId;
- }
- public void setModelVersionId(String modelVersionId) {
- this.modelUuid=modelVersionId;
- this.modelVersionId = modelVersionId;
- }
- public String getModelCustomizationId() {
- return modelCustomizationId;
- }
- public void setModelCustomizationId(String modelCustomizationId) {
- this.modelCustomizationUuid = modelCustomizationId;
- this.modelCustomizationId = modelCustomizationId;
- }
+ public String getModelCustomizationName() {
+ return modelCustomizationName;
+ }
+
+ public void setModelCustomizationName(String modelCustomizationName) {
+ modelInstanceName = modelCustomizationName;
+ this.modelCustomizationName = modelCustomizationName;
+ }
+
+ public String getModelNameVersionId() {
+ return modelNameVersionId;
+ }
+
+ public void setModelNameVersionId(String modelNameVersionId) {
+ this.modelNameVersionId = modelNameVersionId;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ public ModelType getModelType() {
+ return modelType;
+ }
+
+ public void setModelType(ModelType modelType) {
+ this.modelType = modelType;
+ }
+
+ public String getModelInvariantId() {
+ return modelInvariantId;
+ }
+
+ public void setModelInvariantId(String modelInvariantId) {
+ this.modelInvariantUuid = modelInvariantId;
+ this.modelInvariantId = modelInvariantId;
+ }
+
+ public String getModelCustomizationUuid() {
+ return modelCustomizationUuid;
+ }
+
+ public void setModelCustomizationUuid(String modelCustomizationUuid) {
+ this.modelCustomizationUuid = modelCustomizationUuid;
+ }
+
+ public String getModelVersionId() {
+ return modelVersionId;
+ }
+
+ public void setModelVersionId(String modelVersionId) {
+ this.modelUuid = modelVersionId;
+ this.modelVersionId = modelVersionId;
+ }
+
+ public String getModelCustomizationId() {
+ return modelCustomizationId;
+ }
+
+ public void setModelCustomizationId(String modelCustomizationId) {
+ this.modelCustomizationUuid = modelCustomizationId;
+ this.modelCustomizationId = modelCustomizationId;
+ }
+
public String getModelUuid() {
- return modelUuid;
- }
+ return modelUuid;
+ }
+
public String getModelId() {
- return modelId;
- }
- public void setModelUuid(String modelUuid) {
- this.modelId = modelUuid;
- this.modelUuid = modelUuid;
-
- }
- public void setModelId(String modelId) {
- this.modelId = modelId;
- }
- public String getModelInvariantUuid() {
- return modelInvariantUuid;
- }
- public void setModelInvariantUuid(String modelInvariantUuid) {
- this.modelInvariantUuid = modelInvariantUuid;
- }
- public String getModelInstanceName() {
- return modelInstanceName;
- }
- public void setModelInstanceName(String modelInstanceName) {
- this.modelInstanceName = modelInstanceName;
- }
- @Override
- public String toString() {
- return "ModelInfo [modelCustomizationName=" + modelCustomizationName + ", modelInvariantId=" + modelInvariantId
- + ", modelType=" + modelType + ", modelNameVersionId=" + modelNameVersionId + ", modelName=" + modelName
- + ", modelVersion=" + modelVersion + ", modelCustomizationUuid=" + modelCustomizationUuid
- + ", modelVersionId=" + modelVersionId + ", modelCustomizationId=" + modelCustomizationId
- + ", modelUuid=" + modelUuid + ", modelInvariantUuid=" + modelInvariantUuid + ", modelInstanceName="
- + modelInstanceName + "]";
- }
-
-
-} \ No newline at end of file
+ return modelId;
+ }
+
+ public void setModelUuid(String modelUuid) {
+ this.modelId = modelUuid;
+ this.modelUuid = modelUuid;
+
+ }
+
+ public void setModelId(String modelId) {
+ this.modelId = modelId;
+ }
+
+ public String getModelInvariantUuid() {
+ return modelInvariantUuid;
+ }
+
+ public void setModelInvariantUuid(String modelInvariantUuid) {
+ this.modelInvariantUuid = modelInvariantUuid;
+ }
+
+ public String getModelInstanceName() {
+ return modelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ this.modelInstanceName = modelInstanceName;
+ }
+
+ @Override
+ public String toString() {
+ return "ModelInfo [modelCustomizationName=" + modelCustomizationName + ", modelInvariantId=" + modelInvariantId
+ + ", modelType=" + modelType + ", modelNameVersionId=" + modelNameVersionId + ", modelName=" + modelName
+ + ", modelVersion=" + modelVersion + ", modelCustomizationUuid=" + modelCustomizationUuid
+ + ", modelVersionId=" + modelVersionId + ", modelCustomizationId=" + modelCustomizationId
+ + ", modelUuid=" + modelUuid + ", modelInvariantUuid=" + modelInvariantUuid + ", modelInstanceName="
+ + modelInstanceName + "]";
+ }
+
+
+}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java
index 754a70ee94..9a184b0a51 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java
@@ -22,16 +22,7 @@ package org.onap.so.serviceinstancebeans;
/*
* Enum for Model Type values returned by API Handler to BPMN
-*/
+ */
public enum ModelType {
- service,
- vnf,
- vfModule,
- volumeGroup,
- network,
- configuration,
- connectionPoint,
- pnf,
- networkInstanceGroup,
- instanceGroup
+ service, vnf, vfModule, volumeGroup, network, configuration, connectionPoint, pnf, networkInstanceGroup, instanceGroup
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Networks.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Networks.java
index 386078a60b..8f795df654 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/Networks.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Networks.java
@@ -25,7 +25,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -33,66 +32,64 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonRootName(value = "networks")
@JsonInclude(Include.NON_DEFAULT)
-public class Networks implements Serializable{
-
- private static final long serialVersionUID = 8081495240474276501L;
- @JsonProperty("modelInfo")
- protected ModelInfo modelInfo;
- @JsonProperty("cloudConfiguration")
- protected CloudConfiguration cloudConfiguration;
- @JsonProperty("instanceName")
- protected String instanceName;
- @JsonProperty("productFamilyId")
- protected String productFamilyId;
- @JsonProperty("instanceParams")
- private List<Map<String, String>> instanceParams = new ArrayList<>();
-
- public ModelInfo getModelInfo() {
- return modelInfo;
- }
-
- public void setModelInfo(ModelInfo modelInfo) {
- this.modelInfo = modelInfo;
- }
-
- public CloudConfiguration getCloudConfiguration() {
- return cloudConfiguration;
- }
-
- public void setCloudConfiguration(CloudConfiguration cloudConfiguration) {
- this.cloudConfiguration = cloudConfiguration;
- }
-
- public String getInstanceName() {
- return instanceName;
- }
-
- public void setInstanceName(String instanceName) {
- this.instanceName = instanceName;
- }
-
- public String getProductFamilyId() {
- return productFamilyId;
- }
-
- public void setProductFamilyId(String productFamilyId) {
- this.productFamilyId = productFamilyId;
- }
-
- public List<Map<String, String>> getInstanceParams() {
- return instanceParams;
- }
-
- public void setInstanceParams(List<Map<String, String>> instanceParams) {
- this.instanceParams = instanceParams;
- }
-
- @Override
- public String toString() {
- return "Networks [modelInfo=" + modelInfo +
- ", cloudConfiguration=" + cloudConfiguration +
- ", instanceName=" + instanceName + ", productFamilyId=" + productFamilyId +
- ", instanceParams=" + instanceParams + "]";
- }
-
-} \ No newline at end of file
+public class Networks implements Serializable {
+
+ private static final long serialVersionUID = 8081495240474276501L;
+ @JsonProperty("modelInfo")
+ protected ModelInfo modelInfo;
+ @JsonProperty("cloudConfiguration")
+ protected CloudConfiguration cloudConfiguration;
+ @JsonProperty("instanceName")
+ protected String instanceName;
+ @JsonProperty("productFamilyId")
+ protected String productFamilyId;
+ @JsonProperty("instanceParams")
+ private List<Map<String, String>> instanceParams = new ArrayList<>();
+
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
+
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
+
+ public CloudConfiguration getCloudConfiguration() {
+ return cloudConfiguration;
+ }
+
+ public void setCloudConfiguration(CloudConfiguration cloudConfiguration) {
+ this.cloudConfiguration = cloudConfiguration;
+ }
+
+ public String getInstanceName() {
+ return instanceName;
+ }
+
+ public void setInstanceName(String instanceName) {
+ this.instanceName = instanceName;
+ }
+
+ public String getProductFamilyId() {
+ return productFamilyId;
+ }
+
+ public void setProductFamilyId(String productFamilyId) {
+ this.productFamilyId = productFamilyId;
+ }
+
+ public List<Map<String, String>> getInstanceParams() {
+ return instanceParams;
+ }
+
+ public void setInstanceParams(List<Map<String, String>> instanceParams) {
+ this.instanceParams = instanceParams;
+ }
+
+ @Override
+ public String toString() {
+ return "Networks [modelInfo=" + modelInfo + ", cloudConfiguration=" + cloudConfiguration + ", instanceName="
+ + instanceName + ", productFamilyId=" + productFamilyId + ", instanceParams=" + instanceParams + "]";
+ }
+
+}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/OwningEntity.java b/common/src/main/java/org/onap/so/serviceinstancebeans/OwningEntity.java
index f552554ad4..276706d257 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/OwningEntity.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/OwningEntity.java
@@ -21,7 +21,6 @@
package org.onap.so.serviceinstancebeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -30,31 +29,31 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "owningEntity")
@JsonInclude(Include.NON_DEFAULT)
public class OwningEntity implements Serializable {
-
- private static final long serialVersionUID = -3907033130633428448L;
- @JsonProperty("owningEntityId")
- private String owningEntityId;
- @JsonProperty("owningEntityName")
- private String owningEntityName;
-
- public String getOwningEntityId(){
- return owningEntityId;
- }
-
- public void setOwningEntityId(String value) {
- this.owningEntityId = value;
- }
-
- public String getOwningEntityName(){
- return owningEntityName;
- }
-
- public void setOwningEntityName(String value){
- this.owningEntityName = value;
- }
- @Override
- public String toString() {
- return "OwningEntity [owningEntityId=" + owningEntityId
- + ", owningEntityName=" + owningEntityName + "]";
- }
+
+ private static final long serialVersionUID = -3907033130633428448L;
+ @JsonProperty("owningEntityId")
+ private String owningEntityId;
+ @JsonProperty("owningEntityName")
+ private String owningEntityName;
+
+ public String getOwningEntityId() {
+ return owningEntityId;
+ }
+
+ public void setOwningEntityId(String value) {
+ this.owningEntityId = value;
+ }
+
+ public String getOwningEntityName() {
+ return owningEntityName;
+ }
+
+ public void setOwningEntityName(String value) {
+ this.owningEntityName = value;
+ }
+
+ @Override
+ public String toString() {
+ return "OwningEntity [owningEntityId=" + owningEntityId + ", owningEntityName=" + owningEntityName + "]";
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Platform.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Platform.java
index 961062299f..8c4b99fd70 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/Platform.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Platform.java
@@ -21,7 +21,6 @@
package org.onap.so.serviceinstancebeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,19 +30,21 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
@JsonInclude(Include.NON_DEFAULT)
@JsonRootName(value = "platform")
public class Platform implements Serializable {
-
- private static final long serialVersionUID = -7334479240678605536L;
- @JsonProperty("platformName")
- private String platformName;
-
- public String getPlatformName(){
- return platformName;
- }
- public void setPlatformName(String value){
- this.platformName = value;
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("platformName", platformName).toString();
- }
+
+ private static final long serialVersionUID = -7334479240678605536L;
+ @JsonProperty("platformName")
+ private String platformName;
+
+ public String getPlatformName() {
+ return platformName;
+ }
+
+ public void setPlatformName(String value) {
+ this.platformName = value;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("platformName", platformName).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/PolicyException.java b/common/src/main/java/org/onap/so/serviceinstancebeans/PolicyException.java
index 263089e5c1..db0ce233c3 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/PolicyException.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/PolicyException.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.03.30 at 02:48:23 PM CDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.03.30 at 02:48:23 PM CDT
//
@@ -34,9 +34,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for policyException complex type.
+ * <p>
+ * Java class for policyException complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="policyException">
@@ -51,9 +53,7 @@ import javax.xml.bind.annotation.XmlType;
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "policyException")
-public class PolicyException
- extends ExceptionType
-{
+public class PolicyException extends ExceptionType {
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Project.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Project.java
index 47bd2bb802..e7db88921f 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/Project.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Project.java
@@ -21,7 +21,6 @@
package org.onap.so.serviceinstancebeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,21 +30,21 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
@JsonRootName(value = "project")
@JsonInclude(Include.NON_DEFAULT)
public class Project implements Serializable {
-
- private static final long serialVersionUID = -3868114191925177035L;
- @JsonProperty("projectName")
- private String projectName;
-
- public String getProjectName(){
- return projectName;
- }
- public void setProjectName(String value) {
- this.projectName = value;
- }
+ private static final long serialVersionUID = -3868114191925177035L;
+ @JsonProperty("projectName")
+ private String projectName;
+
+ public String getProjectName() {
+ return projectName;
+ }
+
+ public void setProjectName(String value) {
+ this.projectName = value;
+ }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("projectName", projectName).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("projectName", projectName).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RelatedInstance.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RelatedInstance.java
index cfdba18fe1..a6a679d42f 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RelatedInstance.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RelatedInstance.java
@@ -21,7 +21,6 @@
package org.onap.so.serviceinstancebeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,46 +30,54 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
@JsonRootName(value = "relatedInstance")
@JsonInclude(Include.NON_DEFAULT)
public class RelatedInstance implements Serializable {
-
- private static final long serialVersionUID = 137250604008221644L;
- @JsonProperty("instanceName")
- protected String instanceName;
- @JsonProperty("instanceId")
- protected String instanceId;
- @JsonProperty("modelInfo")
- protected ModelInfo modelInfo;
- //Configuration field
- @JsonProperty("instanceDirection")
- protected InstanceDirection instanceDirection;
-
-
- public String getInstanceName() {
- return instanceName;
- }
- public void setInstanceName(String instanceName) {
- this.instanceName = instanceName;
- }
- public String getInstanceId() {
- return instanceId;
- }
- public void setInstanceId(String instanceId) {
- this.instanceId = instanceId;
- }
- public ModelInfo getModelInfo() {
- return modelInfo;
- }
- public void setModelInfo(ModelInfo modelInfo) {
- this.modelInfo = modelInfo;
- }
- public InstanceDirection getInstanceDirection() {
- return instanceDirection;
- }
- public void setInstanceDirection(InstanceDirection instanceDirection) {
- this.instanceDirection = instanceDirection;
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("instanceName", instanceName).append("instanceId", instanceId)
- .append("modelInfo", modelInfo).append("instanceDirection", instanceDirection).toString();
- }
+
+ private static final long serialVersionUID = 137250604008221644L;
+ @JsonProperty("instanceName")
+ protected String instanceName;
+ @JsonProperty("instanceId")
+ protected String instanceId;
+ @JsonProperty("modelInfo")
+ protected ModelInfo modelInfo;
+ // Configuration field
+ @JsonProperty("instanceDirection")
+ protected InstanceDirection instanceDirection;
+
+
+ public String getInstanceName() {
+ return instanceName;
+ }
+
+ public void setInstanceName(String instanceName) {
+ this.instanceName = instanceName;
+ }
+
+ public String getInstanceId() {
+ return instanceId;
+ }
+
+ public void setInstanceId(String instanceId) {
+ this.instanceId = instanceId;
+ }
+
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
+
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
+
+ public InstanceDirection getInstanceDirection() {
+ return instanceDirection;
+ }
+
+ public void setInstanceDirection(InstanceDirection instanceDirection) {
+ this.instanceDirection = instanceDirection;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("instanceName", instanceName).append("instanceId", instanceId)
+ .append("modelInfo", modelInfo).append("instanceDirection", instanceDirection).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RelatedInstanceList.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RelatedInstanceList.java
index 9d10865e24..7a545cf9fb 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RelatedInstanceList.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RelatedInstanceList.java
@@ -21,7 +21,6 @@
package org.onap.so.serviceinstancebeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,22 +30,22 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class RelatedInstanceList implements Serializable {
- private static final long serialVersionUID = 6333898302094446243L;
- @JsonProperty("relatedInstance")
- protected RelatedInstance relatedInstance;
+ private static final long serialVersionUID = 6333898302094446243L;
+ @JsonProperty("relatedInstance")
+ protected RelatedInstance relatedInstance;
- public RelatedInstance getRelatedInstance() {
- return relatedInstance;
- }
+ public RelatedInstance getRelatedInstance() {
+ return relatedInstance;
+ }
- public void setRelatedInstance(RelatedInstance relatedInstance) {
- this.relatedInstance = relatedInstance;
- }
+ public void setRelatedInstance(RelatedInstance relatedInstance) {
+ this.relatedInstance = relatedInstance;
+ }
- @Override
- public String toString() {
- return "RelatedInstanceList [relatedInstance=" + relatedInstance + "]";
- }
+ @Override
+ public String toString() {
+ return "RelatedInstanceList [relatedInstance=" + relatedInstance + "]";
+ }
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java
index d39efddf43..8635af5b94 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java
@@ -21,9 +21,7 @@
package org.onap.so.serviceinstancebeans;
import java.util.List;
-
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@@ -40,67 +38,86 @@ public class Request {
protected InstanceReferences instanceReferences;
protected RequestStatus requestStatus;
protected List<RequestProcessingData> requestProcessingData;
-
-
- public String getRequestId() {
- return requestId;
- }
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
- public String getStartTime() {
- return startTime;
- }
- public void setStartTime(String startTime) {
- this.startTime = startTime;
- }
- public String getFinishTime() {
- return finishTime;
- }
- public void setFinishTime(String finishTime) {
- this.finishTime = finishTime;
- }
- public String getRequestScope() {
- return requestScope;
- }
- public void setRequestScope(String requestScope) {
- this.requestScope = requestScope;
- }
- public String getRequestType() {
- return requestType;
- }
- public void setRequestType(String requestType) {
- this.requestType = requestType;
- }
- public RequestStatus getRequestStatus() {
- return requestStatus;
- }
- public void setRequestStatus(RequestStatus requestStatus) {
- this.requestStatus = requestStatus;
- }
- public InstanceReferences getInstanceReferences() {
- return instanceReferences;
- }
- public void setInstanceReferences(InstanceReferences instanceReferences) {
- this.instanceReferences = instanceReferences;
- }
- public RequestDetails getRequestDetails() {
- return requestDetails;
- }
- public void setRequestDetails(RequestDetails requestDetails) {
- this.requestDetails = requestDetails;
- }
- public List<RequestProcessingData> getRequestProcessingData() {
- return requestProcessingData;
- }
- public void setRequestProcessingData(List<RequestProcessingData> requestProcessingData) {
- this.requestProcessingData = requestProcessingData;
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("requestId", requestId).append("startTime", startTime)
- .append("finishTime", finishTime).append("requestScope", requestScope).append("requestType", requestType)
- .append("requestDetails", requestDetails).append("instanceReferences", instanceReferences)
- .append("requestStatus", requestStatus).append("requestProcessingData", requestProcessingData).toString();
- }
+
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getStartTime() {
+ return startTime;
+ }
+
+ public void setStartTime(String startTime) {
+ this.startTime = startTime;
+ }
+
+ public String getFinishTime() {
+ return finishTime;
+ }
+
+ public void setFinishTime(String finishTime) {
+ this.finishTime = finishTime;
+ }
+
+ public String getRequestScope() {
+ return requestScope;
+ }
+
+ public void setRequestScope(String requestScope) {
+ this.requestScope = requestScope;
+ }
+
+ public String getRequestType() {
+ return requestType;
+ }
+
+ public void setRequestType(String requestType) {
+ this.requestType = requestType;
+ }
+
+ public RequestStatus getRequestStatus() {
+ return requestStatus;
+ }
+
+ public void setRequestStatus(RequestStatus requestStatus) {
+ this.requestStatus = requestStatus;
+ }
+
+ public InstanceReferences getInstanceReferences() {
+ return instanceReferences;
+ }
+
+ public void setInstanceReferences(InstanceReferences instanceReferences) {
+ this.instanceReferences = instanceReferences;
+ }
+
+ public RequestDetails getRequestDetails() {
+ return requestDetails;
+ }
+
+ public void setRequestDetails(RequestDetails requestDetails) {
+ this.requestDetails = requestDetails;
+ }
+
+ public List<RequestProcessingData> getRequestProcessingData() {
+ return requestProcessingData;
+ }
+
+ public void setRequestProcessingData(List<RequestProcessingData> requestProcessingData) {
+ this.requestProcessingData = requestProcessingData;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("requestId", requestId).append("startTime", startTime)
+ .append("finishTime", finishTime).append("requestScope", requestScope)
+ .append("requestType", requestType).append("requestDetails", requestDetails)
+ .append("instanceReferences", instanceReferences).append("requestStatus", requestStatus)
+ .append("requestProcessingData", requestProcessingData).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestDetails.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestDetails.java
index 0364043e8e..9cee8f772e 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestDetails.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestDetails.java
@@ -25,7 +25,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -35,39 +34,37 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class RequestDetails implements Serializable {
- private static final long serialVersionUID = -73080684945860609L;
- @JsonProperty("modelInfo")
+ private static final long serialVersionUID = -73080684945860609L;
+ @JsonProperty("modelInfo")
protected ModelInfo modelInfo;
- @JsonProperty("requestInfo")
+ @JsonProperty("requestInfo")
protected RequestInfo requestInfo;
- @JsonProperty("relatedInstanceList")
+ @JsonProperty("relatedInstanceList")
protected RelatedInstanceList[] relatedInstanceList;
- @JsonProperty("subscriberInfo")
+ @JsonProperty("subscriberInfo")
protected SubscriberInfo subscriberInfo;
- @JsonProperty("cloudConfiguration")
+ @JsonProperty("cloudConfiguration")
protected CloudConfiguration cloudConfiguration;
- @JsonProperty("requestParameters")
+ @JsonProperty("requestParameters")
protected RequestParameters requestParameters;
- @JsonProperty("project")
+ @JsonProperty("project")
protected Project project;
- @JsonProperty("owningEntity")
+ @JsonProperty("owningEntity")
protected OwningEntity owningEntity;
- @JsonProperty("platform")
+ @JsonProperty("platform")
protected Platform platform;
- @JsonProperty("lineOfBusiness")
+ @JsonProperty("lineOfBusiness")
protected LineOfBusiness lineOfBusiness;
- @JsonProperty("instanceName")
- private List<Map<String, String>> instanceName = new ArrayList<>();
- @JsonProperty("configurationParameters")
- protected List<Map<String, String>> configurationParameters = new ArrayList<>();
-
+ @JsonProperty("instanceName")
+ private List<Map<String, String>> instanceName = new ArrayList<>();
+ @JsonProperty("configurationParameters")
+ protected List<Map<String, String>> configurationParameters = new ArrayList<>();
+
- /**
+ /**
* Gets the value of the serviceInfo property.
*
- * @return
- * possible object is
- * {@link ModelInfo }
+ * @return possible object is {@link ModelInfo }
*
*/
public ModelInfo getModelInfo() {
@@ -77,9 +74,7 @@ public class RequestDetails implements Serializable {
/**
* Sets the value of the serviceInfo property.
*
- * @param value
- * allowed object is
- * {@link ModelInfo }
+ * @param value allowed object is {@link ModelInfo }
*
*/
public void setModelInfo(ModelInfo value) {
@@ -89,9 +84,7 @@ public class RequestDetails implements Serializable {
/**
* Gets the value of the requestInfo property.
*
- * @return
- * possible object is
- * {@link RequestInfo }
+ * @return possible object is {@link RequestInfo }
*
*/
public RequestInfo getRequestInfo() {
@@ -101,9 +94,7 @@ public class RequestDetails implements Serializable {
/**
* Sets the value of the requestInfo property.
*
- * @param value
- * allowed object is
- * {@link RequestInfo }
+ * @param value allowed object is {@link RequestInfo }
*
*/
public void setRequestInfo(RequestInfo value) {
@@ -113,9 +104,7 @@ public class RequestDetails implements Serializable {
/**
* Gets the value of the subscriberInfo property.
*
- * @return
- * possible object is
- * {@link SubscriberInfo }
+ * @return possible object is {@link SubscriberInfo }
*
*/
public SubscriberInfo getSubscriberInfo() {
@@ -125,9 +114,7 @@ public class RequestDetails implements Serializable {
/**
* Sets the value of the subscriberInfo property.
*
- * @param value
- * allowed object is
- * {@link SubscriberInfo }
+ * @param value allowed object is {@link SubscriberInfo }
*
*/
public void setSubscriberInfo(SubscriberInfo value) {
@@ -137,9 +124,7 @@ public class RequestDetails implements Serializable {
/**
* Gets the value of the cloudConfiguration property.
*
- * @return
- * possible object is
- * {@link CloudConfiguration }
+ * @return possible object is {@link CloudConfiguration }
*
*/
public CloudConfiguration getCloudConfiguration() {
@@ -149,9 +134,7 @@ public class RequestDetails implements Serializable {
/**
* Sets the value of the cloudConfiguration property.
*
- * @param value
- * allowed object is
- * {@link CloudConfiguration }
+ * @param value allowed object is {@link CloudConfiguration }
*
*/
public void setCloudConfiguration(CloudConfiguration value) {
@@ -161,9 +144,7 @@ public class RequestDetails implements Serializable {
/**
* Gets the value of the requestParameters property.
*
- * @return
- * possible object is
- * {@link RequestParameters }
+ * @return possible object is {@link RequestParameters }
*
*/
public RequestParameters getRequestParameters() {
@@ -173,139 +154,132 @@ public class RequestDetails implements Serializable {
/**
* Sets the value of the requestParameters property.
*
- * @param value
- * allowed object is
- * {@link RequestParameters }
+ * @param value allowed object is {@link RequestParameters }
*
*/
public void setRequestParameters(RequestParameters value) {
this.requestParameters = value;
}
- public RelatedInstanceList[] getRelatedInstanceList() {
- return relatedInstanceList;
- }
+ public RelatedInstanceList[] getRelatedInstanceList() {
+ return relatedInstanceList;
+ }
+
+ public void setRelatedInstanceList(RelatedInstanceList[] relatedInstanceList) {
+ this.relatedInstanceList = relatedInstanceList;
+ }
- public void setRelatedInstanceList(RelatedInstanceList[] relatedInstanceList) {
- this.relatedInstanceList = relatedInstanceList;
- }
- /**
- * Gets the value of the project property.
- *
- * @return
- * possible object is
- * {@link Project }
- *
- */
- public Project getProject(){
- return project;
- }
- /**
+ /**
+ * Gets the value of the project property.
+ *
+ * @return possible object is {@link Project }
+ *
+ */
+ public Project getProject() {
+ return project;
+ }
+
+ /**
* Sets the value of the project property.
*
- * @param value
- * allowed object is
- * {@link Project }
+ * @param value allowed object is {@link Project }
*
*/
- public void setProject(Project value){
- this.project = value;
- }
- /**
- * Gets the value of the owningEntity property.
- *
- * @return
- * possible object is
- * {@link OwningEntity }
- *
- */
- public OwningEntity getOwningEntity(){
- return owningEntity;
- }
- /**
+ public void setProject(Project value) {
+ this.project = value;
+ }
+
+ /**
+ * Gets the value of the owningEntity property.
+ *
+ * @return possible object is {@link OwningEntity }
+ *
+ */
+ public OwningEntity getOwningEntity() {
+ return owningEntity;
+ }
+
+ /**
* Sets the value of the owningEntity property.
*
- * @param value
- * allowed object is
- * {@link OwningEntity }
+ * @param value allowed object is {@link OwningEntity }
*
*/
- public void setOwningEntity(OwningEntity value){
- this.owningEntity = value;
- }
- /**
+ public void setOwningEntity(OwningEntity value) {
+ this.owningEntity = value;
+ }
+
+ /**
* Gets the value of the platform property.
*
- * @return
- * possible object is
- * {@link Platform }
+ * @return possible object is {@link Platform }
*
*/
- public Platform getPlatform(){
- return platform;
- }
- /**
+ public Platform getPlatform() {
+ return platform;
+ }
+
+ /**
* Sets the value of the platform property.
*
- * @param value
- * allowed object is
- * {@link Platform }
+ * @param value allowed object is {@link Platform }
*
*/
- public void setPlatform(Platform value){
- this.platform = value;
- }
- /**
+ public void setPlatform(Platform value) {
+ this.platform = value;
+ }
+
+ /**
* Gets the value of the lineOfBusiness property.
*
- * @return
- * possible object is
- * {@link LineOfBusiness }
+ * @return possible object is {@link LineOfBusiness }
*
*/
- public LineOfBusiness getLineOfBusiness(){
- return lineOfBusiness;
- }
- /**
+ public LineOfBusiness getLineOfBusiness() {
+ return lineOfBusiness;
+ }
+
+ /**
* Sets the value of the lineOfBusiness property.
*
- * @param value
- * allowed object is
- * {@link LineOfBusiness }
+ * @param value allowed object is {@link LineOfBusiness }
*
*/
- public void setLineOfBusiness(LineOfBusiness value){
- this.lineOfBusiness = value;
- }
- /**
+ public void setLineOfBusiness(LineOfBusiness value) {
+ this.lineOfBusiness = value;
+ }
+
+ /**
* Gets the value of the instanceName property.
*/
- public List<Map<String, String>> getInstanceName() {
- return instanceName;
- }
- /**
+ public List<Map<String, String>> getInstanceName() {
+ return instanceName;
+ }
+
+ /**
* Sets the value of the instanceName property.
*
* @param value
*
*/
- public void setInstanceName(List<Map<String, String>> instanceName) {
- this.instanceName = instanceName;
- }
- public List<Map<String, String>> getConfigurationParameters() {
- return configurationParameters;
- }
+ public void setInstanceName(List<Map<String, String>> instanceName) {
+ this.instanceName = instanceName;
+ }
+
+ public List<Map<String, String>> getConfigurationParameters() {
+ return configurationParameters;
+ }
- public void setConfigurationParameters(List<Map<String, String>> configurationParameters) {
- this.configurationParameters = configurationParameters;
- }
+ public void setConfigurationParameters(List<Map<String, String>> configurationParameters) {
+ this.configurationParameters = configurationParameters;
+ }
- @Override
- public String toString() {
- return "RequestDetails [modelInfo=" + modelInfo + ", requestInfo=" + requestInfo + ", relatedInstanceList="
- + Arrays.toString(relatedInstanceList) + ", subscriberInfo=" + subscriberInfo + ", cloudConfiguration="
- + cloudConfiguration + ", requestParameters=" + requestParameters + ", project=" + project
- + ", owningEntity=" + owningEntity + ", platform=" + platform + ", lineOfBusiness=" + lineOfBusiness
- + ", instanceName=" + instanceName + ", configurationParameters=" + configurationParameters + "]";
- }
+ @Override
+ public String toString() {
+ return "RequestDetails [modelInfo=" + modelInfo + ", requestInfo=" + requestInfo + ", relatedInstanceList="
+ + Arrays.toString(relatedInstanceList) + ", subscriberInfo=" + subscriberInfo + ", cloudConfiguration="
+ + cloudConfiguration + ", requestParameters=" + requestParameters + ", project=" + project
+ + ", owningEntity=" + owningEntity + ", platform=" + platform + ", lineOfBusiness=" + lineOfBusiness
+ + ", instanceName=" + instanceName + ", configurationParameters=" + configurationParameters + "]";
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestError.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestError.java
index 76137d0f58..121fd4a1a5 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestError.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestError.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.04.07 at 08:25:52 AM CDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.04.07 at 08:25:52 AM CDT
//
@@ -33,14 +33,15 @@ import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.fasterxml.jackson.annotation.JsonRootName;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -60,10 +61,7 @@ import com.fasterxml.jackson.annotation.JsonRootName;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "policyException",
- "serviceException"
-})
+@XmlType(name = "", propOrder = {"policyException", "serviceException"})
@XmlRootElement(name = "requestError")
@JsonRootName(value = "requestError")
public class RequestError {
@@ -74,10 +72,8 @@ public class RequestError {
/**
* Gets the value of the policyException property.
*
- * @return
- * possible object is
- * {@link PolicyException }
- *
+ * @return possible object is {@link PolicyException }
+ *
*/
public PolicyException getPolicyException() {
return policyException;
@@ -86,10 +82,8 @@ public class RequestError {
/**
* Sets the value of the policyException property.
*
- * @param value
- * allowed object is
- * {@link PolicyException }
- *
+ * @param value allowed object is {@link PolicyException }
+ *
*/
public void setPolicyException(PolicyException value) {
this.policyException = value;
@@ -98,10 +92,8 @@ public class RequestError {
/**
* Gets the value of the serviceException property.
*
- * @return
- * possible object is
- * {@link ServiceException }
- *
+ * @return possible object is {@link ServiceException }
+ *
*/
public ServiceException getServiceException() {
return serviceException;
@@ -110,19 +102,17 @@ public class RequestError {
/**
* Sets the value of the serviceException property.
*
- * @param value
- * allowed object is
- * {@link ServiceException }
- *
+ * @param value allowed object is {@link ServiceException }
+ *
*/
public void setServiceException(ServiceException value) {
this.serviceException = value;
}
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("policyException", policyException)
- .append("serviceException", serviceException).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("policyException", policyException)
+ .append("serviceException", serviceException).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java
index fd7877822b..61192c3147 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java
@@ -21,7 +21,6 @@
package org.onap.so.serviceinstancebeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -33,36 +32,34 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion;
@JsonInclude(Include.NON_DEFAULT)
public class RequestInfo implements Serializable {
- private static final long serialVersionUID = -1370946827136030181L;
- @JsonProperty("billingAccountNumber")
- protected String billingAccountNumber;
- @JsonProperty("callbackUrl")
- protected String callbackUrl;
- @JsonProperty("correlator")
+ private static final long serialVersionUID = -1370946827136030181L;
+ @JsonProperty("billingAccountNumber")
+ protected String billingAccountNumber;
+ @JsonProperty("callbackUrl")
+ protected String callbackUrl;
+ @JsonProperty("correlator")
protected String correlator;
- @JsonProperty("orderNumber")
+ @JsonProperty("orderNumber")
protected String orderNumber;
- @JsonProperty("productFamilyId")
+ @JsonProperty("productFamilyId")
protected String productFamilyId;
- @JsonProperty("orderVersion")
+ @JsonProperty("orderVersion")
protected Integer orderVersion;
- @JsonSerialize(include=Inclusion.ALWAYS)
- @JsonProperty("source")
+ @JsonSerialize(include = Inclusion.ALWAYS)
+ @JsonProperty("source")
protected String source;
- @JsonProperty("instanceName")
+ @JsonProperty("instanceName")
protected String instanceName;
- @JsonProperty("suppressRollback")
- @JsonSerialize(include=Inclusion.ALWAYS)
+ @JsonProperty("suppressRollback")
+ @JsonSerialize(include = Inclusion.ALWAYS)
protected boolean suppressRollback;
- @JsonProperty("requestorId")
+ @JsonProperty("requestorId")
protected String requestorId;
/**
* Gets the value of the callbackUrl property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getCallbackUrl() {
@@ -72,9 +69,7 @@ public class RequestInfo implements Serializable {
/**
* Sets the value of the callbackUrl property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setCallbackUrl(String value) {
@@ -84,9 +79,7 @@ public class RequestInfo implements Serializable {
/**
* Gets the value of the correlator property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getCorrelator() {
@@ -96,9 +89,7 @@ public class RequestInfo implements Serializable {
/**
* Sets the value of the correlator property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setCorrelator(String value) {
@@ -108,9 +99,7 @@ public class RequestInfo implements Serializable {
/**
* Gets the value of the orderNumber property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getOrderNumber() {
@@ -120,9 +109,7 @@ public class RequestInfo implements Serializable {
/**
* Sets the value of the orderNumber property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setOrderNumber(String value) {
@@ -132,9 +119,7 @@ public class RequestInfo implements Serializable {
/**
* Gets the value of the orderVersion property.
*
- * @return
- * possible object is
- * {@link Integer }
+ * @return possible object is {@link Integer }
*
*/
public Integer getOrderVersion() {
@@ -144,9 +129,7 @@ public class RequestInfo implements Serializable {
/**
* Sets the value of the orderVersion property.
*
- * @param value
- * allowed object is
- * {@link Integer }
+ * @param value allowed object is {@link Integer }
*
*/
public void setOrderVersion(Integer value) {
@@ -156,9 +139,7 @@ public class RequestInfo implements Serializable {
/**
* Gets the value of the source property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getSource() {
@@ -168,69 +149,65 @@ public class RequestInfo implements Serializable {
/**
* Sets the value of the source property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setSource(String value) {
this.source = value;
}
- public String getInstanceName() {
- return instanceName;
- }
-
- public void setInstanceName(String instanceName) {
- this.instanceName = instanceName;
- }
-
- public String getBillingAccountNumber() {
- return billingAccountNumber;
- }
-
- public void setBillingAccountNumber(String billingAccountNumber) {
- this.billingAccountNumber = billingAccountNumber;
- }
-
- public String getProductFamilyId() {
- return productFamilyId;
- }
-
- public void setProductFamilyId(String productFamilyId) {
- this.productFamilyId = productFamilyId;
- }
-
- /**
- * Required for Marshalers to send the fields.
- * @return
- */
- public boolean getSuppressRollback() {
- return suppressRollback;
- }
-
- public void setSuppressRollback(boolean suppressRollback) {
- this.suppressRollback = suppressRollback;
- }
-
- public String getRequestorId() {
- return requestorId;
- }
-
- public void setRequestorId(String requestorId) {
- this.requestorId = requestorId;
- }
-
- @Override
- public String toString() {
- return "RequestInfo [billingAccountNumber=" + billingAccountNumber
- + ", callbackUrl=" + callbackUrl + ", correlator=" + correlator
- + ", orderNumber=" + orderNumber + ", productFamilyId="
- + productFamilyId + ", orderVersion=" + orderVersion
- + ", source=" + source + ", instanceName=" + instanceName
- + ", suppressRollback=" + suppressRollback + ", requestorId="
- + requestorId + "]";
- }
+ public String getInstanceName() {
+ return instanceName;
+ }
+
+ public void setInstanceName(String instanceName) {
+ this.instanceName = instanceName;
+ }
+
+ public String getBillingAccountNumber() {
+ return billingAccountNumber;
+ }
+
+ public void setBillingAccountNumber(String billingAccountNumber) {
+ this.billingAccountNumber = billingAccountNumber;
+ }
+
+ public String getProductFamilyId() {
+ return productFamilyId;
+ }
+
+ public void setProductFamilyId(String productFamilyId) {
+ this.productFamilyId = productFamilyId;
+ }
+
+ /**
+ * Required for Marshalers to send the fields.
+ *
+ * @return
+ */
+ public boolean getSuppressRollback() {
+ return suppressRollback;
+ }
+
+ public void setSuppressRollback(boolean suppressRollback) {
+ this.suppressRollback = suppressRollback;
+ }
+
+ public String getRequestorId() {
+ return requestorId;
+ }
+
+ public void setRequestorId(String requestorId) {
+ this.requestorId = requestorId;
+ }
+
+ @Override
+ public String toString() {
+ return "RequestInfo [billingAccountNumber=" + billingAccountNumber + ", callbackUrl=" + callbackUrl
+ + ", correlator=" + correlator + ", orderNumber=" + orderNumber + ", productFamilyId=" + productFamilyId
+ + ", orderVersion=" + orderVersion + ", source=" + source + ", instanceName=" + instanceName
+ + ", suppressRollback=" + suppressRollback + ", requestorId=" + requestorId + "]";
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestList.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestList.java
index a4c0ddfcf2..8374aa7638 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestList.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestList.java
@@ -28,17 +28,17 @@ public class RequestList {
protected Request request;
- public Request getRequest() {
- return request;
- }
-
- public void setRequest(Request request) {
- this.request = request;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("request", request).toString();
- }
+ public Request getRequest() {
+ return request;
+ }
+
+ public void setRequest(Request request) {
+ this.request = request;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("request", request).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java
index 2085e66dde..1df2c10411 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java
@@ -25,7 +25,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -35,126 +34,127 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class RequestParameters implements Serializable {
- private static final long serialVersionUID = -5979049912538894930L;
- @JsonProperty("subscriptionServiceType")
- private String subscriptionServiceType;
- @JsonProperty("userParams")
- private List<Map<String, Object>> userParams = new ArrayList<>();
- @JsonProperty("aLaCarte")
- private Boolean aLaCarte;
- @JsonProperty("payload")
- private String payload;
- @JsonProperty("usePreload")
- private Boolean usePreload; // usePreload would always be true for Update
-
- @JsonProperty("autoBuildVfModules")
- private Boolean autoBuildVfModules;
- @JsonProperty("cascadeDelete")
- private Boolean cascadeDelete;
- @JsonProperty("testApi")
- private String testApi; // usePreload would always be true for Update
- @JsonProperty("rebuildVolumeGroups")
- private Boolean rebuildVolumeGroups;
-
- public String getSubscriptionServiceType() {
- return subscriptionServiceType;
- }
-
- public void setSubscriptionServiceType(String subscriptionServiceType) {
- this.subscriptionServiceType = subscriptionServiceType;
- }
- @JsonProperty("aLaCarte")
- public Boolean getALaCarte() {
- return aLaCarte;
- }
- @JsonProperty("aLaCarte")
- public void setaLaCarte(Boolean aLaCarte) {
- this.aLaCarte = aLaCarte;
- }
-
- public Boolean isaLaCarte() {
- return aLaCarte;
- }
-
- public String getPayload(){
- return payload;
- }
- public void setPayload(String value){
- this.payload = value;
- }
-
- public Boolean isUsePreload() {
- return usePreload;
- }
-
- @JsonProperty("usePreload")
- public Boolean getUsePreload() {
- return usePreload;
- }
-
- @JsonProperty("usePreload")
- public void setUsePreload(Boolean usePreload) {
- this.usePreload = usePreload;
- }
-
- public String getTestApi() {
- return testApi;
- }
-
- public void setTestApi(String testApi) {
- this.testApi = testApi;
- }
-
- public List<Map<String, Object>> getUserParams() {
- return userParams;
- }
-
- public void setUserParams(List<Map<String, Object>> userParams) {
- this.userParams = userParams;
- }
-
- public String getUserParamValue(String name){
- if(userParams!=null){
- for(Map<String, Object> param:userParams){
- if(param.containsKey("name") && param.get("name").equals(name) && param.containsKey("value")){
- return param.get("value").toString();
- }
- }
- }
- return null;
- }
-
- public Boolean getAutoBuildVfModules() {
- return autoBuildVfModules;
- }
-
- public void setAutoBuildVfModules(Boolean autoBuildVfModules) {
- this.autoBuildVfModules = autoBuildVfModules;
- }
-
- public Boolean getCascadeDelete() {
- return cascadeDelete;
- }
-
- public void setCascadeDelete(Boolean cascadeDelete) {
- this.cascadeDelete = cascadeDelete;
- }
-
- public Boolean getRebuildVolumeGroups() {
- return rebuildVolumeGroups;
- }
-
- public void setRebuildVolumeGroups(Boolean rebuildVolumeGroups) {
- this.rebuildVolumeGroups = rebuildVolumeGroups;
- }
-
- @Override
- public String toString() {
- return "RequestParameters [subscriptionServiceType="
- + subscriptionServiceType + ", userParams=" + userParams
- + ", aLaCarte=" + aLaCarte + ", testApi= " + testApi + ", autoBuildVfModules="
- + autoBuildVfModules + ", usePreload="
- + usePreload + ", rebuildVolumeGroups="
- + rebuildVolumeGroups + ", payload=" + payload + "]";
- }
-} \ No newline at end of file
+ private static final long serialVersionUID = -5979049912538894930L;
+ @JsonProperty("subscriptionServiceType")
+ private String subscriptionServiceType;
+ @JsonProperty("userParams")
+ private List<Map<String, Object>> userParams = new ArrayList<>();
+ @JsonProperty("aLaCarte")
+ private Boolean aLaCarte;
+ @JsonProperty("payload")
+ private String payload;
+ @JsonProperty("usePreload")
+ private Boolean usePreload; // usePreload would always be true for Update
+
+ @JsonProperty("autoBuildVfModules")
+ private Boolean autoBuildVfModules;
+ @JsonProperty("cascadeDelete")
+ private Boolean cascadeDelete;
+ @JsonProperty("testApi")
+ private String testApi; // usePreload would always be true for Update
+ @JsonProperty("rebuildVolumeGroups")
+ private Boolean rebuildVolumeGroups;
+
+ public String getSubscriptionServiceType() {
+ return subscriptionServiceType;
+ }
+
+ public void setSubscriptionServiceType(String subscriptionServiceType) {
+ this.subscriptionServiceType = subscriptionServiceType;
+ }
+
+ @JsonProperty("aLaCarte")
+ public Boolean getALaCarte() {
+ return aLaCarte;
+ }
+
+ @JsonProperty("aLaCarte")
+ public void setaLaCarte(Boolean aLaCarte) {
+ this.aLaCarte = aLaCarte;
+ }
+
+ public Boolean isaLaCarte() {
+ return aLaCarte;
+ }
+
+ public String getPayload() {
+ return payload;
+ }
+
+ public void setPayload(String value) {
+ this.payload = value;
+ }
+
+ public Boolean isUsePreload() {
+ return usePreload;
+ }
+
+ @JsonProperty("usePreload")
+ public Boolean getUsePreload() {
+ return usePreload;
+ }
+
+ @JsonProperty("usePreload")
+ public void setUsePreload(Boolean usePreload) {
+ this.usePreload = usePreload;
+ }
+
+ public String getTestApi() {
+ return testApi;
+ }
+
+ public void setTestApi(String testApi) {
+ this.testApi = testApi;
+ }
+
+ public List<Map<String, Object>> getUserParams() {
+ return userParams;
+ }
+
+ public void setUserParams(List<Map<String, Object>> userParams) {
+ this.userParams = userParams;
+ }
+
+ public String getUserParamValue(String name) {
+ if (userParams != null) {
+ for (Map<String, Object> param : userParams) {
+ if (param.containsKey("name") && param.get("name").equals(name) && param.containsKey("value")) {
+ return param.get("value").toString();
+ }
+ }
+ }
+ return null;
+ }
+
+ public Boolean getAutoBuildVfModules() {
+ return autoBuildVfModules;
+ }
+
+ public void setAutoBuildVfModules(Boolean autoBuildVfModules) {
+ this.autoBuildVfModules = autoBuildVfModules;
+ }
+
+ public Boolean getCascadeDelete() {
+ return cascadeDelete;
+ }
+
+ public void setCascadeDelete(Boolean cascadeDelete) {
+ this.cascadeDelete = cascadeDelete;
+ }
+
+ public Boolean getRebuildVolumeGroups() {
+ return rebuildVolumeGroups;
+ }
+
+ public void setRebuildVolumeGroups(Boolean rebuildVolumeGroups) {
+ this.rebuildVolumeGroups = rebuildVolumeGroups;
+ }
+
+ @Override
+ public String toString() {
+ return "RequestParameters [subscriptionServiceType=" + subscriptionServiceType + ", userParams=" + userParams
+ + ", aLaCarte=" + aLaCarte + ", testApi= " + testApi + ", autoBuildVfModules=" + autoBuildVfModules
+ + ", usePreload=" + usePreload + ", rebuildVolumeGroups=" + rebuildVolumeGroups + ", payload=" + payload
+ + "]";
+ }
+}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestProcessingData.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestProcessingData.java
index 3373f78335..508987cfeb 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestProcessingData.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestProcessingData.java
@@ -1,19 +1,15 @@
-/* ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/*
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -21,7 +17,6 @@ package org.onap.so.serviceinstancebeans;
import java.util.HashMap;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import org.apache.commons.lang3.builder.ToStringBuilder;
@@ -29,34 +24,40 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
@JsonInclude(Include.NON_DEFAULT)
public class RequestProcessingData {
-
- protected String groupingId;
- protected String tag;
- protected List<HashMap<String, String>> dataPairs;
-
- public String getGroupingId() {
- return groupingId;
- }
- public void setGroupingId(String groupingId) {
- this.groupingId = groupingId;
- }
- public String getTag() {
- return tag;
- }
- public void setTag(String tag) {
- this.tag = tag;
- }
- public List<HashMap<String, String>> getDataPairs() {
- return dataPairs;
- }
- public void setDataPairs(List<HashMap<String, String>> dataPairs) {
- this.dataPairs = dataPairs;
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("groupingId", groupingId).append("tag", tag)
- .append("dataPairs", dataPairs).toString();
- }
-
-
+
+ protected String groupingId;
+ protected String tag;
+ protected List<HashMap<String, String>> dataPairs;
+
+ public String getGroupingId() {
+ return groupingId;
+ }
+
+ public void setGroupingId(String groupingId) {
+ this.groupingId = groupingId;
+ }
+
+ public String getTag() {
+ return tag;
+ }
+
+ public void setTag(String tag) {
+ this.tag = tag;
+ }
+
+ public List<HashMap<String, String>> getDataPairs() {
+ return dataPairs;
+ }
+
+ public void setDataPairs(List<HashMap<String, String>> dataPairs) {
+ this.dataPairs = dataPairs;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("groupingId", groupingId).append("tag", tag)
+ .append("dataPairs", dataPairs).toString();
+ }
+
+
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java
index 088e414094..19ce5e72f3 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java
@@ -21,9 +21,7 @@
package org.onap.so.serviceinstancebeans;
import java.net.URL;
-
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@@ -31,33 +29,40 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonRootName(value = "requestReferences")
@JsonInclude(Include.NON_DEFAULT)
public class RequestReferences {
-
- String requestId;
- String instanceId;
- URL requestSelfLink;
-
- public String getRequestId() {
- return requestId;
- }
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
- public String getInstanceId() {
- return instanceId;
- }
- public void setInstanceId(String instanceId) {
- this.instanceId = instanceId;
- }
- public URL getRequestSelfLink() {
- return requestSelfLink;
- }
- public void setRequestSelfLink(URL requestSelfLink) {
- this.requestSelfLink = requestSelfLink;
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("requestId", requestId).append("instanceId", instanceId).append("requestSelfLink", requestSelfLink).toString();
- }
+
+ String requestId;
+ String instanceId;
+ URL requestSelfLink;
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getInstanceId() {
+ return instanceId;
+ }
+
+ public void setInstanceId(String instanceId) {
+ this.instanceId = instanceId;
+ }
+
+ public URL getRequestSelfLink() {
+ return requestSelfLink;
+ }
+
+ public void setRequestSelfLink(URL requestSelfLink) {
+ this.requestSelfLink = requestSelfLink;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("requestId", requestId).append("instanceId", instanceId)
+ .append("requestSelfLink", requestSelfLink).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java
index 710c820148..f659ae241a 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java
@@ -28,42 +28,50 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
@JsonInclude(Include.NON_DEFAULT)
public class RequestStatus {
- @JsonProperty("requestState")
- protected String requestState;
- @JsonProperty("statusMessage")
+ @JsonProperty("requestState")
+ protected String requestState;
+ @JsonProperty("statusMessage")
protected String statusMessage;
- @JsonProperty("percentProgress")
+ @JsonProperty("percentProgress")
protected Integer percentProgress;
- @JsonProperty("timestamp")
+ @JsonProperty("timestamp")
protected String timeStamp;
- public String getRequestState() {
- return requestState;
- }
- public void setRequestState(String requestState) {
- this.requestState = requestState;
- }
- public String getStatusMessage() {
- return statusMessage;
- }
- public void setStatusMessage(String statusMessage) {
- this.statusMessage = statusMessage;
- }
- public Integer getPercentProgress() {
- return percentProgress;
- }
- public void setPercentProgress(Integer percentProgress) {
- this.percentProgress = percentProgress;
- }
- public String getTimeStamp() {
- return timeStamp;
- }
- public void setTimeStamp(String timeStamp) {
- this.timeStamp = timeStamp;
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("requestState", requestState).append("statusMessage", statusMessage)
- .append("percentProgress", percentProgress).append("timestamp", timeStamp).toString();
- }
+ public String getRequestState() {
+ return requestState;
+ }
+
+ public void setRequestState(String requestState) {
+ this.requestState = requestState;
+ }
+
+ public String getStatusMessage() {
+ return statusMessage;
+ }
+
+ public void setStatusMessage(String statusMessage) {
+ this.statusMessage = statusMessage;
+ }
+
+ public Integer getPercentProgress() {
+ return percentProgress;
+ }
+
+ public void setPercentProgress(Integer percentProgress) {
+ this.percentProgress = percentProgress;
+ }
+
+ public String getTimeStamp() {
+ return timeStamp;
+ }
+
+ public void setTimeStamp(String timeStamp) {
+ this.timeStamp = timeStamp;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("requestState", requestState).append("statusMessage", statusMessage)
+ .append("percentProgress", percentProgress).append("timestamp", timeStamp).toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java
index 68fd95c293..f239774d57 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java
@@ -25,7 +25,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -33,28 +32,32 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "resources")
@JsonInclude(Include.NON_DEFAULT)
-public class Resources implements Serializable{
-
- private static final long serialVersionUID = 2194797231782624520L;
- @JsonProperty("vnfs")
- private List<Vnfs> vnfs = new ArrayList<>();
- @JsonProperty("networks")
- private List<Networks> networks = new ArrayList<>();
-
- public List<Vnfs> getVnfs() {
- return vnfs;
- }
- public void setVnfs(List<Vnfs> vnfs) {
- this.vnfs = vnfs;
- }
- public List<Networks> getNetworks() {
- return networks;
- }
- public void setNetworks(List<Networks> networks) {
- this.networks = networks;
- }
- @Override
- public String toString() {
- return "Resources [vnfs=" + vnfs + ", networks=" + networks + "]";
- }
-} \ No newline at end of file
+public class Resources implements Serializable {
+
+ private static final long serialVersionUID = 2194797231782624520L;
+ @JsonProperty("vnfs")
+ private List<Vnfs> vnfs = new ArrayList<>();
+ @JsonProperty("networks")
+ private List<Networks> networks = new ArrayList<>();
+
+ public List<Vnfs> getVnfs() {
+ return vnfs;
+ }
+
+ public void setVnfs(List<Vnfs> vnfs) {
+ this.vnfs = vnfs;
+ }
+
+ public List<Networks> getNetworks() {
+ return networks;
+ }
+
+ public void setNetworks(List<Networks> networks) {
+ this.networks = networks;
+ }
+
+ @Override
+ public String toString() {
+ return "Resources [vnfs=" + vnfs + ", networks=" + networks + "]";
+ }
+}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Service.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Service.java
index 66848d343c..c368f67907 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/Service.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Service.java
@@ -25,7 +25,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -33,66 +32,63 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonRootName(value = "service")
@JsonInclude(Include.NON_DEFAULT)
-public class Service implements Serializable{
-
- private static final long serialVersionUID = 2194797231782624520L;
- @JsonProperty("modelInfo")
- protected ModelInfo modelInfo;
- @JsonProperty("cloudConfiguration")
- protected CloudConfiguration cloudConfiguration;
- @JsonProperty("instanceName")
- protected String instanceName;
- @JsonProperty("instanceParams")
- private List<Map<String, String>> instanceParams = new ArrayList<>();
- @JsonProperty("resources")
- protected Resources resources;
+public class Service implements Serializable {
+
+ private static final long serialVersionUID = 2194797231782624520L;
+ @JsonProperty("modelInfo")
+ protected ModelInfo modelInfo;
+ @JsonProperty("cloudConfiguration")
+ protected CloudConfiguration cloudConfiguration;
+ @JsonProperty("instanceName")
+ protected String instanceName;
+ @JsonProperty("instanceParams")
+ private List<Map<String, String>> instanceParams = new ArrayList<>();
+ @JsonProperty("resources")
+ protected Resources resources;
- public ModelInfo getModelInfo() {
- return modelInfo;
- }
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
- public void setModelInfo(ModelInfo modelInfo) {
- this.modelInfo = modelInfo;
- }
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
- public CloudConfiguration getCloudConfiguration() {
- return cloudConfiguration;
- }
+ public CloudConfiguration getCloudConfiguration() {
+ return cloudConfiguration;
+ }
- public void setCloudConfiguration(CloudConfiguration cloudConfiguration) {
- this.cloudConfiguration = cloudConfiguration;
- }
+ public void setCloudConfiguration(CloudConfiguration cloudConfiguration) {
+ this.cloudConfiguration = cloudConfiguration;
+ }
- public String getInstanceName() {
- return instanceName;
- }
+ public String getInstanceName() {
+ return instanceName;
+ }
- public void setInstanceName(String instanceName) {
- this.instanceName = instanceName;
- }
+ public void setInstanceName(String instanceName) {
+ this.instanceName = instanceName;
+ }
- public List<Map<String, String>> getInstanceParams() {
- return instanceParams;
- }
+ public List<Map<String, String>> getInstanceParams() {
+ return instanceParams;
+ }
- public void setInstanceParams(List<Map<String, String>> instanceParams) {
- this.instanceParams = instanceParams;
- }
+ public void setInstanceParams(List<Map<String, String>> instanceParams) {
+ this.instanceParams = instanceParams;
+ }
- public Resources getResources() {
- return resources;
- }
+ public Resources getResources() {
+ return resources;
+ }
- public void setResources(Resources resources) {
- this.resources = resources;
- }
+ public void setResources(Resources resources) {
+ this.resources = resources;
+ }
- @Override
- public String toString() {
- return "Service [modelInfo=" + modelInfo +
- ", cloudConfiguration=" + cloudConfiguration
- + ", instanceName=" + instanceName +
- ", instanceParams=" + instanceParams +
- ", resources=" + resources + "]";
- }
-} \ No newline at end of file
+ @Override
+ public String toString() {
+ return "Service [modelInfo=" + modelInfo + ", cloudConfiguration=" + cloudConfiguration + ", instanceName="
+ + instanceName + ", instanceParams=" + instanceParams + ", resources=" + resources + "]";
+ }
+}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceException.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceException.java
index 7efb7f0bff..f2976136e9 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceException.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceException.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.03.30 at 02:48:23 PM CDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.03.30 at 02:48:23 PM CDT
//
@@ -31,14 +31,15 @@ package org.onap.so.serviceinstancebeans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
-
import com.fasterxml.jackson.annotation.JsonRootName;
/**
- * <p>Java class for serviceException complex type.
+ * <p>
+ * Java class for serviceException complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="serviceException">
@@ -54,9 +55,7 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "serviceException")
@JsonRootName(value = "serviceException")
-public class ServiceException
- extends ExceptionType
-{
+public class ServiceException extends ExceptionType {
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java
index ea241aa074..1a0e13587e 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java
@@ -21,104 +21,103 @@
package org.onap.so.serviceinstancebeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class ServiceInstancesRequest implements Serializable {
- private static final long serialVersionUID = -4959169541182257787L;
- @JsonProperty("requestDetails")
- private RequestDetails requestDetails;
- @JsonProperty("serviceInstanceId")
- private String serviceInstanceId;
- @JsonProperty("vnfInstanceId")
- private String vnfInstanceId;
- @JsonProperty("networkInstanceId")
- private String networkInstanceId;
- @JsonProperty("volumeGroupInstanceId")
- private String volumeGroupInstanceId;
- @JsonProperty("vfModuleInstanceId")
- private String vfModuleInstanceId;
- @JsonProperty("configurationId")
- private String configurationId;
- @JsonProperty("instanceGroupId")
- private String instanceGroupId;
-
- public RequestDetails getRequestDetails() {
- return requestDetails;
- }
-
- public void setRequestDetails(RequestDetails requestDetails) {
- this.requestDetails = requestDetails;
- }
-
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
-
- public String getVnfInstanceId() {
- return vnfInstanceId;
- }
-
- public void setVnfInstanceId(String vnfInstanceId) {
- this.vnfInstanceId = vnfInstanceId;
- }
-
- public String getNetworkInstanceId() {
- return networkInstanceId;
- }
-
- public void setNetworkInstanceId(String networkInstanceId) {
- this.networkInstanceId = networkInstanceId;
- }
-
- public String getVolumeGroupInstanceId() {
- return volumeGroupInstanceId;
- }
-
- public void setVolumeGroupInstanceId(String volumeGroupInstanceId) {
- this.volumeGroupInstanceId = volumeGroupInstanceId;
- }
-
- public String getVfModuleInstanceId() {
- return vfModuleInstanceId;
- }
-
- public void setVfModuleInstanceId(String vfModuleInstanceId) {
- this.vfModuleInstanceId = vfModuleInstanceId;
- }
-
- public String getConfigurationId() {
- return configurationId;
- }
-
- public void setConfigurationId(String configurationId) {
- this.configurationId = configurationId;
- }
-
- public String getInstanceGroupId() {
- return instanceGroupId;
- }
-
- public void setInstanceGroupId(String instanceGroupId) {
- this.instanceGroupId = instanceGroupId;
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder("ServiceInstancesRequest{");
- sb.append("requestDetails=").append(requestDetails);
- sb.append(", serviceInstanceId='").append(serviceInstanceId).append('\'');
- sb.append(", vnfInstanceId='").append(vnfInstanceId).append('\'');
- sb.append(", networkInstanceId='").append(networkInstanceId).append('\'');
- sb.append(", volumeGroupInstanceId='").append(volumeGroupInstanceId).append('\'');
- sb.append(", vfModuleInstanceId='").append(vfModuleInstanceId).append('\'');
- sb.append(", configurationId='").append(configurationId).append('\'');
- sb.append('}');
- return sb.toString();
- }
+ private static final long serialVersionUID = -4959169541182257787L;
+ @JsonProperty("requestDetails")
+ private RequestDetails requestDetails;
+ @JsonProperty("serviceInstanceId")
+ private String serviceInstanceId;
+ @JsonProperty("vnfInstanceId")
+ private String vnfInstanceId;
+ @JsonProperty("networkInstanceId")
+ private String networkInstanceId;
+ @JsonProperty("volumeGroupInstanceId")
+ private String volumeGroupInstanceId;
+ @JsonProperty("vfModuleInstanceId")
+ private String vfModuleInstanceId;
+ @JsonProperty("configurationId")
+ private String configurationId;
+ @JsonProperty("instanceGroupId")
+ private String instanceGroupId;
+
+ public RequestDetails getRequestDetails() {
+ return requestDetails;
+ }
+
+ public void setRequestDetails(RequestDetails requestDetails) {
+ this.requestDetails = requestDetails;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getVnfInstanceId() {
+ return vnfInstanceId;
+ }
+
+ public void setVnfInstanceId(String vnfInstanceId) {
+ this.vnfInstanceId = vnfInstanceId;
+ }
+
+ public String getNetworkInstanceId() {
+ return networkInstanceId;
+ }
+
+ public void setNetworkInstanceId(String networkInstanceId) {
+ this.networkInstanceId = networkInstanceId;
+ }
+
+ public String getVolumeGroupInstanceId() {
+ return volumeGroupInstanceId;
+ }
+
+ public void setVolumeGroupInstanceId(String volumeGroupInstanceId) {
+ this.volumeGroupInstanceId = volumeGroupInstanceId;
+ }
+
+ public String getVfModuleInstanceId() {
+ return vfModuleInstanceId;
+ }
+
+ public void setVfModuleInstanceId(String vfModuleInstanceId) {
+ this.vfModuleInstanceId = vfModuleInstanceId;
+ }
+
+ public String getConfigurationId() {
+ return configurationId;
+ }
+
+ public void setConfigurationId(String configurationId) {
+ this.configurationId = configurationId;
+ }
+
+ public String getInstanceGroupId() {
+ return instanceGroupId;
+ }
+
+ public void setInstanceGroupId(String instanceGroupId) {
+ this.instanceGroupId = instanceGroupId;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("ServiceInstancesRequest{");
+ sb.append("requestDetails=").append(requestDetails);
+ sb.append(", serviceInstanceId='").append(serviceInstanceId).append('\'');
+ sb.append(", vnfInstanceId='").append(vnfInstanceId).append('\'');
+ sb.append(", networkInstanceId='").append(networkInstanceId).append('\'');
+ sb.append(", volumeGroupInstanceId='").append(volumeGroupInstanceId).append('\'');
+ sb.append(", vfModuleInstanceId='").append(vfModuleInstanceId).append('\'');
+ sb.append(", configurationId='").append(configurationId).append('\'');
+ sb.append('}');
+ return sb.toString();
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesResponse.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesResponse.java
index db3add8d47..ded0a21652 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesResponse.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesResponse.java
@@ -23,21 +23,21 @@ package org.onap.so.serviceinstancebeans;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class ServiceInstancesResponse {
-
- RequestReferences requestReferences;
-
- public RequestReferences getRequestReferences() {
- return requestReferences;
- }
-
- public void setRequestReferences(RequestReferences requestReferences) {
- this.requestReferences = requestReferences;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("requestReferences", requestReferences).toString();
- }
-
+
+ RequestReferences requestReferences;
+
+ public RequestReferences getRequestReferences() {
+ return requestReferences;
+ }
+
+ public void setRequestReferences(RequestReferences requestReferences) {
+ this.requestReferences = requestReferences;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("requestReferences", requestReferences).toString();
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/SubscriberInfo.java b/common/src/main/java/org/onap/so/serviceinstancebeans/SubscriberInfo.java
index 03780231fc..590be0955a 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/SubscriberInfo.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/SubscriberInfo.java
@@ -21,7 +21,6 @@
package org.onap.so.serviceinstancebeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,18 +30,16 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class SubscriberInfo implements Serializable {
- private static final long serialVersionUID = -1750701712128104652L;
- @JsonProperty("globalSubscriberId")
+ private static final long serialVersionUID = -1750701712128104652L;
+ @JsonProperty("globalSubscriberId")
protected String globalSubscriberId;
- @JsonProperty("subscriberName")
+ @JsonProperty("subscriberName")
protected String subscriberName;
/**
* Gets the value of the globalSubscriberId property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getGlobalSubscriberId() {
@@ -52,9 +49,7 @@ public class SubscriberInfo implements Serializable {
/**
* Sets the value of the globalSubscriberId property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setGlobalSubscriberId(String value) {
@@ -64,9 +59,7 @@ public class SubscriberInfo implements Serializable {
/**
* Gets the value of the subscriberName property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getSubscriberName() {
@@ -76,19 +69,16 @@ public class SubscriberInfo implements Serializable {
/**
* Sets the value of the subscriberName property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setSubscriberName(String value) {
this.subscriberName = value;
}
- @Override
- public String toString() {
- return "SubscriberInfo [globalSubscriberId=" + globalSubscriberId
- + ", subscriberName=" + subscriberName + "]";
- }
+ @Override
+ public String toString() {
+ return "SubscriberInfo [globalSubscriberId=" + globalSubscriberId + ", subscriberName=" + subscriberName + "]";
+ }
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/VfModules.java b/common/src/main/java/org/onap/so/serviceinstancebeans/VfModules.java
index 74f8af80a7..5c4834d021 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/VfModules.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/VfModules.java
@@ -25,7 +25,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -33,67 +32,66 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonRootName(value = "vfmodules")
@JsonInclude(Include.NON_DEFAULT)
-public class VfModules implements Serializable{
-
- private static final long serialVersionUID = 8081495240474276501L;
- @JsonProperty("modelInfo")
- protected ModelInfo modelInfo;
- @JsonProperty("cloudConfiguration")
- protected CloudConfiguration cloudConfiguration;
- @JsonProperty("instanceName")
- protected String instanceName;
- @JsonProperty("volumeGroupInstanceName")
- protected String volumeGroupInstanceName;
- @JsonProperty("instanceParams")
- private List<Map<String, String>> instanceParams = new ArrayList<>();
-
-
- public ModelInfo getModelInfo() {
- return modelInfo;
- }
-
- public void setModelInfo(ModelInfo modelInfo) {
- this.modelInfo = modelInfo;
- }
-
- public CloudConfiguration getCloudConfiguration() {
- return cloudConfiguration;
- }
-
- public void setCloudConfiguration(CloudConfiguration cloudConfiguration) {
- this.cloudConfiguration = cloudConfiguration;
- }
-
- public String getInstanceName() {
- return instanceName;
- }
-
- public void setInstanceName(String instanceName) {
- this.instanceName = instanceName;
- }
-
- public String getVolumeGroupInstanceName() {
- return volumeGroupInstanceName;
- }
-
- public void setVolumeGroupInstanceName(String volumeGroupInstanceName) {
- this.volumeGroupInstanceName = volumeGroupInstanceName;
- }
-
- public List<Map<String, String>> getInstanceParams() {
- return instanceParams;
- }
-
- public void setInstanceParams(List<Map<String, String>> instanceParams) {
- this.instanceParams = instanceParams;
- }
-
- @Override
- public String toString() {
- return "VfModules [modelInfo=" + modelInfo +
- ", cloudConfiguration=" + cloudConfiguration +
- ", instanceName=" + instanceName + ", volumeGroupInstanceName="
- + volumeGroupInstanceName + ", instanceParams=" + instanceParams + "]";
- }
-
-} \ No newline at end of file
+public class VfModules implements Serializable {
+
+ private static final long serialVersionUID = 8081495240474276501L;
+ @JsonProperty("modelInfo")
+ protected ModelInfo modelInfo;
+ @JsonProperty("cloudConfiguration")
+ protected CloudConfiguration cloudConfiguration;
+ @JsonProperty("instanceName")
+ protected String instanceName;
+ @JsonProperty("volumeGroupInstanceName")
+ protected String volumeGroupInstanceName;
+ @JsonProperty("instanceParams")
+ private List<Map<String, String>> instanceParams = new ArrayList<>();
+
+
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
+
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
+
+ public CloudConfiguration getCloudConfiguration() {
+ return cloudConfiguration;
+ }
+
+ public void setCloudConfiguration(CloudConfiguration cloudConfiguration) {
+ this.cloudConfiguration = cloudConfiguration;
+ }
+
+ public String getInstanceName() {
+ return instanceName;
+ }
+
+ public void setInstanceName(String instanceName) {
+ this.instanceName = instanceName;
+ }
+
+ public String getVolumeGroupInstanceName() {
+ return volumeGroupInstanceName;
+ }
+
+ public void setVolumeGroupInstanceName(String volumeGroupInstanceName) {
+ this.volumeGroupInstanceName = volumeGroupInstanceName;
+ }
+
+ public List<Map<String, String>> getInstanceParams() {
+ return instanceParams;
+ }
+
+ public void setInstanceParams(List<Map<String, String>> instanceParams) {
+ this.instanceParams = instanceParams;
+ }
+
+ @Override
+ public String toString() {
+ return "VfModules [modelInfo=" + modelInfo + ", cloudConfiguration=" + cloudConfiguration + ", instanceName="
+ + instanceName + ", volumeGroupInstanceName=" + volumeGroupInstanceName + ", instanceParams="
+ + instanceParams + "]";
+ }
+
+}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Vnfs.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Vnfs.java
index b55a528935..a2eb35464b 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/Vnfs.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Vnfs.java
@@ -25,7 +25,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -33,99 +32,97 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonRootName(value = "vnfs")
@JsonInclude(Include.NON_DEFAULT)
-public class Vnfs implements Serializable{
-
- private static final long serialVersionUID = 8081495240474276501L;
- @JsonProperty("modelInfo")
- protected ModelInfo modelInfo;
- @JsonProperty("cloudConfiguration")
- protected CloudConfiguration cloudConfiguration;
- @JsonProperty("instanceName")
- protected String instanceName;
- @JsonProperty("platform")
- protected Platform platform;
- @JsonProperty("lineOfBusiness")
- protected LineOfBusiness lineOfBusiness;
- @JsonProperty("productFamilyId")
- protected String productFamilyId;
- @JsonProperty("instanceParams")
- private List<Map<String, String>> instanceParams = new ArrayList<>();
- @JsonProperty("vfModules")
- private List<VfModules> vfModules = new ArrayList<>();
-
-
- public ModelInfo getModelInfo() {
- return modelInfo;
- }
-
- public void setModelInfo(ModelInfo modelInfo) {
- this.modelInfo = modelInfo;
- }
-
- public CloudConfiguration getCloudConfiguration() {
- return cloudConfiguration;
- }
-
- public void setCloudConfiguration(CloudConfiguration cloudConfiguration) {
- this.cloudConfiguration = cloudConfiguration;
- }
-
- public String getInstanceName() {
- return instanceName;
- }
-
- public void setInstanceName(String instanceName) {
- this.instanceName = instanceName;
- }
-
- public Platform getPlatform() {
- return platform;
- }
-
- public void setPlatform(Platform platform) {
- this.platform = platform;
- }
-
- public LineOfBusiness getLineOfBusiness() {
- return lineOfBusiness;
- }
-
- public void setLineOfBusiness(LineOfBusiness lineOfBusiness) {
- this.lineOfBusiness = lineOfBusiness;
- }
-
- public String getProductFamilyId() {
- return productFamilyId;
- }
-
- public void setProductFamilyId(String productFamilyId) {
- this.productFamilyId = productFamilyId;
- }
-
- public List<Map<String, String>> getInstanceParams() {
- return instanceParams;
- }
-
- public void setInstanceParams(List<Map<String, String>> instanceParams) {
- this.instanceParams = instanceParams;
- }
-
- public List<VfModules> getVfModules() {
- return vfModules;
- }
-
- public void setVfModules(List<VfModules> vfModules) {
- this.vfModules = vfModules;
- }
-
- @Override
- public String toString() {
- return "Vnfs [modelInfo=" + modelInfo +
- ", cloudConfiguration=" + cloudConfiguration +
- ", instanceName=" + instanceName + ", platform=" + platform + ", " +
- "lineOfBusiness=" + lineOfBusiness +
- ", productFamilyId=" + productFamilyId + ", instanceParams=" + instanceParams +
- ", vfModules=" + vfModules + "]";
- }
-
-} \ No newline at end of file
+public class Vnfs implements Serializable {
+
+ private static final long serialVersionUID = 8081495240474276501L;
+ @JsonProperty("modelInfo")
+ protected ModelInfo modelInfo;
+ @JsonProperty("cloudConfiguration")
+ protected CloudConfiguration cloudConfiguration;
+ @JsonProperty("instanceName")
+ protected String instanceName;
+ @JsonProperty("platform")
+ protected Platform platform;
+ @JsonProperty("lineOfBusiness")
+ protected LineOfBusiness lineOfBusiness;
+ @JsonProperty("productFamilyId")
+ protected String productFamilyId;
+ @JsonProperty("instanceParams")
+ private List<Map<String, String>> instanceParams = new ArrayList<>();
+ @JsonProperty("vfModules")
+ private List<VfModules> vfModules = new ArrayList<>();
+
+
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
+
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
+
+ public CloudConfiguration getCloudConfiguration() {
+ return cloudConfiguration;
+ }
+
+ public void setCloudConfiguration(CloudConfiguration cloudConfiguration) {
+ this.cloudConfiguration = cloudConfiguration;
+ }
+
+ public String getInstanceName() {
+ return instanceName;
+ }
+
+ public void setInstanceName(String instanceName) {
+ this.instanceName = instanceName;
+ }
+
+ public Platform getPlatform() {
+ return platform;
+ }
+
+ public void setPlatform(Platform platform) {
+ this.platform = platform;
+ }
+
+ public LineOfBusiness getLineOfBusiness() {
+ return lineOfBusiness;
+ }
+
+ public void setLineOfBusiness(LineOfBusiness lineOfBusiness) {
+ this.lineOfBusiness = lineOfBusiness;
+ }
+
+ public String getProductFamilyId() {
+ return productFamilyId;
+ }
+
+ public void setProductFamilyId(String productFamilyId) {
+ this.productFamilyId = productFamilyId;
+ }
+
+ public List<Map<String, String>> getInstanceParams() {
+ return instanceParams;
+ }
+
+ public void setInstanceParams(List<Map<String, String>> instanceParams) {
+ this.instanceParams = instanceParams;
+ }
+
+ public List<VfModules> getVfModules() {
+ return vfModules;
+ }
+
+ public void setVfModules(List<VfModules> vfModules) {
+ this.vfModules = vfModules;
+ }
+
+ @Override
+ public String toString() {
+ return "Vnfs [modelInfo=" + modelInfo + ", cloudConfiguration=" + cloudConfiguration + ", instanceName="
+ + instanceName + ", platform=" + platform + ", " + "lineOfBusiness=" + lineOfBusiness
+ + ", productFamilyId=" + productFamilyId + ", instanceParams=" + instanceParams + ", vfModules="
+ + vfModules + "]";
+ }
+
+}
diff --git a/common/src/main/java/org/onap/so/spring/SpringContextHelper.java b/common/src/main/java/org/onap/so/spring/SpringContextHelper.java
index 1fae5f3e23..b8b08a3917 100644
--- a/common/src/main/java/org/onap/so/spring/SpringContextHelper.java
+++ b/common/src/main/java/org/onap/so/spring/SpringContextHelper.java
@@ -27,14 +27,14 @@ import org.springframework.stereotype.Component;
@Component
public class SpringContextHelper implements ApplicationContextAware {
- private static ApplicationContext context;
+ private static ApplicationContext context;
- @Override
- public void setApplicationContext(ApplicationContext applicationContext) {
- context = applicationContext;
- }
+ @Override
+ public void setApplicationContext(ApplicationContext applicationContext) {
+ context = applicationContext;
+ }
- public static ApplicationContext getAppContext() {
- return context;
- }
+ public static ApplicationContext getAppContext() {
+ return context;
+ }
}
diff --git a/common/src/main/java/org/onap/so/test/categories/SlowTests.java b/common/src/main/java/org/onap/so/test/categories/SlowTests.java
index 58a14041d0..ae5b40b2d6 100644
--- a/common/src/main/java/org/onap/so/test/categories/SlowTests.java
+++ b/common/src/main/java/org/onap/so/test/categories/SlowTests.java
@@ -21,5 +21,5 @@
package org.onap.so.test.categories;
public interface SlowTests {
-/* category marker */
+ /* category marker */
}
diff --git a/common/src/main/java/org/onap/so/utils/CheckResults.java b/common/src/main/java/org/onap/so/utils/CheckResults.java
index 4f6089d0e3..5b4c40e3db 100644
--- a/common/src/main/java/org/onap/so/utils/CheckResults.java
+++ b/common/src/main/java/org/onap/so/utils/CheckResults.java
@@ -24,7 +24,6 @@ package org.onap.so.utils;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@@ -33,33 +32,33 @@ import javax.xml.bind.annotation.XmlRootElement;
public class CheckResults {
@XmlElement(name = "checkresult")
- private List <CheckResult> results;
+ private List<CheckResult> results;
- public CheckResults () {
+ public CheckResults() {
results = new ArrayList<>();
}
- public List <CheckResult> getResults () {
+ public List<CheckResult> getResults() {
return results;
}
- public void addHostCheckResult (String hostname, int state, String output) {
- CheckResult newResult = new CheckResult ();
- newResult.setType ("host");
- newResult.setHostname (hostname);
- newResult.setState (state);
- newResult.setOutput (output);
- results.add (newResult);
+ public void addHostCheckResult(String hostname, int state, String output) {
+ CheckResult newResult = new CheckResult();
+ newResult.setType("host");
+ newResult.setHostname(hostname);
+ newResult.setState(state);
+ newResult.setOutput(output);
+ results.add(newResult);
}
- public void addServiceCheckResult (String hostname, String servicename, int state, String output) {
- CheckResult newResult = new CheckResult ();
- newResult.setType ("service");
- newResult.setHostname (hostname);
- newResult.setServicename (servicename);
- newResult.setState (state);
- newResult.setOutput (output);
- results.add (newResult);
+ public void addServiceCheckResult(String hostname, String servicename, int state, String output) {
+ CheckResult newResult = new CheckResult();
+ newResult.setType("service");
+ newResult.setHostname(hostname);
+ newResult.setServicename(servicename);
+ newResult.setState(state);
+ newResult.setOutput(output);
+ results.add(newResult);
}
public static class CheckResult {
@@ -71,47 +70,47 @@ public class CheckResults {
private String output;
@XmlAttribute(required = true)
- public String getType () {
+ public String getType() {
return type;
}
- public void setType (String type) {
+ public void setType(String type) {
this.type = type;
}
@XmlElement(required = true)
- public String getHostname () {
+ public String getHostname() {
return hostname;
}
- public void setHostname (String hostname) {
+ public void setHostname(String hostname) {
this.hostname = hostname;
}
@XmlElement(required = false)
- public String getServicename () {
+ public String getServicename() {
return servicename;
}
- public void setServicename (String servicename) {
+ public void setServicename(String servicename) {
this.servicename = servicename;
}
@XmlElement(required = true)
- public int getState () {
+ public int getState() {
return state;
}
- public void setState (int state) {
+ public void setState(int state) {
this.state = state;
}
@XmlElement(required = true)
- public String getOutput () {
+ public String getOutput() {
return output;
}
- public void setOutput (String output) {
+ public void setOutput(String output) {
this.output = output;
}
}
diff --git a/common/src/main/java/org/onap/so/utils/CryptoUtils.java b/common/src/main/java/org/onap/so/utils/CryptoUtils.java
index 7d272e39c7..09b48d266f 100644
--- a/common/src/main/java/org/onap/so/utils/CryptoUtils.java
+++ b/common/src/main/java/org/onap/so/utils/CryptoUtils.java
@@ -27,7 +27,6 @@ import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
@@ -52,13 +51,12 @@ public final class CryptoUtils {
private static final String AES_GCM_NO_PADDING = "AES/GCM/NoPadding";
/**
- * encrypt a value and generate a keyfile
- * if the keyfile is not found then a new one is created
+ * encrypt a value and generate a keyfile if the keyfile is not found then a new one is created
*
* @throws GeneralSecurityException
*/
- public static String encrypt (String value, String keyString) throws GeneralSecurityException {
- SecretKeySpec sks = getSecretKeySpec (keyString);
+ public static String encrypt(String value, String keyString) throws GeneralSecurityException {
+ SecretKeySpec sks = getSecretKeySpec(keyString);
Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING);
byte[] initVector = new byte[GCM_IV_LENGTH];
(new SecureRandom()).nextBytes(initVector);
@@ -76,8 +74,8 @@ public final class CryptoUtils {
*
* @throws GeneralSecurityException
*/
- public static String decrypt (String message, String keyString) throws GeneralSecurityException {
- SecretKeySpec sks = getSecretKeySpec (keyString);
+ public static String decrypt(String message, String keyString) throws GeneralSecurityException {
+ SecretKeySpec sks = getSecretKeySpec(keyString);
byte[] cipherText = hexStringToByteArray(message);
Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING);
byte[] initVector = Arrays.copyOfRange(cipherText, 0, GCM_IV_LENGTH);
@@ -86,31 +84,33 @@ public final class CryptoUtils {
byte[] plaintext = cipher.doFinal(cipherText, GCM_IV_LENGTH, cipherText.length - GCM_IV_LENGTH);
return new String(plaintext);
}
-
+
public static String encryptCloudConfigPassword(String message) {
- try {
- return CryptoUtils.encrypt(message, CLOUD_KEY);
- } catch (GeneralSecurityException e) {
- logger.error("{} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(),
- ErrorCode.BusinessProcesssError.getValue(), "Exception in encryptPassword ", e);
- return null;
- }
+ try {
+ return CryptoUtils.encrypt(message, CLOUD_KEY);
+ } catch (GeneralSecurityException e) {
+ logger.error("{} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(),
+ ErrorCode.BusinessProcesssError.getValue(), "Exception in encryptPassword ", e);
+ return null;
+ }
}
+
public static String decryptCloudConfigPassword(String message) {
- try {
- return CryptoUtils.decrypt(message, CLOUD_KEY);
- } catch (GeneralSecurityException e) {
- logger.error("{} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(),
- ErrorCode.BusinessProcesssError.getValue(), "Exception in encryptPassword ", e);
- return null;
- }
+ try {
+ return CryptoUtils.decrypt(message, CLOUD_KEY);
+ } catch (GeneralSecurityException e) {
+ logger.error("{} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(),
+ ErrorCode.BusinessProcesssError.getValue(), "Exception in encryptPassword ", e);
+ return null;
+ }
}
- private static SecretKeySpec getSecretKeySpec (String keyString) {
- byte[] key = hexStringToByteArray (keyString);
- return new SecretKeySpec (key, AES);
+
+ private static SecretKeySpec getSecretKeySpec(String keyString) {
+ byte[] key = hexStringToByteArray(keyString);
+ return new SecretKeySpec(key, AES);
}
- public static String byteArrayToHexString (byte[] b) {
+ public static String byteArrayToHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (byte aB : b) {
int v = aB & 0xff;
@@ -119,14 +119,14 @@ public final class CryptoUtils {
}
sb.append(Integer.toHexString(v));
}
- return sb.toString ().toUpperCase ();
+ return sb.toString().toUpperCase();
}
- private static byte[] hexStringToByteArray (String s) {
- byte[] b = new byte[s.length () / 2];
+ private static byte[] hexStringToByteArray(String s) {
+ byte[] b = new byte[s.length() / 2];
for (int i = 0; i < b.length; i++) {
int index = i * 2;
- int v = Integer.parseInt (s.substring (index, index + 2), 16);
+ int v = Integer.parseInt(s.substring(index, index + 2), 16);
b[i] = (byte) v;
}
return b;
diff --git a/common/src/main/java/org/onap/so/utils/TargetEntity.java b/common/src/main/java/org/onap/so/utils/TargetEntity.java
index a4480f2d95..5f87378b79 100644
--- a/common/src/main/java/org/onap/so/utils/TargetEntity.java
+++ b/common/src/main/java/org/onap/so/utils/TargetEntity.java
@@ -23,18 +23,17 @@ package org.onap.so.utils;
import java.util.EnumSet;
public enum TargetEntity {
- OPENSTACK_ADAPTER, BPMN, GRM ,AAI, DMAAP, POLICY, CATALOG_DB, REQUEST_DB,
- VNF_ADAPTER, SDNC_ADAPTER, SNIRO, SDC, EXTERNAL, MULTICLOUD;
+ OPENSTACK_ADAPTER, BPMN, GRM, AAI, DMAAP, POLICY, CATALOG_DB, REQUEST_DB, VNF_ADAPTER, SDNC_ADAPTER, SNIRO, SDC, EXTERNAL, MULTICLOUD;
private static final String PREFIX = "SO";
public static EnumSet<TargetEntity> getSOInternalComponents() {
- return EnumSet.of(OPENSTACK_ADAPTER, BPMN,CATALOG_DB,REQUEST_DB,VNF_ADAPTER,SDNC_ADAPTER);
+ return EnumSet.of(OPENSTACK_ADAPTER, BPMN, CATALOG_DB, REQUEST_DB, VNF_ADAPTER, SDNC_ADAPTER);
}
@Override
- public String toString(){
- if(getSOInternalComponents().contains(this))
+ public String toString() {
+ if (getSOInternalComponents().contains(this))
return TargetEntity.PREFIX + "." + this.name();
else
return this.name();
diff --git a/common/src/main/java/org/onap/so/utils/UUIDChecker.java b/common/src/main/java/org/onap/so/utils/UUIDChecker.java
index 19a92b834c..585ffcc7c4 100644
--- a/common/src/main/java/org/onap/so/utils/UUIDChecker.java
+++ b/common/src/main/java/org/onap/so/utils/UUIDChecker.java
@@ -24,7 +24,6 @@
package org.onap.so.utils;
import java.util.UUID;
-
import org.onap.so.logger.MessageEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -35,10 +34,9 @@ public class UUIDChecker {
private static final Logger logger = LoggerFactory.getLogger(UUIDChecker.class);
- private UUIDChecker() {
- }
+ private UUIDChecker() {}
- public static boolean isValidUUID (String id) {
+ public static boolean isValidUUID(String id) {
try {
if (null == id) {
return false;
@@ -51,7 +49,7 @@ public class UUIDChecker {
}
}
- public static String getUUID () {
+ public static String getUUID() {
String result = UUID.randomUUID().toString();
logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID, result);
return result;
diff --git a/common/src/main/java/org/onap/so/utils/XmlMarshaller.java b/common/src/main/java/org/onap/so/utils/XmlMarshaller.java
index 4aeecf88d8..0022ecbb96 100644
--- a/common/src/main/java/org/onap/so/utils/XmlMarshaller.java
+++ b/common/src/main/java/org/onap/so/utils/XmlMarshaller.java
@@ -25,7 +25,6 @@ package org.onap.so.utils;
import java.io.StringReader;
import java.io.StringWriter;
-
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
@@ -33,7 +32,6 @@ import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;
-
import org.onap.so.exceptions.MarshallerException;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
@@ -54,8 +52,8 @@ public class XmlMarshaller {
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.marshal(object, stringWriter);
} catch (JAXBException e) {
- logger.error("{} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(),
- ErrorCode.SchemaError.getValue(), e.getMessage(), e);
+ logger.error("{} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), ErrorCode.SchemaError.getValue(),
+ e.getMessage(), e);
throw new MarshallerException(e.getMessage(), ErrorCode.SchemaError.getValue(), e);
}
@@ -79,8 +77,8 @@ public class XmlMarshaller {
SAXSource source = new SAXSource(xmlReader, inputSource);
object = jaxbUnmarshaller.unmarshal(source, object.getClass()).getValue();
} catch (Exception e) {
- logger.error("{} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(),
- ErrorCode.SchemaError.getValue(), e.getMessage(), e);
+ logger.error("{} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), ErrorCode.SchemaError.getValue(),
+ e.getMessage(), e);
throw new MarshallerException(e.getMessage(), ErrorCode.SchemaError.getValue(), e);
}
diff --git a/common/src/main/java/org/onap/so/web/exceptions/ExceptionResponse.java b/common/src/main/java/org/onap/so/web/exceptions/ExceptionResponse.java
index 048634190a..7fec597521 100644
--- a/common/src/main/java/org/onap/so/web/exceptions/ExceptionResponse.java
+++ b/common/src/main/java/org/onap/so/web/exceptions/ExceptionResponse.java
@@ -25,22 +25,21 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "message"
-})
+@JsonPropertyOrder({"message"})
public class ExceptionResponse {
- @JsonProperty("message")
- private String message;
+ @JsonProperty("message")
+ private String message;
- public ExceptionResponse(String message) {
- this.message = message;
- }
- public String getMessage() {
- return message;
- }
+ public ExceptionResponse(String message) {
+ this.message = message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
}
diff --git a/common/src/main/java/org/onap/so/web/exceptions/RuntimeExceptionMapper.java b/common/src/main/java/org/onap/so/web/exceptions/RuntimeExceptionMapper.java
index 2c249f1607..d20433df2e 100644
--- a/common/src/main/java/org/onap/so/web/exceptions/RuntimeExceptionMapper.java
+++ b/common/src/main/java/org/onap/so/web/exceptions/RuntimeExceptionMapper.java
@@ -26,23 +26,22 @@ import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
-
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RuntimeExceptionMapper implements ExceptionMapper<RuntimeException> {
- private static Logger logger = LoggerFactory.getLogger(RuntimeExceptionMapper.class);
+ private static Logger logger = LoggerFactory.getLogger(RuntimeExceptionMapper.class);
+
+ @Override
+ public Response toResponse(RuntimeException exception) {
- @Override
- public Response toResponse(RuntimeException exception) {
-
- if (exception instanceof NotFoundException) {
- return Response.status(Status.NOT_FOUND).build();
- } else {
- logger.error("Error occured", exception);
- return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new ExceptionResponse("Unexpected Internal Exception")).build();
- }
- }
+ if (exception instanceof NotFoundException) {
+ return Response.status(Status.NOT_FOUND).build();
+ } else {
+ logger.error("Error occured", exception);
+ return Response.status(Status.INTERNAL_SERVER_ERROR)
+ .entity(new ExceptionResponse("Unexpected Internal Exception")).build();
+ }
+ }
}
diff --git a/common/src/test/java/org/onap/so/BeansTest.java b/common/src/test/java/org/onap/so/BeansTest.java
index 54cbced563..8bde3c4eb7 100644
--- a/common/src/test/java/org/onap/so/BeansTest.java
+++ b/common/src/test/java/org/onap/so/BeansTest.java
@@ -24,17 +24,14 @@ import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.onap.so.openpojo.rules.HasAnnotationMatcher.hasAnnotation;
import static org.onap.so.openpojo.rules.HasAnnotationPropertyWithValueMatcher.hasAnnotationPropertyWithValue;
-
import javax.persistence.Column;
import javax.persistence.Temporal;
-
import org.junit.Test;
import org.onap.so.openpojo.rules.CustomSetterMustExistRule;
import org.onap.so.openpojo.rules.EqualsAndHashCodeTester;
import org.onap.so.openpojo.rules.HasEqualsAndHashCodeRule;
import org.onap.so.openpojo.rules.HasToStringRule;
import org.onap.so.openpojo.rules.ToStringTester;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterEnum;
@@ -55,42 +52,39 @@ import com.openpojo.validation.test.impl.SetterTester;
public class BeansTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
-
- private PojoClassFilter enumFilter = new FilterEnum();
-
-
-
- @Test
- public void pojoStructure() {
- test("org.onap.so.client.policy.entities");
- test("org.onap.so.client.grm.beans");
- test("org.onap.so.client.ruby.beans");
- test("org.onap.so.client.sdno.beans");
- test("org.onap.so.entity");
- test("org.onap.so.serviceinstancebeans");
- }
-
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new NoNestedClassRule())
- .with(new NoStaticExceptFinalRule())
- .with(new SerializableMustHaveSerialVersionUIDRule())
- .with(new NoPublicFieldsExceptStaticFinalRule())
- .with(new SetterTester())
- .with(new GetterTester())
-
-
-
- .build();
-
-
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses,enumFilter,new FilterNonConcrete());
- }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ private PojoClassFilter enumFilter = new FilterEnum();
+
+
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.client.policy.entities");
+ test("org.onap.so.client.grm.beans");
+ test("org.onap.so.client.ruby.beans");
+ test("org.onap.so.client.sdno.beans");
+ test("org.onap.so.entity");
+ test("org.onap.so.serviceinstancebeans");
+ }
+
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new NoNestedClassRule())
+ .with(new NoStaticExceptFinalRule()).with(new SerializableMustHaveSerialVersionUIDRule())
+ .with(new NoPublicFieldsExceptStaticFinalRule()).with(new SetterTester()).with(new GetterTester())
+
+
+
+ .build();
+
+
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, enumFilter,
+ new FilterNonConcrete());
+ }
+
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/common/src/test/java/org/onap/so/NonSpringSuite.java b/common/src/test/java/org/onap/so/NonSpringSuite.java
index 86bb421123..f7a36768b2 100644
--- a/common/src/test/java/org/onap/so/NonSpringSuite.java
+++ b/common/src/test/java/org/onap/so/NonSpringSuite.java
@@ -22,7 +22,6 @@ package org.onap.so;
import org.junit.runner.RunWith;
import org.onap.so.test.categories.SpringAware;
-
import com.googlecode.junittoolbox.ExcludeCategories;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
diff --git a/common/src/test/java/org/onap/so/SpringSuite.java b/common/src/test/java/org/onap/so/SpringSuite.java
index 93d4d31f5c..1bd019f69b 100644
--- a/common/src/test/java/org/onap/so/SpringSuite.java
+++ b/common/src/test/java/org/onap/so/SpringSuite.java
@@ -22,7 +22,6 @@ package org.onap.so;
import org.junit.runner.RunWith;
import org.onap.so.test.categories.SpringAware;
-
import com.googlecode.junittoolbox.IncludeCategories;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
diff --git a/common/src/test/java/org/onap/so/adapter_utils/tests/CryptoTest.java b/common/src/test/java/org/onap/so/adapter_utils/tests/CryptoTest.java
index 418220778a..1c7c472830 100644
--- a/common/src/test/java/org/onap/so/adapter_utils/tests/CryptoTest.java
+++ b/common/src/test/java/org/onap/so/adapter_utils/tests/CryptoTest.java
@@ -24,12 +24,9 @@ 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.security.GeneralSecurityException;
-
import org.junit.BeforeClass;
import org.junit.Test;
-
import org.onap.so.utils.CryptoUtils;
/**
@@ -39,45 +36,45 @@ import org.onap.so.utils.CryptoUtils;
*/
public class CryptoTest {
- private static String testKey = "546573746F736973546573746F736973";
+ private static String testKey = "546573746F736973546573746F736973";
- /**
- * This method is called before any test occurs.
- * It creates a fake tree from scratch
+ /**
+ * This method is called before any test occurs. It creates a fake tree from scratch
*/
@BeforeClass
- public static final void prepare () {
-
+ public static final void prepare() {
+
}
/**
* This method implements a test of tree structure, mainly the storage of the leaves structure.
- * @throws GeneralSecurityException
+ *
+ * @throws GeneralSecurityException
*/
@Test
- public final void testEncryption () throws GeneralSecurityException {
- String hexString = CryptoUtils.byteArrayToHexString("testosistestosi".getBytes());
-
- final String testData = "This is a test string";
- final String nonTestData = "This is not the right String";
-
- String encodeString = CryptoUtils.encrypt(testData, testKey);
-
- assertNotNull(encodeString);
-
- assertTrue(testData.equals(CryptoUtils.decrypt(encodeString, testKey)));
- assertFalse(nonTestData.equals(CryptoUtils.decrypt(encodeString, testKey)));
-
- String encode2String = CryptoUtils.encrypt(testData, testKey);
- assertNotNull(encode2String);
-
- assertEquals(CryptoUtils.decrypt(encodeString, testKey),CryptoUtils.decrypt(encode2String, testKey));
-
- encodeString = CryptoUtils.encryptCloudConfigPassword(testData);
-
- assertEquals(testData, CryptoUtils.decryptCloudConfigPassword(encodeString));
-
- System.out.println(CryptoUtils.encrypt("poBpmn:password1$", "aa3871669d893c7fb8abbcda31b88b4f"));
+ public final void testEncryption() throws GeneralSecurityException {
+ String hexString = CryptoUtils.byteArrayToHexString("testosistestosi".getBytes());
+
+ final String testData = "This is a test string";
+ final String nonTestData = "This is not the right String";
+
+ String encodeString = CryptoUtils.encrypt(testData, testKey);
+
+ assertNotNull(encodeString);
+
+ assertTrue(testData.equals(CryptoUtils.decrypt(encodeString, testKey)));
+ assertFalse(nonTestData.equals(CryptoUtils.decrypt(encodeString, testKey)));
+
+ String encode2String = CryptoUtils.encrypt(testData, testKey);
+ assertNotNull(encode2String);
+
+ assertEquals(CryptoUtils.decrypt(encodeString, testKey), CryptoUtils.decrypt(encode2String, testKey));
+
+ encodeString = CryptoUtils.encryptCloudConfigPassword(testData);
+
+ assertEquals(testData, CryptoUtils.decryptCloudConfigPassword(encodeString));
+
+ System.out.println(CryptoUtils.encrypt("poBpmn:password1$", "aa3871669d893c7fb8abbcda31b88b4f"));
}
}
diff --git a/common/src/test/java/org/onap/so/client/HttpClientTest.java b/common/src/test/java/org/onap/so/client/HttpClientTest.java
index 346bf1426d..b12ed5956a 100644
--- a/common/src/test/java/org/onap/so/client/HttpClientTest.java
+++ b/common/src/test/java/org/onap/so/client/HttpClientTest.java
@@ -28,80 +28,73 @@ import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
-
import java.net.MalformedURLException;
import java.net.URL;
-
import org.junit.Rule;
import org.junit.Test;
import org.onap.so.utils.TargetEntity;
-
import com.github.tomakehurst.wiremock.junit.WireMockRule;
-public class HttpClientTest{
+public class HttpClientTest {
- private final HttpClientFactory httpClientFactory = new HttpClientFactory();
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicHttpsPort());
+ private final HttpClientFactory httpClientFactory = new HttpClientFactory();
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicHttpsPort());
- @Test
- public void testPost_success() throws MalformedURLException{
+ @Test
+ public void testPost_success() throws MalformedURLException {
- wireMockRule.stubFor(post(urlEqualTo("/services/sdnc/post"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody("")));
+ wireMockRule.stubFor(post(urlEqualTo("/services/sdnc/post"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody("")));
- URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post");
- HttpClient client = httpClientFactory.newJsonClient(url, TargetEntity.BPMN);
+ URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post");
+ HttpClient client = httpClientFactory.newJsonClient(url, TargetEntity.BPMN);
- client.addBasicAuthHeader("97FF88AB352DA16E00DDD81E3876431DEF8744465DACA489EB3B3BE1F10F63EDA1715E626D0A4827A3E19CD88421BF", "123");
- client.addAdditionalHeader("Accept", "application/json");
+ client.addBasicAuthHeader(
+ "97FF88AB352DA16E00DDD81E3876431DEF8744465DACA489EB3B3BE1F10F63EDA1715E626D0A4827A3E19CD88421BF",
+ "123");
+ client.addAdditionalHeader("Accept", "application/json");
- client.post("{}");
+ client.post("{}");
- verify(exactly(1), postRequestedFor(urlEqualTo("/services/sdnc/post")));
- }
+ verify(exactly(1), postRequestedFor(urlEqualTo("/services/sdnc/post")));
+ }
@Test
- public void testPost_nullHeader() throws MalformedURLException{
+ public void testPost_nullHeader() throws MalformedURLException {
- wireMockRule.stubFor(post(urlEqualTo("/services/sdnc/post"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody("")));
+ wireMockRule.stubFor(post(urlEqualTo("/services/sdnc/post"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody("")));
- URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post");
- HttpClient client = httpClientFactory.newJsonClient(url, TargetEntity.BPMN);
+ URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post");
+ HttpClient client = httpClientFactory.newJsonClient(url, TargetEntity.BPMN);
- client.addAdditionalHeader("Accept", "application/json");
- client.addAdditionalHeader("id", null);
+ client.addAdditionalHeader("Accept", "application/json");
+ client.addAdditionalHeader("id", null);
- client.post("{}");
+ client.post("{}");
- verify(exactly(1), postRequestedFor(urlEqualTo("/services/sdnc/post"))
- .withHeader("Accept", equalTo("application/json")));
- }
+ verify(exactly(1),
+ postRequestedFor(urlEqualTo("/services/sdnc/post")).withHeader("Accept", equalTo("application/json")));
+ }
@Test
- public void testPost_nullBasicAuth() throws MalformedURLException{
+ public void testPost_nullBasicAuth() throws MalformedURLException {
- wireMockRule.stubFor(post(urlEqualTo("/services/sdnc/post"))
- .willReturn(aResponse().withStatus(200)
- .withHeader("Content-Type", "application/json")
- .withBody("")));
+ wireMockRule.stubFor(post(urlEqualTo("/services/sdnc/post"))
+ .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody("")));
- URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post");
- HttpClient client = httpClientFactory.newJsonClient(url, TargetEntity.BPMN);
+ URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post");
+ HttpClient client = httpClientFactory.newJsonClient(url, TargetEntity.BPMN);
- client.addBasicAuthHeader("", "12345");
- client.addAdditionalHeader("Accept", "application/json");
+ client.addBasicAuthHeader("", "12345");
+ client.addAdditionalHeader("Accept", "application/json");
- client.post("{}");
+ client.post("{}");
- verify(exactly(1), postRequestedFor(urlEqualTo("/services/sdnc/post"))
- .withHeader("Accept", equalTo("application/json")));
- }
+ verify(exactly(1),
+ postRequestedFor(urlEqualTo("/services/sdnc/post")).withHeader("Accept", equalTo("application/json")));
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/RestClientTest.java b/common/src/test/java/org/onap/so/client/RestClientTest.java
index 06196fd73e..b550079607 100644
--- a/common/src/test/java/org/onap/so/client/RestClientTest.java
+++ b/common/src/test/java/org/onap/so/client/RestClientTest.java
@@ -28,15 +28,12 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
-
import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriBuilderException;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -48,44 +45,45 @@ import org.mockito.junit.MockitoJUnitRunner;
public class RestClientTest {
- private final HttpClientFactory httpClientFactory = new HttpClientFactory();
- @Mock
- private RestProperties props;
+ private final HttpClientFactory httpClientFactory = new HttpClientFactory();
+ @Mock
+ private RestProperties props;
+
+
+ @Test
+ public void retries() throws Exception {
+ RestClient spy = buildSpy();
+ RestRequest mockCallable = mock(RestRequest.class);
+ when(mockCallable.call()).thenThrow(new WebApplicationException(new SocketTimeoutException()));
+ doReturn(mockCallable).when(spy).buildRequest(any(String.class), ArgumentMatchers.isNull());
+ try {
+ spy.get();
+ } catch (Exception e) {
+ // we expect an exception, ignore it
+ }
+ verify(mockCallable, times(3)).call();
+
+ }
+
+ @Test
+ public void exceptionDoNotRetry() throws Exception {
+ RestClient spy = buildSpy();
+ RestRequest mockCallable = mock(RestRequest.class);
+ when(mockCallable.call()).thenThrow(new WebApplicationException(new NotFoundException()));
+ doReturn(mockCallable).when(spy).buildRequest(any(String.class), ArgumentMatchers.isNull());
+ try {
+ spy.get();
+ } catch (Exception e) {
+ // we expect an exception, ignore it
+ }
+ verify(mockCallable, times(1)).call();
+
+ }
+ private RestClient buildSpy() throws MalformedURLException, IllegalArgumentException, UriBuilderException {
+ RestClient client = httpClientFactory.newJsonClient(UriBuilder.fromUri("http://localhost/test").build().toURL(),
+ TargetEntity.BPMN);
- @Test
- public void retries() throws Exception {
- RestClient spy = buildSpy();
- RestRequest mockCallable = mock(RestRequest.class);
- when(mockCallable.call()).thenThrow(new WebApplicationException(new SocketTimeoutException()));
- doReturn(mockCallable).when(spy).buildRequest(any(String.class), ArgumentMatchers.isNull());
- try {
- spy.get();
- } catch (Exception e) {
- //we expect an exception, ignore it
- }
- verify(mockCallable, times(3)).call();
-
- }
-
- @Test
- public void exceptionDoNotRetry() throws Exception {
- RestClient spy = buildSpy();
- RestRequest mockCallable = mock(RestRequest.class);
- when(mockCallable.call()).thenThrow(new WebApplicationException(new NotFoundException()));
- doReturn(mockCallable).when(spy).buildRequest(any(String.class), ArgumentMatchers.isNull());
- try {
- spy.get();
- } catch (Exception e) {
- //we expect an exception, ignore it
- }
- verify(mockCallable, times(1)).call();
-
- }
- private RestClient buildSpy() throws MalformedURLException, IllegalArgumentException, UriBuilderException {
- RestClient client = httpClientFactory
- .newJsonClient(UriBuilder.fromUri("http://localhost/test").build().toURL(), TargetEntity.BPMN);
-
- return spy(client);
- }
+ return spy(client);
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIClientResponseExceptionMapperTest.java b/common/src/test/java/org/onap/so/client/aai/AAIClientResponseExceptionMapperTest.java
index 981a4ddacc..7af36b0bdd 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIClientResponseExceptionMapperTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIClientResponseExceptionMapperTest.java
@@ -21,50 +21,48 @@
package org.onap.so.client.aai;
import static org.junit.Assert.assertEquals;
-
import java.util.Arrays;
import java.util.List;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.so.client.aai.entities.AAIError;
import org.onap.so.client.aai.entities.RequestError;
import org.onap.so.client.aai.entities.ServiceException;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class AAIClientResponseExceptionMapperTest {
- AAIClientResponseExceptionMapper mapper;
- String errorMsg;
-
- @Before
- public void before() {
- mapper = new AAIClientResponseExceptionMapper();
- errorMsg = "Error calling A&AI. Request-Id=" + mapper.getRequestId() + " ";
- }
-
- @Test
- public void testExtractMessageWithEntity() throws JsonProcessingException {
- ServiceException svcException = new ServiceException();
- svcException.setText("test %1 message - %2");
- svcException.setVariables(Arrays.asList("error", "service exception %1 test"));
-
- RequestError requestError = new RequestError();
- requestError.setServiceException(svcException);
-
- AAIError error = new AAIError();
- error.setRequestError(requestError);
-
- ObjectMapper objMapper = new ObjectMapper();
- String strRequestError = objMapper.writeValueAsString(error);
+ AAIClientResponseExceptionMapper mapper;
+ String errorMsg;
+
+ @Before
+ public void before() {
+ mapper = new AAIClientResponseExceptionMapper();
+ errorMsg = "Error calling A&AI. Request-Id=" + mapper.getRequestId() + " ";
+ }
+
+ @Test
+ public void testExtractMessageWithEntity() throws JsonProcessingException {
+ ServiceException svcException = new ServiceException();
+ svcException.setText("test %1 message - %2");
+ svcException.setVariables(Arrays.asList("error", "service exception %1 test"));
+
+ RequestError requestError = new RequestError();
+ requestError.setServiceException(svcException);
+
+ AAIError error = new AAIError();
+ error.setRequestError(requestError);
+
+ ObjectMapper objMapper = new ObjectMapper();
+ String strRequestError = objMapper.writeValueAsString(error);
+
+ assertEquals(errorMsg + "test error message - service exception error test",
+ mapper.extractMessage(strRequestError).get());
+ }
- assertEquals(errorMsg + "test error message - service exception error test", mapper.extractMessage(strRequestError).get());
- }
-
- @Test
- public void testExtractMessageWithoutEntity() {
- assertEquals(errorMsg, mapper.extractMessage("").get());
- }
+ @Test
+ public void testExtractMessageWithoutEntity() {
+ assertEquals(errorMsg, mapper.extractMessage("").get());
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIConfigurationClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAIConfigurationClientTest.java
index 525dff7562..cf87355ec7 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIConfigurationClientTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIConfigurationClientTest.java
@@ -26,10 +26,8 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.Optional;
import java.util.UUID;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
@@ -40,116 +38,119 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.onap.so.serviceinstancebeans.ModelInfo;
import org.onap.so.serviceinstancebeans.RequestDetails;
-@RunWith(MockitoJUnitRunner.class)
+
+@RunWith(MockitoJUnitRunner.class)
public class AAIConfigurationClientTest {
- @Mock
- AAIResourcesClient aaiClient;
-
- @InjectMocks
- AAIConfigurationClient aaiConfigurationClient = new AAIConfigurationClient();
-
- @Test
- public void verifyCreate() {
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelInvariantId("testInvariantID");
- modelInfo.setModelVersionId("testVersionID");
- modelInfo.setModelCustomizationId("testCustomizationID");
-
- RequestDetails requestDetails = new RequestDetails();
- requestDetails.setModelInfo(modelInfo);
-
- String configurationId = UUID.randomUUID().toString();
- String configurationType = "test";
- String configurationSubType = "test";
-
- // Test Create Configuration
- doNothing().when(aaiClient).create(isA(AAIResourceUri.class), isA(Object.class));
- aaiConfigurationClient.createConfiguration(requestDetails, configurationId, configurationType, configurationSubType);
- verify(aaiClient, times(1)).create(isA(AAIResourceUri.class), isA(Object.class));
- }
-
- @Test
- public void verifyConfigurePayload() {
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelInvariantId("testInvariantID");
- modelInfo.setModelVersionId("testVersionID");
- modelInfo.setModelCustomizationId("testCustomizationID");
-
- RequestDetails requestDetails = new RequestDetails();
- requestDetails.setModelInfo(modelInfo);
-
- String configurationId = UUID.randomUUID().toString();
- String configurationType = "test";
- String configurationSubType = "test";
- AAIResourceUri uri = aaiConfigurationClient.getConfigurationURI(configurationId);
-
- Configuration payload = aaiConfigurationClient.configurePayload(requestDetails, configurationId, configurationType, configurationSubType);
-
- assertEquals(configurationId, payload.getConfigurationId());
- assertEquals(configurationType, payload.getConfigurationType());
- assertEquals(configurationSubType, payload.getConfigurationSubType());
- assertEquals(uri.build().getPath(), payload.getConfigurationSelflink());
- assertEquals("PreCreated", payload.getOrchestrationStatus());
- assertEquals("", payload.getOperationalStatus());
- assertEquals(modelInfo.getModelVersionId(), payload.getModelVersionId());
- assertEquals(modelInfo.getModelInvariantId(), payload.getModelInvariantId());
- assertEquals(modelInfo.getModelCustomizationId(), payload.getModelCustomizationId());
- }
-
- @Test
- public void testDeleteConfiguration() {
- String uuid = UUID.randomUUID().toString();
- doNothing().when(aaiClient).delete(isA(AAIResourceUri.class));
- aaiConfigurationClient.deleteConfiguration(uuid);
- verify(aaiClient, times(1)).delete(aaiConfigurationClient.getConfigurationURI(uuid));
- }
-
- @Test
- public void testUpdateOrchestrationStatus() {
- String uuid = UUID.randomUUID().toString();
- doNothing().when(aaiClient).update(isA(AAIResourceUri.class), isA(Object.class));
- aaiConfigurationClient.updateOrchestrationStatus(uuid, "testPayload");
- verify(aaiClient, times(1)).update(aaiConfigurationClient.getConfigurationURI(uuid), "testPayload");
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testGetConfiguration() {
- String uuid = UUID.randomUUID().toString();
- Optional<Configuration> expectedConfiguration = Optional.of(new Configuration());
- expectedConfiguration.get().setConfigurationId(uuid);
-
- doReturn(expectedConfiguration).when(aaiClient).get(isA(Class.class), isA(AAIResourceUri.class));
- Configuration actualConfiguration = aaiConfigurationClient.getConfiguration(uuid);
- verify(aaiClient, times(1)).get(Configuration.class, aaiConfigurationClient.getConfigurationURI(uuid));
- assertEquals(expectedConfiguration.get(), actualConfiguration);
- }
-
- @Test
- public void testConfigurationExists() {
- String uuid = UUID.randomUUID().toString();
- AAIResourceUri uri = aaiConfigurationClient.getConfigurationURI(uuid);
- boolean expectedResult;
- boolean actualResult;
-
- expectedResult = true;
- doReturn(expectedResult).when(aaiClient).exists(isA(AAIResourceUri.class));
- actualResult = aaiConfigurationClient.configurationExists(uuid);
- assertEquals(expectedResult, actualResult);
-
- expectedResult = false;
- doReturn(expectedResult).when(aaiClient).exists(isA(AAIResourceUri.class));
- actualResult = aaiConfigurationClient.configurationExists(uuid);
- assertEquals(expectedResult, actualResult);
-
- verify(aaiClient, times(2)).exists(uri);
- }
-
- @Test
- public void testGetConfigurationURI() {
- String uuid = UUID.randomUUID().toString();
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, uuid);
- assertEquals(uri, aaiConfigurationClient.getConfigurationURI(uuid));
- }
+ @Mock
+ AAIResourcesClient aaiClient;
+
+ @InjectMocks
+ AAIConfigurationClient aaiConfigurationClient = new AAIConfigurationClient();
+
+ @Test
+ public void verifyCreate() {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelInvariantId("testInvariantID");
+ modelInfo.setModelVersionId("testVersionID");
+ modelInfo.setModelCustomizationId("testCustomizationID");
+
+ RequestDetails requestDetails = new RequestDetails();
+ requestDetails.setModelInfo(modelInfo);
+
+ String configurationId = UUID.randomUUID().toString();
+ String configurationType = "test";
+ String configurationSubType = "test";
+
+ // Test Create Configuration
+ doNothing().when(aaiClient).create(isA(AAIResourceUri.class), isA(Object.class));
+ aaiConfigurationClient.createConfiguration(requestDetails, configurationId, configurationType,
+ configurationSubType);
+ verify(aaiClient, times(1)).create(isA(AAIResourceUri.class), isA(Object.class));
+ }
+
+ @Test
+ public void verifyConfigurePayload() {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelInvariantId("testInvariantID");
+ modelInfo.setModelVersionId("testVersionID");
+ modelInfo.setModelCustomizationId("testCustomizationID");
+
+ RequestDetails requestDetails = new RequestDetails();
+ requestDetails.setModelInfo(modelInfo);
+
+ String configurationId = UUID.randomUUID().toString();
+ String configurationType = "test";
+ String configurationSubType = "test";
+ AAIResourceUri uri = aaiConfigurationClient.getConfigurationURI(configurationId);
+
+ Configuration payload = aaiConfigurationClient.configurePayload(requestDetails, configurationId,
+ configurationType, configurationSubType);
+
+ assertEquals(configurationId, payload.getConfigurationId());
+ assertEquals(configurationType, payload.getConfigurationType());
+ assertEquals(configurationSubType, payload.getConfigurationSubType());
+ assertEquals(uri.build().getPath(), payload.getConfigurationSelflink());
+ assertEquals("PreCreated", payload.getOrchestrationStatus());
+ assertEquals("", payload.getOperationalStatus());
+ assertEquals(modelInfo.getModelVersionId(), payload.getModelVersionId());
+ assertEquals(modelInfo.getModelInvariantId(), payload.getModelInvariantId());
+ assertEquals(modelInfo.getModelCustomizationId(), payload.getModelCustomizationId());
+ }
+
+ @Test
+ public void testDeleteConfiguration() {
+ String uuid = UUID.randomUUID().toString();
+ doNothing().when(aaiClient).delete(isA(AAIResourceUri.class));
+ aaiConfigurationClient.deleteConfiguration(uuid);
+ verify(aaiClient, times(1)).delete(aaiConfigurationClient.getConfigurationURI(uuid));
+ }
+
+ @Test
+ public void testUpdateOrchestrationStatus() {
+ String uuid = UUID.randomUUID().toString();
+ doNothing().when(aaiClient).update(isA(AAIResourceUri.class), isA(Object.class));
+ aaiConfigurationClient.updateOrchestrationStatus(uuid, "testPayload");
+ verify(aaiClient, times(1)).update(aaiConfigurationClient.getConfigurationURI(uuid), "testPayload");
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testGetConfiguration() {
+ String uuid = UUID.randomUUID().toString();
+ Optional<Configuration> expectedConfiguration = Optional.of(new Configuration());
+ expectedConfiguration.get().setConfigurationId(uuid);
+
+ doReturn(expectedConfiguration).when(aaiClient).get(isA(Class.class), isA(AAIResourceUri.class));
+ Configuration actualConfiguration = aaiConfigurationClient.getConfiguration(uuid);
+ verify(aaiClient, times(1)).get(Configuration.class, aaiConfigurationClient.getConfigurationURI(uuid));
+ assertEquals(expectedConfiguration.get(), actualConfiguration);
+ }
+
+ @Test
+ public void testConfigurationExists() {
+ String uuid = UUID.randomUUID().toString();
+ AAIResourceUri uri = aaiConfigurationClient.getConfigurationURI(uuid);
+ boolean expectedResult;
+ boolean actualResult;
+
+ expectedResult = true;
+ doReturn(expectedResult).when(aaiClient).exists(isA(AAIResourceUri.class));
+ actualResult = aaiConfigurationClient.configurationExists(uuid);
+ assertEquals(expectedResult, actualResult);
+
+ expectedResult = false;
+ doReturn(expectedResult).when(aaiClient).exists(isA(AAIResourceUri.class));
+ actualResult = aaiConfigurationClient.configurationExists(uuid);
+ assertEquals(expectedResult, actualResult);
+
+ verify(aaiClient, times(2)).exists(uri);
+ }
+
+ @Test
+ public void testGetConfigurationURI() {
+ String uuid = UUID.randomUUID().toString();
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, uuid);
+ assertEquals(uri, aaiConfigurationClient.getConfigurationURI(uuid));
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIErrorFormatterTest.java b/common/src/test/java/org/onap/so/client/aai/AAIErrorFormatterTest.java
index bea927afa5..2ef50dd77b 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIErrorFormatterTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIErrorFormatterTest.java
@@ -22,11 +22,9 @@ package org.onap.so.client.aai;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
@@ -37,52 +35,54 @@ import org.onap.so.client.aai.entities.ServiceException;
public class AAIErrorFormatterTest {
- @Mock private AAIError errorObj;
-
- @Before
- public void init() {
- MockitoAnnotations.initMocks(this);
- }
- @Test
- public void testFillInTemplateWithReplace() {
- String error = "Error %1 on %2";
- List<String> list = Arrays.asList("PUT", "hello %1");
- AAIErrorFormatter formatter = new AAIErrorFormatter(errorObj);
- String result = formatter.fillInTemplate(error, list);
- assertEquals("equal", "Error PUT on hello PUT", result);
-
- }
-
- @Test
- public void testFillInTemplateWithoutReplace() {
- String error = "Error";
- List<String> list = new ArrayList<>();
- AAIErrorFormatter formatter = new AAIErrorFormatter(errorObj);
- String result = formatter.fillInTemplate(error, list);
- assertEquals("equal", "Error", result);
- }
-
- @Test
- public void testGetMessage() {
- ServiceException svcException = new ServiceException();
- svcException.setText("test %1 message - %2");
- svcException.setVariables(Arrays.asList("error", "service exception %1 test"));
-
- RequestError requestError = new RequestError();
- requestError.setServiceException(svcException);
-
- doReturn(requestError).when(errorObj).getRequestError();
-
- AAIErrorFormatter formatter = new AAIErrorFormatter(errorObj);
- String result = formatter.getMessage();
- assertEquals("equal", "test error message - service exception error test", result);
- }
-
- @Test
- public void testGetMessageNoParsable() {
- errorObj.setRequestError(null);
- AAIErrorFormatter formatter = new AAIErrorFormatter(errorObj);
- String result = formatter.getMessage();
- assertEquals("equal", "no parsable error message found", result);
- }
+ @Mock
+ private AAIError errorObj;
+
+ @Before
+ public void init() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void testFillInTemplateWithReplace() {
+ String error = "Error %1 on %2";
+ List<String> list = Arrays.asList("PUT", "hello %1");
+ AAIErrorFormatter formatter = new AAIErrorFormatter(errorObj);
+ String result = formatter.fillInTemplate(error, list);
+ assertEquals("equal", "Error PUT on hello PUT", result);
+
+ }
+
+ @Test
+ public void testFillInTemplateWithoutReplace() {
+ String error = "Error";
+ List<String> list = new ArrayList<>();
+ AAIErrorFormatter formatter = new AAIErrorFormatter(errorObj);
+ String result = formatter.fillInTemplate(error, list);
+ assertEquals("equal", "Error", result);
+ }
+
+ @Test
+ public void testGetMessage() {
+ ServiceException svcException = new ServiceException();
+ svcException.setText("test %1 message - %2");
+ svcException.setVariables(Arrays.asList("error", "service exception %1 test"));
+
+ RequestError requestError = new RequestError();
+ requestError.setServiceException(svcException);
+
+ doReturn(requestError).when(errorObj).getRequestError();
+
+ AAIErrorFormatter formatter = new AAIErrorFormatter(errorObj);
+ String result = formatter.getMessage();
+ assertEquals("equal", "test error message - service exception error test", result);
+ }
+
+ @Test
+ public void testGetMessageNoParsable() {
+ errorObj.setRequestError(null);
+ AAIErrorFormatter formatter = new AAIErrorFormatter(errorObj);
+ String result = formatter.getMessage();
+ assertEquals("equal", "no parsable error message found", result);
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java b/common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java
index 64a83f92ab..8f449c21f3 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java
@@ -21,70 +21,71 @@
package org.onap.so.client.aai;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.client.aai.entities.uri.AAIUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
public class AAIObjectTypeTest {
-
- @Test
- public void fromTypeNameTest() throws IllegalArgumentException, IllegalAccessException, InstantiationException {
- AAIObjectType type = AAIObjectType.fromTypeName("allotted-resource");
- assertEquals("allotted-resource", type.typeName());
-
- }
-
- @Test
- public void customTypeTest() throws IllegalArgumentException, IllegalAccessException, InstantiationException {
- AAIObjectType type = AAIObjectType.fromTypeName("my-custom-name");
- assertEquals("my-custom-name", type.typeName());
- }
- @Test
- public void verifyDefaultCase() {
- assertEquals("default removed for tenant", "tenant", AAIObjectType.DEFAULT_TENANT.typeName());
- assertEquals("default removed for cloud-region", "cloud-region", AAIObjectType.DEFAULT_CLOUD_REGION.typeName());
- }
-
- @Test
- public void verifyRegularCase() {
- assertEquals("default removed for tenant", "allotted-resource", AAIObjectType.ALLOTTED_RESOURCE.typeName());
- }
-
- @Test
- public void instanceGroupObjectTypeTest() {
- final String id = "test1";
- AAIUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, id);
- assertEquals("/network/instance-groups/instance-group/test1", aaiUri.build().toString());
- }
-
- @Test
- public void collectionObjectTypeTest() {
- final String id = "test1";
- AAIUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, id);
- assertEquals("/network/collections/collection/test1", aaiUri.build().toString());
- }
-
- @Test
- public void genericVnfTest() {
- AAIObjectType type = AAIObjectType.GENERIC_VNF;
- assertEquals("/network/generic-vnfs/generic-vnf/{vnf-id}", type.uriTemplate());
- assertEquals("/generic-vnfs/generic-vnf/{vnf-id}", type.partialUri());
- }
-
- @Test
- public void pInterfaceTest() {
- AAIObjectType type = AAIObjectType.P_INTERFACE;
- assertEquals("/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces/p-interface/{interface-name}", type.uriTemplate());
- assertEquals("/p-interfaces/p-interface/{interface-name}", type.partialUri());
- }
-
- @Test
- public void networkPolicyObjectTypeTest() {
- final String id = "test1";
- AAIUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, id);
- assertEquals("/network/network-policies/network-policy/test1", aaiUri.build().toString());
- }
+ @Test
+ public void fromTypeNameTest() throws IllegalArgumentException, IllegalAccessException, InstantiationException {
+ AAIObjectType type = AAIObjectType.fromTypeName("allotted-resource");
+ assertEquals("allotted-resource", type.typeName());
+
+ }
+
+ @Test
+ public void customTypeTest() throws IllegalArgumentException, IllegalAccessException, InstantiationException {
+ AAIObjectType type = AAIObjectType.fromTypeName("my-custom-name");
+ assertEquals("my-custom-name", type.typeName());
+
+ }
+
+ @Test
+ public void verifyDefaultCase() {
+ assertEquals("default removed for tenant", "tenant", AAIObjectType.DEFAULT_TENANT.typeName());
+ assertEquals("default removed for cloud-region", "cloud-region", AAIObjectType.DEFAULT_CLOUD_REGION.typeName());
+ }
+
+ @Test
+ public void verifyRegularCase() {
+ assertEquals("default removed for tenant", "allotted-resource", AAIObjectType.ALLOTTED_RESOURCE.typeName());
+ }
+
+ @Test
+ public void instanceGroupObjectTypeTest() {
+ final String id = "test1";
+ AAIUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, id);
+ assertEquals("/network/instance-groups/instance-group/test1", aaiUri.build().toString());
+ }
+
+ @Test
+ public void collectionObjectTypeTest() {
+ final String id = "test1";
+ AAIUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, id);
+ assertEquals("/network/collections/collection/test1", aaiUri.build().toString());
+ }
+
+ @Test
+ public void genericVnfTest() {
+ AAIObjectType type = AAIObjectType.GENERIC_VNF;
+ assertEquals("/network/generic-vnfs/generic-vnf/{vnf-id}", type.uriTemplate());
+ assertEquals("/generic-vnfs/generic-vnf/{vnf-id}", type.partialUri());
+ }
+
+ @Test
+ public void pInterfaceTest() {
+ AAIObjectType type = AAIObjectType.P_INTERFACE;
+ assertEquals("/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces/p-interface/{interface-name}",
+ type.uriTemplate());
+ assertEquals("/p-interfaces/p-interface/{interface-name}", type.partialUri());
+ }
+
+ @Test
+ public void networkPolicyObjectTypeTest() {
+ final String id = "test1";
+ AAIUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, id);
+ assertEquals("/network/network-policies/network-policy/test1", aaiUri.build().toString());
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIPServerTest.java b/common/src/test/java/org/onap/so/client/aai/AAIPServerTest.java
index ba48e4368d..4b3b7e9881 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIPServerTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIPServerTest.java
@@ -21,7 +21,6 @@
package org.onap.so.client.aai;
import static org.junit.Assert.assertEquals;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
@@ -29,24 +28,25 @@ import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import org.onap.aai.domain.yang.Pserver;
+
public class AAIPServerTest {
- @Test
- public void pserverTest() throws IOException {
- AAIRestClientImpl client = new AAIRestClientImpl();
- String json = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/aai/pserver.json")));
- List<Pserver> list = client.getListOfPservers(json);
-
- assertEquals("", list.get(0).getHostname(), "test");
- assertEquals("", list.size(), 2);
- }
-
- @Test
- @Ignore // IGNORED FOR 1710 MERGE TO ONAP
- public void pserverActualTest() throws IOException {
- AAIRestClientImpl client = new AAIRestClientImpl();
- List<Pserver> list = client.getPhysicalServerByVnfId("d946afed-8ebe-4c5d-9665-54fcc043b8e7");
- assertEquals("", list.size(), 0);
- }
+ @Test
+ public void pserverTest() throws IOException {
+ AAIRestClientImpl client = new AAIRestClientImpl();
+ String json = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/aai/pserver.json")));
+ List<Pserver> list = client.getListOfPservers(json);
+
+ assertEquals("", list.get(0).getHostname(), "test");
+ assertEquals("", list.size(), 2);
+ }
+
+ @Test
+ @Ignore // IGNORED FOR 1710 MERGE TO ONAP
+ public void pserverActualTest() throws IOException {
+ AAIRestClientImpl client = new AAIRestClientImpl();
+ List<Pserver> list = client.getPhysicalServerByVnfId("d946afed-8ebe-4c5d-9665-54fcc043b8e7");
+ assertEquals("", list.size(), 0);
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java
index e648ea38da..5b2bff277d 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java
@@ -29,16 +29,13 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
-
import javax.ws.rs.core.GenericType;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
@@ -58,88 +55,97 @@ import org.onap.so.client.graphinventory.GraphInventoryClient;
import org.onap.so.client.graphinventory.GraphInventorySubgraphType;
import org.onap.so.client.graphinventory.entities.Pathed;
import org.onap.so.client.graphinventory.entities.ResourceAndUrl;
-
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
-@RunWith(MockitoJUnitRunner.class)
+@RunWith(MockitoJUnitRunner.class)
public class AAIQueryClientTest {
-
- @Mock
- private RestClient restClient;
-
- @Mock
- private GraphInventoryClient client;
-
- @InjectMocks
- @Spy
- private AAIQueryClient aaiQueryClient = new AAIQueryClient();
-
- private String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/query/";
-
- private ObjectMapper mapper = new ObjectMapper();
- @Test
- public void testQuery() {
- List<AAIResourceUri> uris = Arrays.asList(AAIUriFactory.createResourceUri(AAIObjectType.CUSTOM_QUERY));
-
- Format format = Format.SIMPLE;
- CustomQuery query = new CustomQuery(uris);
-
- doReturn(restClient).when(client).createClient(isA(AAIUri.class));
- aaiQueryClient.query(format, query);
- verify(client, times(1)).createClient(AAIUriFactory.createResourceUri(AAIObjectType.CUSTOM_QUERY).queryParam("format", format.toString()));
- verify(restClient, times(1)).put(query, String.class);
- }
-
- @Test
- public void testCreateClient() {
- String depth = "testDepth";
- GraphInventorySubgraphType subgraph = GraphInventorySubgraphType.STAR;
-
- aaiQueryClient.depth(depth);
- aaiQueryClient.nodesOnly();
- aaiQueryClient.subgraph(subgraph);
-
- AAIUri aaiUri = spy(AAIUriFactory.createResourceUri(AAIObjectType.CUSTOM_QUERY));
- doReturn(aaiUri).when(aaiUri).clone();
- aaiQueryClient.setupQueryParams(aaiUri);
-
- verify(aaiUri, times(1)).queryParam("depth", depth);
- verify(aaiUri, times(1)).queryParam("nodesOnly", "");
- verify(aaiUri, times(1)).queryParam("subgraph", subgraph.toString());
- }
-
- @Test
- public void querySingleResourceTest() throws IOException {
- doReturn(getJson("single-query-result.json")).when(aaiQueryClient).query(eq(Format.RESOURCE_AND_URL), any(CustomQuery.class));
- List<Complex> result = aaiQueryClient.querySingleResource(new CustomQuery(Arrays.asList(AAIUriFactory.createNodesUri(AAIObjectType.COMPLEX, "test"))), Complex.class);
- assertEquals(2, result.size());
- assertEquals("complex-id-15100-jc689q2", result.get(1).getPhysicalLocationId());
- }
-
- @Test
- public void getResourceAndUrlTest() throws IOException {
- doReturn(getJson("single-query-result.json")).when(aaiQueryClient).query(eq(Format.RESOURCE_AND_URL), any(CustomQuery.class));
- List<ResourceAndUrl<AAIResultWrapper>> result = aaiQueryClient.getResourceAndUrl(new CustomQuery(Arrays.asList(AAIUriFactory.createNodesUri(AAIObjectType.COMPLEX, "test"))));
- assertEquals(2, result.size());
-
- assertEquals(1, result.get(1).getWrapper().getRelationships().get().getRelatedUris(AAIObjectType.PSERVER).size());
- }
-
- @Test
- public void querySingleTypeTest() throws IOException {
- when(client.createClient(isA(AAIUri.class))).thenReturn(restClient);
- when(restClient.put(any(Object.class), any(GenericType.class))).thenReturn(mapper.readValue(getJson("pathed-result.json"), new TypeReference<Results<Map<String, Object>>>(){}));
-
-
- List<Pathed> results = aaiQueryClient.queryPathed(new CustomQuery(Arrays.asList(AAIUriFactory.createNodesUri(AAIObjectType.COMPLEX, "test"))));
-
- assertEquals(2, results.size());
- assertEquals("service-instance", results.get(1).getResourceType());
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + filename)));
- }
+
+ @Mock
+ private RestClient restClient;
+
+ @Mock
+ private GraphInventoryClient client;
+
+ @InjectMocks
+ @Spy
+ private AAIQueryClient aaiQueryClient = new AAIQueryClient();
+
+ private String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/query/";
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ public void testQuery() {
+ List<AAIResourceUri> uris = Arrays.asList(AAIUriFactory.createResourceUri(AAIObjectType.CUSTOM_QUERY));
+
+ Format format = Format.SIMPLE;
+ CustomQuery query = new CustomQuery(uris);
+
+ doReturn(restClient).when(client).createClient(isA(AAIUri.class));
+ aaiQueryClient.query(format, query);
+ verify(client, times(1)).createClient(
+ AAIUriFactory.createResourceUri(AAIObjectType.CUSTOM_QUERY).queryParam("format", format.toString()));
+ verify(restClient, times(1)).put(query, String.class);
+ }
+
+ @Test
+ public void testCreateClient() {
+ String depth = "testDepth";
+ GraphInventorySubgraphType subgraph = GraphInventorySubgraphType.STAR;
+
+ aaiQueryClient.depth(depth);
+ aaiQueryClient.nodesOnly();
+ aaiQueryClient.subgraph(subgraph);
+
+ AAIUri aaiUri = spy(AAIUriFactory.createResourceUri(AAIObjectType.CUSTOM_QUERY));
+ doReturn(aaiUri).when(aaiUri).clone();
+ aaiQueryClient.setupQueryParams(aaiUri);
+
+ verify(aaiUri, times(1)).queryParam("depth", depth);
+ verify(aaiUri, times(1)).queryParam("nodesOnly", "");
+ verify(aaiUri, times(1)).queryParam("subgraph", subgraph.toString());
+ }
+
+ @Test
+ public void querySingleResourceTest() throws IOException {
+ doReturn(getJson("single-query-result.json")).when(aaiQueryClient).query(eq(Format.RESOURCE_AND_URL),
+ any(CustomQuery.class));
+ List<Complex> result = aaiQueryClient.querySingleResource(
+ new CustomQuery(Arrays.asList(AAIUriFactory.createNodesUri(AAIObjectType.COMPLEX, "test"))),
+ Complex.class);
+ assertEquals(2, result.size());
+ assertEquals("complex-id-15100-jc689q2", result.get(1).getPhysicalLocationId());
+ }
+
+ @Test
+ public void getResourceAndUrlTest() throws IOException {
+ doReturn(getJson("single-query-result.json")).when(aaiQueryClient).query(eq(Format.RESOURCE_AND_URL),
+ any(CustomQuery.class));
+ List<ResourceAndUrl<AAIResultWrapper>> result = aaiQueryClient.getResourceAndUrl(
+ new CustomQuery(Arrays.asList(AAIUriFactory.createNodesUri(AAIObjectType.COMPLEX, "test"))));
+ assertEquals(2, result.size());
+
+ assertEquals(1,
+ result.get(1).getWrapper().getRelationships().get().getRelatedUris(AAIObjectType.PSERVER).size());
+ }
+
+ @Test
+ public void querySingleTypeTest() throws IOException {
+ when(client.createClient(isA(AAIUri.class))).thenReturn(restClient);
+ when(restClient.put(any(Object.class), any(GenericType.class))).thenReturn(
+ mapper.readValue(getJson("pathed-result.json"), new TypeReference<Results<Map<String, Object>>>() {}));
+
+
+ List<Pathed> results = aaiQueryClient.queryPathed(
+ new CustomQuery(Arrays.asList(AAIUriFactory.createNodesUri(AAIObjectType.COMPLEX, "test"))));
+
+ assertEquals(2, results.size());
+ assertEquals("service-instance", results.get(1).getResourceType());
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + filename)));
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java
index c63d602bca..94d14684c7 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java
@@ -33,9 +33,7 @@ import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doReturn;
-
import javax.ws.rs.BadRequestException;
-
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -50,7 +48,6 @@ import org.onap.so.client.aai.entities.AAIResultWrapper;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl;
-
import com.github.tomakehurst.wiremock.admin.NotFoundException;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
@@ -58,186 +55,147 @@ import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class AAIResourcesClientTest {
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
-
- @Spy
- public AAIClient client;
-
- @InjectMocks
- public AAIResourcesClient aaiClient = new AAIResourcesClient();
-
- private String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/query/";
-
- @Before
- public void beforeTest() {
- doReturn(new DefaultAAIPropertiesImpl(wireMockRule.port())).when(client).getRestProperties();
- }
-
- @Test
- public void verifyNotExists() {
- AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test");
- wireMockRule.stubFor(get(
- urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
- .willReturn(
- aResponse()
- .withHeader("Content-Type", "text/plain")
- .withBody("hello")
- .withStatus(404)));
- AAIResourcesClient client= aaiClient;
- boolean result = client.exists(path);
- assertEquals("path not found", false, result);
- }
-
- @Test
- public void verifyDelete() {
- AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test2");
- wireMockRule.stubFor(get(
- urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
- .willReturn(
- aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("aai/resources/mockObject.json")
- .withStatus(200)));
- wireMockRule.stubFor(delete(
- urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
- .withQueryParam("resource-version", equalTo("1234"))
- .willReturn(
- aResponse()
- .withStatus(204)));
- AAIResourcesClient client= aaiClient;
- client.delete(path);
- }
-
- @Test
- public void verifyBasicAuth() {
- AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test3");
- wireMockRule.stubFor(get(
- urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build().toString()))
- .withHeader("Authorization", equalTo("Basic dGVzdDp0ZXN0"))
- .willReturn(
- aResponse()
- .withHeader("Content-Type", "application/json")
- .withBodyFile("aai/resources/mockObject.json")
- .withStatus(200)));
- AAIResourcesClient client= aaiClient;
- client.get(path);
- }
-
- @Test
- public void verifyConnect() {
- AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test2");
- AAIResourceUri path2 = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test3");
- wireMockRule.stubFor(put(
- urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build() + "/relationship-list/relationship"))
- .willReturn(
- aResponse()
- .withHeader("Content-Type", "application/json")
- .withStatus(200)));
-
- AAIResourceUri pathClone = path.clone();
- AAIResourcesClient client= aaiClient;
- client.connect(path, path2);
- assertEquals("uri not modified", pathClone.build().toString(), path.build().toString());
- }
-
- @Test
- public void verifyDisconnect() {
- AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test2");
- AAIResourceUri path2 = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test3");
-
- wireMockRule.stubFor(delete(
- urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build() + "/relationship-list/relationship"))
- .willReturn(
- aResponse()
- .withStatus(204)));
-
- AAIResourceUri pathClone = path.clone();
- AAIResourcesClient client= aaiClient;
- client.disconnect(path, path2);
- assertEquals("uri not modified", pathClone.build().toString(), path.build().toString());
- }
-
- @Test
- public void verifyPatch() {
- AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test2");
-
- wireMockRule.stubFor(post(
- urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
- .willReturn(
- aResponse()
- .withStatus(200)));
-
- AAIResourcesClient client= aaiClient;
-
- client.update(path, "{}");
- }
-
- @Test
- public void verifyNotExistsGet() {
- AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test");
- wireMockRule.stubFor(get(
- urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
- .willReturn(
- aResponse()
- .withHeader("Content-Type", "text/plain")
- .withBody("hello")
- .withStatus(404)));
- AAIResourcesClient client= aaiClient;
- AAIResultWrapper result = client.get(path);
- assertEquals("is empty", true, result.isEmpty());
- }
-
- @Test
- public void verifyNotExistsGetException() {
- AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test");
- wireMockRule.stubFor(get(
- urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
- .willReturn(
- aResponse()
- .withHeader("Content-Type", "text/plain")
- .withBody("hello")
- .withStatus(404)));
- AAIResourcesClient client= aaiClient;
- thrown.expect(NotFoundException.class);
- thrown.expectMessage(containsString(path.build() + " not found in A&AI"));
- AAIResultWrapper result = client.get(path, NotFoundException.class);
- }
-
- @Test
- public void verifyFailedCallException() {
- AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test");
- wireMockRule.stubFor(get(
- urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
- .willReturn(
- aResponse()
- .withHeader("Content-Type", "text/plain")
- .withBodyFile("aai/error-message.json")
- .withStatus(400)));
- AAIResourcesClient client= aaiClient;
-
- thrown.expect(BadRequestException.class);
- thrown.expectMessage(containsString("Invalid input performing PUT on url (msg=Precondition Required:resource-version not passed for update of url"));
- AAIResultWrapper result = client.get(path);
- }
-
- @Test
- public void buildRelationshipTest() {
- AAIResourcesClient client = aaiClient;
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test");
- Relationship relationship = new Relationship();
- relationship.setRelatedLink(uri.build().toString());
- Relationship actual = client.buildRelationship(uri);
- assertThat("expect equal no label", actual, sameBeanAs(relationship));
-
- relationship.setRelationshipLabel(AAIEdgeLabel.USES.toString());
- actual = client.buildRelationship(uri, AAIEdgeLabel.USES);
- assertThat("expect equal has label", actual, sameBeanAs(relationship));
-
- }
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+
+ @Spy
+ public AAIClient client;
+
+ @InjectMocks
+ public AAIResourcesClient aaiClient = new AAIResourcesClient();
+
+ private String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/query/";
+
+ @Before
+ public void beforeTest() {
+ doReturn(new DefaultAAIPropertiesImpl(wireMockRule.port())).when(client).getRestProperties();
+ }
+
+ @Test
+ public void verifyNotExists() {
+ AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test");
+ wireMockRule.stubFor(get(urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
+ .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("hello").withStatus(404)));
+ AAIResourcesClient client = aaiClient;
+ boolean result = client.exists(path);
+ assertEquals("path not found", false, result);
+ }
+
+ @Test
+ public void verifyDelete() {
+ AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test2");
+ wireMockRule.stubFor(get(urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("aai/resources/mockObject.json").withStatus(200)));
+ wireMockRule.stubFor(delete(urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
+ .withQueryParam("resource-version", equalTo("1234")).willReturn(aResponse().withStatus(204)));
+ AAIResourcesClient client = aaiClient;
+ client.delete(path);
+ }
+
+ @Test
+ public void verifyBasicAuth() {
+ AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test3");
+ wireMockRule.stubFor(get(urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build().toString()))
+ .withHeader("Authorization", equalTo("Basic dGVzdDp0ZXN0"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("aai/resources/mockObject.json").withStatus(200)));
+ AAIResourcesClient client = aaiClient;
+ client.get(path);
+ }
+
+ @Test
+ public void verifyConnect() {
+ AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test2");
+ AAIResourceUri path2 = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test3");
+ wireMockRule.stubFor(
+ put(urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build() + "/relationship-list/relationship"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(200)));
+
+ AAIResourceUri pathClone = path.clone();
+ AAIResourcesClient client = aaiClient;
+ client.connect(path, path2);
+ assertEquals("uri not modified", pathClone.build().toString(), path.build().toString());
+ }
+
+ @Test
+ public void verifyDisconnect() {
+ AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test2");
+ AAIResourceUri path2 = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test3");
+
+ wireMockRule.stubFor(
+ delete(urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build() + "/relationship-list/relationship"))
+ .willReturn(aResponse().withStatus(204)));
+
+ AAIResourceUri pathClone = path.clone();
+ AAIResourcesClient client = aaiClient;
+ client.disconnect(path, path2);
+ assertEquals("uri not modified", pathClone.build().toString(), path.build().toString());
+ }
+
+ @Test
+ public void verifyPatch() {
+ AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test2");
+
+ wireMockRule.stubFor(post(urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
+ .willReturn(aResponse().withStatus(200)));
+
+ AAIResourcesClient client = aaiClient;
+
+ client.update(path, "{}");
+ }
+
+ @Test
+ public void verifyNotExistsGet() {
+ AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test");
+ wireMockRule.stubFor(get(urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
+ .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("hello").withStatus(404)));
+ AAIResourcesClient client = aaiClient;
+ AAIResultWrapper result = client.get(path);
+ assertEquals("is empty", true, result.isEmpty());
+ }
+
+ @Test
+ public void verifyNotExistsGetException() {
+ AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test");
+ wireMockRule.stubFor(get(urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build()))
+ .willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("hello").withStatus(404)));
+ AAIResourcesClient client = aaiClient;
+ thrown.expect(NotFoundException.class);
+ thrown.expectMessage(containsString(path.build() + " not found in A&AI"));
+ AAIResultWrapper result = client.get(path, NotFoundException.class);
+ }
+
+ @Test
+ public void verifyFailedCallException() {
+ AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test");
+ wireMockRule.stubFor(get(urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build())).willReturn(aResponse()
+ .withHeader("Content-Type", "text/plain").withBodyFile("aai/error-message.json").withStatus(400)));
+ AAIResourcesClient client = aaiClient;
+
+ thrown.expect(BadRequestException.class);
+ thrown.expectMessage(containsString(
+ "Invalid input performing PUT on url (msg=Precondition Required:resource-version not passed for update of url"));
+ AAIResultWrapper result = client.get(path);
+ }
+
+ @Test
+ public void buildRelationshipTest() {
+ AAIResourcesClient client = aaiClient;
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test");
+ Relationship relationship = new Relationship();
+ relationship.setRelatedLink(uri.build().toString());
+ Relationship actual = client.buildRelationship(uri);
+ assertThat("expect equal no label", actual, sameBeanAs(relationship));
+
+ relationship.setRelationshipLabel(AAIEdgeLabel.USES.toString());
+ actual = client.buildRelationship(uri, AAIEdgeLabel.USES);
+ assertThat("expect equal has label", actual, sameBeanAs(relationship));
+
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java
index 46e4c98b3e..55da6e7d52 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java
@@ -28,14 +28,11 @@ import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
-
import java.util.List;
import java.util.Optional;
-
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -48,80 +45,77 @@ import org.onap.so.client.aai.entities.AAIResultWrapper;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.onap.so.client.aai.entities.uri.ServiceInstanceUri;
import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl;
-
import com.github.tomakehurst.wiremock.junit.WireMockRule;
@RunWith(MockitoJUnitRunner.class)
public class AAIResourcesClientWithServiceInstanceUriTest {
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Spy
- public AAIClient client;
-
- @InjectMocks
- public AAIResourcesClient aaiClient = new AAIResourcesClient();
-
- private ServiceInstanceUri uri;
- @Before
- public void setUp() {
- doReturn(new DefaultAAIPropertiesImpl(wireMockRule.port())).when(client).getRestProperties();
- wireMockRule.stubFor(get(urlMatching("/aai/v[0-9]+/nodes.*"))
- .willReturn(aResponse()
- .withStatus(404)
- .withHeader("Content-Type", "application/json")
- .withHeader("Mock", "true")));
-
- uri = spy((ServiceInstanceUri)AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "id"));
- doReturn(aaiClient).when(uri).getResourcesClient();
- }
-
- @Test
- public void getWithClass() {
- AAIResourcesClient client = aaiClient;
- Optional<String> result = client.get(String.class, uri);
-
- assertThat(result.isPresent(), equalTo(false));
- }
-
- @Test
- public void getFullResponse() {
- AAIResourcesClient client = aaiClient;
- Response result = client.getFullResponse(uri);
- assertThat(result.getStatus(), equalTo(Status.NOT_FOUND.getStatusCode()));
- }
-
- @Test
- public void getWithGenericType() {
- AAIResourcesClient client = aaiClient;
- Optional<List<String>> result = client.get(new GenericType<List<String>>() {}, uri);
- assertThat(result.isPresent(), equalTo(false));
- }
-
- @Test
- public void getAAIWrapper() {
- AAIResourcesClient client = aaiClient;
- AAIResultWrapper result = client.get(uri);
- assertThat(result.isEmpty(), equalTo(true));
- }
-
- @Test
- public void getWithException() {
- AAIResourcesClient client = aaiClient;
- this.thrown.expect(IllegalArgumentException.class);
- AAIResultWrapper result = client.get(uri, IllegalArgumentException.class);
- }
-
- @Test
- public void existsTest() {
- AAIResourcesClient client = aaiClient;
- doReturn(uri).when(uri).clone();
- boolean result = client.exists(uri);
- assertThat(result, equalTo(false));
- }
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Spy
+ public AAIClient client;
+
+ @InjectMocks
+ public AAIResourcesClient aaiClient = new AAIResourcesClient();
+
+ private ServiceInstanceUri uri;
+
+ @Before
+ public void setUp() {
+ doReturn(new DefaultAAIPropertiesImpl(wireMockRule.port())).when(client).getRestProperties();
+ wireMockRule.stubFor(get(urlMatching("/aai/v[0-9]+/nodes.*")).willReturn(
+ aResponse().withStatus(404).withHeader("Content-Type", "application/json").withHeader("Mock", "true")));
+
+ uri = spy((ServiceInstanceUri) AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "id"));
+ doReturn(aaiClient).when(uri).getResourcesClient();
+ }
+
+ @Test
+ public void getWithClass() {
+ AAIResourcesClient client = aaiClient;
+ Optional<String> result = client.get(String.class, uri);
+
+ assertThat(result.isPresent(), equalTo(false));
+ }
+
+ @Test
+ public void getFullResponse() {
+ AAIResourcesClient client = aaiClient;
+ Response result = client.getFullResponse(uri);
+ assertThat(result.getStatus(), equalTo(Status.NOT_FOUND.getStatusCode()));
+ }
+
+ @Test
+ public void getWithGenericType() {
+ AAIResourcesClient client = aaiClient;
+ Optional<List<String>> result = client.get(new GenericType<List<String>>() {}, uri);
+ assertThat(result.isPresent(), equalTo(false));
+ }
+
+ @Test
+ public void getAAIWrapper() {
+ AAIResourcesClient client = aaiClient;
+ AAIResultWrapper result = client.get(uri);
+ assertThat(result.isEmpty(), equalTo(true));
+ }
+
+ @Test
+ public void getWithException() {
+ AAIResourcesClient client = aaiClient;
+ this.thrown.expect(IllegalArgumentException.class);
+ AAIResultWrapper result = client.get(uri, IllegalArgumentException.class);
+ }
+
+ @Test
+ public void existsTest() {
+ AAIResourcesClient client = aaiClient;
+ doReturn(uri).when(uri).clone();
+ boolean result = client.exists(uri);
+ assertThat(result, equalTo(false));
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java
index 95b30f934b..2f551fecc4 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java
@@ -28,12 +28,9 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.net.URI;
import java.net.URISyntaxException;
-
import javax.ws.rs.core.Response;
-
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -43,37 +40,37 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.onap.so.client.RestClientSSL;
import org.onap.so.client.graphinventory.GraphInventoryPatchConverter;
import org.onap.so.client.graphinventory.exceptions.GraphInventoryPatchDepthExceededException;
-
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(MockitoJUnitRunner.class)
public class AAIRestClientTest {
- @Mock
- private AAIProperties props;
-
- private ObjectMapper mapper = new AAICommonObjectMapperProvider().getMapper();
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Test
- public void failPatchOnComplexObject() throws URISyntaxException {
- AAIRestClient client = new AAIRestClient(props, new URI(""));
- this.thrown.expect(GraphInventoryPatchDepthExceededException.class);
- this.thrown.expectMessage(containsString("Object exceeds allowed depth for update action"));
- client.patch("{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"relationship-list\" : [{\"key\" : \"value\"}], \"nested\" : { \"key\" : \"value\" }}");
- }
-
- @Test
- public void verifyPatchValidation() throws URISyntaxException {
- AAIRestClient client = new AAIRestClient(props, new URI(""));
- AAIRestClient spy = spy(client);
- GraphInventoryPatchConverter patchValidatorMock = mock(GraphInventoryPatchConverter.class);
- doReturn(patchValidatorMock).when(spy).getPatchConverter();
- String payload = "{}";
- doReturn(Response.ok().build()).when(spy).method(eq("PATCH"), any());
- spy.patch(payload);
- verify(patchValidatorMock, times(1)).convertPatchFormat(eq((Object)payload));
- }
+ @Mock
+ private AAIProperties props;
+
+ private ObjectMapper mapper = new AAICommonObjectMapperProvider().getMapper();
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void failPatchOnComplexObject() throws URISyntaxException {
+ AAIRestClient client = new AAIRestClient(props, new URI(""));
+ this.thrown.expect(GraphInventoryPatchDepthExceededException.class);
+ this.thrown.expectMessage(containsString("Object exceeds allowed depth for update action"));
+ client.patch(
+ "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"relationship-list\" : [{\"key\" : \"value\"}], \"nested\" : { \"key\" : \"value\" }}");
+ }
+
+ @Test
+ public void verifyPatchValidation() throws URISyntaxException {
+ AAIRestClient client = new AAIRestClient(props, new URI(""));
+ AAIRestClient spy = spy(client);
+ GraphInventoryPatchConverter patchValidatorMock = mock(GraphInventoryPatchConverter.class);
+ doReturn(patchValidatorMock).when(spy).getPatchConverter();
+ String payload = "{}";
+ doReturn(Response.ok().build()).when(spy).method(eq("PATCH"), any());
+ spy.patch(payload);
+ verify(patchValidatorMock, times(1)).convertPatchFormat(eq((Object) payload));
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java
index d875f384b0..1c49c11382 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java
@@ -29,12 +29,10 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
-
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
@@ -51,7 +49,6 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl;
import org.onap.so.client.graphinventory.GraphInventoryPatchConverter;
import org.skyscreamer.jsonassert.JSONAssert;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -60,77 +57,78 @@ import com.fasterxml.jackson.databind.SerializationFeature;
@RunWith(MockitoJUnitRunner.class)
public class AAISingleTransactionClientTest {
- private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/singletransaction/";
- AAIResourceUri uriA = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "pserver-hostname");
- AAIResourceUri uriB = AAIUriFactory.createResourceUri(AAIObjectType.COMPLEX, "my-complex");
-
- ObjectMapper mapper;
-
- public AAIClient client = new AAIClient();
-
- public AAIResourcesClient aaiClient = new AAIResourcesClient();
-
- @Before
- public void before() throws JsonParseException, JsonMappingException, IOException {
- mapper = new AAICommonObjectMapperProvider().getMapper();
- mapper.enable(SerializationFeature.INDENT_OUTPUT);
- }
-
- @Test
- public void testRequest() throws JSONException,IOException {
- Pserver pserver = new Pserver();
- pserver.setHostname("pserver-hostname");
- pserver.setFqdn("pserver-bulk-process-single-transactions-multiple-actions-1-fqdn");
- Pserver pserver2 = new Pserver();
- pserver2.setFqdn("patched-fqdn");
- Complex complex = new Complex();
- complex.setCity("my-city");
- AAISingleTransactionClient singleTransaction =
- aaiClient.beginSingleTransaction()
- .create(uriA, pserver)
- .update(uriA, pserver2)
- .create(uriB, complex);
-
-
- SingleTransactionRequest actual = singleTransaction.getRequest();
-
- SingleTransactionRequest expected = mapper.readValue(this.getJson("sample-request.json"), SingleTransactionRequest.class);
-
- JSONAssert.assertEquals(mapper.writeValueAsString(expected),mapper.writeValueAsString(actual), false);
- }
-
- @Test
- public void testFailure() throws IOException {
- AAISingleTransactionClient singleTransaction = aaiClient.beginSingleTransaction();
- SingleTransactionResponse expected = mapper.readValue(this.getJson("sample-response-failure.json"), SingleTransactionResponse.class);
- Optional<String> errorMessage = singleTransaction.locateErrorMessages(expected);
-
- assertThat(expected.getOperationResponses().size(), greaterThan(0));
- assertThat(errorMessage.isPresent(), equalTo(true));
-
- }
-
- @Test
- public void testSuccessResponse() throws IOException {
- AAISingleTransactionClient singleTransaction = aaiClient.beginSingleTransaction();
- SingleTransactionResponse expected = mapper.readValue(this.getJson("sample-response.json"), SingleTransactionResponse.class);
- Optional<String> errorMessage = singleTransaction.locateErrorMessages(expected);
-
- assertThat(expected.getOperationResponses().size(), greaterThan(0));
- assertThat(errorMessage.isPresent(), equalTo(false));
-
- }
-
- @Test
- public void confirmPatchFormat() {
- AAISingleTransactionClient singleTransaction = spy(new AAISingleTransactionClient(aaiClient, client));
- GraphInventoryPatchConverter mock = mock(GraphInventoryPatchConverter.class);
- doReturn(mock).when(singleTransaction).getPatchConverter();
- singleTransaction.update(uriA, "{}");
- verify(mock, times(1)).convertPatchFormat(any());
- }
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + filename)));
- }
-
+ private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/singletransaction/";
+ AAIResourceUri uriA = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "pserver-hostname");
+ AAIResourceUri uriB = AAIUriFactory.createResourceUri(AAIObjectType.COMPLEX, "my-complex");
+
+ ObjectMapper mapper;
+
+ public AAIClient client = new AAIClient();
+
+ public AAIResourcesClient aaiClient = new AAIResourcesClient();
+
+ @Before
+ public void before() throws JsonParseException, JsonMappingException, IOException {
+ mapper = new AAICommonObjectMapperProvider().getMapper();
+ mapper.enable(SerializationFeature.INDENT_OUTPUT);
+ }
+
+ @Test
+ public void testRequest() throws JSONException, IOException {
+ Pserver pserver = new Pserver();
+ pserver.setHostname("pserver-hostname");
+ pserver.setFqdn("pserver-bulk-process-single-transactions-multiple-actions-1-fqdn");
+ Pserver pserver2 = new Pserver();
+ pserver2.setFqdn("patched-fqdn");
+ Complex complex = new Complex();
+ complex.setCity("my-city");
+ AAISingleTransactionClient singleTransaction =
+ aaiClient.beginSingleTransaction().create(uriA, pserver).update(uriA, pserver2).create(uriB, complex);
+
+
+ SingleTransactionRequest actual = singleTransaction.getRequest();
+
+ SingleTransactionRequest expected =
+ mapper.readValue(this.getJson("sample-request.json"), SingleTransactionRequest.class);
+
+ JSONAssert.assertEquals(mapper.writeValueAsString(expected), mapper.writeValueAsString(actual), false);
+ }
+
+ @Test
+ public void testFailure() throws IOException {
+ AAISingleTransactionClient singleTransaction = aaiClient.beginSingleTransaction();
+ SingleTransactionResponse expected =
+ mapper.readValue(this.getJson("sample-response-failure.json"), SingleTransactionResponse.class);
+ Optional<String> errorMessage = singleTransaction.locateErrorMessages(expected);
+
+ assertThat(expected.getOperationResponses().size(), greaterThan(0));
+ assertThat(errorMessage.isPresent(), equalTo(true));
+
+ }
+
+ @Test
+ public void testSuccessResponse() throws IOException {
+ AAISingleTransactionClient singleTransaction = aaiClient.beginSingleTransaction();
+ SingleTransactionResponse expected =
+ mapper.readValue(this.getJson("sample-response.json"), SingleTransactionResponse.class);
+ Optional<String> errorMessage = singleTransaction.locateErrorMessages(expected);
+
+ assertThat(expected.getOperationResponses().size(), greaterThan(0));
+ assertThat(errorMessage.isPresent(), equalTo(false));
+
+ }
+
+ @Test
+ public void confirmPatchFormat() {
+ AAISingleTransactionClient singleTransaction = spy(new AAISingleTransactionClient(aaiClient, client));
+ GraphInventoryPatchConverter mock = mock(GraphInventoryPatchConverter.class);
+ doReturn(mock).when(singleTransaction).getPatchConverter();
+ singleTransaction.update(uriA, "{}");
+ verify(mock, times(1)).convertPatchFormat(any());
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + filename)));
+ }
+
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java
index 3e2801c452..adbdbb419f 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java
@@ -27,7 +27,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
@@ -35,7 +34,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -47,7 +45,6 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl;
import org.onap.so.client.graphinventory.GraphInventoryPatchConverter;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -57,109 +54,115 @@ import com.fasterxml.jackson.databind.SerializationFeature;
@RunWith(MockitoJUnitRunner.class)
public class AAITransactionalClientTest {
- private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/bulkprocess/";
- AAIResourceUri uriA = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test1");
- AAIResourceUri uriB = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "test2");
- AAIResourceUri uriC = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test3");
- AAIResourceUri uriD = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "test4");
- AAIResourceUri uriE = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test5");
- AAIResourceUri uriF = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "test6");
-
- ObjectMapper mapper;
-
- public AAIClient client = new AAIClient();
-
- public AAIResourcesClient aaiClient = new AAIResourcesClient();
-
- @Before
- public void before() throws JsonParseException, JsonMappingException, IOException {
- mapper = new AAICommonObjectMapperProvider().getMapper();
- mapper.enable(SerializationFeature.INDENT_OUTPUT);
- }
-
- @Test
- public void testCreate() throws IOException {
- final Relationship body = new Relationship();
- body.setRelatedLink(uriB.build().toString());
-
- AAITransactionalClient transactions = aaiClient.beginTransaction()
- .create(uriA.clone().relationshipAPI(), body);
-
- String serializedTransactions = mapper.writeValueAsString(transactions.getTransactions());
- Map<String, Object> actual = mapper.readValue(serializedTransactions, new TypeReference<Map<String, Object>>(){});
- Map<String, Object> expected = mapper.readValue(getJson("test-request-small.json"), new TypeReference<Map<String, Object>>(){});
-
- assertEquals(actual, expected);
- }
-
- @Test
- public void testConnect() throws IOException {
- List<AAIResourceUri> uris = new ArrayList<AAIResourceUri>();
- uris.add(uriB);
-
- AAIResourceUri uriAClone = uriA.clone();
- AAITransactionalClient transactions = aaiClient
- .beginTransaction().connect(uriA, uris).connect(uriC, uriD)
- .beginNewTransaction().connect(uriE, uriF);
-
- String serializedTransactions = mapper.writeValueAsString(transactions.getTransactions());
- Map<String, Object> actual = mapper.readValue(serializedTransactions, new TypeReference<Map<String, Object>>(){});
- Map<String, Object> expected = mapper.readValue(getJson("test-request.json"), new TypeReference<Map<String, Object>>(){});
-
- assertEquals(actual, expected);
- assertEquals("uri not manipulated", uriAClone.build().toString(), uriA.build().toString());
- }
-
- @Test
- public void testDisconnect() throws IOException {
- List<AAIResourceUri> uris = new ArrayList<AAIResourceUri>();
- uris.add(uriB);
-
- AAITransactionalClient transactions = aaiClient.beginTransaction()
- .disconnect(uriA, uris);
-
- String serializedTransactions = mapper.writeValueAsString(transactions.getTransactions());
- Map<String, Object> actual = mapper.readValue(serializedTransactions, new TypeReference<Map<String, Object>>(){});
- Map<String, Object> expected = mapper.readValue(getJson("test-request-small.json").replace("put", "delete"), new TypeReference<Map<String, Object>>(){});
-
- assertEquals(actual, expected);
- }
-
- @Test
- public void testUpdate() throws IOException {
- final Relationship body = new Relationship();
- body.setRelatedLink(uriB.build().toString());
-
- AAIResourceUri uriAClone = uriA.clone().relationshipAPI();
- AAITransactionalClient transactions = aaiClient.beginTransaction().update(uriAClone, body);
-
- String serializedTransactions = mapper.writeValueAsString(transactions.getTransactions());
- Map<String, Object> actual = mapper.readValue(serializedTransactions, new TypeReference<Map<String, Object>>(){});
- Map<String, Object> expected = mapper.readValue(getJson("test-request-small.json").replace("put", "patch"), new TypeReference<Map<String, Object>>(){});
-
- assertEquals(actual, expected);
- }
-
- @Test
- public void verifyResponse() throws IOException {
- AAITransactionalClient transactions = aaiClient
- .beginTransaction();
-
- assertEquals("success status", Optional.empty(), transactions.locateErrorMessages(getJson("response-success.json")));
- assertEquals(transactions.locateErrorMessages(getJson("response-failure.json")).get(), "another error message\nmy great error");
- }
-
- @Test
- public void confirmPatchFormat() {
- AAITransactionalClient transactionClient = spy(new AAITransactionalClient(aaiClient, client));
- GraphInventoryPatchConverter mock = mock(GraphInventoryPatchConverter.class);
- doReturn(mock).when(transactionClient).getPatchConverter();
- transactionClient.update(uriA, "{}");
- verify(mock, times(1)).convertPatchFormat(any());
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + filename)));
- }
-
+ private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/bulkprocess/";
+ AAIResourceUri uriA = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test1");
+ AAIResourceUri uriB = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "test2");
+ AAIResourceUri uriC = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test3");
+ AAIResourceUri uriD = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "test4");
+ AAIResourceUri uriE = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test5");
+ AAIResourceUri uriF = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "test6");
+
+ ObjectMapper mapper;
+
+ public AAIClient client = new AAIClient();
+
+ public AAIResourcesClient aaiClient = new AAIResourcesClient();
+
+ @Before
+ public void before() throws JsonParseException, JsonMappingException, IOException {
+ mapper = new AAICommonObjectMapperProvider().getMapper();
+ mapper.enable(SerializationFeature.INDENT_OUTPUT);
+ }
+
+ @Test
+ public void testCreate() throws IOException {
+ final Relationship body = new Relationship();
+ body.setRelatedLink(uriB.build().toString());
+
+ AAITransactionalClient transactions = aaiClient.beginTransaction().create(uriA.clone().relationshipAPI(), body);
+
+ String serializedTransactions = mapper.writeValueAsString(transactions.getTransactions());
+ Map<String, Object> actual =
+ mapper.readValue(serializedTransactions, new TypeReference<Map<String, Object>>() {});
+ Map<String, Object> expected =
+ mapper.readValue(getJson("test-request-small.json"), new TypeReference<Map<String, Object>>() {});
+
+ assertEquals(actual, expected);
+ }
+
+ @Test
+ public void testConnect() throws IOException {
+ List<AAIResourceUri> uris = new ArrayList<AAIResourceUri>();
+ uris.add(uriB);
+
+ AAIResourceUri uriAClone = uriA.clone();
+ AAITransactionalClient transactions = aaiClient.beginTransaction().connect(uriA, uris).connect(uriC, uriD)
+ .beginNewTransaction().connect(uriE, uriF);
+
+ String serializedTransactions = mapper.writeValueAsString(transactions.getTransactions());
+ Map<String, Object> actual =
+ mapper.readValue(serializedTransactions, new TypeReference<Map<String, Object>>() {});
+ Map<String, Object> expected =
+ mapper.readValue(getJson("test-request.json"), new TypeReference<Map<String, Object>>() {});
+
+ assertEquals(actual, expected);
+ assertEquals("uri not manipulated", uriAClone.build().toString(), uriA.build().toString());
+ }
+
+ @Test
+ public void testDisconnect() throws IOException {
+ List<AAIResourceUri> uris = new ArrayList<AAIResourceUri>();
+ uris.add(uriB);
+
+ AAITransactionalClient transactions = aaiClient.beginTransaction().disconnect(uriA, uris);
+
+ String serializedTransactions = mapper.writeValueAsString(transactions.getTransactions());
+ Map<String, Object> actual =
+ mapper.readValue(serializedTransactions, new TypeReference<Map<String, Object>>() {});
+ Map<String, Object> expected = mapper.readValue(getJson("test-request-small.json").replace("put", "delete"),
+ new TypeReference<Map<String, Object>>() {});
+
+ assertEquals(actual, expected);
+ }
+
+ @Test
+ public void testUpdate() throws IOException {
+ final Relationship body = new Relationship();
+ body.setRelatedLink(uriB.build().toString());
+
+ AAIResourceUri uriAClone = uriA.clone().relationshipAPI();
+ AAITransactionalClient transactions = aaiClient.beginTransaction().update(uriAClone, body);
+
+ String serializedTransactions = mapper.writeValueAsString(transactions.getTransactions());
+ Map<String, Object> actual =
+ mapper.readValue(serializedTransactions, new TypeReference<Map<String, Object>>() {});
+ Map<String, Object> expected = mapper.readValue(getJson("test-request-small.json").replace("put", "patch"),
+ new TypeReference<Map<String, Object>>() {});
+
+ assertEquals(actual, expected);
+ }
+
+ @Test
+ public void verifyResponse() throws IOException {
+ AAITransactionalClient transactions = aaiClient.beginTransaction();
+
+ assertEquals("success status", Optional.empty(),
+ transactions.locateErrorMessages(getJson("response-success.json")));
+ assertEquals(transactions.locateErrorMessages(getJson("response-failure.json")).get(),
+ "another error message\nmy great error");
+ }
+
+ @Test
+ public void confirmPatchFormat() {
+ AAITransactionalClient transactionClient = spy(new AAITransactionalClient(aaiClient, client));
+ GraphInventoryPatchConverter mock = mock(GraphInventoryPatchConverter.class);
+ doReturn(mock).when(transactionClient).getPatchConverter();
+ transactionClient.update(uriA, "{}");
+ verify(mock, times(1)).convertPatchFormat(any());
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + filename)));
+ }
+
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIURITest.java b/common/src/test/java/org/onap/so/client/aai/AAIURITest.java
index cb426c5392..556b4429d4 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIURITest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIURITest.java
@@ -21,24 +21,21 @@
package org.onap.so.client.aai;
import static org.junit.Assert.assertEquals;
-
import javax.ws.rs.core.UriBuilder;
-
import org.junit.Test;
import org.onap.so.client.aai.entities.uri.AAIUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
public class AAIURITest {
-
-
-
- @Test
- public void verifyTemplateReplacement() {
- final String id = "test1";
- AAIUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, id);
- String manualReplace = AAIObjectType.CONFIGURATION.toString().replaceAll("\\{configuration-id\\}", id);
- assertEquals("uri template replaced", aaiUri.build(), UriBuilder.fromPath(manualReplace).build());
- }
+
+ @Test
+ public void verifyTemplateReplacement() {
+ final String id = "test1";
+ AAIUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, id);
+ String manualReplace = AAIObjectType.CONFIGURATION.toString().replaceAll("\\{configuration-id\\}", id);
+ assertEquals("uri template replaced", aaiUri.build(), UriBuilder.fromPath(manualReplace).build());
+
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIUpdatorTest.java b/common/src/test/java/org/onap/so/client/aai/AAIUpdatorTest.java
index 3fc97761a4..d18dbec944 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIUpdatorTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIUpdatorTest.java
@@ -30,31 +30,31 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
-@RunWith(MockitoJUnitRunner.class)
+@RunWith(MockitoJUnitRunner.class)
public class AAIUpdatorTest {
-
- @Mock
- protected AAIRestClientI client;
- String vnfName = "testVnf";
- AAIUpdatorImpl updator;
-
- @Before
- public void init(){
- updator = new AAIUpdatorImpl();
- updator.setClient(client);
- }
- @Test
- public void testUpdateVnfToLocked() throws Exception{
- doNothing().when(client).updateMaintenceFlagVnfId(isA(String.class), isA(Boolean.class));
- updator.updateVnfToLocked(vnfName);
- verify(client, times(1)).updateMaintenceFlagVnfId(vnfName, true);
- }
-
- @Test
- public void testUpdateVnfToUnLocked() throws Exception {
- doNothing().when(client).updateMaintenceFlagVnfId(isA(String.class), isA(Boolean.class));
- updator.updateVnfToUnLocked(vnfName);
- verify(client, times(1)).updateMaintenceFlagVnfId(vnfName, false);
- }
-} \ No newline at end of file
+ @Mock
+ protected AAIRestClientI client;
+ String vnfName = "testVnf";
+ AAIUpdatorImpl updator;
+
+ @Before
+ public void init() {
+ updator = new AAIUpdatorImpl();
+ updator.setClient(client);
+ }
+
+ @Test
+ public void testUpdateVnfToLocked() throws Exception {
+ doNothing().when(client).updateMaintenceFlagVnfId(isA(String.class), isA(Boolean.class));
+ updator.updateVnfToLocked(vnfName);
+ verify(client, times(1)).updateMaintenceFlagVnfId(vnfName, true);
+ }
+
+ @Test
+ public void testUpdateVnfToUnLocked() throws Exception {
+ doNothing().when(client).updateMaintenceFlagVnfId(isA(String.class), isA(Boolean.class));
+ updator.updateVnfToUnLocked(vnfName);
+ verify(client, times(1)).updateMaintenceFlagVnfId(vnfName, false);
+ }
+}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java b/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java
index 85d690feaf..5fa2ff0295 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java
@@ -22,7 +22,6 @@ package org.onap.so.client.aai;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@@ -34,74 +33,74 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.onap.aai.domain.yang.GenericVnf;
import org.onap.aai.domain.yang.Pserver;
-@RunWith(MockitoJUnitRunner.class)
+@RunWith(MockitoJUnitRunner.class)
public class AAIValidatorTest {
-
- @Mock
- protected AAIRestClientI client;
- String vnfName = "testVnf";
- String uuid = "UUID";
- AAIValidatorImpl validator;
-
- @Before
- public void init(){
- validator = new AAIValidatorImpl();
- validator.setClient(client);
- }
-
- public List<Pserver> getPserversLocked(){
- Pserver pserver1 = new Pserver();
- pserver1.setInMaint(true);
- Pserver pserver2 = new Pserver();
- pserver2.setInMaint(false);
- List<Pserver> pservers = new ArrayList<Pserver>();
- pservers.add(pserver1);
- pservers.add(pserver2);
- return pservers;
- }
-
- public List<Pserver> getPserversNotLocked(){
- Pserver pserver1 = new Pserver();
- pserver1.setInMaint(false);
- Pserver pserver2 = new Pserver();
- pserver2.setInMaint(false);
- List<Pserver> pservers = new ArrayList<Pserver>();
- pservers.add(pserver1);
- pservers.add(pserver2);
- return pservers;
- }
-
- public GenericVnf createGenericVnfs(boolean locked){
- GenericVnf genericVnf = new GenericVnf();
- genericVnf.setInMaint(locked);
- return genericVnf;
- }
- @Test
- public void test_IsPhysicalServerLocked_True() throws IOException{
- when(client.getPhysicalServerByVnfId(vnfName)).thenReturn(getPserversLocked());
- boolean locked = validator.isPhysicalServerLocked(vnfName);
- assertEquals(true, locked);
- }
-
- @Test
- public void test_IsPhysicalServerLocked_False() throws IOException {
- when(client.getPhysicalServerByVnfId(vnfName)).thenReturn(getPserversNotLocked());
- boolean locked = validator.isPhysicalServerLocked(vnfName);
- assertEquals(false, locked);
- }
-
- @Test
- public void test_IsVNFLocked_False() {
- when(client.getVnfByName(vnfName)).thenReturn(createGenericVnfs(false));
- boolean locked = validator.isVNFLocked(vnfName);
- assertEquals(false, locked);
- }
+ @Mock
+ protected AAIRestClientI client;
+ String vnfName = "testVnf";
+ String uuid = "UUID";
+ AAIValidatorImpl validator;
+
+ @Before
+ public void init() {
+ validator = new AAIValidatorImpl();
+ validator.setClient(client);
+ }
+
+ public List<Pserver> getPserversLocked() {
+ Pserver pserver1 = new Pserver();
+ pserver1.setInMaint(true);
+ Pserver pserver2 = new Pserver();
+ pserver2.setInMaint(false);
+ List<Pserver> pservers = new ArrayList<Pserver>();
+ pservers.add(pserver1);
+ pservers.add(pserver2);
+ return pservers;
+ }
+
+ public List<Pserver> getPserversNotLocked() {
+ Pserver pserver1 = new Pserver();
+ pserver1.setInMaint(false);
+ Pserver pserver2 = new Pserver();
+ pserver2.setInMaint(false);
+ List<Pserver> pservers = new ArrayList<Pserver>();
+ pservers.add(pserver1);
+ pservers.add(pserver2);
+ return pservers;
+ }
+
+ public GenericVnf createGenericVnfs(boolean locked) {
+ GenericVnf genericVnf = new GenericVnf();
+ genericVnf.setInMaint(locked);
+ return genericVnf;
+ }
+
+ @Test
+ public void test_IsPhysicalServerLocked_True() throws IOException {
+ when(client.getPhysicalServerByVnfId(vnfName)).thenReturn(getPserversLocked());
+ boolean locked = validator.isPhysicalServerLocked(vnfName);
+ assertEquals(true, locked);
+ }
+
+ @Test
+ public void test_IsPhysicalServerLocked_False() throws IOException {
+ when(client.getPhysicalServerByVnfId(vnfName)).thenReturn(getPserversNotLocked());
+ boolean locked = validator.isPhysicalServerLocked(vnfName);
+ assertEquals(false, locked);
+ }
+
+ @Test
+ public void test_IsVNFLocked_False() {
+ when(client.getVnfByName(vnfName)).thenReturn(createGenericVnfs(false));
+ boolean locked = validator.isVNFLocked(vnfName);
+ assertEquals(false, locked);
+ }
- @Test
- public void test_IsVNFLocked_True() {
- when(client.getVnfByName(vnfName)).thenReturn(createGenericVnfs(true));
- boolean locked = validator.isVNFLocked(vnfName);
- assertEquals(true,locked );
- }
+ @Test
+ public void test_IsVNFLocked_True() {
+ when(client.getVnfByName(vnfName)).thenReturn(createGenericVnfs(true));
+ boolean locked = validator.isVNFLocked(vnfName);
+ assertEquals(true, locked);
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java b/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java
index a5bbc64eb9..6e55fe17fa 100644
--- a/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java
@@ -22,7 +22,6 @@ package org.onap.so.client.aai;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-
import org.junit.Test;
import org.onap.so.client.graphinventory.entities.DSLNode;
import org.onap.so.client.graphinventory.entities.DSLQueryBuilder;
@@ -30,83 +29,83 @@ import org.onap.so.client.graphinventory.entities.__;
public class DSLQueryBuilderTest {
-
- @Test
- public void whereTest() {
- DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.CLOUD_REGION,
- __.key("cloud-owner", "att-nc"),
- __.key("cloud-region-id", "test")));
-
- builder.to(__.node(AAIObjectType.VLAN_TAG)).where(
- __.node(AAIObjectType.OWNING_ENTITY,
- __.key("owning-entity-name", "name")
- )
- ).to(__.node(AAIObjectType.VLAN_TAG, __.key("vlan-id-outer", "108")).output());
-
- assertEquals("cloud-region('cloud-owner', 'att-nc')('cloud-region-id', 'test') > "
- + "vlan-tag (> owning-entity('owning-entity-name', 'name')) > "
- + "vlan-tag*('vlan-id-outer', '108')", builder.build());
- }
-
- @Test
- public void unionTest() {
- DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.GENERIC_VNF,
- __.key("vnf-id", "vnfId")).output());
-
- builder.union(__.node(AAIObjectType.PSERVER).output().to(__.node(AAIObjectType.COMPLEX).output()),
- __.node(AAIObjectType.VSERVER).to(__.node(AAIObjectType.PSERVER).output().to(__.node(AAIObjectType.COMPLEX).output())));
-
- assertEquals("generic-vnf*('vnf-id', 'vnfId') > " + "[ pserver* > complex*, "
- + "vserver > pserver* > complex* ]", builder.build());
- }
-
- @Test
- public void whereUnionTest() {
- DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.GENERIC_VNF,
- __.key("vnf-id", "vnfId")).output());
-
- builder.where(
- __.union(
- __.node(AAIObjectType.PSERVER, __.key("hostname", "hostname1")),
- __.node(AAIObjectType.VSERVER).to(__.node(AAIObjectType.PSERVER, __.key("hostname", "hostname1")))));
-
- assertEquals("generic-vnf*('vnf-id', 'vnfId') (> [ pserver('hostname', 'hostname1'), "
- + "vserver > pserver('hostname', 'hostname1') ])", builder.build());
- }
-
- @Test
- public void notNullTest() {
- DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.CLOUD_REGION,
- __.key("cloud-owner", "", "null").not()).output());
-
- assertEquals("cloud-region* !('cloud-owner', ' ', ' null ')", builder.build());
- }
-
- @Test
- public void shortCutToTest() {
- DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.PSERVER,
- __.key("hostname", "my-hostname")).output());
-
- builder.to(AAIObjectType.P_INTERFACE).to(AAIObjectType.SRIOV_PF, __.key("pf-pci-id", "my-id"));
- assertEquals("pserver*('hostname', 'my-hostname') > p-interface > sriov-pf('pf-pci-id', 'my-id')", builder.build());
- }
-
- @Test
- public void limitTest() {
- DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.PSERVER,
- __.key("hostname", "my-hostname")).output());
-
- builder.to(AAIObjectType.P_INTERFACE).limit(2).to(AAIObjectType.SRIOV_PF, __.key("pf-pci-id", "my-id"));
- assertEquals("pserver*('hostname', 'my-hostname') > p-interface > sriov-pf('pf-pci-id', 'my-id') LIMIT 2", builder.build());
- }
-
- @Test
- public void equalsTest() {
- DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.PSERVER,
- __.key("hostname", "my-hostname")).output());
-
- builder.to(AAIObjectType.P_INTERFACE).to(AAIObjectType.SRIOV_PF, __.key("pf-pci-id", "my-id"));
- assertTrue(builder.equals("pserver*('hostname', 'my-hostname') > p-interface > sriov-pf('pf-pci-id', 'my-id')"));
- assertTrue(builder.equals(builder));
- }
+
+ @Test
+ public void whereTest() {
+ DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.CLOUD_REGION,
+ __.key("cloud-owner", "att-nc"), __.key("cloud-region-id", "test")));
+
+ builder.to(__.node(AAIObjectType.VLAN_TAG))
+ .where(__.node(AAIObjectType.OWNING_ENTITY, __.key("owning-entity-name", "name")))
+ .to(__.node(AAIObjectType.VLAN_TAG, __.key("vlan-id-outer", "108")).output());
+
+ assertEquals("cloud-region('cloud-owner', 'att-nc')('cloud-region-id', 'test') > "
+ + "vlan-tag (> owning-entity('owning-entity-name', 'name')) > " + "vlan-tag*('vlan-id-outer', '108')",
+ builder.build());
+ }
+
+ @Test
+ public void unionTest() {
+ DSLQueryBuilder<DSLNode, DSLNode> builder =
+ new DSLQueryBuilder<>(new DSLNode(AAIObjectType.GENERIC_VNF, __.key("vnf-id", "vnfId")).output());
+
+ builder.union(__.node(AAIObjectType.PSERVER).output().to(__.node(AAIObjectType.COMPLEX).output()),
+ __.node(AAIObjectType.VSERVER)
+ .to(__.node(AAIObjectType.PSERVER).output().to(__.node(AAIObjectType.COMPLEX).output())));
+
+ assertEquals(
+ "generic-vnf*('vnf-id', 'vnfId') > " + "[ pserver* > complex*, " + "vserver > pserver* > complex* ]",
+ builder.build());
+ }
+
+ @Test
+ public void whereUnionTest() {
+ DSLQueryBuilder<DSLNode, DSLNode> builder =
+ new DSLQueryBuilder<>(new DSLNode(AAIObjectType.GENERIC_VNF, __.key("vnf-id", "vnfId")).output());
+
+ builder.where(__.union(__.node(AAIObjectType.PSERVER, __.key("hostname", "hostname1")),
+ __.node(AAIObjectType.VSERVER).to(__.node(AAIObjectType.PSERVER, __.key("hostname", "hostname1")))));
+
+ assertEquals("generic-vnf*('vnf-id', 'vnfId') (> [ pserver('hostname', 'hostname1'), "
+ + "vserver > pserver('hostname', 'hostname1') ])", builder.build());
+ }
+
+ @Test
+ public void notNullTest() {
+ DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(
+ new DSLNode(AAIObjectType.CLOUD_REGION, __.key("cloud-owner", "", "null").not()).output());
+
+ assertEquals("cloud-region* !('cloud-owner', ' ', ' null ')", builder.build());
+ }
+
+ @Test
+ public void shortCutToTest() {
+ DSLQueryBuilder<DSLNode, DSLNode> builder =
+ new DSLQueryBuilder<>(new DSLNode(AAIObjectType.PSERVER, __.key("hostname", "my-hostname")).output());
+
+ builder.to(AAIObjectType.P_INTERFACE).to(AAIObjectType.SRIOV_PF, __.key("pf-pci-id", "my-id"));
+ assertEquals("pserver*('hostname', 'my-hostname') > p-interface > sriov-pf('pf-pci-id', 'my-id')",
+ builder.build());
+ }
+
+ @Test
+ public void limitTest() {
+ DSLQueryBuilder<DSLNode, DSLNode> builder =
+ new DSLQueryBuilder<>(new DSLNode(AAIObjectType.PSERVER, __.key("hostname", "my-hostname")).output());
+
+ builder.to(AAIObjectType.P_INTERFACE).limit(2).to(AAIObjectType.SRIOV_PF, __.key("pf-pci-id", "my-id"));
+ assertEquals("pserver*('hostname', 'my-hostname') > p-interface > sriov-pf('pf-pci-id', 'my-id') LIMIT 2",
+ builder.build());
+ }
+
+ @Test
+ public void equalsTest() {
+ DSLQueryBuilder<DSLNode, DSLNode> builder =
+ new DSLQueryBuilder<>(new DSLNode(AAIObjectType.PSERVER, __.key("hostname", "my-hostname")).output());
+
+ builder.to(AAIObjectType.P_INTERFACE).to(AAIObjectType.SRIOV_PF, __.key("pf-pci-id", "my-id"));
+ assertTrue(
+ builder.equals("pserver*('hostname', 'my-hostname') > p-interface > sriov-pf('pf-pci-id', 'my-id')"));
+ assertTrue(builder.equals(builder));
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/entities/AAIResultWrapperTest.java b/common/src/test/java/org/onap/so/client/aai/entities/AAIResultWrapperTest.java
index 324be0114d..157109c119 100644
--- a/common/src/test/java/org/onap/so/client/aai/entities/AAIResultWrapperTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/entities/AAIResultWrapperTest.java
@@ -21,7 +21,6 @@
package org.onap.so.client.aai.entities;
import static org.junit.Assert.assertEquals;
-
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
@@ -29,7 +28,6 @@ import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -39,75 +37,74 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.onap.aai.domain.yang.GenericVnf;
import org.onap.so.client.aai.AAICommonObjectMapperProvider;
import org.springframework.util.SerializationUtils;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-@RunWith(MockitoJUnitRunner.class)
+@RunWith(MockitoJUnitRunner.class)
public class AAIResultWrapperTest {
- String json;
- @Rule
- public ExpectedException thrown= ExpectedException.none();
-
- AAIResultWrapper aaiResultWrapper;
- AAIResultWrapper aaiResultWrapperEmpty;
-
- @Before
- public void init() throws IOException {
- final String RESOURCE_PATH = "src/test/resources/__files/aai/resources/";
- json = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "e2e-complex.json")));
-
- aaiResultWrapper = new AAIResultWrapper(json);
- aaiResultWrapperEmpty = new AAIResultWrapper("{}");
- }
-
- @Test
- public void testAAIResultWrapperIsSerializable() throws IOException {
- AAIResultWrapper original = new AAIResultWrapper("");
- byte[] serialized = SerializationUtils.serialize(original);
- AAIResultWrapper deserialized = (AAIResultWrapper) SerializationUtils.deserialize(serialized);
- assertEquals(deserialized.getJson(), original.getJson());
- }
-
- @Test
- public void testGetRelationshipsEmpty() {
- Optional<Relationships> relationships = aaiResultWrapperEmpty.getRelationships();
- assertEquals("Compare relationships", Optional.empty(), relationships);
- }
-
- @Test
- public void testAsMap() throws JsonParseException, JsonMappingException, IOException {
- ObjectMapper mapper = new AAICommonObjectMapperProvider().getMapper();
- Map<String, Object> expected = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
-
- Map<String, Object> actual = aaiResultWrapper.asMap();
- assertEquals(expected, actual);
- }
-
- @Test
- public void testAsMapEmpty() {
- Map<String, Object> actual = aaiResultWrapperEmpty.asMap();
- assertEquals(new HashMap<>(), actual);
- }
-
- @Test
- public void nullCases() {
-
- AAIResultWrapper wrapper = new AAIResultWrapper(null);
-
- assertEquals(Optional.empty(), wrapper.getRelationships());
- assertEquals("{}", wrapper.getJson());
- assertEquals(Optional.empty(), wrapper.asBean(GenericVnf.class));
- assertEquals(true, wrapper.asMap().isEmpty());
- assertEquals("{}", wrapper.toString());
-
- }
-
- @Test
- public void objectConstructor() {
- AAIResultWrapper wrapper = new AAIResultWrapper(new GenericVnf());
- assertEquals("{}", wrapper.getJson());
- }
+ String json;
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ AAIResultWrapper aaiResultWrapper;
+ AAIResultWrapper aaiResultWrapperEmpty;
+
+ @Before
+ public void init() throws IOException {
+ final String RESOURCE_PATH = "src/test/resources/__files/aai/resources/";
+ json = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "e2e-complex.json")));
+
+ aaiResultWrapper = new AAIResultWrapper(json);
+ aaiResultWrapperEmpty = new AAIResultWrapper("{}");
+ }
+
+ @Test
+ public void testAAIResultWrapperIsSerializable() throws IOException {
+ AAIResultWrapper original = new AAIResultWrapper("");
+ byte[] serialized = SerializationUtils.serialize(original);
+ AAIResultWrapper deserialized = (AAIResultWrapper) SerializationUtils.deserialize(serialized);
+ assertEquals(deserialized.getJson(), original.getJson());
+ }
+
+ @Test
+ public void testGetRelationshipsEmpty() {
+ Optional<Relationships> relationships = aaiResultWrapperEmpty.getRelationships();
+ assertEquals("Compare relationships", Optional.empty(), relationships);
+ }
+
+ @Test
+ public void testAsMap() throws JsonParseException, JsonMappingException, IOException {
+ ObjectMapper mapper = new AAICommonObjectMapperProvider().getMapper();
+ Map<String, Object> expected = mapper.readValue(json, new TypeReference<Map<String, Object>>() {});
+
+ Map<String, Object> actual = aaiResultWrapper.asMap();
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testAsMapEmpty() {
+ Map<String, Object> actual = aaiResultWrapperEmpty.asMap();
+ assertEquals(new HashMap<>(), actual);
+ }
+
+ @Test
+ public void nullCases() {
+
+ AAIResultWrapper wrapper = new AAIResultWrapper(null);
+
+ assertEquals(Optional.empty(), wrapper.getRelationships());
+ assertEquals("{}", wrapper.getJson());
+ assertEquals(Optional.empty(), wrapper.asBean(GenericVnf.class));
+ assertEquals(true, wrapper.asMap().isEmpty());
+ assertEquals("{}", wrapper.toString());
+
+ }
+
+ @Test
+ public void objectConstructor() {
+ AAIResultWrapper wrapper = new AAIResultWrapper(new GenericVnf());
+ assertEquals("{}", wrapper.getJson());
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/entities/RelationshipsTest.java b/common/src/test/java/org/onap/so/client/aai/entities/RelationshipsTest.java
index 8d11f69308..ec7c6434a7 100644
--- a/common/src/test/java/org/onap/so/client/aai/entities/RelationshipsTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/entities/RelationshipsTest.java
@@ -21,13 +21,11 @@
package org.onap.so.client.aai.entities;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
-
import org.junit.Test;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
@@ -35,27 +33,27 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory;
public class RelationshipsTest {
- private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/resources/";
-
- @Test
- public void run() throws IOException {
- final String content = new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + "e2e-complex.json")));
-
- AAIResultWrapper wrapper = new AAIResultWrapper(content);
- Relationships relationships = wrapper.getRelationships().get();
-
- List<AAIResourceUri> test = relationships.getRelatedUris(AAIObjectType.VCE);
-
- System.out.println(test.get(0).build());
- List<AAIResourceUri> uris = Arrays.asList(
- AAIUriFactory.createResourceUri(AAIObjectType.VCE, "a9fec18e-1ea3-40e4-a6c0-a89b3de07053"),
- AAIUriFactory.createResourceUri(AAIObjectType.VCE, "8ae1e5f8-61f1-4c71-913a-b40cc4593cb9"),
- AAIUriFactory.createResourceUri(AAIObjectType.VCE, "a2935fa9-b743-49f4-9813-a127f13c4e93"),
- AAIUriFactory.createResourceUri(AAIObjectType.VCE, "c7fe7698-8063-4e26-8bd3-ca3edde0b0d4"));
-
-
- assertTrue(uris.containsAll(test) && test.containsAll(uris));
-
- }
+ private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/resources/";
+
+ @Test
+ public void run() throws IOException {
+ final String content = new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + "e2e-complex.json")));
+
+ AAIResultWrapper wrapper = new AAIResultWrapper(content);
+ Relationships relationships = wrapper.getRelationships().get();
+
+ List<AAIResourceUri> test = relationships.getRelatedUris(AAIObjectType.VCE);
+
+ System.out.println(test.get(0).build());
+ List<AAIResourceUri> uris = Arrays.asList(
+ AAIUriFactory.createResourceUri(AAIObjectType.VCE, "a9fec18e-1ea3-40e4-a6c0-a89b3de07053"),
+ AAIUriFactory.createResourceUri(AAIObjectType.VCE, "8ae1e5f8-61f1-4c71-913a-b40cc4593cb9"),
+ AAIUriFactory.createResourceUri(AAIObjectType.VCE, "a2935fa9-b743-49f4-9813-a127f13c4e93"),
+ AAIUriFactory.createResourceUri(AAIObjectType.VCE, "c7fe7698-8063-4e26-8bd3-ca3edde0b0d4"));
+
+
+ assertTrue(uris.containsAll(test) && test.containsAll(uris));
+
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromParentUriTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromParentUriTest.java
index beb18a389c..d26ff8d507 100644
--- a/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromParentUriTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromParentUriTest.java
@@ -21,21 +21,23 @@
package org.onap.so.client.aai.entities.uri;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.client.aai.AAIObjectType;
public class AAISimpleUriFromParentUriTest {
-
- @Test
- public void appendChildren() {
-
- AAIResourceUri parentUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "key1", "key2", "key3");
-
- AAIUri uri = new AAISimpleUri(parentUri, AAIObjectType.ALLOTTED_RESOURCE, "key4");
-
- assertEquals("path appended", "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3/allotted-resources/allotted-resource/key4", uri.build().toString());
-
- }
+
+ @Test
+ public void appendChildren() {
+
+ AAIResourceUri parentUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "key1", "key2", "key3");
+
+ AAIUri uri = new AAISimpleUri(parentUri, AAIObjectType.ALLOTTED_RESOURCE, "key4");
+
+ assertEquals("path appended",
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3/allotted-resources/allotted-resource/key4",
+ uri.build().toString());
+
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromUriTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromUriTest.java
index 5a69a42f35..ab1529d3ba 100644
--- a/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromUriTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromUriTest.java
@@ -21,40 +21,46 @@
package org.onap.so.client.aai.entities.uri;
import static org.junit.Assert.assertEquals;
-
import javax.ws.rs.core.UriBuilder;
-
import org.junit.Test;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.graphinventory.entities.uri.SimpleUri;
public class AAISimpleUriFromUriTest {
-
-
- @Test
- public void removeHost() {
-
- AAIUri uri = new AAISimpleUri(AAIObjectType.UNKNOWN, UriBuilder.fromUri("https://localhost:8443/aai/v9/network/vces/vce/a9fec18e-1ea3-40e4-a6c0-a89b3de07053").build());
-
- assertEquals("root and version removed", "/network/vces/vce/a9fec18e-1ea3-40e4-a6c0-a89b3de07053", uri.build().toString());
-
- }
- @Test
- public void noChange() {
-
- AAIUri uri = new AAISimpleUri(AAIObjectType.UNKNOWN, UriBuilder.fromUri("/network/vces/vce/a9fec18e-1ea3-40e4-a6c0-a89b3de07053").build());
-
- assertEquals("no change", "/network/vces/vce/a9fec18e-1ea3-40e4-a6c0-a89b3de07053", uri.build().toString());
-
- }
-
- @Test
- public void encodingPreserved() {
-
- AAIUri uri = new AAISimpleUri(AAIObjectType.UNKNOWN, UriBuilder.fromUri("/network/vces/vce/a9f%20%20ec18e-1ea3-40e4-a6c0-a89b3de07053").build());
-
- assertEquals("encoding preserved", "/network/vces/vce/a9f%20%20ec18e-1ea3-40e4-a6c0-a89b3de07053", uri.build().toString());
-
- }
+
+
+ @Test
+ public void removeHost() {
+
+ AAIUri uri = new AAISimpleUri(AAIObjectType.UNKNOWN,
+ UriBuilder
+ .fromUri("https://localhost:8443/aai/v9/network/vces/vce/a9fec18e-1ea3-40e4-a6c0-a89b3de07053")
+ .build());
+
+ assertEquals("root and version removed", "/network/vces/vce/a9fec18e-1ea3-40e4-a6c0-a89b3de07053",
+ uri.build().toString());
+
+ }
+
+ @Test
+ public void noChange() {
+
+ AAIUri uri = new AAISimpleUri(AAIObjectType.UNKNOWN,
+ UriBuilder.fromUri("/network/vces/vce/a9fec18e-1ea3-40e4-a6c0-a89b3de07053").build());
+
+ assertEquals("no change", "/network/vces/vce/a9fec18e-1ea3-40e4-a6c0-a89b3de07053", uri.build().toString());
+
+ }
+
+ @Test
+ public void encodingPreserved() {
+
+ AAIUri uri = new AAISimpleUri(AAIObjectType.UNKNOWN,
+ UriBuilder.fromUri("/network/vces/vce/a9f%20%20ec18e-1ea3-40e4-a6c0-a89b3de07053").build());
+
+ assertEquals("encoding preserved", "/network/vces/vce/a9f%20%20ec18e-1ea3-40e4-a6c0-a89b3de07053",
+ uri.build().toString());
+
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriTest.java
index 2a0e9df9ed..4e9d5aa8e8 100644
--- a/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriTest.java
@@ -24,7 +24,6 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.junit.Assert.assertEquals;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
@@ -33,7 +32,6 @@ import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
-
import org.junit.Test;
import org.onap.so.client.aai.AAIObjectPlurals;
import org.onap.so.client.aai.AAIObjectType;
@@ -42,81 +40,81 @@ import org.onap.so.client.graphinventory.entities.uri.SimpleUri;
public class AAISimpleUriTest {
-
-
- @Test
- public void relatedToTestPlural() {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test1");
- uri.relatedTo(AAIObjectPlurals.PSERVER);
- String uriOutput = uri.build().toString();
- assertEquals(true, uriOutput.contains("related-to"));
- }
-
- @Test
- public void relatedToTestSingular() {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test1");
- uri.relatedTo(AAIObjectType.PSERVER, "test2");
- String uriOutput = uri.build().toString();
- assertEquals(true, uriOutput.contains("related-to"));
- }
-
- @Test
- public void cloneTestSingular() {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test1");
- AAIResourceUri cloned = uri.clone();
- Map<String,String> keys = cloned.getURIKeys();
- assertThat(keys.values(), contains("test1"));
- }
-
- @Test
- public void cloneTestPlural() {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF);
- AAIResourceUri cloned = uri.clone();
- Map<String,String> keys = cloned.getURIKeys();
- assertThat(keys.values(), empty());
- }
-
- @Test
- public void getKeysTest() {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, "cloud1", "cloud2", "tenant1", "vserver1");
- Map<String,String> keys = uri.getURIKeys();
- System.out.println(keys);
- System.out.println(uri.build());
- assertEquals("vserver1", keys.get("vserver-id"));
- }
-
- @Test
- public void getEncodedKeyTest() {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "test1", "my value", "test3");
- Map<String,String> keys = uri.getURIKeys();
-
- assertEquals("my value", keys.get("service-type"));
- }
-
- @Test
- public void serializeTest() throws IOException, ClassNotFoundException {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test1");
-
- uri.depth(Depth.ONE);
- uri.limit(1);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
-
- ObjectOutputStream objectOutputStream
- = new ObjectOutputStream(bos);
- objectOutputStream.writeObject(uri);
- objectOutputStream.flush();
- objectOutputStream.close();
-
- ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
-
- ObjectInputStream objectInputStream
- = new ObjectInputStream(bis);
- AAIResourceUri e2 = (AAIResourceUri) objectInputStream.readObject();
- objectInputStream.close();
-
- uri.queryParam("test", "value");
- e2.queryParam("test", "value");
-
- assertEquals(e2.build().toString(), uri.build().toString());
- }
+
+
+ @Test
+ public void relatedToTestPlural() {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test1");
+ uri.relatedTo(AAIObjectPlurals.PSERVER);
+ String uriOutput = uri.build().toString();
+ assertEquals(true, uriOutput.contains("related-to"));
+ }
+
+ @Test
+ public void relatedToTestSingular() {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test1");
+ uri.relatedTo(AAIObjectType.PSERVER, "test2");
+ String uriOutput = uri.build().toString();
+ assertEquals(true, uriOutput.contains("related-to"));
+ }
+
+ @Test
+ public void cloneTestSingular() {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test1");
+ AAIResourceUri cloned = uri.clone();
+ Map<String, String> keys = cloned.getURIKeys();
+ assertThat(keys.values(), contains("test1"));
+ }
+
+ @Test
+ public void cloneTestPlural() {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF);
+ AAIResourceUri cloned = uri.clone();
+ Map<String, String> keys = cloned.getURIKeys();
+ assertThat(keys.values(), empty());
+ }
+
+ @Test
+ public void getKeysTest() {
+ AAIResourceUri uri =
+ AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, "cloud1", "cloud2", "tenant1", "vserver1");
+ Map<String, String> keys = uri.getURIKeys();
+ System.out.println(keys);
+ System.out.println(uri.build());
+ assertEquals("vserver1", keys.get("vserver-id"));
+ }
+
+ @Test
+ public void getEncodedKeyTest() {
+ AAIResourceUri uri =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "test1", "my value", "test3");
+ Map<String, String> keys = uri.getURIKeys();
+
+ assertEquals("my value", keys.get("service-type"));
+ }
+
+ @Test
+ public void serializeTest() throws IOException, ClassNotFoundException {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test1");
+
+ uri.depth(Depth.ONE);
+ uri.limit(1);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+
+ ObjectOutputStream objectOutputStream = new ObjectOutputStream(bos);
+ objectOutputStream.writeObject(uri);
+ objectOutputStream.flush();
+ objectOutputStream.close();
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+
+ ObjectInputStream objectInputStream = new ObjectInputStream(bis);
+ AAIResourceUri e2 = (AAIResourceUri) objectInputStream.readObject();
+ objectInputStream.close();
+
+ uri.queryParam("test", "value");
+ e2.queryParam("test", "value");
+
+ assertEquals(e2.build().toString(), uri.build().toString());
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/AAIUriFactoryTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/AAIUriFactoryTest.java
index 0ddf5c707b..9b4f5dafb5 100644
--- a/common/src/test/java/org/onap/so/client/aai/entities/uri/AAIUriFactoryTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/AAIUriFactoryTest.java
@@ -21,7 +21,6 @@
package org.onap.so.client.aai.entities.uri;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.client.aai.AAIObjectPlurals;
import org.onap.so.client.aai.AAIObjectType;
@@ -29,40 +28,41 @@ import org.onap.so.client.graphinventory.entities.uri.SimpleUri;
public class AAIUriFactoryTest {
- @Test
- public void testCreateResourceUri() {
-
- AAIUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "VIP(VelocitytoIP)");
-
- String expected = "/network/generic-vnfs/generic-vnf/VIP%28VelocitytoIP%29";
- assertEquals(expected, uri.build().toString());
- }
-
- @Test
- public void testCreateNodesUri() {
-
- AAIUri uri = AAIUriFactory.createNodesUri(AAIObjectType.GENERIC_VNF, "VIP(VelocitytoIP)");
-
- String expected = "/nodes/generic-vnfs/generic-vnf/VIP%28VelocitytoIP%29";
- assertEquals(expected, uri.build().toString());
- }
-
- @Test
- public void testCreateResourceFromExistingURI() {
-
- AAIUri uri = new AAISimpleUri(AAIObjectType.GENERIC_VNF, "VIP(VelocitytoIP)");
- AAIUri uri2 = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.GENERIC_VNF, uri.build());
-
- String expected = "/network/generic-vnfs/generic-vnf/VIP%28VelocitytoIP%29";
- assertEquals(expected, uri2.build().toString());
- }
-
- @Test
- public void testCreateResourceURIForPluralsWithValues() {
-
- AAIUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.SERVICE_INSTANCE, "customerId", "serviceType");
-
- String expected = "/business/customers/customer/customerId/service-subscriptions/service-subscription/serviceType/service-instances";
- assertEquals(expected, uri.build().toString());
- }
+ @Test
+ public void testCreateResourceUri() {
+
+ AAIUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "VIP(VelocitytoIP)");
+
+ String expected = "/network/generic-vnfs/generic-vnf/VIP%28VelocitytoIP%29";
+ assertEquals(expected, uri.build().toString());
+ }
+
+ @Test
+ public void testCreateNodesUri() {
+
+ AAIUri uri = AAIUriFactory.createNodesUri(AAIObjectType.GENERIC_VNF, "VIP(VelocitytoIP)");
+
+ String expected = "/nodes/generic-vnfs/generic-vnf/VIP%28VelocitytoIP%29";
+ assertEquals(expected, uri.build().toString());
+ }
+
+ @Test
+ public void testCreateResourceFromExistingURI() {
+
+ AAIUri uri = new AAISimpleUri(AAIObjectType.GENERIC_VNF, "VIP(VelocitytoIP)");
+ AAIUri uri2 = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.GENERIC_VNF, uri.build());
+
+ String expected = "/network/generic-vnfs/generic-vnf/VIP%28VelocitytoIP%29";
+ assertEquals(expected, uri2.build().toString());
+ }
+
+ @Test
+ public void testCreateResourceURIForPluralsWithValues() {
+
+ AAIUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.SERVICE_INSTANCE, "customerId", "serviceType");
+
+ String expected =
+ "/business/customers/customer/customerId/service-subscriptions/service-subscription/serviceType/service-instances";
+ assertEquals(expected, uri.build().toString());
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUriTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUriTest.java
index 0d2da3339a..4be6753894 100644
--- a/common/src/test/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUriTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUriTest.java
@@ -24,29 +24,31 @@ import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
-
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
-
import javax.ws.rs.core.UriBuilder;
-
import org.junit.Test;
import org.onap.so.client.graphinventory.exceptions.GraphInventoryPayloadException;
import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriNotFoundException;
public class AllottedResourceLookupUriTest {
- @Test
- public void oneKey() throws IOException, URISyntaxException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
-
- AllottedResourceLookupUri instance = new AllottedResourceLookupUri("key1");
- AllottedResourceLookupUri spy = spy(instance);
- doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3/allotted-resources/allotted-resource/key4").when(spy).getObjectById(any(Object.class));
-
- final URI result = spy.build();
- final URI expected = UriBuilder.fromPath("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3/allotted-resources/allotted-resource/key4").build();
- assertEquals("result is equal", expected, result);
-
- }
+ @Test
+ public void oneKey()
+ throws IOException, URISyntaxException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
+
+ AllottedResourceLookupUri instance = new AllottedResourceLookupUri("key1");
+ AllottedResourceLookupUri spy = spy(instance);
+ doReturn(
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3/allotted-resources/allotted-resource/key4")
+ .when(spy).getObjectById(any(Object.class));
+
+ final URI result = spy.build();
+ final URI expected = UriBuilder.fromPath(
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3/allotted-resources/allotted-resource/key4")
+ .build();
+ assertEquals("result is equal", expected, result);
+
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/IncorrectNumberOfUriKeysTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/IncorrectNumberOfUriKeysTest.java
index e84326e95f..86ee08c4e6 100644
--- a/common/src/test/java/org/onap/so/client/aai/entities/uri/IncorrectNumberOfUriKeysTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/IncorrectNumberOfUriKeysTest.java
@@ -23,7 +23,6 @@ package org.onap.so.client.aai.entities.uri;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -33,38 +32,40 @@ import org.onap.so.client.graphinventory.exceptions.IncorrectNumberOfUriKeys;
public class IncorrectNumberOfUriKeysTest {
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Test
- public void verifyIncorrectNumberOfKeysSingle() {
-
- thrown.expect(IncorrectNumberOfUriKeys.class);
- thrown.expectMessage(equalTo("Expected 3 variables: [cloud-owner, cloud-region-id, volume-group-id]"));
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, "volume-group-id");
-
- }
-
- @Test
- public void verifyIncorrectNumberOfKeysPlural() {
-
- thrown.expect(IncorrectNumberOfUriKeys.class);
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VOLUME_GROUP, "my-cloud-owner");
-
- }
-
- @Test
- public void verifyIncorrectNumberOfKeysFromParent() {
-
- thrown.expect(IncorrectNumberOfUriKeys.class);
- AAIResourceUri parentUri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, "my-cloud-owner", "my-cloud-region-id");
- AAIResourceUri uri = AAIUriFactory.createResourceFromParentURI(parentUri, AAIObjectType.VOLUME_GROUP);
- }
-
- @Test
- public void verifyIncorrectNumberOfKeysHttpAware() {
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void verifyIncorrectNumberOfKeysSingle() {
+
+ thrown.expect(IncorrectNumberOfUriKeys.class);
+ thrown.expectMessage(equalTo("Expected 3 variables: [cloud-owner, cloud-region-id, volume-group-id]"));
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, "volume-group-id");
+
+ }
+
+ @Test
+ public void verifyIncorrectNumberOfKeysPlural() {
+
+ thrown.expect(IncorrectNumberOfUriKeys.class);
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VOLUME_GROUP, "my-cloud-owner");
+
+ }
+
+ @Test
+ public void verifyIncorrectNumberOfKeysFromParent() {
+
+ thrown.expect(IncorrectNumberOfUriKeys.class);
+ AAIResourceUri parentUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, "my-cloud-owner", "my-cloud-region-id");
+ AAIResourceUri uri = AAIUriFactory.createResourceFromParentURI(parentUri, AAIObjectType.VOLUME_GROUP);
+ }
+
+ @Test
+ public void verifyIncorrectNumberOfKeysHttpAware() {
- thrown.expect(IncorrectNumberOfUriKeys.class);
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "customer-id", "subscription-id");
- }
+ thrown.expect(IncorrectNumberOfUriKeys.class);
+ AAIResourceUri uri =
+ AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "customer-id", "subscription-id");
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java
index c369767e38..e829666577 100644
--- a/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java
@@ -32,17 +32,14 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
-
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.UriBuilder;
-
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -59,149 +56,175 @@ import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl;
import org.onap.so.client.graphinventory.exceptions.GraphInventoryPayloadException;
import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriComputationException;
import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriNotFoundException;
-
import com.github.tomakehurst.wiremock.junit.WireMockRule;
@RunWith(MockitoJUnitRunner.class)
public class ServiceInstanceUriTest {
- private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/resources/";
-
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
-
- @Rule
- public final ExpectedException exception = ExpectedException.none();
-
- @Spy
- public AAIClient client;
-
- @InjectMocks
- public AAIResourcesClient aaiClient = new AAIResourcesClient();
-
- @Before
- public void beforeTest() {
- doReturn(new DefaultAAIPropertiesImpl(wireMockRule.port())).when(client).getRestProperties();
- }
- @Test
- public void found() throws IOException {
- final String content = new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + "service-instance-pathed-query.json")));
-
- ServiceInstanceUri instance = new ServiceInstanceUri("key3");
- final Optional<String> result = instance.extractRelatedLink(content);
- final String expected = "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3";
- assertEquals("result is equal", expected, result.get());
-
- }
-
- @Test
- public void oneKey() throws IOException, URISyntaxException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
-
- ServiceInstanceUri instance = new ServiceInstanceUri("key1");
- ServiceInstanceUri spy = spy(instance);
- doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3").when(spy).getObjectById(any(Object.class));
-
- final URI result = spy.build();
- final URI expected = UriBuilder.fromPath("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3").build();
- assertEquals("result is equal", expected, result);
-
- }
-
- @Test
- public void oneKeyQueryParams() throws IOException, URISyntaxException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
-
- ServiceInstanceUri instance = new ServiceInstanceUri("key1");
- ServiceInstanceUri spy = spy(instance);
- doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3").when(spy).getObjectById(any(Object.class));
-
- final URI result = spy.resourceVersion("1234").build();
- final URI expected = UriBuilder.fromUri("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3?resource-version=1234").build();
- assertEquals("result is equal", expected, result);
-
- }
-
- @Test
- public void oneKeyEncoded() throws IOException, URISyntaxException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
-
- ServiceInstanceUri instance = new ServiceInstanceUri("key1");
- ServiceInstanceUri spy = spy(instance);
- doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3%20space").when(spy).getObjectById(any(Object.class));
-
- final URI result = spy.build();
- final URI expected = UriBuilder.fromUri("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3%20space").build();
- assertEquals("result is equal", expected, result);
-
- }
-
- @Test
- public void oneKeyGetKeys() throws IOException, URISyntaxException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
-
- ServiceInstanceUri instance = new ServiceInstanceUri("key1");
- ServiceInstanceUri spy = spy(instance);
- doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3%28space").when(spy).getObjectById(any(Object.class));
-
- assertThat(spy.getURIKeys().values(), contains("key1", "key2", "key3(space"));
-
- }
- @Test
- public void oneKeyClone() throws GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
- ServiceInstanceUri instance = new ServiceInstanceUri("key1");
- ServiceInstanceUri spy = spy(instance);
- String uri = "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3";
- doReturn(uri).when(spy).getObjectById(any(Object.class));
- doReturn(Optional.of(uri)).when(spy).getCachedValue();
- final URI result = spy.resourceVersion("1234").clone().build();
- final URI expected = UriBuilder.fromUri("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3?resource-version=1234").build();
- assertEquals("result is equal", expected, result);
- }
-
- @Test
- public void threeKey() throws IOException {
-
- ServiceInstanceUri instance = new ServiceInstanceUri("key1", "key2", "key3");
- final URI result = instance.build();
- final URI expected = UriBuilder.fromPath("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3").build();
- assertEquals("result is equal", expected, result);
-
- }
-
- @Test
- public void notfound() throws IOException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
- final String content = new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + "empty-query-result.json")));
-
- ServiceInstanceUri instance = new ServiceInstanceUri("key3");
- ServiceInstanceUri spy = spy(instance);
- AAIResourcesClient mockResourcesClient = mock(AAIResourcesClient.class);
- AAIResultWrapper wrapper = mock(AAIResultWrapper.class);
- when(mockResourcesClient.get(ArgumentMatchers.<AAIResourceUri>any(AAIResourceUri.class), ArgumentMatchers.<Class<NotFoundException>>any())).thenReturn(wrapper);
- when(wrapper.getJson()).thenReturn(content);
- when(spy.getResourcesClient()).thenReturn(mockResourcesClient);
- exception.expect(GraphInventoryUriComputationException.class);
- spy.build();
-
- }
-
- @Test
- public void cloneTest() {
- ServiceInstanceUri instance = new ServiceInstanceUri("key1", "key2", "key3");
- final URI result = instance.build();
- final URI result2 = instance.clone().queryParam("something", "new").build();
- assertEquals("uris are not equal", false, result.toString().equals(result2.toString()));
-
- }
-
- @Test
- public void noVertexFound() throws GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
- ServiceInstanceUri instance = new ServiceInstanceUri("key3");
- ServiceInstanceUri spy = spy(instance);
- AAIResourcesClient client = aaiClient;
- doReturn(client).when(spy).getResourcesClient();
- wireMockRule.stubFor(get(urlPathMatching("/aai/v[0-9]+/nodes/service-instances/service-instance/key3"))
- .willReturn(aResponse()
- .withStatus(404)
- .withHeader("Content-Type", "application/json")
- .withBodyFile("")));
- exception.expect(NotFoundException.class);
- spy.build();
- }
+ private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/resources/";
+
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
+
+ @Rule
+ public final ExpectedException exception = ExpectedException.none();
+
+ @Spy
+ public AAIClient client;
+
+ @InjectMocks
+ public AAIResourcesClient aaiClient = new AAIResourcesClient();
+
+ @Before
+ public void beforeTest() {
+ doReturn(new DefaultAAIPropertiesImpl(wireMockRule.port())).when(client).getRestProperties();
+ }
+
+ @Test
+ public void found() throws IOException {
+ final String content = new String(
+ Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + "service-instance-pathed-query.json")));
+
+ ServiceInstanceUri instance = new ServiceInstanceUri("key3");
+ final Optional<String> result = instance.extractRelatedLink(content);
+ final String expected =
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3";
+ assertEquals("result is equal", expected, result.get());
+
+ }
+
+ @Test
+ public void oneKey()
+ throws IOException, URISyntaxException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
+
+ ServiceInstanceUri instance = new ServiceInstanceUri("key1");
+ ServiceInstanceUri spy = spy(instance);
+ doReturn(
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3")
+ .when(spy).getObjectById(any(Object.class));
+
+ final URI result = spy.build();
+ final URI expected = UriBuilder.fromPath(
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3")
+ .build();
+ assertEquals("result is equal", expected, result);
+
+ }
+
+ @Test
+ public void oneKeyQueryParams()
+ throws IOException, URISyntaxException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
+
+ ServiceInstanceUri instance = new ServiceInstanceUri("key1");
+ ServiceInstanceUri spy = spy(instance);
+ doReturn(
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3")
+ .when(spy).getObjectById(any(Object.class));
+
+ final URI result = spy.resourceVersion("1234").build();
+ final URI expected = UriBuilder.fromUri(
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3?resource-version=1234")
+ .build();
+ assertEquals("result is equal", expected, result);
+
+ }
+
+ @Test
+ public void oneKeyEncoded()
+ throws IOException, URISyntaxException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
+
+ ServiceInstanceUri instance = new ServiceInstanceUri("key1");
+ ServiceInstanceUri spy = spy(instance);
+ doReturn(
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3%20space")
+ .when(spy).getObjectById(any(Object.class));
+
+ final URI result = spy.build();
+ final URI expected = UriBuilder.fromUri(
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3%20space")
+ .build();
+ assertEquals("result is equal", expected, result);
+
+ }
+
+ @Test
+ public void oneKeyGetKeys()
+ throws IOException, URISyntaxException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
+
+ ServiceInstanceUri instance = new ServiceInstanceUri("key1");
+ ServiceInstanceUri spy = spy(instance);
+ doReturn(
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3%28space")
+ .when(spy).getObjectById(any(Object.class));
+
+ assertThat(spy.getURIKeys().values(), contains("key1", "key2", "key3(space"));
+
+ }
+
+ @Test
+ public void oneKeyClone() throws GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
+ ServiceInstanceUri instance = new ServiceInstanceUri("key1");
+ ServiceInstanceUri spy = spy(instance);
+ String uri =
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3";
+ doReturn(uri).when(spy).getObjectById(any(Object.class));
+ doReturn(Optional.of(uri)).when(spy).getCachedValue();
+ final URI result = spy.resourceVersion("1234").clone().build();
+ final URI expected = UriBuilder.fromUri(
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3?resource-version=1234")
+ .build();
+ assertEquals("result is equal", expected, result);
+ }
+
+ @Test
+ public void threeKey() throws IOException {
+
+ ServiceInstanceUri instance = new ServiceInstanceUri("key1", "key2", "key3");
+ final URI result = instance.build();
+ final URI expected = UriBuilder.fromPath(
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3")
+ .build();
+ assertEquals("result is equal", expected, result);
+
+ }
+
+ @Test
+ public void notfound() throws IOException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
+ final String content =
+ new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + "empty-query-result.json")));
+
+ ServiceInstanceUri instance = new ServiceInstanceUri("key3");
+ ServiceInstanceUri spy = spy(instance);
+ AAIResourcesClient mockResourcesClient = mock(AAIResourcesClient.class);
+ AAIResultWrapper wrapper = mock(AAIResultWrapper.class);
+ when(mockResourcesClient.get(ArgumentMatchers.<AAIResourceUri>any(AAIResourceUri.class),
+ ArgumentMatchers.<Class<NotFoundException>>any())).thenReturn(wrapper);
+ when(wrapper.getJson()).thenReturn(content);
+ when(spy.getResourcesClient()).thenReturn(mockResourcesClient);
+ exception.expect(GraphInventoryUriComputationException.class);
+ spy.build();
+
+ }
+
+ @Test
+ public void cloneTest() {
+ ServiceInstanceUri instance = new ServiceInstanceUri("key1", "key2", "key3");
+ final URI result = instance.build();
+ final URI result2 = instance.clone().queryParam("something", "new").build();
+ assertEquals("uris are not equal", false, result.toString().equals(result2.toString()));
+
+ }
+
+ @Test
+ public void noVertexFound() throws GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
+ ServiceInstanceUri instance = new ServiceInstanceUri("key3");
+ ServiceInstanceUri spy = spy(instance);
+ AAIResourcesClient client = aaiClient;
+ doReturn(client).when(spy).getResourcesClient();
+ wireMockRule
+ .stubFor(get(urlPathMatching("/aai/v[0-9]+/nodes/service-instances/service-instance/key3")).willReturn(
+ aResponse().withStatus(404).withHeader("Content-Type", "application/json").withBodyFile("")));
+ exception.expect(NotFoundException.class);
+ spy.build();
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/objects/CustomAAIObjectType.java b/common/src/test/java/org/onap/so/client/aai/objects/CustomAAIObjectType.java
index 3979902962..f437197f71 100644
--- a/common/src/test/java/org/onap/so/client/aai/objects/CustomAAIObjectType.java
+++ b/common/src/test/java/org/onap/so/client/aai/objects/CustomAAIObjectType.java
@@ -24,17 +24,19 @@ import org.onap.so.client.aai.AAINamespaceConstants;
import org.onap.so.client.aai.AAIObjectType;
public class CustomAAIObjectType extends AAIObjectType {
-
- private static final long serialVersionUID = 1919729212831978098L;
-
- public static final AAIObjectType CUSTOM = new CustomAAIObjectType(AAINamespaceConstants.NETWORK, "my-url", "my-custom-name");
-
- /* Default constructor automatically called by AAIObjectType */
- public CustomAAIObjectType() {
- super();
- }
- protected CustomAAIObjectType(String parent, String uri, String name) {
- super(parent, uri, name);
- }
+
+ private static final long serialVersionUID = 1919729212831978098L;
+
+ public static final AAIObjectType CUSTOM =
+ new CustomAAIObjectType(AAINamespaceConstants.NETWORK, "my-url", "my-custom-name");
+
+ /* Default constructor automatically called by AAIObjectType */
+ public CustomAAIObjectType() {
+ super();
+ }
+
+ protected CustomAAIObjectType(String parent, String uri, String name) {
+ super(parent, uri, name);
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java b/common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java
index f4490faacc..bc600310b3 100644
--- a/common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java
+++ b/common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java
@@ -24,7 +24,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.net.URI;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
@@ -80,8 +79,8 @@ public class AdapterRestClientTest {
String encyptedMessage = CryptoUtils.encrypt("testAdapter", CRYPTO_KEY);
when(adapterRestPropertiesMock.getAuth()).thenReturn(encyptedMessage);
when(adapterRestPropertiesMock.getKey()).thenReturn(INVALID_CRYPTO_KEY);
- AdapterRestClient testedObject = new AdapterRestClient(adapterRestPropertiesMock, new URI(""),
- "accept", "contentType");
+ AdapterRestClient testedObject =
+ new AdapterRestClient(adapterRestPropertiesMock, new URI(""), "accept", "contentType");
// when
testedObject.initializeHeaderMap(headerMap);
// then
diff --git a/common/src/test/java/org/onap/so/client/cds/CDSProcessingClientTest.java b/common/src/test/java/org/onap/so/client/cds/CDSProcessingClientTest.java
index f6bf21458d..18ec9efa50 100644
--- a/common/src/test/java/org/onap/so/client/cds/CDSProcessingClientTest.java
+++ b/common/src/test/java/org/onap/so/client/cds/CDSProcessingClientTest.java
@@ -23,7 +23,6 @@ package org.onap.so.client.cds;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
-
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.stub.StreamObserver;
@@ -68,42 +67,40 @@ public class CDSProcessingClientTest {
@Before
public void setUp() throws Exception {
String serverName = InProcessServerBuilder.generateName();
- grpcCleanup.register(InProcessServerBuilder.forName(serverName)
- .fallbackHandlerRegistry(serviceRegistry).directExecutor().build().start());
+ grpcCleanup.register(InProcessServerBuilder.forName(serverName).fallbackHandlerRegistry(serviceRegistry)
+ .directExecutor().build().start());
handler = new CDSProcessingHandler(listener);
- client =
- new CDSProcessingClient(InProcessChannelBuilder.forName(serverName).directExecutor().build(), handler);
+ client = new CDSProcessingClient(InProcessChannelBuilder.forName(serverName).directExecutor().build(), handler);
- final BluePrintProcessingServiceImplBase routeChatImpl =
- new BluePrintProcessingServiceImplBase() {
- @Override
- public StreamObserver<ExecutionServiceInput> process(
+ final BluePrintProcessingServiceImplBase routeChatImpl = new BluePrintProcessingServiceImplBase() {
+ @Override
+ public StreamObserver<ExecutionServiceInput> process(
StreamObserver<ExecutionServiceOutput> responseObserver) {
- responseObserverRef.set(responseObserver);
+ responseObserverRef.set(responseObserver);
- StreamObserver<ExecutionServiceInput> requestObserver = new StreamObserver<ExecutionServiceInput>() {
- @Override
- public void onNext(ExecutionServiceInput message) {
- messagesDelivered.add(message.getActionIdentifiers().getActionName());
- }
+ StreamObserver<ExecutionServiceInput> requestObserver = new StreamObserver<ExecutionServiceInput>() {
+ @Override
+ public void onNext(ExecutionServiceInput message) {
+ messagesDelivered.add(message.getActionIdentifiers().getActionName());
+ }
- @Override
- public void onError(Throwable t) {
+ @Override
+ public void onError(Throwable t) {
- }
+ }
- @Override
- public void onCompleted() {
- allRequestsDelivered.countDown();
- }
- };
+ @Override
+ public void onCompleted() {
+ allRequestsDelivered.countDown();
+ }
+ };
- return requestObserver;
- }
- };
+ return requestObserver;
+ }
+ };
serviceRegistry.addService(routeChatImpl);
}
@@ -122,8 +119,8 @@ public class CDSProcessingClientTest {
@Test
public void testSendMessageFail() throws Exception {
- ExecutionServiceInput fakeRequest1 = ExecutionServiceInput.newBuilder().setActionIdentifiers(
- ActionIdentifiers.newBuilder().setActionName("request1").build()).build();
+ ExecutionServiceInput fakeRequest1 = ExecutionServiceInput.newBuilder()
+ .setActionIdentifiers(ActionIdentifiers.newBuilder().setActionName("request1").build()).build();
CountDownLatch finishLatch = client.sendRequest(fakeRequest1);
@@ -136,14 +133,14 @@ public class CDSProcessingClientTest {
@Test
public void testSendMessage() throws Exception {
- ExecutionServiceInput fakeRequest1 = ExecutionServiceInput.newBuilder().setActionIdentifiers(
- ActionIdentifiers.newBuilder().setActionName("request1").build()).build();
+ ExecutionServiceInput fakeRequest1 = ExecutionServiceInput.newBuilder()
+ .setActionIdentifiers(ActionIdentifiers.newBuilder().setActionName("request1").build()).build();
- ExecutionServiceOutput fakeResponse1 = ExecutionServiceOutput.newBuilder().setActionIdentifiers(
- ActionIdentifiers.newBuilder().setActionName("response1").build()).build();
+ ExecutionServiceOutput fakeResponse1 = ExecutionServiceOutput.newBuilder()
+ .setActionIdentifiers(ActionIdentifiers.newBuilder().setActionName("response1").build()).build();
- ExecutionServiceOutput fakeResponse2 = ExecutionServiceOutput.newBuilder().setActionIdentifiers(
- ActionIdentifiers.newBuilder().setActionName("response2").build()).build();
+ ExecutionServiceOutput fakeResponse2 = ExecutionServiceOutput.newBuilder()
+ .setActionIdentifiers(ActionIdentifiers.newBuilder().setActionName("response2").build()).build();
CountDownLatch finishLatch = client.sendRequest(fakeRequest1);
diff --git a/common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java b/common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java
index 636f92835f..e233db48b0 100644
--- a/common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java
+++ b/common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java
@@ -1,17 +1,14 @@
/*
* Copyright (C) 2019 Bell Canada.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
*/
package org.onap.so.client.cds;
@@ -63,8 +60,8 @@ public class TestCDSPropertiesImpl implements CDSProperties {
return false;
}
- @Override
- public int getTimeout() {
- return 60;
- }
+ @Override
+ public int getTimeout() {
+ return 60;
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/defaultproperties/DefaultAAIPropertiesImpl.java b/common/src/test/java/org/onap/so/client/defaultproperties/DefaultAAIPropertiesImpl.java
index 65c76561dc..7789386667 100644
--- a/common/src/test/java/org/onap/so/client/defaultproperties/DefaultAAIPropertiesImpl.java
+++ b/common/src/test/java/org/onap/so/client/defaultproperties/DefaultAAIPropertiesImpl.java
@@ -29,65 +29,67 @@ import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
-
import org.onap.so.client.aai.AAIProperties;
import org.onap.so.client.aai.AAIVersion;
public class DefaultAAIPropertiesImpl implements AAIProperties {
-
- final Map<Object, Object> props;
- public DefaultAAIPropertiesImpl() {
- File initialFile = new File("src/test/resources/aai.properties");
- Map<Object, Object> temp;
- try (InputStream targetStream = new FileInputStream(initialFile)) {
- Properties properties = new Properties();
- properties.load(targetStream);
- temp = properties;
- } catch (IOException e) {
- temp = new HashMap<>();
- }
- this.props = temp;
- }
-
- public DefaultAAIPropertiesImpl(int port) {
- File initialFile = new File("src/test/resources/aai.properties");
- Map<Object, Object> temp;
- try (InputStream targetStream = new FileInputStream(initialFile)) {
- Properties properties = new Properties();
- properties.load(targetStream);
- temp = properties;
- } catch (IOException e) {
- temp = new HashMap<>();
- }
- this.props = temp;
- this.props.put("aai.endpoint", this.props.get("aai.endpoint").toString().replaceFirst(":\\d+", ":" + port));
+ final Map<Object, Object> props;
+
+ public DefaultAAIPropertiesImpl() {
+ File initialFile = new File("src/test/resources/aai.properties");
+ Map<Object, Object> temp;
+ try (InputStream targetStream = new FileInputStream(initialFile)) {
+ Properties properties = new Properties();
+ properties.load(targetStream);
+ temp = properties;
+ } catch (IOException e) {
+ temp = new HashMap<>();
+ }
+ this.props = temp;
+
+ }
+
+ public DefaultAAIPropertiesImpl(int port) {
+ File initialFile = new File("src/test/resources/aai.properties");
+ Map<Object, Object> temp;
+ try (InputStream targetStream = new FileInputStream(initialFile)) {
+ Properties properties = new Properties();
+ properties.load(targetStream);
+ temp = properties;
+ } catch (IOException e) {
+ temp = new HashMap<>();
+ }
+ this.props = temp;
+ this.props.put("aai.endpoint", this.props.get("aai.endpoint").toString().replaceFirst(":\\d+", ":" + port));
+
+ }
+
+ @Override
+ public URL getEndpoint() throws MalformedURLException {
+ return new URL(props.get("aai.endpoint").toString());
+ }
- }
- @Override
- public URL getEndpoint() throws MalformedURLException {
- return new URL(props.get("aai.endpoint").toString());
- }
+ @Override
+ public String getSystemName() {
+ return "MSO";
+ }
- @Override
- public String getSystemName() {
- return "MSO";
- }
- @Override
- public AAIVersion getDefaultVersion() {
- return AAIVersion.LATEST;
- }
+ @Override
+ public AAIVersion getDefaultVersion() {
+ return AAIVersion.LATEST;
+ }
- @Override
- public String getAuth() {
- Object value = props.get("aai.auth");
- return value == null ? null : value.toString();
- }
+ @Override
+ public String getAuth() {
+ Object value = props.get("aai.auth");
+ return value == null ? null : value.toString();
+ }
- @Override
- public String getKey() {
- Object value = props.get("mso.msoKey");
- return value == null ? null : value.toString();
- }
+ @Override
+ public String getKey() {
+ Object value = props.get("mso.msoKey");
+ return value == null ? null : value.toString();
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/dmaap/DmaapClientTest.java b/common/src/test/java/org/onap/so/client/dmaap/DmaapClientTest.java
index 4b90cfe021..26fb1cd336 100644
--- a/common/src/test/java/org/onap/so/client/dmaap/DmaapClientTest.java
+++ b/common/src/test/java/org/onap/so/client/dmaap/DmaapClientTest.java
@@ -21,21 +21,19 @@
package org.onap.so.client.dmaap;
import static org.junit.Assert.assertEquals;
-
import java.io.FileNotFoundException;
import java.io.IOException;
-
import org.junit.Test;
import org.onap.so.client.sdno.dmaap.SDNOHealthCheckDmaapConsumer;
public class DmaapClientTest {
- @Test
- public void deobfuscateTest() throws FileNotFoundException, IOException {
- String encodedBase64 = "dGVzdHBhc3N3b3Jk";
- String notEncoded = "testpassword";
- DmaapConsumer consumer = new SDNOHealthCheckDmaapConsumer();
- assertEquals("decoded password", notEncoded, consumer.deobfuscatePassword(encodedBase64));
+ @Test
+ public void deobfuscateTest() throws FileNotFoundException, IOException {
+ String encodedBase64 = "dGVzdHBhc3N3b3Jk";
+ String notEncoded = "testpassword";
+ DmaapConsumer consumer = new SDNOHealthCheckDmaapConsumer();
+ assertEquals("decoded password", notEncoded, consumer.deobfuscatePassword(encodedBase64));
- }
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java b/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java
index 0836ed23eb..4bfac38151 100644
--- a/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java
+++ b/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java
@@ -20,7 +20,6 @@
package org.onap.so.client.dmaap;
import org.junit.Test;
-
import javax.ws.rs.ProcessingException;
import java.io.IOException;
import java.util.Optional;
@@ -49,12 +48,11 @@ public class DmaapPublisherTest {
}
};
- public DmaapPublisherTest() throws IOException {
- }
+ public DmaapPublisherTest() throws IOException {}
@Test(expected = ProcessingException.class)
public void sendTest() throws Exception {
- dmaapPublisher.send("{'key': 'value'}");
+ dmaapPublisher.send("{'key': 'value'}");
}
-} \ No newline at end of file
+}
diff --git a/common/src/test/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverterTest.java b/common/src/test/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverterTest.java
index d24b3ff147..1f047b3b36 100644
--- a/common/src/test/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverterTest.java
+++ b/common/src/test/java/org/onap/so/client/graphinventory/GraphInventoryPatchConverterTest.java
@@ -24,12 +24,10 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -37,7 +35,6 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.onap.aai.domain.yang.GenericVnf;
import org.onap.so.client.aai.AAICommonObjectMapperProvider;
import org.onap.so.client.graphinventory.GraphInventoryPatchConverter;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -46,69 +43,76 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(MockitoJUnitRunner.class)
public class GraphInventoryPatchConverterTest {
- private ObjectMapper mapper = new AAICommonObjectMapperProvider().getMapper();
+ private ObjectMapper mapper = new AAICommonObjectMapperProvider().getMapper();
+
+ @Test
+ public void convertObjectToPatchFormatTest()
+ throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
+ GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter();
+ GenericVnf vnf = new GenericVnf();
+ vnf.setIpv4Loopback0Address("");
+ String result = validator.marshallObjectToPatchFormat(vnf);
+ GenericVnf resultObj = mapper.readValue(result.toString(), GenericVnf.class);
+ assertTrue("expect object to become a String to prevent double marshalling", result instanceof String);
+ assertNull("expect null because of custom mapper", resultObj.getIpv4Loopback0Address());
+
+ }
+
+ @Test
+ public void convertStringToPatchFormatTest()
+ throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
+ GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter();
+ String payload = "{\"ipv4-loopback0-address\":\"\"}";
+ String result = validator.marshallObjectToPatchFormat(payload);
+
+ assertEquals("expect no change", payload, result);
+ }
+
+ @Test
+ public void convertStringToPatchFormatNull_Test()
+ throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
+ GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter();
+ String payload = "{\"ipv4-loopback0-address\": null}";
+ String result = validator.marshallObjectToPatchFormat(payload);
+ System.out.println(result);
+ assertEquals("expect no change", payload, result);
+ }
+
+ @Test
+ public void convertMapToPatchFormatTest()
+ throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
+ GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter();
+ HashMap<String, String> map = new HashMap<>();
+ map.put("ipv4-loopback0-address", "");
+ map.put("ipv4-loopback1-address", "192.168.1.1");
+ String result = validator.marshallObjectToPatchFormat(map);
+
+ assertEquals("expect string", "{\"ipv4-loopback1-address\":\"192.168.1.1\"}", result);
+ }
+
+ @Test
+ public void hasComplexObjectTest() {
+ GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter();
+ String hasNesting = "{ \"hello\" : \"world\", \"nested\" : { \"key\" : \"value\" } }";
+ String noNesting = "{ \"hello\" : \"world\" }";
+ String arrayCase =
+ "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"nestedComplex\" : [{\"key\" : \"value\"}]}";
+ String empty = "{}";
+ String arrayCaseSimpleOnly = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"]}";
+ String relationshipListCaseNesting =
+ "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"relationship-list\" : [{\"key\" : \"value\"}], \"nested\" : { \"key\" : \"value\" }}";
+ String relationshipListCase =
+ "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"relationship-list\" : [{\"key\" : \"value\"}]}";
+ String nothing = "";
+
+ assertTrue("expect has nesting", validator.hasComplexObject(hasNesting));
+ assertFalse("expect no nesting", validator.hasComplexObject(noNesting));
+ assertTrue("expect has nesting", validator.hasComplexObject(arrayCase));
+ assertFalse("expect no nesting", validator.hasComplexObject(empty));
+ assertFalse("expect no nesting", validator.hasComplexObject(arrayCaseSimpleOnly));
+ assertFalse("expect no nesting", validator.hasComplexObject(relationshipListCase));
+ assertTrue("expect has nesting", validator.hasComplexObject(relationshipListCaseNesting));
+ assertFalse("expect no nesting", validator.hasComplexObject(nothing));
+ }
- @Test
- public void convertObjectToPatchFormatTest() throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
- GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter();
- GenericVnf vnf = new GenericVnf();
- vnf.setIpv4Loopback0Address("");
- String result = validator.marshallObjectToPatchFormat(vnf);
- GenericVnf resultObj = mapper.readValue(result.toString(), GenericVnf.class);
- assertTrue("expect object to become a String to prevent double marshalling", result instanceof String);
- assertNull("expect null because of custom mapper", resultObj.getIpv4Loopback0Address());
-
- }
-
- @Test
- public void convertStringToPatchFormatTest() throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
- GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter();
- String payload = "{\"ipv4-loopback0-address\":\"\"}";
- String result = validator.marshallObjectToPatchFormat(payload);
-
- assertEquals("expect no change", payload, result);
- }
-
- @Test
- public void convertStringToPatchFormatNull_Test() throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
- GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter();
- String payload = "{\"ipv4-loopback0-address\": null}";
- String result = validator.marshallObjectToPatchFormat(payload);
- System.out.println(result);
- assertEquals("expect no change", payload, result);
- }
-
- @Test
- public void convertMapToPatchFormatTest() throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
- GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter();
- HashMap<String, String> map = new HashMap<>();
- map.put("ipv4-loopback0-address", "");
- map.put("ipv4-loopback1-address", "192.168.1.1");
- String result = validator.marshallObjectToPatchFormat(map);
-
- assertEquals("expect string", "{\"ipv4-loopback1-address\":\"192.168.1.1\"}", result);
- }
-
- @Test
- public void hasComplexObjectTest() {
- GraphInventoryPatchConverter validator = new GraphInventoryPatchConverter();
- String hasNesting = "{ \"hello\" : \"world\", \"nested\" : { \"key\" : \"value\" } }";
- String noNesting = "{ \"hello\" : \"world\" }";
- String arrayCase = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"nestedComplex\" : [{\"key\" : \"value\"}]}";
- String empty = "{}";
- String arrayCaseSimpleOnly = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"]}";
- String relationshipListCaseNesting = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"relationship-list\" : [{\"key\" : \"value\"}], \"nested\" : { \"key\" : \"value\" }}";
- String relationshipListCase = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"relationship-list\" : [{\"key\" : \"value\"}]}";
- String nothing = "";
-
- assertTrue("expect has nesting", validator.hasComplexObject(hasNesting));
- assertFalse("expect no nesting", validator.hasComplexObject(noNesting));
- assertTrue("expect has nesting", validator.hasComplexObject(arrayCase));
- assertFalse("expect no nesting", validator.hasComplexObject(empty));
- assertFalse("expect no nesting", validator.hasComplexObject(arrayCaseSimpleOnly));
- assertFalse("expect no nesting", validator.hasComplexObject(relationshipListCase));
- assertTrue("expect has nesting", validator.hasComplexObject(relationshipListCaseNesting));
- assertFalse("expect no nesting", validator.hasComplexObject(nothing));
- }
-
}
diff --git a/common/src/test/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImplTest.java b/common/src/test/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImplTest.java
index be93f47585..fb26e1870e 100644
--- a/common/src/test/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImplTest.java
+++ b/common/src/test/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImplTest.java
@@ -21,9 +21,7 @@
package org.onap.so.client.graphinventory.entities.uri.parsers;
import static org.junit.Assert.assertEquals;
-
import java.util.Map;
-
import org.junit.Test;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.graphinventory.entities.uri.parsers.UriParser;
@@ -31,19 +29,19 @@ import org.onap.so.client.graphinventory.entities.uri.parsers.UriParserSpringImp
public class UriParserSpringImplTest {
-
-
-
- @Test
- public void reverseTemplate() {
- final UriParser parser = new UriParserSpringImpl(AAIObjectType.SERVICE_INSTANCE.toString());
- final String uri = "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3";
-
- Map<String, String> result = parser.parse(uri);
-
- assertEquals("found customer-id", "key1", result.get("global-customer-id"));
- assertEquals("found service-type", "key2", result.get("service-type"));
- assertEquals("found service-instance-id", "key3", result.get("service-instance-id"));
-
- }
+
+
+ @Test
+ public void reverseTemplate() {
+ final UriParser parser = new UriParserSpringImpl(AAIObjectType.SERVICE_INSTANCE.toString());
+ final String uri =
+ "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3";
+
+ Map<String, String> result = parser.parse(uri);
+
+ assertEquals("found customer-id", "key1", result.get("global-customer-id"));
+ assertEquals("found service-type", "key2", result.get("service-type"));
+ assertEquals("found service-instance-id", "key3", result.get("service-instance-id"));
+
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/grm/GRMBeansTest.java b/common/src/test/java/org/onap/so/client/grm/GRMBeansTest.java
index 76b7369399..8ffb70665c 100644
--- a/common/src/test/java/org/onap/so/client/grm/GRMBeansTest.java
+++ b/common/src/test/java/org/onap/so/client/grm/GRMBeansTest.java
@@ -21,9 +21,7 @@
package org.onap.so.client.grm;
import java.util.List;
-
import org.junit.Test;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterEnum;
@@ -38,25 +36,21 @@ import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
public class GRMBeansTest {
- private static final String POJO_PACKAGE = "org.onap.so.client.grm.beans";
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
+ private static final String POJO_PACKAGE = "org.onap.so.client.grm.beans";
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ @Test
+ public void testPojoStructureAndBehavior() {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule())
+ .with(new SetterTester()).with(new GetterTester()).build();
+
+ validator.validate(POJO_PACKAGE, new FilterPackageInfo(), new FilterEnum(), filterTestClasses);
+ }
- @Test
- public void testPojoStructureAndBehavior() {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterMustExistRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
- validator.validate(POJO_PACKAGE, new FilterPackageInfo(), new FilterEnum(), filterTestClasses);
- }
-
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
-
}
diff --git a/common/src/test/java/org/onap/so/client/grm/ServiceEndPointListTest.java b/common/src/test/java/org/onap/so/client/grm/ServiceEndPointListTest.java
index d0d0e6701b..65069899de 100644
--- a/common/src/test/java/org/onap/so/client/grm/ServiceEndPointListTest.java
+++ b/common/src/test/java/org/onap/so/client/grm/ServiceEndPointListTest.java
@@ -27,73 +27,71 @@ import static org.junit.Assert.*;
import org.junit.Test;
import org.onap.so.client.grm.beans.ServiceEndPoint;
import org.onap.so.client.grm.beans.ServiceEndPointList;
-
import com.fasterxml.jackson.databind.ObjectMapper;
public class ServiceEndPointListTest {
-
- private ObjectMapper mapper = new ObjectMapper();
-
- @Test
- public void testUnmarshall() throws Exception {
- String endpointsJson = getFileContentsAsString("__files/grm/endpoints.json");
- ServiceEndPointList sel = mapper.readValue(endpointsJson, ServiceEndPointList.class);
-
- List<ServiceEndPoint> list = sel.getServiceEndPointList();
- ServiceEndPoint se = list.get(0);
-
- assertEquals(3, list.size());
- assertEquals("dummy.pod.ns.dummy-pod3", se.getName());
- assertEquals(Integer.valueOf(1), Integer.valueOf(se.getVersion().getMajor()));
- assertEquals(Integer.valueOf(0), Integer.valueOf(se.getVersion().getMinor()));
- assertEquals(Integer.valueOf(0), Integer.valueOf(se.getVersion().getPatch()));
- assertEquals("192.168.120.218", se.getHostAddress());
- assertEquals("32004", se.getListenPort());
- assertEquals("37.7022", se.getLatitude());
- assertEquals("121.9358", se.getLongitude());
- assertEquals("/", se.getContextPath());
- assertEquals("edge", se.getOperationalInfo().getCreatedBy());
- assertEquals("edge", se.getOperationalInfo().getUpdatedBy());
- assertEquals("Environment", se.getProperties().get(0).getName());
- assertEquals("DEV", se.getProperties().get(0).getValue());
- }
-
- @Test
- public void testUnmarshallServiceEndpointListStartsWithUppercase() throws Exception {
- String endpointsJson = getFileContentsAsString("__files/grm/endpoints2.json");
- ServiceEndPointList sel = mapper.readValue(endpointsJson, ServiceEndPointList.class);
-
- List<ServiceEndPoint> list = sel.getServiceEndPointList();
- ServiceEndPoint se = list.get(0);
-
- assertEquals(3, list.size());
- assertEquals("dummy.pod.ns.dummy-pod3", se.getName());
- assertEquals(Integer.valueOf(1), Integer.valueOf(se.getVersion().getMajor()));
- assertEquals(Integer.valueOf(0), Integer.valueOf(se.getVersion().getMinor()));
- assertEquals(Integer.valueOf(0), Integer.valueOf(se.getVersion().getPatch()));
- assertEquals("192.168.120.218", se.getHostAddress());
- assertEquals("32004", se.getListenPort());
- assertEquals("37.7022", se.getLatitude());
- assertEquals("121.9358", se.getLongitude());
- assertEquals("/", se.getContextPath());
- assertEquals("edge", se.getOperationalInfo().getCreatedBy());
- assertEquals("edge", se.getOperationalInfo().getUpdatedBy());
- assertEquals("Environment", se.getProperties().get(0).getName());
- assertEquals("DEV", se.getProperties().get(0).getValue());
- }
-
- protected String getFileContentsAsString(String fileName) {
- String content = "";
- try {
- ClassLoader classLoader = this.getClass().getClassLoader();
- File file = new File(classLoader.getResource(fileName).getFile());
- content = new String(Files.readAllBytes(file.toPath()));
- }
- catch(Exception e) {
- e.printStackTrace();
- System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage());
- }
- return content;
- }
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ public void testUnmarshall() throws Exception {
+ String endpointsJson = getFileContentsAsString("__files/grm/endpoints.json");
+ ServiceEndPointList sel = mapper.readValue(endpointsJson, ServiceEndPointList.class);
+
+ List<ServiceEndPoint> list = sel.getServiceEndPointList();
+ ServiceEndPoint se = list.get(0);
+
+ assertEquals(3, list.size());
+ assertEquals("dummy.pod.ns.dummy-pod3", se.getName());
+ assertEquals(Integer.valueOf(1), Integer.valueOf(se.getVersion().getMajor()));
+ assertEquals(Integer.valueOf(0), Integer.valueOf(se.getVersion().getMinor()));
+ assertEquals(Integer.valueOf(0), Integer.valueOf(se.getVersion().getPatch()));
+ assertEquals("192.168.120.218", se.getHostAddress());
+ assertEquals("32004", se.getListenPort());
+ assertEquals("37.7022", se.getLatitude());
+ assertEquals("121.9358", se.getLongitude());
+ assertEquals("/", se.getContextPath());
+ assertEquals("edge", se.getOperationalInfo().getCreatedBy());
+ assertEquals("edge", se.getOperationalInfo().getUpdatedBy());
+ assertEquals("Environment", se.getProperties().get(0).getName());
+ assertEquals("DEV", se.getProperties().get(0).getValue());
+ }
+
+ @Test
+ public void testUnmarshallServiceEndpointListStartsWithUppercase() throws Exception {
+ String endpointsJson = getFileContentsAsString("__files/grm/endpoints2.json");
+ ServiceEndPointList sel = mapper.readValue(endpointsJson, ServiceEndPointList.class);
+
+ List<ServiceEndPoint> list = sel.getServiceEndPointList();
+ ServiceEndPoint se = list.get(0);
+
+ assertEquals(3, list.size());
+ assertEquals("dummy.pod.ns.dummy-pod3", se.getName());
+ assertEquals(Integer.valueOf(1), Integer.valueOf(se.getVersion().getMajor()));
+ assertEquals(Integer.valueOf(0), Integer.valueOf(se.getVersion().getMinor()));
+ assertEquals(Integer.valueOf(0), Integer.valueOf(se.getVersion().getPatch()));
+ assertEquals("192.168.120.218", se.getHostAddress());
+ assertEquals("32004", se.getListenPort());
+ assertEquals("37.7022", se.getLatitude());
+ assertEquals("121.9358", se.getLongitude());
+ assertEquals("/", se.getContextPath());
+ assertEquals("edge", se.getOperationalInfo().getCreatedBy());
+ assertEquals("edge", se.getOperationalInfo().getUpdatedBy());
+ assertEquals("Environment", se.getProperties().get(0).getName());
+ assertEquals("DEV", se.getProperties().get(0).getValue());
+ }
+
+ protected String getFileContentsAsString(String fileName) {
+
+ String content = "";
+ try {
+ ClassLoader classLoader = this.getClass().getClassLoader();
+ File file = new File(classLoader.getResource(fileName).getFile());
+ content = new String(Files.readAllBytes(file.toPath()));
+ } catch (Exception e) {
+ e.printStackTrace();
+ System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage());
+ }
+ return content;
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/grm/ServiceEndPointRequestTest.java b/common/src/test/java/org/onap/so/client/grm/ServiceEndPointRequestTest.java
index 4fe6bca05e..2c1a5ad5fa 100644
--- a/common/src/test/java/org/onap/so/client/grm/ServiceEndPointRequestTest.java
+++ b/common/src/test/java/org/onap/so/client/grm/ServiceEndPointRequestTest.java
@@ -29,62 +29,61 @@ import org.onap.so.client.grm.beans.Property;
import org.onap.so.client.grm.beans.ServiceEndPoint;
import org.onap.so.client.grm.beans.ServiceEndPointRequest;
import org.onap.so.client.grm.beans.Version;
-
import com.fasterxml.jackson.databind.ObjectMapper;
public class ServiceEndPointRequestTest {
- private ObjectMapper mapper = new ObjectMapper();
-
- @Test
- public void testMarshall() throws Exception {
-
- String expected =
- "{\"serviceEndPoint\":{\"name\":\"TEST.ECOMP_PSL.Inventory\",\"version\":{\"major\":1,\"minor\":0,\"patch\":\"0\"}," +
- "\"hostAddress\":\"127.0.0.1\",\"listenPort\":\"8080\",\"latitude\":\"37.7022\",\"longitude\":\"121.9358\"," +
- "\"contextPath\":\"/\",\"routeOffer\":\"TEST\",\"operationalInfo\":{\"createdBy\":\"edge\",\"updatedBy\":\"edge\"}," +
- "\"properties\":[{\"name\":\"Environment\",\"value\":\"TEST\"},{\"name\":\"cpfrun_cluster_name\"," +
- "\"value\":\"testcase_cluster_no_cluster\"}]},\"env\":\"DEV\"}";
-
- Version ver = new Version();
- ver.setMajor(1);
- ver.setMinor(0);
- ver.setPatch("0");
-
- ServiceEndPoint sep = new ServiceEndPoint();
- sep.setName("TEST.ECOMP_PSL.Inventory");
- sep.setVersion(ver);
- sep.setHostAddress("127.0.0.1");
- sep.setListenPort("8080");
- sep.setLatitude("37.7022");
- sep.setLongitude("121.9358");
- sep.setContextPath("/");
- sep.setRouteOffer("TEST");
-
- OperationalInfo operInfo = new OperationalInfo();
- operInfo.setCreatedBy("edge");
- operInfo.setUpdatedBy("edge");
-
- sep.setOperationalInfo(operInfo);
-
- Property prop1 = new Property();
- prop1.setName("Environment");
- prop1.setValue("TEST");
-
- Property prop2 = new Property();
- prop2.setName("cpfrun_cluster_name");
- prop2.setValue("testcase_cluster_no_cluster");
-
- List<Property> props = new ArrayList<Property>();
- props.add(prop1);
- props.add(prop2);
-
- sep.setProperties(props);
-
- ServiceEndPointRequest request = new ServiceEndPointRequest();
- request.setEnv("DEV");
- request.setServiceEndPoint(sep);
-
- assertEquals(expected, mapper.writeValueAsString(request));
- }
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ public void testMarshall() throws Exception {
+
+ String expected =
+ "{\"serviceEndPoint\":{\"name\":\"TEST.ECOMP_PSL.Inventory\",\"version\":{\"major\":1,\"minor\":0,\"patch\":\"0\"},"
+ + "\"hostAddress\":\"127.0.0.1\",\"listenPort\":\"8080\",\"latitude\":\"37.7022\",\"longitude\":\"121.9358\","
+ + "\"contextPath\":\"/\",\"routeOffer\":\"TEST\",\"operationalInfo\":{\"createdBy\":\"edge\",\"updatedBy\":\"edge\"},"
+ + "\"properties\":[{\"name\":\"Environment\",\"value\":\"TEST\"},{\"name\":\"cpfrun_cluster_name\","
+ + "\"value\":\"testcase_cluster_no_cluster\"}]},\"env\":\"DEV\"}";
+
+ Version ver = new Version();
+ ver.setMajor(1);
+ ver.setMinor(0);
+ ver.setPatch("0");
+
+ ServiceEndPoint sep = new ServiceEndPoint();
+ sep.setName("TEST.ECOMP_PSL.Inventory");
+ sep.setVersion(ver);
+ sep.setHostAddress("127.0.0.1");
+ sep.setListenPort("8080");
+ sep.setLatitude("37.7022");
+ sep.setLongitude("121.9358");
+ sep.setContextPath("/");
+ sep.setRouteOffer("TEST");
+
+ OperationalInfo operInfo = new OperationalInfo();
+ operInfo.setCreatedBy("edge");
+ operInfo.setUpdatedBy("edge");
+
+ sep.setOperationalInfo(operInfo);
+
+ Property prop1 = new Property();
+ prop1.setName("Environment");
+ prop1.setValue("TEST");
+
+ Property prop2 = new Property();
+ prop2.setName("cpfrun_cluster_name");
+ prop2.setValue("testcase_cluster_no_cluster");
+
+ List<Property> props = new ArrayList<Property>();
+ props.add(prop1);
+ props.add(prop2);
+
+ sep.setProperties(props);
+
+ ServiceEndPointRequest request = new ServiceEndPointRequest();
+ request.setEnv("DEV");
+ request.setServiceEndPoint(sep);
+
+ assertEquals(expected, mapper.writeValueAsString(request));
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/grm/exception/GRMClientCallFailedTest.java b/common/src/test/java/org/onap/so/client/grm/exception/GRMClientCallFailedTest.java
index 989a753800..0dfd55c0b4 100644
--- a/common/src/test/java/org/onap/so/client/grm/exception/GRMClientCallFailedTest.java
+++ b/common/src/test/java/org/onap/so/client/grm/exception/GRMClientCallFailedTest.java
@@ -20,7 +20,6 @@
package org.onap.so.client.grm.exception;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.client.grm.exceptions.GRMClientCallFailed;
diff --git a/common/src/test/java/org/onap/so/client/policy/PolicyClientImplTest.java b/common/src/test/java/org/onap/so/client/policy/PolicyClientImplTest.java
index 46f9de2268..ad22c65248 100644
--- a/common/src/test/java/org/onap/so/client/policy/PolicyClientImplTest.java
+++ b/common/src/test/java/org/onap/so/client/policy/PolicyClientImplTest.java
@@ -26,12 +26,10 @@ import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.ArgumentMatchers.any;
-
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
-
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
@@ -43,7 +41,6 @@ import org.onap.so.client.policy.entities.DictionaryData;
import org.onap.so.client.policy.entities.PolicyConfig;
import org.onap.so.client.policy.entities.PolicyDecision;
import org.onap.so.client.policy.entities.PolicyServiceType;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -52,99 +49,101 @@ import com.fasterxml.jackson.databind.SerializationFeature;
public class PolicyClientImplTest {
- @BeforeClass
- public static void setUp() {
- System.setProperty("mso.config.path", "src/test/resources");
- }
-
- private static String RESOURCE_PATH = "src/test/resources/__files/Policy/";
-
- @Test
- public void successReadProperties() {
- PolicyRestClient client = new PolicyRestClient(new PolicyRestPropertiesImpl(), PolicyServiceType.GET_DECISION);
- Map<String, String> map = new HashMap<>();
- client.initializeHeaderMap(map);
- assertEquals("Found expected Client Auth", "Basic bTAzNzQzOnBvbGljeVIwY2sk", map.get("ClientAuth"));
- assertEquals("Found expected Authorization", "Basic dGVzdHBkcDphbHBoYTEyMw==", map.get("Authorization"));
- assertEquals("Found expected Environment", "TEST", map.get("Environment"));
- }
-
- @Test
- @Ignore
- public void getDecisionTest() {
- PolicyClient client = new PolicyClientImpl();
- PolicyDecision decision = client.getDecision("S", "V", "BB1", "1", "123");
- assertEquals("Decision is correct", decision.getDecision(), "PERMIT");
- assertEquals("Decision details is correct", decision.getDetails(), "Retry");
- }
-
- @Test
- @Ignore
- public void getAllowedTreatmentsTest() {
- PolicyClient client = new PolicyClientImpl();
- DictionaryData dictClient = client.getAllowedTreatments("BB1", "1");
- final String dictBbidString = dictClient.getBbid().getString();
- final String dictWorkStepString = dictClient.getWorkstep().getString();
- assertEquals("DictionaryData matches a response Bbid", dictBbidString, "BB1");
- assertEquals("DicitonaryData matches a response WorkStep", dictWorkStepString, "1");
- }
-
- @Test
- public void getDecisionMockTest() {
- String serviceType = "S";
- String vnfType = "V";
- String bbID = "BB1";
- String workStep = "1";
- String errorCode = "123";
-
- PolicyDecision expected = new PolicyDecision();
- expected.setDecision("PERMIT");
- expected.setDetails("Retry");
-
- DecisionAttributes decisionAttributes = new DecisionAttributes();
- decisionAttributes.setServiceType(serviceType);
- decisionAttributes.setVNFType(vnfType);
- decisionAttributes.setBBID(bbID);
- decisionAttributes.setWorkStep(workStep);
- decisionAttributes.setErrorCode(errorCode);
- PolicyClient client = Mockito.spy(PolicyClientImpl.class);
-
- doReturn(expected).when(client).getDecision(serviceType, vnfType, bbID, workStep, errorCode);
-
- PolicyDecision actual = client.getDecision(serviceType, vnfType, bbID, workStep, errorCode);
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void getConfigFromStringJsonTest() throws JsonParseException, JsonMappingException, IOException {
- PolicyClientImpl client = new PolicyClientImpl();
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
- mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
- Config expected = mapper.readValue(new File(RESOURCE_PATH + "configJson.json"), Config.class);
- PolicyConfig[] returnedPolicyConfigList = mapper.readValue(new File(RESOURCE_PATH + "policyConfig.json"), PolicyConfig[].class);
- String configJson = returnedPolicyConfigList[0].getConfig();
- Config actual = client.getConfigFromStringJson(configJson);
-
- assertThat(actual, sameBeanAs(expected));
- }
-
- @Test
- public void getConfigWithPolicyNameTest() throws JsonParseException, JsonMappingException, IOException {
- PolicyClientImpl client = Mockito.spy(PolicyClientImpl.class);
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
- mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
- PolicyConfig[] returnedPolicyConfigList = mapper.readValue(new File(RESOURCE_PATH + "policyConfig.json"), PolicyConfig[].class);
- Config expected = mapper.readValue(new File(RESOURCE_PATH + "configJson.json"), Config.class);
-
- PolicyRestClient mockedClient = Mockito.mock(PolicyRestClient.class);
- doReturn(mockedClient).when(client).getPolicyRestClient(PolicyServiceType.GET_CONFIG);
- doReturn(returnedPolicyConfigList).when(mockedClient).post(isA(ConfigRequestParameters.class), any());
-
- Config actual = client.getConfigWithPolicyName("policyName");
-
- assertThat(actual, sameBeanAs(expected));
-
- }
+ @BeforeClass
+ public static void setUp() {
+ System.setProperty("mso.config.path", "src/test/resources");
+ }
+
+ private static String RESOURCE_PATH = "src/test/resources/__files/Policy/";
+
+ @Test
+ public void successReadProperties() {
+ PolicyRestClient client = new PolicyRestClient(new PolicyRestPropertiesImpl(), PolicyServiceType.GET_DECISION);
+ Map<String, String> map = new HashMap<>();
+ client.initializeHeaderMap(map);
+ assertEquals("Found expected Client Auth", "Basic bTAzNzQzOnBvbGljeVIwY2sk", map.get("ClientAuth"));
+ assertEquals("Found expected Authorization", "Basic dGVzdHBkcDphbHBoYTEyMw==", map.get("Authorization"));
+ assertEquals("Found expected Environment", "TEST", map.get("Environment"));
+ }
+
+ @Test
+ @Ignore
+ public void getDecisionTest() {
+ PolicyClient client = new PolicyClientImpl();
+ PolicyDecision decision = client.getDecision("S", "V", "BB1", "1", "123");
+ assertEquals("Decision is correct", decision.getDecision(), "PERMIT");
+ assertEquals("Decision details is correct", decision.getDetails(), "Retry");
+ }
+
+ @Test
+ @Ignore
+ public void getAllowedTreatmentsTest() {
+ PolicyClient client = new PolicyClientImpl();
+ DictionaryData dictClient = client.getAllowedTreatments("BB1", "1");
+ final String dictBbidString = dictClient.getBbid().getString();
+ final String dictWorkStepString = dictClient.getWorkstep().getString();
+ assertEquals("DictionaryData matches a response Bbid", dictBbidString, "BB1");
+ assertEquals("DicitonaryData matches a response WorkStep", dictWorkStepString, "1");
+ }
+
+ @Test
+ public void getDecisionMockTest() {
+ String serviceType = "S";
+ String vnfType = "V";
+ String bbID = "BB1";
+ String workStep = "1";
+ String errorCode = "123";
+
+ PolicyDecision expected = new PolicyDecision();
+ expected.setDecision("PERMIT");
+ expected.setDetails("Retry");
+
+ DecisionAttributes decisionAttributes = new DecisionAttributes();
+ decisionAttributes.setServiceType(serviceType);
+ decisionAttributes.setVNFType(vnfType);
+ decisionAttributes.setBBID(bbID);
+ decisionAttributes.setWorkStep(workStep);
+ decisionAttributes.setErrorCode(errorCode);
+ PolicyClient client = Mockito.spy(PolicyClientImpl.class);
+
+ doReturn(expected).when(client).getDecision(serviceType, vnfType, bbID, workStep, errorCode);
+
+ PolicyDecision actual = client.getDecision(serviceType, vnfType, bbID, workStep, errorCode);
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void getConfigFromStringJsonTest() throws JsonParseException, JsonMappingException, IOException {
+ PolicyClientImpl client = new PolicyClientImpl();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
+ mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
+ Config expected = mapper.readValue(new File(RESOURCE_PATH + "configJson.json"), Config.class);
+ PolicyConfig[] returnedPolicyConfigList =
+ mapper.readValue(new File(RESOURCE_PATH + "policyConfig.json"), PolicyConfig[].class);
+ String configJson = returnedPolicyConfigList[0].getConfig();
+ Config actual = client.getConfigFromStringJson(configJson);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void getConfigWithPolicyNameTest() throws JsonParseException, JsonMappingException, IOException {
+ PolicyClientImpl client = Mockito.spy(PolicyClientImpl.class);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
+ mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
+ PolicyConfig[] returnedPolicyConfigList =
+ mapper.readValue(new File(RESOURCE_PATH + "policyConfig.json"), PolicyConfig[].class);
+ Config expected = mapper.readValue(new File(RESOURCE_PATH + "configJson.json"), Config.class);
+
+ PolicyRestClient mockedClient = Mockito.mock(PolicyRestClient.class);
+ doReturn(mockedClient).when(client).getPolicyRestClient(PolicyServiceType.GET_CONFIG);
+ doReturn(returnedPolicyConfigList).when(mockedClient).post(isA(ConfigRequestParameters.class), any());
+
+ Config actual = client.getConfigWithPolicyName("policyName");
+
+ assertThat(actual, sameBeanAs(expected));
+
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/policy/entities/PolicyEntitiesTest.java b/common/src/test/java/org/onap/so/client/policy/entities/PolicyEntitiesTest.java
index 2796affa49..9d03fb9643 100644
--- a/common/src/test/java/org/onap/so/client/policy/entities/PolicyEntitiesTest.java
+++ b/common/src/test/java/org/onap/so/client/policy/entities/PolicyEntitiesTest.java
@@ -21,7 +21,6 @@
package org.onap.so.client.policy.entities;
import org.junit.Test;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterEnum;
@@ -35,25 +34,22 @@ import com.openpojo.validation.test.impl.SetterTester;
public class PolicyEntitiesTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.client.policy.entities");
+ }
- @Test
- public void pojoStructure() {
- test("org.onap.so.client.policy.entities");
- }
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule())
+ .with(new SetterTester()).with(new GetterTester()).build();
+ validator.validate(pojoPackage, new FilterPackageInfo(), new FilterEnum(), filterTestClasses);
+ }
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterMustExistRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
- validator.validate(pojoPackage, new FilterPackageInfo(), new FilterEnum(), filterTestClasses);
- }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/ruby/RubyCheckClientTest.java b/common/src/test/java/org/onap/so/client/ruby/RubyCheckClientTest.java
index ba8772b05c..1ca8942ac1 100644
--- a/common/src/test/java/org/onap/so/client/ruby/RubyCheckClientTest.java
+++ b/common/src/test/java/org/onap/so/client/ruby/RubyCheckClientTest.java
@@ -24,83 +24,78 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.time.format.DateTimeFormatter;
-
import org.junit.Test;
import org.onap.so.client.ruby.beans.Ruby;
-
import static org.apache.commons.lang3.StringUtils.*;
import com.fasterxml.jackson.databind.ObjectMapper;
public class RubyCheckClientTest {
- private final String fileLocation = "src/test/resources/org/onap/so/client/ruby/create-ticket/";
- private static final String REQUEST_ID = "abc123";
- private static final String SOURCE_NAME = "source-name";
- private static final String TIME = "test-time";
- private static final String REASON = "reason";
- private static final String WORK_FLOW_ID = "work-flow-Id";
- private static final String NOTIFICATION = "notification";
-
+ private final String fileLocation = "src/test/resources/org/onap/so/client/ruby/create-ticket/";
+ private static final String REQUEST_ID = "abc123";
+ private static final String SOURCE_NAME = "source-name";
+ private static final String TIME = "test-time";
+ private static final String REASON = "reason";
+ private static final String WORK_FLOW_ID = "work-flow-Id";
+ private static final String NOTIFICATION = "notification";
+
+
+
+ @Test
+ public void verifyRubyCreateTicketRequest() throws IOException, ParseException {
+ String content = this.getJson("create-ticket-request.json");
+ ObjectMapper mapper = new ObjectMapper();
+ Ruby expected = mapper.readValue(content, Ruby.class);
+ RubyClient client = new RubyClient();
+ RubyClient spy = spy(client);
+ when(spy.getTime()).thenReturn(TIME);
+ String actual = spy.buildRequest(REQUEST_ID, SOURCE_NAME, REASON, WORK_FLOW_ID, NOTIFICATION);
+ assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual);
+ }
+
+
+ @Test
+ public void verifyTimeFormat() {
+ RubyClient client = new RubyClient();
+ String time = client.getTime();
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z");
+ formatter.parse(time);
+ }
+
+
+ @Test
+ public void verifyReasonCharLimit() throws IOException {
+ final String reasonLong = repeat("*", 256);
+ RubyClient client = new RubyClient();
+ try {
+ client.buildRequest(REQUEST_ID, SOURCE_NAME, reasonLong, WORK_FLOW_ID, NOTIFICATION);
+ fail("Should have thrown IllegalArgumentException but did not!");
+ } catch (final IllegalArgumentException e) {
+ final String msg = "reason exceeds 255 characters";
+ assertEquals(msg, e.getMessage());
+ }
+ }
+
+ @Test
+ public void verifyNotificationCharLimit() throws IOException {
+ final String notificationLong = repeat("*", 1025);
+ RubyClient client = new RubyClient();
+ try {
+ client.buildRequest(REQUEST_ID, SOURCE_NAME, REASON, WORK_FLOW_ID, notificationLong);
+ fail("Should have thrown IllegalArgumentException but did not!");
+ } catch (final IllegalArgumentException e) {
+ final String msg = "notification exceeds 1024 characters";
+ assertEquals(msg, e.getMessage());
+ }
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(fileLocation + filename)));
+ }
-
- @Test
- public void verifyRubyCreateTicketRequest() throws IOException, ParseException{
- String content = this.getJson("create-ticket-request.json");
- ObjectMapper mapper = new ObjectMapper();
- Ruby expected = mapper.readValue(content, Ruby.class);
- RubyClient client = new RubyClient();
- RubyClient spy = spy(client);
- when(spy.getTime()).thenReturn(TIME);
- String actual = spy.buildRequest(REQUEST_ID, SOURCE_NAME, REASON, WORK_FLOW_ID, NOTIFICATION);
- assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual);
- }
-
-
- @Test
- public void verifyTimeFormat() {
- RubyClient client = new RubyClient();
- String time = client.getTime();
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z");
- formatter.parse(time);
- }
-
-
- @Test
- public void verifyReasonCharLimit() throws IOException{
- final String reasonLong = repeat("*", 256);
- RubyClient client = new RubyClient();
- try{
- client.buildRequest(REQUEST_ID, SOURCE_NAME, reasonLong, WORK_FLOW_ID, NOTIFICATION);
- fail("Should have thrown IllegalArgumentException but did not!");
- }
- catch(final IllegalArgumentException e){
- final String msg = "reason exceeds 255 characters";
- assertEquals(msg, e.getMessage());
- }
- }
-
- @Test
- public void verifyNotificationCharLimit() throws IOException{
- final String notificationLong = repeat("*", 1025);
- RubyClient client = new RubyClient();
- try{
- client.buildRequest(REQUEST_ID, SOURCE_NAME, REASON, WORK_FLOW_ID, notificationLong);
- fail("Should have thrown IllegalArgumentException but did not!");
- }
- catch(final IllegalArgumentException e){
- final String msg = "notification exceeds 1024 characters";
- assertEquals(msg, e.getMessage());
- }
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get(fileLocation + filename)));
- }
-
}
-
+
diff --git a/common/src/test/java/org/onap/so/client/ruby/beans/RubyBeansTest.java b/common/src/test/java/org/onap/so/client/ruby/beans/RubyBeansTest.java
index eb142be4c6..ca80930468 100644
--- a/common/src/test/java/org/onap/so/client/ruby/beans/RubyBeansTest.java
+++ b/common/src/test/java/org/onap/so/client/ruby/beans/RubyBeansTest.java
@@ -21,7 +21,6 @@
package org.onap.so.client.ruby.beans;
import org.junit.Test;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterEnum;
@@ -35,25 +34,22 @@ import com.openpojo.validation.test.impl.SetterTester;
public class RubyBeansTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.client.ruby.beans");
+ }
- @Test
- public void pojoStructure() {
- test("org.onap.so.client.ruby.beans");
- }
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule())
+ .with(new SetterTester()).with(new GetterTester()).build();
+ validator.validate(pojoPackage, new FilterPackageInfo(), new FilterEnum(), filterTestClasses);
+ }
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterMustExistRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
- validator.validate(pojoPackage, new FilterPackageInfo(), new FilterEnum(), filterTestClasses);
- }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/sdno/SDNOHealthCheckClientTest.java b/common/src/test/java/org/onap/so/client/sdno/SDNOHealthCheckClientTest.java
index 4887aed522..750e578558 100644
--- a/common/src/test/java/org/onap/so/client/sdno/SDNOHealthCheckClientTest.java
+++ b/common/src/test/java/org/onap/so/client/sdno/SDNOHealthCheckClientTest.java
@@ -21,74 +21,74 @@
package org.onap.so.client.sdno;
import static org.junit.Assert.assertEquals;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
-
import org.junit.Test;
import org.onap.so.client.sdno.beans.SDNO;
-
import com.fasterxml.jackson.databind.ObjectMapper;
public class SDNOHealthCheckClientTest {
-
-
- private final String fileLocation = "src/test/resources/org/onap/so/client/sdno/health-check/";
- private static final String userId = "test-user";
- private static final Optional<String> clliCode = Optional.of("test-clli");
- private static final String requestId = "test-request-id";
- private static final String configurationId = "test-configuration-id";
- private static final String interfaceId = "test-interface-id";
-
- @Test
- public void verfyLPortMirrorPreCheckRequest() throws IOException{
- String content = this.getJson("custom-lport-mirror-pre-check-request.json");
- ObjectMapper mapper = new ObjectMapper();
- SDNO expected = mapper.readValue(content, SDNO.class);
- SDNOHealthCheckClient client = new SDNOHealthCheckClient();
- String actual = client.buildLPortMirrorCheckPreRequest(userId, requestId, clliCode, configurationId, interfaceId);
- assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual);
- }
-
- @Test
- public void verfyLPortMirrorPostCheckRequest() throws IOException{
- String content = this.getJson("custom-lport-mirror-post-check-request.json");
- ObjectMapper mapper = new ObjectMapper();
- SDNO expected = mapper.readValue(content, SDNO.class);
- SDNOHealthCheckClient client = new SDNOHealthCheckClient();
- String actual = client.buildLPortMirrorCheckPostRequest(userId, requestId, clliCode, configurationId, interfaceId);
- assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual);
- }
-
-
- @Test
- public void verifyPortMirrorPostCheckRequest() throws IOException{
- String content = this.getJson("custom-port-mirror-post-check-request.json");
- ObjectMapper mapper = new ObjectMapper();
- SDNO expected = mapper.readValue(content, SDNO.class);
- SDNOHealthCheckClient client = new SDNOHealthCheckClient();
- String actual = client.buildPortMirrorPostCheckRequest(userId, requestId, clliCode, configurationId);
-
- assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual);
-
- }
- @Test
- public void verifyPortMirrorPreCheckRequest() throws IOException {
- String content = this.getJson("custom-port-mirror-pre-check-request.json");
- ObjectMapper mapper = new ObjectMapper();
- SDNO expected = mapper.readValue(content, SDNO.class);
- SDNOHealthCheckClient client = new SDNOHealthCheckClient();
- String actual = client.buildPortMirrorPreCheckRequest(userId, requestId, clliCode, configurationId);
-
- assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual);
-
- }
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get(fileLocation + filename)));
- }
-
+
+
+ private final String fileLocation = "src/test/resources/org/onap/so/client/sdno/health-check/";
+ private static final String userId = "test-user";
+ private static final Optional<String> clliCode = Optional.of("test-clli");
+ private static final String requestId = "test-request-id";
+ private static final String configurationId = "test-configuration-id";
+ private static final String interfaceId = "test-interface-id";
+
+ @Test
+ public void verfyLPortMirrorPreCheckRequest() throws IOException {
+ String content = this.getJson("custom-lport-mirror-pre-check-request.json");
+ ObjectMapper mapper = new ObjectMapper();
+ SDNO expected = mapper.readValue(content, SDNO.class);
+ SDNOHealthCheckClient client = new SDNOHealthCheckClient();
+ String actual =
+ client.buildLPortMirrorCheckPreRequest(userId, requestId, clliCode, configurationId, interfaceId);
+ assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual);
+ }
+
+ @Test
+ public void verfyLPortMirrorPostCheckRequest() throws IOException {
+ String content = this.getJson("custom-lport-mirror-post-check-request.json");
+ ObjectMapper mapper = new ObjectMapper();
+ SDNO expected = mapper.readValue(content, SDNO.class);
+ SDNOHealthCheckClient client = new SDNOHealthCheckClient();
+ String actual =
+ client.buildLPortMirrorCheckPostRequest(userId, requestId, clliCode, configurationId, interfaceId);
+ assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual);
+ }
+
+
+ @Test
+ public void verifyPortMirrorPostCheckRequest() throws IOException {
+ String content = this.getJson("custom-port-mirror-post-check-request.json");
+ ObjectMapper mapper = new ObjectMapper();
+ SDNO expected = mapper.readValue(content, SDNO.class);
+ SDNOHealthCheckClient client = new SDNOHealthCheckClient();
+ String actual = client.buildPortMirrorPostCheckRequest(userId, requestId, clliCode, configurationId);
+
+ assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual);
+
+ }
+
+ @Test
+ public void verifyPortMirrorPreCheckRequest() throws IOException {
+ String content = this.getJson("custom-port-mirror-pre-check-request.json");
+ ObjectMapper mapper = new ObjectMapper();
+ SDNO expected = mapper.readValue(content, SDNO.class);
+ SDNOHealthCheckClient client = new SDNOHealthCheckClient();
+ String actual = client.buildPortMirrorPreCheckRequest(userId, requestId, clliCode, configurationId);
+
+ assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual);
+
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(fileLocation + filename)));
+ }
+
}
diff --git a/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorImplTest.java b/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorImplTest.java
index 79ce196bd3..c2278c26f9 100644
--- a/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorImplTest.java
+++ b/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorImplTest.java
@@ -22,7 +22,6 @@ package org.onap.so.client.sdno;
import static org.junit.Assert.assertEquals;
import java.util.UUID;
-
import org.junit.Test;
import org.onap.aai.domain.yang.GenericVnf;
import org.onap.so.client.sdno.beans.RequestHealthDiagnostic;
@@ -30,28 +29,28 @@ import org.onap.so.client.sdno.beans.SDNO;
public class SDNOValidatorImplTest {
- @Test
- public void buildRequestDiagnosticTest() throws Exception {
- SDNOValidatorImpl validator = new SDNOValidatorImpl();
- UUID uuid = UUID.randomUUID();
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfName("VNFNAME");
- vnf.setVnfId("test");
- vnf.setIpv4OamAddress("1.2.3.4");
- vnf.setNfRole("VPE");
- SDNO request = validator.buildRequestDiagnostic(vnf, uuid, "mechid");
- assertEquals(request.getNodeType(), "VPE");
- assertEquals(request.getOperation(), "health-diagnostic");
-
- RequestHealthDiagnostic innerRequest = request.getBody().getInput().getRequestHealthDiagnostic();
- assertEquals(innerRequest.getRequestClientName(), "MSO");
- assertEquals(innerRequest.getRequestNodeName(), "VNFNAME");
- assertEquals(innerRequest.getRequestNodeUuid(), "test");
- assertEquals(innerRequest.getRequestNodeType(), "VPE");
- assertEquals(innerRequest.getRequestNodeIp(), "1.2.3.4");
- assertEquals(innerRequest.getRequestUserId(), "mechid");
- assertEquals(innerRequest.getRequestId(), uuid.toString());
- assertEquals(innerRequest.getHealthDiagnosticCode(), "default");
+ @Test
+ public void buildRequestDiagnosticTest() throws Exception {
+ SDNOValidatorImpl validator = new SDNOValidatorImpl();
+ UUID uuid = UUID.randomUUID();
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfName("VNFNAME");
+ vnf.setVnfId("test");
+ vnf.setIpv4OamAddress("1.2.3.4");
+ vnf.setNfRole("VPE");
+ SDNO request = validator.buildRequestDiagnostic(vnf, uuid, "mechid");
+ assertEquals(request.getNodeType(), "VPE");
+ assertEquals(request.getOperation(), "health-diagnostic");
+
+ RequestHealthDiagnostic innerRequest = request.getBody().getInput().getRequestHealthDiagnostic();
+ assertEquals(innerRequest.getRequestClientName(), "MSO");
+ assertEquals(innerRequest.getRequestNodeName(), "VNFNAME");
+ assertEquals(innerRequest.getRequestNodeUuid(), "test");
+ assertEquals(innerRequest.getRequestNodeType(), "VPE");
+ assertEquals(innerRequest.getRequestNodeIp(), "1.2.3.4");
+ assertEquals(innerRequest.getRequestUserId(), "mechid");
+ assertEquals(innerRequest.getRequestId(), uuid.toString());
+ assertEquals(innerRequest.getHealthDiagnosticCode(), "default");
- }
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorTest.java b/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorTest.java
index 9794c9b622..18b9be0983 100644
--- a/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorTest.java
+++ b/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorTest.java
@@ -25,13 +25,11 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.UUID;
-
import org.hamcrest.core.StringContains;
import org.junit.Before;
import org.junit.Ignore;
@@ -47,70 +45,76 @@ import org.onap.so.client.dmaap.exceptions.DMaaPConsumerFailure;
import org.onap.so.client.exceptions.SDNOException;
import org.onap.so.client.sdno.beans.SDNO;
import org.onap.so.client.sdno.dmaap.SDNOHealthCheckDmaapConsumer;
-
import com.fasterxml.jackson.databind.ObjectMapper;
public class SDNOValidatorTest {
-
- @Mock private Consumer mrConsumer;
- @Spy private SDNOHealthCheckDmaapConsumer dmaapConsumer;
- private final String fileLocation = "src/test/resources/org/onap/so/client/sdno/";
- private final String uuid = "xyz123";
- @Rule public ExpectedException thrown = ExpectedException.none();
-
- @Before
- public void setUpTests() {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void success() throws IOException, Exception {
- when(dmaapConsumer.getConsumer()).thenReturn(mrConsumer);
- when(mrConsumer.fetch()).thenReturn(Arrays.asList(new String[]{getJson("response.json"), getJson("output-success.json")}));
-
- SDNOValidatorImpl validator = new SDNOValidatorImpl();
- SDNOValidatorImpl spy = spy(validator);
- when(dmaapConsumer.getRequestId()).thenReturn("xyz123");
- doReturn(dmaapConsumer).when(spy).getConsumer(any(String.class));
- boolean result = spy.pollForResponse("xyz123");
- assertEquals("result is true", result, true);
- }
-
- @Test
- public void failure() throws IOException, Exception {
- when(dmaapConsumer.getConsumer()).thenReturn(mrConsumer);
- when(mrConsumer.fetch()).thenReturn(Arrays.asList(new String[]{getJson("response.json"), getJson("output-failure.json")}));
-
- SDNOValidatorImpl validator = new SDNOValidatorImpl();
- SDNOValidatorImpl spy = spy(validator);
- when(dmaapConsumer.getRequestId()).thenReturn("xyz123");
- doReturn(dmaapConsumer).when(spy).getConsumer(any(String.class));
- thrown.expect(SDNOException.class);
- thrown.expectMessage(new StringContains("my error message"));
- boolean result = spy.pollForResponse("xyz123");
-
- }
- @Ignore
- @Test
- public void run() throws Exception {
- SDNOValidatorImpl validator = new SDNOValidatorImpl();
- UUID uuid = UUID.randomUUID();
- GenericVnf vnf = new GenericVnf();
- vnf.setVnfId("test");
- vnf.setIpv4OamAddress("1.2.3.4");
- vnf.setNfRole("VPE");
- SDNO request = validator.buildRequestDiagnostic(vnf, uuid, "mechid");
- ObjectMapper mapper = new ObjectMapper();
- String json = mapper.writeValueAsString(request);
- validator.submitRequest(json);
- thrown.expect(DMaaPConsumerFailure.class);
- boolean result = validator.pollForResponse(uuid.toString());
- System.out.println(json);
- }
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get(fileLocation + filename)));
- }
+ @Mock
+ private Consumer mrConsumer;
+ @Spy
+ private SDNOHealthCheckDmaapConsumer dmaapConsumer;
+ private final String fileLocation = "src/test/resources/org/onap/so/client/sdno/";
+ private final String uuid = "xyz123";
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Before
+ public void setUpTests() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void success() throws IOException, Exception {
+ when(dmaapConsumer.getConsumer()).thenReturn(mrConsumer);
+ when(mrConsumer.fetch())
+ .thenReturn(Arrays.asList(new String[] {getJson("response.json"), getJson("output-success.json")}));
+
+ SDNOValidatorImpl validator = new SDNOValidatorImpl();
+ SDNOValidatorImpl spy = spy(validator);
+ when(dmaapConsumer.getRequestId()).thenReturn("xyz123");
+ doReturn(dmaapConsumer).when(spy).getConsumer(any(String.class));
+ boolean result = spy.pollForResponse("xyz123");
+ assertEquals("result is true", result, true);
+ }
+
+ @Test
+ public void failure() throws IOException, Exception {
+ when(dmaapConsumer.getConsumer()).thenReturn(mrConsumer);
+ when(mrConsumer.fetch())
+ .thenReturn(Arrays.asList(new String[] {getJson("response.json"), getJson("output-failure.json")}));
+
+ SDNOValidatorImpl validator = new SDNOValidatorImpl();
+ SDNOValidatorImpl spy = spy(validator);
+ when(dmaapConsumer.getRequestId()).thenReturn("xyz123");
+ doReturn(dmaapConsumer).when(spy).getConsumer(any(String.class));
+ thrown.expect(SDNOException.class);
+ thrown.expectMessage(new StringContains("my error message"));
+ boolean result = spy.pollForResponse("xyz123");
+
+ }
+
+ @Ignore
+ @Test
+ public void run() throws Exception {
+ SDNOValidatorImpl validator = new SDNOValidatorImpl();
+ UUID uuid = UUID.randomUUID();
+ GenericVnf vnf = new GenericVnf();
+ vnf.setVnfId("test");
+ vnf.setIpv4OamAddress("1.2.3.4");
+ vnf.setNfRole("VPE");
+ SDNO request = validator.buildRequestDiagnostic(vnf, uuid, "mechid");
+ ObjectMapper mapper = new ObjectMapper();
+ String json = mapper.writeValueAsString(request);
+ validator.submitRequest(json);
+ thrown.expect(DMaaPConsumerFailure.class);
+ boolean result = validator.pollForResponse(uuid.toString());
+ System.out.println(json);
+
+ }
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(fileLocation + filename)));
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/sdno/beans/SdnoBeansTest.java b/common/src/test/java/org/onap/so/client/sdno/beans/SdnoBeansTest.java
index bdfefd028c..6f33c490f6 100644
--- a/common/src/test/java/org/onap/so/client/sdno/beans/SdnoBeansTest.java
+++ b/common/src/test/java/org/onap/so/client/sdno/beans/SdnoBeansTest.java
@@ -21,7 +21,6 @@
package org.onap.so.client.sdno.beans;
import org.junit.Test;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterEnum;
@@ -35,25 +34,22 @@ import com.openpojo.validation.test.impl.SetterTester;
public class SdnoBeansTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.client.sdno.beans");
+ }
- @Test
- public void pojoStructure() {
- test("org.onap.so.client.sdno.beans");
- }
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule())
+ .with(new SetterTester()).with(new GetterTester()).build();
+ validator.validate(pojoPackage, new FilterPackageInfo(), new FilterEnum(), filterTestClasses);
+ }
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterMustExistRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
- validator.validate(pojoPackage, new FilterPackageInfo(), new FilterEnum(), filterTestClasses);
- }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/common/src/test/java/org/onap/so/configuration/rest/BasicHttpHeadersProviderTest.java b/common/src/test/java/org/onap/so/configuration/rest/BasicHttpHeadersProviderTest.java
index 3e762cfbe7..cab39824b0 100644
--- a/common/src/test/java/org/onap/so/configuration/rest/BasicHttpHeadersProviderTest.java
+++ b/common/src/test/java/org/onap/so/configuration/rest/BasicHttpHeadersProviderTest.java
@@ -23,9 +23,7 @@ package org.onap.so.configuration.rest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.onap.so.configuration.rest.BasicHttpHeadersProvider.AUTHORIZATION_HEADER;
-
import java.util.Arrays;
-
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
diff --git a/common/src/test/java/org/onap/so/configuration/rest/HttpComponentsClientConfigurationTest.java b/common/src/test/java/org/onap/so/configuration/rest/HttpComponentsClientConfigurationTest.java
index 5084acc934..4b054ff7d1 100644
--- a/common/src/test/java/org/onap/so/configuration/rest/HttpComponentsClientConfigurationTest.java
+++ b/common/src/test/java/org/onap/so/configuration/rest/HttpComponentsClientConfigurationTest.java
@@ -21,7 +21,6 @@
package org.onap.so.configuration.rest;
import static org.junit.Assert.assertNotNull;
-
import org.junit.Test;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
diff --git a/common/src/test/java/org/onap/so/constants/DefaultsTest.java b/common/src/test/java/org/onap/so/constants/DefaultsTest.java
index 6383d0ea4c..11ecc96c36 100644
--- a/common/src/test/java/org/onap/so/constants/DefaultsTest.java
+++ b/common/src/test/java/org/onap/so/constants/DefaultsTest.java
@@ -21,7 +21,6 @@
package org.onap.so.constants;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
@@ -38,9 +37,9 @@ import org.springframework.test.context.junit4.SpringRunner;
@Category(SpringAware.class)
public class DefaultsTest {
- @Test
- public void checkValue() {
-
- assertEquals("my-custom-owner", Defaults.CLOUD_OWNER.toString());
- }
+ @Test
+ public void checkValue() {
+
+ assertEquals("my-custom-owner", Defaults.CLOUD_OWNER.toString());
+ }
}
diff --git a/common/src/test/java/org/onap/so/entity/MsoRequestTest.java b/common/src/test/java/org/onap/so/entity/MsoRequestTest.java
index 73b5c7ea2d..1561f67b3a 100644
--- a/common/src/test/java/org/onap/so/entity/MsoRequestTest.java
+++ b/common/src/test/java/org/onap/so/entity/MsoRequestTest.java
@@ -23,7 +23,6 @@ package org.onap.so.entity;
import org.junit.Test;
import org.onap.so.openpojo.rules.HasToStringRule;
import org.onap.so.openpojo.rules.ToStringTester;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterEnum;
@@ -46,14 +45,11 @@ public class MsoRequestTest {
}
private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterMustExistRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule())
+ .with(new SetterTester()).with(new GetterTester()).build();
validator.validate(pojoPackage, new FilterPackageInfo(), new FilterEnum(), filterTestClasses);
}
+
private static class FilterTestClasses implements PojoClassFilter {
public boolean include(PojoClass pojoClass) {
return !pojoClass.getSourcePath().contains("/test-classes/");
diff --git a/common/src/test/java/org/onap/so/exceptions/ValidationExceptionTest.java b/common/src/test/java/org/onap/so/exceptions/ValidationExceptionTest.java
index 27fb584b3b..c72f3f63f3 100644
--- a/common/src/test/java/org/onap/so/exceptions/ValidationExceptionTest.java
+++ b/common/src/test/java/org/onap/so/exceptions/ValidationExceptionTest.java
@@ -28,25 +28,25 @@ import org.junit.Test;
*/
public class ValidationExceptionTest {
@Test
- public void validationExceptionOverrideMessageFalse(){
+ public void validationExceptionOverrideMessageFalse() {
ValidationException e = new ValidationException("testMessage", false);
Assert.assertEquals("testMessage", e.getMessage());
}
@Test
- public void validationExceptionOverrideMessageTrue(){
+ public void validationExceptionOverrideMessageTrue() {
ValidationException e = new ValidationException("testMessage", true);
Assert.assertEquals("No valid testMessage is specified", e.getMessage());
}
@Test
- public void validationException(){
+ public void validationException() {
ValidationException e = new ValidationException("testMessage");
Assert.assertEquals("No valid testMessage is specified", e.getMessage());
}
@Test
- public void validationExceptionVersion(){
+ public void validationExceptionVersion() {
ValidationException e = new ValidationException("testMessage", "secondTestMessage");
Assert.assertEquals("testMessage does not match secondTestMessage", e.getMessage());
}
diff --git a/common/src/test/java/org/onap/so/jsonpath/JsonPathUtilTest.java b/common/src/test/java/org/onap/so/jsonpath/JsonPathUtilTest.java
index 06e25daa98..494d531090 100644
--- a/common/src/test/java/org/onap/so/jsonpath/JsonPathUtilTest.java
+++ b/common/src/test/java/org/onap/so/jsonpath/JsonPathUtilTest.java
@@ -21,35 +21,39 @@
package org.onap.so.jsonpath;
import static org.junit.Assert.assertEquals;
-
import java.util.Collections;
import java.util.Optional;
-
import org.junit.Test;
public class JsonPathUtilTest {
- private static final String json = "{\"test\" : \"hello\", \"test2\" : {\"nested\" : \"value\"}}";
- @Test
- public void pathExistsTest() {
- assertEquals("test is found", JsonPathUtil.getInstance().pathExists(json, "$.test"), true);
- assertEquals("nothing is not found", JsonPathUtil.getInstance().pathExists(json, "$.nothing"), false);
- }
-
- @Test
- public void locateResultTest() {
- assertEquals("value of hello is found", Optional.of("hello"), JsonPathUtil.getInstance().locateResult(json, "$.test"));
- assertEquals("nothing returns empty", Optional.empty(), JsonPathUtil.getInstance().locateResult(json, "$.nothing"));
- }
-
- @Test
- public void simpleAndComplexValues() {
- assertEquals("json doc found", Optional.of("{\"nested\":\"value\"}"), JsonPathUtil.getInstance().locateResult(json, "$.test2"));
- assertEquals("value found", Optional.of("value"), JsonPathUtil.getInstance().locateResult(json, "$.test2.nested"));
- }
-
- @Test
- public void pathListTest() {
- assertEquals(Collections.singletonList("$['test2']['nested']"), JsonPathUtil.getInstance().getPathList(json, "$.*.*"));
- }
+ private static final String json = "{\"test\" : \"hello\", \"test2\" : {\"nested\" : \"value\"}}";
+
+ @Test
+ public void pathExistsTest() {
+ assertEquals("test is found", JsonPathUtil.getInstance().pathExists(json, "$.test"), true);
+ assertEquals("nothing is not found", JsonPathUtil.getInstance().pathExists(json, "$.nothing"), false);
+ }
+
+ @Test
+ public void locateResultTest() {
+ assertEquals("value of hello is found", Optional.of("hello"),
+ JsonPathUtil.getInstance().locateResult(json, "$.test"));
+ assertEquals("nothing returns empty", Optional.empty(),
+ JsonPathUtil.getInstance().locateResult(json, "$.nothing"));
+ }
+
+ @Test
+ public void simpleAndComplexValues() {
+ assertEquals("json doc found", Optional.of("{\"nested\":\"value\"}"),
+ JsonPathUtil.getInstance().locateResult(json, "$.test2"));
+ assertEquals("value found", Optional.of("value"),
+ JsonPathUtil.getInstance().locateResult(json, "$.test2.nested"));
+ }
+
+ @Test
+ public void pathListTest() {
+ assertEquals(Collections.singletonList("$['test2']['nested']"),
+ JsonPathUtil.getInstance().getPathList(json, "$.*.*"));
+ }
}
diff --git a/common/src/test/java/org/onap/so/serviceinstancebeans/RequestStatusTest.java b/common/src/test/java/org/onap/so/serviceinstancebeans/RequestStatusTest.java
index fa4d2f772d..b9e389e2ec 100644
--- a/common/src/test/java/org/onap/so/serviceinstancebeans/RequestStatusTest.java
+++ b/common/src/test/java/org/onap/so/serviceinstancebeans/RequestStatusTest.java
@@ -26,18 +26,19 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class RequestStatusTest {
- @Test
- public void requestStatusDefaultValues() throws Exception {
- RequestStatus requestStatus = new RequestStatus();
- requestStatus.setRequestState("COMPLETE");
- requestStatus.setStatusMessage("STATUS: COMPLETED");
- requestStatus.setPercentProgress(100);
- requestStatus.setTimeStamp("Fri, 08 Mar 2019 04:41:42 GMT");
- String expectedResponse = "{\"requestState\":\"COMPLETE\",\"statusMessage\":\"STATUS: COMPLETED\",\"percentProgress\":100,\"timestamp\":\"Fri, 08 Mar 2019 04:41:42 GMT\"}";
+ @Test
+ public void requestStatusDefaultValues() throws Exception {
+ RequestStatus requestStatus = new RequestStatus();
+ requestStatus.setRequestState("COMPLETE");
+ requestStatus.setStatusMessage("STATUS: COMPLETED");
+ requestStatus.setPercentProgress(100);
+ requestStatus.setTimeStamp("Fri, 08 Mar 2019 04:41:42 GMT");
+ String expectedResponse =
+ "{\"requestState\":\"COMPLETE\",\"statusMessage\":\"STATUS: COMPLETED\",\"percentProgress\":100,\"timestamp\":\"Fri, 08 Mar 2019 04:41:42 GMT\"}";
- ObjectMapper mapper = new ObjectMapper();
- String realResponse = mapper.writeValueAsString(requestStatus);
-
- JSONAssert.assertEquals(expectedResponse, realResponse, false);
- }
+ ObjectMapper mapper = new ObjectMapper();
+ String realResponse = mapper.writeValueAsString(requestStatus);
+
+ JSONAssert.assertEquals(expectedResponse, realResponse, false);
+ }
}
diff --git a/common/src/test/java/org/onap/so/serviceinstancebeans/ServiceInstanceBeansTest.java b/common/src/test/java/org/onap/so/serviceinstancebeans/ServiceInstanceBeansTest.java
index 946214efa4..1b20fc40ab 100644
--- a/common/src/test/java/org/onap/so/serviceinstancebeans/ServiceInstanceBeansTest.java
+++ b/common/src/test/java/org/onap/so/serviceinstancebeans/ServiceInstanceBeansTest.java
@@ -21,13 +21,10 @@
package org.onap.so.serviceinstancebeans;
import static org.junit.Assert.assertEquals;
-
import java.io.IOException;
-
import org.junit.Test;
import org.onap.so.openpojo.rules.HasToStringRule;
import org.onap.so.openpojo.rules.ToStringTester;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.openpojo.reflection.PojoClass;
@@ -42,40 +39,37 @@ import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
public class ServiceInstanceBeansTest {
-
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
- @Test
- public void pojoStructure() {
- test("org.onap.so.serviceinstancebeans");
- }
-
- @Test
- public void cloudConfigurationkeepDefaultValues() throws IOException {
- CloudConfiguration cloudConfiguration = new CloudConfiguration();
- cloudConfiguration.setLcpCloudRegionId("myRegionId");
- ObjectMapper mapper = new ObjectMapper();
-
- assertEquals("{\"cloudOwner\":\"CloudOwner\",\"lcpCloudRegionId\":\"myRegionId\"}", mapper.writeValueAsString(cloudConfiguration));
-
-
- }
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.serviceinstancebeans");
+ }
+
+ @Test
+ public void cloudConfigurationkeepDefaultValues() throws IOException {
+ CloudConfiguration cloudConfiguration = new CloudConfiguration();
+ cloudConfiguration.setLcpCloudRegionId("myRegionId");
+ ObjectMapper mapper = new ObjectMapper();
+
+ assertEquals("{\"cloudOwner\":\"CloudOwner\",\"lcpCloudRegionId\":\"myRegionId\"}",
+ mapper.writeValueAsString(cloudConfiguration));
+
+
+ }
+
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule())
+ .with(new HasToStringRule()).with(new SetterTester()).with(new GetterTester())
+ .with(new ToStringTester()).build();
+ validator.validate(pojoPackage, new FilterPackageInfo(), new FilterEnum(), filterTestClasses);
+ }
+
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterMustExistRule())
- .with(new HasToStringRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .with(new ToStringTester())
- .build();
- validator.validate(pojoPackage, new FilterPackageInfo(), new FilterEnum(), filterTestClasses);
- }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
-
}
diff --git a/common/src/test/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequestTest.java b/common/src/test/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequestTest.java
index 2e67ff4b2b..de197156bd 100644
--- a/common/src/test/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequestTest.java
+++ b/common/src/test/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequestTest.java
@@ -22,23 +22,23 @@ package org.onap.so.serviceinstancebeans;
import org.junit.Assert;
import org.junit.Test;
-
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ServiceInstancesRequestTest {
- @Test
- public void serializeServiceInstance() {
- String incomingRequest = "{\"requestDetails\":{\"modelInfo\":{\"modelInvariantUuid\":\"9647dfc4-2083-11e7-93ae-92361f002672\",\"modelType\":\"configuration\",\"modelName\":\"MSO-Configuration\",\"modelVersion\":\"1.0\",\"modelUuid\":\"36a3a8ea-49a6-4ac8-b06c-89a545444455\",\"modelCustomizationUuid\":\"68dc9a92-214c-11e7-93ae-92361f002671\"},\"requestInfo\":{\"source\":\"VID\",\"instanceName\":\"port_mirror_config_m830-01\",\"suppressRollback\":false,\"requestorId\":\"mdg1215\"},\"relatedInstanceList\":[{\"relatedInstance\":{\"instanceId\":\"956121e0-542d-4b30-b8c7-be611e3c8f13\",\"modelInfo\":{\"modelInvariantUuid\":\"9647dfc4-2083-11e7-93ae-92361f002671\",\"modelType\":\"service\",\"modelName\":\"MSOTADevInfra_vSAMP10a_Service\",\"modelVersion\":\"1.0\",\"modelUuid\":\"5df8b6de-2083-11e7-93ae-92361f002671\"}}},{\"relatedInstance\":{\"instanceId\":\"956121e0-542d-4b30-b8c7-be611e3c8f11\",\"modelInfo\":{\"modelInvariantUuid\":\"36a3a8ea-49a6-4ac8-b06c-89a545444456\",\"modelType\":\"vnf\",\"modelName\":\"testvnf\",\"modelVersion\":\"1.0\",\"modelUuid\":\"956121e0-542d-4b30-b8c7-be611e3c8f14\",\"modelCustomizationUuid\":\"68dc9a92-214c-11e7-93ae-92361f002676\"},\"instanceDirection\":\"source\"}},{\"relatedInstance\":{\"instanceId\":\"956121e0-542d-4b30-b8c7-be611e3c8f12\",\"modelInfo\":{\"modelInvariantUuid\":\"36a3a8ea-49a6-4ac8-b06c-89a545444477\",\"modelType\":\"vnf\",\"modelName\":\"svProbe vnf model name\",\"modelVersion\":\"1.0\",\"modelUuid\":\"36a3a8ea-49a6-4ac8-b06c-89a545444488\",\"modelCustomizationUuid\":\"68dc9a92-214c-11e7-93ae-92361f002672\"},\"instanceDirection\":\"destination\"}}],\"cloudConfiguration\":{\"lcpCloudRegionId\":\"mdt1\"},\"requestParameters\":{\"subscriptionServiceType\":\"MSO-dev-service-type\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"}],\"aLaCarte\":false,\"autoBuildVfModules\":false,\"cascadeDelete\":false,\"usePreload\":true,\"rebuildVolumeGroups\":false}},\"serviceInstanceId\":\"956121e0-542d-4b30-b8c7-be611e3c8f13\"}";
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- try {
- ServiceInstancesRequest request = mapper.readValue(incomingRequest, ServiceInstancesRequest.class);
- System.out.println("Java Object: " + request);
- } catch (Exception e) {
- System.out.println("Caught Exception " + e.getMessage());
- Assert.fail("Caught error on object serialization");
- }
- }
+ @Test
+ public void serializeServiceInstance() {
+ String incomingRequest =
+ "{\"requestDetails\":{\"modelInfo\":{\"modelInvariantUuid\":\"9647dfc4-2083-11e7-93ae-92361f002672\",\"modelType\":\"configuration\",\"modelName\":\"MSO-Configuration\",\"modelVersion\":\"1.0\",\"modelUuid\":\"36a3a8ea-49a6-4ac8-b06c-89a545444455\",\"modelCustomizationUuid\":\"68dc9a92-214c-11e7-93ae-92361f002671\"},\"requestInfo\":{\"source\":\"VID\",\"instanceName\":\"port_mirror_config_m830-01\",\"suppressRollback\":false,\"requestorId\":\"mdg1215\"},\"relatedInstanceList\":[{\"relatedInstance\":{\"instanceId\":\"956121e0-542d-4b30-b8c7-be611e3c8f13\",\"modelInfo\":{\"modelInvariantUuid\":\"9647dfc4-2083-11e7-93ae-92361f002671\",\"modelType\":\"service\",\"modelName\":\"MSOTADevInfra_vSAMP10a_Service\",\"modelVersion\":\"1.0\",\"modelUuid\":\"5df8b6de-2083-11e7-93ae-92361f002671\"}}},{\"relatedInstance\":{\"instanceId\":\"956121e0-542d-4b30-b8c7-be611e3c8f11\",\"modelInfo\":{\"modelInvariantUuid\":\"36a3a8ea-49a6-4ac8-b06c-89a545444456\",\"modelType\":\"vnf\",\"modelName\":\"testvnf\",\"modelVersion\":\"1.0\",\"modelUuid\":\"956121e0-542d-4b30-b8c7-be611e3c8f14\",\"modelCustomizationUuid\":\"68dc9a92-214c-11e7-93ae-92361f002676\"},\"instanceDirection\":\"source\"}},{\"relatedInstance\":{\"instanceId\":\"956121e0-542d-4b30-b8c7-be611e3c8f12\",\"modelInfo\":{\"modelInvariantUuid\":\"36a3a8ea-49a6-4ac8-b06c-89a545444477\",\"modelType\":\"vnf\",\"modelName\":\"svProbe vnf model name\",\"modelVersion\":\"1.0\",\"modelUuid\":\"36a3a8ea-49a6-4ac8-b06c-89a545444488\",\"modelCustomizationUuid\":\"68dc9a92-214c-11e7-93ae-92361f002672\"},\"instanceDirection\":\"destination\"}}],\"cloudConfiguration\":{\"lcpCloudRegionId\":\"mdt1\"},\"requestParameters\":{\"subscriptionServiceType\":\"MSO-dev-service-type\",\"userParams\":[{\"name\":\"someUserParam\",\"value\":\"someValue\"}],\"aLaCarte\":false,\"autoBuildVfModules\":false,\"cascadeDelete\":false,\"usePreload\":true,\"rebuildVolumeGroups\":false}},\"serviceInstanceId\":\"956121e0-542d-4b30-b8c7-be611e3c8f13\"}";
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ try {
+ ServiceInstancesRequest request = mapper.readValue(incomingRequest, ServiceInstancesRequest.class);
+ System.out.println("Java Object: " + request);
+ } catch (Exception e) {
+ System.out.println("Caught Exception " + e.getMessage());
+ Assert.fail("Caught error on object serialization");
+ }
+ }
}
diff --git a/common/src/test/java/org/onap/so/test/categories/SpringAware.java b/common/src/test/java/org/onap/so/test/categories/SpringAware.java
index 21035fcd4d..2462e678d9 100644
--- a/common/src/test/java/org/onap/so/test/categories/SpringAware.java
+++ b/common/src/test/java/org/onap/so/test/categories/SpringAware.java
@@ -21,5 +21,5 @@
package org.onap.so.test.categories;
public interface SpringAware {
- /* category marker */
+ /* category marker */
}
diff --git a/common/src/test/java/org/onap/so/utils/CheckResultsTest.java b/common/src/test/java/org/onap/so/utils/CheckResultsTest.java
index 0e1da16b9e..01de7167e8 100644
--- a/common/src/test/java/org/onap/so/utils/CheckResultsTest.java
+++ b/common/src/test/java/org/onap/so/utils/CheckResultsTest.java
@@ -21,11 +21,8 @@
package org.onap.so.utils;
import static org.junit.Assert.*;
-
import java.util.List;
-
import org.junit.Test;
-
import org.onap.so.utils.CheckResults.CheckResult;
public class CheckResultsTest {
@@ -34,25 +31,25 @@ public class CheckResultsTest {
* Test method for {@link org.onap.so.utils.CheckResults#getResults()}.
*/
@Test
- public final void testGetResults () {
- CheckResults cr = new CheckResults ();
- cr.addHostCheckResult ("host1", 0, "output");
- cr.addHostCheckResult ("host2", 2, "output2");
- cr.addServiceCheckResult ("host1", "service1", 0, "outputServ");
- cr.addServiceCheckResult ("host1", "service2", 2, "outputServ2");
- cr.addServiceCheckResult ("host2", "service1", 0, "output2Serv");
- cr.addServiceCheckResult ("host2", "service2", 2, "output2Serv2");
- List <CheckResult> res = cr.getResults ();
- assertEquals(res.size (), 6);
- assertEquals(res.get (0).getHostname (), "host1");
- assertEquals(res.get (1).getHostname (), "host2");
- assertEquals(res.get (2).getHostname (), "host1");
- assertEquals(res.get (3).getHostname (), "host1");
- assertEquals(res.get (4).getHostname (), "host2");
- assertEquals(res.get (5).getHostname (), "host2");
- assertEquals(res.get (0).getServicename (), null);
- assertEquals(res.get (3).getServicename (), "service2");
- assertEquals(res.get (5).getState (), 2);
+ public final void testGetResults() {
+ CheckResults cr = new CheckResults();
+ cr.addHostCheckResult("host1", 0, "output");
+ cr.addHostCheckResult("host2", 2, "output2");
+ cr.addServiceCheckResult("host1", "service1", 0, "outputServ");
+ cr.addServiceCheckResult("host1", "service2", 2, "outputServ2");
+ cr.addServiceCheckResult("host2", "service1", 0, "output2Serv");
+ cr.addServiceCheckResult("host2", "service2", 2, "output2Serv2");
+ List<CheckResult> res = cr.getResults();
+ assertEquals(res.size(), 6);
+ assertEquals(res.get(0).getHostname(), "host1");
+ assertEquals(res.get(1).getHostname(), "host2");
+ assertEquals(res.get(2).getHostname(), "host1");
+ assertEquals(res.get(3).getHostname(), "host1");
+ assertEquals(res.get(4).getHostname(), "host2");
+ assertEquals(res.get(5).getHostname(), "host2");
+ assertEquals(res.get(0).getServicename(), null);
+ assertEquals(res.get(3).getServicename(), "service2");
+ assertEquals(res.get(5).getState(), 2);
}
}
diff --git a/common/src/test/java/org/onap/so/utils/TestAppender.java b/common/src/test/java/org/onap/so/utils/TestAppender.java
index fba9c71c68..a1add63078 100644
--- a/common/src/test/java/org/onap/so/utils/TestAppender.java
+++ b/common/src/test/java/org/onap/so/utils/TestAppender.java
@@ -23,19 +23,18 @@ package org.onap.so.utils;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
-
import java.util.ArrayList;
import java.util.List;
public class TestAppender extends AppenderBase<ILoggingEvent> {
public static List<ILoggingEvent> events = new ArrayList<>();
-
- @Override
- protected void append(ILoggingEvent loggingEvent) {
- if (loggingEvent.getLevel() == Level.INFO) {
- events.add(loggingEvent);
+
+ @Override
+ protected void append(ILoggingEvent loggingEvent) {
+ if (loggingEvent.getLevel() == Level.INFO) {
+ events.add(loggingEvent);
}
- }
+ }
}
diff --git a/common/src/test/java/org/onap/so/utils/UUIDCheckerTest.java b/common/src/test/java/org/onap/so/utils/UUIDCheckerTest.java
index 9c9f58710e..433145f6f7 100644
--- a/common/src/test/java/org/onap/so/utils/UUIDCheckerTest.java
+++ b/common/src/test/java/org/onap/so/utils/UUIDCheckerTest.java
@@ -23,18 +23,17 @@
package org.onap.so.utils;
import static org.junit.Assert.*;
-
import org.junit.Test;
public class UUIDCheckerTest {
- @Test
- public void isValidUUIDTest(){
- String nullID = null;
- String badID = "This is not a UUID";
- String id = UUIDChecker.getUUID();
- assertFalse(UUIDChecker.isValidUUID(nullID));
- assertFalse(UUIDChecker.isValidUUID(badID));
- assertTrue(UUIDChecker.isValidUUID(id));
- }
+ @Test
+ public void isValidUUIDTest() {
+ String nullID = null;
+ String badID = "This is not a UUID";
+ String id = UUIDChecker.getUUID();
+ assertFalse(UUIDChecker.isValidUUID(nullID));
+ assertFalse(UUIDChecker.isValidUUID(badID));
+ assertTrue(UUIDChecker.isValidUUID(id));
+ }
}
diff --git a/common/src/test/java/org/onap/so/utils/XMLMarshallerTest.java b/common/src/test/java/org/onap/so/utils/XMLMarshallerTest.java
index 148e1b452c..402b215ff9 100644
--- a/common/src/test/java/org/onap/so/utils/XMLMarshallerTest.java
+++ b/common/src/test/java/org/onap/so/utils/XMLMarshallerTest.java
@@ -22,7 +22,6 @@ package org.onap.so.utils;
import org.junit.Assert;
import org.junit.Test;
-
import javax.xml.bind.annotation.XmlRootElement;
/**
@@ -57,8 +56,7 @@ public class XMLMarshallerTest {
String firstName;
String lastName;
- public TestPOJO() {
- }
+ public TestPOJO() {}
public String getFirstName() {
@@ -79,14 +77,18 @@ public class XMLMarshallerTest {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof TestPOJO)) return false;
+ if (this == o)
+ return true;
+ if (!(o instanceof TestPOJO))
+ return false;
TestPOJO testPOJO = (TestPOJO) o;
- if (getFirstName() != null ? !getFirstName().equals(testPOJO.getFirstName()) : testPOJO.getFirstName() != null)
+ if (getFirstName() != null ? !getFirstName().equals(testPOJO.getFirstName())
+ : testPOJO.getFirstName() != null)
return false;
- return getLastName() != null ? getLastName().equals(testPOJO.getLastName()) : testPOJO.getLastName() == null;
+ return getLastName() != null ? getLastName().equals(testPOJO.getLastName())
+ : testPOJO.getLastName() == null;
}
@Override
diff --git a/common/src/test/java/org/onap/so/web/exceptions/RuntimeExceptionMapperTest.java b/common/src/test/java/org/onap/so/web/exceptions/RuntimeExceptionMapperTest.java
index b49c5312e5..d1d3f2a5f0 100644
--- a/common/src/test/java/org/onap/so/web/exceptions/RuntimeExceptionMapperTest.java
+++ b/common/src/test/java/org/onap/so/web/exceptions/RuntimeExceptionMapperTest.java
@@ -26,11 +26,9 @@ import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
-
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-
import org.junit.AfterClass;
import org.junit.Test;
@@ -38,29 +36,29 @@ import org.junit.Test;
public class RuntimeExceptionMapperTest {
-
- @Test
- public void testResponse() {
-
- RuntimeExceptionMapper mapper = new RuntimeExceptionMapper();
-
- Response r = mapper.toResponse(new RuntimeException("This is the run time exception message"));
-
- assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), r.getStatus());
- assertThat(r.getEntity(), instanceOf(ExceptionResponse.class));
- assertThat(((ExceptionResponse)r.getEntity()).getMessage(), equalTo("Unexpected Internal Exception"));
-
- }
-
- @Test
- public void preserve404ExceptionForForwarding() {
-
- RuntimeExceptionMapper mapper = new RuntimeExceptionMapper();
-
- Response r = mapper.toResponse(new NotFoundException("not found"));
-
- assertEquals(Status.NOT_FOUND.getStatusCode(), r.getStatus());
- assertThat(r.getEntity(), is(nullValue()));
- }
-
+
+ @Test
+ public void testResponse() {
+
+ RuntimeExceptionMapper mapper = new RuntimeExceptionMapper();
+
+ Response r = mapper.toResponse(new RuntimeException("This is the run time exception message"));
+
+ assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), r.getStatus());
+ assertThat(r.getEntity(), instanceOf(ExceptionResponse.class));
+ assertThat(((ExceptionResponse) r.getEntity()).getMessage(), equalTo("Unexpected Internal Exception"));
+
+ }
+
+ @Test
+ public void preserve404ExceptionForForwarding() {
+
+ RuntimeExceptionMapper mapper = new RuntimeExceptionMapper();
+
+ Response r = mapper.toResponse(new NotFoundException("not found"));
+
+ assertEquals(Status.NOT_FOUND.getStatusCode(), r.getStatus());
+ assertThat(r.getEntity(), is(nullValue()));
+ }
+
}
diff --git a/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java b/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java
index 08499cfd22..a6cce27f91 100644
--- a/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java
+++ b/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java
@@ -37,7 +37,7 @@ import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
-public class SOAPLoggingInInterceptor extends AbstractSoapInterceptor{
+public class SOAPLoggingInInterceptor extends AbstractSoapInterceptor {
protected static Logger logger = LoggerFactory.getLogger(SOAPLoggingInInterceptor.class);
@@ -49,10 +49,10 @@ public class SOAPLoggingInInterceptor extends AbstractSoapInterceptor{
public void handleMessage(SoapMessage message) throws Fault {
try {
SOAPMDCSetup mdcSetup = new SOAPMDCSetup();
- Map<String, List<String>> headers = (Map<String,List<String>>) message.get(Message.PROTOCOL_HEADERS);
- HttpServletRequest request = (HttpServletRequest)message.get(AbstractHTTPDestination.HTTP_REQUEST);
+ Map<String, List<String>> headers = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);
+ HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
request.getRemoteAddr();
-
+
setRequestId(headers);
setInvocationId(headers);
setServiceName(message);
@@ -67,36 +67,38 @@ public class SOAPLoggingInInterceptor extends AbstractSoapInterceptor{
logger.warn("Error in incoming SOAP Message Inteceptor", e);
}
}
-
+
private void setServiceName(SoapMessage message) {
String requestURI = (String) message.get(Message.REQUEST_URI);
MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, requestURI);
}
- //CXF Appears to flatten headers to lower case
- private void setMDCPartnerName(Map<String, List<String>> headers){
- String partnerName=getValueOrDefault(headers, ONAPLogConstants.Headers.PARTNER_NAME.toLowerCase(),"");
- MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME,partnerName);
+ // CXF Appears to flatten headers to lower case
+ private void setMDCPartnerName(Map<String, List<String>> headers) {
+ String partnerName = getValueOrDefault(headers, ONAPLogConstants.Headers.PARTNER_NAME.toLowerCase(), "");
+ MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName);
}
private void setInvocationId(Map<String, List<String>> headers) {
- String invocationId=getValueOrDefault(headers, ONAPLogConstants.Headers.INVOCATION_ID.toLowerCase(),UUID.randomUUID().toString());
+ String invocationId = getValueOrDefault(headers, ONAPLogConstants.Headers.INVOCATION_ID.toLowerCase(),
+ UUID.randomUUID().toString());
MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
}
private void setRequestId(Map<String, List<String>> headers) {
- String requestId=getValueOrDefault(headers, ONAPLogConstants.Headers.REQUEST_ID.toLowerCase(),UUID.randomUUID().toString());
- MDC.put(ONAPLogConstants.MDCs.REQUEST_ID,requestId);
+ String requestId = getValueOrDefault(headers, ONAPLogConstants.Headers.REQUEST_ID.toLowerCase(),
+ UUID.randomUUID().toString());
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
}
- private String getValueOrDefault(Map<String, List<String>> headers, String headerName, String defaultValue){
+ private String getValueOrDefault(Map<String, List<String>> headers, String headerName, String defaultValue) {
String headerValue;
- List<String> headerList=headers.get(headerName);
- if(headerList != null && !headerList.isEmpty()){
- headerValue= headerList.get(0);
- if(headerValue == null || headerValue.isEmpty())
+ List<String> headerList = headers.get(headerName);
+ if (headerList != null && !headerList.isEmpty()) {
+ headerValue = headerList.get(0);
+ if (headerValue == null || headerValue.isEmpty())
headerValue = defaultValue;
- }else
+ } else
headerValue = defaultValue;
return headerValue;
}
diff --git a/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingOutInterceptor.java b/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingOutInterceptor.java
index ed4ba76268..92b266870c 100644
--- a/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingOutInterceptor.java
+++ b/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingOutInterceptor.java
@@ -33,14 +33,14 @@ import org.slf4j.MDC;
-public class SOAPLoggingOutInterceptor extends AbstractSoapInterceptor{
+public class SOAPLoggingOutInterceptor extends AbstractSoapInterceptor {
private static final String _500 = "500";
protected static Logger logger = LoggerFactory.getLogger(SOAPLoggingOutInterceptor.class);
-
-
+
+
public SOAPLoggingOutInterceptor() {
super(Phase.WRITE);
}
@@ -50,15 +50,16 @@ public class SOAPLoggingOutInterceptor extends AbstractSoapInterceptor{
try {
Exception ex = message.getContent(Exception.class);
if (ex == null) {
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.COMPLETED.toString());
- }else{
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE,
+ ONAPLogConstants.ResponseStatus.COMPLETED.toString());
+ } else {
int responseCode = 0;
responseCode = (int) message.get(Message.RESPONSE_CODE);
- if(responseCode != 0 )
+ if (responseCode != 0)
MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(responseCode));
else
MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, _500);
-
+
MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.ERROR.toString());
}
logger.info(ONAPLogConstants.Markers.EXIT, "Exiting");
diff --git a/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPMDCSetup.java b/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPMDCSetup.java
index ef47106fa1..8258ce6f99 100644
--- a/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPMDCSetup.java
+++ b/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPMDCSetup.java
@@ -35,18 +35,18 @@ import org.slf4j.MDC;
public class SOAPMDCSetup {
-
- protected static Logger logger = LoggerFactory.getLogger(SOAPMDCSetup.class);
-
+
+ protected static Logger logger = LoggerFactory.getLogger(SOAPMDCSetup.class);
+
private static final String INSTANCE_UUID = UUID.randomUUID().toString();
-
- public void setInstanceUUID(){
+
+ public void setInstanceUUID() {
MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, INSTANCE_UUID);
}
- public void setServerFQDN(){
+ public void setServerFQDN() {
String serverFQDN = "";
- InetAddress addr= null;
+ InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
serverFQDN = addr.toString();
@@ -57,17 +57,18 @@ public class SOAPMDCSetup {
MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, serverFQDN);
}
- public void setClientIPAddress(HttpServletRequest httpServletRequest){
+ public void setClientIPAddress(HttpServletRequest httpServletRequest) {
String remoteIpAddress = "";
if (httpServletRequest != null) {
remoteIpAddress = httpServletRequest.getRemoteAddr();
- }
+ }
MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, remoteIpAddress);
}
public void setEntryTimeStamp() {
- MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
+ MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,
+ ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
}
-
-
+
+
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/BpmnRequest.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/BpmnRequest.java
index bc2e5b1893..c67613534b 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/BpmnRequest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/BpmnRequest.java
@@ -21,232 +21,229 @@
package org.onap.so.apihandler.camundabeans;
import org.onap.so.apihandler.common.CommonConstants;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
/**
- * JavaBean JSON class for a "bpmnRequest" which contains the JSON payload that
- * will be passed to the Camunda process
+ * JavaBean JSON class for a "bpmnRequest" which contains the JSON payload that will be passed to the Camunda process
*/
-@JsonPropertyOrder({CommonConstants.REQUEST_ID_VARIABLE,
- CommonConstants.IS_BASE_VF_MODULE_VARIABLE, CommonConstants.RECIPE_TIMEOUT_VARIABLE,
- CommonConstants.REQUEST_ACTION_VARIABLE, CommonConstants.SERVICE_INSTANCE_ID_VARIABLE,
- CommonConstants.VNF_ID_VARIABLE, CommonConstants.VF_MODULE_ID_VARIABLE,
- CommonConstants.VOLUME_GROUP_ID_VARIABLE, CommonConstants.NETWORK_ID_VARIABLE,
- CommonConstants.SERVICE_TYPE_VARIABLE, CommonConstants.VNF_TYPE_VARIABLE,
- CommonConstants.VF_MODULE_TYPE_VARIABLE, CommonConstants.NETWORK_TYPE_VARIABLE,
- CommonConstants.REQUEST_DETAILS_VARIABLE})
+@JsonPropertyOrder({CommonConstants.REQUEST_ID_VARIABLE, CommonConstants.IS_BASE_VF_MODULE_VARIABLE,
+ CommonConstants.RECIPE_TIMEOUT_VARIABLE, CommonConstants.REQUEST_ACTION_VARIABLE,
+ CommonConstants.SERVICE_INSTANCE_ID_VARIABLE, CommonConstants.VNF_ID_VARIABLE,
+ CommonConstants.VF_MODULE_ID_VARIABLE, CommonConstants.VOLUME_GROUP_ID_VARIABLE,
+ CommonConstants.NETWORK_ID_VARIABLE, CommonConstants.SERVICE_TYPE_VARIABLE, CommonConstants.VNF_TYPE_VARIABLE,
+ CommonConstants.VF_MODULE_TYPE_VARIABLE, CommonConstants.NETWORK_TYPE_VARIABLE,
+ CommonConstants.REQUEST_DETAILS_VARIABLE})
@JsonRootName(CommonConstants.CAMUNDA_ROOT_INPUT)
public class BpmnRequest {
- @JsonProperty(CommonConstants.CAMUNDA_HOST)
- private CamundaInput host;
-
- @JsonProperty(CommonConstants.REQUEST_ID_VARIABLE)
- private CamundaInput requestId;
-
- @JsonProperty(CommonConstants.IS_BASE_VF_MODULE_VARIABLE)
- private CamundaBooleanInput isBaseVfModule;
-
- @JsonProperty(CommonConstants.RECIPE_TIMEOUT_VARIABLE)
- private CamundaIntegerInput recipeTimeout;
-
- @JsonProperty(CommonConstants.REQUEST_ACTION_VARIABLE)
- private CamundaInput requestAction;
-
- @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE)
- private CamundaInput serviceInstanceId;
-
- @JsonProperty(CommonConstants.VNF_ID_VARIABLE)
- private CamundaInput vnfId;
-
- @JsonProperty(CommonConstants.VF_MODULE_ID_VARIABLE)
- private CamundaInput vfModuleId;
-
- @JsonProperty(CommonConstants.VOLUME_GROUP_ID_VARIABLE)
- private CamundaInput volumeGroupId;
-
- @JsonProperty(CommonConstants.NETWORK_ID_VARIABLE)
- private CamundaInput networkId;
-
- @JsonProperty(CommonConstants.SERVICE_TYPE_VARIABLE)
- private CamundaInput serviceType;
-
- @JsonProperty(CommonConstants.VNF_TYPE_VARIABLE)
- private CamundaInput vnfType;
-
- @JsonProperty(CommonConstants.VF_MODULE_TYPE_VARIABLE)
- private CamundaInput vfModuleType;
-
- @JsonProperty(CommonConstants.NETWORK_TYPE_VARIABLE)
- private CamundaInput networkType;
-
- @JsonProperty(CommonConstants.REQUEST_DETAILS_VARIABLE)
- private CamundaInput requestDetails;
-
- public BpmnRequest() {
- /* Empty constructor */
-
- }
-
- @JsonProperty(CommonConstants.CAMUNDA_HOST)
- public CamundaInput getHost() {
- return host;
- }
-
- @JsonProperty(CommonConstants.CAMUNDA_HOST)
- public void setHost(CamundaInput host) {
- this.host = host;
- }
-
- @JsonProperty(CommonConstants.REQUEST_ID_VARIABLE)
- public CamundaInput getRequestId() {
- return requestId;
- }
-
- @JsonProperty(CommonConstants.REQUEST_ID_VARIABLE)
- public void setRequestId(CamundaInput requestId) {
- this.requestId = requestId;
- }
-
- @JsonProperty(CommonConstants.IS_BASE_VF_MODULE_VARIABLE)
- public CamundaBooleanInput getIsBaseVfModule() {
- return isBaseVfModule;
- }
-
- @JsonProperty(CommonConstants.IS_BASE_VF_MODULE_VARIABLE)
- public void setIsBaseVfModule(CamundaBooleanInput isBaseVfModule) {
- this.isBaseVfModule = isBaseVfModule;
- }
-
- @JsonProperty(CommonConstants.RECIPE_TIMEOUT_VARIABLE)
- public CamundaIntegerInput getRecipeTimeout() {
- return recipeTimeout;
- }
-
- @JsonProperty(CommonConstants.RECIPE_TIMEOUT_VARIABLE)
- public void setRecipeTimeout(CamundaIntegerInput recipeTimeout) {
- this.recipeTimeout = recipeTimeout;
- }
-
- @JsonProperty(CommonConstants.REQUEST_ACTION_VARIABLE)
- public CamundaInput getRequestAction() {
- return requestAction;
- }
-
- @JsonProperty(CommonConstants.REQUEST_ACTION_VARIABLE)
- public void setRequestAction(CamundaInput requestAction) {
- this.requestAction = requestAction;
- }
- @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE)
- public CamundaInput getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE)
- public void setServiceInstanceId(CamundaInput serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
-
- @JsonProperty(CommonConstants.VNF_ID_VARIABLE)
- public CamundaInput getVnfId() {
- return vnfId;
- }
-
- @JsonProperty(CommonConstants.VNF_ID_VARIABLE)
- public void setVnfId(CamundaInput vnfId) {
- this.vnfId = vnfId;
- }
-
- @JsonProperty(CommonConstants.VF_MODULE_ID_VARIABLE)
- public CamundaInput getVfModuleId() {
- return vfModuleId;
- }
-
- @JsonProperty(CommonConstants.VF_MODULE_ID_VARIABLE)
- public void setVfModuleId(CamundaInput vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
-
- @JsonProperty(CommonConstants.VOLUME_GROUP_ID_VARIABLE)
- public CamundaInput getVolumeGroupId() {
- return volumeGroupId;
- }
-
- @JsonProperty(CommonConstants.VOLUME_GROUP_ID_VARIABLE)
- public void setVolumeGroupId(CamundaInput volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
-
- @JsonProperty(CommonConstants.NETWORK_ID_VARIABLE)
- public CamundaInput getNetworkId() {
- return networkId;
- }
-
- @JsonProperty(CommonConstants.NETWORK_ID_VARIABLE)
- public void setNetworkId(CamundaInput networkId) {
- this.networkId = networkId;
- }
-
- @JsonProperty(CommonConstants.SERVICE_TYPE_VARIABLE)
- public CamundaInput getServiceType() {
- return serviceType;
- }
-
- @JsonProperty(CommonConstants.SERVICE_TYPE_VARIABLE)
- public void setServiceType(CamundaInput serviceType) {
- this.serviceType = serviceType;
- }
-
- @JsonProperty(CommonConstants.VNF_TYPE_VARIABLE)
- public CamundaInput getVnfType() {
- return vnfType;
- }
-
- @JsonProperty(CommonConstants.VNF_TYPE_VARIABLE)
- public void setVnfType(CamundaInput vnfType) {
- this.vnfType = vnfType;
- }
-
- @JsonProperty(CommonConstants.VF_MODULE_TYPE_VARIABLE)
- public CamundaInput getVfModuleType() {
- return vfModuleType;
- }
-
- @JsonProperty(CommonConstants.VF_MODULE_TYPE_VARIABLE)
- public void setVfModuleType(CamundaInput vfModuleType) {
- this.vfModuleType = vfModuleType;
- }
-
- @JsonProperty(CommonConstants.NETWORK_TYPE_VARIABLE)
- public CamundaInput getNetworkType() {
- return networkType;
- }
-
- @JsonProperty(CommonConstants.NETWORK_TYPE_VARIABLE)
- public void setNetworkType(CamundaInput networkType) {
- this.networkType = networkType;
- }
-
- @JsonProperty(CommonConstants.REQUEST_DETAILS_VARIABLE)
- public CamundaInput getRequestDetails() {
- return requestDetails;
- }
-
- @JsonProperty(CommonConstants.REQUEST_DETAILS_VARIABLE)
- public void setRequestDetails(CamundaInput requestDetails) {
- this.requestDetails = requestDetails;
- }
-
-
-
-
- @Override
- public String toString() {
-
- return "BpmnRequest";
- }
-
+ @JsonProperty(CommonConstants.CAMUNDA_HOST)
+ private CamundaInput host;
+
+ @JsonProperty(CommonConstants.REQUEST_ID_VARIABLE)
+ private CamundaInput requestId;
+
+ @JsonProperty(CommonConstants.IS_BASE_VF_MODULE_VARIABLE)
+ private CamundaBooleanInput isBaseVfModule;
+
+ @JsonProperty(CommonConstants.RECIPE_TIMEOUT_VARIABLE)
+ private CamundaIntegerInput recipeTimeout;
+
+ @JsonProperty(CommonConstants.REQUEST_ACTION_VARIABLE)
+ private CamundaInput requestAction;
+
+ @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE)
+ private CamundaInput serviceInstanceId;
+
+ @JsonProperty(CommonConstants.VNF_ID_VARIABLE)
+ private CamundaInput vnfId;
+
+ @JsonProperty(CommonConstants.VF_MODULE_ID_VARIABLE)
+ private CamundaInput vfModuleId;
+
+ @JsonProperty(CommonConstants.VOLUME_GROUP_ID_VARIABLE)
+ private CamundaInput volumeGroupId;
+
+ @JsonProperty(CommonConstants.NETWORK_ID_VARIABLE)
+ private CamundaInput networkId;
+
+ @JsonProperty(CommonConstants.SERVICE_TYPE_VARIABLE)
+ private CamundaInput serviceType;
+
+ @JsonProperty(CommonConstants.VNF_TYPE_VARIABLE)
+ private CamundaInput vnfType;
+
+ @JsonProperty(CommonConstants.VF_MODULE_TYPE_VARIABLE)
+ private CamundaInput vfModuleType;
+
+ @JsonProperty(CommonConstants.NETWORK_TYPE_VARIABLE)
+ private CamundaInput networkType;
+
+ @JsonProperty(CommonConstants.REQUEST_DETAILS_VARIABLE)
+ private CamundaInput requestDetails;
+
+ public BpmnRequest() {
+ /* Empty constructor */
+
+ }
+
+ @JsonProperty(CommonConstants.CAMUNDA_HOST)
+ public CamundaInput getHost() {
+ return host;
+ }
+
+ @JsonProperty(CommonConstants.CAMUNDA_HOST)
+ public void setHost(CamundaInput host) {
+ this.host = host;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_ID_VARIABLE)
+ public CamundaInput getRequestId() {
+ return requestId;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_ID_VARIABLE)
+ public void setRequestId(CamundaInput requestId) {
+ this.requestId = requestId;
+ }
+
+ @JsonProperty(CommonConstants.IS_BASE_VF_MODULE_VARIABLE)
+ public CamundaBooleanInput getIsBaseVfModule() {
+ return isBaseVfModule;
+ }
+
+ @JsonProperty(CommonConstants.IS_BASE_VF_MODULE_VARIABLE)
+ public void setIsBaseVfModule(CamundaBooleanInput isBaseVfModule) {
+ this.isBaseVfModule = isBaseVfModule;
+ }
+
+ @JsonProperty(CommonConstants.RECIPE_TIMEOUT_VARIABLE)
+ public CamundaIntegerInput getRecipeTimeout() {
+ return recipeTimeout;
+ }
+
+ @JsonProperty(CommonConstants.RECIPE_TIMEOUT_VARIABLE)
+ public void setRecipeTimeout(CamundaIntegerInput recipeTimeout) {
+ this.recipeTimeout = recipeTimeout;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_ACTION_VARIABLE)
+ public CamundaInput getRequestAction() {
+ return requestAction;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_ACTION_VARIABLE)
+ public void setRequestAction(CamundaInput requestAction) {
+ this.requestAction = requestAction;
+ }
+
+ @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE)
+ public CamundaInput getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE)
+ public void setServiceInstanceId(CamundaInput serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ @JsonProperty(CommonConstants.VNF_ID_VARIABLE)
+ public CamundaInput getVnfId() {
+ return vnfId;
+ }
+
+ @JsonProperty(CommonConstants.VNF_ID_VARIABLE)
+ public void setVnfId(CamundaInput vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ @JsonProperty(CommonConstants.VF_MODULE_ID_VARIABLE)
+ public CamundaInput getVfModuleId() {
+ return vfModuleId;
+ }
+
+ @JsonProperty(CommonConstants.VF_MODULE_ID_VARIABLE)
+ public void setVfModuleId(CamundaInput vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ @JsonProperty(CommonConstants.VOLUME_GROUP_ID_VARIABLE)
+ public CamundaInput getVolumeGroupId() {
+ return volumeGroupId;
+ }
+
+ @JsonProperty(CommonConstants.VOLUME_GROUP_ID_VARIABLE)
+ public void setVolumeGroupId(CamundaInput volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ @JsonProperty(CommonConstants.NETWORK_ID_VARIABLE)
+ public CamundaInput getNetworkId() {
+ return networkId;
+ }
+
+ @JsonProperty(CommonConstants.NETWORK_ID_VARIABLE)
+ public void setNetworkId(CamundaInput networkId) {
+ this.networkId = networkId;
+ }
+
+ @JsonProperty(CommonConstants.SERVICE_TYPE_VARIABLE)
+ public CamundaInput getServiceType() {
+ return serviceType;
+ }
+
+ @JsonProperty(CommonConstants.SERVICE_TYPE_VARIABLE)
+ public void setServiceType(CamundaInput serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ @JsonProperty(CommonConstants.VNF_TYPE_VARIABLE)
+ public CamundaInput getVnfType() {
+ return vnfType;
+ }
+
+ @JsonProperty(CommonConstants.VNF_TYPE_VARIABLE)
+ public void setVnfType(CamundaInput vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ @JsonProperty(CommonConstants.VF_MODULE_TYPE_VARIABLE)
+ public CamundaInput getVfModuleType() {
+ return vfModuleType;
+ }
+
+ @JsonProperty(CommonConstants.VF_MODULE_TYPE_VARIABLE)
+ public void setVfModuleType(CamundaInput vfModuleType) {
+ this.vfModuleType = vfModuleType;
+ }
+
+ @JsonProperty(CommonConstants.NETWORK_TYPE_VARIABLE)
+ public CamundaInput getNetworkType() {
+ return networkType;
+ }
+
+ @JsonProperty(CommonConstants.NETWORK_TYPE_VARIABLE)
+ public void setNetworkType(CamundaInput networkType) {
+ this.networkType = networkType;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_DETAILS_VARIABLE)
+ public CamundaInput getRequestDetails() {
+ return requestDetails;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_DETAILS_VARIABLE)
+ public void setRequestDetails(CamundaInput requestDetails) {
+ this.requestDetails = requestDetails;
+ }
+
+
+
+ @Override
+ public String toString() {
+
+ return "BpmnRequest";
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaBooleanInput.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaBooleanInput.java
index ea44375ff7..9afcadcede 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaBooleanInput.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaBooleanInput.java
@@ -23,12 +23,10 @@ package org.onap.so.apihandler.camundabeans;
import org.onap.so.apihandler.common.CommonConstants;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/**
- * JavaBean JSON class for a "gMyServiceInput" which contains the xml payload that
- * will be passed to the Camunda process
+ * JavaBean JSON class for a "gMyServiceInput" which contains the xml payload that will be passed to the Camunda process
*/
@@ -40,8 +38,7 @@ public class CamundaBooleanInput {
private String type = "Boolean";
- public CamundaBooleanInput() {
- }
+ public CamundaBooleanInput() {}
@JsonProperty(CommonConstants.CAMUNDA_VALUE)
public boolean getValue() {
@@ -55,15 +52,15 @@ public class CamundaBooleanInput {
@JsonProperty(CommonConstants.CAMUNDA_TYPE)
public String getType() {
- return type;
- }
+ return type;
+ }
@JsonProperty(CommonConstants.CAMUNDA_TYPE)
- public void setType(String type) {
- this.type = type;
- }
+ public void setType(String type) {
+ this.type = type;
+ }
- @Override
+ @Override
public String toString() {
return "CamundaInput [value=" + value + ", type=" + type + "]";
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaBpmnRequestInput.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaBpmnRequestInput.java
index 25293c7807..33eea6871a 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaBpmnRequestInput.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaBpmnRequestInput.java
@@ -23,12 +23,10 @@ package org.onap.so.apihandler.camundabeans;
import org.onap.so.apihandler.common.CommonConstants;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/**
- * JavaBean JSON class for a "gMyServiceInput" which contains the xml payload that
- * will be passed to the Camunda process
+ * JavaBean JSON class for a "gMyServiceInput" which contains the xml payload that will be passed to the Camunda process
*/
public class CamundaBpmnRequestInput {
@@ -54,15 +52,15 @@ public class CamundaBpmnRequestInput {
@JsonProperty(CommonConstants.CAMUNDA_TYPE)
public String getType() {
- return type;
- }
+ return type;
+ }
@JsonProperty(CommonConstants.CAMUNDA_TYPE)
- public void setType(String type) {
- this.type = type;
- }
+ public void setType(String type) {
+ this.type = type;
+ }
- @Override
+ @Override
public String toString() {
return "CamundaInput [value=" + value + ", type=" + type + "]";
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaInput.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaInput.java
index 29e72e005a..b384c4ff89 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaInput.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaInput.java
@@ -22,55 +22,50 @@ package org.onap.so.apihandler.camundabeans;
-
import org.onap.so.apihandler.common.CommonConstants;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/**
- * JavaBean JSON class for a "gMyServiceInput" which contains the xml payload that
- * will be passed to the Camunda process
+ * JavaBean JSON class for a "gMyServiceInput" which contains the xml payload that will be passed to the Camunda process
*
*/
public class CamundaInput {
-
- @JsonProperty(CommonConstants.CAMUNDA_VALUE)
- private String value;
-
-
- @JsonProperty(CommonConstants.CAMUNDA_TYPE)
- private String type = "String";
-
-
- @JsonProperty(CommonConstants.CAMUNDA_VALUE)
- public String getValue() {
- return value;
- }
-
- @JsonProperty(CommonConstants.CAMUNDA_TYPE)
- public String getType() {
- return type;
- }
-
- @JsonProperty(CommonConstants.CAMUNDA_TYPE)
- public void setType(String type) {
- this.type = type;
- }
-
- @JsonProperty(CommonConstants.CAMUNDA_VALUE)
- public void setValue(String value) {
- this.value = value;
- }
-
- @Override
- public String toString() {
- return "CamundaInput [value=" + value + ", type=" + type + "]";
- }
-
-
-
-
-
+
+ @JsonProperty(CommonConstants.CAMUNDA_VALUE)
+ private String value;
+
+
+ @JsonProperty(CommonConstants.CAMUNDA_TYPE)
+ private String type = "String";
+
+
+ @JsonProperty(CommonConstants.CAMUNDA_VALUE)
+ public String getValue() {
+ return value;
+ }
+
+ @JsonProperty(CommonConstants.CAMUNDA_TYPE)
+ public String getType() {
+ return type;
+ }
+
+ @JsonProperty(CommonConstants.CAMUNDA_TYPE)
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ @JsonProperty(CommonConstants.CAMUNDA_VALUE)
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return "CamundaInput [value=" + value + ", type=" + type + "]";
+ }
+
+
+
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaIntegerInput.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaIntegerInput.java
index 5bcfc6fb53..b75efe4bb0 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaIntegerInput.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaIntegerInput.java
@@ -23,24 +23,21 @@ package org.onap.so.apihandler.camundabeans;
import org.onap.so.apihandler.common.CommonConstants;
-
import com.fasterxml.jackson.annotation.JsonProperty;
/**
- * JavaBean JSON class for a "gMyServiceInput" which contains the xml payload that
- * will be passed to the Camunda process
+ * JavaBean JSON class for a "gMyServiceInput" which contains the xml payload that will be passed to the Camunda process
*/
public class CamundaIntegerInput {
@JsonProperty(CommonConstants.CAMUNDA_VALUE)
private int value;
-
+
@JsonProperty(CommonConstants.CAMUNDA_TYPE)
private String type = "Integer";
- public CamundaIntegerInput() {
- }
+ public CamundaIntegerInput() {}
@JsonProperty(CommonConstants.CAMUNDA_VALUE)
public int getValue() {
@@ -51,18 +48,18 @@ public class CamundaIntegerInput {
public void setValue(int value) {
this.value = value;
}
-
+
@JsonProperty(CommonConstants.CAMUNDA_TYPE)
public String getType() {
- return type;
- }
+ return type;
+ }
@JsonProperty(CommonConstants.CAMUNDA_TYPE)
- public void setType(String type) {
- this.type = type;
- }
+ public void setType(String type) {
+ this.type = type;
+ }
- @Override
+ @Override
public String toString() {
return "CamundaInput [value=" + Integer.toString(value) + ", type=" + type + "]";
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequest.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequest.java
index c57c0965b9..eb94b0d16e 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequest.java
@@ -98,10 +98,7 @@ public class CamundaMacroRequest {
@Override
public String toString() {
- return "CamundaMacroRequest{" +
- "requestId=" + requestId +
- ", action=" + action +
- ", serviceInstanceId=" + serviceInstanceId +
- '}';
+ return "CamundaMacroRequest{" + "requestId=" + requestId + ", action=" + action + ", serviceInstanceId="
+ + serviceInstanceId + '}';
}
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequestSerializer.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequestSerializer.java
index 81adb40498..82077a84e6 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequestSerializer.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequestSerializer.java
@@ -27,11 +27,12 @@ import com.fasterxml.jackson.databind.SerializationFeature;
/**
* Class used to create data object and serialize it to JSON which the BPEL macro flow understands.
*/
-public class CamundaMacroRequestSerializer {
+public class CamundaMacroRequestSerializer {
- private CamundaMacroRequestSerializer(){}
+ private CamundaMacroRequestSerializer() {}
- public static String getJsonRequest(String requestId, String action, String serviceInstanceId)throws JsonProcessingException{
+ public static String getJsonRequest(String requestId, String action, String serviceInstanceId)
+ throws JsonProcessingException {
CamundaMacroRequest macroRequest = new CamundaMacroRequest();
macroRequest.setAction(getCamundaInput(action));
macroRequest.setRequestId(getCamundaInput(requestId));
@@ -41,7 +42,7 @@ public class CamundaMacroRequestSerializer {
return mapper.writeValueAsString(macroRequest);
}
- private static CamundaInput getCamundaInput(String value){
+ private static CamundaInput getCamundaInput(String value) {
CamundaInput input = new CamundaInput();
input.setType("String");
input.setValue(value);
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaRequest.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaRequest.java
index 48eeede7b3..0a74b360c2 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaRequest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaRequest.java
@@ -22,114 +22,109 @@ package org.onap.so.apihandler.camundabeans;
-
-
import org.onap.so.apihandler.common.CommonConstants;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
/**
- * JavaBean JSON class for a "variables" which contains the xml payload that
- * will be passed to the Camunda process
+ * JavaBean JSON class for a "variables" which contains the xml payload that will be passed to the Camunda process
*
*/
-@JsonPropertyOrder({ CommonConstants.CAMUNDA_SERVICE_INPUT, CommonConstants.CAMUNDA_HOST,
- CommonConstants.SCHEMA_VERSION_HEADER, CommonConstants.REQUEST_ID_HEADER, CommonConstants.SERVICE_INSTANCE_ID_HEADER,
- CommonConstants. REQUEST_TIMEOUT_HEADER, CommonConstants.CAMUNDA_SERVICE_INPUT})
+@JsonPropertyOrder({CommonConstants.CAMUNDA_SERVICE_INPUT, CommonConstants.CAMUNDA_HOST,
+ CommonConstants.SCHEMA_VERSION_HEADER, CommonConstants.REQUEST_ID_HEADER,
+ CommonConstants.SERVICE_INSTANCE_ID_HEADER, CommonConstants.REQUEST_TIMEOUT_HEADER,
+ CommonConstants.CAMUNDA_SERVICE_INPUT})
@JsonRootName(CommonConstants.CAMUNDA_ROOT_INPUT)
public class CamundaRequest {
- @JsonProperty(CommonConstants.CAMUNDA_SERVICE_INPUT)
- private CamundaInput serviceInput;
-
- @JsonProperty(CommonConstants.CAMUNDA_HOST)
- private CamundaInput host;
-
- @JsonProperty(CommonConstants.SCHEMA_VERSION_HEADER)
- private CamundaInput schema;
-
- @JsonProperty(CommonConstants.REQUEST_ID_HEADER)
- private CamundaInput reqid;
-
- @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_HEADER)
- private CamundaInput svcid;
-
- @JsonProperty(CommonConstants.REQUEST_TIMEOUT_HEADER)
- private CamundaInput timeout;
-
- public CamundaRequest() {
- }
-
- @JsonProperty(CommonConstants.CAMUNDA_SERVICE_INPUT)
- public CamundaInput getServiceInput() {
- return serviceInput;
- }
-
- @JsonProperty(CommonConstants.CAMUNDA_SERVICE_INPUT)
- public void setServiceInput(CamundaInput serviceInput) {
- this.serviceInput = serviceInput;
- }
-
- @JsonProperty(CommonConstants.CAMUNDA_HOST)
- public CamundaInput getHost() {
- return host;
- }
-
- @JsonProperty(CommonConstants.CAMUNDA_HOST)
- public void setHost(CamundaInput host) {
- this.host = host;
- }
-
- @JsonProperty(CommonConstants.SCHEMA_VERSION_HEADER)
- public CamundaInput getSchema() {
- return schema;
- }
-
- @JsonProperty(CommonConstants.SCHEMA_VERSION_HEADER)
- public void setSchema(CamundaInput schema) {
- this.schema = schema;
- }
-
- @JsonProperty(CommonConstants.REQUEST_ID_HEADER)
- public CamundaInput getReqid() {
- return reqid;
- }
-
- @JsonProperty(CommonConstants.REQUEST_ID_HEADER)
- public void setReqid(CamundaInput reqid) {
- this.reqid = reqid;
- }
-
- @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_HEADER)
- public CamundaInput getSvcid() {
- return svcid;
- }
-
- @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_HEADER)
- public void setSvcid(CamundaInput svcid) {
- this.svcid = svcid;
- }
-
-
- @JsonProperty(CommonConstants.REQUEST_TIMEOUT_HEADER)
- public CamundaInput getTimeout() {
- return timeout;
- }
-
- @JsonProperty(CommonConstants.REQUEST_TIMEOUT_HEADER)
- public void setTimeout(CamundaInput timeout) {
- this.timeout = timeout;
- }
-
-
-
- @Override
- public String toString() {
- return "CamundaRequest [serviceInput=" + serviceInput + ", host="
- + host + ", schema=" + schema + ", reqid=" + reqid + ", svcid="
- + svcid + ", timeout=" + timeout + "]";
- }
-
+ @JsonProperty(CommonConstants.CAMUNDA_SERVICE_INPUT)
+ private CamundaInput serviceInput;
+
+ @JsonProperty(CommonConstants.CAMUNDA_HOST)
+ private CamundaInput host;
+
+ @JsonProperty(CommonConstants.SCHEMA_VERSION_HEADER)
+ private CamundaInput schema;
+
+ @JsonProperty(CommonConstants.REQUEST_ID_HEADER)
+ private CamundaInput reqid;
+
+ @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_HEADER)
+ private CamundaInput svcid;
+
+ @JsonProperty(CommonConstants.REQUEST_TIMEOUT_HEADER)
+ private CamundaInput timeout;
+
+ public CamundaRequest() {}
+
+ @JsonProperty(CommonConstants.CAMUNDA_SERVICE_INPUT)
+ public CamundaInput getServiceInput() {
+ return serviceInput;
+ }
+
+ @JsonProperty(CommonConstants.CAMUNDA_SERVICE_INPUT)
+ public void setServiceInput(CamundaInput serviceInput) {
+ this.serviceInput = serviceInput;
+ }
+
+ @JsonProperty(CommonConstants.CAMUNDA_HOST)
+ public CamundaInput getHost() {
+ return host;
+ }
+
+ @JsonProperty(CommonConstants.CAMUNDA_HOST)
+ public void setHost(CamundaInput host) {
+ this.host = host;
+ }
+
+ @JsonProperty(CommonConstants.SCHEMA_VERSION_HEADER)
+ public CamundaInput getSchema() {
+ return schema;
+ }
+
+ @JsonProperty(CommonConstants.SCHEMA_VERSION_HEADER)
+ public void setSchema(CamundaInput schema) {
+ this.schema = schema;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_ID_HEADER)
+ public CamundaInput getReqid() {
+ return reqid;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_ID_HEADER)
+ public void setReqid(CamundaInput reqid) {
+ this.reqid = reqid;
+ }
+
+ @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_HEADER)
+ public CamundaInput getSvcid() {
+ return svcid;
+ }
+
+ @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_HEADER)
+ public void setSvcid(CamundaInput svcid) {
+ this.svcid = svcid;
+ }
+
+
+ @JsonProperty(CommonConstants.REQUEST_TIMEOUT_HEADER)
+ public CamundaInput getTimeout() {
+ return timeout;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_TIMEOUT_HEADER)
+ public void setTimeout(CamundaInput timeout) {
+ this.timeout = timeout;
+ }
+
+
+
+ @Override
+ public String toString() {
+ return "CamundaRequest [serviceInput=" + serviceInput + ", host=" + host + ", schema=" + schema + ", reqid="
+ + reqid + ", svcid=" + svcid + ", timeout=" + timeout + "]";
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java
index 92f4542b82..8977f11e36 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java
@@ -23,74 +23,70 @@ package org.onap.so.apihandler.camundabeans;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
- * JavaBean JSON class for a "variables" which contains the xml payload that
- * will be passed to the Camunda process
+ * JavaBean JSON class for a "variables" which contains the xml payload that will be passed to the Camunda process
*
*/
public class CamundaResponse {
-
- @JsonProperty("response")
- private String response;
- @JsonProperty("messageCode")
- private int messageCode;
- @JsonProperty("message")
- private String message;
- @JsonProperty("processInstanceID")
- private String processInstanceID;
- @JsonProperty("variables")
- private String variables;
-
- public String getProcessInstanceID() {
- return processInstanceID;
- }
-
- public void setProcessInstanceID(String processInstanceID) {
- this.processInstanceID = processInstanceID;
- }
-
- public String getVariables() {
- return variables;
- }
-
- public void setVariables(String variables) {
- this.variables = variables;
- }
-
- public CamundaResponse() {
- }
-
- public String getResponse() {
- return response;
- }
-
- public void setResponse(String response) {
- this.response = response;
- }
-
- public int getMessageCode() {
- return messageCode;
- }
-
- public void setMessageCode(int messageCode) {
- this.messageCode = messageCode;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- @Override
- public String toString() {
- return "CamundaResponse [response=" + response + ", messageCode="
- + messageCode + ", message=" + message + "]";
- }
-
-
-
-
+
+ @JsonProperty("response")
+ private String response;
+ @JsonProperty("messageCode")
+ private int messageCode;
+ @JsonProperty("message")
+ private String message;
+ @JsonProperty("processInstanceID")
+ private String processInstanceID;
+ @JsonProperty("variables")
+ private String variables;
+
+ public String getProcessInstanceID() {
+ return processInstanceID;
+ }
+
+ public void setProcessInstanceID(String processInstanceID) {
+ this.processInstanceID = processInstanceID;
+ }
+
+ public String getVariables() {
+ return variables;
+ }
+
+ public void setVariables(String variables) {
+ this.variables = variables;
+ }
+
+ public CamundaResponse() {}
+
+ public String getResponse() {
+ return response;
+ }
+
+ public void setResponse(String response) {
+ this.response = response;
+ }
+
+ public int getMessageCode() {
+ return messageCode;
+ }
+
+ public void setMessageCode(int messageCode) {
+ this.messageCode = messageCode;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ @Override
+ public String toString() {
+ return "CamundaResponse [response=" + response + ", messageCode=" + messageCode + ", message=" + message + "]";
+ }
+
+
+
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java
index 7e9eed32b1..3880bd43b1 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java
@@ -22,330 +22,331 @@ package org.onap.so.apihandler.camundabeans;
import org.onap.so.apihandler.common.CommonConstants;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;
/**
- * JavaBean JSON class for a "variables" which contains the JSON payload that
- * will be passed to the Camunda process
+ * JavaBean JSON class for a "variables" which contains the JSON payload that will be passed to the Camunda process
*/
@JsonPropertyOrder({CommonConstants.CAMUNDA_SERVICE_INPUT, CommonConstants.REQUEST_ID_VARIABLE,
- CommonConstants.REQUEST_ID_HEADER,
- CommonConstants.IS_BASE_VF_MODULE_VARIABLE, CommonConstants.RECIPE_TIMEOUT_VARIABLE,
- CommonConstants.REQUEST_ACTION_VARIABLE, CommonConstants.SERVICE_INSTANCE_ID_VARIABLE,
- CommonConstants.PNF_CORRELATION_ID, CommonConstants.VNF_ID_VARIABLE, CommonConstants.VF_MODULE_ID_VARIABLE,
- CommonConstants.VOLUME_GROUP_ID_VARIABLE, CommonConstants.NETWORK_ID_VARIABLE,
- CommonConstants.CONFIGURATION_ID_VARIABLE, CommonConstants.SERVICE_TYPE_VARIABLE,
- CommonConstants.VNF_TYPE_VARIABLE, CommonConstants.VF_MODULE_TYPE_VARIABLE,
- CommonConstants.NETWORK_TYPE_VARIABLE, CommonConstants.CAMUNDA_SERVICE_INPUT, CommonConstants.RECIPE_PARAMS})
+ CommonConstants.REQUEST_ID_HEADER, CommonConstants.IS_BASE_VF_MODULE_VARIABLE,
+ CommonConstants.RECIPE_TIMEOUT_VARIABLE, CommonConstants.REQUEST_ACTION_VARIABLE,
+ CommonConstants.SERVICE_INSTANCE_ID_VARIABLE, CommonConstants.PNF_CORRELATION_ID,
+ CommonConstants.VNF_ID_VARIABLE, CommonConstants.VF_MODULE_ID_VARIABLE,
+ CommonConstants.VOLUME_GROUP_ID_VARIABLE, CommonConstants.NETWORK_ID_VARIABLE,
+ CommonConstants.CONFIGURATION_ID_VARIABLE, CommonConstants.SERVICE_TYPE_VARIABLE,
+ CommonConstants.VNF_TYPE_VARIABLE, CommonConstants.VF_MODULE_TYPE_VARIABLE,
+ CommonConstants.NETWORK_TYPE_VARIABLE, CommonConstants.CAMUNDA_SERVICE_INPUT, CommonConstants.RECIPE_PARAMS})
@JsonRootName(CommonConstants.CAMUNDA_ROOT_INPUT)
public class CamundaVIDRequest {
- @JsonProperty(CommonConstants.CAMUNDA_SERVICE_INPUT)
- private CamundaInput serviceInput;
-
- @JsonProperty(CommonConstants.CAMUNDA_HOST)
- private CamundaInput host;
+ @JsonProperty(CommonConstants.CAMUNDA_SERVICE_INPUT)
+ private CamundaInput serviceInput;
+
+ @JsonProperty(CommonConstants.CAMUNDA_HOST)
+ private CamundaInput host;
+
+ @JsonProperty(CommonConstants.REQUEST_ID_VARIABLE)
+ private CamundaInput requestId;
+
+ @JsonProperty(CommonConstants.REQUEST_ID_HEADER)
+ private CamundaInput msoRequestId;
+
+ @JsonProperty(CommonConstants.IS_BASE_VF_MODULE_VARIABLE)
+ private CamundaBooleanInput isBaseVfModule;
+
+ @JsonProperty(CommonConstants.RECIPE_TIMEOUT_VARIABLE)
+ private CamundaIntegerInput recipeTimeout;
+
+ @JsonProperty(CommonConstants.REQUEST_ACTION_VARIABLE)
+ private CamundaInput requestAction;
+
+ @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE)
+ private CamundaInput serviceInstanceId;
+
+ @JsonProperty(CommonConstants.PNF_CORRELATION_ID)
+ private CamundaInput pnfCorrelationId;
+
+ @JsonProperty(CommonConstants.VNF_ID_VARIABLE)
+ private CamundaInput vnfId;
+
+ @JsonProperty(CommonConstants.VF_MODULE_ID_VARIABLE)
+ private CamundaInput vfModuleId;
+
+ @JsonProperty(CommonConstants.VOLUME_GROUP_ID_VARIABLE)
+ private CamundaInput volumeGroupId;
+
+ @JsonProperty(CommonConstants.NETWORK_ID_VARIABLE)
+ private CamundaInput networkId;
+
+ @JsonProperty(CommonConstants.CONFIGURATION_ID_VARIABLE)
+ private CamundaInput configurationId;
+
+ @JsonProperty(CommonConstants.SERVICE_TYPE_VARIABLE)
+ private CamundaInput serviceType;
+
+ @JsonProperty(CommonConstants.VNF_TYPE_VARIABLE)
+ private CamundaInput vnfType;
+
+ @JsonProperty(CommonConstants.VF_MODULE_TYPE_VARIABLE)
+ private CamundaInput vfModuleType;
+
+ @JsonProperty(CommonConstants.NETWORK_TYPE_VARIABLE)
+ private CamundaInput networkType;
+
+ @JsonProperty(CommonConstants.RECIPE_PARAMS)
+ private CamundaInput recipeParams;
+
+ @JsonProperty(CommonConstants.API_VERSION)
+ private CamundaInput apiVersion;
+
+ @JsonProperty(CommonConstants.ALACARTE)
+ private CamundaBooleanInput aLaCarte;
+
+ @JsonProperty(CommonConstants.REQUEST_URI)
+ private CamundaInput requestUri;
+
+ @JsonProperty(CommonConstants.INSTANCE_GROUP_ID)
+ private CamundaInput instanceGroupId;
+
+ @JsonProperty(CommonConstants.CAMUNDA_SERVICE_INPUT)
+ public CamundaInput getServiceInput() {
+ return serviceInput;
+ }
+
+ @JsonProperty(CommonConstants.CAMUNDA_SERVICE_INPUT)
+ public void setServiceInput(CamundaInput serviceInput) {
+ this.serviceInput = serviceInput;
+ }
+
+ @JsonProperty(CommonConstants.CAMUNDA_HOST)
+ public CamundaInput getHost() {
+ return host;
+ }
+
+ @JsonProperty(CommonConstants.CAMUNDA_HOST)
+ public void setHost(CamundaInput host) {
+ this.host = host;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_ID_VARIABLE)
+ public CamundaInput getRequestId() {
+ return requestId;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_ID_VARIABLE)
+ public void setRequestId(CamundaInput requestId) {
+ this.requestId = requestId;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_ID_HEADER)
+ public CamundaInput getMsoRequestId() {
+ return msoRequestId;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_ID_HEADER)
+ public void setMsoRequestId(CamundaInput msoRequestIdp) {
+ this.msoRequestId = msoRequestIdp;
+ }
+
+ @JsonProperty(CommonConstants.IS_BASE_VF_MODULE_VARIABLE)
+ public CamundaBooleanInput getIsBaseVfModule() {
+ return isBaseVfModule;
+ }
+
+ @JsonProperty(CommonConstants.IS_BASE_VF_MODULE_VARIABLE)
+ public void setIsBaseVfModule(CamundaBooleanInput isBaseVfModule) {
+ this.isBaseVfModule = isBaseVfModule;
+ }
+
+ @JsonProperty(CommonConstants.RECIPE_TIMEOUT_VARIABLE)
+ public CamundaIntegerInput getRecipeTimeout() {
+ return recipeTimeout;
+ }
+
+ @JsonProperty(CommonConstants.RECIPE_TIMEOUT_VARIABLE)
+ public void setRecipeTimeout(CamundaIntegerInput recipeTimeout) {
+ this.recipeTimeout = recipeTimeout;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_ACTION_VARIABLE)
+ public CamundaInput getRequestAction() {
+ return requestAction;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_ACTION_VARIABLE)
+ public void setRequestAction(CamundaInput requestAction) {
+ this.requestAction = requestAction;
+ }
+
+ @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE)
+ public CamundaInput getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE)
+ public void setServiceInstanceId(CamundaInput serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ @JsonProperty(CommonConstants.PNF_CORRELATION_ID)
+ public CamundaInput getPnfCorrelationId() {
+ return pnfCorrelationId;
+ }
+
+ @JsonProperty(CommonConstants.PNF_CORRELATION_ID)
+ public void setPnfCorrelationId(CamundaInput pnfCorrelationId) {
+ this.pnfCorrelationId = pnfCorrelationId;
+ }
+
+ @JsonProperty(CommonConstants.VNF_ID_VARIABLE)
+ public CamundaInput getVnfId() {
+ return vnfId;
+ }
+
+ @JsonProperty(CommonConstants.VNF_ID_VARIABLE)
+ public void setVnfId(CamundaInput vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ @JsonProperty(CommonConstants.VF_MODULE_ID_VARIABLE)
+ public CamundaInput getVfModuleId() {
+ return vfModuleId;
+ }
+
+ @JsonProperty(CommonConstants.VF_MODULE_ID_VARIABLE)
+ public void setVfModuleId(CamundaInput vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ @JsonProperty(CommonConstants.VOLUME_GROUP_ID_VARIABLE)
+ public CamundaInput getVolumeGroupId() {
+ return volumeGroupId;
+ }
+
+ @JsonProperty(CommonConstants.VOLUME_GROUP_ID_VARIABLE)
+ public void setVolumeGroupId(CamundaInput volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+
+ @JsonProperty(CommonConstants.NETWORK_ID_VARIABLE)
+ public CamundaInput getNetworkId() {
+ return networkId;
+ }
+
+ @JsonProperty(CommonConstants.NETWORK_ID_VARIABLE)
+ public void setNetworkId(CamundaInput networkId) {
+ this.networkId = networkId;
+ }
+
+ @JsonProperty(CommonConstants.CONFIGURATION_ID_VARIABLE)
+ public CamundaInput getConfigurationId() {
+ return configurationId;
+ }
+
+ @JsonProperty(CommonConstants.CONFIGURATION_ID_VARIABLE)
+ public void setConfigurationId(CamundaInput configurationId) {
+ this.configurationId = configurationId;
+ }
+
+ @JsonProperty(CommonConstants.SERVICE_TYPE_VARIABLE)
+ public CamundaInput getServiceType() {
+ return serviceType;
+ }
+
+ @JsonProperty(CommonConstants.SERVICE_TYPE_VARIABLE)
+ public void setServiceType(CamundaInput serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ @JsonProperty(CommonConstants.VNF_TYPE_VARIABLE)
+ public CamundaInput getVnfType() {
+ return vnfType;
+ }
+
+ @JsonProperty(CommonConstants.VNF_TYPE_VARIABLE)
+ public void setVnfType(CamundaInput vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ @JsonProperty(CommonConstants.VF_MODULE_TYPE_VARIABLE)
+ public CamundaInput getVfModuleType() {
+ return vfModuleType;
+ }
+
+ @JsonProperty(CommonConstants.VF_MODULE_TYPE_VARIABLE)
+ public void setVfModuleType(CamundaInput vfModuleType) {
+ this.vfModuleType = vfModuleType;
+ }
+
+ @JsonProperty(CommonConstants.NETWORK_TYPE_VARIABLE)
+ public CamundaInput getNetworkType() {
+ return networkType;
+ }
+
+ @JsonProperty(CommonConstants.NETWORK_TYPE_VARIABLE)
+ public void setNetworkType(CamundaInput networkType) {
+ this.networkType = networkType;
+ }
+
+ @JsonProperty(CommonConstants.API_VERSION)
+ public CamundaInput getApiVersion() {
+ return apiVersion;
+ }
+
+ @JsonProperty(CommonConstants.API_VERSION)
+ public void setApiVersion(CamundaInput apiVersion) {
+ this.apiVersion = apiVersion;
+ }
+
+ @JsonProperty(CommonConstants.ALACARTE)
+ public CamundaBooleanInput getaLaCarte() {
+ return aLaCarte;
+ }
+
+ @JsonProperty(CommonConstants.ALACARTE)
+ public void setaLaCarte(CamundaBooleanInput aLaCarte) {
+ this.aLaCarte = aLaCarte;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_URI)
+ public CamundaInput getRequestUri() {
+ return requestUri;
+ }
+
+ @JsonProperty(CommonConstants.REQUEST_URI)
+ public void setRequestUri(CamundaInput requestUri) {
+ this.requestUri = requestUri;
+ }
+
+ public CamundaInput getRecipeParams() {
+ return recipeParams;
+ }
+
+ public void setRecipeParams(CamundaInput recipeParams) {
+ this.recipeParams = recipeParams;
+ }
+
+ @JsonProperty(CommonConstants.INSTANCE_GROUP_ID)
+ public void setInstanceGroupId(CamundaInput instanceGroupIdInput) {
+ this.instanceGroupId = instanceGroupIdInput;
+ }
+
+ @JsonProperty(CommonConstants.INSTANCE_GROUP_ID)
+ public CamundaInput getInstanceGroupId() {
+ return instanceGroupId;
+ }
+
+ @Override
+ public String toString() {
+ // return "CamundaRequest [requestId=" + + ", host="
+ // + host + ", schema=" + schema + ", reqid=" + reqid + ", svcid="
+ // + svcid + ", timeout=" + timeout + "]";
+ return "CamundaRequest";
+ }
- @JsonProperty(CommonConstants.REQUEST_ID_VARIABLE)
- private CamundaInput requestId;
- @JsonProperty(CommonConstants.REQUEST_ID_HEADER)
- private CamundaInput msoRequestId;
-
- @JsonProperty(CommonConstants.IS_BASE_VF_MODULE_VARIABLE)
- private CamundaBooleanInput isBaseVfModule;
-
- @JsonProperty(CommonConstants.RECIPE_TIMEOUT_VARIABLE)
- private CamundaIntegerInput recipeTimeout;
-
- @JsonProperty(CommonConstants.REQUEST_ACTION_VARIABLE)
- private CamundaInput requestAction;
-
- @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE)
- private CamundaInput serviceInstanceId;
-
- @JsonProperty(CommonConstants.PNF_CORRELATION_ID)
- private CamundaInput pnfCorrelationId;
-
- @JsonProperty(CommonConstants.VNF_ID_VARIABLE)
- private CamundaInput vnfId;
-
- @JsonProperty(CommonConstants.VF_MODULE_ID_VARIABLE)
- private CamundaInput vfModuleId;
-
- @JsonProperty(CommonConstants.VOLUME_GROUP_ID_VARIABLE)
- private CamundaInput volumeGroupId;
-
- @JsonProperty(CommonConstants.NETWORK_ID_VARIABLE)
- private CamundaInput networkId;
-
- @JsonProperty(CommonConstants.CONFIGURATION_ID_VARIABLE)
- private CamundaInput configurationId;
-
- @JsonProperty(CommonConstants.SERVICE_TYPE_VARIABLE)
- private CamundaInput serviceType;
-
- @JsonProperty(CommonConstants.VNF_TYPE_VARIABLE)
- private CamundaInput vnfType;
-
- @JsonProperty(CommonConstants.VF_MODULE_TYPE_VARIABLE)
- private CamundaInput vfModuleType;
-
- @JsonProperty(CommonConstants.NETWORK_TYPE_VARIABLE)
- private CamundaInput networkType;
-
- @JsonProperty(CommonConstants.RECIPE_PARAMS)
- private CamundaInput recipeParams;
-
- @JsonProperty(CommonConstants.API_VERSION)
- private CamundaInput apiVersion;
-
- @JsonProperty(CommonConstants.ALACARTE)
- private CamundaBooleanInput aLaCarte;
-
- @JsonProperty(CommonConstants.REQUEST_URI)
- private CamundaInput requestUri;
-
- @JsonProperty(CommonConstants.INSTANCE_GROUP_ID)
- private CamundaInput instanceGroupId;
-
- @JsonProperty(CommonConstants.CAMUNDA_SERVICE_INPUT)
- public CamundaInput getServiceInput() {
- return serviceInput;
- }
-
- @JsonProperty(CommonConstants.CAMUNDA_SERVICE_INPUT)
- public void setServiceInput(CamundaInput serviceInput) {
- this.serviceInput = serviceInput;
- }
-
- @JsonProperty(CommonConstants.CAMUNDA_HOST)
- public CamundaInput getHost() {
- return host;
- }
-
- @JsonProperty(CommonConstants.CAMUNDA_HOST)
- public void setHost(CamundaInput host) {
- this.host = host;
- }
-
- @JsonProperty(CommonConstants.REQUEST_ID_VARIABLE)
- public CamundaInput getRequestId() {
- return requestId;
- }
-
- @JsonProperty(CommonConstants.REQUEST_ID_VARIABLE)
- public void setRequestId(CamundaInput requestId) {
- this.requestId = requestId;
- }
-
- @JsonProperty(CommonConstants.REQUEST_ID_HEADER)
- public CamundaInput getMsoRequestId() {
- return msoRequestId;
- }
-
- @JsonProperty(CommonConstants.REQUEST_ID_HEADER)
- public void setMsoRequestId(CamundaInput msoRequestIdp) {
- this.msoRequestId = msoRequestIdp;
- }
-
- @JsonProperty(CommonConstants.IS_BASE_VF_MODULE_VARIABLE)
- public CamundaBooleanInput getIsBaseVfModule() {
- return isBaseVfModule;
- }
-
- @JsonProperty(CommonConstants.IS_BASE_VF_MODULE_VARIABLE)
- public void setIsBaseVfModule(CamundaBooleanInput isBaseVfModule) {
- this.isBaseVfModule = isBaseVfModule;
- }
-
- @JsonProperty(CommonConstants.RECIPE_TIMEOUT_VARIABLE)
- public CamundaIntegerInput getRecipeTimeout() {
- return recipeTimeout;
- }
-
- @JsonProperty(CommonConstants.RECIPE_TIMEOUT_VARIABLE)
- public void setRecipeTimeout(CamundaIntegerInput recipeTimeout) {
- this.recipeTimeout = recipeTimeout;
- }
-
- @JsonProperty(CommonConstants.REQUEST_ACTION_VARIABLE)
- public CamundaInput getRequestAction() {
- return requestAction;
- }
-
- @JsonProperty(CommonConstants.REQUEST_ACTION_VARIABLE)
- public void setRequestAction(CamundaInput requestAction) {
- this.requestAction = requestAction;
- }
- @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE)
- public CamundaInput getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE)
- public void setServiceInstanceId(CamundaInput serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
-
- @JsonProperty(CommonConstants.PNF_CORRELATION_ID)
- public CamundaInput getPnfCorrelationId() {
- return pnfCorrelationId;
- }
-
- @JsonProperty(CommonConstants.PNF_CORRELATION_ID)
- public void setPnfCorrelationId(CamundaInput pnfCorrelationId) {
- this.pnfCorrelationId = pnfCorrelationId;
- }
-
- @JsonProperty(CommonConstants.VNF_ID_VARIABLE)
- public CamundaInput getVnfId() {
- return vnfId;
- }
-
- @JsonProperty(CommonConstants.VNF_ID_VARIABLE)
- public void setVnfId(CamundaInput vnfId) {
- this.vnfId = vnfId;
- }
-
- @JsonProperty(CommonConstants.VF_MODULE_ID_VARIABLE)
- public CamundaInput getVfModuleId() {
- return vfModuleId;
- }
-
- @JsonProperty(CommonConstants.VF_MODULE_ID_VARIABLE)
- public void setVfModuleId(CamundaInput vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
-
- @JsonProperty(CommonConstants.VOLUME_GROUP_ID_VARIABLE)
- public CamundaInput getVolumeGroupId() {
- return volumeGroupId;
- }
-
- @JsonProperty(CommonConstants.VOLUME_GROUP_ID_VARIABLE)
- public void setVolumeGroupId(CamundaInput volumeGroupId) {
- this.volumeGroupId = volumeGroupId;
- }
-
- @JsonProperty(CommonConstants.NETWORK_ID_VARIABLE)
- public CamundaInput getNetworkId() {
- return networkId;
- }
-
- @JsonProperty(CommonConstants.NETWORK_ID_VARIABLE)
- public void setNetworkId(CamundaInput networkId) {
- this.networkId = networkId;
- }
-
- @JsonProperty(CommonConstants.CONFIGURATION_ID_VARIABLE)
- public CamundaInput getConfigurationId() {
- return configurationId;
- }
-
- @JsonProperty(CommonConstants.CONFIGURATION_ID_VARIABLE)
- public void setConfigurationId(CamundaInput configurationId) {
- this.configurationId = configurationId;
- }
-
- @JsonProperty(CommonConstants.SERVICE_TYPE_VARIABLE)
- public CamundaInput getServiceType() {
- return serviceType;
- }
-
- @JsonProperty(CommonConstants.SERVICE_TYPE_VARIABLE)
- public void setServiceType(CamundaInput serviceType) {
- this.serviceType = serviceType;
- }
-
- @JsonProperty(CommonConstants.VNF_TYPE_VARIABLE)
- public CamundaInput getVnfType() {
- return vnfType;
- }
-
- @JsonProperty(CommonConstants.VNF_TYPE_VARIABLE)
- public void setVnfType(CamundaInput vnfType) {
- this.vnfType = vnfType;
- }
-
- @JsonProperty(CommonConstants.VF_MODULE_TYPE_VARIABLE)
- public CamundaInput getVfModuleType() {
- return vfModuleType;
- }
-
- @JsonProperty(CommonConstants.VF_MODULE_TYPE_VARIABLE)
- public void setVfModuleType(CamundaInput vfModuleType) {
- this.vfModuleType = vfModuleType;
- }
-
- @JsonProperty(CommonConstants.NETWORK_TYPE_VARIABLE)
- public CamundaInput getNetworkType() {
- return networkType;
- }
-
- @JsonProperty(CommonConstants.NETWORK_TYPE_VARIABLE)
- public void setNetworkType(CamundaInput networkType) {
- this.networkType = networkType;
- }
-
- @JsonProperty(CommonConstants.API_VERSION)
- public CamundaInput getApiVersion() {
- return apiVersion;
- }
-
- @JsonProperty(CommonConstants.API_VERSION)
- public void setApiVersion(CamundaInput apiVersion) {
- this.apiVersion = apiVersion;
- }
-
- @JsonProperty(CommonConstants.ALACARTE)
- public CamundaBooleanInput getaLaCarte() {
- return aLaCarte;
- }
-
- @JsonProperty(CommonConstants.ALACARTE)
- public void setaLaCarte(CamundaBooleanInput aLaCarte) {
- this.aLaCarte = aLaCarte;
- }
-
- @JsonProperty(CommonConstants.REQUEST_URI)
- public CamundaInput getRequestUri() {
- return requestUri;
- }
-
- @JsonProperty(CommonConstants.REQUEST_URI)
- public void setRequestUri(CamundaInput requestUri) {
- this.requestUri = requestUri;
- }
-
- public CamundaInput getRecipeParams() {
- return recipeParams;
- }
-
- public void setRecipeParams(CamundaInput recipeParams) {
- this.recipeParams = recipeParams;
- }
- @JsonProperty(CommonConstants.INSTANCE_GROUP_ID)
- public void setInstanceGroupId(CamundaInput instanceGroupIdInput) {
- this.instanceGroupId = instanceGroupIdInput;
- }
- @JsonProperty(CommonConstants.INSTANCE_GROUP_ID)
- public CamundaInput getInstanceGroupId() {
- return instanceGroupId;
- }
-
- @Override
- public String toString() {
- //return "CamundaRequest [requestId=" + + ", host="
- // + host + ", schema=" + schema + ", reqid=" + reqid + ", svcid="
- // + svcid + ", timeout=" + timeout + "]";
- return "CamundaRequest";
- }
-
-
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/Track.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/Track.java
index 3d4dc85089..112ab9966e 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/Track.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/Track.java
@@ -22,28 +22,28 @@ package org.onap.so.apihandler.camundabeans;
public class Track {
- String title;
- String singer;
+ String title;
+ String singer;
- public String getTitle() {
- return title;
- }
+ public String getTitle() {
+ return title;
+ }
- public void setTitle(String title) {
- this.title = title;
- }
+ public void setTitle(String title) {
+ this.title = title;
+ }
- public String getSinger() {
- return singer;
- }
+ public String getSinger() {
+ return singer;
+ }
- public void setSinger(String singer) {
- this.singer = singer;
- }
+ public void setSinger(String singer) {
+ this.singer = singer;
+ }
- @Override
- public String toString() {
- return "Track [title=" + title + ", singer=" + singer + "]";
- }
+ @Override
+ public String toString() {
+ return "Track [title=" + title + ", singer=" + singer + "]";
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java
index 9b77c1469b..d11f1706e9 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java
@@ -26,9 +26,7 @@ package org.onap.so.apihandler.common;
import java.io.IOException;
import java.util.UUID;
-
import javax.xml.bind.DatatypeConverter;
-
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
@@ -45,263 +43,270 @@ import org.onap.so.logger.MessageEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
-public class CamundaClient extends RequestClient{
- private static Logger logger = LoggerFactory.getLogger(CamundaClient.class);
- private static final String CAMUNDA_URL_MESAGE = "Camunda url is: ";
-
- public CamundaClient() {
- super(CommonConstants.CAMUNDA);
- }
-
-
- @Override
- public HttpResponse post(String camundaReqXML, String requestId,
- String requestTimeout, String schemaVersion, String serviceInstanceId, String action)
- throws ClientProtocolException, IOException{
- HttpPost post = new HttpPost(url);
- logger.debug(CAMUNDA_URL_MESAGE + url);
- String jsonReq = wrapRequest(camundaReqXML, requestId, serviceInstanceId, requestTimeout, schemaVersion);
-
- StringEntity input = new StringEntity(jsonReq);
- input.setContentType(CommonConstants.CONTENT_TYPE_JSON);
- logger.info("Camunda Request Content: {}", jsonReq);
-
-
- post.setEntity(input);
- setupHeaders(post);
-
- HttpResponse response = client.execute(post);
- logger.debug("Response is: {}", response);
-
- return response;
- }
-
-
- private void setupHeaders(HttpPost post) {
- post.addHeader(ONAPLogConstants.Headers.REQUEST_ID, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
- post.addHeader(ONAPLogConstants.Headers.INVOCATION_ID, UUID.randomUUID().toString());
-
- String encryptedCredentials = null;
- if(props!=null){
- encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH);
- if(encryptedCredentials != null){
- String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP));
- if(userCredentials != null){
- post.addHeader("Authorization", "Basic " + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes())));
- }
- }
- }
- }
-
- @Override
- public HttpResponse post(String jsonReq)
- throws ClientProtocolException, IOException{
- HttpPost post = new HttpPost(url);
- logger.debug(CAMUNDA_URL_MESAGE + url);
-
- StringEntity input = new StringEntity(jsonReq);
- input.setContentType(CommonConstants.CONTENT_TYPE_JSON);
- setupHeaders(post);
-
- String encryptedCredentials = null;
- if(props!=null){
- encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH);
- if(encryptedCredentials != null){
- String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP));
- if(userCredentials != null){
- post.addHeader("Authorization", "Basic " + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes())));
- }
- }
- }
-
-
- post.setEntity(input);
- HttpResponse response = client.execute(post);
- logger.debug("Response is: {}", response);
-
- return response;
- }
-
- public HttpResponse post(RequestClientParameter parameterObject)
- throws ClientProtocolException, IOException{
- HttpPost post = new HttpPost(url);
- logger.debug(CAMUNDA_URL_MESAGE+ url);
- String jsonReq = wrapVIDRequest(parameterObject.getRequestId(), parameterObject.isBaseVfModule(), parameterObject.getRecipeTimeout(), parameterObject.getRequestAction(),
- parameterObject.getServiceInstanceId(), parameterObject.getPnfCorrelationId(), parameterObject.getVnfId(), parameterObject.getVfModuleId(), parameterObject.getVolumeGroupId(), parameterObject.getNetworkId(), parameterObject.getConfigurationId(),
- parameterObject.getServiceType(), parameterObject.getVnfType(), parameterObject.getVfModuleType(), parameterObject.getNetworkType(), parameterObject.getRequestDetails(), parameterObject.getApiVersion(), parameterObject.isaLaCarte(), parameterObject.getRequestUri(), parameterObject.getRecipeParamXsd(),
- parameterObject.getInstanceGroupId());
-
- StringEntity input = new StringEntity(jsonReq);
- input.setContentType(CommonConstants.CONTENT_TYPE_JSON);
-
-
- setupHeaders(post);
-
- String encryptedCredentials = null;
- if(props!=null){
- encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH);
- if(encryptedCredentials != null){
- String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP));
- if(userCredentials != null){
- post.addHeader("Authorization", "Basic " + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes())));
- }
- }
- }
-
- post.setEntity(input);
- HttpResponse response = client.execute(post);
- logger.debug("Response is: {}", response);
-
- return response;
- }
-
- @Override
+public class CamundaClient extends RequestClient {
+ private static Logger logger = LoggerFactory.getLogger(CamundaClient.class);
+ private static final String CAMUNDA_URL_MESAGE = "Camunda url is: ";
+
+ public CamundaClient() {
+ super(CommonConstants.CAMUNDA);
+ }
+
+
+ @Override
+ public HttpResponse post(String camundaReqXML, String requestId, String requestTimeout, String schemaVersion,
+ String serviceInstanceId, String action) throws ClientProtocolException, IOException {
+ HttpPost post = new HttpPost(url);
+ logger.debug(CAMUNDA_URL_MESAGE + url);
+ String jsonReq = wrapRequest(camundaReqXML, requestId, serviceInstanceId, requestTimeout, schemaVersion);
+
+ StringEntity input = new StringEntity(jsonReq);
+ input.setContentType(CommonConstants.CONTENT_TYPE_JSON);
+ logger.info("Camunda Request Content: {}", jsonReq);
+
+
+ post.setEntity(input);
+ setupHeaders(post);
+
+ HttpResponse response = client.execute(post);
+ logger.debug("Response is: {}", response);
+
+ return response;
+ }
+
+
+ private void setupHeaders(HttpPost post) {
+ post.addHeader(ONAPLogConstants.Headers.REQUEST_ID, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
+ post.addHeader(ONAPLogConstants.Headers.INVOCATION_ID, UUID.randomUUID().toString());
+
+ String encryptedCredentials = null;
+ if (props != null) {
+ encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH);
+ if (encryptedCredentials != null) {
+ String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH,
+ props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP));
+ if (userCredentials != null) {
+ post.addHeader("Authorization",
+ "Basic " + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes())));
+ }
+ }
+ }
+ }
+
+ @Override
+ public HttpResponse post(String jsonReq) throws ClientProtocolException, IOException {
+ HttpPost post = new HttpPost(url);
+ logger.debug(CAMUNDA_URL_MESAGE + url);
+
+ StringEntity input = new StringEntity(jsonReq);
+ input.setContentType(CommonConstants.CONTENT_TYPE_JSON);
+ setupHeaders(post);
+
+ String encryptedCredentials = null;
+ if (props != null) {
+ encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH);
+ if (encryptedCredentials != null) {
+ String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH,
+ props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP));
+ if (userCredentials != null) {
+ post.addHeader("Authorization",
+ "Basic " + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes())));
+ }
+ }
+ }
+
+
+ post.setEntity(input);
+ HttpResponse response = client.execute(post);
+ logger.debug("Response is: {}", response);
+
+ return response;
+ }
+
+ public HttpResponse post(RequestClientParameter parameterObject) throws ClientProtocolException, IOException {
+ HttpPost post = new HttpPost(url);
+ logger.debug(CAMUNDA_URL_MESAGE + url);
+ String jsonReq = wrapVIDRequest(parameterObject.getRequestId(), parameterObject.isBaseVfModule(),
+ parameterObject.getRecipeTimeout(), parameterObject.getRequestAction(),
+ parameterObject.getServiceInstanceId(), parameterObject.getPnfCorrelationId(),
+ parameterObject.getVnfId(), parameterObject.getVfModuleId(), parameterObject.getVolumeGroupId(),
+ parameterObject.getNetworkId(), parameterObject.getConfigurationId(), parameterObject.getServiceType(),
+ parameterObject.getVnfType(), parameterObject.getVfModuleType(), parameterObject.getNetworkType(),
+ parameterObject.getRequestDetails(), parameterObject.getApiVersion(), parameterObject.isaLaCarte(),
+ parameterObject.getRequestUri(), parameterObject.getRecipeParamXsd(),
+ parameterObject.getInstanceGroupId());
+
+ StringEntity input = new StringEntity(jsonReq);
+ input.setContentType(CommonConstants.CONTENT_TYPE_JSON);
+
+
+ setupHeaders(post);
+
+ String encryptedCredentials = null;
+ if (props != null) {
+ encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH);
+ if (encryptedCredentials != null) {
+ String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH,
+ props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP));
+ if (userCredentials != null) {
+ post.addHeader("Authorization",
+ "Basic " + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes())));
+ }
+ }
+ }
+
+ post.setEntity(input);
+ HttpResponse response = client.execute(post);
+ logger.debug("Response is: {}", response);
+
+ return response;
+ }
+
+ @Override
public HttpResponse get() {
return null;
}
- protected String wrapRequest(String reqXML, String requestId, String serviceInstanceId, String requestTimeout, String schemaVersion){
- String jsonReq = null;
-
- try{
- CamundaRequest camundaRequest = new CamundaRequest();
- CamundaInput camundaInput = new CamundaInput();
- CamundaInput host = new CamundaInput();
- CamundaInput schema = new CamundaInput();
- CamundaInput reqid = new CamundaInput();
- CamundaInput svcid = new CamundaInput();
- CamundaInput timeout = new CamundaInput();
- camundaInput.setValue(StringUtils.defaultString(reqXML));
- host.setValue(parseURL());
- schema.setValue(StringUtils.defaultString(schemaVersion));
- reqid.setValue(requestId);
- svcid.setValue(serviceInstanceId);
- timeout.setValue(StringUtils.defaultString(requestTimeout));
- camundaRequest.setServiceInput(camundaInput);
- camundaRequest.setHost(host);
- camundaRequest.setReqid(reqid);
- camundaRequest.setSvcid(svcid);
- camundaRequest.setSchema(schema);
- camundaRequest.setTimeout(timeout);
- ObjectMapper mapper = new ObjectMapper();
-
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
-
- jsonReq = mapper.writeValueAsString(camundaRequest);
- logger.trace("request body is {}", jsonReq);
- }catch(Exception e){
- logger.error("{} {} {} {} {}", MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapRequest",
- ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e);
- }
- return jsonReq;
- }
-
-
- protected String wrapVIDRequest(String requestId, boolean isBaseVfModule,
- int recipeTimeout, String requestAction, String serviceInstanceId, String pnfCorrelationId,
- String vnfId, String vfModuleId, String volumeGroupId, String networkId, String configurationId,
- String serviceType, String vnfType, String vfModuleType, String networkType,
- String requestDetails, String apiVersion, boolean aLaCarte, String requestUri, String paramXsd,
- String instanceGroupId){
- String jsonReq = null;
-
- try{
- CamundaVIDRequest camundaRequest = new CamundaVIDRequest();
- CamundaInput serviceInput = new CamundaInput();
- CamundaInput host = new CamundaInput();
- CamundaInput requestIdInput= new CamundaInput();
- CamundaBooleanInput isBaseVfModuleInput = new CamundaBooleanInput();
- CamundaIntegerInput recipeTimeoutInput = new CamundaIntegerInput();
- CamundaInput requestActionInput = new CamundaInput();
- CamundaInput serviceInstanceIdInput = new CamundaInput();
- CamundaInput pnfCorrelationIdInput = new CamundaInput();
- CamundaInput vnfIdInput = new CamundaInput();
- CamundaInput vfModuleIdInput = new CamundaInput();
- CamundaInput volumeGroupIdInput = new CamundaInput();
- CamundaInput networkIdInput = new CamundaInput();
- CamundaInput configurationIdInput = new CamundaInput();
- CamundaInput serviceTypeInput = new CamundaInput();
- CamundaInput vnfTypeInput = new CamundaInput();
- CamundaInput vfModuleTypeInput = new CamundaInput();
- CamundaInput networkTypeInput = new CamundaInput();
- CamundaBooleanInput aLaCarteInput = new CamundaBooleanInput();
- CamundaInput apiVersionInput = new CamundaInput();
- CamundaInput requestUriInput = new CamundaInput();
- CamundaInput recipeParamsInput = new CamundaInput();
- CamundaInput instanceGroupIdInput = new CamundaInput();
-
- //host.setValue(parseURL());
- requestIdInput.setValue(StringUtils.defaultString(requestId));
- isBaseVfModuleInput.setValue(isBaseVfModule);
- recipeTimeoutInput.setValue(recipeTimeout);
- requestActionInput.setValue(StringUtils.defaultString(requestAction));
- serviceInstanceIdInput.setValue(StringUtils.defaultString(serviceInstanceId));
- pnfCorrelationIdInput.setValue(StringUtils.defaultString(pnfCorrelationId));
- vnfIdInput.setValue(StringUtils.defaultString(vnfId));
- vfModuleIdInput.setValue(StringUtils.defaultString(vfModuleId));
- volumeGroupIdInput.setValue(StringUtils.defaultString(volumeGroupId));
- networkIdInput.setValue(StringUtils.defaultString(networkId));
- configurationIdInput.setValue(StringUtils.defaultString(configurationId));
- serviceTypeInput.setValue(StringUtils.defaultString(serviceType));
- vnfTypeInput.setValue(StringUtils.defaultString(vnfType));
- vfModuleTypeInput.setValue(StringUtils.defaultString(vfModuleType));
- networkTypeInput.setValue(StringUtils.defaultString(networkType));
- aLaCarteInput.setValue(aLaCarte);
- apiVersionInput.setValue(StringUtils.defaultString(apiVersion));
- requestUriInput.setValue(StringUtils.defaultString(requestUri));
- recipeParamsInput.setValue(paramXsd);
- instanceGroupIdInput.setValue(StringUtils.defaultString(instanceGroupId));
-
- serviceInput.setValue(requestDetails);
- camundaRequest.setServiceInput(serviceInput);
- camundaRequest.setHost(host);
- camundaRequest.setRequestId(requestIdInput);
- camundaRequest.setMsoRequestId(requestIdInput);
- camundaRequest.setIsBaseVfModule(isBaseVfModuleInput);
- camundaRequest.setRecipeTimeout(recipeTimeoutInput);
- camundaRequest.setRequestAction(requestActionInput);
- camundaRequest.setServiceInstanceId(serviceInstanceIdInput);
- camundaRequest.setPnfCorrelationId(pnfCorrelationIdInput);
- camundaRequest.setVnfId(vnfIdInput);
- camundaRequest.setVfModuleId(vfModuleIdInput);
- camundaRequest.setVolumeGroupId(volumeGroupIdInput);
- camundaRequest.setNetworkId(networkIdInput);
- camundaRequest.setConfigurationId(configurationIdInput);
- camundaRequest.setServiceType(serviceTypeInput);
- camundaRequest.setVnfType(vnfTypeInput);
- camundaRequest.setVfModuleType(vfModuleTypeInput);
- camundaRequest.setNetworkType(networkTypeInput);
- camundaRequest.setaLaCarte(aLaCarteInput);
- camundaRequest.setApiVersion(apiVersionInput);
- camundaRequest.setRequestUri(requestUriInput);
- camundaRequest.setRecipeParams(recipeParamsInput);
- camundaRequest.setInstanceGroupId(instanceGroupIdInput);
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
-
- jsonReq = mapper.writeValueAsString(camundaRequest);
- logger.trace("request body is {}", jsonReq);
- }catch(Exception e){
- logger.error("{} {} {} {} {}", MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapVIDRequest",
- ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e);
- }
- return jsonReq;
- }
-
- private String parseURL(){
- String[] parts = url.split(":");
- String host = "";
- if(parts.length>=2){
- host = parts[1];
- if(host.length()>2){
- host = host.substring(2);
- }
- }
- return host;
- }
+ protected String wrapRequest(String reqXML, String requestId, String serviceInstanceId, String requestTimeout,
+ String schemaVersion) {
+ String jsonReq = null;
+
+ try {
+ CamundaRequest camundaRequest = new CamundaRequest();
+ CamundaInput camundaInput = new CamundaInput();
+ CamundaInput host = new CamundaInput();
+ CamundaInput schema = new CamundaInput();
+ CamundaInput reqid = new CamundaInput();
+ CamundaInput svcid = new CamundaInput();
+ CamundaInput timeout = new CamundaInput();
+ camundaInput.setValue(StringUtils.defaultString(reqXML));
+ host.setValue(parseURL());
+ schema.setValue(StringUtils.defaultString(schemaVersion));
+ reqid.setValue(requestId);
+ svcid.setValue(serviceInstanceId);
+ timeout.setValue(StringUtils.defaultString(requestTimeout));
+ camundaRequest.setServiceInput(camundaInput);
+ camundaRequest.setHost(host);
+ camundaRequest.setReqid(reqid);
+ camundaRequest.setSvcid(svcid);
+ camundaRequest.setSchema(schema);
+ camundaRequest.setTimeout(timeout);
+ ObjectMapper mapper = new ObjectMapper();
+
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
+
+ jsonReq = mapper.writeValueAsString(camundaRequest);
+ logger.trace("request body is {}", jsonReq);
+ } catch (Exception e) {
+ logger.error("{} {} {} {} {}", MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapRequest",
+ ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e);
+ }
+ return jsonReq;
+ }
+
+
+ protected String wrapVIDRequest(String requestId, boolean isBaseVfModule, int recipeTimeout, String requestAction,
+ String serviceInstanceId, String pnfCorrelationId, String vnfId, String vfModuleId, String volumeGroupId,
+ String networkId, String configurationId, String serviceType, String vnfType, String vfModuleType,
+ String networkType, String requestDetails, String apiVersion, boolean aLaCarte, String requestUri,
+ String paramXsd, String instanceGroupId) {
+ String jsonReq = null;
+
+ try {
+ CamundaVIDRequest camundaRequest = new CamundaVIDRequest();
+ CamundaInput serviceInput = new CamundaInput();
+ CamundaInput host = new CamundaInput();
+ CamundaInput requestIdInput = new CamundaInput();
+ CamundaBooleanInput isBaseVfModuleInput = new CamundaBooleanInput();
+ CamundaIntegerInput recipeTimeoutInput = new CamundaIntegerInput();
+ CamundaInput requestActionInput = new CamundaInput();
+ CamundaInput serviceInstanceIdInput = new CamundaInput();
+ CamundaInput pnfCorrelationIdInput = new CamundaInput();
+ CamundaInput vnfIdInput = new CamundaInput();
+ CamundaInput vfModuleIdInput = new CamundaInput();
+ CamundaInput volumeGroupIdInput = new CamundaInput();
+ CamundaInput networkIdInput = new CamundaInput();
+ CamundaInput configurationIdInput = new CamundaInput();
+ CamundaInput serviceTypeInput = new CamundaInput();
+ CamundaInput vnfTypeInput = new CamundaInput();
+ CamundaInput vfModuleTypeInput = new CamundaInput();
+ CamundaInput networkTypeInput = new CamundaInput();
+ CamundaBooleanInput aLaCarteInput = new CamundaBooleanInput();
+ CamundaInput apiVersionInput = new CamundaInput();
+ CamundaInput requestUriInput = new CamundaInput();
+ CamundaInput recipeParamsInput = new CamundaInput();
+ CamundaInput instanceGroupIdInput = new CamundaInput();
+
+ // host.setValue(parseURL());
+ requestIdInput.setValue(StringUtils.defaultString(requestId));
+ isBaseVfModuleInput.setValue(isBaseVfModule);
+ recipeTimeoutInput.setValue(recipeTimeout);
+ requestActionInput.setValue(StringUtils.defaultString(requestAction));
+ serviceInstanceIdInput.setValue(StringUtils.defaultString(serviceInstanceId));
+ pnfCorrelationIdInput.setValue(StringUtils.defaultString(pnfCorrelationId));
+ vnfIdInput.setValue(StringUtils.defaultString(vnfId));
+ vfModuleIdInput.setValue(StringUtils.defaultString(vfModuleId));
+ volumeGroupIdInput.setValue(StringUtils.defaultString(volumeGroupId));
+ networkIdInput.setValue(StringUtils.defaultString(networkId));
+ configurationIdInput.setValue(StringUtils.defaultString(configurationId));
+ serviceTypeInput.setValue(StringUtils.defaultString(serviceType));
+ vnfTypeInput.setValue(StringUtils.defaultString(vnfType));
+ vfModuleTypeInput.setValue(StringUtils.defaultString(vfModuleType));
+ networkTypeInput.setValue(StringUtils.defaultString(networkType));
+ aLaCarteInput.setValue(aLaCarte);
+ apiVersionInput.setValue(StringUtils.defaultString(apiVersion));
+ requestUriInput.setValue(StringUtils.defaultString(requestUri));
+ recipeParamsInput.setValue(paramXsd);
+ instanceGroupIdInput.setValue(StringUtils.defaultString(instanceGroupId));
+
+ serviceInput.setValue(requestDetails);
+ camundaRequest.setServiceInput(serviceInput);
+ camundaRequest.setHost(host);
+ camundaRequest.setRequestId(requestIdInput);
+ camundaRequest.setMsoRequestId(requestIdInput);
+ camundaRequest.setIsBaseVfModule(isBaseVfModuleInput);
+ camundaRequest.setRecipeTimeout(recipeTimeoutInput);
+ camundaRequest.setRequestAction(requestActionInput);
+ camundaRequest.setServiceInstanceId(serviceInstanceIdInput);
+ camundaRequest.setPnfCorrelationId(pnfCorrelationIdInput);
+ camundaRequest.setVnfId(vnfIdInput);
+ camundaRequest.setVfModuleId(vfModuleIdInput);
+ camundaRequest.setVolumeGroupId(volumeGroupIdInput);
+ camundaRequest.setNetworkId(networkIdInput);
+ camundaRequest.setConfigurationId(configurationIdInput);
+ camundaRequest.setServiceType(serviceTypeInput);
+ camundaRequest.setVnfType(vnfTypeInput);
+ camundaRequest.setVfModuleType(vfModuleTypeInput);
+ camundaRequest.setNetworkType(networkTypeInput);
+ camundaRequest.setaLaCarte(aLaCarteInput);
+ camundaRequest.setApiVersion(apiVersionInput);
+ camundaRequest.setRequestUri(requestUriInput);
+ camundaRequest.setRecipeParams(recipeParamsInput);
+ camundaRequest.setInstanceGroupId(instanceGroupIdInput);
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
+
+ jsonReq = mapper.writeValueAsString(camundaRequest);
+ logger.trace("request body is {}", jsonReq);
+ } catch (Exception e) {
+ logger.error("{} {} {} {} {}", MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapVIDRequest",
+ ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e);
+ }
+ return jsonReq;
+ }
+
+ private String parseURL() {
+ String[] parts = url.split(":");
+ String host = "";
+ if (parts.length >= 2) {
+ host = parts[1];
+ if (host.length() > 2) {
+ host = host.substring(2);
+ }
+ }
+ return host;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaTaskClient.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaTaskClient.java
index d8c785dcb3..d6d999b4b5 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaTaskClient.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaTaskClient.java
@@ -23,9 +23,7 @@
package org.onap.so.apihandler.common;
import java.io.IOException;
-
import javax.xml.bind.DatatypeConverter;
-
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
@@ -33,64 +31,66 @@ import org.apache.http.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class CamundaTaskClient extends RequestClient{
- private static Logger logger = LoggerFactory.getLogger(CamundaTaskClient.class);
+public class CamundaTaskClient extends RequestClient {
+ private static Logger logger = LoggerFactory.getLogger(CamundaTaskClient.class);
+
+ public CamundaTaskClient() {
+ super(CommonConstants.CAMUNDATASK);
+ }
+
+ @Override
+ public HttpResponse post(String jsonReq) throws IOException {
+ HttpPost post = new HttpPost(url);
+ logger.debug("Camunda Task url is: {}", url);
- public CamundaTaskClient() {
- super(CommonConstants.CAMUNDATASK);
- }
-
- @Override
- public HttpResponse post(String jsonReq) throws IOException{
- HttpPost post = new HttpPost(url);
- logger.debug("Camunda Task url is: {}", url);
+ StringEntity input = new StringEntity(jsonReq);
+ input.setContentType(CommonConstants.CONTENT_TYPE_JSON);
- StringEntity input = new StringEntity(jsonReq);
- input.setContentType(CommonConstants.CONTENT_TYPE_JSON);
+ String encryptedCredentials;
+ if (props != null) {
+ encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH);
+ if (encryptedCredentials != null) {
+ String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH,
+ props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP));
+ if (userCredentials != null) {
+ post.addHeader("Authorization",
+ "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()));
+ }
+ }
+ }
- String encryptedCredentials;
- if(props!=null){
- encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH);
- if(encryptedCredentials != null){
- String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP));
- if(userCredentials != null){
- post.addHeader("Authorization", "Basic " + DatatypeConverter
- .printBase64Binary(userCredentials.getBytes()));
- }
- }
- }
+ post.setEntity(input);
+ return client.execute(post);
+ }
- post.setEntity(input);
- return client.execute(post);
- }
-
- @Override
- public HttpResponse post(String camundaReqXML, String requestId,
- String requestTimeout, String schemaVersion, String serviceInstanceId, String action) {
- throw new UnsupportedOperationException("Method not supported.");
- }
+ @Override
+ public HttpResponse post(String camundaReqXML, String requestId, String requestTimeout, String schemaVersion,
+ String serviceInstanceId, String action) {
+ throw new UnsupportedOperationException("Method not supported.");
+ }
- @Override
- public HttpResponse post(RequestClientParameter params) {
- throw new UnsupportedOperationException("Method not supported.");
- }
+ @Override
+ public HttpResponse post(RequestClientParameter params) {
+ throw new UnsupportedOperationException("Method not supported.");
+ }
- @Override
- public HttpResponse get() throws IOException {
- HttpGet get = new HttpGet(url);
- logger.debug("Camunda Task url is: {}", url);
- String encryptedCredentials;
- if(props!=null){
- encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH);
- if(encryptedCredentials != null){
- String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP));
- if(userCredentials != null){
- get.addHeader("Authorization", "Basic " + new String(DatatypeConverter
- .printBase64Binary(userCredentials.getBytes())));
- }
- }
- }
- return client.execute(get);
- }
+ @Override
+ public HttpResponse get() throws IOException {
+ HttpGet get = new HttpGet(url);
+ logger.debug("Camunda Task url is: {}", url);
+ String encryptedCredentials;
+ if (props != null) {
+ encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH);
+ if (encryptedCredentials != null) {
+ String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH,
+ props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP));
+ if (userCredentials != null) {
+ get.addHeader("Authorization",
+ "Basic " + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes())));
+ }
+ }
+ }
+ return client.execute(get);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CommonConstants.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CommonConstants.java
index 1dece5c341..e48c98a395 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CommonConstants.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CommonConstants.java
@@ -32,57 +32,57 @@ public final class CommonConstants {
public static final String SERVICE_INSTANCE_ID_HEADER = "mso-service-instance-id";
public static final String ACTION_HEADER = "mso-action";
- public static final String G_REQUEST_ID = "mso-request-id";
- public static final String G_SERVICEINSTANCEID = "serviceInstanceId";
- public static final String G_ACTION = "gAction";
+ public static final String G_REQUEST_ID = "mso-request-id";
+ public static final String G_SERVICEINSTANCEID = "serviceInstanceId";
+ public static final String G_ACTION = "gAction";
- public static final String CAMUNDA_SERVICE_INPUT = "bpmnRequest";
- public static final String CAMUNDA_ROOT_INPUT = "variables";
- public static final String CONTENT_TYPE_JSON= "application/json";
- public static final String CAMUNDA_TYPE = "type";
- public static final String CAMUNDA_VALUE = "value";
- public static final String CAMUNDA_URL = "mso.camundaURL";
- public static final String CAMUNDA_AUTH = "mso.camundaAuth";
- public static final String BPEL_SEARCH_STR = "active-bpel";
- public static final String TASK_SEARCH_STR = "task";
- public static final int BPEL = 0;
- public static final int CAMUNDA = 1;
- public static final int CAMUNDATASK = 2;
- public static final String CAMUNDA_HOST = "host";
- public static final String REQUEST_ID_VARIABLE = "requestId";
- public static final String IS_BASE_VF_MODULE_VARIABLE = "isBaseVfModule";
- public static final String RECIPE_TIMEOUT_VARIABLE = "recipeTimeout";
- public static final String REQUEST_ACTION_VARIABLE = "requestAction";
- public static final String SERVICE_INSTANCE_ID_VARIABLE = "serviceInstanceId";
- public static final String PNF_CORRELATION_ID = "pnfCorrelationId";
- public static final String VNF_ID_VARIABLE = "vnfId";
- public static final String VF_MODULE_ID_VARIABLE = "vfModuleId";
- public static final String VOLUME_GROUP_ID_VARIABLE = "volumeGroupId";
- public static final String NETWORK_ID_VARIABLE = "networkId";
- public static final String CONFIGURATION_ID_VARIABLE = "configurationId";
- public static final String SERVICE_TYPE_VARIABLE = "serviceType";
- public static final String VNF_TYPE_VARIABLE = "vnfType";
- public static final String VF_MODULE_TYPE_VARIABLE = "vfModuleType";
- public static final String NETWORK_TYPE_VARIABLE = "networkType";
- public static final String REQUEST_DETAILS_VARIABLE = "requestDetails";
- public static final String ALACARTE_ORCHESTRATION = "mso.infra.default.alacarte.orchestrationUri";
- public static final String ALACARTE_RECIPE_TIMEOUT = "mso.infra.default.alacarte.recipeTimeout";
- public static final String RECIPE_PARAMS = "recipeParams";
- public static final String ALACARTE_TEST_API = "mso.infra.default.alacarte.testApi";
- public static final String MACRO_TEST_API = "mso.infra.service.macro.default.testApi";
- public static final String ALACARTE = "aLaCarte";
- public static final String API_VERSION = "apiVersion";
- public static final String REQUEST_URI = "requestUri";
- public static final String API_MINOR_VERSION = "mso.infra.default.versions.apiMinorVersion";
- public static final String API_PATCH_VERSION = "mso.infra.default.versions.apiPatchVersion";
- public static final String X_TRANSACTION_ID = "X-TransactionID";
- public static final String X_MINOR_VERSION = "X-MinorVersion";
- public static final String X_PATCH_VERSION = "X-PatchVersion";
- public static final String X_LATEST_VERSION = "X-LatestVersion";
- public static final String INSTANCE_GROUP_ID = "instanceGroupId";
- public static final String INSTANCE_GROUP_INSTANCE_ID = "instanceGroupInstanceId";
-
- private CommonConstants () {
- // prevent creating an instance of this class
- }
+ public static final String CAMUNDA_SERVICE_INPUT = "bpmnRequest";
+ public static final String CAMUNDA_ROOT_INPUT = "variables";
+ public static final String CONTENT_TYPE_JSON = "application/json";
+ public static final String CAMUNDA_TYPE = "type";
+ public static final String CAMUNDA_VALUE = "value";
+ public static final String CAMUNDA_URL = "mso.camundaURL";
+ public static final String CAMUNDA_AUTH = "mso.camundaAuth";
+ public static final String BPEL_SEARCH_STR = "active-bpel";
+ public static final String TASK_SEARCH_STR = "task";
+ public static final int BPEL = 0;
+ public static final int CAMUNDA = 1;
+ public static final int CAMUNDATASK = 2;
+ public static final String CAMUNDA_HOST = "host";
+ public static final String REQUEST_ID_VARIABLE = "requestId";
+ public static final String IS_BASE_VF_MODULE_VARIABLE = "isBaseVfModule";
+ public static final String RECIPE_TIMEOUT_VARIABLE = "recipeTimeout";
+ public static final String REQUEST_ACTION_VARIABLE = "requestAction";
+ public static final String SERVICE_INSTANCE_ID_VARIABLE = "serviceInstanceId";
+ public static final String PNF_CORRELATION_ID = "pnfCorrelationId";
+ public static final String VNF_ID_VARIABLE = "vnfId";
+ public static final String VF_MODULE_ID_VARIABLE = "vfModuleId";
+ public static final String VOLUME_GROUP_ID_VARIABLE = "volumeGroupId";
+ public static final String NETWORK_ID_VARIABLE = "networkId";
+ public static final String CONFIGURATION_ID_VARIABLE = "configurationId";
+ public static final String SERVICE_TYPE_VARIABLE = "serviceType";
+ public static final String VNF_TYPE_VARIABLE = "vnfType";
+ public static final String VF_MODULE_TYPE_VARIABLE = "vfModuleType";
+ public static final String NETWORK_TYPE_VARIABLE = "networkType";
+ public static final String REQUEST_DETAILS_VARIABLE = "requestDetails";
+ public static final String ALACARTE_ORCHESTRATION = "mso.infra.default.alacarte.orchestrationUri";
+ public static final String ALACARTE_RECIPE_TIMEOUT = "mso.infra.default.alacarte.recipeTimeout";
+ public static final String RECIPE_PARAMS = "recipeParams";
+ public static final String ALACARTE_TEST_API = "mso.infra.default.alacarte.testApi";
+ public static final String MACRO_TEST_API = "mso.infra.service.macro.default.testApi";
+ public static final String ALACARTE = "aLaCarte";
+ public static final String API_VERSION = "apiVersion";
+ public static final String REQUEST_URI = "requestUri";
+ public static final String API_MINOR_VERSION = "mso.infra.default.versions.apiMinorVersion";
+ public static final String API_PATCH_VERSION = "mso.infra.default.versions.apiPatchVersion";
+ public static final String X_TRANSACTION_ID = "X-TransactionID";
+ public static final String X_MINOR_VERSION = "X-MinorVersion";
+ public static final String X_PATCH_VERSION = "X-PatchVersion";
+ public static final String X_LATEST_VERSION = "X-LatestVersion";
+ public static final String INSTANCE_GROUP_ID = "instanceGroupId";
+ public static final String INSTANCE_GROUP_INSTANCE_ID = "instanceGroupInstanceId";
+
+ private CommonConstants() {
+ // prevent creating an instance of this class
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ErrorNumbers.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ErrorNumbers.java
index 5d755b9529..468fe61562 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ErrorNumbers.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ErrorNumbers.java
@@ -19,11 +19,10 @@
*/
package org.onap.so.apihandler.common;
-
+
public final class ErrorNumbers {
- private ErrorNumbers() {
- }
+ private ErrorNumbers() {}
public static final String REQUEST_FAILED_SCHEMA_VALIDATION = "1000";
public static final String RECIPE_DOES_NOT_EXIST = "1010";
@@ -48,7 +47,7 @@ public final class ErrorNumbers {
public static final String DISCONNECT_ALREADY_COMPLETE = "1100";
public static final String CANCEL_ALREADY_COMPLETE = "1110";
-
+
public static final String LOCKED_CREATE_ON_THE_SAME_VNF_NAME_IN_PROGRESS = "1400";
public static final String LOCKED_SAME_ACTION_AND_VNF_ID = "1410";
@@ -68,7 +67,7 @@ public final class ErrorNumbers {
public static final String NO_COMMUNICATION_TO_SDNC_ADAPTER = "7000";
public static final String NO_RESPONSE_FROM_SDNC_ADAPTER = "7010";
public static final String ERROR_FROM_SDNC_ADAPTER = "7020";
-
+
public static final String SVC_GENERAL_SERVICE_ERROR = "SVC0001";
public static final String SVC_BAD_PARAMETER = "SVC0002";
public static final String SVC_NO_SERVER_RESOURCES = "SVC1000";
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/LSInputImpl.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/LSInputImpl.java
index 60473fb8c4..a8085cfaaf 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/LSInputImpl.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/LSInputImpl.java
@@ -23,7 +23,6 @@ package org.onap.so.apihandler.common;
import java.io.InputStream;
import java.io.Reader;
-
import org.w3c.dom.ls.LSInput;
public class LSInputImpl implements LSInput {
@@ -38,82 +37,82 @@ public class LSInputImpl implements LSInput {
protected boolean fCertifiedText;
@Override
- public InputStream getByteStream () {
+ public InputStream getByteStream() {
return fByteStream;
}
@Override
- public void setByteStream (InputStream byteStream) {
+ public void setByteStream(InputStream byteStream) {
fByteStream = byteStream;
}
@Override
- public Reader getCharacterStream () {
+ public Reader getCharacterStream() {
return fCharStream;
}
@Override
- public void setCharacterStream (Reader characterStream) {
+ public void setCharacterStream(Reader characterStream) {
fCharStream = characterStream;
}
@Override
- public String getStringData () {
+ public String getStringData() {
return fData;
}
@Override
- public void setStringData (String stringData) {
+ public void setStringData(String stringData) {
fData = stringData;
}
@Override
- public String getEncoding () {
+ public String getEncoding() {
return fEncoding;
}
@Override
- public void setEncoding (String encoding) {
+ public void setEncoding(String encoding) {
fEncoding = encoding;
}
@Override
- public String getPublicId () {
+ public String getPublicId() {
return fPublicId;
}
@Override
- public void setPublicId (String publicId) {
+ public void setPublicId(String publicId) {
fPublicId = publicId;
}
@Override
- public String getSystemId () {
+ public String getSystemId() {
return fSystemId;
}
@Override
- public void setSystemId (String systemId) {
+ public void setSystemId(String systemId) {
fSystemId = systemId;
}
@Override
- public String getBaseURI () {
+ public String getBaseURI() {
return fBaseSystemId;
}
@Override
- public void setBaseURI (String baseURI) {
+ public void setBaseURI(String baseURI) {
fBaseSystemId = baseURI;
}
@Override
- public boolean getCertifiedText () {
+ public boolean getCertifiedText() {
return fCertifiedText;
}
@Override
- public void setCertifiedText (boolean certifiedText) {
+ public void setCertifiedText(boolean certifiedText) {
fCertifiedText = certifiedText;
}
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java
index ee1ea8e562..ad8cc3f250 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java
@@ -27,40 +27,39 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
public class PathResourceResolver implements LSResourceResolver {
-
+
private static Logger logger = LoggerFactory.getLogger(PathResourceResolver.class);
private String path;
-
+
public PathResourceResolver(String path) {
-
- this.path = path;
+
+ this.path = path;
}
-
+
@Override
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
-
+
LSInputImpl input = new LSInputImpl();
-
+
InputStream stream = null;
- try {
- stream = new FileInputStream(path + systemId);
- } catch (FileNotFoundException e) {
- logger.debug ("Could not resolve resource based on file: {}", path + systemId, e);
- }
-
+ try {
+ stream = new FileInputStream(path + systemId);
+ } catch (FileNotFoundException e) {
+ logger.debug("Could not resolve resource based on file: {}", path + systemId, e);
+ }
+
input.setPublicId(publicId);
input.setSystemId(systemId);
input.setBaseURI(baseURI);
input.setCharacterStream(new InputStreamReader(stream));
-
+
return input;
}
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java
index 9f5c8460a1..0aac35d5a9 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java
@@ -24,7 +24,6 @@ package org.onap.so.apihandler.common;
import java.io.IOException;
import java.security.GeneralSecurityException;
-
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
@@ -34,72 +33,70 @@ import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
public abstract class RequestClient {
- private static Logger logger = LoggerFactory.getLogger(RequestClient.class);
- protected Environment props;
- protected String url;
- protected HttpClient client;
- private int type;
-
- public RequestClient(int type){
- this.type = type;
- }
-
- public void setProps(Environment env) {
- this.props = env;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public String getUrl() {
- return url;
- }
-
- public int getType(){
- return type;
- }
-
- public HttpClient getClient() {
- return client;
- }
-
- public void setClient(HttpClient client) {
- this.client = client;
- }
-
- public abstract HttpResponse post(String request, String requestId, String requestTimeout, String schemaVersion, String serviceInstanceId, String action) throws IOException;
-
- public abstract HttpResponse post(String request) throws ClientProtocolException, IOException;
-
- public abstract HttpResponse post(RequestClientParameter parameterObject) throws ClientProtocolException, IOException;
-
- public abstract HttpResponse get()
- throws IOException;
-
- protected String decryptPropValue(String prop, String defaultValue, String encryptionKey) {
- try {
- String result = CryptoUtils.decrypt(prop, encryptionKey);
- return result;
- }
- catch (GeneralSecurityException e) {
- logger.debug("Security exception", e);
- }
- return defaultValue;
- }
-
- protected String getEncryptedPropValue (String prop, String defaultValue, String encryptionKey) {
- try {
- String result = CryptoUtils.decrypt(prop, encryptionKey);
- return result;
- }
- catch (GeneralSecurityException e) {
- logger.debug("Security exception", e);
- }
- return defaultValue;
- }
-
-
+ private static Logger logger = LoggerFactory.getLogger(RequestClient.class);
+ protected Environment props;
+ protected String url;
+ protected HttpClient client;
+ private int type;
+
+ public RequestClient(int type) {
+ this.type = type;
+ }
+
+ public void setProps(Environment env) {
+ this.props = env;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public int getType() {
+ return type;
+ }
+
+ public HttpClient getClient() {
+ return client;
+ }
+
+ public void setClient(HttpClient client) {
+ this.client = client;
+ }
+
+ public abstract HttpResponse post(String request, String requestId, String requestTimeout, String schemaVersion,
+ String serviceInstanceId, String action) throws IOException;
+
+ public abstract HttpResponse post(String request) throws ClientProtocolException, IOException;
+
+ public abstract HttpResponse post(RequestClientParameter parameterObject)
+ throws ClientProtocolException, IOException;
+
+ public abstract HttpResponse get() throws IOException;
+
+ protected String decryptPropValue(String prop, String defaultValue, String encryptionKey) {
+ try {
+ String result = CryptoUtils.decrypt(prop, encryptionKey);
+ return result;
+ } catch (GeneralSecurityException e) {
+ logger.debug("Security exception", e);
+ }
+ return defaultValue;
+ }
+
+ protected String getEncryptedPropValue(String prop, String defaultValue, String encryptionKey) {
+ try {
+ String result = CryptoUtils.decrypt(prop, encryptionKey);
+ return result;
+ } catch (GeneralSecurityException e) {
+ logger.debug("Security exception", e);
+ }
+ return defaultValue;
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java
index e94f186c60..4149d5ee45 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java
@@ -22,7 +22,6 @@ package org.onap.so.apihandler.common;
-
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
@@ -30,39 +29,37 @@ import org.springframework.stereotype.Component;
@Component
public class RequestClientFactory {
-
- @Autowired
- private Environment env;
-
- //based on URI, returns BPEL, CamundaTask or Camunda client
- public RequestClient getRequestClient(String orchestrationURI) throws IllegalStateException{
- RequestClient retClient;
- String url;
- if(orchestrationURI.contains(CommonConstants.TASK_SEARCH_STR)){
- url = env.getProperty(CommonConstants.CAMUNDA_URL) + orchestrationURI;
- retClient = new CamundaTaskClient();
- }
- else{
- url = env.getProperty(CommonConstants.CAMUNDA_URL) + orchestrationURI;
- retClient = new CamundaClient();
- }
- retClient.setClient(new DefaultHttpClient());
- retClient.setProps(env);
- retClient.setUrl(url);
- return retClient;
-
- }
+ @Autowired
+ private Environment env;
+
+ // based on URI, returns BPEL, CamundaTask or Camunda client
+ public RequestClient getRequestClient(String orchestrationURI) throws IllegalStateException {
+ RequestClient retClient;
+
+ String url;
+ if (orchestrationURI.contains(CommonConstants.TASK_SEARCH_STR)) {
+ url = env.getProperty(CommonConstants.CAMUNDA_URL) + orchestrationURI;
+ retClient = new CamundaTaskClient();
+ } else {
+ url = env.getProperty(CommonConstants.CAMUNDA_URL) + orchestrationURI;
+ retClient = new CamundaClient();
+ }
+ retClient.setClient(new DefaultHttpClient());
+ retClient.setProps(env);
+ retClient.setUrl(url);
+ return retClient;
+
+ }
+
+ public Environment getEnv() {
+ return env;
+ }
- public Environment getEnv() {
- return env;
- }
+ public void setEnv(Environment env) {
+ this.env = env;
+ }
- public void setEnv(Environment env) {
- this.env = env;
- }
-
-
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java
index 209f337a1e..20c512af37 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java
@@ -40,10 +40,10 @@ public class RequestClientParameter {
private String networkType;
private String requestDetails;
private String apiVersion;
- private boolean aLaCarte;
+ private boolean aLaCarte;
private String recipeParamXsd;
- private String requestUri;
- private String instanceGroupId;
+ private String requestUri;
+ private String instanceGroupId;
private RequestClientParameter(Builder builder) {
requestId = builder.requestId;
@@ -67,7 +67,7 @@ public class RequestClientParameter {
aLaCarte = builder.aLaCarte;
requestUri = builder.requestUri;
instanceGroupId = builder.instanceGroupId;
-
+
}
public String getRequestId() {
@@ -139,22 +139,22 @@ public class RequestClientParameter {
}
public String getApiVersion() {
- return apiVersion;
- }
-
- public boolean isaLaCarte() {
- return aLaCarte;
- }
-
- public String getRequestUri() {
- return requestUri;
- }
-
- public String getInstanceGroupId() {
- return instanceGroupId;
- }
-
- public static class Builder {
+ return apiVersion;
+ }
+
+ public boolean isaLaCarte() {
+ return aLaCarte;
+ }
+
+ public String getRequestUri() {
+ return requestUri;
+ }
+
+ public String getInstanceGroupId() {
+ return instanceGroupId;
+ }
+
+ public static class Builder {
private String requestId;
private boolean isBaseVfModule = false;
private int recipeTimeout;
@@ -172,10 +172,10 @@ public class RequestClientParameter {
private String networkType;
private String requestDetails;
private String apiVersion;
- private boolean aLaCarte = false;
+ private boolean aLaCarte = false;
private String recipeParamXsd;
- private String requestUri;
- private String instanceGroupId;
+ private String requestUri;
+ private String instanceGroupId;
public Builder setRequestId(String requestId) {
this.requestId = requestId;
@@ -261,28 +261,28 @@ public class RequestClientParameter {
this.recipeParamXsd = recipeParamXsd;
return this;
}
-
+
public Builder setApiVersion(String apiVersion) {
- this.apiVersion = apiVersion;
- return this;
+ this.apiVersion = apiVersion;
+ return this;
}
-
+
public Builder setALaCarte(boolean aLaCarte) {
- this.aLaCarte = aLaCarte;
- return this;
+ this.aLaCarte = aLaCarte;
+ return this;
}
-
+
public Builder setRequestUri(String requestUri) {
- this.requestUri = requestUri;
- return this;
+ this.requestUri = requestUri;
+ return this;
}
-
+
public Builder setInstanceGroupId(String instanceGroupId) {
- this.instanceGroupId = instanceGroupId;
- return this;
- }
+ this.instanceGroupId = instanceGroupId;
+ return this;
+ }
- public RequestClientParameter build(){
+ public RequestClientParameter build() {
return new RequestClientParameter(this);
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java
index 6b43e96b08..fff4c1d508 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java
@@ -24,7 +24,6 @@ package org.onap.so.apihandler.common;
import java.io.IOException;
-
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
@@ -37,189 +36,205 @@ import org.onap.so.apihandlerinfra.exceptions.ValidateException;
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResponseHandler {
- private CamundaResponse response;
- private int status;
- private String responseBody="";
- private HttpResponse httpResponse;
- private int type;
- private static Logger logger = LoggerFactory.getLogger(ResponseHandler.class);
-
- public ResponseHandler(HttpResponse httpResponse, int type) throws ApiException{
- this.httpResponse = httpResponse;
- this.type=type;
- parseResponse();
- }
-
-
- private void parseResponse() throws ApiException{
- int statusCode = httpResponse.getStatusLine().getStatusCode();
- status = setStatus(statusCode);
- if(type==CommonConstants.CAMUNDA){
- parseCamunda();
- }else if(type==CommonConstants.CAMUNDATASK){
- parseCamundaTask();
- }else {
- parseBpel();
- }
-
- }
-
-
-
- private void parseCamunda() throws ApiException{
- try{
- HttpEntity entity = httpResponse.getEntity();
- responseBody = EntityUtils.toString(entity);
- } catch (IOException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-
-
- ValidateException validateException = new ValidateException.Builder("IOException getting Camunda response body", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
- throw validateException;
- }
-
- ObjectMapper mapper = new ObjectMapper();
- try {
- response = mapper.readValue(responseBody, CamundaResponse.class);
- } catch (IOException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-
-
- ValidateException validateException = new ValidateException.Builder("Cannot parse Camunda Response", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
- throw validateException;
- }
- if(response!=null){
- responseBody = response.getResponse();
- }else{
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER, ErrorCode.BusinessProcesssError)
- .targetEntity("Camunda").targetServiceName("parseCamunda").build();
- BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL)
- .errorInfo(errorLoggerInfo).build();
+ private CamundaResponse response;
+ private int status;
+ private String responseBody = "";
+ private HttpResponse httpResponse;
+ private int type;
+ private static Logger logger = LoggerFactory.getLogger(ResponseHandler.class);
+
+ public ResponseHandler(HttpResponse httpResponse, int type) throws ApiException {
+ this.httpResponse = httpResponse;
+ this.type = type;
+ parseResponse();
+ }
+
+
+ private void parseResponse() throws ApiException {
+ int statusCode = httpResponse.getStatusLine().getStatusCode();
+ status = setStatus(statusCode);
+ if (type == CommonConstants.CAMUNDA) {
+ parseCamunda();
+ } else if (type == CommonConstants.CAMUNDATASK) {
+ parseCamundaTask();
+ } else {
+ parseBpel();
+ }
+
+ }
+
+
+
+ private void parseCamunda() throws ApiException {
+ try {
+ HttpEntity entity = httpResponse.getEntity();
+ responseBody = EntityUtils.toString(entity);
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder("IOException getting Camunda response body",
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ throw validateException;
+ }
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ response = mapper.readValue(responseBody, CamundaResponse.class);
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder("Cannot parse Camunda Response", HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
+ throw validateException;
+ }
+ if (response != null) {
+ responseBody = response.getResponse();
+ } else {
+ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER,
+ ErrorCode.BusinessProcesssError).targetEntity("Camunda").targetServiceName("parseCamunda").build();
+ BPMNFailureException bpmnFailureException =
+ new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL)
+ .errorInfo(errorLoggerInfo).build();
+ }
+ }
+
+ private void parseBpel() throws ApiException {
+
+ HttpEntity bpelEntity = httpResponse.getEntity();
+
+ try {
+ if (bpelEntity != null) {
+ responseBody = EntityUtils.toString(bpelEntity);
+
+ }
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
+ ValidateException validateException =
+ new ValidateException.Builder("Could not convert BPEL response to string",
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ throw validateException;
+ }
+ if (status != HttpStatus.SC_ACCEPTED) {
+ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER,
+ ErrorCode.BusinessProcesssError).targetEntity("BPEL").targetServiceName("parseBpel").build();
+
+
+ BPMNFailureException bpmnFailureException =
+ new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL)
+ .errorInfo(errorLoggerInfo).build();
+
+ throw bpmnFailureException;
+ }
+
+ }
+
+ private void parseCamundaTask() throws ApiException {
+
+ HttpEntity camundataskEntity = httpResponse.getEntity();
+
+ try {
+ if (camundataskEntity != null) {
+ responseBody = EntityUtils.toString(camundataskEntity);
}
- }
-
- private void parseBpel() throws ApiException{
-
- HttpEntity bpelEntity = httpResponse.getEntity();
-
- try {
- if (bpelEntity != null) {
- responseBody = EntityUtils.toString(bpelEntity);
-
- }
- }catch(IOException e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
- ValidateException validateException = new ValidateException.Builder("Could not convert BPEL response to string", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
- throw validateException;
- }
- if(status!=HttpStatus.SC_ACCEPTED){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER, ErrorCode.BusinessProcesssError)
- .targetEntity("BPEL").targetServiceName("parseBpel").build();
-
-
- BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL)
- .errorInfo(errorLoggerInfo).build();
-
- throw bpmnFailureException;
- }
-
- }
-
- private void parseCamundaTask() throws ApiException{
-
- HttpEntity camundataskEntity = httpResponse.getEntity();
-
- try {
- if (camundataskEntity != null) {
- responseBody = EntityUtils.toString(camundataskEntity);
- }
- }catch(IOException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
-
-
- ValidateException validateException = new ValidateException.Builder("Could not convert CamundaTask response to string", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
- throw validateException;
- }
- if(status!=HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_ACCEPTED){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER, ErrorCode.BusinessProcesssError)
- .targetEntity("CAMUNDATASK").targetServiceName("parseCamundaTask").build();
-
-
- BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL)
- .errorInfo(errorLoggerInfo).build();
-
- throw bpmnFailureException;
- }
-
- }
-
- private int setStatus(int statusCode){
- int httpStatus;
- switch(statusCode) {
- case HttpStatus.SC_ACCEPTED:
- case HttpStatus.SC_OK:
- httpStatus = HttpStatus.SC_ACCEPTED;
- break;
- case HttpStatus.SC_BAD_REQUEST:
- httpStatus = HttpStatus.SC_BAD_REQUEST;
- break;
- case HttpStatus.SC_UNAUTHORIZED:
- case HttpStatus.SC_FORBIDDEN:
- httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
- break;
- case HttpStatus.SC_NOT_FOUND:
- httpStatus = HttpStatus.SC_NOT_IMPLEMENTED;
- break;
- case HttpStatus.SC_INTERNAL_SERVER_ERROR:
- httpStatus = HttpStatus.SC_BAD_GATEWAY;
- break;
- case HttpStatus.SC_SERVICE_UNAVAILABLE:
- httpStatus = HttpStatus.SC_SERVICE_UNAVAILABLE;
- break;
- case HttpStatus.SC_NO_CONTENT:
- httpStatus = HttpStatus.SC_NO_CONTENT;
- break;
- default:
- httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
- break;
- }
- return httpStatus;
- }
-
-
- public CamundaResponse getResponse() {
- return response;
- }
-
-
- public void setResponse(CamundaResponse response) {
- this.response = response;
- }
-
-
- public String getResponseBody() {
- return responseBody;
- }
-
-
- public void setResponseBody(String responseBody) {
- this.responseBody = responseBody;
- }
-
-
- public int getStatus() {
- return status;
- }
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder("Could not convert CamundaTask response to string",
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ throw validateException;
+ }
+ if (status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_ACCEPTED) {
+ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER,
+ ErrorCode.BusinessProcesssError).targetEntity("CAMUNDATASK").targetServiceName("parseCamundaTask")
+ .build();
+
+
+ BPMNFailureException bpmnFailureException =
+ new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL)
+ .errorInfo(errorLoggerInfo).build();
+
+ throw bpmnFailureException;
+ }
+
+ }
+
+ private int setStatus(int statusCode) {
+ int httpStatus;
+ switch (statusCode) {
+ case HttpStatus.SC_ACCEPTED:
+ case HttpStatus.SC_OK:
+ httpStatus = HttpStatus.SC_ACCEPTED;
+ break;
+ case HttpStatus.SC_BAD_REQUEST:
+ httpStatus = HttpStatus.SC_BAD_REQUEST;
+ break;
+ case HttpStatus.SC_UNAUTHORIZED:
+ case HttpStatus.SC_FORBIDDEN:
+ httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
+ break;
+ case HttpStatus.SC_NOT_FOUND:
+ httpStatus = HttpStatus.SC_NOT_IMPLEMENTED;
+ break;
+ case HttpStatus.SC_INTERNAL_SERVER_ERROR:
+ httpStatus = HttpStatus.SC_BAD_GATEWAY;
+ break;
+ case HttpStatus.SC_SERVICE_UNAVAILABLE:
+ httpStatus = HttpStatus.SC_SERVICE_UNAVAILABLE;
+ break;
+ case HttpStatus.SC_NO_CONTENT:
+ httpStatus = HttpStatus.SC_NO_CONTENT;
+ break;
+ default:
+ httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
+ break;
+ }
+ return httpStatus;
+ }
+
+
+ public CamundaResponse getResponse() {
+ return response;
+ }
+
+
+ public void setResponse(CamundaResponse response) {
+ this.response = response;
+ }
+
+
+ public String getResponseBody() {
+ return responseBody;
+ }
+
+
+ public void setResponseBody(String responseBody) {
+ this.responseBody = responseBody;
+ }
+
+
+ public int getStatus() {
+ return status;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java
index c3dfe2c685..b972f7e1db 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java
@@ -25,18 +25,15 @@ package org.onap.so.apihandler.common;
import java.io.FileInputStream;
import java.io.IOException;
-
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
-
import org.apache.commons.io.IOUtils;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
@@ -46,7 +43,7 @@ public class XMLValidator {
private static String XSDS_PATH;
static {
- String prefixMsoPropertiesPath = System.getProperty ("mso.config.path");
+ String prefixMsoPropertiesPath = System.getProperty("mso.config.path");
if (prefixMsoPropertiesPath == null) {
prefixMsoPropertiesPath = "";
}
@@ -61,44 +58,44 @@ public class XMLValidator {
private static Logger logger = LoggerFactory.getLogger(XMLValidator.class);
- public XMLValidator (String xsdFile){
+ public XMLValidator(String xsdFile) {
- try (FileInputStream xsdStream = new FileInputStream (XSDS_PATH + xsdFile)) {
+ try (FileInputStream xsdStream = new FileInputStream(XSDS_PATH + xsdFile)) {
- stringXsd = IOUtils.toString (xsdStream);
+ stringXsd = IOUtils.toString(xsdStream);
- factory = SchemaFactory.newInstance (XMLConstants.W3C_XML_SCHEMA_NS_URI);
- factory.setResourceResolver (new PathResourceResolver (XSDS_PATH));
- factory.setFeature (XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+ factory.setResourceResolver(new PathResourceResolver(XSDS_PATH));
+ factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- String quotedXsd = stringXsd.replaceAll ("&#34;", "\"");
- Source src = new StreamSource (new java.io.StringReader (quotedXsd));
- schema = factory.newSchema (src);
+ String quotedXsd = stringXsd.replaceAll("&#34;", "\"");
+ Source src = new StreamSource(new java.io.StringReader(quotedXsd));
+ schema = factory.newSchema(src);
} catch (IOException | SAXException e) {
- logger.debug ("Cannot open file {}", XSDS_PATH + xsdFile, e);
- errorMsg = "ErrorDetails: xsd file " + xsdFile + "could not be opened - " + e.getMessage ();
+ logger.debug("Cannot open file {}", XSDS_PATH + xsdFile, e);
+ errorMsg = "ErrorDetails: xsd file " + xsdFile + "could not be opened - " + e.getMessage();
}
}
// Returns null when XML valid, otherwise returns error details.
- public String isXmlValid (String stringXml) {
+ public String isXmlValid(String stringXml) {
try {
- if (errorMsg != null && !errorMsg.isEmpty ()) {
+ if (errorMsg != null && !errorMsg.isEmpty()) {
return errorMsg;
}
- Source src2 = new StreamSource (new java.io.StringReader (stringXml));
- Validator validator = schema.newValidator ();
- validator.validate (src2);
+ Source src2 = new StreamSource(new java.io.StringReader(stringXml));
+ Validator validator = schema.newValidator();
+ validator.validate(src2);
} catch (IOException | SAXException e) {
- logger.debug ("Exception: ", e);
- return "ErrorDetails: " + e.getMessage ();
+ logger.debug("Exception: ", e);
+ return "ErrorDetails: " + e.getMessage();
} catch (Exception e) {
- logger.error("{} {} {}", MessageEnum.APIH_CANNOT_READ_SCHEMA.toString(),
- ErrorCode.SchemaError.getValue(), "APIH cannot read schema file", e);
+ logger.error("{} {} {}", MessageEnum.APIH_CANNOT_READ_SCHEMA.toString(), ErrorCode.SchemaError.getValue(),
+ "APIH cannot read schema file", e);
return "ErrorDetails: " + "Unable to read the schema file";
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java
index 17dd9859b0..399e0650f9 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java
@@ -20,12 +20,10 @@
package org.onap.so.apihandler.filters;
import java.io.IOException;
-
import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.ext.Provider;
-
import org.apache.http.HttpStatus;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.onap.so.db.request.beans.InfraActiveRequests;
@@ -41,20 +39,20 @@ import org.springframework.stereotype.Component;
@Component
public class RequestIdFilter implements ContainerRequestFilter {
- protected static Logger logger = LoggerFactory.getLogger(RequestIdFilter.class);
-
- @Autowired
- private RequestsDbClient infraActiveRequestsClient;
+ protected static Logger logger = LoggerFactory.getLogger(RequestIdFilter.class);
+
+ @Autowired
+ private RequestsDbClient infraActiveRequestsClient;
+
+ @Override
+ public void filter(ContainerRequestContext context) throws IOException {
+ String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
- @Override
- public void filter(ContainerRequestContext context) throws IOException {
- String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
-
InfraActiveRequests infraActiveRequests = infraActiveRequestsClient.getInfraActiveRequestbyRequestId(requestId);
-
+
if (infraActiveRequests != null) {
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(HttpStatus.SC_BAD_REQUEST));
- logger.error("RequestID exists in RequestDB.InfraActiveRequests : " + requestId);
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(HttpStatus.SC_BAD_REQUEST));
+ logger.error("RequestID exists in RequestDB.InfraActiveRequests : " + requestId);
}
- }
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java
index aeed65b3c3..403dd920e8 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java
@@ -23,7 +23,6 @@
package org.onap.so.apihandler.recipe;
import java.io.IOException;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
@@ -32,21 +31,20 @@ import org.springframework.web.client.ResponseErrorHandler;
-public class CamundaClientErrorHandler implements ResponseErrorHandler{
-
- private static Logger logger = LoggerFactory.getLogger(CamundaClientErrorHandler.class);
-
- @Override
- public void handleError(ClientHttpResponse response) throws IOException {
+public class CamundaClientErrorHandler implements ResponseErrorHandler {
+
+ private static Logger logger = LoggerFactory.getLogger(CamundaClientErrorHandler.class);
+
+ @Override
+ public void handleError(ClientHttpResponse response) throws IOException {
+
+ logger.debug(response.getBody().toString());
+ }
- logger.debug(response.getBody().toString());
- }
+ @Override
+ public boolean hasError(ClientHttpResponse response) throws IOException {
+ HttpStatus.Series series = response.getStatusCode().series();
+ return (HttpStatus.Series.CLIENT_ERROR.equals(series) || HttpStatus.Series.SERVER_ERROR.equals(series));
+ }
- @Override
- public boolean hasError(ClientHttpResponse response) throws IOException {
- HttpStatus.Series series = response.getStatusCode().series();
- return (HttpStatus.Series.CLIENT_ERROR.equals(series)
- || HttpStatus.Series.SERVER_ERROR.equals(series));
- }
-
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java
index 897e2a5fc8..77dbff9ebb 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java
@@ -22,29 +22,7 @@ package org.onap.so.apihandlerinfra;
/*
* Enum for Status values returned by API Handler to Tail-F
-*/
-public enum Action implements Actions{
- createInstance,
- updateInstance,
- deleteInstance,
- configureInstance,
- replaceInstance,
- activateInstance,
- deactivateInstance,
- enablePort,
- disablePort,
- addRelationships,
- removeRelationships,
- inPlaceSoftwareUpdate,
- applyUpdatedConfig,
- completeTask,
- assignInstance,
- unassignInstance,
- compareModel,
- scaleInstance,
- deactivateAndCloudDelete,
- scaleOut,
- recreateInstance,
- addMembers,
- removeMembers
+ */
+public enum Action implements Actions {
+ createInstance, updateInstance, deleteInstance, configureInstance, replaceInstance, activateInstance, deactivateInstance, enablePort, disablePort, addRelationships, removeRelationships, inPlaceSoftwareUpdate, applyUpdatedConfig, completeTask, assignInstance, unassignInstance, compareModel, scaleInstance, deactivateAndCloudDelete, scaleOut, recreateInstance, addMembers, removeMembers
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Constants.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Constants.java
index d824696147..0bbc3e336f 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Constants.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Constants.java
@@ -23,32 +23,31 @@ package org.onap.so.apihandlerinfra;
public class Constants {
- private Constants() {
- }
+ private Constants() {}
- public static final String REQUEST_ID_PATH = "/{request-id}";
+ public static final String REQUEST_ID_PATH = "/{request-id}";
- public static final String STATUS_SUCCESS = "SUCCESS";
+ public static final String STATUS_SUCCESS = "SUCCESS";
- public static final String MODIFIED_BY_APIHANDLER = "APIH";
+ public static final String MODIFIED_BY_APIHANDLER = "APIH";
- public static final long PROGRESS_REQUEST_COMPLETED = 100L;
- public static final long PROGRESS_REQUEST_RECEIVED = 0L;
- public static final long PROGRESS_REQUEST_IN_PROGRESS = 20L;
+ public static final long PROGRESS_REQUEST_COMPLETED = 100L;
+ public static final long PROGRESS_REQUEST_RECEIVED = 0L;
+ public static final long PROGRESS_REQUEST_IN_PROGRESS = 20L;
- public static final String VNF_TYPE_WILDCARD = "*";
+ public static final String VNF_TYPE_WILDCARD = "*";
- public static final String VOLUME_GROUP_COMPONENT_TYPE = "VOLUME_GROUP";
+ public static final String VOLUME_GROUP_COMPONENT_TYPE = "VOLUME_GROUP";
- public static final String VALID_INSTANCE_NAME_FORMAT = "^[a-zA-Z][a-zA-Z0-9._-]*$";
+ public static final String VALID_INSTANCE_NAME_FORMAT = "^[a-zA-Z][a-zA-Z0-9._-]*$";
+
+ public static final String A_LA_CARTE = "aLaCarte";
+
+ public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
+
+ public final static String VNF_REQUEST_SCOPE = "vnf";
+ public final static String SERVICE_INSTANCE_PATH = "/serviceInstances";
+ public final static String SERVICE_INSTANTIATION_PATH = "/serviceInstantiation";
+ public final static String ORCHESTRATION_REQUESTS_PATH = "/orchestrationRequests";
- public static final String A_LA_CARTE = "aLaCarte";
-
- public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
-
- public final static String VNF_REQUEST_SCOPE = "vnf";
- public final static String SERVICE_INSTANCE_PATH = "/serviceInstances";
- public final static String SERVICE_INSTANTIATION_PATH = "/serviceInstantiation";
- public final static String ORCHESTRATION_REQUESTS_PATH = "/orchestrationRequests";
-
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Messages.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Messages.java
index 555c536efb..c313cba032 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Messages.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Messages.java
@@ -23,34 +23,39 @@ package org.onap.so.apihandlerinfra;
import java.util.HashMap;
import java.util.Map;
-
import org.onap.so.apihandler.common.ErrorNumbers;
public class Messages {
- protected static final Map<String,String> errors = new HashMap<>();
- static {
- errors.put(ErrorNumbers.REQUEST_FAILED_SCHEMA_VALIDATION + "_service", "Service request FAILED schema validation. %s");
- errors.put(ErrorNumbers.REQUEST_FAILED_SCHEMA_VALIDATION + "_feature", "Feature request FAILED schema validation. %s");
- errors.put(ErrorNumbers.RECIPE_DOES_NOT_EXIST, "Recipe for %s-type and action specified does not exist in catalog %s");
- errors.put(ErrorNumbers.SERVICE_PARAMETERS_FAILED_SCHEMA_VALIDATION, "Service specific parameters passed in request FAILED schema validation. %s");
-
- errors.put(ErrorNumbers.LOCKED_CREATE_ON_THE_SAME_VNF_NAME_IN_PROGRESS, "%s-name (%s) is locked (status = %s) because already working on a CREATE request with same %s-name.");
- errors.put(ErrorNumbers.LOCKED_SAME_ACTION_AND_VNF_ID, "%s-id (%s) is locked (status = %s) because already working on a request with same action (%s) for this %s-id.");
- errors.put(ErrorNumbers.REQUEST_TIMED_OUT, "Service request timed out before completing");
- errors.put(ErrorNumbers.ERROR_FROM_BPEL, "BPEL returned an error: %s");
- errors.put(ErrorNumbers.NO_COMMUNICATION_TO_BPEL, "Could not communicate with BPEL %s");
- errors.put(ErrorNumbers.NO_RESPONSE_FROM_BPEL, "No response from BPEL %s");
- errors.put(ErrorNumbers.COULD_NOT_WRITE_TO_REQUESTS_DB, "Could not insert or update record in MSO_REQUESTS DB %s");
- errors.put(ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, "Could not communicate with MSO_REQUESTS DB %s");
- errors.put(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB, "Could not communicate with MSO_CATALOG DB %s");
- errors.put(ErrorNumbers.ERROR_FROM_CATALOG_DB, "Received error from MSO_CATALOG DB %s");
- }
-
- private Messages(){
- }
-
- public static Map<String,String> getErrors() {
- return errors;
- }
+ protected static final Map<String, String> errors = new HashMap<>();
+ static {
+ errors.put(ErrorNumbers.REQUEST_FAILED_SCHEMA_VALIDATION + "_service",
+ "Service request FAILED schema validation. %s");
+ errors.put(ErrorNumbers.REQUEST_FAILED_SCHEMA_VALIDATION + "_feature",
+ "Feature request FAILED schema validation. %s");
+ errors.put(ErrorNumbers.RECIPE_DOES_NOT_EXIST,
+ "Recipe for %s-type and action specified does not exist in catalog %s");
+ errors.put(ErrorNumbers.SERVICE_PARAMETERS_FAILED_SCHEMA_VALIDATION,
+ "Service specific parameters passed in request FAILED schema validation. %s");
+
+ errors.put(ErrorNumbers.LOCKED_CREATE_ON_THE_SAME_VNF_NAME_IN_PROGRESS,
+ "%s-name (%s) is locked (status = %s) because already working on a CREATE request with same %s-name.");
+ errors.put(ErrorNumbers.LOCKED_SAME_ACTION_AND_VNF_ID,
+ "%s-id (%s) is locked (status = %s) because already working on a request with same action (%s) for this %s-id.");
+ errors.put(ErrorNumbers.REQUEST_TIMED_OUT, "Service request timed out before completing");
+ errors.put(ErrorNumbers.ERROR_FROM_BPEL, "BPEL returned an error: %s");
+ errors.put(ErrorNumbers.NO_COMMUNICATION_TO_BPEL, "Could not communicate with BPEL %s");
+ errors.put(ErrorNumbers.NO_RESPONSE_FROM_BPEL, "No response from BPEL %s");
+ errors.put(ErrorNumbers.COULD_NOT_WRITE_TO_REQUESTS_DB,
+ "Could not insert or update record in MSO_REQUESTS DB %s");
+ errors.put(ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, "Could not communicate with MSO_REQUESTS DB %s");
+ errors.put(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB, "Could not communicate with MSO_CATALOG DB %s");
+ errors.put(ErrorNumbers.ERROR_FROM_CATALOG_DB, "Received error from MSO_CATALOG DB %s");
+ }
+
+ private Messages() {}
+
+ public static Map<String, String> getErrors() {
+ return errors;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/ModelType.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/ModelType.java
index 7b3ea3a181..0c10599a52 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/ModelType.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/ModelType.java
@@ -22,11 +22,7 @@ package org.onap.so.apihandlerinfra;
/*
* Enum for Status values returned by API Handler to Tail-F
-*/
+ */
public enum ModelType {
- service,
- vnf,
- vfModule,
- volumeGroup,
- network
+ service, vnf, vfModule, volumeGroup, network
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/MsoException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/MsoException.java
index defc904b05..ed2946d78a 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/MsoException.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/MsoException.java
@@ -21,6 +21,5 @@
package org.onap.so.apihandlerinfra;
public enum MsoException {
- ServiceException,
- PolicyException,
+ ServiceException, PolicyException,
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Status.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Status.java
index fe9764a2f2..b791bf147b 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Status.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Status.java
@@ -23,14 +23,7 @@ package org.onap.so.apihandlerinfra;
/*
* Enum for Status values returned by API Handler to Tail-F
-*/
+ */
public enum Status {
- PENDING,
- IN_PROGRESS,
- COMPLETE,
- COMPLETED,
- FAILED,
- TIMEOUT,
- UNLOCKED,
- PENDING_MANUAL_TASK
+ PENDING, IN_PROGRESS, COMPLETE, COMPLETED, FAILED, TIMEOUT, UNLOCKED, PENDING_MANUAL_TASK
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java
index fdf6b80e1c..c7f6459482 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java
@@ -22,36 +22,34 @@ package org.onap.so.apihandlerinfra.exceptions;
import java.util.List;
-
-
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
-public abstract class ApiException extends Exception{
+public abstract class ApiException extends Exception {
/**
- *
- */
- private static final long serialVersionUID = 683162058616691134L;
- private int httpResponseCode;
+ *
+ */
+ private static final long serialVersionUID = 683162058616691134L;
+ private int httpResponseCode;
private String messageID;
private ErrorLoggerInfo errorLoggerInfo;
- private List<String> variables;
+ private List<String> variables;
- public ApiException(Builder builder){
+ public ApiException(Builder builder) {
super(builder.message, builder.cause);
this.httpResponseCode = builder.httpResponseCode;
this.messageID = builder.messageID;
this.variables = builder.variables;
this.errorLoggerInfo = builder.errorLoggerInfo;
- this.variables = builder.variables;
+ this.variables = builder.variables;
}
public ApiException(String message, Throwable cause) {
- super(message, cause);
- }
+ super(message, cause);
+ }
- public String getMessageID() {
+ public String getMessageID() {
return messageID;
}
@@ -76,7 +74,7 @@ public abstract class ApiException extends Exception{
private ErrorLoggerInfo errorLoggerInfo = null;
private List<String> variables = null;
-
+
public Builder(String message, int httpResponseCode, String messageID) {
this.message = message;
this.httpResponseCode = httpResponseCode;
@@ -103,7 +101,7 @@ public abstract class ApiException extends Exception{
return (T) this;
}
- public T errorInfo(ErrorLoggerInfo errorLoggerInfo){
+ public T errorInfo(ErrorLoggerInfo errorLoggerInfo) {
this.errorLoggerInfo = errorLoggerInfo;
return (T) this;
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java
index 4c069d5b1a..3b977639fc 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java
@@ -27,7 +27,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
-
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
@@ -37,15 +36,11 @@ import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
-
-
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.onap.so.serviceinstancebeans.RequestError;
import org.onap.so.serviceinstancebeans.ServiceException;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -58,7 +53,7 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> {
private static Logger logger = LoggerFactory.getLogger(ApiExceptionMapper.class);
-
+
private final JAXBContext context;
private final Marshaller marshaller;
@@ -66,14 +61,15 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> {
private HttpHeaders headers;
public ApiExceptionMapper() {
- try {
- context = JAXBContext.newInstance(RequestError.class);
- marshaller = context.createMarshaller();
- } catch (JAXBException e) {
- logger.debug("could not create JAXB marshaller");
- throw new IllegalStateException(e);
- }
+ try {
+ context = JAXBContext.newInstance(RequestError.class);
+ marshaller = context.createMarshaller();
+ } catch (JAXBException e) {
+ logger.debug("could not create JAXB marshaller");
+ throw new IllegalStateException(e);
+ }
}
+
@Override
public Response toResponse(ApiException exception) {
@@ -93,23 +89,24 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> {
}
-
+
List<MediaType> typeList = Optional.ofNullable(headers.getAcceptableMediaTypes()).orElse(new ArrayList<>());
List<String> typeListString = typeList.stream().map(item -> item.toString()).collect(Collectors.toList());
MediaType type;
if (typeListString.stream().anyMatch(item -> item.contains(MediaType.APPLICATION_XML))) {
- type = MediaType.APPLICATION_XML_TYPE;
+ type = MediaType.APPLICATION_XML_TYPE;
} else if (typeListString.stream().anyMatch(item -> typeListString.contains(MediaType.APPLICATION_JSON))) {
- type = MediaType.APPLICATION_JSON_TYPE;
+ type = MediaType.APPLICATION_JSON_TYPE;
} else {
- type = MediaType.APPLICATION_JSON_TYPE;
+ type = MediaType.APPLICATION_JSON_TYPE;
}
- return buildServiceErrorResponse(errorText,messageId,variables, type);
+ return buildServiceErrorResponse(errorText, messageId, variables, type);
}
- protected String buildServiceErrorResponse(String errorText, String messageId, List<String> variables, MediaType type){
+ protected String buildServiceErrorResponse(String errorText, String messageId, List<String> variables,
+ MediaType type) {
RequestError re = new RequestError();
ServiceException se = new ServiceException();
se.setMessageId(messageId);
@@ -123,21 +120,22 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> {
String requestErrorStr;
ObjectMapper mapper = createObjectMapper();
-
+
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
try {
- if (MediaType.APPLICATION_JSON_TYPE.equals(type)) {
- requestErrorStr = mapper.writeValueAsString(re);
+ if (MediaType.APPLICATION_JSON_TYPE.equals(type)) {
+ requestErrorStr = mapper.writeValueAsString(re);
} else {
- StringWriter sw = new StringWriter();
- this.getMarshaller().marshal(re, sw);
- requestErrorStr = sw.toString();
+ StringWriter sw = new StringWriter();
+ this.getMarshaller().marshal(re, sw);
+ requestErrorStr = sw.toString();
}
} catch (JsonProcessingException | JAXBException e) {
- String errorMsg = "Exception in buildServiceErrorResponse writing exceptionType to string " + e.getMessage();
+ String errorMsg =
+ "Exception in buildServiceErrorResponse writing exceptionType to string " + e.getMessage();
logger.error("{} {} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), "BuildServiceErrorResponse",
- ErrorCode.DataError.getValue(), errorMsg, e);
+ ErrorCode.DataError.getValue(), errorMsg, e);
return errorMsg;
}
@@ -145,19 +143,21 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> {
}
protected void writeErrorLog(Exception e, String errorText, ErrorLoggerInfo errorLogInfo) {
- if( e!= null)
+ if (e != null)
logger.error("Exception occurred", e);
- if(errorLogInfo != null)
- logger.error(errorLogInfo.getLoggerMessageType().toString(), errorLogInfo.getErrorSource(), errorLogInfo.getTargetEntity(), errorLogInfo.getTargetServiceName(), errorLogInfo.getErrorCode(), errorText);
-
+ if (errorLogInfo != null)
+ logger.error(errorLogInfo.getLoggerMessageType().toString(), errorLogInfo.getErrorSource(),
+ errorLogInfo.getTargetEntity(), errorLogInfo.getTargetServiceName(), errorLogInfo.getErrorCode(),
+ errorText);
+
}
- public ObjectMapper createObjectMapper(){
+ public ObjectMapper createObjectMapper() {
return new ObjectMapper();
}
-
+
public Marshaller getMarshaller() {
- return marshaller;
+ return marshaller;
}
-
+
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/BPMNFailureException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/BPMNFailureException.java
index 8c215de213..97d46bd6f1 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/BPMNFailureException.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/BPMNFailureException.java
@@ -28,11 +28,11 @@ public class BPMNFailureException extends ApiException {
super(builder);
}
- public static class Builder extends ApiException.Builder<Builder>{
+ public static class Builder extends ApiException.Builder<Builder> {
public Builder(String message, int httpResponseCode, String messageID) {
- super(bpmnFailMessage.replaceAll ("\\$HTTPSTATUS", message),httpResponseCode,messageID);
+ super(bpmnFailMessage.replaceAll("\\$HTTPSTATUS", message), httpResponseCode, messageID);
}
public BPMNFailureException build() {
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ClientConnectionException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ClientConnectionException.java
index cf4c9168ea..4af5289ad7 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ClientConnectionException.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ClientConnectionException.java
@@ -23,19 +23,19 @@ package org.onap.so.apihandlerinfra.exceptions;
public class ClientConnectionException extends ApiException {
/**
- *
- */
- private static final long serialVersionUID = 1L;
- private static final String clientFailMessage = "Client from $URL failed to connect";
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private static final String clientFailMessage = "Client from $URL failed to connect";
private ClientConnectionException(Builder builder) {
super(builder);
}
- public static class Builder extends ApiException.Builder<Builder>{
+ public static class Builder extends ApiException.Builder<Builder> {
public Builder(String message, int httpResponseCode, String messageID) {
- super(clientFailMessage.replaceAll ("\\$URL", message),httpResponseCode,messageID);
+ super(clientFailMessage.replaceAll("\\$URL", message), httpResponseCode, messageID);
}
public ClientConnectionException build() {
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ContactCamundaException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ContactCamundaException.java
index e1ec46a9c1..6b38eec4ae 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ContactCamundaException.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ContactCamundaException.java
@@ -22,17 +22,19 @@ package org.onap.so.apihandlerinfra.exceptions;
public class ContactCamundaException extends ApiException {
- private static final String contactCamundaErrorMessage = "Unable to get process-instance history from Camunda for requestId: %s due to error: %s";
+ private static final String contactCamundaErrorMessage =
+ "Unable to get process-instance history from Camunda for requestId: %s due to error: %s";
private ContactCamundaException(Builder builder) {
super(builder);
}
- public static class Builder extends ApiException.Builder<Builder>{
+ public static class Builder extends ApiException.Builder<Builder> {
public Builder(String requestId, String error, int httpResponseCode, String messageID) {
- super(contactCamundaErrorMessage.format(contactCamundaErrorMessage, requestId, error),httpResponseCode,messageID);
+ super(contactCamundaErrorMessage.format(contactCamundaErrorMessage, requestId, error), httpResponseCode,
+ messageID);
}
public ContactCamundaException build() {
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java
index 718dc6421d..21e9b44b19 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java
@@ -22,18 +22,21 @@ package org.onap.so.apihandlerinfra.exceptions;
public class DuplicateRequestException extends ApiException {
- private static final String duplicateFailMessage = "Error: Locked instance - This %s (%s) " + "already has a request being worked with a status of %s (RequestId - %s). The existing request must finish or be cleaned up before proceeding.";
+ private static final String duplicateFailMessage = "Error: Locked instance - This %s (%s) "
+ + "already has a request being worked with a status of %s (RequestId - %s). The existing request must finish or be cleaned up before proceeding.";
private DuplicateRequestException(Builder builder) {
super(builder);
}
- public static class Builder extends ApiException.Builder<Builder>{
+ public static class Builder extends ApiException.Builder<Builder> {
- public Builder(String requestScope,String instance, String requestStatus, String requestID, int httpResponseCode, String messageID) {
- super(String.format(duplicateFailMessage,requestScope,instance,requestStatus,requestID),httpResponseCode,messageID);
+ public Builder(String requestScope, String instance, String requestStatus, String requestID,
+ int httpResponseCode, String messageID) {
+ super(String.format(duplicateFailMessage, requestScope, instance, requestStatus, requestID),
+ httpResponseCode, messageID);
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RequestDbFailureException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RequestDbFailureException.java
index 154ae36d41..577a14674b 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RequestDbFailureException.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RequestDbFailureException.java
@@ -28,11 +28,11 @@ public class RequestDbFailureException extends ApiException {
super(builder);
}
- public static class Builder extends ApiException.Builder<Builder>{
+ public static class Builder extends ApiException.Builder<Builder> {
public Builder(String action, String error, int httpResponseCode, String messageID) {
- super(requestDbFailMessage.format(requestDbFailMessage, action, error),httpResponseCode,messageID);
+ super(requestDbFailMessage.format(requestDbFailMessage, action, error), httpResponseCode, messageID);
}
public RequestDbFailureException build() {
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java
index b0cf39e1a2..372ed30d8e 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java
@@ -28,10 +28,10 @@ public class ValidateException extends ApiException {
}
- public static class Builder extends ApiException.Builder<Builder>{
+ public static class Builder extends ApiException.Builder<Builder> {
public Builder(String message, int httpResponseCode, String messageID) {
- super(message,httpResponseCode,messageID);
+ super(message, httpResponseCode, messageID);
}
public ValidateException build() {
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/VfModuleNotFoundException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/VfModuleNotFoundException.java
index d80f2f7b48..cbd3f65a61 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/VfModuleNotFoundException.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/VfModuleNotFoundException.java
@@ -24,19 +24,20 @@ public class VfModuleNotFoundException extends ApiException {
/**
- *
- */
- private static final long serialVersionUID = 1L;
+ *
+ */
+ private static final long serialVersionUID = 1L;
- private VfModuleNotFoundException(Builder builder) {
+ private VfModuleNotFoundException(Builder builder) {
super(builder);
}
- public static class Builder extends ApiException.Builder<Builder>{
+ public static class Builder extends ApiException.Builder<Builder> {
public Builder(String message, int httpResponseCode, String messageID) {
- super(message,httpResponseCode,messageID);
+ super(message, httpResponseCode, messageID);
}
+
public VfModuleNotFoundException build() {
return new VfModuleNotFoundException(this);
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/logging/ErrorLoggerInfo.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/logging/ErrorLoggerInfo.java
index 058d80868c..a896078d44 100644
--- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/logging/ErrorLoggerInfo.java
+++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/logging/ErrorLoggerInfo.java
@@ -21,24 +21,24 @@
package org.onap.so.apihandlerinfra.logging;
import java.io.Serializable;
-
import org.onap.so.logger.MessageEnum;
import org.onap.so.logger.ErrorCode;
-public class ErrorLoggerInfo implements Serializable{
+public class ErrorLoggerInfo implements Serializable {
/**
- *
- */
- private static final long serialVersionUID = -2917784544098682110L;
- private MessageEnum loggerMessageType;
+ *
+ */
+ private static final long serialVersionUID = -2917784544098682110L;
+ private MessageEnum loggerMessageType;
private String errorSource;
private String targetEntity;
private String targetServiceName;
private ErrorCode errorCode;
- private ErrorLoggerInfo(MessageEnum loggerMessageType, String errorSource, String targetEntity, String targetServiceName, ErrorCode errorCode){
+ private ErrorLoggerInfo(MessageEnum loggerMessageType, String errorSource, String targetEntity,
+ String targetServiceName, ErrorCode errorCode) {
this.loggerMessageType = loggerMessageType;
this.errorSource = errorSource;
this.targetEntity = targetEntity;
@@ -66,44 +66,44 @@ public class ErrorLoggerInfo implements Serializable{
return errorCode;
}
- public static class Builder{
+ public static class Builder {
private MessageEnum loggerMessageType;
private String errorSource = "";
private String targetEntity = "";
private String targetServiceName = "";
private ErrorCode errorCode;
- public Builder(MessageEnum loggerMessageType, ErrorCode errorCode){
+ public Builder(MessageEnum loggerMessageType, ErrorCode errorCode) {
this.loggerMessageType = loggerMessageType;
this.errorCode = errorCode;
}
- public Builder loggerMessageType(MessageEnum loggerMessageType){
+ public Builder loggerMessageType(MessageEnum loggerMessageType) {
this.loggerMessageType = loggerMessageType;
return this;
}
- public Builder errorSource(String errorSource){
+ public Builder errorSource(String errorSource) {
this.errorSource = errorSource;
return this;
}
- public Builder targetEntity(String targetEntity){
+ public Builder targetEntity(String targetEntity) {
this.targetEntity = targetEntity;
return this;
}
- public Builder targetServiceName(String targetServiceName){
+ public Builder targetServiceName(String targetServiceName) {
this.targetServiceName = targetServiceName;
return this;
}
- public Builder errorCode(ErrorCode errorCode){
+ public Builder errorCode(ErrorCode errorCode) {
this.errorCode = errorCode;
return this;
}
- public ErrorLoggerInfo build(){
+ public ErrorLoggerInfo build() {
return new ErrorLoggerInfo(loggerMessageType, errorSource, targetEntity, targetServiceName, errorCode);
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/BeansTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/BeansTest.java
index b596636f6d..af582fb868 100644
--- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/BeansTest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/BeansTest.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandler.camundabeans;
import org.junit.Test;
-
import com.openpojo.validation.Validator;
import com.openpojo.validation.ValidatorBuilder;
import com.openpojo.validation.rule.impl.GetterMustExistRule;
@@ -39,34 +38,33 @@ import org.onap.so.openpojo.rules.ToStringTester;
public class BeansTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
-
- private PojoClassFilter enumFilter = new FilterEnum();
-
-
- @Test
- public void pojoStructure() {
- test("org.onap.so.apihandler.camundabeans");
- }
-
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
-
-
-
-
- .with(new SetterTester())
- .with(new GetterTester())
- .with(new ToStringTester())
-
- .build();
-
-
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses,enumFilter,new FilterNonConcrete());
- }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ private PojoClassFilter enumFilter = new FilterEnum();
+
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.apihandler.camundabeans");
+ }
+
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create()
+
+
+
+ .with(new SetterTester()).with(new GetterTester()).with(new ToStringTester())
+
+ .build();
+
+
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, enumFilter,
+ new FilterNonConcrete());
+ }
+
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/BpmnRequestTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/BpmnRequestTest.java
index 7087e90b73..7291f87554 100644
--- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/BpmnRequestTest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/BpmnRequestTest.java
@@ -175,4 +175,4 @@ public class BpmnRequestTest {
bpmnRequest.setRequestDetails(new CamundaInput());
}
-} \ No newline at end of file
+}
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequestSerializerTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequestSerializerTest.java
index 36966342b2..4636fcc90d 100644
--- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequestSerializerTest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/camundabeans/CamundaMacroRequestSerializerTest.java
@@ -28,9 +28,11 @@ import org.junit.Test;
*/
public class CamundaMacroRequestSerializerTest {
@Test
- public void testWithAllParameters() throws Exception{
+ public void testWithAllParameters() throws Exception {
String jsonRequest = CamundaMacroRequestSerializer.getJsonRequest("requestId", "action", "serviceInstanceId");
Assert.assertNotNull(jsonRequest);
- Assert.assertEquals("{\"variables\":{\"mso-request-id\":{\"value\":\"requestId\",\"type\":\"String\"},\"gAction\":{\"value\":\"action\",\"type\":\"String\"},\"serviceInstanceId\":{\"value\":\"serviceInstanceId\",\"type\":\"String\"}}}", jsonRequest);
+ Assert.assertEquals(
+ "{\"variables\":{\"mso-request-id\":{\"value\":\"requestId\",\"type\":\"String\"},\"gAction\":{\"value\":\"action\",\"type\":\"String\"},\"serviceInstanceId\":{\"value\":\"serviceInstanceId\",\"type\":\"String\"}}}",
+ jsonRequest);
}
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/AllTestsTestSuite.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/AllTestsTestSuite.java
index 47c166eff9..d1558a2a2c 100644
--- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/AllTestsTestSuite.java
+++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/AllTestsTestSuite.java
@@ -21,13 +21,12 @@
package org.onap.so.apihandler.common;
import org.junit.runner.RunWith;
-
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses("**/*Test.class")
public class AllTestsTestSuite {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java
index edab3b07b6..36d004e87d 100644
--- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java
@@ -29,11 +29,9 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ProtocolVersion;
@@ -50,7 +48,6 @@ import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.env.MockEnvironment;
-
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -60,7 +57,7 @@ import com.fasterxml.jackson.databind.JsonMappingException;
*
*
*/
-public class CamundaClientTest{
+public class CamundaClientTest {
@@ -74,31 +71,31 @@ public class CamundaClientTest{
}
@Test
- public void tesCamundaPost() throws JsonGenerationException,
- JsonMappingException, IOException {
+ public void tesCamundaPost() throws JsonGenerationException, JsonMappingException, IOException {
- String responseBody ="{\"links\":[{\"method\":\"GET\",\"href\":\"http://localhost:9080/engine-rest/process-instance/2047c658-37ae-11e5-9505-7a1020524153\",\"rel\":\"self\"}],\"id\":\"2047c658-37ae-11e5-9505-7a1020524153\",\"definitionId\":\"dummy:10:73298961-37ad-11e5-9505-7a1020524153\",\"businessKey\":null,\"caseInstanceId\":null,\"ended\":true,\"suspended\":false}";
+ String responseBody =
+ "{\"links\":[{\"method\":\"GET\",\"href\":\"http://localhost:9080/engine-rest/process-instance/2047c658-37ae-11e5-9505-7a1020524153\",\"rel\":\"self\"}],\"id\":\"2047c658-37ae-11e5-9505-7a1020524153\",\"definitionId\":\"dummy:10:73298961-37ad-11e5-9505-7a1020524153\",\"businessKey\":null,\"caseInstanceId\":null,\"ended\":true,\"suspended\":false}";
HttpResponse mockResponse = createResponse(200, responseBody);
mockHttpClient = Mockito.mock(HttpClient.class);
ArgumentCaptor<HttpPost> httpPostCaptor = ArgumentCaptor.forClass(HttpPost.class);
- Mockito.when(mockHttpClient.execute(Mockito.any(HttpPost.class)))
- .thenReturn(mockResponse);
+ Mockito.when(mockHttpClient.execute(Mockito.any(HttpPost.class))).thenReturn(mockResponse);
String reqXML = "<xml>test</xml>";
String orchestrationURI = "/engine-rest/process-definition/key/dummy/start";
MockEnvironment environment = new MockEnvironment();
-
+
environment.setProperty("mso.camundaUR", "yourValue1");
- environment.setProperty("mso.camundaAuth", "E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE");
+ environment.setProperty("mso.camundaAuth",
+ "E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE");
environment.setProperty("org.onap.so.adapters.network.encryptionKey", "aa3871669d893c7fb8abbcda31b88b4f");
-
-
+
+
RequestClientFactory reqClientFactory = new RequestClientFactory();
reqClientFactory.setEnv(environment);
RequestClient requestClient = reqClientFactory.getRequestClient(orchestrationURI);
-
+
requestClient.setClient(mockHttpClient);
HttpResponse response = requestClient.post(reqXML, "reqId", "timeout", "version", null, null);
@@ -107,22 +104,21 @@ public class CamundaClientTest{
assertEquals(requestClient.getType(), CommonConstants.CAMUNDA);
assertEquals(statusCode, HttpStatus.SC_OK);
-
+
requestClient = reqClientFactory.getRequestClient(orchestrationURI);
requestClient.setClient(mockHttpClient);
response = requestClient.post(null, "reqId", null, null, null, null);
assertEquals(requestClient.getType(), CommonConstants.CAMUNDA);
assertEquals(statusCode, HttpStatus.SC_OK);
- verify(mockHttpClient,times(2)).execute(httpPostCaptor.capture());
+ verify(mockHttpClient, times(2)).execute(httpPostCaptor.capture());
assertThat(httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)).isNotEmpty();
- Assert.assertEquals("Basic YXBpaEJwbW46Y2FtdW5kYS1SMTUxMiE=",httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)[0].getValue());
+ Assert.assertEquals("Basic YXBpaEJwbW46Y2FtdW5kYS1SMTUxMiE=",
+ httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)[0].getValue());
}
- private HttpResponse createResponse(int respStatus,
- String respBody) {
- HttpResponse response = new BasicHttpResponse(
- new BasicStatusLine(
- new ProtocolVersion("HTTP", 1, 1), respStatus, ""));
+ private HttpResponse createResponse(int respStatus, String respBody) {
+ HttpResponse response =
+ new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), respStatus, ""));
response.setStatusCode(respStatus);
try {
response.setEntity(new StringEntity(respBody));
@@ -132,62 +128,64 @@ public class CamundaClientTest{
}
return response;
}
-
- public String inputStream(String JsonInput)throws IOException{
+
+ public String inputStream(String JsonInput) throws IOException {
JsonInput = "src/test/resources/CamundaClientTest" + JsonInput;
String input = new String(Files.readAllBytes(Paths.get(JsonInput)));
return input;
}
-
+
@Test
- public void wrapVIDRequestTest() throws IOException{
- CamundaClient testClient = new CamundaClient();
- testClient.setUrl("/mso/async/services/CreateGenericALaCarteServiceInstance");
-
- String requestId = "f7ce78bb-423b-11e7-93f8-0050569a796";
- boolean isBaseVfModule = true;
- int recipeTimeout = 10000;
- String requestAction = "createInstance";
- String serviceInstanceId = "12345679";
- String pnfCorrelationId = "12345679";
- String vnfId = "234567891";
- String vfModuleId = "345678912";
- String volumeGroupId = "456789123";
- String networkId = "567891234";
- String configurationId = "678912345";
- String serviceType = "testService";
- String vnfType = "testVnf";
- String vfModuleType = "vfModuleType";
- String networkType = "networkType";
- String requestDetails = "{requestDetails: }";
- String apiVersion = "6";
- boolean aLaCarte = true;
- String requestUri = "v7/serviceInstances/assign";
- String instanceGroupId = "ff305d54-75b4-431b-adb2-eb6b9e5ff000";
-
- String testResult = testClient.wrapVIDRequest(requestId, isBaseVfModule, recipeTimeout, requestAction, serviceInstanceId, pnfCorrelationId,
- vnfId, vfModuleId, volumeGroupId, networkId, configurationId, serviceType,
- vnfType, vfModuleType, networkType, requestDetails, apiVersion, aLaCarte, requestUri, "", instanceGroupId);
- String expected = inputStream("/WrappedVIDRequest.json");
-
- assertEquals(expected, testResult);
+ public void wrapVIDRequestTest() throws IOException {
+ CamundaClient testClient = new CamundaClient();
+ testClient.setUrl("/mso/async/services/CreateGenericALaCarteServiceInstance");
+
+ String requestId = "f7ce78bb-423b-11e7-93f8-0050569a796";
+ boolean isBaseVfModule = true;
+ int recipeTimeout = 10000;
+ String requestAction = "createInstance";
+ String serviceInstanceId = "12345679";
+ String pnfCorrelationId = "12345679";
+ String vnfId = "234567891";
+ String vfModuleId = "345678912";
+ String volumeGroupId = "456789123";
+ String networkId = "567891234";
+ String configurationId = "678912345";
+ String serviceType = "testService";
+ String vnfType = "testVnf";
+ String vfModuleType = "vfModuleType";
+ String networkType = "networkType";
+ String requestDetails = "{requestDetails: }";
+ String apiVersion = "6";
+ boolean aLaCarte = true;
+ String requestUri = "v7/serviceInstances/assign";
+ String instanceGroupId = "ff305d54-75b4-431b-adb2-eb6b9e5ff000";
+
+ String testResult = testClient.wrapVIDRequest(requestId, isBaseVfModule, recipeTimeout, requestAction,
+ serviceInstanceId, pnfCorrelationId, vnfId, vfModuleId, volumeGroupId, networkId, configurationId,
+ serviceType, vnfType, vfModuleType, networkType, requestDetails, apiVersion, aLaCarte, requestUri, "",
+ instanceGroupId);
+ String expected = inputStream("/WrappedVIDRequest.json");
+
+ assertEquals(expected, testResult);
}
@Test
- public void testPost() throws Exception{
+ public void testPost() throws Exception {
CamundaClient testClient = new CamundaClient();
String orchestrationURI = "/engine-rest/process-definition/key/dummy/start";
MockEnvironment environment = new MockEnvironment();
-
+
environment.setProperty("mso.camundaUR", "yourValue1");
testClient.setProps(environment);
testClient.setClient(mockHttpClient);
-
+
testClient.setUrl(orchestrationURI);
-
- String responseBody ="{\"links\":[{\"method\":\"GET\",\"href\":\"http://localhost:9080/engine-rest/process-instance/2047c658-37ae-11e5-9505-7a1020524153\",\"rel\":\"self\"}],\"id\":\"2047c658-37ae-11e5-9505-7a1020524153\",\"definitionId\":\"dummy:10:73298961-37ad-11e5-9505-7a1020524153\",\"businessKey\":null,\"caseInstanceId\":null,\"ended\":true,\"suspended\":false}";
+
+ String responseBody =
+ "{\"links\":[{\"method\":\"GET\",\"href\":\"http://localhost:9080/engine-rest/process-instance/2047c658-37ae-11e5-9505-7a1020524153\",\"rel\":\"self\"}],\"id\":\"2047c658-37ae-11e5-9505-7a1020524153\",\"definitionId\":\"dummy:10:73298961-37ad-11e5-9505-7a1020524153\",\"businessKey\":null,\"caseInstanceId\":null,\"ended\":true,\"suspended\":false}";
assertNull(testClient.post(responseBody));
-
+
}
@Test
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaTaskClientTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaTaskClientTest.java
index 2ba0e4a173..9e9ab6048e 100644
--- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaTaskClientTest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaTaskClientTest.java
@@ -25,11 +25,9 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
-
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
@@ -47,8 +45,8 @@ import org.springframework.core.env.Environment;
@RunWith(MockitoJUnitRunner.class)
public class CamundaTaskClientTest {
- @Mock
- private Environment env;
+ @Mock
+ private Environment env;
private CamundaTaskClient testedObject = new CamundaTaskClient();
private HttpClient httpClientMock;
private static final String JSON_REQUEST = "{\"value1\": \"aaa\",\"value2\": \"bbb\"}";
@@ -61,7 +59,8 @@ public class CamundaTaskClientTest {
@Before
public void init() {
- when(env.getProperty(eq(CommonConstants.CAMUNDA_AUTH))).thenReturn("E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE");
+ when(env.getProperty(eq(CommonConstants.CAMUNDA_AUTH))).thenReturn(
+ "E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE");
when(env.getProperty(eq(CommonConstants.ENCRYPTION_KEY_PROP))).thenReturn("aa3871669d893c7fb8abbcda31b88b4f");
testedObject = new CamundaTaskClient();
httpClientMock = mock(HttpClient.class);
@@ -75,8 +74,8 @@ public class CamundaTaskClientTest {
testedObject.post(JSON_REQUEST);
verify(httpClientMock).execute(httpPostCaptor.capture());
checkUri(httpPostCaptor.getValue());
- assertThat(httpPostCaptor.getValue().getEntity().getContentType().getValue()).
- isEqualTo(CommonConstants.CONTENT_TYPE_JSON);
+ assertThat(httpPostCaptor.getValue().getEntity().getContentType().getValue())
+ .isEqualTo(CommonConstants.CONTENT_TYPE_JSON);
assertThat(getJsonFromEntity(httpPostCaptor.getValue().getEntity())).isEqualTo(JSON_REQUEST);
}
@@ -87,7 +86,8 @@ public class CamundaTaskClientTest {
testedObject.post(JSON_REQUEST);
verify(httpClientMock).execute(httpPostCaptor.capture());
assertThat(httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)).isNotEmpty();
- Assert.assertEquals("Basic YXBpaEJwbW46Y2FtdW5kYS1SMTUxMiE=",httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)[0].getValue());
+ Assert.assertEquals("Basic YXBpaEJwbW46Y2FtdW5kYS1SMTUxMiE=",
+ httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)[0].getValue());
}
@Test
@@ -106,7 +106,8 @@ public class CamundaTaskClientTest {
testedObject.get();
verify(httpClientMock).execute(httpGetCaptor.capture());
assertThat(httpGetCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)).isNotEmpty();
- Assert.assertEquals("Basic YXBpaEJwbW46Y2FtdW5kYS1SMTUxMiE=",httpGetCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)[0].getValue());
+ Assert.assertEquals("Basic YXBpaEJwbW46Y2FtdW5kYS1SMTUxMiE=",
+ httpGetCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)[0].getValue());
}
@Test(expected = UnsupportedOperationException.class)
@@ -127,8 +128,7 @@ public class CamundaTaskClientTest {
}
private String getJsonFromEntity(HttpEntity httpEntity) throws IOException {
- BufferedReader rd = new BufferedReader(
- new InputStreamReader(httpEntity.getContent()));
+ BufferedReader rd = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
StringBuilder result = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
@@ -137,4 +137,4 @@ public class CamundaTaskClientTest {
return result.toString();
}
-} \ No newline at end of file
+}
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java
index 0d4778b5b6..2095a9117d 100644
--- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java
@@ -19,7 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
+
package org.onap.so.apihandler.common;
@@ -28,7 +28,6 @@ import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ProtocolVersion;
@@ -46,100 +45,98 @@ import org.onap.so.apihandlerinfra.exceptions.ValidateException;
*
*
*/
-public class ResponseHandlerTest{
+public class ResponseHandlerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
- public void tesParseCamundaResponse () throws ApiException {
+ public void tesParseCamundaResponse() throws ApiException {
// String body
// ="{\"links\":[{\"method\":\"GET\",\"href\":\"http://localhost:9080/engine-rest/process-instance/2047c658-37ae-11e5-9505-7a1020524153\",\"rel\":\"self\"}],\"id\":\"2047c658-37ae-11e5-9505-7a1020524153\",\"definitionId\":\"dummy:10:73298961-37ad-11e5-9505-7a1020524153\",\"businessKey\":null,\"caseInstanceId\":null,\"ended\":true,\"suspended\":false}";
String body = "{ \"response\": \"<xml>xml</xml>\"," + "\"messageCode\": 200,"
- + "\"message\": \"Successfully started the process\"}";
+ + "\"message\": \"Successfully started the process\"}";
- HttpResponse response = createResponse (200, body, "application/json");
+ HttpResponse response = createResponse(200, body, "application/json");
- ResponseHandler respHandler = new ResponseHandler (response, 1);
-
- int status = respHandler.getStatus ();
- assertEquals (status, HttpStatus.SC_ACCEPTED);
- assertEquals (respHandler.getResponse ().getMessage (), "Successfully started the process");
+ ResponseHandler respHandler = new ResponseHandler(response, 1);
+
+ int status = respHandler.getStatus();
+ assertEquals(status, HttpStatus.SC_ACCEPTED);
+ assertEquals(respHandler.getResponse().getMessage(), "Successfully started the process");
}
-
+
@Test
- public void tesParseCamundaResponseForCamundaTaskType () throws ApiException {
- String body = "{ \"response\": \"<xml>xml</xml>\"," + "\"messageCode\": 200,"
- + "\"message\": \"Successfully started the process\"}";
+ public void tesParseCamundaResponseForCamundaTaskType() throws ApiException {
+ String body = "{ \"response\": \"<xml>xml</xml>\"," + "\"messageCode\": 200,"
+ + "\"message\": \"Successfully started the process\"}";
+
+ HttpResponse response = createResponse(200, body, "application/json");
- HttpResponse response = createResponse (200, body, "application/json");
+ ResponseHandler respHandler = new ResponseHandler(response, 2);
- ResponseHandler respHandler = new ResponseHandler (response, 2);
-
- int status = respHandler.getStatus ();
- assertEquals (status, HttpStatus.SC_ACCEPTED);
- assertEquals (respHandler.getResponseBody(), body);
+ int status = respHandler.getStatus();
+ assertEquals(status, HttpStatus.SC_ACCEPTED);
+ assertEquals(respHandler.getResponseBody(), body);
}
+
@Test
- public void tesParseBpelResponse () throws ApiException{
+ public void tesParseBpelResponse() throws ApiException {
String body = "<test:service-response xmlns:test=\"http://org.onap/so/test\">"
- + "<test:request-id>req5</test:request-id>"
- + "<test:request-action>test</test:request-action>"
- + "<test:source>test</test:source>"
- + "<test:ack-final-indicator>n</test:ack-final-indicator>"
- + "</test:service-response>";
+ + "<test:request-id>req5</test:request-id>" + "<test:request-action>test</test:request-action>"
+ + "<test:source>test</test:source>" + "<test:ack-final-indicator>n</test:ack-final-indicator>"
+ + "</test:service-response>";
- HttpResponse response = createResponse (200, body, "text/xml");
+ HttpResponse response = createResponse(200, body, "text/xml");
- ResponseHandler respHandler = new ResponseHandler (response, 0);
+ ResponseHandler respHandler = new ResponseHandler(response, 0);
- int status = respHandler.getStatus ();
- assertEquals (status, HttpStatus.SC_ACCEPTED);
- assertTrue (respHandler.getResponseBody () != null);
+ int status = respHandler.getStatus();
+ assertEquals(status, HttpStatus.SC_ACCEPTED);
+ assertTrue(respHandler.getResponseBody() != null);
}
@Test
- public void tesMappingErrorResponse () throws ApiException {
+ public void tesMappingErrorResponse() throws ApiException {
thrown.expect(ValidateException.class);
thrown.expectMessage(startsWith("Cannot parse Camunda Response"));
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
-
- HttpResponse response = createResponse (HttpStatus.SC_NOT_FOUND, "<html>error</html>", "text/html");
- ResponseHandler respHandler = new ResponseHandler (response, 1);
- int status = respHandler.getStatus ();
+ HttpResponse response = createResponse(HttpStatus.SC_NOT_FOUND, "<html>error</html>", "text/html");
+ ResponseHandler respHandler = new ResponseHandler(response, 1);
+
+ int status = respHandler.getStatus();
- assertEquals (HttpStatus.SC_NOT_IMPLEMENTED, status);
+ assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, status);
}
@Test
- public void tesGenricErrorResponse () throws ApiException {
+ public void tesGenricErrorResponse() throws ApiException {
String body = "{ \"response\": \"<xml>xml</xml>\"," + "\"messageCode\": 500,"
- + "\"message\": \"Something went wrong\"}";
+ + "\"message\": \"Something went wrong\"}";
- HttpResponse response = createResponse (500, body, "application/json");
- ResponseHandler respHandler = new ResponseHandler (response, 1);
- int status = respHandler.getStatus ();
- assertEquals (status, HttpStatus.SC_BAD_GATEWAY);
- assertEquals (respHandler.getResponse ().getMessage (), "Something went wrong");
+ HttpResponse response = createResponse(500, body, "application/json");
+ ResponseHandler respHandler = new ResponseHandler(response, 1);
+ int status = respHandler.getStatus();
+ assertEquals(status, HttpStatus.SC_BAD_GATEWAY);
+ assertEquals(respHandler.getResponse().getMessage(), "Something went wrong");
}
- private HttpResponse createResponse (int respStatus, String respBody, String contentType) {
- HttpResponse response = new BasicHttpResponse (new BasicStatusLine (new ProtocolVersion ("HTTP", 1, 1),
- respStatus,
- ""));
- response.setStatusCode (respStatus);
+ private HttpResponse createResponse(int respStatus, String respBody, String contentType) {
+ HttpResponse response =
+ new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), respStatus, ""));
+ response.setStatusCode(respStatus);
try {
- response.setEntity (new StringEntity (respBody));
- response.setHeader ("Content-Type", contentType);
+ response.setEntity(new StringEntity(respBody));
+ response.setHeader("Content-Type", contentType);
} catch (Exception e) {
- e.printStackTrace ();
+ e.printStackTrace();
}
return response;
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java
index dae6542b8b..6c674db9f4 100644
--- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java
@@ -2,11 +2,8 @@ package org.onap.so.apihandler.filters;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
-
import java.io.IOException;
-
import javax.ws.rs.container.ContainerRequestContext;
-
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
@@ -29,40 +26,41 @@ public class RequestIdFilterTest {
@Mock
ContainerRequestContext mockContext;
-
- @Mock
- protected RequestsDbClient requestsDbClient;
-
+
+ @Mock
+ protected RequestsDbClient requestsDbClient;
+
@InjectMocks
@Spy
RequestIdFilter requestIdFilter;
-
+
@Rule
public ExpectedException thrown = ExpectedException.none();
-
- @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
-
- @Test
- public void filterTest() throws IOException {
-
- String requestId = "32807a28-1a14-4b88-b7b3-2950918aa769";
- MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
-
- //ExpectedRecord InfraActiveRequests
+
+ @Rule
+ public MockitoRule mockitoRule = MockitoJUnit.rule();
+
+ @Test
+ public void filterTest() throws IOException {
+
+ String requestId = "32807a28-1a14-4b88-b7b3-2950918aa769";
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
+
+ // ExpectedRecord InfraActiveRequests
InfraActiveRequests infraActiveRequests = new InfraActiveRequests();
infraActiveRequests.setRequestStatus("FAILED");
infraActiveRequests.setProgress(100L);
infraActiveRequests.setLastModifiedBy("APIH");
infraActiveRequests.setRequestScope("network");
infraActiveRequests.setRequestAction("deleteInstance");
- infraActiveRequests.setRequestId("32807a28-1a14-4b88-b7b3-2950918aa769");
-
- doReturn(infraActiveRequests).when(requestsDbClient).getInfraActiveRequestbyRequestId(requestId);
-
- requestIdFilter.filter(mockContext);
-
- Mockito.verify( requestIdFilter, Mockito.times(1)).filter(mockContext);
- assertEquals(MDC.get(ONAPLogConstants.MDCs.RESPONSE_CODE), String.valueOf(HttpStatus.SC_BAD_REQUEST));
-
- }
+ infraActiveRequests.setRequestId("32807a28-1a14-4b88-b7b3-2950918aa769");
+
+ doReturn(infraActiveRequests).when(requestsDbClient).getInfraActiveRequestbyRequestId(requestId);
+
+ requestIdFilter.filter(mockContext);
+
+ Mockito.verify(requestIdFilter, Mockito.times(1)).filter(mockContext);
+ assertEquals(MDC.get(ONAPLogConstants.MDCs.RESPONSE_CODE), String.valueOf(HttpStatus.SC_BAD_REQUEST));
+
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java
index 564121b7b5..9065a1a9ea 100644
--- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java
@@ -1,30 +1,23 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2018 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.so.apihandler.recipe;
import static org.junit.Assert.assertEquals;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
-
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.junit.Before;
@@ -32,41 +25,41 @@ import org.junit.Test;
import org.mockito.Mockito;
public class CamundaClientErrorHandlerTest {
-
- private ClientHttpResponse clientHttpResponse;
- private CamundaClientErrorHandler clientErrorHandler;
-
- @Before
- public void before() {
- clientHttpResponse = Mockito.mock(ClientHttpResponse.class);
- clientErrorHandler = new CamundaClientErrorHandler();
- }
-
- @Test
- public void handleError_SERVER_ERROR_Test() throws IOException {
- Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
- Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
- clientErrorHandler.handleError(clientHttpResponse);
- boolean serverHasError = clientErrorHandler.hasError(clientHttpResponse);
- assertEquals(true, serverHasError);
- }
-
- @Test
- public void handleError_CLIENT_ERROR_Test() throws IOException {
- Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST);
- Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
- clientErrorHandler.handleError(clientHttpResponse);
- boolean clientHasError = clientErrorHandler.hasError(clientHttpResponse);
- assertEquals(true, clientHasError);
- }
-
- @Test
- public void handleError_SUCCESS_Test() throws IOException {
- Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
- Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
- clientErrorHandler.handleError(clientHttpResponse);
- boolean hasNoError = clientErrorHandler.hasError(clientHttpResponse);
- assertEquals(false, hasNoError);
- }
-
-} \ No newline at end of file
+
+ private ClientHttpResponse clientHttpResponse;
+ private CamundaClientErrorHandler clientErrorHandler;
+
+ @Before
+ public void before() {
+ clientHttpResponse = Mockito.mock(ClientHttpResponse.class);
+ clientErrorHandler = new CamundaClientErrorHandler();
+ }
+
+ @Test
+ public void handleError_SERVER_ERROR_Test() throws IOException {
+ Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
+ Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
+ clientErrorHandler.handleError(clientHttpResponse);
+ boolean serverHasError = clientErrorHandler.hasError(clientHttpResponse);
+ assertEquals(true, serverHasError);
+ }
+
+ @Test
+ public void handleError_CLIENT_ERROR_Test() throws IOException {
+ Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST);
+ Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
+ clientErrorHandler.handleError(clientHttpResponse);
+ boolean clientHasError = clientErrorHandler.hasError(clientHttpResponse);
+ assertEquals(true, clientHasError);
+ }
+
+ @Test
+ public void handleError_SUCCESS_Test() throws IOException {
+ Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
+ Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
+ clientErrorHandler.handleError(clientHttpResponse);
+ boolean hasNoError = clientErrorHandler.hasError(clientHttpResponse);
+ assertEquals(false, hasNoError);
+ }
+
+}
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java
index 42190a4a1e..2cdf4f1a3f 100644
--- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java
@@ -26,15 +26,12 @@ import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onap.so.apihandler.common.ErrorNumbers;
import org.onap.so.apihandlerinfra.exceptions.*;
-
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
-
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
@@ -52,7 +49,8 @@ public class ApiExceptionTest {
thrown.expectMessage("Message rewritten");
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
- RecipeNotFoundException testException = new RecipeNotFoundException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).message("Message rewritten").build();
+ RecipeNotFoundException testException = new RecipeNotFoundException.Builder("Test Message",
+ HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).message("Message rewritten").build();
throw testException;
}
@@ -65,8 +63,9 @@ public class ApiExceptionTest {
thrown.expectMessage(startsWith("Request Failed due to BPEL error with HTTP Status ="));
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
- thrown.expect(hasProperty("variables",sameBeanAs(testVariables)));
- BPMNFailureException testException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).variables(testVariables).build();
+ thrown.expect(hasProperty("variables", sameBeanAs(testVariables)));
+ BPMNFailureException testException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,
+ ErrorNumbers.SVC_BAD_PARAMETER).variables(testVariables).build();
throw testException;
}
@@ -81,32 +80,39 @@ public class ApiExceptionTest {
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
thrown.expect(hasProperty("cause", sameBeanAs(ioException)));
- ClientConnectionException testException = new ClientConnectionException.Builder("test", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).cause(ioException).build();
+ ClientConnectionException testException =
+ new ClientConnectionException.Builder("test", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER)
+ .cause(ioException).build();
throw testException;
}
@Test
public void testDuplicateRequestException() throws ApiException {
- ErrorLoggerInfo testLog = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ErrorLoggerInfo testLog =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
thrown.expect(DuplicateRequestException.class);
thrown.expectMessage(startsWith("Error: Locked instance"));
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
thrown.expect(hasProperty("errorLoggerInfo", sameBeanAs(testLog)));
- DuplicateRequestException testException = new DuplicateRequestException.Builder("Test1", "Test2","Test3","Test4", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(testLog).build();
+ DuplicateRequestException testException = new DuplicateRequestException.Builder("Test1", "Test2", "Test3",
+ "Test4", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(testLog).build();
throw testException;
}
@Test
- public void testValidateException() throws ApiException {
+ public void testValidateException() throws ApiException {
thrown.expect(ValidateException.class);
thrown.expectMessage("Test Message");
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)));
- ValidateException testException = new ValidateException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).messageID(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).build();
+ ValidateException testException =
+ new ValidateException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER)
+ .messageID(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).build();
throw testException;
}
@@ -117,7 +123,9 @@ public class ApiExceptionTest {
thrown.expectMessage("Test Message");
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_CONFLICT)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
- VfModuleNotFoundException testException = new VfModuleNotFoundException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).httpResponseCode(HttpStatus.SC_CONFLICT).build();
+ VfModuleNotFoundException testException =
+ new VfModuleNotFoundException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,
+ ErrorNumbers.SVC_BAD_PARAMETER).httpResponseCode(HttpStatus.SC_CONFLICT).build();
throw testException;
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java
index 48711a2595..1beb3b37a7 100644
--- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java
+++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java
@@ -27,11 +27,11 @@ import ch.qos.logback.core.AppenderBase;
-public class TestAppender extends AppenderBase<ILoggingEvent> {
+public class TestAppender extends AppenderBase<ILoggingEvent> {
public static List<ILoggingEvent> events = new ArrayList<>();
-
- @Override
- protected void append(ILoggingEvent loggingEvent) {
- events.add(loggingEvent);
- }
+
+ @Override
+ protected void append(ILoggingEvent loggingEvent) {
+ events.add(loggingEvent);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapperTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapperTest.java
index 1962f00d52..2922aaa896 100644
--- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapperTest.java
+++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapperTest.java
@@ -32,19 +32,15 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
-
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;
-
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
@@ -62,7 +58,6 @@ import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException;
import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException;
import org.onap.so.apihandlerinfra.exceptions.ValidateException;
import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -70,93 +65,111 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(MockitoJUnitRunner.class)
public class ApiExceptionMapperTest {
- @Mock
- private HttpHeaders headers;
- @Mock
- private Marshaller marshaller;
-
- @InjectMocks
+ @Mock
+ private HttpHeaders headers;
+ @Mock
+ private Marshaller marshaller;
+
+ @InjectMocks
ApiExceptionMapper mapper = new ApiExceptionMapper();
- @Before
- public void setUp() {
- when(headers.getAcceptableMediaTypes()).thenReturn(Arrays.asList(MediaType.APPLICATION_JSON_TYPE));
- }
+ @Before
+ public void setUp() {
+ when(headers.getAcceptableMediaTypes()).thenReturn(Arrays.asList(MediaType.APPLICATION_JSON_TYPE));
+ }
+
@Test
public void testObjectMapperError() throws JsonProcessingException {
ObjectMapper mockedMapper = Mockito.mock(ObjectMapper.class);
Mockito.when(mockedMapper.writeValueAsString(anyObject())).thenThrow(JsonProcessingException.class);
- ValidateException validateException = new ValidateException.Builder("Test", 0 , null).build();
+ ValidateException validateException = new ValidateException.Builder("Test", 0, null).build();
ApiExceptionMapper mockedException = Mockito.spy(mapper);
Mockito.doReturn(mockedMapper).when(mockedException).createObjectMapper();
Response resp = mockedException.toResponse((ApiException) validateException);
- /// assertEquals(resp.getStatus(), HttpStatus.SC_BAD_REQUEST);
- assertThat(resp.getEntity().toString(),startsWith("Exception in buildServiceErrorResponse writing exceptionType to string"));
+ /// assertEquals(resp.getStatus(), HttpStatus.SC_BAD_REQUEST);
+ assertThat(resp.getEntity().toString(),
+ startsWith("Exception in buildServiceErrorResponse writing exceptionType to string"));
}
@Test
- public void testValidateResponse(){
- ValidateException validateException = new ValidateException.Builder("Test Message", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).build();
+ public void testValidateResponse() {
+ ValidateException validateException =
+ new ValidateException.Builder("Test Message", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER)
+ .build();
Response resp = mapper.toResponse((ApiException) validateException);
assertEquals(resp.getStatus(), HttpStatus.SC_BAD_REQUEST);
}
@Test
- public void testBPMNFailureResponse(){
- BPMNFailureException bpmnException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).build();
+ public void testBPMNFailureResponse() {
+ BPMNFailureException bpmnException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,
+ ErrorNumbers.SVC_BAD_PARAMETER).build();
Response resp = mapper.toResponse((ApiException) bpmnException);
assertEquals(resp.getStatus(), HttpStatus.SC_NOT_FOUND);
}
+
@Test
- public void testClientConnectionResponse(){
- ClientConnectionException clientConnectionException = new ClientConnectionException.Builder("test", HttpStatus.SC_INTERNAL_SERVER_ERROR,ErrorNumbers.SVC_BAD_PARAMETER).build();
- Response resp = mapper.toResponse((ApiException) clientConnectionException);
+ public void testClientConnectionResponse() {
+ ClientConnectionException clientConnectionException = new ClientConnectionException.Builder("test",
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).build();
+ Response resp = mapper.toResponse((ApiException) clientConnectionException);
assertEquals(resp.getStatus(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
+
@Test
public void testVFModuleResponse() {
- VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder("Test Message", HttpStatus.SC_CONFLICT,ErrorNumbers.SVC_BAD_PARAMETER).build();
- Response resp = mapper.toResponse((ApiException) vfModuleException);
+ VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder("Test Message",
+ HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_BAD_PARAMETER).build();
+ Response resp = mapper.toResponse((ApiException) vfModuleException);
assertEquals(resp.getStatus(), HttpStatus.SC_CONFLICT);
}
+
@Test
public void testDuplicateRequestResponse() throws IOException {
- DuplicateRequestException duplicateRequestException = new DuplicateRequestException.Builder("Test1", "Test2","Test3","Test4", HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_BAD_PARAMETER).build();
- Response resp = mapper.toResponse((ApiException) duplicateRequestException);
+ DuplicateRequestException duplicateRequestException = new DuplicateRequestException.Builder("Test1", "Test2",
+ "Test3", "Test4", HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_BAD_PARAMETER).build();
+ Response resp = mapper.toResponse((ApiException) duplicateRequestException);
assertEquals(resp.getStatus(), HttpStatus.SC_BAD_GATEWAY);
}
-
+
@Test
public void verifyXMLPath() throws JAXBException {
- when(headers.getAcceptableMediaTypes()).thenReturn(Arrays.asList(MediaType.APPLICATION_XML_TYPE));
- BPMNFailureException bpmnException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).build();
+ when(headers.getAcceptableMediaTypes()).thenReturn(Arrays.asList(MediaType.APPLICATION_XML_TYPE));
+ BPMNFailureException bpmnException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,
+ ErrorNumbers.SVC_BAD_PARAMETER).build();
ApiExceptionMapper mapperSpy = Mockito.spy(mapper);
doReturn(marshaller).when(mapperSpy).getMarshaller();
- Response resp = mapperSpy.toResponse((ApiException) bpmnException);
+ Response resp = mapperSpy.toResponse((ApiException) bpmnException);
verify(marshaller, times(1)).marshal(any(Object.class), any(Writer.class));
}
-
+
@Test
public void verifyMediaType() {
- ApiExceptionMapper mapperSpy = Mockito.spy(mapper);
- BPMNFailureException bpmnException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).build();
- when(headers.getAcceptableMediaTypes()).thenReturn(Arrays.asList(MediaType.APPLICATION_XML_TYPE.withCharset("UTF-8")));
- mapperSpy.toResponse(bpmnException);
- verify(mapperSpy, times(1)).buildServiceErrorResponse(any(String.class), any(String.class), ArgumentMatchers.isNull(), eq(MediaType.APPLICATION_XML_TYPE));
- when(headers.getAcceptableMediaTypes()).thenReturn(Arrays.asList(MediaType.APPLICATION_JSON_TYPE.withCharset("UTF-8")));
- mapperSpy = Mockito.spy(mapper);
- mapperSpy.toResponse(bpmnException);
- verify(mapperSpy, times(1)).buildServiceErrorResponse(any(String.class), any(String.class), ArgumentMatchers.isNull(), eq(MediaType.APPLICATION_JSON_TYPE));
- when(headers.getAcceptableMediaTypes()).thenReturn(null);
- mapperSpy = Mockito.spy(mapper);
- mapperSpy.toResponse(bpmnException);
- verify(mapperSpy, times(1)).buildServiceErrorResponse(any(String.class), any(String.class),ArgumentMatchers.isNull(), eq(MediaType.APPLICATION_JSON_TYPE));
+ ApiExceptionMapper mapperSpy = Mockito.spy(mapper);
+ BPMNFailureException bpmnException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,
+ ErrorNumbers.SVC_BAD_PARAMETER).build();
+ when(headers.getAcceptableMediaTypes())
+ .thenReturn(Arrays.asList(MediaType.APPLICATION_XML_TYPE.withCharset("UTF-8")));
+ mapperSpy.toResponse(bpmnException);
+ verify(mapperSpy, times(1)).buildServiceErrorResponse(any(String.class), any(String.class),
+ ArgumentMatchers.isNull(), eq(MediaType.APPLICATION_XML_TYPE));
+ when(headers.getAcceptableMediaTypes())
+ .thenReturn(Arrays.asList(MediaType.APPLICATION_JSON_TYPE.withCharset("UTF-8")));
+ mapperSpy = Mockito.spy(mapper);
+ mapperSpy.toResponse(bpmnException);
+ verify(mapperSpy, times(1)).buildServiceErrorResponse(any(String.class), any(String.class),
+ ArgumentMatchers.isNull(), eq(MediaType.APPLICATION_JSON_TYPE));
+ when(headers.getAcceptableMediaTypes()).thenReturn(null);
+ mapperSpy = Mockito.spy(mapper);
+ mapperSpy.toResponse(bpmnException);
+ verify(mapperSpy, times(1)).buildServiceErrorResponse(any(String.class), any(String.class),
+ ArgumentMatchers.isNull(), eq(MediaType.APPLICATION_JSON_TYPE));
}
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/common/ResponseBuilder.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/common/ResponseBuilder.java
index 67bbc3db8e..b921f5beea 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/common/ResponseBuilder.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/common/ResponseBuilder.java
@@ -23,7 +23,6 @@ package org.onap.so.apihandler.common;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@@ -31,31 +30,31 @@ import org.springframework.stereotype.Component;
@Component
public class ResponseBuilder {
-
- @Value("${mso.infra.default.versions.apiMinorVersion}")
- private String apiMinorVersion;
- @Value("${mso.infra.default.versions.apiPatchVersion}")
- private String apiPatchVersion;
-
- public Response buildResponse(int status, String requestId, Object jsonResponse, String apiVersion) {
-
- if (apiVersion.matches("v[1-9]")) {
- apiVersion = apiVersion.substring(1);
- }
-
- String latestVersion = apiVersion + "." + apiMinorVersion + "." + apiPatchVersion;
-
- javax.ws.rs.core.Response.ResponseBuilder builder = Response.status(status)
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .header(CommonConstants.X_MINOR_VERSION, apiMinorVersion)
- .header(CommonConstants.X_PATCH_VERSION, apiPatchVersion)
- .header(CommonConstants.X_LATEST_VERSION, latestVersion);
-
- if(StringUtils.isNotBlank(requestId)) {
- builder.header(CommonConstants.X_TRANSACTION_ID, requestId);
- }
-
- return builder.entity(jsonResponse).build();
- }
+
+ @Value("${mso.infra.default.versions.apiMinorVersion}")
+ private String apiMinorVersion;
+ @Value("${mso.infra.default.versions.apiPatchVersion}")
+ private String apiPatchVersion;
+
+ public Response buildResponse(int status, String requestId, Object jsonResponse, String apiVersion) {
+
+ if (apiVersion.matches("v[1-9]")) {
+ apiVersion = apiVersion.substring(1);
+ }
+
+ String latestVersion = apiVersion + "." + apiMinorVersion + "." + apiPatchVersion;
+
+ javax.ws.rs.core.Response.ResponseBuilder builder =
+ Response.status(status).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .header(CommonConstants.X_MINOR_VERSION, apiMinorVersion)
+ .header(CommonConstants.X_PATCH_VERSION, apiPatchVersion)
+ .header(CommonConstants.X_LATEST_VERSION, latestVersion);
+
+ if (StringUtils.isNotBlank(requestId)) {
+ builder.header(CommonConstants.X_TRANSACTION_ID, requestId);
+ }
+
+ return builder.entity(jsonResponse).build();
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/filters/RequestUriFilter.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/filters/RequestUriFilter.java
index 91ab580b07..a3ff1ab95d 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/filters/RequestUriFilter.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/filters/RequestUriFilter.java
@@ -22,37 +22,40 @@ package org.onap.so.apihandler.filters;
import java.io.IOException;
import java.net.URI;
-
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.UriInfo;
-
import org.onap.so.apihandlerinfra.Constants;
@PreMatching
public class RequestUriFilter implements ContainerRequestFilter {
- private String requestURI;
- @Override
- public void filter(ContainerRequestContext context) throws IOException {
- UriInfo uriInfo = context.getUriInfo();
- URI baseURI = uriInfo.getBaseUri();
- requestURI = uriInfo.getPath();
-
- if(requestURI.contains("onap/so/infra/serviceInstances")){
- requestURI = requestURI.replaceFirst("serviceInstances", "serviceInstantiation");
- if(!requestURI.contains(Constants.SERVICE_INSTANCE_PATH)){
- //Adds /serviceInstances after the version provided in the URI
- requestURI = new StringBuilder(requestURI).insert(requestURI.indexOf(Constants.SERVICE_INSTANTIATION_PATH) + 24, Constants.SERVICE_INSTANCE_PATH).toString();
- }
- requestURI = baseURI + requestURI;
- URI uri = URI.create(requestURI);
- context.setRequestUri(uri);
- }
- }
- public String getRequestUri(){
- return requestURI;
- }
+ private String requestURI;
+
+ @Override
+ public void filter(ContainerRequestContext context) throws IOException {
+ UriInfo uriInfo = context.getUriInfo();
+ URI baseURI = uriInfo.getBaseUri();
+ requestURI = uriInfo.getPath();
+
+ if (requestURI.contains("onap/so/infra/serviceInstances")) {
+ requestURI = requestURI.replaceFirst("serviceInstances", "serviceInstantiation");
+ if (!requestURI.contains(Constants.SERVICE_INSTANCE_PATH)) {
+ // Adds /serviceInstances after the version provided in the URI
+ requestURI = new StringBuilder(requestURI)
+ .insert(requestURI.indexOf(Constants.SERVICE_INSTANTIATION_PATH) + 24,
+ Constants.SERVICE_INSTANCE_PATH)
+ .toString();
+ }
+ requestURI = baseURI + requestURI;
+ URI uri = URI.create(requestURI);
+ context.setRequestUri(uri);
+ }
+ }
+
+ public String getRequestUri() {
+ return requestURI;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java
index 74d5f7a9e6..71c56733b6 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java
@@ -23,7 +23,6 @@
package org.onap.so.apihandler.recipe;
import java.io.IOException;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
@@ -32,20 +31,19 @@ import org.springframework.web.client.ResponseErrorHandler;
-public class CamundaClientErrorHandler implements ResponseErrorHandler{
-
- private static Logger logger = LoggerFactory.getLogger(CamundaClientErrorHandler.class);
-
- @Override
- public void handleError(ClientHttpResponse response) throws IOException {
- logger.debug(response.getBody().toString());
- }
+public class CamundaClientErrorHandler implements ResponseErrorHandler {
+
+ private static Logger logger = LoggerFactory.getLogger(CamundaClientErrorHandler.class);
+
+ @Override
+ public void handleError(ClientHttpResponse response) throws IOException {
+ logger.debug(response.getBody().toString());
+ }
+
+ @Override
+ public boolean hasError(ClientHttpResponse response) throws IOException {
+ HttpStatus.Series series = response.getStatusCode().series();
+ return (HttpStatus.Series.CLIENT_ERROR.equals(series) || HttpStatus.Series.SERVER_ERROR.equals(series));
+ }
- @Override
- public boolean hasError(ClientHttpResponse response) throws IOException {
- HttpStatus.Series series = response.getStatusCode().series();
- return (HttpStatus.Series.CLIENT_ERROR.equals(series)
- || HttpStatus.Series.SERVER_ERROR.equals(series));
- }
-
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java
index 897e2a5fc8..77dbff9ebb 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java
@@ -22,29 +22,7 @@ package org.onap.so.apihandlerinfra;
/*
* Enum for Status values returned by API Handler to Tail-F
-*/
-public enum Action implements Actions{
- createInstance,
- updateInstance,
- deleteInstance,
- configureInstance,
- replaceInstance,
- activateInstance,
- deactivateInstance,
- enablePort,
- disablePort,
- addRelationships,
- removeRelationships,
- inPlaceSoftwareUpdate,
- applyUpdatedConfig,
- completeTask,
- assignInstance,
- unassignInstance,
- compareModel,
- scaleInstance,
- deactivateAndCloudDelete,
- scaleOut,
- recreateInstance,
- addMembers,
- removeMembers
+ */
+public enum Action implements Actions {
+ createInstance, updateInstance, deleteInstance, configureInstance, replaceInstance, activateInstance, deactivateInstance, enablePort, disablePort, addRelationships, removeRelationships, inPlaceSoftwareUpdate, applyUpdatedConfig, completeTask, assignInstance, unassignInstance, compareModel, scaleInstance, deactivateAndCloudDelete, scaleOut, recreateInstance, addMembers, removeMembers
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java
index f3f98f3f2a..bc1972a593 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra;
import java.util.concurrent.Executor;
-
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
@@ -31,43 +30,43 @@ import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator;
-@SpringBootApplication(scanBasePackages = { "org.onap"})
+@SpringBootApplication(scanBasePackages = {"org.onap"})
@EnableAsync
public class ApiHandlerApplication {
-
- @Value("${mso.async.core-pool-size}")
- private int corePoolSize;
- @Value("${mso.async.max-pool-size}")
- private int maxPoolSize;
+ @Value("${mso.async.core-pool-size}")
+ private int corePoolSize;
+
+ @Value("${mso.async.max-pool-size}")
+ private int maxPoolSize;
- @Value("${mso.async.queue-capacity}")
- private int queueCapacity;
+ @Value("${mso.async.queue-capacity}")
+ private int queueCapacity;
- private static final String LOGS_DIR = "logs_dir";
+ private static final String LOGS_DIR = "logs_dir";
- private static void setLogsDir() {
- if (System.getProperty(LOGS_DIR) == null) {
- System.getProperties().setProperty(LOGS_DIR, "./logs/apih/");
- }
- }
+ private static void setLogsDir() {
+ if (System.getProperty(LOGS_DIR) == null) {
+ System.getProperties().setProperty(LOGS_DIR, "./logs/apih/");
+ }
+ }
- public static void main(String[] args) {
- SpringApplication.run(ApiHandlerApplication.class, args);
- System.getProperties().setProperty("mso.db", "MARIADB");
- System.getProperties().setProperty("server.name", "Springboot");
- setLogsDir();
- }
+ public static void main(String[] args) {
+ SpringApplication.run(ApiHandlerApplication.class, args);
+ System.getProperties().setProperty("mso.db", "MARIADB");
+ System.getProperties().setProperty("server.name", "Springboot");
+ setLogsDir();
+ }
- @Bean
- public Executor asyncExecutor() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setCorePoolSize(corePoolSize);
- executor.setMaxPoolSize(maxPoolSize);
- executor.setQueueCapacity(queueCapacity);
- executor.setThreadNamePrefix("mso-apihandler-infra-");
- executor.setTaskDecorator(new MDCTaskDecorator());
- executor.initialize();
- return executor;
- }
+ @Bean
+ public Executor asyncExecutor() {
+ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+ executor.setCorePoolSize(corePoolSize);
+ executor.setMaxPoolSize(maxPoolSize);
+ executor.setQueueCapacity(queueCapacity);
+ executor.setThreadNamePrefix("mso-apihandler-infra-");
+ executor.setTaskDecorator(new MDCTaskDecorator());
+ executor.initialize();
+ return executor;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java
index de38bc717a..449aa4ba3f 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java
@@ -28,7 +28,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
@@ -39,7 +38,6 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.json.JSONObject;
@@ -64,7 +62,6 @@ import org.onap.so.db.request.beans.OperationStatus;
import org.onap.so.db.request.client.RequestsDbClient;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.onap.so.serviceinstancebeans.ModelInfo;
import org.onap.so.serviceinstancebeans.ModelType;
import org.onap.so.serviceinstancebeans.RequestDetails;
@@ -76,9 +73,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@@ -88,678 +83,308 @@ import io.swagger.annotations.ApiOperation;
@Api(value = "/onap/so/infra/e2eServiceInstances", description = "API Requests for E2E Service Instances")
public class E2EServiceInstances {
- private HashMap<String, String> instanceIdMap = new HashMap<>();
- private static final Logger logger = LoggerFactory.getLogger(E2EServiceInstances.class);
-
- private static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
-
- private static final String END_OF_THE_TRANSACTION = "End of the transaction, the final response is: ";
-
- @Autowired
- private MsoRequest msoRequest;
-
- @Autowired
- private RequestClientFactory requestClientFactory;
-
- @Autowired
- private RequestsDbClient requestsDbClient;
-
- @Autowired
- private CatalogDbClient catalogDbClient;
-
- @Autowired
- private ResponseBuilder builder;
-
- /**
- * POST Requests for E2E Service create Instance on a version provided
- * @throws ApiException
- */
-
- @POST
- @Path("/{version:[vV][3-5]}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create an E2E Service Instance on a version provided", response = Response.class)
- public Response createE2EServiceInstance(String request,
- @PathParam("version") String version) throws ApiException {
-
- return processE2EserviceInstances(request, Action.createInstance, null,
- version);
- }
-
- /**
- * PUT Requests for E2E Service update Instance on a version provided
- * @throws ApiException
- */
-
- @PUT
- @Path("/{version:[vV][3-5]}/{serviceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update an E2E Service Instance on a version provided and serviceId", response = Response.class)
- public Response updateE2EServiceInstance(String request,
- @PathParam("version") String version,
- @PathParam("serviceId") String serviceId) throws ApiException {
-
- instanceIdMap.put("serviceId", serviceId);
-
- return updateE2EserviceInstances(request, Action.updateInstance, instanceIdMap,
- version);
- }
-
- /**
- * DELETE Requests for E2E Service delete Instance on a specified version
- * and serviceId
- * @throws ApiException
- */
-
- @DELETE
- @Path("/{version:[vV][3-5]}/{serviceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Delete E2E Service Instance on a specified version and serviceId", response = Response.class)
- public Response deleteE2EServiceInstance(String request,
- @PathParam("version") String version,
- @PathParam("serviceId") String serviceId) throws ApiException {
-
- instanceIdMap.put("serviceId", serviceId);
-
- return deleteE2EserviceInstances(request, Action.deleteInstance,
- instanceIdMap, version);
- }
-
- @GET
- @Path("/{version:[vV][3-5]}/{serviceId}/operations/{operationId}")
- @ApiOperation(value = "Find e2eServiceInstances Requests for a given serviceId and operationId", response = Response.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response getE2EServiceInstances(
- @PathParam("serviceId") String serviceId,
- @PathParam("version") String version,
- @PathParam("operationId") String operationId) {
- return getE2EServiceInstance(serviceId, operationId, version);
- }
-
+ private HashMap<String, String> instanceIdMap = new HashMap<>();
+ private static final Logger logger = LoggerFactory.getLogger(E2EServiceInstances.class);
+
+ private static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
+
+ private static final String END_OF_THE_TRANSACTION = "End of the transaction, the final response is: ";
+
+ @Autowired
+ private MsoRequest msoRequest;
+
+ @Autowired
+ private RequestClientFactory requestClientFactory;
+
+ @Autowired
+ private RequestsDbClient requestsDbClient;
+
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+
+ @Autowired
+ private ResponseBuilder builder;
+
+ /**
+ * POST Requests for E2E Service create Instance on a version provided
+ *
+ * @throws ApiException
+ */
+
+ @POST
+ @Path("/{version:[vV][3-5]}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create an E2E Service Instance on a version provided", response = Response.class)
+ public Response createE2EServiceInstance(String request, @PathParam("version") String version) throws ApiException {
+
+ return processE2EserviceInstances(request, Action.createInstance, null, version);
+ }
+
+ /**
+ * PUT Requests for E2E Service update Instance on a version provided
+ *
+ * @throws ApiException
+ */
+
+ @PUT
+ @Path("/{version:[vV][3-5]}/{serviceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update an E2E Service Instance on a version provided and serviceId",
+ response = Response.class)
+ public Response updateE2EServiceInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceId") String serviceId) throws ApiException {
+
+ instanceIdMap.put("serviceId", serviceId);
+
+ return updateE2EserviceInstances(request, Action.updateInstance, instanceIdMap, version);
+ }
+
+ /**
+ * DELETE Requests for E2E Service delete Instance on a specified version and serviceId
+ *
+ * @throws ApiException
+ */
+
+ @DELETE
+ @Path("/{version:[vV][3-5]}/{serviceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete E2E Service Instance on a specified version and serviceId", response = Response.class)
+ public Response deleteE2EServiceInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceId") String serviceId) throws ApiException {
+
+ instanceIdMap.put("serviceId", serviceId);
+
+ return deleteE2EserviceInstances(request, Action.deleteInstance, instanceIdMap, version);
+ }
+
+ @GET
+ @Path("/{version:[vV][3-5]}/{serviceId}/operations/{operationId}")
+ @ApiOperation(value = "Find e2eServiceInstances Requests for a given serviceId and operationId",
+ response = Response.class)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getE2EServiceInstances(@PathParam("serviceId") String serviceId,
+ @PathParam("version") String version, @PathParam("operationId") String operationId) {
+ return getE2EServiceInstance(serviceId, operationId, version);
+ }
+
+ /**
+ * Scale Requests for E2E Service scale Instance on a specified version
+ *
+ * @throws ApiException
+ */
+
+ @POST
+ @Path("/{version:[vV][3-5]}/{serviceId}/scale")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Scale E2E Service Instance on a specified version", response = Response.class)
+ public Response scaleE2EServiceInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceId") String serviceId) throws ApiException {
+
+ logger.debug("------------------scale begin------------------");
+ instanceIdMap.put("serviceId", serviceId);
+ return scaleE2EserviceInstances(request, Action.scaleInstance, instanceIdMap, version);
+ }
+
/**
- * Scale Requests for E2E Service scale Instance on a specified version
- * @throws ApiException
+ * GET Requests for Comparing model of service instance with target version
+ *
+ * @throws ApiException
*/
-
- @POST
- @Path("/{version:[vV][3-5]}/{serviceId}/scale")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Scale E2E Service Instance on a specified version",response=Response.class)
- public Response scaleE2EServiceInstance(String request,
- @PathParam("version") String version,
- @PathParam("serviceId") String serviceId) throws ApiException {
-
- logger.debug("------------------scale begin------------------");
- instanceIdMap.put("serviceId", serviceId);
- return scaleE2EserviceInstances(request, Action.scaleInstance, instanceIdMap, version);
- }
- /**
- * GET Requests for Comparing model of service instance with target version
- * @throws ApiException
- */
-
- @POST
- @Path("/{version:[vV][3-5]}/{serviceId}/modeldifferences")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Find added and deleted resources of target model for the e2eserviceInstance on a given serviceId ", response = Response.class)
- public Response compareModelwithTargetVersion(String request,
- @PathParam("serviceId") String serviceId,
- @PathParam("version") String version) throws ApiException {
-
- instanceIdMap.put("serviceId", serviceId);
-
- return compareModelwithTargetVersion(request, Action.compareModel, instanceIdMap, version);
- }
-
- private Response compareModelwithTargetVersion(String requestJSON, Action action,
- HashMap<String, String> instanceIdMap, String version) throws ApiException {
-
- String requestId = UUID.randomUUID().toString();
- long startTime = System.currentTimeMillis();
-
- CompareModelsRequest e2eCompareModelReq;
-
- ObjectMapper mapper = new ObjectMapper();
- try {
- e2eCompareModelReq = mapper.readValue(requestJSON, CompareModelsRequest.class);
-
- } catch (Exception e) {
-
- logger.debug("Mapping of request to JSON object failed : ", e);
- Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
- MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
- ErrorNumbers.SVC_BAD_PARAMETER, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity().toString());
-
- return response;
- }
-
- return runCompareModelBPMWorkflow(e2eCompareModelReq, requestJSON, requestId, startTime, action, version);
-
- }
-
- private Response runCompareModelBPMWorkflow(CompareModelsRequest e2eCompareModelReq,
- String requestJSON, String requestId, long startTime, Action action, String version) throws ApiException {
-
- // Define RecipeLookupResult info here instead of query DB for efficiency
- String workflowUrl = "/mso/async/services/CompareModelofE2EServiceInstance";
- int recipeTimeout = 180;
-
- RequestClient requestClient;
- HttpResponse response;
-
- long subStartTime = System.currentTimeMillis();
-
- try {
- requestClient = requestClientFactory.getRequestClient(workflowUrl);
-
- JSONObject jjo = new JSONObject(requestJSON);
- String bpmnRequest = jjo.toString();
-
- // Capture audit event
- logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
- String serviceId = instanceIdMap.get("serviceId");
- String serviceType = e2eCompareModelReq.getServiceType();
- RequestClientParameter postParam = new RequestClientParameter.Builder()
- .setRequestId(requestId)
- .setBaseVfModule(false)
- .setRecipeTimeout(recipeTimeout)
- .setRequestAction(action.name())
- .setServiceInstanceId(serviceId)
- .setServiceType(serviceType)
- .setRequestDetails(bpmnRequest)
- .setALaCarte(false).build();
- response = requestClient.post(postParam);
- } catch (Exception e) {
- Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
- MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
- ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
- ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine",e);
- logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString());
- return resp;
- }
-
- if (response == null) {
- Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
- "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
- logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString());
- return resp;
- }
-
- ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
- int bpelStatus = respHandler.getStatus();
-
- return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action,
- instanceIdMap, version);
- }
-
- private Response getE2EServiceInstance(String serviceId, String operationId, String version) {
-
- GetE2EServiceInstanceResponse e2eServiceResponse = new GetE2EServiceInstanceResponse();
-
- String apiVersion = version.substring(1);
-
- long startTime = System.currentTimeMillis();
-
- OperationStatus operationStatus;
-
- try {
- operationStatus = requestsDbClient.getOneByServiceIdAndOperationId(serviceId,
- operationId);
- } catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(),
- "Exception while communciate with Request DB - Infra Request Lookup", e);
- Response response = msoRequest.buildServiceErrorResponse(
- HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
- e.getMessage(),
- ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
-
- }
-
- if (operationStatus == null) {
- Response resp = msoRequest.buildServiceErrorResponse(
- HttpStatus.SC_NO_CONTENT, MsoException.ServiceException,
- "E2E serviceId " + serviceId + " is not found in DB",
- ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.BusinessProcesssError.getValue(),
- "Null response from RequestDB when searching by serviceId");
- logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
- return resp;
-
- }
-
- e2eServiceResponse.setOperation(operationStatus);
-
- return builder.buildResponse(HttpStatus.SC_OK, null, e2eServiceResponse, apiVersion);
- }
-
- private Response deleteE2EserviceInstances(String requestJSON,
- Action action, HashMap<String, String> instanceIdMap, String version) throws ApiException {
- // TODO should be a new one or the same service instance Id
- long startTime = System.currentTimeMillis();
- E2EServiceInstanceDeleteRequest e2eDelReq;
-
- ObjectMapper mapper = new ObjectMapper();
- try {
- e2eDelReq = mapper.readValue(requestJSON,
- E2EServiceInstanceDeleteRequest.class);
-
- } catch (Exception e) {
-
- logger.debug("Mapping of request to JSON object failed : ", e);
- Response response = msoRequest.buildServiceErrorResponse(
- HttpStatus.SC_BAD_REQUEST,
- MsoException.ServiceException,
- "Mapping of request to JSON object failed. "
- + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER,
- null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
- }
-
- String requestId = UUID.randomUUID().toString();
- RecipeLookupResult recipeLookupResult;
- try {
- //TODO Get the service template model version uuid from AAI.
- recipeLookupResult = getServiceInstanceOrchestrationURI(null, action);
- } catch (Exception e) {
- logger.error(MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
-
- Response response = msoRequest.buildServiceErrorResponse(
- HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
- "No communication to catalog DB " + e.getMessage(),
- ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
-
- msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "Exception while communciate with "
- + "Catalog DB", action,
- ModelType.service.name(), requestJSON);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
- }
- if (recipeLookupResult == null) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.DataError.getValue(), "No recipe found in DB");
- Response response = msoRequest.buildServiceErrorResponse(
- HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
- "Recipe does not exist in catalog DB",
- ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
-
- msoRequest.createErrorRequestRecord(Status.FAILED, requestId,"Recipe does not exist in catalog DB", action, ModelType.service.name(), requestJSON);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
- }
-
- RequestClient requestClient;
- HttpResponse response;
-
- long subStartTime = System.currentTimeMillis();
- try {
- requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI());
-
- JSONObject jjo = new JSONObject(requestJSON);
- jjo.put("operationId", requestId);
-
- String bpmnRequest = jjo.toString();
-
- // Capture audit event
- logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
- String serviceId = instanceIdMap.get("serviceId");
- String serviceInstanceType = e2eDelReq.getServiceType();
- RequestClientParameter clientParam = new RequestClientParameter.Builder()
- .setRequestId(requestId)
- .setBaseVfModule(false)
- .setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
- .setRequestAction(action.name())
- .setServiceInstanceId(serviceId)
- .setServiceType(serviceInstanceType)
- .setRequestDetails(bpmnRequest)
- .setApiVersion(version)
- .setALaCarte(false)
- .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build();
- response = requestClient.post(clientParam);
-
- } catch (Exception e) {
- Response resp = msoRequest.buildServiceErrorResponse(
- HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
- "Failed calling bpmn " + e.getMessage(),
- ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine");
- logger.debug("End of the transaction, the final response is: " + resp.getEntity());
- return resp;
- }
-
- if (response == null) {
- Response resp = msoRequest.buildServiceErrorResponse(
- HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
- "bpelResponse is null",
- ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
- logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
- return resp;
- }
-
- ResponseHandler respHandler = new ResponseHandler(response,
- requestClient.getType());
- int bpelStatus = respHandler.getStatus();
-
- return beplStatusUpdate(requestId, startTime, requestClient, respHandler,
- bpelStatus, action, instanceIdMap, version);
- }
-
- private Response updateE2EserviceInstances(String requestJSON, Action action,
- HashMap<String, String> instanceIdMap, String version) throws ApiException {
-
- String requestId = UUID.randomUUID().toString();
- long startTime = System.currentTimeMillis();
- E2EServiceInstanceRequest e2eSir;
- String serviceId = instanceIdMap.get("serviceId");
-
- ObjectMapper mapper = new ObjectMapper();
- try {
- e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class);
-
- } catch (Exception e) {
-
- logger.debug("Mapping of request to JSON object failed : ", e);
- Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
- MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
- ErrorNumbers.SVC_BAD_PARAMETER, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
- }
-
- ServiceInstancesRequest sir = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
- sir.getRequestDetails().getRequestParameters().setaLaCarte(true);
- try {
- parseRequest(sir, instanceIdMap, action, version, requestJSON, false, requestId);
- } catch (Exception e) {
- logger.debug("Validation failed: ", e);
- Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
- MsoException.ServiceException, "Error parsing request. " + e.getMessage(),
- ErrorNumbers.SVC_BAD_PARAMETER, null, version);
- if (requestId != null) {
- logger.debug("Logging failed message to the database");
- }
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
- }
-
- RecipeLookupResult recipeLookupResult;
- try {
- recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action);
- } catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
- Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
- MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
- ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
-
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
-
- return response;
- }
-
- if (recipeLookupResult == null) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.DataError.getValue(), "No recipe found in DB");
- Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
- MsoException.ServiceException, "Recipe does not exist in catalog DB",
- ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
-
- return response;
- }
-
- String serviceInstanceType = e2eSir.getService().getServiceType();
-
- RequestClient requestClient;
- HttpResponse response;
-
- long subStartTime = System.currentTimeMillis();
- String sirRequestJson = convertToString(sir);
-
- try {
- requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI());
-
- // Capture audit event
- logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
- RequestClientParameter postParam = new RequestClientParameter.Builder()
- .setRequestId(requestId)
- .setBaseVfModule(false)
- .setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
- .setRequestAction(action.name())
- .setServiceInstanceId(serviceId)
- .setServiceType(serviceInstanceType)
- .setRequestDetails(sirRequestJson)
- .setApiVersion(version)
- .setALaCarte(false)
- .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build();
- response = requestClient.post(postParam);
- } catch (Exception e) {
- logger.debug("Exception while communicate with BPMN engine", e);
- Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
- MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
- ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
-
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine");
- logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity());
-
- return getBPMNResp;
- }
-
- if (response == null) {
- Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
- MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
- logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity());
- return getBPMNResp;
- }
-
- ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
- int bpelStatus = respHandler.getStatus();
-
- return beplStatusUpdate(serviceId, startTime, requestClient, respHandler,
- bpelStatus, action, instanceIdMap, version);
- }
-
- private Response processE2EserviceInstances(String requestJSON, Action action,
- HashMap<String, String> instanceIdMap, String version) throws ApiException {
-
- String requestId = UUID.randomUUID().toString();
- long startTime = System.currentTimeMillis();
- E2EServiceInstanceRequest e2eSir;
-
- MsoRequest msoRequest = new MsoRequest();
- ObjectMapper mapper = new ObjectMapper();
- try {
- e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class);
-
- } catch (Exception e) {
-
- logger.debug("Mapping of request to JSON object failed : ", e);
- Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
- MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
- ErrorNumbers.SVC_BAD_PARAMETER, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
- }
-
- ServiceInstancesRequest sir = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
- sir.getRequestDetails().getRequestParameters().setaLaCarte(true);
- try {
- parseRequest(sir, instanceIdMap, action, version, requestJSON, false, requestId);
- } catch (Exception e) {
- logger.debug("Validation failed: ", e);
- Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
- MsoException.ServiceException, "Error parsing request. " + e.getMessage(),
- ErrorNumbers.SVC_BAD_PARAMETER, null, version);
- if (requestId != null) {
- logger.debug("Logging failed message to the database");
- }
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
- }
-
- RecipeLookupResult recipeLookupResult;
- try {
- recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action);
- } catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
- Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
- MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
- ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
- }
-
- if (recipeLookupResult == null) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.DataError.getValue(), "No recipe found in DB");
- Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
- MsoException.ServiceException, "Recipe does not exist in catalog DB",
- ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
- }
-
- String serviceInstanceType = e2eSir.getService().getServiceType();
-
- String serviceId = "";
- RequestClient requestClient;
- HttpResponse response;
-
- long subStartTime = System.currentTimeMillis();
- String sirRequestJson = convertToString(sir);
-
- try {
- requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI());
-
- // Capture audit event
- logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
- RequestClientParameter parameter = new RequestClientParameter.Builder()
- .setRequestId(requestId)
- .setBaseVfModule(false)
- .setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
- .setRequestAction(action.name())
- .setServiceInstanceId(serviceId)
- .setServiceType(serviceInstanceType)
- .setRequestDetails(sirRequestJson)
- .setApiVersion(version)
- .setALaCarte(false)
- .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build();
- response = requestClient.post(parameter);
- } catch (Exception e) {
- Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
- MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
- ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
-
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine");
- logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
- return resp;
- }
-
- if (response == null) {
- Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
- MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
- logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
- return resp;
- }
-
- ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
- int bpelStatus = respHandler.getStatus();
-
- return beplStatusUpdate(requestId, startTime, requestClient, respHandler,
- bpelStatus, action, instanceIdMap, version);
- }
-
- private Response scaleE2EserviceInstances(String requestJSON,
- Action action, HashMap<String, String> instanceIdMap, String version) throws ApiException {
+
+ @POST
+ @Path("/{version:[vV][3-5]}/{serviceId}/modeldifferences")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(
+ value = "Find added and deleted resources of target model for the e2eserviceInstance on a given serviceId ",
+ response = Response.class)
+ public Response compareModelwithTargetVersion(String request, @PathParam("serviceId") String serviceId,
+ @PathParam("version") String version) throws ApiException {
+
+ instanceIdMap.put("serviceId", serviceId);
+
+ return compareModelwithTargetVersion(request, Action.compareModel, instanceIdMap, version);
+ }
+
+ private Response compareModelwithTargetVersion(String requestJSON, Action action,
+ HashMap<String, String> instanceIdMap, String version) throws ApiException {
String requestId = UUID.randomUUID().toString();
long startTime = System.currentTimeMillis();
- E2EServiceInstanceScaleRequest e2eScaleReq;
+
+ CompareModelsRequest e2eCompareModelReq;
ObjectMapper mapper = new ObjectMapper();
try {
- e2eScaleReq = mapper.readValue(requestJSON,
- E2EServiceInstanceScaleRequest.class);
+ e2eCompareModelReq = mapper.readValue(requestJSON, CompareModelsRequest.class);
} catch (Exception e) {
logger.debug("Mapping of request to JSON object failed : ", e);
- Response response = msoRequest.buildServiceErrorResponse(
- HttpStatus.SC_BAD_REQUEST,
- MsoException.ServiceException,
- "Mapping of request to JSON object failed. "
- + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER,
- null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
+ MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
+ ErrorNumbers.SVC_BAD_PARAMETER, null, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity().toString());
+
+ return response;
}
+ return runCompareModelBPMWorkflow(e2eCompareModelReq, requestJSON, requestId, startTime, action, version);
+
+ }
+
+ private Response runCompareModelBPMWorkflow(CompareModelsRequest e2eCompareModelReq, String requestJSON,
+ String requestId, long startTime, Action action, String version) throws ApiException {
+
+ // Define RecipeLookupResult info here instead of query DB for efficiency
+ String workflowUrl = "/mso/async/services/CompareModelofE2EServiceInstance";
+ int recipeTimeout = 180;
+
+ RequestClient requestClient;
+ HttpResponse response;
+
+ long subStartTime = System.currentTimeMillis();
+
+ try {
+ requestClient = requestClientFactory.getRequestClient(workflowUrl);
+
+ JSONObject jjo = new JSONObject(requestJSON);
+ String bpmnRequest = jjo.toString();
+
+ // Capture audit event
+ logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
+ String serviceId = instanceIdMap.get("serviceId");
+ String serviceType = e2eCompareModelReq.getServiceType();
+ RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId)
+ .setBaseVfModule(false).setRecipeTimeout(recipeTimeout).setRequestAction(action.name())
+ .setServiceInstanceId(serviceId).setServiceType(serviceType).setRequestDetails(bpmnRequest)
+ .setALaCarte(false).build();
+ response = requestClient.post(postParam);
+ } catch (Exception e) {
+ Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
+ MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
+ ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
+ logger.error("", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
+ ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine", e);
+ logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString());
+ return resp;
+ }
+
+ if (response == null) {
+ Response resp =
+ msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
+ "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
+ logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString());
+ return resp;
+ }
+
+ ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
+ int bpelStatus = respHandler.getStatus();
+
+ return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
+ version);
+ }
+
+ private Response getE2EServiceInstance(String serviceId, String operationId, String version) {
+
+ GetE2EServiceInstanceResponse e2eServiceResponse = new GetE2EServiceInstanceResponse();
+
+ String apiVersion = version.substring(1);
+
+ long startTime = System.currentTimeMillis();
+
+ OperationStatus operationStatus;
+
+ try {
+ operationStatus = requestsDbClient.getOneByServiceIdAndOperationId(serviceId, operationId);
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.AvailabilityError.getValue(),
+ "Exception while communciate with Request DB - Infra Request Lookup", e);
+ Response response =
+ msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
+ e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
+
+ }
+
+ if (operationStatus == null) {
+ Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NO_CONTENT,
+ MsoException.ServiceException, "E2E serviceId " + serviceId + " is not found in DB",
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Null response from RequestDB when searching by serviceId");
+ logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
+ return resp;
+
+ }
+
+ e2eServiceResponse.setOperation(operationStatus);
+
+ return builder.buildResponse(HttpStatus.SC_OK, null, e2eServiceResponse, apiVersion);
+ }
+
+ private Response deleteE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
+ String version) throws ApiException {
+ // TODO should be a new one or the same service instance Id
+ long startTime = System.currentTimeMillis();
+ E2EServiceInstanceDeleteRequest e2eDelReq;
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ e2eDelReq = mapper.readValue(requestJSON, E2EServiceInstanceDeleteRequest.class);
+
+ } catch (Exception e) {
+
+ logger.debug("Mapping of request to JSON object failed : ", e);
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
+ MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
+ ErrorNumbers.SVC_BAD_PARAMETER, null, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
+ }
+
+ String requestId = UUID.randomUUID().toString();
RecipeLookupResult recipeLookupResult;
try {
- //TODO Get the service template model version uuid from AAI.
- recipeLookupResult = getServiceInstanceOrchestrationURI(null, action);
+ // TODO Get the service template model version uuid from AAI.
+ recipeLookupResult = getServiceInstanceOrchestrationURI(null, action);
} catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
+ logger.error(MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
- Response response = msoRequest.buildServiceErrorResponse(
- HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
- "No communication to catalog DB " + e.getMessage(),
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
+ MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
-
- msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "No communication to catalog DB " + e.getMessage(), action, ModelType.service.name(), requestJSON);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
+
+ msoRequest.createErrorRequestRecord(Status.FAILED, requestId,
+ "Exception while communciate with " + "Catalog DB", action, ModelType.service.name(), requestJSON);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
}
if (recipeLookupResult == null) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.DataError.getValue(), "No recipe found in DB");
-
- Response response = msoRequest.buildServiceErrorResponse(
- HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
- "Recipe does not exist in catalog DB",
- ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
- msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "No recipe found in DB", action, ModelType.service.name(), requestJSON);
- logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
- return response;
+ logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.DataError.getValue(), "No recipe found in DB");
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
+ MsoException.ServiceException, "Recipe does not exist in catalog DB",
+ ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
+
+ msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "Recipe does not exist in catalog DB", action,
+ ModelType.service.name(), requestJSON);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
}
RequestClient requestClient;
@@ -775,274 +400,591 @@ public class E2EServiceInstances {
String bpmnRequest = jjo.toString();
// Capture audit event
- logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
- String serviceId = instanceIdMap.get("serviceId");
- String serviceInstanceType = e2eScaleReq.getService().getServiceType();
- RequestClientParameter postParam = new RequestClientParameter.Builder()
- .setRequestId(requestId)
- .setBaseVfModule(false)
- .setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
- .setRequestAction(action.name())
- .setServiceInstanceId(serviceId)
- .setServiceType(serviceInstanceType)
- .setRequestDetails(bpmnRequest)
- .setApiVersion(version)
- .setALaCarte(false)
- .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build();
+ logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
+ String serviceId = instanceIdMap.get("serviceId");
+ String serviceInstanceType = e2eDelReq.getServiceType();
+ RequestClientParameter clientParam = new RequestClientParameter.Builder().setRequestId(requestId)
+ .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
+ .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType)
+ .setRequestDetails(bpmnRequest).setApiVersion(version).setALaCarte(false)
+ .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build();
+ response = requestClient.post(clientParam);
+
+ } catch (Exception e) {
+ Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
+ MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
+ ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine");
+ logger.debug("End of the transaction, the final response is: " + resp.getEntity());
+ return resp;
+ }
+
+ if (response == null) {
+ Response resp =
+ msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
+ "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
+ logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
+ return resp;
+ }
+
+ ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
+ int bpelStatus = respHandler.getStatus();
+
+ return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
+ version);
+ }
+
+ private Response updateE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
+ String version) throws ApiException {
+
+ String requestId = UUID.randomUUID().toString();
+ long startTime = System.currentTimeMillis();
+ E2EServiceInstanceRequest e2eSir;
+ String serviceId = instanceIdMap.get("serviceId");
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class);
+
+ } catch (Exception e) {
+
+ logger.debug("Mapping of request to JSON object failed : ", e);
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
+ MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
+ ErrorNumbers.SVC_BAD_PARAMETER, null, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
+ }
+
+ ServiceInstancesRequest sir = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
+ sir.getRequestDetails().getRequestParameters().setaLaCarte(true);
+ try {
+ parseRequest(sir, instanceIdMap, action, version, requestJSON, false, requestId);
+ } catch (Exception e) {
+ logger.debug("Validation failed: ", e);
+ Response response =
+ msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
+ "Error parsing request. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version);
+ if (requestId != null) {
+ logger.debug("Logging failed message to the database");
+ }
+ logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
+ }
+
+ RecipeLookupResult recipeLookupResult;
+ try {
+ recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action);
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
+ MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
+ ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
+
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+
+ return response;
+ }
+
+ if (recipeLookupResult == null) {
+ logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.DataError.getValue(), "No recipe found in DB");
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
+ MsoException.ServiceException, "Recipe does not exist in catalog DB",
+ ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+
+ return response;
+ }
+
+ String serviceInstanceType = e2eSir.getService().getServiceType();
+
+ RequestClient requestClient;
+ HttpResponse response;
+
+ long subStartTime = System.currentTimeMillis();
+ String sirRequestJson = convertToString(sir);
+
+ try {
+ requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI());
+
+ // Capture audit event
+ logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
+ RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId)
+ .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
+ .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType)
+ .setRequestDetails(sirRequestJson).setApiVersion(version).setALaCarte(false)
+ .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build();
response = requestClient.post(postParam);
- } catch (Exception e) {
- Response resp = msoRequest.buildServiceErrorResponse(
- HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
- "Failed calling bpmn " + e.getMessage(),
+ } catch (Exception e) {
+ logger.debug("Exception while communicate with BPMN engine", e);
+ Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
+ MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine", e);
- logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
- return resp;
+ logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine");
+ logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity());
+
+ return getBPMNResp;
}
if (response == null) {
- Response resp = msoRequest.buildServiceErrorResponse(
- HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
- "bpelResponse is null",
+ Response getBPMNResp =
+ msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
+ "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
+ logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity());
+ return getBPMNResp;
+ }
+
+ ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
+ int bpelStatus = respHandler.getStatus();
+
+ return beplStatusUpdate(serviceId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
+ version);
+ }
+
+ private Response processE2EserviceInstances(String requestJSON, Action action,
+ HashMap<String, String> instanceIdMap, String version) throws ApiException {
+
+ String requestId = UUID.randomUUID().toString();
+ long startTime = System.currentTimeMillis();
+ E2EServiceInstanceRequest e2eSir;
+
+ MsoRequest msoRequest = new MsoRequest();
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class);
+
+ } catch (Exception e) {
+
+ logger.debug("Mapping of request to JSON object failed : ", e);
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
+ MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
+ ErrorNumbers.SVC_BAD_PARAMETER, null, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
+ }
+
+ ServiceInstancesRequest sir = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
+ sir.getRequestDetails().getRequestParameters().setaLaCarte(true);
+ try {
+ parseRequest(sir, instanceIdMap, action, version, requestJSON, false, requestId);
+ } catch (Exception e) {
+ logger.debug("Validation failed: ", e);
+ Response response =
+ msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
+ "Error parsing request. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version);
+ if (requestId != null) {
+ logger.debug("Logging failed message to the database");
+ }
+ logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
+ }
+
+ RecipeLookupResult recipeLookupResult;
+ try {
+ recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action);
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
+ MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
+ ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
+ }
+
+ if (recipeLookupResult == null) {
+ logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.DataError.getValue(), "No recipe found in DB");
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
+ MsoException.ServiceException, "Recipe does not exist in catalog DB",
+ ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
+ }
+
+ String serviceInstanceType = e2eSir.getService().getServiceType();
+
+ String serviceId = "";
+ RequestClient requestClient;
+ HttpResponse response;
+
+ long subStartTime = System.currentTimeMillis();
+ String sirRequestJson = convertToString(sir);
+
+ try {
+ requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI());
+
+ // Capture audit event
+ logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
+ RequestClientParameter parameter = new RequestClientParameter.Builder().setRequestId(requestId)
+ .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
+ .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType)
+ .setRequestDetails(sirRequestJson).setApiVersion(version).setALaCarte(false)
+ .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build();
+ response = requestClient.post(parameter);
+ } catch (Exception e) {
+ Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
+ MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
+ ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
+
+ logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine");
+ logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
+ return resp;
+ }
+
+ if (response == null) {
+ Response resp =
+ msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
+ "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
+ logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
+ return resp;
+ }
+
+ ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
+ int bpelStatus = respHandler.getStatus();
+
+ return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
+ version);
+ }
+
+ private Response scaleE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
+ String version) throws ApiException {
+
+ String requestId = UUID.randomUUID().toString();
+ long startTime = System.currentTimeMillis();
+ E2EServiceInstanceScaleRequest e2eScaleReq;
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ e2eScaleReq = mapper.readValue(requestJSON, E2EServiceInstanceScaleRequest.class);
+
+ } catch (Exception e) {
+
+ logger.debug("Mapping of request to JSON object failed : ", e);
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
+ MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
+ ErrorNumbers.SVC_BAD_PARAMETER, null, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
+ }
+
+ RecipeLookupResult recipeLookupResult;
+ try {
+ // TODO Get the service template model version uuid from AAI.
+ recipeLookupResult = getServiceInstanceOrchestrationURI(null, action);
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
+
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
+ MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
+ ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
+
+ msoRequest.createErrorRequestRecord(Status.FAILED, requestId,
+ "No communication to catalog DB " + e.getMessage(), action, ModelType.service.name(), requestJSON);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
+ }
+ if (recipeLookupResult == null) {
+ logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.DataError.getValue(), "No recipe found in DB");
+
+ Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
+ MsoException.ServiceException, "Recipe does not exist in catalog DB",
+ ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
+ msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "No recipe found in DB", action,
+ ModelType.service.name(), requestJSON);
+ logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
+ return response;
+ }
+
+ RequestClient requestClient;
+ HttpResponse response;
+
+ long subStartTime = System.currentTimeMillis();
+ try {
+ requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI());
+
+ JSONObject jjo = new JSONObject(requestJSON);
+ jjo.put("operationId", requestId);
+
+ String bpmnRequest = jjo.toString();
+
+ // Capture audit event
+ logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
+ String serviceId = instanceIdMap.get("serviceId");
+ String serviceInstanceType = e2eScaleReq.getService().getServiceType();
+ RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId)
+ .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
+ .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType)
+ .setRequestDetails(bpmnRequest).setApiVersion(version).setALaCarte(false)
+ .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build();
+ response = requestClient.post(postParam);
+ } catch (Exception e) {
+ Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
+ MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
- logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
- return resp;
+
+ logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine", e);
+ logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
+ return resp;
}
- ResponseHandler respHandler = new ResponseHandler(response,
- requestClient.getType());
+ if (response == null) {
+ Response resp =
+ msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
+ "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
+ ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
+ logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
+ return resp;
+ }
+
+ ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
int bpelStatus = respHandler.getStatus();
- return beplStatusUpdate(requestId, startTime, requestClient, respHandler,
- bpelStatus, action, instanceIdMap, version);
+ return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
+ version);
}
- private Response beplStatusUpdate(String serviceId, long startTime,
- RequestClient requestClient,
- ResponseHandler respHandler, int bpelStatus, Action action,
- HashMap<String, String> instanceIdMap, String version) {
-
- String apiVersion = version.substring(1);
-
- // BPMN accepted the request, the request is in progress
- if (bpelStatus == HttpStatus.SC_ACCEPTED) {
- String camundaJSONResponseBody = respHandler.getResponseBody();
- logger.debug("Received from Camunda: " + camundaJSONResponseBody);
- logger.debug(END_OF_THE_TRANSACTION + camundaJSONResponseBody);
- return builder.buildResponse(HttpStatus.SC_ACCEPTED, null, camundaJSONResponseBody, apiVersion);
- } else {
- List<String> variables = new ArrayList<>();
- variables.add(bpelStatus + "");
- String camundaJSONResponseBody = respHandler.getResponseBody();
- if (camundaJSONResponseBody != null
- && !camundaJSONResponseBody.isEmpty()) {
- Response resp = msoRequest.buildServiceErrorResponse(
- bpelStatus, MsoException.ServiceException,
- "Request Failed due to BPEL error with HTTP Status= %1 "
- + '\n' + camundaJSONResponseBody,
- ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(),
- ErrorCode.BusinessProcesssError.getValue(),
- "Response from BPEL engine is failed with HTTP Status=" + bpelStatus);
- logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
- return resp;
- } else {
- Response resp = msoRequest
- .buildServiceErrorResponse(
- bpelStatus,
- MsoException.ServiceException,
- "Request Failed due to BPEL error with HTTP Status= %1",
- ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
- variables, version);
- logger.error("", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(),
- ErrorCode.BusinessProcesssError.getValue(),
- "Response from BPEL engine is empty");
- logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
- return resp;
- }
- }
- }
-
- /**
- * Getting recipes from catalogDb
- *
- * @param serviceModelUUID the service model version uuid
- * @param action the action for the service
- * @return the service recipe result
- */
- private RecipeLookupResult getServiceInstanceOrchestrationURI(String serviceModelUUID, Action action) {
-
- RecipeLookupResult recipeLookupResult = getServiceURI(serviceModelUUID, action);
-
- if (recipeLookupResult != null) {
- logger.debug(
- "Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + ", recipe Timeout is: " + Integer
- .toString(recipeLookupResult.getRecipeTimeout()));
- } else {
- logger.debug("No matching recipe record found");
- }
- return recipeLookupResult;
- }
-
- /**
- * Getting recipes from catalogDb
- * If Service recipe is not set, use default recipe, if set , use special recipe.
- * @param serviceModelUUID the service version uuid
- * @param action the action of the service.
- * @return the service recipe result.
- */
- private RecipeLookupResult getServiceURI(String serviceModelUUID, Action action) {
-
- String defaultServiceModelName = "UUI_DEFAULT";
-
- Service defaultServiceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
- //set recipe as default generic recipe
- ServiceRecipe recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(defaultServiceRecord.getModelUUID(), action.name());
- //check the service special recipe
- if(null != serviceModelUUID && ! serviceModelUUID.isEmpty()){
- ServiceRecipe serviceSpecialRecipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(
- serviceModelUUID, action.name());
- if(null != serviceSpecialRecipe){
- //set service special recipe.
- recipe = serviceSpecialRecipe;
- }
- }
-
- if (recipe == null) {
- return null;
- }
- return new RecipeLookupResult(recipe.getOrchestrationUri(),
- recipe.getRecipeTimeout(), recipe.getParamXsd());
-
- }
-
- /**
- * Converting E2EServiceInstanceRequest to ServiceInstanceRequest and
- * passing it to camunda engine.
- *
- * @param e2eSir
- * @return
- */
- private ServiceInstancesRequest mapReqJsonToSvcInstReq(E2EServiceInstanceRequest e2eSir,
- String requestJSON) {
-
- ServiceInstancesRequest sir = new ServiceInstancesRequest();
-
- String returnString = null;
- RequestDetails requestDetails = new RequestDetails();
- ModelInfo modelInfo = new ModelInfo();
-
- // ModelInvariantId
- modelInfo.setModelInvariantId(e2eSir.getService().getServiceInvariantUuid());
-
- // modelNameVersionId
- modelInfo.setModelNameVersionId(e2eSir.getService().getServiceUuid());
-
- // String modelInfoValue =
- // e2eSir.getService().getParameters().getNodeTemplateName();
- // String[] arrayOfInfo = modelInfoValue.split(":");
- // String modelName = arrayOfInfo[0];
- // String modelVersion = arrayOfInfo[1];
-
- // TODO: To ensure, if we dont get the values from the UUI
- String modelName = "voLTE";
- String modelVersion = "1.0";
- // modelName
- modelInfo.setModelName(modelName);
-
- // modelVersion
- modelInfo.setModelVersion(modelVersion);
-
- // modelType
- modelInfo.setModelType(ModelType.service);
-
- // setting modelInfo to requestDetails
- requestDetails.setModelInfo(modelInfo);
-
- SubscriberInfo subscriberInfo = new SubscriberInfo();
-
- // globalsubscriberId
- subscriberInfo.setGlobalSubscriberId(e2eSir.getService().getGlobalSubscriberId());
-
- // setting subscriberInfo to requestDetails
- requestDetails.setSubscriberInfo(subscriberInfo);
-
- RequestInfo requestInfo = new RequestInfo();
-
- // instanceName
- requestInfo.setInstanceName(e2eSir.getService().getName());
-
- // source
- requestInfo.setSource("UUI");
-
- // suppressRollback
- requestInfo.setSuppressRollback(true);
-
- // setting requestInfo to requestDetails
- requestDetails.setRequestInfo(requestInfo);
-
- RequestParameters requestParameters = new RequestParameters();
-
- // subscriptionServiceType
- requestParameters.setSubscriptionServiceType("MOG");
-
- // Userparams
- //List<E2EUserParam> userParams;
- // userParams =
- // e2eSir.getService().getParameters().getRequestParameters().getUserParams();
- List<Map<String, Object>> userParamList = new ArrayList<>();
- Map<String, Object> userParamMap = new HashMap<>();
- // complete json request updated in the camunda
- userParamMap.put("UUIRequest", requestJSON);
- userParamMap.put("ServiceInstanceName", e2eSir.getService().getName());
-
- // Map<String, String> userParamMap3 = null;
- // for (E2EUserParam userp : userParams) {
- // userParamMap.put(userp.getName(), userp.getValue());
- //
- // }
- userParamList.add(userParamMap);
- requestParameters.setUserParams(userParamList);
-
- // setting requestParameters to requestDetails
- requestDetails.setRequestParameters(requestParameters);
-
- sir.setRequestDetails(requestDetails);
-
- return sir;
- }
-
-
- private void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Action action, String version,
- String requestJSON, Boolean aLaCarte, String requestId) throws ValidateException {
- int reqVersion = Integer.parseInt(version.substring(1));
- try {
- msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte);
- } catch (Exception e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ValidateException validateException = new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
-
- msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action, ModelType.service.name(), requestJSON);
-
- throw validateException;
- }
- }
-
- private String convertToString(ServiceInstancesRequest sir) {
- String returnString = null;
- // converting to string
- ObjectMapper mapper = new ObjectMapper();
- try {
- returnString = mapper.writeValueAsString(sir);
- } catch (IOException e) {
- logger.debug("Exception while converting ServiceInstancesRequest object to string", e);
- }
-
- return returnString;
- }
+ private Response beplStatusUpdate(String serviceId, long startTime, RequestClient requestClient,
+ ResponseHandler respHandler, int bpelStatus, Action action, HashMap<String, String> instanceIdMap,
+ String version) {
+
+ String apiVersion = version.substring(1);
+
+ // BPMN accepted the request, the request is in progress
+ if (bpelStatus == HttpStatus.SC_ACCEPTED) {
+ String camundaJSONResponseBody = respHandler.getResponseBody();
+ logger.debug("Received from Camunda: " + camundaJSONResponseBody);
+ logger.debug(END_OF_THE_TRANSACTION + camundaJSONResponseBody);
+ return builder.buildResponse(HttpStatus.SC_ACCEPTED, null, camundaJSONResponseBody, apiVersion);
+ } else {
+ List<String> variables = new ArrayList<>();
+ variables.add(bpelStatus + "");
+ String camundaJSONResponseBody = respHandler.getResponseBody();
+ if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) {
+ Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException,
+ "Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version);
+ logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(),
+ ErrorCode.BusinessProcesssError.getValue(),
+ "Response from BPEL engine is failed with HTTP Status=" + bpelStatus);
+ logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
+ return resp;
+ } else {
+ Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException,
+ "Request Failed due to BPEL error with HTTP Status= %1",
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version);
+ logger.error("", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(),
+ ErrorCode.BusinessProcesssError.getValue(), "Response from BPEL engine is empty");
+ logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
+ return resp;
+ }
+ }
+ }
+
+ /**
+ * Getting recipes from catalogDb
+ *
+ * @param serviceModelUUID the service model version uuid
+ * @param action the action for the service
+ * @return the service recipe result
+ */
+ private RecipeLookupResult getServiceInstanceOrchestrationURI(String serviceModelUUID, Action action) {
+
+ RecipeLookupResult recipeLookupResult = getServiceURI(serviceModelUUID, action);
+
+ if (recipeLookupResult != null) {
+ logger.debug("Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + ", recipe Timeout is: "
+ + Integer.toString(recipeLookupResult.getRecipeTimeout()));
+ } else {
+ logger.debug("No matching recipe record found");
+ }
+ return recipeLookupResult;
+ }
+
+ /**
+ * Getting recipes from catalogDb If Service recipe is not set, use default recipe, if set , use special recipe.
+ *
+ * @param serviceModelUUID the service version uuid
+ * @param action the action of the service.
+ * @return the service recipe result.
+ */
+ private RecipeLookupResult getServiceURI(String serviceModelUUID, Action action) {
+
+ String defaultServiceModelName = "UUI_DEFAULT";
+
+ Service defaultServiceRecord =
+ catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
+ // set recipe as default generic recipe
+ ServiceRecipe recipe =
+ catalogDbClient.getFirstByServiceModelUUIDAndAction(defaultServiceRecord.getModelUUID(), action.name());
+ // check the service special recipe
+ if (null != serviceModelUUID && !serviceModelUUID.isEmpty()) {
+ ServiceRecipe serviceSpecialRecipe =
+ catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceModelUUID, action.name());
+ if (null != serviceSpecialRecipe) {
+ // set service special recipe.
+ recipe = serviceSpecialRecipe;
+ }
+ }
+
+ if (recipe == null) {
+ return null;
+ }
+ return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout(), recipe.getParamXsd());
+
+ }
+
+ /**
+ * Converting E2EServiceInstanceRequest to ServiceInstanceRequest and passing it to camunda engine.
+ *
+ * @param e2eSir
+ * @return
+ */
+ private ServiceInstancesRequest mapReqJsonToSvcInstReq(E2EServiceInstanceRequest e2eSir, String requestJSON) {
+
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+
+ String returnString = null;
+ RequestDetails requestDetails = new RequestDetails();
+ ModelInfo modelInfo = new ModelInfo();
+
+ // ModelInvariantId
+ modelInfo.setModelInvariantId(e2eSir.getService().getServiceInvariantUuid());
+
+ // modelNameVersionId
+ modelInfo.setModelNameVersionId(e2eSir.getService().getServiceUuid());
+
+ // String modelInfoValue =
+ // e2eSir.getService().getParameters().getNodeTemplateName();
+ // String[] arrayOfInfo = modelInfoValue.split(":");
+ // String modelName = arrayOfInfo[0];
+ // String modelVersion = arrayOfInfo[1];
+
+ // TODO: To ensure, if we dont get the values from the UUI
+ String modelName = "voLTE";
+ String modelVersion = "1.0";
+ // modelName
+ modelInfo.setModelName(modelName);
+
+ // modelVersion
+ modelInfo.setModelVersion(modelVersion);
+
+ // modelType
+ modelInfo.setModelType(ModelType.service);
+
+ // setting modelInfo to requestDetails
+ requestDetails.setModelInfo(modelInfo);
+
+ SubscriberInfo subscriberInfo = new SubscriberInfo();
+
+ // globalsubscriberId
+ subscriberInfo.setGlobalSubscriberId(e2eSir.getService().getGlobalSubscriberId());
+
+ // setting subscriberInfo to requestDetails
+ requestDetails.setSubscriberInfo(subscriberInfo);
+
+ RequestInfo requestInfo = new RequestInfo();
+
+ // instanceName
+ requestInfo.setInstanceName(e2eSir.getService().getName());
+
+ // source
+ requestInfo.setSource("UUI");
+
+ // suppressRollback
+ requestInfo.setSuppressRollback(true);
+
+ // setting requestInfo to requestDetails
+ requestDetails.setRequestInfo(requestInfo);
+
+ RequestParameters requestParameters = new RequestParameters();
+
+ // subscriptionServiceType
+ requestParameters.setSubscriptionServiceType("MOG");
+
+ // Userparams
+ // List<E2EUserParam> userParams;
+ // userParams =
+ // e2eSir.getService().getParameters().getRequestParameters().getUserParams();
+ List<Map<String, Object>> userParamList = new ArrayList<>();
+ Map<String, Object> userParamMap = new HashMap<>();
+ // complete json request updated in the camunda
+ userParamMap.put("UUIRequest", requestJSON);
+ userParamMap.put("ServiceInstanceName", e2eSir.getService().getName());
+
+ // Map<String, String> userParamMap3 = null;
+ // for (E2EUserParam userp : userParams) {
+ // userParamMap.put(userp.getName(), userp.getValue());
+ //
+ // }
+ userParamList.add(userParamMap);
+ requestParameters.setUserParams(userParamList);
+
+ // setting requestParameters to requestDetails
+ requestDetails.setRequestParameters(requestParameters);
+
+ sir.setRequestDetails(requestDetails);
+
+ return sir;
+ }
+
+
+ private void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Action action,
+ String version, String requestJSON, Boolean aLaCarte, String requestId) throws ValidateException {
+ int reqVersion = Integer.parseInt(version.substring(1));
+ try {
+ msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte);
+ } catch (Exception e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ValidateException validateException =
+ new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
+
+ msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action,
+ ModelType.service.name(), requestJSON);
+
+ throw validateException;
+ }
+ }
+
+ private String convertToString(ServiceInstancesRequest sir) {
+ String returnString = null;
+ // converting to string
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ returnString = mapper.writeValueAsString(sir);
+ } catch (IOException e) {
+ logger.debug("Exception while converting ServiceInstancesRequest object to string", e);
+ }
+
+ return returnString;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java
index ad20c5c527..4d283f26b1 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java
@@ -25,12 +25,10 @@ package org.onap.so.apihandlerinfra;
import java.net.URI;
import java.util.Collections;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
-
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import javax.ws.rs.DefaultValue;
@@ -42,7 +40,6 @@ import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
-
import org.apache.http.HttpStatus;
import org.onap.so.logger.MessageEnum;
import org.springframework.beans.factory.annotation.Autowired;
@@ -58,166 +55,163 @@ import io.swagger.annotations.ApiOperation;
@Component
@Path("/globalhealthcheck")
-@Api(value="/globalhealthcheck",description="APIH Infra Global Health Check")
+@Api(value = "/globalhealthcheck", description = "APIH Infra Global Health Check")
public class GlobalHealthcheckHandler {
- private static Logger logger = LoggerFactory.getLogger(GlobalHealthcheckHandler.class);
- private static final String CONTEXTPATH_PROPERTY = "management.context-path";
- private static final String PROPERTY_DOMAIN = "mso.health.endpoints";
- private static final String CATALOGDB_PROPERTY = PROPERTY_DOMAIN + ".catalogdb";
- private static final String REQUESTDB_PROPERTY = PROPERTY_DOMAIN + ".requestdb";
- private static final String SDNC_PROPERTY = PROPERTY_DOMAIN + ".sdnc";
- private static final String OPENSTACK_PROPERTY = PROPERTY_DOMAIN + ".openstack";
- private static final String BPMN_PROPERTY = PROPERTY_DOMAIN + ".bpmn";
- private static final String ASDC_PROPERTY = PROPERTY_DOMAIN + ".asdc";
- private static final String REQUESTDBATTSVC_PROPERTY = PROPERTY_DOMAIN + ".requestdbattsvc";
- private static final String DEFAULT_PROPERTY_VALUE = "";
-
+ private static Logger logger = LoggerFactory.getLogger(GlobalHealthcheckHandler.class);
+ private static final String CONTEXTPATH_PROPERTY = "management.context-path";
+ private static final String PROPERTY_DOMAIN = "mso.health.endpoints";
+ private static final String CATALOGDB_PROPERTY = PROPERTY_DOMAIN + ".catalogdb";
+ private static final String REQUESTDB_PROPERTY = PROPERTY_DOMAIN + ".requestdb";
+ private static final String SDNC_PROPERTY = PROPERTY_DOMAIN + ".sdnc";
+ private static final String OPENSTACK_PROPERTY = PROPERTY_DOMAIN + ".openstack";
+ private static final String BPMN_PROPERTY = PROPERTY_DOMAIN + ".bpmn";
+ private static final String ASDC_PROPERTY = PROPERTY_DOMAIN + ".asdc";
+ private static final String REQUESTDBATTSVC_PROPERTY = PROPERTY_DOMAIN + ".requestdbattsvc";
+ private static final String DEFAULT_PROPERTY_VALUE = "";
+
// e.g. /manage
private String actuatorContextPath;
- private String endpointCatalogdb;
- private String endpointRequestdb;
- private String endpointSdnc;
- private String endpointOpenstack;
- private String endpointBpmn;
- private String endpointAsdc;
- private String endpointRequestdbAttsvc;
-
- @Autowired
- private Environment env;
-
- @Autowired
- private RestTemplate restTemplate;
- private final String health = "/health";
-
-
- @PostConstruct
- protected void init() {
- actuatorContextPath = env.getProperty(CONTEXTPATH_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
- endpointCatalogdb = env.getProperty(CATALOGDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
- endpointRequestdb = env.getProperty(REQUESTDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
- endpointSdnc = env.getProperty(SDNC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
- endpointOpenstack = env.getProperty(OPENSTACK_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
- endpointBpmn = env.getProperty(BPMN_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
- endpointAsdc = env.getProperty(ASDC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
- endpointRequestdbAttsvc = env.getProperty(REQUESTDBATTSVC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
- }
-
+ private String endpointCatalogdb;
+ private String endpointRequestdb;
+ private String endpointSdnc;
+ private String endpointOpenstack;
+ private String endpointBpmn;
+ private String endpointAsdc;
+ private String endpointRequestdbAttsvc;
+
+ @Autowired
+ private Environment env;
+
+ @Autowired
+ private RestTemplate restTemplate;
+ private final String health = "/health";
+
+
+ @PostConstruct
+ protected void init() {
+ actuatorContextPath = env.getProperty(CONTEXTPATH_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
+ endpointCatalogdb = env.getProperty(CATALOGDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
+ endpointRequestdb = env.getProperty(REQUESTDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
+ endpointSdnc = env.getProperty(SDNC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
+ endpointOpenstack = env.getProperty(OPENSTACK_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
+ endpointBpmn = env.getProperty(BPMN_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
+ endpointAsdc = env.getProperty(ASDC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
+ endpointRequestdbAttsvc = env.getProperty(REQUESTDBATTSVC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
+ }
+
@GET
@Produces("application/json")
- @ApiOperation(value="Performing global health check",response=Response.class)
+ @ApiOperation(value = "Performing global health check", response = Response.class)
@Transactional
- public Response globalHealthcheck (@DefaultValue("true") @QueryParam("enableBpmn") boolean enableBpmn,
- @Context ContainerRequestContext requestContext) {
- Response HEALTH_CHECK_RESPONSE = null;
+ public Response globalHealthcheck(@DefaultValue("true") @QueryParam("enableBpmn") boolean enableBpmn,
+ @Context ContainerRequestContext requestContext) {
+ Response HEALTH_CHECK_RESPONSE = null;
// Build internal response object
HealthcheckResponse rsp = new HealthcheckResponse();
-
- try{
+
+ try {
// Generated RequestId
String requestId = requestContext.getProperty("requestId").toString();
logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
-
+
// set APIH status, this is the main entry point
rsp.setApih(HealthcheckStatus.UP.toString());
// set BPMN
rsp.setBpmn(querySubsystemHealth(MsoSubsystems.BPMN));
// set SDNCAdapter
- rsp.setSdncAdapter(querySubsystemHealth(MsoSubsystems.SDNC));
+ rsp.setSdncAdapter(querySubsystemHealth(MsoSubsystems.SDNC));
// set ASDCController
- rsp.setAsdcController(querySubsystemHealth(MsoSubsystems.ASDC));
+ rsp.setAsdcController(querySubsystemHealth(MsoSubsystems.ASDC));
// set CatalogDbAdapter
- rsp.setCatalogdbAdapter(querySubsystemHealth(MsoSubsystems.CATALOGDB));
+ rsp.setCatalogdbAdapter(querySubsystemHealth(MsoSubsystems.CATALOGDB));
// set RequestDbAdapter
- rsp.setRequestdbAdapter(querySubsystemHealth(MsoSubsystems.REQUESTDB));
+ rsp.setRequestdbAdapter(querySubsystemHealth(MsoSubsystems.REQUESTDB));
// set OpenStackAdapter
- rsp.setOpenstackAdapter(querySubsystemHealth(MsoSubsystems.OPENSTACK));
+ rsp.setOpenstackAdapter(querySubsystemHealth(MsoSubsystems.OPENSTACK));
// set RequestDbAdapterAttSvc
rsp.setRequestdbAdapterAttsvc(querySubsystemHealth(MsoSubsystems.REQUESTDBATT));
// set Message
rsp.setMessage(String.format("HttpStatus: %s", HttpStatus.SC_OK));
logger.info(rsp.toString());
- HEALTH_CHECK_RESPONSE = Response.status (HttpStatus.SC_OK)
- .entity (rsp)
- .build ();
-
- }catch (Exception ex){
- logger.error("Exception occurred", ex);
- rsp.setMessage(ex.getMessage());
- HEALTH_CHECK_RESPONSE = Response.status (HttpStatus.SC_INTERNAL_SERVER_ERROR)
- .entity (rsp)
- .build ();
- }
-
+ HEALTH_CHECK_RESPONSE = Response.status(HttpStatus.SC_OK).entity(rsp).build();
+
+ } catch (Exception ex) {
+ logger.error("Exception occurred", ex);
+ rsp.setMessage(ex.getMessage());
+ HEALTH_CHECK_RESPONSE = Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(rsp).build();
+ }
+
return HEALTH_CHECK_RESPONSE;
}
-
- protected HttpEntity<String> buildHttpEntityForRequest(){
+
+ protected HttpEntity<String> buildHttpEntityForRequest() {
HttpHeaders headers = new HttpHeaders();
- headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
+ headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("Content-Type", "application/json");
- HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
+ HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
return entity;
}
-
- protected String querySubsystemHealth(MsoSubsystems subsystem){
- try{
+
+ protected String querySubsystemHealth(MsoSubsystems subsystem) {
+ try {
// get port number for the subsystem
- String ept = getEndpointUrlForSubsystemEnum(subsystem);
-
- // build final endpoint url
- UriBuilder builder = UriBuilder.fromPath(ept).path(actuatorContextPath).path(health);
- URI uri = builder.build();
- logger.info("Calculated URL: {}", uri.toString());
-
- ResponseEntity<SubsystemHealthcheckResponse> result =
- restTemplate.exchange(uri, HttpMethod.GET, buildHttpEntityForRequest(), SubsystemHealthcheckResponse.class);
-
- return processResponseFromSubsystem(result,subsystem);
-
- }catch(Exception ex){
- logger.error("Exception occured in GlobalHealthcheckHandler.querySubsystemHealth() ", ex);
- return HealthcheckStatus.DOWN.toString();
- }
+ String ept = getEndpointUrlForSubsystemEnum(subsystem);
+
+ // build final endpoint url
+ UriBuilder builder = UriBuilder.fromPath(ept).path(actuatorContextPath).path(health);
+ URI uri = builder.build();
+ logger.info("Calculated URL: {}", uri.toString());
+
+ ResponseEntity<SubsystemHealthcheckResponse> result = restTemplate.exchange(uri, HttpMethod.GET,
+ buildHttpEntityForRequest(), SubsystemHealthcheckResponse.class);
+
+ return processResponseFromSubsystem(result, subsystem);
+
+ } catch (Exception ex) {
+ logger.error("Exception occured in GlobalHealthcheckHandler.querySubsystemHealth() ", ex);
+ return HealthcheckStatus.DOWN.toString();
+ }
}
- protected String processResponseFromSubsystem(ResponseEntity<SubsystemHealthcheckResponse> result, MsoSubsystems subsystem){
- if(result == null || result.getStatusCodeValue() != HttpStatus.SC_OK){
- logger.error(String.format("Globalhealthcheck: checking subsystem: %s failed ! result object is: %s",
- subsystem,
- result == null? "NULL": result));
- return HealthcheckStatus.DOWN.toString();
+
+ protected String processResponseFromSubsystem(ResponseEntity<SubsystemHealthcheckResponse> result,
+ MsoSubsystems subsystem) {
+ if (result == null || result.getStatusCodeValue() != HttpStatus.SC_OK) {
+ logger.error(String.format("Globalhealthcheck: checking subsystem: %s failed ! result object is: %s",
+ subsystem, result == null ? "NULL" : result));
+ return HealthcheckStatus.DOWN.toString();
}
-
+
SubsystemHealthcheckResponse body = result.getBody();
- String status = body.getStatus();
- if("UP".equalsIgnoreCase(status)){
- return HealthcheckStatus.UP.toString();
- }else{
- logger.error("{}, query health endpoint did not return UP status!", subsystem);
- return HealthcheckStatus.DOWN.toString();
- }
- }
-
-
- protected String getEndpointUrlForSubsystemEnum(MsoSubsystems subsystem){
- switch (subsystem){
- case SDNC:
- return this.endpointSdnc;
- case ASDC:
- return this.endpointAsdc;
- case BPMN:
- return this.endpointBpmn;
- case CATALOGDB:
- return this.endpointCatalogdb;
- case OPENSTACK:
- return this.endpointOpenstack;
- case REQUESTDB:
- return this.endpointRequestdb;
- case REQUESTDBATT:
- return this.endpointRequestdbAttsvc;
- default:
- return "";
- }
+ String status = body.getStatus();
+ if ("UP".equalsIgnoreCase(status)) {
+ return HealthcheckStatus.UP.toString();
+ } else {
+ logger.error("{}, query health endpoint did not return UP status!", subsystem);
+ return HealthcheckStatus.DOWN.toString();
+ }
+ }
+
+
+ protected String getEndpointUrlForSubsystemEnum(MsoSubsystems subsystem) {
+ switch (subsystem) {
+ case SDNC:
+ return this.endpointSdnc;
+ case ASDC:
+ return this.endpointAsdc;
+ case BPMN:
+ return this.endpointBpmn;
+ case CATALOGDB:
+ return this.endpointCatalogdb;
+ case OPENSTACK:
+ return this.endpointOpenstack;
+ case REQUESTDB:
+ return this.endpointRequestdb;
+ case REQUESTDBATT:
+ return this.endpointRequestdbAttsvc;
+ default:
+ return "";
+ }
}
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java
index 8f0bbc4e1f..fad3dd4055 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java
@@ -22,100 +22,95 @@ package org.onap.so.apihandlerinfra;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class HealthcheckResponse {
- private String apih;
- private String bpmn;
- private String sdncAdapter;
- private String asdcController;
- private String catalogdbAdapter;
- private String requestdbAdapter;
- private String openstackAdapter;
- private String requestdbAdapterAttsvc;
- private String message = "";
-
- public String getApih() {
- return apih;
- }
-
- public void setApih(String apih) {
- this.apih = apih;
- }
-
- public String getBpmn() {
- return bpmn;
- }
-
- public void setBpmn(String bpmn) {
- this.bpmn = bpmn;
- }
-
- public String getSdncAdapter() {
- return sdncAdapter;
- }
-
- public void setSdncAdapter(String sdncAdapter) {
- this.sdncAdapter = sdncAdapter;
- }
-
- public String getAsdcController() {
- return asdcController;
- }
-
- public void setAsdcController(String asdcController) {
- this.asdcController = asdcController;
- }
-
- public String getCatalogdbAdapter() {
- return catalogdbAdapter;
- }
-
- public void setCatalogdbAdapter(String catalogdbAdapter) {
- this.catalogdbAdapter = catalogdbAdapter;
- }
-
- public String getRequestdbAdapter() {
- return requestdbAdapter;
- }
-
- public void setRequestdbAdapter(String requestdbAdapter) {
- this.requestdbAdapter = requestdbAdapter;
- }
-
- public String getOpenstackAdapter() {
- return openstackAdapter;
- }
-
- public void setOpenstackAdapter(String openstackAdapter) {
- this.openstackAdapter = openstackAdapter;
- }
-
- public String getRequestdbAdapterAttsvc() {
- return requestdbAdapterAttsvc;
- }
-
- public void setRequestdbAdapterAttsvc(String requestdbAdapterAttsvc) {
- this.requestdbAdapterAttsvc = requestdbAdapterAttsvc;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).
- append("apih", this.apih).
- append("pbmn", this.bpmn).
- append("sdncAdapter", this.sdncAdapter).
- append("asdcController", this.asdcController).
- append("catalogdbAdapter", this.catalogdbAdapter).
- append("requestdbAdapter", this.requestdbAdapter).
- append("openstackAdapter", this.openstackAdapter).
- append("requestdbAdapterAttsvc", this.requestdbAdapterAttsvc).
- append("message", this.message).
- toString();
- }
+ private String apih;
+ private String bpmn;
+ private String sdncAdapter;
+ private String asdcController;
+ private String catalogdbAdapter;
+ private String requestdbAdapter;
+ private String openstackAdapter;
+ private String requestdbAdapterAttsvc;
+ private String message = "";
+
+ public String getApih() {
+ return apih;
+ }
+
+ public void setApih(String apih) {
+ this.apih = apih;
+ }
+
+ public String getBpmn() {
+ return bpmn;
+ }
+
+ public void setBpmn(String bpmn) {
+ this.bpmn = bpmn;
+ }
+
+ public String getSdncAdapter() {
+ return sdncAdapter;
+ }
+
+ public void setSdncAdapter(String sdncAdapter) {
+ this.sdncAdapter = sdncAdapter;
+ }
+
+ public String getAsdcController() {
+ return asdcController;
+ }
+
+ public void setAsdcController(String asdcController) {
+ this.asdcController = asdcController;
+ }
+
+ public String getCatalogdbAdapter() {
+ return catalogdbAdapter;
+ }
+
+ public void setCatalogdbAdapter(String catalogdbAdapter) {
+ this.catalogdbAdapter = catalogdbAdapter;
+ }
+
+ public String getRequestdbAdapter() {
+ return requestdbAdapter;
+ }
+
+ public void setRequestdbAdapter(String requestdbAdapter) {
+ this.requestdbAdapter = requestdbAdapter;
+ }
+
+ public String getOpenstackAdapter() {
+ return openstackAdapter;
+ }
+
+ public void setOpenstackAdapter(String openstackAdapter) {
+ this.openstackAdapter = openstackAdapter;
+ }
+
+ public String getRequestdbAdapterAttsvc() {
+ return requestdbAdapterAttsvc;
+ }
+
+ public void setRequestdbAdapterAttsvc(String requestdbAdapterAttsvc) {
+ this.requestdbAdapterAttsvc = requestdbAdapterAttsvc;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("apih", this.apih).append("pbmn", this.bpmn)
+ .append("sdncAdapter", this.sdncAdapter).append("asdcController", this.asdcController)
+ .append("catalogdbAdapter", this.catalogdbAdapter).append("requestdbAdapter", this.requestdbAdapter)
+ .append("openstackAdapter", this.openstackAdapter)
+ .append("requestdbAdapterAttsvc", this.requestdbAdapterAttsvc).append("message", this.message)
+ .toString();
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java
index 89c4e0efda..077a3c2d60 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java
@@ -20,15 +20,16 @@
package org.onap.so.apihandlerinfra;
public enum HealthcheckStatus {
- UP("UP"), DOWN("DOWN");
-
- private String status;
- private HealthcheckStatus(String status) {
- this.status = status;
- }
-
- @Override
- public String toString(){
- return status;
- }
+ UP("UP"), DOWN("DOWN");
+
+ private String status;
+
+ private HealthcheckStatus(String status) {
+ this.status = status;
+ }
+
+ @Override
+ public String toString() {
+ return status;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java
index 51962f2b9e..c491444f39 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java
@@ -48,7 +48,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
@@ -64,182 +63,201 @@ import java.util.HashMap;
@Component
@Path("/onap/so/infra/instanceManagement")
-@Api(value="/onap/so/infra/instanceManagement",description="Infrastructure API Requests for Instance Management")
+@Api(value = "/onap/so/infra/instanceManagement", description = "Infrastructure API Requests for Instance Management")
public class InstanceManagement {
- private static Logger logger = LoggerFactory.getLogger(InstanceManagement.class);
- private static String uriPrefix = "/instanceManagement/";
- private static final String SAVE_TO_DB = "save instance to db";
-
- @Autowired
- private RequestsDbClient infraActiveRequestsClient;
-
- @Autowired
- private CatalogDbClient catalogDbClient;
-
- @Autowired
- private MsoRequest msoRequest;
-
- @Autowired
- private RequestHandlerUtils requestHandlerUtils;
-
- @POST
- @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/workflows/{workflowUuid}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Execute custom workflow",response=Response.class)
- @Transactional
- public Response executeCustomWorkflow(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- instanceIdMap.put("workflowUuid", workflowUuid);
- return processCustomWorkflowRequest(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId, requestContext);
- }
-
- private Response processCustomWorkflowRequest(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, ContainerRequestContext requestContext) throws ApiException {
- String serviceInstanceId = null;
- if (instanceIdMap != null) {
- serviceInstanceId = instanceIdMap.get("serviceInstanceId");
- }
- Boolean aLaCarte = true;
- long startTime = System.currentTimeMillis ();
- ServiceInstancesRequest sir = null;
- String apiVersion = version.substring(1);
-
- String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix);
-
- sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, requestId, requestUri);
- String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri);
- InfraActiveRequests currentActiveReq = msoRequest.createRequestObject (sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
-
- try {
- requestHandlerUtils.validateHeaders(requestContext);
- } catch (ValidationException e) {
- logger.error("Exception occurred", e);
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
+ private static Logger logger = LoggerFactory.getLogger(InstanceManagement.class);
+ private static String uriPrefix = "/instanceManagement/";
+ private static final String SAVE_TO_DB = "save instance to db";
+
+ @Autowired
+ private RequestsDbClient infraActiveRequestsClient;
+
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+
+ @Autowired
+ private MsoRequest msoRequest;
+
+ @Autowired
+ private RequestHandlerUtils requestHandlerUtils;
+
+ @POST
+ @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/workflows/{workflowUuid}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Execute custom workflow", response = Response.class)
+ @Transactional
+ public Response executeCustomWorkflow(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ instanceIdMap.put("workflowUuid", workflowUuid);
+ return processCustomWorkflowRequest(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId,
+ requestContext);
+ }
+
+ private Response processCustomWorkflowRequest(String requestJSON, Actions action,
+ HashMap<String, String> instanceIdMap, String version, String requestId,
+ ContainerRequestContext requestContext) throws ApiException {
+ String serviceInstanceId = null;
+ if (instanceIdMap != null) {
+ serviceInstanceId = instanceIdMap.get("serviceInstanceId");
+ }
+ Boolean aLaCarte = true;
+ long startTime = System.currentTimeMillis();
+ ServiceInstancesRequest sir = null;
+ String apiVersion = version.substring(1);
+
+ String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix);
+
+ sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest,
+ requestId, requestUri);
+ String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri);
+ InfraActiveRequests currentActiveReq =
+ msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
+
+ try {
+ requestHandlerUtils.validateHeaders(requestContext);
+ } catch (ValidationException e) {
+ logger.error("Exception occurred", e);
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ValidateException validateException =
+ new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
throw validateException;
- }
-
- requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, currentActiveReq);
- requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap);
-
- int requestVersion = Integer.parseInt(version.substring(1));
- String vnfType = msoRequest.getVnfType(sir,requestScope,action,requestVersion);
-
- if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null){
- currentActiveReq.setVnfType(vnfType);
- }
-
- InfraActiveRequests dup = null;
- boolean inProgress = false;
-
- dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope, currentActiveReq);
-
- if(dup != null){
- inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
- }
-
- if (dup != null && inProgress) {
- requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, null, requestScope, dup);
- }
- ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
-
- RequestReferences referencesResponse = new RequestReferences();
-
- referencesResponse.setRequestId(requestId);
-
- serviceResponse.setRequestReferences(referencesResponse);
- Boolean isBaseVfModule = false;
-
- String workflowUuid = null;
- if (instanceIdMap !=null) {
- workflowUuid = instanceIdMap.get("workflowUuid");
- }
+ }
+
+ requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId,
+ currentActiveReq);
+ requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap);
+
+ int requestVersion = Integer.parseInt(version.substring(1));
+ String vnfType = msoRequest.getVnfType(sir, requestScope, action, requestVersion);
+
+ if (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null) {
+ currentActiveReq.setVnfType(vnfType);
+ }
+
+ InfraActiveRequests dup = null;
+ boolean inProgress = false;
+
+ dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope,
+ currentActiveReq);
+
+ if (dup != null) {
+ inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
+ }
+
+ if (dup != null && inProgress) {
+ requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime,
+ msoRequest, null, requestScope, dup);
+ }
+ ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
+
+ RequestReferences referencesResponse = new RequestReferences();
+
+ referencesResponse.setRequestId(requestId);
+
+ serviceResponse.setRequestReferences(referencesResponse);
+ Boolean isBaseVfModule = false;
+
+ String workflowUuid = null;
+ if (instanceIdMap != null) {
+ workflowUuid = instanceIdMap.get("workflowUuid");
+ }
RecipeLookupResult recipeLookupResult = getInstanceManagementWorkflowRecipe(currentActiveReq, workflowUuid);
-
- String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, true);
-
- serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir);
- String vnfId = "";
-
- if(sir.getVnfInstanceId () != null){
- vnfId = sir.getVnfInstanceId ();
- }
-
- try{
+
+ String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, true);
+
+ serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir);
+ String vnfId = "";
+
+ if (sir.getVnfInstanceId() != null) {
+ vnfId = sir.getVnfInstanceId();
+ }
+
+ try {
infraActiveRequestsClient.save(currentActiveReq);
- }catch(Exception e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
- .errorInfo(errorLoggerInfo).build();
- }
-
- RequestClientParameter requestClientParameter = null;
- try {
- requestClientParameter = new RequestClientParameter.Builder()
- .setRequestId(requestId)
- .setBaseVfModule(isBaseVfModule)
- .setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
- .setRequestAction(action.toString())
- .setServiceInstanceId(serviceInstanceId)
- .setVnfId(vnfId)
- .setServiceType(serviceInstanceType)
- .setVnfType(vnfType)
- .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action))
- .setApiVersion(apiVersion)
- .setALaCarte(aLaCarte)
- .setRequestUri(requestUri)
- .build();
- } catch (IOException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER)
- .errorInfo(errorLoggerInfo).build();
- }
- return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope);
- }
-
- private RecipeLookupResult getInstanceManagementWorkflowRecipe(InfraActiveRequests currentActiveReq, String workflowUuid) throws ApiException {
- RecipeLookupResult recipeLookupResult = null;
-
+ } catch (Exception e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
+ }
+
+ RequestClientParameter requestClientParameter = null;
try {
- recipeLookupResult = getCustomWorkflowUri(workflowUuid);
- } catch (IOException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
- requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
- throw validateException;
- }
-
+ requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId)
+ .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
+ .setRequestAction(action.toString()).setServiceInstanceId(serviceInstanceId).setVnfId(vnfId)
+ .setServiceType(serviceInstanceType).setVnfType(vnfType)
+ .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action))
+ .setApiVersion(apiVersion).setALaCarte(aLaCarte).setRequestUri(requestUri).build();
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(),
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
+ .build();
+ }
+ return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter,
+ recipeLookupResult.getOrchestrationURI(), requestScope);
+ }
+
+ private RecipeLookupResult getInstanceManagementWorkflowRecipe(InfraActiveRequests currentActiveReq,
+ String workflowUuid) throws ApiException {
+ RecipeLookupResult recipeLookupResult = null;
+
+ try {
+ recipeLookupResult = getCustomWorkflowUri(workflowUuid);
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ValidateException validateException =
+ new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
+ requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
+ throw validateException;
+ }
+
if (recipeLookupResult == null) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- RecipeNotFoundException recipeNotFoundExceptionException = new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR)
- .errorInfo(errorLoggerInfo).build();
- requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, recipeNotFoundExceptionException.getMessage());
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ RecipeNotFoundException recipeNotFoundExceptionException =
+ new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.",
+ HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo)
+ .build();
+ requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED,
+ recipeNotFoundExceptionException.getMessage());
throw recipeNotFoundExceptionException;
- }
-
+ }
+
return recipeLookupResult;
- }
-
+ }
+
private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) throws IOException {
-
- String recipeUri = null;
- Workflow workflow = catalogDbClient.findWorkflowByArtifactUUID(workflowUuid);
- if (workflow == null) {
- return null;
- }
- else {
- String workflowName = workflow.getArtifactName();
- recipeUri = "/mso/async/services/" + workflowName;
- }
- return new RecipeLookupResult(recipeUri, 180);
- }
+
+ String recipeUri = null;
+ Workflow workflow = catalogDbClient.findWorkflowByArtifactUUID(workflowUuid);
+ if (workflow == null) {
+ return null;
+ } else {
+ String workflowName = workflow.getArtifactName();
+ recipeUri = "/mso/async/services/" + workflowName;
+ }
+ return new RecipeLookupResult(recipeUri, 180);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java
index 866a4e7ca1..67d6a0d1fc 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java
@@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra;
import javax.annotation.PostConstruct;
import javax.ws.rs.ApplicationPath;
-
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
import org.onap.so.apihandler.filters.RequestUriFilter;
@@ -34,7 +33,6 @@ import org.onap.so.apihandlerinfra.tenantisolation.ModelDistributionRequest;
import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging;
import org.onap.so.web.exceptions.RuntimeExceptionMapper;
import org.springframework.context.annotation.Configuration;
-
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
@@ -45,38 +43,38 @@ public class JerseyConfiguration extends ResourceConfig {
- @PostConstruct
- public void setUp() {
- register(GlobalHealthcheckHandler.class);
- register(NodeHealthcheckHandler.class);
- register(ServiceInstances.class);
- register(TasksHandler.class);
- register(CloudOrchestration.class);
- register(CloudResourcesOrchestration.class);
- register(OrchestrationRequests.class);
- register(JaxRsFilterLogging.class);
- register(ManualTasks.class);
- register(TasksHandler.class);
- register(ApiListingResource.class);
- register(SwaggerSerializers.class);
- register(ApiExceptionMapper.class);
- register(RuntimeExceptionMapper.class);
- register(RequestUriFilter.class);
- register(RequestIdFilter.class);
- register(E2EServiceInstances.class);
- register(WorkflowSpecificationsHandler.class);
- register(InstanceManagement.class);
- // this registration seems to be needed to get predictable
- // execution behavior for the above JSON Exception Mappers
- register(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider.class);
- register(ModelDistributionRequest.class);
- property(ServletProperties.FILTER_FORWARD_ON_404, true);
- BeanConfig beanConfig = new BeanConfig();
- beanConfig.setVersion("1.0.2");
- beanConfig.setSchemes(new String[] { "https" });
- beanConfig.setResourcePackage("org.onap.so.apihandlerinfra");
- beanConfig.setPrettyPrint(true);
- beanConfig.setScan(true);
- }
+ @PostConstruct
+ public void setUp() {
+ register(GlobalHealthcheckHandler.class);
+ register(NodeHealthcheckHandler.class);
+ register(ServiceInstances.class);
+ register(TasksHandler.class);
+ register(CloudOrchestration.class);
+ register(CloudResourcesOrchestration.class);
+ register(OrchestrationRequests.class);
+ register(JaxRsFilterLogging.class);
+ register(ManualTasks.class);
+ register(TasksHandler.class);
+ register(ApiListingResource.class);
+ register(SwaggerSerializers.class);
+ register(ApiExceptionMapper.class);
+ register(RuntimeExceptionMapper.class);
+ register(RequestUriFilter.class);
+ register(RequestIdFilter.class);
+ register(E2EServiceInstances.class);
+ register(WorkflowSpecificationsHandler.class);
+ register(InstanceManagement.class);
+ // this registration seems to be needed to get predictable
+ // execution behavior for the above JSON Exception Mappers
+ register(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider.class);
+ register(ModelDistributionRequest.class);
+ property(ServletProperties.FILTER_FORWARD_ON_404, true);
+ BeanConfig beanConfig = new BeanConfig();
+ beanConfig.setVersion("1.0.2");
+ beanConfig.setSchemes(new String[] {"https"});
+ beanConfig.setResourcePackage("org.onap.so.apihandlerinfra");
+ beanConfig.setPrettyPrint(true);
+ beanConfig.setScan(true);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java
index ad589ddc9c..3c06804594 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java
@@ -24,7 +24,6 @@
package org.onap.so.apihandlerinfra;
import java.io.IOException;
-
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
@@ -35,7 +34,6 @@ import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.onap.so.apihandler.common.ErrorNumbers;
@@ -46,7 +44,6 @@ import org.onap.so.apihandler.common.ResponseHandler;
import org.onap.so.apihandlerinfra.exceptions.ApiException;
import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException;
import org.onap.so.apihandlerinfra.exceptions.ValidateException;
-
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
import org.onap.so.apihandlerinfra.tasksbeans.TaskRequestReference;
import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest;
@@ -56,193 +53,212 @@ import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
-
import io.swagger.annotations.ApiOperation;
@Path("/tasks")
@Component
public class ManualTasks {
- private static Logger logger = LoggerFactory.getLogger(ManualTasks.class);
-
-
- @org.springframework.beans.factory.annotation.Value("${mso.camunda.rest.task.uri}")
- private String taskUri;
-
- @Autowired
- private RequestClientFactory reqClientFactory;
-
- @Autowired
- private MsoRequest msoRequest;
-
- @Autowired
- private ResponseBuilder builder;
-
- @POST
- @Path("/{version:[vV]1}/{taskId}/complete")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Complete specified task",response=Response.class)
- @Transactional
- public Response completeTask(String request, @PathParam("version") String version, @PathParam("taskId") String taskId,
- @Context ContainerRequestContext requestContext) throws ApiException {
-
- String requestId = requestContext.getProperty("requestId").toString();
- logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
- long startTime = System.currentTimeMillis ();
- logger.debug ("requestId is: {}", requestId);
- TasksRequest taskRequest = null;
- String apiVersion = version.substring(1);
-
- try{
- ObjectMapper mapper = new ObjectMapper();
- taskRequest= mapper.readValue(request, TasksRequest.class);
-
- if (taskRequest.getRequestDetails() == null) {
- throw new ValidationException("requestDetails");
- }
- if (taskRequest.getRequestDetails().getRequestInfo() == null) {
- throw new ValidationException("requestInfo");
- }
- if (empty(taskRequest.getRequestDetails().getRequestInfo().getSource())) {
- throw new ValidationException("source");
- }
- if (empty(taskRequest.getRequestDetails().getRequestInfo().getRequestorId())) {
- throw new ValidationException("requestorId");
- }
-
- }catch(IOException e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build();
-
-
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed: " + e.getMessage(),
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
-
- throw validateException;
- }
- catch(ValidationException e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-
-
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON Object failed. " + e.getMessage(),
- HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
- throw validateException;
-
- }
- //Create Request Record
- InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(taskRequest,Action.completeTask,requestId,Status.PENDING,request);
-
- // Transform the request to Camunda-style Complete request
- Variables variablesForComplete = new Variables();
- Value sourceValue = new Value();
- sourceValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getSource());
- Value responseValue = new Value();
- responseValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getResponseValue().name());
- Value requestorIdValue = new Value();
- requestorIdValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getRequestorId());
- variablesForComplete.setSource(sourceValue);
- variablesForComplete.setResponseValue(responseValue);
- variablesForComplete.setRequestorId(requestorIdValue);
-
- String camundaJsonReq = null;
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
- camundaJsonReq = mapper.writeValueAsString(variablesForComplete);
- } catch(JsonProcessingException e){
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.UnknownError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-
-
- ValidateException validateException = new ValidateException.Builder("Mapping of JSON object to Camunda request failed",
- HttpStatus.SC_INTERNAL_SERVER_ERROR,ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
- throw validateException;
- }
-
- RequestClient requestClient = null;
- HttpResponse response = null;
- long subStartTime = System.currentTimeMillis();
- String requestUrl = taskUri + "/" + taskId + "/complete";
- try {
- requestClient = reqClientFactory.getRequestClient (requestUrl);
- // Capture audit event
-
- response = requestClient.post(camundaJsonReq);
-
- } catch (Exception e) {
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-
-
-
- BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
- HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
-
- throw bpmnFailureException;
- }
-
- if (response == null) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-
-
- BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
- HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
+ private static Logger logger = LoggerFactory.getLogger(ManualTasks.class);
+
+
+ @org.springframework.beans.factory.annotation.Value("${mso.camunda.rest.task.uri}")
+ private String taskUri;
+
+ @Autowired
+ private RequestClientFactory reqClientFactory;
+
+ @Autowired
+ private MsoRequest msoRequest;
+
+ @Autowired
+ private ResponseBuilder builder;
+
+ @POST
+ @Path("/{version:[vV]1}/{taskId}/complete")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Complete specified task", response = Response.class)
+ @Transactional
+ public Response completeTask(String request, @PathParam("version") String version,
+ @PathParam("taskId") String taskId, @Context ContainerRequestContext requestContext) throws ApiException {
+
+ String requestId = requestContext.getProperty("requestId").toString();
+ logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
+ long startTime = System.currentTimeMillis();
+ logger.debug("requestId is: {}", requestId);
+ TasksRequest taskRequest = null;
+ String apiVersion = version.substring(1);
+
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ taskRequest = mapper.readValue(request, TasksRequest.class);
+
+ if (taskRequest.getRequestDetails() == null) {
+ throw new ValidationException("requestDetails");
+ }
+ if (taskRequest.getRequestDetails().getRequestInfo() == null) {
+ throw new ValidationException("requestInfo");
+ }
+ if (empty(taskRequest.getRequestDetails().getRequestInfo().getSource())) {
+ throw new ValidationException("source");
+ }
+ if (empty(taskRequest.getRequestDetails().getRequestInfo().getRequestorId())) {
+ throw new ValidationException("requestorId");
+ }
+
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON object failed: " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+
+ throw validateException;
+ } catch (ValidationException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON Object failed. " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
+ .build();
+ throw validateException;
+
+ }
+ // Create Request Record
+ InfraActiveRequests currentActiveReq =
+ msoRequest.createRequestObject(taskRequest, Action.completeTask, requestId, Status.PENDING, request);
+
+ // Transform the request to Camunda-style Complete request
+ Variables variablesForComplete = new Variables();
+ Value sourceValue = new Value();
+ sourceValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getSource());
+ Value responseValue = new Value();
+ responseValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getResponseValue().name());
+ Value requestorIdValue = new Value();
+ requestorIdValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getRequestorId());
+ variablesForComplete.setSource(sourceValue);
+ variablesForComplete.setResponseValue(responseValue);
+ variablesForComplete.setRequestorId(requestorIdValue);
+
+ String camundaJsonReq = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
+ camundaJsonReq = mapper.writeValueAsString(variablesForComplete);
+ } catch (JsonProcessingException e) {
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.UnknownError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of JSON object to Camunda request failed",
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR)
+ .errorInfo(errorLoggerInfo).build();
+ throw validateException;
+ }
+
+ RequestClient requestClient = null;
+ HttpResponse response = null;
+ long subStartTime = System.currentTimeMillis();
+ String requestUrl = taskUri + "/" + taskId + "/complete";
+ try {
+ requestClient = reqClientFactory.getRequestClient(requestUrl);
+ // Capture audit event
+
+ response = requestClient.post(camundaJsonReq);
+
+ } catch (Exception e) {
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+
+
+ BPMNFailureException bpmnFailureException =
+ new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
+ HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo)
+ .build();
throw bpmnFailureException;
+ }
- }
+ if (response == null) {
+ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
+ ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
- int bpelStatus = respHandler.getStatus ();
- // BPEL accepted the request, the request is in progress
- if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {
- logger.debug ("Received good response from Camunda");
- TaskRequestReference trr = new TaskRequestReference();
- trr.setTaskId(taskId);
- String completeResp = null;
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
- completeResp = mapper.writeValueAsString(trr);
- }
- catch (JsonProcessingException e) {
+ BPMNFailureException bpmnFailureException =
+ new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
+ HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo)
+ .build();
+
+ throw bpmnFailureException;
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).build();
+ }
+ ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
+ int bpelStatus = respHandler.getStatus();
- ValidateException validateException = new ValidateException.Builder("Request Failed due to bad response format" ,
- bpelStatus,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+ // BPEL accepted the request, the request is in progress
+ if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {
+ logger.debug("Received good response from Camunda");
+ TaskRequestReference trr = new TaskRequestReference();
+ trr.setTaskId(taskId);
+ String completeResp = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
+ completeResp = mapper.writeValueAsString(trr);
+ } catch (JsonProcessingException e) {
+
+ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR,
+ ErrorCode.BusinessProcesssError).build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder("Request Failed due to bad response format", bpelStatus,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
throw validateException;
- }
- logger.debug("Response to the caller: {}", completeResp);
- logger.debug ("End of the transaction, the final response is: {}", completeResp);
- return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, completeResp, apiVersion);
- } else {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).build();
+ }
+ logger.debug("Response to the caller: {}", completeResp);
+ logger.debug("End of the transaction, the final response is: {}", completeResp);
+ return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, completeResp, apiVersion);
+ } else {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError)
+ .build();
BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
- bpelStatus,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+ bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
throw bpmnFailureException;
-
- }
-
- }
-
- private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
- }
-
+
+ }
+
+ }
+
+ private static boolean empty(String s) {
+ return (s == null || s.trim().isEmpty());
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java
index dc8e6b6958..277675f310 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java
@@ -34,7 +34,6 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.StringTokenizer;
-
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.xml.XMLConstants;
@@ -43,7 +42,6 @@ import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
-
import org.onap.so.apihandler.common.ResponseBuilder;
import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest;
import org.onap.so.apihandlerinfra.validation.MembersValidation;
@@ -95,7 +93,6 @@ import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -104,351 +101,358 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class MsoRequest {
-
- @Autowired
- private RequestsDbClient requestsDbClient;
-
- @Autowired
- private ResponseBuilder builder;
-
+
+ @Autowired
+ private RequestsDbClient requestsDbClient;
+
+ @Autowired
+ private ResponseBuilder builder;
+
private static Logger logger = LoggerFactory.getLogger(MsoRequest.class);
-
- public Response buildServiceErrorResponse (int httpResponseCode, MsoException exceptionType,
- String errorText, String messageId, List<String> variables, String version) {
-
- if(errorText.length() > 1999){
- errorText = errorText.substring(0, 1999);
- }
-
- RequestError re = new RequestError();
-
- if("PolicyException".equals(exceptionType.name())){
-
- PolicyException pe = new PolicyException();
- pe.setMessageId(messageId);
- pe.setText(errorText);
- if(variables != null){
- for(String variable: variables){
- pe.getVariables().add(variable);
- }
- }
- re.setPolicyException(pe);
-
- } else {
-
- ServiceException se = new ServiceException();
- se.setMessageId(messageId);
- se.setText(errorText);
- if(variables != null){
- for(String variable: variables){
- se.getVariables().add(variable);
- }
- }
- re.setServiceException(se);
- }
+
+ public Response buildServiceErrorResponse(int httpResponseCode, MsoException exceptionType, String errorText,
+ String messageId, List<String> variables, String version) {
+
+ if (errorText.length() > 1999) {
+ errorText = errorText.substring(0, 1999);
+ }
+
+ RequestError re = new RequestError();
+
+ if ("PolicyException".equals(exceptionType.name())) {
+
+ PolicyException pe = new PolicyException();
+ pe.setMessageId(messageId);
+ pe.setText(errorText);
+ if (variables != null) {
+ for (String variable : variables) {
+ pe.getVariables().add(variable);
+ }
+ }
+ re.setPolicyException(pe);
+
+ } else {
+
+ ServiceException se = new ServiceException();
+ se.setMessageId(messageId);
+ se.setText(errorText);
+ if (variables != null) {
+ for (String variable : variables) {
+ se.getVariables().add(variable);
+ }
+ }
+ re.setServiceException(se);
+ }
String requestErrorStr = null;
- try{
- ObjectMapper mapper = new ObjectMapper();
- mapper.setSerializationInclusion(Include.NON_DEFAULT);
- requestErrorStr = mapper.writeValueAsString(re);
- }catch(Exception e){
- logger.error("{} {} {}", MessageEnum.APIH_VALIDATION_ERROR.toString(), ErrorCode.DataError.getValue(),
- "Exception in buildServiceErrorResponse writing exceptionType to string ", e);
- }
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(Include.NON_DEFAULT);
+ requestErrorStr = mapper.writeValueAsString(re);
+ } catch (Exception e) {
+ logger.error("{} {} {}", MessageEnum.APIH_VALIDATION_ERROR.toString(), ErrorCode.DataError.getValue(),
+ "Exception in buildServiceErrorResponse writing exceptionType to string ", e);
+ }
return builder.buildResponse(httpResponseCode, null, requestErrorStr, version);
}
-
+
// Parse request JSON
- public void parse (ServiceInstancesRequest sir, HashMap<String,String> instanceIdMap, Actions action, String version,
- String originalRequestJSON, int reqVersion, Boolean aLaCarteFlag) throws ValidationException, IOException {
-
- logger.debug ("Validating the Service Instance request");
+ public void parse(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action,
+ String version, String originalRequestJSON, int reqVersion, Boolean aLaCarteFlag)
+ throws ValidationException, IOException {
+
+ logger.debug("Validating the Service Instance request");
List<ValidationRule> rules = new ArrayList<>();
- logger.debug ("Incoming version is: {} coverting to int: {}", version, reqVersion);
- RequestParameters requestParameters = sir.getRequestDetails().getRequestParameters();
- ValidationInformation info = new ValidationInformation(sir, instanceIdMap, action,
- reqVersion, aLaCarteFlag, requestParameters);
-
+ logger.debug("Incoming version is: {} coverting to int: {}", version, reqVersion);
+ RequestParameters requestParameters = sir.getRequestDetails().getRequestParameters();
+ ValidationInformation info =
+ new ValidationInformation(sir, instanceIdMap, action, reqVersion, aLaCarteFlag, requestParameters);
+
rules.add(new InstanceIdMapValidation());
-
+
String workflowUuid = null;
if (instanceIdMap != null) {
- workflowUuid = instanceIdMap.get("workflowUuid");
+ workflowUuid = instanceIdMap.get("workflowUuid");
}
-
+
if (workflowUuid != null) {
- rules.add(new CustomWorkflowValidation());
- }else if(reqVersion >= 6 && action == Action.inPlaceSoftwareUpdate){
- rules.add(new InPlaceSoftwareUpdateValidation());
- }else if(reqVersion >= 6 && action == Action.applyUpdatedConfig){
- rules.add(new ApplyUpdatedConfigValidation());
- }else if(action == Action.addMembers || action == Action.removeMembers){
- rules.add(new MembersValidation());
- }else{
- rules.add(new RequestScopeValidation());
- rules.add(new RequestParametersValidation());
- rules.add(new RequestInfoValidation());
- rules.add(new ModelInfoValidation());
- rules.add(new CloudConfigurationValidation());
- rules.add(new SubscriberInfoValidation());
- rules.add(new PlatformLOBValidation());
- rules.add(new ProjectOwningEntityValidation());
- rules.add(new RelatedInstancesValidation());
- rules.add(new ConfigurationParametersValidation());
- }
- if(reqVersion >= 7 && requestParameters != null && requestParameters.getUserParams() != null){
- for(Map<String, Object> params : requestParameters.getUserParams()){
- if(params.containsKey("service")){
- ObjectMapper obj = new ObjectMapper();
- String input = obj.writeValueAsString(params.get("service"));
- Service validate = obj.readValue(input, Service.class);
- info.setUserParams(validate);
- rules.add(new UserParamsValidation());
- break;
- }
- }
- }
- for(ValidationRule rule : rules){
- rule.validate(info);
- }
+ rules.add(new CustomWorkflowValidation());
+ } else if (reqVersion >= 6 && action == Action.inPlaceSoftwareUpdate) {
+ rules.add(new InPlaceSoftwareUpdateValidation());
+ } else if (reqVersion >= 6 && action == Action.applyUpdatedConfig) {
+ rules.add(new ApplyUpdatedConfigValidation());
+ } else if (action == Action.addMembers || action == Action.removeMembers) {
+ rules.add(new MembersValidation());
+ } else {
+ rules.add(new RequestScopeValidation());
+ rules.add(new RequestParametersValidation());
+ rules.add(new RequestInfoValidation());
+ rules.add(new ModelInfoValidation());
+ rules.add(new CloudConfigurationValidation());
+ rules.add(new SubscriberInfoValidation());
+ rules.add(new PlatformLOBValidation());
+ rules.add(new ProjectOwningEntityValidation());
+ rules.add(new RelatedInstancesValidation());
+ rules.add(new ConfigurationParametersValidation());
+ }
+ if (reqVersion >= 7 && requestParameters != null && requestParameters.getUserParams() != null) {
+ for (Map<String, Object> params : requestParameters.getUserParams()) {
+ if (params.containsKey("service")) {
+ ObjectMapper obj = new ObjectMapper();
+ String input = obj.writeValueAsString(params.get("service"));
+ Service validate = obj.readValue(input, Service.class);
+ info.setUserParams(validate);
+ rules.add(new UserParamsValidation());
+ break;
+ }
+ }
+ }
+ for (ValidationRule rule : rules) {
+ rule.validate(info);
+ }
}
- void parseOrchestration (ServiceInstancesRequest sir) throws ValidationException {
+
+ void parseOrchestration(ServiceInstancesRequest sir) throws ValidationException {
RequestInfo requestInfo = sir.getRequestDetails().getRequestInfo();
if (requestInfo == null) {
- throw new ValidationException ("requestInfo");
+ throw new ValidationException("requestInfo");
}
- if (empty (requestInfo.getSource ())) {
- throw new ValidationException ("source");
+ if (empty(requestInfo.getSource())) {
+ throw new ValidationException("source");
}
- if (empty (requestInfo.getRequestorId ())) {
- throw new ValidationException ("requestorId");
+ if (empty(requestInfo.getRequestorId())) {
+ throw new ValidationException("requestorId");
}
}
- public Map<String, List<String>> getOrchestrationFilters (MultivaluedMap<String, String> queryParams) throws ValidationException {
+
+ public Map<String, List<String>> getOrchestrationFilters(MultivaluedMap<String, String> queryParams)
+ throws ValidationException {
String queryParam = null;
Map<String, List<String>> orchestrationFilterParams = new HashMap<>();
- for (Entry<String,List<String>> entry : queryParams.entrySet()) {
+ for (Entry<String, List<String>> entry : queryParams.entrySet()) {
queryParam = entry.getKey();
- try{
- if("filter".equalsIgnoreCase(queryParam)){
- for(String value : entry.getValue()) {
- StringTokenizer st = new StringTokenizer(value, ":");
-
- int counter=0;
- String mapKey=null;
- List<String> orchestrationList = new ArrayList<>();
- while (st.hasMoreElements()) {
- if(counter == 0){
- mapKey = st.nextElement() + "";
- } else{
- orchestrationList.add(st.nextElement() + "");
- }
- counter++;
- }
- orchestrationFilterParams.put(mapKey, orchestrationList);
- }
- }
-
- }catch(Exception e){
- throw new ValidationException ("QueryParam ServiceInfo", e);
- }
+ try {
+ if ("filter".equalsIgnoreCase(queryParam)) {
+ for (String value : entry.getValue()) {
+ StringTokenizer st = new StringTokenizer(value, ":");
+
+ int counter = 0;
+ String mapKey = null;
+ List<String> orchestrationList = new ArrayList<>();
+ while (st.hasMoreElements()) {
+ if (counter == 0) {
+ mapKey = st.nextElement() + "";
+ } else {
+ orchestrationList.add(st.nextElement() + "");
+ }
+ counter++;
+ }
+ orchestrationFilterParams.put(mapKey, orchestrationList);
+ }
+ }
+
+ } catch (Exception e) {
+ throw new ValidationException("QueryParam ServiceInfo", e);
+ }
}
return orchestrationFilterParams;
- }
+ }
- public InfraActiveRequests createRequestObject (ServiceInstancesRequest servInsReq, Actions action, String requestId,
- Status status, String originalRequestJSON, String requestScope) {
- InfraActiveRequests aq = new InfraActiveRequests ();
+ public InfraActiveRequests createRequestObject(ServiceInstancesRequest servInsReq, Actions action, String requestId,
+ Status status, String originalRequestJSON, String requestScope) {
+ InfraActiveRequests aq = new InfraActiveRequests();
try {
if (null == servInsReq) {
- servInsReq = new ServiceInstancesRequest ();
+ servInsReq = new ServiceInstancesRequest();
}
String networkType = "";
String vnfType = "";
- aq.setRequestId (requestId);
+ aq.setRequestId(requestId);
aq.setRequestAction(action.toString());
aq.setAction(action.toString());
aq.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
- Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
-
- aq.setStartTime (startTimeStamp);
- if(requestScope.equals(ModelType.instanceGroup.name()) && action == Action.deleteInstance){
- aq.setRequestScope(requestScope);
- }else{
- RequestInfo requestInfo =servInsReq.getRequestDetails().getRequestInfo();
- if (requestInfo != null) {
-
- if(requestInfo.getSource() != null){
- aq.setSource(requestInfo.getSource());
- }
- if(requestInfo.getCallbackUrl() != null){
- aq.setCallBackUrl(requestInfo.getCallbackUrl());
- }
- if(requestInfo.getCorrelator() != null){
- aq.setCorrelator(requestInfo.getCorrelator());
- }
-
- if(requestInfo.getRequestorId() != null) {
- aq.setRequestorId(requestInfo.getRequestorId());
- }
- }
-
- if (servInsReq.getRequestDetails().getModelInfo() != null || (action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig)) {
- aq.setRequestScope(requestScope);
- }
-
- if (servInsReq.getRequestDetails().getCloudConfiguration() != null) {
- CloudConfiguration cloudConfiguration = servInsReq.getRequestDetails().getCloudConfiguration();
- if(cloudConfiguration.getLcpCloudRegionId() != null) {
- aq.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId());
- }
-
- if(cloudConfiguration.getTenantId() != null) {
- aq.setTenantId(cloudConfiguration.getTenantId());
- }
-
- }
-
- if(servInsReq.getServiceInstanceId() != null){
- aq.setServiceInstanceId(servInsReq.getServiceInstanceId());
- }
-
- if(servInsReq.getVnfInstanceId() != null){
- aq.setVnfId(servInsReq.getVnfInstanceId());
- }
-
- if(ModelType.service.name().equalsIgnoreCase(requestScope)){
- if(servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null){
- aq.setServiceInstanceName(requestInfo.getInstanceName());
- }
- }
-
- if(ModelType.network.name().equalsIgnoreCase(requestScope)){
- aq.setNetworkName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName());
- aq.setNetworkType(networkType);
- aq.setNetworkId(servInsReq.getNetworkInstanceId());
- }
-
- if(ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)){
- aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId());
- aq.setVolumeGroupName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName());
- aq.setVnfType(vnfType);
-
- }
-
- if(ModelType.vfModule.name().equalsIgnoreCase(requestScope)){
- aq.setVfModuleName(requestInfo.getInstanceName());
- aq.setVfModuleModelName(servInsReq.getRequestDetails().getModelInfo().getModelName());
- aq.setVfModuleId(servInsReq.getVfModuleInstanceId());
- aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId());
- aq.setVnfType(vnfType);
-
- }
-
- if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
- aq.setConfigurationId(servInsReq.getConfigurationId());
- aq.setConfigurationName(requestInfo.getInstanceName());
- }
- if(requestScope.equalsIgnoreCase(ModelType.instanceGroup.name())){
- aq.setInstanceGroupId(servInsReq.getInstanceGroupId());
- aq.setInstanceGroupName(requestInfo.getInstanceName());
- }
- if(ModelType.vnf.name().equalsIgnoreCase(requestScope)){
- if (requestInfo != null) {
- aq.setVnfName(requestInfo.getInstanceName());
- }
- if (null != servInsReq.getRequestDetails()) {
- RelatedInstanceList[] instanceList = servInsReq.getRequestDetails().getRelatedInstanceList();
-
- if (instanceList != null) {
-
- for(RelatedInstanceList relatedInstanceList : instanceList){
-
- RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
- if(relatedInstance.getModelInfo().getModelType().equals(ModelType.service)){
- aq.setVnfType(vnfType);
- }
- }
- }
- }
- }
+ Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
+
+ aq.setStartTime(startTimeStamp);
+ if (requestScope.equals(ModelType.instanceGroup.name()) && action == Action.deleteInstance) {
+ aq.setRequestScope(requestScope);
+ } else {
+ RequestInfo requestInfo = servInsReq.getRequestDetails().getRequestInfo();
+ if (requestInfo != null) {
+
+ if (requestInfo.getSource() != null) {
+ aq.setSource(requestInfo.getSource());
+ }
+ if (requestInfo.getCallbackUrl() != null) {
+ aq.setCallBackUrl(requestInfo.getCallbackUrl());
+ }
+ if (requestInfo.getCorrelator() != null) {
+ aq.setCorrelator(requestInfo.getCorrelator());
+ }
+
+ if (requestInfo.getRequestorId() != null) {
+ aq.setRequestorId(requestInfo.getRequestorId());
+ }
+ }
+
+ if (servInsReq.getRequestDetails().getModelInfo() != null
+ || (action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig)) {
+ aq.setRequestScope(requestScope);
+ }
+
+ if (servInsReq.getRequestDetails().getCloudConfiguration() != null) {
+ CloudConfiguration cloudConfiguration = servInsReq.getRequestDetails().getCloudConfiguration();
+ if (cloudConfiguration.getLcpCloudRegionId() != null) {
+ aq.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId());
+ }
+
+ if (cloudConfiguration.getTenantId() != null) {
+ aq.setTenantId(cloudConfiguration.getTenantId());
+ }
+
+ }
+
+ if (servInsReq.getServiceInstanceId() != null) {
+ aq.setServiceInstanceId(servInsReq.getServiceInstanceId());
+ }
+
+ if (servInsReq.getVnfInstanceId() != null) {
+ aq.setVnfId(servInsReq.getVnfInstanceId());
+ }
+
+ if (ModelType.service.name().equalsIgnoreCase(requestScope)) {
+ if (servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null) {
+ aq.setServiceInstanceName(requestInfo.getInstanceName());
+ }
+ }
+
+ if (ModelType.network.name().equalsIgnoreCase(requestScope)) {
+ aq.setNetworkName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName());
+ aq.setNetworkType(networkType);
+ aq.setNetworkId(servInsReq.getNetworkInstanceId());
+ }
+
+ if (ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)) {
+ aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId());
+ aq.setVolumeGroupName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName());
+ aq.setVnfType(vnfType);
+
+ }
+
+ if (ModelType.vfModule.name().equalsIgnoreCase(requestScope)) {
+ aq.setVfModuleName(requestInfo.getInstanceName());
+ aq.setVfModuleModelName(servInsReq.getRequestDetails().getModelInfo().getModelName());
+ aq.setVfModuleId(servInsReq.getVfModuleInstanceId());
+ aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId());
+ aq.setVnfType(vnfType);
+
+ }
+
+ if (ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
+ aq.setConfigurationId(servInsReq.getConfigurationId());
+ aq.setConfigurationName(requestInfo.getInstanceName());
+ }
+ if (requestScope.equalsIgnoreCase(ModelType.instanceGroup.name())) {
+ aq.setInstanceGroupId(servInsReq.getInstanceGroupId());
+ aq.setInstanceGroupName(requestInfo.getInstanceName());
+ }
+ if (ModelType.vnf.name().equalsIgnoreCase(requestScope)) {
+ if (requestInfo != null) {
+ aq.setVnfName(requestInfo.getInstanceName());
+ }
+ if (null != servInsReq.getRequestDetails()) {
+ RelatedInstanceList[] instanceList = servInsReq.getRequestDetails().getRelatedInstanceList();
+
+ if (instanceList != null) {
+
+ for (RelatedInstanceList relatedInstanceList : instanceList) {
+
+ RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
+ if (relatedInstance.getModelInfo().getModelType().equals(ModelType.service)) {
+ aq.setVnfType(vnfType);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ aq.setRequestBody(originalRequestJSON);
+
+ aq.setRequestStatus(status.toString());
+ aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ } catch (Exception e) {
+ logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(),
+ "Exception when creation record request", e);
+
+ if (!status.equals(Status.FAILED)) {
+ throw e;
+ }
+ }
+ return aq;
+ }
+
+ public InfraActiveRequests createRequestObject(TasksRequest taskRequest, Action action, String requestId,
+ Status status, String originalRequestJSON) {
+ InfraActiveRequests aq = new InfraActiveRequests();
+ try {
+
+ org.onap.so.apihandlerinfra.tasksbeans.RequestInfo requestInfo =
+ taskRequest.getRequestDetails().getRequestInfo();
+ aq.setRequestId(requestId);
+ aq.setRequestAction(action.name());
+ aq.setAction(action.name());
+ aq.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
+
+ Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
+
+ aq.setStartTime(startTimeStamp);
+ if (requestInfo != null) {
+
+ if (requestInfo.getSource() != null) {
+ aq.setSource(requestInfo.getSource());
+ }
+
+ if (requestInfo.getRequestorId() != null) {
+ aq.setRequestorId(requestInfo.getRequestorId());
+ }
}
- aq.setRequestBody (originalRequestJSON);
+ aq.setRequestBody(originalRequestJSON);
+ aq.setRequestStatus(status.toString());
+ aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
- aq.setRequestStatus (status.toString ());
- aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER);
} catch (Exception e) {
- logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(),
- "Exception when creation record request", e);
+ logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(),
+ "Exception when creation record request", e);
- if (!status.equals (Status.FAILED)) {
+ if (!status.equals(Status.FAILED)) {
throw e;
}
}
return aq;
}
-
- public InfraActiveRequests createRequestObject (TasksRequest taskRequest, Action action, String requestId,
- Status status, String originalRequestJSON) {
- InfraActiveRequests aq = new InfraActiveRequests ();
- try {
-
- org.onap.so.apihandlerinfra.tasksbeans.RequestInfo requestInfo = taskRequest.getRequestDetails().getRequestInfo();
- aq.setRequestId (requestId);
- aq.setRequestAction(action.name());
- aq.setAction(action.name());
- aq.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
-
- Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
-
- aq.setStartTime (startTimeStamp);
- if (requestInfo != null) {
-
- if(requestInfo.getSource() != null){
- aq.setSource(requestInfo.getSource());
- }
-
- if(requestInfo.getRequestorId() != null) {
- aq.setRequestorId(requestInfo.getRequestorId());
- }
- }
-
- aq.setRequestBody (originalRequestJSON);
- aq.setRequestStatus (status.toString ());
- aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER);
-
- } catch (Exception e) {
- logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(),
- "Exception when creation record request", e);
-
- if (!status.equals (Status.FAILED)) {
- throw e;
- }
- }
- return aq;
- }
-
- public void createErrorRequestRecord (Status status, String requestId, String errorMessage, Actions action, String requestScope, String requestJSON) {
+
+ public void createErrorRequestRecord(Status status, String requestId, String errorMessage, Actions action,
+ String requestScope, String requestJSON) {
try {
InfraActiveRequests request = new InfraActiveRequests(requestId);
- Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
- request.setStartTime (startTimeStamp);
+ Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
+ request.setStartTime(startTimeStamp);
request.setRequestStatus(status.toString());
request.setStatusMessage(errorMessage);
request.setProgress((long) 100);
@@ -458,338 +462,345 @@ public class MsoRequest {
request.setRequestBody(requestJSON);
Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
request.setEndTime(endTimeStamp);
- request.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
- requestsDbClient.save(request);
+ request.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
+ requestsDbClient.save(request);
} catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(),
- ErrorCode.DataError.getValue(), "Exception when updating record in DB");
- logger.debug("Exception: ", e);
- }
+ logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(),
+ ErrorCode.DataError.getValue(), "Exception when updating record in DB");
+ logger.debug("Exception: ", e);
+ }
}
-
-
- public Response buildResponse (int httpResponseCode, String errorCode, InfraActiveRequests inProgress) {
- return buildResponseWithError (httpResponseCode, errorCode, inProgress, null);
+
+ public Response buildResponse(int httpResponseCode, String errorCode, InfraActiveRequests inProgress) {
+ return buildResponseWithError(httpResponseCode, errorCode, inProgress, null);
}
- public Response buildResponseWithError (int httpResponseCode,
- String errorCode,
- InfraActiveRequests inProgress,
- String errorString) {
+ public Response buildResponseWithError(int httpResponseCode, String errorCode, InfraActiveRequests inProgress,
+ String errorString) {
// Log the failed request into the MSO Requests database
- return Response.status (httpResponseCode).entity (null).build ();
+ return Response.status(httpResponseCode).entity(null).build();
}
- public Response buildResponseFailedValidation (int httpResponseCode, String exceptionMessage) {
+ public Response buildResponseFailedValidation(int httpResponseCode, String exceptionMessage) {
- return Response.status (httpResponseCode).entity (null).build ();
+ return Response.status(httpResponseCode).entity(null).build();
}
-
-
-
- public String getServiceType (VnfInputs vnfInputs) {
- if (vnfInputs.getServiceType () != null)
- return vnfInputs.getServiceType ();
- if (vnfInputs.getServiceId () != null)
- return vnfInputs.getServiceId ();
- return null;
+
+
+
+ public String getServiceType(VnfInputs vnfInputs) {
+ if (vnfInputs.getServiceType() != null)
+ return vnfInputs.getServiceType();
+ if (vnfInputs.getServiceId() != null)
+ return vnfInputs.getServiceId();
+ return null;
}
- public long translateStatus (RequestStatusType status) {
+ public long translateStatus(RequestStatusType status) {
switch (status) {
- case FAILED:
- case COMPLETE:
- return Constants.PROGRESS_REQUEST_COMPLETED;
- case IN_PROGRESS:
- return Constants.PROGRESS_REQUEST_IN_PROGRESS;
- default:
- return 0;
+ case FAILED:
+ case COMPLETE:
+ return Constants.PROGRESS_REQUEST_COMPLETED;
+ case IN_PROGRESS:
+ return Constants.PROGRESS_REQUEST_IN_PROGRESS;
+ default:
+ return 0;
}
}
- public static String domToStr (Document doc) {
+ public static String domToStr(Document doc) {
if (doc == null) {
return null;
}
try {
- StringWriter sw = new StringWriter ();
- StreamResult sr = new StreamResult (sw);
- TransformerFactory tf = TransformerFactory.newInstance ();
- tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
- tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET,"");
- Transformer t = tf.newTransformer ();
- t.setOutputProperty (OutputKeys.STANDALONE, "yes");
- NodeList nl = doc.getDocumentElement ().getChildNodes ();
+ StringWriter sw = new StringWriter();
+ StreamResult sr = new StreamResult(sw);
+ TransformerFactory tf = TransformerFactory.newInstance();
+ tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
+ tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
+ Transformer t = tf.newTransformer();
+ t.setOutputProperty(OutputKeys.STANDALONE, "yes");
+ NodeList nl = doc.getDocumentElement().getChildNodes();
DOMSource source = null;
- for (int x = 0; x < nl.getLength (); x++) {
- Node e = nl.item (x);
+ for (int x = 0; x < nl.getLength(); x++) {
+ Node e = nl.item(x);
if (e instanceof Element) {
- source = new DOMSource (e);
+ source = new DOMSource(e);
break;
}
}
if (source != null) {
- t.transform (source, sr);
+ t.transform(source, sr);
- String s = sw.toString ();
+ String s = sw.toString();
return s;
}
return null;
} catch (Exception e) {
- logger.error("{} {} {}", MessageEnum.APIH_DOM2STR_ERROR.toString(), ErrorCode.DataError.getValue(),
- "Exception in domToStr", e);
- }
+ logger.error("{} {} {}", MessageEnum.APIH_DOM2STR_ERROR.toString(), ErrorCode.DataError.getValue(),
+ "Exception in domToStr", e);
+ }
return null;
}
- public void addBPMNSpecificInputs(VnfRequest vnfReq, VnfInputs vnfInputs, String personaModelId, String personaModelVersion, Boolean isBaseVfModule,
- String vnfPersonaModelId, String vnfPersonaModelVersion) {
- vnfInputs.setPersonaModelId(personaModelId);
- vnfInputs.setPersonaModelVersion(personaModelVersion);
- vnfInputs.setIsBaseVfModule(isBaseVfModule);
- vnfInputs.setVnfPersonaModelId(vnfPersonaModelId);
- vnfInputs.setVnfPersonaModelVersion(vnfPersonaModelVersion);
+ public void addBPMNSpecificInputs(VnfRequest vnfReq, VnfInputs vnfInputs, String personaModelId,
+ String personaModelVersion, Boolean isBaseVfModule, String vnfPersonaModelId,
+ String vnfPersonaModelVersion) {
+ vnfInputs.setPersonaModelId(personaModelId);
+ vnfInputs.setPersonaModelVersion(personaModelVersion);
+ vnfInputs.setIsBaseVfModule(isBaseVfModule);
+ vnfInputs.setVnfPersonaModelId(vnfPersonaModelId);
+ vnfInputs.setVnfPersonaModelVersion(vnfPersonaModelVersion);
+
+ vnfReq.setVnfInputs(vnfInputs);
- vnfReq.setVnfInputs(vnfInputs);
-
}
private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
+ return (s == null || s.trim().isEmpty());
}
- public String getRequestJSON(ServiceInstancesRequest sir) throws JsonGenerationException, JsonMappingException, IOException {
- ObjectMapper mapper = new ObjectMapper();
- mapper.setSerializationInclusion(Include.NON_NULL);
- //mapper.configure(Feature.WRAP_ROOT_VALUE, true);
- logger.debug ("building sir from object {}", sir);
- String requestJSON = mapper.writeValueAsString(sir);
-
- // Perform mapping from VID-style modelInfo fields to ASDC-style modelInfo fields
-
- logger.debug("REQUEST JSON before mapping: {}", requestJSON);
- // modelUuid = modelVersionId
- requestJSON = requestJSON.replaceAll("\"modelVersionId\":","\"modelUuid\":");
- // modelCustomizationUuid = modelCustomizationId
- requestJSON = requestJSON.replaceAll("\"modelCustomizationId\":","\"modelCustomizationUuid\":");
- // modelInstanceName = modelCustomizationName
- requestJSON = requestJSON.replaceAll("\"modelCustomizationName\":","\"modelInstanceName\":");
- // modelInvariantUuid = modelInvariantId
- requestJSON = requestJSON.replaceAll("\"modelInvariantId\":","\"modelInvariantUuid\":");
- logger.debug("REQUEST JSON after mapping: {}", requestJSON);
-
- return requestJSON;
+ public String getRequestJSON(ServiceInstancesRequest sir)
+ throws JsonGenerationException, JsonMappingException, IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(Include.NON_NULL);
+ // mapper.configure(Feature.WRAP_ROOT_VALUE, true);
+ logger.debug("building sir from object {}", sir);
+ String requestJSON = mapper.writeValueAsString(sir);
+
+ // Perform mapping from VID-style modelInfo fields to ASDC-style modelInfo fields
+
+ logger.debug("REQUEST JSON before mapping: {}", requestJSON);
+ // modelUuid = modelVersionId
+ requestJSON = requestJSON.replaceAll("\"modelVersionId\":", "\"modelUuid\":");
+ // modelCustomizationUuid = modelCustomizationId
+ requestJSON = requestJSON.replaceAll("\"modelCustomizationId\":", "\"modelCustomizationUuid\":");
+ // modelInstanceName = modelCustomizationName
+ requestJSON = requestJSON.replaceAll("\"modelCustomizationName\":", "\"modelInstanceName\":");
+ // modelInvariantUuid = modelInvariantId
+ requestJSON = requestJSON.replaceAll("\"modelInvariantId\":", "\"modelInvariantUuid\":");
+ logger.debug("REQUEST JSON after mapping: {}", requestJSON);
+
+ return requestJSON;
}
- public boolean getAlacarteFlag(ServiceInstancesRequest sir) {
- if(sir.getRequestDetails().getRequestParameters() != null &&
- sir.getRequestDetails().getRequestParameters().getALaCarte() != null)
- return sir.getRequestDetails().getRequestParameters().getALaCarte();
-
- return false;
- }
+ public boolean getAlacarteFlag(ServiceInstancesRequest sir) {
+ if (sir.getRequestDetails().getRequestParameters() != null
+ && sir.getRequestDetails().getRequestParameters().getALaCarte() != null)
+ return sir.getRequestDetails().getRequestParameters().getALaCarte();
+
+ return false;
+ }
- public String getNetworkType(ServiceInstancesRequest sir, String requestScope) {
- if(requestScope.equalsIgnoreCase(ModelType.network.name()))
- return sir.getRequestDetails().getModelInfo().getModelName();
- else return null;
- }
+ public String getNetworkType(ServiceInstancesRequest sir, String requestScope) {
+ if (requestScope.equalsIgnoreCase(ModelType.network.name()))
+ return sir.getRequestDetails().getModelInfo().getModelName();
+ else
+ return null;
+ }
- public String getServiceInstanceType(ServiceInstancesRequest sir, String requestScope) {
- if(requestScope.equalsIgnoreCase(ModelType.network.name()))
- return sir.getRequestDetails().getModelInfo().getModelName();
- else return null;
- }
+ public String getServiceInstanceType(ServiceInstancesRequest sir, String requestScope) {
+ if (requestScope.equalsIgnoreCase(ModelType.network.name()))
+ return sir.getRequestDetails().getModelInfo().getModelName();
+ else
+ return null;
+ }
- public String getSDCServiceModelVersion(ServiceInstancesRequest sir) {
- String sdcServiceModelVersion = null;
- if(sir.getRequestDetails().getRelatedInstanceList() != null)
- for(RelatedInstanceList relatedInstanceList : sir.getRequestDetails().getRelatedInstanceList()){
- RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
- ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo ();
- if(relatedInstanceModelInfo.getModelType().equals(ModelType.service))
- sdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion ();
- }
+ public String getSDCServiceModelVersion(ServiceInstancesRequest sir) {
+ String sdcServiceModelVersion = null;
+ if (sir.getRequestDetails().getRelatedInstanceList() != null)
+ for (RelatedInstanceList relatedInstanceList : sir.getRequestDetails().getRelatedInstanceList()) {
+ RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
+ ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo();
+ if (relatedInstanceModelInfo.getModelType().equals(ModelType.service))
+ sdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion();
+ }
return sdcServiceModelVersion;
- }
-
-
- public String getVfModuleType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) {
-
- String serviceInstanceType = null;
- String networkType = null;
- String vnfType = null;
- String vfModuleType = null;
- String vfModuleModelName = null;
- ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
- RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
- String serviceModelName = null;
+ }
+
+
+ public String getVfModuleType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) {
+
+ String serviceInstanceType = null;
+ String networkType = null;
+ String vnfType = null;
+ String vfModuleType = null;
+ String vfModuleModelName = null;
+ ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
+ RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
+ String serviceModelName = null;
String vnfModelName = null;
String asdcServiceModelVersion = null;
String volumeGroupId = null;
boolean isRelatedServiceInstancePresent = false;
boolean isRelatedVnfInstancePresent = false;
- boolean isSourceVnfPresent = false;
- boolean isDestinationVnfPresent = false;
- boolean isConnectionPointPresent = false;
-
- if (instanceList != null) {
- for(RelatedInstanceList relatedInstanceList : instanceList){
- RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
- ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo ();
-
- if (action != Action.deleteInstance) {
-
- if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
- if(InstanceDirection.source.equals(relatedInstance.getInstanceDirection()) && relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
- isSourceVnfPresent = true;
- } else if(InstanceDirection.destination.equals(relatedInstance.getInstanceDirection()) &&
- (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) || (relatedInstanceModelInfo.getModelType().equals(ModelType.pnf) && reqVersion == 6))) {
- isDestinationVnfPresent = true;
- }
- }
-
- if(ModelType.connectionPoint.equals(relatedInstanceModelInfo.getModelType()) && ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
- isConnectionPointPresent = true;
- }
- }
-
-
- if(relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
- isRelatedServiceInstancePresent = true;
- serviceModelName = relatedInstanceModelInfo.getModelName ();
- asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion ();
- } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) {
- isRelatedVnfInstancePresent = true;
- vnfModelName = relatedInstanceModelInfo.getModelCustomizationName();
- } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) {
- volumeGroupId = relatedInstance.getInstanceId ();
- }
- }
-
- if(requestScope.equalsIgnoreCase (ModelType.volumeGroup.name ())) {
- serviceInstanceType = serviceModelName;
- vnfType = serviceModelName + "/" + vnfModelName;
- }
- else if(requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) {
- vfModuleModelName = modelInfo.getModelName ();
- serviceInstanceType = serviceModelName;
- vnfType = serviceModelName + "/" + vnfModelName;
- vfModuleType = vnfType + "::" + vfModuleModelName;
- sir.setVolumeGroupInstanceId (volumeGroupId);
- }
- else if (requestScope.equalsIgnoreCase (ModelType.vnf.name ()))
- vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName();
-
- }
-
- return vfModuleType;
-
- }
-
- public String getVnfType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) {
-
- String serviceInstanceType = null;
- String networkType = null;
- String vnfType = null;
- String vfModuleType = null;
- String vfModuleModelName = null;
- ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
- RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
- String serviceModelName = null;
+ boolean isSourceVnfPresent = false;
+ boolean isDestinationVnfPresent = false;
+ boolean isConnectionPointPresent = false;
+
+ if (instanceList != null) {
+ for (RelatedInstanceList relatedInstanceList : instanceList) {
+ RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
+ ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo();
+
+ if (action != Action.deleteInstance) {
+
+ if (ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
+ if (InstanceDirection.source.equals(relatedInstance.getInstanceDirection())
+ && relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
+ isSourceVnfPresent = true;
+ } else if (InstanceDirection.destination.equals(relatedInstance.getInstanceDirection())
+ && (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)
+ || (relatedInstanceModelInfo.getModelType().equals(ModelType.pnf)
+ && reqVersion == 6))) {
+ isDestinationVnfPresent = true;
+ }
+ }
+
+ if (ModelType.connectionPoint.equals(relatedInstanceModelInfo.getModelType())
+ && ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
+ isConnectionPointPresent = true;
+ }
+ }
+
+
+ if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
+ isRelatedServiceInstancePresent = true;
+ serviceModelName = relatedInstanceModelInfo.getModelName();
+ asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion();
+ } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)
+ && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) {
+ isRelatedVnfInstancePresent = true;
+ vnfModelName = relatedInstanceModelInfo.getModelCustomizationName();
+ } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) {
+ volumeGroupId = relatedInstance.getInstanceId();
+ }
+ }
+
+ if (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name())) {
+ serviceInstanceType = serviceModelName;
+ vnfType = serviceModelName + "/" + vnfModelName;
+ } else if (requestScope.equalsIgnoreCase(ModelType.vfModule.name())) {
+ vfModuleModelName = modelInfo.getModelName();
+ serviceInstanceType = serviceModelName;
+ vnfType = serviceModelName + "/" + vnfModelName;
+ vfModuleType = vnfType + "::" + vfModuleModelName;
+ sir.setVolumeGroupInstanceId(volumeGroupId);
+ } else if (requestScope.equalsIgnoreCase(ModelType.vnf.name()))
+ vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName();
+
+ }
+
+ return vfModuleType;
+
+ }
+
+ public String getVnfType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) {
+
+ String serviceInstanceType = null;
+ String networkType = null;
+ String vnfType = null;
+ String vfModuleType = null;
+ String vfModuleModelName = null;
+ ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
+ RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
+ String serviceModelName = null;
String vnfModelName = null;
String asdcServiceModelVersion = null;
String volumeGroupId = null;
boolean isRelatedServiceInstancePresent = false;
boolean isRelatedVnfInstancePresent = false;
- boolean isSourceVnfPresent = false;
- boolean isDestinationVnfPresent = false;
- boolean isConnectionPointPresent = false;
-
- if (instanceList != null) {
- for(RelatedInstanceList relatedInstanceList : instanceList){
- RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
- ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo ();
-
- if (action != Action.deleteInstance) {
-
- if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
- if(InstanceDirection.source.equals(relatedInstance.getInstanceDirection()) && relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
- isSourceVnfPresent = true;
- } else if(InstanceDirection.destination.equals(relatedInstance.getInstanceDirection()) &&
- (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) || (relatedInstanceModelInfo.getModelType().equals(ModelType.pnf) && reqVersion == 6))) {
- isDestinationVnfPresent = true;
- }
- }
-
- if(ModelType.connectionPoint.equals(relatedInstanceModelInfo.getModelType()) && ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
- isConnectionPointPresent = true;
- }
- }
-
-
- if(relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
- isRelatedServiceInstancePresent = true;
- serviceModelName = relatedInstanceModelInfo.getModelName ();
- asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion ();
- } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) {
- isRelatedVnfInstancePresent = true;
- vnfModelName = relatedInstanceModelInfo.getModelCustomizationName();
- } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) {
- volumeGroupId = relatedInstance.getInstanceId ();
- }
- }
-
- if(requestScope.equalsIgnoreCase (ModelType.volumeGroup.name ())) {
- serviceInstanceType = serviceModelName;
- vnfType = serviceModelName + "/" + vnfModelName;
- }
- else if(requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) {
- vfModuleModelName = modelInfo.getModelName ();
- serviceInstanceType = serviceModelName;
- vnfType = serviceModelName + "/" + vnfModelName;
- vfModuleType = vnfType + "::" + vfModuleModelName;
- sir.setVolumeGroupInstanceId (volumeGroupId);
- }
- else if (requestScope.equalsIgnoreCase (ModelType.vnf.name ()))
- vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName();
-
- }
-
- return vnfType;
-
- }
-
- public Optional<URL> buildSelfLinkUrl(String url, String requestId) {
- Optional<URL> selfLinkUrl = Optional.empty();
- String version = "";
- try {
- URL aUrl = new URL(url);
- String aPath = aUrl.getPath();
- if (aPath.indexOf("/v") == -1) {
- version = aPath.substring(aPath.indexOf("/V"), aPath.indexOf("/V")+4);
- } else {
- version = aPath.substring(aPath.indexOf("/v"), aPath.indexOf("/v")+4);
- }
- String selfLinkPath = Constants.ORCHESTRATION_REQUESTS_PATH.concat(version).concat(requestId);
- selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath));
- } catch (Exception e) {
- selfLinkUrl = Optional.empty(); // ignore
- }
- return selfLinkUrl;
- }
+ boolean isSourceVnfPresent = false;
+ boolean isDestinationVnfPresent = false;
+ boolean isConnectionPointPresent = false;
+
+ if (instanceList != null) {
+ for (RelatedInstanceList relatedInstanceList : instanceList) {
+ RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
+ ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo();
+
+ if (action != Action.deleteInstance) {
+
+ if (ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
+ if (InstanceDirection.source.equals(relatedInstance.getInstanceDirection())
+ && relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
+ isSourceVnfPresent = true;
+ } else if (InstanceDirection.destination.equals(relatedInstance.getInstanceDirection())
+ && (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)
+ || (relatedInstanceModelInfo.getModelType().equals(ModelType.pnf)
+ && reqVersion == 6))) {
+ isDestinationVnfPresent = true;
+ }
+ }
+
+ if (ModelType.connectionPoint.equals(relatedInstanceModelInfo.getModelType())
+ && ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
+ isConnectionPointPresent = true;
+ }
+ }
+
+
+ if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
+ isRelatedServiceInstancePresent = true;
+ serviceModelName = relatedInstanceModelInfo.getModelName();
+ asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion();
+ } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)
+ && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) {
+ isRelatedVnfInstancePresent = true;
+ vnfModelName = relatedInstanceModelInfo.getModelCustomizationName();
+ } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) {
+ volumeGroupId = relatedInstance.getInstanceId();
+ }
+ }
+
+ if (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name())) {
+ serviceInstanceType = serviceModelName;
+ vnfType = serviceModelName + "/" + vnfModelName;
+ } else if (requestScope.equalsIgnoreCase(ModelType.vfModule.name())) {
+ vfModuleModelName = modelInfo.getModelName();
+ serviceInstanceType = serviceModelName;
+ vnfType = serviceModelName + "/" + vnfModelName;
+ vfModuleType = vnfType + "::" + vfModuleModelName;
+ sir.setVolumeGroupInstanceId(volumeGroupId);
+ } else if (requestScope.equalsIgnoreCase(ModelType.vnf.name()))
+ vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName();
+
+ }
+
+ return vnfType;
+
+ }
+
+ public Optional<URL> buildSelfLinkUrl(String url, String requestId) {
+ Optional<URL> selfLinkUrl = Optional.empty();
+ String version = "";
+ try {
+ URL aUrl = new URL(url);
+ String aPath = aUrl.getPath();
+ if (aPath.indexOf("/v") == -1) {
+ version = aPath.substring(aPath.indexOf("/V"), aPath.indexOf("/V") + 4);
+ } else {
+ version = aPath.substring(aPath.indexOf("/v"), aPath.indexOf("/v") + 4);
+ }
+ String selfLinkPath = Constants.ORCHESTRATION_REQUESTS_PATH.concat(version).concat(requestId);
+ selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath));
+ } catch (Exception e) {
+ selfLinkUrl = Optional.empty(); // ignore
+ }
+ return selfLinkUrl;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java
index cfdce473a4..fd0df1d2b0 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java
@@ -20,23 +20,19 @@
package org.onap.so.apihandlerinfra;
public enum MsoSubsystems {
- APIH ("API Handler"),
- ASDC ("ASDC Controller"),
- BPMN ("BPMN Infra"),
- CATALOGDB ("CatalogDb Adapter"),
- OPENSTACK ("Openstack Adapter"),
- REQUESTDB ("RequestDB Adapter"),
- REQUESTDBATT ("RequestDB Adapter ATT Svc"),
- SDNC ("SDNC Adapter");
- private String subsystem;
- private MsoSubsystems(String subsystem){
- this.subsystem = subsystem;
- }
-
- @Override
- public String toString(){
- return subsystem;
- }
-
+ APIH("API Handler"), ASDC("ASDC Controller"), BPMN("BPMN Infra"), CATALOGDB("CatalogDb Adapter"), OPENSTACK(
+ "Openstack Adapter"), REQUESTDB(
+ "RequestDB Adapter"), REQUESTDBATT("RequestDB Adapter ATT Svc"), SDNC("SDNC Adapter");
+ private String subsystem;
+
+ private MsoSubsystems(String subsystem) {
+ this.subsystem = subsystem;
+ }
+
+ @Override
+ public String toString() {
+ return subsystem;
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java
index 351a35826d..9810895ad9 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java
@@ -23,7 +23,6 @@
package org.onap.so.apihandlerinfra;
import java.net.UnknownHostException;
-
import javax.transaction.Transactional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@@ -31,34 +30,31 @@ import javax.ws.rs.Produces;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.onap.so.logger.MessageEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Path("/nodehealthcheck")
-@Api(value="/nodehealthcheck",description="API Handler Infra Node Health Check")
+@Api(value = "/nodehealthcheck", description = "API Handler Infra Node Health Check")
@Component
public class NodeHealthcheckHandler {
private static Logger logger = LoggerFactory.getLogger(NodeHealthcheckHandler.class);
-
- private static final String CHECK_HTML = "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Health Check</title></head><body>Application ready</body></html>";
- public static final Response HEALTH_CHECK_RESPONSE = Response.status (HttpStatus.SC_OK)
- .entity (CHECK_HTML)
- .build ();
-
+ private static final String CHECK_HTML =
+ "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Health Check</title></head><body>Application ready</body></html>";
+
+ public static final Response HEALTH_CHECK_RESPONSE = Response.status(HttpStatus.SC_OK).entity(CHECK_HTML).build();
+
@GET
@Produces("text/html")
- @ApiOperation(value="Performing node health check",response=Response.class)
+ @ApiOperation(value = "Performing node health check", response = Response.class)
@Transactional
- public Response nodeHealthcheck (@Context ContainerRequestContext requestContext) throws UnknownHostException {
+ public Response nodeHealthcheck(@Context ContainerRequestContext requestContext) throws UnknownHostException {
// Generated RequestId
String requestId = requestContext.getProperty("requestId").toString();
logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java
index f613d3e193..34dcd4b0c4 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java
@@ -28,7 +28,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
@@ -41,14 +40,12 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
-
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.onap.so.apihandler.common.ErrorNumbers;
import org.onap.so.apihandler.common.ResponseBuilder;
import org.onap.so.apihandlerinfra.exceptions.ApiException;
import org.onap.so.apihandlerinfra.exceptions.ValidateException;
-
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.db.request.beans.RequestProcessingData;
@@ -56,7 +53,6 @@ import org.onap.so.db.request.client.RequestsDbClient;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse;
import org.onap.so.serviceinstancebeans.GetOrchestrationResponse;
import org.onap.so.serviceinstancebeans.InstanceReferences;
@@ -69,365 +65,397 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Path("onap/so/infra/orchestrationRequests")
-@Api(value="onap/so/infra/orchestrationRequests",description="API Requests for Orchestration requests")
+@Api(value = "onap/so/infra/orchestrationRequests", description = "API Requests for Orchestration requests")
@Component
public class OrchestrationRequests {
private static Logger logger = LoggerFactory.getLogger(OrchestrationRequests.class);
-
+
@Autowired
- private RequestsDbClient requestsDbClient;
+ private RequestsDbClient requestsDbClient;
@Autowired
private MsoRequest msoRequest;
-
- @Autowired
- private ResponseBuilder builder;
- @GET
- @Path("/{version:[vV][4-7]}/{requestId}")
- @ApiOperation(value="Find Orchestrated Requests for a given requestId",response=Response.class)
- @Produces(MediaType.APPLICATION_JSON)
- @Transactional
- public Response getOrchestrationRequest(@PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException{
+ @Autowired
+ private ResponseBuilder builder;
+
+ @GET
+ @Path("/{version:[vV][4-7]}/{requestId}")
+ @ApiOperation(value = "Find Orchestrated Requests for a given requestId", response = Response.class)
+ @Produces(MediaType.APPLICATION_JSON)
+ @Transactional
+ public Response getOrchestrationRequest(@PathParam("requestId") String requestId,
+ @PathParam("version") String version) throws ApiException {
- String apiVersion = version.substring(1);
- GetOrchestrationResponse orchestrationResponse = new GetOrchestrationResponse();
+ String apiVersion = version.substring(1);
+ GetOrchestrationResponse orchestrationResponse = new GetOrchestrationResponse();
- InfraActiveRequests infraActiveRequest = null;
- List<org.onap.so.db.request.beans.RequestProcessingData> requestProcessingData = null;
- try {
- infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
- requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(requestId);
+ InfraActiveRequests infraActiveRequest = null;
+ List<org.onap.so.db.request.beans.RequestProcessingData> requestProcessingData = null;
+ try {
+ infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
+ requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(requestId);
- } catch (Exception e) {
- logger.error("Exception occurred", e);
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build();
+ } catch (Exception e) {
+ logger.error("Exception occurred", e);
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build();
+ ValidateException validateException =
+ new ValidateException.Builder("Exception while communciate with Request DB - Infra Request Lookup",
+ HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e)
+ .errorInfo(errorLoggerInfo).build();
- ValidateException validateException = new ValidateException.Builder("Exception while communciate with Request DB - Infra Request Lookup",
- HttpStatus.SC_NOT_FOUND,ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e).errorInfo(errorLoggerInfo).build();
+ throw validateException;
- throw validateException;
+ }
- }
-
- if(infraActiveRequest == null) {
+ if (infraActiveRequest == null) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).build();
+ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
+ ErrorCode.BusinessProcesssError).build();
- ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
- HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+ ValidateException validateException =
+ new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
+ HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
+ .errorInfo(errorLoggerInfo).build();
throw validateException;
}
-
+
Request request = mapInfraActiveRequestToRequest(infraActiveRequest);
- if(!requestProcessingData.isEmpty()){
+ if (!requestProcessingData.isEmpty()) {
request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData));
}
- request.setRequestId(requestId);
+ request.setRequestId(requestId);
orchestrationResponse.setRequest(request);
-
+
return builder.buildResponse(HttpStatus.SC_OK, requestId, orchestrationResponse, apiVersion);
- }
-
- @GET
- @Path("/{version:[vV][4-7]}")
- @ApiOperation(value="Find Orchestrated Requests for a URI Information",response=Response.class)
- @Produces(MediaType.APPLICATION_JSON)
- @Transactional
- public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version) throws ApiException{
-
- long startTime = System.currentTimeMillis ();
-
- MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
-
- List<InfraActiveRequests> activeRequests = null;
-
- GetOrchestrationListResponse orchestrationList = null;
- Map<String, List<String>> orchestrationMap;
- String apiVersion = version.substring(1);
-
- try {
- orchestrationMap = msoRequest.getOrchestrationFilters(queryParams);
- if (orchestrationMap.isEmpty()) {
- throw new ValidationException("At least one filter query param must be specified");
- }
- }catch(ValidationException ex){
- logger.error("Exception occurred", ex);
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.DataError).build();
- ValidateException validateException = new ValidateException.Builder(ex.getMessage(),
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
- throw validateException;
-
- }
-
- activeRequests = requestsDbClient.getOrchestrationFiltersFromInfraActive(orchestrationMap);
-
- orchestrationList = new GetOrchestrationListResponse();
- List<RequestList> requestLists = new ArrayList<>();
-
- for(InfraActiveRequests infraActive : activeRequests){
- List<RequestProcessingData> requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId());
- RequestList requestList = new RequestList();
- Request request = mapInfraActiveRequestToRequest(infraActive);
- if(!requestProcessingData.isEmpty()){
- request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData));
- }
- requestList.setRequest(request);
- requestLists.add(requestList);
- }
-
- orchestrationList.setRequestList(requestLists);
- return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
- }
-
-
- @POST
- @Path("/{version: [vV][4-7]}/{requestId}/unlock")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Unlock Orchestrated Requests for a given requestId",response=Response.class)
- @Transactional
- public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException{
-
- long startTime = System.currentTimeMillis ();
- logger.debug ("requestId is: {}", requestId);
- ServiceInstancesRequest sir = null;
-
- InfraActiveRequests infraActiveRequest = null;
- Request request = null;
-
- try{
- ObjectMapper mapper = new ObjectMapper();
- sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class);
- } catch(IOException e){
- logger.error("Exception occurred", e);
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build();
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
+ }
+
+ @GET
+ @Path("/{version:[vV][4-7]}")
+ @ApiOperation(value = "Find Orchestrated Requests for a URI Information", response = Response.class)
+ @Produces(MediaType.APPLICATION_JSON)
+ @Transactional
+ public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version)
+ throws ApiException {
+
+ long startTime = System.currentTimeMillis();
+
+ MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
+
+ List<InfraActiveRequests> activeRequests = null;
+
+ GetOrchestrationListResponse orchestrationList = null;
+ Map<String, List<String>> orchestrationMap;
+ String apiVersion = version.substring(1);
+
+ try {
+ orchestrationMap = msoRequest.getOrchestrationFilters(queryParams);
+ if (orchestrationMap.isEmpty()) {
+ throw new ValidationException("At least one filter query param must be specified");
+ }
+ } catch (ValidationException ex) {
+ logger.error("Exception occurred", ex);
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.DataError).build();
+ ValidateException validateException =
+ new ValidateException.Builder(ex.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
+ throw validateException;
+
+ }
+
+ activeRequests = requestsDbClient.getOrchestrationFiltersFromInfraActive(orchestrationMap);
+
+ orchestrationList = new GetOrchestrationListResponse();
+ List<RequestList> requestLists = new ArrayList<>();
+
+ for (InfraActiveRequests infraActive : activeRequests) {
+ List<RequestProcessingData> requestProcessingData =
+ requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId());
+ RequestList requestList = new RequestList();
+ Request request = mapInfraActiveRequestToRequest(infraActive);
+ if (!requestProcessingData.isEmpty()) {
+ request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData));
+ }
+ requestList.setRequest(request);
+ requestLists.add(requestList);
+ }
+
+ orchestrationList.setRequestList(requestLists);
+ return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
+ }
+
+
+ @POST
+ @Path("/{version: [vV][4-7]}/{requestId}/unlock")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Unlock Orchestrated Requests for a given requestId", response = Response.class)
+ @Transactional
+ public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId,
+ @PathParam("version") String version) throws ApiException {
+
+ long startTime = System.currentTimeMillis();
+ logger.debug("requestId is: {}", requestId);
+ ServiceInstancesRequest sir = null;
+
+ InfraActiveRequests infraActiveRequest = null;
+ Request request = null;
+
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class);
+ } catch (IOException e) {
+ logger.error("Exception occurred", e);
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
throw validateException;
- }
- try{
- msoRequest.parseOrchestration(sir);
- } catch (Exception e) {
- logger.error("Exception occurred", e);
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build();
- ValidateException validateException = new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
+ }
+ try {
+ msoRequest.parseOrchestration(sir);
+ } catch (Exception e) {
+ logger.error("Exception occurred", e);
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+ ValidateException validateException =
+ new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
+ throw validateException;
+ }
+
+ infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
+ if (infraActiveRequest == null) {
+ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,
+ ErrorCode.BusinessProcesssError).build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder("Null response from RequestDB when searching by RequestId",
+ HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo)
+ .build();
+
throw validateException;
- }
-
- infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
- if(infraActiveRequest == null) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.BusinessProcesssError).build();
-
-
- ValidateException validateException = new ValidateException.Builder("Null response from RequestDB when searching by RequestId",
- HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
-
- throw validateException;
-
- }else{
- String status = infraActiveRequest.getRequestStatus();
- if(status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING") || status.equalsIgnoreCase("PENDING_MANUAL_TASK")){
- infraActiveRequest.setRequestStatus("UNLOCKED");
- infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
- infraActiveRequest.setRequestId(requestId);
- requestsDbClient.save(infraActiveRequest);
- }else{
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError).build();
-
-
- ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " has a status of " + status + " and can not be unlocked",
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
-
- throw validateException;
- }
- }
- return Response.status (HttpStatus.SC_NO_CONTENT).entity ("").build ();
- }
-
- private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException{
-
- String requestBody = iar.getRequestBody();
- Request request = new Request();
-
- ObjectMapper mapper = new ObjectMapper();
-
- request.setRequestId(iar.getRequestId());
- request.setRequestScope(iar.getRequestScope());
- request.setRequestType(iar.getRequestAction());
- String rollbackStatusMessage = iar.getRollbackStatusMessage();
- String flowStatusMessage = iar.getFlowStatus();
- String retryStatusMessage = iar.getRetryStatusMessage();
-
-
- InstanceReferences ir = new InstanceReferences();
- if(iar.getNetworkId() != null)
- ir.setNetworkInstanceId(iar.getNetworkId());
- if(iar.getNetworkName() != null)
- ir.setNetworkInstanceName(iar.getNetworkName());
- if(iar.getServiceInstanceId() != null)
- ir.setServiceInstanceId(iar.getServiceInstanceId());
- if(iar.getServiceInstanceName() != null)
- ir.setServiceInstanceName(iar.getServiceInstanceName());
- if(iar.getVfModuleId() != null)
- ir.setVfModuleInstanceId(iar.getVfModuleId());
- if(iar.getVfModuleName() != null)
- ir.setVfModuleInstanceName(iar.getVfModuleName());
- if(iar.getVnfId() != null)
- ir.setVnfInstanceId(iar.getVnfId());
- if(iar.getVnfName() != null)
- ir.setVnfInstanceName(iar.getVnfName());
- if(iar.getVolumeGroupId() != null)
- ir.setVolumeGroupInstanceId(iar.getVolumeGroupId());
- if(iar.getVolumeGroupName() != null)
- ir.setVolumeGroupInstanceName(iar.getVolumeGroupName());
- if(iar.getRequestorId() != null)
- ir.setRequestorId(iar.getRequestorId());
- if(iar.getInstanceGroupId() != null)
- ir.setInstanceGroupId(iar.getInstanceGroupId());
- if(iar.getInstanceGroupName() != null)
- ir.setInstanceGroupName(iar.getInstanceGroupName());
-
-
-
- request.setInstanceReferences(ir);
-
- RequestDetails requestDetails = null;
-
- if(StringUtils.isNotBlank(requestBody)) {
- try {
- if(requestBody.contains("\"requestDetails\":")){
- ServiceInstancesRequest sir = mapper.readValue(requestBody, ServiceInstancesRequest.class);
- requestDetails = sir.getRequestDetails();
- } else {
- requestDetails = mapper.readValue(requestBody, RequestDetails.class);
- }
- } catch (IOException e) {
- logger.error("Exception occurred", e);
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build();
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed : ",
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
-
- throw validateException;
- }
- }
- request.setRequestDetails(requestDetails);
-
- if(iar.getStartTime() != null) {
- String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT";
- request.setStartTime(startTimeStamp);
- }
- if(iar.getEndTime() != null){
- String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT";
- request.setFinishTime(endTimeStamp);
- }
- String statusMessages = null;
- RequestStatus status = new RequestStatus();
- if(iar.getStatusMessage() != null){
- statusMessages = "STATUS: " + iar.getStatusMessage();
- }
- if(flowStatusMessage != null){
- if(statusMessages != null){
- statusMessages = statusMessages + " " + "FLOW STATUS: " + flowStatusMessage;
- }else{
- statusMessages = "FLOW STATUS: " + flowStatusMessage;
- }
- }
- if(retryStatusMessage != null){
- if(statusMessages != null){
- statusMessages = statusMessages + " " + "RETRY STATUS: " + retryStatusMessage;
- }else{
- statusMessages = "RETRY STATUS: " + retryStatusMessage;
- }
- }
- if(rollbackStatusMessage != null){
- if(statusMessages != null){
- statusMessages = statusMessages + " " + "ROLLBACK STATUS: " + rollbackStatusMessage;
- }else{
- statusMessages = "ROLLBACK STATUS: " + rollbackStatusMessage;
- }
- }
- if(statusMessages != null){
- status.setStatusMessage(statusMessages);
- }
- if(iar.getModifyTime() != null){
- String timeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getModifyTime()) + " GMT";
- status.setTimeStamp(timeStamp);
- }
-
-
- if(iar.getRequestStatus() != null){
- status.setRequestState(iar.getRequestStatus());
- }
-
- if(iar.getProgress() != null){
- status.setPercentProgress(iar.getProgress().intValue());
- }
-
- request.setRequestStatus(status);
-
- return request;
- }
-
- public List<org.onap.so.serviceinstancebeans.RequestProcessingData> mapRequestProcessingData(List<org.onap.so.db.request.beans.RequestProcessingData> processingData){
- List<org.onap.so.serviceinstancebeans.RequestProcessingData> addedRequestProcessingData = new ArrayList<>();
- org.onap.so.serviceinstancebeans.RequestProcessingData finalProcessingData = new org.onap.so.serviceinstancebeans.RequestProcessingData();
- String currentGroupingId = null;
- HashMap<String, String> tempMap = new HashMap<>();
- List<HashMap<String, String>> tempList = new ArrayList<>();
- for(RequestProcessingData data : processingData){
- String groupingId = data.getGroupingId();
- String tag = data.getTag();
- if(currentGroupingId == null || !currentGroupingId.equals(groupingId)){
- if(!tempMap.isEmpty()){
- tempList.add(tempMap);
- finalProcessingData.setDataPairs(tempList);
- addedRequestProcessingData.add(finalProcessingData);
- }
- finalProcessingData = new org.onap.so.serviceinstancebeans.RequestProcessingData();
- if(groupingId != null){
- finalProcessingData.setGroupingId(groupingId);
- }
- if(tag != null){
- finalProcessingData.setTag(tag);
- }
- currentGroupingId = groupingId;
- tempMap = new HashMap<>();
- tempList = new ArrayList<>();
- if(data.getName() != null && data.getValue() != null){
- tempMap.put(data.getName(), data.getValue());
- }
- }else{
- if(data.getName() != null && data.getValue() != null){
- tempMap.put(data.getName(), data.getValue());
- }
- }
- }
- if(tempMap.size() > 0){
- tempList.add(tempMap);
- finalProcessingData.setDataPairs(tempList);
- }
- addedRequestProcessingData.add(finalProcessingData);
- return addedRequestProcessingData;
- }
- }
+
+ } else {
+ String status = infraActiveRequest.getRequestStatus();
+ if (status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING")
+ || status.equalsIgnoreCase("PENDING_MANUAL_TASK")) {
+ infraActiveRequest.setRequestStatus("UNLOCKED");
+ infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ infraActiveRequest.setRequestId(requestId);
+ requestsDbClient.save(infraActiveRequest);
+ } else {
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
+ .build();
+
+
+ ValidateException validateException = new ValidateException.Builder(
+ "Orchestration RequestId " + requestId + " has a status of " + status
+ + " and can not be unlocked",
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo)
+ .build();
+
+ throw validateException;
+ }
+ }
+ return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build();
+ }
+
+ private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException {
+
+ String requestBody = iar.getRequestBody();
+ Request request = new Request();
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ request.setRequestId(iar.getRequestId());
+ request.setRequestScope(iar.getRequestScope());
+ request.setRequestType(iar.getRequestAction());
+ String rollbackStatusMessage = iar.getRollbackStatusMessage();
+ String flowStatusMessage = iar.getFlowStatus();
+ String retryStatusMessage = iar.getRetryStatusMessage();
+
+
+ InstanceReferences ir = new InstanceReferences();
+ if (iar.getNetworkId() != null)
+ ir.setNetworkInstanceId(iar.getNetworkId());
+ if (iar.getNetworkName() != null)
+ ir.setNetworkInstanceName(iar.getNetworkName());
+ if (iar.getServiceInstanceId() != null)
+ ir.setServiceInstanceId(iar.getServiceInstanceId());
+ if (iar.getServiceInstanceName() != null)
+ ir.setServiceInstanceName(iar.getServiceInstanceName());
+ if (iar.getVfModuleId() != null)
+ ir.setVfModuleInstanceId(iar.getVfModuleId());
+ if (iar.getVfModuleName() != null)
+ ir.setVfModuleInstanceName(iar.getVfModuleName());
+ if (iar.getVnfId() != null)
+ ir.setVnfInstanceId(iar.getVnfId());
+ if (iar.getVnfName() != null)
+ ir.setVnfInstanceName(iar.getVnfName());
+ if (iar.getVolumeGroupId() != null)
+ ir.setVolumeGroupInstanceId(iar.getVolumeGroupId());
+ if (iar.getVolumeGroupName() != null)
+ ir.setVolumeGroupInstanceName(iar.getVolumeGroupName());
+ if (iar.getRequestorId() != null)
+ ir.setRequestorId(iar.getRequestorId());
+ if (iar.getInstanceGroupId() != null)
+ ir.setInstanceGroupId(iar.getInstanceGroupId());
+ if (iar.getInstanceGroupName() != null)
+ ir.setInstanceGroupName(iar.getInstanceGroupName());
+
+
+
+ request.setInstanceReferences(ir);
+
+ RequestDetails requestDetails = null;
+
+ if (StringUtils.isNotBlank(requestBody)) {
+ try {
+ if (requestBody.contains("\"requestDetails\":")) {
+ ServiceInstancesRequest sir = mapper.readValue(requestBody, ServiceInstancesRequest.class);
+ requestDetails = sir.getRequestDetails();
+ } else {
+ requestDetails = mapper.readValue(requestBody, RequestDetails.class);
+ }
+ } catch (IOException e) {
+ logger.error("Exception occurred", e);
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON object failed : ",
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+
+ throw validateException;
+ }
+ }
+ request.setRequestDetails(requestDetails);
+
+ if (iar.getStartTime() != null) {
+ String startTimeStamp =
+ new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT";
+ request.setStartTime(startTimeStamp);
+ }
+ if (iar.getEndTime() != null) {
+ String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT";
+ request.setFinishTime(endTimeStamp);
+ }
+ String statusMessages = null;
+ RequestStatus status = new RequestStatus();
+ if (iar.getStatusMessage() != null) {
+ statusMessages = "STATUS: " + iar.getStatusMessage();
+ }
+ if (flowStatusMessage != null) {
+ if (statusMessages != null) {
+ statusMessages = statusMessages + " " + "FLOW STATUS: " + flowStatusMessage;
+ } else {
+ statusMessages = "FLOW STATUS: " + flowStatusMessage;
+ }
+ }
+ if (retryStatusMessage != null) {
+ if (statusMessages != null) {
+ statusMessages = statusMessages + " " + "RETRY STATUS: " + retryStatusMessage;
+ } else {
+ statusMessages = "RETRY STATUS: " + retryStatusMessage;
+ }
+ }
+ if (rollbackStatusMessage != null) {
+ if (statusMessages != null) {
+ statusMessages = statusMessages + " " + "ROLLBACK STATUS: " + rollbackStatusMessage;
+ } else {
+ statusMessages = "ROLLBACK STATUS: " + rollbackStatusMessage;
+ }
+ }
+ if (statusMessages != null) {
+ status.setStatusMessage(statusMessages);
+ }
+ if (iar.getModifyTime() != null) {
+ String timeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getModifyTime()) + " GMT";
+ status.setTimeStamp(timeStamp);
+ }
+
+
+ if (iar.getRequestStatus() != null) {
+ status.setRequestState(iar.getRequestStatus());
+ }
+
+ if (iar.getProgress() != null) {
+ status.setPercentProgress(iar.getProgress().intValue());
+ }
+
+ request.setRequestStatus(status);
+
+ return request;
+ }
+
+ public List<org.onap.so.serviceinstancebeans.RequestProcessingData> mapRequestProcessingData(
+ List<org.onap.so.db.request.beans.RequestProcessingData> processingData) {
+ List<org.onap.so.serviceinstancebeans.RequestProcessingData> addedRequestProcessingData = new ArrayList<>();
+ org.onap.so.serviceinstancebeans.RequestProcessingData finalProcessingData =
+ new org.onap.so.serviceinstancebeans.RequestProcessingData();
+ String currentGroupingId = null;
+ HashMap<String, String> tempMap = new HashMap<>();
+ List<HashMap<String, String>> tempList = new ArrayList<>();
+ for (RequestProcessingData data : processingData) {
+ String groupingId = data.getGroupingId();
+ String tag = data.getTag();
+ if (currentGroupingId == null || !currentGroupingId.equals(groupingId)) {
+ if (!tempMap.isEmpty()) {
+ tempList.add(tempMap);
+ finalProcessingData.setDataPairs(tempList);
+ addedRequestProcessingData.add(finalProcessingData);
+ }
+ finalProcessingData = new org.onap.so.serviceinstancebeans.RequestProcessingData();
+ if (groupingId != null) {
+ finalProcessingData.setGroupingId(groupingId);
+ }
+ if (tag != null) {
+ finalProcessingData.setTag(tag);
+ }
+ currentGroupingId = groupingId;
+ tempMap = new HashMap<>();
+ tempList = new ArrayList<>();
+ if (data.getName() != null && data.getValue() != null) {
+ tempMap.put(data.getName(), data.getValue());
+ }
+ } else {
+ if (data.getName() != null && data.getValue() != null) {
+ tempMap.put(data.getName(), data.getValue());
+ }
+ }
+ }
+ if (tempMap.size() > 0) {
+ tempList.add(tempMap);
+ finalProcessingData.setDataPairs(tempList);
+ }
+ addedRequestProcessingData.add(finalProcessingData);
+ return addedRequestProcessingData;
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RecipeLookupResult.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RecipeLookupResult.java
index 83d270552d..8f7403a7f9 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RecipeLookupResult.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RecipeLookupResult.java
@@ -27,35 +27,35 @@ public class RecipeLookupResult {
private int recipeTimeout;
// the service recipe param.
private String recipeParamXsd;
-
+
public RecipeLookupResult(String orchestrationURI, int recipeTimeout) {
- this.orchestrationURI = orchestrationURI;
- this.recipeTimeout = recipeTimeout;
+ this.orchestrationURI = orchestrationURI;
+ this.recipeTimeout = recipeTimeout;
}
-
+
public RecipeLookupResult(String orchestrationURI, int recipeTimeout, String recipeParamXsd) {
this.orchestrationURI = orchestrationURI;
this.recipeTimeout = recipeTimeout;
this.recipeParamXsd = recipeParamXsd;
}
-
- public String getOrchestrationURI () {
- return orchestrationURI;
+
+ public String getOrchestrationURI() {
+ return orchestrationURI;
}
-
- public void setOrchestrationURI (String orchestrationURI) {
- this.orchestrationURI = orchestrationURI;
+
+ public void setOrchestrationURI(String orchestrationURI) {
+ this.orchestrationURI = orchestrationURI;
}
-
- public int getRecipeTimeout () {
- return recipeTimeout;
+
+ public int getRecipeTimeout() {
+ return recipeTimeout;
}
-
- public void setRecipeTimeout (int recipeTimeout) {
- this.recipeTimeout = recipeTimeout;
+
+ public void setRecipeTimeout(int recipeTimeout) {
+ this.recipeTimeout = recipeTimeout;
}
-
+
/**
* @return Returns the recipeParamXsd.
*/
@@ -63,14 +63,14 @@ public class RecipeLookupResult {
return recipeParamXsd;
}
-
+
/**
* @param recipeParamXsd The recipeParamXsd to set.
*/
public void setRecipeParamXsd(String recipeParamXsd) {
this.recipeParamXsd = recipeParamXsd;
}
-
-
+
+
}
-
+
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestActionMap.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestActionMap.java
index 86dd048120..c97c80901e 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestActionMap.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestActionMap.java
@@ -25,7 +25,7 @@ import java.util.Map;
/*
* Map of actions to RequestActions
-*/
+ */
public class RequestActionMap {
private static final Map<String, String> actionMap;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java
index c02b40aeca..bbcc120ab6 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java
@@ -26,7 +26,6 @@ package org.onap.so.apihandlerinfra;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
-
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
@@ -77,14 +76,11 @@ import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
-
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.xml.bind.DatatypeConverter;
-
import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID;
-
import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;
@@ -98,470 +94,532 @@ import java.util.Optional;
@Component
public class RequestHandlerUtils {
- private static Logger logger = LoggerFactory.getLogger(RequestHandlerUtils.class);
-
- private static final String SAVE_TO_DB = "save instance to db";
-
- @Autowired
- private Environment env;
-
- @Autowired
- private RequestClientFactory reqClientFactory;
-
- @Autowired
- private RequestsDbClient infraActiveRequestsClient;
-
- @Autowired
- private ResponseBuilder builder;
-
- @Autowired
- private MsoRequest msoRequest;
-
- @Autowired
- private RestTemplate restTemplate;
-
- @Autowired
- private CatalogDbClient catalogDbClient;
-
- public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter, String orchestrationUri, String requestScope)throws ApiException {
- RequestClient requestClient = null;
- HttpResponse response = null;
- try {
- requestClient = reqClientFactory.getRequestClient (orchestrationUri);
- response = requestClient.post(requestClientParameter);
- } catch (Exception e) {
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ private static Logger logger = LoggerFactory.getLogger(RequestHandlerUtils.class);
+
+ private static final String SAVE_TO_DB = "save instance to db";
+
+ @Autowired
+ private Environment env;
+
+ @Autowired
+ private RequestClientFactory reqClientFactory;
+
+ @Autowired
+ private RequestsDbClient infraActiveRequestsClient;
+
+ @Autowired
+ private ResponseBuilder builder;
+
+ @Autowired
+ private MsoRequest msoRequest;
+
+ @Autowired
+ private RestTemplate restTemplate;
+
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+
+ public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter,
+ String orchestrationUri, String requestScope) throws ApiException {
+ RequestClient requestClient = null;
+ HttpResponse response = null;
+ try {
+ requestClient = reqClientFactory.getRequestClient(orchestrationUri);
+ response = requestClient.post(requestClientParameter);
+ } catch (Exception e) {
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
String url = requestClient != null ? requestClient.getUrl() : "";
- ClientConnectionException clientException = new ClientConnectionException.Builder(url, HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build();
+ ClientConnectionException clientException =
+ new ClientConnectionException.Builder(url, HttpStatus.SC_BAD_GATEWAY,
+ ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build();
updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage());
throw clientException;
- }
+ }
+
+ if (response == null) {
- if (response == null) {
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ClientConnectionException clientException = new ClientConnectionException.Builder(requestClient.getUrl(), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
+ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
+ ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ClientConnectionException clientException = new ClientConnectionException.Builder(requestClient.getUrl(),
+ HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage());
throw clientException;
- }
+ }
- ResponseHandler respHandler = null;
+ ResponseHandler respHandler = null;
int bpelStatus = 500;
try {
- respHandler = new ResponseHandler (response, requestClient.getType ());
- bpelStatus = respHandler.getStatus ();
+ respHandler = new ResponseHandler(response, requestClient.getType());
+ bpelStatus = respHandler.getStatus();
} catch (ApiException e) {
logger.error("Exception occurred", e);
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ValidateException validateException = new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ValidateException validateException =
+ new ValidateException.Builder("Exception caught mapping Camunda JSON response to object",
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
+ throw validateException;
+ }
+
+ // BPEL accepted the request, the request is in progress
+ if (bpelStatus == HttpStatus.SC_ACCEPTED) {
+ ServiceInstancesResponse jsonResponse;
+ CamundaResponse camundaResp = respHandler.getResponse();
+
+ if ("Success".equalsIgnoreCase(camundaResp.getMessage())) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class);
+ jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId());
+ Optional<URL> selfLinkUrl = msoRequest.buildSelfLinkUrl(currentActiveReq.getRequestUrl(),
+ requestClientParameter.getRequestId());
+ if (selfLinkUrl.isPresent()) {
+ jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get());
+ } else {
+ jsonResponse.getRequestReferences().setRequestSelfLink(null);
+ }
+ } catch (IOException e) {
+ logger.error("Exception occurred", e);
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ValidateException validateException =
+ new ValidateException.Builder("Exception caught mapping Camunda JSON response to object",
+ HttpStatus.SC_NOT_ACCEPTABLE, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
+ throw validateException;
+ }
+ return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(),
+ jsonResponse, requestClientParameter.getApiVersion());
+ }
+ }
+
+ List<String> variables = new ArrayList<>();
+ variables.add(bpelStatus + "");
+ String camundaJSONResponseBody = respHandler.getResponseBody();
+ if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) {
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError)
+ .errorSource(requestClient.getUrl()).build();
+ BPMNFailureException bpmnException =
+ new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+
+ updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage());
+
+ throw bpmnException;
+ } else {
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError)
+ .errorSource(requestClient.getUrl()).build();
+
+
+ BPMNFailureException servException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
+ bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+ updateStatus(currentActiveReq, Status.FAILED, servException.getMessage());
+
+ throw servException;
+ }
+ }
+
+ public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage)
+ throws RequestDbFailureException {
+ if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
+ aq.setStatusMessage(errorMessage);
+ aq.setProgress(new Long(100));
+ aq.setRequestStatus(status.toString());
+ Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
+ aq.setEndTime(endTimeStamp);
+ try {
+ infraActiveRequestsClient.save(aq);
+ } catch (Exception e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(),
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ }
+ }
+ }
+
+ public String deriveRequestScope(Actions action, ServiceInstancesRequest sir, String requestUri) {
+ if (action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig) {
+ return (ModelType.vnf.name());
+ } else if (action == Action.addMembers || action == Action.removeMembers) {
+ return (ModelType.instanceGroup.toString());
+ } else {
+ String requestScope;
+ if (sir.getRequestDetails().getModelInfo().getModelType() == null) {
+ requestScope = requestScopeFromUri(requestUri);
+ } else {
+ requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
+ }
+ return requestScope;
+ }
+ }
+
+
+ public void validateHeaders(ContainerRequestContext context) throws ValidationException {
+ MultivaluedMap<String, String> headers = context.getHeaders();
+ if (!headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID)) {
+ throw new ValidationException(ONAPLogConstants.Headers.REQUEST_ID + " header", true);
+ }
+ if (!headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME)) {
+ throw new ValidationException(ONAPLogConstants.Headers.PARTNER_NAME + " header", true);
+ }
+ if (!headers.containsKey(REQUESTOR_ID)) {
+ throw new ValidationException(REQUESTOR_ID + " header", true);
+ }
+ }
+
+ public String getRequestUri(ContainerRequestContext context, String uriPrefix) {
+ String requestUri = context.getUriInfo().getPath();
+ String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri);
+ MDC.put(LogConstants.HTTP_URL, httpUrl);
+ requestUri = requestUri.substring(requestUri.indexOf(uriPrefix) + uriPrefix.length());
+ return requestUri;
+ }
+
+ public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime,
+ MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq)
+ throws ApiException {
+ InfraActiveRequests dup = null;
+ try {
+ if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance
+ || action == Action.activateInstance || action == Action.assignInstance))) {
+ dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope);
+ }
+ } catch (Exception e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ RequestDbFailureException requestDbFailureException =
+ new RequestDbFailureException.Builder("check for duplicate instance", e.toString(),
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage());
+ throw requestDbFailureException;
+ }
+ return dup;
+ }
+
+ public boolean camundaHistoryCheck(InfraActiveRequests duplicateRecord, InfraActiveRequests currentActiveReq)
+ throws RequestDbFailureException, ContactCamundaException {
+ String requestId = duplicateRecord.getRequestId();
+ String path = env.getProperty("mso.camunda.rest.history.uri") + requestId;
+ String targetUrl = env.getProperty("mso.camundaURL") + path;
+ HttpHeaders headers =
+ setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey"));
+ HttpEntity<?> requestEntity = new HttpEntity<>(headers);
+ ResponseEntity<List<HistoricProcessInstanceEntity>> response = null;
+ try {
+ response = restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity,
+ new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {});
+ } catch (HttpStatusCodeException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ContactCamundaException contactCamundaException =
+ new ContactCamundaException.Builder(requestId, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
+ updateStatus(currentActiveReq, Status.FAILED, contactCamundaException.getMessage());
+ throw contactCamundaException;
+ }
+ if (response.getBody().isEmpty()) {
+ updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed");
+ }
+ for (HistoricProcessInstance instance : response.getBody()) {
+ if (instance.getState().equals("ACTIVE")) {
+ return true;
+ } else {
+ updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed");
+ }
+ }
+ return false;
+ }
+
+ protected HttpHeaders setCamundaHeaders(String auth, String msoKey) {
+ HttpHeaders headers = new HttpHeaders();
+ List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>();
+ acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON);
+ headers.setAccept(acceptableMediaTypes);
+ try {
+ String userCredentials = CryptoUtils.decrypt(auth, msoKey);
+ if (userCredentials != null) {
+ headers.add(HttpHeaders.AUTHORIZATION,
+ "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()));
+ }
+ } catch (GeneralSecurityException e) {
+ logger.error("Security exception", e);
+ }
+ return headers;
+ }
+
+ public ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action,
+ long startTime, ServiceInstancesRequest sir, MsoRequest msoRequest, String requestId, String requestUri)
+ throws ApiException {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ return mapper.readValue(requestJSON, ServiceInstancesRequest.class);
+
+ } catch (IOException e) {
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+ ValidateException validateException =
+ new ValidateException.Builder("Error mapping request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
+ String requestScope = requestScopeFromUri(requestUri);
+
+ msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action,
+ requestScope, requestJSON);
+
+ throw validateException;
+ }
+ }
+
+ public void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action,
+ String version, String requestJSON, Boolean aLaCarte, String requestId,
+ InfraActiveRequests currentActiveReq) throws ValidateException, RequestDbFailureException {
+ int reqVersion = Integer.parseInt(version.substring(1));
+ try {
+ msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte);
+ } catch (Exception e) {
+ logger.error("failed to parse request", e);
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ValidateException validateException =
+ new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
+
updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
+
throw validateException;
}
+ }
+
+ public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action,
+ HashMap<String, String> instanceIdMap, long startTime, MsoRequest msoRequest, String instanceName,
+ String requestScope, InfraActiveRequests dup) throws ApiException {
+
+ String instance = null;
+ if (instanceName != null) {
+ instance = instanceName;
+ } else {
+ instance = instanceIdMap.get(requestScope + "InstanceId");
+ }
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+ DuplicateRequestException dupException =
+ new DuplicateRequestException.Builder(requestScope, instance, dup.getRequestStatus(),
+ dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
+ .errorInfo(errorLoggerInfo).build();
+
+ updateStatus(currentActiveReq, Status.FAILED, dupException.getMessage());
+
+ throw dupException;
+ }
+
+ public String getRequestId(ContainerRequestContext requestContext) throws ValidateException {
+ String requestId = null;
+ if (requestContext.getProperty("requestId") != null) {
+ requestId = requestContext.getProperty("requestId").toString();
+ }
+ if (UUIDChecker.isValidUUID(requestId)) {
+ return requestId;
+ } else {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ValidateException validateException =
+ new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID",
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER)
+ .errorInfo(errorLoggerInfo).build();
+
+ throw validateException;
+ }
+ }
+
+ public void setInstanceId(InfraActiveRequests currentActiveReq, String requestScope, String instanceId,
+ Map<String, String> instanceIdMap) {
+ if (StringUtils.isNotBlank(instanceId)) {
+ if (ModelType.service.name().equalsIgnoreCase(requestScope)) {
+ currentActiveReq.setServiceInstanceId(instanceId);
+ } else if (ModelType.vnf.name().equalsIgnoreCase(requestScope)) {
+ currentActiveReq.setVnfId(instanceId);
+ } else if (ModelType.vfModule.name().equalsIgnoreCase(requestScope)) {
+ currentActiveReq.setVfModuleId(instanceId);
+ } else if (ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)) {
+ currentActiveReq.setVolumeGroupId(instanceId);
+ } else if (ModelType.network.name().equalsIgnoreCase(requestScope)) {
+ currentActiveReq.setNetworkId(instanceId);
+ } else if (ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
+ currentActiveReq.setConfigurationId(instanceId);
+ } else if (ModelType.instanceGroup.toString().equalsIgnoreCase(requestScope)) {
+ currentActiveReq.setInstanceGroupId(instanceId);
+ }
+ } else if (instanceIdMap != null && !instanceIdMap.isEmpty()) {
+ if (instanceIdMap.get("serviceInstanceId") != null) {
+ currentActiveReq.setServiceInstanceId(instanceIdMap.get("serviceInstanceId"));
+ }
+ if (instanceIdMap.get("vnfInstanceId") != null) {
+ currentActiveReq.setVnfId(instanceIdMap.get("vnfInstanceId"));
+ }
+ if (instanceIdMap.get("vfModuleInstanceId") != null) {
+ currentActiveReq.setVfModuleId(instanceIdMap.get("vfModuleInstanceId"));
+ }
+ if (instanceIdMap.get("volumeGroupInstanceId") != null) {
+ currentActiveReq.setVolumeGroupId(instanceIdMap.get("volumeGroupInstanceId"));
+ }
+ if (instanceIdMap.get("networkInstanceId") != null) {
+ currentActiveReq.setNetworkId(instanceIdMap.get("networkInstanceId"));
+ }
+ if (instanceIdMap.get("configurationInstanceId") != null) {
+ currentActiveReq.setConfigurationId(instanceIdMap.get("configurationInstanceId"));
+ }
+ if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) {
+ currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID));
+ }
+ }
+ }
+
+ public String mapJSONtoMSOStyle(String msoRawRequest, ServiceInstancesRequest serviceInstRequest,
+ boolean isAlaCarte, Actions action) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(Include.NON_NULL);
+ if (msoRawRequest != null) {
+ ServiceInstancesRequest sir = mapper.readValue(msoRawRequest, ServiceInstancesRequest.class);
+ if (serviceInstRequest != null && serviceInstRequest.getRequestDetails() != null
+ && serviceInstRequest.getRequestDetails().getRequestParameters() != null) {
+ if (!isAlaCarte && Action.createInstance.equals(action)) {
+ sir.getRequestDetails()
+ .setCloudConfiguration(serviceInstRequest.getRequestDetails().getCloudConfiguration());
+ sir.getRequestDetails().getRequestParameters().setUserParams(
+ serviceInstRequest.getRequestDetails().getRequestParameters().getUserParams());
+ }
+ sir.getRequestDetails().getRequestParameters()
+ .setUsePreload(serviceInstRequest.getRequestDetails().getRequestParameters().getUsePreload());
+ }
+
+ logger.debug("Value as string: {}", mapper.writeValueAsString(sir));
+ return mapper.writeValueAsString(sir);
+ }
+ return null;
+ }
+
+ public Optional<String> retrieveModelName(RequestParameters requestParams) {
+ String requestTestApi = null;
+ TestApi testApi = null;
+
+ if (requestParams != null) {
+ requestTestApi = requestParams.getTestApi();
+ }
+
+ if (requestTestApi == null) {
+ if (requestParams != null && requestParams.getALaCarte() != null && !requestParams.getALaCarte()) {
+ requestTestApi = env.getProperty(CommonConstants.MACRO_TEST_API);
+ } else {
+ requestTestApi = env.getProperty(CommonConstants.ALACARTE_TEST_API);
+ }
+ }
+
+ try {
+ testApi = TestApi.valueOf(requestTestApi);
+ return Optional.of(testApi.getModelName());
+ } catch (Exception e) {
+ logger.warn("Catching the exception on the valueOf enum call and continuing", e);
+ throw new IllegalArgumentException("Invalid TestApi is provided", e);
+ }
+ }
+
+ public String getDefaultModel(ServiceInstancesRequest sir) {
+ String defaultModel = sir.getRequestDetails().getRequestInfo().getSource() + "_DEFAULT";
+ Optional<String> oModelName = retrieveModelName(sir.getRequestDetails().getRequestParameters());
+ if (oModelName.isPresent()) {
+ defaultModel = oModelName.get();
+ }
+ return defaultModel;
+ }
+
+ public String getServiceType(String requestScope, ServiceInstancesRequest sir, Boolean aLaCarteFlag) {
+ String serviceType = null;
+ if (requestScope.equalsIgnoreCase(ModelType.service.toString())) {
+ String defaultServiceModelName = getDefaultModel(sir);
+ org.onap.so.db.catalog.beans.Service serviceRecord;
+ if (aLaCarteFlag) {
+ serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
+ if (serviceRecord != null) {
+ serviceType = serviceRecord.getServiceType();
+ }
+ } else {
+ serviceRecord =
+ catalogDbClient.getServiceByID(sir.getRequestDetails().getModelInfo().getModelVersionId());
+ if (serviceRecord != null) {
+ serviceType = serviceRecord.getServiceType();
+ } else {
+ serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
+ if (serviceRecord != null) {
+ serviceType = serviceRecord.getServiceType();
+ }
+ }
+ }
+ } else {
+ serviceType = msoRequest.getServiceInstanceType(sir, requestScope);
+ }
+ return serviceType;
+ }
+
+ protected String setServiceInstanceId(String requestScope, ServiceInstancesRequest sir) {
+ if (sir.getServiceInstanceId() != null) {
+ return sir.getServiceInstanceId();
+ } else if (requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) {
+ RelatedInstanceList[] relatedInstances = sir.getRequestDetails().getRelatedInstanceList();
+ if (relatedInstances != null) {
+ for (RelatedInstanceList relatedInstanceList : relatedInstances) {
+ RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
+ if (relatedInstance.getModelInfo().getModelType() == ModelType.service) {
+ return relatedInstance.getInstanceId();
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ private String requestScopeFromUri(String requestUri) {
+ String requestScope;
+ if (requestUri.contains(ModelType.network.name())) {
+ requestScope = ModelType.network.name();
+ } else if (requestUri.contains(ModelType.vfModule.name())) {
+ requestScope = ModelType.vfModule.name();
+ } else if (requestUri.contains(ModelType.volumeGroup.name())) {
+ requestScope = ModelType.volumeGroup.name();
+ } else if (requestUri.contains(ModelType.configuration.name())) {
+ requestScope = ModelType.configuration.name();
+ } else if (requestUri.contains(ModelType.vnf.name())) {
+ requestScope = ModelType.vnf.name();
+ } else {
+ requestScope = ModelType.service.name();
+ }
+ return requestScope;
+ }
- // BPEL accepted the request, the request is in progress
- if (bpelStatus == HttpStatus.SC_ACCEPTED) {
- ServiceInstancesResponse jsonResponse;
- CamundaResponse camundaResp = respHandler.getResponse();
-
- if("Success".equalsIgnoreCase(camundaResp.getMessage())) {
- try {
- ObjectMapper mapper = new ObjectMapper();
- jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class);
- jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId());
- Optional<URL> selfLinkUrl = msoRequest.buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId());
- if(selfLinkUrl.isPresent()){
- jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get());
- } else {
- jsonResponse.getRequestReferences().setRequestSelfLink(null);
- }
- } catch (IOException e) {
- logger.error("Exception occurred", e);
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ValidateException validateException = new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", HttpStatus.SC_NOT_ACCEPTABLE, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
- updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
- throw validateException;
- }
- return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(), jsonResponse, requestClientParameter.getApiVersion());
- }
- }
-
- List<String> variables = new ArrayList<>();
- variables.add(bpelStatus + "");
- String camundaJSONResponseBody = respHandler.getResponseBody ();
- if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty ()) {
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).errorSource(requestClient.getUrl()).build();
- BPMNFailureException bpmnException = new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
- .errorInfo(errorLoggerInfo).build();
-
- updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage());
-
- throw bpmnException;
- } else {
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).errorSource(requestClient.getUrl()).build();
-
-
- BPMNFailureException servException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
- .errorInfo(errorLoggerInfo).build();
- updateStatus(currentActiveReq, Status.FAILED, servException.getMessage());
-
- throw servException;
- }
- }
-
- public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage) throws RequestDbFailureException{
- if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
- aq.setStatusMessage (errorMessage);
- aq.setProgress(new Long(100));
- aq.setRequestStatus(status.toString());
- Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis());
- aq.setEndTime (endTimeStamp);
- try{
- infraActiveRequestsClient.save(aq);
- }catch(Exception e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
- .errorInfo(errorLoggerInfo).build();
- }
- }
- }
-
- public String deriveRequestScope(Actions action, ServiceInstancesRequest sir, String requestUri) {
- if(action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig){
- return (ModelType.vnf.name());
- }else if(action == Action.addMembers || action == Action.removeMembers){
- return(ModelType.instanceGroup.toString());
- }else{
- String requestScope;
- if(sir.getRequestDetails().getModelInfo().getModelType() == null){
- requestScope = requestScopeFromUri(requestUri);
- }else{
- requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
- }
- return requestScope;
- }
- }
-
-
- public void validateHeaders(ContainerRequestContext context) throws ValidationException{
- MultivaluedMap<String, String> headers = context.getHeaders();
- if(!headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID)){
- throw new ValidationException(ONAPLogConstants.Headers.REQUEST_ID + " header", true);
- }
- if(!headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME)){
- throw new ValidationException(ONAPLogConstants.Headers.PARTNER_NAME + " header", true);
- }
- if(!headers.containsKey(REQUESTOR_ID)){
- throw new ValidationException(REQUESTOR_ID + " header", true);
- }
- }
-
- public String getRequestUri(ContainerRequestContext context, String uriPrefix){
- String requestUri = context.getUriInfo().getPath();
- String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri);
- MDC.put(LogConstants.HTTP_URL, httpUrl);
- requestUri = requestUri.substring(requestUri.indexOf(uriPrefix) + uriPrefix.length());
- return requestUri;
- }
-
- public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime,
- MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
- InfraActiveRequests dup = null;
- try {
- if(!(instanceName==null && requestScope.equals("service") && (action == Action.createInstance || action == Action.activateInstance || action == Action.assignInstance))){
- dup = infraActiveRequestsClient.checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope);
- }
- } catch (Exception e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- RequestDbFailureException requestDbFailureException = new RequestDbFailureException.Builder("check for duplicate instance", e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
- .errorInfo(errorLoggerInfo).build();
- updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage());
- throw requestDbFailureException;
- }
- return dup;
- }
-
- public boolean camundaHistoryCheck(InfraActiveRequests duplicateRecord, InfraActiveRequests currentActiveReq) throws RequestDbFailureException, ContactCamundaException{
- String requestId = duplicateRecord.getRequestId();
- String path = env.getProperty("mso.camunda.rest.history.uri") + requestId;
- String targetUrl = env.getProperty("mso.camundaURL") + path;
- HttpHeaders headers = setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey"));
- HttpEntity<?> requestEntity = new HttpEntity<>(headers);
- ResponseEntity<List<HistoricProcessInstanceEntity>> response = null;
- try{
- response = restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>(){});
- }catch(HttpStatusCodeException e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ContactCamundaException contactCamundaException= new ContactCamundaException.Builder(requestId, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
- .errorInfo(errorLoggerInfo).build();
- updateStatus(currentActiveReq, Status.FAILED, contactCamundaException.getMessage());
- throw contactCamundaException;
- }
- if(response.getBody().isEmpty()){
- updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed");
- }
- for(HistoricProcessInstance instance : response.getBody()){
- if(instance.getState().equals("ACTIVE")){
- return true;
- }else{
- updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed");
- }
- }
- return false;
- }
-
- protected HttpHeaders setCamundaHeaders(String auth, String msoKey) {
- HttpHeaders headers = new HttpHeaders();
- List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>();
- acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON);
- headers.setAccept(acceptableMediaTypes);
- try {
- String userCredentials = CryptoUtils.decrypt(auth, msoKey);
- if(userCredentials != null) {
- headers.add(HttpHeaders.AUTHORIZATION, "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()));
- }
- } catch(GeneralSecurityException e) {
- logger.error("Security exception", e);
- }
- return headers;
- }
-
- public ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action, long startTime,
- ServiceInstancesRequest sir, MsoRequest msoRequest, String requestId, String requestUri) throws ApiException {
- try{
- ObjectMapper mapper = new ObjectMapper();
- return mapper.readValue(requestJSON, ServiceInstancesRequest.class);
-
- } catch (IOException e) {
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-
- ValidateException validateException = new ValidateException.Builder("Error mapping request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
- String requestScope = requestScopeFromUri(requestUri);
-
- msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action, requestScope, requestJSON);
-
- throw validateException;
- }
- }
-
- public void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action, String version,
- String requestJSON, Boolean aLaCarte, String requestId, InfraActiveRequests currentActiveReq) throws ValidateException, RequestDbFailureException {
- int reqVersion = Integer.parseInt(version.substring(1));
- try {
- msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte);
- } catch (Exception e) {
- logger.error("failed to parse request", e);
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ValidateException validateException = new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
-
- updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
-
- throw validateException;
- }
- }
-
- public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action, HashMap<String, String> instanceIdMap, long startTime, MsoRequest msoRequest,
- String instanceName, String requestScope, InfraActiveRequests dup) throws ApiException {
-
- String instance = null;
- if(instanceName != null){
- instance = instanceName;
- }else{
- instance = instanceIdMap.get(requestScope + "InstanceId");
- }
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-
- DuplicateRequestException dupException = new DuplicateRequestException.Builder(requestScope,instance,dup.getRequestStatus(),dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
- .errorInfo(errorLoggerInfo).build();
-
- updateStatus(currentActiveReq, Status.FAILED, dupException.getMessage());
-
- throw dupException;
- }
-
- public String getRequestId(ContainerRequestContext requestContext) throws ValidateException {
- String requestId = null;
- if (requestContext.getProperty("requestId") != null) {
- requestId = requestContext.getProperty("requestId").toString();
- }
- if (UUIDChecker.isValidUUID(requestId)) {
- return requestId;
- } else {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ValidateException validateException = new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID", HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER)
- .errorInfo(errorLoggerInfo).build();
-
- throw validateException;
- }
- }
-
- public void setInstanceId(InfraActiveRequests currentActiveReq, String requestScope, String instanceId, Map<String, String> instanceIdMap) {
- if(StringUtils.isNotBlank(instanceId)) {
- if(ModelType.service.name().equalsIgnoreCase(requestScope)) {
- currentActiveReq.setServiceInstanceId(instanceId);
- } else if(ModelType.vnf.name().equalsIgnoreCase(requestScope)) {
- currentActiveReq.setVnfId(instanceId);
- } else if(ModelType.vfModule.name().equalsIgnoreCase(requestScope)) {
- currentActiveReq.setVfModuleId(instanceId);
- } else if(ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)) {
- currentActiveReq.setVolumeGroupId(instanceId);
- } else if(ModelType.network.name().equalsIgnoreCase(requestScope)) {
- currentActiveReq.setNetworkId(instanceId);
- } else if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
- currentActiveReq.setConfigurationId(instanceId);
- }else if(ModelType.instanceGroup.toString().equalsIgnoreCase(requestScope)){
- currentActiveReq.setInstanceGroupId(instanceId);
- }
- } else if(instanceIdMap != null && !instanceIdMap.isEmpty()) {
- if(instanceIdMap.get("serviceInstanceId") != null){
- currentActiveReq.setServiceInstanceId(instanceIdMap.get("serviceInstanceId"));
- }
- if(instanceIdMap.get("vnfInstanceId") != null){
- currentActiveReq.setVnfId(instanceIdMap.get("vnfInstanceId"));
- }
- if(instanceIdMap.get("vfModuleInstanceId") != null){
- currentActiveReq.setVfModuleId(instanceIdMap.get("vfModuleInstanceId"));
- }
- if(instanceIdMap.get("volumeGroupInstanceId") != null){
- currentActiveReq.setVolumeGroupId(instanceIdMap.get("volumeGroupInstanceId"));
- }
- if(instanceIdMap.get("networkInstanceId") != null){
- currentActiveReq.setNetworkId(instanceIdMap.get("networkInstanceId"));
- }
- if(instanceIdMap.get("configurationInstanceId") != null){
- currentActiveReq.setConfigurationId(instanceIdMap.get("configurationInstanceId"));
- }
- if(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null){
- currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID));
- }
- }
- }
-
- public String mapJSONtoMSOStyle(String msoRawRequest, ServiceInstancesRequest serviceInstRequest, boolean isAlaCarte, Actions action) throws IOException {
- ObjectMapper mapper = new ObjectMapper();
- mapper.setSerializationInclusion(Include.NON_NULL);
- if(msoRawRequest != null){
- ServiceInstancesRequest sir = mapper.readValue(msoRawRequest, ServiceInstancesRequest.class);
- if( serviceInstRequest != null &&
- serviceInstRequest.getRequestDetails() != null &&
- serviceInstRequest.getRequestDetails().getRequestParameters() != null) {
- if( !isAlaCarte && Action.createInstance.equals(action)) {
- sir.getRequestDetails().setCloudConfiguration(serviceInstRequest.getRequestDetails().getCloudConfiguration());
- sir.getRequestDetails().getRequestParameters().setUserParams(serviceInstRequest.getRequestDetails().getRequestParameters().getUserParams());
- }
- sir.getRequestDetails().getRequestParameters().setUsePreload(serviceInstRequest.getRequestDetails().getRequestParameters().getUsePreload());
- }
-
- logger.debug("Value as string: {}", mapper.writeValueAsString(sir));
- return mapper.writeValueAsString(sir);
- }
- return null;
- }
-
- public Optional<String> retrieveModelName(RequestParameters requestParams) {
- String requestTestApi = null;
- TestApi testApi = null;
-
- if (requestParams != null) {
- requestTestApi = requestParams.getTestApi();
- }
-
- if (requestTestApi == null) {
- if(requestParams != null && requestParams.getALaCarte() != null && !requestParams.getALaCarte()) {
- requestTestApi = env.getProperty(CommonConstants.MACRO_TEST_API);
- } else {
- requestTestApi = env.getProperty(CommonConstants.ALACARTE_TEST_API);
- }
- }
-
- try {
- testApi = TestApi.valueOf(requestTestApi);
- return Optional.of(testApi.getModelName());
- } catch (Exception e) {
- logger.warn("Catching the exception on the valueOf enum call and continuing", e);
- throw new IllegalArgumentException("Invalid TestApi is provided", e);
- }
- }
-
- public String getDefaultModel(ServiceInstancesRequest sir) {
- String defaultModel = sir.getRequestDetails().getRequestInfo().getSource() + "_DEFAULT";
- Optional<String> oModelName = retrieveModelName(sir.getRequestDetails().getRequestParameters());
- if (oModelName.isPresent()) {
- defaultModel = oModelName.get();
- }
- return defaultModel;
- }
-
- public String getServiceType(String requestScope, ServiceInstancesRequest sir, Boolean aLaCarteFlag){
- String serviceType = null;
- if(requestScope.equalsIgnoreCase(ModelType.service.toString())){
- String defaultServiceModelName = getDefaultModel(sir);
- org.onap.so.db.catalog.beans.Service serviceRecord;
- if(aLaCarteFlag){
- serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
- if(serviceRecord != null){
- serviceType = serviceRecord.getServiceType();
- }
- }else{
- serviceRecord = catalogDbClient.getServiceByID(sir.getRequestDetails().getModelInfo().getModelVersionId());
- if(serviceRecord != null){
- serviceType = serviceRecord.getServiceType();
- }else{
- serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
- if(serviceRecord != null){
- serviceType = serviceRecord.getServiceType();
- }
- }
- }
- }else{
- serviceType = msoRequest.getServiceInstanceType(sir, requestScope);
- }
- return serviceType;
- }
-
- protected String setServiceInstanceId(String requestScope, ServiceInstancesRequest sir){
- if(sir.getServiceInstanceId () != null){
- return sir.getServiceInstanceId ();
- }else if(requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())){
- RelatedInstanceList[] relatedInstances = sir.getRequestDetails().getRelatedInstanceList();
- if(relatedInstances != null){
- for(RelatedInstanceList relatedInstanceList : relatedInstances){
- RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
- if(relatedInstance.getModelInfo().getModelType() == ModelType.service){
- return relatedInstance.getInstanceId();
- }
- }
- }
- }
- return null;
- }
-
- private String requestScopeFromUri(String requestUri){
- String requestScope;
- if(requestUri.contains(ModelType.network.name())){
- requestScope = ModelType.network.name();
- }else if(requestUri.contains(ModelType.vfModule.name())){
- requestScope = ModelType.vfModule.name();
- }else if(requestUri.contains(ModelType.volumeGroup.name())){
- requestScope = ModelType.volumeGroup.name();
- }else if(requestUri.contains(ModelType.configuration.name())){
- requestScope = ModelType.configuration.name();
- }else if(requestUri.contains(ModelType.vnf.name())){
- requestScope = ModelType.vnf.name();
- }else{
- requestScope = ModelType.service.name();
- }
- return requestScope;
- }
-
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java
index ad97918a03..931a1eb52b 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java
@@ -74,7 +74,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
-
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@@ -96,1432 +95,1611 @@ import java.util.Optional;
@Component
@Path("/onap/so/infra/serviceInstantiation")
-@Api(value="/onap/so/infra/serviceInstantiation",description="Infrastructure API Requests for Service Instances")
+@Api(value = "/onap/so/infra/serviceInstantiation", description = "Infrastructure API Requests for Service Instances")
public class ServiceInstances {
- private static Logger logger = LoggerFactory.getLogger(MsoRequest.class);
- private static String NAME = "name";
- private static String VALUE = "value";
- private static String uriPrefix = "/serviceInstantiation/";
- private static final String SAVE_TO_DB = "save instance to db";
-
- @Autowired
- private Environment env;
-
- @Autowired
- private CatalogDbClient catalogDbClient;
-
- @Autowired
- private RequestsDbClient infraActiveRequestsClient;
-
- @Autowired
- private MsoRequest msoRequest;
-
- @Autowired
- private RequestHandlerUtils requestHandlerUtils;
-
- @POST
+ private static Logger logger = LoggerFactory.getLogger(MsoRequest.class);
+ private static String NAME = "name";
+ private static String VALUE = "value";
+ private static String uriPrefix = "/serviceInstantiation/";
+ private static final String SAVE_TO_DB = "save instance to db";
+
+ @Autowired
+ private Environment env;
+
+ @Autowired
+ private CatalogDbClient catalogDbClient;
+
+ @Autowired
+ private RequestsDbClient infraActiveRequestsClient;
+
+ @Autowired
+ private MsoRequest msoRequest;
+
+ @Autowired
+ private RequestHandlerUtils requestHandlerUtils;
+
+ @POST
@Path("/{version:[vV][5-7]}/serviceInstances")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Create a Service Instance on a version provided",response=Response.class)
- @Transactional
- public Response createServiceInstance(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- return serviceInstances(request, Action.createInstance, null, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/activate")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Activate provided Service Instance",response=Response.class)
- @Transactional
- public Response activateServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- return serviceInstances(request, Action.activateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/deactivate")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Deactivate provided Service Instance",response=Response.class)
- @Transactional
- public Response deactivateServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- return serviceInstances(request, Action.deactivateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @DELETE
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Delete provided Service Instance",response=Response.class)
- @Transactional
- public Response deleteServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][7]}/serviceInstances/assign")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Assign Service Instance", response=Response.class)
- @Transactional
- public Response assignServiceInstance(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- return serviceInstances(request, Action.assignInstance, null, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/unassign")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Unassign Service Instance", response=Response.class)
- @Transactional
- public Response unassignServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<String,String>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- return serviceInstances(request, Action.unassignInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Create Port Mirroring Configuration",response=Response.class)
- @Transactional
- public Response createPortConfiguration(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- return configurationRecipeLookup(request, Action.createInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @DELETE
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Delete provided Port",response=Response.class)
- @Transactional
- public Response deletePortConfiguration(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("configurationInstanceId", configurationInstanceId);
- return configurationRecipeLookup(request, Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/enablePort")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Enable Port Mirroring",response=Response.class)
- @Transactional
- public Response enablePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("configurationInstanceId", configurationInstanceId);
- return configurationRecipeLookup(request, Action.enablePort, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/disablePort")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Disable Port Mirroring",response=Response.class)
- @Transactional
- public Response disablePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("configurationInstanceId", configurationInstanceId);
- return configurationRecipeLookup(request, Action.disablePort, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/activate")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Activate Port Mirroring",response=Response.class)
- @Transactional
- public Response activatePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("configurationInstanceId", configurationInstanceId);
- return configurationRecipeLookup(request, Action.activateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/deactivate")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Deactivate Port Mirroring",response=Response.class)
- @Transactional
- public Response deactivatePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("configurationInstanceId", configurationInstanceId);
- return configurationRecipeLookup(request, Action.deactivateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/addRelationships")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Add Relationships to a Service Instance",response=Response.class)
- @Transactional
- public Response addRelationships(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- return configurationRecipeLookup(request, Action.addRelationships, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/removeRelationships")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Remove Relationships from Service Instance",response=Response.class)
- @Transactional
- public Response removeRelationships(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- return configurationRecipeLookup(request, Action.removeRelationships, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Create VNF on a specified version and serviceInstance",response=Response.class)
- @Transactional
- public Response createVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- try{
- return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }catch (Exception e){
- logger.error("Error in vnf", e);
- throw e;
- }
- }
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/replace")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Replace provided VNF instance",response=Response.class)
- @Transactional
- public Response replaceVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- return serviceInstances(request, Action.replaceInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @PUT
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Update VNF on a specified version, serviceInstance and vnfInstance",response=Response.class)
- @Transactional
- public Response updateVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/applyUpdatedConfig")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Apply updated configuration",response=Response.class)
- public Response applyUpdatedConfig(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- return serviceInstances(request, Action.applyUpdatedConfig, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/recreate")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Recreate VNF Instance",response=Response.class)
- public Response recreateVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- return serviceInstances(request, Action.recreateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
-
- @DELETE
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Delete provided VNF instance",response=Response.class)
- @Transactional
- public Response deleteVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Create VfModule on a specified version, serviceInstance and vnfInstance",response=Response.class)
- @Transactional
- public Response createVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}/replace")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Create VfModule on a specified version, serviceInstance and vnfInstance",response=Response.class)
- @Transactional
- public Response replaceVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId,
- @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
- return serviceInstances(request, Action.replaceInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @PUT
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Update VfModule on a specified version, serviceInstance, vnfInstance and vfModule",response=Response.class)
- @Transactional
- public Response updateVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId,
- @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
- return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/inPlaceSoftwareUpdate")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Perform VNF software update",response=Response.class)
- @Transactional
- public Response inPlaceSoftwareUpdate(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- return serviceInstances(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @DELETE
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Delete provided VfModule instance",response=Response.class)
- @Transactional
- public Response deleteVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId,
- @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
- return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}/deactivateAndCloudDelete")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Deactivate and Cloud Delete VfModule instance",response=Response.class)
- @Transactional
- public Response deactivateAndCloudDeleteVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
- Response response = serviceInstances(request, Action.deactivateAndCloudDelete, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- return response;
- }
-
- @POST
- @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/scaleOut")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="VF Auto Scale Out",response=Response.class)
- @Transactional
- public Response scaleOutVfModule(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- return serviceInstances(request, Action.scaleOut, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Create VolumeGroup on a specified version, serviceInstance, vnfInstance",response=Response.class)
- @Transactional
- public Response createVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @PUT
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Update VolumeGroup on a specified version, serviceInstance, vnfInstance and volumeGroup",response=Response.class)
- @Transactional
- public Response updateVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId,
- @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId);
- return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @DELETE
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Delete provided VolumeGroup instance",response=Response.class)
- @Transactional
- public Response deleteVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("vnfInstanceId") String vnfInstanceId,
- @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("vnfInstanceId", vnfInstanceId);
- instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId);
- return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/networks")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Create NetworkInstance on a specified version and serviceInstance ",response=Response.class)
- @Transactional
- public Response createNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @PUT
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/networks/{networkInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Update VolumeGroup on a specified version, serviceInstance, networkInstance",response=Response.class)
- @Transactional
- public Response updateNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("networkInstanceId") String networkInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("networkInstanceId", networkInstanceId);
- return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @DELETE
- @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/networks/{networkInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Delete provided Network instance",response=Response.class)
- @Transactional
- public Response deleteNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
- @PathParam("networkInstanceId") String networkInstanceId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put("serviceInstanceId", serviceInstanceId);
- instanceIdMap.put("networkInstanceId", networkInstanceId);
- return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create a Service Instance on a version provided", response = Response.class)
+ @Transactional
+ public Response createServiceInstance(String request, @PathParam("version") String version,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ return serviceInstances(request, Action.createInstance, null, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/activate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Activate provided Service Instance", response = Response.class)
+ @Transactional
+ public Response activateServiceInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ return serviceInstances(request, Action.activateInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/deactivate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Deactivate provided Service Instance", response = Response.class)
+ @Transactional
+ public Response deactivateServiceInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ return serviceInstances(request, Action.deactivateInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @DELETE
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete provided Service Instance", response = Response.class)
+ @Transactional
+ public Response deleteServiceInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][7]}/serviceInstances/assign")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Assign Service Instance", response = Response.class)
+ @Transactional
+ public Response assignServiceInstance(String request, @PathParam("version") String version,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ return serviceInstances(request, Action.assignInstance, null, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/unassign")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Unassign Service Instance", response = Response.class)
+ @Transactional
+ public Response unassignServiceInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<String, String>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ return serviceInstances(request, Action.unassignInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Port Mirroring Configuration", response = Response.class)
+ @Transactional
+ public Response createPortConfiguration(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ return configurationRecipeLookup(request, Action.createInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @DELETE
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete provided Port", response = Response.class)
+ @Transactional
+ public Response deletePortConfiguration(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId,
+ @PathParam("configurationInstanceId") String configurationInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("configurationInstanceId", configurationInstanceId);
+ return configurationRecipeLookup(request, Action.deleteInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/enablePort")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Enable Port Mirroring", response = Response.class)
+ @Transactional
+ public Response enablePort(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId,
+ @PathParam("configurationInstanceId") String configurationInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("configurationInstanceId", configurationInstanceId);
+ return configurationRecipeLookup(request, Action.enablePort, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/disablePort")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Disable Port Mirroring", response = Response.class)
+ @Transactional
+ public Response disablePort(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId,
+ @PathParam("configurationInstanceId") String configurationInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("configurationInstanceId", configurationInstanceId);
+ return configurationRecipeLookup(request, Action.disablePort, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/activate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Activate Port Mirroring", response = Response.class)
+ @Transactional
+ public Response activatePort(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId,
+ @PathParam("configurationInstanceId") String configurationInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("configurationInstanceId", configurationInstanceId);
+ return configurationRecipeLookup(request, Action.activateInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/deactivate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Deactivate Port Mirroring", response = Response.class)
+ @Transactional
+ public Response deactivatePort(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId,
+ @PathParam("configurationInstanceId") String configurationInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("configurationInstanceId", configurationInstanceId);
+ return configurationRecipeLookup(request, Action.deactivateInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/addRelationships")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Add Relationships to a Service Instance", response = Response.class)
+ @Transactional
+ public Response addRelationships(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ return configurationRecipeLookup(request, Action.addRelationships, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/removeRelationships")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Remove Relationships from Service Instance", response = Response.class)
+ @Transactional
+ public Response removeRelationships(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ return configurationRecipeLookup(request, Action.removeRelationships, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create VNF on a specified version and serviceInstance", response = Response.class)
+ @Transactional
+ public Response createVnfInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ try {
+ return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ } catch (Exception e) {
+ logger.error("Error in vnf", e);
+ throw e;
+ }
+ }
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/replace")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Replace provided VNF instance", response = Response.class)
+ @Transactional
+ public Response replaceVnfInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ return serviceInstances(request, Action.replaceInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @PUT
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update VNF on a specified version, serviceInstance and vnfInstance",
+ response = Response.class)
+ @Transactional
+ public Response updateVnfInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/applyUpdatedConfig")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Apply updated configuration", response = Response.class)
+ public Response applyUpdatedConfig(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ return serviceInstances(request, Action.applyUpdatedConfig, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/recreate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Recreate VNF Instance", response = Response.class)
+ public Response recreateVnfInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ return serviceInstances(request, Action.recreateInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+
+ @DELETE
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete provided VNF instance", response = Response.class)
+ @Transactional
+ public Response deleteVnfInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create VfModule on a specified version, serviceInstance and vnfInstance",
+ response = Response.class)
+ @Transactional
+ public Response createVfModuleInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}/replace")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create VfModule on a specified version, serviceInstance and vnfInstance",
+ response = Response.class)
+ @Transactional
+ public Response replaceVfModuleInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
+ return serviceInstances(request, Action.replaceInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @PUT
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update VfModule on a specified version, serviceInstance, vnfInstance and vfModule",
+ response = Response.class)
+ @Transactional
+ public Response updateVfModuleInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
+ return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/inPlaceSoftwareUpdate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Perform VNF software update", response = Response.class)
+ @Transactional
+ public Response inPlaceSoftwareUpdate(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ return serviceInstances(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @DELETE
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete provided VfModule instance", response = Response.class)
+ @Transactional
+ public Response deleteVfModuleInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
+ return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}/deactivateAndCloudDelete")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Deactivate and Cloud Delete VfModule instance", response = Response.class)
+ @Transactional
+ public Response deactivateAndCloudDeleteVfModuleInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
+ Response response = serviceInstances(request, Action.deactivateAndCloudDelete, instanceIdMap, version,
+ requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ return response;
+ }
+
+ @POST
+ @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/scaleOut")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "VF Auto Scale Out", response = Response.class)
+ @Transactional
+ public Response scaleOutVfModule(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ return serviceInstances(request, Action.scaleOut, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create VolumeGroup on a specified version, serviceInstance, vnfInstance",
+ response = Response.class)
+ @Transactional
+ public Response createVolumeGroupInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @PUT
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update VolumeGroup on a specified version, serviceInstance, vnfInstance and volumeGroup",
+ response = Response.class)
+ @Transactional
+ public Response updateVolumeGroupInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId);
+ return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @DELETE
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete provided VolumeGroup instance", response = Response.class)
+ @Transactional
+ public Response deleteVolumeGroupInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId);
+ return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/networks")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create NetworkInstance on a specified version and serviceInstance ",
+ response = Response.class)
+ @Transactional
+ public Response createNetworkInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @PUT
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/networks/{networkInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update VolumeGroup on a specified version, serviceInstance, networkInstance",
+ response = Response.class)
+ @Transactional
+ public Response updateNetworkInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId,
+ @PathParam("networkInstanceId") String networkInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("networkInstanceId", networkInstanceId);
+ return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @DELETE
+ @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/networks/{networkInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete provided Network instance", response = Response.class)
+ @Transactional
+ public Response deleteNetworkInstance(String request, @PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId,
+ @PathParam("networkInstanceId") String networkInstanceId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("networkInstanceId", networkInstanceId);
+ return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
@Path("/{version:[vV][7]}/instanceGroups")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Create instanceGroups",response=Response.class)
- @Transactional
- public Response createInstanceGroups(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- return serviceInstances(request, Action.createInstance, null, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @DELETE
- @Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Delete instanceGroup",response=Response.class)
- @Transactional
- public Response deleteInstanceGroups(@PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId);
- return deleteInstanceGroups(Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix), requestContext);
- }
-
- @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create instanceGroups", response = Response.class)
+ @Transactional
+ public Response createInstanceGroups(String request, @PathParam("version") String version,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ return serviceInstances(request, Action.createInstance, null, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @DELETE
+ @Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete instanceGroup", response = Response.class)
+ @Transactional
+ public Response deleteInstanceGroups(@PathParam("version") String version,
+ @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId);
+ return deleteInstanceGroups(Action.deleteInstance, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix), requestContext);
+ }
+
+ @POST
@Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}/addMembers")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Add instanceGroup members",response=Response.class)
- @Transactional
- public Response addInstanceGroupMembers(String request, @PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId);
- return serviceInstances(request, Action.addMembers, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Add instanceGroup members", response = Response.class)
+ @Transactional
+ public Response addInstanceGroupMembers(String request, @PathParam("version") String version,
+ @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId);
+ return serviceInstances(request, Action.addMembers, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ @POST
@Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}/removeMembers")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Remove instanceGroup members",response=Response.class)
- @Transactional
- public Response removeInstanceGroupMembers(String request, @PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) throws ApiException {
- String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId);
- return serviceInstances(request, Action.removeMembers, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
- }
-
- public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException {
- String serviceInstanceId = (instanceIdMap ==null)? null:instanceIdMap.get("serviceInstanceId");
- Boolean aLaCarte = null;
- long startTime = System.currentTimeMillis ();
- ServiceInstancesRequest sir = null;
- String apiVersion = version.substring(1);
-
- sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, requestId, requestUri);
- String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri);
- InfraActiveRequests currentActiveReq = msoRequest.createRequestObject (sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
- if(sir.getRequestDetails().getRequestParameters() != null){
- aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte();
- }
- requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, currentActiveReq);
- requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap);
-
- int requestVersion = Integer.parseInt(version.substring(1));
- String instanceName = null;
- if (sir.getRequestDetails().getRequestInfo() != null) {
- instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName();
- }
- boolean alaCarteFlag = msoRequest.getAlacarteFlag(sir);
- String vnfType = msoRequest.getVnfType(sir,requestScope,action,requestVersion);
- String networkType = msoRequest.getNetworkType(sir,requestScope);
- String sdcServiceModelVersion = msoRequest.getSDCServiceModelVersion(sir);
- String vfModuleType = msoRequest.getVfModuleType(sir,requestScope,action,requestVersion);
-
- if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null){
- currentActiveReq.setVnfType(vnfType);
- }else if(requestScope.equalsIgnoreCase(ModelType.network.name()) && networkType != null){
- currentActiveReq.setNetworkType(networkType);
- }
-
- InfraActiveRequests dup = null;
- boolean inProgress = false;
-
- dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,requestScope, currentActiveReq);
-
- if(dup != null){
- inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
- }
-
- if (dup != null && inProgress) {
- requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, instanceName, requestScope, dup);
- }
- ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
-
- RequestReferences referencesResponse = new RequestReferences();
-
- referencesResponse.setRequestId(requestId);
-
- serviceResponse.setRequestReferences(referencesResponse);
- Boolean isBaseVfModule = false;
-
- RecipeLookupResult recipeLookupResult = getServiceInstanceOrchestrationURI(sir, action, alaCarteFlag, currentActiveReq);
- String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, alaCarteFlag);
- ModelType modelType;
- ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
- if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
- modelType = ModelType.vnf;
- }else if(action == Action.addMembers || action == Action.removeMembers){
- modelType = ModelType.instanceGroup;
- }else {
- modelType =modelInfo.getModelType();
- }
-
- if (modelType.equals(ModelType.vfModule)) {
-
-
- // Get VF Module-specific base module indicator
- VfModule vfm = null;
-
- String modelVersionId = modelInfo.getModelVersionId();
-
- if(modelVersionId != null) {
- vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId);
- } else if(modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null){
- vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(), modelInfo.getModelVersion());
- }
-
- if (vfm != null) {
- if (vfm.getIsBase()) {
- isBaseVfModule = true;
- }
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Remove instanceGroup members", response = Response.class)
+ @Transactional
+ public Response removeInstanceGroupMembers(String request, @PathParam("version") String version,
+ @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext)
+ throws ApiException {
+ String requestId = requestHandlerUtils.getRequestId(requestContext);
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId);
+ return serviceInstances(request, Action.removeMembers, instanceIdMap, version, requestId,
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
+ }
+
+ public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap,
+ String version, String requestId, String requestUri) throws ApiException {
+ String serviceInstanceId = (instanceIdMap == null) ? null : instanceIdMap.get("serviceInstanceId");
+ Boolean aLaCarte = null;
+ long startTime = System.currentTimeMillis();
+ ServiceInstancesRequest sir = null;
+ String apiVersion = version.substring(1);
+
+ sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest,
+ requestId, requestUri);
+ String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri);
+ InfraActiveRequests currentActiveReq =
+ msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
+ if (sir.getRequestDetails().getRequestParameters() != null) {
+ aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte();
+ }
+ requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId,
+ currentActiveReq);
+ requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap);
+
+ int requestVersion = Integer.parseInt(version.substring(1));
+ String instanceName = null;
+ if (sir.getRequestDetails().getRequestInfo() != null) {
+ instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName();
+ }
+ boolean alaCarteFlag = msoRequest.getAlacarteFlag(sir);
+ String vnfType = msoRequest.getVnfType(sir, requestScope, action, requestVersion);
+ String networkType = msoRequest.getNetworkType(sir, requestScope);
+ String sdcServiceModelVersion = msoRequest.getSDCServiceModelVersion(sir);
+ String vfModuleType = msoRequest.getVfModuleType(sir, requestScope, action, requestVersion);
+
+ if (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null) {
+ currentActiveReq.setVnfType(vnfType);
+ } else if (requestScope.equalsIgnoreCase(ModelType.network.name()) && networkType != null) {
+ currentActiveReq.setNetworkType(networkType);
+ }
+
+ InfraActiveRequests dup = null;
+ boolean inProgress = false;
+
+ dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,
+ requestScope, currentActiveReq);
+
+ if (dup != null) {
+ inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
+ }
+
+ if (dup != null && inProgress) {
+ requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime,
+ msoRequest, instanceName, requestScope, dup);
+ }
+ ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
+
+ RequestReferences referencesResponse = new RequestReferences();
+
+ referencesResponse.setRequestId(requestId);
+
+ serviceResponse.setRequestReferences(referencesResponse);
+ Boolean isBaseVfModule = false;
+
+ RecipeLookupResult recipeLookupResult =
+ getServiceInstanceOrchestrationURI(sir, action, alaCarteFlag, currentActiveReq);
+ String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, alaCarteFlag);
+ ModelType modelType;
+ ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
+ if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
+ modelType = ModelType.vnf;
+ } else if (action == Action.addMembers || action == Action.removeMembers) {
+ modelType = ModelType.instanceGroup;
+ } else {
+ modelType = modelInfo.getModelType();
+ }
+
+ if (modelType.equals(ModelType.vfModule)) {
+
+
+ // Get VF Module-specific base module indicator
+ VfModule vfm = null;
+
+ String modelVersionId = modelInfo.getModelVersionId();
+
+ if (modelVersionId != null) {
+ vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId);
+ } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) {
+ vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(),
+ modelInfo.getModelVersion());
+ }
+
+ if (vfm != null) {
+ if (vfm.getIsBase()) {
+ isBaseVfModule = true;
+ }
} else if (action == Action.createInstance || action == Action.updateInstance) {
- // There is no entry for this vfModuleType with this version, if specified, in VF_MODULE table in Catalog DB.
- // This request cannot proceed
-
- String serviceVersionText = "";
- if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty ()) {
- serviceVersionText = " with version " + sdcServiceModelVersion;
- }
-
- String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName() + serviceVersionText + " not found in MSO Catalog DB";
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage, HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
+ // There is no entry for this vfModuleType with this version, if specified, in VF_MODULE table in
+ // Catalog DB.
+ // This request cannot proceed
+
+ String serviceVersionText = "";
+ if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) {
+ serviceVersionText = " with version " + sdcServiceModelVersion;
+ }
+
+ String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName()
+ + serviceVersionText + " not found in MSO Catalog DB";
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage,
+ HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage());
throw vfModuleException;
- }
- }
-
-
- serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir);
- String vnfId = "";
- String vfModuleId = "";
- String volumeGroupId = "";
- String networkId = "";
- String pnfCorrelationId = "";
- String instanceGroupId = null;
-
- if(sir.getVnfInstanceId () != null){
- vnfId = sir.getVnfInstanceId ();
- }
-
- if(sir.getVfModuleInstanceId () != null){
- vfModuleId = sir.getVfModuleInstanceId ();
- }
-
- if(sir.getVolumeGroupInstanceId () != null){
- volumeGroupId = sir.getVolumeGroupInstanceId ();
- }
-
- if(sir.getNetworkInstanceId () != null){
- networkId = sir.getNetworkInstanceId ();
- }
- if(sir.getInstanceGroupId() != null){
- instanceGroupId = sir.getInstanceGroupId();
- }
+ }
+ }
+
+
+ serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir);
+ String vnfId = "";
+ String vfModuleId = "";
+ String volumeGroupId = "";
+ String networkId = "";
+ String pnfCorrelationId = "";
+ String instanceGroupId = null;
+
+ if (sir.getVnfInstanceId() != null) {
+ vnfId = sir.getVnfInstanceId();
+ }
+
+ if (sir.getVfModuleInstanceId() != null) {
+ vfModuleId = sir.getVfModuleInstanceId();
+ }
+
+ if (sir.getVolumeGroupInstanceId() != null) {
+ volumeGroupId = sir.getVolumeGroupInstanceId();
+ }
+
+ if (sir.getNetworkInstanceId() != null) {
+ networkId = sir.getNetworkInstanceId();
+ }
+ if (sir.getInstanceGroupId() != null) {
+ instanceGroupId = sir.getInstanceGroupId();
+ }
pnfCorrelationId = getPnfCorrelationId(sir);
- try{
+ try {
infraActiveRequestsClient.save(currentActiveReq);
- }catch(Exception e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
- .errorInfo(errorLoggerInfo).build();
+ } catch (Exception e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
}
-
- if(!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance){
- aLaCarte = true;
- }else if(aLaCarte == null){
- aLaCarte = false;
- }
-
- RequestClientParameter requestClientParameter = null;
- try {
- requestClientParameter = new RequestClientParameter.Builder()
- .setRequestId(requestId)
- .setBaseVfModule(isBaseVfModule)
- .setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
- .setRequestAction(action.toString())
- .setServiceInstanceId(serviceInstanceId)
- .setPnfCorrelationId(pnfCorrelationId)
- .setVnfId(vnfId)
- .setVfModuleId(vfModuleId)
- .setVolumeGroupId(volumeGroupId)
- .setNetworkId(networkId)
- .setServiceType(serviceInstanceType)
- .setVnfType(vnfType)
- .setVfModuleType(vfModuleType)
- .setNetworkType(networkType)
- .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action))
- .setApiVersion(apiVersion)
- .setALaCarte(aLaCarte)
- .setRequestUri(requestUri)
- .setInstanceGroupId(instanceGroupId).build();
- } catch (IOException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER)
- .errorInfo(errorLoggerInfo).build();
- }
- return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope);
- }
- public Response deleteInstanceGroups(Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri, ContainerRequestContext requestContext) throws ApiException {
- String instanceGroupId = instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID);
- Boolean aLaCarte = true;
- long startTime = System.currentTimeMillis ();
- String apiVersion = version.substring(1);
- ServiceInstancesRequest sir = new ServiceInstancesRequest();
- sir.setInstanceGroupId(instanceGroupId);
-
- String requestScope = ModelType.instanceGroup.toString();
- InfraActiveRequests currentActiveReq = msoRequest.createRequestObject (sir, action, requestId, Status.IN_PROGRESS, null, requestScope);
- requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap);
- try {
- requestHandlerUtils.validateHeaders(requestContext);
- } catch (ValidationException e) {
- logger.error("Exception occurred", e);
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
+
+ if (!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance) {
+ aLaCarte = true;
+ } else if (aLaCarte == null) {
+ aLaCarte = false;
+ }
+
+ RequestClientParameter requestClientParameter = null;
+ try {
+ requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId)
+ .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
+ .setRequestAction(action.toString()).setServiceInstanceId(serviceInstanceId)
+ .setPnfCorrelationId(pnfCorrelationId).setVnfId(vnfId).setVfModuleId(vfModuleId)
+ .setVolumeGroupId(volumeGroupId).setNetworkId(networkId).setServiceType(serviceInstanceType)
+ .setVnfType(vnfType).setVfModuleType(vfModuleType).setNetworkType(networkType)
+ .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action))
+ .setApiVersion(apiVersion).setALaCarte(aLaCarte).setRequestUri(requestUri)
+ .setInstanceGroupId(instanceGroupId).build();
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(),
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
+ .build();
+ }
+ return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter,
+ recipeLookupResult.getOrchestrationURI(), requestScope);
+ }
+
+ public Response deleteInstanceGroups(Actions action, HashMap<String, String> instanceIdMap, String version,
+ String requestId, String requestUri, ContainerRequestContext requestContext) throws ApiException {
+ String instanceGroupId = instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID);
+ Boolean aLaCarte = true;
+ long startTime = System.currentTimeMillis();
+ String apiVersion = version.substring(1);
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ sir.setInstanceGroupId(instanceGroupId);
+
+ String requestScope = ModelType.instanceGroup.toString();
+ InfraActiveRequests currentActiveReq =
+ msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, null, requestScope);
+ requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap);
+ try {
+ requestHandlerUtils.validateHeaders(requestContext);
+ } catch (ValidationException e) {
+ logger.error("Exception occurred", e);
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ValidateException validateException =
+ new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
throw validateException;
- }
-
- InfraActiveRequests dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope, currentActiveReq);
- boolean inProgress = false;
-
- if(dup != null){
- inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
- }
-
- if (dup != null && inProgress) {
- requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, null, requestScope, dup);
- }
-
- ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
-
- RequestReferences referencesResponse = new RequestReferences();
-
- referencesResponse.setRequestId(requestId);
-
- serviceResponse.setRequestReferences(referencesResponse);
- Boolean isBaseVfModule = false;
+ }
+
+ InfraActiveRequests dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null,
+ requestScope, currentActiveReq);
+ boolean inProgress = false;
+
+ if (dup != null) {
+ inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
+ }
+
+ if (dup != null && inProgress) {
+ requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime,
+ msoRequest, null, requestScope, dup);
+ }
+
+ ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
+
+ RequestReferences referencesResponse = new RequestReferences();
+
+ referencesResponse.setRequestId(requestId);
+
+ serviceResponse.setRequestReferences(referencesResponse);
+ Boolean isBaseVfModule = false;
RecipeLookupResult recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
-
- try{
+
+ try {
infraActiveRequestsClient.save(currentActiveReq);
- }catch(Exception e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
- .errorInfo(errorLoggerInfo).build();
+ } catch (Exception e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
}
-
- RequestClientParameter requestClientParameter = new RequestClientParameter.Builder()
- .setRequestId(requestId)
- .setBaseVfModule(isBaseVfModule)
- .setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
- .setRequestAction(action.toString())
- .setApiVersion(apiVersion)
- .setALaCarte(aLaCarte)
- .setRequestUri(requestUri)
- .setInstanceGroupId(instanceGroupId).build();
-
- return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope);
- }
-
- private String getPnfCorrelationId(ServiceInstancesRequest sir) {
- return Optional.of(sir)
- .map(ServiceInstancesRequest::getRequestDetails)
- .map(RequestDetails::getRequestParameters)
- .map(parameters -> parameters.getUserParamValue("pnfId"))
- .orElse("");
- }
-
- private RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action, boolean alaCarteFlag,
- InfraActiveRequests currentActiveReq) throws ApiException {
- RecipeLookupResult recipeLookupResult = null;
- //if the aLaCarte flag is set to TRUE, the API-H should choose the VID_DEFAULT recipe for the requested action
- ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
- // Query MSO Catalog DB
-
- if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
- recipeLookupResult = getDefaultVnfUri(sir, action);
- }else if(action == Action.addMembers || action == Action.removeMembers){
- recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
- }else if (modelInfo.getModelType().equals(ModelType.service)) {
- try {
- recipeLookupResult = getServiceURI(sir, action,alaCarteFlag);
- } catch (IOException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-
-
- ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
+
+ RequestClientParameter requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId)
+ .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
+ .setRequestAction(action.toString()).setApiVersion(apiVersion).setALaCarte(aLaCarte)
+ .setRequestUri(requestUri).setInstanceGroupId(instanceGroupId).build();
+
+ return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter,
+ recipeLookupResult.getOrchestrationURI(), requestScope);
+ }
+
+ private String getPnfCorrelationId(ServiceInstancesRequest sir) {
+ return Optional.of(sir).map(ServiceInstancesRequest::getRequestDetails)
+ .map(RequestDetails::getRequestParameters).map(parameters -> parameters.getUserParamValue("pnfId"))
+ .orElse("");
+ }
+
+ private RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action,
+ boolean alaCarteFlag, InfraActiveRequests currentActiveReq) throws ApiException {
+ RecipeLookupResult recipeLookupResult = null;
+ // if the aLaCarte flag is set to TRUE, the API-H should choose the VID_DEFAULT recipe for the requested action
+ ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
+ // Query MSO Catalog DB
+
+ if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
+ recipeLookupResult = getDefaultVnfUri(sir, action);
+ } else if (action == Action.addMembers || action == Action.removeMembers) {
+ recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
+ } else if (modelInfo.getModelType().equals(ModelType.service)) {
+ try {
+ recipeLookupResult = getServiceURI(sir, action, alaCarteFlag);
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
throw validateException;
- }
- } else if (modelInfo.getModelType().equals(ModelType.vfModule) ||
- modelInfo.getModelType().equals(ModelType.volumeGroup) || modelInfo.getModelType().equals(ModelType.vnf)) {
+ }
+ } else if (modelInfo.getModelType().equals(ModelType.vfModule)
+ || modelInfo.getModelType().equals(ModelType.volumeGroup)
+ || modelInfo.getModelType().equals(ModelType.vnf)) {
try {
- recipeLookupResult = getVnfOrVfModuleUri( sir, action);
+ recipeLookupResult = getVnfOrVfModuleUri(sir, action);
} catch (ValidationException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
+ ValidateException validateException =
+ new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
throw validateException;
}
- }else if (modelInfo.getModelType().equals(ModelType.network)) {
+ } else if (modelInfo.getModelType().equals(ModelType.network)) {
try {
- recipeLookupResult = getNetworkUri( sir, action);
+ recipeLookupResult = getNetworkUri(sir, action);
} catch (ValidationException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
+ ValidateException validateException =
+ new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
throw validateException;
}
- }else if(modelInfo.getModelType().equals(ModelType.instanceGroup)){
- recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
+ } else if (modelInfo.getModelType().equals(ModelType.instanceGroup)) {
+ recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
}
if (recipeLookupResult == null) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- RecipeNotFoundException recipeNotFoundExceptionException = new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR)
- .errorInfo(errorLoggerInfo).build();
+ RecipeNotFoundException recipeNotFoundExceptionException =
+ new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.",
+ HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo)
+ .build();
- requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, recipeNotFoundExceptionException.getMessage());
+ requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED,
+ recipeNotFoundExceptionException.getMessage());
throw recipeNotFoundExceptionException;
- }
- return recipeLookupResult;
- }
-
- private RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, boolean alaCarteFlag) throws IOException {
- // SERVICE REQUEST
- // Construct the default service name
- // TODO need to make this a configurable property
- String defaultServiceModelName = requestHandlerUtils.getDefaultModel(servInstReq);
- RequestDetails requestDetails = servInstReq.getRequestDetails();
- ModelInfo modelInfo = requestDetails.getModelInfo();
- org.onap.so.db.catalog.beans.Service serviceRecord;
- List<org.onap.so.db.catalog.beans.Service> serviceRecordList;
- ServiceRecipe recipe = null;
-
- if(alaCarteFlag){
- serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
- if(serviceRecord !=null){
- recipe =catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),action.toString());
- }
- }else{
- serviceRecord = catalogDbClient.getServiceByID(modelInfo.getModelVersionId());
- recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(modelInfo.getModelVersionId(), action.toString());
- if (recipe == null){
- serviceRecordList = catalogDbClient.getServiceByModelInvariantUUIDOrderByModelVersionDesc(modelInfo.getModelInvariantId());
- if(!serviceRecordList.isEmpty()){
- for(org.onap.so.db.catalog.beans.Service record : serviceRecordList){
- recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(record.getModelUUID(),action.toString());
- if(recipe != null){
- break;
- }
- }
- }
- }
- }
-
- //if an aLaCarte flag was sent in the request, throw an error if the recipe was not found
- RequestParameters reqParam = requestDetails.getRequestParameters();
- if(reqParam!=null && alaCarteFlag && recipe==null){
- return null;
- } else if(!alaCarteFlag && recipe != null && Action.createInstance.equals(action)) {
- mapToLegacyRequest(requestDetails);
- }else if (recipe == null) { //aLaCarte wasn't sent, so we'll try the default
- serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
- recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),action.toString());
- }
- if(modelInfo.getModelVersionId() == null) {
- modelInfo.setModelVersionId(serviceRecord.getModelUUID());
- }
- if(recipe==null){
- return null;
- }
- return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ());
- }
-
- protected void mapToLegacyRequest(RequestDetails requestDetails) throws IOException {
- RequestParameters reqParam;
- if (requestDetails.getRequestParameters() == null) {
- reqParam = new RequestParameters();
- } else {
- reqParam = requestDetails.getRequestParameters();
- }
- if(requestDetails.getCloudConfiguration() == null) {
- CloudConfiguration cloudConfig = configureCloudConfig(reqParam);
- if(cloudConfig != null) {
- requestDetails.setCloudConfiguration(cloudConfig);
- }
- }
-
- List<Map<String, Object>> userParams = configureUserParams(reqParam);
- if(!userParams.isEmpty()) {
- if (reqParam == null) {
- requestDetails.setRequestParameters(new RequestParameters());
- }
- requestDetails.getRequestParameters().setUserParams(userParams);
- }
- }
-
- protected CloudConfiguration configureCloudConfig(RequestParameters reqParams) throws IOException {
-
- for(Map<String, Object> params : reqParams.getUserParams()){
- if(params.containsKey("service")){
- Service service = serviceMapper(params);
-
- Optional<CloudConfiguration> targetConfiguration = addCloudConfig(service.getCloudConfiguration());
-
- if (targetConfiguration.isPresent()) {
- return targetConfiguration.get();
- } else {
- for(Networks network : service.getResources().getNetworks()) {
- targetConfiguration = addCloudConfig(network.getCloudConfiguration());
- if(targetConfiguration.isPresent()) {
- return targetConfiguration.get();
- }
- }
-
- for(Vnfs vnf : service.getResources().getVnfs()) {
- targetConfiguration = addCloudConfig(vnf.getCloudConfiguration());
-
- if(targetConfiguration.isPresent()) {
- return targetConfiguration.get();
- }
-
- for(VfModules vfModule : vnf.getVfModules()) {
- targetConfiguration = addCloudConfig(vfModule.getCloudConfiguration());
-
- if(targetConfiguration.isPresent()) {
- return targetConfiguration.get();
- }
- }
- }
- }
- }
- }
-
- return null;
- }
-
- private Optional<CloudConfiguration> addCloudConfig(CloudConfiguration sourceCloudConfiguration) {
- CloudConfiguration targetConfiguration = new CloudConfiguration();
- if(sourceCloudConfiguration != null) {
- targetConfiguration.setAicNodeClli(sourceCloudConfiguration.getAicNodeClli());
- targetConfiguration.setTenantId(sourceCloudConfiguration.getTenantId());
- targetConfiguration.setLcpCloudRegionId(sourceCloudConfiguration.getLcpCloudRegionId());
- targetConfiguration.setCloudOwner(sourceCloudConfiguration.getCloudOwner());
- return Optional.of(targetConfiguration);
- }
- return Optional.empty();
- }
-
- protected List<Map<String, Object>> configureUserParams(RequestParameters reqParams) throws IOException {
- logger.debug("Configuring UserParams for Macro Request");
- Map<String, Object> userParams = new HashMap<>();
-
- for(Map<String, Object> params : reqParams.getUserParams()){
- if(params.containsKey("service")){
- Service service = serviceMapper(params);
-
- addUserParams(userParams, service.getInstanceParams());
-
- for(Networks network : service.getResources().getNetworks()) {
- addUserParams(userParams, network.getInstanceParams());
- }
-
- for(Vnfs vnf: service.getResources().getVnfs()) {
- addUserParams(userParams, vnf.getInstanceParams());
-
- for(VfModules vfModule: vnf.getVfModules()) {
- addUserParams(userParams, vfModule.getInstanceParams());
- }
- }
- }
- }
-
- return mapFlatMapToNameValue(userParams);
+ }
+ return recipeLookupResult;
+ }
+
+ private RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, boolean alaCarteFlag)
+ throws IOException {
+ // SERVICE REQUEST
+ // Construct the default service name
+ // TODO need to make this a configurable property
+ String defaultServiceModelName = requestHandlerUtils.getDefaultModel(servInstReq);
+ RequestDetails requestDetails = servInstReq.getRequestDetails();
+ ModelInfo modelInfo = requestDetails.getModelInfo();
+ org.onap.so.db.catalog.beans.Service serviceRecord;
+ List<org.onap.so.db.catalog.beans.Service> serviceRecordList;
+ ServiceRecipe recipe = null;
+
+ if (alaCarteFlag) {
+ serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
+ if (serviceRecord != null) {
+ recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),
+ action.toString());
+ }
+ } else {
+ serviceRecord = catalogDbClient.getServiceByID(modelInfo.getModelVersionId());
+ recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(modelInfo.getModelVersionId(),
+ action.toString());
+ if (recipe == null) {
+ serviceRecordList = catalogDbClient
+ .getServiceByModelInvariantUUIDOrderByModelVersionDesc(modelInfo.getModelInvariantId());
+ if (!serviceRecordList.isEmpty()) {
+ for (org.onap.so.db.catalog.beans.Service record : serviceRecordList) {
+ recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(record.getModelUUID(),
+ action.toString());
+ if (recipe != null) {
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ // if an aLaCarte flag was sent in the request, throw an error if the recipe was not found
+ RequestParameters reqParam = requestDetails.getRequestParameters();
+ if (reqParam != null && alaCarteFlag && recipe == null) {
+ return null;
+ } else if (!alaCarteFlag && recipe != null && Action.createInstance.equals(action)) {
+ mapToLegacyRequest(requestDetails);
+ } else if (recipe == null) { // aLaCarte wasn't sent, so we'll try the default
+ serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
+ recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),
+ action.toString());
+ }
+ if (modelInfo.getModelVersionId() == null) {
+ modelInfo.setModelVersionId(serviceRecord.getModelUUID());
+ }
+ if (recipe == null) {
+ return null;
+ }
+ return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());
+ }
+
+ protected void mapToLegacyRequest(RequestDetails requestDetails) throws IOException {
+ RequestParameters reqParam;
+ if (requestDetails.getRequestParameters() == null) {
+ reqParam = new RequestParameters();
+ } else {
+ reqParam = requestDetails.getRequestParameters();
+ }
+ if (requestDetails.getCloudConfiguration() == null) {
+ CloudConfiguration cloudConfig = configureCloudConfig(reqParam);
+ if (cloudConfig != null) {
+ requestDetails.setCloudConfiguration(cloudConfig);
+ }
+ }
+
+ List<Map<String, Object>> userParams = configureUserParams(reqParam);
+ if (!userParams.isEmpty()) {
+ if (reqParam == null) {
+ requestDetails.setRequestParameters(new RequestParameters());
+ }
+ requestDetails.getRequestParameters().setUserParams(userParams);
+ }
+ }
+
+ protected CloudConfiguration configureCloudConfig(RequestParameters reqParams) throws IOException {
+
+ for (Map<String, Object> params : reqParams.getUserParams()) {
+ if (params.containsKey("service")) {
+ Service service = serviceMapper(params);
+
+ Optional<CloudConfiguration> targetConfiguration = addCloudConfig(service.getCloudConfiguration());
+
+ if (targetConfiguration.isPresent()) {
+ return targetConfiguration.get();
+ } else {
+ for (Networks network : service.getResources().getNetworks()) {
+ targetConfiguration = addCloudConfig(network.getCloudConfiguration());
+ if (targetConfiguration.isPresent()) {
+ return targetConfiguration.get();
+ }
+ }
+
+ for (Vnfs vnf : service.getResources().getVnfs()) {
+ targetConfiguration = addCloudConfig(vnf.getCloudConfiguration());
+
+ if (targetConfiguration.isPresent()) {
+ return targetConfiguration.get();
+ }
+
+ for (VfModules vfModule : vnf.getVfModules()) {
+ targetConfiguration = addCloudConfig(vfModule.getCloudConfiguration());
+
+ if (targetConfiguration.isPresent()) {
+ return targetConfiguration.get();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private Optional<CloudConfiguration> addCloudConfig(CloudConfiguration sourceCloudConfiguration) {
+ CloudConfiguration targetConfiguration = new CloudConfiguration();
+ if (sourceCloudConfiguration != null) {
+ targetConfiguration.setAicNodeClli(sourceCloudConfiguration.getAicNodeClli());
+ targetConfiguration.setTenantId(sourceCloudConfiguration.getTenantId());
+ targetConfiguration.setLcpCloudRegionId(sourceCloudConfiguration.getLcpCloudRegionId());
+ targetConfiguration.setCloudOwner(sourceCloudConfiguration.getCloudOwner());
+ return Optional.of(targetConfiguration);
+ }
+ return Optional.empty();
+ }
+
+ protected List<Map<String, Object>> configureUserParams(RequestParameters reqParams) throws IOException {
+ logger.debug("Configuring UserParams for Macro Request");
+ Map<String, Object> userParams = new HashMap<>();
+
+ for (Map<String, Object> params : reqParams.getUserParams()) {
+ if (params.containsKey("service")) {
+ Service service = serviceMapper(params);
+
+ addUserParams(userParams, service.getInstanceParams());
+
+ for (Networks network : service.getResources().getNetworks()) {
+ addUserParams(userParams, network.getInstanceParams());
+ }
+
+ for (Vnfs vnf : service.getResources().getVnfs()) {
+ addUserParams(userParams, vnf.getInstanceParams());
+
+ for (VfModules vfModule : vnf.getVfModules()) {
+ addUserParams(userParams, vfModule.getInstanceParams());
+ }
+ }
+ }
+ }
+
+ return mapFlatMapToNameValue(userParams);
}
- private Service serviceMapper(Map<String, Object> params)
- throws JsonProcessingException, IOException, JsonParseException, JsonMappingException {
- ObjectMapper obj = new ObjectMapper();
- String input = obj.writeValueAsString(params.get("service"));
- return obj.readValue(input, Service.class);
- }
-
- private void addUserParams(Map<String, Object> targetUserParams, List<Map<String, String>> sourceUserParams) {
- for(Map<String, String> map : sourceUserParams) {
- for (Map.Entry<String, String> entry : map.entrySet()) {
- targetUserParams.put(entry.getKey(), entry.getValue());
- }
- }
- }
-
- protected List<Map<String, Object>> mapFlatMapToNameValue(Map<String, Object> flatMap) {
- List<Map<String, Object>> targetUserParams = new ArrayList<>();
-
- for(Map.Entry<String, Object> map : flatMap.entrySet()) {
- Map<String, Object> targetMap = new HashMap<>();
- targetMap.put(NAME, map.getKey());
- targetMap.put(VALUE, map.getValue());
- targetUserParams.add(targetMap);
- }
- return targetUserParams;
- }
-
- private RecipeLookupResult getVnfOrVfModuleUri(ServiceInstancesRequest servInstReq, Actions action) throws ValidationException {
-
- ModelInfo modelInfo = servInstReq.getRequestDetails().getModelInfo();
- String vnfComponentType = modelInfo.getModelType().name();
-
- RelatedInstanceList[] instanceList = null;
- if (servInstReq.getRequestDetails() != null) {
- instanceList = servInstReq.getRequestDetails().getRelatedInstanceList();
- }
-
- Recipe recipe = null;
- String defaultSource = requestHandlerUtils.getDefaultModel(servInstReq);
- String modelCustomizationId = modelInfo.getModelCustomizationId();
- String modelCustomizationName = modelInfo.getModelCustomizationName();
- String relatedInstanceModelVersionId = null;
- String relatedInstanceModelInvariantId = null;
- String relatedInstanceVersion = null;
- String relatedInstanceModelCustomizationName = null;
-
- if (instanceList != null) {
-
- for(RelatedInstanceList relatedInstanceList : instanceList){
-
- RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
- ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo();
- if(relatedInstanceModelInfo.getModelType().equals(ModelType.service)){
- relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
- relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
- }
-
- if(relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)){
- relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
- relatedInstanceModelInvariantId = relatedInstanceModelInfo.getModelInvariantId();
- relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
- relatedInstanceModelCustomizationName = relatedInstanceModelInfo.getModelCustomizationName();
- }
- }
-
- if(modelInfo.getModelType().equals(ModelType.vnf)) {
- // a. For a vnf request (only create, no update currently):
- // i. (v3-v4) If modelInfo.modelCustomizationId is provided, use it to validate catalog DB has record in vnf_resource_customization.model_customization_uuid.
- // ii. (v2-v4) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or pre-v3), then modelInfo.modelCustomizationName must have
- // been provided (else create request should be rejected). APIH should use the relatedInstance.modelInfo[service].modelVersionId** + modelInfo[vnf].modelCustomizationName
- // to “join�? service_to_resource_customizations with vnf_resource_customization to confirm a vnf_resource_customization.model_customization_uuid record exists.
- // **If relatedInstance.modelInfo[service].modelVersionId was not provided, use relatedInstance.modelInfo[service].modelInvariantId + modelVersion instead to lookup modelVersionId
- // (MODEL_UUID) in SERVICE table.
- // iii. Regardless of how the value was provided/obtained above, APIH must always populate vnfModelCustomizationId in bpmnRequest. It would be assumed it was MSO generated
- // during 1707 data migration if VID did not provide it originally on request.
- // iv. Note: continue to construct the “vnf-type�? value and pass to BPMN (must still be populated in A&AI).
- // 1. If modelCustomizationName is NOT provided on a vnf/vfModule request, use modelCustomizationId to look it up in our catalog to construct vnf-type value to pass to BPMN.
-
- VnfResource vnfResource = null;
- VnfResourceCustomization vrc=null;
- // Validation for vnfResource
-
- if(modelCustomizationId!=null) {
+ private Service serviceMapper(Map<String, Object> params)
+ throws JsonProcessingException, IOException, JsonParseException, JsonMappingException {
+ ObjectMapper obj = new ObjectMapper();
+ String input = obj.writeValueAsString(params.get("service"));
+ return obj.readValue(input, Service.class);
+ }
+
+ private void addUserParams(Map<String, Object> targetUserParams, List<Map<String, String>> sourceUserParams) {
+ for (Map<String, String> map : sourceUserParams) {
+ for (Map.Entry<String, String> entry : map.entrySet()) {
+ targetUserParams.put(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+
+ protected List<Map<String, Object>> mapFlatMapToNameValue(Map<String, Object> flatMap) {
+ List<Map<String, Object>> targetUserParams = new ArrayList<>();
+
+ for (Map.Entry<String, Object> map : flatMap.entrySet()) {
+ Map<String, Object> targetMap = new HashMap<>();
+ targetMap.put(NAME, map.getKey());
+ targetMap.put(VALUE, map.getValue());
+ targetUserParams.add(targetMap);
+ }
+ return targetUserParams;
+ }
+
+ private RecipeLookupResult getVnfOrVfModuleUri(ServiceInstancesRequest servInstReq, Actions action)
+ throws ValidationException {
+
+ ModelInfo modelInfo = servInstReq.getRequestDetails().getModelInfo();
+ String vnfComponentType = modelInfo.getModelType().name();
+
+ RelatedInstanceList[] instanceList = null;
+ if (servInstReq.getRequestDetails() != null) {
+ instanceList = servInstReq.getRequestDetails().getRelatedInstanceList();
+ }
+
+ Recipe recipe = null;
+ String defaultSource = requestHandlerUtils.getDefaultModel(servInstReq);
+ String modelCustomizationId = modelInfo.getModelCustomizationId();
+ String modelCustomizationName = modelInfo.getModelCustomizationName();
+ String relatedInstanceModelVersionId = null;
+ String relatedInstanceModelInvariantId = null;
+ String relatedInstanceVersion = null;
+ String relatedInstanceModelCustomizationName = null;
+
+ if (instanceList != null) {
+
+ for (RelatedInstanceList relatedInstanceList : instanceList) {
+
+ RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
+ ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo();
+ if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
+ relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
+ relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
+ }
+
+ if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
+ relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
+ relatedInstanceModelInvariantId = relatedInstanceModelInfo.getModelInvariantId();
+ relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
+ relatedInstanceModelCustomizationName = relatedInstanceModelInfo.getModelCustomizationName();
+ }
+ }
+
+ if (modelInfo.getModelType().equals(ModelType.vnf)) {
+ // a. For a vnf request (only create, no update currently):
+ // i. (v3-v4) If modelInfo.modelCustomizationId is provided, use it to validate catalog DB has record in
+ // vnf_resource_customization.model_customization_uuid.
+ // ii. (v2-v4) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or
+ // pre-v3), then modelInfo.modelCustomizationName must have
+ // been provided (else create request should be rejected). APIH should use the
+ // relatedInstance.modelInfo[service].modelVersionId** + modelInfo[vnf].modelCustomizationName
+ // to “join�? service_to_resource_customizations with vnf_resource_customization to confirm a
+ // vnf_resource_customization.model_customization_uuid record exists.
+ // **If relatedInstance.modelInfo[service].modelVersionId was not provided, use
+ // relatedInstance.modelInfo[service].modelInvariantId + modelVersion instead to lookup modelVersionId
+ // (MODEL_UUID) in SERVICE table.
+ // iii. Regardless of how the value was provided/obtained above, APIH must always populate
+ // vnfModelCustomizationId in bpmnRequest. It would be assumed it was MSO generated
+ // during 1707 data migration if VID did not provide it originally on request.
+ // iv. Note: continue to construct the “vnf-type�? value and pass to BPMN (must still be populated
+ // in A&AI).
+ // 1. If modelCustomizationName is NOT provided on a vnf/vfModule request, use modelCustomizationId to
+ // look it up in our catalog to construct vnf-type value to pass to BPMN.
+
+ VnfResource vnfResource = null;
+ VnfResourceCustomization vrc = null;
+ // Validation for vnfResource
+
+ if (modelCustomizationId != null) {
vrc = catalogDbClient.getVnfResourceCustomizationByModelCustomizationUUID(modelCustomizationId);
- if(vrc != null){
- vnfResource = vrc.getVnfResources();
+ if (vrc != null) {
+ vnfResource = vrc.getVnfResources();
+ }
+ } else {
+ org.onap.so.db.catalog.beans.Service service =
+ catalogDbClient.getServiceByID(relatedInstanceModelVersionId);
+ if (service == null) {
+ service = catalogDbClient.getServiceByModelVersionAndModelInvariantUUID(relatedInstanceVersion,
+ relatedInstanceModelInvariantId);
+ }
+
+ if (service == null) {
+ throw new ValidationException("service in relatedInstance");
}
- } else {
- org.onap.so.db.catalog.beans.Service service = catalogDbClient.getServiceByID(relatedInstanceModelVersionId);
- if(service == null) {
- service = catalogDbClient.getServiceByModelVersionAndModelInvariantUUID(relatedInstanceVersion, relatedInstanceModelInvariantId);
- }
-
- if(service == null) {
- throw new ValidationException("service in relatedInstance");
- }
for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) {
if (vnfResourceCustom.getModelInstanceName().equals(modelCustomizationName)) {
- vrc=vnfResourceCustom;
+ vrc = vnfResourceCustom;
}
}
-
- if(vrc != null) {
- vnfResource = vrc.getVnfResources();
+
+ if (vrc != null) {
+ vnfResource = vrc.getVnfResources();
modelInfo.setModelCustomizationId(vrc.getModelCustomizationUUID());
modelInfo.setModelCustomizationUuid(vrc.getModelCustomizationUUID());
- }
- }
+ }
+ }
- if(vnfResource==null){
- throw new ValidationException("vnfResource");
- } else {
- if(modelInfo.getModelVersionId() == null) {
+ if (vnfResource == null) {
+ throw new ValidationException("vnfResource");
+ } else {
+ if (modelInfo.getModelVersionId() == null) {
modelInfo.setModelVersionId(vnfResource.getModelUUID());
- }
- }
-
- VnfRecipe vnfRecipe = null;
-
- if(vrc != null) {
- String nfRole = vrc.getNfRole();
- if(nfRole != null) {
- vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(vrc.getNfRole(), action.toString());
- }
- }
-
- if(vnfRecipe == null) {
- vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
- }
-
- if (vnfRecipe == null) {
- return null;
- }
-
- return new RecipeLookupResult (vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
- } else {
- /* (v5-v7) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or pre-v3), then modelInfo.modelCustomizationName must have
- // been provided (else create request should be rejected). APIH should use the relatedInstance.modelInfo[vnf].modelVersionId + modelInfo[vnf].modelCustomizationName
- // to join vnf_to_resource_customizations with vf_resource_customization to confirm a vf_resource_customization.model_customization_uuid record exists.
- // Once the vnfs model_customization_uuid has been obtained, use it to find all vfModule customizations for that vnf customization in the vnf_res_custom_to_vf_module_custom join table.
- // For each vf_module_cust_model_customization_uuid value returned, use that UUID to query vf_module_customization table along with modelInfo[vfModule|volumeGroup].modelVersionId to
- // confirm record matches request data (and to identify the modelCustomizationId associated with the vfModule in the request). This means taking each record found
- // in vf_module_customization and looking up in vf_module (using vf_module_customization’s FK into vf_module) to find a match on MODEL_INVARIANT_UUID (modelInvariantId)
- // and MODEL_VERSION (modelVersion).
- */
- VfModuleCustomization vfmc = null;
- VnfResource vnfr;
- VnfResourceCustomization vnfrc;
- VfModule vfModule = null;
-
- if(modelInfo.getModelCustomizationId() != null) {
- vfmc = catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID(modelInfo.getModelCustomizationId());
- } else {
- vnfr = catalogDbClient.getVnfResourceByModelUUID(relatedInstanceModelVersionId);
- if(vnfr == null){
- vnfr = catalogDbClient.getFirstVnfResourceByModelInvariantUUIDAndModelVersion(relatedInstanceModelInvariantId, relatedInstanceVersion);
- }
- vnfrc = catalogDbClient.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources(relatedInstanceModelCustomizationName, vnfr);
-
- List<VfModuleCustomization> list = vnfrc.getVfModuleCustomizations();
-
- String vfModuleModelUUID = modelInfo.getModelVersionId();
- for(VfModuleCustomization vf : list) {
- VfModuleCustomization vfmCustom;
- if(vfModuleModelUUID != null){
- vfmCustom = catalogDbClient.getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(vf.getModelCustomizationUUID(), vfModuleModelUUID);
- if(vfmCustom != null){
- vfModule = vfmCustom.getVfModule();
- }
- }else{
- vfmCustom = catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID(vf.getModelCustomizationUUID());
- if(vfmCustom != null){
- vfModule = vfmCustom.getVfModule();
- }else{
- vfModule = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(relatedInstanceModelInvariantId, relatedInstanceVersion);
- }
- }
-
- if(vfModule != null) {
- modelInfo.setModelCustomizationId(vf.getModelCustomizationUUID());
- modelInfo.setModelCustomizationUuid(vf.getModelCustomizationUUID());
- break;
- }
- }
- }
-
- if(vfmc == null && vfModule == null) {
- throw new ValidationException("vfModuleCustomization");
- } else if (vfModule == null && vfmc != null) {
- vfModule = vfmc.getVfModule(); // can't be null as vfModuleModelUUID is not-null property in VfModuleCustomization table
- }
-
- if(modelInfo.getModelVersionId() == null) {
- modelInfo.setModelVersionId(vfModule.getModelUUID());
- }
-
-
- recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(vfModule.getModelUUID(), vnfComponentType, action.toString());
- if(recipe == null){
- List<VfModule> vfModuleRecords= catalogDbClient.getVfModuleByModelInvariantUUIDOrderByModelVersionDesc(vfModule.getModelInvariantUUID());
- if(!vfModuleRecords.isEmpty()){
- for(VfModule record : vfModuleRecords){
- recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(record.getModelUUID(), vnfComponentType, action.toString());
- if(recipe != null){
- break;
- }
- }
- }
- }
- if(recipe == null) {
- recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(defaultSource, vnfComponentType, action.toString());
- if (recipe == null) {
- recipe = catalogDbClient.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction(vnfComponentType, action.toString());
- }
-
- if(recipe == null) {
- return null;
- }
- }
- }
- } else {
-
- if(modelInfo.getModelType().equals(ModelType.vnf)) {
- recipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
- if (recipe == null) {
- return null;
- }
- } else {
- recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(defaultSource, vnfComponentType, action.toString());
-
- if (recipe == null) {
- return null;
- }
- }
- }
-
- return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ());
- }
-
+ }
+ }
+
+ VnfRecipe vnfRecipe = null;
+
+ if (vrc != null) {
+ String nfRole = vrc.getNfRole();
+ if (nfRole != null) {
+ vnfRecipe =
+ catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(vrc.getNfRole(), action.toString());
+ }
+ }
+
+ if (vnfRecipe == null) {
+ vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
+ }
+
+ if (vnfRecipe == null) {
+ return null;
+ }
+
+ return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
+ } else {
+ /*
+ * (v5-v7) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or
+ * pre-v3), then modelInfo.modelCustomizationName must have // been provided (else create request should
+ * be rejected). APIH should use the relatedInstance.modelInfo[vnf].modelVersionId +
+ * modelInfo[vnf].modelCustomizationName // to join vnf_to_resource_customizations with
+ * vf_resource_customization to confirm a vf_resource_customization.model_customization_uuid record
+ * exists. // Once the vnfs model_customization_uuid has been obtained, use it to find all vfModule
+ * customizations for that vnf customization in the vnf_res_custom_to_vf_module_custom join table. //
+ * For each vf_module_cust_model_customization_uuid value returned, use that UUID to query
+ * vf_module_customization table along with modelInfo[vfModule|volumeGroup].modelVersionId to // confirm
+ * record matches request data (and to identify the modelCustomizationId associated with the vfModule in
+ * the request). This means taking each record found // in vf_module_customization and looking up in
+ * vf_module (using vf_module_customization’s FK into vf_module) to find a match on
+ * MODEL_INVARIANT_UUID (modelInvariantId) // and MODEL_VERSION (modelVersion).
+ */
+ VfModuleCustomization vfmc = null;
+ VnfResource vnfr;
+ VnfResourceCustomization vnfrc;
+ VfModule vfModule = null;
+
+ if (modelInfo.getModelCustomizationId() != null) {
+ vfmc = catalogDbClient
+ .getVfModuleCustomizationByModelCuztomizationUUID(modelInfo.getModelCustomizationId());
+ } else {
+ vnfr = catalogDbClient.getVnfResourceByModelUUID(relatedInstanceModelVersionId);
+ if (vnfr == null) {
+ vnfr = catalogDbClient.getFirstVnfResourceByModelInvariantUUIDAndModelVersion(
+ relatedInstanceModelInvariantId, relatedInstanceVersion);
+ }
+ vnfrc = catalogDbClient.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources(
+ relatedInstanceModelCustomizationName, vnfr);
+
+ List<VfModuleCustomization> list = vnfrc.getVfModuleCustomizations();
+
+ String vfModuleModelUUID = modelInfo.getModelVersionId();
+ for (VfModuleCustomization vf : list) {
+ VfModuleCustomization vfmCustom;
+ if (vfModuleModelUUID != null) {
+ vfmCustom = catalogDbClient
+ .getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
+ vf.getModelCustomizationUUID(), vfModuleModelUUID);
+ if (vfmCustom != null) {
+ vfModule = vfmCustom.getVfModule();
+ }
+ } else {
+ vfmCustom = catalogDbClient
+ .getVfModuleCustomizationByModelCuztomizationUUID(vf.getModelCustomizationUUID());
+ if (vfmCustom != null) {
+ vfModule = vfmCustom.getVfModule();
+ } else {
+ vfModule = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(
+ relatedInstanceModelInvariantId, relatedInstanceVersion);
+ }
+ }
+
+ if (vfModule != null) {
+ modelInfo.setModelCustomizationId(vf.getModelCustomizationUUID());
+ modelInfo.setModelCustomizationUuid(vf.getModelCustomizationUUID());
+ break;
+ }
+ }
+ }
+
+ if (vfmc == null && vfModule == null) {
+ throw new ValidationException("vfModuleCustomization");
+ } else if (vfModule == null && vfmc != null) {
+ vfModule = vfmc.getVfModule(); // can't be null as vfModuleModelUUID is not-null property in
+ // VfModuleCustomization table
+ }
+
+ if (modelInfo.getModelVersionId() == null) {
+ modelInfo.setModelVersionId(vfModule.getModelUUID());
+ }
+
+
+ recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+ vfModule.getModelUUID(), vnfComponentType, action.toString());
+ if (recipe == null) {
+ List<VfModule> vfModuleRecords = catalogDbClient
+ .getVfModuleByModelInvariantUUIDOrderByModelVersionDesc(vfModule.getModelInvariantUUID());
+ if (!vfModuleRecords.isEmpty()) {
+ for (VfModule record : vfModuleRecords) {
+ recipe = catalogDbClient
+ .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+ record.getModelUUID(), vnfComponentType, action.toString());
+ if (recipe != null) {
+ break;
+ }
+ }
+ }
+ }
+ if (recipe == null) {
+ recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+ defaultSource, vnfComponentType, action.toString());
+ if (recipe == null) {
+ recipe = catalogDbClient.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction(
+ vnfComponentType, action.toString());
+ }
+
+ if (recipe == null) {
+ return null;
+ }
+ }
+ }
+ } else {
+
+ if (modelInfo.getModelType().equals(ModelType.vnf)) {
+ recipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
+ if (recipe == null) {
+ return null;
+ }
+ } else {
+ recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+ defaultSource, vnfComponentType, action.toString());
+
+ if (recipe == null) {
+ return null;
+ }
+ }
+ }
+
+ return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());
+ }
+
private RecipeLookupResult getDefaultVnfUri(ServiceInstancesRequest sir, Actions action) {
-
- String defaultSource = requestHandlerUtils.getDefaultModel(sir);
- VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
+ String defaultSource = requestHandlerUtils.getDefaultModel(sir);
+
+ VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
- if (vnfRecipe == null) {
- return null;
- }
+ if (vnfRecipe == null) {
+ return null;
+ }
- return new RecipeLookupResult (vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
- }
+ return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
+ }
private RecipeLookupResult getNetworkUri(ServiceInstancesRequest sir, Actions action) throws ValidationException {
- String defaultNetworkType = requestHandlerUtils.getDefaultModel(sir);
-
- ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
- String modelName = modelInfo.getModelName();
- Recipe recipe = null;
-
- if(modelInfo.getModelCustomizationId()!=null){
- NetworkResourceCustomization networkResourceCustomization = catalogDbClient.getNetworkResourceCustomizationByModelCustomizationUUID(modelInfo.getModelCustomizationId());
- if(networkResourceCustomization != null){
- NetworkResource networkResource = networkResourceCustomization.getNetworkResource();
- if(networkResource!=null){
- if(modelInfo.getModelVersionId() == null) {
- modelInfo.setModelVersionId(networkResource.getModelUUID());
- }
- recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(networkResource.getModelName(), action.toString());
- }else{
- throw new ValidationException("no catalog entry found");
- }
- }else if(action != Action.deleteInstance){
- throw new ValidationException("modelCustomizationId for networkResourceCustomization lookup", true);
- }
- }else{
- //ok for version < 3 and action delete
- if(modelName != null){
- recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(modelName, action.toString());
- }
- }
-
- if(recipe == null){
- recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(defaultNetworkType, action.toString());
- }
-
- return recipe !=null ? new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()) : null;
- }
-
-
- private Response configurationRecipeLookup(String requestJSON, Action action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException {
- String serviceInstanceId = (instanceIdMap ==null)? null:instanceIdMap.get("serviceInstanceId");
- Boolean aLaCarte = null;
- String apiVersion = version.substring(1);
- boolean inProgress = false;
-
- long startTime = System.currentTimeMillis ();
- ServiceInstancesRequest sir = null;
-
- sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, requestId, requestUri);
- String requestScope = requestHandlerUtils.deriveRequestScope(action,sir, requestUri);
- InfraActiveRequests currentActiveReq = msoRequest.createRequestObject ( sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
- if(sir.getRequestDetails().getRequestParameters() != null){
- aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte();
- }
- requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, currentActiveReq);
- requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap);
- String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName();
-
- InfraActiveRequests dup = null;
-
- dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,requestScope, currentActiveReq);
-
- if(dup != null){
- inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
- }
-
- if (instanceIdMap != null && dup != null && inProgress) {
- requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, instanceName, requestScope, dup);
- }
-
- ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
- RequestReferences referencesResponse = new RequestReferences();
- referencesResponse.setRequestId(requestId);
- serviceResponse.setRequestReferences(referencesResponse);
-
-
- String orchestrationUri = env.getProperty(CommonConstants.ALACARTE_ORCHESTRATION);
- String timeOut = env.getProperty(CommonConstants.ALACARTE_RECIPE_TIMEOUT);
-
- if (StringUtils.isBlank(orchestrationUri) || StringUtils.isBlank(timeOut)) {
- String error = StringUtils.isBlank(orchestrationUri) ? "ALaCarte Orchestration URI not found in properties" : "ALaCarte Recipe Timeout not found in properties";
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-
-
- ValidateException validateException = new ValidateException.Builder(error, HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR)
- .errorInfo(errorLoggerInfo).build();
+ String defaultNetworkType = requestHandlerUtils.getDefaultModel(sir);
+
+ ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
+ String modelName = modelInfo.getModelName();
+ Recipe recipe = null;
+
+ if (modelInfo.getModelCustomizationId() != null) {
+ NetworkResourceCustomization networkResourceCustomization = catalogDbClient
+ .getNetworkResourceCustomizationByModelCustomizationUUID(modelInfo.getModelCustomizationId());
+ if (networkResourceCustomization != null) {
+ NetworkResource networkResource = networkResourceCustomization.getNetworkResource();
+ if (networkResource != null) {
+ if (modelInfo.getModelVersionId() == null) {
+ modelInfo.setModelVersionId(networkResource.getModelUUID());
+ }
+ recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(networkResource.getModelName(),
+ action.toString());
+ } else {
+ throw new ValidationException("no catalog entry found");
+ }
+ } else if (action != Action.deleteInstance) {
+ throw new ValidationException("modelCustomizationId for networkResourceCustomization lookup", true);
+ }
+ } else {
+ // ok for version < 3 and action delete
+ if (modelName != null) {
+ recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(modelName, action.toString());
+ }
+ }
+
+ if (recipe == null) {
+ recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(defaultNetworkType, action.toString());
+ }
+
+ return recipe != null ? new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()) : null;
+ }
+
+
+ private Response configurationRecipeLookup(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
+ String version, String requestId, String requestUri) throws ApiException {
+ String serviceInstanceId = (instanceIdMap == null) ? null : instanceIdMap.get("serviceInstanceId");
+ Boolean aLaCarte = null;
+ String apiVersion = version.substring(1);
+ boolean inProgress = false;
+
+ long startTime = System.currentTimeMillis();
+ ServiceInstancesRequest sir = null;
+
+ sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest,
+ requestId, requestUri);
+ String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri);
+ InfraActiveRequests currentActiveReq =
+ msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
+ if (sir.getRequestDetails().getRequestParameters() != null) {
+ aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte();
+ }
+ requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId,
+ currentActiveReq);
+ requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap);
+ String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName();
+
+ InfraActiveRequests dup = null;
+
+ dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,
+ requestScope, currentActiveReq);
+
+ if (dup != null) {
+ inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
+ }
+
+ if (instanceIdMap != null && dup != null && inProgress) {
+ requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime,
+ msoRequest, instanceName, requestScope, dup);
+ }
+
+ ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
+ RequestReferences referencesResponse = new RequestReferences();
+ referencesResponse.setRequestId(requestId);
+ serviceResponse.setRequestReferences(referencesResponse);
+
+
+ String orchestrationUri = env.getProperty(CommonConstants.ALACARTE_ORCHESTRATION);
+ String timeOut = env.getProperty(CommonConstants.ALACARTE_RECIPE_TIMEOUT);
+
+ if (StringUtils.isBlank(orchestrationUri) || StringUtils.isBlank(timeOut)) {
+ String error = StringUtils.isBlank(orchestrationUri) ? "ALaCarte Orchestration URI not found in properties"
+ : "ALaCarte Recipe Timeout not found in properties";
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+
+ ValidateException validateException = new ValidateException.Builder(error, HttpStatus.SC_NOT_FOUND,
+ ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
throw validateException;
-
- }
-
- serviceInstanceId = "";
- String configurationId = "";
- String pnfCorrelationId = "";
-
- if(sir.getServiceInstanceId () != null){
- serviceInstanceId = sir.getServiceInstanceId ();
- }
-
- if(sir.getConfigurationId() != null){
+
+ }
+
+ serviceInstanceId = "";
+ String configurationId = "";
+ String pnfCorrelationId = "";
+
+ if (sir.getServiceInstanceId() != null) {
+ serviceInstanceId = sir.getServiceInstanceId();
+ }
+
+ if (sir.getConfigurationId() != null) {
configurationId = sir.getConfigurationId();
}
pnfCorrelationId = getPnfCorrelationId(sir);
- try{
- infraActiveRequestsClient.save(currentActiveReq);
- }catch(Exception e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
- .errorInfo(errorLoggerInfo).build();
- }
-
- if(!requestScope.equalsIgnoreCase(ModelType.service.name())){
- aLaCarte = true;
- }else if(aLaCarte == null){
- aLaCarte = false;
- }
- RequestClientParameter requestClientParameter = null;
- try {
- requestClientParameter = new RequestClientParameter.Builder()
- .setRequestId(requestId)
- .setBaseVfModule(false)
- .setRecipeTimeout(Integer.parseInt(timeOut))
- .setRequestAction(action.toString())
- .setServiceInstanceId(serviceInstanceId)
- .setPnfCorrelationId(pnfCorrelationId)
- .setConfigurationId(configurationId)
- .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action))
- .setApiVersion(apiVersion)
- .setALaCarte(aLaCarte)
- .setRequestUri(requestUri).build();
- } catch (IOException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER)
- .errorInfo(errorLoggerInfo).build();
- }
-
- return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, orchestrationUri, requestScope);
- }
-
+ try {
+ infraActiveRequestsClient.save(currentActiveReq);
+ } catch (Exception e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
+ }
+
+ if (!requestScope.equalsIgnoreCase(ModelType.service.name())) {
+ aLaCarte = true;
+ } else if (aLaCarte == null) {
+ aLaCarte = false;
+ }
+ RequestClientParameter requestClientParameter = null;
+ try {
+ requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId).setBaseVfModule(false)
+ .setRecipeTimeout(Integer.parseInt(timeOut)).setRequestAction(action.toString())
+ .setServiceInstanceId(serviceInstanceId).setPnfCorrelationId(pnfCorrelationId)
+ .setConfigurationId(configurationId)
+ .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action))
+ .setApiVersion(apiVersion).setALaCarte(aLaCarte).setRequestUri(requestUri).build();
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(),
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
+ .build();
+ }
+
+ return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, orchestrationUri,
+ requestScope);
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SubsystemHealthcheckResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SubsystemHealthcheckResponse.java
index 625df66d2a..8b25018ee7 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SubsystemHealthcheckResponse.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SubsystemHealthcheckResponse.java
@@ -22,15 +22,15 @@ package org.onap.so.apihandlerinfra;
import java.io.Serializable;
public class SubsystemHealthcheckResponse implements Serializable {
- private static final long serialVersionUID = 1L;
- private String status;
+ private static final long serialVersionUID = 1L;
+ private String status;
- public String getStatus() {
- return status;
- }
+ public String getStatus() {
+ return status;
+ }
- public void setStatus(String status) {
- this.status = status;
- }
+ public void setStatus(String status) {
+ this.status = status;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java
index b7bd28f45f..7bd7f95286 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java
@@ -26,7 +26,6 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-
import javax.transaction.Transactional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@@ -34,7 +33,6 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
-
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
@@ -48,7 +46,6 @@ import org.onap.so.apihandler.common.ResponseHandler;
import org.onap.so.apihandlerinfra.exceptions.ApiException;
import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException;
import org.onap.so.apihandlerinfra.exceptions.ValidateException;
-
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
import org.onap.so.apihandlerinfra.tasksbeans.TaskList;
import org.onap.so.apihandlerinfra.tasksbeans.TaskVariableValue;
@@ -56,264 +53,279 @@ import org.onap.so.apihandlerinfra.tasksbeans.TaskVariables;
import org.onap.so.apihandlerinfra.tasksbeans.TasksGetResponse;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Path("onap/so/infra/tasks")
-@Api(value="onap/so/infra/tasks",description="Queries of Manual Tasks")
+@Api(value = "onap/so/infra/tasks", description = "Queries of Manual Tasks")
@Component
public class TasksHandler {
private static Logger logger = LoggerFactory.getLogger(TasksHandler.class);
-
+
@Value("${mso.camunda.rest.task.uri}")
private String requestUrl;
-
- @Autowired
- private RequestClientFactory reqClientFactory;
- @Autowired
- private ResponseBuilder builder;
-
+ @Autowired
+ private RequestClientFactory reqClientFactory;
+
+ @Autowired
+ private ResponseBuilder builder;
+
@Path("/{version:[vV]1}")
@GET
- @ApiOperation(value="Finds Manual Tasks",response=Response.class)
+ @ApiOperation(value = "Finds Manual Tasks", response = Response.class)
@Transactional
- public Response queryFilters (@QueryParam("taskId") String taskId,
- @QueryParam("originalRequestId") String originalRequestId,
- @QueryParam("subscriptionServiceType") String subscriptionServiceType,
- @QueryParam("nfRole") String nfRole,
- @QueryParam("buildingBlockName") String buildingBlockName,
- @QueryParam("originalRequestDate") String originalRequestDate,
- @QueryParam("originalRequestorId") String originalRequestorId,
- @PathParam("version") String version) throws ApiException {
- Response responseBack = null;
- String apiVersion = version.substring(1);
+ public Response queryFilters(@QueryParam("taskId") String taskId,
+ @QueryParam("originalRequestId") String originalRequestId,
+ @QueryParam("subscriptionServiceType") String subscriptionServiceType, @QueryParam("nfRole") String nfRole,
+ @QueryParam("buildingBlockName") String buildingBlockName,
+ @QueryParam("originalRequestDate") String originalRequestDate,
+ @QueryParam("originalRequestorId") String originalRequestorId, @PathParam("version") String version)
+ throws ApiException {
+ Response responseBack = null;
+ String apiVersion = version.substring(1);
// Prepare the query string to /task interface
TaskVariables tv = new TaskVariables();
-
+
List<TaskVariableValue> tvvList = new ArrayList<>();
-
+
if (originalRequestId != null) {
- TaskVariableValue tvv = new TaskVariableValue();
- tvv.setName("originalRequestId");
- tvv.setValue(originalRequestId);
- tvv.setOperator("eq");
- tvvList.add(tvv);
+ TaskVariableValue tvv = new TaskVariableValue();
+ tvv.setName("originalRequestId");
+ tvv.setValue(originalRequestId);
+ tvv.setOperator("eq");
+ tvvList.add(tvv);
}
if (subscriptionServiceType != null) {
- TaskVariableValue tvv = new TaskVariableValue();
- tvv.setName("subscriptionServiceType");
- tvv.setValue(subscriptionServiceType);
- tvv.setOperator("eq");
- tvvList.add(tvv);
+ TaskVariableValue tvv = new TaskVariableValue();
+ tvv.setName("subscriptionServiceType");
+ tvv.setValue(subscriptionServiceType);
+ tvv.setOperator("eq");
+ tvvList.add(tvv);
}
if (nfRole != null) {
- TaskVariableValue tvv = new TaskVariableValue();
- tvv.setName("nfRole");
- tvv.setValue(nfRole);
- tvv.setOperator("eq");
- tvvList.add(tvv);
+ TaskVariableValue tvv = new TaskVariableValue();
+ tvv.setName("nfRole");
+ tvv.setValue(nfRole);
+ tvv.setOperator("eq");
+ tvvList.add(tvv);
}
if (buildingBlockName != null) {
- TaskVariableValue tvv = new TaskVariableValue();
- tvv.setName("buildingBlockName");
- tvv.setValue(buildingBlockName);
- tvv.setOperator("eq");
- tvvList.add(tvv);
+ TaskVariableValue tvv = new TaskVariableValue();
+ tvv.setName("buildingBlockName");
+ tvv.setValue(buildingBlockName);
+ tvv.setOperator("eq");
+ tvvList.add(tvv);
}
if (originalRequestDate != null) {
- TaskVariableValue tvv = new TaskVariableValue();
- tvv.setName("originalRequestDate");
- tvv.setValue(originalRequestDate);
- tvv.setOperator("eq");
- tvvList.add(tvv);
+ TaskVariableValue tvv = new TaskVariableValue();
+ tvv.setName("originalRequestDate");
+ tvv.setValue(originalRequestDate);
+ tvv.setOperator("eq");
+ tvvList.add(tvv);
}
if (originalRequestorId != null) {
- TaskVariableValue tvv = new TaskVariableValue();
- tvv.setName("originalRequestorId");
- tvv.setValue(originalRequestorId);
- tvv.setOperator("eq");
- tvvList.add(tvv);
- }
-
+ TaskVariableValue tvv = new TaskVariableValue();
+ tvv.setName("originalRequestorId");
+ tvv.setValue(originalRequestorId);
+ tvv.setOperator("eq");
+ tvvList.add(tvv);
+ }
+
tv.setTaskVariables(tvvList);
-
+
RequestClient requestClient = null;
-
- HttpResponse response = null;
-
- try {
- requestClient = reqClientFactory.getRequestClient(requestUrl);
- // Capture audit event
- ObjectMapper mapper = new ObjectMapper();
- String camundaJsonReq = mapper.writeValueAsString(tv);
- response = requestClient.post(camundaJsonReq);
-
- } catch(JsonProcessingException e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build();
-
-
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
-
- throw validateException;
- } catch(IOException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).build();
- BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
- throw bpmnFailureException;
- }
- TasksGetResponse trr = new TasksGetResponse();
- List<TaskList> taskList = new ArrayList<>();
-
- ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
- int bpelStatus = respHandler.getStatus ();
- if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {
- String respBody = respHandler.getResponseBody();
- if (respBody != null) {
- JSONArray data = new JSONArray(respBody);
-
- for (int i=0; i<data.length();i++) {
- JSONObject taskEntry = data.getJSONObject(i);
- String id = taskEntry.getString("id");
- if (taskId != null && !taskId.equals(id)) {
- continue;
- }
- // Get variables info for each task ID
- TaskList taskListEntry = null;
- taskListEntry = getTaskInfo(id);
-
- taskList.add(taskListEntry);
-
- }
- trr.setTaskList(taskList);
- }
-
- } else {
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).build();
-
-
- BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
- .errorInfo(errorLoggerInfo).build();
-
- throw bpmnFailureException;
- }
-
- String jsonResponse = null;
- try {
- ObjectMapper mapper = new ObjectMapper();
- jsonResponse = mapper.writeValueAsString(trr);
- }
- catch (JsonProcessingException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build();
-
-
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
-
- throw validateException;
- }
-
- return builder.buildResponse(HttpStatus.SC_ACCEPTED, "", jsonResponse, apiVersion);
- }
+
+ HttpResponse response = null;
+
+ try {
+ requestClient = reqClientFactory.getRequestClient(requestUrl);
+ // Capture audit event
+ ObjectMapper mapper = new ObjectMapper();
+ String camundaJsonReq = mapper.writeValueAsString(tv);
+ response = requestClient.post(camundaJsonReq);
+
+ } catch (JsonProcessingException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+
+ throw validateException;
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
+ .build();
+ BPMNFailureException bpmnFailureException =
+ new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
+ HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
+ throw bpmnFailureException;
+ }
+ TasksGetResponse trr = new TasksGetResponse();
+ List<TaskList> taskList = new ArrayList<>();
+
+ ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
+ int bpelStatus = respHandler.getStatus();
+ if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {
+ String respBody = respHandler.getResponseBody();
+ if (respBody != null) {
+ JSONArray data = new JSONArray(respBody);
+
+ for (int i = 0; i < data.length(); i++) {
+ JSONObject taskEntry = data.getJSONObject(i);
+ String id = taskEntry.getString("id");
+ if (taskId != null && !taskId.equals(id)) {
+ continue;
+ }
+ // Get variables info for each task ID
+ TaskList taskListEntry = null;
+ taskListEntry = getTaskInfo(id);
+
+ taskList.add(taskListEntry);
+
+ }
+ trr.setTaskList(taskList);
+ }
+
+ } else {
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError)
+ .build();
+
+
+ BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
+ bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+
+ throw bpmnFailureException;
+ }
+
+ String jsonResponse = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ jsonResponse = mapper.writeValueAsString(trr);
+ } catch (JsonProcessingException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+
+ throw validateException;
+ }
+
+ return builder.buildResponse(HttpStatus.SC_ACCEPTED, "", jsonResponse, apiVersion);
+ }
// Makes a GET call to Camunda to get variables for this task
- private TaskList getTaskInfo(String taskId) throws ApiException{
- TaskList taskList;
- String getRequestUrl = UriBuilder.fromUri(requestUrl).path(taskId).path("variables").build().toString();
- HttpResponse getResponse;
-
- RequestClient requestClient = reqClientFactory.getRequestClient (getRequestUrl);
- // Capture audit event
- try {
- getResponse = requestClient.get();
- }catch(IOException e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).build();
- BPMNFailureException validateException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
- throw validateException;
- }
- ResponseHandler respHandler = new ResponseHandler (getResponse, requestClient.getType ());
- int bpelStatus = respHandler.getStatus ();
- if (bpelStatus == HttpStatus.SC_ACCEPTED) {
- String respBody = respHandler.getResponseBody();
- if (respBody != null) {
- taskList = buildTaskList(taskId, respBody);
- }
- else {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).build();
+ private TaskList getTaskInfo(String taskId) throws ApiException {
+ TaskList taskList;
+ String getRequestUrl = UriBuilder.fromUri(requestUrl).path(taskId).path("variables").build().toString();
+ HttpResponse getResponse;
+
+ RequestClient requestClient = reqClientFactory.getRequestClient(getRequestUrl);
+ // Capture audit event
+ try {
+ getResponse = requestClient.get();
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
+ .build();
+ BPMNFailureException validateException =
+ new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
+ HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
+ throw validateException;
+ }
+ ResponseHandler respHandler = new ResponseHandler(getResponse, requestClient.getType());
+ int bpelStatus = respHandler.getStatus();
+ if (bpelStatus == HttpStatus.SC_ACCEPTED) {
+ String respBody = respHandler.getResponseBody();
+ if (respBody != null) {
+ taskList = buildTaskList(taskId, respBody);
+ } else {
+ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
+ ErrorCode.AvailabilityError).build();
+ BPMNFailureException bpmnFailureException =
+ new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
+ HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
- BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
+ throw bpmnFailureException;
+ }
- throw bpmnFailureException;
- }
-
- }
- else {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).build();
+ } else {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
+ .build();
+ BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
+ bpelStatus, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
- BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
+ throw bpmnFailureException;
+ }
+
+ return taskList;
- throw bpmnFailureException;
- }
-
- return taskList;
-
}
-
+
private TaskList buildTaskList(String taskId, String respBody) throws JSONException {
- TaskList taskList = new TaskList();
- JSONObject variables = new JSONObject(respBody);
-
- taskList.setTaskId(taskId);
- taskList.setType(getOptVariableValue(variables, "type"));
- taskList.setNfRole(getOptVariableValue(variables, "nfRole"));
- taskList.setSubscriptionServiceType(getOptVariableValue(variables, "subscriptionServiceType"));
- taskList.setOriginalRequestId(getOptVariableValue(variables, "originalRequestId"));
- taskList.setOriginalRequestorId(getOptVariableValue(variables, "originalRequestorId"));
- taskList.setErrorSource(getOptVariableValue(variables, "errorSource"));
- taskList.setErrorCode(getOptVariableValue(variables, "errorCode"));
- taskList.setErrorMessage(getOptVariableValue(variables, "errorMessage"));
- taskList.setBuildingBlockName(getOptVariableValue(variables, "buildingBlockName"));
- taskList.setBuildingBlockStep(getOptVariableValue(variables, "buildingBlockStep"));
- taskList.setDescription(getOptVariableValue(variables, "description"));
- taskList.setTimeout(getOptVariableValue(variables, "timeout"));
-
- String validResponses = getOptVariableValue(variables, "validResponses").toLowerCase();
- List<String> items = Arrays.asList(validResponses.split("\\s*,\\s*"));
- taskList.setValidResponses(items);
-
- return taskList;
+ TaskList taskList = new TaskList();
+ JSONObject variables = new JSONObject(respBody);
+
+ taskList.setTaskId(taskId);
+ taskList.setType(getOptVariableValue(variables, "type"));
+ taskList.setNfRole(getOptVariableValue(variables, "nfRole"));
+ taskList.setSubscriptionServiceType(getOptVariableValue(variables, "subscriptionServiceType"));
+ taskList.setOriginalRequestId(getOptVariableValue(variables, "originalRequestId"));
+ taskList.setOriginalRequestorId(getOptVariableValue(variables, "originalRequestorId"));
+ taskList.setErrorSource(getOptVariableValue(variables, "errorSource"));
+ taskList.setErrorCode(getOptVariableValue(variables, "errorCode"));
+ taskList.setErrorMessage(getOptVariableValue(variables, "errorMessage"));
+ taskList.setBuildingBlockName(getOptVariableValue(variables, "buildingBlockName"));
+ taskList.setBuildingBlockStep(getOptVariableValue(variables, "buildingBlockStep"));
+ taskList.setDescription(getOptVariableValue(variables, "description"));
+ taskList.setTimeout(getOptVariableValue(variables, "timeout"));
+
+ String validResponses = getOptVariableValue(variables, "validResponses").toLowerCase();
+ List<String> items = Arrays.asList(validResponses.split("\\s*,\\s*"));
+ taskList.setValidResponses(items);
+
+ return taskList;
}
-
+
private String getOptVariableValue(JSONObject variables, String name) throws JSONException {
- String variableEntry = variables.optString(name);
- String value = "";
- if (!variableEntry.isEmpty()) {
- JSONObject variableEntryJson = new JSONObject(variableEntry);
- value = variableEntryJson.optString("value");
- }
- return value;
+ String variableEntry = variables.optString(name);
+ String value = "";
+ if (!variableEntry.isEmpty()) {
+ JSONObject variableEntryJson = new JSONObject(variableEntry);
+ value = variableEntryJson.optString("value");
+ }
+ return value;
}
-
-
+
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TestApi.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TestApi.java
index d2e96562ea..7497617e4d 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TestApi.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TestApi.java
@@ -21,17 +21,16 @@
package org.onap.so.apihandlerinfra;
public enum TestApi {
- GR_API("GR-API-DEFAULT"),
- VNF_API("VNF-API-DEFAULT");
-
- private final String modelName;
-
- private TestApi(String modelName) {
- this.modelName = modelName;
- }
-
- public String getModelName() {
- return modelName;
- }
+ GR_API("GR-API-DEFAULT"), VNF_API("VNF-API-DEFAULT");
+
+ private final String modelName;
+
+ private TestApi(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java
index aca0fa511e..97b80098e6 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java
@@ -34,24 +34,21 @@ import org.springframework.util.StringUtils;
@Configuration("att-security-config")
@Order(2)
public class WebSecurityConfigImpl extends WebSecurityConfig {
-
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf().disable()
- .authorizeRequests()
- .antMatchers("/manage/health","/manage/info").permitAll()
- .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),",").toString())
- .and()
- .httpBasic();
-
- }
-
- @Override
- public void configure(WebSecurity web) throws Exception {
- super.configure(web);
- StrictHttpFirewall firewall = new MSOSpringFirewall();
- web.httpFirewall(firewall);
- }
+
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll()
+ .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",").toString())
+ .and().httpBasic();
+
+ }
+
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ super.configure(web);
+ StrictHttpFirewall firewall = new MSOSpringFirewall();
+ web.httpFirewall(firewall);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java
index dba393dcd6..bc4f389469 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java
@@ -21,70 +21,68 @@ package org.onap.so.apihandlerinfra;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import javax.transaction.Transactional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
-
import org.onap.so.apihandler.common.ErrorNumbers;
import org.onap.so.apihandler.common.ResponseBuilder;
import org.onap.so.apihandlerinfra.exceptions.ValidateException;
-
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowSpecifications;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Path("onap/so/infra/workflowSpecifications")
-@Api(value="onap/so/infra/workflowSpecifications",description="Queries of Workflow Specifications")
+@Api(value = "onap/so/infra/workflowSpecifications", description = "Queries of Workflow Specifications")
@Component
public class WorkflowSpecificationsHandler {
@Autowired
- private ResponseBuilder builder;
-
+ private ResponseBuilder builder;
+
@Path("/{version:[vV]1}/workflows")
@GET
- @ApiOperation(value="Finds Workflow Specifications",response=Response.class)
+ @ApiOperation(value = "Finds Workflow Specifications", response = Response.class)
@Transactional
- public Response queryFilters (@QueryParam("vnfModelVersionId") String vnfModelVersionId,
- @PathParam("version") String version) throws Exception {
-
- String apiVersion = version.substring(1);
-
- ObjectMapper mapper1 = new ObjectMapper();
- mapper1.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-
- //Replace with Catalog DB Query
- WorkflowSpecifications workflowSpecifications = mapper1.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/__files/WorkflowSpecifications.json"))), WorkflowSpecifications.class);
-
- String jsonResponse = null;
- try {
- ObjectMapper mapper = new ObjectMapper();
- jsonResponse = mapper.writeValueAsString(workflowSpecifications);
- }
- catch (JsonProcessingException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build();
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
- throw validateException;
- }
-
- return builder.buildResponse(HttpStatus.SC_OK, "", jsonResponse, apiVersion);
- }
+ public Response queryFilters(@QueryParam("vnfModelVersionId") String vnfModelVersionId,
+ @PathParam("version") String version) throws Exception {
+
+ String apiVersion = version.substring(1);
+
+ ObjectMapper mapper1 = new ObjectMapper();
+ mapper1.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+
+ // Replace with Catalog DB Query
+ WorkflowSpecifications workflowSpecifications = mapper1.readValue(
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/WorkflowSpecifications.json"))),
+ WorkflowSpecifications.class);
+
+ String jsonResponse = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ jsonResponse = mapper.writeValueAsString(workflowSpecifications);
+ } catch (JsonProcessingException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ throw validateException;
+ }
+
+ return builder.buildResponse(HttpStatus.SC_OK, "", jsonResponse, apiVersion);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java
index 3aa54bdfb3..4d81695e55 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java
@@ -23,7 +23,6 @@ package org.onap.so.apihandlerinfra.configuration;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
-
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -40,41 +39,31 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "entityManagerFactory",
- basePackages = {"org.onap.so.db.catalog.data.repository"}
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory",
+ basePackages = {"org.onap.so.db.catalog.data.repository"})
@Profile({"!test"})
public class CatalogDBConfig {
-
- @Primary
- @Bean(name = "dataSource")
- @ConfigurationProperties(prefix = "spring.datasource")
- public DataSource dataSource() {
- return DataSourceBuilder.create().build();
- }
- @Primary
- @Bean(name = "entityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("dataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.catalog.beans")
- .persistenceUnit("catalogDB")
- .build();
- }
+ @Primary
+ @Bean(name = "dataSource")
+ @ConfigurationProperties(prefix = "spring.datasource")
+ public DataSource dataSource() {
+ return DataSourceBuilder.create().build();
+ }
+
+ @Primary
+ @Bean(name = "entityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("dataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.catalog.beans").persistenceUnit("catalogDB")
+ .build();
+ }
- @Primary
- @Bean(name = "transactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("entityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
+ @Primary
+ @Bean(name = "transactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java
index 908b864536..1bc54ffe7b 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java
@@ -23,7 +23,6 @@ package org.onap.so.apihandlerinfra.configuration;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
-
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -39,40 +38,30 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager",
- basePackages = { "org.onap.so.db.request.data.repository"}
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory",
+ transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"})
@Profile({"!test"})
public class RequestDBConfig {
- @Bean(name = "requestDataSource")
- @ConfigurationProperties(prefix = "request.datasource")
- public DataSource dataSource() {
- return DataSourceBuilder.create().build();
- }
+ @Bean(name = "requestDataSource")
+ @ConfigurationProperties(prefix = "request.datasource")
+ public DataSource dataSource() {
+ return DataSourceBuilder.create().build();
+ }
- @Bean(name = "requestEntityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("requestDataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.request.beans")
- .persistenceUnit("requestDB")
- .build();
- }
+ @Bean(name = "requestEntityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("requestDataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB")
+ .build();
+ }
- @Bean(name = "requestTransactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("requestEntityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
+ @Bean(name = "requestTransactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/CompareModelsRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/CompareModelsRequest.java
index 89482f7879..2bca89f980 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/CompareModelsRequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/CompareModelsRequest.java
@@ -25,44 +25,44 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class CompareModelsRequest {
- private String globalSubscriberId;
-
- private String serviceType;
+ private String globalSubscriberId;
- private String modelInvariantIdTarget;
-
- private String modelVersionIdTarget;
+ private String serviceType;
+ private String modelInvariantIdTarget;
- public String getGlobalSubscriberId() {
- return globalSubscriberId;
- }
+ private String modelVersionIdTarget;
- public void setGlobalSubscriberId(String globalSubscriberId) {
- this.globalSubscriberId = globalSubscriberId;
- }
- public String getServiceType() {
- return serviceType;
- }
+ public String getGlobalSubscriberId() {
+ return globalSubscriberId;
+ }
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
+ public void setGlobalSubscriberId(String globalSubscriberId) {
+ this.globalSubscriberId = globalSubscriberId;
+ }
- public String getModelInvariantIdTarget() {
- return modelInvariantIdTarget;
- }
+ public String getServiceType() {
+ return serviceType;
+ }
- public void setModelInvariantIdTarget(String modelInvariantIdTarget) {
- this.modelInvariantIdTarget = modelInvariantIdTarget;
- }
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
- public String getModelVersionIdTarget() {
- return modelVersionIdTarget;
- }
+ public String getModelInvariantIdTarget() {
+ return modelInvariantIdTarget;
+ }
- public void setModelVersionIdTarget(String modelVersionIdTarget) {
- this.modelVersionIdTarget = modelVersionIdTarget;
- }
+ public void setModelInvariantIdTarget(String modelInvariantIdTarget) {
+ this.modelInvariantIdTarget = modelInvariantIdTarget;
+ }
+
+ public String getModelVersionIdTarget() {
+ return modelVersionIdTarget;
+ }
+
+ public void setModelVersionIdTarget(String modelVersionIdTarget) {
+ this.modelVersionIdTarget = modelVersionIdTarget;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcResp.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcResp.java
index a2b410f57f..c620c379ec 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcResp.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcResp.java
@@ -25,13 +25,13 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class DelE2ESvcResp {
- private String operationId;
+ private String operationId;
- public String getOperationId() {
- return operationId;
- }
+ public String getOperationId() {
+ return operationId;
+ }
- public void setOperationId(String operationId) {
- this.operationId = operationId;
- }
+ public void setOperationId(String operationId) {
+ this.operationId = operationId;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EParameters.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EParameters.java
index 6dfa4b6587..6c8ac55523 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EParameters.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EParameters.java
@@ -23,41 +23,40 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-@JsonIgnoreProperties({ "additionalProperties" })
+@JsonIgnoreProperties({"additionalProperties"})
public class E2EParameters {
- @JsonProperty("locationConstraints")
- List<LocationConstraint> locationConstraints;
+ @JsonProperty("locationConstraints")
+ List<LocationConstraint> locationConstraints;
+
+ @JsonProperty("resources")
+ private List<ResourceRequest> resources;
- @JsonProperty("resources")
- private List<ResourceRequest> resources;
+ @JsonProperty("requestInputs")
+ private HashMap<String, ?> requestInputs;
- @JsonProperty("requestInputs")
- private HashMap<String, ?> requestInputs;
+ @JsonIgnore
+ private Map<String, Object> additionalProperties = new HashMap<>();
- @JsonIgnore
- private Map<String, Object> additionalProperties = new HashMap<>();
+ public Map<String, Object> getAdditionalProperties() {
+ return additionalProperties;
+ }
- public Map<String, Object> getAdditionalProperties() {
- return additionalProperties;
- }
+ public void setAdditionalProperties(Map<String, Object> additionalProperties) {
+ this.additionalProperties = additionalProperties;
+ }
- public void setAdditionalProperties(Map<String, Object> additionalProperties) {
- this.additionalProperties = additionalProperties;
- }
-
/**
* @return Returns the resources.
*/
public List<ResourceRequest> getResources() {
return resources;
}
-
+
/**
* @param resources The resources to set.
*/
@@ -73,11 +72,11 @@ public class E2EParameters {
this.locationConstraints = locationConstraints;
}
- public HashMap<String, ?> getRequestInputs() {
- return requestInputs;
- }
+ public HashMap<String, ?> getRequestInputs() {
+ return requestInputs;
+ }
- public void setRequestInputs(HashMap<String, ?> requestInputs) {
- this.requestInputs = requestInputs;
- }
+ public void setRequestInputs(HashMap<String, ?> requestInputs) {
+ this.requestInputs = requestInputs;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java
index dfe94dd2f0..77abbbfa9a 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java
@@ -22,92 +22,91 @@
package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
import java.sql.Timestamp;
-
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class E2ERequest {
- protected String operationId;
- protected String operation;
- protected String result;
- protected String reason;
- protected String userId;
- protected String operationContent;
- protected long progress;
- protected String operateAt;
- protected String finishedAt;
-
- public String getOperationId() {
- return operationId;
- }
-
- public void setOperationId(String operationId) {
- this.operationId = operationId;
- }
-
- public String getOperation() {
- return operation;
- }
-
- public void setOperation(String operation) {
- this.operation = operation;
- }
-
- public String getResult() {
- return result;
- }
-
- public void setResult(String result) {
- this.result = result;
- }
-
- public String getReason() {
- return reason;
- }
-
- public void setReason(String reason) {
- this.reason = reason;
- }
-
- public String getUserId() {
- return userId;
- }
-
- public void setUserId(String userId) {
- this.userId = userId;
- }
-
- public String getOperationContent() {
- return operationContent;
- }
-
- public void setOperationContent(String operationContent) {
- this.operationContent = operationContent;
- }
-
- public long getProgress() {
- return progress;
- }
-
- public void setProgress(long progress) {
- this.progress = progress;
- }
-
- public String getOperateAt() {
- return operateAt;
- }
-
- public void setOperateAt(String operateAt) {
- this.operateAt = operateAt;
- }
-
- public String getFinishedAt() {
- return finishedAt;
- }
-
- public void setFinishedAt(String finishedAt) {
- this.finishedAt = finishedAt;
- }
+ protected String operationId;
+ protected String operation;
+ protected String result;
+ protected String reason;
+ protected String userId;
+ protected String operationContent;
+ protected long progress;
+ protected String operateAt;
+ protected String finishedAt;
+
+ public String getOperationId() {
+ return operationId;
+ }
+
+ public void setOperationId(String operationId) {
+ this.operationId = operationId;
+ }
+
+ public String getOperation() {
+ return operation;
+ }
+
+ public void setOperation(String operation) {
+ this.operation = operation;
+ }
+
+ public String getResult() {
+ return result;
+ }
+
+ public void setResult(String result) {
+ this.result = result;
+ }
+
+ public String getReason() {
+ return reason;
+ }
+
+ public void setReason(String reason) {
+ this.reason = reason;
+ }
+
+ public String getUserId() {
+ return userId;
+ }
+
+ public void setUserId(String userId) {
+ this.userId = userId;
+ }
+
+ public String getOperationContent() {
+ return operationContent;
+ }
+
+ public void setOperationContent(String operationContent) {
+ this.operationContent = operationContent;
+ }
+
+ public long getProgress() {
+ return progress;
+ }
+
+ public void setProgress(long progress) {
+ this.progress = progress;
+ }
+
+ public String getOperateAt() {
+ return operateAt;
+ }
+
+ public void setOperateAt(String operateAt) {
+ this.operateAt = operateAt;
+ }
+
+ public String getFinishedAt() {
+ return finishedAt;
+ }
+
+ public void setFinishedAt(String finishedAt) {
+ this.finishedAt = finishedAt;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java
index 9f6a9b438c..f969674ed1 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java
@@ -22,99 +22,98 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
-@JsonIgnoreProperties({ "additionalProperties" })
+@JsonIgnoreProperties({"additionalProperties"})
public class E2EService {
- @JsonProperty("name")
- private String name;
+ @JsonProperty("name")
+ private String name;
- @JsonProperty("description")
- private String description;
+ @JsonProperty("description")
+ private String description;
- @JsonProperty("serviceInvariantUuid")
- private String serviceInvariantUuid;
+ @JsonProperty("serviceInvariantUuid")
+ private String serviceInvariantUuid;
- @JsonProperty("serviceUuid")
- private String serviceUuid;
+ @JsonProperty("serviceUuid")
+ private String serviceUuid;
- @JsonProperty("globalSubscriberId")
- private String globalSubscriberId;
+ @JsonProperty("globalSubscriberId")
+ private String globalSubscriberId;
- @JsonProperty("serviceType")
- private String serviceType;
+ @JsonProperty("serviceType")
+ private String serviceType;
- @JsonProperty("parameters")
- private E2EParameters parameters;
+ @JsonProperty("parameters")
+ private E2EParameters parameters;
- @JsonIgnore
- private Map<String, Object> additionalProperties = new HashMap<>();
+ @JsonIgnore
+ private Map<String, Object> additionalProperties = new HashMap<>();
- public String getName() {
- return name;
- }
+ public String getName() {
+ return name;
+ }
- public void setName(String name) {
- this.name = name;
- }
+ public void setName(String name) {
+ this.name = name;
+ }
- public String getDescription() {
- return description;
- }
+ public String getDescription() {
+ return description;
+ }
- public void setDescription(String description) {
- this.description = description;
- }
+ public void setDescription(String description) {
+ this.description = description;
+ }
- public E2EParameters getParameters() {
- return parameters;
- }
+ public E2EParameters getParameters() {
+ return parameters;
+ }
- public void setParameters(E2EParameters parameters) {
- this.parameters = parameters;
- }
+ public void setParameters(E2EParameters parameters) {
+ this.parameters = parameters;
+ }
- public Map<String, Object> getAdditionalProperties() {
- return additionalProperties;
- }
+ public Map<String, Object> getAdditionalProperties() {
+ return additionalProperties;
+ }
- public void setAdditionalProperties(Map<String, Object> additionalProperties) {
- this.additionalProperties = additionalProperties;
- }
+ public void setAdditionalProperties(Map<String, Object> additionalProperties) {
+ this.additionalProperties = additionalProperties;
+ }
- public String getServiceInvariantUuid() {
- return serviceInvariantUuid;
- }
+ public String getServiceInvariantUuid() {
+ return serviceInvariantUuid;
+ }
- public void setServiceInvariantUuid(String serviceInvariantUuid) {
- this.serviceInvariantUuid = serviceInvariantUuid;
- }
+ public void setServiceInvariantUuid(String serviceInvariantUuid) {
+ this.serviceInvariantUuid = serviceInvariantUuid;
+ }
- public String getGlobalSubscriberId() {
- return globalSubscriberId;
- }
+ public String getGlobalSubscriberId() {
+ return globalSubscriberId;
+ }
- public void setGlobalSubscriberId(String globalSubscriberId) {
- this.globalSubscriberId = globalSubscriberId;
- }
+ public void setGlobalSubscriberId(String globalSubscriberId) {
+ this.globalSubscriberId = globalSubscriberId;
+ }
- public String getServiceType() {
- return serviceType;
- }
+ public String getServiceType() {
+ return serviceType;
+ }
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
- public String getServiceUuid() {
- return serviceUuid;
- }
+ public String getServiceUuid() {
+ return serviceUuid;
+ }
- public void setServiceUuid(String serviceUuid) {
- this.serviceUuid = serviceUuid;
- }
+ public void setServiceUuid(String serviceUuid) {
+ this.serviceUuid = serviceUuid;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequest.java
index a920bdfdc8..3335410658 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequest.java
@@ -23,24 +23,24 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
public class E2EServiceInstanceDeleteRequest {
- private String globalSubscriberId;
-
- private String serviceType;
-
- public String getGlobalSubscriberId() {
- return globalSubscriberId;
- }
-
- public void setGlobalSubscriberId(String globalSubscriberId) {
- this.globalSubscriberId = globalSubscriberId;
- }
-
- public String getServiceType() {
- return serviceType;
- }
-
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
-
+ private String globalSubscriberId;
+
+ private String serviceType;
+
+ public String getGlobalSubscriberId() {
+ return globalSubscriberId;
+ }
+
+ public void setGlobalSubscriberId(String globalSubscriberId) {
+ this.globalSubscriberId = globalSubscriberId;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceRequest.java
index e3edf3b742..9f354f02b4 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceRequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceRequest.java
@@ -22,40 +22,39 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
-@JsonIgnoreProperties({ "additionalProperties" })
+@JsonIgnoreProperties({"additionalProperties"})
public class E2EServiceInstanceRequest {
- @JsonProperty("service")
- private E2EService service;
+ @JsonProperty("service")
+ private E2EService service;
+
+ @JsonIgnore
+ private Map<String, Object> additionalProperties = new HashMap<>();
+
+ public E2EService getService() {
+ return service;
+ }
- @JsonIgnore
- private Map<String, Object> additionalProperties = new HashMap<>();
+ public void setService(E2EService service) {
+ this.service = service;
+ }
- public E2EService getService() {
- return service;
- }
+ public Map<String, Object> getAdditionalProperties() {
+ return this.additionalProperties;
+ }
- public void setService(E2EService service) {
- this.service = service;
- }
- public Map<String, Object> getAdditionalProperties() {
- return this.additionalProperties;
- }
-
-
- public void setAdditionalProperties(Map<String, Object> additionalProperties) {
- this.additionalProperties = additionalProperties;
- }
+ public void setAdditionalProperties(Map<String, Object> additionalProperties) {
+ this.additionalProperties = additionalProperties;
+ }
- public void setAdditionalProperty(String name, Object value) {
- this.additionalProperties.put(name, value);
- }
+ public void setAdditionalProperty(String name, Object value) {
+ this.additionalProperties.put(name, value);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParam.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParam.java
index 531824e379..dbfe023684 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParam.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParam.java
@@ -22,48 +22,47 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
import java.util.HashMap;
import java.util.Map;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public class E2EUserParam {
- @JsonProperty("name")
- private String name;
+ @JsonProperty("name")
+ private String name;
+
+ @JsonProperty("value")
+ private String value;
+
+ @JsonIgnore
+ private Map<String, Object> additionalProperties = new HashMap<>();
- @JsonProperty("value")
- private String value;
+ public String getName() {
+ return name;
+ }
- @JsonIgnore
- private Map<String, Object> additionalProperties = new HashMap<>();
+ public void setName(String name) {
+ this.name = name;
+ }
- public String getName() {
- return name;
- }
+ public String getValue() {
+ return value;
+ }
- public void setName(String name) {
- this.name = name;
- }
+ public void setValue(String value) {
+ this.value = value;
+ }
- public String getValue() {
- return value;
- }
+ public Map<String, Object> getAdditionalProperties() {
+ return this.additionalProperties;
+ }
- public void setValue(String value) {
- this.value = value;
- }
+ public void setAdditionalProperty(String name, Object value) {
+ this.additionalProperties.put(name, value);
+ }
- public Map<String, Object> getAdditionalProperties() {
- return this.additionalProperties;
- }
+ public void setAdditionalProperties(Map<String, Object> additionalProperties) {
+ this.additionalProperties = additionalProperties;
+ }
- public void setAdditionalProperty(String name, Object value) {
- this.additionalProperties.put(name, value);
- }
- public void setAdditionalProperties(Map<String, Object> additionalProperties) {
- this.additionalProperties = additionalProperties;
- }
-
-
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java
index 5c958ad2a3..f7fa01aeb0 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java
@@ -22,28 +22,27 @@
package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
import org.onap.so.db.request.beans.OperationStatus;
-
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class GetE2EServiceInstanceResponse {
- protected OperationStatus operation;
+ protected OperationStatus operation;
-// public OperationStatus getOperationStatus() {
-// return operation;
-// }
-//
-// public void setOperationStatus(OperationStatus requestDB) {
-// this.operation = requestDB;
-// }
+ // public OperationStatus getOperationStatus() {
+ // return operation;
+ // }
+ //
+ // public void setOperationStatus(OperationStatus requestDB) {
+ // this.operation = requestDB;
+ // }
- public OperationStatus getOperation() {
- return operation;
- }
+ public OperationStatus getOperation() {
+ return operation;
+ }
- public void setOperation(OperationStatus operation) {
- this.operation = operation;
- }
+ public void setOperation(OperationStatus operation) {
+ this.operation = operation;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/LocationConstraint.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/LocationConstraint.java
index b1256a236b..dc5b69e2f2 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/LocationConstraint.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/LocationConstraint.java
@@ -57,7 +57,7 @@ public class LocationConstraint {
this.vnfProfileId = vnfProfileId;
}
-
+
/**
* @return Returns the locationConstraints.
*/
@@ -65,7 +65,7 @@ public class LocationConstraint {
return locationConstraints;
}
-
+
/**
* @param locationConstraints The locationConstraints to set.
*/
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParameters.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParameters.java
index e7baf98411..02885c7bbb 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParameters.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParameters.java
@@ -36,6 +36,7 @@ public class NsParameters {
private List<LocationConstraint> locationConstraints;
private Map<String, Object> additionalParamForNs = new HashMap<>();
+
/**
* @return Returns the locationConstraints.
*/
@@ -50,7 +51,7 @@ public class NsParameters {
this.locationConstraints = locationConstraints;
}
-
+
/**
* @return Returns the additionalParamForNs.
*/
@@ -58,7 +59,7 @@ public class NsParameters {
return additionalParamForNs;
}
-
+
/**
* @param additionalParamForNs The additionalParamForNs to set.
*/
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java
index 6518523256..44592ce2e4 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java
@@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import java.util.HashMap;
import java.util.Map;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/VimLocation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/VimLocation.java
index 72d370425f..5a4b55c048 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/VimLocation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/VimLocation.java
@@ -26,7 +26,7 @@ public class VimLocation {
@JsonProperty("vimId")
private String vimId;
-
+
/**
* @return Returns the vimId.
*/
@@ -34,12 +34,12 @@ public class VimLocation {
return vimId;
}
-
+
/**
* @param vimId The vimId to set.
*/
public void setVimId(String vimId) {
this.vimId = vimId;
}
-
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/package-info.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/package-info.java
index 2312678460..8b85ce7e34 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/package-info.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/package-info.java
@@ -19,12 +19,13 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.01.08 at 03:50:12 PM EST
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.01.08 at 03:50:12 PM EST
//
-@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/so/request/types/v1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
+@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/so/request/types/v1",
+ elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.onap.so.apihandlerinfra;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestDetails.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestDetails.java
index 957450fab0..ebb1912503 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestDetails.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestDetails.java
@@ -24,16 +24,15 @@ import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonRootName(value = "requestDetails")
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class RequestDetails {
- protected RequestInfo requestInfo;
- /**
+ protected RequestInfo requestInfo;
+
+ /**
* Gets the value of the requestInfo property.
*
- * @return
- * possible object is
- * {@link RequestInfo }
+ * @return possible object is {@link RequestInfo }
*
*/
public RequestInfo getRequestInfo() {
@@ -43,9 +42,7 @@ public class RequestDetails {
/**
* Sets the value of the requestInfo property.
*
- * @param value
- * allowed object is
- * {@link RequestInfo }
+ * @param value allowed object is {@link RequestInfo }
*
*/
public void setRequestInfo(RequestInfo value) {
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestInfo.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestInfo.java
index aae8786bb0..61d31b3a55 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestInfo.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestInfo.java
@@ -22,19 +22,17 @@ package org.onap.so.apihandlerinfra.tasksbeans;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class RequestInfo {
- protected String source;
- protected ValidResponses responseValue;
+ protected String source;
+ protected ValidResponses responseValue;
protected String requestorId;
-
+
/**
* Gets the value of the source property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getSource() {
@@ -44,30 +42,28 @@ public class RequestInfo {
/**
* Sets the value of the source property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setSource(String value) {
this.source = value;
}
- public ValidResponses getResponseValue() {
- return responseValue;
- }
+ public ValidResponses getResponseValue() {
+ return responseValue;
+ }
+
+ public void setResponseValue(ValidResponses responseValue) {
+ this.responseValue = responseValue;
+ }
- public void setResponseValue(ValidResponses responseValue) {
- this.responseValue = responseValue;
- }
-
- public String getRequestorId() {
- return requestorId;
- }
+ public String getRequestorId() {
+ return requestorId;
+ }
- public void setRequestorId(String requestorId) {
- this.requestorId = requestorId;
- }
+ public void setRequestorId(String requestorId) {
+ this.requestorId = requestorId;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskList.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskList.java
index ceba65fa97..f690aa5f01 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskList.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskList.java
@@ -21,21 +21,20 @@
package org.onap.so.apihandlerinfra.tasksbeans;
import java.util.List;
-
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
-public class TaskList {
- protected String taskId;
- protected String type;
- protected String nfRole;
- protected String subscriptionServiceType;
- protected String originalRequestId;
- protected String originalRequestorId;
- protected String errorSource;
- protected String errorCode;
- protected String errorMessage;
- protected String buildingBlockName;
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
+public class TaskList {
+ protected String taskId;
+ protected String type;
+ protected String nfRole;
+ protected String subscriptionServiceType;
+ protected String originalRequestId;
+ protected String originalRequestorId;
+ protected String errorSource;
+ protected String errorCode;
+ protected String errorMessage;
+ protected String buildingBlockName;
protected String buildingBlockStep;
protected String description;
protected String timeout;
@@ -44,10 +43,8 @@ public class TaskList {
/**
* Gets the value of the taskId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getTaskId() {
return taskId;
@@ -56,10 +53,8 @@ public class TaskList {
/**
* Sets the value of the taskId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setTaskId(String value) {
this.taskId = value;
@@ -68,10 +63,8 @@ public class TaskList {
/**
* Gets the value of the type property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getType() {
return type;
@@ -80,10 +73,8 @@ public class TaskList {
/**
* Sets the value of the type property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setType(String value) {
this.type = value;
@@ -92,10 +83,8 @@ public class TaskList {
/**
* Gets the value of the nfRole property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getNfRole() {
return nfRole;
@@ -104,10 +93,8 @@ public class TaskList {
/**
* Sets the value of the nfRole property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setNfRole(String value) {
this.nfRole = value;
@@ -116,10 +103,8 @@ public class TaskList {
/**
* Gets the value of the subscriptionServiceType property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getSubscriptionServiceType() {
return subscriptionServiceType;
@@ -128,10 +113,8 @@ public class TaskList {
/**
* Sets the value of the subscriptionServiceType property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setSubscriptionServiceType(String value) {
this.subscriptionServiceType = value;
@@ -140,10 +123,8 @@ public class TaskList {
/**
* Gets the value of the originalRequestId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getOriginalRequestId() {
return originalRequestId;
@@ -152,10 +133,8 @@ public class TaskList {
/**
* Sets the value of the originalRequestId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setOriginalRequestId(String value) {
this.originalRequestId = value;
@@ -164,10 +143,8 @@ public class TaskList {
/**
* Gets the value of the originalRequestorId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getOriginalRequestorId() {
return originalRequestorId;
@@ -176,10 +153,8 @@ public class TaskList {
/**
* Sets the value of the originalRequestorId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setOriginalRequestorId(String value) {
this.originalRequestorId = value;
@@ -188,10 +163,8 @@ public class TaskList {
/**
* Gets the value of the errorSource property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorSource() {
return errorSource;
@@ -200,10 +173,8 @@ public class TaskList {
/**
* Sets the value of the errorSource property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorSource(String value) {
this.errorSource = value;
@@ -212,10 +183,8 @@ public class TaskList {
/**
* Gets the value of the errorCode property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorCode() {
return errorCode;
@@ -224,10 +193,8 @@ public class TaskList {
/**
* Sets the value of the errorCode property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorCode(String value) {
this.errorCode = value;
@@ -236,10 +203,8 @@ public class TaskList {
/**
* Gets the value of the errorMessage property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getErrorMessage() {
return errorMessage;
@@ -248,10 +213,8 @@ public class TaskList {
/**
* Sets the value of the errorMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
@@ -260,10 +223,8 @@ public class TaskList {
/**
* Gets the value of the buildingBlockName property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getBuildingBlockName() {
return buildingBlockName;
@@ -272,10 +233,8 @@ public class TaskList {
/**
* Sets the value of the buildingBlockName property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setBuildingBlockName(String value) {
this.buildingBlockName = value;
@@ -284,10 +243,8 @@ public class TaskList {
/**
* Gets the value of the buildingBlockStep property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getBuildingBlockStep() {
return buildingBlockStep;
@@ -296,22 +253,18 @@ public class TaskList {
/**
* Sets the value of the buildingBlockStep property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setBuildingBlockStep(String value) {
this.buildingBlockStep = value;
}
-
+
/**
* Gets the value of the description property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getDescription() {
return description;
@@ -320,22 +273,18 @@ public class TaskList {
/**
* Sets the value of the description property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setDescription(String value) {
this.description = value;
}
-
+
/**
* Gets the value of the timeout property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getTimeout() {
return timeout;
@@ -344,10 +293,8 @@ public class TaskList {
/**
* Sets the value of the timeout property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setTimeout(String value) {
this.timeout = value;
@@ -356,10 +303,8 @@ public class TaskList {
/**
* Gets the value of the validResponses property.
*
- * @return
- * possible object is
- * {@link ValidResponses }
- *
+ * @return possible object is {@link ValidResponses }
+ *
*/
public List<String> getValidResponses() {
return validResponses;
@@ -368,16 +313,13 @@ public class TaskList {
/**
* Sets the value of the validResponses property.
*
- * @param value
- * allowed object is
- * {@link ValidResponses }
- *
+ * @param value allowed object is {@link ValidResponses }
+ *
*/
public void setValidResponses(List<String> value) {
this.validResponses = value;
}
-
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskRequestReference.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskRequestReference.java
index 860fe6bddb..18c9005f40 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskRequestReference.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskRequestReference.java
@@ -1,19 +1,15 @@
-/* ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/*
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2017 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
@@ -21,18 +17,17 @@ package org.onap.so.apihandlerinfra.tasksbeans;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+
@JsonRootName(value = "taskRequestReference")
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class TaskRequestReference {
- protected String taskId;
-
+ protected String taskId;
+
/**
* Gets the value of the taskId property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getTaskId() {
@@ -42,15 +37,13 @@ public class TaskRequestReference {
/**
* Sets the value of the taskId property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setTaskId(String value) {
this.taskId = value;
}
-
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariableValue.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariableValue.java
index 441d4f315a..fab42515d5 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariableValue.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariableValue.java
@@ -22,19 +22,17 @@ package org.onap.so.apihandlerinfra.tasksbeans;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class TaskVariableValue {
- protected String name;
- protected String value;
- protected String operator;
-
- /**
+ protected String name;
+ protected String value;
+ protected String operator;
+
+ /**
* Gets the value of the name property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getName() {
@@ -44,22 +42,18 @@ public class TaskVariableValue {
/**
* Sets the value of the name property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
-
-
+
+
/**
* Gets the value of the value property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getValue() {
@@ -69,21 +63,17 @@ public class TaskVariableValue {
/**
* Sets the value of the value property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
-
+
/**
* Gets the value of the operator property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getOperator() {
@@ -93,15 +83,13 @@ public class TaskVariableValue {
/**
* Sets the value of the operator property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setOperator(String value) {
this.operator = value;
}
-
-
+
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariables.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariables.java
index 7d5b465891..e759b4f87a 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariables.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariables.java
@@ -21,19 +21,18 @@
package org.onap.so.apihandlerinfra.tasksbeans;
import java.util.List;
-
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class TaskVariables {
- private List<TaskVariableValue> taskVariables;
+ private List<TaskVariableValue> taskVariables;
- public List<TaskVariableValue> getTaskVariables() {
- return taskVariables;
- }
+ public List<TaskVariableValue> getTaskVariables() {
+ return taskVariables;
+ }
- public void setTaskVariables(List<TaskVariableValue> taskVariables) {
- this.taskVariables = taskVariables;
- }
+ public void setTaskVariables(List<TaskVariableValue> taskVariables) {
+ this.taskVariables = taskVariables;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksGetResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksGetResponse.java
index 5ee01aeaf6..b0b6f43e03 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksGetResponse.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksGetResponse.java
@@ -24,13 +24,13 @@ import java.util.List;
public class TasksGetResponse {
- private List<TaskList> taskList;
+ private List<TaskList> taskList;
- public List<TaskList> getTaskList() {
- return taskList;
- }
+ public List<TaskList> getTaskList() {
+ return taskList;
+ }
- public void setTaskList(List<TaskList> taskList) {
- this.taskList = taskList;
- }
+ public void setTaskList(List<TaskList> taskList) {
+ this.taskList = taskList;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksRequest.java
index 0544f536a2..bd37ecd10a 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksRequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksRequest.java
@@ -22,13 +22,13 @@ package org.onap.so.apihandlerinfra.tasksbeans;
public class TasksRequest {
- private RequestDetails requestDetails;
+ private RequestDetails requestDetails;
- public RequestDetails getRequestDetails() {
- return requestDetails;
- }
+ public RequestDetails getRequestDetails() {
+ return requestDetails;
+ }
- public void setRequestDetails(RequestDetails requestDetails) {
- this.requestDetails = requestDetails;
- }
+ public void setRequestDetails(RequestDetails requestDetails) {
+ this.requestDetails = requestDetails;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/ValidResponses.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/ValidResponses.java
index 18fc7f9739..e25e40ced4 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/ValidResponses.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/ValidResponses.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
@@ -30,17 +30,11 @@ package org.onap.so.apihandlerinfra.tasksbeans;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public enum ValidResponses {
- rollback,
- abort,
- skip,
- retry,
- manual,
- resume
- ;
+ rollback, abort, skip, retry, manual, resume;
public String value() {
return name();
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Value.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Value.java
index 98ed5b653f..be113010b4 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Value.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Value.java
@@ -22,17 +22,15 @@ package org.onap.so.apihandlerinfra.tasksbeans;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class Value {
- protected String value;
-
+ protected String value;
+
/**
* Gets the value of the value property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getValue() {
@@ -42,14 +40,12 @@ public class Value {
/**
* Sets the value of the value property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
-
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Variables.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Variables.java
index 1ed011db91..7338f19d28 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Variables.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Variables.java
@@ -22,20 +22,19 @@ package org.onap.so.apihandlerinfra.tasksbeans;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+
@JsonRootName(value = "variables")
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class Variables {
- protected Value source;
- protected Value responseValue;
+ protected Value source;
+ protected Value responseValue;
protected Value requestorId;
-
+
/**
* Gets the value of the source property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public Value getSource() {
@@ -45,30 +44,28 @@ public class Variables {
/**
* Sets the value of the source property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setSource(Value value) {
this.source = value;
}
- public Value getResponseValue() {
- return responseValue;
- }
+ public Value getResponseValue() {
+ return responseValue;
+ }
- public void setResponseValue(Value responseValue) {
- this.responseValue = responseValue;
- }
+ public void setResponseValue(Value responseValue) {
+ this.responseValue = responseValue;
+ }
-
- public Value getRequestorId() {
- return requestorId;
- }
- public void setRequestorId(Value requestorId) {
- this.requestorId = requestorId;
- }
+ public Value getRequestorId() {
+ return requestorId;
+ }
+
+ public void setRequestorId(Value requestorId) {
+ this.requestorId = requestorId;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java
index 1ea77acf95..db2b5b6b4e 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java
@@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra.tenantisolation;
import java.net.MalformedURLException;
import java.net.URL;
-
import org.onap.so.client.aai.AAIProperties;
import org.onap.so.client.aai.AAIVersion;
import org.onap.so.spring.SpringContextHelper;
@@ -30,39 +29,40 @@ import org.springframework.context.ApplicationContext;
public class AaiClientPropertiesImpl implements AAIProperties {
- private String aaiEndpoint;
- private String auth;
- private String key;
- public AaiClientPropertiesImpl() {
-
- ApplicationContext context = SpringContextHelper.getAppContext();
- aaiEndpoint = context.getEnvironment().getProperty("mso.aai.endpoint");
- this.auth = context.getEnvironment().getProperty("aai.auth");
- this.key = context.getEnvironment().getProperty("mso.msoKey");
- }
+ private String aaiEndpoint;
+ private String auth;
+ private String key;
+
+ public AaiClientPropertiesImpl() {
+
+ ApplicationContext context = SpringContextHelper.getAppContext();
+ aaiEndpoint = context.getEnvironment().getProperty("mso.aai.endpoint");
+ this.auth = context.getEnvironment().getProperty("aai.auth");
+ this.key = context.getEnvironment().getProperty("mso.msoKey");
+ }
+
+ @Override
+ public URL getEndpoint() throws MalformedURLException {
+ return new URL(aaiEndpoint);
+ }
- @Override
- public URL getEndpoint() throws MalformedURLException {
- return new URL(aaiEndpoint);
- }
+ @Override
+ public String getSystemName() {
+ return "MSO";
+ }
- @Override
- public String getSystemName() {
- return "MSO";
- }
-
- @Override
- public AAIVersion getDefaultVersion() {
- return AAIVersion.LATEST;
- }
+ @Override
+ public AAIVersion getDefaultVersion() {
+ return AAIVersion.LATEST;
+ }
- @Override
- public String getAuth() {
- return this.auth;
- }
+ @Override
+ public String getAuth() {
+ return this.auth;
+ }
- @Override
- public String getKey() {
- return this.key;
- }
+ @Override
+ public String getKey() {
+ return this.key;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java
index be8f603a28..d79d73c036 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java
@@ -27,7 +27,6 @@ import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.UUID;
-
import javax.inject.Provider;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
@@ -39,7 +38,6 @@ import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.onap.so.apihandler.common.ErrorNumbers;
import org.onap.so.apihandlerinfra.Constants;
@@ -61,186 +59,199 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Component
@Path("/onap/so/infra/cloudResources")
-@Api(value="/onap/so/infra/cloudResources",description="API Requests for cloud resources - Tenant Isolation")
+@Api(value = "/onap/so/infra/cloudResources", description = "API Requests for cloud resources - Tenant Isolation")
public class CloudOrchestration {
- private static Logger logger = LoggerFactory.getLogger(CloudOrchestration.class);
- private static final String ENVIRONMENT_ID_KEY = "operationalEnvironmentId";
-
- @Autowired
- private TenantIsolationRequest tenantIsolationRequest ;
-
- @Autowired
- private RequestsDbClient requestsDbClient;
-
- @Autowired
- private Provider<TenantIsolationRunnable> tenantIsolationRunnable;
-
- @POST
- @Path("/{version:[vV][1]}/operationalEnvironments")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Create an Operational Environment",response=Response.class)
- @Transactional
- public Response createOperationEnvironment(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException{
- logger.debug("Received request to Create Operational Environment");
- return cloudOrchestration(request, Action.create, null, version, getRequestId(requestContext));
- }
-
- @POST
- @Path("/{version:[vV][1]}/operationalEnvironments/{operationalEnvironmentId}/activate")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Activate an Operational Environment",response=Response.class)
- @Transactional
- public Response activateOperationEnvironment(String request, @PathParam("version") String version, @PathParam("operationalEnvironmentId") String operationalEnvironmentId,
- @Context ContainerRequestContext requestContext) throws ApiException{
- logger.debug("Received request to Activate an Operational Environment");
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put(ENVIRONMENT_ID_KEY, operationalEnvironmentId);
- return cloudOrchestration(request, Action.activate, instanceIdMap, version, getRequestId(requestContext));
- }
-
- @POST
- @Path("/{version:[vV][1]}/operationalEnvironments/{operationalEnvironmentId}/deactivate")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Deactivate an Operational Environment",response=Response.class)
- @Transactional
- public Response deactivateOperationEnvironment(String request, @PathParam("version") String version, @PathParam("operationalEnvironmentId") String operationalEnvironmentId, @Context ContainerRequestContext requestContext) throws ApiException{
- logger.debug("Received request to Deactivate an Operational Environment");
- HashMap<String, String> instanceIdMap = new HashMap<>();
- instanceIdMap.put(ENVIRONMENT_ID_KEY, operationalEnvironmentId);
- return cloudOrchestration(request, Action.deactivate, instanceIdMap, version, getRequestId(requestContext));
- }
-
-
- private Response cloudOrchestration(String requestJSON, Action action, HashMap<String, String> instanceIdMap, String version, String requestId) throws ApiException{
- logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
- long startTime = System.currentTimeMillis ();
- CloudOrchestrationRequest cor = null;
- tenantIsolationRequest.setRequestId(requestId);
-
- cor = convertJsonToCloudOrchestrationRequest(requestJSON, action, startTime, cor);
-
- try {
- tenantIsolationRequest.parse(cor, instanceIdMap, action);
- }catch(ValidationException e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
- ErrorCode.SchemaError).build();
-
-
- throw new ValidateException.Builder("Mapping of request to JSON object failed. " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER)
- .cause(e).errorInfo(errorLoggerInfo).build();
- }
-
- String instanceName = cor.getRequestDetails().getRequestInfo().getInstanceName();
- String resourceType = cor.getRequestDetails().getRequestInfo().getResourceType().name();
- InfraActiveRequests dup = null;
-
- dup = duplicateCheck(action, instanceIdMap, startTime, instanceName, resourceType);
-
- if(dup == null && (Action.activate.equals(action) || Action.deactivate.equals(action))) {
- dup = requestsDbClient.checkVnfIdStatus(cor.getOperationalEnvironmentId());
- }
-
- if(dup != null) {
- String instance = null;
- if(instanceName != null){
- instance = instanceName;
- }else if (instanceIdMap != null){
- instance = instanceIdMap.get(resourceType + "InstanceId");
- }
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError).build();
-
-
- throw new DuplicateRequestException.Builder(resourceType,instance,dup.getRequestStatus(),dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
- .errorInfo(errorLoggerInfo).build();
- }
-
- String instanceId = null;
-
- if(instanceIdMap != null && instanceIdMap.get(ENVIRONMENT_ID_KEY) != null) {
- instanceId = instanceIdMap.get(ENVIRONMENT_ID_KEY);
- } else {
- instanceId = UUID.randomUUID().toString();
- tenantIsolationRequest.setOperationalEnvironmentId(instanceId);
- cor.setOperationalEnvironmentId(instanceId);
- }
-
- tenantIsolationRequest.createRequestRecord(Status.IN_PROGRESS, action);
-
- OperationalEnvironment opEnv = cor.getRequestDetails().getRequestParameters().getOperationalEnvironmentType();
- String operationalEnvType = opEnv != null ? opEnv.name() : null;
-
- TenantIsolationRunnable runnable = tenantIsolationRunnable.get();
- runnable.run(action, operationalEnvType, cor, requestId);
-
- String encodedValue;
- try {
- encodedValue = new String(instanceId.getBytes("UTF-8"));
- } catch(UnsupportedEncodingException ex) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
- ErrorCode.DataError).build();
-
-
- throw new ValidateException.Builder("Could not encode instanceID" + ex.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER)
- .cause(ex).errorInfo(errorLoggerInfo).build();
- }
-
- TenantSyncResponse tenantResponse = new TenantSyncResponse();
- RequestReferences reqReference = new RequestReferences();
- reqReference.setInstanceId(encodedValue);
- reqReference.setRequestId(requestId);
- tenantResponse.setRequestReferences(reqReference);
-
- return Response.ok(tenantResponse).build();
- }
-
- private InfraActiveRequests duplicateCheck(Action action, HashMap<String, String> instanceIdMap, long startTime,
- String instanceName, String requestScope) throws ApiException {
- try {
- return requestsDbClient.checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope);
- } catch (Exception e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-
-
- throw new ValidateException.Builder("Duplicate Check Request", HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
- .errorInfo(errorLoggerInfo).build();
- }
- }
-
- private CloudOrchestrationRequest convertJsonToCloudOrchestrationRequest(String requestJSON, Action action, long startTime,
- CloudOrchestrationRequest cor) throws ApiException {
- try{
- logger.debug("Converting incoming JSON request to Object");
- ObjectMapper mapper = new ObjectMapper();
- return mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
- } catch(IOException e){
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
- ErrorCode.SchemaError).build();
-
-
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed. " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER)
- .cause(e).errorInfo(errorLoggerInfo).build();
- if (tenantIsolationRequest.getRequestId () != null) {
- tenantIsolationRequest.createRequestRecord (Status.FAILED, action);
- }
- throw validateException;
- }
- }
-
- private String getRequestId(ContainerRequestContext requestContext) {
- return requestContext.getProperty("requestId").toString();
- }
+ private static Logger logger = LoggerFactory.getLogger(CloudOrchestration.class);
+ private static final String ENVIRONMENT_ID_KEY = "operationalEnvironmentId";
+
+ @Autowired
+ private TenantIsolationRequest tenantIsolationRequest;
+
+ @Autowired
+ private RequestsDbClient requestsDbClient;
+
+ @Autowired
+ private Provider<TenantIsolationRunnable> tenantIsolationRunnable;
+
+ @POST
+ @Path("/{version:[vV][1]}/operationalEnvironments")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create an Operational Environment", response = Response.class)
+ @Transactional
+ public Response createOperationEnvironment(String request, @PathParam("version") String version,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ logger.debug("Received request to Create Operational Environment");
+ return cloudOrchestration(request, Action.create, null, version, getRequestId(requestContext));
+ }
+
+ @POST
+ @Path("/{version:[vV][1]}/operationalEnvironments/{operationalEnvironmentId}/activate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Activate an Operational Environment", response = Response.class)
+ @Transactional
+ public Response activateOperationEnvironment(String request, @PathParam("version") String version,
+ @PathParam("operationalEnvironmentId") String operationalEnvironmentId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ logger.debug("Received request to Activate an Operational Environment");
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put(ENVIRONMENT_ID_KEY, operationalEnvironmentId);
+ return cloudOrchestration(request, Action.activate, instanceIdMap, version, getRequestId(requestContext));
+ }
+
+ @POST
+ @Path("/{version:[vV][1]}/operationalEnvironments/{operationalEnvironmentId}/deactivate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Deactivate an Operational Environment", response = Response.class)
+ @Transactional
+ public Response deactivateOperationEnvironment(String request, @PathParam("version") String version,
+ @PathParam("operationalEnvironmentId") String operationalEnvironmentId,
+ @Context ContainerRequestContext requestContext) throws ApiException {
+ logger.debug("Received request to Deactivate an Operational Environment");
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put(ENVIRONMENT_ID_KEY, operationalEnvironmentId);
+ return cloudOrchestration(request, Action.deactivate, instanceIdMap, version, getRequestId(requestContext));
+ }
+
+
+ private Response cloudOrchestration(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
+ String version, String requestId) throws ApiException {
+ logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
+ long startTime = System.currentTimeMillis();
+ CloudOrchestrationRequest cor = null;
+ tenantIsolationRequest.setRequestId(requestId);
+
+ cor = convertJsonToCloudOrchestrationRequest(requestJSON, action, startTime, cor);
+
+ try {
+ tenantIsolationRequest.parse(cor, instanceIdMap, action);
+ } catch (ValidationException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+
+
+ throw new ValidateException.Builder("Mapping of request to JSON object failed. " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo)
+ .build();
+ }
+
+ String instanceName = cor.getRequestDetails().getRequestInfo().getInstanceName();
+ String resourceType = cor.getRequestDetails().getRequestInfo().getResourceType().name();
+ InfraActiveRequests dup = null;
+
+ dup = duplicateCheck(action, instanceIdMap, startTime, instanceName, resourceType);
+
+ if (dup == null && (Action.activate.equals(action) || Action.deactivate.equals(action))) {
+ dup = requestsDbClient.checkVnfIdStatus(cor.getOperationalEnvironmentId());
+ }
+
+ if (dup != null) {
+ String instance = null;
+ if (instanceName != null) {
+ instance = instanceName;
+ } else if (instanceIdMap != null) {
+ instance = instanceIdMap.get(resourceType + "InstanceId");
+ }
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError).build();
+
+
+ throw new DuplicateRequestException.Builder(resourceType, instance, dup.getRequestStatus(),
+ dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
+ .errorInfo(errorLoggerInfo).build();
+ }
+
+ String instanceId = null;
+
+ if (instanceIdMap != null && instanceIdMap.get(ENVIRONMENT_ID_KEY) != null) {
+ instanceId = instanceIdMap.get(ENVIRONMENT_ID_KEY);
+ } else {
+ instanceId = UUID.randomUUID().toString();
+ tenantIsolationRequest.setOperationalEnvironmentId(instanceId);
+ cor.setOperationalEnvironmentId(instanceId);
+ }
+
+ tenantIsolationRequest.createRequestRecord(Status.IN_PROGRESS, action);
+
+ OperationalEnvironment opEnv = cor.getRequestDetails().getRequestParameters().getOperationalEnvironmentType();
+ String operationalEnvType = opEnv != null ? opEnv.name() : null;
+
+ TenantIsolationRunnable runnable = tenantIsolationRunnable.get();
+ runnable.run(action, operationalEnvType, cor, requestId);
+
+ String encodedValue;
+ try {
+ encodedValue = new String(instanceId.getBytes("UTF-8"));
+ } catch (UnsupportedEncodingException ex) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.DataError).build();
+
+
+ throw new ValidateException.Builder("Could not encode instanceID" + ex.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(ex).errorInfo(errorLoggerInfo)
+ .build();
+ }
+
+ TenantSyncResponse tenantResponse = new TenantSyncResponse();
+ RequestReferences reqReference = new RequestReferences();
+ reqReference.setInstanceId(encodedValue);
+ reqReference.setRequestId(requestId);
+ tenantResponse.setRequestReferences(reqReference);
+
+ return Response.ok(tenantResponse).build();
+ }
+
+ private InfraActiveRequests duplicateCheck(Action action, HashMap<String, String> instanceIdMap, long startTime,
+ String instanceName, String requestScope) throws ApiException {
+ try {
+ return requestsDbClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope);
+ } catch (Exception e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+
+ throw new ValidateException.Builder("Duplicate Check Request", HttpStatus.SC_INTERNAL_SERVER_ERROR,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
+ }
+ }
+
+ private CloudOrchestrationRequest convertJsonToCloudOrchestrationRequest(String requestJSON, Action action,
+ long startTime, CloudOrchestrationRequest cor) throws ApiException {
+ try {
+ logger.debug("Converting incoming JSON request to Object");
+ ObjectMapper mapper = new ObjectMapper();
+ return mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
+ } catch (IOException e) {
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON object failed. " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ if (tenantIsolationRequest.getRequestId() != null) {
+ tenantIsolationRequest.createRequestRecord(Status.FAILED, action);
+ }
+ throw validateException;
+ }
+ }
+
+ private String getRequestId(ContainerRequestContext requestContext) {
+ return requestContext.getProperty("requestId").toString();
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationRequest.java
index d387928e22..6660cc653c 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationRequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationRequest.java
@@ -21,61 +21,58 @@
package org.onap.so.apihandlerinfra.tenantisolation;
import java.io.Serializable;
-
import org.onap.so.apihandlerinfra.tenantisolationbeans.Distribution;
import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestDetails;
-
import com.fasterxml.jackson.annotation.JsonProperty;
public class CloudOrchestrationRequest implements Serializable {
- private static final long serialVersionUID = -4959169541182257787L;
- @JsonProperty("requestDetails")
- private RequestDetails requestDetails;
- @JsonProperty("operationalEnvironmentId")
- private String operationalEnvironmentId;
- @JsonProperty("distribution")
- private Distribution distribution;
- @JsonProperty("distributionId")
- private String distributionId;
-
- public String getOperationalEnvironmentId() {
- return operationalEnvironmentId;
- }
+ private static final long serialVersionUID = -4959169541182257787L;
+ @JsonProperty("requestDetails")
+ private RequestDetails requestDetails;
+ @JsonProperty("operationalEnvironmentId")
+ private String operationalEnvironmentId;
+ @JsonProperty("distribution")
+ private Distribution distribution;
+ @JsonProperty("distributionId")
+ private String distributionId;
+
+ public String getOperationalEnvironmentId() {
+ return operationalEnvironmentId;
+ }
+
+ public void setOperationalEnvironmentId(String operationalEnvironmentId) {
+ this.operationalEnvironmentId = operationalEnvironmentId;
+ }
+
+ public RequestDetails getRequestDetails() {
+ return requestDetails;
+ }
- public void setOperationalEnvironmentId(String operationalEnvironmentId) {
- this.operationalEnvironmentId = operationalEnvironmentId;
- }
+ public void setRequestDetails(RequestDetails requestDetails) {
+ this.requestDetails = requestDetails;
+ }
- public RequestDetails getRequestDetails() {
- return requestDetails;
- }
-
- public void setRequestDetails(RequestDetails requestDetails){
- this.requestDetails = requestDetails;
- }
+ public Distribution getDistribution() {
+ return distribution;
+ }
- public Distribution getDistribution() {
- return distribution;
- }
+ public void setDistribution(Distribution distribution) {
+ this.distribution = distribution;
+ }
- public void setDistribution(Distribution distribution) {
- this.distribution = distribution;
- }
+ public String getDistributionId() {
+ return distributionId;
+ }
- public String getDistributionId() {
- return distributionId;
- }
+ public void setDistributionId(String distributionId) {
+ this.distributionId = distributionId;
+ }
- public void setDistributionId(String distributionId) {
- this.distributionId = distributionId;
- }
-
- @Override
- public String toString() {
- return "ServiceInstancesRequest [requestDetails=" + requestDetails
- + ", operationalEnvironmentId=" + operationalEnvironmentId
- + ", distribution=" + distribution
- + ", distributionId=" + distributionId + "]";
- }
+ @Override
+ public String toString() {
+ return "ServiceInstancesRequest [requestDetails=" + requestDetails + ", operationalEnvironmentId="
+ + operationalEnvironmentId + ", distribution=" + distribution + ", distributionId=" + distributionId
+ + "]";
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java
index fe74b108ba..be6d5b06ca 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java
@@ -27,7 +27,6 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
@@ -40,14 +39,12 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
-
import org.apache.http.HttpStatus;
import org.onap.so.apihandler.common.ErrorNumbers;
import org.onap.so.apihandler.common.ResponseBuilder;
import org.onap.so.apihandlerinfra.Constants;
import org.onap.so.apihandlerinfra.exceptions.ApiException;
import org.onap.so.apihandlerinfra.exceptions.ValidateException;
-
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
import org.onap.so.apihandlerinfra.tenantisolationbeans.CloudOrchestrationRequestList;
import org.onap.so.apihandlerinfra.tenantisolationbeans.CloudOrchestrationResponse;
@@ -60,231 +57,257 @@ import org.onap.so.db.request.client.RequestsDbClient;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Component
@Path("onap/so/infra/cloudResourcesRequests")
-@Api(value="onap/so/infra/cloudResourcesRequests",description="API GET Requests for cloud resources - Tenant Isolation")
+@Api(value = "onap/so/infra/cloudResourcesRequests",
+ description = "API GET Requests for cloud resources - Tenant Isolation")
public class CloudResourcesOrchestration {
- private static Logger logger = LoggerFactory.getLogger(CloudResourcesOrchestration.class);
-
- @Autowired
- RequestsDbClient requestDbClient;
-
- @Autowired
- private ResponseBuilder builder;
-
- @POST
- @Path("/{version: [vV][1]}/{requestId}/unlock")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Unlock CloudOrchestration requests for a specified requestId")
- @Transactional
- public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException{
- TenantIsolationRequest msoRequest = new TenantIsolationRequest(requestId);
- InfraActiveRequests infraActiveRequest = null;
-
- CloudOrchestrationRequest cor = null;
-
- logger.debug ("requestId is: " + requestId);
-
- try{
- ObjectMapper mapper = new ObjectMapper();
- cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
- } catch(IOException e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
- ErrorCode.SchemaError).build();
-
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed. " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER)
- .cause(e).errorInfo(errorLoggerInfo).build();
- throw validateException;
- }
-
- try{
- msoRequest.parseOrchestration(cor);
- } catch (ValidationException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
- ErrorCode.SchemaError).build();
- ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER)
- .cause(e).errorInfo(errorLoggerInfo).build();
- throw validateException;
- }
- try {
- infraActiveRequest = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
- }catch(Exception e){
- ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).build();
- throw validateException;
- }
- if(infraActiveRequest == null) {
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.BusinessProcesssError).build();
- ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB", HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
- .errorInfo(errorLoggerInfo).build();
-
- throw validateException;
-
- }else{
- String status = infraActiveRequest.getRequestStatus();
- if(status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING") || status.equalsIgnoreCase("PENDING_MANUAL_TASK")){
- infraActiveRequest.setRequestStatus("UNLOCKED");
- infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
- infraActiveRequest.setRequestId(requestId);
- requestDbClient.save(infraActiveRequest);
- }else{
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,
- ErrorCode.DataError).build();
- ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " has a status of " + status + " and can not be unlocked",
- HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
-
- throw validateException;
- }
- }
-
- return Response.status (HttpStatus.SC_NO_CONTENT).entity ("").build ();
- }
-
- @GET
- @Path("/{version:[vV][1]}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Get status of an Operational Environment based on filter criteria",response=Response.class)
- @Transactional
- public Response getOperationEnvironmentStatusFilter(@Context UriInfo ui, @PathParam("version") String version ) throws ApiException{
-
- MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
- List<String> requestIdKey = queryParams.get("requestId");
- String apiVersion = version.substring(1);
-
- if(queryParams.size() == 1 && requestIdKey != null) {
- String requestId = requestIdKey.get(0);
-
- CloudOrchestrationResponse cloudOrchestrationGetResponse = new CloudOrchestrationResponse();
- TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest (requestId);
- InfraActiveRequests requestDB = null;
-
- try {
- requestDB = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
- } catch (Exception e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build();
- ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
- .errorInfo(errorLoggerInfo).build();
- throw validateException;
- }
-
- if(requestDB == null) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).build();
- ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
- HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
- .errorInfo(errorLoggerInfo).build();
-
- throw validateException;
- }
-
- Request request = mapInfraActiveRequestToRequest(requestDB);
- cloudOrchestrationGetResponse.setRequest(request);
- return builder.buildResponse(HttpStatus.SC_OK, requestId, cloudOrchestrationGetResponse, apiVersion);
-
- } else {
- TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest ();
- List<InfraActiveRequests> activeRequests = null;
- CloudOrchestrationRequestList orchestrationList = null;
-
-
- Map<String, String> orchestrationMap;
- try{
- orchestrationMap = tenantIsolationRequest.getOrchestrationFilters(queryParams);
- }catch(ValidationException ex){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
- ValidateException validateException = new ValidateException.Builder(ex.getMessage(),
- HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex)
- .errorInfo(errorLoggerInfo).build();
-
- throw validateException;
-
- }
- activeRequests = requestDbClient.getCloudOrchestrationFiltersFromInfraActive(orchestrationMap);
- orchestrationList = new CloudOrchestrationRequestList();
- List<CloudOrchestrationResponse> requestLists = new ArrayList<CloudOrchestrationResponse>();
-
- for(InfraActiveRequests infraActive : activeRequests){
-
- Request request = mapInfraActiveRequestToRequest(infraActive);
- CloudOrchestrationResponse requestList = new CloudOrchestrationResponse();
- requestList.setRequest(request);
- requestLists.add(requestList);
- }
- orchestrationList.setRequestList(requestLists);
-
- return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
- }
- }
-
- private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException {
- Request request = new Request();
- request.setRequestId(iar.getRequestId());
- request.setRequestScope(iar.getRequestScope());
- request.setRequestType(iar.getRequestAction());
-
- InstanceReferences ir = new InstanceReferences();
-
- if(iar.getOperationalEnvId() != null)
- ir.setOperationalEnvironmentId(iar.getOperationalEnvId());
- if(iar.getOperationalEnvName() != null)
- ir.setOperationalEnvName(iar.getOperationalEnvName());
- if(iar.getRequestorId() != null)
- ir.setRequestorId(iar.getRequestorId());
-
- request.setInstanceReferences(ir);
- String requestBody = iar.getRequestBody();
- RequestDetails requestDetails = null;
-
- if (requestBody != null) {
- try {
- ObjectMapper mapper = new ObjectMapper();
- requestDetails = mapper.readValue(requestBody, RequestDetails.class);
- } catch (IOException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build();
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed. " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER)
- .cause(e).errorInfo(errorLoggerInfo).build();
- throw validateException;
- }
- }
-
- request.setRequestDetails(requestDetails);
- String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT";
- request.setStartTime(startTimeStamp);
-
- RequestStatus status = new RequestStatus();
- if(iar.getStatusMessage() != null){
- status.setStatusMessage(iar.getStatusMessage());
- }
-
- if(iar.getEndTime() != null){
- String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT";
- status.setTimeStamp(endTimeStamp);
- }
-
- if(iar.getRequestStatus() != null){
- status.setRequestState(iar.getRequestStatus());
- }
-
- if(iar.getProgress() != null){
- status.setPercentProgress(iar.getProgress().toString());
- }
-
- request.setRequestStatus(status);
-
- return request;
- }
+ private static Logger logger = LoggerFactory.getLogger(CloudResourcesOrchestration.class);
+
+ @Autowired
+ RequestsDbClient requestDbClient;
+
+ @Autowired
+ private ResponseBuilder builder;
+
+ @POST
+ @Path("/{version: [vV][1]}/{requestId}/unlock")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Unlock CloudOrchestration requests for a specified requestId")
+ @Transactional
+ public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId,
+ @PathParam("version") String version) throws ApiException {
+ TenantIsolationRequest msoRequest = new TenantIsolationRequest(requestId);
+ InfraActiveRequests infraActiveRequest = null;
+
+ CloudOrchestrationRequest cor = null;
+
+ logger.debug("requestId is: " + requestId);
+
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON object failed. " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ throw validateException;
+ }
+
+ try {
+ msoRequest.parseOrchestration(cor);
+ } catch (ValidationException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+ ValidateException validateException =
+ new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
+ throw validateException;
+ }
+ try {
+ infraActiveRequest = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
+ } catch (Exception e) {
+ ValidateException validateException = new ValidateException.Builder(e.getMessage(),
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).build();
+ throw validateException;
+ }
+ if (infraActiveRequest == null) {
+
+ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,
+ ErrorCode.BusinessProcesssError).build();
+ ValidateException validateException =
+ new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
+ .errorInfo(errorLoggerInfo).build();
+
+ throw validateException;
+
+ } else {
+ String status = infraActiveRequest.getRequestStatus();
+ if (status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING")
+ || status.equalsIgnoreCase("PENDING_MANUAL_TASK")) {
+ infraActiveRequest.setRequestStatus("UNLOCKED");
+ infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ infraActiveRequest.setRequestId(requestId);
+ requestDbClient.save(infraActiveRequest);
+ } else {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
+ .build();
+ ValidateException validateException = new ValidateException.Builder(
+ "Orchestration RequestId " + requestId + " has a status of " + status
+ + " and can not be unlocked",
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo)
+ .build();
+
+ throw validateException;
+ }
+ }
+
+ return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build();
+ }
+
+ @GET
+ @Path("/{version:[vV][1]}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get status of an Operational Environment based on filter criteria",
+ response = Response.class)
+ @Transactional
+ public Response getOperationEnvironmentStatusFilter(@Context UriInfo ui, @PathParam("version") String version)
+ throws ApiException {
+
+ MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
+ List<String> requestIdKey = queryParams.get("requestId");
+ String apiVersion = version.substring(1);
+
+ if (queryParams.size() == 1 && requestIdKey != null) {
+ String requestId = requestIdKey.get(0);
+
+ CloudOrchestrationResponse cloudOrchestrationGetResponse = new CloudOrchestrationResponse();
+ TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest(requestId);
+ InfraActiveRequests requestDB = null;
+
+ try {
+ requestDB = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
+ } catch (Exception e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError)
+ .build();
+ ValidateException validateException =
+ new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
+ throw validateException;
+ }
+
+ if (requestDB == null) {
+ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
+ ErrorCode.BusinessProcesssError).build();
+ ValidateException validateException =
+ new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
+ HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
+ .errorInfo(errorLoggerInfo).build();
+
+ throw validateException;
+ }
+
+ Request request = mapInfraActiveRequestToRequest(requestDB);
+ cloudOrchestrationGetResponse.setRequest(request);
+ return builder.buildResponse(HttpStatus.SC_OK, requestId, cloudOrchestrationGetResponse, apiVersion);
+
+ } else {
+ TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest();
+ List<InfraActiveRequests> activeRequests = null;
+ CloudOrchestrationRequestList orchestrationList = null;
+
+
+ Map<String, String> orchestrationMap;
+ try {
+ orchestrationMap = tenantIsolationRequest.getOrchestrationFilters(queryParams);
+ } catch (ValidationException ex) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
+ .build();
+ ValidateException validateException =
+ new ValidateException.Builder(ex.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
+ ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
+
+ throw validateException;
+
+ }
+ activeRequests = requestDbClient.getCloudOrchestrationFiltersFromInfraActive(orchestrationMap);
+ orchestrationList = new CloudOrchestrationRequestList();
+ List<CloudOrchestrationResponse> requestLists = new ArrayList<CloudOrchestrationResponse>();
+
+ for (InfraActiveRequests infraActive : activeRequests) {
+
+ Request request = mapInfraActiveRequestToRequest(infraActive);
+ CloudOrchestrationResponse requestList = new CloudOrchestrationResponse();
+ requestList.setRequest(request);
+ requestLists.add(requestList);
+ }
+ orchestrationList.setRequestList(requestLists);
+
+ return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
+ }
+ }
+
+ private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException {
+ Request request = new Request();
+ request.setRequestId(iar.getRequestId());
+ request.setRequestScope(iar.getRequestScope());
+ request.setRequestType(iar.getRequestAction());
+
+ InstanceReferences ir = new InstanceReferences();
+
+ if (iar.getOperationalEnvId() != null)
+ ir.setOperationalEnvironmentId(iar.getOperationalEnvId());
+ if (iar.getOperationalEnvName() != null)
+ ir.setOperationalEnvName(iar.getOperationalEnvName());
+ if (iar.getRequestorId() != null)
+ ir.setRequestorId(iar.getRequestorId());
+
+ request.setInstanceReferences(ir);
+ String requestBody = iar.getRequestBody();
+ RequestDetails requestDetails = null;
+
+ if (requestBody != null) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ requestDetails = mapper.readValue(requestBody, RequestDetails.class);
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON object failed. " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ throw validateException;
+ }
+ }
+
+ request.setRequestDetails(requestDetails);
+ String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT";
+ request.setStartTime(startTimeStamp);
+
+ RequestStatus status = new RequestStatus();
+ if (iar.getStatusMessage() != null) {
+ status.setStatusMessage(iar.getStatusMessage());
+ }
+
+ if (iar.getEndTime() != null) {
+ String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT";
+ status.setTimeStamp(endTimeStamp);
+ }
+
+ if (iar.getRequestStatus() != null) {
+ status.setRequestState(iar.getRequestStatus());
+ }
+
+ if (iar.getProgress() != null) {
+ status.setPercentProgress(iar.getProgress().toString());
+ }
+
+ request.setRequestStatus(status);
+
+ return request;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java
index 60a05d74e5..f7b3811bce 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java
@@ -22,54 +22,52 @@ package org.onap.so.apihandlerinfra.tenantisolation;
import java.net.MalformedURLException;
import java.net.URL;
-
import javax.ws.rs.core.MediaType;
-
import org.onap.so.client.grm.GRMProperties;
import org.onap.so.spring.SpringContextHelper;
import org.springframework.context.ApplicationContext;
public class GrmClientPropertiesImpl implements GRMProperties {
- private String grmEndpoint;
- private String grmAuth;
- private String grmKey;
-
- public GrmClientPropertiesImpl() {
- ApplicationContext context = SpringContextHelper.getAppContext();
- grmEndpoint = context.getEnvironment().getProperty("mso.grm.endpoint");
- grmAuth = context.getEnvironment().getProperty("mso.grm.auth");
- grmKey = context.getEnvironment().getProperty("mso.msoKey");
- }
-
- @Override
- public URL getEndpoint() throws MalformedURLException {
- return new URL(grmEndpoint);
- }
+ private String grmEndpoint;
+ private String grmAuth;
+ private String grmKey;
+
+ public GrmClientPropertiesImpl() {
+ ApplicationContext context = SpringContextHelper.getAppContext();
+ grmEndpoint = context.getEnvironment().getProperty("mso.grm.endpoint");
+ grmAuth = context.getEnvironment().getProperty("mso.grm.auth");
+ grmKey = context.getEnvironment().getProperty("mso.msoKey");
+ }
+
+ @Override
+ public URL getEndpoint() throws MalformedURLException {
+ return new URL(grmEndpoint);
+ }
- @Override
- public String getSystemName() {
- return "MSO";
- }
+ @Override
+ public String getSystemName() {
+ return "MSO";
+ }
- @Override
- public String getDefaultVersion() {
- return "v1";
- }
+ @Override
+ public String getDefaultVersion() {
+ return "v1";
+ }
- @Override
- public String getAuth() {
- return grmAuth;
- }
+ @Override
+ public String getAuth() {
+ return grmAuth;
+ }
- @Override
- public String getKey() {
- return grmKey;
- }
+ @Override
+ public String getKey() {
+ return grmKey;
+ }
- @Override
- public String getContentType() {
- return MediaType.APPLICATION_JSON;
- }
+ @Override
+ public String getContentType() {
+ return MediaType.APPLICATION_JSON;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java
index 4be1ec9187..b2933df030 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java
@@ -24,7 +24,6 @@ package org.onap.so.apihandlerinfra.tenantisolation;
import java.io.IOException;
import java.util.List;
-
import javax.inject.Provider;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
@@ -34,7 +33,6 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.onap.so.apihandler.common.ErrorNumbers;
@@ -54,110 +52,118 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Component
@Path("/onap/so/infra/modelDistributions")
-@Api(value="/onap/so/infra/modelDistributions",description="API Requests for Model Distributions")
+@Api(value = "/onap/so/infra/modelDistributions", description = "API Requests for Model Distributions")
public class ModelDistributionRequest {
-
- private static Logger logger = LoggerFactory.getLogger(ModelDistributionRequest.class);
- @Autowired
- private Provider<TenantIsolationRunnable> tenantIsolationRunnable;
-
- @PATCH
- @Path("/{version:[vV][1]}/distributions/{distributionId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value="Update model distribution status",response=Response.class)
- @Transactional
- public Response updateModelDistributionStatus(String requestJSON, @PathParam("version") String version, @PathParam("distributionId") String distributionId) throws ApiException{
- long startTime = System.currentTimeMillis ();
- Distribution distributionRequest = null;
-
- try {
- ObjectMapper mapper = new ObjectMapper();
- distributionRequest = mapper.readValue(requestJSON, Distribution.class);
- } catch(IOException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
- ErrorCode.SchemaError).build();
-
-
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed. " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER)
- .cause(e).errorInfo(errorLoggerInfo).build();
- throw validateException;
-
- }
-
- try {
- parse(distributionRequest);
- } catch(ValidationException e) {
-
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
- ErrorCode.SchemaError).build();
-
-
- ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER)
- .cause(e).errorInfo(errorLoggerInfo).build();
- throw validateException;
- }
-
- CloudOrchestrationRequest cor = new CloudOrchestrationRequest();
- cor.setDistribution(distributionRequest);
- cor.setDistributionId(distributionId);
-
- TenantIsolationRunnable runnable = tenantIsolationRunnable.get();
- runnable.run(Action.distributionStatus, null, cor, null);
-
- return Response.ok().build();
- }
-
- private void parse(Distribution distributionRequest) throws ValidationException {
- if(distributionRequest.getStatus() == null) {
- throw new ValidationException("status");
- }
-
- if(StringUtils.isBlank(distributionRequest.getErrorReason()) && Status.DISTRIBUTION_COMPLETE_ERROR.equals(distributionRequest.getStatus())) {
- throw new ValidationException("errorReason");
- }
- }
-
- private Response buildServiceErrorResponse (int httpResponseCode, MsoException exceptionType, String text,
- String messageId, List<String> variables) throws ApiException{
- RequestError re = new RequestError();
- ServiceException se = new ServiceException();
- se.setMessageId(messageId);
- se.setText(text);
- if(variables != null){
- if(variables != null){
- for(String variable: variables){
- se.getVariables().add(variable);
- }
- }
- }
- re.setServiceException(se);
+
+ private static Logger logger = LoggerFactory.getLogger(ModelDistributionRequest.class);
+ @Autowired
+ private Provider<TenantIsolationRunnable> tenantIsolationRunnable;
+
+ @PATCH
+ @Path("/{version:[vV][1]}/distributions/{distributionId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update model distribution status", response = Response.class)
+ @Transactional
+ public Response updateModelDistributionStatus(String requestJSON, @PathParam("version") String version,
+ @PathParam("distributionId") String distributionId) throws ApiException {
+ long startTime = System.currentTimeMillis();
+ Distribution distributionRequest = null;
+
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ distributionRequest = mapper.readValue(requestJSON, Distribution.class);
+ } catch (IOException e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON object failed. " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ throw validateException;
+
+ }
+
+ try {
+ parse(distributionRequest);
+ } catch (ValidationException e) {
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
+ throw validateException;
+ }
+
+ CloudOrchestrationRequest cor = new CloudOrchestrationRequest();
+ cor.setDistribution(distributionRequest);
+ cor.setDistributionId(distributionId);
+
+ TenantIsolationRunnable runnable = tenantIsolationRunnable.get();
+ runnable.run(Action.distributionStatus, null, cor, null);
+
+ return Response.ok().build();
+ }
+
+ private void parse(Distribution distributionRequest) throws ValidationException {
+ if (distributionRequest.getStatus() == null) {
+ throw new ValidationException("status");
+ }
+
+ if (StringUtils.isBlank(distributionRequest.getErrorReason())
+ && Status.DISTRIBUTION_COMPLETE_ERROR.equals(distributionRequest.getStatus())) {
+ throw new ValidationException("errorReason");
+ }
+ }
+
+ private Response buildServiceErrorResponse(int httpResponseCode, MsoException exceptionType, String text,
+ String messageId, List<String> variables) throws ApiException {
+ RequestError re = new RequestError();
+ ServiceException se = new ServiceException();
+ se.setMessageId(messageId);
+ se.setText(text);
+ if (variables != null) {
+ if (variables != null) {
+ for (String variable : variables) {
+ se.getVariables().add(variable);
+ }
+ }
+ }
+ re.setServiceException(se);
String requestErrorStr = null;
- try{
- ObjectMapper mapper = new ObjectMapper();
- mapper.setSerializationInclusion(Include.NON_DEFAULT);
- requestErrorStr = mapper.writeValueAsString(re);
- }catch(JsonProcessingException e){
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(Include.NON_DEFAULT);
+ requestErrorStr = mapper.writeValueAsString(re);
+ } catch (JsonProcessingException e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.DataError).build();
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.DataError).build();
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed. " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER)
- .cause(e).errorInfo(errorLoggerInfo).build();
- throw validateException;
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON object failed. " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ throw validateException;
}
- return Response.status (httpResponseCode).entity(requestErrorStr).build ();
+ return Response.status(httpResponseCode).entity(requestErrorStr).build();
}
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java
index 82a5d1ebbf..696616099f 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java
@@ -27,9 +27,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-
import javax.ws.rs.core.MultivaluedMap;
-
import org.apache.commons.lang3.StringUtils;
import org.onap.so.apihandlerinfra.Constants;
import org.onap.so.apihandlerinfra.Status;
@@ -49,14 +47,12 @@ import org.onap.so.db.request.client.RequestsDbClient;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import org.onap.so.utils.UUIDChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -75,316 +71,323 @@ public class TenantIsolationRequest {
private long progress = Constants.PROGRESS_REQUEST_RECEIVED;
private String requestScope;
private CloudOrchestrationRequest cor;
-
+
@Autowired
- private RequestsDbClient requestsDbClient;
-
+ private RequestsDbClient requestsDbClient;
+
private static Logger logger = LoggerFactory.getLogger(TenantIsolationRequest.class);
- TenantIsolationRequest (String requestId) {
+ TenantIsolationRequest(String requestId) {
this.requestId = requestId;
}
- TenantIsolationRequest () {
+ TenantIsolationRequest() {}
+
+ void parse(CloudOrchestrationRequest request, HashMap<String, String> instanceIdMap, Action action)
+ throws ValidationException {
+ this.cor = request;
+ this.requestInfo = request.getRequestDetails().getRequestInfo();
+
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ requestJSON = mapper.writeValueAsString(request.getRequestDetails());
+
+ } catch (JsonProcessingException e) {
+ throw new ValidationException("Parse ServiceInstanceRequest to JSON string", true);
+ }
+
+ String envId = null;
+ if (instanceIdMap != null) {
+ envId = instanceIdMap.get("operationalEnvironmentId");
+ if (envId != null && !UUIDChecker.isValidUUID(envId)) {
+ throw new ValidationException("operationalEnvironmentId", true);
+ }
+ cor.setOperationalEnvironmentId(envId);
+ }
+
+ this.operationalEnvironmentId = envId;
+
+ RequestDetails requestDetails = request.getRequestDetails();
+ RequestParameters requestParameters = requestDetails.getRequestParameters();
+
+ requestInfoValidation(action, requestInfo);
+
+ requestParamsValidation(action, requestParameters);
+
+ relatedInstanceValidation(action, requestDetails, requestParameters);
+
+ }
+
+ private void relatedInstanceValidation(Action action, RequestDetails requestDetails,
+ RequestParameters requestParameters) throws ValidationException {
+ RelatedInstanceList[] instanceList = requestDetails.getRelatedInstanceList();
+
+ if (requestParameters == null) {
+ throw new ValidationException("requestParameters", true);
+ }
+ if ((Action.activate.equals(action) || Action.deactivate.equals(action))
+ && OperationalEnvironment.ECOMP.equals(requestParameters.getOperationalEnvironmentType())) {
+ throw new ValidationException("operationalEnvironmentType in requestParameters", true);
+ }
+
+ if (!Action.deactivate.equals(action)
+ && OperationalEnvironment.VNF.equals(requestParameters.getOperationalEnvironmentType())) {
+ if (instanceList != null && instanceList.length > 0) {
+ for (RelatedInstanceList relatedInstanceList : instanceList) {
+ RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
+
+ if (relatedInstance.getResourceType() == null) {
+ throw new ValidationException("ResourceType in relatedInstance", true);
+ }
+
+ if (!empty(relatedInstance.getInstanceName())
+ && !relatedInstance.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) {
+ throw new ValidationException("instanceName format", true);
+ }
+
+ if (empty(relatedInstance.getInstanceId())) {
+ throw new ValidationException("instanceId in relatedInstance", true);
+ }
+
+ if (!UUIDChecker.isValidUUID(relatedInstance.getInstanceId())) {
+ throw new ValidationException("instanceId format in relatedInstance", true);
+ }
+ }
+ } else {
+ throw new ValidationException("relatedInstanceList", true);
+ }
+ }
}
-
- void parse(CloudOrchestrationRequest request, HashMap<String,String> instanceIdMap, Action action) throws ValidationException {
- this.cor = request;
- this.requestInfo = request.getRequestDetails().getRequestInfo();
-
- try{
- ObjectMapper mapper = new ObjectMapper();
- requestJSON = mapper.writeValueAsString(request.getRequestDetails());
-
- } catch(JsonProcessingException e){
- throw new ValidationException ("Parse ServiceInstanceRequest to JSON string", true);
+
+ private void requestParamsValidation(Action action, RequestParameters requestParameters)
+ throws ValidationException {
+
+ if (requestParameters != null) {
+ if (!Action.deactivate.equals(action) && requestParameters.getOperationalEnvironmentType() == null) {
+ throw new ValidationException("OperationalEnvironmentType", true);
+ }
+
+ if (Action.create.equals(action) && empty(requestParameters.getTenantContext())) {
+ throw new ValidationException("Tenant Context", true);
+ }
+ if (!Action.deactivate.equals(action) && empty(requestParameters.getWorkloadContext())) {
+ throw new ValidationException("Workload Context", true);
+ }
+
+ Manifest manifest = requestParameters.getManifest();
+
+ if (Action.activate.equals(action)) {
+ if (manifest == null) {
+ throw new ValidationException("Manifest on Activate", true);
+ } else {
+ List<ServiceModelList> serviceModelList = manifest.getServiceModelList();
+
+ if (serviceModelList.isEmpty()) {
+ throw new ValidationException(" empty ServiceModelList", true);
+ }
+
+ for (ServiceModelList list : serviceModelList) {
+ if (empty(list.getServiceModelVersionId())) {
+ throw new ValidationException("ServiceModelVersionId", true);
+ }
+
+ if (!UUIDChecker.isValidUUID(list.getServiceModelVersionId())) {
+ throw new ValidationException("ServiceModelVersionId format", true);
+ }
+
+ if (list.getRecoveryAction() == null) {
+ throw new ValidationException("RecoveryAction", true);
+ }
+ }
+ }
+ }
+ } else if (!Action.deactivate.equals(action)) {
+ throw new ValidationException("request Parameters", true);
+ }
+ }
+
+ private void requestInfoValidation(Action action, RequestInfo requestInfo) throws ValidationException {
+
+ if (Action.create.equals(action) && empty(requestInfo.getInstanceName())) {
+ throw new ValidationException("instanceName", true);
+ }
+
+ if (!empty(requestInfo.getInstanceName())
+ && !requestInfo.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) {
+ throw new ValidationException("instanceName format", true);
+ }
+
+ if (empty(requestInfo.getSource())) {
+ throw new ValidationException("source", true);
}
-
- String envId = null;
- if(instanceIdMap != null) {
- envId = instanceIdMap.get("operationalEnvironmentId");
- if(envId != null && !UUIDChecker.isValidUUID (envId)){
- throw new ValidationException ("operationalEnvironmentId", true);
- }
- cor.setOperationalEnvironmentId(envId);
- }
-
- this.operationalEnvironmentId = envId;
-
- RequestDetails requestDetails = request.getRequestDetails();
- RequestParameters requestParameters = requestDetails.getRequestParameters();
-
- requestInfoValidation(action, requestInfo);
-
- requestParamsValidation(action, requestParameters);
-
- relatedInstanceValidation(action, requestDetails, requestParameters);
-
- }
-
- private void relatedInstanceValidation(Action action, RequestDetails requestDetails, RequestParameters requestParameters) throws ValidationException {
- RelatedInstanceList[] instanceList = requestDetails.getRelatedInstanceList();
-
- if (requestParameters == null) {
- throw new ValidationException("requestParameters", true);
- }
- if((Action.activate.equals(action) || Action.deactivate.equals(action)) && OperationalEnvironment.ECOMP.equals(requestParameters.getOperationalEnvironmentType())) {
- throw new ValidationException("operationalEnvironmentType in requestParameters", true);
- }
-
- if(!Action.deactivate.equals(action) && OperationalEnvironment.VNF.equals(requestParameters.getOperationalEnvironmentType())) {
- if(instanceList != null && instanceList.length > 0) {
- for(RelatedInstanceList relatedInstanceList : instanceList){
- RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
-
- if(relatedInstance.getResourceType() == null) {
- throw new ValidationException("ResourceType in relatedInstance", true);
- }
-
- if(!empty(relatedInstance.getInstanceName()) && !relatedInstance.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) {
- throw new ValidationException ("instanceName format", true);
- }
-
- if (empty (relatedInstance.getInstanceId ())) {
- throw new ValidationException ("instanceId in relatedInstance", true);
- }
-
- if (!UUIDChecker.isValidUUID (relatedInstance.getInstanceId ())) {
- throw new ValidationException ("instanceId format in relatedInstance", true);
- }
- }
- } else {
- throw new ValidationException ("relatedInstanceList", true);
- }
- }
- }
-
- private void requestParamsValidation(Action action, RequestParameters requestParameters) throws ValidationException {
-
- if(requestParameters != null) {
- if(!Action.deactivate.equals(action) && requestParameters.getOperationalEnvironmentType() == null) {
- throw new ValidationException ("OperationalEnvironmentType", true);
- }
-
- if (Action.create.equals(action) && empty(requestParameters.getTenantContext())) {
- throw new ValidationException ("Tenant Context", true);
- }
- if (!Action.deactivate.equals(action) && empty(requestParameters.getWorkloadContext())) {
- throw new ValidationException ("Workload Context", true);
- }
-
- Manifest manifest = requestParameters.getManifest();
-
- if(Action.activate.equals(action)) {
- if(manifest == null) {
- throw new ValidationException ("Manifest on Activate", true);
- } else {
- List<ServiceModelList> serviceModelList = manifest.getServiceModelList();
-
- if(serviceModelList.isEmpty()) {
- throw new ValidationException (" empty ServiceModelList", true);
- }
-
- for(ServiceModelList list : serviceModelList) {
- if(empty(list.getServiceModelVersionId())) {
- throw new ValidationException ("ServiceModelVersionId", true);
- }
-
- if (!UUIDChecker.isValidUUID (list.getServiceModelVersionId())) {
- throw new ValidationException ("ServiceModelVersionId format", true);
- }
-
- if(list.getRecoveryAction() == null) {
- throw new ValidationException ("RecoveryAction", true);
- }
- }
- }
- }
- } else if(!Action.deactivate.equals(action)) {
- throw new ValidationException("request Parameters", true);
- }
- }
-
- private void requestInfoValidation(Action action, RequestInfo requestInfo) throws ValidationException {
-
- if(Action.create.equals(action) && empty(requestInfo.getInstanceName())) {
- throw new ValidationException ("instanceName", true);
- }
-
- if(!empty(requestInfo.getInstanceName()) && !requestInfo.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) {
- throw new ValidationException ("instanceName format", true);
- }
-
- if (empty(requestInfo.getSource())) {
- throw new ValidationException ("source", true);
+
+ if (empty(requestInfo.getRequestorId())) {
+ throw new ValidationException("requestorId", true);
}
-
- if(empty(requestInfo.getRequestorId())) {
- throw new ValidationException ("requestorId", true);
+
+ ResourceType resourceType = requestInfo.getResourceType();
+ if (resourceType == null) {
+ throw new ValidationException("resourceType", true);
}
-
- ResourceType resourceType = requestInfo.getResourceType();
- if(resourceType == null) {
- throw new ValidationException ("resourceType", true);
- }
-
- this.requestScope = resourceType.name();
- }
-
- void parseOrchestration (CloudOrchestrationRequest cor) throws ValidationException {
+
+ this.requestScope = resourceType.name();
+ }
+
+ void parseOrchestration(CloudOrchestrationRequest cor) throws ValidationException {
this.cor = cor;
- try{
- ObjectMapper mapper = new ObjectMapper();
- requestJSON = mapper.writeValueAsString(cor.getRequestDetails());
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ requestJSON = mapper.writeValueAsString(cor.getRequestDetails());
- } catch(JsonProcessingException e){
- throw new ValidationException ("Parse CloudOrchestrationRequest to JSON string", e);
+ } catch (JsonProcessingException e) {
+ throw new ValidationException("Parse CloudOrchestrationRequest to JSON string", e);
}
- if(cor.getRequestDetails() == null){
+ if (cor.getRequestDetails() == null) {
throw new ValidationException("requestDetails", true);
}
this.requestInfo = cor.getRequestDetails().getRequestInfo();
if (this.requestInfo == null) {
- throw new ValidationException ("requestInfo", true);
+ throw new ValidationException("requestInfo", true);
}
- if (empty (requestInfo.getSource ())) {
- throw new ValidationException ("source", true);
+ if (empty(requestInfo.getSource())) {
+ throw new ValidationException("source", true);
}
- if (empty (requestInfo.getRequestorId ())) {
- throw new ValidationException ("requestorId", true);
+ if (empty(requestInfo.getRequestorId())) {
+ throw new ValidationException("requestorId", true);
}
}
-
- public void createRequestRecord (Status status, Action action){
-
- InfraActiveRequests aq = new InfraActiveRequests ();
- aq.setRequestId (requestId);
-
- aq.setRequestAction(action.name());
- aq.setAction(action.name());
-
- Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
-
- aq.setStartTime (startTimeStamp);
-
- if (requestInfo != null) {
-
- if(requestInfo.getSource() != null){
- aq.setSource(requestInfo.getSource());
- }
- if(requestInfo.getRequestorId() != null) {
- aq.setRequestorId(requestInfo.getRequestorId());
- }
- if(requestInfo.getResourceType() != null) {
- aq.setRequestScope(requestInfo.getResourceType().name());
- }
- }
-
- if(ResourceType.operationalEnvironment.name().equalsIgnoreCase(requestScope) && requestInfo != null) {
- aq.setOperationalEnvId(operationalEnvironmentId);
- aq.setOperationalEnvName(requestInfo.getInstanceName());
- }
-
- aq.setRequestBody (this.requestJSON);
-
- aq.setRequestStatus (status.toString ());
- aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER);
-
- if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
- aq.setStatusMessage (this.errorMessage);
- aq.setResponseBody (this.responseBody);
- aq.setProgress(Long.valueOf(100));
-
- Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis());
- aq.setEndTime (endTimeStamp);
- } else if(status == Status.IN_PROGRESS) {
- aq.setProgress(Constants.PROGRESS_REQUEST_IN_PROGRESS);
- }
- requestsDbClient.save(aq);
+
+ public void createRequestRecord(Status status, Action action) {
+
+ InfraActiveRequests aq = new InfraActiveRequests();
+ aq.setRequestId(requestId);
+
+ aq.setRequestAction(action.name());
+ aq.setAction(action.name());
+
+ Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
+
+ aq.setStartTime(startTimeStamp);
+
+ if (requestInfo != null) {
+
+ if (requestInfo.getSource() != null) {
+ aq.setSource(requestInfo.getSource());
+ }
+ if (requestInfo.getRequestorId() != null) {
+ aq.setRequestorId(requestInfo.getRequestorId());
+ }
+ if (requestInfo.getResourceType() != null) {
+ aq.setRequestScope(requestInfo.getResourceType().name());
+ }
+ }
+
+ if (ResourceType.operationalEnvironment.name().equalsIgnoreCase(requestScope) && requestInfo != null) {
+ aq.setOperationalEnvId(operationalEnvironmentId);
+ aq.setOperationalEnvName(requestInfo.getInstanceName());
+ }
+
+ aq.setRequestBody(this.requestJSON);
+
+ aq.setRequestStatus(status.toString());
+ aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+
+ if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
+ aq.setStatusMessage(this.errorMessage);
+ aq.setResponseBody(this.responseBody);
+ aq.setProgress(Long.valueOf(100));
+
+ Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
+ aq.setEndTime(endTimeStamp);
+ } else if (status == Status.IN_PROGRESS) {
+ aq.setProgress(Constants.PROGRESS_REQUEST_IN_PROGRESS);
+ }
+ requestsDbClient.save(aq);
}
-
-
- public Map<String, String> getOrchestrationFilters (MultivaluedMap<String, String> queryParams) throws ValidationException {
+
+
+ public Map<String, String> getOrchestrationFilters(MultivaluedMap<String, String> queryParams)
+ throws ValidationException {
String queryParam = null;
Map<String, String> orchestrationFilterParams = new HashMap<>();
- for (Entry<String,List<String>> entry : queryParams.entrySet()) {
+ for (Entry<String, List<String>> entry : queryParams.entrySet()) {
queryParam = entry.getKey();
- try{
- for(String value : entry.getValue()) {
- if(StringUtils.isBlank(value)) {
- throw (new Exception(queryParam + " value"));
- }
- orchestrationFilterParams.put(queryParam, value);
- }
- }catch(Exception e){
- throw new ValidationException (e.getMessage(), true);
- }
+ try {
+ for (String value : entry.getValue()) {
+ if (StringUtils.isBlank(value)) {
+ throw (new Exception(queryParam + " value"));
+ }
+ orchestrationFilterParams.put(queryParam, value);
+ }
+ } catch (Exception e) {
+ throw new ValidationException(e.getMessage(), true);
+ }
}
return orchestrationFilterParams;
- }
+ }
+
+ private static boolean empty(String s) {
+ return (s == null || s.trim().isEmpty());
+ }
- private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
- }
-
- public String getRequestId () {
+ public String getRequestId() {
return requestId;
}
-
+
public void setRequestId(String requestId) {
- this.requestId = requestId;
+ this.requestId = requestId;
+ }
+
+ public void updateFinalStatus() {
+ try {
+ InfraActiveRequests request = new InfraActiveRequests(requestId);
+ request.setRequestStatus(status.toString());
+ request.setStatusMessage(this.errorMessage);
+ request.setProgress(this.progress);
+ request.setResponseBody(this.responseBody);
+ request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ requestsDbClient.save(request);
+ } catch (Exception e) {
+ logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(),
+ ErrorCode.DataError.getValue(), "Exception when updating record in DB");
+ logger.debug("Exception: ", e);
+ }
}
- public void updateFinalStatus() {
- try {
- InfraActiveRequests request = new InfraActiveRequests(requestId);
- request.setRequestStatus(status.toString());
- request.setStatusMessage(this.errorMessage);
- request.setProgress(this.progress);
- request.setResponseBody(this.responseBody);
- request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
- requestsDbClient.save(request);
- } catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(),
- ErrorCode.DataError.getValue(), "Exception when updating record in DB");
- logger.debug("Exception: ", e);
- }
- }
-
- public void setStatus (RequestStatusType status) {
+ public void setStatus(RequestStatusType status) {
this.status = status;
switch (status) {
- case FAILED:
- case COMPLETE:
- this.progress = Constants.PROGRESS_REQUEST_COMPLETED;
- break;
- case IN_PROGRESS:
- this.progress = Constants.PROGRESS_REQUEST_IN_PROGRESS;
- break;
- case PENDING:
- break;
- case TIMEOUT:
- break;
- case UNLOCKED:
- break;
- default:
- break;
+ case FAILED:
+ case COMPLETE:
+ this.progress = Constants.PROGRESS_REQUEST_COMPLETED;
+ break;
+ case IN_PROGRESS:
+ this.progress = Constants.PROGRESS_REQUEST_IN_PROGRESS;
+ break;
+ case PENDING:
+ break;
+ case TIMEOUT:
+ break;
+ case UNLOCKED:
+ break;
+ default:
+ break;
}
}
- public String getOperationalEnvironmentId() {
- return operationalEnvironmentId;
- }
+ public String getOperationalEnvironmentId() {
+ return operationalEnvironmentId;
+ }
- public void setOperationalEnvironmentId(String operationalEnvironmentId) {
- this.operationalEnvironmentId = operationalEnvironmentId;
- }
+ public void setOperationalEnvironmentId(String operationalEnvironmentId) {
+ this.operationalEnvironmentId = operationalEnvironmentId;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRunnable.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRunnable.java
index 98104e9073..b2596f9013 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRunnable.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRunnable.java
@@ -48,57 +48,63 @@ import org.springframework.stereotype.Component;
@Scope("prototype")
public class TenantIsolationRunnable {
- private static final Logger logger = LoggerFactory.getLogger(TenantIsolationRunnable.class);
-
- @Autowired
- private RequestsDBHelper requestDb;
- @Autowired
- private CreateEcompOperationalEnvironment createEcompOpEnv;
- @Autowired
- private CreateVnfOperationalEnvironment createVnfOpEnv;
- @Autowired
- private ActivateVnfOperationalEnvironment activateVnfOpEnv;
- @Autowired
- private DeactivateVnfOperationalEnvironment deactivateVnfOpEnv;
- @Autowired
- private ActivateVnfStatusOperationalEnvironment activateVnfStatusOpEnv;
-
- @Async
- public void run(Action action, String operationalEnvType, CloudOrchestrationRequest cor, String requestId) throws ApiException {
+ private static final Logger logger = LoggerFactory.getLogger(TenantIsolationRunnable.class);
- logger.debug("Starting threadExecution in TenantIsolationRunnable for Action {} and OperationalEnvType: {}",
- action.name(), operationalEnvType);
- try {
-
- if(Action.create.equals(action)) {
- if(OperationalEnvironment.ECOMP.name().equalsIgnoreCase(operationalEnvType)) {
- createEcompOpEnv.execute(requestId, cor);
- } else if(OperationalEnvironment.VNF.name().equalsIgnoreCase(operationalEnvType)) {
- createVnfOpEnv.execute(requestId, cor);
- } else {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
- ValidateException validateException = new ValidateException.Builder("Invalid OperationalEnvironment Type specified for Create Action",
+ @Autowired
+ private RequestsDBHelper requestDb;
+ @Autowired
+ private CreateEcompOperationalEnvironment createEcompOpEnv;
+ @Autowired
+ private CreateVnfOperationalEnvironment createVnfOpEnv;
+ @Autowired
+ private ActivateVnfOperationalEnvironment activateVnfOpEnv;
+ @Autowired
+ private DeactivateVnfOperationalEnvironment deactivateVnfOpEnv;
+ @Autowired
+ private ActivateVnfStatusOperationalEnvironment activateVnfStatusOpEnv;
+
+ @Async
+ public void run(Action action, String operationalEnvType, CloudOrchestrationRequest cor, String requestId)
+ throws ApiException {
+
+ logger.debug("Starting threadExecution in TenantIsolationRunnable for Action {} and OperationalEnvType: {}",
+ action.name(), operationalEnvType);
+ try {
+
+ if (Action.create.equals(action)) {
+ if (OperationalEnvironment.ECOMP.name().equalsIgnoreCase(operationalEnvType)) {
+ createEcompOpEnv.execute(requestId, cor);
+ } else if (OperationalEnvironment.VNF.name().equalsIgnoreCase(operationalEnvType)) {
+ createVnfOpEnv.execute(requestId, cor);
+ } else {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError)
+ .build();
+ ValidateException validateException = new ValidateException.Builder(
+ "Invalid OperationalEnvironment Type specified for Create Action",
HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
- .build();
+ .build();
throw validateException;
- }
- } else if(Action.activate.equals(action)) {
- activateVnfOpEnv.execute(requestId, cor);
- } else if(Action.deactivate.equals(action)) {
- deactivateVnfOpEnv.execute(requestId, cor);
- } else if(Action.distributionStatus.equals(action)) {
- activateVnfStatusOpEnv.execute(requestId, cor);
- } else {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
- ValidateException validateException = new ValidateException.Builder("Invalid Action specified: " + action,
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
+ }
+ } else if (Action.activate.equals(action)) {
+ activateVnfOpEnv.execute(requestId, cor);
+ } else if (Action.deactivate.equals(action)) {
+ deactivateVnfOpEnv.execute(requestId, cor);
+ } else if (Action.distributionStatus.equals(action)) {
+ activateVnfStatusOpEnv.execute(requestId, cor);
+ } else {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
+ ValidateException validateException =
+ new ValidateException.Builder("Invalid Action specified: " + action, HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
throw validateException;
- }
- }catch(ApiException e) {
+ }
+ } catch (ApiException e) {
requestDb.updateInfraFailureCompletion(e.getMessage(), requestId, cor.getOperationalEnvironmentId());
throw e;
}
- }
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/CreateEcompOperationEnvironmentBean.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/CreateEcompOperationEnvironmentBean.java
index 44198d727d..d79e5311c7 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/CreateEcompOperationEnvironmentBean.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/CreateEcompOperationEnvironmentBean.java
@@ -26,137 +26,132 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "operationalEnvironmentId",
- "operationalEnvironmentName",
- "operationalEnvironmentType",
- "tenantContext",
- "workloadContext"
-})
+@JsonPropertyOrder({"operationalEnvironmentId", "operationalEnvironmentName", "operationalEnvironmentType",
+ "tenantContext", "workloadContext"})
public class CreateEcompOperationEnvironmentBean {
- @JsonProperty("operationalEnvironmentId")
- private String operationalEnvironmentId;
- @JsonProperty("operationalEnvironmentName")
- private String operationalEnvironmentName;
- @JsonProperty("operationalEnvironmentType")
- private String operationalEnvironmentType;
- @JsonProperty("tenantContext")
- private String tenantContext;
- @JsonProperty("workloadContext")
- private String workloadContext;
- @JsonProperty("action")
- private String action;
-
- public CreateEcompOperationEnvironmentBean() {}
-
- /**
- *
- * @param operationalEnvironmentId
- * @param operationalEnvironmentName
- * @param operationalEnvironmentType
- * @param tenantContext
- * @param workloadContext
- */
- public CreateEcompOperationEnvironmentBean(String operationalEnvironmentId, String operationalEnvironmentName, String operationalEnvironmentType,
- String tenantContext, String workloadContext, String action) {
- this.operationalEnvironmentId = operationalEnvironmentId;
- this.operationalEnvironmentName = operationalEnvironmentName;
- this.operationalEnvironmentType = operationalEnvironmentType;
- this.tenantContext = tenantContext;
- this.workloadContext = workloadContext;
- this.action = action;
- }
-
- @JsonProperty("operationalEnvironmentId")
- public String getOperationalEnvironmentId() {
- return operationalEnvironmentId;
- }
-
- @JsonProperty("operationalEnvironmentId")
- public void setOperationalEnvironmentId(String operationalEnvironmentId) {
- this.operationalEnvironmentId = operationalEnvironmentId;
- }
-
- public CreateEcompOperationEnvironmentBean withOperationalEnvironmentId(String operationalEnvironmentId) {
- this.operationalEnvironmentId = operationalEnvironmentId;
- return this;
- }
-
-
- @JsonProperty("operationalEnvironmentName")
- public String getoperationalEnvironmentName() {
- return operationalEnvironmentName;
- }
-
- @JsonProperty("operationalEnvironmentName")
- public void setoperationalEnvironmentName(String operationalEnvironmentName) {
- this.operationalEnvironmentName = operationalEnvironmentName;
- }
-
- public CreateEcompOperationEnvironmentBean withOperationalEnvironmentName(String operationalEnvironmentName) {
- this.operationalEnvironmentName = operationalEnvironmentName;
- return this;
- }
-
- @JsonProperty("operationalEnvironmentType")
- public String getoperationalEnvironmentType() {
- return operationalEnvironmentType;
- }
-
- @JsonProperty("operationalEnvironmentType")
- public void setoperationalEnvironmentType(String operationalEnvironmentType) {
- this.operationalEnvironmentType = operationalEnvironmentType;
- }
-
- public CreateEcompOperationEnvironmentBean withOperationalEnvironmentType(String operationalEnvironmentType) {
- this.operationalEnvironmentType = operationalEnvironmentType;
- return this;
- }
-
- @JsonProperty("tenantContext")
- public String gettenantContext() {
- return tenantContext;
- }
-
- @JsonProperty("tenantContext")
- public void settenantContext(String tenantContext) {
- this.tenantContext = tenantContext;
- }
-
- public CreateEcompOperationEnvironmentBean withTenantContext(String tenantContext) {
- this.tenantContext = tenantContext;
- return this;
- }
-
- @JsonProperty("workloadContext")
- public String getworkloadContext() {
- return workloadContext;
- }
-
- @JsonProperty("workloadContext")
- public void setworkloadContext(String workloadContext) {
- this.workloadContext = workloadContext;
- }
-
- public CreateEcompOperationEnvironmentBean withWorkloadContext(String workloadContext) {
- this.workloadContext = workloadContext;
- return this;
- }
-
- @JsonProperty("action")
- public String getaction() {
- return action;
- }
-
- @JsonProperty("action")
- public void setaction(String action) {
- this.action = action;
- }
-
- public CreateEcompOperationEnvironmentBean withaction(String action) {
- this.action = action;
- return this;
- }
+ @JsonProperty("operationalEnvironmentId")
+ private String operationalEnvironmentId;
+ @JsonProperty("operationalEnvironmentName")
+ private String operationalEnvironmentName;
+ @JsonProperty("operationalEnvironmentType")
+ private String operationalEnvironmentType;
+ @JsonProperty("tenantContext")
+ private String tenantContext;
+ @JsonProperty("workloadContext")
+ private String workloadContext;
+ @JsonProperty("action")
+ private String action;
+
+ public CreateEcompOperationEnvironmentBean() {}
+
+ /**
+ *
+ * @param operationalEnvironmentId
+ * @param operationalEnvironmentName
+ * @param operationalEnvironmentType
+ * @param tenantContext
+ * @param workloadContext
+ */
+ public CreateEcompOperationEnvironmentBean(String operationalEnvironmentId, String operationalEnvironmentName,
+ String operationalEnvironmentType, String tenantContext, String workloadContext, String action) {
+ this.operationalEnvironmentId = operationalEnvironmentId;
+ this.operationalEnvironmentName = operationalEnvironmentName;
+ this.operationalEnvironmentType = operationalEnvironmentType;
+ this.tenantContext = tenantContext;
+ this.workloadContext = workloadContext;
+ this.action = action;
+ }
+
+ @JsonProperty("operationalEnvironmentId")
+ public String getOperationalEnvironmentId() {
+ return operationalEnvironmentId;
+ }
+
+ @JsonProperty("operationalEnvironmentId")
+ public void setOperationalEnvironmentId(String operationalEnvironmentId) {
+ this.operationalEnvironmentId = operationalEnvironmentId;
+ }
+
+ public CreateEcompOperationEnvironmentBean withOperationalEnvironmentId(String operationalEnvironmentId) {
+ this.operationalEnvironmentId = operationalEnvironmentId;
+ return this;
+ }
+
+
+ @JsonProperty("operationalEnvironmentName")
+ public String getoperationalEnvironmentName() {
+ return operationalEnvironmentName;
+ }
+
+ @JsonProperty("operationalEnvironmentName")
+ public void setoperationalEnvironmentName(String operationalEnvironmentName) {
+ this.operationalEnvironmentName = operationalEnvironmentName;
+ }
+
+ public CreateEcompOperationEnvironmentBean withOperationalEnvironmentName(String operationalEnvironmentName) {
+ this.operationalEnvironmentName = operationalEnvironmentName;
+ return this;
+ }
+
+ @JsonProperty("operationalEnvironmentType")
+ public String getoperationalEnvironmentType() {
+ return operationalEnvironmentType;
+ }
+
+ @JsonProperty("operationalEnvironmentType")
+ public void setoperationalEnvironmentType(String operationalEnvironmentType) {
+ this.operationalEnvironmentType = operationalEnvironmentType;
+ }
+
+ public CreateEcompOperationEnvironmentBean withOperationalEnvironmentType(String operationalEnvironmentType) {
+ this.operationalEnvironmentType = operationalEnvironmentType;
+ return this;
+ }
+
+ @JsonProperty("tenantContext")
+ public String gettenantContext() {
+ return tenantContext;
+ }
+
+ @JsonProperty("tenantContext")
+ public void settenantContext(String tenantContext) {
+ this.tenantContext = tenantContext;
+ }
+
+ public CreateEcompOperationEnvironmentBean withTenantContext(String tenantContext) {
+ this.tenantContext = tenantContext;
+ return this;
+ }
+
+ @JsonProperty("workloadContext")
+ public String getworkloadContext() {
+ return workloadContext;
+ }
+
+ @JsonProperty("workloadContext")
+ public void setworkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
+
+ public CreateEcompOperationEnvironmentBean withWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ return this;
+ }
+
+ @JsonProperty("action")
+ public String getaction() {
+ return action;
+ }
+
+ @JsonProperty("action")
+ public void setaction(String action) {
+ this.action = action;
+ }
+
+ public CreateEcompOperationEnvironmentBean withaction(String action) {
+ this.action = action;
+ return this;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClient.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClient.java
index 55b1ea6198..340d143b42 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClient.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClient.java
@@ -21,9 +21,7 @@
package org.onap.so.apihandlerinfra.tenantisolation.dmaap;
import java.io.IOException;
-
import javax.inject.Provider;
-
import org.apache.http.HttpStatus;
import org.onap.so.apihandler.common.ErrorNumbers;
import org.onap.so.apihandlerinfra.exceptions.ApiException;
@@ -33,49 +31,53 @@ import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class DmaapOperationalEnvClient {
- @Autowired
- private Provider<OperationalEnvironmentPublisher> dmaapPublisher;
-
- protected String buildRequest(String operationalEnvironmentId, String operationalEnvironmentName, String operationalEnvironmentType, String tenantContext, String workloadContext, String action )
- throws ApiException {
- final CreateEcompOperationEnvironmentBean operationalEnv = new CreateEcompOperationEnvironmentBean();
- operationalEnv.withOperationalEnvironmentId(operationalEnvironmentId)
- .withOperationalEnvironmentName(operationalEnvironmentName)
- .withOperationalEnvironmentType(operationalEnvironmentType)
- .withTenantContext(tenantContext)
- .withWorkloadContext(workloadContext)
- .withaction(action);
- try {
- return this.getJson(operationalEnv);
- }catch(JsonProcessingException ex){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build();
- ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed : " + ex.getMessage(),
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(ex).errorInfo(errorLoggerInfo).build();
+ @Autowired
+ private Provider<OperationalEnvironmentPublisher> dmaapPublisher;
+
+ protected String buildRequest(String operationalEnvironmentId, String operationalEnvironmentName,
+ String operationalEnvironmentType, String tenantContext, String workloadContext, String action)
+ throws ApiException {
+ final CreateEcompOperationEnvironmentBean operationalEnv = new CreateEcompOperationEnvironmentBean();
+ operationalEnv.withOperationalEnvironmentId(operationalEnvironmentId)
+ .withOperationalEnvironmentName(operationalEnvironmentName)
+ .withOperationalEnvironmentType(operationalEnvironmentType).withTenantContext(tenantContext)
+ .withWorkloadContext(workloadContext).withaction(action);
+ try {
+ return this.getJson(operationalEnv);
+ } catch (JsonProcessingException ex) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .build();
+ ValidateException validateException =
+ new ValidateException.Builder("Mapping of request to JSON object failed : " + ex.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(ex)
+ .errorInfo(errorLoggerInfo).build();
+
+ throw validateException;
+ }
+ }
+
+ protected String getJson(CreateEcompOperationEnvironmentBean obj) throws JsonProcessingException {
+
+ final ObjectMapper mapper = new ObjectMapper();
+ return mapper.writeValueAsString(obj);
- throw validateException;
- }
- }
+ }
- protected String getJson(CreateEcompOperationEnvironmentBean obj) throws JsonProcessingException {
-
- final ObjectMapper mapper = new ObjectMapper();
- return mapper.writeValueAsString(obj);
-
- }
-
- public void dmaapPublishOperationalEnvRequest(String operationalEnvironmentId, String operationalEnvironmentName, String operationalEnvironmentType,
- String tenantContext, String workloadContext, String action ) throws ApiException, IOException, InterruptedException {
+ public void dmaapPublishOperationalEnvRequest(String operationalEnvironmentId, String operationalEnvironmentName,
+ String operationalEnvironmentType, String tenantContext, String workloadContext, String action)
+ throws ApiException, IOException, InterruptedException {
- String request = this.buildRequest(operationalEnvironmentId, operationalEnvironmentName, operationalEnvironmentType, tenantContext, workloadContext, action);
- dmaapPublisher.get().send(request);
+ String request = this.buildRequest(operationalEnvironmentId, operationalEnvironmentName,
+ operationalEnvironmentType, tenantContext, workloadContext, action);
+ dmaapPublisher.get().send(request);
- }
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapPropertiesImpl.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapPropertiesImpl.java
index 8409d9c300..4ba69f55e9 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapPropertiesImpl.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapPropertiesImpl.java
@@ -22,34 +22,30 @@ package org.onap.so.apihandlerinfra.tenantisolation.dmaap;
import java.util.HashMap;
import java.util.Map;
-
import org.onap.so.client.dmaap.DmaapProperties;
import org.onap.so.spring.SpringContextHelper;
import org.springframework.context.ApplicationContext;
public class DmaapPropertiesImpl implements DmaapProperties {
- private final Map<String, String> props = new HashMap<>();
- private static final String[] propertyNames = {
- "mso.so.operational-environment.dmaap.auth",
- "mso.msoKey",
- "mso.so.operational-environment.publisher.topic",
- "mso.so.operational-environment.dmaap.host"
- };
- public DmaapPropertiesImpl () {
- ApplicationContext context = SpringContextHelper.getAppContext();
-
- for (String name : propertyNames) {
- this.props.put(name, context.getEnvironment().getProperty(name));
-
- }
-
- }
-
- @Override
- public Map<String, String> getProperties() {
-
- return this.props;
- }
+ private final Map<String, String> props = new HashMap<>();
+ private static final String[] propertyNames = {"mso.so.operational-environment.dmaap.auth", "mso.msoKey",
+ "mso.so.operational-environment.publisher.topic", "mso.so.operational-environment.dmaap.host"};
+
+ public DmaapPropertiesImpl() {
+ ApplicationContext context = SpringContextHelper.getAppContext();
+
+ for (String name : propertyNames) {
+ this.props.put(name, context.getEnvironment().getProperty(name));
+
+ }
+
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+
+ return this.props;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisher.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisher.java
index 31bc6fcb4f..350a091d97 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisher.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisher.java
@@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra.tenantisolation.dmaap;
import java.io.IOException;
import java.util.Optional;
-
import org.onap.so.client.dmaap.DmaapPublisher;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@@ -31,31 +30,31 @@ import org.springframework.stereotype.Component;
@Scope("prototype")
public class OperationalEnvironmentPublisher extends DmaapPublisher {
-
- public OperationalEnvironmentPublisher() throws IOException {
- super();
- }
-
- @Override
- public String getAuth() {
-
- return this.msoProperties.get("mso.so.operational-environment.dmaap.auth");
- }
-
- @Override
- public String getKey() {
-
- return this.msoProperties.get("mso.msoKey");
- }
-
- @Override
- public String getTopic() {
-
- return this.msoProperties.get("mso.so.operational-environment.publisher.topic");
- }
-
- @Override
- public Optional<String> getHost() {
- return Optional.ofNullable(this.msoProperties.get("mso.so.operational-environment.dmaap.host"));
- }
+
+ public OperationalEnvironmentPublisher() throws IOException {
+ super();
+ }
+
+ @Override
+ public String getAuth() {
+
+ return this.msoProperties.get("mso.so.operational-environment.dmaap.auth");
+ }
+
+ @Override
+ public String getKey() {
+
+ return this.msoProperties.get("mso.msoKey");
+ }
+
+ @Override
+ public String getTopic() {
+
+ return this.msoProperties.get("mso.so.operational-environment.publisher.topic");
+ }
+
+ @Override
+ public Optional<String> getHost() {
+ return Optional.ofNullable(this.msoProperties.get("mso.so.operational-environment.dmaap.host"));
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailed.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailed.java
index 4f4fa1ae35..3ceb8e7897 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailed.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailed.java
@@ -22,8 +22,8 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions;
public class AAIClientCallFailed extends Exception {
- public AAIClientCallFailed(String message, Throwable cause) {
- super(message, cause);
- }
+ public AAIClientCallFailed(String message, Throwable cause) {
+ super(message, cause);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailed.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailed.java
index 9cdef3c9d1..cacbb557b2 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailed.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailed.java
@@ -22,15 +22,15 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions;
public class SDCClientCallFailed extends Exception {
- private static final long serialVersionUID = 3066575499816576134L;
+ private static final long serialVersionUID = 3066575499816576134L;
+
+ public SDCClientCallFailed(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public SDCClientCallFailed(String message) {
+ super(message);
+ }
- public SDCClientCallFailed(String message, Throwable cause) {
- super(message, cause);
- }
- public SDCClientCallFailed(String message) {
- super(message);
- }
-
-
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationException.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationException.java
index af3e7937af..14e6464960 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationException.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationException.java
@@ -22,15 +22,15 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions;
public class TenantIsolationException extends Exception {
- private static final long serialVersionUID = 6948152225371031774L;
-
- public TenantIsolationException() {
- super();
-
- }
-
- public TenantIsolationException(String msg) {
- super ("Tenant Isolation error: " + msg);
-
- }
-} \ No newline at end of file
+ private static final long serialVersionUID = 6948152225371031774L;
+
+ public TenantIsolationException() {
+ super();
+
+ }
+
+ public TenantIsolationException(String msg) {
+ super("Tenant Isolation error: " + msg);
+
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java
index 870fa11b5c..8b3b91ae1a 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java
@@ -25,9 +25,7 @@ package org.onap.so.apihandlerinfra.tenantisolation.helpers;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
-
import javax.ws.rs.NotFoundException;
-
import org.onap.aai.domain.yang.OperationalEnvironment;
import org.onap.so.apihandlerinfra.tenantisolation.exceptions.AAIClientCallFailed;
import org.onap.so.client.aai.AAIObjectType;
@@ -43,81 +41,89 @@ import org.springframework.stereotype.Component;
@Component
public class AAIClientHelper {
-
- private static Logger logger = LoggerFactory.getLogger(AAIClientHelper.class);
-
- /**
- * Get managing ECOMP Environment Info from A&AI
- * @param id = operationalEnvironmentId
- * @return AAIResultWrapper object
- */
- public AAIResultWrapper getAaiOperationalEnvironment(String id){
-
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, id);
- uri.depth(Depth.ZERO);
- AAIResourcesClient client = this.getClient();
- return client.get(uri, NotFoundException.class);
- }
-
-
- /**
- * Update managing ECOMP Environment Info from A&AI
- * @param id = operationalEnvironmentId
- * @param AAIOperationalEnvironment object
- */
- public void updateAaiOperationalEnvironment(String id, OperationalEnvironment aaiRequest){
-
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, id);
- AAIResourcesClient client = this.getClient();
- client.update(uri, aaiRequest);
-
- }
-
-
- public void updateAaiOperationalEnvironment(String operationalEnvironmentId, Map<String, String> payload) throws Exception {
- try {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, operationalEnvironmentId);
- AAIResourcesClient aaiClient = this.getClient();
- aaiClient.update(uri, payload);
- }
- catch(Exception ex) {
- logStackTrace(ex);
- throw new AAIClientCallFailed("Call to A&AI failed!", ex);
- }
- }
-
- /**
- * Create an Operational Environment object in A&AI
- * @param AAIOperationalEnvironment object
- */
- public void createOperationalEnvironment(OperationalEnvironment operationalEnvironment){
-
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, operationalEnvironment.getOperationalEnvironmentId());
- AAIResourcesClient client = this.getClient();
- client.create(uri, operationalEnvironment);
- }
-
- /**
- * Create a relationship between ECOMP managing and VNF Operational Environments
- * @param managingEcompOperationalEnvironmentId
- * @param vnfOperationalEnvironmentId
- * @throws Exception
- */
- public void createRelationship(String managingEcompOperationalEnvironmentId, String vnfOperationalEnvironmentId) {
-
- AAIResourceUri ecompEnvUri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, managingEcompOperationalEnvironmentId);
- AAIResourceUri vnfEnvUri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, vnfOperationalEnvironmentId);
- AAIResourcesClient client = this.getClient();
- client.connect(vnfEnvUri, ecompEnvUri);
-
- }
-
- private void logStackTrace(Exception e) {
- StringWriter sw = new StringWriter();
- e.printStackTrace(new PrintWriter(sw));
- }
-
- protected AAIResourcesClient getClient() {
- return new AAIResourcesClient();
- }
+
+ private static Logger logger = LoggerFactory.getLogger(AAIClientHelper.class);
+
+ /**
+ * Get managing ECOMP Environment Info from A&AI
+ *
+ * @param id = operationalEnvironmentId
+ * @return AAIResultWrapper object
+ */
+ public AAIResultWrapper getAaiOperationalEnvironment(String id) {
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, id);
+ uri.depth(Depth.ZERO);
+ AAIResourcesClient client = this.getClient();
+ return client.get(uri, NotFoundException.class);
+ }
+
+
+ /**
+ * Update managing ECOMP Environment Info from A&AI
+ *
+ * @param id = operationalEnvironmentId
+ * @param AAIOperationalEnvironment object
+ */
+ public void updateAaiOperationalEnvironment(String id, OperationalEnvironment aaiRequest) {
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, id);
+ AAIResourcesClient client = this.getClient();
+ client.update(uri, aaiRequest);
+
+ }
+
+
+ public void updateAaiOperationalEnvironment(String operationalEnvironmentId, Map<String, String> payload)
+ throws Exception {
+ try {
+ AAIResourceUri uri =
+ AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, operationalEnvironmentId);
+ AAIResourcesClient aaiClient = this.getClient();
+ aaiClient.update(uri, payload);
+ } catch (Exception ex) {
+ logStackTrace(ex);
+ throw new AAIClientCallFailed("Call to A&AI failed!", ex);
+ }
+ }
+
+ /**
+ * Create an Operational Environment object in A&AI
+ *
+ * @param AAIOperationalEnvironment object
+ */
+ public void createOperationalEnvironment(OperationalEnvironment operationalEnvironment) {
+
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT,
+ operationalEnvironment.getOperationalEnvironmentId());
+ AAIResourcesClient client = this.getClient();
+ client.create(uri, operationalEnvironment);
+ }
+
+ /**
+ * Create a relationship between ECOMP managing and VNF Operational Environments
+ *
+ * @param managingEcompOperationalEnvironmentId
+ * @param vnfOperationalEnvironmentId
+ * @throws Exception
+ */
+ public void createRelationship(String managingEcompOperationalEnvironmentId, String vnfOperationalEnvironmentId) {
+
+ AAIResourceUri ecompEnvUri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT,
+ managingEcompOperationalEnvironmentId);
+ AAIResourceUri vnfEnvUri =
+ AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, vnfOperationalEnvironmentId);
+ AAIResourcesClient client = this.getClient();
+ client.connect(vnfEnvUri, ecompEnvUri);
+
+ }
+
+ private void logStackTrace(Exception e) {
+ StringWriter sw = new StringWriter();
+ e.printStackTrace(new PrintWriter(sw));
+ }
+
+ protected AAIResourcesClient getClient() {
+ return new AAIResourcesClient();
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilder.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilder.java
index dc6019c9cb..b5294cd8b8 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilder.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilder.java
@@ -26,17 +26,21 @@ import org.springframework.stereotype.Component;
@Component
public class AAIClientObjectBuilder {
-
- public OperationalEnvironment buildAAIOperationalEnvironment(String status, CloudOrchestrationRequest cloudOrchestrationRequest) {
- OperationalEnvironment env = new OperationalEnvironment();
- env.setOperationalEnvironmentId(cloudOrchestrationRequest.getOperationalEnvironmentId());
- env.setOperationalEnvironmentName(cloudOrchestrationRequest.getRequestDetails().getRequestInfo().getInstanceName());
- env.setOperationalEnvironmentType(cloudOrchestrationRequest.getRequestDetails().getRequestParameters().getOperationalEnvironmentType().toString());
- env.setOperationalEnvironmentStatus(status);
- env.setTenantContext(cloudOrchestrationRequest.getRequestDetails().getRequestParameters().getTenantContext());
- env.setWorkloadContext(cloudOrchestrationRequest.getRequestDetails().getRequestParameters().getWorkloadContext());
- return env;
- }
+
+ public OperationalEnvironment buildAAIOperationalEnvironment(String status,
+ CloudOrchestrationRequest cloudOrchestrationRequest) {
+ OperationalEnvironment env = new OperationalEnvironment();
+ env.setOperationalEnvironmentId(cloudOrchestrationRequest.getOperationalEnvironmentId());
+ env.setOperationalEnvironmentName(
+ cloudOrchestrationRequest.getRequestDetails().getRequestInfo().getInstanceName());
+ env.setOperationalEnvironmentType(cloudOrchestrationRequest.getRequestDetails().getRequestParameters()
+ .getOperationalEnvironmentType().toString());
+ env.setOperationalEnvironmentStatus(status);
+ env.setTenantContext(cloudOrchestrationRequest.getRequestDetails().getRequestParameters().getTenantContext());
+ env.setWorkloadContext(
+ cloudOrchestrationRequest.getRequestDetails().getRequestParameters().getWorkloadContext());
+ return env;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java
index de1d9e9cfb..98b49d39d7 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java
@@ -30,94 +30,89 @@ import org.springframework.stereotype.Component;
@Component
public class ActivateVnfDBHelper {
-
- private static Logger logger = LoggerFactory.getLogger(ActivateVnfDBHelper.class);
-
- /**
- * Insert record to OperationalEnvServiceModelStatus table
- * @param requestId - String
- * @param operationalEnvironmentId - String
- * @param serviceModelVersionId - String
- * @param status - String
- * @param recoveryAction - String
- * @param retryCount - int
- * @param workloadContext - String
- * @return serviceModelStatus - OperationalEnvServiceModelStatus object
- */
- public OperationalEnvServiceModelStatus insertRecordToOperationalEnvServiceModelStatus( String requestId,
- String operationalEnvironmentId,
- String serviceModelVersionId,
- String status,
- String recoveryAction,
- int retryCount,
- String workloadContext,
- String vnfOperationalEnvironmentId) {
- OperationalEnvServiceModelStatus serviceModelStatus = new OperationalEnvServiceModelStatus();
- serviceModelStatus.setRequestId(requestId);
- serviceModelStatus.setOperationalEnvId(operationalEnvironmentId);
- serviceModelStatus.setServiceModelVersionId(serviceModelVersionId);
- serviceModelStatus.setServiceModelVersionDistrStatus(status);
- serviceModelStatus.setRecoveryAction(recoveryAction);
- serviceModelStatus.setRetryCount(new Integer(retryCount));
- serviceModelStatus.setWorkloadContext(workloadContext);
- serviceModelStatus.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
- return serviceModelStatus;
- }
- /**
- * Update RetryCount & Status in OperationalEnvServiceModelStatus table
- * @param serviceModelStatusResponse - OperationalEnvServiceModelStatus object
- * @param status - String
- * @param retryCount - int
- * @return serviceModelStatusResponse - OperationalEnvServiceModelStatus object
- */
- public OperationalEnvServiceModelStatus updateRetryCountAndStatusInOperationalEnvServiceModelStatus(OperationalEnvServiceModelStatus serviceModelStatusResponse,
- String status,
- int retryCount) {
- serviceModelStatusResponse.setServiceModelVersionDistrStatus(status);
- serviceModelStatusResponse.setRetryCount(new Integer(retryCount));
- return serviceModelStatusResponse;
- }
-
- /**
- * Insert record to OperationalEnvDistributionStatus table
- * @param distributionId - String
- * @param operationalEnvironmentId - String
- * @param serviceModelVersionId - String
- * @param requestId - String
- * @param status - String
- * @param distributionIdErrorReason - String
- * @return distStatus - OperationalEnvDistributionStatus object
- */
- public OperationalEnvDistributionStatus insertRecordToOperationalEnvDistributionStatus( String distributionId,
- String operationalEnvironmentId,
- String serviceModelVersionId,
- String requestId,
- String status,
- String distributionIdErrorReason) {
- OperationalEnvDistributionStatus distStatus = new OperationalEnvDistributionStatus();
- distStatus.setDistributionId(distributionId);
- distStatus.setOperationalEnvId(operationalEnvironmentId);
- distStatus.setServiceModelVersionId(serviceModelVersionId);
- distStatus.setRequestId(requestId);
- distStatus.setDistributionIdStatus(status);
- distStatus.setDistributionIdErrorReason(distributionIdErrorReason);
- return distStatus;
- }
-
- /**
- * Update Status in OperationalEnvDistributionStatus table
- * @param distributionStatusResponse - OperationalEnvDistributionStatus object
- * @param status - String
- * @param distributionIdErrorReason - String
- * @return distributionStatusResponse - OperationalEnvDistributionStatus object
- */
- public OperationalEnvDistributionStatus updateStatusInOperationalEnvDistributionStatus(OperationalEnvDistributionStatus distributionStatusResponse,
- String status,
- String distributionIdErrorReason) {
- distributionStatusResponse.setDistributionIdStatus(status);
- distributionStatusResponse.setDistributionIdErrorReason(distributionIdErrorReason);
- return distributionStatusResponse;
- }
-
+ private static Logger logger = LoggerFactory.getLogger(ActivateVnfDBHelper.class);
+
+ /**
+ * Insert record to OperationalEnvServiceModelStatus table
+ *
+ * @param requestId - String
+ * @param operationalEnvironmentId - String
+ * @param serviceModelVersionId - String
+ * @param status - String
+ * @param recoveryAction - String
+ * @param retryCount - int
+ * @param workloadContext - String
+ * @return serviceModelStatus - OperationalEnvServiceModelStatus object
+ */
+ public OperationalEnvServiceModelStatus insertRecordToOperationalEnvServiceModelStatus(String requestId,
+ String operationalEnvironmentId, String serviceModelVersionId, String status, String recoveryAction,
+ int retryCount, String workloadContext, String vnfOperationalEnvironmentId) {
+ OperationalEnvServiceModelStatus serviceModelStatus = new OperationalEnvServiceModelStatus();
+ serviceModelStatus.setRequestId(requestId);
+ serviceModelStatus.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelStatus.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelStatus.setServiceModelVersionDistrStatus(status);
+ serviceModelStatus.setRecoveryAction(recoveryAction);
+ serviceModelStatus.setRetryCount(new Integer(retryCount));
+ serviceModelStatus.setWorkloadContext(workloadContext);
+ serviceModelStatus.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
+ return serviceModelStatus;
+ }
+
+ /**
+ * Update RetryCount & Status in OperationalEnvServiceModelStatus table
+ *
+ * @param serviceModelStatusResponse - OperationalEnvServiceModelStatus object
+ * @param status - String
+ * @param retryCount - int
+ * @return serviceModelStatusResponse - OperationalEnvServiceModelStatus object
+ */
+ public OperationalEnvServiceModelStatus updateRetryCountAndStatusInOperationalEnvServiceModelStatus(
+ OperationalEnvServiceModelStatus serviceModelStatusResponse, String status, int retryCount) {
+ serviceModelStatusResponse.setServiceModelVersionDistrStatus(status);
+ serviceModelStatusResponse.setRetryCount(new Integer(retryCount));
+ return serviceModelStatusResponse;
+ }
+
+ /**
+ * Insert record to OperationalEnvDistributionStatus table
+ *
+ * @param distributionId - String
+ * @param operationalEnvironmentId - String
+ * @param serviceModelVersionId - String
+ * @param requestId - String
+ * @param status - String
+ * @param distributionIdErrorReason - String
+ * @return distStatus - OperationalEnvDistributionStatus object
+ */
+ public OperationalEnvDistributionStatus insertRecordToOperationalEnvDistributionStatus(String distributionId,
+ String operationalEnvironmentId, String serviceModelVersionId, String requestId, String status,
+ String distributionIdErrorReason) {
+ OperationalEnvDistributionStatus distStatus = new OperationalEnvDistributionStatus();
+ distStatus.setDistributionId(distributionId);
+ distStatus.setOperationalEnvId(operationalEnvironmentId);
+ distStatus.setServiceModelVersionId(serviceModelVersionId);
+ distStatus.setRequestId(requestId);
+ distStatus.setDistributionIdStatus(status);
+ distStatus.setDistributionIdErrorReason(distributionIdErrorReason);
+ return distStatus;
+ }
+
+ /**
+ * Update Status in OperationalEnvDistributionStatus table
+ *
+ * @param distributionStatusResponse - OperationalEnvDistributionStatus object
+ * @param status - String
+ * @param distributionIdErrorReason - String
+ * @return distributionStatusResponse - OperationalEnvDistributionStatus object
+ */
+ public OperationalEnvDistributionStatus updateStatusInOperationalEnvDistributionStatus(
+ OperationalEnvDistributionStatus distributionStatusResponse, String status,
+ String distributionIdErrorReason) {
+ distributionStatusResponse.setDistributionIdStatus(status);
+ distributionStatusResponse.setDistributionIdErrorReason(distributionIdErrorReason);
+ return distributionStatusResponse;
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java
index bf5623a9da..b5ba9281a6 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java
@@ -24,10 +24,8 @@ package org.onap.so.apihandlerinfra.tenantisolation.helpers;
import java.net.URL;
import java.util.UUID;
-
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
-
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -49,185 +47,198 @@ import org.springframework.stereotype.Component;
@Component
public class SDCClientHelper {
- private static Logger logger = LoggerFactory.getLogger(SDCClientHelper.class);
- private static final String SDC_CONTENT_TYPE = "application/json";
- private static final String SDC_ACCEPT_TYPE = "application/json";
- private static String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/";
-
- private static String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!";
- private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC.";
- private final HttpClientFactory httpClientFactory = new HttpClientFactory();
-
- @Value("${mso.sdc.endpoint}")
- private String sdcEndpoint;
- @Value("${mso.sdc.activate.userid}")
- private String sdcActivateUserId;
- @Value("${mso.sdc.activate.instanceid}")
- private String sdcActivateInstanceId;
- @Value("${mso.sdc.client.auth}")
- private String sdcClientAuth;
- @Value("${mso.msoKey}")
- private String msoKey;
-
- /**
- * Send POST request to SDC for operational activation
- * @param serviceModelVersionI - String
- * @param operationalEnvironmentId - String
- * @param workloadContext - String
- * @return sdcResponseJsonObj - JSONObject object
- * @throws JSONException
- */
- public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId, String workloadContext) throws ApiException {
- JSONObject sdcResponseJsonObj = new JSONObject();
-
- try {
- String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
- String jsonPayload = this.buildJsonWorkloadContext(workloadContext);
- String basicAuthCred = getBasicAuth();
-
- if ( basicAuthCred == null || "".equals(basicAuthCred) ) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
- ValidateException validateException = new ValidateException.Builder(" SDC credentials 'mso.sdc.client.auth' not setup in properties file!",
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+ private static Logger logger = LoggerFactory.getLogger(SDCClientHelper.class);
+ private static final String SDC_CONTENT_TYPE = "application/json";
+ private static final String SDC_ACCEPT_TYPE = "application/json";
+ private static String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/";
+
+ private static String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!";
+ private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC.";
+ private final HttpClientFactory httpClientFactory = new HttpClientFactory();
+
+ @Value("${mso.sdc.endpoint}")
+ private String sdcEndpoint;
+ @Value("${mso.sdc.activate.userid}")
+ private String sdcActivateUserId;
+ @Value("${mso.sdc.activate.instanceid}")
+ private String sdcActivateInstanceId;
+ @Value("${mso.sdc.client.auth}")
+ private String sdcClientAuth;
+ @Value("${mso.msoKey}")
+ private String msoKey;
+
+ /**
+ * Send POST request to SDC for operational activation
+ *
+ * @param serviceModelVersionI - String
+ * @param operationalEnvironmentId - String
+ * @param workloadContext - String
+ * @return sdcResponseJsonObj - JSONObject object
+ * @throws JSONException
+ */
+ public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId,
+ String workloadContext) throws ApiException {
+ JSONObject sdcResponseJsonObj = new JSONObject();
+
+ try {
+ String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
+ String jsonPayload = this.buildJsonWorkloadContext(workloadContext);
+ String basicAuthCred = getBasicAuth();
+
+ if (basicAuthCred == null || "".equals(basicAuthCred)) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
+ .build();
+ ValidateException validateException = new ValidateException.Builder(
+ " SDC credentials 'mso.sdc.client.auth' not setup in properties file!",
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo)
+ .build();
throw validateException;
- }
-
- URL url = new URL(urlString);
-
- HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.SDC);
- httpClient.addBasicAuthHeader(sdcClientAuth, msoKey);
- httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId);
- httpClient.addAdditionalHeader("X-ECOMP-RequestID", UUID.randomUUID().toString());
- httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE);
- httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE);
- httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId);
-
- Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
- int statusCode = apiResponse.getStatus();;
-
- String responseData = apiResponse.readEntity(String.class);
- sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
-
- } catch (Exception ex) {
- logger.debug("calling SDC Exception message: {}", ex.getMessage());
- String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
- logger.debug(errorMessage);
- sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
- sdcResponseJsonObj.put("messageId", "");
- sdcResponseJsonObj.put("message", errorMessage);
-
- }
- return sdcResponseJsonObj;
- }
-
- /**
- * set HttpPostResponse
- * @param config - RESTConfig object
- * @param jsonPayload - String
- * @return client - RestClient object
- */
- public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
- try {
+ }
+
+ URL url = new URL(urlString);
+
+ HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.SDC);
+ httpClient.addBasicAuthHeader(sdcClientAuth, msoKey);
+ httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId);
+ httpClient.addAdditionalHeader("X-ECOMP-RequestID", UUID.randomUUID().toString());
+ httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE);
+ httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE);
+ httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId);
+
+ Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
+ int statusCode = apiResponse.getStatus();;
+
+ String responseData = apiResponse.readEntity(String.class);
+ sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
+
+ } catch (Exception ex) {
+ logger.debug("calling SDC Exception message: {}", ex.getMessage());
+ String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
+ logger.debug(errorMessage);
+ sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
+ sdcResponseJsonObj.put("messageId", "");
+ sdcResponseJsonObj.put("message", errorMessage);
+
+ }
+ return sdcResponseJsonObj;
+ }
+
+ /**
+ * set HttpPostResponse
+ *
+ * @param config - RESTConfig object
+ * @param jsonPayload - String
+ * @return client - RestClient object
+ */
+ public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
+ try {
return client.post(jsonPayload);
- }catch(Exception ex){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
- ValidateException validateException = new ValidateException.Builder("Bad request could not post payload",
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
+ } catch (Exception ex) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
+ .build();
+ ValidateException validateException =
+ new ValidateException.Builder("Bad request could not post payload", HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
throw validateException;
}
- }
-
- /**
- * enhance Response
- * @param sdcResponseJsonObj - JSONObject object
- * @param statusCode - int
- * @return enhancedAsdcResponseJsonObj - JSONObject object
- */
- public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException {
-
- JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
-
- String message = "";
- String messageId = "";
-
- if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
- enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
- enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
- enhancedAsdcResponseJsonObj.put("messageId", "");
- enhancedAsdcResponseJsonObj.put("message", "Success");
-
- } else { // error
- if (sdcResponseJsonObj.has("requestError") ) {
- JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError");
- if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException") ) {
- message = requestErrorObj.getJSONObject("serviceException").getString("text");
- messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId");
- }
- if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException") ) {
- message = requestErrorObj.getJSONObject("policyException").getString("text");
- messageId = requestErrorObj.getJSONObject("policyException").getString("messageId");
- }
- enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
- enhancedAsdcResponseJsonObj.put("messageId", messageId);
- enhancedAsdcResponseJsonObj.put("message", message);
-
- } else {
- // unexpected format
- enhancedAsdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
- enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR);
- enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT);
- }
- }
- return enhancedAsdcResponseJsonObj;
-
- }
-
- /**
- * Build Uri
- * @param serviceModelVersionId - String
- * @param operationalEnvironmentId - String
- * @return uriBuilder - String
- */
- public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) {
- String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId +"/activate";
- UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI)
- .path(path);
- return uriBuilder.build().toString();
- }
-
- /**
- * Build JSON context
- * @param workloadContext - String
- * @return String json
- * @throws JSONException
- */
- public String buildJsonWorkloadContext(String workloadContext) throws JSONException {
- return new JSONObject().put("workloadContext", workloadContext).toString();
-
- }
-
- /**
- * decrypt value
- * @param toDecrypt - String
- * @param msokey - String
- * @return result - String
- */
- public synchronized String decrypt(String toDecrypt, String msokey){
- String result = null;
- try {
- result = CryptoUtils.decrypt(toDecrypt, msokey);
-
- }
- catch (Exception e) {
- logger.debug("Failed to decrypt credentials: {}", toDecrypt, e);
- }
- return result;
- }
-
- private String getBasicAuth() {
- return decrypt(sdcClientAuth, msoKey);
- }
+ }
+
+ /**
+ * enhance Response
+ *
+ * @param sdcResponseJsonObj - JSONObject object
+ * @param statusCode - int
+ * @return enhancedAsdcResponseJsonObj - JSONObject object
+ */
+ public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException {
+
+ JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
+
+ String message = "";
+ String messageId = "";
+
+ if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
+ enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
+ enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
+ enhancedAsdcResponseJsonObj.put("messageId", "");
+ enhancedAsdcResponseJsonObj.put("message", "Success");
+
+ } else { // error
+ if (sdcResponseJsonObj.has("requestError")) {
+ JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError");
+ if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException")) {
+ message = requestErrorObj.getJSONObject("serviceException").getString("text");
+ messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId");
+ }
+ if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException")) {
+ message = requestErrorObj.getJSONObject("policyException").getString("text");
+ messageId = requestErrorObj.getJSONObject("policyException").getString("messageId");
+ }
+ enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
+ enhancedAsdcResponseJsonObj.put("messageId", messageId);
+ enhancedAsdcResponseJsonObj.put("message", message);
+
+ } else {
+ // unexpected format
+ enhancedAsdcResponseJsonObj.put("statusCode",
+ String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
+ enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR);
+ enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT);
+ }
+ }
+ return enhancedAsdcResponseJsonObj;
+
+ }
+
+ /**
+ * Build Uri
+ *
+ * @param serviceModelVersionId - String
+ * @param operationalEnvironmentId - String
+ * @return uriBuilder - String
+ */
+ public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) {
+ String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId + "/activate";
+ UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI).path(path);
+ return uriBuilder.build().toString();
+ }
+
+ /**
+ * Build JSON context
+ *
+ * @param workloadContext - String
+ * @return String json
+ * @throws JSONException
+ */
+ public String buildJsonWorkloadContext(String workloadContext) throws JSONException {
+ return new JSONObject().put("workloadContext", workloadContext).toString();
+
+ }
+
+ /**
+ * decrypt value
+ *
+ * @param toDecrypt - String
+ * @param msokey - String
+ * @return result - String
+ */
+ public synchronized String decrypt(String toDecrypt, String msokey) {
+ String result = null;
+ try {
+ result = CryptoUtils.decrypt(toDecrypt, msokey);
+
+ } catch (Exception e) {
+ logger.debug("Failed to decrypt credentials: {}", toDecrypt, e);
+ }
+ return result;
+ }
+
+ private String getBasicAuth() {
+ return decrypt(sdcClientAuth, msoKey);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java
index dde45a81c9..3957f86bab 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java
@@ -22,9 +22,7 @@ package org.onap.so.apihandlerinfra.tenantisolation.process;
import java.util.List;
import java.util.Optional;
-
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.json.JSONObject;
import org.onap.aai.domain.yang.OperationalEnvironment;
@@ -57,145 +55,155 @@ import org.springframework.stereotype.Component;
@Component
public class ActivateVnfOperationalEnvironment {
- private static final Logger logger = LoggerFactory.getLogger(ActivateVnfOperationalEnvironment.class);
- private static final int DEFAULT_ACTIVATE_RETRY_COUNT = 3;
- private static final String DISTRIBUTION_STATUS_SENT = "SENT";
- private static final String OPER_ENVIRONMENT_ID_KEY = "operational-environment-id";
-
- @Autowired
- private ActivateVnfDBHelper dbHelper;
- @Autowired
- private AAIClientHelper aaiHelper;
- @Autowired
- private RequestsDBHelper requestDb;
- @Autowired
- private SDCClientHelper sdcClientHelper;
-
- @Value("${mso.tenant.isolation.retry.count}")
- private String sdcRetryCount;
-
- @Autowired
- RequestsDbClient client;
-
- /**
- * The Point-Of-Entry from APIH with VID request to send activate request
- * @param requestId - String
- * @param request - CloudOrchestrationRequest object
- * @return void - nothing
- */
- public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException{
- String vnfOperationalEnvironmentId = request.getOperationalEnvironmentId();
-
- String vidWorkloadContext = request.getRequestDetails().getRequestParameters().getWorkloadContext();
- List<ServiceModelList> serviceModelVersionIdList = request.getRequestDetails().getRequestParameters().getManifest().getServiceModelList();
-
- String ecompOperationalEnvironmentId = null;
- AAIResultWrapper wrapper = getAAIOperationalEnvironment(vnfOperationalEnvironmentId);
- Optional<Relationships> optRelationships = wrapper.getRelationships();
- if (optRelationships.isPresent()) {
- Relationships relationships = optRelationships.get();
- List<AAIResourceUri> operationalEnvironments = relationships.getRelatedAAIUris(AAIObjectType.OPERATIONAL_ENVIRONMENT);
- if (!operationalEnvironments.isEmpty()) {
- ecompOperationalEnvironmentId = operationalEnvironments.get(0).getURIKeys().get(OPER_ENVIRONMENT_ID_KEY);
- }
- }
- logger.debug(" vnfOperationalEnvironmentId : {}", vnfOperationalEnvironmentId);
- logger.debug(" ecompOperationalEnvironmentId : {}", ecompOperationalEnvironmentId);
-
- OperationalEnvironment operationalEnv = wrapper.asBean(OperationalEnvironment.class).get();
- String workloadContext = operationalEnv.getWorkloadContext();
- logger.debug(" aai workloadContext: {}", workloadContext);
- if (!vidWorkloadContext.equals(workloadContext)) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
- throw new ValidateException.Builder(" The vid workloadContext did not match from aai record. " + " vid workloadContext:" + vidWorkloadContext + " aai workloadContext:" + workloadContext,
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
- }
- if (ecompOperationalEnvironmentId==null) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
- throw new ValidateException.Builder(" The ECOMP OE was not in aai record; the value of relationship.relationship-data key: " + OPER_ENVIRONMENT_ID_KEY,
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
- }
-
- processActivateSDCRequest(requestId, ecompOperationalEnvironmentId, serviceModelVersionIdList, workloadContext, vnfOperationalEnvironmentId);
-
- }
-
-
- /**
- * The Method to send the Activation Requests to SDC
- * @param requestId - String
- * @param operationalEnvironmentId - String
- * @param serviceModelVersionIdList - List<ServiceModelList> list
- * @param workloadContext - String
- * @return jsonResponse - JSONObject object
- */
- public void processActivateSDCRequest(String requestId, String operationalEnvironmentId,
- List<ServiceModelList> serviceModelVersionIdList,
- String workloadContext, String vnfOperationalEnvironmentId) throws ApiException {
-
- JSONObject jsonResponse = null;
- int retryCount = 0;
- try {
- retryCount = Integer.parseInt(sdcRetryCount);
- } catch (NumberFormatException e) {
- retryCount = DEFAULT_ACTIVATE_RETRY_COUNT;
- }
-
- // loop through the serviceModelVersionId, and send request SDC
- for(ServiceModelList serviceModelList : serviceModelVersionIdList){
- String serviceModelVersionId = serviceModelList.getServiceModelVersionId();
- String recoveryAction = serviceModelList.getRecoveryAction().toString().toUpperCase();
-
- // should insert 1 row
- OperationalEnvServiceModelStatus serviceModelStatus =
- dbHelper.insertRecordToOperationalEnvServiceModelStatus(requestId,
- operationalEnvironmentId,
- serviceModelVersionId,
- DISTRIBUTION_STATUS_SENT,
- recoveryAction,
- retryCount,
- workloadContext,
- vnfOperationalEnvironmentId);
- client.save(serviceModelStatus);
-
- String distributionId = "";
-
- jsonResponse = sdcClientHelper.postActivateOperationalEnvironment(serviceModelVersionId, operationalEnvironmentId, workloadContext);
-
- String statusCode = jsonResponse.get("statusCode").toString();
- if (statusCode.equals(String.valueOf(Response.Status.ACCEPTED.getStatusCode()))) {
- distributionId = jsonResponse.get("distributionId").toString();
- // should insert 1 row
- OperationalEnvDistributionStatus distStatus =
- dbHelper.insertRecordToOperationalEnvDistributionStatus(distributionId,
- operationalEnvironmentId,
- serviceModelVersionId,
- requestId,
- DISTRIBUTION_STATUS_SENT,
- "");
- client.save(distStatus);
-
- } else {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
- String dbErrorMessage = " Failure calling SDC: statusCode: " + statusCode +
- "; messageId: " + jsonResponse.get("messageId") +
- "; message: " + jsonResponse.get("message");
+ private static final Logger logger = LoggerFactory.getLogger(ActivateVnfOperationalEnvironment.class);
+ private static final int DEFAULT_ACTIVATE_RETRY_COUNT = 3;
+ private static final String DISTRIBUTION_STATUS_SENT = "SENT";
+ private static final String OPER_ENVIRONMENT_ID_KEY = "operational-environment-id";
+
+ @Autowired
+ private ActivateVnfDBHelper dbHelper;
+ @Autowired
+ private AAIClientHelper aaiHelper;
+ @Autowired
+ private RequestsDBHelper requestDb;
+ @Autowired
+ private SDCClientHelper sdcClientHelper;
+
+ @Value("${mso.tenant.isolation.retry.count}")
+ private String sdcRetryCount;
+
+ @Autowired
+ RequestsDbClient client;
+
+ /**
+ * The Point-Of-Entry from APIH with VID request to send activate request
+ *
+ * @param requestId - String
+ * @param request - CloudOrchestrationRequest object
+ * @return void - nothing
+ */
+ public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException {
+ String vnfOperationalEnvironmentId = request.getOperationalEnvironmentId();
+
+ String vidWorkloadContext = request.getRequestDetails().getRequestParameters().getWorkloadContext();
+ List<ServiceModelList> serviceModelVersionIdList =
+ request.getRequestDetails().getRequestParameters().getManifest().getServiceModelList();
+
+ String ecompOperationalEnvironmentId = null;
+ AAIResultWrapper wrapper = getAAIOperationalEnvironment(vnfOperationalEnvironmentId);
+ Optional<Relationships> optRelationships = wrapper.getRelationships();
+ if (optRelationships.isPresent()) {
+ Relationships relationships = optRelationships.get();
+ List<AAIResourceUri> operationalEnvironments =
+ relationships.getRelatedAAIUris(AAIObjectType.OPERATIONAL_ENVIRONMENT);
+ if (!operationalEnvironments.isEmpty()) {
+ ecompOperationalEnvironmentId =
+ operationalEnvironments.get(0).getURIKeys().get(OPER_ENVIRONMENT_ID_KEY);
+ }
+ }
+ logger.debug(" vnfOperationalEnvironmentId : {}", vnfOperationalEnvironmentId);
+ logger.debug(" ecompOperationalEnvironmentId : {}", ecompOperationalEnvironmentId);
+
+ OperationalEnvironment operationalEnv = wrapper.asBean(OperationalEnvironment.class).get();
+ String workloadContext = operationalEnv.getWorkloadContext();
+ logger.debug(" aai workloadContext: {}", workloadContext);
+ if (!vidWorkloadContext.equals(workloadContext)) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
+ .build();
+ throw new ValidateException.Builder(
+ " The vid workloadContext did not match from aai record. " + " vid workloadContext:"
+ + vidWorkloadContext + " aai workloadContext:" + workloadContext,
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo)
+ .build();
+ }
+ if (ecompOperationalEnvironmentId == null) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
+ .build();
+ throw new ValidateException.Builder(
+ " The ECOMP OE was not in aai record; the value of relationship.relationship-data key: "
+ + OPER_ENVIRONMENT_ID_KEY,
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo)
+ .build();
+ }
+
+ processActivateSDCRequest(requestId, ecompOperationalEnvironmentId, serviceModelVersionIdList, workloadContext,
+ vnfOperationalEnvironmentId);
+
+ }
+
+
+ /**
+ * The Method to send the Activation Requests to SDC
+ *
+ * @param requestId - String
+ * @param operationalEnvironmentId - String
+ * @param serviceModelVersionIdList - List<ServiceModelList> list
+ * @param workloadContext - String
+ * @return jsonResponse - JSONObject object
+ */
+ public void processActivateSDCRequest(String requestId, String operationalEnvironmentId,
+ List<ServiceModelList> serviceModelVersionIdList, String workloadContext,
+ String vnfOperationalEnvironmentId) throws ApiException {
+
+ JSONObject jsonResponse = null;
+ int retryCount = 0;
+ try {
+ retryCount = Integer.parseInt(sdcRetryCount);
+ } catch (NumberFormatException e) {
+ retryCount = DEFAULT_ACTIVATE_RETRY_COUNT;
+ }
+
+ // loop through the serviceModelVersionId, and send request SDC
+ for (ServiceModelList serviceModelList : serviceModelVersionIdList) {
+ String serviceModelVersionId = serviceModelList.getServiceModelVersionId();
+ String recoveryAction = serviceModelList.getRecoveryAction().toString().toUpperCase();
+
+ // should insert 1 row
+ OperationalEnvServiceModelStatus serviceModelStatus =
+ dbHelper.insertRecordToOperationalEnvServiceModelStatus(requestId, operationalEnvironmentId,
+ serviceModelVersionId, DISTRIBUTION_STATUS_SENT, recoveryAction, retryCount,
+ workloadContext, vnfOperationalEnvironmentId);
+ client.save(serviceModelStatus);
+
+ String distributionId = "";
+
+ jsonResponse = sdcClientHelper.postActivateOperationalEnvironment(serviceModelVersionId,
+ operationalEnvironmentId, workloadContext);
+
+ String statusCode = jsonResponse.get("statusCode").toString();
+ if (statusCode.equals(String.valueOf(Response.Status.ACCEPTED.getStatusCode()))) {
+ distributionId = jsonResponse.get("distributionId").toString();
+ // should insert 1 row
+ OperationalEnvDistributionStatus distStatus = dbHelper.insertRecordToOperationalEnvDistributionStatus(
+ distributionId, operationalEnvironmentId, serviceModelVersionId, requestId,
+ DISTRIBUTION_STATUS_SENT, "");
+ client.save(distStatus);
+
+ } else {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
+ .build();
+ String dbErrorMessage = " Failure calling SDC: statusCode: " + statusCode + "; messageId: "
+ + jsonResponse.get("messageId") + "; message: " + jsonResponse.get("message");
requestDb.updateInfraFailureCompletion(dbErrorMessage, requestId, operationalEnvironmentId);
- throw new ValidateException.Builder(dbErrorMessage,
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
- }
- }
-
- }
-
- /**
- * Get AAIOperationalEnvironment object
- * @param operationalEnvironmentId - String
- * @return operationalEnv - AAIOperationalEnvironment object
- */
- public AAIResultWrapper getAAIOperationalEnvironment(String operationalEnvironmentId) {
- return aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId);
- }
+ throw new ValidateException.Builder(dbErrorMessage, HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+ }
+ }
+
+ }
+
+ /**
+ * Get AAIOperationalEnvironment object
+ *
+ * @param operationalEnvironmentId - String
+ * @return operationalEnv - AAIOperationalEnvironment object
+ */
+ public AAIResultWrapper getAAIOperationalEnvironment(String operationalEnvironmentId) {
+ return aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java
index cd05aa558e..3005abaf9b 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java
@@ -25,9 +25,7 @@ package org.onap.so.apihandlerinfra.tenantisolation.process;
import java.util.List;
import java.util.Optional;
-
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.json.JSONObject;
import org.onap.aai.domain.yang.OperationalEnvironment;
@@ -56,272 +54,278 @@ import org.springframework.stereotype.Component;
@Component
public class ActivateVnfStatusOperationalEnvironment {
- private static Logger logger = LoggerFactory.getLogger(ActivateVnfStatusOperationalEnvironment.class);
- private String origRequestId = "";
- private String errorMessage = "";
- private OperationalEnvDistributionStatus queryDistributionDbResponse = null;
- private OperationalEnvServiceModelStatus queryServiceModelResponse = null;
- private boolean isOverallSuccess = false;
-
- private final int RETRY_COUNT_ZERO = 0;
- private final String ERROR_REASON_ABORTED = "ABORTED";
- private final String RECOVERY_ACTION_RETRY = "RETRY";
- private final String RECOVERY_ACTION_ABORT = "ABORT";
- private final String RECOVERY_ACTION_SKIP = "SKIP";
- private final String DISTRIBUTION_STATUS_OK = DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString();
- private final String DISTRIBUTION_STATUS_ERROR = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString();
- private final String DISTRIBUTION_STATUS_SENT = "SENT";
-
- private final String MESSAGE_UNDEFINED_ID = "Undefined Error Message!";
-
- @Autowired
- private ActivateVnfDBHelper dbHelper;
- @Autowired
- private RequestsDBHelper requestDb;
- @Autowired
- private SDCClientHelper sdcClientHelper;
- @Autowired
- private RequestsDbClient client;
- @Autowired
- private AAIClientHelper aaiHelper;
-
- /**
- * The Point-Of-Entry from APIH with activate status from SDC
- * @param requestId - String
- * @param request - CloudOrchestrationRequest - object
- * @return void - nothing
- */
- public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException {
-
- try {
-
- String operationalEnvironmentId = "";
-
- String sdcDistributionId = request.getDistributionId();
- Distribution sdcStatus = request.getDistribution();
-
- // Distribution, Query for operationalEnvironmentId, serviceModelVersionId, origRequestId
- this.queryDistributionDbResponse = client.getDistributionStatusById(sdcDistributionId);
- operationalEnvironmentId = this.queryDistributionDbResponse.getOperationalEnvId();
- this.origRequestId = this.queryDistributionDbResponse.getRequestId();
-
- // ServiceModel, Query for recoveryAction, retryCountString
- this.queryServiceModelResponse = client.findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId(operationalEnvironmentId, queryDistributionDbResponse.getServiceModelVersionId(), this.origRequestId);
-
- processActivateSDCStatus(sdcDistributionId, sdcStatus, this.queryDistributionDbResponse, this.queryServiceModelResponse);
-
- // After EVERY status processed, need to query the status of all service modelId
- // to determine the OVERALL status if "COMPLETE" or "FAILURE":
- checkOrUpdateOverallStatus(operationalEnvironmentId, this.origRequestId);
-
- // Update AAI to ACTIVE if Overall success
- if (isOverallSuccess) {
- String vnfOperationalEnvironmentId = this.queryServiceModelResponse.getVnfOperationalEnvId();
- OperationalEnvironment aaiOpEnv = getAAIOperationalEnvironment(vnfOperationalEnvironmentId);
- if (aaiOpEnv != null) {
- aaiOpEnv.setOperationalEnvironmentStatus("ACTIVE");
- aaiHelper.updateAaiOperationalEnvironment(vnfOperationalEnvironmentId, aaiOpEnv);
- }else {
- requestDb.updateInfraFailureCompletion("Unable to update ACTIVATE status in AAI. ", this.origRequestId, this.queryServiceModelResponse.getVnfOperationalEnvId());
- }
- }
-
- } catch(Exception e) {
- requestDb.updateInfraFailureCompletion(e.getMessage(), this.origRequestId, this.queryServiceModelResponse.getVnfOperationalEnvId());
+ private static Logger logger = LoggerFactory.getLogger(ActivateVnfStatusOperationalEnvironment.class);
+ private String origRequestId = "";
+ private String errorMessage = "";
+ private OperationalEnvDistributionStatus queryDistributionDbResponse = null;
+ private OperationalEnvServiceModelStatus queryServiceModelResponse = null;
+ private boolean isOverallSuccess = false;
+
+ private final int RETRY_COUNT_ZERO = 0;
+ private final String ERROR_REASON_ABORTED = "ABORTED";
+ private final String RECOVERY_ACTION_RETRY = "RETRY";
+ private final String RECOVERY_ACTION_ABORT = "ABORT";
+ private final String RECOVERY_ACTION_SKIP = "SKIP";
+ private final String DISTRIBUTION_STATUS_OK = DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString();
+ private final String DISTRIBUTION_STATUS_ERROR = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString();
+ private final String DISTRIBUTION_STATUS_SENT = "SENT";
+
+ private final String MESSAGE_UNDEFINED_ID = "Undefined Error Message!";
+
+ @Autowired
+ private ActivateVnfDBHelper dbHelper;
+ @Autowired
+ private RequestsDBHelper requestDb;
+ @Autowired
+ private SDCClientHelper sdcClientHelper;
+ @Autowired
+ private RequestsDbClient client;
+ @Autowired
+ private AAIClientHelper aaiHelper;
+
+ /**
+ * The Point-Of-Entry from APIH with activate status from SDC
+ *
+ * @param requestId - String
+ * @param request - CloudOrchestrationRequest - object
+ * @return void - nothing
+ */
+ public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException {
+
+ try {
+
+ String operationalEnvironmentId = "";
+
+ String sdcDistributionId = request.getDistributionId();
+ Distribution sdcStatus = request.getDistribution();
+
+ // Distribution, Query for operationalEnvironmentId, serviceModelVersionId, origRequestId
+ this.queryDistributionDbResponse = client.getDistributionStatusById(sdcDistributionId);
+ operationalEnvironmentId = this.queryDistributionDbResponse.getOperationalEnvId();
+ this.origRequestId = this.queryDistributionDbResponse.getRequestId();
+
+ // ServiceModel, Query for recoveryAction, retryCountString
+ this.queryServiceModelResponse =
+ client.findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId(operationalEnvironmentId,
+ queryDistributionDbResponse.getServiceModelVersionId(), this.origRequestId);
+
+ processActivateSDCStatus(sdcDistributionId, sdcStatus, this.queryDistributionDbResponse,
+ this.queryServiceModelResponse);
+
+ // After EVERY status processed, need to query the status of all service modelId
+ // to determine the OVERALL status if "COMPLETE" or "FAILURE":
+ checkOrUpdateOverallStatus(operationalEnvironmentId, this.origRequestId);
+
+ // Update AAI to ACTIVE if Overall success
+ if (isOverallSuccess) {
+ String vnfOperationalEnvironmentId = this.queryServiceModelResponse.getVnfOperationalEnvId();
+ OperationalEnvironment aaiOpEnv = getAAIOperationalEnvironment(vnfOperationalEnvironmentId);
+ if (aaiOpEnv != null) {
+ aaiOpEnv.setOperationalEnvironmentStatus("ACTIVE");
+ aaiHelper.updateAaiOperationalEnvironment(vnfOperationalEnvironmentId, aaiOpEnv);
+ } else {
+ requestDb.updateInfraFailureCompletion("Unable to update ACTIVATE status in AAI. ",
+ this.origRequestId, this.queryServiceModelResponse.getVnfOperationalEnvId());
+ }
+ }
+
+ } catch (Exception e) {
+ requestDb.updateInfraFailureCompletion(e.getMessage(), this.origRequestId,
+ this.queryServiceModelResponse.getVnfOperationalEnvId());
}
-
- }
-
- /**
- * The Method to process the Activation Status from SDC
- * @param sdcDistributionId - string
- * @param sdcStatus - Distribution object
- * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object
- * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object
- * @return void - nothing
- */
- public void processActivateSDCStatus(String sdcDistributionId, Distribution sdcStatus, OperationalEnvDistributionStatus queryDistributionDbResponse,
- OperationalEnvServiceModelStatus queryServiceModelResponse) throws ApiException {
-
- String sdcStatusValue = sdcStatus.getStatus().toString();
- String recoveryAction = queryServiceModelResponse.getRecoveryAction();
- int retryCount = queryServiceModelResponse.getRetryCount();
-
- // Validate/process status
- if (sdcStatus.getStatus().toString().equals(DISTRIBUTION_STATUS_OK)) {
- // should update 1 row, update status to "DISTRIBUTION_COMPLETE_OK"
- OperationalEnvDistributionStatus updateDistStatusOk =
- dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse,
- sdcStatusValue,
- "");
- client.save(updateDistStatusOk);
- // should update 1 row, update status and retryCount = 0 (ie, serviceModelVersionId is DONE!)
- OperationalEnvServiceModelStatus updateRetryCountZeroAndStatusOk =
- dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse,
- sdcStatusValue,
- RETRY_COUNT_ZERO);
- client.save(updateRetryCountZeroAndStatusOk);
- } else {
-
- // "DISTRIBUTION_COMPLETE_ERROR", Check if recoveryAction is "RETRY"
- if (recoveryAction.equals(RECOVERY_ACTION_RETRY) && retryCount > RETRY_COUNT_ZERO) {
-
- // RESEND / RETRY serviceModelVersionId to SDC
-
- JSONObject jsonResponse = callSDClientForRetry(queryDistributionDbResponse, queryServiceModelResponse, sdcStatus);
-
- } else { // either RETRY & Count = 0, or 'ABORT', or 'SKIP'
-
- if (recoveryAction.equals(RECOVERY_ACTION_SKIP) || recoveryAction.equals(RECOVERY_ACTION_ABORT)) {
- String modifiedStatus = "";
- String errorReason = "";
- if (recoveryAction.equals(RECOVERY_ACTION_SKIP)) { // considered SUCCESS
- modifiedStatus = DISTRIBUTION_STATUS_OK;
- } else {
- if (recoveryAction.equals(RECOVERY_ACTION_ABORT)) {
- modifiedStatus = DISTRIBUTION_STATUS_ERROR; // ABORT, error
- errorReason = ERROR_REASON_ABORTED;
- }
- }
-
- sdcStatusValue = modifiedStatus;
- OperationalEnvServiceModelStatus updateRetryCountZeroAndStatus =
- dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse,
- modifiedStatus,
- RETRY_COUNT_ZERO);
- client.save(updateRetryCountZeroAndStatus);
- OperationalEnvDistributionStatus updateDistStatus =
- dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse,
- modifiedStatus,
- errorReason);
- client.save(updateDistStatus);
- } else {
- // RETRY & Count = 0 (do nothing!)
- }
- }
- }
- }
-
- /**
- * The Method to call SDC for recoveryActioin RETRY
- * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object
- * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object
- * @param sdcStatus - Distribution object
- * @return JSONObject object
- */
- public JSONObject callSDClientForRetry(OperationalEnvDistributionStatus queryDistributionDbResponse,
- OperationalEnvServiceModelStatus queryServiceModelResponse,
- Distribution sdcStatus) throws ApiException {
-
- JSONObject jsonResponse = null;
-
- String operEnvironmentId = queryDistributionDbResponse.getOperationalEnvId();
- String serviceModelVersionId = queryDistributionDbResponse.getServiceModelVersionId();
- String originalRequestId = queryServiceModelResponse.getRequestId();
- int retryCount = queryServiceModelResponse.getRetryCount();
- String workloadContext = queryServiceModelResponse.getWorkloadContext();
-
-
- jsonResponse = sdcClientHelper.postActivateOperationalEnvironment(serviceModelVersionId, operEnvironmentId, workloadContext);
- String statusCode = jsonResponse.get("statusCode").toString();
- if (statusCode.equals(String.valueOf(Response.Status.ACCEPTED.getStatusCode()))) {
- String newDistributionId = jsonResponse.get("distributionId").toString();
- // should insert 1 row, NEW distributionId for replacement of the serviceModelServiceId record
- OperationalEnvDistributionStatus insertNewDistributionId =
- dbHelper.insertRecordToOperationalEnvDistributionStatus(newDistributionId,
- operEnvironmentId,
- serviceModelVersionId,
- originalRequestId,
- DISTRIBUTION_STATUS_SENT,
- "");
- client.save(insertNewDistributionId);
-
- // update retryCount (less 1) for the serviceModelServiceId
- retryCount = retryCount - 1;
- // should update 1 row, original insert
- OperationalEnvServiceModelStatus updateRetryCountAndStatus =
- dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse,
- DISTRIBUTION_STATUS_SENT,
- retryCount);
- client.save(updateRetryCountAndStatus);
-
- // should update 1 row, OLD distributionId set to status error (ie, old distributionId is DONE!).
- OperationalEnvDistributionStatus updateStatus =
- dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse,
- DISTRIBUTION_STATUS_ERROR,
- sdcStatus.getErrorReason());
- client.save(updateStatus);
- } else {
- String dbErrorMessage = "Failure calling SDC: statusCode: " + statusCode +
- "; messageId: " + jsonResponse.get("messageId") +
- "; message: " + jsonResponse.get("message");
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
- ValidateException validateException = new ValidateException.Builder(dbErrorMessage,
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
- requestDb.updateInfraFailureCompletion(dbErrorMessage, this.origRequestId, operEnvironmentId);
- throw validateException;
- }
-
- return jsonResponse;
-
- }
-
-
- /**
- * The Method to check the overall status of the Activation for an operationalEnvironmentId
- * @param operationalEnvironmentId - string
- * @param origRequestId - string
- * @return void - nothing
- */
- public void checkOrUpdateOverallStatus(String operationalEnvironmentId, String origRequestId) throws ApiException{
-
- List<OperationalEnvServiceModelStatus> queryServiceModelResponseList = client.getAllByOperationalEnvIdAndRequestId(operationalEnvironmentId, origRequestId);
-
- String status = "Waiting";
- int count = 0;
- // loop through the statuses of the service model
- for (OperationalEnvServiceModelStatus querySrvModelResponse : queryServiceModelResponseList) {
- status = querySrvModelResponse.getServiceModelVersionDistrStatus();
- // all should be OK to be completed.
- if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString()) &&
- (querySrvModelResponse.getRetryCount() == 0))) {
- status = "Completed";
- count ++;
- }
- // one error with zero retry, means all are failures.
- if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString()) &&
- (querySrvModelResponse.getRetryCount() == 0))) {
- status = "Failure";
- count = queryServiceModelResponseList.size();
- break;
- }
- }
-
- if (status.equals("Completed") && queryServiceModelResponseList.size() == count) {
- String messageStatus = "Overall Activation process is complete. " + status;
- isOverallSuccess = true;
- requestDb.updateInfraSuccessCompletion(messageStatus, origRequestId, operationalEnvironmentId);
- } else {
- if (status.equals("Failure") && queryServiceModelResponseList.size() == count) {
- this.errorMessage = "Overall Activation process is a Failure. " + status;
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
- ValidateException validateException = new ValidateException.Builder(this.errorMessage,
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+
+ }
+
+ /**
+ * The Method to process the Activation Status from SDC
+ *
+ * @param sdcDistributionId - string
+ * @param sdcStatus - Distribution object
+ * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object
+ * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object
+ * @return void - nothing
+ */
+ public void processActivateSDCStatus(String sdcDistributionId, Distribution sdcStatus,
+ OperationalEnvDistributionStatus queryDistributionDbResponse,
+ OperationalEnvServiceModelStatus queryServiceModelResponse) throws ApiException {
+
+ String sdcStatusValue = sdcStatus.getStatus().toString();
+ String recoveryAction = queryServiceModelResponse.getRecoveryAction();
+ int retryCount = queryServiceModelResponse.getRetryCount();
+
+ // Validate/process status
+ if (sdcStatus.getStatus().toString().equals(DISTRIBUTION_STATUS_OK)) {
+ // should update 1 row, update status to "DISTRIBUTION_COMPLETE_OK"
+ OperationalEnvDistributionStatus updateDistStatusOk = dbHelper
+ .updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse, sdcStatusValue, "");
+ client.save(updateDistStatusOk);
+ // should update 1 row, update status and retryCount = 0 (ie, serviceModelVersionId is DONE!)
+ OperationalEnvServiceModelStatus updateRetryCountZeroAndStatusOk =
+ dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse,
+ sdcStatusValue, RETRY_COUNT_ZERO);
+ client.save(updateRetryCountZeroAndStatusOk);
+ } else {
+
+ // "DISTRIBUTION_COMPLETE_ERROR", Check if recoveryAction is "RETRY"
+ if (recoveryAction.equals(RECOVERY_ACTION_RETRY) && retryCount > RETRY_COUNT_ZERO) {
+
+ // RESEND / RETRY serviceModelVersionId to SDC
+
+ JSONObject jsonResponse =
+ callSDClientForRetry(queryDistributionDbResponse, queryServiceModelResponse, sdcStatus);
+
+ } else { // either RETRY & Count = 0, or 'ABORT', or 'SKIP'
+
+ if (recoveryAction.equals(RECOVERY_ACTION_SKIP) || recoveryAction.equals(RECOVERY_ACTION_ABORT)) {
+ String modifiedStatus = "";
+ String errorReason = "";
+ if (recoveryAction.equals(RECOVERY_ACTION_SKIP)) { // considered SUCCESS
+ modifiedStatus = DISTRIBUTION_STATUS_OK;
+ } else {
+ if (recoveryAction.equals(RECOVERY_ACTION_ABORT)) {
+ modifiedStatus = DISTRIBUTION_STATUS_ERROR; // ABORT, error
+ errorReason = ERROR_REASON_ABORTED;
+ }
+ }
+
+ sdcStatusValue = modifiedStatus;
+ OperationalEnvServiceModelStatus updateRetryCountZeroAndStatus =
+ dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(
+ queryServiceModelResponse, modifiedStatus, RETRY_COUNT_ZERO);
+ client.save(updateRetryCountZeroAndStatus);
+ OperationalEnvDistributionStatus updateDistStatus =
+ dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse,
+ modifiedStatus, errorReason);
+ client.save(updateDistStatus);
+ } else {
+ // RETRY & Count = 0 (do nothing!)
+ }
+ }
+ }
+ }
+
+ /**
+ * The Method to call SDC for recoveryActioin RETRY
+ *
+ * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object
+ * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object
+ * @param sdcStatus - Distribution object
+ * @return JSONObject object
+ */
+ public JSONObject callSDClientForRetry(OperationalEnvDistributionStatus queryDistributionDbResponse,
+ OperationalEnvServiceModelStatus queryServiceModelResponse, Distribution sdcStatus) throws ApiException {
+
+ JSONObject jsonResponse = null;
+
+ String operEnvironmentId = queryDistributionDbResponse.getOperationalEnvId();
+ String serviceModelVersionId = queryDistributionDbResponse.getServiceModelVersionId();
+ String originalRequestId = queryServiceModelResponse.getRequestId();
+ int retryCount = queryServiceModelResponse.getRetryCount();
+ String workloadContext = queryServiceModelResponse.getWorkloadContext();
+
+
+ jsonResponse = sdcClientHelper.postActivateOperationalEnvironment(serviceModelVersionId, operEnvironmentId,
+ workloadContext);
+ String statusCode = jsonResponse.get("statusCode").toString();
+ if (statusCode.equals(String.valueOf(Response.Status.ACCEPTED.getStatusCode()))) {
+ String newDistributionId = jsonResponse.get("distributionId").toString();
+ // should insert 1 row, NEW distributionId for replacement of the serviceModelServiceId record
+ OperationalEnvDistributionStatus insertNewDistributionId =
+ dbHelper.insertRecordToOperationalEnvDistributionStatus(newDistributionId, operEnvironmentId,
+ serviceModelVersionId, originalRequestId, DISTRIBUTION_STATUS_SENT, "");
+ client.save(insertNewDistributionId);
+
+ // update retryCount (less 1) for the serviceModelServiceId
+ retryCount = retryCount - 1;
+ // should update 1 row, original insert
+ OperationalEnvServiceModelStatus updateRetryCountAndStatus =
+ dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse,
+ DISTRIBUTION_STATUS_SENT, retryCount);
+ client.save(updateRetryCountAndStatus);
+
+ // should update 1 row, OLD distributionId set to status error (ie, old distributionId is DONE!).
+ OperationalEnvDistributionStatus updateStatus = dbHelper.updateStatusInOperationalEnvDistributionStatus(
+ queryDistributionDbResponse, DISTRIBUTION_STATUS_ERROR, sdcStatus.getErrorReason());
+ client.save(updateStatus);
+ } else {
+ String dbErrorMessage = "Failure calling SDC: statusCode: " + statusCode + "; messageId: "
+ + jsonResponse.get("messageId") + "; message: " + jsonResponse.get("message");
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
+ .build();
+ ValidateException validateException =
+ new ValidateException.Builder(dbErrorMessage, HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+ requestDb.updateInfraFailureCompletion(dbErrorMessage, this.origRequestId, operEnvironmentId);
+ throw validateException;
+ }
+
+ return jsonResponse;
+
+ }
+
+
+ /**
+ * The Method to check the overall status of the Activation for an operationalEnvironmentId
+ *
+ * @param operationalEnvironmentId - string
+ * @param origRequestId - string
+ * @return void - nothing
+ */
+ public void checkOrUpdateOverallStatus(String operationalEnvironmentId, String origRequestId) throws ApiException {
+
+ List<OperationalEnvServiceModelStatus> queryServiceModelResponseList =
+ client.getAllByOperationalEnvIdAndRequestId(operationalEnvironmentId, origRequestId);
+
+ String status = "Waiting";
+ int count = 0;
+ // loop through the statuses of the service model
+ for (OperationalEnvServiceModelStatus querySrvModelResponse : queryServiceModelResponseList) {
+ status = querySrvModelResponse.getServiceModelVersionDistrStatus();
+ // all should be OK to be completed.
+ if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString())
+ && (querySrvModelResponse.getRetryCount() == 0))) {
+ status = "Completed";
+ count++;
+ }
+ // one error with zero retry, means all are failures.
+ if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString())
+ && (querySrvModelResponse.getRetryCount() == 0))) {
+ status = "Failure";
+ count = queryServiceModelResponseList.size();
+ break;
+ }
+ }
+
+ if (status.equals("Completed") && queryServiceModelResponseList.size() == count) {
+ String messageStatus = "Overall Activation process is complete. " + status;
+ isOverallSuccess = true;
+ requestDb.updateInfraSuccessCompletion(messageStatus, origRequestId, operationalEnvironmentId);
+ } else {
+ if (status.equals("Failure") && queryServiceModelResponseList.size() == count) {
+ this.errorMessage = "Overall Activation process is a Failure. " + status;
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
+ .build();
+ ValidateException validateException =
+ new ValidateException.Builder(this.errorMessage, HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
requestDb.updateInfraFailureCompletion(this.errorMessage, origRequestId, operationalEnvironmentId);
- throw validateException;
- }
-
- }
- }
-
- /**
- * Get OperationalEnvironment object
- * @param operationalEnvironmentId - String
- * @return operationalEnv - OperationalEnvironment object
- */
- private OperationalEnvironment getAAIOperationalEnvironment(String operationalEnvironmentId) {
- AAIResultWrapper aaiResult = aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId);
- Optional<OperationalEnvironment> operationalEnvironmentOpt = aaiResult.asBean(OperationalEnvironment.class);
- return operationalEnvironmentOpt.isPresent() ? operationalEnvironmentOpt.get() : null;
- }
+ throw validateException;
+ }
+
+ }
+ }
+
+ /**
+ * Get OperationalEnvironment object
+ *
+ * @param operationalEnvironmentId - String
+ * @return operationalEnv - OperationalEnvironment object
+ */
+ private OperationalEnvironment getAAIOperationalEnvironment(String operationalEnvironmentId) {
+ AAIResultWrapper aaiResult = aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId);
+ Optional<OperationalEnvironment> operationalEnvironmentOpt = aaiResult.asBean(OperationalEnvironment.class);
+ return operationalEnvironmentOpt.isPresent() ? operationalEnvironmentOpt.get() : null;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironment.java
index e9c9be9dd4..3812aa9edf 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironment.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironment.java
@@ -41,48 +41,51 @@ import org.springframework.stereotype.Component;
@Component
public class CreateEcompOperationalEnvironment {
-
- private static Logger logger = LoggerFactory.getLogger(CreateEcompOperationalEnvironment.class);
-
- @Autowired
- private AAIClientObjectBuilder aaiClientObjectBuilder;
- @Autowired
- private AAIClientHelper aaiHelper;
- @Autowired
- private RequestsDBHelper requestDb;
- @Autowired
- private DmaapOperationalEnvClient dmaapClient;
- public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException{
+ private static Logger logger = LoggerFactory.getLogger(CreateEcompOperationalEnvironment.class);
- //Create ECOMP Managing Environment object in A&AI
- aaiHelper.createOperationalEnvironment(aaiClientObjectBuilder.buildAAIOperationalEnvironment("ACTIVE", request));
+ @Autowired
+ private AAIClientObjectBuilder aaiClientObjectBuilder;
+ @Autowired
+ private AAIClientHelper aaiHelper;
+ @Autowired
+ private RequestsDBHelper requestDb;
+ @Autowired
+ private DmaapOperationalEnvClient dmaapClient;
- // Call client to publish to DMaap
+ public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException {
+
+ // Create ECOMP Managing Environment object in A&AI
+ aaiHelper
+ .createOperationalEnvironment(aaiClientObjectBuilder.buildAAIOperationalEnvironment("ACTIVE", request));
+
+ // Call client to publish to DMaap
try {
- logger.debug("1 {}", request.getOperationalEnvironmentId());
- logger.debug("2 {}", request.getRequestDetails().getRequestInfo().getInstanceName());
- logger.debug("3 {}", request.getRequestDetails().getRequestParameters().getOperationalEnvironmentType()
- .toString());
- logger.debug("4 {}", request.getRequestDetails().getRequestParameters().getTenantContext());
- logger.debug("5 {}", request.getRequestDetails().getRequestParameters().getWorkloadContext());
+ logger.debug("1 {}", request.getOperationalEnvironmentId());
+ logger.debug("2 {}", request.getRequestDetails().getRequestInfo().getInstanceName());
+ logger.debug("3 {}",
+ request.getRequestDetails().getRequestParameters().getOperationalEnvironmentType().toString());
+ logger.debug("4 {}", request.getRequestDetails().getRequestParameters().getTenantContext());
+ logger.debug("5 {}", request.getRequestDetails().getRequestParameters().getWorkloadContext());
dmaapClient.dmaapPublishOperationalEnvRequest(request.getOperationalEnvironmentId(),
request.getRequestDetails().getRequestInfo().getInstanceName(),
request.getRequestDetails().getRequestParameters().getOperationalEnvironmentType().toString(),
request.getRequestDetails().getRequestParameters().getTenantContext(),
- request.getRequestDetails().getRequestParameters().getWorkloadContext(),
- "Create");
- }catch(Exception e){
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
- ValidateException validateException = new ValidateException.Builder("Could not publish DMaap", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
+ request.getRequestDetails().getRequestParameters().getWorkloadContext(), "Create");
+ } catch (Exception e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
+ ValidateException validateException =
+ new ValidateException.Builder("Could not publish DMaap", HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
requestDb.updateInfraFailureCompletion(e.getMessage(), requestId, request.getOperationalEnvironmentId());
throw validateException;
}
- //Update request database
- requestDb.updateInfraSuccessCompletion("SUCCESSFULLY Created ECOMP OperationalEnvironment.", requestId, request.getOperationalEnvironmentId());
+ // Update request database
+ requestDb.updateInfraSuccessCompletion("SUCCESSFULLY Created ECOMP OperationalEnvironment.", requestId,
+ request.getOperationalEnvironmentId());
- }
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java
index cc3e3aeb16..fe81a07212 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java
@@ -24,9 +24,7 @@ package org.onap.so.apihandlerinfra.tenantisolation.process;
import java.util.ArrayList;
import java.util.List;
-
import javax.ws.rs.NotFoundException;
-
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.onap.aai.domain.yang.OperationalEnvironment;
@@ -54,178 +52,184 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class CreateVnfOperationalEnvironment {
-
- private static Logger logger = LoggerFactory.getLogger(CreateVnfOperationalEnvironment.class);
- protected CloudOrchestrationRequest request;
-
- @Autowired
- private AAIClientObjectBuilder aaiClientObjectBuilder;
- @Autowired
- private AAIClientHelper aaiHelper;
- @Autowired
- private RequestsDBHelper requestDb;
- private GRMClient grmClient;
-
- public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException{
- try {
- setRequest(request);
- ObjectMapper objectMapper = new ObjectMapper();
- AAIResultWrapper aaiResultWrapper = aaiHelper.getAaiOperationalEnvironment(getEcompManagingEnvironmentId());
- if (aaiResultWrapper.isEmpty()) {
- throw new NotFoundException(getEcompManagingEnvironmentId() + " not found in A&AI");
- }
- OperationalEnvironment aaiEnv = aaiResultWrapper.asBean(OperationalEnvironment.class).get();
-
- //Find ECOMP environments in GRM
- logger.debug(" Start of GRM findRunningServicesAsString");
- String searchKey = getSearchKey(aaiEnv);
- String tenantContext = getTenantContext().toUpperCase();
- String jsonResponse = getGrmClient().findRunningServicesAsString(searchKey, 1, tenantContext);
- ServiceEndPointList sel = objectMapper.readValue(jsonResponse, ServiceEndPointList.class);
- if(sel.getServiceEndPointList().size() == 0) {
- throw new TenantIsolationException("GRM did not find any matches for " + searchKey + " in " + tenantContext);
- }
-
- //Replicate end-point for VNF Operating environment in GRM
- List<ServiceEndPointRequest> serviceEndpointRequestList = buildEndPointRequestList(sel);
- int ctr = 0;
- int total = serviceEndpointRequestList.size();
- for (ServiceEndPointRequest requestList : serviceEndpointRequestList) {
- logger.debug("Creating endpoint " + ++ctr + " of " + total + ": " + requestList.getServiceEndPoint().getName());
- getGrmClient().addServiceEndPoint(requestList);
- }
-
- //Create VNF operating in A&AI
- aaiHelper.createOperationalEnvironment(aaiClientObjectBuilder.buildAAIOperationalEnvironment("INACTIVE", request));
- aaiHelper.createRelationship(request.getOperationalEnvironmentId(), getEcompManagingEnvironmentId());
-
- //Update request database
- requestDb.updateInfraSuccessCompletion("SUCCESSFULLY created VNF operational environment", requestId, request.getOperationalEnvironmentId());
-
- }catch(Exception e) {
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
-
-
- ValidateException validateException = new ValidateException.Builder(e.getMessage(),
- HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
-
- throw validateException;
- }
- }
-
-
- protected String getEcompManagingEnvironmentId() throws TenantIsolationException {
- RelatedInstanceList[] relatedInstances = request.getRequestDetails().getRelatedInstanceList();
- if (relatedInstances.length > 0 && relatedInstances[0].getRelatedInstance() != null) {
- return relatedInstances[0].getRelatedInstance().getInstanceId();
- } else {
- return null;
- }
- }
-
-
- protected String getTenantContext() throws TenantIsolationException {
- if(!StringUtils.isEmpty(request.getRequestDetails().getRequestParameters().getTenantContext())) {
- return request.getRequestDetails().getRequestParameters().getTenantContext();
- }
- else {
- throw new TenantIsolationException("Tenant Context is missing from request!");
- }
- }
-
-
- private List<ServiceEndPointRequest> buildEndPointRequestList(ServiceEndPointList serviceEndPointList) throws TenantIsolationException {
- List<ServiceEndPoint> endpointList = serviceEndPointList.getServiceEndPointList();
- logger.debug("Number of service endpoints from GRM: {}", endpointList.size());
- List<ServiceEndPointRequest> serviceEndPointRequestList = new ArrayList<ServiceEndPointRequest>();
- for(ServiceEndPoint serviceEndpoint : endpointList) {
- serviceEndPointRequestList.add(buildServiceEndpoint(serviceEndpoint));
- }
- return serviceEndPointRequestList;
- }
-
-
- private ServiceEndPointRequest buildServiceEndpoint(ServiceEndPoint serviceEndpoint) throws TenantIsolationException {
-
- //@TODO: handle nulls? Put in a ServiceEndpointWrapper class which will check for nulls and flatten access to fields
- Version ver = new Version();
- ver.setMajor(serviceEndpoint.getVersion().getMajor());
- ver.setMinor(serviceEndpoint.getVersion().getMinor());
- ver.setPatch(serviceEndpoint.getVersion().getPatch());
-
- ServiceEndPoint endpoint = new ServiceEndPoint();
- endpoint.setName(buildServiceNameForVnf(serviceEndpoint.getName()));
-
- endpoint.setVersion(ver);
- endpoint.setHostAddress(serviceEndpoint.getHostAddress());
- endpoint.setListenPort(serviceEndpoint.getListenPort());
- endpoint.setLatitude(serviceEndpoint.getLatitude());
- endpoint.setLongitude(serviceEndpoint.getLongitude());
- endpoint.setContextPath(serviceEndpoint.getContextPath());
- endpoint.setRouteOffer(serviceEndpoint.getRouteOffer());
-
- OperationalInfo operInfo = new OperationalInfo();
- operInfo.setCreatedBy(serviceEndpoint.getOperationalInfo().getCreatedBy());
- operInfo.setUpdatedBy(serviceEndpoint.getOperationalInfo().getUpdatedBy());
-
- endpoint.setOperationalInfo(operInfo);
- endpoint.setProperties(serviceEndpoint.getProperties());
-
- String env = getEnvironmentName(serviceEndpoint.getProperties());
-
- ServiceEndPointRequest serviceEndPontRequest = new ServiceEndPointRequest();
- serviceEndPontRequest.setEnv(env);
- serviceEndPontRequest.setServiceEndPoint(endpoint);
-
- return serviceEndPontRequest;
- }
-
-
- protected String getEnvironmentName(List<Property> props) {
- String env = "";
- for(Property prop : props) {
- if(prop.getName().equalsIgnoreCase("Environment")) {
- env = prop.getValue();
- }
- }
- return env;
- }
-
-
- protected String buildServiceNameForVnf(String fqName) throws TenantIsolationException {
- // Service name format is: {tenantContext}.{workloadContext}.{serviceName} e.g. TEST.ECOMP_PSL.Inventory
- // We need to extract the serviceName, in the above example: "Inventory"
- String[] tokens = fqName.split("[.]");
- String serviceName;
- if(tokens.length > 0) {
- serviceName = tokens[tokens.length-1];
- }
- else {
- throw new TenantIsolationException("Fully qualified service name is null.");
- }
- String tenantContext = request.getRequestDetails().getRequestParameters().getTenantContext();
- String workloadContext = request.getRequestDetails().getRequestParameters().getWorkloadContext();
- return tenantContext + "." + workloadContext + "." + serviceName;
- }
-
- protected String getSearchKey(OperationalEnvironment aaiEnv) {
- return aaiEnv.getTenantContext() + "." + aaiEnv.getWorkloadContext() + ".*";
- }
-
- public void setRequest(CloudOrchestrationRequest request) {
- this.request = request;
- }
-
- private GRMClient getGrmClient() {
- if(grmClient == null) {
- this.grmClient = new GRMClient();
- }
-
- return grmClient;
- }
+
+ private static Logger logger = LoggerFactory.getLogger(CreateVnfOperationalEnvironment.class);
+ protected CloudOrchestrationRequest request;
+
+ @Autowired
+ private AAIClientObjectBuilder aaiClientObjectBuilder;
+ @Autowired
+ private AAIClientHelper aaiHelper;
+ @Autowired
+ private RequestsDBHelper requestDb;
+ private GRMClient grmClient;
+
+ public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException {
+ try {
+ setRequest(request);
+ ObjectMapper objectMapper = new ObjectMapper();
+ AAIResultWrapper aaiResultWrapper = aaiHelper.getAaiOperationalEnvironment(getEcompManagingEnvironmentId());
+ if (aaiResultWrapper.isEmpty()) {
+ throw new NotFoundException(getEcompManagingEnvironmentId() + " not found in A&AI");
+ }
+ OperationalEnvironment aaiEnv = aaiResultWrapper.asBean(OperationalEnvironment.class).get();
+
+ // Find ECOMP environments in GRM
+ logger.debug(" Start of GRM findRunningServicesAsString");
+ String searchKey = getSearchKey(aaiEnv);
+ String tenantContext = getTenantContext().toUpperCase();
+ String jsonResponse = getGrmClient().findRunningServicesAsString(searchKey, 1, tenantContext);
+ ServiceEndPointList sel = objectMapper.readValue(jsonResponse, ServiceEndPointList.class);
+ if (sel.getServiceEndPointList().size() == 0) {
+ throw new TenantIsolationException(
+ "GRM did not find any matches for " + searchKey + " in " + tenantContext);
+ }
+
+ // Replicate end-point for VNF Operating environment in GRM
+ List<ServiceEndPointRequest> serviceEndpointRequestList = buildEndPointRequestList(sel);
+ int ctr = 0;
+ int total = serviceEndpointRequestList.size();
+ for (ServiceEndPointRequest requestList : serviceEndpointRequestList) {
+ logger.debug("Creating endpoint " + ++ctr + " of " + total + ": "
+ + requestList.getServiceEndPoint().getName());
+ getGrmClient().addServiceEndPoint(requestList);
+ }
+
+ // Create VNF operating in A&AI
+ aaiHelper.createOperationalEnvironment(
+ aaiClientObjectBuilder.buildAAIOperationalEnvironment("INACTIVE", request));
+ aaiHelper.createRelationship(request.getOperationalEnvironmentId(), getEcompManagingEnvironmentId());
+
+ // Update request database
+ requestDb.updateInfraSuccessCompletion("SUCCESSFULLY created VNF operational environment", requestId,
+ request.getOperationalEnvironmentId());
+
+ } catch (Exception e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
+
+
+ ValidateException validateException =
+ new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
+
+ throw validateException;
+ }
+ }
+
+
+ protected String getEcompManagingEnvironmentId() throws TenantIsolationException {
+ RelatedInstanceList[] relatedInstances = request.getRequestDetails().getRelatedInstanceList();
+ if (relatedInstances.length > 0 && relatedInstances[0].getRelatedInstance() != null) {
+ return relatedInstances[0].getRelatedInstance().getInstanceId();
+ } else {
+ return null;
+ }
+ }
+
+
+ protected String getTenantContext() throws TenantIsolationException {
+ if (!StringUtils.isEmpty(request.getRequestDetails().getRequestParameters().getTenantContext())) {
+ return request.getRequestDetails().getRequestParameters().getTenantContext();
+ } else {
+ throw new TenantIsolationException("Tenant Context is missing from request!");
+ }
+ }
+
+
+ private List<ServiceEndPointRequest> buildEndPointRequestList(ServiceEndPointList serviceEndPointList)
+ throws TenantIsolationException {
+ List<ServiceEndPoint> endpointList = serviceEndPointList.getServiceEndPointList();
+ logger.debug("Number of service endpoints from GRM: {}", endpointList.size());
+ List<ServiceEndPointRequest> serviceEndPointRequestList = new ArrayList<ServiceEndPointRequest>();
+ for (ServiceEndPoint serviceEndpoint : endpointList) {
+ serviceEndPointRequestList.add(buildServiceEndpoint(serviceEndpoint));
+ }
+ return serviceEndPointRequestList;
+ }
+
+
+ private ServiceEndPointRequest buildServiceEndpoint(ServiceEndPoint serviceEndpoint)
+ throws TenantIsolationException {
+
+ // @TODO: handle nulls? Put in a ServiceEndpointWrapper class which will check for nulls and flatten access to
+ // fields
+ Version ver = new Version();
+ ver.setMajor(serviceEndpoint.getVersion().getMajor());
+ ver.setMinor(serviceEndpoint.getVersion().getMinor());
+ ver.setPatch(serviceEndpoint.getVersion().getPatch());
+
+ ServiceEndPoint endpoint = new ServiceEndPoint();
+ endpoint.setName(buildServiceNameForVnf(serviceEndpoint.getName()));
+
+ endpoint.setVersion(ver);
+ endpoint.setHostAddress(serviceEndpoint.getHostAddress());
+ endpoint.setListenPort(serviceEndpoint.getListenPort());
+ endpoint.setLatitude(serviceEndpoint.getLatitude());
+ endpoint.setLongitude(serviceEndpoint.getLongitude());
+ endpoint.setContextPath(serviceEndpoint.getContextPath());
+ endpoint.setRouteOffer(serviceEndpoint.getRouteOffer());
+
+ OperationalInfo operInfo = new OperationalInfo();
+ operInfo.setCreatedBy(serviceEndpoint.getOperationalInfo().getCreatedBy());
+ operInfo.setUpdatedBy(serviceEndpoint.getOperationalInfo().getUpdatedBy());
+
+ endpoint.setOperationalInfo(operInfo);
+ endpoint.setProperties(serviceEndpoint.getProperties());
+
+ String env = getEnvironmentName(serviceEndpoint.getProperties());
+
+ ServiceEndPointRequest serviceEndPontRequest = new ServiceEndPointRequest();
+ serviceEndPontRequest.setEnv(env);
+ serviceEndPontRequest.setServiceEndPoint(endpoint);
+
+ return serviceEndPontRequest;
+ }
+
+
+ protected String getEnvironmentName(List<Property> props) {
+ String env = "";
+ for (Property prop : props) {
+ if (prop.getName().equalsIgnoreCase("Environment")) {
+ env = prop.getValue();
+ }
+ }
+ return env;
+ }
+
+
+ protected String buildServiceNameForVnf(String fqName) throws TenantIsolationException {
+ // Service name format is: {tenantContext}.{workloadContext}.{serviceName} e.g. TEST.ECOMP_PSL.Inventory
+ // We need to extract the serviceName, in the above example: "Inventory"
+ String[] tokens = fqName.split("[.]");
+ String serviceName;
+ if (tokens.length > 0) {
+ serviceName = tokens[tokens.length - 1];
+ } else {
+ throw new TenantIsolationException("Fully qualified service name is null.");
+ }
+ String tenantContext = request.getRequestDetails().getRequestParameters().getTenantContext();
+ String workloadContext = request.getRequestDetails().getRequestParameters().getWorkloadContext();
+ return tenantContext + "." + workloadContext + "." + serviceName;
+ }
+
+ protected String getSearchKey(OperationalEnvironment aaiEnv) {
+ return aaiEnv.getTenantContext() + "." + aaiEnv.getWorkloadContext() + ".*";
+ }
+
+ public void setRequest(CloudOrchestrationRequest request) {
+ this.request = request;
+ }
+
+ private GRMClient getGrmClient() {
+ if (grmClient == null) {
+ this.grmClient = new GRMClient();
+ }
+
+ return grmClient;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java
index 7f8b330727..e8ea153a6a 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java
@@ -23,7 +23,6 @@
package org.onap.so.apihandlerinfra.tenantisolation.process;
import java.util.Optional;
-
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.onap.aai.domain.yang.OperationalEnvironment;
@@ -45,50 +44,53 @@ import org.springframework.stereotype.Component;
@Component
public class DeactivateVnfOperationalEnvironment {
- private static Logger logger = LoggerFactory.getLogger(DeactivateVnfOperationalEnvironment
- .class);
-
- @Autowired
+ private static Logger logger = LoggerFactory.getLogger(DeactivateVnfOperationalEnvironment.class);
+
+ @Autowired
private AAIClientHelper aaiHelper;
- @Autowired
+ @Autowired
private RequestsDBHelper requestDb;
-
- public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException {
- String operationalEnvironmentId = request.getOperationalEnvironmentId();
-
- OperationalEnvironment aaiOpEnv = getAAIOperationalEnvironment(operationalEnvironmentId);
- if (aaiOpEnv != null) {
- String operationalEnvironmentStatus = aaiOpEnv.getOperationalEnvironmentStatus();
-
- if(StringUtils.isBlank(operationalEnvironmentStatus)) {
- String error = "OperationalEnvironmentStatus is null on OperationalEnvironmentId: " + operationalEnvironmentId;
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
- throw new ValidateException.Builder(error, HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
- .errorInfo(errorLoggerInfo)
- .build();
- }
-
- if(operationalEnvironmentStatus.equalsIgnoreCase("ACTIVE")) {
-
- aaiOpEnv.setOperationalEnvironmentStatus("INACTIVE");
- aaiHelper.updateAaiOperationalEnvironment(operationalEnvironmentId, aaiOpEnv);
-
- } else if(!operationalEnvironmentStatus.equalsIgnoreCase("INACTIVE")) {
- String error = "Invalid OperationalEnvironmentStatus on OperationalEnvironmentId: " + operationalEnvironmentId;
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
- ValidateException validateException = new ValidateException.Builder(error,
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
- requestDb.updateInfraFailureCompletion(error, requestId, operationalEnvironmentId);
- throw validateException;
- }
-
- requestDb.updateInfraSuccessCompletion("SUCCESSFULLY Deactivated OperationalEnvironment", requestId, operationalEnvironmentId);
- }
- }
-
- private OperationalEnvironment getAAIOperationalEnvironment(String operationalEnvironmentId) {
- AAIResultWrapper aaiResult = aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId);
- Optional<OperationalEnvironment> operationalEnvironmentOpt = aaiResult.asBean(OperationalEnvironment.class);
- return operationalEnvironmentOpt.isPresent() ? operationalEnvironmentOpt.get() : null;
- }
+
+ public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException {
+ String operationalEnvironmentId = request.getOperationalEnvironmentId();
+
+ OperationalEnvironment aaiOpEnv = getAAIOperationalEnvironment(operationalEnvironmentId);
+ if (aaiOpEnv != null) {
+ String operationalEnvironmentStatus = aaiOpEnv.getOperationalEnvironmentStatus();
+
+ if (StringUtils.isBlank(operationalEnvironmentStatus)) {
+ String error =
+ "OperationalEnvironmentStatus is null on OperationalEnvironmentId: " + operationalEnvironmentId;
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
+ throw new ValidateException.Builder(error, HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+ }
+
+ if (operationalEnvironmentStatus.equalsIgnoreCase("ACTIVE")) {
+
+ aaiOpEnv.setOperationalEnvironmentStatus("INACTIVE");
+ aaiHelper.updateAaiOperationalEnvironment(operationalEnvironmentId, aaiOpEnv);
+
+ } else if (!operationalEnvironmentStatus.equalsIgnoreCase("INACTIVE")) {
+ String error =
+ "Invalid OperationalEnvironmentStatus on OperationalEnvironmentId: " + operationalEnvironmentId;
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
+ ValidateException validateException = new ValidateException.Builder(error, HttpStatus.SC_BAD_REQUEST,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+ requestDb.updateInfraFailureCompletion(error, requestId, operationalEnvironmentId);
+ throw validateException;
+ }
+
+ requestDb.updateInfraSuccessCompletion("SUCCESSFULLY Deactivated OperationalEnvironment", requestId,
+ operationalEnvironmentId);
+ }
+ }
+
+ private OperationalEnvironment getAAIOperationalEnvironment(String operationalEnvironmentId) {
+ AAIResultWrapper aaiResult = aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId);
+ Optional<OperationalEnvironment> operationalEnvironmentOpt = aaiResult.asBean(OperationalEnvironment.class);
+ return operationalEnvironmentOpt.isPresent() ? operationalEnvironmentOpt.get() : null;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Action.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Action.java
index 3f7a5536f3..3fc567e81e 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Action.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Action.java
@@ -21,8 +21,5 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
public enum Action {
- create,
- activate,
- deactivate,
- distributionStatus
+ create, activate, deactivate, distributionStatus
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationRequestList.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationRequestList.java
index 25c8538003..71eb6020b4 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationRequestList.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationRequestList.java
@@ -24,14 +24,14 @@ import java.util.List;
public class CloudOrchestrationRequestList {
- private List<CloudOrchestrationResponse> requestList;
+ private List<CloudOrchestrationResponse> requestList;
- public List<CloudOrchestrationResponse> getRequestList() {
- return requestList;
- }
+ public List<CloudOrchestrationResponse> getRequestList() {
+ return requestList;
+ }
- public void setRequestList(List<CloudOrchestrationResponse> requestList) {
- this.requestList = requestList;
- }
+ public void setRequestList(List<CloudOrchestrationResponse> requestList) {
+ this.requestList = requestList;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationResponse.java
index bd5167c395..7dc219407e 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationResponse.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationResponse.java
@@ -25,14 +25,14 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_DEFAULT)
public class CloudOrchestrationResponse {
-
- protected Request request;
-
- public Request getRequest() {
- return request;
- }
- public void setRequest(Request request) {
- this.request = request;
- }
+ protected Request request;
+
+ public Request getRequest() {
+ return request;
+ }
+
+ public void setRequest(Request request) {
+ this.request = request;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Distribution.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Distribution.java
index b556178427..255d3a50f9 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Distribution.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Distribution.java
@@ -22,29 +22,29 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans;
import java.io.Serializable;
-public class Distribution implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = -529289171571892371L;
- private Status status;
- private String errorReason;
-
- public Status getStatus() {
- return status;
- }
-
- public void setStatus(Status status) {
- this.status = status;
- }
-
- public String getErrorReason() {
- return errorReason;
- }
-
- public void setErrorReason(String errorReason) {
- this.errorReason = errorReason;
- }
+public class Distribution implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -529289171571892371L;
+ private Status status;
+ private String errorReason;
+
+ public Status getStatus() {
+ return status;
+ }
+
+ public void setStatus(Status status) {
+ this.status = status;
+ }
+
+ public String getErrorReason() {
+ return errorReason;
+ }
+
+ public void setErrorReason(String errorReason) {
+ this.errorReason = errorReason;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/DistributionStatus.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/DistributionStatus.java
index d54c6238ae..1b30b6fa14 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/DistributionStatus.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/DistributionStatus.java
@@ -21,6 +21,5 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
public enum DistributionStatus {
- DISTRIBUTION_COMPLETE_OK,
- DISTRIBUTION_COMPLETE_ERROR
+ DISTRIBUTION_COMPLETE_OK, DISTRIBUTION_COMPLETE_ERROR
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/InstanceReferences.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/InstanceReferences.java
index 097660d9f3..34e219415b 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/InstanceReferences.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/InstanceReferences.java
@@ -29,32 +29,32 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class InstanceReferences {
- private String operationalEnvironmentId;
- private String operationalEnvName;
- private String requestorId;
-
- public String getOperationalEnvironmentId() {
- return operationalEnvironmentId;
- }
-
- public void setOperationalEnvironmentId(String operationalEnvironmentId) {
- this.operationalEnvironmentId = operationalEnvironmentId;
- }
-
- public String getOperationalEnvName() {
- return operationalEnvName;
- }
-
- public void setOperationalEnvName(String operationalEnvName) {
- this.operationalEnvName = operationalEnvName;
- }
-
- public String getRequestorId() {
- return requestorId;
- }
-
- public void setRequestorId(String requestorId) {
- this.requestorId = requestorId;
- }
-
+ private String operationalEnvironmentId;
+ private String operationalEnvName;
+ private String requestorId;
+
+ public String getOperationalEnvironmentId() {
+ return operationalEnvironmentId;
+ }
+
+ public void setOperationalEnvironmentId(String operationalEnvironmentId) {
+ this.operationalEnvironmentId = operationalEnvironmentId;
+ }
+
+ public String getOperationalEnvName() {
+ return operationalEnvName;
+ }
+
+ public void setOperationalEnvName(String operationalEnvName) {
+ this.operationalEnvName = operationalEnvName;
+ }
+
+ public String getRequestorId() {
+ return requestorId;
+ }
+
+ public void setRequestorId(String requestorId) {
+ this.requestorId = requestorId;
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java
index afb9ebdff3..4c66a3118e 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java
@@ -23,7 +23,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -33,21 +32,21 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class Manifest implements Serializable {
- private static final long serialVersionUID = -3460949513229380541L;
- @JsonProperty("serviceModelList")
- private List<ServiceModelList> serviceModelList = new ArrayList<ServiceModelList>();
-
- public List<ServiceModelList> getServiceModelList() {
- return serviceModelList;
- }
-
- public void setServiceModelList(List<ServiceModelList> serviceModelList) {
- this.serviceModelList = serviceModelList;
- }
-
- @Override
- public String toString() {
- return "Manifest [serviceModelList=" + serviceModelList.toString() + "]";
- }
-
+ private static final long serialVersionUID = -3460949513229380541L;
+ @JsonProperty("serviceModelList")
+ private List<ServiceModelList> serviceModelList = new ArrayList<ServiceModelList>();
+
+ public List<ServiceModelList> getServiceModelList() {
+ return serviceModelList;
+ }
+
+ public void setServiceModelList(List<ServiceModelList> serviceModelList) {
+ this.serviceModelList = serviceModelList;
+ }
+
+ @Override
+ public String toString() {
+ return "Manifest [serviceModelList=" + serviceModelList.toString() + "]";
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/OperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/OperationalEnvironment.java
index 61acc9f94c..d16093de04 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/OperationalEnvironment.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/OperationalEnvironment.java
@@ -22,6 +22,5 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans;
public enum OperationalEnvironment {
- ECOMP,
- VNF
+ ECOMP, VNF
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RecoveryAction.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RecoveryAction.java
index f32c11f8a8..91d7aa2b89 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RecoveryAction.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RecoveryAction.java
@@ -22,7 +22,5 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans;
public enum RecoveryAction {
- retry,
- abort,
- skip
+ retry, abort, skip
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstance.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstance.java
index 78faea7b8e..75f7e91742 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstance.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstance.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -30,39 +29,43 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "relatedInstance")
@JsonInclude(Include.NON_DEFAULT)
public class RelatedInstance implements Serializable {
-
- private static final long serialVersionUID = -6775477105573153067L;
- @JsonProperty("instanceName")
- protected String instanceName;
- @JsonProperty("instanceId")
- protected String instanceId;
- @JsonProperty("resourceType")
- protected ResourceType resourceType;
- public String getInstanceName() {
- return instanceName;
- }
- public void setInstanceName(String instanceName) {
- this.instanceName = instanceName;
- }
- public String getInstanceId() {
- return instanceId;
- }
- public void setInstanceId(String instanceId) {
- this.instanceId = instanceId;
- }
- public ResourceType getResourceType() {
- return resourceType;
- }
- public void setResourceType(ResourceType resourceType) {
- this.resourceType = resourceType;
- }
+ private static final long serialVersionUID = -6775477105573153067L;
+ @JsonProperty("instanceName")
+ protected String instanceName;
+ @JsonProperty("instanceId")
+ protected String instanceId;
+ @JsonProperty("resourceType")
+ protected ResourceType resourceType;
+
+ public String getInstanceName() {
+ return instanceName;
+ }
+
+ public void setInstanceName(String instanceName) {
+ this.instanceName = instanceName;
+ }
+
+ public String getInstanceId() {
+ return instanceId;
+ }
+
+ public void setInstanceId(String instanceId) {
+ this.instanceId = instanceId;
+ }
+
+ public ResourceType getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(ResourceType resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ @Override
+ public String toString() {
+ return "RelatedInstance [instanceName=" + instanceName + ", instanceId=" + instanceId + ", resourceType="
+ + resourceType + "]";
+ }
- @Override
- public String toString() {
- return "RelatedInstance [instanceName=" + instanceName +
- ", instanceId=" + instanceId +
- ", resourceType=" + resourceType + "]";
- }
-
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstanceList.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstanceList.java
index ee54392e9d..73fb20660a 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstanceList.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstanceList.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,15 +30,15 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class RelatedInstanceList implements Serializable {
- private static final long serialVersionUID = 1758713583807257102L;
- @JsonProperty("relatedInstance")
- protected RelatedInstance relatedInstance;
+ private static final long serialVersionUID = 1758713583807257102L;
+ @JsonProperty("relatedInstance")
+ protected RelatedInstance relatedInstance;
- public RelatedInstance getRelatedInstance() {
- return relatedInstance;
- }
+ public RelatedInstance getRelatedInstance() {
+ return relatedInstance;
+ }
- public void setRelatedInstance(RelatedInstance relatedInstance) {
- this.relatedInstance = relatedInstance;
- }
+ public void setRelatedInstance(RelatedInstance relatedInstance) {
+ this.relatedInstance = relatedInstance;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Request.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Request.java
index 7d927512e6..eb4e9384f5 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Request.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Request.java
@@ -36,55 +36,62 @@ public class Request {
protected String requestType;
protected RequestDetails requestDetails;
protected RequestStatus requestStatus;
-
-
- public String getRequestId() {
- return requestId;
- }
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
- public String getStartTime() {
- return startTime;
- }
- public void setStartTime(String startTime) {
- this.startTime = startTime;
- }
-
- public String getRequestScope() {
- return requestScope;
- }
- public void setRequestScope(String requestScope) {
- this.requestScope = requestScope;
- }
-
- public String getRequestType() {
- return requestType;
- }
- public void setRequestType(String requestType) {
- this.requestType = requestType;
- }
-
- public RequestStatus getRequestStatus() {
- return requestStatus;
- }
- public void setRequestStatus(RequestStatus requestStatus) {
- this.requestStatus = requestStatus;
- }
-
- public InstanceReferences getInstanceReferences() {
- return instanceReferences;
- }
- public void setInstanceReferences(InstanceReferences instanceReferences) {
- this.instanceReferences = instanceReferences;
- }
-
- public RequestDetails getRequestDetails() {
- return requestDetails;
- }
- public void setRequestDetails(RequestDetails requestDetails) {
- this.requestDetails = requestDetails;
- }
-
-} \ No newline at end of file
+
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getStartTime() {
+ return startTime;
+ }
+
+ public void setStartTime(String startTime) {
+ this.startTime = startTime;
+ }
+
+ public String getRequestScope() {
+ return requestScope;
+ }
+
+ public void setRequestScope(String requestScope) {
+ this.requestScope = requestScope;
+ }
+
+ public String getRequestType() {
+ return requestType;
+ }
+
+ public void setRequestType(String requestType) {
+ this.requestType = requestType;
+ }
+
+ public RequestStatus getRequestStatus() {
+ return requestStatus;
+ }
+
+ public void setRequestStatus(RequestStatus requestStatus) {
+ this.requestStatus = requestStatus;
+ }
+
+ public InstanceReferences getInstanceReferences() {
+ return instanceReferences;
+ }
+
+ public void setInstanceReferences(InstanceReferences instanceReferences) {
+ this.instanceReferences = instanceReferences;
+ }
+
+ public RequestDetails getRequestDetails() {
+ return requestDetails;
+ }
+
+ public void setRequestDetails(RequestDetails requestDetails) {
+ this.requestDetails = requestDetails;
+ }
+
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestDetails.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestDetails.java
index 36e3bf95e7..ff427c719f 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestDetails.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestDetails.java
@@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans;
import java.io.Serializable;
import java.util.Arrays;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -32,20 +31,18 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class RequestDetails implements Serializable {
- private static final long serialVersionUID = -73080684945860609L;
- @JsonProperty("requestInfo")
+ private static final long serialVersionUID = -73080684945860609L;
+ @JsonProperty("requestInfo")
protected RequestInfo requestInfo;
- @JsonProperty("relatedInstanceList")
+ @JsonProperty("relatedInstanceList")
protected RelatedInstanceList[] relatedInstanceList;
- @JsonProperty("requestParameters")
+ @JsonProperty("requestParameters")
protected RequestParameters requestParameters;
/**
* Gets the value of the requestInfo property.
*
- * @return
- * possible object is
- * {@link RequestInfo }
+ * @return possible object is {@link RequestInfo }
*
*/
public RequestInfo getRequestInfo() {
@@ -55,9 +52,7 @@ public class RequestDetails implements Serializable {
/**
* Sets the value of the requestInfo property.
*
- * @param value
- * allowed object is
- * {@link RequestInfo }
+ * @param value allowed object is {@link RequestInfo }
*
*/
public void setRequestInfo(RequestInfo value) {
@@ -67,9 +62,7 @@ public class RequestDetails implements Serializable {
/**
* Gets the value of the requestParameters property.
*
- * @return
- * possible object is
- * {@link RequestParameters }
+ * @return possible object is {@link RequestParameters }
*
*/
public RequestParameters getRequestParameters() {
@@ -79,26 +72,24 @@ public class RequestDetails implements Serializable {
/**
* Sets the value of the requestParameters property.
*
- * @param value
- * allowed object is
- * {@link RequestParameters }
+ * @param value allowed object is {@link RequestParameters }
*
*/
public void setRequestParameters(RequestParameters value) {
this.requestParameters = value;
}
- public RelatedInstanceList[] getRelatedInstanceList() {
- return relatedInstanceList;
- }
+ public RelatedInstanceList[] getRelatedInstanceList() {
+ return relatedInstanceList;
+ }
- public void setRelatedInstanceList(RelatedInstanceList[] relatedInstanceList) {
- this.relatedInstanceList = relatedInstanceList;
- }
- @Override
- public String toString() {
- return "RequestDetails [requestInfo=" + requestInfo +
- ", relatedInstanceList=" + Arrays.toString(relatedInstanceList) +
- ", requestParameters=" + requestParameters + "]";
- }
+ public void setRelatedInstanceList(RelatedInstanceList[] relatedInstanceList) {
+ this.relatedInstanceList = relatedInstanceList;
+ }
+
+ @Override
+ public String toString() {
+ return "RequestDetails [requestInfo=" + requestInfo + ", relatedInstanceList="
+ + Arrays.toString(relatedInstanceList) + ", requestParameters=" + requestParameters + "]";
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestInfo.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestInfo.java
index d57d4bf366..b40fc3f07d 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestInfo.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestInfo.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,22 +30,20 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class RequestInfo implements Serializable {
- private static final long serialVersionUID = 1346372792555344857L;
- @JsonProperty("resourceType")
+ private static final long serialVersionUID = 1346372792555344857L;
+ @JsonProperty("resourceType")
protected ResourceType resourceType;
- @JsonProperty("source")
+ @JsonProperty("source")
protected String source;
- @JsonProperty("instanceName")
+ @JsonProperty("instanceName")
protected String instanceName;
- @JsonProperty("requestorId")
+ @JsonProperty("requestorId")
protected String requestorId;
- /**
+ /**
* Gets the value of the resourceType property.
*
- * @return
- * possible object is
- * {@link ResourceType }
+ * @return possible object is {@link ResourceType }
*
*/
public ResourceType getResourceType() {
@@ -56,9 +53,7 @@ public class RequestInfo implements Serializable {
/**
* Sets the value of the source property.
*
- * @param value
- * allowed object is
- * {@link ResourceType }
+ * @param value allowed object is {@link ResourceType }
*
*/
public void setResourceType(ResourceType value) {
@@ -69,9 +64,7 @@ public class RequestInfo implements Serializable {
/**
* Gets the value of the source property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getSource() {
@@ -81,38 +74,34 @@ public class RequestInfo implements Serializable {
/**
* Sets the value of the source property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setSource(String value) {
this.source = value;
}
- public String getInstanceName() {
- return instanceName;
- }
-
- public void setInstanceName(String instanceName) {
- this.instanceName = instanceName;
- }
-
- public String getRequestorId() {
- return requestorId;
- }
-
- public void setRequestorId(String requestorId) {
- this.requestorId = requestorId;
- }
-
- @Override
- public String toString() {
- return "RequestInfo [source=" + source
- + ", instanceName=" + instanceName
- + ", requestorId=" + requestorId
- + ", resourceType=" + resourceType + "]";
- }
+ public String getInstanceName() {
+ return instanceName;
+ }
+
+ public void setInstanceName(String instanceName) {
+ this.instanceName = instanceName;
+ }
+
+ public String getRequestorId() {
+ return requestorId;
+ }
+
+ public void setRequestorId(String requestorId) {
+ this.requestorId = requestorId;
+ }
+
+ @Override
+ public String toString() {
+ return "RequestInfo [source=" + source + ", instanceName=" + instanceName + ", requestorId=" + requestorId
+ + ", resourceType=" + resourceType + "]";
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestList.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestList.java
index 170b5e7609..20021888c0 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestList.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestList.java
@@ -30,17 +30,15 @@ import com.fasterxml.jackson.annotation.JsonRootName;
public class RequestList {
- @JsonProperty("request")
+ @JsonProperty("request")
protected Request request;
- @JsonProperty("requestStatus")
+ @JsonProperty("requestStatus")
protected RequestStatus requestStatus;
/**
* Gets the value of the request property.
*
- * @return
- * possible object is
- * {@link Request }
+ * @return possible object is {@link Request }
*
*/
public Request getRequest() {
@@ -50,9 +48,7 @@ public class RequestList {
/**
* Sets the value of the requestInfo property.
*
- * @param value
- * allowed object is
- * {@link Request }
+ * @param value allowed object is {@link Request }
*
*/
public void setRequest(Request value) {
@@ -62,22 +58,18 @@ public class RequestList {
/**
* Gets the value of the requestStatus property.
*
- * @return
- * possible object is
- * {@link RequestStatus }
+ * @return possible object is {@link RequestStatus }
*
*/
public RequestStatus getRequestStatus() {
return requestStatus;
}
-
+
/**
* Sets the value of the requestStatus property.
*
- * @param value
- * allowed object is
- * {@link RequestStatus }
+ * @param value allowed object is {@link RequestStatus }
*
*/
public void setRequestStatus(RequestStatus value) {
@@ -85,9 +77,8 @@ public class RequestList {
}
- @Override
- public String toString() {
- return "RequestList [request=" + request +
- ", requestStatus=" + requestStatus + "]";
- }
-} \ No newline at end of file
+ @Override
+ public String toString() {
+ return "RequestList [request=" + request + ", requestStatus=" + requestStatus + "]";
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestParameters.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestParameters.java
index 1a12c47d7d..299d177099 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestParameters.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestParameters.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,54 +30,52 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class RequestParameters implements Serializable {
- private static final long serialVersionUID = 8530327178156183693L;
- @JsonProperty("operationalEnvironmentType")
- private OperationalEnvironment operationalEnvironmentType;
- @JsonProperty("tenantContext")
- private String tenantContext;
- @JsonProperty("workloadContext")
- private String workloadContext;
- @JsonProperty("manifest")
- private Manifest manifest;
-
- public OperationalEnvironment getOperationalEnvironmentType() {
- return operationalEnvironmentType;
- }
+ private static final long serialVersionUID = 8530327178156183693L;
+ @JsonProperty("operationalEnvironmentType")
+ private OperationalEnvironment operationalEnvironmentType;
+ @JsonProperty("tenantContext")
+ private String tenantContext;
+ @JsonProperty("workloadContext")
+ private String workloadContext;
+ @JsonProperty("manifest")
+ private Manifest manifest;
+
+ public OperationalEnvironment getOperationalEnvironmentType() {
+ return operationalEnvironmentType;
+ }
+
+ public void setOperationalEnvironmentType(OperationalEnvironment operationalEnvironmentType) {
+ this.operationalEnvironmentType = operationalEnvironmentType;
+ }
+
+ public String getTenantContext() {
+ return tenantContext;
+ }
+
+ public void setTenantContext(String tenantContext) {
+ this.tenantContext = tenantContext;
+ }
- public void setOperationalEnvironmentType(OperationalEnvironment operationalEnvironmentType) {
- this.operationalEnvironmentType = operationalEnvironmentType;
- }
+ public String getWorkloadContext() {
+ return workloadContext;
+ }
- public String getTenantContext() {
- return tenantContext;
- }
+ public void setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
- public void setTenantContext(String tenantContext) {
- this.tenantContext = tenantContext;
- }
-
- public String getWorkloadContext() {
- return workloadContext;
- }
+ public Manifest getManifest() {
+ return manifest;
+ }
- public void setWorkloadContext(String workloadContext) {
- this.workloadContext = workloadContext;
- }
-
- public Manifest getManifest() {
- return manifest;
- }
+ public void setManifest(Manifest manifest) {
+ this.manifest = manifest;
+ }
- public void setManifest(Manifest manifest) {
- this.manifest = manifest;
- }
-
- @Override
- public String toString() {
- return "RequestParameters [operationalEnvironmentType=" + operationalEnvironmentType
- + ", tenantContext=" + tenantContext
- + ", workloadContext=" + workloadContext
- + ", manifes=" + manifest +"]";
- }
+ @Override
+ public String toString() {
+ return "RequestParameters [operationalEnvironmentType=" + operationalEnvironmentType + ", tenantContext="
+ + tenantContext + ", workloadContext=" + workloadContext + ", manifes=" + manifest + "]";
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestReferences.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestReferences.java
index 337de3c51d..d766bcf2dd 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestReferences.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestReferences.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -30,67 +29,58 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "requestReferences")
@JsonInclude(Include.NON_DEFAULT)
public class RequestReferences implements Serializable {
-
- private static final long serialVersionUID = 5873356773819905368L;
-
- @JsonProperty("requestId")
- protected String requestId;
-
- @JsonProperty("instanceId")
- String instanceId;
+
+ private static final long serialVersionUID = 5873356773819905368L;
+
+ @JsonProperty("requestId")
+ protected String requestId;
+
+ @JsonProperty("instanceId")
+ String instanceId;
/**
* Gets the value of the requestId property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
- */
- public String getRequestId() {
- return requestId;
- }
-
+ */
+ public String getRequestId() {
+ return requestId;
+ }
+
/**
* Sets the value of the requestId property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
- */
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
+ */
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
/**
* Gets the value of the instanceId property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
- */
- public String getInstanceId() {
- return instanceId;
- }
-
+ */
+ public String getInstanceId() {
+ return instanceId;
+ }
+
/**
* Sets the value of the instanceId property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
- */
- public void setInstanceId(String instanceId) {
- this.instanceId = instanceId;
- }
+ */
+ public void setInstanceId(String instanceId) {
+ this.instanceId = instanceId;
+ }
+
+ @Override
+ public String toString() {
+ return "RequestReferences [requestId=" + requestId + ", instanceId=" + instanceId + "]";
+ }
- @Override
- public String toString() {
- return "RequestReferences [requestId=" + requestId +
- ", instanceId=" + instanceId + "]";
- }
-
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestStatus.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestStatus.java
index 6fd765b76f..f1f9417805 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestStatus.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestStatus.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,39 +30,46 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class RequestStatus implements Serializable {
- private static final long serialVersionUID = -1835437975187313144L;
- @JsonProperty("requestState")
- protected String requestState;
- @JsonProperty("statusMessage")
+ private static final long serialVersionUID = -1835437975187313144L;
+ @JsonProperty("requestState")
+ protected String requestState;
+ @JsonProperty("statusMessage")
protected String statusMessage;
- @JsonProperty("percentProgress")
+ @JsonProperty("percentProgress")
protected String percentProgress;
- @JsonProperty("timestamp")
+ @JsonProperty("timestamp")
protected String timeStamp;
- public String getRequestState() {
- return requestState;
- }
- public void setRequestState(String requestState) {
- this.requestState = requestState;
- }
- public String getStatusMessage() {
- return statusMessage;
- }
- public void setStatusMessage(String statusMessage) {
- this.statusMessage = statusMessage;
- }
- public String getPercentProgress() {
- return percentProgress;
- }
- public void setPercentProgress(String percentProgress) {
- this.percentProgress = percentProgress;
- }
- public String getTimeStamp() {
- return timeStamp;
- }
- public void setTimeStamp(String timeStamp) {
- this.timeStamp = timeStamp;
- }
-} \ No newline at end of file
+ public String getRequestState() {
+ return requestState;
+ }
+
+ public void setRequestState(String requestState) {
+ this.requestState = requestState;
+ }
+
+ public String getStatusMessage() {
+ return statusMessage;
+ }
+
+ public void setStatusMessage(String statusMessage) {
+ this.statusMessage = statusMessage;
+ }
+
+ public String getPercentProgress() {
+ return percentProgress;
+ }
+
+ public void setPercentProgress(String percentProgress) {
+ this.percentProgress = percentProgress;
+ }
+
+ public String getTimeStamp() {
+ return timeStamp;
+ }
+
+ public void setTimeStamp(String timeStamp) {
+ this.timeStamp = timeStamp;
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ResourceType.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ResourceType.java
index 835c2657d1..edeee56249 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ResourceType.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ResourceType.java
@@ -22,5 +22,5 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans;
public enum ResourceType {
- operationalEnvironment
+ operationalEnvironment
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ServiceModelList.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ServiceModelList.java
index 4dea3149ad..fbbd183380 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ServiceModelList.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ServiceModelList.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,29 +30,32 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class ServiceModelList implements Serializable {
- private static final long serialVersionUID = 1758713583807257102L;
-
- @JsonProperty("serviceModelVersionId")
- protected String serviceModelVersionId;
- @JsonProperty("recoveryAction")
- protected RecoveryAction recoveryAction;
-
- public String getServiceModelVersionId() {
- return serviceModelVersionId;
- }
- public void setServiceModelVersionId(String serviceModelVersionId) {
- this.serviceModelVersionId = serviceModelVersionId;
- }
- public RecoveryAction getRecoveryAction() {
- return recoveryAction;
- }
- public void setRecoveryAction(RecoveryAction recoveryAction) {
- this.recoveryAction = recoveryAction;
- }
-
- @Override
- public String toString() {
- return "ServiceModelList [serviceModelVersionId=" + serviceModelVersionId + ","
- + "recoveryAction=" + recoveryAction +"]";
- }
+ private static final long serialVersionUID = 1758713583807257102L;
+
+ @JsonProperty("serviceModelVersionId")
+ protected String serviceModelVersionId;
+ @JsonProperty("recoveryAction")
+ protected RecoveryAction recoveryAction;
+
+ public String getServiceModelVersionId() {
+ return serviceModelVersionId;
+ }
+
+ public void setServiceModelVersionId(String serviceModelVersionId) {
+ this.serviceModelVersionId = serviceModelVersionId;
+ }
+
+ public RecoveryAction getRecoveryAction() {
+ return recoveryAction;
+ }
+
+ public void setRecoveryAction(RecoveryAction recoveryAction) {
+ this.recoveryAction = recoveryAction;
+ }
+
+ @Override
+ public String toString() {
+ return "ServiceModelList [serviceModelVersionId=" + serviceModelVersionId + "," + "recoveryAction="
+ + recoveryAction + "]";
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Status.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Status.java
index a7c6c67395..5182f448fe 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Status.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Status.java
@@ -21,6 +21,5 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
public enum Status {
- DISTRIBUTION_COMPLETE_OK,
- DISTRIBUTION_COMPLETE_ERROR
+ DISTRIBUTION_COMPLETE_OK, DISTRIBUTION_COMPLETE_ERROR
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationRequest.java
index 003cb0815a..6d4c17519b 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationRequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationRequest.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -31,65 +30,72 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonInclude(Include.NON_DEFAULT)
public class TenantIsolationRequest implements Serializable {
- private static final long serialVersionUID = -210322298981798607L;
- @JsonProperty("requestId")
+ private static final long serialVersionUID = -210322298981798607L;
+ @JsonProperty("requestId")
protected String requestId;
- @JsonProperty("startTime")
+ @JsonProperty("startTime")
protected String startTime;
- @JsonProperty("requestScope")
+ @JsonProperty("requestScope")
protected String requestScope;
- @JsonProperty("requestType")
+ @JsonProperty("requestType")
protected String requestType;
- @JsonProperty("requestDetails")
+ @JsonProperty("requestDetails")
protected RequestDetails requestDetails;
- @JsonProperty("requestStatus")
+ @JsonProperty("requestStatus")
protected RequestStatus requestStatus;
-
- public String getRequestId() {
- return requestId;
- }
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
- public String getStartTime() {
- return startTime;
- }
- public void setStartTime(String startTime) {
- this.startTime = startTime;
- }
- public String getRequestScope() {
- return requestScope;
- }
- public void setRequestScope(String requestScope) {
- this.requestScope = requestScope;
- }
- public String getRequestType() {
- return requestType;
- }
- public void setRequestType(String requestType) {
- this.requestType = requestType;
- }
- public RequestStatus getRequestStatus() {
- return requestStatus;
- }
- public void setRequestStatus(RequestStatus requestStatus) {
- this.requestStatus = requestStatus;
- }
-
- public RequestDetails getRequestDetails() {
- return requestDetails;
- }
- public void setRequestDetails(RequestDetails requestDetails) {
- this.requestDetails = requestDetails;
- }
-
- @Override
- public String toString() {
- return "Request [requestId=" + requestId +
- ", startTime=" + startTime +
- ", requestType=" + requestType +
- ", requestDetails=" + requestDetails.toString() +
- ", requestStatus=" + requestStatus.toString() + "]";
- }
-
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getStartTime() {
+ return startTime;
+ }
+
+ public void setStartTime(String startTime) {
+ this.startTime = startTime;
+ }
+
+ public String getRequestScope() {
+ return requestScope;
+ }
+
+ public void setRequestScope(String requestScope) {
+ this.requestScope = requestScope;
+ }
+
+ public String getRequestType() {
+ return requestType;
+ }
+
+ public void setRequestType(String requestType) {
+ this.requestType = requestType;
+ }
+
+ public RequestStatus getRequestStatus() {
+ return requestStatus;
+ }
+
+ public void setRequestStatus(RequestStatus requestStatus) {
+ this.requestStatus = requestStatus;
+ }
+
+ public RequestDetails getRequestDetails() {
+ return requestDetails;
+ }
+
+ public void setRequestDetails(RequestDetails requestDetails) {
+ this.requestDetails = requestDetails;
+ }
+
+ @Override
+ public String toString() {
+ return "Request [requestId=" + requestId + ", startTime=" + startTime + ", requestType=" + requestType
+ + ", requestDetails=" + requestDetails.toString() + ", requestStatus=" + requestStatus.toString() + "]";
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationResponse.java
index 15a0ab840c..b4ce83afca 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationResponse.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationResponse.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
import java.io.Serializable;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -30,86 +29,74 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "tenantIsolationResponse")
@JsonInclude(Include.NON_DEFAULT)
public class TenantIsolationResponse implements Serializable {
-
- private static final long serialVersionUID = 756749312745898666L;
- @JsonProperty("requestId")
- protected String requestId;
- @JsonProperty("status")
- String status;
- @JsonProperty("message")
- String message;
+
+ private static final long serialVersionUID = 756749312745898666L;
+ @JsonProperty("requestId")
+ protected String requestId;
+ @JsonProperty("status")
+ String status;
+ @JsonProperty("message")
+ String message;
/**
* Gets the value of the requestId property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
- */
- public String getRequestId() {
- return requestId;
- }
-
+ */
+ public String getRequestId() {
+ return requestId;
+ }
+
/**
* Sets the value of the requestId property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
- */
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
+ */
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
/**
* Gets the value of the status property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
- */
- public String getStatus() {
- return status;
- }
-
+ */
+ public String getStatus() {
+ return status;
+ }
+
/**
* Sets the value of the status property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
- */
- public void setStatus(String status) {
- this.status = status;
- }
-
- /**
+ */
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ /**
* Gets the value of the message property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
- */
- public String getMessage() {
- return message;
- }
-
+ */
+ public String getMessage() {
+ return message;
+ }
+
/**
* Sets the value of the message property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
- */
- public void setMessage(String message) {
- this.message = message;
- }
+ */
+ public void setMessage(String message) {
+ this.message = message;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantSyncResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantSyncResponse.java
index 7281e1c708..0327232b43 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantSyncResponse.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantSyncResponse.java
@@ -21,15 +21,15 @@
package org.onap.so.apihandlerinfra.tenantisolationbeans;
public class TenantSyncResponse {
-
- private RequestReferences requestReferences;
- public RequestReferences getRequestReferences() {
- return requestReferences;
- }
+ private RequestReferences requestReferences;
- public void setRequestReferences(RequestReferences requestReferences) {
- this.requestReferences = requestReferences;
- }
+ public RequestReferences getRequestReferences() {
+ return requestReferences;
+ }
+
+ public void setRequestReferences(RequestReferences requestReferences) {
+ this.requestReferences = requestReferences;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/package-info.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/package-info.java
index 713a763321..45f85bf5d3 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/package-info.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/package-info.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
package org.onap.so.apihandlerinfra.tenantisolationbeans;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ApplyUpdatedConfigValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ApplyUpdatedConfigValidation.java
index 243bbf1474..07b2d4426f 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ApplyUpdatedConfigValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ApplyUpdatedConfigValidation.java
@@ -25,25 +25,26 @@ import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.RequestInfo;
import org.onap.so.serviceinstancebeans.RequestParameters;
-public class ApplyUpdatedConfigValidation implements ValidationRule{
+public class ApplyUpdatedConfigValidation implements ValidationRule {
private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
+ return (s == null || s.trim().isEmpty());
}
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters();
- RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo();
-
- if(requestInfo == null){
- throw new ValidationException("requestInfo");
- }else if(empty(requestInfo.getRequestorId())) {
- throw new ValidationException ("requestorId");
- }else if (empty (requestInfo.getSource ())) {
- throw new ValidationException ("source");
+
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters();
+ RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo();
+
+ if (requestInfo == null) {
+ throw new ValidationException("requestInfo");
+ } else if (empty(requestInfo.getRequestorId())) {
+ throw new ValidationException("requestorId");
+ } else if (empty(requestInfo.getSource())) {
+ throw new ValidationException("source");
+ }
+ if (requestParameters == null) {
+ throw new ValidationException("requestParameters");
}
- if(requestParameters == null){
- throw new ValidationException("requestParameters");
- }
return info;
- }
-} \ No newline at end of file
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java
index 937ce19741..2207c52048 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java
@@ -27,53 +27,61 @@ import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.CloudConfiguration;
import org.onap.so.serviceinstancebeans.ModelType;
-public class CloudConfigurationValidation implements ValidationRule{
- public boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
- }
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails().getCloudConfiguration();
- String requestScope = info.getRequestScope();
- int reqVersion = info.getReqVersion();
- Actions action = info.getAction();
- Boolean aLaCarteFlag = info.getALaCarteFlag();
-
- if(!requestScope.equals(ModelType.instanceGroup.toString())){
- if(cloudConfiguration == null && reqVersion >= 5 && (aLaCarteFlag != null && aLaCarteFlag)){
- if((!requestScope.equalsIgnoreCase(ModelType.service.name()) && !requestScope.equalsIgnoreCase(ModelType.configuration.name())) &&
- (action == Action.createInstance || action == Action.deleteInstance || action == Action.updateInstance)){
- throw new ValidationException ("cloudConfiguration");
- }
- if((requestScope.equalsIgnoreCase(ModelType.vnf.name()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name())) &&
- action == Action.replaceInstance){
- throw new ValidationException ("cloudConfiguration");
- }
- if(requestScope.equalsIgnoreCase(ModelType.configuration.name()) &&
- (action == Action.enablePort || action == Action.disablePort || action == Action.activateInstance || action == Action.deactivateInstance)){
- throw new ValidationException ("cloudConfiguration");
- }
- if(requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && (action == Action.deactivateAndCloudDelete || action == Action.scaleOut)){
- throw new ValidationException("cloudConfiguration");
- }
- if(requestScope.equals(ModelType.vnf.name()) && action == Action.recreateInstance){
- throw new ValidationException("cloudConfiguration", true);
- }
- }
- }
-
- if (cloudConfiguration == null && ((aLaCarteFlag != null && !aLaCarteFlag) && requestScope.equalsIgnoreCase (ModelType.service.name ()) && reqVersion < 5)) {
- throw new ValidationException ("cloudConfiguration");
+public class CloudConfigurationValidation implements ValidationRule {
+ public boolean empty(String s) {
+ return (s == null || s.trim().isEmpty());
+ }
+
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails().getCloudConfiguration();
+ String requestScope = info.getRequestScope();
+ int reqVersion = info.getReqVersion();
+ Actions action = info.getAction();
+ Boolean aLaCarteFlag = info.getALaCarteFlag();
+
+ if (!requestScope.equals(ModelType.instanceGroup.toString())) {
+ if (cloudConfiguration == null && reqVersion >= 5 && (aLaCarteFlag != null && aLaCarteFlag)) {
+ if ((!requestScope.equalsIgnoreCase(ModelType.service.name())
+ && !requestScope.equalsIgnoreCase(ModelType.configuration.name()))
+ && (action == Action.createInstance || action == Action.deleteInstance
+ || action == Action.updateInstance)) {
+ throw new ValidationException("cloudConfiguration");
+ }
+ if ((requestScope.equalsIgnoreCase(ModelType.vnf.name())
+ || requestScope.equalsIgnoreCase(ModelType.vfModule.name()))
+ && action == Action.replaceInstance) {
+ throw new ValidationException("cloudConfiguration");
+ }
+ if (requestScope.equalsIgnoreCase(ModelType.configuration.name())
+ && (action == Action.enablePort || action == Action.disablePort
+ || action == Action.activateInstance || action == Action.deactivateInstance)) {
+ throw new ValidationException("cloudConfiguration");
+ }
+ if (requestScope.equalsIgnoreCase(ModelType.vfModule.name())
+ && (action == Action.deactivateAndCloudDelete || action == Action.scaleOut)) {
+ throw new ValidationException("cloudConfiguration");
+ }
+ if (requestScope.equals(ModelType.vnf.name()) && action == Action.recreateInstance) {
+ throw new ValidationException("cloudConfiguration", true);
+ }
+ }
+ }
+
+ if (cloudConfiguration == null && ((aLaCarteFlag != null && !aLaCarteFlag)
+ && requestScope.equalsIgnoreCase(ModelType.service.name()) && reqVersion < 5)) {
+ throw new ValidationException("cloudConfiguration");
}
if (cloudConfiguration != null) {
- if (empty (cloudConfiguration.getLcpCloudRegionId ())) {
- throw new ValidationException ("lcpCloudRegionId");
- }
- if (empty (cloudConfiguration.getTenantId ()) && !(requestScope.equalsIgnoreCase(ModelType.configuration.name()))) {
- throw new ValidationException ("tenantId");
- }
- }
- return info;
- }
-} \ No newline at end of file
+ if (empty(cloudConfiguration.getLcpCloudRegionId())) {
+ throw new ValidationException("lcpCloudRegionId");
+ }
+ if (empty(cloudConfiguration.getTenantId())
+ && !(requestScope.equalsIgnoreCase(ModelType.configuration.name()))) {
+ throw new ValidationException("tenantId");
+ }
+ }
+ return info;
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ConfigurationParametersValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ConfigurationParametersValidation.java
index 8fdb43f20c..158de70309 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ConfigurationParametersValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ConfigurationParametersValidation.java
@@ -23,27 +23,28 @@ package org.onap.so.apihandlerinfra.validation;
import java.util.List;
import java.util.Map;
-
import org.onap.so.apihandlerinfra.Action;
import org.onap.so.apihandlerinfra.Actions;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.ModelType;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
-public class ConfigurationParametersValidation implements ValidationRule{
+public class ConfigurationParametersValidation implements ValidationRule {
private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
+ return (s == null || s.trim().isEmpty());
}
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- ServiceInstancesRequest sir = info.getSir();
- List<Map<String, String>> configParams = sir.getRequestDetails().getConfigurationParameters();
- String requestScope = info.getRequestScope();
- Actions action = info.getAction();
-
- if(configParams.isEmpty() && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut){
- throw new ValidationException("configuration parameters");
- }
+
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ ServiceInstancesRequest sir = info.getSir();
+ List<Map<String, String>> configParams = sir.getRequestDetails().getConfigurationParameters();
+ String requestScope = info.getRequestScope();
+ Actions action = info.getAction();
+
+ if (configParams.isEmpty() && requestScope.equalsIgnoreCase(ModelType.vfModule.name())
+ && action == Action.scaleOut) {
+ throw new ValidationException("configuration parameters");
+ }
return info;
- }
-} \ No newline at end of file
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java
index 0602f09796..01e3de99ec 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java
@@ -25,28 +25,27 @@ package org.onap.so.apihandlerinfra.validation;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.CloudConfiguration;
import org.onap.so.serviceinstancebeans.RequestParameters;
-
import com.google.common.base.Strings;
public class CustomWorkflowValidation implements ValidationRule {
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException {
- RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters();
- CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails().getCloudConfiguration();
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters();
+ CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails().getCloudConfiguration();
- if (cloudConfiguration == null) {
- throw new ValidationException("cloudConfiguration");
- } else if (Strings.isNullOrEmpty((cloudConfiguration.getCloudOwner()))) {
- throw new ValidationException("cloudOwner");
- } else if (Strings.isNullOrEmpty((cloudConfiguration.getLcpCloudRegionId()))) {
- throw new ValidationException("lcpCloudRegionId");
- } else if (Strings.isNullOrEmpty((cloudConfiguration.getTenantId()))) {
- throw new ValidationException("tenantId");
- }
- if (requestParameters == null) {
- throw new ValidationException("requestParameters");
- }
- return info;
- }
+ if (cloudConfiguration == null) {
+ throw new ValidationException("cloudConfiguration");
+ } else if (Strings.isNullOrEmpty((cloudConfiguration.getCloudOwner()))) {
+ throw new ValidationException("cloudOwner");
+ } else if (Strings.isNullOrEmpty((cloudConfiguration.getLcpCloudRegionId()))) {
+ throw new ValidationException("lcpCloudRegionId");
+ } else if (Strings.isNullOrEmpty((cloudConfiguration.getTenantId()))) {
+ throw new ValidationException("tenantId");
+ }
+ if (requestParameters == null) {
+ throw new ValidationException("requestParameters");
+ }
+ return info;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InPlaceSoftwareUpdateValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InPlaceSoftwareUpdateValidation.java
index afbacb465d..6ffd9dcef8 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InPlaceSoftwareUpdateValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InPlaceSoftwareUpdateValidation.java
@@ -26,33 +26,34 @@ import org.onap.so.serviceinstancebeans.CloudConfiguration;
import org.onap.so.serviceinstancebeans.RequestInfo;
import org.onap.so.serviceinstancebeans.RequestParameters;
-public class InPlaceSoftwareUpdateValidation implements ValidationRule{
+public class InPlaceSoftwareUpdateValidation implements ValidationRule {
private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
+ return (s == null || s.trim().isEmpty());
}
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters();
- CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails ().getCloudConfiguration();
- RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo();
- if (cloudConfiguration == null) {
- throw new ValidationException ("cloudConfiguration");
- }else if (empty (cloudConfiguration.getLcpCloudRegionId ())) {
- throw new ValidationException ("lcpCloudRegionId");
- }else if (empty (cloudConfiguration.getTenantId ())) {
- throw new ValidationException ("tenantId");
- }
- if(requestInfo == null){
- throw new ValidationException("requestInfo");
- }else if(empty(requestInfo.getRequestorId())) {
- throw new ValidationException ("requestorId");
- }else if (empty (requestInfo.getSource ())) {
- throw new ValidationException ("source");
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters();
+ CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails().getCloudConfiguration();
+ RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo();
+
+ if (cloudConfiguration == null) {
+ throw new ValidationException("cloudConfiguration");
+ } else if (empty(cloudConfiguration.getLcpCloudRegionId())) {
+ throw new ValidationException("lcpCloudRegionId");
+ } else if (empty(cloudConfiguration.getTenantId())) {
+ throw new ValidationException("tenantId");
+ }
+ if (requestInfo == null) {
+ throw new ValidationException("requestInfo");
+ } else if (empty(requestInfo.getRequestorId())) {
+ throw new ValidationException("requestorId");
+ } else if (empty(requestInfo.getSource())) {
+ throw new ValidationException("source");
+ }
+ if (requestParameters == null) {
+ throw new ValidationException("requestParameters");
}
- if(requestParameters == null){
- throw new ValidationException("requestParameters");
- }
return info;
- }
-} \ No newline at end of file
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java
index fad11a5cc6..907bc942eb 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java
@@ -22,68 +22,67 @@
package org.onap.so.apihandlerinfra.validation;
import java.util.HashMap;
-
import org.onap.so.apihandler.common.CommonConstants;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
import org.onap.so.utils.UUIDChecker;
-public class InstanceIdMapValidation implements ValidationRule{
+public class InstanceIdMapValidation implements ValidationRule {
+
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ HashMap<String, String> instanceIdMap = info.getInstanceIdMap();
+ ServiceInstancesRequest sir = info.getSir();
+ if (instanceIdMap != null) {
+ if (instanceIdMap.get("serviceInstanceId") != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get("serviceInstanceId"))) {
+ throw new ValidationException("serviceInstanceId");
+ }
+ sir.setServiceInstanceId(instanceIdMap.get("serviceInstanceId"));
+ }
+
+ if (instanceIdMap.get("vnfInstanceId") != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get("vnfInstanceId"))) {
+ throw new ValidationException("vnfInstanceId");
+ }
+ sir.setVnfInstanceId(instanceIdMap.get("vnfInstanceId"));
+ }
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- HashMap<String, String> instanceIdMap = info.getInstanceIdMap();
- ServiceInstancesRequest sir = info.getSir();
- if(instanceIdMap != null){
- if(instanceIdMap.get("serviceInstanceId") != null){
- if (!UUIDChecker.isValidUUID (instanceIdMap.get ("serviceInstanceId"))) {
- throw new ValidationException ("serviceInstanceId");
- }
- sir.setServiceInstanceId(instanceIdMap.get("serviceInstanceId"));
- }
+ if (instanceIdMap.get("vfModuleInstanceId") != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get("vfModuleInstanceId"))) {
+ throw new ValidationException("vfModuleInstanceId");
+ }
+ sir.setVfModuleInstanceId(instanceIdMap.get("vfModuleInstanceId"));
+ }
- if(instanceIdMap.get("vnfInstanceId") != null){
- if (!UUIDChecker.isValidUUID (instanceIdMap.get ("vnfInstanceId"))) {
- throw new ValidationException ("vnfInstanceId");
- }
- sir.setVnfInstanceId(instanceIdMap.get("vnfInstanceId"));
- }
+ if (instanceIdMap.get("volumeGroupInstanceId") != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get("volumeGroupInstanceId"))) {
+ throw new ValidationException("volumeGroupInstanceId");
+ }
+ sir.setVolumeGroupInstanceId(instanceIdMap.get("volumeGroupInstanceId"));
+ }
- if(instanceIdMap.get("vfModuleInstanceId") != null){
- if (!UUIDChecker.isValidUUID (instanceIdMap.get ("vfModuleInstanceId"))) {
- throw new ValidationException ("vfModuleInstanceId");
- }
- sir.setVfModuleInstanceId(instanceIdMap.get("vfModuleInstanceId"));
- }
+ if (instanceIdMap.get("networkInstanceId") != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get("networkInstanceId"))) {
+ throw new ValidationException("networkInstanceId");
+ }
+ sir.setNetworkInstanceId(instanceIdMap.get("networkInstanceId"));
+ }
- if(instanceIdMap.get("volumeGroupInstanceId") != null){
- if (!UUIDChecker.isValidUUID (instanceIdMap.get ("volumeGroupInstanceId"))) {
- throw new ValidationException ("volumeGroupInstanceId");
- }
- sir.setVolumeGroupInstanceId(instanceIdMap.get("volumeGroupInstanceId"));
- }
+ if (instanceIdMap.get("configurationInstanceId") != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get("configurationInstanceId"))) {
+ throw new ValidationException("configurationInstanceId");
+ }
+ sir.setConfigurationId(instanceIdMap.get("configurationInstanceId"));
+ }
- if(instanceIdMap.get("networkInstanceId") != null){
- if (!UUIDChecker.isValidUUID (instanceIdMap.get ("networkInstanceId"))) {
- throw new ValidationException ("networkInstanceId");
- }
- sir.setNetworkInstanceId(instanceIdMap.get("networkInstanceId"));
- }
-
- if(instanceIdMap.get("configurationInstanceId") != null){
- if (!UUIDChecker.isValidUUID (instanceIdMap.get ("configurationInstanceId"))) {
- throw new ValidationException ("configurationInstanceId");
- }
- sir.setConfigurationId(instanceIdMap.get("configurationInstanceId"));
- }
-
- if(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null){
- if (!UUIDChecker.isValidUUID (instanceIdMap.get (CommonConstants.INSTANCE_GROUP_INSTANCE_ID))) {
- throw new ValidationException (CommonConstants.INSTANCE_GROUP_INSTANCE_ID, true);
- }
- sir.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID));
- }
+ if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID))) {
+ throw new ValidationException(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, true);
+ }
+ sir.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID));
+ }
}
return info;
- }
-} \ No newline at end of file
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/MembersValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/MembersValidation.java
index 89bb15dcb1..5e38979b89 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/MembersValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/MembersValidation.java
@@ -27,43 +27,44 @@ import org.onap.so.serviceinstancebeans.RelatedInstance;
import org.onap.so.serviceinstancebeans.RelatedInstanceList;
import org.onap.so.serviceinstancebeans.RequestInfo;
-public class MembersValidation implements ValidationRule{
+public class MembersValidation implements ValidationRule {
private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
+ return (s == null || s.trim().isEmpty());
}
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo();
- RelatedInstanceList[] relatedInstanceList = info.getSir().getRequestDetails().getRelatedInstanceList();
- boolean vnfRelatedInstance = false;
-
- if(requestInfo == null){
- throw new ValidationException("requestInfo", true);
- }else if(empty(requestInfo.getRequestorId())) {
- throw new ValidationException ("requestorId", true);
- }else if (empty (requestInfo.getSource ())) {
- throw new ValidationException ("source", true);
+
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo();
+ RelatedInstanceList[] relatedInstanceList = info.getSir().getRequestDetails().getRelatedInstanceList();
+ boolean vnfRelatedInstance = false;
+
+ if (requestInfo == null) {
+ throw new ValidationException("requestInfo", true);
+ } else if (empty(requestInfo.getRequestorId())) {
+ throw new ValidationException("requestorId", true);
+ } else if (empty(requestInfo.getSource())) {
+ throw new ValidationException("source", true);
+ }
+ if (relatedInstanceList == null) {
+ throw new ValidationException("related instances", true);
+ } else {
+ for (RelatedInstanceList instanceList : relatedInstanceList) {
+ RelatedInstance relatedInstance = instanceList.getRelatedInstance();
+ ModelType modelType = relatedInstance.getModelInfo().getModelType();
+ if (empty(relatedInstance.getInstanceId())) {
+ throw new ValidationException("instanceId in relatedInstances", true);
+ }
+ if (modelType == null) {
+ throw new ValidationException("modelType in relatedInstance", true);
+ }
+ if (modelType == ModelType.vnf) {
+ vnfRelatedInstance = true;
+ }
+ }
+ if (!vnfRelatedInstance) {
+ throw new ValidationException("vnf relatedInstance", true);
+ }
}
- if(relatedInstanceList == null){
- throw new ValidationException("related instances", true);
- }else{
- for(RelatedInstanceList instanceList : relatedInstanceList){
- RelatedInstance relatedInstance = instanceList.getRelatedInstance();
- ModelType modelType = relatedInstance.getModelInfo().getModelType();
- if(empty(relatedInstance.getInstanceId())){
- throw new ValidationException("instanceId in relatedInstances", true);
- }
- if (modelType == null) {
- throw new ValidationException("modelType in relatedInstance", true);
- }
- if(modelType == ModelType.vnf){
- vnfRelatedInstance = true;
- }
- }
- if(!vnfRelatedInstance){
- throw new ValidationException("vnf relatedInstance", true);
- }
- }
return info;
- }
-} \ No newline at end of file
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java
index e2a1bdc46a..ecc79c72e8 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java
@@ -29,109 +29,141 @@ import org.onap.so.serviceinstancebeans.ModelInfo;
import org.onap.so.serviceinstancebeans.ModelType;
import org.onap.so.serviceinstancebeans.RequestParameters;
import org.onap.so.utils.UUIDChecker;
-public class ModelInfoValidation implements ValidationRule{
- private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
- }
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- ModelInfo modelInfo = info.getSir().getRequestDetails().getModelInfo();
- RequestParameters requestParameters = info.getReqParameters();
- String requestScope = info.getRequestScope();
- Actions action = info.getAction();
- int reqVersion = info.getReqVersion();
- Boolean aLaCarteFlag = info.getALaCarteFlag();
- if(!requestScope.equals(ModelType.instanceGroup.toString())){
+public class ModelInfoValidation implements ValidationRule {
+ private static boolean empty(String s) {
+ return (s == null || s.trim().isEmpty());
+ }
- if(!empty(modelInfo.getModelNameVersionId())){
- modelInfo.setModelVersionId(modelInfo.getModelNameVersionId());
- }
- // modelCustomizationId is required when usePreLoad is false for v4 and higher for VF Module Create
- if(requestParameters != null && reqVersion >= 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.createInstance && !requestParameters.isUsePreload()) {
- if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) {
- throw new ValidationException("modelCustomizationId");
- }
- }
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ ModelInfo modelInfo = info.getSir().getRequestDetails().getModelInfo();
+ RequestParameters requestParameters = info.getReqParameters();
+ String requestScope = info.getRequestScope();
+ Actions action = info.getAction();
+ int reqVersion = info.getReqVersion();
+ Boolean aLaCarteFlag = info.getALaCarteFlag();
- // modelCustomizationId is required for v5 and higher for VF Module Replace
- if(requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.replaceInstance) {
- if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) {
- throw new ValidationException("modelCustomizationId");
- }
- }
+ if (!requestScope.equals(ModelType.instanceGroup.toString())) {
- // modelCustomizationId or modelCustomizationName are required for VNF Replace
- if(requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.replaceInstance || action == Action.recreateInstance) {
- if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId()) && modelInfo.getModelCustomizationName() == null) {
- throw new ValidationException("modelCustomizationId or modelCustomizationName");
- }
- }
+ if (!empty(modelInfo.getModelNameVersionId())) {
+ modelInfo.setModelVersionId(modelInfo.getModelNameVersionId());
+ }
+ // modelCustomizationId is required when usePreLoad is false for v4 and higher for VF Module Create
+ if (requestParameters != null && reqVersion >= 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name())
+ && action == Action.createInstance && !requestParameters.isUsePreload()) {
+ if (!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) {
+ throw new ValidationException("modelCustomizationId");
+ }
+ }
- //is required for serviceInstance delete macro when aLaCarte=false (v3)
- //create and updates except for network (except v4)
- if (empty (modelInfo.getModelInvariantId ()) && ((reqVersion >2 && (aLaCarteFlag != null && !aLaCarteFlag) && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) ||
- !(reqVersion < 4 && requestScope.equalsIgnoreCase (ModelType.network.name ())) &&
- (action == Action.createInstance || action == Action.updateInstance || action == Action.enablePort || action == Action.disablePort || action == Action.addRelationships || action == Action.removeRelationships ||
- (requestScope.equalsIgnoreCase(ModelType.configuration.name()) && (action == Action.activateInstance || action == Action.deactivateInstance))))) {
- throw new ValidationException ("modelInvariantId");
- }
- if(empty(modelInfo.getModelInvariantId()) && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)){
- throw new ValidationException("modelInvariantId");
- }
- if(empty(modelInfo.getModelInvariantId()) && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)){
- throw new ValidationException("modelInvariantId", true);
- }
- if (!empty (modelInfo.getModelInvariantId ()) && !UUIDChecker.isValidUUID (modelInfo.getModelInvariantId ())) {
- throw new ValidationException ("modelInvariantId format");
- }
+ // modelCustomizationId is required for v5 and higher for VF Module Replace
+ if (requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name())
+ && action == Action.replaceInstance) {
+ if (!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) {
+ throw new ValidationException("modelCustomizationId");
+ }
+ }
- if(reqVersion >= 4 && !(requestScope.equalsIgnoreCase(ModelType.configuration.name())) && empty (modelInfo.getModelName ()) && (action == Action.createInstance || action == Action.updateInstance ||
- action == Action.addRelationships || action == Action.removeRelationships || action == Action.recreateInstance || ((action == Action.deleteInstance || action == Action.scaleOut) && (requestScope.equalsIgnoreCase (ModelType.vfModule.name ()))))){
- throw new ValidationException ("modelName", true);
- }
+ // modelCustomizationId or modelCustomizationName are required for VNF Replace
+ if (requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vnf.name())
+ && action == Action.replaceInstance || action == Action.recreateInstance) {
+ if (!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())
+ && modelInfo.getModelCustomizationName() == null) {
+ throw new ValidationException("modelCustomizationId or modelCustomizationName");
+ }
+ }
- if (empty (modelInfo.getModelVersion ()) && !(requestScope.equalsIgnoreCase(ModelType.configuration.name())) &&
- (!(reqVersion < 4 && requestScope.equalsIgnoreCase (ModelType.network.name ()))
- && (action == Action.createInstance || action == Action.updateInstance || action == Action.addRelationships || action == Action.removeRelationships || action == Action.scaleOut))) {
- throw new ValidationException ("modelVersion");
- }
+ // is required for serviceInstance delete macro when aLaCarte=false (v3)
+ // create and updates except for network (except v4)
+ if (empty(modelInfo.getModelInvariantId()) && ((reqVersion > 2 && (aLaCarteFlag != null && !aLaCarteFlag)
+ && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance)
+ || !(reqVersion < 4 && requestScope.equalsIgnoreCase(ModelType.network.name()))
+ && (action == Action.createInstance || action == Action.updateInstance
+ || action == Action.enablePort || action == Action.disablePort
+ || action == Action.addRelationships || action == Action.removeRelationships
+ || (requestScope.equalsIgnoreCase(ModelType.configuration.name())
+ && (action == Action.activateInstance
+ || action == Action.deactivateInstance))))) {
+ throw new ValidationException("modelInvariantId");
+ }
+ if (empty(modelInfo.getModelInvariantId())
+ && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)) {
+ throw new ValidationException("modelInvariantId");
+ }
+ if (empty(modelInfo.getModelInvariantId())
+ && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)) {
+ throw new ValidationException("modelInvariantId", true);
+ }
+ if (!empty(modelInfo.getModelInvariantId()) && !UUIDChecker.isValidUUID(modelInfo.getModelInvariantId())) {
+ throw new ValidationException("modelInvariantId format");
+ }
- if(empty(modelInfo.getModelVersion()) && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)){
- throw new ValidationException("modelVersion", true);
- }
+ if (reqVersion >= 4 && !(requestScope.equalsIgnoreCase(ModelType.configuration.name()))
+ && empty(modelInfo.getModelName())
+ && (action == Action.createInstance || action == Action.updateInstance
+ || action == Action.addRelationships || action == Action.removeRelationships
+ || action == Action.recreateInstance
+ || ((action == Action.deleteInstance || action == Action.scaleOut)
+ && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()))))) {
+ throw new ValidationException("modelName", true);
+ }
- // is required for serviceInstance delete macro when aLaCarte=false in v4
- if (reqVersion >= 4 && empty (modelInfo.getModelVersionId()) && (((aLaCarteFlag != null && !aLaCarteFlag) && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) ||
- (action == Action.createInstance || action == Action.updateInstance || action == Action.enablePort || action == Action.disablePort || action == Action.addRelationships || action == Action.removeRelationships ||
- (requestScope.equalsIgnoreCase(ModelType.configuration.name()) && (action == Action.activateInstance || action == Action.deactivateInstance))))) {
- throw new ValidationException ("modelVersionId");
- }
- if(empty(modelInfo.getModelVersionId()) && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)){
- throw new ValidationException("modelVersionId", true);
- }
- if(empty(modelInfo.getModelVersionId()) && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)){
- throw new ValidationException("modelVersionId");
- }
+ if (empty(modelInfo.getModelVersion()) && !(requestScope.equalsIgnoreCase(ModelType.configuration.name()))
+ && (!(reqVersion < 4 && requestScope.equalsIgnoreCase(ModelType.network.name()))
+ && (action == Action.createInstance || action == Action.updateInstance
+ || action == Action.addRelationships || action == Action.removeRelationships
+ || action == Action.scaleOut))) {
+ throw new ValidationException("modelVersion");
+ }
- if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action != Action.deleteInstance && empty (modelInfo.getModelCustomizationName ())) {
- if (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) {
- throw new ValidationException ("modelCustomizationId or modelCustomizationName");
- }
- }
+ if (empty(modelInfo.getModelVersion())
+ && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)) {
+ throw new ValidationException("modelVersion", true);
+ }
- if(reqVersion >= 4 && (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) && (requestScope.equalsIgnoreCase (ModelType.network.name ()) || requestScope.equalsIgnoreCase(ModelType.configuration.name()))
- && (action == Action.updateInstance || action == Action.createInstance)){
- throw new ValidationException ("modelCustomizationId");
- }
- if(empty(modelInfo.getModelCustomizationId()) && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut && !(requestParameters.getTestApi() == TestApi.VNF_API.name() && requestParameters.isUsePreload() == true)){
- throw new ValidationException ("modelCustomizationId");
- }
- }else{
- if(empty(modelInfo.getModelVersionId()) && action == Action.createInstance){
- throw new ValidationException("modelVersionId", true);
- }
- }
- return info;
- }
+ // is required for serviceInstance delete macro when aLaCarte=false in v4
+ if (reqVersion >= 4 && empty(modelInfo.getModelVersionId()) && (((aLaCarteFlag != null && !aLaCarteFlag)
+ && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance)
+ || (action == Action.createInstance || action == Action.updateInstance
+ || action == Action.enablePort || action == Action.disablePort
+ || action == Action.addRelationships || action == Action.removeRelationships
+ || (requestScope.equalsIgnoreCase(ModelType.configuration.name())
+ && (action == Action.activateInstance || action == Action.deactivateInstance))))) {
+ throw new ValidationException("modelVersionId");
+ }
+ if (empty(modelInfo.getModelVersionId())
+ && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)) {
+ throw new ValidationException("modelVersionId", true);
+ }
+ if (empty(modelInfo.getModelVersionId())
+ && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)) {
+ throw new ValidationException("modelVersionId");
+ }
+
+ if (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action != Action.deleteInstance
+ && empty(modelInfo.getModelCustomizationName())) {
+ if (!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) {
+ throw new ValidationException("modelCustomizationId or modelCustomizationName");
+ }
+ }
+
+ if (reqVersion >= 4 && (!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId()))
+ && (requestScope.equalsIgnoreCase(ModelType.network.name())
+ || requestScope.equalsIgnoreCase(ModelType.configuration.name()))
+ && (action == Action.updateInstance || action == Action.createInstance)) {
+ throw new ValidationException("modelCustomizationId");
+ }
+ if (empty(modelInfo.getModelCustomizationId()) && requestScope.equalsIgnoreCase(ModelType.vfModule.name())
+ && action == Action.scaleOut && !(requestParameters.getTestApi() == TestApi.VNF_API.name()
+ && requestParameters.isUsePreload() == true)) {
+ throw new ValidationException("modelCustomizationId");
+ }
+ } else {
+ if (empty(modelInfo.getModelVersionId()) && action == Action.createInstance) {
+ throw new ValidationException("modelVersionId", true);
+ }
+ }
+ return info;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java
index 7c51f3e5ce..c80e89e21d 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java
@@ -28,33 +28,34 @@ import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.LineOfBusiness;
import org.onap.so.serviceinstancebeans.Platform;
-public class PlatformLOBValidation implements ValidationRule{
+public class PlatformLOBValidation implements ValidationRule {
private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
+ return (s == null || s.trim().isEmpty());
}
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- int reqVersion = info.getReqVersion();
- Platform platform;
- LineOfBusiness lineOfBusiness;
- String requestScope = info.getRequestScope();
- Actions action = info.getAction();
-
- platform = info.getSir().getRequestDetails().getPlatform();
- lineOfBusiness = info.getSir().getRequestDetails().getLineOfBusiness();
- if(reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance){
- if(reqVersion > 5 && platform == null) {
- throw new ValidationException("platform");
- }
- if(platform != null && empty(platform.getPlatformName())){
- throw new ValidationException("platformName");
- }
- if(lineOfBusiness != null && empty(lineOfBusiness.getLineOfBusinessName())){
- throw new ValidationException("lineOfBusinessName");
+
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ int reqVersion = info.getReqVersion();
+ Platform platform;
+ LineOfBusiness lineOfBusiness;
+ String requestScope = info.getRequestScope();
+ Actions action = info.getAction();
+
+ platform = info.getSir().getRequestDetails().getPlatform();
+ lineOfBusiness = info.getSir().getRequestDetails().getLineOfBusiness();
+ if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance) {
+ if (reqVersion > 5 && platform == null) {
+ throw new ValidationException("platform");
+ }
+ if (platform != null && empty(platform.getPlatformName())) {
+ throw new ValidationException("platformName");
}
- }
+ if (lineOfBusiness != null && empty(lineOfBusiness.getLineOfBusinessName())) {
+ throw new ValidationException("lineOfBusinessName");
+ }
+ }
info.setPlatform(platform);
info.setLOB(lineOfBusiness);
return info;
- }
-} \ No newline at end of file
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java
index f6a3c03555..60e1274469 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java
@@ -28,33 +28,35 @@ import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.OwningEntity;
import org.onap.so.serviceinstancebeans.Project;
-public class ProjectOwningEntityValidation implements ValidationRule{
+public class ProjectOwningEntityValidation implements ValidationRule {
private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
+ return (s == null || s.trim().isEmpty());
}
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- int reqVersion = info.getReqVersion();
- Project project;
- OwningEntity owningEntity;
- String requestScope = info.getRequestScope();
- Actions action = info.getAction();
-
- project = info.getSir().getRequestDetails().getProject();
- owningEntity = info.getSir().getRequestDetails().getOwningEntity();
- if(reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.createInstance || action == Action.assignInstance){
- if(reqVersion > 5 && owningEntity == null) {
- throw new ValidationException("owningEntity");
- }
- if(owningEntity != null && empty(owningEntity.getOwningEntityId())){
- throw new ValidationException("owningEntityId");
- }
- if(project != null && empty(project.getProjectName())){
- throw new ValidationException("projectName");
- }
- }
- info.setProject(project);
- info.setOE(owningEntity);
+
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ int reqVersion = info.getReqVersion();
+ Project project;
+ OwningEntity owningEntity;
+ String requestScope = info.getRequestScope();
+ Actions action = info.getAction();
+
+ project = info.getSir().getRequestDetails().getProject();
+ owningEntity = info.getSir().getRequestDetails().getOwningEntity();
+ if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.service.name())
+ && action == Action.createInstance || action == Action.assignInstance) {
+ if (reqVersion > 5 && owningEntity == null) {
+ throw new ValidationException("owningEntity");
+ }
+ if (owningEntity != null && empty(owningEntity.getOwningEntityId())) {
+ throw new ValidationException("owningEntityId");
+ }
+ if (project != null && empty(project.getProjectName())) {
+ throw new ValidationException("projectName");
+ }
+ }
+ info.setProject(project);
+ info.setOE(owningEntity);
return info;
- }
-} \ No newline at end of file
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java
index 5eb3083003..b02bd95d97 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java
@@ -37,214 +37,238 @@ import org.onap.so.utils.UUIDChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class RelatedInstancesValidation implements ValidationRule{
-
- private static Logger logger = LoggerFactory.getLogger(RelatedInstancesValidation.class);
-
- private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
- }
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- ServiceInstancesRequest sir = info.getSir();
- Actions action = info.getAction();
- int reqVersion = info.getReqVersion();
- String requestScope = info.getRequestScope();
- String serviceInstanceType = null;
- String networkType = null;
- String vnfType = null;
- String vfModuleType = null;
- String vfModuleModelName = null;
- ModelInfo modelInfo = info.getSir().getRequestDetails().getModelInfo();
- RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
- String serviceModelName = null;
+public class RelatedInstancesValidation implements ValidationRule {
+
+ private static Logger logger = LoggerFactory.getLogger(RelatedInstancesValidation.class);
+
+ private static boolean empty(String s) {
+ return (s == null || s.trim().isEmpty());
+ }
+
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ ServiceInstancesRequest sir = info.getSir();
+ Actions action = info.getAction();
+ int reqVersion = info.getReqVersion();
+ String requestScope = info.getRequestScope();
+ String serviceInstanceType = null;
+ String networkType = null;
+ String vnfType = null;
+ String vfModuleType = null;
+ String vfModuleModelName = null;
+ ModelInfo modelInfo = info.getSir().getRequestDetails().getModelInfo();
+ RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
+ String serviceModelName = null;
String vnfModelName = null;
String asdcServiceModelVersion = null;
String volumeGroupId = null;
boolean isRelatedServiceInstancePresent = false;
boolean isRelatedVnfInstancePresent = false;
- boolean isSourceVnfPresent = false;
- boolean isDestinationVnfPresent = false;
- boolean isConnectionPointPresent = false;
-
- if(requestScope.equalsIgnoreCase(ModelType.service.name())){
- serviceInstanceType = modelInfo.getModelName();
- info.setServiceInstanceType(serviceInstanceType);
- }
- if(requestScope.equalsIgnoreCase(ModelType.network.name())){
- networkType = modelInfo.getModelName();
- info.setNetworkType(networkType);
- }
- if (instanceList != null) {
- for(RelatedInstanceList relatedInstanceList : instanceList){
- RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
-
- ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo ();
- if (relatedInstanceModelInfo == null) {
- throw new ValidationException ("modelInfo in relatedInstance");
- }
-
- if (relatedInstanceModelInfo.getModelType () == null) {
- throw new ValidationException ("modelType in relatedInstance");
- }
-
- if(empty(relatedInstance.getInstanceName ()) && ModelType.pnf.equals(relatedInstanceModelInfo.getModelType())) {
- throw new ValidationException ("instanceName in relatedInstance for pnf modelType");
- }
-
- if (!empty (relatedInstance.getInstanceName ())) {
- if (!relatedInstance.getInstanceName ().matches (Constants.VALID_INSTANCE_NAME_FORMAT)) {
- throw new ValidationException ("instanceName format in relatedInstance");
- }
- }
-
- if (empty (relatedInstance.getInstanceId ()) && !ModelType.pnf.equals(relatedInstanceModelInfo.getModelType())) {
- throw new ValidationException ("instanceId in relatedInstance");
- }
-
- if (!empty(relatedInstance.getInstanceId ()) && !UUIDChecker.isValidUUID (relatedInstance.getInstanceId ())) {
- throw new ValidationException ("instanceId format in relatedInstance");
- }
- if(empty(relatedInstanceModelInfo.getModelVersionId()) && requestScope.equals(ModelType.instanceGroup.toString()) && relatedInstanceModelInfo.getModelType().equals(ModelType.service)){
- throw new ValidationException("modelVersionId in relatedInstance", true);
- }
- if(requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString()) && relatedInstanceModelInfo.getModelType().equals(ModelType.service)){
- isRelatedServiceInstancePresent = true;
- }
-
- if (action != Action.deleteInstance && !requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) {
- if(!( relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup) ||
- relatedInstanceModelInfo.getModelType().equals(ModelType.connectionPoint) ||
- relatedInstanceModelInfo.getModelType().equals(ModelType.pnf) ||
- relatedInstanceModelInfo.getModelType().equals(ModelType.networkInstanceGroup))) {
-
- if(empty (relatedInstanceModelInfo.getModelInvariantId ())) {
- throw new ValidationException ("modelInvariantId in relatedInstance");
- } else if(reqVersion >= 4 && empty(relatedInstanceModelInfo.getModelVersionId ())) {
- throw new ValidationException("modelVersionId in relatedInstance");
- } else if(empty(relatedInstanceModelInfo.getModelName ())) {
- throw new ValidationException ("modelName in relatedInstance");
- } else if (empty (relatedInstanceModelInfo.getModelVersion ())) {
- throw new ValidationException ("modelVersion in relatedInstance");
- }
- }
-
- if (!empty (relatedInstanceModelInfo.getModelInvariantId ()) &&
- !UUIDChecker.isValidUUID (relatedInstanceModelInfo.getModelInvariantId ())) {
- throw new ValidationException ("modelInvariantId format in relatedInstance");
- }
-
- if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
- if(InstanceDirection.source.equals(relatedInstance.getInstanceDirection()) && relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
- isSourceVnfPresent = true;
- } else if(InstanceDirection.destination.equals(relatedInstance.getInstanceDirection()) &&
- (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) || (relatedInstanceModelInfo.getModelType().equals(ModelType.pnf)))) {
- isDestinationVnfPresent = true;
- }
- }
-
- if(ModelType.connectionPoint.equals(relatedInstanceModelInfo.getModelType()) && ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
- isConnectionPointPresent = true;
- }
- }
-
- if (empty (relatedInstanceModelInfo.getModelCustomizationName ()) && relatedInstanceModelInfo.getModelType ().equals (ModelType.vnf) ) {
- if(reqVersion >=4 && empty (relatedInstanceModelInfo.getModelCustomizationId()) && action != Action.deleteInstance) {
- throw new ValidationException ("modelCustomizationName or modelCustomizationId in relatedInstance of vnf");
- }
- }
-
- if(relatedInstanceModelInfo.getModelType().equals(ModelType.service) && !(requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString()) && action == Action.createInstance)) {
- isRelatedServiceInstancePresent = true;
- if (!relatedInstance.getInstanceId ().equals (sir.getServiceInstanceId ())) {
- throw new ValidationException ("serviceInstanceId matching the serviceInstanceId in request URI");
- }
- serviceModelName = relatedInstanceModelInfo.getModelName ();
- asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion ();
- } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) {
- isRelatedVnfInstancePresent = true;
- if (!relatedInstance.getInstanceId ().equals (sir.getVnfInstanceId ())) {
- throw new ValidationException ("vnfInstanceId matching the vnfInstanceId in request URI");
- }
- vnfModelName = relatedInstanceModelInfo.getModelCustomizationName();
- } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) {
- volumeGroupId = relatedInstance.getInstanceId ();
- }
- }
-
- if(action == Action.createInstance && ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
- if(!isSourceVnfPresent) {
- throw new ValidationException ("source vnf relatedInstance for Port Configuration");
- }
-
- if(!isDestinationVnfPresent) {
- throw new ValidationException ("destination vnf relatedInstance for Port Configuration");
- }
- }
-
- if((action == Action.enablePort || action == Action.disablePort) && ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
- if(!isConnectionPointPresent) {
- throw new ValidationException ("connectionPoint relatedInstance for Port Configuration");
- }
- }
- if(requestScope.equals(ModelType.instanceGroup.toString())){
- if(!isRelatedServiceInstancePresent){
- throw new ValidationException("related service instance for instanceGroup request", true);
- }
- }
- if(requestScope.equalsIgnoreCase (ModelType.volumeGroup.name ())) {
- if (!isRelatedServiceInstancePresent) {
- throw new ValidationException ("related service instance for volumeGroup request");
- }
- if (!isRelatedVnfInstancePresent) {
- throw new ValidationException ("related vnf instance for volumeGroup request");
- }
- serviceInstanceType = serviceModelName;
- vnfType = serviceModelName + "/" + vnfModelName;
- info.setServiceInstanceType(serviceInstanceType);
- info.setVnfType(vnfType);
- }
- else if(requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) {
- if (!isRelatedServiceInstancePresent) {
- throw new ValidationException ("related service instance for vfModule request");
- }
- if (!isRelatedVnfInstancePresent) {
- throw new ValidationException ("related vnf instance for vfModule request");
- }
- vfModuleModelName = modelInfo.getModelName ();
- serviceInstanceType = serviceModelName;
- vnfType = serviceModelName + "/" + vnfModelName;
- vfModuleType = vnfType + "::" + vfModuleModelName;
- sir.setVolumeGroupInstanceId (volumeGroupId);
- info.setVfModuleModelName(vfModuleModelName);
- info.setVnfType(vnfType);
- info.setServiceInstanceType(serviceInstanceType);
- info.setVfModuleType(vfModuleType);
- }
- else if (requestScope.equalsIgnoreCase (ModelType.vnf.name ())) {
- if (!isRelatedServiceInstancePresent) {
- throw new ValidationException ("related service instance for vnf request");
- }
- vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName();
- info.setVnfType(vnfType);
- }
+ boolean isSourceVnfPresent = false;
+ boolean isDestinationVnfPresent = false;
+ boolean isConnectionPointPresent = false;
+
+ if (requestScope.equalsIgnoreCase(ModelType.service.name())) {
+ serviceInstanceType = modelInfo.getModelName();
+ info.setServiceInstanceType(serviceInstanceType);
+ }
+ if (requestScope.equalsIgnoreCase(ModelType.network.name())) {
+ networkType = modelInfo.getModelName();
+ info.setNetworkType(networkType);
+ }
+ if (instanceList != null) {
+ for (RelatedInstanceList relatedInstanceList : instanceList) {
+ RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
+
+ ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo();
+ if (relatedInstanceModelInfo == null) {
+ throw new ValidationException("modelInfo in relatedInstance");
+ }
+
+ if (relatedInstanceModelInfo.getModelType() == null) {
+ throw new ValidationException("modelType in relatedInstance");
+ }
+
+ if (empty(relatedInstance.getInstanceName())
+ && ModelType.pnf.equals(relatedInstanceModelInfo.getModelType())) {
+ throw new ValidationException("instanceName in relatedInstance for pnf modelType");
+ }
+
+ if (!empty(relatedInstance.getInstanceName())) {
+ if (!relatedInstance.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) {
+ throw new ValidationException("instanceName format in relatedInstance");
+ }
+ }
+
+ if (empty(relatedInstance.getInstanceId())
+ && !ModelType.pnf.equals(relatedInstanceModelInfo.getModelType())) {
+ throw new ValidationException("instanceId in relatedInstance");
+ }
+
+ if (!empty(relatedInstance.getInstanceId())
+ && !UUIDChecker.isValidUUID(relatedInstance.getInstanceId())) {
+ throw new ValidationException("instanceId format in relatedInstance");
+ }
+ if (empty(relatedInstanceModelInfo.getModelVersionId())
+ && requestScope.equals(ModelType.instanceGroup.toString())
+ && relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
+ throw new ValidationException("modelVersionId in relatedInstance", true);
+ }
+ if (requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())
+ && relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
+ isRelatedServiceInstancePresent = true;
+ }
+
+ if (action != Action.deleteInstance
+ && !requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) {
+ if (!(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)
+ || relatedInstanceModelInfo.getModelType().equals(ModelType.connectionPoint)
+ || relatedInstanceModelInfo.getModelType().equals(ModelType.pnf)
+ || relatedInstanceModelInfo.getModelType().equals(ModelType.networkInstanceGroup))) {
+
+ if (empty(relatedInstanceModelInfo.getModelInvariantId())) {
+ throw new ValidationException("modelInvariantId in relatedInstance");
+ } else if (reqVersion >= 4 && empty(relatedInstanceModelInfo.getModelVersionId())) {
+ throw new ValidationException("modelVersionId in relatedInstance");
+ } else if (empty(relatedInstanceModelInfo.getModelName())) {
+ throw new ValidationException("modelName in relatedInstance");
+ } else if (empty(relatedInstanceModelInfo.getModelVersion())) {
+ throw new ValidationException("modelVersion in relatedInstance");
+ }
+ }
+
+ if (!empty(relatedInstanceModelInfo.getModelInvariantId())
+ && !UUIDChecker.isValidUUID(relatedInstanceModelInfo.getModelInvariantId())) {
+ throw new ValidationException("modelInvariantId format in relatedInstance");
+ }
+
+ if (ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
+ if (InstanceDirection.source.equals(relatedInstance.getInstanceDirection())
+ && relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
+ isSourceVnfPresent = true;
+ } else if (InstanceDirection.destination.equals(relatedInstance.getInstanceDirection())
+ && (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)
+ || (relatedInstanceModelInfo.getModelType().equals(ModelType.pnf)))) {
+ isDestinationVnfPresent = true;
+ }
+ }
+
+ if (ModelType.connectionPoint.equals(relatedInstanceModelInfo.getModelType())
+ && ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
+ isConnectionPointPresent = true;
+ }
+ }
+
+ if (empty(relatedInstanceModelInfo.getModelCustomizationName())
+ && relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
+ if (reqVersion >= 4 && empty(relatedInstanceModelInfo.getModelCustomizationId())
+ && action != Action.deleteInstance) {
+ throw new ValidationException(
+ "modelCustomizationName or modelCustomizationId in relatedInstance of vnf");
+ }
+ }
+
+ if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)
+ && !(requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())
+ && action == Action.createInstance)) {
+ isRelatedServiceInstancePresent = true;
+ if (!relatedInstance.getInstanceId().equals(sir.getServiceInstanceId())) {
+ throw new ValidationException(
+ "serviceInstanceId matching the serviceInstanceId in request URI");
+ }
+ serviceModelName = relatedInstanceModelInfo.getModelName();
+ asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion();
+ } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)
+ && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) {
+ isRelatedVnfInstancePresent = true;
+ if (!relatedInstance.getInstanceId().equals(sir.getVnfInstanceId())) {
+ throw new ValidationException("vnfInstanceId matching the vnfInstanceId in request URI");
+ }
+ vnfModelName = relatedInstanceModelInfo.getModelCustomizationName();
+ } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) {
+ volumeGroupId = relatedInstance.getInstanceId();
+ }
+ }
+
+ if (action == Action.createInstance && ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
+ if (!isSourceVnfPresent) {
+ throw new ValidationException("source vnf relatedInstance for Port Configuration");
+ }
+
+ if (!isDestinationVnfPresent) {
+ throw new ValidationException("destination vnf relatedInstance for Port Configuration");
+ }
+ }
+
+ if ((action == Action.enablePort || action == Action.disablePort)
+ && ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
+ if (!isConnectionPointPresent) {
+ throw new ValidationException("connectionPoint relatedInstance for Port Configuration");
+ }
+ }
+ if (requestScope.equals(ModelType.instanceGroup.toString())) {
+ if (!isRelatedServiceInstancePresent) {
+ throw new ValidationException("related service instance for instanceGroup request", true);
+ }
+ }
+ if (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name())) {
+ if (!isRelatedServiceInstancePresent) {
+ throw new ValidationException("related service instance for volumeGroup request");
+ }
+ if (!isRelatedVnfInstancePresent) {
+ throw new ValidationException("related vnf instance for volumeGroup request");
+ }
+ serviceInstanceType = serviceModelName;
+ vnfType = serviceModelName + "/" + vnfModelName;
+ info.setServiceInstanceType(serviceInstanceType);
+ info.setVnfType(vnfType);
+ } else if (requestScope.equalsIgnoreCase(ModelType.vfModule.name())) {
+ if (!isRelatedServiceInstancePresent) {
+ throw new ValidationException("related service instance for vfModule request");
+ }
+ if (!isRelatedVnfInstancePresent) {
+ throw new ValidationException("related vnf instance for vfModule request");
+ }
+ vfModuleModelName = modelInfo.getModelName();
+ serviceInstanceType = serviceModelName;
+ vnfType = serviceModelName + "/" + vnfModelName;
+ vfModuleType = vnfType + "::" + vfModuleModelName;
+ sir.setVolumeGroupInstanceId(volumeGroupId);
+ info.setVfModuleModelName(vfModuleModelName);
+ info.setVnfType(vnfType);
+ info.setServiceInstanceType(serviceInstanceType);
+ info.setVfModuleType(vfModuleType);
+ } else if (requestScope.equalsIgnoreCase(ModelType.vnf.name())) {
+ if (!isRelatedServiceInstancePresent) {
+ throw new ValidationException("related service instance for vnf request");
+ }
+ vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName();
+ info.setVnfType(vnfType);
+ }
+ } else if (((requestScope.equalsIgnoreCase(ModelType.vnf.name())
+ || requestScope.equalsIgnoreCase(ModelType.volumeGroup.name())
+ || requestScope.equalsIgnoreCase(ModelType.vfModule.name())
+ || requestScope.equalsIgnoreCase(ModelType.configuration.name()))
+ && (action == Action.createInstance || action == Action.enablePort || action == Action.disablePort))
+ || (reqVersion >= 4
+ && (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name())
+ || requestScope.equalsIgnoreCase(ModelType.vfModule.name()))
+ && action == Action.updateInstance
+ || (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut))
+ || (requestScope.equalsIgnoreCase(ModelType.service.name())
+ && (action.equals(Action.addRelationships) || action.equals(Action.removeRelationships)))) {
+ logger.debug("related instance exception");
+ throw new ValidationException("related instances");
}
- else if ((( requestScope.equalsIgnoreCase(ModelType.vnf.name ()) || requestScope.equalsIgnoreCase(ModelType.volumeGroup.name ()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name ())
- || requestScope.equalsIgnoreCase(ModelType.configuration.name())) && (action == Action.createInstance || action == Action.enablePort || action == Action.disablePort)) ||
- (reqVersion >= 4 && (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name ()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) && action == Action.updateInstance ||
- (requestScope.equalsIgnoreCase(ModelType.vfModule.name ()) && action == Action.scaleOut)) ||
- (requestScope.equalsIgnoreCase(ModelType.service.name()) && (action.equals(Action.addRelationships) || action.equals(Action.removeRelationships)))){
- logger.debug("related instance exception");
- throw new ValidationException ("related instances");
+ if (instanceList == null && requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())
+ && action == Action.createInstance) {
+ throw new ValidationException("relatedInstanceList", true);
}
- if(instanceList == null && requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString()) && action == Action.createInstance){
- throw new ValidationException("relatedInstanceList", true);
- }
- info.setVfModuleModelName(vfModuleModelName);
- info.setServiceInstanceType(serviceInstanceType);
- info.setVnfType(vnfType);
- info.setAsdcServiceModelVersion(asdcServiceModelVersion);
- info.setVfModuleType(vfModuleType);
- return info;
- }
+ info.setVfModuleModelName(vfModuleModelName);
+ info.setServiceInstanceType(serviceInstanceType);
+ info.setVnfType(vnfType);
+ info.setAsdcServiceModelVersion(asdcServiceModelVersion);
+ info.setVfModuleType(vfModuleType);
+ return info;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestInfoValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestInfoValidation.java
index bdc9649ecc..483c9db81b 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestInfoValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestInfoValidation.java
@@ -28,40 +28,44 @@ import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.ModelType;
import org.onap.so.serviceinstancebeans.RequestInfo;
-public class RequestInfoValidation implements ValidationRule{
+public class RequestInfoValidation implements ValidationRule {
private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
+ return (s == null || s.trim().isEmpty());
}
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo();
- int reqVersion = info.getReqVersion();
- String requestScope = info.getRequestScope();
- Actions action = info.getAction();
- Boolean aLaCarteFlag = info.getALaCarteFlag();
-
- //required for all operations in V4
- if(empty(requestInfo.getRequestorId()) && reqVersion >= 4) {
- throw new ValidationException ("requestorId");
+
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo();
+ int reqVersion = info.getReqVersion();
+ String requestScope = info.getRequestScope();
+ Actions action = info.getAction();
+ Boolean aLaCarteFlag = info.getALaCarteFlag();
+
+ // required for all operations in V4
+ if (empty(requestInfo.getRequestorId()) && reqVersion >= 4) {
+ throw new ValidationException("requestorId");
}
- if (empty (requestInfo.getSource ())) {
- throw new ValidationException ("source");
+ if (empty(requestInfo.getSource())) {
+ throw new ValidationException("source");
}
- if (!empty (requestInfo.getInstanceName ())) {
- if (!requestInfo.getInstanceName ().matches (Constants.VALID_INSTANCE_NAME_FORMAT)) {
- throw new ValidationException ("instanceName format");
- }
+ if (!empty(requestInfo.getInstanceName())) {
+ if (!requestInfo.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) {
+ throw new ValidationException("instanceName format");
+ }
}
- if (empty (requestInfo.getProductFamilyId ())) {
- // Mandatory for vnf Create(aLaCarte=true), Network Create(aLaCarte=true) and network update
- //Mandatory for macro request create service instance
- if((requestScope.equalsIgnoreCase (ModelType.vnf.name ()) && action == Action.createInstance) ||
- (requestScope.equalsIgnoreCase (ModelType.network.name ()) && (action == Action.createInstance || action == Action.updateInstance)) ||
- (reqVersion > 3 && (aLaCarteFlag != null && !aLaCarteFlag) && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.createInstance)) {
- throw new ValidationException ("productFamilyId");
- }
+ if (empty(requestInfo.getProductFamilyId())) {
+ // Mandatory for vnf Create(aLaCarte=true), Network Create(aLaCarte=true) and network update
+ // Mandatory for macro request create service instance
+ if ((requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance)
+ || (requestScope.equalsIgnoreCase(ModelType.network.name())
+ && (action == Action.createInstance || action == Action.updateInstance))
+ || (reqVersion > 3 && (aLaCarteFlag != null && !aLaCarteFlag)
+ && requestScope.equalsIgnoreCase(ModelType.service.name())
+ && action == Action.createInstance)) {
+ throw new ValidationException("productFamilyId");
+ }
}
return info;
- }
-} \ No newline at end of file
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidation.java
index 8e1a6f5d35..edf48227f1 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidation.java
@@ -27,99 +27,98 @@ import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.ModelType;
import org.onap.so.serviceinstancebeans.RequestParameters;
-public class RequestParametersValidation implements ValidationRule{
- private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
+public class RequestParametersValidation implements ValidationRule {
+ private static boolean empty(String s) {
+ return (s == null || s.trim().isEmpty());
}
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- int reqVersion = info.getReqVersion();
- String requestScope = info.getRequestScope();
- Actions action = info.getAction();
- RequestParameters requestParameters = info.getReqParameters();
-
- if (requestScope.equalsIgnoreCase(ModelType.service.name()) && (action == Action.createInstance || action == Action.assignInstance)) {
- if (requestParameters == null) {
- throw new ValidationException ("requestParameters");
- }
- if (empty (requestParameters.getSubscriptionServiceType())) {
- throw new ValidationException ("subscriptionServiceType");
- }
+
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ int reqVersion = info.getReqVersion();
+ String requestScope = info.getRequestScope();
+ Actions action = info.getAction();
+ RequestParameters requestParameters = info.getReqParameters();
+
+ if (requestScope.equalsIgnoreCase(ModelType.service.name())
+ && (action == Action.createInstance || action == Action.assignInstance)) {
+ if (requestParameters == null) {
+ throw new ValidationException("requestParameters");
+ }
+ if (empty(requestParameters.getSubscriptionServiceType())) {
+ throw new ValidationException("subscriptionServiceType");
+ }
}
- if(reqVersion >= 4){
- if(Action.addRelationships.equals(action) || Action.removeRelationships.equals(action)) {
- if(requestParameters == null || requestParameters.getALaCarte() == null) {
- throw new ValidationException ("aLaCarte in requestParameters");
- }
- }
+ if (reqVersion >= 4) {
+ if (Action.addRelationships.equals(action) || Action.removeRelationships.equals(action)) {
+ if (requestParameters == null || requestParameters.getALaCarte() == null) {
+ throw new ValidationException("aLaCarte in requestParameters");
+ }
+ }
}
- if(requestParameters == null && !requestScope.equalsIgnoreCase(ModelType.service.name())){
- info.setALaCarteFlag(true);
- }
- if(requestParameters != null){
- if(requestScope.equalsIgnoreCase(ModelType.vnf.name())){
- if(action == Action.updateInstance){
- if(requestParameters.isUsePreload() == null){
- requestParameters.setUsePreload(true);
- }
- }
- if(action == Action.replaceInstance){
- if(requestParameters.getRebuildVolumeGroups() == null){
- requestParameters.setRebuildVolumeGroups(false);
- }
- }
- }
- if(requestScope.equalsIgnoreCase(ModelType.vfModule.name())){
- if(action == Action.createInstance || action == Action.updateInstance){
- if(requestParameters.isUsePreload() == null){
- if(reqVersion >= 4){
- if (requestParameters.getALaCarte() == null || requestParameters.getALaCarte() == true) {
- requestParameters.setUsePreload(true);
- }
- else {
- requestParameters.setUsePreload(false);
- }
- }
- else {
- requestParameters.setUsePreload(true);
- }
- }
- }
- }
- if(requestScope.equalsIgnoreCase(ModelType.service.name())){
- if(action == Action.createInstance){
- if(requestParameters.isUsePreload() == null){
- if(reqVersion >= 4){
- if (requestParameters.getALaCarte() == null || requestParameters.getALaCarte() == false) {
- requestParameters.setUsePreload(false);
- }
- else {
- requestParameters.setUsePreload(true);
- }
- }
- else {
- requestParameters.setUsePreload(true);
- }
- }
- }
- }
- if(reqVersion >= 4){
- if(requestParameters.getALaCarte() != null){
- info.setALaCarteFlag(requestParameters.getALaCarte());
- }else if(requestScope.equalsIgnoreCase(ModelType.service.name())){
- if(action == Action.createInstance || action == Action.deleteInstance || action == Action.activateInstance || action == Action.deactivateInstance){
- if(requestParameters.getALaCarte() == null){
- requestParameters.setaLaCarte(false);
- info.setALaCarteFlag(requestParameters.getALaCarte());
- }
- }
- }else{
- info.setALaCarteFlag(true);
- }
- }else{
- info.setALaCarteFlag(true);
- }
+ if (requestParameters == null && !requestScope.equalsIgnoreCase(ModelType.service.name())) {
+ info.setALaCarteFlag(true);
}
- return info;
- }
-} \ No newline at end of file
+ if (requestParameters != null) {
+ if (requestScope.equalsIgnoreCase(ModelType.vnf.name())) {
+ if (action == Action.updateInstance) {
+ if (requestParameters.isUsePreload() == null) {
+ requestParameters.setUsePreload(true);
+ }
+ }
+ if (action == Action.replaceInstance) {
+ if (requestParameters.getRebuildVolumeGroups() == null) {
+ requestParameters.setRebuildVolumeGroups(false);
+ }
+ }
+ }
+ if (requestScope.equalsIgnoreCase(ModelType.vfModule.name())) {
+ if (action == Action.createInstance || action == Action.updateInstance) {
+ if (requestParameters.isUsePreload() == null) {
+ if (reqVersion >= 4) {
+ if (requestParameters.getALaCarte() == null || requestParameters.getALaCarte() == true) {
+ requestParameters.setUsePreload(true);
+ } else {
+ requestParameters.setUsePreload(false);
+ }
+ } else {
+ requestParameters.setUsePreload(true);
+ }
+ }
+ }
+ }
+ if (requestScope.equalsIgnoreCase(ModelType.service.name())) {
+ if (action == Action.createInstance) {
+ if (requestParameters.isUsePreload() == null) {
+ if (reqVersion >= 4) {
+ if (requestParameters.getALaCarte() == null || requestParameters.getALaCarte() == false) {
+ requestParameters.setUsePreload(false);
+ } else {
+ requestParameters.setUsePreload(true);
+ }
+ } else {
+ requestParameters.setUsePreload(true);
+ }
+ }
+ }
+ }
+ if (reqVersion >= 4) {
+ if (requestParameters.getALaCarte() != null) {
+ info.setALaCarteFlag(requestParameters.getALaCarte());
+ } else if (requestScope.equalsIgnoreCase(ModelType.service.name())) {
+ if (action == Action.createInstance || action == Action.deleteInstance
+ || action == Action.activateInstance || action == Action.deactivateInstance) {
+ if (requestParameters.getALaCarte() == null) {
+ requestParameters.setaLaCarte(false);
+ info.setALaCarteFlag(requestParameters.getALaCarte());
+ }
+ }
+ } else {
+ info.setALaCarteFlag(true);
+ }
+ } else {
+ info.setALaCarteFlag(true);
+ }
+ }
+ return info;
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestScopeValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestScopeValidation.java
index 51a9afe200..635a715558 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestScopeValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestScopeValidation.java
@@ -25,25 +25,25 @@ import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.ModelInfo;
import org.onap.so.serviceinstancebeans.RequestInfo;
-public class RequestScopeValidation implements ValidationRule{
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- ModelInfo modelInfo = info.getSir().getRequestDetails().getModelInfo();
- RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo();
- String requestScope;
-
+public class RequestScopeValidation implements ValidationRule {
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ ModelInfo modelInfo = info.getSir().getRequestDetails().getModelInfo();
+ RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo();
+ String requestScope;
+
if (modelInfo == null) {
- throw new ValidationException ("model-info");
+ throw new ValidationException("model-info");
+ }
+ if (requestInfo == null) {
+ throw new ValidationException("requestInfo");
}
- if (requestInfo == null) {
- throw new ValidationException ("requestInfo");
- }
- info.setRequestInfo(requestInfo);
- if (modelInfo.getModelType () == null) {
- throw new ValidationException ("modelType");
+ info.setRequestInfo(requestInfo);
+ if (modelInfo.getModelType() == null) {
+ throw new ValidationException("modelType");
}
requestScope = info.getSir().getRequestDetails().getModelInfo().getModelType().name();
info.setRequestScope(requestScope);
return info;
- }
-} \ No newline at end of file
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/SubscriberInfoValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/SubscriberInfoValidation.java
index d9298f5f4e..4f68ef319c 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/SubscriberInfoValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/SubscriberInfoValidation.java
@@ -27,25 +27,27 @@ import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.ModelType;
import org.onap.so.serviceinstancebeans.SubscriberInfo;
-public class SubscriberInfoValidation implements ValidationRule{
+public class SubscriberInfoValidation implements ValidationRule {
private static boolean empty(String s) {
- return (s == null || s.trim().isEmpty());
+ return (s == null || s.trim().isEmpty());
}
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- String requestScope = info.getRequestScope();
- int reqVersion = info.getReqVersion();
- Actions action = info.getAction();
-
- if (reqVersion > 4 && requestScope.equalsIgnoreCase (ModelType.service.name ()) && action == Action.createInstance || action == Action.assignInstance) {
- SubscriberInfo subscriberInfo = info.getSir().getRequestDetails ().getSubscriberInfo();
- if (subscriberInfo == null) {
- throw new ValidationException ("subscriberInfo");
- }
- if (empty (subscriberInfo.getGlobalSubscriberId ())) {
- throw new ValidationException ("globalSubscriberId");
- }
+
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ String requestScope = info.getRequestScope();
+ int reqVersion = info.getReqVersion();
+ Actions action = info.getAction();
+
+ if (reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.createInstance
+ || action == Action.assignInstance) {
+ SubscriberInfo subscriberInfo = info.getSir().getRequestDetails().getSubscriberInfo();
+ if (subscriberInfo == null) {
+ throw new ValidationException("subscriberInfo");
+ }
+ if (empty(subscriberInfo.getGlobalSubscriberId())) {
+ throw new ValidationException("globalSubscriberId");
+ }
}
return info;
- }
-} \ No newline at end of file
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java
index 894e488e92..067e8611d0 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java
@@ -23,7 +23,6 @@ package org.onap.so.apihandlerinfra.validation;
import java.util.ArrayList;
import java.util.List;
-
import org.onap.so.apihandlerinfra.Action;
import org.onap.so.apihandlerinfra.Actions;
import org.onap.so.exceptions.ValidationException;
@@ -33,103 +32,107 @@ import org.onap.so.serviceinstancebeans.Service;
import org.onap.so.serviceinstancebeans.VfModules;
import org.onap.so.serviceinstancebeans.Vnfs;
-public class UserParamsValidation implements ValidationRule{
- @Override
- public ValidationInformation validate(ValidationInformation info) throws ValidationException{
- Service validate = info.getUserParams();
- Actions action = info.getAction();
-
- if(validate.getModelInfo() == null){
- throw new ValidationException ("modelInfo in userParams", true);
- }else if(validate.getModelInfo().getModelType() == null){
- throw new ValidationException("modelType in userParams service modelInfo", true);
- }else if(validate.getModelInfo().getModelVersionId() == null){
- throw new ValidationException("modelVersionId in userParams service modelInfo", true);
- }
- modelInfoValidation(info.getSir().getRequestDetails().getModelInfo(), validate.getModelInfo());
- if(validate.getInstanceName() != null && info.getRequestInfo().getInstanceName() != null){
- instanceNameValidation(info, validate);
- }
- for(Vnfs vnf : validate.getResources().getVnfs()){
- if(vnf.getModelInfo() == null){
- throw new ValidationException ("modelInfo in userParams vnf resources", true);
- }else if(vnf.getModelInfo().getModelCustomizationId() == null){
- throw new ValidationException ("modelCustomizationId in userParams vnf resources", true);
- }else if(vnf.getModelInfo().getModelVersionId() == null){
- throw new ValidationException("modelVersionId in userParams vnf resources", true);
- }
- if(vnf.getCloudConfiguration() == null){
- throw new ValidationException ("cloudConfiguration in userParams vnf resources", true);
- }
- if(action == Action.createInstance || action == Action.assignInstance){
- if(vnf.getPlatform() == null){
- throw new ValidationException ("platform in userParams vnf resources", true);
- }if(vnf.getProductFamilyId() == null){
- throw new ValidationException ("productFamilyId in userParams vnf resources", true);
- }
- }
- if (vnf.getPlatform() != null && vnf.getPlatform().getPlatformName() == null){
- throw new ValidationException ("platformName in userParams vnf resources", true);
- }
- if(vnf.getVfModules().isEmpty()){
- throw new ValidationException ("vfModules in userParams vnf resources", true);
- }
- for(VfModules vfModules : vnf.getVfModules()){
- if(vfModules.getModelInfo() == null){
- throw new ValidationException ("modelInfo in userParams vfModules resources", true);
- }else if(vfModules.getModelInfo().getModelCustomizationId() == null){
- throw new ValidationException ("modelCustomizationId in userParams vfModule resources", true);
- }else if(vfModules.getModelInfo().getModelVersionId() == null){
- throw new ValidationException("modelVersionId in userParams vfModule resources", true);
- }
- }
- }
-
- List<Networks> validateNetworks = new ArrayList<>();
- validateNetworks = validate.getResources().getNetworks();
- if(validateNetworks != null){
- for(Networks networks : validateNetworks){
- if(networks.getModelInfo() == null){
- throw new ValidationException ("modelInfo in userParams network resources", true);
- }else if(networks.getModelInfo().getModelCustomizationId() == null){
- throw new ValidationException ("modelCustomizationId in userParams network resources", true);
- }else if(networks.getModelInfo().getModelVersionId() == null){
- throw new ValidationException("modelVersionId in userParams network resources", true);
- }
- if(networks.getCloudConfiguration() == null){
- throw new ValidationException ("cloudConfiguration in userParams network resources", true);
- }
- }
- }
- return info;
- }
- public void instanceNameValidation(ValidationInformation info, Service validate) throws ValidationException{
- if(!info.getRequestInfo().getInstanceName().equals(validate.getInstanceName())){
- throw new ValidationException("instanceName in requestInfo", "instanceName in userParams service");
- }
- }
- public void modelInfoValidation(ModelInfo info, ModelInfo userParamInfo) throws ValidationException{
- if(!info.getModelType().equals(userParamInfo.getModelType())){
- throw new ValidationException("modelType in modelInfo", "modelType in userParams service");
- }
- if((info.getModelInvariantId() != null && userParamInfo.getModelInvariantId() != null) &&
- (!info.getModelInvariantId().equals(userParamInfo.getModelInvariantId()))){
- throw new ValidationException("modelInvariantId in modelInfo", "modelInvariantId in userParams service");
- }
- if(!info.getModelVersionId().equals(userParamInfo.getModelVersionId())){
- throw new ValidationException("modelVersionId in modelInfo", "modelVersionId in userParams service");
- }
- if((info.getModelName() != null && userParamInfo.getModelName() != null) &&
- (!info.getModelName().equals(userParamInfo.getModelName()))){
- throw new ValidationException("modelName in modelInfo", "modelName in userParams service");
- }
- if((info.getModelVersion() != null && userParamInfo.getModelVersion() != null) &&
- (!info.getModelVersion().equals(userParamInfo.getModelVersion()))){
- throw new ValidationException("modelVersion in modelInfo", "modelVersion in userParams service");
- }
- if((info.getModelCustomizationId() != null && userParamInfo.getModelCustomizationId() != null) &&
- (!info.getModelCustomizationId().equals(userParamInfo.getModelCustomizationId()))){
- throw new ValidationException("modelCustomizationId in modelInfo", "modelCustomizationId in userParams service");
- }
- }
-} \ No newline at end of file
+public class UserParamsValidation implements ValidationRule {
+ @Override
+ public ValidationInformation validate(ValidationInformation info) throws ValidationException {
+ Service validate = info.getUserParams();
+ Actions action = info.getAction();
+
+ if (validate.getModelInfo() == null) {
+ throw new ValidationException("modelInfo in userParams", true);
+ } else if (validate.getModelInfo().getModelType() == null) {
+ throw new ValidationException("modelType in userParams service modelInfo", true);
+ } else if (validate.getModelInfo().getModelVersionId() == null) {
+ throw new ValidationException("modelVersionId in userParams service modelInfo", true);
+ }
+ modelInfoValidation(info.getSir().getRequestDetails().getModelInfo(), validate.getModelInfo());
+ if (validate.getInstanceName() != null && info.getRequestInfo().getInstanceName() != null) {
+ instanceNameValidation(info, validate);
+ }
+ for (Vnfs vnf : validate.getResources().getVnfs()) {
+ if (vnf.getModelInfo() == null) {
+ throw new ValidationException("modelInfo in userParams vnf resources", true);
+ } else if (vnf.getModelInfo().getModelCustomizationId() == null) {
+ throw new ValidationException("modelCustomizationId in userParams vnf resources", true);
+ } else if (vnf.getModelInfo().getModelVersionId() == null) {
+ throw new ValidationException("modelVersionId in userParams vnf resources", true);
+ }
+ if (vnf.getCloudConfiguration() == null) {
+ throw new ValidationException("cloudConfiguration in userParams vnf resources", true);
+ }
+ if (action == Action.createInstance || action == Action.assignInstance) {
+ if (vnf.getPlatform() == null) {
+ throw new ValidationException("platform in userParams vnf resources", true);
+ }
+ if (vnf.getProductFamilyId() == null) {
+ throw new ValidationException("productFamilyId in userParams vnf resources", true);
+ }
+ }
+ if (vnf.getPlatform() != null && vnf.getPlatform().getPlatformName() == null) {
+ throw new ValidationException("platformName in userParams vnf resources", true);
+ }
+ if (vnf.getVfModules().isEmpty()) {
+ throw new ValidationException("vfModules in userParams vnf resources", true);
+ }
+ for (VfModules vfModules : vnf.getVfModules()) {
+ if (vfModules.getModelInfo() == null) {
+ throw new ValidationException("modelInfo in userParams vfModules resources", true);
+ } else if (vfModules.getModelInfo().getModelCustomizationId() == null) {
+ throw new ValidationException("modelCustomizationId in userParams vfModule resources", true);
+ } else if (vfModules.getModelInfo().getModelVersionId() == null) {
+ throw new ValidationException("modelVersionId in userParams vfModule resources", true);
+ }
+ }
+ }
+
+ List<Networks> validateNetworks = new ArrayList<>();
+ validateNetworks = validate.getResources().getNetworks();
+ if (validateNetworks != null) {
+ for (Networks networks : validateNetworks) {
+ if (networks.getModelInfo() == null) {
+ throw new ValidationException("modelInfo in userParams network resources", true);
+ } else if (networks.getModelInfo().getModelCustomizationId() == null) {
+ throw new ValidationException("modelCustomizationId in userParams network resources", true);
+ } else if (networks.getModelInfo().getModelVersionId() == null) {
+ throw new ValidationException("modelVersionId in userParams network resources", true);
+ }
+ if (networks.getCloudConfiguration() == null) {
+ throw new ValidationException("cloudConfiguration in userParams network resources", true);
+ }
+ }
+ }
+ return info;
+ }
+
+ public void instanceNameValidation(ValidationInformation info, Service validate) throws ValidationException {
+ if (!info.getRequestInfo().getInstanceName().equals(validate.getInstanceName())) {
+ throw new ValidationException("instanceName in requestInfo", "instanceName in userParams service");
+ }
+ }
+
+ public void modelInfoValidation(ModelInfo info, ModelInfo userParamInfo) throws ValidationException {
+ if (!info.getModelType().equals(userParamInfo.getModelType())) {
+ throw new ValidationException("modelType in modelInfo", "modelType in userParams service");
+ }
+ if ((info.getModelInvariantId() != null && userParamInfo.getModelInvariantId() != null)
+ && (!info.getModelInvariantId().equals(userParamInfo.getModelInvariantId()))) {
+ throw new ValidationException("modelInvariantId in modelInfo", "modelInvariantId in userParams service");
+ }
+ if (!info.getModelVersionId().equals(userParamInfo.getModelVersionId())) {
+ throw new ValidationException("modelVersionId in modelInfo", "modelVersionId in userParams service");
+ }
+ if ((info.getModelName() != null && userParamInfo.getModelName() != null)
+ && (!info.getModelName().equals(userParamInfo.getModelName()))) {
+ throw new ValidationException("modelName in modelInfo", "modelName in userParams service");
+ }
+ if ((info.getModelVersion() != null && userParamInfo.getModelVersion() != null)
+ && (!info.getModelVersion().equals(userParamInfo.getModelVersion()))) {
+ throw new ValidationException("modelVersion in modelInfo", "modelVersion in userParams service");
+ }
+ if ((info.getModelCustomizationId() != null && userParamInfo.getModelCustomizationId() != null)
+ && (!info.getModelCustomizationId().equals(userParamInfo.getModelCustomizationId()))) {
+ throw new ValidationException("modelCustomizationId in modelInfo",
+ "modelCustomizationId in userParams service");
+ }
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationInformation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationInformation.java
index 7fc9567123..68b2a78a85 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationInformation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationInformation.java
@@ -22,7 +22,6 @@
package org.onap.so.apihandlerinfra.validation;
import java.util.HashMap;
-
import org.onap.so.apihandlerinfra.Actions;
import org.onap.so.serviceinstancebeans.LineOfBusiness;
import org.onap.so.serviceinstancebeans.OwningEntity;
@@ -33,148 +32,186 @@ import org.onap.so.serviceinstancebeans.RequestParameters;
import org.onap.so.serviceinstancebeans.Service;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
-public class ValidationInformation{
- ServiceInstancesRequest sir;
- HashMap<String,String> instanceIdMap;
- Actions action;
- int reqVersion;
- String requestScope;
- Boolean aLaCarteFlag;
- RequestParameters requestParameters;
- RequestInfo requestInfo;
- String serviceInstanceType;
- String vfModuleModelName;
- String vnfType;
- String asdcServiceModelVersion;
- String vfModuleType;
- String networkType;
- Platform platform;
- LineOfBusiness lob;
- Project project;
- OwningEntity owningEntity;
- Service userParams;
-
- public ValidationInformation(ServiceInstancesRequest sir, HashMap<String,String> instanceIdMap,
- Actions action, int reqVersion, Boolean aLaCarteFlag, RequestParameters requestParameters){
- this.sir = sir;
- this.instanceIdMap = instanceIdMap;
- this.action = action;
- this.reqVersion = reqVersion;
- this.aLaCarteFlag = aLaCarteFlag;
- this.requestParameters = requestParameters;
- }
- public ServiceInstancesRequest getSir(){
- return this.sir;
- }
- public void setSir(ServiceInstancesRequest value){
- this.sir = value;
- }
- public HashMap<String, String> getInstanceIdMap(){
- return this.instanceIdMap;
- }
- public void setInstanceIdMap(HashMap<String, String> value){
- this.instanceIdMap = value;
- }
- public Actions getAction(){
- return this.action;
- }
- public void setAction(Actions value){
- this.action = value;
- }
- public RequestInfo getRequestInfo(){
- return this.requestInfo;
- }
- public void setRequestInfo(RequestInfo value){
- this.requestInfo = value;
- }
- public int getReqVersion(){
- return this.reqVersion;
- }
- public void setReqVersion(int value){
- this.reqVersion = value;
- }
- public String getRequestScope(){
- return this.requestScope;
- }
- public void setRequestScope(String value){
- this.requestScope = value;
- }
- public Boolean getALaCarteFlag(){
- return this.aLaCarteFlag;
- }
- public void setALaCarteFlag(Boolean value){
- this.aLaCarteFlag = value;
- }
- public RequestParameters getReqParameters(){
- return this.requestParameters;
- }
- public void setReqParameters(RequestParameters value){
- this.requestParameters = value;
- }
- public String getServiceInstanceType(){
- return this.serviceInstanceType;
- }
- public void setServiceInstanceType(String value){
- this.serviceInstanceType = value;
- }
- public String getVfModuleModelName(){
- return this.vfModuleModelName;
- }
- public void setVfModuleModelName(String value){
- this.vfModuleModelName = value;
- }
- public String getVnfType(){
- return this.vnfType;
- }
- public void setVnfType(String value){
- this.vnfType = value;
- }
- public String getAsdcServiceModelVersion(){
- return this.asdcServiceModelVersion;
- }
- public void setAsdcServiceModelVersion(String value){
- this.asdcServiceModelVersion = value;
- }
- public String getVfModuleType(){
- return this.vfModuleType;
- }
- public void setVfModuleType(String value){
- this.vfModuleType = value;
- }
- public String getNetworkType(){
- return this.networkType;
- }
- public void setNetworkType(String value){
- this.networkType = value;
- }
- public Platform getPlatform(){
- return this.platform;
- }
- public void setPlatform(Platform value){
- this.platform = value;
- }
- public LineOfBusiness getLOB(){
- return this.lob;
- }
- public void setLOB(LineOfBusiness value){
- this.lob = value;
- }
- public Project getProject(){
- return this.project;
- }
- public void setProject(Project value){
- this.project = value;
- }
- public OwningEntity getOE(){
- return this.owningEntity;
- }
- public void setOE(OwningEntity value){
- this.owningEntity = value;
- }
- public Service getUserParams(){
- return this.userParams;
- }
- public void setUserParams(Service value){
- this.userParams = value;
- }
-} \ No newline at end of file
+public class ValidationInformation {
+ ServiceInstancesRequest sir;
+ HashMap<String, String> instanceIdMap;
+ Actions action;
+ int reqVersion;
+ String requestScope;
+ Boolean aLaCarteFlag;
+ RequestParameters requestParameters;
+ RequestInfo requestInfo;
+ String serviceInstanceType;
+ String vfModuleModelName;
+ String vnfType;
+ String asdcServiceModelVersion;
+ String vfModuleType;
+ String networkType;
+ Platform platform;
+ LineOfBusiness lob;
+ Project project;
+ OwningEntity owningEntity;
+ Service userParams;
+
+ public ValidationInformation(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action,
+ int reqVersion, Boolean aLaCarteFlag, RequestParameters requestParameters) {
+ this.sir = sir;
+ this.instanceIdMap = instanceIdMap;
+ this.action = action;
+ this.reqVersion = reqVersion;
+ this.aLaCarteFlag = aLaCarteFlag;
+ this.requestParameters = requestParameters;
+ }
+
+ public ServiceInstancesRequest getSir() {
+ return this.sir;
+ }
+
+ public void setSir(ServiceInstancesRequest value) {
+ this.sir = value;
+ }
+
+ public HashMap<String, String> getInstanceIdMap() {
+ return this.instanceIdMap;
+ }
+
+ public void setInstanceIdMap(HashMap<String, String> value) {
+ this.instanceIdMap = value;
+ }
+
+ public Actions getAction() {
+ return this.action;
+ }
+
+ public void setAction(Actions value) {
+ this.action = value;
+ }
+
+ public RequestInfo getRequestInfo() {
+ return this.requestInfo;
+ }
+
+ public void setRequestInfo(RequestInfo value) {
+ this.requestInfo = value;
+ }
+
+ public int getReqVersion() {
+ return this.reqVersion;
+ }
+
+ public void setReqVersion(int value) {
+ this.reqVersion = value;
+ }
+
+ public String getRequestScope() {
+ return this.requestScope;
+ }
+
+ public void setRequestScope(String value) {
+ this.requestScope = value;
+ }
+
+ public Boolean getALaCarteFlag() {
+ return this.aLaCarteFlag;
+ }
+
+ public void setALaCarteFlag(Boolean value) {
+ this.aLaCarteFlag = value;
+ }
+
+ public RequestParameters getReqParameters() {
+ return this.requestParameters;
+ }
+
+ public void setReqParameters(RequestParameters value) {
+ this.requestParameters = value;
+ }
+
+ public String getServiceInstanceType() {
+ return this.serviceInstanceType;
+ }
+
+ public void setServiceInstanceType(String value) {
+ this.serviceInstanceType = value;
+ }
+
+ public String getVfModuleModelName() {
+ return this.vfModuleModelName;
+ }
+
+ public void setVfModuleModelName(String value) {
+ this.vfModuleModelName = value;
+ }
+
+ public String getVnfType() {
+ return this.vnfType;
+ }
+
+ public void setVnfType(String value) {
+ this.vnfType = value;
+ }
+
+ public String getAsdcServiceModelVersion() {
+ return this.asdcServiceModelVersion;
+ }
+
+ public void setAsdcServiceModelVersion(String value) {
+ this.asdcServiceModelVersion = value;
+ }
+
+ public String getVfModuleType() {
+ return this.vfModuleType;
+ }
+
+ public void setVfModuleType(String value) {
+ this.vfModuleType = value;
+ }
+
+ public String getNetworkType() {
+ return this.networkType;
+ }
+
+ public void setNetworkType(String value) {
+ this.networkType = value;
+ }
+
+ public Platform getPlatform() {
+ return this.platform;
+ }
+
+ public void setPlatform(Platform value) {
+ this.platform = value;
+ }
+
+ public LineOfBusiness getLOB() {
+ return this.lob;
+ }
+
+ public void setLOB(LineOfBusiness value) {
+ this.lob = value;
+ }
+
+ public Project getProject() {
+ return this.project;
+ }
+
+ public void setProject(Project value) {
+ this.project = value;
+ }
+
+ public OwningEntity getOE() {
+ return this.owningEntity;
+ }
+
+ public void setOE(OwningEntity value) {
+ this.owningEntity = value;
+ }
+
+ public Service getUserParams() {
+ return this.userParams;
+ }
+
+ public void setUserParams(Service value) {
+ this.userParams = value;
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationRule.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationRule.java
index a5d85f6533..e8073bd1d1 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationRule.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationRule.java
@@ -23,6 +23,6 @@ package org.onap.so.apihandlerinfra.validation;
import org.onap.so.exceptions.ValidationException;
-public interface ValidationRule{
- ValidationInformation validate(ValidationInformation info)throws ValidationException;
-} \ No newline at end of file
+public interface ValidationRule {
+ ValidationInformation validate(ValidationInformation info) throws ValidationException;
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ActionType.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ActionType.java
index 15fe0a5be3..796db8c32a 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ActionType.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ActionType.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
@@ -34,10 +34,13 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for action-type.
+ * <p>
+ * Java class for action-type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
* <p>
+ * The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ *
* <pre>
* &lt;simpleType name="action-type">
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
@@ -59,15 +62,7 @@ import javax.xml.bind.annotation.XmlType;
@XmlEnum
public enum ActionType {
- CREATE,
- SETSTATUS,
- REPLACE,
- UPDATE,
- DELETE,
- CREATE_VF_MODULE,
- UPDATE_VF_MODULE,
- DELETE_VF_MODULE,
- NOT_PROVIDED;
+ CREATE, SETSTATUS, REPLACE, UPDATE, DELETE, CREATE_VF_MODULE, UPDATE_VF_MODULE, DELETE_VF_MODULE, NOT_PROVIDED;
public String value() {
return name();
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ModelType.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ModelType.java
index 3f708c49d5..e24ecd4eac 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ModelType.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ModelType.java
@@ -22,11 +22,7 @@ package org.onap.so.apihandlerinfra.vnfbeans;
/*
* Enum for Status values returned by API Handler to Tail-F
-*/
+ */
public enum ModelType {
- service,
- vnf,
- vfModule,
- volumeGroup,
- network
+ service, vnf, vfModule, volumeGroup, network
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java
index 72be61105b..2236b09f2a 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
@@ -36,31 +36,28 @@ import javax.xml.namespace.QName;
/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the org.onap.so.apihandlerinfra.vnfbeans1 package.
- * <p>An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
- * provided in this class.
+ * This object contains factory methods for each Java content interface and Java element interface generated in the
+ * org.onap.so.apihandlerinfra.vnfbeans1 package.
+ * <p>
+ * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content.
+ * The Java representation of XML content can consist of schema derived interfaces and classes representing the binding
+ * of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in
+ * this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _VnfParams_QNAME = new QName("http://org.onap/so/infra/vnf-request/v1", "vnf-params");
- private final static QName _NetworkParams_QNAME = new QName("http://org.onap/so/infra/vnf-request/v1", "network-params");
+ private final static QName _NetworkParams_QNAME =
+ new QName("http://org.onap/so/infra/vnf-request/v1", "network-params");
/**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.so.apihandlerinfra.vnfbeans1
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
+ * org.onap.so.apihandlerinfra.vnfbeans1
*
*/
- public ObjectFactory() {
- }
+ public ObjectFactory() {}
/**
* Create an instance of {@link VnfInputs }
@@ -102,7 +99,7 @@ public class ObjectFactory {
return new VnfRequest();
}
-
+
/**
* Create an instance of {@link VnfTypes }
*
@@ -118,7 +115,7 @@ public class ObjectFactory {
public VnfRequests createVnfRequests() {
return new VnfRequests();
}
-
+
/**
* Create an instance of {@link VfModuleModelName }
*
@@ -126,7 +123,7 @@ public class ObjectFactory {
public VfModuleModelName createVfModuleModelName() {
return new VfModuleModelName();
}
-
+
/**
* Create an instance of {@link VfModuleModelNames }
*
@@ -135,9 +132,8 @@ public class ObjectFactory {
return new VfModuleModelNames();
}
-
-
-
+
+
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Object }{@code >}}
*
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestInfo.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestInfo.java
index dc8457c6a4..2af0a02d17 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestInfo.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestInfo.java
@@ -37,9 +37,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -63,16 +65,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "requestId",
- "action",
- "requestStatus",
- "statusMessage",
- "progress",
- "startTime",
- "endTime",
- "source"
-})
+@XmlType(name = "", propOrder = {"requestId", "action", "requestStatus", "statusMessage", "progress", "startTime",
+ "endTime", "source"})
@XmlRootElement(name = "request-info")
public class RequestInfo {
@@ -94,9 +88,7 @@ public class RequestInfo {
/**
* Gets the value of the requestId property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getRequestId() {
@@ -106,9 +98,7 @@ public class RequestInfo {
/**
* Sets the value of the requestId property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setRequestId(String value) {
@@ -118,9 +108,7 @@ public class RequestInfo {
/**
* Gets the value of the action property.
*
- * @return
- * possible object is
- * {@link ActionType }
+ * @return possible object is {@link ActionType }
*
*/
public ActionType getAction() {
@@ -130,9 +118,7 @@ public class RequestInfo {
/**
* Sets the value of the action property.
*
- * @param value
- * allowed object is
- * {@link ActionType }
+ * @param value allowed object is {@link ActionType }
*
*/
public void setAction(ActionType value) {
@@ -142,9 +128,7 @@ public class RequestInfo {
/**
* Gets the value of the requestStatus property.
*
- * @return
- * possible object is
- * {@link RequestStatusType }
+ * @return possible object is {@link RequestStatusType }
*
*/
public RequestStatusType getRequestStatus() {
@@ -154,9 +138,7 @@ public class RequestInfo {
/**
* Sets the value of the requestStatus property.
*
- * @param value
- * allowed object is
- * {@link RequestStatusType }
+ * @param value allowed object is {@link RequestStatusType }
*
*/
public void setRequestStatus(RequestStatusType value) {
@@ -166,9 +148,7 @@ public class RequestInfo {
/**
* Gets the value of the statusMessage property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getStatusMessage() {
@@ -178,9 +158,7 @@ public class RequestInfo {
/**
* Sets the value of the statusMessage property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setStatusMessage(String value) {
@@ -190,9 +168,7 @@ public class RequestInfo {
/**
* Gets the value of the progress property.
*
- * @return
- * possible object is
- * {@link Integer }
+ * @return possible object is {@link Integer }
*
*/
public String getProgress() {
@@ -202,9 +178,7 @@ public class RequestInfo {
/**
* Sets the value of the progress property.
*
- * @param value
- * allowed object is
- * {@link Integer }
+ * @param value allowed object is {@link Integer }
*
*/
public void setProgress(String value) {
@@ -214,9 +188,7 @@ public class RequestInfo {
/**
* Gets the value of the startTime property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getStartTime() {
@@ -226,9 +198,7 @@ public class RequestInfo {
/**
* Sets the value of the startTime property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setStartTime(String value) {
@@ -238,9 +208,7 @@ public class RequestInfo {
/**
* Gets the value of the endTime property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getEndTime() {
@@ -250,9 +218,7 @@ public class RequestInfo {
/**
* Sets the value of the endTime property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setEndTime(String value) {
@@ -262,9 +228,7 @@ public class RequestInfo {
/**
* Gets the value of the source property.
*
- * @return
- * possible object is
- * {@link String }
+ * @return possible object is {@link String }
*
*/
public String getSource() {
@@ -274,9 +238,7 @@ public class RequestInfo {
/**
* Sets the value of the source property.
*
- * @param value
- * allowed object is
- * {@link String }
+ * @param value allowed object is {@link String }
*
*/
public void setSource(String value) {
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestStatusType.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestStatusType.java
index 8c98b9f801..d7250c6ebf 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestStatusType.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestStatusType.java
@@ -34,10 +34,13 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for request-status-type.
+ * <p>
+ * Java class for request-status-type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
* <p>
+ * The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ *
* <pre>
* &lt;simpleType name="request-status-type">
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
@@ -53,12 +56,7 @@ import javax.xml.bind.annotation.XmlType;
@XmlEnum
public enum RequestStatusType {
- COMPLETE,
- FAILED,
- IN_PROGRESS,
- PENDING,
- TIMEOUT,
- UNLOCKED;
+ COMPLETE, FAILED, IN_PROGRESS, PENDING, TIMEOUT, UNLOCKED;
public String value() {
return name();
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelName.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelName.java
index 74065482f8..1bf99b1362 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelName.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelName.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
@@ -38,9 +38,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -63,40 +65,31 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "modelName",
- "modelVersion",
- "modelInvariantUuid",
- "isBase",
- "id",
- "description",
- "asdcServiceModelVersion"
-})
+@XmlType(name = "", propOrder = {"modelName", "modelVersion", "modelInvariantUuid", "isBase", "id", "description",
+ "asdcServiceModelVersion"})
@XmlRootElement(name = "vf-module-model-name")
public class VfModuleModelName {
- @XmlElement(name="model-name", required = true)
+ @XmlElement(name = "model-name", required = true)
protected String modelName;
- @XmlElement(name="model-version", required = true)
+ @XmlElement(name = "model-version", required = true)
protected String modelVersion;
- @XmlElement(name="model-invariant-uuid", required = true)
+ @XmlElement(name = "model-invariant-uuid", required = true)
protected String modelInvariantUuid;
- @XmlElement(name="is-base", required = true)
+ @XmlElement(name = "is-base", required = true)
protected Boolean isBase;
- @XmlElement(name="id", required = true)
+ @XmlElement(name = "id", required = true)
protected String id;
- @XmlElement(name="description", required = true)
+ @XmlElement(name = "description", required = true)
protected String description;
- @XmlElement(name="asdc-service-model-version", required = true)
+ @XmlElement(name = "asdc-service-model-version", required = true)
protected String asdcServiceModelVersion;
/**
* Gets the value of the modelName property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getModelName() {
return modelName;
@@ -105,22 +98,18 @@ public class VfModuleModelName {
/**
* Sets the value of the modelName property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setModelName(String value) {
this.modelName = value;
}
-
+
/**
* Gets the value of the modelVersion property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getModelVersion() {
return modelVersion;
@@ -129,22 +118,18 @@ public class VfModuleModelName {
/**
* Sets the value of the modelVersion property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setModelVersion(String value) {
this.modelVersion = value;
}
-
+
/**
* Gets the value of the modelInvariantUuid property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getModelInvariantUuid() {
return modelInvariantUuid;
@@ -153,22 +138,18 @@ public class VfModuleModelName {
/**
* Sets the value of the modelInvariantUuid property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setModelInvariantUuid(String value) {
this.modelInvariantUuid = value;
}
-
+
/**
* Gets the value of the isBase property.
*
- * @return
- * possible object is
- * {@link Boolean }
- *
+ * @return possible object is {@link Boolean }
+ *
*/
public Boolean getIsBase() {
return isBase;
@@ -177,10 +158,8 @@ public class VfModuleModelName {
/**
* Sets the value of the isBase property.
*
- * @param value
- * allowed object is
- * {@link Boolean }
- *
+ * @param value allowed object is {@link Boolean }
+ *
*/
public void setIsBase(Boolean value) {
this.isBase = value;
@@ -189,10 +168,8 @@ public class VfModuleModelName {
/**
* Gets the value of the id property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getId() {
return id;
@@ -201,10 +178,8 @@ public class VfModuleModelName {
/**
* Sets the value of the id property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setId(String value) {
this.id = value;
@@ -213,10 +188,8 @@ public class VfModuleModelName {
/**
* Gets the value of the description property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getDescription() {
return description;
@@ -225,22 +198,18 @@ public class VfModuleModelName {
/**
* Sets the value of the description property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setDescription(String value) {
this.description = value;
}
-
+
/**
* Gets the value of the asdcServiceModelVersion property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getAsdcServiceModelVersion() {
return asdcServiceModelVersion;
@@ -249,10 +218,8 @@ public class VfModuleModelName {
/**
* Sets the value of the asdcServiceModelVersion property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setAsdcServiceModelVersion(String value) {
this.asdcServiceModelVersion = value;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelNames.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelNames.java
index 9904884620..2b334f262d 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelNames.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelNames.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
@@ -31,7 +31,6 @@ package org.onap.so.apihandlerinfra.vnfbeans;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -40,9 +39,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -59,9 +60,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "vfModuleModelName"
-})
+@XmlType(name = "", propOrder = {"vfModuleModelName"})
@XmlRootElement(name = "vf-module-model-names")
public class VfModuleModelNames {
@@ -72,21 +71,20 @@ public class VfModuleModelNames {
* Gets the value of the vfModuleModelName property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the vnfType property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to
+ * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for
+ * the vnfType property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getVfModuleModelName().add(newItem);
+ * getVfModuleModelName().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link VfModuleModelName }
+ * Objects of the following type(s) are allowed in the list {@link VfModuleModelName }
*
*
*/
@@ -96,9 +94,9 @@ public class VfModuleModelNames {
}
return this.vfModuleModelName;
}
-
+
public void setVfModuleModelName(List<VfModuleModelName> vfModuleModelName) {
- this.vfModuleModelName=vfModuleModelName;
+ this.vfModuleModelName = vfModuleModelName;
}
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfInputs.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfInputs.java
index 8816d0d4fc..f6b539dbe5 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfInputs.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfInputs.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
@@ -37,9 +37,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -81,32 +83,14 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "vnfId",
- "vfModuleId",
- "vnfName",
- "vfModuleName",
- "vnfType",
- "vfModuleModelName",
- "asdcServiceModelVersion",
- "serviceInstanceId",
- "backoutOnFailure",
- "serviceType",
- "serviceId",
- "aicNodeClli",
- "aicCloudRegion",
- "tenantId",
- "provStatus",
- "volumeGroupName",
- "volumeGroupId",
- // BEGIN - elements valid only on BPMN interface
- "personaModelId",
- "personaModelVersion",
- "isBaseVfModule",
- "vnfPersonaModelId",
- "vnfPersonaModelVersion"
- // END - elements valid only on BPMN interface
-})
+@XmlType(name = "",
+ propOrder = {"vnfId", "vfModuleId", "vnfName", "vfModuleName", "vnfType", "vfModuleModelName",
+ "asdcServiceModelVersion", "serviceInstanceId", "backoutOnFailure", "serviceType", "serviceId",
+ "aicNodeClli", "aicCloudRegion", "tenantId", "provStatus", "volumeGroupName", "volumeGroupId",
+ // BEGIN - elements valid only on BPMN interface
+ "personaModelId", "personaModelVersion", "isBaseVfModule", "vnfPersonaModelId", "vnfPersonaModelVersion"
+ // END - elements valid only on BPMN interface
+ })
@XmlRootElement(name = "vnf-inputs")
public class VnfInputs {
@@ -158,10 +142,8 @@ public class VnfInputs {
/**
* Gets the value of the vnfId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfId() {
return vnfId;
@@ -170,10 +152,8 @@ public class VnfInputs {
/**
* Sets the value of the vnfId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfId(String value) {
this.vnfId = value;
@@ -182,10 +162,8 @@ public class VnfInputs {
/**
* Gets the value of the vnfName property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfName() {
return vnfName;
@@ -194,10 +172,8 @@ public class VnfInputs {
/**
* Sets the value of the vnfName property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfName(String value) {
this.vnfName = value;
@@ -206,10 +182,8 @@ public class VnfInputs {
/**
* Gets the value of the vnfType property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfType() {
return vnfType;
@@ -218,22 +192,18 @@ public class VnfInputs {
/**
* Sets the value of the vnfType property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfType(String value) {
this.vnfType = value;
}
-
+
/**
* Gets the value of the serviceInstanceId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getServiceInstanceId() {
return serviceInstanceId;
@@ -242,10 +212,8 @@ public class VnfInputs {
/**
* Sets the value of the serviceInstanceId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setServiceInstanceId(String value) {
this.serviceInstanceId = value;
@@ -254,10 +222,8 @@ public class VnfInputs {
/**
* Gets the value of the serviceType property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getServiceType() {
return serviceType;
@@ -266,22 +232,18 @@ public class VnfInputs {
/**
* Sets the value of the serviceType property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setServiceType(String value) {
this.serviceType = value;
}
-
+
/**
* Gets the value of the serviceId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getServiceId() {
return serviceId;
@@ -290,12 +252,10 @@ public class VnfInputs {
/**
* Sets the value of the serviceId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
- public void setServiceId (String value) {
+ public void setServiceId(String value) {
this.serviceId = value;
}
@@ -303,10 +263,8 @@ public class VnfInputs {
/**
* Gets the value of the aicNodeClli property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getAicNodeClli() {
return aicNodeClli;
@@ -315,22 +273,18 @@ public class VnfInputs {
/**
* Sets the value of the aicNodeClli property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setAicNodeClli(String value) {
this.aicNodeClli = value;
}
-
+
/**
* Gets the value of the aicCloudRegion property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getAicCloudRegion() {
return aicCloudRegion;
@@ -339,10 +293,8 @@ public class VnfInputs {
/**
* Sets the value of the aicCloudRegion property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setAicCloudRegion(String value) {
this.aicCloudRegion = value;
@@ -351,10 +303,8 @@ public class VnfInputs {
/**
* Gets the value of the tenantId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getTenantId() {
return tenantId;
@@ -363,10 +313,8 @@ public class VnfInputs {
/**
* Sets the value of the tenantId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setTenantId(String value) {
this.tenantId = value;
@@ -375,10 +323,8 @@ public class VnfInputs {
/**
* Gets the value of the provStatus property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getProvStatus() {
return provStatus;
@@ -387,22 +333,18 @@ public class VnfInputs {
/**
* Sets the value of the provStatus property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setProvStatus(String value) {
this.provStatus = value;
}
-
+
/**
* Gets the value of the volumeGroupName property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVolumeGroupName() {
return volumeGroupName;
@@ -411,22 +353,18 @@ public class VnfInputs {
/**
* Sets the value of the volumeGroupName property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVolumeGroupName(String value) {
this.volumeGroupName = value;
}
-
+
/**
* Gets the value of the volumeGroupId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVolumeGroupId() {
return volumeGroupId;
@@ -435,22 +373,18 @@ public class VnfInputs {
/**
* Sets the value of the volumeGroupId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVolumeGroupId(String value) {
this.volumeGroupId = value;
}
-
+
/**
* Gets the value of the vfModuleId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVfModuleId() {
return vfModuleId;
@@ -459,22 +393,18 @@ public class VnfInputs {
/**
* Sets the value of the vfModuleId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVfModuleId(String value) {
this.vfModuleId = value;
}
-
+
/**
* Gets the value of the vfModuleName property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVfModuleName() {
return vfModuleName;
@@ -483,22 +413,18 @@ public class VnfInputs {
/**
* Sets the value of the vfModuleName property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVfModuleName(String value) {
this.vfModuleName = value;
}
-
+
/**
* Gets the value of the vfModuleModelName property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVfModuleModelName() {
return vfModuleModelName;
@@ -507,22 +433,18 @@ public class VnfInputs {
/**
* Sets the value of the vfModuleModelName property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVfModuleModelName(String value) {
this.vfModuleModelName = value;
}
-
+
/**
* Gets the value of the asdcServiceModelVersion property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getAsdcServiceModelVersion() {
return asdcServiceModelVersion;
@@ -531,22 +453,18 @@ public class VnfInputs {
/**
* Sets the value of the asdcServiceModelVersion property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setAsdcServiceModelVersion(String value) {
this.asdcServiceModelVersion = value;
}
-
+
/**
* Gets the value of the backoutOnFailure property.
*
- * @return
- * possible object is
- * {@link Boolean }
- *
+ * @return possible object is {@link Boolean }
+ *
*/
public Boolean getBackoutOnFailure() {
return backoutOnFailure;
@@ -555,22 +473,18 @@ public class VnfInputs {
/**
* Sets the value of the backoutOnFailure property.
*
- * @param value
- * allowed object is
- * {@link Boolean }
- *
+ * @param value allowed object is {@link Boolean }
+ *
*/
public void setBackoutOnFailure(Boolean value) {
this.backoutOnFailure = value;
}
-
+
/**
* Gets the value of the personaModelId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getPersonaModelId() {
return personaModelId;
@@ -579,22 +493,18 @@ public class VnfInputs {
/**
* Sets the value of the personaModelId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setPersonaModelId(String value) {
this.personaModelId = value;
}
-
+
/**
* Gets the value of the personaModelVersion property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getPersonaModelVersion() {
return personaModelVersion;
@@ -603,23 +513,19 @@ public class VnfInputs {
/**
* Sets the value of the personaModelVersion property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setPersonaModelVersion(String value) {
this.personaModelVersion = value;
}
-
-
+
+
/**
* Gets the value of the isBaseVfModule property.
*
- * @return
- * possible object is
- * {@link Boolean }
- *
+ * @return possible object is {@link Boolean }
+ *
*/
public Boolean getIsBaseVfModule() {
return isBaseVfModule;
@@ -628,22 +534,18 @@ public class VnfInputs {
/**
* Sets the value of the isBaseVfModule property.
*
- * @param value
- * allowed object is
- * {@link Boolean }
- *
+ * @param value allowed object is {@link Boolean }
+ *
*/
public void setIsBaseVfModule(Boolean value) {
this.isBaseVfModule = value;
}
-
+
/**
* Gets the value of the vnfPersonaModelId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfPersonaModelId() {
return vnfPersonaModelId;
@@ -652,22 +554,18 @@ public class VnfInputs {
/**
* Sets the value of the vnfPersonaModelId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfPersonaModelId(String value) {
this.vnfPersonaModelId = value;
}
-
+
/**
* Gets the value of the vnfPersonaModelVersion property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfPersonaModelVersion() {
return vnfPersonaModelVersion;
@@ -676,14 +574,12 @@ public class VnfInputs {
/**
* Sets the value of the vnfPersonaModelVersion property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfPersonaModelVersion(String value) {
this.vnfPersonaModelVersion = value;
- }
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfOutputs.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfOutputs.java
index 114a3ae137..051dcce5d3 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfOutputs.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfOutputs.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
@@ -37,9 +37,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -63,16 +65,8 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "vnfId",
- "vfModuleId",
- "vnfName",
- "vfModuleName",
- "aicNodeClli",
- "tenantId",
- "volumeGroupName",
- "volumeGroupId"
-})
+@XmlType(name = "", propOrder = {"vnfId", "vfModuleId", "vnfName", "vfModuleName", "aicNodeClli", "tenantId",
+ "volumeGroupName", "volumeGroupId"})
@XmlRootElement(name = "vnf-outputs")
public class VnfOutputs {
@@ -96,10 +90,8 @@ public class VnfOutputs {
/**
* Gets the value of the vnfId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfId() {
return vnfId;
@@ -108,22 +100,18 @@ public class VnfOutputs {
/**
* Sets the value of the vnfId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfId(String value) {
this.vnfId = value;
}
-
+
/**
* Gets the value of the vfModuleId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVfModuleId() {
return vfModuleId;
@@ -132,10 +120,8 @@ public class VnfOutputs {
/**
* Sets the value of the vfModuleId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVfModuleId(String value) {
this.vfModuleId = value;
@@ -146,10 +132,8 @@ public class VnfOutputs {
/**
* Gets the value of the vnfName property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVnfName() {
return vnfName;
@@ -158,22 +142,18 @@ public class VnfOutputs {
/**
* Sets the value of the vnfName property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVnfName(String value) {
this.vnfName = value;
}
-
+
/**
* Gets the value of the vfModuleName property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVfModuleName() {
return vfModuleName;
@@ -182,10 +162,8 @@ public class VnfOutputs {
/**
* Sets the value of the vfModuleName property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVfModuleName(String value) {
this.vfModuleName = value;
@@ -195,10 +173,8 @@ public class VnfOutputs {
/**
* Gets the value of the aicNodeClli property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getAicNodeClli() {
return aicNodeClli;
@@ -207,10 +183,8 @@ public class VnfOutputs {
/**
* Sets the value of the aicNodeClli property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setAicNodeClli(String value) {
this.aicNodeClli = value;
@@ -219,10 +193,8 @@ public class VnfOutputs {
/**
* Gets the value of the tenantId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getTenantId() {
return tenantId;
@@ -231,22 +203,18 @@ public class VnfOutputs {
/**
* Sets the value of the tenantId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setTenantId(String value) {
this.tenantId = value;
}
-
+
/**
* Gets the value of the volumeGroupName property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVolumeGroupName() {
return volumeGroupName;
@@ -255,22 +223,18 @@ public class VnfOutputs {
/**
* Sets the value of the volumeGroupName property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVolumeGroupName(String value) {
this.volumeGroupName = value;
}
-
+
/**
* Gets the value of the volumeGroupId property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getVolumeGroupId() {
return volumeGroupId;
@@ -279,10 +243,8 @@ public class VnfOutputs {
/**
* Sets the value of the volumeGroupId property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setVolumeGroupId(String value) {
this.volumeGroupId = value;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequest.java
index 07b186e149..9007f7c97b 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequest.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
@@ -37,9 +37,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -61,12 +63,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "requestInfo",
- "vnfInputs",
- "vnfParams",
- "vnfOutputs"
-})
+@XmlType(name = "", propOrder = {"requestInfo", "vnfInputs", "vnfParams", "vnfOutputs"})
@XmlRootElement(name = "vnf-request")
public class VnfRequest {
@@ -78,15 +75,13 @@ public class VnfRequest {
protected Object vnfParams;
@XmlElement(name = "vnf-outputs")
protected VnfOutputs vnfOutputs;
-
+
/**
* Gets the value of the requestInfo property.
*
- * @return
- * possible object is
- * {@link RequestInfo }
- *
+ * @return possible object is {@link RequestInfo }
+ *
*/
public RequestInfo getRequestInfo() {
return requestInfo;
@@ -95,10 +90,8 @@ public class VnfRequest {
/**
* Sets the value of the requestInfo property.
*
- * @param value
- * allowed object is
- * {@link RequestInfo }
- *
+ * @param value allowed object is {@link RequestInfo }
+ *
*/
public void setRequestInfo(RequestInfo value) {
this.requestInfo = value;
@@ -107,10 +100,8 @@ public class VnfRequest {
/**
* Gets the value of the vnfInputs property.
*
- * @return
- * possible object is
- * {@link VnfInputs }
- *
+ * @return possible object is {@link VnfInputs }
+ *
*/
public VnfInputs getVnfInputs() {
return vnfInputs;
@@ -119,10 +110,8 @@ public class VnfRequest {
/**
* Sets the value of the vnfInputs property.
*
- * @param value
- * allowed object is
- * {@link VnfInputs }
- *
+ * @param value allowed object is {@link VnfInputs }
+ *
*/
public void setVnfInputs(VnfInputs value) {
this.vnfInputs = value;
@@ -131,10 +120,8 @@ public class VnfRequest {
/**
* Gets the value of the vnfParams property.
*
- * @return
- * possible object is
- * {@link Object }
- *
+ * @return possible object is {@link Object }
+ *
*/
public Object getVnfParams() {
return vnfParams;
@@ -143,10 +130,8 @@ public class VnfRequest {
/**
* Sets the value of the vnfParams property.
*
- * @param value
- * allowed object is
- * {@link Object }
- *
+ * @param value allowed object is {@link Object }
+ *
*/
public void setVnfParams(Object value) {
this.vnfParams = value;
@@ -155,10 +140,8 @@ public class VnfRequest {
/**
* Gets the value of the vnfOutputs property.
*
- * @return
- * possible object is
- * {@link VnfOutputs }
- *
+ * @return possible object is {@link VnfOutputs }
+ *
*/
public VnfOutputs getVnfOutputs() {
return vnfOutputs;
@@ -167,13 +150,11 @@ public class VnfRequest {
/**
* Sets the value of the vnfOutputs property.
*
- * @param value
- * allowed object is
- * {@link VnfOutputs }
- *
+ * @param value allowed object is {@link VnfOutputs }
+ *
*/
public void setVnfOutputs(VnfOutputs value) {
this.vnfOutputs = value;
}
- }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequests.java
index caa0cae84d..677b983205 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequests.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequests.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
@@ -31,7 +31,6 @@ package org.onap.so.apihandlerinfra.vnfbeans;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -40,9 +39,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -59,9 +60,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "vnfRequest"
-})
+@XmlType(name = "", propOrder = {"vnfRequest"})
@XmlRootElement(name = "vnf-requests")
public class VnfRequests {
@@ -72,21 +71,20 @@ public class VnfRequests {
* Gets the value of the vnfRequest property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the vnfRequest property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to
+ * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for
+ * the vnfRequest property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getVnfRequest().add(newItem);
+ * getVnfRequest().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link VnfRequest }
+ * Objects of the following type(s) are allowed in the list {@link VnfRequest }
*
*
*/
@@ -98,6 +96,6 @@ public class VnfRequests {
}
public void setVnfRequest(List<VnfRequest> vnfRequest) {
- this.vnfRequest=vnfRequest;
+ this.vnfRequest = vnfRequest;
}
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfType.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfType.java
index dd556a7c34..1917839b47 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfType.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfType.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
@@ -37,9 +37,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -58,11 +60,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "type",
- "id",
- "description"
-})
+@XmlType(name = "", propOrder = {"type", "id", "description"})
@XmlRootElement(name = "vnf-type")
public class VnfType {
@@ -76,10 +74,8 @@ public class VnfType {
/**
* Gets the value of the type property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getType() {
return type;
@@ -88,10 +84,8 @@ public class VnfType {
/**
* Sets the value of the type property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setType(String value) {
this.type = value;
@@ -100,10 +94,8 @@ public class VnfType {
/**
* Gets the value of the id property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getId() {
return id;
@@ -112,10 +104,8 @@ public class VnfType {
/**
* Sets the value of the id property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setId(String value) {
this.id = value;
@@ -124,10 +114,8 @@ public class VnfType {
/**
* Gets the value of the description property.
*
- * @return
- * possible object is
- * {@link String }
- *
+ * @return possible object is {@link String }
+ *
*/
public String getDescription() {
return description;
@@ -136,10 +124,8 @@ public class VnfType {
/**
* Sets the value of the description property.
*
- * @param value
- * allowed object is
- * {@link String }
- *
+ * @param value allowed object is {@link String }
+ *
*/
public void setDescription(String value) {
this.description = value;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfTypes.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfTypes.java
index 6728c69172..7ce179de8e 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfTypes.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfTypes.java
@@ -19,10 +19,10 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
@@ -31,7 +31,6 @@ package org.onap.so.apihandlerinfra.vnfbeans;
import java.util.ArrayList;
import java.util.List;
-
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@@ -40,9 +39,11 @@ import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -59,9 +60,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "vnfType"
-})
+@XmlType(name = "", propOrder = {"vnfType"})
@XmlRootElement(name = "vnf-types")
public class VnfTypes {
@@ -72,21 +71,20 @@ public class VnfTypes {
* Gets the value of the vnfType property.
*
* <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the vnfType property.
+ * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to
+ * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for
+ * the vnfType property.
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getVnfType().add(newItem);
+ * getVnfType().add(newItem);
* </pre>
*
*
* <p>
- * Objects of the following type(s) are allowed in the list
- * {@link VnfType }
+ * Objects of the following type(s) are allowed in the list {@link VnfType }
*
*
*/
@@ -96,9 +94,9 @@ public class VnfTypes {
}
return this.vnfType;
}
-
- public void setVnfType( List<VnfType> vnfType) {
- this.vnfType=vnfType;
+
+ public void setVnfType(List<VnfType> vnfType) {
+ this.vnfType = vnfType;
}
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/package-info.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/package-info.java
index 3eb84299f4..efcfecffce 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/package-info.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/package-info.java
@@ -19,12 +19,13 @@
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.09.03 at 02:02:13 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.09.03 at 02:02:13 PM EDT
//
-@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/so/infra/vnf-request/v1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
+@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/so/infra/vnf-request/v1",
+ elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.onap.so.apihandlerinfra.vnfbeans;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ActivitySequence.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ActivitySequence.java
index 594b43e07d..75cc1ecec6 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ActivitySequence.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ActivitySequence.java
@@ -24,10 +24,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "name",
- "description"
-})
+@JsonPropertyOrder({"name", "description"})
public class ActivitySequence {
@JsonProperty("name")
@@ -39,8 +36,7 @@ public class ActivitySequence {
* No args constructor for use in serialization
*
*/
- public ActivitySequence() {
- }
+ public ActivitySequence() {}
/**
*
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ArtifactInfo.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ArtifactInfo.java
index 0861ff2033..26f37c1319 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ArtifactInfo.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ArtifactInfo.java
@@ -24,17 +24,8 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "artifactType",
- "artifactUuid",
- "artifactName",
- "artifactVersion",
- "artifactDescription",
- "workflowName",
- "operationName",
- "workflowSource",
- "workflowResourceTarget"
-})
+@JsonPropertyOrder({"artifactType", "artifactUuid", "artifactName", "artifactVersion", "artifactDescription",
+ "workflowName", "operationName", "workflowSource", "workflowResourceTarget"})
public class ArtifactInfo {
@JsonProperty("artifactType")
@@ -60,8 +51,7 @@ public class ArtifactInfo {
* No args constructor for use in serialization
*
*/
- public ArtifactInfo() {
- }
+ public ArtifactInfo() {}
/**
*
@@ -75,7 +65,9 @@ public class ArtifactInfo {
* @param artifactUuid
* @param artifactDescription
*/
- public ArtifactInfo(String artifactType, String artifactUuid, String artifactName, String artifactVersion, String artifactDescription, String workflowName, String operationName, String workflowSource, String workflowResourceTarget) {
+ public ArtifactInfo(String artifactType, String artifactUuid, String artifactName, String artifactVersion,
+ String artifactDescription, String workflowName, String operationName, String workflowSource,
+ String workflowResourceTarget) {
super();
this.artifactType = artifactType;
this.artifactUuid = artifactUuid;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/Validation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/Validation.java
index 3a4d5cb5f0..324f368c26 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/Validation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/Validation.java
@@ -24,10 +24,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "maxLength",
- "allowableChars"
-})
+@JsonPropertyOrder({"maxLength", "allowableChars"})
public class Validation {
@JsonProperty("maxLength")
@@ -39,8 +36,7 @@ public class Validation {
* No args constructor for use in serialization
*
*/
- public Validation() {
- }
+ public Validation() {}
/**
*
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowInputParameter.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowInputParameter.java
index 416442c216..8cbd622667 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowInputParameter.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowInputParameter.java
@@ -25,14 +25,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "label",
- "inputType",
- "required",
- "validation",
- "soFieldName",
- "soPayloadLocation"
-})
+@JsonPropertyOrder({"label", "inputType", "required", "validation", "soFieldName", "soPayloadLocation"})
public class WorkflowInputParameter {
@JsonProperty("label")
@@ -52,8 +45,7 @@ public class WorkflowInputParameter {
* No args constructor for use in serialization
*
*/
- public WorkflowInputParameter() {
- }
+ public WorkflowInputParameter() {}
/**
*
@@ -64,7 +56,8 @@ public class WorkflowInputParameter {
* @param required
* @param soFieldName
*/
- public WorkflowInputParameter(String label, String inputType, Boolean required, List<Validation> validation, String soFieldName, String soPayloadLocation) {
+ public WorkflowInputParameter(String label, String inputType, Boolean required, List<Validation> validation,
+ String soFieldName, String soPayloadLocation) {
super();
this.label = label;
this.inputType = inputType;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecification.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecification.java
index 86dc44ef39..d8a0a8b662 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecification.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecification.java
@@ -25,11 +25,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "artifactInfo",
- "activitySequence",
- "workflowInputParameters"
-})
+@JsonPropertyOrder({"artifactInfo", "activitySequence", "workflowInputParameters"})
public class WorkflowSpecification {
@JsonProperty("artifactInfo")
@@ -43,8 +39,7 @@ public class WorkflowSpecification {
* No args constructor for use in serialization
*
*/
- public WorkflowSpecification() {
- }
+ public WorkflowSpecification() {}
/**
*
@@ -52,7 +47,8 @@ public class WorkflowSpecification {
* @param artifactInfo
* @param workflowInputParameters
*/
- public WorkflowSpecification(ArtifactInfo artifactInfo, List<ActivitySequence> activitySequence, List<WorkflowInputParameter> workflowInputParameters) {
+ public WorkflowSpecification(ArtifactInfo artifactInfo, List<ActivitySequence> activitySequence,
+ List<WorkflowInputParameter> workflowInputParameters) {
super();
this.artifactInfo = artifactInfo;
this.activitySequence = activitySequence;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationList.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationList.java
index c6bf4e3d41..ba54e7271a 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationList.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationList.java
@@ -24,9 +24,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "workflowSpecification"
-})
+@JsonPropertyOrder({"workflowSpecification"})
public class WorkflowSpecificationList {
@JsonProperty("workflowSpecification")
@@ -36,8 +34,7 @@ public class WorkflowSpecificationList {
* No args constructor for use in serialization
*
*/
- public WorkflowSpecificationList() {
- }
+ public WorkflowSpecificationList() {}
/**
*
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecifications.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecifications.java
index ffe9980af4..922f5601d5 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecifications.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecifications.java
@@ -25,9 +25,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({
- "workflowSpecificationList"
-})
+@JsonPropertyOrder({"workflowSpecificationList"})
public class WorkflowSpecifications {
@JsonProperty("workflowSpecificationList")
@@ -37,8 +35,7 @@ public class WorkflowSpecifications {
* No args constructor for use in serialization
*
*/
- public WorkflowSpecifications() {
- }
+ public WorkflowSpecifications() {}
/**
*
@@ -59,7 +56,8 @@ public class WorkflowSpecifications {
this.workflowSpecificationList = workflowSpecificationList;
}
- public WorkflowSpecifications withWorkflowSpecificationList(List<WorkflowSpecificationList> workflowSpecificationList) {
+ public WorkflowSpecifications withWorkflowSpecificationList(
+ List<WorkflowSpecificationList> workflowSpecificationList) {
this.workflowSpecificationList = workflowSpecificationList;
return this;
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java
index 8a45752949..b8a2f22566 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java
@@ -21,10 +21,8 @@
package org.onap.so.apihandler.common;
import static org.junit.Assert.assertEquals;
-
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.junit.Test;
import org.onap.so.apihandlerinfra.BaseTest;
@@ -33,41 +31,41 @@ import org.springframework.beans.factory.annotation.Autowired;
public class ResponseBuilderTest extends BaseTest {
- @Autowired
- private ResponseBuilder builder;
-
+ @Autowired
+ private ResponseBuilder builder;
+
@Test
- public void testBuildResponseResponse () throws ApiException {
-
- String requestId = null;
- String apiVersion = "1";
- String jsonResponse = "Successfully started the process";
-
+ public void testBuildResponseResponse() throws ApiException {
+
+ String requestId = null;
+ String apiVersion = "1";
+ String jsonResponse = "Successfully started the process";
+
Response response = builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, jsonResponse, apiVersion);
-
+
assertEquals(202, response.getStatus());
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0));
assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0));
assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0));
-
+
}
-
+
@Test
- public void testBuildResponseVersion () throws ApiException {
-
- String requestId = "123456-67889";
- String apiVersion = "v5";
- String jsonResponse = "Successfully started the process";
-
+ public void testBuildResponseVersion() throws ApiException {
+
+ String requestId = "123456-67889";
+ String apiVersion = "v5";
+ String jsonResponse = "Successfully started the process";
+
Response response = builder.buildResponse(HttpStatus.SC_CREATED, requestId, jsonResponse, apiVersion);
-
+
assertEquals(201, response.getStatus());
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0));
assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0));
assertEquals("5.0.0", response.getHeaders().get("X-LatestVersion").get(0));
-
+
}
-
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java
index db3dcb5af5..276b438529 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java
@@ -23,35 +23,33 @@ package org.onap.so.apihandler.filters;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.net.URI;
-
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.UriInfo;
-
import org.junit.Test;
import org.onap.so.apihandlerinfra.BaseTest;
-public class RequestUriFilterTest extends BaseTest{
-
- @Test
- public void filterTest() throws IOException {
- RequestUriFilter URIFilter = new RequestUriFilter();
- URI baseURI = URI.create("http://localhost:58879/");
- String requestURI = "onap/so/infra/serviceInstances/v5";
-
- ContainerRequestContext mockContext = mock(ContainerRequestContext.class);
- UriInfo mockInfo = mock(UriInfo.class);
-
- when(mockContext.getUriInfo()).thenReturn(mockInfo);
- when(mockInfo.getBaseUri()).thenReturn(baseURI);
- when(mockInfo.getPath()).thenReturn(requestURI);
-
-
- URIFilter.filter(mockContext);
- assertEquals("http://localhost:58879/onap/so/infra/serviceInstantiation/v5/serviceInstances", URIFilter.getRequestUri());
- }
+public class RequestUriFilterTest extends BaseTest {
+
+ @Test
+ public void filterTest() throws IOException {
+ RequestUriFilter URIFilter = new RequestUriFilter();
+ URI baseURI = URI.create("http://localhost:58879/");
+ String requestURI = "onap/so/infra/serviceInstances/v5";
+
+ ContainerRequestContext mockContext = mock(ContainerRequestContext.class);
+ UriInfo mockInfo = mock(UriInfo.class);
+
+ when(mockContext.getUriInfo()).thenReturn(mockInfo);
+ when(mockInfo.getBaseUri()).thenReturn(baseURI);
+ when(mockInfo.getPath()).thenReturn(requestURI);
+
+
+ URIFilter.filter(mockContext);
+ assertEquals("http://localhost:58879/onap/so/infra/serviceInstantiation/v5/serviceInstances",
+ URIFilter.getRequestUri());
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java
index 564121b7b5..9065a1a9ea 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java
@@ -1,30 +1,23 @@
/*
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= ONAP - SO
+ * ================================================================================ Copyright (C) 2018 AT&T Intellectual
+ * Property. All rights reserved. ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.so.apihandler.recipe;
import static org.junit.Assert.assertEquals;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
-
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.junit.Before;
@@ -32,41 +25,41 @@ import org.junit.Test;
import org.mockito.Mockito;
public class CamundaClientErrorHandlerTest {
-
- private ClientHttpResponse clientHttpResponse;
- private CamundaClientErrorHandler clientErrorHandler;
-
- @Before
- public void before() {
- clientHttpResponse = Mockito.mock(ClientHttpResponse.class);
- clientErrorHandler = new CamundaClientErrorHandler();
- }
-
- @Test
- public void handleError_SERVER_ERROR_Test() throws IOException {
- Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
- Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
- clientErrorHandler.handleError(clientHttpResponse);
- boolean serverHasError = clientErrorHandler.hasError(clientHttpResponse);
- assertEquals(true, serverHasError);
- }
-
- @Test
- public void handleError_CLIENT_ERROR_Test() throws IOException {
- Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST);
- Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
- clientErrorHandler.handleError(clientHttpResponse);
- boolean clientHasError = clientErrorHandler.hasError(clientHttpResponse);
- assertEquals(true, clientHasError);
- }
-
- @Test
- public void handleError_SUCCESS_Test() throws IOException {
- Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
- Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
- clientErrorHandler.handleError(clientHttpResponse);
- boolean hasNoError = clientErrorHandler.hasError(clientHttpResponse);
- assertEquals(false, hasNoError);
- }
-
-} \ No newline at end of file
+
+ private ClientHttpResponse clientHttpResponse;
+ private CamundaClientErrorHandler clientErrorHandler;
+
+ @Before
+ public void before() {
+ clientHttpResponse = Mockito.mock(ClientHttpResponse.class);
+ clientErrorHandler = new CamundaClientErrorHandler();
+ }
+
+ @Test
+ public void handleError_SERVER_ERROR_Test() throws IOException {
+ Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
+ Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
+ clientErrorHandler.handleError(clientHttpResponse);
+ boolean serverHasError = clientErrorHandler.hasError(clientHttpResponse);
+ assertEquals(true, serverHasError);
+ }
+
+ @Test
+ public void handleError_CLIENT_ERROR_Test() throws IOException {
+ Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST);
+ Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
+ clientErrorHandler.handleError(clientHttpResponse);
+ boolean clientHasError = clientErrorHandler.hasError(clientHttpResponse);
+ assertEquals(true, clientHasError);
+ }
+
+ @Test
+ public void handleError_SUCCESS_Test() throws IOException {
+ Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
+ Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
+ clientErrorHandler.handleError(clientHttpResponse);
+ boolean hasNoError = clientErrorHandler.hasError(clientHttpResponse);
+ assertEquals(false, hasNoError);
+ }
+
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java
index 68869b77d4..75a6eeea7d 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java
@@ -19,14 +19,14 @@
*/
package org.onap.so.apihandlerinfra;
-import org.junit.runner.RunWith;
+import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses("**/*Test.class")
public class AllTestsTestSuite {
- // the class remains empty,
- // used only as a holder for the above annotations
+ // the class remains empty,
+ // used only as a holder for the above annotations
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java
index 6efcdc47e5..bc867503f2 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java
@@ -26,15 +26,12 @@ import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onap.so.apihandler.common.ErrorNumbers;
import org.onap.so.apihandlerinfra.exceptions.*;
-
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
-
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
-
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
@@ -52,7 +49,8 @@ public class ApiExceptionTest extends BaseTest {
thrown.expectMessage("Message rewritten");
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
- RecipeNotFoundException testException = new RecipeNotFoundException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).message("Message rewritten").build();
+ RecipeNotFoundException testException = new RecipeNotFoundException.Builder("Test Message",
+ HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).message("Message rewritten").build();
throw testException;
}
@@ -65,8 +63,9 @@ public class ApiExceptionTest extends BaseTest {
thrown.expectMessage(startsWith("Request Failed due to BPEL error with HTTP Status ="));
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
- thrown.expect(hasProperty("variables",sameBeanAs(testVariables)));
- BPMNFailureException testException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).variables(testVariables).build();
+ thrown.expect(hasProperty("variables", sameBeanAs(testVariables)));
+ BPMNFailureException testException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,
+ ErrorNumbers.SVC_BAD_PARAMETER).variables(testVariables).build();
throw testException;
}
@@ -81,33 +80,40 @@ public class ApiExceptionTest extends BaseTest {
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
thrown.expect(hasProperty("cause", sameBeanAs(ioException)));
- ClientConnectionException testException = new ClientConnectionException.Builder("test", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).cause(ioException).build();
+ ClientConnectionException testException =
+ new ClientConnectionException.Builder("test", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER)
+ .cause(ioException).build();
throw testException;
}
@Test
public void testDuplicateRequestException() throws ApiException {
- ErrorLoggerInfo testLog = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ ErrorLoggerInfo testLog =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
thrown.expect(DuplicateRequestException.class);
thrown.expectMessage(startsWith("Error: Locked instance"));
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
thrown.expect(hasProperty("errorLoggerInfo", sameBeanAs(testLog)));
- DuplicateRequestException testException = new DuplicateRequestException.Builder("Test1", "Test2","Test3","Test4", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(testLog).build();
+ DuplicateRequestException testException = new DuplicateRequestException.Builder("Test1", "Test2", "Test3",
+ "Test4", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(testLog).build();
throw testException;
}
@Test
public void testValidateException() throws ApiException {
-
+
thrown.expect(ValidateException.class);
thrown.expectMessage("Test Message");
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)));
- ValidateException testException = new ValidateException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).messageID(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).build();
+ ValidateException testException =
+ new ValidateException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER)
+ .messageID(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).build();
throw testException;
}
@@ -118,7 +124,9 @@ public class ApiExceptionTest extends BaseTest {
thrown.expectMessage("Test Message");
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_CONFLICT)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
- VfModuleNotFoundException testException = new VfModuleNotFoundException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).httpResponseCode(HttpStatus.SC_CONFLICT).build();
+ VfModuleNotFoundException testException =
+ new VfModuleNotFoundException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,
+ ErrorNumbers.SVC_BAD_PARAMETER).httpResponseCode(HttpStatus.SC_CONFLICT).build();
throw testException;
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java
index 170b305bb5..da37be98b2 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java
@@ -24,9 +24,7 @@ package org.onap.so.apihandlerinfra;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import javax.transaction.Transactional;
-
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
@@ -41,7 +39,6 @@ import org.springframework.core.env.Environment;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
-
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
@@ -52,42 +49,46 @@ import com.github.tomakehurst.wiremock.client.WireMock;
@Transactional
@AutoConfigureWireMock(port = 0)
public abstract class BaseTest {
- protected Logger logger = LoggerFactory.getLogger(BaseTest.class);
- protected TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
+ protected Logger logger = LoggerFactory.getLogger(BaseTest.class);
+ protected TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
+
+ @Autowired
+ protected Environment env;
+
+ @LocalServerPort
+ private int port;
+
+ @Autowired
+ protected WireMockServer wireMockServer;
+
+ protected String createURLWithPort(String uri) {
+ return "http://localhost:" + port + uri;
+ }
+
+ protected String createURLWithPort(String uri, int iPort) {
+ return "http://localhost:" + iPort + uri;
+ }
- @Autowired
- protected Environment env;
+ @After
+ public void tearDown() {
+ wireMockServer.resetAll();
+ }
- @LocalServerPort
- private int port;
-
- @Autowired
- protected WireMockServer wireMockServer;
-
- protected String createURLWithPort(String uri) {
- return "http://localhost:" + port + uri;
- }
-
- protected String createURLWithPort(String uri, int iPort) {
- return "http://localhost:" + iPort + uri;
- }
-
- @After
- public void tearDown(){
- wireMockServer.resetAll();
- }
+ public static String getResponseTemplate;
+ public static String getResponseTemplateNoBody;
+ public static String infraActivePost;
- public static String getResponseTemplate;
- public static String getResponseTemplateNoBody;
- public static String infraActivePost;
- @BeforeClass
- public static void setupTest() throws Exception {
- getResponseTemplate = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json")));
- getResponseTemplateNoBody = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json")));
- infraActivePost = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json")));
- }
+ @BeforeClass
+ public static void setupTest() throws Exception {
+ getResponseTemplate = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json")));
+ getResponseTemplateNoBody = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json")));
+ infraActivePost = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json")));
+ }
- public String getTestUrl(String requestId) {
- return "/infraActiveRequests/" + requestId;
- }
+ public String getTestUrl(String requestId) {
+ return "/infraActiveRequests/" + requestId;
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java
index e249c2d8ef..53982ca9d1 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java
@@ -1,4 +1,5 @@
package org.onap.so.apihandlerinfra;
+
/*-
* ============LICENSE_START=======================================================
* ONAP - SO
@@ -20,7 +21,6 @@ package org.onap.so.apihandlerinfra;
*/
import org.junit.Before;
import org.junit.Test;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterEnum;
@@ -33,36 +33,34 @@ import com.openpojo.validation.test.impl.SetterTester;
public class BeanMultiTest {
- Validator validator;
- PojoClassFilter enumFilter;
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
+ Validator validator;
+ PojoClassFilter enumFilter;
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ @Before
+ public void setup() {
+ enumFilter = new FilterEnum();
+ validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule())
+ .with(new SetterTester(), new GetterTester()).build();
+ }
+
+ @Test
+ public void validateBeansMsoApihandlerBeans() {
+ test("org.onap.so.apihandlerinfra.e2eserviceinstancebeans");
+ test("org.onap.so.apihandlerinfra.tasksbeans");
+ test("org.onap.so.apihandlerinfra.vnfbeans");
+ test("org.onap.so.apihandlerinfra.tenantisolationbeans");
+ test("org.onap.so.apihandlerinfra.workflowspecificationbeans");
+ }
- @Before
- public void setup(){
- enumFilter = new FilterEnum();
- validator = ValidatorBuilder.create()
- .with(new SetterMustExistRule(),
- new GetterMustExistRule())
- .with(new SetterTester(),
- new GetterTester())
- .build();
- }
- @Test
- public void validateBeansMsoApihandlerBeans() {
- test("org.onap.so.apihandlerinfra.e2eserviceinstancebeans");
- test("org.onap.so.apihandlerinfra.tasksbeans");
- test("org.onap.so.apihandlerinfra.vnfbeans");
- test("org.onap.so.apihandlerinfra.tenantisolationbeans");
- test("org.onap.so.apihandlerinfra.workflowspecificationbeans");
- }
+ private void test(String packageName) {
+ validator.validate(packageName, enumFilter, filterTestClasses);
- private void test(String packageName) {
- validator.validate(packageName, enumFilter, filterTestClasses);
+ }
- }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java
index 18eb46278d..7ddab572e3 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java
@@ -29,14 +29,11 @@ import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
@@ -50,224 +47,239 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.http.Fault;
public class E2EServiceInstancesTest extends BaseTest {
-private final ObjectMapper mapper = new ObjectMapper();
-
- private final String e2eServInstancesUri = "/onap/so/infra/e2eServiceInstances/";
-
-
- @Before
- public void init() throws JsonProcessingException {
- wireMockServer.stubFor(post(urlPathEqualTo("/testOrchestrationUri"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")).withRequestBody(equalToJson("{\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"Error parsing request: No valid requestorId is specified\",\"progress\":100,\"startTime\":1533541051247,\"endTime\":1533541051247,\"source\":null,\"vnfId\":null,\"vnfName\":null,\"vnfType\":null,\"serviceType\":null,\"aicNodeClli\":null,\"tenantId\":null,\"provStatus\":null,\"vnfParams\":null,\"vnfOutputs\":null,\"requestBody\":\"{\\r\\n \\\"service\\\":{\\r\\n \\\"name\\\":\\\"so_test4\\\",\\r\\n \\\"description\\\":\\\"so_test2\\\",\\r\\n \\\"serviceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561519\\\",\\r\\n \\\"serviceUuid\\\":\\\"592f9437-a9c0-4303-b9f6-c445bb7e9814\\\",\\r\\n \\\"globalSubscriberId\\\":\\\"123457\\\",\\r\\n \\\"serviceType\\\":\\\"voLTE\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"resources\\\":[\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vIMS\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vBAS-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vMME-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vEPC\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"61c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"62c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-CSCF-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad1\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"underlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561513\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561514\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"overlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561517\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561518\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n }\\r\\n ],\\r\\n \\\"requestInputs\\\":{\\r\\n \\\"externalDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"m6000_mng_ip\\\":\\\"181.18.20.2\\\",\\r\\n \\\"externalCompanyFtpDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"externalPluginManageNetworkName\\\":\\\"plugin_net_2014\\\",\\r\\n \\\"externalManageNetworkName\\\":\\\"mng_net_2017\\\",\\r\\n \\\"sfc_data_network\\\":\\\"sfc_data_net_2016\\\",\\r\\n \\\"NatIpRange\\\":\\\"210.1.1.10-210.1.1.20\\\",\\r\\n \\\"location\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\",\\r\\n \\\"sdncontroller\\\":\\\"9b9f02c0-298b-458a-bc9c-be3692e4f35e\\\"\\r\\n }\\r\\n }\\r\\n\\r\\n }\\r\\n\\r\\n}\",\"responseBody\":null,\"lastModifiedBy\":\"APIH\",\"modifyTime\":null,\"requestType\":null,\"volumeGroupId\":null,\"volumeGroupName\":null,\"vfModuleId\":null,\"vfModuleName\":null,\"vfModuleModelName\":null,\"aaiServiceId\":null,\"aicCloudRegion\":null,\"callBackUrl\":null,\"correlator\":null,\"serviceInstanceId\":null,\"serviceInstanceName\":null,\"requestScope\":\"service\",\"requestAction\":\"createInstance\",\"networkId\":null,\"networkName\":null,\"networkType\":null,\"requestorId\":null,\"configurationId\":null,\"configurationName\":null,\"operationalEnvId\":null,\"operationalEnvName\":null,\"requestURI\":\"d167c9d0-1785-4e93-b319-996ebbcc3272\"}")).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- Service defaultService = new Service();
- defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- ServiceRecipe serviceRecipe = new ServiceRecipe();
- serviceRecipe.setServiceModelUUID(defaultService.getModelUUID());
- serviceRecipe.setAction(Action.scaleInstance.name());
- serviceRecipe.setRecipeTimeout(180);
- serviceRecipe.setOrchestrationUri("/testOrchestrationUri");
-
- wireMockServer.stubFor(get(urlPathEqualTo("/service/search/findFirstByModelNameOrderByModelVersionDesc"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo("/serviceRecipe/search/findFirstByServiceModelUUIDAndAction"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
-
- }
- public String inputStream(String JsonInput)throws IOException{
- JsonInput = "src/test/resources/E2EServiceInstancesTest" + JsonInput;
- return new String(Files.readAllBytes(Paths.get(JsonInput)));
- }
- public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod){
- HttpHeaders headers = new HttpHeaders();
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type",MediaType.APPLICATION_JSON);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath));
- HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
-
- return restTemplate.exchange(builder.toUriString(),
- reqMethod, request, String.class);
- }
-
- @Test
- public void createE2EServiceInstanceNoRequestInfo() throws IOException{
- String uri = e2eServInstancesUri + "v3";
- ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
- }
- @Test
- public void updateE2EServiceInstanceJSONMappingError() throws IOException{
- String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e";
- ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.PUT);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
- RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
- assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed"));
- }
- @Test
- public void updateE2EServiceInstanceNoRequestorId() throws IOException{
- RequestError expectedResponse = new RequestError();
- ServiceException exception = new ServiceException();
- exception.setMessageId("SVC0002");
- exception.setText("Error parsing request. Error parsing request: No valid requestorId is specified");
- expectedResponse.setServiceException(exception);
-
- String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e";
- ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
- RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
- assertThat(realResponse, sameBeanAs(expectedResponse));
- }
- @Test
- public void deleteE2EServiceInstance() throws IOException{
- RequestError expectedResponse = new RequestError();
- ServiceException exception = new ServiceException();
- exception.setMessageId("SVC1000");
- exception.setText("No communication to catalog DB null");
- expectedResponse.setServiceException(exception);
-
- String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e";
- ResponseEntity<String> response = sendRequest(inputStream("/DeleteRequest.json"), uri, HttpMethod.DELETE);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
- }
- @Test
- public void deleteE2EServiceInstanceNotValid() throws IOException{
- String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e";
- ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.DELETE);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
- RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
- assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed"));
- }
- @Test
- public void getE2EServiceInstanceNullOperationalStatus() throws IOException{
- String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/operations/9b9f02c0-298b-458a-bc9c-be3692e4f35e";
- wireMockServer.stubFor(get(urlPathEqualTo("/operationStatus/search/findOneByServiceIdAndOperationId"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.GET);
-
- assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatusCode().value());
- }
- @Test
- public void scaleE2EServiceInstanceMappingError() throws IOException{
- String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale";
- ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
- RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
- assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed"));
- }
- @Test
- public void scaleE2EServiceInstance() throws IOException{
- String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale";
- ResponseEntity<String> response = sendRequest(inputStream("/ScaleRequest.json"), uri, HttpMethod.POST);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
- }
-
- @Test
- public void updateE2EServiceInstance() throws IOException{
- String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e";
- ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT);
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
- }
-
- @Test
- public void getE2EServiceInstance() throws IOException{
- OperationStatus status = new OperationStatus();
- status.setOperationId("operationId");
- status.setServiceId("9b9f02c0-298b-458a-bc9c-be3692e4f35e");
- wireMockServer.stubFor(get(urlPathEqualTo("/operationStatus/search/findOneByServiceIdAndOperationId"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(status))
- .withStatus(HttpStatus.SC_OK)));
- String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e/operations/operationId";
- ResponseEntity<String> response = sendRequest("", uri, HttpMethod.GET);
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- }
- @Test
- public void compareModelWithTargetVersionBadRequest() throws IOException{
- String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences";
- ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST);
-
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
- RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
- assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed"));
- }
- @Test
- public void compareModelWithTargetVersion() throws IOException{
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("Camunda/SuccessfulResponse.json").withStatus(org.apache.http.HttpStatus.SC_ACCEPTED)));
-
- String expectedResponse = "success";
- String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences";
- ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST);
-
- assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
- String actualResponse = response.getBody();
- assertEquals(expectedResponse, actualResponse);
- }
- @Test
- public void compareModelWithTargetVersionEmptyResponse() throws IOException{
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance"))
- .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));
-
- RequestError expectedResponse = new RequestError();
- ServiceException exception = new ServiceException();
- exception.setMessageId("SVC1000");
- exception.setText("Failed calling bpmn localhost:" + env.getProperty("wiremock.server.port") + " failed to respond");
- expectedResponse.setServiceException(exception);
-
- String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences";
- ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST);
-
- assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value());
- RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
- assertThat(realResponse, sameBeanAs(expectedResponse));
- }
- @Test
- public void compareModelWithTargetVersionBadBpelResponse() throws IOException{
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY)));
-
- String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences";
- ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST);
-
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
- assertTrue(realResponse.getServiceException().getText().contains("Request Failed due to BPEL error with HTTP Status"));
- }
- @Test
- public void compareModelWithTargetVersionNoBPELResponse() throws IOException{
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json")
- .withBody("{}").withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY)));
-
- String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences";
- ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST);
-
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
- RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
- assertTrue(realResponse.getServiceException().getText().contains("Request Failed due to BPEL error with HTTP Status"));
- }
-} \ No newline at end of file
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private final String e2eServInstancesUri = "/onap/so/infra/e2eServiceInstances/";
+
+
+ @Before
+ public void init() throws JsonProcessingException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/testOrchestrationUri")).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")).withRequestBody(equalToJson(
+ "{\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"Error parsing request: No valid requestorId is specified\",\"progress\":100,\"startTime\":1533541051247,\"endTime\":1533541051247,\"source\":null,\"vnfId\":null,\"vnfName\":null,\"vnfType\":null,\"serviceType\":null,\"aicNodeClli\":null,\"tenantId\":null,\"provStatus\":null,\"vnfParams\":null,\"vnfOutputs\":null,\"requestBody\":\"{\\r\\n \\\"service\\\":{\\r\\n \\\"name\\\":\\\"so_test4\\\",\\r\\n \\\"description\\\":\\\"so_test2\\\",\\r\\n \\\"serviceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561519\\\",\\r\\n \\\"serviceUuid\\\":\\\"592f9437-a9c0-4303-b9f6-c445bb7e9814\\\",\\r\\n \\\"globalSubscriberId\\\":\\\"123457\\\",\\r\\n \\\"serviceType\\\":\\\"voLTE\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"resources\\\":[\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vIMS\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vBAS-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vMME-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vEPC\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"61c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"62c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-CSCF-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad1\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"underlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561513\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561514\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"overlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561517\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561518\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n }\\r\\n ],\\r\\n \\\"requestInputs\\\":{\\r\\n \\\"externalDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"m6000_mng_ip\\\":\\\"181.18.20.2\\\",\\r\\n \\\"externalCompanyFtpDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"externalPluginManageNetworkName\\\":\\\"plugin_net_2014\\\",\\r\\n \\\"externalManageNetworkName\\\":\\\"mng_net_2017\\\",\\r\\n \\\"sfc_data_network\\\":\\\"sfc_data_net_2016\\\",\\r\\n \\\"NatIpRange\\\":\\\"210.1.1.10-210.1.1.20\\\",\\r\\n \\\"location\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\",\\r\\n \\\"sdncontroller\\\":\\\"9b9f02c0-298b-458a-bc9c-be3692e4f35e\\\"\\r\\n }\\r\\n }\\r\\n\\r\\n }\\r\\n\\r\\n}\",\"responseBody\":null,\"lastModifiedBy\":\"APIH\",\"modifyTime\":null,\"requestType\":null,\"volumeGroupId\":null,\"volumeGroupName\":null,\"vfModuleId\":null,\"vfModuleName\":null,\"vfModuleModelName\":null,\"aaiServiceId\":null,\"aicCloudRegion\":null,\"callBackUrl\":null,\"correlator\":null,\"serviceInstanceId\":null,\"serviceInstanceName\":null,\"requestScope\":\"service\",\"requestAction\":\"createInstance\",\"networkId\":null,\"networkName\":null,\"networkType\":null,\"requestorId\":null,\"configurationId\":null,\"configurationName\":null,\"operationalEnvId\":null,\"operationalEnvName\":null,\"requestURI\":\"d167c9d0-1785-4e93-b319-996ebbcc3272\"}"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+ Service defaultService = new Service();
+ defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ ServiceRecipe serviceRecipe = new ServiceRecipe();
+ serviceRecipe.setServiceModelUUID(defaultService.getModelUUID());
+ serviceRecipe.setAction(Action.scaleInstance.name());
+ serviceRecipe.setRecipeTimeout(180);
+ serviceRecipe.setOrchestrationUri("/testOrchestrationUri");
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/service/search/findFirstByModelNameOrderByModelVersionDesc"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/serviceRecipe/search/findFirstByServiceModelUUIDAndAction"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+
+ }
+
+ public String inputStream(String JsonInput) throws IOException {
+ JsonInput = "src/test/resources/E2EServiceInstancesTest" + JsonInput;
+ return new String(Files.readAllBytes(Paths.get(JsonInput)));
+ }
+
+ public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) {
+ HttpHeaders headers = new HttpHeaders();
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath));
+ HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
+
+ return restTemplate.exchange(builder.toUriString(), reqMethod, request, String.class);
+ }
+
+ @Test
+ public void createE2EServiceInstanceNoRequestInfo() throws IOException {
+ String uri = e2eServInstancesUri + "v3";
+ ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ }
+
+ @Test
+ public void updateE2EServiceInstanceJSONMappingError() throws IOException {
+ String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e";
+ ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.PUT);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
+ assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed"));
+ }
+
+ @Test
+ public void updateE2EServiceInstanceNoRequestorId() throws IOException {
+ RequestError expectedResponse = new RequestError();
+ ServiceException exception = new ServiceException();
+ exception.setMessageId("SVC0002");
+ exception.setText("Error parsing request. Error parsing request: No valid requestorId is specified");
+ expectedResponse.setServiceException(exception);
+
+ String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e";
+ ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
+ assertThat(realResponse, sameBeanAs(expectedResponse));
+ }
+
+ @Test
+ public void deleteE2EServiceInstance() throws IOException {
+ RequestError expectedResponse = new RequestError();
+ ServiceException exception = new ServiceException();
+ exception.setMessageId("SVC1000");
+ exception.setText("No communication to catalog DB null");
+ expectedResponse.setServiceException(exception);
+
+ String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e";
+ ResponseEntity<String> response = sendRequest(inputStream("/DeleteRequest.json"), uri, HttpMethod.DELETE);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ }
+
+ @Test
+ public void deleteE2EServiceInstanceNotValid() throws IOException {
+ String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e";
+ ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.DELETE);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
+ assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed"));
+ }
+
+ @Test
+ public void getE2EServiceInstanceNullOperationalStatus() throws IOException {
+ String uri = e2eServInstancesUri
+ + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/operations/9b9f02c0-298b-458a-bc9c-be3692e4f35e";
+ wireMockServer.stubFor(get(urlPathEqualTo("/operationStatus/search/findOneByServiceIdAndOperationId"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+ ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.GET);
+
+ assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatusCode().value());
+ }
+
+ @Test
+ public void scaleE2EServiceInstanceMappingError() throws IOException {
+ String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale";
+ ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
+ assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed"));
+ }
+
+ @Test
+ public void scaleE2EServiceInstance() throws IOException {
+ String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale";
+ ResponseEntity<String> response = sendRequest(inputStream("/ScaleRequest.json"), uri, HttpMethod.POST);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ }
+
+ @Test
+ public void updateE2EServiceInstance() throws IOException {
+ String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e";
+ ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT);
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ }
+
+ @Test
+ public void getE2EServiceInstance() throws IOException {
+ OperationStatus status = new OperationStatus();
+ status.setOperationId("operationId");
+ status.setServiceId("9b9f02c0-298b-458a-bc9c-be3692e4f35e");
+ wireMockServer.stubFor(get(urlPathEqualTo("/operationStatus/search/findOneByServiceIdAndOperationId"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(status)).withStatus(HttpStatus.SC_OK)));
+ String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e/operations/operationId";
+ ResponseEntity<String> response = sendRequest("", uri, HttpMethod.GET);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ }
+
+ @Test
+ public void compareModelWithTargetVersionBadRequest() throws IOException {
+ String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences";
+ ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
+ assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed"));
+ }
+
+ @Test
+ public void compareModelWithTargetVersion() throws IOException {
+ wireMockServer.stubFor(
+ post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")).willReturn(aResponse()
+ .withHeader("Content-Type", "application/json").withBodyFile("Camunda/SuccessfulResponse.json")
+ .withStatus(org.apache.http.HttpStatus.SC_ACCEPTED)));
+
+ String expectedResponse = "success";
+ String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences";
+ ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST);
+
+ assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
+ String actualResponse = response.getBody();
+ assertEquals(expectedResponse, actualResponse);
+ }
+
+ @Test
+ public void compareModelWithTargetVersionEmptyResponse() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance"))
+ .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));
+
+ RequestError expectedResponse = new RequestError();
+ ServiceException exception = new ServiceException();
+ exception.setMessageId("SVC1000");
+ exception.setText(
+ "Failed calling bpmn localhost:" + env.getProperty("wiremock.server.port") + " failed to respond");
+ expectedResponse.setServiceException(exception);
+
+ String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences";
+ ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST);
+
+ assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value());
+ RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
+ assertThat(realResponse, sameBeanAs(expectedResponse));
+ }
+
+ @Test
+ public void compareModelWithTargetVersionBadBpelResponse() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withBodyFile("Camunda/TestResponse.json")
+ .withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY)));
+
+ String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences";
+ ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST);
+
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
+ assertTrue(realResponse.getServiceException().getText()
+ .contains("Request Failed due to BPEL error with HTTP Status"));
+ }
+
+ @Test
+ public void compareModelWithTargetVersionNoBPELResponse() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{}")
+ .withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY)));
+
+ String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences";
+ ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST);
+
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
+ RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
+ assertTrue(realResponse.getServiceException().getText()
+ .contains("Request Failed due to BPEL error with HTTP Status"));
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java
index 1e4b99d4ff..5d0fb298d9 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.apihandlerinfra;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
-
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
@@ -36,17 +36,14 @@ import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
-
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration
@Profile({"test"})
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "entityManagerFactory",
- basePackages = {"org.onap.so.db.catalog.data.repository"}
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory",
+ basePackages = {"org.onap.so.db.catalog.data.repository"})
public class EmbeddedCatalogDbConfig {
@Bean
@@ -54,49 +51,36 @@ public class EmbeddedCatalogDbConfig {
return new MariaDB4jSpringService();
}
- @Primary
- @Bean(name = "dataSource")
+ @Primary
+ @Bean(name = "dataSource")
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
-
- @Primary
- @Bean(name = "entityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("dataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.catalog.beans")
- .persistenceUnit("catalogDB")
- .build();
- }
- @Primary
- @Bean(name = "transactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("entityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
+ @Primary
+ @Bean(name = "entityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("dataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.catalog.beans").persistenceUnit("catalogDB")
+ .build();
+ }
+
+ @Primary
+ @Bean(name = "transactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java
index 00efb6b410..0ec06177c8 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java
@@ -19,10 +19,10 @@
*/
package org.onap.so.apihandlerinfra;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
-
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
@@ -37,17 +37,14 @@ import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
-
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration
@Profile({"test"})
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager",
- basePackages = { "org.onap.so.db.request.data.repository" }
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory",
+ transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"})
public class EmbeddedRequestDbConfig {
@Bean
@@ -56,47 +53,34 @@ public class EmbeddedRequestDbConfig {
}
- @Bean(name = "requestDataSource")
- @ConfigurationProperties(prefix = "request.datasource")
+ @Bean(name = "requestDataSource")
+ @ConfigurationProperties(prefix = "request.datasource")
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName2}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName2}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
- @Bean(name = "requestEntityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("requestDataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.request.beans")
- .persistenceUnit("requestDB")
- .build();
- }
+ @Bean(name = "requestEntityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("requestDataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB")
+ .build();
+ }
- @Bean(name = "requestTransactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("requestEntityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
+ @Bean(name = "requestTransactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java
index 45fadb540a..928b488f6a 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java
@@ -25,18 +25,15 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
-
import static org.mockito.ArgumentMatchers.anyObject;
import static org.mockito.ArgumentMatchers.anyString;
import java.net.URI;
import java.util.Collections;
import java.util.List;
-
import org.springframework.test.util.ReflectionTestUtils;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
-
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
@@ -62,175 +59,170 @@ public class GlobalHealthcheckHandlerTest {
@Mock
ContainerRequestContext requestContext;
-
+
@InjectMocks
@Spy
- GlobalHealthcheckHandler globalhealth;
-
- @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
-
+ GlobalHealthcheckHandler globalhealth;
+
+ @Rule
+ public MockitoRule mockitoRule = MockitoJUnit.rule();
+
+ @Test
+ public void testQuerySubsystemHealthNullResult() {
+ ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage");
+ ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8080");
+
+ Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class),
+ ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(null);
+
+ String result = globalhealth.querySubsystemHealth(MsoSubsystems.BPMN);
+ System.out.println(result);
+ assertEquals(HealthcheckStatus.DOWN.toString(), result);
+ }
+
+ @Test
+ public void testQuerySubsystemHealthNotNullResult() {
+ ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage");
+ ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080");
+
+ SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse();
+ subSystemResponse.setStatus("UP");
+ ResponseEntity<Object> r = new ResponseEntity<>(subSystemResponse, HttpStatus.OK);
+
+ Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class),
+ ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(r);
+
+ String result = globalhealth.querySubsystemHealth(MsoSubsystems.ASDC);
+ System.out.println(result);
+ assertEquals(HealthcheckStatus.UP.toString(), result);
+ }
+
+ private Response globalHealthcheck(String status) {
+ ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage");
+ ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080");
+ ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081");
+ ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082");
+ ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083");
+ ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084");
+ ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085");
+ ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086");
+
+ SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse();
+
+ subSystemResponse.setStatus(status);
+ ResponseEntity<Object> r = new ResponseEntity<>(subSystemResponse, HttpStatus.OK);
+ Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class),
+ ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(r);
+
+ Mockito.when(requestContext.getProperty(anyString())).thenReturn("1234567890");
+ Response response = globalhealth.globalHealthcheck(true, requestContext);
+
+ return response;
+ }
+
+ @Test
+ public void globalHealthcheckAllUPTest() throws JSONException {
+ Response response = globalHealthcheck("UP");
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+ HealthcheckResponse root;
+ root = (HealthcheckResponse) response.getEntity();
+ String apistatus = root.getApih();
+ assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
+
+ String bpmnstatus = root.getBpmn();
+ assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
+
+ String sdncstatus = root.getSdncAdapter();
+ assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
+
+ String asdcstatus = root.getAsdcController();
+ assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
+
+ String catastatus = root.getCatalogdbAdapter();
+ assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
+
+ String reqdbstatus = root.getRequestdbAdapter();
+ assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
+
+ String openstatus = root.getOpenstackAdapter();
+ assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
+
+ String reqdbattstatus = root.getRequestdbAdapterAttsvc();
+ assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
+ }
+
+ @Test
+ public void globalHealthcheckAllDOWNTest() throws JSONException {
+ Response response = globalHealthcheck("DOWN");
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+ HealthcheckResponse root;
+ root = (HealthcheckResponse) response.getEntity();
+ String apistatus = root.getApih();
+ assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
+
+ String bpmnstatus = root.getBpmn();
+ assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
+
+ String sdncstatus = root.getSdncAdapter();
+ assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
+
+ String asdcstatus = root.getAsdcController();
+ assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
+
+ String catastatus = root.getCatalogdbAdapter();
+ assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
+
+ String reqdbstatus = root.getRequestdbAdapter();
+ assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
+
+ String openstatus = root.getOpenstackAdapter();
+ assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
+
+ String reqdbattstatus = root.getRequestdbAdapterAttsvc();
+ assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
+ }
+
@Test
- public void testQuerySubsystemHealthNullResult(){
- ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage");
- ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8080");
-
- Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class),
- ArgumentMatchers.any(HttpMethod.class),
- ArgumentMatchers.<HttpEntity<?>> any(),
- ArgumentMatchers.<Class<Object>> any())).thenReturn(null);
-
- String result = globalhealth.querySubsystemHealth(MsoSubsystems.BPMN);
- System.out.println(result);
- assertEquals(HealthcheckStatus.DOWN.toString(),result);
+ public void buildHttpEntityForRequestTest() {
+ HttpEntity<String> he = globalhealth.buildHttpEntityForRequest();
+ assertEquals(MediaType.APPLICATION_JSON, he.getHeaders().getAccept().get(0));
+ assertEquals(MediaType.APPLICATION_JSON, he.getHeaders().getContentType());
}
-
+
@Test
- public void testQuerySubsystemHealthNotNullResult(){
- ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage");
- ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080");
-
- SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse();
- subSystemResponse.setStatus("UP");
- ResponseEntity<Object> r = new ResponseEntity<>(subSystemResponse,HttpStatus.OK);
-
- Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class),
- ArgumentMatchers.any(HttpMethod.class),
- ArgumentMatchers.<HttpEntity<?>> any(),
- ArgumentMatchers.<Class<Object>> any())).thenReturn(r);
-
- String result = globalhealth.querySubsystemHealth(MsoSubsystems.ASDC);
- System.out.println(result);
- assertEquals(HealthcheckStatus.UP.toString(),result);
+ public void getEndpointUrlForSubsystemEnumTest() {
+ ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage");
+ ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080");
+ ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081");
+ ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082");
+ ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083");
+ ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084");
+ ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085");
+ ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086");
+
+ String result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.ASDC);
+ assertEquals("http://localhost:8080", result);
+ result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.SDNC);
+ assertEquals("http://localhost:8081", result);
+ result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.BPMN);
+ assertEquals("http://localhost:8082", result);
+ result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.CATALOGDB);
+ assertEquals("http://localhost:8083", result);
+ result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.OPENSTACK);
+ assertEquals("http://localhost:8084", result);
+ result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDB);
+ assertEquals("http://localhost:8085", result);
+ result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDBATT);
+ assertEquals("http://localhost:8086", result);
}
-
- private Response globalHealthcheck (String status){
- ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage");
- ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080");
- ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081");
- ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082");
- ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083");
- ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084");
- ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085");
- ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086");
-
- SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse();
-
- subSystemResponse.setStatus(status);
- ResponseEntity<Object> r = new ResponseEntity<>(subSystemResponse,HttpStatus.OK);
- Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class),
- ArgumentMatchers.any(HttpMethod.class),
- ArgumentMatchers.<HttpEntity<?>> any(),
- ArgumentMatchers.<Class<Object>> any())).thenReturn(r);
-
- Mockito.when(requestContext.getProperty(anyString())).thenReturn("1234567890");
- Response response = globalhealth.globalHealthcheck(true, requestContext);
-
- return response;
+
+ @Test
+ public void processResponseFromSubsystemTest() {
+ SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse();
+ subSystemResponse.setStatus("UP");
+ ResponseEntity<SubsystemHealthcheckResponse> r = new ResponseEntity<>(subSystemResponse, HttpStatus.OK);
+ String result = globalhealth.processResponseFromSubsystem(r, MsoSubsystems.BPMN);
+ assertEquals("UP", result);
}
-
- @Test
- public void globalHealthcheckAllUPTest() throws JSONException {
- Response response = globalHealthcheck("UP");
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatus());
- HealthcheckResponse root;
- root = (HealthcheckResponse) response.getEntity();
- String apistatus = root.getApih();
- assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
- String bpmnstatus = root.getBpmn();
- assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
- String sdncstatus = root.getSdncAdapter();
- assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
- String asdcstatus = root.getAsdcController();
- assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
- String catastatus = root.getCatalogdbAdapter();
- assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
- String reqdbstatus = root.getRequestdbAdapter();
- assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
- String openstatus = root.getOpenstackAdapter();
- assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
- String reqdbattstatus = root.getRequestdbAdapterAttsvc();
- assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
- }
-
- @Test
- public void globalHealthcheckAllDOWNTest() throws JSONException {
- Response response = globalHealthcheck("DOWN");
- assertEquals(Response.Status.OK.getStatusCode(),response.getStatus());
- HealthcheckResponse root;
- root = (HealthcheckResponse) response.getEntity();
- String apistatus = root.getApih();
- assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
- String bpmnstatus = root.getBpmn();
- assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
-
- String sdncstatus = root.getSdncAdapter();
- assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
-
- String asdcstatus = root.getAsdcController();
- assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
-
- String catastatus = root.getCatalogdbAdapter();
- assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
-
- String reqdbstatus = root.getRequestdbAdapter();
- assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
-
- String openstatus = root.getOpenstackAdapter();
- assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
-
- String reqdbattstatus = root.getRequestdbAdapterAttsvc();
- assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
- }
-
- @Test
- public void buildHttpEntityForRequestTest(){
- HttpEntity<String> he = globalhealth.buildHttpEntityForRequest();
- assertEquals (MediaType.APPLICATION_JSON,he.getHeaders().getAccept().get(0));
- assertEquals (MediaType.APPLICATION_JSON,he.getHeaders().getContentType());
- }
-
- @Test
- public void getEndpointUrlForSubsystemEnumTest(){
- ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage");
- ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080");
- ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081");
- ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082");
- ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083");
- ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084");
- ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085");
- ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086");
-
- String result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.ASDC);
- assertEquals("http://localhost:8080", result);
- result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.SDNC);
- assertEquals("http://localhost:8081", result);
- result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.BPMN);
- assertEquals("http://localhost:8082", result);
- result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.CATALOGDB);
- assertEquals("http://localhost:8083", result);
- result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.OPENSTACK);
- assertEquals("http://localhost:8084", result);
- result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDB);
- assertEquals("http://localhost:8085", result);
- result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDBATT);
- assertEquals("http://localhost:8086", result);
- }
-
- @Test
- public void processResponseFromSubsystemTest(){
- SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse();
- subSystemResponse.setStatus("UP");
- ResponseEntity<SubsystemHealthcheckResponse> r = new ResponseEntity<>(subSystemResponse,HttpStatus.OK);
- String result = globalhealth.processResponseFromSubsystem(r,MsoSubsystems.BPMN);
- assertEquals("UP",result);
- }
-
-} \ No newline at end of file
+
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java
index e694120405..9fc9e4a51b 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java
@@ -32,17 +32,14 @@ import static org.junit.Assert.assertThat;
import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID;
import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID;
import static org.onap.so.logger.MdcConstants.CLIENT_ID;
-
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
@@ -57,17 +54,16 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class InstanceManagementTest extends BaseTest{
+public class InstanceManagementTest extends BaseTest {
+
+ private final ObjectMapper mapper = new ObjectMapper();
+ private ObjectMapper errorMapper = new ObjectMapper();
- private final ObjectMapper mapper = new ObjectMapper();
- private ObjectMapper errorMapper = new ObjectMapper();
-
@Value("${wiremock.server.port}")
- private String wiremockPort;
+ private String wiremockPort;
private final String instanceManagementUri = "/onap/so/infra/instanceManagement/";
@@ -77,99 +73,102 @@ public class InstanceManagementTest extends BaseTest{
private int initialPort;
private HttpHeaders headers;
- @Before
- public void beforeClass() {
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
+ @Before
+ public void beforeClass() {
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
// set headers
- headers = new HttpHeaders();
- headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name");
- headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
+ headers = new HttpHeaders();
+ headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name");
+ headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
headers.set(CLIENT_ID, "VID");
headers.set(REQUESTOR_ID, "xxxxxx");
- try { // generate one-time port number to avoid RANDOM port number later.
- initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH));
- initialPort = initialUrl.getPort();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public String inputStream(String JsonInput)throws IOException{
+ try { // generate one-time port number to avoid RANDOM port number later.
+ initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH));
+ initialPort = initialUrl.getPort();
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests.*")).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public String inputStream(String JsonInput) throws IOException {
JsonInput = "src/test/resources/ServiceInstanceTest" + JsonInput;
return new String(Files.readAllBytes(Paths.get(JsonInput)));
}
private URL createExpectedSelfLink(String version, String requestId) {
- System.out.println("createdUrl: " + initialUrl.toString());
- try {
- selfLink = new URL(initialUrl.toString().concat("/").concat(version).concat("/").concat(requestId));
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- return selfLink;
+ System.out.println("createdUrl: " + initialUrl.toString());
+ try {
+ selfLink = new URL(initialUrl.toString().concat("/").concat(version).concat("/").concat(requestId));
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ return selfLink;
}
-
- private String getWiremockResponseForCatalogdb(String file) {
- try {
- File resource= ResourceUtils.getFile("classpath:__files/catalogdb/"+file);
- return new String(Files.readAllBytes(resource.toPath())).replaceAll("localhost:8090","localhost:"+wiremockPort);
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- }
-
- }
-
- public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod, HttpHeaders headers){
-
- if (!headers.containsKey(HttpHeaders.ACCEPT)) {
- headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
- }
- if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
- headers.set(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON);
- }
+
+ private String getWiremockResponseForCatalogdb(String file) {
+ try {
+ File resource = ResourceUtils.getFile("classpath:__files/catalogdb/" + file);
+ return new String(Files.readAllBytes(resource.toPath())).replaceAll("localhost:8090",
+ "localhost:" + wiremockPort);
+ } catch (IOException e) {
+ e.printStackTrace();
+ return null;
+ }
+
+ }
+
+ public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod,
+ HttpHeaders headers) {
+
+ if (!headers.containsKey(HttpHeaders.ACCEPT)) {
+ headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
+ }
+ if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
+ headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
+ }
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath, initialPort));
HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
- return restTemplate.exchange(builder.toUriString(),
- reqMethod, request, String.class);
+ return restTemplate.exchange(builder.toUriString(), reqMethod, request, String.class);
}
-
- public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod){
- return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders());
+
+ public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) {
+ return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders());
}
@Test
public void executeCustomWorkflow() throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/testingWorkflow"))
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/testingWorkflow"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/workflow/search/findByArtifactUUID[?]artifactUUID=71526781-e55c-4cb7-adb3-97e09d9c76be"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("workflow_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/workflow/search/findByArtifactUUID[?]artifactUUID=71526781-e55c-4cb7-adb3-97e09d9c76be"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("workflow_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v1","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v1", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = instanceManagementUri + "v1" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/workflows/71526781-e55c-4cb7-adb3-97e09d9c76be";
- ResponseEntity<String> response = sendRequest(inputStream("/ExecuteCustomWorkflow.json"), uri, HttpMethod.POST, headers);
+ uri = instanceManagementUri + "v1"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/workflows/71526781-e55c-4cb7-adb3-97e09d9c76be";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ExecuteCustomWorkflow.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java
index a22e61e75f..ad0a878931 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java
@@ -27,7 +27,6 @@ import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static org.onap.so.logger.MdcConstants.ECOMP_REQUEST_ID;
import static org.onap.so.logger.MdcConstants.ENDTIME;
@@ -38,13 +37,10 @@ import static org.onap.so.logger.MdcConstants.RESPONSEDESC;
import static org.onap.so.logger.MdcConstants.SERVICE_NAME;
import static org.onap.so.logger.MdcConstants.STATUSCODE;
import static org.onap.so.logger.MdcConstants.CLIENT_ID;
-
import java.io.IOException;
import java.util.Map;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.junit.Test;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
@@ -60,15 +56,13 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.http.Fault;
-
import ch.qos.logback.classic.spi.ILoggingEvent;
-public class ManualTasksTest extends BaseTest{
+public class ManualTasksTest extends BaseTest {
private final String basePath = "/tasks/v1/";
@@ -83,14 +77,14 @@ public class ManualTasksTest extends BaseTest{
RequestDetails reqDetail = new RequestDetails();
RequestInfo reqInfo = new RequestInfo();
reqInfo.setRequestorId("testId");
- reqInfo.setSource("testSource");
+ reqInfo.setSource("testSource");
reqInfo.setResponseValue(ValidResponses.skip);
reqDetail.setRequestInfo(reqInfo);
taskReq.setRequestDetails(reqDetail);
- //expected response
+ // expected response
TaskRequestReference expectedResponse = new TaskRequestReference();
- expectedResponse.setTaskId(taskId);
+ expectedResponse.setTaskId(taskId);
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON);
headers.set("Content-Type", MediaType.APPLICATION_JSON);
@@ -98,10 +92,10 @@ public class ManualTasksTest extends BaseTest{
headers.set(CLIENT_ID, "VID");
HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete");
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete");
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
ObjectMapper mapper = new ObjectMapper();
@@ -111,32 +105,31 @@ public class ManualTasksTest extends BaseTest{
TaskRequestReference realResponse = mapper.readValue(response.getBody(), TaskRequestReference.class);
- //then
- assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
- assertThat(realResponse, sameBeanAs(expectedResponse));
-
- for(ILoggingEvent logEvent : TestAppender.events)
- if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") &&
- logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")
- ){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+ // then
+ assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
+ assertThat(realResponse, sameBeanAs(expectedResponse));
+
+ for (ILoggingEvent logEvent : TestAppender.events)
+ if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging")
+ && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
assertNotNull(mdc.get(INVOCATION_ID));
- assertEquals("UNKNOWN",mdc.get(PARTNERNAME));
- assertEquals("tasks/v1/55/complete",mdc.get(SERVICE_NAME));
- assertEquals("INPROGRESS",mdc.get(STATUSCODE));
- }else if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") &&
- logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+ assertEquals("UNKNOWN", mdc.get(PARTNERNAME));
+ assertEquals("tasks/v1/55/complete", mdc.get(SERVICE_NAME));
+ assertEquals("INPROGRESS", mdc.get(STATUSCODE));
+ } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging")
+ && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP));
assertNotNull(mdc.get(ENDTIME));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
assertNotNull(mdc.get(INVOCATION_ID));
- assertEquals("202",mdc.get(RESPONSECODE));
- assertEquals("UNKNOWN",mdc.get(PARTNERNAME));
- assertEquals("tasks/v1/55/complete",mdc.get(SERVICE_NAME));
- assertEquals("COMPLETE",mdc.get(STATUSCODE));
+ assertEquals("202", mdc.get(RESPONSECODE));
+ assertEquals("UNKNOWN", mdc.get(PARTNERNAME));
+ assertEquals("tasks/v1/55/complete", mdc.get(SERVICE_NAME));
+ assertEquals("COMPLETE", mdc.get(STATUSCODE));
assertNotNull(mdc.get(RESPONSEDESC));
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0));
@@ -144,6 +137,7 @@ public class ManualTasksTest extends BaseTest{
assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0));
}
}
+
@Test
public void completeTaskMappingError() throws IOException {
String invalidRequest = "test";
@@ -151,9 +145,9 @@ public class ManualTasksTest extends BaseTest{
ServiceException se = new ServiceException();
se.setMessageId("SVC0002");
se.setText("Mapping of request to JSON object failed: Unrecognized token \'test\': "
- + "was expecting \'null\', \'true\', \'false\' or NaN\n at [Source: (String)\"test\"; line: 1, column: 9]");
+ + "was expecting \'null\', \'true\', \'false\' or NaN\n at [Source: (String)\"test\"; line: 1, column: 9]");
expectedResponse.setServiceException(se);
-
+
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON);
headers.set("Content-Type", MediaType.APPLICATION_JSON);
@@ -161,26 +155,27 @@ public class ManualTasksTest extends BaseTest{
headers.set(CLIENT_ID, "VID");
HttpEntity<String> entity = new HttpEntity<String>(invalidRequest, headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + "55" + "/complete");
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + "55" + "/complete");
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-
+
RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
assertThat(realResponse, sameBeanAs(expectedResponse));
}
+
@Test
public void completeTaskValidationError() throws IOException {
String taskId = "55";
TasksRequest taskReq = new TasksRequest();
RequestDetails reqDetail = new RequestDetails();
RequestInfo reqInfo = new RequestInfo();
- reqInfo.setSource("testSource");
+ reqInfo.setSource("testSource");
reqInfo.setResponseValue(ValidResponses.skip);
reqDetail.setRequestInfo(reqInfo);
taskReq.setRequestDetails(reqDetail);
@@ -197,30 +192,31 @@ public class ManualTasksTest extends BaseTest{
headers.set(CLIENT_ID, "VID");
HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete");
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete");
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
assertThat(realResponse, sameBeanAs(expectedResponse));
}
+
@Test
public void completeTaskBpelResponseError() throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo("/sobpmnengine/task/55/complete"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withFault(Fault.EMPTY_RESPONSE)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/sobpmnengine/task/55/complete")).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withFault(Fault.EMPTY_RESPONSE)));
String taskId = "55";
TasksRequest taskReq = new TasksRequest();
RequestDetails reqDetail = new RequestDetails();
RequestInfo reqInfo = new RequestInfo();
reqInfo.setRequestorId("testId");
- reqInfo.setSource("testSource");
+ reqInfo.setSource("testSource");
reqInfo.setResponseValue(ValidResponses.skip);
reqDetail.setRequestInfo(reqInfo);
taskReq.setRequestDetails(reqDetail);
@@ -237,10 +233,10 @@ public class ManualTasksTest extends BaseTest{
headers.set(CLIENT_ID, "VID");
HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete");
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete");
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
ObjectMapper mapper = new ObjectMapper();
@@ -248,7 +244,7 @@ public class ManualTasksTest extends BaseTest{
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class);
- assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value());
+ assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value());
assertThat(realResponse, sameBeanAs(expectedResponse));
}
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java
index d6fff7bdfb..c30b9dedf2 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java
@@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
@@ -32,12 +31,10 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Optional;
-
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
-
import org.apache.http.HttpStatus;
import org.junit.ClassRule;
import org.junit.Rule;
@@ -49,11 +46,9 @@ import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.w3c.dom.Document;
@@ -61,463 +56,977 @@ import org.xml.sax.InputSource;
@RunWith(JUnitParamsRunner.class)
public class MsoRequestTest extends BaseTest {
- private ObjectMapper mapper = new ObjectMapper();
- private HashMap<String, String> instanceIdMapTest = new HashMap<String, String>();
- private ServiceInstancesRequest sir;
- private MsoRequest msoRequest;
- private Action action;
- private String version;
- private int reqVersion;
- private String originalRequestJSON;
- private String requestJSON;
- private boolean expected;
- private String expectedException;
-
- @ClassRule
+ private ObjectMapper mapper = new ObjectMapper();
+ private HashMap<String, String> instanceIdMapTest = new HashMap<String, String>();
+ private ServiceInstancesRequest sir;
+ private MsoRequest msoRequest;
+ private Action action;
+ private String version;
+ private int reqVersion;
+ private String originalRequestJSON;
+ private String requestJSON;
+ private boolean expected;
+ private String expectedException;
+
+ @ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- public String inputStream(String JsonInput)throws IOException{
- JsonInput = "src/test/resources/MsoRequestTest" + JsonInput;
- String input = new String(Files.readAllBytes(Paths.get(JsonInput)));
- return input;
- }
- //Tests for successful validation of incoming JSON requests through the parse method
- @Test
- @Parameters(method = "successParameters")
- public void successTest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMapTest, Action action, int reqVersion) throws ValidationException, IOException{
- this.sir = sir;
- this.instanceIdMapTest = instanceIdMapTest;
- this.action = action;
- this.reqVersion = reqVersion;
- this.version = "v" + reqVersion;
- this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
- this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
- this.instanceIdMapTest.put("vfModuleInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
- this.instanceIdMapTest.put("volumeGroupInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
- this.instanceIdMapTest.put("networkInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
- this.instanceIdMapTest.put("configurationInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
- this.msoRequest = new MsoRequest();
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- }
- @Parameters
- private Collection<Object[]> successParameters() throws JsonParseException, JsonMappingException, IOException{
- return Arrays.asList(new Object[][]{
- {mapper.readValue(inputStream("/CloudConfiguration/EmptyCloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "3"},
- {mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyOwningEntityName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "5"},
- {mapper.readValue(inputStream("/PlatformAndLineOfBusiness/OptionalLineOfBusiness.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"},
- {mapper.readValue(inputStream("/ProjectAndOwningEntity/OptionalProject.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"},
- {mapper.readValue(inputStream("/PlatformAndLineOfBusiness/PlatformTest.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"},
- {mapper.readValue(inputStream("/RequestInfo/EmptyRequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "3"},
- {mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyIdFlag.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"},
- {mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyIdUpdate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"},
- {mapper.readValue(inputStream("/ModelInfo/ModelCustomizationIdUsingPreload.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"},
- {mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdConfigurationDelete.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"},
- {mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "4"},
- {mapper.readValue(inputStream("/ModelInfo/ModelVersionNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"},
- {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationIdEmpty.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "5"},
- {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationNameNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"},
- {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationTest.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"},
- {mapper.readValue(inputStream("/ModelInfo/ServiceModelNameEmptyOnActivate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "2"},
- {mapper.readValue(inputStream("/ModelInfo/ServiceModelNameEmptyOnDelete.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "2"},
- {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "4"},
- {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"},
- {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationIdService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"},
- {mapper.readValue(inputStream("/RelatedInstances/RelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"},
- {mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "5"},
- {mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVfModule.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"},
- {mapper.readValue(inputStream("/SuccessfulValidation/ServiceInPlaceSoftwareUpdate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, "6"},
- {mapper.readValue(inputStream("/SuccessfulValidation/ServiceInPlaceSoftwareUpdate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, "6"},
- {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, "5"},
- {mapper.readValue(inputStream("/SuccessfulValidation/VnfActivate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "6"},
- {mapper.readValue(inputStream("/RequestParameters/VnfRequestParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "6"},
- {mapper.readValue(inputStream("/SuccessfulValidation/v3DeleteNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"},
- {mapper.readValue(inputStream("/SuccessfulValidation/v3UpdateNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "3"},
- {mapper.readValue(inputStream("/SuccessfulValidation/v5CreateConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "5"},
- {mapper.readValue(inputStream("/SuccessfulValidation/v6CreateConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"},
- {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, "5"},
- {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, "5"},
- {mapper.readValue(inputStream("/SuccessfulValidation/v5ActivateConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"},
- {mapper.readValue(inputStream("/RelatedInstances/v5ActivateNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"},
- {mapper.readValue(inputStream("/SuccessfulValidation/v5DeactivateConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "5"},
- {mapper.readValue(inputStream("/RelatedInstances/v5DeactivateNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "5"},
- {mapper.readValue(inputStream("/SuccessfulValidation/v6AddRelationships.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, "6"},
- {mapper.readValue(inputStream("/SuccessfulValidation/UserParams.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, "5"},
- {mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, "7"},
- {mapper.readValue(inputStream("/SuccessfulValidation/ServiceUnassign.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.unassignInstance, "7"}
- });
- }
- @Test
- @Parameters(method = "customWorkflowSuccessParameters")
- public void customWorkflowSuccessTest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMapTest, Action action, int reqVersion) throws ValidationException, IOException{
- this.sir = sir;
- this.instanceIdMapTest = instanceIdMapTest;
- this.action = action;
- this.reqVersion = reqVersion;
- this.version = "v" + reqVersion;
- this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
- this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
- this.instanceIdMapTest.put("workflowUuid", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
- this.msoRequest = new MsoRequest();
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- }
- @Parameters
- private Collection<Object[]> customWorkflowSuccessParameters() throws JsonParseException, JsonMappingException, IOException{
- return Arrays.asList(new Object[][]{
- {mapper.readValue(inputStream("/SuccessfulValidation/v1ExecuteCustomWorkflow.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, "1"}
-
- });
- }
- @Test
- @Parameters(method = "aLaCarteParameters")
- public void aLaCarteFlagTest(boolean expected, ServiceInstancesRequest sir) throws JsonParseException, IOException, ValidationException{
- this.expected = expected;
- this.sir = sir;
- this.msoRequest = new MsoRequest();
- assertEquals(expected, msoRequest.getAlacarteFlag(sir));
- }
- @Parameters
- private Collection<Object[]> aLaCarteParameters() throws IOException{
- return Arrays.asList(new Object[][] {
- {false, mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), ServiceInstancesRequest.class)},
- {true, mapper.readValue(inputStream("/RequestParameters/RequestParametersALaCarteTrue.json"), ServiceInstancesRequest.class)}
- });
- }
- //Tests various scenarios ensuring that requests containing missing or invalid information will throw a ValidationException
- @Test
- @Parameters(method = "validationParameters")
- public void validationFailureTest(String expectedException, ServiceInstancesRequest sir, HashMap<String,String> instanceIdMapTest, Action action, int reqVersion) throws JsonParseException, JsonMappingException, IOException, ValidationException{
- this.expectedException = expectedException;
- this.sir = sir;
- this.instanceIdMapTest = instanceIdMapTest;
- this.action = action;
- this.reqVersion = reqVersion;
- this.version = "v" + reqVersion;
- this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
- this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
- this.instanceIdMapTest.put("instanceGroupId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
- thrown.expect(ValidationException.class);
- thrown.expectMessage(expectedException);
- this.msoRequest = new MsoRequest();
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- }
- @Parameters
- private Collection<Object[]> validationParameters() throws IOException{
- return Arrays.asList(new Object[][] {
- //ValidationException for CloudConfiguration
- {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/CloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 4},
- {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 5},
- {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationConfig.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5},
- {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateCloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6},
- {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/DeactivateAndCloudDeleteCloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateAndCloudDelete, 7},
- {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/ScaleOutNoCloudConfig.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7},
- {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/VnfRecreateCloudConfig.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7},
- {"No valid lcpCloudRegionId is specified", mapper.readValue(inputStream("/CloudConfiguration/EmptyLcpCloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid lcpCloudRegionId is specified", mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateCloudRegionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6},
- {"No valid tenantId is specified", mapper.readValue(inputStream("/CloudConfiguration/EmptyTenantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid tenantId is specified", mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateTenantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6},
- //ValidationException for ModelInfo
- {"No valid modelCustomizationId is specified", mapper.readValue(inputStream("/ModelInfo/ModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 5},
- {"No valid modelCustomizationId is specified", mapper.readValue(inputStream("/ModelInfo/v5CreateConfigurationModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid modelCustomizationId is specified", mapper.readValue(inputStream("/ModelInfo/v4CreateVfModuleMissingModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 4},
- {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationIdPreload.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 5},
- {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/ModelCustomizationName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5},
- {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/ModelCustomization.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 6},
- {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/ModelCustomization.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 6},
- {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 5},
- {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateNoModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7},
- {"No valid modelCustomizationId is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7},
- {"No valid model-info is specified", mapper.readValue(inputStream("/ModelInfo/ModelInfoNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid modelInvariantId format is specified", mapper.readValue(inputStream("/ModelInfo/InvalidModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 2},
- {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/ModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, 4},
- {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/v5ModelInvariantIdNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5},
- {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/v5ModelInvariantIdDisablePort.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, 5},
- {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 3},
- {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 3},
- {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/v5DeactivateModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, 5},
- {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/v3UpdateNetworkBad.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 4},
- {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7},
- {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7},
- {"No valid modelName is specified", mapper.readValue(inputStream("/ModelInfo/VfModuleModelName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, 4},
- {"No valid modelName is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7},
- {"No valid modelName is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7},
- {"No valid modelType is specified", mapper.readValue(inputStream("/ModelInfo/ModelTypeNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 3},
- {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionVfModule.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 3},
- {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionServiceCreate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 3},
- {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelVersion.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7},
- {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelVersion.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7},
- {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/ConfigurationModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5},
- {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 4},
- {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, 4},
- {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 5},
- {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5},
- {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, 5},
- {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionIdCreate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v5ActivateModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5},
- {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7},
- {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7},
- {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/CreateInstanceGroupNoModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 7},
- //ValidationException for Platform and LineOfBusiness
- {"No valid lineOfBusinessName is specified", mapper.readValue(inputStream("/PlatformAndLineOfBusiness/EmptyLineOfBusiness.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid platform is specified", mapper.readValue(inputStream("/PlatformAndLineOfBusiness/Platform.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 6},
- {"No valid platformName is specified", mapper.readValue(inputStream("/PlatformAndLineOfBusiness/EmptyPlatformName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- //ValidationException for Project and OwningEntity
- {"No valid owningEntity is specified", mapper.readValue(inputStream("/ProjectAndOwningEntity/OwningEntity.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 6},
- {"No valid owningEntityId is specified", mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyOwningEntityId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid projectName is specified", mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyProjectName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid owningEntity is specified", mapper.readValue(inputStream("/ProjectAndOwningEntity/ServiceAssignNoOE.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- //ValidationException for RelatedInstances
- {"No valid connectionPoint relatedInstance for Port Configuration is specified", mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoConnectionPoint.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, 5},
- {"No valid connectionPoint relatedInstance for Port Configuration is specified", mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoConnectionPoint.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5},
- {"No valid destination vnf relatedInstance for Port Configuration is specified", mapper.readValue(inputStream("/RelatedInstances/v5CreateNoDestinationRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid instanceId format in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesIdFormat.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid instanceId in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid instanceName format in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesNameFormat.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid instanceName in relatedInstance for pnf modelType is specified", mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.removeRelationships, 6},
- {"No valid instanceName in relatedInstance for pnf modelType is specified", mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, 6},
- {"No valid modelCustomizationName or modelCustomizationId in relatedInstance of vnf is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5},
- {"No valid modelInfo in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid modelInvariantId format in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantIdFormat.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid modelInvariantId in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid modelName in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid modelType in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelType.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid modelVersion in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelVersion.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid modelVersionId in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/ServiceNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, 2},
- {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/ServiceNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.removeRelationships, 2},
- {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, 2},
- {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5},
- {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/v5CreateNoRelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/v4RelatedInstancesNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 4},
- {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/ScaleOutNoRelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7},
- {"No valid related service instance for vfModule request is specified", mapper.readValue(inputStream("/RelatedInstances/VfModuleRelatedInstancesService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5},
- {"No valid related service instance for vnf request is specified", mapper.readValue(inputStream("/RelatedInstances/VnfRelatedInstancesService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5},
- {"No valid related service instance for volumeGroup request is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesServiceInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5},
- {"No valid related vnf instance for vfModule request is specified", mapper.readValue(inputStream("/RelatedInstances/VfModuleRelatedInstancesVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5},
- {"No valid related vnf instance for volumeGroup request is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVnfInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5},
- {"No valid serviceInstanceId matching the serviceInstanceId in request URI is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesInstanceId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5},
- {"No valid serviceInstanceId matching the serviceInstanceId in request URI is specified", mapper.readValue(inputStream("/RelatedInstances/v6VnfDeleteInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, 6},
- {"No valid source vnf relatedInstance for Port Configuration is specified", mapper.readValue(inputStream("/RelatedInstances/v5CreateNoSourceRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid vnfInstanceId matching the vnfInstanceId in request URI is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVnfInstanceId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5},
- {"No valid instanceName format is specified", mapper.readValue(inputStream("/RelatedInstances/InvalidInstanceName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 2},
- {"No valid relatedInstanceList is specified", mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupNoRelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 7},
- {"No valid related service instance for instanceGroup request is specified", mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 7},
- {"No valid modelVersionId in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupRelatedInstanceModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 7},
- //ValidationException for RequestInfo
- {"No valid requestInfo is specified", mapper.readValue(inputStream("/RequestInfo/RequestInfoNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid requestInfo is specified", mapper.readValue(inputStream("/RequestInfo/RequestInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, 6},
- {"No valid requestInfo is specified", mapper.readValue(inputStream("/RequestInfo/RequestInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6},
- {"No valid requestInfo is specified", mapper.readValue(inputStream("/RequestInfo/ScaleOutNoRequestInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7},
- {"No valid productFamilyId is specified", mapper.readValue(inputStream("/RequestInfo/VnfProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 3},
- {"No valid productFamilyId is specified", mapper.readValue(inputStream("/RequestInfo/NetworkProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 3},
- {"No valid productFamilyId is specified", mapper.readValue(inputStream("/RequestInfo/NetworkProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 3},
- {"No valid productFamilyId is specified", mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid requestorId is specified", mapper.readValue(inputStream("/RequestInfo/EmptyRequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid requestorId is specified", mapper.readValue(inputStream("/RequestInfo/RequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, 6},
- {"No valid requestorId is specified", mapper.readValue(inputStream("/RequestInfo/RequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6},
- //ValidationException for RequestParameters
- {"No valid aLaCarte in requestParameters", mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, 4},
- {"No valid requestParameters is specified", mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid requestParameters is specified", mapper.readValue(inputStream("/RequestParameters/RequestParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, 6},
- {"No valid requestParameters is specified", mapper.readValue(inputStream("/RequestParameters/RequestParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6},
- {"No valid requestParameters is specified", mapper.readValue(inputStream("/RequestParameters/AssignEmptyReqParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- //ValidationException for SubscriberInfo
- {"No valid globalSubscriberId is specified", mapper.readValue(inputStream("/SubscriberInfo/EmptyGlobalSubscriberId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid subscriberInfo is specified", mapper.readValue(inputStream("/SubscriberInfo/EmptySubscriberInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid subscriptionServiceType is specified", mapper.readValue(inputStream("/SubscriberInfo/EmptySubscriptionServiceType.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5},
- {"No valid subscriberInfo is specified", mapper.readValue(inputStream("/SubscriberInfo/AssignEmptySubscriberInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- //Validation for UserParams
- {"No valid cloudConfiguration in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/AssignCloudConfigVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid cloudConfiguration in userParams network resources is specified", mapper.readValue(inputStream("/RequestParameters/NetworkCloudConfig.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid modelInfo in userParams is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsModelInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid modelInfo in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsVnfModelInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid modelVersionId in userParams service modelInfo is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid modelVersionId in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/VnfModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid modelVersionId in userParams vfModule resources is specified", mapper.readValue(inputStream("/RequestParameters/VfModuleModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid modelVersionId in userParams network resources is specified", mapper.readValue(inputStream("/RequestParameters/NetworkModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid platform in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsPlatform.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid platformName in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsPlatformName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid productFamilyId in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/ProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid vfModules in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/VfModules.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid modelInfo in userParams vfModules resources is specified", mapper.readValue(inputStream("/RequestParameters/VfModulesModelInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid modelInfo in userParams network resources is specified", mapper.readValue(inputStream("/RequestParameters/Network.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid modelCustomizationId in userParams vfModule resources is specified", mapper.readValue(inputStream("/RequestParameters/VfModuleModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid modelCustomizationId in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/VnfModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- {"No valid modelCustomizationId in userParams network resources is specified", mapper.readValue(inputStream("/RequestParameters/NetworkModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7},
- //Validation for ConfigurationParameters
- {"No valid configuration parameters is specified", mapper.readValue(inputStream("/ConfigurationParameters/NoConfigurationParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7},
- //Validation for Add and Remove Members
- {"No valid vnf relatedInstance is specified", mapper.readValue(inputStream("/MembersValidation/RelatedInstancesVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7},
- {"No valid related instances is specified", mapper.readValue(inputStream("/MembersValidation/RelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7},
- {"No valid requestInfo is specified", mapper.readValue(inputStream("/MembersValidation/MembersRequestInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7},
- {"No valid requestorId is specified", mapper.readValue(inputStream("/MembersValidation/MembersRequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7},
- {"No valid source is specified", mapper.readValue(inputStream("/MembersValidation/AddMembersSource.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7},
- {"No valid instanceId in relatedInstances is specified", mapper.readValue(inputStream("/MembersValidation/AddMembersInstanceId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7},
- {"No valid modelType in relatedInstance is specified", mapper.readValue(inputStream("/MembersValidation/DeleteMembersModelType.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.removeMembers, 7}
- });
- }
- @Test
- public void nullInstanceIdMapTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{
- this.sir = mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), ServiceInstancesRequest.class);
- this.instanceIdMapTest = null;
- this.reqVersion = 5;
- this.version = "v" + reqVersion;
- thrown.expect(NullPointerException.class);
- this.msoRequest = new MsoRequest();
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- }
-
- @Test
- public void serviceInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{
- this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class);
- this.instanceIdMapTest.put("serviceInstanceId", "test");
- this.action = Action.createInstance;
- this.reqVersion = 5;
- this.version = "v" + reqVersion;
- thrown.expect(ValidationException.class);
- thrown.expectMessage("No valid serviceInstanceId is specified");
- this.msoRequest = new MsoRequest();
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- }
- @Test
- public void vnfInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{
- this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class);
- this.instanceIdMapTest.put("vnfInstanceId", "test");
- this.action = Action.createInstance;
- this.reqVersion = 5;
- this.version = "v" + reqVersion;
- thrown.expect(ValidationException.class);
- thrown.expectMessage("No valid vnfInstanceId is specified");
- this.msoRequest = new MsoRequest();
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- }
- @Test
- public void vfModuleInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{
- this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class);
- this.instanceIdMapTest.put("vfModuleInstanceId", "test");
- this.action = Action.createInstance;
- this.reqVersion = 5;
- this.version = "v" + reqVersion;
- thrown.expect(ValidationException.class);
- thrown.expectMessage("No valid vfModuleInstanceId is specified");
- this.msoRequest = new MsoRequest();
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- }
- @Test
- public void volumeGroupInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{
- this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class);
- this.instanceIdMapTest.put("volumeGroupInstanceId", "test");
- this.action = Action.createInstance;
- this.reqVersion = 5;
- this.version = "v" + reqVersion;
- thrown.expect(ValidationException.class);
- thrown.expectMessage("No valid volumeGroupInstanceId is specified");
- this.msoRequest = new MsoRequest();
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- }
- @Test
- public void networkInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{
- this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class);
- this.instanceIdMapTest.put("networkInstanceId", "test");
- this.action = Action.createInstance;
- this.reqVersion = 5;
- this.version = "v" + reqVersion;
- thrown.expect(ValidationException.class);
- thrown.expectMessage("No valid networkInstanceId is specified");
- this.msoRequest = new MsoRequest();
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- }
- @Test
- public void configurationInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{
- this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class);
- this.instanceIdMapTest.put("configurationInstanceId", "test");
- this.action = Action.createInstance;
- thrown.expect(ValidationException.class);
- this.reqVersion = 5;
- this.version = "v" + reqVersion;
- thrown.expectMessage("No valid configurationInstanceId is specified");
- this.msoRequest = new MsoRequest();
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- }
- @Test
- public void instanceGroupIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{
- this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class);
- this.instanceIdMapTest.put("instanceGroupInstanceId", "test");
- this.action = Action.createInstance;
- thrown.expect(ValidationException.class);
- this.reqVersion = 7;
- this.version = "v" + reqVersion;
- thrown.expectMessage("No valid instanceGroupInstanceId is specified");
- this.msoRequest = new MsoRequest();
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- }
- @Test
- public void testVfModuleV4UsePreLoad() throws JsonParseException, JsonMappingException, IOException, ValidationException {
- this.requestJSON = inputStream("/SuccessfulValidation/v4CreateVfModule.json");
- this.instanceIdMapTest.put("serviceInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc");
- this.instanceIdMapTest.put("vnfInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc");
- this.reqVersion = 4;
- this.version = "v" + reqVersion;
- this.sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class);
- this.msoRequest = new MsoRequest ();
- msoRequest.parse(sir, instanceIdMapTest, Action.createInstance, version, originalRequestJSON, reqVersion, false);
-
- this.requestJSON = inputStream("/ModelInfo/v4CreateVfModuleNoCustomizationId.json");
- this.instanceIdMapTest.put("serviceInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc");
- this.instanceIdMapTest.put("vnfInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc");
- this.sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class);
- msoRequest = new MsoRequest ();
- msoRequest.parse(sir, instanceIdMapTest, Action.createInstance, version, originalRequestJSON, reqVersion, false);
- }
- @Test
- public void buildServiceErrorResponseTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{
- this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class);
- this.instanceIdMapTest.put("serviceInstanceId", "test");
- this.action = Action.createInstance;
- this.reqVersion = 5;
- this.version = "v" + reqVersion;
- thrown.expect(ValidationException.class);
- thrown.expectMessage("No valid serviceInstanceId is specified");
- this.msoRequest = new MsoRequest();
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
- MsoException.ServiceException, "Mapping of request to JSON object failed. ",
- ErrorNumbers.SVC_BAD_PARAMETER, null, version);
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ public String inputStream(String JsonInput) throws IOException {
+ JsonInput = "src/test/resources/MsoRequestTest" + JsonInput;
+ String input = new String(Files.readAllBytes(Paths.get(JsonInput)));
+ return input;
+ }
+
+ // Tests for successful validation of incoming JSON requests through the parse method
+ @Test
+ @Parameters(method = "successParameters")
+ public void successTest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMapTest, Action action,
+ int reqVersion) throws ValidationException, IOException {
+ this.sir = sir;
+ this.instanceIdMapTest = instanceIdMapTest;
+ this.action = action;
+ this.reqVersion = reqVersion;
+ this.version = "v" + reqVersion;
+ this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
+ this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
+ this.instanceIdMapTest.put("vfModuleInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
+ this.instanceIdMapTest.put("volumeGroupInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
+ this.instanceIdMapTest.put("networkInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
+ this.instanceIdMapTest.put("configurationInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
+ this.msoRequest = new MsoRequest();
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ }
+
+ @Parameters
+ private Collection<Object[]> successParameters() throws JsonParseException, JsonMappingException, IOException {
+ return Arrays.asList(new Object[][] {
+ {mapper.readValue(inputStream("/CloudConfiguration/EmptyCloudConfiguration.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "3"},
+ {mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyOwningEntityName.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "5"},
+ {mapper.readValue(inputStream("/PlatformAndLineOfBusiness/OptionalLineOfBusiness.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"},
+ {mapper.readValue(inputStream("/ProjectAndOwningEntity/OptionalProject.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"},
+ {mapper.readValue(inputStream("/PlatformAndLineOfBusiness/PlatformTest.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"},
+ {mapper.readValue(inputStream("/RequestInfo/EmptyRequestorId.json"), ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, "3"},
+ {mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyIdFlag.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"},
+ {mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyIdUpdate.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"},
+ {mapper.readValue(inputStream("/ModelInfo/ModelCustomizationIdUsingPreload.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"},
+ {mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdConfigurationDelete.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"},
+ {mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdService.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "4"},
+ {mapper.readValue(inputStream("/ModelInfo/ModelVersionNetwork.json"), ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.deleteInstance, "3"},
+ {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationIdEmpty.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "5"},
+ {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationNameNull.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"},
+ {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationTest.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"},
+ {mapper.readValue(inputStream("/ModelInfo/ServiceModelNameEmptyOnActivate.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "2"},
+ {mapper.readValue(inputStream("/ModelInfo/ServiceModelNameEmptyOnDelete.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "2"},
+ {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationId.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "4"},
+ {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationId.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"},
+ {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationIdService.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"},
+ {mapper.readValue(inputStream("/RelatedInstances/RelatedInstances.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"},
+ {mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantId.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "5"},
+ {mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVfModule.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/ServiceInPlaceSoftwareUpdate.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, "6"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/ServiceInPlaceSoftwareUpdate.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, "6"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableService.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, "5"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/VnfActivate.json"), ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, "6"},
+ {mapper.readValue(inputStream("/RequestParameters/VnfRequestParameters.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "6"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/v3DeleteNetwork.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/v3UpdateNetwork.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "3"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/v5CreateConfiguration.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "5"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/v6CreateConfiguration.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableConfiguration.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, "5"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableConfiguration.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, "5"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/v5ActivateConfiguration.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"},
+ {mapper.readValue(inputStream("/RelatedInstances/v5ActivateNoRelatedInstance.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/v5DeactivateConfiguration.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "5"},
+ {mapper.readValue(inputStream("/RelatedInstances/v5DeactivateNoRelatedInstance.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "5"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/v6AddRelationships.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, "6"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/UserParams.json"), ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.addRelationships, "5"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, "7"},
+ {mapper.readValue(inputStream("/SuccessfulValidation/ServiceUnassign.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.unassignInstance, "7"}});
+ }
+
+ @Test
+ @Parameters(method = "customWorkflowSuccessParameters")
+ public void customWorkflowSuccessTest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMapTest,
+ Action action, int reqVersion) throws ValidationException, IOException {
+ this.sir = sir;
+ this.instanceIdMapTest = instanceIdMapTest;
+ this.action = action;
+ this.reqVersion = reqVersion;
+ this.version = "v" + reqVersion;
+ this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
+ this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
+ this.instanceIdMapTest.put("workflowUuid", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
+ this.msoRequest = new MsoRequest();
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ }
+
+ @Parameters
+ private Collection<Object[]> customWorkflowSuccessParameters()
+ throws JsonParseException, JsonMappingException, IOException {
+ return Arrays.asList(
+ new Object[][] {{mapper.readValue(inputStream("/SuccessfulValidation/v1ExecuteCustomWorkflow.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, "1"}
+
+ });
+ }
+
+ @Test
+ @Parameters(method = "aLaCarteParameters")
+ public void aLaCarteFlagTest(boolean expected, ServiceInstancesRequest sir)
+ throws JsonParseException, IOException, ValidationException {
+ this.expected = expected;
+ this.sir = sir;
+ this.msoRequest = new MsoRequest();
+ assertEquals(expected, msoRequest.getAlacarteFlag(sir));
+ }
+
+ @Parameters
+ private Collection<Object[]> aLaCarteParameters() throws IOException {
+ return Arrays.asList(new Object[][] {
+ {false, mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"),
+ ServiceInstancesRequest.class)},
+ {true, mapper.readValue(inputStream("/RequestParameters/RequestParametersALaCarteTrue.json"),
+ ServiceInstancesRequest.class)}});
+ }
+
+ // Tests various scenarios ensuring that requests containing missing or invalid information will throw a
+ // ValidationException
+ @Test
+ @Parameters(method = "validationParameters")
+ public void validationFailureTest(String expectedException, ServiceInstancesRequest sir,
+ HashMap<String, String> instanceIdMapTest, Action action, int reqVersion)
+ throws JsonParseException, JsonMappingException, IOException, ValidationException {
+ this.expectedException = expectedException;
+ this.sir = sir;
+ this.instanceIdMapTest = instanceIdMapTest;
+ this.action = action;
+ this.reqVersion = reqVersion;
+ this.version = "v" + reqVersion;
+ this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
+ this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
+ this.instanceIdMapTest.put("instanceGroupId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000");
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage(expectedException);
+ this.msoRequest = new MsoRequest();
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ }
+
+ @Parameters
+ private Collection<Object[]> validationParameters() throws IOException {
+ return Arrays.asList(new Object[][] {
+ // ValidationException for CloudConfiguration
+ {"No valid cloudConfiguration is specified",
+ mapper.readValue(inputStream("/CloudConfiguration/CloudConfiguration.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 4},
+ {"No valid cloudConfiguration is specified",
+ mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationNetwork.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid cloudConfiguration is specified",
+ mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationVnf.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.replaceInstance, 5},
+ {"No valid cloudConfiguration is specified",
+ mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationConfig.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.enablePort, 5},
+ {"No valid cloudConfiguration is specified",
+ mapper.readValue(
+ inputStream("/CloudConfiguration/InPlaceSoftwareUpdateCloudConfiguration.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6},
+ {"No valid cloudConfiguration is specified",
+ mapper.readValue(
+ inputStream("/CloudConfiguration/DeactivateAndCloudDeleteCloudConfiguration.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.deactivateAndCloudDelete, 7},
+ {"No valid cloudConfiguration is specified",
+ mapper.readValue(inputStream("/CloudConfiguration/ScaleOutNoCloudConfig.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.scaleOut, 7},
+ {"No valid cloudConfiguration is specified",
+ mapper.readValue(inputStream("/CloudConfiguration/VnfRecreateCloudConfig.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.recreateInstance, 7},
+ {"No valid lcpCloudRegionId is specified",
+ mapper.readValue(inputStream("/CloudConfiguration/EmptyLcpCloudConfiguration.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid lcpCloudRegionId is specified",
+ mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateCloudRegionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6},
+ {"No valid tenantId is specified",
+ mapper.readValue(inputStream("/CloudConfiguration/EmptyTenantId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid tenantId is specified",
+ mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateTenantId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6},
+ // ValidationException for ModelInfo
+ {"No valid modelCustomizationId is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelCustomizationId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.replaceInstance, 5},
+ {"No valid modelCustomizationId is specified",
+ mapper.readValue(inputStream("/ModelInfo/v5CreateConfigurationModelCustomizationId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid modelCustomizationId is specified",
+ mapper.readValue(inputStream("/ModelInfo/v4CreateVfModuleMissingModelCustomizationId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 4},
+ {"No valid modelCustomizationId or modelCustomizationName is specified",
+ mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid modelCustomizationId or modelCustomizationName is specified",
+ mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationIdPreload.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.replaceInstance, 5},
+ {"No valid modelCustomizationId or modelCustomizationName is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelCustomizationName.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 5},
+ {"No valid modelCustomizationId or modelCustomizationName is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelCustomization.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.replaceInstance, 6},
+ {"No valid modelCustomizationId or modelCustomizationName is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelCustomization.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.updateInstance, 6},
+ {"No valid modelCustomizationId or modelCustomizationName is specified",
+ mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.replaceInstance, 5},
+ {"No valid modelCustomizationId or modelCustomizationName is specified",
+ mapper.readValue(inputStream("/ModelInfo/VnfRecreateNoModelCustomizationId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.recreateInstance, 7},
+ {"No valid modelCustomizationId is specified",
+ mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelCustomizationId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.scaleOut, 7},
+ {"No valid model-info is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelInfoNull.json"), ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid modelInvariantId format is specified",
+ mapper.readValue(inputStream("/ModelInfo/InvalidModelInvariantId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 2},
+ {"No valid modelInvariantId is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelInvariantId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.deactivateInstance, 4},
+ {"No valid modelInvariantId is specified",
+ mapper.readValue(inputStream("/ModelInfo/v5ModelInvariantIdNetwork.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.enablePort, 5},
+ {"No valid modelInvariantId is specified",
+ mapper.readValue(inputStream("/ModelInfo/v5ModelInvariantIdDisablePort.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.disablePort, 5},
+ {"No valid modelInvariantId is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdVnf.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.updateInstance, 3},
+ {"No valid modelInvariantId is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdConfiguration.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 3},
+ {"No valid modelInvariantId is specified",
+ mapper.readValue(inputStream("/ModelInfo/v5DeactivateModelInvariantId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.deactivateInstance, 5},
+ {"No valid modelInvariantId is specified",
+ mapper.readValue(inputStream("/ModelInfo/v3UpdateNetworkBad.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.updateInstance, 4},
+ {"No valid modelInvariantId is specified",
+ mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelInvariantId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.scaleOut, 7},
+ {"No valid modelInvariantId is specified",
+ mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelInvariantId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.recreateInstance, 7},
+ {"No valid modelName is specified",
+ mapper.readValue(inputStream("/ModelInfo/VfModuleModelName.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.deleteInstance, 4},
+ {"No valid modelName is specified",
+ mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelName.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.scaleOut, 7},
+ {"No valid modelName is specified",
+ mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelName.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.recreateInstance, 7},
+ {"No valid modelType is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelTypeNull.json"), ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid modelVersion is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelVersionService.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.updateInstance, 3},
+ {"No valid modelVersion is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelVersionVfModule.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 3},
+ {"No valid modelVersion is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelVersionServiceCreate.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 3},
+ {"No valid modelVersion is specified",
+ mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelVersion.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.scaleOut, 7},
+ {"No valid modelVersion is specified",
+ mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelVersion.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.recreateInstance, 7},
+ {"No valid modelVersionId is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelVersionId.json"), ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid modelVersionId is specified",
+ mapper.readValue(inputStream("/ModelInfo/ConfigurationModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 5},
+ {"No valid modelVersionId is specified",
+ mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 4},
+ {"No valid modelVersionId is specified",
+ mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.deactivateInstance, 4},
+ {"No valid modelVersionId is specified",
+ mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.updateInstance, 5},
+ {"No valid modelVersionId is specified",
+ mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.enablePort, 5},
+ {"No valid modelVersionId is specified",
+ mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.disablePort, 5},
+ {"No valid modelVersionId is specified",
+ mapper.readValue(inputStream("/ModelInfo/ModelVersionIdCreate.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid modelVersionId is specified",
+ mapper.readValue(inputStream("/ModelInfo/v5ActivateModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 5},
+ {"No valid modelVersionId is specified",
+ mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.scaleOut, 7},
+ {"No valid modelVersionId is specified",
+ mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.recreateInstance, 7},
+ {"No valid modelVersionId is specified",
+ mapper.readValue(inputStream("/ModelInfo/CreateInstanceGroupNoModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 7},
+ // ValidationException for Platform and LineOfBusiness
+ {"No valid lineOfBusinessName is specified",
+ mapper.readValue(inputStream("/PlatformAndLineOfBusiness/EmptyLineOfBusiness.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid platform is specified",
+ mapper.readValue(inputStream("/PlatformAndLineOfBusiness/Platform.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 6},
+ {"No valid platformName is specified",
+ mapper.readValue(inputStream("/PlatformAndLineOfBusiness/EmptyPlatformName.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ // ValidationException for Project and OwningEntity
+ {"No valid owningEntity is specified",
+ mapper.readValue(inputStream("/ProjectAndOwningEntity/OwningEntity.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 6},
+ {"No valid owningEntityId is specified",
+ mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyOwningEntityId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid projectName is specified",
+ mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyProjectName.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid owningEntity is specified",
+ mapper.readValue(inputStream("/ProjectAndOwningEntity/ServiceAssignNoOE.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ // ValidationException for RelatedInstances
+ {"No valid connectionPoint relatedInstance for Port Configuration is specified",
+ mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoConnectionPoint.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.disablePort, 5},
+ {"No valid connectionPoint relatedInstance for Port Configuration is specified",
+ mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoConnectionPoint.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.enablePort, 5},
+ {"No valid destination vnf relatedInstance for Port Configuration is specified",
+ mapper.readValue(inputStream("/RelatedInstances/v5CreateNoDestinationRelatedInstance.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid instanceId format in relatedInstance is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesIdFormat.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid instanceId in relatedInstance is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid instanceName format in relatedInstance is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesNameFormat.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid instanceName in relatedInstance for pnf modelType is specified",
+ mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.removeRelationships, 6},
+ {"No valid instanceName in relatedInstance for pnf modelType is specified",
+ mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.addRelationships, 6},
+ {"No valid modelCustomizationName or modelCustomizationId in relatedInstance of vnf is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelCustomizationId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 5},
+ {"No valid modelInfo in relatedInstance is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInfo.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid modelInvariantId format in relatedInstance is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantIdFormat.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid modelInvariantId in relatedInstance is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid modelName in relatedInstance is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelName.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid modelType in relatedInstance is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelType.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid modelVersion in relatedInstance is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelVersion.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid modelVersionId in relatedInstance is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid related instances is specified",
+ mapper.readValue(inputStream("/RelatedInstances/ServiceNoRelatedInstance.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.addRelationships, 2},
+ {"No valid related instances is specified",
+ mapper.readValue(inputStream("/RelatedInstances/ServiceNoRelatedInstance.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.removeRelationships, 2},
+ {"No valid related instances is specified",
+ mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoRelatedInstance.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.disablePort, 2},
+ {"No valid related instances is specified",
+ mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoRelatedInstance.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.enablePort, 5},
+ {"No valid related instances is specified",
+ mapper.readValue(inputStream("/RelatedInstances/v5CreateNoRelatedInstances.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid related instances is specified",
+ mapper.readValue(inputStream("/RelatedInstances/v4RelatedInstancesNull.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.updateInstance, 4},
+ {"No valid related instances is specified",
+ mapper.readValue(inputStream("/RelatedInstances/ScaleOutNoRelatedInstances.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.scaleOut, 7},
+ {"No valid related service instance for vfModule request is specified",
+ mapper.readValue(inputStream("/RelatedInstances/VfModuleRelatedInstancesService.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 5},
+ {"No valid related service instance for vnf request is specified",
+ mapper.readValue(inputStream("/RelatedInstances/VnfRelatedInstancesService.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 5},
+ {"No valid related service instance for volumeGroup request is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesServiceInstance.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 5},
+ {"No valid related vnf instance for vfModule request is specified",
+ mapper.readValue(inputStream("/RelatedInstances/VfModuleRelatedInstancesVnf.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 5},
+ {"No valid related vnf instance for volumeGroup request is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVnfInstance.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 5},
+ {"No valid serviceInstanceId matching the serviceInstanceId in request URI is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesInstanceId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 5},
+ {"No valid serviceInstanceId matching the serviceInstanceId in request URI is specified",
+ mapper.readValue(inputStream("/RelatedInstances/v6VnfDeleteInstance.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.deleteInstance, 6},
+ {"No valid source vnf relatedInstance for Port Configuration is specified",
+ mapper.readValue(inputStream("/RelatedInstances/v5CreateNoSourceRelatedInstance.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid vnfInstanceId matching the vnfInstanceId in request URI is specified",
+ mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVnfInstanceId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.activateInstance, 5},
+ {"No valid instanceName format is specified",
+ mapper.readValue(inputStream("/RelatedInstances/InvalidInstanceName.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 2},
+ {"No valid relatedInstanceList is specified",
+ mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupNoRelatedInstances.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 7},
+ {"No valid related service instance for instanceGroup request is specified",
+ mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupService.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 7},
+ {"No valid modelVersionId in relatedInstance is specified",
+ mapper.readValue(
+ inputStream("/RelatedInstances/CreateInstanceGroupRelatedInstanceModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 7},
+ // ValidationException for RequestInfo
+ {"No valid requestInfo is specified",
+ mapper.readValue(inputStream("/RequestInfo/RequestInfoNull.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid requestInfo is specified",
+ mapper.readValue(inputStream("/RequestInfo/RequestInfo.json"), ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.applyUpdatedConfig, 6},
+ {"No valid requestInfo is specified",
+ mapper.readValue(inputStream("/RequestInfo/RequestInfo.json"), ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6},
+ {"No valid requestInfo is specified",
+ mapper.readValue(inputStream("/RequestInfo/ScaleOutNoRequestInfo.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.scaleOut, 7},
+ {"No valid productFamilyId is specified",
+ mapper.readValue(inputStream("/RequestInfo/VnfProductFamilyId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 3},
+ {"No valid productFamilyId is specified",
+ mapper.readValue(inputStream("/RequestInfo/NetworkProductFamilyId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 3},
+ {"No valid productFamilyId is specified",
+ mapper.readValue(inputStream("/RequestInfo/NetworkProductFamilyId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.updateInstance, 3},
+ {"No valid productFamilyId is specified",
+ mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid requestorId is specified",
+ mapper.readValue(inputStream("/RequestInfo/EmptyRequestorId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid requestorId is specified",
+ mapper.readValue(inputStream("/RequestInfo/RequestorId.json"), ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.applyUpdatedConfig, 6},
+ {"No valid requestorId is specified",
+ mapper.readValue(inputStream("/RequestInfo/RequestorId.json"), ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6},
+ // ValidationException for RequestParameters
+ {"No valid aLaCarte in requestParameters",
+ mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.addRelationships, 4},
+ {"No valid requestParameters is specified",
+ mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid requestParameters is specified",
+ mapper.readValue(inputStream("/RequestParameters/RequestParameters.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.applyUpdatedConfig, 6},
+ {"No valid requestParameters is specified",
+ mapper.readValue(inputStream("/RequestParameters/RequestParameters.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6},
+ {"No valid requestParameters is specified",
+ mapper.readValue(inputStream("/RequestParameters/AssignEmptyReqParameters.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ // ValidationException for SubscriberInfo
+ {"No valid globalSubscriberId is specified",
+ mapper.readValue(inputStream("/SubscriberInfo/EmptyGlobalSubscriberId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid subscriberInfo is specified",
+ mapper.readValue(inputStream("/SubscriberInfo/EmptySubscriberInfo.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid subscriptionServiceType is specified",
+ mapper.readValue(inputStream("/SubscriberInfo/EmptySubscriptionServiceType.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 5},
+ {"No valid subscriberInfo is specified",
+ mapper.readValue(inputStream("/SubscriberInfo/AssignEmptySubscriberInfo.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ // Validation for UserParams
+ {"No valid cloudConfiguration in userParams vnf resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/AssignCloudConfigVnf.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid cloudConfiguration in userParams network resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/NetworkCloudConfig.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid modelInfo in userParams is specified",
+ mapper.readValue(inputStream("/RequestParameters/UserParamsModelInfo.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid modelInfo in userParams vnf resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/UserParamsVnfModelInfo.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid modelVersionId in userParams service modelInfo is specified",
+ mapper.readValue(inputStream("/RequestParameters/UserParamsModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid modelVersionId in userParams vnf resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/VnfModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid modelVersionId in userParams vfModule resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/VfModuleModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid modelVersionId in userParams network resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/NetworkModelVersionId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid platform in userParams vnf resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/UserParamsPlatform.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid platformName in userParams vnf resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/UserParamsPlatformName.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid productFamilyId in userParams vnf resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/ProductFamilyId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid vfModules in userParams vnf resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/VfModules.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid modelInfo in userParams vfModules resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/VfModulesModelInfo.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid modelInfo in userParams network resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/Network.json"), ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid modelCustomizationId in userParams vfModule resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/VfModuleModelCustomizationId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid modelCustomizationId in userParams vnf resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/VnfModelCustomizationId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ {"No valid modelCustomizationId in userParams network resources is specified",
+ mapper.readValue(inputStream("/RequestParameters/NetworkModelCustomizationId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.assignInstance, 7},
+ // Validation for ConfigurationParameters
+ {"No valid configuration parameters is specified",
+ mapper.readValue(inputStream("/ConfigurationParameters/NoConfigurationParameters.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.scaleOut, 7},
+ // Validation for Add and Remove Members
+ {"No valid vnf relatedInstance is specified",
+ mapper.readValue(inputStream("/MembersValidation/RelatedInstancesVnf.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.addMembers, 7},
+ {"No valid related instances is specified",
+ mapper.readValue(inputStream("/MembersValidation/RelatedInstances.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.addMembers, 7},
+ {"No valid requestInfo is specified",
+ mapper.readValue(inputStream("/MembersValidation/MembersRequestInfo.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.addMembers, 7},
+ {"No valid requestorId is specified",
+ mapper.readValue(inputStream("/MembersValidation/MembersRequestorId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.addMembers, 7},
+ {"No valid source is specified",
+ mapper.readValue(inputStream("/MembersValidation/AddMembersSource.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.addMembers, 7},
+ {"No valid instanceId in relatedInstances is specified",
+ mapper.readValue(inputStream("/MembersValidation/AddMembersInstanceId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.addMembers, 7},
+ {"No valid modelType in relatedInstance is specified",
+ mapper.readValue(inputStream("/MembersValidation/DeleteMembersModelType.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.removeMembers, 7}});
+ }
+
+ @Test
+ public void nullInstanceIdMapTest()
+ throws JsonParseException, JsonMappingException, IOException, ValidationException {
+ this.sir = mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"),
+ ServiceInstancesRequest.class);
+ this.instanceIdMapTest = null;
+ this.reqVersion = 5;
+ this.version = "v" + reqVersion;
+ thrown.expect(NullPointerException.class);
+ this.msoRequest = new MsoRequest();
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ }
+
+ @Test
+ public void serviceInstanceIdHashMapFailureTest()
+ throws JsonParseException, JsonMappingException, IOException, ValidationException {
+ this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"),
+ ServiceInstancesRequest.class);
+ this.instanceIdMapTest.put("serviceInstanceId", "test");
+ this.action = Action.createInstance;
+ this.reqVersion = 5;
+ this.version = "v" + reqVersion;
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid serviceInstanceId is specified");
+ this.msoRequest = new MsoRequest();
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ }
+
+ @Test
+ public void vnfInstanceIdHashMapFailureTest()
+ throws JsonParseException, JsonMappingException, IOException, ValidationException {
+ this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"),
+ ServiceInstancesRequest.class);
+ this.instanceIdMapTest.put("vnfInstanceId", "test");
+ this.action = Action.createInstance;
+ this.reqVersion = 5;
+ this.version = "v" + reqVersion;
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid vnfInstanceId is specified");
+ this.msoRequest = new MsoRequest();
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ }
+
+ @Test
+ public void vfModuleInstanceIdHashMapFailureTest()
+ throws JsonParseException, JsonMappingException, IOException, ValidationException {
+ this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"),
+ ServiceInstancesRequest.class);
+ this.instanceIdMapTest.put("vfModuleInstanceId", "test");
+ this.action = Action.createInstance;
+ this.reqVersion = 5;
+ this.version = "v" + reqVersion;
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid vfModuleInstanceId is specified");
+ this.msoRequest = new MsoRequest();
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ }
+
+ @Test
+ public void volumeGroupInstanceIdHashMapFailureTest()
+ throws JsonParseException, JsonMappingException, IOException, ValidationException {
+ this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"),
+ ServiceInstancesRequest.class);
+ this.instanceIdMapTest.put("volumeGroupInstanceId", "test");
+ this.action = Action.createInstance;
+ this.reqVersion = 5;
+ this.version = "v" + reqVersion;
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid volumeGroupInstanceId is specified");
+ this.msoRequest = new MsoRequest();
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ }
+
+ @Test
+ public void networkInstanceIdHashMapFailureTest()
+ throws JsonParseException, JsonMappingException, IOException, ValidationException {
+ this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"),
+ ServiceInstancesRequest.class);
+ this.instanceIdMapTest.put("networkInstanceId", "test");
+ this.action = Action.createInstance;
+ this.reqVersion = 5;
+ this.version = "v" + reqVersion;
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid networkInstanceId is specified");
+ this.msoRequest = new MsoRequest();
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ }
+
+ @Test
+ public void configurationInstanceIdHashMapFailureTest()
+ throws JsonParseException, JsonMappingException, IOException, ValidationException {
+ this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"),
+ ServiceInstancesRequest.class);
+ this.instanceIdMapTest.put("configurationInstanceId", "test");
+ this.action = Action.createInstance;
+ thrown.expect(ValidationException.class);
+ this.reqVersion = 5;
+ this.version = "v" + reqVersion;
+ thrown.expectMessage("No valid configurationInstanceId is specified");
+ this.msoRequest = new MsoRequest();
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ }
+
+ @Test
+ public void instanceGroupIdHashMapFailureTest()
+ throws JsonParseException, JsonMappingException, IOException, ValidationException {
+ this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"),
+ ServiceInstancesRequest.class);
+ this.instanceIdMapTest.put("instanceGroupInstanceId", "test");
+ this.action = Action.createInstance;
+ thrown.expect(ValidationException.class);
+ this.reqVersion = 7;
+ this.version = "v" + reqVersion;
+ thrown.expectMessage("No valid instanceGroupInstanceId is specified");
+ this.msoRequest = new MsoRequest();
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ }
+
+ @Test
+ public void testVfModuleV4UsePreLoad()
+ throws JsonParseException, JsonMappingException, IOException, ValidationException {
+ this.requestJSON = inputStream("/SuccessfulValidation/v4CreateVfModule.json");
+ this.instanceIdMapTest.put("serviceInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc");
+ this.instanceIdMapTest.put("vnfInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc");
+ this.reqVersion = 4;
+ this.version = "v" + reqVersion;
+ this.sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class);
+ this.msoRequest = new MsoRequest();
+ msoRequest.parse(sir, instanceIdMapTest, Action.createInstance, version, originalRequestJSON, reqVersion,
+ false);
+
+ this.requestJSON = inputStream("/ModelInfo/v4CreateVfModuleNoCustomizationId.json");
+ this.instanceIdMapTest.put("serviceInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc");
+ this.instanceIdMapTest.put("vnfInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc");
+ this.sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class);
+ msoRequest = new MsoRequest();
+ msoRequest.parse(sir, instanceIdMapTest, Action.createInstance, version, originalRequestJSON, reqVersion,
+ false);
+ }
+
+ @Test
+ public void buildServiceErrorResponseTest()
+ throws JsonParseException, JsonMappingException, IOException, ValidationException {
+ this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"),
+ ServiceInstancesRequest.class);
+ this.instanceIdMapTest.put("serviceInstanceId", "test");
+ this.action = Action.createInstance;
+ this.reqVersion = 5;
+ this.version = "v" + reqVersion;
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid serviceInstanceId is specified");
+ this.msoRequest = new MsoRequest();
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ Response response =
+ msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
+ "Mapping of request to JSON object failed. ", ErrorNumbers.SVC_BAD_PARAMETER, null, version);
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0));
assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0));
assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0));
- }
- @Test
- public void buildServiceErrorPolicyExceptionResponseTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{
- this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class);
- this.instanceIdMapTest.put("serviceInstanceId", "test");
- this.action = Action.createInstance;
- this.reqVersion = 5;
- this.version = "v" + reqVersion;
- thrown.expect(ValidationException.class);
- thrown.expectMessage("No valid serviceInstanceId is specified");
- this.msoRequest = new MsoRequest();
-
-
- this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
- Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
- MsoException.PolicyException, "Mapping of request to JSON object failed. ",
- ErrorNumbers.SVC_BAD_PARAMETER, null, version);
+ }
+
+ @Test
+ public void buildServiceErrorPolicyExceptionResponseTest()
+ throws JsonParseException, JsonMappingException, IOException, ValidationException {
+ this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"),
+ ServiceInstancesRequest.class);
+ this.instanceIdMapTest.put("serviceInstanceId", "test");
+ this.action = Action.createInstance;
+ this.reqVersion = 5;
+ this.version = "v" + reqVersion;
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid serviceInstanceId is specified");
+ this.msoRequest = new MsoRequest();
+
+
+ this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false);
+ Response response =
+ msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.PolicyException,
+ "Mapping of request to JSON object failed. ", ErrorNumbers.SVC_BAD_PARAMETER, null, version);
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0));
assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0));
assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0));
- }
+ }
@Test
public void domToStrTest() throws Exception {
@@ -531,17 +1040,18 @@ public class MsoRequestTest extends BaseTest {
@Test
public void buildSelfLinkUrlTest() throws Exception {
- // v - version
- String incomingUrl = "http://localhost:8080/onap/infra/so/serviceInstantiation/v7/serviceInstances";
- String expectedSelfLink = "http://localhost:8080/orchestrationRequests/v7/efce3167-5e45-4666-9d4d-22e23648e5d1";
- String requestId = "efce3167-5e45-4666-9d4d-22e23648e5d1";
- this.msoRequest = new MsoRequest();
- Optional<URL> actualSelfLinkUrl = msoRequest.buildSelfLinkUrl(incomingUrl, requestId);
- assertEquals(expectedSelfLink, actualSelfLinkUrl.get().toString());
- // V - Version
- String incomingUrlV = "http://localhost:8080/onap/infra/so/serviceInstantiation/V7/serviceInstances";
- String expectedSelfLinkV = "http://localhost:8080/orchestrationRequests/V7/efce3167-5e45-4666-9d4d-22e23648e5d1";
- Optional<URL> actualSelfLinkUrlV = msoRequest.buildSelfLinkUrl(incomingUrlV, requestId);
- assertEquals(expectedSelfLinkV, actualSelfLinkUrlV.get().toString());
- }
-} \ No newline at end of file
+ // v - version
+ String incomingUrl = "http://localhost:8080/onap/infra/so/serviceInstantiation/v7/serviceInstances";
+ String expectedSelfLink = "http://localhost:8080/orchestrationRequests/v7/efce3167-5e45-4666-9d4d-22e23648e5d1";
+ String requestId = "efce3167-5e45-4666-9d4d-22e23648e5d1";
+ this.msoRequest = new MsoRequest();
+ Optional<URL> actualSelfLinkUrl = msoRequest.buildSelfLinkUrl(incomingUrl, requestId);
+ assertEquals(expectedSelfLink, actualSelfLinkUrl.get().toString());
+ // V - Version
+ String incomingUrlV = "http://localhost:8080/onap/infra/so/serviceInstantiation/V7/serviceInstances";
+ String expectedSelfLinkV =
+ "http://localhost:8080/orchestrationRequests/V7/efce3167-5e45-4666-9d4d-22e23648e5d1";
+ Optional<URL> actualSelfLinkUrlV = msoRequest.buildSelfLinkUrl(incomingUrlV, requestId);
+ assertEquals(expectedSelfLinkV, actualSelfLinkUrlV.get().toString());
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java
index e96558171d..321ea3ac7d 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java
@@ -31,7 +31,6 @@ import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
@@ -40,10 +39,8 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.junit.Ignore;
import org.junit.Test;
@@ -63,7 +60,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -73,8 +69,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class OrchestrationRequestsTest extends BaseTest {
@Autowired
private RequestsDbClient requestsDbClient;
-
- @Autowired
+
+ @Autowired
private OrchestrationRequests orchReq;
private static final GetOrchestrationListResponse ORCHESTRATION_LIST = generateOrchestrationList();
@@ -113,13 +109,12 @@ public class OrchestrationRequestsTest extends BaseTest {
UriComponentsBuilder builder = UriComponentsBuilder
.fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId));
- ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET,
- entity, GetOrchestrationResponse.class);
+ ResponseEntity<GetOrchestrationResponse> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(),
- sameBeanAs(testResponse).ignoring("request.startTime").ignoring("request.finishTime")
- .ignoring("request.requestStatus.timeStamp"));
+ assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime")
+ .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp"));
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0));
assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0));
@@ -127,7 +122,7 @@ public class OrchestrationRequestsTest extends BaseTest {
assertEquals("00032ab7-na18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0));
assertNotNull(response.getBody().getRequest().getFinishTime());
}
-
+
@Test
public void testGetOrchestrationRequestInstanceGroup() throws Exception {
setupTestGetOrchestrationRequestInstanceGroup();
@@ -145,19 +140,18 @@ public class OrchestrationRequestsTest extends BaseTest {
UriComponentsBuilder builder = UriComponentsBuilder
.fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId));
- ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET,
- entity, GetOrchestrationResponse.class);
+ ResponseEntity<GetOrchestrationResponse> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(),
- sameBeanAs(testResponse).ignoring("request.startTime").ignoring("request.finishTime")
- .ignoring("request.requestStatus.timeStamp"));
+ assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime")
+ .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp"));
}
@Test
public void testGetOrchestrationRequestRequestDetails() throws Exception {
setupTestGetOrchestrationRequestRequestDetails("00032ab7-3fb3-42e5-965d-8ea592502017", "COMPLETED");
- //Test request with modelInfo request body
+ // Test request with modelInfo request body
GetOrchestrationResponse testResponse = new GetOrchestrationResponse();
Request request = ORCHESTRATION_LIST.getRequestList().get(0).getRequest();
@@ -172,13 +166,12 @@ public class OrchestrationRequestsTest extends BaseTest {
UriComponentsBuilder builder = UriComponentsBuilder
.fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId));
- ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET,
- entity, GetOrchestrationResponse.class);
+ ResponseEntity<GetOrchestrationResponse> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertThat(response.getBody(),
- sameBeanAs(testResponse).ignoring("request.startTime").ignoring("request.finishTime")
- .ignoring("request.requestStatus.timeStamp"));
+ assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime")
+ .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp"));
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0));
assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0));
@@ -188,12 +181,12 @@ public class OrchestrationRequestsTest extends BaseTest {
@Test
public void testGetOrchestrationRequestNoRequestID() {
- HttpHeaders headers = new HttpHeaders();
- headers.set("Accept", "application/json; charset=UTF-8");
- headers.set("Content-Type", "application/json; charset=UTF-8");
+ HttpHeaders headers = new HttpHeaders();
+ headers.set("Accept", "application/json; charset=UTF-8");
+ headers.set("Content-Type", "application/json; charset=UTF-8");
HttpEntity<Request> entity = new HttpEntity<Request>(null, headers);
- UriComponentsBuilder builder = UriComponentsBuilder
- .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v6/"));
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v6/"));
ResponseEntity<GetOrchestrationListResponse> response = restTemplate.exchange(builder.toUriString(),
HttpMethod.GET, entity, GetOrchestrationListResponse.class);
@@ -206,10 +199,11 @@ public class OrchestrationRequestsTest extends BaseTest {
List<String> values = new ArrayList<>();
values.add("EQUALS");
values.add("vfModule");
-
+
ObjectMapper mapper = new ObjectMapper();
- GetOrchestrationListResponse testResponse = mapper.readValue(new File("src/test/resources/OrchestrationRequest/OrchestrationFilterResponse.json"),
- GetOrchestrationListResponse.class);
+ GetOrchestrationListResponse testResponse =
+ mapper.readValue(new File("src/test/resources/OrchestrationRequest/OrchestrationFilterResponse.json"),
+ GetOrchestrationListResponse.class);
Map<String, List<String>> orchestrationMap = new HashMap<>();
orchestrationMap.put("modelType", values);
@@ -219,18 +213,17 @@ public class OrchestrationRequestsTest extends BaseTest {
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON);
HttpEntity<Request> entity = new HttpEntity<Request>(null, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder
- .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v6?filter=modelType:EQUALS:vfModule"));
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(
+ createURLWithPort("/onap/so/infra/orchestrationRequests/v6?filter=modelType:EQUALS:vfModule"));
ResponseEntity<GetOrchestrationListResponse> response = restTemplate.exchange(builder.toUriString(),
HttpMethod.GET, entity, GetOrchestrationListResponse.class);
- assertThat(response.getBody(),
- sameBeanAs(testResponse).ignoring("requestList.request.startTime").ignoring("requestList.request.finishTime")
- .ignoring("requestList.request.requestStatus.timeStamp"));
+ assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("requestList.request.startTime")
+ .ignoring("requestList.request.finishTime").ignoring("requestList.request.requestStatus.timeStamp"));
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
assertEquals(requests.size(), response.getBody().getRequestList().size());
-
+
}
@Test
@@ -238,7 +231,8 @@ public class OrchestrationRequestsTest extends BaseTest {
setupTestUnlockOrchestrationRequest("0017f68c-eb2d-45bb-b7c7-ec31b37dc349", "UNLOCKED");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
- String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json")));
+ String requestJSON =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json")));
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON);
headers.set("Content-Type", MediaType.APPLICATION_JSON);
@@ -254,11 +248,12 @@ public class OrchestrationRequestsTest extends BaseTest {
expectedRequestError = new RequestError();
se = new ServiceException();
se.setMessageId(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR);
- se.setText("Orchestration RequestId 0017f68c-eb2d-45bb-b7c7-ec31b37dc349 has a status of UNLOCKED and can not be unlocked");
+ se.setText(
+ "Orchestration RequestId 0017f68c-eb2d-45bb-b7c7-ec31b37dc349 has a status of UNLOCKED and can not be unlocked");
expectedRequestError.setServiceException(se);
- builder = UriComponentsBuilder.fromHttpUrl(
- createURLWithPort("/onap/so/infra/orchestrationRequests/v6/0017f68c-eb2d-45bb-b7c7-ec31b37dc349/unlock"));
+ builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(
+ "/onap/so/infra/orchestrationRequests/v6/0017f68c-eb2d-45bb-b7c7-ec31b37dc349/unlock"));
response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
actualRequestError = mapper.readValue(response.getBody(), RequestError.class);
@@ -272,7 +267,8 @@ public class OrchestrationRequestsTest extends BaseTest {
setupTestUnlockOrchestrationRequest_invalid_Json();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
- String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json")));
+ String requestJSON =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json")));
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON);
headers.set("Content-Type", MediaType.APPLICATION_JSON);
@@ -306,7 +302,8 @@ public class OrchestrationRequestsTest extends BaseTest {
throws JsonParseException, JsonMappingException, IOException, ValidationException {
setupTestUnlockOrchestrationRequest_Valid_Status("5ffbabd6-b793-4377-a1ab-082670fbc7ac", "PENDING");
ObjectMapper mapper = new ObjectMapper();
- String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json")));
+ String requestJSON =
+ new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json")));
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON);
headers.set("Content-Type", MediaType.APPLICATION_JSON);
@@ -318,14 +315,15 @@ public class OrchestrationRequestsTest extends BaseTest {
// Test valid status
request = ORCHESTRATION_LIST.getRequestList().get(1).getRequest();
- builder = UriComponentsBuilder.fromHttpUrl(
- createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + "5ffbabd6-b793-4377-a1ab-082670fbc7ac" + "/unlock"));
+ builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(
+ "/onap/so/infra/orchestrationRequests/v7/" + "5ffbabd6-b793-4377-a1ab-082670fbc7ac" + "/unlock"));
response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
- //Cannot assert anything further here, already have a wiremock in place which ensures that the post was properly called to update.
+ // Cannot assert anything further here, already have a wiremock in place which ensures that the post was
+ // properly called to update.
}
- @Ignore //What is this testing?
+ @Ignore // What is this testing?
@Test
public void testGetOrchestrationRequestRequestDetailsWhiteSpace() throws Exception {
InfraActiveRequests requests = new InfraActiveRequests();
@@ -346,8 +344,8 @@ public class OrchestrationRequestsTest extends BaseTest {
UriComponentsBuilder builder = UriComponentsBuilder
.fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId"));
- ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET,
- entity, GetOrchestrationResponse.class);
+ ResponseEntity<GetOrchestrationResponse> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
@@ -357,19 +355,20 @@ public class OrchestrationRequestsTest extends BaseTest {
assertEquals("requestId", response.getHeaders().get("X-TransactionID").get(0));
}
- @Ignore //What is this testing?
+ @Ignore // What is this testing?
@Test
public void testGetOrchestrationRequestRequestDetailsAlaCarte() throws IOException {
InfraActiveRequests requests = new InfraActiveRequests();
- String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/AlaCarteRequest.json")));
+ String requestJSON = new String(
+ Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/AlaCarteRequest.json")));
requests.setAction("create");
requests.setRequestBody(requestJSON);
requests.setRequestId("requestId");
requests.setRequestScope("service");
requests.setRequestType("createInstance");
-// iar.save(requests);
+ // iar.save(requests);
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON);
headers.set("Content-Type", MediaType.APPLICATION_JSON);
@@ -378,8 +377,8 @@ public class OrchestrationRequestsTest extends BaseTest {
UriComponentsBuilder builder = UriComponentsBuilder
.fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId"));
- ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET,
- entity, GetOrchestrationResponse.class);
+ ResponseEntity<GetOrchestrationResponse> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
@@ -388,96 +387,112 @@ public class OrchestrationRequestsTest extends BaseTest {
assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0));
assertEquals("requestId", response.getHeaders().get("X-TransactionID").get(0));
}
+
@Test
- public void mapRequestProcessingDataTest() throws JsonParseException, JsonMappingException, IOException{
- RequestProcessingData entry = new RequestProcessingData();
- RequestProcessingData secondEntry = new RequestProcessingData();
- List<HashMap<String, String>> expectedList = new ArrayList<>();
- HashMap<String, String> expectedMap = new HashMap<>();
- List<HashMap<String, String>> secondExpectedList = new ArrayList<>();
- HashMap<String, String> secondExpectedMap = new HashMap<>();
- List<RequestProcessingData> expectedDataList = new ArrayList<>();
- entry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca714");
- entry.setTag("pincFabricConfigRequest");
- expectedMap.put("requestAction", "assign");
- expectedMap.put("pincFabricId", "testId");
- expectedList.add(expectedMap);
- entry.setDataPairs(expectedList);
- secondEntry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca715");
- secondEntry.setTag("pincFabricConfig");
- secondExpectedMap.put("requestAction", "unassign");
- secondExpectedList.add(secondExpectedMap);
- secondEntry.setDataPairs(secondExpectedList);
- expectedDataList.add(entry);
- expectedDataList.add(secondEntry);
-
- List<org.onap.so.db.request.beans.RequestProcessingData> processingData = new ArrayList<>();
- List<RequestProcessingData> actualProcessingData = new ArrayList<>();
- ObjectMapper mapper = new ObjectMapper();
- processingData = mapper.readValue(new File("src/test/resources/OrchestrationRequest/RequestProcessingData.json"),
- new TypeReference<List<org.onap.so.db.request.beans.RequestProcessingData>>(){});
+ public void mapRequestProcessingDataTest() throws JsonParseException, JsonMappingException, IOException {
+ RequestProcessingData entry = new RequestProcessingData();
+ RequestProcessingData secondEntry = new RequestProcessingData();
+ List<HashMap<String, String>> expectedList = new ArrayList<>();
+ HashMap<String, String> expectedMap = new HashMap<>();
+ List<HashMap<String, String>> secondExpectedList = new ArrayList<>();
+ HashMap<String, String> secondExpectedMap = new HashMap<>();
+ List<RequestProcessingData> expectedDataList = new ArrayList<>();
+ entry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca714");
+ entry.setTag("pincFabricConfigRequest");
+ expectedMap.put("requestAction", "assign");
+ expectedMap.put("pincFabricId", "testId");
+ expectedList.add(expectedMap);
+ entry.setDataPairs(expectedList);
+ secondEntry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca715");
+ secondEntry.setTag("pincFabricConfig");
+ secondExpectedMap.put("requestAction", "unassign");
+ secondExpectedList.add(secondExpectedMap);
+ secondEntry.setDataPairs(secondExpectedList);
+ expectedDataList.add(entry);
+ expectedDataList.add(secondEntry);
+
+ List<org.onap.so.db.request.beans.RequestProcessingData> processingData = new ArrayList<>();
+ List<RequestProcessingData> actualProcessingData = new ArrayList<>();
+ ObjectMapper mapper = new ObjectMapper();
+ processingData =
+ mapper.readValue(new File("src/test/resources/OrchestrationRequest/RequestProcessingData.json"),
+ new TypeReference<List<org.onap.so.db.request.beans.RequestProcessingData>>() {});
actualProcessingData = orchReq.mapRequestProcessingData(processingData);
- assertThat(actualProcessingData,sameBeanAs(expectedDataList));
+ assertThat(actualProcessingData, sameBeanAs(expectedDataList));
}
- public void setupTestGetOrchestrationRequest() throws Exception{
- //For testGetOrchestrationRequest
- wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequest.json"))))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/"))
- .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json"))))
- .withStatus(HttpStatus.SC_OK)));
+ public void setupTestGetOrchestrationRequest() throws Exception {
+ // For testGetOrchestrationRequest
+ wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(new String(Files.readAllBytes(
+ Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequest.json"))))
+ .withStatus(HttpStatus.SC_OK)));
+ wireMockServer
+ .stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/"))
+ .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(new String(Files.readAllBytes(Paths
+ .get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json"))))
+ .withStatus(HttpStatus.SC_OK)));
}
- public void setupTestGetOrchestrationRequestInstanceGroup() throws Exception{
- //For testGetOrchestrationRequest
- wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequestInstanceGroup.json"))))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/"))
- .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json"))))
- .withStatus(HttpStatus.SC_OK)));
+
+ public void setupTestGetOrchestrationRequestInstanceGroup() throws Exception {
+ // For testGetOrchestrationRequest
+ wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(new String(Files.readAllBytes(Paths.get(
+ "src/test/resources/OrchestrationRequest/getOrchestrationRequestInstanceGroup.json"))))
+ .withStatus(HttpStatus.SC_OK)));
+ wireMockServer
+ .stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/"))
+ .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(new String(Files.readAllBytes(Paths
+ .get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json"))))
+ .withStatus(HttpStatus.SC_OK)));
}
- private void setupTestGetOrchestrationRequestRequestDetails(String requestId, String status) throws Exception{
- wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequestDetails.json"))))
+ private void setupTestGetOrchestrationRequestRequestDetails(String requestId, String status) throws Exception {
+ wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(new String(Files.readAllBytes(
+ Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequestDetails.json"))))
.withStatus(HttpStatus.SC_OK)));
}
private void setupTestUnlockOrchestrationRequest(String requestId, String status) {
- wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(String.format(getResponseTemplate, requestId, status))
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId)))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(String.format(getResponseTemplate, requestId, status)).withStatus(HttpStatus.SC_OK)));
}
private void setupTestUnlockOrchestrationRequest_invalid_Json() {
- wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(INVALID_REQUEST_ID))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_NOT_FOUND)));
+ wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(INVALID_REQUEST_ID))).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_NOT_FOUND)));
}
private void setupTestUnlockOrchestrationRequest_Valid_Status(String requestID, String status) {
- wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestID))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(String.format(getResponseTemplate, requestID, status))
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestID)))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(String.format(getResponseTemplate, requestID, status)).withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(String.format(infraActivePost, requestID))
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("")))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(String.format(infraActivePost, requestID)).withStatus(HttpStatus.SC_OK)));
}
- private void setupTestGetOrchestrationRequestFilter() throws Exception{
- //for testGetOrchestrationRequestFilter();
- wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/getOrchestrationFiltersFromInfraActive/")).withRequestBody(equalToJson("{\"modelType\":[\"EQUALS\",\"vfModule\"]}")).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getRequestDetailsFilter.json"))))
- .withStatus(HttpStatus.SC_OK)));
+ private void setupTestGetOrchestrationRequestFilter() throws Exception {
+ // for testGetOrchestrationRequestFilter();
+ wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/getOrchestrationFiltersFromInfraActive/"))
+ .withRequestBody(equalToJson("{\"modelType\":[\"EQUALS\",\"vfModule\"]}"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(new String(Files.readAllBytes(
+ Paths.get("src/test/resources/OrchestrationRequest/getRequestDetailsFilter.json"))))
+ .withStatus(HttpStatus.SC_OK)));
}
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java
index a5f9514be2..dc0cd473c2 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java
@@ -32,20 +32,16 @@ import static org.junit.Assert.assertTrue;
import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID;
import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID;
import static org.onap.so.logger.MdcConstants.CLIENT_ID;
-
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
-
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.MediaType;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
-
import org.junit.Test;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException;
@@ -65,7 +61,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -73,92 +68,91 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class RequestHandlerUtilsTest extends BaseTest{
+public class RequestHandlerUtilsTest extends BaseTest {
+
+ private final ObjectMapper mapper = new ObjectMapper();
+ private ObjectMapper errorMapper = new ObjectMapper();
- private final ObjectMapper mapper = new ObjectMapper();
- private ObjectMapper errorMapper = new ObjectMapper();
-
@Autowired
private RequestHandlerUtils requestHandlerUtils;
- @Value("${wiremock.server.port}")
- private String wiremockPort;
-
+ @Value("${wiremock.server.port}")
+ private String wiremockPort;
+
private URL initialUrl;
private int initialPort;
private HttpHeaders headers;
- @Before
- public void beforeClass() {
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
+ @Before
+ public void beforeClass() {
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
// set headers
- headers = new HttpHeaders();
- headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name");
- headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
+ headers = new HttpHeaders();
+ headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name");
+ headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
headers.set(CLIENT_ID, "VID");
headers.set(REQUESTOR_ID, "xxxxxx");
- try { // generate one-time port number to avoid RANDOM port number later.
- initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH));
- initialPort = initialUrl.getPort();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public String inputStream(String JsonInput)throws IOException{
+ try { // generate one-time port number to avoid RANDOM port number later.
+ initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH));
+ initialPort = initialUrl.getPort();
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests.*")).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public String inputStream(String JsonInput) throws IOException {
JsonInput = "src/test/resources/ServiceInstanceTest" + JsonInput;
return new String(Files.readAllBytes(Paths.get(JsonInput)));
}
-
- public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod, HttpHeaders headers){
-
- if (!headers.containsKey(HttpHeaders.ACCEPT)) {
- headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
- }
- if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
- headers.set(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON);
- }
+
+ public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod,
+ HttpHeaders headers) {
+
+ if (!headers.containsKey(HttpHeaders.ACCEPT)) {
+ headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
+ }
+ if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
+ headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
+ }
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath, initialPort));
HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
- return restTemplate.exchange(builder.toUriString(),
- reqMethod, request, String.class);
+ return restTemplate.exchange(builder.toUriString(), reqMethod, request, String.class);
}
-
- public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod){
- return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders());
+
+ public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) {
+ return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders());
}
@Test
- public void test_mapJSONtoMSOStyle() throws IOException{
+ public void test_mapJSONtoMSOStyle() throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
- String testRequest= inputStream("/ServiceInstanceDefault.json");
+ String testRequest = inputStream("/ServiceInstanceDefault.json");
String resultString = requestHandlerUtils.mapJSONtoMSOStyle(testRequest, null, false, null);
ServiceInstancesRequest sir = mapper.readValue(resultString, ServiceInstancesRequest.class);
ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
- assertEquals("f7ce78bb-423b-11e7-93f8-0050569a796",modelInfo.getModelCustomizationUuid());
- assertEquals("modelInstanceName",modelInfo.getModelInstanceName());
- assertEquals("f7ce78bb-423b-11e7-93f8-0050569a7965",modelInfo.getModelInvariantUuid());
- assertEquals("10",modelInfo.getModelUuid());
+ assertEquals("f7ce78bb-423b-11e7-93f8-0050569a796", modelInfo.getModelCustomizationUuid());
+ assertEquals("modelInstanceName", modelInfo.getModelInstanceName());
+ assertEquals("f7ce78bb-423b-11e7-93f8-0050569a7965", modelInfo.getModelInvariantUuid());
+ assertEquals("10", modelInfo.getModelUuid());
}
-
-
+
+
@Test
- public void test_mapJSONtoMSOStyleUsePreload() throws IOException{
+ public void test_mapJSONtoMSOStyleUsePreload() throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
- String testRequest= inputStream("/ServiceInstanceDefault.json");
+ String testRequest = inputStream("/ServiceInstanceDefault.json");
ServiceInstancesRequest sir = new ServiceInstancesRequest();
RequestDetails rd = new RequestDetails();
RequestParameters rp = new RequestParameters();
@@ -168,163 +162,178 @@ public class RequestHandlerUtilsTest extends BaseTest{
String resultString = requestHandlerUtils.mapJSONtoMSOStyle(testRequest, sir, false, null);
ServiceInstancesRequest sir1 = mapper.readValue(resultString, ServiceInstancesRequest.class);
assertTrue(sir1.getRequestDetails().getRequestParameters().getUsePreload());
- }
-
+ }
+
@Test
- public void setServiceTypeTestALaCarte() throws JsonProcessingException{
- String requestScope = ModelType.service.toString();
- Boolean aLaCarteFlag = true;
- ServiceInstancesRequest sir = new ServiceInstancesRequest();
- RequestDetails requestDetails = new RequestDetails();
- RequestInfo requestInfo = new RequestInfo();
- requestInfo.setSource("VID");
- requestDetails.setRequestInfo(requestInfo);
- sir.setRequestDetails(requestDetails);
- Service defaultService = new Service();
- defaultService.setServiceType("testServiceTypeALaCarte");
-
- wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
+ public void setServiceTypeTestALaCarte() throws JsonProcessingException {
+ String requestScope = ModelType.service.toString();
+ Boolean aLaCarteFlag = true;
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setSource("VID");
+ requestDetails.setRequestInfo(requestInfo);
+ sir.setRequestDetails(requestDetails);
+ Service defaultService = new Service();
+ defaultService.setServiceType("testServiceTypeALaCarte");
+
+ wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag);
- assertEquals(serviceType, "testServiceTypeALaCarte");
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag);
+ assertEquals(serviceType, "testServiceTypeALaCarte");
}
+
@Test
- public void setServiceTypeTest() throws JsonProcessingException{
- String requestScope = ModelType.service.toString();
- Boolean aLaCarteFlag = false;
- ServiceInstancesRequest sir = new ServiceInstancesRequest();
- RequestDetails requestDetails = new RequestDetails();
- RequestInfo requestInfo = new RequestInfo();
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a");
- requestInfo.setSource("VID");
- requestDetails.setModelInfo(modelInfo);
- requestDetails.setRequestInfo(requestInfo);
- sir.setRequestDetails(requestDetails);
- Service defaultService = new Service();
- defaultService.setServiceType("testServiceType");
-
- wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a"))
+ public void setServiceTypeTest() throws JsonProcessingException {
+ String requestScope = ModelType.service.toString();
+ Boolean aLaCarteFlag = false;
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a");
+ requestInfo.setSource("VID");
+ requestDetails.setModelInfo(modelInfo);
+ requestDetails.setRequestInfo(requestInfo);
+ sir.setRequestDetails(requestDetails);
+ Service defaultService = new Service();
+ defaultService.setServiceType("testServiceType");
+
+ wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag);
- assertEquals(serviceType, "testServiceType");
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag);
+ assertEquals(serviceType, "testServiceType");
}
+
@Test
- public void setServiceTypeTestDefault() throws JsonProcessingException{
- String requestScope = ModelType.service.toString();
- Boolean aLaCarteFlag = false;
- ServiceInstancesRequest sir = new ServiceInstancesRequest();
- RequestDetails requestDetails = new RequestDetails();
- RequestInfo requestInfo = new RequestInfo();
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a");
- requestInfo.setSource("VID");
- requestDetails.setModelInfo(modelInfo);
- requestDetails.setRequestInfo(requestInfo);
- sir.setRequestDetails(requestDetails);
- Service defaultService = new Service();
- defaultService.setServiceType("testServiceType");
-
- wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a"))
+ public void setServiceTypeTestDefault() throws JsonProcessingException {
+ String requestScope = ModelType.service.toString();
+ Boolean aLaCarteFlag = false;
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a");
+ requestInfo.setSource("VID");
+ requestDetails.setModelInfo(modelInfo);
+ requestDetails.setRequestInfo(requestInfo);
+ sir.setRequestDetails(requestDetails);
+ Service defaultService = new Service();
+ defaultService.setServiceType("testServiceType");
+
+ wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withStatus(HttpStatus.SC_NOT_FOUND)));
- wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
+ wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag);
- assertEquals(serviceType, "testServiceType");
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag);
+ assertEquals(serviceType, "testServiceType");
}
+
@Test
- public void setServiceTypeTestNetwork() throws JsonProcessingException{
- String requestScope = ModelType.network.toString();
- Boolean aLaCarteFlag = null;
- ServiceInstancesRequest sir = new ServiceInstancesRequest();
- RequestDetails requestDetails = new RequestDetails();
- RequestInfo requestInfo = new RequestInfo();
- ModelInfo modelInfo = new ModelInfo();
- modelInfo.setModelName("networkModelName");
- requestInfo.setSource("VID");
- requestDetails.setModelInfo(modelInfo);
- requestDetails.setRequestInfo(requestInfo);
- sir.setRequestDetails(requestDetails);
-
- String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag);
- assertEquals(serviceType, "networkModelName");
+ public void setServiceTypeTestNetwork() throws JsonProcessingException {
+ String requestScope = ModelType.network.toString();
+ Boolean aLaCarteFlag = null;
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelName("networkModelName");
+ requestInfo.setSource("VID");
+ requestDetails.setModelInfo(modelInfo);
+ requestDetails.setRequestInfo(requestInfo);
+ sir.setRequestDetails(requestDetails);
+
+ String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag);
+ assertEquals(serviceType, "networkModelName");
}
+
@Test
- public void setServiceInstanceIdInstanceGroupTest() throws JsonParseException, JsonMappingException, IOException{
- String requestScope = "instanceGroup";
- ServiceInstancesRequest sir = mapper.readValue(inputStream("/CreateInstanceGroup.json"), ServiceInstancesRequest.class);
- assertEquals("ddcbbf3d-f2c1-4ca0-8852-76a807285efc", requestHandlerUtils.setServiceInstanceId(requestScope, sir));
+ public void setServiceInstanceIdInstanceGroupTest() throws JsonParseException, JsonMappingException, IOException {
+ String requestScope = "instanceGroup";
+ ServiceInstancesRequest sir =
+ mapper.readValue(inputStream("/CreateInstanceGroup.json"), ServiceInstancesRequest.class);
+ assertEquals("ddcbbf3d-f2c1-4ca0-8852-76a807285efc",
+ requestHandlerUtils.setServiceInstanceId(requestScope, sir));
}
+
@Test
- public void setServiceInstanceIdTest(){
- String requestScope = "vnf";
- ServiceInstancesRequest sir = new ServiceInstancesRequest();
- sir.setServiceInstanceId("f0a35706-efc4-4e27-80ea-a995d7a2a40f");
- assertEquals("f0a35706-efc4-4e27-80ea-a995d7a2a40f", requestHandlerUtils.setServiceInstanceId(requestScope, sir));
+ public void setServiceInstanceIdTest() {
+ String requestScope = "vnf";
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ sir.setServiceInstanceId("f0a35706-efc4-4e27-80ea-a995d7a2a40f");
+ assertEquals("f0a35706-efc4-4e27-80ea-a995d7a2a40f",
+ requestHandlerUtils.setServiceInstanceId(requestScope, sir));
}
+
@Test
- public void setServiceInstanceIdReturnNullTest(){
- String requestScope = "vnf";
- ServiceInstancesRequest sir = new ServiceInstancesRequest();
- assertNull(requestHandlerUtils.setServiceInstanceId(requestScope, sir));
+ public void setServiceInstanceIdReturnNullTest() {
+ String requestScope = "vnf";
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ assertNull(requestHandlerUtils.setServiceInstanceId(requestScope, sir));
}
+
@Test
- public void camundaHistoryCheckTest() throws ContactCamundaException, RequestDbFailureException{
- wireMockServer.stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBodyFile("Camunda/HistoryCheckResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- InfraActiveRequests duplicateRecord = new InfraActiveRequests();
- duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f");
- boolean inProgress = false;
- inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null);
- assertTrue(inProgress);
+ public void camundaHistoryCheckTest() throws ContactCamundaException, RequestDbFailureException {
+ wireMockServer.stubFor(get(
+ ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBodyFile("Camunda/HistoryCheckResponse.json")
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ InfraActiveRequests duplicateRecord = new InfraActiveRequests();
+ duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f");
+ boolean inProgress = false;
+ inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null);
+ assertTrue(inProgress);
}
+
@Test
- public void camundaHistoryCheckNoneFoundTest() throws ContactCamundaException, RequestDbFailureException{
- wireMockServer.stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody("[]").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- InfraActiveRequests duplicateRecord = new InfraActiveRequests();
- duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f");
- boolean inProgress = false;
- inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null);
- assertFalse(inProgress);
+ public void camundaHistoryCheckNoneFoundTest() throws ContactCamundaException, RequestDbFailureException {
+ wireMockServer.stubFor(get(
+ ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody("[]").withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ InfraActiveRequests duplicateRecord = new InfraActiveRequests();
+ duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f");
+ boolean inProgress = false;
+ inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null);
+ assertFalse(inProgress);
}
+
@Test
- public void camundaHistoryCheckNotInProgressTest()throws ContactCamundaException, RequestDbFailureException{
- wireMockServer.stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBodyFile("Camunda/HistoryCheckResponseCompleted.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- InfraActiveRequests duplicateRecord = new InfraActiveRequests();
- duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f");
- boolean inProgress = false;
- inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null);
- assertFalse(inProgress);
+ public void camundaHistoryCheckNotInProgressTest() throws ContactCamundaException, RequestDbFailureException {
+ wireMockServer.stubFor(get(
+ ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBodyFile("Camunda/HistoryCheckResponseCompleted.json")
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ InfraActiveRequests duplicateRecord = new InfraActiveRequests();
+ duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f");
+ boolean inProgress = false;
+ inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null);
+ assertFalse(inProgress);
}
+
@Test
- public void setCamundaHeadersTest()throws ContactCamundaException, RequestDbFailureException{
- String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password
- String key = "07a7159d3bf51a0e53be7a8f89699be7";
- HttpHeaders headers = requestHandlerUtils.setCamundaHeaders(encryptedAuth, key);
- List<org.springframework.http.MediaType> acceptedType = headers.getAccept();
- String expectedAcceptedType = "application/json";
- assertEquals(expectedAcceptedType, acceptedType.get(0).toString());
- String basicAuth = headers.getFirst(HttpHeaders.AUTHORIZATION);
- String expectedBasicAuth = "Basic dXNlcjpwYXNzd29yZA==";
- assertEquals(expectedBasicAuth, basicAuth);
- }
-
+ public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException {
+ String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password
+ String key = "07a7159d3bf51a0e53be7a8f89699be7";
+ HttpHeaders headers = requestHandlerUtils.setCamundaHeaders(encryptedAuth, key);
+ List<org.springframework.http.MediaType> acceptedType = headers.getAccept();
+ String expectedAcceptedType = "application/json";
+ assertEquals(expectedAcceptedType, acceptedType.get(0).toString());
+ String basicAuth = headers.getFirst(HttpHeaders.AUTHORIZATION);
+ String expectedBasicAuth = "Basic dXNlcjpwYXNzd29yZA==";
+ assertEquals(expectedBasicAuth, basicAuth);
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java
index 33d9d413d6..328414930e 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java
@@ -21,10 +21,8 @@
package org.onap.so.apihandlerinfra;
import java.util.List;
-
import org.junit.Before;
import org.junit.Test;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.filters.FilterEnum;
import com.openpojo.reflection.impl.PojoClassFactory;
@@ -34,17 +32,19 @@ import com.openpojo.validation.rule.impl.*;
import com.openpojo.validation.test.impl.*;
-public class ServiceInstanceBeansTest extends BaseTest{
- List<PojoClass> pojoClasses;
- @Before
- public void setup() {
- pojoClasses = PojoClassFactory.getPojoClassesRecursively("org.onap.so.serviceinstancebeans", new FilterEnum());
- }
- @Test
- public void validateGettersAndSetters() {
- Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule())
- .with(new SetterTester(), new GetterTester()).build();
- validator.validate(pojoClasses);
- }
+public class ServiceInstanceBeansTest extends BaseTest {
+ List<PojoClass> pojoClasses;
+
+ @Before
+ public void setup() {
+ pojoClasses = PojoClassFactory.getPojoClassesRecursively("org.onap.so.serviceinstancebeans", new FilterEnum());
+ }
+
+ @Test
+ public void validateGettersAndSetters() {
+ Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule())
+ .with(new SetterTester(), new GetterTester()).build();
+ validator.validate(pojoClasses);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java
index d3899fd318..1bb3932cff 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java
@@ -42,8 +42,6 @@ import static org.onap.so.logger.MdcConstants.RESPONSEDESC;
import static org.onap.so.logger.MdcConstants.SERVICE_NAME;
import static org.onap.so.logger.MdcConstants.STATUSCODE;
import static org.onap.so.logger.HttpHeadersConstants.TRANSACTION_ID;
-
-
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
@@ -52,10 +50,8 @@ import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
@@ -78,7 +74,6 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -86,20 +81,19 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.http.Fault;
-
import ch.qos.logback.classic.spi.ILoggingEvent;
-public class ServiceInstancesTest extends BaseTest{
+public class ServiceInstancesTest extends BaseTest {
+
+ private final ObjectMapper mapper = new ObjectMapper();
+ private ObjectMapper errorMapper = new ObjectMapper();
- private final ObjectMapper mapper = new ObjectMapper();
- private ObjectMapper errorMapper = new ObjectMapper();
-
@Autowired
private ServiceInstances servInstances;
-
- @Value("${wiremock.server.port}")
- private String wiremockPort;
+
+ @Value("${wiremock.server.port}")
+ private String wiremockPort;
private final String servInstanceuri = "/onap/so/infra/serviceInstantiation/";
private final String servInstanceUriPrev7 = "/onap/so/infra/serviceInstances/";
@@ -109,79 +103,79 @@ public class ServiceInstancesTest extends BaseTest{
private int initialPort;
private HttpHeaders headers;
- @Before
- public void beforeClass() {
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
+ @Before
+ public void beforeClass() {
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
// set headers
- headers = new HttpHeaders();
- headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name");
- headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
+ headers = new HttpHeaders();
+ headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name");
+ headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
headers.set(CLIENT_ID, "VID");
headers.set(REQUESTOR_ID, "xxxxxx");
- try { // generate one-time port number to avoid RANDOM port number later.
- initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH));
- initialPort = initialUrl.getPort();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- }
-
- public String inputStream(String JsonInput)throws IOException{
+ try { // generate one-time port number to avoid RANDOM port number later.
+ initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH));
+ initialPort = initialUrl.getPort();
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests.*")).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
+ }
+
+ public String inputStream(String JsonInput) throws IOException {
JsonInput = "src/test/resources/ServiceInstanceTest" + JsonInput;
return new String(Files.readAllBytes(Paths.get(JsonInput)));
}
private URL createExpectedSelfLink(String version, String requestId) {
- System.out.println("createdUrl: " + initialUrl.toString());
- try {
- selfLink = new URL(initialUrl.toString().concat("/").concat(version).concat("/").concat(requestId));
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- return selfLink;
- }
-
- private String getWiremockResponseForCatalogdb(String file) {
- try {
- File resource= ResourceUtils.getFile("classpath:__files/catalogdb/"+file);
- return new String(Files.readAllBytes(resource.toPath())).replaceAll("localhost:8090","localhost:"+wiremockPort);
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- }
-
- }
-
- public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod, HttpHeaders headers){
-
- if (!headers.containsKey(HttpHeaders.ACCEPT)) {
- headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
- }
- if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
- headers.set(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON);
- }
+ System.out.println("createdUrl: " + initialUrl.toString());
+ try {
+ selfLink = new URL(initialUrl.toString().concat("/").concat(version).concat("/").concat(requestId));
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ }
+ return selfLink;
+ }
+
+ private String getWiremockResponseForCatalogdb(String file) {
+ try {
+ File resource = ResourceUtils.getFile("classpath:__files/catalogdb/" + file);
+ return new String(Files.readAllBytes(resource.toPath())).replaceAll("localhost:8090",
+ "localhost:" + wiremockPort);
+ } catch (IOException e) {
+ e.printStackTrace();
+ return null;
+ }
+
+ }
+
+ public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod,
+ HttpHeaders headers) {
+
+ if (!headers.containsKey(HttpHeaders.ACCEPT)) {
+ headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
+ }
+ if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
+ headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
+ }
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath, initialPort));
HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
- return restTemplate.exchange(builder.toUriString(),
- reqMethod, request, String.class);
+ return restTemplate.exchange(builder.toUriString(), reqMethod, request, String.class);
}
-
- public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod){
- return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders());
+
+ public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) {
+ return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders());
}
-
+
@Test
- public void createServiceInstanceVIDDefault() throws IOException{
+ public void createServiceInstanceVIDDefault() throws IOException {
TestAppender.events.clear();
ServiceRecipe serviceRecipe = new ServiceRecipe();
@@ -192,68 +186,67 @@ public class ServiceInstancesTest extends BaseTest{
serviceRecipe.setRecipeTimeout(180);
Service defaultService = new Service();
defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
-
+
+
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
- //expect
+ // expect
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
- //then
+ // then
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
-
-
-
- for(ILoggingEvent logEvent : TestAppender.events)
- if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") &&
- logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")
- ){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+
+
+
+ for (ILoggingEvent logEvent : TestAppender.events)
+ if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging")
+ && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
assertNotNull(mdc.get(INVOCATION_ID));
- assertEquals("UNKNOWN",mdc.get(PARTNERNAME));
- assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances",mdc.get(SERVICE_NAME));
- assertEquals("INPROGRESS",mdc.get(STATUSCODE));
- }else if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") &&
- logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+ assertEquals("UNKNOWN", mdc.get(PARTNERNAME));
+ assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances", mdc.get(SERVICE_NAME));
+ assertEquals("INPROGRESS", mdc.get(STATUSCODE));
+ } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging")
+ && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP));
assertNotNull(mdc.get(ENDTIME));
assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
assertNotNull(mdc.get(INVOCATION_ID));
- assertEquals("202",mdc.get(RESPONSECODE));
- assertEquals("UNKNOWN",mdc.get(PARTNERNAME));
- assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances",mdc.get(SERVICE_NAME));
- assertEquals("COMPLETE",mdc.get(STATUSCODE));
+ assertEquals("202", mdc.get(RESPONSECODE));
+ assertEquals("UNKNOWN", mdc.get(PARTNERNAME));
+ assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances", mdc.get(SERVICE_NAME));
+ assertEquals("COMPLETE", mdc.get(STATUSCODE));
assertNotNull(mdc.get(RESPONSEDESC));
assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0));
assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0));
assertEquals("5.0.0", response.getHeaders().get("X-LatestVersion").get(0));
}
}
+
@Test
- public void createServiceInstanceServiceInstancesUri() throws IOException{
+ public void createServiceInstanceServiceInstancesUri() throws IOException {
ServiceRecipe serviceRecipe = new ServiceRecipe();
serviceRecipe.setOrchestrationUri("/mso/async/services/CreateGenericALaCarteServiceInstance");
serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
@@ -262,37 +255,37 @@ public class ServiceInstancesTest extends BaseTest{
serviceRecipe.setRecipeTimeout(180);
Service defaultService = new Service();
defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
+
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateGenericALaCarteServiceInstance"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
+
wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
- //expect
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+ // expect
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceUriPrev7 + "v5";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePrev7.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstancePrev7.json"), uri, HttpMethod.POST, headers);
- //then
+ // then
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
- public void createServiceInstanceBpelStatusError() throws IOException{
+ public void createServiceInstanceBpelStatusError() throws IOException {
ServiceRecipe serviceRecipe = new ServiceRecipe();
serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
@@ -303,486 +296,505 @@ public class ServiceInstancesTest extends BaseTest{
defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY)));
-
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY)));
+
wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceStatusError.json"), uri, HttpMethod.POST);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceStatusError.json"), uri, HttpMethod.POST);
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
}
+
@Test
- public void createServiceInstanceBadGateway() throws IOException{
- ServiceRecipe serviceRecipe = new ServiceRecipe();
- serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
- serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- serviceRecipe.setAction(Action.createInstance.toString());
- serviceRecipe.setId(1);
- serviceRecipe.setRecipeTimeout(180);
- Service defaultService = new Service();
- defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
+ public void createServiceInstanceBadGateway() throws IOException {
+ ServiceRecipe serviceRecipe = new ServiceRecipe();
+ serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
+ serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ serviceRecipe.setAction(Action.createInstance.toString());
+ serviceRecipe.setId(1);
+ serviceRecipe.setRecipeTimeout(180);
+ Service defaultService = new Service();
+ defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY).withBody("{}")));
-
- wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceBadGateway.json"), uri, HttpMethod.POST);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceBadGateway.json"), uri, HttpMethod.POST);
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
}
+
@Test
- public void createServiceInstanceEmptyResponse() throws IOException{
- ServiceRecipe serviceRecipe = new ServiceRecipe();
- serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
- serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- serviceRecipe.setAction(Action.createInstance.toString());
- serviceRecipe.setId(1);
- serviceRecipe.setRecipeTimeout(180);
- Service defaultService = new Service();
- defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
+ public void createServiceInstanceEmptyResponse() throws IOException {
+ ServiceRecipe serviceRecipe = new ServiceRecipe();
+ serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
+ serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ serviceRecipe.setAction(Action.createInstance.toString());
+ serviceRecipe.setId(1);
+ serviceRecipe.setRecipeTimeout(180);
+ Service defaultService = new Service();
+ defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));
-
- wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
-
+
+ wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+
uri = servInstanceuri + "v5/serviceInstances";
ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceEmpty.json"), uri, HttpMethod.POST);
assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value());
}
+
@Test
- public void activateServiceInstanceNoRecipeALaCarte() throws IOException{
- TestAppender.events.clear();
+ public void activateServiceInstanceNoRecipeALaCarte() throws IOException {
+ TestAppender.events.clear();
uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/activate";
- HttpHeaders requestIDheaders = new HttpHeaders();
- requestIDheaders.set(ONAPLogConstants.Headers.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceALaCarteTrueNoRecipe.json"), uri, HttpMethod.POST, requestIDheaders);
+ HttpHeaders requestIDheaders = new HttpHeaders();
+ requestIDheaders.set(ONAPLogConstants.Headers.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
+ ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceALaCarteTrueNoRecipe.json"), uri,
+ HttpMethod.POST, requestIDheaders);
Service defaultService = new Service();
defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
+
wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search/findFirstByServiceModelUUIDAndAction?serviceModelUUID=d88da85c-d9e8-4f73-b837-3a72a431622a&action=activateInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_NOT_FOUND)));
+
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/serviceRecipe/search/findFirstByServiceModelUUIDAndAction?serviceModelUUID=d88da85c-d9e8-4f73-b837-3a72a431622a&action=activateInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_NOT_FOUND)));
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
}
+
@Test
- public void activateServiceInstanceNoRecipe() throws IOException{
+ public void activateServiceInstanceNoRecipe() throws IOException {
uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/activate";
Service defaultService = new Service();
defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_NOT_FOUND)));
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search/.*")).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_NOT_FOUND)));
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceNoRecipe.json"), uri, HttpMethod.POST);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceNoRecipe.json"), uri, HttpMethod.POST);
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value());
}
+
@Test
- public void activateServiceInstance() throws IOException{
- ServiceRecipe serviceRecipe = new ServiceRecipe();
- serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
- serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- serviceRecipe.setAction(Action.createInstance.toString());
- serviceRecipe.setId(1);
- serviceRecipe.setRecipeTimeout(180);
- Service defaultService = new Service();
- defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+ public void activateServiceInstance() throws IOException {
+ ServiceRecipe serviceRecipe = new ServiceRecipe();
+ serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
+ serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ serviceRecipe.setAction(Action.createInstance.toString());
+ serviceRecipe.setId(1);
+ serviceRecipe.setRecipeTimeout(180);
+ Service defaultService = new Service();
+ defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/activate";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceActivate.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceActivate.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
- public void deactivateServiceInstance() throws IOException{
+ public void deactivateServiceInstance() throws IOException {
- ServiceRecipe serviceRecipe = new ServiceRecipe();
- serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
- serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- serviceRecipe.setAction(Action.createInstance.toString());
- serviceRecipe.setId(1);
- serviceRecipe.setRecipeTimeout(180);
- Service defaultService = new Service();
- defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ ServiceRecipe serviceRecipe = new ServiceRecipe();
+ serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
+ serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ serviceRecipe.setAction(Action.createInstance.toString());
+ serviceRecipe.setId(1);
+ serviceRecipe.setRecipeTimeout(180);
+ Service defaultService = new Service();
+ defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
-
- //expected response
+ wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/deactivate";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDeactivate.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDeactivate.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void deleteServiceInstance() throws IOException {
- ServiceRecipe serviceRecipe = new ServiceRecipe();
- serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
- serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- serviceRecipe.setAction(Action.createInstance.toString());
- serviceRecipe.setId(1);
- serviceRecipe.setRecipeTimeout(180);
- Service defaultService = new Service();
- defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ ServiceRecipe serviceRecipe = new ServiceRecipe();
+ serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
+ serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ serviceRecipe.setAction(Action.createInstance.toString());
+ serviceRecipe.setId(1);
+ serviceRecipe.setRecipeTimeout(180);
+ Service defaultService = new Service();
+ defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a8868/";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDelete.json"), uri, HttpMethod.DELETE, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDelete.json"), uri, HttpMethod.DELETE, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void assignServiceInstance() throws IOException {
- ServiceRecipe serviceRecipe = new ServiceRecipe();
- serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
- serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- serviceRecipe.setAction(Action.createInstance.toString());
- serviceRecipe.setId(1);
- serviceRecipe.setRecipeTimeout(180);
- Service defaultService = new Service();
- defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ ServiceRecipe serviceRecipe = new ServiceRecipe();
+ serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
+ serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ serviceRecipe.setAction(Action.createInstance.toString());
+ serviceRecipe.setId(1);
+ serviceRecipe.setRecipeTimeout(180);
+ Service defaultService = new Service();
+ defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v7" + "/serviceInstances/assign";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceAssign.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceAssign.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
@Test
public void unassignServiceInstance() throws IOException {
- ServiceRecipe serviceRecipe = new ServiceRecipe();
- serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
- serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- serviceRecipe.setAction(Action.createInstance.toString());
- serviceRecipe.setId(1);
- serviceRecipe.setRecipeTimeout(180);
- Service defaultService = new Service();
- defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ ServiceRecipe serviceRecipe = new ServiceRecipe();
+ serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
+ serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ serviceRecipe.setAction(Action.createInstance.toString());
+ serviceRecipe.setId(1);
+ serviceRecipe.setRecipeTimeout(180);
+ Service defaultService = new Service();
+ defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v7" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/unassign";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceUnassign.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceUnassign.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void createPortConfiguration() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePortConfiguration.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstancePortConfiguration.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
assertTrue(response.getBody().contains("1882939"));
}
+
@Test
public void createPortConfigurationEmptyProductFamilyId() throws IOException {
uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceParseFail.json"), uri, HttpMethod.POST);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceParseFail.json"), uri, HttpMethod.POST);
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
}
+
@Test
public void deletePortConfiguration() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstance.json"), uri, HttpMethod.DELETE, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstance.json"), uri, HttpMethod.DELETE, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void enablePort() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/enablePort";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceEnablePort.json"), uri, HttpMethod.POST, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/enablePort";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceEnablePort.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void disablePort() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/disablePort";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDisablePort.json"), uri, HttpMethod.POST, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/disablePort";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDisablePort.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void activatePort() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/activate";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceActivatePort.json"), uri, HttpMethod.POST, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/activate";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceActivatePort.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void deactivatePort() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/deactivate";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDeactivatePort.json"), uri, HttpMethod.POST, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/deactivate";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDeactivatePort.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void addRelationships() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/addRelationships";
- ResponseEntity<String> response = sendRequest(inputStream("/AddRelationships.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/AddRelationships.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void removeRelationships() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/removeRelationships";
- ResponseEntity<String> response = sendRequest(inputStream("/RemoveRelationships.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/RemoveRelationships.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void createVnfInstanceNoALaCarte() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
@@ -790,34 +802,39 @@ public class ServiceInstancesTest extends BaseTest{
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002671"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_ReplaceVnf_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002671"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfResourceCustomization_ReplaceVnf_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/1/vnfResources"))
+ wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/1/vnfResources"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vnfResources_ReplaceVnf_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=createInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfRecipeReplaceInstance_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=createInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfRecipeReplaceInstance_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v7" + "/serviceInstances/49585b36-2b5a-443a-8b10-c75d34bb5e46/vnfs";
- ResponseEntity<String> response = sendRequest(inputStream("/VnfCreateDefault.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/VnfCreateDefault.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void createVnfInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
@@ -832,281 +849,317 @@ public class ServiceInstancesTest extends BaseTest{
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vnfResourceCustomizationsList_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
-
-
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002672/vnfResources"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfResourcesCreateVnf_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=createInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfRecipeCreateInstance_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(
+ get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002672/vnfResources"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfResourcesCreateVnf_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=createInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfRecipeCreateInstance_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v7" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs";
- ResponseEntity<String> response = sendRequest(inputStream("/VnfWithServiceRelatedInstance.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/VnfWithServiceRelatedInstance.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
assertTrue(response.getBody().contains("1882939"));
}
+
@Test
public void createVnfWithServiceRelatedInstanceFail() throws IOException {
uri = servInstanceUriPrev7 + "v6" + "/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs";
- ResponseEntity<String> response = sendRequest(inputStream("/VnfWithServiceRelatedInstanceFail.json"), uri, HttpMethod.POST);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/VnfWithServiceRelatedInstanceFail.json"), uri, HttpMethod.POST);
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
}
+
@Test
- public void createVnfInstanceInvalidVnfResource() throws IOException {
+ public void createVnfInstanceInvalidVnfResource() throws IOException {
uri = servInstanceuri + "v7" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs";
ResponseEntity<String> response = sendRequest(inputStream("/NoVnfResource.json"), uri, HttpMethod.POST);
-
+
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
assertEquals("No valid vnfResource is specified", realResponse.getServiceException().getText());
}
+
@Test
public void replaceVnfInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002671"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_ReplaceVnf_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002671"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfResourceCustomization_ReplaceVnf_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/1/vnfResources"))
+ wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/1/vnfResources"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vnfResources_ReplaceVnf_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=replaceInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfRecipeReplaceInstance_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=replaceInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfRecipeReplaceInstance_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace";
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace";
ResponseEntity<String> response = sendRequest(inputStream("/ReplaceVnf.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void replaceVnfRecreateInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/RecreateInfraVce"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources"))
+ wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vnfResources_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=TEST&action=replaceInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfRecipe_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=TEST&action=replaceInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfRecipe_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace";
- ResponseEntity<String> response = sendRequest(inputStream("/ReplaceVnfRecreate.json"), uri, HttpMethod.POST, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ReplaceVnfRecreate.json"), uri, HttpMethod.POST, headers);
logger.debug(response.getBody());
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void recreateVnfInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources"))
+ wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vnfResources_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=recreateInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfRecipe_ResponseWorkflowAction.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=recreateInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfRecipe_ResponseWorkflowAction.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/recreate";
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/recreate";
ResponseEntity<String> response = sendRequest(inputStream("/VnfRecreate.json"), uri, HttpMethod.POST, headers);
logger.debug(response.getBody());
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
- public void updateVnfInstance() throws IOException {
+ public void updateVnfInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources"))
+ wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vnfResources_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" +
- "[?]nfRole=GR-API-DEFAULT&action=updateInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("UpdateVnfRecipe_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction"
+ + "[?]nfRole=GR-API-DEFAULT&action=updateInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("UpdateVnfRecipe_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000";
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000";
ResponseEntity<String> response = sendRequest(inputStream("/UpdateVnf.json"), uri, HttpMethod.PUT, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
- public void applyUpdatedConfig() throws IOException {
+ public void applyUpdatedConfig() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/VnfConfigUpdate"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" +
- "[?]nfRole=GR-API-DEFAULT&action=applyUpdatedConfig"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfRecipeApplyUpdatedConfig_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+ wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction"
+ + "[?]nfRole=GR-API-DEFAULT&action=applyUpdatedConfig"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfRecipeApplyUpdatedConfig_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/applyUpdatedConfig";
- ResponseEntity<String> response = sendRequest(inputStream("/ApplyUpdatedConfig.json"), uri, HttpMethod.POST, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/applyUpdatedConfig";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ApplyUpdatedConfig.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void deleteVnfInstanceV5() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" +
- "[?]nfRole=GR-API-DEFAULT&action=deleteInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfRecipeDelete_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction"
+ + "[?]nfRole=GR-API-DEFAULT&action=deleteInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfRecipeDelete_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v5" + "/serviceInstances/e446b97d-9c35-437a-95a2-6b4c542c4507/vnfs/49befbfe-fccb-421d-bb4c-0734a43f5ea0";
- ResponseEntity<String> response = sendRequest(inputStream("/DeleteVnfV5.json"), uri, HttpMethod.DELETE, headers);
-
+ uri = servInstanceuri + "v5"
+ + "/serviceInstances/e446b97d-9c35-437a-95a2-6b4c542c4507/vnfs/49befbfe-fccb-421d-bb4c-0734a43f5ea0";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/DeleteVnfV5.json"), uri, HttpMethod.DELETE, headers);
+
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void createVfModuleInstance() throws IOException {
- wireMockServer.stubFor(get(urlMatching("/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc\\?MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching("/vfModule/20c4431c-246d-11e7-93ae-92361f002671"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching("/vfModuleCustomization/1/vfModule"))
+ wireMockServer.stubFor(get(urlMatching(
+ "/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc\\?MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching("/vfModule/20c4431c-246d-11e7-93ae-92361f002671"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching("/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc\\?MODEL_CUSTOMIZATION_UUID=20c4431c-246d-11e7-93ae-92361f002671"))
+ wireMockServer.stubFor(get(urlMatching("/vfModuleCustomization/1/vfModule"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateVfModuleInfra"))
+
+ wireMockServer.stubFor(get(urlMatching(
+ "/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc\\?MODEL_CUSTOMIZATION_UUID=20c4431c-246d-11e7-93ae-92361f002671"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateVfModuleInfra"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching("/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" +
- "[?]vfModuleModelUUID=20c4431c-246d-11e7-93ae-92361f002671&vnfComponentType=vfModule&action=createInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipe_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(get(urlMatching(
+ "/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction"
+ + "[?]vfModuleModelUUID=20c4431c-246d-11e7-93ae-92361f002671&vnfComponentType=vfModule&action=createInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipe_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/7a88cbeb-0ec8-4765-a271-4f9e90c3da7b/vnfs/cbba721b-4803-4df7-9347-307c9a955426/vfModules";
- ResponseEntity<String> response = sendRequest(inputStream("/VfModuleWithRelatedInstances.json"), uri, HttpMethod.POST, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/7a88cbeb-0ec8-4765-a271-4f9e90c3da7b/vnfs/cbba721b-4803-4df7-9347-307c9a955426/vfModules";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/VfModuleWithRelatedInstances.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
assertTrue(response.getBody().contains("1882939"));
}
+
@Test
public void createVfModuleInstanceNoModelCustomization() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateVfModuleInfra"))
@@ -1118,24 +1171,28 @@ public class ServiceInstancesTest extends BaseTest{
.withBody(getWiremockResponseForCatalogdb("vnfResourceForVfModule_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources" +
- "[?]MODEL_INSTANCE_NAME=test&VNF_RESOURCE_MODEL_UUID=fe6478e4-ea33-3346-ac12-ab121484a3fe"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomizationForVfModule_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer
+ .stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources"
+ + "[?]MODEL_INSTANCE_NAME=test&VNF_RESOURCE_MODEL_UUID=fe6478e4-ea33-3346-ac12-ab121484a3fe"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfResourceCustomizationForVfModule_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations"))
+ wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationsPCM_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDAndVfModuleModelUUIDOrderByCreatedDesc[?]" +
- "MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002672&MODEL_UUID=066de97e-253e-11e7-93ae-92361f002672"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationPCM_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDAndVfModuleModelUUIDOrderByCreatedDesc[?]"
+ + "MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002672&MODEL_UUID=066de97e-253e-11e7-93ae-92361f002672"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vfModuleCustomizationPCM_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/2/vfModule"))
+ wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/2/vfModule"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vfModulePCM_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
@@ -1146,25 +1203,30 @@ public class ServiceInstancesTest extends BaseTest{
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVnfComponentTypeAndAction" +
- "[?]vnfComponentType=vfModule&action=createInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVNF_API_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+ wireMockServer.stubFor(
+ get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVnfComponentTypeAndAction"
+ + "[?]vnfComponentType=vfModule&action=createInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfComponentRecipeVNF_API_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v6","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v6", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v6" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules";
- ResponseEntity<String> response = sendRequest(inputStream("/VfModuleNoModelCustomization.json"), uri, HttpMethod.POST, headers);
+ uri = servInstanceuri + "v6"
+ + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/VfModuleNoModelCustomization.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ObjectMapper mapper = new ObjectMapper();
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void deleteVfModuleInstanceNoMatchingModelUUD() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
@@ -1176,22 +1238,25 @@ public class ServiceInstancesTest extends BaseTest{
.withBody(getWiremockResponseForCatalogdb("vnfResourceForVfModule_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomizationForVfModule_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer
+ .stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfResourceCustomizationForVfModule_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations"))
+ wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationsPCM_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002672"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationPCM_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002672"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationPCM_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/2/vfModule"))
+ wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/2/vfModule"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vfModulePCM_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
@@ -1201,27 +1266,32 @@ public class ServiceInstancesTest extends BaseTest{
.withBody(getWiremockResponseForCatalogdb("vfModulePCM_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" +
- "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeleteVfModule_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction"
+ + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfComponentRecipeDeleteVfModule_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v6","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v6", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v6" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000";
- ResponseEntity<String> response = sendRequest(inputStream("/VfModuleNoMatchingModelUUID.json"), uri, HttpMethod.DELETE, headers);
-
+ uri = servInstanceuri + "v6"
+ + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/VfModuleNoMatchingModelUUID.json"), uri, HttpMethod.DELETE, headers);
+
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ObjectMapper mapper = new ObjectMapper();
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void createVfModuleInstanceNoRecipe() throws IOException {
@@ -1230,72 +1300,86 @@ public class ServiceInstancesTest extends BaseTest{
.withBody(getWiremockResponseForCatalogdb("vnfResourceForVfModule_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources" +
- "[?]MODEL_INSTANCE_NAME=test&VNF_RESOURCE_MODEL_UUID=fe6478e4-ea33-3346-ac12-ab121484a3fe"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomizationForVfModule_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer
+ .stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources"
+ + "[?]MODEL_INSTANCE_NAME=test&VNF_RESOURCE_MODEL_UUID=fe6478e4-ea33-3346-ac12-ab121484a3fe"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfResourceCustomizationForVfModule_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations"))
+ wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationsPCM_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findByModelCustomizationUUIDAndVfModuleModelUUID[?]" +
- "modelCustomizationUUID=b4ea86b4-253f-11e7-93ae-92361f002672&vfModuleModelUUID=066de97e-253e-11e7-93ae-92361f002672"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationPCM_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- uri = servInstanceuri + "v6" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules";
- ResponseEntity<String> response = sendRequest(inputStream("/VfModuleInvalid.json"), uri, HttpMethod.POST, headers);
-
+ wireMockServer.stubFor(
+ get(urlMatching(".*/vfModuleCustomization/search/findByModelCustomizationUUIDAndVfModuleModelUUID[?]"
+ + "modelCustomizationUUID=b4ea86b4-253f-11e7-93ae-92361f002672&vfModuleModelUUID=066de97e-253e-11e7-93ae-92361f002672"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vfModuleCustomizationPCM_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ uri = servInstanceuri + "v6"
+ + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/VfModuleInvalid.json"), uri, HttpMethod.POST, headers);
+
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
assertEquals("No valid vfModuleCustomization is specified", realResponse.getServiceException().getText());
}
+
@Test
public void replaceVfModuleInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" +
- "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" +
- "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=replaceInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeleteVfModule_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ wireMockServer
+ .stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]"
+ + "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction"
+ + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=replaceInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfComponentRecipeDeleteVfModule_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace";
- ResponseEntity<String> response = sendRequest(inputStream("/ReplaceVfModule.json"), uri, HttpMethod.POST, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ReplaceVfModule.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void updateVfModuleInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule"))
+ wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
@@ -1305,28 +1389,33 @@ public class ServiceInstancesTest extends BaseTest{
.withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" +
- "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=updateInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipe_GRAPI_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction"
+ + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=updateInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfComponentRecipe_GRAPI_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000";
- ResponseEntity<String> response = sendRequest(inputStream("/UpdateVfModule.json"), uri, HttpMethod.PUT, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/UpdateVfModule.json"), uri, HttpMethod.PUT, headers);
logger.debug(response.getBody());
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
- public void createVfModuleNoModelType() throws IOException{
+ public void createVfModuleNoModelType() throws IOException {
InfraActiveRequests expectedRecord = new InfraActiveRequests();
expectedRecord.setRequestStatus("FAILED");
expectedRecord.setAction("createInstance");
@@ -1341,198 +1430,231 @@ public class ServiceInstancesTest extends BaseTest{
expectedRecord.setRequestAction("createInstance");
expectedRecord.setRequestorId("zz9999");
expectedRecord.setRequestId("32807a28-1a14-4b88-b7b3-2950918aa76d");
- //VnfType is not sent in this request, should be blank in db
+ // VnfType is not sent in this request, should be blank in db
expectedRecord.setVnfType("");
- uri = servInstanceuri + "v5/serviceInstances/32807a28-1a14-4b88-b7b3-2950918aa76d/vnfs/32807a28-1a14-4b88-b7b3-2950918aa76d/vfModules";
+ uri = servInstanceuri
+ + "v5/serviceInstances/32807a28-1a14-4b88-b7b3-2950918aa76d/vnfs/32807a28-1a14-4b88-b7b3-2950918aa76d/vfModules";
- ResponseEntity<String> response = sendRequest(inputStream("/VfModuleNoModelType.json"), uri, HttpMethod.POST, headers);
- //ActualRecord
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/VfModuleNoModelType.json"), uri, HttpMethod.POST, headers);
+ // ActualRecord
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
}
+
@Test
public void inPlaceSoftwareUpdate() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/VnfInPlaceUpdate"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]" +
- "nfRole=GR-API-DEFAULT&action=inPlaceSoftwareUpdate"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfRecipeInPlaceUpdate_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]"
+ + "nfRole=GR-API-DEFAULT&action=inPlaceSoftwareUpdate"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfRecipeInPlaceUpdate_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/inPlaceSoftwareUpdate";
- ResponseEntity<String> response = sendRequest(inputStream("/InPlaceSoftwareUpdate.json"), uri, HttpMethod.POST, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/inPlaceSoftwareUpdate";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/InPlaceSoftwareUpdate.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
-
+
@Test
public void deleteVfModuleInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" +
- "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" +
- "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeleteVfModule_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+ wireMockServer
+ .stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]"
+ + "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction"
+ + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfComponentRecipeDeleteVfModule_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000";
- ResponseEntity<String> response = sendRequest(inputStream("/DeleteVfModule.json"), uri, HttpMethod.DELETE, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/DeleteVfModule.json"), uri, HttpMethod.DELETE, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void deleteVfModuleNoModelInvariantId() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" +
- "[?]vfModuleModelUUID=VNF-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeleteVfModule_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction"
+ + "[?]vfModuleModelUUID=VNF-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfComponentRecipeDeleteVfModule_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/196b4a84-0858-4317-a1f6-497e2e52ae43/vnfs/36e4f902-ec32-451e-8d53-e3edc19e40a4/vfModules/09f3a38d-933f-450a-8784-9e6c4dec3f72";
- ResponseEntity<String> response = sendRequest(inputStream("/DeleteVfModuleNoModelInvariantId.json"), uri, HttpMethod.DELETE, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/196b4a84-0858-4317-a1f6-497e2e52ae43/vnfs/36e4f902-ec32-451e-8d53-e3edc19e40a4/vfModules/09f3a38d-933f-450a-8784-9e6c4dec3f72";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/DeleteVfModuleNoModelInvariantId.json"), uri, HttpMethod.DELETE, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void deactivateAndCloudDeleteVfModuleInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" +
- "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" +
- "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deactivateAndCloudDelete"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeactivate_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+ wireMockServer
+ .stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]"
+ + "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction"
+ + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deactivateAndCloudDelete"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfComponentRecipeDeactivate_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000/deactivateAndCloudDelete";
- ResponseEntity<String> response = sendRequest(inputStream("/DeactivateAndCloudDeleteVfModule.json"), uri, HttpMethod.POST, headers);
-
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000/deactivateAndCloudDelete";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/DeactivateAndCloudDeleteVfModule.json"), uri, HttpMethod.POST, headers);
+
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void createVolumeGroupInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule"))
+ wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vfModuleVolGroup_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" +
- "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=createInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVolGrp_GRAPI_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction"
+ + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=createInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfComponentRecipeVolGrp_GRAPI_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups";
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups";
ResponseEntity<String> response = sendRequest(inputStream("/VolumeGroup.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
assertTrue(response.getBody().contains("1882939"));
}
+
@Test
public void updateVolumeGroupInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule"))
+ wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vfModuleVolGroup_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" +
- "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=updateInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVolGrp_GRAPI_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction"
+ + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=updateInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfComponentRecipeVolGrp_GRAPI_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-431b-adb2-eb6b9e5ff000";
- ResponseEntity<String> response = sendRequest(inputStream("/UpdateVolumeGroup.json"), uri, HttpMethod.PUT, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-431b-adb2-eb6b9e5ff000";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/UpdateVolumeGroup.json"), uri, HttpMethod.PUT, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void deleteVolumeGroupInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
@@ -1543,35 +1665,41 @@ public class ServiceInstancesTest extends BaseTest{
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule"))
+ wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vfModuleVolGroup_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" +
- "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=deleteInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVolGrp_GRAPI_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction"
+ + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=deleteInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfComponentRecipeVolGrp_GRAPI_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-431b-adb2-eb6b9e5ff000";
- ResponseEntity<String> response = sendRequest(inputStream("/DeleteVolumeGroup.json"), uri, HttpMethod.DELETE, headers);
-
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-431b-adb2-eb6b9e5ff000";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/DeleteVolumeGroup.json"), uri, HttpMethod.DELETE, headers);
+
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void createNetworkInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
@@ -1583,30 +1711,33 @@ public class ServiceInstancesTest extends BaseTest{
.withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json"))
.withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json"))
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(
+ get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json"))
+ .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" +
- "modelName=GR-API-DEFAULT&action=createInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+ wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]"
+ + "modelName=GR-API-DEFAULT&action=createInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks";
- ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreate.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/NetworkCreate.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void updateNetworkInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
@@ -1618,30 +1749,33 @@ public class ServiceInstancesTest extends BaseTest{
.withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json"))
.withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json"))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" +
- "modelName=GR-API-DEFAULT&action=updateInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ wireMockServer.stubFor(
+ get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json"))
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]"
+ + "modelName=GR-API-DEFAULT&action=updateInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb";
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb";
ResponseEntity<String> response = sendRequest(inputStream("/UpdateNetwork.json"), uri, HttpMethod.PUT, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
assertTrue(response.getBody().contains("1882939"));
}
+
@Test
public void deleteNetworkInstance() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
@@ -1653,59 +1787,66 @@ public class ServiceInstancesTest extends BaseTest{
.withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json"))
.withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json"))
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(
+ get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json"))
+ .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" +
- "modelName=VNF-API-DEFAULT&action=deleteInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+ wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]"
+ + "modelName=VNF-API-DEFAULT&action=deleteInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb";
- ResponseEntity<String> response = sendRequest(inputStream("/NetworkInstance.json"), uri, HttpMethod.DELETE, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/NetworkInstance.json"), uri, HttpMethod.DELETE, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void deleteNetworkInstanceNoReqParams() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" +
- "modelName=GR-API-DEFAULT&action=deleteInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]"
+ + "modelName=GR-API-DEFAULT&action=deleteInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v6","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v6", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v6" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb";
- ResponseEntity<String> response = sendRequest(inputStream("/NetworkInstanceNoReqParams.json"), uri, HttpMethod.DELETE, headers);
+ uri = servInstanceuri + "v6"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/NetworkInstanceNoReqParams.json"), uri, HttpMethod.DELETE, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void convertJsonToServiceInstanceRequestFail() throws IOException {
- //ExpectedRecord
+ // ExpectedRecord
InfraActiveRequests expectedRecord = new InfraActiveRequests();
expectedRecord.setRequestStatus("FAILED");
expectedRecord.setStatusMessage("Error mapping request: ");
@@ -1716,16 +1857,20 @@ public class ServiceInstancesTest extends BaseTest{
expectedRecord.setRequestAction("deleteInstance");
expectedRecord.setRequestId("32807a28-1a14-4b88-b7b3-2950918aa76d");
- uri = servInstanceuri + "v6" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb";
- ResponseEntity<String> response = sendRequest(inputStream("/ConvertRequestFail.json"), uri, HttpMethod.DELETE, headers);
+ uri = servInstanceuri + "v6"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ConvertRequestFail.json"), uri, HttpMethod.DELETE, headers);
- //ActualRecord
+ // ActualRecord
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
}
+
@Test
public void convertJsonToServiceInstanceRequestConfigurationFail() throws IOException {
- uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/configurations/test/enablePort";
+ uri = servInstanceuri + "v5"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/configurations/test/enablePort";
ResponseEntity<String> response = sendRequest(inputStream("/ConvertRequestFail.json"), uri, HttpMethod.POST);
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
@@ -1745,30 +1890,29 @@ public class ServiceInstancesTest extends BaseTest{
serviceRecipe.setRecipeTimeout(180);
Service defaultService = new Service();
defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
+
wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
-
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+
uri = servInstanceuri + "v7" + "/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceMacro.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceMacro.json"), uri, HttpMethod.POST, headers);
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
@Test
@@ -1782,30 +1926,32 @@ public class ServiceInstancesTest extends BaseTest{
.withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json"))
.withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json"))
- .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(
+ get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json"))
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]"
+ + "modelName=GR-API-DEFAULT&action=createInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" +
- "modelName=GR-API-DEFAULT&action=createInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks";
- ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreateAlternateInstanceName.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/NetworkCreateAlternateInstanceName.json"), uri, HttpMethod.POST, headers);
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
@Test
@@ -1815,9 +1961,10 @@ public class ServiceInstancesTest extends BaseTest{
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks";
- ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreateTestApiIncorrect.json"), uri, HttpMethod.POST);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/NetworkCreateTestApiIncorrect.json"), uri, HttpMethod.POST);
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
@@ -1837,30 +1984,32 @@ public class ServiceInstancesTest extends BaseTest{
.withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json"))
.withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json"))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" +
- "modelName=GR-API-DEFAULT&action=createInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
+ wireMockServer.stubFor(
+ get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json"))
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]"
+ + "modelName=GR-API-DEFAULT&action=createInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks";
- ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreateTestApiGrApi.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/NetworkCreateTestApiGrApi.json"), uri, HttpMethod.POST, headers);
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
@Test
@@ -1874,34 +2023,36 @@ public class ServiceInstancesTest extends BaseTest{
.withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json"))
.withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json"))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" +
- "modelName=VNF-API-DEFAULT&action=createInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkRecipeVNF_API_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
+ wireMockServer.stubFor(
+ get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json"))
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]"
+ + "modelName=VNF-API-DEFAULT&action=createInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkRecipeVNF_API_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks";
- ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreateTestApiVnfApi.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/NetworkCreateTestApiVnfApi.json"), uri, HttpMethod.POST, headers);
- //expected response
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
@Test
- public void activateServiceInstanceRequestStatus() throws IOException{
+ public void activateServiceInstanceRequestStatus() throws IOException {
ServiceRecipe serviceRecipe = new ServiceRecipe();
serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
@@ -1910,33 +2061,32 @@ public class ServiceInstancesTest extends BaseTest{
serviceRecipe.setRecipeTimeout(180);
Service defaultService = new Service();
defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
-
- //expect
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+
+ // expect
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7999/activate";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePrev8.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstancePrev8.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
@Test
@@ -1945,13 +2095,15 @@ public class ServiceInstancesTest extends BaseTest{
HttpHeaders ivalidRequestIdHeaders = new HttpHeaders();
ivalidRequestIdHeaders.set(ONAPLogConstants.Headers.REQUEST_ID, illegalRequestId);
uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, ivalidRequestIdHeaders);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, ivalidRequestIdHeaders);
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
assertTrue(response.getBody().contains("Request Id " + illegalRequestId + " is not a valid UUID"));
}
+
@Test
- public void invalidBPELResponse() throws IOException{
+ public void invalidBPELResponse() throws IOException {
ServiceRecipe serviceRecipe = new ServiceRecipe();
serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
@@ -1961,30 +2113,31 @@ public class ServiceInstancesTest extends BaseTest{
serviceRecipe.setRecipeTimeout(180);
Service defaultService = new Service();
defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBodyFile("Camunda/TestResponseInvalid2.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBodyFile("Camunda/TestResponseInvalid2.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
-
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+
uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
-
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
+
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals("Request Failed due to BPEL error with HTTP Status = 202{\"instanceId\": \"1882939\"}", realResponse.getServiceException().getText());
+ assertEquals("Request Failed due to BPEL error with HTTP Status = 202{\"instanceId\": \"1882939\"}",
+ realResponse.getServiceException().getText());
}
+
@Test
- public void unauthorizedBPELResponse() throws IOException{
+ public void unauthorizedBPELResponse() throws IOException {
ServiceRecipe serviceRecipe = new ServiceRecipe();
serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
@@ -1994,31 +2147,32 @@ public class ServiceInstancesTest extends BaseTest{
serviceRecipe.setRecipeTimeout(180);
Service defaultService = new Service();
defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBodyFile("Camunda/UnauthorizedResponse.json").withStatus(org.apache.http.HttpStatus.SC_UNAUTHORIZED)));
+ .withBodyFile("Camunda/UnauthorizedResponse.json")
+ .withStatus(org.apache.http.HttpStatus.SC_UNAUTHORIZED)));
wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
-
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+
uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals("Exception caught mapping Camunda JSON response to object", realResponse.getServiceException().getText());
+ assertEquals("Exception caught mapping Camunda JSON response to object",
+ realResponse.getServiceException().getText());
}
@Test
- public void invalidBPELResponse2() throws IOException{
+ public void invalidBPELResponse2() throws IOException {
ServiceRecipe serviceRecipe = new ServiceRecipe();
serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
@@ -2028,30 +2182,30 @@ public class ServiceInstancesTest extends BaseTest{
serviceRecipe.setRecipeTimeout(180);
Service defaultService = new Service();
defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBodyFile("Camunda/TestResponseInvalid.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBodyFile("Camunda/TestResponseInvalid.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
-
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
+
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertTrue(realResponse.getServiceException().getText().contains("<aetgt:ErrorMessage>Exception in create execution list 500"));
+ assertTrue(realResponse.getServiceException().getText()
+ .contains("<aetgt:ErrorMessage>Exception in create execution list 500"));
}
@Test
- public void createMacroServiceInstance() throws IOException{
+ public void createMacroServiceInstance() throws IOException {
ServiceRecipe serviceRecipe = new ServiceRecipe();
serviceRecipe.setOrchestrationUri("/mso/async/services/CreateMacroServiceNetworkVnf");
serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
@@ -2060,44 +2214,44 @@ public class ServiceInstancesTest extends BaseTest{
serviceRecipe.setRecipeTimeout(180);
Service defaultService = new Service();
defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateMacroServiceNetworkVnf"))
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateMacroServiceNetworkVnf"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBodyFile("Camunda/TestResponseInvalid.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBodyFile("Camunda/TestResponseInvalid.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
- //expect
+ // expect
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceUriPrev7 + "v5";
- ResponseEntity<String> response = sendRequest(inputStream("/MacroServiceInstance.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/MacroServiceInstance.json"), uri, HttpMethod.POST, headers);
- //then
+ // then
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
@Test
public void testUserParams() throws IOException {
ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest request = mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class);
+ ServiceInstancesRequest request =
+ mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class);
RequestParameters requestParameters = request.getRequestDetails().getRequestParameters();
String userParamsTxt = inputStream("/userParams.txt");
@@ -2112,8 +2266,10 @@ public class ServiceInstancesTest extends BaseTest{
@Test
public void testConfigureCloudConfig() throws IOException {
ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest request = mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class);
- CloudConfiguration cloudConfig = servInstances.configureCloudConfig(request.getRequestDetails().getRequestParameters());
+ ServiceInstancesRequest request =
+ mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class);
+ CloudConfiguration cloudConfig =
+ servInstances.configureCloudConfig(request.getRequestDetails().getRequestParameters());
assertEquals("mdt25b", cloudConfig.getLcpCloudRegionId());
assertEquals("aefb697db6524ddebfe4915591b0a347", cloudConfig.getTenantId());
@@ -2122,24 +2278,28 @@ public class ServiceInstancesTest extends BaseTest{
@Test
public void testMapToLegacyRequest() throws IOException {
ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest request = mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class);
- ServiceInstancesRequest expected = mapper.readValue(inputStream("/LegacyMacroServiceInstance.json"), ServiceInstancesRequest.class);
+ ServiceInstancesRequest request =
+ mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class);
+ ServiceInstancesRequest expected =
+ mapper.readValue(inputStream("/LegacyMacroServiceInstance.json"), ServiceInstancesRequest.class);
servInstances.mapToLegacyRequest(request.getRequestDetails());
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(request));
assertThat(request, sameBeanAs(expected));
}
+
@Test
public void scaleOutVfModule() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule"))
+ wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vfModule_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
@@ -2150,125 +2310,152 @@ public class ServiceInstancesTest extends BaseTest{
.withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" +
- "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=scaleOut"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVfModuleScaleOut_Response.json")).withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/vfModule/search/findByModelInvariantUUIDOrderByModelVersionDesc[?]modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vfModulesListByInvariantId_Response.json")).withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction"
+ + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=scaleOut"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb(
+ "vnfComponentRecipeVfModuleScaleOut_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vfModule/search/findByModelInvariantUUIDOrderByModelVersionDesc[?]modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vfModulesListByInvariantId_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/7a88cbeb-0ec8-4765-a271-4f9e90c3da7b/vnfs/cbba721b-4803-4df7-9347-307c9a955426/vfModules/scaleOut";
- ResponseEntity<String> response = sendRequest(inputStream("/ScaleOutRequest.json"), uri, HttpMethod.POST, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/7a88cbeb-0ec8-4765-a271-4f9e90c3da7b/vnfs/cbba721b-4803-4df7-9347-307c9a955426/vfModules/scaleOut";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ScaleOutRequest.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
assertTrue(response.getBody().contains("1882939"));
}
+
@Test
- public void createServiceInstanceBadResponse() throws IOException{
- ServiceRecipe serviceRecipe = new ServiceRecipe();
- serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
- serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- serviceRecipe.setAction(Action.createInstance.toString());
- serviceRecipe.setId(1);
- serviceRecipe.setRecipeTimeout(180);
- Service defaultService = new Service();
- defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
-
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBodyFile("Camunda/TestBadResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
-
- uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
-
- assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatusCode().value());
- RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals("Exception caught mapping Camunda JSON response to object", realResponse.getServiceException().getText());
- }
- @Test
- public void createServiceInstanceDuplicateError() throws IOException{
- wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
-
+ public void createServiceInstanceBadResponse() throws IOException {
+ ServiceRecipe serviceRecipe = new ServiceRecipe();
+ serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
+ serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+ serviceRecipe.setAction(Action.createInstance.toString());
+ serviceRecipe.setId(1);
+ serviceRecipe.setRecipeTimeout(180);
+ Service defaultService = new Service();
+ defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBodyFile("Camunda/TestBadResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+
uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
-
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
+
+ assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatusCode().value());
+ RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
+ assertEquals("Exception caught mapping Camunda JSON response to object",
+ realResponse.getServiceException().getText());
+ }
+
+ @Test
+ public void createServiceInstanceDuplicateError() throws IOException {
+ wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+
+ uri = servInstanceuri + "v5/serviceInstances";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
+
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals("Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText());
+ assertEquals(
+ "Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error",
+ realResponse.getServiceException().getText());
}
+
@Test
- public void createServiceInstanceDuplicateHistoryCheck() throws IOException{
- wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBodyFile("InfraActiveRequests/createInfraActiveRequests.json")
- .withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
+ public void createServiceInstanceDuplicateHistoryCheck() throws IOException {
+ wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBodyFile("Camunda/HistoryCheckResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
+ .withBodyFile("InfraActiveRequests/createInfraActiveRequests.json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(get(
+ ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBodyFile("Camunda/HistoryCheckResponse.json")
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
-
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
+
assertEquals(Response.Status.CONFLICT.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals("Error: Locked instance - This service (testService9) already has a request being worked with a status of UNLOCKED (RequestId - f0a35706-efc4-4e27-80ea-a995d7a2a40f). The existing request must finish or be cleaned up before proceeding.", realResponse.getServiceException().getText());
+ assertEquals(
+ "Error: Locked instance - This service (testService9) already has a request being worked with a status of UNLOCKED (RequestId - f0a35706-efc4-4e27-80ea-a995d7a2a40f). The existing request must finish or be cleaned up before proceeding.",
+ realResponse.getServiceException().getText());
}
+
@Test
- public void createServiceInstanceDuplicateHistoryCheckException() throws IOException{
- wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBodyFile("InfraActiveRequests/createInfraActiveRequests.json")
- .withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
+ public void createServiceInstanceDuplicateHistoryCheckException() throws IOException {
+ wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR)));
-
+ .withBodyFile("InfraActiveRequests/createInfraActiveRequests.json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(get(
+ ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+
uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
-
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
+
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals("Unable to get process-instance history from Camunda for requestId: f0a35706-efc4-4e27-80ea-a995d7a2a40f due to error: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText());
+ assertEquals(
+ "Unable to get process-instance history from Camunda for requestId: f0a35706-efc4-4e27-80ea-a995d7a2a40f due to error: org.springframework.web.client.HttpServerErrorException: 500 Server Error",
+ realResponse.getServiceException().getText());
}
+
@Test
- public void createServiceInstanceDuplicate() throws IOException{
- wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
-
+ public void createServiceInstanceDuplicate() throws IOException {
+ wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+
uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals("Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText());
+ assertEquals(
+ "Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error",
+ realResponse.getServiceException().getText());
}
-
+
@Test
- public void createServiceInstanceSaveError() throws IOException{
- ServiceRecipe serviceRecipe = new ServiceRecipe();
+ public void createServiceInstanceSaveError() throws IOException {
+ ServiceRecipe serviceRecipe = new ServiceRecipe();
serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
serviceRecipe.setAction(Action.createInstance.toString());
@@ -2276,218 +2463,241 @@ public class ServiceInstancesTest extends BaseTest{
serviceRecipe.setRecipeTimeout(180);
Service defaultService = new Service();
defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a");
- wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
- wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
+ wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(defaultService))
- .withStatus(HttpStatus.SC_OK)));
+ .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+ wireMockServer.stubFor(get(urlMatching(".*/service/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceRecipe))
- .withStatus(HttpStatus.SC_OK)));
-
+ .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK)));
+
uri = servInstanceuri + "v5/serviceInstances";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers);
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals("Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText());
+ assertEquals(
+ "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error",
+ realResponse.getServiceException().getText());
}
+
@Test
public void createPortConfigurationSaveError() throws IOException {
- wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+ wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
+
uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePortConfiguration.json"), uri, HttpMethod.POST, headers);
-
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstancePortConfiguration.json"), uri, HttpMethod.POST, headers);
+
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals("Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText());
+ assertEquals(
+ "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error",
+ realResponse.getServiceException().getText());
}
+
@Test
public void createPortConfigDbUpdateError() throws IOException {
- wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
-
+ wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+
uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations";
- ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceParseFail.json"), uri, HttpMethod.POST, headers);
-
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/ServiceInstanceParseFail.json"), uri, HttpMethod.POST, headers);
+
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals("Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText());
+ assertEquals(
+ "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error",
+ realResponse.getServiceException().getText());
}
+
@Test
- public void vnfUpdateWithNetworkInstanceGroup() throws IOException{
- TestAppender.events.clear();
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+ public void vnfUpdateWithNetworkInstanceGroup() throws IOException {
+ TestAppender.events.clear();
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=2ccae1b4-7d9e-46fa-a452-9180ce008d17"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlMatching(
+ ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=2ccae1b4-7d9e-46fa-a452-9180ce008d17"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources"))
+ wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(getWiremockResponseForCatalogdb("vnfResources_Response.json"))
.withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" +
- "[?]nfRole=GR-API-DEFAULT&action=updateInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("UpdateVnfRecipe_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction"
+ + "[?]nfRole=GR-API-DEFAULT&action=updateInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("UpdateVnfRecipe_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "VID");
- //expect
+ // expect
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7/serviceInstances/e05864f0-ab35-47d0-8be4-56fd9619ba3c/vnfs/f501ce76-a9bc-4601-9837-74fd9f4d5eca";
- ResponseEntity<String> response = sendRequest(inputStream("/VnfwithNeteworkInstanceGroup.json"), uri, HttpMethod.PUT, headers);
- //then
+ uri = servInstanceuri
+ + "v7/serviceInstances/e05864f0-ab35-47d0-8be4-56fd9619ba3c/vnfs/f501ce76-a9bc-4601-9837-74fd9f4d5eca";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/VnfwithNeteworkInstanceGroup.json"), uri, HttpMethod.PUT, headers);
+ // then
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
assertEquals(response.getHeaders().get(TRANSACTION_ID).get(0), "32807a28-1a14-4b88-b7b3-2950918aa76d");
-
- for(ILoggingEvent logEvent : TestAppender.events){
- if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging") &&
- logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
- assertEquals("32807a28-1a14-4b88-b7b3-2950918aa76d", mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
- assertEquals("VID",mdc.get(PARTNERNAME));
+
+ for (ILoggingEvent logEvent : TestAppender.events) {
+ if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging")
+ && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
+ assertEquals("32807a28-1a14-4b88-b7b3-2950918aa76d", mdc.get(ONAPLogConstants.MDCs.REQUEST_ID));
+ assertEquals("VID", mdc.get(PARTNERNAME));
}
}
}
+
@Test
- public void createInstanceGroup() throws IOException{
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+ public void createInstanceGroup() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expect
+
+ // expect
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "/v7/instanceGroups";
- ResponseEntity<String> response = sendRequest(inputStream("/CreateInstanceGroup.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/CreateInstanceGroup.json"), uri, HttpMethod.POST, headers);
- //then
+ // then
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
- public void deleteInstanceGroup() throws IOException{
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+ public void deleteInstanceGroup() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expect
+
+ // expect
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c";
ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE, headers);
- //then
+ // then
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
- public void deleteInstanceGroupNoRequestIdHeader() throws IOException{
+ public void deleteInstanceGroupNoRequestIdHeader() throws IOException {
uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c";
ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE);
- //then
+ // then
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-RequestID header is specified");
+ assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-RequestID header is specified");
}
+
@Test
- public void deleteInstanceGroupNoPartnerNameHeader() throws IOException{
- HttpHeaders noPartnerHeaders = new HttpHeaders();
- noPartnerHeaders.set(ONAPLogConstants.Headers.REQUEST_ID, "eca3a1b1-43ab-457e-ab1c-367263d148b4");
- noPartnerHeaders.set(REQUESTOR_ID, "xxxxxx");
+ public void deleteInstanceGroupNoPartnerNameHeader() throws IOException {
+ HttpHeaders noPartnerHeaders = new HttpHeaders();
+ noPartnerHeaders.set(ONAPLogConstants.Headers.REQUEST_ID, "eca3a1b1-43ab-457e-ab1c-367263d148b4");
+ noPartnerHeaders.set(REQUESTOR_ID, "xxxxxx");
uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c";
ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE, noPartnerHeaders);
- //then
+ // then
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-PartnerName header is specified");
+ assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-PartnerName header is specified");
}
+
@Test
- public void deleteInstanceGroupNoRquestorIdHeader() throws IOException{
+ public void deleteInstanceGroupNoRquestorIdHeader() throws IOException {
HttpHeaders noRequestorIdHheaders = new HttpHeaders();
noRequestorIdHheaders.set(ONAPLogConstants.Headers.REQUEST_ID, "eca3a1b1-43ab-457e-ab1c-367263d148b4");
- noRequestorIdHheaders.set(ONAPLogConstants.Headers.PARTNER_NAME, "eca3a1b1-43ab-457e-ab1c-367263d148b4");
- //expect
+ noRequestorIdHheaders.set(ONAPLogConstants.Headers.PARTNER_NAME, "eca3a1b1-43ab-457e-ab1c-367263d148b4");
+ // expect
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c";
ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE, noRequestorIdHheaders);
-
- //then
+
+ // then
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals(realResponse.getServiceException().getText(), "No valid X-RequestorID header is specified");
+ assertEquals(realResponse.getServiceException().getText(), "No valid X-RequestorID header is specified");
}
+
@Test
- public void addMembers() throws IOException{
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+ public void addMembers() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expect
+ // expect
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c/addMembers";
ResponseEntity<String> response = sendRequest(inputStream("/AddMembers.json"), uri, HttpMethod.POST, headers);
- //then
+ // then
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
- public void removeMembers() throws IOException{
- wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
+ public void removeMembers() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
- //expect
+ // expect
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c/removeMembers";
- ResponseEntity<String> response = sendRequest(inputStream("/RemoveMembers.json"), uri, HttpMethod.POST, headers);
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/RemoveMembers.json"), uri, HttpMethod.POST, headers);
- //then
+ // then
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void deleteNetworkInstanceNoCustomizationEntry() throws IOException {
wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB"))
@@ -2498,38 +2708,43 @@ public class ServiceInstancesTest extends BaseTest{
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withStatus(HttpStatus.SC_NOT_FOUND)));
- wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" +
- "modelName=VNF-API-DEFAULT&action=deleteInstance"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
- .withStatus(org.apache.http.HttpStatus.SC_OK)));
-
- //expected response
+ wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]"
+ + "modelName=VNF-API-DEFAULT&action=deleteInstance"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json"))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ // expected response
ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
RequestReferences requestReferences = new RequestReferences();
requestReferences.setInstanceId("1882939");
- requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d"));
+ requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
expectedResponse.setRequestReferences(requestReferences);
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb";
- ResponseEntity<String> response = sendRequest(inputStream("/NetworkInstance.json"), uri, HttpMethod.DELETE, headers);
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb";
+ ResponseEntity<String> response =
+ sendRequest(inputStream("/NetworkInstance.json"), uri, HttpMethod.DELETE, headers);
assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
+ assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
}
+
@Test
public void updateNetworkInstanceNoCustomizationEntry() throws IOException {
- wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac"))
+ wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withStatus(HttpStatus.SC_NOT_FOUND)));
-
- uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb";
+
+ uri = servInstanceuri + "v7"
+ + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb";
ResponseEntity<String> response = sendRequest(inputStream("/UpdateNetwork.json"), uri, HttpMethod.PUT, headers);
-
+
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
- assertEquals(realResponse.getServiceException().getText(), "No valid modelCustomizationId for networkResourceCustomization lookup is specified");
+ assertEquals(realResponse.getServiceException().getText(),
+ "No valid modelCustomizationId for networkResourceCustomization lookup is specified");
}
-
-
+
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java
index 327141e0f2..77d6f68de9 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java
@@ -27,15 +27,12 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
-
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.junit.Test;
@@ -47,78 +44,80 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class TasksHandlerTest extends BaseTest{
-
- private final String basePath = "onap/so/infra/tasks/v1";
-
- @Test
- public void getTasksTestByOriginalRequestId() throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException{
- wireMockServer.stubFor(post(urlPathEqualTo("/sobpmnengine/task"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("Camunda/GetTaskResponse.json").withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo("/sobpmnengine/task/b5fa707a-f55a-11e7-a796-005056856d52/variables"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("Camunda/GetTaskVariablesResponse.json").withStatus(HttpStatus.SC_OK)));
-
- String requestId = "4f6fe9ac-800c-4540-a93e-10d179fa1b0a";
-
- //expected response
- TasksGetResponse expectedResponse = new TasksGetResponse();
-
- List<TaskList> taskList = new ArrayList<TaskList>();
- TaskList taskList1 = new TaskList();
- List<String> validEntries = new ArrayList<String>();
- validEntries.add(ValidResponses.rollback.toString());
- validEntries.add(ValidResponses.skip.toString());
- validEntries.add(ValidResponses.manual.toString());
- validEntries.add(ValidResponses.abort.toString());
- taskList1.setBuildingBlockName("UpdateConfigurationState");
- taskList1.setBuildingBlockStep("Configurationactivate SDNO Post-Check");
- taskList1.setErrorCode("1002");
- taskList1.setErrorSource("SDNO");
- taskList1.setErrorMessage("SDN-O exception: failed with message FAIL - AnsibleOperations exception: Failed : HTTP error code : 400 - Error Msg : no node list provided and no inventory file found");
- taskList1.setNfRole("VPROBE");
- taskList1.setType("fallout");
- taskList1.setOriginalRequestId(requestId);
- taskList1.setOriginalRequestorId("VID");
- taskList1.setSubscriptionServiceType("PORT-MIRROR");
- taskList1.setTaskId("b5fa707a-f55a-11e7-a796-005056856d52");
- taskList1.setDescription("test task");
- taskList1.setTimeout("PT3000S");
- taskList1.setValidResponses(validEntries);
- taskList.add(taskList1);
-
- expectedResponse.setTaskList(taskList);
- HttpHeaders headers = new HttpHeaders();
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath))
- .queryParam("taskId", "b5fa707a-f55a-11e7-a796-005056856d52");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- ObjectMapper mapper = new ObjectMapper();
-
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-
-
- //then
- assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
- TasksGetResponse realResponse = mapper.readValue(response.getBody(), TasksGetResponse.class);
- assertThat(realResponse, sameBeanAs(expectedResponse));
+public class TasksHandlerTest extends BaseTest {
+
+ private final String basePath = "onap/so/infra/tasks/v1";
+
+ @Test
+ public void getTasksTestByOriginalRequestId()
+ throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo("/sobpmnengine/task"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("Camunda/GetTaskResponse.json").withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/sobpmnengine/task/b5fa707a-f55a-11e7-a796-005056856d52/variables"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("Camunda/GetTaskVariablesResponse.json").withStatus(HttpStatus.SC_OK)));
+
+ String requestId = "4f6fe9ac-800c-4540-a93e-10d179fa1b0a";
+
+ // expected response
+ TasksGetResponse expectedResponse = new TasksGetResponse();
+
+ List<TaskList> taskList = new ArrayList<TaskList>();
+ TaskList taskList1 = new TaskList();
+ List<String> validEntries = new ArrayList<String>();
+ validEntries.add(ValidResponses.rollback.toString());
+ validEntries.add(ValidResponses.skip.toString());
+ validEntries.add(ValidResponses.manual.toString());
+ validEntries.add(ValidResponses.abort.toString());
+ taskList1.setBuildingBlockName("UpdateConfigurationState");
+ taskList1.setBuildingBlockStep("Configurationactivate SDNO Post-Check");
+ taskList1.setErrorCode("1002");
+ taskList1.setErrorSource("SDNO");
+ taskList1.setErrorMessage(
+ "SDN-O exception: failed with message FAIL - AnsibleOperations exception: Failed : HTTP error code : 400 - Error Msg : no node list provided and no inventory file found");
+ taskList1.setNfRole("VPROBE");
+ taskList1.setType("fallout");
+ taskList1.setOriginalRequestId(requestId);
+ taskList1.setOriginalRequestorId("VID");
+ taskList1.setSubscriptionServiceType("PORT-MIRROR");
+ taskList1.setTaskId("b5fa707a-f55a-11e7-a796-005056856d52");
+ taskList1.setDescription("test task");
+ taskList1.setTimeout("PT3000S");
+ taskList1.setValidResponses(validEntries);
+ taskList.add(taskList1);
+
+ expectedResponse.setTaskList(taskList);
+ HttpHeaders headers = new HttpHeaders();
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath))
+ .queryParam("taskId", "b5fa707a-f55a-11e7-a796-005056856d52");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+
+
+ // then
+ assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
+ TasksGetResponse realResponse = mapper.readValue(response.getBody(), TasksGetResponse.class);
+ assertThat(realResponse, sameBeanAs(expectedResponse));
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0));
assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0));
assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0));
- }
+ }
-} \ No newline at end of file
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java
index 48711a2595..1beb3b37a7 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java
@@ -27,11 +27,11 @@ import ch.qos.logback.core.AppenderBase;
-public class TestAppender extends AppenderBase<ILoggingEvent> {
+public class TestAppender extends AppenderBase<ILoggingEvent> {
public static List<ILoggingEvent> events = new ArrayList<>();
-
- @Override
- protected void append(ILoggingEvent loggingEvent) {
- events.add(loggingEvent);
- }
+
+ @Override
+ protected void append(ILoggingEvent loggingEvent) {
+ events.add(loggingEvent);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java
index 760532e6fe..7678de1a19 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java
@@ -23,15 +23,12 @@ package org.onap.so.apihandlerinfra;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
-
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.json.JSONException;
import org.junit.Test;
import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowSpecifications;
@@ -40,43 +37,44 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class WorkflowSpecificationsHandlerTest extends BaseTest{
-
- private final String basePath = "onap/so/infra/workflowSpecifications/v1/workflows";
-
- @Test
- public void getTasksTestByOriginalRequestId() throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException{
-
- HttpHeaders headers = new HttpHeaders();
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath))
- .queryParam("vnfModelVersionId", "b5fa707a-f55a-11e7-a796-005056856d52");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- ObjectMapper mapper = new ObjectMapper();
-
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-
- WorkflowSpecifications expectedResponse = mapper.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/__files/WorkflowSpecifications.json"))), WorkflowSpecifications.class);
+public class WorkflowSpecificationsHandlerTest extends BaseTest {
+
+ private final String basePath = "onap/so/infra/workflowSpecifications/v1/workflows";
+
+ @Test
+ public void getTasksTestByOriginalRequestId()
+ throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException {
+
+ HttpHeaders headers = new HttpHeaders();
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath))
+ .queryParam("vnfModelVersionId", "b5fa707a-f55a-11e7-a796-005056856d52");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+
+ WorkflowSpecifications expectedResponse = mapper.readValue(
+ new String(Files.readAllBytes(Paths.get("src/test/resources/__files/WorkflowSpecifications.json"))),
+ WorkflowSpecifications.class);
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- WorkflowSpecifications realResponse = mapper.readValue(response.getBody(), WorkflowSpecifications.class);
- assertThat(realResponse, sameBeanAs(expectedResponse));
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
+ WorkflowSpecifications realResponse = mapper.readValue(response.getBody(), WorkflowSpecifications.class);
+ assertThat(realResponse, sameBeanAs(expectedResponse));
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0));
assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0));
assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0));
- }
-} \ No newline at end of file
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java
index 96ac02ae75..bc5869e416 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
import org.junit.Test;
-
import static org.junit.Assert.assertEquals;
public class DelE2ESvcRespTest {
@@ -31,7 +30,7 @@ public class DelE2ESvcRespTest {
@Test
public void verifyDelE2ESvcResp() throws Exception {
test.setOperationId("operationId");
- assertEquals(test.getOperationId(),"operationId");
+ assertEquals(test.getOperationId(), "operationId");
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java
index 7cfee66d48..cbc835dfbb 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
import org.junit.Test;
-
import static org.junit.Assert.assertEquals;
public class E2ERequestTest {
@@ -32,23 +31,23 @@ public class E2ERequestTest {
public void verifyE2ERequest() throws Exception {
test.setOperationId("operationId");
- assertEquals(test.getOperationId(),"operationId");
+ assertEquals(test.getOperationId(), "operationId");
test.setOperation("operation");
- assertEquals(test.getOperation(),"operation");
+ assertEquals(test.getOperation(), "operation");
test.setResult("result");
- assertEquals(test.getResult(),"result");
+ assertEquals(test.getResult(), "result");
test.setReason("test");
- assertEquals(test.getReason(),"test");
+ assertEquals(test.getReason(), "test");
test.setUserId("userId");
- assertEquals(test.getUserId(),"userId");
+ assertEquals(test.getUserId(), "userId");
test.setOperationContent("operation");
- assertEquals(test.getOperationContent(),"operation");
+ assertEquals(test.getOperationContent(), "operation");
test.setProgress(123);
- assertEquals(test.getProgress(),123);
+ assertEquals(test.getProgress(), 123);
test.setOperateAt("operate");
- assertEquals(test.getOperateAt(),"operate");
+ assertEquals(test.getOperateAt(), "operate");
test.setFinishedAt("finished");
- assertEquals(test.getFinishedAt(),"finished");
+ assertEquals(test.getFinishedAt(), "finished");
}
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java
index a3bab01dfd..8dfe6dc006 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
import org.junit.Test;
-
import static org.junit.Assert.assertEquals;
public class E2EServiceInstanceDeleteRequestTest {
@@ -33,9 +32,9 @@ public class E2EServiceInstanceDeleteRequestTest {
public void verifyE2ESerInstanceDelReq() throws Exception {
test.setGlobalSubscriberId("id");
- assertEquals(test.getGlobalSubscriberId(),"id");
+ assertEquals(test.getGlobalSubscriberId(), "id");
test.setServiceType("type");
- assertEquals(test.getServiceType(),"type");
+ assertEquals(test.getServiceType(), "type");
}
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java
index 59bfa2a1d2..bb331904ca 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java
@@ -21,10 +21,8 @@
package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
import org.junit.Test;
-
import java.util.HashMap;
import java.util.Map;
-
import static org.junit.Assert.assertEquals;
public class E2EUserParamTest {
@@ -35,13 +33,13 @@ public class E2EUserParamTest {
public void verifyE2EParam() throws Exception {
test.setName("name");
- assertEquals(test.getName(),"name");
+ assertEquals(test.getName(), "name");
test.setValue("value");
- assertEquals(test.getValue(),"value");
+ assertEquals(test.getValue(), "value");
Map<String, Object> additionalProperties = new HashMap<>();
additionalProperties.put("name", test);
- test.setAdditionalProperty("name",test);
- assertEquals(test.getAdditionalProperties(),additionalProperties);
+ test.setAdditionalProperty("name", test);
+ assertEquals(test.getAdditionalProperties(), additionalProperties);
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java
index 59e10b3938..5b09cefc85 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java
@@ -21,12 +21,10 @@
package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
import org.junit.Test;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import static org.junit.Assert.assertEquals;
public class NsParametersTest {
@@ -37,15 +35,15 @@ public class NsParametersTest {
@Test
public void verifyNsParameters() throws Exception {
- LocationConstraint obj =new LocationConstraint();
+ LocationConstraint obj = new LocationConstraint();
List<LocationConstraint> locationConstraints = new ArrayList<LocationConstraint>();
locationConstraints.add(obj);
test.setLocationConstraints(locationConstraints);
- assertEquals(test.getLocationConstraints(),locationConstraints);
- Map<String, Object> additionalParamForNs = new HashMap<String,Object>();
- additionalParamForNs.put("1",test);
+ assertEquals(test.getLocationConstraints(), locationConstraints);
+ Map<String, Object> additionalParamForNs = new HashMap<String, Object>();
+ additionalParamForNs.put("1", test);
test.setAdditionalParamForNs(additionalParamForNs);
- assertEquals(test.getAdditionalParamForNs(),additionalParamForNs);
+ assertEquals(test.getAdditionalParamForNs(), additionalParamForNs);
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java
index cbdfe6b831..9c7fd37d28 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java
@@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra.tasksbeans;
import org.junit.Test;
import org.onap.so.apihandlerinfra.BaseTest;
-
import com.openpojo.reflection.filters.FilterPackageInfo;
import com.openpojo.validation.Validator;
import com.openpojo.validation.ValidatorBuilder;
@@ -31,11 +30,11 @@ import com.openpojo.validation.rule.impl.SetterMustExistRule;
import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
-public class TasksBeansTest extends BaseTest{
- @Test
- public void validateGettersAndSetters() {
- Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule())
- .with(new SetterTester(), new GetterTester()).build();
- validator.validate("org.onap.so.apihandlerinfra.tasksbeans", new FilterPackageInfo());
- }
+public class TasksBeansTest extends BaseTest {
+ @Test
+ public void validateGettersAndSetters() {
+ Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule())
+ .with(new SetterTester(), new GetterTester()).build();
+ validator.validate("org.onap.so.apihandlerinfra.tasksbeans", new FilterPackageInfo());
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java
index 5c5a9e92b3..9ae1e5b232 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java
@@ -27,12 +27,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-
import java.io.File;
import java.io.IOException;
-
import javax.ws.rs.core.MediaType;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Ignore;
@@ -47,207 +44,242 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.databind.ObjectMapper;
public class CloudOrchestrationTest extends BaseTest {
-
- private static final String path = "/onap/so/infra/cloudResources/v1";
-
- private HttpHeaders headers = new HttpHeaders();
-
- @Before
- public void setupTestClass() throws Exception{
- wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_CREATED)));
- }
-
- @Test
- public void testCreateOpEnvObjectMapperError() throws IOException {
-
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments");
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
-
- String body = response.getBody().toString();
- assertTrue(body.contains("Mapping of request to JSON object failed."));
- assertEquals(400, response.getStatusCodeValue());
- }
-
- @Test
- public void testCreateOpEnvError() throws IOException {
-
- String request = "{\"requestDetails\":{\"requestInfo\":{\"resourceType\":\"operationalEnvironment\",\"instanceName\": \"myOpEnv\",\"source\": \"VID\",\"requestorId\": \"xxxxxx\"},"
- + " \"requestParameters\": {\"tenantContext\": \"Test\",\"workloadContext\": \"ECOMP_E2E-IST\"}}}";
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(request, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
-
- String body = response.getBody().toString();
- assertTrue(body.contains("Mapping of request to JSON object failed"));
- assertEquals(400, response.getStatusCodeValue());
- }
-
- @Test
- public void testCreateOpEnvReqRecordDuplicateCheck() throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":null,\"instanceName\":\"myOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(String.format(getResponseTemplate, "123", "PENDING"))
- .withStatus(HttpStatus.SC_OK)));
- ObjectMapper mapper = new ObjectMapper();
- TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"), TenantIsolationRequest.class);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers);
-
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
-
- assertEquals(409, response.getStatusCodeValue());
- }
-
- @Test
- public void testCreateOperationalEnvironment() throws IOException {
- ObjectMapper mapper = new ObjectMapper();
- TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"), TenantIsolationRequest.class);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- headers.set("X-TransactionID", "987654321");
- HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments");
- wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":null,\"instanceName\":\"myOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_NOT_FOUND)));
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
- assertEquals(200, response.getStatusCodeValue());
- }
-
- @Test
- public void testCreateVNFDuplicateCheck() throws IOException {
- wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":null,\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(String.format(getResponseTemplate, "requestId", Status.IN_PROGRESS.toString()))
- .withStatus(HttpStatus.SC_OK)));
- ObjectMapper mapper = new ObjectMapper();
- TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"), TenantIsolationRequest.class);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
- assertEquals(409, response.getStatusCodeValue());
- }
-
- @Test
- public void testCreateVNF() throws IOException {
- ObjectMapper mapper = new ObjectMapper();
- TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"), TenantIsolationRequest.class);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments");
- wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":null,\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_NOT_FOUND)));
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
- assertEquals(200, response.getStatusCodeValue());
- }
-
- @Test
- public void testActivate() throws IOException {
- ObjectMapper mapper = new ObjectMapper();
- TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/ActivateOperationEnvironment.json"), TenantIsolationRequest.class);
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7ff/activate");
- wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":{\"operationalEnvironmentId\":\"ff3514e3-5a33-55df-13ab-12abad84e7ff\"},\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_NOT_FOUND)));
-
- wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("checkVnfIdStatus/ff3514e3-5a33-55df-13ab-12abad84e7ff"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
-
- assertEquals(200, response.getStatusCodeValue());
- }
-
- @Test
- public void testDeactivate() throws IOException {
- ObjectMapper mapper = new ObjectMapper();
- TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"), TenantIsolationRequest.class);
-
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers);
-
-
-// wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":{\"operationalEnvironmentId\":\"ff3514e3-5a33-55df-13ab-12abad84e7fa\"},\"instanceName\":null,\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
-// .withBodyFile((String.format(getResponseTemplate, "ff3514e3-5a33-55df-13ab-12abad84e7fa", Status.COMPLETE.toString()))).withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("checkVnfIdStatus/ff3514e3-5a33-55df-13ab-12abad84e7fa"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7fa/deactivate");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
-
- assertEquals(200, response.getStatusCodeValue());
- }
-
-
- @Test
- @Ignore
- public void testDeactivateDupCheck() throws IOException {
-
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId("requestId");
- iar.setOperationalEnvName("myVnfOpEnv");
- iar.setRequestStatus(Status.IN_PROGRESS.toString());
- iar.setAction(Action.create.toString());
- iar.setRequestAction(Action.create.toString());
- iar.setRequestScope("UNKNOWN");
- //iarRepo.saveAndFlush(iar);
- ObjectMapper mapper = new ObjectMapper();
- String request = mapper.readValue(new File("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"), String.class);
-
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(request, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7ff/deactivate");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
- assertEquals(409, response.getStatusCodeValue());
- }
-
-} \ No newline at end of file
+
+ private static final String path = "/onap/so/infra/cloudResources/v1";
+
+ private HttpHeaders headers = new HttpHeaders();
+
+ @Before
+ public void setupTestClass() throws Exception {
+ wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_CREATED)));
+ }
+
+ @Test
+ public void testCreateOpEnvObjectMapperError() throws IOException {
+
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments");
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+
+ String body = response.getBody().toString();
+ assertTrue(body.contains("Mapping of request to JSON object failed."));
+ assertEquals(400, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testCreateOpEnvError() throws IOException {
+
+ String request =
+ "{\"requestDetails\":{\"requestInfo\":{\"resourceType\":\"operationalEnvironment\",\"instanceName\": \"myOpEnv\",\"source\": \"VID\",\"requestorId\": \"xxxxxx\"},"
+ + " \"requestParameters\": {\"tenantContext\": \"Test\",\"workloadContext\": \"ECOMP_E2E-IST\"}}}";
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<String>(request, headers);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+
+ String body = response.getBody().toString();
+ assertTrue(body.contains("Mapping of request to JSON object failed"));
+ assertEquals(400, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testCreateOpEnvReqRecordDuplicateCheck() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo(
+ "{\"instanceIdMap\":null,\"instanceName\":\"myOpEnv\",\"requestScope\":\"operationalEnvironment\"}"))
+ .willReturn(aResponse()
+ .withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(String.format(getResponseTemplate, "123", "PENDING")).withStatus(HttpStatus.SC_OK)));
+ ObjectMapper mapper = new ObjectMapper();
+ TenantIsolationRequest request =
+ mapper.readValue(new File("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"),
+ TenantIsolationRequest.class);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers);
+
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+
+ assertEquals(409, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testCreateOperationalEnvironment() throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ TenantIsolationRequest request =
+ mapper.readValue(new File("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"),
+ TenantIsolationRequest.class);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ headers.set("X-TransactionID", "987654321");
+ HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments");
+ wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo(
+ "{\"instanceIdMap\":null,\"instanceName\":\"myOpEnv\",\"requestScope\":\"operationalEnvironment\"}"))
+ .willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_NOT_FOUND)));
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+ assertEquals(200, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testCreateVNFDuplicateCheck() throws IOException {
+ wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo(
+ "{\"instanceIdMap\":null,\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}"))
+ .willReturn(aResponse()
+ .withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(String.format(getResponseTemplate, "requestId", Status.IN_PROGRESS.toString()))
+ .withStatus(HttpStatus.SC_OK)));
+ ObjectMapper mapper = new ObjectMapper();
+ TenantIsolationRequest request =
+ mapper.readValue(new File("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"),
+ TenantIsolationRequest.class);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+ assertEquals(409, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testCreateVNF() throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ TenantIsolationRequest request =
+ mapper.readValue(new File("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"),
+ TenantIsolationRequest.class);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments");
+ wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo(
+ "{\"instanceIdMap\":null,\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}"))
+ .willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_NOT_FOUND)));
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+ assertEquals(200, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testActivate() throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ TenantIsolationRequest request =
+ mapper.readValue(new File("src/test/resources/TenantIsolation/ActivateOperationEnvironment.json"),
+ TenantIsolationRequest.class);
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers);
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(
+ createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7ff/activate");
+ wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo(
+ "{\"instanceIdMap\":{\"operationalEnvironmentId\":\"ff3514e3-5a33-55df-13ab-12abad84e7ff\"},\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}"))
+ .willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_NOT_FOUND)));
+
+ wireMockServer.stubFor(
+ get(urlPathEqualTo(getTestUrl("checkVnfIdStatus/ff3514e3-5a33-55df-13ab-12abad84e7ff"))).willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+
+ assertEquals(200, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testDeactivate() throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ TenantIsolationRequest request =
+ mapper.readValue(new File("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"),
+ TenantIsolationRequest.class);
+
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers);
+
+
+ // wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":{\"operationalEnvironmentId\":\"ff3514e3-5a33-55df-13ab-12abad84e7fa\"},\"instanceName\":null,\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE,
+ // MediaType.APPLICATION_JSON)
+ // .withBodyFile((String.format(getResponseTemplate, "ff3514e3-5a33-55df-13ab-12abad84e7fa",
+ // Status.COMPLETE.toString()))).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(
+ get(urlPathEqualTo(getTestUrl("checkVnfIdStatus/ff3514e3-5a33-55df-13ab-12abad84e7fa"))).willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(
+ createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7fa/deactivate");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+
+ assertEquals(200, response.getStatusCodeValue());
+ }
+
+
+ @Test
+ @Ignore
+ public void testDeactivateDupCheck() throws IOException {
+
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId("requestId");
+ iar.setOperationalEnvName("myVnfOpEnv");
+ iar.setRequestStatus(Status.IN_PROGRESS.toString());
+ iar.setAction(Action.create.toString());
+ iar.setRequestAction(Action.create.toString());
+ iar.setRequestScope("UNKNOWN");
+ // iarRepo.saveAndFlush(iar);
+ ObjectMapper mapper = new ObjectMapper();
+ String request = mapper.readValue(
+ new File("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"), String.class);
+
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<String>(request, headers);
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(
+ createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7ff/deactivate");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+ assertEquals(409, response.getStatusCodeValue());
+ }
+
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java
index c119653ae3..5f12060059 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java
@@ -26,11 +26,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-
import java.text.ParseException;
-
import javax.ws.rs.core.MediaType;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
@@ -43,272 +40,283 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
-public class CloudResourcesOrchestrationTest extends BaseTest{
-
- private String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"xxxxxx\" } } }";
- private static final String path = "/onap/so/infra/cloudResourcesRequests";
-
- HttpHeaders headers = new HttpHeaders();
- @Before
- public void setupTestClass() throws Exception{
- wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_CREATED)));
- }
- @Test
- public void testUnlockFailObjectMapping() {
-
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(null, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
-
- String body = response.getBody();
- assertTrue(body.contains("Mapping of request to JSON object failed."));
- assertEquals(400, response.getStatusCodeValue());
- }
-
- @Test
- public void testParseOrchestrationError1() {
- String requestJSON = "{\"requestDetails\": null }";
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
- String body = response.getBody();
- assertTrue(body.contains("No valid requestDetails is specified"));
- assertEquals(400, response.getStatusCodeValue());
- }
-
- @Test
- public void testParseOrchestrationError2() {
- String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"\",\"requestorId\":\"xxxxxx\" } } }";
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
- String body = response.getBody();
- assertTrue(body.contains("No valid source is specified"));
- assertEquals(400, response.getStatusCodeValue());
- }
-
- @Test
- public void testParseOrchestrationError3() {
- String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"\" } } }";
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
- String body = response.getBody();
- assertTrue(body.contains("No valid requestorId is specified"));
- assertEquals(400, response.getStatusCodeValue());
- }
-
- @Test
- public void testGetInfraActiveRequestNull() {
- wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("request-id-null-check"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/request-id-null-check/unlock");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
- String body = response.getBody();
- assertTrue(body.contains("Orchestration RequestId request-id-null-check is not found in DB"));
- assertEquals(400, response.getStatusCodeValue());
-
- }
-
- @Test
- public void testUnlock() throws ParseException {
- wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestUnlock"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(String.format(getResponseTemplate, "requestIdtestUnlock", "IN_PROGRESS"))
- .withStatus(HttpStatus.SC_OK)));
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<>(requestJSON, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/requestIdtestUnlock/unlock");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
-
- assertEquals(204, response.getStatusCodeValue());
- }
-
- @Test
- public void testUnlockComplete() throws ParseException {
- wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestUnlockComplete"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(String.format(getResponseTemplate, "requestIdtestUnlockComplete", "COMPLETE"))
- .withStatus(HttpStatus.SC_OK)));
-
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<>(requestJSON, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/requestIdtestUnlockComplete/unlock");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.POST, entity, String.class);
- String body = response.getBody().toString();
- assertTrue(body.contains("Orchestration RequestId requestIdtestUnlockComplete has a status of COMPLETE and can not be unlocked"));
- assertEquals(400, response.getStatusCodeValue());
- }
-
- @Test
- public void testGetOperationalEnvFilter() {
- wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("not-there"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<>(null, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1");
-
- builder.queryParam("requestId", "not-there");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- //204s cannot have a body
- //assertTrue(response.getBody().contains("Orchestration RequestId not-there is not found in DB"));
- assertEquals(204, response.getStatusCodeValue());
- }
-
- @Test
- public void testGetOperationalEnvSuccess() throws ParseException {
- wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("90c56827-1c78-4827-bc4d-6afcdb37a51f"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(String.format(getResponseTemplateNoBody, "90c56827-1c78-4827-bc4d-6afcdb37a51f", "COMPLETE"))
- .withStatus(HttpStatus.SC_OK)));
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<>("", headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1");
-
- builder.queryParam("requestId", "90c56827-1c78-4827-bc4d-6afcdb37a51f");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(200, response.getStatusCodeValue());
+public class CloudResourcesOrchestrationTest extends BaseTest {
+
+ private String requestJSON =
+ "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"xxxxxx\" } } }";
+ private static final String path = "/onap/so/infra/cloudResourcesRequests";
+
+ HttpHeaders headers = new HttpHeaders();
+
+ @Before
+ public void setupTestClass() throws Exception {
+ wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_CREATED)));
+ }
+
+ @Test
+ public void testUnlockFailObjectMapping() {
+
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<String>(null, headers);
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+
+ String body = response.getBody();
+ assertTrue(body.contains("Mapping of request to JSON object failed."));
+ assertEquals(400, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testParseOrchestrationError1() {
+ String requestJSON = "{\"requestDetails\": null }";
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers);
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+ String body = response.getBody();
+ assertTrue(body.contains("No valid requestDetails is specified"));
+ assertEquals(400, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testParseOrchestrationError2() {
+ String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"\",\"requestorId\":\"xxxxxx\" } } }";
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers);
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+ String body = response.getBody();
+ assertTrue(body.contains("No valid source is specified"));
+ assertEquals(400, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testParseOrchestrationError3() {
+ String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"\" } } }";
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers);
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+ String body = response.getBody();
+ assertTrue(body.contains("No valid requestorId is specified"));
+ assertEquals(400, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testGetInfraActiveRequestNull() {
+ wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("request-id-null-check"))).willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/request-id-null-check/unlock");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+ String body = response.getBody();
+ assertTrue(body.contains("Orchestration RequestId request-id-null-check is not found in DB"));
+ assertEquals(400, response.getStatusCodeValue());
+
+ }
+
+ @Test
+ public void testUnlock() throws ParseException {
+ wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestUnlock"))).willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(String.format(getResponseTemplate, "requestIdtestUnlock", "IN_PROGRESS"))
+ .withStatus(HttpStatus.SC_OK)));
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<>(requestJSON, headers);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/requestIdtestUnlock/unlock");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+
+ assertEquals(204, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testUnlockComplete() throws ParseException {
+ wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestUnlockComplete"))).willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(String.format(getResponseTemplate, "requestIdtestUnlockComplete", "COMPLETE"))
+ .withStatus(HttpStatus.SC_OK)));
+
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<>(requestJSON, headers);
+
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/requestIdtestUnlockComplete/unlock");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
+ String body = response.getBody().toString();
+ assertTrue(body.contains(
+ "Orchestration RequestId requestIdtestUnlockComplete has a status of COMPLETE and can not be unlocked"));
+ assertEquals(400, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testGetOperationalEnvFilter() {
+ wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("not-there"))).willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<>(null, headers);
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1");
+
+ builder.queryParam("requestId", "not-there");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ // 204s cannot have a body
+ // assertTrue(response.getBody().contains("Orchestration RequestId not-there is not found in DB"));
+ assertEquals(204, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testGetOperationalEnvSuccess() throws ParseException {
+ wireMockServer
+ .stubFor(get(urlPathEqualTo(getTestUrl("90c56827-1c78-4827-bc4d-6afcdb37a51f"))).willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(String.format(getResponseTemplateNoBody,
+ "90c56827-1c78-4827-bc4d-6afcdb37a51f", "COMPLETE"))
+ .withStatus(HttpStatus.SC_OK)));
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<>("", headers);
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1");
+
+ builder.queryParam("requestId", "90c56827-1c78-4827-bc4d-6afcdb37a51f");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(200, response.getStatusCodeValue());
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0));
assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0));
assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0));
assertEquals("90c56827-1c78-4827-bc4d-6afcdb37a51f", response.getHeaders().get("X-TransactionID").get(0));
- }
-
- @Test
- public void testGetOperationalEnvFilterSuccess() throws ParseException {
- wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestGetOperationalEnvFilterSuccess"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(String.format(getResponseTemplate, "requestIdtestGetOperationalEnvFilterSuccess", "COMPLETE"))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("getCloudOrchestrationFiltersFromInfraActive"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody("{\"requestId\":\"getCloudOrchestrationFiltersFromInfraActive\", \"operationalEnvironmentName\":\"myVnfOpEnv\"}")
- .withBody("["+String.format(getResponseTemplateNoBody, "requestIdtestGetOperationalEnvFilterSuccess", "COMPLETE")+"]")
- .withStatus(HttpStatus.SC_OK)));
-
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<>(null, headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1");
-
- builder.queryParam("requestId", "requestIdtestGetOperationalEnvFilterSuccess");
- builder.queryParam("operationalEnvironmentName", "myVnfOpEnv");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
- assertEquals(200, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testGetOperationalEnvFilterSuccess() throws ParseException {
+ wireMockServer
+ .stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestGetOperationalEnvFilterSuccess"))).willReturn(
+ aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(String.format(getResponseTemplate,
+ "requestIdtestGetOperationalEnvFilterSuccess", "COMPLETE"))
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(
+ post(urlPathEqualTo(getTestUrl("getCloudOrchestrationFiltersFromInfraActive"))).willReturn(aResponse()
+ .withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(
+ "{\"requestId\":\"getCloudOrchestrationFiltersFromInfraActive\", \"operationalEnvironmentName\":\"myVnfOpEnv\"}")
+ .withBody("[" + String.format(getResponseTemplateNoBody,
+ "requestIdtestGetOperationalEnvFilterSuccess", "COMPLETE") + "]")
+ .withStatus(HttpStatus.SC_OK)));
+
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<>(null, headers);
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1");
+
+ builder.queryParam("requestId", "requestIdtestGetOperationalEnvFilterSuccess");
+ builder.queryParam("operationalEnvironmentName", "myVnfOpEnv");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+ assertEquals(200, response.getStatusCodeValue());
assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0));
assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0));
assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0));
- }
-
- @Test
- public void testGetOperationalEnvFilterException1() throws ParseException {
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId("requestId-getOpEnvFilterEx1");
- iar.setRequestScope("requestScope");
- iar.setRequestType("requestType");
- iar.setOperationalEnvId("operationalEnvironmentId");
- iar.setOperationalEnvName("operationalEnvName");
- iar.setRequestorId("xxxxxx");
- iar.setRequestBody("");
- iar.setRequestStatus("COMPLETE");
- iar.setRequestAction("TEST");
-
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<>("", headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1");
-
- builder.queryParam("filter", "operationalEnvironmentName:EQUALS:myVnfOpEnv");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
- assertEquals(500, response.getStatusCodeValue());
- }
-
- @Test
- public void testGetOperationalEnvFilterException2() throws ParseException {
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId("requestIdFilterException2");
- iar.setRequestScope("requestScope");
- iar.setRequestType("requestType");
- iar.setOperationalEnvId("operationalEnvId");
- iar.setOperationalEnvName("operationalEnvName");
- iar.setRequestorId("xxxxxx");
- iar.setRequestBody("");
- iar.setRequestStatus("COMPLETE");
- iar.setRequestAction("TEST");
-
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<>(null, headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1");
-
- builder.queryParam("operationalEnvironmentName", "");
-
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.GET, entity, String.class);
-
-
- assertEquals(500, response.getStatusCodeValue());
- assertTrue(response.getBody().toString().contains("No valid operationalEnvironmentName value is specified"));
- }
+ }
+
+ @Test
+ public void testGetOperationalEnvFilterException1() throws ParseException {
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId("requestId-getOpEnvFilterEx1");
+ iar.setRequestScope("requestScope");
+ iar.setRequestType("requestType");
+ iar.setOperationalEnvId("operationalEnvironmentId");
+ iar.setOperationalEnvName("operationalEnvName");
+ iar.setRequestorId("xxxxxx");
+ iar.setRequestBody("");
+ iar.setRequestStatus("COMPLETE");
+ iar.setRequestAction("TEST");
+
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<>("", headers);
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1");
+
+ builder.queryParam("filter", "operationalEnvironmentName:EQUALS:myVnfOpEnv");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+ assertEquals(500, response.getStatusCodeValue());
+ }
+
+ @Test
+ public void testGetOperationalEnvFilterException2() throws ParseException {
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId("requestIdFilterException2");
+ iar.setRequestScope("requestScope");
+ iar.setRequestType("requestType");
+ iar.setOperationalEnvId("operationalEnvId");
+ iar.setOperationalEnvName("operationalEnvName");
+ iar.setRequestorId("xxxxxx");
+ iar.setRequestBody("");
+ iar.setRequestStatus("COMPLETE");
+ iar.setRequestAction("TEST");
+
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<String> entity = new HttpEntity<>(null, headers);
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1");
+
+ builder.queryParam("operationalEnvironmentName", "");
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
+
+
+ assertEquals(500, response.getStatusCodeValue());
+ assertTrue(response.getBody().toString().contains("No valid operationalEnvironmentName value is specified"));
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java
index 4e5cfaba48..e9237f604e 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java
@@ -28,13 +28,10 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.Mockito.doNothing;
-
import java.io.IOException;
-
import javax.inject.Provider;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Rule;
@@ -55,82 +52,82 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-public class ModelDistributionRequestTest extends BaseTest{
+public class ModelDistributionRequestTest extends BaseTest {
- private static final String requestJSON = "{\"status\": \"DISTRIBUTION_COMPLETE_ERROR\", \"errorReason\": \"Distribution failed in AAI\" }";
+ private static final String requestJSON =
+ "{\"status\": \"DISTRIBUTION_COMPLETE_ERROR\", \"errorReason\": \"Distribution failed in AAI\" }";
@Rule
public ExpectedException thrown = ExpectedException.none();
- @Mock
- private Provider<TenantIsolationRunnable> thread;
- @InjectMocks
- @Spy
- private ModelDistributionRequest request = new ModelDistributionRequest();
- @Mock
- private TenantIsolationRunnable runnable = new TenantIsolationRunnable();
-
- @Before
- public void beforeTest() {
- Mockito.when(thread.get()).thenReturn(runnable);
- }
-
- @Test
- public void testObjectMapperError() throws ApiException{
+ @Mock
+ private Provider<TenantIsolationRunnable> thread;
+ @InjectMocks
+ @Spy
+ private ModelDistributionRequest request = new ModelDistributionRequest();
+ @Mock
+ private TenantIsolationRunnable runnable = new TenantIsolationRunnable();
+
+ @Before
+ public void beforeTest() {
+ Mockito.when(thread.get()).thenReturn(runnable);
+ }
+
+ @Test
+ public void testObjectMapperError() throws ApiException {
thrown.expect(ValidateException.class);
thrown.expectMessage(startsWith("Mapping of request to JSON object failed"));
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
request.updateModelDistributionStatus("", null, null);
- }
-
- @Test
- public void testParseError1() throws ApiException{
+ }
+
+ @Test
+ public void testParseError1() throws ApiException {
thrown.expect(ValidateException.class);
thrown.expectMessage(startsWith("No valid status is specified"));
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
String requestErrorJSON = "{\"errorReason\": \"Distribution failed in AAI\" }";
request.updateModelDistributionStatus(requestErrorJSON, null, null);
- }
-
- @Test
- public void testParseError2() throws ApiException{
+ }
+
+ @Test
+ public void testParseError2() throws ApiException {
thrown.expect(ValidateException.class);
thrown.expectMessage(startsWith("No valid errorReason is specified"));
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER)));
String requestErrorJSON = "{\"status\": \"DISTRIBUTION_COMPLETE_ERROR\"}";
request.updateModelDistributionStatus(requestErrorJSON, null, null);
- }
-
- @Test
- public void testSuccess() throws ApiException{
- doNothing().when(runnable).run(any(Action.class), anyString(), any(CloudOrchestrationRequest.class), anyString());
-
- Response response = request.updateModelDistributionStatus(requestJSON, null, null);
-
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void testSuccess_PATCH() throws ApiException, IOException{
- String path = "/onap/so/infra/modelDistributions/v1/distributions/ff3514e3-5a33-55df-13ab-12abad84e7fa";
- ObjectMapper mapper = new ObjectMapper();
- Distribution distRequest = mapper.readValue(requestJSON, Distribution.class);
- HttpHeaders headers = new HttpHeaders();
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<Distribution> entity = new HttpEntity<Distribution>(distRequest, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path));
- ResponseEntity<String> response = restTemplate.exchange(
- builder.toUriString(),
- HttpMethod.PATCH, entity, String.class);
- assertEquals(200, response.getStatusCodeValue());
-
- }
-
+ }
+
+ @Test
+ public void testSuccess() throws ApiException {
+ doNothing().when(runnable).run(any(Action.class), anyString(), any(CloudOrchestrationRequest.class),
+ anyString());
+
+ Response response = request.updateModelDistributionStatus(requestJSON, null, null);
+
+ assertEquals(200, response.getStatus());
+ }
+
+ @Test
+ public void testSuccess_PATCH() throws ApiException, IOException {
+ String path = "/onap/so/infra/modelDistributions/v1/distributions/ff3514e3-5a33-55df-13ab-12abad84e7fa";
+ ObjectMapper mapper = new ObjectMapper();
+ Distribution distRequest = mapper.readValue(requestJSON, Distribution.class);
+ HttpHeaders headers = new HttpHeaders();
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<Distribution> entity = new HttpEntity<Distribution>(distRequest, headers);
+
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path));
+ ResponseEntity<String> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.PATCH, entity, String.class);
+ assertEquals(200, response.getStatusCodeValue());
+
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java
index 426be98486..d983d1eca8 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java
@@ -22,11 +22,9 @@ package org.onap.so.apihandlerinfra.tenantisolation;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
-
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
-
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -34,110 +32,116 @@ import org.onap.so.apihandlerinfra.BaseTest;
import org.onap.so.apihandlerinfra.tenantisolationbeans.Action;
import org.onap.so.exceptions.ValidationException;
import org.springframework.test.context.ActiveProfiles;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-public class TenantIsolationRequestTest extends BaseTest{
+public class TenantIsolationRequestTest extends BaseTest {
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Test
+ public void testParseCloudResourceECOMP() throws Exception {
+ try {
+ String requestJSON = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ HashMap<String, String> instanceIdMap = new HashMap<String, String>();
+ CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
+ TenantIsolationRequest request = new TenantIsolationRequest("1234");
+ request.parse(cor, instanceIdMap, Action.create);
+ assertNotNull(request.getRequestId());
+ } catch (ValidationException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ @Test
+ public void testParseCloudResourceVNF() throws Exception {
+ try {
+ String requestJSON = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ HashMap<String, String> instanceIdMap = new HashMap<String, String>();
+ CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
+ TenantIsolationRequest request = new TenantIsolationRequest("1234");
+ request.parse(cor, instanceIdMap, Action.create);
+ assertNotNull(request.getRequestId());
+ } catch (ValidationException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ @Test
+ public void testParseCloudResourceVNFInvalid() throws Exception {
+ expectedException.expect(ValidationException.class);
+
+ String requestJSON = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreateInvalid.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ HashMap<String, String> instanceIdMap = new HashMap<String, String>();
+ CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
+ TenantIsolationRequest request = new TenantIsolationRequest("1234");
+ request.parse(cor, instanceIdMap, Action.create);
+ assertNotNull(request.getRequestId());
+ }
+
+ @Test
+ public void testParseActivateCloudResource() throws Exception {
+ try {
+ String requestJSON = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/TenantIsolation/ActivateOperationEnvironment.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ HashMap<String, String> instanceIdMap = new HashMap<String, String>();
+ CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
+ TenantIsolationRequest request = new TenantIsolationRequest("1234");
+ request.parse(cor, instanceIdMap, Action.activate);
+ assertNotNull(request.getRequestId());
+ } catch (ValidationException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ @Test
+ public void testParseActivateCloudResourceInvalid() throws Exception {
+ expectedException.expect(ValidationException.class);
+
+ String requestJSON = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/TenantIsolation/ActivateOperationEnvironmentInvalid.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ HashMap<String, String> instanceIdMap = new HashMap<String, String>();
+ CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
+ TenantIsolationRequest request = new TenantIsolationRequest("1234");
+ request.parse(cor, instanceIdMap, Action.activate);
+ assertNotNull(request.getRequestId());
+ }
+
+ @Test
+ public void testParseDeactivateCloudResource() throws Exception {
+ try {
+ String requestJSON = new String(Files
+ .readAllBytes(Paths.get("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ HashMap<String, String> instanceIdMap = new HashMap<String, String>();
+ CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
+ TenantIsolationRequest request = new TenantIsolationRequest("1234");
+ request.parse(cor, instanceIdMap, Action.deactivate);
+ assertNotNull(request.getRequestId());
+ } catch (ValidationException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ @Test
+ public void testParseDeactivateCloudResourceInvalid() throws Exception {
+ expectedException.expect(ValidationException.class);
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Test
- public void testParseCloudResourceECOMP() throws Exception{
- try {
- String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json")));
- ObjectMapper mapper = new ObjectMapper();
- HashMap<String, String> instanceIdMap = new HashMap<String,String>();
- CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
- TenantIsolationRequest request = new TenantIsolationRequest ("1234");
- request.parse(cor, instanceIdMap, Action.create);
- assertNotNull(request.getRequestId());
- } catch(ValidationException e) {
- fail(e.getMessage());
- }
- }
-
- @Test
- public void testParseCloudResourceVNF() throws Exception{
- try {
- String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json")));
- ObjectMapper mapper = new ObjectMapper();
- HashMap<String, String> instanceIdMap = new HashMap<String,String>();
- CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
- TenantIsolationRequest request = new TenantIsolationRequest ("1234");
- request.parse(cor, instanceIdMap, Action.create);
- assertNotNull(request.getRequestId());
- } catch(ValidationException e) {
- fail(e.getMessage());
- }
- }
-
- @Test
- public void testParseCloudResourceVNFInvalid() throws Exception {
- expectedException.expect(ValidationException.class);
-
- String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreateInvalid.json")));
- ObjectMapper mapper = new ObjectMapper();
- HashMap<String, String> instanceIdMap = new HashMap<String,String>();
- CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
- TenantIsolationRequest request = new TenantIsolationRequest ("1234");
- request.parse(cor, instanceIdMap, Action.create);
- assertNotNull(request.getRequestId());
- }
-
- @Test
- public void testParseActivateCloudResource() throws Exception{
- try {
- String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/ActivateOperationEnvironment.json")));
- ObjectMapper mapper = new ObjectMapper();
- HashMap<String, String> instanceIdMap = new HashMap<String,String>();
- CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
- TenantIsolationRequest request = new TenantIsolationRequest ("1234");
- request.parse(cor, instanceIdMap, Action.activate);
- assertNotNull(request.getRequestId());
- } catch(ValidationException e) {
- fail(e.getMessage());
- }
- }
-
- @Test
- public void testParseActivateCloudResourceInvalid() throws Exception{
- expectedException.expect(ValidationException.class);
-
- String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/ActivateOperationEnvironmentInvalid.json")));
- ObjectMapper mapper = new ObjectMapper();
- HashMap<String, String> instanceIdMap = new HashMap<String,String>();
- CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
- TenantIsolationRequest request = new TenantIsolationRequest ("1234");
- request.parse(cor, instanceIdMap, Action.activate);
- assertNotNull(request.getRequestId());
- }
-
- @Test
- public void testParseDeactivateCloudResource() throws Exception{
- try {
- String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json")));
- ObjectMapper mapper = new ObjectMapper();
- HashMap<String, String> instanceIdMap = new HashMap<String,String>();
- CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
- TenantIsolationRequest request = new TenantIsolationRequest ("1234");
- request.parse(cor, instanceIdMap, Action.deactivate);
- assertNotNull(request.getRequestId());
- } catch(ValidationException e) {
- fail(e.getMessage());
- }
- }
-
- @Test
- public void testParseDeactivateCloudResourceInvalid() throws Exception{
- expectedException.expect(ValidationException.class);
-
- String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/DeactivateOperationEnvironmentInvalid.json")));
- ObjectMapper mapper = new ObjectMapper();
- HashMap<String, String> instanceIdMap = new HashMap<String,String>();
- CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
- TenantIsolationRequest request = new TenantIsolationRequest ("1234");
- request.parse(cor, instanceIdMap, Action.deactivate);
- assertNotNull(request.getRequestId());
- }
+ String requestJSON = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/TenantIsolation/DeactivateOperationEnvironmentInvalid.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ HashMap<String, String> instanceIdMap = new HashMap<String, String>();
+ CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
+ TenantIsolationRequest request = new TenantIsolationRequest("1234");
+ request.parse(cor, instanceIdMap, Action.deactivate);
+ assertNotNull(request.getRequestId());
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java
index ef57fa1a76..34f9c04b82 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java
@@ -21,12 +21,10 @@
package org.onap.so.apihandlerinfra.tenantisolation.dmaap;
import static org.junit.Assert.assertEquals;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.apihandlerinfra.ApiHandlerApplication;
@@ -36,37 +34,37 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-public class DmaapOperationalEnvClientTest extends BaseTest{
-
- private final String fileLocation = "src/test/resources/org/onap/so/client/asdc/create-ecompoe/";
- private static final String operationalEnvironmentId = "28122015552391";
- private static final String operationalEnvironmentName = "OpEnv-name";
- private static final String operationalEnvironmentType = "VNF";
- private static final String tenantContext = "Test";
- private static final String workloadContext = "VNF_E2E-IST";
- private static final String action = "Create";
- @Autowired
- private DmaapOperationalEnvClient client;
-
- @Test
- public void verifyCreateEcompOperationEnvironmentRequest() throws IOException, ApiException {
- String content = this.getJson("ecomp-openv-request.json");
- ObjectMapper mapper = new ObjectMapper();
- CreateEcompOperationEnvironmentBean expected = mapper.readValue(content, CreateEcompOperationEnvironmentBean.class);
-
- String actual = client.buildRequest(operationalEnvironmentId, operationalEnvironmentName, operationalEnvironmentType,
- tenantContext, workloadContext, action);
-
- assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual);
- }
-
-
- private String getJson(String filename) throws IOException {
- return new String(Files.readAllBytes(Paths.get(fileLocation + filename)));
- }
-
+public class DmaapOperationalEnvClientTest extends BaseTest {
+
+ private final String fileLocation = "src/test/resources/org/onap/so/client/asdc/create-ecompoe/";
+ private static final String operationalEnvironmentId = "28122015552391";
+ private static final String operationalEnvironmentName = "OpEnv-name";
+ private static final String operationalEnvironmentType = "VNF";
+ private static final String tenantContext = "Test";
+ private static final String workloadContext = "VNF_E2E-IST";
+ private static final String action = "Create";
+ @Autowired
+ private DmaapOperationalEnvClient client;
+
+ @Test
+ public void verifyCreateEcompOperationEnvironmentRequest() throws IOException, ApiException {
+ String content = this.getJson("ecomp-openv-request.json");
+ ObjectMapper mapper = new ObjectMapper();
+ CreateEcompOperationEnvironmentBean expected =
+ mapper.readValue(content, CreateEcompOperationEnvironmentBean.class);
+
+ String actual = client.buildRequest(operationalEnvironmentId, operationalEnvironmentName,
+ operationalEnvironmentType, tenantContext, workloadContext, action);
+
+ assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual);
+ }
+
+
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(fileLocation + filename)));
+ }
+
}
-
+
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java
index 7329f313a5..4263bbdee1 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java
@@ -21,10 +21,8 @@
package org.onap.so.apihandlerinfra.tenantisolation.dmaap;
import static org.junit.Assert.assertEquals;
-
import java.io.FileNotFoundException;
import java.io.IOException;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.apihandlerinfra.ApiHandlerApplication;
@@ -37,15 +35,17 @@ import org.springframework.test.context.junit4.SpringRunner;
public class OperationalEnvironmentPublisherTest extends BaseTest {
- @Autowired
- private OperationalEnvironmentPublisher publisher;
-
- @Test
- public void getProperties() throws FileNotFoundException, IOException {
-
- assertEquals("B3705D6C2D521257CC2422ACCF03B001811ACC49F564DDB3A2CF2A1378B6D35A23CDCB696F2E1EDFBE6758DFE7C74B94F4A7DF84A0E2BB904935AC4D900D5597DF981ADE6CE1FF3AF993BED0", publisher.getAuth());
- assertEquals("07a7159d3bf51a0e53be7a8f89699be7", publisher.getKey());
- assertEquals("test.operationalEnvironmentEvent", publisher.getTopic());
- assertEquals("http://localhost:" + env.getProperty("wiremock.server.port"), publisher.getHost().get());
- }
+ @Autowired
+ private OperationalEnvironmentPublisher publisher;
+
+ @Test
+ public void getProperties() throws FileNotFoundException, IOException {
+
+ assertEquals(
+ "B3705D6C2D521257CC2422ACCF03B001811ACC49F564DDB3A2CF2A1378B6D35A23CDCB696F2E1EDFBE6758DFE7C74B94F4A7DF84A0E2BB904935AC4D900D5597DF981ADE6CE1FF3AF993BED0",
+ publisher.getAuth());
+ assertEquals("07a7159d3bf51a0e53be7a8f89699be7", publisher.getKey());
+ assertEquals("test.operationalEnvironmentEvent", publisher.getTopic());
+ assertEquals("http://localhost:" + env.getProperty("wiremock.server.port"), publisher.getHost().get());
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java
index 3fcfa5dfa8..cb977607ea 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java
@@ -21,50 +21,48 @@
package org.onap.so.apihandlerinfra.tenantisolation.dmaap;
import static org.junit.Assert.assertEquals;
-
import java.io.IOException;
import java.text.ParseException;
-
import org.junit.Test;
import org.onap.so.apihandlerinfra.BaseTest;
import org.onap.so.apihandlerinfra.tenantisolation.dmaap.CreateEcompOperationEnvironmentBean;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-public class SDCDmaapClientTest extends BaseTest{
-
- private final String fileLocation = "src/test/resources/org/onap/so/client/asdc/create-ecompoe/";
-
- private static final String operationalEnvironmentId = "28122015552391";
- private static final String operationalEnvironmentName = "Operational Environment Name";
- private static final String operationalEnvironmentType = "ECOMP";
- private static final String tenantContext = "TEST";
- private static final String workloadContext = "ECOMP_E2E-IST";
- private static final String action = "Create" ;
-
-
-
- @Test
- public void verifyasdcCreateoeRequest() throws IOException, ParseException{
-
- ObjectMapper mapper = new ObjectMapper();
-
- String expected = "{\"operationalEnvironmentId\":\"28122015552391\",\"operationalEnvironmentName\":\"Operational Environment Name\",\"operationalEnvironmentType\":\"ECOMP\",\"tenantContext\":\"TEST\",\"workloadContext\":\"ECOMP_E2E-IST\",\"action\":\"Create\"}";
-
-
- CreateEcompOperationEnvironmentBean cBean = new CreateEcompOperationEnvironmentBean();
- cBean.setOperationalEnvironmentId(operationalEnvironmentId);
- cBean.setoperationalEnvironmentName(operationalEnvironmentName);
- cBean.setoperationalEnvironmentType(operationalEnvironmentType);
- cBean.settenantContext(tenantContext);
- cBean.setworkloadContext(workloadContext);
- cBean.setaction(action);
-
- String actual = mapper.writeValueAsString(cBean);
-
- assertEquals("payloads are equal", expected, actual);
- }
-
-
-
+public class SDCDmaapClientTest extends BaseTest {
+
+ private final String fileLocation = "src/test/resources/org/onap/so/client/asdc/create-ecompoe/";
+
+ private static final String operationalEnvironmentId = "28122015552391";
+ private static final String operationalEnvironmentName = "Operational Environment Name";
+ private static final String operationalEnvironmentType = "ECOMP";
+ private static final String tenantContext = "TEST";
+ private static final String workloadContext = "ECOMP_E2E-IST";
+ private static final String action = "Create";
+
+
+
+ @Test
+ public void verifyasdcCreateoeRequest() throws IOException, ParseException {
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ String expected =
+ "{\"operationalEnvironmentId\":\"28122015552391\",\"operationalEnvironmentName\":\"Operational Environment Name\",\"operationalEnvironmentType\":\"ECOMP\",\"tenantContext\":\"TEST\",\"workloadContext\":\"ECOMP_E2E-IST\",\"action\":\"Create\"}";
+
+
+ CreateEcompOperationEnvironmentBean cBean = new CreateEcompOperationEnvironmentBean();
+ cBean.setOperationalEnvironmentId(operationalEnvironmentId);
+ cBean.setoperationalEnvironmentName(operationalEnvironmentName);
+ cBean.setoperationalEnvironmentType(operationalEnvironmentType);
+ cBean.settenantContext(tenantContext);
+ cBean.setworkloadContext(workloadContext);
+ cBean.setaction(action);
+
+ String actual = mapper.writeValueAsString(cBean);
+
+ assertEquals("payloads are equal", expected, actual);
+ }
+
+
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java
index 2cb02e9666..8918b015e9 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java
@@ -20,7 +20,6 @@
package org.onap.so.apihandlerinfra.tenantisolation.exceptions;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.apihandlerinfra.BaseTest;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java
index 5ee2eeaeba..7ad55ded48 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java
@@ -21,25 +21,24 @@
package org.onap.so.apihandlerinfra.tenantisolation.exceptions;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.apihandlerinfra.BaseTest;
-public class SDCClientCallFailedTest extends BaseTest{
-
- @Test
- public void testAsdcException() {
- SDCClientCallFailed asdc = new SDCClientCallFailed("failed");
-
- assertEquals("failed", asdc.getMessage());
- }
-
- @Test
- public void testAsdcExceptionWithCause() {
- SDCClientCallFailed asdc = new SDCClientCallFailed("failed", new Throwable("throwable"));
-
- assertEquals("failed", asdc.getMessage());
- assertEquals("throwable", asdc.getCause().getMessage());
- }
+public class SDCClientCallFailedTest extends BaseTest {
+
+ @Test
+ public void testAsdcException() {
+ SDCClientCallFailed asdc = new SDCClientCallFailed("failed");
+
+ assertEquals("failed", asdc.getMessage());
+ }
+
+ @Test
+ public void testAsdcExceptionWithCause() {
+ SDCClientCallFailed asdc = new SDCClientCallFailed("failed", new Throwable("throwable"));
+
+ assertEquals("failed", asdc.getMessage());
+ assertEquals("throwable", asdc.getCause().getMessage());
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java
index f73a194a7b..db5d15a998 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java
@@ -22,24 +22,23 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import org.junit.Test;
import org.onap.so.apihandlerinfra.BaseTest;
-public class TenantIsolationExceptionTest extends BaseTest{
-
- @Test
- public void testTenantIsolation() {
- TenantIsolationException exception = new TenantIsolationException();
-
- assertNotNull(exception);
- }
-
- @Test
- public void testTenantIsolationException() {
- TenantIsolationException exception = new TenantIsolationException("exception");
-
- assertEquals("Tenant Isolation error: exception", exception.getMessage());
- }
+public class TenantIsolationExceptionTest extends BaseTest {
+
+ @Test
+ public void testTenantIsolation() {
+ TenantIsolationException exception = new TenantIsolationException();
+
+ assertNotNull(exception);
+ }
+
+ @Test
+ public void testTenantIsolationException() {
+ TenantIsolationException exception = new TenantIsolationException("exception");
+
+ assertEquals("Tenant Isolation error: exception", exception.getMessage());
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java
index 6c5e968835..3a389ce227 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java
@@ -33,11 +33,9 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-
import org.apache.http.HttpStatus;
import org.junit.Test;
import org.onap.aai.domain.yang.OperationalEnvironment;
@@ -48,100 +46,112 @@ import org.springframework.beans.factory.annotation.Autowired;
-public class AAIClientHelperTest extends BaseTest{
-
- @Autowired
- private AAIClientHelper clientHelper;
-
- @Test
- public void testGetAaiOperationalEnvironmentSuccess() throws Exception {
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED)));
-
- AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001");
- Optional<OperationalEnvironment> aaiOpEnv = wrapper.asBean(OperationalEnvironment.class);
- assertEquals("EMOE-001", aaiOpEnv.get().getOperationalEnvironmentId());
- }
-
- @Test
- public void testUpdateSuccess() {
- wireMockServer.stubFor(post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
-
- OperationalEnvironment ecompEnv = new OperationalEnvironment();
- ecompEnv.setTenantContext("Test");
- ecompEnv.setWorkloadContext("ECOMPL_PSL");
-
- try {
- AAIClientHelper clientHelper = mock(AAIClientHelper.class);
- doNothing().when(clientHelper).updateAaiOperationalEnvironment(any(String.class), any(OperationalEnvironment.class));
- clientHelper.updateAaiOperationalEnvironment("EMOE-001", ecompEnv);
-
- verify(clientHelper, times(1)).updateAaiOperationalEnvironment("EMOE-001", ecompEnv);
- } catch(Exception e) {
- fail("shouldn't reach here");
- }
- }
-
- @Test
- public void testUpdateMapSuccess() {
- wireMockServer.stubFor(post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
-
- Map<String, String> payload = new HashMap<String, String>();
- payload.put("tenant-context", "Test");
- payload.put("workload-context", "ECOMPL_PSL");
- payload.put("operational-environment-status", "ACTIVE");
-
- try {
- AAIClientHelper clientHelper = mock(AAIClientHelper.class);
- doNothing().when(clientHelper).updateAaiOperationalEnvironment("EMOE-001", payload);
- clientHelper.updateAaiOperationalEnvironment("EMOE-001", payload);
-
- verify(clientHelper, times(1)).updateAaiOperationalEnvironment("EMOE-001", payload);
- } catch(Exception e) {
- fail("shouldn't reach here");
- }
- }
-
- @Test
- public void testCreateSuccess() {
- wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
-
- OperationalEnvironment ecompEnv = new OperationalEnvironment();
- ecompEnv.setOperationalEnvironmentId("opeEvnId");
- ecompEnv.setTenantContext("Test");
- ecompEnv.setWorkloadContext("ECOMPL_PSL");
-
- try {
- AAIClientHelper clientHelper = mock(AAIClientHelper.class);
- doNothing().when(clientHelper).createOperationalEnvironment(any(OperationalEnvironment.class));
- clientHelper.createOperationalEnvironment(ecompEnv);
-
- verify(clientHelper, times(1)).createOperationalEnvironment(ecompEnv);
- } catch(Exception e) {
- fail("shouldn't reach here");
- }
- }
-
- @Test
- public void testcreateRelationshipSuccess() {
- wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
-
- OperationalEnvironment ecompEnv = new OperationalEnvironment();
- ecompEnv.setTenantContext("Test");
- ecompEnv.setWorkloadContext("ECOMPL_PSL");
-
- try {
- AAIClientHelper clientHelper = mock(AAIClientHelper.class);
- doNothing().when(clientHelper).createRelationship(anyString(), anyString());
- clientHelper.createRelationship("managingEcomp", "vnfOp");
-
- verify(clientHelper, times(1)).createRelationship("managingEcomp", "vnfOp");
- } catch(Exception e) {
- fail("shouldn't reach here");
- }
- }
+public class AAIClientHelperTest extends BaseTest {
+
+ @Autowired
+ private AAIClientHelper clientHelper;
+
+ @Test
+ public void testGetAaiOperationalEnvironmentSuccess() throws Exception {
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001");
+ Optional<OperationalEnvironment> aaiOpEnv = wrapper.asBean(OperationalEnvironment.class);
+ assertEquals("EMOE-001", aaiOpEnv.get().getOperationalEnvironmentId());
+ }
+
+ @Test
+ public void testUpdateSuccess() {
+ wireMockServer.stubFor(
+ post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ OperationalEnvironment ecompEnv = new OperationalEnvironment();
+ ecompEnv.setTenantContext("Test");
+ ecompEnv.setWorkloadContext("ECOMPL_PSL");
+
+ try {
+ AAIClientHelper clientHelper = mock(AAIClientHelper.class);
+ doNothing().when(clientHelper).updateAaiOperationalEnvironment(any(String.class),
+ any(OperationalEnvironment.class));
+ clientHelper.updateAaiOperationalEnvironment("EMOE-001", ecompEnv);
+
+ verify(clientHelper, times(1)).updateAaiOperationalEnvironment("EMOE-001", ecompEnv);
+ } catch (Exception e) {
+ fail("shouldn't reach here");
+ }
+ }
+
+ @Test
+ public void testUpdateMapSuccess() {
+ wireMockServer.stubFor(
+ post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ Map<String, String> payload = new HashMap<String, String>();
+ payload.put("tenant-context", "Test");
+ payload.put("workload-context", "ECOMPL_PSL");
+ payload.put("operational-environment-status", "ACTIVE");
+
+ try {
+ AAIClientHelper clientHelper = mock(AAIClientHelper.class);
+ doNothing().when(clientHelper).updateAaiOperationalEnvironment("EMOE-001", payload);
+ clientHelper.updateAaiOperationalEnvironment("EMOE-001", payload);
+
+ verify(clientHelper, times(1)).updateAaiOperationalEnvironment("EMOE-001", payload);
+ } catch (Exception e) {
+ fail("shouldn't reach here");
+ }
+ }
+
+ @Test
+ public void testCreateSuccess() {
+ wireMockServer.stubFor(
+ put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ OperationalEnvironment ecompEnv = new OperationalEnvironment();
+ ecompEnv.setOperationalEnvironmentId("opeEvnId");
+ ecompEnv.setTenantContext("Test");
+ ecompEnv.setWorkloadContext("ECOMPL_PSL");
+
+ try {
+ AAIClientHelper clientHelper = mock(AAIClientHelper.class);
+ doNothing().when(clientHelper).createOperationalEnvironment(any(OperationalEnvironment.class));
+ clientHelper.createOperationalEnvironment(ecompEnv);
+
+ verify(clientHelper, times(1)).createOperationalEnvironment(ecompEnv);
+ } catch (Exception e) {
+ fail("shouldn't reach here");
+ }
+ }
+
+ @Test
+ public void testcreateRelationshipSuccess() {
+ wireMockServer.stubFor(
+ put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ OperationalEnvironment ecompEnv = new OperationalEnvironment();
+ ecompEnv.setTenantContext("Test");
+ ecompEnv.setWorkloadContext("ECOMPL_PSL");
+
+ try {
+ AAIClientHelper clientHelper = mock(AAIClientHelper.class);
+ doNothing().when(clientHelper).createRelationship(anyString(), anyString());
+ clientHelper.createRelationship("managingEcomp", "vnfOp");
+
+ verify(clientHelper, times(1)).createRelationship("managingEcomp", "vnfOp");
+ } catch (Exception e) {
+ fail("shouldn't reach here");
+ }
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java
index 3915fc8928..4a602345d3 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.tenantisolation.helpers;
import static org.junit.Assert.assertEquals;
-
import org.junit.Before;
import org.junit.Test;
import org.onap.so.apihandlerinfra.BaseTest;
@@ -30,43 +29,43 @@ import org.onap.so.apihandlerinfra.tenantisolationbeans.OperationalEnvironment;
import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestDetails;
import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestInfo;
import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestParameters;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-public class AAIClientObjectBuilderTest extends BaseTest{
+public class AAIClientObjectBuilderTest extends BaseTest {
- private CloudOrchestrationRequest request;
- private ObjectMapper mapper = new ObjectMapper();
-
- @Before
+ private CloudOrchestrationRequest request;
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Before
public void testSetUp() {
- request = getCloudOrchestrationRequest();
- }
+ request = getCloudOrchestrationRequest();
+ }
+
+ public CloudOrchestrationRequest getCloudOrchestrationRequest() {
+ CloudOrchestrationRequest cor = new CloudOrchestrationRequest();
+ RequestDetails reqDetails = new RequestDetails();
+ RequestInfo reqInfo = new RequestInfo();
+ RequestParameters reqParams = new RequestParameters();
+ reqParams.setTenantContext("TEST");
+ reqParams.setWorkloadContext("ECOMP_TEST");
+ reqParams.setOperationalEnvironmentType(OperationalEnvironment.ECOMP);
+ reqInfo.setInstanceName("TEST_ECOMP_ENVIRONMENT");
+ reqDetails.setRequestInfo(reqInfo);
+ reqDetails.setRequestParameters(reqParams);
+ cor.setRequestDetails(reqDetails);
+ return cor;
+ }
- public CloudOrchestrationRequest getCloudOrchestrationRequest() {
- CloudOrchestrationRequest cor = new CloudOrchestrationRequest();
- RequestDetails reqDetails = new RequestDetails();
- RequestInfo reqInfo = new RequestInfo();
- RequestParameters reqParams = new RequestParameters();
- reqParams.setTenantContext("TEST");
- reqParams.setWorkloadContext("ECOMP_TEST");
- reqParams.setOperationalEnvironmentType(OperationalEnvironment.ECOMP);
- reqInfo.setInstanceName("TEST_ECOMP_ENVIRONMENT");
- reqDetails.setRequestInfo(reqInfo);
- reqDetails.setRequestParameters(reqParams);
- cor.setRequestDetails(reqDetails);
- return cor;
- }
-
- @Test
- public void testGetAaiClientObjectBuilder() throws Exception {
- AAIClientObjectBuilder builder = new AAIClientObjectBuilder();
- org.onap.aai.domain.yang.OperationalEnvironment operEnv = builder.buildAAIOperationalEnvironment("Active", request);
- assertEquals("TEST", operEnv.getTenantContext());
- assertEquals("ECOMP_TEST", operEnv.getWorkloadContext());
- assertEquals("TEST_ECOMP_ENVIRONMENT", operEnv.getOperationalEnvironmentName());
- assertEquals(OperationalEnvironment.ECOMP.toString(), operEnv.getOperationalEnvironmentType());
- }
+ @Test
+ public void testGetAaiClientObjectBuilder() throws Exception {
+ AAIClientObjectBuilder builder = new AAIClientObjectBuilder();
+ org.onap.aai.domain.yang.OperationalEnvironment operEnv =
+ builder.buildAAIOperationalEnvironment("Active", request);
+ assertEquals("TEST", operEnv.getTenantContext());
+ assertEquals("ECOMP_TEST", operEnv.getWorkloadContext());
+ assertEquals("TEST_ECOMP_ENVIRONMENT", operEnv.getOperationalEnvironmentName());
+ assertEquals(OperationalEnvironment.ECOMP.toString(), operEnv.getOperationalEnvironmentType());
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java
index 6fda6afc50..800fb37039 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java
@@ -21,7 +21,6 @@
package org.onap.so.apihandlerinfra.tenantisolation.helpers;
import static org.junit.Assert.assertThat;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -34,112 +33,96 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
-
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
-public class ActivateVnfDBHelperTest extends BaseTest{
-
- String operationalEnvironmentId = "TEST_operationalEnvironmentId";
- String vnfOperationalEnvironmentId = "VNF_operationalEnvironmentId";
- String requestId = "TEST_requestId";
- String origRequestId = "TEST_requestId";
-
- String workloadContext1 = "TEST_workloadContext1";
- String serviceModelVersionId1 = "TEST_serviceModelVersionId1";
- String distributionId1 = "TEST_distributionId1";
- String errorReason = "ABORTED";
- int retryCountThree = 3;
- int retryCountZero = 0;
- String recoveryActionRetry = "RETRY";
- String statusOk = DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString();
- String statusError = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString();
- String statusSent = "SENT";
-
- OperationalEnvDistributionStatus expectedDistStatus;
- OperationalEnvServiceModelStatus expectedServiceModelStatus;
-
- @Autowired
- private ActivateVnfDBHelper dbHelper;
-
- @Before
- public void testSetUp() {
- // prepare expected OperationalEnvDistributionStatus object
- expectedDistStatus = new OperationalEnvDistributionStatus();
- expectedDistStatus.setDistributionId(distributionId1);
- expectedDistStatus.setOperationalEnvId(operationalEnvironmentId);
- expectedDistStatus.setServiceModelVersionId(serviceModelVersionId1);
- expectedDistStatus.setDistributionIdStatus(statusOk);
- expectedDistStatus.setRequestId(requestId);
- expectedDistStatus.setDistributionIdErrorReason("");
-
- // prepare expected OperationalEnvServiceModelStatus object
- expectedServiceModelStatus = new OperationalEnvServiceModelStatus();
- expectedServiceModelStatus.setRequestId(requestId);
- expectedServiceModelStatus.setOperationalEnvId(operationalEnvironmentId);
- expectedServiceModelStatus.setServiceModelVersionId(serviceModelVersionId1);
- expectedServiceModelStatus.setServiceModelVersionDistrStatus(statusOk);
- expectedServiceModelStatus.setRecoveryAction(recoveryActionRetry);
- expectedServiceModelStatus.setRetryCount(new Integer(retryCountThree));
- expectedServiceModelStatus.setWorkloadContext(workloadContext1);
- expectedServiceModelStatus.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
- }
-
- @Test
- public void testOperationalEnvDistributionStatusDbMethods() throws Exception {
-
- // test insert method
- OperationalEnvDistributionStatus distStatus1 =
- dbHelper.insertRecordToOperationalEnvDistributionStatus(distributionId1,
- operationalEnvironmentId,
- serviceModelVersionId1,
- requestId,
- statusOk,
- "");
- assertThat(distStatus1, sameBeanAs(expectedDistStatus));
-
- // prepare updated expected object
- OperationalEnvDistributionStatus expectedUpdatedDistStatus = expectedDistStatus;
- expectedUpdatedDistStatus.setDistributionIdStatus(statusError);
- expectedUpdatedDistStatus.setDistributionIdErrorReason(errorReason);
-
- // test update method - statusOk to statusError
- OperationalEnvDistributionStatus distStatus2 =
- dbHelper.updateStatusInOperationalEnvDistributionStatus(distStatus1,
- statusError,
- errorReason
- );
- assertThat(distStatus2, sameBeanAs(expectedUpdatedDistStatus));
-
- }
-
- @Test
- public void testOperationalEnvServiceModelStatusDbMethods() throws Exception {
-
- // test insert method
- OperationalEnvServiceModelStatus serviceModelStatus1 =
- dbHelper.insertRecordToOperationalEnvServiceModelStatus(requestId,
- operationalEnvironmentId,
- serviceModelVersionId1,
- statusOk,
- recoveryActionRetry,
- retryCountThree,
- workloadContext1,
- vnfOperationalEnvironmentId);
- assertThat(serviceModelStatus1, sameBeanAs(expectedServiceModelStatus));
-
- // prepare updated expected object
- OperationalEnvServiceModelStatus expectedUpdatedServiceModelStatus = serviceModelStatus1;
- expectedUpdatedServiceModelStatus.setServiceModelVersionDistrStatus(statusError);
- expectedUpdatedServiceModelStatus.setRetryCount(new Integer(retryCountZero));
-
- // test update method - update statusOk to statusError & retryCountThree to retryCountZero
- OperationalEnvServiceModelStatus serviceModelStatus2 =
- dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(serviceModelStatus1,
- statusError,
- retryCountZero);
- assertThat(serviceModelStatus2, sameBeanAs(expectedUpdatedServiceModelStatus));
-
- }
-
+public class ActivateVnfDBHelperTest extends BaseTest {
+
+ String operationalEnvironmentId = "TEST_operationalEnvironmentId";
+ String vnfOperationalEnvironmentId = "VNF_operationalEnvironmentId";
+ String requestId = "TEST_requestId";
+ String origRequestId = "TEST_requestId";
+
+ String workloadContext1 = "TEST_workloadContext1";
+ String serviceModelVersionId1 = "TEST_serviceModelVersionId1";
+ String distributionId1 = "TEST_distributionId1";
+ String errorReason = "ABORTED";
+ int retryCountThree = 3;
+ int retryCountZero = 0;
+ String recoveryActionRetry = "RETRY";
+ String statusOk = DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString();
+ String statusError = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString();
+ String statusSent = "SENT";
+
+ OperationalEnvDistributionStatus expectedDistStatus;
+ OperationalEnvServiceModelStatus expectedServiceModelStatus;
+
+ @Autowired
+ private ActivateVnfDBHelper dbHelper;
+
+ @Before
+ public void testSetUp() {
+ // prepare expected OperationalEnvDistributionStatus object
+ expectedDistStatus = new OperationalEnvDistributionStatus();
+ expectedDistStatus.setDistributionId(distributionId1);
+ expectedDistStatus.setOperationalEnvId(operationalEnvironmentId);
+ expectedDistStatus.setServiceModelVersionId(serviceModelVersionId1);
+ expectedDistStatus.setDistributionIdStatus(statusOk);
+ expectedDistStatus.setRequestId(requestId);
+ expectedDistStatus.setDistributionIdErrorReason("");
+
+ // prepare expected OperationalEnvServiceModelStatus object
+ expectedServiceModelStatus = new OperationalEnvServiceModelStatus();
+ expectedServiceModelStatus.setRequestId(requestId);
+ expectedServiceModelStatus.setOperationalEnvId(operationalEnvironmentId);
+ expectedServiceModelStatus.setServiceModelVersionId(serviceModelVersionId1);
+ expectedServiceModelStatus.setServiceModelVersionDistrStatus(statusOk);
+ expectedServiceModelStatus.setRecoveryAction(recoveryActionRetry);
+ expectedServiceModelStatus.setRetryCount(new Integer(retryCountThree));
+ expectedServiceModelStatus.setWorkloadContext(workloadContext1);
+ expectedServiceModelStatus.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
+ }
+
+ @Test
+ public void testOperationalEnvDistributionStatusDbMethods() throws Exception {
+
+ // test insert method
+ OperationalEnvDistributionStatus distStatus1 = dbHelper.insertRecordToOperationalEnvDistributionStatus(
+ distributionId1, operationalEnvironmentId, serviceModelVersionId1, requestId, statusOk, "");
+ assertThat(distStatus1, sameBeanAs(expectedDistStatus));
+
+ // prepare updated expected object
+ OperationalEnvDistributionStatus expectedUpdatedDistStatus = expectedDistStatus;
+ expectedUpdatedDistStatus.setDistributionIdStatus(statusError);
+ expectedUpdatedDistStatus.setDistributionIdErrorReason(errorReason);
+
+ // test update method - statusOk to statusError
+ OperationalEnvDistributionStatus distStatus2 =
+ dbHelper.updateStatusInOperationalEnvDistributionStatus(distStatus1, statusError, errorReason);
+ assertThat(distStatus2, sameBeanAs(expectedUpdatedDistStatus));
+
+ }
+
+ @Test
+ public void testOperationalEnvServiceModelStatusDbMethods() throws Exception {
+
+ // test insert method
+ OperationalEnvServiceModelStatus serviceModelStatus1 = dbHelper.insertRecordToOperationalEnvServiceModelStatus(
+ requestId, operationalEnvironmentId, serviceModelVersionId1, statusOk, recoveryActionRetry,
+ retryCountThree, workloadContext1, vnfOperationalEnvironmentId);
+ assertThat(serviceModelStatus1, sameBeanAs(expectedServiceModelStatus));
+
+ // prepare updated expected object
+ OperationalEnvServiceModelStatus expectedUpdatedServiceModelStatus = serviceModelStatus1;
+ expectedUpdatedServiceModelStatus.setServiceModelVersionDistrStatus(statusError);
+ expectedUpdatedServiceModelStatus.setRetryCount(new Integer(retryCountZero));
+
+ // test update method - update statusOk to statusError & retryCountThree to retryCountZero
+ OperationalEnvServiceModelStatus serviceModelStatus2 =
+ dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(serviceModelStatus1, statusError,
+ retryCountZero);
+ assertThat(serviceModelStatus2, sameBeanAs(expectedUpdatedServiceModelStatus));
+
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java
index 39f5ed834f..063902152c 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java
@@ -25,7 +25,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
-
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -34,160 +33,169 @@ import org.onap.so.apihandlerinfra.BaseTest;
import org.onap.so.apihandlerinfra.exceptions.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
-public class SDCClientHelperTest extends BaseTest{
+public class SDCClientHelperTest extends BaseTest {
- String serviceModelVersionId = "TEST_uuid1";
- String operationalEnvironmentId = "TEST_operationalEnvironmentId";
- String workloadContext = "TEST_workloadContext";
+ String serviceModelVersionId = "TEST_uuid1";
+ String operationalEnvironmentId = "TEST_operationalEnvironmentId";
+ String workloadContext = "TEST_workloadContext";
- @Autowired
- private SDCClientHelper sdcClientUtils;
+ @Autowired
+ private SDCClientHelper sdcClientUtils;
- @Test
- public void postActivateOperationalEnvironment_Test() throws ApiException {
+ @Test
+ public void postActivateOperationalEnvironment_Test() throws ApiException {
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("statusCode", "202");
- jsonObject.put("message", "Success");
- jsonObject.put("distributionId", "TEST_distributionId");
+ JSONObject jsonObject = new JSONObject();
+ jsonObject.put("statusCode", "202");
+ jsonObject.put("message", "Success");
+ jsonObject.put("distributionId", "TEST_distributionId");
- wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_uuid1/distr.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_uuid1/distr.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString())
+ .withStatus(HttpStatus.SC_ACCEPTED)));
- JSONObject jsonResponse = sdcClientUtils.postActivateOperationalEnvironment(serviceModelVersionId, operationalEnvironmentId, workloadContext);
+ JSONObject jsonResponse = sdcClientUtils.postActivateOperationalEnvironment(serviceModelVersionId,
+ operationalEnvironmentId, workloadContext);
- assertEquals("202", jsonResponse.get("statusCode"));
- assertEquals("Success", jsonResponse.get("message"));
+ assertEquals("202", jsonResponse.get("statusCode"));
+ assertEquals("Success", jsonResponse.get("message"));
- }
+ }
- @Test
- public void postActivateOperationalEnvironment_InvalidJson_Test() throws ApiException {
+ @Test
+ public void postActivateOperationalEnvironment_InvalidJson_Test() throws ApiException {
- // ERROR in asdc response, invalid json object
- JSONObject jsonErrorResponse = new JSONObject();
- jsonErrorResponse.put("requestError", "");
+ // ERROR in asdc response, invalid json object
+ JSONObject jsonErrorResponse = new JSONObject();
+ jsonErrorResponse.put("requestError", "");
- wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_uuid1/distr.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonErrorResponse.toString()).withStatus(HttpStatus.SC_BAD_REQUEST)));
+ wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_uuid1/distr.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(jsonErrorResponse.toString()).withStatus(HttpStatus.SC_BAD_REQUEST)));
- JSONObject jsonResponse = sdcClientUtils.postActivateOperationalEnvironment(serviceModelVersionId, operationalEnvironmentId, workloadContext);
+ JSONObject jsonResponse = sdcClientUtils.postActivateOperationalEnvironment(serviceModelVersionId,
+ operationalEnvironmentId, workloadContext);
- assertEquals("500", jsonResponse.get("statusCode"));
- assertEquals("", jsonResponse.get("messageId"));
- assertEquals(" Encountered Error while calling SDC POST Activate. JSONObject[\"requestError\"] is not a JSONObject.", jsonResponse.get("message"));
+ assertEquals("500", jsonResponse.get("statusCode"));
+ assertEquals("", jsonResponse.get("messageId"));
+ assertEquals(
+ " Encountered Error while calling SDC POST Activate. JSONObject[\"requestError\"] is not a JSONObject.",
+ jsonResponse.get("message"));
- }
+ }
- @Test
- public void buildUriBuilderTest() {
+ @Test
+ public void buildUriBuilderTest() {
- try {
- String url = sdcClientUtils.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
- assertEquals("http://localhost:" + env.getProperty("wiremock.server.port") + "/sdc/v1/catalog/services/TEST_uuid1/distribution/TEST_operationalEnvironmentId/activate", url);
+ try {
+ String url = sdcClientUtils.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
+ assertEquals(
+ "http://localhost:" + env.getProperty("wiremock.server.port")
+ + "/sdc/v1/catalog/services/TEST_uuid1/distribution/TEST_operationalEnvironmentId/activate",
+ url);
- } catch (Exception e) {
- fail("Exception caught: " + e.getMessage());
+ } catch (Exception e) {
+ fail("Exception caught: " + e.getMessage());
- }
- }
+ }
+ }
- @Test
- public void buildJsonWorkloadContextTest() throws JSONException {
+ @Test
+ public void buildJsonWorkloadContextTest() throws JSONException {
- String jsonPayload = sdcClientUtils.buildJsonWorkloadContext(workloadContext);
- assertEquals("{\"workloadContext\":\"TEST_workloadContext\"}", jsonPayload);
+ String jsonPayload = sdcClientUtils.buildJsonWorkloadContext(workloadContext);
+ assertEquals("{\"workloadContext\":\"TEST_workloadContext\"}", jsonPayload);
- }
+ }
- @Test
- public void enhanceJsonResponseTest_Success() throws JSONException {
+ @Test
+ public void enhanceJsonResponseTest_Success() throws JSONException {
- // build success response data
- JSONObject sdcResponseJsonObj = new JSONObject();
- sdcResponseJsonObj.put("distributionId", "TEST_distributionId");
+ // build success response data
+ JSONObject sdcResponseJsonObj = new JSONObject();
+ sdcResponseJsonObj.put("distributionId", "TEST_distributionId");
- int statusCode = 202;
- sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode);
+ int statusCode = 202;
+ sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode);
- assertEquals("202", sdcResponseJsonObj.getString("statusCode"));
- assertEquals("", sdcResponseJsonObj.getString("messageId"));
- assertEquals("Success", sdcResponseJsonObj.getString("message"));
- assertEquals("TEST_distributionId", sdcResponseJsonObj.getString("distributionId"));
+ assertEquals("202", sdcResponseJsonObj.getString("statusCode"));
+ assertEquals("", sdcResponseJsonObj.getString("messageId"));
+ assertEquals("Success", sdcResponseJsonObj.getString("message"));
+ assertEquals("TEST_distributionId", sdcResponseJsonObj.getString("distributionId"));
- }
+ }
- @Test
- public void enhanceJsonResponseTest_Error() throws JSONException {
+ @Test
+ public void enhanceJsonResponseTest_Error() throws JSONException {
- // build error response data
- JSONObject jsonMessages = new JSONObject();
- jsonMessages.put("messageId", "SVC4675");
- jsonMessages.put("text", "Error: Service state is invalid for this action.");
- JSONObject jsonServException = new JSONObject();
- jsonServException.put("serviceException", jsonMessages);
- JSONObject jsonErrorRequest = new JSONObject();
- jsonErrorRequest.put("requestError", jsonServException);
+ // build error response data
+ JSONObject jsonMessages = new JSONObject();
+ jsonMessages.put("messageId", "SVC4675");
+ jsonMessages.put("text", "Error: Service state is invalid for this action.");
+ JSONObject jsonServException = new JSONObject();
+ jsonServException.put("serviceException", jsonMessages);
+ JSONObject jsonErrorRequest = new JSONObject();
+ jsonErrorRequest.put("requestError", jsonServException);
- String responseData = jsonErrorRequest.toString();
+ String responseData = jsonErrorRequest.toString();
- JSONObject sdcResponseJsonObj = new JSONObject(responseData);
- int statusCode = 409;
- sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode);
+ JSONObject sdcResponseJsonObj = new JSONObject(responseData);
+ int statusCode = 409;
+ sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode);
- assertEquals("409", sdcResponseJsonObj.getString("statusCode"));
- assertEquals("SVC4675", sdcResponseJsonObj.getString("messageId"));
- assertEquals("Error: Service state is invalid for this action.", sdcResponseJsonObj.getString("message"));
+ assertEquals("409", sdcResponseJsonObj.getString("statusCode"));
+ assertEquals("SVC4675", sdcResponseJsonObj.getString("messageId"));
+ assertEquals("Error: Service state is invalid for this action.", sdcResponseJsonObj.getString("message"));
- }
+ }
- @Test
- public void enhanceJsonResponseTest_Error_policyException() throws JSONException {
+ @Test
+ public void enhanceJsonResponseTest_Error_policyException() throws JSONException {
- // build error response data
- JSONObject jsonMessages = new JSONObject();
- jsonMessages.put("messageId", "POL5003");
- jsonMessages.put("text", "Error: Not authorized to use the API.");
- JSONObject jsonServException = new JSONObject();
- jsonServException.put("policyException", jsonMessages);
- JSONObject jsonErrorRequest = new JSONObject();
- jsonErrorRequest.put("requestError", jsonServException);
+ // build error response data
+ JSONObject jsonMessages = new JSONObject();
+ jsonMessages.put("messageId", "POL5003");
+ jsonMessages.put("text", "Error: Not authorized to use the API.");
+ JSONObject jsonServException = new JSONObject();
+ jsonServException.put("policyException", jsonMessages);
+ JSONObject jsonErrorRequest = new JSONObject();
+ jsonErrorRequest.put("requestError", jsonServException);
- String responseData = jsonErrorRequest.toString();
+ String responseData = jsonErrorRequest.toString();
- JSONObject sdcResponseJsonObj = new JSONObject(responseData);
- int statusCode = 403;
- sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode);
+ JSONObject sdcResponseJsonObj = new JSONObject(responseData);
+ int statusCode = 403;
+ sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode);
- assertEquals("403", sdcResponseJsonObj.getString("statusCode"));
- assertEquals("POL5003", sdcResponseJsonObj.getString("messageId"));
- assertEquals("Error: Not authorized to use the API.", sdcResponseJsonObj.getString("message"));
+ assertEquals("403", sdcResponseJsonObj.getString("statusCode"));
+ assertEquals("POL5003", sdcResponseJsonObj.getString("messageId"));
+ assertEquals("Error: Not authorized to use the API.", sdcResponseJsonObj.getString("message"));
- }
+ }
- @Test
- public void enhanceJsonResponseTest_Error_UnexpectedFormat() throws JSONException {
+ @Test
+ public void enhanceJsonResponseTest_Error_UnexpectedFormat() throws JSONException {
- // build error response data
- JSONObject jsonMessages = new JSONObject();
- jsonMessages.put("messageId", "POL5003");
- jsonMessages.put("text", "Error: Not authorized to use the API.");
- JSONObject jsonServException = new JSONObject();
- jsonServException.put("policyException", jsonMessages);
- JSONObject jsonErrorRequest = new JSONObject();
- jsonErrorRequest.put("unexpectedResponseTag", jsonServException);
+ // build error response data
+ JSONObject jsonMessages = new JSONObject();
+ jsonMessages.put("messageId", "POL5003");
+ jsonMessages.put("text", "Error: Not authorized to use the API.");
+ JSONObject jsonServException = new JSONObject();
+ jsonServException.put("policyException", jsonMessages);
+ JSONObject jsonErrorRequest = new JSONObject();
+ jsonErrorRequest.put("unexpectedResponseTag", jsonServException);
- String responseData = jsonErrorRequest.toString();
+ String responseData = jsonErrorRequest.toString();
- JSONObject sdcResponseJsonObj = new JSONObject(responseData);
- int statusCode = 403;
- sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode);
+ JSONObject sdcResponseJsonObj = new JSONObject(responseData);
+ int statusCode = 403;
+ sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode);
- assertEquals("500", sdcResponseJsonObj.getString("statusCode"));
- assertEquals("Undefined Error Message!", sdcResponseJsonObj.getString("messageId"));
- assertEquals("Unexpected response format from SDC.", sdcResponseJsonObj.getString("message"));
+ assertEquals("500", sdcResponseJsonObj.getString("statusCode"));
+ assertEquals("Undefined Error Message!", sdcResponseJsonObj.getString("messageId"));
+ assertEquals("Unexpected response format from SDC.", sdcResponseJsonObj.getString("message"));
- }
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java
index 4f12afcb71..feebbd49d1 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java
@@ -29,13 +29,10 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.util.ArrayList;
import java.util.List;
-
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
-
import org.apache.http.HttpStatus;
import org.json.JSONObject;
import org.junit.Before;
@@ -57,156 +54,167 @@ import org.onap.so.client.aai.AAIVersion;
import org.onap.so.client.aai.entities.AAIResultWrapper;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class ActivateVnfOperationalEnvironmentTest extends BaseTest{
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Autowired
- private ActivateVnfOperationalEnvironment activateVnf;
- @Autowired
- private AAIClientHelper clientHelper;
-
- private final String requestId = "TEST_requestId";
- private final String operationalEnvironmentId = "1dfe7154-eae0-44f2-8e7a-8e5e7882e55d";
- private final String vnfOperationalEnvironmentId = "1dfe7154-eae0-44f2-8e7a-8e5e7882e66d";
- private final CloudOrchestrationRequest request = new CloudOrchestrationRequest();
- private final String workloadContext = "PVT";
- String recoveryActionRetry = "RETRY";
- private final String serviceModelVersionId = "TEST_serviceModelVersionId";
- int retryCount = 3;
- private final String sdcDistributionId = "TEST_distributionId";
- private final String statusSent = "SENT";
- private final ObjectMapper mapper = new ObjectMapper();
-
- @Before
- public void init(){
- wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/"))
- .withRequestBody(equalTo("{\"requestId\":\"TEST_requestId\",\"operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":3,\"workloadContext\":\"PVT\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e66d\"}"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/"))
- .withRequestBody(equalTo("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestId\",\"distributionIdStatus\":\"SENT\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- }
-
-
- @Test
- public void getAAIOperationalEnvironmentTest() {
-
- OperationalEnvironment aaiOpEnv;
-
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironmentWithRelationship.json").withStatus(HttpStatus.SC_ACCEPTED)));
-
- AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001");
- aaiOpEnv = wrapper.asBean(OperationalEnvironment.class).get();
- assertEquals("EMOE-001", aaiOpEnv.getOperationalEnvironmentId());
- assertEquals("1dfe7154-eae0-44f2-8e7a-8e5e7882e55d", aaiOpEnv.getRelationshipList().getRelationship().get(0).getRelationshipData().get(0).getRelationshipValue());
- assertNotNull(activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId));
- assertEquals( "EMOE-001", activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId).asBean(OperationalEnvironment.class).get().getOperationalEnvironmentId());
-
- }
-
- @Test
- public void executionTest() throws Exception {
-
- List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>();
- ServiceModelList serviceModelList1 = new ServiceModelList();
- serviceModelList1.setRecoveryAction(RecoveryAction.retry);
- serviceModelList1.setServiceModelVersionId(serviceModelVersionId);
- serviceModelVersionIdList.add(serviceModelList1);
-
- RequestDetails requestDetails = new RequestDetails();
- RequestParameters requestParameters = new RequestParameters();
- Manifest manifest = new Manifest();
- manifest.setServiceModelList(serviceModelVersionIdList);
- requestParameters.setManifest(manifest);
- requestParameters.setWorkloadContext(workloadContext);
- requestDetails.setRequestParameters(requestParameters);
-
- request.setOperationalEnvironmentId(vnfOperationalEnvironmentId);
- request.setRequestDetails(requestDetails);
-
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("statusCode", "202");
- jsonObject.put("message", "Success");
- jsonObject.put("distributionId", sdcDistributionId);
-
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/activateOperationalEnvironmentWithRelationship.json").withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED)));
- activateVnf.execute(requestId, request);
- }
-
- @Test
- public void processActivateSDCRequestTest_202() throws Exception {
-
- String distributionId = "TEST_distributionId";
-
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("statusCode", "202");
- jsonObject.put("message", "Success");
- jsonObject.put("distributionId", distributionId);
-
- // prepare request detail
- List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>();
- ServiceModelList serviceModelList1 = new ServiceModelList();
- serviceModelList1.setRecoveryAction(RecoveryAction.retry);
- serviceModelList1.setServiceModelVersionId(serviceModelVersionId);
- serviceModelVersionIdList.add(serviceModelList1);
-
- wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED)));
-
- activateVnf.processActivateSDCRequest(requestId, operationalEnvironmentId, serviceModelVersionIdList, workloadContext, vnfOperationalEnvironmentId);
- }
-
- @Test
- public void processActivateSDCRequestTest_409() throws ApiException, JsonProcessingException {
-
- // ERROR in asdc
- JSONObject jsonMessages = new JSONObject();
- jsonMessages.put("message", "Failure");
- jsonMessages.put("messageId", "SVC4675");
- jsonMessages.put("text", "Error: Service state is invalid for this action.");
- JSONObject jsonServException = new JSONObject();
- jsonServException.put("policyException", jsonMessages);
- //jsonServException.put("serviceException", jsonMessages);
- JSONObject jsonErrorResponse = new JSONObject();
- jsonErrorResponse.put("requestError", jsonServException);
-
- // prepare request detail
- List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>();
- ServiceModelList serviceModelList1 = new ServiceModelList();
- serviceModelList1.setRecoveryAction(RecoveryAction.retry);
- serviceModelList1.setServiceModelVersionId(serviceModelVersionId);
- serviceModelVersionIdList.add(serviceModelList1);
-
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestId);
- iar.setRequestStatus("PENDING");
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonErrorResponse.toString()).withStatus(HttpStatus.SC_CONFLICT)));
- wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
- .withRequestBody(containing("operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\""))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- thrown.expect(ValidateException.class);
-
- activateVnf.processActivateSDCRequest(requestId, operationalEnvironmentId, serviceModelVersionIdList, workloadContext, vnfOperationalEnvironmentId);
- }
-
+public class ActivateVnfOperationalEnvironmentTest extends BaseTest {
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Autowired
+ private ActivateVnfOperationalEnvironment activateVnf;
+ @Autowired
+ private AAIClientHelper clientHelper;
+
+ private final String requestId = "TEST_requestId";
+ private final String operationalEnvironmentId = "1dfe7154-eae0-44f2-8e7a-8e5e7882e55d";
+ private final String vnfOperationalEnvironmentId = "1dfe7154-eae0-44f2-8e7a-8e5e7882e66d";
+ private final CloudOrchestrationRequest request = new CloudOrchestrationRequest();
+ private final String workloadContext = "PVT";
+ String recoveryActionRetry = "RETRY";
+ private final String serviceModelVersionId = "TEST_serviceModelVersionId";
+ int retryCount = 3;
+ private final String sdcDistributionId = "TEST_distributionId";
+ private final String statusSent = "SENT";
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Before
+ public void init() {
+ wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo(
+ "{\"requestId\":\"TEST_requestId\",\"operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":3,\"workloadContext\":\"PVT\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e66d\"}"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(equalTo(
+ "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestId\",\"distributionIdStatus\":\"SENT\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+
+ @Test
+ public void getAAIOperationalEnvironmentTest() {
+
+ OperationalEnvironment aaiOpEnv;
+
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("vnfoperenv/ecompOperationalEnvironmentWithRelationship.json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001");
+ aaiOpEnv = wrapper.asBean(OperationalEnvironment.class).get();
+ assertEquals("EMOE-001", aaiOpEnv.getOperationalEnvironmentId());
+ assertEquals("1dfe7154-eae0-44f2-8e7a-8e5e7882e55d", aaiOpEnv.getRelationshipList().getRelationship().get(0)
+ .getRelationshipData().get(0).getRelationshipValue());
+ assertNotNull(activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId));
+ assertEquals("EMOE-001", activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId)
+ .asBean(OperationalEnvironment.class).get().getOperationalEnvironmentId());
+
+ }
+
+ @Test
+ public void executionTest() throws Exception {
+
+ List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>();
+ ServiceModelList serviceModelList1 = new ServiceModelList();
+ serviceModelList1.setRecoveryAction(RecoveryAction.retry);
+ serviceModelList1.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelVersionIdList.add(serviceModelList1);
+
+ RequestDetails requestDetails = new RequestDetails();
+ RequestParameters requestParameters = new RequestParameters();
+ Manifest manifest = new Manifest();
+ manifest.setServiceModelList(serviceModelVersionIdList);
+ requestParameters.setManifest(manifest);
+ requestParameters.setWorkloadContext(workloadContext);
+ requestDetails.setRequestParameters(requestParameters);
+
+ request.setOperationalEnvironmentId(vnfOperationalEnvironmentId);
+ request.setRequestDetails(requestDetails);
+
+ JSONObject jsonObject = new JSONObject();
+ jsonObject.put("statusCode", "202");
+ jsonObject.put("message", "Success");
+ jsonObject.put("distributionId", sdcDistributionId);
+
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("vnfoperenv/activateOperationalEnvironmentWithRelationship.json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString())
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ activateVnf.execute(requestId, request);
+ }
+
+ @Test
+ public void processActivateSDCRequestTest_202() throws Exception {
+
+ String distributionId = "TEST_distributionId";
+
+ JSONObject jsonObject = new JSONObject();
+ jsonObject.put("statusCode", "202");
+ jsonObject.put("message", "Success");
+ jsonObject.put("distributionId", distributionId);
+
+ // prepare request detail
+ List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>();
+ ServiceModelList serviceModelList1 = new ServiceModelList();
+ serviceModelList1.setRecoveryAction(RecoveryAction.retry);
+ serviceModelList1.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelVersionIdList.add(serviceModelList1);
+
+ wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString())
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ activateVnf.processActivateSDCRequest(requestId, operationalEnvironmentId, serviceModelVersionIdList,
+ workloadContext, vnfOperationalEnvironmentId);
+ }
+
+ @Test
+ public void processActivateSDCRequestTest_409() throws ApiException, JsonProcessingException {
+
+ // ERROR in asdc
+ JSONObject jsonMessages = new JSONObject();
+ jsonMessages.put("message", "Failure");
+ jsonMessages.put("messageId", "SVC4675");
+ jsonMessages.put("text", "Error: Service state is invalid for this action.");
+ JSONObject jsonServException = new JSONObject();
+ jsonServException.put("policyException", jsonMessages);
+ // jsonServException.put("serviceException", jsonMessages);
+ JSONObject jsonErrorResponse = new JSONObject();
+ jsonErrorResponse.put("requestError", jsonServException);
+
+ // prepare request detail
+ List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>();
+ ServiceModelList serviceModelList1 = new ServiceModelList();
+ serviceModelList1.setRecoveryAction(RecoveryAction.retry);
+ serviceModelList1.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelVersionIdList.add(serviceModelList1);
+
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId(requestId);
+ iar.setRequestStatus("PENDING");
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBody(jsonErrorResponse.toString()).withStatus(HttpStatus.SC_CONFLICT)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
+ .withRequestBody(containing("operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\""))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ thrown.expect(ValidateException.class);
+
+ activateVnf.processActivateSDCRequest(requestId, operationalEnvironmentId, serviceModelVersionIdList,
+ workloadContext, vnfOperationalEnvironmentId);
+ }
+
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java
index c6a74f3d4e..9100e82beb 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java
@@ -31,10 +31,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
-
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
-
import org.apache.http.HttpStatus;
import org.json.JSONObject;
import org.junit.Ignore;
@@ -53,606 +51,619 @@ import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.db.request.beans.OperationalEnvDistributionStatus;
import org.onap.so.db.request.beans.OperationalEnvServiceModelStatus;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class ActivateVnfStatusOperationalEnvironmentTest extends BaseTest{
+public class ActivateVnfStatusOperationalEnvironmentTest extends BaseTest {
- @Autowired
- private ActivateVnfStatusOperationalEnvironment activateVnfStatus;
+ @Autowired
+ private ActivateVnfStatusOperationalEnvironment activateVnfStatus;
@Rule
public ExpectedException thrown = ExpectedException.none();
- private final String requestId = "TEST_requestId";
- private final String requestIdOrig = "TEST_requestIdOrig";
- private final String operationalEnvironmentId = "TEST_operationalEnvironmentId";
- private final String vnfOperationalEnvironmentId = "VNF_operationalEnvironmentId";
- private final CloudOrchestrationRequest request = new CloudOrchestrationRequest();
- private final String workloadContext = "TEST_workloadContext";
- private final String recoveryActionRetry = "RETRY";
- private final String recoveryActionAbort = "ABORT";
- private final String recoveryActionSkip = "SKIP";
- private final String serviceModelVersionId = "TEST_serviceModelVersionId";
- private final String serviceModelVersionId1 = "TEST_serviceModelVersionId1";
- private final int retryCountThree = 3;
- private final int retryCountTwo = 2;
- private final int retryCountZero = 0;
- private final String sdcDistributionId1 = "TEST_distributionId1";
- private final String sdcDistributionId = "TEST_distributionId";
- private final String statusOk = Status.DISTRIBUTION_COMPLETE_OK.toString();
- private final String statusError = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString();
- private final String statusSent = "SENT";
- String json = "{\"operational-environment-status\" : \"INACTIVE\"}";
-
- private final ObjectMapper mapper = new ObjectMapper();
-
- @Test
- public void checkOrUpdateOverallStatusTest_Ok() throws Exception {
-
- // two entries, both status Ok & retry 0
- OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
- serviceModelDb.setRequestId(requestIdOrig);
- serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
- serviceModelDb.setWorkloadContext(workloadContext);
- serviceModelDb.setRecoveryAction(recoveryActionRetry);
- serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
- serviceModelDb.setRetryCount(retryCountZero);
- serviceModelDb.setServiceModelVersionDistrStatus(statusOk);
- serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
-
- serviceModelDb.setRequestId(requestIdOrig);
- serviceModelDb.setServiceModelVersionId(serviceModelVersionId1);
- serviceModelDb.setWorkloadContext(workloadContext);
- serviceModelDb.setRecoveryAction(recoveryActionRetry);
- serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
- serviceModelDb.setRetryCount(retryCountZero);
- serviceModelDb.setServiceModelVersionDistrStatus(statusOk);
- serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
-
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestIdOrig);
- iar.setRequestStatus("PENDING");
-
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceModelDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
-
- activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig);
-
- // overall is success
- }
-
- @Test
- public void checkOrUpdateOverallStatusTest_Error() throws JsonProcessingException {
-
- OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
- serviceModelDb.setRequestId(requestIdOrig);
- serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
- serviceModelDb.setWorkloadContext(workloadContext);
- serviceModelDb.setRecoveryAction(recoveryActionRetry);
- serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
- serviceModelDb.setRetryCount(retryCountZero);
- serviceModelDb.setServiceModelVersionDistrStatus(statusError);
- serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceModelDb))
- .withStatus(HttpStatus.SC_OK)));
-
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestIdOrig);
- iar.setRequestStatus("PENDING");
-
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
+ private final String requestId = "TEST_requestId";
+ private final String requestIdOrig = "TEST_requestIdOrig";
+ private final String operationalEnvironmentId = "TEST_operationalEnvironmentId";
+ private final String vnfOperationalEnvironmentId = "VNF_operationalEnvironmentId";
+ private final CloudOrchestrationRequest request = new CloudOrchestrationRequest();
+ private final String workloadContext = "TEST_workloadContext";
+ private final String recoveryActionRetry = "RETRY";
+ private final String recoveryActionAbort = "ABORT";
+ private final String recoveryActionSkip = "SKIP";
+ private final String serviceModelVersionId = "TEST_serviceModelVersionId";
+ private final String serviceModelVersionId1 = "TEST_serviceModelVersionId1";
+ private final int retryCountThree = 3;
+ private final int retryCountTwo = 2;
+ private final int retryCountZero = 0;
+ private final String sdcDistributionId1 = "TEST_distributionId1";
+ private final String sdcDistributionId = "TEST_distributionId";
+ private final String statusOk = Status.DISTRIBUTION_COMPLETE_OK.toString();
+ private final String statusError = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString();
+ private final String statusSent = "SENT";
+ String json = "{\"operational-environment-status\" : \"INACTIVE\"}";
+
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ public void checkOrUpdateOverallStatusTest_Ok() throws Exception {
+
+ // two entries, both status Ok & retry 0
+ OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
+ serviceModelDb.setRequestId(requestIdOrig);
+ serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelDb.setWorkloadContext(workloadContext);
+ serviceModelDb.setRecoveryAction(recoveryActionRetry);
+ serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelDb.setRetryCount(retryCountZero);
+ serviceModelDb.setServiceModelVersionDistrStatus(statusOk);
+ serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
+
+ serviceModelDb.setRequestId(requestIdOrig);
+ serviceModelDb.setServiceModelVersionId(serviceModelVersionId1);
+ serviceModelDb.setWorkloadContext(workloadContext);
+ serviceModelDb.setRecoveryAction(recoveryActionRetry);
+ serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelDb.setRetryCount(retryCountZero);
+ serviceModelDb.setServiceModelVersionDistrStatus(statusOk);
+ serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
+
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId(requestIdOrig);
+ iar.setRequestStatus("PENDING");
+
+ wireMockServer.stubFor(get(urlPathEqualTo(
+ "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+
+ activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig);
+
+ // overall is success
+ }
+
+ @Test
+ public void checkOrUpdateOverallStatusTest_Error() throws JsonProcessingException {
+
+ OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
+ serviceModelDb.setRequestId(requestIdOrig);
+ serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelDb.setWorkloadContext(workloadContext);
+ serviceModelDb.setRecoveryAction(recoveryActionRetry);
+ serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelDb.setRetryCount(retryCountZero);
+ serviceModelDb.setServiceModelVersionDistrStatus(statusError);
+ serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
+ wireMockServer.stubFor(get(urlPathEqualTo(
+ "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK)));
+
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId(requestIdOrig);
+ iar.setRequestStatus("PENDING");
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
try {
activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig);
- }catch(ApiException e){
+ } catch (ApiException e) {
assertThat(e.getMessage(), startsWith("Overall Activation process is a Failure. "));
assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST);
assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR);
}
-
- }
-
- @Test
- public void checkOrUpdateOverallStatusTest_Waiting() throws Exception {
-
- OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
- serviceModelDb.setRequestId(requestIdOrig);
- serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
- serviceModelDb.setWorkloadContext(workloadContext);
- serviceModelDb.setRecoveryAction(recoveryActionRetry);
- serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
- serviceModelDb.setRetryCount(retryCountTwo);
- serviceModelDb.setServiceModelVersionDistrStatus(statusError);
- serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceModelDb))
- .withStatus(HttpStatus.SC_OK)));
-
- activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig);
- }
-
- @Test
- public void executionTest_Ok() throws Exception {
-
- OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
- serviceModelDb.setRequestId(requestIdOrig);
- serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
- serviceModelDb.setWorkloadContext(workloadContext);
- serviceModelDb.setRecoveryAction(recoveryActionRetry);
- serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
- serviceModelDb.setRetryCount(retryCountThree);
- serviceModelDb.setServiceModelVersionDistrStatus(statusSent);
- serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
- serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
-
- OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
- distributionDb.setDistributionId(sdcDistributionId);
- distributionDb.setRequestId(requestIdOrig);
- distributionDb.setOperationalEnvId(operationalEnvironmentId);
- distributionDb.setDistributionIdStatus(statusSent);
- distributionDb.setServiceModelVersionId(serviceModelVersionId);
- distributionDb.setDistributionIdErrorReason(null);
-
- // prepare distribution obj
- Distribution distribution = new Distribution();
- distribution.setStatus(Status.DISTRIBUTION_COMPLETE_OK);
- request.setDistribution(distribution);
- request.setDistributionId(sdcDistributionId);
- request.setOperationalEnvironmentId(operationalEnvironmentId);
-
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestIdOrig);
- iar.setRequestStatus("PENDING");
-
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceModelDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(distributionDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/"))
- .withRequestBody(equalTo("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"recoveryAction\":\"RETRY\",\"retryCount\":0,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/"))
- .withRequestBody(equalTo("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/operational-environment/VNF_operationalEnvironmentId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(put(urlPathEqualTo("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/operational-environment/VNF_operationalEnvironmentId"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
-
- activateVnfStatus.execute(requestId, request);
- }
-
- @Test
- public void executionTest_ERROR_Status_And_RETRY() throws Exception {
-
- OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
- serviceModelDb.setRequestId(requestIdOrig);
- serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
- serviceModelDb.setWorkloadContext(workloadContext);
- serviceModelDb.setRecoveryAction(recoveryActionRetry);
- serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
- serviceModelDb.setRetryCount(retryCountThree);
- serviceModelDb.setServiceModelVersionDistrStatus(statusError);
- serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceModelDb))
- .withStatus(HttpStatus.SC_OK)));
-
- OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
- distributionDb.setDistributionId(sdcDistributionId);
- distributionDb.setRequestId(requestIdOrig);
- distributionDb.setOperationalEnvId(operationalEnvironmentId);
- distributionDb.setDistributionIdStatus(statusError);
- distributionDb.setServiceModelVersionId(serviceModelVersionId);
- distributionDb.setDistributionIdErrorReason(null);
-
-
-
-
- // prepare new distribution obj
- Distribution distribution = new Distribution();
- distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR);
- distribution.setErrorReason("Unable to process.");
- request.setDistribution(distribution);
- request.setDistributionId(sdcDistributionId);
- request.setOperationalEnvironmentId(operationalEnvironmentId);
-
- // prepare sdc return data
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("statusCode", "202");
- jsonObject.put("message", "Success");
- jsonObject.put("distributionId", sdcDistributionId1);
-
- wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceModelDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(distributionDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/"))
- .withRequestBody(equalTo("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_ERROR\",\"distributionIdErrorReason\":\"Unable to process.\",\"createTime\":null,\"modifyTime\":null,\"handler\":{}}"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/"))
- .withRequestBody(equalTo("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":2,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
-
- activateVnfStatus.execute(requestId, request);
- }
-
- @Test
- public void executionTest_ERROR_Status_And_RETRY_And_RetryZero() throws JsonProcessingException {
-
- OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
- serviceModelDb.setRequestId(requestIdOrig);
- serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
- serviceModelDb.setWorkloadContext(workloadContext);
- serviceModelDb.setRecoveryAction(recoveryActionRetry);
- serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
- serviceModelDb.setRetryCount(retryCountZero);
- serviceModelDb.setServiceModelVersionDistrStatus(statusError);
- serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
-
- OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
- distributionDb.setDistributionId(sdcDistributionId);
- distributionDb.setRequestId(requestIdOrig);
- distributionDb.setOperationalEnvId(operationalEnvironmentId);
- distributionDb.setDistributionIdStatus(statusError);
- distributionDb.setServiceModelVersionId(serviceModelVersionId);
- distributionDb.setDistributionIdErrorReason(null);
-
-
-
- // prepare distribution obj
- Distribution distribution = new Distribution();
- distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR);
- request.setDistribution(distribution);
- request.setDistributionId(sdcDistributionId);
- request.setOperationalEnvironmentId(operationalEnvironmentId);
-
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("statusCode", "202");
- jsonObject.put("message", "Success");
- jsonObject.put("distributionId", sdcDistributionId);
-
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestIdOrig);
- iar.setRequestStatus("PENDING");
-
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceModelDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(distributionDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED)));
-
- wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/"))
- .withRequestBody(equalTo("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":2,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"handler\":{}}"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
-
+
+ }
+
+ @Test
+ public void checkOrUpdateOverallStatusTest_Waiting() throws Exception {
+
+ OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
+ serviceModelDb.setRequestId(requestIdOrig);
+ serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelDb.setWorkloadContext(workloadContext);
+ serviceModelDb.setRecoveryAction(recoveryActionRetry);
+ serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelDb.setRetryCount(retryCountTwo);
+ serviceModelDb.setServiceModelVersionDistrStatus(statusError);
+ serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
+ wireMockServer.stubFor(get(urlPathEqualTo(
+ "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK)));
+
+ activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig);
+ }
+
+ @Test
+ public void executionTest_Ok() throws Exception {
+
+ OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
+ serviceModelDb.setRequestId(requestIdOrig);
+ serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelDb.setWorkloadContext(workloadContext);
+ serviceModelDb.setRecoveryAction(recoveryActionRetry);
+ serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelDb.setRetryCount(retryCountThree);
+ serviceModelDb.setServiceModelVersionDistrStatus(statusSent);
+ serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
+
+ OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
+ distributionDb.setDistributionId(sdcDistributionId);
+ distributionDb.setRequestId(requestIdOrig);
+ distributionDb.setOperationalEnvId(operationalEnvironmentId);
+ distributionDb.setDistributionIdStatus(statusSent);
+ distributionDb.setServiceModelVersionId(serviceModelVersionId);
+ distributionDb.setDistributionIdErrorReason(null);
+
+ // prepare distribution obj
+ Distribution distribution = new Distribution();
+ distribution.setStatus(Status.DISTRIBUTION_COMPLETE_OK);
+ request.setDistribution(distribution);
+ request.setDistributionId(sdcDistributionId);
+ request.setOperationalEnvironmentId(operationalEnvironmentId);
+
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId(requestIdOrig);
+ iar.setRequestStatus("PENDING");
+
+ wireMockServer.stubFor(get(urlPathEqualTo(
+ "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo(
+ "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"recoveryAction\":\"RETRY\",\"retryCount\":0,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(equalTo(
+ "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/aai/" + AAIVersion.LATEST
+ + "/cloud-infrastructure/operational-environments/operational-environment/VNF_operationalEnvironmentId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json)
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(put(urlPathEqualTo("/aai/" + AAIVersion.LATEST
+ + "/cloud-infrastructure/operational-environments/operational-environment/VNF_operationalEnvironmentId"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ activateVnfStatus.execute(requestId, request);
+ }
+
+ @Test
+ public void executionTest_ERROR_Status_And_RETRY() throws Exception {
+
+ OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
+ serviceModelDb.setRequestId(requestIdOrig);
+ serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelDb.setWorkloadContext(workloadContext);
+ serviceModelDb.setRecoveryAction(recoveryActionRetry);
+ serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelDb.setRetryCount(retryCountThree);
+ serviceModelDb.setServiceModelVersionDistrStatus(statusError);
+ serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
+ wireMockServer.stubFor(get(urlPathEqualTo(
+ "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK)));
+
+ OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
+ distributionDb.setDistributionId(sdcDistributionId);
+ distributionDb.setRequestId(requestIdOrig);
+ distributionDb.setOperationalEnvId(operationalEnvironmentId);
+ distributionDb.setDistributionIdStatus(statusError);
+ distributionDb.setServiceModelVersionId(serviceModelVersionId);
+ distributionDb.setDistributionIdErrorReason(null);
+
+
+
+ // prepare new distribution obj
+ Distribution distribution = new Distribution();
+ distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR);
+ distribution.setErrorReason("Unable to process.");
+ request.setDistribution(distribution);
+ request.setDistributionId(sdcDistributionId);
+ request.setOperationalEnvironmentId(operationalEnvironmentId);
+
+ // prepare sdc return data
+ JSONObject jsonObject = new JSONObject();
+ jsonObject.put("statusCode", "202");
+ jsonObject.put("message", "Success");
+ jsonObject.put("distributionId", sdcDistributionId1);
+
+ wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString())
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(get(urlPathEqualTo(
+ "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(equalTo(
+ "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_ERROR\",\"distributionIdErrorReason\":\"Unable to process.\",\"createTime\":null,\"modifyTime\":null,\"handler\":{}}"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo(
+ "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":2,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json)
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(
+ put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ activateVnfStatus.execute(requestId, request);
+ }
+
+ @Test
+ public void executionTest_ERROR_Status_And_RETRY_And_RetryZero() throws JsonProcessingException {
+
+ OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
+ serviceModelDb.setRequestId(requestIdOrig);
+ serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelDb.setWorkloadContext(workloadContext);
+ serviceModelDb.setRecoveryAction(recoveryActionRetry);
+ serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelDb.setRetryCount(retryCountZero);
+ serviceModelDb.setServiceModelVersionDistrStatus(statusError);
+ serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
+
+ OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
+ distributionDb.setDistributionId(sdcDistributionId);
+ distributionDb.setRequestId(requestIdOrig);
+ distributionDb.setOperationalEnvId(operationalEnvironmentId);
+ distributionDb.setDistributionIdStatus(statusError);
+ distributionDb.setServiceModelVersionId(serviceModelVersionId);
+ distributionDb.setDistributionIdErrorReason(null);
+
+
+
+ // prepare distribution obj
+ Distribution distribution = new Distribution();
+ distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR);
+ request.setDistribution(distribution);
+ request.setDistributionId(sdcDistributionId);
+ request.setOperationalEnvironmentId(operationalEnvironmentId);
+
+ JSONObject jsonObject = new JSONObject();
+ jsonObject.put("statusCode", "202");
+ jsonObject.put("message", "Success");
+ jsonObject.put("distributionId", sdcDistributionId);
+
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId(requestIdOrig);
+ iar.setRequestStatus("PENDING");
+
+ wireMockServer.stubFor(get(urlPathEqualTo(
+ "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString())
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo(
+ "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":2,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"handler\":{}}"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json)
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(
+ put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
try {
activateVnfStatus.execute(requestId, request);
- }catch(ApiException e){
+ } catch (ApiException e) {
assertThat(e.getMessage(), startsWith("Overall Activation process is a Failure. "));
assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST);
assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR);
}
-
- }
-
- @Test
- public void executionTest_ERROR_Status_And_RETRY_And_ErrorSdc() throws JsonProcessingException {
-
- OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
- serviceModelDb.setRequestId(requestIdOrig);
- serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
- serviceModelDb.setWorkloadContext(workloadContext);
- serviceModelDb.setRecoveryAction(recoveryActionRetry);
- serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
- serviceModelDb.setRetryCount(retryCountThree);
- serviceModelDb.setServiceModelVersionDistrStatus(statusError);
- serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
-
- OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
- distributionDb.setDistributionId(sdcDistributionId);
- distributionDb.setRequestId(requestIdOrig);
- distributionDb.setOperationalEnvId(operationalEnvironmentId);
- distributionDb.setDistributionIdStatus(statusError);
- distributionDb.setServiceModelVersionId(serviceModelVersionId);
- distributionDb.setDistributionIdErrorReason(null);
-
- // prepare distribution obj
- Distribution distribution = new Distribution();
- distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR);
- distribution.setErrorReason("Unable to process.");
- request.setDistribution(distribution);
- request.setDistributionId(sdcDistributionId);
- request.setOperationalEnvironmentId(operationalEnvironmentId);
-
- // ERROR in sdc
- JSONObject jsonMessages = new JSONObject();
- jsonMessages.put("statusCode", "409");
- jsonMessages.put("message", "Undefined Error Message!");
- jsonMessages.put("messageId", "SVC4675");
- jsonMessages.put("text", "Error: Service state is invalid for this action.");
- JSONObject jsonServException = new JSONObject();
- jsonServException.put("serviceException", jsonMessages);
- JSONObject jsonErrorRequest = new JSONObject();
- jsonErrorRequest.put("requestError", jsonServException);
-
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestIdOrig);
- iar.setRequestStatus("PENDING");
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceModelDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(distributionDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
- .withRequestBody(containing("operationalEnvId\":\"VNF_operationalEnvironmentId\""))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonMessages.toString()).withStatus(HttpStatus.SC_CONFLICT)));
-
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
-
- try {
+
+ }
+
+ @Test
+ public void executionTest_ERROR_Status_And_RETRY_And_ErrorSdc() throws JsonProcessingException {
+
+ OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
+ serviceModelDb.setRequestId(requestIdOrig);
+ serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelDb.setWorkloadContext(workloadContext);
+ serviceModelDb.setRecoveryAction(recoveryActionRetry);
+ serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelDb.setRetryCount(retryCountThree);
+ serviceModelDb.setServiceModelVersionDistrStatus(statusError);
+ serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
+
+ OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
+ distributionDb.setDistributionId(sdcDistributionId);
+ distributionDb.setRequestId(requestIdOrig);
+ distributionDb.setOperationalEnvId(operationalEnvironmentId);
+ distributionDb.setDistributionIdStatus(statusError);
+ distributionDb.setServiceModelVersionId(serviceModelVersionId);
+ distributionDb.setDistributionIdErrorReason(null);
+
+ // prepare distribution obj
+ Distribution distribution = new Distribution();
+ distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR);
+ distribution.setErrorReason("Unable to process.");
+ request.setDistribution(distribution);
+ request.setDistributionId(sdcDistributionId);
+ request.setOperationalEnvironmentId(operationalEnvironmentId);
+
+ // ERROR in sdc
+ JSONObject jsonMessages = new JSONObject();
+ jsonMessages.put("statusCode", "409");
+ jsonMessages.put("message", "Undefined Error Message!");
+ jsonMessages.put("messageId", "SVC4675");
+ jsonMessages.put("text", "Error: Service state is invalid for this action.");
+ JSONObject jsonServException = new JSONObject();
+ jsonServException.put("serviceException", jsonMessages);
+ JSONObject jsonErrorRequest = new JSONObject();
+ jsonErrorRequest.put("requestError", jsonServException);
+
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId(requestIdOrig);
+ iar.setRequestStatus("PENDING");
+ wireMockServer.stubFor(get(urlPathEqualTo(
+ "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
+ .withRequestBody(containing("operationalEnvId\":\"VNF_operationalEnvironmentId\""))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonMessages.toString())
+ .withStatus(HttpStatus.SC_CONFLICT)));
+
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json)
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(
+ put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ try {
activateVnfStatus.execute(requestId, request);
- }catch(ApiException e){
+ } catch (ApiException e) {
assertThat(e.getMessage(), startsWith("Failure calling SDC: statusCode: "));
assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST);
assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR);
}
- }
-
- @Test
- public void executionTest_ERROR_Status_And_SKIP() throws Exception {
-
- OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
- serviceModelDb.setRequestId(requestIdOrig);
- serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
- serviceModelDb.setWorkloadContext(workloadContext);
- serviceModelDb.setRecoveryAction(recoveryActionSkip);
- serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
- serviceModelDb.setRetryCount(retryCountThree);
- serviceModelDb.setServiceModelVersionDistrStatus(statusError);
- serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
-
- OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
- distributionDb.setDistributionId(sdcDistributionId);
- distributionDb.setRequestId(requestIdOrig);
- distributionDb.setOperationalEnvId(operationalEnvironmentId);
- distributionDb.setDistributionIdStatus(statusError);
- distributionDb.setServiceModelVersionId(serviceModelVersionId);
- distributionDb.setDistributionIdErrorReason(null);
-
- // prepare distribution obj
- OperationalEnvDistributionStatus distributionStatus = new OperationalEnvDistributionStatus(sdcDistributionId,operationalEnvironmentId,serviceModelVersionId);
- distributionStatus.setDistributionIdStatus(Status.DISTRIBUTION_COMPLETE_ERROR.name());
-
- Distribution distribution = new Distribution();
- distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR);
- request.setDistribution(distribution);
- request.setDistributionId(sdcDistributionId);
- request.setOperationalEnvironmentId(operationalEnvironmentId);
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestIdOrig);
- iar.setRequestStatus("PENDING");
-
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceModelDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(distributionDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/"))
- .withRequestBody(equalTo("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"recoveryAction\":\"SKIP\",\"retryCount\":0,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/"))
- .withRequestBody(equalTo("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
-
- activateVnfStatus.execute(requestId, request);
-
- }
-
- @Test
- public void executionTest_ERROR_Status_And_ABORT() throws JsonProcessingException {
-
- OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
- serviceModelDb.setRequestId(requestIdOrig);
- serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
- serviceModelDb.setWorkloadContext(workloadContext);
- serviceModelDb.setRecoveryAction(recoveryActionAbort);
- serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
- serviceModelDb.setRetryCount(retryCountThree);
- serviceModelDb.setServiceModelVersionDistrStatus(statusError);
- serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
-
- OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
- distributionDb.setDistributionId(sdcDistributionId);
- distributionDb.setRequestId(requestIdOrig);
- distributionDb.setOperationalEnvId(operationalEnvironmentId);
- distributionDb.setDistributionIdStatus(statusError);
- distributionDb.setServiceModelVersionId(serviceModelVersionId);
- distributionDb.setDistributionIdErrorReason(null);
-
-
-
- // prepare distribution obj
- Distribution distribution = new Distribution();
- distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR);
- request.setDistribution(distribution);
- request.setDistributionId(sdcDistributionId);
- request.setOperationalEnvironmentId(operationalEnvironmentId);
-
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestIdOrig);
- iar.setRequestStatus("PENDING");
-
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(serviceModelDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(distributionDb))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/"))
- .withRequestBody(containing("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_ERROR\""))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/"))
- .withRequestBody(containing("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_ERROR\""))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
-
+ }
+
+ @Test
+ public void executionTest_ERROR_Status_And_SKIP() throws Exception {
+
+ OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
+ serviceModelDb.setRequestId(requestIdOrig);
+ serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelDb.setWorkloadContext(workloadContext);
+ serviceModelDb.setRecoveryAction(recoveryActionSkip);
+ serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelDb.setRetryCount(retryCountThree);
+ serviceModelDb.setServiceModelVersionDistrStatus(statusError);
+ serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
+
+ OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
+ distributionDb.setDistributionId(sdcDistributionId);
+ distributionDb.setRequestId(requestIdOrig);
+ distributionDb.setOperationalEnvId(operationalEnvironmentId);
+ distributionDb.setDistributionIdStatus(statusError);
+ distributionDb.setServiceModelVersionId(serviceModelVersionId);
+ distributionDb.setDistributionIdErrorReason(null);
+
+ // prepare distribution obj
+ OperationalEnvDistributionStatus distributionStatus = new OperationalEnvDistributionStatus(sdcDistributionId,
+ operationalEnvironmentId, serviceModelVersionId);
+ distributionStatus.setDistributionIdStatus(Status.DISTRIBUTION_COMPLETE_ERROR.name());
+
+ Distribution distribution = new Distribution();
+ distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR);
+ request.setDistribution(distribution);
+ request.setDistributionId(sdcDistributionId);
+ request.setOperationalEnvironmentId(operationalEnvironmentId);
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId(requestIdOrig);
+ iar.setRequestStatus("PENDING");
+
+ wireMockServer.stubFor(get(urlPathEqualTo(
+ "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo(
+ "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"recoveryAction\":\"SKIP\",\"retryCount\":0,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(equalTo(
+ "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json)
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(
+ put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ activateVnfStatus.execute(requestId, request);
+
+ }
+
+ @Test
+ public void executionTest_ERROR_Status_And_ABORT() throws JsonProcessingException {
+
+ OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
+ serviceModelDb.setRequestId(requestIdOrig);
+ serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelDb.setWorkloadContext(workloadContext);
+ serviceModelDb.setRecoveryAction(recoveryActionAbort);
+ serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelDb.setRetryCount(retryCountThree);
+ serviceModelDb.setServiceModelVersionDistrStatus(statusError);
+ serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId);
+
+ OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
+ distributionDb.setDistributionId(sdcDistributionId);
+ distributionDb.setRequestId(requestIdOrig);
+ distributionDb.setOperationalEnvId(operationalEnvironmentId);
+ distributionDb.setDistributionIdStatus(statusError);
+ distributionDb.setServiceModelVersionId(serviceModelVersionId);
+ distributionDb.setDistributionIdErrorReason(null);
+
+
+
+ // prepare distribution obj
+ Distribution distribution = new Distribution();
+ distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR);
+ request.setDistribution(distribution);
+ request.setDistributionId(sdcDistributionId);
+ request.setOperationalEnvironmentId(operationalEnvironmentId);
+
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId(requestIdOrig);
+ iar.setRequestStatus("PENDING");
+
+ wireMockServer.stubFor(get(urlPathEqualTo(
+ "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(containing(
+ "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_ERROR\""))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(containing(
+ "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_ERROR\""))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json)
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(
+ put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
try {
activateVnfStatus.execute(requestId, request);
- }catch(ApiException e) {
- assertThat(e.getMessage(), startsWith("Overall Activation process is a Failure. "));
- assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST);
- assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR);
- }
-
- }
-
- @Test
- @Ignore
- public void callSDClientForRetryTest_202() throws Exception {
- OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
- serviceModelDb.setRequestId(requestIdOrig);
- serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
- serviceModelDb.setWorkloadContext(workloadContext);
- serviceModelDb.setRecoveryAction(recoveryActionRetry);
- serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
- serviceModelDb.setRetryCount(retryCountThree);
- serviceModelDb.setServiceModelVersionDistrStatus(statusSent);
-
- OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
- distributionDb.setDistributionId(sdcDistributionId);
- distributionDb.setRequestId(requestIdOrig);
- distributionDb.setOperationalEnvId(operationalEnvironmentId);
- distributionDb.setDistributionIdStatus(statusSent);
- distributionDb.setServiceModelVersionId(serviceModelVersionId);
- distributionDb.setDistributionIdErrorReason(null);
-
-
-
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("statusCode", "202");
- jsonObject.put("message", "Success");
- jsonObject.put("distributionId", sdcDistributionId1);
-
- // prepare distribution obj
- Distribution distribution = new Distribution();
- distribution.setStatus(Status.DISTRIBUTION_COMPLETE_OK);
- request.setDistribution(distribution);
- request.setDistributionId(sdcDistributionId);
- request.setOperationalEnvironmentId(operationalEnvironmentId);
-
- wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED)));
-
- JSONObject jsonResponse = activateVnfStatus.callSDClientForRetry(distributionDb, serviceModelDb, distribution);
-
- assertEquals("TEST_distributionId1", jsonResponse.get("distributionId"));
- assertEquals("Success", jsonResponse.get("message"));
- assertEquals("202", jsonResponse.get("statusCode"));
-
- }
+ } catch (ApiException e) {
+ assertThat(e.getMessage(), startsWith("Overall Activation process is a Failure. "));
+ assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST);
+ assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR);
+ }
+
+ }
+
+ @Test
+ @Ignore
+ public void callSDClientForRetryTest_202() throws Exception {
+ OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus();
+ serviceModelDb.setRequestId(requestIdOrig);
+ serviceModelDb.setServiceModelVersionId(serviceModelVersionId);
+ serviceModelDb.setWorkloadContext(workloadContext);
+ serviceModelDb.setRecoveryAction(recoveryActionRetry);
+ serviceModelDb.setOperationalEnvId(operationalEnvironmentId);
+ serviceModelDb.setRetryCount(retryCountThree);
+ serviceModelDb.setServiceModelVersionDistrStatus(statusSent);
+
+ OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus();
+ distributionDb.setDistributionId(sdcDistributionId);
+ distributionDb.setRequestId(requestIdOrig);
+ distributionDb.setOperationalEnvId(operationalEnvironmentId);
+ distributionDb.setDistributionIdStatus(statusSent);
+ distributionDb.setServiceModelVersionId(serviceModelVersionId);
+ distributionDb.setDistributionIdErrorReason(null);
+
+
+
+ JSONObject jsonObject = new JSONObject();
+ jsonObject.put("statusCode", "202");
+ jsonObject.put("message", "Success");
+ jsonObject.put("distributionId", sdcDistributionId1);
+
+ // prepare distribution obj
+ Distribution distribution = new Distribution();
+ distribution.setStatus(Status.DISTRIBUTION_COMPLETE_OK);
+ request.setDistribution(distribution);
+ request.setDistributionId(sdcDistributionId);
+ request.setOperationalEnvironmentId(operationalEnvironmentId);
+
+ wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString())
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ JSONObject jsonResponse = activateVnfStatus.callSDClientForRetry(distributionDb, serviceModelDb, distribution);
+
+ assertEquals("TEST_distributionId1", jsonResponse.get("distributionId"));
+ assertEquals("Success", jsonResponse.get("message"));
+ assertEquals("202", jsonResponse.get("statusCode"));
+
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java
index 22993b17cf..3114f91096 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java
@@ -29,12 +29,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertThat;
-
import java.util.UUID;
-
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
-
import org.apache.http.HttpStatus;
import org.junit.Test;
import org.onap.so.apihandler.common.ErrorNumbers;
@@ -52,90 +49,93 @@ import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class CreateEcompOperationalEnvironmentTest extends BaseTest{
-
- @Autowired
- private CreateEcompOperationalEnvironment createEcompOpEn;
- private final ObjectMapper mapper = new ObjectMapper();
+public class CreateEcompOperationalEnvironmentTest extends BaseTest {
+
+ @Autowired
+ private CreateEcompOperationalEnvironment createEcompOpEn;
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ public CloudOrchestrationRequest getCloudOrchestrationRequest() {
+ CloudOrchestrationRequest request = new CloudOrchestrationRequest();
+ RequestDetails reqDetails = new RequestDetails();
+ RequestInfo reqInfo = new RequestInfo();
+ RequestParameters reqParams = new RequestParameters();
+ reqParams.setTenantContext("TEST");
+ reqParams.setWorkloadContext("ECOMP_TEST");
+ reqParams.setOperationalEnvironmentType(OperationalEnvironment.ECOMP);
+ reqInfo.setInstanceName("TEST_ECOMP_ENVIRONMENT");
+ reqDetails.setRequestInfo(reqInfo);
+ reqDetails.setRequestParameters(reqParams);
+ request.setRequestDetails(reqDetails);
+ request.setOperationalEnvironmentId("operationalEnvId");
+
+ return request;
+ }
+
+ @Test
+ public void testProcess() throws ApiException, JsonProcessingException {
+ wireMockServer.stubFor(
+ put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(post(urlPathMatching("/events/.*")).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
+
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId("123");
+ iar.setOperationalEnvName("myOpEnv");
+ iar.setRequestScope("create");
+ iar.setRequestStatus("PENDING");
+ iar.setRequestAction("UNKNOWN");
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/123"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")).withRequestBody(containing(
+ "{\"requestId\":\"123\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL, operationalEnvironmentId - operationalEnvId; Success Message: SUCCESSFULLY Created ECOMP OperationalEnvironment.\",\"rollbackStatusMessage\":null,\"flowStatus\":null,\"retryStatusMessage\":null,\"progress\":100"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ createEcompOpEn.execute("123", getCloudOrchestrationRequest());
+ }
+
+ @Test
+ public void testProcessException() throws JsonProcessingException {
+ wireMockServer.stubFor(
+ put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(post(urlPathMatching("/events/.*")).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND)));
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
+ ValidateException expectedException = new ValidateException.Builder("Could not publish DMaap",
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
- public CloudOrchestrationRequest getCloudOrchestrationRequest() {
- CloudOrchestrationRequest request = new CloudOrchestrationRequest();
- RequestDetails reqDetails = new RequestDetails();
- RequestInfo reqInfo = new RequestInfo();
- RequestParameters reqParams = new RequestParameters();
- reqParams.setTenantContext("TEST");
- reqParams.setWorkloadContext("ECOMP_TEST");
- reqParams.setOperationalEnvironmentType(OperationalEnvironment.ECOMP);
- reqInfo.setInstanceName("TEST_ECOMP_ENVIRONMENT");
- reqDetails.setRequestInfo(reqInfo);
- reqDetails.setRequestParameters(reqParams);
- request.setRequestDetails(reqDetails);
- request.setOperationalEnvironmentId("operationalEnvId");
-
- return request;
- }
-
- @Test
- public void testProcess() throws ApiException, JsonProcessingException {
- wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(post(urlPathMatching("/events/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
-
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId("123");
- iar.setOperationalEnvName("myOpEnv");
- iar.setRequestScope("create");
- iar.setRequestStatus("PENDING");
- iar.setRequestAction("UNKNOWN");
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/123"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
- .withRequestBody(containing("{\"requestId\":\"123\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL, operationalEnvironmentId - operationalEnvId; Success Message: SUCCESSFULLY Created ECOMP OperationalEnvironment.\",\"rollbackStatusMessage\":null,\"flowStatus\":null,\"retryStatusMessage\":null,\"progress\":100"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- createEcompOpEn.execute("123", getCloudOrchestrationRequest());
- }
-
- @Test
- public void testProcessException() throws JsonProcessingException {
- wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(post(urlPathMatching("/events/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND)));
- ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build();
- ValidateException expectedException = new ValidateException.Builder("Could not publish DMaap", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER)
- .errorInfo(errorLoggerInfo).build();
-
InfraActiveRequests iar = new InfraActiveRequests();
String uuid = UUID.randomUUID().toString();
- iar.setRequestId(uuid);
- iar.setOperationalEnvName("myOpEnv");
- iar.setRequestScope("create");
- iar.setRequestStatus("PENDING");
- iar.setRequestAction("UNKNOWN");
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+uuid))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
- .withRequestBody(containing("{\"requestId\":\""+uuid+ "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE, operationalEnvironmentId - operationalEnvId; Error message:"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
+ iar.setRequestId(uuid);
+ iar.setOperationalEnvName("myOpEnv");
+ iar.setRequestScope("create");
+ iar.setRequestStatus("PENDING");
+ iar.setRequestAction("UNKNOWN");
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + uuid))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
+ .withRequestBody(containing("{\"requestId\":\"" + uuid
+ + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE, operationalEnvironmentId - operationalEnvId; Error message:"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
- try {
+ try {
createEcompOpEn.execute(uuid, getCloudOrchestrationRequest());
- }catch(ApiException e){
+ } catch (ApiException e) {
assertThat(e, sameBeanAs((ApiException) expectedException).ignoring("cause"));
}
- }
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java
index 59a65676e2..ebed4fa16b 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java
@@ -28,15 +28,12 @@ import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.junit.Assert.assertEquals;
-
import java.io.File;
import java.nio.file.Files;
import java.util.List;
import java.util.UUID;
-
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
@@ -49,142 +46,155 @@ import org.onap.so.client.grm.beans.Property;
import org.onap.so.client.grm.beans.ServiceEndPointList;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-public class CreateVnfOperationalEnvironmentTest extends BaseTest{
-
- private CloudOrchestrationRequest request;
- private ServiceEndPointList serviceEndpoints;
- private ServiceEndPointList serviceEndpoints2;
-
- @Autowired
- private CreateVnfOperationalEnvironment createVnfOpEnv;
-
- @Before
- public void testSetUp() throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- String jsonRequest = getFileContentsAsString("__files/vnfoperenv/createVnfOperationalEnvironmentRequest.json");
- request = mapper.readValue(jsonRequest, CloudOrchestrationRequest.class);
- String jsonServiceEndpoints = getFileContentsAsString("__files/vnfoperenv/endpoints.json");
- serviceEndpoints = mapper.readValue(jsonServiceEndpoints, ServiceEndPointList.class);
- String jsonServiceEndpoints2 = getFileContentsAsString("__files/vnfoperenv/endpoints2.json");
- serviceEndpoints2 = mapper.readValue(jsonServiceEndpoints2, ServiceEndPointList.class);
- }
- @Test
- public void testGetEcompManagingEnvironmentId() throws Exception {
- createVnfOpEnv.setRequest(request);
- assertEquals("ff305d54-75b4-431b-adb2-eb6b9e5ff000", createVnfOpEnv.getEcompManagingEnvironmentId());
- }
-
- @Test
- public void testGetTenantContext() throws Exception {
- createVnfOpEnv.setRequest(request);
- assertEquals("Test", createVnfOpEnv.getTenantContext());
- }
-
- @Test
- public void testGetEnvironmentName() {
- createVnfOpEnv.setRequest(request);
- List<Property> props = serviceEndpoints.getServiceEndPointList().get(0).getProperties();
- assertEquals("DEV", createVnfOpEnv.getEnvironmentName(props));
- }
-
- @Test
- public void testGetEnvironmentNameEndpointListBeginWithUpperCase() {
- createVnfOpEnv.setRequest(request);
- List<Property> props = serviceEndpoints2.getServiceEndPointList().get(0).getProperties();
- assertEquals("DEV", createVnfOpEnv.getEnvironmentName(props));
- }
-
- @Test
- public void testBuildServiceNameForVnf() throws Exception {
- createVnfOpEnv.setRequest(request);
- assertEquals("Test.VNF_E2E-IST.Inventory", createVnfOpEnv.buildServiceNameForVnf("TEST.ECOMP_PSL.Inventory"));
- }
-
- @Test
- public void testGetSearchKey() {
- createVnfOpEnv.setRequest(request);
- OperationalEnvironment ecompEnv = new OperationalEnvironment();
- ecompEnv.setTenantContext("Test");
- ecompEnv.setWorkloadContext("ECOMPL_PSL");
- assertEquals("Test.ECOMPL_PSL.*", createVnfOpEnv.getSearchKey(ecompEnv));
- }
-
- public String getFileContentsAsString(String fileName) {
- String content = "";
- try {
- ClassLoader classLoader = this.getClass().getClassLoader();
- File file = new File(classLoader.getResource(fileName).getFile());
- content = new String(Files.readAllBytes(file.toPath()));
- }
- catch(Exception e) {
- e.printStackTrace();
- System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage());
- }
- return content;
- }
-
- @Test
- public void testExecute() throws ApiException, JsonProcessingException {
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/findRunning"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/endpoints.json").withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/add"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED)));
- String requestId = UUID.randomUUID().toString();
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestId);
- iar.setOperationalEnvName("myOpEnv");
- iar.setRequestScope("create");
- iar.setRequestStatus("PENDING");
- iar.setRequestAction("UNKNOWN");
- ObjectMapper mapper = new ObjectMapper();
- wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
- .withRequestBody(containing("{\"requestId\":\""+ requestId+"\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
- createVnfOpEnv.execute(requestId, request);
- }
-
- @Test
- public void testExecuteEndpointsListBeginWithUppercase() throws ApiException, JsonProcessingException {
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/findRunning"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/endpoints2.json").withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/add"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED)));
- String requestId = UUID.randomUUID().toString();
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestId);
- iar.setOperationalEnvName("myOpEnv");
- iar.setRequestScope("create");
- iar.setRequestStatus("PENDING");
- iar.setRequestAction("UNKNOWN");
- ObjectMapper mapper = new ObjectMapper();
- wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
- .withRequestBody(containing("{\"requestId\":\""+ requestId+"\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
-
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
- createVnfOpEnv.execute(requestId, request);
- }
+public class CreateVnfOperationalEnvironmentTest extends BaseTest {
+
+ private CloudOrchestrationRequest request;
+ private ServiceEndPointList serviceEndpoints;
+ private ServiceEndPointList serviceEndpoints2;
+
+ @Autowired
+ private CreateVnfOperationalEnvironment createVnfOpEnv;
+
+ @Before
+ public void testSetUp() throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ String jsonRequest = getFileContentsAsString("__files/vnfoperenv/createVnfOperationalEnvironmentRequest.json");
+ request = mapper.readValue(jsonRequest, CloudOrchestrationRequest.class);
+ String jsonServiceEndpoints = getFileContentsAsString("__files/vnfoperenv/endpoints.json");
+ serviceEndpoints = mapper.readValue(jsonServiceEndpoints, ServiceEndPointList.class);
+ String jsonServiceEndpoints2 = getFileContentsAsString("__files/vnfoperenv/endpoints2.json");
+ serviceEndpoints2 = mapper.readValue(jsonServiceEndpoints2, ServiceEndPointList.class);
+ }
+
+ @Test
+ public void testGetEcompManagingEnvironmentId() throws Exception {
+ createVnfOpEnv.setRequest(request);
+ assertEquals("ff305d54-75b4-431b-adb2-eb6b9e5ff000", createVnfOpEnv.getEcompManagingEnvironmentId());
+ }
+
+ @Test
+ public void testGetTenantContext() throws Exception {
+ createVnfOpEnv.setRequest(request);
+ assertEquals("Test", createVnfOpEnv.getTenantContext());
+ }
+
+ @Test
+ public void testGetEnvironmentName() {
+ createVnfOpEnv.setRequest(request);
+ List<Property> props = serviceEndpoints.getServiceEndPointList().get(0).getProperties();
+ assertEquals("DEV", createVnfOpEnv.getEnvironmentName(props));
+ }
+
+ @Test
+ public void testGetEnvironmentNameEndpointListBeginWithUpperCase() {
+ createVnfOpEnv.setRequest(request);
+ List<Property> props = serviceEndpoints2.getServiceEndPointList().get(0).getProperties();
+ assertEquals("DEV", createVnfOpEnv.getEnvironmentName(props));
+ }
+
+ @Test
+ public void testBuildServiceNameForVnf() throws Exception {
+ createVnfOpEnv.setRequest(request);
+ assertEquals("Test.VNF_E2E-IST.Inventory", createVnfOpEnv.buildServiceNameForVnf("TEST.ECOMP_PSL.Inventory"));
+ }
+
+ @Test
+ public void testGetSearchKey() {
+ createVnfOpEnv.setRequest(request);
+ OperationalEnvironment ecompEnv = new OperationalEnvironment();
+ ecompEnv.setTenantContext("Test");
+ ecompEnv.setWorkloadContext("ECOMPL_PSL");
+ assertEquals("Test.ECOMPL_PSL.*", createVnfOpEnv.getSearchKey(ecompEnv));
+ }
+
+ public String getFileContentsAsString(String fileName) {
+ String content = "";
+ try {
+ ClassLoader classLoader = this.getClass().getClassLoader();
+ File file = new File(classLoader.getResource(fileName).getFile());
+ content = new String(Files.readAllBytes(file.toPath()));
+ } catch (Exception e) {
+ e.printStackTrace();
+ System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage());
+ }
+ return content;
+ }
+
+ @Test
+ public void testExecute() throws ApiException, JsonProcessingException {
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/findRunning"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("vnfoperenv/endpoints.json").withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/add")).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(
+ put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ String requestId = UUID.randomUUID().toString();
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId(requestId);
+ iar.setOperationalEnvName("myOpEnv");
+ iar.setRequestScope("create");
+ iar.setRequestStatus("PENDING");
+ iar.setRequestAction("UNKNOWN");
+ ObjectMapper mapper = new ObjectMapper();
+ wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
+ .withRequestBody(containing("{\"requestId\":\"" + requestId
+ + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+ createVnfOpEnv.execute(requestId, request);
+ }
+
+ @Test
+ public void testExecuteEndpointsListBeginWithUppercase() throws ApiException, JsonProcessingException {
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/findRunning"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("vnfoperenv/endpoints2.json").withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/add")).willReturn(
+ aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(
+ put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ String requestId = UUID.randomUUID().toString();
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId(requestId);
+ iar.setOperationalEnvName("myOpEnv");
+ iar.setRequestScope("create");
+ iar.setRequestStatus("PENDING");
+ iar.setRequestAction("UNKNOWN");
+ ObjectMapper mapper = new ObjectMapper();
+ wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
+ .withRequestBody(containing("{\"requestId\":\"" + requestId
+ + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+ createVnfOpEnv.execute(requestId, request);
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java
index 1e4208c743..16738e9799 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java
@@ -30,10 +30,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
-
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Rule;
@@ -46,129 +44,140 @@ import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestrationRequest;
import org.onap.so.client.aai.AAIVersion;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-public class DeactivateVnfOperationalEnvironmentTest extends BaseTest{
+public class DeactivateVnfOperationalEnvironmentTest extends BaseTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
- @Autowired
- private DeactivateVnfOperationalEnvironment deactivate;
-
- private CloudOrchestrationRequest request = new CloudOrchestrationRequest();
- private String operationalEnvironmentId = "ff3514e3-5a33-55df-13ab-12abad84e7ff";
- private String requestId = "ff3514e3-5a33-55df-13ab-12abad84e7fe";
-
- private ObjectMapper mapper = new ObjectMapper();
-
- @Before
- public void init(){
- wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
- .withRequestBody(containing("{\"requestId\":\""+ requestId+"\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
- }
- @Test
- public void testDeactivateOperationalEnvironment() throws Exception {
- request.setOperationalEnvironmentId(operationalEnvironmentId);
- request.setRequestDetails(null);
-
- String json = "{\"operational-environment-status\" : \"ACTIVE\"}";
-
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
- wireMockServer.stubFor(post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED)));
-
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestId);
- iar.setOperationalEnvName("myOpEnv");
- iar.setRequestScope("create");
- iar.setRequestStatus("PENDING");
- iar.setRequestAction("UNKNOWN");
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
- deactivate.execute(requestId, request);
- }
-
- @Test
- public void testDeactivateInvalidStatus() throws Exception {
- request.setOperationalEnvironmentId(operationalEnvironmentId);
- request.setRequestDetails(null);
-
- String json = "{\"operational-environment-status\" : \"SUCCESS\"}";
-
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED)));
+ @Autowired
+ private DeactivateVnfOperationalEnvironment deactivate;
+
+ private CloudOrchestrationRequest request = new CloudOrchestrationRequest();
+ private String operationalEnvironmentId = "ff3514e3-5a33-55df-13ab-12abad84e7ff";
+ private String requestId = "ff3514e3-5a33-55df-13ab-12abad84e7fe";
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Before
+ public void init() {
+ wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
+ .withRequestBody(containing("{\"requestId\":\"" + requestId
+ + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
+ @Test
+ public void testDeactivateOperationalEnvironment() throws Exception {
+ request.setOperationalEnvironmentId(operationalEnvironmentId);
+ request.setRequestDetails(null);
+
+ String json = "{\"operational-environment-status\" : \"ACTIVE\"}";
+
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json)
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(
+ put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+ wireMockServer.stubFor(
+ post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json")
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId(requestId);
+ iar.setOperationalEnvName("myOpEnv");
+ iar.setRequestScope("create");
+ iar.setRequestStatus("PENDING");
+ iar.setRequestAction("UNKNOWN");
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+ deactivate.execute(requestId, request);
+ }
+
+ @Test
+ public void testDeactivateInvalidStatus() throws Exception {
+ request.setOperationalEnvironmentId(operationalEnvironmentId);
+ request.setRequestDetails(null);
+
+ String json = "{\"operational-environment-status\" : \"SUCCESS\"}";
+
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json)
+ .withStatus(HttpStatus.SC_ACCEPTED)));
thrown.expect(ValidateException.class);
thrown.expectMessage(startsWith("Invalid OperationalEnvironmentStatus on OperationalEnvironmentId: "));
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)));
-
+
InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestId);
- iar.setOperationalEnvName("myOpEnv");
- iar.setRequestScope("create");
- iar.setRequestStatus("PENDING");
- iar.setRequestAction("UNKNOWN");
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
- wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
- .withRequestBody(containing("{\"requestId\":\""+ requestId+"\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE"))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withStatus(HttpStatus.SC_OK)));
+ iar.setRequestId(requestId);
+ iar.setOperationalEnvName("myOpEnv");
+ iar.setRequestScope("create");
+ iar.setRequestStatus("PENDING");
+ iar.setRequestAction("UNKNOWN");
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+ wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/"))
+ .withRequestBody(containing("{\"requestId\":\"" + requestId
+ + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_OK)));
deactivate.execute(requestId, request);
- }
-
- @Test
- public void testDeactivateInactiveStatus() throws Exception {
- request.setOperationalEnvironmentId(operationalEnvironmentId);
- request.setRequestDetails(null);
-
- String json = "{\"operational-environment-status\" : \"INACTIVE\"}";
-
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED)));
-
- InfraActiveRequests iar = new InfraActiveRequests();
- iar.setRequestId(requestId);
- iar.setOperationalEnvName("myOpEnv");
- iar.setRequestScope("create");
- iar.setRequestStatus("PENDING");
- iar.setRequestAction("UNKNOWN");
- wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId))
- .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .withBody(mapper.writeValueAsString(iar))
- .withStatus(HttpStatus.SC_OK)));
-
- deactivate.execute(requestId, request);
- }
-
- @Test
- public void testDeactivateNullStatus() throws Exception {
- request.setOperationalEnvironmentId(operationalEnvironmentId);
- request.setRequestDetails(null);
-
- String json = "{\"operational-environment-status\" : \"\"}";
-
- wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
- .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED)));
+ }
+
+ @Test
+ public void testDeactivateInactiveStatus() throws Exception {
+ request.setOperationalEnvironmentId(operationalEnvironmentId);
+ request.setRequestDetails(null);
+
+ String json = "{\"operational-environment-status\" : \"INACTIVE\"}";
+
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json)
+ .withStatus(HttpStatus.SC_ACCEPTED)));
+
+ InfraActiveRequests iar = new InfraActiveRequests();
+ iar.setRequestId(requestId);
+ iar.setOperationalEnvName("myOpEnv");
+ iar.setRequestScope("create");
+ iar.setRequestStatus("PENDING");
+ iar.setRequestAction("UNKNOWN");
+ wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK)));
+
+ deactivate.execute(requestId, request);
+ }
+
+ @Test
+ public void testDeactivateNullStatus() throws Exception {
+ request.setOperationalEnvironmentId(operationalEnvironmentId);
+ request.setRequestDetails(null);
+
+ String json = "{\"operational-environment-status\" : \"\"}";
+
+ wireMockServer.stubFor(
+ get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*"))
+ .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json)
+ .withStatus(HttpStatus.SC_ACCEPTED)));
thrown.expect(ValidateException.class);
thrown.expectMessage(startsWith("OperationalEnvironmentStatus is null on OperationalEnvironmentId: "));
thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST)));
thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)));
deactivate.execute(requestId, request);
- }
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java
index 8236e6766f..fdc84966e6 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java
@@ -22,12 +22,9 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.util.List;
-
import org.junit.Test;
import org.onap.so.apihandlerinfra.BaseTest;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.filters.FilterPackageInfo;
import com.openpojo.reflection.impl.PojoClassFactory;
@@ -39,49 +36,44 @@ import com.openpojo.validation.rule.impl.SetterMustExistRule;
import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
-public class TenantIsolationBeansTest extends BaseTest{
-
- private static final int EXPECTED_CLASS_COUNT = 25;
- private static final String POJO_PACKAGE = "org.onap.so.apihandlerinfra.tenantisolationbeans";
+public class TenantIsolationBeansTest extends BaseTest {
+
+ private static final int EXPECTED_CLASS_COUNT = 25;
+ private static final String POJO_PACKAGE = "org.onap.so.apihandlerinfra.tenantisolationbeans";
+
+ @Test
+ public void ensureExpectedPojoCount() {
+ List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses(POJO_PACKAGE, new FilterPackageInfo());
+ Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size());
+ }
+
+ @Test
+ public void testPojoStructureAndBehavior() {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule())
+ .with(new SetterTester()).with(new GetterTester()).build();
+
+ validator.validate(POJO_PACKAGE, new FilterPackageInfo());
+ }
+
+ @Test
+ public void testTenantIsolationToString() {
+ TenantIsolationRequest request = new TenantIsolationRequest();
+ request.setRequestId("requestId");
+ request.setRequestScope("scope");
+ request.setRequestType("type");
+ request.setStartTime("time");
+ request.setRequestDetails(new RequestDetails());
+ request.setRequestStatus(new RequestStatus());
- @Test
- public void ensureExpectedPojoCount() {
- List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses( POJO_PACKAGE,
- new FilterPackageInfo());
- Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size());
- }
+ assertNotNull(request.toString());
+ }
- @Test
- public void testPojoStructureAndBehavior() {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new SetterMustExistRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
+ @Test
+ public void testRequestListToString() {
+ RequestList list = new RequestList();
+ list.setRequest(new Request());
+ list.setRequestStatus(new RequestStatus());
- validator.validate(POJO_PACKAGE, new FilterPackageInfo());
- }
-
- @Test
- public void testTenantIsolationToString() {
- TenantIsolationRequest request = new TenantIsolationRequest();
- request.setRequestId("requestId");
- request.setRequestScope("scope");
- request.setRequestType("type");
- request.setStartTime("time");
- request.setRequestDetails(new RequestDetails());
- request.setRequestStatus(new RequestStatus());
-
- assertNotNull(request.toString());
- }
-
- @Test
- public void testRequestListToString() {
- RequestList list = new RequestList();
- list.setRequest(new Request());
- list.setRequestStatus(new RequestStatus());
-
- assertNotNull(list.toString());
- }
+ assertNotNull(list.toString());
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java
index 90c994fce0..0ea35a5b8c 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java
@@ -21,34 +21,32 @@
package org.onap.so.apihandlerinfra.validation;
import static org.junit.Assert.assertEquals;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
-
import org.junit.Test;
import org.onap.so.apihandlerinfra.Action;
import org.onap.so.apihandlerinfra.BaseTest;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-public class CustomWorkflowValidationTest extends BaseTest{
+public class CustomWorkflowValidationTest extends BaseTest {
+
+ @Test
+ public void testCustomWorkflowValidation() throws IOException, ValidationException {
+ String requestJson = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
+ ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(),
+ Action.inPlaceSoftwareUpdate, 1, false, sir.getRequestDetails().getRequestParameters());
+ info.setRequestScope("vnf");
+
+ CustomWorkflowValidation validation = new CustomWorkflowValidation();
+ validation.validate(info);
- @Test
- public void testCustomWorkflowValidation() throws IOException, ValidationException {
- String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json")));
- ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
- ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.inPlaceSoftwareUpdate,
- 1, false, sir.getRequestDetails().getRequestParameters());
- info.setRequestScope("vnf");
-
- CustomWorkflowValidation validation = new CustomWorkflowValidation();
- validation.validate(info);
-
- assertEquals(info.getSir().getRequestDetails().getCloudConfiguration().getCloudOwner(), "att-aic");
- }
+ assertEquals(info.getSir().getRequestDetails().getCloudConfiguration().getCloudOwner(), "att-aic");
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java
index 02fd7a1aca..54da0baa92 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java
@@ -21,35 +21,33 @@
package org.onap.so.apihandlerinfra.validation;
import static org.junit.Assert.assertEquals;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
-
import org.junit.Test;
import org.onap.so.apihandlerinfra.Action;
import org.onap.so.apihandlerinfra.BaseTest;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-public class RelatedInstancesValidationTest extends BaseTest{
+public class RelatedInstancesValidationTest extends BaseTest {
+
+ @Test
+ public void testCreateVnfNetworkInstanceGroup() throws IOException, ValidationException {
+ String requestJson = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/MsoRequestTest/RelatedInstances/v7CreateVnfNetworkInstanceGroup.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
+ ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(),
+ Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters());
+ info.setRequestScope("vnf");
+ sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
+ sir.getRequestDetails().getModelInfo().setModelCustomizationName("name");
+ RelatedInstancesValidation validation = new RelatedInstancesValidation();
+ validation.validate(info);
- @Test
- public void testCreateVnfNetworkInstanceGroup() throws IOException, ValidationException {
- String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RelatedInstances/v7CreateVnfNetworkInstanceGroup.json")));
- ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
- ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance,
- 6, false, sir.getRequestDetails().getRequestParameters());
- info.setRequestScope("vnf");
- sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
- sir.getRequestDetails().getModelInfo().setModelCustomizationName("name");
- RelatedInstancesValidation validation = new RelatedInstancesValidation();
- validation.validate(info);
-
- assertEquals(info.getVnfType(), "Test/name");
- }
+ assertEquals(info.getVnfType(), "Test/name");
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java
index bd9b95dc12..4f5209d8b4 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java
@@ -22,148 +22,153 @@ package org.onap.so.apihandlerinfra.validation;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
-
import org.junit.Test;
import org.onap.so.apihandlerinfra.Action;
import org.onap.so.apihandlerinfra.BaseTest;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-public class RequestParametersValidationTest extends BaseTest{
+public class RequestParametersValidationTest extends BaseTest {
+
+ @Test
+ public void testVfModuleWithFalseALaCarte() throws IOException, ValidationException {
+ String requestJson = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
+ sir.getRequestDetails().getRequestParameters().setUsePreload(null);
+ ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(),
+ Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters());
+ info.setRequestScope("vfModule");
+ sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
+ RequestParametersValidation validation = new RequestParametersValidation();
+ validation.validate(info);
+ assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload());
+ assertFalse(info.getReqParameters().getUsePreload());
+ }
+
+ @Test
+ public void testVfModuleWithNoALaCarte() throws IOException, ValidationException {
+ String requestJson = new String(Files.readAllBytes(Paths
+ .get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersNoALaCarte.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
+ ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(),
+ Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters());
+ info.setRequestScope("vfModule");
+ sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
+ RequestParametersValidation validation = new RequestParametersValidation();
+ validation.validate(info);
+
+ assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload());
+ assertTrue(info.getReqParameters().getUsePreload());
+ }
+
+ @Test
+ public void testVfModuleWithTrueALaCarte() throws IOException, ValidationException {
+ String requestJson = new String(Files.readAllBytes(Paths
+ .get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersIsALaCarte.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
+ sir.getRequestDetails().getRequestParameters().setUsePreload(null);
+ ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(),
+ Action.createInstance, 6, true, sir.getRequestDetails().getRequestParameters());
+ info.setRequestScope("vfModule");
+ sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
+ RequestParametersValidation validation = new RequestParametersValidation();
+ validation.validate(info);
+
+ assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload());
+ assertTrue(info.getReqParameters().getUsePreload());
+ }
+
+ @Test
+ public void testVfModuleWithReqVersionBelow4() throws IOException, ValidationException {
+ String requestJson = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
+ sir.getRequestDetails().getRequestParameters().setUsePreload(null);
+ ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(),
+ Action.createInstance, 3, false, sir.getRequestDetails().getRequestParameters());
+ info.setRequestScope("vfModule");
+ sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
+ RequestParametersValidation validation = new RequestParametersValidation();
+ validation.validate(info);
+ assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload());
+ assertTrue(info.getReqParameters().getUsePreload());
+ }
+
+ @Test
+ public void testServiceWithFalseALaCarte() throws IOException, ValidationException {
+ String requestJson = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
+ sir.getRequestDetails().getRequestParameters().setUsePreload(null);
+ ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(),
+ Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters());
+ sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
+ info.setRequestScope("service");
+ RequestParametersValidation validation = new RequestParametersValidation();
+ validation.validate(info);
+ assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload());
+ assertFalse(info.getReqParameters().getUsePreload());
+ }
+
+ @Test
+ public void testServiceWithNoALaCarte() throws IOException, ValidationException {
+ String requestJson = new String(Files.readAllBytes(Paths
+ .get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersNoALaCarte.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
+ ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(),
+ Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters());
+ sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
+ sir.getRequestDetails().getRequestParameters().setSubscriptionServiceType("subscriptionServiceType");
+ info.setRequestScope("service");
+ RequestParametersValidation validation = new RequestParametersValidation();
+ validation.validate(info);
+ assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload());
+ assertFalse(info.getReqParameters().getUsePreload());
+ }
+
+ @Test
+ public void testServiceWithTrueALaCarte() throws IOException, ValidationException {
+ String requestJson = new String(Files.readAllBytes(Paths
+ .get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersIsALaCarte.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
+ sir.getRequestDetails().getRequestParameters().setUsePreload(null);
+ ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(),
+ Action.createInstance, 6, true, sir.getRequestDetails().getRequestParameters());
+ sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
+ info.setRequestScope("service");
+ RequestParametersValidation validation = new RequestParametersValidation();
+ validation.validate(info);
+ assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload());
+ assertTrue(info.getReqParameters().getUsePreload());
+ }
- @Test
- public void testVfModuleWithFalseALaCarte() throws IOException, ValidationException {
- String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json")));
- ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
- sir.getRequestDetails().getRequestParameters().setUsePreload(null);
- ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance,
- 6, false, sir.getRequestDetails().getRequestParameters());
- info.setRequestScope("vfModule");
- sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
- RequestParametersValidation validation = new RequestParametersValidation();
- validation.validate(info);
- assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload());
- assertFalse(info.getReqParameters().getUsePreload());
- }
-
- @Test
- public void testVfModuleWithNoALaCarte() throws IOException, ValidationException {
- String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersNoALaCarte.json")));
- ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
- ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance,
- 6, false, sir.getRequestDetails().getRequestParameters());
- info.setRequestScope("vfModule");
- sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
- RequestParametersValidation validation = new RequestParametersValidation();
- validation.validate(info);
-
- assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload());
- assertTrue(info.getReqParameters().getUsePreload());
- }
-
- @Test
- public void testVfModuleWithTrueALaCarte() throws IOException, ValidationException {
- String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersIsALaCarte.json")));
- ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
- sir.getRequestDetails().getRequestParameters().setUsePreload(null);
- ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance,
- 6, true, sir.getRequestDetails().getRequestParameters());
- info.setRequestScope("vfModule");
- sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
- RequestParametersValidation validation = new RequestParametersValidation();
- validation.validate(info);
-
- assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload());
- assertTrue(info.getReqParameters().getUsePreload());
- }
-
- @Test
- public void testVfModuleWithReqVersionBelow4() throws IOException, ValidationException {
- String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json")));
- ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
- sir.getRequestDetails().getRequestParameters().setUsePreload(null);
- ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance,
- 3, false, sir.getRequestDetails().getRequestParameters());
- info.setRequestScope("vfModule");
- sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
- RequestParametersValidation validation = new RequestParametersValidation();
- validation.validate(info);
- assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload());
- assertTrue(info.getReqParameters().getUsePreload());
- }
-
- @Test
- public void testServiceWithFalseALaCarte() throws IOException, ValidationException {
- String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json")));
- ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
- sir.getRequestDetails().getRequestParameters().setUsePreload(null);
- ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance,
- 6, false, sir.getRequestDetails().getRequestParameters());
- sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
- info.setRequestScope("service");
- RequestParametersValidation validation = new RequestParametersValidation();
- validation.validate(info);
- assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload());
- assertFalse(info.getReqParameters().getUsePreload());
- }
-
- @Test
- public void testServiceWithNoALaCarte() throws IOException, ValidationException {
- String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersNoALaCarte.json")));
- ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
- ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance,
- 6, false, sir.getRequestDetails().getRequestParameters());
- sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
- sir.getRequestDetails().getRequestParameters().setSubscriptionServiceType("subscriptionServiceType");
- info.setRequestScope("service");
- RequestParametersValidation validation = new RequestParametersValidation();
- validation.validate(info);
- assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload());
- assertFalse(info.getReqParameters().getUsePreload());
- }
-
- @Test
- public void testServiceWithTrueALaCarte() throws IOException, ValidationException {
- String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersIsALaCarte.json")));
- ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
- sir.getRequestDetails().getRequestParameters().setUsePreload(null);
- ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance,
- 6, true, sir.getRequestDetails().getRequestParameters());
- sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
- info.setRequestScope("service");
- RequestParametersValidation validation = new RequestParametersValidation();
- validation.validate(info);
- assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload());
- assertTrue(info.getReqParameters().getUsePreload());
- }
-
- @Test
- public void testServiceWithReqVersionBelow4() throws IOException, ValidationException {
- String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json")));
- ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
- sir.getRequestDetails().getRequestParameters().setUsePreload(null);
- ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance,
- 3, false, sir.getRequestDetails().getRequestParameters());
- sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
- info.setRequestScope("service");
- RequestParametersValidation validation = new RequestParametersValidation();
- validation.validate(info);
- assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload());
- assertTrue(info.getReqParameters().getUsePreload());
- }
+ @Test
+ public void testServiceWithReqVersionBelow4() throws IOException, ValidationException {
+ String requestJson = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
+ sir.getRequestDetails().getRequestParameters().setUsePreload(null);
+ ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(),
+ Action.createInstance, 3, false, sir.getRequestDetails().getRequestParameters());
+ sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
+ info.setRequestScope("service");
+ RequestParametersValidation validation = new RequestParametersValidation();
+ validation.validate(info);
+ assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload());
+ assertTrue(info.getReqParameters().getUsePreload());
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java
index c1c4915672..ba02254ad8 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java
@@ -24,7 +24,6 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
-
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -32,78 +31,94 @@ import org.onap.so.apihandlerinfra.Action;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.Service;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-public class UserParamsValidationTest{
-
- UserParamsValidation validation = new UserParamsValidation();
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- public ValidationInformation setupValidationInformation(String path) throws IOException{
- String jsonInput = new String(Files.readAllBytes(Paths.get(path)));
- ObjectMapper mapper = new ObjectMapper();
- ServiceInstancesRequest sir = mapper.readValue(jsonInput, ServiceInstancesRequest.class);
- ValidationInformation info = new ValidationInformation(sir, null, Action.createInstance, 7, false, sir.getRequestDetails().getRequestParameters());
- for(Map<String, Object> params : sir.getRequestDetails().getRequestParameters().getUserParams()){
- ObjectMapper obj = new ObjectMapper();
- String input = obj.writeValueAsString(params.get("service"));
- Service validate = obj.readValue(input, Service.class);
- info.setUserParams(validate);
- break;
- }
- info.setRequestInfo(sir.getRequestDetails().getRequestInfo());
- return info;
- }
-
- @Test
- public void validateModelTypeExceptionTest() throws IOException, ValidationException{
- thrown.expect(ValidationException.class);
- thrown.expectMessage("No valid modelType in userParams service modelInfo is specified");
- validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelInfoNoModelType.json"));
- }
- @Test
- public void validateInstanceNameExceptionTest() throws IOException, ValidationException{
- thrown.expect(ValidationException.class);
- thrown.expectMessage("instanceName in requestInfo does not match instanceName in userParams service");
- validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/MacroRequest.json"));
- }
- @Test
- public void validateModelTypeTest() throws ValidationException, IOException{
- thrown.expect(ValidationException.class);
- thrown.expectMessage("modelType in modelInfo does not match modelType in userParams service");
- validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelType.json"));
- }
- @Test
- public void validateModelInvariantIdTest() throws ValidationException, IOException{
- thrown.expect(ValidationException.class);
- thrown.expectMessage("modelInvariantId in modelInfo does not match modelInvariantId in userParams service");
- validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelInvariantId.json"));
- }
- @Test
- public void validateModelVersionIdTest() throws ValidationException, IOException{
- thrown.expect(ValidationException.class);
- thrown.expectMessage("modelVersionId in modelInfo does not match modelVersionId in userParams service");
- validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelVersionId.json"));
- }
- @Test
- public void validateModelNameTest() throws ValidationException, IOException{
- thrown.expect(ValidationException.class);
- thrown.expectMessage("modelName in modelInfo does not match modelName in userParams service");
- validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelName.json"));
- }
- @Test
- public void validateModelVersionTest() throws ValidationException, IOException{
- thrown.expect(ValidationException.class);
- thrown.expectMessage("modelVersion in modelInfo does not match modelVersion in userParams service");
- validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelVersion.json"));
- }
- @Test
- public void validateModelCustomizationIdTest() throws ValidationException, IOException{
- thrown.expect(ValidationException.class);
- thrown.expectMessage("modelCustomizationId in modelInfo does not match modelCustomizationId in userParams service");
- validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelCustomizationId.json"));
- }
-} \ No newline at end of file
+public class UserParamsValidationTest {
+
+ UserParamsValidation validation = new UserParamsValidation();
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ public ValidationInformation setupValidationInformation(String path) throws IOException {
+ String jsonInput = new String(Files.readAllBytes(Paths.get(path)));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(jsonInput, ServiceInstancesRequest.class);
+ ValidationInformation info = new ValidationInformation(sir, null, Action.createInstance, 7, false,
+ sir.getRequestDetails().getRequestParameters());
+ for (Map<String, Object> params : sir.getRequestDetails().getRequestParameters().getUserParams()) {
+ ObjectMapper obj = new ObjectMapper();
+ String input = obj.writeValueAsString(params.get("service"));
+ Service validate = obj.readValue(input, Service.class);
+ info.setUserParams(validate);
+ break;
+ }
+ info.setRequestInfo(sir.getRequestDetails().getRequestInfo());
+ return info;
+ }
+
+ @Test
+ public void validateModelTypeExceptionTest() throws IOException, ValidationException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid modelType in userParams service modelInfo is specified");
+ validation.validate(setupValidationInformation(
+ "src/test/resources/Validation/UserParamsValidation/ModelInfoNoModelType.json"));
+ }
+
+ @Test
+ public void validateInstanceNameExceptionTest() throws IOException, ValidationException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("instanceName in requestInfo does not match instanceName in userParams service");
+ validation.validate(
+ setupValidationInformation("src/test/resources/Validation/UserParamsValidation/MacroRequest.json"));
+ }
+
+ @Test
+ public void validateModelTypeTest() throws ValidationException, IOException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("modelType in modelInfo does not match modelType in userParams service");
+ validation.validate(
+ setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelType.json"));
+ }
+
+ @Test
+ public void validateModelInvariantIdTest() throws ValidationException, IOException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("modelInvariantId in modelInfo does not match modelInvariantId in userParams service");
+ validation.validate(
+ setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelInvariantId.json"));
+ }
+
+ @Test
+ public void validateModelVersionIdTest() throws ValidationException, IOException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("modelVersionId in modelInfo does not match modelVersionId in userParams service");
+ validation.validate(
+ setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelVersionId.json"));
+ }
+
+ @Test
+ public void validateModelNameTest() throws ValidationException, IOException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("modelName in modelInfo does not match modelName in userParams service");
+ validation.validate(
+ setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelName.json"));
+ }
+
+ @Test
+ public void validateModelVersionTest() throws ValidationException, IOException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("modelVersion in modelInfo does not match modelVersion in userParams service");
+ validation.validate(
+ setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelVersion.json"));
+ }
+
+ @Test
+ public void validateModelCustomizationIdTest() throws ValidationException, IOException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage(
+ "modelCustomizationId in modelInfo does not match modelCustomizationId in userParams service");
+ validation.validate(setupValidationInformation(
+ "src/test/resources/Validation/UserParamsValidation/ModelCustomizationId.json"));
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationBeansTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationBeansTest.java
index c469a56e48..e208a38f47 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationBeansTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationBeansTest.java
@@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.workflowspecificationbeans;
import org.junit.Test;
import org.onap.so.apihandlerinfra.BaseTest;
-
import com.openpojo.reflection.filters.FilterPackageInfo;
import com.openpojo.validation.Validator;
import com.openpojo.validation.ValidatorBuilder;
@@ -30,11 +29,11 @@ import com.openpojo.validation.rule.impl.SetterMustExistRule;
import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
-public class WorkflowSpecificationBeansTest extends BaseTest{
- @Test
- public void validateGettersAndSetters() {
- Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule())
- .with(new SetterTester(), new GetterTester()).build();
- validator.validate("org.onap.so.apihandlerinfra.tasksbeans", new FilterPackageInfo());
- }
+public class WorkflowSpecificationBeansTest extends BaseTest {
+ @Test
+ public void validateGettersAndSetters() {
+ Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule())
+ .with(new SetterTester(), new GetterTester()).build();
+ validator.validate("org.onap.so.apihandlerinfra.tasksbeans", new FilterPackageInfo());
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java
index 580252ae73..f178a3c0cb 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java
@@ -30,14 +30,11 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
-
import java.io.File;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
-
import javax.ws.rs.core.MediaType;
-
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
@@ -51,119 +48,110 @@ import org.onap.so.client.grm.beans.ServiceEndPointLookupRequest;
import org.onap.so.client.grm.beans.ServiceEndPointRequest;
import org.onap.so.client.grm.exceptions.GRMClientCallFailed;
import org.slf4j.MDC;
-
import ch.qos.logback.classic.spi.ILoggingEvent;
-public class GRMClientTest extends BaseTest{
-
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- private static final String uuidRegex = "(?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-5][0-9a-f]{3}-?[089ab][0-9a-f]{3}-?[0-9a-f]{12}$";
-
- @BeforeClass
- public static void setUp() throws Exception {
- System.setProperty("mso.config.path", "src/test/resources");
- }
-
- @Test
- public void testFind() throws Exception {
+public class GRMClientTest extends BaseTest {
+
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ private static final String uuidRegex =
+ "(?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-5][0-9a-f]{3}-?[089ab][0-9a-f]{3}-?[0-9a-f]{12}$";
+
+ @BeforeClass
+ public static void setUp() throws Exception {
+ System.setProperty("mso.config.path", "src/test/resources");
+ }
+
+ @Test
+ public void testFind() throws Exception {
TestAppender.events.clear();
- String endpoints = getFileContentsAsString("__files/grm/endpoints.json");
- wireMockServer.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning"))
- .willReturn(aResponse()
- .withStatus(200)
- .withHeader("Content-Type", MediaType.APPLICATION_JSON)
- .withBody(endpoints)));
-
- MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, "/test");
- GRMClient client = new GRMClient();
- ServiceEndPointList sel = client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST");
- List<ServiceEndPoint> list = sel.getServiceEndPointList();
- assertEquals(3, list.size());
-
- boolean foundInvoke = false;
- boolean foundInvokeReturn = false;
- for(ILoggingEvent logEvent : TestAppender.events)
- if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging") &&
- logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE")
- ){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+ String endpoints = getFileContentsAsString("__files/grm/endpoints.json");
+ wireMockServer
+ .stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")).willReturn(aResponse()
+ .withStatus(200).withHeader("Content-Type", MediaType.APPLICATION_JSON).withBody(endpoints)));
+
+ MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, "/test");
+ GRMClient client = new GRMClient();
+ ServiceEndPointList sel = client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST");
+ List<ServiceEndPoint> list = sel.getServiceEndPointList();
+ assertEquals(3, list.size());
+
+ boolean foundInvoke = false;
+ boolean foundInvokeReturn = false;
+ for (ILoggingEvent logEvent : TestAppender.events)
+ if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging")
+ && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID));
- assertEquals("GRM",mdc.get("TargetEntity"));
- assertEquals("INPROGRESS",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
- foundInvoke=true;
- }else if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging") &&
- logEvent.getMarker()!= null && logEvent.getMarker().getName().equals("INVOKE_RETURN")){
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
+ assertEquals("GRM", mdc.get("TargetEntity"));
+ assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ foundInvoke = true;
+ } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging")
+ && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE_RETURN")) {
+ Map<String, String> mdc = logEvent.getMDCPropertyMap();
assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID));
- assertEquals("200",mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE));
- assertEquals("COMPLETED",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
- foundInvokeReturn=true;
+ assertEquals("200", mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE));
+ assertEquals("COMPLETED", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ foundInvokeReturn = true;
}
-
- if(!foundInvoke)
+
+ if (!foundInvoke)
fail("INVOKE Marker not found");
-
- if(!foundInvokeReturn)
+
+ if (!foundInvokeReturn)
fail("INVOKE RETURN Marker not found");
-
- wireMockServer.verify(postRequestedFor(urlEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning"))
+
+ wireMockServer.verify(postRequestedFor(urlEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning"))
.withHeader(ONAPLogConstants.Headers.INVOCATION_ID.toString(), matching(uuidRegex))
- .withHeader(ONAPLogConstants.Headers.REQUEST_ID.toString(), matching(uuidRegex))
- .withHeader(ONAPLogConstants.Headers.PARTNER_NAME.toString(), equalTo("SO")));
+ .withHeader(ONAPLogConstants.Headers.REQUEST_ID.toString(), matching(uuidRegex))
+ .withHeader(ONAPLogConstants.Headers.PARTNER_NAME.toString(), equalTo("SO")));
TestAppender.events.clear();
- }
-
- @Test
- public void testFindFail() throws Exception {
- wireMockServer.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning"))
- .willReturn(aResponse()
- .withStatus(400)
- .withHeader("Content-Type", MediaType.APPLICATION_JSON)
- .withBody("")));
-
- GRMClient client = new GRMClient();
- thrown.expect(GRMClientCallFailed.class);
- client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST");
- }
-
- @Test
- public void testAddFail() throws Exception {
- wireMockServer.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/add"))
- .willReturn(aResponse()
- .withStatus(404)
- .withHeader("Content-Type", MediaType.APPLICATION_JSON)
- .withBody("test")));
- ServiceEndPointRequest request = new ServiceEndPointRequest();
- GRMClient client = new GRMClient();
- thrown.expect(GRMClientCallFailed.class);
- client.addServiceEndPoint(request);
- }
-
- @Test
- public void testBuildServiceEndPointLookupRequest() {
- GRMClient client = new GRMClient();
- ServiceEndPointLookupRequest request = client.buildServiceEndPointlookupRequest("TEST.ECOMP_PSL.Inventory", 1, "DEV");
- assertEquals("TEST.ECOMP_PSL.Inventory", request.getServiceEndPoint().getName());
- assertEquals(Integer.valueOf(1), Integer.valueOf(request.getServiceEndPoint().getVersion().getMajor()));
- assertEquals("DEV", request.getEnv());
-
- }
-
- protected String getFileContentsAsString(String fileName) {
- String content = "";
- try {
- ClassLoader classLoader = this.getClass().getClassLoader();
- File file = new File(classLoader.getResource(fileName).getFile());
- content = new String(Files.readAllBytes(file.toPath()));
- }
- catch(Exception e) {
- e.printStackTrace();
- System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage());
- }
- return content;
- }
+ }
+
+ @Test
+ public void testFindFail() throws Exception {
+ wireMockServer.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")).willReturn(
+ aResponse().withStatus(400).withHeader("Content-Type", MediaType.APPLICATION_JSON).withBody("")));
+
+ GRMClient client = new GRMClient();
+ thrown.expect(GRMClientCallFailed.class);
+ client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST");
+ }
+
+ @Test
+ public void testAddFail() throws Exception {
+ wireMockServer.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/add")).willReturn(
+ aResponse().withStatus(404).withHeader("Content-Type", MediaType.APPLICATION_JSON).withBody("test")));
+ ServiceEndPointRequest request = new ServiceEndPointRequest();
+ GRMClient client = new GRMClient();
+ thrown.expect(GRMClientCallFailed.class);
+ client.addServiceEndPoint(request);
+ }
+
+ @Test
+ public void testBuildServiceEndPointLookupRequest() {
+ GRMClient client = new GRMClient();
+ ServiceEndPointLookupRequest request =
+ client.buildServiceEndPointlookupRequest("TEST.ECOMP_PSL.Inventory", 1, "DEV");
+ assertEquals("TEST.ECOMP_PSL.Inventory", request.getServiceEndPoint().getName());
+ assertEquals(Integer.valueOf(1), Integer.valueOf(request.getServiceEndPoint().getVersion().getMajor()));
+ assertEquals("DEV", request.getEnv());
+
+ }
+
+ protected String getFileContentsAsString(String fileName) {
+ String content = "";
+ try {
+ ClassLoader classLoader = this.getClass().getClassLoader();
+ File file = new File(classLoader.getResource(fileName).getFile());
+ content = new String(Files.readAllBytes(file.toPath()));
+ } catch (Exception e) {
+ e.printStackTrace();
+ System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage());
+ }
+ return content;
+ }
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java
index 603f9bb494..8657892c34 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java
@@ -26,6 +26,6 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;
@RepositoryRestResource(collectionResourceRel = "archivedInfraRequests", path = "archivedInfraRequests")
-public interface ArchivedInfraRequestsRepository extends JpaRepository<ArchivedInfraRequests, String> {
+public interface ArchivedInfraRequestsRepository extends JpaRepository<ArchivedInfraRequests, String> {
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java
index cd25b122be..29be0ddc00 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java
@@ -22,7 +22,6 @@ package org.onap.so.db.request.data.repository;
import java.util.Date;
import java.util.List;
-
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
@@ -30,12 +29,19 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "infraActiveRequests", path = "infraActiveRequests")
-public interface InfraActiveRequestsRepository extends JpaRepository<InfraActiveRequests, String>, InfraActiveRequestsRepositoryCustom {
-
- InfraActiveRequests findOneByRequestIdOrClientRequestId(String requestId, String clientRequestId);
- InfraActiveRequests findOneByRequestIdOrClientRequestIdAndRequestType(String requestId,String clientRequestId, String requestType);
- InfraActiveRequests findOneByRequestId(String string);
- InfraActiveRequests findOneByRequestBody(String requestBody);
- List<InfraActiveRequests> findByEndTimeLessThan(Date endTime, Pageable request);
- List<InfraActiveRequests> findByStartTimeLessThanAndEndTime(Date startTime, Date endTime, Pageable request);
+public interface InfraActiveRequestsRepository
+ extends JpaRepository<InfraActiveRequests, String>, InfraActiveRequestsRepositoryCustom {
+
+ InfraActiveRequests findOneByRequestIdOrClientRequestId(String requestId, String clientRequestId);
+
+ InfraActiveRequests findOneByRequestIdOrClientRequestIdAndRequestType(String requestId, String clientRequestId,
+ String requestType);
+
+ InfraActiveRequests findOneByRequestId(String string);
+
+ InfraActiveRequests findOneByRequestBody(String requestBody);
+
+ List<InfraActiveRequests> findByEndTimeLessThan(Date endTime, Pageable request);
+
+ List<InfraActiveRequests> findByStartTimeLessThanAndEndTime(Date startTime, Date endTime, Pageable request);
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryCustom.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryCustom.java
index 570861dfa1..47f8c6b50e 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryCustom.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryCustom.java
@@ -23,7 +23,6 @@ package org.onap.so.db.request.data.repository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.springframework.stereotype.Repository;
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java
index e3f15764d7..b3d57b0137 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java
@@ -34,7 +34,6 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
-
import javax.persistence.EntityManager;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
@@ -44,7 +43,6 @@ import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
-
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -130,9 +128,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
/*
* (non-Javadoc)
*
- * @see
- * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestFromInfraActive(java.
- * lang.String)
+ * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestFromInfraActive(java. lang.String)
*/
@Override
public InfraActiveRequests getRequestFromInfraActive(final String requestId) {
@@ -141,7 +137,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
InfraActiveRequests ar = null;
final Query query = entityManager
- .createQuery("from InfraActiveRequests where requestId = :requestId OR clientRequestId = :requestId");
+ .createQuery("from InfraActiveRequests where requestId = :requestId OR clientRequestId = :requestId");
query.setParameter(REQUEST_ID, requestId);
ar = this.getSingleResult(query);
return ar;
@@ -150,9 +146,8 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
/*
* (non-Javadoc)
*
- * @see
- * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkInstanceNameDuplicate(java.
- * util.HashMap, java.lang.String, java.lang.String)
+ * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkInstanceNameDuplicate(java. util.HashMap,
+ * java.lang.String, java.lang.String)
*/
@Override
public InfraActiveRequests checkInstanceNameDuplicate(final HashMap<String, String> instanceIdMap,
@@ -383,9 +378,8 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
/*
* (non-Javadoc)
*
- * @see
- * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestListFromInfraActive(java
- * .lang.String, java.lang.String, java.lang.String)
+ * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestListFromInfraActive(java .lang.String,
+ * java.lang.String, java.lang.String)
*/
@Override
public List<InfraActiveRequests> getRequestListFromInfraActive(final String queryAttributeName,
@@ -419,9 +413,8 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
/*
* (non-Javadoc)
*
- * @see
- * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestFromInfraActive(java.
- * lang.String, java.lang.String)
+ * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestFromInfraActive(java. lang.String,
+ * java.lang.String)
*/
@Override
public InfraActiveRequests getRequestFromInfraActive(final String requestId, final String requestType) {
@@ -431,7 +424,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
InfraActiveRequests ar = null;
final Query query = entityManager.createQuery(
- "from InfraActiveRequests where (requestId = :requestId OR clientRequestId = :requestId) and requestType = :requestType");
+ "from InfraActiveRequests where (requestId = :requestId OR clientRequestId = :requestId) and requestType = :requestType");
query.setParameter(REQUEST_ID, requestId);
query.setParameter(REQUEST_TYPE, requestType);
ar = this.getSingleResult(query);
@@ -442,9 +435,8 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
/*
* (non-Javadoc)
*
- * @see
- * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkDuplicateByVnfName(java.lang.
- * String, java.lang.String, java.lang.String)
+ * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkDuplicateByVnfName(java.lang. String,
+ * java.lang.String, java.lang.String)
*/
@Override
public InfraActiveRequests checkDuplicateByVnfName(final String vnfName, final String action,
@@ -452,16 +444,17 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
final long startTime = System.currentTimeMillis();
logger.debug("Get infra request from DB for VNF {} and action {} and requestType {}", vnfName, action,
- requestType);
+ requestType);
InfraActiveRequests ar = null;
final Query query = entityManager.createQuery(
- "from InfraActiveRequests where vnfName = :vnfName and action = :action and (requestStatus = 'PENDING' or requestStatus = 'IN_PROGRESS' or requestStatus = 'TIMEOUT' or requestStatus = 'PENDING_MANUAL_TASK') and requestType = :requestType ORDER BY startTime DESC");
+ "from InfraActiveRequests where vnfName = :vnfName and action = :action and (requestStatus = 'PENDING' or requestStatus = 'IN_PROGRESS' or requestStatus = 'TIMEOUT' or requestStatus = 'PENDING_MANUAL_TASK') and requestType = :requestType ORDER BY startTime DESC");
query.setParameter("vnfName", vnfName);
query.setParameter("action", action);
query.setParameter(REQUEST_TYPE, requestType);
- @SuppressWarnings("unchecked") final List<InfraActiveRequests> results = query.getResultList();
+ @SuppressWarnings("unchecked")
+ final List<InfraActiveRequests> results = query.getResultList();
if (!results.isEmpty()) {
ar = results.get(0);
}
@@ -472,9 +465,8 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
/*
* (non-Javadoc)
*
- * @see
- * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkDuplicateByVnfId(java.lang.
- * String, java.lang.String, java.lang.String)
+ * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkDuplicateByVnfId(java.lang. String,
+ * java.lang.String, java.lang.String)
*/
@Override
public InfraActiveRequests checkDuplicateByVnfId(final String vnfId, final String action,
@@ -486,11 +478,12 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
InfraActiveRequests ar = null;
final Query query = entityManager.createQuery(
- "from InfraActiveRequests where vnfId = :vnfId and action = :action and (requestStatus = 'PENDING' or requestStatus = 'IN_PROGRESS' or requestStatus = 'TIMEOUT' or requestStatus = 'PENDING_MANUAL_TASK') and requestType = :requestType ORDER BY startTime DESC");
+ "from InfraActiveRequests where vnfId = :vnfId and action = :action and (requestStatus = 'PENDING' or requestStatus = 'IN_PROGRESS' or requestStatus = 'TIMEOUT' or requestStatus = 'PENDING_MANUAL_TASK') and requestType = :requestType ORDER BY startTime DESC");
query.setParameter("vnfId", vnfId);
query.setParameter("action", action);
query.setParameter(REQUEST_TYPE, requestType);
- @SuppressWarnings("unchecked") final List<InfraActiveRequests> results = query.getResultList();
+ @SuppressWarnings("unchecked")
+ final List<InfraActiveRequests> results = query.getResultList();
if (!results.isEmpty()) {
ar = results.get(0);
}
@@ -501,8 +494,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
/*
* (non-Javadoc)
*
- * @see
- * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkVnfIdStatus(java.lang.String)
+ * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkVnfIdStatus(java.lang.String)
*/
@Override
public InfraActiveRequests checkVnfIdStatus(final String operationalEnvironmentId) {
@@ -560,9 +552,10 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
final Timestamp minTime = new Timestamp(startTime);
final Timestamp maxTime = new Timestamp(endTime);
final Predicate basePredicate = criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
- final Predicate additionalPredicate = criteriaBuilder.and(
- criteriaBuilder.greaterThanOrEqualTo(tableRoot.get(START_TIME), minTime),
- criteriaBuilder.or(tableRoot.get(END_TIME).isNull(), criteriaBuilder.lessThanOrEqualTo(tableRoot.get(END_TIME), maxTime)));
+ final Predicate additionalPredicate =
+ criteriaBuilder.and(criteriaBuilder.greaterThanOrEqualTo(tableRoot.get(START_TIME), minTime),
+ criteriaBuilder.or(tableRoot.get(END_TIME).isNull(),
+ criteriaBuilder.lessThanOrEqualTo(tableRoot.get(END_TIME), maxTime)));
criteriaQuery.where(criteriaBuilder.and(basePredicate, additionalPredicate));
if (maxResult != null) {
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationStatusRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationStatusRepository.java
index 16e10e3d5b..1ef3b10e29 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationStatusRepository.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationStatusRepository.java
@@ -28,8 +28,11 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "operationStatus", path = "operationStatus")
public interface OperationStatusRepository extends JpaRepository<OperationStatus, OperationStatusId> {
-
- OperationStatus findOneByServiceIdAndOperationId(@Param("SERVICE_ID") String serviceId, @Param("OPERATION_ID") String operationId);
- public OperationStatus findOneByServiceName(String serviceName);
- public OperationStatus findOneByServiceId(String serviceId);
+
+ OperationStatus findOneByServiceIdAndOperationId(@Param("SERVICE_ID") String serviceId,
+ @Param("OPERATION_ID") String operationId);
+
+ public OperationStatus findOneByServiceName(String serviceName);
+
+ public OperationStatus findOneByServiceId(String serviceId);
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvDistributionStatusRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvDistributionStatusRepository.java
index e89755d565..09c926aef7 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvDistributionStatusRepository.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvDistributionStatusRepository.java
@@ -28,15 +28,16 @@ import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.transaction.annotation.Transactional;
-@RepositoryRestResource(collectionResourceRel = "operationalEnvDistributionStatus", path = "operationalEnvDistributionStatus")
-public interface OperationalEnvDistributionStatusRepository extends JpaRepository<OperationalEnvDistributionStatus, String> {
+@RepositoryRestResource(collectionResourceRel = "operationalEnvDistributionStatus",
+ path = "operationalEnvDistributionStatus")
+public interface OperationalEnvDistributionStatusRepository
+ extends JpaRepository<OperationalEnvDistributionStatus, String> {
- @Modifying
- @Transactional
- @Query("update OperationalEnvDistributionStatus set distributionIdStatus = :distributionIdStatus where "
- + "distributionId = :distributionId and operationalEnvId = :operationalEnvId and serviceModelVersionId = :serviceModelVersionId")
- public int setDistributionIdStatus(@Param("distributionIdStatus") String distributionIdStatus,
- @Param("distributionId") String distributionId,
- @Param("operationalEnvId") String operationalEnvId,
- @Param("serviceModelVersionId") String serviceModelVersionId);
+ @Modifying
+ @Transactional
+ @Query("update OperationalEnvDistributionStatus set distributionIdStatus = :distributionIdStatus where "
+ + "distributionId = :distributionId and operationalEnvId = :operationalEnvId and serviceModelVersionId = :serviceModelVersionId")
+ public int setDistributionIdStatus(@Param("distributionIdStatus") String distributionIdStatus,
+ @Param("distributionId") String distributionId, @Param("operationalEnvId") String operationalEnvId,
+ @Param("serviceModelVersionId") String serviceModelVersionId);
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvServiceModelStatusRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvServiceModelStatusRepository.java
index ecf1dcb183..65a7ca12cd 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvServiceModelStatusRepository.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvServiceModelStatusRepository.java
@@ -21,7 +21,6 @@
package org.onap.so.db.request.data.repository;
import java.util.List;
-
import org.onap.so.db.request.beans.OperationalEnvServiceModelStatus;
import org.onap.so.db.request.beans.OperationalEnvServiceModelStatusId;
import org.springframework.data.jpa.repository.JpaRepository;
@@ -31,14 +30,19 @@ import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.transaction.annotation.Transactional;
-@RepositoryRestResource(collectionResourceRel = "operationalEnvServiceModelStatus", path = "operationalEnvServiceModelStatus")
-public interface OperationalEnvServiceModelStatusRepository extends JpaRepository<OperationalEnvServiceModelStatus, OperationalEnvServiceModelStatusId>{
+@RepositoryRestResource(collectionResourceRel = "operationalEnvServiceModelStatus",
+ path = "operationalEnvServiceModelStatus")
+public interface OperationalEnvServiceModelStatusRepository
+ extends JpaRepository<OperationalEnvServiceModelStatus, OperationalEnvServiceModelStatusId> {
+
+ public OperationalEnvServiceModelStatus findOneByOperationalEnvIdAndRequestId(String operationalEnvId,
+ String requestId);
+
+ public List<OperationalEnvServiceModelStatus> findAllByOperationalEnvIdAndRequestId(
+ @Param("OPERATIONAL_ENV_ID") String operationalEnvId, @Param("REQUEST_ID") String requestId);
+
+ public OperationalEnvServiceModelStatus findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId(
+ @Param("OPERATIONAL_ENV_ID") String operationalEnvId,
+ @Param("SERVICE_MODEL_VERSION_ID") String serviceModelVersionId, @Param("REQUEST_ID") String requestId);
- public OperationalEnvServiceModelStatus findOneByOperationalEnvIdAndRequestId(String operationalEnvId, String requestId);
- public List<OperationalEnvServiceModelStatus> findAllByOperationalEnvIdAndRequestId(@Param("OPERATIONAL_ENV_ID") String operationalEnvId,
- @Param("REQUEST_ID") String requestId);
- public OperationalEnvServiceModelStatus findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId(@Param("OPERATIONAL_ENV_ID") String operationalEnvId,
- @Param("SERVICE_MODEL_VERSION_ID") String serviceModelVersionId,
- @Param("REQUEST_ID") String requestId);
-
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/RequestProcessingDataRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/RequestProcessingDataRepository.java
index f80be0525c..b1abda3b6f 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/RequestProcessingDataRepository.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/RequestProcessingDataRepository.java
@@ -21,7 +21,6 @@
package org.onap.so.db.request.data.repository;
import java.util.List;
-
import org.onap.so.db.request.beans.RequestProcessingData;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
@@ -29,9 +28,8 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "requestProcessingData", path = "requestProcessingData")
public interface RequestProcessingDataRepository extends JpaRepository<RequestProcessingData, Integer> {
- RequestProcessingData findOneBySoRequestIdAndGroupingIdAndNameAndTag(
- @Param("SO_REQUEST_ID") String soRequestId, @Param("GROUPING_ID") String groupingId,
- @Param("NAME") String name, @Param("TAG") String tag);
+ RequestProcessingData findOneBySoRequestIdAndGroupingIdAndNameAndTag(@Param("SO_REQUEST_ID") String soRequestId,
+ @Param("GROUPING_ID") String groupingId, @Param("NAME") String name, @Param("TAG") String tag);
- List<RequestProcessingData> findBySoRequestIdOrderByGroupingIdDesc(@Param("SO_REQUEST_ID") String soRequestId);
+ List<RequestProcessingData> findBySoRequestIdOrderByGroupingIdDesc(@Param("SO_REQUEST_ID") String soRequestId);
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ResourceOperationStatusRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ResourceOperationStatusRepository.java
index b93bf7840b..2ed2d7cb42 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ResourceOperationStatusRepository.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ResourceOperationStatusRepository.java
@@ -21,7 +21,6 @@
package org.onap.so.db.request.data.repository;
import java.util.List;
-
import org.onap.so.db.request.beans.ResourceOperationStatus;
import org.onap.so.db.request.beans.ResourceOperationStatusId;
import org.springframework.data.jpa.repository.JpaRepository;
@@ -29,7 +28,8 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;
@RepositoryRestResource(collectionResourceRel = "resourceOperationStatus", path = "resourceOperationStatus")
-public interface ResourceOperationStatusRepository extends JpaRepository<ResourceOperationStatus, ResourceOperationStatusId> {
+public interface ResourceOperationStatusRepository
+ extends JpaRepository<ResourceOperationStatus, ResourceOperationStatusId> {
- List<ResourceOperationStatus> findByServiceIdAndOperationId(String serviceId, String operationId);
+ List<ResourceOperationStatus> findByServiceIdAndOperationId(String serviceId, String operationId);
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/SiteStatusRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/SiteStatusRepository.java
index 179d40ad23..ebae4a4cec 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/SiteStatusRepository.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/SiteStatusRepository.java
@@ -26,7 +26,7 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;
@RepositoryRestResource(collectionResourceRel = "siteStatus", path = "siteStatus")
-public interface SiteStatusRepository extends JpaRepository<SiteStatus, String> {
- SiteStatus findOneBySiteName(String siteName);
+public interface SiteStatusRepository extends JpaRepository<SiteStatus, String> {
+ SiteStatus findOneBySiteName(String siteName);
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogComponentDistributionStatusRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogComponentDistributionStatusRepository.java
index 138ec0fb4d..9a89cdf783 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogComponentDistributionStatusRepository.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogComponentDistributionStatusRepository.java
@@ -21,15 +21,16 @@
package org.onap.so.db.request.data.repository;
import java.util.List;
-
import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus;
import org.onap.so.db.request.beans.WatchdogComponentDistributionStatusId;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;
-@RepositoryRestResource(collectionResourceRel = "watchdogComponentDistributionStatus", path = "watchdogComponentDistributionStatus")
-public interface WatchdogComponentDistributionStatusRepository extends JpaRepository<WatchdogComponentDistributionStatus, WatchdogComponentDistributionStatusId> {
+@RepositoryRestResource(collectionResourceRel = "watchdogComponentDistributionStatus",
+ path = "watchdogComponentDistributionStatus")
+public interface WatchdogComponentDistributionStatusRepository
+ extends JpaRepository<WatchdogComponentDistributionStatus, WatchdogComponentDistributionStatusId> {
- public List<WatchdogComponentDistributionStatus> findByDistributionId(String distributionId);
+ public List<WatchdogComponentDistributionStatus> findByDistributionId(String distributionId);
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogDistributionStatusRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogDistributionStatusRepository.java
index 6fddf8567c..7dfd61f8d0 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogDistributionStatusRepository.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogDistributionStatusRepository.java
@@ -27,7 +27,7 @@ import org.springframework.stereotype.Repository;
@RepositoryRestResource(collectionResourceRel = "watchdogDistributionStatus", path = "watchdogDistributionStatus")
public interface WatchdogDistributionStatusRepository extends JpaRepository<WatchdogDistributionStatus, String> {
-
- public WatchdogDistributionStatus findOneByDistributionId(String distributionId);
+
+ public WatchdogDistributionStatus findOneByDistributionId(String distributionId);
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogServiceModVerIdLookupRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogServiceModVerIdLookupRepository.java
index b9585d495e..cf36d0c6e6 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogServiceModVerIdLookupRepository.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogServiceModVerIdLookupRepository.java
@@ -27,8 +27,9 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;
@RepositoryRestResource(collectionResourceRel = "watchdogServiceModVerIdLookup", path = "watchdogServiceModVerIdLookup")
-public interface WatchdogServiceModVerIdLookupRepository extends JpaRepository<WatchdogServiceModVerIdLookup, WatchdogServiceModVerIdLookupId> {
+public interface WatchdogServiceModVerIdLookupRepository
+ extends JpaRepository<WatchdogServiceModVerIdLookup, WatchdogServiceModVerIdLookupId> {
+
+ public WatchdogServiceModVerIdLookup findOneByDistributionId(String distributionId);
- public WatchdogServiceModVerIdLookup findOneByDistributionId(String distributionId);
-
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/TestApplication.java b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/TestApplication.java
index 9bb5cab9b5..1b8fc9755e 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/TestApplication.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/TestApplication.java
@@ -27,12 +27,12 @@ import org.springframework.context.annotation.Profile;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
-@SpringBootApplication(scanBasePackages = { "org.onap.so" })
+@SpringBootApplication(scanBasePackages = {"org.onap.so"})
@Profile("test")
public class TestApplication {
- public static void main(String... args) {
- SpringApplication.run(TestApplication.class, args);
- System.getProperties().setProperty("mso.db", "MARIADB");
- System.getProperties().setProperty("server.name", "Springboot");
- }
+ public static void main(String... args) {
+ SpringApplication.run(TestApplication.class, args);
+ System.getProperties().setProperty("mso.db", "MARIADB");
+ System.getProperties().setProperty("server.name", "Springboot");
+ }
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OperationStatusTest.java b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OperationStatusTest.java
index f3be5a154b..09aa252309 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OperationStatusTest.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OperationStatusTest.java
@@ -23,11 +23,8 @@ package org.onap.so.db.request;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
-
import java.util.Date;
-
import javax.transaction.Transactional;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.TestApplication;
@@ -43,43 +40,43 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
-public class OperationStatusTest {
-
- @Autowired
- private OperationStatusRepository repository;
-
- @Test
- @Transactional
- public void timeStampCreated() throws InterruptedException, NoEntityFoundException {
-
- final String testServiceId = "test-service-id";
- final String testOperationId = "test-operation-id";
- final OperationStatusId id = new OperationStatusId(testServiceId, testOperationId);
- OperationStatus status = new OperationStatus();
-
- status.setServiceId(testServiceId);
- status.setOperationId(testOperationId);
-
- status = repository.saveAndFlush(status);
-
- OperationStatus found = repository.findById(id).
- orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
-
- Date operateAt = found.getOperateAt();
- assertNotNull(operateAt);
- assertEquals(testServiceId, found.getServiceId());
- Date finishedAt = found.getFinishedAt();
- status.setProgress("test-progress");
- //timestamps only set to save on 1 second changes
- Thread.sleep(1000);
- repository.saveAndFlush(status);
-
- OperationStatus foundUpdate = repository.findById(id).
- orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
+public class OperationStatusTest {
+
+ @Autowired
+ private OperationStatusRepository repository;
+
+ @Test
+ @Transactional
+ public void timeStampCreated() throws InterruptedException, NoEntityFoundException {
+
+ final String testServiceId = "test-service-id";
+ final String testOperationId = "test-operation-id";
+ final OperationStatusId id = new OperationStatusId(testServiceId, testOperationId);
+ OperationStatus status = new OperationStatus();
+
+ status.setServiceId(testServiceId);
+ status.setOperationId(testOperationId);
+
+ status = repository.saveAndFlush(status);
+
+ OperationStatus found =
+ repository.findById(id).orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
+
+ Date operateAt = found.getOperateAt();
+ assertNotNull(operateAt);
+ assertEquals(testServiceId, found.getServiceId());
+ Date finishedAt = found.getFinishedAt();
+ status.setProgress("test-progress");
+ // timestamps only set to save on 1 second changes
+ Thread.sleep(1000);
+ repository.saveAndFlush(status);
+
+ OperationStatus foundUpdate =
+ repository.findById(id).orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
- assertEquals(operateAt.toString(), foundUpdate.getOperateAt().toString());
- assertNotNull(foundUpdate.getFinishedAt());
- assertNotEquals(finishedAt.toString(), foundUpdate.getFinishedAt().toString());
- assertEquals("test-progress", foundUpdate.getProgress());
- }
+ assertEquals(operateAt.toString(), foundUpdate.getOperateAt().toString());
+ assertNotNull(foundUpdate.getFinishedAt());
+ assertNotEquals(finishedAt.toString(), foundUpdate.getFinishedAt().toString());
+ assertEquals("test-progress", foundUpdate.getProgress());
+ }
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OperationalEnvServiceModelStatusTest.java b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OperationalEnvServiceModelStatusTest.java
index f1f26fa7cc..94dc777763 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OperationalEnvServiceModelStatusTest.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OperationalEnvServiceModelStatusTest.java
@@ -21,7 +21,6 @@
package org.onap.so.db.request;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.TestApplication;
@@ -40,47 +39,49 @@ import org.springframework.test.context.junit4.SpringRunner;
@ActiveProfiles("test")
public class OperationalEnvServiceModelStatusTest {
- @Autowired
- private OperationalEnvServiceModelStatusRepository repository;
-
-
- @Test
- public void updateWithoutAllKeys() throws Exception {
-
- OperationalEnvServiceModelStatus status = new OperationalEnvServiceModelStatus();
- status.setRequestId("request-id-1");
- status.setOperationalEnvId("oper-env-id-1");
- status.setServiceModelVersionId("service-model-ver-id-1");
- status.setVnfOperationalEnvId("vnf-oper-env-id-1");
- status.setRetryCount(0);
-
- repository.saveAndFlush(status);
- OperationalEnvServiceModelStatus status2 = repository.findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId("oper-env-id-1", "service-model-ver-id-1", "request-id-1");
- status2.setRetryCount(1);
- assertEquals("request-id-1", status2.getRequestId());
- assertEquals("vnf-oper-env-id-1", status2.getVnfOperationalEnvId());
-
- repository.saveAndFlush(status2);
-
- OperationalEnvServiceModelStatus status3 = new OperationalEnvServiceModelStatus();
+ @Autowired
+ private OperationalEnvServiceModelStatusRepository repository;
+
+
+ @Test
+ public void updateWithoutAllKeys() throws Exception {
+
+ OperationalEnvServiceModelStatus status = new OperationalEnvServiceModelStatus();
+ status.setRequestId("request-id-1");
+ status.setOperationalEnvId("oper-env-id-1");
+ status.setServiceModelVersionId("service-model-ver-id-1");
+ status.setVnfOperationalEnvId("vnf-oper-env-id-1");
+ status.setRetryCount(0);
+
+ repository.saveAndFlush(status);
+ OperationalEnvServiceModelStatus status2 =
+ repository.findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId("oper-env-id-1",
+ "service-model-ver-id-1", "request-id-1");
+ status2.setRetryCount(1);
+ assertEquals("request-id-1", status2.getRequestId());
+ assertEquals("vnf-oper-env-id-1", status2.getVnfOperationalEnvId());
+
+ repository.saveAndFlush(status2);
+
+ OperationalEnvServiceModelStatus status3 = new OperationalEnvServiceModelStatus();
+
+ status3.setRequestId("request-id-2");
+ status3.setOperationalEnvId("oper-env-id-1");
+ status3.setServiceModelVersionId("service-model-ver-id-2");
+ status3.setVnfOperationalEnvId("vnf-oper-env-id-2");
+ status3.setRetryCount(2);
+
+ repository.saveAndFlush(status3);
- status3.setRequestId("request-id-2");
- status3.setOperationalEnvId("oper-env-id-1");
- status3.setServiceModelVersionId("service-model-ver-id-2");
- status3.setVnfOperationalEnvId("vnf-oper-env-id-2");
- status3.setRetryCount(2);
-
- repository.saveAndFlush(status3);
-
- OperationalEnvServiceModelStatus exampleObj = new OperationalEnvServiceModelStatus();
- exampleObj.setOperationalEnvId("oper-env-id-1");
- exampleObj.setServiceModelVersionId("service-model-ver-id-1");
- ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("requestId");
- OperationalEnvServiceModelStatus foundStatus = repository.findOne(Example.of(exampleObj,matcher))
- .orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
- if(foundStatus== null)
- throw new Exception("No status found");
+ OperationalEnvServiceModelStatus exampleObj = new OperationalEnvServiceModelStatus();
+ exampleObj.setOperationalEnvId("oper-env-id-1");
+ exampleObj.setServiceModelVersionId("service-model-ver-id-1");
+ ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("requestId");
+ OperationalEnvServiceModelStatus foundStatus = repository.findOne(Example.of(exampleObj, matcher))
+ .orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
+ if (foundStatus == null)
+ throw new Exception("No status found");
- assertEquals(new Integer(1), foundStatus.getRetryCount());
- }
+ assertEquals(new Integer(1), foundStatus.getRetryCount());
+ }
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/RequestDBConfig.java b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/RequestDBConfig.java
index 9c270d619b..26ff25833f 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/RequestDBConfig.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/RequestDBConfig.java
@@ -22,11 +22,9 @@ package org.onap.so.db.request;
import java.util.TimeZone;
-
import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
-
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
@@ -42,45 +40,35 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
-@EnableJpaRepositories(
- entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager",
- basePackages = { "org.onap.so.db.request.data.repository" }
- )
+@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory",
+ transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"})
public class RequestDBConfig {
- @Primary
- @Bean(name = "requestDataSource")
- @ConfigurationProperties(prefix = "spring.datasource")
- public DataSource dataSource() {
- return DataSourceBuilder.create().build();
- }
+ @Primary
+ @Bean(name = "requestDataSource")
+ @ConfigurationProperties(prefix = "spring.datasource")
+ public DataSource dataSource() {
+ return DataSourceBuilder.create().build();
+ }
+
+ @Primary
+ @Bean(name = "requestEntityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
+ @Qualifier("requestDataSource") DataSource dataSource) {
+ return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB")
+ .build();
+ }
- @Primary
- @Bean(name = "requestEntityManagerFactory")
- public LocalContainerEntityManagerFactoryBean
- entityManagerFactory(
- EntityManagerFactoryBuilder builder,
- @Qualifier("requestDataSource") DataSource dataSource
- ) {
- return builder
- .dataSource(dataSource)
- .packages("org.onap.so.db.request.beans")
- .persistenceUnit("requestDB")
- .build();
- }
+ @Primary
+ @Bean(name = "requestTransactionManager")
+ public PlatformTransactionManager transactionManager(
+ @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
+ return new JpaTransactionManager(entityManagerFactory);
+ }
- @Primary
- @Bean(name = "requestTransactionManager")
- public PlatformTransactionManager transactionManager(
- @Qualifier("requestEntityManagerFactory") EntityManagerFactory
- entityManagerFactory
- ) {
- return new JpaTransactionManager(entityManagerFactory);
- }
-
- @PostConstruct
- public void started() {
- TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
- }
+ @PostConstruct
+ public void started() {
+ TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
+ }
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/SiteStatusTest.java b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/SiteStatusTest.java
index 1f99e92d97..93218a2057 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/SiteStatusTest.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/SiteStatusTest.java
@@ -22,9 +22,7 @@ package org.onap.so.db.request;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import javax.transaction.Transactional;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -45,47 +43,45 @@ import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class SiteStatusTest {
-
- @Autowired
- private SiteStatusRepository repository;
-
- @Test
- @Transactional
- public void timeStampCreated() throws InterruptedException, NoEntityFoundException {
- SiteStatus found = repository.findById("test name4").
- orElseThrow(() -> new NoEntityFoundException("Cannot Find Site"));
-
- assertNotNull(found.getCreated());
- assertEquals("test name4", found.getSiteName());
- }
-
- @Test
- public void sortByCreated() {
-
- final PageRequest page1 = new PageRequest(
- 0, 20, Direction.DESC, "created"
- );
-
- SiteStatus example = new SiteStatus();
- example.setStatus(true);
- Page<SiteStatus> found = repository.findAll(Example.of(example), page1);
-
- assertEquals("test name4", found.getContent().get(0).getSiteName());
-
- }
-
- @Test
- public void updateStatus() throws NoEntityFoundException {
-
- SiteStatus status = repository.findById("test name update").
- orElseThrow(() -> new NoEntityFoundException("Cannot Find Site"));
- status.setStatus(false);
-
- repository.saveAndFlush(status);
- status = repository.findById("test name update").
- orElseThrow(() -> new NoEntityFoundException("Cannot Find Site"));
- assertEquals(false, status.getStatus());
-
- }
-
+
+ @Autowired
+ private SiteStatusRepository repository;
+
+ @Test
+ @Transactional
+ public void timeStampCreated() throws InterruptedException, NoEntityFoundException {
+ SiteStatus found =
+ repository.findById("test name4").orElseThrow(() -> new NoEntityFoundException("Cannot Find Site"));
+
+ assertNotNull(found.getCreated());
+ assertEquals("test name4", found.getSiteName());
+ }
+
+ @Test
+ public void sortByCreated() {
+
+ final PageRequest page1 = new PageRequest(0, 20, Direction.DESC, "created");
+
+ SiteStatus example = new SiteStatus();
+ example.setStatus(true);
+ Page<SiteStatus> found = repository.findAll(Example.of(example), page1);
+
+ assertEquals("test name4", found.getContent().get(0).getSiteName());
+
+ }
+
+ @Test
+ public void updateStatus() throws NoEntityFoundException {
+
+ SiteStatus status = repository.findById("test name update")
+ .orElseThrow(() -> new NoEntityFoundException("Cannot Find Site"));
+ status.setStatus(false);
+
+ repository.saveAndFlush(status);
+ status = repository.findById("test name update")
+ .orElseThrow(() -> new NoEntityFoundException("Cannot Find Site"));
+ assertEquals(false, status.getStatus());
+
+ }
+
}
diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImplTest.java b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImplTest.java
index 4dd500d86d..ca30604e06 100644
--- a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImplTest.java
+++ b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImplTest.java
@@ -31,18 +31,15 @@ import static org.mockito.Mockito.mock;
import static org.onap.so.db.request.data.repository.InfraActiveRequestsRepositoryImpl.ACTION;
import static org.onap.so.db.request.data.repository.InfraActiveRequestsRepositoryImpl.REQUEST_ID;
import static org.onap.so.db.request.data.repository.InfraActiveRequestsRepositoryImpl.SERVICE_INSTANCE_ID;
-
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
-
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.TestApplication;
@@ -94,8 +91,8 @@ public class InfraActiveRequestsRepositoryImplTest {
public void test_GetInfraActiveRequests_invalidFiltersMap() {
final Map<String, String[]> filters = new HashMap<>();
filters.put("OverTheMoon", new String[] {"Humpty Dumpty Sat On The Wall"});
- final List<Predicate> predicates =
- objUnderTest.getPredicates(filters, mock(CriteriaBuilder.class), (Root<InfraActiveRequests>)mock(Root.class));
+ final List<Predicate> predicates = objUnderTest.getPredicates(filters, mock(CriteriaBuilder.class),
+ (Root<InfraActiveRequests>) mock(Root.class));
assertTrue(predicates.isEmpty());
}
@@ -224,8 +221,8 @@ public class InfraActiveRequestsRepositoryImplTest {
assertFalse(actualRequests.isEmpty());
assertEquals(3, actualRequests.size());
- assertEquals("ShouldReturnInSearchQuery_1,ShouldReturnInSearchQuery_2,ShouldReturnInSearchQuery_3",
- actualRequests.stream().map(item -> item.getServiceInstanceName()).collect(Collectors.joining(",")));
+ assertEquals("ShouldReturnInSearchQuery_1,ShouldReturnInSearchQuery_2,ShouldReturnInSearchQuery_3",
+ actualRequests.stream().map(item -> item.getServiceInstanceName()).collect(Collectors.joining(",")));
}
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java
index aa7b79765b..2cf442406e 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java
@@ -21,72 +21,68 @@
package org.onap.so.db.request.beans;
import java.util.Objects;
-
import javax.persistence.Entity;
import javax.persistence.Table;
-
import org.apache.commons.lang3.builder.ToStringBuilder;
@Entity
@Table(name = "archived_infra_requests")
public class ArchivedInfraRequests extends InfraRequests {
- private static final long serialVersionUID = 7132783898142451603L;
+ private static final long serialVersionUID = 7132783898142451603L;
- public ArchivedInfraRequests() {
- }
+ public ArchivedInfraRequests() {}
- public ArchivedInfraRequests(String requestId, String action) {
- setRequestId(requestId);
- setAction(action);
- }
+ public ArchivedInfraRequests(String requestId, String action) {
+ setRequestId(requestId);
+ setAction(action);
+ }
- public ArchivedInfraRequests(String requestId) {
- setRequestId(requestId);
- }
+ public ArchivedInfraRequests(String requestId) {
+ setRequestId(requestId);
+ }
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof ArchivedInfraRequests)) {
- return false;
- }
- ArchivedInfraRequests castOther = (ArchivedInfraRequests) other;
- return Objects.equals(getRequestId(), castOther.getRequestId());
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof ArchivedInfraRequests)) {
+ return false;
+ }
+ ArchivedInfraRequests castOther = (ArchivedInfraRequests) other;
+ return Objects.equals(getRequestId(), castOther.getRequestId());
+ }
- @Override
- public int hashCode() {
- return Objects.hash(getRequestId());
- }
+ @Override
+ public int hashCode() {
+ return Objects.hash(getRequestId());
+ }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("requestId", getRequestId())
- .append("clientRequestId", getClientRequestId()).append("action", getAction())
- .append("requestStatus", getRequestStatus()).append("statusMessage", getStatusMessage())
- .append("progress", getProgress()).append("startTime", getStartTime()).append("endTime", getEndTime())
- .append("source", getSource()).append("vnfId", getVnfId()).append("vnfName", getVnfName())
- .append("vnfType", getVnfType()).append("serviceType", getServiceType())
- .append("aicNodeClli", getAicNodeClli()).append("tenantId", getTenantId())
- .append("provStatus", getProvStatus()).append("vnfParams", getVnfParams())
- .append("vnfOutputs", getVnfOutputs()).append("requestBody", getRequestBody())
- .append("responseBody", getResponseBody()).append("lastModifiedBy", getLastModifiedBy())
- .append("modifyTime", getModifyTime()).append("requestType", getRequestType())
- .append("volumeGroupId", getVolumeGroupId()).append("volumeGroupName", getVolumeGroupName())
- .append("vfModuleId", getVfModuleId()).append("vfModuleName", getVfModuleName())
- .append("vfModuleModelName", getVfModuleModelName()).append("aaiServiceId", getAaiServiceId())
- .append("aicCloudRegion", getAicCloudRegion()).append("callBackUrl", getCallBackUrl())
- .append("correlator", getCorrelator()).append("serviceInstanceId", getServiceInstanceId())
- .append("serviceInstanceName", getServiceInstanceName()).append("requestScope", getRequestScope())
- .append("requestAction", getRequestAction()).append("networkId", getNetworkId())
- .append("networkName", getNetworkName()).append("networkType", getNetworkType())
- .append("requestorId", getRequestorId()).append("configurationId", getConfigurationId())
- .append("configurationName", getConfigurationName()).append("operationalEnvId", getOperationalEnvId())
- .append("operationalEnvName", getOperationalEnvName())
- .append("requestUrl", getRequestUrl()).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("requestId", getRequestId())
+ .append("clientRequestId", getClientRequestId()).append("action", getAction())
+ .append("requestStatus", getRequestStatus()).append("statusMessage", getStatusMessage())
+ .append("progress", getProgress()).append("startTime", getStartTime()).append("endTime", getEndTime())
+ .append("source", getSource()).append("vnfId", getVnfId()).append("vnfName", getVnfName())
+ .append("vnfType", getVnfType()).append("serviceType", getServiceType())
+ .append("aicNodeClli", getAicNodeClli()).append("tenantId", getTenantId())
+ .append("provStatus", getProvStatus()).append("vnfParams", getVnfParams())
+ .append("vnfOutputs", getVnfOutputs()).append("requestBody", getRequestBody())
+ .append("responseBody", getResponseBody()).append("lastModifiedBy", getLastModifiedBy())
+ .append("modifyTime", getModifyTime()).append("requestType", getRequestType())
+ .append("volumeGroupId", getVolumeGroupId()).append("volumeGroupName", getVolumeGroupName())
+ .append("vfModuleId", getVfModuleId()).append("vfModuleName", getVfModuleName())
+ .append("vfModuleModelName", getVfModuleModelName()).append("aaiServiceId", getAaiServiceId())
+ .append("aicCloudRegion", getAicCloudRegion()).append("callBackUrl", getCallBackUrl())
+ .append("correlator", getCorrelator()).append("serviceInstanceId", getServiceInstanceId())
+ .append("serviceInstanceName", getServiceInstanceName()).append("requestScope", getRequestScope())
+ .append("requestAction", getRequestAction()).append("networkId", getNetworkId())
+ .append("networkName", getNetworkName()).append("networkType", getNetworkType())
+ .append("requestorId", getRequestorId()).append("configurationId", getConfigurationId())
+ .append("configurationName", getConfigurationName()).append("operationalEnvId", getOperationalEnvId())
+ .append("operationalEnvName", getOperationalEnvName()).append("requestUrl", getRequestUrl()).toString();
+ }
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java
index 08aaeb9960..37fbfd023c 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java
@@ -21,10 +21,8 @@
package org.onap.so.db.request.beans;
import java.util.Objects;
-
import javax.persistence.Entity;
import javax.persistence.Table;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.apache.commons.lang3.builder.ToStringBuilder;
@@ -89,7 +87,6 @@ public class InfraActiveRequests extends InfraRequests {
.append("networkName", getNetworkName()).append("networkType", getNetworkType())
.append("requestorId", getRequestorId()).append("configurationId", getConfigurationId())
.append("configurationName", getConfigurationName()).append("operationalEnvId", getOperationalEnvId())
- .append("operationalEnvName", getOperationalEnvName())
- .append("requestUrl", getRequestUrl()).toString();
+ .append("operationalEnvName", getOperationalEnvName()).append("requestUrl", getRequestUrl()).toString();
}
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java
index 0959cf61d4..a1010a349c 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java
@@ -24,7 +24,6 @@ import java.net.URI;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Objects;
-
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@@ -33,10 +32,8 @@ import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
-
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.onap.so.requestsdb.TimestampXMLAdapter;
-
import uk.co.blackpepper.bowman.annotation.ResourceId;
@MappedSuperclass
@@ -148,8 +145,8 @@ public abstract class InfraRequests implements java.io.Serializable {
@Column(name = "INSTANCE_GROUP_NAME", length = 200)
private String instanceGroupName;
@Column(name = "REQUEST_URL", length = 500)
- private String requestUrl;
-
+ private String requestUrl;
+
@ResourceId
public URI getRequestURI() {
return URI.create(this.requestId);
@@ -194,7 +191,7 @@ public abstract class InfraRequests implements java.io.Serializable {
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
-
+
public String getRollbackStatusMessage() {
return this.rollbackStatusMessage;
}
@@ -202,7 +199,7 @@ public abstract class InfraRequests implements java.io.Serializable {
public void setRollbackStatusMessage(String rollbackStatusMessage) {
this.rollbackStatusMessage = rollbackStatusMessage;
}
-
+
public String getFlowStatus() {
return this.flowStatus;
}
@@ -210,7 +207,7 @@ public abstract class InfraRequests implements java.io.Serializable {
public void setFlowStatus(String flowStatus) {
this.flowStatus = flowStatus;
}
-
+
public String getRetryStatusMessage() {
return this.retryStatusMessage;
}
@@ -530,29 +527,29 @@ public abstract class InfraRequests implements java.io.Serializable {
}
public String getInstanceGroupId() {
- return instanceGroupId;
- }
+ return instanceGroupId;
+ }
- public void setInstanceGroupId(String instanceGroupId) {
- this.instanceGroupId = instanceGroupId;
- }
+ public void setInstanceGroupId(String instanceGroupId) {
+ this.instanceGroupId = instanceGroupId;
+ }
- public String getInstanceGroupName() {
- return instanceGroupName;
- }
+ public String getInstanceGroupName() {
+ return instanceGroupName;
+ }
- public void setInstanceGroupName(String instanceGroupName) {
- this.instanceGroupName = instanceGroupName;
- }
+ public void setInstanceGroupName(String instanceGroupName) {
+ this.instanceGroupName = instanceGroupName;
+ }
- public String getRequestUrl() {
+ public String getRequestUrl() {
return this.requestUrl;
}
-
+
public void setRequestUrl(String requestUrl) {
- this.requestUrl = requestUrl;
- }
-
+ this.requestUrl = requestUrl;
+ }
+
@PrePersist
protected void onCreate() {
if (requestScope == null)
@@ -592,28 +589,28 @@ public abstract class InfraRequests implements java.io.Serializable {
public String toString() {
return new ToStringBuilder(this).append("requestId", getRequestId())
.append("clientRequestId", getClientRequestId()).append("action", getAction())
- .append("requestStatus", getRequestStatus()).append("statusMessage", getStatusMessage()).append("rollbackStatusMessage", getRollbackStatusMessage())
- .append("flowStatus", getFlowStatus()).append("retryStatusMessage", getRetryStatusMessage())
- .append("progress", getProgress()).append("startTime", getStartTime()).append("endTime", getEndTime())
- .append("source", getSource()).append("vnfId", getVnfId()).append("vnfName", getVnfName())
- .append("vnfType", getVnfType()).append("serviceType", getServiceType())
- .append("aicNodeClli", getAicNodeClli()).append("tenantId", getTenantId())
- .append("provStatus", getProvStatus()).append("vnfParams", getVnfParams())
- .append("vnfOutputs", getVnfOutputs()).append("requestBody", getRequestBody())
- .append("responseBody", getResponseBody()).append("lastModifiedBy", getLastModifiedBy())
- .append("modifyTime", getModifyTime()).append("requestType", getRequestType())
- .append("volumeGroupId", getVolumeGroupId()).append("volumeGroupName", getVolumeGroupName())
- .append("vfModuleId", getVfModuleId()).append("vfModuleName", getVfModuleName())
- .append("vfModuleModelName", getVfModuleModelName()).append("aaiServiceId", getAaiServiceId())
- .append("aicCloudRegion", getAicCloudRegion()).append("callBackUrl", getCallBackUrl())
- .append("correlator", getCorrelator()).append("serviceInstanceId", getServiceInstanceId())
+ .append("requestStatus", getRequestStatus()).append("statusMessage", getStatusMessage())
+ .append("rollbackStatusMessage", getRollbackStatusMessage()).append("flowStatus", getFlowStatus())
+ .append("retryStatusMessage", getRetryStatusMessage()).append("progress", getProgress())
+ .append("startTime", getStartTime()).append("endTime", getEndTime()).append("source", getSource())
+ .append("vnfId", getVnfId()).append("vnfName", getVnfName()).append("vnfType", getVnfType())
+ .append("serviceType", getServiceType()).append("aicNodeClli", getAicNodeClli())
+ .append("tenantId", getTenantId()).append("provStatus", getProvStatus())
+ .append("vnfParams", getVnfParams()).append("vnfOutputs", getVnfOutputs())
+ .append("requestBody", getRequestBody()).append("responseBody", getResponseBody())
+ .append("lastModifiedBy", getLastModifiedBy()).append("modifyTime", getModifyTime())
+ .append("requestType", getRequestType()).append("volumeGroupId", getVolumeGroupId())
+ .append("volumeGroupName", getVolumeGroupName()).append("vfModuleId", getVfModuleId())
+ .append("vfModuleName", getVfModuleName()).append("vfModuleModelName", getVfModuleModelName())
+ .append("aaiServiceId", getAaiServiceId()).append("aicCloudRegion", getAicCloudRegion())
+ .append("callBackUrl", getCallBackUrl()).append("correlator", getCorrelator())
+ .append("serviceInstanceId", getServiceInstanceId())
.append("serviceInstanceName", getServiceInstanceName()).append("requestScope", getRequestScope())
.append("requestAction", getRequestAction()).append("networkId", getNetworkId())
.append("networkName", getNetworkName()).append("networkType", getNetworkType())
.append("requestorId", getRequestorId()).append("configurationId", getConfigurationId())
.append("configurationName", getConfigurationName()).append("operationalEnvId", getOperationalEnvId())
- .append("operationalEnvName", getOperationalEnvName())
- .append("instanceGroupId", getInstanceGroupId()).append("instanceGroupName", getInstanceGroupName())
- .append("requestUrl", getRequestUrl()).toString();
+ .append("operationalEnvName", getOperationalEnvName()).append("instanceGroupId", getInstanceGroupId())
+ .append("instanceGroupName", getInstanceGroupName()).append("requestUrl", getRequestUrl()).toString();
}
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationStatus.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationStatus.java
index dff9dd6687..ece9b5ab25 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationStatus.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationStatus.java
@@ -22,7 +22,6 @@ package org.onap.so.db.request.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -36,204 +35,203 @@ import java.util.Objects;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
- * The service operation status
- * <br>
+ * The service operation status <br>
* <p>
* </p>
*
* @author
- * @version ONAP Amsterdam Release 2017-08-28
+ * @version ONAP Amsterdam Release 2017-08-28
*/
@IdClass(OperationStatusId.class)
@Entity
@Table(name = "operation_status")
-public class OperationStatus implements Serializable{
-
+public class OperationStatus implements Serializable {
+
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
- @Column(name = "SERVICE_ID")
+ @Column(name = "SERVICE_ID")
private String serviceId;
@Id
- @Column(name = "OPERATION_ID", length=256)
+ @Column(name = "OPERATION_ID", length = 256)
private String operationId;
-
- @Column(name = "SERVICE_NAME", length=256)
+
+ @Column(name = "SERVICE_NAME", length = 256)
private String serviceName;
-
- @Column(name = "OPERATION_TYPE", length=256)
+
+ @Column(name = "OPERATION_TYPE", length = 256)
private String operation;
-
- @Column(name = "USER_ID", length=256)
+
+ @Column(name = "USER_ID", length = 256)
private String userId;
-
- @Column(name = "RESULT", length=256)
+
+ @Column(name = "RESULT", length = 256)
private String result;
-
- @Column(name = "OPERATION_CONTENT", length=256)
+
+ @Column(name = "OPERATION_CONTENT", length = 256)
private String operationContent;
-
- @Column(name = "PROGRESS", length=256)
+
+ @Column(name = "PROGRESS", length = 256)
private String progress = "0";
-
- @Column(name = "REASON", length=256)
+
+ @Column(name = "REASON", length = 256)
private String reason;
- @Column(name = "OPERATE_AT", length=256, updatable=false)
+ @Column(name = "OPERATE_AT", length = 256, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date operateAt;
-
- @Column(name = "FINISHED_AT", length=256)
+
+ @Column(name = "FINISHED_AT", length = 256)
@Temporal(TemporalType.TIMESTAMP)
private Date finishedAt;
public OperationStatus() {
-
+
}
-
+
public OperationStatus(String serviceId, String operationId) {
- this.serviceId = serviceId;
- this.operationId = operationId;
+ this.serviceId = serviceId;
+ this.operationId = operationId;
}
-
-
+
+
public String getServiceId() {
return serviceId;
}
-
+
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
-
+
public String getOperationId() {
return operationId;
}
-
+
public void setOperationId(String operationId) {
this.operationId = operationId;
}
-
+
public String getOperation() {
return operation;
}
-
+
public void setOperation(String operation) {
this.operation = operation;
}
-
+
public String getServiceName() {
- return serviceName;
- }
+ return serviceName;
+ }
- public void setServiceName(String serviceName) {
- this.serviceName = serviceName;
- }
+ public void setServiceName(String serviceName) {
+ this.serviceName = serviceName;
+ }
- public String getUserId() {
+ public String getUserId() {
return userId;
}
-
+
public void setUserId(String userId) {
this.userId = userId;
}
-
+
public String getResult() {
return result;
}
-
+
public void setResult(String result) {
this.result = result;
}
-
+
public String getOperationContent() {
return operationContent;
}
-
+
public void setOperationContent(String operationContent) {
this.operationContent = operationContent;
}
-
+
public String getProgress() {
return progress;
}
-
+
public void setProgress(String progress) {
this.progress = progress;
}
-
+
public String getReason() {
return reason;
}
-
+
public void setReason(String reason) {
this.reason = reason;
}
-
+
public Date getOperateAt() {
return operateAt;
}
-
+
public Date getFinishedAt() {
return finishedAt;
}
@PrePersist
protected void onCreate() {
- this.finishedAt = this.operateAt = new Date();
+ this.finishedAt = this.operateAt = new Date();
}
-
+
@PreUpdate
protected void onUpdate() {
- this.finishedAt = new Date();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof OperationStatus)) {
- return false;
- }
- OperationStatus castOther = (OperationStatus) other;
- return Objects.equals(getServiceId(), castOther.getServiceId())
- && Objects.equals(getOperationId(), castOther.getOperationId());
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(getServiceId(), getOperationId());
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("serviceId", getServiceId()).append("operationId", getOperationId())
- .append("operation", getOperation()).append("userId", getUserId()).append("result", getResult())
- .append("operationContent", getOperationContent()).append("progress", getProgress())
- .append("reason", getReason()).append("operateAt", getOperateAt()).append("finishedAt", getFinishedAt())
- .toString();
- }
-
-
+ this.finishedAt = new Date();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof OperationStatus)) {
+ return false;
+ }
+ OperationStatus castOther = (OperationStatus) other;
+ return Objects.equals(getServiceId(), castOther.getServiceId())
+ && Objects.equals(getOperationId(), castOther.getOperationId());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getServiceId(), getOperationId());
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("serviceId", getServiceId()).append("operationId", getOperationId())
+ .append("operation", getOperation()).append("userId", getUserId()).append("result", getResult())
+ .append("operationContent", getOperationContent()).append("progress", getProgress())
+ .append("reason", getReason()).append("operateAt", getOperateAt()).append("finishedAt", getFinishedAt())
+ .toString();
+ }
+
+
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationStatusId.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationStatusId.java
index d07788e55c..0e14b09edd 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationStatusId.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationStatusId.java
@@ -22,58 +22,65 @@ package org.onap.so.db.request.beans;
import java.io.Serializable;
import java.util.Objects;
-
import com.openpojo.business.annotation.BusinessKey;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class OperationStatusId implements Serializable {
- private static final long serialVersionUID = 3114959241155882723L;
-
- @BusinessKey
- private String serviceId;
- @BusinessKey
- private String operationId;
-
- public OperationStatusId() {
-
- }
- public OperationStatusId(String serviceId, String operationId) {
- this.serviceId = serviceId;
- this.operationId = operationId;
- }
- public String getServiceId() {
- return serviceId;
- }
- public void setServiceId(String serviceId) {
- this.serviceId = serviceId;
- }
- public String getOperationId() {
- return operationId;
- }
- public void setOperationId(String operationId) {
- this.operationId = operationId;
- }
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof OperationStatusId)) {
- return false;
- }
- OperationStatusId castOther = (OperationStatusId) other;
- return Objects.equals(this.getServiceId(), castOther.getServiceId())
- && Objects.equals(this.getOperationId(), castOther.getOperationId());
- }
- @Override
- public int hashCode() {
- return Objects.hash(this.getServiceId(), this.getOperationId());
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("serviceId", getServiceId()).append("operationId", getOperationId())
- .toString();
- }
+ private static final long serialVersionUID = 3114959241155882723L;
+
+ @BusinessKey
+ private String serviceId;
+ @BusinessKey
+ private String operationId;
+
+ public OperationStatusId() {
+
+ }
+
+ public OperationStatusId(String serviceId, String operationId) {
+ this.serviceId = serviceId;
+ this.operationId = operationId;
+ }
+
+ public String getServiceId() {
+ return serviceId;
+ }
+
+ public void setServiceId(String serviceId) {
+ this.serviceId = serviceId;
+ }
+
+ public String getOperationId() {
+ return operationId;
+ }
+
+ public void setOperationId(String operationId) {
+ this.operationId = operationId;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof OperationStatusId)) {
+ return false;
+ }
+ OperationStatusId castOther = (OperationStatusId) other;
+ return Objects.equals(this.getServiceId(), castOther.getServiceId())
+ && Objects.equals(this.getOperationId(), castOther.getOperationId());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(this.getServiceId(), this.getOperationId());
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("serviceId", getServiceId()).append("operationId", getOperationId())
+ .toString();
+ }
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvDistributionStatus.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvDistributionStatus.java
index a1e1278306..b50be2e8be 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvDistributionStatus.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvDistributionStatus.java
@@ -22,7 +22,6 @@ package org.onap.so.db.request.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -37,8 +36,6 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Objects;
-
-
import org.apache.commons.lang3.builder.ToStringBuilder;
@@ -46,132 +43,134 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
@Table(name = "activate_operational_env_per_distributionid_status")
public class OperationalEnvDistributionStatus implements Serializable {
- /**
- * Serialization id.
- */
- private static final long serialVersionUID = 7398393659281364650L;
-
- @Id
- @Column(name = "DISTRIBUTION_ID", length=45)
- private String distributionId;
- @Column(name = "OPERATIONAL_ENV_ID", length=45)
- private String operationalEnvId;
- @Column(name = "SERVICE_MODEL_VERSION_ID", length=45)
- private String serviceModelVersionId;
- @Column(name = "REQUEST_ID", length=45)
- private String requestId;
- @Column(name = "DISTRIBUTION_ID_STATUS", length=45)
- private String distributionIdStatus;
- @Column(name = "DISTRIBUTION_ID_ERROR_REASON", length=250)
- private String distributionIdErrorReason;
- @Column(name = "CREATE_TIME", updatable=false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date createTime;
- @Column(name = "MODIFY_TIME")
- @Temporal(TemporalType.TIMESTAMP)
- private Date modifyTime;
-
-
- public OperationalEnvDistributionStatus() {
-
- }
-
- public OperationalEnvDistributionStatus(String distributionId, String operationalEnvId, String serviceModelVersionId) {
- this.distributionId = distributionId;
- this.operationalEnvId = operationalEnvId;
- this.serviceModelVersionId = serviceModelVersionId;
- }
- public String getDistributionId() {
- return distributionId;
- }
-
- public void setDistributionId(String distributionId) {
- this.distributionId = distributionId;
- }
-
- public String getOperationalEnvId() {
- return operationalEnvId;
- }
-
- public void setOperationalEnvId(String operationalEnvId) {
- this.operationalEnvId = operationalEnvId;
- }
-
- public String getServiceModelVersionId() {
- return serviceModelVersionId;
- }
-
- public void setServiceModelVersionId(String serviceModelVersionId) {
- this.serviceModelVersionId = serviceModelVersionId;
- }
-
- public String getRequestId() {
- return requestId;
- }
-
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
- public String getDistributionIdStatus() {
- return distributionIdStatus;
- }
-
- public void setDistributionIdStatus(String distributionIdStatus) {
- this.distributionIdStatus = distributionIdStatus;
- }
-
- public String getDistributionIdErrorReason() {
- return distributionIdErrorReason;
- }
-
- public void setDistributionIdErrorReason(String distributionIdErrorReason) {
- this.distributionIdErrorReason = distributionIdErrorReason;
- }
-
- public Date getCreateTime() {
- return createTime;
- }
-
- public Date getModifyTime() {
- return modifyTime;
- }
-
- @PrePersist
- protected void onCreate() {
- this.createTime = this.modifyTime = new Date();
- }
-
- @PreUpdate
- protected void onUpdate() {
- this.modifyTime = new Date();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof OperationalEnvDistributionStatus)) {
- return false;
- }
- OperationalEnvDistributionStatus castOther = (OperationalEnvDistributionStatus) other;
- return Objects.equals(getDistributionId(), castOther.getDistributionId());
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(getDistributionId());
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("distributionId", getDistributionId())
- .append("operationalEnvId", getOperationalEnvId())
- .append("serviceModelVersionId", getServiceModelVersionId()).append("requestId", getRequestId())
- .append("distributionIdStatus", getDistributionIdStatus())
- .append("distributionIdErrorReason", getDistributionIdErrorReason())
- .append("createTime", getCreateTime()).append("modifyTime", getModifyTime()).toString();
- }
-
+ /**
+ * Serialization id.
+ */
+ private static final long serialVersionUID = 7398393659281364650L;
+
+ @Id
+ @Column(name = "DISTRIBUTION_ID", length = 45)
+ private String distributionId;
+ @Column(name = "OPERATIONAL_ENV_ID", length = 45)
+ private String operationalEnvId;
+ @Column(name = "SERVICE_MODEL_VERSION_ID", length = 45)
+ private String serviceModelVersionId;
+ @Column(name = "REQUEST_ID", length = 45)
+ private String requestId;
+ @Column(name = "DISTRIBUTION_ID_STATUS", length = 45)
+ private String distributionIdStatus;
+ @Column(name = "DISTRIBUTION_ID_ERROR_REASON", length = 250)
+ private String distributionIdErrorReason;
+ @Column(name = "CREATE_TIME", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date createTime;
+ @Column(name = "MODIFY_TIME")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date modifyTime;
+
+
+ public OperationalEnvDistributionStatus() {
+
+ }
+
+ public OperationalEnvDistributionStatus(String distributionId, String operationalEnvId,
+ String serviceModelVersionId) {
+ this.distributionId = distributionId;
+ this.operationalEnvId = operationalEnvId;
+ this.serviceModelVersionId = serviceModelVersionId;
+ }
+
+ public String getDistributionId() {
+ return distributionId;
+ }
+
+ public void setDistributionId(String distributionId) {
+ this.distributionId = distributionId;
+ }
+
+ public String getOperationalEnvId() {
+ return operationalEnvId;
+ }
+
+ public void setOperationalEnvId(String operationalEnvId) {
+ this.operationalEnvId = operationalEnvId;
+ }
+
+ public String getServiceModelVersionId() {
+ return serviceModelVersionId;
+ }
+
+ public void setServiceModelVersionId(String serviceModelVersionId) {
+ this.serviceModelVersionId = serviceModelVersionId;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getDistributionIdStatus() {
+ return distributionIdStatus;
+ }
+
+ public void setDistributionIdStatus(String distributionIdStatus) {
+ this.distributionIdStatus = distributionIdStatus;
+ }
+
+ public String getDistributionIdErrorReason() {
+ return distributionIdErrorReason;
+ }
+
+ public void setDistributionIdErrorReason(String distributionIdErrorReason) {
+ this.distributionIdErrorReason = distributionIdErrorReason;
+ }
+
+ public Date getCreateTime() {
+ return createTime;
+ }
+
+ public Date getModifyTime() {
+ return modifyTime;
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.createTime = this.modifyTime = new Date();
+ }
+
+ @PreUpdate
+ protected void onUpdate() {
+ this.modifyTime = new Date();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof OperationalEnvDistributionStatus)) {
+ return false;
+ }
+ OperationalEnvDistributionStatus castOther = (OperationalEnvDistributionStatus) other;
+ return Objects.equals(getDistributionId(), castOther.getDistributionId());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getDistributionId());
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("distributionId", getDistributionId())
+ .append("operationalEnvId", getOperationalEnvId())
+ .append("serviceModelVersionId", getServiceModelVersionId()).append("requestId", getRequestId())
+ .append("distributionIdStatus", getDistributionIdStatus())
+ .append("distributionIdErrorReason", getDistributionIdErrorReason())
+ .append("createTime", getCreateTime()).append("modifyTime", getModifyTime()).toString();
+ }
+
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvServiceModelStatus.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvServiceModelStatus.java
index 79168f8f0b..2278c8cd9d 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvServiceModelStatus.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvServiceModelStatus.java
@@ -22,7 +22,6 @@ package org.onap.so.db.request.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -45,157 +44,158 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
public class OperationalEnvServiceModelStatus implements Serializable {
/**
- * Serialization id.
- */
- private static final long serialVersionUID = 8197084996598869656L;
-
- @Id
- @Column(name = "REQUEST_ID", length=45)
- private String requestId;
- @Id
- @Column(name = "OPERATIONAL_ENV_ID", length=45)
- private String operationalEnvId;
- @Id
- @Column(name = "SERVICE_MODEL_VERSION_ID", length=45)
- private String serviceModelVersionId;
- @Column(name = "SERVICE_MOD_VER_FINAL_DISTR_STATUS", length=45)
- private String serviceModelVersionDistrStatus;
- @Column(name = "RECOVERY_ACTION", length=30)
- private String recoveryAction;
- @Column(name = "RETRY_COUNT_LEFT")
- private Integer retryCount;
- @Column(name = "WORKLOAD_CONTEXT", length=80)
- private String workloadContext;
- @Column(name = "CREATE_TIME", updatable=false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date createTime;
- @Column(name = "MODIFY_TIME")
- @Temporal(TemporalType.TIMESTAMP)
- private Date modifyTime;
- @Column(name = "VNF_OPERATIONAL_ENV_ID", length=45)
- private String vnfOperationalEnvId;
-
- public OperationalEnvServiceModelStatus() {
-
- }
-
- public OperationalEnvServiceModelStatus(String requestId, String operationalEnvId, String serviceModelVersionId) {
- this.requestId = requestId;
- this.operationalEnvId = operationalEnvId;
- this.serviceModelVersionId = serviceModelVersionId;
- }
- public String getRequestId() {
- return requestId;
- }
-
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
- public String getOperationalEnvId() {
- return operationalEnvId;
- }
-
- public void setOperationalEnvId(String operationalEnvId) {
- this.operationalEnvId = operationalEnvId;
- }
-
- public String getServiceModelVersionId() {
- return serviceModelVersionId;
- }
-
- public void setServiceModelVersionId(String serviceModelVersionId) {
- this.serviceModelVersionId = serviceModelVersionId;
- }
-
- public String getServiceModelVersionDistrStatus() {
- return serviceModelVersionDistrStatus;
- }
-
- public void setServiceModelVersionDistrStatus(String serviceModelVersionDistrStatus) {
- this.serviceModelVersionDistrStatus = serviceModelVersionDistrStatus;
- }
-
- public String getRecoveryAction() {
- return recoveryAction;
- }
-
- public void setRecoveryAction(String recoveryAction) {
- this.recoveryAction = recoveryAction;
- }
-
- public Integer getRetryCount() {
- return retryCount;
- }
-
- public void setRetryCount(Integer retryCount) {
- this.retryCount = retryCount;
- }
-
- public String getWorkloadContext() {
- return workloadContext;
- }
-
- public void setWorkloadContext(String workloadContext) {
- this.workloadContext = workloadContext;
- }
-
- public Date getCreateTime() {
- return createTime;
- }
-
-
- public Date getModifyTime() {
- return modifyTime;
- }
-
- public String getVnfOperationalEnvId() {
- return vnfOperationalEnvId;
- }
-
- public void setVnfOperationalEnvId(String vnfOperationalEnvId) {
- this.vnfOperationalEnvId = vnfOperationalEnvId;
- }
-
- @PrePersist
- protected void onCreate() {
- this.createTime = this.modifyTime = new Date();
- }
-
- @PreUpdate
- protected void onUpdate() {
- this.modifyTime = new Date();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof OperationalEnvServiceModelStatus)) {
- return false;
- }
- OperationalEnvServiceModelStatus castOther = (OperationalEnvServiceModelStatus) other;
- return Objects.equals(getRequestId(), castOther.getRequestId())
- && Objects.equals(getOperationalEnvId(), castOther.getOperationalEnvId());
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(getRequestId(), getOperationalEnvId());
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("requestId", getRequestId())
- .append("operationalEnvId", getOperationalEnvId())
- .append("serviceModelVersionId", getServiceModelVersionId())
- .append("serviceModelVersionDistrStatus", getServiceModelVersionDistrStatus())
- .append("recoveryAction", getRecoveryAction()).append("retryCount", getRetryCount())
- .append("workloadContext", getWorkloadContext()).append("createTime", getCreateTime())
- .append("modifyTime", getModifyTime())
- .append("vnfOperationalEnvId", getVnfOperationalEnvId()).toString();
- }
-
+ * Serialization id.
+ */
+ private static final long serialVersionUID = 8197084996598869656L;
+
+ @Id
+ @Column(name = "REQUEST_ID", length = 45)
+ private String requestId;
+ @Id
+ @Column(name = "OPERATIONAL_ENV_ID", length = 45)
+ private String operationalEnvId;
+ @Id
+ @Column(name = "SERVICE_MODEL_VERSION_ID", length = 45)
+ private String serviceModelVersionId;
+ @Column(name = "SERVICE_MOD_VER_FINAL_DISTR_STATUS", length = 45)
+ private String serviceModelVersionDistrStatus;
+ @Column(name = "RECOVERY_ACTION", length = 30)
+ private String recoveryAction;
+ @Column(name = "RETRY_COUNT_LEFT")
+ private Integer retryCount;
+ @Column(name = "WORKLOAD_CONTEXT", length = 80)
+ private String workloadContext;
+ @Column(name = "CREATE_TIME", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date createTime;
+ @Column(name = "MODIFY_TIME")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date modifyTime;
+ @Column(name = "VNF_OPERATIONAL_ENV_ID", length = 45)
+ private String vnfOperationalEnvId;
+
+ public OperationalEnvServiceModelStatus() {
+
+ }
+
+ public OperationalEnvServiceModelStatus(String requestId, String operationalEnvId, String serviceModelVersionId) {
+ this.requestId = requestId;
+ this.operationalEnvId = operationalEnvId;
+ this.serviceModelVersionId = serviceModelVersionId;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getOperationalEnvId() {
+ return operationalEnvId;
+ }
+
+ public void setOperationalEnvId(String operationalEnvId) {
+ this.operationalEnvId = operationalEnvId;
+ }
+
+ public String getServiceModelVersionId() {
+ return serviceModelVersionId;
+ }
+
+ public void setServiceModelVersionId(String serviceModelVersionId) {
+ this.serviceModelVersionId = serviceModelVersionId;
+ }
+
+ public String getServiceModelVersionDistrStatus() {
+ return serviceModelVersionDistrStatus;
+ }
+
+ public void setServiceModelVersionDistrStatus(String serviceModelVersionDistrStatus) {
+ this.serviceModelVersionDistrStatus = serviceModelVersionDistrStatus;
+ }
+
+ public String getRecoveryAction() {
+ return recoveryAction;
+ }
+
+ public void setRecoveryAction(String recoveryAction) {
+ this.recoveryAction = recoveryAction;
+ }
+
+ public Integer getRetryCount() {
+ return retryCount;
+ }
+
+ public void setRetryCount(Integer retryCount) {
+ this.retryCount = retryCount;
+ }
+
+ public String getWorkloadContext() {
+ return workloadContext;
+ }
+
+ public void setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
+
+ public Date getCreateTime() {
+ return createTime;
+ }
+
+
+ public Date getModifyTime() {
+ return modifyTime;
+ }
+
+ public String getVnfOperationalEnvId() {
+ return vnfOperationalEnvId;
+ }
+
+ public void setVnfOperationalEnvId(String vnfOperationalEnvId) {
+ this.vnfOperationalEnvId = vnfOperationalEnvId;
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.createTime = this.modifyTime = new Date();
+ }
+
+ @PreUpdate
+ protected void onUpdate() {
+ this.modifyTime = new Date();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof OperationalEnvServiceModelStatus)) {
+ return false;
+ }
+ OperationalEnvServiceModelStatus castOther = (OperationalEnvServiceModelStatus) other;
+ return Objects.equals(getRequestId(), castOther.getRequestId())
+ && Objects.equals(getOperationalEnvId(), castOther.getOperationalEnvId());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getRequestId(), getOperationalEnvId());
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("requestId", getRequestId())
+ .append("operationalEnvId", getOperationalEnvId())
+ .append("serviceModelVersionId", getServiceModelVersionId())
+ .append("serviceModelVersionDistrStatus", getServiceModelVersionDistrStatus())
+ .append("recoveryAction", getRecoveryAction()).append("retryCount", getRetryCount())
+ .append("workloadContext", getWorkloadContext()).append("createTime", getCreateTime())
+ .append("modifyTime", getModifyTime()).append("vnfOperationalEnvId", getVnfOperationalEnvId())
+ .toString();
+ }
+
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvServiceModelStatusId.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvServiceModelStatusId.java
index 301e24f8ec..8979e3732e 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvServiceModelStatusId.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvServiceModelStatusId.java
@@ -22,61 +22,68 @@ package org.onap.so.db.request.beans;
import java.io.Serializable;
import java.util.Objects;
-
import com.openpojo.business.annotation.BusinessKey;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class OperationalEnvServiceModelStatusId implements Serializable {
- private static final long serialVersionUID = 6885534735320068787L;
-
- @BusinessKey
- private String requestId;
- @BusinessKey
- private String operationalEnvId;
- @BusinessKey
- private String serviceModelVersionId;
-
- public String getRequestId() {
- return requestId;
- }
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
- public String getOperationalEnvId() {
- return operationalEnvId;
- }
- public void setOperationalEnvId(String operationalEnvId) {
- this.operationalEnvId = operationalEnvId;
- }
- public String getServiceModelVersionId() {
- return serviceModelVersionId;
- }
- public void setServiceModelVersionId(String serviceModelVersionId) {
- this.serviceModelVersionId = serviceModelVersionId;
- }
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof OperationalEnvServiceModelStatusId)) {
- return false;
- }
- OperationalEnvServiceModelStatusId castOther = (OperationalEnvServiceModelStatusId) other;
- return Objects.equals(this.getRequestId(), castOther.getRequestId())
- && Objects.equals(this.getOperationalEnvId(), castOther.getOperationalEnvId())
- && Objects.equals(this.getServiceModelVersionId(), castOther.getServiceModelVersionId());
- }
- @Override
- public int hashCode() {
- return Objects.hash(this.getRequestId(), this.getOperationalEnvId(), this.getServiceModelVersionId());
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("requestId", getRequestId())
- .append("operationalEnvId", getOperationalEnvId())
- .append("serviceModelVersionId", getServiceModelVersionId()).toString();
- }
+ private static final long serialVersionUID = 6885534735320068787L;
+
+ @BusinessKey
+ private String requestId;
+ @BusinessKey
+ private String operationalEnvId;
+ @BusinessKey
+ private String serviceModelVersionId;
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getOperationalEnvId() {
+ return operationalEnvId;
+ }
+
+ public void setOperationalEnvId(String operationalEnvId) {
+ this.operationalEnvId = operationalEnvId;
+ }
+
+ public String getServiceModelVersionId() {
+ return serviceModelVersionId;
+ }
+
+ public void setServiceModelVersionId(String serviceModelVersionId) {
+ this.serviceModelVersionId = serviceModelVersionId;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof OperationalEnvServiceModelStatusId)) {
+ return false;
+ }
+ OperationalEnvServiceModelStatusId castOther = (OperationalEnvServiceModelStatusId) other;
+ return Objects.equals(this.getRequestId(), castOther.getRequestId())
+ && Objects.equals(this.getOperationalEnvId(), castOther.getOperationalEnvId())
+ && Objects.equals(this.getServiceModelVersionId(), castOther.getServiceModelVersionId());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(this.getRequestId(), this.getOperationalEnvId(), this.getServiceModelVersionId());
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("requestId", getRequestId())
+ .append("operationalEnvId", getOperationalEnvId())
+ .append("serviceModelVersionId", getServiceModelVersionId()).toString();
+ }
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java
index 0a74c1d7be..2a75c24c46 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java
@@ -22,7 +22,6 @@ package org.onap.so.db.request.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@@ -32,140 +31,137 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.openpojo.business.annotation.BusinessKey;
/**
- * persist the request identifiers created when MSO POSTs a request to PINC
- * <br>
+ * persist the request identifiers created when MSO POSTs a request to PINC <br>
* <p>
* </p>
*
* @author
- * @version
+ * @version
*/
@Entity
@JsonInclude(Include.NON_NULL)
@Table(name = "request_processing_data")
-public class RequestProcessingData implements Serializable{
+public class RequestProcessingData implements Serializable {
- /**
+ /**
*
*/
- private static final long serialVersionUID = -3497593687393936143L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column(name = "ID")
- private Integer id;
-
- @BusinessKey
- @Column(name = "SO_REQUEST_ID", length=50, unique=true)
- private String soRequestId;
-
- @BusinessKey
- @Column(name = "GROUPING_ID", length=100, unique=true)
- private String groupingId;
-
- @BusinessKey
- @Column(name = "NAME", length=200)
- private String name;
-
- @Column(name = "VALUE", columnDefinition = "LONGTEXT")
- private String value;
-
- @BusinessKey
- @Column(name = "TAG", length=200)
- private String tag;
-
- @Column(name = "CREATE_TIME", insertable = false, updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created = null;
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof RequestProcessingData)) {
- return false;
- }
- RequestProcessingData castOther = (RequestProcessingData) other;
- return new EqualsBuilder().append(soRequestId, castOther.soRequestId).append(groupingId, castOther.groupingId)
- .append(name, castOther.name).append(tag, castOther.tag).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(soRequestId).append(groupingId).append(name).append(tag).toHashCode();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", id).append("soRequestId", soRequestId)
- .append("groupingId", groupingId).append("name", name).append("value", value).append("tag", tag)
- .toString();
- }
-
- @PrePersist
- protected void createdAt() {
- this.created = new Date();
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getSoRequestId() {
- return soRequestId;
- }
-
- public void setSoRequestId(String soRequestId) {
- this.soRequestId = soRequestId;
- }
-
- public String getGroupingId() {
- return groupingId;
- }
-
- public void setGroupingId(String groupingId) {
- this.groupingId = groupingId;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getValue() {
- return value;
- }
-
- public void setValue(String value) {
- this.value = value;
- }
-
- public String getTag() {
- return tag;
- }
-
- public void setTag(String tag) {
- this.tag = tag;
- }
-
+ private static final long serialVersionUID = -3497593687393936143L;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "ID")
+ private Integer id;
+
+ @BusinessKey
+ @Column(name = "SO_REQUEST_ID", length = 50, unique = true)
+ private String soRequestId;
+
+ @BusinessKey
+ @Column(name = "GROUPING_ID", length = 100, unique = true)
+ private String groupingId;
+
+ @BusinessKey
+ @Column(name = "NAME", length = 200)
+ private String name;
+
+ @Column(name = "VALUE", columnDefinition = "LONGTEXT")
+ private String value;
+
+ @BusinessKey
+ @Column(name = "TAG", length = 200)
+ private String tag;
+
+ @Column(name = "CREATE_TIME", insertable = false, updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created = null;
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof RequestProcessingData)) {
+ return false;
+ }
+ RequestProcessingData castOther = (RequestProcessingData) other;
+ return new EqualsBuilder().append(soRequestId, castOther.soRequestId).append(groupingId, castOther.groupingId)
+ .append(name, castOther.name).append(tag, castOther.tag).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(soRequestId).append(groupingId).append(name).append(tag).toHashCode();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", id).append("soRequestId", soRequestId)
+ .append("groupingId", groupingId).append("name", name).append("value", value).append("tag", tag)
+ .toString();
+ }
+
+ @PrePersist
+ protected void createdAt() {
+ this.created = new Date();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getSoRequestId() {
+ return soRequestId;
+ }
+
+ public void setSoRequestId(String soRequestId) {
+ this.soRequestId = soRequestId;
+ }
+
+ public String getGroupingId() {
+ return groupingId;
+ }
+
+ public void setGroupingId(String groupingId) {
+ this.groupingId = groupingId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public String getTag() {
+ return tag;
+ }
+
+ public void setTag(String tag) {
+ this.tag = tag;
+ }
+
public Date getCreated() {
- return created;
- }
-} \ No newline at end of file
+ return created;
+ }
+}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ResourceOperationStatus.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ResourceOperationStatus.java
index 386daa6dbb..b415fc360f 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ResourceOperationStatus.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ResourceOperationStatus.java
@@ -21,7 +21,6 @@
package org.onap.so.db.request.beans;
import java.io.Serializable;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -31,19 +30,18 @@ import java.util.Objects;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
- * The Resource operation status
- * <br>
+ * The Resource operation status <br>
* <p>
* </p>
*
* @author
- * @version ONAP Amsterdam Release 2017-08-28
+ * @version ONAP Amsterdam Release 2017-08-28
*/
@IdClass(ResourceOperationStatusId.class)
@Entity
@Table(name = "resource_operation_status")
-public class ResourceOperationStatus implements Serializable{
+public class ResourceOperationStatus implements Serializable {
/**
*
@@ -51,173 +49,172 @@ public class ResourceOperationStatus implements Serializable{
private static final long serialVersionUID = 1L;
@Id
- @Column(name = "SERVICE_ID")
+ @Column(name = "SERVICE_ID")
private String serviceId;
@Id
- @Column(name = "OPERATION_ID", length=256)
+ @Column(name = "OPERATION_ID", length = 256)
private String operationId;
@Id
- @Column(name = "RESOURCE_TEMPLATE_UUID")
+ @Column(name = "RESOURCE_TEMPLATE_UUID")
private String resourceTemplateUUID;
-
- @Column(name = "OPER_TYPE", length=256)
+
+ @Column(name = "OPER_TYPE", length = 256)
private String operType;
-
- @Column(name = "RESOURCE_INSTANCE_ID", length=256)
+
+ @Column(name = "RESOURCE_INSTANCE_ID", length = 256)
private String resourceInstanceID;
-
- @Column(name = "JOB_ID", length=256)
+
+ @Column(name = "JOB_ID", length = 256)
private String jobId;
-
- @Column(name = "STATUS", length=256)
+
+ @Column(name = "STATUS", length = 256)
private String status;
-
- @Column(name = "PROGRESS", length=256)
+
+ @Column(name = "PROGRESS", length = 256)
private String progress = "0";
-
- @Column(name = "ERROR_CODE", length=256)
+
+ @Column(name = "ERROR_CODE", length = 256)
private String errorCode;
-
- @Column(name = "STATUS_DESCRIPOTION", length=256)
+
+ @Column(name = "STATUS_DESCRIPOTION", length = 256)
private String statusDescription;
- public ResourceOperationStatus(){
-
+ public ResourceOperationStatus() {
+
}
-
- public ResourceOperationStatus(String serviceId, String operationId, String resourceTemplateUUID)
- {
+
+ public ResourceOperationStatus(String serviceId, String operationId, String resourceTemplateUUID) {
this.serviceId = serviceId;
this.operationId = operationId;
this.resourceTemplateUUID = resourceTemplateUUID;
}
-
+
public String getServiceId() {
return serviceId;
}
-
+
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
-
+
public String getOperationId() {
return operationId;
}
-
+
public void setOperationId(String operationId) {
this.operationId = operationId;
}
-
+
public String getResourceTemplateUUID() {
return resourceTemplateUUID;
}
-
+
public void setResourceTemplateUUID(String resourceTemplateUUId) {
this.resourceTemplateUUID = resourceTemplateUUId;
}
-
+
public String getJobId() {
return jobId;
}
-
+
public void setJobId(String jobId) {
this.jobId = jobId;
}
-
+
public String getStatus() {
return status;
}
-
+
public void setStatus(String status) {
this.status = status;
}
-
+
public String getProgress() {
return progress;
}
-
+
public void setProgress(String progress) {
this.progress = progress;
}
-
+
public String getErrorCode() {
return errorCode;
}
-
+
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
-
+
public String getStatusDescription() {
return statusDescription;
}
-
+
public void setStatusDescription(String statusDescription) {
this.statusDescription = statusDescription;
}
-
+
public String getResourceInstanceID() {
return resourceInstanceID;
}
-
+
public void setResourceInstanceID(String resourceInstanceID) {
this.resourceInstanceID = resourceInstanceID;
}
-
+
public String getOperType() {
return operType;
}
-
+
public void setOperType(String operType) {
this.operType = operType;
}
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof ResourceOperationStatus)) {
- return false;
- }
- ResourceOperationStatus castOther = (ResourceOperationStatus) other;
- return Objects.equals(getServiceId(), castOther.getServiceId())
- && Objects.equals(getOperationId(), castOther.getOperationId())
- && Objects.equals(getResourceTemplateUUID(), castOther.getResourceTemplateUUID());
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(getServiceId(), getOperationId(), getResourceTemplateUUID());
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("serviceId", getServiceId()).append("operationId", getOperationId())
- .append("resourceTemplateUUID", getResourceTemplateUUID()).append("operType", getOperType())
- .append("resourceInstanceID", getResourceInstanceID()).append("jobId", getJobId())
- .append("status", getStatus()).append("progress", getProgress()).append("errorCode", getErrorCode())
- .append("statusDescription", getStatusDescription()).toString();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof ResourceOperationStatus)) {
+ return false;
+ }
+ ResourceOperationStatus castOther = (ResourceOperationStatus) other;
+ return Objects.equals(getServiceId(), castOther.getServiceId())
+ && Objects.equals(getOperationId(), castOther.getOperationId())
+ && Objects.equals(getResourceTemplateUUID(), castOther.getResourceTemplateUUID());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getServiceId(), getOperationId(), getResourceTemplateUUID());
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("serviceId", getServiceId()).append("operationId", getOperationId())
+ .append("resourceTemplateUUID", getResourceTemplateUUID()).append("operType", getOperType())
+ .append("resourceInstanceID", getResourceInstanceID()).append("jobId", getJobId())
+ .append("status", getStatus()).append("progress", getProgress()).append("errorCode", getErrorCode())
+ .append("statusDescription", getStatusDescription()).toString();
+ }
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ResourceOperationStatusId.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ResourceOperationStatusId.java
index 0f3656cd31..b35a277902 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ResourceOperationStatusId.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ResourceOperationStatusId.java
@@ -22,70 +22,78 @@ package org.onap.so.db.request.beans;
import java.io.Serializable;
import java.util.Objects;
-
import com.openpojo.business.annotation.BusinessKey;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class ResourceOperationStatusId implements Serializable {
- private static final long serialVersionUID = -7425019928845751157L;
-
- @BusinessKey
- private String serviceId;
- @BusinessKey
+ private static final long serialVersionUID = -7425019928845751157L;
+
+ @BusinessKey
+ private String serviceId;
+ @BusinessKey
private String operationId;
- @BusinessKey
+ @BusinessKey
private String resourceTemplateUUID;
-
- public ResourceOperationStatusId() {
-
- }
-
- public ResourceOperationStatusId(String serviceId, String operationId, String resourceTemplateUUID) {
- this.serviceId = serviceId;
- this.operationId = operationId;
- this.resourceTemplateUUID = resourceTemplateUUID;
- }
- public String getServiceId() {
- return serviceId;
- }
- public void setServiceId(String serviceId) {
- this.serviceId = serviceId;
- }
- public String getOperationId() {
- return operationId;
- }
- public void setOperationId(String operationId) {
- this.operationId = operationId;
- }
- public String getResourceTemplateUUID() {
- return resourceTemplateUUID;
- }
- public void setResourceTemplateUUID(String resourceTemplateUUID) {
- this.resourceTemplateUUID = resourceTemplateUUID;
- }
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof ResourceOperationStatusId)) {
- return false;
- }
- ResourceOperationStatusId castOther = (ResourceOperationStatusId) other;
- return Objects.equals(this.getServiceId(), castOther.getServiceId())
- && Objects.equals(this.getOperationId(), castOther.getOperationId())
- && Objects.equals(this.getResourceTemplateUUID(), castOther.getResourceTemplateUUID());
- }
- @Override
- public int hashCode() {
- return Objects.hash(this.getServiceId(), this.getOperationId(),this.getResourceTemplateUUID());
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("serviceId", getServiceId()).append("operationId", getOperationId())
- .append("resourceTemplateUUID", getResourceTemplateUUID()).toString();
- }
-
-
+
+ public ResourceOperationStatusId() {
+
+ }
+
+ public ResourceOperationStatusId(String serviceId, String operationId, String resourceTemplateUUID) {
+ this.serviceId = serviceId;
+ this.operationId = operationId;
+ this.resourceTemplateUUID = resourceTemplateUUID;
+ }
+
+ public String getServiceId() {
+ return serviceId;
+ }
+
+ public void setServiceId(String serviceId) {
+ this.serviceId = serviceId;
+ }
+
+ public String getOperationId() {
+ return operationId;
+ }
+
+ public void setOperationId(String operationId) {
+ this.operationId = operationId;
+ }
+
+ public String getResourceTemplateUUID() {
+ return resourceTemplateUUID;
+ }
+
+ public void setResourceTemplateUUID(String resourceTemplateUUID) {
+ this.resourceTemplateUUID = resourceTemplateUUID;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof ResourceOperationStatusId)) {
+ return false;
+ }
+ ResourceOperationStatusId castOther = (ResourceOperationStatusId) other;
+ return Objects.equals(this.getServiceId(), castOther.getServiceId())
+ && Objects.equals(this.getOperationId(), castOther.getOperationId())
+ && Objects.equals(this.getResourceTemplateUUID(), castOther.getResourceTemplateUUID());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(this.getServiceId(), this.getOperationId(), this.getResourceTemplateUUID());
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("serviceId", getServiceId()).append("operationId", getOperationId())
+ .append("resourceTemplateUUID", getResourceTemplateUUID()).toString();
+ }
+
+
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/SiteStatus.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/SiteStatus.java
index e7a0c39702..da426aecef 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/SiteStatus.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/SiteStatus.java
@@ -23,7 +23,6 @@ package org.onap.so.db.request.beans;
import java.time.format.DateTimeFormatter;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -31,31 +30,29 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import java.util.Objects;
import org.apache.commons.lang3.builder.ToStringBuilder;
@Entity
@Table(name = "site_status")
public class SiteStatus {
-
- @Column(name = "STATUS")
+
+ @Column(name = "STATUS")
private boolean status;
- @Id
- @Column(name = "SITE_NAME")
+ @Id
+ @Column(name = "SITE_NAME")
private String siteName;
- @Column(name = "CREATION_TIMESTAMP", insertable = false, updatable = false)
+ @Column(name = "CREATION_TIMESTAMP", insertable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date created;
- public SiteStatus() {
- }
+ public SiteStatus() {}
public SiteStatus(String siteName) {
- this.siteName = siteName;
- }
+ this.siteName = siteName;
+ }
- public Date getCreated() {
+ public Date getCreated() {
return created;
}
@@ -77,28 +74,29 @@ public class SiteStatus {
@PrePersist
protected void createdAt() {
- this.created = new Date();
+ this.created = new Date();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof SiteStatus)) {
+ return false;
+ }
+ SiteStatus castOther = (SiteStatus) other;
+ return Objects.equals(getSiteName(), castOther.getSiteName());
}
+
@Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof SiteStatus)) {
- return false;
- }
- SiteStatus castOther = (SiteStatus) other;
- return Objects.equals(getSiteName(), castOther.getSiteName());
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(getSiteName());
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("status", getStatus()).append("siteName", getSiteName())
- .append("created", getCreated()).toString();
- }
+ public int hashCode() {
+ return Objects.hash(getSiteName());
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("status", getStatus()).append("siteName", getSiteName())
+ .append("created", getCreated()).toString();
+ }
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/Status.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/Status.java
index f6ee5086c9..0ff894e96f 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/Status.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/Status.java
@@ -23,11 +23,11 @@ package org.onap.so.db.request.beans;
/*
* Enum for Status values returned by API Handler to Tail-F
-*/
+ */
public enum Status {
- PENDING, INPROGRESS, COMPLETED, FAILED, TIMEOUT;
+ PENDING, INPROGRESS, COMPLETED, FAILED, TIMEOUT;
- public boolean isFinished () {
+ public boolean isFinished() {
switch (this) {
case COMPLETED:
case FAILED:
@@ -37,4 +37,4 @@ public enum Status {
return false;
}
}
-} \ No newline at end of file
+}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogComponentDistributionStatus.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogComponentDistributionStatus.java
index f72a7b327a..7e8220e475 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogComponentDistributionStatus.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogComponentDistributionStatus.java
@@ -22,7 +22,6 @@ package org.onap.so.db.request.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -41,100 +40,100 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
public class WatchdogComponentDistributionStatus implements Serializable {
- /**
- * Serialization id.
- */
- private static final long serialVersionUID = -4344508954204488669L;
- @Id
- @Column(name = "DISTRIBUTION_ID", length=45)
- private String distributionId;
- @Id
- @Column(name = "COMPONENT_NAME", length=45)
- private String componentName;
- @Column(name = "COMPONENT_DISTRIBUTION_STATUS", length=45)
- private String componentDistributionStatus;
- @Column(name = "CREATE_TIME", updatable=false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date createTime;
- @Column(name = "MODIFY_TIME")
- @Temporal(TemporalType.TIMESTAMP)
- private Date modifyTime;
-
- public WatchdogComponentDistributionStatus() {
-
- }
-
- public WatchdogComponentDistributionStatus(String distributionId, String componentName) {
- this.distributionId = distributionId;
- this.componentName = componentName;
- }
-
- public String getDistributionId() {
- return distributionId;
- }
-
- public void setDistributionId(String distributionId) {
- this.distributionId = distributionId;
- }
-
- public String getComponentName() {
- return componentName;
- }
-
- public void setComponentName(String componentName) {
- this.componentName = componentName;
- }
-
- public String getComponentDistributionStatus() {
- return componentDistributionStatus;
- }
-
- public void setComponentDistributionStatus(String componentDistributionStatus) {
- this.componentDistributionStatus = componentDistributionStatus;
- }
-
- public Date getCreateTime() {
- return createTime;
- }
-
- public Date getModifyTime() {
- return modifyTime;
- }
-
- @PrePersist
- protected void onCreate() {
- this.createTime = this.modifyTime = new Date();
- }
-
- @PreUpdate
- protected void onUpdate() {
- this.modifyTime = new Date();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof WatchdogComponentDistributionStatus)) {
- return false;
- }
- WatchdogComponentDistributionStatus castOther = (WatchdogComponentDistributionStatus) other;
- return Objects.equals(getDistributionId(), castOther.getDistributionId())
- && Objects.equals(getComponentName(), castOther.getComponentName());
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(getDistributionId(), getComponentName());
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("distributionId", getDistributionId())
- .append("componentName", getComponentName())
- .append("componentDistributionStatus", getComponentDistributionStatus())
- .append("createTime", getCreateTime()).append("modifyTime", getModifyTime()).toString();
- }
+ /**
+ * Serialization id.
+ */
+ private static final long serialVersionUID = -4344508954204488669L;
+ @Id
+ @Column(name = "DISTRIBUTION_ID", length = 45)
+ private String distributionId;
+ @Id
+ @Column(name = "COMPONENT_NAME", length = 45)
+ private String componentName;
+ @Column(name = "COMPONENT_DISTRIBUTION_STATUS", length = 45)
+ private String componentDistributionStatus;
+ @Column(name = "CREATE_TIME", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date createTime;
+ @Column(name = "MODIFY_TIME")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date modifyTime;
+
+ public WatchdogComponentDistributionStatus() {
+
+ }
+
+ public WatchdogComponentDistributionStatus(String distributionId, String componentName) {
+ this.distributionId = distributionId;
+ this.componentName = componentName;
+ }
+
+ public String getDistributionId() {
+ return distributionId;
+ }
+
+ public void setDistributionId(String distributionId) {
+ this.distributionId = distributionId;
+ }
+
+ public String getComponentName() {
+ return componentName;
+ }
+
+ public void setComponentName(String componentName) {
+ this.componentName = componentName;
+ }
+
+ public String getComponentDistributionStatus() {
+ return componentDistributionStatus;
+ }
+
+ public void setComponentDistributionStatus(String componentDistributionStatus) {
+ this.componentDistributionStatus = componentDistributionStatus;
+ }
+
+ public Date getCreateTime() {
+ return createTime;
+ }
+
+ public Date getModifyTime() {
+ return modifyTime;
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.createTime = this.modifyTime = new Date();
+ }
+
+ @PreUpdate
+ protected void onUpdate() {
+ this.modifyTime = new Date();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof WatchdogComponentDistributionStatus)) {
+ return false;
+ }
+ WatchdogComponentDistributionStatus castOther = (WatchdogComponentDistributionStatus) other;
+ return Objects.equals(getDistributionId(), castOther.getDistributionId())
+ && Objects.equals(getComponentName(), castOther.getComponentName());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getDistributionId(), getComponentName());
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("distributionId", getDistributionId())
+ .append("componentName", getComponentName())
+ .append("componentDistributionStatus", getComponentDistributionStatus())
+ .append("createTime", getCreateTime()).append("modifyTime", getModifyTime()).toString();
+ }
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogComponentDistributionStatusId.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogComponentDistributionStatusId.java
index 79e6fbaced..6a0fcf7079 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogComponentDistributionStatusId.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogComponentDistributionStatusId.java
@@ -22,52 +22,57 @@ package org.onap.so.db.request.beans;
import java.io.Serializable;
import java.util.Objects;
-
import com.openpojo.business.annotation.BusinessKey;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class WatchdogComponentDistributionStatusId implements Serializable {
- private static final long serialVersionUID = -4785382368168200031L;
-
- @BusinessKey
- private String distributionId;
- @BusinessKey
- private String componentName;
-
- public String getDistributionId() {
- return distributionId;
- }
- public void setDistributionId(String distributionId) {
- this.distributionId = distributionId;
- }
- public String getComponentName() {
- return componentName;
- }
- public void setComponentName(String componentName) {
- this.componentName = componentName;
- }
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof WatchdogComponentDistributionStatusId)) {
- return false;
- }
- WatchdogComponentDistributionStatusId castOther = (WatchdogComponentDistributionStatusId) other;
- return Objects.equals(this.getDistributionId(), castOther.getDistributionId())
- && Objects.equals(this.getComponentName(), castOther.getComponentName());
- }
- @Override
- public int hashCode() {
- return Objects.hash(this.getDistributionId(), this.getComponentName());
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("distributionId", getDistributionId())
- .append("componentName", getComponentName()).toString();
- }
+ private static final long serialVersionUID = -4785382368168200031L;
+
+ @BusinessKey
+ private String distributionId;
+ @BusinessKey
+ private String componentName;
+
+ public String getDistributionId() {
+ return distributionId;
+ }
+
+ public void setDistributionId(String distributionId) {
+ this.distributionId = distributionId;
+ }
+
+ public String getComponentName() {
+ return componentName;
+ }
+
+ public void setComponentName(String componentName) {
+ this.componentName = componentName;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof WatchdogComponentDistributionStatusId)) {
+ return false;
+ }
+ WatchdogComponentDistributionStatusId castOther = (WatchdogComponentDistributionStatusId) other;
+ return Objects.equals(this.getDistributionId(), castOther.getDistributionId())
+ && Objects.equals(this.getComponentName(), castOther.getComponentName());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(this.getDistributionId(), this.getComponentName());
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("distributionId", getDistributionId())
+ .append("componentName", getComponentName()).toString();
+ }
+
-
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogDistributionStatus.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogDistributionStatus.java
index c8ad5f1843..ca5ae7bbb6 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogDistributionStatus.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogDistributionStatus.java
@@ -22,7 +22,6 @@ package org.onap.so.db.request.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -32,7 +31,6 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
-
import java.util.Objects;
import org.apache.commons.lang3.builder.ToStringBuilder;
@@ -40,97 +38,97 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
@Table(name = "watchdog_distributionid_status")
public class WatchdogDistributionStatus implements Serializable {
- /**
- * Serialization id.
- */
- private static final long serialVersionUID = -4449711060885719079L;
-
- @Id
- @Column(name = "DISTRIBUTION_ID", length=45)
- private String distributionId;
- @Column(name = "DISTRIBUTION_ID_STATUS", length=45)
- private String distributionIdStatus;
- @Column(name = "CREATE_TIME", updatable=false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date createTime;
- @Column(name = "MODIFY_TIME")
- @Temporal(TemporalType.TIMESTAMP)
- private Date modifyTime;
- @Column(name = "LOCK_VERSION")
- private int version;
-
- public WatchdogDistributionStatus() {
-
- }
-
- public WatchdogDistributionStatus(String distributionId) {
- this.distributionId = distributionId;
- }
-
- public String getDistributionId() {
- return distributionId;
- }
-
- public void setDistributionId(String distributionId) {
- this.distributionId = distributionId;
- }
-
- public String getDistributionIdStatus() {
- return distributionIdStatus;
- }
-
- public void setDistributionIdStatus(String distributionIdStatus) {
- this.distributionIdStatus = distributionIdStatus;
- }
-
- public int getVersion() {
- return version;
- }
-
- public void setVersion(int version) {
- this.version = version;
- }
-
- public Date getCreateTime() {
- return createTime;
- }
-
- public Date getModifyTime() {
- return modifyTime;
- }
-
- @PrePersist
- protected void onCreate() {
- this.createTime = this.modifyTime = new Date();
- }
-
- @PreUpdate
- protected void onUpdate() {
- this.modifyTime = new Date();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof WatchdogDistributionStatus)) {
- return false;
- }
- WatchdogDistributionStatus castOther = (WatchdogDistributionStatus) other;
- return Objects.equals(getDistributionId(), castOther.getDistributionId());
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(getDistributionId());
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("distributionId", getDistributionId())
- .append("distributionIdStatus", getDistributionIdStatus()).append("createTime", getCreateTime())
- .append("modifyTime", getModifyTime()).toString();
- }
-
+ /**
+ * Serialization id.
+ */
+ private static final long serialVersionUID = -4449711060885719079L;
+
+ @Id
+ @Column(name = "DISTRIBUTION_ID", length = 45)
+ private String distributionId;
+ @Column(name = "DISTRIBUTION_ID_STATUS", length = 45)
+ private String distributionIdStatus;
+ @Column(name = "CREATE_TIME", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date createTime;
+ @Column(name = "MODIFY_TIME")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date modifyTime;
+ @Column(name = "LOCK_VERSION")
+ private int version;
+
+ public WatchdogDistributionStatus() {
+
+ }
+
+ public WatchdogDistributionStatus(String distributionId) {
+ this.distributionId = distributionId;
+ }
+
+ public String getDistributionId() {
+ return distributionId;
+ }
+
+ public void setDistributionId(String distributionId) {
+ this.distributionId = distributionId;
+ }
+
+ public String getDistributionIdStatus() {
+ return distributionIdStatus;
+ }
+
+ public void setDistributionIdStatus(String distributionIdStatus) {
+ this.distributionIdStatus = distributionIdStatus;
+ }
+
+ public int getVersion() {
+ return version;
+ }
+
+ public void setVersion(int version) {
+ this.version = version;
+ }
+
+ public Date getCreateTime() {
+ return createTime;
+ }
+
+ public Date getModifyTime() {
+ return modifyTime;
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.createTime = this.modifyTime = new Date();
+ }
+
+ @PreUpdate
+ protected void onUpdate() {
+ this.modifyTime = new Date();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof WatchdogDistributionStatus)) {
+ return false;
+ }
+ WatchdogDistributionStatus castOther = (WatchdogDistributionStatus) other;
+ return Objects.equals(getDistributionId(), castOther.getDistributionId());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getDistributionId());
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("distributionId", getDistributionId())
+ .append("distributionIdStatus", getDistributionIdStatus()).append("createTime", getCreateTime())
+ .append("modifyTime", getModifyTime()).toString();
+ }
+
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogServiceModVerIdLookup.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogServiceModVerIdLookup.java
index 25f5802413..d48a9c792e 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogServiceModVerIdLookup.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogServiceModVerIdLookup.java
@@ -24,7 +24,6 @@ import java.io.Serializable;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -33,7 +32,6 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.ToStringBuilder;
@IdClass(WatchdogServiceModVerIdLookupId.class)
@@ -41,103 +39,108 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
@Table(name = "watchdog_service_mod_ver_id_lookup")
public class WatchdogServiceModVerIdLookup implements Serializable {
- /**
- * Serialization id.
- */
- private static final long serialVersionUID = 7783869906430250355L;
-
- @Id
- @Column(name = "DISTRIBUTION_ID", length=45)
- private String distributionId;
- @Id
- @Column(name = "SERVICE_MODEL_VERSION_ID", length=45)
- private String serviceModelVersionId;
- @Column(name = "DISTRIBUTION_NOTIFICATION")
- private String distributionNotification;
- @Column(name = "CONSUMER_ID", length=200)
- private String consumerId;
- @Column(name = "CREATE_TIME", updatable=false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date createTime;
-
- public WatchdogServiceModVerIdLookup() {
-
- }
- /**
- *
- * @param distributionId - Distribution ID
- * @param serviceModelVersionId -- service UUID
- * @param distributionNotification -- Notification content from ASDC
- * @param consumerId -- Consumer ID associated with subscription.
- */
- public WatchdogServiceModVerIdLookup(String distributionId, String serviceModelVersionId,
- Optional<String> distributionNotification, String consumerId) {
- this.distributionId = distributionId;
- this.serviceModelVersionId = serviceModelVersionId;
- this.distributionNotification= distributionNotification.orElse(null);
- this.consumerId = consumerId;
- }
-
- public String getDistributionId() {
- return distributionId;
- }
-
- public void setDistributionId(String distributionId) {
- this.distributionId = distributionId;
- }
-
- public String getServiceModelVersionId() {
- return serviceModelVersionId;
- }
-
- public void setServiceModelVersionId(String serviceModelVersionId) {
- this.serviceModelVersionId = serviceModelVersionId;
- }
-
- public Date getCreateTime() {
- return createTime;
- }
-
- @PrePersist
- protected void onCreate() {
- this.createTime = new Date();
- }
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof WatchdogServiceModVerIdLookup)) {
- return false;
- }
- WatchdogServiceModVerIdLookup castOther = (WatchdogServiceModVerIdLookup) other;
- return Objects.equals(getDistributionId(), castOther.getDistributionId())
- && Objects.equals(getServiceModelVersionId(), castOther.getServiceModelVersionId());
- }
- @Override
- public int hashCode() {
- return Objects.hash(getDistributionId(), getServiceModelVersionId());
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this)
- .append("distributionId", getDistributionId())
- .append("serviceModelVersionId", getServiceModelVersionId())
- .append("createTime", getCreateTime())
- .append("distributionNotification", getDistributionNotification())
- .append("consumerId", getConsumerId())
- .toString();
- }
- public String getDistributionNotification() {
- return distributionNotification;
- }
- public void setDistributionNotification(String distributionNotification) {
- this.distributionNotification = distributionNotification;
- }
- public String getConsumerId() {
- return consumerId;
- }
- public void setConsumerId(String consumerId) {
- this.consumerId = consumerId;
- }
+ /**
+ * Serialization id.
+ */
+ private static final long serialVersionUID = 7783869906430250355L;
+
+ @Id
+ @Column(name = "DISTRIBUTION_ID", length = 45)
+ private String distributionId;
+ @Id
+ @Column(name = "SERVICE_MODEL_VERSION_ID", length = 45)
+ private String serviceModelVersionId;
+ @Column(name = "DISTRIBUTION_NOTIFICATION")
+ private String distributionNotification;
+ @Column(name = "CONSUMER_ID", length = 200)
+ private String consumerId;
+ @Column(name = "CREATE_TIME", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date createTime;
+
+ public WatchdogServiceModVerIdLookup() {
+
+ }
+
+ /**
+ *
+ * @param distributionId - Distribution ID
+ * @param serviceModelVersionId -- service UUID
+ * @param distributionNotification -- Notification content from ASDC
+ * @param consumerId -- Consumer ID associated with subscription.
+ */
+ public WatchdogServiceModVerIdLookup(String distributionId, String serviceModelVersionId,
+ Optional<String> distributionNotification, String consumerId) {
+ this.distributionId = distributionId;
+ this.serviceModelVersionId = serviceModelVersionId;
+ this.distributionNotification = distributionNotification.orElse(null);
+ this.consumerId = consumerId;
+ }
+
+ public String getDistributionId() {
+ return distributionId;
+ }
+
+ public void setDistributionId(String distributionId) {
+ this.distributionId = distributionId;
+ }
+
+ public String getServiceModelVersionId() {
+ return serviceModelVersionId;
+ }
+
+ public void setServiceModelVersionId(String serviceModelVersionId) {
+ this.serviceModelVersionId = serviceModelVersionId;
+ }
+
+ public Date getCreateTime() {
+ return createTime;
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.createTime = new Date();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof WatchdogServiceModVerIdLookup)) {
+ return false;
+ }
+ WatchdogServiceModVerIdLookup castOther = (WatchdogServiceModVerIdLookup) other;
+ return Objects.equals(getDistributionId(), castOther.getDistributionId())
+ && Objects.equals(getServiceModelVersionId(), castOther.getServiceModelVersionId());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getDistributionId(), getServiceModelVersionId());
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("distributionId", getDistributionId())
+ .append("serviceModelVersionId", getServiceModelVersionId()).append("createTime", getCreateTime())
+ .append("distributionNotification", getDistributionNotification()).append("consumerId", getConsumerId())
+ .toString();
+ }
+
+ public String getDistributionNotification() {
+ return distributionNotification;
+ }
+
+ public void setDistributionNotification(String distributionNotification) {
+ this.distributionNotification = distributionNotification;
+ }
+
+ public String getConsumerId() {
+ return consumerId;
+ }
+
+ public void setConsumerId(String consumerId) {
+ this.consumerId = consumerId;
+ }
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogServiceModVerIdLookupId.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogServiceModVerIdLookupId.java
index 2c0b67bac2..dd77037971 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogServiceModVerIdLookupId.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/WatchdogServiceModVerIdLookupId.java
@@ -22,53 +22,58 @@ package org.onap.so.db.request.beans;
import java.io.Serializable;
import java.util.Objects;
-
import com.openpojo.business.annotation.BusinessKey;
import org.apache.commons.lang3.builder.ToStringBuilder;
-public class WatchdogServiceModVerIdLookupId implements Serializable{
+public class WatchdogServiceModVerIdLookupId implements Serializable {
+
+ private static final long serialVersionUID = 9112709226209619993L;
+
+ @BusinessKey
+ private String distributionId;
+ @BusinessKey
+ private String serviceModelVersionId;
+
+ public String getDistributionId() {
+ return distributionId;
+ }
+
+ public void setDistributionId(String distributionId) {
+ this.distributionId = distributionId;
+ }
+
+ public String getServiceModelVersionId() {
+ return serviceModelVersionId;
+ }
+
+ public void setServiceModelVersionId(String serviceModelVersionId) {
+ this.serviceModelVersionId = serviceModelVersionId;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof WatchdogServiceModVerIdLookupId)) {
+ return false;
+ }
+ WatchdogServiceModVerIdLookupId castOther = (WatchdogServiceModVerIdLookupId) other;
+ return Objects.equals(this.getDistributionId(), castOther.getDistributionId())
+ && Objects.equals(getServiceModelVersionId(), castOther.getServiceModelVersionId());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(this.getDistributionId(), this.getServiceModelVersionId());
+ }
- private static final long serialVersionUID = 9112709226209619993L;
-
- @BusinessKey
- private String distributionId;
- @BusinessKey
- private String serviceModelVersionId;
- public String getDistributionId() {
- return distributionId;
- }
- public void setDistributionId(String distributionId) {
- this.distributionId = distributionId;
- }
- public String getServiceModelVersionId() {
- return serviceModelVersionId;
- }
- public void setServiceModelVersionId(String serviceModelVersionId) {
- this.serviceModelVersionId = serviceModelVersionId;
- }
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof WatchdogServiceModVerIdLookupId)) {
- return false;
- }
- WatchdogServiceModVerIdLookupId castOther = (WatchdogServiceModVerIdLookupId) other;
- return Objects.equals(this.getDistributionId(), castOther.getDistributionId())
- && Objects.equals(getServiceModelVersionId(), castOther.getServiceModelVersionId());
- }
- @Override
- public int hashCode() {
- return Objects.hash(this.getDistributionId(), this.getServiceModelVersionId());
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("distributionId", getDistributionId())
- .append("serviceModelVersionId", getServiceModelVersionId()).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("distributionId", getDistributionId())
+ .append("serviceModelVersionId", getServiceModelVersionId()).toString();
+ }
-
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java
index 9c29d968c9..f2ff6fac00 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java
@@ -26,11 +26,9 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-
import javax.annotation.PostConstruct;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
-
import org.apache.http.HttpStatus;
import org.onap.so.db.request.beans.ArchivedInfraRequests;
import org.onap.so.db.request.beans.InfraActiveRequests;
@@ -59,7 +57,6 @@ import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
-
import uk.co.blackpepper.bowman.ClientFactory;
import uk.co.blackpepper.bowman.Configuration;
@@ -67,100 +64,112 @@ import uk.co.blackpepper.bowman.Configuration;
@Primary
public class RequestsDbClient {
- private static final String SERVICE_ID = "SERVICE_ID";
- private static final String OPERATION_ID = "OPERATION_ID";
- private static final String SO_REQUEST_ID = "SO_REQUEST_ID";
- private static final String REQUEST_ID = "REQUEST_ID";
- private static final String OPERATIONAL_ENVIRONMENT_ID = "OPERATIONAL_ENV_ID";
- private static final String SERVICE_MODEL_VERSION_ID = "SERVICE_MODEL_VERSION_ID";
-
-
- @Value("${mso.adapters.requestDb.endpoint}")
- protected String endpoint;
-
- @Value("${mso.adapters.requestDb.auth}")
- private String msoAdaptersAuth;
-
- private String getOrchestrationFilterURI = "/infraActiveRequests/getOrchestrationFiltersFromInfraActive/";
- private static final String OPERATION_STATUS_SEARCH = "/operationStatus/search";
- private static final String OPERATIONAL_ENV_SERVICE_MODEL_STATUS_SEARCH = "/operationalEnvServiceModelStatus/search";
-
-
- private String checkVnfIdStatus = "/infraActiveRequests/checkVnfIdStatus/";
-
- private String infraActiveRequestURI = "/infraActiveRequests/";
-
- private String checkInstanceNameDuplicate = "/infraActiveRequests/checkInstanceNameDuplicate";
-
- private String operationalEnvDistributionStatusURI = "/operationalEnvDistributionStatus/";
-
- private String findOneByServiceIdAndOperationIdURI = "/findOneByServiceIdAndOperationId";
-
- private String findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestIdURI = "/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId";
-
- private String findAllByOperationalEnvIdAndRequestIdURI = "/findAllByOperationalEnvIdAndRequestId";
-
- private String cloudOrchestrationFiltersFromInfraActive = "/infraActiveRequests/getCloudOrchestrationFiltersFromInfraActive";
-
- private String requestProcessingDataURI = "/requestProcessingData";
-
- private final String findBySoRequestIdOrderByGroupingIdDesc = "/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc";
-
-
- @Autowired
- protected RestTemplate restTemplate;
-
- @Autowired
- ClassURLMapper classURLMapper;
-
- @PostConstruct
- public void init() {
- getOrchestrationFilterURI = endpoint + getOrchestrationFilterURI;
- infraActiveRequestURI = endpoint + infraActiveRequestURI;
- checkVnfIdStatus = endpoint + checkVnfIdStatus;
- checkInstanceNameDuplicate = endpoint + checkInstanceNameDuplicate;
- cloudOrchestrationFiltersFromInfraActive = endpoint + cloudOrchestrationFiltersFromInfraActive;
- findOneByServiceIdAndOperationIdURI = endpoint + OPERATION_STATUS_SEARCH + findOneByServiceIdAndOperationIdURI;
- requestProcessingDataURI = endpoint + requestProcessingDataURI;
- operationalEnvDistributionStatusURI = endpoint + operationalEnvDistributionStatusURI;
- findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestIdURI = endpoint + OPERATIONAL_ENV_SERVICE_MODEL_STATUS_SEARCH + findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestIdURI;
- findAllByOperationalEnvIdAndRequestIdURI = endpoint + OPERATIONAL_ENV_SERVICE_MODEL_STATUS_SEARCH + findAllByOperationalEnvIdAndRequestIdURI;
- }
-
- private ClientFactory getClientFactory(){
- URI baseUri = UriBuilder.fromUri(endpoint).build();
- ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory());
-
- return Configuration.builder().setBaseUri(baseUri).setClientHttpRequestFactory(factory).setRestTemplateConfigurer(restTemplate -> {
- restTemplate.getInterceptors().add((new SpringClientFilter()));
-
- restTemplate.getInterceptors().add((request, body, execution) -> {
-
- request.getHeaders().add(HttpHeaders.AUTHORIZATION, msoAdaptersAuth);
- return execution.execute(request, body);
- });
- }).build().buildClientFactory();
- }
-
-
- public List<InfraActiveRequests> getCloudOrchestrationFiltersFromInfraActive(Map<String, String> orchestrationMap){
- URI uri = getUri(cloudOrchestrationFiltersFromInfraActive);
- HttpHeaders headers = getHttpHeaders();
- HttpEntity<Map> entity = new HttpEntity<>(orchestrationMap, headers);
- try{
- return restTemplate.exchange(uri, HttpMethod.POST, entity, new ParameterizedTypeReference<List<InfraActiveRequests>>() {}).getBody();
- }catch(HttpClientErrorException e){
- if(HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()){
- return null;
- }
- throw e;
- }
- }
+ private static final String SERVICE_ID = "SERVICE_ID";
+ private static final String OPERATION_ID = "OPERATION_ID";
+ private static final String SO_REQUEST_ID = "SO_REQUEST_ID";
+ private static final String REQUEST_ID = "REQUEST_ID";
+ private static final String OPERATIONAL_ENVIRONMENT_ID = "OPERATIONAL_ENV_ID";
+ private static final String SERVICE_MODEL_VERSION_ID = "SERVICE_MODEL_VERSION_ID";
+
+
+ @Value("${mso.adapters.requestDb.endpoint}")
+ protected String endpoint;
+
+ @Value("${mso.adapters.requestDb.auth}")
+ private String msoAdaptersAuth;
+
+ private String getOrchestrationFilterURI = "/infraActiveRequests/getOrchestrationFiltersFromInfraActive/";
+ private static final String OPERATION_STATUS_SEARCH = "/operationStatus/search";
+ private static final String OPERATIONAL_ENV_SERVICE_MODEL_STATUS_SEARCH =
+ "/operationalEnvServiceModelStatus/search";
+
+
+ private String checkVnfIdStatus = "/infraActiveRequests/checkVnfIdStatus/";
+
+ private String infraActiveRequestURI = "/infraActiveRequests/";
+
+ private String checkInstanceNameDuplicate = "/infraActiveRequests/checkInstanceNameDuplicate";
+
+ private String operationalEnvDistributionStatusURI = "/operationalEnvDistributionStatus/";
+
+ private String findOneByServiceIdAndOperationIdURI = "/findOneByServiceIdAndOperationId";
+
+ private String findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestIdURI =
+ "/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId";
+
+ private String findAllByOperationalEnvIdAndRequestIdURI = "/findAllByOperationalEnvIdAndRequestId";
+
+ private String cloudOrchestrationFiltersFromInfraActive =
+ "/infraActiveRequests/getCloudOrchestrationFiltersFromInfraActive";
+
+ private String requestProcessingDataURI = "/requestProcessingData";
+
+ private final String findBySoRequestIdOrderByGroupingIdDesc =
+ "/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc";
+
+
+ @Autowired
+ protected RestTemplate restTemplate;
+
+ @Autowired
+ ClassURLMapper classURLMapper;
+
+ @PostConstruct
+ public void init() {
+ getOrchestrationFilterURI = endpoint + getOrchestrationFilterURI;
+ infraActiveRequestURI = endpoint + infraActiveRequestURI;
+ checkVnfIdStatus = endpoint + checkVnfIdStatus;
+ checkInstanceNameDuplicate = endpoint + checkInstanceNameDuplicate;
+ cloudOrchestrationFiltersFromInfraActive = endpoint + cloudOrchestrationFiltersFromInfraActive;
+ findOneByServiceIdAndOperationIdURI = endpoint + OPERATION_STATUS_SEARCH + findOneByServiceIdAndOperationIdURI;
+ requestProcessingDataURI = endpoint + requestProcessingDataURI;
+ operationalEnvDistributionStatusURI = endpoint + operationalEnvDistributionStatusURI;
+ findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestIdURI =
+ endpoint + OPERATIONAL_ENV_SERVICE_MODEL_STATUS_SEARCH
+ + findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestIdURI;
+ findAllByOperationalEnvIdAndRequestIdURI =
+ endpoint + OPERATIONAL_ENV_SERVICE_MODEL_STATUS_SEARCH + findAllByOperationalEnvIdAndRequestIdURI;
+ }
+
+ private ClientFactory getClientFactory() {
+ URI baseUri = UriBuilder.fromUri(endpoint).build();
+ ClientHttpRequestFactory factory =
+ new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory());
+
+ return Configuration.builder().setBaseUri(baseUri).setClientHttpRequestFactory(factory)
+ .setRestTemplateConfigurer(restTemplate -> {
+ restTemplate.getInterceptors().add((new SpringClientFilter()));
+
+ restTemplate.getInterceptors().add((request, body, execution) -> {
+
+ request.getHeaders().add(HttpHeaders.AUTHORIZATION, msoAdaptersAuth);
+ return execution.execute(request, body);
+ });
+ }).build().buildClientFactory();
+ }
+
+
+ public List<InfraActiveRequests> getCloudOrchestrationFiltersFromInfraActive(Map<String, String> orchestrationMap) {
+ URI uri = getUri(cloudOrchestrationFiltersFromInfraActive);
+ HttpHeaders headers = getHttpHeaders();
+ HttpEntity<Map> entity = new HttpEntity<>(orchestrationMap, headers);
+ try {
+ return restTemplate.exchange(uri, HttpMethod.POST, entity,
+ new ParameterizedTypeReference<List<InfraActiveRequests>>() {}).getBody();
+ } catch (HttpClientErrorException e) {
+ if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) {
+ return null;
+ }
+ throw e;
+ }
+ }
public InfraActiveRequests getInfraActiveRequestbyRequestId(String requestId) {
try {
- HttpEntity<?> entity = getHttpEntity();
- InfraActiveRequests infraActiveRequests = restTemplate.exchange(getUri(endpoint + "/infraActiveRequests/" + requestId), HttpMethod.GET, entity, InfraActiveRequests.class).getBody();
+ HttpEntity<?> entity = getHttpEntity();
+ InfraActiveRequests infraActiveRequests =
+ restTemplate.exchange(getUri(endpoint + "/infraActiveRequests/" + requestId), HttpMethod.GET,
+ entity, InfraActiveRequests.class).getBody();
if (infraActiveRequests != null) {
infraActiveRequests.setRequestId(requestId);
}
@@ -173,208 +182,217 @@ public class RequestsDbClient {
}
}
- public List<InfraActiveRequests> getOrchestrationFiltersFromInfraActive(Map<String, List<String>> orchestrationMap) {
- HttpHeaders headers = getHttpHeaders();
- URI uri = getUri(getOrchestrationFilterURI);
- HttpEntity<Map<String, List<String>>> entity = new HttpEntity<>(orchestrationMap, headers);
- return restTemplate.exchange(uri, HttpMethod.POST, entity, new ParameterizedTypeReference<List<InfraActiveRequests>>() {}).getBody();
- }
-
- public InfraActiveRequests checkVnfIdStatus(String operationalEnvironmentId) {
- HttpEntity<?> entity = getHttpEntity();
- URI uri = getUri(checkVnfIdStatus + operationalEnvironmentId);
- return restTemplate.exchange(uri, HttpMethod.GET, entity, InfraActiveRequests.class).getBody();
- }
-
- public InfraActiveRequests checkInstanceNameDuplicate(HashMap<String, String> instanceIdMap, String instanceName, String requestScope) {
- HttpHeaders headers = getHttpHeaders();
- URI uri = getUri(checkInstanceNameDuplicate);
- HttpEntity<InstanceNameDuplicateCheckRequest> entity = new HttpEntity<>(new InstanceNameDuplicateCheckRequest(instanceIdMap, instanceName, requestScope), headers);
- try{
- ResponseEntity<InfraActiveRequests> response = restTemplate.exchange(uri, HttpMethod.POST, entity, InfraActiveRequests.class);
- if(response != null && response.hasBody()) {
- return restTemplate.exchange(uri, HttpMethod.POST, entity, InfraActiveRequests.class).getBody();
- } else {
- return null;
- }
- }catch(HttpClientErrorException e){
- if(HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()){
- return null;
- }
- throw e;
- }
-
- }
-
- public OperationStatus getOneByServiceIdAndOperationId(String serviceId, String operationId) {
- try {
- HttpEntity<?> entity = getHttpEntity();
- OperationStatus operationStatus = restTemplate.exchange(getUri(UriBuilder.fromUri(getUri(findOneByServiceIdAndOperationIdURI))
- .queryParam(SERVICE_ID, serviceId)
- .queryParam(OPERATION_ID, operationId)
- .build().toString()), HttpMethod.GET, entity, OperationStatus.class).getBody();
- if (operationStatus != null) {
- operationStatus.setServiceId(serviceId);
- operationStatus.setOperationId(operationId);
- }
-
- return operationStatus;
- } catch (HttpClientErrorException e) {
- if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) {
- return null;
- }
- throw e;
- }
- }
-
- public OperationalEnvServiceModelStatus findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId(String operationalEnvironmentId, String serviceModelVersionId, String requestId) {
- try {
- HttpEntity<?> entity = getHttpEntity();
- OperationalEnvServiceModelStatus modelStatus = restTemplate.exchange(getUri(UriBuilder.fromUri(findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestIdURI)
- .queryParam(OPERATIONAL_ENVIRONMENT_ID, operationalEnvironmentId)
- .queryParam(SERVICE_MODEL_VERSION_ID, serviceModelVersionId)
- .queryParam(REQUEST_ID, requestId)
- .build().toString()), HttpMethod.GET, entity, OperationalEnvServiceModelStatus.class).getBody();
- if (null != modelStatus) {
- modelStatus.setOperationalEnvId(operationalEnvironmentId);
- modelStatus.setServiceModelVersionId(serviceModelVersionId);
- modelStatus.setRequestId(requestId);
- }
- return modelStatus;
- }catch(HttpClientErrorException e){
- if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) {
- return null;
- }
- throw e;
- }
- }
-
- public List<OperationalEnvServiceModelStatus> getAllByOperationalEnvIdAndRequestId(String operationalEnvironmentId, String requestId){
- return this.getMultipleOperationalEnvServiceModelStatus(getUri(UriBuilder.fromUri(findAllByOperationalEnvIdAndRequestIdURI)
- .queryParam(OPERATIONAL_ENVIRONMENT_ID,operationalEnvironmentId)
- .queryParam(REQUEST_ID,requestId)
- .build().toString()));
- }
-
- public OperationalEnvDistributionStatus getDistributionStatusById(String distributionId){
- try {
- HttpEntity<?> entity = getHttpEntity();
- OperationalEnvDistributionStatus distributionStatus = restTemplate.exchange(getUri(operationalEnvDistributionStatusURI + distributionId),
- HttpMethod.GET, entity, OperationalEnvDistributionStatus.class).getBody();
- if(null != distributionStatus){
- distributionStatus.setDistributionId(distributionId);
- }
- return distributionStatus;
- }catch(HttpClientErrorException e){
- if(HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()){
- return null;
- }
- throw e;
- }
- }
-
- private List<OperationalEnvServiceModelStatus> getMultipleOperationalEnvServiceModelStatus(URI uri){
- Iterable <OperationalEnvServiceModelStatus> iterable = getClientFactory().create(OperationalEnvServiceModelStatus.class).getAll(uri);
- List<OperationalEnvServiceModelStatus> serviceModelStatuses = new ArrayList<>();
- Iterator<OperationalEnvServiceModelStatus> statusIterator = iterable.iterator();
- statusIterator.forEachRemaining(serviceModelStatuses::add);
- return serviceModelStatuses;
- }
-
- public void save(InfraActiveRequests infraActiveRequests) {
- HttpHeaders headers = getHttpHeaders();
- URI uri = getUri(infraActiveRequestURI);
- HttpEntity<InfraActiveRequests> entity = new HttpEntity<>(infraActiveRequests, headers);
- restTemplate.postForLocation(uri, entity);
- }
-
- public <T> void save(T object){
- HttpHeaders headers = getHttpHeaders();
- URI uri = getUri(endpoint+classURLMapper.getURI(object.getClass()));
- HttpEntity<T> entity = new HttpEntity<>(object, headers);
- restTemplate.postForLocation(uri, entity);
- }
-
- public void updateInfraActiveRequests(InfraActiveRequests request) {
- HttpHeaders headers = getHttpHeaders();
- URI uri = getUri(infraActiveRequestURI+request.getRequestId());
- HttpEntity<InfraActiveRequests> entity = new HttpEntity<>(request, headers);
- restTemplate.put(uri, entity);
- }
-
- protected URI getUri(String uri) {
- return URI.create(uri);
- }
-
- public void saveRequestProcessingData(RequestProcessingData requestProcessingData) {
- HttpHeaders headers = getHttpHeaders();
- URI uri = getUri(requestProcessingDataURI);
- HttpEntity<RequestProcessingData> entity = new HttpEntity<>(requestProcessingData, headers);
- restTemplate.postForLocation(uri, entity);
- }
-
- public List<RequestProcessingData> getRequestProcessingDataBySoRequestId(String soRequestId) {
- return this.getRequestProcessingData(getUri(UriBuilder.fromUri(endpoint + findBySoRequestIdOrderByGroupingIdDesc)
- .queryParam(SO_REQUEST_ID,soRequestId)
- .build().toString()));
- }
-
- private List<RequestProcessingData> getRequestProcessingData(URI uri) {
- Iterable<RequestProcessingData> requestProcessingDataIterator = getClientFactory().create(RequestProcessingData.class).getAll(uri);
- List<RequestProcessingData> requestProcessingDataList = new ArrayList<>();
- Iterator<RequestProcessingData> it = requestProcessingDataIterator.iterator();
- it.forEachRemaining(requestProcessingDataList::add);
- return requestProcessingDataList;
- }
-
- @Component
- static class ClassURLMapper {
- private static final Map <Class,String> classURLMap = new HashMap<>();
-
- ClassURLMapper() {
- classURLMap.put(ArchivedInfraRequests.class,"/archivedInfraRequests/");
- classURLMap.put(InfraActiveRequests.class,"/infraActiveRequests/");
- classURLMap.put(OperationalEnvDistributionStatus.class,"/operationalEnvDistributionStatus/");
- classURLMap.put(OperationalEnvServiceModelStatus.class,"/operationalEnvServiceModelStatus/");
- classURLMap.put(OperationStatus.class,"/operationStatus/");
- classURLMap.put(ResourceOperationStatus.class,"/resourceOperationStatus/");
- classURLMap.put(SiteStatus.class,"/siteStatus/");
- classURLMap.put(WatchdogComponentDistributionStatus.class,"/watchdogComponentDistributionStatus/");
- classURLMap.put(WatchdogDistributionStatus.class,"/watchdogDistributionStatus/");
- classURLMap.put(WatchdogServiceModVerIdLookup.class,"/watchdogServiceModVerIdLookup/");
- }
-
- <T> String getURI(Class<T> className) {
- Class actualClass = classURLMap.keySet()
- .stream()
- .filter(requestdbClass -> requestdbClass.isAssignableFrom(className))
- .findFirst()
- .get();
- return classURLMap.get(actualClass);
- }
- }
-
- //USED FOR TEST ONLY
- public void setPortToEndpoint(String port) {
- endpoint = endpoint + port;
- }
-
- //USED FOR TEST ONLY
- public void removePortFromEndpoint() {
- endpoint = endpoint.substring(0, endpoint.lastIndexOf(':') + 1);
- }
-
- private HttpHeaders getHttpHeaders() {
- HttpHeaders headers = new HttpHeaders();
- headers.set(HttpHeaders.AUTHORIZATION, msoAdaptersAuth);
- headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
- headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
- return headers;
- }
-
- private HttpEntity<?> getHttpEntity() {
- HttpHeaders headers = getHttpHeaders();
- return new HttpEntity<>(headers);
- }
+ public List<InfraActiveRequests> getOrchestrationFiltersFromInfraActive(
+ Map<String, List<String>> orchestrationMap) {
+ HttpHeaders headers = getHttpHeaders();
+ URI uri = getUri(getOrchestrationFilterURI);
+ HttpEntity<Map<String, List<String>>> entity = new HttpEntity<>(orchestrationMap, headers);
+ return restTemplate
+ .exchange(uri, HttpMethod.POST, entity, new ParameterizedTypeReference<List<InfraActiveRequests>>() {})
+ .getBody();
+ }
+
+ public InfraActiveRequests checkVnfIdStatus(String operationalEnvironmentId) {
+ HttpEntity<?> entity = getHttpEntity();
+ URI uri = getUri(checkVnfIdStatus + operationalEnvironmentId);
+ return restTemplate.exchange(uri, HttpMethod.GET, entity, InfraActiveRequests.class).getBody();
+ }
+
+ public InfraActiveRequests checkInstanceNameDuplicate(HashMap<String, String> instanceIdMap, String instanceName,
+ String requestScope) {
+ HttpHeaders headers = getHttpHeaders();
+ URI uri = getUri(checkInstanceNameDuplicate);
+ HttpEntity<InstanceNameDuplicateCheckRequest> entity = new HttpEntity<>(
+ new InstanceNameDuplicateCheckRequest(instanceIdMap, instanceName, requestScope), headers);
+ try {
+ ResponseEntity<InfraActiveRequests> response =
+ restTemplate.exchange(uri, HttpMethod.POST, entity, InfraActiveRequests.class);
+ if (response != null && response.hasBody()) {
+ return restTemplate.exchange(uri, HttpMethod.POST, entity, InfraActiveRequests.class).getBody();
+ } else {
+ return null;
+ }
+ } catch (HttpClientErrorException e) {
+ if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) {
+ return null;
+ }
+ throw e;
+ }
+
+ }
+
+ public OperationStatus getOneByServiceIdAndOperationId(String serviceId, String operationId) {
+ try {
+ HttpEntity<?> entity = getHttpEntity();
+ OperationStatus operationStatus = restTemplate.exchange(getUri(
+ UriBuilder.fromUri(getUri(findOneByServiceIdAndOperationIdURI)).queryParam(SERVICE_ID, serviceId)
+ .queryParam(OPERATION_ID, operationId).build().toString()),
+ HttpMethod.GET, entity, OperationStatus.class).getBody();
+ if (operationStatus != null) {
+ operationStatus.setServiceId(serviceId);
+ operationStatus.setOperationId(operationId);
+ }
+
+ return operationStatus;
+ } catch (HttpClientErrorException e) {
+ if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) {
+ return null;
+ }
+ throw e;
+ }
+ }
+
+ public OperationalEnvServiceModelStatus findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId(
+ String operationalEnvironmentId, String serviceModelVersionId, String requestId) {
+ try {
+ HttpEntity<?> entity = getHttpEntity();
+ OperationalEnvServiceModelStatus modelStatus = restTemplate.exchange(
+ getUri(UriBuilder.fromUri(findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestIdURI)
+ .queryParam(OPERATIONAL_ENVIRONMENT_ID, operationalEnvironmentId)
+ .queryParam(SERVICE_MODEL_VERSION_ID, serviceModelVersionId)
+ .queryParam(REQUEST_ID, requestId).build().toString()),
+ HttpMethod.GET, entity, OperationalEnvServiceModelStatus.class).getBody();
+ if (null != modelStatus) {
+ modelStatus.setOperationalEnvId(operationalEnvironmentId);
+ modelStatus.setServiceModelVersionId(serviceModelVersionId);
+ modelStatus.setRequestId(requestId);
+ }
+ return modelStatus;
+ } catch (HttpClientErrorException e) {
+ if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) {
+ return null;
+ }
+ throw e;
+ }
+ }
+
+ public List<OperationalEnvServiceModelStatus> getAllByOperationalEnvIdAndRequestId(String operationalEnvironmentId,
+ String requestId) {
+ return this.getMultipleOperationalEnvServiceModelStatus(
+ getUri(UriBuilder.fromUri(findAllByOperationalEnvIdAndRequestIdURI)
+ .queryParam(OPERATIONAL_ENVIRONMENT_ID, operationalEnvironmentId)
+ .queryParam(REQUEST_ID, requestId).build().toString()));
+ }
+
+ public OperationalEnvDistributionStatus getDistributionStatusById(String distributionId) {
+ try {
+ HttpEntity<?> entity = getHttpEntity();
+ OperationalEnvDistributionStatus distributionStatus =
+ restTemplate.exchange(getUri(operationalEnvDistributionStatusURI + distributionId), HttpMethod.GET,
+ entity, OperationalEnvDistributionStatus.class).getBody();
+ if (null != distributionStatus) {
+ distributionStatus.setDistributionId(distributionId);
+ }
+ return distributionStatus;
+ } catch (HttpClientErrorException e) {
+ if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) {
+ return null;
+ }
+ throw e;
+ }
+ }
+
+ private List<OperationalEnvServiceModelStatus> getMultipleOperationalEnvServiceModelStatus(URI uri) {
+ Iterable<OperationalEnvServiceModelStatus> iterable =
+ getClientFactory().create(OperationalEnvServiceModelStatus.class).getAll(uri);
+ List<OperationalEnvServiceModelStatus> serviceModelStatuses = new ArrayList<>();
+ Iterator<OperationalEnvServiceModelStatus> statusIterator = iterable.iterator();
+ statusIterator.forEachRemaining(serviceModelStatuses::add);
+ return serviceModelStatuses;
+ }
+
+ public void save(InfraActiveRequests infraActiveRequests) {
+ HttpHeaders headers = getHttpHeaders();
+ URI uri = getUri(infraActiveRequestURI);
+ HttpEntity<InfraActiveRequests> entity = new HttpEntity<>(infraActiveRequests, headers);
+ restTemplate.postForLocation(uri, entity);
+ }
+
+ public <T> void save(T object) {
+ HttpHeaders headers = getHttpHeaders();
+ URI uri = getUri(endpoint + classURLMapper.getURI(object.getClass()));
+ HttpEntity<T> entity = new HttpEntity<>(object, headers);
+ restTemplate.postForLocation(uri, entity);
+ }
+
+ public void updateInfraActiveRequests(InfraActiveRequests request) {
+ HttpHeaders headers = getHttpHeaders();
+ URI uri = getUri(infraActiveRequestURI + request.getRequestId());
+ HttpEntity<InfraActiveRequests> entity = new HttpEntity<>(request, headers);
+ restTemplate.put(uri, entity);
+ }
+
+ protected URI getUri(String uri) {
+ return URI.create(uri);
+ }
+
+ public void saveRequestProcessingData(RequestProcessingData requestProcessingData) {
+ HttpHeaders headers = getHttpHeaders();
+ URI uri = getUri(requestProcessingDataURI);
+ HttpEntity<RequestProcessingData> entity = new HttpEntity<>(requestProcessingData, headers);
+ restTemplate.postForLocation(uri, entity);
+ }
+
+ public List<RequestProcessingData> getRequestProcessingDataBySoRequestId(String soRequestId) {
+ return this
+ .getRequestProcessingData(getUri(UriBuilder.fromUri(endpoint + findBySoRequestIdOrderByGroupingIdDesc)
+ .queryParam(SO_REQUEST_ID, soRequestId).build().toString()));
+ }
+
+ private List<RequestProcessingData> getRequestProcessingData(URI uri) {
+ Iterable<RequestProcessingData> requestProcessingDataIterator =
+ getClientFactory().create(RequestProcessingData.class).getAll(uri);
+ List<RequestProcessingData> requestProcessingDataList = new ArrayList<>();
+ Iterator<RequestProcessingData> it = requestProcessingDataIterator.iterator();
+ it.forEachRemaining(requestProcessingDataList::add);
+ return requestProcessingDataList;
+ }
+
+ @Component
+ static class ClassURLMapper {
+ private static final Map<Class, String> classURLMap = new HashMap<>();
+
+ ClassURLMapper() {
+ classURLMap.put(ArchivedInfraRequests.class, "/archivedInfraRequests/");
+ classURLMap.put(InfraActiveRequests.class, "/infraActiveRequests/");
+ classURLMap.put(OperationalEnvDistributionStatus.class, "/operationalEnvDistributionStatus/");
+ classURLMap.put(OperationalEnvServiceModelStatus.class, "/operationalEnvServiceModelStatus/");
+ classURLMap.put(OperationStatus.class, "/operationStatus/");
+ classURLMap.put(ResourceOperationStatus.class, "/resourceOperationStatus/");
+ classURLMap.put(SiteStatus.class, "/siteStatus/");
+ classURLMap.put(WatchdogComponentDistributionStatus.class, "/watchdogComponentDistributionStatus/");
+ classURLMap.put(WatchdogDistributionStatus.class, "/watchdogDistributionStatus/");
+ classURLMap.put(WatchdogServiceModVerIdLookup.class, "/watchdogServiceModVerIdLookup/");
+ }
+
+ <T> String getURI(Class<T> className) {
+ Class actualClass = classURLMap.keySet().stream()
+ .filter(requestdbClass -> requestdbClass.isAssignableFrom(className)).findFirst().get();
+ return classURLMap.get(actualClass);
+ }
+ }
+
+ // USED FOR TEST ONLY
+ public void setPortToEndpoint(String port) {
+ endpoint = endpoint + port;
+ }
+
+ // USED FOR TEST ONLY
+ public void removePortFromEndpoint() {
+ endpoint = endpoint.substring(0, endpoint.lastIndexOf(':') + 1);
+ }
+
+ private HttpHeaders getHttpHeaders() {
+ HttpHeaders headers = new HttpHeaders();
+ headers.set(HttpHeaders.AUTHORIZATION, msoAdaptersAuth);
+ headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
+ headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
+ return headers;
+ }
+
+ private HttpEntity<?> getHttpEntity() {
+ HttpHeaders headers = getHttpHeaders();
+ return new HttpEntity<>(headers);
+ }
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/data/controller/InstanceNameDuplicateCheckRequest.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/data/controller/InstanceNameDuplicateCheckRequest.java
index a6f283a264..548bc25815 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/data/controller/InstanceNameDuplicateCheckRequest.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/data/controller/InstanceNameDuplicateCheckRequest.java
@@ -28,10 +28,10 @@ public class InstanceNameDuplicateCheckRequest {
private String instanceName;
private String requestScope;
- public InstanceNameDuplicateCheckRequest() {
- }
+ public InstanceNameDuplicateCheckRequest() {}
- public InstanceNameDuplicateCheckRequest(HashMap<String, String> instanceIdMap, String instanceName, String requestScope) {
+ public InstanceNameDuplicateCheckRequest(HashMap<String, String> instanceIdMap, String instanceName,
+ String requestScope) {
this.instanceIdMap = instanceIdMap;
this.instanceName = instanceName;
this.requestScope = requestScope;
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/exceptions/NoEntityFoundException.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/exceptions/NoEntityFoundException.java
index 76418629e1..7f00c42038 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/exceptions/NoEntityFoundException.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/exceptions/NoEntityFoundException.java
@@ -19,6 +19,7 @@
*/
package org.onap.so.db.request.exceptions;
+
public class NoEntityFoundException extends Exception {
/**
@@ -27,7 +28,7 @@ public class NoEntityFoundException extends Exception {
private static final long serialVersionUID = 545820289784366486L;
public NoEntityFoundException(String errorMessage) {
- super(errorMessage);
+ super(errorMessage);
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/RequestsDBHelper.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/RequestsDBHelper.java
index da72ef985c..e4464450ea 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/RequestsDBHelper.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/RequestsDBHelper.java
@@ -23,7 +23,6 @@
package org.onap.so.requestsdb;
import java.sql.Timestamp;
-
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.db.request.client.RequestsDbClient;
import org.slf4j.Logger;
@@ -34,79 +33,84 @@ import org.springframework.stereotype.Component;
@Component
public class RequestsDBHelper {
-
- private static final String UNKNOWN = "UNKNOWN";
- private static Logger logger = LoggerFactory.getLogger(RequestsDBHelper.class);
- private String className = this.getClass().getSimpleName() +" class\'s ";
- private String methodName = "";
- private String classMethodMessage = "";
- @Autowired
- @Qualifier("RequestsDbClient")
- private RequestsDbClient requestsDbClient;
- /**
- * This util method is to update the InfraRequest table to Complete
- * @param msg - string, unique message for each caller
- * @param requestId - string
- * @param operationalEnvironmentId - string
- * @return void - nothing
- * @throws Exception
- */
- public void updateInfraSuccessCompletion(String msg, String requestId, String operationalEnvironmentId) {
- methodName = "updateInfraSuccessCompletion() method.";
- classMethodMessage = className + " " + methodName;
- logger.debug("Begin of {}", classMethodMessage);
-
- InfraActiveRequests request = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
-
- request.setRequestStatus("COMPLETE");
- request.setStatusMessage("SUCCESSFUL, operationalEnvironmentId - " + operationalEnvironmentId + "; Success Message: " + msg);
- request.setProgress(100L);
- request.setLastModifiedBy("APIH");
- request.setOperationalEnvId(operationalEnvironmentId);
- if(request.getAction() == null){
- request.setRequestAction(UNKNOWN);
- }
- if(request.getRequestScope() == null){
- request.setRequestScope(UNKNOWN);
- }
- Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
+
+ private static final String UNKNOWN = "UNKNOWN";
+ private static Logger logger = LoggerFactory.getLogger(RequestsDBHelper.class);
+ private String className = this.getClass().getSimpleName() + " class\'s ";
+ private String methodName = "";
+ private String classMethodMessage = "";
+ @Autowired
+ @Qualifier("RequestsDbClient")
+ private RequestsDbClient requestsDbClient;
+
+ /**
+ * This util method is to update the InfraRequest table to Complete
+ *
+ * @param msg - string, unique message for each caller
+ * @param requestId - string
+ * @param operationalEnvironmentId - string
+ * @return void - nothing
+ * @throws Exception
+ */
+ public void updateInfraSuccessCompletion(String msg, String requestId, String operationalEnvironmentId) {
+ methodName = "updateInfraSuccessCompletion() method.";
+ classMethodMessage = className + " " + methodName;
+ logger.debug("Begin of {}", classMethodMessage);
+
+ InfraActiveRequests request = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
+
+ request.setRequestStatus("COMPLETE");
+ request.setStatusMessage(
+ "SUCCESSFUL, operationalEnvironmentId - " + operationalEnvironmentId + "; Success Message: " + msg);
+ request.setProgress(100L);
+ request.setLastModifiedBy("APIH");
+ request.setOperationalEnvId(operationalEnvironmentId);
+ if (request.getAction() == null) {
+ request.setRequestAction(UNKNOWN);
+ }
+ if (request.getRequestScope() == null) {
+ request.setRequestScope(UNKNOWN);
+ }
+ Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
request.setEndTime(endTimeStamp);
- requestsDbClient.save(request);
-
- logger.debug("End of {}", classMethodMessage);
-
- }
-
- /**
- * This util method is to update the InfraRequest table to Failure
- * @param msg - string, unique message for each caller
- * @param requestId - string
- * @param operationalEnvironmentId - string
- * @return void - nothing
- * @throws Exception
- */
- public void updateInfraFailureCompletion(String msg, String requestId, String operationalEnvironmentId) {
- methodName = "updateInfraFailureCompletion() method.";
- classMethodMessage = className + " " + methodName;
- logger.debug("Begin of {}", classMethodMessage);
-
- InfraActiveRequests request = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
- request.setRequestStatus("FAILED");
- request.setStatusMessage("FAILURE, operationalEnvironmentId - " + operationalEnvironmentId + "; Error message: " + msg);
- request.setProgress(100L);
- request.setLastModifiedBy("APIH");
- request.setOperationalEnvId(operationalEnvironmentId);
- if(request.getAction() == null){
- request.setRequestAction(UNKNOWN);
- }
- if(request.getRequestScope() == null){
- request.setRequestScope(UNKNOWN);
- }
- Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
+ requestsDbClient.save(request);
+
+ logger.debug("End of {}", classMethodMessage);
+
+ }
+
+ /**
+ * This util method is to update the InfraRequest table to Failure
+ *
+ * @param msg - string, unique message for each caller
+ * @param requestId - string
+ * @param operationalEnvironmentId - string
+ * @return void - nothing
+ * @throws Exception
+ */
+ public void updateInfraFailureCompletion(String msg, String requestId, String operationalEnvironmentId) {
+ methodName = "updateInfraFailureCompletion() method.";
+ classMethodMessage = className + " " + methodName;
+ logger.debug("Begin of {}", classMethodMessage);
+
+ InfraActiveRequests request = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
+ request.setRequestStatus("FAILED");
+ request.setStatusMessage(
+ "FAILURE, operationalEnvironmentId - " + operationalEnvironmentId + "; Error message: " + msg);
+ request.setProgress(100L);
+ request.setLastModifiedBy("APIH");
+ request.setOperationalEnvId(operationalEnvironmentId);
+ if (request.getAction() == null) {
+ request.setRequestAction(UNKNOWN);
+ }
+ if (request.getRequestScope() == null) {
+ request.setRequestScope(UNKNOWN);
+ }
+ Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
request.setEndTime(endTimeStamp);
- requestsDbClient.save(request);
-
- logger.debug("End of {}", classMethodMessage);
-
- }
+ requestsDbClient.save(request);
+
+ logger.debug("End of {}", classMethodMessage);
+
+ }
}
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/RequestsDbConstant.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/RequestsDbConstant.java
index 60bad3791c..deb4ab96bb 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/RequestsDbConstant.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/RequestsDbConstant.java
@@ -21,13 +21,12 @@
package org.onap.so.requestsdb;
/**
- * The constants of the request db
- * <br>
+ * The constants of the request db <br>
* <p>
* </p>
*
* @author
- * @version ONAP Amsterdam Release 2017-08-28
+ * @version ONAP Amsterdam Release 2017-08-28
*/
public class RequestsDbConstant {
diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/TimestampXMLAdapter.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/TimestampXMLAdapter.java
index 3a326598a7..d1477c0674 100644
--- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/TimestampXMLAdapter.java
+++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/requestsdb/TimestampXMLAdapter.java
@@ -22,21 +22,20 @@ package org.onap.so.requestsdb;
import java.sql.Timestamp;
-
import javax.xml.bind.annotation.adapters.XmlAdapter;
-public class TimestampXMLAdapter extends XmlAdapter <Long, Timestamp> {
+public class TimestampXMLAdapter extends XmlAdapter<Long, Timestamp> {
@Override
- public Long marshal (Timestamp v) throws Exception {
- return v.getTime ();
+ public Long marshal(Timestamp v) throws Exception {
+ return v.getTime();
}
@Override
- public Timestamp unmarshal (Long v) throws Exception {
+ public Timestamp unmarshal(Long v) throws Exception {
if (v == null) {
return new Timestamp(0);
}
- return new Timestamp (v);
+ return new Timestamp(v);
}
}
diff --git a/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/db/request/beans/BeansTest.java b/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/db/request/beans/BeansTest.java
index 3f9443ff4a..4211a5ed47 100644
--- a/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/db/request/beans/BeansTest.java
+++ b/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/db/request/beans/BeansTest.java
@@ -21,16 +21,13 @@
package org.onap.so.db.request.beans;
import static org.onap.so.openpojo.rules.HasAnnotationMatcher.hasAnnotation;
-
import javax.persistence.Temporal;
-
import org.junit.Test;
import org.onap.so.openpojo.rules.CustomSetterMustExistRule;
import org.onap.so.openpojo.rules.EqualsAndHashCodeTester;
import org.onap.so.openpojo.rules.HasEqualsAndHashCodeRule;
import org.onap.so.openpojo.rules.HasToStringRule;
import org.onap.so.openpojo.rules.ToStringTester;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterEnum;
@@ -43,29 +40,24 @@ import com.openpojo.validation.test.impl.SetterTester;
public class BeansTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
-
- @Test
- public void pojoStructure() {
- test("org.onap.so.db.request.beans");
- }
-
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new CustomSetterMustExistRule().exclude(hasAnnotation(Temporal.class)))
- .with(new HasEqualsAndHashCodeRule())
- .with(new HasToStringRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .with(new EqualsAndHashCodeTester())
- .with(new ToStringTester())
- .build();
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, new FilterEnum());
- }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.db.request.beans");
+ }
+
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule())
+ .with(new CustomSetterMustExistRule().exclude(hasAnnotation(Temporal.class)))
+ .with(new HasEqualsAndHashCodeRule()).with(new HasToStringRule()).with(new SetterTester())
+ .with(new GetterTester()).with(new EqualsAndHashCodeTester()).with(new ToStringTester()).build();
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, new FilterEnum());
+ }
+
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpec.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpec.java
index 9fcb1824db..00eff8f0c9 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpec.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpec.java
@@ -4,7 +4,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
@@ -19,13 +18,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@@ -34,142 +30,141 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "ACTIVITY_SPEC")
public class ActivitySpec implements Serializable {
- private static final long serialVersionUID = 6902290480087262973L;
-
- @Id
- @Column(name = "ID", nullable = false, updatable = false)
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer ID;
-
- @BusinessKey
- @Column(name = "NAME")
- private String name;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @BusinessKey
- @Column(name = "VERSION")
- private Double version;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpec")
- private List<WorkflowActivitySpecSequence> workflowActivitySpecSequence;
-
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpec")
- private List<ActivitySpecActivitySpecCategories> activitySpecActivitySpecCategories;
-
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpec")
- private List<ActivitySpecUserParameters> activitySpecUserParameters;
-
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpec")
- private List<ActivitySpecActivitySpecParameters> activitySpecActivitySpecParameters;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public Integer getID() {
- return ID;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
-
- public Double getVersion() {
- return version;
- }
-
- public void setVersion(Double version) {
- this.version = version;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- @LinkedResource
- public List<WorkflowActivitySpecSequence> getWorkflowActivitySpecSequence() {
- return workflowActivitySpecSequence;
- }
-
- public void setWorkflowActivitySpecSequence(
- List<WorkflowActivitySpecSequence> workflowActivitySpecSequence) {
- this.workflowActivitySpecSequence = workflowActivitySpecSequence;
- }
-
- @LinkedResource
- public List<ActivitySpecUserParameters> getActivitySpecUserParameters() {
- return activitySpecUserParameters;
- }
-
- public void setActivitySpecUserParameters(
- List<ActivitySpecUserParameters> activitySpecUserParameters) {
- this.activitySpecUserParameters = activitySpecUserParameters;
- }
-
- @LinkedResource
- public List<ActivitySpecActivitySpecCategories> getActivitySpecActivitySpecCategories() {
- return activitySpecActivitySpecCategories;
- }
-
- public void setActivitySpecActivitySpecCategories(
- List<ActivitySpecActivitySpecCategories> activitySpecActivitySpecCategories) {
- this.activitySpecActivitySpecCategories = activitySpecActivitySpecCategories;
- }
-
- @LinkedResource
- public List<ActivitySpecActivitySpecParameters> getActivitySpecActivitySpecParameters() {
- return activitySpecActivitySpecParameters;
- }
-
- public void setActivitySpecActivitySpecParameters(
- List<ActivitySpecActivitySpecParameters> activitySpecActivitySpecParameters) {
- this.activitySpecActivitySpecParameters = activitySpecActivitySpecParameters;
- }
-
-
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("name", name)
- .append("description", description).append("version", version)
- .append("created", created).append("workflowActivitySpecSequence", workflowActivitySpecSequence)
- .append("activitySpecActivitySpecCategories", activitySpecActivitySpecCategories).toString();
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ActivitySpec)) {
- return false;
- }
- ActivitySpec castOther = (ActivitySpec) other;
- return new EqualsBuilder().append(name, castOther.name).append(version, castOther.version).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(name).append(version).toHashCode();
- }
+ private static final long serialVersionUID = 6902290480087262973L;
+
+ @Id
+ @Column(name = "ID", nullable = false, updatable = false)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer ID;
+
+ @BusinessKey
+ @Column(name = "NAME")
+ private String name;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @BusinessKey
+ @Column(name = "VERSION")
+ private Double version;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpec")
+ private List<WorkflowActivitySpecSequence> workflowActivitySpecSequence;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpec")
+ private List<ActivitySpecActivitySpecCategories> activitySpecActivitySpecCategories;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpec")
+ private List<ActivitySpecUserParameters> activitySpecUserParameters;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpec")
+ private List<ActivitySpecActivitySpecParameters> activitySpecActivitySpecParameters;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+
+ public Double getVersion() {
+ return version;
+ }
+
+ public void setVersion(Double version) {
+ this.version = version;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ @LinkedResource
+ public List<WorkflowActivitySpecSequence> getWorkflowActivitySpecSequence() {
+ return workflowActivitySpecSequence;
+ }
+
+ public void setWorkflowActivitySpecSequence(List<WorkflowActivitySpecSequence> workflowActivitySpecSequence) {
+ this.workflowActivitySpecSequence = workflowActivitySpecSequence;
+ }
+
+ @LinkedResource
+ public List<ActivitySpecUserParameters> getActivitySpecUserParameters() {
+ return activitySpecUserParameters;
+ }
+
+ public void setActivitySpecUserParameters(List<ActivitySpecUserParameters> activitySpecUserParameters) {
+ this.activitySpecUserParameters = activitySpecUserParameters;
+ }
+
+ @LinkedResource
+ public List<ActivitySpecActivitySpecCategories> getActivitySpecActivitySpecCategories() {
+ return activitySpecActivitySpecCategories;
+ }
+
+ public void setActivitySpecActivitySpecCategories(
+ List<ActivitySpecActivitySpecCategories> activitySpecActivitySpecCategories) {
+ this.activitySpecActivitySpecCategories = activitySpecActivitySpecCategories;
+ }
+
+ @LinkedResource
+ public List<ActivitySpecActivitySpecParameters> getActivitySpecActivitySpecParameters() {
+ return activitySpecActivitySpecParameters;
+ }
+
+ public void setActivitySpecActivitySpecParameters(
+ List<ActivitySpecActivitySpecParameters> activitySpecActivitySpecParameters) {
+ this.activitySpecActivitySpecParameters = activitySpecActivitySpecParameters;
+ }
+
+
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("name", name).append("description", description)
+ .append("version", version).append("created", created)
+ .append("workflowActivitySpecSequence", workflowActivitySpecSequence)
+ .append("activitySpecActivitySpecCategories", activitySpecActivitySpecCategories).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ActivitySpec)) {
+ return false;
+ }
+ ActivitySpec castOther = (ActivitySpec) other;
+ return new EqualsBuilder().append(name, castOther.name).append(version, castOther.version).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(name).append(version).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategories.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategories.java
index e18188dff8..3518805b0d 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategories.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategories.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -37,13 +36,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@@ -51,88 +47,86 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "activity_spec_to_activity_spec_categories")
public class ActivitySpecActivitySpecCategories implements Serializable {
- private static final long serialVersionUID = 6228647901909437418L;
-
- @Id
- @Column(name = "ID", nullable = false, updatable = false)
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer ID;
-
- @BusinessKey
- @Id
- @Column(name = "ACTIVITY_SPEC_ID")
- private Integer activitySpecId;
-
- @BusinessKey
- @Id
- @Column(name = "ACTIVITY_SPEC_CATEGORIES_ID")
- private Integer activitySpecCategoriesId;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "ACTIVITY_SPEC_ID", updatable = false, insertable = false)
- private ActivitySpec activitySpec;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "ACTIVITY_SPEC_CATEGORIES_ID", updatable = false, insertable = false)
- private ActivitySpecCategories activitySpecCategories;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this)
- .append("activitySpecId", activitySpecId)
- .append("activitySpecCategoriesId", activitySpecCategoriesId)
- .toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ActivitySpecActivitySpecCategories)) {
- return false;
- }
- ActivitySpecActivitySpecCategories castOther = (ActivitySpecActivitySpecCategories) other;
- return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
- .append(activitySpecCategoriesId, castOther.activitySpecCategoriesId).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(activitySpecId).append(activitySpecCategoriesId).toHashCode();
- }
-
- public Integer getID() {
- return ID;
- }
-
- public Integer getActivitySpecId() {
- return activitySpecId;
- }
-
- public void setActivitySpecId(Integer activitySpecId) {
- this.activitySpecId = activitySpecId;
- }
-
- public Integer getActivitySpecCategoriesId() {
- return activitySpecCategoriesId;
- }
-
- public void setActivitySpecCategoriesId(Integer activitySpecCategoriesId) {
- this.activitySpecCategoriesId = activitySpecCategoriesId;
- }
-
- public ActivitySpec getActivitySpec() {
- return activitySpec;
- }
-
- public void setActivitySpec(ActivitySpec activitySpec) {
- this.activitySpec = activitySpec;
- }
-
- public ActivitySpecCategories getActivitySpecCategories() {
- return activitySpecCategories;
- }
-
- public void setActivitySpecCategories(ActivitySpecCategories activitySpecCategories) {
- this.activitySpecCategories = activitySpecCategories;
- }
+ private static final long serialVersionUID = 6228647901909437418L;
+
+ @Id
+ @Column(name = "ID", nullable = false, updatable = false)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer ID;
+
+ @BusinessKey
+ @Id
+ @Column(name = "ACTIVITY_SPEC_ID")
+ private Integer activitySpecId;
+
+ @BusinessKey
+ @Id
+ @Column(name = "ACTIVITY_SPEC_CATEGORIES_ID")
+ private Integer activitySpecCategoriesId;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "ACTIVITY_SPEC_ID", updatable = false, insertable = false)
+ private ActivitySpec activitySpec;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "ACTIVITY_SPEC_CATEGORIES_ID", updatable = false, insertable = false)
+ private ActivitySpecCategories activitySpecCategories;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("activitySpecId", activitySpecId)
+ .append("activitySpecCategoriesId", activitySpecCategoriesId).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ActivitySpecActivitySpecCategories)) {
+ return false;
+ }
+ ActivitySpecActivitySpecCategories castOther = (ActivitySpecActivitySpecCategories) other;
+ return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
+ .append(activitySpecCategoriesId, castOther.activitySpecCategoriesId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(activitySpecId).append(activitySpecCategoriesId).toHashCode();
+ }
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public Integer getActivitySpecId() {
+ return activitySpecId;
+ }
+
+ public void setActivitySpecId(Integer activitySpecId) {
+ this.activitySpecId = activitySpecId;
+ }
+
+ public Integer getActivitySpecCategoriesId() {
+ return activitySpecCategoriesId;
+ }
+
+ public void setActivitySpecCategoriesId(Integer activitySpecCategoriesId) {
+ this.activitySpecCategoriesId = activitySpecCategoriesId;
+ }
+
+ public ActivitySpec getActivitySpec() {
+ return activitySpec;
+ }
+
+ public void setActivitySpec(ActivitySpec activitySpec) {
+ this.activitySpec = activitySpec;
+ }
+
+ public ActivitySpecCategories getActivitySpecCategories() {
+ return activitySpecCategories;
+ }
+
+ public void setActivitySpecCategories(ActivitySpecCategories activitySpecCategories) {
+ this.activitySpecCategories = activitySpecCategories;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategoriesId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategoriesId.java
index e31c5fcece..e3dcd359ec 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategoriesId.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategoriesId.java
@@ -21,60 +21,62 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
public class ActivitySpecActivitySpecCategoriesId implements Serializable {
-
- private static final long serialVersionUID = 1563771827209840959L;
- private Integer ID;
- @BusinessKey
- private Integer activitySpecId;
- @BusinessKey
- private Integer activitySpecCategoriesId;
-
- public Integer getID() {
- return ID;
- }
- public void setID(Integer iD) {
- ID = iD;
- }
- public Integer getActivitySpecCategoriesId() {
- return activitySpecCategoriesId;
- }
- public void setActivitySpecCategoriesId(Integer activitySpecCategoriesId) {
- this.activitySpecCategoriesId = activitySpecCategoriesId;
- }
- public Integer getActivitySpecId() {
- return activitySpecId;
- }
- public void setActivitySpecId(Integer activitySpecId) {
- this.activitySpecId = activitySpecId;
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("activitySpecId", activitySpecId)
- .append("activitySpecCategoriesId", activitySpecCategoriesId)
- .toString();
- }
+ private static final long serialVersionUID = 1563771827209840959L;
+ private Integer ID;
+ @BusinessKey
+ private Integer activitySpecId;
+ @BusinessKey
+ private Integer activitySpecCategoriesId;
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public void setID(Integer iD) {
+ ID = iD;
+ }
+
+ public Integer getActivitySpecCategoriesId() {
+ return activitySpecCategoriesId;
+ }
+
+ public void setActivitySpecCategoriesId(Integer activitySpecCategoriesId) {
+ this.activitySpecCategoriesId = activitySpecCategoriesId;
+ }
+
+ public Integer getActivitySpecId() {
+ return activitySpecId;
+ }
+
+ public void setActivitySpecId(Integer activitySpecId) {
+ this.activitySpecId = activitySpecId;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("activitySpecId", activitySpecId)
+ .append("activitySpecCategoriesId", activitySpecCategoriesId).toString();
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ActivitySpecActivitySpecCategoriesId)) {
- return false;
- }
- ActivitySpecActivitySpecCategoriesId castOther = (ActivitySpecActivitySpecCategoriesId) other;
- return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
- .append(activitySpecCategoriesId, castOther.activitySpecCategoriesId).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ActivitySpecActivitySpecCategoriesId)) {
+ return false;
+ }
+ ActivitySpecActivitySpecCategoriesId castOther = (ActivitySpecActivitySpecCategoriesId) other;
+ return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
+ .append(activitySpecCategoriesId, castOther.activitySpecCategoriesId).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(activitySpecId).append(activitySpecCategoriesId).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(activitySpecId).append(activitySpecCategoriesId).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParameters.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParameters.java
index 181380244d..f0c9bd99ce 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParameters.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParameters.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -37,13 +36,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@@ -51,88 +47,86 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "activity_spec_to_activity_spec_parameters")
public class ActivitySpecActivitySpecParameters implements Serializable {
- private static final long serialVersionUID = -2036788837696381115L;
-
- @Id
- @Column(name = "ID", nullable = false, updatable = false)
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer ID;
-
- @BusinessKey
- @Id
- @Column(name = "ACTIVITY_SPEC_ID")
- private Integer activitySpecId;
-
- @BusinessKey
- @Id
- @Column(name = "ACTIVITY_SPEC_PARAMETERS_ID")
- private Integer activitySpecParametersId;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "ACTIVITY_SPEC_ID", updatable = false, insertable = false)
- private ActivitySpec activitySpec;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "ACTIVITY_SPEC_PARAMETERS_ID", updatable = false, insertable = false)
- private ActivitySpecParameters activitySpecParameters;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this)
- .append("activitySpecId", activitySpecId)
- .append("activitySpecCategoriesId", activitySpecParametersId)
- .toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ActivitySpecActivitySpecParameters)) {
- return false;
- }
- ActivitySpecActivitySpecParameters castOther = (ActivitySpecActivitySpecParameters) other;
- return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
- .append(activitySpecParametersId, castOther.activitySpecParametersId).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(activitySpecId).append(activitySpecParametersId).toHashCode();
- }
-
- public Integer getID() {
- return ID;
- }
-
- public Integer getActivitySpecId() {
- return activitySpecId;
- }
-
- public void setActivitySpecId(Integer activitySpecId) {
- this.activitySpecId = activitySpecId;
- }
-
- public Integer getActivitySpecParametersId() {
- return activitySpecParametersId;
- }
-
- public void setActivitySpecParametersId(Integer activitySpecParametersId) {
- this.activitySpecParametersId = activitySpecParametersId;
- }
-
- public ActivitySpec getActivitySpec() {
- return activitySpec;
- }
-
- public void setActivitySpec(ActivitySpec activitySpec) {
- this.activitySpec = activitySpec;
- }
-
- public ActivitySpecParameters getActivitySpecParameters() {
- return activitySpecParameters;
- }
-
- public void setActivitySpecParameters(ActivitySpecParameters activitySpecParameters) {
- this.activitySpecParameters = activitySpecParameters;
- }
+ private static final long serialVersionUID = -2036788837696381115L;
+
+ @Id
+ @Column(name = "ID", nullable = false, updatable = false)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer ID;
+
+ @BusinessKey
+ @Id
+ @Column(name = "ACTIVITY_SPEC_ID")
+ private Integer activitySpecId;
+
+ @BusinessKey
+ @Id
+ @Column(name = "ACTIVITY_SPEC_PARAMETERS_ID")
+ private Integer activitySpecParametersId;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "ACTIVITY_SPEC_ID", updatable = false, insertable = false)
+ private ActivitySpec activitySpec;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "ACTIVITY_SPEC_PARAMETERS_ID", updatable = false, insertable = false)
+ private ActivitySpecParameters activitySpecParameters;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("activitySpecId", activitySpecId)
+ .append("activitySpecCategoriesId", activitySpecParametersId).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ActivitySpecActivitySpecParameters)) {
+ return false;
+ }
+ ActivitySpecActivitySpecParameters castOther = (ActivitySpecActivitySpecParameters) other;
+ return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
+ .append(activitySpecParametersId, castOther.activitySpecParametersId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(activitySpecId).append(activitySpecParametersId).toHashCode();
+ }
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public Integer getActivitySpecId() {
+ return activitySpecId;
+ }
+
+ public void setActivitySpecId(Integer activitySpecId) {
+ this.activitySpecId = activitySpecId;
+ }
+
+ public Integer getActivitySpecParametersId() {
+ return activitySpecParametersId;
+ }
+
+ public void setActivitySpecParametersId(Integer activitySpecParametersId) {
+ this.activitySpecParametersId = activitySpecParametersId;
+ }
+
+ public ActivitySpec getActivitySpec() {
+ return activitySpec;
+ }
+
+ public void setActivitySpec(ActivitySpec activitySpec) {
+ this.activitySpec = activitySpec;
+ }
+
+ public ActivitySpecParameters getActivitySpecParameters() {
+ return activitySpecParameters;
+ }
+
+ public void setActivitySpecParameters(ActivitySpecParameters activitySpecParameters) {
+ this.activitySpecParameters = activitySpecParameters;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParametersId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParametersId.java
index 36c3a07c3f..8f4cc6d966 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParametersId.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParametersId.java
@@ -21,61 +21,63 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
public class ActivitySpecActivitySpecParametersId implements Serializable {
-
- private static final long serialVersionUID = 1563771827209840959L;
-
- private Integer ID;
- @BusinessKey
- private Integer activitySpecId;
- @BusinessKey
- private Integer activitySpecParametersId;
-
- public Integer getID() {
- return ID;
- }
- public void setID(Integer iD) {
- ID = iD;
- }
- public Integer getActivitySpecParametersId() {
- return activitySpecParametersId;
- }
- public void setActivitySpecParametersId(Integer activitySpecParametersId) {
- this.activitySpecParametersId = activitySpecParametersId;
- }
- public Integer getActivitySpecId() {
- return activitySpecId;
- }
- public void setActivitySpecId(Integer activitySpecId) {
- this.activitySpecId = activitySpecId;
- }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("activitySpecId", activitySpecId)
- .append("activitySpecCategoriesId", activitySpecParametersId)
- .toString();
- }
+ private static final long serialVersionUID = 1563771827209840959L;
+
+ private Integer ID;
+ @BusinessKey
+ private Integer activitySpecId;
+ @BusinessKey
+ private Integer activitySpecParametersId;
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public void setID(Integer iD) {
+ ID = iD;
+ }
+
+ public Integer getActivitySpecParametersId() {
+ return activitySpecParametersId;
+ }
+
+ public void setActivitySpecParametersId(Integer activitySpecParametersId) {
+ this.activitySpecParametersId = activitySpecParametersId;
+ }
+
+ public Integer getActivitySpecId() {
+ return activitySpecId;
+ }
+
+ public void setActivitySpecId(Integer activitySpecId) {
+ this.activitySpecId = activitySpecId;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("activitySpecId", activitySpecId)
+ .append("activitySpecCategoriesId", activitySpecParametersId).toString();
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ActivitySpecActivitySpecParametersId)) {
- return false;
- }
- ActivitySpecActivitySpecParametersId castOther = (ActivitySpecActivitySpecParametersId) other;
- return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
- .append(activitySpecParametersId, castOther.activitySpecParametersId).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ActivitySpecActivitySpecParametersId)) {
+ return false;
+ }
+ ActivitySpecActivitySpecParametersId castOther = (ActivitySpecActivitySpecParametersId) other;
+ return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
+ .append(activitySpecParametersId, castOther.activitySpecParametersId).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(activitySpecId).append(activitySpecParametersId).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(activitySpecId).append(activitySpecParametersId).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecCategories.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecCategories.java
index 737b174a9b..a42a73aac9 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecCategories.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecCategories.java
@@ -4,7 +4,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
@@ -19,13 +18,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@@ -34,58 +30,59 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "ACTIVITY_SPEC_CATEGORIES")
public class ActivitySpecCategories implements Serializable {
- private static final long serialVersionUID = -6251150462067699643L;
+ private static final long serialVersionUID = -6251150462067699643L;
+
+ @Id
+ @Column(name = "ID", nullable = false, updatable = false)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer ID;
+
+ @BusinessKey
+ @Column(name = "NAME")
+ private String name;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpecCategories")
+ private List<ActivitySpecActivitySpecCategories> activitySpecActivitySpecCategories;
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
- @Id
- @Column(name = "ID", nullable = false, updatable = false)
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer ID;
-
- @BusinessKey
- @Column(name = "NAME")
- private String name;
-
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpecCategories")
- private List<ActivitySpecActivitySpecCategories> activitySpecActivitySpecCategories;
-
- public Integer getID() {
- return ID;
- }
-
- public String getName() {
- return name;
- }
+ @LinkedResource
+ public List<ActivitySpecActivitySpecCategories> getActivitySpecActivitySpecCategories() {
+ return activitySpecActivitySpecCategories;
+ }
- public void setName(String name) {
- this.name = name;
- }
+ public void setActivitySpecActivitySpecCategories(
+ List<ActivitySpecActivitySpecCategories> activitySpecActivitySpecCategories) {
+ this.activitySpecActivitySpecCategories = activitySpecActivitySpecCategories;
+ }
- @LinkedResource
- public List<ActivitySpecActivitySpecCategories> getActivitySpecActivitySpecCategories() {
- return activitySpecActivitySpecCategories;
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("name", name)
+ .append("activitySpecActivitySpecCategories", activitySpecActivitySpecCategories).toString();
+ }
- public void setActivitySpecActivitySpecCategories(
- List<ActivitySpecActivitySpecCategories> activitySpecActivitySpecCategories) {
- this.activitySpecActivitySpecCategories = activitySpecActivitySpecCategories;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("name", name)
- .append("activitySpecActivitySpecCategories", activitySpecActivitySpecCategories).toString();
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ActivitySpecCategories)) {
- return false;
- }
- ActivitySpecCategories castOther = (ActivitySpecCategories) other;
- return new EqualsBuilder().append(name, castOther.name).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ActivitySpecCategories)) {
+ return false;
+ }
+ ActivitySpecCategories castOther = (ActivitySpecCategories) other;
+ return new EqualsBuilder().append(name, castOther.name).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(name).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(name).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecParameters.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecParameters.java
index 9e3e301456..49e0f3fa79 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecParameters.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecParameters.java
@@ -4,7 +4,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
@@ -20,13 +19,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@@ -34,110 +30,111 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "ACTIVITY_SPEC_PARAMETERS")
public class ActivitySpecParameters implements Serializable {
-
- private static final long serialVersionUID = 3627711377147710046L;
-
- @Id
- @Column(name = "ID", nullable = false, updatable = false)
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer ID;
-
- @BusinessKey
- @Column(name = "NAME")
- private String name;
-
- @Column(name = "TYPE")
- private String type;
-
- @BusinessKey
- @Column(name = "DIRECTION")
- private String direction;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpecParameters")
- private List<ActivitySpecActivitySpecParameters> activitySpecActivitySpecParameters;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @LinkedResource
- public List<ActivitySpecActivitySpecParameters> getActivitySpecActivitySpecParameters() {
- return activitySpecActivitySpecParameters;
- }
-
- public void setActivitySpecActivitySpecParameters(
- List<ActivitySpecActivitySpecParameters> activitySpecActivitySpecParameters) {
- this.activitySpecActivitySpecParameters = activitySpecActivitySpecParameters;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("name", name).append("direction", direction)
- .append("activitySpecActivitySpecParameters", activitySpecActivitySpecParameters).toString();
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ActivitySpecParameters)) {
- return false;
- }
- ActivitySpecParameters castOther = (ActivitySpecParameters) other;
- return new EqualsBuilder().append(ID, castOther.ID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(ID).toHashCode();
- }
-
- public Integer getID() {
- return ID;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
-
- public String getDirection() {
- return direction;
- }
-
- public void setDirection(String direction) {
- this.direction = direction;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
+
+ private static final long serialVersionUID = 3627711377147710046L;
+
+ @Id
+ @Column(name = "ID", nullable = false, updatable = false)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer ID;
+
+ @BusinessKey
+ @Column(name = "NAME")
+ private String name;
+
+ @Column(name = "TYPE")
+ private String type;
+
+ @BusinessKey
+ @Column(name = "DIRECTION")
+ private String direction;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpecParameters")
+ private List<ActivitySpecActivitySpecParameters> activitySpecActivitySpecParameters;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @LinkedResource
+ public List<ActivitySpecActivitySpecParameters> getActivitySpecActivitySpecParameters() {
+ return activitySpecActivitySpecParameters;
+ }
+
+ public void setActivitySpecActivitySpecParameters(
+ List<ActivitySpecActivitySpecParameters> activitySpecActivitySpecParameters) {
+ this.activitySpecActivitySpecParameters = activitySpecActivitySpecParameters;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("name", name).append("direction", direction)
+ .append("activitySpecActivitySpecParameters", activitySpecActivitySpecParameters).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ActivitySpecParameters)) {
+ return false;
+ }
+ ActivitySpecParameters castOther = (ActivitySpecParameters) other;
+ return new EqualsBuilder().append(ID, castOther.ID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(ID).toHashCode();
+ }
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getDirection() {
+ return direction;
+ }
+
+ public void setDirection(String direction) {
+ this.direction = direction;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParameters.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParameters.java
index 8cf3351274..be32da379e 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParameters.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParameters.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -37,13 +36,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@@ -51,88 +47,86 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "activity_spec_to_user_parameters")
public class ActivitySpecUserParameters implements Serializable {
- private static final long serialVersionUID = 5599242118780268449L;
-
- @Id
- @Column(name = "ID", nullable = false, updatable = false)
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer ID;
-
- @BusinessKey
- @Id
- @Column(name = "ACTIVITY_SPEC_ID")
- private Integer activitySpecId;
-
- @BusinessKey
- @Id
- @Column(name = "USER_PARAMETERS_ID")
- private Integer userParametersId;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "ACTIVITY_SPEC_ID", updatable = false, insertable = false)
- private ActivitySpec activitySpec;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "USER_PARAMETERS_ID", updatable = false, insertable = false)
- private UserParameters userParameters;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this)
- .append("activitySpecId", activitySpecId)
- .append("userParametersId", userParametersId)
- .toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ActivitySpecUserParameters)) {
- return false;
- }
- ActivitySpecUserParameters castOther = (ActivitySpecUserParameters) other;
- return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
- .append(userParametersId, castOther.userParametersId).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(activitySpecId).append(userParametersId).toHashCode();
- }
-
- public Integer getID() {
- return ID;
- }
-
- public Integer getActivitySpecId() {
- return activitySpecId;
- }
-
- public void setActivitySpecId(Integer activitySpecId) {
- this.activitySpecId = activitySpecId;
- }
-
- public Integer getUserParametersId() {
- return userParametersId;
- }
-
- public void setUserParametersId(Integer userParametersId) {
- this.userParametersId = userParametersId;
- }
-
- public ActivitySpec getActivitySpec() {
- return activitySpec;
- }
-
- public void setActivitySpec(ActivitySpec activitySpec) {
- this.activitySpec = activitySpec;
- }
-
- public UserParameters getUserParameters() {
- return userParameters;
- }
-
- public void setUserParameters(UserParameters userParameters) {
- this.userParameters = userParameters;
- }
+ private static final long serialVersionUID = 5599242118780268449L;
+
+ @Id
+ @Column(name = "ID", nullable = false, updatable = false)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer ID;
+
+ @BusinessKey
+ @Id
+ @Column(name = "ACTIVITY_SPEC_ID")
+ private Integer activitySpecId;
+
+ @BusinessKey
+ @Id
+ @Column(name = "USER_PARAMETERS_ID")
+ private Integer userParametersId;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "ACTIVITY_SPEC_ID", updatable = false, insertable = false)
+ private ActivitySpec activitySpec;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "USER_PARAMETERS_ID", updatable = false, insertable = false)
+ private UserParameters userParameters;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("activitySpecId", activitySpecId)
+ .append("userParametersId", userParametersId).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ActivitySpecUserParameters)) {
+ return false;
+ }
+ ActivitySpecUserParameters castOther = (ActivitySpecUserParameters) other;
+ return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
+ .append(userParametersId, castOther.userParametersId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(activitySpecId).append(userParametersId).toHashCode();
+ }
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public Integer getActivitySpecId() {
+ return activitySpecId;
+ }
+
+ public void setActivitySpecId(Integer activitySpecId) {
+ this.activitySpecId = activitySpecId;
+ }
+
+ public Integer getUserParametersId() {
+ return userParametersId;
+ }
+
+ public void setUserParametersId(Integer userParametersId) {
+ this.userParametersId = userParametersId;
+ }
+
+ public ActivitySpec getActivitySpec() {
+ return activitySpec;
+ }
+
+ public void setActivitySpec(ActivitySpec activitySpec) {
+ this.activitySpec = activitySpec;
+ }
+
+ public UserParameters getUserParameters() {
+ return userParameters;
+ }
+
+ public void setUserParameters(UserParameters userParameters) {
+ this.userParameters = userParameters;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParametersId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParametersId.java
index 3e739ac013..fd55d6e961 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParametersId.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParametersId.java
@@ -21,62 +21,64 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
public class ActivitySpecUserParametersId implements Serializable {
-
- private static final long serialVersionUID = 1563771827209840959L;
- private Integer ID;
- @BusinessKey
- private Integer activitySpecId;
- @BusinessKey
- private Integer userParametersId;
-
- public Integer getID() {
- return ID;
- }
- public void setID(Integer iD) {
- ID = iD;
- }
- public Integer getUserParametersId() {
- return userParametersId;
- }
- public void setUserParametersId(Integer userParametersId) {
- this.userParametersId = userParametersId;
- }
- public Integer getActivitySpecId() {
- return activitySpecId;
- }
- public void setActivitySpecId(Integer activitySpecId) {
- this.activitySpecId = activitySpecId;
- }
+ private static final long serialVersionUID = 1563771827209840959L;
+
+ private Integer ID;
+ @BusinessKey
+ private Integer activitySpecId;
+ @BusinessKey
+ private Integer userParametersId;
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public void setID(Integer iD) {
+ ID = iD;
+ }
+
+ public Integer getUserParametersId() {
+ return userParametersId;
+ }
+
+ public void setUserParametersId(Integer userParametersId) {
+ this.userParametersId = userParametersId;
+ }
+
+ public Integer getActivitySpecId() {
+ return activitySpecId;
+ }
+
+ public void setActivitySpecId(Integer activitySpecId) {
+ this.activitySpecId = activitySpecId;
+ }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("activitySpecId", activitySpecId)
- .append("userParametersId", userParametersId)
- .toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("activitySpecId", activitySpecId)
+ .append("userParametersId", userParametersId).toString();
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ActivitySpecUserParametersId)) {
- return false;
- }
- ActivitySpecUserParametersId castOther = (ActivitySpecUserParametersId) other;
- return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
- .append(userParametersId, castOther.userParametersId).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ActivitySpecUserParametersId)) {
+ return false;
+ }
+ ActivitySpecUserParametersId castOther = (ActivitySpecUserParametersId) other;
+ return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
+ .append(userParametersId, castOther.userParametersId).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(activitySpecId).append(userParametersId).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(activitySpecId).append(userParametersId).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AllottedResource.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AllottedResource.java
index 1d3ee7c36e..c3a662d883 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AllottedResource.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AllottedResource.java
@@ -24,7 +24,6 @@ import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -34,148 +33,145 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "allotted_resource")
public class AllottedResource implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
- @BusinessKey
- @Id
- @Column(name = "MODEL_UUID")
- private String modelUUID;
-
- @Column(name = "MODEL_INVARIANT_UUID")
- private String modelInvariantUUID;
-
- @Column(name = "MODEL_VERSION")
- private String modelVersion;
-
- @Column(name = "MODEL_NAME")
- private String modelName;
-
- @Column(name = "TOSCA_NODE_TYPE")
- private String toscaNodeType;
-
- @Column(name = "SUBCATEGORY")
- private String subcategory;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "allottedResource")
- private Set<AllottedResourceCustomization> allotedResourceCustomization;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelInvariantUUID", modelInvariantUUID)
- .append("modelVersion", modelVersion).append("modelName", modelName)
- .append("toscaNodeType", toscaNodeType).append("subcategory", subcategory)
- .append("description", description).append("created", created)
- .append("allotedResourceCustomization", allotedResourceCustomization).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof AllottedResource)) {
- return false;
- }
- AllottedResource castOther = (AllottedResource) other;
- return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelUUID).toHashCode();
- }
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @LinkedResource
- public Set<AllottedResourceCustomization> getAllotedResourceCustomization() {
- if (allotedResourceCustomization == null)
- allotedResourceCustomization = new HashSet<>();
- return allotedResourceCustomization;
- }
-
- public void setAllotedResourceCustomization(Set<AllottedResourceCustomization> allotedResourceCustomization) {
- this.allotedResourceCustomization = allotedResourceCustomization;
- }
-
- public String getModelUUID() {
- return this.modelUUID;
- }
-
- public void setModelUUID(String modelUUID) {
- this.modelUUID = modelUUID;
- }
-
- public String getModelInvariantUUID() {
- return this.modelInvariantUUID;
- }
-
- public void setModelInvariantUUID(String modelInvariantUUID) {
- this.modelInvariantUUID = modelInvariantUUID;
- }
-
- public String getModelVersion() {
- return this.modelVersion;
- }
-
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
-
- public String getModelName() {
- return this.modelName;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public String getToscaNodeType() {
- return this.toscaNodeType;
- }
-
- public void setToscaNodeType(String toscaNodeType) {
- this.toscaNodeType = toscaNodeType;
- }
-
- public String getSubcategory() {
- return this.subcategory;
- }
-
- public void setSubcategory(String subcategory) {
- this.subcategory = subcategory;
- }
-
- public String getDescription() {
- return this.description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Date getCreated() {
- return created;
- }
+ private static final long serialVersionUID = 768026109321305392L;
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_UUID")
+ private String modelUUID;
+
+ @Column(name = "MODEL_INVARIANT_UUID")
+ private String modelInvariantUUID;
+
+ @Column(name = "MODEL_VERSION")
+ private String modelVersion;
+
+ @Column(name = "MODEL_NAME")
+ private String modelName;
+
+ @Column(name = "TOSCA_NODE_TYPE")
+ private String toscaNodeType;
+
+ @Column(name = "SUBCATEGORY")
+ private String subcategory;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "allottedResource")
+ private Set<AllottedResourceCustomization> allotedResourceCustomization;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelInvariantUUID", modelInvariantUUID)
+ .append("modelVersion", modelVersion).append("modelName", modelName)
+ .append("toscaNodeType", toscaNodeType).append("subcategory", subcategory)
+ .append("description", description).append("created", created)
+ .append("allotedResourceCustomization", allotedResourceCustomization).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof AllottedResource)) {
+ return false;
+ }
+ AllottedResource castOther = (AllottedResource) other;
+ return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelUUID).toHashCode();
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @LinkedResource
+ public Set<AllottedResourceCustomization> getAllotedResourceCustomization() {
+ if (allotedResourceCustomization == null)
+ allotedResourceCustomization = new HashSet<>();
+ return allotedResourceCustomization;
+ }
+
+ public void setAllotedResourceCustomization(Set<AllottedResourceCustomization> allotedResourceCustomization) {
+ this.allotedResourceCustomization = allotedResourceCustomization;
+ }
+
+ public String getModelUUID() {
+ return this.modelUUID;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ this.modelUUID = modelUUID;
+ }
+
+ public String getModelInvariantUUID() {
+ return this.modelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ this.modelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getModelVersion() {
+ return this.modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ public String getModelName() {
+ return this.modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getToscaNodeType() {
+ return this.toscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ this.toscaNodeType = toscaNodeType;
+ }
+
+ public String getSubcategory() {
+ return this.subcategory;
+ }
+
+ public void setSubcategory(String subcategory) {
+ this.subcategory = subcategory;
+ }
+
+ public String getDescription() {
+ return this.description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AllottedResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AllottedResourceCustomization.java
index 04b93c3886..b3734caccc 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AllottedResourceCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AllottedResourceCustomization.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -34,222 +33,219 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "allotted_resource_customization")
public class AllottedResourceCustomization implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
+ private static final long serialVersionUID = 768026109321305392L;
- @BusinessKey
- @Id
- @Column(name = "MODEL_CUSTOMIZATION_UUID")
- private String modelCustomizationUUID;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_CUSTOMIZATION_UUID")
+ private String modelCustomizationUUID;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
- @Column(name = "MODEL_INSTANCE_NAME")
- private String modelInstanceName;
-
- @Column(name = "PROVIDING_SERVICE_MODEL_INVARIANT_UUID")
- private String providingServiceModelInvariantUUID;
+ @Column(name = "MODEL_INSTANCE_NAME")
+ private String modelInstanceName;
+
+ @Column(name = "PROVIDING_SERVICE_MODEL_INVARIANT_UUID")
+ private String providingServiceModelInvariantUUID;
- @Column(name = "PROVIDING_SERVICE_MODEL_UUID")
- private String providingServiceModelUUID;
+ @Column(name = "PROVIDING_SERVICE_MODEL_UUID")
+ private String providingServiceModelUUID;
- @Column(name = "PROVIDING_SERVICE_MODEL_NAME")
- private String providingServiceModelName;
+ @Column(name = "PROVIDING_SERVICE_MODEL_NAME")
+ private String providingServiceModelName;
- @Column(name = "TARGET_NETWORK_ROLE")
- private String targetNetworkRole;
-
- @Column(name = "NF_FUNCTION")
- private String nfFunction;
+ @Column(name = "TARGET_NETWORK_ROLE")
+ private String targetNetworkRole;
+
+ @Column(name = "NF_FUNCTION")
+ private String nfFunction;
- @Column(name = "NF_TYPE")
- private String nfType;
+ @Column(name = "NF_TYPE")
+ private String nfType;
- @Column(name = "NF_ROLE")
- private String nfRole;
-
- @Column(name = "NF_NAMING_CODE")
- private String nfNamingCode;
-
- @Column(name = "MIN_INSTANCES")
- private Integer minInstances;
+ @Column(name = "NF_ROLE")
+ private String nfRole;
+
+ @Column(name = "NF_NAMING_CODE")
+ private String nfNamingCode;
+
+ @Column(name = "MIN_INSTANCES")
+ private Integer minInstances;
- @Column(name = "MAX_INSTANCES")
- private Integer maxInstances;
+ @Column(name = "MAX_INSTANCES")
+ private Integer maxInstances;
- @Column(name = "RESOURCE_INPUT")
- private String resourceInput;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "AR_MODEL_UUID")
- private AllottedResource allottedResource;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
- .append("created", created).append("modelInstanceName", modelInstanceName)
- .append("providingServiceModelInvariantUUID", providingServiceModelInvariantUUID)
- .append("providingServiceModelUUID", providingServiceModelUUID)
- .append("providingServiceModelName", providingServiceModelName)
- .append("targetNetworkRole", targetNetworkRole).append("nfFunction", nfFunction)
- .append("nfType", nfType).append("nfRole", nfRole).append("nfNamingCode", nfNamingCode)
- .append("minInstances", minInstances).append("maxInstances", maxInstances)
- .append("allottedResource", allottedResource).toString();
- }
+ @Column(name = "RESOURCE_INPUT")
+ private String resourceInput;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "AR_MODEL_UUID")
+ private AllottedResource allottedResource;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
+ .append("created", created).append("modelInstanceName", modelInstanceName)
+ .append("providingServiceModelInvariantUUID", providingServiceModelInvariantUUID)
+ .append("providingServiceModelUUID", providingServiceModelUUID)
+ .append("providingServiceModelName", providingServiceModelName)
+ .append("targetNetworkRole", targetNetworkRole).append("nfFunction", nfFunction)
+ .append("nfType", nfType).append("nfRole", nfRole).append("nfNamingCode", nfNamingCode)
+ .append("minInstances", minInstances).append("maxInstances", maxInstances)
+ .append("allottedResource", allottedResource).toString();
+ }
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof AllottedResourceCustomization)) {
- return false;
- }
- AllottedResourceCustomization castOther = (AllottedResourceCustomization) other;
- return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode();
- }
-
- public String getProvidingServiceModelUUID() {
- return providingServiceModelUUID;
- }
-
- public void setProvidingServiceModelUUID(String providingServiceModelUUID) {
- this.providingServiceModelUUID = providingServiceModelUUID;
- }
-
- public String getProvidingServiceModelName() {
- return providingServiceModelName;
- }
-
- public void setProvidingServiceModelName(String providingServiceModelName) {
- this.providingServiceModelName = providingServiceModelName;
- }
-
- public AllottedResourceCustomization() {
- super();
- }
-
- public String getModelCustomizationUUID() {
- return this.modelCustomizationUUID;
- }
-
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
-
- public Date getCreated() {
- return this.created;
- }
-
- public String getModelInstanceName() {
- return this.modelInstanceName;
- }
-
- public void setModelInstanceName(String modelInstanceName) {
- this.modelInstanceName = modelInstanceName;
- }
-
- @LinkedResource
- public AllottedResource getAllottedResource() {
- return this.allottedResource;
- }
-
- public void setAllottedResource(AllottedResource allottedResource) {
- this.allottedResource = allottedResource;
- }
-
- public String getProvidingServiceModelInvariantUUID() {
- return this.providingServiceModelInvariantUUID;
- }
-
- public void setProvidingServiceModelInvariantUUID(String providingServiceModelInvariantUUID) {
- this.providingServiceModelInvariantUUID = providingServiceModelInvariantUUID;
- }
-
- public String getTargetNetworkRole() {
- return this.targetNetworkRole;
- }
-
- public void setTargetNetworkRole(String targetNetworkRole) {
- this.targetNetworkRole = targetNetworkRole;
- }
-
- public String getNfFunction() {
- return this.nfFunction;
- }
-
- public void setNfFunction(String nfFunction) {
- this.nfFunction = nfFunction;
- }
-
- public String getNfType() {
- return this.nfType;
- }
-
- public void setNfType(String nfType) {
- this.nfType = nfType;
- }
-
- public String getNfRole() {
- return this.nfRole;
- }
-
- public void setNfRole(String nfRole) {
- this.nfRole = nfRole;
- }
-
- public String getNfNamingCode() {
- return this.nfNamingCode;
- }
-
- public void setNfNamingCode(String nfNamingCode) {
- this.nfNamingCode = nfNamingCode;
- }
-
- public Integer getMinInstances() {
- return this.minInstances;
- }
-
- public void setMinInstances(Integer minInstances) {
- this.minInstances = minInstances;
- }
-
- public Integer getMaxInstances() {
- return this.maxInstances;
- }
-
- public void setMaxInstances(Integer maxInstances) {
- this.maxInstances = maxInstances;
- }
-
- public String getResourceInput() {
- return resourceInput;
- }
-
- public void setResourceInput(String resourceInput) {
- this.resourceInput = resourceInput;
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof AllottedResourceCustomization)) {
+ return false;
+ }
+ AllottedResourceCustomization castOther = (AllottedResourceCustomization) other;
+ return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode();
+ }
+
+ public String getProvidingServiceModelUUID() {
+ return providingServiceModelUUID;
+ }
+
+ public void setProvidingServiceModelUUID(String providingServiceModelUUID) {
+ this.providingServiceModelUUID = providingServiceModelUUID;
+ }
+
+ public String getProvidingServiceModelName() {
+ return providingServiceModelName;
+ }
+
+ public void setProvidingServiceModelName(String providingServiceModelName) {
+ this.providingServiceModelName = providingServiceModelName;
+ }
+
+ public AllottedResourceCustomization() {
+ super();
+ }
+
+ public String getModelCustomizationUUID() {
+ return this.modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ public Date getCreated() {
+ return this.created;
+ }
+
+ public String getModelInstanceName() {
+ return this.modelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ this.modelInstanceName = modelInstanceName;
+ }
+
+ @LinkedResource
+ public AllottedResource getAllottedResource() {
+ return this.allottedResource;
+ }
+
+ public void setAllottedResource(AllottedResource allottedResource) {
+ this.allottedResource = allottedResource;
+ }
+
+ public String getProvidingServiceModelInvariantUUID() {
+ return this.providingServiceModelInvariantUUID;
+ }
+
+ public void setProvidingServiceModelInvariantUUID(String providingServiceModelInvariantUUID) {
+ this.providingServiceModelInvariantUUID = providingServiceModelInvariantUUID;
+ }
+
+ public String getTargetNetworkRole() {
+ return this.targetNetworkRole;
+ }
+
+ public void setTargetNetworkRole(String targetNetworkRole) {
+ this.targetNetworkRole = targetNetworkRole;
+ }
+
+ public String getNfFunction() {
+ return this.nfFunction;
+ }
+
+ public void setNfFunction(String nfFunction) {
+ this.nfFunction = nfFunction;
+ }
+
+ public String getNfType() {
+ return this.nfType;
+ }
+
+ public void setNfType(String nfType) {
+ this.nfType = nfType;
+ }
+
+ public String getNfRole() {
+ return this.nfRole;
+ }
+
+ public void setNfRole(String nfRole) {
+ this.nfRole = nfRole;
+ }
+
+ public String getNfNamingCode() {
+ return this.nfNamingCode;
+ }
+
+ public void setNfNamingCode(String nfNamingCode) {
+ this.nfNamingCode = nfNamingCode;
+ }
+
+ public Integer getMinInstances() {
+ return this.minInstances;
+ }
+
+ public void setMinInstances(Integer minInstances) {
+ this.minInstances = minInstances;
+ }
+
+ public Integer getMaxInstances() {
+ return this.maxInstances;
+ }
+
+ public void setMaxInstances(Integer maxInstances) {
+ this.maxInstances = maxInstances;
+ }
+
+ public String getResourceInput() {
+ return resourceInput;
+ }
+
+ public void setResourceInput(String resourceInput) {
+ this.resourceInput = resourceInput;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ArRecipe.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ArRecipe.java
index 86ff743475..176c02c8cd 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ArRecipe.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ArRecipe.java
@@ -22,163 +22,160 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@Table(name = "ar_recipe")
public class ArRecipe implements Recipe, Serializable {
- private static final long serialVersionUID = 768026109321305392L;
-
- @Id
- @Column(name = "ID", nullable = false)
- private Integer id;
- @BusinessKey
- @Column(name = "MODEL_NAME", nullable = false)
- private String modelName;
- @BusinessKey
- @Column(name = "ACTION", nullable = false)
- private String action;
-
- @Column(name = "VERSION_STR", nullable = false)
- private String version;
- @BusinessKey
- @Column(name = "SERVICE_TYPE")
- private String serviceType;
-
- @Column(name = "DESCRIPTION")
- private String description;
- @BusinessKey
- @Column(name = "ORCHESTRATION_URI", nullable = false)
- private String orchestrationUri;
-
- @Column(name = "AR_PARAM_XSD")
- private String paramXsd;
-
- @Column(name = "RECIPE_TIMEOUT")
- private Integer recipeTimeout;
-
- @Column(name = "CREATION_TIMESTAMP", nullable = false, updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getModelName() {
- return modelName;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
- public String getServiceType() {
- return serviceType;
- }
-
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getOrchestrationUri() {
- return orchestrationUri;
- }
-
- public void setOrchestrationUri(String orchestrationUri) {
- this.orchestrationUri = orchestrationUri;
- }
-
- public String getParamXsd() {
- return paramXsd;
- }
-
- public void setParamXsd(String paramXsd) {
- this.paramXsd = paramXsd;
- }
-
- public Integer getRecipeTimeout() {
- return recipeTimeout;
- }
-
- public void setRecipeTimeout(Integer recipeTimeout) {
- this.recipeTimeout = recipeTimeout;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelName", getModelName()).append("action", getAction())
- .append("version", getVersion()).append("serviceType", getServiceType())
- .append("description", getDescription()).append("orchestrationUri", getOrchestrationUri())
- .append("paramXSD", getParamXsd()).append("recipeTimeout", getRecipeTimeout())
- .append("created", getCreated()).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof ArRecipe)) {
- return false;
- }
- ArRecipe castOther = (ArRecipe) other;
- return new EqualsBuilder().append(getId(), castOther.getId()).append(getModelName(), castOther.getModelName())
- .append(getAction(), castOther.getAction()).append(getServiceType(), castOther.getServiceType())
- .append(getOrchestrationUri(), castOther.getOrchestrationUri()).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(getId()).append(getModelName()).append(getAction()).append(getServiceType())
- .append(getOrchestrationUri()).toHashCode();
- }
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @Id
+ @Column(name = "ID", nullable = false)
+ private Integer id;
+ @BusinessKey
+ @Column(name = "MODEL_NAME", nullable = false)
+ private String modelName;
+ @BusinessKey
+ @Column(name = "ACTION", nullable = false)
+ private String action;
+
+ @Column(name = "VERSION_STR", nullable = false)
+ private String version;
+ @BusinessKey
+ @Column(name = "SERVICE_TYPE")
+ private String serviceType;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+ @BusinessKey
+ @Column(name = "ORCHESTRATION_URI", nullable = false)
+ private String orchestrationUri;
+
+ @Column(name = "AR_PARAM_XSD")
+ private String paramXsd;
+
+ @Column(name = "RECIPE_TIMEOUT")
+ private Integer recipeTimeout;
+
+ @Column(name = "CREATION_TIMESTAMP", nullable = false, updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getOrchestrationUri() {
+ return orchestrationUri;
+ }
+
+ public void setOrchestrationUri(String orchestrationUri) {
+ this.orchestrationUri = orchestrationUri;
+ }
+
+ public String getParamXsd() {
+ return paramXsd;
+ }
+
+ public void setParamXsd(String paramXsd) {
+ this.paramXsd = paramXsd;
+ }
+
+ public Integer getRecipeTimeout() {
+ return recipeTimeout;
+ }
+
+ public void setRecipeTimeout(Integer recipeTimeout) {
+ this.recipeTimeout = recipeTimeout;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelName", getModelName()).append("action", getAction())
+ .append("version", getVersion()).append("serviceType", getServiceType())
+ .append("description", getDescription()).append("orchestrationUri", getOrchestrationUri())
+ .append("paramXSD", getParamXsd()).append("recipeTimeout", getRecipeTimeout())
+ .append("created", getCreated()).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof ArRecipe)) {
+ return false;
+ }
+ ArRecipe castOther = (ArRecipe) other;
+ return new EqualsBuilder().append(getId(), castOther.getId()).append(getModelName(), castOther.getModelName())
+ .append(getAction(), castOther.getAction()).append(getServiceType(), castOther.getServiceType())
+ .append(getOrchestrationUri(), castOther.getOrchestrationUri()).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(getId()).append(getModelName()).append(getAction()).append(getServiceType())
+ .append(getOrchestrationUri()).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AuthenticationType.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AuthenticationType.java
index b1cb07447d..c0f60325ea 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AuthenticationType.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/AuthenticationType.java
@@ -21,5 +21,5 @@
package org.onap.so.db.catalog.beans;
public enum AuthenticationType {
- USERNAME_PASSWORD, RACKSPACE_APIKEY;
+ USERNAME_PASSWORD, RACKSPACE_APIKEY;
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/BuildingBlockDetail.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/BuildingBlockDetail.java
index cc2abacce2..54e2144c81 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/BuildingBlockDetail.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/BuildingBlockDetail.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.List;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -34,85 +33,83 @@ import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.onap.so.db.catalog.beans.macro.OrchestrationFlow;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@Table(name = "building_block_detail")
public class BuildingBlockDetail implements Serializable {
- private static final long serialVersionUID = -2375223199178059155L;
-
- @Id
- @Column(name = "id")
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
-
- @BusinessKey
- @Column(name = "BUILDING_BLOCK_NAME")
- private String buildingBlockName;
-
- @Enumerated(EnumType.STRING)
- @Column(name = "RESOURCE_TYPE")
- private ResourceType resourceType;
-
- @Enumerated(EnumType.STRING)
- @Column(name = "TARGET_ACTION")
- private OrchestrationAction targetAction;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("buildingBlockName", buildingBlockName)
- .append("resourceType", resourceType).append("targetAction", targetAction).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof BuildingBlockDetail)) {
- return false;
- }
- BuildingBlockDetail castOther = (BuildingBlockDetail) other;
- return new EqualsBuilder().append(buildingBlockName, castOther.buildingBlockName).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(buildingBlockName).toHashCode();
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getBuildingBlockName() {
- return buildingBlockName;
- }
-
- public void setBuildingBlockName(String buildingBlockName) {
- this.buildingBlockName = buildingBlockName;
- }
-
- public ResourceType getResourceType() {
- return resourceType;
- }
-
- public void setResourceType(ResourceType resourceType) {
- this.resourceType = resourceType;
- }
-
- public OrchestrationAction getTargetAction() {
- return targetAction;
- }
-
- public void setTargetAction(OrchestrationAction targetAction) {
- this.targetAction = targetAction;
- }
+ private static final long serialVersionUID = -2375223199178059155L;
+
+ @Id
+ @Column(name = "id")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer id;
+
+ @BusinessKey
+ @Column(name = "BUILDING_BLOCK_NAME")
+ private String buildingBlockName;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "RESOURCE_TYPE")
+ private ResourceType resourceType;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "TARGET_ACTION")
+ private OrchestrationAction targetAction;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("buildingBlockName", buildingBlockName)
+ .append("resourceType", resourceType).append("targetAction", targetAction).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof BuildingBlockDetail)) {
+ return false;
+ }
+ BuildingBlockDetail castOther = (BuildingBlockDetail) other;
+ return new EqualsBuilder().append(buildingBlockName, castOther.buildingBlockName).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(buildingBlockName).toHashCode();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getBuildingBlockName() {
+ return buildingBlockName;
+ }
+
+ public void setBuildingBlockName(String buildingBlockName) {
+ this.buildingBlockName = buildingBlockName;
+ }
+
+ public ResourceType getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(ResourceType resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public OrchestrationAction getTargetAction() {
+ return targetAction;
+ }
+
+ public void setTargetAction(OrchestrationAction targetAction) {
+ this.targetAction = targetAction;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudIdentity.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudIdentity.java
index bb01f6f804..7dd163bafa 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudIdentity.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudIdentity.java
@@ -23,13 +23,10 @@ package org.onap.so.db.catalog.beans;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.openpojo.business.annotation.BusinessKey;
import org.apache.commons.lang3.builder.HashCodeBuilder;
-
import java.util.Date;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
@@ -41,9 +38,8 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
- * EntityBean class for a CloudIdentity. This bean represents a cloud identity
- * service instance (i.e. a DCP node) in the NVP/AIC cloud. It will be loaded via
- * CloudConfig object, of which it is a component.
+ * EntityBean class for a CloudIdentity. This bean represents a cloud identity service instance (i.e. a DCP node) in the
+ * NVP/AIC cloud. It will be loaded via CloudConfig object, of which it is a component.
*
*/
@Entity
@@ -55,53 +51,53 @@ public class CloudIdentity {
@Id
@Column(name = "ID")
private String id;
-
+
@JsonProperty("identity_url")
@BusinessKey
@Column(name = "IDENTITY_URL")
private String identityUrl;
-
+
@JsonProperty("mso_id")
@BusinessKey
@Column(name = "MSO_ID")
private String msoId;
-
+
@JsonProperty("mso_pass")
@BusinessKey
@Column(name = "MSO_PASS")
private String msoPass;
-
+
@JsonProperty("project_domain_name")
@BusinessKey
@Column(name = "PROJECT_DOMAIN_NAME")
private String projectDomainName;
-
+
@JsonProperty("user_domain_name")
@BusinessKey
@Column(name = "USER_DOMAIN_NAME")
private String userDomainName;
-
+
@JsonProperty("admin_tenant")
@BusinessKey
@Column(name = "ADMIN_TENANT")
private String adminTenant;
-
+
@JsonProperty("member_role")
@BusinessKey
@Column(name = "MEMBER_ROLE")
private String memberRole;
-
+
@JsonProperty("tenant_metadata")
@BusinessKey
@Column(name = "TENANT_METADATA")
private Boolean tenantMetadata;
-
+
@JsonProperty("identity_server_type")
@BusinessKey
@Enumerated(EnumType.STRING)
@Column(name = "IDENTITY_SERVER_TYPE")
private ServerType identityServerType;
-
+
@JsonProperty("identity_authentication_type")
@BusinessKey
@Enumerated(EnumType.STRING)
@@ -111,7 +107,7 @@ public class CloudIdentity {
@JsonProperty("last_updated_by")
@BusinessKey
@Column(name = "LAST_UPDATED_BY")
- private String lastUpdatedBy ;
+ private String lastUpdatedBy;
@JsonProperty("creation_timestamp")
@BusinessKey
@@ -124,7 +120,7 @@ public class CloudIdentity {
@Column(name = "UPDATE_TIMESTAMP")
@Temporal(TemporalType.TIMESTAMP)
private Date updated;
-
+
public CloudIdentity() {}
@PrePersist
@@ -133,38 +129,39 @@ public class CloudIdentity {
this.updated = new Date();
}
- public String getId () {
+ public String getId() {
return id;
}
- public void setId (String id) {
+ public void setId(String id) {
this.id = id;
}
public String getIdentityUrl() {
- return this.identityUrl;
+ return this.identityUrl;
}
+
public void setIdentityUrl(String url) {
- this.identityUrl = url;
+ this.identityUrl = url;
}
- public String getMsoId () {
+ public String getMsoId() {
return msoId;
}
- public void setMsoId (String id) {
+ public void setMsoId(String id) {
this.msoId = id;
}
- public String getMsoPass () {
+ public String getMsoPass() {
return msoPass;
}
- public void setMsoPass (String pwd) {
+ public void setMsoPass(String pwd) {
this.msoPass = pwd;
}
- public String getAdminTenant () {
+ public String getAdminTenant() {
return adminTenant;
}
@@ -192,15 +189,15 @@ public class CloudIdentity {
this.updated = updated;
}
- public void setAdminTenant (String tenant) {
+ public void setAdminTenant(String tenant) {
this.adminTenant = tenant;
}
- public String getMemberRole () {
+ public String getMemberRole() {
return memberRole;
}
- public void setMemberRole (String role) {
+ public void setMemberRole(String role) {
this.memberRole = role;
}
@@ -208,100 +205,106 @@ public class CloudIdentity {
return tenantMetadata;
}
- public void setTenantMetadata (Boolean meta) {
+ public void setTenantMetadata(Boolean meta) {
this.tenantMetadata = meta;
}
-
+
public ServerType getIdentityServerType() {
- return this.identityServerType;
+ return this.identityServerType;
}
+
public void setIdentityServerType(ServerType ist) {
- this.identityServerType = ist;
+ this.identityServerType = ist;
}
+
public String getIdentityServerTypeAsString() {
- return this.identityServerType.toString();
+ return this.identityServerType.toString();
}
+
/**
- * @return the identityAuthenticationType
- */
- public AuthenticationType getIdentityAuthenticationType() {
- return identityAuthenticationType;
- }
-
- /**
- * @param identityAuthenticationType the identityAuthenticationType to set
- */
- public void setIdentityAuthenticationType(AuthenticationType identityAuthenticationType) {
- this.identityAuthenticationType = identityAuthenticationType;
- }
-
- public String getProjectDomainName() {
- return projectDomainName;
- }
-
- public void setProjectDomainName(String projectDomainName) {
- this.projectDomainName = projectDomainName;
- }
-
- public String getUserDomainName() {
- return userDomainName;
- }
-
- public void setUserDomainName(String userDomainName) {
- this.userDomainName = userDomainName;
- }
- @Override
- public CloudIdentity clone() {
- CloudIdentity cloudIdentityCopy = new CloudIdentity();
-
- cloudIdentityCopy.id = this.id;
- cloudIdentityCopy.identityUrl = this.identityUrl;
- cloudIdentityCopy.msoId = this.msoId;
- cloudIdentityCopy.msoPass = this.msoPass;
- cloudIdentityCopy.adminTenant = this.adminTenant;
- cloudIdentityCopy.memberRole = this.memberRole;
- cloudIdentityCopy.tenantMetadata = this.tenantMetadata;
- cloudIdentityCopy.identityServerType = this.identityServerType;
- cloudIdentityCopy.identityAuthenticationType = this.identityAuthenticationType;
- cloudIdentityCopy.projectDomainName = this.projectDomainName;
- cloudIdentityCopy.userDomainName = this.userDomainName;
-
- return cloudIdentityCopy;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("id", getId())
- .append("identityUrl", getIdentityUrl()).append("msoId", getMsoId())
- .append("projectDomain", getProjectDomainName()).append("userDomain", getUserDomainName())
- .append("adminTenant", getAdminTenant()).append("memberRole", getMemberRole())
- .append("tenantMetadata", getTenantMetadata()).append("identityServerType", getIdentityServerType())
- .append("identityAuthenticationType", getIdentityAuthenticationType()).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (other == null) {
- return false;
- }
- if (!getClass().equals(other.getClass())) {
- return false;
- }
- CloudIdentity castOther = (CloudIdentity) other;
- return new EqualsBuilder().append(getId(), castOther.getId())
- .append(getIdentityUrl(), castOther.getIdentityUrl()).append(getMsoId(), castOther.getMsoId())
- .append(getMsoPass(), castOther.getMsoPass()).append(getAdminTenant(), castOther.getAdminTenant())
- .append(getProjectDomainName(), castOther.getProjectDomainName()).append(getUserDomainName(), castOther.getUserDomainName())
- .append(getMemberRole(), castOther.getMemberRole())
- .append(getTenantMetadata(), castOther.getTenantMetadata())
- .append(getIdentityServerType(), castOther.getIdentityServerType())
- .append(getIdentityAuthenticationType(), castOther.getIdentityAuthenticationType()).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder(1, 31).append(getId()).append(getIdentityUrl()).append(getMsoId())
- .append(getMsoPass()).append(getProjectDomainName()).append(getUserDomainName()).append(getAdminTenant()).append(getMemberRole()).append(getTenantMetadata())
- .append(getIdentityServerType()).append(getIdentityAuthenticationType()).toHashCode();
- }
-} \ No newline at end of file
+ * @return the identityAuthenticationType
+ */
+ public AuthenticationType getIdentityAuthenticationType() {
+ return identityAuthenticationType;
+ }
+
+ /**
+ * @param identityAuthenticationType the identityAuthenticationType to set
+ */
+ public void setIdentityAuthenticationType(AuthenticationType identityAuthenticationType) {
+ this.identityAuthenticationType = identityAuthenticationType;
+ }
+
+ public String getProjectDomainName() {
+ return projectDomainName;
+ }
+
+ public void setProjectDomainName(String projectDomainName) {
+ this.projectDomainName = projectDomainName;
+ }
+
+ public String getUserDomainName() {
+ return userDomainName;
+ }
+
+ public void setUserDomainName(String userDomainName) {
+ this.userDomainName = userDomainName;
+ }
+
+ @Override
+ public CloudIdentity clone() {
+ CloudIdentity cloudIdentityCopy = new CloudIdentity();
+
+ cloudIdentityCopy.id = this.id;
+ cloudIdentityCopy.identityUrl = this.identityUrl;
+ cloudIdentityCopy.msoId = this.msoId;
+ cloudIdentityCopy.msoPass = this.msoPass;
+ cloudIdentityCopy.adminTenant = this.adminTenant;
+ cloudIdentityCopy.memberRole = this.memberRole;
+ cloudIdentityCopy.tenantMetadata = this.tenantMetadata;
+ cloudIdentityCopy.identityServerType = this.identityServerType;
+ cloudIdentityCopy.identityAuthenticationType = this.identityAuthenticationType;
+ cloudIdentityCopy.projectDomainName = this.projectDomainName;
+ cloudIdentityCopy.userDomainName = this.userDomainName;
+
+ return cloudIdentityCopy;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("id", getId())
+ .append("identityUrl", getIdentityUrl()).append("msoId", getMsoId())
+ .append("projectDomain", getProjectDomainName()).append("userDomain", getUserDomainName())
+ .append("adminTenant", getAdminTenant()).append("memberRole", getMemberRole())
+ .append("tenantMetadata", getTenantMetadata()).append("identityServerType", getIdentityServerType())
+ .append("identityAuthenticationType", getIdentityAuthenticationType()).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (other == null) {
+ return false;
+ }
+ if (!getClass().equals(other.getClass())) {
+ return false;
+ }
+ CloudIdentity castOther = (CloudIdentity) other;
+ return new EqualsBuilder().append(getId(), castOther.getId())
+ .append(getIdentityUrl(), castOther.getIdentityUrl()).append(getMsoId(), castOther.getMsoId())
+ .append(getMsoPass(), castOther.getMsoPass()).append(getAdminTenant(), castOther.getAdminTenant())
+ .append(getProjectDomainName(), castOther.getProjectDomainName())
+ .append(getUserDomainName(), castOther.getUserDomainName())
+ .append(getMemberRole(), castOther.getMemberRole())
+ .append(getTenantMetadata(), castOther.getTenantMetadata())
+ .append(getIdentityServerType(), castOther.getIdentityServerType())
+ .append(getIdentityAuthenticationType(), castOther.getIdentityAuthenticationType()).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(1, 31).append(getId()).append(getIdentityUrl()).append(getMsoId())
+ .append(getMsoPass()).append(getProjectDomainName()).append(getUserDomainName())
+ .append(getAdminTenant()).append(getMemberRole()).append(getTenantMetadata())
+ .append(getIdentityServerType()).append(getIdentityAuthenticationType()).toHashCode();
+ }
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudSite.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudSite.java
index 433ae986ab..053bf745e1 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudSite.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudSite.java
@@ -23,7 +23,6 @@ package org.onap.so.db.catalog.beans;
import java.net.URI;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -36,24 +35,20 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
-
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.RemoteResource;
import uk.co.blackpepper.bowman.annotation.ResourceId;
/**
- * EntityBean class for a CloudSite. This bean represents a cloud location
- * (i.e. and LCP node) in the NVP/AIC cloud. It will be loaded via CloudConfig
- * object, of which it is a component
+ * EntityBean class for a CloudSite. This bean represents a cloud location (i.e. and LCP node) in the NVP/AIC cloud. It
+ * will be loaded via CloudConfig object, of which it is a component
*
*/
@RemoteResource("/cloudSite")
@@ -111,7 +106,7 @@ public class CloudSite {
@JsonProperty("last_updated_by")
@BusinessKey
@Column(name = "LAST_UPDATED_BY")
- private String lastUpdatedBy ;
+ private String lastUpdatedBy;
@JsonProperty("creation_timestamp")
@BusinessKey
@@ -159,10 +154,12 @@ public class CloudSite {
}
@ResourceId
- public URI getUri() {return this.uri;}
+ public URI getUri() {
+ return this.uri;
+ }
public void setUri(URI uri) {
- this.uri = uri;
+ this.uri = uri;
}
public String getRegionId() {
@@ -174,7 +171,8 @@ public class CloudSite {
}
public String getIdentityServiceId() {
- return identityServiceId == null ? (identityService== null? null:identityService.getId()):identityServiceId;
+ return identityServiceId == null ? (identityService == null ? null : identityService.getId())
+ : identityServiceId;
}
public String getCloudVersion() {
@@ -241,13 +239,14 @@ public class CloudSite {
this.orchestrator = orchestrator;
}
- public CloudIdentity getIdentityService () {
+ public CloudIdentity getIdentityService() {
return identityService;
}
- public void setIdentityService (CloudIdentity identity) {
+ public void setIdentityService(CloudIdentity identity) {
this.identityService = identity;
}
+
@Deprecated
public void setIdentityServiceId(String identityServiceId) {
this.identityServiceId = identityServiceId;
@@ -272,7 +271,8 @@ public class CloudSite {
CloudSite castOther = (CloudSite) other;
return new EqualsBuilder().append(getRegionId(), castOther.getRegionId())
.append(getIdentityServiceId(), castOther.getIdentityServiceId())
- .append(getCloudVersion(), castOther.getCloudVersion()).append(getClli(), castOther.getClli()).isEquals();
+ .append(getCloudVersion(), castOther.getCloudVersion()).append(getClli(), castOther.getClli())
+ .isEquals();
}
@Override
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudifyManager.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudifyManager.java
index 30ebca8699..a3df245ae6 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudifyManager.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CloudifyManager.java
@@ -21,15 +21,12 @@
package org.onap.so.db.catalog.beans;
import java.util.Date;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.openpojo.business.annotation.BusinessKey;
-
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -39,11 +36,9 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
- * EntityBean class for a Cloudify Manager. This bean represents a Cloudify
- * node through which TOSCA-based VNFs may be deployed. Each CloudSite in the
- * CloudConfig may have a Cloudify Manager for deployments using TOSCA blueprints.
- * Cloudify Managers may support multiple Cloud Sites, but each site will have
- * at most one Cloudify Manager.
+ * EntityBean class for a Cloudify Manager. This bean represents a Cloudify node through which TOSCA-based VNFs may be
+ * deployed. Each CloudSite in the CloudConfig may have a Cloudify Manager for deployments using TOSCA blueprints.
+ * Cloudify Managers may support multiple Cloud Sites, but each site will have at most one Cloudify Manager.
*
* This does not replace the ability to use the CloudSite directly via Openstack.
*
@@ -52,156 +47,157 @@ import javax.persistence.TemporalType;
@Entity
@Table(name = "cloudify_managers")
public class CloudifyManager {
-
- @JsonProperty
- @BusinessKey
- @Id
- @Column(name = "ID")
- private String id;
-
- @BusinessKey
- @JsonProperty ("cloudify_url")
- @Column(name = "CLOUDIFY_URL")
- private String cloudifyUrl;
-
- @BusinessKey
- @JsonProperty("username")
- @Column(name = "USERNAME")
- private String username;
-
- @BusinessKey
- @JsonProperty("password")
- @Column(name = "PASSWORD")
- private String password;
-
- @BusinessKey
- @JsonProperty("version")
- @Column(name = "VERSION")
- private String version;
-
- @JsonProperty("last_updated_by")
- @BusinessKey
- @Column(name = "LAST_UPDATED_BY")
- private String lastUpdatedBy ;
-
- @JsonProperty("creation_timestamp")
- @BusinessKey
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @JsonProperty("update_timestamp")
- @BusinessKey
- @Column(name = "UPDATE_TIMESTAMP")
- @Temporal(TemporalType.TIMESTAMP)
- private Date updated;
-
- public CloudifyManager() {}
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- this.updated = new Date();
- }
-
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
-
- public String getCloudifyUrl() {
- return cloudifyUrl;
- }
-
- public void setCloudifyUrl(String cloudifyUrl) {
- this.cloudifyUrl = cloudifyUrl;
- }
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getPassword() {
+
+ @JsonProperty
+ @BusinessKey
+ @Id
+ @Column(name = "ID")
+ private String id;
+
+ @BusinessKey
+ @JsonProperty("cloudify_url")
+ @Column(name = "CLOUDIFY_URL")
+ private String cloudifyUrl;
+
+ @BusinessKey
+ @JsonProperty("username")
+ @Column(name = "USERNAME")
+ private String username;
+
+ @BusinessKey
+ @JsonProperty("password")
+ @Column(name = "PASSWORD")
+ private String password;
+
+ @BusinessKey
+ @JsonProperty("version")
+ @Column(name = "VERSION")
+ private String version;
+
+ @JsonProperty("last_updated_by")
+ @BusinessKey
+ @Column(name = "LAST_UPDATED_BY")
+ private String lastUpdatedBy;
+
+ @JsonProperty("creation_timestamp")
+ @BusinessKey
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @JsonProperty("update_timestamp")
+ @BusinessKey
+ @Column(name = "UPDATE_TIMESTAMP")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date updated;
+
+ public CloudifyManager() {}
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ this.updated = new Date();
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getCloudifyUrl() {
+ return cloudifyUrl;
+ }
+
+ public void setCloudifyUrl(String cloudifyUrl) {
+ this.cloudifyUrl = cloudifyUrl;
+ }
+
+ 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;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
- public String getLastUpdatedBy() {
- return lastUpdatedBy;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public Date getUpdated() {
- return updated;
- }
-
- public void setLastUpdatedBy(String lastUpdatedBy) {
- this.lastUpdatedBy = lastUpdatedBy;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- public void setUpdated(Date updated) {
- this.updated = updated;
- }
-
- @Override
- public CloudifyManager clone() {
- CloudifyManager cloudifyManagerCopy = new CloudifyManager();
- cloudifyManagerCopy.id = this.id;
- cloudifyManagerCopy.cloudifyUrl = this.cloudifyUrl;
- cloudifyManagerCopy.username = this.username;
- cloudifyManagerCopy.password = this.password;
- cloudifyManagerCopy.version = this.version;
- return cloudifyManagerCopy;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("id", getId())
- .append("cloudifyUrl", getCloudifyUrl()).append("username", getUsername())
- .append("password", getPassword()).append("version", getVersion()).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (other == null) {
- return false;
- }
- if (!getClass().equals(other.getClass())) {
- return false;
- }
- CloudifyManager castOther = (CloudifyManager) other;
- return new EqualsBuilder().append(getId(), castOther.getId())
- .append(getCloudifyUrl(), castOther.getCloudifyUrl()).append(getUsername(), castOther.getUsername())
- .append(getPassword(), castOther.getPassword()).append(getVersion(), castOther.getVersion()).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder(1, 31).append(getId()).append(getCloudifyUrl()).append(getUsername())
- .append(getPassword()).append(getVersion()).toHashCode();
- }
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getLastUpdatedBy() {
+ return lastUpdatedBy;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public Date getUpdated() {
+ return updated;
+ }
+
+ public void setLastUpdatedBy(String lastUpdatedBy) {
+ this.lastUpdatedBy = lastUpdatedBy;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ public void setUpdated(Date updated) {
+ this.updated = updated;
+ }
+
+ @Override
+ public CloudifyManager clone() {
+ CloudifyManager cloudifyManagerCopy = new CloudifyManager();
+ cloudifyManagerCopy.id = this.id;
+ cloudifyManagerCopy.cloudifyUrl = this.cloudifyUrl;
+ cloudifyManagerCopy.username = this.username;
+ cloudifyManagerCopy.password = this.password;
+ cloudifyManagerCopy.version = this.version;
+ return cloudifyManagerCopy;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("id", getId())
+ .append("cloudifyUrl", getCloudifyUrl()).append("username", getUsername())
+ .append("password", getPassword()).append("version", getVersion()).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (other == null) {
+ return false;
+ }
+ if (!getClass().equals(other.getClass())) {
+ return false;
+ }
+ CloudifyManager castOther = (CloudifyManager) other;
+ return new EqualsBuilder().append(getId(), castOther.getId())
+ .append(getCloudifyUrl(), castOther.getCloudifyUrl()).append(getUsername(), castOther.getUsername())
+ .append(getPassword(), castOther.getPassword()).append(getVersion(), castOther.getVersion()).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(1, 31).append(getId()).append(getCloudifyUrl()).append(getUsername())
+ .append(getPassword()).append(getVersion()).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionNetworkResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionNetworkResourceCustomization.java
index d4de5cbcdf..566268ba57 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionNetworkResourceCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionNetworkResourceCustomization.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -34,175 +33,172 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "collection_network_resource_customization")
public class CollectionNetworkResourceCustomization implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 11115611315801079L;
-
- @BusinessKey
- @Id
- @Column(name = "MODEL_CUSTOMIZATION_UUID")
- private String modelCustomizationUUID = null;
-
- @Column(name = "MODEL_INSTANCE_NAME")
- private String modelInstanceName;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @BusinessKey
- @Column(name = "NETWORK_TECHNOLOGY")
- private String networkTechnology;
-
- @BusinessKey
- @Column(name = "NETWORK_TYPE")
- private String networkType = null;
-
- @BusinessKey
- @Column(name = "NETWORK_SCOPE")
- private String networkScope;
-
- @BusinessKey
- @Column(name = "NETWORK_ROLE")
- private String networkRole;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "NETWORK_RESOURCE_MODEL_UUID")
- private NetworkResource networkResource = null;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "INSTANCE_GROUP_MODEL_UUID")
- private InstanceGroup instanceGroup = null;
-
- @BusinessKey
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "CRC_MODEL_CUSTOMIZATION_UUID")
- private NetworkCollectionResourceCustomization networkResourceCustomization = null;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof CollectionNetworkResourceCustomization)) {
- return false;
- }
- CollectionNetworkResourceCustomization castOther = (CollectionNetworkResourceCustomization) other;
- return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID)
- .append(networkTechnology, castOther.networkTechnology).append(networkType, castOther.networkType)
- .append(networkScope, castOther.networkScope).append(networkRole, castOther.networkRole)
- .append(networkResourceCustomization, castOther.networkResourceCustomization).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelCustomizationUUID).append(networkTechnology).append(networkType)
- .append(networkScope).append(networkRole).append(networkResourceCustomization).toHashCode();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
- .append("modelInstanceName", modelInstanceName).append("created", created)
- .append("networkTechnology", networkTechnology).append("networkType", networkType)
- .append("networkScope", networkScope).append("networkRole", networkRole)
- .append("networkResource", networkResource).append("collectionResource", networkResourceCustomization)
- .toString();
- }
-
- public String getModelCustomizationUUID() {
- return this.modelCustomizationUUID;
- }
-
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
-
- @LinkedResource
- public NetworkCollectionResourceCustomization getNetworkResourceCustomization() {
- return networkResourceCustomization;
- }
-
- public void setNetworkResourceCustomization(NetworkCollectionResourceCustomization networkResourceCustomization) {
- this.networkResourceCustomization = networkResourceCustomization;
- }
-
- public String getModelInstanceName() {
- return this.modelInstanceName;
- }
-
- public void setModelInstanceName(String modelInstanceName) {
- this.modelInstanceName = modelInstanceName;
- }
-
- @LinkedResource
- public NetworkResource getNetworkResource() {
- return this.networkResource;
- }
-
- public void setNetworkResource(NetworkResource networkResource) {
- this.networkResource = networkResource;
- }
-
- public String getNetworkType() {
- return this.networkType;
- }
-
- public void setNetworkType(String networkType) {
- this.networkType = networkType;
- }
-
- public Date getCreated() {
- return this.created;
- }
-
- public String getNetworkTechnology() {
- return this.networkTechnology;
- }
-
- public void setNetworkTechnology(String networkTechnology) {
- this.networkTechnology = networkTechnology;
- }
-
- public String getNetworkScope() {
- return this.networkScope;
- }
-
- public void setNetworkScope(String networkScope) {
- this.networkScope = networkScope;
- }
-
- public void setNetworkRole(String networkRole) {
- this.networkRole = networkRole;
- }
-
- public String getNetworkRole() {
- return this.networkRole;
- }
-
- @LinkedResource
- public InstanceGroup getInstanceGroup() {
- return instanceGroup;
- }
-
- public void setInstanceGroup(InstanceGroup instanceGroup) {
- this.instanceGroup = instanceGroup;
- }
-
+ /**
+ *
+ */
+ private static final long serialVersionUID = 11115611315801079L;
+
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_CUSTOMIZATION_UUID")
+ private String modelCustomizationUUID = null;
+
+ @Column(name = "MODEL_INSTANCE_NAME")
+ private String modelInstanceName;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @BusinessKey
+ @Column(name = "NETWORK_TECHNOLOGY")
+ private String networkTechnology;
+
+ @BusinessKey
+ @Column(name = "NETWORK_TYPE")
+ private String networkType = null;
+
+ @BusinessKey
+ @Column(name = "NETWORK_SCOPE")
+ private String networkScope;
+
+ @BusinessKey
+ @Column(name = "NETWORK_ROLE")
+ private String networkRole;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "NETWORK_RESOURCE_MODEL_UUID")
+ private NetworkResource networkResource = null;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "INSTANCE_GROUP_MODEL_UUID")
+ private InstanceGroup instanceGroup = null;
+
+ @BusinessKey
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "CRC_MODEL_CUSTOMIZATION_UUID")
+ private NetworkCollectionResourceCustomization networkResourceCustomization = null;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof CollectionNetworkResourceCustomization)) {
+ return false;
+ }
+ CollectionNetworkResourceCustomization castOther = (CollectionNetworkResourceCustomization) other;
+ return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID)
+ .append(networkTechnology, castOther.networkTechnology).append(networkType, castOther.networkType)
+ .append(networkScope, castOther.networkScope).append(networkRole, castOther.networkRole)
+ .append(networkResourceCustomization, castOther.networkResourceCustomization).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelCustomizationUUID).append(networkTechnology).append(networkType)
+ .append(networkScope).append(networkRole).append(networkResourceCustomization).toHashCode();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
+ .append("modelInstanceName", modelInstanceName).append("created", created)
+ .append("networkTechnology", networkTechnology).append("networkType", networkType)
+ .append("networkScope", networkScope).append("networkRole", networkRole)
+ .append("networkResource", networkResource).append("collectionResource", networkResourceCustomization)
+ .toString();
+ }
+
+ public String getModelCustomizationUUID() {
+ return this.modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ @LinkedResource
+ public NetworkCollectionResourceCustomization getNetworkResourceCustomization() {
+ return networkResourceCustomization;
+ }
+
+ public void setNetworkResourceCustomization(NetworkCollectionResourceCustomization networkResourceCustomization) {
+ this.networkResourceCustomization = networkResourceCustomization;
+ }
+
+ public String getModelInstanceName() {
+ return this.modelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ this.modelInstanceName = modelInstanceName;
+ }
+
+ @LinkedResource
+ public NetworkResource getNetworkResource() {
+ return this.networkResource;
+ }
+
+ public void setNetworkResource(NetworkResource networkResource) {
+ this.networkResource = networkResource;
+ }
+
+ public String getNetworkType() {
+ return this.networkType;
+ }
+
+ public void setNetworkType(String networkType) {
+ this.networkType = networkType;
+ }
+
+ public Date getCreated() {
+ return this.created;
+ }
+
+ public String getNetworkTechnology() {
+ return this.networkTechnology;
+ }
+
+ public void setNetworkTechnology(String networkTechnology) {
+ this.networkTechnology = networkTechnology;
+ }
+
+ public String getNetworkScope() {
+ return this.networkScope;
+ }
+
+ public void setNetworkScope(String networkScope) {
+ this.networkScope = networkScope;
+ }
+
+ public void setNetworkRole(String networkRole) {
+ this.networkRole = networkRole;
+ }
+
+ public String getNetworkRole() {
+ return this.networkRole;
+ }
+
+ @LinkedResource
+ public InstanceGroup getInstanceGroup() {
+ return instanceGroup;
+ }
+
+ public void setInstanceGroup(InstanceGroup instanceGroup) {
+ this.instanceGroup = instanceGroup;
+ }
+
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResource.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResource.java
index f8148aa781..9a92d0a64f 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResource.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResource.java
@@ -23,7 +23,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -34,148 +33,145 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "collection_resource")
public class CollectionResource implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -8612818857960992110L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -8612818857960992110L;
- @BusinessKey
- @Id
- @Column(name = "MODEL_UUID")
- private String modelUUID;
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_UUID")
+ private String modelUUID;
- @Column(name = "MODEL_NAME")
- private String modelName;
+ @Column(name = "MODEL_NAME")
+ private String modelName;
- @Column(name = "MODEL_INVARIANT_UUID")
- private String modelInvariantUUID;
+ @Column(name = "MODEL_INVARIANT_UUID")
+ private String modelInvariantUUID;
- @Column(name = "MODEL_VERSION")
- private String modelVersion;
-
- @Column(name = "TOSCA_NODE_TYPE")
- private String toscaNodeType;
+ @Column(name = "MODEL_VERSION")
+ private String modelVersion;
+
+ @Column(name = "TOSCA_NODE_TYPE")
+ private String toscaNodeType;
- @Column(name = "DESCRIPTION")
- private String description;
+ @Column(name = "DESCRIPTION")
+ private String description;
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "collectionResource")
- private Set<CollectionResourceCustomization> collectionResourceCustomization;
-
- @OneToOne(cascade = CascadeType.ALL, mappedBy = "collectionResource")
- private InstanceGroup instanceGroup;
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof CollectionResource)) {
- return false;
- }
- CollectionResource castOther = (CollectionResource) other;
- return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelUUID).toHashCode();
- }
-
- public Set<CollectionResourceCustomization> getCollectionResourceCustomization() {
- return collectionResourceCustomization;
- }
-
- public void setCollectionResourceCustomization(
- Set<CollectionResourceCustomization> collectionResourceCustomization) {
- this.collectionResourceCustomization = collectionResourceCustomization;
- }
-
- public String getModelUUID() {
- return modelUUID;
- }
-
- public Date getCreated() {
- return this.created;
- }
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public void setModelUUID(String modelUUID) {
- this.modelUUID = modelUUID;
- }
-
- public String getModelName() {
- return modelName;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public String getModelInvariantUUID() {
- return modelInvariantUUID;
- }
-
- public void setModelInvariantUUID(String modelInvariantUUID) {
- this.modelInvariantUUID = modelInvariantUUID;
- }
-
- public String getModelVersion() {
- return modelVersion;
- }
-
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
-
- public String getToscaNodeType() {
- return toscaNodeType;
- }
-
- public void setToscaNodeType(String toscaNodeType) {
- this.toscaNodeType = toscaNodeType;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- @LinkedResource
- public InstanceGroup getInstanceGroup() {
- return instanceGroup;
- }
-
- public void setInstanceGroup(InstanceGroup instanceGroup) {
- this.instanceGroup = instanceGroup;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelName", modelName)
- .append("modelInvariantUUID", modelInvariantUUID).append("modelVersion", modelVersion)
- .append("toscaNodeType", toscaNodeType).append("description", description).append("created", created)
- .toString();
- }
-} \ No newline at end of file
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "collectionResource")
+ private Set<CollectionResourceCustomization> collectionResourceCustomization;
+
+ @OneToOne(cascade = CascadeType.ALL, mappedBy = "collectionResource")
+ private InstanceGroup instanceGroup;
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof CollectionResource)) {
+ return false;
+ }
+ CollectionResource castOther = (CollectionResource) other;
+ return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelUUID).toHashCode();
+ }
+
+ public Set<CollectionResourceCustomization> getCollectionResourceCustomization() {
+ return collectionResourceCustomization;
+ }
+
+ public void setCollectionResourceCustomization(
+ Set<CollectionResourceCustomization> collectionResourceCustomization) {
+ this.collectionResourceCustomization = collectionResourceCustomization;
+ }
+
+ public String getModelUUID() {
+ return modelUUID;
+ }
+
+ public Date getCreated() {
+ return this.created;
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public void setModelUUID(String modelUUID) {
+ this.modelUUID = modelUUID;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getModelInvariantUUID() {
+ return modelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ this.modelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ public String getToscaNodeType() {
+ return toscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ this.toscaNodeType = toscaNodeType;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ @LinkedResource
+ public InstanceGroup getInstanceGroup() {
+ return instanceGroup;
+ }
+
+ public void setInstanceGroup(InstanceGroup instanceGroup) {
+ this.instanceGroup = instanceGroup;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelName", modelName)
+ .append("modelInvariantUUID", modelInvariantUUID).append("modelVersion", modelVersion)
+ .append("toscaNodeType", toscaNodeType).append("description", description).append("created", created)
+ .toString();
+ }
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceCustomization.java
index 34389de22f..8214c0a074 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceCustomization.java
@@ -23,7 +23,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
@@ -39,13 +38,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@@ -54,127 +50,127 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "collection_resource_customization")
public class CollectionResourceCustomization implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -8328823396870652841L;
-
- @BusinessKey
- @Id
- @Column(name = "MODEL_CUSTOMIZATION_UUID")
- private String modelCustomizationUUID;
-
- @Column(name = "MODEL_INSTANCE_NAME")
- private String modelInstanceName;
-
- @Column(name = "COLLECTION_RESOURCE_TYPE")
- private String type;
-
- @Column(name = "ROLE")
- private String role;
-
- @Column(name = "FUNCTION")
- private String function;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "CR_MODEL_UUID")
- private CollectionResource collectionResource;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "collectionResourceCust")
- private List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupCustomizations;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
- .append("modelInstanceName", modelInstanceName).append("type", type).append("role", role)
- .append("function", function).append("created", created)
- .append("collectionResource", collectionResource)
- .append("collectionInstanceGroupCustomizations", collectionInstanceGroupCustomizations).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof CollectionResourceCustomization)) {
- return false;
- }
- CollectionResourceCustomization castOther = (CollectionResourceCustomization) other;
- return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode();
- }
-
- public Date getCreated() {
- return this.created;
- }
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public String getModelCustomizationUUID() {
- return modelCustomizationUUID;
- }
-
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
-
- public String getModelInstanceName() {
- return modelInstanceName;
- }
-
- public void setModelInstanceName(String modelInstanceName) {
- this.modelInstanceName = modelInstanceName;
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
-
- public String getRole() {
- return role;
- }
-
- public void setRole(String role) {
- this.role = role;
- }
-
- public String getFunction() {
- return function;
- }
-
- public void setFunction(String function) {
- this.function = function;
- }
-
- @LinkedResource
- public CollectionResource getCollectionResource() {
- return collectionResource;
- }
-
- public void setCollectionResource(CollectionResource collectionResource) {
- this.collectionResource = collectionResource;
- }
-
- @LinkedResource
- public List<CollectionResourceInstanceGroupCustomization> getCollectionInstanceGroupCustomizations() {
- return collectionInstanceGroupCustomizations;
- }
-
- public void setCollectionInstanceGroupCustomizations(
- List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupCustomizations) {
- this.collectionInstanceGroupCustomizations = collectionInstanceGroupCustomizations;
- }
-} \ No newline at end of file
+ /**
+ *
+ */
+ private static final long serialVersionUID = -8328823396870652841L;
+
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_CUSTOMIZATION_UUID")
+ private String modelCustomizationUUID;
+
+ @Column(name = "MODEL_INSTANCE_NAME")
+ private String modelInstanceName;
+
+ @Column(name = "COLLECTION_RESOURCE_TYPE")
+ private String type;
+
+ @Column(name = "ROLE")
+ private String role;
+
+ @Column(name = "FUNCTION")
+ private String function;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "CR_MODEL_UUID")
+ private CollectionResource collectionResource;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "collectionResourceCust")
+ private List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupCustomizations;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
+ .append("modelInstanceName", modelInstanceName).append("type", type).append("role", role)
+ .append("function", function).append("created", created)
+ .append("collectionResource", collectionResource)
+ .append("collectionInstanceGroupCustomizations", collectionInstanceGroupCustomizations).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof CollectionResourceCustomization)) {
+ return false;
+ }
+ CollectionResourceCustomization castOther = (CollectionResourceCustomization) other;
+ return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode();
+ }
+
+ public Date getCreated() {
+ return this.created;
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public String getModelCustomizationUUID() {
+ return modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ public String getModelInstanceName() {
+ return modelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ this.modelInstanceName = modelInstanceName;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+
+ public String getFunction() {
+ return function;
+ }
+
+ public void setFunction(String function) {
+ this.function = function;
+ }
+
+ @LinkedResource
+ public CollectionResource getCollectionResource() {
+ return collectionResource;
+ }
+
+ public void setCollectionResource(CollectionResource collectionResource) {
+ this.collectionResource = collectionResource;
+ }
+
+ @LinkedResource
+ public List<CollectionResourceInstanceGroupCustomization> getCollectionInstanceGroupCustomizations() {
+ return collectionInstanceGroupCustomizations;
+ }
+
+ public void setCollectionInstanceGroupCustomizations(
+ List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupCustomizations) {
+ this.collectionInstanceGroupCustomizations = collectionInstanceGroupCustomizations;
+ }
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceInstanceGroupCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceInstanceGroupCustomization.java
index 7379225a34..4a72f9a3c2 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceInstanceGroupCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceInstanceGroupCustomization.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -35,13 +34,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@@ -49,132 +45,132 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "collection_resource_instance_group_customization")
public class CollectionResourceInstanceGroupCustomization implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 5169990063225044265L;
-
- @BusinessKey
- @Id
- @Column(name = "COLLECTION_RESOURCE_CUSTOMIZATION_MODEL_UUID")
- private String modelCustomizationUUID;
-
- @BusinessKey
- @Id
- @Column(name = "INSTANCE_GROUP_MODEL_UUID")
- private String modelUUID;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "COLLECTION_RESOURCE_CUSTOMIZATION_MODEL_UUID", updatable = false, insertable = false)
- private CollectionResourceCustomization collectionResourceCust;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "INSTANCE_GROUP_MODEL_UUID", updatable = false, insertable = false)
- private InstanceGroup instanceGroup;
-
- @Column(name = "FUNCTION")
- private String function;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @Column(name = "SUBINTERFACE_NETWORK_QUANTITY")
- private Integer subInterfaceNetworkQuantity;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
- .append("modelUUID", modelUUID).append("collectionResourceCust", collectionResourceCust)
- .append("instanceGroup", instanceGroup).append("function", function).append("description", description)
- .append("created", created).append("subInterfaceNetworkQuantity", subInterfaceNetworkQuantity)
- .toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof CollectionResourceInstanceGroupCustomization)) {
- return false;
- }
- CollectionResourceInstanceGroupCustomization castOther = (CollectionResourceInstanceGroupCustomization) other;
- return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID)
- .append(modelUUID, castOther.modelUUID).append(collectionResourceCust, castOther.collectionResourceCust)
- .append(instanceGroup, castOther.instanceGroup).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelCustomizationUUID).append(modelUUID).append(collectionResourceCust)
- .append(instanceGroup).toHashCode();
- }
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public String getModelCustomizationUUID() {
- return modelCustomizationUUID;
- }
-
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
-
- public String getModelUUID() {
- return modelUUID;
- }
-
- public void setModelUUID(String modelUUID) {
- this.modelUUID = modelUUID;
- }
-
- public String getFunction() {
- return function;
- }
-
- public void setFunction(String function) {
- this.function = function;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public Integer getSubInterfaceNetworkQuantity() {
- return subInterfaceNetworkQuantity;
- }
-
- public void setSubInterfaceNetworkQuantity(Integer subInterfaceNetworkQuantity) {
- this.subInterfaceNetworkQuantity = subInterfaceNetworkQuantity;
- }
-
- @LinkedResource
- public CollectionResourceCustomization getCollectionResourceCust() {
- return collectionResourceCust;
- }
-
- public void setCollectionResourceCust(CollectionResourceCustomization collectionResourceCust) {
- this.collectionResourceCust = collectionResourceCust;
- }
-
- @LinkedResource
- public InstanceGroup getInstanceGroup() {
- return instanceGroup;
- }
-
- public void setInstanceGroup(InstanceGroup instanceGroup) {
- this.instanceGroup = instanceGroup;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = 5169990063225044265L;
+
+ @BusinessKey
+ @Id
+ @Column(name = "COLLECTION_RESOURCE_CUSTOMIZATION_MODEL_UUID")
+ private String modelCustomizationUUID;
+
+ @BusinessKey
+ @Id
+ @Column(name = "INSTANCE_GROUP_MODEL_UUID")
+ private String modelUUID;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "COLLECTION_RESOURCE_CUSTOMIZATION_MODEL_UUID", updatable = false, insertable = false)
+ private CollectionResourceCustomization collectionResourceCust;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "INSTANCE_GROUP_MODEL_UUID", updatable = false, insertable = false)
+ private InstanceGroup instanceGroup;
+
+ @Column(name = "FUNCTION")
+ private String function;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @Column(name = "SUBINTERFACE_NETWORK_QUANTITY")
+ private Integer subInterfaceNetworkQuantity;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
+ .append("modelUUID", modelUUID).append("collectionResourceCust", collectionResourceCust)
+ .append("instanceGroup", instanceGroup).append("function", function).append("description", description)
+ .append("created", created).append("subInterfaceNetworkQuantity", subInterfaceNetworkQuantity)
+ .toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof CollectionResourceInstanceGroupCustomization)) {
+ return false;
+ }
+ CollectionResourceInstanceGroupCustomization castOther = (CollectionResourceInstanceGroupCustomization) other;
+ return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID)
+ .append(modelUUID, castOther.modelUUID).append(collectionResourceCust, castOther.collectionResourceCust)
+ .append(instanceGroup, castOther.instanceGroup).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelCustomizationUUID).append(modelUUID).append(collectionResourceCust)
+ .append(instanceGroup).toHashCode();
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public String getModelCustomizationUUID() {
+ return modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ public String getModelUUID() {
+ return modelUUID;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ this.modelUUID = modelUUID;
+ }
+
+ public String getFunction() {
+ return function;
+ }
+
+ public void setFunction(String function) {
+ this.function = function;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public Integer getSubInterfaceNetworkQuantity() {
+ return subInterfaceNetworkQuantity;
+ }
+
+ public void setSubInterfaceNetworkQuantity(Integer subInterfaceNetworkQuantity) {
+ this.subInterfaceNetworkQuantity = subInterfaceNetworkQuantity;
+ }
+
+ @LinkedResource
+ public CollectionResourceCustomization getCollectionResourceCust() {
+ return collectionResourceCust;
+ }
+
+ public void setCollectionResourceCust(CollectionResourceCustomization collectionResourceCust) {
+ this.collectionResourceCust = collectionResourceCust;
+ }
+
+ @LinkedResource
+ public InstanceGroup getInstanceGroup() {
+ return instanceGroup;
+ }
+
+ public void setInstanceGroup(InstanceGroup instanceGroup) {
+ this.instanceGroup = instanceGroup;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceInstanceGroupCustomizationId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceInstanceGroupCustomizationId.java
index ff35bdb390..6d5c4109ee 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceInstanceGroupCustomizationId.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CollectionResourceInstanceGroupCustomizationId.java
@@ -21,58 +21,57 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
public class CollectionResourceInstanceGroupCustomizationId implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 7118300524797895317L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 7118300524797895317L;
- @BusinessKey
- private String modelCustomizationUUID;
- @BusinessKey
- private String modelUUID;
+ @BusinessKey
+ private String modelCustomizationUUID;
+ @BusinessKey
+ private String modelUUID;
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
- .append("modelUUID", modelUUID).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
+ .append("modelUUID", modelUUID).toString();
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof CollectionResourceInstanceGroupCustomizationId)) {
- return false;
- }
- CollectionResourceInstanceGroupCustomizationId castOther = (CollectionResourceInstanceGroupCustomizationId) other;
- return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID)
- .append(modelUUID, castOther.modelUUID).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof CollectionResourceInstanceGroupCustomizationId)) {
+ return false;
+ }
+ CollectionResourceInstanceGroupCustomizationId castOther =
+ (CollectionResourceInstanceGroupCustomizationId) other;
+ return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID)
+ .append(modelUUID, castOther.modelUUID).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelCustomizationUUID).append(modelUUID).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelCustomizationUUID).append(modelUUID).toHashCode();
+ }
- public String getModelCustomizationUUID() {
- return this.modelCustomizationUUID;
- }
+ public String getModelCustomizationUUID() {
+ return this.modelCustomizationUUID;
+ }
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
- public String getModelUUID() {
- return this.modelUUID;
- }
+ public String getModelUUID() {
+ return this.modelUUID;
+ }
- public void setModelUUID(String modelUUID) {
- this.modelUUID = modelUUID;
- }
+ public void setModelUUID(String modelUUID) {
+ this.modelUUID = modelUUID;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResource.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResource.java
index ccfa71306b..9c2e1de244 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResource.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResource.java
@@ -23,7 +23,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -33,151 +32,149 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
-@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
+@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Entity
@Table(name = "configuration")
public class ConfigurationResource implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 6675926401792679171L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 6675926401792679171L;
+
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_UUID")
+ private String modelUUID;
+
+ @Column(name = "MODEL_INVARIANT_UUID")
+ private String modelInvariantUUID;
- @BusinessKey
- @Id
- @Column(name = "MODEL_UUID")
- private String modelUUID;
+ @Column(name = "MODEL_VERSION")
+ private String modelVersion;
- @Column(name = "MODEL_INVARIANT_UUID")
- private String modelInvariantUUID;
+ @Column(name = "MODEL_NAME")
+ private String modelName;
+
+ @Column(name = "TOSCA_NODE_TYPE")
+ private String toscaNodeType;
- @Column(name = "MODEL_VERSION")
- private String modelVersion;
-
- @Column(name = "MODEL_NAME")
- private String modelName;
-
- @Column(name = "TOSCA_NODE_TYPE")
- private String toscaNodeType;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "configurationResource")
- private Set<ConfigurationResourceCustomization> configurationResourceCustomization;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "configurationResource")
- private Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomization;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public String getModelUUID() {
- return modelUUID;
- }
-
- public void setModelUUID(String modelUUID) {
- this.modelUUID = modelUUID;
- }
-
- public String getModelInvariantUUID() {
- return modelInvariantUUID;
- }
-
- public void setModelInvariantUUID(String modelInvariantUUID) {
- this.modelInvariantUUID = modelInvariantUUID;
- }
-
- public String getModelVersion() {
- return modelVersion;
- }
-
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
-
- public String getModelName() {
- return modelName;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public String getToscaNodeType() {
- return toscaNodeType;
- }
-
- public void setToscaNodeType(String toscaNodeType) {
- this.toscaNodeType = toscaNodeType;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Date getCreated() {
- return created;
- }
-
- @LinkedResource
- public Set<ConfigurationResourceCustomization> getConfigurationResourceCustomization() {
- return configurationResourceCustomization;
- }
-
- public void setConfigurationResourceCustomization(
- Set<ConfigurationResourceCustomization> configurationResourceCustomization) {
- this.configurationResourceCustomization = configurationResourceCustomization;
- }
-
- @LinkedResource
- public Set<CvnfcConfigurationCustomization> getCvnfcConfigurationCustomization() {
- return cvnfcConfigurationCustomization;
- }
-
- public void setCvnfcConfigurationCustomization(Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomization) {
- this.cvnfcConfigurationCustomization = cvnfcConfigurationCustomization;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelInvariantUUID", modelInvariantUUID)
- .append("modelVersion", modelVersion).append("modelName", modelName)
- .append("toscaNodeType", toscaNodeType).append("description", description).append("created", created)
- .append("configurationResourceCustomization", configurationResourceCustomization).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ConfigurationResource)) {
- return false;
- }
- ConfigurationResource castOther = (ConfigurationResource) other;
- return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelUUID).toHashCode();
- }
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "configurationResource")
+ private Set<ConfigurationResourceCustomization> configurationResourceCustomization;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "configurationResource")
+ private Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomization;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public String getModelUUID() {
+ return modelUUID;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ this.modelUUID = modelUUID;
+ }
+
+ public String getModelInvariantUUID() {
+ return modelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ this.modelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getToscaNodeType() {
+ return toscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ this.toscaNodeType = toscaNodeType;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ @LinkedResource
+ public Set<ConfigurationResourceCustomization> getConfigurationResourceCustomization() {
+ return configurationResourceCustomization;
+ }
+
+ public void setConfigurationResourceCustomization(
+ Set<ConfigurationResourceCustomization> configurationResourceCustomization) {
+ this.configurationResourceCustomization = configurationResourceCustomization;
+ }
+
+ @LinkedResource
+ public Set<CvnfcConfigurationCustomization> getCvnfcConfigurationCustomization() {
+ return cvnfcConfigurationCustomization;
+ }
+
+ public void setCvnfcConfigurationCustomization(
+ Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomization) {
+ this.cvnfcConfigurationCustomization = cvnfcConfigurationCustomization;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelInvariantUUID", modelInvariantUUID)
+ .append("modelVersion", modelVersion).append("modelName", modelName)
+ .append("toscaNodeType", toscaNodeType).append("description", description).append("created", created)
+ .append("configurationResourceCustomization", configurationResourceCustomization).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ConfigurationResource)) {
+ return false;
+ }
+ ConfigurationResource castOther = (ConfigurationResource) other;
+ return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelUUID).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResourceCustomization.java
index 0b02c11701..059935fff3 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResourceCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResourceCustomization.java
@@ -23,7 +23,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -38,153 +37,150 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "configuration_customization")
public class ConfigurationResourceCustomization implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 1230671937560638856L;
-
- @BusinessKey
- @Id
- @Column(name = "MODEL_CUSTOMIZATION_UUID")
- private String modelCustomizationUUID;
-
- @Column(name = "MODEL_INSTANCE_NAME")
- private String modelInstanceName;
-
- @Column(name = "CONFIGURATION_FUNCTION")
- private String nfFunction;
-
- @Column(name = "CONFIGURATION_TYPE")
- private String nfType;
-
- @Column(name = "CONFIGURATION_ROLE")
- private String nfRole;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @Column(name = "SERVICE_PROXY_CUSTOMIZATION_MODEL_CUSTOMIZATION_UUID")
- private String serviceProxyResourceCustomizationUUID;
-
- @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "CONFIGURATION_CUSTOMIZATION_MODEL_CUSTOMIZATION_UUID")
- private ConfigurationResourceCustomization configResourceCustomization;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "CONFIGURATION_MODEL_UUID")
- private ConfigurationResource configurationResource;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public String getModelCustomizationUUID() {
- return modelCustomizationUUID;
- }
-
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
-
- public String getModelInstanceName() {
- return modelInstanceName;
- }
-
- public void setModelInstanceName(String modelInstanceName) {
- this.modelInstanceName = modelInstanceName;
- }
-
- public String getNfFunction() {
- return nfFunction;
- }
-
- public void setNfFunction(String nfFunction) {
- this.nfFunction = nfFunction;
- }
-
- public String getNfType() {
- return nfType;
- }
-
- public void setNfType(String nfType) {
- this.nfType = nfType;
- }
-
- public String getNfRole() {
- return nfRole;
- }
-
- public void setNfRole(String nfRole) {
- this.nfRole = nfRole;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public String getServiceProxyResourceCustomizationUUID() {
- return serviceProxyResourceCustomizationUUID;
- }
-
- public void setServiceProxyResourceCustomizationUUID(String serviceProxyResourceCustomizationUUID) {
- this.serviceProxyResourceCustomizationUUID = serviceProxyResourceCustomizationUUID;
- }
-
- @LinkedResource
- public ConfigurationResourceCustomization getConfigResourceCustomization() {
- return configResourceCustomization;
- }
-
- public void setConfigResourceCustomization(ConfigurationResourceCustomization configResourceCustomization) {
- this.configResourceCustomization = configResourceCustomization;
- }
-
- @LinkedResource
- public ConfigurationResource getConfigurationResource() {
- return configurationResource;
- }
-
- public void setConfigurationResource(ConfigurationResource configurationResource) {
- this.configurationResource = configurationResource;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
- .append("modelInstanceName", modelInstanceName).append("nfFunction", nfFunction)
- .append("nfType", nfType).append("nfRole", nfRole).append("created", created)
- //.append("serviceProxyResourceCustomization", serviceProxyResourceCustomization)
- .append("configResourceCustomization", configResourceCustomization)
- .append("configurationResource", configurationResource).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ConfigurationResourceCustomization)) {
- return false;
- }
- ConfigurationResourceCustomization castOther = (ConfigurationResourceCustomization) other;
- return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode();
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1230671937560638856L;
+
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_CUSTOMIZATION_UUID")
+ private String modelCustomizationUUID;
+
+ @Column(name = "MODEL_INSTANCE_NAME")
+ private String modelInstanceName;
+
+ @Column(name = "CONFIGURATION_FUNCTION")
+ private String nfFunction;
+
+ @Column(name = "CONFIGURATION_TYPE")
+ private String nfType;
+
+ @Column(name = "CONFIGURATION_ROLE")
+ private String nfRole;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @Column(name = "SERVICE_PROXY_CUSTOMIZATION_MODEL_CUSTOMIZATION_UUID")
+ private String serviceProxyResourceCustomizationUUID;
+
+ @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "CONFIGURATION_CUSTOMIZATION_MODEL_CUSTOMIZATION_UUID")
+ private ConfigurationResourceCustomization configResourceCustomization;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "CONFIGURATION_MODEL_UUID")
+ private ConfigurationResource configurationResource;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public String getModelCustomizationUUID() {
+ return modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ public String getModelInstanceName() {
+ return modelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ this.modelInstanceName = modelInstanceName;
+ }
+
+ public String getNfFunction() {
+ return nfFunction;
+ }
+
+ public void setNfFunction(String nfFunction) {
+ this.nfFunction = nfFunction;
+ }
+
+ public String getNfType() {
+ return nfType;
+ }
+
+ public void setNfType(String nfType) {
+ this.nfType = nfType;
+ }
+
+ public String getNfRole() {
+ return nfRole;
+ }
+
+ public void setNfRole(String nfRole) {
+ this.nfRole = nfRole;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public String getServiceProxyResourceCustomizationUUID() {
+ return serviceProxyResourceCustomizationUUID;
+ }
+
+ public void setServiceProxyResourceCustomizationUUID(String serviceProxyResourceCustomizationUUID) {
+ this.serviceProxyResourceCustomizationUUID = serviceProxyResourceCustomizationUUID;
+ }
+
+ @LinkedResource
+ public ConfigurationResourceCustomization getConfigResourceCustomization() {
+ return configResourceCustomization;
+ }
+
+ public void setConfigResourceCustomization(ConfigurationResourceCustomization configResourceCustomization) {
+ this.configResourceCustomization = configResourceCustomization;
+ }
+
+ @LinkedResource
+ public ConfigurationResource getConfigurationResource() {
+ return configurationResource;
+ }
+
+ public void setConfigurationResource(ConfigurationResource configurationResource) {
+ this.configurationResource = configurationResource;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
+ .append("modelInstanceName", modelInstanceName).append("nfFunction", nfFunction)
+ .append("nfType", nfType).append("nfRole", nfRole).append("created", created)
+ // .append("serviceProxyResourceCustomization", serviceProxyResourceCustomization)
+ .append("configResourceCustomization", configResourceCustomization)
+ .append("configurationResource", configurationResource).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ConfigurationResourceCustomization)) {
+ return false;
+ }
+ ConfigurationResourceCustomization castOther = (ConfigurationResourceCustomization) other;
+ return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ControllerSelectionReference.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ControllerSelectionReference.java
index de0dd39edc..425e0b8bbc 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ControllerSelectionReference.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ControllerSelectionReference.java
@@ -20,13 +20,11 @@ package org.onap.so.db.catalog.beans;
*/
import java.io.Serializable;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
-
import com.openpojo.business.annotation.BusinessKey;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
@@ -37,70 +35,75 @@ import org.apache.commons.lang3.builder.EqualsBuilder;
@Table(name = "CONTROLLER_SELECTION_REFERENCE")
public class ControllerSelectionReference implements Serializable {
- private static final long serialVersionUID = -608098800737567188L;
-
- @BusinessKey
- @Id
- @Column(name = "VNF_TYPE")
- private String vnfType;
-
- @BusinessKey
- @Id
- @Column(name = "CONTROLLER_NAME")
+ private static final long serialVersionUID = -608098800737567188L;
+
+ @BusinessKey
+ @Id
+ @Column(name = "VNF_TYPE")
+ private String vnfType;
+
+ @BusinessKey
+ @Id
+ @Column(name = "CONTROLLER_NAME")
private String controllerName;
-
- @BusinessKey
- @Id
- @Column(name = "ACTION_CATEGORY")
+
+ @BusinessKey
+ @Id
+ @Column(name = "ACTION_CATEGORY")
private String actionCategory;
-
- public String getVnfType() {
- return vnfType;
- }
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
- public String getControllerName() {
- return controllerName;
- }
- public void setControllerName(String controllerName) {
- this.controllerName = controllerName;
- }
- public String getActionCategory() {
- return actionCategory;
- }
- public void setActionCategory(String actionCategory) {
- this.actionCategory = actionCategory;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("vnfType", vnfType).append("controllerName", controllerName)
- .append("actionCategory", actionCategory).toString();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ControllerSelectionReference)) {
- return false;
- }
- ControllerSelectionReference castOther = (ControllerSelectionReference) other;
- return new EqualsBuilder().append(vnfType, castOther.vnfType).append(controllerName, castOther.controllerName)
- .append(actionCategory, castOther.actionCategory).isEquals();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(vnfType).append(controllerName).append(actionCategory).toHashCode();
- }
+
+ public String getVnfType() {
+ return vnfType;
+ }
+
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ public String getControllerName() {
+ return controllerName;
+ }
+
+ public void setControllerName(String controllerName) {
+ this.controllerName = controllerName;
+ }
+
+ public String getActionCategory() {
+ return actionCategory;
+ }
+
+ public void setActionCategory(String actionCategory) {
+ this.actionCategory = actionCategory;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("vnfType", vnfType).append("controllerName", controllerName)
+ .append("actionCategory", actionCategory).toString();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ControllerSelectionReference)) {
+ return false;
+ }
+ ControllerSelectionReference castOther = (ControllerSelectionReference) other;
+ return new EqualsBuilder().append(vnfType, castOther.vnfType).append(controllerName, castOther.controllerName)
+ .append(actionCategory, castOther.actionCategory).isEquals();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(vnfType).append(controllerName).append(actionCategory).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ControllerSelectionReferenceId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ControllerSelectionReferenceId.java
index e6ee349be6..f06519c74c 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ControllerSelectionReferenceId.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ControllerSelectionReferenceId.java
@@ -21,7 +21,6 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import com.openpojo.business.annotation.BusinessKey;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
@@ -30,54 +29,59 @@ import org.apache.commons.lang3.builder.EqualsBuilder;
public class ControllerSelectionReferenceId implements Serializable {
- private static final long serialVersionUID = 1L;
- @BusinessKey
- private String vnfType;
- @BusinessKey
+ private static final long serialVersionUID = 1L;
+ @BusinessKey
+ private String vnfType;
+ @BusinessKey
private String controllerName;
- @BusinessKey
+ @BusinessKey
private String actionCategory;
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ControllerSelectionReferenceId)) {
- return false;
- }
- ControllerSelectionReferenceId castOther = (ControllerSelectionReferenceId) other;
- return new EqualsBuilder().append(vnfType, castOther.vnfType).append(controllerName, castOther.controllerName)
- .append(actionCategory, castOther.actionCategory).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(vnfType).append(controllerName).append(actionCategory).toHashCode();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("vnfType", vnfType).append("controllerName", controllerName)
- .append("actionCategory", actionCategory).toString();
- }
-
- public String getVnfType() {
- return vnfType;
- }
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
- public String getControllerName() {
- return controllerName;
- }
- public void setControllerName(String controllerName) {
- this.controllerName = controllerName;
- }
- public String getActionCategory() {
- return actionCategory;
- }
- public void setActionCategory(String actionCategory) {
- this.actionCategory = actionCategory;
- }
-
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ControllerSelectionReferenceId)) {
+ return false;
+ }
+ ControllerSelectionReferenceId castOther = (ControllerSelectionReferenceId) other;
+ return new EqualsBuilder().append(vnfType, castOther.vnfType).append(controllerName, castOther.controllerName)
+ .append(actionCategory, castOther.actionCategory).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(vnfType).append(controllerName).append(actionCategory).toHashCode();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("vnfType", vnfType).append("controllerName", controllerName)
+ .append("actionCategory", actionCategory).toString();
+ }
+
+ public String getVnfType() {
+ return vnfType;
+ }
+
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ public String getControllerName() {
+ return controllerName;
+ }
+
+ public void setControllerName(String controllerName) {
+ this.controllerName = controllerName;
+ }
+
+ public String getActionCategory() {
+ return actionCategory;
+ }
+
+ public void setActionCategory(String actionCategory) {
+ this.actionCategory = actionCategory;
+ }
+
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcConfigurationCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcConfigurationCustomization.java
index 1e09c6e671..05d43d093c 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcConfigurationCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcConfigurationCustomization.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -37,174 +36,172 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.fasterxml.jackson.annotation.JsonFormat;
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "cvnfc_configuration_customization")
public class CvnfcConfigurationCustomization implements Serializable {
- private static final long serialVersionUID = -3153216266280581103L;
-
- @Id
- @BusinessKey
- @Column(name = "ID")
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
-
- @Column(name = "MODEL_CUSTOMIZATION_UUID")
- private String modelCustomizationUUID;
-
- @Column(name = "MODEL_INSTANCE_NAME")
- private String modelInstanceName;
-
- @Column(name = "CONFIGURATION_TYPE")
- private String configurationType;
-
- @Column(name = "CONFIGURATION_ROLE")
- private String configurationRole;
-
- @Column(name = "CONFIGURATION_FUNCTION")
- private String configurationFunction;
-
- @Column(name = "POLICY_NAME")
- private String policyName;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "CONFIGURATION_MODEL_UUID")
- private ConfigurationResource configurationResource;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "CVNFC_CUSTOMIZATION_ID")
- private CvnfcCustomization cvnfcCustomization;
-
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof CvnfcConfigurationCustomization)) {
- return false;
- }
- CvnfcConfigurationCustomization castOther = (CvnfcConfigurationCustomization) other;
- return new EqualsBuilder().append(id, castOther.id).isEquals();
- }
-
-
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(id).toHashCode();
- }
-
-
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", id).append("modelCustomizationUUID", modelCustomizationUUID)
- .append("modelInstanceName", modelInstanceName).append("configurationType", configurationType)
- .append("configurationRole", configurationRole).append("configurationFunction", configurationFunction)
- .append("policyName", policyName).append("created", created)
- .append("configurationResource", configurationResource).append("cvnfcCustomization", cvnfcCustomization).toString();
- }
-
-
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getModelCustomizationUUID() {
- return modelCustomizationUUID;
- }
-
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
-
- public String getModelInstanceName() {
- return modelInstanceName;
- }
-
- public void setModelInstanceName(String modelInstanceName) {
- this.modelInstanceName = modelInstanceName;
- }
-
- public String getConfigurationType() {
- return configurationType;
- }
-
- public void setConfigurationType(String configurationType) {
- this.configurationType = configurationType;
- }
-
- public String getConfigurationRole() {
- return configurationRole;
- }
-
- public void setConfigurationRole(String configurationRole) {
- this.configurationRole = configurationRole;
- }
-
- public String getConfigurationFunction() {
- return configurationFunction;
- }
-
- public void setConfigurationFunction(String configurationFunction) {
- this.configurationFunction = configurationFunction;
- }
-
- public String getPolicyName() {
- return policyName;
- }
-
- public void setPolicyName(String policyName) {
- this.policyName = policyName;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
+ private static final long serialVersionUID = -3153216266280581103L;
+
+ @Id
+ @BusinessKey
+ @Column(name = "ID")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer id;
+
+ @Column(name = "MODEL_CUSTOMIZATION_UUID")
+ private String modelCustomizationUUID;
+
+ @Column(name = "MODEL_INSTANCE_NAME")
+ private String modelInstanceName;
+
+ @Column(name = "CONFIGURATION_TYPE")
+ private String configurationType;
+
+ @Column(name = "CONFIGURATION_ROLE")
+ private String configurationRole;
+
+ @Column(name = "CONFIGURATION_FUNCTION")
+ private String configurationFunction;
+
+ @Column(name = "POLICY_NAME")
+ private String policyName;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "CONFIGURATION_MODEL_UUID")
+ private ConfigurationResource configurationResource;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "CVNFC_CUSTOMIZATION_ID")
+ private CvnfcCustomization cvnfcCustomization;
+
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof CvnfcConfigurationCustomization)) {
+ return false;
+ }
+ CvnfcConfigurationCustomization castOther = (CvnfcConfigurationCustomization) other;
+ return new EqualsBuilder().append(id, castOther.id).isEquals();
+ }
+
+
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(id).toHashCode();
+ }
+
+
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", id).append("modelCustomizationUUID", modelCustomizationUUID)
+ .append("modelInstanceName", modelInstanceName).append("configurationType", configurationType)
+ .append("configurationRole", configurationRole).append("configurationFunction", configurationFunction)
+ .append("policyName", policyName).append("created", created)
+ .append("configurationResource", configurationResource).append("cvnfcCustomization", cvnfcCustomization)
+ .toString();
+ }
+
+
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getModelCustomizationUUID() {
+ return modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ public String getModelInstanceName() {
+ return modelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ this.modelInstanceName = modelInstanceName;
+ }
+
+ public String getConfigurationType() {
+ return configurationType;
+ }
+
+ public void setConfigurationType(String configurationType) {
+ this.configurationType = configurationType;
+ }
+
+ public String getConfigurationRole() {
+ return configurationRole;
+ }
+
+ public void setConfigurationRole(String configurationRole) {
+ this.configurationRole = configurationRole;
+ }
+
+ public String getConfigurationFunction() {
+ return configurationFunction;
+ }
+
+ public void setConfigurationFunction(String configurationFunction) {
+ this.configurationFunction = configurationFunction;
+ }
+
+ public String getPolicyName() {
+ return policyName;
+ }
+
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ @LinkedResource
+ public ConfigurationResource getConfigurationResource() {
+ return configurationResource;
+ }
+
+ public void setConfigurationResource(ConfigurationResource configurationResource) {
+ this.configurationResource = configurationResource;
+ }
- @LinkedResource
- public ConfigurationResource getConfigurationResource() {
- return configurationResource;
- }
-
- public void setConfigurationResource(ConfigurationResource configurationResource) {
- this.configurationResource = configurationResource;
- }
+ @LinkedResource
+ public CvnfcCustomization getCvnfcCustomization() {
+ return cvnfcCustomization;
+ }
- @LinkedResource
- public CvnfcCustomization getCvnfcCustomization() {
- return cvnfcCustomization;
- }
-
- public void setCvnfcCustomization(CvnfcCustomization cvnfcCustomization) {
- this.cvnfcCustomization = cvnfcCustomization;
- }
+ public void setCvnfcCustomization(CvnfcCustomization cvnfcCustomization) {
+ this.cvnfcCustomization = cvnfcCustomization;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcCustomization.java
index a7bbb9fb01..da3e391e11 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcCustomization.java
@@ -23,7 +23,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -38,226 +37,223 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.fasterxml.jackson.annotation.JsonFormat;
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "cvnfc_customization")
public class CvnfcCustomization implements Serializable {
- private static final long serialVersionUID = -3772469944364616486L;
-
- @Id
- @Column(name = "ID")
- @BusinessKey
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
-
- @Column(name = "MODEL_CUSTOMIZATION_UUID")
- private String modelCustomizationUUID;
-
- @Column(name = "MODEL_INSTANCE_NAME")
- private String modelInstanceName;
-
- @Column(name = "MODEL_UUID")
- private String modelUUID;
-
- @Column(name = "MODEL_INVARIANT_UUID")
- private String modelInvariantUUID;
-
- @Column(name = "MODEL_VERSION")
- private String modelVersion;
-
- @Column(name = "MODEL_NAME")
- private String modelName;
-
- @Column(name = "TOSCA_NODE_TYPE")
- private String toscaNodeType;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @Column(name = "NFC_FUNCTION")
- private String nfcFunction;
-
- @Column(name = "NFC_NAMING_CODE")
- private String nfcNamingCode;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "VF_MODULE_CUSTOMIZATION_ID")
- private VfModuleCustomization vfModuleCustomization;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "VNFC_CUST_MODEL_CUSTOMIZATION_UUID")
- private VnfcCustomization vnfcCustomization;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "cvnfcCustomization")
- private Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomization;
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof CvnfcCustomization)) {
- return false;
- }
- CvnfcCustomization castOther = (CvnfcCustomization) other;
- return new EqualsBuilder().append(id, castOther.id).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(id).toHashCode();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", id).append("modelCustomizationUUID", modelCustomizationUUID)
- .append("modelInstanceName", modelInstanceName).append("modelUUID", modelUUID)
- .append("modelInvariantUUID", modelInvariantUUID).append("modelVersion", modelVersion)
- .append("modelName", modelName).append("toscaNodeType", toscaNodeType)
- .append("description", description).append("nfcFunction", nfcFunction)
- .append("nfcNamingCode", nfcNamingCode).append("created", created)
- .append("vnfVfmoduleCvnfcConfigurationCustomization", cvnfcConfigurationCustomization)
- .toString();
- }
-
- @LinkedResource
- public VnfcCustomization getVnfcCustomization() {
- return vnfcCustomization;
- }
-
- public void setVnfcCustomization(VnfcCustomization vnfcCustomization) {
- this.vnfcCustomization = vnfcCustomization;
- }
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @LinkedResource
- public Set<CvnfcConfigurationCustomization> getCvnfcConfigurationCustomization() {
- return cvnfcConfigurationCustomization;
- }
-
- public void setCvnfcConfigurationCustomization(Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomization) {
- this.cvnfcConfigurationCustomization = cvnfcConfigurationCustomization;
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getModelCustomizationUUID() {
- return modelCustomizationUUID;
- }
-
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
-
- public String getModelInstanceName() {
- return modelInstanceName;
- }
-
- public void setModelInstanceName(String modelInstanceName) {
- this.modelInstanceName = modelInstanceName;
- }
-
- public String getModelUUID() {
- return modelUUID;
- }
-
- public void setModelUUID(String modelUUID) {
- this.modelUUID = modelUUID;
- }
-
- public String getModelInvariantUUID() {
- return modelInvariantUUID;
- }
-
- public void setModelInvariantUUID(String modelInvariantUUID) {
- this.modelInvariantUUID = modelInvariantUUID;
- }
-
- public String getModelVersion() {
- return modelVersion;
- }
-
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
-
- public String getModelName() {
- return modelName;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public String getToscaNodeType() {
- return toscaNodeType;
- }
-
- public void setToscaNodeType(String toscaNodeType) {
- this.toscaNodeType = toscaNodeType;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getNfcFunction() {
- return nfcFunction;
- }
-
- public void setNfcFunction(String nfcFunction) {
- this.nfcFunction = nfcFunction;
- }
-
- public String getNfcNamingCode() {
- return nfcNamingCode;
- }
-
- public void setNfcNamingCode(String nfcNamingCode) {
- this.nfcNamingCode = nfcNamingCode;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- @LinkedResource
- public VfModuleCustomization getVfModuleCustomization() {
- return vfModuleCustomization;
- }
-
- public void setVfModuleCustomization(VfModuleCustomization vfModuleCustomization) {
- this.vfModuleCustomization = vfModuleCustomization;
- }
+ private static final long serialVersionUID = -3772469944364616486L;
+
+ @Id
+ @Column(name = "ID")
+ @BusinessKey
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer id;
+
+ @Column(name = "MODEL_CUSTOMIZATION_UUID")
+ private String modelCustomizationUUID;
+
+ @Column(name = "MODEL_INSTANCE_NAME")
+ private String modelInstanceName;
+
+ @Column(name = "MODEL_UUID")
+ private String modelUUID;
+
+ @Column(name = "MODEL_INVARIANT_UUID")
+ private String modelInvariantUUID;
+
+ @Column(name = "MODEL_VERSION")
+ private String modelVersion;
+
+ @Column(name = "MODEL_NAME")
+ private String modelName;
+
+ @Column(name = "TOSCA_NODE_TYPE")
+ private String toscaNodeType;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @Column(name = "NFC_FUNCTION")
+ private String nfcFunction;
+
+ @Column(name = "NFC_NAMING_CODE")
+ private String nfcNamingCode;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "VF_MODULE_CUSTOMIZATION_ID")
+ private VfModuleCustomization vfModuleCustomization;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "VNFC_CUST_MODEL_CUSTOMIZATION_UUID")
+ private VnfcCustomization vnfcCustomization;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "cvnfcCustomization")
+ private Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomization;
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof CvnfcCustomization)) {
+ return false;
+ }
+ CvnfcCustomization castOther = (CvnfcCustomization) other;
+ return new EqualsBuilder().append(id, castOther.id).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(id).toHashCode();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", id).append("modelCustomizationUUID", modelCustomizationUUID)
+ .append("modelInstanceName", modelInstanceName).append("modelUUID", modelUUID)
+ .append("modelInvariantUUID", modelInvariantUUID).append("modelVersion", modelVersion)
+ .append("modelName", modelName).append("toscaNodeType", toscaNodeType)
+ .append("description", description).append("nfcFunction", nfcFunction)
+ .append("nfcNamingCode", nfcNamingCode).append("created", created)
+ .append("vnfVfmoduleCvnfcConfigurationCustomization", cvnfcConfigurationCustomization).toString();
+ }
+
+ @LinkedResource
+ public VnfcCustomization getVnfcCustomization() {
+ return vnfcCustomization;
+ }
+
+ public void setVnfcCustomization(VnfcCustomization vnfcCustomization) {
+ this.vnfcCustomization = vnfcCustomization;
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @LinkedResource
+ public Set<CvnfcConfigurationCustomization> getCvnfcConfigurationCustomization() {
+ return cvnfcConfigurationCustomization;
+ }
+
+ public void setCvnfcConfigurationCustomization(
+ Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomization) {
+ this.cvnfcConfigurationCustomization = cvnfcConfigurationCustomization;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getModelCustomizationUUID() {
+ return modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ public String getModelInstanceName() {
+ return modelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ this.modelInstanceName = modelInstanceName;
+ }
+
+ public String getModelUUID() {
+ return modelUUID;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ this.modelUUID = modelUUID;
+ }
+
+ public String getModelInvariantUUID() {
+ return modelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ this.modelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getToscaNodeType() {
+ return toscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ this.toscaNodeType = toscaNodeType;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getNfcFunction() {
+ return nfcFunction;
+ }
+
+ public void setNfcFunction(String nfcFunction) {
+ this.nfcFunction = nfcFunction;
+ }
+
+ public String getNfcNamingCode() {
+ return nfcNamingCode;
+ }
+
+ public void setNfcNamingCode(String nfcNamingCode) {
+ this.nfcNamingCode = nfcNamingCode;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ @LinkedResource
+ public VfModuleCustomization getVfModuleCustomization() {
+ return vfModuleCustomization;
+ }
+
+ public void setVfModuleCustomization(VfModuleCustomization vfModuleCustomization) {
+ this.vfModuleCustomization = vfModuleCustomization;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ExternalServiceToInternalService.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ExternalServiceToInternalService.java
index d076aebf86..f664e79702 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ExternalServiceToInternalService.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ExternalServiceToInternalService.java
@@ -21,112 +21,109 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@Table(name = "external_service_to_internal_model_mapping")
public class ExternalServiceToInternalService implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 3825246668050173010L;
-
- @Id
- @Column(name = "Id")
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
-
- @BusinessKey
- @Column(name = "SERVICE_NAME")
- private String serviceName;
-
- @BusinessKey
- @Column(name = "PRODUCT_FLAVOR")
- private String productFlavor;
-
- @BusinessKey
- @Column(name = "SUBSCRIPTION_SERVICE_TYPE")
- private String subscriptionServiceType;
-
- @BusinessKey
- @Column(name = "SERVICE_MODEL_UUID")
- private String serviceModelUUID;
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ExternalServiceToInternalService)) {
- return false;
- }
- ExternalServiceToInternalService castOther = (ExternalServiceToInternalService) other;
- return new EqualsBuilder().append(serviceName, castOther.serviceName)
- .append(productFlavor, castOther.productFlavor)
- .append(subscriptionServiceType, castOther.subscriptionServiceType)
- .append(serviceModelUUID, castOther.serviceModelUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(serviceName).append(productFlavor).append(subscriptionServiceType)
- .append(serviceModelUUID).toHashCode();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", id).append("serviceName", serviceName)
- .append("productFlavor", productFlavor).append("subscriptionServiceType", subscriptionServiceType)
- .append("serviceModelUUID", serviceModelUUID).toString();
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getServiceName() {
- return serviceName;
- }
-
- public void setServiceName(String serviceName) {
- this.serviceName = serviceName;
- }
-
- public String getProductFlavor() {
- return productFlavor;
- }
-
- public void setProductFlavor(String productFlavor) {
- this.productFlavor = productFlavor;
- }
-
- public String getSubscriptionServiceType() {
- return subscriptionServiceType;
- }
-
- public void setSubscriptionServiceType(String subscriptionServiceType) {
- this.subscriptionServiceType = subscriptionServiceType;
- }
-
- public String getServiceModelUUID() {
- return serviceModelUUID;
- }
-
- public void setServiceModelUUID(String serviceModelUUID) {
- this.serviceModelUUID = serviceModelUUID;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = 3825246668050173010L;
+
+ @Id
+ @Column(name = "Id")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer id;
+
+ @BusinessKey
+ @Column(name = "SERVICE_NAME")
+ private String serviceName;
+
+ @BusinessKey
+ @Column(name = "PRODUCT_FLAVOR")
+ private String productFlavor;
+
+ @BusinessKey
+ @Column(name = "SUBSCRIPTION_SERVICE_TYPE")
+ private String subscriptionServiceType;
+
+ @BusinessKey
+ @Column(name = "SERVICE_MODEL_UUID")
+ private String serviceModelUUID;
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ExternalServiceToInternalService)) {
+ return false;
+ }
+ ExternalServiceToInternalService castOther = (ExternalServiceToInternalService) other;
+ return new EqualsBuilder().append(serviceName, castOther.serviceName)
+ .append(productFlavor, castOther.productFlavor)
+ .append(subscriptionServiceType, castOther.subscriptionServiceType)
+ .append(serviceModelUUID, castOther.serviceModelUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(serviceName).append(productFlavor).append(subscriptionServiceType)
+ .append(serviceModelUUID).toHashCode();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", id).append("serviceName", serviceName)
+ .append("productFlavor", productFlavor).append("subscriptionServiceType", subscriptionServiceType)
+ .append("serviceModelUUID", serviceModelUUID).toString();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getServiceName() {
+ return serviceName;
+ }
+
+ public void setServiceName(String serviceName) {
+ this.serviceName = serviceName;
+ }
+
+ public String getProductFlavor() {
+ return productFlavor;
+ }
+
+ public void setProductFlavor(String productFlavor) {
+ this.productFlavor = productFlavor;
+ }
+
+ public String getSubscriptionServiceType() {
+ return subscriptionServiceType;
+ }
+
+ public void setSubscriptionServiceType(String subscriptionServiceType) {
+ this.subscriptionServiceType = subscriptionServiceType;
+ }
+
+ public String getServiceModelUUID() {
+ return serviceModelUUID;
+ }
+
+ public void setServiceModelUUID(String serviceModelUUID) {
+ this.serviceModelUUID = serviceModelUUID;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatEnvironment.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatEnvironment.java
index 6abe8d5110..511f7cf709 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatEnvironment.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatEnvironment.java
@@ -23,7 +23,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.text.DateFormat;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -32,132 +31,130 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@Table(name = "heat_environment")
public class HeatEnvironment implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
+ private static final long serialVersionUID = 768026109321305392L;
- @BusinessKey
- @Id
- @Column(name = "ARTIFACT_UUID")
- private String artifactUuid;
-
- @Column(name = "NAME")
- private String name = null;
-
- @Column(name = "DESCRIPTION")
- private String description = null;
-
- @Lob
- @Column(name = "BODY", columnDefinition = "LONGTEXT")
- private String environment = null;
-
- @Column(name = "ARTIFACT_CHECKSUM")
- private String artifactChecksum;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @BusinessKey
- @Column(name = "VERSION")
- private String version;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof HeatEnvironment)) {
- return false;
- }
- HeatEnvironment castOther = (HeatEnvironment) other;
- return new EqualsBuilder().append(artifactUuid, castOther.artifactUuid).append(version, castOther.version)
- .isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(artifactUuid).append(version).toHashCode();
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
- public String getArtifactUuid() {
- return this.artifactUuid;
- }
-
- public void setArtifactUuid(String artifactUuid) {
- this.artifactUuid = artifactUuid;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDescription() {
- return this.description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getEnvironment() {
- return this.environment;
- }
-
- public void setEnvironment(String environment) {
- this.environment = environment;
- }
-
- public String getArtifactChecksum() {
- return artifactChecksum;
- }
-
- public void setArtifactChecksum(String artifactChecksum) {
- this.artifactChecksum = artifactChecksum;
- }
-
- public Date getCreated() {
- return created;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("Artifact UUID=" + this.artifactUuid);
- sb.append(", name=");
- sb.append(name);
- sb.append(", version=");
- sb.append(version);
- sb.append(", description=");
- sb.append(this.description == null ? "null" : this.description);
- sb.append(", body=");
- sb.append(this.environment == null ? "null" : this.environment);
- if (this.created != null) {
- sb.append(",creationTimestamp=");
- sb.append(DateFormat.getInstance().format(this.created));
- }
- return sb.toString();
- }
+ @BusinessKey
+ @Id
+ @Column(name = "ARTIFACT_UUID")
+ private String artifactUuid;
+
+ @Column(name = "NAME")
+ private String name = null;
+
+ @Column(name = "DESCRIPTION")
+ private String description = null;
+
+ @Lob
+ @Column(name = "BODY", columnDefinition = "LONGTEXT")
+ private String environment = null;
+
+ @Column(name = "ARTIFACT_CHECKSUM")
+ private String artifactChecksum;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @BusinessKey
+ @Column(name = "VERSION")
+ private String version;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof HeatEnvironment)) {
+ return false;
+ }
+ HeatEnvironment castOther = (HeatEnvironment) other;
+ return new EqualsBuilder().append(artifactUuid, castOther.artifactUuid).append(version, castOther.version)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(artifactUuid).append(version).toHashCode();
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getArtifactUuid() {
+ return this.artifactUuid;
+ }
+
+ public void setArtifactUuid(String artifactUuid) {
+ this.artifactUuid = artifactUuid;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDescription() {
+ return this.description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getEnvironment() {
+ return this.environment;
+ }
+
+ public void setEnvironment(String environment) {
+ this.environment = environment;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public void setArtifactChecksum(String artifactChecksum) {
+ this.artifactChecksum = artifactChecksum;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Artifact UUID=" + this.artifactUuid);
+ sb.append(", name=");
+ sb.append(name);
+ sb.append(", version=");
+ sb.append(version);
+ sb.append(", description=");
+ sb.append(this.description == null ? "null" : this.description);
+ sb.append(", body=");
+ sb.append(this.environment == null ? "null" : this.environment);
+ if (this.created != null) {
+ sb.append(",creationTimestamp=");
+ sb.append(DateFormat.getInstance().format(this.created));
+ }
+ return sb.toString();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatFiles.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatFiles.java
index 6fe1e08f0d..3badf2ae11 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatFiles.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatFiles.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -31,127 +30,125 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@Table(name = "heat_files")
public class HeatFiles implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
+ private static final long serialVersionUID = 768026109321305392L;
- @BusinessKey
- @Id
- @Column(name = "ARTIFACT_UUID")
- private String artifactUuid;
-
- @Column(name = "DESCRIPTION")
- private String description = null;
+ @BusinessKey
+ @Id
+ @Column(name = "ARTIFACT_UUID")
+ private String artifactUuid;
+
+ @Column(name = "DESCRIPTION")
+ private String description = null;
- @Column(name = "NAME")
- private String fileName;
-
- @Lob
- @Column(name = "BODY", columnDefinition = "LONGTEXT")
- private String fileBody;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @Column(name = "ARTIFACT_CHECKSUM")
- private String artifactChecksum;
-
- @Column(name = "VERSION")
- private String version;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("artifactUuid", artifactUuid).append("description", description)
- .append("fileName", fileName).append("fileBody", fileBody).append("created", created)
- .append("artifactChecksum", artifactChecksum).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof HeatFiles)) {
- return false;
- }
- HeatFiles castOther = (HeatFiles) other;
- return new EqualsBuilder().append(artifactUuid, castOther.artifactUuid).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(artifactUuid).toHashCode();
- }
-
- public String getArtifactUuid() {
- return this.artifactUuid;
- }
-
- public void setArtifactUuid(String artifactUuid) {
- this.artifactUuid = artifactUuid;
- }
-
- public String getDescription() {
- return this.description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getFileName() {
- return this.fileName;
- }
-
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
-
- public String getFileBody() {
- return this.fileBody;
- }
-
- public void setFileBody(String fileBody) {
- this.fileBody = fileBody;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public String getAsdcUuid() {
- return this.artifactUuid;
- }
-
- public void setAsdcUuid(String artifactUuid) {
- this.artifactUuid = artifactUuid;
- }
-
- public String getArtifactChecksum() {
- return artifactChecksum;
- }
-
- public void setArtifactChecksum(String artifactChecksum) {
- this.artifactChecksum = artifactChecksum;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
+ @Column(name = "NAME")
+ private String fileName;
+
+ @Lob
+ @Column(name = "BODY", columnDefinition = "LONGTEXT")
+ private String fileBody;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @Column(name = "ARTIFACT_CHECKSUM")
+ private String artifactChecksum;
+
+ @Column(name = "VERSION")
+ private String version;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("artifactUuid", artifactUuid).append("description", description)
+ .append("fileName", fileName).append("fileBody", fileBody).append("created", created)
+ .append("artifactChecksum", artifactChecksum).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof HeatFiles)) {
+ return false;
+ }
+ HeatFiles castOther = (HeatFiles) other;
+ return new EqualsBuilder().append(artifactUuid, castOther.artifactUuid).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(artifactUuid).toHashCode();
+ }
+
+ public String getArtifactUuid() {
+ return this.artifactUuid;
+ }
+
+ public void setArtifactUuid(String artifactUuid) {
+ this.artifactUuid = artifactUuid;
+ }
+
+ public String getDescription() {
+ return this.description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getFileName() {
+ return this.fileName;
+ }
+
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ public String getFileBody() {
+ return this.fileBody;
+ }
+
+ public void setFileBody(String fileBody) {
+ this.fileBody = fileBody;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public String getAsdcUuid() {
+ return this.artifactUuid;
+ }
+
+ public void setAsdcUuid(String artifactUuid) {
+ this.artifactUuid = artifactUuid;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public void setArtifactChecksum(String artifactChecksum) {
+ this.artifactChecksum = artifactChecksum;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplate.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplate.java
index 2389793f33..82725f089d 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplate.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplate.java
@@ -26,7 +26,6 @@ import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -39,173 +38,171 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "heat_template")
public class HeatTemplate implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
-
- @BusinessKey
- @Id
- @Column(name = "ARTIFACT_UUID", length = 200)
- private String artifactUuid;
-
- @Column(name = "NAME", length = 200)
- private String templateName;
-
- @Lob
- @Column(name = "BODY", columnDefinition = "LONGTEXT")
- private String templateBody = null;
-
- @Column(name = "TIMEOUT_MINUTES", length = 20)
- private Integer timeoutMinutes;
-
- @BusinessKey
- @Column(name = "VERSION")
- private String version;
-
- @Column(name = "DESCRIPTION", length = 1200)
- private String description;
-
- @Column(name = "ARTIFACT_CHECKSUM", length = 200)
- private String artifactChecksum;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "heatTemplateArtifactUuid")
- private Set<HeatTemplateParam> parameters;
-
- @OneToMany(cascade = CascadeType.ALL)
- @JoinTable(name = "heat_nested_template", joinColumns = @JoinColumn(name = "PARENT_HEAT_TEMPLATE_UUID"), inverseJoinColumns = @JoinColumn(name = "CHILD_HEAT_TEMPLATE_UUID"))
- private List<HeatTemplate> childTemplates;
-
- public enum TemplateStatus {
- PARENT, CHILD, PARENT_COMPLETE
- }
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("artifactUuid", artifactUuid).append("templateName", templateName)
- .append("templateBody", templateBody).append("timeoutMinutes", timeoutMinutes)
- .append("version", version).append("description", description)
- .append("artifactChecksum", artifactChecksum).append("created", created)
- .append("parameters", parameters).append("childTemplates", childTemplates).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof HeatTemplate)) {
- return false;
- }
- HeatTemplate castOther = (HeatTemplate) other;
- return new EqualsBuilder().append(artifactUuid, castOther.artifactUuid).append(version, castOther.version)
- .isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(artifactUuid).append(version).toHashCode();
- }
-
- @LinkedResource
- public List<HeatTemplate> getChildTemplates() {
- if (childTemplates == null)
- childTemplates = new ArrayList<>();
- return childTemplates;
- }
-
- public void setChildTemplates(List<HeatTemplate> childTemplates) {
- this.childTemplates = childTemplates;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
- public String getArtifactUuid() {
- return this.artifactUuid;
- }
-
- public void setArtifactUuid(String artifactUuid) {
- this.artifactUuid = artifactUuid;
- }
-
- public String getTemplateName() {
- return templateName;
- }
-
- public void setTemplateName(String templateName) {
- this.templateName = templateName;
- }
-
- public String getTemplateBody() {
- return templateBody;
- }
-
- public void setTemplateBody(String templateBody) {
- this.templateBody = templateBody;
- }
-
- public Integer getTimeoutMinutes() {
- return timeoutMinutes;
- }
-
- public void setTimeoutMinutes(Integer timeout) {
- this.timeoutMinutes = timeout;
- }
-
- @LinkedResource
- public Set<HeatTemplateParam> getParameters() {
- if (parameters == null)
- parameters = new HashSet<>();
- return parameters;
- }
-
- public void setParameters(Set<HeatTemplateParam> parameters) {
- this.parameters = parameters;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getHeatTemplate() {
- return this.templateBody;
- }
-
- public String getArtifactChecksum() {
- return artifactChecksum;
- }
-
- public void setArtifactChecksum(String artifactChecksum) {
- this.artifactChecksum = artifactChecksum;
- }
-
- public Date getCreated() {
- return created;
- }
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @BusinessKey
+ @Id
+ @Column(name = "ARTIFACT_UUID", length = 200)
+ private String artifactUuid;
+
+ @Column(name = "NAME", length = 200)
+ private String templateName;
+
+ @Lob
+ @Column(name = "BODY", columnDefinition = "LONGTEXT")
+ private String templateBody = null;
+
+ @Column(name = "TIMEOUT_MINUTES", length = 20)
+ private Integer timeoutMinutes;
+
+ @BusinessKey
+ @Column(name = "VERSION")
+ private String version;
+
+ @Column(name = "DESCRIPTION", length = 1200)
+ private String description;
+
+ @Column(name = "ARTIFACT_CHECKSUM", length = 200)
+ private String artifactChecksum;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "heatTemplateArtifactUuid")
+ private Set<HeatTemplateParam> parameters;
+
+ @OneToMany(cascade = CascadeType.ALL)
+ @JoinTable(name = "heat_nested_template", joinColumns = @JoinColumn(name = "PARENT_HEAT_TEMPLATE_UUID"),
+ inverseJoinColumns = @JoinColumn(name = "CHILD_HEAT_TEMPLATE_UUID"))
+ private List<HeatTemplate> childTemplates;
+
+ public enum TemplateStatus {
+ PARENT, CHILD, PARENT_COMPLETE
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("artifactUuid", artifactUuid).append("templateName", templateName)
+ .append("templateBody", templateBody).append("timeoutMinutes", timeoutMinutes)
+ .append("version", version).append("description", description)
+ .append("artifactChecksum", artifactChecksum).append("created", created)
+ .append("parameters", parameters).append("childTemplates", childTemplates).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof HeatTemplate)) {
+ return false;
+ }
+ HeatTemplate castOther = (HeatTemplate) other;
+ return new EqualsBuilder().append(artifactUuid, castOther.artifactUuid).append(version, castOther.version)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(artifactUuid).append(version).toHashCode();
+ }
+
+ @LinkedResource
+ public List<HeatTemplate> getChildTemplates() {
+ if (childTemplates == null)
+ childTemplates = new ArrayList<>();
+ return childTemplates;
+ }
+
+ public void setChildTemplates(List<HeatTemplate> childTemplates) {
+ this.childTemplates = childTemplates;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getArtifactUuid() {
+ return this.artifactUuid;
+ }
+
+ public void setArtifactUuid(String artifactUuid) {
+ this.artifactUuid = artifactUuid;
+ }
+
+ public String getTemplateName() {
+ return templateName;
+ }
+
+ public void setTemplateName(String templateName) {
+ this.templateName = templateName;
+ }
+
+ public String getTemplateBody() {
+ return templateBody;
+ }
+
+ public void setTemplateBody(String templateBody) {
+ this.templateBody = templateBody;
+ }
+
+ public Integer getTimeoutMinutes() {
+ return timeoutMinutes;
+ }
+
+ public void setTimeoutMinutes(Integer timeout) {
+ this.timeoutMinutes = timeout;
+ }
+
+ @LinkedResource
+ public Set<HeatTemplateParam> getParameters() {
+ if (parameters == null)
+ parameters = new HashSet<>();
+ return parameters;
+ }
+
+ public void setParameters(Set<HeatTemplateParam> parameters) {
+ this.parameters = parameters;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getHeatTemplate() {
+ return this.templateBody;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public void setArtifactChecksum(String artifactChecksum) {
+ this.artifactChecksum = artifactChecksum;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplateParam.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplateParam.java
index cdbe7aee7a..6abf695797 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplateParam.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplateParam.java
@@ -21,17 +21,14 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@IdClass(HeatTemplateParamId.class)
@@ -39,86 +36,86 @@ import com.openpojo.business.annotation.BusinessKey;
@Table(name = "heat_template_params")
public class HeatTemplateParam implements Serializable {
- @BusinessKey
- @Id
- @Column(name = "HEAT_TEMPLATE_ARTIFACT_UUID")
- private String heatTemplateArtifactUuid;
-
- @BusinessKey
- @Id
- @Column(name = "PARAM_NAME")
- private String paramName;
-
- @Column(name = "IS_REQUIRED")
- private Boolean required;
-
- @Column(name = "PARAM_TYPE")
- private String paramType;
-
- @Column(name = "PARAM_ALIAS")
- private String paramAlias;
-
- public static final long serialVersionUID = -1322322139926390329L;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("heatTemplateArtifactUuid", heatTemplateArtifactUuid)
- .append("paramName", paramName).append("required", required).append("paramType", paramType)
- .append("paramAlias", paramAlias).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof HeatTemplateParam)) {
- return false;
- }
- HeatTemplateParam castOther = (HeatTemplateParam) other;
- return new EqualsBuilder().append(heatTemplateArtifactUuid, castOther.heatTemplateArtifactUuid)
- .append(paramName, castOther.paramName).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(heatTemplateArtifactUuid).append(paramName).toHashCode();
- }
-
- public String getHeatTemplateArtifactUuid() {
- return this.heatTemplateArtifactUuid;
- }
-
- public void setHeatTemplateArtifactUuid(String heatTemplateArtifactUuid) {
- this.heatTemplateArtifactUuid = heatTemplateArtifactUuid;
- }
-
- public String getParamName() {
- return paramName;
- }
-
- public void setParamName(String paramName) {
- this.paramName = paramName;
- }
-
- public Boolean isRequired() {
- return required;
- }
-
- public void setRequired(Boolean required) {
- this.required = required;
- }
-
- public String getParamAlias() {
- return paramAlias;
- }
-
- public void setParamAlias(String paramAlias) {
- this.paramAlias = paramAlias;
- }
-
- public String getParamType() {
- return paramType;
- }
-
- public void setParamType(String paramType) {
- this.paramType = paramType;
- }
+ @BusinessKey
+ @Id
+ @Column(name = "HEAT_TEMPLATE_ARTIFACT_UUID")
+ private String heatTemplateArtifactUuid;
+
+ @BusinessKey
+ @Id
+ @Column(name = "PARAM_NAME")
+ private String paramName;
+
+ @Column(name = "IS_REQUIRED")
+ private Boolean required;
+
+ @Column(name = "PARAM_TYPE")
+ private String paramType;
+
+ @Column(name = "PARAM_ALIAS")
+ private String paramAlias;
+
+ public static final long serialVersionUID = -1322322139926390329L;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("heatTemplateArtifactUuid", heatTemplateArtifactUuid)
+ .append("paramName", paramName).append("required", required).append("paramType", paramType)
+ .append("paramAlias", paramAlias).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof HeatTemplateParam)) {
+ return false;
+ }
+ HeatTemplateParam castOther = (HeatTemplateParam) other;
+ return new EqualsBuilder().append(heatTemplateArtifactUuid, castOther.heatTemplateArtifactUuid)
+ .append(paramName, castOther.paramName).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(heatTemplateArtifactUuid).append(paramName).toHashCode();
+ }
+
+ public String getHeatTemplateArtifactUuid() {
+ return this.heatTemplateArtifactUuid;
+ }
+
+ public void setHeatTemplateArtifactUuid(String heatTemplateArtifactUuid) {
+ this.heatTemplateArtifactUuid = heatTemplateArtifactUuid;
+ }
+
+ public String getParamName() {
+ return paramName;
+ }
+
+ public void setParamName(String paramName) {
+ this.paramName = paramName;
+ }
+
+ public Boolean isRequired() {
+ return required;
+ }
+
+ public void setRequired(Boolean required) {
+ this.required = required;
+ }
+
+ public String getParamAlias() {
+ return paramAlias;
+ }
+
+ public void setParamAlias(String paramAlias) {
+ this.paramAlias = paramAlias;
+ }
+
+ public String getParamType() {
+ return paramType;
+ }
+
+ public void setParamType(String paramType) {
+ this.paramType = paramType;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplateParamId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplateParamId.java
index 61c199c43f..6e494bf95f 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplateParamId.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HeatTemplateParamId.java
@@ -21,55 +21,53 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
public class HeatTemplateParamId implements Serializable {
- @BusinessKey
- private String heatTemplateArtifactUuid;
- @BusinessKey
- private String paramName;
+ @BusinessKey
+ private String heatTemplateArtifactUuid;
+ @BusinessKey
+ private String paramName;
- public static final long serialVersionUID = -1322322139926390329L;
+ public static final long serialVersionUID = -1322322139926390329L;
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof HeatTemplateParamId)) {
- return false;
- }
- HeatTemplateParamId castOther = (HeatTemplateParamId) other;
- return new EqualsBuilder().append(heatTemplateArtifactUuid, castOther.heatTemplateArtifactUuid)
- .append(paramName, castOther.paramName).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof HeatTemplateParamId)) {
+ return false;
+ }
+ HeatTemplateParamId castOther = (HeatTemplateParamId) other;
+ return new EqualsBuilder().append(heatTemplateArtifactUuid, castOther.heatTemplateArtifactUuid)
+ .append(paramName, castOther.paramName).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(heatTemplateArtifactUuid).append(paramName).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(heatTemplateArtifactUuid).append(paramName).toHashCode();
+ }
- public String getHeatTemplateArtifactUuid() {
- return this.heatTemplateArtifactUuid;
- }
+ public String getHeatTemplateArtifactUuid() {
+ return this.heatTemplateArtifactUuid;
+ }
- public void setHeatTemplateArtifactUuid(String heatTemplateArtifactUuid) {
- this.heatTemplateArtifactUuid = heatTemplateArtifactUuid;
- }
+ public void setHeatTemplateArtifactUuid(String heatTemplateArtifactUuid) {
+ this.heatTemplateArtifactUuid = heatTemplateArtifactUuid;
+ }
- public String getParamName() {
- return this.paramName;
- }
+ public String getParamName() {
+ return this.paramName;
+ }
- public void setParamName(String paramName) {
- this.paramName = paramName;
- }
+ public void setParamName(String paramName) {
+ this.paramName = paramName;
+ }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("heatTemplateArtifactUuid", heatTemplateArtifactUuid)
- .append("paramName", paramName).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("heatTemplateArtifactUuid", heatTemplateArtifactUuid)
+ .append("paramName", paramName).toString();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HomingInstance.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HomingInstance.java
index ef474be159..75871afe83 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HomingInstance.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/HomingInstance.java
@@ -26,7 +26,6 @@ import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import uk.co.blackpepper.bowman.annotation.RemoteResource;
import uk.co.blackpepper.bowman.annotation.ResourceId;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -35,8 +34,8 @@ import javax.persistence.Transient;
import java.net.URI;
/**
- * EntityBean class for a HomingInstance. This bean represents a homing instance
- * of a service, populated on successful homing
+ * EntityBean class for a HomingInstance. This bean represents a homing instance of a service, populated on successful
+ * homing
*
*/
@RemoteResource("/homingInstance")
@@ -69,11 +68,11 @@ public class HomingInstance {
@Transient
private URI uri;
- public HomingInstance () {
+ public HomingInstance() {
}
- public HomingInstance (HomingInstance homingInstance) {
+ public HomingInstance(HomingInstance homingInstance) {
this.serviceInstanceId = homingInstance.getServiceInstanceId();
this.cloudRegionId = homingInstance.getCloudRegionId();
this.cloudOwner = homingInstance.getCloudOwner();
@@ -105,7 +104,7 @@ public class HomingInstance {
return this.cloudOwner;
}
- public void setCloudOwner (String cloudOwner) {
+ public void setCloudOwner(String cloudOwner) {
this.cloudOwner = cloudOwner;
}
@@ -131,8 +130,7 @@ public class HomingInstance {
@Override
public String toString() {
return new ToStringBuilder(this).append("serviceInstanceId", serviceInstanceId)
- .append("cloudRegionId", cloudRegionId)
- .append("cloudOwner", cloudOwner)
+ .append("cloudRegionId", cloudRegionId).append("cloudOwner", cloudOwner)
.append("oofDirectives", oofDirectives).toString();
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/InstanceGroup.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/InstanceGroup.java
index 43d4acffcc..d226ffee13 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/InstanceGroup.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/InstanceGroup.java
@@ -24,7 +24,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
@@ -42,13 +41,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@@ -57,177 +53,177 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "instance_group")
public class InstanceGroup implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -263859017727376578L;
-
- @BusinessKey
- @Id
- @Column(name = "MODEL_UUID")
- private String modelUUID;
-
- @Column(name = "MODEL_NAME")
- private String modelName;
-
- @Column(name = "MODEL_INVARIANT_UUID")
- private String modelInvariantUUID;
-
- @Column(name = "MODEL_VERSION")
- private String modelVersion;
-
- @Column(name = "ROLE")
- private String role;
-
- @Column(name = "TOSCA_NODE_TYPE")
- private String toscaNodeType;
-
- @Enumerated(EnumType.STRING)
- @Column(name = "INSTANCE_GROUP_TYPE")
- private InstanceGroupType type;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "CR_MODEL_UUID")
- private CollectionResource collectionResource;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "instanceGroup")
- private List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupCustomizations;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "instanceGroup")
- private List<VnfcInstanceGroupCustomization> vnfcInstanceGroupCustomizations = new ArrayList<>();
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "instanceGroup")
- private List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomizations;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelName", modelName)
- .append("modelInvariantUUID", modelInvariantUUID).append("modelVersion", modelVersion)
- .append("role", role).append("toscaNodeType", toscaNodeType).append("type", type)
- .append("created", created).append("collectionResource", collectionResource)
- .append("collectionInstanceGroupCustomizations", collectionInstanceGroupCustomizations)
- .append("vnfcInstanceGroupCustomizations", vnfcInstanceGroupCustomizations).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof InstanceGroup)) {
- return false;
- }
- InstanceGroup castOther = (InstanceGroup) other;
- return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelUUID).toHashCode();
- }
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public String getModelUUID() {
- return modelUUID;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public void setModelUUID(String modelUUID) {
- this.modelUUID = modelUUID;
- }
-
- public String getModelName() {
- return modelName;
- }
-
- public String getToscaNodeType() {
- return toscaNodeType;
- }
-
- public void setToscaNodeType(String toscaNodeType) {
- this.toscaNodeType = toscaNodeType;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public String getModelInvariantUUID() {
- return modelInvariantUUID;
- }
-
- public void setModelInvariantUUID(String modelInvariantUUID) {
- this.modelInvariantUUID = modelInvariantUUID;
- }
-
- public String getModelVersion() {
- return modelVersion;
- }
-
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
-
- public String getRole() {
- return role;
- }
-
- public void setRole(String role) {
- this.role = role;
- }
-
- public InstanceGroupType getType() {
- return type;
- }
-
- public void setType(InstanceGroupType type) {
- this.type = type;
- }
-
- @LinkedResource
- public CollectionResource getCollectionResource() {
- return collectionResource;
- }
-
- public void setCollectionResource(CollectionResource collectionResource) {
- this.collectionResource = collectionResource;
- }
-
- @LinkedResource
- public List<CollectionResourceInstanceGroupCustomization> getCollectionInstanceGroupCustomizations() {
- return collectionInstanceGroupCustomizations;
- }
-
- public void setCollectionInstanceGroupCustomizations(
- List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupCustomizations) {
- this.collectionInstanceGroupCustomizations = collectionInstanceGroupCustomizations;
- }
-
- @LinkedResource
- public List<VnfcInstanceGroupCustomization> getVnfcInstanceGroupCustomizations() {
- return vnfcInstanceGroupCustomizations;
- }
-
- public void setVnfcInstanceGroupCustomizations(
- List<VnfcInstanceGroupCustomization> vnfcInstanceGroupCustomizations) {
- this.vnfcInstanceGroupCustomizations = vnfcInstanceGroupCustomizations;
- }
-
- @LinkedResource
- public List<CollectionNetworkResourceCustomization> getCollectionNetworkResourceCustomizations() {
- return collectionNetworkResourceCustomizations;
- }
-
- public void setCollectionNetworkResourceCustomizations(
- List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomizations) {
- this.collectionNetworkResourceCustomizations = collectionNetworkResourceCustomizations;
- }
-} \ No newline at end of file
+ /**
+ *
+ */
+ private static final long serialVersionUID = -263859017727376578L;
+
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_UUID")
+ private String modelUUID;
+
+ @Column(name = "MODEL_NAME")
+ private String modelName;
+
+ @Column(name = "MODEL_INVARIANT_UUID")
+ private String modelInvariantUUID;
+
+ @Column(name = "MODEL_VERSION")
+ private String modelVersion;
+
+ @Column(name = "ROLE")
+ private String role;
+
+ @Column(name = "TOSCA_NODE_TYPE")
+ private String toscaNodeType;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "INSTANCE_GROUP_TYPE")
+ private InstanceGroupType type;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "CR_MODEL_UUID")
+ private CollectionResource collectionResource;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "instanceGroup")
+ private List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupCustomizations;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "instanceGroup")
+ private List<VnfcInstanceGroupCustomization> vnfcInstanceGroupCustomizations = new ArrayList<>();
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "instanceGroup")
+ private List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomizations;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelName", modelName)
+ .append("modelInvariantUUID", modelInvariantUUID).append("modelVersion", modelVersion)
+ .append("role", role).append("toscaNodeType", toscaNodeType).append("type", type)
+ .append("created", created).append("collectionResource", collectionResource)
+ .append("collectionInstanceGroupCustomizations", collectionInstanceGroupCustomizations)
+ .append("vnfcInstanceGroupCustomizations", vnfcInstanceGroupCustomizations).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof InstanceGroup)) {
+ return false;
+ }
+ InstanceGroup castOther = (InstanceGroup) other;
+ return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelUUID).toHashCode();
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public String getModelUUID() {
+ return modelUUID;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ this.modelUUID = modelUUID;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public String getToscaNodeType() {
+ return toscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ this.toscaNodeType = toscaNodeType;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getModelInvariantUUID() {
+ return modelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ this.modelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+
+ public InstanceGroupType getType() {
+ return type;
+ }
+
+ public void setType(InstanceGroupType type) {
+ this.type = type;
+ }
+
+ @LinkedResource
+ public CollectionResource getCollectionResource() {
+ return collectionResource;
+ }
+
+ public void setCollectionResource(CollectionResource collectionResource) {
+ this.collectionResource = collectionResource;
+ }
+
+ @LinkedResource
+ public List<CollectionResourceInstanceGroupCustomization> getCollectionInstanceGroupCustomizations() {
+ return collectionInstanceGroupCustomizations;
+ }
+
+ public void setCollectionInstanceGroupCustomizations(
+ List<CollectionResourceInstanceGroupCustomization> collectionInstanceGroupCustomizations) {
+ this.collectionInstanceGroupCustomizations = collectionInstanceGroupCustomizations;
+ }
+
+ @LinkedResource
+ public List<VnfcInstanceGroupCustomization> getVnfcInstanceGroupCustomizations() {
+ return vnfcInstanceGroupCustomizations;
+ }
+
+ public void setVnfcInstanceGroupCustomizations(
+ List<VnfcInstanceGroupCustomization> vnfcInstanceGroupCustomizations) {
+ this.vnfcInstanceGroupCustomizations = vnfcInstanceGroupCustomizations;
+ }
+
+ @LinkedResource
+ public List<CollectionNetworkResourceCustomization> getCollectionNetworkResourceCustomizations() {
+ return collectionNetworkResourceCustomizations;
+ }
+
+ public void setCollectionNetworkResourceCustomizations(
+ List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomizations) {
+ this.collectionNetworkResourceCustomizations = collectionNetworkResourceCustomizations;
+ }
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/InstanceGroupType.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/InstanceGroupType.java
index e67078b104..764d3c4a53 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/InstanceGroupType.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/InstanceGroupType.java
@@ -21,5 +21,5 @@
package org.onap.so.db.catalog.beans;
public enum InstanceGroupType {
- L3_NETWORK, VNFC;
+ L3_NETWORK, VNFC;
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Model.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Model.java
index 9c5c23ef0e..0592e8f058 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Model.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Model.java
@@ -23,7 +23,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -36,194 +35,193 @@ import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
+
@Entity
@Table(name = "model")
public class Model implements Serializable {
-
- private static final long serialVersionUID = 768026109321305392L;
-
- @Id
- @Column(name = "ID", nullable = false, updatable = false)
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
- @Column(name = "MODEL_CUSTOMIZATION_ID", length = 40)
- private String modelCustomizationId = null;
- @Column(name = "MODEL_CUSTOMIZATION_NAME", length = 40)
- private String modelCustomizationName = null;
- @Column(name = "MODEL_INVARIANT_ID", length = 40)
- private String modelInvariantId = null;
- @Column(name = "MODEL_NAME", length = 40)
- private String modelName = null;
- @BusinessKey
- @Column(name = "MODEL_TYPE", length = 20)
- private String modelType = null;
- @Column(name = "MODEL_VERSION", length = 20)
- private String modelVersion = null;
- @BusinessKey
- @Column(name = "MODEL_VERSION_ID", length = 40)
- private String modelVersionId = null;
- @Column(name = "CREATION_TIMESTAMP", nullable = false, updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created = null;
- @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy="modelId")
- @MapKey(name = "action")
- private Map<String,ModelRecipe> recipes;
-
- /**
- * @return the id
- */
- public Integer getId() {
- return id;
- }
-
- /**
- * @return the modelCustomizationId
- */
- public String getModelCustomizationId() {
- return modelCustomizationId;
- }
-
- /**
- * @param modelCustomizationId the modelCustomizationId to set
- */
- public void setModelCustomizationId(String modelCustomizationId) {
- this.modelCustomizationId = modelCustomizationId;
- }
-
- /**
- * @return the modelCustomizationName
- */
- public String getModelCustomizationName() {
- return modelCustomizationName;
- }
-
- /**
- * @param modelCustomizationName the modelCustomizationName to set
- */
- public void setModelCustomizationName(String modelCustomizationName) {
- this.modelCustomizationName = modelCustomizationName;
- }
-
- /**
- * @return the modelInvariantId
- */
- public String getModelInvariantId() {
- return modelInvariantId;
- }
-
- /**
- * @param modelInvariantId the modelInvariantId to set
- */
- public void setModelInvariantId(String modelInvariantId) {
- this.modelInvariantId = modelInvariantId;
- }
-
- /**
- * @return the modelName
- */
- public String getModelName() {
- return modelName;
- }
-
- /**
- * @param modelName the modelName to set
- */
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- /**
- * @return the modelType
- */
- public String getModelType() {
- return modelType;
- }
-
- /**
- * @param modelType the modelType to set
- */
- public void setModelType(String modelType) {
- this.modelType = modelType;
- }
-
- /**
- * @return the modelVersion
- */
- public String getModelVersion() {
- return modelVersion;
- }
-
- /**
- * @param modelVersion the modelVersion to set
- */
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
-
- /**
- * @return the modelVersionId
- */
- public String getModelVersionId() {
- return modelVersionId;
- }
-
- /**
- * @param modelVersionId the modelVersionId to set
- */
- public void setModelVersionId(String modelVersionId) {
- this.modelVersionId = modelVersionId;
- }
-
- /**
- * @return the created
- */
- public Date getCreated() {
- return created;
- }
-
- /**
- * @return the recipes
- */
- public Map<String, ModelRecipe> getRecipes() {
- return recipes;
- }
-
- /**
- * @param recipes the recipes to set
- */
- public void setRecipes(Map<String, ModelRecipe> recipes) {
- this.recipes = recipes;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Model)) {
- return false;
- }
- Model castOther = (Model) other;
- return new EqualsBuilder().append(getModelType(), castOther.getModelType())
- .append(getModelVersionId(), castOther.getModelVersionId()).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(getModelType()).append(getModelVersionId()).toHashCode();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).append("modelCustomizationId", getModelCustomizationId())
- .append("modelCustomizationName", getModelCustomizationName())
- .append("modelInvariantId", getModelInvariantId()).append("modelName", getModelName())
- .append("modelType", getModelType()).append("modelVersion", getModelVersion())
- .append("modelVersionId", getModelVersionId()).append("created", getCreated())
- .append("recipes", getRecipes()).toString();
- }
+
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @Id
+ @Column(name = "ID", nullable = false, updatable = false)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer id;
+ @Column(name = "MODEL_CUSTOMIZATION_ID", length = 40)
+ private String modelCustomizationId = null;
+ @Column(name = "MODEL_CUSTOMIZATION_NAME", length = 40)
+ private String modelCustomizationName = null;
+ @Column(name = "MODEL_INVARIANT_ID", length = 40)
+ private String modelInvariantId = null;
+ @Column(name = "MODEL_NAME", length = 40)
+ private String modelName = null;
+ @BusinessKey
+ @Column(name = "MODEL_TYPE", length = 20)
+ private String modelType = null;
+ @Column(name = "MODEL_VERSION", length = 20)
+ private String modelVersion = null;
+ @BusinessKey
+ @Column(name = "MODEL_VERSION_ID", length = 40)
+ private String modelVersionId = null;
+ @Column(name = "CREATION_TIMESTAMP", nullable = false, updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created = null;
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "modelId")
+ @MapKey(name = "action")
+ private Map<String, ModelRecipe> recipes;
+
+ /**
+ * @return the id
+ */
+ public Integer getId() {
+ return id;
+ }
+
+ /**
+ * @return the modelCustomizationId
+ */
+ public String getModelCustomizationId() {
+ return modelCustomizationId;
+ }
+
+ /**
+ * @param modelCustomizationId the modelCustomizationId to set
+ */
+ public void setModelCustomizationId(String modelCustomizationId) {
+ this.modelCustomizationId = modelCustomizationId;
+ }
+
+ /**
+ * @return the modelCustomizationName
+ */
+ public String getModelCustomizationName() {
+ return modelCustomizationName;
+ }
+
+ /**
+ * @param modelCustomizationName the modelCustomizationName to set
+ */
+ public void setModelCustomizationName(String modelCustomizationName) {
+ this.modelCustomizationName = modelCustomizationName;
+ }
+
+ /**
+ * @return the modelInvariantId
+ */
+ public String getModelInvariantId() {
+ return modelInvariantId;
+ }
+
+ /**
+ * @param modelInvariantId the modelInvariantId to set
+ */
+ public void setModelInvariantId(String modelInvariantId) {
+ this.modelInvariantId = modelInvariantId;
+ }
+
+ /**
+ * @return the modelName
+ */
+ public String getModelName() {
+ return modelName;
+ }
+
+ /**
+ * @param modelName the modelName to set
+ */
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ /**
+ * @return the modelType
+ */
+ public String getModelType() {
+ return modelType;
+ }
+
+ /**
+ * @param modelType the modelType to set
+ */
+ public void setModelType(String modelType) {
+ this.modelType = modelType;
+ }
+
+ /**
+ * @return the modelVersion
+ */
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ /**
+ * @param modelVersion the modelVersion to set
+ */
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ /**
+ * @return the modelVersionId
+ */
+ public String getModelVersionId() {
+ return modelVersionId;
+ }
+
+ /**
+ * @param modelVersionId the modelVersionId to set
+ */
+ public void setModelVersionId(String modelVersionId) {
+ this.modelVersionId = modelVersionId;
+ }
+
+ /**
+ * @return the created
+ */
+ public Date getCreated() {
+ return created;
+ }
+
+ /**
+ * @return the recipes
+ */
+ public Map<String, ModelRecipe> getRecipes() {
+ return recipes;
+ }
+
+ /**
+ * @param recipes the recipes to set
+ */
+ public void setRecipes(Map<String, ModelRecipe> recipes) {
+ this.recipes = recipes;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Model)) {
+ return false;
+ }
+ Model castOther = (Model) other;
+ return new EqualsBuilder().append(getModelType(), castOther.getModelType())
+ .append(getModelVersionId(), castOther.getModelVersionId()).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(getModelType()).append(getModelVersionId()).toHashCode();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", getId()).append("modelCustomizationId", getModelCustomizationId())
+ .append("modelCustomizationName", getModelCustomizationName())
+ .append("modelInvariantId", getModelInvariantId()).append("modelName", getModelName())
+ .append("modelType", getModelType()).append("modelVersion", getModelVersion())
+ .append("modelVersionId", getModelVersionId()).append("created", getCreated())
+ .append("recipes", getRecipes()).toString();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ModelRecipe.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ModelRecipe.java
index 3d7cb68172..3f89e9db74 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ModelRecipe.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ModelRecipe.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@@ -31,176 +30,174 @@ import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@Table(name = "model_recipe")
public class ModelRecipe implements Serializable {
-
- private static final long serialVersionUID = 768026109321305392L;
-
- @Id
- @Column(name = "ID", nullable = false, updatable = false)
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
- @BusinessKey
- @Column(name = "MODEL_ID", nullable = false)
- private Integer modelId;
- @BusinessKey
- @Column(name = "ACTION", length = 50)
- private String action = null;
- @Column(name = "SCHEMA_VERSION", length = 20)
- private String schemaVersion = null;
- @Column(name = "DESCRIPTION", length = 1200)
- private String description = null;
- @Column(name = "ORCHESTRATION_URI", length = 256)
- private String orchestrationUri = null;
- @Column(name = "MODEL_PARAM_XSD", length = 2048)
- private String modelParamXSD = null;
- @Column(name = "RECIPE_TIMEOUT")
- private Integer recipeTimeout;
- @Column(name = "CREATION_TIMESTAMP", nullable = false, updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created = null;
-
- /**
- * @return the id
- */
- public Integer getId() {
- return id;
- }
-
- /**
- * @return the modelId
- */
- public Integer getModelId() {
- return modelId;
- }
-
- /**
- * @param modelId the modelId to set
- */
- public void setModelId(Integer modelId) {
- this.modelId = modelId;
- }
-
- /**
- * @return the action
- */
- public String getAction() {
- return action;
- }
-
- /**
- * @param action the action to set
- */
- public void setAction(String action) {
- this.action = action;
- }
-
- /**
- * @return the versionStr
- */
- public String getSchemaVersion() {
- return schemaVersion;
- }
-
- /**
- * @param schemaVersion the versionStr to set
- */
- public void setSchemaVersion(String schemaVersion) {
- this.schemaVersion = schemaVersion;
- }
-
- /**
- * @return the description
- */
- public String getDescription() {
- return description;
- }
-
- /**
- * @param description the description to set
- */
- public void setDescription(String description) {
- this.description = description;
- }
-
- /**
- * @return the orchestrationUri
- */
- public String getOrchestrationUri() {
- return orchestrationUri;
- }
-
- /**
- * @param orchestrationUri the orchestrationUri to set
- */
- public void setOrchestrationUri(String orchestrationUri) {
- this.orchestrationUri = orchestrationUri;
- }
-
- /**
- * @return the modelParamXSD
- */
- public String getModelParamXSD() {
- return modelParamXSD;
- }
-
- /**
- * @param modelParamXSD the modelParamXSD to set
- */
- public void setModelParamXSD(String modelParamXSD) {
- this.modelParamXSD = modelParamXSD;
- }
-
- /**
- * @return the recipeTimeout
- */
- public Integer getRecipeTimeout() {
- return recipeTimeout;
- }
-
- /**
- * @param recipeTimeout the recipeTimeout to set
- */
- public void setRecipeTimeout(Integer recipeTimeout) {
- this.recipeTimeout = recipeTimeout;
- }
-
- /**
- * @return the created
- */
- public Date getCreated() {
- return created;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ModelRecipe)) {
- return false;
- }
- ModelRecipe castOther = (ModelRecipe) other;
- return new EqualsBuilder().append(getModelId(), castOther.getModelId())
- .append(getAction(), castOther.getAction()).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(getModelId()).append(getAction()).toHashCode();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).append("modelId", getModelId())
- .append("action", getAction()).append("schemaVersion", getSchemaVersion())
- .append("description", getDescription()).append("orchestrationUri", getOrchestrationUri())
- .append("modelParamXSD", getModelParamXSD()).append("recipeTimeout", getRecipeTimeout())
- .append("created", getCreated()).toString();
- }
+
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @Id
+ @Column(name = "ID", nullable = false, updatable = false)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer id;
+ @BusinessKey
+ @Column(name = "MODEL_ID", nullable = false)
+ private Integer modelId;
+ @BusinessKey
+ @Column(name = "ACTION", length = 50)
+ private String action = null;
+ @Column(name = "SCHEMA_VERSION", length = 20)
+ private String schemaVersion = null;
+ @Column(name = "DESCRIPTION", length = 1200)
+ private String description = null;
+ @Column(name = "ORCHESTRATION_URI", length = 256)
+ private String orchestrationUri = null;
+ @Column(name = "MODEL_PARAM_XSD", length = 2048)
+ private String modelParamXSD = null;
+ @Column(name = "RECIPE_TIMEOUT")
+ private Integer recipeTimeout;
+ @Column(name = "CREATION_TIMESTAMP", nullable = false, updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created = null;
+
+ /**
+ * @return the id
+ */
+ public Integer getId() {
+ return id;
+ }
+
+ /**
+ * @return the modelId
+ */
+ public Integer getModelId() {
+ return modelId;
+ }
+
+ /**
+ * @param modelId the modelId to set
+ */
+ public void setModelId(Integer modelId) {
+ this.modelId = modelId;
+ }
+
+ /**
+ * @return the action
+ */
+ public String getAction() {
+ return action;
+ }
+
+ /**
+ * @param action the action to set
+ */
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ /**
+ * @return the versionStr
+ */
+ public String getSchemaVersion() {
+ return schemaVersion;
+ }
+
+ /**
+ * @param schemaVersion the versionStr to set
+ */
+ public void setSchemaVersion(String schemaVersion) {
+ this.schemaVersion = schemaVersion;
+ }
+
+ /**
+ * @return the description
+ */
+ public String getDescription() {
+ return description;
+ }
+
+ /**
+ * @param description the description to set
+ */
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ /**
+ * @return the orchestrationUri
+ */
+ public String getOrchestrationUri() {
+ return orchestrationUri;
+ }
+
+ /**
+ * @param orchestrationUri the orchestrationUri to set
+ */
+ public void setOrchestrationUri(String orchestrationUri) {
+ this.orchestrationUri = orchestrationUri;
+ }
+
+ /**
+ * @return the modelParamXSD
+ */
+ public String getModelParamXSD() {
+ return modelParamXSD;
+ }
+
+ /**
+ * @param modelParamXSD the modelParamXSD to set
+ */
+ public void setModelParamXSD(String modelParamXSD) {
+ this.modelParamXSD = modelParamXSD;
+ }
+
+ /**
+ * @return the recipeTimeout
+ */
+ public Integer getRecipeTimeout() {
+ return recipeTimeout;
+ }
+
+ /**
+ * @param recipeTimeout the recipeTimeout to set
+ */
+ public void setRecipeTimeout(Integer recipeTimeout) {
+ this.recipeTimeout = recipeTimeout;
+ }
+
+ /**
+ * @return the created
+ */
+ public Date getCreated() {
+ return created;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ModelRecipe)) {
+ return false;
+ }
+ ModelRecipe castOther = (ModelRecipe) other;
+ return new EqualsBuilder().append(getModelId(), castOther.getModelId())
+ .append(getAction(), castOther.getAction()).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(getModelId()).append(getAction()).toHashCode();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", getId()).append("modelId", getModelId())
+ .append("action", getAction()).append("schemaVersion", getSchemaVersion())
+ .append("description", getDescription()).append("orchestrationUri", getOrchestrationUri())
+ .append("modelParamXSD", getModelParamXSD()).append("recipeTimeout", getRecipeTimeout())
+ .append("created", getCreated()).toString();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkCollectionResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkCollectionResourceCustomization.java
index a1b51f9a6b..bb9079be23 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkCollectionResourceCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkCollectionResourceCustomization.java
@@ -21,33 +21,31 @@
package org.onap.so.db.catalog.beans;
import java.util.Set;
-
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@DiscriminatorValue(value = "NetworkCollection")
public class NetworkCollectionResourceCustomization extends CollectionResourceCustomization {
- /**
- *
- */
- private static final long serialVersionUID = -4571173204548832466L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -4571173204548832466L;
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "networkResourceCustomization")
- private Set<CollectionNetworkResourceCustomization> networkResourceCustomization;
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "networkResourceCustomization")
+ private Set<CollectionNetworkResourceCustomization> networkResourceCustomization;
- @LinkedResource
- public Set<CollectionNetworkResourceCustomization> getNetworkResourceCustomization() {
- return networkResourceCustomization;
- }
+ @LinkedResource
+ public Set<CollectionNetworkResourceCustomization> getNetworkResourceCustomization() {
+ return networkResourceCustomization;
+ }
- public void setNetworkResourceCustomization(
- Set<CollectionNetworkResourceCustomization> networkResourceCustomization) {
- this.networkResourceCustomization = networkResourceCustomization;
- }
+ public void setNetworkResourceCustomization(
+ Set<CollectionNetworkResourceCustomization> networkResourceCustomization) {
+ this.networkResourceCustomization = networkResourceCustomization;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkInstanceGroup.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkInstanceGroup.java
index edda4b8122..24782efcf0 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkInstanceGroup.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkInstanceGroup.java
@@ -27,8 +27,8 @@ import javax.persistence.Entity;
@DiscriminatorValue(value = "L3_NETWORK")
public class NetworkInstanceGroup extends InstanceGroup {
- /**
- *
- */
- private static final long serialVersionUID = 1934855643166769237L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1934855643166769237L;
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkRecipe.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkRecipe.java
index 51bcd54ae1..7bdbe9cdba 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkRecipe.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkRecipe.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -30,156 +29,154 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@Table(name = "network_recipe")
public class NetworkRecipe implements Serializable, Recipe {
- private static final long serialVersionUID = 768026109321305392L;
-
- @Id
- @Column(name = "id")
- private Integer id;
-
- @BusinessKey
- @Column(name = "ACTION")
- protected String action;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @BusinessKey
- @Column(name = "ORCHESTRATION_URI")
- protected String orchestrationUri;
-
- @Column(name = "RECIPE_TIMEOUT")
- private Integer recipeTimeout;
-
- @Column(name = "VERSION_STR")
- private String versionStr;
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @Id
+ @Column(name = "id")
+ private Integer id;
+
+ @BusinessKey
+ @Column(name = "ACTION")
+ protected String action;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @BusinessKey
+ @Column(name = "ORCHESTRATION_URI")
+ protected String orchestrationUri;
+
+ @Column(name = "RECIPE_TIMEOUT")
+ private Integer recipeTimeout;
+
+ @Column(name = "VERSION_STR")
+ private String versionStr;
- @BusinessKey
- @Column(name = "SERVICE_TYPE")
- private String serviceType;
+ @BusinessKey
+ @Column(name = "SERVICE_TYPE")
+ private String serviceType;
- @BusinessKey
- @Column(name = "MODEL_NAME")
- private String modelName;
-
- @Column(name = "NETWORK_PARAM_XSD")
- private String paramXsd;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof NetworkRecipe)) {
- return false;
- }
- NetworkRecipe castOther = (NetworkRecipe) other;
- return new EqualsBuilder().append(action, castOther.action).append(orchestrationUri, castOther.orchestrationUri)
- .append(serviceType, castOther.serviceType).append(modelName, castOther.modelName).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(action).append(orchestrationUri).append(serviceType).append(modelName)
- .toHashCode();
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getOrchestrationUri() {
- return orchestrationUri;
- }
-
- public void setOrchestrationUri(String orchestrationUri) {
- this.orchestrationUri = orchestrationUri;
- }
-
- public Integer getRecipeTimeout() {
- return recipeTimeout;
- }
-
- public void setRecipeTimeout(Integer recipeTimeout) {
- this.recipeTimeout = recipeTimeout;
- }
-
- public String getServiceType() {
- return serviceType;
- }
-
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public String getModelName() {
- return modelName;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public String getParamXsd() {
- return paramXsd;
- }
-
- public void setParamXsd(String paramXsd) {
- this.paramXsd = paramXsd;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append(super.toString());
- sb.append(",modelName=" + modelName);
- sb.append(",networkParamXSD=" + paramXsd);
- return sb.toString();
- }
-
- public String getVersionStr() {
- return versionStr;
- }
-
- public void setVersionStr(String versionStr) {
- this.versionStr = versionStr;
- }
+ @BusinessKey
+ @Column(name = "MODEL_NAME")
+ private String modelName;
+
+ @Column(name = "NETWORK_PARAM_XSD")
+ private String paramXsd;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof NetworkRecipe)) {
+ return false;
+ }
+ NetworkRecipe castOther = (NetworkRecipe) other;
+ return new EqualsBuilder().append(action, castOther.action).append(orchestrationUri, castOther.orchestrationUri)
+ .append(serviceType, castOther.serviceType).append(modelName, castOther.modelName).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(action).append(orchestrationUri).append(serviceType).append(modelName)
+ .toHashCode();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getOrchestrationUri() {
+ return orchestrationUri;
+ }
+
+ public void setOrchestrationUri(String orchestrationUri) {
+ this.orchestrationUri = orchestrationUri;
+ }
+
+ public Integer getRecipeTimeout() {
+ return recipeTimeout;
+ }
+
+ public void setRecipeTimeout(Integer recipeTimeout) {
+ this.recipeTimeout = recipeTimeout;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getParamXsd() {
+ return paramXsd;
+ }
+
+ public void setParamXsd(String paramXsd) {
+ this.paramXsd = paramXsd;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(super.toString());
+ sb.append(",modelName=" + modelName);
+ sb.append(",networkParamXSD=" + paramXsd);
+ return sb.toString();
+ }
+
+ public String getVersionStr() {
+ return versionStr;
+ }
+
+ public void setVersionStr(String versionStr) {
+ this.versionStr = versionStr;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResource.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResource.java
index c31cd61ce0..6876200754 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResource.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResource.java
@@ -25,7 +25,6 @@ import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -38,268 +37,263 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "network_resource")
public class NetworkResource implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
+ private static final long serialVersionUID = 768026109321305392L;
- @BusinessKey
- @Id
- @Column(name = "MODEL_UUID")
- private String modelUUID;
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_UUID")
+ private String modelUUID;
- @Column(name = "ORCHESTRATION_MODE")
- private String orchestrationMode = null;
+ @Column(name = "ORCHESTRATION_MODE")
+ private String orchestrationMode = null;
- @Column(name = "DESCRIPTION")
- private String description = null;
+ @Column(name = "DESCRIPTION")
+ private String description = null;
- @Column(name = "NEUTRON_NETWORK_TYPE")
- private String neutronNetworkType = null;
+ @Column(name = "NEUTRON_NETWORK_TYPE")
+ private String neutronNetworkType = null;
- @Column(name = "AIC_VERSION_MIN")
- private String aicVersionMin = null;
+ @Column(name = "AIC_VERSION_MIN")
+ private String aicVersionMin = null;
- @Column(name = "AIC_VERSION_MAX")
- private String aicVersionMax = null;
+ @Column(name = "AIC_VERSION_MAX")
+ private String aicVersionMax = null;
- @Column(name = "MODEL_NAME")
- private String modelName;
+ @Column(name = "MODEL_NAME")
+ private String modelName;
- @Column(name = "MODEL_INVARIANT_UUID")
- private String modelInvariantUUID;
+ @Column(name = "MODEL_INVARIANT_UUID")
+ private String modelInvariantUUID;
- @Column(name = "MODEL_VERSION")
- private String modelVersion;
+ @Column(name = "MODEL_VERSION")
+ private String modelVersion;
- @Column(name = "TOSCA_NODE_TYPE")
- private String toscaNodeType;
+ @Column(name = "TOSCA_NODE_TYPE")
+ private String toscaNodeType;
- @Column(name = "RESOURCE_CATEGORY")
- private String category;
+ @Column(name = "RESOURCE_CATEGORY")
+ private String category;
- @Column(name = "RESOURCE_SUB_CATEGORY")
- private String subCategory;
+ @Column(name = "RESOURCE_SUB_CATEGORY")
+ private String subCategory;
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
- @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "networkResource")
- private List<NetworkResourceCustomization> networkResourceCustomization;
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "networkResource")
+ private List<NetworkResourceCustomization> networkResourceCustomization;
- @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "networkResource")
- private List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomization;
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "networkResource")
+ private List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomization;
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "HEAT_TEMPLATE_ARTIFACT_UUID")
- private HeatTemplate heatTemplate;
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "HEAT_TEMPLATE_ARTIFACT_UUID")
+ private HeatTemplate heatTemplate;
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof NetworkResource)) {
- return false;
- }
- NetworkResource castOther = (NetworkResource) other;
- return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof NetworkResource)) {
+ return false;
+ }
+ NetworkResource castOther = (NetworkResource) other;
+ return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelUUID).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelUUID).toHashCode();
+ }
- @LinkedResource
- public List<NetworkResourceCustomization> getNetworkResourceCustomization() {
- return networkResourceCustomization;
- }
+ @LinkedResource
+ public List<NetworkResourceCustomization> getNetworkResourceCustomization() {
+ return networkResourceCustomization;
+ }
- public void addNetworkResourceCustomization(NetworkResourceCustomization networkResourceCustomization) {
- if (this.networkResourceCustomization == null)
- this.networkResourceCustomization = new ArrayList<>();
+ public void addNetworkResourceCustomization(NetworkResourceCustomization networkResourceCustomization) {
+ if (this.networkResourceCustomization == null)
+ this.networkResourceCustomization = new ArrayList<>();
- this.networkResourceCustomization.add(networkResourceCustomization);
- }
+ this.networkResourceCustomization.add(networkResourceCustomization);
+ }
- public void setNetworkResourceCustomization(List<NetworkResourceCustomization> networkResourceCustomization) {
- this.networkResourceCustomization = networkResourceCustomization;
- }
+ public void setNetworkResourceCustomization(List<NetworkResourceCustomization> networkResourceCustomization) {
+ this.networkResourceCustomization = networkResourceCustomization;
+ }
- @LinkedResource
- public List<CollectionNetworkResourceCustomization> getCollectionNetworkResourceCustomization() {
- return collectionNetworkResourceCustomization;
- }
+ @LinkedResource
+ public List<CollectionNetworkResourceCustomization> getCollectionNetworkResourceCustomization() {
+ return collectionNetworkResourceCustomization;
+ }
- public void setCollectionNetworkResourceCustomization(
- List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomization) {
- this.collectionNetworkResourceCustomization = collectionNetworkResourceCustomization;
- }
-
- public String getOrchestrationMode() {
- return orchestrationMode;
- }
-
- public void setOrchestrationMode(String orchestrationMode) {
- this.orchestrationMode = orchestrationMode;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getNeutronNetworkType() {
- return neutronNetworkType;
- }
-
- public void setNeutronNetworkType(String neutronNetworkType) {
- this.neutronNetworkType = neutronNetworkType;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public String getAicVersionMin() {
- return aicVersionMin;
- }
-
- public void setAicVersionMin(String aicVersionMin) {
- this.aicVersionMin = aicVersionMin;
- }
-
- public String getAicVersionMax() {
- return aicVersionMax;
- }
-
- public void setAicVersionMax(String aicVersionMax) {
- this.aicVersionMax = aicVersionMax;
- }
-
- public String getModelName() {
- return modelName;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public String getModelInvariantUUID() {
- return modelInvariantUUID;
- }
-
- public void setModelInvariantUUID(String modelInvariantUUID) {
- this.modelInvariantUUID = modelInvariantUUID;
- }
-
- public String getToscaNodeType() {
- return toscaNodeType;
- }
-
- public void setToscaNodeType(String toscaNodeType) {
- this.toscaNodeType = toscaNodeType;
- }
-
- public String getModelUUID() {
- return modelUUID;
- }
-
- public void setModelUUID(String modelUUID) {
- this.modelUUID = modelUUID;
- }
-
- /**
- * @return Returns the category.
- */
- public String getCategory() {
- return category;
- }
-
- /**
- * @param category
- * The category to set.
- */
- public void setCategory(String category) {
- this.category = category;
- }
-
- /**
- * @return Returns the subCategory.
- */
- public String getSubCategory() {
- return subCategory;
- }
-
- /**
- * @param subCategory
- * The subCategory to set.
- */
- public void setSubCategory(String subCategory) {
- this.subCategory = subCategory;
- }
-
- @LinkedResource
- public HeatTemplate getHeatTemplate() {
- return heatTemplate;
- }
-
- public void setHeatTemplate(HeatTemplate heatTemplate) {
- this.heatTemplate = heatTemplate;
- }
-
- public String getModelVersion() {
- return modelVersion;
- }
-
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("NETWORK Resource:");
- sb.append("modelVersion=");
- sb.append(modelVersion);
- sb.append(",mode=");
- sb.append(orchestrationMode);
- sb.append(",neutronType=");
- sb.append(neutronNetworkType);
- sb.append(",aicVersionMin=");
- sb.append(aicVersionMin);
- sb.append(",aicVersionMax=");
- sb.append(aicVersionMax);
- sb.append(",modelName=");
- sb.append(modelName);
- sb.append(",modelInvariantUUID=");
- sb.append(modelInvariantUUID);
- sb.append(",toscaNodeType=");
- sb.append(toscaNodeType);
- sb.append(",modelUUID=");
- sb.append(modelUUID);
-
- if (created != null) {
- sb.append(",created=");
- sb.append(DateFormat.getInstance().format(created));
- }
-
- return sb.toString();
- }
+ public void setCollectionNetworkResourceCustomization(
+ List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomization) {
+ this.collectionNetworkResourceCustomization = collectionNetworkResourceCustomization;
+ }
+
+ public String getOrchestrationMode() {
+ return orchestrationMode;
+ }
+
+ public void setOrchestrationMode(String orchestrationMode) {
+ this.orchestrationMode = orchestrationMode;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getNeutronNetworkType() {
+ return neutronNetworkType;
+ }
+
+ public void setNeutronNetworkType(String neutronNetworkType) {
+ this.neutronNetworkType = neutronNetworkType;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public String getAicVersionMin() {
+ return aicVersionMin;
+ }
+
+ public void setAicVersionMin(String aicVersionMin) {
+ this.aicVersionMin = aicVersionMin;
+ }
+
+ public String getAicVersionMax() {
+ return aicVersionMax;
+ }
+
+ public void setAicVersionMax(String aicVersionMax) {
+ this.aicVersionMax = aicVersionMax;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getModelInvariantUUID() {
+ return modelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ this.modelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getToscaNodeType() {
+ return toscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ this.toscaNodeType = toscaNodeType;
+ }
+
+ public String getModelUUID() {
+ return modelUUID;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ this.modelUUID = modelUUID;
+ }
+
+ /**
+ * @return Returns the category.
+ */
+ public String getCategory() {
+ return category;
+ }
+
+ /**
+ * @param category The category to set.
+ */
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ /**
+ * @return Returns the subCategory.
+ */
+ public String getSubCategory() {
+ return subCategory;
+ }
+
+ /**
+ * @param subCategory The subCategory to set.
+ */
+ public void setSubCategory(String subCategory) {
+ this.subCategory = subCategory;
+ }
+
+ @LinkedResource
+ public HeatTemplate getHeatTemplate() {
+ return heatTemplate;
+ }
+
+ public void setHeatTemplate(HeatTemplate heatTemplate) {
+ this.heatTemplate = heatTemplate;
+ }
+
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("NETWORK Resource:");
+ sb.append("modelVersion=");
+ sb.append(modelVersion);
+ sb.append(",mode=");
+ sb.append(orchestrationMode);
+ sb.append(",neutronType=");
+ sb.append(neutronNetworkType);
+ sb.append(",aicVersionMin=");
+ sb.append(aicVersionMin);
+ sb.append(",aicVersionMax=");
+ sb.append(aicVersionMax);
+ sb.append(",modelName=");
+ sb.append(modelName);
+ sb.append(",modelInvariantUUID=");
+ sb.append(modelInvariantUUID);
+ sb.append(",toscaNodeType=");
+ sb.append(toscaNodeType);
+ sb.append(",modelUUID=");
+ sb.append(modelUUID);
+
+ if (created != null) {
+ sb.append(",created=");
+ sb.append(DateFormat.getInstance().format(created));
+ }
+
+ return sb.toString();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResourceCustomization.java
index 1e3b6fc220..9287fbcf84 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResourceCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResourceCustomization.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -34,149 +33,146 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "network_resource_customization")
public class NetworkResourceCustomization implements Serializable {
- public static final long serialVersionUID = -1322322139926390329L;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
- .append("modelInstanceName", modelInstanceName).append("created", created)
- .append("networkTechnology", networkTechnology).append("networkType", networkType)
- .append("networkScope", networkScope).append("networkRole", networkRole)
- .append("networkResource", networkResource).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof NetworkResourceCustomization)) {
- return false;
- }
- NetworkResourceCustomization castOther = (NetworkResourceCustomization) other;
- return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode();
- }
-
- public NetworkResourceCustomization() {
- super();
- }
-
- @BusinessKey
- @Id
- @Column(name = "MODEL_CUSTOMIZATION_UUID")
- private String modelCustomizationUUID = null;
-
- @Column(name = "MODEL_INSTANCE_NAME")
- private String modelInstanceName;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @Column(name = "NETWORK_TECHNOLOGY")
- private String networkTechnology;
-
- @Column(name = "NETWORK_TYPE")
- private String networkType = null;
-
- @Column(name = "NETWORK_SCOPE")
- private String networkScope;
-
- @Column(name = "NETWORK_ROLE")
- private String networkRole;
-
- @Column(name = "RESOURCE_INPUT")
- private String resourceInput;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "NETWORK_RESOURCE_MODEL_UUID")
- private NetworkResource networkResource = null;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public String getModelCustomizationUUID() {
- return this.modelCustomizationUUID;
- }
-
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
-
- public String getModelInstanceName() {
- return this.modelInstanceName;
- }
-
- public void setModelInstanceName(String modelInstanceName) {
- this.modelInstanceName = modelInstanceName;
- }
-
- @LinkedResource
- public NetworkResource getNetworkResource() {
- return this.networkResource;
- }
-
- public void setNetworkResource(NetworkResource networkResource) {
- this.networkResource = networkResource;
- }
-
- public String getNetworkType() {
- return this.networkType;
- }
-
- public void setNetworkType(String networkType) {
- this.networkType = networkType;
- }
-
- public Date getCreated() {
- return this.created;
- }
-
- public String getNetworkTechnology() {
- return this.networkTechnology;
- }
-
- public void setNetworkTechnology(String networkTechnology) {
- this.networkTechnology = networkTechnology;
- }
-
- public String getNetworkScope() {
- return this.networkScope;
- }
-
- public void setNetworkScope(String networkScope) {
- this.networkScope = networkScope;
- }
+ public static final long serialVersionUID = -1322322139926390329L;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
+ .append("modelInstanceName", modelInstanceName).append("created", created)
+ .append("networkTechnology", networkTechnology).append("networkType", networkType)
+ .append("networkScope", networkScope).append("networkRole", networkRole)
+ .append("networkResource", networkResource).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof NetworkResourceCustomization)) {
+ return false;
+ }
+ NetworkResourceCustomization castOther = (NetworkResourceCustomization) other;
+ return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode();
+ }
+
+ public NetworkResourceCustomization() {
+ super();
+ }
+
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_CUSTOMIZATION_UUID")
+ private String modelCustomizationUUID = null;
+
+ @Column(name = "MODEL_INSTANCE_NAME")
+ private String modelInstanceName;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @Column(name = "NETWORK_TECHNOLOGY")
+ private String networkTechnology;
+
+ @Column(name = "NETWORK_TYPE")
+ private String networkType = null;
+
+ @Column(name = "NETWORK_SCOPE")
+ private String networkScope;
+
+ @Column(name = "NETWORK_ROLE")
+ private String networkRole;
+
+ @Column(name = "RESOURCE_INPUT")
+ private String resourceInput;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "NETWORK_RESOURCE_MODEL_UUID")
+ private NetworkResource networkResource = null;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public String getModelCustomizationUUID() {
+ return this.modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ public String getModelInstanceName() {
+ return this.modelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ this.modelInstanceName = modelInstanceName;
+ }
+
+ @LinkedResource
+ public NetworkResource getNetworkResource() {
+ return this.networkResource;
+ }
+
+ public void setNetworkResource(NetworkResource networkResource) {
+ this.networkResource = networkResource;
+ }
+
+ public String getNetworkType() {
+ return this.networkType;
+ }
+
+ public void setNetworkType(String networkType) {
+ this.networkType = networkType;
+ }
+
+ public Date getCreated() {
+ return this.created;
+ }
+
+ public String getNetworkTechnology() {
+ return this.networkTechnology;
+ }
+
+ public void setNetworkTechnology(String networkTechnology) {
+ this.networkTechnology = networkTechnology;
+ }
+
+ public String getNetworkScope() {
+ return this.networkScope;
+ }
+
+ public void setNetworkScope(String networkScope) {
+ this.networkScope = networkScope;
+ }
- public void setNetworkRole(String networkRole) {
- this.networkRole = networkRole;
- }
+ public void setNetworkRole(String networkRole) {
+ this.networkRole = networkRole;
+ }
- public String getNetworkRole() {
- return this.networkRole;
- }
+ public String getNetworkRole() {
+ return this.networkRole;
+ }
- public String getResourceInput() {
- return resourceInput;
- }
+ public String getResourceInput() {
+ return resourceInput;
+ }
- public void setResourceInput(String resourceInput) {
- this.resourceInput = resourceInput;
- }
+ public void setResourceInput(String resourceInput) {
+ this.resourceInput = resourceInput;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationAction.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationAction.java
index 1fd254f254..cf8644eedc 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationAction.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationAction.java
@@ -20,28 +20,20 @@
package org.onap.so.db.catalog.beans;
-//TODO find this file a new location?
+// TODO find this file a new location?
public enum OrchestrationAction {
- ASSIGN("Assign"),
- UNASSIGN("Unassign"),
- ACTIVATE("Activate"),
- DEACTIVATE("Deactivate"),
- CHANGE_MODEL("ChangeModel"),
- CREATE("Create"),
- DELETE("Delete"),
- UPDATE("Update"),
- ADD_MEMBERS("AddMembers"),
- REMOVE_MEMBERS("RemoveMembers"),
- CUSTOM("Custom");
-
- private final String name;
-
- private OrchestrationAction(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return name;
- }
+ ASSIGN("Assign"), UNASSIGN("Unassign"), ACTIVATE("Activate"), DEACTIVATE("Deactivate"), CHANGE_MODEL(
+ "ChangeModel"), CREATE("Create"), DELETE("Delete"), UPDATE(
+ "Update"), ADD_MEMBERS("AddMembers"), REMOVE_MEMBERS("RemoveMembers"), CUSTOM("Custom");
+
+ private final String name;
+
+ private OrchestrationAction(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java
index 0fa07cfe0f..e608bfed21 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java
@@ -21,41 +21,37 @@
package org.onap.so.db.catalog.beans;
public enum OrchestrationStatus {
- ACTIVE("Active", "active"),
- ASSIGNED("Assigned", "assigned"),
- CREATED("Created", "created"),
- INVENTORIED("Inventoried", "inventoried"),
- PENDING("Pending", "pending"),
- PENDING_ACTIVATION("PendingActivation", "pending.?activation"),
- PENDING_CREATE("PendingCreate", "pending.?create"),
- PENDING_DELETE("PendingDelete", "pending.?delete"),
- PRECREATED("PreCreated", "pre.?created"),
- CONFIGASSIGNED("ConfigAssigned", "config.?assigned"),
- CONFIGURE("Configure" , "configure"),
- CONFIGURED("Configured" , "configured");
+ ACTIVE("Active", "active"), ASSIGNED("Assigned", "assigned"), CREATED("Created", "created"), INVENTORIED(
+ "Inventoried", "inventoried"), PENDING("Pending", "pending"), PENDING_ACTIVATION("PendingActivation",
+ "pending.?activation"), PENDING_CREATE("PendingCreate", "pending.?create"), PENDING_DELETE(
+ "PendingDelete", "pending.?delete"), PRECREATED("PreCreated",
+ "pre.?created"), CONFIGASSIGNED("ConfigAssigned", "config.?assigned"), CONFIGURE(
+ "Configure", "configure"), CONFIGURED("Configured", "configured");
- private final String name;
- private final String fuzzyMatcher;
- private OrchestrationStatus(String name, String fuzzyMatcher) {
- this.name = name;
- this.fuzzyMatcher = fuzzyMatcher;
- }
+ private final String name;
+ private final String fuzzyMatcher;
- @Override
- public String toString() {
- return name;
- }
- /**
- * case insensitive regular expression match to enum value
- *
- * @param status
- * @return
- */
- public boolean fuzzyMap(String status) {
- if (status != null) {
- return status.matches("(?i)" + this.fuzzyMatcher);
- } else {
- return false;
- }
- }
+ private OrchestrationStatus(String name, String fuzzyMatcher) {
+ this.name = name;
+ this.fuzzyMatcher = fuzzyMatcher;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+
+ /**
+ * case insensitive regular expression match to enum value
+ *
+ * @param status
+ * @return
+ */
+ public boolean fuzzyMap(String status) {
+ if (status != null) {
+ return status.matches("(?i)" + this.fuzzyMatcher);
+ } else {
+ return false;
+ }
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatusStateTransitionDirective.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatusStateTransitionDirective.java
index 245fcdcf92..fd3f387e3f 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatusStateTransitionDirective.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatusStateTransitionDirective.java
@@ -21,7 +21,6 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
@@ -30,105 +29,103 @@ import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@Table(name = "orchestration_status_state_transition_directive")
public class OrchestrationStatusStateTransitionDirective implements Serializable {
- private static final long serialVersionUID = -4626396955833442376L;
-
- @Id
- @Column(name = "id")
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
-
- @Enumerated(EnumType.STRING)
- @Column(name = "RESOURCE_TYPE")
- @BusinessKey
- private ResourceType resourceType;
-
- @Enumerated(EnumType.STRING)
- @Column(name = "ORCHESTRATION_STATUS")
- @BusinessKey
- private OrchestrationStatus orchestrationStatus;
-
- @Enumerated(EnumType.STRING)
- @Column(name = "TARGET_ACTION")
- @BusinessKey
- private OrchestrationAction targetAction;
-
- @Enumerated(EnumType.STRING)
- @Column(name = "FLOW_DIRECTIVE")
- @BusinessKey
- private OrchestrationStatusValidationDirective flowDirective;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", id).append("resourceType", resourceType)
- .append("orchestrationStatus", orchestrationStatus).append("targetAction", targetAction)
- .append("flowDirective", flowDirective).toString();
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public ResourceType getResourceType() {
- return resourceType;
- }
-
- public void setResourceType(ResourceType resourceType) {
- this.resourceType = resourceType;
- }
-
- public OrchestrationStatus getOrchestrationStatus() {
- return orchestrationStatus;
- }
-
- public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
- this.orchestrationStatus = orchestrationStatus;
- }
-
- public OrchestrationAction getTargetAction() {
- return targetAction;
- }
-
- public void setTargetAction(OrchestrationAction targetAction) {
- this.targetAction = targetAction;
- }
-
- public OrchestrationStatusValidationDirective getFlowDirective() {
- return flowDirective;
- }
-
- public void setFlowDirective(OrchestrationStatusValidationDirective flowDirective) {
- this.flowDirective = flowDirective;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof OrchestrationStatusStateTransitionDirective)) {
- return false;
- }
- OrchestrationStatusStateTransitionDirective castOther = (OrchestrationStatusStateTransitionDirective) other;
- return new EqualsBuilder().append(getResourceType(), castOther.getResourceType())
- .append(getOrchestrationStatus(), castOther.getOrchestrationStatus())
- .append(getTargetAction(), castOther.getTargetAction())
- .append(getFlowDirective(), castOther.getFlowDirective()).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(getResourceType()).append(getOrchestrationStatus())
- .append(getTargetAction()).append(getFlowDirective()).toHashCode();
- }
+ private static final long serialVersionUID = -4626396955833442376L;
+
+ @Id
+ @Column(name = "id")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer id;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "RESOURCE_TYPE")
+ @BusinessKey
+ private ResourceType resourceType;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "ORCHESTRATION_STATUS")
+ @BusinessKey
+ private OrchestrationStatus orchestrationStatus;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "TARGET_ACTION")
+ @BusinessKey
+ private OrchestrationAction targetAction;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "FLOW_DIRECTIVE")
+ @BusinessKey
+ private OrchestrationStatusValidationDirective flowDirective;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", id).append("resourceType", resourceType)
+ .append("orchestrationStatus", orchestrationStatus).append("targetAction", targetAction)
+ .append("flowDirective", flowDirective).toString();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public ResourceType getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(ResourceType resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public OrchestrationStatus getOrchestrationStatus() {
+ return orchestrationStatus;
+ }
+
+ public void setOrchestrationStatus(OrchestrationStatus orchestrationStatus) {
+ this.orchestrationStatus = orchestrationStatus;
+ }
+
+ public OrchestrationAction getTargetAction() {
+ return targetAction;
+ }
+
+ public void setTargetAction(OrchestrationAction targetAction) {
+ this.targetAction = targetAction;
+ }
+
+ public OrchestrationStatusValidationDirective getFlowDirective() {
+ return flowDirective;
+ }
+
+ public void setFlowDirective(OrchestrationStatusValidationDirective flowDirective) {
+ this.flowDirective = flowDirective;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof OrchestrationStatusStateTransitionDirective)) {
+ return false;
+ }
+ OrchestrationStatusStateTransitionDirective castOther = (OrchestrationStatusStateTransitionDirective) other;
+ return new EqualsBuilder().append(getResourceType(), castOther.getResourceType())
+ .append(getOrchestrationStatus(), castOther.getOrchestrationStatus())
+ .append(getTargetAction(), castOther.getTargetAction())
+ .append(getFlowDirective(), castOther.getFlowDirective()).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(getResourceType()).append(getOrchestrationStatus())
+ .append(getTargetAction()).append(getFlowDirective()).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatusValidationDirective.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatusValidationDirective.java
index f92aadf7a7..269a73e2c2 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatusValidationDirective.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatusValidationDirective.java
@@ -20,18 +20,18 @@
package org.onap.so.db.catalog.beans;
-//TODO find this file a new location?
+// TODO find this file a new location?
public enum OrchestrationStatusValidationDirective {
- SILENT_SUCCESS("SilentSuccess"), CONTINUE("Continue"), FAIL("Fail"), VALIDATION_SKIPPED("ValidationSkiPped");
+ SILENT_SUCCESS("SilentSuccess"), CONTINUE("Continue"), FAIL("Fail"), VALIDATION_SKIPPED("ValidationSkiPped");
- private final String name;
+ private final String name;
- private OrchestrationStatusValidationDirective(String name) {
- this.name = name;
- }
+ private OrchestrationStatusValidationDirective(String name) {
+ this.name = name;
+ }
- @Override
- public String toString() {
- return name;
- }
+ @Override
+ public String toString() {
+ return name;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResource.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResource.java
index 5e9a07443f..cb3195bbac 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResource.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResource.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.db.catalog.beans;
@@ -88,11 +83,10 @@ public class PnfResource implements Serializable {
@Override
public String toString() {
return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelInvariantUUID", modelInvariantUUID)
- .append("modelName", modelName).append("modelVersion", modelVersion)
- .append("toscaNodeType", toscaNodeType).append("description", description)
- .append("orchestrationMode", orchestrationMode).append("created", created)
- .append("pnfResourceCustomizations", pnfResourceCustomizations)
- .toString();
+ .append("modelName", modelName).append("modelVersion", modelVersion)
+ .append("toscaNodeType", toscaNodeType).append("description", description)
+ .append("orchestrationMode", orchestrationMode).append("created", created)
+ .append("pnfResourceCustomizations", pnfResourceCustomizations).toString();
}
@Override
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceCustomization.java
index 0c236897cb..fabbc5007f 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceCustomization.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.db.catalog.beans;
@@ -91,12 +86,11 @@ public class PnfResourceCustomization implements Serializable {
@Override
public String toString() {
return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
- .append("modelInstanceName", modelInstanceName).append("created", created)
- .append("nfFunction", nfFunction)
- .append("nfType", nfType).append("nfRole", nfRole).append("nfNamingCode", nfNamingCode)
- .append("multiStageDesign", multiStageDesign).append("pnfResources", pnfResources)
- .append("blueprintName", blueprintName).append("blueprintVersion", blueprintVersion)
- .toString();
+ .append("modelInstanceName", modelInstanceName).append("created", created)
+ .append("nfFunction", nfFunction).append("nfType", nfType).append("nfRole", nfRole)
+ .append("nfNamingCode", nfNamingCode).append("multiStageDesign", multiStageDesign)
+ .append("pnfResources", pnfResources).append("blueprintName", blueprintName)
+ .append("blueprintVersion", blueprintVersion).toString();
}
@Override
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Recipe.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Recipe.java
index ff6b713e6b..c030d44d81 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Recipe.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Recipe.java
@@ -21,15 +21,15 @@
package org.onap.so.db.catalog.beans;
public interface Recipe {
- public Integer getId();
+ public Integer getId();
- public String getAction();
+ public String getAction();
- public String getDescription();
+ public String getDescription();
- public String getParamXsd();
+ public String getParamXsd();
- public String getOrchestrationUri();
+ public String getOrchestrationUri();
- public Integer getRecipeTimeout();
+ public Integer getRecipeTimeout();
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ResourceType.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ResourceType.java
index 6d5c0fd9a8..b41548ca99 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ResourceType.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ResourceType.java
@@ -21,24 +21,18 @@
package org.onap.so.db.catalog.beans;
public enum ResourceType {
- SERVICE("Service"),
- VNF("Vnf"),
- VOLUME_GROUP("VolumeGroup"),
- VF_MODULE("VfModule"),
- NETWORK("Network"),
- NETWORK_COLLECTION("NetworkCollection"),
- CONFIGURATION("Configuration"),
- INSTANCE_GROUP("InstanceGroup"),
- NO_VALIDATE("NoValidate");
-
- private final String name;
-
- private ResourceType(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return name;
- }
+ SERVICE("Service"), VNF("Vnf"), VOLUME_GROUP("VolumeGroup"), VF_MODULE("VfModule"), NETWORK(
+ "Network"), NETWORK_COLLECTION("NetworkCollection"), CONFIGURATION(
+ "Configuration"), INSTANCE_GROUP("InstanceGroup"), NO_VALIDATE("NoValidate");
+
+ private final String name;
+
+ private ResourceType(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServerType.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServerType.java
index 194215325b..92ba56cb4e 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServerType.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServerType.java
@@ -21,5 +21,5 @@
package org.onap.so.db.catalog.beans;
public enum ServerType {
- KEYSTONE, ORM, KEYSTONE_V3;
+ KEYSTONE, ORM, KEYSTONE_V3;
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java
index 2a8e86c5b0..c333033ba2 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java
@@ -26,7 +26,6 @@ import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -41,14 +40,11 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.fasterxml.jackson.annotation.JsonFormat;
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@@ -98,36 +94,45 @@ public class Service implements Serializable {
private String resourceOrder;
@OneToMany(cascade = CascadeType.ALL)
- @JoinTable(name = "network_resource_customization_to_service", joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"), inverseJoinColumns = @JoinColumn(name = "RESOURCE_MODEL_CUSTOMIZATION_UUID"))
+ @JoinTable(name = "network_resource_customization_to_service",
+ joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"),
+ inverseJoinColumns = @JoinColumn(name = "RESOURCE_MODEL_CUSTOMIZATION_UUID"))
private List<NetworkResourceCustomization> networkCustomizations;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "service")
private List<VnfResourceCustomization> vnfCustomizations;
@OneToMany(cascade = CascadeType.ALL)
- @JoinTable(name = "allotted_resource_customization_to_service", joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"), inverseJoinColumns = @JoinColumn(name = "RESOURCE_MODEL_CUSTOMIZATION_UUID"))
+ @JoinTable(name = "allotted_resource_customization_to_service",
+ joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"),
+ inverseJoinColumns = @JoinColumn(name = "RESOURCE_MODEL_CUSTOMIZATION_UUID"))
private List<AllottedResourceCustomization> allottedCustomizations;
@OneToMany(cascade = CascadeType.ALL)
- @JoinTable(name = "collection_resource_customization_to_service", joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"), inverseJoinColumns = @JoinColumn(name = "RESOURCE_MODEL_CUSTOMIZATION_UUID"))
+ @JoinTable(name = "collection_resource_customization_to_service",
+ joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"),
+ inverseJoinColumns = @JoinColumn(name = "RESOURCE_MODEL_CUSTOMIZATION_UUID"))
private List<CollectionResourceCustomization> collectionResourceCustomizations;
@OneToMany(cascade = CascadeType.ALL)
- @JoinTable(name = "service_proxy_customization_to_service", joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"), inverseJoinColumns = @JoinColumn(name = "RESOURCE_MODEL_CUSTOMIZATION_UUID"))
+ @JoinTable(name = "service_proxy_customization_to_service", joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"),
+ inverseJoinColumns = @JoinColumn(name = "RESOURCE_MODEL_CUSTOMIZATION_UUID"))
private List<ServiceProxyResourceCustomization> serviceProxyCustomizations;
-
+
@OneToMany(cascade = CascadeType.ALL)
- @JoinTable(name = "configuration_customization_to_service", joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"), inverseJoinColumns = @JoinColumn(name = "RESOURCE_MODEL_CUSTOMIZATION_UUID"))
+ @JoinTable(name = "configuration_customization_to_service", joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"),
+ inverseJoinColumns = @JoinColumn(name = "RESOURCE_MODEL_CUSTOMIZATION_UUID"))
private List<ConfigurationResourceCustomization> configurationCustomizations;
-
+
@OneToMany(cascade = CascadeType.ALL)
- @JoinTable(name = "pnf_resource_customization_to_service", joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"), inverseJoinColumns = @JoinColumn(name = "RESOURCE_MODEL_CUSTOMIZATION_UUID"))
+ @JoinTable(name = "pnf_resource_customization_to_service", joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"),
+ inverseJoinColumns = @JoinColumn(name = "RESOURCE_MODEL_CUSTOMIZATION_UUID"))
private List<PnfResourceCustomization> pnfCustomizations;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "service")
@MapKey(name = "action")
private Map<String, ServiceRecipe> recipes;
-
+
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "TOSCA_CSAR_ARTIFACT_UUID")
private ToscaCsar csar;
@@ -143,10 +148,9 @@ public class Service implements Serializable {
.append("allottedCustomizations", allottedCustomizations)
.append("collectionResourceCustomizations", collectionResourceCustomizations)
.append("serviceProxyCustomizations", serviceProxyCustomizations)
- .append("configurationCustomizations", configurationCustomizations)
- .append("pnfCustomizations", pnfCustomizations)
- .append("recipes", recipes)
- .append("csar", csar).toString();
+ .append("configurationCustomizations", configurationCustomizations)
+ .append("pnfCustomizations", pnfCustomizations).append("recipes", recipes).append("csar", csar)
+ .toString();
}
@PrePersist
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceProxyResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceProxyResourceCustomization.java
index d725c505ff..d8be423f5a 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceProxyResourceCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceProxyResourceCustomization.java
@@ -23,7 +23,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -40,162 +39,158 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "service_proxy_customization")
public class ServiceProxyResourceCustomization implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -2822457299134903084L;
-
- @BusinessKey
- @Id
- @Column(name = "MODEL_CUSTOMIZATION_UUID")
- private String modelCustomizationUUID;
-
- @Column(name = "MODEL_INSTANCE_NAME")
- private String modelInstanceName;
-
- @Column(name = "MODEL_UUID")
- private String modelUUID;
-
- @Column(name = "MODEL_INVARIANT_UUID")
- private String modelInvariantUUID;
-
- @Column(name = "MODEL_VERSION")
- private String modelVersion;
-
- @Column(name = "MODEL_NAME")
- private String modelName;
-
- @Column(name = "TOSCA_NODE_TYPE")
- private String toscaNodeType;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "SOURCE_SERVICE_MODEL_UUID")
- private Service sourceService;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public String getModelCustomizationUUID() {
- return modelCustomizationUUID;
- }
-
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
-
- public String getModelInstanceName() {
- return modelInstanceName;
- }
-
- public void setModelInstanceName(String modelInstanceName) {
- this.modelInstanceName = modelInstanceName;
- }
-
- public String getToscaNodeType() {
- return toscaNodeType;
- }
-
- public void setToscaNodeType(String toscaNodeType) {
- this.toscaNodeType = toscaNodeType;
- }
-
- public Date getCreated() {
- return created;
- }
-
- @LinkedResource
- public Service getSourceService() {
- return sourceService;
- }
-
- public void setSourceService(Service sourceService) {
- this.sourceService = sourceService;
- }
-
- public String getModelUUID() {
- return modelUUID;
- }
-
- public void setModelUUID(String modelUUID) {
- this.modelUUID = modelUUID;
- }
-
- public String getModelInvariantUUID() {
- return modelInvariantUUID;
- }
-
- public void setModelInvariantUUID(String modelInvariantUUID) {
- this.modelInvariantUUID = modelInvariantUUID;
- }
-
- public String getModelVersion() {
- return modelVersion;
- }
-
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
-
- public String getModelName() {
- return modelName;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
- .append("modelInstanceName", modelInstanceName).append("toscaNodeType", toscaNodeType)
- .append("modelUUID", modelUUID)
- .append("modelInvariantUUID",modelInvariantUUID).append("modelName",modelName)
- .append("description",description)
- .append("created", created).append("sourceService", sourceService).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ServiceProxyResourceCustomization)) {
- return false;
- }
- ServiceProxyResourceCustomization castOther = (ServiceProxyResourceCustomization) other;
- return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode();
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -2822457299134903084L;
+
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_CUSTOMIZATION_UUID")
+ private String modelCustomizationUUID;
+
+ @Column(name = "MODEL_INSTANCE_NAME")
+ private String modelInstanceName;
+
+ @Column(name = "MODEL_UUID")
+ private String modelUUID;
+
+ @Column(name = "MODEL_INVARIANT_UUID")
+ private String modelInvariantUUID;
+
+ @Column(name = "MODEL_VERSION")
+ private String modelVersion;
+
+ @Column(name = "MODEL_NAME")
+ private String modelName;
+
+ @Column(name = "TOSCA_NODE_TYPE")
+ private String toscaNodeType;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "SOURCE_SERVICE_MODEL_UUID")
+ private Service sourceService;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public String getModelCustomizationUUID() {
+ return modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ public String getModelInstanceName() {
+ return modelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ this.modelInstanceName = modelInstanceName;
+ }
+
+ public String getToscaNodeType() {
+ return toscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ this.toscaNodeType = toscaNodeType;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ @LinkedResource
+ public Service getSourceService() {
+ return sourceService;
+ }
+
+ public void setSourceService(Service sourceService) {
+ this.sourceService = sourceService;
+ }
+
+ public String getModelUUID() {
+ return modelUUID;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ this.modelUUID = modelUUID;
+ }
+
+ public String getModelInvariantUUID() {
+ return modelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ this.modelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
+ .append("modelInstanceName", modelInstanceName).append("toscaNodeType", toscaNodeType)
+ .append("modelUUID", modelUUID).append("modelInvariantUUID", modelInvariantUUID)
+ .append("modelName", modelName).append("description", description).append("created", created)
+ .append("sourceService", sourceService).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ServiceProxyResourceCustomization)) {
+ return false;
+ }
+ ServiceProxyResourceCustomization castOther = (ServiceProxyResourceCustomization) other;
+ return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceRecipe.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceRecipe.java
index 79b27e7deb..5a241afc3a 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceRecipe.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceRecipe.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -34,168 +33,166 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@Table(name = "service_recipe")
public class ServiceRecipe implements Serializable, Recipe {
-
- private static final long serialVersionUID = 768026109321305392L;
-
- @Id
- @Column(name = "id")
- private Integer id;
-
- @BusinessKey
- @Column(name = "SERVICE_MODEL_UUID")
- private String serviceModelUUID;
-
- @BusinessKey
- @Column(name = "ACTION")
- private String action;
-
- @Column(name = "description")
- private String description;
-
- @BusinessKey
- @Column(name = "ORCHESTRATION_URI")
- private String orchestrationUri;
-
- @Column(name = "SERVICE_PARAM_XSD")
- private String paramXsd;
-
- @Column(name = "RECIPE_TIMEOUT")
- private Integer recipeTimeout;
-
- @Column(name = "SERVICE_TIMEOUT_INTERIM")
- private Integer serviceTimeoutInterim;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @BusinessKey
- @ManyToOne(cascade = CascadeType.ALL)
- @JoinColumn(name = "SERVICE_MODEL_UUID", referencedColumnName = "MODEL_UUID",insertable = false, updatable = false)
- private Service service;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", id).append("serviceModelUUID", serviceModelUUID)
- .append("action", action).append("description", description)
- .append("orchestrationUri", orchestrationUri).append("serviceParamXSD", paramXsd)
- .append("recipeTimeout", recipeTimeout).append("serviceTimeoutInterim", serviceTimeoutInterim)
- .append("created", created).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ServiceRecipe)) {
- return false;
- }
- ServiceRecipe castOther = (ServiceRecipe) other;
- return new EqualsBuilder().append(serviceModelUUID, castOther.serviceModelUUID).append(action, castOther.action)
- .append(orchestrationUri, castOther.orchestrationUri).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(serviceModelUUID).append(action).append(orchestrationUri).toHashCode();
- }
-
- // This 'default' CTR is now needed for backward compatibility since a new
- // CTR was added below
- public ServiceRecipe() {
- super();
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- public String getServiceModelUUID() {
- return serviceModelUUID;
- }
-
- public void setServiceModelUUID(String serviceModelUUID) {
- this.serviceModelUUID = serviceModelUUID;
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getOrchestrationUri() {
- return orchestrationUri;
- }
-
- public void setOrchestrationUri(String orchestrationUri) {
- this.orchestrationUri = orchestrationUri;
- }
-
- public String getParamXsd() {
- return paramXsd;
- }
-
- public void setParamXsd(String paramXsd) {
- this.paramXsd = paramXsd;
- }
-
- public Integer getRecipeTimeout() {
- return recipeTimeout;
- }
-
- public void setRecipeTimeout(Integer recipeTimeout) {
- this.recipeTimeout = recipeTimeout;
- }
-
- public Integer getServiceTimeoutInterim() {
- return serviceTimeoutInterim;
- }
-
- public void setServiceTimeoutInterim(Integer serviceTimeoutInterim) {
- this.serviceTimeoutInterim = serviceTimeoutInterim;
- }
-
- public Service getService() {
- return service;
- }
-
- public void setService(Service service) {
- this.service = service;
- }
-
- public Date getCreated() {
- return created;
- }
+
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @Id
+ @Column(name = "id")
+ private Integer id;
+
+ @BusinessKey
+ @Column(name = "SERVICE_MODEL_UUID")
+ private String serviceModelUUID;
+
+ @BusinessKey
+ @Column(name = "ACTION")
+ private String action;
+
+ @Column(name = "description")
+ private String description;
+
+ @BusinessKey
+ @Column(name = "ORCHESTRATION_URI")
+ private String orchestrationUri;
+
+ @Column(name = "SERVICE_PARAM_XSD")
+ private String paramXsd;
+
+ @Column(name = "RECIPE_TIMEOUT")
+ private Integer recipeTimeout;
+
+ @Column(name = "SERVICE_TIMEOUT_INTERIM")
+ private Integer serviceTimeoutInterim;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @BusinessKey
+ @ManyToOne(cascade = CascadeType.ALL)
+ @JoinColumn(name = "SERVICE_MODEL_UUID", referencedColumnName = "MODEL_UUID", insertable = false, updatable = false)
+ private Service service;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", id).append("serviceModelUUID", serviceModelUUID)
+ .append("action", action).append("description", description)
+ .append("orchestrationUri", orchestrationUri).append("serviceParamXSD", paramXsd)
+ .append("recipeTimeout", recipeTimeout).append("serviceTimeoutInterim", serviceTimeoutInterim)
+ .append("created", created).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ServiceRecipe)) {
+ return false;
+ }
+ ServiceRecipe castOther = (ServiceRecipe) other;
+ return new EqualsBuilder().append(serviceModelUUID, castOther.serviceModelUUID).append(action, castOther.action)
+ .append(orchestrationUri, castOther.orchestrationUri).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(serviceModelUUID).append(action).append(orchestrationUri).toHashCode();
+ }
+
+ // This 'default' CTR is now needed for backward compatibility since a new
+ // CTR was added below
+ public ServiceRecipe() {
+ super();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ public String getServiceModelUUID() {
+ return serviceModelUUID;
+ }
+
+ public void setServiceModelUUID(String serviceModelUUID) {
+ this.serviceModelUUID = serviceModelUUID;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getOrchestrationUri() {
+ return orchestrationUri;
+ }
+
+ public void setOrchestrationUri(String orchestrationUri) {
+ this.orchestrationUri = orchestrationUri;
+ }
+
+ public String getParamXsd() {
+ return paramXsd;
+ }
+
+ public void setParamXsd(String paramXsd) {
+ this.paramXsd = paramXsd;
+ }
+
+ public Integer getRecipeTimeout() {
+ return recipeTimeout;
+ }
+
+ public void setRecipeTimeout(Integer recipeTimeout) {
+ this.recipeTimeout = recipeTimeout;
+ }
+
+ public Integer getServiceTimeoutInterim() {
+ return serviceTimeoutInterim;
+ }
+
+ public void setServiceTimeoutInterim(Integer serviceTimeoutInterim) {
+ this.serviceTimeoutInterim = serviceTimeoutInterim;
+ }
+
+ public Service getService() {
+ return service;
+ }
+
+ public void setService(Service service) {
+ this.service = service;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/SubType.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/SubType.java
index 3230d8427b..77663606a2 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/SubType.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/SubType.java
@@ -21,14 +21,16 @@
package org.onap.so.db.catalog.beans;
public enum SubType {
- SUB_INTERFACE("SUB-INTERFACE");
-
- private final String value;
- SubType(String value){
- this.value = value;
- }
- @Override
- public String toString() {
- return this.value;
- }
+ SUB_INTERFACE("SUB-INTERFACE");
+
+ private final String value;
+
+ SubType(String value) {
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return this.value;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/TempNetworkHeatTemplateLookup.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/TempNetworkHeatTemplateLookup.java
index 484a5a9e97..b037b926f1 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/TempNetworkHeatTemplateLookup.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/TempNetworkHeatTemplateLookup.java
@@ -21,16 +21,13 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@@ -38,82 +35,82 @@ import com.openpojo.business.annotation.BusinessKey;
@IdClass(TempNetworkHeatTemplateLookupId.class)
public class TempNetworkHeatTemplateLookup implements Serializable {
- public static final long serialVersionUID = -1322322139926390329L;
-
- @BusinessKey
- @Id
- @Column(name = "NETWORK_RESOURCE_MODEL_NAME")
- private String networkResourceModelName;
-
- @BusinessKey
- @Id
- @Column(name = "HEAT_TEMPLATE_ARTIFACT_UUID")
- private String heatTemplateArtifactUuid;
-
- @Column(name = "AIC_VERSION_MIN")
- private String aicVersionMin;
-
- @Column(name = "AIC_VERSION_MAX")
- private String aicVersionMax;
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof TempNetworkHeatTemplateLookup)) {
- return false;
- }
- TempNetworkHeatTemplateLookup castOther = (TempNetworkHeatTemplateLookup) other;
- return new EqualsBuilder().append(networkResourceModelName, castOther.networkResourceModelName)
- .append(heatTemplateArtifactUuid, castOther.heatTemplateArtifactUuid).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(networkResourceModelName).append(heatTemplateArtifactUuid).toHashCode();
- }
-
- public TempNetworkHeatTemplateLookup() {
- super();
- }
-
- public String getNetworkResourceModelName() {
- return this.networkResourceModelName;
- }
-
- public void setNetworkResourceModelName(String networkResourceModelName) {
- this.networkResourceModelName = networkResourceModelName;
- }
-
- public String getHeatTemplateArtifactUuid() {
- return this.heatTemplateArtifactUuid;
- }
-
- public void setHeatTemplateArtifactUuid(String heatTemplateArtifactUuid) {
- this.heatTemplateArtifactUuid = heatTemplateArtifactUuid;
- }
-
- public String getAicVersionMin() {
- return this.aicVersionMin;
- }
-
- public void setAicVersionMin(String aicVersionMin) {
- this.aicVersionMin = aicVersionMin;
- }
-
- public String getAicVersionMax() {
- return this.aicVersionMax;
- }
-
- public void setAicVersionMax(String aicVersionMax) {
- this.aicVersionMax = aicVersionMax;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("NetworkResourceModelName=" + this.networkResourceModelName);
- sb.append("HeatTemplateArtifactUuid=" + this.heatTemplateArtifactUuid);
- sb.append("aicVersionMin=" + this.aicVersionMin);
- sb.append("aicVersionMax=" + this.aicVersionMax);
- return sb.toString();
- }
+ public static final long serialVersionUID = -1322322139926390329L;
+
+ @BusinessKey
+ @Id
+ @Column(name = "NETWORK_RESOURCE_MODEL_NAME")
+ private String networkResourceModelName;
+
+ @BusinessKey
+ @Id
+ @Column(name = "HEAT_TEMPLATE_ARTIFACT_UUID")
+ private String heatTemplateArtifactUuid;
+
+ @Column(name = "AIC_VERSION_MIN")
+ private String aicVersionMin;
+
+ @Column(name = "AIC_VERSION_MAX")
+ private String aicVersionMax;
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof TempNetworkHeatTemplateLookup)) {
+ return false;
+ }
+ TempNetworkHeatTemplateLookup castOther = (TempNetworkHeatTemplateLookup) other;
+ return new EqualsBuilder().append(networkResourceModelName, castOther.networkResourceModelName)
+ .append(heatTemplateArtifactUuid, castOther.heatTemplateArtifactUuid).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(networkResourceModelName).append(heatTemplateArtifactUuid).toHashCode();
+ }
+
+ public TempNetworkHeatTemplateLookup() {
+ super();
+ }
+
+ public String getNetworkResourceModelName() {
+ return this.networkResourceModelName;
+ }
+
+ public void setNetworkResourceModelName(String networkResourceModelName) {
+ this.networkResourceModelName = networkResourceModelName;
+ }
+
+ public String getHeatTemplateArtifactUuid() {
+ return this.heatTemplateArtifactUuid;
+ }
+
+ public void setHeatTemplateArtifactUuid(String heatTemplateArtifactUuid) {
+ this.heatTemplateArtifactUuid = heatTemplateArtifactUuid;
+ }
+
+ public String getAicVersionMin() {
+ return this.aicVersionMin;
+ }
+
+ public void setAicVersionMin(String aicVersionMin) {
+ this.aicVersionMin = aicVersionMin;
+ }
+
+ public String getAicVersionMax() {
+ return this.aicVersionMax;
+ }
+
+ public void setAicVersionMax(String aicVersionMax) {
+ this.aicVersionMax = aicVersionMax;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("NetworkResourceModelName=" + this.networkResourceModelName);
+ sb.append("HeatTemplateArtifactUuid=" + this.heatTemplateArtifactUuid);
+ sb.append("aicVersionMin=" + this.aicVersionMin);
+ sb.append("aicVersionMax=" + this.aicVersionMax);
+ return sb.toString();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/TempNetworkHeatTemplateLookupId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/TempNetworkHeatTemplateLookupId.java
index 2be6fe4e12..ff48b7b195 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/TempNetworkHeatTemplateLookupId.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/TempNetworkHeatTemplateLookupId.java
@@ -21,58 +21,56 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
public class TempNetworkHeatTemplateLookupId implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -3660507980620002091L;
- @BusinessKey
- private String networkResourceModelName;
- @BusinessKey
- private String heatTemplateArtifactUuid;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -3660507980620002091L;
+ @BusinessKey
+ private String networkResourceModelName;
+ @BusinessKey
+ private String heatTemplateArtifactUuid;
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("networkResourceModelName", networkResourceModelName)
- .append("heatTemplateArtifactUuid", heatTemplateArtifactUuid).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("networkResourceModelName", networkResourceModelName)
+ .append("heatTemplateArtifactUuid", heatTemplateArtifactUuid).toString();
+ }
- public String getNetworkResourceModelName() {
- return networkResourceModelName;
- }
+ public String getNetworkResourceModelName() {
+ return networkResourceModelName;
+ }
- public void setNetworkResourceModelName(String networkResourceModelName) {
- this.networkResourceModelName = networkResourceModelName;
- }
+ public void setNetworkResourceModelName(String networkResourceModelName) {
+ this.networkResourceModelName = networkResourceModelName;
+ }
- public String getHeatTemplateArtifactUuid() {
- return heatTemplateArtifactUuid;
- }
+ public String getHeatTemplateArtifactUuid() {
+ return heatTemplateArtifactUuid;
+ }
- public void setHeatTemplateArtifactUuid(String heatTemplateArtifactUuid) {
- this.heatTemplateArtifactUuid = heatTemplateArtifactUuid;
- }
+ public void setHeatTemplateArtifactUuid(String heatTemplateArtifactUuid) {
+ this.heatTemplateArtifactUuid = heatTemplateArtifactUuid;
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof TempNetworkHeatTemplateLookupId)) {
- return false;
- }
- TempNetworkHeatTemplateLookupId castOther = (TempNetworkHeatTemplateLookupId) other;
- return new EqualsBuilder().append(networkResourceModelName, castOther.networkResourceModelName)
- .append(heatTemplateArtifactUuid, castOther.heatTemplateArtifactUuid).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof TempNetworkHeatTemplateLookupId)) {
+ return false;
+ }
+ TempNetworkHeatTemplateLookupId castOther = (TempNetworkHeatTemplateLookupId) other;
+ return new EqualsBuilder().append(networkResourceModelName, castOther.networkResourceModelName)
+ .append(heatTemplateArtifactUuid, castOther.heatTemplateArtifactUuid).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(networkResourceModelName).append(heatTemplateArtifactUuid).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(networkResourceModelName).append(heatTemplateArtifactUuid).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ToscaCsar.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ToscaCsar.java
index 567675044e..2f9b19ada0 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ToscaCsar.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ToscaCsar.java
@@ -23,7 +23,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -33,139 +32,135 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "tosca_csar")
public class ToscaCsar implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
+ private static final long serialVersionUID = 768026109321305392L;
- @BusinessKey
- @Id
- @Column(name = "ARTIFACT_UUID")
- private String artifactUUID;
-
- @Column(name = "NAME")
- private String name;
+ @BusinessKey
+ @Id
+ @Column(name = "ARTIFACT_UUID")
+ private String artifactUUID;
+
+ @Column(name = "NAME")
+ private String name;
- @Column(name = "ARTIFACT_CHECKSUM")
- private String artifactChecksum;
+ @Column(name = "ARTIFACT_CHECKSUM")
+ private String artifactChecksum;
- @Column(name = "URL")
- private String url;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @BusinessKey
- @Column(name = "Version")
- private String version;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "csar")
- @JsonIgnore
- private List<Service> services;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("artifactUUID", artifactUUID).append("name", name)
- .append("artifactChecksum", artifactChecksum).append("url", url).append("description", description)
- .append("created", created).append("version", version).append("services", services).toString();
- }
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof ToscaCsar)) {
- return false;
- }
- ToscaCsar castOther = (ToscaCsar) other;
- return new EqualsBuilder().append(artifactUUID, castOther.artifactUUID).append(version, castOther.version)
- .isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(artifactUUID).append(version).toHashCode();
- }
-
- public ToscaCsar() {
- }
-
- public String getArtifactUUID() {
- return artifactUUID;
- }
-
- public void setArtifactUUID(String artifactUUID) {
- this.artifactUUID = artifactUUID;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
- public String getArtifactChecksum() {
- return artifactChecksum;
- }
-
- public void setArtifactChecksum(String artifactChecksum) {
- this.artifactChecksum = artifactChecksum;
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Date getCreated() {
- return created;
- }
-
- @LinkedResource
- public List<Service> getServices() {
- return services;
- }
-
- public void setServices(List<Service> services) {
- this.services = services;
- }
+ @Column(name = "URL")
+ private String url;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @BusinessKey
+ @Column(name = "Version")
+ private String version;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "csar")
+ @JsonIgnore
+ private List<Service> services;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("artifactUUID", artifactUUID).append("name", name)
+ .append("artifactChecksum", artifactChecksum).append("url", url).append("description", description)
+ .append("created", created).append("version", version).append("services", services).toString();
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof ToscaCsar)) {
+ return false;
+ }
+ ToscaCsar castOther = (ToscaCsar) other;
+ return new EqualsBuilder().append(artifactUUID, castOther.artifactUUID).append(version, castOther.version)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(artifactUUID).append(version).toHashCode();
+ }
+
+ public ToscaCsar() {}
+
+ public String getArtifactUUID() {
+ return artifactUUID;
+ }
+
+ public void setArtifactUUID(String artifactUUID) {
+ this.artifactUUID = artifactUUID;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public void setArtifactChecksum(String artifactChecksum) {
+ this.artifactChecksum = artifactChecksum;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ @LinkedResource
+ public List<Service> getServices() {
+ return services;
+ }
+
+ public void setServices(List<Service> services) {
+ this.services = services;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/UserParameters.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/UserParameters.java
index 7d23717b2f..a20647d5c1 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/UserParameters.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/UserParameters.java
@@ -4,7 +4,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
@@ -19,13 +18,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@@ -34,153 +30,153 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "USER_PARAMETERS")
public class UserParameters implements Serializable {
- private static final long serialVersionUID = -5036895978102778877L;
-
- @Id
- @Column(name = "ID", nullable = false, updatable = false)
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer ID;
-
- @BusinessKey
- @Column(name = "NAME")
- private String name;
-
- @Column(name = "PAYLOAD_LOCATION")
- private String payloadLocation;
-
- @Column(name = "LABEL")
- private String label;
-
- @Column(name = "TYPE")
- private String type;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @Column(name = "IS_REQUIRED")
- private Boolean isRequried;
-
- @Column(name = "MAX_LENGTH")
- private Integer maxLength;
-
- @Column(name = "ALLOWABLE_CHARS")
- private String allowableChars;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
-
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "userParameters")
- private List<ActivitySpecUserParameters> activitySpecUserParameters;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public Integer getID() {
- return ID;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @LinkedResource
- public List<ActivitySpecUserParameters> getActivitySpecUserParameters() {
- return activitySpecUserParameters;
- }
-
- public void setActivitySpecUserParameters(
- List<ActivitySpecUserParameters> activitySpecUserParameters) {
- this.activitySpecUserParameters = activitySpecUserParameters;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("name", name)
- .append("ActivitySpecUserParameters", activitySpecUserParameters).toString();
- }
- public String getPayloadLocation() {
- return payloadLocation;
- }
-
- public void setPayloadLocation(String payloadLocation) {
- this.payloadLocation = payloadLocation;
- }
-
- public String getLabel() {
- return label;
- }
-
- public void setLabel(String label) {
- this.label = label;
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Boolean getIsRequried() {
- return isRequried;
- }
-
- public void setIsRequried(Boolean isRequried) {
- this.isRequried = isRequried;
- }
-
- public Integer getMaxLength() {
- return maxLength;
- }
-
- public void setMaxLength(Integer maxLength) {
- this.maxLength = maxLength;
- }
-
- public String getAllowableChars() {
- return allowableChars;
- }
-
- public void setAllowableChars(String allowableChars) {
- this.allowableChars = allowableChars;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof UserParameters)) {
- return false;
- }
- UserParameters castOther = (UserParameters) other;
- return new EqualsBuilder().append(name, castOther.name).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(name).toHashCode();
- }
+ private static final long serialVersionUID = -5036895978102778877L;
+
+ @Id
+ @Column(name = "ID", nullable = false, updatable = false)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer ID;
+
+ @BusinessKey
+ @Column(name = "NAME")
+ private String name;
+
+ @Column(name = "PAYLOAD_LOCATION")
+ private String payloadLocation;
+
+ @Column(name = "LABEL")
+ private String label;
+
+ @Column(name = "TYPE")
+ private String type;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @Column(name = "IS_REQUIRED")
+ private Boolean isRequried;
+
+ @Column(name = "MAX_LENGTH")
+ private Integer maxLength;
+
+ @Column(name = "ALLOWABLE_CHARS")
+ private String allowableChars;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "userParameters")
+ private List<ActivitySpecUserParameters> activitySpecUserParameters;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @LinkedResource
+ public List<ActivitySpecUserParameters> getActivitySpecUserParameters() {
+ return activitySpecUserParameters;
+ }
+
+ public void setActivitySpecUserParameters(List<ActivitySpecUserParameters> activitySpecUserParameters) {
+ this.activitySpecUserParameters = activitySpecUserParameters;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("name", name)
+ .append("ActivitySpecUserParameters", activitySpecUserParameters).toString();
+ }
+
+ public String getPayloadLocation() {
+ return payloadLocation;
+ }
+
+ public void setPayloadLocation(String payloadLocation) {
+ this.payloadLocation = payloadLocation;
+ }
+
+ public String getLabel() {
+ return label;
+ }
+
+ public void setLabel(String label) {
+ this.label = label;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Boolean getIsRequried() {
+ return isRequried;
+ }
+
+ public void setIsRequried(Boolean isRequried) {
+ this.isRequried = isRequried;
+ }
+
+ public Integer getMaxLength() {
+ return maxLength;
+ }
+
+ public void setMaxLength(Integer maxLength) {
+ this.maxLength = maxLength;
+ }
+
+ public String getAllowableChars() {
+ return allowableChars;
+ }
+
+ public void setAllowableChars(String allowableChars) {
+ this.allowableChars = allowableChars;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof UserParameters)) {
+ return false;
+ }
+ UserParameters castOther = (UserParameters) other;
+ return new EqualsBuilder().append(name, castOther.name).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(name).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VFCInstanceGroup.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VFCInstanceGroup.java
index e44309e258..ea7d1adad6 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VFCInstanceGroup.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VFCInstanceGroup.java
@@ -27,8 +27,8 @@ import javax.persistence.Entity;
@DiscriminatorValue(value = "VNFC")
public class VFCInstanceGroup extends InstanceGroup {
- /**
- *
- */
- private static final long serialVersionUID = -6254325954630189563L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -6254325954630189563L;
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModule.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModule.java
index 7d53a0b843..0c7820f5f0 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModule.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModule.java
@@ -24,7 +24,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -39,194 +38,192 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.fasterxml.jackson.annotation.JsonFormat;
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "vf_module")
public class VfModule implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
-
- @Id
- @BusinessKey
- @Column(name = "MODEL_UUID")
- private String modelUUID;
-
- @Column(name = "MODEL_INVARIANT_UUID")
- private String modelInvariantUUID;
-
- @Column(name = "MODEL_NAME")
- private String modelName;
-
- @Column(name = "MODEL_VERSION")
- private String modelVersion;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @Column(name = "IS_BASE")
- private Boolean isBase;
-
- @OneToOne(cascade = CascadeType.ALL)
- @JoinColumn(name = "VOL_HEAT_TEMPLATE_ARTIFACT_UUID")
- private HeatTemplate volumeHeatTemplate;
-
- @OneToOne(cascade = CascadeType.ALL)
- @JoinColumn(name = "HEAT_TEMPLATE_ARTIFACT_UUID")
- private HeatTemplate moduleHeatTemplate;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @OneToMany(cascade = CascadeType.ALL)
- @JoinTable(name = "vf_module_to_heat_files", joinColumns = @JoinColumn(name = "VF_MODULE_MODEL_UUID"), inverseJoinColumns = @JoinColumn(name = "HEAT_FILES_ARTIFACT_UUID"))
- private List<HeatFiles> heatFiles;
-
- @OneToMany(mappedBy = "vfModule")
- private List<VfModuleCustomization> vfModuleCustomization;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "VNF_RESOURCE_MODEL_UUID")
- private VnfResource vnfResources;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelInvariantUUID", modelInvariantUUID)
- .append("modelName", modelName).append("modelVersion", modelVersion).append("description", description)
- .append("isBase", isBase).append("volumeHeatTemplate", volumeHeatTemplate)
- .append("moduleHeatTemplate", moduleHeatTemplate).append("created", created)
- .append("heatFiles", heatFiles).append("vfModuleCustomization", vfModuleCustomization)
- .append("vnfResources", vnfResources).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VfModule)) {
- return false;
- }
- VfModule castOther = (VfModule) other;
- return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelUUID).toHashCode();
- }
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public String getModelInvariantUUID() {
- return modelInvariantUUID;
- }
-
- public void setModelInvariantUUID(String modelInvariantUUID) {
- this.modelInvariantUUID = modelInvariantUUID;
- }
-
- @LinkedResource
- public List<VfModuleCustomization> getVfModuleCustomization() {
- if (vfModuleCustomization == null)
- vfModuleCustomization = new ArrayList<>();
-
- return vfModuleCustomization;
- }
-
- public void setVfModuleCustomization(List<VfModuleCustomization> vfModuleCustomization) {
- this.vfModuleCustomization = vfModuleCustomization;
- }
-
- public String getModelName() {
- return this.modelName;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public Boolean getIsBase() {
- return isBase;
- }
-
- public void setIsBase(Boolean isBase) {
- this.isBase = isBase;
- }
-
- @LinkedResource
- public List<HeatFiles> getHeatFiles() {
- if (heatFiles == null)
- heatFiles = new ArrayList<>();
- return heatFiles;
- }
-
- public void setHeatFiles(List<HeatFiles> heatFiles) {
- this.heatFiles = heatFiles;
- }
-
- @LinkedResource
- public VnfResource getVnfResources() {
- return vnfResources;
- }
-
- public void setVnfResources(VnfResource vnfResources) {
- this.vnfResources = vnfResources;
- }
-
- public String getDescription() {
- return this.description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public String getModelUUID() {
- return modelUUID;
- }
-
- public void setModelUUID(String modelUUID) {
- this.modelUUID = modelUUID;
- }
-
- public String getModelVersion() {
- return modelVersion;
- }
-
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
-
- @LinkedResource
- public HeatTemplate getVolumeHeatTemplate() {
- return volumeHeatTemplate;
- }
-
- public void setVolumeHeatTemplate(HeatTemplate volumeHeatTemplate) {
- this.volumeHeatTemplate = volumeHeatTemplate;
- }
-
- @LinkedResource
- public HeatTemplate getModuleHeatTemplate() {
- return moduleHeatTemplate;
- }
-
- public void setModuleHeatTemplate(HeatTemplate moduleHeatTemplate) {
- this.moduleHeatTemplate = moduleHeatTemplate;
- }
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @Id
+ @BusinessKey
+ @Column(name = "MODEL_UUID")
+ private String modelUUID;
+
+ @Column(name = "MODEL_INVARIANT_UUID")
+ private String modelInvariantUUID;
+
+ @Column(name = "MODEL_NAME")
+ private String modelName;
+
+ @Column(name = "MODEL_VERSION")
+ private String modelVersion;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @Column(name = "IS_BASE")
+ private Boolean isBase;
+
+ @OneToOne(cascade = CascadeType.ALL)
+ @JoinColumn(name = "VOL_HEAT_TEMPLATE_ARTIFACT_UUID")
+ private HeatTemplate volumeHeatTemplate;
+
+ @OneToOne(cascade = CascadeType.ALL)
+ @JoinColumn(name = "HEAT_TEMPLATE_ARTIFACT_UUID")
+ private HeatTemplate moduleHeatTemplate;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @OneToMany(cascade = CascadeType.ALL)
+ @JoinTable(name = "vf_module_to_heat_files", joinColumns = @JoinColumn(name = "VF_MODULE_MODEL_UUID"),
+ inverseJoinColumns = @JoinColumn(name = "HEAT_FILES_ARTIFACT_UUID"))
+ private List<HeatFiles> heatFiles;
+
+ @OneToMany(mappedBy = "vfModule")
+ private List<VfModuleCustomization> vfModuleCustomization;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "VNF_RESOURCE_MODEL_UUID")
+ private VnfResource vnfResources;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelInvariantUUID", modelInvariantUUID)
+ .append("modelName", modelName).append("modelVersion", modelVersion).append("description", description)
+ .append("isBase", isBase).append("volumeHeatTemplate", volumeHeatTemplate)
+ .append("moduleHeatTemplate", moduleHeatTemplate).append("created", created)
+ .append("heatFiles", heatFiles).append("vfModuleCustomization", vfModuleCustomization)
+ .append("vnfResources", vnfResources).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VfModule)) {
+ return false;
+ }
+ VfModule castOther = (VfModule) other;
+ return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelUUID).toHashCode();
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public String getModelInvariantUUID() {
+ return modelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ this.modelInvariantUUID = modelInvariantUUID;
+ }
+
+ @LinkedResource
+ public List<VfModuleCustomization> getVfModuleCustomization() {
+ if (vfModuleCustomization == null)
+ vfModuleCustomization = new ArrayList<>();
+
+ return vfModuleCustomization;
+ }
+
+ public void setVfModuleCustomization(List<VfModuleCustomization> vfModuleCustomization) {
+ this.vfModuleCustomization = vfModuleCustomization;
+ }
+
+ public String getModelName() {
+ return this.modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public Boolean getIsBase() {
+ return isBase;
+ }
+
+ public void setIsBase(Boolean isBase) {
+ this.isBase = isBase;
+ }
+
+ @LinkedResource
+ public List<HeatFiles> getHeatFiles() {
+ if (heatFiles == null)
+ heatFiles = new ArrayList<>();
+ return heatFiles;
+ }
+
+ public void setHeatFiles(List<HeatFiles> heatFiles) {
+ this.heatFiles = heatFiles;
+ }
+
+ @LinkedResource
+ public VnfResource getVnfResources() {
+ return vnfResources;
+ }
+
+ public void setVnfResources(VnfResource vnfResources) {
+ this.vnfResources = vnfResources;
+ }
+
+ public String getDescription() {
+ return this.description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public String getModelUUID() {
+ return modelUUID;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ this.modelUUID = modelUUID;
+ }
+
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ @LinkedResource
+ public HeatTemplate getVolumeHeatTemplate() {
+ return volumeHeatTemplate;
+ }
+
+ public void setVolumeHeatTemplate(HeatTemplate volumeHeatTemplate) {
+ this.volumeHeatTemplate = volumeHeatTemplate;
+ }
+
+ @LinkedResource
+ public HeatTemplate getModuleHeatTemplate() {
+ return moduleHeatTemplate;
+ }
+
+ public void setModuleHeatTemplate(HeatTemplate moduleHeatTemplate) {
+ this.moduleHeatTemplate = moduleHeatTemplate;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModuleCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModuleCustomization.java
index 4ec2a92a73..29f8bcece5 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModuleCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModuleCustomization.java
@@ -25,7 +25,6 @@ import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -39,208 +38,205 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.onap.so.db.catalog.beans.macro.OrchestrationFlow;
-
import com.fasterxml.jackson.annotation.JsonFormat;
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "vf_module_customization")
public class VfModuleCustomization implements Serializable {
- public static final long serialVersionUID = -1322322139926390329L;
-
- @Id
- @BusinessKey
- @Column(name = "ID")
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
-
- @Column(name = "MODEL_CUSTOMIZATION_UUID")
- private String modelCustomizationUUID;
-
- @Column(name = "LABEL")
- private String label;
-
- @Column(name = "MIN_INSTANCES")
- private Integer minInstances;
-
- @Column(name = "MAX_INSTANCES")
- private Integer maxInstances;
-
- @Column(name = "INITIAL_COUNT")
- private Integer initialCount;
-
- @Column(name = "AVAILABILITY_ZONE_COUNT")
- private Integer availabilityZoneCount;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @ManyToOne(cascade = CascadeType.ALL)
- @JoinColumn(name = "VOL_ENVIRONMENT_ARTIFACT_UUID")
- HeatEnvironment volumeHeatEnv;
-
- @ManyToOne(cascade = CascadeType.ALL)
- @JoinColumn(name = "HEAT_ENVIRONMENT_ARTIFACT_UUID")
- HeatEnvironment heatEnvironment;
-
- @ManyToOne(cascade = CascadeType.ALL)
- @JoinColumn(name = "VF_MODULE_MODEL_UUID")
- private VfModule vfModule;
-
- @ManyToOne(cascade = CascadeType.ALL)
- @JoinColumn(name = "VNF_RESOURCE_CUSTOMIZATION_ID")
- private VnfResourceCustomization vnfCustomization;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "vfModuleCustomization")
- private Set<CvnfcCustomization> cvnfcCustomization;
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VfModuleCustomization)) {
- return false;
- }
- VfModuleCustomization castOther = (VfModuleCustomization) other;
- return new EqualsBuilder().append(id, castOther.id).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(id).toHashCode();
- }
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID).append("label", label)
- .append("minInstances", minInstances).append("maxInstances", maxInstances)
- .append("initialCount", initialCount).append("availabilityZoneCount", availabilityZoneCount)
- .append("created", created).append("volumeHeatEnv", volumeHeatEnv)
- .append("heatEnvironment", heatEnvironment).append("vfModule", vfModule).toString();
- }
-
-
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public VnfResourceCustomization getVnfCustomization() {
- return vnfCustomization;
- }
-
- public void setVnfCustomization(VnfResourceCustomization vnfCustomization) {
- this.vnfCustomization = vnfCustomization;
- }
-
- public VfModuleCustomization() {
- super();
- }
-
- public String getModelCustomizationUUID() {
- return this.modelCustomizationUUID;
- }
-
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
-
- @LinkedResource
- public HeatEnvironment getVolumeHeatEnv() {
- return volumeHeatEnv;
- }
-
- public void setVolumeHeatEnv(HeatEnvironment volumeHeatEnv) {
- this.volumeHeatEnv = volumeHeatEnv;
- }
-
- @LinkedResource
- public HeatEnvironment getHeatEnvironment() {
- return heatEnvironment;
- }
-
- public void setHeatEnvironment(HeatEnvironment heatEnvironment) {
- this.heatEnvironment = heatEnvironment;
- }
-
- public Integer getMinInstances() {
- return this.minInstances;
- }
-
- public void setMinInstances(Integer minInstances) {
- this.minInstances = minInstances;
- }
-
- public Integer getMaxInstances() {
- return this.maxInstances;
- }
-
- public void setMaxInstances(Integer maxInstances) {
- this.maxInstances = maxInstances;
- }
-
- public Integer getInitialCount() {
- return this.initialCount;
- }
-
- public void setInitialCount(Integer initialCount) {
- this.initialCount = initialCount;
- }
-
- public Integer getAvailabilityZoneCount() {
- return this.availabilityZoneCount;
- }
-
- public void setAvailabilityZoneCount(Integer availabilityZoneCount) {
- this.availabilityZoneCount = availabilityZoneCount;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public String getLabel() {
- return this.label;
- }
-
- public void setLabel(String label) {
- this.label = label;
- }
-
- @LinkedResource
- public VfModule getVfModule() {
- return this.vfModule;
- }
-
- public void setVfModule(VfModule vfModule) {
- this.vfModule = vfModule;
- }
-
- @LinkedResource
- public Set<CvnfcCustomization> getCvnfcCustomization() {
- if (cvnfcCustomization == null)
- cvnfcCustomization = new HashSet<>();
- return cvnfcCustomization;
- }
-
- public void setCvnfcCustomization(Set<CvnfcCustomization> cvnfcCustomization) {
- this.cvnfcCustomization = cvnfcCustomization;
- }
+ public static final long serialVersionUID = -1322322139926390329L;
+
+ @Id
+ @BusinessKey
+ @Column(name = "ID")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer id;
+
+ @Column(name = "MODEL_CUSTOMIZATION_UUID")
+ private String modelCustomizationUUID;
+
+ @Column(name = "LABEL")
+ private String label;
+
+ @Column(name = "MIN_INSTANCES")
+ private Integer minInstances;
+
+ @Column(name = "MAX_INSTANCES")
+ private Integer maxInstances;
+
+ @Column(name = "INITIAL_COUNT")
+ private Integer initialCount;
+
+ @Column(name = "AVAILABILITY_ZONE_COUNT")
+ private Integer availabilityZoneCount;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @ManyToOne(cascade = CascadeType.ALL)
+ @JoinColumn(name = "VOL_ENVIRONMENT_ARTIFACT_UUID")
+ HeatEnvironment volumeHeatEnv;
+
+ @ManyToOne(cascade = CascadeType.ALL)
+ @JoinColumn(name = "HEAT_ENVIRONMENT_ARTIFACT_UUID")
+ HeatEnvironment heatEnvironment;
+
+ @ManyToOne(cascade = CascadeType.ALL)
+ @JoinColumn(name = "VF_MODULE_MODEL_UUID")
+ private VfModule vfModule;
+
+ @ManyToOne(cascade = CascadeType.ALL)
+ @JoinColumn(name = "VNF_RESOURCE_CUSTOMIZATION_ID")
+ private VnfResourceCustomization vnfCustomization;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "vfModuleCustomization")
+ private Set<CvnfcCustomization> cvnfcCustomization;
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VfModuleCustomization)) {
+ return false;
+ }
+ VfModuleCustomization castOther = (VfModuleCustomization) other;
+ return new EqualsBuilder().append(id, castOther.id).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(id).toHashCode();
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID).append("label", label)
+ .append("minInstances", minInstances).append("maxInstances", maxInstances)
+ .append("initialCount", initialCount).append("availabilityZoneCount", availabilityZoneCount)
+ .append("created", created).append("volumeHeatEnv", volumeHeatEnv)
+ .append("heatEnvironment", heatEnvironment).append("vfModule", vfModule).toString();
+ }
+
+
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public VnfResourceCustomization getVnfCustomization() {
+ return vnfCustomization;
+ }
+
+ public void setVnfCustomization(VnfResourceCustomization vnfCustomization) {
+ this.vnfCustomization = vnfCustomization;
+ }
+
+ public VfModuleCustomization() {
+ super();
+ }
+
+ public String getModelCustomizationUUID() {
+ return this.modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ @LinkedResource
+ public HeatEnvironment getVolumeHeatEnv() {
+ return volumeHeatEnv;
+ }
+
+ public void setVolumeHeatEnv(HeatEnvironment volumeHeatEnv) {
+ this.volumeHeatEnv = volumeHeatEnv;
+ }
+
+ @LinkedResource
+ public HeatEnvironment getHeatEnvironment() {
+ return heatEnvironment;
+ }
+
+ public void setHeatEnvironment(HeatEnvironment heatEnvironment) {
+ this.heatEnvironment = heatEnvironment;
+ }
+
+ public Integer getMinInstances() {
+ return this.minInstances;
+ }
+
+ public void setMinInstances(Integer minInstances) {
+ this.minInstances = minInstances;
+ }
+
+ public Integer getMaxInstances() {
+ return this.maxInstances;
+ }
+
+ public void setMaxInstances(Integer maxInstances) {
+ this.maxInstances = maxInstances;
+ }
+
+ public Integer getInitialCount() {
+ return this.initialCount;
+ }
+
+ public void setInitialCount(Integer initialCount) {
+ this.initialCount = initialCount;
+ }
+
+ public Integer getAvailabilityZoneCount() {
+ return this.availabilityZoneCount;
+ }
+
+ public void setAvailabilityZoneCount(Integer availabilityZoneCount) {
+ this.availabilityZoneCount = availabilityZoneCount;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public String getLabel() {
+ return this.label;
+ }
+
+ public void setLabel(String label) {
+ this.label = label;
+ }
+
+ @LinkedResource
+ public VfModule getVfModule() {
+ return this.vfModule;
+ }
+
+ public void setVfModule(VfModule vfModule) {
+ this.vfModule = vfModule;
+ }
+
+ @LinkedResource
+ public Set<CvnfcCustomization> getCvnfcCustomization() {
+ if (cvnfcCustomization == null)
+ cvnfcCustomization = new HashSet<>();
+ return cvnfcCustomization;
+ }
+
+ public void setCvnfcCustomization(Set<CvnfcCustomization> cvnfcCustomization) {
+ this.cvnfcCustomization = cvnfcCustomization;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfComponentsRecipe.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfComponentsRecipe.java
index e4ac0d5816..58e7c6c61c 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfComponentsRecipe.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfComponentsRecipe.java
@@ -21,151 +21,148 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@Table(name = "vnf_components_recipe")
public class VnfComponentsRecipe implements Serializable, Recipe {
- private static final long serialVersionUID = 768026109321305392L;
+ private static final long serialVersionUID = 768026109321305392L;
- @Id
- @Column(name = "id")
- private Integer id;
+ @Id
+ @Column(name = "id")
+ private Integer id;
- @BusinessKey
- @Column(name = "ACTION")
- private String action;
+ @BusinessKey
+ @Column(name = "ACTION")
+ private String action;
- @Column(name = "DESCRIPTION")
- private String description;
-
- @BusinessKey
- @Column(name = "ORCHESTRATION_URI")
- private String orchestrationUri;
-
- @Column(name = "RECIPE_TIMEOUT")
- private Integer recipeTimeout;
-
- @BusinessKey
- @Column(name = "VNF_TYPE")
- private String vnfType;
-
- @Column(name = "VNF_COMPONENT_PARAM_XSD")
- private String paramXsd;
-
- @Column(name = "VNF_COMPONENT_TYPE")
- private String vnfComponentType;
-
- @BusinessKey
- @Column(name = "VF_MODULE_MODEL_UUID")
- private String vfModuleModelUUID;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", id).append("action", action).append("description", description)
- .append("orchestrationUri", orchestrationUri).append("recipeTimeout", recipeTimeout)
- .append("vnfType", vnfType).append("paramXsd", paramXsd).append("vnfComponentType", vnfComponentType)
- .append("vfModuleModelUUID", vfModuleModelUUID).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VnfComponentsRecipe)) {
- return false;
- }
- VnfComponentsRecipe castOther = (VnfComponentsRecipe) other;
- return new EqualsBuilder().append(action, castOther.action).append(orchestrationUri, castOther.orchestrationUri)
- .append(vnfType, castOther.vnfType).append(vfModuleModelUUID, castOther.vfModuleModelUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(action).append(orchestrationUri).append(vnfType).append(vfModuleModelUUID)
- .toHashCode();
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public void setOrchestrationUri(String orchestrationUri) {
- this.orchestrationUri = orchestrationUri;
- }
-
- public void setRecipeTimeout(Integer recipeTimeout) {
- this.recipeTimeout = recipeTimeout;
- }
-
- public String getVnfType() {
- return vnfType;
- }
-
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
-
- public String getParamXsd() {
- return paramXsd;
- }
-
- public void setParamXsd(String paramXsd) {
- this.paramXsd = paramXsd;
- }
-
- public String getVnfComponentType() {
- return vnfComponentType;
- }
-
- public void setVnfComponentType(String vnfComponentType) {
- this.vnfComponentType = vnfComponentType;
- }
-
- public String getVfModuleModelUUID() {
- return vfModuleModelUUID;
- }
-
- public void setVfModuleModelUUID(String vfModuleModelUUID) {
- this.vfModuleModelUUID = vfModuleModelUUID;
- }
-
- @Override
- public String getOrchestrationUri() {
- return orchestrationUri;
- }
-
- @Override
- public Integer getRecipeTimeout() {
- return recipeTimeout;
- }
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @BusinessKey
+ @Column(name = "ORCHESTRATION_URI")
+ private String orchestrationUri;
+
+ @Column(name = "RECIPE_TIMEOUT")
+ private Integer recipeTimeout;
+
+ @BusinessKey
+ @Column(name = "VNF_TYPE")
+ private String vnfType;
+
+ @Column(name = "VNF_COMPONENT_PARAM_XSD")
+ private String paramXsd;
+
+ @Column(name = "VNF_COMPONENT_TYPE")
+ private String vnfComponentType;
+
+ @BusinessKey
+ @Column(name = "VF_MODULE_MODEL_UUID")
+ private String vfModuleModelUUID;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", id).append("action", action).append("description", description)
+ .append("orchestrationUri", orchestrationUri).append("recipeTimeout", recipeTimeout)
+ .append("vnfType", vnfType).append("paramXsd", paramXsd).append("vnfComponentType", vnfComponentType)
+ .append("vfModuleModelUUID", vfModuleModelUUID).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VnfComponentsRecipe)) {
+ return false;
+ }
+ VnfComponentsRecipe castOther = (VnfComponentsRecipe) other;
+ return new EqualsBuilder().append(action, castOther.action).append(orchestrationUri, castOther.orchestrationUri)
+ .append(vnfType, castOther.vnfType).append(vfModuleModelUUID, castOther.vfModuleModelUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(action).append(orchestrationUri).append(vnfType).append(vfModuleModelUUID)
+ .toHashCode();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public void setOrchestrationUri(String orchestrationUri) {
+ this.orchestrationUri = orchestrationUri;
+ }
+
+ public void setRecipeTimeout(Integer recipeTimeout) {
+ this.recipeTimeout = recipeTimeout;
+ }
+
+ public String getVnfType() {
+ return vnfType;
+ }
+
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ public String getParamXsd() {
+ return paramXsd;
+ }
+
+ public void setParamXsd(String paramXsd) {
+ this.paramXsd = paramXsd;
+ }
+
+ public String getVnfComponentType() {
+ return vnfComponentType;
+ }
+
+ public void setVnfComponentType(String vnfComponentType) {
+ this.vnfComponentType = vnfComponentType;
+ }
+
+ public String getVfModuleModelUUID() {
+ return vfModuleModelUUID;
+ }
+
+ public void setVfModuleModelUUID(String vfModuleModelUUID) {
+ this.vfModuleModelUUID = vfModuleModelUUID;
+ }
+
+ @Override
+ public String getOrchestrationUri() {
+ return orchestrationUri;
+ }
+
+ @Override
+ public Integer getRecipeTimeout() {
+ return recipeTimeout;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfRecipe.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfRecipe.java
index ab2eb622c1..8bf45b52c7 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfRecipe.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfRecipe.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -30,169 +29,167 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@Table(name = "vnf_recipe")
public class VnfRecipe implements Serializable, Recipe {
- private static final long serialVersionUID = 768026109321305392L;
-
- @Id
- @Column(name = "id")
- private Integer id;
-
- @BusinessKey
- @Column(name = "NF_ROLE")
- private String nfRole;
-
- @Column(name = "VNF_PARAM_XSD")
- private String paramXsd;
-
- @Column(name = "VF_MODULE_ID")
- private String vfModuleId;
-
- @BusinessKey
- @Column(name = "ACTION")
- protected String action;
-
- @Column(name = "description")
- private String description;
-
- @BusinessKey
- @Column(name = "ORCHESTRATION_URI")
- protected String orchestrationUri;
-
- @Column(name = "RECIPE_TIMEOUT")
- private Integer recipeTimeout;
-
- @Column(name = "VERSION_STR")
- private String versionStr;
-
- @BusinessKey
- @Column(name = "SERVICE_TYPE")
- private String serviceType;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", id).append("vnfType", nfRole).append("paramXsd", paramXsd)
- .append("vfModuleId", vfModuleId).append("action", action).append("description", description)
- .append("orchestrationUri", orchestrationUri).append("recipeTimeout", recipeTimeout)
- .append("serviceType", serviceType).append("created", created).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VnfRecipe)) {
- return false;
- }
- VnfRecipe castOther = (VnfRecipe) other;
- return new EqualsBuilder().append(nfRole, castOther.nfRole).append(action, castOther.action)
- .append(orchestrationUri, castOther.orchestrationUri).append(serviceType, castOther.serviceType)
- .isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(nfRole).append(action).append(orchestrationUri).append(serviceType)
- .toHashCode();
- }
-
- public String getNfRole() {
- return nfRole;
- }
-
- public void setNfRole(String nfRole) {
- this.nfRole = nfRole;
- }
-
- public String getParamXsd() {
- return paramXsd;
- }
-
- public void setParamXsd(String paramXsd) {
- this.paramXsd = paramXsd;
- }
-
- public String getVfModuleId() {
- return vfModuleId;
- }
-
- public void setVfModuleId(String vfModuleId) {
- this.vfModuleId = vfModuleId;
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getOrchestrationUri() {
- return orchestrationUri;
- }
-
- public void setOrchestrationUri(String orchestrationUri) {
- this.orchestrationUri = orchestrationUri;
- }
-
- public Integer getRecipeTimeout() {
- return recipeTimeout;
- }
-
- public void setRecipeTimeout(Integer recipeTimeout) {
- this.recipeTimeout = recipeTimeout;
- }
-
- public String getServiceType() {
- return serviceType;
- }
-
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public String getVersionStr() {
- return versionStr;
- }
-
- public void setVersionStr(String versionStr) {
- this.versionStr = versionStr;
- }
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @Id
+ @Column(name = "id")
+ private Integer id;
+
+ @BusinessKey
+ @Column(name = "NF_ROLE")
+ private String nfRole;
+
+ @Column(name = "VNF_PARAM_XSD")
+ private String paramXsd;
+
+ @Column(name = "VF_MODULE_ID")
+ private String vfModuleId;
+
+ @BusinessKey
+ @Column(name = "ACTION")
+ protected String action;
+
+ @Column(name = "description")
+ private String description;
+
+ @BusinessKey
+ @Column(name = "ORCHESTRATION_URI")
+ protected String orchestrationUri;
+
+ @Column(name = "RECIPE_TIMEOUT")
+ private Integer recipeTimeout;
+
+ @Column(name = "VERSION_STR")
+ private String versionStr;
+
+ @BusinessKey
+ @Column(name = "SERVICE_TYPE")
+ private String serviceType;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", id).append("vnfType", nfRole).append("paramXsd", paramXsd)
+ .append("vfModuleId", vfModuleId).append("action", action).append("description", description)
+ .append("orchestrationUri", orchestrationUri).append("recipeTimeout", recipeTimeout)
+ .append("serviceType", serviceType).append("created", created).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VnfRecipe)) {
+ return false;
+ }
+ VnfRecipe castOther = (VnfRecipe) other;
+ return new EqualsBuilder().append(nfRole, castOther.nfRole).append(action, castOther.action)
+ .append(orchestrationUri, castOther.orchestrationUri).append(serviceType, castOther.serviceType)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(nfRole).append(action).append(orchestrationUri).append(serviceType)
+ .toHashCode();
+ }
+
+ public String getNfRole() {
+ return nfRole;
+ }
+
+ public void setNfRole(String nfRole) {
+ this.nfRole = nfRole;
+ }
+
+ public String getParamXsd() {
+ return paramXsd;
+ }
+
+ public void setParamXsd(String paramXsd) {
+ this.paramXsd = paramXsd;
+ }
+
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
+
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getOrchestrationUri() {
+ return orchestrationUri;
+ }
+
+ public void setOrchestrationUri(String orchestrationUri) {
+ this.orchestrationUri = orchestrationUri;
+ }
+
+ public Integer getRecipeTimeout() {
+ return recipeTimeout;
+ }
+
+ public void setRecipeTimeout(Integer recipeTimeout) {
+ this.recipeTimeout = recipeTimeout;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public String getVersionStr() {
+ return versionStr;
+ }
+
+ public void setVersionStr(String versionStr) {
+ this.versionStr = versionStr;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResource.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResource.java
index 41269fb010..5d9deb6c89 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResource.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResource.java
@@ -24,7 +24,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
@@ -36,13 +35,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@@ -51,228 +47,225 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "vnf_resource")
public class VnfResource implements Serializable {
- private static final long serialVersionUID = 768026109321305392L;
-
- @BusinessKey
- @Id
- @Column(name = "MODEL_UUID")
- private String modelUUID;
-
- @Column(name = "MODEL_INVARIANT_UUID")
- private String modelInvariantUUID;
-
- @Column(name = "MODEL_NAME")
- private String modelName;
-
- @Column(name = "MODEL_VERSION")
- private String modelVersion;
-
- @Column(name = "TOSCA_NODE_TYPE")
- private String toscaNodeType;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @Column(name = "ORCHESTRATION_MODE")
- private String orchestrationMode;
-
- @Column(name = "AIC_VERSION_MIN")
- private String aicVersionMin;
-
- @Column(name = "AIC_VERSION_MAX")
- private String aicVersionMax;
-
- @Column(name = "RESOURCE_CATEGORY")
- private String category;
-
- @Column(name = "RESOURCE_SUB_CATEGORY")
- private String subCategory;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @ManyToOne(fetch = FetchType.LAZY)
- @NotFound(action = NotFoundAction.IGNORE)
- @JoinColumn(name = "HEAT_TEMPLATE_ARTIFACT_UUID")
- private HeatTemplate heatTemplates;
-
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "vnfResources")
- private List<VnfResourceCustomization> vnfResourceCustomizations;
-
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "vnfResource")
- private List<VnfResourceWorkflow> vnfResourceWorkflow;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelInvariantUUID", modelInvariantUUID)
- .append("modelName", modelName).append("modelVersion", modelVersion)
- .append("toscaNodeType", toscaNodeType).append("description", description)
- .append("orchestrationMode", orchestrationMode).append("aicVersionMin", aicVersionMin)
- .append("aicVersionMax", aicVersionMax).append("created", created)
- .append("heatTemplates", heatTemplates).append("vnfResourceCustomizations", vnfResourceCustomizations)
- .append("vnfResourceWorkflow",vnfResourceWorkflow)
- .toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VnfResource)) {
- return false;
- }
- VnfResource castOther = (VnfResource) other;
- return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelUUID).toHashCode();
- }
-
- public String getOrchestrationMode() {
- return orchestrationMode;
- }
-
- public void setOrchestrationMode(String orchestrationMode) {
- this.orchestrationMode = orchestrationMode;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public String getAicVersionMin() {
- return this.aicVersionMin;
- }
-
- public void setAicVersionMin(String aicVersionMin) {
- this.aicVersionMin = aicVersionMin;
- }
-
- public String getAicVersionMax() {
- return this.aicVersionMax;
- }
-
- public void setAicVersionMax(String aicVersionMax) {
- this.aicVersionMax = aicVersionMax;
- }
-
- /**
- * @return Returns the category.
- */
- public String getCategory() {
- return category;
- }
-
- /**
- * @param category
- * The category to set.
- */
- public void setCategory(String category) {
- this.category = category;
- }
-
- /**
- * @return Returns the subCategory.
- */
- public String getSubCategory() {
- return subCategory;
- }
-
- /**
- * @param subCategory
- * The subCategory to set.
- */
- public void setSubCategory(String subCategory) {
- this.subCategory = subCategory;
- }
-
- public String getModelInvariantUUID() {
- return this.modelInvariantUUID;
- }
-
- public void setModelInvariantUUID(String modelInvariantUUID) {
- this.modelInvariantUUID = modelInvariantUUID;
- }
-
- public String getModelName() {
- return modelName;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public String getModelUUID() {
- return modelUUID;
- }
-
- public void setModelUUID(String modelUUID) {
- this.modelUUID = modelUUID;
- }
-
- public String getModelInvariantId() {
- return this.modelInvariantUUID;
- }
-
- public String getToscaNodeType() {
- return toscaNodeType;
- }
-
- public void setToscaNodeType(String toscaNodeType) {
- this.toscaNodeType = toscaNodeType;
- }
-
- @LinkedResource
- public List<VnfResourceCustomization> getVnfResourceCustomizations() {
- if (vnfResourceCustomizations == null)
- vnfResourceCustomizations = new ArrayList<>();
- return vnfResourceCustomizations;
- }
-
- public void setVnfResourceCustomizations(List<VnfResourceCustomization> vnfResourceCustomizations) {
- this.vnfResourceCustomizations = vnfResourceCustomizations;
- }
-
- @LinkedResource
- public HeatTemplate getHeatTemplates() {
- return heatTemplates;
- }
-
- public void setHeatTemplates(HeatTemplate heatTemplates) {
- this.heatTemplates = heatTemplates;
- }
-
- public String getModelVersion() {
- return modelVersion;
- }
-
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
-
- @LinkedResource
- public List<VnfResourceWorkflow> getVnfResourceWorkflow() {
- if (vnfResourceWorkflow == null)
- vnfResourceWorkflow = new ArrayList<>();
- return vnfResourceWorkflow;
- }
-
- public void setVnfResourceWorkflow(List<VnfResourceWorkflow> vnfResourceWorkflow) {
- this.vnfResourceWorkflow = vnfResourceWorkflow;
- }
+ private static final long serialVersionUID = 768026109321305392L;
+
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_UUID")
+ private String modelUUID;
+
+ @Column(name = "MODEL_INVARIANT_UUID")
+ private String modelInvariantUUID;
+
+ @Column(name = "MODEL_NAME")
+ private String modelName;
+
+ @Column(name = "MODEL_VERSION")
+ private String modelVersion;
+
+ @Column(name = "TOSCA_NODE_TYPE")
+ private String toscaNodeType;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @Column(name = "ORCHESTRATION_MODE")
+ private String orchestrationMode;
+
+ @Column(name = "AIC_VERSION_MIN")
+ private String aicVersionMin;
+
+ @Column(name = "AIC_VERSION_MAX")
+ private String aicVersionMax;
+
+ @Column(name = "RESOURCE_CATEGORY")
+ private String category;
+
+ @Column(name = "RESOURCE_SUB_CATEGORY")
+ private String subCategory;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @ManyToOne(fetch = FetchType.LAZY)
+ @NotFound(action = NotFoundAction.IGNORE)
+ @JoinColumn(name = "HEAT_TEMPLATE_ARTIFACT_UUID")
+ private HeatTemplate heatTemplates;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "vnfResources")
+ private List<VnfResourceCustomization> vnfResourceCustomizations;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "vnfResource")
+ private List<VnfResourceWorkflow> vnfResourceWorkflow;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelUUID", modelUUID).append("modelInvariantUUID", modelInvariantUUID)
+ .append("modelName", modelName).append("modelVersion", modelVersion)
+ .append("toscaNodeType", toscaNodeType).append("description", description)
+ .append("orchestrationMode", orchestrationMode).append("aicVersionMin", aicVersionMin)
+ .append("aicVersionMax", aicVersionMax).append("created", created)
+ .append("heatTemplates", heatTemplates).append("vnfResourceCustomizations", vnfResourceCustomizations)
+ .append("vnfResourceWorkflow", vnfResourceWorkflow).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VnfResource)) {
+ return false;
+ }
+ VnfResource castOther = (VnfResource) other;
+ return new EqualsBuilder().append(modelUUID, castOther.modelUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelUUID).toHashCode();
+ }
+
+ public String getOrchestrationMode() {
+ return orchestrationMode;
+ }
+
+ public void setOrchestrationMode(String orchestrationMode) {
+ this.orchestrationMode = orchestrationMode;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public String getAicVersionMin() {
+ return this.aicVersionMin;
+ }
+
+ public void setAicVersionMin(String aicVersionMin) {
+ this.aicVersionMin = aicVersionMin;
+ }
+
+ public String getAicVersionMax() {
+ return this.aicVersionMax;
+ }
+
+ public void setAicVersionMax(String aicVersionMax) {
+ this.aicVersionMax = aicVersionMax;
+ }
+
+ /**
+ * @return Returns the category.
+ */
+ public String getCategory() {
+ return category;
+ }
+
+ /**
+ * @param category The category to set.
+ */
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ /**
+ * @return Returns the subCategory.
+ */
+ public String getSubCategory() {
+ return subCategory;
+ }
+
+ /**
+ * @param subCategory The subCategory to set.
+ */
+ public void setSubCategory(String subCategory) {
+ this.subCategory = subCategory;
+ }
+
+ public String getModelInvariantUUID() {
+ return this.modelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ this.modelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getModelUUID() {
+ return modelUUID;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ this.modelUUID = modelUUID;
+ }
+
+ public String getModelInvariantId() {
+ return this.modelInvariantUUID;
+ }
+
+ public String getToscaNodeType() {
+ return toscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ this.toscaNodeType = toscaNodeType;
+ }
+
+ @LinkedResource
+ public List<VnfResourceCustomization> getVnfResourceCustomizations() {
+ if (vnfResourceCustomizations == null)
+ vnfResourceCustomizations = new ArrayList<>();
+ return vnfResourceCustomizations;
+ }
+
+ public void setVnfResourceCustomizations(List<VnfResourceCustomization> vnfResourceCustomizations) {
+ this.vnfResourceCustomizations = vnfResourceCustomizations;
+ }
+
+ @LinkedResource
+ public HeatTemplate getHeatTemplates() {
+ return heatTemplates;
+ }
+
+ public void setHeatTemplates(HeatTemplate heatTemplates) {
+ this.heatTemplates = heatTemplates;
+ }
+
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ @LinkedResource
+ public List<VnfResourceWorkflow> getVnfResourceWorkflow() {
+ if (vnfResourceWorkflow == null)
+ vnfResourceWorkflow = new ArrayList<>();
+ return vnfResourceWorkflow;
+ }
+
+ public void setVnfResourceWorkflow(List<VnfResourceWorkflow> vnfResourceWorkflow) {
+ this.vnfResourceWorkflow = vnfResourceWorkflow;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java
index 1cbc7b561f..af99aa8c80 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java
@@ -26,7 +26,6 @@ import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -42,14 +41,11 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.fasterxml.jackson.annotation.JsonFormat;
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@@ -57,13 +53,13 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
public class VnfResourceCustomization implements Serializable {
private static final long serialVersionUID = 768026109321305392L;
-
+
@Id
@BusinessKey
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
-
+
@Column(name = "MODEL_CUSTOMIZATION_UUID")
private String modelCustomizationUUID;
@@ -105,17 +101,17 @@ public class VnfResourceCustomization implements Serializable {
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "VNF_RESOURCE_MODEL_UUID")
private VnfResource vnfResources;
-
+
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "SERVICE_MODEL_UUID")
private Service service;
- @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER, mappedBy = "vnfCustomization")
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "vnfCustomization")
private List<VfModuleCustomization> vfModuleCustomizations;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "vnfResourceCust")
private List<VnfcInstanceGroupCustomization> vnfcInstanceGroupCustomizations = new ArrayList<>();
-
+
@Column(name = "CDS_BLUEPRINT_NAME")
private String blueprintName;
@@ -175,7 +171,7 @@ public class VnfResourceCustomization implements Serializable {
public void setId(Integer id) {
this.id = id;
}
-
+
@LinkedResource
public Service getService() {
return service;
@@ -295,7 +291,7 @@ public class VnfResourceCustomization implements Serializable {
List<VnfcInstanceGroupCustomization> vnfcInstanceGroupCustomizations) {
this.vnfcInstanceGroupCustomizations = vnfcInstanceGroupCustomizations;
}
-
+
public String getResourceInput() {
return resourceInput;
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflow.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflow.java
index 8790e738ef..f49ae26305 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflow.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflow.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -37,101 +36,97 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@IdClass(VnfResourceWorkflowId.class)
@Table(name = "VNF_RESOURCE_TO_WORKFLOW")
public class VnfResourceWorkflow implements Serializable {
-
- private static final long serialVersionUID = -1326433350241927676L;
-
- @Id
- @Column(name = "ID", nullable = false, updatable = false)
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer ID;
-
- @BusinessKey
- @Id
- @Column(name = "VNF_RESOURCE_MODEL_UUID")
- private String vnfResourceModelUUID;
-
- @BusinessKey
- @Id
- @Column(name = "WORKFLOW_ID")
- private Integer workflowId;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "VNF_RESOURCE_MODEL_UUID", updatable = false, insertable = false)
- private VnfResource vnfResource;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "WORKFLOW_ID", updatable = false, insertable = false)
- private Workflow workflow;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("vnfResourceModelUUID", vnfResourceModelUUID)
- .append("workflowId", workflowId)
- .toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VnfResourceWorkflow)) {
- return false;
- }
- VnfResourceWorkflow castOther = (VnfResourceWorkflow) other;
- return new EqualsBuilder().append(vnfResourceModelUUID, castOther.vnfResourceModelUUID)
- .append(workflowId, castOther.workflowId).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(vnfResourceModelUUID).append(workflowId).toHashCode();
- }
-
- public Integer getID() {
- return ID;
- }
-
- public String getVnfResourceModelUUID() {
- return vnfResourceModelUUID;
- }
-
- public void setVnfResourceModelUUID(String vnfResourceModelUUID) {
- this.vnfResourceModelUUID = vnfResourceModelUUID;
- }
-
- public Integer getWorkflowId() {
- return workflowId;
- }
-
- public void setWorkflowId(Integer workflowId) {
- this.workflowId = workflowId;
- }
-
- public VnfResource getVnfResource() {
- return vnfResource;
- }
-
- public void setVnfResource(VnfResource vnfResource) {
- this.vnfResource = vnfResource;
- }
-
- public Workflow getWorkflow() {
- return workflow;
- }
-
- public void setWorkflow(Workflow workflow) {
- this.workflow = workflow;
- }
-
+
+ private static final long serialVersionUID = -1326433350241927676L;
+
+ @Id
+ @Column(name = "ID", nullable = false, updatable = false)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer ID;
+
+ @BusinessKey
+ @Id
+ @Column(name = "VNF_RESOURCE_MODEL_UUID")
+ private String vnfResourceModelUUID;
+
+ @BusinessKey
+ @Id
+ @Column(name = "WORKFLOW_ID")
+ private Integer workflowId;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "VNF_RESOURCE_MODEL_UUID", updatable = false, insertable = false)
+ private VnfResource vnfResource;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "WORKFLOW_ID", updatable = false, insertable = false)
+ private Workflow workflow;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("vnfResourceModelUUID", vnfResourceModelUUID)
+ .append("workflowId", workflowId).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VnfResourceWorkflow)) {
+ return false;
+ }
+ VnfResourceWorkflow castOther = (VnfResourceWorkflow) other;
+ return new EqualsBuilder().append(vnfResourceModelUUID, castOther.vnfResourceModelUUID)
+ .append(workflowId, castOther.workflowId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(vnfResourceModelUUID).append(workflowId).toHashCode();
+ }
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public String getVnfResourceModelUUID() {
+ return vnfResourceModelUUID;
+ }
+
+ public void setVnfResourceModelUUID(String vnfResourceModelUUID) {
+ this.vnfResourceModelUUID = vnfResourceModelUUID;
+ }
+
+ public Integer getWorkflowId() {
+ return workflowId;
+ }
+
+ public void setWorkflowId(Integer workflowId) {
+ this.workflowId = workflowId;
+ }
+
+ public VnfResource getVnfResource() {
+ return vnfResource;
+ }
+
+ public void setVnfResource(VnfResource vnfResource) {
+ this.vnfResource = vnfResource;
+ }
+
+ public Workflow getWorkflow() {
+ return workflow;
+ }
+
+ public void setWorkflow(Workflow workflow) {
+ this.workflow = workflow;
+ }
+
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflowId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflowId.java
index ad8aa0587d..837b9c09b2 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflowId.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflowId.java
@@ -21,61 +21,64 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
public class VnfResourceWorkflowId implements Serializable {
-
- private static final long serialVersionUID = -594459957997483601L;
-
- private Integer ID;
- @BusinessKey
- private String vnfResourceModelUUID;
- @BusinessKey
- private Integer workflowId;
-
- public String getVnfResourceModelUUID() {
- return vnfResourceModelUUID;
- }
- public void setVnfResourceModelUUID(String vnfResourceModelUUID) {
- this.vnfResourceModelUUID = vnfResourceModelUUID;
- }
- public Integer getWorkflowId() {
- return workflowId;
- }
- public void setWorkflowId(Integer workflowId) {
- this.workflowId = workflowId;
- }
- public Integer getID() {
- return ID;
- }
- public void setID(Integer ID) {
- this.ID = ID;
- }
+ private static final long serialVersionUID = -594459957997483601L;
+
+ private Integer ID;
+
+ @BusinessKey
+ private String vnfResourceModelUUID;
+ @BusinessKey
+ private Integer workflowId;
+
+ public String getVnfResourceModelUUID() {
+ return vnfResourceModelUUID;
+ }
+
+ public void setVnfResourceModelUUID(String vnfResourceModelUUID) {
+ this.vnfResourceModelUUID = vnfResourceModelUUID;
+ }
+
+ public Integer getWorkflowId() {
+ return workflowId;
+ }
+
+ public void setWorkflowId(Integer workflowId) {
+ this.workflowId = workflowId;
+ }
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public void setID(Integer ID) {
+ this.ID = ID;
+ }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("vnfResourceModelUUID", vnfResourceModelUUID)
- .append("workflowId", workflowId).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("vnfResourceModelUUID", vnfResourceModelUUID)
+ .append("workflowId", workflowId).toString();
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VnfResourceWorkflowId)) {
- return false;
- }
- VnfResourceWorkflowId castOther = (VnfResourceWorkflowId) other;
- return new EqualsBuilder().append(vnfResourceModelUUID, castOther.vnfResourceModelUUID)
- .append(workflowId, castOther.workflowId).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VnfResourceWorkflowId)) {
+ return false;
+ }
+ VnfResourceWorkflowId castOther = (VnfResourceWorkflowId) other;
+ return new EqualsBuilder().append(vnfResourceModelUUID, castOther.vnfResourceModelUUID)
+ .append(workflowId, castOther.workflowId).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(vnfResourceModelUUID).append(workflowId).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(vnfResourceModelUUID).append(workflowId).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcCustomization.java
index 8534242a58..f6ae503c61 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcCustomization.java
@@ -23,7 +23,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -33,7 +32,6 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import com.fasterxml.jackson.annotation.JsonFormat;
import com.openpojo.business.annotation.BusinessKey;
import org.apache.commons.lang3.builder.HashCodeBuilder;
@@ -44,148 +42,148 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
@Table(name = "vnfc_customization")
public class VnfcCustomization implements Serializable {
- private static final long serialVersionUID = -3772469944364616486L;
-
- @BusinessKey
- @Id
- @Column(name = "MODEL_CUSTOMIZATION_UUID")
- private String modelCustomizationUUID;
-
- @Column(name = "MODEL_INSTANCE_NAME")
- private String modelInstanceName;
-
- @Column(name = "MODEL_UUID")
- private String modelUUID;
-
- @Column(name = "MODEL_INVARIANT_UUID")
- private String modelInvariantUUID;
-
- @Column(name = "MODEL_VERSION")
- private String modelVersion;
-
- @Column(name = "MODEL_NAME")
- private String modelName;
-
- @Column(name = "TOSCA_NODE_TYPE")
- private String toscaNodeType;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "vnfcCustomization")
- private List<CvnfcCustomization> cvnfcCustomization;
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VnfcCustomization)) {
- return false;
- }
- VnfcCustomization castOther = (VnfcCustomization) other;
- return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
- .append("modelInstanceName", modelInstanceName).append("modelUUID", modelUUID)
- .append("modelInvariantUUID", modelInvariantUUID).append("modelVersion", modelVersion)
- .append("modelName", modelName).append("toscaNodeType", toscaNodeType)
- .append("description", description).append("created", created)
- .append("cvnfcCustomization", cvnfcCustomization).toString();
- }
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public String getModelCustomizationUUID() {
- return modelCustomizationUUID;
- }
-
- public void setModelCustomizationUUID(String modelCustomizationUUID) {
- this.modelCustomizationUUID = modelCustomizationUUID;
- }
-
- public String getModelInstanceName() {
- return modelInstanceName;
- }
-
- public void setModelInstanceName(String modelInstanceName) {
- this.modelInstanceName = modelInstanceName;
- }
-
- public String getModelUUID() {
- return modelUUID;
- }
-
- public void setModelUUID(String modelUUID) {
- this.modelUUID = modelUUID;
- }
-
- public String getModelInvariantUUID() {
- return modelInvariantUUID;
- }
-
- public void setModelInvariantUUID(String modelInvariantUUID) {
- this.modelInvariantUUID = modelInvariantUUID;
- }
-
- public String getModelVersion() {
- return modelVersion;
- }
-
- public void setModelVersion(String modelVersion) {
- this.modelVersion = modelVersion;
- }
-
- public String getModelName() {
- return modelName;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public String getToscaNodeType() {
- return toscaNodeType;
- }
-
- public void setToscaNodeType(String toscaNodeType) {
- this.toscaNodeType = toscaNodeType;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- public List<CvnfcCustomization> getCvnfcCustomization() {
- return cvnfcCustomization;
- }
-
- public void setCvnfcCustomization(List<CvnfcCustomization> cvnfcCustomization) {
- this.cvnfcCustomization = cvnfcCustomization;
- }
+ private static final long serialVersionUID = -3772469944364616486L;
+
+ @BusinessKey
+ @Id
+ @Column(name = "MODEL_CUSTOMIZATION_UUID")
+ private String modelCustomizationUUID;
+
+ @Column(name = "MODEL_INSTANCE_NAME")
+ private String modelInstanceName;
+
+ @Column(name = "MODEL_UUID")
+ private String modelUUID;
+
+ @Column(name = "MODEL_INVARIANT_UUID")
+ private String modelInvariantUUID;
+
+ @Column(name = "MODEL_VERSION")
+ private String modelVersion;
+
+ @Column(name = "MODEL_NAME")
+ private String modelName;
+
+ @Column(name = "TOSCA_NODE_TYPE")
+ private String toscaNodeType;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "vnfcCustomization")
+ private List<CvnfcCustomization> cvnfcCustomization;
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VnfcCustomization)) {
+ return false;
+ }
+ VnfcCustomization castOther = (VnfcCustomization) other;
+ return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID)
+ .append("modelInstanceName", modelInstanceName).append("modelUUID", modelUUID)
+ .append("modelInvariantUUID", modelInvariantUUID).append("modelVersion", modelVersion)
+ .append("modelName", modelName).append("toscaNodeType", toscaNodeType)
+ .append("description", description).append("created", created)
+ .append("cvnfcCustomization", cvnfcCustomization).toString();
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public String getModelCustomizationUUID() {
+ return modelCustomizationUUID;
+ }
+
+ public void setModelCustomizationUUID(String modelCustomizationUUID) {
+ this.modelCustomizationUUID = modelCustomizationUUID;
+ }
+
+ public String getModelInstanceName() {
+ return modelInstanceName;
+ }
+
+ public void setModelInstanceName(String modelInstanceName) {
+ this.modelInstanceName = modelInstanceName;
+ }
+
+ public String getModelUUID() {
+ return modelUUID;
+ }
+
+ public void setModelUUID(String modelUUID) {
+ this.modelUUID = modelUUID;
+ }
+
+ public String getModelInvariantUUID() {
+ return modelInvariantUUID;
+ }
+
+ public void setModelInvariantUUID(String modelInvariantUUID) {
+ this.modelInvariantUUID = modelInvariantUUID;
+ }
+
+ public String getModelVersion() {
+ return modelVersion;
+ }
+
+ public void setModelVersion(String modelVersion) {
+ this.modelVersion = modelVersion;
+ }
+
+ public String getModelName() {
+ return modelName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getToscaNodeType() {
+ return toscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ this.toscaNodeType = toscaNodeType;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ public List<CvnfcCustomization> getCvnfcCustomization() {
+ return cvnfcCustomization;
+ }
+
+ public void setCvnfcCustomization(List<CvnfcCustomization> cvnfcCustomization) {
+ this.cvnfcCustomization = cvnfcCustomization;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcInstanceGroupCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcInstanceGroupCustomization.java
index db1c929f9d..695e5bbbb9 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcInstanceGroupCustomization.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcInstanceGroupCustomization.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -37,13 +36,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@@ -51,108 +47,107 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "vnfc_instance_group_customization")
public class VnfcInstanceGroupCustomization implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -8288218040186901676L;
-
- @Id
- @BusinessKey
- @Column(name = "ID")
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "VNF_RESOURCE_CUSTOMIZATION_ID")
- private VnfResourceCustomization vnfResourceCust;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "INSTANCE_GROUP_MODEL_UUID")
- private InstanceGroup instanceGroup;
-
- @Column(name = "FUNCTION")
- private String function;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof VnfcInstanceGroupCustomization)) {
- return false;
- }
- VnfcInstanceGroupCustomization castOther = (VnfcInstanceGroupCustomization) other;
- return new EqualsBuilder().append(id, castOther.id).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(id).toHashCode();
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this)
- .append("function", function).append("description", description)
- .append("created", created).toString();
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public Date getCreated(){
- return created;
- }
-
- public String getFunction() {
- return function;
- }
-
- public void setFunction(String function) {
- this.function = function;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- @LinkedResource
- public VnfResourceCustomization getVnfResourceCust() {
- return vnfResourceCust;
- }
-
- public void setVnfResourceCust(VnfResourceCustomization vnfResourceCust) {
- this.vnfResourceCust = vnfResourceCust;
- }
-
- @LinkedResource
- public InstanceGroup getInstanceGroup() {
- return instanceGroup;
- }
-
- public void setInstanceGroup(InstanceGroup instanceGroup) {
- this.instanceGroup = instanceGroup;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -8288218040186901676L;
+
+ @Id
+ @BusinessKey
+ @Column(name = "ID")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer id;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "VNF_RESOURCE_CUSTOMIZATION_ID")
+ private VnfResourceCustomization vnfResourceCust;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "INSTANCE_GROUP_MODEL_UUID")
+ private InstanceGroup instanceGroup;
+
+ @Column(name = "FUNCTION")
+ private String function;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof VnfcInstanceGroupCustomization)) {
+ return false;
+ }
+ VnfcInstanceGroupCustomization castOther = (VnfcInstanceGroupCustomization) other;
+ return new EqualsBuilder().append(id, castOther.id).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(id).toHashCode();
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("function", function).append("description", description)
+ .append("created", created).toString();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public String getFunction() {
+ return function;
+ }
+
+ public void setFunction(String function) {
+ this.function = function;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ @LinkedResource
+ public VnfResourceCustomization getVnfResourceCust() {
+ return vnfResourceCust;
+ }
+
+ public void setVnfResourceCust(VnfResourceCustomization vnfResourceCust) {
+ this.vnfResourceCust = vnfResourceCust;
+ }
+
+ @LinkedResource
+ public InstanceGroup getInstanceGroup() {
+ return instanceGroup;
+ }
+
+ public void setInstanceGroup(InstanceGroup instanceGroup) {
+ this.instanceGroup = instanceGroup;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java
index cdbf41747c..1f46bc01f7 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java
@@ -4,7 +4,6 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
@@ -19,13 +18,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@@ -34,203 +30,202 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "workflow")
public class Workflow implements Serializable {
- private static final long serialVersionUID = 1485794141983033264L;
-
- @Id
- @Column(name = "ID", nullable = false, updatable = false)
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer ID;
-
- @Column(name = "ARTIFACT_UUID")
- private String artifactUUID;
-
- @Column(name = "ARTIFACT_NAME")
- private String artifactName;
-
- @Column(name = "NAME")
- private String name;
-
- @Column(name = "OPERATION_NAME")
- private String operationName;
-
- @Column(name = "VERSION")
- private Double version;
-
- @Column(name = "DESCRIPTION")
- private String description;
-
- @Lob
- @Column(name = "BODY", columnDefinition = "LONGTEXT")
- private String body = null;
-
- @Column(name = "RESOURCE_TARGET")
- private String resourceTarget;
-
- @Column(name = "SOURCE")
- private String source;
-
- @Column(name = "TIMEOUT_MINUTES")
- private Integer timeoutMinutes;
-
- @Column(name = "ARTIFACT_CHECKSUM")
- private String artifactChecksum;
-
- @Column(name = "CREATION_TIMESTAMP", updatable = false)
- @Temporal(TemporalType.TIMESTAMP)
- private Date created;
-
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "workflow")
- private List<VnfResourceWorkflow> vnfResourceWorkflow;
-
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "workflow")
- private List<WorkflowActivitySpecSequence> workflowActivitySpecSequence;
-
- @PrePersist
- protected void onCreate() {
- this.created = new Date();
- }
-
- public Integer getID() {
- return ID;
- }
-
- public String getArtifactUUID() {
- return artifactUUID;
- }
-
- public void setArtifactUUID(String artifactUUID) {
- this.artifactUUID = artifactUUID;
- }
-
- public String getArtifactName() {
- return artifactName;
- }
-
- public void setArtifactName(String artifactName) {
- this.artifactName = artifactName;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getOperationName() {
- return operationName;
- }
-
- public void setOperationName(String operationName) {
- this.operationName = operationName;
- }
-
- public Double getVersion() {
- return version;
- }
-
- public void setVersion(Double version) {
- this.version = version;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getBody() {
- return body;
- }
-
- public void setBody(String body) {
- this.body = body;
- }
-
- public String getResourceTarget() {
- return resourceTarget;
- }
-
- public void setResourceTarget(String resourceTarget) {
- this.resourceTarget = resourceTarget;
- }
-
- public String getSource() {
- return source;
- }
-
- public void setSource(String source) {
- this.source = source;
- }
-
- public Integer getTimeoutMinutes() {
- return timeoutMinutes;
- }
-
- public void setTimeoutMinutes(Integer timeoutMinutes) {
- this.timeoutMinutes = timeoutMinutes;
- }
-
- public String getArtifactChecksum() {
- return artifactChecksum;
- }
-
- public void setArtifactChecksum(String artifactChecksum) {
- this.artifactChecksum = artifactChecksum;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- @LinkedResource
- public List<VnfResourceWorkflow> getVnfResourceWorkflow() {
- return vnfResourceWorkflow;
- }
-
- public void setVnfResourceWorkflow(
- List<VnfResourceWorkflow> vnfResourceWorkflow) {
- this.vnfResourceWorkflow = vnfResourceWorkflow;
- }
-
- @LinkedResource
- public List<WorkflowActivitySpecSequence> getWorkflowActivitySpecSequence() {
- return workflowActivitySpecSequence;
- }
-
- public void setWorkflowActivitySpecSequence(
- List<WorkflowActivitySpecSequence> workflowActivitySpecSequence) {
- this.workflowActivitySpecSequence = workflowActivitySpecSequence;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("ID", ID).append("artifactUUID", artifactUUID)
- .append("artifactName", artifactName).append("name", name)
- .append("operationName", operationName).append("version", version).append("description", description)
- .append("body",body).append("resourceTarget",resourceTarget).append("source", source)
- .append("timeoutMinutes", timeoutMinutes).append("artifactChecksum", artifactChecksum)
- .append("created", created).append("vnfResourceWorkflow", vnfResourceWorkflow)
- .append("WorkflowActivitySpecSequence",workflowActivitySpecSequence).toString();
- }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof Workflow)) {
- return false;
- }
- Workflow castOther = (Workflow) other;
- return new EqualsBuilder().append(ID, castOther.ID).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(ID).toHashCode();
- }
+ private static final long serialVersionUID = 1485794141983033264L;
+
+ @Id
+ @Column(name = "ID", nullable = false, updatable = false)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer ID;
+
+ @Column(name = "ARTIFACT_UUID")
+ private String artifactUUID;
+
+ @Column(name = "ARTIFACT_NAME")
+ private String artifactName;
+
+ @Column(name = "NAME")
+ private String name;
+
+ @Column(name = "OPERATION_NAME")
+ private String operationName;
+
+ @Column(name = "VERSION")
+ private Double version;
+
+ @Column(name = "DESCRIPTION")
+ private String description;
+
+ @Lob
+ @Column(name = "BODY", columnDefinition = "LONGTEXT")
+ private String body = null;
+
+ @Column(name = "RESOURCE_TARGET")
+ private String resourceTarget;
+
+ @Column(name = "SOURCE")
+ private String source;
+
+ @Column(name = "TIMEOUT_MINUTES")
+ private Integer timeoutMinutes;
+
+ @Column(name = "ARTIFACT_CHECKSUM")
+ private String artifactChecksum;
+
+ @Column(name = "CREATION_TIMESTAMP", updatable = false)
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date created;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "workflow")
+ private List<VnfResourceWorkflow> vnfResourceWorkflow;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "workflow")
+ private List<WorkflowActivitySpecSequence> workflowActivitySpecSequence;
+
+ @PrePersist
+ protected void onCreate() {
+ this.created = new Date();
+ }
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public String getArtifactUUID() {
+ return artifactUUID;
+ }
+
+ public void setArtifactUUID(String artifactUUID) {
+ this.artifactUUID = artifactUUID;
+ }
+
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ public void setArtifactName(String artifactName) {
+ this.artifactName = artifactName;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getOperationName() {
+ return operationName;
+ }
+
+ public void setOperationName(String operationName) {
+ this.operationName = operationName;
+ }
+
+ public Double getVersion() {
+ return version;
+ }
+
+ public void setVersion(Double version) {
+ this.version = version;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getBody() {
+ return body;
+ }
+
+ public void setBody(String body) {
+ this.body = body;
+ }
+
+ public String getResourceTarget() {
+ return resourceTarget;
+ }
+
+ public void setResourceTarget(String resourceTarget) {
+ this.resourceTarget = resourceTarget;
+ }
+
+ public String getSource() {
+ return source;
+ }
+
+ public void setSource(String source) {
+ this.source = source;
+ }
+
+ public Integer getTimeoutMinutes() {
+ return timeoutMinutes;
+ }
+
+ public void setTimeoutMinutes(Integer timeoutMinutes) {
+ this.timeoutMinutes = timeoutMinutes;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public void setArtifactChecksum(String artifactChecksum) {
+ this.artifactChecksum = artifactChecksum;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ @LinkedResource
+ public List<VnfResourceWorkflow> getVnfResourceWorkflow() {
+ return vnfResourceWorkflow;
+ }
+
+ public void setVnfResourceWorkflow(List<VnfResourceWorkflow> vnfResourceWorkflow) {
+ this.vnfResourceWorkflow = vnfResourceWorkflow;
+ }
+
+ @LinkedResource
+ public List<WorkflowActivitySpecSequence> getWorkflowActivitySpecSequence() {
+ return workflowActivitySpecSequence;
+ }
+
+ public void setWorkflowActivitySpecSequence(List<WorkflowActivitySpecSequence> workflowActivitySpecSequence) {
+ this.workflowActivitySpecSequence = workflowActivitySpecSequence;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("ID", ID).append("artifactUUID", artifactUUID)
+ .append("artifactName", artifactName).append("name", name).append("operationName", operationName)
+ .append("version", version).append("description", description).append("body", body)
+ .append("resourceTarget", resourceTarget).append("source", source)
+ .append("timeoutMinutes", timeoutMinutes).append("artifactChecksum", artifactChecksum)
+ .append("created", created).append("vnfResourceWorkflow", vnfResourceWorkflow)
+ .append("WorkflowActivitySpecSequence", workflowActivitySpecSequence).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof Workflow)) {
+ return false;
+ }
+ Workflow castOther = (Workflow) other;
+ return new EqualsBuilder().append(ID, castOther.ID).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(ID).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequence.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequence.java
index 8a1881edf3..4b497cc7da 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequence.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequence.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans;
import java.io.Serializable;
import java.util.Date;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -37,13 +36,10 @@ import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@@ -51,87 +47,86 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Table(name = "workflow_activity_spec_sequence")
public class WorkflowActivitySpecSequence implements Serializable {
- private static final long serialVersionUID = -8788505759463286871L;
-
- @Id
- @Column(name = "ID", nullable = false, updatable = false)
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer ID;
-
- @BusinessKey
- @Id
- @Column(name = "ACTIVITY_SPEC_ID")
- private Integer activitySpecId;
-
- @BusinessKey
- @Id
- @Column(name = "WORKFLOW_ID")
- private Integer workflowId;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "ACTIVITY_SPEC_ID", updatable = false, insertable = false)
- private ActivitySpec activitySpec;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "WORKFLOW_ID", updatable = false, insertable = false)
- private Workflow workflow;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("workflowId", workflowId)
- .append("activitySpecId", activitySpecId)
- .toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof WorkflowActivitySpecSequence)) {
- return false;
- }
- WorkflowActivitySpecSequence castOther = (WorkflowActivitySpecSequence) other;
- return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
- .append(workflowId, castOther.workflowId).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(activitySpecId).append(workflowId).toHashCode();
- }
-
- public Integer getID() {
- return ID;
- }
-
- public Integer getActivitySpecId() {
- return activitySpecId;
- }
-
- public void setActivitySpecId(Integer activitySpecId) {
- this.activitySpecId = activitySpecId;
- }
-
- public Integer getWorkflowId() {
- return workflowId;
- }
-
- public void setWorkflowId(Integer workflowId) {
- this.workflowId = workflowId;
- }
-
- public ActivitySpec getActivitySpec() {
- return activitySpec;
- }
-
- public void setActivitySpec(ActivitySpec activitySpec) {
- this.activitySpec = activitySpec;
- }
-
- public Workflow getWorkflow() {
- return workflow;
- }
-
- public void setWorkflow(Workflow workflow) {
- this.workflow = workflow;
- }
-
+ private static final long serialVersionUID = -8788505759463286871L;
+
+ @Id
+ @Column(name = "ID", nullable = false, updatable = false)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer ID;
+
+ @BusinessKey
+ @Id
+ @Column(name = "ACTIVITY_SPEC_ID")
+ private Integer activitySpecId;
+
+ @BusinessKey
+ @Id
+ @Column(name = "WORKFLOW_ID")
+ private Integer workflowId;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "ACTIVITY_SPEC_ID", updatable = false, insertable = false)
+ private ActivitySpec activitySpec;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "WORKFLOW_ID", updatable = false, insertable = false)
+ private Workflow workflow;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("workflowId", workflowId).append("activitySpecId", activitySpecId)
+ .toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof WorkflowActivitySpecSequence)) {
+ return false;
+ }
+ WorkflowActivitySpecSequence castOther = (WorkflowActivitySpecSequence) other;
+ return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId)
+ .append(workflowId, castOther.workflowId).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(activitySpecId).append(workflowId).toHashCode();
+ }
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public Integer getActivitySpecId() {
+ return activitySpecId;
+ }
+
+ public void setActivitySpecId(Integer activitySpecId) {
+ this.activitySpecId = activitySpecId;
+ }
+
+ public Integer getWorkflowId() {
+ return workflowId;
+ }
+
+ public void setWorkflowId(Integer workflowId) {
+ this.workflowId = workflowId;
+ }
+
+ public ActivitySpec getActivitySpec() {
+ return activitySpec;
+ }
+
+ public void setActivitySpec(ActivitySpec activitySpec) {
+ this.activitySpec = activitySpec;
+ }
+
+ public Workflow getWorkflow() {
+ return workflow;
+ }
+
+ public void setWorkflow(Workflow workflow) {
+ this.workflow = workflow;
+ }
+
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequenceId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequenceId.java
index f0a5759c3a..41af2ed3a5 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequenceId.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequenceId.java
@@ -21,62 +21,64 @@
package org.onap.so.db.catalog.beans;
import java.io.Serializable;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
public class WorkflowActivitySpecSequenceId implements Serializable {
-
- private static final long serialVersionUID = -8987314754011453123L;
-
- private Integer ID;
- @BusinessKey
- private Integer workflowId;
- @BusinessKey
- private Integer activitySpecId;
-
- public Integer getID() {
- return ID;
- }
- public void setID(Integer ID) {
- this.ID = ID;
- }
-
- public Integer getWorkflowId() {
- return workflowId;
- }
- public void setWorkflowId(Integer workflowId) {
- this.workflowId = workflowId;
- }
- public Integer getActivitySpecId() {
- return activitySpecId;
- }
- public void setActivitySpecId(Integer activitySpecId) {
- this.activitySpecId = activitySpecId;
- }
+ private static final long serialVersionUID = -8987314754011453123L;
+
+ private Integer ID;
+
+ @BusinessKey
+ private Integer workflowId;
+ @BusinessKey
+ private Integer activitySpecId;
+
+ public Integer getID() {
+ return ID;
+ }
+
+ public void setID(Integer ID) {
+ this.ID = ID;
+ }
+
+ public Integer getWorkflowId() {
+ return workflowId;
+ }
+
+ public void setWorkflowId(Integer workflowId) {
+ this.workflowId = workflowId;
+ }
+
+ public Integer getActivitySpecId() {
+ return activitySpecId;
+ }
+
+ public void setActivitySpecId(Integer activitySpecId) {
+ this.activitySpecId = activitySpecId;
+ }
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("workflowId", workflowId)
- .append("activitySpecId", activitySpecId).toString();
- }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("workflowId", workflowId).append("activitySpecId", activitySpecId)
+ .toString();
+ }
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof WorkflowActivitySpecSequenceId)) {
- return false;
- }
- WorkflowActivitySpecSequenceId castOther = (WorkflowActivitySpecSequenceId) other;
- return new EqualsBuilder().append(workflowId, castOther.workflowId)
- .append(activitySpecId, castOther.activitySpecId).isEquals();
- }
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof WorkflowActivitySpecSequenceId)) {
+ return false;
+ }
+ WorkflowActivitySpecSequenceId castOther = (WorkflowActivitySpecSequenceId) other;
+ return new EqualsBuilder().append(workflowId, castOther.workflowId)
+ .append(activitySpecId, castOther.activitySpecId).isEquals();
+ }
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(workflowId).append(activitySpecId).toHashCode();
- }
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(workflowId).append(activitySpecId).toHashCode();
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/NorthBoundRequest.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/NorthBoundRequest.java
index 4025e348f8..6319ae01eb 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/NorthBoundRequest.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/NorthBoundRequest.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans.macro;
import java.io.Serializable;
import java.util.List;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -32,181 +31,177 @@ import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "northbound_request_ref_lookup")
public class NorthBoundRequest implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -2238991039015148725L;
-
- @Id
- @Column(name = "id")
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
-
- @BusinessKey
- @Column(name = "MACRO_ACTION")
- private String macroAction;
-
- @BusinessKey
- @Column(name = "ACTION")
- private String action;
-
- @BusinessKey
- @Column(name = "REQUEST_SCOPE")
- private String requestScope;
-
- @BusinessKey
- @Column(name = "IS_ALACARTE")
- private Boolean isAlacarte;
-
- @BusinessKey
- @Column(name = "IS_TOPLEVELFLOW")
- private Boolean isToplevelflow;
-
- @BusinessKey
- @Column(name = "MIN_API_VERSION")
- private Double minApiVersion;
-
- @BusinessKey
- @Column(name = "MAX_API_VERSION")
- private Double maxApiVersion;
-
- @BusinessKey
- @Column(name = "CLOUD_OWNER")
- private String cloudOwner;
-
- @BusinessKey
- @Column(name = "SERVICE_TYPE")
- private String serviceType;
-
- @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "northBoundRequest")
- private List<OrchestrationFlow> orchestrationFlowList;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", id).append("action", action).append("requestScope", requestScope)
- .append("isAlacarte", isAlacarte).append("isToplevelflow", isToplevelflow)
- .append("minApiVersion", minApiVersion).append("maxApiVersion", maxApiVersion)
- .append("cloudOwner",cloudOwner).append("serviceType",serviceType).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof NorthBoundRequest)) {
- return false;
- }
- NorthBoundRequest castOther = (NorthBoundRequest) other;
- return new EqualsBuilder().append(action, castOther.action).append(requestScope, castOther.requestScope)
- .append(isAlacarte, castOther.isAlacarte).append(isToplevelflow, castOther.isToplevelflow)
- .append(minApiVersion, castOther.minApiVersion).append(maxApiVersion, castOther.maxApiVersion)
- .append(cloudOwner, castOther.cloudOwner).append(serviceType, castOther.serviceType)
- .isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(action).append(requestScope).append(isAlacarte).append(isToplevelflow)
- .append(minApiVersion).append(maxApiVersion).append(cloudOwner).append(serviceType).toHashCode();
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- public String getMacroAction() {
- return macroAction;
- }
-
- public void setMacroAction(String macroAction) {
- this.macroAction = macroAction;
- }
-
- public String getRequestScope() {
- return requestScope;
- }
-
- public void setRequestScope(String requestScope) {
- this.requestScope = requestScope;
- }
-
- public Boolean getIsAlacarte() {
- return isAlacarte;
- }
-
- public void setIsAlacarte(Boolean isAlacarte) {
- this.isAlacarte = isAlacarte;
- }
-
- public Boolean getIsToplevelflow() {
- return isToplevelflow;
- }
-
- public void setIsToplevelflow(Boolean isToplevelflow) {
- this.isToplevelflow = isToplevelflow;
- }
-
- public Double getMinApiVersion() {
- return minApiVersion;
- }
-
- public void setMinApiVersion(Double minApiVersion) {
- this.minApiVersion = minApiVersion;
- }
-
- public Double getMaxApiVersion() {
- return maxApiVersion;
- }
-
- public void setMaxApiVersion(Double maxApiVersion) {
- this.maxApiVersion = maxApiVersion;
- }
-
- public String getCloudOwner() {
- return cloudOwner;
- }
-
- public void setCloudOwner(String cloudOwner) {
- this.cloudOwner = cloudOwner;
- }
-
- public String getServiceType() {
- return serviceType;
- }
-
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
-
- @LinkedResource
- public List<OrchestrationFlow> getOrchestrationFlowList() {
- return orchestrationFlowList;
- }
-
- public void setOrchestrationFlowList(List<OrchestrationFlow> orchestrationFlowList) {
- this.orchestrationFlowList = orchestrationFlowList;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -2238991039015148725L;
+
+ @Id
+ @Column(name = "id")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer id;
+
+ @BusinessKey
+ @Column(name = "MACRO_ACTION")
+ private String macroAction;
+
+ @BusinessKey
+ @Column(name = "ACTION")
+ private String action;
+
+ @BusinessKey
+ @Column(name = "REQUEST_SCOPE")
+ private String requestScope;
+
+ @BusinessKey
+ @Column(name = "IS_ALACARTE")
+ private Boolean isAlacarte;
+
+ @BusinessKey
+ @Column(name = "IS_TOPLEVELFLOW")
+ private Boolean isToplevelflow;
+
+ @BusinessKey
+ @Column(name = "MIN_API_VERSION")
+ private Double minApiVersion;
+
+ @BusinessKey
+ @Column(name = "MAX_API_VERSION")
+ private Double maxApiVersion;
+
+ @BusinessKey
+ @Column(name = "CLOUD_OWNER")
+ private String cloudOwner;
+
+ @BusinessKey
+ @Column(name = "SERVICE_TYPE")
+ private String serviceType;
+
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "northBoundRequest")
+ private List<OrchestrationFlow> orchestrationFlowList;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", id).append("action", action).append("requestScope", requestScope)
+ .append("isAlacarte", isAlacarte).append("isToplevelflow", isToplevelflow)
+ .append("minApiVersion", minApiVersion).append("maxApiVersion", maxApiVersion)
+ .append("cloudOwner", cloudOwner).append("serviceType", serviceType).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof NorthBoundRequest)) {
+ return false;
+ }
+ NorthBoundRequest castOther = (NorthBoundRequest) other;
+ return new EqualsBuilder().append(action, castOther.action).append(requestScope, castOther.requestScope)
+ .append(isAlacarte, castOther.isAlacarte).append(isToplevelflow, castOther.isToplevelflow)
+ .append(minApiVersion, castOther.minApiVersion).append(maxApiVersion, castOther.maxApiVersion)
+ .append(cloudOwner, castOther.cloudOwner).append(serviceType, castOther.serviceType).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(action).append(requestScope).append(isAlacarte).append(isToplevelflow)
+ .append(minApiVersion).append(maxApiVersion).append(cloudOwner).append(serviceType).toHashCode();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getMacroAction() {
+ return macroAction;
+ }
+
+ public void setMacroAction(String macroAction) {
+ this.macroAction = macroAction;
+ }
+
+ public String getRequestScope() {
+ return requestScope;
+ }
+
+ public void setRequestScope(String requestScope) {
+ this.requestScope = requestScope;
+ }
+
+ public Boolean getIsAlacarte() {
+ return isAlacarte;
+ }
+
+ public void setIsAlacarte(Boolean isAlacarte) {
+ this.isAlacarte = isAlacarte;
+ }
+
+ public Boolean getIsToplevelflow() {
+ return isToplevelflow;
+ }
+
+ public void setIsToplevelflow(Boolean isToplevelflow) {
+ this.isToplevelflow = isToplevelflow;
+ }
+
+ public Double getMinApiVersion() {
+ return minApiVersion;
+ }
+
+ public void setMinApiVersion(Double minApiVersion) {
+ this.minApiVersion = minApiVersion;
+ }
+
+ public Double getMaxApiVersion() {
+ return maxApiVersion;
+ }
+
+ public void setMaxApiVersion(Double maxApiVersion) {
+ this.maxApiVersion = maxApiVersion;
+ }
+
+ public String getCloudOwner() {
+ return cloudOwner;
+ }
+
+ public void setCloudOwner(String cloudOwner) {
+ this.cloudOwner = cloudOwner;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ @LinkedResource
+ public List<OrchestrationFlow> getOrchestrationFlowList() {
+ return orchestrationFlowList;
+ }
+
+ public void setOrchestrationFlowList(List<OrchestrationFlow> orchestrationFlowList) {
+ this.orchestrationFlowList = orchestrationFlowList;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/OrchestrationFlow.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/OrchestrationFlow.java
index fc017c63aa..b74ade1e1f 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/OrchestrationFlow.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/OrchestrationFlow.java
@@ -21,7 +21,6 @@
package org.onap.so.db.catalog.beans.macro;
import java.io.Serializable;
-
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -32,116 +31,113 @@ import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.onap.so.db.catalog.beans.BuildingBlockDetail;
-
import com.openpojo.business.annotation.BusinessKey;
-
import uk.co.blackpepper.bowman.annotation.LinkedResource;
@Entity
@Table(name = "orchestration_flow_reference")
public class OrchestrationFlow implements Serializable {
- private static final long serialVersionUID = 2457818854397870011L;
-
- @Id
- @Column(name = "ID")
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
-
- @BusinessKey
- @Column(name = "COMPOSITE_ACTION")
- private String action;
-
- @BusinessKey
- @Column(name = "SEQ_NO")
- private Integer sequenceNumber;
-
- @BusinessKey
- @Column(name = "FLOW_NAME")
- private String flowName;
-
- @BusinessKey
- @Column(name = "FLOW_VERSION")
- private Double flowVersion;
-
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
- @JoinColumn(name = "NB_REQ_REF_LOOKUP_ID")
- private NorthBoundRequest northBoundRequest;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", id).append("action", action)
- .append("sequenceNumber", sequenceNumber).append("flowName", flowName)
- .append("flowVersion", flowVersion).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof OrchestrationFlow)) {
- return false;
- }
- OrchestrationFlow castOther = (OrchestrationFlow) other;
- return new EqualsBuilder().append(action, castOther.action).append(sequenceNumber, castOther.sequenceNumber)
- .append(flowName, castOther.flowName).append(flowVersion, castOther.flowVersion).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(action).append(sequenceNumber).append(flowName).append(flowVersion)
- .toHashCode();
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- public Integer getSequenceNumber() {
- return sequenceNumber;
- }
-
- public void setSequenceNumber(Integer sequenceNumber) {
- this.sequenceNumber = sequenceNumber;
- }
-
- public String getFlowName() {
- return flowName;
- }
-
- public void setFlowName(String flowName) {
- this.flowName = flowName;
- }
-
- public Double getFlowVersion() {
- return flowVersion;
- }
-
- public void setFlowVersion(Double flowVersion) {
- this.flowVersion = flowVersion;
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- @LinkedResource
- public NorthBoundRequest getNorthBoundRequest() {
- return northBoundRequest;
- }
-
- public void setNorthBoundRequest(NorthBoundRequest northBoundRequest) {
- this.northBoundRequest = northBoundRequest;
- }
+ private static final long serialVersionUID = 2457818854397870011L;
+
+ @Id
+ @Column(name = "ID")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer id;
+
+ @BusinessKey
+ @Column(name = "COMPOSITE_ACTION")
+ private String action;
+
+ @BusinessKey
+ @Column(name = "SEQ_NO")
+ private Integer sequenceNumber;
+
+ @BusinessKey
+ @Column(name = "FLOW_NAME")
+ private String flowName;
+
+ @BusinessKey
+ @Column(name = "FLOW_VERSION")
+ private Double flowVersion;
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "NB_REQ_REF_LOOKUP_ID")
+ private NorthBoundRequest northBoundRequest;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", id).append("action", action)
+ .append("sequenceNumber", sequenceNumber).append("flowName", flowName)
+ .append("flowVersion", flowVersion).toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof OrchestrationFlow)) {
+ return false;
+ }
+ OrchestrationFlow castOther = (OrchestrationFlow) other;
+ return new EqualsBuilder().append(action, castOther.action).append(sequenceNumber, castOther.sequenceNumber)
+ .append(flowName, castOther.flowName).append(flowVersion, castOther.flowVersion).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(action).append(sequenceNumber).append(flowName).append(flowVersion)
+ .toHashCode();
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public Integer getSequenceNumber() {
+ return sequenceNumber;
+ }
+
+ public void setSequenceNumber(Integer sequenceNumber) {
+ this.sequenceNumber = sequenceNumber;
+ }
+
+ public String getFlowName() {
+ return flowName;
+ }
+
+ public void setFlowName(String flowName) {
+ this.flowName = flowName;
+ }
+
+ public Double getFlowVersion() {
+ return flowVersion;
+ }
+
+ public void setFlowVersion(Double flowVersion) {
+ this.flowVersion = flowVersion;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @LinkedResource
+ public NorthBoundRequest getNorthBoundRequest() {
+ return northBoundRequest;
+ }
+
+ public void setNorthBoundRequest(NorthBoundRequest northBoundRequest) {
+ this.northBoundRequest = northBoundRequest;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java
index 23d9d7bc6c..a12edac8a0 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java
@@ -21,146 +21,144 @@
package org.onap.so.db.catalog.beans.macro;
import java.io.Serializable;
-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
-
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
-
import com.openpojo.business.annotation.BusinessKey;
@Entity
@Table(name = "rainy_day_handler_macro")
public class RainyDayHandlerStatus implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- @Id
- @Column(name = "id")
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
-
- @BusinessKey
- @Column(name = "FLOW_NAME")
- private String flowName;
-
- @BusinessKey
- @Column(name = "SERVICE_TYPE")
- private String serviceType;
-
- @BusinessKey
- @Column(name = "VNF_TYPE")
- private String vnfType;
-
- @BusinessKey
- @Column(name = "ERROR_CODE")
- private String errorCode;
-
- @BusinessKey
- @Column(name = "WORK_STEP")
- private String workStep;
-
- @BusinessKey
- @Column(name = "POLICY")
- private String policy;
-
- @Column(name = "SECONDARY_POLICY")
- private String secondaryPolicy;
-
- @Override
- public String toString() {
- return new ToStringBuilder(this).append("id", id).append("flowName", flowName)
- .append("serviceType", serviceType).append("vnfType", vnfType).append("errorCode", errorCode)
- .append("workStep", workStep).append("policy", policy).append("secondaryPolicy",secondaryPolicy).toString();
- }
-
- @Override
- public boolean equals(final Object other) {
- if (!(other instanceof RainyDayHandlerStatus)) {
- return false;
- }
- RainyDayHandlerStatus castOther = (RainyDayHandlerStatus) other;
- return new EqualsBuilder().append(flowName, castOther.flowName).append(serviceType, castOther.serviceType)
- .append(vnfType, castOther.vnfType).append(errorCode, castOther.errorCode)
- .append(workStep, castOther.workStep).append(policy, castOther.policy).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder().append(flowName).append(serviceType).append(vnfType).append(errorCode)
- .append(workStep).append(policy).toHashCode();
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getFlowName() {
- return flowName;
- }
-
- public void setFlowName(String flowName) {
- this.flowName = flowName;
- }
-
- public String getServiceType() {
- return serviceType;
- }
-
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
-
- public String getVnfType() {
- return vnfType;
- }
-
- public void setVnfType(String vnfType) {
- this.vnfType = vnfType;
- }
-
- public String getErrorCode() {
- return errorCode;
- }
-
- public void setErrorCode(String errorCode) {
- this.errorCode = errorCode;
- }
-
- public String getWorkStep() {
- return workStep;
- }
-
- public void setWorkStep(String workStep) {
- this.workStep = workStep;
- }
-
- public String getPolicy() {
- return policy;
- }
-
- public void setPolicy(String policy) {
- this.policy = policy;
- }
-
- public String getSecondaryPolicy() {
- return secondaryPolicy;
- }
-
- public void setSecondaryPolicy(String secondaryPolicy) {
- this.secondaryPolicy = secondaryPolicy;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name = "id")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Integer id;
+
+ @BusinessKey
+ @Column(name = "FLOW_NAME")
+ private String flowName;
+
+ @BusinessKey
+ @Column(name = "SERVICE_TYPE")
+ private String serviceType;
+
+ @BusinessKey
+ @Column(name = "VNF_TYPE")
+ private String vnfType;
+
+ @BusinessKey
+ @Column(name = "ERROR_CODE")
+ private String errorCode;
+
+ @BusinessKey
+ @Column(name = "WORK_STEP")
+ private String workStep;
+
+ @BusinessKey
+ @Column(name = "POLICY")
+ private String policy;
+
+ @Column(name = "SECONDARY_POLICY")
+ private String secondaryPolicy;
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("id", id).append("flowName", flowName)
+ .append("serviceType", serviceType).append("vnfType", vnfType).append("errorCode", errorCode)
+ .append("workStep", workStep).append("policy", policy).append("secondaryPolicy", secondaryPolicy)
+ .toString();
+ }
+
+ @Override
+ public boolean equals(final Object other) {
+ if (!(other instanceof RainyDayHandlerStatus)) {
+ return false;
+ }
+ RainyDayHandlerStatus castOther = (RainyDayHandlerStatus) other;
+ return new EqualsBuilder().append(flowName, castOther.flowName).append(serviceType, castOther.serviceType)
+ .append(vnfType, castOther.vnfType).append(errorCode, castOther.errorCode)
+ .append(workStep, castOther.workStep).append(policy, castOther.policy).isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder().append(flowName).append(serviceType).append(vnfType).append(errorCode)
+ .append(workStep).append(policy).toHashCode();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getFlowName() {
+ return flowName;
+ }
+
+ public void setFlowName(String flowName) {
+ this.flowName = flowName;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getVnfType() {
+ return vnfType;
+ }
+
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ public String getErrorCode() {
+ return errorCode;
+ }
+
+ public void setErrorCode(String errorCode) {
+ this.errorCode = errorCode;
+ }
+
+ public String getWorkStep() {
+ return workStep;
+ }
+
+ public void setWorkStep(String workStep) {
+ this.workStep = workStep;
+ }
+
+ public String getPolicy() {
+ return policy;
+ }
+
+ public void setPolicy(String policy) {
+ this.policy = policy;
+ }
+
+ public String getSecondaryPolicy() {
+ return secondaryPolicy;
+ }
+
+ public void setSecondaryPolicy(String secondaryPolicy) {
+ this.secondaryPolicy = secondaryPolicy;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java
index 2ce1263f69..f75ccf0b2f 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java
@@ -25,11 +25,9 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
-
import javax.annotation.PostConstruct;
import javax.persistence.EntityNotFoundException;
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.db.catalog.beans.BuildingBlockDetail;
import org.onap.so.db.catalog.beans.CloudSite;
import org.onap.so.db.catalog.beans.CloudifyManager;
@@ -75,14 +73,13 @@ import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
-
import uk.co.blackpepper.bowman.Client;
import uk.co.blackpepper.bowman.ClientFactory;
import uk.co.blackpepper.bowman.Configuration;
@Component("CatalogDbClient")
public class CatalogDbClient {
-
+
private static final Logger logger = LoggerFactory.getLogger(CatalogDbClient.class);
private static final String CLOUD_SITE = "/cloudSite";
@@ -91,10 +88,12 @@ public class CatalogDbClient {
private static final String RAINY_DAY_HANDLER_MACRO = "/rainy_day_handler_macro";
private static final String NORTHBOUND_REQUEST_REF_LOOKUP = "/northbound_request_ref_lookup";
private static final String NETWORK_RESOURCE_CUSTOMIZATION = "/networkResourceCustomization";
- private static final String COLLECTION_RESOURCE_INSTANCE_GROUP_CUSTOMIZATION = "/collectionResourceInstanceGroupCustomization";
+ private static final String COLLECTION_RESOURCE_INSTANCE_GROUP_CUSTOMIZATION =
+ "/collectionResourceInstanceGroupCustomization";
private static final String VNFC_INSTANCE_GROUP_CUSTOMIZATION = "/vnfcInstanceGroupCustomization";
private static final String ORCHESTRATION_FLOW = "/orchestrationFlow";
- private static final String ORCHESTRATION_STATUS_STATE_TRANSITION_DIRECTIVE = "/orchestrationStatusStateTransitionDirective";
+ private static final String ORCHESTRATION_STATUS_STATE_TRANSITION_DIRECTIVE =
+ "/orchestrationStatusStateTransitionDirective";
private static final String INSTANCE_GROUP = "/instanceGroup";
private static final String COLLECTION_NETWORK_RESOURCE_CUSTOMIZATION = "/collectionNetworkResourceCustomization";
private static final String BUILDING_BLOCK_DETAIL = "/buildingBlockDetail";
@@ -146,7 +145,7 @@ public class CatalogDbClient {
private static final String CLOUD_VERSION = "cloudVersion";
private static final String HOMING_INSTANCE = "/homingInstance";
private static final String ARTIFACT_UUID = "artifactUUID";
-
+
private static final String TARGET_ENTITY = "SO:CatalogDB";
private static final String ASTERISK = "*";
@@ -159,23 +158,34 @@ public class CatalogDbClient {
private String findFirstByModelVersionAndModelInvariantUUIDURI = "/findFirstByModelVersionAndModelInvariantUUID";
private String findByModelInvariantUUIDURI = "/findByModelInvariantUUIDOrderByModelVersionDesc";
private String findFirstByModelNameAndAction = "/findFirstByModelNameAndAction";
- private String findFirstResourceByModelInvariantUUIDAndModelVersion = "/findFirstResourceByModelInvariantUUIDAndModelVersion";
+ private String findFirstResourceByModelInvariantUUIDAndModelVersion =
+ "/findFirstResourceByModelInvariantUUIDAndModelVersion";
private String findByModelInstanceNameAndVnfResources = "/findByModelInstanceNameAndVnfResources";
private String findFirstVnfRecipeByNfRoleAndAction = "/findFirstVnfRecipeByNfRoleAndAction";
- private String findByModelCustomizationUUIDAndVfModuleModelUUID = "/findFirstByModelCustomizationUUIDAndVfModuleModelUUIDOrderByCreatedDesc";
- private String findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction = "/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction";
- private String findFirstVnfComponentsRecipeByVnfComponentTypeAndAction = "/findFirstVnfComponentsRecipeByVnfComponentTypeAndAction";
- private String findVfModuleByModelInvariantUUIDOrderByModelVersionDesc = "/findByModelInvariantUUIDOrderByModelVersionDesc";
- private String findFirstVfModuleByModelInvariantUUIDAndModelVersion = "/findFirstVfModuleByModelInvariantUUIDAndModelVersion";
+ private String findByModelCustomizationUUIDAndVfModuleModelUUID =
+ "/findFirstByModelCustomizationUUIDAndVfModuleModelUUIDOrderByCreatedDesc";
+ private String findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction =
+ "/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction";
+ private String findFirstVnfComponentsRecipeByVnfComponentTypeAndAction =
+ "/findFirstVnfComponentsRecipeByVnfComponentTypeAndAction";
+ private String findVfModuleByModelInvariantUUIDOrderByModelVersionDesc =
+ "/findByModelInvariantUUIDOrderByModelVersionDesc";
+ private String findFirstVfModuleByModelInvariantUUIDAndModelVersion =
+ "/findFirstVfModuleByModelInvariantUUIDAndModelVersion";
private String findOneByBuildingBlockName = "/findOneByBuildingBlockName";
- private String findOneByResourceTypeAndOrchestrationStatusAndTargetAction = "/findOneByResourceTypeAndOrchestrationStatusAndTargetAction";
+ private String findOneByResourceTypeAndOrchestrationStatusAndTargetAction =
+ "/findOneByResourceTypeAndOrchestrationStatusAndTargetAction";
private String findByAction = "/findByAction";
private String findVnfcInstanceGroupCustomizationByModelCustomizationUUID = "/findByModelCustomizationUUID";
- private String findCollectionResourceInstanceGroupCustomizationByModelCustomizationUUID = "/findByModelCustomizationUUID";
+ private String findCollectionResourceInstanceGroupCustomizationByModelCustomizationUUID =
+ "/findByModelCustomizationUUID";
private String findOneByActionAndRequestScopeAndIsAlacarte = "/findOneByActionAndRequestScopeAndIsAlacarte";
- private String findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwner = "/findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwner";
- private String findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType = "/findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType";
- private String findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep = "/findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep";
+ private String findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwner =
+ "/findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwner";
+ private String findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType =
+ "/findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType";
+ private String findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep =
+ "/findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep";
private String findByClliAndCloudVersion = "/findByClliAndCloudVersion";
private String findServiceByServiceInstanceId = "/findServiceByServiceInstanceId";
private String findPnfResourceCustomizationByModelUuid = "/findPnfResourceCustomizationByModelUuid";
@@ -245,7 +255,7 @@ public class CatalogDbClient {
private final Client<HomingInstance> homingInstanceClient;
private final Client<CloudifyManager> cloudifyManagerClient;
-
+
private final Client<CvnfcCustomization> cvnfcCustomizationClient;
private final Client<ControllerSelectionReference> controllerSelectionReferenceClient;
@@ -253,7 +263,7 @@ public class CatalogDbClient {
private final Client<PnfResource> pnfResourceClient;
private final Client<PnfResourceCustomization> pnfResourceCustomizationClient;
-
+
private final Client<Workflow> workflowClient;
@Value("${mso.catalog.db.spring.endpoint:#{null}}")
@@ -266,49 +276,72 @@ public class CatalogDbClient {
RestTemplate restTemplate;
@PostConstruct
- public void init(){
- findExternalToInternalServiceByServiceName = endpoint + EXTERNAL_SERVICE_TO_INTERNAL_MODEL_MAPPING + SEARCH + findExternalToInternalServiceByServiceName;
- findServiceByModelName = endpoint + SERVICE + SEARCH + findServiceByModelName;
- findServiceRecipeByActionAndServiceModelUUID = endpoint + SERVICE_RECIPE + SEARCH + findServiceRecipeByActionAndServiceModelUUID;
- findServiceByModelUUID = endpoint + SERVICE + SEARCH + findServiceByModelUUID;
+ public void init() {
+ findExternalToInternalServiceByServiceName = endpoint + EXTERNAL_SERVICE_TO_INTERNAL_MODEL_MAPPING + SEARCH
+ + findExternalToInternalServiceByServiceName;
+ findServiceByModelName = endpoint + SERVICE + SEARCH + findServiceByModelName;
+ findServiceRecipeByActionAndServiceModelUUID =
+ endpoint + SERVICE_RECIPE + SEARCH + findServiceRecipeByActionAndServiceModelUUID;
+ findServiceByModelUUID = endpoint + SERVICE + SEARCH + findServiceByModelUUID;
findFirstByModelNameURI = endpoint + SERVICE + SEARCH + findFirstByModelNameURI;
- findFirstByModelVersionAndModelInvariantUUIDURI = endpoint + SERVICE + SEARCH + findFirstByModelVersionAndModelInvariantUUIDURI;
+ findFirstByModelVersionAndModelInvariantUUIDURI =
+ endpoint + SERVICE + SEARCH + findFirstByModelVersionAndModelInvariantUUIDURI;
findByModelInvariantUUIDURI = endpoint + SERVICE + SEARCH + findByModelInvariantUUIDURI;
- findFirstByServiceModelUUIDAndActionURI = endpoint + SERVICE_RECIPE + SEARCH + findFirstByServiceModelUUIDAndActionURI;
+ findFirstByServiceModelUUIDAndActionURI =
+ endpoint + SERVICE_RECIPE + SEARCH + findFirstByServiceModelUUIDAndActionURI;
findFirstByModelNameAndAction = endpoint + NETWORK_RECIPE + SEARCH + findFirstByModelNameAndAction;
- findFirstResourceByModelInvariantUUIDAndModelVersion = endpoint + VNF_RESOURCE + SEARCH + findFirstResourceByModelInvariantUUIDAndModelVersion;
- findByModelInstanceNameAndVnfResources = endpoint + VNF_RESOURCE_CUSTOMIZATION + SEARCH + findByModelInstanceNameAndVnfResources;
+ findFirstResourceByModelInvariantUUIDAndModelVersion =
+ endpoint + VNF_RESOURCE + SEARCH + findFirstResourceByModelInvariantUUIDAndModelVersion;
+ findByModelInstanceNameAndVnfResources =
+ endpoint + VNF_RESOURCE_CUSTOMIZATION + SEARCH + findByModelInstanceNameAndVnfResources;
findFirstVnfRecipeByNfRoleAndAction = endpoint + VNF_RECIPE + SEARCH + findFirstVnfRecipeByNfRoleAndAction;
- findByModelCustomizationUUIDAndVfModuleModelUUID = endpoint + VFMODULE_CUSTOMIZATION + SEARCH + findByModelCustomizationUUIDAndVfModuleModelUUID;
- findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction = endpoint + VNF_COMPONENTS_RECIPE + SEARCH + findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction;
- findFirstVnfComponentsRecipeByVnfComponentTypeAndAction = endpoint + VNF_COMPONENTS_RECIPE + SEARCH + findFirstVnfComponentsRecipeByVnfComponentTypeAndAction;
- findVfModuleByModelInvariantUUIDOrderByModelVersionDesc = endpoint + VFMODULE + SEARCH +findVfModuleByModelInvariantUUIDOrderByModelVersionDesc;
- findFirstVfModuleByModelInvariantUUIDAndModelVersion = endpoint + VFMODULE + SEARCH + findFirstVfModuleByModelInvariantUUIDAndModelVersion;
+ findByModelCustomizationUUIDAndVfModuleModelUUID =
+ endpoint + VFMODULE_CUSTOMIZATION + SEARCH + findByModelCustomizationUUIDAndVfModuleModelUUID;
+ findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction = endpoint + VNF_COMPONENTS_RECIPE
+ + SEARCH + findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction;
+ findFirstVnfComponentsRecipeByVnfComponentTypeAndAction =
+ endpoint + VNF_COMPONENTS_RECIPE + SEARCH + findFirstVnfComponentsRecipeByVnfComponentTypeAndAction;
+ findVfModuleByModelInvariantUUIDOrderByModelVersionDesc =
+ endpoint + VFMODULE + SEARCH + findVfModuleByModelInvariantUUIDOrderByModelVersionDesc;
+ findFirstVfModuleByModelInvariantUUIDAndModelVersion =
+ endpoint + VFMODULE + SEARCH + findFirstVfModuleByModelInvariantUUIDAndModelVersion;
findOneByBuildingBlockName = endpoint + BUILDING_BLOCK_DETAIL + SEARCH + findOneByBuildingBlockName;
- findOneByResourceTypeAndOrchestrationStatusAndTargetAction = endpoint + ORCHESTRATION_STATUS_STATE_TRANSITION_DIRECTIVE + SEARCH + findOneByResourceTypeAndOrchestrationStatusAndTargetAction;
+ findOneByResourceTypeAndOrchestrationStatusAndTargetAction =
+ endpoint + ORCHESTRATION_STATUS_STATE_TRANSITION_DIRECTIVE + SEARCH
+ + findOneByResourceTypeAndOrchestrationStatusAndTargetAction;
findByAction = endpoint + ORCHESTRATION_FLOW + SEARCH + findByAction;
- findVnfcInstanceGroupCustomizationByModelCustomizationUUID = endpoint + VNFC_INSTANCE_GROUP_CUSTOMIZATION + SEARCH + findVnfcInstanceGroupCustomizationByModelCustomizationUUID;
- findCollectionResourceInstanceGroupCustomizationByModelCustomizationUUID = endpoint + COLLECTION_RESOURCE_INSTANCE_GROUP_CUSTOMIZATION + SEARCH + findCollectionResourceInstanceGroupCustomizationByModelCustomizationUUID;
- findOneByActionAndRequestScopeAndIsAlacarte = endpoint + NORTHBOUND_REQUEST_REF_LOOKUP + SEARCH + findOneByActionAndRequestScopeAndIsAlacarte;
- findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwner = endpoint + NORTHBOUND_REQUEST_REF_LOOKUP + SEARCH + findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwner;
- findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType = endpoint + NORTHBOUND_REQUEST_REF_LOOKUP + SEARCH + findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType;
- findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep = endpoint + RAINY_DAY_HANDLER_MACRO + SEARCH + findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep;
+ findVnfcInstanceGroupCustomizationByModelCustomizationUUID = endpoint + VNFC_INSTANCE_GROUP_CUSTOMIZATION
+ + SEARCH + findVnfcInstanceGroupCustomizationByModelCustomizationUUID;
+ findCollectionResourceInstanceGroupCustomizationByModelCustomizationUUID =
+ endpoint + COLLECTION_RESOURCE_INSTANCE_GROUP_CUSTOMIZATION + SEARCH
+ + findCollectionResourceInstanceGroupCustomizationByModelCustomizationUUID;
+ findOneByActionAndRequestScopeAndIsAlacarte =
+ endpoint + NORTHBOUND_REQUEST_REF_LOOKUP + SEARCH + findOneByActionAndRequestScopeAndIsAlacarte;
+ findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwner = endpoint + NORTHBOUND_REQUEST_REF_LOOKUP + SEARCH
+ + findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwner;
+ findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType =
+ endpoint + NORTHBOUND_REQUEST_REF_LOOKUP + SEARCH
+ + findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType;
+ findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep = endpoint + RAINY_DAY_HANDLER_MACRO + SEARCH
+ + findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep;
findByClliAndCloudVersion = endpoint + CLOUD_SITE + SEARCH + findByClliAndCloudVersion;
findPnfResourceCustomizationByModelUuid =
- endpoint + PNF_RESOURCE_CUSTOMIZATION + SEARCH + findPnfResourceCustomizationByModelUuid;
-
+ endpoint + PNF_RESOURCE_CUSTOMIZATION + SEARCH + findPnfResourceCustomizationByModelUuid;
+
findWorkflowByArtifactUUID = endpoint + WORKFLOW + SEARCH + findWorkflowByArtifactUUID;
serviceURI = endpoint + SERVICE + URI_SEPARATOR;
vfModuleURI = endpoint + VFMODULE + URI_SEPARATOR;
vnfResourceURI = endpoint + VNF_RESOURCE + URI_SEPARATOR;
vfModuleCustomizationURI = endpoint + VFMODULE_CUSTOMIZATION + URI_SEPARATOR;
- networkCollectionResourceCustomizationURI = endpoint + NETWORK_COLLECTION_RESOURCE_CUSTOMIZATION + URI_SEPARATOR;
+ networkCollectionResourceCustomizationURI =
+ endpoint + NETWORK_COLLECTION_RESOURCE_CUSTOMIZATION + URI_SEPARATOR;
networkResourceCustomizationURI = endpoint + NETWORK_RESOURCE_CUSTOMIZATION + URI_SEPARATOR;
cvnfcResourceCustomizationURI = endpoint + CVNFC_CUSTOMZIATION + URI_SEPARATOR;
vnfResourceCustomizationURI = endpoint + VNF_RESOURCE_CUSTOMIZATION + URI_SEPARATOR;
- collectionNetworkResourceCustomizationURI = endpoint + COLLECTION_NETWORK_RESOURCE_CUSTOMIZATION + URI_SEPARATOR;
+ collectionNetworkResourceCustomizationURI =
+ endpoint + COLLECTION_NETWORK_RESOURCE_CUSTOMIZATION + URI_SEPARATOR;
instanceGroupURI = endpoint + INSTANCE_GROUP + URI_SEPARATOR;
cloudifyManagerURI = endpoint + CLOUDIFY_MANAGER + URI_SEPARATOR;
cloudSiteURI = endpoint + CLOUD_SITE + URI_SEPARATOR;
@@ -320,18 +353,20 @@ public class CatalogDbClient {
}
public CatalogDbClient() {
- ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory());
+ ClientHttpRequestFactory factory =
+ new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory());
- ClientFactory clientFactory = Configuration.builder().setClientHttpRequestFactory(factory).setRestTemplateConfigurer(restTemplate -> {
- restTemplate.getInterceptors().add((new SpringClientFilter()));
+ ClientFactory clientFactory =
+ Configuration.builder().setClientHttpRequestFactory(factory).setRestTemplateConfigurer(restTemplate -> {
+ restTemplate.getInterceptors().add((new SpringClientFilter()));
- restTemplate.getInterceptors().add((request, body, execution) -> {
+ restTemplate.getInterceptors().add((request, body, execution) -> {
- request.getHeaders().add(HttpHeaders.AUTHORIZATION, msoAdaptersAuth);
- request.getHeaders().add(LogConstants.TARGET_ENTITY_HEADER,TARGET_ENTITY);
- return execution.execute(request, body);
- });
- }).build().buildClientFactory();
+ request.getHeaders().add(HttpHeaders.AUTHORIZATION, msoAdaptersAuth);
+ request.getHeaders().add(LogConstants.TARGET_ENTITY_HEADER, TARGET_ENTITY);
+ return execution.execute(request, body);
+ });
+ }).build().buildClientFactory();
serviceClient = clientFactory.create(Service.class);
networkRecipeClient = clientFactory.create(NetworkRecipe.class);
networkResourceCustomizationClient = clientFactory.create(NetworkResourceCustomization.class);
@@ -345,14 +380,16 @@ public class CatalogDbClient {
northBoundRequestClient = clientFactory.create(NorthBoundRequest.class);
rainyDayHandlerStatusClient = clientFactory.create(RainyDayHandlerStatus.class);
buildingBlockDetailClient = clientFactory.create(BuildingBlockDetail.class);
- orchestrationStatusStateTransitionDirectiveClient = clientFactory
- .create(OrchestrationStatusStateTransitionDirective.class);
+ orchestrationStatusStateTransitionDirectiveClient =
+ clientFactory.create(OrchestrationStatusStateTransitionDirective.class);
vnfcInstanceGroupCustomizationClient = clientFactory.create(VnfcInstanceGroupCustomization.class);
- collectionResourceInstanceGroupCustomizationClient = clientFactory
- .create(CollectionResourceInstanceGroupCustomization.class);
+ collectionResourceInstanceGroupCustomizationClient =
+ clientFactory.create(CollectionResourceInstanceGroupCustomization.class);
instanceGroupClient = clientFactory.create(InstanceGroup.class);
- networkCollectionResourceCustomizationClient = clientFactory.create(NetworkCollectionResourceCustomization.class);
- collectionNetworkResourceCustomizationClient = clientFactory.create(CollectionNetworkResourceCustomization.class);
+ networkCollectionResourceCustomizationClient =
+ clientFactory.create(NetworkCollectionResourceCustomization.class);
+ collectionNetworkResourceCustomizationClient =
+ clientFactory.create(CollectionNetworkResourceCustomization.class);
cloudSiteClient = clientFactory.create(CloudSite.class);
homingInstanceClient = clientFactory.create(HomingInstance.class);
cloudifyManagerClient = clientFactory.create(CloudifyManager.class);
@@ -366,18 +403,20 @@ public class CatalogDbClient {
}
public CatalogDbClient(String baseUri, String auth) {
- ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory());
+ ClientHttpRequestFactory factory =
+ new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory());
- ClientFactory clientFactory = Configuration.builder().setBaseUri(baseUri).setClientHttpRequestFactory(factory).setRestTemplateConfigurer(restTemplate -> {
- restTemplate.getInterceptors().add((new SpringClientFilter()));
+ ClientFactory clientFactory = Configuration.builder().setBaseUri(baseUri).setClientHttpRequestFactory(factory)
+ .setRestTemplateConfigurer(restTemplate -> {
+ restTemplate.getInterceptors().add((new SpringClientFilter()));
- restTemplate.getInterceptors().add((request, body, execution) -> {
+ restTemplate.getInterceptors().add((request, body, execution) -> {
- request.getHeaders().add(HttpHeaders.AUTHORIZATION, auth);
- request.getHeaders().add(LogConstants.TARGET_ENTITY_HEADER,TARGET_ENTITY);
- return execution.execute(request, body);
- });
- }).build().buildClientFactory();
+ request.getHeaders().add(HttpHeaders.AUTHORIZATION, auth);
+ request.getHeaders().add(LogConstants.TARGET_ENTITY_HEADER, TARGET_ENTITY);
+ return execution.execute(request, body);
+ });
+ }).build().buildClientFactory();
serviceClient = clientFactory.create(Service.class);
networkRecipeClient = clientFactory.create(NetworkRecipe.class);
networkResourceCustomizationClient = clientFactory.create(NetworkResourceCustomization.class);
@@ -391,14 +430,16 @@ public class CatalogDbClient {
northBoundRequestClient = clientFactory.create(NorthBoundRequest.class);
rainyDayHandlerStatusClient = clientFactory.create(RainyDayHandlerStatus.class);
buildingBlockDetailClient = clientFactory.create(BuildingBlockDetail.class);
- orchestrationStatusStateTransitionDirectiveClient = clientFactory
- .create(OrchestrationStatusStateTransitionDirective.class);
+ orchestrationStatusStateTransitionDirectiveClient =
+ clientFactory.create(OrchestrationStatusStateTransitionDirective.class);
vnfcInstanceGroupCustomizationClient = clientFactory.create(VnfcInstanceGroupCustomization.class);
- collectionResourceInstanceGroupCustomizationClient = clientFactory
- .create(CollectionResourceInstanceGroupCustomization.class);
+ collectionResourceInstanceGroupCustomizationClient =
+ clientFactory.create(CollectionResourceInstanceGroupCustomization.class);
instanceGroupClient = clientFactory.create(InstanceGroup.class);
- networkCollectionResourceCustomizationClient = clientFactory.create(NetworkCollectionResourceCustomization.class);
- collectionNetworkResourceCustomizationClient = clientFactory.create(CollectionNetworkResourceCustomization.class);
+ networkCollectionResourceCustomizationClient =
+ clientFactory.create(NetworkCollectionResourceCustomization.class);
+ collectionNetworkResourceCustomizationClient =
+ clientFactory.create(CollectionNetworkResourceCustomization.class);
cloudSiteClient = clientFactory.create(CloudSite.class);
homingInstanceClient = clientFactory.create(HomingInstance.class);
cloudifyManagerClient = clientFactory.create(CloudifyManager.class);
@@ -411,9 +452,11 @@ public class CatalogDbClient {
workflowClient = clientFactory.create(Workflow.class);
}
- public NetworkCollectionResourceCustomization getNetworkCollectionResourceCustomizationByID(String modelCustomizationUUID) {
+ public NetworkCollectionResourceCustomization getNetworkCollectionResourceCustomizationByID(
+ String modelCustomizationUUID) {
NetworkCollectionResourceCustomization networkCollectionResourceCustomization =
- this.getSingleResource(networkCollectionResourceCustomizationClient, getUri(networkCollectionResourceCustomizationURI + modelCustomizationUUID));
+ this.getSingleResource(networkCollectionResourceCustomizationClient,
+ getUri(networkCollectionResourceCustomizationURI + modelCustomizationUUID));
if (networkCollectionResourceCustomization != null) {
networkCollectionResourceCustomization.setModelCustomizationUUID(modelCustomizationUUID);
}
@@ -421,7 +464,7 @@ public class CatalogDbClient {
}
public Service getServiceByID(String modelUUID) {
- Service service = getSingleResource(serviceClient,getUri(serviceURI + modelUUID));
+ Service service = getSingleResource(serviceClient, getUri(serviceURI + modelUUID));
if (service != null) {
service.setModelUUID(modelUUID);
}
@@ -429,14 +472,14 @@ public class CatalogDbClient {
}
public VfModule getVfModuleByModelUUID(String modelUUID) {
- VfModule vfModule = getSingleResource(vfModuleClient,getUri(vfModuleURI + modelUUID));
+ VfModule vfModule = getSingleResource(vfModuleClient, getUri(vfModuleURI + modelUUID));
if (vfModule != null) {
vfModule.setModelUUID(modelUUID);
}
return vfModule;
}
- public VnfResource getVnfResourceByModelUUID(String modelUUID){
+ public VnfResource getVnfResourceByModelUUID(String modelUUID) {
VnfResource vnfResource = this.getSingleResource(vnfResourceClient, getUri(vnfResourceURI + modelUUID));
if (vnfResource != null) {
@@ -445,17 +488,19 @@ public class CatalogDbClient {
return vnfResource;
}
- //A VNFResource customization UUID is the same object across services, so we can return anyone from the list
+ // A VNFResource customization UUID is the same object across services, so we can return anyone from the list
// In the future the client should query starting at a service model uuid
- public VnfResourceCustomization getVnfResourceCustomizationByModelCustomizationUUID(String modelCustomizationUUID){
- List<VnfResourceCustomization> vnfResourceCustomization = this.getMultipleResources(vnfResourceCustomizationClient,getUri(endpoint + VNF_RESOURCE_CUSTOMIZATION + SEARCH + "/findByModelCustomizationUUID" + "?MODEL_CUSTOMIZATION_UUID="+ modelCustomizationUUID));
- if(vnfResourceCustomization != null && !vnfResourceCustomization.isEmpty()){
+ public VnfResourceCustomization getVnfResourceCustomizationByModelCustomizationUUID(String modelCustomizationUUID) {
+ List<VnfResourceCustomization> vnfResourceCustomization = this.getMultipleResources(
+ vnfResourceCustomizationClient, getUri(endpoint + VNF_RESOURCE_CUSTOMIZATION + SEARCH
+ + "/findByModelCustomizationUUID" + "?MODEL_CUSTOMIZATION_UUID=" + modelCustomizationUUID));
+ if (vnfResourceCustomization != null && !vnfResourceCustomization.isEmpty()) {
return vnfResourceCustomization.get(0);
- }
- else{
+ } else {
return null;
}
}
+
public PnfResource getPnfResourceByModelUUID(String modelUUID) {
PnfResource PnfResource = this.getSingleResource(pnfResourceClient, getUri(pnfResourceURI + modelUUID));
if (PnfResource != null) {
@@ -466,7 +511,7 @@ public class CatalogDbClient {
public PnfResourceCustomization getPnfResourceCustomizationByModelCustomizationUUID(String modelCustomizationUUID) {
PnfResourceCustomization pnfResourceCustomization = getSingleResource(pnfResourceCustomizationClient,
- getUri(pnfResourceCustomizationURI + modelCustomizationUUID));
+ getUri(pnfResourceCustomizationURI + modelCustomizationUUID));
if (pnfResourceCustomization != null) {
pnfResourceCustomization.setModelCustomizationUUID(modelCustomizationUUID);
}
@@ -474,15 +519,17 @@ public class CatalogDbClient {
}
public List<PnfResourceCustomization> getPnfResourceCustomizationByModelUuid(String modelUuid) {
- return this.getMultipleResources(pnfResourceCustomizationClient, getUri(
- UriBuilder.fromUri(findPnfResourceCustomizationByModelUuid).queryParam("SERVICE_MODEL_UUID", modelUuid)
- .build().toString()));
+ return this.getMultipleResources(pnfResourceCustomizationClient,
+ getUri(UriBuilder.fromUri(findPnfResourceCustomizationByModelUuid)
+ .queryParam("SERVICE_MODEL_UUID", modelUuid).build().toString()));
}
- public CollectionNetworkResourceCustomization getCollectionNetworkResourceCustomizationByID(String modelCustomizationUUID) {
+ public CollectionNetworkResourceCustomization getCollectionNetworkResourceCustomizationByID(
+ String modelCustomizationUUID) {
CollectionNetworkResourceCustomization collectionNetworkResourceCustomization =
- this.getSingleResource(collectionNetworkResourceCustomizationClient,getUri(UriBuilder
- .fromUri(collectionNetworkResourceCustomizationURI + modelCustomizationUUID).build().toString()));
+ this.getSingleResource(collectionNetworkResourceCustomizationClient,
+ getUri(UriBuilder.fromUri(collectionNetworkResourceCustomizationURI + modelCustomizationUUID)
+ .build().toString()));
if (collectionNetworkResourceCustomization != null) {
collectionNetworkResourceCustomization.setModelCustomizationUUID(modelCustomizationUUID);
}
@@ -498,12 +545,16 @@ public class CatalogDbClient {
}
public VfModuleCustomization getVfModuleCustomizationByModelCuztomizationUUID(String modelCustomizationUUID) {
- return this.getSingleResource(vfModuleCustomizationClient, getUri(endpoint + VFMODULE_CUSTOMIZATION + SEARCH + "/findFirstByModelCustomizationUUIDOrderByCreatedDesc" + "?MODEL_CUSTOMIZATION_UUID="+ modelCustomizationUUID));
+ return this.getSingleResource(vfModuleCustomizationClient,
+ getUri(endpoint + VFMODULE_CUSTOMIZATION + SEARCH
+ + "/findFirstByModelCustomizationUUIDOrderByCreatedDesc" + "?MODEL_CUSTOMIZATION_UUID="
+ + modelCustomizationUUID));
}
- public NetworkResourceCustomization getNetworkResourceCustomizationByModelCustomizationUUID(String modelCustomizationUUID){
- NetworkResourceCustomization networkResourceCustomization =
- this.getSingleResource(networkResourceCustomizationClient, getUri(networkResourceCustomizationURI + modelCustomizationUUID));
+ public NetworkResourceCustomization getNetworkResourceCustomizationByModelCustomizationUUID(
+ String modelCustomizationUUID) {
+ NetworkResourceCustomization networkResourceCustomization = this.getSingleResource(
+ networkResourceCustomizationClient, getUri(networkResourceCustomizationURI + modelCustomizationUUID));
if (networkResourceCustomization != null) {
networkResourceCustomization.setModelCustomizationUUID(modelCustomizationUUID);
}
@@ -512,8 +563,9 @@ public class CatalogDbClient {
public BuildingBlockDetail getBuildingBlockDetail(String buildingBlockName) {
- BuildingBlockDetail buildingBlockDetail = getSingleResource(buildingBlockDetailClient, getUri(UriBuilder
- .fromUri(findOneByBuildingBlockName).queryParam(BUILDING_BLOCK_NAME, buildingBlockName).build().toString()));
+ BuildingBlockDetail buildingBlockDetail =
+ getSingleResource(buildingBlockDetailClient, getUri(UriBuilder.fromUri(findOneByBuildingBlockName)
+ .queryParam(BUILDING_BLOCK_NAME, buildingBlockName).build().toString()));
if (buildingBlockDetail != null) {
buildingBlockDetail.setBuildingBlockName(buildingBlockName);
}
@@ -523,228 +575,217 @@ public class CatalogDbClient {
public OrchestrationStatusStateTransitionDirective getOrchestrationStatusStateTransitionDirective(
ResourceType resourceType, OrchestrationStatus orchestrationStatus, OrchestrationAction targetAction) {
- return getSingleResource(orchestrationStatusStateTransitionDirectiveClient, UriBuilder
- .fromUri(findOneByResourceTypeAndOrchestrationStatusAndTargetAction)
- .queryParam(RESOURCE_TYPE, resourceType.name())
- .queryParam(ORCHESTRATION_STATUS, orchestrationStatus.name())
- .queryParam(TARGET_ACTION, targetAction.name()).build());
+ return getSingleResource(orchestrationStatusStateTransitionDirectiveClient,
+ UriBuilder.fromUri(findOneByResourceTypeAndOrchestrationStatusAndTargetAction)
+ .queryParam(RESOURCE_TYPE, resourceType.name())
+ .queryParam(ORCHESTRATION_STATUS, orchestrationStatus.name())
+ .queryParam(TARGET_ACTION, targetAction.name()).build());
}
public List<OrchestrationFlow> getOrchestrationFlowByAction(String action) {
- return this.getMultipleResources(orchestrationClient, UriBuilder
- .fromUri(findByAction).queryParam(ACTION, action).build());
+ return this.getMultipleResources(orchestrationClient,
+ UriBuilder.fromUri(findByAction).queryParam(ACTION, action).build());
}
public List<VnfcInstanceGroupCustomization> getVnfcInstanceGroupsByVnfResourceCust(String modelCustomizationUUID) {
- return this.getMultipleResources(vnfcInstanceGroupCustomizationClient, UriBuilder
- .fromUri(findVnfcInstanceGroupCustomizationByModelCustomizationUUID)
- .queryParam(MODEL_CUSTOMIZATION_UUID, modelCustomizationUUID).build());
+ return this.getMultipleResources(vnfcInstanceGroupCustomizationClient,
+ UriBuilder.fromUri(findVnfcInstanceGroupCustomizationByModelCustomizationUUID)
+ .queryParam(MODEL_CUSTOMIZATION_UUID, modelCustomizationUUID).build());
}
public List<CollectionResourceInstanceGroupCustomization> getCollectionResourceInstanceGroupCustomizationByModelCustUUID(
String modelCustomizationUUID) {
- return this.getMultipleResources(collectionResourceInstanceGroupCustomizationClient, UriBuilder
- .fromUri(findCollectionResourceInstanceGroupCustomizationByModelCustomizationUUID)
- .queryParam(MODEL_CUSTOMIZATION_UUID, modelCustomizationUUID).build());
+ return this.getMultipleResources(collectionResourceInstanceGroupCustomizationClient,
+ UriBuilder.fromUri(findCollectionResourceInstanceGroupCustomizationByModelCustomizationUUID)
+ .queryParam(MODEL_CUSTOMIZATION_UUID, modelCustomizationUUID).build());
}
- public VfModuleCustomization getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(String modelCustomizationUUID, String vfModuleModelUUID) {
- return this.getSingleResource(vfModuleCustomizationClient, getUri(UriBuilder
- .fromUri(findByModelCustomizationUUIDAndVfModuleModelUUID)
- .queryParam("MODEL_CUSTOMIZATION_UUID",modelCustomizationUUID)
- .queryParam("MODEL_UUID",vfModuleModelUUID).build().toString()));
+ public VfModuleCustomization getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
+ String modelCustomizationUUID, String vfModuleModelUUID) {
+ return this.getSingleResource(vfModuleCustomizationClient,
+ getUri(UriBuilder.fromUri(findByModelCustomizationUUIDAndVfModuleModelUUID)
+ .queryParam("MODEL_CUSTOMIZATION_UUID", modelCustomizationUUID)
+ .queryParam("MODEL_UUID", vfModuleModelUUID).build().toString()));
}
public NorthBoundRequest getNorthBoundRequestByActionAndIsALaCarteAndRequestScope(String requestAction,
String resourceName, boolean aLaCarte) {
- return this.getSingleResource(northBoundRequestClient, UriBuilder
- .fromUri(findOneByActionAndRequestScopeAndIsAlacarte)
- .queryParam(ACTION, requestAction).queryParam(REQUEST_SCOPE, resourceName)
- .queryParam(IS_ALACARTE, aLaCarte).build());
+ return this.getSingleResource(northBoundRequestClient,
+ UriBuilder.fromUri(findOneByActionAndRequestScopeAndIsAlacarte).queryParam(ACTION, requestAction)
+ .queryParam(REQUEST_SCOPE, resourceName).queryParam(IS_ALACARTE, aLaCarte).build());
}
-
+
public NorthBoundRequest getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(String requestAction,
String resourceName, boolean aLaCarte, String cloudOwner) {
- return this.getSingleResource(northBoundRequestClient, getUri(UriBuilder
- .fromUri(findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType)
- .queryParam(ACTION, requestAction).queryParam(REQUEST_SCOPE, resourceName)
- .queryParam(IS_ALACARTE, aLaCarte)
- .queryParam(CLOUD_OWNER, cloudOwner)
- .queryParam(SERVICE_TYPE, ASTERISK).build().toString()));
- }
-
- public NorthBoundRequest getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwnerAndServiceType(String requestAction,
- String resourceName, boolean aLaCarte, String cloudOwner, String serviceType) {
- return this.getSingleResource(northBoundRequestClient, getUri(UriBuilder
- .fromUri(findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType)
- .queryParam(ACTION, requestAction).queryParam(REQUEST_SCOPE, resourceName)
- .queryParam(IS_ALACARTE, aLaCarte)
- .queryParam(CLOUD_OWNER, cloudOwner)
- .queryParam(SERVICE_TYPE, serviceType).build().toString()));
+ return this.getSingleResource(northBoundRequestClient,
+ getUri(UriBuilder.fromUri(findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType)
+ .queryParam(ACTION, requestAction).queryParam(REQUEST_SCOPE, resourceName)
+ .queryParam(IS_ALACARTE, aLaCarte).queryParam(CLOUD_OWNER, cloudOwner)
+ .queryParam(SERVICE_TYPE, ASTERISK).build().toString()));
+ }
+
+ public NorthBoundRequest getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwnerAndServiceType(
+ String requestAction, String resourceName, boolean aLaCarte, String cloudOwner, String serviceType) {
+ return this.getSingleResource(northBoundRequestClient,
+ getUri(UriBuilder.fromUri(findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType)
+ .queryParam(ACTION, requestAction).queryParam(REQUEST_SCOPE, resourceName)
+ .queryParam(IS_ALACARTE, aLaCarte).queryParam(CLOUD_OWNER, cloudOwner)
+ .queryParam(SERVICE_TYPE, serviceType).build().toString()));
}
public RainyDayHandlerStatus getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(
String flowName, String serviceType, String vnfType, String errorCode, String workStep) {
- return this.getSingleResource(rainyDayHandlerStatusClient, getUri(UriBuilder
- .fromUri(findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep)
- .queryParam(FLOW_NAME, flowName).queryParam(SERVICE_TYPE, serviceType)
- .queryParam(VNF_TYPE, vnfType).queryParam(ERROR_CODE, errorCode).queryParam(WORK_STEP, workStep)
- .build().toString()));
+ return this.getSingleResource(rainyDayHandlerStatusClient,
+ getUri(UriBuilder.fromUri(findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep)
+ .queryParam(FLOW_NAME, flowName).queryParam(SERVICE_TYPE, serviceType)
+ .queryParam(VNF_TYPE, vnfType).queryParam(ERROR_CODE, errorCode).queryParam(WORK_STEP, workStep)
+ .build().toString()));
}
- public ServiceRecipe getFirstByServiceModelUUIDAndAction(String modelUUID, String action){
- return this.getSingleResource(serviceRecipeClient, getUri(UriBuilder
- .fromUri(findFirstByServiceModelUUIDAndActionURI)
- .queryParam(SERVICE_MODEL_UUID,modelUUID)
- .queryParam(ACTION,action).build().toString()));
+ public ServiceRecipe getFirstByServiceModelUUIDAndAction(String modelUUID, String action) {
+ return this.getSingleResource(serviceRecipeClient,
+ getUri(UriBuilder.fromUri(findFirstByServiceModelUUIDAndActionURI)
+ .queryParam(SERVICE_MODEL_UUID, modelUUID).queryParam(ACTION, action).build().toString()));
}
- public NetworkRecipe getFirstNetworkRecipeByModelNameAndAction(String modelName, String action){
- return this.getSingleResource(networkRecipeClient, UriBuilder
- .fromUri(findFirstByModelNameAndAction)
- .queryParam(MODEL_NAME,modelName)
- .queryParam(ACTION,action).build());
+ public NetworkRecipe getFirstNetworkRecipeByModelNameAndAction(String modelName, String action) {
+ return this.getSingleResource(networkRecipeClient, UriBuilder.fromUri(findFirstByModelNameAndAction)
+ .queryParam(MODEL_NAME, modelName).queryParam(ACTION, action).build());
}
-
- public ControllerSelectionReference getControllerSelectionReferenceByVnfTypeAndActionCategory(String vnfType, String actionCategory) {
- return this.getSingleResource(controllerSelectionReferenceClient, UriBuilder
- .fromUri(endpoint + "/controllerSelectionReference/search/findControllerSelectionReferenceByVnfTypeAndActionCategory")
- .queryParam("VNF_TYPE", vnfType).queryParam("ACTION_CATEGORY", actionCategory).build());
+
+ public ControllerSelectionReference getControllerSelectionReferenceByVnfTypeAndActionCategory(String vnfType,
+ String actionCategory) {
+ return this.getSingleResource(controllerSelectionReferenceClient, UriBuilder.fromUri(endpoint
+ + "/controllerSelectionReference/search/findControllerSelectionReferenceByVnfTypeAndActionCategory")
+ .queryParam("VNF_TYPE", vnfType).queryParam("ACTION_CATEGORY", actionCategory).build());
}
- public Service getFirstByModelNameOrderByModelVersionDesc(String modelName){
- return this.getSingleResource(serviceClient,UriBuilder
- .fromUri(findFirstByModelNameURI)
- .queryParam(MODEL_NAME,modelName).build());
+ public Service getFirstByModelNameOrderByModelVersionDesc(String modelName) {
+ return this.getSingleResource(serviceClient,
+ UriBuilder.fromUri(findFirstByModelNameURI).queryParam(MODEL_NAME, modelName).build());
}
- public ExternalServiceToInternalService findExternalToInternalServiceByServiceName(String serviceName){
- return this.getSingleResource(externalServiceToInternalServiceClient, getUri(UriBuilder
- .fromUri(findExternalToInternalServiceByServiceName)
- .queryParam(SERVICE_NAME,serviceName).build().toString()));
+ public ExternalServiceToInternalService findExternalToInternalServiceByServiceName(String serviceName) {
+ return this.getSingleResource(externalServiceToInternalServiceClient,
+ getUri(UriBuilder.fromUri(findExternalToInternalServiceByServiceName)
+ .queryParam(SERVICE_NAME, serviceName).build().toString()));
}
- public ServiceRecipe findServiceRecipeByActionAndServiceModelUUID(String action,String modelUUID){
- return this.getSingleResource(serviceRecipeClient, getUri(UriBuilder
- .fromUri(findServiceRecipeByActionAndServiceModelUUID)
- .queryParam(ACTION,action)
- .queryParam(SERVICE_MODEL_UUID,modelUUID).build().toString()));
+ public ServiceRecipe findServiceRecipeByActionAndServiceModelUUID(String action, String modelUUID) {
+ return this.getSingleResource(serviceRecipeClient,
+ getUri(UriBuilder.fromUri(findServiceRecipeByActionAndServiceModelUUID).queryParam(ACTION, action)
+ .queryParam(SERVICE_MODEL_UUID, modelUUID).build().toString()));
}
- public Service getServiceByModelName(String modelName){
- return this.getSingleResource(serviceClient,getUri(UriBuilder
- .fromUri(findServiceByModelName)
- .queryParam(MODEL_NAME,modelName).build().toString()));
+ public Service getServiceByModelName(String modelName) {
+ return this.getSingleResource(serviceClient, getUri(
+ UriBuilder.fromUri(findServiceByModelName).queryParam(MODEL_NAME, modelName).build().toString()));
}
- public Service getServiceByModelUUID(String modelModelUUID){
- return this.getSingleResource(serviceClient,getUri(UriBuilder
- .fromUri(findServiceByModelUUID)
- .queryParam(MODEL_UUID,modelModelUUID).build().toString()));
+ public Service getServiceByModelUUID(String modelModelUUID) {
+ return this.getSingleResource(serviceClient, getUri(
+ UriBuilder.fromUri(findServiceByModelUUID).queryParam(MODEL_UUID, modelModelUUID).build().toString()));
}
- public VnfResource getFirstVnfResourceByModelInvariantUUIDAndModelVersion(String modelInvariantUUID, String modelVersion){
- return this.getSingleResource(vnfResourceClient, getUri(UriBuilder
- .fromUri(findFirstResourceByModelInvariantUUIDAndModelVersion)
- .queryParam(MODEL_INVARIANT_UUID,modelInvariantUUID)
- .queryParam(MODEL_VERSION,modelVersion).build().toString()));
+ public VnfResource getFirstVnfResourceByModelInvariantUUIDAndModelVersion(String modelInvariantUUID,
+ String modelVersion) {
+ return this.getSingleResource(vnfResourceClient,
+ getUri(UriBuilder.fromUri(findFirstResourceByModelInvariantUUIDAndModelVersion)
+ .queryParam(MODEL_INVARIANT_UUID, modelInvariantUUID).queryParam(MODEL_VERSION, modelVersion)
+ .build().toString()));
}
- public VnfResourceCustomization getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources(String modelInstanceName, VnfResource vnfResource){
- return this.getSingleResource(vnfResourceCustomizationClient, getUri(UriBuilder
- .fromUri(findByModelInstanceNameAndVnfResources)
- .queryParam("MODEL_INSTANCE_NAME",modelInstanceName)
- .queryParam("VNF_RESOURCE_MODEL_UUID",vnfResource.getModelUUID()).build().toString()));
+ public VnfResourceCustomization getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources(
+ String modelInstanceName, VnfResource vnfResource) {
+ return this.getSingleResource(vnfResourceCustomizationClient,
+ getUri(UriBuilder.fromUri(findByModelInstanceNameAndVnfResources)
+ .queryParam("MODEL_INSTANCE_NAME", modelInstanceName)
+ .queryParam("VNF_RESOURCE_MODEL_UUID", vnfResource.getModelUUID()).build().toString()));
}
- public VnfRecipe getFirstVnfRecipeByNfRoleAndAction(String nfRole, String action){
- return this.getSingleResource(vnfRecipeClient,getUri(UriBuilder
- .fromUri(findFirstVnfRecipeByNfRoleAndAction)
- .queryParam(NF_ROLE,nfRole)
- .queryParam(ACTION,action).build().toString()));
+ public VnfRecipe getFirstVnfRecipeByNfRoleAndAction(String nfRole, String action) {
+ return this.getSingleResource(vnfRecipeClient, getUri(UriBuilder.fromUri(findFirstVnfRecipeByNfRoleAndAction)
+ .queryParam(NF_ROLE, nfRole).queryParam(ACTION, action).build().toString()));
}
- public VnfComponentsRecipe getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(String vfModuleModelUUID, String vnfComponentType, String action){
- return this.getSingleResource(vnfComponentsRecipeClient,getUri(UriBuilder
- .fromUri(findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction)
- .queryParam(VF_MODULE_MODEL_UUID,vfModuleModelUUID)
- .queryParam(VNF_COMPONENT_TYPE,vnfComponentType)
- .queryParam(ACTION,action).build().toString()));
+ public VnfComponentsRecipe getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+ String vfModuleModelUUID, String vnfComponentType, String action) {
+ return this.getSingleResource(vnfComponentsRecipeClient,
+ getUri(UriBuilder.fromUri(findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction)
+ .queryParam(VF_MODULE_MODEL_UUID, vfModuleModelUUID)
+ .queryParam(VNF_COMPONENT_TYPE, vnfComponentType).queryParam(ACTION, action).build()
+ .toString()));
}
- public VnfComponentsRecipe getFirstVnfComponentsRecipeByVnfComponentTypeAndAction(String vnfComponentType, String action) {
- return this.getSingleResource(vnfComponentsRecipeClient,getUri(UriBuilder
- .fromUri(findFirstVnfComponentsRecipeByVnfComponentTypeAndAction)
- .queryParam(VNF_COMPONENT_TYPE,vnfComponentType)
- .queryParam(ACTION,action).build().toString()));
+ public VnfComponentsRecipe getFirstVnfComponentsRecipeByVnfComponentTypeAndAction(String vnfComponentType,
+ String action) {
+ return this.getSingleResource(vnfComponentsRecipeClient,
+ getUri(UriBuilder.fromUri(findFirstVnfComponentsRecipeByVnfComponentTypeAndAction)
+ .queryParam(VNF_COMPONENT_TYPE, vnfComponentType).queryParam(ACTION, action).build()
+ .toString()));
}
- protected URI getUri(String template){
+
+ protected URI getUri(String template) {
return URI.create(template);
}
public CloudifyManager getCloudifyManager(String id) {
- return this.getSingleResource(cloudifyManagerClient,getUri(cloudifyManagerURI + id));
+ return this.getSingleResource(cloudifyManagerClient, getUri(cloudifyManagerURI + id));
}
- public CloudSite getCloudSite(String id){
- return this.getSingleResource(cloudSiteClient,
- getUri(cloudSiteURI + id));
+ public CloudSite getCloudSite(String id) {
+ return this.getSingleResource(cloudSiteClient, getUri(cloudSiteURI + id));
}
- public CloudSite getCloudSite(String id, String uri){
- return this.getSingleResource(cloudSiteClient,
- getUri(uri + id));
+ public CloudSite getCloudSite(String id, String uri) {
+ return this.getSingleResource(cloudSiteClient, getUri(uri + id));
}
- public void postCloudSite(CloudSite cloudSite){
+ public void postCloudSite(CloudSite cloudSite) {
this.postSingleResource(cloudSiteClient, cloudSite);
}
- public CloudSite getCloudSiteByClliAndAicVersion (String clli, String cloudVersion){
- return this.getSingleResource(cloudSiteClient, getUri(UriBuilder
- .fromUri(findByClliAndCloudVersion)
- .queryParam(CLLI,clli).queryParam(CLOUD_VERSION,cloudVersion).build().toString()));
+ public CloudSite getCloudSiteByClliAndAicVersion(String clli, String cloudVersion) {
+ return this.getSingleResource(cloudSiteClient, getUri(UriBuilder.fromUri(findByClliAndCloudVersion)
+ .queryParam(CLLI, clli).queryParam(CLOUD_VERSION, cloudVersion).build().toString()));
}
- public HomingInstance getHomingInstance (String serviceInstanceId){
- return this.getSingleResource(homingInstanceClient,
- getUri(homingInstanceURI + serviceInstanceId));
+ public HomingInstance getHomingInstance(String serviceInstanceId) {
+ return this.getSingleResource(homingInstanceClient, getUri(homingInstanceURI + serviceInstanceId));
}
- public HomingInstance getHomingInstance (String serviceInstanceId, String uri){
- return this.getSingleResource(homingInstanceClient,
- getUri(uri + serviceInstanceId));
+ public HomingInstance getHomingInstance(String serviceInstanceId, String uri) {
+ return this.getSingleResource(homingInstanceClient, getUri(uri + serviceInstanceId));
}
- public void postHomingInstance(HomingInstance homingInstance){
+ public void postHomingInstance(HomingInstance homingInstance) {
this.postSingleResource(homingInstanceClient, homingInstance);
}
public Service getServiceByModelVersionAndModelInvariantUUID(String modelVersion, String modelInvariantUUID) {
- return this.getSingleResource(serviceClient, getUri(UriBuilder
- .fromUri(findFirstByModelVersionAndModelInvariantUUIDURI)
- .queryParam(MODEL_VERSION, modelVersion)
- .queryParam(MODEL_INVARIANT_UUID, modelInvariantUUID).build().toString()));
+ return this.getSingleResource(serviceClient,
+ getUri(UriBuilder.fromUri(findFirstByModelVersionAndModelInvariantUUIDURI)
+ .queryParam(MODEL_VERSION, modelVersion).queryParam(MODEL_INVARIANT_UUID, modelInvariantUUID)
+ .build().toString()));
}
- public VfModule getVfModuleByModelInvariantUUIDAndModelVersion(String modelInvariantUUID, String modelVersion){
- return this.getSingleResource(vfModuleClient,getUri(UriBuilder
- .fromUri(findFirstVfModuleByModelInvariantUUIDAndModelVersion)
- .queryParam(MODEL_INVARIANT_UUID, modelInvariantUUID)
- .queryParam(MODEL_VERSION, modelVersion).build().toString()));
+ public VfModule getVfModuleByModelInvariantUUIDAndModelVersion(String modelInvariantUUID, String modelVersion) {
+ return this.getSingleResource(vfModuleClient,
+ getUri(UriBuilder.fromUri(findFirstVfModuleByModelInvariantUUIDAndModelVersion)
+ .queryParam(MODEL_INVARIANT_UUID, modelInvariantUUID).queryParam(MODEL_VERSION, modelVersion)
+ .build().toString()));
}
public List<Service> getServiceByModelInvariantUUIDOrderByModelVersionDesc(String modelInvariantUUID) {
- return this.getMultipleResources(serviceClient, getUri(UriBuilder
- .fromUri(findByModelInvariantUUIDURI)
+ return this.getMultipleResources(serviceClient, getUri(UriBuilder.fromUri(findByModelInvariantUUIDURI)
.queryParam(MODEL_INVARIANT_UUID, modelInvariantUUID).build().toString()));
}
public List<VfModule> getVfModuleByModelInvariantUUIDOrderByModelVersionDesc(String modelInvariantUUID) {
- return this.getMultipleResources(vfModuleClient, getUri(UriBuilder
- .fromUri(findVfModuleByModelInvariantUUIDOrderByModelVersionDesc)
- .queryParam(MODEL_INVARIANT_UUID, modelInvariantUUID).build().toString()));
+ return this.getMultipleResources(vfModuleClient,
+ getUri(UriBuilder.fromUri(findVfModuleByModelInvariantUUIDOrderByModelVersionDesc)
+ .queryParam(MODEL_INVARIANT_UUID, modelInvariantUUID).build().toString()));
}
private <T> T getSingleResource(Client<T> client, URI uri) {
@@ -759,64 +800,76 @@ public class CatalogDbClient {
return list;
}
- private <T> URI postSingleResource(Client<T> client, T type){
+ private <T> URI postSingleResource(Client<T> client, T type) {
return client.post(type);
}
-
+
public List<CvnfcCustomization> getCvnfcCustomization(String serviceModelUUID, String vnfCustomizationUUID,
- String vfModuleCustomizationUUID) {
+ String vfModuleCustomizationUUID) {
Service service = this.getServiceByID(serviceModelUUID);
- VnfResourceCustomization vnfResourceCust = findVnfResourceCustomizationInList(vnfCustomizationUUID, service.getVnfCustomizations());
- VfModuleCustomization vfModuleCust = findVfModuleCustomizationInList(vfModuleCustomizationUUID , vnfResourceCust.getVfModuleCustomizations());
+ VnfResourceCustomization vnfResourceCust =
+ findVnfResourceCustomizationInList(vnfCustomizationUUID, service.getVnfCustomizations());
+ VfModuleCustomization vfModuleCust =
+ findVfModuleCustomizationInList(vfModuleCustomizationUUID, vnfResourceCust.getVfModuleCustomizations());
return vfModuleCust.getCvnfcCustomization().stream().collect(Collectors.toList());
}
-
- private VnfResourceCustomization findVnfResourceCustomizationInList(String vnfCustomizationUUID , List<VnfResourceCustomization> vnfResourceCusts){
+
+ private VnfResourceCustomization findVnfResourceCustomizationInList(String vnfCustomizationUUID,
+ List<VnfResourceCustomization> vnfResourceCusts) {
List<VnfResourceCustomization> filtered = vnfResourceCusts.stream()
.filter(vnfCustRes -> vnfCustomizationUUID.equals(vnfCustRes.getModelCustomizationUUID()))
.collect(Collectors.toList());
- if(filtered != null && !filtered.isEmpty() && filtered.size() == 1){
+ if (filtered != null && !filtered.isEmpty() && filtered.size() == 1) {
return filtered.get(0);
- }else
- throw new EntityNotFoundException("Unable to find VnfResourceCustomization ModelCustomizationUUID:" + vnfCustomizationUUID);
+ } else
+ throw new EntityNotFoundException(
+ "Unable to find VnfResourceCustomization ModelCustomizationUUID:" + vnfCustomizationUUID);
}
-
- private VfModuleCustomization findVfModuleCustomizationInList(String vfModuleCustomizationUUID , List<VfModuleCustomization> vfModuleList){
+
+ private VfModuleCustomization findVfModuleCustomizationInList(String vfModuleCustomizationUUID,
+ List<VfModuleCustomization> vfModuleList) {
List<VfModuleCustomization> filtered = vfModuleList.stream()
.filter(vfModuleCust -> vfModuleCustomizationUUID.equals(vfModuleCust.getModelCustomizationUUID()))
.collect(Collectors.toList());
- if(filtered != null && !filtered.isEmpty() && filtered.size() == 1){
+ if (filtered != null && !filtered.isEmpty() && filtered.size() == 1) {
return filtered.get(0);
- }else
- throw new EntityNotFoundException("Unable to find VfModuleCustomization ModelCustomizationUUID:" + vfModuleCustomizationUUID);
+ } else
+ throw new EntityNotFoundException(
+ "Unable to find VfModuleCustomization ModelCustomizationUUID:" + vfModuleCustomizationUUID);
}
-
- private CvnfcCustomization findCvnfcCustomizationInAList(String cvnfcCustomizationUuid , List<CvnfcCustomization> cvnfcCustomList){
+
+ private CvnfcCustomization findCvnfcCustomizationInAList(String cvnfcCustomizationUuid,
+ List<CvnfcCustomization> cvnfcCustomList) {
List<CvnfcCustomization> filtered = cvnfcCustomList.stream()
.filter(cvnfc -> cvnfcCustomizationUuid.equals(cvnfc.getModelCustomizationUUID()))
.collect(Collectors.toList());
- if(filtered != null && !filtered.isEmpty() && filtered.size() == 1){
+ if (filtered != null && !filtered.isEmpty() && filtered.size() == 1) {
logger.debug("Found CvnfcCustomization: {}", filtered.get(0));
return filtered.get(0);
- }else
- throw new EntityNotFoundException("Unable to find CvnfcCustomization ModelCustomizationUUID:" + cvnfcCustomizationUuid);
+ } else
+ throw new EntityNotFoundException(
+ "Unable to find CvnfcCustomization ModelCustomizationUUID:" + cvnfcCustomizationUuid);
}
-
+
public CvnfcConfigurationCustomization getCvnfcCustomization(String serviceModelUUID, String vnfCustomizationUuid,
String vfModuleCustomizationUuid, String cvnfcCustomizationUuid) {
- List<CvnfcCustomization> cvnfcCustomization = getCvnfcCustomization(serviceModelUUID,vnfCustomizationUuid,vfModuleCustomizationUuid);
- CvnfcCustomization cvnfc = findCvnfcCustomizationInAList(cvnfcCustomizationUuid,cvnfcCustomization );
- List<CvnfcConfigurationCustomization> fabricConfigs = cvnfc.getCvnfcConfigurationCustomization().stream().filter(cvnfcCustom -> cvnfcCustom.getConfigurationResource().getToscaNodeType().contains("FabricConfiguration")).collect(Collectors.toList());
- if(fabricConfigs != null && !fabricConfigs.isEmpty() && fabricConfigs.size() == 1){
+ List<CvnfcCustomization> cvnfcCustomization =
+ getCvnfcCustomization(serviceModelUUID, vnfCustomizationUuid, vfModuleCustomizationUuid);
+ CvnfcCustomization cvnfc = findCvnfcCustomizationInAList(cvnfcCustomizationUuid, cvnfcCustomization);
+ List<CvnfcConfigurationCustomization> fabricConfigs = cvnfc
+ .getCvnfcConfigurationCustomization().stream().filter(cvnfcCustom -> cvnfcCustom
+ .getConfigurationResource().getToscaNodeType().contains("FabricConfiguration"))
+ .collect(Collectors.toList());
+ if (fabricConfigs != null && !fabricConfigs.isEmpty() && fabricConfigs.size() == 1) {
logger.debug("Found Fabric Configuration: {}", fabricConfigs.get(0));
return fabricConfigs.get(0);
- }else
- throw new EntityNotFoundException("Unable to find CvnfcConfigurationCustomization ModelCustomizationUUID:" + cvnfcCustomizationUuid);
- }
-
- public Workflow findWorkflowByArtifactUUID (String artifactUUID) {
- return this.getSingleResource(workflowClient,getUri(UriBuilder
- .fromUri(findWorkflowByArtifactUUID)
- .queryParam(ARTIFACT_UUID, artifactUUID).build().toString()));
+ } else
+ throw new EntityNotFoundException(
+ "Unable to find CvnfcConfigurationCustomization ModelCustomizationUUID:" + cvnfcCustomizationUuid);
+ }
+
+ public Workflow findWorkflowByArtifactUUID(String artifactUUID) {
+ return this.getSingleResource(workflowClient, getUri(UriBuilder.fromUri(findWorkflowByArtifactUUID)
+ .queryParam(ARTIFACT_UUID, artifactUUID).build().toString()));
}
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/AllottedResourceCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/AllottedResourceCustomizationRepository.java
index 57fe2df182..4c2891be6a 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/AllottedResourceCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/AllottedResourceCustomizationRepository.java
@@ -21,7 +21,6 @@
package org.onap.so.db.catalog.data.repository;
import java.util.List;
-
import org.onap.so.db.catalog.beans.AllottedResourceCustomization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
@@ -30,9 +29,11 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "allottedResourceCustomization", path = "allottedResourceCustomization")
public interface AllottedResourceCustomizationRepository extends JpaRepository<AllottedResourceCustomization, String> {
- @Query(value = "SELECT * FROM ALLOTTED_RESOURCE_CUSTOMIZATION WHERE PROVIDING_SERVICE_MODEL_UUID =?0", nativeQuery = true)
- List<AllottedResourceCustomization> queryByProvidingServiceModelUUID(String providingServiceModelUUID);
+ @Query(value = "SELECT * FROM ALLOTTED_RESOURCE_CUSTOMIZATION WHERE PROVIDING_SERVICE_MODEL_UUID =?0",
+ nativeQuery = true)
+ List<AllottedResourceCustomization> queryByProvidingServiceModelUUID(String providingServiceModelUUID);
+
+ List<AllottedResourceCustomization> findByModelCustomizationUUID(String modelCustomizationUUID);
- List<AllottedResourceCustomization> findByModelCustomizationUUID(String modelCustomizationUUID);
- AllottedResourceCustomization findOneByModelCustomizationUUID(String modelCustomizationUUID);
-} \ No newline at end of file
+ AllottedResourceCustomization findOneByModelCustomizationUUID(String modelCustomizationUUID);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/AllottedResourceRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/AllottedResourceRepository.java
index 9d0ac92449..ba23f351b5 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/AllottedResourceRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/AllottedResourceRepository.java
@@ -26,5 +26,5 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "allottedResource", path = "allottedResource")
public interface AllottedResourceRepository extends JpaRepository<AllottedResource, String> {
- AllottedResource findResourceByModelUUID(String modelUUID);
+ AllottedResource findResourceByModelUUID(String modelUUID);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ArRecipeRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ArRecipeRepository.java
index 22f3ccbead..bdc30b7220 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ArRecipeRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ArRecipeRepository.java
@@ -27,6 +27,7 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "arRecipe", path = "arRecipe")
public interface ArRecipeRepository extends JpaRepository<ArRecipe, String> {
- ArRecipe findByModelNameAndAction(String modelName, String action);
- ArRecipe findByModelNameAndActionAndVersion(String modelName, String action, String version);
+ ArRecipe findByModelNameAndAction(String modelName, String action);
+
+ ArRecipe findByModelNameAndActionAndVersion(String modelName, String action, String version);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/BuildingBlockDetailRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/BuildingBlockDetailRepository.java
index d86377127c..6a1028c868 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/BuildingBlockDetailRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/BuildingBlockDetailRepository.java
@@ -26,5 +26,5 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "buildingBlockDetail", path = "buildingBlockDetail")
public interface BuildingBlockDetailRepository extends JpaRepository<BuildingBlockDetail, String> {
- BuildingBlockDetail findOneByBuildingBlockName(String buildingBlockName);
+ BuildingBlockDetail findOneByBuildingBlockName(String buildingBlockName);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CloudSiteRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CloudSiteRepository.java
index fc5a95769d..0ae0c186b5 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CloudSiteRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CloudSiteRepository.java
@@ -23,12 +23,11 @@ package org.onap.so.db.catalog.data.repository;
import org.onap.so.db.catalog.beans.CloudSite;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-
import javax.transaction.Transactional;
@RepositoryRestResource(collectionResourceRel = "cloudSite", path = "cloudSite")
@Transactional
public interface CloudSiteRepository extends JpaRepository<CloudSite, String> {
- CloudSite findByClliAndCloudVersion(String clli,String cloudVersion);
+ CloudSite findByClliAndCloudVersion(String clli, String cloudVersion);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionNetworkResourceCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionNetworkResourceCustomizationRepository.java
index d27dce161e..5b006ec4ce 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionNetworkResourceCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionNetworkResourceCustomizationRepository.java
@@ -23,10 +23,11 @@ import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-@RepositoryRestResource(collectionResourceRel = "collectionNetworkResourceCustomization", path = "collectionNetworkResourceCustomization")
+@RepositoryRestResource(collectionResourceRel = "collectionNetworkResourceCustomization",
+ path = "collectionNetworkResourceCustomization")
public interface CollectionNetworkResourceCustomizationRepository
- extends JpaRepository<CollectionNetworkResourceCustomization, String> {
-
- CollectionNetworkResourceCustomization findOneByModelCustomizationUUID(String modelCustomizationUUID);
+ extends JpaRepository<CollectionNetworkResourceCustomization, String> {
-} \ No newline at end of file
+ CollectionNetworkResourceCustomization findOneByModelCustomizationUUID(String modelCustomizationUUID);
+
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceCustomizationRepository.java
index 6e33eac556..d86910e318 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceCustomizationRepository.java
@@ -23,7 +23,9 @@ import org.onap.so.db.catalog.beans.CollectionResourceCustomization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-@RepositoryRestResource(collectionResourceRel = "collectionResourceCustomization", path = "collectionResourceCustomization")
-public interface CollectionResourceCustomizationRepository extends JpaRepository<CollectionResourceCustomization, Long> {
- CollectionResourceCustomization findByModelCustomizationUUID(String modelCustomizationUUID);
-} \ No newline at end of file
+@RepositoryRestResource(collectionResourceRel = "collectionResourceCustomization",
+ path = "collectionResourceCustomization")
+public interface CollectionResourceCustomizationRepository
+ extends JpaRepository<CollectionResourceCustomization, Long> {
+ CollectionResourceCustomization findByModelCustomizationUUID(String modelCustomizationUUID);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceInstanceGroupCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceInstanceGroupCustomizationRepository.java
index 32e09bf2af..5336c65bdc 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceInstanceGroupCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceInstanceGroupCustomizationRepository.java
@@ -21,14 +21,14 @@
package org.onap.so.db.catalog.data.repository;
import java.util.List;
-
import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-@RepositoryRestResource(collectionResourceRel = "collectionResourceInstanceGroupCustomization", path = "collectionResourceInstanceGroupCustomization")
+@RepositoryRestResource(collectionResourceRel = "collectionResourceInstanceGroupCustomization",
+ path = "collectionResourceInstanceGroupCustomization")
public interface CollectionResourceInstanceGroupCustomizationRepository
- extends JpaRepository<CollectionResourceInstanceGroupCustomization, String> {
+ extends JpaRepository<CollectionResourceInstanceGroupCustomization, String> {
- List<CollectionResourceInstanceGroupCustomization> findByModelCustomizationUUID(String modelCustomizationlUUID);
+ List<CollectionResourceInstanceGroupCustomization> findByModelCustomizationUUID(String modelCustomizationlUUID);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceRepository.java
index 5d847b87fb..1d8da188ce 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CollectionResourceRepository.java
@@ -25,5 +25,5 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "collectionResource", path = "collectionResource")
public interface CollectionResourceRepository extends JpaRepository<CollectionResource, String> {
- CollectionResource findByModelUUID(String modelUUID);
-} \ No newline at end of file
+ CollectionResource findByModelUUID(String modelUUID);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ConfigurationResourceCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ConfigurationResourceCustomizationRepository.java
index cd96f05c3e..43104986ff 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ConfigurationResourceCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ConfigurationResourceCustomizationRepository.java
@@ -23,8 +23,9 @@ import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-@RepositoryRestResource(collectionResourceRel = "configurationResourceCustomization", path = "configurationResourceCustomization")
+@RepositoryRestResource(collectionResourceRel = "configurationResourceCustomization",
+ path = "configurationResourceCustomization")
public interface ConfigurationResourceCustomizationRepository
- extends JpaRepository<ConfigurationResourceCustomization, String> {
+ extends JpaRepository<ConfigurationResourceCustomization, String> {
-} \ No newline at end of file
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ConfigurationResourceRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ConfigurationResourceRepository.java
index 5a29035cdb..9500b57d4c 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ConfigurationResourceRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ConfigurationResourceRepository.java
@@ -25,5 +25,5 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "configurationResource", path = "configurationResource")
public interface ConfigurationResourceRepository extends JpaRepository<ConfigurationResource, Long> {
- ConfigurationResource findResourceByModelUUID(String modelUUID);
-} \ No newline at end of file
+ ConfigurationResource findResourceByModelUUID(String modelUUID);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ControllerSelectionReferenceRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ControllerSelectionReferenceRepository.java
index ad162b547a..fa6f0ed7c0 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ControllerSelectionReferenceRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ControllerSelectionReferenceRepository.java
@@ -26,10 +26,10 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
- @RepositoryRestResource(collectionResourceRel = "controllerSelectionReference", path = "controllerSelectionReference")
- public interface ControllerSelectionReferenceRepository extends JpaRepository<ControllerSelectionReference, String> {
-
- public ControllerSelectionReference findControllerSelectionReferenceByVnfTypeAndActionCategory(@Param("VNF_TYPE") String vnfType,
- @Param("ACTION_CATEGORY") String actionCategory);
-
- }
+@RepositoryRestResource(collectionResourceRel = "controllerSelectionReference", path = "controllerSelectionReference")
+public interface ControllerSelectionReferenceRepository extends JpaRepository<ControllerSelectionReference, String> {
+
+ public ControllerSelectionReference findControllerSelectionReferenceByVnfTypeAndActionCategory(
+ @Param("VNF_TYPE") String vnfType, @Param("ACTION_CATEGORY") String actionCategory);
+
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CvnfcConfigurationCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CvnfcConfigurationCustomizationRepository.java
index ddb089dede..1e5a07350d 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CvnfcConfigurationCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CvnfcConfigurationCustomizationRepository.java
@@ -24,7 +24,9 @@ import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-@RepositoryRestResource(collectionResourceRel = "cvnfcConfigurationCustomization", path = "cvnfcConfigurationCustomization")
-public interface CvnfcConfigurationCustomizationRepository extends JpaRepository<CvnfcConfigurationCustomization, Integer> {
+@RepositoryRestResource(collectionResourceRel = "cvnfcConfigurationCustomization",
+ path = "cvnfcConfigurationCustomization")
+public interface CvnfcConfigurationCustomizationRepository
+ extends JpaRepository<CvnfcConfigurationCustomization, Integer> {
-} \ No newline at end of file
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepository.java
index 879d7bf82f..927848e5d4 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepository.java
@@ -21,7 +21,6 @@
package org.onap.so.db.catalog.data.repository;
import java.util.List;
-
import org.onap.so.db.catalog.beans.CvnfcCustomization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
@@ -30,7 +29,8 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "cvnfcCustomization", path = "cvnfcCustomization")
public interface CvnfcCustomizationRepository extends JpaRepository<CvnfcCustomization, Integer> {
- CvnfcCustomization findOneByModelCustomizationUUID(String modelCustomizationUuid);
- List<CvnfcCustomization> findByModelCustomizationUUID(String modelCustomizationUUID);
+ CvnfcCustomization findOneByModelCustomizationUUID(String modelCustomizationUuid);
+
+ List<CvnfcCustomization> findByModelCustomizationUUID(String modelCustomizationUUID);
-} \ No newline at end of file
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ExternalServiceToInternalServiceRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ExternalServiceToInternalServiceRepository.java
index 91a912920e..546d1819dc 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ExternalServiceToInternalServiceRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ExternalServiceToInternalServiceRepository.java
@@ -24,9 +24,12 @@ import org.onap.so.db.catalog.beans.ExternalServiceToInternalService;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-@RepositoryRestResource(collectionResourceRel = "externalServiceToInternalService", path = "externalServiceToInternalService")
+@RepositoryRestResource(collectionResourceRel = "externalServiceToInternalService",
+ path = "externalServiceToInternalService")
public interface ExternalServiceToInternalServiceRepository
- extends JpaRepository<ExternalServiceToInternalService, Integer> {
- ExternalServiceToInternalService findByServiceName(String serviceName);
- ExternalServiceToInternalService findByServiceNameAndSubscriptionServiceType(String serviceName , String subscriptionServiceType);
+ extends JpaRepository<ExternalServiceToInternalService, Integer> {
+ ExternalServiceToInternalService findByServiceName(String serviceName);
+
+ ExternalServiceToInternalService findByServiceNameAndSubscriptionServiceType(String serviceName,
+ String subscriptionServiceType);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HeatEnvironmentRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HeatEnvironmentRepository.java
index 85d57e5b85..aa2f5fc039 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HeatEnvironmentRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HeatEnvironmentRepository.java
@@ -26,5 +26,5 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "heatEnvironment", path = "heatEnvironment")
public interface HeatEnvironmentRepository extends JpaRepository<HeatEnvironment, String> {
- HeatEnvironment findByArtifactUuid(String artifactUUID);
+ HeatEnvironment findByArtifactUuid(String artifactUUID);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HeatTemplateRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HeatTemplateRepository.java
index cb79506868..6390d932f8 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HeatTemplateRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HeatTemplateRepository.java
@@ -26,5 +26,5 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "heatTemplate", path = "heatTemplate")
public interface HeatTemplateRepository extends JpaRepository<HeatTemplate, String> {
- HeatTemplate findByArtifactUuid(String artifactUUID);
-} \ No newline at end of file
+ HeatTemplate findByArtifactUuid(String artifactUUID);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HomingInstanceRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HomingInstanceRepository.java
index aea8d3e537..a86990afb0 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HomingInstanceRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HomingInstanceRepository.java
@@ -26,5 +26,5 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "homingInstance", path = "homingInstance")
public interface HomingInstanceRepository extends JpaRepository<HomingInstance, String> {
- HomingInstance findServiceByServiceInstanceId(String serviceInstanceId);
+ HomingInstance findServiceByServiceInstanceId(String serviceInstanceId);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/InstanceGroupRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/InstanceGroupRepository.java
index 5f5d85ae99..7e1f81ab6e 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/InstanceGroupRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/InstanceGroupRepository.java
@@ -25,5 +25,5 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "instanceGroup", path = "instanceGroup")
public interface InstanceGroupRepository extends JpaRepository<InstanceGroup, String> {
- InstanceGroup findByModelUUID(String modelUUID);
-} \ No newline at end of file
+ InstanceGroup findByModelUUID(String modelUUID);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ModelRecipeRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ModelRecipeRepository.java
index c54331b43d..2c4c0b129a 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ModelRecipeRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ModelRecipeRepository.java
@@ -27,7 +27,7 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "modelRecipe", path = "modelRecipe")
public interface ModelRecipeRepository extends JpaRepository<ModelRecipe, Integer> {
-
- ModelRecipe findByModelIdAndAction(String modelId, String action);
-
+
+ ModelRecipe findByModelIdAndAction(String modelId, String action);
+
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ModelRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ModelRepository.java
index e6e2904d43..9867dce4a6 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ModelRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ModelRepository.java
@@ -27,7 +27,7 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "model", path = "model")
public interface ModelRepository extends JpaRepository<Model, Integer> {
-
- Model findByModelVersionIdAndModelType(String modelVersionid, String modelType);
-
+
+ Model findByModelVersionIdAndModelType(String modelVersionid, String modelType);
+
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkCollectionResourceCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkCollectionResourceCustomizationRepository.java
index 1d9bf71396..6073478d13 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkCollectionResourceCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkCollectionResourceCustomizationRepository.java
@@ -23,7 +23,9 @@ import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-@RepositoryRestResource(collectionResourceRel = "networkCollectionResourceCustomization", path = "networkCollectionResourceCustomization")
-public interface NetworkCollectionResourceCustomizationRepository extends JpaRepository<NetworkCollectionResourceCustomization, String> {
- NetworkCollectionResourceCustomization findByModelCustomizationUUID(String modelCustomizationUUID);
-} \ No newline at end of file
+@RepositoryRestResource(collectionResourceRel = "networkCollectionResourceCustomization",
+ path = "networkCollectionResourceCustomization")
+public interface NetworkCollectionResourceCustomizationRepository
+ extends JpaRepository<NetworkCollectionResourceCustomization, String> {
+ NetworkCollectionResourceCustomization findByModelCustomizationUUID(String modelCustomizationUUID);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkInstanceGroupRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkInstanceGroupRepository.java
index e2981ce96e..91c8f365e3 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkInstanceGroupRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkInstanceGroupRepository.java
@@ -25,6 +25,6 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "networkInstanceGroup", path = "networkInstanceGroup")
-public interface NetworkInstanceGroupRepository extends JpaRepository<NetworkInstanceGroup, String> {
- NetworkInstanceGroup findByModelUUID(String modelUUID);
+public interface NetworkInstanceGroupRepository extends JpaRepository<NetworkInstanceGroup, String> {
+ NetworkInstanceGroup findByModelUUID(String modelUUID);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkRecipeRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkRecipeRepository.java
index c74fade8e3..d163e5f87c 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkRecipeRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkRecipeRepository.java
@@ -26,6 +26,7 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "networkRecipe", path = "networkRecipe")
public interface NetworkRecipeRepository extends JpaRepository<NetworkRecipe, String> {
- NetworkRecipe findFirstByModelNameAndAction(String modelName, String action);
- NetworkRecipe findFirstByModelNameAndActionAndVersionStr(String modelName, String action, String versionStr);
-} \ No newline at end of file
+ NetworkRecipe findFirstByModelNameAndAction(String modelName, String action);
+
+ NetworkRecipe findFirstByModelNameAndActionAndVersionStr(String modelName, String action, String versionStr);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkResourceCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkResourceCustomizationRepository.java
index 799d98c5e4..76f33995b5 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkResourceCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkResourceCustomizationRepository.java
@@ -21,18 +21,17 @@
package org.onap.so.db.catalog.data.repository;
import java.util.List;
-
import org.onap.so.db.catalog.beans.NetworkResourceCustomization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "networkResourceCustomization", path = "networkResourceCustomization")
public interface NetworkResourceCustomizationRepository extends JpaRepository<NetworkResourceCustomization, String> {
- List<NetworkResourceCustomization> findByModelCustomizationUUID(String modelCustomizationUUID);
+ List<NetworkResourceCustomization> findByModelCustomizationUUID(String modelCustomizationUUID);
- NetworkResourceCustomization findOneByModelCustomizationUUID(String modelCustomizationUUID);
+ NetworkResourceCustomization findOneByModelCustomizationUUID(String modelCustomizationUUID);
- List<NetworkResourceCustomization> findByNetworkType(String networkType);
+ List<NetworkResourceCustomization> findByNetworkType(String networkType);
- NetworkResourceCustomization findOneByNetworkType(String networkType);
-} \ No newline at end of file
+ NetworkResourceCustomization findOneByNetworkType(String networkType);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkResourceRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkResourceRepository.java
index 94c57945d1..eaeb4292fb 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkResourceRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NetworkResourceRepository.java
@@ -28,14 +28,18 @@ import org.springframework.stereotype.Repository;
@Repository
public interface NetworkResourceRepository extends JpaRepository<NetworkResource, String> {
- /**
- * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the sorting
- * @param modelName
- * @return
- */
- @Query(value = "SELECT * FROM network_resource WHERE MODEL_NAME = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;", nativeQuery = true)
- NetworkResource findFirstByModelNameOrderByModelVersionDesc(String modelName);
-
- NetworkResource findResourceByModelUUID(String modelUUID);
- NetworkResource findOneByModelName(String modelName);
+ /**
+ * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the
+ * sorting
+ *
+ * @param modelName
+ * @return
+ */
+ @Query(value = "SELECT * FROM network_resource WHERE MODEL_NAME = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;",
+ nativeQuery = true)
+ NetworkResource findFirstByModelNameOrderByModelVersionDesc(String modelName);
+
+ NetworkResource findResourceByModelUUID(String modelUUID);
+
+ NetworkResource findOneByModelName(String modelName);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NorthBoundRequestRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NorthBoundRequestRepository.java
index 09732c2d8b..2e2228f489 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NorthBoundRequestRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/NorthBoundRequestRepository.java
@@ -26,7 +26,12 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "northbound_request_ref_lookup", path = "northbound_request_ref_lookup")
public interface NorthBoundRequestRepository extends JpaRepository<NorthBoundRequest, Integer> {
- NorthBoundRequest findOneByActionAndRequestScopeAndIsAlacarte(String action, String requestScope, Boolean isALaCarte);
- NorthBoundRequest findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwner(String action, String requestScope, Boolean isALaCarte, String cloudOwner);
- NorthBoundRequest findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType(String action, String requestScope, Boolean isALaCarte, String cloudOwner, String serviceType);
+ NorthBoundRequest findOneByActionAndRequestScopeAndIsAlacarte(String action, String requestScope,
+ Boolean isALaCarte);
+
+ NorthBoundRequest findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwner(String action, String requestScope,
+ Boolean isALaCarte, String cloudOwner);
+
+ NorthBoundRequest findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType(String action,
+ String requestScope, Boolean isALaCarte, String cloudOwner, String serviceType);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/OrchestrationFlowRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/OrchestrationFlowRepository.java
index 12fbc418f7..e56aff7dc6 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/OrchestrationFlowRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/OrchestrationFlowRepository.java
@@ -23,12 +23,11 @@ package org.onap.so.db.catalog.data.repository;
import org.onap.so.db.catalog.beans.macro.OrchestrationFlow;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-
import java.util.List;
@RepositoryRestResource(collectionResourceRel = "orchestrationFlow", path = "orchestrationFlow")
public interface OrchestrationFlowRepository extends JpaRepository<OrchestrationFlow, Integer> {
- List<OrchestrationFlow> findByAction(String action);
+ List<OrchestrationFlow> findByAction(String action);
- OrchestrationFlow findOneByAction(String action);
+ OrchestrationFlow findOneByAction(String action);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/OrchestrationStatusStateTransitionDirectiveRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/OrchestrationStatusStateTransitionDirectiveRepository.java
index e88480a022..ac9e057790 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/OrchestrationStatusStateTransitionDirectiveRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/OrchestrationStatusStateTransitionDirectiveRepository.java
@@ -27,7 +27,10 @@ import org.onap.so.db.catalog.beans.ResourceType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-@RepositoryRestResource(collectionResourceRel = "orchestrationStatusStateTransitionDirective", path = "orchestrationStatusStateTransitionDirective")
-public interface OrchestrationStatusStateTransitionDirectiveRepository extends JpaRepository<OrchestrationStatusStateTransitionDirective, String> {
- OrchestrationStatusStateTransitionDirective findOneByResourceTypeAndOrchestrationStatusAndTargetAction(ResourceType resourceType, OrchestrationStatus orchestrationStatus, OrchestrationAction targetAction);
+@RepositoryRestResource(collectionResourceRel = "orchestrationStatusStateTransitionDirective",
+ path = "orchestrationStatusStateTransitionDirective")
+public interface OrchestrationStatusStateTransitionDirectiveRepository
+ extends JpaRepository<OrchestrationStatusStateTransitionDirective, String> {
+ OrchestrationStatusStateTransitionDirective findOneByResourceTypeAndOrchestrationStatusAndTargetAction(
+ ResourceType resourceType, OrchestrationStatus orchestrationStatus, OrchestrationAction targetAction);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/PnfCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/PnfCustomizationRepository.java
index f64311a561..7b228294e7 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/PnfCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/PnfCustomizationRepository.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.db.catalog.data.repository;
@@ -32,12 +27,14 @@ public interface PnfCustomizationRepository extends JpaRepository<PnfResourceCus
/**
* Used to fetch the @{link PnfResourceCustomization} by the Model UUID.
*
- * This operation is required by {@link org.onap.so.db.catalog.client.CatalogDbClient} to provide PnfResourceCustomization based on model UUID without projection.
+ * This operation is required by {@link org.onap.so.db.catalog.client.CatalogDbClient} to provide
+ * PnfResourceCustomization based on model UUID without projection.
*
* @param serviceModelUuid model UUID
* @return List of PnfResourceCustomization
*/
- @Query(value = "select b.* from pnf_resource_customization_to_service a join pnf_resource_customization b where a.RESOURCE_MODEL_CUSTOMIZATION_UUID = b.MODEL_CUSTOMIZATION_UUID and a.SERVICE_MODEL_UUID = ?1", nativeQuery = true)
+ @Query(value = "select b.* from pnf_resource_customization_to_service a join pnf_resource_customization b where a.RESOURCE_MODEL_CUSTOMIZATION_UUID = b.MODEL_CUSTOMIZATION_UUID and a.SERVICE_MODEL_UUID = ?1",
+ nativeQuery = true)
List<PnfResourceCustomization> findPnfResourceCustomizationByModelUuid(
- @Param("SERVICE_MODEL_UUID") String serviceModelUuid);
-} \ No newline at end of file
+ @Param("SERVICE_MODEL_UUID") String serviceModelUuid);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/PnfResourceRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/PnfResourceRepository.java
index bf8e83bbac..69006e5e7a 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/PnfResourceRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/PnfResourceRepository.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.db.catalog.data.repository;
@@ -26,4 +21,4 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "pnfResource", path = "pnfResource")
public interface PnfResourceRepository extends JpaRepository<PnfResource, String> {
-} \ No newline at end of file
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java
index 5039384845..2c61d91d6b 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java
@@ -26,6 +26,6 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "rainy_day_handler_macro", path = "rainy_day_handler_macro")
public interface RainyDayHandlerStatusRepository extends JpaRepository<RainyDayHandlerStatus, Integer> {
- RainyDayHandlerStatus findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(
- String flowName, String serviceType, String vnfType, String errorCode, String workStep);
+ RainyDayHandlerStatus findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(String flowName,
+ String serviceType, String vnfType, String errorCode, String workStep);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceProxyResourceCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceProxyResourceCustomizationRepository.java
index cb98c8a709..706873b125 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceProxyResourceCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceProxyResourceCustomizationRepository.java
@@ -23,9 +23,10 @@ import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-@RepositoryRestResource(collectionResourceRel = "serviceProxyResourceCustomization", path = "serviceProxyResourceCustomization")
+@RepositoryRestResource(collectionResourceRel = "serviceProxyResourceCustomization",
+ path = "serviceProxyResourceCustomization")
public interface ServiceProxyResourceCustomizationRepository
- extends JpaRepository<ServiceProxyResourceCustomization, String> {
-
- ServiceProxyResourceCustomization findResourceByModelCustomizationUUID(String modelCustomizationUUID);
-} \ No newline at end of file
+ extends JpaRepository<ServiceProxyResourceCustomization, String> {
+
+ ServiceProxyResourceCustomization findResourceByModelCustomizationUUID(String modelCustomizationUUID);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRecipeRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRecipeRepository.java
index 40ab1704fd..898911fd1c 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRecipeRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRecipeRepository.java
@@ -26,9 +26,9 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "serviceRecipe", path = "serviceRecipe")
public interface ServiceRecipeRepository extends JpaRepository<ServiceRecipe, Long> {
- ServiceRecipe findByActionAndServiceModelUUID(String action, String serviceModelUUID);
+ ServiceRecipe findByActionAndServiceModelUUID(String action, String serviceModelUUID);
- ServiceRecipe findByAction(String action);
+ ServiceRecipe findByAction(String action);
- ServiceRecipe findFirstByServiceModelUUIDAndAction(String serviceModelUUID, String action);
-} \ No newline at end of file
+ ServiceRecipe findFirstByServiceModelUUIDAndAction(String serviceModelUUID, String action);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRepository.java
index 2d29a78351..c107192060 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRepository.java
@@ -24,72 +24,89 @@ import org.onap.so.db.catalog.beans.Service;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-
import java.util.List;
@RepositoryRestResource(collectionResourceRel = "service", path = "service")
public interface ServiceRepository extends JpaRepository<Service, String> {
- List<Service> findByModelName(String modelName);
-
- Service findOneByModelName(String modelName);
-
- /**
- * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the sorting
- * @param modelName
- * @return
- */
- @Query(value = "SELECT * FROM service WHERE MODEL_NAME = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;", nativeQuery = true)
- Service findFirstByModelNameOrderByModelVersionDesc(String modelName);
-
- /**
- * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the sorting
- * @param modelName
- * @return
- */
- @Query(value = "SELECT * FROM service WHERE MODEL_NAME = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;", nativeQuery = true)
- Service findByModelNameOrderByModelVersionDesc(String modelName);
-
- Service findOneByModelNameAndModelVersion(String modelName, String modelVersion);
-
- Service findByModelNameAndModelVersion(String modelName, String modelVersion);
-
- Service findByServiceType(String serviceType);
-
- /**
- * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the sorting
- * @param modelUUID
- * @return
- */
- @Query(value = "SELECT * FROM service WHERE MODEL_UUID = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;", nativeQuery = true)
- Service findFirstOneByModelUUIDOrderByModelVersionDesc(String modelUUID);
-
- /**
- * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the sorting
- * @param modelUUID
- * @return
- */
- @Query(value = "SELECT * FROM service WHERE MODEL_UUID = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;", nativeQuery = true)
- Service findOneByModelUUIDOrderByModelVersionDesc(String modelUUID);
-
- Service findFirstByModelVersionAndModelInvariantUUID(String modelVersion, String modelInvariantUUID);
-
- /**
- * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the sorting
- * @param modelInvariantUUID
- * @return
- */
- @Query(value = "SELECT * FROM service WHERE MODEL_INVARIANT_UUID = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;", nativeQuery = true)
- Service findFirstByModelInvariantUUIDOrderByModelVersionDesc(String modelInvariantUUID);
-
- List<Service> findByModelUUID(String modelUUID);
-
- Service findOneByModelUUID(String modelUUID);
-
- /**
- * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the sorting
- * @param modelInvariantUUID
- * @return
- */
- @Query(value = "SELECT * FROM service WHERE MODEL_INVARIANT_UUID = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC;", nativeQuery = true)
- List<Service> findByModelInvariantUUIDOrderByModelVersionDesc(String modelInvariantUUID);
-} \ No newline at end of file
+ List<Service> findByModelName(String modelName);
+
+ Service findOneByModelName(String modelName);
+
+ /**
+ * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the
+ * sorting
+ *
+ * @param modelName
+ * @return
+ */
+ @Query(value = "SELECT * FROM service WHERE MODEL_NAME = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;",
+ nativeQuery = true)
+ Service findFirstByModelNameOrderByModelVersionDesc(String modelName);
+
+ /**
+ * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the
+ * sorting
+ *
+ * @param modelName
+ * @return
+ */
+ @Query(value = "SELECT * FROM service WHERE MODEL_NAME = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;",
+ nativeQuery = true)
+ Service findByModelNameOrderByModelVersionDesc(String modelName);
+
+ Service findOneByModelNameAndModelVersion(String modelName, String modelVersion);
+
+ Service findByModelNameAndModelVersion(String modelName, String modelVersion);
+
+ Service findByServiceType(String serviceType);
+
+ /**
+ * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the
+ * sorting
+ *
+ * @param modelUUID
+ * @return
+ */
+ @Query(value = "SELECT * FROM service WHERE MODEL_UUID = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;",
+ nativeQuery = true)
+ Service findFirstOneByModelUUIDOrderByModelVersionDesc(String modelUUID);
+
+ /**
+ * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the
+ * sorting
+ *
+ * @param modelUUID
+ * @return
+ */
+ @Query(value = "SELECT * FROM service WHERE MODEL_UUID = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;",
+ nativeQuery = true)
+ Service findOneByModelUUIDOrderByModelVersionDesc(String modelUUID);
+
+ Service findFirstByModelVersionAndModelInvariantUUID(String modelVersion, String modelInvariantUUID);
+
+ /**
+ * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the
+ * sorting
+ *
+ * @param modelInvariantUUID
+ * @return
+ */
+ @Query(value = "SELECT * FROM service WHERE MODEL_INVARIANT_UUID = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;",
+ nativeQuery = true)
+ Service findFirstByModelInvariantUUIDOrderByModelVersionDesc(String modelInvariantUUID);
+
+ List<Service> findByModelUUID(String modelUUID);
+
+ Service findOneByModelUUID(String modelUUID);
+
+ /**
+ * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the
+ * sorting
+ *
+ * @param modelInvariantUUID
+ * @return
+ */
+ @Query(value = "SELECT * FROM service WHERE MODEL_INVARIANT_UUID = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC;",
+ nativeQuery = true)
+ List<Service> findByModelInvariantUUIDOrderByModelVersionDesc(String modelInvariantUUID);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/TempNetworkHeatTemplateRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/TempNetworkHeatTemplateRepository.java
index d506c5b585..d9b7399de6 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/TempNetworkHeatTemplateRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/TempNetworkHeatTemplateRepository.java
@@ -27,5 +27,5 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "tempNetworkHeatTemplateLookup", path = "tempNetworkHeatTemplateLookup")
public interface TempNetworkHeatTemplateRepository extends JpaRepository<TempNetworkHeatTemplateLookup, String> {
- TempNetworkHeatTemplateLookup findFirstBynetworkResourceModelName(String networkResourceModelName);
-} \ No newline at end of file
+ TempNetworkHeatTemplateLookup findFirstBynetworkResourceModelName(String networkResourceModelName);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFCInstanceGroupRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFCInstanceGroupRepository.java
index da091827b7..69cabd948d 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFCInstanceGroupRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFCInstanceGroupRepository.java
@@ -25,6 +25,6 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "vfcInstanceGroup", path = "vfcInstanceGroup")
-public interface VFCInstanceGroupRepository extends JpaRepository<VFCInstanceGroup, String> {
- VFCInstanceGroup findByModelUUID(String modelUUID);
+public interface VFCInstanceGroupRepository extends JpaRepository<VFCInstanceGroup, String> {
+ VFCInstanceGroup findByModelUUID(String modelUUID);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFModuleCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFModuleCustomizationRepository.java
index e8fb654f57..8b27c7bf10 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFModuleCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFModuleCustomizationRepository.java
@@ -27,7 +27,10 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "vfModuleCustomization", path = "vfModuleCustomization")
public interface VFModuleCustomizationRepository extends JpaRepository<VfModuleCustomization, Integer> {
- VfModuleCustomization findFirstByModelCustomizationUUIDOrderByCreatedDesc(@Param("MODEL_CUSTOMIZATION_UUID")String modelCustomizationUUID);
+ VfModuleCustomization findFirstByModelCustomizationUUIDOrderByCreatedDesc(
+ @Param("MODEL_CUSTOMIZATION_UUID") String modelCustomizationUUID);
- VfModuleCustomization findFirstByModelCustomizationUUIDAndVfModuleModelUUIDOrderByCreatedDesc(@Param("MODEL_CUSTOMIZATION_UUID")String modelCustomizationUUID, @Param("MODEL_UUID")String vfModuleModelUUID);
-} \ No newline at end of file
+ VfModuleCustomization findFirstByModelCustomizationUUIDAndVfModuleModelUUIDOrderByCreatedDesc(
+ @Param("MODEL_CUSTOMIZATION_UUID") String modelCustomizationUUID,
+ @Param("MODEL_UUID") String vfModuleModelUUID);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFModuleRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFModuleRepository.java
index 56ae11f4cb..c937394a29 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFModuleRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VFModuleRepository.java
@@ -24,34 +24,39 @@ import org.onap.so.db.catalog.beans.VfModule;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-
import java.util.List;
@RepositoryRestResource(collectionResourceRel = "vfModule", path = "vfModule")
public interface VFModuleRepository extends JpaRepository<VfModule, String> {
- VfModule findByModelUUID(String modelUUID);
-
- VfModule findFirstVfModuleByModelInvariantUUIDAndModelVersion(String modelInvariantUUID, String modelVersion);
-
- VfModule findByModelName(String modelName);
-
- /**
- * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the sorting
- * @param modelName
- * @return
- */
- @Query(value = "SELECT * FROM vf_module WHERE MODEL_NAME = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;", nativeQuery = true)
- VfModule findFirstByModelNameOrderByModelVersionDesc(String modelName);
-
- VfModule findFirstByModelInvariantUUIDAndModelUUID(String modelCustomizationUUID, String modelUUID);
-
- VfModule findFirstByModelInvariantUUID(String modelCustomizationUUID);
-
- /**
- * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the sorting
- * @param modelInvariantUUID
- * @return
- */
- @Query(value = "SELECT * FROM vf_module WHERE MODEL_INVARIANT_UUID = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC;", nativeQuery = true)
- List<VfModule> findByModelInvariantUUIDOrderByModelVersionDesc(String modelInvariantUUID);
-} \ No newline at end of file
+ VfModule findByModelUUID(String modelUUID);
+
+ VfModule findFirstVfModuleByModelInvariantUUIDAndModelVersion(String modelInvariantUUID, String modelVersion);
+
+ VfModule findByModelName(String modelName);
+
+ /**
+ * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the
+ * sorting
+ *
+ * @param modelName
+ * @return
+ */
+ @Query(value = "SELECT * FROM vf_module WHERE MODEL_NAME = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC LIMIT 1;",
+ nativeQuery = true)
+ VfModule findFirstByModelNameOrderByModelVersionDesc(String modelName);
+
+ VfModule findFirstByModelInvariantUUIDAndModelUUID(String modelCustomizationUUID, String modelUUID);
+
+ VfModule findFirstByModelInvariantUUID(String modelCustomizationUUID);
+
+ /**
+ * This method will not work for versions greater than 255, as it is utilizing an ip address function to do the
+ * sorting
+ *
+ * @param modelInvariantUUID
+ * @return
+ */
+ @Query(value = "SELECT * FROM vf_module WHERE MODEL_INVARIANT_UUID = ?1 ORDER BY INET_ATON(SUBSTRING_INDEX(CONCAT(MODEL_VERSION,'.0.0.0'),'.',4)) DESC;",
+ nativeQuery = true)
+ List<VfModule> findByModelInvariantUUIDOrderByModelVersionDesc(String modelInvariantUUID);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfComponentRecipeRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfComponentRecipeRepository.java
index 440a675c97..cbca3cd1b7 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfComponentRecipeRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfComponentRecipeRepository.java
@@ -27,13 +27,13 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "vnfComponentsRecipe", path = "vnfComponentsRecipe")
public interface VnfComponentRecipeRepository extends JpaRepository<VnfComponentsRecipe, String> {
- VnfComponentsRecipe findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfTypeAndAction(String vfModuleModelUUID,
- String vnfType, String action);
+ VnfComponentsRecipe findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfTypeAndAction(String vfModuleModelUUID,
+ String vnfType, String action);
- VnfComponentsRecipe findFirstVnfComponentsRecipeByVnfTypeAndAction(String vnfType, String action);
+ VnfComponentsRecipe findFirstVnfComponentsRecipeByVnfTypeAndAction(String vnfType, String action);
- VnfComponentsRecipe findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(String vfModuleModelUUID,
- String vnfComponentType, String action);
+ VnfComponentsRecipe findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+ String vfModuleModelUUID, String vnfComponentType, String action);
- VnfComponentsRecipe findFirstVnfComponentsRecipeByVnfComponentTypeAndAction(String vnfComponentType, String action);
-} \ No newline at end of file
+ VnfComponentsRecipe findFirstVnfComponentsRecipeByVnfComponentTypeAndAction(String vnfComponentType, String action);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfCustomizationRepository.java
index fa8d8c065e..c72fade411 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfCustomizationRepository.java
@@ -29,11 +29,15 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "vnfResourceCustomization", path = "vnfResourceCustomization")
public interface VnfCustomizationRepository extends JpaRepository<VnfResourceCustomization, Integer> {
- List<VnfResourceCustomization> findByModelCustomizationUUID(@Param("MODEL_CUSTOMIZATION_UUID")String modelCustomizationUUID);
+ List<VnfResourceCustomization> findByModelCustomizationUUID(
+ @Param("MODEL_CUSTOMIZATION_UUID") String modelCustomizationUUID);
VnfResourceCustomization findOneByModelCustomizationUUID(String modelCustomizationUuid);
- @Query(value = "SELECT * FROM vnf_resource_customization WHERE MODEL_INSTANCE_NAME = ?1 AND VNF_RESOURCE_MODEL_UUID = ?2 LIMIT 1;", nativeQuery = true)
- VnfResourceCustomization findByModelInstanceNameAndVnfResources(@Param("MODEL_INSTANCE_NAME")String modelInstanceName, @Param("VNF_RESOURCE_MODEL_UUID")String vnfResourceModelUUID);
+ @Query(value = "SELECT * FROM vnf_resource_customization WHERE MODEL_INSTANCE_NAME = ?1 AND VNF_RESOURCE_MODEL_UUID = ?2 LIMIT 1;",
+ nativeQuery = true)
+ VnfResourceCustomization findByModelInstanceNameAndVnfResources(
+ @Param("MODEL_INSTANCE_NAME") String modelInstanceName,
+ @Param("VNF_RESOURCE_MODEL_UUID") String vnfResourceModelUUID);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfRecipeRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfRecipeRepository.java
index b99e2bd4b6..985e6674ea 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfRecipeRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfRecipeRepository.java
@@ -26,9 +26,9 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "vnfRecipe", path = "vnfRecipe")
public interface VnfRecipeRepository extends JpaRepository<VnfRecipe, String> {
- VnfRecipe findVnfRecipeByServiceTypeAndAction(String serviceType, String action);
-
- VnfRecipe findFirstVnfRecipeByNfRoleAndAction(String nfRole, String action);
+ VnfRecipe findVnfRecipeByServiceTypeAndAction(String serviceType, String action);
- VnfRecipe findFirstVnfRecipeByNfRoleAndActionAndVersionStr(String nfRole, String action, String versionStr);
-} \ No newline at end of file
+ VnfRecipe findFirstVnfRecipeByNfRoleAndAction(String nfRole, String action);
+
+ VnfRecipe findFirstVnfRecipeByNfRoleAndActionAndVersionStr(String nfRole, String action, String versionStr);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfResourceRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfResourceRepository.java
index e48f8bb653..965a85f504 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfResourceRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfResourceRepository.java
@@ -27,15 +27,15 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "vnfResource", path = "vnfResource")
public interface VnfResourceRepository extends JpaRepository<VnfResource, String> {
- VnfResource findResourceByModelNameAndModelUUID(String modelName, String modelUUID);
+ VnfResource findResourceByModelNameAndModelUUID(String modelName, String modelUUID);
- VnfResource findByModelName(String modelName);
+ VnfResource findByModelName(String modelName);
- VnfResource findByModelNameAndModelVersion(String modelName, String modelVersion);
+ VnfResource findByModelNameAndModelVersion(String modelName, String modelVersion);
- VnfResource findResourceByModelUUID(String modelUUID);
+ VnfResource findResourceByModelUUID(String modelUUID);
- VnfResource findResourceByModelInvariantUUID(String modelInvariantUUID);
+ VnfResource findResourceByModelInvariantUUID(String modelInvariantUUID);
- VnfResource findFirstResourceByModelInvariantUUIDAndModelVersion(String modelInvariantUUID, String modelVersion);
-} \ No newline at end of file
+ VnfResource findFirstResourceByModelInvariantUUIDAndModelVersion(String modelInvariantUUID, String modelVersion);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfResourceWorkflowRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfResourceWorkflowRepository.java
index d722ab2d6a..9e4a2a303b 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfResourceWorkflowRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfResourceWorkflowRepository.java
@@ -21,14 +21,12 @@
package org.onap.so.db.catalog.data.repository;
import java.util.List;
-
import org.onap.so.db.catalog.beans.VnfResource;
import org.onap.so.db.catalog.beans.VnfResourceWorkflow;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "vnfResourceWorkflow", path = "vnfResourceWorkflow")
-public interface VnfResourceWorkflowRepository
- extends JpaRepository<VnfResourceWorkflow, String> {
- List<VnfResourceWorkflow> findByVnfResourceModelUUID(String vnfResourceModelUUID);
+public interface VnfResourceWorkflowRepository extends JpaRepository<VnfResourceWorkflow, String> {
+ List<VnfResourceWorkflow> findByVnfResourceModelUUID(String vnfResourceModelUUID);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepository.java
index 64840f11f9..1dddd18697 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepository.java
@@ -26,5 +26,5 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "vnfcCustomization", path = "vnfcCustomization")
public interface VnfcCustomizationRepository extends JpaRepository<VnfcCustomization, String> {
- VnfcCustomization findOneByModelCustomizationUUID(String modelCustomizationUuid);
-} \ No newline at end of file
+ VnfcCustomization findOneByModelCustomizationUUID(String modelCustomizationUuid);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfcInstanceGroupCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfcInstanceGroupCustomizationRepository.java
index c18bf006da..0b9d50fa1e 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfcInstanceGroupCustomizationRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfcInstanceGroupCustomizationRepository.java
@@ -21,12 +21,12 @@
package org.onap.so.db.catalog.data.repository;
import java.util.List;
-
import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
-@RepositoryRestResource(collectionResourceRel = "vnfcInstanceGroupCustomization", path = "vnfcInstanceGroupCustomization")
+@RepositoryRestResource(collectionResourceRel = "vnfcInstanceGroupCustomization",
+ path = "vnfcInstanceGroupCustomization")
public interface VnfcInstanceGroupCustomizationRepository
- extends JpaRepository<VnfcInstanceGroupCustomization, String> {
+ extends JpaRepository<VnfcInstanceGroupCustomization, String> {
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java
index f33a5b6ff9..b73896ac5c 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java
@@ -26,5 +26,5 @@ import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "workflow", path = "workflow")
public interface WorkflowRepository extends JpaRepository<Workflow, String> {
- Workflow findByArtifactUUID(String artifactUUID);
-} \ No newline at end of file
+ Workflow findByArtifactUUID(String artifactUUID);
+}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/exceptions/NoEntityFoundException.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/exceptions/NoEntityFoundException.java
index f06d7c9c17..63a5614ea0 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/exceptions/NoEntityFoundException.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/exceptions/NoEntityFoundException.java
@@ -29,7 +29,7 @@ public class NoEntityFoundException extends Exception {
private static final long serialVersionUID = 545820289784366486L;
public NoEntityFoundException(String errorMessage) {
- super(errorMessage);
+ super(errorMessage);
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/rest/beans/ServiceMacroHolder.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/rest/beans/ServiceMacroHolder.java
index fc968a4ef9..f9cbb0d462 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/rest/beans/ServiceMacroHolder.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/rest/beans/ServiceMacroHolder.java
@@ -22,173 +22,186 @@ package org.onap.so.db.catalog.rest.beans;
import java.io.Serializable;
import java.util.ArrayList;
-
import org.onap.so.db.catalog.beans.AllottedResourceCustomization;
import org.onap.so.db.catalog.beans.NetworkResourceCustomization;
import org.onap.so.db.catalog.beans.Service;
import org.onap.so.db.catalog.beans.VnfResource;
import org.onap.so.db.catalog.beans.VnfResourceCustomization;
-
import com.openpojo.business.annotation.BusinessKey;
/*
- * A simple holder for Service and its associated elements:
- * VnfResource, 1-n VfModule, Network TBD
+ * A simple holder for Service and its associated elements: VnfResource, 1-n VfModule, Network TBD
*/
public class ServiceMacroHolder implements Serializable {
-
- private static final long serialVersionUID = 768026109321305392L;
- @BusinessKey
- private Service service;
- private ArrayList<VnfResource> vnfResources;
- private ArrayList<NetworkResourceCustomization> networkResourceCustomizations;
- private ArrayList<AllottedResourceCustomization> allottedResourceCustomizations;
- private ArrayList<VnfResourceCustomization> vnfResourceCustomizations;
-
-
- public ServiceMacroHolder() {
- super();
- this.service = null;
- this.vnfResources = new ArrayList<VnfResource>();
- this.networkResourceCustomizations = new ArrayList<>();
- this.allottedResourceCustomizations = new ArrayList<>();
- this.vnfResourceCustomizations = new ArrayList<>();
- }
- public ServiceMacroHolder(Service service) {
- this();
- this.service = service;
- }
-
- public Service getService() {
- return this.service;
- }
- public void setService(Service service) {
- this.service = service;
- }
-
- public void setVnfResources(ArrayList<VnfResource> vnfResources) {
- this.vnfResources = vnfResources;
- }
- public ArrayList<VnfResource> getVnfResources() {
- return this.vnfResources;
- }
- public void addVnfResource(VnfResource vr) {
- if (vr != null) {
- if (this.vnfResources != null) {
- this.vnfResources.add(vr);
- } else {
- this.vnfResources = new ArrayList<>();
- this.vnfResources.add(vr);
- }
- }
- }
-
- public void setVnfResourceCustomizations(ArrayList<VnfResourceCustomization> vnfResourceCustomizations) {
- this.vnfResourceCustomizations = vnfResourceCustomizations;
- }
- public ArrayList<VnfResourceCustomization> getVnfResourceCustomizations() {
- return this.vnfResourceCustomizations;
- }
- public void addVnfResourceCustomizations(VnfResourceCustomization vrc) {
- if (vrc != null) {
- if (this.vnfResourceCustomizations != null) {
- this.vnfResourceCustomizations.add(vrc);
- } else {
- this.vnfResourceCustomizations = new ArrayList<>();
- this.vnfResourceCustomizations.add(vrc);
- }
- }
- }
-
- public void setNetworkResourceCustomization(ArrayList<NetworkResourceCustomization> networkResourceCustomizations) {
- this.networkResourceCustomizations = networkResourceCustomizations;
- }
- public ArrayList<NetworkResourceCustomization> getNetworkResourceCustomization() {
- return this.networkResourceCustomizations;
- }
- public void addNetworkResourceCustomization(NetworkResourceCustomization nrc) {
- if (this.networkResourceCustomizations != null) {
- this.networkResourceCustomizations.add(nrc);
- } else {
- this.networkResourceCustomizations = new ArrayList<>();
- this.networkResourceCustomizations.add(nrc);
- }
- }
-
- public void setAllottedResourceCustomization(ArrayList<AllottedResourceCustomization> allottedResourceCustomizations) {
- this.allottedResourceCustomizations = allottedResourceCustomizations;
- }
- public ArrayList<AllottedResourceCustomization> getAllottedResourceCustomization() {
- return this.allottedResourceCustomizations;
- }
- public void addAllottedResourceCustomization(AllottedResourceCustomization arc) {
- if (this.allottedResourceCustomizations != null) {
- this.allottedResourceCustomizations.add(arc);
- } else {
- this.allottedResourceCustomizations = new ArrayList<>();
- this.allottedResourceCustomizations.add(arc);
- }
- }
+
+ private static final long serialVersionUID = 768026109321305392L;
+ @BusinessKey
+ private Service service;
+ private ArrayList<VnfResource> vnfResources;
+ private ArrayList<NetworkResourceCustomization> networkResourceCustomizations;
+ private ArrayList<AllottedResourceCustomization> allottedResourceCustomizations;
+ private ArrayList<VnfResourceCustomization> vnfResourceCustomizations;
+
+
+ public ServiceMacroHolder() {
+ super();
+ this.service = null;
+ this.vnfResources = new ArrayList<VnfResource>();
+ this.networkResourceCustomizations = new ArrayList<>();
+ this.allottedResourceCustomizations = new ArrayList<>();
+ this.vnfResourceCustomizations = new ArrayList<>();
+ }
+
+ public ServiceMacroHolder(Service service) {
+ this();
+ this.service = service;
+ }
+
+ public Service getService() {
+ return this.service;
+ }
+
+ public void setService(Service service) {
+ this.service = service;
+ }
+
+ public void setVnfResources(ArrayList<VnfResource> vnfResources) {
+ this.vnfResources = vnfResources;
+ }
+
+ public ArrayList<VnfResource> getVnfResources() {
+ return this.vnfResources;
+ }
+
+ public void addVnfResource(VnfResource vr) {
+ if (vr != null) {
+ if (this.vnfResources != null) {
+ this.vnfResources.add(vr);
+ } else {
+ this.vnfResources = new ArrayList<>();
+ this.vnfResources.add(vr);
+ }
+ }
+ }
+
+ public void setVnfResourceCustomizations(ArrayList<VnfResourceCustomization> vnfResourceCustomizations) {
+ this.vnfResourceCustomizations = vnfResourceCustomizations;
+ }
+
+ public ArrayList<VnfResourceCustomization> getVnfResourceCustomizations() {
+ return this.vnfResourceCustomizations;
+ }
+
+ public void addVnfResourceCustomizations(VnfResourceCustomization vrc) {
+ if (vrc != null) {
+ if (this.vnfResourceCustomizations != null) {
+ this.vnfResourceCustomizations.add(vrc);
+ } else {
+ this.vnfResourceCustomizations = new ArrayList<>();
+ this.vnfResourceCustomizations.add(vrc);
+ }
+ }
+ }
+
+ public void setNetworkResourceCustomization(ArrayList<NetworkResourceCustomization> networkResourceCustomizations) {
+ this.networkResourceCustomizations = networkResourceCustomizations;
+ }
+
+ public ArrayList<NetworkResourceCustomization> getNetworkResourceCustomization() {
+ return this.networkResourceCustomizations;
+ }
+
+ public void addNetworkResourceCustomization(NetworkResourceCustomization nrc) {
+ if (this.networkResourceCustomizations != null) {
+ this.networkResourceCustomizations.add(nrc);
+ } else {
+ this.networkResourceCustomizations = new ArrayList<>();
+ this.networkResourceCustomizations.add(nrc);
+ }
+ }
+
+ public void setAllottedResourceCustomization(
+ ArrayList<AllottedResourceCustomization> allottedResourceCustomizations) {
+ this.allottedResourceCustomizations = allottedResourceCustomizations;
+ }
+
+ public ArrayList<AllottedResourceCustomization> getAllottedResourceCustomization() {
+ return this.allottedResourceCustomizations;
+ }
+
+ public void addAllottedResourceCustomization(AllottedResourceCustomization arc) {
+ if (this.allottedResourceCustomizations != null) {
+ this.allottedResourceCustomizations.add(arc);
+ } else {
+ this.allottedResourceCustomizations = new ArrayList<>();
+ this.allottedResourceCustomizations.add(arc);
+ }
+ }
@Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("ServicePlus: ");
- if (this.service != null) {
- sb.append("service: " + this.service.toString());
- } else {
- sb.append("service: null");
- }
- if (this.vnfResourceCustomizations != null && this.vnfResourceCustomizations.size() > 0) {
- int i=0;
- sb.append("VnfResources: ");
- for (VnfResourceCustomization vrc : this.vnfResourceCustomizations) {
- sb.append(", vnfResourceCustomization[" + i++ + "]:" + vrc.toString());
- }
- } else {
- sb.append("none");
- }
- if (this.vnfResources != null && this.vnfResources.size() > 0) {
- int i=0;
- sb.append("VnfResources: ");
- for (VnfResource vr : this.vnfResources) {
- sb.append(", vnfResource[" + i++ + "]:" + vr.toString());
- }
- } else {
- sb.append("none");
- }
- if (this.networkResourceCustomizations != null && this.networkResourceCustomizations.size() > 0) {
- int i=0;
- sb.append("NetworkResourceCustomizations:");
- for (NetworkResourceCustomization nrc : this.networkResourceCustomizations) {
- sb.append("NRC[" + i++ + "]: " + nrc.toString());
- }
- }
- if (this.allottedResourceCustomizations != null && this.allottedResourceCustomizations.size() > 0) {
- int i=0;
- sb.append("AllottedResourceCustomizations:");
- for (AllottedResourceCustomization arc : this.allottedResourceCustomizations) {
- sb.append("ARC[" + i++ + "]: " + arc.toString());
- }
- }
-
- return sb.toString();
- }
- public ArrayList<NetworkResourceCustomization> getNetworkResourceCustomizations() {
- return networkResourceCustomizations;
- }
- public void setNetworkResourceCustomizations(ArrayList<NetworkResourceCustomization> networkResourceCustomizations) {
- this.networkResourceCustomizations = networkResourceCustomizations;
- }
- public ArrayList<AllottedResourceCustomization> getAllottedResourceCustomizations() {
- return allottedResourceCustomizations;
- }
- public void setAllottedResourceCustomizations(ArrayList<AllottedResourceCustomization> allottedResourceCustomizations) {
- this.allottedResourceCustomizations = allottedResourceCustomizations;
- }
-
-
-
-
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("ServicePlus: ");
+ if (this.service != null) {
+ sb.append("service: " + this.service.toString());
+ } else {
+ sb.append("service: null");
+ }
+ if (this.vnfResourceCustomizations != null && this.vnfResourceCustomizations.size() > 0) {
+ int i = 0;
+ sb.append("VnfResources: ");
+ for (VnfResourceCustomization vrc : this.vnfResourceCustomizations) {
+ sb.append(", vnfResourceCustomization[" + i++ + "]:" + vrc.toString());
+ }
+ } else {
+ sb.append("none");
+ }
+ if (this.vnfResources != null && this.vnfResources.size() > 0) {
+ int i = 0;
+ sb.append("VnfResources: ");
+ for (VnfResource vr : this.vnfResources) {
+ sb.append(", vnfResource[" + i++ + "]:" + vr.toString());
+ }
+ } else {
+ sb.append("none");
+ }
+ if (this.networkResourceCustomizations != null && this.networkResourceCustomizations.size() > 0) {
+ int i = 0;
+ sb.append("NetworkResourceCustomizations:");
+ for (NetworkResourceCustomization nrc : this.networkResourceCustomizations) {
+ sb.append("NRC[" + i++ + "]: " + nrc.toString());
+ }
+ }
+ if (this.allottedResourceCustomizations != null && this.allottedResourceCustomizations.size() > 0) {
+ int i = 0;
+ sb.append("AllottedResourceCustomizations:");
+ for (AllottedResourceCustomization arc : this.allottedResourceCustomizations) {
+ sb.append("ARC[" + i++ + "]: " + arc.toString());
+ }
+ }
+
+ return sb.toString();
+ }
+
+ public ArrayList<NetworkResourceCustomization> getNetworkResourceCustomizations() {
+ return networkResourceCustomizations;
+ }
+
+ public void setNetworkResourceCustomizations(
+ ArrayList<NetworkResourceCustomization> networkResourceCustomizations) {
+ this.networkResourceCustomizations = networkResourceCustomizations;
+ }
+
+ public ArrayList<AllottedResourceCustomization> getAllottedResourceCustomizations() {
+ return allottedResourceCustomizations;
+ }
+
+ public void setAllottedResourceCustomizations(
+ ArrayList<AllottedResourceCustomization> allottedResourceCustomizations) {
+ this.allottedResourceCustomizations = allottedResourceCustomizations;
+ }
+
+
+
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioning.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioning.java
index 6951c4412d..a7610fec92 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioning.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioning.java
@@ -24,89 +24,91 @@ package org.onap.so.db.catalog.utils;
import java.io.Serializable;
/**
- * This class is the base class for object that requires a Version in Catalog DB.
- * The version is built on a string as ASDC provides a number like 1.2 or 2.0 ...
- * This class supports also 1.2.3.4... (Maven like version)
+ * This class is the base class for object that requires a Version in Catalog DB. The version is built on a string as
+ * ASDC provides a number like 1.2 or 2.0 ... This class supports also 1.2.3.4... (Maven like version)
*
*
*/
public class MavenLikeVersioning implements Serializable {
- protected String version;
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
- /**
- * This method is used to compare the current object version to a specified one
- * It is assumed that the version is like the maven one, eg: 2.0.1.5.6
- *
- * @param versionToCompare The version that will be used for comparison
- * @return True if the current object is more recent than the specified version, False otherwise
- *
- */
- public boolean isMoreRecentThan (String versionToCompare) {
- if (versionToCompare == null || versionToCompare.trim().isEmpty() || this.version == null || this.version.trim().isEmpty()) {
- return false;
- }
- String[] currentVersionArray = this.version.split("\\.");
- String[] specifiedVersionArray = versionToCompare.split("\\.");
-
- int smalestStringLength = Math.min(currentVersionArray.length, specifiedVersionArray.length);
-
- for (int currentVersionIndex = 0; currentVersionIndex < smalestStringLength; ++currentVersionIndex) {
-
- if (Integer.parseInt(currentVersionArray[currentVersionIndex]) < Integer
- .parseInt(specifiedVersionArray[currentVersionIndex])) {
- return false;
- } else if (Integer.parseInt(currentVersionArray[currentVersionIndex]) > Integer
- .parseInt(specifiedVersionArray[currentVersionIndex])) {
- return true;
- }
- }
- try {
- // Even if versionToCompare has more digits, it means versionToCompare is more recent
- return Integer.parseInt(currentVersionArray[smalestStringLength - 1]) != Integer
- .parseInt(specifiedVersionArray[smalestStringLength - 1])
- || currentVersionArray.length > specifiedVersionArray.length;
- } catch (NumberFormatException e) {
- return false;
- }
- }
-
- /**
- * This method is used to compare the current object version to a specified one
- * It is assumed that the version is like the maven one, eg: 2.0.1.5.6
- *
- * @param versionToCompare The version that will be used for comparison
- * @return True if the current object is equal to the specified version, False otherwise
- *
- */
- public boolean isTheSameVersion (String versionToCompare) {
- if (versionToCompare == null && this.version == null) {
- return true;
- } else if (versionToCompare == null || versionToCompare.trim().equals("") || this.version == null || this.version.trim().equals("")) {
- return false;
- }
- String [] currentVersionArray = this.version.split("\\.");
- String [] specifiedVersionArray = versionToCompare.split("\\.");
-
- if (currentVersionArray.length != specifiedVersionArray.length) {
- return false;
- }
-
- for (int currentVersionIndex=0;currentVersionIndex < currentVersionArray.length;++currentVersionIndex) {
-
- if (Integer.parseInt(currentVersionArray[currentVersionIndex]) != Integer.parseInt(specifiedVersionArray[currentVersionIndex])) {
- return false;
- }
- }
-
- return true;
- }
+ protected String version;
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ /**
+ * This method is used to compare the current object version to a specified one It is assumed that the version is
+ * like the maven one, eg: 2.0.1.5.6
+ *
+ * @param versionToCompare The version that will be used for comparison
+ * @return True if the current object is more recent than the specified version, False otherwise
+ *
+ */
+ public boolean isMoreRecentThan(String versionToCompare) {
+ if (versionToCompare == null || versionToCompare.trim().isEmpty() || this.version == null
+ || this.version.trim().isEmpty()) {
+ return false;
+ }
+ String[] currentVersionArray = this.version.split("\\.");
+ String[] specifiedVersionArray = versionToCompare.split("\\.");
+
+ int smalestStringLength = Math.min(currentVersionArray.length, specifiedVersionArray.length);
+
+ for (int currentVersionIndex = 0; currentVersionIndex < smalestStringLength; ++currentVersionIndex) {
+
+ if (Integer.parseInt(currentVersionArray[currentVersionIndex]) < Integer
+ .parseInt(specifiedVersionArray[currentVersionIndex])) {
+ return false;
+ } else if (Integer.parseInt(currentVersionArray[currentVersionIndex]) > Integer
+ .parseInt(specifiedVersionArray[currentVersionIndex])) {
+ return true;
+ }
+ }
+ try {
+ // Even if versionToCompare has more digits, it means versionToCompare is more recent
+ return Integer.parseInt(currentVersionArray[smalestStringLength - 1]) != Integer
+ .parseInt(specifiedVersionArray[smalestStringLength - 1])
+ || currentVersionArray.length > specifiedVersionArray.length;
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+
+ /**
+ * This method is used to compare the current object version to a specified one It is assumed that the version is
+ * like the maven one, eg: 2.0.1.5.6
+ *
+ * @param versionToCompare The version that will be used for comparison
+ * @return True if the current object is equal to the specified version, False otherwise
+ *
+ */
+ public boolean isTheSameVersion(String versionToCompare) {
+ if (versionToCompare == null && this.version == null) {
+ return true;
+ } else if (versionToCompare == null || versionToCompare.trim().equals("") || this.version == null
+ || this.version.trim().equals("")) {
+ return false;
+ }
+ String[] currentVersionArray = this.version.split("\\.");
+ String[] specifiedVersionArray = versionToCompare.split("\\.");
+
+ if (currentVersionArray.length != specifiedVersionArray.length) {
+ return false;
+ }
+
+ for (int currentVersionIndex = 0; currentVersionIndex < currentVersionArray.length; ++currentVersionIndex) {
+
+ if (Integer.parseInt(currentVersionArray[currentVersionIndex]) != Integer
+ .parseInt(specifiedVersionArray[currentVersionIndex])) {
+ return false;
+ }
+ }
+
+ return true;
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioningComparator.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioningComparator.java
index 85fc9b3df2..be219e794c 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioningComparator.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioningComparator.java
@@ -26,24 +26,24 @@ import java.util.Comparator;
/**
* This class can be used to sort object from MavenLikeVersioning type.
*
- *
+ *
*
*/
public class MavenLikeVersioningComparator implements Comparator<MavenLikeVersioning> {
-
- @Override
- public int compare(MavenLikeVersioning o1, MavenLikeVersioning o2) {
- final int BEFORE = -1;
- final int EQUAL = 0;
- final int AFTER = 1;
-
- if (o1.isTheSameVersion(o2.getVersion())) {
- return EQUAL;
- } else if (o1.isMoreRecentThan(o2.getVersion())) {
- return AFTER;
- } else {
- return BEFORE;
- }
- }
+
+ @Override
+ public int compare(MavenLikeVersioning o1, MavenLikeVersioning o2) {
+ final int BEFORE = -1;
+ final int EQUAL = 0;
+ final int AFTER = 1;
+
+ if (o1.isTheSameVersion(o2.getVersion())) {
+ return EQUAL;
+ } else if (o1.isMoreRecentThan(o2.getVersion())) {
+ return AFTER;
+ } else {
+ return BEFORE;
+ }
+ }
}
diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/RecordNotFoundException.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/RecordNotFoundException.java
index 4168492245..7759b01c6a 100644
--- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/RecordNotFoundException.java
+++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/RecordNotFoundException.java
@@ -21,30 +21,30 @@
package org.onap.so.db.catalog.utils;
/*
-* Exception of the ASDC controller.
-*/
+ * Exception of the ASDC controller.
+ */
public class RecordNotFoundException extends Exception {
- /**
- * serialization id.
- */
- private static final long serialVersionUID = 8425657297510362736L;
+ /**
+ * serialization id.
+ */
+ private static final long serialVersionUID = 8425657297510362736L;
- /**
- * @param message The message to dump
- * @param cause The Throwable cause object
- */
- public RecordNotFoundException(final String message) {
- super (message);
+ /**
+ * @param message The message to dump
+ * @param cause The Throwable cause object
+ */
+ public RecordNotFoundException(final String message) {
+ super(message);
- }
+ }
- /**
- * @param message The message to dump
- * @param cause The Throwable cause object
- */
- public RecordNotFoundException(final String message, final Throwable cause) {
- super (message, cause);
+ /**
+ * @param message The message to dump
+ * @param cause The Throwable cause object
+ */
+ public RecordNotFoundException(final String message, final Throwable cause) {
+ super(message, cause);
- }
+ }
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/BaseTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/BaseTest.java
index 5bfa300a03..bbd4c99a60 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/BaseTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/BaseTest.java
@@ -34,51 +34,51 @@ import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class BaseTest {
-
- protected VnfcCustomization setUpVnfcCustomization(){
- VnfcCustomization vnfcCustomization = new VnfcCustomization();
- vnfcCustomization.setModelInstanceName("testVnfcCustomizationModelInstanceName");
- vnfcCustomization.setModelUUID("321228a4-9f15-11e8-98d0-529269fb1459");
- vnfcCustomization.setModelInvariantUUID("c0659136-9f15-11e8-98d0-529269fb1459");
- vnfcCustomization.setModelVersion("testModelVersion");
- vnfcCustomization.setModelName("testModelName");
- vnfcCustomization.setToscaNodeType("testToscaModelType");
- vnfcCustomization.setDescription("testVnfcCustomizationDescription");
- return vnfcCustomization;
+
+ protected VnfcCustomization setUpVnfcCustomization() {
+ VnfcCustomization vnfcCustomization = new VnfcCustomization();
+ vnfcCustomization.setModelInstanceName("testVnfcCustomizationModelInstanceName");
+ vnfcCustomization.setModelUUID("321228a4-9f15-11e8-98d0-529269fb1459");
+ vnfcCustomization.setModelInvariantUUID("c0659136-9f15-11e8-98d0-529269fb1459");
+ vnfcCustomization.setModelVersion("testModelVersion");
+ vnfcCustomization.setModelName("testModelName");
+ vnfcCustomization.setToscaNodeType("testToscaModelType");
+ vnfcCustomization.setDescription("testVnfcCustomizationDescription");
+ return vnfcCustomization;
}
-
- protected CvnfcCustomization setUpCvnfcCustomization(){
- CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
- cvnfcCustomization.setModelInstanceName("cvfncCustomizationTestModelInstanceName");
- cvnfcCustomization.setModelUUID("321228a4-9f15-11e8-98d0-529269fb1459");
- cvnfcCustomization.setModelInvariantUUID("c0659136-9f15-11e8-98d0-529269fb1459");
- cvnfcCustomization.setModelVersion("testModelVersion");
- cvnfcCustomization.setModelName("testModelName");
- cvnfcCustomization.setToscaNodeType("testToscaNodeType");
- cvnfcCustomization.setDescription("description");
- cvnfcCustomization.setNfcFunction("testNfcFunction");
- cvnfcCustomization.setNfcNamingCode("testNfcNamingCode");
- return cvnfcCustomization;
+
+ protected CvnfcCustomization setUpCvnfcCustomization() {
+ CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
+ cvnfcCustomization.setModelInstanceName("cvfncCustomizationTestModelInstanceName");
+ cvnfcCustomization.setModelUUID("321228a4-9f15-11e8-98d0-529269fb1459");
+ cvnfcCustomization.setModelInvariantUUID("c0659136-9f15-11e8-98d0-529269fb1459");
+ cvnfcCustomization.setModelVersion("testModelVersion");
+ cvnfcCustomization.setModelName("testModelName");
+ cvnfcCustomization.setToscaNodeType("testToscaNodeType");
+ cvnfcCustomization.setDescription("description");
+ cvnfcCustomization.setNfcFunction("testNfcFunction");
+ cvnfcCustomization.setNfcNamingCode("testNfcNamingCode");
+ return cvnfcCustomization;
}
-
- protected VfModule setUpVfModule(){
- VfModule vFModule = new VfModule();
- vFModule.setModelUUID("cb82ffd8-252a-11e7-93ae-92361f002671");
- vFModule.setModelVersion("testModelVersion");
- vFModule.setModelName("testModelName");
- vFModule.setIsBase(false);
- return vFModule;
+
+ protected VfModule setUpVfModule() {
+ VfModule vFModule = new VfModule();
+ vFModule.setModelUUID("cb82ffd8-252a-11e7-93ae-92361f002671");
+ vFModule.setModelVersion("testModelVersion");
+ vFModule.setModelName("testModelName");
+ vFModule.setIsBase(false);
+ return vFModule;
}
-
- protected VnfResource setUpVnfResource(){
- VnfResource vnfResource = new VnfResource();
- vnfResource.setModelUUID("cb82ffd8-252a-11e7-93ae-92361f002671");
- vnfResource.setModelInvariantUUID("az82ffd8-252a-11e7-93ae-92361f002677");
- vnfResource.setModelVersion("testModelVersion");
- vnfResource.setOrchestrationMode("HEAT");
- return vnfResource;
+
+ protected VnfResource setUpVnfResource() {
+ VnfResource vnfResource = new VnfResource();
+ vnfResource.setModelUUID("cb82ffd8-252a-11e7-93ae-92361f002671");
+ vnfResource.setModelInvariantUUID("az82ffd8-252a-11e7-93ae-92361f002677");
+ vnfResource.setModelVersion("testModelVersion");
+ vnfResource.setOrchestrationMode("HEAT");
+ return vnfResource;
}
-
+
@Test
- public void testNothing(){}
+ public void testNothing() {}
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/BuildingBlockDetailTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/BuildingBlockDetailTest.java
index 73f1ef49fa..6f54288d9a 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/BuildingBlockDetailTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/BuildingBlockDetailTest.java
@@ -21,7 +21,6 @@
package org.onap.so.db.catalog;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.db.catalog.beans.BuildingBlockDetail;
@@ -37,16 +36,17 @@ import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class BuildingBlockDetailTest {
- @Autowired
- private BuildingBlockDetailRepository buildingBlockDetailRepository;
-
- @Test
- public void BuildingBlockDetailSingleLookupValidationTest() {
- String buildingBlockName = "AssignServiceInstanceBB";
-
- BuildingBlockDetail buildingBlockDetail = buildingBlockDetailRepository.findOneByBuildingBlockName(buildingBlockName);
- assertEquals(buildingBlockName, buildingBlockDetail.getBuildingBlockName());
- assertEquals(ResourceType.SERVICE, buildingBlockDetail.getResourceType());
- assertEquals(OrchestrationAction.ASSIGN, buildingBlockDetail.getTargetAction());
- }
+ @Autowired
+ private BuildingBlockDetailRepository buildingBlockDetailRepository;
+
+ @Test
+ public void BuildingBlockDetailSingleLookupValidationTest() {
+ String buildingBlockName = "AssignServiceInstanceBB";
+
+ BuildingBlockDetail buildingBlockDetail =
+ buildingBlockDetailRepository.findOneByBuildingBlockName(buildingBlockName);
+ assertEquals(buildingBlockName, buildingBlockDetail.getBuildingBlockName());
+ assertEquals(ResourceType.SERVICE, buildingBlockDetail.getResourceType());
+ assertEquals(OrchestrationAction.ASSIGN, buildingBlockDetail.getTargetAction());
+ }
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/ControllerSelectionReferenceTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/ControllerSelectionReferenceTest.java
index 489f8a0a3d..f3670649ae 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/ControllerSelectionReferenceTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/ControllerSelectionReferenceTest.java
@@ -22,7 +22,6 @@ package org.onap.so.db.catalog;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.db.catalog.beans.ControllerSelectionReference;
@@ -37,32 +36,32 @@ import org.springframework.test.context.junit4.SpringRunner;
@ActiveProfiles("test")
public class ControllerSelectionReferenceTest {
- @Autowired
- private ControllerSelectionReferenceRepository controllerSelectionReferenceRepository;
-
- @Test
- public void Find_ControllerNameByVnfTypeAndAction_Test() {
- String vnfType = "vLoadBalancerMS/vLoadBalancerMS 0";
- String controllerName = "APPC";
- String actionCategory = "ConfigScaleOut";
- ControllerSelectionReference controller =
- controllerSelectionReferenceRepository.findControllerSelectionReferenceByVnfTypeAndActionCategory(vnfType, actionCategory);
- assertEquals(vnfType, controller.getVnfType());
- assertEquals(controllerName, controller.getControllerName());
- assertEquals(actionCategory, controller.getActionCategory());
- }
-
- @Test
- public final void controllerDataTest() {
- ControllerSelectionReference controller = new ControllerSelectionReference();
+ @Autowired
+ private ControllerSelectionReferenceRepository controllerSelectionReferenceRepository;
+
+ @Test
+ public void Find_ControllerNameByVnfTypeAndAction_Test() {
+ String vnfType = "vLoadBalancerMS/vLoadBalancerMS 0";
+ String controllerName = "APPC";
+ String actionCategory = "ConfigScaleOut";
+ ControllerSelectionReference controller = controllerSelectionReferenceRepository
+ .findControllerSelectionReferenceByVnfTypeAndActionCategory(vnfType, actionCategory);
+ assertEquals(vnfType, controller.getVnfType());
+ assertEquals(controllerName, controller.getControllerName());
+ assertEquals(actionCategory, controller.getActionCategory());
+ }
+
+ @Test
+ public final void controllerDataTest() {
+ ControllerSelectionReference controller = new ControllerSelectionReference();
- controller.setVnfType("vnfType");
- assertTrue(controller.getVnfType().equalsIgnoreCase("vnfType"));
+ controller.setVnfType("vnfType");
+ assertTrue(controller.getVnfType().equalsIgnoreCase("vnfType"));
- controller.setControllerName("controllerName");
- assertTrue(controller.getControllerName().equalsIgnoreCase("controllerName"));
+ controller.setControllerName("controllerName");
+ assertTrue(controller.getControllerName().equalsIgnoreCase("controllerName"));
- controller.setActionCategory("actionCategory");
- assertTrue(controller.getActionCategory().equalsIgnoreCase("actionCategory"));
- }
+ controller.setActionCategory("actionCategory");
+ assertTrue(controller.getActionCategory().equalsIgnoreCase("actionCategory"));
+ }
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/EmbeddedMariaDbConfig.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/EmbeddedMariaDbConfig.java
index 06a7b1ed29..314e648d9e 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/EmbeddedMariaDbConfig.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/EmbeddedMariaDbConfig.java
@@ -19,6 +19,7 @@
*/
package org.onap.so.db.catalog;
+
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
@@ -30,7 +31,7 @@ import org.springframework.context.annotation.Profile;
import javax.sql.DataSource;
@Configuration
-@Profile({"test","local"})
+@Profile({"test", "local"})
public class EmbeddedMariaDbConfig {
@Bean
@@ -40,21 +41,16 @@ public class EmbeddedMariaDbConfig {
@Bean
DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService,
- @Value("${mariaDB4j.databaseName}") String databaseName,
- @Value("${spring.datasource.username}") String datasourceUsername,
- @Value("${spring.datasource.password}") String datasourcePassword,
- @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
- //Create our database with default root user and no password
+ @Value("${mariaDB4j.databaseName}") String databaseName,
+ @Value("${spring.datasource.username}") String datasourceUsername,
+ @Value("${spring.datasource.password}") String datasourcePassword,
+ @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException {
+ // Create our database with default root user and no password
mariaDB4jSpringService.getDB().createDB(databaseName);
DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration();
- return DataSourceBuilder
- .create()
- .username(datasourceUsername)
- .password(datasourcePassword)
- .url(config.getURL(databaseName))
- .driverClassName(datasourceDriver)
- .build();
+ return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword)
+ .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build();
}
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/MavenVersioningTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/MavenVersioningTest.java
index b5d6271f7c..63328213c7 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/MavenVersioningTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/MavenVersioningTest.java
@@ -22,166 +22,163 @@ package org.onap.so.db.catalog;
import static org.junit.Assert.*;
-
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
-
import org.junit.Test;
-
import org.onap.so.db.catalog.utils.MavenLikeVersioningComparator;
import org.onap.so.db.catalog.utils.MavenLikeVersioning;
public class MavenVersioningTest {
- @Test
- public final void testVersion () {
- MavenLikeVersioning mavenVersioning = new MavenLikeVersioning ();
- assertFalse(mavenVersioning.isMoreRecentThan("0.0.0"));
- assertFalse(mavenVersioning.isMoreRecentThan(null));
- mavenVersioning.setVersion("0.0.1");
-
- assertFalse(mavenVersioning.isMoreRecentThan(null));
- assertTrue(mavenVersioning.isMoreRecentThan("0.0.0"));
- assertTrue(mavenVersioning.isMoreRecentThan("0.0.0.1"));
-
- assertFalse(mavenVersioning.isMoreRecentThan("0.0.2"));
- assertFalse(mavenVersioning.isMoreRecentThan("0.0.1"));
- assertFalse(mavenVersioning.isMoreRecentThan("00.00.01"));
-
- assertFalse(mavenVersioning.isMoreRecentThan("0.1"));
- assertFalse(mavenVersioning.isMoreRecentThan("1"));
- assertFalse(mavenVersioning.isMoreRecentThan("0.1.0.2"));
-
- assertFalse(mavenVersioning.isMoreRecentThan("0.1.1"));
- assertFalse(mavenVersioning.isMoreRecentThan("2.1.1"));
-
- mavenVersioning.setVersion("1.0.1");
- assertTrue(mavenVersioning.isMoreRecentThan("0.0.0"));
- assertTrue(mavenVersioning.isMoreRecentThan("0.5.2"));
- assertTrue(mavenVersioning.isMoreRecentThan("1.0.0"));
-
- assertFalse(mavenVersioning.isMoreRecentThan("2.1.1"));
- assertFalse(mavenVersioning.isMoreRecentThan("02.001.0001"));
- assertFalse(mavenVersioning.isMoreRecentThan("1.0.1"));
- assertFalse(mavenVersioning.isMoreRecentThan("1.0.2"));
- assertFalse(mavenVersioning.isMoreRecentThan("1.1.1"));
- assertFalse(mavenVersioning.isMoreRecentThan("1.0.10"));
-
-
- mavenVersioning.setVersion("100.0.1");
- assertTrue(mavenVersioning.isMoreRecentThan("0.0.0"));
- assertTrue(mavenVersioning.isMoreRecentThan("0.5.2"));
- assertTrue(mavenVersioning.isMoreRecentThan("1.0.0"));
-
- assertFalse(mavenVersioning.isMoreRecentThan("101.1.1"));
- assertFalse(mavenVersioning.isMoreRecentThan("100.0.1"));
- assertFalse(mavenVersioning.isMoreRecentThan("100.0.2"));
- assertFalse(mavenVersioning.isMoreRecentThan("100.1.1"));
-
- assertFalse(mavenVersioning.isMoreRecentThan("100.0.1.4"));
- }
-
- @Test
- public final void testOneDigitVersion() {
- MavenLikeVersioning oneDigit = new MavenLikeVersioning();
- oneDigit.setVersion("1");
- assertFalse(oneDigit.isMoreRecentThan("2"));
- assertFalse(oneDigit.isMoreRecentThan("2.0"));
- assertFalse(oneDigit.isMoreRecentThan("1.0"));
-
- oneDigit.setVersion("1.0");
- assertTrue(oneDigit.isMoreRecentThan("1"));
-
- oneDigit.setVersion("1");
- assertFalse(oneDigit.isTheSameVersion("1.1"));
- assertFalse(oneDigit.isTheSameVersion("1.0"));
- assertFalse(oneDigit.isTheSameVersion("1.0.0"));
-
- oneDigit.setVersion("2");
- assertTrue(oneDigit.isMoreRecentThan("1"));
- assertTrue(oneDigit.isMoreRecentThan("1.0"));
- assertTrue(oneDigit.isMoreRecentThan("1.1"));
- assertTrue(oneDigit.isMoreRecentThan("0.1"));
- assertFalse(oneDigit.isMoreRecentThan("2.0"));
-
- }
-
- @Test
- public final void testVersionEquals () {
-
- MavenLikeVersioning heatTemplate = new MavenLikeVersioning();
- assertFalse(heatTemplate.isTheSameVersion("100.0"));
- assertTrue(heatTemplate.isTheSameVersion(null));
- heatTemplate.setVersion("100.0.1");
- assertFalse(heatTemplate.isTheSameVersion(null));
- assertFalse(heatTemplate.isTheSameVersion("100.0"));
- assertFalse(heatTemplate.isTheSameVersion("100"));
- assertFalse(heatTemplate.isTheSameVersion("100.0.1.1"));
- assertTrue(heatTemplate.isTheSameVersion("100.0.1"));
- assertTrue(heatTemplate.isTheSameVersion("00100.000.0001"));
- assertFalse(heatTemplate.isTheSameVersion("0.0.1"));
- assertTrue(heatTemplate.isTheSameVersion("100.0.01"));
-
- }
-
- @Test
- public final void testListSort () {
- MavenLikeVersioning test1 = new MavenLikeVersioning();
- test1.setVersion("1.1");
- MavenLikeVersioning test2 = new MavenLikeVersioning();
- test2.setVersion("1.10");
- MavenLikeVersioning test3 = new MavenLikeVersioning();
- test3.setVersion("1.2");
- MavenLikeVersioning test4 = new MavenLikeVersioning();
- test4.setVersion("1.20");
- MavenLikeVersioning test5 = new MavenLikeVersioning();
- test5.setVersion("1.02");
- MavenLikeVersioning test6 = new MavenLikeVersioning();
- test6.setVersion("2.02");
- MavenLikeVersioning test7 = new MavenLikeVersioning();
- test7.setVersion("0.02");
- MavenLikeVersioning test8 = new MavenLikeVersioning();
- test8.setVersion("2.02");
- MavenLikeVersioning test9 = new MavenLikeVersioning();
- test9.setVersion("10.2004");
- MavenLikeVersioning test10 = new MavenLikeVersioning();
- test10.setVersion("2");
- MavenLikeVersioning test11 = new MavenLikeVersioning();
- test11.setVersion("12");
- MavenLikeVersioning test12 = new MavenLikeVersioning();
- test12.setVersion("2.0");
-
- List<MavenLikeVersioning> list= new LinkedList<MavenLikeVersioning>();
- list.add(test1);
- list.add(test2);
- list.add(test3);
- list.add(test4);
- list.add(test5);
- list.add(test6);
- list.add(test7);
- list.add(test8);
- list.add(test9);
- list.add(test10);
- list.add(test11);
- list.add(test12);
-
- Collections.sort(list,new MavenLikeVersioningComparator());
- //Collections.reverse(list);
- assertTrue(list.get(0).getVersion().equals("0.02"));
- assertTrue(list.get(1).getVersion().equals("1.1"));
- assertTrue(list.get(2).getVersion().equals("1.02") || list.get(3).getVersion().equals("1.02"));
- assertTrue(list.get(3).getVersion().equals("1.2") || list.get(2).getVersion().equals("1.2"));
- assertTrue(list.get(4).getVersion().equals("1.10"));
- assertTrue(list.get(5).getVersion().equals("1.20"));
- assertTrue(list.get(6).getVersion().equals("2"));
- assertTrue(list.get(7).getVersion().equals("2.0"));
- assertTrue(list.get(8).getVersion().equals("2.02"));
- assertTrue(list.get(9).getVersion().equals("2.02"));
- assertTrue(list.get(10).getVersion().equals("10.2004"));
- assertTrue(list.get(11).getVersion().equals("12"));
-
- }
+ @Test
+ public final void testVersion() {
+ MavenLikeVersioning mavenVersioning = new MavenLikeVersioning();
+ assertFalse(mavenVersioning.isMoreRecentThan("0.0.0"));
+ assertFalse(mavenVersioning.isMoreRecentThan(null));
+ mavenVersioning.setVersion("0.0.1");
+
+ assertFalse(mavenVersioning.isMoreRecentThan(null));
+ assertTrue(mavenVersioning.isMoreRecentThan("0.0.0"));
+ assertTrue(mavenVersioning.isMoreRecentThan("0.0.0.1"));
+
+ assertFalse(mavenVersioning.isMoreRecentThan("0.0.2"));
+ assertFalse(mavenVersioning.isMoreRecentThan("0.0.1"));
+ assertFalse(mavenVersioning.isMoreRecentThan("00.00.01"));
+
+ assertFalse(mavenVersioning.isMoreRecentThan("0.1"));
+ assertFalse(mavenVersioning.isMoreRecentThan("1"));
+ assertFalse(mavenVersioning.isMoreRecentThan("0.1.0.2"));
+
+ assertFalse(mavenVersioning.isMoreRecentThan("0.1.1"));
+ assertFalse(mavenVersioning.isMoreRecentThan("2.1.1"));
+
+ mavenVersioning.setVersion("1.0.1");
+ assertTrue(mavenVersioning.isMoreRecentThan("0.0.0"));
+ assertTrue(mavenVersioning.isMoreRecentThan("0.5.2"));
+ assertTrue(mavenVersioning.isMoreRecentThan("1.0.0"));
+
+ assertFalse(mavenVersioning.isMoreRecentThan("2.1.1"));
+ assertFalse(mavenVersioning.isMoreRecentThan("02.001.0001"));
+ assertFalse(mavenVersioning.isMoreRecentThan("1.0.1"));
+ assertFalse(mavenVersioning.isMoreRecentThan("1.0.2"));
+ assertFalse(mavenVersioning.isMoreRecentThan("1.1.1"));
+ assertFalse(mavenVersioning.isMoreRecentThan("1.0.10"));
+
+
+ mavenVersioning.setVersion("100.0.1");
+ assertTrue(mavenVersioning.isMoreRecentThan("0.0.0"));
+ assertTrue(mavenVersioning.isMoreRecentThan("0.5.2"));
+ assertTrue(mavenVersioning.isMoreRecentThan("1.0.0"));
+
+ assertFalse(mavenVersioning.isMoreRecentThan("101.1.1"));
+ assertFalse(mavenVersioning.isMoreRecentThan("100.0.1"));
+ assertFalse(mavenVersioning.isMoreRecentThan("100.0.2"));
+ assertFalse(mavenVersioning.isMoreRecentThan("100.1.1"));
+
+ assertFalse(mavenVersioning.isMoreRecentThan("100.0.1.4"));
+ }
+
+ @Test
+ public final void testOneDigitVersion() {
+ MavenLikeVersioning oneDigit = new MavenLikeVersioning();
+ oneDigit.setVersion("1");
+ assertFalse(oneDigit.isMoreRecentThan("2"));
+ assertFalse(oneDigit.isMoreRecentThan("2.0"));
+ assertFalse(oneDigit.isMoreRecentThan("1.0"));
+
+ oneDigit.setVersion("1.0");
+ assertTrue(oneDigit.isMoreRecentThan("1"));
+
+ oneDigit.setVersion("1");
+ assertFalse(oneDigit.isTheSameVersion("1.1"));
+ assertFalse(oneDigit.isTheSameVersion("1.0"));
+ assertFalse(oneDigit.isTheSameVersion("1.0.0"));
+
+ oneDigit.setVersion("2");
+ assertTrue(oneDigit.isMoreRecentThan("1"));
+ assertTrue(oneDigit.isMoreRecentThan("1.0"));
+ assertTrue(oneDigit.isMoreRecentThan("1.1"));
+ assertTrue(oneDigit.isMoreRecentThan("0.1"));
+ assertFalse(oneDigit.isMoreRecentThan("2.0"));
+
+ }
+
+ @Test
+ public final void testVersionEquals() {
+
+ MavenLikeVersioning heatTemplate = new MavenLikeVersioning();
+ assertFalse(heatTemplate.isTheSameVersion("100.0"));
+ assertTrue(heatTemplate.isTheSameVersion(null));
+ heatTemplate.setVersion("100.0.1");
+ assertFalse(heatTemplate.isTheSameVersion(null));
+ assertFalse(heatTemplate.isTheSameVersion("100.0"));
+ assertFalse(heatTemplate.isTheSameVersion("100"));
+ assertFalse(heatTemplate.isTheSameVersion("100.0.1.1"));
+ assertTrue(heatTemplate.isTheSameVersion("100.0.1"));
+ assertTrue(heatTemplate.isTheSameVersion("00100.000.0001"));
+ assertFalse(heatTemplate.isTheSameVersion("0.0.1"));
+ assertTrue(heatTemplate.isTheSameVersion("100.0.01"));
+
+ }
+
+ @Test
+ public final void testListSort() {
+ MavenLikeVersioning test1 = new MavenLikeVersioning();
+ test1.setVersion("1.1");
+ MavenLikeVersioning test2 = new MavenLikeVersioning();
+ test2.setVersion("1.10");
+ MavenLikeVersioning test3 = new MavenLikeVersioning();
+ test3.setVersion("1.2");
+ MavenLikeVersioning test4 = new MavenLikeVersioning();
+ test4.setVersion("1.20");
+ MavenLikeVersioning test5 = new MavenLikeVersioning();
+ test5.setVersion("1.02");
+ MavenLikeVersioning test6 = new MavenLikeVersioning();
+ test6.setVersion("2.02");
+ MavenLikeVersioning test7 = new MavenLikeVersioning();
+ test7.setVersion("0.02");
+ MavenLikeVersioning test8 = new MavenLikeVersioning();
+ test8.setVersion("2.02");
+ MavenLikeVersioning test9 = new MavenLikeVersioning();
+ test9.setVersion("10.2004");
+ MavenLikeVersioning test10 = new MavenLikeVersioning();
+ test10.setVersion("2");
+ MavenLikeVersioning test11 = new MavenLikeVersioning();
+ test11.setVersion("12");
+ MavenLikeVersioning test12 = new MavenLikeVersioning();
+ test12.setVersion("2.0");
+
+ List<MavenLikeVersioning> list = new LinkedList<MavenLikeVersioning>();
+ list.add(test1);
+ list.add(test2);
+ list.add(test3);
+ list.add(test4);
+ list.add(test5);
+ list.add(test6);
+ list.add(test7);
+ list.add(test8);
+ list.add(test9);
+ list.add(test10);
+ list.add(test11);
+ list.add(test12);
+
+ Collections.sort(list, new MavenLikeVersioningComparator());
+ // Collections.reverse(list);
+ assertTrue(list.get(0).getVersion().equals("0.02"));
+ assertTrue(list.get(1).getVersion().equals("1.1"));
+ assertTrue(list.get(2).getVersion().equals("1.02") || list.get(3).getVersion().equals("1.02"));
+ assertTrue(list.get(3).getVersion().equals("1.2") || list.get(2).getVersion().equals("1.2"));
+ assertTrue(list.get(4).getVersion().equals("1.10"));
+ assertTrue(list.get(5).getVersion().equals("1.20"));
+ assertTrue(list.get(6).getVersion().equals("2"));
+ assertTrue(list.get(7).getVersion().equals("2.0"));
+ assertTrue(list.get(8).getVersion().equals("2.02"));
+ assertTrue(list.get(9).getVersion().equals("2.02"));
+ assertTrue(list.get(10).getVersion().equals("10.2004"));
+ assertTrue(list.get(11).getVersion().equals("12"));
+
+ }
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/NetworkTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/NetworkTest.java
index 456c826d19..7d79a4c464 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/NetworkTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/NetworkTest.java
@@ -21,7 +21,6 @@
package org.onap.so.db.catalog;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.db.catalog.beans.NetworkResource;
@@ -35,12 +34,12 @@ import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class NetworkTest {
- @Autowired
- private NetworkResourceRepository networkRepo;
-
- @Test
- public void BuildingBlockDetailSingleLookupValidationTest() {
- NetworkResource latestNetwork = networkRepo.findFirstByModelNameOrderByModelVersionDesc("CONTRAIL30_GNDIRECT");
- assertEquals("10b36f65-f4e6-4be6-ae49-9596dc1c47fz",latestNetwork.getModelUUID());
- }
+ @Autowired
+ private NetworkResourceRepository networkRepo;
+
+ @Test
+ public void BuildingBlockDetailSingleLookupValidationTest() {
+ NetworkResource latestNetwork = networkRepo.findFirstByModelNameOrderByModelVersionDesc("CONTRAIL30_GNDIRECT");
+ assertEquals("10b36f65-f4e6-4be6-ae49-9596dc1c47fz", latestNetwork.getModelUUID());
+ }
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/OrchestrationStatusStateTransitionDirectiveTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/OrchestrationStatusStateTransitionDirectiveTest.java
index b6aa408185..3d470df593 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/OrchestrationStatusStateTransitionDirectiveTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/OrchestrationStatusStateTransitionDirectiveTest.java
@@ -21,7 +21,6 @@
package org.onap.so.db.catalog;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.db.catalog.beans.OrchestrationAction;
@@ -39,15 +38,20 @@ import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class OrchestrationStatusStateTransitionDirectiveTest {
- @Autowired
- private OrchestrationStatusStateTransitionDirectiveRepository orchestrationStatusStateTransitionDirectiveRepository;
+ @Autowired
+ private OrchestrationStatusStateTransitionDirectiveRepository orchestrationStatusStateTransitionDirectiveRepository;
- @Test
- public void OrchestrationStatusTransitionDBSingleLookupValidationTest() {
- OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective = orchestrationStatusStateTransitionDirectiveRepository.findOneByResourceTypeAndOrchestrationStatusAndTargetAction(ResourceType.SERVICE, OrchestrationStatus.ASSIGNED, OrchestrationAction.ASSIGN);
- assertEquals(ResourceType.SERVICE, orchestrationStatusStateTransitionDirective.getResourceType());
- assertEquals(OrchestrationStatus.ASSIGNED, orchestrationStatusStateTransitionDirective.getOrchestrationStatus());
- assertEquals(OrchestrationAction.ASSIGN, orchestrationStatusStateTransitionDirective.getTargetAction());
- assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS, orchestrationStatusStateTransitionDirective.getFlowDirective());
- }
+ @Test
+ public void OrchestrationStatusTransitionDBSingleLookupValidationTest() {
+ OrchestrationStatusStateTransitionDirective orchestrationStatusStateTransitionDirective =
+ orchestrationStatusStateTransitionDirectiveRepository
+ .findOneByResourceTypeAndOrchestrationStatusAndTargetAction(ResourceType.SERVICE,
+ OrchestrationStatus.ASSIGNED, OrchestrationAction.ASSIGN);
+ assertEquals(ResourceType.SERVICE, orchestrationStatusStateTransitionDirective.getResourceType());
+ assertEquals(OrchestrationStatus.ASSIGNED,
+ orchestrationStatusStateTransitionDirective.getOrchestrationStatus());
+ assertEquals(OrchestrationAction.ASSIGN, orchestrationStatusStateTransitionDirective.getTargetAction());
+ assertEquals(OrchestrationStatusValidationDirective.SILENT_SUCCESS,
+ orchestrationStatusStateTransitionDirective.getFlowDirective());
+ }
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/ServiceTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/ServiceTest.java
index 7028d9161c..96f7037fc3 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/ServiceTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/ServiceTest.java
@@ -22,9 +22,7 @@ package org.onap.so.db.catalog;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-
import java.util.List;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.db.catalog.beans.PnfResource;
@@ -46,23 +44,23 @@ public class ServiceTest {
@Test
public void Find_LatestService_Test() {
- Service latestVersionService = serviceRepo
- .findFirstByModelNameOrderByModelVersionDesc("MSOTADevInfra_vSAMP10a_Service");
+ Service latestVersionService =
+ serviceRepo.findFirstByModelNameOrderByModelVersionDesc("MSOTADevInfra_vSAMP10a_Service");
assertEquals("5df8b6de-2083-11e7-93ae-92361f002675", latestVersionService.getModelUUID());
}
@Test
public void Find_LatestService_Test_2() {
- Service latestVersionService = serviceRepo
- .findByModelNameOrderByModelVersionDesc("MSOTADevInfra_vSAMP10a_Service");
+ Service latestVersionService =
+ serviceRepo.findByModelNameOrderByModelVersionDesc("MSOTADevInfra_vSAMP10a_Service");
assertEquals("5df8b6de-2083-11e7-93ae-92361f002675", latestVersionService.getModelUUID());
}
@Test
public void Find_LatestService_Test_Invariant_UUID() {
- List<Service> latestVersionService = serviceRepo
- .findByModelInvariantUUIDOrderByModelVersionDesc("9647dfc4-2083-11e7-93ae-92361f002671");
+ List<Service> latestVersionService =
+ serviceRepo.findByModelInvariantUUIDOrderByModelVersionDesc("9647dfc4-2083-11e7-93ae-92361f002671");
assertEquals("5df8b6de-2083-11e7-93ae-92361f002675", latestVersionService.get(0).getModelUUID());
assertEquals("5df8b6de-2083-11e7-93ae-92361f002674", latestVersionService.get(1).getModelUUID());
assertEquals("5df8b6de-2083-11e7-93ae-92361f002673", latestVersionService.get(2).getModelUUID());
@@ -72,15 +70,15 @@ public class ServiceTest {
@Test
public void Find_LatestService_Test_4() {
- Service latestVersionService = serviceRepo
- .findOneByModelUUIDOrderByModelVersionDesc("5df8b6de-2083-11e7-93ae-92361f002671");
+ Service latestVersionService =
+ serviceRepo.findOneByModelUUIDOrderByModelVersionDesc("5df8b6de-2083-11e7-93ae-92361f002671");
assertEquals("5df8b6de-2083-11e7-93ae-92361f002671", latestVersionService.getModelUUID());
}
@Test
public void Find_LatestService_Test_5() {
Service latestVersionService = serviceRepo
- .findFirstByModelInvariantUUIDOrderByModelVersionDesc("9647dfc4-2083-11e7-93ae-92361f002671");
+ .findFirstByModelInvariantUUIDOrderByModelVersionDesc("9647dfc4-2083-11e7-93ae-92361f002671");
assertEquals("5df8b6de-2083-11e7-93ae-92361f002675", latestVersionService.getModelUUID());
}
@@ -93,8 +91,8 @@ public class ServiceTest {
@Test
public void findByModelInvariantUUIDOrderByModelVersionDesc_ValidInvariantUuid_ExpectedOutput() {
- List<Service> services = serviceRepo
- .findByModelInvariantUUIDOrderByModelVersionDesc("9647dfc4-2083-11e7-93ae-92361f002676");
+ List<Service> services =
+ serviceRepo.findByModelInvariantUUIDOrderByModelVersionDesc("9647dfc4-2083-11e7-93ae-92361f002676");
assertEquals("One PNF service found", 1, services.size());
assertEquals("5df8b6de-2083-11e7-93ae-92361f002676", services.get(0).getModelUUID());
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/TempNetworkHeatTemplateLookupTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/TempNetworkHeatTemplateLookupTest.java
index b09ec7193d..e0de3cf375 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/TempNetworkHeatTemplateLookupTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/TempNetworkHeatTemplateLookupTest.java
@@ -21,7 +21,6 @@
package org.onap.so.db.catalog;
import static org.junit.Assert.assertTrue;
-
import org.junit.Test;
import org.onap.so.db.catalog.beans.TempNetworkHeatTemplateLookup;
@@ -30,21 +29,21 @@ import org.onap.so.db.catalog.beans.TempNetworkHeatTemplateLookup;
public class TempNetworkHeatTemplateLookupTest {
- @Test
- public final void tempNetworkHeatTemplateLookupDataTest() {
- TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup = new TempNetworkHeatTemplateLookup();
- tempNetworkHeatTemplateLookup.setAicVersionMax("aicVersionMax");
- assertTrue(tempNetworkHeatTemplateLookup.getAicVersionMax().equalsIgnoreCase("aicVersionMax"));
- tempNetworkHeatTemplateLookup.setAicVersionMin("aicVersionMin");
- assertTrue(tempNetworkHeatTemplateLookup.getAicVersionMin().equalsIgnoreCase("aicVersionMin"));
- tempNetworkHeatTemplateLookup.setHeatTemplateArtifactUuid("heatTemplateArtifactUuid");
- assertTrue(tempNetworkHeatTemplateLookup.getHeatTemplateArtifactUuid()
- .equalsIgnoreCase("heatTemplateArtifactUuid"));
- tempNetworkHeatTemplateLookup.setNetworkResourceModelName("networkResourceModelName");
- assertTrue(tempNetworkHeatTemplateLookup.getNetworkResourceModelName()
- .equalsIgnoreCase("networkResourceModelName"));
-// assertTrue(tempNetworkHeatTemplateLookup.toString() != null);
-
- }
+ @Test
+ public final void tempNetworkHeatTemplateLookupDataTest() {
+ TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup = new TempNetworkHeatTemplateLookup();
+ tempNetworkHeatTemplateLookup.setAicVersionMax("aicVersionMax");
+ assertTrue(tempNetworkHeatTemplateLookup.getAicVersionMax().equalsIgnoreCase("aicVersionMax"));
+ tempNetworkHeatTemplateLookup.setAicVersionMin("aicVersionMin");
+ assertTrue(tempNetworkHeatTemplateLookup.getAicVersionMin().equalsIgnoreCase("aicVersionMin"));
+ tempNetworkHeatTemplateLookup.setHeatTemplateArtifactUuid("heatTemplateArtifactUuid");
+ assertTrue(tempNetworkHeatTemplateLookup.getHeatTemplateArtifactUuid()
+ .equalsIgnoreCase("heatTemplateArtifactUuid"));
+ tempNetworkHeatTemplateLookup.setNetworkResourceModelName("networkResourceModelName");
+ assertTrue(tempNetworkHeatTemplateLookup.getNetworkResourceModelName()
+ .equalsIgnoreCase("networkResourceModelName"));
+ // assertTrue(tempNetworkHeatTemplateLookup.toString() != null);
+
+ }
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/TestApplication.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/TestApplication.java
index 64b393628c..2d786fe2a7 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/TestApplication.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/TestApplication.java
@@ -26,23 +26,23 @@ import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
-@SpringBootApplication(scanBasePackages = { "org.onap.so.db.catalog","org.onap.so.client", "org.onap.so.configuration"})
+@SpringBootApplication(scanBasePackages = {"org.onap.so.db.catalog", "org.onap.so.client", "org.onap.so.configuration"})
@EnableJpaRepositories("org.onap.so.db.catalog.data.repository")
@EntityScan("org.onap.so.db.catalog")
@Profile("test")
public class TestApplication {
- private static final String LOGS_DIR = "logs_dir";
-
- private static void setLogsDir() {
- if (System.getProperty(LOGS_DIR) == null) {
- System.getProperties().setProperty(LOGS_DIR, "./logs/catdb/");
- }
- }
-
- public static void main(String... args) {
- SpringApplication.run(TestApplication.class, args);
- System.getProperties().setProperty("mso.db", "MARIADB");
- System.getProperties().setProperty("server.name", "Springboot");
+ private static final String LOGS_DIR = "logs_dir";
+
+ private static void setLogsDir() {
+ if (System.getProperty(LOGS_DIR) == null) {
+ System.getProperties().setProperty(LOGS_DIR, "./logs/catdb/");
+ }
+ }
+
+ public static void main(String... args) {
+ SpringApplication.run(TestApplication.class, args);
+ System.getProperties().setProperty("mso.db", "MARIADB");
+ System.getProperties().setProperty("server.name", "Springboot");
setLogsDir();
- }
+ }
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/VFModuleTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/VFModuleTest.java
index 1f13bd946a..5887842b74 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/VFModuleTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/VFModuleTest.java
@@ -21,9 +21,7 @@
package org.onap.so.db.catalog;
import static org.junit.Assert.assertEquals;
-
import java.util.List;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.so.db.catalog.beans.VfModule;
@@ -37,20 +35,21 @@ import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class VFModuleTest {
- @Autowired
- private VFModuleRepository vfModuleRepo;
-
- @Test
- public void VFModule_Versioned_LookUp() {
- VfModule latestModule = vfModuleRepo.findFirstByModelNameOrderByModelVersionDesc("vSAMP10aDEV::PCM::module-1");
- assertEquals("066de97e-253e-11e7-93ae-92361f002675",latestModule.getModelUUID());
- }
-
- @Test
- public void VFModule_Versioned_LookUp_LIst() {
- List<VfModule> moduleList = vfModuleRepo.findByModelInvariantUUIDOrderByModelVersionDesc("64efd51a-2544-11e7-93ae-92361f002671");
- assertEquals("066de97e-253e-11e7-93ae-92361f002675",moduleList.get(0).getModelUUID());
- assertEquals("066de97e-253e-11e7-93ae-92361f002674",moduleList.get(1).getModelUUID());
- assertEquals("066de97e-253e-11e7-93ae-92361f002673",moduleList.get(2).getModelUUID());
- }
+ @Autowired
+ private VFModuleRepository vfModuleRepo;
+
+ @Test
+ public void VFModule_Versioned_LookUp() {
+ VfModule latestModule = vfModuleRepo.findFirstByModelNameOrderByModelVersionDesc("vSAMP10aDEV::PCM::module-1");
+ assertEquals("066de97e-253e-11e7-93ae-92361f002675", latestModule.getModelUUID());
+ }
+
+ @Test
+ public void VFModule_Versioned_LookUp_LIst() {
+ List<VfModule> moduleList =
+ vfModuleRepo.findByModelInvariantUUIDOrderByModelVersionDesc("64efd51a-2544-11e7-93ae-92361f002671");
+ assertEquals("066de97e-253e-11e7-93ae-92361f002675", moduleList.get(0).getModelUUID());
+ assertEquals("066de97e-253e-11e7-93ae-92361f002674", moduleList.get(1).getModelUUID());
+ assertEquals("066de97e-253e-11e7-93ae-92361f002673", moduleList.get(2).getModelUUID());
+ }
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/BeansTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/BeansTest.java
index 2188380bbd..f710890883 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/BeansTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/BeansTest.java
@@ -24,11 +24,9 @@ import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.onap.so.openpojo.rules.HasAnnotationMatcher.hasAnnotation;
import static org.onap.so.openpojo.rules.HasAnnotationPropertyWithValueMatcher.hasAnnotationPropertyWithValue;
-
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Temporal;
-
import org.junit.Ignore;
import org.junit.Test;
import org.onap.so.openpojo.rules.CustomSetterMustExistRule;
@@ -36,7 +34,6 @@ import org.onap.so.openpojo.rules.EqualsAndHashCodeTester;
import org.onap.so.openpojo.rules.HasEqualsAndHashCodeRule;
import org.onap.so.openpojo.rules.HasToStringRule;
import org.onap.so.openpojo.rules.ToStringTester;
-
import com.openpojo.reflection.PojoClass;
import com.openpojo.reflection.PojoClassFilter;
import com.openpojo.reflection.filters.FilterEnum;
@@ -57,45 +54,40 @@ import com.openpojo.validation.test.impl.SetterTester;
public class BeansTest {
- private PojoClassFilter filterTestClasses = new FilterTestClasses();
-
- private PojoClassFilter enumFilter = new FilterEnum();
-
-
+ private PojoClassFilter filterTestClasses = new FilterTestClasses();
+
+ private PojoClassFilter enumFilter = new FilterEnum();
+
+
+
+ @Test
+ public void pojoStructure() {
+ test("org.onap.so.db.catalog.beans");
+ test("org.onap.so.db.catalog.beans.macro");
+ }
+
+ private void test(String pojoPackage) {
+ Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new NoPrimitivesRule())
+ .with(new NoNestedClassRule()).with(new NoStaticExceptFinalRule())
+ .with(new SerializableMustHaveSerialVersionUIDRule()).with(new HasToStringRule())
+ .with(new EqualsAndHashCodeTester()).with(new NoPublicFieldsExceptStaticFinalRule())
+ .with(new CustomSetterMustExistRule()
+ .exclude(allOf(hasAnnotationPropertyWithValue(Column.class, "updatable", equalTo(false)),
+ hasAnnotation(GeneratedValue.class)), hasAnnotation(Temporal.class)))
+
+ .with(new SetterTester()).with(new GetterTester()).with(new ToStringTester())
+ .with(new HasEqualsAndHashCodeRule())
+
+ .build();
+
- @Test
- public void pojoStructure() {
- test("org.onap.so.db.catalog.beans");
- test("org.onap.so.db.catalog.beans.macro");
- }
+ validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses, enumFilter,
+ new FilterNonConcrete());
+ }
- private void test(String pojoPackage) {
- Validator validator = ValidatorBuilder.create()
- .with(new GetterMustExistRule())
- .with(new NoPrimitivesRule())
- .with(new NoNestedClassRule())
- .with(new NoStaticExceptFinalRule())
- .with(new SerializableMustHaveSerialVersionUIDRule())
- .with(new HasToStringRule())
- .with(new EqualsAndHashCodeTester())
- .with(new NoPublicFieldsExceptStaticFinalRule())
- .with(new CustomSetterMustExistRule().exclude(
- allOf(hasAnnotationPropertyWithValue(Column.class, "updatable", equalTo(false)), hasAnnotation(GeneratedValue.class)),
- hasAnnotation(Temporal.class)))
-
- .with(new SetterTester())
- .with(new GetterTester())
- .with(new ToStringTester())
- .with(new HasEqualsAndHashCodeRule())
-
- .build();
-
-
- validator.validate(pojoPackage, new FilterPackageInfo(), filterTestClasses,enumFilter,new FilterNonConcrete());
- }
- private static class FilterTestClasses implements PojoClassFilter {
- public boolean include(PojoClass pojoClass) {
- return !pojoClass.getSourcePath().contains("/test-classes/");
- }
- }
+ private static class FilterTestClasses implements PojoClassFilter {
+ public boolean include(PojoClass pojoClass) {
+ return !pojoClass.getSourcePath().contains("/test-classes/");
+ }
+ }
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CloudIdentityTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CloudIdentityTest.java
index f8f3435fe1..f4e52235d5 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CloudIdentityTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CloudIdentityTest.java
@@ -23,9 +23,7 @@ package org.onap.so.db.catalog.beans;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-
import java.security.GeneralSecurityException;
-
import org.junit.Test;
import org.onap.so.db.catalog.beans.AuthenticationType;
import org.onap.so.db.catalog.beans.CloudIdentity;
@@ -33,71 +31,71 @@ import org.onap.so.db.catalog.beans.ServerType;
import org.onap.so.utils.CryptoUtils;
public class CloudIdentityTest {
-
- private CloudIdentity cloudIdentity = new CloudIdentity();
- private static final String ID = "testId";
- private static final String IDENTITY_URL = "testIdentityUrl";
- private static final String MSO_ID = "testMsoId";
- private static final String MSO_PASS = "testMsoPassword";
- private static final String ADMIN_TENANT = "testAdminTenant";
- private static final String MEMBER_ROLE = "testMemberRole";
- private static final Boolean TENANT_METADATA = true;
-
+
+ private CloudIdentity cloudIdentity = new CloudIdentity();
+ private static final String ID = "testId";
+ private static final String IDENTITY_URL = "testIdentityUrl";
+ private static final String MSO_ID = "testMsoId";
+ private static final String MSO_PASS = "testMsoPassword";
+ private static final String ADMIN_TENANT = "testAdminTenant";
+ private static final String MEMBER_ROLE = "testMemberRole";
+ private static final Boolean TENANT_METADATA = true;
+
@Test
- public final void testCloudIdentity () {
- CloudIdentity id = new CloudIdentity ();
- id.setAdminTenant ("AdminTenant");
- id.setId ("id");
-// id.setKeystoneUrl ("keystone");
- id.setIdentityUrl ("keystone");
- id.setMemberRole ("member");
- id.setMsoId ("msoId");
- id.setMsoPass (CryptoUtils.encryptCloudConfigPassword("password"));
- id.setTenantMetadata (true);
+ public final void testCloudIdentity() {
+ CloudIdentity id = new CloudIdentity();
+ id.setAdminTenant("AdminTenant");
+ id.setId("id");
+ // id.setKeystoneUrl ("keystone");
+ id.setIdentityUrl("keystone");
+ id.setMemberRole("member");
+ id.setMsoId("msoId");
+ id.setMsoPass(CryptoUtils.encryptCloudConfigPassword("password"));
+ id.setTenantMetadata(true);
id.setIdentityServerType(null);
id.setIdentityAuthenticationType(null);
-
- assertTrue (id.getAdminTenant ().equals ("AdminTenant"));
- assertTrue (id.getId ().equals ("id"));
-// assertTrue (id.getKeystoneUrl ().equals ("keystone"));
- assertTrue (id.getMemberRole ().equals ("member"));
- assertTrue (id.getMsoId ().equals ("msoId"));
- assertTrue (CryptoUtils.decryptCloudConfigPassword(id.getMsoPass()).equals ("password"));
- assertTrue (id.getTenantMetadata ());
-// assertTrue (id.toString ().contains ("keystone"));
+
+ assertTrue(id.getAdminTenant().equals("AdminTenant"));
+ assertTrue(id.getId().equals("id"));
+ // assertTrue (id.getKeystoneUrl ().equals ("keystone"));
+ assertTrue(id.getMemberRole().equals("member"));
+ assertTrue(id.getMsoId().equals("msoId"));
+ assertTrue(CryptoUtils.decryptCloudConfigPassword(id.getMsoPass()).equals("password"));
+ assertTrue(id.getTenantMetadata());
+ // assertTrue (id.toString ().contains ("keystone"));
assertTrue(id.toString().contains("null"));
}
@Test
- public final void testEncryption () throws GeneralSecurityException {
+ public final void testEncryption() throws GeneralSecurityException {
String encrypted = CryptoUtils.encryptCloudConfigPassword("password");
- assertTrue (encrypted != null);
- assertTrue (!encrypted.equals ("password"));
+ assertTrue(encrypted != null);
+ assertTrue(!encrypted.equals("password"));
}
-
+
@Test
public void cloneTest() {
- cloudIdentity = setupCloudIdentity(cloudIdentity, ID, IDENTITY_URL, MSO_ID, MSO_PASS, ADMIN_TENANT,
- MEMBER_ROLE, TENANT_METADATA, ServerType.ORM, AuthenticationType.USERNAME_PASSWORD);
- CloudIdentity cloudIdentity2 = cloudIdentity.clone();
-
- assertEquals(cloudIdentity.getClass(), cloudIdentity2.getClass());
+ cloudIdentity = setupCloudIdentity(cloudIdentity, ID, IDENTITY_URL, MSO_ID, MSO_PASS, ADMIN_TENANT, MEMBER_ROLE,
+ TENANT_METADATA, ServerType.ORM, AuthenticationType.USERNAME_PASSWORD);
+ CloudIdentity cloudIdentity2 = cloudIdentity.clone();
+
+ assertEquals(cloudIdentity.getClass(), cloudIdentity2.getClass());
+ }
+
+ private CloudIdentity setupCloudIdentity(CloudIdentity obj, String id, String identityUrl, String msoId,
+ String msoPass, String adminTenant, String memberRole, Boolean tenantMetadata,
+ ServerType identityServerType, AuthenticationType identityAuthenticationType) {
+ obj.setId(id);
+ obj.setIdentityUrl(identityUrl);
+ obj.setMsoId(msoId);
+ obj.setMsoPass(msoPass);
+ obj.setAdminTenant(adminTenant);
+ obj.setMemberRole(memberRole);
+ obj.setTenantMetadata(tenantMetadata);
+ obj.setIdentityServerType(identityServerType);
+ obj.setIdentityAuthenticationType(identityAuthenticationType);
+
+ return obj;
}
-
- private CloudIdentity setupCloudIdentity(CloudIdentity obj, String id, String identityUrl,
- String msoId, String msoPass, String adminTenant, String memberRole, Boolean tenantMetadata,
- ServerType identityServerType, AuthenticationType identityAuthenticationType) {
- obj.setId(id);
- obj.setIdentityUrl(identityUrl);
- obj.setMsoId(msoId);
- obj.setMsoPass(msoPass);
- obj.setAdminTenant(adminTenant);
- obj.setMemberRole(memberRole);
- obj.setTenantMetadata(tenantMetadata);
- obj.setIdentityServerType(identityServerType);
- obj.setIdentityAuthenticationType(identityAuthenticationType);
-
- return obj;
- }
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CloudifyManagerTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CloudifyManagerTest.java
index 2405a413cf..da8abe061b 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CloudifyManagerTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CloudifyManagerTest.java
@@ -25,23 +25,23 @@ import org.junit.Test;
import org.onap.so.db.catalog.beans.CloudifyManager;
public class CloudifyManagerTest {
-
- private CloudifyManager cloudifyManager = new CloudifyManager();
- private static final String ID = "testId";
- private static final String CLOUDIFY_URL = "testCloudifyUrl";
- private static final String USERNAME = "testUsername";
- private static final String PASSWORD = "testPassword";
- private static final String VERSION = "testVersion";
-
- @Test
- public void cloneTest() {
- cloudifyManager.setId(ID);
- cloudifyManager.setCloudifyUrl(CLOUDIFY_URL);
- cloudifyManager.setUsername(USERNAME);
- cloudifyManager.setPassword(PASSWORD);
- cloudifyManager.setVersion(VERSION);
-
- CloudifyManager clone = cloudifyManager.clone();
- assertEquals(cloudifyManager, clone);
- }
+
+ private CloudifyManager cloudifyManager = new CloudifyManager();
+ private static final String ID = "testId";
+ private static final String CLOUDIFY_URL = "testCloudifyUrl";
+ private static final String USERNAME = "testUsername";
+ private static final String PASSWORD = "testPassword";
+ private static final String VERSION = "testVersion";
+
+ @Test
+ public void cloneTest() {
+ cloudifyManager.setId(ID);
+ cloudifyManager.setCloudifyUrl(CLOUDIFY_URL);
+ cloudifyManager.setUsername(USERNAME);
+ cloudifyManager.setPassword(PASSWORD);
+ cloudifyManager.setVersion(VERSION);
+
+ CloudifyManager clone = cloudifyManager.clone();
+ assertEquals(cloudifyManager, clone);
+ }
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CvnfcConfigurationCustomizationTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CvnfcConfigurationCustomizationTest.java
index e5a17228b7..8828c8d363 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CvnfcConfigurationCustomizationTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CvnfcConfigurationCustomizationTest.java
@@ -21,49 +21,52 @@
package org.onap.so.db.catalog.beans;
import static org.junit.Assert.assertTrue;
-
import org.junit.Test;
public class CvnfcConfigurationCustomizationTest {
-
- private static final String CONFIGURATION_FUNCTION = "testconfigurationFunction";
- private static final String CONFIGURATION_ROLE = "testconfigurationRole";
- private static final String CONFIGURATION_TYPE = "testconfigurationType";
- private static final Integer ID = new Integer(1);
- private static final String MODEL_CUSTOMIZATION_UUID = "testModelCustomizationUUID";
- private static final String MODEL_INSTANCE_NAME = "testModelInstanceName";
- private static final String MODEL_UUID = "testModelUUID";
- private static final String POLICY_NAME = "testPolicyName";
-
+
+ private static final String CONFIGURATION_FUNCTION = "testconfigurationFunction";
+ private static final String CONFIGURATION_ROLE = "testconfigurationRole";
+ private static final String CONFIGURATION_TYPE = "testconfigurationType";
+ private static final Integer ID = new Integer(1);
+ private static final String MODEL_CUSTOMIZATION_UUID = "testModelCustomizationUUID";
+ private static final String MODEL_INSTANCE_NAME = "testModelInstanceName";
+ private static final String MODEL_UUID = "testModelUUID";
+ private static final String POLICY_NAME = "testPolicyName";
+
@Test
- public final void testVnfVfmoduleCvnfcConfigurationCustomization () {
- CvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization = new CvnfcConfigurationCustomization();
- vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationFunction(CONFIGURATION_FUNCTION);
- vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationResource(setupConfigurationResource());
- vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationRole(CONFIGURATION_ROLE);
- vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationType(CONFIGURATION_TYPE);
- CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
- cvnfcCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
- vnfVfmoduleCvnfcConfigurationCustomization.setCvnfcCustomization(cvnfcCustomization);
- vnfVfmoduleCvnfcConfigurationCustomization.setId(ID);
- vnfVfmoduleCvnfcConfigurationCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
- vnfVfmoduleCvnfcConfigurationCustomization.setModelInstanceName(MODEL_INSTANCE_NAME);
- vnfVfmoduleCvnfcConfigurationCustomization.setPolicyName(POLICY_NAME);
+ public final void testVnfVfmoduleCvnfcConfigurationCustomization() {
+ CvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization =
+ new CvnfcConfigurationCustomization();
+ vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationFunction(CONFIGURATION_FUNCTION);
+ vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationResource(setupConfigurationResource());
+ vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationRole(CONFIGURATION_ROLE);
+ vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationType(CONFIGURATION_TYPE);
+ CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
+ cvnfcCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
+ vnfVfmoduleCvnfcConfigurationCustomization.setCvnfcCustomization(cvnfcCustomization);
+ vnfVfmoduleCvnfcConfigurationCustomization.setId(ID);
+ vnfVfmoduleCvnfcConfigurationCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
+ vnfVfmoduleCvnfcConfigurationCustomization.setModelInstanceName(MODEL_INSTANCE_NAME);
+ vnfVfmoduleCvnfcConfigurationCustomization.setPolicyName(POLICY_NAME);
- assertTrue (vnfVfmoduleCvnfcConfigurationCustomization.getId().equals (new Integer(1)));
- assertTrue (vnfVfmoduleCvnfcConfigurationCustomization.getConfigurationFunction().equals (CONFIGURATION_FUNCTION));
- assertTrue (vnfVfmoduleCvnfcConfigurationCustomization.getConfigurationRole().equals (CONFIGURATION_ROLE));
- assertTrue (vnfVfmoduleCvnfcConfigurationCustomization.getConfigurationType().equals (CONFIGURATION_TYPE));
- assertTrue (vnfVfmoduleCvnfcConfigurationCustomization.getModelCustomizationUUID().equals (MODEL_CUSTOMIZATION_UUID));
- assertTrue (vnfVfmoduleCvnfcConfigurationCustomization.getModelInstanceName().equals (MODEL_INSTANCE_NAME));
- assertTrue (vnfVfmoduleCvnfcConfigurationCustomization.getPolicyName().equals (POLICY_NAME));
- assertTrue (vnfVfmoduleCvnfcConfigurationCustomization.getCvnfcCustomization().getModelCustomizationUUID().equals (MODEL_CUSTOMIZATION_UUID));
+ assertTrue(vnfVfmoduleCvnfcConfigurationCustomization.getId().equals(new Integer(1)));
+ assertTrue(
+ vnfVfmoduleCvnfcConfigurationCustomization.getConfigurationFunction().equals(CONFIGURATION_FUNCTION));
+ assertTrue(vnfVfmoduleCvnfcConfigurationCustomization.getConfigurationRole().equals(CONFIGURATION_ROLE));
+ assertTrue(vnfVfmoduleCvnfcConfigurationCustomization.getConfigurationType().equals(CONFIGURATION_TYPE));
+ assertTrue(vnfVfmoduleCvnfcConfigurationCustomization.getModelCustomizationUUID()
+ .equals(MODEL_CUSTOMIZATION_UUID));
+ assertTrue(vnfVfmoduleCvnfcConfigurationCustomization.getModelInstanceName().equals(MODEL_INSTANCE_NAME));
+ assertTrue(vnfVfmoduleCvnfcConfigurationCustomization.getPolicyName().equals(POLICY_NAME));
+ assertTrue(vnfVfmoduleCvnfcConfigurationCustomization.getCvnfcCustomization().getModelCustomizationUUID()
+ .equals(MODEL_CUSTOMIZATION_UUID));
}
-
- private ConfigurationResource setupConfigurationResource(){
- ConfigurationResource configurationResource = new ConfigurationResource();
- configurationResource.setModelUUID(MODEL_UUID);
- return configurationResource;
+
+ private ConfigurationResource setupConfigurationResource() {
+ ConfigurationResource configurationResource = new ConfigurationResource();
+ configurationResource.setModelUUID(MODEL_UUID);
+ return configurationResource;
}
-} \ No newline at end of file
+}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CvnfcCustomizationTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CvnfcCustomizationTest.java
index 4ab05f363a..80e3d53c57 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CvnfcCustomizationTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/CvnfcCustomizationTest.java
@@ -21,69 +21,68 @@
package org.onap.so.db.catalog.beans;
import static org.junit.Assert.assertTrue;
-
import java.util.HashSet;
import java.util.Set;
-
import org.junit.Test;
public class CvnfcCustomizationTest {
-
- private static final Integer ID = new Integer(1);
- private static final String DESCRIPTION = "testDescription";
- private static final String MODEL_CUSTOMIZATION_UUID = "testModelCustomizationUUID";
- private static final String MODEL_INSTANCE_NAME = "testModelInstanceName";
- private static final String MODEL_INVARIANT_UUID = "testModelInvariantUUID";
- private static final String MODEL_NAME = "testModelName";
- private static final String MODEL_UUID = "testModelUUID";
- private static final String MODEL_VERSION = "testModelVersion";
- private static final String TOSCA_NODE_TYPE = "testToscaNodeType";
- private static final String NFC_FUNCTION = "testNfcFunction";
- private static final String NFC_NAMING_CODE = "testNfcNamingCode";
-
+
+ private static final Integer ID = new Integer(1);
+ private static final String DESCRIPTION = "testDescription";
+ private static final String MODEL_CUSTOMIZATION_UUID = "testModelCustomizationUUID";
+ private static final String MODEL_INSTANCE_NAME = "testModelInstanceName";
+ private static final String MODEL_INVARIANT_UUID = "testModelInvariantUUID";
+ private static final String MODEL_NAME = "testModelName";
+ private static final String MODEL_UUID = "testModelUUID";
+ private static final String MODEL_VERSION = "testModelVersion";
+ private static final String TOSCA_NODE_TYPE = "testToscaNodeType";
+ private static final String NFC_FUNCTION = "testNfcFunction";
+ private static final String NFC_NAMING_CODE = "testNfcNamingCode";
+
@Test
- public final void testCvnfcCustomization () {
- CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
- cvnfcCustomization.setDescription(DESCRIPTION);
- cvnfcCustomization.setId(ID);
- cvnfcCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
- cvnfcCustomization.setModelInstanceName(MODEL_INSTANCE_NAME);
- cvnfcCustomization.setModelInvariantUUID(MODEL_INVARIANT_UUID);
- cvnfcCustomization.setModelName(MODEL_NAME);
- cvnfcCustomization.setModelUUID(MODEL_UUID);
- cvnfcCustomization.setModelVersion(MODEL_VERSION);
- cvnfcCustomization.setNfcFunction(NFC_FUNCTION);
- cvnfcCustomization.setNfcNamingCode(NFC_NAMING_CODE);
- cvnfcCustomization.setToscaNodeType(TOSCA_NODE_TYPE);
- cvnfcCustomization.setVfModuleCustomization(setupVfModuleCustomization());
- Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomizationSet = new HashSet();
- cvnfcConfigurationCustomizationSet.add(setupCvnfcConfigurationCustomization());
- cvnfcCustomization.setCvnfcConfigurationCustomization(cvnfcConfigurationCustomizationSet);
+ public final void testCvnfcCustomization() {
+ CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
+ cvnfcCustomization.setDescription(DESCRIPTION);
+ cvnfcCustomization.setId(ID);
+ cvnfcCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
+ cvnfcCustomization.setModelInstanceName(MODEL_INSTANCE_NAME);
+ cvnfcCustomization.setModelInvariantUUID(MODEL_INVARIANT_UUID);
+ cvnfcCustomization.setModelName(MODEL_NAME);
+ cvnfcCustomization.setModelUUID(MODEL_UUID);
+ cvnfcCustomization.setModelVersion(MODEL_VERSION);
+ cvnfcCustomization.setNfcFunction(NFC_FUNCTION);
+ cvnfcCustomization.setNfcNamingCode(NFC_NAMING_CODE);
+ cvnfcCustomization.setToscaNodeType(TOSCA_NODE_TYPE);
+ cvnfcCustomization.setVfModuleCustomization(setupVfModuleCustomization());
+ Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomizationSet = new HashSet();
+ cvnfcConfigurationCustomizationSet.add(setupCvnfcConfigurationCustomization());
+ cvnfcCustomization.setCvnfcConfigurationCustomization(cvnfcConfigurationCustomizationSet);
- assertTrue (cvnfcCustomization.getId().equals (new Integer(1)));
- assertTrue (cvnfcCustomization.getDescription().equals (DESCRIPTION));
- assertTrue (cvnfcCustomization.getModelCustomizationUUID().equals (MODEL_CUSTOMIZATION_UUID));
- assertTrue (cvnfcCustomization.getModelInstanceName().equals (MODEL_INSTANCE_NAME));
- assertTrue (cvnfcCustomization.getModelInvariantUUID().equals (MODEL_INVARIANT_UUID));
- assertTrue (cvnfcCustomization.getModelName().equals (MODEL_NAME));
- assertTrue (cvnfcCustomization.getModelUUID().equals (MODEL_UUID));
- assertTrue (cvnfcCustomization.getModelVersion().equals (MODEL_VERSION));
- assertTrue (cvnfcCustomization.getNfcFunction().equals (NFC_FUNCTION));
- assertTrue (cvnfcCustomization.getNfcNamingCode().equals (NFC_NAMING_CODE));
- assertTrue (cvnfcCustomization.getToscaNodeType().equals (TOSCA_NODE_TYPE));
- assertTrue (cvnfcCustomization.getVfModuleCustomization().getModelCustomizationUUID().equals (MODEL_CUSTOMIZATION_UUID));
+ assertTrue(cvnfcCustomization.getId().equals(new Integer(1)));
+ assertTrue(cvnfcCustomization.getDescription().equals(DESCRIPTION));
+ assertTrue(cvnfcCustomization.getModelCustomizationUUID().equals(MODEL_CUSTOMIZATION_UUID));
+ assertTrue(cvnfcCustomization.getModelInstanceName().equals(MODEL_INSTANCE_NAME));
+ assertTrue(cvnfcCustomization.getModelInvariantUUID().equals(MODEL_INVARIANT_UUID));
+ assertTrue(cvnfcCustomization.getModelName().equals(MODEL_NAME));
+ assertTrue(cvnfcCustomization.getModelUUID().equals(MODEL_UUID));
+ assertTrue(cvnfcCustomization.getModelVersion().equals(MODEL_VERSION));
+ assertTrue(cvnfcCustomization.getNfcFunction().equals(NFC_FUNCTION));
+ assertTrue(cvnfcCustomization.getNfcNamingCode().equals(NFC_NAMING_CODE));
+ assertTrue(cvnfcCustomization.getToscaNodeType().equals(TOSCA_NODE_TYPE));
+ assertTrue(cvnfcCustomization.getVfModuleCustomization().getModelCustomizationUUID()
+ .equals(MODEL_CUSTOMIZATION_UUID));
}
-
- private VfModuleCustomization setupVfModuleCustomization(){
- VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
- vfModuleCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
- return vfModuleCustomization;
+
+ private VfModuleCustomization setupVfModuleCustomization() {
+ VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
+ vfModuleCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
+ return vfModuleCustomization;
}
-
- private CvnfcConfigurationCustomization setupCvnfcConfigurationCustomization(){
- CvnfcConfigurationCustomization cvnfcConfigurationCustomization = new CvnfcConfigurationCustomization();
- cvnfcConfigurationCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
- return cvnfcConfigurationCustomization;
+
+ private CvnfcConfigurationCustomization setupCvnfcConfigurationCustomization() {
+ CvnfcConfigurationCustomization cvnfcConfigurationCustomization = new CvnfcConfigurationCustomization();
+ cvnfcConfigurationCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
+ return cvnfcConfigurationCustomization;
}
-} \ No newline at end of file
+}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/VnfcCustomizationTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/VnfcCustomizationTest.java
index 2a315d83b6..e71c0ae272 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/VnfcCustomizationTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/beans/VnfcCustomizationTest.java
@@ -21,57 +21,56 @@
package org.onap.so.db.catalog.beans;
import static org.junit.Assert.assertTrue;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Test;
public class VnfcCustomizationTest {
-
- private static final String DESCRIPTION = "testDescription";
- private static final String MODEL_CUSTOMIZATION_UUID = "testModelCustomizationUUID";
- private static final String MODEL_INSTANCE_NAME = "testModelInstanceName";
- private static final String MODEL_INVARIANT_UUID = "testModelInvariantUUID";
- private static final String MODEL_NAME = "testModelName";
- private static final String MODEL_UUID = "testModelUUID";
- private static final String MODEL_VERSION = "testModelVersion";
- private static final String TOSCA_NODE_TYPE = "testToscaNodeType";
-
+
+ private static final String DESCRIPTION = "testDescription";
+ private static final String MODEL_CUSTOMIZATION_UUID = "testModelCustomizationUUID";
+ private static final String MODEL_INSTANCE_NAME = "testModelInstanceName";
+ private static final String MODEL_INVARIANT_UUID = "testModelInvariantUUID";
+ private static final String MODEL_NAME = "testModelName";
+ private static final String MODEL_UUID = "testModelUUID";
+ private static final String MODEL_VERSION = "testModelVersion";
+ private static final String TOSCA_NODE_TYPE = "testToscaNodeType";
+
@Test
- public final void testVnfcCustomization () {
- VnfcCustomization vnfcCustomization = new VnfcCustomization();
- vnfcCustomization.setCvnfcCustomization(setupCvnfcCustomizationList());
- vnfcCustomization.setDescription(DESCRIPTION);
- vnfcCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
- vnfcCustomization.setModelInstanceName(MODEL_INSTANCE_NAME);
- vnfcCustomization.setModelInvariantUUID(MODEL_INVARIANT_UUID);
- vnfcCustomization.setModelName(MODEL_NAME);
- vnfcCustomization.setModelUUID(MODEL_UUID);
- vnfcCustomization.setModelVersion(MODEL_VERSION);
- vnfcCustomization.setToscaNodeType(TOSCA_NODE_TYPE);
-
- assertTrue (vnfcCustomization.getDescription().equals (DESCRIPTION));
- assertTrue (vnfcCustomization.getModelCustomizationUUID().equals (MODEL_CUSTOMIZATION_UUID));
- assertTrue (vnfcCustomization.getModelInstanceName().equals (MODEL_INSTANCE_NAME));
- assertTrue (vnfcCustomization.getModelInvariantUUID().equals (MODEL_INVARIANT_UUID));
- assertTrue (vnfcCustomization.getModelName().equals (MODEL_NAME));
- assertTrue (vnfcCustomization.getModelUUID().equals (MODEL_UUID));
- assertTrue (vnfcCustomization.getModelVersion().equals (MODEL_VERSION));
- assertTrue (vnfcCustomization.getToscaNodeType().equals (TOSCA_NODE_TYPE));
- assertTrue (vnfcCustomization.getCvnfcCustomization().get(0).getModelCustomizationUUID().equals (MODEL_CUSTOMIZATION_UUID));
+ public final void testVnfcCustomization() {
+ VnfcCustomization vnfcCustomization = new VnfcCustomization();
+ vnfcCustomization.setCvnfcCustomization(setupCvnfcCustomizationList());
+ vnfcCustomization.setDescription(DESCRIPTION);
+ vnfcCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
+ vnfcCustomization.setModelInstanceName(MODEL_INSTANCE_NAME);
+ vnfcCustomization.setModelInvariantUUID(MODEL_INVARIANT_UUID);
+ vnfcCustomization.setModelName(MODEL_NAME);
+ vnfcCustomization.setModelUUID(MODEL_UUID);
+ vnfcCustomization.setModelVersion(MODEL_VERSION);
+ vnfcCustomization.setToscaNodeType(TOSCA_NODE_TYPE);
+
+ assertTrue(vnfcCustomization.getDescription().equals(DESCRIPTION));
+ assertTrue(vnfcCustomization.getModelCustomizationUUID().equals(MODEL_CUSTOMIZATION_UUID));
+ assertTrue(vnfcCustomization.getModelInstanceName().equals(MODEL_INSTANCE_NAME));
+ assertTrue(vnfcCustomization.getModelInvariantUUID().equals(MODEL_INVARIANT_UUID));
+ assertTrue(vnfcCustomization.getModelName().equals(MODEL_NAME));
+ assertTrue(vnfcCustomization.getModelUUID().equals(MODEL_UUID));
+ assertTrue(vnfcCustomization.getModelVersion().equals(MODEL_VERSION));
+ assertTrue(vnfcCustomization.getToscaNodeType().equals(TOSCA_NODE_TYPE));
+ assertTrue(vnfcCustomization.getCvnfcCustomization().get(0).getModelCustomizationUUID()
+ .equals(MODEL_CUSTOMIZATION_UUID));
+ }
+
+ private List<CvnfcCustomization> setupCvnfcCustomizationList() {
+ CvnfcCustomization testCvnfcCustomization = new CvnfcCustomization();
+ testCvnfcCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
+ testCvnfcCustomization.setDescription(DESCRIPTION);
+ testCvnfcCustomization.setModelVersion(MODEL_VERSION);
+ testCvnfcCustomization.setModelInstanceName(MODEL_INSTANCE_NAME);
+ testCvnfcCustomization.setToscaNodeType(TOSCA_NODE_TYPE);
+ List<CvnfcCustomization> testCvnfcCustomizationList = new ArrayList();
+ testCvnfcCustomizationList.add(testCvnfcCustomization);
+ return testCvnfcCustomizationList;
}
-
- private List<CvnfcCustomization> setupCvnfcCustomizationList(){
- CvnfcCustomization testCvnfcCustomization = new CvnfcCustomization();
- testCvnfcCustomization.setModelCustomizationUUID(MODEL_CUSTOMIZATION_UUID);
- testCvnfcCustomization.setDescription(DESCRIPTION);
- testCvnfcCustomization.setModelVersion(MODEL_VERSION);
- testCvnfcCustomization.setModelInstanceName(MODEL_INSTANCE_NAME);
- testCvnfcCustomization.setToscaNodeType(TOSCA_NODE_TYPE);
- List<CvnfcCustomization> testCvnfcCustomizationList = new ArrayList();
- testCvnfcCustomizationList.add(testCvnfcCustomization);
- return testCvnfcCustomizationList;
- }
-
-} \ No newline at end of file
+
+}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CloudSiteRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CloudSiteRepositoryTest.java
index 8978f38298..a6f1059ba0 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CloudSiteRepositoryTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CloudSiteRepositoryTest.java
@@ -27,28 +27,27 @@ import org.onap.so.db.catalog.beans.CloudSite;
import org.onap.so.db.catalog.exceptions.NoEntityFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
-
import java.util.List;
public class CloudSiteRepositoryTest extends BaseTest {
-
+
@Autowired
private CloudSiteRepository cloudSiteRepository;
-
+
@Test
public void findByClliAndAicVersionTest() throws Exception {
- CloudSite cloudSite = cloudSiteRepository.findByClliAndCloudVersion("MDT13","2.5");
+ CloudSite cloudSite = cloudSiteRepository.findByClliAndCloudVersion("MDT13", "2.5");
Assert.assertNotNull(cloudSite);
- Assert.assertEquals("mtn13",cloudSite.getId());
+ Assert.assertEquals("mtn13", cloudSite.getId());
}
@Test
public void findOneTest() throws Exception {
- CloudSite cloudSite = cloudSiteRepository.findById("mtn13").
- orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
-
+ CloudSite cloudSite = cloudSiteRepository.findById("mtn13")
+ .orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
+
Assert.assertNotNull(cloudSite);
- Assert.assertEquals("mtn13",cloudSite.getId());
+ Assert.assertEquals("mtn13", cloudSite.getId());
}
@Test
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CloudifyManagerRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CloudifyManagerRepositoryTest.java
index 1ed8c84435..3f4343952e 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CloudifyManagerRepositoryTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CloudifyManagerRepositoryTest.java
@@ -35,7 +35,7 @@ public class CloudifyManagerRepositoryTest extends BaseTest {
@Test
public void findOneTest() throws Exception {
CloudifyManager cloudifyManager = cloudifyManagerRepository.findById("mtn13")
- .orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
+ .orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
Assert.assertNotNull(cloudifyManager);
Assert.assertEquals("mtn13", cloudifyManager.getId());
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CollectionNetworkResourceCustomizationRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CollectionNetworkResourceCustomizationRepositoryTest.java
index 90ec07f154..3740fd2058 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CollectionNetworkResourceCustomizationRepositoryTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CollectionNetworkResourceCustomizationRepositoryTest.java
@@ -22,9 +22,7 @@ package org.onap.so.db.catalog.data.repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
-
import java.util.List;
-
import org.junit.Assert;
import org.junit.Test;
import org.onap.so.db.catalog.BaseTest;
@@ -33,17 +31,18 @@ import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization;
public class CollectionNetworkResourceCustomizationRepositoryTest extends BaseTest {
@Autowired
private CollectionNetworkResourceCustomizationRepository cnrcRepo;
-
+
@Test
public void findAllTest() throws Exception {
List<CollectionNetworkResourceCustomization> cnrcList = cnrcRepo.findAll();
Assert.assertFalse(CollectionUtils.isEmpty(cnrcList));
}
-
+
@Test
public void findOneByUuidTest() throws Exception {
- CollectionNetworkResourceCustomization cnrc = cnrcRepo.findOneByModelCustomizationUUID("3bdbb104-ffff-483e-9f8b-c095b3d3068c");
- Assert.assertTrue(cnrc != null);
- Assert.assertTrue("ExtVL 01".equals(cnrc.getModelInstanceName()));
+ CollectionNetworkResourceCustomization cnrc =
+ cnrcRepo.findOneByModelCustomizationUUID("3bdbb104-ffff-483e-9f8b-c095b3d3068c");
+ Assert.assertTrue(cnrc != null);
+ Assert.assertTrue("ExtVL 01".equals(cnrc.getModelInstanceName()));
}
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java
index 7aab47a625..371a9c13e0 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java
@@ -22,12 +22,10 @@ package org.onap.so.db.catalog.data.repository;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
-
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-
import org.junit.Assert;
import org.junit.Test;
import org.onap.so.db.catalog.BaseTest;
@@ -46,162 +44,159 @@ import org.springframework.util.CollectionUtils;
public class CvnfcCustomizationRepositoryTest extends BaseTest {
@Autowired
private CvnfcCustomizationRepository cvnfcCustomizationRepository;
-
+
@Test
public void findAllTest() throws Exception {
List<CvnfcCustomization> cvnfcCustomizationList = cvnfcCustomizationRepository.findAll();
Assert.assertFalse(CollectionUtils.isEmpty(cvnfcCustomizationList));
}
-
+
@Test
@Transactional
public void createAndGetAllTest() throws Exception {
-
- CvnfcCustomization cvnfcCustomization = setUpCvnfcCustomization();
- cvnfcCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
-
- VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
- vfModuleCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
-
- VfModule vFModule = setUpVfModule();
- VnfResource vnfResource = setUpVnfResource();
-
- vFModule.setVnfResources(vnfResource);
- vfModuleCustomization.setVfModule(vFModule);
- cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization);
-
- VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization();
- vnfResourceCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
- vnfResourceCustomization.setModelInstanceName("testModelInstanceName");
-
- List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList<>();
- vnfResourceCustomizations.add(vnfResourceCustomization);
- vnfResource.setVnfResourceCustomizations(vnfResourceCustomizations);
- vnfResourceCustomization.setVnfResources(vnfResource);
-
-
- VnfcCustomization vnfcCustomization = setUpVnfcCustomization();
- vnfcCustomization.setModelCustomizationUUID("d95d704a-9ff2-11e8-98d0-529269fb1459");
-
- cvnfcCustomizationRepository.save(cvnfcCustomization);
-
- List<CvnfcCustomization> cvnfcCustomizationList = cvnfcCustomizationRepository.findAll();
- boolean matchFound = false;
- for (CvnfcCustomization foundCvnfcCustomization : cvnfcCustomizationList) {
- if (foundCvnfcCustomization.getDescription().equalsIgnoreCase(cvnfcCustomization.getDescription())) {
-
- assertThat(cvnfcCustomization, sameBeanAs(foundCvnfcCustomization)
- .ignoring("id")
- .ignoring("created")
- .ignoring("vnfVfmoduleCvnfcConfigurationCustomization")
- .ignoring("vnfResourceCusteModelCustomizationUUID"));
-
- matchFound = true;
- break;
- }
- }
- Assert.assertTrue(matchFound);
+
+ CvnfcCustomization cvnfcCustomization = setUpCvnfcCustomization();
+ cvnfcCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
+
+ VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
+ vfModuleCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
+
+ VfModule vFModule = setUpVfModule();
+ VnfResource vnfResource = setUpVnfResource();
+
+ vFModule.setVnfResources(vnfResource);
+ vfModuleCustomization.setVfModule(vFModule);
+ cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization);
+
+ VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization();
+ vnfResourceCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
+ vnfResourceCustomization.setModelInstanceName("testModelInstanceName");
+
+ List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList<>();
+ vnfResourceCustomizations.add(vnfResourceCustomization);
+ vnfResource.setVnfResourceCustomizations(vnfResourceCustomizations);
+ vnfResourceCustomization.setVnfResources(vnfResource);
+
+
+ VnfcCustomization vnfcCustomization = setUpVnfcCustomization();
+ vnfcCustomization.setModelCustomizationUUID("d95d704a-9ff2-11e8-98d0-529269fb1459");
+
+ cvnfcCustomizationRepository.save(cvnfcCustomization);
+
+ List<CvnfcCustomization> cvnfcCustomizationList = cvnfcCustomizationRepository.findAll();
+ boolean matchFound = false;
+ for (CvnfcCustomization foundCvnfcCustomization : cvnfcCustomizationList) {
+ if (foundCvnfcCustomization.getDescription().equalsIgnoreCase(cvnfcCustomization.getDescription())) {
+
+ assertThat(cvnfcCustomization,
+ sameBeanAs(foundCvnfcCustomization).ignoring("id").ignoring("created")
+ .ignoring("vnfVfmoduleCvnfcConfigurationCustomization")
+ .ignoring("vnfResourceCusteModelCustomizationUUID"));
+
+ matchFound = true;
+ break;
+ }
+ }
+ Assert.assertTrue(matchFound);
}
-
+
@Test
@Transactional
public void createAndGetCvnfcCustomizationListTest() throws Exception {
-
- CvnfcCustomization cvnfcCustomization = setUpCvnfcCustomization();
- cvnfcCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
-
- VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
- vfModuleCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
-
- VfModule vFModule = setUpVfModule();
- VnfResource vnfResource = setUpVnfResource();
-
- vFModule.setVnfResources(vnfResource);
- vfModuleCustomization.setVfModule(vFModule);
- cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization);
-
- VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization();
- vnfResourceCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
- vnfResourceCustomization.setModelInstanceName("testModelInstanceName");
-
- List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList<>();
- vnfResourceCustomizations.add(vnfResourceCustomization);
- vnfResource.setVnfResourceCustomizations(vnfResourceCustomizations);
- vnfResourceCustomization.setVnfResources(vnfResource);
-
-
-
- VnfcCustomization vnfcCustomization = setUpVnfcCustomization();
- vnfcCustomization.setModelCustomizationUUID("d95d704a-9ff2-11e8-98d0-529269fb1459");
-
-
-
-
- cvnfcCustomizationRepository.save(cvnfcCustomization);
-
- List<CvnfcCustomization> cvnfcCustomizationList = cvnfcCustomizationRepository.findByModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
- boolean matchFound = false;
- for (CvnfcCustomization foundCvnfcCustomization : cvnfcCustomizationList) {
- if (foundCvnfcCustomization.getDescription().equalsIgnoreCase(cvnfcCustomization.getDescription())) {
-
- assertThat(cvnfcCustomization, sameBeanAs(foundCvnfcCustomization)
- .ignoring("id")
- .ignoring("created")
- .ignoring("vnfVfmoduleCvnfcConfigurationCustomization")
- .ignoring("vnfResourceCusteModelCustomizationUUID"));
-
- matchFound = true;
- break;
- }
- }
- Assert.assertTrue(matchFound);
+
+ CvnfcCustomization cvnfcCustomization = setUpCvnfcCustomization();
+ cvnfcCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
+
+ VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
+ vfModuleCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
+
+ VfModule vFModule = setUpVfModule();
+ VnfResource vnfResource = setUpVnfResource();
+
+ vFModule.setVnfResources(vnfResource);
+ vfModuleCustomization.setVfModule(vFModule);
+ cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization);
+
+ VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization();
+ vnfResourceCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
+ vnfResourceCustomization.setModelInstanceName("testModelInstanceName");
+
+ List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList<>();
+ vnfResourceCustomizations.add(vnfResourceCustomization);
+ vnfResource.setVnfResourceCustomizations(vnfResourceCustomizations);
+ vnfResourceCustomization.setVnfResources(vnfResource);
+
+
+
+ VnfcCustomization vnfcCustomization = setUpVnfcCustomization();
+ vnfcCustomization.setModelCustomizationUUID("d95d704a-9ff2-11e8-98d0-529269fb1459");
+
+
+
+ cvnfcCustomizationRepository.save(cvnfcCustomization);
+
+ List<CvnfcCustomization> cvnfcCustomizationList =
+ cvnfcCustomizationRepository.findByModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
+ boolean matchFound = false;
+ for (CvnfcCustomization foundCvnfcCustomization : cvnfcCustomizationList) {
+ if (foundCvnfcCustomization.getDescription().equalsIgnoreCase(cvnfcCustomization.getDescription())) {
+
+ assertThat(cvnfcCustomization,
+ sameBeanAs(foundCvnfcCustomization).ignoring("id").ignoring("created")
+ .ignoring("vnfVfmoduleCvnfcConfigurationCustomization")
+ .ignoring("vnfResourceCusteModelCustomizationUUID"));
+
+ matchFound = true;
+ break;
+ }
+ }
+ Assert.assertTrue(matchFound);
}
-
-
+
+
@Test
@Transactional
public void createAndGetCvnfcCustomizationTest() throws Exception {
-
- CvnfcCustomization cvnfcCustomization = setUpCvnfcCustomization();
- cvnfcCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
-
- VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
- vfModuleCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
-
- VfModule vFModule = setUpVfModule();
- VnfResource vnfResource = setUpVnfResource();
-
- vFModule.setVnfResources(vnfResource);
- vfModuleCustomization.setVfModule(vFModule);
- cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization);
-
- VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization();
- vnfResourceCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
- vnfResourceCustomization.setModelInstanceName("testModelInstanceName");
-
- List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList();
- vnfResourceCustomizations.add(vnfResourceCustomization);
- vnfResource.setVnfResourceCustomizations(vnfResourceCustomizations);
- vnfResourceCustomization.setVnfResources(vnfResource);
-
-
-
- VnfcCustomization vnfcCustomization = setUpVnfcCustomization();
- vnfcCustomization.setModelCustomizationUUID("d95d704a-9ff2-11e8-98d0-529269fb1459");
-
- cvnfcCustomizationRepository.save(cvnfcCustomization);
-
- CvnfcCustomization cvnfcCustomizationList = cvnfcCustomizationRepository.findOneByModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
-
- assertThat(cvnfcCustomization, sameBeanAs(cvnfcCustomizationList)
- .ignoring("id")
- .ignoring("created")
- .ignoring("vnfVfmoduleCvnfcConfigurationCustomization")
- .ignoring("vnfResourceCusteModelCustomizationUUID"));
+
+ CvnfcCustomization cvnfcCustomization = setUpCvnfcCustomization();
+ cvnfcCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
+
+ VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
+ vfModuleCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
+
+ VfModule vFModule = setUpVfModule();
+ VnfResource vnfResource = setUpVnfResource();
+
+ vFModule.setVnfResources(vnfResource);
+ vfModuleCustomization.setVfModule(vFModule);
+ cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization);
+
+ VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization();
+ vnfResourceCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
+ vnfResourceCustomization.setModelInstanceName("testModelInstanceName");
+
+ List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList();
+ vnfResourceCustomizations.add(vnfResourceCustomization);
+ vnfResource.setVnfResourceCustomizations(vnfResourceCustomizations);
+ vnfResourceCustomization.setVnfResources(vnfResource);
+
+
+
+ VnfcCustomization vnfcCustomization = setUpVnfcCustomization();
+ vnfcCustomization.setModelCustomizationUUID("d95d704a-9ff2-11e8-98d0-529269fb1459");
+
+ cvnfcCustomizationRepository.save(cvnfcCustomization);
+
+ CvnfcCustomization cvnfcCustomizationList =
+ cvnfcCustomizationRepository.findOneByModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
+
+ assertThat(cvnfcCustomization,
+ sameBeanAs(cvnfcCustomizationList).ignoring("id").ignoring("created")
+ .ignoring("vnfVfmoduleCvnfcConfigurationCustomization")
+ .ignoring("vnfResourceCusteModelCustomizationUUID"));
}
-
-
-
-
+
+
+
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/PnfCustomizationRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/PnfCustomizationRepositoryTest.java
index 0eec84f4c3..d0c621ddd0 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/PnfCustomizationRepositoryTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/PnfCustomizationRepositoryTest.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.db.catalog.data.repository;
@@ -22,7 +17,6 @@ package org.onap.so.db.catalog.data.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
import java.util.List;
import org.junit.Test;
import org.onap.so.db.catalog.BaseTest;
@@ -38,16 +32,16 @@ public class PnfCustomizationRepositoryTest extends BaseTest {
@Test
public void findById_ValidUuid_ExpectedOutput() throws Exception {
- PnfResourceCustomization pnfResourceCustomization = pnfCustomizationRepository
- .findById("68dc9a92-214c-11e7-93ae-92361f002680")
- .orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
+ PnfResourceCustomization pnfResourceCustomization =
+ pnfCustomizationRepository.findById("68dc9a92-214c-11e7-93ae-92361f002680")
+ .orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
checkPnfResourceCustomization(pnfResourceCustomization);
}
@Test
public void findPnfResourceCustomizationByModelUuid_ValidServiceUuidAndCustomizationUuid_ExpectedOutput() {
List<PnfResourceCustomization> pnfResourceCustomizationList = pnfCustomizationRepository
- .findPnfResourceCustomizationByModelUuid("5df8b6de-2083-11e7-93ae-92361f002676");
+ .findPnfResourceCustomizationByModelUuid("5df8b6de-2083-11e7-93ae-92361f002676");
assertEquals("Found the matching resource entity", 1, pnfResourceCustomizationList.size());
checkPnfResourceCustomization(pnfResourceCustomizationList.get(0));
}
@@ -62,7 +56,7 @@ public class PnfCustomizationRepositoryTest extends BaseTest {
assertEquals("PNFResource modelUUID", "ff2ae348-214a-11e7-93ae-92361f002680", pnfResource.getModelUUID());
assertEquals("PNFResource modelInvariantUUID", "2fff5b20-214b-11e7-93ae-92361f002680",
- pnfResource.getModelInvariantUUID());
+ pnfResource.getModelInvariantUUID());
assertEquals("PNFResource modelVersion", "1.0", pnfResource.getModelVersion());
assertEquals("PNFResource orchestration mode", "", pnfResource.getOrchestrationMode());
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/PnfResourceRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/PnfResourceRepositoryTest.java
index 4dde3b25df..f0b7c20261 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/PnfResourceRepositoryTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/PnfResourceRepositoryTest.java
@@ -1,26 +1,20 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.db.catalog.data.repository;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.db.catalog.BaseTest;
import org.onap.so.db.catalog.beans.PnfResource;
@@ -36,15 +30,15 @@ public class PnfResourceRepositoryTest extends BaseTest {
public void findResourceById_validUuid_expectedOutput() throws Exception {
PnfResource pnfResource = pnfResourceRepository.findById("ff2ae348-214a-11e7-93ae-92361f002680")
- .orElseThrow(() -> new NoEntityFoundException("Cannot Find Entity"));
+ .orElseThrow(() -> new NoEntityFoundException("Cannot Find Entity"));
checkPnfResource(pnfResource);
}
private void checkPnfResource(PnfResource pnfResource) {
assertEquals("PNFResource modelUUID", "ff2ae348-214a-11e7-93ae-92361f002680", pnfResource.getModelUUID());
assertEquals("PNFResource modelInvariantUUID", "2fff5b20-214b-11e7-93ae-92361f002680",
- pnfResource.getModelInvariantUUID());
+ pnfResource.getModelInvariantUUID());
assertEquals("PNFResource modelVersion", "1.0", pnfResource.getModelVersion());
assertEquals("PNFResource orchestration mode", "", pnfResource.getOrchestrationMode());
}
-} \ No newline at end of file
+}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java
index 1fc6617c2c..612963d35b 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java
@@ -22,9 +22,7 @@ package org.onap.so.db.catalog.data.repository;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
-
import java.util.List;
-
import org.junit.Assert;
import org.junit.Test;
import org.onap.so.db.catalog.BaseTest;
@@ -42,24 +40,25 @@ public class VnfcCustomizationRepositoryTest extends BaseTest {
public void findAllTest() throws Exception {
List<VnfcCustomization> vnfcCustomizationList = vnfcCustomizationRepository.findAll();
Assert.assertFalse(CollectionUtils.isEmpty(vnfcCustomizationList));
-
- VnfcCustomization vnfcCustomization = vnfcCustomizationRepository.findById("9bcce658-9b37-11e8-98d0-529269fb1459").
- orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
+
+ VnfcCustomization vnfcCustomization =
+ vnfcCustomizationRepository.findById("9bcce658-9b37-11e8-98d0-529269fb1459")
+ .orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
Assert.assertTrue(vnfcCustomization.getDescription().equalsIgnoreCase("testVnfcCustomizationDescription"));
}
-
+
@Test
@Transactional
public void createAndGetTest() throws Exception {
-
- VnfcCustomization vnfcCustomization = setUpVnfcCustomization();
- vnfcCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
- vnfcCustomizationRepository.save(vnfcCustomization);
-
- VnfcCustomization foundVnfcCustomization = vnfcCustomizationRepository.findById("cf9f6efc-9f14-11e8-98d0-529269fb1459").
- orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
-
- assertThat(vnfcCustomization, sameBeanAs(foundVnfcCustomization)
- .ignoring("created"));
+
+ VnfcCustomization vnfcCustomization = setUpVnfcCustomization();
+ vnfcCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459");
+ vnfcCustomizationRepository.save(vnfcCustomization);
+
+ VnfcCustomization foundVnfcCustomization =
+ vnfcCustomizationRepository.findById("cf9f6efc-9f14-11e8-98d0-529269fb1459")
+ .orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation"));
+
+ assertThat(vnfcCustomization, sameBeanAs(foundVnfcCustomization).ignoring("created"));
}
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java
index be5800608d..d541627d0e 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java
@@ -1,20 +1,15 @@
/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix
+ * Foundation. ================================================================================ Licensed under the
+ * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may
+ * obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions and limitations under the
+ * License.
*
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
+ * SPDX-License-Identifier: Apache-2.0 ============LICENSE_END=========================================================
*/
package org.onap.so.db.catalog.data.repository;
@@ -22,7 +17,6 @@ package org.onap.so.db.catalog.data.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
import java.util.List;
import org.junit.Test;
import org.onap.so.db.catalog.BaseTest;
@@ -39,10 +33,9 @@ public class WorkflowRepositoryTest extends BaseTest {
@Test
public void findByArtifactUuid_ValidUuid_ExpectedOutput() throws Exception {
- Workflow workflow = workflowRepository
- .findByArtifactUUID("5b0c4322-643d-4c9f-b184-4516049e99b1");
-
+ Workflow workflow = workflowRepository.findByArtifactUUID("5b0c4322-643d-4c9f-b184-4516049e99b1");
+
assertEquals("artifactName", "testingWorkflow", workflow.getArtifactName());
}
-
+
}
diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/test/RecordNotFoundExceptionTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/test/RecordNotFoundExceptionTest.java
index 506a6b73c9..27990313b1 100644
--- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/test/RecordNotFoundExceptionTest.java
+++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/test/RecordNotFoundExceptionTest.java
@@ -23,10 +23,8 @@ package org.onap.so.db.catalog.test;
import org.junit.Test;
import org.onap.so.db.catalog.beans.VfModule;
import org.onap.so.db.catalog.utils.RecordNotFoundException;
-
import java.util.ArrayList;
import java.util.List;
-
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;
@@ -34,7 +32,7 @@ import static org.junit.Assert.assertEquals;
public class RecordNotFoundExceptionTest {
@Test
- public void paramConstructor(){
+ public void paramConstructor() {
RecordNotFoundException ex = new RecordNotFoundException("Exceoption raised", new Exception());
assertNotNull(ex);
assertNotNull(ex.getMessage());
diff --git a/pom.xml b/pom.xml
index 01d66b4366..88b3b8da00 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,783 +1,894 @@
<?xml version="1.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.onap.oparent</groupId>
- <artifactId>oparent</artifactId>
- <version>1.2.1</version>
- <relativePath/>
- </parent>
- <groupId>org.onap.so</groupId>
- <artifactId>so</artifactId>
- <packaging>pom</packaging>
- <version>1.4.0-SNAPSHOT</version>
- <name>so</name>
- <description>This Maven project is responsible to build and package all child projects - contributions in the MSO project.
+<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.onap.oparent</groupId>
+ <artifactId>oparent</artifactId>
+ <version>1.2.1</version>
+ <relativePath />
+ </parent>
+ <groupId>org.onap.so</groupId>
+ <artifactId>so</artifactId>
+ <packaging>pom</packaging>
+ <version>1.4.0-SNAPSHOT</version>
+ <name>so</name>
+ <description>This Maven project is responsible to build and package all child projects - contributions in the MSO project.
This build can be configured to run Functional tests and to start/stop a jboss server + Mysql DB.
"mvn clean install -P with-integration-tests -Dintegration-tests-user=root -Dintegration-tests-group=root -Dintegration-tests-db-type=MYSQL"
</description>
- <organization>
- <name>ONAP - SO</name>
- <url>http://www.onap.org/</url>
- </organization>
- <modules>
- <module>deployment-configs</module>
- <module>common</module>
- <module>mso-catalog-db</module>
- <module>mso-api-handlers</module>
- <module>adapters</module>
- <module>asdc-controller</module>
- <module>bpmn</module>
- <module>cloudify-client</module>
- <module>cxf-logging</module>
- <module>so-monitoring</module>
- <module>packages</module>
- </modules>
- <properties>
- <project.mso.base.folder>.</project.mso.base.folder>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <sonar.language>java</sonar.language>
- <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
- <sonar.surefire.reportsPath>${project.build.directory}/surefire-reports</sonar.surefire.reportsPath>
- <sonar.jacoco.reportPath>${project.build.directory}/code-coverage/jacoco-ut.exec</sonar.jacoco.reportPath>
- <!--sonar.jacoco.itReportPath>${project.mso.base.folder}/packages/arquillian-unit-tests/target/mso-automated-tests/jacoco-it.exec</sonar.jacoco.itReportPath -->
- <sonar.jacoco.reportMissing.force.zero>true</sonar.jacoco.reportMissing.force.zero>
- <sonar.projectVersion>${project.version}</sonar.projectVersion>
- <sonar.cpd.exclusions>**/*</sonar.cpd.exclusions>
- <jacoco.version>0.7.5.201505241946</jacoco.version>
- <org.apache.maven.user-settings/>
- <!-- TODO: update to version 1.4.0 for Dublin -->
- <openstack.version>1.4.0-SNAPSHOT</openstack.version>
- <maven.build.timestamp.format>yyyyMMdd'T'HHmm</maven.build.timestamp.format>
- <originalClassifier>original</originalClassifier>
- <docker.skip>true</docker.skip>
- <docker.skip.build>true</docker.skip.build>
- <docker.skip.push>true</docker.skip.push>
- <docker.buildArg.project_version>${project.version}</docker.buildArg.project_version>
- <docker.buildArg.artifact_id>${project.artifactId}</docker.buildArg.artifact_id>
- <docker.buildArg.docker_repository>${dockerPullRepo}</docker.buildArg.docker_repository>
- <enforcer.skip>true</enforcer.skip>
- <nexusproxy>https://nexus.onap.org</nexusproxy>
- <releaseNexusPath>content/repositories/releases/</releaseNexusPath>
- <snapshotNexusPath>content/repositories/snapshots/</snapshotNexusPath>
- <publicNexusPath>content/repositories/public/</publicNexusPath>
- <siteNexusPath>content/sites/site/org/onap/so/${project.version}/</siteNexusPath>
- <cxf.version>3.2.6</cxf.version>
- <jax.ws.rs>2.1</jax.ws.rs>
- <springboot.version>2.0.5.RELEASE</springboot.version>
- <camunda.springboot.version>3.2.0</camunda.springboot.version>
- </properties>
- <distributionManagement>
- <repository>
- <id>ecomp-releases</id>
- <url>${nexusproxy}/${releaseNexusPath}</url>
- </repository>
- <snapshotRepository>
- <id>ecomp-snapshots</id>
- <url>${nexusproxy}/${snapshotNexusPath}</url>
- </snapshotRepository>
- <site>
- <id>ecomp-site</id>
- <url>dav:${nexusproxy}${siteNexusPath}</url>
- </site>
- </distributionManagement>
- <reporting>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>2.10.4</version>
- <configuration>
- <failOnError>false</failOnError>
- <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet>
- <docletArtifact>
- <groupId>org.umlgraph</groupId>
- <artifactId>umlgraph</artifactId>
- <version>5.6</version>
- </docletArtifact>
- <additionalparam>-views</additionalparam>
- <useStandardDocletOptions>true</useStandardDocletOptions>
- </configuration>
- </plugin>
- </plugins>
- </reporting>
- <!-- configure build -->
- <!-- *********************************************************************************************************** -->
- <!-- Plugins and repositories -->
- <pluginRepositories>
- <pluginRepository>
- <id>central</id>
- <url>http://repo1.maven.org/maven2</url>
- </pluginRepository>
- <pluginRepository>
- <id>restlet</id>
- <url>http://maven.restlet.com</url>
- </pluginRepository>
- <pluginRepository>
- <id>ecomp-public</id>
- <url>${nexusproxy}/${publicNexusPath}</url>
- <snapshots>
- <enabled>false</enabled>
- </snapshots>
- </pluginRepository>
- <pluginRepository>
- <id>ecomp-release</id>
- <url>${nexusproxy}/${releaseNexusPath}</url>
- <snapshots>
- <enabled>false</enabled>
- </snapshots>
- </pluginRepository>
- <pluginRepository>
- <id>ecomp-snapshots</id>
- <url>${nexusproxy}/${snapshotNexusPath}</url>
- <releases>
- <enabled>false</enabled>
- </releases>
- </pluginRepository>
- </pluginRepositories>
- <repositories>
- <repository>
- <id>ecomp-public</id>
- <url>https://nexus.onap.org/content/repositories/public/</url>
- <snapshots>
- <enabled>false</enabled>
- </snapshots>
- </repository>
- <repository>
- <id>ecomp-releases</id>
- <url>https://nexus.onap.org/content/repositories/releases/</url>
- <snapshots>
- <enabled>false</enabled>
- </snapshots>
- </repository>
- <repository>
- <id>ecomp-snapshots</id>
- <url>https://nexus.onap.org/content/repositories/snapshots/</url>
- <releases>
- <enabled>false</enabled>
- </releases>
- </repository>
- <repository>
- <id>camunda-bpm</id>
- <url>https://app.camunda.com/nexus/content/repositories/camunda-bpm/</url>
- </repository>
- <repository>
- <id>camunda-public</id>
- <url>https://app.camunda.com/nexus/content/groups/public</url>
- </repository>
- <repository>
- <!-- TODO: remove from ONAP environemnt -->
- <id>onap-releases</id>
- <url>https://nexus.onap.org/content/repositories/releases/</url>
- <snapshots>
- <enabled>false</enabled>
- </snapshots>
- </repository>
- <repository>
- <!-- TODO: remove from ONAP environemnt -->
- <id>onap-snapshots</id>
- <url>https://nexus.onap.org/content/repositories/snapshots/</url>
- <releases>
- <enabled>false</enabled>
- </releases>
- </repository>
- </repositories>
- <!-- *********************************************************************************************************** -->
- <!-- Build -->
- <build>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- </resource>
- <resource>
- <directory>target/generated-sources/license</directory>
- <includes>
- <include>third-party-licenses.txt</include>
- </includes>
- </resource>
- <resource>
- <directory>target/generated-resources/licenses</directory>
- <includes>
- <include>*.*</include>
- </includes>
- <targetPath>third-party-licenses</targetPath>
- </resource>
- </resources>
- <plugins>
- <plugin>
- <groupId>org.sonatype.plugins</groupId>
- <artifactId>nexus-staging-maven-plugin</artifactId>
- <version>1.6.7</version>
- <extensions>true</extensions>
- <configuration>
- <nexusUrl>${nexusproxy}</nexusUrl>
- <stagingProfileId>176c31dfe190a</stagingProfileId>
- <serverId>ecomp-staging</serverId>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <version>2.8</version> <!-- This version supports the "deployAtEnd" parameter -->
- <configuration>
- <skip/>
- </configuration>
- </plugin>
+ <organization>
+ <name>ONAP - SO</name>
+ <url>http://www.onap.org/</url>
+ </organization>
+ <modules>
+ <module>deployment-configs</module>
+ <module>common</module>
+ <module>mso-catalog-db</module>
+ <module>mso-api-handlers</module>
+ <module>adapters</module>
+ <module>asdc-controller</module>
+ <module>bpmn</module>
+ <module>cloudify-client</module>
+ <module>cxf-logging</module>
+ <module>so-monitoring</module>
+ <module>packages</module>
+ </modules>
+ <properties>
+ <project.mso.base.folder>.</project.mso.base.folder>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+ <sonar.language>java</sonar.language>
+ <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
+ <sonar.surefire.reportsPath>${project.build.directory}/surefire-reports</sonar.surefire.reportsPath>
+ <sonar.jacoco.reportPath>${project.build.directory}/code-coverage/jacoco-ut.exec</sonar.jacoco.reportPath>
+ <!--sonar.jacoco.itReportPath>${project.mso.base.folder}/packages/arquillian-unit-tests/target/mso-automated-tests/jacoco-it.exec</sonar.jacoco.itReportPath -->
+ <sonar.jacoco.reportMissing.force.zero>true</sonar.jacoco.reportMissing.force.zero>
+ <sonar.projectVersion>${project.version}</sonar.projectVersion>
+ <sonar.cpd.exclusions>**/*</sonar.cpd.exclusions>
+ <jacoco.version>0.7.5.201505241946</jacoco.version>
+ <org.apache.maven.user-settings />
+ <!-- TODO: update to version 1.4.0 for Dublin -->
+ <openstack.version>1.4.0-SNAPSHOT</openstack.version>
+ <maven.build.timestamp.format>yyyyMMdd'T'HHmm</maven.build.timestamp.format>
+ <originalClassifier>original</originalClassifier>
+ <docker.skip>true</docker.skip>
+ <docker.skip.build>true</docker.skip.build>
+ <docker.skip.push>true</docker.skip.push>
+ <docker.buildArg.project_version>${project.version}</docker.buildArg.project_version>
+ <docker.buildArg.artifact_id>${project.artifactId}</docker.buildArg.artifact_id>
+ <docker.buildArg.docker_repository>${dockerPullRepo}</docker.buildArg.docker_repository>
+ <enforcer.skip>true</enforcer.skip>
+ <nexusproxy>https://nexus.onap.org</nexusproxy>
+ <releaseNexusPath>content/repositories/releases/</releaseNexusPath>
+ <snapshotNexusPath>content/repositories/snapshots/</snapshotNexusPath>
+ <publicNexusPath>content/repositories/public/</publicNexusPath>
+ <siteNexusPath>content/sites/site/org/onap/so/${project.version}/</siteNexusPath>
+ <cxf.version>3.2.6</cxf.version>
+ <jax.ws.rs>2.1</jax.ws.rs>
+ <springboot.version>2.0.5.RELEASE</springboot.version>
+ <camunda.springboot.version>3.2.0</camunda.springboot.version>
+ <format.skipValidate>false</format.skipValidate>
+ <format.skipExecute>true</format.skipExecute>
+ </properties>
+ <distributionManagement>
+ <repository>
+ <id>ecomp-releases</id>
+ <url>${nexusproxy}/${releaseNexusPath}</url>
+ </repository>
+ <snapshotRepository>
+ <id>ecomp-snapshots</id>
+ <url>${nexusproxy}/${snapshotNexusPath}</url>
+ </snapshotRepository>
+ <site>
+ <id>ecomp-site</id>
+ <url>dav:${nexusproxy}${siteNexusPath}</url>
+ </site>
+ </distributionManagement>
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>2.10.4</version>
+ <configuration>
+ <failOnError>false</failOnError>
+ <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet>
+ <docletArtifact>
+ <groupId>org.umlgraph</groupId>
+ <artifactId>umlgraph</artifactId>
+ <version>5.6</version>
+ </docletArtifact>
+ <additionalparam>-views</additionalparam>
+ <useStandardDocletOptions>true</useStandardDocletOptions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </reporting>
+ <!-- configure build -->
+ <!-- *********************************************************************************************************** -->
+ <!-- Plugins and repositories -->
+ <pluginRepositories>
+ <pluginRepository>
+ <id>central</id>
+ <url>http://repo1.maven.org/maven2</url>
+ </pluginRepository>
+ <pluginRepository>
+ <id>restlet</id>
+ <url>http://maven.restlet.com</url>
+ </pluginRepository>
+ <pluginRepository>
+ <id>ecomp-public</id>
+ <url>${nexusproxy}/${publicNexusPath}</url>
+ <snapshots>
+ <enabled>false</enabled>
+ </snapshots>
+ </pluginRepository>
+ <pluginRepository>
+ <id>ecomp-release</id>
+ <url>${nexusproxy}/${releaseNexusPath}</url>
+ <snapshots>
+ <enabled>false</enabled>
+ </snapshots>
+ </pluginRepository>
+ <pluginRepository>
+ <id>ecomp-snapshots</id>
+ <url>${nexusproxy}/${snapshotNexusPath}</url>
+ <releases>
+ <enabled>false</enabled>
+ </releases>
+ </pluginRepository>
+ </pluginRepositories>
+ <repositories>
+ <repository>
+ <id>ecomp-public</id>
+ <url>https://nexus.onap.org/content/repositories/public/</url>
+ <snapshots>
+ <enabled>false</enabled>
+ </snapshots>
+ </repository>
+ <repository>
+ <id>ecomp-releases</id>
+ <url>https://nexus.onap.org/content/repositories/releases/</url>
+ <snapshots>
+ <enabled>false</enabled>
+ </snapshots>
+ </repository>
+ <repository>
+ <id>ecomp-snapshots</id>
+ <url>https://nexus.onap.org/content/repositories/snapshots/</url>
+ <releases>
+ <enabled>false</enabled>
+ </releases>
+ </repository>
+ <repository>
+ <id>camunda-bpm</id>
+ <url>https://app.camunda.com/nexus/content/repositories/camunda-bpm/</url>
+ </repository>
+ <repository>
+ <id>camunda-public</id>
+ <url>https://app.camunda.com/nexus/content/groups/public</url>
+ </repository>
+ <repository>
+ <!-- TODO: remove from ONAP environemnt -->
+ <id>onap-releases</id>
+ <url>https://nexus.onap.org/content/repositories/releases/</url>
+ <snapshots>
+ <enabled>false</enabled>
+ </snapshots>
+ </repository>
+ <repository>
+ <!-- TODO: remove from ONAP environemnt -->
+ <id>onap-snapshots</id>
+ <url>https://nexus.onap.org/content/repositories/snapshots/</url>
+ <releases>
+ <enabled>false</enabled>
+ </releases>
+ </repository>
+ </repositories>
+ <!-- *********************************************************************************************************** -->
+ <!-- Build -->
+ <build>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ </resource>
+ <resource>
+ <directory>target/generated-sources/license</directory>
+ <includes>
+ <include>third-party-licenses.txt</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>target/generated-resources/licenses</directory>
+ <includes>
+ <include>*.*</include>
+ </includes>
+ <targetPath>third-party-licenses</targetPath>
+ </resource>
+ </resources>
+ <plugins>
+ <plugin>
+ <groupId>org.sonatype.plugins</groupId>
+ <artifactId>nexus-staging-maven-plugin</artifactId>
+ <version>1.6.7</version>
+ <extensions>true</extensions>
+ <configuration>
+ <nexusUrl>${nexusproxy}</nexusUrl>
+ <stagingProfileId>176c31dfe190a</stagingProfileId>
+ <serverId>ecomp-staging</serverId>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-deploy-plugin</artifactId>
+ <version>2.8</version> <!-- This version supports the "deployAtEnd" parameter -->
+ <configuration>
+ <skip />
+ </configuration>
+ </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>3.6.1</version>
- <configuration>
- <debug>true</debug>
- <compilerArgument>-Xlint</compilerArgument>
- <verbose>true</verbose>
- <showDeprecation>true</showDeprecation>
- <showWarnings>true</showWarnings>
- <source>1.8</source>
- <target>1.8</target>
- <compilerArgs>
- <arg>-parameters</arg>
- </compilerArgs>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-ejb-plugin</artifactId>
- <version>2.2.1</version>
- <configuration>
- <ejbVersion>3.0</ejbVersion>
- <archive>
- <manifest>
- <addClasspath>true</addClasspath>
- </manifest>
- </archive>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <version>2.17</version>
- <configuration>
- <skip>true</skip>
- <includes>**/org/openecomp/**/*.java</includes>
- <configLocation>/google_checks.xml</configLocation>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>findbugs-maven-plugin</artifactId>
- <version>2.5.2</version>
- <configuration>
- <includeFilterFile>project-configs/code-tools/findbugs_include_filter.xml</includeFilterFile>
- <nested>true</nested>
- <findbugsXmlOutput>true</findbugsXmlOutput>
- <findbugsXmlWithMessages>true</findbugsXmlWithMessages>
- <xmlOutput>true</xmlOutput>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>sonar-maven-plugin</artifactId>
- <version>5.1</version>
- </plugin>
- <plugin>
- <artifactId>maven-scm-plugin</artifactId>
- <version>1.8.1</version>
- <configuration>
- <tag>${project.artifactId}-${project.version}</tag>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>2.9</version>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-site-plugin</artifactId>
- <version>3.6</version>
- <dependencies>
- <dependency>
- <groupId>org.apache.maven.wagon</groupId>
- <artifactId>wagon-webdav-jackrabbit</artifactId>
- <version>2.10</version>
- </dependency>
- </dependencies>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>cobertura-maven-plugin</artifactId>
- <version>2.5.2</version>
- <configuration>
- <formats>
- <format>xml</format>
- </formats>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>versions-maven-plugin</artifactId>
- <version>1.3.1</version>
- </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.6.1</version>
+ <configuration>
+ <debug>true</debug>
+ <compilerArgument>-Xlint</compilerArgument>
+ <verbose>true</verbose>
+ <showDeprecation>true</showDeprecation>
+ <showWarnings>true</showWarnings>
+ <source>1.8</source>
+ <target>1.8</target>
+ <compilerArgs>
+ <arg>-parameters</arg>
+ </compilerArgs>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-ejb-plugin</artifactId>
+ <version>2.2.1</version>
+ <configuration>
+ <ejbVersion>3.0</ejbVersion>
+ <archive>
+ <manifest>
+ <addClasspath>true</addClasspath>
+ </manifest>
+ </archive>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>2.17</version>
+ <configuration>
+ <skip>true</skip>
+ <includes>**/org/openecomp/**/*.java</includes>
+ <configLocation>/google_checks.xml</configLocation>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>findbugs-maven-plugin</artifactId>
+ <version>2.5.2</version>
+ <configuration>
+ <includeFilterFile>project-configs/code-tools/findbugs_include_filter.xml</includeFilterFile>
+ <nested>true</nested>
+ <findbugsXmlOutput>true</findbugsXmlOutput>
+ <findbugsXmlWithMessages>true</findbugsXmlWithMessages>
+ <xmlOutput>true</xmlOutput>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>sonar-maven-plugin</artifactId>
+ <version>5.1</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-scm-plugin</artifactId>
+ <version>1.8.1</version>
+ <configuration>
+ <tag>${project.artifactId}-${project.version}</tag>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>2.9</version>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-site-plugin</artifactId>
+ <version>3.6</version>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.maven.wagon</groupId>
+ <artifactId>wagon-webdav-jackrabbit</artifactId>
+ <version>2.10</version>
+ </dependency>
+ </dependencies>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>cobertura-maven-plugin</artifactId>
+ <version>2.5.2</version>
+ <configuration>
+ <formats>
+ <format>xml</format>
+ </formats>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>versions-maven-plugin</artifactId>
+ <version>1.3.1</version>
+ </plugin>
- <plugin>
- <groupId>com.fortify.ps.maven.plugin</groupId>
- <artifactId>sca-maven-plugin</artifactId>
- <version>4.20</version>
- <configuration>
- <buildId>mso-${project.version}</buildId>
- <source>1.8</source>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- <version>${jacoco.version}</version>
- <executions>
- <execution>
- <id>default-prepare-agent</id>
- <goals>
- <goal>prepare-agent</goal>
- </goals>
- </execution>
- <execution>
- <id>default-report</id>
- <goals>
- <goal>report</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>license-maven-plugin</artifactId>
- <version>1.15</version>
- <configuration>
- <inceptionYear>2017</inceptionYear>
- <projectName>ONAP - SO</projectName>
- <licenseName>apache_v2</licenseName>
- <addJavaLicenseAfterPackage>false</addJavaLicenseAfterPackage>
- <emptyLineAfterHeader>true</emptyLineAfterHeader>
- <trimHeaderLine>true</trimHeaderLine>
- <processStartTag>============LICENSE_START=======================================================</processStartTag>
- <sectionDelimiter>================================================================================</sectionDelimiter>
- <processEndTag>============LICENSE_END=========================================================</processEndTag>
- <includes>
- <include>**/*.java</include>
- <include>**/*.groovy</include>
- </includes>
- <excludes>
- <exclude>**/com/att/**</exclude>
- </excludes>
- </configuration>
- <executions>
- <execution>
- <id>verify-headers</id>
- <goals>
- <goal>check-file-header</goal>
- </goals>
- <configuration>
- <failOnNotUptodateHeader>true</failOnNotUptodateHeader>
- <failOnMissingHeader>true</failOnMissingHeader>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>io.fabric8</groupId>
- <artifactId>fabric8-maven-plugin</artifactId>
- <version>3.5.33</version>
- <configuration>
- <skip>${docker.skip}</skip>
- <skipBuild>${docker.skip.build}</skipBuild>
- <skipPush>${docker.skip.push}</skipPush>
- <dockerHost>${docker.newHost}</dockerHost> <!-- 1. Update address to your local docker VM. 2. Add IP to your NO_PROXY
- environment variable -->
- <certPath>${docker.host.cert.path}</certPath><!-- Add -Ddocker.host.cert.pat="path
- to your local certs directory" to maven build command -->
- <pushRegistry>${dockerPushRepo}</pushRegistry> <!-- Update .m2/settings.xml Add server id settings.dockerRepository, username,
- and password -->
- <pullRegistry>${dockerPullRepo}</pullRegistry> <!-- If docker repo is not public. Update .m2/settings.xml Add server id
- settings.dockerRepository, username, and password -->
- <images>
- <image>
- <alias>service</alias>
- <name>${artifactId}:${project.version}</name>
- <build>
- <dockerFileDir>${project.build.directory}</dockerFileDir>
- </build>
- </image>
- </images>
- </configuration>
- <executions>
- <execution>
- <id>start</id>
- <goals>
- <goal>build</goal>
- <goal>push</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <version>2.20</version>
- <configuration>
- <systemPropertyVariables>
- <so.log.level>DEBUG</so.log.level>
- </systemPropertyVariables>
- <rerunFailingTestsCount>2</rerunFailingTestsCount>
- <parallel>classes</parallel>
- <useUnlimitedThreads>false</useUnlimitedThreads>
- <threadCount>1</threadCount>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-failsafe-plugin</artifactId>
- <version>2.20</version>
- <configuration>
- <skip>true</skip>
- <systemPropertyVariables>
- <so.log.level>DEBUG</so.log.level>
- </systemPropertyVariables>
- <rerunFailingTestsCount>2</rerunFailingTestsCount>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-dependency-plugin</artifactId>
- <executions>
- <execution>
- <id>extract-docker-file</id>
- <goals>
- <goal>unpack</goal>
- </goals>
- <configuration>
- <artifactItems>
- <artifactItem>
- <groupId>org.onap.so</groupId>
- <artifactId>deployment-configs</artifactId>
- <version>${project.version}</version>
- <outputDirectory>${project.build.directory}</outputDirectory>
- <includes>*,scripts/**,certs/**, logger/*.xml</includes>
- <excludes>Kubernetes</excludes>
- </artifactItem>
- </artifactItems>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <version>3.0.2</version>
- <executions>
- <execution>
- <id>tests</id>
- <goals>
- <goal>test-jar</goal>
- </goals>
- <configuration>
- <skip>false</skip>
- </configuration>
- </execution>
- <execution>
- <id>original</id>
- <phase>package</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- <configuration>
- <classifier>${originalClassifier}</classifier>
- <includes>
- <include>**</include>
- </includes>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <version>${springboot.version}</version>
- <executions>
- <execution>
- <id>build-info</id>
- <goals>
- <goal>build-info</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
- <!-- *********************************************************************************************************** -->
- <!-- Dependencies -->
- <dependencies>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.module</groupId>
- <artifactId>jackson-module-jaxb-annotations</artifactId>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.jaxrs</groupId>
- <artifactId>jackson-jaxrs-base</artifactId>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.jaxrs</groupId>
- <artifactId>jackson-jaxrs-json-provider</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.ws.rs</groupId>
- <artifactId>javax.ws.rs-api</artifactId>
- <version>${jax.ws.rs}</version>
- </dependency>
- <dependency>
- <groupId>javax.annotation</groupId>
- <artifactId>javax.annotation-api</artifactId>
- <version>1.3.1</version>
- </dependency>
- <dependency>
- <groupId>javax.inject</groupId>
- <artifactId>javax.inject</artifactId>
- <version>1</version>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-library</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>xmlunit</groupId>
- <artifactId>xmlunit</artifactId>
- <version>1.6</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.github.tomakehurst</groupId>
- <artifactId>wiremock-standalone</artifactId>
- <version>2.13.0</version>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>jetty</artifactId>
- </exclusion>
- <exclusion>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </exclusion>
- <exclusion>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- </exclusion>
- <exclusion>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- </exclusion>
- <exclusion>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.skyscreamer</groupId>
- <artifactId>jsonassert</artifactId>
- </exclusion>
- <exclusion>
- <groupId>xmlunit</groupId>
- <artifactId>xmlunit</artifactId>
- </exclusion>
- <exclusion>
- <groupId>com.jayway.jsonpath</groupId>
- <artifactId>json-path</artifactId>
- </exclusion>
- <exclusion>
- <groupId>net.sf.jopt-simple</groupId>
- <artifactId>jopt-simple</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>com.openpojo</groupId>
- <artifactId>openpojo</artifactId>
- <version>0.8.10</version>
- </dependency>
- <dependency>
- <groupId>com.shazam</groupId>
- <artifactId>shazamcrest</artifactId>
- <version>0.11</version>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <version>3.11.1</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.googlecode.junit-toolbox</groupId>
- <artifactId>junit-toolbox</artifactId>
- <version>2.4</version>
- </dependency>
- </dependencies>
- <dependencyManagement>
- <dependencies>
- <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
- <!-- force use of version 4.5 everywhere in transient deps, aligned on
- WildFly 10 version -->
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpcore</artifactId>
- <version>4.4.4</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>1.10</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.5</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>com.sun.xml.fastinfoset</groupId>
- <artifactId>FastInfoset</artifactId>
- <version>1.2.13</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-dependencies</artifactId>
- <version>${springboot.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <version>1.23</version>
- </dependency>
- <dependency>
- <groupId>javax.interceptor</groupId>
- <artifactId>javax.interceptor-api</artifactId>
- <version>1.2.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <version>${springboot.version}</version>
- <exclusions>
- <exclusion>
- <groupId>com.vaadin.external.google</groupId>
- <artifactId>android-json</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>net.javacrumbs.shedlock</groupId>
- <artifactId>shedlock-spring</artifactId>
- <version>0.18.2</version>
- </dependency>
- <dependency>
- <groupId>net.javacrumbs.shedlock</groupId>
- <artifactId>shedlock-provider-jdbc-template</artifactId>
- <version>0.18.2</version>
- </dependency>
- <dependency>
- <groupId>org.flywaydb</groupId>
- <artifactId>flyway-core</artifactId>
- <version>5.1.4</version>
- </dependency>
- <dependency>
- <groupId>org.json</groupId>
- <artifactId>json</artifactId>
- <version>20140107</version>
- </dependency>
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <version>1.19</version>
- </dependency>
- </dependencies>
- </dependencyManagement>
- <profiles>
- <profile>
- <id>docker-image-build</id>
- <properties>
- <docker.skip>false</docker.skip>
- <docker.skip.build>false</docker.skip.build>
- <fabric8.skipResourceValidation>true</fabric8.skipResourceValidation>
- </properties>
- </profile>
- <profile>
- <id>docker-image-build-push</id>
- <properties>
- <docker.skip>false</docker.skip>
- <docker.skip.build>false</docker.skip.build>
- <docker.skip.push>false</docker.skip.push>
- <fabric8.skipResourceValidation>true</fabric8.skipResourceValidation>
- </properties>
- </profile>
- <profile>
- <id>m2e</id>
- <activation>
- <property>
- <name>m2e.version</name>
- </property>
- </activation>
- <properties>
- <originalClassifier/>
- </properties>
- </profile>
- </profiles>
+ <plugin>
+ <groupId>com.fortify.ps.maven.plugin</groupId>
+ <artifactId>sca-maven-plugin</artifactId>
+ <version>4.20</version>
+ <configuration>
+ <buildId>mso-${project.version}</buildId>
+ <source>1.8</source>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.jacoco</groupId>
+ <artifactId>jacoco-maven-plugin</artifactId>
+ <version>${jacoco.version}</version>
+ <executions>
+ <execution>
+ <id>default-prepare-agent</id>
+ <goals>
+ <goal>prepare-agent</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>default-report</id>
+ <goals>
+ <goal>report</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>license-maven-plugin</artifactId>
+ <version>1.15</version>
+ <configuration>
+ <inceptionYear>2017</inceptionYear>
+ <projectName>ONAP - SO</projectName>
+ <licenseName>apache_v2</licenseName>
+ <addJavaLicenseAfterPackage>false</addJavaLicenseAfterPackage>
+ <emptyLineAfterHeader>true</emptyLineAfterHeader>
+ <trimHeaderLine>true</trimHeaderLine>
+ <processStartTag>============LICENSE_START=======================================================</processStartTag>
+ <sectionDelimiter>================================================================================</sectionDelimiter>
+ <processEndTag>============LICENSE_END=========================================================</processEndTag>
+ <includes>
+ <include>**/*.java</include>
+ <include>**/*.groovy</include>
+ </includes>
+ <excludes>
+ <exclude>**/com/att/**</exclude>
+ </excludes>
+ </configuration>
+ <executions>
+ <execution>
+ <id>verify-headers</id>
+ <goals>
+ <goal>check-file-header</goal>
+ </goals>
+ <configuration>
+ <failOnNotUptodateHeader>true</failOnNotUptodateHeader>
+ <failOnMissingHeader>true</failOnMissingHeader>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.gmaven</groupId>
+ <artifactId>groovy-maven-plugin</artifactId>
+ <version>2.0</version>
+ <executions>
+ <!-- set absolute base path from super pom -->
+ <execution>
+ <id>find-basepath</id>
+ <phase>validate</phase>
+ <goals>
+ <goal>execute</goal>
+ </goals>
+ <configuration>
+ <source>
+ <![CDATA[
+ import java.io.File;
+ log.info('## define projects super pom absolute path through basepath_marker')
+ String p = "basepath_marker";
+ File f = null;
+ if( p != null ) {
+ def _max_child_poms = 0
+ while( _max_child_poms++ < 5 ) {
+ f = new File( p );
+ if( f.exists() ) {
+ break;
+ }
+ p = "../" + p;
+ }
+ }
+ if( f != null ) {
+ String basePath = f.getCanonicalPath();
+ basePath = basePath.substring( 0, basePath.lastIndexOf( File.separator ) );
+ project.properties['base-path'] = basePath.replace( '\\' , '/');
+ log.info(' - used base path = ' + project.properties['base-path'] );
+ } else {
+ log.error( 'Could not find basepath_marker marker file!' );
+ System.stop( 0 );
+ }
+ ]]>
+ </source>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>net.revelc.code.formatter</groupId>
+ <artifactId>formatter-maven-plugin</artifactId>
+ <version>2.9.0</version>
+ <executions>
+ <execution>
+ <id>format-java</id>
+ <goals>
+ <goal>format</goal>
+ </goals>
+ <configuration>
+ <skip>${format.skipExecute}</skip>
+ <configFile>${base-path}/project-configs/code-tools/onap-eclipse-format.xml</configFile>
+ </configuration>
+ </execution>
+ <execution>
+ <id>format-xml</id>
+ <goals>
+ <goal>format</goal>
+ </goals>
+ <configuration>
+ <skip>${format.skipExecute}</skip>
+ <sourceDirectory>${project.basedir}</sourceDirectory>
+ <configXmlFile>${base-path}/project-configs/code-tools/pom-format.properties</configXmlFile>
+ <includes>
+ <include>${project.basedir}/pom.xml</include>
+ </includes>
+ </configuration>
+ </execution>
+ <execution>
+ <id>validate-java</id>
+ <goals>
+ <goal>validate</goal>
+ </goals>
+ <configuration>
+ <skip>${format.skipValidate}</skip>
+ <configFile>${base-path}/project-configs/code-tools/onap-eclipse-format.xml</configFile>
+ </configuration>
+ </execution>
+ <execution>
+ <id>validate-poms</id>
+ <goals>
+ <goal>validate</goal>
+ </goals>
+ <configuration>
+ <skip>${format.skipValidate}</skip>
+ <configFile>${base-path}/project-configs/code-tools/pom-format.properties</configFile>
+ <includes>
+ <include>${project.basedir}/pom.xml</include>
+ </includes>
+ </configuration>
+ </execution>
+ </executions>
+ <dependencies>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-annotations</artifactId>
+ <version>2.9.8</version>
+ </dependency>
+ </dependencies>
+ </plugin>
+ </plugins>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>io.fabric8</groupId>
+ <artifactId>fabric8-maven-plugin</artifactId>
+ <version>3.5.33</version>
+ <configuration>
+ <skip>${docker.skip}</skip>
+ <skipBuild>${docker.skip.build}</skipBuild>
+ <skipPush>${docker.skip.push}</skipPush>
+ <dockerHost>${docker.newHost}</dockerHost> <!-- 1. Update address to your local docker VM. 2. Add IP to your NO_PROXY environment variable -->
+ <certPath>${docker.host.cert.path}</certPath><!-- Add -Ddocker.host.cert.pat="path to your local certs directory"
+ to maven build command -->
+ <pushRegistry>${dockerPushRepo}</pushRegistry> <!-- Update .m2/settings.xml Add server id settings.dockerRepository, username, and password -->
+ <pullRegistry>${dockerPullRepo}</pullRegistry> <!-- If docker repo is not public. Update .m2/settings.xml Add server id settings.dockerRepository, username, and password -->
+ <images>
+ <image>
+ <alias>service</alias>
+ <name>${artifactId}:${project.version}</name>
+ <build>
+ <dockerFileDir>${project.build.directory}</dockerFileDir>
+ </build>
+ </image>
+ </images>
+ </configuration>
+ <executions>
+ <execution>
+ <id>start</id>
+ <goals>
+ <goal>build</goal>
+ <goal>push</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <version>2.20</version>
+ <configuration>
+ <systemPropertyVariables>
+ <so.log.level>DEBUG</so.log.level>
+ </systemPropertyVariables>
+ <rerunFailingTestsCount>2</rerunFailingTestsCount>
+ <parallel>classes</parallel>
+ <useUnlimitedThreads>false</useUnlimitedThreads>
+ <threadCount>1</threadCount>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-failsafe-plugin</artifactId>
+ <version>2.20</version>
+ <configuration>
+ <skip>true</skip>
+ <systemPropertyVariables>
+ <so.log.level>DEBUG</so.log.level>
+ </systemPropertyVariables>
+ <rerunFailingTestsCount>2</rerunFailingTestsCount>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>extract-docker-file</id>
+ <goals>
+ <goal>unpack</goal>
+ </goals>
+ <configuration>
+ <artifactItems>
+ <artifactItem>
+ <groupId>org.onap.so</groupId>
+ <artifactId>deployment-configs</artifactId>
+ <version>${project.version}</version>
+ <outputDirectory>${project.build.directory}</outputDirectory>
+ <includes>*,scripts/**,certs/**, logger/*.xml</includes>
+ <excludes>Kubernetes</excludes>
+ </artifactItem>
+ </artifactItems>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <version>3.0.2</version>
+ <executions>
+ <execution>
+ <id>tests</id>
+ <goals>
+ <goal>test-jar</goal>
+ </goals>
+ <configuration>
+ <skip>false</skip>
+ </configuration>
+ </execution>
+ <execution>
+ <id>original</id>
+ <phase>package</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ <configuration>
+ <classifier>${originalClassifier}</classifier>
+ <includes>
+ <include>**</include>
+ </includes>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-maven-plugin</artifactId>
+ <version>${springboot.version}</version>
+ <executions>
+ <execution>
+ <id>build-info</id>
+ <goals>
+ <goal>build-info</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ </build>
+ <!-- *********************************************************************************************************** -->
+ <!-- Dependencies -->
+ <dependencies>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.module</groupId>
+ <artifactId>jackson-module-jaxb-annotations</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-annotations</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.jaxrs</groupId>
+ <artifactId>jackson-jaxrs-base</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.jaxrs</groupId>
+ <artifactId>jackson-jaxrs-json-provider</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>javax.ws.rs</groupId>
+ <artifactId>javax.ws.rs-api</artifactId>
+ <version>${jax.ws.rs}</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.annotation</groupId>
+ <artifactId>javax.annotation-api</artifactId>
+ <version>1.3.1</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.inject</groupId>
+ <artifactId>javax.inject</artifactId>
+ <version>1</version>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>xmlunit</groupId>
+ <artifactId>xmlunit</artifactId>
+ <version>1.6</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.github.tomakehurst</groupId>
+ <artifactId>wiremock-standalone</artifactId>
+ <version>2.13.0</version>
+ <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>org.mortbay.jetty</groupId>
+ <artifactId>jetty</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-annotations</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpclient</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.skyscreamer</groupId>
+ <artifactId>jsonassert</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>xmlunit</groupId>
+ <artifactId>xmlunit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.jayway.jsonpath</groupId>
+ <artifactId>json-path</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>net.sf.jopt-simple</groupId>
+ <artifactId>jopt-simple</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>com.openpojo</groupId>
+ <artifactId>openpojo</artifactId>
+ <version>0.8.10</version>
+ </dependency>
+ <dependency>
+ <groupId>com.shazam</groupId>
+ <artifactId>shazamcrest</artifactId>
+ <version>0.11</version>
+ <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <version>3.11.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.googlecode.junit-toolbox</groupId>
+ <artifactId>junit-toolbox</artifactId>
+ <version>2.4</version>
+ </dependency>
+ </dependencies>
+ <dependencyManagement>
+ <dependencies>
+ <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
+ <!-- force use of version 4.5 everywhere in transient deps, aligned on WildFly 10 version -->
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpcore</artifactId>
+ <version>4.4.4</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-codec</groupId>
+ <artifactId>commons-codec</artifactId>
+ <version>1.10</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <version>2.5</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.xml.fastinfoset</groupId>
+ <artifactId>FastInfoset</artifactId>
+ <version>1.2.13</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-dependencies</artifactId>
+ <version>${springboot.version}</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.yaml</groupId>
+ <artifactId>snakeyaml</artifactId>
+ <version>1.23</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.interceptor</groupId>
+ <artifactId>javax.interceptor-api</artifactId>
+ <version>1.2.2</version>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-test</artifactId>
+ <version>${springboot.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>com.vaadin.external.google</groupId>
+ <artifactId>android-json</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>net.javacrumbs.shedlock</groupId>
+ <artifactId>shedlock-spring</artifactId>
+ <version>0.18.2</version>
+ </dependency>
+ <dependency>
+ <groupId>net.javacrumbs.shedlock</groupId>
+ <artifactId>shedlock-provider-jdbc-template</artifactId>
+ <version>0.18.2</version>
+ </dependency>
+ <dependency>
+ <groupId>org.flywaydb</groupId>
+ <artifactId>flyway-core</artifactId>
+ <version>5.1.4</version>
+ </dependency>
+ <dependency>
+ <groupId>org.json</groupId>
+ <artifactId>json</artifactId>
+ <version>20140107</version>
+ </dependency>
+ <dependency>
+ <groupId>org.yaml</groupId>
+ <artifactId>snakeyaml</artifactId>
+ <version>1.19</version>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+ <profiles>
+ <profile>
+ <id>docker-image-build</id>
+ <properties>
+ <docker.skip>false</docker.skip>
+ <docker.skip.build>false</docker.skip.build>
+ <fabric8.skipResourceValidation>true</fabric8.skipResourceValidation>
+ </properties>
+ </profile>
+ <profile>
+ <id>docker-image-build-push</id>
+ <properties>
+ <docker.skip>false</docker.skip>
+ <docker.skip.build>false</docker.skip.build>
+ <docker.skip.push>false</docker.skip.push>
+ <fabric8.skipResourceValidation>true</fabric8.skipResourceValidation>
+ </properties>
+ </profile>
+ <profile>
+ <id>format</id>
+ <properties>
+ <format.skipValidate>true</format.skipValidate>
+ <format.skipExecute>false</format.skipExecute>
+ </properties>
+ </profile>
+ <profile>
+ <id>m2e</id>
+ <activation>
+ <property>
+ <name>m2e.version</name>
+ </property>
+ </activation>
+ <properties>
+ <originalClassifier />
+ </properties>
+ </profile>
+ </profiles>
</project>
diff --git a/project-configs/code-tools/onap-eclipse-format.xml b/project-configs/code-tools/onap-eclipse-format.xml
new file mode 100644
index 0000000000..cd136171fa
--- /dev/null
+++ b/project-configs/code-tools/onap-eclipse-format.xml
@@ -0,0 +1,313 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<profiles version="12">
+<profile kind="CodeFormatterProfile" name="ONAP Java Rule" version="12">
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_for_statment" value="common_lines"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_method_invocation" value="common_lines"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_switch_statement" value="common_lines"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="2"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_enum_constant_declaration" value="common_lines"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
+<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_if_while_statement" value="common_lines"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="2"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_enum_constant" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/>
+<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="120"/>
+<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_catch_clause" value="common_lines"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_lambda_body" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_type_parameters" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="3"/>
+<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_annotation" value="common_lines"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
+<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.wrap_before_conditional_operator" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines" value="2147483647"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/>
+<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_try_clause" value="common_lines"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/>
+<setting id="org.eclipse.jdt.core.compiler.source" value="1.8"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.wrap_before_assignment_operator" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.8"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_method_delcaration" value="common_lines"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_type_arguments" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.8"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_lambda_declaration" value="common_lines"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
+<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="false"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="0"/>
+<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="120"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
+<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
+</profile>
+</profiles>
diff --git a/project-configs/code-tools/pom-format.properties b/project-configs/code-tools/pom-format.properties
new file mode 100644
index 0000000000..4452c2a4bb
--- /dev/null
+++ b/project-configs/code-tools/pom-format.properties
@@ -0,0 +1,5 @@
+maxLineLength=120
+wrapLongLines=true
+tabInsteadOfSpaces=false
+tabWidth=2
+splitMultiAttrs=false \ No newline at end of file
diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ActivityInstance.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ActivityInstance.java
index f92d9fcbfe..7ef00bd798 100644
--- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ActivityInstance.java
+++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ActivityInstance.java
@@ -20,7 +20,6 @@
package org.onap.so.monitoring.camunda.model;
import static org.onap.so.monitoring.utils.ObjectEqualsUtils.isEqual;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@@ -184,5 +183,5 @@ public class ActivityInstance {
}
return false;
}
-
+
}
diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessDefinition.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessDefinition.java
index c38cbcf5c3..76dc096c45 100644
--- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessDefinition.java
+++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessDefinition.java
@@ -20,7 +20,6 @@
package org.onap.so.monitoring.camunda.model;
import static org.onap.so.monitoring.utils.ObjectEqualsUtils.isEqual;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessInstance.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessInstance.java
index 0a2db7dea7..872fae50b0 100644
--- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessInstance.java
+++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessInstance.java
@@ -20,7 +20,6 @@
package org.onap.so.monitoring.camunda.model;
import static org.onap.so.monitoring.utils.ObjectEqualsUtils.isEqual;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessInstanceVariable.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessInstanceVariable.java
index 4154133cce..6d7da58f90 100644
--- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessInstanceVariable.java
+++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/ProcessInstanceVariable.java
@@ -20,7 +20,6 @@
package org.onap.so.monitoring.camunda.model;
import static org.onap.so.monitoring.utils.ObjectEqualsUtils.isEqual;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/SoActiveInfraRequests.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/SoActiveInfraRequests.java
index 124101a999..6c1d1ad99f 100644
--- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/SoActiveInfraRequests.java
+++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/camunda/model/SoActiveInfraRequests.java
@@ -20,7 +20,6 @@
package org.onap.so.monitoring.camunda.model;
import static org.onap.so.monitoring.utils.ObjectEqualsUtils.isEqual;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/camunda/CamundaRestUrlProvider.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/camunda/CamundaRestUrlProvider.java
index dc887bbac1..ab23f24b2a 100644
--- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/camunda/CamundaRestUrlProvider.java
+++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/camunda/CamundaRestUrlProvider.java
@@ -20,7 +20,6 @@
package org.onap.so.monitoring.configuration.camunda;
import java.net.URI;
-
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;
@@ -52,8 +51,8 @@ public class CamundaRestUrlProvider {
/**
* see {@link <a href=
- * "https://docs.camunda.org/manual/7.5/reference/rest/history/process-instance/get-process-instance/">Get
- * Single Process Instance</a>}.
+ * "https://docs.camunda.org/manual/7.5/reference/rest/history/process-instance/get-process-instance/">Get Single
+ * Process Instance</a>}.
*
* @param processInstanceId the process instance id.
* @return URL
@@ -64,8 +63,7 @@ public class CamundaRestUrlProvider {
}
/**
- * see {@link <a href=
- * "https://docs.camunda.org/manual/7.5/reference/rest/process-definition/get-xml/">Get BPMN 2.0
+ * see {@link <a href= "https://docs.camunda.org/manual/7.5/reference/rest/process-definition/get-xml/">Get BPMN 2.0
* XML</a>}.
*
* @param processDefinitionId the process definition id.
@@ -78,8 +76,8 @@ public class CamundaRestUrlProvider {
/**
* see {@link <a href=
- * "https://docs.camunda.org/manual/7.5/reference/rest/history/activity-instance/get-activity-instance/">Get
- * Single Activity Instance (Historic)</a>}.
+ * "https://docs.camunda.org/manual/7.5/reference/rest/history/activity-instance/get-activity-instance/">Get Single
+ * Activity Instance (Historic)</a>}.
*
* @param processInstanceId the process instance id.
* @return URL
@@ -92,8 +90,8 @@ public class CamundaRestUrlProvider {
/**
* see {@link <a href=
- * "https://docs.camunda.org/manual/7.5/reference/rest/history/variable-instance/get-variable-instance/">Get
- * Single Variable Instance</a>}.
+ * "https://docs.camunda.org/manual/7.5/reference/rest/history/variable-instance/get-variable-instance/">Get Single
+ * Variable Instance</a>}.
*
* @param processInstanceId the process instance id.
* @return URL
diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/database/DatabaseUrlProvider.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/database/DatabaseUrlProvider.java
index 7531cfcf7e..67f588eb54 100644
--- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/database/DatabaseUrlProvider.java
+++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/database/DatabaseUrlProvider.java
@@ -20,7 +20,6 @@
package org.onap.so.monitoring.configuration.database;
import java.net.URI;
-
import org.springframework.web.util.UriComponentsBuilder;
/**
diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/HttpServiceProviderConfiguration.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/HttpServiceProviderConfiguration.java
index 11c4d1b4f4..6d8d82bc44 100644
--- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/HttpServiceProviderConfiguration.java
+++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/HttpServiceProviderConfiguration.java
@@ -20,7 +20,6 @@
package org.onap.so.monitoring.configuration.rest;
import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE;
-
import org.onap.so.configuration.rest.BasicHttpHeadersProvider;
import org.onap.so.configuration.rest.HttpHeadersProvider;
import org.onap.so.rest.service.HttpRestServiceProvider;
diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProvider.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProvider.java
index 209fac8fe1..b701203564 100644
--- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProvider.java
+++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProvider.java
@@ -21,7 +21,6 @@ package org.onap.so.monitoring.db.service;
import java.util.List;
import java.util.Map;
-
import org.onap.so.monitoring.model.SoInfraRequest;
diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProviderImpl.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProviderImpl.java
index 49e3d4f92f..9ef54272ef 100644
--- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProviderImpl.java
+++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProviderImpl.java
@@ -20,12 +20,10 @@
package org.onap.so.monitoring.db.service;
import static org.onap.so.monitoring.configuration.rest.HttpServiceProviderConfiguration.DATABASE_HTTP_REST_SERVICE_PROVIDER;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
-
import org.onap.so.monitoring.camunda.model.SoActiveInfraRequests;
import org.onap.so.monitoring.configuration.database.DatabaseUrlProvider;
import org.onap.so.monitoring.model.SoInfraRequest;
@@ -34,7 +32,6 @@ import org.onap.so.rest.service.HttpRestServiceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
-
import com.google.common.base.Optional;
/**
diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProvider.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProvider.java
index e0e0432452..729e57b885 100644
--- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProvider.java
+++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProvider.java
@@ -20,13 +20,11 @@
package org.onap.so.monitoring.rest.service;
import java.util.List;
-
import org.onap.so.monitoring.model.ActivityInstanceDetail;
import org.onap.so.monitoring.model.ProcessDefinitionDetail;
import org.onap.so.monitoring.model.ProcessInstanceDetail;
import org.onap.so.monitoring.model.ProcessInstanceIdDetail;
import org.onap.so.monitoring.model.ProcessInstanceVariableDetail;
-
import com.google.common.base.Optional;
/**
@@ -35,13 +33,13 @@ import com.google.common.base.Optional;
public interface CamundaProcessDataServiceProvider {
Optional<ProcessInstanceIdDetail> getProcessInstanceIdDetail(final String requestId);
-
+
Optional<ProcessInstanceDetail> getSingleProcessInstanceDetail(final String processInstanceId);
Optional<ProcessDefinitionDetail> getProcessDefinition(final String processDefinitionId);
-
+
List<ActivityInstanceDetail> getActivityInstance(final String processInstanceId);
-
+
List<ProcessInstanceVariableDetail> getProcessInstanceVariable(final String processInstanceId);
}
diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderImpl.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderImpl.java
index b7a439fc28..e0996fd2ad 100644
--- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderImpl.java
+++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderImpl.java
@@ -20,11 +20,9 @@
package org.onap.so.monitoring.rest.service;
import static org.onap.so.monitoring.configuration.rest.HttpServiceProviderConfiguration.CAMUNDA_HTTP_REST_SERVICE_PROVIDER;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-
import org.onap.so.monitoring.camunda.model.ActivityInstance;
import org.onap.so.monitoring.camunda.model.ProcessDefinition;
import org.onap.so.monitoring.camunda.model.ProcessInstance;
@@ -41,7 +39,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
-
import com.google.common.base.Optional;
/**
diff --git a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/CamundaConfigurationTest.java b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/CamundaConfigurationTest.java
index fb56d841e4..b08d247106 100644
--- a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/CamundaConfigurationTest.java
+++ b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/CamundaConfigurationTest.java
@@ -20,7 +20,6 @@
package org.onap.so.monitoring.configuration;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
import org.onap.so.monitoring.configuration.camunda.CamundaConfiguration;
import org.onap.so.monitoring.configuration.camunda.CamundaRestUrlProvider;
diff --git a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/CamundaRestUrlProviderTest.java b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/CamundaRestUrlProviderTest.java
index 3cd8a33d77..e2d6ddb959 100644
--- a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/CamundaRestUrlProviderTest.java
+++ b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/CamundaRestUrlProviderTest.java
@@ -20,9 +20,7 @@
package org.onap.so.monitoring.configuration;
import static org.junit.Assert.assertEquals;
-
import java.util.UUID;
-
import org.junit.Test;
import org.onap.so.monitoring.configuration.camunda.CamundaRestUrlProvider;
diff --git a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/HttpServiceProviderConfigurationTest.java b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/HttpServiceProviderConfigurationTest.java
index 9df24c1921..d85a03485f 100644
--- a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/HttpServiceProviderConfigurationTest.java
+++ b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/HttpServiceProviderConfigurationTest.java
@@ -20,7 +20,6 @@
package org.onap.so.monitoring.configuration;
import static org.junit.Assert.assertNotNull;
-
import org.junit.Test;
import org.onap.so.monitoring.configuration.rest.HttpServiceProviderConfiguration;
import org.onap.so.rest.service.HttpRestServiceProvider;
diff --git a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/PojoClassesTests.java b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/PojoClassesTests.java
index f51d4c64b1..fbd0aea5ec 100644
--- a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/PojoClassesTests.java
+++ b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/PojoClassesTests.java
@@ -20,22 +20,18 @@
package org.onap.so.monitoring.configuration;
import static org.junit.Assert.assertFalse;
-
import java.util.Set;
import java.util.regex.Pattern;
-
import org.junit.Test;
import org.onap.so.openpojo.rules.ToStringTester;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.RegexPatternTypeFilter;
-
import com.openpojo.reflection.filters.FilterPackageInfo;
import com.openpojo.validation.Validator;
import com.openpojo.validation.ValidatorBuilder;
import com.openpojo.validation.test.impl.GetterTester;
import com.openpojo.validation.test.impl.SetterTester;
-
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
diff --git a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/database/DatabaseUrlProviderTest.java b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/database/DatabaseUrlProviderTest.java
index d820e9435d..5484b7a7ca 100644
--- a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/database/DatabaseUrlProviderTest.java
+++ b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/database/DatabaseUrlProviderTest.java
@@ -20,7 +20,6 @@
package org.onap.so.monitoring.configuration.database;
import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
diff --git a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/db/api/DatabaseServiceProviderTest.java b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/db/api/DatabaseServiceProviderTest.java
index 3a7ce18bf7..36a39d9cad 100644
--- a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/db/api/DatabaseServiceProviderTest.java
+++ b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/db/api/DatabaseServiceProviderTest.java
@@ -25,13 +25,11 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import org.junit.Test;
import org.onap.so.monitoring.camunda.model.SoActiveInfraRequests;
import org.onap.so.monitoring.configuration.database.DatabaseUrlProvider;
@@ -39,7 +37,6 @@ import org.onap.so.monitoring.db.service.DatabaseServiceProvider;
import org.onap.so.monitoring.db.service.DatabaseServiceProviderImpl;
import org.onap.so.monitoring.model.SoInfraRequest;
import org.onap.so.rest.service.HttpRestServiceProvider;
-
import com.google.common.base.Optional;
diff --git a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderTest.java b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderTest.java
index d21cf6d02b..61b8b898a9 100644
--- a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderTest.java
+++ b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderTest.java
@@ -24,10 +24,8 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.util.List;
import java.util.UUID;
-
import org.junit.Test;
import org.onap.so.monitoring.camunda.model.ActivityInstance;
import org.onap.so.monitoring.camunda.model.ProcessDefinition;
@@ -39,7 +37,6 @@ import org.onap.so.monitoring.model.ProcessDefinitionDetail;
import org.onap.so.monitoring.model.ProcessInstanceIdDetail;
import org.onap.so.monitoring.model.ProcessInstanceVariableDetail;
import org.onap.so.rest.service.HttpRestServiceProvider;
-
import com.google.common.base.Optional;
diff --git a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/utils/ObjectEqualsUtilsTest.java b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/utils/ObjectEqualsUtilsTest.java
index dd363abe3a..b4dd27129d 100644
--- a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/utils/ObjectEqualsUtilsTest.java
+++ b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/utils/ObjectEqualsUtilsTest.java
@@ -21,10 +21,8 @@ package org.onap.so.monitoring.utils;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
import java.util.Arrays;
import java.util.List;
-
import org.junit.Test;
diff --git a/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/JerseyConfiguration.java b/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/JerseyConfiguration.java
index 0f03f23898..22a1583fc2 100644
--- a/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/JerseyConfiguration.java
+++ b/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/JerseyConfiguration.java
@@ -21,7 +21,6 @@ package org.onap.so.monitoring.rest.api;
import javax.annotation.PostConstruct;
import javax.ws.rs.ApplicationPath;
-
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Configuration;
diff --git a/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java b/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java
index d2fa08fdfd..d48d18dad0 100644
--- a/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java
+++ b/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java
@@ -21,7 +21,6 @@ package org.onap.so.monitoring.rest.api;
import java.util.List;
import java.util.Map;
-
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@@ -31,7 +30,6 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-
import org.onap.so.monitoring.db.service.DatabaseServiceProvider;
import org.onap.so.monitoring.model.ActivityInstanceDetail;
import org.onap.so.monitoring.model.ProcessDefinitionDetail;
@@ -46,7 +44,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
import com.google.common.base.Optional;
/**
diff --git a/so-monitoring/so-monitoring-service/src/test/java/org/onap/so/monitoring/rest/api/SoMonitoringControllerTest.java b/so-monitoring/so-monitoring-service/src/test/java/org/onap/so/monitoring/rest/api/SoMonitoringControllerTest.java
index 2c4d036397..e22f1a359f 100644
--- a/so-monitoring/so-monitoring-service/src/test/java/org/onap/so/monitoring/rest/api/SoMonitoringControllerTest.java
+++ b/so-monitoring/so-monitoring-service/src/test/java/org/onap/so/monitoring/rest/api/SoMonitoringControllerTest.java
@@ -42,7 +42,6 @@ import static org.springframework.test.web.client.match.MockRestRequestMatchers.
import static org.springframework.test.web.client.response.MockRestResponseCreators.withBadRequest;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withUnauthorizedRequest;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -50,10 +49,8 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;